xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/st.c (revision 1cba8b6cee3f680c2277b786670ad0c9ec746efd)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * SCSI	 SCSA-compliant and not-so-DDI-compliant Tape Driver
29  */
30 
31 #if defined(lint) && !defined(DEBUG)
32 #define	DEBUG	1
33 #endif
34 
35 #include <sys/modctl.h>
36 #include <sys/scsi/scsi.h>
37 #include <sys/mtio.h>
38 #include <sys/scsi/targets/stdef.h>
39 #include <sys/file.h>
40 #include <sys/kstat.h>
41 #include <sys/ddidmareq.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/byteorder.h>
45 
46 #define	IOSP	KSTAT_IO_PTR(un->un_stats)
47 /*
48  * stats maintained only for reads/writes as commands
49  * like rewind etc skew the wait/busy times
50  */
51 #define	IS_RW(bp) 	((bp)->b_bcount > 0)
52 #define	ST_DO_KSTATS(bp, kstat_function) \
53 	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
54 		kstat_function(IOSP); \
55 	}
56 
57 #define	ST_DO_ERRSTATS(un, x)  \
58 	if (un->un_errstats) { \
59 		struct st_errstats *stp; \
60 		stp = (struct st_errstats *)un->un_errstats->ks_data; \
61 		stp->x.value.ul++; \
62 	}
63 
64 #define	FILL_SCSI1_LUN(devp, pkt) 					\
65 	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
66 		int _lun;						\
67 		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
68 		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
69 		if (_lun > 0) {						\
70 			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
71 			    _lun;					\
72 		}							\
73 	}
74 
75 /*
76  * get an available contig mem header, cp.
77  * when big_enough is true, we will return NULL, if no big enough
78  * contig mem is found.
79  * when big_enough is false, we will try to find cp containing big
80  * enough contig mem. if not found, we will ruturn the last cp available.
81  *
82  * used by st_get_contig_mem()
83  */
84 #define	ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough) {		\
85 	struct contig_mem *tmp_cp = NULL;				\
86 	for ((cp) = (un)->un_contig_mem;				\
87 	    (cp) != NULL;						\
88 	    tmp_cp = (cp), (cp) = (cp)->cm_next) { 			\
89 		if (((cp)->cm_len >= (len)) || 				\
90 		    (!(big_enough) && ((cp)->cm_next == NULL))) { 	\
91 			if (tmp_cp == NULL) { 				\
92 				(un)->un_contig_mem = (cp)->cm_next; 	\
93 			} else { 					\
94 				tmp_cp->cm_next = (cp)->cm_next; 	\
95 			} 						\
96 			(cp)->cm_next = NULL; 				\
97 			(un)->un_contig_mem_available_num--; 		\
98 			break; 						\
99 		} 							\
100 	} 								\
101 }
102 
103 #define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
104 #define	COPY_POS(dest, source) bcopy(source, dest, sizeof (tapepos_t))
105 #define	ISALNUM(byte) \
106 	(((byte) >= 'a' && (byte) <= 'z') || \
107 	((byte) >= 'A' && (byte) <= 'Z') || \
108 	((byte) >= '0' && (byte) <= '9'))
109 
110 #define	ONE_K	1024
111 
112 #define	MAX_SPACE_CNT(cnt) if (cnt >= 0) { \
113 		if (cnt > MIN(SP_CNT_MASK, INT32_MAX)) \
114 			return (EINVAL); \
115 	} else { \
116 		if (-(cnt) > MIN(SP_CNT_MASK, INT32_MAX)) \
117 			return (EINVAL); \
118 	} \
119 
120 /*
121  * Global External Data Definitions
122  */
123 extern struct scsi_key_strings scsi_cmds[];
124 extern uchar_t	scsi_cdb_size[];
125 
126 /*
127  * Local Static Data
128  */
129 static void *st_state;
130 static char *const st_label = "st";
131 static volatile int st_recov_sz = sizeof (recov_info);
132 static const char mp_misconf[] = {
133 	"St Tape is misconfigured, MPxIO enabled and "
134 	"tape-command-recovery-disable set in st.conf\n"
135 };
136 
137 #ifdef	__x86
138 /*
139  * We need to use below DMA attr to alloc physically contiguous
140  * memory to do I/O in big block size
141  */
142 static ddi_dma_attr_t st_contig_mem_dma_attr = {
143 	DMA_ATTR_V0,    /* version number */
144 	0x0,		/* lowest usable address */
145 	0xFFFFFFFFull,  /* high DMA address range */
146 	0xFFFFFFFFull,  /* DMA counter register */
147 	1,		/* DMA address alignment */
148 	1,		/* DMA burstsizes */
149 	1,		/* min effective DMA size */
150 	0xFFFFFFFFull,  /* max DMA xfer size */
151 	0xFFFFFFFFull,  /* segment boundary */
152 	1,		/* s/g list length */
153 	1,		/* granularity of device */
154 	0		/* DMA transfer flags */
155 };
156 
157 static ddi_device_acc_attr_t st_acc_attr = {
158 	DDI_DEVICE_ATTR_V0,
159 	DDI_NEVERSWAP_ACC,
160 	DDI_STRICTORDER_ACC
161 };
162 
163 /* set limitation for the number of contig_mem */
164 static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
165 #endif
166 
167 /*
168  * Tunable parameters
169  *
170  * DISCLAIMER
171  * ----------
172  * These parameters are intended for use only in system testing; if you use
173  * them in production systems, you do so at your own risk. Altering any
174  * variable not listed below may cause unpredictable system behavior.
175  *
176  * st_check_media_time
177  *
178  *   Three second state check
179  *
180  * st_allow_large_xfer
181  *
182  *   Gated with ST_NO_RECSIZE_LIMIT
183  *
184  *   0 - Transfers larger than 64KB will not be allowed
185  *       regardless of the setting of ST_NO_RECSIZE_LIMIT
186  *   1 - Transfers larger than 64KB will be allowed
187  *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
188  *
189  * st_report_soft_errors_on_close
190  *
191  *  Gated with ST_SOFT_ERROR_REPORTING
192  *
193  *  0 - Errors will not be reported on close regardless
194  *      of the setting of ST_SOFT_ERROR_REPORTING
195  *
196  *  1 - Errors will be reported on close if
197  *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
198  */
199 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
200 static int st_retry_count	= ST_RETRY_COUNT;
201 
202 static int st_io_time		= ST_IO_TIME;
203 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
204 
205 static int st_space_time	= ST_SPACE_TIME;
206 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
207 
208 static int st_error_level	= SCSI_ERR_RETRYABLE;
209 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
210 
211 static int st_max_throttle	= ST_MAX_THROTTLE;
212 
213 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
214 
215 static int st_allow_large_xfer = 1;
216 static int st_report_soft_errors_on_close = 1;
217 
218 /*
219  * End of tunable parameters list
220  */
221 
222 
223 
224 /*
225  * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
226  *
227  * Asynchronous I/O's main offering is that it is a non-blocking way to do
228  * reads and writes.  The driver will queue up all the requests it gets and
229  * have them ready to transport to the HBA.  Unfortunately, we cannot always
230  * just ship the I/O requests to the HBA, as there errors and exceptions
231  * that may happen when we don't want the HBA to continue.  Therein comes
232  * the flush-on-errors capability.  If the HBA supports it, then st will
233  * send in st_max_throttle I/O requests at the same time.
234  *
235  * Persistent errors : This was also reasonably simple.  In the interrupt
236  * routines, if there was an error or exception (FM, LEOT, media error,
237  * transport error), the persistent error bits are set and shuts everything
238  * down, but setting the throttle to zero.  If we hit and exception in the
239  * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
240  * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
241  * the appropriate error, and this will preserve order. Of course, depending
242  * on the exception we have to show a zero read or write before we show
243  * errors back to the application.
244  */
245 
246 extern const int st_ndrivetypes;	/* defined in st_conf.c */
247 extern const struct st_drivetype st_drivetypes[];
248 extern const char st_conf_version[];
249 
250 #ifdef STDEBUG
251 static int st_soft_error_report_debug = 0;
252 volatile int st_debug = 0;
253 static volatile dev_info_t *st_lastdev;
254 static kmutex_t st_debug_mutex;
255 #endif
256 
257 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
258 
259 static const struct vid_drivetype {
260 	char	*vid;
261 	char	type;
262 } st_vid_dt[] = {
263 	{"LTO-CVE ",	MT_LTO},
264 	{"QUANTUM ",    MT_ISDLT},
265 	{"SONY    ",    MT_ISAIT},
266 	{"STK     ",	MT_ISSTK9840}
267 };
268 
269 static const struct driver_minor_data {
270 	char	*name;
271 	int	minor;
272 } st_minor_data[] = {
273 	/*
274 	 * The top 4 entries are for the default densities,
275 	 * don't alter their position.
276 	 */
277 	{"",	0},
278 	{"n",	MT_NOREWIND},
279 	{"b",	MT_BSD},
280 	{"bn",	MT_NOREWIND | MT_BSD},
281 	{"l",	MT_DENSITY1},
282 	{"m",	MT_DENSITY2},
283 	{"h",	MT_DENSITY3},
284 	{"c",	MT_DENSITY4},
285 	{"u",	MT_DENSITY4},
286 	{"ln",	MT_DENSITY1 | MT_NOREWIND},
287 	{"mn",	MT_DENSITY2 | MT_NOREWIND},
288 	{"hn",	MT_DENSITY3 | MT_NOREWIND},
289 	{"cn",	MT_DENSITY4 | MT_NOREWIND},
290 	{"un",	MT_DENSITY4 | MT_NOREWIND},
291 	{"lb",	MT_DENSITY1 | MT_BSD},
292 	{"mb",	MT_DENSITY2 | MT_BSD},
293 	{"hb",	MT_DENSITY3 | MT_BSD},
294 	{"cb",	MT_DENSITY4 | MT_BSD},
295 	{"ub",	MT_DENSITY4 | MT_BSD},
296 	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
297 	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
298 	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
299 	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
300 	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
301 };
302 
303 /* strings used in many debug and warning messages */
304 static const char wr_str[]  = "write";
305 static const char rd_str[]  = "read";
306 static const char wrg_str[] = "writing";
307 static const char rdg_str[] = "reading";
308 static const char *space_strs[] = {
309 	"records",
310 	"filemarks",
311 	"sequential filemarks",
312 	"eod",
313 	"setmarks",
314 	"sequential setmarks",
315 	"Reserved",
316 	"Reserved"
317 };
318 static const char *load_strs[] = {
319 	"unload",		/* LD_UNLOAD		0 */
320 	"load",			/* LD_LOAD		1 */
321 	"retension",		/* LD_RETEN		2 */
322 	"load reten",		/* LD_LOAD | LD_RETEN	3 */
323 	"eod",			/* LD_EOT		4 */
324 	"load EOD",		/* LD_LOAD | LD_EOT	5 */
325 	"reten EOD",		/* LD_RETEN | LD_EOT	6 */
326 	"load reten EOD"	/* LD_LOAD|LD_RETEN|LD_EOT 7 */
327 	"hold",			/* LD_HOLD		8 */
328 	"load and hold"		/* LD_LOAD | LD_HOLD	9 */
329 };
330 
331 static const char *errstatenames[] = {
332 	"COMMAND_DONE",
333 	"COMMAND_DONE_ERROR",
334 	"COMMAND_DONE_ERROR_RECOVERED",
335 	"QUE_COMMAND",
336 	"QUE_BUSY_COMMAND",
337 	"QUE_SENSE",
338 	"JUST_RETURN",
339 	"COMMAND_DONE_EACCES",
340 	"QUE_LAST_COMMAND",
341 	"COMMAND_TIMEOUT",
342 	"PATH_FAILED",
343 	"DEVICE_RESET",
344 	"DEVICE_TAMPER",
345 	"ATTEMPT_RETRY"
346 };
347 
348 const char *bogusID = "Unknown Media ID";
349 
350 /* default density offsets in the table above */
351 #define	DEF_BLANK	0
352 #define	DEF_NOREWIND	1
353 #define	DEF_BSD		2
354 #define	DEF_BSD_NR	3
355 
356 /* Sense Key, ASC/ASCQ for which tape ejection is needed */
357 
358 static struct tape_failure_code {
359 	uchar_t key;
360 	uchar_t add_code;
361 	uchar_t qual_code;
362 } st_tape_failure_code[] = {
363 	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
364 	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
365 	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
366 	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
367 	{ KEY_NOT_READY, 0x53, 0x00},
368 	{ 0xff}
369 };
370 
371 /*  clean bit position and mask */
372 
373 static struct cln_bit_position {
374 	ushort_t cln_bit_byte;
375 	uchar_t cln_bit_mask;
376 } st_cln_bit_position[] = {
377 	{ 21, 0x08},
378 	{ 70, 0xc0},
379 	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
380 };
381 
382 /*
383  * architecture dependent allocation restrictions. For x86, we'll set
384  * dma_attr_addr_hi to st_max_phys_addr and dma_attr_sgllen to
385  * st_sgl_size during _init().
386  */
387 #if defined(__sparc)
388 static ddi_dma_attr_t st_alloc_attr = {
389 	DMA_ATTR_V0,	/* version number */
390 	0x0,		/* lowest usable address */
391 	0xFFFFFFFFull,	/* high DMA address range */
392 	0xFFFFFFFFull,	/* DMA counter register */
393 	1,		/* DMA address alignment */
394 	1,		/* DMA burstsizes */
395 	1,		/* min effective DMA size */
396 	0xFFFFFFFFull,	/* max DMA xfer size */
397 	0xFFFFFFFFull,	/* segment boundary */
398 	1,		/* s/g list length */
399 	512,		/* granularity of device */
400 	0		/* DMA transfer flags */
401 };
402 #elif defined(__x86)
403 static ddi_dma_attr_t st_alloc_attr = {
404 	DMA_ATTR_V0,	/* version number */
405 	0x0,		/* lowest usable address */
406 	0x0,		/* high DMA address range [set in _init()] */
407 	0xFFFFull,	/* DMA counter register */
408 	512,		/* DMA address alignment */
409 	1,		/* DMA burstsizes */
410 	1,		/* min effective DMA size */
411 	0xFFFFFFFFull,	/* max DMA xfer size */
412 	0xFFFFFFFFull,  /* segment boundary */
413 	0,		/* s/g list length */
414 	512,		/* granularity of device [set in _init()] */
415 	0		/* DMA transfer flags */
416 };
417 uint64_t st_max_phys_addr = 0xFFFFFFFFull;
418 int st_sgl_size = 0xF;
419 
420 #endif
421 
422 /*
423  * Configuration Data:
424  *
425  * Device driver ops vector
426  */
427 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
428 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
429 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
430 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
431 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
432 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
433 static int st_strategy(struct buf *bp);
434 static int st_queued_strategy(buf_t *bp);
435 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
436 	cred_t *cred_p, int *rval_p);
437 extern int nulldev(), nodev();
438 
439 static struct cb_ops st_cb_ops = {
440 	st_open,		/* open */
441 	st_close,		/* close */
442 	st_queued_strategy,	/* strategy Not Block device but async checks */
443 	nodev,			/* print */
444 	nodev,			/* dump */
445 	st_read,		/* read */
446 	st_write,		/* write */
447 	st_ioctl,		/* ioctl */
448 	nodev,			/* devmap */
449 	nodev,			/* mmap */
450 	nodev,			/* segmap */
451 	nochpoll,		/* poll */
452 	ddi_prop_op,		/* cb_prop_op */
453 	0,			/* streamtab  */
454 	D_64BIT | D_MP | D_NEW | D_HOTPLUG |
455 	D_OPEN_RETURNS_EINTR,	/* cb_flag */
456 	CB_REV,			/* cb_rev */
457 	st_aread, 		/* async I/O read entry point */
458 	st_awrite		/* async I/O write entry point */
459 
460 };
461 
462 static int st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
463 		void **result);
464 static int st_probe(dev_info_t *dev);
465 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
466 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
467 
468 static struct dev_ops st_ops = {
469 	DEVO_REV,		/* devo_rev, */
470 	0,			/* refcnt  */
471 	st_info,		/* info */
472 	nulldev,		/* identify */
473 	st_probe,		/* probe */
474 	st_attach,		/* attach */
475 	st_detach,		/* detach */
476 	nodev,			/* reset */
477 	&st_cb_ops,		/* driver operations */
478 	(struct bus_ops *)0,	/* bus operations */
479 	nulldev,		/* power */
480 	ddi_quiesce_not_needed,	/* devo_quiesce */
481 };
482 
483 /*
484  * Local Function Declarations
485  */
486 static char *st_print_scsi_cmd(char cmd);
487 static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
488     char *title, char *cdb);
489 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
490     char *title, char *data, int len);
491 static int st_doattach(struct scsi_device *devp, int (*canwait)());
492 static void st_known_tape_type(struct scsi_tape *un);
493 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
494     struct st_drivetype *);
495 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
496     struct st_drivetype *);
497 static int st_get_conf_from_tape_drive(struct scsi_tape *, char *,
498     struct st_drivetype *);
499 static int st_get_densities_from_tape_drive(struct scsi_tape *,
500     struct st_drivetype *);
501 static int st_get_timeout_values_from_tape_drive(struct scsi_tape *,
502     struct st_drivetype *);
503 static int st_get_timeouts_value(struct scsi_tape *, uchar_t, ushort_t *,
504     ushort_t);
505 static int st_get_default_conf(struct scsi_tape *, char *,
506     struct st_drivetype *);
507 static int st_rw(dev_t dev, struct uio *uio, int flag);
508 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
509 static int st_find_eod(struct scsi_tape *un);
510 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
511 static int st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *, int flag);
512 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
513 static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
514 static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
515 static void st_start(struct scsi_tape *un);
516 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
517     clock_t timeout_interval, int queued);
518 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
519     clock_t timeout_interval);
520 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
521 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
522 static void st_init(struct scsi_tape *un);
523 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
524     int (*func)(caddr_t));
525 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
526     struct buf *bp, int (*func)(caddr_t));
527 static void st_intr(struct scsi_pkt *pkt);
528 static void st_set_state(struct scsi_tape *un, buf_t *bp);
529 static void st_test_append(struct buf *bp);
530 static int st_runout(caddr_t);
531 static int st_cmd(struct scsi_tape *un, int com, int64_t count, int wait);
532 static int st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com,
533     int64_t count);
534 static int st_set_compression(struct scsi_tape *un);
535 static int st_write_fm(dev_t dev, int wfm);
536 static int st_determine_generic(struct scsi_tape *un);
537 static int st_determine_density(struct scsi_tape *un, int rw);
538 static int st_get_density(struct scsi_tape *un);
539 static int st_set_density(struct scsi_tape *un);
540 static int st_loadtape(struct scsi_tape *un);
541 static int st_modesense(struct scsi_tape *un);
542 static int st_modeselect(struct scsi_tape *un);
543 static errstate st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
544 static int st_wrongtapetype(struct scsi_tape *un);
545 static errstate st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
546 static errstate st_handle_sense(struct scsi_tape *un, struct buf *bp,
547     tapepos_t *);
548 static errstate st_handle_autosense(struct scsi_tape *un, struct buf *bp,
549     tapepos_t *);
550 static int st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag);
551 static void st_update_error_stack(struct scsi_tape *un, struct scsi_pkt *pkt,
552     struct scsi_arq_status *cmd);
553 static void st_empty_error_stack(struct scsi_tape *un);
554 static errstate st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
555     struct scsi_arq_status *, tapepos_t *);
556 static int st_report_soft_errors(dev_t dev, int flag);
557 static void st_delayed_cv_broadcast(void *arg);
558 static int st_check_media(dev_t dev, enum mtio_state state);
559 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
560 static void st_intr_restart(void *arg);
561 static void st_start_restart(void *arg);
562 static int st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
563     struct seq_mode *page_data, int page_size);
564 static int st_change_block_size(struct scsi_tape *un, uint32_t nblksz);
565 static int st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
566     struct seq_mode *page_data, int page_size);
567 static int st_read_block_limits(struct scsi_tape *un,
568     struct read_blklim *read_blk);
569 static int st_report_density_support(struct scsi_tape *un,
570     uchar_t *density_data, size_t buflen);
571 static int st_report_supported_operation(struct scsi_tape *un,
572     uchar_t *oper_data, uchar_t option_code, ushort_t service_action);
573 static int st_tape_init(struct scsi_tape *un);
574 static void st_flush(struct scsi_tape *un);
575 static void st_set_pe_errno(struct scsi_tape *un);
576 static void st_hba_unflush(struct scsi_tape *un);
577 static void st_turn_pe_on(struct scsi_tape *un);
578 static void st_turn_pe_off(struct scsi_tape *un);
579 static void st_set_pe_flag(struct scsi_tape *un);
580 static void st_clear_pe(struct scsi_tape *un);
581 static void st_wait_for_io(struct scsi_tape *un);
582 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
583 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
584 static int st_reserve_release(struct scsi_tape *un, int command, ubufunc_t ubf);
585 static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb);
586 static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
587     int count);
588 static int st_take_ownership(struct scsi_tape *un, ubufunc_t ubf);
589 static int st_check_asc_ascq(struct scsi_tape *un);
590 static int st_check_clean_bit(struct scsi_tape *un);
591 static int st_check_alert_flags(struct scsi_tape *un);
592 static int st_check_sequential_clean_bit(struct scsi_tape *un);
593 static int st_check_sense_clean_bit(struct scsi_tape *un);
594 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
595 static void st_calculate_timeouts(struct scsi_tape *un);
596 static writablity st_is_drive_worm(struct scsi_tape *un);
597 static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
598     void *buf, size_t size, ubufunc_t bufunc);
599 static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
600     caddr_t dest, uchar_t page);
601 static int st_update_block_pos(struct scsi_tape *un, bufunc_t bf,
602     int post_space);
603 static int st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
604     read_p_types type, size_t data_sz, const caddr_t responce, int post_space);
605 static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
606 static int st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf,
607     tapepos_t *pos, uint64_t lblk, uchar_t partition);
608 static int st_mtfsf_ioctl(struct scsi_tape *un, int64_t files);
609 static int st_mtfsr_ioctl(struct scsi_tape *un, int64_t count);
610 static int st_mtbsf_ioctl(struct scsi_tape *un, int64_t files);
611 static int st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count);
612 static int st_mtbsr_ioctl(struct scsi_tape *un, int64_t num);
613 static int st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt);
614 static int st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt);
615 static int st_backward_space_files(struct scsi_tape *un, int64_t count,
616     int infront);
617 static int st_forward_space_files(struct scsi_tape *un, int64_t files);
618 static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
619     int32_t fileno);
620 static int st_space_to_begining_of_file(struct scsi_tape *un);
621 static int st_space_records(struct scsi_tape *un, int64_t records);
622 static int st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc);
623 static errstate st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
624     errstate onentry);
625 static void st_recover(void *arg);
626 static void st_recov_cb(struct scsi_pkt *pkt);
627 static int st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait);
628 static int st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
629     int flag);
630 static void st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
631     struct scsi_pkt *cmd);
632 static int st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf);
633 static int st_test_path_to_device(struct scsi_tape *un);
634 static int st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
635     read_pos_data_t *raw);
636 static int st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
637     read_pos_data_t *raw);
638 static int st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
639     cmd_attribute const * cmd_att, tapepos_t *read);
640 static errstate st_recover_reissue_pkt(struct scsi_tape *us,
641     struct scsi_pkt *pkt);
642 static int st_transport(struct scsi_tape *un, struct scsi_pkt *pkt);
643 static buf_t *st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp);
644 static void st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp);
645 static int st_reset(struct scsi_tape *un, int reset_type);
646 static void st_reset_notification(caddr_t arg);
647 static const cmd_attribute *st_lookup_cmd_attribute(unsigned char cmd);
648 
649 static int st_set_target_TLR_mode(struct scsi_tape *un, ubufunc_t ubf);
650 static int st_make_sure_mode_data_is_correct(struct scsi_tape *un,
651     ubufunc_t ubf);
652 
653 #ifdef	__x86
654 /*
655  * routines for I/O in big block size
656  */
657 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
658 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
659     int alloc_flags);
660 static int st_bigblk_xfer_done(struct buf *bp);
661 static struct buf *st_get_bigblk_bp(struct buf *bp);
662 #endif
663 static void st_print_position(dev_info_t *dev, char *label, uint_t level,
664     const char *comment, tapepos_t *pos);
665 
666 /*
667  * error statistics create/update functions
668  */
669 static int st_create_errstats(struct scsi_tape *, int);
670 static int st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf,
671     tapepos_t *pos);
672 
673 #ifdef STDEBUG
674 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
675 #endif /* STDEBUG */
676 static char *st_dev_name(dev_t dev);
677 
678 #if !defined(lint)
679 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
680     scsi_pkt buf uio scsi_cdb uscsi_cmd))
681 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
682 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", recov_info))
683 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
684 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
685 #endif
686 
687 /*
688  * autoconfiguration routines.
689  */
690 char _depends_on[] = "misc/scsi";
691 
692 static struct modldrv modldrv = {
693 	&mod_driverops,		/* Type of module. This one is a driver */
694 	"SCSI tape Driver", 	/* Name of the module. */
695 	&st_ops			/* driver ops */
696 };
697 
698 static struct modlinkage modlinkage = {
699 	MODREV_1, &modldrv, NULL
700 };
701 
702 /*
703  * Notes on Post Reset Behavior in the tape driver:
704  *
705  * When the tape drive is opened, the driver  attempts  to make sure that
706  * the tape head is positioned exactly where it was left when it was last
707  * closed  provided  the  medium  is not  changed.  If the tape  drive is
708  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
709  * of position due to reset) will happen when the first tape operation or
710  * I/O occurs.  The repositioning (if required) may not be possible under
711  * certain situations such as when the device firmware not able to report
712  * the medium  change in the REQUEST  SENSE data  because of a reset or a
713  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
714  * extraordinary  situations, where the driver fails to position the head
715  * at its  original  position,  it will fail the open the first  time, to
716  * save the applications from overwriting the data.  All further attempts
717  * to open the tape device will result in the driver  attempting  to load
718  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
719  * indicate  that further  attempts to open the tape device may result in
720  * the tape being  loaded at BOT will be printed on the  console.  If the
721  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
722  * original tape head  position,  will result in the failure of the first
723  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
724  * internal tape position  which will  necessitate  the  applications  to
725  * validate the position by using either a tape  positioning  ioctl (such
726  * as MTREW) or closing and reopening the tape device.
727  *
728  */
729 
730 int
731 _init(void)
732 {
733 	int e;
734 
735 	if (((e = ddi_soft_state_init(&st_state,
736 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
737 		return (e);
738 	}
739 
740 	if ((e = mod_install(&modlinkage)) != 0) {
741 		ddi_soft_state_fini(&st_state);
742 	} else {
743 #ifdef STDEBUG
744 		mutex_init(&st_debug_mutex, NULL, MUTEX_DRIVER, NULL);
745 #endif
746 
747 #if defined(__x86)
748 		/* set the max physical address for iob allocs on x86 */
749 		st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
750 
751 		/*
752 		 * set the sgllen for iob allocs on x86. If this is set less
753 		 * than the number of pages the buffer will take
754 		 * (taking into account alignment), it would force the
755 		 * allocator to try and allocate contiguous pages.
756 		 */
757 		st_alloc_attr.dma_attr_sgllen = st_sgl_size;
758 #endif
759 	}
760 
761 	return (e);
762 }
763 
764 int
765 _fini(void)
766 {
767 	int e;
768 
769 	if ((e = mod_remove(&modlinkage)) != 0) {
770 		return (e);
771 	}
772 
773 #ifdef STDEBUG
774 	mutex_destroy(&st_debug_mutex);
775 #endif
776 
777 	ddi_soft_state_fini(&st_state);
778 
779 	return (e);
780 }
781 
782 int
783 _info(struct modinfo *modinfop)
784 {
785 	return (mod_info(&modlinkage, modinfop));
786 }
787 
788 
789 static int
790 st_probe(dev_info_t *devi)
791 {
792 	int instance;
793 	struct scsi_device *devp;
794 	int rval;
795 
796 #if !defined(__sparc)
797 	char    *tape_prop;
798 	int	tape_prop_len;
799 #endif
800 
801 	ST_ENTR(devi, st_probe);
802 
803 	/* If self identifying device */
804 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
805 		return (DDI_PROBE_DONTCARE);
806 	}
807 
808 #if !defined(__sparc)
809 	/*
810 	 * Since some x86 HBAs have devnodes that look like SCSI as
811 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
812 	 * we check for the presence of the "tape" property.
813 	 */
814 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
815 	    DDI_PROP_CANSLEEP, "tape",
816 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
817 		return (DDI_PROBE_FAILURE);
818 	}
819 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
820 		kmem_free(tape_prop, tape_prop_len);
821 		return (DDI_PROBE_FAILURE);
822 	}
823 	kmem_free(tape_prop, tape_prop_len);
824 #endif
825 
826 	devp = ddi_get_driver_private(devi);
827 	instance = ddi_get_instance(devi);
828 
829 	if (ddi_get_soft_state(st_state, instance) != NULL) {
830 		return (DDI_PROBE_PARTIAL);
831 	}
832 
833 
834 	/*
835 	 * Turn around and call probe routine to see whether
836 	 * we actually have a tape at this SCSI nexus.
837 	 */
838 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
839 
840 		/*
841 		 * In checking the whole inq_dtype byte we are looking at both
842 		 * the Peripheral Qualifier and the Peripheral Device Type.
843 		 * For this driver we are only interested in sequential devices
844 		 * that are connected or capable if connecting to this logical
845 		 * unit.
846 		 */
847 		if (devp->sd_inq->inq_dtype ==
848 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
849 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
850 			    "probe exists\n");
851 			rval = DDI_PROBE_SUCCESS;
852 		} else {
853 			rval = DDI_PROBE_FAILURE;
854 		}
855 	} else {
856 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
857 		    "probe failure: nothing there\n");
858 		rval = DDI_PROBE_FAILURE;
859 	}
860 	scsi_unprobe(devp);
861 	return (rval);
862 }
863 
864 static int
865 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
866 {
867 	int 	instance;
868 	int	wide;
869 	int 	dev_instance;
870 	int	ret_status;
871 	struct	scsi_device *devp;
872 	int	node_ix;
873 	struct	scsi_tape *un;
874 
875 	ST_ENTR(devi, st_attach);
876 
877 	devp = ddi_get_driver_private(devi);
878 	instance = ddi_get_instance(devi);
879 
880 	switch (cmd) {
881 		case DDI_ATTACH:
882 			if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
883 			    "tape-command-recovery-disable", 0) != 0) {
884 				st_recov_sz = sizeof (pkt_info);
885 			}
886 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
887 				return (DDI_FAILURE);
888 			}
889 			break;
890 		case DDI_RESUME:
891 			/*
892 			 * Suspend/Resume
893 			 *
894 			 * When the driver suspended, there might be
895 			 * outstanding cmds and therefore we need to
896 			 * reset the suspended flag and resume the scsi
897 			 * watch thread and restart commands and timeouts
898 			 */
899 
900 			if (!(un = ddi_get_soft_state(st_state, instance))) {
901 				return (DDI_FAILURE);
902 			}
903 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
904 			    un->un_dev);
905 
906 			mutex_enter(ST_MUTEX);
907 
908 			un->un_throttle = un->un_max_throttle;
909 			un->un_tids_at_suspend = 0;
910 			un->un_pwr_mgmt = ST_PWR_NORMAL;
911 
912 			if (un->un_swr_token) {
913 				scsi_watch_resume(un->un_swr_token);
914 			}
915 
916 			/*
917 			 * Restart timeouts
918 			 */
919 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
920 				mutex_exit(ST_MUTEX);
921 				un->un_delay_tid = timeout(
922 				    st_delayed_cv_broadcast, un,
923 				    drv_usectohz((clock_t)
924 				    MEDIA_ACCESS_DELAY));
925 				mutex_enter(ST_MUTEX);
926 			}
927 
928 			if (un->un_tids_at_suspend & ST_HIB_TID) {
929 				mutex_exit(ST_MUTEX);
930 				un->un_hib_tid = timeout(st_intr_restart, un,
931 				    ST_STATUS_BUSY_TIMEOUT);
932 				mutex_enter(ST_MUTEX);
933 			}
934 
935 			ret_status = st_clear_unit_attentions(dev_instance, 5);
936 
937 			/*
938 			 * now check if we need to restore the tape position
939 			 */
940 			if ((un->un_suspend_pos.pmode != invalid) &&
941 			    ((un->un_suspend_pos.fileno > 0) ||
942 			    (un->un_suspend_pos.blkno > 0)) ||
943 			    (un->un_suspend_pos.lgclblkno > 0)) {
944 				if (ret_status != 0) {
945 					/*
946 					 * tape didn't get good TUR
947 					 * just print out error messages
948 					 */
949 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
950 					    "st_attach-RESUME: tape failure "
951 					    " tape position will be lost");
952 				} else {
953 					/* this prints errors */
954 					(void) st_validate_tapemarks(un,
955 					    st_uscsi_cmd, &un->un_suspend_pos);
956 				}
957 				/*
958 				 * there are no retries, if there is an error
959 				 * we don't know if the tape has changed
960 				 */
961 				un->un_suspend_pos.pmode = invalid;
962 			}
963 
964 			/* now we are ready to start up any queued I/Os */
965 			if (un->un_ncmds || un->un_quef) {
966 				st_start(un);
967 			}
968 
969 			cv_broadcast(&un->un_suspend_cv);
970 			mutex_exit(ST_MUTEX);
971 			return (DDI_SUCCESS);
972 
973 		default:
974 			return (DDI_FAILURE);
975 	}
976 
977 	un = ddi_get_soft_state(st_state, instance);
978 
979 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
980 	    "st_attach: instance=%x\n", instance);
981 
982 	/*
983 	 * Add a zero-length attribute to tell the world we support
984 	 * kernel ioctls (for layered drivers)
985 	 */
986 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
987 	    DDI_KERNEL_IOCTL, NULL, 0);
988 
989 	ddi_report_dev((dev_info_t *)devi);
990 
991 	/*
992 	 * If it's a SCSI-2 tape drive which supports wide,
993 	 * tell the host adapter to use wide.
994 	 */
995 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
996 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
997 
998 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
999 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1000 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
1001 	}
1002 
1003 	/*
1004 	 * enable autorequest sense; keep the rq packet around in case
1005 	 * the autorequest sense fails because of a busy condition
1006 	 * do a getcap first in case the capability is not variable
1007 	 */
1008 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
1009 		un->un_arq_enabled = 1;
1010 	} else {
1011 		un->un_arq_enabled =
1012 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
1013 	}
1014 
1015 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
1016 	    (un->un_arq_enabled ? "enabled" : "disabled"));
1017 
1018 	un->un_untagged_qing =
1019 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
1020 
1021 	/*
1022 	 * XXX - This is just for 2.6.  to tell users that write buffering
1023 	 *	has gone away.
1024 	 */
1025 	if (un->un_arq_enabled && un->un_untagged_qing) {
1026 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
1027 		    "tape-driver-buffering", 0) != 0) {
1028 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1029 			    "Write Data Buffering has been depricated. Your "
1030 			    "applications should continue to work normally.\n"
1031 			    " But, they should  ported to use Asynchronous "
1032 			    " I/O\n"
1033 			    " For more information, read about "
1034 			    " tape-driver-buffering "
1035 			    "property in the st(7d) man page\n");
1036 		}
1037 	}
1038 
1039 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
1040 	un->un_flush_on_errors = 0;
1041 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
1042 
1043 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
1044 	    "throttle=%x, max_throttle = %x\n",
1045 	    un->un_throttle, un->un_max_throttle);
1046 
1047 	/* initialize persistent errors to nil */
1048 	un->un_persistence = 0;
1049 	un->un_persist_errors = 0;
1050 
1051 	/*
1052 	 * Get dma-max from HBA driver. If it is not defined, use 64k
1053 	 */
1054 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
1055 	if (un->un_maxdma == -1) {
1056 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1057 		    "Received a value that looked like -1. Using 64k maxdma");
1058 		un->un_maxdma = (64 * ONE_K);
1059 	}
1060 
1061 #ifdef	__x86
1062 	/*
1063 	 * for x86, the device may be able to DMA more than the system will
1064 	 * allow under some circumstances. We need account for both the HBA's
1065 	 * and system's contraints.
1066 	 *
1067 	 * Get the maximum DMA under worse case conditions. e.g. looking at the
1068 	 * device constraints, the max copy buffer size, and the worse case
1069 	 * fragmentation. NOTE: this may differ from dma-max since dma-max
1070 	 * doesn't take the worse case framentation into account.
1071 	 *
1072 	 * e.g. a device may be able to DMA 16MBytes, but can only DMA 1MByte
1073 	 * if none of the pages are contiguous. Keeping track of both of these
1074 	 * values allows us to support larger tape block sizes on some devices.
1075 	 */
1076 	un->un_maxdma_arch = scsi_ifgetcap(&devp->sd_address, "dma-max-arch",
1077 	    1);
1078 
1079 	/*
1080 	 * If the dma-max-arch capability is not implemented, or the value
1081 	 * comes back higher than what was reported in dma-max, use dma-max.
1082 	 */
1083 	if ((un->un_maxdma_arch == -1) ||
1084 	    ((uint_t)un->un_maxdma < (uint_t)un->un_maxdma_arch)) {
1085 		un->un_maxdma_arch = un->un_maxdma;
1086 	}
1087 #endif
1088 
1089 	/*
1090 	 * Get the max allowable cdb size
1091 	 */
1092 	un->un_max_cdb_sz =
1093 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
1094 	if (un->un_max_cdb_sz < CDB_GROUP0) {
1095 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1096 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
1097 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
1098 	}
1099 
1100 	if (strcmp(ddi_driver_name(ddi_get_parent(ST_DEVINFO)), "scsi_vhci")) {
1101 		un->un_multipath = 0;
1102 	} else {
1103 		un->un_multipath = 1;
1104 	}
1105 
1106 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1107 
1108 	un->un_mediastate = MTIO_NONE;
1109 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1110 
1111 	/*
1112 	 * initialize kstats
1113 	 */
1114 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1115 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1116 	if (un->un_stats) {
1117 		un->un_stats->ks_lock = ST_MUTEX;
1118 		kstat_install(un->un_stats);
1119 	}
1120 	(void) st_create_errstats(un, instance);
1121 
1122 	/*
1123 	 * find the drive type for this target
1124 	 */
1125 	mutex_enter(ST_MUTEX);
1126 	un->un_dev = MTMINOR(instance);
1127 	st_known_tape_type(un);
1128 	un->un_dev = 0;
1129 	mutex_exit(ST_MUTEX);
1130 
1131 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
1132 		int minor;
1133 		char *name;
1134 
1135 		name  = st_minor_data[node_ix].name;
1136 		minor = st_minor_data[node_ix].minor;
1137 
1138 		/*
1139 		 * For default devices set the density to the
1140 		 * preferred default density for this device.
1141 		 */
1142 		if (node_ix <= DEF_BSD_NR) {
1143 			minor |= un->un_dp->default_density;
1144 		}
1145 		minor |= MTMINOR(instance);
1146 
1147 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
1148 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
1149 			continue;
1150 		}
1151 
1152 		ddi_remove_minor_node(devi, NULL);
1153 
1154 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1155 		    st_reset_notification, (caddr_t)un);
1156 		cv_destroy(&un->un_clscv);
1157 		cv_destroy(&un->un_sbuf_cv);
1158 		cv_destroy(&un->un_queue_cv);
1159 		cv_destroy(&un->un_state_cv);
1160 #ifdef	__x86
1161 		cv_destroy(&un->un_contig_mem_cv);
1162 #endif
1163 		cv_destroy(&un->un_suspend_cv);
1164 		cv_destroy(&un->un_tape_busy_cv);
1165 		cv_destroy(&un->un_recov_buf_cv);
1166 		if (un->un_recov_taskq) {
1167 			ddi_taskq_destroy(un->un_recov_taskq);
1168 		}
1169 		if (un->un_sbufp) {
1170 			freerbuf(un->un_sbufp);
1171 		}
1172 		if (un->un_recov_buf) {
1173 			freerbuf(un->un_recov_buf);
1174 		}
1175 		if (un->un_uscsi_rqs_buf) {
1176 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1177 		}
1178 		if (un->un_mspl) {
1179 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1180 		}
1181 		if (un->un_dp_size) {
1182 			kmem_free(un->un_dp, un->un_dp_size);
1183 		}
1184 		if (un->un_state) {
1185 			kstat_delete(un->un_stats);
1186 		}
1187 		if (un->un_errstats) {
1188 			kstat_delete(un->un_errstats);
1189 		}
1190 
1191 		scsi_destroy_pkt(un->un_rqs);
1192 		scsi_free_consistent_buf(un->un_rqs_bp);
1193 		ddi_soft_state_free(st_state, instance);
1194 		devp->sd_private = NULL;
1195 		devp->sd_sense = NULL;
1196 
1197 		ddi_prop_remove_all(devi);
1198 		return (DDI_FAILURE);
1199 	}
1200 
1201 	return (DDI_SUCCESS);
1202 }
1203 
1204 /*
1205  * st_detach:
1206  *
1207  * we allow a detach if and only if:
1208  *	- no tape is currently inserted
1209  *	- tape position is at BOT or unknown
1210  *		(if it is not at BOT then a no rewind
1211  *		device was opened and we have to preserve state)
1212  *	- it must be in a closed state : no timeouts or scsi_watch requests
1213  *		will exist if it is closed, so we don't need to check for
1214  *		them here.
1215  */
1216 /*ARGSUSED*/
1217 static int
1218 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1219 {
1220 	int instance;
1221 	int result;
1222 	struct scsi_device *devp;
1223 	struct scsi_tape *un;
1224 	clock_t wait_cmds_complete;
1225 
1226 	ST_ENTR(devi, st_detach);
1227 
1228 	instance = ddi_get_instance(devi);
1229 
1230 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1231 		return (DDI_FAILURE);
1232 	}
1233 
1234 	mutex_enter(ST_MUTEX);
1235 
1236 	/*
1237 	 * Clear error entry stack
1238 	 */
1239 	st_empty_error_stack(un);
1240 
1241 	mutex_exit(ST_MUTEX);
1242 
1243 	switch (cmd) {
1244 
1245 	case DDI_DETACH:
1246 		/*
1247 		 * Undo what we did in st_attach & st_doattach,
1248 		 * freeing resources and removing things we installed.
1249 		 * The system framework guarantees we are not active
1250 		 * with this devinfo node in any other entry points at
1251 		 * this time.
1252 		 */
1253 
1254 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1255 		    "st_detach: instance=%x, un=%p\n", instance,
1256 		    (void *)un);
1257 
1258 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1259 		    ((un->un_rsvd_status & ST_APPLICATION_RESERVATIONS) != 0) ||
1260 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1261 		    (un->un_state != ST_STATE_CLOSED)) {
1262 			/*
1263 			 * we cannot unload some targets because the
1264 			 * inquiry returns junk unless immediately
1265 			 * after a reset
1266 			 */
1267 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1268 			    "cannot unload instance %x\n", instance);
1269 			un->un_unit_attention_flags |= 4;
1270 			return (DDI_FAILURE);
1271 		}
1272 
1273 		/*
1274 		 * if the tape has been removed then we may unload;
1275 		 * do a test unit ready and if it returns NOT READY
1276 		 * then we assume that it is safe to unload.
1277 		 * as a side effect, pmode may be set to invalid if the
1278 		 * the test unit ready fails;
1279 		 * also un_state may be set to non-closed, so reset it
1280 		 */
1281 		if ((un->un_dev) &&		/* Been opened since attach */
1282 		    ((un->un_pos.pmode == legacy) &&
1283 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1284 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1285 		    ((un->un_pos.pmode == logical) &&
1286 		    (un->un_pos.lgclblkno > 0))) {
1287 			mutex_enter(ST_MUTEX);
1288 			/*
1289 			 * Send Test Unit Ready in the hopes that if
1290 			 * the drive is not in the state we think it is.
1291 			 * And the state will be changed so it can be detached.
1292 			 * If the command fails to reach the device and
1293 			 * the drive was not rewound or unloaded we want
1294 			 * to fail the detach till a user command fails
1295 			 * where after the detach will succead.
1296 			 */
1297 			result = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
1298 			/*
1299 			 * After TUR un_state may be set to non-closed,
1300 			 * so reset it back.
1301 			 */
1302 			un->un_state = ST_STATE_CLOSED;
1303 			mutex_exit(ST_MUTEX);
1304 		}
1305 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1306 		    "un_status=%x, fileno=%x, blkno=%x\n",
1307 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1308 
1309 		/*
1310 		 * check again:
1311 		 * if we are not at BOT then it is not safe to unload
1312 		 */
1313 		if ((un->un_dev) &&		/* Been opened since attach */
1314 		    (result != EACCES) &&	/* drive is use by somebody */
1315 		    ((((un->un_pos.pmode == legacy) &&
1316 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1317 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1318 		    ((un->un_pos.pmode == logical) &&
1319 		    (un->un_pos.lgclblkno > 0))) &&
1320 		    ((un->un_state == ST_STATE_CLOSED) &&
1321 		    (un->un_laststate == ST_STATE_CLOSING)))) {
1322 
1323 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1324 			    "cannot detach: pmode=%d fileno=0x%x, blkno=0x%x"
1325 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1326 			    un->un_pos.fileno, un->un_pos.blkno,
1327 			    un->un_pos.lgclblkno);
1328 			un->un_unit_attention_flags |= 4;
1329 			return (DDI_FAILURE);
1330 		}
1331 
1332 		/*
1333 		 * Just To make sure that we have released the
1334 		 * tape unit .
1335 		 */
1336 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1337 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1338 			mutex_enter(ST_MUTEX);
1339 			(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
1340 			mutex_exit(ST_MUTEX);
1341 		}
1342 
1343 		/*
1344 		 * now remove other data structures allocated in st_doattach()
1345 		 */
1346 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1347 		    "destroying/freeing\n");
1348 
1349 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1350 		    st_reset_notification, (caddr_t)un);
1351 		cv_destroy(&un->un_clscv);
1352 		cv_destroy(&un->un_sbuf_cv);
1353 		cv_destroy(&un->un_queue_cv);
1354 		cv_destroy(&un->un_suspend_cv);
1355 		cv_destroy(&un->un_tape_busy_cv);
1356 		cv_destroy(&un->un_recov_buf_cv);
1357 
1358 		if (un->un_recov_taskq) {
1359 			ddi_taskq_destroy(un->un_recov_taskq);
1360 		}
1361 
1362 		if (un->un_hib_tid) {
1363 			(void) untimeout(un->un_hib_tid);
1364 			un->un_hib_tid = 0;
1365 		}
1366 
1367 		if (un->un_delay_tid) {
1368 			(void) untimeout(un->un_delay_tid);
1369 			un->un_delay_tid = 0;
1370 		}
1371 		cv_destroy(&un->un_state_cv);
1372 
1373 #ifdef	__x86
1374 		cv_destroy(&un->un_contig_mem_cv);
1375 
1376 		if (un->un_contig_mem_hdl != NULL) {
1377 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1378 		}
1379 #endif
1380 		if (un->un_sbufp) {
1381 			freerbuf(un->un_sbufp);
1382 		}
1383 		if (un->un_recov_buf) {
1384 			freerbuf(un->un_recov_buf);
1385 		}
1386 		if (un->un_uscsi_rqs_buf) {
1387 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1388 		}
1389 		if (un->un_mspl) {
1390 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1391 		}
1392 		if (un->un_rqs) {
1393 			scsi_destroy_pkt(un->un_rqs);
1394 			scsi_free_consistent_buf(un->un_rqs_bp);
1395 		}
1396 		if (un->un_mkr_pkt) {
1397 			scsi_destroy_pkt(un->un_mkr_pkt);
1398 		}
1399 		if (un->un_arq_enabled) {
1400 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1401 		}
1402 		if (un->un_dp_size) {
1403 			kmem_free(un->un_dp, un->un_dp_size);
1404 		}
1405 		if (un->un_stats) {
1406 			kstat_delete(un->un_stats);
1407 			un->un_stats = (kstat_t *)0;
1408 		}
1409 		if (un->un_errstats) {
1410 			kstat_delete(un->un_errstats);
1411 			un->un_errstats = (kstat_t *)0;
1412 		}
1413 		if (un->un_media_id_len) {
1414 			kmem_free(un->un_media_id, un->un_media_id_len);
1415 		}
1416 		devp = ST_SCSI_DEVP;
1417 		ddi_soft_state_free(st_state, instance);
1418 		devp->sd_private = NULL;
1419 		devp->sd_sense = NULL;
1420 		scsi_unprobe(devp);
1421 		ddi_prop_remove_all(devi);
1422 		ddi_remove_minor_node(devi, NULL);
1423 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1424 		return (DDI_SUCCESS);
1425 
1426 	case DDI_SUSPEND:
1427 
1428 		/*
1429 		 * Suspend/Resume
1430 		 *
1431 		 * To process DDI_SUSPEND, we must do the following:
1432 		 *
1433 		 *  - check ddi_removing_power to see if power will be turned
1434 		 *    off. if so, return DDI_FAILURE
1435 		 *  - check if we are already suspended,
1436 		 *    if so, return DDI_FAILURE
1437 		 *  - check if device state is CLOSED,
1438 		 *    if not, return DDI_FAILURE.
1439 		 *  - wait until outstanding operations complete
1440 		 *  - save tape state
1441 		 *  - block new operations
1442 		 *  - cancel pending timeouts
1443 		 *
1444 		 */
1445 
1446 		if (ddi_removing_power(devi)) {
1447 			return (DDI_FAILURE);
1448 		}
1449 		mutex_enter(ST_MUTEX);
1450 
1451 		/*
1452 		 * Shouldn't already be suspended, if so return failure
1453 		 */
1454 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1455 			mutex_exit(ST_MUTEX);
1456 			return (DDI_FAILURE);
1457 		}
1458 		if (un->un_state != ST_STATE_CLOSED) {
1459 			mutex_exit(ST_MUTEX);
1460 			return (DDI_FAILURE);
1461 		}
1462 
1463 		/*
1464 		 * Wait for all outstanding I/O's to complete
1465 		 *
1466 		 * we wait on both ncmds and the wait queue for times
1467 		 * when we are flushing after persistent errors are
1468 		 * flagged, which is when ncmds can be 0, and the
1469 		 * queue can still have I/O's.  This way we preserve
1470 		 * order of biodone's.
1471 		 */
1472 		wait_cmds_complete = ddi_get_lbolt();
1473 		wait_cmds_complete +=
1474 		    st_wait_cmds_complete * drv_usectohz(1000000);
1475 		while (un->un_ncmds || un->un_quef ||
1476 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1477 
1478 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1479 			    wait_cmds_complete) == -1) {
1480 				/*
1481 				 * Time expired then cancel the command
1482 				 */
1483 				if (st_reset(un, RESET_LUN) == 0) {
1484 					if (un->un_last_throttle) {
1485 						un->un_throttle =
1486 						    un->un_last_throttle;
1487 					}
1488 					mutex_exit(ST_MUTEX);
1489 					return (DDI_FAILURE);
1490 				} else {
1491 					break;
1492 				}
1493 			}
1494 		}
1495 
1496 		/*
1497 		 * DDI_SUSPEND says that the system "may" power down, we
1498 		 * remember the file and block number before rewinding.
1499 		 * we also need to save state before issuing
1500 		 * any WRITE_FILE_MARK command.
1501 		 */
1502 		(void) st_update_block_pos(un, st_cmd, 0);
1503 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1504 
1505 
1506 		/*
1507 		 * Issue a zero write file fmk command to tell the drive to
1508 		 * flush any buffered tape marks
1509 		 */
1510 		(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1511 
1512 		/*
1513 		 * Because not all tape drives correctly implement buffer
1514 		 * flushing with the zero write file fmk command, issue a
1515 		 * synchronous rewind command to force data flushing.
1516 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1517 		 * anyway.
1518 		 */
1519 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
1520 
1521 		/* stop any new operations */
1522 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1523 		un->un_throttle = 0;
1524 
1525 		/*
1526 		 * cancel any outstanding timeouts
1527 		 */
1528 		if (un->un_delay_tid) {
1529 			timeout_id_t temp_id = un->un_delay_tid;
1530 			un->un_delay_tid = 0;
1531 			un->un_tids_at_suspend |= ST_DELAY_TID;
1532 			mutex_exit(ST_MUTEX);
1533 			(void) untimeout(temp_id);
1534 			mutex_enter(ST_MUTEX);
1535 		}
1536 
1537 		if (un->un_hib_tid) {
1538 			timeout_id_t temp_id = un->un_hib_tid;
1539 			un->un_hib_tid = 0;
1540 			un->un_tids_at_suspend |= ST_HIB_TID;
1541 			mutex_exit(ST_MUTEX);
1542 			(void) untimeout(temp_id);
1543 			mutex_enter(ST_MUTEX);
1544 		}
1545 
1546 		/*
1547 		 * Suspend the scsi_watch_thread
1548 		 */
1549 		if (un->un_swr_token) {
1550 			opaque_t temp_token = un->un_swr_token;
1551 			mutex_exit(ST_MUTEX);
1552 			scsi_watch_suspend(temp_token);
1553 		} else {
1554 			mutex_exit(ST_MUTEX);
1555 		}
1556 
1557 		return (DDI_SUCCESS);
1558 
1559 	default:
1560 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1561 		return (DDI_FAILURE);
1562 	}
1563 }
1564 
1565 
1566 /* ARGSUSED */
1567 static int
1568 st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1569 {
1570 	dev_t dev;
1571 	struct scsi_tape *un;
1572 	int instance, error;
1573 
1574 	ST_ENTR(dip, st_info);
1575 
1576 	switch (infocmd) {
1577 	case DDI_INFO_DEVT2DEVINFO:
1578 		dev = (dev_t)arg;
1579 		instance = MTUNIT(dev);
1580 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1581 			return (DDI_FAILURE);
1582 		*result = (void *) ST_DEVINFO;
1583 		error = DDI_SUCCESS;
1584 		break;
1585 	case DDI_INFO_DEVT2INSTANCE:
1586 		dev = (dev_t)arg;
1587 		instance = MTUNIT(dev);
1588 		*result = (void *)(uintptr_t)instance;
1589 		error = DDI_SUCCESS;
1590 		break;
1591 	default:
1592 		error = DDI_FAILURE;
1593 	}
1594 	return (error);
1595 }
1596 
1597 static int
1598 st_doattach(struct scsi_device *devp, int (*canwait)())
1599 {
1600 	struct scsi_tape *un = NULL;
1601 	recov_info *ri;
1602 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1603 	int instance;
1604 	size_t rlen;
1605 
1606 	ST_FUNC(devp->sd_dev, st_doattach);
1607 	/*
1608 	 * Call the routine scsi_probe to do some of the dirty work.
1609 	 * If the INQUIRY command succeeds, the field sd_inq in the
1610 	 * device structure will be filled in.
1611 	 */
1612 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1613 	    "st_doattach(): probing\n");
1614 
1615 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1616 
1617 		/*
1618 		 * In checking the whole inq_dtype byte we are looking at both
1619 		 * the Peripheral Qualifier and the Peripheral Device Type.
1620 		 * For this driver we are only interested in sequential devices
1621 		 * that are connected or capable if connecting to this logical
1622 		 * unit.
1623 		 */
1624 		if (devp->sd_inq->inq_dtype ==
1625 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1626 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1627 			    "probe exists\n");
1628 		} else {
1629 			/* Something there but not a tape device */
1630 			scsi_unprobe(devp);
1631 			return (DDI_FAILURE);
1632 		}
1633 	} else {
1634 		/* Nothing there */
1635 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1636 		    "probe failure: nothing there\n");
1637 		scsi_unprobe(devp);
1638 		return (DDI_FAILURE);
1639 	}
1640 
1641 
1642 	/*
1643 	 * The actual unit is present.
1644 	 * Now is the time to fill in the rest of our info..
1645 	 */
1646 	instance = ddi_get_instance(devp->sd_dev);
1647 
1648 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1649 		goto error;
1650 	}
1651 	un = ddi_get_soft_state(st_state, instance);
1652 
1653 	ASSERT(un != NULL);
1654 
1655 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
1656 	    MAX_SENSE_LENGTH, B_READ, canwait, NULL);
1657 	if (un->un_rqs_bp == NULL) {
1658 		goto error;
1659 	}
1660 	un->un_rqs = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
1661 	    CDB_GROUP0, 1, st_recov_sz, PKT_CONSISTENT, canwait, NULL);
1662 	if (!un->un_rqs) {
1663 		goto error;
1664 	}
1665 	ASSERT(un->un_rqs->pkt_resid == 0);
1666 	devp->sd_sense =
1667 	    (struct scsi_extended_sense *)un->un_rqs_bp->b_un.b_addr;
1668 	ASSERT(geterror(un->un_rqs_bp) == NULL);
1669 
1670 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs->pkt_cdbp,
1671 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
1672 	FILL_SCSI1_LUN(devp, un->un_rqs);
1673 	un->un_rqs->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1674 	un->un_rqs->pkt_time = st_io_time;
1675 	un->un_rqs->pkt_comp = st_intr;
1676 	ri = (recov_info *)un->un_rqs->pkt_private;
1677 	if (st_recov_sz == sizeof (recov_info)) {
1678 		ri->privatelen = sizeof (recov_info);
1679 	} else {
1680 		ri->privatelen = sizeof (pkt_info);
1681 	}
1682 
1683 	un->un_sbufp = getrbuf(km_flags);
1684 	un->un_recov_buf = getrbuf(km_flags);
1685 
1686 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1687 
1688 	/*
1689 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1690 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1691 	 * is obsolete and we want more flexibility in controlling the DMA
1692 	 * address constraints.
1693 	 */
1694 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1695 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1696 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1697 
1698 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1699 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1700 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1701 
1702 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1703 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1704 		    "probe partial failure: no space\n");
1705 		goto error;
1706 	}
1707 
1708 	bzero(un->un_mspl, sizeof (struct seq_mode));
1709 
1710 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1711 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1712 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1713 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1714 #ifdef	__x86
1715 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1716 #endif
1717 
1718 	/* Initialize power managemnet condition variable */
1719 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1720 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1721 	cv_init(&un->un_recov_buf_cv, NULL, CV_DRIVER, NULL);
1722 
1723 	un->un_recov_taskq = ddi_taskq_create(devp->sd_dev,
1724 	    "un_recov_taskq", 1, TASKQ_DEFAULTPRI, km_flags);
1725 
1726 	ASSERT(un->un_recov_taskq != NULL);
1727 
1728 	un->un_pos.pmode = invalid;
1729 	un->un_sd	= devp;
1730 	un->un_swr_token = (opaque_t)NULL;
1731 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1732 	un->un_wormable = st_is_drive_worm;
1733 	un->un_media_id_method = st_get_media_identification;
1734 	/*
1735 	 * setting long a initial as it contains logical file info.
1736 	 * support for long format is mandatory but many drive don't do it.
1737 	 */
1738 	un->un_read_pos_type = LONG_POS;
1739 
1740 	un->un_suspend_pos.pmode = invalid;
1741 
1742 	st_add_recovery_info_to_pkt(un, un->un_rqs_bp, un->un_rqs);
1743 
1744 #ifdef	__x86
1745 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1746 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1747 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1748 		    "allocation of contiguous memory dma handle failed!");
1749 		un->un_contig_mem_hdl = NULL;
1750 		goto error;
1751 	}
1752 #endif
1753 
1754 	/*
1755 	 * Since this driver manages devices with "remote" hardware,
1756 	 * i.e. the devices themselves have no "reg" properties,
1757 	 * the SUSPEND/RESUME commands in detach/attach will not be
1758 	 * called by the power management framework unless we request
1759 	 * it by creating a "pm-hardware-state" property and setting it
1760 	 * to value "needs-suspend-resume".
1761 	 */
1762 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1763 	    "pm-hardware-state", "needs-suspend-resume") !=
1764 	    DDI_PROP_SUCCESS) {
1765 
1766 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1767 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1768 		goto error;
1769 	}
1770 
1771 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1772 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1773 
1774 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1775 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1776 		    "failed\n");
1777 		goto error;
1778 	}
1779 
1780 	(void) scsi_reset_notify(ROUTE, SCSI_RESET_NOTIFY,
1781 	    st_reset_notification, (caddr_t)un);
1782 
1783 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "attach success\n");
1784 	return (DDI_SUCCESS);
1785 
1786 error:
1787 	devp->sd_sense = NULL;
1788 
1789 	ddi_remove_minor_node(devp->sd_dev, NULL);
1790 	if (un) {
1791 		if (un->un_mspl) {
1792 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1793 		}
1794 		if (un->un_read_pos_data) {
1795 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1796 		}
1797 		if (un->un_sbufp) {
1798 			freerbuf(un->un_sbufp);
1799 		}
1800 		if (un->un_recov_buf) {
1801 			freerbuf(un->un_recov_buf);
1802 		}
1803 		if (un->un_uscsi_rqs_buf) {
1804 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1805 		}
1806 #ifdef	__x86
1807 		if (un->un_contig_mem_hdl != NULL) {
1808 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1809 		}
1810 #endif
1811 		if (un->un_rqs) {
1812 			scsi_destroy_pkt(un->un_rqs);
1813 		}
1814 
1815 		if (un->un_rqs_bp) {
1816 			scsi_free_consistent_buf(un->un_rqs_bp);
1817 		}
1818 
1819 		ddi_soft_state_free(st_state, instance);
1820 		devp->sd_private = NULL;
1821 	}
1822 
1823 	if (devp->sd_inq) {
1824 		scsi_unprobe(devp);
1825 	}
1826 	return (DDI_FAILURE);
1827 }
1828 
1829 typedef int
1830 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1831 
1832 static cfg_functp config_functs[] = {
1833 	st_get_conf_from_st_dot_conf,
1834 	st_get_conf_from_st_conf_dot_c,
1835 	st_get_conf_from_tape_drive,
1836 	st_get_default_conf
1837 };
1838 
1839 
1840 /*
1841  * determine tape type, using tape-config-list or built-in table or
1842  * use a generic tape config entry
1843  */
1844 static void
1845 st_known_tape_type(struct scsi_tape *un)
1846 {
1847 	struct st_drivetype *dp;
1848 	cfg_functp *config_funct;
1849 	uchar_t reserved;
1850 
1851 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1852 
1853 	reserved = (un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1854 	    : ST_RELEASE;
1855 
1856 	/*
1857 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1858 	 *	 no vid & pid inquiry data.  So, we provide one.
1859 	 */
1860 	if (ST_INQUIRY->inq_len == 0 ||
1861 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1862 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1863 	}
1864 
1865 	if (un->un_dp_size == 0) {
1866 		un->un_dp_size = sizeof (struct st_drivetype);
1867 		dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1868 		un->un_dp = dp;
1869 	} else {
1870 		dp = un->un_dp;
1871 	}
1872 
1873 	un->un_dp->non_motion_timeout = st_io_time;
1874 	/*
1875 	 * Loop through the configuration methods till one works.
1876 	 */
1877 	for (config_funct = &config_functs[0]; ; config_funct++) {
1878 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1879 			break;
1880 		}
1881 	}
1882 
1883 	if (un->un_dp->type != ST_TYPE_INVALID) {
1884 		int result;
1885 
1886 		/* try and enable TLR */
1887 		un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
1888 		result = st_set_target_TLR_mode(un, st_uscsi_cmd);
1889 		if (result == EACCES) {
1890 			/*
1891 			 * From attach command failed.
1892 			 * Set dp type so is run again on open.
1893 			 */
1894 			un->un_dp->type = ST_TYPE_INVALID;
1895 			un->un_tlr_flag = TLR_NOT_KNOWN;
1896 		} else if (result == 0) {
1897 			if (scsi_ifgetcap(&un->un_sd->sd_address,
1898 			    "tran-layer-retries", 1) == -1) {
1899 				un->un_tlr_flag = TLR_NOT_SUPPORTED;
1900 				(void) st_set_target_TLR_mode(un, st_uscsi_cmd);
1901 			} else {
1902 				un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
1903 			}
1904 		} else {
1905 			un->un_tlr_flag = TLR_NOT_SUPPORTED;
1906 		}
1907 	}
1908 
1909 
1910 
1911 
1912 	/*
1913 	 * If we didn't just make up this configuration and
1914 	 * all the density codes are the same..
1915 	 * Set Auto Density over ride.
1916 	 */
1917 	if (*config_funct != st_get_default_conf) {
1918 		/*
1919 		 * If this device is one that is configured and all
1920 		 * densities are the same, This saves doing gets and set
1921 		 * that yield nothing.
1922 		 */
1923 		if ((dp->densities[0]) == (dp->densities[1]) &&
1924 		    (dp->densities[0]) == (dp->densities[2]) &&
1925 		    (dp->densities[0]) == (dp->densities[3])) {
1926 
1927 			dp->options |= ST_AUTODEN_OVERRIDE;
1928 		}
1929 	}
1930 
1931 
1932 	/*
1933 	 * Store tape drive characteristics.
1934 	 */
1935 	un->un_status = 0;
1936 	un->un_attached = 1;
1937 	un->un_init_options = dp->options;
1938 
1939 	/* setup operation time-outs based on options */
1940 	st_calculate_timeouts(un);
1941 
1942 	/* make sure if we are supposed to be variable, make it variable */
1943 	if (dp->options & ST_VARIABLE) {
1944 		dp->bsize = 0;
1945 	}
1946 
1947 	if (reserved != ((un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1948 	    : ST_RELEASE)) {
1949 		(void) st_reserve_release(un, reserved, st_uscsi_cmd);
1950 	}
1951 
1952 	un->un_unit_attention_flags |= 1;
1953 
1954 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1955 
1956 }
1957 
1958 
1959 typedef struct {
1960 	int mask;
1961 	int bottom;
1962 	int top;
1963 	char *name;
1964 } conf_limit;
1965 
1966 static const conf_limit conf_limits[] = {
1967 
1968 	-1,		1,		2,		"conf version",
1969 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1970 	-1,		0,		0xffffff,	"block size",
1971 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1972 	-1,		0,		4,		"number of densities",
1973 	-1,		0,		UINT8_MAX,	"density code",
1974 	-1,		0,		3,		"default density",
1975 	-1,		0,		UINT16_MAX,	"non motion timeout",
1976 	-1,		0,		UINT16_MAX,	"I/O timeout",
1977 	-1,		0,		UINT16_MAX,	"space timeout",
1978 	-1,		0,		UINT16_MAX,	"load timeout",
1979 	-1,		0,		UINT16_MAX,	"unload timeout",
1980 	-1,		0,		UINT16_MAX,	"erase timeout",
1981 	0,		0,		0,		NULL
1982 };
1983 
1984 static int
1985 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1986     const char *conf_name)
1987 {
1988 	int dens;
1989 	int ndens;
1990 	int value;
1991 	int type;
1992 	int count;
1993 	const conf_limit *limit = &conf_limits[0];
1994 
1995 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1996 
1997 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1998 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1999 
2000 	count = list_len;
2001 	type = *list;
2002 	for (;  count && limit->name; count--, list++, limit++) {
2003 
2004 		value = *list;
2005 		if (value & ~limit->mask) {
2006 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2007 			    "%s %s value invalid bits set: 0x%X\n",
2008 			    conf_name, limit->name, value & ~limit->mask);
2009 			*list &= limit->mask;
2010 		} else if (value < limit->bottom) {
2011 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2012 			    "%s %s value too low: value = %d limit %d\n",
2013 			    conf_name, limit->name, value, limit->bottom);
2014 		} else if (value > limit->top) {
2015 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2016 			    "%s %s value too high: value = %d limit %d\n",
2017 			    conf_name, limit->name, value, limit->top);
2018 		} else {
2019 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2020 			    "%s %s value = 0x%X\n",
2021 			    conf_name, limit->name, value);
2022 		}
2023 
2024 		/* If not the number of densities continue */
2025 		if (limit != &conf_limits[4]) {
2026 			continue;
2027 		}
2028 
2029 		/* If number of densities is not in range can't use config */
2030 		if (value < limit->bottom || value > limit->top) {
2031 			return (-1);
2032 		}
2033 
2034 		ndens = min(value, NDENSITIES);
2035 		if ((type == 1) && (list_len - ndens) != 6) {
2036 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2037 			    "%s conf version 1 with %d densities has %d items"
2038 			    " should have %d",
2039 			    conf_name, ndens, list_len, 6 + ndens);
2040 		} else if ((type == 2) && (list_len - ndens) != 13) {
2041 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2042 			    "%s conf version 2 with %d densities has %d items"
2043 			    " should have %d",
2044 			    conf_name, ndens, list_len, 13 + ndens);
2045 		}
2046 
2047 		limit++;
2048 		for (dens = 0; dens < ndens && count; dens++) {
2049 			count--;
2050 			list++;
2051 			value = *list;
2052 			if (value < limit->bottom) {
2053 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2054 				    "%s density[%d] value too low: value ="
2055 				    " 0x%X limit 0x%X\n",
2056 				    conf_name, dens, value, limit->bottom);
2057 			} else if (value > limit->top) {
2058 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2059 				    "%s density[%d] value too high: value ="
2060 				    " 0x%X limit 0x%X\n",
2061 				    conf_name, dens, value, limit->top);
2062 			} else {
2063 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2064 				    "%s density[%d] value = 0x%X\n",
2065 				    conf_name, dens, value);
2066 			}
2067 		}
2068 	}
2069 
2070 	return (0);
2071 }
2072 
2073 static int
2074 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
2075     struct st_drivetype *dp)
2076 {
2077 	caddr_t config_list = NULL;
2078 	caddr_t data_list = NULL;
2079 	int	*data_ptr;
2080 	caddr_t vidptr, prettyptr, datanameptr;
2081 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
2082 	int config_list_len, data_list_len, len, i;
2083 	int version;
2084 	int found = 0;
2085 
2086 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
2087 
2088 	/*
2089 	 * Determine type of tape controller. Type is determined by
2090 	 * checking the vendor ids of the earlier inquiry command and
2091 	 * comparing those with vids in tape-config-list defined in st.conf
2092 	 */
2093 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
2094 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
2095 	    != DDI_PROP_SUCCESS) {
2096 		return (found);
2097 	}
2098 
2099 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2100 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
2101 
2102 	/*
2103 	 * Compare vids in each triplet - if it matches, get value for
2104 	 * data_name and contruct a st_drivetype struct
2105 	 * tripletlen is not set yet!
2106 	 */
2107 	for (len = config_list_len, vidptr = config_list;
2108 	    len > 0;
2109 	    vidptr += tripletlen, len -= tripletlen) {
2110 
2111 		vidlen = strlen(vidptr);
2112 		prettyptr = vidptr + vidlen + 1;
2113 		prettylen = strlen(prettyptr);
2114 		datanameptr = prettyptr + prettylen + 1;
2115 		datanamelen = strlen(datanameptr);
2116 		tripletlen = vidlen + prettylen + datanamelen + 3;
2117 
2118 		if (vidlen == 0) {
2119 			continue;
2120 		}
2121 
2122 		/*
2123 		 * If inquiry vid dosen't match this triplets vid,
2124 		 * try the next.
2125 		 */
2126 		if (strncasecmp(vidpid, vidptr, vidlen)) {
2127 			continue;
2128 		}
2129 
2130 		/*
2131 		 * if prettylen is zero then use the vid string
2132 		 */
2133 		if (prettylen == 0) {
2134 			prettyptr = vidptr;
2135 			prettylen = vidlen;
2136 		}
2137 
2138 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2139 		    "vid = %s, pretty=%s, dataname = %s\n",
2140 		    vidptr, prettyptr, datanameptr);
2141 
2142 		/*
2143 		 * get the data list
2144 		 */
2145 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
2146 		    datanameptr, (caddr_t)&data_list,
2147 		    &data_list_len) != DDI_PROP_SUCCESS) {
2148 			/*
2149 			 * Error in getting property value
2150 			 * print warning!
2151 			 */
2152 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2153 			    "data property (%s) has no value\n",
2154 			    datanameptr);
2155 			continue;
2156 		}
2157 
2158 		/*
2159 		 * now initialize the st_drivetype struct
2160 		 */
2161 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
2162 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
2163 		(void) strncpy(dp->vid, vidptr, dp->length);
2164 		data_ptr = (int *)data_list;
2165 		/*
2166 		 * check if data is enough for version, type,
2167 		 * bsize, options, # of densities, density1,
2168 		 * density2, ..., default_density
2169 		 */
2170 		if ((data_list_len < 5 * sizeof (int)) ||
2171 		    (data_list_len < 6 * sizeof (int) +
2172 		    *(data_ptr + 4) * sizeof (int))) {
2173 			/*
2174 			 * print warning and skip to next triplet.
2175 			 */
2176 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2177 			    "data property (%s) incomplete\n",
2178 			    datanameptr);
2179 			kmem_free(data_list, data_list_len);
2180 			continue;
2181 		}
2182 
2183 		if (st_validate_conf_data(un, data_ptr,
2184 		    data_list_len / sizeof (int), datanameptr)) {
2185 			kmem_free(data_list, data_list_len);
2186 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2187 			    "data property (%s) rejected\n",
2188 			    datanameptr);
2189 			continue;
2190 		}
2191 
2192 		/*
2193 		 * check version
2194 		 */
2195 		version = *data_ptr++;
2196 		if (version != 1 && version != 2) {
2197 			/* print warning but accept it */
2198 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2199 			    "Version # for data property (%s) "
2200 			    "not set to 1 or 2\n", datanameptr);
2201 		}
2202 
2203 		dp->type    = *data_ptr++;
2204 		dp->bsize   = *data_ptr++;
2205 		dp->options = *data_ptr++;
2206 		dp->options |= ST_DYNAMIC;
2207 		len = *data_ptr++;
2208 		for (i = 0; i < NDENSITIES; i++) {
2209 			if (i < len) {
2210 				dp->densities[i] = *data_ptr++;
2211 			}
2212 		}
2213 		dp->default_density = *data_ptr << 3;
2214 		if (version == 2 &&
2215 		    data_list_len >= (13 + len) * sizeof (int)) {
2216 			data_ptr++;
2217 			dp->non_motion_timeout	= *data_ptr++;
2218 			dp->io_timeout		= *data_ptr++;
2219 			dp->rewind_timeout	= *data_ptr++;
2220 			dp->space_timeout	= *data_ptr++;
2221 			dp->load_timeout	= *data_ptr++;
2222 			dp->unload_timeout	= *data_ptr++;
2223 			dp->erase_timeout	= *data_ptr++;
2224 		}
2225 		kmem_free(data_list, data_list_len);
2226 		found = 1;
2227 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2228 		    "found in st.conf: vid = %s, pretty=%s\n",
2229 		    dp->vid, dp->name);
2230 		break;
2231 	}
2232 
2233 	/*
2234 	 * free up the memory allocated by ddi_getlongprop
2235 	 */
2236 	if (config_list) {
2237 		kmem_free(config_list, config_list_len);
2238 	}
2239 	return (found);
2240 }
2241 
2242 static int
2243 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2244     struct st_drivetype *dp)
2245 {
2246 	int i;
2247 
2248 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2249 	/*
2250 	 * Determine type of tape controller.  Type is determined by
2251 	 * checking the result of the earlier inquiry command and
2252 	 * comparing vendor ids with strings in a table declared in st_conf.c.
2253 	 */
2254 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2255 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2256 
2257 	for (i = 0; i < st_ndrivetypes; i++) {
2258 		if (st_drivetypes[i].length == 0) {
2259 			continue;
2260 		}
2261 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2262 		    st_drivetypes[i].length)) {
2263 			continue;
2264 		}
2265 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2266 		return (1);
2267 	}
2268 	return (0);
2269 }
2270 
2271 static int
2272 st_get_conf_from_tape_drive(struct scsi_tape *un, char *vidpid,
2273     struct st_drivetype *dp)
2274 {
2275 	int bsize;
2276 	ulong_t maxbsize;
2277 	caddr_t buf;
2278 	struct st_drivetype *tem_dp;
2279 	struct read_blklim *blklim;
2280 	int rval;
2281 	int i;
2282 
2283 	ST_FUNC(ST_DEVINFO, st_get_conf_from_tape_drive);
2284 
2285 	/*
2286 	 * Determine the type of tape controller. Type is determined by
2287 	 * sending SCSI commands to tape drive and deriving the type from
2288 	 * the returned data.
2289 	 */
2290 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2291 	    "st_get_conf_from_tape_drive(): asking tape drive\n");
2292 
2293 	tem_dp = kmem_zalloc(sizeof (struct st_drivetype), KM_SLEEP);
2294 
2295 	/*
2296 	 * Make up a name
2297 	 */
2298 	bcopy(vidpid, tem_dp->name, VIDPIDLEN);
2299 	tem_dp->name[VIDPIDLEN] = '\0';
2300 	tem_dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2301 	(void) strncpy(tem_dp->vid, ST_INQUIRY->inq_vid, tem_dp->length);
2302 	/*
2303 	 * 'clean' vendor and product strings of non-printing chars
2304 	 */
2305 	for (i = 0; i < VIDPIDLEN - 1; i ++) {
2306 		if (tem_dp->name[i] < ' ' || tem_dp->name[i] > '~') {
2307 			tem_dp->name[i] = '.';
2308 		}
2309 	}
2310 
2311 	/*
2312 	 * MODE SENSE to determine block size.
2313 	 */
2314 	un->un_dp->options |= ST_MODE_SEL_COMP | ST_UNLOADABLE;
2315 	rval = st_modesense(un);
2316 	if (rval) {
2317 		if (rval == EACCES) {
2318 			un->un_dp->type = ST_TYPE_INVALID;
2319 			rval = 1;
2320 		} else {
2321 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
2322 			rval = 0;
2323 		}
2324 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2325 		    "st_get_conf_from_tape_drive(): fail to mode sense\n");
2326 		goto exit;
2327 	}
2328 
2329 	/* Can mode sense page 0x10 or 0xf */
2330 	tem_dp->options |= ST_MODE_SEL_COMP;
2331 	bsize = (un->un_mspl->high_bl << 16)	|
2332 	    (un->un_mspl->mid_bl << 8)		|
2333 	    (un->un_mspl->low_bl);
2334 
2335 	if (bsize == 0) {
2336 		tem_dp->options |= ST_VARIABLE;
2337 		tem_dp->bsize = 0;
2338 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
2339 		rval = st_change_block_size(un, 0);
2340 		if (rval) {
2341 			if (rval == EACCES) {
2342 				un->un_dp->type = ST_TYPE_INVALID;
2343 				rval = 1;
2344 			} else {
2345 				rval = 0;
2346 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2347 				    "st_get_conf_from_tape_drive(): "
2348 				    "Fixed record size is too large and"
2349 				    "cannot switch to variable record size");
2350 			}
2351 			goto exit;
2352 		}
2353 		tem_dp->options |= ST_VARIABLE;
2354 	} else {
2355 		rval = st_change_block_size(un, 0);
2356 		if (rval == 0) {
2357 			tem_dp->options |= ST_VARIABLE;
2358 			tem_dp->bsize = 0;
2359 		} else if (rval != EACCES) {
2360 			tem_dp->bsize = bsize;
2361 		} else {
2362 			un->un_dp->type = ST_TYPE_INVALID;
2363 			rval = 1;
2364 			goto exit;
2365 		}
2366 	}
2367 
2368 	/*
2369 	 * If READ BLOCk LIMITS works and upper block size limit is
2370 	 * more than 64K, ST_NO_RECSIZE_LIMIT is supported.
2371 	 */
2372 	blklim = kmem_zalloc(sizeof (struct read_blklim), KM_SLEEP);
2373 	rval = st_read_block_limits(un, blklim);
2374 	if (rval) {
2375 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2376 		    "st_get_conf_from_tape_drive(): "
2377 		    "fail to read block limits.\n");
2378 		rval = 0;
2379 		kmem_free(blklim, sizeof (struct read_blklim));
2380 		goto exit;
2381 	}
2382 	maxbsize = (blklim->max_hi << 16) +
2383 	    (blklim->max_mid << 8) + blklim->max_lo;
2384 	if (maxbsize > ST_MAXRECSIZE_VARIABLE) {
2385 		tem_dp->options |= ST_NO_RECSIZE_LIMIT;
2386 	}
2387 	kmem_free(blklim, sizeof (struct read_blklim));
2388 
2389 	/*
2390 	 * Inquiry VPD page 0xb0 to see if the tape drive supports WORM
2391 	 */
2392 	buf = kmem_zalloc(6, KM_SLEEP);
2393 	rval = st_get_special_inquiry(un, 6, buf, 0xb0);
2394 	if (rval) {
2395 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2396 		    "st_get_conf_from_tape_drive(): "
2397 		    "fail to read vitial inquiry.\n");
2398 		rval = 0;
2399 		kmem_free(buf, 6);
2400 		goto exit;
2401 	}
2402 	if (buf[4] & 1) {
2403 		tem_dp->options |= ST_WORMABLE;
2404 	}
2405 	kmem_free(buf, 6);
2406 
2407 	/* Assume BSD BSR KNOWS_EOD */
2408 	tem_dp->options |= ST_BSF | ST_BSR | ST_KNOWS_EOD | ST_UNLOADABLE;
2409 	tem_dp->max_rretries = -1;
2410 	tem_dp->max_wretries = -1;
2411 
2412 	/*
2413 	 * Decide the densities supported by tape drive by sending
2414 	 * REPORT DENSITY SUPPORT command.
2415 	 */
2416 	if (st_get_densities_from_tape_drive(un, tem_dp) == 0) {
2417 		goto exit;
2418 	}
2419 
2420 	/*
2421 	 * Decide the timeout values for several commands by sending
2422 	 * REPORT SUPPORTED OPERATION CODES command.
2423 	 */
2424 	rval = st_get_timeout_values_from_tape_drive(un, tem_dp);
2425 	if (rval == 0 || ((rval == 1) && (tem_dp->type == ST_TYPE_INVALID))) {
2426 		goto exit;
2427 	}
2428 
2429 	bcopy(tem_dp, dp, sizeof (struct st_drivetype));
2430 	rval = 1;
2431 
2432 exit:
2433 	un->un_status = KEY_NO_SENSE;
2434 	kmem_free(tem_dp, sizeof (struct st_drivetype));
2435 	return (rval);
2436 }
2437 
2438 static int
2439 st_get_densities_from_tape_drive(struct scsi_tape *un,
2440     struct st_drivetype *dp)
2441 {
2442 	int i, p;
2443 	size_t buflen;
2444 	ushort_t des_len;
2445 	uchar_t *den_header;
2446 	uchar_t num_den;
2447 	uchar_t den[NDENSITIES];
2448 	uchar_t deflt[NDENSITIES];
2449 	struct report_density_desc *den_desc;
2450 
2451 	ST_FUNC(ST_DEVINFO, st_get_densities_from_type_drive);
2452 
2453 	/*
2454 	 * Since we have no idea how many densitiy support entries
2455 	 * will be returned, we send the command firstly assuming
2456 	 * there is only one. Then we can decide the number of
2457 	 * entries by available density support length. If multiple
2458 	 * entries exist, we will resend the command with enough
2459 	 * buffer size.
2460 	 */
2461 	buflen = sizeof (struct report_density_header) +
2462 	    sizeof (struct report_density_desc);
2463 	den_header = kmem_zalloc(buflen, KM_SLEEP);
2464 	if (st_report_density_support(un, den_header, buflen) != 0) {
2465 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2466 		    "st_get_conf_from_tape_drive(): fail to report density.\n");
2467 		kmem_free(den_header, buflen);
2468 		return (0);
2469 	}
2470 	des_len =
2471 	    BE_16(((struct report_density_header *)den_header)->ava_dens_len);
2472 	num_den = (des_len - 2) / sizeof (struct report_density_desc);
2473 
2474 	if (num_den > 1) {
2475 		kmem_free(den_header, buflen);
2476 		buflen = sizeof (struct report_density_header) +
2477 		    sizeof (struct report_density_desc) * num_den;
2478 		den_header = kmem_zalloc(buflen, KM_SLEEP);
2479 		if (st_report_density_support(un, den_header, buflen) != 0) {
2480 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2481 			    "st_get_conf_from_tape_drive(): "
2482 			    "fail to report density.\n");
2483 			kmem_free(den_header, buflen);
2484 			return (0);
2485 		}
2486 	}
2487 
2488 	den_desc = (struct report_density_desc *)(den_header
2489 	    + sizeof (struct report_density_header));
2490 
2491 	/*
2492 	 * Decide the drive type by assigning organization
2493 	 */
2494 	for (i = 0; i < ST_NUM_MEMBERS(st_vid_dt); i ++) {
2495 		if (strncmp(st_vid_dt[i].vid, (char *)(den_desc->ass_org),
2496 		    8) == 0) {
2497 			dp->type = st_vid_dt[i].type;
2498 			break;
2499 		}
2500 	}
2501 	if (i == ST_NUM_MEMBERS(st_vid_dt)) {
2502 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2503 		    "st_get_conf_from_tape_drive(): "
2504 		    "can't find match of assigned ort.\n");
2505 		kmem_free(den_header, buflen);
2506 		return (0);
2507 	}
2508 
2509 	/*
2510 	 * The tape drive may support many tape formats, but the st driver
2511 	 * supports only the four highest densities. Since density code
2512 	 * values are returned by ascending sequence, we start from the
2513 	 * last entry of density support data block descriptor.
2514 	 */
2515 	p = 0;
2516 	den_desc += num_den - 1;
2517 	for (i = 0; i < num_den && p < NDENSITIES; i ++, den_desc --) {
2518 		if ((den_desc->pri_den != 0) && (den_desc->wrtok)) {
2519 			if (p != 0) {
2520 				if (den_desc->pri_den >= den[p - 1]) {
2521 					continue;
2522 				}
2523 			}
2524 			den[p] = den_desc->pri_den;
2525 			deflt[p] = den_desc->deflt;
2526 			p ++;
2527 		}
2528 	}
2529 
2530 	switch (p) {
2531 	case 0:
2532 		bzero(dp->densities, NDENSITIES);
2533 		dp->options |= ST_AUTODEN_OVERRIDE;
2534 		dp->default_density = MT_DENSITY4;
2535 		break;
2536 
2537 	case 1:
2538 		(void) memset(dp->densities, den[0], NDENSITIES);
2539 		dp->options |= ST_AUTODEN_OVERRIDE;
2540 		dp->default_density = MT_DENSITY4;
2541 		break;
2542 
2543 	case 2:
2544 		dp->densities[0] = den[1];
2545 		dp->densities[1] = den[1];
2546 		dp->densities[2] = den[0];
2547 		dp->densities[3] = den[0];
2548 		if (deflt[0]) {
2549 			dp->default_density = MT_DENSITY4;
2550 		} else {
2551 			dp->default_density = MT_DENSITY2;
2552 		}
2553 		break;
2554 
2555 	case 3:
2556 		dp->densities[0] = den[2];
2557 		dp->densities[1] = den[1];
2558 		dp->densities[2] = den[0];
2559 		dp->densities[3] = den[0];
2560 		if (deflt[0]) {
2561 			dp->default_density = MT_DENSITY4;
2562 		} else if (deflt[1]) {
2563 			dp->default_density = MT_DENSITY2;
2564 		} else {
2565 			dp->default_density = MT_DENSITY1;
2566 		}
2567 		break;
2568 
2569 	default:
2570 		for (i = p; i > p - NDENSITIES; i --) {
2571 			dp->densities[i - 1] = den[p - i];
2572 		}
2573 		if (deflt[0]) {
2574 			dp->default_density = MT_DENSITY4;
2575 		} else if (deflt[1]) {
2576 			dp->default_density = MT_DENSITY3;
2577 		} else if (deflt[2]) {
2578 			dp->default_density = MT_DENSITY2;
2579 		} else {
2580 			dp->default_density = MT_DENSITY1;
2581 		}
2582 		break;
2583 	}
2584 
2585 	bzero(dp->mediatype, NDENSITIES);
2586 
2587 	kmem_free(den_header, buflen);
2588 	return (1);
2589 }
2590 
2591 static int
2592 st_get_timeout_values_from_tape_drive(struct scsi_tape *un,
2593     struct st_drivetype *dp)
2594 {
2595 	ushort_t timeout;
2596 	int rval;
2597 
2598 	ST_FUNC(ST_DEVINFO, st_get_timeout_values_from_type_drive);
2599 
2600 	rval = st_get_timeouts_value(un, SCMD_ERASE, &timeout, 0);
2601 	if (rval) {
2602 		if (rval == EACCES) {
2603 			un->un_dp->type = ST_TYPE_INVALID;
2604 			dp->type = ST_TYPE_INVALID;
2605 			return (1);
2606 		}
2607 		return (0);
2608 	}
2609 	dp->erase_timeout = timeout;
2610 
2611 	rval = st_get_timeouts_value(un, SCMD_READ, &timeout, 0);
2612 	if (rval) {
2613 		if (rval == EACCES) {
2614 			un->un_dp->type = ST_TYPE_INVALID;
2615 			dp->type = ST_TYPE_INVALID;
2616 			return (1);
2617 		}
2618 		return (0);
2619 	}
2620 	dp->io_timeout = timeout;
2621 
2622 	rval = st_get_timeouts_value(un, SCMD_WRITE, &timeout, 0);
2623 	if (rval) {
2624 		if (rval == EACCES) {
2625 			un->un_dp->type = ST_TYPE_INVALID;
2626 			dp->type = ST_TYPE_INVALID;
2627 			return (1);
2628 		}
2629 		return (0);
2630 	}
2631 	dp->io_timeout = max(dp->io_timeout, timeout);
2632 
2633 	rval = st_get_timeouts_value(un, SCMD_SPACE, &timeout, 0);
2634 	if (rval) {
2635 		if (rval == EACCES) {
2636 			un->un_dp->type = ST_TYPE_INVALID;
2637 			dp->type = ST_TYPE_INVALID;
2638 			return (1);
2639 		}
2640 		return (0);
2641 	}
2642 	dp->space_timeout = timeout;
2643 
2644 	rval = st_get_timeouts_value(un, SCMD_LOAD, &timeout, 0);
2645 	if (rval) {
2646 		if (rval == EACCES) {
2647 			un->un_dp->type = ST_TYPE_INVALID;
2648 			dp->type = ST_TYPE_INVALID;
2649 			return (1);
2650 		}
2651 		return (0);
2652 	}
2653 	dp->load_timeout = timeout;
2654 	dp->unload_timeout = timeout;
2655 
2656 	rval = st_get_timeouts_value(un, SCMD_REWIND, &timeout, 0);
2657 	if (rval) {
2658 		if (rval == EACCES) {
2659 			un->un_dp->type = ST_TYPE_INVALID;
2660 			dp->type = ST_TYPE_INVALID;
2661 			return (1);
2662 		}
2663 		return (0);
2664 	}
2665 	dp->rewind_timeout = timeout;
2666 
2667 	rval = st_get_timeouts_value(un, SCMD_INQUIRY, &timeout, 0);
2668 	if (rval) {
2669 		if (rval == EACCES) {
2670 			un->un_dp->type = ST_TYPE_INVALID;
2671 			dp->type = ST_TYPE_INVALID;
2672 			return (1);
2673 		}
2674 		return (0);
2675 	}
2676 	dp->non_motion_timeout = timeout;
2677 
2678 	return (1);
2679 }
2680 
2681 static int
2682 st_get_timeouts_value(struct scsi_tape *un, uchar_t option_code,
2683     ushort_t *timeout_value, ushort_t service_action)
2684 {
2685 	uchar_t *timeouts;
2686 	uchar_t *oper;
2687 	uchar_t support;
2688 	uchar_t cdbsize;
2689 	uchar_t ctdp;
2690 	size_t buflen;
2691 	int rval;
2692 
2693 	ST_FUNC(ST_DEVINFO, st_get_timeouts_value);
2694 
2695 	buflen = sizeof (struct one_com_des) +
2696 	    sizeof (struct com_timeout_des);
2697 	oper = kmem_zalloc(buflen, KM_SLEEP);
2698 	rval = st_report_supported_operation(un, oper, option_code,
2699 	    service_action);
2700 
2701 	if (rval) {
2702 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2703 		    "st_get_timeouts_value(): "
2704 		    "fail to timeouts value for command %d.\n", option_code);
2705 		kmem_free(oper, buflen);
2706 		return (rval);
2707 	}
2708 
2709 	support = ((struct one_com_des *)oper)->support;
2710 	if ((support != SUPPORT_VALUES_SUPPORT_SCSI) &&
2711 	    (support != SUPPORT_VALUES_SUPPORT_VENDOR)) {
2712 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2713 		    "st_get_timeouts_value(): "
2714 		    "command %d is not supported.\n", option_code);
2715 		kmem_free(oper, buflen);
2716 		return (ENOTSUP);
2717 	}
2718 
2719 	ctdp = ((struct one_com_des *)oper)->ctdp;
2720 	if (!ctdp) {
2721 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2722 		    "st_get_timeouts_value(): "
2723 		    "command timeout is not included.\n");
2724 		kmem_free(oper, buflen);
2725 		return (ENOTSUP);
2726 	}
2727 
2728 	cdbsize = BE_16(((struct one_com_des *)oper)->cdb_size);
2729 	timeouts = (uchar_t *)(oper + cdbsize + 4);
2730 
2731 	/*
2732 	 * Timeout value in seconds is 4 bytes, but we only support the lower 2
2733 	 * bytes. If the higher 2 bytes are not zero, the timeout value is set
2734 	 * to 0xFFFF.
2735 	 */
2736 	if (*(timeouts + 8) != 0 || *(timeouts + 9) != 0) {
2737 		*timeout_value = USHRT_MAX;
2738 	} else {
2739 		*timeout_value = ((*(timeouts + 10)) << 8) |
2740 		    (*(timeouts + 11));
2741 	}
2742 
2743 	kmem_free(oper, buflen);
2744 	return (0);
2745 }
2746 
2747 static int
2748 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2749 {
2750 	int i;
2751 
2752 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2753 
2754 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2755 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2756 
2757 	/*
2758 	 * Make up a name
2759 	 */
2760 	bcopy("Vendor '", dp->name, 8);
2761 	bcopy(vidpid, &dp->name[8], VIDLEN);
2762 	bcopy("' Product '", &dp->name[16], 11);
2763 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2764 	dp->name[ST_NAMESIZE - 2] = '\'';
2765 	dp->name[ST_NAMESIZE - 1] = '\0';
2766 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2767 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2768 	/*
2769 	 * 'clean' vendor and product strings of non-printing chars
2770 	 */
2771 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2772 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2773 			dp->name[i] = '.';
2774 		}
2775 	}
2776 	dp->type = ST_TYPE_INVALID;
2777 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2778 
2779 	return (1); /* Can Not Fail */
2780 }
2781 
2782 /*
2783  * Regular Unix Entry points
2784  */
2785 
2786 
2787 
2788 /* ARGSUSED */
2789 static int
2790 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2791 {
2792 	dev_t dev = *dev_p;
2793 	int rval = 0;
2794 
2795 	GET_SOFT_STATE(dev);
2796 
2797 	ST_ENTR(ST_DEVINFO, st_open);
2798 
2799 	/*
2800 	 * validate that we are addressing a sensible unit
2801 	 */
2802 	mutex_enter(ST_MUTEX);
2803 
2804 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2805 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2806 	    st_dev_name(dev), *dev_p, flag, otyp);
2807 
2808 	/*
2809 	 * All device accesss go thru st_strategy() where we check
2810 	 * suspend status
2811 	 */
2812 
2813 	if (!un->un_attached) {
2814 		st_known_tape_type(un);
2815 		if (!un->un_attached) {
2816 			rval = ENXIO;
2817 			goto exit;
2818 		}
2819 
2820 	}
2821 
2822 	/*
2823 	 * Check for the case of the tape in the middle of closing.
2824 	 * This isn't simply a check of the current state, because
2825 	 * we could be in state of sensing with the previous state
2826 	 * that of closing.
2827 	 *
2828 	 * And don't allow multiple opens.
2829 	 */
2830 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2831 		un->un_laststate = un->un_state;
2832 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2833 		while (IS_CLOSING(un) ||
2834 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2835 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2836 				rval = EINTR;
2837 				un->un_state = un->un_laststate;
2838 				goto exit;
2839 			}
2840 		}
2841 	} else if (un->un_state != ST_STATE_CLOSED) {
2842 		rval = EBUSY;
2843 		goto busy;
2844 	}
2845 
2846 	/*
2847 	 * record current dev
2848 	 */
2849 	un->un_dev = dev;
2850 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2851 	un->un_errno = 0;	/* no errors yet */
2852 	un->un_restore_pos = 0;
2853 	un->un_rqs_state = 0;
2854 
2855 	/*
2856 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2857 	 * anything, leave internal states alone, if fileno >= 0
2858 	 */
2859 	if (flag & (FNDELAY | FNONBLOCK)) {
2860 		switch (un->un_pos.pmode) {
2861 
2862 		case invalid:
2863 			un->un_state = ST_STATE_OFFLINE;
2864 			break;
2865 
2866 		case legacy:
2867 			/*
2868 			 * If position is anything other than rewound.
2869 			 */
2870 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2871 				/*
2872 				 * set un_read_only/write-protect status.
2873 				 *
2874 				 * If the tape is not bot we can assume
2875 				 * that mspl->wp_status is set properly.
2876 				 * else
2877 				 * we need to do a mode sense/Tur once
2878 				 * again to get the actual tape status.(since
2879 				 * user might have replaced the tape)
2880 				 * Hence make the st state OFFLINE so that
2881 				 * we re-intialize the tape once again.
2882 				 */
2883 				un->un_read_only =
2884 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2885 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2886 			} else {
2887 				un->un_state = ST_STATE_OFFLINE;
2888 			}
2889 			break;
2890 		case logical:
2891 			if (un->un_pos.lgclblkno == 0) {
2892 				un->un_state = ST_STATE_OFFLINE;
2893 			} else {
2894 				un->un_read_only =
2895 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2896 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2897 			}
2898 			break;
2899 		}
2900 		rval = 0;
2901 	} else {
2902 		/*
2903 		 * Not opening O_NDELAY.
2904 		 */
2905 		un->un_state = ST_STATE_OPENING;
2906 
2907 		/*
2908 		 * Clear error entry stack
2909 		 */
2910 		st_empty_error_stack(un);
2911 
2912 		rval = st_tape_init(un);
2913 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2914 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2915 			rval = 0; /* so open doesn't fail */
2916 		} else if (rval) {
2917 			/*
2918 			 * Release the tape unit, if reserved and not
2919 			 * preserve reserve.
2920 			 */
2921 			if ((un->un_rsvd_status &
2922 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2923 				(void) st_reserve_release(un, ST_RELEASE,
2924 				    st_uscsi_cmd);
2925 			}
2926 		} else {
2927 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2928 		}
2929 	}
2930 
2931 exit:
2932 	/*
2933 	 * we don't want any uninvited guests scrogging our data when we're
2934 	 * busy with something, so for successful opens or failed opens
2935 	 * (except for EBUSY), reset these counters and state appropriately.
2936 	 */
2937 	if (rval != EBUSY) {
2938 		if (rval) {
2939 			un->un_state = ST_STATE_CLOSED;
2940 		}
2941 		un->un_err_resid = 0;
2942 		un->un_retry_ct = 0;
2943 	}
2944 busy:
2945 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2946 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2947 	mutex_exit(ST_MUTEX);
2948 	return (rval);
2949 
2950 }
2951 
2952 static int
2953 st_tape_init(struct scsi_tape *un)
2954 {
2955 	int err;
2956 	int rval = 0;
2957 
2958 	ST_FUNC(ST_DEVINFO, st_tape_init);
2959 
2960 	ASSERT(mutex_owned(ST_MUTEX));
2961 
2962 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2963 	    "st_tape_init(un = 0x%p, oflags = %d)\n", (void*)un, un->un_oflags);
2964 
2965 	/*
2966 	 * Clean up after any errors left by 'last' close.
2967 	 * This also handles the case of the initial open.
2968 	 */
2969 	if (un->un_state != ST_STATE_INITIALIZING) {
2970 		un->un_laststate = un->un_state;
2971 		un->un_state = ST_STATE_OPENING;
2972 	}
2973 
2974 	un->un_kbytes_xferred = 0;
2975 
2976 	/*
2977 	 * do a throw away TUR to clear check condition
2978 	 */
2979 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2980 
2981 	/*
2982 	 * If test unit ready fails because the drive is reserved
2983 	 * by another host fail the open for no access.
2984 	 */
2985 	if (err) {
2986 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2987 			un->un_state = ST_STATE_CLOSED;
2988 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2989 			    "st_tape_init: RESERVATION CONFLICT\n");
2990 			rval = EACCES;
2991 			goto exit;
2992 		} else if ((un->un_rsvd_status &
2993 		    ST_APPLICATION_RESERVATIONS) != 0) {
2994 			if ((ST_RQSENSE != NULL) &&
2995 			    (ST_RQSENSE->es_add_code == 0x2a &&
2996 			    ST_RQSENSE->es_qual_code == 0x03)) {
2997 				un->un_state = ST_STATE_CLOSED;
2998 				rval = EACCES;
2999 				goto exit;
3000 			}
3001 		}
3002 	}
3003 
3004 	/*
3005 	 * Tape self identification could fail if the tape drive is used by
3006 	 * another host during attach time. We try to get the tape type
3007 	 * again. This is also applied to any posponed configuration methods.
3008 	 */
3009 	if (un->un_dp->type == ST_TYPE_INVALID) {
3010 		un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
3011 		st_known_tape_type(un);
3012 	}
3013 
3014 	/*
3015 	 * If the tape type is still invalid, try to determine the generic
3016 	 * configuration.
3017 	 */
3018 	if (un->un_dp->type == ST_TYPE_INVALID) {
3019 		rval = st_determine_generic(un);
3020 		if (rval) {
3021 			if (rval != EACCES) {
3022 				rval = EIO;
3023 			}
3024 			un->un_state = ST_STATE_CLOSED;
3025 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3026 			    "st_tape_init: %s invalid type\n",
3027 			    rval == EACCES ? "EACCES" : "EIO");
3028 			goto exit;
3029 		}
3030 		/*
3031 		 * If this is a Unknown Type drive,
3032 		 * Use the READ BLOCK LIMITS to determine if
3033 		 * allow large xfer is approprate if not globally
3034 		 * disabled with st_allow_large_xfer.
3035 		 */
3036 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
3037 	} else {
3038 
3039 		/*
3040 		 * If we allow_large_xfer (ie >64k) and have not yet found out
3041 		 * the max block size supported by the drive,
3042 		 * find it by issueing a READ_BLKLIM command.
3043 		 * if READ_BLKLIM cmd fails, assume drive doesn't
3044 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
3045 		 */
3046 		un->un_allow_large_xfer = st_allow_large_xfer &&
3047 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
3048 	}
3049 	/*
3050 	 * if maxbsize is unknown, set the maximum block size.
3051 	 */
3052 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
3053 
3054 		/*
3055 		 * Get the Block limits of the tape drive.
3056 		 * if un->un_allow_large_xfer = 0 , then make sure
3057 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
3058 		 */
3059 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
3060 
3061 		err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3062 		if (err) {
3063 			/* Retry */
3064 			err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3065 		}
3066 		if (!err) {
3067 
3068 			/*
3069 			 * if cmd successful, use limit returned
3070 			 */
3071 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
3072 			    (un->un_rbl->max_mid << 8) +
3073 			    un->un_rbl->max_lo;
3074 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
3075 			    un->un_rbl->min_lo;
3076 			un->un_data_mod = 1 << un->un_rbl->granularity;
3077 			if ((un->un_maxbsize == 0) ||
3078 			    (un->un_allow_large_xfer == 0 &&
3079 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
3080 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3081 
3082 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
3083 				/*
3084 				 * Drive is not one that is configured, But the
3085 				 * READ BLOCK LIMITS tells us it can do large
3086 				 * xfers.
3087 				 */
3088 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
3089 					un->un_dp->options |=
3090 					    ST_NO_RECSIZE_LIMIT;
3091 				}
3092 				/*
3093 				 * If max and mimimum block limits are the
3094 				 * same this is a fixed block size device.
3095 				 */
3096 				if (un->un_maxbsize == un->un_minbsize) {
3097 					un->un_dp->options &= ~ST_VARIABLE;
3098 				}
3099 			}
3100 
3101 			if (un->un_minbsize == 0) {
3102 				un->un_minbsize = 1;
3103 			}
3104 
3105 		} else { /* error on read block limits */
3106 
3107 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3108 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
3109 			    " errno = %d un_rsvd_status = 0x%X\n",
3110 			    err, un->un_rsvd_status);
3111 
3112 			/*
3113 			 * since read block limits cmd failed,
3114 			 * do not allow large xfers.
3115 			 * use old values in st_minphys
3116 			 */
3117 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
3118 				rval = EACCES;
3119 			} else {
3120 				un->un_allow_large_xfer = 0;
3121 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3122 				    "!Disabling large transfers\n");
3123 
3124 				/*
3125 				 * we guess maxbsize and minbsize
3126 				 */
3127 				if (un->un_bsize) {
3128 					un->un_maxbsize = un->un_minbsize =
3129 					    un->un_bsize;
3130 				} else {
3131 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3132 					un->un_minbsize = 1;
3133 				}
3134 				/*
3135 				 * Data Mod must be set,
3136 				 * Even if read block limits fails.
3137 				 * Prevents Divide By Zero in st_rw().
3138 				 */
3139 				un->un_data_mod = 1;
3140 			}
3141 		}
3142 		if (un->un_rbl) {
3143 			kmem_free(un->un_rbl, RBLSIZE);
3144 			un->un_rbl = NULL;
3145 		}
3146 
3147 		if (rval) {
3148 			goto exit;
3149 		}
3150 	}
3151 
3152 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3153 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
3154 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
3155 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
3156 
3157 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
3158 
3159 	if (err != 0) {
3160 		if (err == EINTR) {
3161 			un->un_laststate = un->un_state;
3162 			un->un_state = ST_STATE_CLOSED;
3163 			rval = EINTR;
3164 			goto exit;
3165 		}
3166 		/*
3167 		 * Make sure the tape is ready
3168 		 */
3169 		un->un_pos.pmode = invalid;
3170 		if (un->un_status != KEY_UNIT_ATTENTION) {
3171 			/*
3172 			 * allow open no media.  Subsequent MTIOCSTATE
3173 			 * with media present will complete the open
3174 			 * logic.
3175 			 */
3176 			un->un_laststate = un->un_state;
3177 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
3178 				un->un_mediastate = MTIO_EJECTED;
3179 				un->un_state = ST_STATE_OFFLINE;
3180 				rval = 0;
3181 				goto exit;
3182 			} else {
3183 				un->un_state = ST_STATE_CLOSED;
3184 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3185 				    "st_tape_init EIO no media, not opened "
3186 				    "O_NONBLOCK|O_EXCL\n");
3187 				rval = EIO;
3188 				goto exit;
3189 			}
3190 		}
3191 	}
3192 
3193 	/*
3194 	 * On each open, initialize block size from drivetype struct,
3195 	 * as it could have been changed by MTSRSZ ioctl.
3196 	 * Now, ST_VARIABLE simply means drive is capable of variable
3197 	 * mode. All drives are assumed to support fixed records.
3198 	 * Hence, un_bsize tells what mode the drive is in.
3199 	 *	un_bsize	= 0	- variable record length
3200 	 *			= x	- fixed record length is x
3201 	 */
3202 	un->un_bsize = un->un_dp->bsize;
3203 
3204 	/*
3205 	 * If saved position is valid go there
3206 	 */
3207 	if (un->un_restore_pos) {
3208 		un->un_restore_pos = 0;
3209 		un->un_pos.fileno = un->un_save_fileno;
3210 		un->un_pos.blkno = un->un_save_blkno;
3211 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &un->un_pos);
3212 		if (rval != 0) {
3213 			if (rval != EACCES) {
3214 				rval = EIO;
3215 			}
3216 			un->un_laststate = un->un_state;
3217 			un->un_state = ST_STATE_CLOSED;
3218 			goto exit;
3219 		}
3220 	}
3221 
3222 	if (un->un_pos.pmode == invalid) {
3223 		rval = st_loadtape(un);
3224 		if (rval) {
3225 			if (rval != EACCES) {
3226 				rval = EIO;
3227 			}
3228 			un->un_laststate = un->un_state;
3229 			un->un_state = ST_STATE_CLOSED;
3230 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3231 			    "st_tape_init: %s can't open tape\n",
3232 			    rval == EACCES ? "EACCES" : "EIO");
3233 			goto exit;
3234 		}
3235 	}
3236 
3237 	/*
3238 	 * do a mode sense to pick up state of current write-protect,
3239 	 * Could cause reserve and fail due to conflict.
3240 	 */
3241 	if (un->un_unit_attention_flags) {
3242 		rval = st_modesense(un);
3243 		if (rval == EACCES) {
3244 			goto exit;
3245 		}
3246 	}
3247 
3248 	/*
3249 	 * If we are opening the tape for writing, check
3250 	 * to make sure that the tape can be written.
3251 	 */
3252 	if (un->un_oflags & FWRITE) {
3253 		err = 0;
3254 		if (un->un_mspl->wp) {
3255 			un->un_status = KEY_WRITE_PROTECT;
3256 			un->un_laststate = un->un_state;
3257 			un->un_state = ST_STATE_CLOSED;
3258 			rval = EACCES;
3259 			/*
3260 			 * STK sets the wp bit if volsafe tape is loaded.
3261 			 */
3262 			if ((un->un_dp->type == MT_ISSTK9840) &&
3263 			    (un->un_dp->options & ST_WORMABLE)) {
3264 				un->un_read_only = RDONLY;
3265 			} else {
3266 				goto exit;
3267 			}
3268 		} else {
3269 			un->un_read_only = RDWR;
3270 		}
3271 	} else {
3272 		un->un_read_only = RDONLY;
3273 	}
3274 
3275 	if (un->un_dp->options & ST_WORMABLE &&
3276 	    un->un_unit_attention_flags) {
3277 		un->un_read_only |= un->un_wormable(un);
3278 
3279 		if (((un->un_read_only == WORM) ||
3280 		    (un->un_read_only == RDWORM)) &&
3281 		    ((un->un_oflags & FWRITE) == FWRITE)) {
3282 			un->un_status = KEY_DATA_PROTECT;
3283 			rval = EACCES;
3284 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3285 			    "read_only = %d eof = %d oflag = %d\n",
3286 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3287 		}
3288 	}
3289 
3290 	/*
3291 	 * If we're opening the tape write-only, we need to
3292 	 * write 2 filemarks on the HP 1/2 inch drive, to
3293 	 * create a null file.
3294 	 */
3295 	if ((un->un_read_only == RDWR) ||
3296 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3297 		if (un->un_dp->options & ST_REEL) {
3298 			un->un_fmneeded = 2;
3299 		} else {
3300 			un->un_fmneeded = 1;
3301 		}
3302 	} else {
3303 		un->un_fmneeded = 0;
3304 	}
3305 
3306 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3307 	    "fmneeded = %x\n", un->un_fmneeded);
3308 
3309 	/*
3310 	 * Make sure the density can be selected correctly.
3311 	 * If WORM can only write at the append point which in most cases
3312 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3313 	 * to set and try densities if a BOP.
3314 	 */
3315 	if (st_determine_density(un,
3316 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3317 		un->un_status = KEY_ILLEGAL_REQUEST;
3318 		un->un_laststate = un->un_state;
3319 		un->un_state = ST_STATE_CLOSED;
3320 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3321 		    "st_tape_init: EIO can't determine density\n");
3322 		rval = EIO;
3323 		goto exit;
3324 	}
3325 
3326 	/*
3327 	 * Destroy the knowledge that we have 'determined'
3328 	 * density so that a later read at BOT comes along
3329 	 * does the right density determination.
3330 	 */
3331 
3332 	un->un_density_known = 0;
3333 
3334 
3335 	/*
3336 	 * Okay, the tape is loaded and either at BOT or somewhere past.
3337 	 * Mark the state such that any I/O or tape space operations
3338 	 * will get/set the right density, etc..
3339 	 */
3340 	un->un_laststate = un->un_state;
3341 	un->un_lastop = ST_OP_NIL;
3342 	un->un_mediastate = MTIO_INSERTED;
3343 	cv_broadcast(&un->un_state_cv);
3344 
3345 	/*
3346 	 *  Set test append flag if writing.
3347 	 *  First write must check that tape is positioned correctly.
3348 	 */
3349 	un->un_test_append = (un->un_oflags & FWRITE);
3350 
3351 	/*
3352 	 * if there are pending unit attention flags.
3353 	 * Check that the media has not changed.
3354 	 */
3355 	if (un->un_unit_attention_flags) {
3356 		rval = st_get_media_identification(un, st_uscsi_cmd);
3357 		if (rval != 0 && rval != EACCES) {
3358 			rval = EIO;
3359 		}
3360 		un->un_unit_attention_flags = 0;
3361 	}
3362 
3363 exit:
3364 	un->un_err_resid = 0;
3365 	un->un_last_resid = 0;
3366 	un->un_last_count = 0;
3367 
3368 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3369 	    "st_tape_init: return val = %x\n", rval);
3370 	return (rval);
3371 
3372 }
3373 
3374 
3375 
3376 /* ARGSUSED */
3377 static int
3378 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3379 {
3380 	int err = 0;
3381 	int count, last_state;
3382 	minor_t minor = getminor(dev);
3383 #ifdef	__x86
3384 	struct contig_mem *cp, *cp_temp;
3385 #endif
3386 
3387 	GET_SOFT_STATE(dev);
3388 
3389 	ST_ENTR(ST_DEVINFO, st_close);
3390 
3391 	/*
3392 	 * wait till all cmds in the pipeline have been completed
3393 	 */
3394 	mutex_enter(ST_MUTEX);
3395 
3396 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3397 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3398 
3399 	st_wait_for_io(un);
3400 
3401 	/* turn off persistent errors on close, as we want close to succeed */
3402 	st_turn_pe_off(un);
3403 
3404 	/*
3405 	 * set state to indicate that we are in process of closing
3406 	 */
3407 	last_state = un->un_laststate = un->un_state;
3408 	un->un_state = ST_STATE_CLOSING;
3409 
3410 	ST_POS(ST_DEVINFO, "st_close1:", &un->un_pos);
3411 
3412 	/*
3413 	 * BSD behavior:
3414 	 * a close always causes a silent span to the next file if we've hit
3415 	 * an EOF (but not yet read across it).
3416 	 */
3417 	if ((minor & MT_BSD) && (un->un_pos.eof == ST_EOF)) {
3418 		if (un->un_pos.pmode != invalid) {
3419 			un->un_pos.fileno++;
3420 			un->un_pos.blkno = 0;
3421 		}
3422 		un->un_pos.eof = ST_NO_EOF;
3423 	}
3424 
3425 	/*
3426 	 * SVR4 behavior for skipping to next file:
3427 	 *
3428 	 * If we have not seen a filemark, space to the next file
3429 	 *
3430 	 * If we have already seen the filemark we are physically in the next
3431 	 * file and we only increment the filenumber
3432 	 */
3433 	if (((minor & (MT_BSD | MT_NOREWIND)) == MT_NOREWIND) &&
3434 	    (flag & FREAD) &&		/* reading or at least asked to */
3435 	    (un->un_mediastate == MTIO_INSERTED) &&	/* tape loaded */
3436 	    (un->un_pos.pmode != invalid) &&		/* XXX position known */
3437 	    ((un->un_pos.blkno != 0) && 		/* inside a file */
3438 	    (un->un_lastop != ST_OP_WRITE) &&		/* Didn't just write */
3439 	    (un->un_lastop != ST_OP_WEOF))) {		/* or write filemarks */
3440 		switch (un->un_pos.eof) {
3441 		case ST_NO_EOF:
3442 			/*
3443 			 * if we were reading and did not read the complete file
3444 			 * skip to the next file, leaving the tape correctly
3445 			 * positioned to read the first record of the next file
3446 			 * Check first for REEL if we are at EOT by trying to
3447 			 * read a block
3448 			 */
3449 			if ((un->un_dp->options & ST_REEL) &&
3450 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3451 			    (un->un_pos.blkno == 0)) {
3452 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3453 					ST_DEBUG2(ST_DEVINFO, st_label,
3454 					    SCSI_DEBUG,
3455 					    "st_close : EIO can't space\n");
3456 					err = EIO;
3457 					goto error_out;
3458 				}
3459 				if (un->un_pos.eof >= ST_EOF_PENDING) {
3460 					un->un_pos.eof = ST_EOT_PENDING;
3461 					un->un_pos.fileno += 1;
3462 					un->un_pos.blkno   = 0;
3463 					break;
3464 				}
3465 			}
3466 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3467 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3468 				    "st_close: EIO can't space #2\n");
3469 				err = EIO;
3470 				goto error_out;
3471 			} else {
3472 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3473 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3474 				    un->un_pos.fileno, un->un_pos.blkno,
3475 				    un->un_pos.eof);
3476 				un->un_pos.eof = ST_NO_EOF;
3477 			}
3478 			break;
3479 
3480 		case ST_EOF_PENDING:
3481 		case ST_EOF:
3482 			un->un_pos.fileno += 1;
3483 			un->un_pos.lgclblkno += 1;
3484 			un->un_pos.blkno   = 0;
3485 			un->un_pos.eof = ST_NO_EOF;
3486 			break;
3487 
3488 		case ST_EOT:
3489 		case ST_EOT_PENDING:
3490 		case ST_EOM:
3491 			/* nothing to do */
3492 			break;
3493 		default:
3494 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
3495 			    "Undefined state 0x%x", un->un_pos.eof);
3496 
3497 		}
3498 	}
3499 
3500 
3501 	/*
3502 	 * For performance reasons (HP 88780), the driver should
3503 	 * postpone writing the second tape mark until just before a file
3504 	 * positioning ioctl is issued (e.g., rewind).	This means that
3505 	 * the user must not manually rewind the tape because the tape will
3506 	 * be missing the second tape mark which marks EOM.
3507 	 * However, this small performance improvement is not worth the risk.
3508 	 */
3509 
3510 	/*
3511 	 * We need to back up over the filemark we inadvertently popped
3512 	 * over doing a read in between the two filemarks that constitute
3513 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3514 	 * set while reading.
3515 	 *
3516 	 * If we happen to be at physical eot (ST_EOM) (writing case),
3517 	 * the writing of filemark(s) will clear the ST_EOM state, which
3518 	 * we don't want, so we save this state and restore it later.
3519 	 */
3520 
3521 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3522 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3523 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3524 
3525 	if (un->un_pos.eof == ST_EOT_PENDING) {
3526 		if (minor & MT_NOREWIND) {
3527 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3528 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3529 				    "st_close: EIO can't space #3\n");
3530 				err = EIO;
3531 				goto error_out;
3532 			} else {
3533 				un->un_pos.blkno = 0;
3534 				un->un_pos.eof = ST_EOT;
3535 			}
3536 		} else {
3537 			un->un_pos.eof = ST_NO_EOF;
3538 		}
3539 
3540 	/*
3541 	 * Do we need to write a file mark?
3542 	 *
3543 	 * only write filemarks if there are fmks to be written and
3544 	 *   - open for write (possibly read/write)
3545 	 *   - the last operation was a write
3546 	 * or:
3547 	 *   -	opened for wronly
3548 	 *   -	no data was written
3549 	 */
3550 	} else if ((un->un_pos.pmode != invalid) &&
3551 	    (un->un_fmneeded > 0) &&
3552 	    (((flag & FWRITE) &&
3553 	    ((un->un_lastop == ST_OP_WRITE)||(un->un_lastop == ST_OP_WEOF))) ||
3554 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3555 
3556 		/* save ST_EOM state */
3557 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3558 
3559 		/*
3560 		 * Note that we will write a filemark if we had opened
3561 		 * the tape write only and no data was written, thus
3562 		 * creating a null file.
3563 		 *
3564 		 * If the user already wrote one, we only have to write 1 more.
3565 		 * If they wrote two, we don't have to write any.
3566 		 */
3567 
3568 		count = un->un_fmneeded;
3569 		if (count > 0) {
3570 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, count, SYNC_CMD)) {
3571 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3572 				    "st_close : EIO can't wfm\n");
3573 				err = EIO;
3574 				goto error_out;
3575 			}
3576 			if ((un->un_dp->options & ST_REEL) &&
3577 			    (minor & MT_NOREWIND)) {
3578 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3579 					ST_DEBUG2(ST_DEVINFO, st_label,
3580 					    SCSI_DEBUG,
3581 					    "st_close : EIO space fmk(-1)\n");
3582 					err = EIO;
3583 					goto error_out;
3584 				}
3585 				un->un_pos.eof = ST_NO_EOF;
3586 				/* fix up block number */
3587 				un->un_pos.blkno = 0;
3588 			}
3589 		}
3590 
3591 		/*
3592 		 * If we aren't going to be rewinding, and we were at
3593 		 * physical eot, restore the state that indicates we
3594 		 * are at physical eot. Once you have reached physical
3595 		 * eot, and you close the tape, the only thing you can
3596 		 * do on the next open is to rewind. Access to trailer
3597 		 * records is only allowed without closing the device.
3598 		 */
3599 		if ((minor & MT_NOREWIND) == 0 && was_at_eom) {
3600 			un->un_pos.eof = ST_EOM;
3601 		}
3602 	}
3603 
3604 	/*
3605 	 * report soft errors if enabled and available, if we never accessed
3606 	 * the drive, don't get errors. This will prevent some DAT error
3607 	 * messages upon LOG SENSE.
3608 	 */
3609 	if (st_report_soft_errors_on_close &&
3610 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3611 	    (last_state != ST_STATE_OFFLINE)) {
3612 		if (st_report_soft_errors(dev, flag)) {
3613 			err = EIO;
3614 			goto error_out;
3615 		}
3616 	}
3617 
3618 
3619 	/*
3620 	 * Do we need to rewind? Can we rewind?
3621 	 */
3622 	if ((minor & MT_NOREWIND) == 0 &&
3623 	    un->un_pos.pmode != invalid && err == 0) {
3624 		/*
3625 		 * We'd like to rewind with the
3626 		 * 'immediate' bit set, but this
3627 		 * causes problems on some drives
3628 		 * where subsequent opens get a
3629 		 * 'NOT READY' error condition
3630 		 * back while the tape is rewinding,
3631 		 * which is impossible to distinguish
3632 		 * from the condition of 'no tape loaded'.
3633 		 *
3634 		 * Also, for some targets, if you disconnect
3635 		 * with the 'immediate' bit set, you don't
3636 		 * actually return right away, i.e., the
3637 		 * target ignores your request for immediate
3638 		 * return.
3639 		 *
3640 		 * Instead, we'll fire off an async rewind
3641 		 * command. We'll mark the device as closed,
3642 		 * and any subsequent open will stall on
3643 		 * the first TEST_UNIT_READY until the rewind
3644 		 * completes.
3645 		 */
3646 
3647 		/*
3648 		 * Used to be if reserve was not supported we'd send an
3649 		 * asynchronious rewind. Comments above may be slightly invalid
3650 		 * as the immediate bit was never set. Doing an immedate rewind
3651 		 * makes sense, I think fixes to not ready status might handle
3652 		 * the problems described above.
3653 		 */
3654 		if (un->un_sd->sd_inq->inq_ansi < 2) {
3655 			if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
3656 				err = EIO;
3657 			}
3658 		} else {
3659 			/* flush data for older drives per scsi spec. */
3660 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD)) {
3661 				err = EIO;
3662 			} else {
3663 				/* release the drive before rewind immediate */
3664 				if ((un->un_rsvd_status &
3665 				    (ST_RESERVE | ST_PRESERVE_RESERVE)) ==
3666 				    ST_RESERVE) {
3667 					if (st_reserve_release(un, ST_RELEASE,
3668 					    st_uscsi_cmd)) {
3669 						err = EIO;
3670 					}
3671 				}
3672 
3673 				/* send rewind with immediate bit set */
3674 				if (st_cmd(un, SCMD_REWIND, 1, ASYNC_CMD)) {
3675 					err = EIO;
3676 				}
3677 			}
3678 		}
3679 		/*
3680 		 * Setting positions invalid in case the rewind doesn't
3681 		 * happen. Drives don't like to rewind if resets happen
3682 		 * they will tend to move back to where the rewind was
3683 		 * issued if a reset or something happens so that if a
3684 		 * write happens the data doesn't get clobbered.
3685 		 *
3686 		 * Not a big deal if the position is invalid when the
3687 		 * open occures it will do a read position.
3688 		 */
3689 		un->un_pos.pmode = invalid;
3690 		un->un_running.pmode = invalid;
3691 
3692 		if (err == EIO) {
3693 			goto error_out;
3694 		}
3695 	}
3696 
3697 	/*
3698 	 * eject tape if necessary
3699 	 */
3700 	if (un->un_eject_tape_on_failure) {
3701 		un->un_eject_tape_on_failure = 0;
3702 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3703 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3704 			    "st_close : can't unload tape\n");
3705 			err = EIO;
3706 			goto error_out;
3707 		} else {
3708 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3709 			    "st_close : tape unloaded \n");
3710 			un->un_pos.eof = ST_NO_EOF;
3711 			un->un_mediastate = MTIO_EJECTED;
3712 		}
3713 	}
3714 	/*
3715 	 * Release the tape unit, if default reserve/release
3716 	 * behaviour.
3717 	 */
3718 	if ((un->un_rsvd_status &
3719 	    (ST_RESERVE | ST_PRESERVE_RESERVE |
3720 	    ST_APPLICATION_RESERVATIONS)) == ST_RESERVE) {
3721 		(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
3722 	}
3723 error_out:
3724 	/*
3725 	 * clear up state
3726 	 */
3727 	un->un_laststate = un->un_state;
3728 	un->un_state = ST_STATE_CLOSED;
3729 	un->un_lastop = ST_OP_NIL;
3730 	un->un_throttle = 1;	/* assume one request at time, for now */
3731 	un->un_retry_ct = 0;
3732 	un->un_errno = 0;
3733 	un->un_swr_token = (opaque_t)NULL;
3734 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3735 
3736 	/* Restore the options to the init time settings */
3737 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3738 		un->un_dp->options |= ST_READ_IGNORE_ILI;
3739 	} else {
3740 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3741 	}
3742 
3743 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3744 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3745 	} else {
3746 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3747 	}
3748 
3749 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3750 		un->un_dp->options |= ST_SHORT_FILEMARKS;
3751 	} else {
3752 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3753 	}
3754 
3755 	ASSERT(mutex_owned(ST_MUTEX));
3756 
3757 	/*
3758 	 * Signal anyone awaiting a close operation to complete.
3759 	 */
3760 	cv_signal(&un->un_clscv);
3761 
3762 	/*
3763 	 * any kind of error on closing causes all state to be tossed
3764 	 */
3765 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3766 		/*
3767 		 * note that st_intr has already set
3768 		 * un_pos.pmode to invalid.
3769 		 */
3770 		un->un_density_known = 0;
3771 	}
3772 
3773 #ifdef	__x86
3774 	/*
3775 	 * free any contiguous mem alloc'ed for big block I/O
3776 	 */
3777 	cp = un->un_contig_mem;
3778 	while (cp) {
3779 		if (cp->cm_addr) {
3780 			ddi_dma_mem_free(&cp->cm_acc_hdl);
3781 		}
3782 		cp_temp = cp;
3783 		cp = cp->cm_next;
3784 		kmem_free(cp_temp,
3785 		    sizeof (struct contig_mem) + biosize());
3786 	}
3787 	un->un_contig_mem_total_num = 0;
3788 	un->un_contig_mem_available_num = 0;
3789 	un->un_contig_mem = NULL;
3790 	un->un_max_contig_mem_len = 0;
3791 #endif
3792 
3793 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3794 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3795 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3796 
3797 	mutex_exit(ST_MUTEX);
3798 	return (err);
3799 }
3800 
3801 /*
3802  * These routines perform raw i/o operations.
3803  */
3804 
3805 /* ARGSUSED2 */
3806 static int
3807 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3808 {
3809 #ifdef STDEBUG
3810 	GET_SOFT_STATE(dev);
3811 	ST_ENTR(ST_DEVINFO, st_aread);
3812 #endif
3813 	return (st_arw(dev, aio, B_READ));
3814 }
3815 
3816 
3817 /* ARGSUSED2 */
3818 static int
3819 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3820 {
3821 #ifdef STDEBUG
3822 	GET_SOFT_STATE(dev);
3823 	ST_ENTR(ST_DEVINFO, st_awrite);
3824 #endif
3825 	return (st_arw(dev, aio, B_WRITE));
3826 }
3827 
3828 
3829 
3830 /* ARGSUSED */
3831 static int
3832 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3833 {
3834 #ifdef STDEBUG
3835 	GET_SOFT_STATE(dev);
3836 	ST_ENTR(ST_DEVINFO, st_read);
3837 #endif
3838 	return (st_rw(dev, uiop, B_READ));
3839 }
3840 
3841 /* ARGSUSED */
3842 static int
3843 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3844 {
3845 #ifdef STDEBUG
3846 	GET_SOFT_STATE(dev);
3847 	ST_ENTR(ST_DEVINFO, st_write);
3848 #endif
3849 	return (st_rw(dev, uiop, B_WRITE));
3850 }
3851 
3852 /*
3853  * Due to historical reasons, old limits are: For variable-length devices:
3854  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3855  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3856  * (let it through unmodified. For fixed-length record devices:
3857  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3858  *
3859  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3860  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3861  * command to the drive).
3862  *
3863  */
3864 static void
3865 st_minphys(struct buf *bp)
3866 {
3867 	struct scsi_tape *un;
3868 
3869 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3870 
3871 	ST_FUNC(ST_DEVINFO, st_minphys);
3872 
3873 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3874 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3875 	    bp->b_bcount);
3876 
3877 	if (un->un_allow_large_xfer) {
3878 
3879 		/*
3880 		 * check un_maxbsize for variable length devices only
3881 		 */
3882 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3883 			bp->b_bcount = un->un_maxbsize;
3884 		}
3885 		/*
3886 		 * can't go more that HBA maxdma limit in either fixed-length
3887 		 * or variable-length tape drives.
3888 		 */
3889 		if (bp->b_bcount > un->un_maxdma) {
3890 			bp->b_bcount = un->un_maxdma;
3891 		}
3892 	} else {
3893 
3894 		/*
3895 		 *  use old fixed limits
3896 		 */
3897 		if (un->un_bsize == 0) {
3898 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3899 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3900 			}
3901 		} else {
3902 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3903 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3904 			}
3905 		}
3906 	}
3907 
3908 	/*
3909 	 * For regular raw I/O and Fixed Block length devices, make sure
3910 	 * the adjusted block count is a whole multiple of the device
3911 	 * block size.
3912 	 */
3913 	if (bp != un->un_sbufp && un->un_bsize) {
3914 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3915 	}
3916 }
3917 
3918 static int
3919 st_rw(dev_t dev, struct uio *uio, int flag)
3920 {
3921 	int rval = 0;
3922 	long len;
3923 
3924 	GET_SOFT_STATE(dev);
3925 
3926 	ST_FUNC(ST_DEVINFO, st_rw);
3927 
3928 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3929 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3930 	    (flag == B_READ ? rd_str: wr_str));
3931 
3932 	/* get local copy of transfer length */
3933 	len = uio->uio_iov->iov_len;
3934 
3935 	mutex_enter(ST_MUTEX);
3936 
3937 	/*
3938 	 * Clear error entry stack
3939 	 */
3940 	st_empty_error_stack(un);
3941 
3942 	/*
3943 	 * If in fixed block size mode and requested read or write
3944 	 * is not an even multiple of that block size.
3945 	 */
3946 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3947 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3948 		    "%s: not modulo %d block size\n",
3949 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3950 		rval = EINVAL;
3951 	}
3952 
3953 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3954 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3955 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3956 		    "%s: not modulo %d device granularity\n",
3957 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3958 		rval = EINVAL;
3959 	}
3960 
3961 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
3962 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
3963 		rval = EFAULT;
3964 	}
3965 
3966 	if (rval != 0) {
3967 		un->un_errno = rval;
3968 		mutex_exit(ST_MUTEX);
3969 		return (rval);
3970 	}
3971 
3972 	/*
3973 	 * Reset this so it can be set if Berkeley and read over a filemark.
3974 	 */
3975 	un->un_silent_skip = 0;
3976 	mutex_exit(ST_MUTEX);
3977 
3978 	len = uio->uio_resid;
3979 
3980 	rval = physio(st_queued_strategy, (struct buf *)NULL,
3981 	    dev, flag, st_minphys, uio);
3982 	/*
3983 	 * if we have hit logical EOT during this xfer and there is not a
3984 	 * full residue, then set eof back  to ST_EOM to make sure that
3985 	 * the user will see at least one zero write
3986 	 * after this short write
3987 	 */
3988 	mutex_enter(ST_MUTEX);
3989 	if (un->un_pos.eof > ST_NO_EOF) {
3990 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3991 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3992 	}
3993 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3994 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3995 			un->un_pos.eof = ST_EOM;
3996 		} else if (uio->uio_resid == len) {
3997 			un->un_pos.eof = ST_NO_EOF;
3998 		}
3999 	}
4000 
4001 	if (un->un_silent_skip && uio->uio_resid != len) {
4002 		un->un_pos.eof = ST_EOF;
4003 		un->un_pos.blkno = un->un_save_blkno;
4004 		un->un_pos.fileno--;
4005 	}
4006 
4007 	un->un_errno = rval;
4008 
4009 	mutex_exit(ST_MUTEX);
4010 
4011 	return (rval);
4012 }
4013 
4014 static int
4015 st_arw(dev_t dev, struct aio_req *aio, int flag)
4016 {
4017 	struct uio *uio = aio->aio_uio;
4018 	int rval = 0;
4019 	long len;
4020 
4021 	GET_SOFT_STATE(dev);
4022 
4023 	ST_FUNC(ST_DEVINFO, st_arw);
4024 
4025 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4026 	    "st_arw(dev = 0x%lx, flag = %s)\n", dev,
4027 	    (flag == B_READ ? rd_str: wr_str));
4028 
4029 	/* get local copy of transfer length */
4030 	len = uio->uio_iov->iov_len;
4031 
4032 	mutex_enter(ST_MUTEX);
4033 
4034 	/*
4035 	 * If in fixed block size mode and requested read or write
4036 	 * is not an even multiple of that block size.
4037 	 */
4038 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
4039 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4040 		    "%s: not modulo %d block size\n",
4041 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
4042 		rval = EINVAL;
4043 	}
4044 
4045 	/* If device has set granularity in the READ_BLKLIM we honor it. */
4046 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
4047 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4048 		    "%s: not modulo %d device granularity\n",
4049 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
4050 		rval = EINVAL;
4051 	}
4052 
4053 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
4054 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
4055 		rval = EFAULT;
4056 	}
4057 
4058 	if (rval != 0) {
4059 		un->un_errno = rval;
4060 		mutex_exit(ST_MUTEX);
4061 		return (rval);
4062 	}
4063 
4064 	mutex_exit(ST_MUTEX);
4065 
4066 	len = uio->uio_resid;
4067 
4068 	rval =
4069 	    aphysio(st_queued_strategy, anocancel, dev, flag, st_minphys, aio);
4070 
4071 	/*
4072 	 * if we have hit logical EOT during this xfer and there is not a
4073 	 * full residue, then set eof back  to ST_EOM to make sure that
4074 	 * the user will see at least one zero write
4075 	 * after this short write
4076 	 *
4077 	 * we keep this here just in case the application is not using
4078 	 * persistent errors
4079 	 */
4080 	mutex_enter(ST_MUTEX);
4081 	if (un->un_pos.eof > ST_NO_EOF) {
4082 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4083 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
4084 	}
4085 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
4086 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
4087 			un->un_pos.eof = ST_EOM;
4088 		} else if (uio->uio_resid == len &&
4089 		    !(un->un_persistence && un->un_persist_errors)) {
4090 			un->un_pos.eof = ST_NO_EOF;
4091 		}
4092 	}
4093 	un->un_errno = rval;
4094 	mutex_exit(ST_MUTEX);
4095 
4096 	return (rval);
4097 }
4098 
4099 
4100 
4101 static int
4102 st_queued_strategy(buf_t *bp)
4103 {
4104 	struct scsi_tape *un;
4105 	char reading = bp->b_flags & B_READ;
4106 	int wasopening = 0;
4107 
4108 	/*
4109 	 * validate arguments
4110 	 */
4111 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4112 	if (un == NULL) {
4113 		bp->b_resid = bp->b_bcount;
4114 		bioerror(bp, ENXIO);
4115 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4116 		    "st_queued_strategy: ENXIO error exit\n");
4117 		biodone(bp);
4118 		return (0);
4119 	}
4120 
4121 	ST_ENTR(ST_DEVINFO, st_queued_strategy);
4122 
4123 	mutex_enter(ST_MUTEX);
4124 
4125 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4126 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4127 	}
4128 
4129 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4130 	    "st_queued_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4131 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4132 
4133 	/*
4134 	 * If persistent errors have been flagged, just nix this one. We wait
4135 	 * for any outstanding I/O's below, so we will be in order.
4136 	 */
4137 	if (un->un_persistence && un->un_persist_errors) {
4138 		goto exit;
4139 	}
4140 
4141 	/*
4142 	 * If last command was non queued, wait till it finishes.
4143 	 */
4144 	while (un->un_sbuf_busy) {
4145 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
4146 		/* woke up because of an error */
4147 		if (un->un_persistence && un->un_persist_errors) {
4148 			goto exit;
4149 		}
4150 	}
4151 
4152 	/*
4153 	 * s_buf and recovery commands shouldn't come here.
4154 	 */
4155 	ASSERT(bp != un->un_recov_buf);
4156 	ASSERT(bp != un->un_sbufp);
4157 
4158 	/*
4159 	 * If we haven't done/checked reservation on the tape unit
4160 	 * do it now.
4161 	 */
4162 	if ((un->un_rsvd_status &
4163 	    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
4164 		if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
4165 			if (st_reserve_release(un, ST_RESERVE, st_uscsi_cmd)) {
4166 				st_bioerror(bp, un->un_errno);
4167 				goto exit;
4168 			}
4169 		} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4170 			/*
4171 			 * Enter here to restore position for possible
4172 			 * resets when the device was closed and opened
4173 			 * in O_NDELAY mode subsequently
4174 			 */
4175 			un->un_state = ST_STATE_INITIALIZING;
4176 			(void) st_cmd(un, SCMD_TEST_UNIT_READY,
4177 			    0, SYNC_CMD);
4178 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4179 		}
4180 		un->un_rsvd_status |= ST_INIT_RESERVE;
4181 	}
4182 
4183 	/*
4184 	 * If we are offline, we have to initialize everything first.
4185 	 * This is to handle either when opened with O_NDELAY, or
4186 	 * we just got a new tape in the drive, after an offline.
4187 	 * We don't observe O_NDELAY past the open,
4188 	 * as it will not make sense for tapes.
4189 	 */
4190 	if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
4191 		/*
4192 		 * reset state to avoid recursion
4193 		 */
4194 		un->un_laststate = un->un_state;
4195 		un->un_state = ST_STATE_INITIALIZING;
4196 		if (st_tape_init(un)) {
4197 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4198 			    "stioctl : OFFLINE init failure ");
4199 			un->un_state = ST_STATE_OFFLINE;
4200 			un->un_pos.pmode = invalid;
4201 			goto b_done_err;
4202 		}
4203 		/* un_restore_pos make invalid */
4204 		un->un_state = ST_STATE_OPEN_PENDING_IO;
4205 		un->un_restore_pos = 0;
4206 	}
4207 	/*
4208 	 * Check for legal operations
4209 	 */
4210 	if (un->un_pos.pmode == invalid) {
4211 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4212 		    "strategy with un->un_pos.pmode invalid\n");
4213 		goto b_done_err;
4214 	}
4215 
4216 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4217 	    "st_queued_strategy(): regular io\n");
4218 
4219 	/*
4220 	 * Process this first. If we were reading, and we're pending
4221 	 * logical eot, that means we've bumped one file mark too far.
4222 	 */
4223 
4224 	/*
4225 	 * Recursion warning: st_cmd will route back through here.
4226 	 * Not anymore st_cmd will go through st_strategy()!
4227 	 */
4228 	if (un->un_pos.eof == ST_EOT_PENDING) {
4229 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4230 			un->un_pos.pmode = invalid;
4231 			un->un_density_known = 0;
4232 			goto b_done_err;
4233 		}
4234 		un->un_pos.blkno = 0; /* fix up block number.. */
4235 		un->un_pos.eof = ST_EOT;
4236 	}
4237 
4238 	/*
4239 	 * If we are in the process of opening, we may have to
4240 	 * determine/set the correct density. We also may have
4241 	 * to do a test_append (if QIC) to see whether we are
4242 	 * in a position to append to the end of the tape.
4243 	 *
4244 	 * If we're already at logical eot, we transition
4245 	 * to ST_NO_EOF. If we're at physical eot, we punt
4246 	 * to the switch statement below to handle.
4247 	 */
4248 	if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
4249 	    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
4250 
4251 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4252 			if (st_determine_density(un, (int)reading)) {
4253 				goto b_done_err;
4254 			}
4255 		}
4256 
4257 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4258 		    "pending_io@fileno %d rw %d qic %d eof %d\n",
4259 		    un->un_pos.fileno, (int)reading,
4260 		    (un->un_dp->options & ST_QIC) ? 1 : 0,
4261 		    un->un_pos.eof);
4262 
4263 		if (!reading && un->un_pos.eof != ST_EOM) {
4264 			if (un->un_pos.eof == ST_EOT) {
4265 				un->un_pos.eof = ST_NO_EOF;
4266 			} else if (un->un_pos.pmode != invalid &&
4267 			    (un->un_dp->options & ST_QIC)) {
4268 				/*
4269 				 * st_test_append() will do it all
4270 				 */
4271 				st_test_append(bp);
4272 				mutex_exit(ST_MUTEX);
4273 				return (0);
4274 			}
4275 		}
4276 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4277 			wasopening = 1;
4278 		}
4279 		un->un_laststate = un->un_state;
4280 		un->un_state = ST_STATE_OPEN;
4281 	}
4282 
4283 
4284 	/*
4285 	 * Process rest of END OF FILE and END OF TAPE conditions
4286 	 */
4287 
4288 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4289 	    "eof=%x, wasopening=%x\n",
4290 	    un->un_pos.eof, wasopening);
4291 
4292 	switch (un->un_pos.eof) {
4293 	case ST_EOM:
4294 		/*
4295 		 * This allows writes to proceed past physical
4296 		 * eot. We'll *really* be in trouble if the
4297 		 * user continues blindly writing data too
4298 		 * much past this point (unwind the tape).
4299 		 * Physical eot really means 'early warning
4300 		 * eot' in this context.
4301 		 *
4302 		 * Every other write from now on will succeed
4303 		 * (if sufficient  tape left).
4304 		 * This write will return with resid == count
4305 		 * but the next one should be successful
4306 		 *
4307 		 * Note that we only transition to logical EOT
4308 		 * if the last state wasn't the OPENING state.
4309 		 * We explicitly prohibit running up to physical
4310 		 * eot, closing the device, and then re-opening
4311 		 * to proceed. Trailer records may only be gotten
4312 		 * at by keeping the tape open after hitting eot.
4313 		 *
4314 		 * Also note that ST_EOM cannot be set by reading-
4315 		 * this can only be set during writing. Reading
4316 		 * up to the end of the tape gets a blank check
4317 		 * or a double-filemark indication (ST_EOT_PENDING),
4318 		 * and we prohibit reading after that point.
4319 		 *
4320 		 */
4321 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
4322 		if (wasopening == 0) {
4323 			/*
4324 			 * this allows st_rw() to reset it back to
4325 			 * will see a zero write
4326 			 */
4327 			un->un_pos.eof = ST_WRITE_AFTER_EOM;
4328 		}
4329 		un->un_status = SUN_KEY_EOT;
4330 		goto b_done;
4331 
4332 	case ST_WRITE_AFTER_EOM:
4333 	case ST_EOT:
4334 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
4335 		un->un_status = SUN_KEY_EOT;
4336 		if (SVR4_BEHAVIOR && reading) {
4337 			goto b_done_err;
4338 		}
4339 
4340 		if (reading) {
4341 			goto b_done;
4342 		}
4343 		un->un_pos.eof = ST_NO_EOF;
4344 		break;
4345 
4346 	case ST_EOF_PENDING:
4347 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4348 		    "EOF PENDING\n");
4349 		un->un_status = SUN_KEY_EOF;
4350 		if (SVR4_BEHAVIOR) {
4351 			un->un_pos.eof = ST_EOF;
4352 			goto b_done;
4353 		}
4354 		/* FALLTHROUGH */
4355 	case ST_EOF:
4356 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
4357 		un->un_status = SUN_KEY_EOF;
4358 		if (SVR4_BEHAVIOR) {
4359 			goto b_done_err;
4360 		}
4361 
4362 		if (BSD_BEHAVIOR) {
4363 			un->un_pos.eof = ST_NO_EOF;
4364 			un->un_pos.fileno += 1;
4365 			un->un_pos.blkno   = 0;
4366 		}
4367 
4368 		if (reading) {
4369 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4370 			    "now file %d (read)\n",
4371 			    un->un_pos.fileno);
4372 			goto b_done;
4373 		}
4374 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4375 		    "now file %d (write)\n", un->un_pos.fileno);
4376 		break;
4377 	default:
4378 		un->un_status = 0;
4379 		break;
4380 	}
4381 
4382 	bp->b_flags &= ~(B_DONE);
4383 	st_bioerror(bp, 0);
4384 	bp->av_forw = NULL;
4385 	bp->b_resid = 0;
4386 	SET_BP_PKT(bp, 0);
4387 
4388 
4389 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4390 	    "st_queued_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4391 	    " pkt=0x%p\n",
4392 	    (void *)bp->b_forw, bp->b_bcount,
4393 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4394 
4395 #ifdef	__x86
4396 	/*
4397 	 * We will replace bp with a new bp that can do big blk xfer
4398 	 * if the requested xfer size is bigger than un->un_maxdma_arch
4399 	 *
4400 	 * Also, we need to make sure that we're handling real I/O
4401 	 * by checking group 0/1 SCSI I/O commands, if needed
4402 	 */
4403 	if (bp->b_bcount > un->un_maxdma_arch &&
4404 	    ((uchar_t)(uintptr_t)bp->b_forw == SCMD_READ ||
4405 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G4 ||
4406 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE ||
4407 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G4)) {
4408 		mutex_exit(ST_MUTEX);
4409 		bp = st_get_bigblk_bp(bp);
4410 		mutex_enter(ST_MUTEX);
4411 	}
4412 #endif
4413 
4414 	/* put on wait queue */
4415 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4416 	    "st_queued_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4417 	    (void *)un->un_quef, (void *)bp);
4418 
4419 	st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quel, bp);
4420 
4421 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4422 
4423 	st_start(un);
4424 
4425 	mutex_exit(ST_MUTEX);
4426 	return (0);
4427 
4428 b_done_err:
4429 	st_bioerror(bp, EIO);
4430 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4431 	    "st_queued_strategy : EIO b_done_err\n");
4432 
4433 b_done:
4434 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4435 	    "st_queued_strategy: b_done\n");
4436 
4437 exit:
4438 	/*
4439 	 * make sure no commands are outstanding or waiting before closing,
4440 	 * so we can guarantee order
4441 	 */
4442 	st_wait_for_io(un);
4443 	un->un_err_resid = bp->b_resid = bp->b_bcount;
4444 
4445 	/* override errno here, if persistent errors were flagged */
4446 	if (un->un_persistence && un->un_persist_errors)
4447 		bioerror(bp, un->un_errno);
4448 
4449 	mutex_exit(ST_MUTEX);
4450 
4451 	biodone(bp);
4452 	ASSERT(mutex_owned(ST_MUTEX) == 0);
4453 	return (0);
4454 }
4455 
4456 
4457 static int
4458 st_strategy(struct buf *bp)
4459 {
4460 	struct scsi_tape *un;
4461 
4462 	/*
4463 	 * validate arguments
4464 	 */
4465 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4466 	if (un == NULL) {
4467 		bp->b_resid = bp->b_bcount;
4468 		bioerror(bp, ENXIO);
4469 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4470 		    "st_strategy: ENXIO error exit\n");
4471 
4472 		biodone(bp);
4473 		return (0);
4474 
4475 	}
4476 
4477 	ST_ENTR(ST_DEVINFO, st_strategy);
4478 
4479 	mutex_enter(ST_MUTEX);
4480 
4481 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4482 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4483 	}
4484 
4485 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4486 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4487 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4488 
4489 	ASSERT((bp == un->un_recov_buf) || (bp == un->un_sbufp));
4490 
4491 	bp->b_flags &= ~(B_DONE);
4492 	st_bioerror(bp, 0);
4493 	bp->av_forw = NULL;
4494 	bp->b_resid = 0;
4495 	SET_BP_PKT(bp, 0);
4496 
4497 
4498 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4499 	    "st_strategy: cmd=0x%x  count=%ld  resid=%ld flags=0x%x"
4500 	    " pkt=0x%p\n",
4501 	    (unsigned char)(uintptr_t)bp->b_forw, bp->b_bcount,
4502 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4503 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4504 
4505 	st_start(un);
4506 
4507 	mutex_exit(ST_MUTEX);
4508 	return (0);
4509 }
4510 
4511 /*
4512  * this routine spaces forward over filemarks
4513  */
4514 static int
4515 st_space_fmks(struct scsi_tape *un, int64_t count)
4516 {
4517 	int rval = 0;
4518 
4519 	ST_FUNC(ST_DEVINFO, st_space_fmks);
4520 
4521 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4522 	    "st_space_fmks(dev = 0x%lx, count = %"PRIx64")\n",
4523 	    un->un_dev, count);
4524 
4525 	ASSERT(mutex_owned(ST_MUTEX));
4526 
4527 	/*
4528 	 * the risk with doing only one space operation is that we
4529 	 * may accidentily jump in old data
4530 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4531 	 * because the 8200 does not append a marker; in order not to
4532 	 * sacrifice the fast file skip, we do a slow skip if the low
4533 	 * density device has been opened
4534 	 */
4535 
4536 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4537 	    !((un->un_dp->type == ST_TYPE_EXB8500 &&
4538 	    MT_DENSITY(un->un_dev) == 0))) {
4539 		if (st_cmd(un, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4540 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4541 			    "space_fmks : EIO can't do space cmd #1\n");
4542 			rval = EIO;
4543 		}
4544 	} else {
4545 		while (count > 0) {
4546 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4547 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4548 				    "space_fmks : EIO can't do space cmd #2\n");
4549 				rval = EIO;
4550 				break;
4551 			}
4552 			count -= 1;
4553 			/*
4554 			 * read a block to see if we have reached
4555 			 * end of medium (double filemark for reel or
4556 			 * medium error for others)
4557 			 */
4558 			if (count > 0) {
4559 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
4560 					ST_DEBUG2(ST_DEVINFO, st_label,
4561 					    SCSI_DEBUG,
4562 					    "space_fmks : EIO can't do "
4563 					    "space cmd #3\n");
4564 					rval = EIO;
4565 					break;
4566 				}
4567 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4568 				    (un->un_dp->options & ST_REEL)) {
4569 					un->un_status = SUN_KEY_EOT;
4570 					ST_DEBUG2(ST_DEVINFO, st_label,
4571 					    SCSI_DEBUG,
4572 					    "space_fmks : EIO ST_REEL\n");
4573 					rval = EIO;
4574 					break;
4575 				} else if (IN_EOF(un->un_pos)) {
4576 					un->un_pos.eof = ST_NO_EOF;
4577 					un->un_pos.fileno++;
4578 					un->un_pos.blkno = 0;
4579 					count--;
4580 				} else if (un->un_pos.eof > ST_EOF) {
4581 					ST_DEBUG2(ST_DEVINFO, st_label,
4582 					    SCSI_DEBUG,
4583 					    "space_fmks, EIO > ST_EOF\n");
4584 					rval = EIO;
4585 					break;
4586 				}
4587 
4588 			}
4589 		}
4590 		un->un_err_resid = count;
4591 		COPY_POS(&un->un_pos, &un->un_err_pos);
4592 	}
4593 	ASSERT(mutex_owned(ST_MUTEX));
4594 	return (rval);
4595 }
4596 
4597 /*
4598  * this routine spaces to EOD
4599  *
4600  * it keeps track of the current filenumber and returns the filenumber after
4601  * the last successful space operation, we keep the number high because as
4602  * tapes are getting larger, the possibility of more and more files exist,
4603  * 0x100000 (1 Meg of files) probably will never have to be changed any time
4604  * soon
4605  */
4606 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4607 
4608 static int
4609 st_find_eod(struct scsi_tape *un)
4610 {
4611 	tapepos_t savepos;
4612 	int64_t sp_type;
4613 	int result;
4614 
4615 	if (un == NULL) {
4616 		return (-1);
4617 	}
4618 
4619 	ST_FUNC(ST_DEVINFO, st_find_eod);
4620 
4621 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4622 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", un->un_dev,
4623 	    un->un_pos.fileno);
4624 
4625 	ASSERT(mutex_owned(ST_MUTEX));
4626 
4627 	COPY_POS(&savepos, &un->un_pos);
4628 
4629 	/*
4630 	 * see if the drive is smart enough to do the skips in
4631 	 * one operation; 1/2" use two filemarks
4632 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4633 	 * because the 8200 does not append a marker; in order not to
4634 	 * sacrifice the fast file skip, we do a slow skip if the low
4635 	 * density device has been opened
4636 	 */
4637 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4638 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4639 		    (MT_DENSITY(un->un_dev) == 0)) {
4640 			sp_type = Fmk(1);
4641 		} else if (un->un_pos.pmode == logical) {
4642 			sp_type = SPACE(SP_EOD, 0);
4643 		} else {
4644 			sp_type = Fmk(MAX_SKIP);
4645 		}
4646 	} else {
4647 		sp_type = Fmk(1);
4648 	}
4649 
4650 	for (;;) {
4651 		result = st_cmd(un, SCMD_SPACE, sp_type, SYNC_CMD);
4652 
4653 		if (result == 0) {
4654 			COPY_POS(&savepos, &un->un_pos);
4655 		}
4656 
4657 		if (sp_type == SPACE(SP_EOD, 0)) {
4658 			if (result != 0) {
4659 				sp_type = Fmk(MAX_SKIP);
4660 				continue;
4661 			}
4662 
4663 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4664 			    "st_find_eod: 0x%"PRIx64"\n",
4665 			    savepos.lgclblkno);
4666 			/*
4667 			 * What we return will become the current file position.
4668 			 * After completing the space command with the position
4669 			 * mode that is not invalid a read position command will
4670 			 * be automaticly issued. If the drive support the long
4671 			 * read position format a valid file position can be
4672 			 * returned.
4673 			 */
4674 			return (un->un_pos.fileno);
4675 		}
4676 
4677 		if (result != 0) {
4678 			break;
4679 		}
4680 
4681 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4682 		    "count=%"PRIx64", eof=%x, status=%x\n",
4683 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4684 
4685 		/*
4686 		 * If we're not EOM smart,  space a record
4687 		 * to see whether we're now in the slot between
4688 		 * the two sequential filemarks that logical
4689 		 * EOM consists of (REEL) or hit nowhere land
4690 		 * (8mm).
4691 		 */
4692 		if (sp_type == Fmk(1)) {
4693 			/*
4694 			 * no fast skipping, check a record
4695 			 */
4696 			if (st_cmd(un, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4697 				break;
4698 			}
4699 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4700 			    (un->un_dp->options & ST_REEL)) {
4701 				un->un_status = KEY_BLANK_CHECK;
4702 				un->un_pos.fileno++;
4703 				un->un_pos.blkno = 0;
4704 				break;
4705 			}
4706 			if (IN_EOF(un->un_pos)) {
4707 				un->un_pos.eof = ST_NO_EOF;
4708 				un->un_pos.fileno++;
4709 				un->un_pos.blkno = 0;
4710 			}
4711 			if (un->un_pos.eof > ST_EOF) {
4712 				break;
4713 			}
4714 		} else {
4715 			if (un->un_pos.eof > ST_EOF) {
4716 				break;
4717 			}
4718 		}
4719 	}
4720 
4721 	if (un->un_dp->options & ST_KNOWS_EOD) {
4722 		COPY_POS(&savepos, &un->un_pos);
4723 	}
4724 
4725 	ASSERT(mutex_owned(ST_MUTEX));
4726 
4727 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4728 	    "st_find_eod: %x\n", savepos.fileno);
4729 	return (savepos.fileno);
4730 }
4731 
4732 
4733 /*
4734  * this routine is frequently used in ioctls below;
4735  * it determines whether we know the density and if not will
4736  * determine it
4737  * if we have written the tape before, one or more filemarks are written
4738  *
4739  * depending on the stepflag, the head is repositioned to where it was before
4740  * the filemarks were written in order not to confuse step counts
4741  */
4742 #define	STEPBACK    0
4743 #define	NO_STEPBACK 1
4744 
4745 static int
4746 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4747 {
4748 
4749 	GET_SOFT_STATE(dev);
4750 
4751 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4752 
4753 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4754 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4755 	    "\n", dev, wfm, mode, stepflag);
4756 
4757 	ASSERT(mutex_owned(ST_MUTEX));
4758 
4759 	/*
4760 	 * If we don't yet know the density of the tape we have inserted,
4761 	 * we have to either unconditionally set it (if we're 'writing'),
4762 	 * or we have to determine it. As side effects, check for any
4763 	 * write-protect errors, and for the need to put out any file-marks
4764 	 * before positioning a tape.
4765 	 *
4766 	 * If we are going to be spacing forward, and we haven't determined
4767 	 * the tape density yet, we have to do so now...
4768 	 */
4769 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4770 		if (st_determine_density(un, mode)) {
4771 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4772 			    "check_density_or_wfm : EIO can't determine "
4773 			    "density\n");
4774 			un->un_errno = EIO;
4775 			return (EIO);
4776 		}
4777 		/*
4778 		 * Presumably we are at BOT. If we attempt to write, it will
4779 		 * either work okay, or bomb. We don't do a st_test_append
4780 		 * unless we're past BOT.
4781 		 */
4782 		un->un_laststate = un->un_state;
4783 		un->un_state = ST_STATE_OPEN;
4784 
4785 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4786 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4787 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4788 
4789 		tapepos_t spos;
4790 
4791 		COPY_POS(&spos, &un->un_pos);
4792 
4793 		/*
4794 		 * We need to write one or two filemarks.
4795 		 * In the case of the HP, we need to
4796 		 * position the head between the two
4797 		 * marks.
4798 		 */
4799 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4800 			wfm = un->un_fmneeded;
4801 			un->un_fmneeded = 0;
4802 		}
4803 
4804 		if (st_write_fm(dev, wfm)) {
4805 			un->un_pos.pmode = invalid;
4806 			un->un_density_known = 0;
4807 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4808 			    "check_density_or_wfm : EIO can't write fm\n");
4809 			un->un_errno = EIO;
4810 			return (EIO);
4811 		}
4812 
4813 		if (stepflag == STEPBACK) {
4814 			if (st_cmd(un, SCMD_SPACE, Fmk(-wfm), SYNC_CMD)) {
4815 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4816 				    "check_density_or_wfm : EIO can't space "
4817 				    "(-wfm)\n");
4818 				un->un_errno = EIO;
4819 				return (EIO);
4820 			}
4821 			COPY_POS(&un->un_pos, &spos);
4822 		}
4823 	}
4824 
4825 	/*
4826 	 * Whatever we do at this point clears the state of the eof flag.
4827 	 */
4828 
4829 	un->un_pos.eof = ST_NO_EOF;
4830 
4831 	/*
4832 	 * If writing, let's check that we're positioned correctly
4833 	 * at the end of tape before issuing the next write.
4834 	 */
4835 	if (un->un_read_only == RDWR) {
4836 		un->un_test_append = 1;
4837 	}
4838 
4839 	ASSERT(mutex_owned(ST_MUTEX));
4840 	return (0);
4841 }
4842 
4843 
4844 /*
4845  * Wait for all outstaning I/O's to complete
4846  *
4847  * we wait on both ncmds and the wait queue for times when we are flushing
4848  * after persistent errors are flagged, which is when ncmds can be 0, and the
4849  * queue can still have I/O's.  This way we preserve order of biodone's.
4850  */
4851 static void
4852 st_wait_for_io(struct scsi_tape *un)
4853 {
4854 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4855 	ASSERT(mutex_owned(ST_MUTEX));
4856 	while ((un->un_ncmds) || (un->un_quef) || (un->un_runqf)) {
4857 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4858 	}
4859 }
4860 
4861 /*
4862  * This routine implements the ioctl calls.  It is called
4863  * from the device switch at normal priority.
4864  */
4865 /*ARGSUSED*/
4866 static int
4867 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4868     int *rval_p)
4869 {
4870 	int tmp, rval = 0;
4871 
4872 	GET_SOFT_STATE(dev);
4873 
4874 	ST_ENTR(ST_DEVINFO, st_ioctl);
4875 
4876 	mutex_enter(ST_MUTEX);
4877 
4878 	ASSERT(un->un_recov_buf_busy == 0);
4879 
4880 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4881 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4882 	    "pe_flag = %d\n",
4883 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4884 	    un->un_persistence && un->un_persist_errors);
4885 
4886 	/*
4887 	 * We don't want to block on these, so let them through
4888 	 * and we don't care about setting driver states here.
4889 	 */
4890 	if ((cmd == MTIOCGETDRIVETYPE) ||
4891 	    (cmd == MTIOCGUARANTEEDORDER) ||
4892 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4893 		goto check_commands;
4894 	}
4895 
4896 	/*
4897 	 * We clear error entry stack except command
4898 	 * MTIOCGETERROR and MTIOCGET
4899 	 */
4900 	if ((cmd != MTIOCGETERROR) &&
4901 	    (cmd != MTIOCGET)) {
4902 		st_empty_error_stack(un);
4903 	}
4904 
4905 	/*
4906 	 * wait for all outstanding commands to complete, or be dequeued.
4907 	 * And because ioctl's are synchronous commands, any return value
4908 	 * after this,  will be in order
4909 	 */
4910 	st_wait_for_io(un);
4911 
4912 	/*
4913 	 * allow only a through clear errors and persistent status, and
4914 	 * status
4915 	 */
4916 	if (un->un_persistence && un->un_persist_errors) {
4917 		if ((cmd == MTIOCLRERR) ||
4918 		    (cmd == MTIOCPERSISTENT) ||
4919 		    (cmd == MTIOCGET)) {
4920 			goto check_commands;
4921 		} else {
4922 			rval = un->un_errno;
4923 			goto exit;
4924 		}
4925 	}
4926 
4927 	ASSERT(un->un_throttle != 0);
4928 	un->un_throttle = 1;	/* > 1 will never happen here */
4929 	un->un_errno = 0;	/* start clean from here */
4930 
4931 	/*
4932 	 * first and foremost, handle any ST_EOT_PENDING cases.
4933 	 * That is, if a logical eot is pending notice, notice it.
4934 	 */
4935 	if (un->un_pos.eof == ST_EOT_PENDING) {
4936 		int resid = un->un_err_resid;
4937 		uchar_t status = un->un_status;
4938 		uchar_t lastop = un->un_lastop;
4939 
4940 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4941 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4942 			    "stioctl : EIO can't space fmk(-1)\n");
4943 			rval = EIO;
4944 			goto exit;
4945 		}
4946 		un->un_lastop = lastop; /* restore last operation */
4947 		if (status == SUN_KEY_EOF) {
4948 			un->un_status = SUN_KEY_EOT;
4949 		} else {
4950 			un->un_status = status;
4951 		}
4952 		un->un_err_resid  = resid;
4953 		/* fix up block number */
4954 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4955 		/* now we're at logical eot */
4956 		un->un_pos.eof = ST_EOT;
4957 	}
4958 
4959 	/*
4960 	 * now, handle the rest of the situations
4961 	 */
4962 check_commands:
4963 	switch (cmd) {
4964 	case MTIOCGET:
4965 	{
4966 #ifdef _MULTI_DATAMODEL
4967 		/*
4968 		 * For use when a 32 bit app makes a call into a
4969 		 * 64 bit ioctl
4970 		 */
4971 		struct mtget32		mtg_local32;
4972 		struct mtget32 		*mtget_32 = &mtg_local32;
4973 #endif /* _MULTI_DATAMODEL */
4974 
4975 			/* Get tape status */
4976 		struct mtget mtg_local;
4977 		struct mtget *mtget = &mtg_local;
4978 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4979 		    "st_ioctl: MTIOCGET\n");
4980 
4981 		bzero((caddr_t)mtget, sizeof (struct mtget));
4982 		mtget->mt_erreg = un->un_status;
4983 		mtget->mt_resid = un->un_err_resid;
4984 		mtget->mt_dsreg = un->un_retry_ct;
4985 		if (un->un_err_pos.pmode == legacy) {
4986 			mtget->mt_fileno = un->un_err_pos.fileno;
4987 		} else {
4988 			mtget->mt_fileno = -1;
4989 		}
4990 		/*
4991 		 * If the value is positive fine.
4992 		 * If its negative we need to return a value based on the
4993 		 * old way if counting backwards from INF (1,000,000,000).
4994 		 */
4995 		if (un->un_err_pos.blkno >= 0) {
4996 			mtget->mt_blkno = un->un_err_pos.blkno;
4997 		} else {
4998 			mtget->mt_blkno = INF + 1 - (-un->un_err_pos.blkno);
4999 		}
5000 		mtget->mt_type = un->un_dp->type;
5001 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
5002 		if (un->un_read_pos_type != NO_POS) {
5003 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
5004 		}
5005 		if (un->un_dp->options & ST_REEL) {
5006 			mtget->mt_flags |= MTF_REEL;
5007 			mtget->mt_bf = 20;
5008 		} else {		/* 1/4" cartridges */
5009 			switch (mtget->mt_type) {
5010 			/* Emulex cartridge tape */
5011 			case MT_ISMT02:
5012 				mtget->mt_bf = 40;
5013 				break;
5014 			default:
5015 				mtget->mt_bf = 126;
5016 				break;
5017 			}
5018 		}
5019 
5020 		/*
5021 		 * If large transfers are allowed and drive options
5022 		 * has no record size limit set. Calculate blocking
5023 		 * factor from the lesser of maxbsize and maxdma.
5024 		 */
5025 		if ((un->un_allow_large_xfer) &&
5026 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
5027 			mtget->mt_bf = min(un->un_maxbsize,
5028 			    un->un_maxdma) / SECSIZE;
5029 		}
5030 
5031 		if (un->un_read_only == WORM ||
5032 		    un->un_read_only == RDWORM) {
5033 			mtget->mt_flags |= MTF_WORM_MEDIA;
5034 		}
5035 
5036 		/*
5037 		 * In persistent error mode sending a non-queued can hang
5038 		 * because this ioctl gets to be run without turning off
5039 		 * persistense. Fake the answer based on previous info.
5040 		 */
5041 		if (un->un_persistence) {
5042 			rval = 0;
5043 		} else {
5044 			rval = st_check_clean_bit(un);
5045 		}
5046 		if (rval == 0) {
5047 			/*
5048 			 * If zero is returned or in persistent mode,
5049 			 * use the old data.
5050 			 */
5051 			if ((un->un_HeadClean & (TAPE_ALERT_SUPPORTED |
5052 			    TAPE_SEQUENTIAL_SUPPORTED|TAPE_ALERT_NOT_SUPPORTED))
5053 			    != TAPE_ALERT_NOT_SUPPORTED) {
5054 				mtget->mt_flags |= MTF_TAPE_CLN_SUPPORTED;
5055 			}
5056 			if (un->un_HeadClean & (TAPE_PREVIOUSLY_DIRTY |
5057 			    TAPE_ALERT_STILL_DIRTY)) {
5058 				mtget->mt_flags |= MTF_TAPE_HEAD_DIRTY;
5059 			}
5060 		} else {
5061 			mtget->mt_flags |= (ushort_t)rval;
5062 			rval = 0;
5063 		}
5064 
5065 		un->un_status = 0;		/* Reset status */
5066 		un->un_err_resid = 0;
5067 		tmp = sizeof (struct mtget);
5068 
5069 #ifdef _MULTI_DATAMODEL
5070 
5071 		switch (ddi_model_convert_from(flag & FMODELS)) {
5072 		case DDI_MODEL_ILP32:
5073 			/*
5074 			 * Convert 64 bit back to 32 bit before doing
5075 			 * copyout. This is what the ILP32 app expects.
5076 			 */
5077 			mtget_32->mt_erreg = 	mtget->mt_erreg;
5078 			mtget_32->mt_resid = 	mtget->mt_resid;
5079 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
5080 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
5081 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
5082 			mtget_32->mt_type =  	mtget->mt_type;
5083 			mtget_32->mt_flags = 	mtget->mt_flags;
5084 			mtget_32->mt_bf = 	mtget->mt_bf;
5085 
5086 			if (ddi_copyout(mtget_32, (void *)arg,
5087 			    sizeof (struct mtget32), flag)) {
5088 				rval = EFAULT;
5089 			}
5090 			break;
5091 
5092 		case DDI_MODEL_NONE:
5093 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5094 				rval = EFAULT;
5095 			}
5096 			break;
5097 		}
5098 #else /* ! _MULTI_DATAMODE */
5099 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5100 			rval = EFAULT;
5101 		}
5102 #endif /* _MULTI_DATAMODE */
5103 
5104 		break;
5105 	}
5106 	case MTIOCGETERROR:
5107 			/*
5108 			 * get error entry from error stack
5109 			 */
5110 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5111 			    "st_ioctl: MTIOCGETERROR\n");
5112 
5113 			rval = st_get_error_entry(un, arg, flag);
5114 
5115 			break;
5116 
5117 	case MTIOCSTATE:
5118 		{
5119 			/*
5120 			 * return when media presence matches state
5121 			 */
5122 			enum mtio_state state;
5123 
5124 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5125 			    "st_ioctl: MTIOCSTATE\n");
5126 
5127 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
5128 				rval = EFAULT;
5129 
5130 			mutex_exit(ST_MUTEX);
5131 
5132 			rval = st_check_media(dev, state);
5133 
5134 			mutex_enter(ST_MUTEX);
5135 
5136 			if (rval != 0) {
5137 				break;
5138 			}
5139 
5140 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
5141 			    sizeof (int), flag))
5142 				rval = EFAULT;
5143 			break;
5144 
5145 		}
5146 
5147 	case MTIOCGETDRIVETYPE:
5148 		{
5149 #ifdef _MULTI_DATAMODEL
5150 		/*
5151 		 * For use when a 32 bit app makes a call into a
5152 		 * 64 bit ioctl
5153 		 */
5154 		struct mtdrivetype_request32	mtdtrq32;
5155 #endif /* _MULTI_DATAMODEL */
5156 
5157 			/*
5158 			 * return mtdrivetype
5159 			 */
5160 			struct mtdrivetype_request mtdtrq;
5161 			struct mtdrivetype mtdrtyp;
5162 			struct mtdrivetype *mtdt = &mtdrtyp;
5163 			struct st_drivetype *stdt = un->un_dp;
5164 
5165 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5166 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
5167 
5168 #ifdef _MULTI_DATAMODEL
5169 		switch (ddi_model_convert_from(flag & FMODELS)) {
5170 		case DDI_MODEL_ILP32:
5171 		{
5172 			if (ddi_copyin((void *)arg, &mtdtrq32,
5173 			    sizeof (struct mtdrivetype_request32), flag)) {
5174 				rval = EFAULT;
5175 				break;
5176 			}
5177 			mtdtrq.size = mtdtrq32.size;
5178 			mtdtrq.mtdtp =
5179 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
5180 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5181 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
5182 			break;
5183 		}
5184 		case DDI_MODEL_NONE:
5185 			if (ddi_copyin((void *)arg, &mtdtrq,
5186 			    sizeof (struct mtdrivetype_request), flag)) {
5187 				rval = EFAULT;
5188 				break;
5189 			}
5190 			break;
5191 		}
5192 
5193 #else /* ! _MULTI_DATAMODEL */
5194 		if (ddi_copyin((void *)arg, &mtdtrq,
5195 		    sizeof (struct mtdrivetype_request), flag)) {
5196 			rval = EFAULT;
5197 			break;
5198 		}
5199 #endif /* _MULTI_DATAMODEL */
5200 
5201 			/*
5202 			 * if requested size is < 0 then return
5203 			 * error.
5204 			 */
5205 			if (mtdtrq.size < 0) {
5206 				rval = EINVAL;
5207 				break;
5208 			}
5209 			bzero(mtdt, sizeof (struct mtdrivetype));
5210 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
5211 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
5212 			mtdt->type = stdt->type;
5213 			mtdt->bsize = stdt->bsize;
5214 			mtdt->options = stdt->options;
5215 			mtdt->max_rretries = stdt->max_rretries;
5216 			mtdt->max_wretries = stdt->max_wretries;
5217 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5218 				mtdt->densities[tmp] = stdt->densities[tmp];
5219 			}
5220 			mtdt->default_density = stdt->default_density;
5221 			/*
5222 			 * Speed hasn't been used since the hayday of reel tape.
5223 			 * For all drives not setting the option ST_KNOWS_MEDIA
5224 			 * the speed member renamed to mediatype are zeros.
5225 			 * Those drives that have ST_KNOWS_MEDIA set use the
5226 			 * new mediatype member which is used to figure the
5227 			 * type of media loaded.
5228 			 *
5229 			 * So as to not break applications speed in the
5230 			 * mtdrivetype structure is not renamed.
5231 			 */
5232 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5233 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
5234 			}
5235 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
5236 			mtdt->io_timeout = stdt->io_timeout;
5237 			mtdt->rewind_timeout = stdt->rewind_timeout;
5238 			mtdt->space_timeout = stdt->space_timeout;
5239 			mtdt->load_timeout = stdt->load_timeout;
5240 			mtdt->unload_timeout = stdt->unload_timeout;
5241 			mtdt->erase_timeout = stdt->erase_timeout;
5242 
5243 			/*
5244 			 * Limit the maximum length of the result to
5245 			 * sizeof (struct mtdrivetype).
5246 			 */
5247 			tmp = sizeof (struct mtdrivetype);
5248 			if (mtdtrq.size < tmp)
5249 				tmp = mtdtrq.size;
5250 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
5251 				rval = EFAULT;
5252 			}
5253 			break;
5254 		}
5255 	case MTIOCPERSISTENT:
5256 
5257 		if (ddi_copyin((void *)arg, &tmp, sizeof (tmp), flag)) {
5258 			rval = EFAULT;
5259 			break;
5260 		}
5261 
5262 		if (tmp) {
5263 			st_turn_pe_on(un);
5264 		} else {
5265 			st_turn_pe_off(un);
5266 		}
5267 
5268 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5269 		    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
5270 		    un->un_persistence);
5271 
5272 		break;
5273 
5274 	case MTIOCPERSISTENTSTATUS:
5275 		tmp = (int)un->un_persistence;
5276 
5277 		if (ddi_copyout(&tmp, (void *)arg, sizeof (tmp), flag)) {
5278 			rval = EFAULT;
5279 		}
5280 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5281 		    "st_ioctl: MTIOCPERSISTENTSTATUS:persistence = %d\n",
5282 		    un->un_persistence);
5283 
5284 		break;
5285 
5286 	case MTIOCLRERR:
5287 		{
5288 			/* clear persistent errors */
5289 
5290 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5291 			    "st_ioctl: MTIOCLRERR\n");
5292 
5293 			st_clear_pe(un);
5294 
5295 			break;
5296 		}
5297 
5298 	case MTIOCGUARANTEEDORDER:
5299 		{
5300 			/*
5301 			 * this is just a holder to make a valid ioctl and
5302 			 * it won't be in any earlier release
5303 			 */
5304 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5305 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
5306 
5307 			break;
5308 		}
5309 
5310 	case MTIOCRESERVE:
5311 		{
5312 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5313 			    "st_ioctl: MTIOCRESERVE\n");
5314 
5315 			/*
5316 			 * Check if Reserve/Release is supported.
5317 			 */
5318 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5319 				rval = ENOTTY;
5320 				break;
5321 			}
5322 
5323 			rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5324 
5325 			if (rval == 0) {
5326 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
5327 			}
5328 			break;
5329 		}
5330 
5331 	case MTIOCRELEASE:
5332 		{
5333 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5334 			    "st_ioctl: MTIOCRELEASE\n");
5335 
5336 			/*
5337 			 * Check if Reserve/Release is supported.
5338 			 */
5339 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5340 				rval = ENOTTY;
5341 				break;
5342 			}
5343 
5344 			/*
5345 			 * Used to just clear ST_PRESERVE_RESERVE which
5346 			 * made the reservation release at next close.
5347 			 * As the user may have opened and then done a
5348 			 * persistant reservation we now need to drop
5349 			 * the reservation without closing if the user
5350 			 * attempts to do this.
5351 			 */
5352 			rval = st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
5353 
5354 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5355 
5356 			break;
5357 		}
5358 
5359 	case MTIOCFORCERESERVE:
5360 	{
5361 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5362 		    "st_ioctl: MTIOCFORCERESERVE\n");
5363 
5364 		/*
5365 		 * Check if Reserve/Release is supported.
5366 		 */
5367 		if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5368 			rval = ENOTTY;
5369 			break;
5370 		}
5371 		/*
5372 		 * allow only super user to run this.
5373 		 */
5374 		if (drv_priv(cred_p) != 0) {
5375 			rval = EPERM;
5376 			break;
5377 		}
5378 		/*
5379 		 * Throw away reserve,
5380 		 * not using test-unit-ready
5381 		 * since reserve can succeed without tape being
5382 		 * present in the drive.
5383 		 */
5384 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5385 
5386 		rval = st_take_ownership(un, st_uscsi_cmd);
5387 
5388 		break;
5389 	}
5390 
5391 	case USCSICMD:
5392 	{
5393 		cred_t	*cr;
5394 
5395 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5396 		    "st_ioctl: USCSICMD\n");
5397 
5398 		cr = ddi_get_cred();
5399 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5400 			rval = EPERM;
5401 		} else {
5402 			rval = st_uscsi_cmd(un, (struct uscsi_cmd *)arg, flag);
5403 		}
5404 		break;
5405 	}
5406 	case MTIOCTOP:
5407 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5408 		    "st_ioctl: MTIOCTOP\n");
5409 		rval = st_mtioctop(un, arg, flag);
5410 		break;
5411 
5412 	case MTIOCLTOP:
5413 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5414 		    "st_ioctl: MTIOLCTOP\n");
5415 		rval = st_mtiocltop(un, arg, flag);
5416 		break;
5417 
5418 	case MTIOCREADIGNOREILI:
5419 		{
5420 			int set_ili;
5421 
5422 			if (ddi_copyin((void *)arg, &set_ili,
5423 			    sizeof (set_ili), flag)) {
5424 				rval = EFAULT;
5425 				break;
5426 			}
5427 
5428 			if (un->un_bsize) {
5429 				rval = ENOTTY;
5430 				break;
5431 			}
5432 
5433 			switch (set_ili) {
5434 			case 0:
5435 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5436 				break;
5437 
5438 			case 1:
5439 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5440 				break;
5441 
5442 			default:
5443 				rval = EINVAL;
5444 				break;
5445 			}
5446 			break;
5447 		}
5448 
5449 	case MTIOCREADIGNOREEOFS:
5450 		{
5451 			int ignore_eof;
5452 
5453 			if (ddi_copyin((void *)arg, &ignore_eof,
5454 			    sizeof (ignore_eof), flag)) {
5455 				rval = EFAULT;
5456 				break;
5457 			}
5458 
5459 			if (!(un->un_dp->options & ST_REEL)) {
5460 				rval = ENOTTY;
5461 				break;
5462 			}
5463 
5464 			switch (ignore_eof) {
5465 			case 0:
5466 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5467 				break;
5468 
5469 			case 1:
5470 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5471 				break;
5472 
5473 			default:
5474 				rval = EINVAL;
5475 				break;
5476 			}
5477 			break;
5478 		}
5479 
5480 	case MTIOCSHORTFMK:
5481 	{
5482 		int short_fmk;
5483 
5484 		if (ddi_copyin((void *)arg, &short_fmk,
5485 		    sizeof (short_fmk), flag)) {
5486 			rval = EFAULT;
5487 			break;
5488 		}
5489 
5490 		switch (un->un_dp->type) {
5491 		case ST_TYPE_EXB8500:
5492 		case ST_TYPE_EXABYTE:
5493 			if (!short_fmk) {
5494 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5495 			} else if (short_fmk == 1) {
5496 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5497 			} else {
5498 				rval = EINVAL;
5499 			}
5500 			break;
5501 
5502 		default:
5503 			rval = ENOTTY;
5504 			break;
5505 		}
5506 		break;
5507 	}
5508 
5509 	case MTIOCGETPOS:
5510 		rval = st_update_block_pos(un, st_cmd, 0);
5511 		if (rval == 0) {
5512 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5513 			    sizeof (tapepos_t), flag)) {
5514 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5515 				    "MTIOCGETPOS copy out failed\n");
5516 				rval = EFAULT;
5517 			}
5518 		}
5519 		break;
5520 
5521 	case MTIOCRESTPOS:
5522 	{
5523 		tapepos_t dest;
5524 
5525 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5526 		    flag) != 0) {
5527 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5528 			    "MTIOCRESTPOS copy in failed\n");
5529 			rval = EFAULT;
5530 			break;
5531 		}
5532 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &dest);
5533 		if (rval != 0) {
5534 			rval = EIO;
5535 		}
5536 		break;
5537 	}
5538 	default:
5539 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5540 		    "st_ioctl: unknown ioctl\n");
5541 		rval = ENOTTY;
5542 	}
5543 
5544 exit:
5545 	if (!(un->un_persistence && un->un_persist_errors)) {
5546 		un->un_errno = rval;
5547 	}
5548 
5549 	mutex_exit(ST_MUTEX);
5550 
5551 	return (rval);
5552 }
5553 
5554 
5555 /*
5556  * do some MTIOCTOP tape operations
5557  */
5558 static int
5559 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5560 {
5561 #ifdef _MULTI_DATAMODEL
5562 	/*
5563 	 * For use when a 32 bit app makes a call into a
5564 	 * 64 bit ioctl
5565 	 */
5566 	struct mtop32	mtop_32_for_64;
5567 #endif /* _MULTI_DATAMODEL */
5568 	struct mtop passed;
5569 	struct mtlop local;
5570 	int rval = 0;
5571 
5572 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5573 
5574 	ASSERT(mutex_owned(ST_MUTEX));
5575 
5576 #ifdef _MULTI_DATAMODEL
5577 	switch (ddi_model_convert_from(flag & FMODELS)) {
5578 	case DDI_MODEL_ILP32:
5579 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5580 		    sizeof (struct mtop32), flag)) {
5581 			return (EFAULT);
5582 		}
5583 		local.mt_op = mtop_32_for_64.mt_op;
5584 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5585 		break;
5586 
5587 	case DDI_MODEL_NONE:
5588 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5589 			return (EFAULT);
5590 		}
5591 		local.mt_op = passed.mt_op;
5592 		/* prevent sign extention */
5593 		local.mt_count = (UINT32_MAX & passed.mt_count);
5594 		break;
5595 	}
5596 
5597 #else /* ! _MULTI_DATAMODEL */
5598 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5599 		return (EFAULT);
5600 	}
5601 	local.mt_op = passed.mt_op;
5602 	/* prevent sign extention */
5603 	local.mt_count = (UINT32_MAX & passed.mt_count);
5604 #endif /* _MULTI_DATAMODEL */
5605 
5606 	rval = st_do_mtioctop(un, &local);
5607 
5608 #ifdef _MULTI_DATAMODEL
5609 	switch (ddi_model_convert_from(flag & FMODELS)) {
5610 	case DDI_MODEL_ILP32:
5611 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5612 			rval = ERANGE;
5613 			break;
5614 		}
5615 		/*
5616 		 * Convert 64 bit back to 32 bit before doing
5617 		 * copyout. This is what the ILP32 app expects.
5618 		 */
5619 		mtop_32_for_64.mt_op = local.mt_op;
5620 		mtop_32_for_64.mt_count = local.mt_count;
5621 
5622 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5623 		    sizeof (struct mtop32), flag)) {
5624 			rval = EFAULT;
5625 		}
5626 		break;
5627 
5628 	case DDI_MODEL_NONE:
5629 		passed.mt_count = local.mt_count;
5630 		passed.mt_op = local.mt_op;
5631 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5632 			rval = EFAULT;
5633 		}
5634 		break;
5635 	}
5636 #else /* ! _MULTI_DATAMODE */
5637 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5638 		rval = ERANGE;
5639 	} else {
5640 		passed.mt_op = local.mt_op;
5641 		passed.mt_count = local.mt_count;
5642 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5643 			rval = EFAULT;
5644 		}
5645 	}
5646 #endif /* _MULTI_DATAMODE */
5647 
5648 
5649 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5650 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5651 	    un->un_pos.blkno, un->un_pos.eof);
5652 
5653 	if (un->un_pos.pmode == invalid) {
5654 		un->un_density_known = 0;
5655 	}
5656 
5657 	ASSERT(mutex_owned(ST_MUTEX));
5658 	return (rval);
5659 }
5660 
5661 static int
5662 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5663 {
5664 	struct mtlop local;
5665 	int rval;
5666 
5667 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5668 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5669 		return (EFAULT);
5670 	}
5671 
5672 	rval = st_do_mtioctop(un, &local);
5673 
5674 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5675 		rval = EFAULT;
5676 	}
5677 	return (rval);
5678 }
5679 
5680 
5681 static int
5682 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5683 {
5684 	dev_t dev = un->un_dev;
5685 	int savefile;
5686 	int rval = 0;
5687 
5688 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5689 
5690 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5691 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5692 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5693 	    "fileno=%x, blkno=%x, eof=%x\n",
5694 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5695 
5696 	un->un_status = 0;
5697 
5698 	/*
5699 	 * if we are going to mess with a tape, we have to make sure we have
5700 	 * one and are not offline (i.e. no tape is initialized).  We let
5701 	 * commands pass here that don't actually touch the tape, except for
5702 	 * loading and initialization (rewinding).
5703 	 */
5704 	if (un->un_state == ST_STATE_OFFLINE) {
5705 		switch (mtop->mt_op) {
5706 		case MTLOAD:
5707 		case MTNOP:
5708 			/*
5709 			 * We don't want strategy calling st_tape_init here,
5710 			 * so, change state
5711 			 */
5712 			un->un_state = ST_STATE_INITIALIZING;
5713 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5714 			    "st_do_mtioctop : OFFLINE state = %d\n",
5715 			    un->un_state);
5716 			break;
5717 		default:
5718 			/*
5719 			 * reinitialize by normal means
5720 			 */
5721 			rval = st_tape_init(un);
5722 			if (rval) {
5723 				un->un_state = ST_STATE_INITIALIZING;
5724 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5725 				    "st_do_mtioctop : OFFLINE init failure ");
5726 				un->un_state = ST_STATE_OFFLINE;
5727 				un->un_pos.pmode = invalid;
5728 				if (rval != EACCES) {
5729 					rval = EIO;
5730 				}
5731 				return (rval);
5732 			}
5733 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5734 			break;
5735 		}
5736 	}
5737 
5738 	/*
5739 	 * If the file position is invalid, allow only those
5740 	 * commands that properly position the tape and fail
5741 	 * the rest with EIO
5742 	 */
5743 	if (un->un_pos.pmode == invalid) {
5744 		switch (mtop->mt_op) {
5745 		case MTWEOF:
5746 		case MTRETEN:
5747 		case MTERASE:
5748 		case MTEOM:
5749 		case MTFSF:
5750 		case MTFSR:
5751 		case MTBSF:
5752 		case MTNBSF:
5753 		case MTBSR:
5754 		case MTSRSZ:
5755 		case MTGRSZ:
5756 		case MTSEEK:
5757 		case MTBSSF:
5758 		case MTFSSF:
5759 			return (EIO);
5760 			/* NOTREACHED */
5761 		case MTREW:
5762 		case MTLOAD:
5763 		case MTOFFL:
5764 		case MTNOP:
5765 		case MTTELL:
5766 		case MTLOCK:
5767 		case MTUNLOCK:
5768 			break;
5769 
5770 		default:
5771 			return (ENOTTY);
5772 			/* NOTREACHED */
5773 		}
5774 	}
5775 
5776 	switch (mtop->mt_op) {
5777 	case MTERASE:
5778 		/*
5779 		 * MTERASE rewinds the tape, erase it completely, and returns
5780 		 * to the beginning of the tape
5781 		 */
5782 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5783 			un->un_status = KEY_WRITE_PROTECT;
5784 			un->un_err_resid = mtop->mt_count;
5785 			COPY_POS(&un->un_err_pos, &un->un_pos);
5786 			return (EACCES);
5787 		}
5788 		if (un->un_dp->options & ST_REEL) {
5789 			un->un_fmneeded = 2;
5790 		} else {
5791 			un->un_fmneeded = 1;
5792 		}
5793 		mtop->mt_count = mtop->mt_count ? 1 : 0;
5794 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5795 		    st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
5796 		    st_cmd(un, SCMD_ERASE, mtop->mt_count, SYNC_CMD)) {
5797 			un->un_pos.pmode = invalid;
5798 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5799 			    "st_do_mtioctop : EIO space or erase or "
5800 			    "check den)\n");
5801 			rval = EIO;
5802 		} else {
5803 			/* QIC and helical scan rewind after erase */
5804 			if (un->un_dp->options & ST_REEL) {
5805 				(void) st_cmd(un, SCMD_REWIND, 0, ASYNC_CMD);
5806 			}
5807 		}
5808 		break;
5809 
5810 	case MTWEOF:
5811 		/*
5812 		 * write an end-of-file record
5813 		 */
5814 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5815 			un->un_status = KEY_WRITE_PROTECT;
5816 			un->un_err_resid = mtop->mt_count;
5817 			COPY_POS(&un->un_err_pos, &un->un_pos);
5818 			return (EACCES);
5819 		}
5820 
5821 		/*
5822 		 * zero count means just flush buffers
5823 		 * negative count is not permitted
5824 		 */
5825 		if (mtop->mt_count < 0) {
5826 			return (EINVAL);
5827 		}
5828 
5829 		/* Not on worm */
5830 		if (un->un_read_only == RDWR) {
5831 			un->un_test_append = 1;
5832 		}
5833 
5834 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5835 			if (st_determine_density(un, B_WRITE)) {
5836 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5837 				    "st_do_mtioctop : EIO : MTWEOF can't "
5838 				    "determine density");
5839 				return (EIO);
5840 			}
5841 		}
5842 
5843 		rval = st_write_fm(dev, (int)mtop->mt_count);
5844 		if ((rval != 0) && (rval != EACCES)) {
5845 			/*
5846 			 * Failure due to something other than illegal
5847 			 * request results in loss of state (st_intr).
5848 			 */
5849 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5850 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5851 			    "file mark");
5852 			rval = EIO;
5853 		}
5854 		break;
5855 
5856 	case MTRETEN:
5857 		/*
5858 		 * retension the tape
5859 		 */
5860 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5861 		    st_cmd(un, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5862 			un->un_pos.pmode = invalid;
5863 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5864 			    "st_do_mtioctop : EIO : MTRETEN ");
5865 			rval = EIO;
5866 		}
5867 		break;
5868 
5869 	case MTREW:
5870 		/*
5871 		 * rewind  the tape
5872 		 */
5873 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5874 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5875 			    "st_do_mtioctop : EIO:MTREW check "
5876 			    "density/wfm failed");
5877 			return (EIO);
5878 		}
5879 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
5880 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5881 			    "st_do_mtioctop : EIO : MTREW ");
5882 			rval = EIO;
5883 		}
5884 		break;
5885 
5886 	case MTOFFL:
5887 		/*
5888 		 * rewinds, and, if appropriate, takes the device offline by
5889 		 * unloading the tape
5890 		 */
5891 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5892 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5893 			    "st_do_mtioctop :EIO:MTOFFL check "
5894 			    "density/wfm failed");
5895 			return (EIO);
5896 		}
5897 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
5898 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5899 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5900 			    "st_do_mtioctop : EIO : MTOFFL");
5901 			return (EIO);
5902 		}
5903 		un->un_pos.eof = ST_NO_EOF;
5904 		un->un_laststate = un->un_state;
5905 		un->un_state = ST_STATE_OFFLINE;
5906 		un->un_mediastate = MTIO_EJECTED;
5907 		break;
5908 
5909 	case MTLOAD:
5910 		/*
5911 		 * This is to load a tape into the drive
5912 		 * Note that if the tape is not loaded, the device will have
5913 		 * to be opened via O_NDELAY or O_NONBLOCK.
5914 		 */
5915 		/*
5916 		 * Let's try and clean things up, if we are not
5917 		 * initializing, and then send in the load command, no
5918 		 * matter what.
5919 		 *
5920 		 * load after a media change by the user.
5921 		 */
5922 
5923 		if (un->un_state > ST_STATE_INITIALIZING) {
5924 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5925 		}
5926 		rval = st_cmd(un, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5927 		/* Load command to a drive that doesn't support load */
5928 		if ((rval == EIO) &&
5929 		    ((un->un_status == KEY_NOT_READY) &&
5930 			/* Medium not present */
5931 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5932 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5933 		    (un->un_dp->type == MT_ISSTK9840) &&
5934 			/* CSL not present */
5935 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5936 			rval = ENOTTY;
5937 			break;
5938 		} else if (rval != EACCES && rval != 0) {
5939 			rval = EIO;
5940 		}
5941 		if (rval) {
5942 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5943 			    "st_do_mtioctop : %s : MTLOAD\n",
5944 			    rval == EACCES ? "EACCES" : "EIO");
5945 			/*
5946 			 * If load tape fails, who knows what happened...
5947 			 */
5948 			un->un_pos.pmode = invalid;
5949 			break;
5950 		}
5951 
5952 		/*
5953 		 * reset all counters appropriately using rewind, as if LOAD
5954 		 * succeeds, we are at BOT
5955 		 */
5956 		un->un_state = ST_STATE_INITIALIZING;
5957 
5958 		rval = st_tape_init(un);
5959 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5960 			rval = 0;
5961 			break;
5962 		}
5963 
5964 		if (rval != 0) {
5965 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5966 			    "st_do_mtioctop : EIO : MTLOAD calls "
5967 			    "st_tape_init\n");
5968 			rval = EIO;
5969 			un->un_state = ST_STATE_OFFLINE;
5970 		}
5971 
5972 		break;
5973 
5974 	case MTNOP:
5975 		un->un_status = 0;		/* Reset status */
5976 		un->un_err_resid = 0;
5977 		mtop->mt_count = MTUNIT(dev);
5978 		break;
5979 
5980 	case MTEOM:
5981 		/*
5982 		 * positions the tape at a location just after the last file
5983 		 * written on the tape. For cartridge and 8 mm, this after
5984 		 * the last file mark; for reel, this is inbetween the two
5985 		 * last 2 file marks
5986 		 */
5987 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5988 		    (un->un_lastop == ST_OP_WRITE) ||
5989 		    (un->un_lastop == ST_OP_WEOF)) {
5990 			/*
5991 			 * If the command wants to move to logical end
5992 			 * of media, and we're already there, we're done.
5993 			 * If we were at logical eot, we reset the state
5994 			 * to be *not* at logical eot.
5995 			 *
5996 			 * If we're at physical or logical eot, we prohibit
5997 			 * forward space operations (unconditionally).
5998 			 *
5999 			 * Also if the last operation was a write of any
6000 			 * kind the tape is at EOD.
6001 			 */
6002 			return (0);
6003 		}
6004 		/*
6005 		 * physical tape position may not be what we've been
6006 		 * telling the user; adjust the request accordingly
6007 		 */
6008 		if (IN_EOF(un->un_pos)) {
6009 			un->un_pos.fileno++;
6010 			un->un_pos.blkno = 0;
6011 		}
6012 
6013 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
6014 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6015 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
6016 			    " failed");
6017 			return (EIO);
6018 		}
6019 
6020 		/*
6021 		 * st_find_eod() returns the last fileno we knew about;
6022 		 */
6023 		savefile = st_find_eod(un);
6024 
6025 		if ((un->un_status != KEY_BLANK_CHECK) &&
6026 		    (un->un_status != SUN_KEY_EOT)) {
6027 			un->un_pos.pmode = invalid;
6028 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6029 			    "st_do_mtioctop : EIO : MTEOM status check failed");
6030 			rval = EIO;
6031 		} else {
6032 			/*
6033 			 * For 1/2" reel tapes assume logical EOT marked
6034 			 * by two file marks or we don't care that we may
6035 			 * be extending the last file on the tape.
6036 			 */
6037 			if (un->un_dp->options & ST_REEL) {
6038 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
6039 					un->un_pos.pmode = invalid;
6040 					ST_DEBUG2(ST_DEVINFO, st_label,
6041 					    SCSI_DEBUG,
6042 					    "st_do_mtioctop : EIO : MTEOM space"
6043 					    " cmd failed");
6044 					rval = EIO;
6045 					break;
6046 				}
6047 				/*
6048 				 * Fix up the block number.
6049 				 */
6050 				un->un_pos.blkno = 0;
6051 				un->un_err_pos.blkno = 0;
6052 			}
6053 			un->un_err_resid = 0;
6054 			un->un_pos.fileno = savefile;
6055 			un->un_pos.eof = ST_EOT;
6056 		}
6057 		un->un_status = 0;
6058 		break;
6059 
6060 	case MTFSF:
6061 		MAX_SPACE_CNT(mtop->mt_count);
6062 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
6063 		break;
6064 
6065 	case MTFSR:
6066 		MAX_SPACE_CNT(mtop->mt_count);
6067 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
6068 		break;
6069 
6070 	case MTBSF:
6071 		MAX_SPACE_CNT(mtop->mt_count);
6072 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
6073 		break;
6074 
6075 	case MTNBSF:
6076 		MAX_SPACE_CNT(mtop->mt_count);
6077 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
6078 		break;
6079 
6080 	case MTBSR:
6081 		MAX_SPACE_CNT(mtop->mt_count);
6082 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
6083 		break;
6084 
6085 	case MTBSSF:
6086 		MAX_SPACE_CNT(mtop->mt_count);
6087 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
6088 		break;
6089 
6090 	case MTFSSF:
6091 		MAX_SPACE_CNT(mtop->mt_count);
6092 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
6093 		break;
6094 
6095 	case MTSRSZ:
6096 
6097 		/*
6098 		 * Set record-size to that sent by user
6099 		 * Check to see if there is reason that the requested
6100 		 * block size should not be set.
6101 		 */
6102 
6103 		/* If requesting variable block size is it ok? */
6104 		if ((mtop->mt_count == 0) &&
6105 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
6106 			return (ENOTTY);
6107 		}
6108 
6109 		/*
6110 		 * If requested block size is not variable "0",
6111 		 * is it less then minimum.
6112 		 */
6113 		if ((mtop->mt_count != 0) &&
6114 		    (mtop->mt_count < un->un_minbsize)) {
6115 			return (EINVAL);
6116 		}
6117 
6118 		/* Is the requested block size more then maximum */
6119 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
6120 		    (un->un_maxbsize != 0)) {
6121 			return (EINVAL);
6122 		}
6123 
6124 		/* Is requested block size a modulus the device likes */
6125 		if ((mtop->mt_count % un->un_data_mod) != 0) {
6126 			return (EINVAL);
6127 		}
6128 
6129 		if (st_change_block_size(un, (uint32_t)mtop->mt_count) != 0) {
6130 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6131 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
6132 			return (EIO);
6133 		}
6134 
6135 		return (0);
6136 
6137 	case MTGRSZ:
6138 		/*
6139 		 * Get record-size to the user
6140 		 */
6141 		mtop->mt_count = un->un_bsize;
6142 		rval = 0;
6143 		break;
6144 
6145 	case MTTELL:
6146 		rval = st_update_block_pos(un, st_cmd, 0);
6147 		mtop->mt_count = un->un_pos.lgclblkno;
6148 		break;
6149 
6150 	case MTSEEK:
6151 		rval = st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
6152 		    (uint64_t)mtop->mt_count, un->un_pos.partition);
6153 		/*
6154 		 * This bit of magic make mt print the actual position if
6155 		 * the resulting position was not what was asked for.
6156 		 */
6157 		if (rval == ESPIPE) {
6158 			rval = EIO;
6159 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
6160 				mtop->mt_op = MTTELL;
6161 				mtop->mt_count = un->un_pos.lgclblkno;
6162 			}
6163 		}
6164 		break;
6165 
6166 	case MTLOCK:
6167 		if (st_cmd(un, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
6168 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6169 			    "st_do_mtioctop : EIO : MTLOCK");
6170 			rval = EIO;
6171 		}
6172 		break;
6173 
6174 	case MTUNLOCK:
6175 		if (st_cmd(un, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
6176 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6177 			    "st_do_mtioctop : EIO : MTUNLOCK");
6178 			rval = EIO;
6179 		}
6180 		break;
6181 
6182 	default:
6183 		rval = ENOTTY;
6184 	}
6185 
6186 	return (rval);
6187 }
6188 
6189 
6190 /*
6191  * Run a command for uscsi ioctl.
6192  */
6193 static int
6194 st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
6195 {
6196 	struct uscsi_cmd	*uscmd;
6197 	struct buf	*bp;
6198 	enum uio_seg	uioseg;
6199 	int	offline_state = 0;
6200 	int	err = 0;
6201 	dev_t dev = un->un_dev;
6202 
6203 	ST_FUNC(ST_DEVINFO, st_uscsi_cmd);
6204 
6205 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6206 	    "st_uscsi_cmd(dev = 0x%lx)\n", un->un_dev);
6207 
6208 	ASSERT(mutex_owned(ST_MUTEX));
6209 
6210 	/*
6211 	 * We really don't know what commands are coming in here and
6212 	 * we don't want to limit the commands coming in.
6213 	 *
6214 	 * If st_tape_init() gets called from st_strategy(), then we
6215 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
6216 	 * which it never will, as we set it below.  To prevent
6217 	 * st_tape_init() from getting called, we have to set state to other
6218 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
6219 	 * achieves this purpose already.
6220 	 *
6221 	 * We use offline_state to preserve the OFFLINE state, if it exists,
6222 	 * so other entry points to the driver might have the chance to call
6223 	 * st_tape_init().
6224 	 */
6225 	if (un->un_state == ST_STATE_OFFLINE) {
6226 		un->un_laststate = ST_STATE_OFFLINE;
6227 		un->un_state = ST_STATE_INITIALIZING;
6228 		offline_state = 1;
6229 	}
6230 
6231 	mutex_exit(ST_MUTEX);
6232 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag, ROUTE, &uscmd);
6233 	mutex_enter(ST_MUTEX);
6234 	if (err != 0) {
6235 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6236 		    "st_uscsi_cmd: scsi_uscsi_alloc_and_copyin failed\n");
6237 		goto exit;
6238 	}
6239 
6240 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
6241 
6242 	/* check to see if this command requires the drive to be reserved */
6243 	if (uscmd->uscsi_cdb != NULL) {
6244 		err = st_check_cdb_for_need_to_reserve(un,
6245 		    (uchar_t *)uscmd->uscsi_cdb);
6246 		if (err) {
6247 			goto exit_free;
6248 		}
6249 		/*
6250 		 * If this is a space command we need to save the starting
6251 		 * point so we can retry from there if the command fails.
6252 		 */
6253 		if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6254 		    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) {
6255 			(void) st_update_block_pos(un, st_cmd, 0);
6256 		}
6257 	}
6258 
6259 	/*
6260 	 * Forground should not be doing anything while recovery is active.
6261 	 */
6262 	ASSERT(un->un_recov_buf_busy == 0);
6263 
6264 	/*
6265 	 * Get buffer resources...
6266 	 */
6267 	while (un->un_sbuf_busy)
6268 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6269 	un->un_sbuf_busy = 1;
6270 
6271 #ifdef STDEBUG
6272 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0x7) > 6) {
6273 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
6274 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6275 		    "uscsi cdb", uscmd->uscsi_cdb);
6276 		if (uscmd->uscsi_buflen) {
6277 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6278 			    "uscsi %s of %ld bytes %s %s space\n",
6279 			    (rw == B_READ) ? rd_str : wr_str,
6280 			    uscmd->uscsi_buflen,
6281 			    (rw == B_READ) ? "to" : "from",
6282 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
6283 		}
6284 	}
6285 #endif /* STDEBUG */
6286 
6287 	/*
6288 	 * Although st_uscsi_cmd() never makes use of these
6289 	 * now, we are just being safe and consistent.
6290 	 */
6291 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
6292 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
6293 
6294 	un->un_srqbufp = uscmd->uscsi_rqbuf;
6295 	bp = un->un_sbufp;
6296 	bzero(bp, sizeof (buf_t));
6297 	if (uscmd->uscsi_cdb != NULL) {
6298 		bp->b_forw = (struct buf *)(uintptr_t)uscmd->uscsi_cdb[0];
6299 	}
6300 	bp->b_back = (struct buf *)uscmd;
6301 
6302 	mutex_exit(ST_MUTEX);
6303 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, st_strategy, bp, NULL);
6304 	mutex_enter(ST_MUTEX);
6305 
6306 	/*
6307 	 * If scsi reset successful, don't write any filemarks.
6308 	 */
6309 	if ((err == 0) && (uscmd->uscsi_flags &
6310 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
6311 		un->un_fmneeded = 0;
6312 	}
6313 
6314 exit_free:
6315 	/*
6316 	 * Free resources
6317 	 */
6318 	un->un_sbuf_busy = 0;
6319 	un->un_srqbufp = NULL;
6320 
6321 	/*
6322 	 * If was a space command need to update logical block position.
6323 	 * If the command failed such that positioning is invalid, Don't
6324 	 * update the position as the user must do this to validate the
6325 	 * position for data protection.
6326 	 */
6327 	if ((uscmd->uscsi_cdb != NULL) &&
6328 	    ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6329 	    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) &&
6330 	    (un->un_pos.pmode != invalid)) {
6331 		un->un_running.pmode = invalid;
6332 		(void) st_update_block_pos(un, st_cmd, 1);
6333 		/*
6334 		 * Set running position to invalid so it updates on the
6335 		 * next command.
6336 		 */
6337 		un->un_running.pmode = invalid;
6338 	}
6339 	cv_signal(&un->un_sbuf_cv);
6340 	mutex_exit(ST_MUTEX);
6341 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
6342 	mutex_enter(ST_MUTEX);
6343 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6344 	    "st_uscsi_cmd returns 0x%x\n", err);
6345 
6346 exit:
6347 	/* don't lose offline state */
6348 	if (offline_state) {
6349 		un->un_state = ST_STATE_OFFLINE;
6350 	}
6351 
6352 	ASSERT(mutex_owned(ST_MUTEX));
6353 	return (err);
6354 }
6355 
6356 static int
6357 st_write_fm(dev_t dev, int wfm)
6358 {
6359 	int i;
6360 	int rval;
6361 
6362 	GET_SOFT_STATE(dev);
6363 
6364 	ST_FUNC(ST_DEVINFO, st_write_fm);
6365 
6366 	ASSERT(mutex_owned(ST_MUTEX));
6367 
6368 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6369 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6370 
6371 	/*
6372 	 * write one filemark at the time after EOT
6373 	 */
6374 	if (un->un_pos.eof >= ST_EOT) {
6375 		for (i = 0; i < wfm; i++) {
6376 			rval = st_cmd(un, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6377 			if (rval == EACCES) {
6378 				return (rval);
6379 			}
6380 			if (rval != 0) {
6381 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6382 				    "st_write_fm : EIO : write EOT file mark");
6383 				return (EIO);
6384 			}
6385 		}
6386 	} else {
6387 		rval = st_cmd(un, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6388 		if (rval == EACCES) {
6389 			return (rval);
6390 		}
6391 		if (rval) {
6392 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6393 			    "st_write_fm : EIO : write file mark");
6394 			return (EIO);
6395 		}
6396 	}
6397 
6398 	ASSERT(mutex_owned(ST_MUTEX));
6399 	return (0);
6400 }
6401 
6402 #ifdef STDEBUG
6403 static void
6404 st_start_dump(struct scsi_tape *un, struct buf *bp)
6405 {
6406 	struct scsi_pkt *pkt = BP_PKT(bp);
6407 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6408 
6409 	ST_FUNC(ST_DEVINFO, st_start_dump);
6410 
6411 	if ((st_debug & 0x7) < 6)
6412 		return;
6413 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6414 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6415 	    (void *)bp->b_forw, bp->b_bcount,
6416 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6417 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6418 	    "st_start: cdb",  (caddr_t)cdbp);
6419 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6420 	    "st_start: fileno=%d, blk=%d\n",
6421 	    un->un_pos.fileno, un->un_pos.blkno);
6422 }
6423 #endif
6424 
6425 
6426 /*
6427  * Command start && done functions
6428  */
6429 
6430 /*
6431  * st_start()
6432  *
6433  * Called from:
6434  *  st_strategy() to start a command.
6435  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6436  *  st_attach() when resuming from power down state.
6437  *  st_start_restart() to retry transport when device was previously busy.
6438  *  st_done_and_mutex_exit() to start the next command when previous is done.
6439  *
6440  * On entry:
6441  *  scsi_pkt may or may not be allocated.
6442  *
6443  */
6444 static void
6445 st_start(struct scsi_tape *un)
6446 {
6447 	struct buf *bp;
6448 	int status;
6449 	int queued;
6450 
6451 	ST_FUNC(ST_DEVINFO, st_start);
6452 	ASSERT(mutex_owned(ST_MUTEX));
6453 
6454 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6455 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6456 
6457 	if (un->un_recov_buf_busy) {
6458 		/* recovery commands can happen anytime */
6459 		bp = un->un_recov_buf;
6460 		queued = 0;
6461 	} else if (un->un_sbuf_busy) {
6462 		/* sbuf commands should only happen with an empty queue. */
6463 		ASSERT(un->un_quef == NULL);
6464 		ASSERT(un->un_runqf == NULL);
6465 		bp = un->un_sbufp;
6466 		queued = 0;
6467 	} else if (un->un_quef != NULL) {
6468 		if (un->un_persistence && un->un_persist_errors) {
6469 			return;
6470 		}
6471 		bp = un->un_quef;
6472 		queued = 1;
6473 	} else {
6474 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6475 		    "st_start() returning no buf found\n");
6476 		return;
6477 	}
6478 
6479 	ASSERT((bp->b_flags & B_DONE) == 0);
6480 
6481 	/*
6482 	 * Don't send more than un_throttle commands to the HBA
6483 	 */
6484 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6485 		/*
6486 		 * if doing recovery we know there is outstanding commands.
6487 		 */
6488 		if (bp != un->un_recov_buf) {
6489 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6490 			    "st_start returning throttle = %d or ncmds = %d\n",
6491 			    un->un_throttle, un->un_ncmds);
6492 			if (un->un_ncmds == 0) {
6493 				typedef void (*func)();
6494 				func fnc = (func)st_runout;
6495 
6496 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6497 				    "Sending delayed start to st_runout()\n");
6498 				mutex_exit(ST_MUTEX);
6499 				(void) timeout(fnc, un, drv_usectohz(1000000));
6500 				mutex_enter(ST_MUTEX);
6501 			}
6502 			return;
6503 		}
6504 	}
6505 
6506 	/*
6507 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6508 	 * build the command.
6509 	 */
6510 	if (BP_PKT(bp) == NULL) {
6511 		ASSERT((bp->b_flags & B_DONE) == 0);
6512 		st_make_cmd(un, bp, st_runout);
6513 		ASSERT((bp->b_flags & B_DONE) == 0);
6514 		status = geterror(bp);
6515 
6516 		/*
6517 		 * Some HBA's don't call bioerror() to set an error.
6518 		 * And geterror() returns zero if B_ERROR is not set.
6519 		 * So if we get zero we must check b_error.
6520 		 */
6521 		if (status == 0 && bp->b_error != 0) {
6522 			status = bp->b_error;
6523 			bioerror(bp, status);
6524 		}
6525 
6526 		/*
6527 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6528 		 * In tape ENOMEM has special meaning so we'll change it.
6529 		 */
6530 		if (status == ENOMEM) {
6531 			status = 0;
6532 			bioerror(bp, status);
6533 		}
6534 
6535 		/*
6536 		 * Did it fail and is it retryable?
6537 		 * If so return and wait for the callback through st_runout.
6538 		 * Also looks like scsi_init_pkt() will setup a callback even
6539 		 * if it isn't retryable.
6540 		 */
6541 		if (BP_PKT(bp) == NULL) {
6542 			if (status == 0) {
6543 				/*
6544 				 * If first attempt save state.
6545 				 */
6546 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6547 					un->un_laststate = un->un_state;
6548 					un->un_state = ST_STATE_RESOURCE_WAIT;
6549 				}
6550 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6551 				    "temp no resources for pkt\n");
6552 			} else if (status == EINVAL) {
6553 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6554 				    "scsi_init_pkt rejected pkt as too big\n");
6555 				if (un->un_persistence) {
6556 					st_set_pe_flag(un);
6557 				}
6558 			} else {
6559 				/*
6560 				 * Unlikely that it would be retryable then not.
6561 				 */
6562 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6563 					un->un_state = un->un_laststate;
6564 				}
6565 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6566 				    "perm no resources for pkt errno = 0x%x\n",
6567 				    status);
6568 			}
6569 			return;
6570 		}
6571 		/*
6572 		 * Worked this time set the state back.
6573 		 */
6574 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6575 			un->un_state = un->un_laststate;
6576 		}
6577 	}
6578 
6579 	if (queued) {
6580 		/*
6581 		 * move from waitq to runq
6582 		 */
6583 		(void) st_remove_from_queue(&un->un_quef, &un->un_quel, bp);
6584 		st_add_to_queue(&un->un_runqf, &un->un_runql, un->un_runql, bp);
6585 	}
6586 
6587 
6588 #ifdef STDEBUG
6589 	st_start_dump(un, bp);
6590 #endif
6591 
6592 	/* could not get here if throttle was zero */
6593 	un->un_last_throttle = un->un_throttle;
6594 	un->un_throttle = 0;	/* so nothing else will come in here */
6595 	un->un_ncmds++;
6596 
6597 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6598 
6599 	status = st_transport(un, BP_PKT(bp));
6600 
6601 	if (un->un_last_throttle) {
6602 		un->un_throttle = un->un_last_throttle;
6603 	}
6604 
6605 	if (status != TRAN_ACCEPT) {
6606 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6607 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
6608 		    "Unhappy transport packet status 0x%x\n", status);
6609 
6610 		if (status == TRAN_BUSY) {
6611 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
6612 
6613 			/*
6614 			 * If command recovery is enabled and this isn't
6615 			 * a recovery command try command recovery.
6616 			 */
6617 			if (pkti->privatelen == sizeof (recov_info) &&
6618 			    bp != un->un_recov_buf) {
6619 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
6620 				    "Command Recovery called on busy send\n");
6621 				if (st_command_recovery(un, BP_PKT(bp),
6622 				    ATTEMPT_RETRY) == JUST_RETURN) {
6623 					return;
6624 				}
6625 			} else {
6626 				mutex_exit(ST_MUTEX);
6627 				if (st_handle_start_busy(un, bp,
6628 				    ST_TRAN_BUSY_TIMEOUT, queued) == 0) {
6629 					mutex_enter(ST_MUTEX);
6630 					return;
6631 				}
6632 				/*
6633 				 * if too many retries, fail the transport
6634 				 */
6635 				mutex_enter(ST_MUTEX);
6636 			}
6637 		}
6638 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6639 		    "transport rejected %d\n", status);
6640 		bp->b_resid = bp->b_bcount;
6641 
6642 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6643 		ST_DO_ERRSTATS(un, st_transerrs);
6644 		if ((bp == un->un_recov_buf) && (status == TRAN_BUSY)) {
6645 			st_bioerror(bp, EBUSY);
6646 		} else {
6647 			st_bioerror(bp, EIO);
6648 			st_set_pe_flag(un);
6649 		}
6650 		st_done_and_mutex_exit(un, bp);
6651 		mutex_enter(ST_MUTEX);
6652 	}
6653 
6654 	ASSERT(mutex_owned(ST_MUTEX));
6655 }
6656 
6657 /*
6658  * if the transport is busy, then put this bp back on the waitq
6659  */
6660 static int
6661 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6662     clock_t timeout_interval, int queued)
6663 {
6664 
6665 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
6666 
6667 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6668 
6669 	mutex_enter(ST_MUTEX);
6670 
6671 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6672 	    "st_handle_start_busy()\n");
6673 
6674 	/*
6675 	 * Check to see if we hit the retry timeout and one last check for
6676 	 * making sure this is the last on the runq, if it is not, we have
6677 	 * to fail
6678 	 */
6679 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
6680 	    ((queued) && (un->un_runql != bp))) {
6681 		mutex_exit(ST_MUTEX);
6682 		return (-1);
6683 	}
6684 
6685 	if (queued) {
6686 		/* put the bp back on the waitq */
6687 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
6688 	}
6689 
6690 	/*
6691 	 * Decrement un_ncmds so that this
6692 	 * gets thru' st_start() again.
6693 	 */
6694 	un->un_ncmds--;
6695 
6696 	if (queued) {
6697 		/*
6698 		 * since this is an error case, we won't have to do this list
6699 		 * walking much. We've already made sure this bp was the
6700 		 * last on the runq
6701 		 */
6702 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6703 
6704 		/*
6705 		 * send a marker pkt, if appropriate
6706 		 */
6707 		st_hba_unflush(un);
6708 
6709 	}
6710 	/*
6711 	 * all queues are aligned, we are just waiting to
6712 	 * transport, don't alloc any more buf p's, when
6713 	 * st_start is reentered.
6714 	 */
6715 	(void) timeout(st_start_restart, un, timeout_interval);
6716 
6717 	mutex_exit(ST_MUTEX);
6718 	return (0);
6719 }
6720 
6721 
6722 /*
6723  * st_runout a callback that is called what a resource allocatation failed
6724  */
6725 static int
6726 st_runout(caddr_t arg)
6727 {
6728 	struct scsi_tape *un = (struct scsi_tape *)arg;
6729 	struct buf *bp;
6730 	int queued;
6731 
6732 	ASSERT(un != NULL);
6733 
6734 	ST_FUNC(ST_DEVINFO, st_runout);
6735 
6736 	mutex_enter(ST_MUTEX);
6737 
6738 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6739 
6740 	if (un->un_recov_buf_busy != 0) {
6741 		bp = un->un_recov_buf;
6742 		queued = 0;
6743 	} else if (un->un_sbuf_busy != 0) {
6744 		/* sbuf commands should only happen with an empty queue. */
6745 		ASSERT(un->un_quef == NULL);
6746 		ASSERT(un->un_runqf == NULL);
6747 		bp = un->un_sbufp;
6748 		queued = 0;
6749 	} else if (un->un_quef != NULL) {
6750 		bp = un->un_quef;
6751 		if (un->un_persistence && un->un_persist_errors) {
6752 			mutex_exit(ST_MUTEX);
6753 			bp->b_resid = bp->b_bcount;
6754 			biodone(bp);
6755 			return (1);
6756 		}
6757 		queued = 1;
6758 	} else {
6759 		ASSERT(1 == 0);
6760 		mutex_exit(ST_MUTEX);
6761 		return (1);
6762 	}
6763 
6764 	/*
6765 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6766 	 */
6767 	if ((bp != NULL) && (geterror(bp) != 0)) {
6768 
6769 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6770 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6771 		    bp->b_flags, geterror(bp));
6772 		ASSERT((bp->b_flags & B_DONE) == 0);
6773 
6774 		if (queued) {
6775 			(void) st_remove_from_queue(&un->un_quef, &un->un_quel,
6776 			    bp);
6777 		}
6778 		mutex_exit(ST_MUTEX);
6779 
6780 		ASSERT((bp->b_flags & B_DONE) == 0);
6781 
6782 		/*
6783 		 * Set resid, Error already set, then unblock calling thread.
6784 		 */
6785 		bp->b_resid = bp->b_bcount;
6786 		biodone(bp);
6787 	} else {
6788 		/*
6789 		 * Try Again
6790 		 */
6791 		st_start(un);
6792 		mutex_exit(ST_MUTEX);
6793 	}
6794 
6795 	/*
6796 	 * Comments courtesy of sd.c
6797 	 * The scsi_init_pkt routine allows for the callback function to
6798 	 * return a 0 indicating the callback should be rescheduled or a 1
6799 	 * indicating not to reschedule. This routine always returns 1
6800 	 * because the driver always provides a callback function to
6801 	 * scsi_init_pkt. This results in a callback always being scheduled
6802 	 * (via the scsi_init_pkt callback implementation) if a resource
6803 	 * failure occurs.
6804 	 */
6805 
6806 	return (1);
6807 }
6808 
6809 /*
6810  * st_done_and_mutex_exit()
6811  *	- remove bp from runq
6812  *	- start up the next request
6813  *	- if this was an asynch bp, clean up
6814  *	- exit with released mutex
6815  */
6816 static void
6817 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6818 {
6819 	int pe_flagged = 0;
6820 	struct scsi_pkt *pkt = BP_PKT(bp);
6821 	pkt_info *pktinfo = pkt->pkt_private;
6822 
6823 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6824 #if !defined(lint)
6825 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6826 #endif
6827 
6828 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6829 
6830 	ASSERT(mutex_owned(ST_MUTEX));
6831 
6832 	(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6833 
6834 	un->un_ncmds--;
6835 	cv_signal(&un->un_queue_cv);
6836 
6837 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6838 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6839 	    "0x%x\n", pkt->pkt_cdbp[0], bp->b_bcount,
6840 	    bp->b_resid, bp->b_flags);
6841 
6842 
6843 	/*
6844 	 * update kstats with transfer count info
6845 	 */
6846 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6847 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6848 		if (bp->b_flags & B_READ) {
6849 			IOSP->reads++;
6850 			IOSP->nread += n_done;
6851 		} else {
6852 			IOSP->writes++;
6853 			IOSP->nwritten += n_done;
6854 		}
6855 	}
6856 
6857 	/*
6858 	 * Start the next one before releasing resources on this one, if
6859 	 * there is something on the queue and persistent errors has not been
6860 	 * flagged
6861 	 */
6862 
6863 	if ((pe_flagged = (un->un_persistence && un->un_persist_errors)) != 0) {
6864 		un->un_last_resid = bp->b_resid;
6865 		un->un_last_count = bp->b_bcount;
6866 	}
6867 
6868 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6869 		cv_broadcast(&un->un_tape_busy_cv);
6870 	} else if (un->un_quef && un->un_throttle && !pe_flagged &&
6871 	    (bp != un->un_recov_buf)) {
6872 		st_start(un);
6873 	}
6874 
6875 	un->un_retry_ct = max(pktinfo->pkt_retry_cnt, pktinfo->str_retry_cnt);
6876 
6877 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6878 		/*
6879 		 * Since we marked this ourselves as ASYNC,
6880 		 * there isn't anybody around waiting for
6881 		 * completion any more.
6882 		 */
6883 		uchar_t *cmd = pkt->pkt_cdbp;
6884 		if (*cmd == SCMD_READ || *cmd == SCMD_WRITE) {
6885 			bp->b_un.b_addr = (caddr_t)0;
6886 		}
6887 		ST_DEBUG(ST_DEVINFO, st_label, CE_NOTE,
6888 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6889 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
6890 		    "CDB sent with B_ASYNC",  (caddr_t)cmd);
6891 		if (pkt) {
6892 			scsi_destroy_pkt(pkt);
6893 		}
6894 		un->un_sbuf_busy = 0;
6895 		cv_signal(&un->un_sbuf_cv);
6896 		mutex_exit(ST_MUTEX);
6897 		return;
6898 	}
6899 
6900 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6901 		/*
6902 		 * Copy status from scsi_pkt to uscsi_cmd
6903 		 * since st_uscsi_cmd needs it
6904 		 */
6905 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6906 	}
6907 
6908 
6909 #ifdef STDEBUG
6910 	if (((st_debug & 0x7) >= 4) &&
6911 	    (((un->un_pos.blkno % 100) == 0) ||
6912 	    (un->un_persistence && un->un_persist_errors))) {
6913 
6914 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6915 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6916 		    "un_errno = %d, un_pe = %d\n",
6917 		    un->un_ncmds, un->un_throttle, un->un_errno,
6918 		    un->un_persist_errors);
6919 	}
6920 
6921 #endif
6922 
6923 	mutex_exit(ST_MUTEX);
6924 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6925 	    "st_done_and_mutex_exit: freeing pkt\n");
6926 
6927 	if (pkt) {
6928 		scsi_destroy_pkt(pkt);
6929 	}
6930 
6931 	biodone(bp);
6932 
6933 	/*
6934 	 * now that we biodoned that command, if persistent errors have been
6935 	 * flagged, flush the waitq
6936 	 */
6937 	if (pe_flagged)
6938 		st_flush(un);
6939 }
6940 
6941 
6942 /*
6943  * Tape error, flush tape driver queue.
6944  */
6945 static void
6946 st_flush(struct scsi_tape *un)
6947 {
6948 	struct buf *bp;
6949 
6950 	ST_FUNC(ST_DEVINFO, st_flush);
6951 
6952 	mutex_enter(ST_MUTEX);
6953 
6954 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6955 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6956 	    un->un_ncmds, (void *)un->un_quef);
6957 
6958 	/*
6959 	 * if we still have commands outstanding, wait for them to come in
6960 	 * before flushing the queue, and make sure there is a queue
6961 	 */
6962 	if (un->un_ncmds || !un->un_quef)
6963 		goto exit;
6964 
6965 	/*
6966 	 * we have no more commands outstanding, so let's deal with special
6967 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6968 	 * is 0, then we know there was no error and we return a 0 read or
6969 	 * write before showing errors
6970 	 */
6971 
6972 	/* Flush the wait queue. */
6973 	while ((bp = un->un_quef) != NULL) {
6974 		un->un_quef = bp->b_actf;
6975 
6976 		bp->b_resid = bp->b_bcount;
6977 
6978 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6979 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6980 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6981 
6982 		st_set_pe_errno(un);
6983 
6984 		bioerror(bp, un->un_errno);
6985 
6986 		mutex_exit(ST_MUTEX);
6987 		/* it should have one, but check anyway */
6988 		if (BP_PKT(bp)) {
6989 			scsi_destroy_pkt(BP_PKT(bp));
6990 		}
6991 		biodone(bp);
6992 		mutex_enter(ST_MUTEX);
6993 	}
6994 
6995 	/*
6996 	 * It's not a bad practice to reset the
6997 	 * waitq tail pointer to NULL.
6998 	 */
6999 	un->un_quel = NULL;
7000 
7001 exit:
7002 	/* we mucked with the queue, so let others know about it */
7003 	cv_signal(&un->un_queue_cv);
7004 	mutex_exit(ST_MUTEX);
7005 }
7006 
7007 
7008 /*
7009  * Utility functions
7010  */
7011 static int
7012 st_determine_generic(struct scsi_tape *un)
7013 {
7014 	int bsize;
7015 	static char *cart = "0.25 inch cartridge";
7016 	char *sizestr;
7017 
7018 	ST_FUNC(ST_DEVINFO, st_determine_generic);
7019 
7020 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7021 	    "st_determine_generic(un = 0x%p)\n", (void*)un);
7022 
7023 	ASSERT(mutex_owned(ST_MUTEX));
7024 
7025 	if (st_modesense(un)) {
7026 		return (-1);
7027 	}
7028 
7029 	bsize = (un->un_mspl->high_bl << 16)	|
7030 	    (un->un_mspl->mid_bl << 8)	|
7031 	    (un->un_mspl->low_bl);
7032 
7033 	if (bsize == 0) {
7034 		un->un_dp->options |= ST_VARIABLE;
7035 		un->un_dp->bsize = 0;
7036 		un->un_bsize = 0;
7037 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
7038 		/*
7039 		 * record size of this device too big.
7040 		 * try and convert it to variable record length.
7041 		 *
7042 		 */
7043 		un->un_dp->options |= ST_VARIABLE;
7044 		if (st_change_block_size(un, 0) != 0) {
7045 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7046 			    "Fixed Record Size %d is too large\n", bsize);
7047 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7048 			    "Cannot switch to variable record size\n");
7049 			un->un_dp->options &= ~ST_VARIABLE;
7050 			return (-1);
7051 		}
7052 	} else if (st_change_block_size(un, 0) == 0) {
7053 		/*
7054 		 * If the drive was set to a non zero block size,
7055 		 * See if it can be set to a zero block size.
7056 		 * If it works, ST_VARIABLE so user can set it as they want.
7057 		 */
7058 		un->un_dp->options |= ST_VARIABLE;
7059 		un->un_dp->bsize = 0;
7060 		un->un_bsize = 0;
7061 	} else {
7062 		un->un_dp->bsize = bsize;
7063 		un->un_bsize = bsize;
7064 	}
7065 
7066 
7067 	switch (un->un_mspl->density) {
7068 	default:
7069 	case 0x0:
7070 		/*
7071 		 * default density, cannot determine any other
7072 		 * information.
7073 		 */
7074 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
7075 		un->un_dp->type = ST_TYPE_DEFAULT;
7076 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
7077 		break;
7078 	case 0x1:
7079 	case 0x2:
7080 	case 0x3:
7081 	case 0x6:
7082 		/*
7083 		 * 1/2" reel
7084 		 */
7085 		sizestr = "0.50 inch reel";
7086 		un->un_dp->type = ST_TYPE_REEL;
7087 		un->un_dp->options |= ST_REEL;
7088 		un->un_dp->densities[0] = 0x1;
7089 		un->un_dp->densities[1] = 0x2;
7090 		un->un_dp->densities[2] = 0x6;
7091 		un->un_dp->densities[3] = 0x3;
7092 		break;
7093 	case 0x4:
7094 	case 0x5:
7095 	case 0x7:
7096 	case 0x0b:
7097 
7098 		/*
7099 		 * Quarter inch.
7100 		 */
7101 		sizestr = cart;
7102 		un->un_dp->type = ST_TYPE_DEFAULT;
7103 		un->un_dp->options |= ST_QIC;
7104 
7105 		un->un_dp->densities[1] = 0x4;
7106 		un->un_dp->densities[2] = 0x5;
7107 		un->un_dp->densities[3] = 0x7;
7108 		un->un_dp->densities[0] = 0x0b;
7109 		break;
7110 
7111 	case 0x0f:
7112 	case 0x10:
7113 	case 0x11:
7114 	case 0x12:
7115 		/*
7116 		 * QIC-120, QIC-150, QIC-320, QIC-600
7117 		 */
7118 		sizestr = cart;
7119 		un->un_dp->type = ST_TYPE_DEFAULT;
7120 		un->un_dp->options |= ST_QIC;
7121 		un->un_dp->densities[0] = 0x0f;
7122 		un->un_dp->densities[1] = 0x10;
7123 		un->un_dp->densities[2] = 0x11;
7124 		un->un_dp->densities[3] = 0x12;
7125 		break;
7126 
7127 	case 0x09:
7128 	case 0x0a:
7129 	case 0x0c:
7130 	case 0x0d:
7131 		/*
7132 		 * 1/2" cartridge tapes. Include HI-TC.
7133 		 */
7134 		sizestr = cart;
7135 		sizestr[2] = '5';
7136 		sizestr[3] = '0';
7137 		un->un_dp->type = ST_TYPE_HIC;
7138 		un->un_dp->densities[0] = 0x09;
7139 		un->un_dp->densities[1] = 0x0a;
7140 		un->un_dp->densities[2] = 0x0c;
7141 		un->un_dp->densities[3] = 0x0d;
7142 		break;
7143 
7144 	case 0x13:
7145 			/* DDS-2/DDS-3 scsi spec densities */
7146 	case 0x24:
7147 	case 0x25:
7148 	case 0x26:
7149 		sizestr = "DAT Data Storage (DDS)";
7150 		un->un_dp->type = ST_TYPE_DAT;
7151 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7152 		break;
7153 
7154 	case 0x14:
7155 		/*
7156 		 * Helical Scan (Exabyte) devices
7157 		 */
7158 		sizestr = "8mm helical scan cartridge";
7159 		un->un_dp->type = ST_TYPE_EXABYTE;
7160 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7161 		break;
7162 	}
7163 
7164 	/*
7165 	 * Assume LONG ERASE, BSF and BSR
7166 	 */
7167 
7168 	un->un_dp->options |=
7169 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
7170 
7171 	/*
7172 	 * Only if mode sense data says no buffered write, set NOBUF
7173 	 */
7174 	if (un->un_mspl->bufm == 0)
7175 		un->un_dp->options |= ST_NOBUF;
7176 
7177 	/*
7178 	 * set up large read and write retry counts
7179 	 */
7180 
7181 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
7182 
7183 	/*
7184 	 * If this is a 0.50 inch reel tape, and
7185 	 * it is *not* variable mode, try and
7186 	 * set it to variable record length
7187 	 * mode.
7188 	 */
7189 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
7190 	    (un->un_dp->options & ST_VARIABLE)) {
7191 		if (st_change_block_size(un, 0) == 0) {
7192 			un->un_dp->bsize = 0;
7193 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
7194 			    un->un_mspl->low_bl = 0;
7195 		}
7196 	}
7197 
7198 	/*
7199 	 * Write to console about type of device found
7200 	 */
7201 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
7202 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
7203 	    sizestr);
7204 	if (un->un_dp->options & ST_VARIABLE) {
7205 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7206 		    "!Variable record length I/O\n");
7207 	} else {
7208 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7209 		    "!Fixed record length (%d byte blocks) I/O\n",
7210 		    un->un_dp->bsize);
7211 	}
7212 	ASSERT(mutex_owned(ST_MUTEX));
7213 	return (0);
7214 }
7215 
7216 static int
7217 st_determine_density(struct scsi_tape *un, int rw)
7218 {
7219 	int rval = 0;
7220 
7221 	ST_FUNC(ST_DEVINFO, st_determine_density);
7222 
7223 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7224 	    "st_determine_density(un = 0x%p, rw = %s)\n",
7225 	    (void*)un, (rw == B_WRITE ? wr_str: rd_str));
7226 
7227 	ASSERT(mutex_owned(ST_MUTEX));
7228 
7229 	/*
7230 	 * If we're past BOT, density is determined already.
7231 	 */
7232 	if (un->un_pos.pmode == logical) {
7233 		if (un->un_pos.lgclblkno != 0) {
7234 			goto exit;
7235 		}
7236 	} else if (un->un_pos.pmode == legacy) {
7237 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
7238 			/*
7239 			 * XXX: put in a bitch message about attempting to
7240 			 * XXX: change density past BOT.
7241 			 */
7242 			goto exit;
7243 		}
7244 	} else {
7245 		goto exit;
7246 	}
7247 	if ((un->un_pos.pmode == logical) &&
7248 	    (un->un_pos.lgclblkno != 0)) {
7249 		goto exit;
7250 	}
7251 
7252 
7253 	/*
7254 	 * If we're going to be writing, we set the density
7255 	 */
7256 	if (rw == 0 || rw == B_WRITE) {
7257 		/* un_curdens is used as an index into densities table */
7258 		un->un_curdens = MT_DENSITY(un->un_dev);
7259 		if (st_set_density(un)) {
7260 			rval = -1;
7261 		}
7262 		goto exit;
7263 	}
7264 
7265 	/*
7266 	 * If density is known already,
7267 	 * we don't have to get it again.(?)
7268 	 */
7269 	if (!un->un_density_known) {
7270 		if (st_get_density(un)) {
7271 			rval = -1;
7272 		}
7273 	}
7274 
7275 exit:
7276 	ASSERT(mutex_owned(ST_MUTEX));
7277 	return (rval);
7278 }
7279 
7280 
7281 /*
7282  * Try to determine density. We do this by attempting to read the
7283  * first record off the tape, cycling through the available density
7284  * codes as we go.
7285  */
7286 
7287 static int
7288 st_get_density(struct scsi_tape *un)
7289 {
7290 	int succes = 0, rval = -1, i;
7291 	uint_t size;
7292 	uchar_t dens, olddens;
7293 
7294 	ST_FUNC(ST_DEVINFO, st_get_density);
7295 
7296 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7297 	    "st_get_density(un = 0x%p)\n", (void*)un);
7298 
7299 	ASSERT(mutex_owned(ST_MUTEX));
7300 
7301 	/*
7302 	 * If Auto Density override is enabled The drive has
7303 	 * only one density and there is no point in attempting
7304 	 * find the correct one.
7305 	 *
7306 	 * Since most modern drives auto detect the density
7307 	 * and format of the recorded media before they come
7308 	 * ready. What this function does is a legacy behavior
7309 	 * and modern drives not only don't need it, The backup
7310 	 * utilities that do positioning via uscsi find the un-
7311 	 * expected rewinds problematic.
7312 	 *
7313 	 * The drives that need this are old reel to reel devices.
7314 	 * I took a swag and said they must be scsi-1 or older.
7315 	 * I don't beleave there will any of the newer devices
7316 	 * that need this. There will be some scsi-1 devices that
7317 	 * don't need this but I don't think they will be using the
7318 	 * BIG aftermarket backup and restore utilitys.
7319 	 */
7320 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
7321 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
7322 		un->un_density_known = 1;
7323 		rval = 0;
7324 		goto exit;
7325 	}
7326 
7327 	/*
7328 	 * This will only work on variable record length tapes
7329 	 * if and only if all variable record length tapes autodensity
7330 	 * select.
7331 	 */
7332 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
7333 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
7334 
7335 	/*
7336 	 * Start at the specified density
7337 	 */
7338 
7339 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
7340 
7341 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
7342 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
7343 		/*
7344 		 * If we've done this density before,
7345 		 * don't bother to do it again.
7346 		 */
7347 		dens = un->un_dp->densities[un->un_curdens];
7348 		if (i > 0 && dens == olddens)
7349 			continue;
7350 		olddens = dens;
7351 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7352 		    "trying density 0x%x\n", dens);
7353 		if (st_set_density(un)) {
7354 			continue;
7355 		}
7356 
7357 		/*
7358 		 * XXX - the creates lots of headaches and slowdowns - must
7359 		 * fix.
7360 		 */
7361 		succes = (st_cmd(un, SCMD_READ, (int)size, SYNC_CMD) == 0);
7362 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
7363 			break;
7364 		}
7365 		if (succes) {
7366 			st_init(un);
7367 			rval = 0;
7368 			un->un_density_known = 1;
7369 			break;
7370 		}
7371 	}
7372 	kmem_free(un->un_tmpbuf, size);
7373 	un->un_tmpbuf = 0;
7374 
7375 exit:
7376 	ASSERT(mutex_owned(ST_MUTEX));
7377 	return (rval);
7378 }
7379 
7380 static int
7381 st_set_density(struct scsi_tape *un)
7382 {
7383 	int rval = 0;
7384 
7385 	ST_FUNC(ST_DEVINFO, st_set_density);
7386 
7387 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7388 	    "st_set_density(un = 0x%p): density = 0x%x\n", (void*)un,
7389 	    un->un_dp->densities[un->un_curdens]);
7390 
7391 	ASSERT(mutex_owned(ST_MUTEX));
7392 
7393 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7394 
7395 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
7396 		/*
7397 		 * If auto density override is not set, Use mode select
7398 		 * to set density and compression.
7399 		 */
7400 		if (st_modeselect(un)) {
7401 			rval = -1;
7402 		}
7403 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
7404 		/*
7405 		 * If auto density and mode select compression are set,
7406 		 * This is a drive with one density code but compression
7407 		 * can be enabled or disabled.
7408 		 * Set compression but no need to set density.
7409 		 */
7410 		rval = st_set_compression(un);
7411 		if ((rval != 0) && (rval != EALREADY)) {
7412 			rval = -1;
7413 		} else {
7414 			rval = 0;
7415 		}
7416 	}
7417 
7418 	/* If sucessful set density and/or compression, mark density known */
7419 	if (rval == 0) {
7420 		un->un_density_known = 1;
7421 	}
7422 
7423 	ASSERT(mutex_owned(ST_MUTEX));
7424 	return (rval);
7425 }
7426 
7427 static int
7428 st_loadtape(struct scsi_tape *un)
7429 {
7430 	int rval;
7431 
7432 	ST_FUNC(ST_DEVINFO, st_loadtape);
7433 
7434 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7435 	    "st_loadtape(un = 0x%p)\n", (void*) un);
7436 
7437 	ASSERT(mutex_owned(ST_MUTEX));
7438 
7439 	rval = st_update_block_pos(un, st_cmd, 0);
7440 	if (rval == EACCES) {
7441 		return (rval);
7442 	}
7443 
7444 	/*
7445 	 * 'LOAD' the tape to BOT by rewinding
7446 	 */
7447 	rval = st_cmd(un, SCMD_REWIND, 1, SYNC_CMD);
7448 	if (rval == 0) {
7449 		st_init(un);
7450 		un->un_density_known = 0;
7451 	}
7452 
7453 	ASSERT(mutex_owned(ST_MUTEX));
7454 	return (rval);
7455 }
7456 
7457 
7458 /*
7459  * Note: QIC devices aren't so smart.  If you try to append
7460  * after EOM, the write can fail because the device doesn't know
7461  * it's at EOM.	 In that case, issue a read.  The read should fail
7462  * because there's no data, but the device knows it's at EOM,
7463  * so a subsequent write should succeed.  To further confuse matters,
7464  * the target returns the same error if the tape is positioned
7465  * such that a write would overwrite existing data.  That's why
7466  * we have to do the append test.  A read in the middle of
7467  * recorded data would succeed, thus indicating we're attempting
7468  * something illegal.
7469  */
7470 
7471 
7472 static void
7473 st_test_append(struct buf *bp)
7474 {
7475 	dev_t dev = bp->b_edev;
7476 	struct scsi_tape *un;
7477 	uchar_t status;
7478 	unsigned bcount;
7479 
7480 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7481 
7482 	ST_FUNC(ST_DEVINFO, st_test_append);
7483 
7484 	ASSERT(mutex_owned(ST_MUTEX));
7485 
7486 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7487 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7488 
7489 	un->un_laststate = un->un_state;
7490 	un->un_state = ST_STATE_APPEND_TESTING;
7491 	un->un_test_append = 0;
7492 
7493 	/*
7494 	 * first, map in the buffer, because we're doing a double write --
7495 	 * first into the kernel, then onto the tape.
7496 	 */
7497 	bp_mapin(bp);
7498 
7499 	/*
7500 	 * get a copy of the data....
7501 	 */
7502 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7503 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7504 
7505 	/*
7506 	 * attempt the write..
7507 	 */
7508 
7509 	if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7510 success:
7511 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7512 		    "append write succeeded\n");
7513 		bp->b_resid = un->un_sbufp->b_resid;
7514 		mutex_exit(ST_MUTEX);
7515 		bcount = (unsigned)bp->b_bcount;
7516 		biodone(bp);
7517 		mutex_enter(ST_MUTEX);
7518 		un->un_laststate = un->un_state;
7519 		un->un_state = ST_STATE_OPEN;
7520 		kmem_free(un->un_tmpbuf, bcount);
7521 		un->un_tmpbuf = NULL;
7522 		return;
7523 	}
7524 
7525 	/*
7526 	 * The append failed. Do a short read. If that fails,  we are at EOM
7527 	 * so we can retry the write command. If that succeeds, than we're
7528 	 * all screwed up (the controller reported a real error).
7529 	 *
7530 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7531 	 * XXX: block size?
7532 	 *
7533 	 */
7534 	status = un->un_status;
7535 	un->un_status = 0;
7536 	(void) st_cmd(un, SCMD_READ, SECSIZE, SYNC_CMD);
7537 	if (un->un_status == KEY_BLANK_CHECK) {
7538 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7539 		    "append at EOM\n");
7540 		/*
7541 		 * Okay- the read failed. We should actually have confused
7542 		 * the controller enough to allow writing. In any case, the
7543 		 * i/o is on its own from here on out.
7544 		 */
7545 		un->un_laststate = un->un_state;
7546 		un->un_state = ST_STATE_OPEN;
7547 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7548 		if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount,
7549 		    SYNC_CMD) == 0) {
7550 			goto success;
7551 		}
7552 	}
7553 
7554 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7555 	    "append write failed- not at EOM\n");
7556 	bp->b_resid = bp->b_bcount;
7557 	st_bioerror(bp, EIO);
7558 
7559 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7560 	    "st_test_append : EIO : append write failed - not at EOM");
7561 
7562 	/*
7563 	 * backspace one record to get back to where we were
7564 	 */
7565 	if (st_cmd(un, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7566 		un->un_pos.pmode = invalid;
7567 	}
7568 
7569 	un->un_err_resid = bp->b_resid;
7570 	un->un_status = status;
7571 
7572 	/*
7573 	 * Note: biodone will do a bp_mapout()
7574 	 */
7575 	mutex_exit(ST_MUTEX);
7576 	bcount = (unsigned)bp->b_bcount;
7577 	biodone(bp);
7578 	mutex_enter(ST_MUTEX);
7579 	un->un_laststate = un->un_state;
7580 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7581 	kmem_free(un->un_tmpbuf, bcount);
7582 	un->un_tmpbuf = NULL;
7583 }
7584 
7585 /*
7586  * Special command handler
7587  */
7588 
7589 /*
7590  * common st_cmd code. The fourth parameter states
7591  * whether the caller wishes to await the results
7592  * Note the release of the mutex during most of the function
7593  */
7594 static int
7595 st_cmd(struct scsi_tape *un, int com, int64_t count, int wait)
7596 {
7597 	struct buf *bp;
7598 	int err;
7599 	uint_t last_err_resid;
7600 
7601 	ST_FUNC(ST_DEVINFO, st_cmd);
7602 
7603 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7604 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %"PRIx64", wait = %d)\n",
7605 	    un->un_dev, com, count, wait);
7606 
7607 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7608 	ASSERT(mutex_owned(ST_MUTEX));
7609 
7610 #ifdef STDEBUG
7611 	if ((st_debug & 0x7)) {
7612 		st_debug_cmds(un, com, count, wait);
7613 	}
7614 #endif
7615 
7616 	st_wait_for_io(un);
7617 
7618 	/* check to see if this command requires the drive to be reserved */
7619 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7620 
7621 	if (err) {
7622 		return (err);
7623 	}
7624 
7625 	/*
7626 	 * A space command is not recoverable if we don't know were we
7627 	 * were when it was issued.
7628 	 */
7629 	if ((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) {
7630 		(void) st_update_block_pos(un, st_cmd, 0);
7631 	}
7632 
7633 	/*
7634 	 * Forground should not be doing anything while recovery is active.
7635 	 */
7636 	ASSERT(un->un_recov_buf_busy == 0);
7637 
7638 	while (un->un_sbuf_busy)
7639 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7640 	un->un_sbuf_busy = 1;
7641 
7642 	bp = un->un_sbufp;
7643 	bzero(bp, sizeof (buf_t));
7644 
7645 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7646 
7647 	err = st_setup_cmd(un, bp, com, count);
7648 
7649 	un->un_sbuf_busy = 0;
7650 
7651 	/*
7652 	 * If was a space command need to update logical block position.
7653 	 * Only do this if the command was sucessful or it will mask the fact
7654 	 * that the space command failed by promoting the pmode to logical.
7655 	 */
7656 	if (((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) &&
7657 	    (un->un_pos.pmode != invalid)) {
7658 		un->un_running.pmode = invalid;
7659 		last_err_resid = un->un_err_resid;
7660 		(void) st_update_block_pos(un, st_cmd, 1);
7661 		/*
7662 		 * Set running position to invalid so it updates on the
7663 		 * next command.
7664 		 */
7665 		un->un_running.pmode = invalid;
7666 		un->un_err_resid = last_err_resid;
7667 	}
7668 
7669 	cv_signal(&un->un_sbuf_cv);
7670 
7671 	return (err);
7672 }
7673 
7674 static int
7675 st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com, int64_t count)
7676 {
7677 	int err;
7678 	dev_t dev = un->un_dev;
7679 
7680 	ST_FUNC(ST_DEVINFO, st_setup_cmd);
7681 	/*
7682 	 * Set count to the actual size of the data tranfer.
7683 	 * For commands with no data transfer, set bp->b_bcount
7684 	 * to the value to be used when constructing the
7685 	 * cdb in st_make_cmd().
7686 	 */
7687 	switch (com) {
7688 	case SCMD_READ:
7689 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7690 		    "special read %"PRId64"\n", count);
7691 		bp->b_flags |= B_READ;
7692 		bp->b_un.b_addr = un->un_tmpbuf;
7693 		break;
7694 
7695 	case SCMD_WRITE:
7696 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7697 		    "special write %"PRId64"\n", count);
7698 		bp->b_un.b_addr = un->un_tmpbuf;
7699 		break;
7700 
7701 	case SCMD_WRITE_FILE_MARK:
7702 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7703 		    "write %"PRId64" file marks\n", count);
7704 		bp->b_bcount = count;
7705 		count = 0;
7706 		break;
7707 
7708 	case SCMD_REWIND:
7709 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7710 		bp->b_bcount = count;
7711 		count = 0;
7712 		break;
7713 
7714 	case SCMD_SPACE:
7715 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7716 		/*
7717 		 * If the user could have entered a number that will
7718 		 * not fit in the 12 bit count field of space(8),
7719 		 * use space(16).
7720 		 */
7721 		if (((int64_t)SPACE_CNT(count) > 0x7fffff) ||
7722 		    ((int64_t)SPACE_CNT(count) < -(0x7fffff))) {
7723 			com = SCMD_SPACE_G4;
7724 		}
7725 		bp->b_bcount = count;
7726 		count = 0;
7727 		break;
7728 
7729 	case SCMD_RESERVE:
7730 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7731 		bp->b_bcount = 0;
7732 		count = 0;
7733 		break;
7734 
7735 	case SCMD_RELEASE:
7736 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7737 		bp->b_bcount = 0;
7738 		count = 0;
7739 		break;
7740 
7741 	case SCMD_LOAD:
7742 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7743 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7744 		bp->b_bcount = count;
7745 		count = 0;
7746 		break;
7747 
7748 	case SCMD_ERASE:
7749 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7750 		    "erase tape\n");
7751 		bp->b_bcount = count;
7752 		count = 0;
7753 		break;
7754 
7755 	case SCMD_MODE_SENSE:
7756 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7757 		    "mode sense\n");
7758 		bp->b_flags |= B_READ;
7759 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7760 		break;
7761 
7762 	case SCMD_MODE_SELECT:
7763 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7764 		    "mode select\n");
7765 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7766 		break;
7767 
7768 	case SCMD_READ_BLKLIM:
7769 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7770 		    "read block limits\n");
7771 		bp->b_bcount = count;
7772 		bp->b_flags |= B_READ;
7773 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7774 		break;
7775 
7776 	case SCMD_TEST_UNIT_READY:
7777 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7778 		    "test unit ready\n");
7779 		bp->b_bcount = 0;
7780 		count = 0;
7781 		break;
7782 
7783 	case SCMD_DOORLOCK:
7784 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7785 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7786 		bp->b_bcount = count = 0;
7787 		break;
7788 
7789 	case SCMD_READ_POSITION:
7790 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7791 		    "read position\n");
7792 		switch (un->un_read_pos_type) {
7793 		case LONG_POS:
7794 			count = sizeof (tape_position_long_t);
7795 			break;
7796 		case EXT_POS:
7797 			count = min(count, sizeof (tape_position_ext_t));
7798 			break;
7799 		case SHORT_POS:
7800 			count = sizeof (tape_position_t);
7801 			break;
7802 		default:
7803 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7804 			    "Unknown read position type 0x%x in "
7805 			    "st_make_cmd()\n", un->un_read_pos_type);
7806 		}
7807 		bp->b_bcount = count;
7808 		bp->b_flags |= B_READ;
7809 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7810 		break;
7811 
7812 	default:
7813 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7814 		    "Unhandled scsi command 0x%x in st_setup_cmd()\n", com);
7815 	}
7816 
7817 	mutex_exit(ST_MUTEX);
7818 
7819 	if (count > 0) {
7820 		int flg = (bp->b_flags & B_READ) ? B_READ : B_WRITE;
7821 		/*
7822 		 * We're going to do actual I/O.
7823 		 * Set things up for physio.
7824 		 */
7825 		struct iovec aiov;
7826 		struct uio auio;
7827 		struct uio *uio = &auio;
7828 
7829 		bzero(&auio, sizeof (struct uio));
7830 		bzero(&aiov, sizeof (struct iovec));
7831 		aiov.iov_base = bp->b_un.b_addr;
7832 		aiov.iov_len = count;
7833 
7834 		uio->uio_iov = &aiov;
7835 		uio->uio_iovcnt = 1;
7836 		uio->uio_resid = aiov.iov_len;
7837 		uio->uio_segflg = UIO_SYSSPACE;
7838 
7839 		/*
7840 		 * Let physio do the rest...
7841 		 */
7842 		bp->b_forw = (struct buf *)(uintptr_t)com;
7843 		bp->b_back = NULL;
7844 		err = physio(st_strategy, bp, dev, flg, st_minphys, uio);
7845 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7846 		    "st_setup_cmd: physio returns %d\n", err);
7847 	} else {
7848 		/*
7849 		 * Mimic physio
7850 		 */
7851 		bp->b_forw = (struct buf *)(uintptr_t)com;
7852 		bp->b_back = NULL;
7853 		bp->b_edev = dev;
7854 		bp->b_dev = cmpdev(dev);
7855 		bp->b_blkno = 0;
7856 		bp->b_resid = 0;
7857 		(void) st_strategy(bp);
7858 		if (bp->b_flags & B_ASYNC) {
7859 			/*
7860 			 * This is an async command- the caller won't wait
7861 			 * and doesn't care about errors.
7862 			 */
7863 			mutex_enter(ST_MUTEX);
7864 			return (0);
7865 		}
7866 
7867 		/*
7868 		 * BugTraq #4260046
7869 		 * ----------------
7870 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7871 		 * unconditionally. The old comment said...
7872 		 *
7873 		 * "if strategy was flagged with  persistent errors, we would
7874 		 *  have an error here, and the bp would never be sent, so we
7875 		 *  don't want to wait on a bp that was never sent...or hang"
7876 		 *
7877 		 * The new rationale, courtesy of Chitrank...
7878 		 *
7879 		 * "we should unconditionally biowait() here because
7880 		 *  st_strategy() will do a biodone() in the persistent error
7881 		 *  case and the following biowait() will return immediately.
7882 		 *  If not, in the case of "errors after pkt alloc" in
7883 		 *  st_start(), we will not biowait here which will cause the
7884 		 *  next biowait() to return immediately which will cause
7885 		 *  us to send out the next command. In the case where both of
7886 		 *  these use the sbuf, when the first command completes we'll
7887 		 *  free the packet attached to sbuf and the same pkt will
7888 		 *  get freed again when we complete the second command.
7889 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7890 		 *  st_start() for the pkt alloc failure case because physio()
7891 		 *  does biowait() and will hang if we don't do biodone()"
7892 		 */
7893 
7894 		err = biowait(bp);
7895 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7896 		    "st_setup_cmd: biowait returns %d\n", err);
7897 	}
7898 
7899 	mutex_enter(ST_MUTEX);
7900 
7901 	return (err);
7902 }
7903 
7904 static int
7905 st_set_compression(struct scsi_tape *un)
7906 {
7907 	int rval;
7908 	int turn_compression_on;
7909 	minor_t minor;
7910 
7911 	ST_FUNC(ST_DEVINFO, st_set_compression);
7912 
7913 	/*
7914 	 * Drive either dosn't have compression or it is controlled with
7915 	 * special density codes. Return ENOTTY so caller
7916 	 * knows nothing was done.
7917 	 */
7918 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7919 		un->un_comp_page = 0;
7920 		return (ENOTTY);
7921 	}
7922 
7923 	/* set compression based on minor node opened */
7924 	minor = MT_DENSITY(un->un_dev);
7925 
7926 	/*
7927 	 * If this the compression density or
7928 	 * the drive has two densities and uses mode select for
7929 	 * control of compression turn on compression for MT_DENSITY2
7930 	 * as well.
7931 	 */
7932 	if ((minor == ST_COMPRESSION_DENSITY) ||
7933 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7934 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7935 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7936 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7937 
7938 		turn_compression_on = 1;
7939 	} else {
7940 		turn_compression_on = 0;
7941 	}
7942 
7943 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7944 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7945 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7946 
7947 	/*
7948 	 * Need to determine which page does the device use for compression.
7949 	 * First try the data compression page. If this fails try the device
7950 	 * configuration page
7951 	 */
7952 
7953 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7954 		rval = st_set_datacomp_page(un, turn_compression_on);
7955 		if (rval == EALREADY) {
7956 			return (rval);
7957 		}
7958 		if (rval != 0) {
7959 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7960 				/*
7961 				 * This device does not support data
7962 				 * compression page
7963 				 */
7964 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7965 			} else if (un->un_state >= ST_STATE_OPEN) {
7966 				un->un_pos.pmode = invalid;
7967 				rval = EIO;
7968 			} else {
7969 				rval = -1;
7970 			}
7971 		} else {
7972 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7973 		}
7974 	}
7975 
7976 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7977 		rval = st_set_devconfig_page(un, turn_compression_on);
7978 		if (rval == EALREADY) {
7979 			return (rval);
7980 		}
7981 		if (rval != 0) {
7982 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7983 				/*
7984 				 * This device does not support
7985 				 * compression at all advice the
7986 				 * user and unset ST_MODE_SEL_COMP
7987 				 */
7988 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7989 				un->un_comp_page = 0;
7990 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7991 				    "Device Does Not Support Compression\n");
7992 			} else if (un->un_state >= ST_STATE_OPEN) {
7993 				un->un_pos.pmode = invalid;
7994 				rval = EIO;
7995 			} else {
7996 				rval = -1;
7997 			}
7998 		}
7999 	}
8000 
8001 	return (rval);
8002 }
8003 
8004 /*
8005  * set or unset compression thru device configuration page.
8006  */
8007 static int
8008 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
8009 {
8010 	unsigned char cflag;
8011 	int rval = 0;
8012 
8013 
8014 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
8015 
8016 	ASSERT(mutex_owned(ST_MUTEX));
8017 
8018 	/*
8019 	 * if the mode sense page is not the correct one, load the correct one.
8020 	 */
8021 	if (un->un_mspl->page_code != ST_DEV_CONFIG_PAGE) {
8022 		rval = st_gen_mode_sense(un, st_uscsi_cmd, ST_DEV_CONFIG_PAGE,
8023 		    un->un_mspl, sizeof (struct seq_mode));
8024 		if (rval)
8025 			return (rval);
8026 	}
8027 
8028 	/*
8029 	 * Figure what to set compression flag to.
8030 	 */
8031 	if (compression_on) {
8032 		/* They have selected a compression node */
8033 		if (un->un_dp->type == ST_TYPE_FUJI) {
8034 			cflag = 0x84;   /* use EDRC */
8035 		} else {
8036 			cflag = ST_DEV_CONFIG_DEF_COMP;
8037 		}
8038 	} else {
8039 		cflag = ST_DEV_CONFIG_NO_COMP;
8040 	}
8041 
8042 	/*
8043 	 * If compression is already set the way it was requested.
8044 	 * And if this not the first time we has tried.
8045 	 */
8046 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
8047 	    (un->un_comp_page == ST_DEV_CONFIG_PAGE)) {
8048 		return (EALREADY);
8049 	}
8050 
8051 	un->un_mspl->page.dev.comp_alg = cflag;
8052 	/*
8053 	 * need to send mode select even if correct compression is
8054 	 * already set since need to set density code
8055 	 */
8056 
8057 #ifdef STDEBUG
8058 	if ((st_debug & 0x7) >= 6) {
8059 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8060 		    "st_set_devconfig_page: sense data for mode select",
8061 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8062 	}
8063 #endif
8064 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8065 	    sizeof (struct seq_mode));
8066 
8067 	return (rval);
8068 }
8069 
8070 /*
8071  * set/reset compression bit thru data compression page
8072  */
8073 static int
8074 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
8075 {
8076 	int compression_on_already;
8077 	int rval = 0;
8078 
8079 
8080 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
8081 
8082 	ASSERT(mutex_owned(ST_MUTEX));
8083 
8084 	/*
8085 	 * if the mode sense page is not the correct one, load the correct one.
8086 	 */
8087 	if (un->un_mspl->page_code != ST_DEV_DATACOMP_PAGE) {
8088 		rval = st_gen_mode_sense(un, st_uscsi_cmd, ST_DEV_DATACOMP_PAGE,
8089 		    un->un_mspl, sizeof (struct seq_mode));
8090 		if (rval)
8091 			return (rval);
8092 	}
8093 
8094 	/*
8095 	 * If drive is not capable of compression (at this time)
8096 	 * return EALREADY so caller doesn't think that this page
8097 	 * is not supported. This check is for drives that can
8098 	 * disable compression from the front panel or configuration.
8099 	 * I doubt that a drive that supports this page is not really
8100 	 * capable of compression.
8101 	 */
8102 	if (un->un_mspl->page.comp.dcc == 0) {
8103 		return (EALREADY);
8104 	}
8105 
8106 	/* See if compression currently turned on */
8107 	if (un->un_mspl->page.comp.dce) {
8108 		compression_on_already = 1;
8109 	} else {
8110 		compression_on_already = 0;
8111 	}
8112 
8113 	/*
8114 	 * If compression is already set the way it was requested.
8115 	 * And if this not the first time we has tried.
8116 	 */
8117 	if ((compression_on == compression_on_already) &&
8118 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
8119 		return (EALREADY);
8120 	}
8121 
8122 	/*
8123 	 * if we are already set to the appropriate compression
8124 	 * mode, don't set it again
8125 	 */
8126 	if (compression_on) {
8127 		/* compression selected */
8128 		un->un_mspl->page.comp.dce = 1;
8129 	} else {
8130 		un->un_mspl->page.comp.dce = 0;
8131 	}
8132 
8133 
8134 #ifdef STDEBUG
8135 	if ((st_debug & 0x7) >= 6) {
8136 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8137 		    "st_set_datacomp_page: sense data for mode select",
8138 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8139 	}
8140 #endif
8141 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8142 	    sizeof (struct seq_mode));
8143 
8144 	return (rval);
8145 }
8146 
8147 static int
8148 st_modesense(struct scsi_tape *un)
8149 {
8150 	int rval;
8151 	uchar_t page;
8152 
8153 	ST_FUNC(ST_DEVINFO, st_modesense);
8154 
8155 	page = un->un_comp_page;
8156 
8157 	switch (page) {
8158 	case ST_DEV_DATACOMP_PAGE:
8159 	case ST_DEV_CONFIG_PAGE: /* FALLTHROUGH */
8160 		rval = st_gen_mode_sense(un, st_uscsi_cmd, page, un->un_mspl,
8161 		    sizeof (struct seq_mode));
8162 		break;
8163 
8164 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
8165 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
8166 			page = ST_DEV_DATACOMP_PAGE;
8167 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8168 			    un->un_mspl, sizeof (struct seq_mode));
8169 			if (rval == 0 && un->un_mspl->page_code == page) {
8170 				un->un_comp_page = page;
8171 				break;
8172 			}
8173 			page = ST_DEV_CONFIG_PAGE;
8174 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8175 			    un->un_mspl, sizeof (struct seq_mode));
8176 			if (rval == 0 && un->un_mspl->page_code == page) {
8177 				un->un_comp_page = page;
8178 				break;
8179 			}
8180 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
8181 			un->un_comp_page = 0;
8182 		} else {
8183 			un->un_comp_page = 0;
8184 		}
8185 
8186 	default:	/* FALLTHROUGH */
8187 		rval = st_cmd(un, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
8188 	}
8189 	return (rval);
8190 }
8191 
8192 static int
8193 st_modeselect(struct scsi_tape *un)
8194 {
8195 	int rval = 0;
8196 	int ix;
8197 
8198 	ST_FUNC(ST_DEVINFO, st_modeselect);
8199 
8200 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8201 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
8202 	    un->un_dev, un->un_mspl->density);
8203 
8204 	ASSERT(mutex_owned(ST_MUTEX));
8205 
8206 	/*
8207 	 * The parameter list should be the same for all of the
8208 	 * cases that follow so set them here
8209 	 *
8210 	 * Try mode select first if if fails set fields manually
8211 	 */
8212 	rval = st_modesense(un);
8213 	if (rval != 0) {
8214 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8215 		    "st_modeselect: First mode sense failed\n");
8216 		un->un_mspl->bd_len  = 8;
8217 		un->un_mspl->high_nb = 0;
8218 		un->un_mspl->mid_nb  = 0;
8219 		un->un_mspl->low_nb  = 0;
8220 	}
8221 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
8222 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
8223 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
8224 
8225 
8226 	/*
8227 	 * If configured to use a specific density code for a media type.
8228 	 * curdens is previously set by the minor node opened.
8229 	 * If the media type doesn't match the minor node we change it so it
8230 	 * looks like the correct one was opened.
8231 	 */
8232 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
8233 		uchar_t best;
8234 
8235 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
8236 			if (un->un_mspl->media_type ==
8237 			    un->un_dp->mediatype[ix]) {
8238 				best = ix;
8239 				/*
8240 				 * It matches but it might not be the only one.
8241 				 * Use the highest matching media type but not
8242 				 * to exceed the density selected by the open.
8243 				 */
8244 				if (ix < un->un_curdens) {
8245 					continue;
8246 				}
8247 				un->un_curdens = ix;
8248 				break;
8249 			}
8250 		}
8251 		/* If a match was found best will not be 0xff any more */
8252 		if (best < NDENSITIES) {
8253 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8254 			    "found media 0x%X using density 0x%X\n",
8255 			    un->un_mspl->media_type,
8256 			    un->un_dp->densities[best]);
8257 			un->un_mspl->density = un->un_dp->densities[best];
8258 		} else {
8259 			/* Otherwise set density based on minor node opened */
8260 			un->un_mspl->density =
8261 			    un->un_dp->densities[un->un_curdens];
8262 		}
8263 	} else {
8264 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
8265 	}
8266 
8267 	if (un->un_dp->options & ST_NOBUF) {
8268 		un->un_mspl->bufm = 0;
8269 	} else {
8270 		un->un_mspl->bufm = 1;
8271 	}
8272 
8273 	rval = st_set_compression(un);
8274 
8275 	/*
8276 	 * If st_set_compression returned invalid or already it
8277 	 * found no need to do the mode select.
8278 	 * So do it here.
8279 	 */
8280 	if ((rval == ENOTTY) || (rval == EALREADY)) {
8281 
8282 		/* Zero non-writeable fields */
8283 		un->un_mspl->data_len = 0;
8284 		un->un_mspl->media_type = 0;
8285 		un->un_mspl->wp = 0;
8286 
8287 		/* need to set the density code */
8288 		rval = st_cmd(un, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
8289 		if (rval != 0) {
8290 			if (un->un_state >= ST_STATE_OPEN) {
8291 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8292 				    "unable to set tape mode\n");
8293 				un->un_pos.pmode = invalid;
8294 				rval = EIO;
8295 			} else {
8296 				rval = -1;
8297 			}
8298 		}
8299 	}
8300 
8301 	/*
8302 	 * The spec recommends to send a mode sense after a mode select
8303 	 */
8304 	(void) st_modesense(un);
8305 
8306 	ASSERT(mutex_owned(ST_MUTEX));
8307 
8308 	return (rval);
8309 }
8310 
8311 /*
8312  * st_gen_mode_sense
8313  *
8314  * generic mode sense.. it allows for any page
8315  */
8316 static int
8317 st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
8318     struct seq_mode *page_data, int page_size)
8319 {
8320 
8321 	int r;
8322 	char	cdb[CDB_GROUP0];
8323 	struct uscsi_cmd *com;
8324 	struct scsi_arq_status status;
8325 
8326 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
8327 
8328 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8329 
8330 	bzero(cdb, CDB_GROUP0);
8331 	cdb[0] = SCMD_MODE_SENSE;
8332 	cdb[2] = (char)page;
8333 	cdb[4] = (char)page_size;
8334 
8335 	com->uscsi_cdb = cdb;
8336 	com->uscsi_cdblen = CDB_GROUP0;
8337 	com->uscsi_bufaddr = (caddr_t)page_data;
8338 	com->uscsi_buflen = page_size;
8339 	com->uscsi_rqlen = sizeof (status);
8340 	com->uscsi_rqbuf = (caddr_t)&status;
8341 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8342 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8343 
8344 	r = ubf(un, com, FKIOCTL);
8345 	kmem_free(com, sizeof (*com));
8346 	return (r);
8347 }
8348 
8349 /*
8350  * st_gen_mode_select
8351  *
8352  * generic mode select.. it allows for any page
8353  */
8354 static int
8355 st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
8356     struct seq_mode *page_data, int page_size)
8357 {
8358 
8359 	int r;
8360 	char cdb[CDB_GROUP0];
8361 	struct uscsi_cmd *com;
8362 	struct scsi_arq_status status;
8363 
8364 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
8365 
8366 	/* Zero non-writeable fields */
8367 	page_data->data_len = 0;
8368 	page_data->media_type = 0;
8369 	page_data->wp = 0;
8370 
8371 	/*
8372 	 * If mode select has any page data, zero the ps (Page Savable) bit.
8373 	 */
8374 	if (page_size > MSIZE) {
8375 		page_data->ps = 0;
8376 	}
8377 
8378 
8379 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8380 
8381 	/*
8382 	 * then, do a mode select to set what ever info
8383 	 */
8384 	bzero(cdb, CDB_GROUP0);
8385 	cdb[0] = SCMD_MODE_SELECT;
8386 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
8387 	cdb[4] = (char)page_size;
8388 
8389 	com->uscsi_cdb = cdb;
8390 	com->uscsi_cdblen = CDB_GROUP0;
8391 	com->uscsi_bufaddr = (caddr_t)page_data;
8392 	com->uscsi_buflen = page_size;
8393 	com->uscsi_rqlen = sizeof (status);
8394 	com->uscsi_rqbuf = (caddr_t)&status;
8395 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8396 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_WRITE;
8397 
8398 	r = ubf(un, com, FKIOCTL);
8399 
8400 	kmem_free(com, sizeof (*com));
8401 	return (r);
8402 }
8403 
8404 static int
8405 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
8406 {
8407 	int rval;
8408 	char cdb[CDB_GROUP0];
8409 	struct uscsi_cmd *com;
8410 	struct scsi_arq_status status;
8411 
8412 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
8413 
8414 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8415 
8416 	bzero(cdb, CDB_GROUP0);
8417 	cdb[0] = SCMD_READ_BLKLIM;
8418 
8419 	com->uscsi_cdb = cdb;
8420 	com->uscsi_cdblen = CDB_GROUP0;
8421 	com->uscsi_bufaddr = (caddr_t)read_blk;
8422 	com->uscsi_buflen = sizeof (struct read_blklim);
8423 	com->uscsi_rqlen = sizeof (status);
8424 	com->uscsi_rqbuf = (caddr_t)&status;
8425 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8426 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8427 
8428 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8429 	if (com->uscsi_status || com->uscsi_resid) {
8430 		rval = -1;
8431 	}
8432 
8433 	kmem_free(com, sizeof (*com));
8434 	return (rval);
8435 }
8436 
8437 static int
8438 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
8439     size_t buflen)
8440 {
8441 	int rval;
8442 	char cdb[CDB_GROUP1];
8443 	struct uscsi_cmd *com;
8444 	struct scsi_arq_status status;
8445 
8446 	ST_FUNC(ST_DEVINFO, st_report_density_support);
8447 
8448 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8449 
8450 	bzero(cdb, CDB_GROUP1);
8451 	cdb[0] = SCMD_REPORT_DENSITIES;
8452 	cdb[7] = (buflen & 0xff00) >> 8;
8453 	cdb[8] = buflen & 0xff;
8454 
8455 	com->uscsi_cdb = cdb;
8456 	com->uscsi_cdblen = CDB_GROUP1;
8457 	com->uscsi_bufaddr = (caddr_t)density_data;
8458 	com->uscsi_buflen = buflen;
8459 	com->uscsi_rqlen = sizeof (status);
8460 	com->uscsi_rqbuf = (caddr_t)&status;
8461 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8462 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8463 
8464 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8465 	if (com->uscsi_status || com->uscsi_resid) {
8466 		rval = -1;
8467 	}
8468 
8469 	kmem_free(com, sizeof (*com));
8470 	return (rval);
8471 }
8472 
8473 static int
8474 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
8475     uchar_t option_code, ushort_t service_action)
8476 {
8477 	int rval;
8478 	char cdb[CDB_GROUP5];
8479 	struct uscsi_cmd *com;
8480 	struct scsi_arq_status status;
8481 	uint32_t allo_length;
8482 
8483 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
8484 
8485 	allo_length = sizeof (struct one_com_des) +
8486 	    sizeof (struct com_timeout_des);
8487 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8488 
8489 	bzero(cdb, CDB_GROUP5);
8490 	cdb[0] = (char)SCMD_MAINTENANCE_IN;
8491 	cdb[1] = SSVC_ACTION_GET_SUPPORTED_OPERATIONS;
8492 	if (service_action) {
8493 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
8494 		cdb[4] = (service_action & 0xff00) >> 8;
8495 		cdb[5] = service_action & 0xff;
8496 	} else {
8497 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
8498 		    0x80); /* RCTD */
8499 	}
8500 	cdb[3] = option_code;
8501 	cdb[6] = (allo_length & 0xff000000) >> 24;
8502 	cdb[7] = (allo_length & 0xff0000) >> 16;
8503 	cdb[8] = (allo_length & 0xff00) >> 8;
8504 	cdb[9] = allo_length & 0xff;
8505 
8506 	com->uscsi_cdb = cdb;
8507 	com->uscsi_cdblen = CDB_GROUP5;
8508 	com->uscsi_bufaddr = (caddr_t)oper_data;
8509 	com->uscsi_buflen = allo_length;
8510 	com->uscsi_rqlen = sizeof (status);
8511 	com->uscsi_rqbuf = (caddr_t)&status;
8512 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8513 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8514 
8515 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8516 	if (com->uscsi_status) {
8517 		rval = -1;
8518 	}
8519 
8520 	kmem_free(com, sizeof (*com));
8521 	return (rval);
8522 }
8523 
8524 /*
8525  * Changes devices blocksize and bsize to requested blocksize nblksz.
8526  * Returns returned value from first failed call or zero on success.
8527  */
8528 static int
8529 st_change_block_size(struct scsi_tape *un, uint32_t nblksz)
8530 {
8531 	struct seq_mode *current;
8532 	int rval;
8533 	uint32_t oldblksz;
8534 
8535 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8536 
8537 	current = kmem_zalloc(MSIZE, KM_SLEEP);
8538 
8539 	/*
8540 	 * If we haven't got the compression page yet, do that first.
8541 	 */
8542 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
8543 		(void) st_modesense(un);
8544 	}
8545 
8546 	/* Read current settings */
8547 	rval = st_gen_mode_sense(un, st_uscsi_cmd, 0, current, MSIZE);
8548 	if (rval != 0) {
8549 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8550 		    "mode sense for change block size failed: rval = %d", rval);
8551 		goto finish;
8552 	}
8553 
8554 	/* Figure the current block size */
8555 	oldblksz =
8556 	    (current->high_bl << 16) |
8557 	    (current->mid_bl << 8) |
8558 	    (current->low_bl);
8559 
8560 	/* If current block size is the same as requested were done */
8561 	if (oldblksz == nblksz) {
8562 		un->un_bsize = nblksz;
8563 		rval = 0;
8564 		goto finish;
8565 	}
8566 
8567 	/* Change to requested block size */
8568 	current->high_bl = (uchar_t)(nblksz >> 16);
8569 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8570 	current->low_bl  = (uchar_t)(nblksz);
8571 
8572 	/* Attempt to change block size */
8573 	rval = st_gen_mode_select(un, st_uscsi_cmd, current, MSIZE);
8574 	if (rval != 0) {
8575 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8576 		    "Set new block size failed: rval = %d", rval);
8577 		goto finish;
8578 	}
8579 
8580 	/* Read back and verify setting */
8581 	rval = st_modesense(un);
8582 	if (rval == 0) {
8583 		un->un_bsize =
8584 		    (un->un_mspl->high_bl << 16) |
8585 		    (un->un_mspl->mid_bl << 8) |
8586 		    (un->un_mspl->low_bl);
8587 
8588 		if (un->un_bsize != nblksz) {
8589 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8590 			    "Blocksize set does not equal requested blocksize"
8591 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8592 			rval = EIO;
8593 		}
8594 	}
8595 finish:
8596 	kmem_free(current, MSIZE);
8597 	return (rval);
8598 }
8599 
8600 
8601 static void
8602 st_init(struct scsi_tape *un)
8603 {
8604 	ST_FUNC(ST_DEVINFO, st_init);
8605 
8606 	ASSERT(mutex_owned(ST_MUTEX));
8607 
8608 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8609 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8610 	    un->un_dev);
8611 
8612 	un->un_pos.blkno = 0;
8613 	un->un_pos.fileno = 0;
8614 	un->un_lastop = ST_OP_NIL;
8615 	un->un_pos.eof = ST_NO_EOF;
8616 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8617 	if (st_error_level != SCSI_ERR_ALL) {
8618 		if (DEBUGGING) {
8619 			st_error_level = SCSI_ERR_ALL;
8620 		} else {
8621 			st_error_level = SCSI_ERR_RETRYABLE;
8622 		}
8623 	}
8624 }
8625 
8626 
8627 static void
8628 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8629 {
8630 	struct scsi_pkt *pkt;
8631 	struct uscsi_cmd *ucmd;
8632 	recov_info *ri;
8633 	int tval = 0;
8634 	int64_t count;
8635 	uint32_t additional = 0;
8636 	uint32_t address = 0;
8637 	union scsi_cdb *ucdb;
8638 	int flags = 0;
8639 	int cdb_len = CDB_GROUP0; /* default */
8640 	uchar_t com;
8641 	char fixbit;
8642 	char short_fm = 0;
8643 	optype prev_op = un->un_lastop;
8644 	int stat_size =
8645 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
8646 
8647 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8648 
8649 	ASSERT(mutex_owned(ST_MUTEX));
8650 
8651 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8652 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8653 
8654 
8655 	/*
8656 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8657 	 * Length Indicator bits on read/write commands, for setting
8658 	 * the Long bit on erase commands, and for setting the Code
8659 	 * Field bits on space commands.
8660 	 */
8661 
8662 	/* regular raw I/O */
8663 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
8664 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8665 		    CDB_GROUP0, stat_size, st_recov_sz, 0, func,
8666 		    (caddr_t)un);
8667 		if (pkt == NULL) {
8668 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8669 			    "Read Write scsi_init_pkt() failure\n");
8670 			goto exit;
8671 		}
8672 		ASSERT(pkt->pkt_resid == 0);
8673 #ifdef STDEBUG
8674 		bzero(pkt->pkt_private, st_recov_sz);
8675 		bzero(pkt->pkt_scbp, stat_size);
8676 #endif
8677 		ri = (recov_info *)pkt->pkt_private;
8678 		ri->privatelen = st_recov_sz;
8679 		if (un->un_bsize == 0) {
8680 			count = bp->b_bcount;
8681 			fixbit = 0;
8682 		} else {
8683 			count = bp->b_bcount / un->un_bsize;
8684 			fixbit = 1;
8685 		}
8686 		if (bp->b_flags & B_READ) {
8687 			com = SCMD_READ;
8688 			un->un_lastop = ST_OP_READ;
8689 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8690 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8691 				fixbit = 2;
8692 			}
8693 		} else {
8694 			com = SCMD_WRITE;
8695 			un->un_lastop = ST_OP_WRITE;
8696 		}
8697 		tval = un->un_dp->io_timeout;
8698 
8699 		/*
8700 		 * For really large xfers, increase timeout
8701 		 */
8702 		if (bp->b_bcount > (10 * ONE_MEG))
8703 			tval *= bp->b_bcount/(10 * ONE_MEG);
8704 
8705 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8706 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8707 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8708 
8709 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8710 		/*
8711 		 * uscsi - build command, allocate scsi resources
8712 		 */
8713 		st_make_uscsi_cmd(un, ucmd, bp, func);
8714 		goto exit;
8715 
8716 	} else {				/* special I/O */
8717 		struct buf *allocbp = NULL;
8718 		com = (uchar_t)(uintptr_t)bp->b_forw;
8719 		count = bp->b_bcount;
8720 
8721 		switch (com) {
8722 		case SCMD_READ:
8723 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8724 			    "special read %"PRId64"\n", count);
8725 			if (un->un_bsize == 0) {
8726 				fixbit = 2;	/* suppress SILI */
8727 			} else {
8728 				fixbit = 1;	/* Fixed Block Mode */
8729 				count /= un->un_bsize;
8730 			}
8731 			allocbp = bp;
8732 			un->un_lastop = ST_OP_READ;
8733 			tval = un->un_dp->io_timeout;
8734 			break;
8735 
8736 		case SCMD_WRITE:
8737 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8738 			    "special write %"PRId64"\n", count);
8739 			if (un->un_bsize != 0) {
8740 				fixbit = 1;	/* Fixed Block Mode */
8741 				count /= un->un_bsize;
8742 			} else {
8743 				fixbit = 0;
8744 			}
8745 			allocbp = bp;
8746 			un->un_lastop = ST_OP_WRITE;
8747 			tval = un->un_dp->io_timeout;
8748 			break;
8749 
8750 		case SCMD_WRITE_FILE_MARK:
8751 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8752 			    "write %"PRId64" file marks\n", count);
8753 			un->un_lastop = ST_OP_WEOF;
8754 			fixbit = 0;
8755 			tval = un->un_dp->io_timeout;
8756 			/*
8757 			 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8758 			 * device, set the Vendor Unique bit to
8759 			 * write Short File Mark.
8760 			 */
8761 			if ((un->un_dp->options & ST_SHORT_FILEMARKS) &&
8762 			    ((un->un_dp->type == ST_TYPE_EXB8500) ||
8763 			    (un->un_dp->type == ST_TYPE_EXABYTE))) {
8764 				/*
8765 				 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8766 				 * is set to to write Short File Mark
8767 				 */
8768 				short_fm = 1;
8769 			}
8770 			break;
8771 
8772 		case SCMD_REWIND:
8773 			/*
8774 			 * In the case of rewind we're gona do the rewind with
8775 			 * the immediate bit set so status will be retured when
8776 			 * the command is accepted by the device. We clear the
8777 			 * B_ASYNC flag so we wait for that acceptance.
8778 			 */
8779 			fixbit = 0;
8780 			if (bp->b_flags & B_ASYNC) {
8781 				allocbp = bp;
8782 				if (count) {
8783 					fixbit = 1;
8784 					bp->b_flags &= ~B_ASYNC;
8785 				}
8786 			}
8787 			count = 0;
8788 			bp->b_bcount = 0;
8789 			un->un_lastop = ST_OP_CTL;
8790 			tval = un->un_dp->rewind_timeout;
8791 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8792 			    "rewind\n");
8793 			break;
8794 
8795 		case SCMD_SPACE_G4:
8796 			cdb_len = CDB_GROUP4;
8797 			fixbit = SPACE_TYPE(bp->b_bcount);
8798 			count = SPACE_CNT(bp->b_bcount);
8799 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8800 			    " %s space %s %"PRId64" from file %d blk %d\n",
8801 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8802 			    space_strs[fixbit & 7], count,
8803 			    un->un_pos.fileno, un->un_pos.blkno);
8804 			address = (count >> 48) & 0x1fff;
8805 			additional = (count >> 16) & 0xffffffff;
8806 			count &= 0xffff;
8807 			count <<= 16;
8808 			un->un_lastop = ST_OP_CTL;
8809 			tval = un->un_dp->space_timeout;
8810 			break;
8811 
8812 		case SCMD_SPACE:
8813 			fixbit = SPACE_TYPE(bp->b_bcount);
8814 			count = SPACE_CNT(bp->b_bcount);
8815 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8816 			    " %s space %s %"PRId64" from file %d blk %d\n",
8817 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8818 			    space_strs[fixbit & 7], count,
8819 			    un->un_pos.fileno, un->un_pos.blkno);
8820 			count &= 0xffffffff;
8821 			un->un_lastop = ST_OP_CTL;
8822 			tval = un->un_dp->space_timeout;
8823 			break;
8824 
8825 		case SCMD_LOAD:
8826 			ASSERT(count < 10);
8827 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8828 			    "%s tape\n", load_strs[count]);
8829 			fixbit = 0;
8830 
8831 			/* Loading or Unloading */
8832 			if (count & LD_LOAD) {
8833 				tval = un->un_dp->load_timeout;
8834 			} else {
8835 				tval = un->un_dp->unload_timeout;
8836 			}
8837 			/* Is Retension requested */
8838 			if (count & LD_RETEN) {
8839 				tval += un->un_dp->rewind_timeout;
8840 			}
8841 			un->un_lastop = ST_OP_CTL;
8842 			break;
8843 
8844 		case SCMD_ERASE:
8845 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8846 			    "erase tape\n");
8847 			ASSERT(count == 1); /* mt sets this */
8848 			if (count == 1) {
8849 				/*
8850 				 * do long erase
8851 				 */
8852 				fixbit = 1; /* Long */
8853 
8854 				/* Drive might not honor immidiate bit */
8855 				tval = un->un_dp->erase_timeout;
8856 			} else {
8857 				/* Short Erase */
8858 				tval = un->un_dp->erase_timeout;
8859 				fixbit = 0;
8860 			}
8861 			un->un_lastop = ST_OP_CTL;
8862 			count = 0;
8863 			break;
8864 
8865 		case SCMD_MODE_SENSE:
8866 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8867 			    "mode sense\n");
8868 			allocbp = bp;
8869 			fixbit = 0;
8870 			tval = un->un_dp->non_motion_timeout;
8871 			un->un_lastop = ST_OP_CTL;
8872 			break;
8873 
8874 		case SCMD_MODE_SELECT:
8875 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8876 			    "mode select\n");
8877 			allocbp = bp;
8878 			fixbit = 0;
8879 			tval = un->un_dp->non_motion_timeout;
8880 			un->un_lastop = ST_OP_CTL;
8881 			break;
8882 
8883 		case SCMD_RESERVE:
8884 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8885 			    "reserve\n");
8886 			fixbit = 0;
8887 			tval = un->un_dp->non_motion_timeout;
8888 			un->un_lastop = ST_OP_CTL;
8889 			break;
8890 
8891 		case SCMD_RELEASE:
8892 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8893 			    "release\n");
8894 			fixbit = 0;
8895 			tval = un->un_dp->non_motion_timeout;
8896 			un->un_lastop = ST_OP_CTL;
8897 			break;
8898 
8899 		case SCMD_READ_BLKLIM:
8900 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8901 			    "read block limits\n");
8902 			allocbp = bp;
8903 			fixbit = count = 0;
8904 			tval = un->un_dp->non_motion_timeout;
8905 			un->un_lastop = ST_OP_CTL;
8906 			break;
8907 
8908 		case SCMD_TEST_UNIT_READY:
8909 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8910 			    "test unit ready\n");
8911 			fixbit = 0;
8912 			tval = un->un_dp->non_motion_timeout;
8913 			un->un_lastop = ST_OP_CTL;
8914 			break;
8915 
8916 		case SCMD_DOORLOCK:
8917 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8918 			    "prevent/allow media removal\n");
8919 			fixbit = 0;
8920 			tval = un->un_dp->non_motion_timeout;
8921 			un->un_lastop = ST_OP_CTL;
8922 			break;
8923 
8924 		case SCMD_READ_POSITION:
8925 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8926 			    "read position\n");
8927 			fixbit = un->un_read_pos_type;
8928 			cdb_len = CDB_GROUP1;
8929 			tval = un->un_dp->non_motion_timeout;
8930 			allocbp = bp;
8931 			un->un_lastop = ST_OP_CTL;
8932 			switch (un->un_read_pos_type) {
8933 			case LONG_POS:
8934 				count = 0;
8935 				break;
8936 			case EXT_POS:
8937 				count = sizeof (tape_position_ext_t);
8938 				break;
8939 			case SHORT_POS:
8940 				count = 0;
8941 				break;
8942 			default:
8943 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8944 				    "Unknown read position type 0x%x in "
8945 				    " st_make_cmd()\n", un->un_read_pos_type);
8946 			}
8947 			break;
8948 
8949 		default:
8950 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8951 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8952 			    com);
8953 		}
8954 
8955 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8956 		    st_recov_sz, 0, func, (caddr_t)un);
8957 		if (pkt == NULL) {
8958 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8959 			    "generic command scsi_init_pkt() failure\n");
8960 			goto exit;
8961 		}
8962 
8963 		ASSERT(pkt->pkt_resid == 0);
8964 #ifdef STDEBUG
8965 		bzero(pkt->pkt_private, st_recov_sz);
8966 		bzero(pkt->pkt_scbp, stat_size);
8967 #endif
8968 		ri = (recov_info *)pkt->pkt_private;
8969 		ri->privatelen = st_recov_sz;
8970 		if (allocbp) {
8971 			ASSERT(geterror(allocbp) == 0);
8972 		}
8973 
8974 	}
8975 
8976 	ucdb = (union scsi_cdb *)pkt->pkt_cdbp;
8977 
8978 	(void) scsi_setup_cdb(ucdb, com, address, (uint_t)count, additional);
8979 	FILL_SCSI1_LUN(un->un_sd, pkt);
8980 	/*
8981 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8982 	 */
8983 	ucdb->t_code = fixbit;
8984 	ucdb->g0_vu_1 = short_fm;
8985 	pkt->pkt_flags = flags;
8986 
8987 	ASSERT(tval);
8988 	pkt->pkt_time = tval;
8989 	if (bp == un->un_recov_buf) {
8990 		pkt->pkt_comp = st_recov_cb;
8991 	} else {
8992 		pkt->pkt_comp = st_intr;
8993 	}
8994 
8995 	st_add_recovery_info_to_pkt(un, bp, pkt);
8996 
8997 	/*
8998 	 * If we just write data to tape and did a command that doesn't
8999 	 * change position, we still need to write a filemark.
9000 	 */
9001 	if ((prev_op == ST_OP_WRITE) || (prev_op == ST_OP_WEOF)) {
9002 		recov_info *rcvi = pkt->pkt_private;
9003 		cmd_attribute const *atrib;
9004 
9005 		if (rcvi->privatelen == sizeof (recov_info)) {
9006 			atrib = rcvi->cmd_attrib;
9007 		} else {
9008 			atrib = st_lookup_cmd_attribute(com);
9009 		}
9010 		if (atrib->chg_tape_direction == DIR_NONE) {
9011 			un->un_lastop = prev_op;
9012 		}
9013 	}
9014 
9015 exit:
9016 	ASSERT(mutex_owned(ST_MUTEX));
9017 }
9018 
9019 
9020 /*
9021  * Build a command based on a uscsi command;
9022  */
9023 static void
9024 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
9025     struct buf *bp, int (*func)(caddr_t))
9026 {
9027 	struct scsi_pkt *pkt;
9028 	recov_info *ri;
9029 	caddr_t cdb;
9030 	int	cdblen;
9031 	int	stat_size = 1;
9032 	int	flags = 0;
9033 
9034 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
9035 
9036 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9037 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
9038 
9039 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
9040 		if (un->un_arq_enabled) {
9041 			if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
9042 				stat_size = (int)(ucmd->uscsi_rqlen) +
9043 				    sizeof (struct scsi_arq_status) -
9044 				    sizeof (struct scsi_extended_sense);
9045 				flags = PKT_XARQ;
9046 			} else {
9047 				stat_size = sizeof (struct scsi_arq_status);
9048 			}
9049 		}
9050 	}
9051 
9052 	ASSERT(mutex_owned(ST_MUTEX));
9053 
9054 	cdb = ucmd->uscsi_cdb;
9055 	cdblen = ucmd->uscsi_cdblen;
9056 
9057 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9058 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
9059 	    ucmd->uscsi_buflen, bp->b_bcount);
9060 	pkt = scsi_init_pkt(ROUTE, NULL,
9061 	    (bp->b_bcount > 0) ? bp : NULL,
9062 	    cdblen, stat_size, st_recov_sz, flags, func, (caddr_t)un);
9063 	if (pkt == NULL) {
9064 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
9065 		    "uscsi command scsi_init_pkt() failure\n");
9066 		goto exit;
9067 	}
9068 
9069 	ASSERT(pkt->pkt_resid == 0);
9070 #ifdef STDEBUG
9071 	bzero(pkt->pkt_private, st_recov_sz);
9072 	bzero(pkt->pkt_scbp, stat_size);
9073 #endif
9074 	ri = (recov_info *)pkt->pkt_private;
9075 	ri->privatelen = st_recov_sz;
9076 
9077 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
9078 
9079 #ifdef STDEBUG
9080 	if ((st_debug & 0x7) >= 6) {
9081 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
9082 		    "pkt_cdbp", (char *)cdb, cdblen);
9083 	}
9084 #endif
9085 
9086 	if (ucmd->uscsi_flags & USCSI_SILENT) {
9087 		pkt->pkt_flags |= FLAG_SILENT;
9088 	}
9089 
9090 	(void) scsi_uscsi_pktinit(ucmd, pkt);
9091 
9092 	pkt->pkt_time = ucmd->uscsi_timeout;
9093 	if (bp == un->un_recov_buf) {
9094 		pkt->pkt_comp = st_recov_cb;
9095 	} else {
9096 		pkt->pkt_comp = st_intr;
9097 	}
9098 
9099 	st_add_recovery_info_to_pkt(un, bp, pkt);
9100 exit:
9101 	ASSERT(mutex_owned(ST_MUTEX));
9102 }
9103 
9104 
9105 /*
9106  * restart cmd currently at the head of the runq
9107  *
9108  * If scsi_transport() succeeds or the retries
9109  * count exhausted, restore the throttle that was
9110  * zeroed out in st_handle_intr_busy().
9111  *
9112  */
9113 static void
9114 st_intr_restart(void *arg)
9115 {
9116 	struct scsi_tape *un = arg;
9117 	struct buf *bp;
9118 	int queued;
9119 	int status = TRAN_ACCEPT;
9120 
9121 	mutex_enter(ST_MUTEX);
9122 
9123 	ST_FUNC(ST_DEVINFO, st_intr_restart);
9124 
9125 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9126 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
9127 
9128 	un->un_hib_tid = 0;
9129 
9130 	if (un->un_recov_buf_busy != 0) {
9131 		bp = un->un_recov_buf;
9132 		queued = 0;
9133 	} else if (un->un_sbuf_busy != 0) {
9134 		bp = un->un_sbufp;
9135 		queued = 0;
9136 	} else if (un->un_quef != NULL) {
9137 		bp = un->un_quef;
9138 		queued = 1;
9139 	} else {
9140 		mutex_exit(ST_MUTEX);
9141 		return;
9142 	}
9143 
9144 	/*
9145 	 * Here we know :
9146 	 *	throttle = 0, via st_handle_intr_busy
9147 	 */
9148 
9149 	if (queued) {
9150 		/*
9151 		 * move from waitq to runq, if there is anything on the waitq
9152 		 */
9153 		(void) st_remove_from_queue(&un->un_quef, &un->un_quef, bp);
9154 
9155 		if (un->un_runqf) {
9156 			/*
9157 			 * not good, we don't want to requeue something after
9158 			 * another.
9159 			 */
9160 			goto done_error;
9161 		} else {
9162 			un->un_runqf = bp;
9163 			un->un_runql = bp;
9164 		}
9165 	}
9166 
9167 	ST_CDB(ST_DEVINFO, "Interrupt restart CDB",
9168 	    (char *)BP_PKT(bp)->pkt_cdbp);
9169 
9170 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
9171 
9172 	status = st_transport(un, BP_PKT(bp));
9173 
9174 	if (status != TRAN_ACCEPT) {
9175 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9176 
9177 		if (status == TRAN_BUSY) {
9178 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
9179 
9180 			if (pkti->privatelen == sizeof (recov_info) &&
9181 			    un->un_unit_attention_flags &&
9182 			    bp != un->un_recov_buf) {
9183 			un->un_unit_attention_flags = 0;
9184 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9185 				    "Command Recovery called on busy resend\n");
9186 				if (st_command_recovery(un, BP_PKT(bp),
9187 				    ATTEMPT_RETRY) == JUST_RETURN) {
9188 					mutex_exit(ST_MUTEX);
9189 					return;
9190 				}
9191 			}
9192 			mutex_exit(ST_MUTEX);
9193 			if (st_handle_intr_busy(un, bp,
9194 			    ST_TRAN_BUSY_TIMEOUT) == 0)
9195 				return;	/* timeout is setup again */
9196 			mutex_enter(ST_MUTEX);
9197 		}
9198 
9199 done_error:
9200 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9201 		    "restart transport rejected\n");
9202 		bp->b_resid = bp->b_bcount;
9203 
9204 		if (un->un_last_throttle) {
9205 			un->un_throttle = un->un_last_throttle;
9206 		}
9207 		if (status != TRAN_ACCEPT) {
9208 			ST_DO_ERRSTATS(un, st_transerrs);
9209 		}
9210 		ST_DO_KSTATS(bp, kstat_waitq_exit);
9211 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9212 		    "busy restart aborted\n");
9213 		st_set_pe_flag(un);
9214 		st_bioerror(bp, EIO);
9215 		st_done_and_mutex_exit(un, bp);
9216 	} else {
9217 		if (un->un_last_throttle) {
9218 			un->un_throttle = un->un_last_throttle;
9219 		}
9220 		mutex_exit(ST_MUTEX);
9221 	}
9222 }
9223 
9224 /*
9225  * st_check_media():
9226  * Periodically check the media state using scsi_watch service;
9227  * this service calls back after TUR and possibly request sense
9228  * the callback handler (st_media_watch_cb()) decodes the request sense
9229  * data (if any)
9230  */
9231 
9232 static int
9233 st_check_media(dev_t dev, enum mtio_state state)
9234 {
9235 	int rval = 0;
9236 	enum mtio_state	prev_state;
9237 	opaque_t token = NULL;
9238 
9239 	GET_SOFT_STATE(dev);
9240 
9241 	ST_FUNC(ST_DEVINFO, st_check_media);
9242 
9243 	mutex_enter(ST_MUTEX);
9244 
9245 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9246 	    "st_check_media:state=%x, mediastate=%x\n",
9247 	    state, un->un_mediastate);
9248 
9249 	prev_state = un->un_mediastate;
9250 
9251 	/*
9252 	 * is there anything to do?
9253 	 */
9254 retry:
9255 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
9256 		/*
9257 		 * submit the request to the scsi_watch service;
9258 		 * scsi_media_watch_cb() does the real work
9259 		 */
9260 		mutex_exit(ST_MUTEX);
9261 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
9262 		    st_check_media_time, SENSE_LENGTH,
9263 		    st_media_watch_cb, (caddr_t)dev);
9264 		if (token == NULL) {
9265 			rval = EAGAIN;
9266 			goto done;
9267 		}
9268 		mutex_enter(ST_MUTEX);
9269 
9270 		un->un_swr_token = token;
9271 		un->un_specified_mediastate = state;
9272 
9273 		/*
9274 		 * now wait for media change
9275 		 * we will not be signalled unless mediastate == state but it
9276 		 * still better to test for this condition, since there
9277 		 * is a 5 sec cv_broadcast delay when
9278 		 *  mediastate == MTIO_INSERTED
9279 		 */
9280 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9281 		    "st_check_media:waiting for media state change\n");
9282 		while (un->un_mediastate == state) {
9283 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
9284 				mutex_exit(ST_MUTEX);
9285 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9286 				    "st_check_media:waiting for media state "
9287 				    "was interrupted\n");
9288 				rval = EINTR;
9289 				goto done;
9290 			}
9291 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9292 			    "st_check_media:received signal, state=%x\n",
9293 			    un->un_mediastate);
9294 		}
9295 	}
9296 
9297 	/*
9298 	 * if we transitioned to MTIO_INSERTED, media has really been
9299 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
9300 	 * Reset and retry the state change.  If everything is ok, replay
9301 	 * the open() logic.
9302 	 */
9303 	if ((un->un_mediastate == MTIO_INSERTED) &&
9304 	    (un->un_state == ST_STATE_OFFLINE)) {
9305 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9306 		    "st_check_media: calling st_cmd to confirm inserted\n");
9307 
9308 		/*
9309 		 * set this early so that TUR will make it through strategy
9310 		 * without triggering a st_tape_init().  We needed it set
9311 		 * before calling st_tape_init() ourselves anyway.  If TUR
9312 		 * fails, set it back
9313 		 */
9314 		un->un_state = ST_STATE_INITIALIZING;
9315 
9316 		/*
9317 		 * If not reserved fail as getting reservation conflict
9318 		 * will make this hang forever.
9319 		 */
9320 		if ((un->un_rsvd_status &
9321 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9322 			mutex_exit(ST_MUTEX);
9323 			rval = EACCES;
9324 			goto done;
9325 		}
9326 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
9327 		if (rval == EACCES) {
9328 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9329 			    "st_check_media: TUR got Reservation Conflict\n");
9330 			mutex_exit(ST_MUTEX);
9331 			goto done;
9332 		}
9333 		if (rval) {
9334 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9335 			    "st_check_media: TUR failed, going to retry\n");
9336 			un->un_mediastate = prev_state;
9337 			un->un_state = ST_STATE_OFFLINE;
9338 			goto retry;
9339 		}
9340 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9341 		    "st_check_media: media inserted\n");
9342 
9343 		/* this also rewinds the tape */
9344 		rval = st_tape_init(un);
9345 		if (rval != 0) {
9346 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9347 			    "st_check_media : OFFLINE init failure ");
9348 			un->un_state = ST_STATE_OFFLINE;
9349 			un->un_pos.pmode = invalid;
9350 		} else {
9351 			un->un_state = ST_STATE_OPEN_PENDING_IO;
9352 		}
9353 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
9354 	    (un->un_state != ST_STATE_OFFLINE)) {
9355 		/*
9356 		 * supported devices must be rewound before ejection
9357 		 * rewind resets fileno & blkno
9358 		 */
9359 		un->un_laststate = un->un_state;
9360 		un->un_state = ST_STATE_OFFLINE;
9361 	}
9362 	mutex_exit(ST_MUTEX);
9363 done:
9364 	if (token) {
9365 		(void) scsi_watch_request_terminate(token,
9366 		    SCSI_WATCH_TERMINATE_WAIT);
9367 		mutex_enter(ST_MUTEX);
9368 		un->un_swr_token = (opaque_t)NULL;
9369 		mutex_exit(ST_MUTEX);
9370 	}
9371 
9372 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
9373 
9374 	return (rval);
9375 }
9376 
9377 /*
9378  * st_media_watch_cb() is called by scsi_watch_thread for
9379  * verifying the request sense data (if any)
9380  */
9381 static int
9382 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
9383 {
9384 	struct scsi_status *statusp = resultp->statusp;
9385 	struct scsi_extended_sense *sensep = resultp->sensep;
9386 	uchar_t actual_sense_length = resultp->actual_sense_length;
9387 	struct scsi_tape *un;
9388 	enum mtio_state state = MTIO_NONE;
9389 	int instance;
9390 	dev_t dev = (dev_t)arg;
9391 
9392 	instance = MTUNIT(dev);
9393 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
9394 		return (-1);
9395 	}
9396 
9397 	mutex_enter(ST_MUTEX);
9398 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
9399 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9400 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
9401 	    *((char *)statusp), (void *)sensep,
9402 	    actual_sense_length);
9403 
9404 
9405 	/*
9406 	 * if there was a check condition then sensep points to valid
9407 	 * sense data
9408 	 * if status was not a check condition but a reservation or busy
9409 	 * status then the new state is MTIO_NONE
9410 	 */
9411 	if (sensep) {
9412 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9413 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
9414 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
9415 
9416 		switch (un->un_dp->type) {
9417 		default:
9418 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9419 			    "st_media_watch_cb: unknown drive type %d, "
9420 			    "default to ST_TYPE_HP\n", un->un_dp->type);
9421 		/* FALLTHROUGH */
9422 
9423 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
9424 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
9425 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
9426 			if (un->un_dp->type == ST_TYPE_FUJI) {
9427 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9428 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
9429 			} else {
9430 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9431 				    "st_media_watch_cb: ST_TYPE_HP\n");
9432 			}
9433 			switch (sensep->es_key) {
9434 			case KEY_UNIT_ATTENTION:
9435 				/* not ready to ready transition */
9436 				/* hp/es_qual_code == 80 on>off>on */
9437 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
9438 				if (sensep->es_add_code == 0x28) {
9439 					state = MTIO_INSERTED;
9440 				}
9441 				break;
9442 			case KEY_NOT_READY:
9443 				/* in process, rewinding or loading */
9444 				if ((sensep->es_add_code == 0x04) &&
9445 				    (sensep->es_qual_code == 0x00)) {
9446 					state = MTIO_EJECTED;
9447 				}
9448 				break;
9449 			}
9450 			break;
9451 
9452 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
9453 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9454 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
9455 			switch (sensep->es_key) {
9456 			case KEY_UNIT_ATTENTION:
9457 				/* operator medium removal request */
9458 				if ((sensep->es_add_code == 0x5a) &&
9459 				    (sensep->es_qual_code == 0x01)) {
9460 					state = MTIO_EJECTED;
9461 				/* not ready to ready transition */
9462 				} else if ((sensep->es_add_code == 0x28) &&
9463 				    (sensep->es_qual_code == 0x00)) {
9464 					state = MTIO_INSERTED;
9465 				}
9466 				break;
9467 			case KEY_NOT_READY:
9468 				/* medium not present */
9469 				if (sensep->es_add_code == 0x3a) {
9470 					state = MTIO_EJECTED;
9471 				}
9472 				break;
9473 			}
9474 			break;
9475 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
9476 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9477 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
9478 			switch (sensep->es_key) {
9479 			case KEY_NOT_READY:
9480 				if ((sensep->es_add_code == 0x04) &&
9481 				    (sensep->es_qual_code == 0x00)) {
9482 					/* volume not mounted? */
9483 					state = MTIO_EJECTED;
9484 				} else if (sensep->es_add_code == 0x3a) {
9485 					state = MTIO_EJECTED;
9486 				}
9487 				break;
9488 			case KEY_UNIT_ATTENTION:
9489 				state = MTIO_EJECTED;
9490 				break;
9491 			}
9492 			break;
9493 
9494 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
9495 			switch (sensep->es_key) {
9496 			case KEY_UNIT_ATTENTION:
9497 				if (sensep->es_add_code == 0x28) {
9498 					state = MTIO_INSERTED;
9499 				}
9500 				break;
9501 			case KEY_NOT_READY:
9502 				if (sensep->es_add_code == 0x04) {
9503 					/* in transition but could be either */
9504 					state = un->un_specified_mediastate;
9505 				} else if ((sensep->es_add_code == 0x3a) &&
9506 				    (sensep->es_qual_code == 0x00)) {
9507 					state = MTIO_EJECTED;
9508 				}
9509 				break;
9510 			}
9511 			break;
9512 		}
9513 	} else if (*((char *)statusp) == STATUS_GOOD) {
9514 		state = MTIO_INSERTED;
9515 	}
9516 
9517 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9518 	    "st_media_watch_cb:state=%x, specified=%x\n",
9519 	    state, un->un_specified_mediastate);
9520 
9521 	/*
9522 	 * now signal the waiting thread if this is *not* the specified state;
9523 	 * delay the signal if the state is MTIO_INSERTED
9524 	 * to allow the target to recover
9525 	 */
9526 	if (state != un->un_specified_mediastate) {
9527 		un->un_mediastate = state;
9528 		if (state == MTIO_INSERTED) {
9529 			/*
9530 			 * delay the signal to give the drive a chance
9531 			 * to do what it apparently needs to do
9532 			 */
9533 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9534 			    "st_media_watch_cb:delayed cv_broadcast\n");
9535 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
9536 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
9537 		} else {
9538 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9539 			    "st_media_watch_cb:immediate cv_broadcast\n");
9540 			cv_broadcast(&un->un_state_cv);
9541 		}
9542 	}
9543 	mutex_exit(ST_MUTEX);
9544 	return (0);
9545 }
9546 
9547 /*
9548  * delayed cv_broadcast to allow for target to recover
9549  * from media insertion
9550  */
9551 static void
9552 st_delayed_cv_broadcast(void *arg)
9553 {
9554 	struct scsi_tape *un = arg;
9555 
9556 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
9557 
9558 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9559 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
9560 
9561 	mutex_enter(ST_MUTEX);
9562 	cv_broadcast(&un->un_state_cv);
9563 	mutex_exit(ST_MUTEX);
9564 }
9565 
9566 /*
9567  * restart cmd currently at the start of the waitq
9568  */
9569 static void
9570 st_start_restart(void *arg)
9571 {
9572 	struct scsi_tape *un = arg;
9573 
9574 	ST_FUNC(ST_DEVINFO, st_start_restart);
9575 
9576 	ASSERT(un != NULL);
9577 
9578 	mutex_enter(ST_MUTEX);
9579 
9580 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_tran_restart()\n");
9581 
9582 	st_start(un);
9583 
9584 	mutex_exit(ST_MUTEX);
9585 }
9586 
9587 
9588 /*
9589  * Command completion processing
9590  *
9591  */
9592 static void
9593 st_intr(struct scsi_pkt *pkt)
9594 {
9595 	recov_info *rcv = pkt->pkt_private;
9596 	struct buf *bp = rcv->cmd_bp;
9597 	struct scsi_tape *un;
9598 	errstate action = COMMAND_DONE;
9599 	clock_t	timout;
9600 	int	status;
9601 
9602 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
9603 
9604 	ST_FUNC(ST_DEVINFO, st_intr);
9605 
9606 	ASSERT(un != NULL);
9607 
9608 	mutex_enter(ST_MUTEX);
9609 
9610 	ASSERT(bp != un->un_recov_buf);
9611 
9612 	un->un_rqs_state &= ~(ST_RQS_ERROR);
9613 
9614 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
9615 
9616 	if (pkt->pkt_reason != CMD_CMPLT) {
9617 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9618 		    "Unhappy packet status reason = %s statistics = 0x%x\n",
9619 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9620 
9621 		/* If device has gone away not much else to do */
9622 		if (pkt->pkt_reason == CMD_DEV_GONE) {
9623 			action = COMMAND_DONE_ERROR;
9624 		} else if ((pkt == un->un_rqs) ||
9625 		    (un->un_state == ST_STATE_SENSING)) {
9626 			ASSERT(pkt == un->un_rqs);
9627 			ASSERT(un->un_state == ST_STATE_SENSING);
9628 			un->un_state = un->un_laststate;
9629 			rcv->cmd_bp = un->un_rqs_bp;
9630 			ST_DO_ERRSTATS(un, st_transerrs);
9631 			action = COMMAND_DONE_ERROR;
9632 		} else {
9633 			action = st_handle_incomplete(un, bp);
9634 		}
9635 	/*
9636 	 * At this point we know that the command was successfully
9637 	 * completed. Now what?
9638 	 */
9639 	} else if ((pkt == un->un_rqs) || (un->un_state == ST_STATE_SENSING)) {
9640 		/*
9641 		 * okay. We were running a REQUEST SENSE. Find
9642 		 * out what to do next.
9643 		 */
9644 		ASSERT(pkt == un->un_rqs);
9645 		ASSERT(un->un_state == ST_STATE_SENSING);
9646 		scsi_sync_pkt(pkt);
9647 		action = st_handle_sense(un, bp, &un->un_pos);
9648 		/*
9649 		 * Make rqs isn't going to be retied.
9650 		 */
9651 		if (action != QUE_BUSY_COMMAND && action != QUE_COMMAND) {
9652 			/*
9653 			 * set pkt back to original packet in case we will have
9654 			 * to requeue it
9655 			 */
9656 			pkt = BP_PKT(bp);
9657 			rcv->cmd_bp = un->un_rqs_bp;
9658 			/*
9659 			 * some actions are based on un_state, hence
9660 			 * restore the state st was in before ST_STATE_SENSING.
9661 			 */
9662 			un->un_state = un->un_laststate;
9663 		}
9664 
9665 	} else if (un->un_arq_enabled && (pkt->pkt_state & STATE_ARQ_DONE)) {
9666 		/*
9667 		 * the transport layer successfully completed an autorqsense
9668 		 */
9669 		action = st_handle_autosense(un, bp, &un->un_pos);
9670 
9671 	} else  if ((SCBP(pkt)->sts_busy) ||
9672 	    (SCBP(pkt)->sts_chk) ||
9673 	    (SCBP(pkt)->sts_vu7)) {
9674 		/*
9675 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9676 		 * to see if the status bits we're okay. If a request sense
9677 		 * is to be run, that will happen.
9678 		 */
9679 		action = st_check_error(un, pkt);
9680 	}
9681 
9682 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9683 		switch (action) {
9684 			case QUE_COMMAND:
9685 				/*
9686 				 * return cmd to head to the queue
9687 				 * since we are suspending so that
9688 				 * it gets restarted during resume
9689 				 */
9690 				st_add_to_queue(&un->un_runqf, &un->un_runql,
9691 				    un->un_runqf, bp);
9692 
9693 				action = JUST_RETURN;
9694 				break;
9695 
9696 			case QUE_SENSE:
9697 				action = COMMAND_DONE_ERROR;
9698 				break;
9699 
9700 			default:
9701 				break;
9702 		}
9703 	}
9704 
9705 	/*
9706 	 * check for undetected path failover.
9707 	 */
9708 	if (un->un_multipath) {
9709 
9710 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
9711 		int pkt_valid = 0;
9712 
9713 		if (ucmd) {
9714 			/*
9715 			 * Also copies path instance to the uscsi structure.
9716 			 */
9717 			pkt_valid = scsi_uscsi_pktfini(pkt, ucmd);
9718 
9719 			/*
9720 			 * scsi_uscsi_pktfini() zeros pkt_path_instance.
9721 			 */
9722 			pkt->pkt_path_instance = ucmd->uscsi_path_instance;
9723 		} else {
9724 			pkt_valid = scsi_pkt_allocated_correctly(pkt);
9725 		}
9726 
9727 		/*
9728 		 * If the scsi_pkt was not allocated correctly the
9729 		 * pkt_path_instance is not even there.
9730 		 */
9731 		if ((pkt_valid != 0) &&
9732 		    (un->un_last_path_instance != pkt->pkt_path_instance)) {
9733 			/*
9734 			 * Don't recover the path change if it was done
9735 			 * intentionally or if the device has not completely
9736 			 * opened yet.
9737 			 */
9738 			if (((pkt->pkt_flags & FLAG_PKT_PATH_INSTANCE) == 0) &&
9739 			    (un->un_state > ST_STATE_OPENING)) {
9740 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
9741 				    "Failover detected, action is %s\n",
9742 				    errstatenames[action]);
9743 				if (action == COMMAND_DONE) {
9744 					action = PATH_FAILED;
9745 				}
9746 			}
9747 			un->un_last_path_instance = pkt->pkt_path_instance;
9748 		}
9749 	}
9750 
9751 	/*
9752 	 * Restore old state if we were sensing.
9753 	 */
9754 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9755 		un->un_state = un->un_laststate;
9756 	}
9757 
9758 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9759 	    "st_intr: pkt=%p, bp=%p, action=%s, status=%x\n",
9760 	    (void *)pkt, (void *)bp, errstatenames[action], SCBP_C(pkt));
9761 
9762 again:
9763 	switch (action) {
9764 	case COMMAND_DONE_EACCES:
9765 		/* this is to report a reservation conflict */
9766 		st_bioerror(bp, EACCES);
9767 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9768 		    "Reservation Conflict \n");
9769 		un->un_pos.pmode = invalid;
9770 
9771 		/*FALLTHROUGH*/
9772 	case COMMAND_DONE_ERROR:
9773 		if (un->un_pos.eof < ST_EOT_PENDING &&
9774 		    un->un_state >= ST_STATE_OPEN) {
9775 			/*
9776 			 * all errors set state of the tape to 'unknown'
9777 			 * unless we're at EOT or are doing append testing.
9778 			 * If sense key was illegal request, preserve state.
9779 			 */
9780 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9781 				un->un_pos.pmode = invalid;
9782 			}
9783 		}
9784 
9785 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9786 		/*
9787 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9788 		 * make sure an error ocurrs, so make sure at least EIO is
9789 		 * returned
9790 		 */
9791 		if (geterror(bp) == 0)
9792 			st_bioerror(bp, EIO);
9793 
9794 		st_set_pe_flag(un);
9795 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9796 		    (un->un_errno == EIO)) {
9797 			un->un_rqs_state &= ~(ST_RQS_VALID);
9798 		}
9799 		break;
9800 
9801 	case COMMAND_DONE_ERROR_RECOVERED:
9802 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9803 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9804 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9805 		if (geterror(bp) == 0) {
9806 			st_bioerror(bp, EIO);
9807 		}
9808 		st_set_pe_flag(un);
9809 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9810 		    (un->un_errno == EIO)) {
9811 			un->un_rqs_state &= ~(ST_RQS_VALID);
9812 		}
9813 		/*FALLTHROUGH*/
9814 	case COMMAND_DONE:
9815 		st_set_state(un, bp);
9816 		break;
9817 
9818 	case QUE_SENSE:
9819 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9820 			goto sense_error;
9821 
9822 		if (un->un_state != ST_STATE_SENSING) {
9823 			un->un_laststate = un->un_state;
9824 			un->un_state = ST_STATE_SENSING;
9825 		}
9826 
9827 		/*
9828 		 * zero the sense data.
9829 		 */
9830 		bzero(un->un_rqs->pkt_scbp, SENSE_LENGTH);
9831 
9832 		/*
9833 		 * If this is not a retry on QUE_SENSE point to the original
9834 		 * bp of the command that got us here.
9835 		 */
9836 		if (pkt != un->un_rqs) {
9837 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp = bp;
9838 		}
9839 
9840 		if (un->un_throttle) {
9841 			un->un_last_throttle = un->un_throttle;
9842 			un->un_throttle = 0;
9843 		}
9844 
9845 		ST_CDB(ST_DEVINFO, "Queue sense CDB",
9846 		    (char *)BP_PKT(bp)->pkt_cdbp);
9847 
9848 		/*
9849 		 * never retry this, some other command will have nuked the
9850 		 * sense, anyway
9851 		 */
9852 		status = st_transport(un, un->un_rqs);
9853 
9854 		if (un->un_last_throttle) {
9855 			un->un_throttle = un->un_last_throttle;
9856 		}
9857 
9858 		if (status == TRAN_ACCEPT) {
9859 			mutex_exit(ST_MUTEX);
9860 			return;
9861 		}
9862 		if (status != TRAN_BUSY)
9863 			ST_DO_ERRSTATS(un, st_transerrs);
9864 sense_error:
9865 		un->un_pos.pmode = invalid;
9866 		st_bioerror(bp, EIO);
9867 		st_set_pe_flag(un);
9868 		break;
9869 
9870 	case QUE_BUSY_COMMAND:
9871 		/* longish timeout */
9872 		timout = ST_STATUS_BUSY_TIMEOUT;
9873 		goto que_it_up;
9874 
9875 	case QUE_COMMAND:
9876 		/* short timeout */
9877 		timout = ST_TRAN_BUSY_TIMEOUT;
9878 que_it_up:
9879 		/*
9880 		 * let st_handle_intr_busy put this bp back on waitq and make
9881 		 * checks to see if it is ok to requeue the command.
9882 		 */
9883 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9884 
9885 		/*
9886 		 * Save the throttle before setting up the timeout
9887 		 */
9888 		if (un->un_throttle) {
9889 			un->un_last_throttle = un->un_throttle;
9890 		}
9891 		mutex_exit(ST_MUTEX);
9892 		if (st_handle_intr_busy(un, bp, timout) == 0)
9893 			return;		/* timeout is setup again */
9894 
9895 		mutex_enter(ST_MUTEX);
9896 		un->un_pos.pmode = invalid;
9897 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9898 		st_bioerror(bp, EIO);
9899 		st_set_pe_flag(un);
9900 		break;
9901 
9902 	case QUE_LAST_COMMAND:
9903 
9904 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9905 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9906 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9907 			goto last_command_error;
9908 		}
9909 		mutex_exit(ST_MUTEX);
9910 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9911 			return;
9912 		mutex_enter(ST_MUTEX);
9913 last_command_error:
9914 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9915 		un->un_pos.pmode = invalid;
9916 		st_bioerror(bp, EIO);
9917 		st_set_pe_flag(un);
9918 		break;
9919 
9920 	case COMMAND_TIMEOUT:
9921 	case DEVICE_RESET:
9922 	case DEVICE_TAMPER:
9923 	case ATTEMPT_RETRY:
9924 	case PATH_FAILED:
9925 		ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9926 		    "Command Recovery called on %s status\n",
9927 		    errstatenames[action]);
9928 		action = st_command_recovery(un, pkt, action);
9929 		goto again;
9930 
9931 	default:
9932 		ASSERT(0);
9933 		/* FALLTHRU */
9934 	case JUST_RETURN:
9935 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9936 		mutex_exit(ST_MUTEX);
9937 		return;
9938 	}
9939 
9940 	ST_DO_KSTATS(bp, kstat_runq_exit);
9941 	st_done_and_mutex_exit(un, bp);
9942 }
9943 
9944 static errstate
9945 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9946 {
9947 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9948 	recov_info *rinfo;
9949 	errstate rval = COMMAND_DONE_ERROR;
9950 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9951 	    un->un_rqs : BP_PKT(bp);
9952 	int result;
9953 
9954 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9955 
9956 	rinfo = (recov_info *)pkt->pkt_private;
9957 
9958 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9959 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9960 
9961 	ASSERT(mutex_owned(ST_MUTEX));
9962 
9963 	switch (pkt->pkt_reason) {
9964 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9965 		/*
9966 		 * this occurs when accessing a powered down drive, no
9967 		 * need to complain; just fail the open
9968 		 */
9969 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9970 
9971 		/*
9972 		 * if we have commands outstanding in HBA, and a command
9973 		 * comes back incomplete, we're hosed, so reset target
9974 		 * If we have the bus, but cmd_incomplete, we probably just
9975 		 * have a failed selection, so don't reset the target, just
9976 		 * requeue the command and try again
9977 		 */
9978 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9979 			goto reset_target;
9980 		}
9981 
9982 		/*
9983 		 * Retry selection a couple more times if we're
9984 		 * open.  If opening, we only try just once to
9985 		 * reduce probe time for nonexistant devices.
9986 		 */
9987 		if ((un->un_laststate > ST_STATE_OPENING) &&
9988 		    (rinfo->pkt_retry_cnt < st_selection_retry_count)) {
9989 			/* XXX check retriable? */
9990 			rval = QUE_COMMAND;
9991 		}
9992 		ST_DO_ERRSTATS(un, st_transerrs);
9993 		break;
9994 
9995 	case CMD_ABORTED:
9996 		/*
9997 		 * most likely this is caused by flush-on-error support. If
9998 		 * it was not there, the we're in trouble.
9999 		 */
10000 		if (!un->un_flush_on_errors) {
10001 			un->un_status = SUN_KEY_FATAL;
10002 			goto reset_target;
10003 		}
10004 
10005 		st_set_pe_errno(un);
10006 		bioerror(bp, un->un_errno);
10007 		if (un->un_errno)
10008 			return (COMMAND_DONE_ERROR);
10009 		else
10010 			return (COMMAND_DONE);
10011 
10012 	case CMD_TIMEOUT:	/* Command timed out */
10013 		un->un_status = SUN_KEY_TIMEOUT;
10014 		return (COMMAND_TIMEOUT);
10015 
10016 	case CMD_TRAN_ERR:
10017 	case CMD_RESET:
10018 		if (pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET)) {
10019 			if ((un->un_rsvd_status &
10020 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
10021 			    ST_RESERVE) {
10022 				un->un_rsvd_status |= ST_LOST_RESERVE;
10023 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
10024 				    "Lost Reservation\n");
10025 			}
10026 			rval = DEVICE_RESET;
10027 			return (rval);
10028 		}
10029 		if (pkt->pkt_statistics & (STAT_ABORTED | STAT_TERMINATED)) {
10030 			rval = DEVICE_RESET;
10031 			return (rval);
10032 		}
10033 		/*FALLTHROUGH*/
10034 	default:
10035 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10036 		    "Unhandled packet status reason = %s statistics = 0x%x\n",
10037 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
10038 reset_target:
10039 
10040 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10041 		    "transport completed with %s\n",
10042 		    scsi_rname(pkt->pkt_reason));
10043 		ST_DO_ERRSTATS(un, st_transerrs);
10044 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
10045 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
10046 		    STAT_ABORTED)) == 0)) {
10047 
10048 			/*
10049 			 * If we haven't reserved the drive don't reset it.
10050 			 */
10051 			if ((un->un_rsvd_status &
10052 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
10053 				return (rval);
10054 			}
10055 
10056 			/*
10057 			 * if we aren't lost yet we will be soon.
10058 			 */
10059 			un->un_pos.pmode = invalid;
10060 
10061 			result = st_reset(un, RESET_LUN);
10062 
10063 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
10064 				/* no hope left to recover */
10065 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
10066 				    "recovery by resets failed\n");
10067 				return (rval);
10068 			}
10069 		}
10070 	}
10071 
10072 
10073 	if (rinfo->pkt_retry_cnt++ < st_retry_count) {
10074 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
10075 			rval = QUE_COMMAND;
10076 		} else if (bp == un->un_sbufp) {
10077 			if (rinfo->privatelen == sizeof (recov_info)) {
10078 				if (rinfo->cmd_attrib->retriable) {
10079 					/*
10080 					 * These commands can be rerun
10081 					 * with impunity
10082 					 */
10083 					rval = QUE_COMMAND;
10084 				}
10085 			} else {
10086 				cmd_attribute const *attrib;
10087 				attrib =
10088 				    st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10089 				if (attrib->retriable) {
10090 					rval = QUE_COMMAND;
10091 				}
10092 			}
10093 		}
10094 	} else {
10095 		rval = COMMAND_DONE_ERROR;
10096 	}
10097 
10098 	if (un->un_state >= ST_STATE_OPEN) {
10099 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10100 		    fail, scsi_rname(pkt->pkt_reason),
10101 		    (rval == COMMAND_DONE_ERROR)?
10102 		    "giving up" : "retrying command");
10103 	}
10104 	return (rval);
10105 }
10106 
10107 /*
10108  * if the device is busy, then put this bp back on the waitq, on the
10109  * interrupt thread, where we want the head of the queue and not the
10110  * end
10111  *
10112  * The callers of this routine should take measures to save the
10113  * un_throttle in un_last_throttle which will be restored in
10114  * st_intr_restart(). The only exception should be st_intr_restart()
10115  * calling this routine for which the saving is already done.
10116  */
10117 static int
10118 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
10119 	clock_t timeout_interval)
10120 {
10121 
10122 	int queued;
10123 	int rval = 0;
10124 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
10125 
10126 	mutex_enter(ST_MUTEX);
10127 
10128 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
10129 
10130 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10131 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
10132 
10133 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
10134 		queued = 1;
10135 	} else {
10136 		queued = 0;
10137 	}
10138 
10139 	/*
10140 	 * Check to see if we hit the retry timeout. We check to make sure
10141 	 * this is the first one on the runq and make sure we have not
10142 	 * queued up any more, so this one has to be the last on the list
10143 	 * also. If it is not, we have to fail.  If it is not the first, but
10144 	 * is the last we are in trouble anyway, as we are in the interrupt
10145 	 * context here.
10146 	 */
10147 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
10148 	    ((un->un_runqf != bp) && (un->un_runql != bp) && (queued))) {
10149 		rval = -1;
10150 		goto exit;
10151 	}
10152 
10153 	/* put the bp back on the waitq */
10154 	if (queued) {
10155 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
10156 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
10157 	}
10158 
10159 	/*
10160 	 * We don't want any other commands being started in the mean time.
10161 	 * If start had just released mutex after putting something on the
10162 	 * runq, we won't even get here.
10163 	 */
10164 	un->un_throttle = 0;
10165 
10166 	/*
10167 	 * send a marker pkt, if appropriate
10168 	 */
10169 	st_hba_unflush(un);
10170 
10171 	/*
10172 	 * all queues are aligned, we are just waiting to
10173 	 * transport
10174 	 */
10175 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
10176 
10177 exit:
10178 	mutex_exit(ST_MUTEX);
10179 	return (rval);
10180 }
10181 
10182 /*
10183  * To get one error entry from error stack
10184  */
10185 static int
10186 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
10187 {
10188 #ifdef _MULTI_DATAMODEL
10189 	/*
10190 	 * For use when a 32 bit app makes a call into a
10191 	 * 64 bit ioctl
10192 	 */
10193 	struct mterror_entry32 err_entry32;
10194 #endif /* _MULTI_DATAMODEL */
10195 
10196 	int rval = 0;
10197 	struct mterror_entry err_entry;
10198 	struct mterror_entry_stack *err_link_entry_p;
10199 	size_t arq_status_len_in, arq_status_len_kr;
10200 
10201 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
10202 
10203 	ASSERT(mutex_owned(ST_MUTEX));
10204 
10205 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10206 	    "st_get_error_entry()\n");
10207 
10208 	/*
10209 	 * if error record stack empty, return ENXIO
10210 	 */
10211 	if (un->un_error_entry_stk == NULL) {
10212 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10213 		    "st_get_error_entry: Error Entry Stack Empty!\n");
10214 		rval = ENXIO;
10215 		goto ret;
10216 	}
10217 
10218 	/*
10219 	 * get the top entry from stack
10220 	 */
10221 	err_link_entry_p = un->un_error_entry_stk;
10222 	arq_status_len_kr =
10223 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
10224 
10225 #ifdef _MULTI_DATAMODEL
10226 	switch (ddi_model_convert_from(flag & FMODELS)) {
10227 	case DDI_MODEL_ILP32:
10228 		if (ddi_copyin((void *)arg, &err_entry32,
10229 		    MTERROR_ENTRY_SIZE_32, flag)) {
10230 			rval = EFAULT;
10231 			goto ret;
10232 		}
10233 
10234 		arq_status_len_in =
10235 		    (size_t)err_entry32.mtee_arq_status_len;
10236 
10237 		err_entry32.mtee_cdb_len =
10238 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
10239 
10240 		if (arq_status_len_in > arq_status_len_kr)
10241 			err_entry32.mtee_arq_status_len =
10242 			    (size32_t)arq_status_len_kr;
10243 
10244 		if (ddi_copyout(
10245 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10246 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
10247 		    err_entry32.mtee_cdb_len, flag)) {
10248 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10249 			    "st_get_error_entry: Copy cdb buffer error!");
10250 			rval = EFAULT;
10251 		}
10252 
10253 		if (ddi_copyout(
10254 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10255 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
10256 		    err_entry32.mtee_arq_status_len, flag)) {
10257 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10258 			    "st_get_error_entry: copy arq status error!");
10259 			rval = EFAULT;
10260 		}
10261 
10262 		if (ddi_copyout(&err_entry32, (void *)arg,
10263 		    MTERROR_ENTRY_SIZE_32, flag)) {
10264 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10265 			    "st_get_error_entry: copy arq status out error!");
10266 			rval = EFAULT;
10267 		}
10268 		break;
10269 
10270 	case DDI_MODEL_NONE:
10271 		if (ddi_copyin((void *)arg, &err_entry,
10272 		    MTERROR_ENTRY_SIZE_64, flag)) {
10273 			rval = EFAULT;
10274 			goto ret;
10275 		}
10276 		arq_status_len_in = err_entry.mtee_arq_status_len;
10277 
10278 		err_entry.mtee_cdb_len =
10279 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
10280 
10281 		if (arq_status_len_in > arq_status_len_kr)
10282 			err_entry.mtee_arq_status_len =
10283 			    arq_status_len_kr;
10284 
10285 		if (ddi_copyout(
10286 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10287 		    err_entry.mtee_cdb_buf,
10288 		    err_entry.mtee_cdb_len, flag)) {
10289 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10290 			    "st_get_error_entry: Copy cdb buffer error!");
10291 			rval = EFAULT;
10292 		}
10293 
10294 		if (ddi_copyout(
10295 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10296 		    err_entry.mtee_arq_status,
10297 		    err_entry.mtee_arq_status_len, flag)) {
10298 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10299 			    "st_get_error_entry: copy arq status error!");
10300 			rval = EFAULT;
10301 		}
10302 
10303 		if (ddi_copyout(&err_entry, (void *)arg,
10304 		    MTERROR_ENTRY_SIZE_64, flag)) {
10305 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10306 			    "st_get_error_entry: copy arq status out error!");
10307 			rval = EFAULT;
10308 		}
10309 		break;
10310 	}
10311 #else /* _MULTI_DATAMODEL */
10312 	if (ddi_copyin((void *)arg, &err_entry,
10313 	    MTERROR_ENTRY_SIZE_64, flag)) {
10314 		rval = EFAULT;
10315 		goto ret;
10316 	}
10317 	arq_status_len_in = err_entry.mtee_arq_status_len;
10318 
10319 	err_entry.mtee_cdb_len =
10320 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
10321 
10322 	if (arq_status_len_in > arq_status_len_kr)
10323 		err_entry.mtee_arq_status_len =
10324 		    arq_status_len_kr;
10325 
10326 	if (ddi_copyout(
10327 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10328 	    err_entry.mtee_cdb_buf,
10329 	    err_entry.mtee_cdb_len, flag)) {
10330 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10331 		    "st_get_error_entry: Copy cdb buffer error!");
10332 		rval = EFAULT;
10333 	}
10334 
10335 	if (ddi_copyout(
10336 	    err_link_entry_p->mtees_entry.mtee_arq_status,
10337 	    err_entry.mtee_arq_status,
10338 	    err_entry.mtee_arq_status_len, flag)) {
10339 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10340 		    "st_get_error_entry: copy arq status buffer error!");
10341 		rval = EFAULT;
10342 	}
10343 
10344 	if (ddi_copyout(&err_entry, (void *)arg,
10345 	    MTERROR_ENTRY_SIZE_64, flag)) {
10346 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10347 		    "st_get_error_entry: copy arq status out error!");
10348 		rval = EFAULT;
10349 	}
10350 #endif /* _MULTI_DATAMODEL */
10351 
10352 	/*
10353 	 * update stack
10354 	 */
10355 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
10356 
10357 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
10358 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
10359 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
10360 
10361 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
10362 	    SECMDS_STATUS_SIZE);
10363 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
10364 
10365 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
10366 	err_link_entry_p = NULL;
10367 ret:
10368 	return (rval);
10369 }
10370 
10371 /*
10372  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
10373  * the scsi CDB command which causes the error and generates sense data and
10374  * the scsi status.
10375  *
10376  *      error-record stack
10377  *
10378  *
10379  *             TOP                                     BOTTOM
10380  *              ------------------------------------------
10381  *              |   0   |   1   |   2   |   ...  |   n   |
10382  *              ------------------------------------------
10383  *                  ^
10384  *                  |
10385  *       pointer to error entry
10386  *
10387  * when st driver generates one sense data record, it creates a error-entry
10388  * and pushes it onto the stack.
10389  *
10390  */
10391 
10392 static void
10393 st_update_error_stack(struct scsi_tape *un,
10394 			struct scsi_pkt *pkt,
10395 			struct scsi_arq_status *cmd)
10396 {
10397 	struct mterror_entry_stack *err_entry_tmp;
10398 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
10399 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
10400 
10401 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
10402 
10403 	ASSERT(mutex_owned(ST_MUTEX));
10404 
10405 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10406 	    "st_update_error_stack()\n");
10407 
10408 	ASSERT(cmd);
10409 	ASSERT(cdbp);
10410 	if (cdblen == 0) {
10411 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10412 		    "st_update_error_stack: CDB length error!\n");
10413 		return;
10414 	}
10415 
10416 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
10417 	ASSERT(err_entry_tmp != NULL);
10418 
10419 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
10420 	    kmem_alloc(cdblen, KM_SLEEP);
10421 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
10422 
10423 	err_entry_tmp->mtees_entry.mtee_arq_status =
10424 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
10425 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
10426 
10427 	/*
10428 	 * copy cdb command & length to current error entry
10429 	 */
10430 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
10431 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
10432 
10433 	/*
10434 	 * copy scsi status length to current error entry
10435 	 */
10436 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
10437 	    SECMDS_STATUS_SIZE;
10438 
10439 	/*
10440 	 * copy sense data and scsi status to current error entry
10441 	 */
10442 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
10443 	    SECMDS_STATUS_SIZE);
10444 
10445 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
10446 	un->un_error_entry_stk = err_entry_tmp;
10447 
10448 }
10449 
10450 /*
10451  * Empty all the error entry in stack
10452  */
10453 static void
10454 st_empty_error_stack(struct scsi_tape *un)
10455 {
10456 	struct mterror_entry_stack *linkp;
10457 
10458 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
10459 
10460 	ASSERT(mutex_owned(ST_MUTEX));
10461 
10462 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10463 	    "st_empty_entry_stack()\n");
10464 
10465 	while (un->un_error_entry_stk != NULL) {
10466 		linkp = un->un_error_entry_stk;
10467 		un->un_error_entry_stk =
10468 		    un->un_error_entry_stk->mtees_nextp;
10469 
10470 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
10471 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
10472 			    linkp->mtees_entry.mtee_cdb_len);
10473 
10474 		if (linkp->mtees_entry.mtee_arq_status != NULL)
10475 			kmem_free(linkp->mtees_entry.mtee_arq_status,
10476 			    linkp->mtees_entry.mtee_arq_status_len);
10477 
10478 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
10479 		linkp = NULL;
10480 	}
10481 }
10482 
10483 static errstate
10484 st_handle_sense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10485 {
10486 	struct scsi_pkt *pkt = BP_PKT(bp);
10487 	struct scsi_pkt *rqpkt = un->un_rqs;
10488 	struct scsi_arq_status arqstat;
10489 	recov_info *rcif = pkt->pkt_private;
10490 
10491 	errstate rval = COMMAND_DONE_ERROR;
10492 	int amt;
10493 
10494 	ST_FUNC(ST_DEVINFO, st_handle_sense);
10495 
10496 	ASSERT(mutex_owned(ST_MUTEX));
10497 
10498 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10499 	    "st_handle_sense()\n");
10500 
10501 	if (SCBP(rqpkt)->sts_busy) {
10502 		if (rcif->privatelen == sizeof (recov_info)) {
10503 			ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
10504 			    "Attempt recovery of busy unit on request sense\n");
10505 			rval = ATTEMPT_RETRY;
10506 		} else if (rcif->pkt_retry_cnt++ < st_retry_count) {
10507 			ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10508 			    "Retry busy unit on request sense\n");
10509 			rval = QUE_BUSY_COMMAND;
10510 		}
10511 		return (rval);
10512 	} else if (SCBP(rqpkt)->sts_chk) {
10513 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10514 		    "Check Condition on REQUEST SENSE\n");
10515 		return (rval);
10516 	}
10517 
10518 	/*
10519 	 * Make sure there is sense data to look at.
10520 	 */
10521 	if ((rqpkt->pkt_state & (STATE_GOT_BUS | STATE_GOT_TARGET |
10522 	    STATE_SENT_CMD | STATE_GOT_STATUS)) != (STATE_GOT_BUS |
10523 	    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) {
10524 		return (rval);
10525 	}
10526 
10527 	/* was there enough data? */
10528 	amt = (int)MAX_SENSE_LENGTH - rqpkt->pkt_resid;
10529 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
10530 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10531 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10532 		    "REQUEST SENSE couldn't get sense data\n");
10533 		return (rval);
10534 	}
10535 
10536 	bcopy(SCBP(pkt), &arqstat.sts_status,
10537 	    sizeof (struct scsi_status));
10538 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
10539 	    sizeof (struct scsi_status));
10540 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
10541 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
10542 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
10543 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
10544 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
10545 
10546 	/*
10547 	 * copy one arqstat entry in the sense data buffer
10548 	 */
10549 	st_update_error_stack(un, pkt, &arqstat);
10550 	return (st_decode_sense(un, bp, amt, &arqstat, pos));
10551 }
10552 
10553 static errstate
10554 st_handle_autosense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10555 {
10556 	struct scsi_pkt *pkt = BP_PKT(bp);
10557 	struct scsi_arq_status *arqstat =
10558 	    (struct scsi_arq_status *)pkt->pkt_scbp;
10559 	errstate rval = COMMAND_DONE_ERROR;
10560 	int amt;
10561 
10562 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
10563 
10564 	ASSERT(mutex_owned(ST_MUTEX));
10565 
10566 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10567 	    "st_handle_autosense()\n");
10568 
10569 	if (arqstat->sts_rqpkt_status.sts_busy) {
10570 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10571 		    "busy unit on request sense\n");
10572 		/*
10573 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
10574 		 * the disadvantage is that we do not have any delay for the
10575 		 * second retry of rqsense and we have to keep a packet around
10576 		 */
10577 		return (QUE_SENSE);
10578 
10579 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
10580 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10581 		    "transport error on REQUEST SENSE\n");
10582 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
10583 		    ((arqstat->sts_rqpkt_statistics &
10584 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
10585 			if (st_reset(un, RESET_LUN) == 0) {
10586 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10587 				    "recovery by resets failed\n");
10588 			}
10589 		}
10590 		return (rval);
10591 
10592 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
10593 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10594 		    "Check Condition on REQUEST SENSE\n");
10595 		return (rval);
10596 	}
10597 
10598 
10599 	/* was there enough data? */
10600 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10601 		amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10602 	} else {
10603 		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
10604 			amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10605 		} else {
10606 			amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10607 		}
10608 	}
10609 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
10610 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10611 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10612 		    "REQUEST SENSE couldn't get sense data\n");
10613 		return (rval);
10614 	}
10615 
10616 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10617 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, MAX_SENSE_LENGTH);
10618 	} else {
10619 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
10620 	}
10621 
10622 	/*
10623 	 * copy one arqstat entry in the sense data buffer
10624 	 */
10625 	st_update_error_stack(un, pkt, arqstat);
10626 
10627 	return (st_decode_sense(un, bp, amt, arqstat, pos));
10628 }
10629 
10630 static errstate
10631 st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
10632     struct scsi_arq_status *statusp, tapepos_t *pos)
10633 {
10634 	struct scsi_pkt *pkt = BP_PKT(bp);
10635 	recov_info *ri = pkt->pkt_private;
10636 	errstate rval = COMMAND_DONE_ERROR;
10637 	cmd_attribute const *attrib;
10638 	long resid;
10639 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10640 	int severity;
10641 	int get_error;
10642 
10643 	ST_FUNC(ST_DEVINFO, st_decode_sense);
10644 
10645 	ASSERT(mutex_owned(ST_MUTEX));
10646 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10647 	    "st_decode_sense()\n");
10648 
10649 	/*
10650 	 * For uscsi commands, squirrel away a copy of the
10651 	 * results of the Request Sense.
10652 	 */
10653 	if (USCSI_CMD(bp)) {
10654 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
10655 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
10656 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
10657 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
10658 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
10659 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
10660 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10661 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
10662 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
10663 		}
10664 	}
10665 
10666 	if (ri->privatelen == sizeof (recov_info)) {
10667 		attrib = ri->cmd_attrib;
10668 	} else {
10669 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10670 	}
10671 
10672 	/*
10673 	 * If the drive is an MT-02, reposition the
10674 	 * secondary error code into the proper place.
10675 	 *
10676 	 * XXX	MT-02 is non-CCS tape, so secondary error code
10677 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
10678 	 * so it's in byte 12.
10679 	 */
10680 	if (un->un_dp->type == ST_TYPE_EMULEX) {
10681 		sensep->es_code = sensep->es_add_info[0];
10682 	}
10683 
10684 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
10685 	    (caddr_t)&CDBP(pkt)->scc_cmd);
10686 
10687 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)statusp,
10688 	    sizeof (*statusp));
10689 
10690 	/* for normal I/O check extract the resid values. */
10691 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
10692 		if (sensep->es_valid) {
10693 			resid =
10694 			    (sensep->es_info_1 << 24) |
10695 			    (sensep->es_info_2 << 16) |
10696 			    (sensep->es_info_3 << 8)  |
10697 			    (sensep->es_info_4);
10698 			/* If fixed block */
10699 			if (un->un_bsize) {
10700 				resid *= un->un_bsize;
10701 			}
10702 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
10703 			resid = pkt->pkt_resid;
10704 		} else {
10705 			resid = bp->b_bcount;
10706 		}
10707 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10708 		    "st_decode_sense (rw): xferred bit = %d, resid=%ld (%d), "
10709 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
10710 		    resid,
10711 		    (sensep->es_info_1 << 24) |
10712 		    (sensep->es_info_2 << 16) |
10713 		    (sensep->es_info_3 << 8)  |
10714 		    (sensep->es_info_4),
10715 		    pkt->pkt_resid);
10716 		/*
10717 		 * The problem is, what should we believe?
10718 		 */
10719 		if (resid && (pkt->pkt_resid == 0)) {
10720 			pkt->pkt_resid = resid;
10721 		}
10722 	} else {
10723 		/*
10724 		 * If the command is SCMD_SPACE, we need to get the
10725 		 * residual as returned in the sense data, to adjust
10726 		 * our idea of current tape position correctly
10727 		 */
10728 		if ((sensep->es_valid) &&
10729 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10730 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10731 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
10732 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE_G4) ||
10733 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK)) {
10734 			resid =
10735 			    (sensep->es_info_1 << 24) |
10736 			    (sensep->es_info_2 << 16) |
10737 			    (sensep->es_info_3 << 8)  |
10738 			    (sensep->es_info_4);
10739 			bp->b_resid = resid;
10740 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10741 			    "st_decode_sense(other):	resid=%ld\n", resid);
10742 		} else {
10743 			/*
10744 			 * If the special command is SCMD_READ,
10745 			 * the correct resid will be set later.
10746 			 */
10747 			if (attrib->get_cnt != NULL) {
10748 				resid = attrib->get_cnt(pkt->pkt_cdbp);
10749 			} else {
10750 				resid = bp->b_bcount;
10751 			}
10752 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10753 			    "st_decode_sense(special read):  resid=%ld\n",
10754 			    resid);
10755 		}
10756 	}
10757 
10758 	if ((un->un_state >= ST_STATE_OPEN) &&
10759 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
10760 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
10761 		    "Failed CDB", (char *)pkt->pkt_cdbp);
10762 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10763 		    "sense data", (char *)sensep, amt);
10764 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10765 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10766 		    bp->b_bcount, resid, pkt->pkt_resid);
10767 	}
10768 
10769 	switch (un->un_status = sensep->es_key) {
10770 	case KEY_NO_SENSE:
10771 		severity = SCSI_ERR_INFO;
10772 
10773 		/*
10774 		 * Erase, locate or rewind operation in progress, retry
10775 		 * ASC  ASCQ
10776 		 *  00   18    Erase operation in progress
10777 		 *  00   19    Locate operation in progress
10778 		 *  00   1A    Rewind operation in progress
10779 		 */
10780 		if (sensep->es_add_code == 0 &&
10781 		    ((sensep->es_qual_code == 0x18) ||
10782 		    (sensep->es_qual_code == 0x19) ||
10783 		    (sensep->es_qual_code == 0x1a))) {
10784 			rval = QUE_BUSY_COMMAND;
10785 			break;
10786 		}
10787 
10788 		goto common;
10789 
10790 	case KEY_RECOVERABLE_ERROR:
10791 		severity = SCSI_ERR_RECOVERED;
10792 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10793 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10794 			if (un->un_dp->options &
10795 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10796 				rval = QUE_LAST_COMMAND;
10797 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10798 				    severity, pos->lgclblkno,
10799 				    un->un_err_pos.lgclblkno, scsi_cmds,
10800 				    sensep);
10801 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10802 				    "Command will be retried\n");
10803 			} else {
10804 				severity = SCSI_ERR_FATAL;
10805 				rval = COMMAND_DONE_ERROR_RECOVERED;
10806 				ST_DO_ERRSTATS(un, st_softerrs);
10807 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10808 				    severity, pos->lgclblkno,
10809 				    un->un_err_pos.lgclblkno, scsi_cmds,
10810 				    sensep);
10811 			}
10812 			break;
10813 		}
10814 common:
10815 		/*
10816 		 * XXX only want reads to be stopped by filemarks.
10817 		 * Don't want them to be stopped by EOT.  EOT matters
10818 		 * only on write.
10819 		 */
10820 		if (sensep->es_filmk && !sensep->es_eom) {
10821 			rval = COMMAND_DONE;
10822 		} else if (sensep->es_eom) {
10823 			rval = COMMAND_DONE;
10824 		} else if (sensep->es_ili) {
10825 			/*
10826 			 * Fun with variable length record devices:
10827 			 * for specifying larger blocks sizes than the
10828 			 * actual physical record size.
10829 			 */
10830 			if (un->un_bsize == 0 && resid > 0) {
10831 				/*
10832 				 * XXX! Ugly.
10833 				 * The requested blocksize is > tape blocksize,
10834 				 * so this is ok, so we just return the
10835 				 * actual size xferred.
10836 				 */
10837 				pkt->pkt_resid = resid;
10838 				rval = COMMAND_DONE;
10839 			} else if (un->un_bsize == 0 && resid < 0) {
10840 				/*
10841 				 * The requested blocksize is < tape blocksize,
10842 				 * so this is not ok, so we err with ENOMEM
10843 				 */
10844 				rval = COMMAND_DONE_ERROR_RECOVERED;
10845 				st_bioerror(bp, ENOMEM);
10846 			} else {
10847 				ST_DO_ERRSTATS(un, st_softerrs);
10848 				severity = SCSI_ERR_FATAL;
10849 				rval = COMMAND_DONE_ERROR;
10850 				st_bioerror(bp, EINVAL);
10851 				un->un_running.pmode = invalid;
10852 			}
10853 		} else {
10854 			/*
10855 			 * we hope and pray for this just being
10856 			 * something we can ignore (ie. a
10857 			 * truly recoverable soft error)
10858 			 */
10859 			rval = COMMAND_DONE;
10860 		}
10861 		if (sensep->es_filmk) {
10862 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10863 			    "filemark\n");
10864 			un->un_status = SUN_KEY_EOF;
10865 			pos->eof = ST_EOF_PENDING;
10866 			st_set_pe_flag(un);
10867 		}
10868 
10869 		/*
10870 		 * ignore eom when reading, a fmk should terminate reading
10871 		 */
10872 		if ((sensep->es_eom) &&
10873 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10874 			if ((sensep->es_add_code == 0) &&
10875 			    (sensep->es_qual_code == 4)) {
10876 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10877 				    "bot\n");
10878 				un->un_status = SUN_KEY_BOT;
10879 				pos->eof = ST_NO_EOF;
10880 				pos->lgclblkno = 0;
10881 				pos->fileno = 0;
10882 				pos->blkno = 0;
10883 				if (pos->pmode != legacy)
10884 					pos->pmode = legacy;
10885 			} else {
10886 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10887 				    "eom\n");
10888 				un->un_status = SUN_KEY_EOT;
10889 				pos->eof = ST_EOM;
10890 			}
10891 			st_set_pe_flag(un);
10892 		}
10893 
10894 		break;
10895 
10896 	case KEY_ILLEGAL_REQUEST:
10897 
10898 		if (un->un_laststate >= ST_STATE_OPEN) {
10899 			ST_DO_ERRSTATS(un, st_softerrs);
10900 			severity = SCSI_ERR_FATAL;
10901 		} else {
10902 			severity = SCSI_ERR_INFO;
10903 		}
10904 		break;
10905 
10906 	case KEY_MEDIUM_ERROR:
10907 		ST_DO_ERRSTATS(un, st_harderrs);
10908 		severity = SCSI_ERR_FATAL;
10909 		un->un_pos.pmode = invalid;
10910 		un->un_running.pmode = invalid;
10911 check_keys:
10912 		/*
10913 		 * attempt to process the keys in the presence of
10914 		 * other errors
10915 		 */
10916 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10917 			/*
10918 			 * Fun with variable length record devices:
10919 			 * for specifying larger blocks sizes than the
10920 			 * actual physical record size.
10921 			 */
10922 			if (un->un_bsize == 0 && resid > 0) {
10923 				/*
10924 				 * XXX! Ugly
10925 				 */
10926 				pkt->pkt_resid = resid;
10927 			} else if (un->un_bsize == 0 && resid < 0) {
10928 				st_bioerror(bp, EINVAL);
10929 			} else {
10930 				severity = SCSI_ERR_FATAL;
10931 				rval = COMMAND_DONE_ERROR;
10932 				st_bioerror(bp, EINVAL);
10933 			}
10934 		}
10935 		if (sensep->es_filmk) {
10936 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10937 			    "filemark\n");
10938 			un->un_status = SUN_KEY_EOF;
10939 			pos->eof = ST_EOF_PENDING;
10940 			st_set_pe_flag(un);
10941 		}
10942 
10943 		/*
10944 		 * ignore eom when reading, a fmk should terminate reading
10945 		 */
10946 		if ((sensep->es_eom) &&
10947 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10948 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10949 			un->un_status = SUN_KEY_EOT;
10950 			pos->eof = ST_EOM;
10951 			st_set_pe_flag(un);
10952 		}
10953 
10954 		break;
10955 
10956 	case KEY_VOLUME_OVERFLOW:
10957 		ST_DO_ERRSTATS(un, st_softerrs);
10958 		pos->eof = ST_EOM;
10959 		severity = SCSI_ERR_FATAL;
10960 		rval = COMMAND_DONE_ERROR;
10961 		goto check_keys;
10962 
10963 	case KEY_HARDWARE_ERROR:
10964 		ST_DO_ERRSTATS(un, st_harderrs);
10965 		severity = SCSI_ERR_FATAL;
10966 		rval = COMMAND_DONE_ERROR;
10967 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10968 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10969 		break;
10970 
10971 	case KEY_BLANK_CHECK:
10972 		ST_DO_ERRSTATS(un, st_softerrs);
10973 		severity = SCSI_ERR_INFO;
10974 
10975 		/*
10976 		 * if not a special request and some data was xferred then it
10977 		 * it is not an error yet
10978 		 */
10979 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10980 			/*
10981 			 * no error for read with or without data xferred
10982 			 */
10983 			un->un_status = SUN_KEY_EOT;
10984 			pos->eof = ST_EOT;
10985 			rval = COMMAND_DONE_ERROR;
10986 			un->un_running.pmode = invalid;
10987 			st_set_pe_flag(un);
10988 			goto check_keys;
10989 		} else if (bp != un->un_sbufp &&
10990 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10991 			rval = COMMAND_DONE;
10992 		} else {
10993 			rval = COMMAND_DONE_ERROR_RECOVERED;
10994 		}
10995 
10996 		if (un->un_laststate >= ST_STATE_OPEN) {
10997 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10998 			    "blank check\n");
10999 			pos->eof = ST_EOM;
11000 		}
11001 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
11002 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
11003 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
11004 		    (un->un_dp->options & ST_KNOWS_EOD)) {
11005 			/*
11006 			 * we were doing a fast forward by skipping
11007 			 * multiple fmk at the time
11008 			 */
11009 			st_bioerror(bp, EIO);
11010 			severity = SCSI_ERR_RECOVERED;
11011 			rval	 = COMMAND_DONE;
11012 		}
11013 		st_set_pe_flag(un);
11014 		goto check_keys;
11015 
11016 	case KEY_WRITE_PROTECT:
11017 		if (st_wrongtapetype(un)) {
11018 			un->un_status = SUN_KEY_WRONGMEDIA;
11019 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11020 			    "wrong tape for writing- use DC6150 tape "
11021 			    "(or equivalent)\n");
11022 			severity = SCSI_ERR_UNKNOWN;
11023 		} else {
11024 			severity = SCSI_ERR_FATAL;
11025 		}
11026 		ST_DO_ERRSTATS(un, st_harderrs);
11027 		rval = COMMAND_DONE_ERROR;
11028 		st_bioerror(bp, EACCES);
11029 		break;
11030 
11031 	case KEY_UNIT_ATTENTION:
11032 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11033 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
11034 
11035 		un->un_unit_attention_flags |= 1;
11036 		/*
11037 		 * If we have detected a Bus Reset and the tape
11038 		 * drive has been reserved.
11039 		 */
11040 		if (ST_RQSENSE->es_add_code == 0x29) {
11041 			rval = DEVICE_RESET;
11042 			if ((un->un_rsvd_status &
11043 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
11044 			    ST_RESERVE) {
11045 				un->un_rsvd_status |= ST_LOST_RESERVE;
11046 				ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
11047 				    "st_decode_sense: Lost Reservation\n");
11048 			}
11049 		}
11050 
11051 		/*
11052 		 * If this is a recovery command and retrable, retry.
11053 		 */
11054 		if (bp == un->un_recov_buf) {
11055 			severity = SCSI_ERR_INFO;
11056 			if (attrib->retriable &&
11057 			    ri->pkt_retry_cnt++ < st_retry_count) {
11058 				rval = QUE_COMMAND;
11059 			} else {
11060 				rval = COMMAND_DONE_ERROR;
11061 			}
11062 			break; /* Don't set position invalid */
11063 		}
11064 
11065 		/*
11066 		 * If ST_APPLICATION_RESERVATIONS is set,
11067 		 * If the asc/ascq indicates that the reservation
11068 		 * has been cleared just allow the write to continue
11069 		 * which would force a scsi 2 reserve.
11070 		 * If preempted that persistent reservation
11071 		 * the scsi 2 reserve would get a reservation conflict.
11072 		 */
11073 		if ((un->un_rsvd_status &
11074 		    ST_APPLICATION_RESERVATIONS) != 0) {
11075 			/*
11076 			 * RESERVATIONS PREEMPTED
11077 			 * With MPxIO this could be a fail over? XXX
11078 			 */
11079 			if (ST_RQSENSE->es_add_code == 0x2a &&
11080 			    ST_RQSENSE->es_qual_code == 0x03) {
11081 				severity = SCSI_ERR_INFO;
11082 				rval = COMMAND_DONE_ERROR;
11083 				pos->pmode = invalid;
11084 				break;
11085 			/*
11086 			 * RESERVATIONS RELEASED
11087 			 */
11088 			} else if (ST_RQSENSE->es_add_code == 0x2a &&
11089 			    ST_RQSENSE->es_qual_code == 0x04) {
11090 				severity = SCSI_ERR_INFO;
11091 				rval = COMMAND_DONE;
11092 				break;
11093 			}
11094 		}
11095 
11096 		if (un->un_state <= ST_STATE_OPENING) {
11097 			/*
11098 			 * Look, the tape isn't open yet, now determine
11099 			 * if the cause is a BUS RESET, Save the file
11100 			 * and Block positions for the callers to
11101 			 * recover from the loss of position.
11102 			 */
11103 			severity = SCSI_ERR_INFO;
11104 			if ((pos->pmode != invalid) &&
11105 			    (rval == DEVICE_RESET) &&
11106 			    (un->un_restore_pos != 1)) {
11107 				un->un_save_fileno = pos->fileno;
11108 				un->un_save_blkno = pos->blkno;
11109 				un->un_restore_pos = 1;
11110 			}
11111 
11112 			if (attrib->retriable &&
11113 			    ri->pkt_retry_cnt++ < st_retry_count) {
11114 				rval = QUE_COMMAND;
11115 			} else if (rval == DEVICE_RESET) {
11116 				break;
11117 			} else {
11118 				rval = COMMAND_DONE_ERROR;
11119 			}
11120 		/*
11121 		 * Means it thinks the mode parameters have changed.
11122 		 * This is the result of a reset clearing settings or
11123 		 * another initiator changing what we set.
11124 		 */
11125 		}
11126 		if (ST_RQSENSE->es_add_code == 0x2a) {
11127 			if (ST_RQSENSE->es_qual_code == 0x1) {
11128 				/* Error recovery will modeselect and retry. */
11129 				rval = DEVICE_TAMPER;
11130 				severity = SCSI_ERR_INFO;
11131 				break; /* don't set position invalid */
11132 			}
11133 			if (ST_RQSENSE->es_qual_code == 0x0 ||
11134 			    ST_RQSENSE->es_qual_code == 0x2 ||
11135 			    ST_RQSENSE->es_qual_code == 0x3 ||
11136 			    ST_RQSENSE->es_qual_code == 0x4 ||
11137 			    ST_RQSENSE->es_qual_code == 0x5 ||
11138 			    ST_RQSENSE->es_qual_code == 0x6 ||
11139 			    ST_RQSENSE->es_qual_code == 0x7) {
11140 				rval = DEVICE_TAMPER;
11141 				severity = SCSI_ERR_INFO;
11142 			}
11143 		} else if (ST_RQSENSE->es_add_code == 0x28 &&
11144 		    ((ST_RQSENSE->es_qual_code == 0x0) ||
11145 		    ST_RQSENSE->es_qual_code == 0x5)) {
11146 			/*
11147 			 * Not Ready to Ready change, Media may have changed.
11148 			 */
11149 			rval = DEVICE_TAMPER;
11150 			severity = SCSI_ERR_RETRYABLE;
11151 		} else {
11152 			if (rval != DEVICE_RESET) {
11153 				rval = COMMAND_DONE_ERROR;
11154 			} else {
11155 				/*
11156 				 * Returning DEVICE_RESET will call
11157 				 * error recovery.
11158 				 */
11159 				severity = SCSI_ERR_INFO;
11160 				break; /* don't set position invalid */
11161 			}
11162 			/*
11163 			 * Check if it is an Unexpected Unit Attention.
11164 			 * If state is >= ST_STATE_OPEN, we have
11165 			 * already done the initialization .
11166 			 * In this case it is Fatal Error
11167 			 * since no further reading/writing
11168 			 * can be done with fileno set to < 0.
11169 			 */
11170 			if (un->un_state >= ST_STATE_OPEN) {
11171 				ST_DO_ERRSTATS(un, st_harderrs);
11172 				severity = SCSI_ERR_FATAL;
11173 			} else {
11174 				severity = SCSI_ERR_INFO;
11175 			}
11176 		}
11177 
11178 		pos->pmode = invalid;
11179 
11180 		break;
11181 
11182 	case KEY_NOT_READY:
11183 		/*
11184 		 * If in process of getting ready retry.
11185 		 */
11186 		if (sensep->es_add_code == 0x04) {
11187 			switch (sensep->es_qual_code) {
11188 			case 0x07:
11189 				/*
11190 				 * We get here when the tape is rewinding.
11191 				 * QUE_BUSY_COMMAND retries every 10 seconds.
11192 				 */
11193 				if (ri->pkt_retry_cnt++ <
11194 				    (un->un_dp->rewind_timeout / 10)) {
11195 					rval = QUE_BUSY_COMMAND;
11196 					severity = SCSI_ERR_INFO;
11197 				} else {
11198 					/* give up */
11199 					rval = COMMAND_DONE_ERROR;
11200 					severity = SCSI_ERR_FATAL;
11201 				}
11202 				break;
11203 			case 0x01:
11204 				if (ri->pkt_retry_cnt++ < st_retry_count) {
11205 					rval = QUE_COMMAND;
11206 					severity = SCSI_ERR_INFO;
11207 					break;
11208 				}
11209 			default: /* FALLTHRU */
11210 				/* give up */
11211 				rval = COMMAND_DONE_ERROR;
11212 				severity = SCSI_ERR_FATAL;
11213 			}
11214 		} else {
11215 			/* give up */
11216 			rval = COMMAND_DONE_ERROR;
11217 			severity = SCSI_ERR_FATAL;
11218 		}
11219 
11220 		/*
11221 		 * If this was an error and after device opened
11222 		 * do error stats.
11223 		 */
11224 		if (rval == COMMAND_DONE_ERROR &&
11225 		    un->un_state > ST_STATE_OPENING) {
11226 			ST_DO_ERRSTATS(un, st_harderrs);
11227 		}
11228 
11229 		if (ST_RQSENSE->es_add_code == 0x3a) {
11230 			if (st_error_level >= SCSI_ERR_FATAL)
11231 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11232 				    "Tape not inserted in drive\n");
11233 			un->un_mediastate = MTIO_EJECTED;
11234 			cv_broadcast(&un->un_state_cv);
11235 		}
11236 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
11237 		    (rval != QUE_COMMAND))
11238 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
11239 		break;
11240 
11241 	case KEY_ABORTED_COMMAND:
11242 		/* XXX Do drives return this when they see a lost light? */
11243 		/* Testing would say yes */
11244 
11245 		if (ri->pkt_retry_cnt++ < st_retry_count) {
11246 			rval = ATTEMPT_RETRY;
11247 			severity = SCSI_ERR_RETRYABLE;
11248 			goto check_keys;
11249 		}
11250 		/*
11251 		 * Probably a parity error...
11252 		 * if we retry here then this may cause data to be
11253 		 * written twice or data skipped during reading
11254 		 */
11255 		ST_DO_ERRSTATS(un, st_harderrs);
11256 		severity = SCSI_ERR_FATAL;
11257 		rval = COMMAND_DONE_ERROR;
11258 		goto check_keys;
11259 
11260 	default:
11261 		/*
11262 		 * Undecoded sense key.	 Try retries and hope
11263 		 * that will fix the problem.  Otherwise, we're
11264 		 * dead.
11265 		 */
11266 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11267 		    "Unhandled Sense Key '%s'\n",
11268 		    sense_keys[un->un_status]);
11269 		ST_DO_ERRSTATS(un, st_harderrs);
11270 		severity = SCSI_ERR_FATAL;
11271 		rval = COMMAND_DONE_ERROR;
11272 		goto check_keys;
11273 	}
11274 
11275 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
11276 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
11277 	    (un->un_laststate > ST_STATE_OPENING) &&
11278 	    (severity >= st_error_level))) {
11279 
11280 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
11281 		    pos->lgclblkno, un->un_err_pos.lgclblkno,
11282 		    scsi_cmds, sensep);
11283 		if (sensep->es_filmk) {
11284 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11285 			    "File Mark Detected\n");
11286 		}
11287 		if (sensep->es_eom) {
11288 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11289 			    "End-of-Media Detected\n");
11290 		}
11291 		if (sensep->es_ili) {
11292 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11293 			    "Incorrect Length Indicator Set\n");
11294 		}
11295 	}
11296 	get_error = geterror(bp);
11297 	if (((rval == COMMAND_DONE_ERROR) ||
11298 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
11299 	    ((get_error == EIO) || (get_error == 0))) {
11300 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
11301 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
11302 		if (un->un_rqs_state & ST_RQS_READ) {
11303 			un->un_rqs_state &= ~(ST_RQS_READ);
11304 		} else {
11305 			un->un_rqs_state |= ST_RQS_OVR;
11306 		}
11307 	}
11308 
11309 	return (rval);
11310 }
11311 
11312 
11313 static int
11314 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
11315 {
11316 	int status = TRAN_ACCEPT;
11317 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
11318 
11319 	mutex_enter(ST_MUTEX);
11320 
11321 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
11322 
11323 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11324 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
11325 
11326 	/*
11327 	 * Check to see if we hit the retry timeout. We check to make sure
11328 	 * this is the first one on the runq and make sure we have not
11329 	 * queued up any more, so this one has to be the last on the list
11330 	 * also. If it is not, we have to fail.  If it is not the first, but
11331 	 * is the last we are in trouble anyway, as we are in the interrupt
11332 	 * context here.
11333 	 */
11334 	if ((pktinfo->pkt_retry_cnt > st_retry_count) ||
11335 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
11336 		goto exit;
11337 	}
11338 
11339 	if (un->un_throttle) {
11340 		un->un_last_throttle = un->un_throttle;
11341 		un->un_throttle = 0;
11342 	}
11343 
11344 	/*
11345 	 * Here we know : bp is the first and last one on the runq
11346 	 * it is not necessary to put it back on the head of the
11347 	 * waitq and then move from waitq to runq. Save this queuing
11348 	 * and call scsi_transport.
11349 	 */
11350 	ST_CDB(ST_DEVINFO, "Retry lcmd CDB", (char *)BP_PKT(bp)->pkt_cdbp);
11351 
11352 	status = st_transport(un, BP_PKT(bp));
11353 
11354 	if (status == TRAN_ACCEPT) {
11355 		if (un->un_last_throttle) {
11356 			un->un_throttle = un->un_last_throttle;
11357 		}
11358 		mutex_exit(ST_MUTEX);
11359 
11360 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11361 		    "restart transport \n");
11362 		return (0);
11363 	}
11364 
11365 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
11366 	mutex_exit(ST_MUTEX);
11367 
11368 	if (status == TRAN_BUSY) {
11369 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
11370 			return (0);
11371 		}
11372 	}
11373 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11374 	    "restart transport rejected\n");
11375 	mutex_enter(ST_MUTEX);
11376 	ST_DO_ERRSTATS(un, st_transerrs);
11377 	if (un->un_last_throttle) {
11378 		un->un_throttle = un->un_last_throttle;
11379 	}
11380 exit:
11381 	mutex_exit(ST_MUTEX);
11382 	return (-1);
11383 }
11384 
11385 static int
11386 st_wrongtapetype(struct scsi_tape *un)
11387 {
11388 
11389 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
11390 
11391 	ASSERT(mutex_owned(ST_MUTEX));
11392 
11393 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
11394 
11395 	/*
11396 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
11397 	 */
11398 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
11399 		switch (un->un_dp->type) {
11400 		case ST_TYPE_WANGTEK:
11401 		case ST_TYPE_ARCHIVE:
11402 			/*
11403 			 * If this really worked, we could go off of
11404 			 * the density codes set in the modesense
11405 			 * page. For this drive, 0x10 == QIC-120,
11406 			 * 0xf == QIC-150, and 0x5 should be for
11407 			 * both QIC-24 and, maybe, QIC-11. However,
11408 			 * the h/w doesn't do what the manual says
11409 			 * that it should, so we'll key off of
11410 			 * getting a WRITE PROTECT error AND wp *not*
11411 			 * set in the mode sense information.
11412 			 */
11413 			/*
11414 			 * XXX but we already know that status is
11415 			 * write protect, so don't check it again.
11416 			 */
11417 
11418 			if (un->un_status == KEY_WRITE_PROTECT &&
11419 			    un->un_mspl->wp == 0) {
11420 				return (1);
11421 			}
11422 			break;
11423 		default:
11424 			break;
11425 		}
11426 	}
11427 	return (0);
11428 }
11429 
11430 static errstate
11431 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
11432 {
11433 	errstate action;
11434 	recov_info *rcvi = pkt->pkt_private;
11435 	buf_t *bp = rcvi->cmd_bp;
11436 	struct scsi_arq_status *stat = (struct scsi_arq_status *)pkt->pkt_scbp;
11437 
11438 	ST_FUNC(ST_DEVINFO, st_check_error);
11439 
11440 	ASSERT(mutex_owned(ST_MUTEX));
11441 
11442 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
11443 
11444 	switch (SCBP_C(pkt)) {
11445 	case STATUS_RESERVATION_CONFLICT:
11446 		/*
11447 		 * Command recovery is enabled, not just opening,
11448 		 * we had the drive reserved and we thing its ours.
11449 		 * Call recovery to attempt to take it back.
11450 		 */
11451 		if ((rcvi->privatelen == sizeof (recov_info)) &&
11452 		    (bp != un->un_recov_buf) &&
11453 		    (un->un_state > ST_STATE_OPEN_PENDING_IO) &&
11454 		    ((un->un_rsvd_status & (ST_RESERVE |
11455 		    ST_APPLICATION_RESERVATIONS)) != 0)) {
11456 			action = ATTEMPT_RETRY;
11457 			un->un_rsvd_status |= ST_LOST_RESERVE;
11458 		} else {
11459 			action = COMMAND_DONE_EACCES;
11460 			un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
11461 		}
11462 		break;
11463 
11464 	case STATUS_BUSY:
11465 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
11466 		if (rcvi->privatelen == sizeof (recov_info) &&
11467 		    un->un_multipath && (pkt->pkt_state == (STATE_GOT_BUS |
11468 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS))) {
11469 			/*
11470 			 * Status returned by scsi_vhci indicating path
11471 			 * has failed over.
11472 			 */
11473 			action = PATH_FAILED;
11474 			break;
11475 		}
11476 		/* FALLTHRU */
11477 	case STATUS_QFULL:
11478 		if (rcvi->privatelen == sizeof (recov_info)) {
11479 			/*
11480 			 * If recovery is inabled use it instead of
11481 			 * blind reties.
11482 			 */
11483 			action = ATTEMPT_RETRY;
11484 		} else if (rcvi->pkt_retry_cnt++ < st_retry_count) {
11485 			action = QUE_BUSY_COMMAND;
11486 		} else if ((un->un_rsvd_status &
11487 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
11488 			/*
11489 			 * If this is a command done before reserve is done
11490 			 * don't reset.
11491 			 */
11492 			action = COMMAND_DONE_ERROR;
11493 		} else {
11494 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11495 			    "unit busy too long\n");
11496 			(void) st_reset(un, RESET_ALL);
11497 			action = COMMAND_DONE_ERROR;
11498 		}
11499 		break;
11500 
11501 	case STATUS_CHECK:
11502 	case STATUS_TERMINATED:
11503 		/*
11504 		 * we should only get here if the auto rqsense failed
11505 		 * thru a uscsi cmd without autorequest sense
11506 		 * so we just try again
11507 		 */
11508 		if (un->un_arq_enabled &&
11509 		    stat->sts_rqpkt_reason == CMD_CMPLT &&
11510 		    (stat->sts_rqpkt_state & (STATE_GOT_BUS |
11511 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) ==
11512 		    (STATE_GOT_BUS | STATE_GOT_TARGET | STATE_SENT_CMD |
11513 		    STATE_GOT_STATUS)) {
11514 
11515 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11516 			    "Really got sense data\n");
11517 			action = st_decode_sense(un, bp, MAX_SENSE_LENGTH -
11518 			    pkt->pkt_resid, stat, &un->un_pos);
11519 		} else {
11520 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11521 			    "Trying to queue sense command\n");
11522 			action = QUE_SENSE;
11523 		}
11524 		break;
11525 
11526 	case STATUS_TASK_ABORT:
11527 		/*
11528 		 * This is an aborted task. This can be a reset on the other
11529 		 * port of a multiport drive. Lets try and recover it.
11530 		 */
11531 		action = DEVICE_RESET;
11532 		break;
11533 
11534 	default:
11535 		action = COMMAND_DONE;
11536 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
11537 		    "Unexpected scsi status byte 0x%x\n", SCBP_C(pkt));
11538 	}
11539 	return (action);
11540 }
11541 
11542 static void
11543 st_calc_bnum(struct scsi_tape *un, struct buf *bp, struct scsi_pkt *pkt)
11544 {
11545 	int nblks;
11546 	int nfiles;
11547 	long count;
11548 	recov_info *ri = pkt->pkt_private;
11549 	cmd_attribute const *attrib;
11550 
11551 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
11552 
11553 	ASSERT(mutex_owned(ST_MUTEX));
11554 
11555 	if (ri->privatelen == sizeof (recov_info)) {
11556 		attrib = ri->cmd_attrib;
11557 		ASSERT(attrib->recov_pos_type == POS_EXPECTED);
11558 		ASSERT(attrib->chg_tape_pos);
11559 	} else {
11560 		ri = NULL;
11561 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
11562 	}
11563 
11564 	count = bp->b_bcount - bp->b_resid;
11565 
11566 	/* Command reads or writes data */
11567 	if (attrib->transfers_data != TRAN_NONE) {
11568 		if (count == 0) {
11569 			/* failed writes should not make it here */
11570 			ASSERT(attrib->transfers_data == TRAN_READ);
11571 			nblks = 0;
11572 			nfiles = 1;
11573 		} else if (un->un_bsize == 0) {
11574 			/*
11575 			 * If variable block mode.
11576 			 * Fixed bit in CBD should be zero.
11577 			 */
11578 			ASSERT((pkt->pkt_cdbp[1] & 1) == 0);
11579 			nblks = 1;
11580 			un->un_kbytes_xferred += (count / ONE_K);
11581 			nfiles = 0;
11582 		} else {
11583 			/*
11584 			 * If fixed block mode.
11585 			 * Fixed bit in CBD should be one.
11586 			 */
11587 			ASSERT((pkt->pkt_cdbp[1] & 1) == 1);
11588 			nblks = (count / un->un_bsize);
11589 			un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
11590 			nfiles = 0;
11591 		}
11592 		/*
11593 		 * So its possable to read some blocks and hit a filemark.
11594 		 * Example reading in fixed block mode where more then one
11595 		 * block at a time is requested. In this case because the
11596 		 * filemark is hit something less then the requesed number
11597 		 * of blocks is read.
11598 		 */
11599 		if (un->un_pos.eof == ST_EOF_PENDING && bp->b_resid) {
11600 			nfiles = 1;
11601 		}
11602 	} else {
11603 		nblks = 0;
11604 		nfiles = count;
11605 	}
11606 
11607 	/*
11608 	 * If some command failed after this one started and it seems
11609 	 * to have finshed without error count the position.
11610 	 */
11611 	if (un->un_persistence && un->un_persist_errors) {
11612 		ASSERT(un->un_pos.pmode != invalid);
11613 	}
11614 
11615 	if (attrib->chg_tape_direction == DIR_FORW) {
11616 		un->un_pos.blkno += nblks;
11617 		un->un_pos.lgclblkno += nblks;
11618 		un->un_pos.lgclblkno += nfiles;
11619 	} else if (attrib->chg_tape_direction == DIR_REVC) {
11620 		un->un_pos.blkno -= nblks;
11621 		un->un_pos.lgclblkno -= nblks;
11622 		un->un_pos.lgclblkno -= nfiles;
11623 	} else {
11624 		ASSERT(0);
11625 	}
11626 
11627 	/* recovery disabled */
11628 	if (ri == NULL) {
11629 		un->un_running.pmode = invalid;
11630 		return;
11631 	}
11632 
11633 	/*
11634 	 * If we didn't just read a filemark.
11635 	 */
11636 	if (un->un_pos.eof != ST_EOF_PENDING) {
11637 		ASSERT(nblks != 0 && nfiles == 0);
11638 		/*
11639 		 * If Previously calulated expected position does not match
11640 		 * debug the expected position.
11641 		 */
11642 		if ((ri->pos.pmode != invalid) && nblks &&
11643 		    ((un->un_pos.blkno != ri->pos.blkno) ||
11644 		    (un->un_pos.lgclblkno != ri->pos.lgclblkno))) {
11645 #ifdef STDEBUG
11646 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11647 			    "Expected", &ri->pos);
11648 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11649 			    "But Got", &un->un_pos);
11650 #endif
11651 			un->un_running.pmode = invalid;
11652 		}
11653 	} else {
11654 		ASSERT(nfiles != 0);
11655 		if (un->un_running.pmode != invalid) {
11656 			/*
11657 			 * blkno and lgclblkno already counted in
11658 			 * st_add_recovery_info_to_pkt(). Since a block was not
11659 			 * read and a filemark was.
11660 			 */
11661 			if (attrib->chg_tape_direction == DIR_FORW) {
11662 				un->un_running.fileno++;
11663 				un->un_running.blkno = 0;
11664 			} else if (attrib->chg_tape_direction == DIR_REVC) {
11665 				un->un_running.fileno--;
11666 				un->un_running.blkno = LASTBLK;
11667 			}
11668 		}
11669 	}
11670 }
11671 
11672 static void
11673 st_set_state(struct scsi_tape *un, struct buf *bp)
11674 {
11675 	struct scsi_pkt *sp = BP_PKT(bp);
11676 	struct uscsi_cmd *ucmd;
11677 
11678 	ST_FUNC(ST_DEVINFO, st_set_state);
11679 
11680 	ASSERT(mutex_owned(ST_MUTEX));
11681 	ASSERT(bp != un->un_recov_buf);
11682 
11683 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11684 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
11685 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
11686 
11687 	if (bp != un->un_sbufp) {
11688 #ifdef STDEBUG
11689 		if (DEBUGGING && sp->pkt_resid) {
11690 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11691 			    "pkt_resid %ld bcount %ld\n",
11692 			    sp->pkt_resid, bp->b_bcount);
11693 		}
11694 #endif
11695 		bp->b_resid = sp->pkt_resid;
11696 		if (geterror(bp) != EIO) {
11697 			st_calc_bnum(un, bp, sp);
11698 		}
11699 		if (bp->b_flags & B_READ) {
11700 			un->un_lastop = ST_OP_READ;
11701 			un->un_fmneeded = 0;
11702 		} else {
11703 			un->un_lastop = ST_OP_WRITE;
11704 			if (un->un_dp->options & ST_REEL) {
11705 				un->un_fmneeded = 2;
11706 			} else {
11707 				un->un_fmneeded = 1;
11708 			}
11709 		}
11710 		/*
11711 		 * all is honky dory at this point, so let's
11712 		 * readjust the throttle, to increase speed, if we
11713 		 * have not throttled down.
11714 		 */
11715 		if (un->un_throttle) {
11716 			un->un_throttle = un->un_max_throttle;
11717 		}
11718 	} else {
11719 		optype new_lastop = ST_OP_NIL;
11720 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
11721 
11722 		switch (cmd) {
11723 		case SCMD_WRITE:
11724 		case SCMD_WRITE_G4:
11725 			bp->b_resid = sp->pkt_resid;
11726 			new_lastop = ST_OP_WRITE;
11727 			if (geterror(bp) == EIO) {
11728 				break;
11729 			}
11730 			st_calc_bnum(un, bp, sp);
11731 			if (un->un_dp->options & ST_REEL) {
11732 				un->un_fmneeded = 2;
11733 			} else {
11734 				un->un_fmneeded = 1;
11735 			}
11736 			break;
11737 		case SCMD_READ:
11738 		case SCMD_READ_G4:
11739 			bp->b_resid = sp->pkt_resid;
11740 			new_lastop = ST_OP_READ;
11741 			if (geterror(bp) == EIO) {
11742 				break;
11743 			}
11744 			st_calc_bnum(un, bp, sp);
11745 			un->un_fmneeded = 0;
11746 			break;
11747 		case SCMD_WRITE_FILE_MARK_G4:
11748 		case SCMD_WRITE_FILE_MARK:
11749 		{
11750 			int fmdone;
11751 
11752 			if (un->un_pos.eof != ST_EOM) {
11753 				un->un_pos.eof = ST_NO_EOF;
11754 			}
11755 			fmdone = (bp->b_bcount - bp->b_resid);
11756 			if (fmdone > 0) {
11757 				un->un_lastop = new_lastop = ST_OP_WEOF;
11758 				un->un_pos.lgclblkno += fmdone;
11759 				un->un_pos.fileno += fmdone;
11760 				un->un_pos.blkno = 0;
11761 			} else {
11762 				new_lastop = ST_OP_CTL;
11763 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11764 				    "Flushed buffer\n");
11765 			}
11766 			if (fmdone > un->un_fmneeded) {
11767 				un->un_fmneeded = 0;
11768 			} else {
11769 				un->un_fmneeded -= fmdone;
11770 			}
11771 			break;
11772 		}
11773 		case SCMD_REWIND:
11774 			un->un_pos.eof = ST_NO_EOF;
11775 			un->un_pos.fileno = 0;
11776 			un->un_pos.blkno = 0;
11777 			un->un_pos.lgclblkno = 0;
11778 			if (un->un_pos.pmode != legacy)
11779 				un->un_pos.pmode = legacy;
11780 			new_lastop = ST_OP_CTL;
11781 			un->un_restore_pos = 0;
11782 			break;
11783 
11784 		case SCMD_SPACE:
11785 		case SCMD_SPACE_G4:
11786 		{
11787 			int64_t count;
11788 			int64_t resid;
11789 			int64_t done;
11790 			cmd_attribute const *attrib;
11791 			recov_info *ri = sp->pkt_private;
11792 
11793 			if (ri->privatelen == sizeof (recov_info)) {
11794 				attrib = ri->cmd_attrib;
11795 			} else {
11796 				attrib =
11797 				    st_lookup_cmd_attribute(sp->pkt_cdbp[0]);
11798 			}
11799 
11800 			resid = (int64_t)SPACE_CNT(bp->b_resid);
11801 			count = (int64_t)attrib->get_cnt(sp->pkt_cdbp);
11802 
11803 			if (count >= 0) {
11804 				done = (count - resid);
11805 			} else {
11806 				done = ((-count) - resid);
11807 			}
11808 			if (done > 0) {
11809 				un->un_lastop = new_lastop = ST_OP_CTL;
11810 			} else {
11811 				new_lastop = ST_OP_CTL;
11812 			}
11813 
11814 			ST_SPAC(ST_DEVINFO, st_label, CE_WARN,
11815 			    "space cmd: cdb[1] = %s\n"
11816 			    "space data:       = 0x%lx\n"
11817 			    "space count:      = %"PRId64"\n"
11818 			    "space resid:      = %"PRId64"\n"
11819 			    "spaces done:      = %"PRId64"\n"
11820 			    "fileno before     = %d\n"
11821 			    "blkno before      = %d\n",
11822 			    space_strs[sp->pkt_cdbp[1] & 7],
11823 			    bp->b_bcount,
11824 			    count, resid, done,
11825 			    un->un_pos.fileno, un->un_pos.blkno);
11826 
11827 			switch (sp->pkt_cdbp[1]) {
11828 			case SPACE_TYPE(SP_FLM):
11829 				/* Space file forward */
11830 				if (count >= 0) {
11831 					if (un->un_pos.eof <= ST_EOF) {
11832 						un->un_pos.eof = ST_NO_EOF;
11833 					}
11834 					un->un_pos.fileno += done;
11835 					un->un_pos.blkno = 0;
11836 					break;
11837 				}
11838 				/* Space file backward */
11839 				if (done > un->un_pos.fileno) {
11840 					un->un_pos.fileno = 0;
11841 					un->un_pos.blkno = 0;
11842 				} else {
11843 					un->un_pos.fileno -= done;
11844 					un->un_pos.blkno = LASTBLK;
11845 					un->un_running.pmode = invalid;
11846 				}
11847 				break;
11848 			case SPACE_TYPE(SP_BLK):
11849 				/* Space block forward */
11850 				if (count >= 0) {
11851 					un->un_pos.blkno += done;
11852 					break;
11853 				}
11854 				/* Space block backward */
11855 				if (un->un_pos.eof >= ST_EOF_PENDING) {
11856 				/*
11857 				 * we stepped back into
11858 				 * a previous file; we are not
11859 				 * making an effort to pretend that
11860 				 * we are still in the current file
11861 				 * ie. logical == physical position
11862 				 * and leave it to st_ioctl to correct
11863 				 */
11864 					if (done > un->un_pos.blkno) {
11865 						un->un_pos.blkno = 0;
11866 					} else {
11867 						un->un_pos.fileno--;
11868 						un->un_pos.blkno = LASTBLK;
11869 						un->un_running.pmode = invalid;
11870 					}
11871 				} else {
11872 					un->un_pos.blkno -= done;
11873 				}
11874 				break;
11875 			case SPACE_TYPE(SP_SQFLM):
11876 				un->un_pos.pmode = logical;
11877 				un->un_pos.blkno = 0;
11878 				un->un_lastop = new_lastop = ST_OP_CTL;
11879 				break;
11880 			case SPACE_TYPE(SP_EOD):
11881 				un->un_pos.pmode = logical;
11882 				un->un_pos.eof = ST_EOM;
11883 				un->un_status = KEY_BLANK_CHECK;
11884 				break;
11885 			default:
11886 				un->un_pos.pmode = invalid;
11887 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11888 				    "Unsupported space cmd: %s\n",
11889 				    space_strs[sp->pkt_cdbp[1] & 7]);
11890 
11891 				un->un_lastop = new_lastop = ST_OP_CTL;
11892 			}
11893 
11894 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11895 			    "after_space rs %"PRId64" fil %d blk %d\n",
11896 			    resid, un->un_pos.fileno, un->un_pos.blkno);
11897 
11898 			break;
11899 		}
11900 		case SCMD_LOAD:
11901 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
11902 				un->un_pos.fileno = 0;
11903 				if (un->un_pos.pmode != legacy)
11904 					un->un_pos.pmode = legacy;
11905 			} else {
11906 				un->un_state = ST_STATE_OFFLINE;
11907 				un->un_pos.pmode = invalid;
11908 
11909 			}
11910 			/*
11911 			 * If we are loading or unloading we expect the media id
11912 			 * to change. Lets make it unknown.
11913 			 */
11914 			if (un->un_media_id != bogusID && un->un_media_id_len) {
11915 				kmem_free(un->un_media_id, un->un_media_id_len);
11916 				un->un_media_id = NULL;
11917 				un->un_media_id_len = 0;
11918 			}
11919 			un->un_density_known = 0;
11920 			un->un_pos.eof = ST_NO_EOF;
11921 			un->un_pos.blkno = 0;
11922 			un->un_lastop = new_lastop = ST_OP_CTL;
11923 			break;
11924 		case SCMD_ERASE:
11925 			un->un_pos.eof = ST_NO_EOF;
11926 			un->un_pos.blkno = 0;
11927 			un->un_pos.fileno = 0;
11928 			un->un_pos.lgclblkno = 0;
11929 			if (un->un_pos.pmode != legacy)
11930 				un->un_pos.pmode = legacy;
11931 			new_lastop = ST_OP_CTL;
11932 			break;
11933 		case SCMD_RESERVE:
11934 			un->un_rsvd_status |= ST_RESERVE;
11935 			un->un_rsvd_status &=
11936 			    ~(ST_RELEASE | ST_LOST_RESERVE |
11937 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11938 			new_lastop = ST_OP_CTL;
11939 			break;
11940 		case SCMD_RELEASE:
11941 			un->un_rsvd_status |= ST_RELEASE;
11942 			un->un_rsvd_status &=
11943 			    ~(ST_RESERVE | ST_LOST_RESERVE |
11944 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11945 			new_lastop = ST_OP_CTL;
11946 			break;
11947 		case SCMD_PERSISTENT_RESERVE_IN:
11948 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11949 			    "PGR_IN command\n");
11950 			new_lastop = ST_OP_CTL;
11951 			break;
11952 		case SCMD_PERSISTENT_RESERVE_OUT:
11953 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
11954 			case ST_SA_SCSI3_RESERVE:
11955 			case ST_SA_SCSI3_PREEMPT:
11956 			case ST_SA_SCSI3_PREEMPTANDABORT:
11957 				un->un_rsvd_status |=
11958 				    (ST_APPLICATION_RESERVATIONS | ST_RESERVE);
11959 				un->un_rsvd_status &= ~(ST_RELEASE |
11960 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11961 				    ST_INITIATED_RESET);
11962 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11963 				    "PGR Reserve and set: entering"
11964 				    " ST_APPLICATION_RESERVATIONS mode");
11965 				break;
11966 			case ST_SA_SCSI3_REGISTER:
11967 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11968 				    "PGR Reserve register key");
11969 				un->un_rsvd_status |= ST_INIT_RESERVE;
11970 				break;
11971 			case ST_SA_SCSI3_CLEAR:
11972 				un->un_rsvd_status &= ~ST_INIT_RESERVE;
11973 				/* FALLTHROUGH */
11974 			case ST_SA_SCSI3_RELEASE:
11975 				un->un_rsvd_status &=
11976 				    ~(ST_APPLICATION_RESERVATIONS | ST_RESERVE |
11977 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11978 				    ST_INITIATED_RESET);
11979 				un->un_rsvd_status |= ST_RELEASE;
11980 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11981 				    "PGR Release and reset: exiting"
11982 				    " ST_APPLICATION_RESERVATIONS mode");
11983 				break;
11984 			}
11985 			new_lastop = ST_OP_CTL;
11986 			break;
11987 		case SCMD_TEST_UNIT_READY:
11988 		case SCMD_READ_BLKLIM:
11989 		case SCMD_REQUEST_SENSE:
11990 		case SCMD_INQUIRY:
11991 		case SCMD_RECOVER_BUF:
11992 		case SCMD_MODE_SELECT:
11993 		case SCMD_MODE_SENSE:
11994 		case SCMD_DOORLOCK:
11995 		case SCMD_READ_BUFFER:
11996 		case SCMD_REPORT_DENSITIES:
11997 		case SCMD_LOG_SELECT_G1:
11998 		case SCMD_LOG_SENSE_G1:
11999 		case SCMD_REPORT_LUNS:
12000 		case SCMD_READ_ATTRIBUTE:
12001 		case SCMD_WRITE_ATTRIBUTE:
12002 		case SCMD_SVC_ACTION_IN_G5:
12003 			new_lastop = ST_OP_CTL;
12004 			break;
12005 		case SCMD_READ_POSITION:
12006 			new_lastop = ST_OP_CTL;
12007 			/*
12008 			 * Only if the buf used was un_sbufp.
12009 			 * Among other things the prevents read positions used
12010 			 * as part of error recovery from messing up our
12011 			 * current position as they will use un_recov_buf.
12012 			 */
12013 			if (USCSI_CMD(bp)) {
12014 				(void) st_get_read_pos(un, bp);
12015 			}
12016 			break;
12017 		case SCMD_LOCATE:
12018 		case SCMD_LOCATE_G4:
12019 			/* Locate makes position mode no longer legacy */
12020 			un->un_lastop = new_lastop = ST_OP_CTL;
12021 			break;
12022 		case SCMD_MAINTENANCE_IN:
12023 			switch (sp->pkt_cdbp[1]) {
12024 			case SSVC_ACTION_GET_SUPPORTED_OPERATIONS:
12025 			case SSVC_ACTION_SET_TARGET_PORT_GROUPS:
12026 				new_lastop = ST_OP_CTL;
12027 				break;
12028 			}
12029 			if (new_lastop != ST_OP_NIL) {
12030 				break;
12031 			}
12032 		default:
12033 			/*
12034 			 * Unknown command, If was USCSI and USCSI_SILENT
12035 			 * flag was not set, set position to unknown.
12036 			 */
12037 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
12038 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
12039 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
12040 				    "unknown cmd 0x%X caused loss of state\n",
12041 				    cmd);
12042 			} else {
12043 				/*
12044 				 * keep the old agreement to allow unknown
12045 				 * commands with the USCSI_SILENT set.
12046 				 * This prevents ASSERT below.
12047 				 */
12048 				new_lastop = ST_OP_CTL;
12049 				break;
12050 			}
12051 			/* FALLTHROUGH */
12052 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
12053 			un->un_pos.pmode = invalid;
12054 			un->un_lastop = new_lastop = ST_OP_CTL;
12055 			break;
12056 		}
12057 
12058 		/* new_lastop should have been changed */
12059 		ASSERT(new_lastop != ST_OP_NIL);
12060 
12061 		/* If un_lastop should copy new_lastop  */
12062 		if (((un->un_lastop == ST_OP_WRITE) ||
12063 		    (un->un_lastop == ST_OP_WEOF)) &&
12064 		    new_lastop != ST_OP_CTL) {
12065 			un->un_lastop = new_lastop;
12066 		}
12067 	}
12068 
12069 	/*
12070 	 * In the st driver we have a logical and physical file position.
12071 	 * Under BSD behavior, when you get a zero read, the logical position
12072 	 * is before the filemark but after the last record of the file.
12073 	 * The physical position is after the filemark. MTIOCGET should always
12074 	 * return the logical file position.
12075 	 *
12076 	 * The next read gives a silent skip to the next file.
12077 	 * Under SVR4, the logical file position remains before the filemark
12078 	 * until the file is closed or a space operation is performed.
12079 	 * Hence set err_resid and err_file before changing fileno if case
12080 	 * BSD Behaviour.
12081 	 */
12082 	un->un_err_resid = bp->b_resid;
12083 	COPY_POS(&un->un_err_pos, &un->un_pos);
12084 
12085 
12086 	/*
12087 	 * If we've seen a filemark via the last read operation
12088 	 * advance the file counter, but mark things such that
12089 	 * the next read operation gets a zero count. We have
12090 	 * to put this here to handle the case of sitting right
12091 	 * at the end of a tape file having seen the file mark,
12092 	 * but the tape is closed and then re-opened without
12093 	 * any further i/o. That is, the position information
12094 	 * must be updated before a close.
12095 	 */
12096 
12097 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
12098 		/*
12099 		 * If we're a 1/2" tape, and we get a filemark
12100 		 * right on block 0, *AND* we were not in the
12101 		 * first file on the tape, and we've hit logical EOM.
12102 		 * We'll mark the state so that later we do the
12103 		 * right thing (in st_close(), st_strategy() or
12104 		 * st_ioctl()).
12105 		 *
12106 		 */
12107 		if ((un->un_dp->options & ST_REEL) &&
12108 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
12109 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
12110 			un->un_pos.eof = ST_EOT_PENDING;
12111 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12112 			    "eot pending\n");
12113 			un->un_pos.fileno++;
12114 			un->un_pos.blkno = 0;
12115 		} else if (BSD_BEHAVIOR) {
12116 			/*
12117 			 * If the read of the filemark was a side effect
12118 			 * of reading some blocks (i.e., data was actually
12119 			 * read), then the EOF mark is pending and the
12120 			 * bump into the next file awaits the next read
12121 			 * operation (which will return a zero count), or
12122 			 * a close or a space operation, else the bump
12123 			 * into the next file occurs now.
12124 			 */
12125 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12126 			    "resid=%lx, bcount=%lx\n",
12127 			    bp->b_resid, bp->b_bcount);
12128 
12129 			if (bp->b_resid != bp->b_bcount) {
12130 				un->un_pos.eof = ST_EOF;
12131 			} else {
12132 				un->un_silent_skip = 1;
12133 				un->un_pos.eof = ST_NO_EOF;
12134 				un->un_pos.fileno++;
12135 				un->un_pos.lgclblkno++;
12136 				un->un_save_blkno = un->un_pos.blkno;
12137 				un->un_pos.blkno = 0;
12138 			}
12139 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12140 			    "eof of file %d, eof=%d\n",
12141 			    un->un_pos.fileno, un->un_pos.eof);
12142 		} else if (SVR4_BEHAVIOR) {
12143 			/*
12144 			 * If the read of the filemark was a side effect
12145 			 * of reading some blocks (i.e., data was actually
12146 			 * read), then the next read should return 0
12147 			 */
12148 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12149 			    "resid=%lx, bcount=%lx\n",
12150 			    bp->b_resid, bp->b_bcount);
12151 			if (bp->b_resid == bp->b_bcount) {
12152 				un->un_pos.eof = ST_EOF;
12153 			}
12154 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12155 			    "eof of file=%d, eof=%d\n",
12156 			    un->un_pos.fileno, un->un_pos.eof);
12157 		}
12158 	}
12159 }
12160 
12161 /*
12162  * set the correct un_errno, to take corner cases into consideration
12163  */
12164 static void
12165 st_set_pe_errno(struct scsi_tape *un)
12166 {
12167 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
12168 
12169 	ASSERT(mutex_owned(ST_MUTEX));
12170 
12171 	/* if errno is already set, don't reset it */
12172 	if (un->un_errno)
12173 		return;
12174 
12175 	/* here un_errno == 0 */
12176 	/*
12177 	 * if the last transfer before flushing all the
12178 	 * waiting I/O's, was 0 (resid = count), then we
12179 	 * want to give the user an error on all the rest,
12180 	 * so here.  If there was a transfer, we set the
12181 	 * resid and counts to 0, and let it drop through,
12182 	 * giving a zero return.  the next I/O will then
12183 	 * give an error.
12184 	 */
12185 	if (un->un_last_resid == un->un_last_count) {
12186 		switch (un->un_pos.eof) {
12187 		case ST_EOM:
12188 			un->un_errno = ENOMEM;
12189 			break;
12190 		case ST_EOT:
12191 		case ST_EOF:
12192 			un->un_errno = EIO;
12193 			break;
12194 		}
12195 	} else {
12196 		/*
12197 		 * we know they did not have a zero, so make
12198 		 * sure they get one
12199 		 */
12200 		un->un_last_resid = un->un_last_count = 0;
12201 	}
12202 }
12203 
12204 
12205 /*
12206  * send in a marker pkt to terminate flushing of commands by BBA (via
12207  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
12208  */
12209 static void
12210 st_hba_unflush(struct scsi_tape *un)
12211 {
12212 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
12213 
12214 	ASSERT(mutex_owned(ST_MUTEX));
12215 
12216 	if (!un->un_flush_on_errors)
12217 		return;
12218 
12219 #ifdef FLUSH_ON_ERRORS
12220 
12221 	if (!un->un_mkr_pkt) {
12222 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
12223 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
12224 
12225 		/* we slept, so it must be there */
12226 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
12227 	}
12228 
12229 	st_transport(un, un->un_mkr_pkt);
12230 #endif
12231 }
12232 
12233 static char *
12234 st_print_scsi_cmd(char cmd)
12235 {
12236 	char tmp[64];
12237 	char *cpnt;
12238 
12239 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
12240 	/* tmp goes out of scope on return and caller sees garbage */
12241 	if (cpnt == tmp) {
12242 		cpnt = "Unknown Command";
12243 	}
12244 	return (cpnt);
12245 }
12246 
12247 static void
12248 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
12249     char *title, char *cdb)
12250 {
12251 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
12252 	char buf[256];
12253 	struct scsi_tape *un;
12254 	int instance = ddi_get_instance(dip);
12255 
12256 	un = ddi_get_soft_state(st_state, instance);
12257 
12258 	ST_FUNC(dip, st_print_cdb);
12259 
12260 	/* force one line output so repeated commands are printed once */
12261 	if ((st_debug & 0x180) == 0x100) {
12262 		scsi_log(dip, label, level, "node %s cmd %s\n",
12263 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
12264 		return;
12265 	}
12266 
12267 	/* force one line output so repeated CDB's are printed once */
12268 	if ((st_debug & 0x180) == 0x80) {
12269 		st_clean_print(dip, label, level, NULL, cdb, len);
12270 	} else {
12271 		(void) sprintf(buf, "%s for cmd(%s)", title,
12272 		    st_print_scsi_cmd(*cdb));
12273 		st_clean_print(dip, label, level, buf, cdb, len);
12274 	}
12275 }
12276 
12277 static void
12278 st_clean_print(dev_info_t *dev, char *label, uint_t level,
12279     char *title, char *data, int len)
12280 {
12281 	int	i;
12282 	int 	c;
12283 	char	*format;
12284 	char	buf[256];
12285 	uchar_t	byte;
12286 
12287 	ST_FUNC(dev, st_clean_print);
12288 
12289 
12290 	if (title) {
12291 		(void) sprintf(buf, "%s:\n", title);
12292 		scsi_log(dev, label, level, "%s", buf);
12293 		level = CE_CONT;
12294 	}
12295 
12296 	for (i = 0; i < len; ) {
12297 		buf[0] = 0;
12298 		for (c = 0; c < 8 && i < len; c++, i++) {
12299 			byte = (uchar_t)data[i];
12300 			if (byte < 0x10)
12301 				format = "0x0%x ";
12302 			else
12303 				format = "0x%x ";
12304 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
12305 		}
12306 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
12307 
12308 		scsi_log(dev, label, level, "%s\n", buf);
12309 		level = CE_CONT;
12310 	}
12311 }
12312 
12313 /*
12314  * Conditionally enabled debugging
12315  */
12316 #ifdef	STDEBUG
12317 static void
12318 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
12319 {
12320 	char tmpbuf[64];
12321 
12322 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
12323 
12324 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12325 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
12326 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
12327 	    count, count,
12328 	    wait == ASYNC_CMD ? "a" : "");
12329 }
12330 #endif	/* STDEBUG */
12331 
12332 /*
12333  * Returns pointer to name of minor node name of device 'dev'.
12334  */
12335 static char *
12336 st_dev_name(dev_t dev)
12337 {
12338 	struct scsi_tape *un;
12339 	const char density[] = { 'l', 'm', 'h', 'c' };
12340 	static char name[32];
12341 	minor_t minor;
12342 	int instance;
12343 	int nprt = 0;
12344 
12345 	minor = getminor(dev);
12346 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
12347 	un = ddi_get_soft_state(st_state, instance);
12348 	if (un) {
12349 		ST_FUNC(ST_DEVINFO, st_dev_name);
12350 	}
12351 
12352 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
12353 
12354 	if (minor & MT_BSD) {
12355 		name[++nprt] = 'b';
12356 	}
12357 
12358 	if (minor & MT_NOREWIND) {
12359 		name[++nprt] = 'n';
12360 	}
12361 
12362 	/* NULL terminator */
12363 	name[++nprt] = 0;
12364 
12365 	return (name);
12366 }
12367 
12368 /*
12369  * Soft error reporting, so far unique to each drive
12370  *
12371  * Currently supported: exabyte and DAT soft error reporting
12372  */
12373 static int
12374 st_report_exabyte_soft_errors(dev_t dev, int flag)
12375 {
12376 	uchar_t *sensep;
12377 	int amt;
12378 	int rval = 0;
12379 	char cdb[CDB_GROUP0], *c = cdb;
12380 	struct uscsi_cmd *com;
12381 
12382 	GET_SOFT_STATE(dev);
12383 
12384 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
12385 
12386 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12387 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
12388 	    dev, flag);
12389 
12390 	ASSERT(mutex_owned(ST_MUTEX));
12391 
12392 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12393 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
12394 
12395 	*c++ = SCMD_REQUEST_SENSE;
12396 	*c++ = 0;
12397 	*c++ = 0;
12398 	*c++ = 0;
12399 	*c++ = TAPE_SENSE_LENGTH;
12400 	/*
12401 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
12402 	 */
12403 	*c   = (char)0x80;
12404 
12405 	com->uscsi_cdb = cdb;
12406 	com->uscsi_cdblen = CDB_GROUP0;
12407 	com->uscsi_bufaddr = (caddr_t)sensep;
12408 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
12409 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12410 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12411 
12412 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12413 	if (rval || com->uscsi_status) {
12414 		goto done;
12415 	}
12416 
12417 	/*
12418 	 * was there enough data?
12419 	 */
12420 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
12421 
12422 	if ((amt >= 19) && un->un_kbytes_xferred) {
12423 		uint_t count, error_rate;
12424 		uint_t rate;
12425 
12426 		if (sensep[21] & CLN) {
12427 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12428 			    "Periodic head cleaning required");
12429 		}
12430 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
12431 			goto done;
12432 		}
12433 		/*
12434 		 * check if soft error reporting needs to be done.
12435 		 */
12436 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
12437 		count &= 0xffffff;
12438 		error_rate = (count * 100)/un->un_kbytes_xferred;
12439 
12440 #ifdef	STDEBUG
12441 		if (st_soft_error_report_debug) {
12442 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12443 			    "Exabyte Soft Error Report:\n");
12444 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12445 			    "read/write error counter: %d\n", count);
12446 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12447 			    "number of bytes transferred: %dK\n",
12448 			    un->un_kbytes_xferred);
12449 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12450 			    "error_rate: %d%%\n", error_rate);
12451 
12452 			if (amt >= 22) {
12453 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12454 				    "unit sense: 0x%b 0x%b 0x%b\n",
12455 				    sensep[19], SENSE_19_BITS,
12456 				    sensep[20], SENSE_20_BITS,
12457 				    sensep[21], SENSE_21_BITS);
12458 			}
12459 			if (amt >= 27) {
12460 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12461 				    "tracking retry counter: %d\n",
12462 				    sensep[26]);
12463 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12464 				    "read/write retry counter: %d\n",
12465 				    sensep[27]);
12466 			}
12467 		}
12468 #endif
12469 
12470 		if (flag & FWRITE) {
12471 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
12472 		} else {
12473 			rate = EXABYTE_READ_ERROR_THRESHOLD;
12474 		}
12475 		if (error_rate >= rate) {
12476 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12477 			    "Soft error rate (%d%%) during %s was too high",
12478 			    error_rate,
12479 			    ((flag & FWRITE) ? wrg_str : rdg_str));
12480 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12481 			    "Please, replace tape cartridge\n");
12482 		}
12483 	}
12484 
12485 done:
12486 	kmem_free(com, sizeof (*com));
12487 	kmem_free(sensep, TAPE_SENSE_LENGTH);
12488 
12489 	if (rval != 0) {
12490 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12491 		    "exabyte soft error reporting failed\n");
12492 	}
12493 	return (rval);
12494 }
12495 
12496 /*
12497  * this is very specific to Archive 4mm dat
12498  */
12499 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
12500 
12501 static int
12502 st_report_dat_soft_errors(dev_t dev, int flag)
12503 {
12504 	uchar_t *sensep;
12505 	int amt, i;
12506 	int rval = 0;
12507 	char cdb[CDB_GROUP1], *c = cdb;
12508 	struct uscsi_cmd *com;
12509 	struct scsi_arq_status status;
12510 
12511 	GET_SOFT_STATE(dev);
12512 
12513 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
12514 
12515 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12516 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12517 
12518 	ASSERT(mutex_owned(ST_MUTEX));
12519 
12520 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12521 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12522 
12523 	*c++ = SCMD_LOG_SENSE_G1;
12524 	*c++ = 0;
12525 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
12526 	*c++ = 0;
12527 	*c++ = 0;
12528 	*c++ = 0;
12529 	*c++ = 2;
12530 	*c++ = 0;
12531 	*c++ = (char)LOG_SENSE_LENGTH;
12532 	*c   = 0;
12533 	com->uscsi_cdb    = cdb;
12534 	com->uscsi_cdblen  = CDB_GROUP1;
12535 	com->uscsi_bufaddr = (caddr_t)sensep;
12536 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
12537 	com->uscsi_rqlen = sizeof (status);
12538 	com->uscsi_rqbuf = (caddr_t)&status;
12539 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
12540 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12541 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12542 	if (rval) {
12543 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12544 		    "DAT soft error reporting failed\n");
12545 	}
12546 	if (rval || com->uscsi_status) {
12547 		goto done;
12548 	}
12549 
12550 	/*
12551 	 * was there enough data?
12552 	 */
12553 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
12554 
12555 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
12556 		int total, retries, param_code;
12557 
12558 		total = -1;
12559 		retries = -1;
12560 		amt = sensep[3] + 4;
12561 
12562 
12563 #ifdef STDEBUG
12564 		if (st_soft_error_report_debug) {
12565 			(void) printf("logsense:");
12566 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
12567 				if (i % 16 == 0) {
12568 					(void) printf("\t\n");
12569 				}
12570 				(void) printf(" %x", sensep[i]);
12571 			}
12572 			(void) printf("\n");
12573 		}
12574 #endif
12575 
12576 		/*
12577 		 * parse the param_codes
12578 		 */
12579 		if (sensep[0] == 2 || sensep[0] == 3) {
12580 			for (i = 4; i < amt; i++) {
12581 				param_code = (sensep[i++] << 8);
12582 				param_code += sensep[i++];
12583 				i++; /* skip control byte */
12584 				if (param_code == 5) {
12585 					if (sensep[i++] == 4) {
12586 						total = (sensep[i++] << 24);
12587 						total += (sensep[i++] << 16);
12588 						total += (sensep[i++] << 8);
12589 						total += sensep[i];
12590 					}
12591 				} else if (param_code == 0x8007) {
12592 					if (sensep[i++] == 2) {
12593 						retries = sensep[i++] << 8;
12594 						retries += sensep[i];
12595 					}
12596 				} else {
12597 					i += sensep[i];
12598 				}
12599 			}
12600 		}
12601 
12602 		/*
12603 		 * if the log sense returned valid numbers then determine
12604 		 * the read and write error thresholds based on the amount of
12605 		 * data transferred
12606 		 */
12607 
12608 		if (total > 0 && retries > 0) {
12609 			short normal_retries = 0;
12610 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12611 			    "total xferred (%s) =%x, retries=%x\n",
12612 			    ((flag & FWRITE) ? wrg_str : rdg_str),
12613 			    total, retries);
12614 
12615 			if (flag & FWRITE) {
12616 				if (total <=
12617 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
12618 					normal_retries =
12619 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
12620 				} else {
12621 					normal_retries =
12622 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
12623 				}
12624 			} else {
12625 				if (total <=
12626 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
12627 					normal_retries =
12628 					    DAT_SMALL_READ_ERROR_THRESHOLD;
12629 				} else {
12630 					normal_retries =
12631 					    DAT_LARGE_READ_ERROR_THRESHOLD;
12632 				}
12633 			}
12634 
12635 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12636 			"normal retries=%d\n", normal_retries);
12637 
12638 			if (retries >= normal_retries) {
12639 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12640 				    "Soft error rate (retries = %d) during "
12641 				    "%s was too high",  retries,
12642 				    ((flag & FWRITE) ? wrg_str : rdg_str));
12643 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12644 				    "Periodic head cleaning required "
12645 				    "and/or replace tape cartridge\n");
12646 			}
12647 
12648 		} else if (total == -1 || retries == -1) {
12649 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12650 			    "log sense parameter code does not make sense\n");
12651 		}
12652 	}
12653 
12654 	/*
12655 	 * reset all values
12656 	 */
12657 	c = cdb;
12658 	*c++ = SCMD_LOG_SELECT_G1;
12659 	*c++ = 2;	/* this resets all values */
12660 	*c++ = (char)0xc0;
12661 	*c++ = 0;
12662 	*c++ = 0;
12663 	*c++ = 0;
12664 	*c++ = 0;
12665 	*c++ = 0;
12666 	*c++ = 0;
12667 	*c   = 0;
12668 	com->uscsi_bufaddr = NULL;
12669 	com->uscsi_buflen  = 0;
12670 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
12671 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12672 	if (rval) {
12673 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12674 		    "DAT soft error reset failed\n");
12675 	}
12676 done:
12677 	kmem_free(com, sizeof (*com));
12678 	kmem_free(sensep, LOG_SENSE_LENGTH);
12679 	return (rval);
12680 }
12681 
12682 static int
12683 st_report_soft_errors(dev_t dev, int flag)
12684 {
12685 	GET_SOFT_STATE(dev);
12686 
12687 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
12688 
12689 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12690 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12691 
12692 	ASSERT(mutex_owned(ST_MUTEX));
12693 
12694 	switch (un->un_dp->type) {
12695 	case ST_TYPE_EXB8500:
12696 	case ST_TYPE_EXABYTE:
12697 		return (st_report_exabyte_soft_errors(dev, flag));
12698 		/*NOTREACHED*/
12699 	case ST_TYPE_PYTHON:
12700 		return (st_report_dat_soft_errors(dev, flag));
12701 		/*NOTREACHED*/
12702 	default:
12703 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
12704 		return (-1);
12705 	}
12706 }
12707 
12708 /*
12709  * persistent error routines
12710  */
12711 
12712 /*
12713  * enable persistent errors, and set the throttle appropriately, checking
12714  * for flush-on-errors capability
12715  */
12716 static void
12717 st_turn_pe_on(struct scsi_tape *un)
12718 {
12719 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
12720 
12721 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
12722 	ASSERT(mutex_owned(ST_MUTEX));
12723 
12724 	un->un_persistence = 1;
12725 
12726 	/*
12727 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
12728 	 * enabled.  This will simplify the error handling for request senses
12729 	 */
12730 
12731 	if (un->un_arq_enabled && un->un_untagged_qing) {
12732 		uchar_t f_o_e;
12733 
12734 		mutex_exit(ST_MUTEX);
12735 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
12736 		    1 : 0;
12737 		mutex_enter(ST_MUTEX);
12738 
12739 		un->un_flush_on_errors = f_o_e;
12740 	} else {
12741 		un->un_flush_on_errors = 0;
12742 	}
12743 
12744 	if (un->un_flush_on_errors)
12745 		un->un_max_throttle = (uchar_t)st_max_throttle;
12746 	else
12747 		un->un_max_throttle = 1;
12748 
12749 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
12750 		un->un_max_throttle = 1;
12751 
12752 	/* this will send a marker pkt */
12753 	st_clear_pe(un);
12754 }
12755 
12756 /*
12757  * This turns persistent errors permanently off
12758  */
12759 static void
12760 st_turn_pe_off(struct scsi_tape *un)
12761 {
12762 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
12763 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
12764 	ASSERT(mutex_owned(ST_MUTEX));
12765 
12766 	/* turn it off for good */
12767 	un->un_persistence = 0;
12768 
12769 	/* this will send a marker pkt */
12770 	st_clear_pe(un);
12771 
12772 	/* turn off flush on error capability, if enabled */
12773 	if (un->un_flush_on_errors) {
12774 		mutex_exit(ST_MUTEX);
12775 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
12776 		mutex_enter(ST_MUTEX);
12777 	}
12778 
12779 
12780 	un->un_flush_on_errors = 0;
12781 }
12782 
12783 /*
12784  * This clear persistent errors, allowing more commands through, and also
12785  * sending a marker packet.
12786  */
12787 static void
12788 st_clear_pe(struct scsi_tape *un)
12789 {
12790 	ST_FUNC(ST_DEVINFO, st_clear_pe);
12791 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
12792 	ASSERT(mutex_owned(ST_MUTEX));
12793 
12794 	un->un_persist_errors = 0;
12795 	un->un_throttle = un->un_last_throttle = 1;
12796 	un->un_errno = 0;
12797 	st_hba_unflush(un);
12798 }
12799 
12800 /*
12801  * This will flag persistent errors, shutting everything down, if the
12802  * application had enabled persistent errors via MTIOCPERSISTENT
12803  */
12804 static void
12805 st_set_pe_flag(struct scsi_tape *un)
12806 {
12807 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
12808 	ASSERT(mutex_owned(ST_MUTEX));
12809 
12810 	if (un->un_persistence) {
12811 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
12812 		un->un_persist_errors = 1;
12813 		un->un_throttle = un->un_last_throttle = 0;
12814 		cv_broadcast(&un->un_sbuf_cv);
12815 	}
12816 }
12817 
12818 static int
12819 st_do_reserve(struct scsi_tape *un)
12820 {
12821 	int rval;
12822 	int was_lost = un->un_rsvd_status & ST_LOST_RESERVE;
12823 
12824 	ST_FUNC(ST_DEVINFO, st_do_reserve);
12825 
12826 	/*
12827 	 * Issue a Throw-Away reserve command to clear the
12828 	 * check condition.
12829 	 * If the current behaviour of reserve/release is to
12830 	 * hold reservation across opens , and if a Bus reset
12831 	 * has been issued between opens then this command
12832 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
12833 	 * In this case return an EACCES so that user knows that
12834 	 * reservation has been lost in between opens.
12835 	 * If this error is not returned and we continue with
12836 	 * successful open , then user may think position of the
12837 	 * tape is still the same but inreality we would rewind the
12838 	 * tape and continue from BOT.
12839 	 */
12840 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12841 	if (rval) {
12842 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
12843 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
12844 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
12845 			un->un_errno = EACCES;
12846 			return (EACCES);
12847 		}
12848 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12849 	}
12850 	if (rval == 0) {
12851 		un->un_rsvd_status |= ST_INIT_RESERVE;
12852 	}
12853 	if (was_lost) {
12854 		un->un_running.pmode = invalid;
12855 	}
12856 
12857 	return (rval);
12858 }
12859 
12860 static int
12861 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb)
12862 {
12863 	int rval;
12864 	cmd_attribute const *attrib;
12865 
12866 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
12867 
12868 	/*
12869 	 * If already reserved no need to do it again.
12870 	 * Also if Reserve and Release are disabled Just return.
12871 	 */
12872 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12873 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12874 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12875 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12876 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
12877 		    st_print_scsi_cmd((uchar_t)cdb[0]));
12878 		return (0);
12879 	}
12880 
12881 	/* See if command is on the list */
12882 	attrib = st_lookup_cmd_attribute(cdb[0]);
12883 
12884 	if (attrib == NULL) {
12885 		rval = 1; /* Not found, when in doubt reserve */
12886 	} else if ((attrib->requires_reserve) != 0) {
12887 		rval = 1;
12888 	} else if ((attrib->reserve_byte) != 0) {
12889 		/*
12890 		 * cmd is on list.
12891 		 * if byte is zero always allowed.
12892 		 */
12893 		rval = 1;
12894 	} else if (((cdb[attrib->reserve_byte]) &
12895 	    (attrib->reserve_mask)) != 0) {
12896 		rval = 1;
12897 	} else {
12898 		rval = 0;
12899 	}
12900 
12901 	if (rval) {
12902 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12903 		    "Command %s requires reservation",
12904 		    st_print_scsi_cmd(cdb[0]));
12905 
12906 		rval = st_do_reserve(un);
12907 	}
12908 
12909 	return (rval);
12910 }
12911 
12912 static int
12913 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
12914 {
12915 	int rval;
12916 	cmd_attribute const *attrib;
12917 
12918 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
12919 
12920 	/*
12921 	 * Do not reserve when already reserved, when not supported or when
12922 	 * auto-rewinding on device closure.
12923 	 */
12924 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12925 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12926 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE) ||
12927 	    ((un->un_state == ST_STATE_CLOSING) && (cmd == SCMD_REWIND))) {
12928 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12929 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
12930 		    st_print_scsi_cmd(cmd));
12931 		return (0);
12932 	}
12933 
12934 	/* search for this command on the list */
12935 	attrib = st_lookup_cmd_attribute(cmd);
12936 
12937 	if (attrib == NULL) {
12938 		rval = 1; /* Not found, when in doubt reserve */
12939 	} else if ((attrib->requires_reserve) != 0) {
12940 		rval = 1;
12941 	} else if ((attrib->reserve_byte) != 0) {
12942 		/*
12943 		 * cmd is on list.
12944 		 * if byte is zero always allowed.
12945 		 */
12946 		rval = 1;
12947 	} else if (((attrib->reserve_mask) & cnt) != 0) {
12948 		rval = 1;
12949 	} else {
12950 		rval = 0;
12951 	}
12952 
12953 	if (rval) {
12954 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12955 		    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
12956 
12957 		rval = st_do_reserve(un);
12958 	}
12959 
12960 	return (rval);
12961 }
12962 
12963 static int
12964 st_reserve_release(struct scsi_tape *un, int cmd, ubufunc_t ubf)
12965 {
12966 	struct uscsi_cmd	uscsi_cmd;
12967 	int			rval;
12968 	char			cdb[CDB_GROUP0];
12969 	struct scsi_arq_status	stat;
12970 
12971 
12972 
12973 	ST_FUNC(ST_DEVINFO, st_reserve_release);
12974 
12975 	ASSERT(mutex_owned(ST_MUTEX));
12976 
12977 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12978 	    "st_reserve_release: %s \n",
12979 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
12980 
12981 	bzero(&cdb, CDB_GROUP0);
12982 	if (cmd == ST_RELEASE) {
12983 		cdb[0] = SCMD_RELEASE;
12984 	} else {
12985 		cdb[0] = SCMD_RESERVE;
12986 	}
12987 	bzero(&uscsi_cmd, sizeof (struct uscsi_cmd));
12988 	uscsi_cmd.uscsi_flags = USCSI_WRITE | USCSI_RQENABLE;
12989 	uscsi_cmd.uscsi_cdb = cdb;
12990 	uscsi_cmd.uscsi_cdblen = CDB_GROUP0;
12991 	uscsi_cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
12992 	uscsi_cmd.uscsi_rqbuf = (caddr_t)&stat;
12993 	uscsi_cmd.uscsi_rqlen = sizeof (stat);
12994 
12995 	rval = ubf(un, &uscsi_cmd, FKIOCTL);
12996 
12997 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12998 	    "st_reserve_release: rval(1)=%d\n", rval);
12999 
13000 	if (rval) {
13001 		if (uscsi_cmd.uscsi_status == STATUS_RESERVATION_CONFLICT) {
13002 			rval = EACCES;
13003 		}
13004 		/*
13005 		 * dynamically turn off reserve/release support
13006 		 * in case of drives which do not support
13007 		 * reserve/release command(ATAPI drives).
13008 		 */
13009 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
13010 			if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
13011 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
13012 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13013 				    "Tape unit does not support "
13014 				    "reserve/release \n");
13015 			}
13016 			rval = 0;
13017 		}
13018 	}
13019 	return (rval);
13020 }
13021 
13022 static int
13023 st_take_ownership(struct scsi_tape *un, ubufunc_t ubf)
13024 {
13025 	int rval;
13026 
13027 	ST_FUNC(ST_DEVINFO, st_take_ownership);
13028 
13029 	ASSERT(mutex_owned(ST_MUTEX));
13030 
13031 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13032 	    "st_take_ownership: Entering ...\n");
13033 
13034 
13035 	rval = st_reserve_release(un, ST_RESERVE, ubf);
13036 	/*
13037 	 * XXX -> Should reset be done only if we get EACCES.
13038 	 * .
13039 	 */
13040 	if (rval) {
13041 		if (st_reset(un, RESET_LUN) == 0) {
13042 			return (EIO);
13043 		}
13044 		un->un_rsvd_status &=
13045 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
13046 
13047 		mutex_exit(ST_MUTEX);
13048 		delay(drv_usectohz(ST_RESERVATION_DELAY));
13049 		mutex_enter(ST_MUTEX);
13050 		/*
13051 		 * remove the check condition.
13052 		 */
13053 		(void) st_reserve_release(un, ST_RESERVE, ubf);
13054 		rval = st_reserve_release(un, ST_RESERVE, ubf);
13055 		if (rval != 0) {
13056 			if ((st_reserve_release(un, ST_RESERVE, ubf))
13057 			    != 0) {
13058 				rval = (un->un_rsvd_status &
13059 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
13060 				return (rval);
13061 			}
13062 		}
13063 		/*
13064 		 * Set tape state to ST_STATE_OFFLINE , in case if
13065 		 * the user wants to continue and start using
13066 		 * the tape.
13067 		 */
13068 		un->un_state = ST_STATE_OFFLINE;
13069 		un->un_rsvd_status |= ST_INIT_RESERVE;
13070 	}
13071 	return (rval);
13072 }
13073 
13074 static int
13075 st_create_errstats(struct scsi_tape *un, int instance)
13076 {
13077 	char	kstatname[KSTAT_STRLEN];
13078 
13079 	ST_FUNC(ST_DEVINFO, st_create_errstats);
13080 
13081 	/*
13082 	 * Create device error kstats
13083 	 */
13084 
13085 	if (un->un_errstats == (kstat_t *)0) {
13086 		(void) sprintf(kstatname, "st%d,err", instance);
13087 		un->un_errstats = kstat_create("sterr", instance, kstatname,
13088 		    "device_error", KSTAT_TYPE_NAMED,
13089 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
13090 		    KSTAT_FLAG_PERSISTENT);
13091 
13092 		if (un->un_errstats) {
13093 			struct st_errstats	*stp;
13094 
13095 			stp = (struct st_errstats *)un->un_errstats->ks_data;
13096 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
13097 			    KSTAT_DATA_ULONG);
13098 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
13099 			    KSTAT_DATA_ULONG);
13100 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
13101 			    KSTAT_DATA_ULONG);
13102 			kstat_named_init(&stp->st_vid, "Vendor",
13103 			    KSTAT_DATA_CHAR);
13104 			kstat_named_init(&stp->st_pid, "Product",
13105 			    KSTAT_DATA_CHAR);
13106 			kstat_named_init(&stp->st_revision, "Revision",
13107 			    KSTAT_DATA_CHAR);
13108 			kstat_named_init(&stp->st_serial, "Serial No",
13109 			    KSTAT_DATA_CHAR);
13110 			un->un_errstats->ks_private = un;
13111 			un->un_errstats->ks_update = nulldev;
13112 			kstat_install(un->un_errstats);
13113 			/*
13114 			 * Fill in the static data
13115 			 */
13116 			(void) strncpy(&stp->st_vid.value.c[0],
13117 			    ST_INQUIRY->inq_vid, 8);
13118 			/*
13119 			 * XXX:  Emulex MT-02 (and emulators) predates
13120 			 *	 SCSI-1 and has no vid & pid inquiry data.
13121 			 */
13122 			if (ST_INQUIRY->inq_len != 0) {
13123 				(void) strncpy(&stp->st_pid.value.c[0],
13124 				    ST_INQUIRY->inq_pid, 16);
13125 				(void) strncpy(&stp->st_revision.value.c[0],
13126 				    ST_INQUIRY->inq_revision, 4);
13127 			}
13128 		}
13129 	}
13130 	return (0);
13131 }
13132 
13133 static int
13134 st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos)
13135 {
13136 	int rval;
13137 	bufunc_t bf = (ubf == st_uscsi_rcmd) ? st_rcmd : st_cmd;
13138 
13139 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
13140 
13141 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
13142 	ASSERT(mutex_owned(ST_MUTEX));
13143 
13144 	/* Can't restore an invalid position */
13145 	if (pos->pmode == invalid) {
13146 		return (4);
13147 	}
13148 
13149 	/*
13150 	 * Assumtions:
13151 	 *	If a position was read and is in logical position mode.
13152 	 *	If a drive supports read position it supports locate.
13153 	 *	If the read position type is not NO_POS. even though
13154 	 *	   a read position make not have been attemped yet.
13155 	 *
13156 	 *	The drive can locate to the position.
13157 	 */
13158 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
13159 		/*
13160 		 * If position mode is logical or legacy mode try
13161 		 * to locate there as it is faster.
13162 		 * If it fails try the old way.
13163 		 */
13164 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13165 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
13166 		    pos->lgclblkno);
13167 
13168 		if (st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
13169 		    pos->lgclblkno, pos->partition) == 0) {
13170 			/* Assume we are there copy rest of position back */
13171 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
13172 				COPY_POS(&un->un_pos, pos);
13173 			}
13174 			return (0);
13175 		}
13176 
13177 		/*
13178 		 * If logical block locate failed to restore a logical
13179 		 * position, can't recover.
13180 		 */
13181 		if (pos->pmode == logical) {
13182 			return (-1);
13183 		}
13184 	}
13185 
13186 
13187 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13188 	    "Restoring tape position at fileno=%x, blkno=%x....",
13189 	    pos->fileno, pos->blkno);
13190 
13191 	/*
13192 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
13193 	 * so as not to rewind tape on RESETS: Gee, Has life ever
13194 	 * been simple in tape land ?
13195 	 */
13196 	rval = bf(un, SCMD_REWIND, 0, SYNC_CMD);
13197 	if (rval) {
13198 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
13199 		    "Failed to restore the last file and block position: In"
13200 		    " this state, Tape will be loaded at BOT during next open");
13201 		un->un_pos.pmode = invalid;
13202 		return (rval);
13203 	}
13204 
13205 	/* If the position was as the result of back space file */
13206 	if (pos->blkno > (INF / 2)) {
13207 		/* Go one extra file forward */
13208 		pos->fileno++;
13209 		/* Figure how many blocks to back into the previous file */
13210 		pos->blkno = -(INF - pos->blkno);
13211 	}
13212 
13213 	/* Go to requested fileno */
13214 	if (pos->fileno) {
13215 		rval = st_cmd(un, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
13216 		if (rval) {
13217 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13218 			    "Failed to restore the last file position: In this "
13219 			    " state, Tape will be loaded at BOT during next"
13220 			    " open %d", __LINE__);
13221 			un->un_pos.pmode = invalid;
13222 			pos->pmode = invalid;
13223 			return (rval);
13224 		}
13225 	}
13226 
13227 	/*
13228 	 * If backing into a file we already did an extra file forward.
13229 	 * Now we have to back over the filemark to get to the end of
13230 	 * the previous file. The blkno has been ajusted to a negative
13231 	 * value so we will get to the expected location.
13232 	 */
13233 	if (pos->blkno) {
13234 		rval = bf(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
13235 		if (rval) {
13236 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13237 			    "Failed to restore the last file position: In this "
13238 			    " state, Tape will be loaded at BOT during next"
13239 			    " open %d", __LINE__);
13240 			un->un_pos.pmode = invalid;
13241 			pos->pmode = invalid;
13242 			return (rval);
13243 		}
13244 	}
13245 
13246 	/*
13247 	 * The position mode, block and fileno should be correct,
13248 	 * This updates eof and logical position information.
13249 	 */
13250 	un->un_pos.eof = pos->eof;
13251 	un->un_pos.lgclblkno = pos->lgclblkno;
13252 
13253 	return (0);
13254 }
13255 
13256 /*
13257  * check sense key, ASC, ASCQ in order to determine if the tape needs
13258  * to be ejected
13259  */
13260 
13261 static int
13262 st_check_asc_ascq(struct scsi_tape *un)
13263 {
13264 	struct scsi_extended_sense *sensep = ST_RQSENSE;
13265 	struct tape_failure_code   *code;
13266 
13267 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
13268 
13269 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
13270 		if ((code->key  == sensep->es_key) &&
13271 		    (code->add_code  == sensep->es_add_code) &&
13272 		    (code->qual_code == sensep->es_qual_code))
13273 			return (1);
13274 	}
13275 	return (0);
13276 }
13277 
13278 /*
13279  * st_logpage_supported() sends a Log Sense command with
13280  * page code = 0 = Supported Log Pages Page to the device,
13281  * to see whether the page 'page' is supported.
13282  * Return values are:
13283  * -1 if the Log Sense command fails
13284  * 0 if page is not supported
13285  * 1 if page is supported
13286  */
13287 
13288 static int
13289 st_logpage_supported(struct scsi_tape *un, uchar_t page)
13290 {
13291 	uchar_t *sp, *sensep;
13292 	unsigned length;
13293 	struct uscsi_cmd *com;
13294 	struct scsi_arq_status status;
13295 	int rval;
13296 	char cdb[CDB_GROUP1] = {
13297 		SCMD_LOG_SENSE_G1,
13298 		0,
13299 		SUPPORTED_LOG_PAGES_PAGE,
13300 		0,
13301 		0,
13302 		0,
13303 		0,
13304 		0,
13305 		(char)LOG_SENSE_LENGTH,
13306 		0
13307 	};
13308 
13309 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
13310 
13311 	ASSERT(mutex_owned(ST_MUTEX));
13312 
13313 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13314 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
13315 
13316 	com->uscsi_cdb = cdb;
13317 	com->uscsi_cdblen = CDB_GROUP1;
13318 	com->uscsi_bufaddr = (caddr_t)sensep;
13319 	com->uscsi_buflen = LOG_SENSE_LENGTH;
13320 	com->uscsi_rqlen = sizeof (status);
13321 	com->uscsi_rqbuf = (caddr_t)&status;
13322 	com->uscsi_flags =
13323 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13324 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13325 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13326 	if (rval || com->uscsi_status) {
13327 		/* uscsi-command failed */
13328 		rval = -1;
13329 	} else {
13330 
13331 		sp = sensep + 3;
13332 
13333 		for (length = *sp++; length > 0; length--, sp++) {
13334 
13335 			if (*sp == page) {
13336 				rval = 1;
13337 				break;
13338 			}
13339 		}
13340 	}
13341 	kmem_free(com, sizeof (struct uscsi_cmd));
13342 	kmem_free(sensep, LOG_SENSE_LENGTH);
13343 	return (rval);
13344 }
13345 
13346 
13347 /*
13348  * st_check_clean_bit() gets the status of the tape's cleaning bit.
13349  *
13350  * If the device does support the TapeAlert log page, then the cleaning bit
13351  * information will be read from this page. Otherwise we will see if one of
13352  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
13353  * the device, which means, that we can get the cleaning bit information via
13354  * a RequestSense command.
13355  * If both methods of getting cleaning bit information are not supported
13356  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
13357  * returns with
13358  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
13359  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
13360  * If the call to st_uscsi_cmd() to do the Log Sense or the Request Sense
13361  * command fails, or if the amount of Request Sense data is not enough, then
13362  *  st_check_clean_bit() returns with -1.
13363  */
13364 
13365 static int
13366 st_check_clean_bit(struct scsi_tape *un)
13367 {
13368 	int rval = 0;
13369 
13370 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
13371 
13372 	ASSERT(mutex_owned(ST_MUTEX));
13373 
13374 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
13375 		return (rval);
13376 	}
13377 
13378 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13379 
13380 		rval = st_logpage_supported(un, TAPE_SEQUENTIAL_PAGE);
13381 		if (rval == -1) {
13382 			return (0);
13383 		}
13384 		if (rval == 1) {
13385 
13386 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
13387 		}
13388 
13389 		rval = st_logpage_supported(un, TAPE_ALERT_PAGE);
13390 		if (rval == -1) {
13391 			return (0);
13392 		}
13393 		if (rval == 1) {
13394 
13395 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
13396 		}
13397 
13398 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13399 
13400 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
13401 		}
13402 	}
13403 
13404 	rval = 0;
13405 
13406 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
13407 
13408 		rval = st_check_sequential_clean_bit(un);
13409 		if (rval == -1) {
13410 			return (0);
13411 		}
13412 	}
13413 
13414 	if ((rval == 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
13415 
13416 		rval = st_check_alert_flags(un);
13417 		if (rval == -1) {
13418 			return (0);
13419 		}
13420 	}
13421 
13422 	if ((rval == 0) && (un->un_dp->options & ST_CLN_MASK)) {
13423 
13424 		rval = st_check_sense_clean_bit(un);
13425 		if (rval == -1) {
13426 			return (0);
13427 		}
13428 	}
13429 
13430 	/*
13431 	 * If found a supported means to check need to clean.
13432 	 */
13433 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
13434 
13435 		/*
13436 		 * head needs to be cleaned.
13437 		 */
13438 		if (rval & MTF_TAPE_HEAD_DIRTY) {
13439 
13440 			/*
13441 			 * Print log message only first time
13442 			 * found needing cleaned.
13443 			 */
13444 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
13445 
13446 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
13447 				    "Periodic head cleaning required");
13448 
13449 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
13450 			}
13451 
13452 		} else {
13453 
13454 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
13455 		}
13456 	}
13457 
13458 	return (rval);
13459 }
13460 
13461 
13462 static int
13463 st_check_sequential_clean_bit(struct scsi_tape *un)
13464 {
13465 	int rval;
13466 	int ix;
13467 	ushort_t parameter;
13468 	struct uscsi_cmd *cmd;
13469 	struct log_sequential_page *sp;
13470 	struct log_sequential_page_parameter *prm;
13471 	struct scsi_arq_status status;
13472 	char cdb[CDB_GROUP1] = {
13473 		SCMD_LOG_SENSE_G1,
13474 		0,
13475 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
13476 		0,
13477 		0,
13478 		0,
13479 		0,
13480 		(char)(sizeof (struct log_sequential_page) >> 8),
13481 		(char)(sizeof (struct log_sequential_page)),
13482 		0
13483 	};
13484 
13485 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
13486 
13487 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13488 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
13489 
13490 	cmd->uscsi_flags   =
13491 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13492 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13493 	cmd->uscsi_cdb	   = cdb;
13494 	cmd->uscsi_cdblen  = CDB_GROUP1;
13495 	cmd->uscsi_bufaddr = (caddr_t)sp;
13496 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
13497 	cmd->uscsi_rqlen   = sizeof (status);
13498 	cmd->uscsi_rqbuf   = (caddr_t)&status;
13499 
13500 	rval = st_uscsi_cmd(un, cmd, FKIOCTL);
13501 
13502 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
13503 
13504 		rval = -1;
13505 
13506 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
13507 
13508 		rval = -1;
13509 	}
13510 
13511 	prm = &sp->param[0];
13512 
13513 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
13514 
13515 		if (prm->log_param.length == 0) {
13516 			break;
13517 		}
13518 
13519 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
13520 		    (prm->log_param.pc_lo & 0xff));
13521 
13522 		if (parameter == SEQUENTIAL_NEED_CLN) {
13523 
13524 			rval = MTF_TAPE_CLN_SUPPORTED;
13525 			if (prm->param_value[prm->log_param.length - 1]) {
13526 
13527 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13528 				    "sequential log says head dirty\n");
13529 				rval |= MTF_TAPE_HEAD_DIRTY;
13530 			}
13531 		}
13532 		prm = (struct log_sequential_page_parameter *)
13533 		    &prm->param_value[prm->log_param.length];
13534 	}
13535 
13536 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13537 	kmem_free(sp,  sizeof (struct log_sequential_page));
13538 
13539 	return (rval);
13540 }
13541 
13542 
13543 static int
13544 st_check_alert_flags(struct scsi_tape *un)
13545 {
13546 	struct st_tape_alert *ta;
13547 	struct uscsi_cmd *com;
13548 	struct scsi_arq_status status;
13549 	unsigned ix, length;
13550 	int rval;
13551 	tape_alert_flags flag;
13552 	char cdb[CDB_GROUP1] = {
13553 		SCMD_LOG_SENSE_G1,
13554 		0,
13555 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
13556 		0,
13557 		0,
13558 		0,
13559 		0,
13560 		(char)(sizeof (struct st_tape_alert) >> 8),
13561 		(char)(sizeof (struct st_tape_alert)),
13562 		0
13563 	};
13564 
13565 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
13566 
13567 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13568 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
13569 
13570 	com->uscsi_cdb = cdb;
13571 	com->uscsi_cdblen = CDB_GROUP1;
13572 	com->uscsi_bufaddr = (caddr_t)ta;
13573 	com->uscsi_buflen = sizeof (struct st_tape_alert);
13574 	com->uscsi_rqlen = sizeof (status);
13575 	com->uscsi_rqbuf = (caddr_t)&status;
13576 	com->uscsi_flags =
13577 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13578 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13579 
13580 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13581 
13582 	if (rval || com->uscsi_status || com->uscsi_resid) {
13583 
13584 		rval = -1; /* uscsi-command failed */
13585 
13586 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
13587 
13588 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13589 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
13590 		rval = -1;
13591 	}
13592 
13593 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
13594 
13595 
13596 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
13597 
13598 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13599 		    "TapeAlert length %d\n", length);
13600 	}
13601 
13602 
13603 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
13604 
13605 		/*
13606 		 * if rval is bad before the first pass don't bother
13607 		 */
13608 		if (ix == 0 && rval != 0) {
13609 
13610 			break;
13611 		}
13612 
13613 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
13614 		    ta->param[ix].log_param.pc_lo);
13615 
13616 		if ((ta->param[ix].param_value & 1) == 0) {
13617 			continue;
13618 		}
13619 		/*
13620 		 * check to see if current parameter is of interest.
13621 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
13622 		 */
13623 		if ((flag == TAF_CLEAN_NOW) ||
13624 		    (flag == TAF_CLEAN_PERIODIC) ||
13625 		    ((flag == CLEAN_FOR_ERRORS) &&
13626 		    (un->un_dp->type == ST_TYPE_STK9840))) {
13627 
13628 			rval = MTF_TAPE_CLN_SUPPORTED;
13629 
13630 
13631 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13632 			    "alert_page drive needs clean %d\n", flag);
13633 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
13634 			rval |= MTF_TAPE_HEAD_DIRTY;
13635 
13636 		} else if (flag == TAF_CLEANING_MEDIA) {
13637 
13638 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13639 			    "alert_page drive was cleaned\n");
13640 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
13641 		}
13642 
13643 	}
13644 
13645 	/*
13646 	 * Report it as dirty till we see it cleaned
13647 	 */
13648 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
13649 
13650 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13651 		    "alert_page still dirty\n");
13652 		rval |= MTF_TAPE_HEAD_DIRTY;
13653 	}
13654 
13655 	kmem_free(com, sizeof (struct uscsi_cmd));
13656 	kmem_free(ta,  sizeof (struct st_tape_alert));
13657 
13658 	return (rval);
13659 }
13660 
13661 
13662 static int
13663 st_check_sense_clean_bit(struct scsi_tape *un)
13664 {
13665 	uchar_t *sensep;
13666 	char cdb[CDB_GROUP0];
13667 	struct uscsi_cmd *com;
13668 	ushort_t byte_pos;
13669 	uchar_t bit_mask;
13670 	unsigned length;
13671 	int index;
13672 	int rval;
13673 
13674 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
13675 
13676 	/*
13677 	 * Since this tape does not support Tape Alert,
13678 	 * we now try to get the cleanbit status via
13679 	 * Request Sense.
13680 	 */
13681 
13682 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
13683 
13684 		index = 0;
13685 
13686 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
13687 
13688 		index = 1;
13689 
13690 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
13691 
13692 		index = 2;
13693 
13694 	} else {
13695 
13696 		return (-1);
13697 	}
13698 
13699 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
13700 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
13701 	length = byte_pos + 1;
13702 
13703 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13704 	sensep = kmem_zalloc(length, KM_SLEEP);
13705 
13706 	cdb[0] = SCMD_REQUEST_SENSE;
13707 	cdb[1] = 0;
13708 	cdb[2] = 0;
13709 	cdb[3] = 0;
13710 	cdb[4] = (char)length;
13711 	cdb[5] = 0;
13712 
13713 	com->uscsi_cdb = cdb;
13714 	com->uscsi_cdblen = CDB_GROUP0;
13715 	com->uscsi_bufaddr = (caddr_t)sensep;
13716 	com->uscsi_buflen = length;
13717 	com->uscsi_flags =
13718 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13719 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13720 
13721 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13722 
13723 	if (rval || com->uscsi_status || com->uscsi_resid) {
13724 
13725 		rval = -1;
13726 
13727 	} else {
13728 
13729 		rval = MTF_TAPE_CLN_SUPPORTED;
13730 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
13731 
13732 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13733 			    "sense data says head dirty\n");
13734 			rval |= MTF_TAPE_HEAD_DIRTY;
13735 		}
13736 	}
13737 
13738 	kmem_free(com, sizeof (struct uscsi_cmd));
13739 	kmem_free(sensep, length);
13740 	return (rval);
13741 }
13742 
13743 /*
13744  * st_clear_unit_attention
13745  *
13746  *  	run test unit ready's to clear out outstanding
13747  * 	unit attentions.
13748  * 	returns zero for SUCCESS or the errno from st_cmd call
13749  */
13750 static int
13751 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
13752 {
13753 	int	i    = 0;
13754 	int	rval;
13755 
13756 	GET_SOFT_STATE(dev_instance);
13757 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
13758 
13759 	do {
13760 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
13761 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
13762 	return (rval);
13763 }
13764 
13765 static void
13766 st_calculate_timeouts(struct scsi_tape *un)
13767 {
13768 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
13769 
13770 	if (un->un_dp->non_motion_timeout == 0) {
13771 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13772 			un->un_dp->non_motion_timeout =
13773 			    st_io_time * st_long_timeout_x;
13774 		} else {
13775 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
13776 		}
13777 	}
13778 
13779 	if (un->un_dp->io_timeout == 0) {
13780 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13781 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
13782 		} else {
13783 			un->un_dp->io_timeout = (ushort_t)st_io_time;
13784 		}
13785 	}
13786 
13787 	if (un->un_dp->rewind_timeout == 0) {
13788 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13789 			un->un_dp->rewind_timeout =
13790 			    st_space_time * st_long_timeout_x;
13791 		} else {
13792 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
13793 		}
13794 	}
13795 
13796 	if (un->un_dp->space_timeout == 0) {
13797 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13798 			un->un_dp->space_timeout =
13799 			    st_space_time * st_long_timeout_x;
13800 		} else {
13801 			un->un_dp->space_timeout = (ushort_t)st_space_time;
13802 		}
13803 	}
13804 
13805 	if (un->un_dp->load_timeout == 0) {
13806 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13807 			un->un_dp->load_timeout =
13808 			    st_space_time * st_long_timeout_x;
13809 		} else {
13810 			un->un_dp->load_timeout = (ushort_t)st_space_time;
13811 		}
13812 	}
13813 
13814 	if (un->un_dp->unload_timeout == 0) {
13815 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13816 			un->un_dp->unload_timeout =
13817 			    st_space_time * st_long_timeout_x;
13818 		} else {
13819 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
13820 		}
13821 	}
13822 
13823 	if (un->un_dp->erase_timeout == 0) {
13824 		if (un->un_dp->options & ST_LONG_ERASE) {
13825 			un->un_dp->erase_timeout =
13826 			    st_space_time * st_long_space_time_x;
13827 		} else {
13828 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
13829 		}
13830 	}
13831 }
13832 
13833 
13834 static writablity
13835 st_is_not_wormable(struct scsi_tape *un)
13836 {
13837 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
13838 	return (RDWR);
13839 }
13840 
13841 static writablity
13842 st_is_hp_dat_tape_worm(struct scsi_tape *un)
13843 {
13844 	writablity wrt;
13845 
13846 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
13847 
13848 	/* Mode sense should be current */
13849 	if (un->un_mspl->media_type == 1) {
13850 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13851 		    "Drive has WORM media loaded\n");
13852 		wrt = WORM;
13853 	} else {
13854 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13855 		    "Drive has non WORM media loaded\n");
13856 		wrt = RDWR;
13857 	}
13858 	return (wrt);
13859 }
13860 
13861 #define	HP_DAT_INQUIRY 0x4A
13862 static writablity
13863 st_is_hp_dat_worm(struct scsi_tape *un)
13864 {
13865 	char *buf;
13866 	int result;
13867 	writablity wrt;
13868 
13869 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
13870 
13871 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
13872 
13873 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
13874 
13875 	if (result != 0) {
13876 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13877 		    "Read Standard Inquiry for WORM support failed");
13878 		wrt = FAILED;
13879 	} else if ((buf[40] & 1) == 0) {
13880 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13881 		    "Drive is NOT WORMable\n");
13882 		/* This drive doesn't support it so don't check again */
13883 		un->un_dp->options &= ~ST_WORMABLE;
13884 		wrt = RDWR;
13885 		un->un_wormable = st_is_not_wormable;
13886 	} else {
13887 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13888 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13889 		un->un_wormable = st_is_hp_dat_tape_worm;
13890 		wrt = un->un_wormable(un);
13891 	}
13892 
13893 	kmem_free(buf, HP_DAT_INQUIRY);
13894 
13895 	/*
13896 	 * If drive doesn't support it no point in checking further.
13897 	 */
13898 	return (wrt);
13899 }
13900 
13901 static writablity
13902 st_is_hp_lto_tape_worm(struct scsi_tape *un)
13903 {
13904 	writablity wrt;
13905 
13906 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
13907 
13908 	/* Mode sense should be current */
13909 	switch (un->un_mspl->media_type) {
13910 	case 0x00:
13911 		switch (un->un_mspl->density) {
13912 		case 0x40:
13913 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13914 			    "Drive has standard Gen I media loaded\n");
13915 			break;
13916 		case 0x42:
13917 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13918 			    "Drive has standard Gen II media loaded\n");
13919 			break;
13920 		case 0x44:
13921 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13922 			    "Drive has standard Gen III media loaded\n");
13923 			break;
13924 		case 0x46:
13925 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13926 			    "Drive has standard Gen IV media loaded\n");
13927 			break;
13928 		default:
13929 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13930 			    "Drive has standard unknown 0x%X media loaded\n",
13931 			    un->un_mspl->density);
13932 		}
13933 		wrt = RDWR;
13934 		break;
13935 	case 0x01:
13936 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13937 		    "Drive has WORM medium loaded\n");
13938 		wrt = WORM;
13939 		break;
13940 	case 0x80:
13941 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13942 		    "Drive has CD-ROM emulation medium loaded\n");
13943 		wrt = WORM;
13944 		break;
13945 	default:
13946 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13947 		    "Drive has an unexpected medium type 0x%X loaded\n",
13948 		    un->un_mspl->media_type);
13949 		wrt = RDWR;
13950 	}
13951 
13952 	return (wrt);
13953 }
13954 
13955 #define	LTO_REQ_INQUIRY 44
13956 static writablity
13957 st_is_hp_lto_worm(struct scsi_tape *un)
13958 {
13959 	char *buf;
13960 	int result;
13961 	writablity wrt;
13962 
13963 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
13964 
13965 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
13966 
13967 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
13968 
13969 	if (result != 0) {
13970 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13971 		    "Read Standard Inquiry for WORM support failed");
13972 		wrt = FAILED;
13973 	} else if ((buf[40] & 1) == 0) {
13974 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13975 		    "Drive is NOT WORMable\n");
13976 		/* This drive doesn't support it so don't check again */
13977 		un->un_dp->options &= ~ST_WORMABLE;
13978 		wrt = RDWR;
13979 		un->un_wormable = st_is_not_wormable;
13980 	} else {
13981 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13982 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13983 		un->un_wormable = st_is_hp_lto_tape_worm;
13984 		wrt = un->un_wormable(un);
13985 	}
13986 
13987 	kmem_free(buf, LTO_REQ_INQUIRY);
13988 
13989 	/*
13990 	 * If drive doesn't support it no point in checking further.
13991 	 */
13992 	return (wrt);
13993 }
13994 
13995 static writablity
13996 st_is_t10_worm_device(struct scsi_tape *un)
13997 {
13998 	writablity wrt;
13999 
14000 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
14001 
14002 	if (un->un_mspl->media_type == 0x3c) {
14003 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14004 		    "Drive has WORM media loaded\n");
14005 		wrt = WORM;
14006 	} else {
14007 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14008 		    "Drive has non WORM media loaded\n");
14009 		wrt = RDWR;
14010 	}
14011 	return (wrt);
14012 }
14013 
14014 #define	SEQ_CAP_PAGE	(char)0xb0
14015 static writablity
14016 st_is_t10_worm(struct scsi_tape *un)
14017 {
14018 	char *buf;
14019 	int result;
14020 	writablity wrt;
14021 
14022 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
14023 
14024 	buf = kmem_zalloc(6, KM_SLEEP);
14025 
14026 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
14027 
14028 	if (result != 0) {
14029 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14030 		    "Read Vitial Inquiry for Sequental Capability"
14031 		    " WORM support failed %x", result);
14032 		wrt = FAILED;
14033 	} else if ((buf[4] & 1) == 0) {
14034 		ASSERT(buf[1] == SEQ_CAP_PAGE);
14035 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14036 		    "Drive is NOT WORMable\n");
14037 		/* This drive doesn't support it so don't check again */
14038 		un->un_dp->options &= ~ST_WORMABLE;
14039 		wrt = RDWR;
14040 		un->un_wormable = st_is_not_wormable;
14041 	} else {
14042 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14043 		    "Drive supports WORM\n");
14044 		un->un_wormable = st_is_t10_worm_device;
14045 		wrt = un->un_wormable(un);
14046 	}
14047 
14048 	kmem_free(buf, 6);
14049 
14050 	return (wrt);
14051 }
14052 
14053 
14054 #define	STK_REQ_SENSE 26
14055 
14056 static writablity
14057 st_is_stk_worm(struct scsi_tape *un)
14058 {
14059 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
14060 	struct scsi_extended_sense *sense;
14061 	struct uscsi_cmd *cmd;
14062 	char *buf;
14063 	int result;
14064 	writablity wrt;
14065 
14066 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
14067 
14068 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14069 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
14070 	sense = (struct scsi_extended_sense *)buf;
14071 
14072 	cmd->uscsi_flags = USCSI_READ;
14073 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14074 	cmd->uscsi_cdb = &cdb[0];
14075 	cmd->uscsi_bufaddr = buf;
14076 	cmd->uscsi_buflen = STK_REQ_SENSE;
14077 	cmd->uscsi_cdblen = CDB_GROUP0;
14078 	cmd->uscsi_rqlen = 0;
14079 	cmd->uscsi_rqbuf = NULL;
14080 
14081 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14082 
14083 	if (result != 0 || cmd->uscsi_status != 0) {
14084 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14085 		    "Request Sense for WORM failed");
14086 		wrt = RDWR;
14087 	} else if (sense->es_add_len + 8 < 24) {
14088 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14089 		    "Drive didn't send enough sense data for WORM byte %d\n",
14090 		    sense->es_add_len + 8);
14091 		wrt = RDWR;
14092 		un->un_wormable = st_is_not_wormable;
14093 	} else if ((buf[24]) & 0x02) {
14094 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14095 		    "Drive has WORM tape loaded\n");
14096 		wrt = WORM;
14097 		un->un_wormable = st_is_stk_worm;
14098 	} else {
14099 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14100 		    "Drive has normal tape loaded\n");
14101 		wrt = RDWR;
14102 		un->un_wormable = st_is_stk_worm;
14103 	}
14104 
14105 	kmem_free(buf, STK_REQ_SENSE);
14106 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14107 	return (wrt);
14108 }
14109 
14110 #define	DLT_INQ_SZ 44
14111 
14112 static writablity
14113 st_is_dlt_tape_worm(struct scsi_tape *un)
14114 {
14115 	caddr_t buf;
14116 	int result;
14117 	writablity wrt;
14118 
14119 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
14120 
14121 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14122 
14123 	/* Read Attribute Media Type */
14124 
14125 	result = st_read_attributes(un, 0x0408, buf, 10, st_uscsi_cmd);
14126 
14127 	/*
14128 	 * If this quantum drive is attached via an HBA that cannot
14129 	 * support thr read attributes command return error in the
14130 	 * hope that someday they will support the t10 method.
14131 	 */
14132 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
14133 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14134 		    "Read Attribute Command for WORM Media detection is not "
14135 		    "supported on the HBA that this drive is attached to.");
14136 		wrt = RDWR;
14137 		un->un_wormable = st_is_not_wormable;
14138 		goto out;
14139 	}
14140 
14141 	if (result != 0) {
14142 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14143 		    "Read Attribute Command for WORM Media returned 0x%x",
14144 		    result);
14145 		wrt = RDWR;
14146 		un->un_dp->options &= ~ST_WORMABLE;
14147 		goto out;
14148 	}
14149 
14150 	if ((uchar_t)buf[9] == 0x80) {
14151 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14152 		    "Drive media is WORM\n");
14153 		wrt = WORM;
14154 	} else {
14155 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14156 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
14157 		wrt = RDWR;
14158 	}
14159 
14160 out:
14161 	kmem_free(buf, DLT_INQ_SZ);
14162 	return (wrt);
14163 }
14164 
14165 static writablity
14166 st_is_dlt_worm(struct scsi_tape *un)
14167 {
14168 	caddr_t buf;
14169 	int result;
14170 	writablity wrt;
14171 
14172 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
14173 
14174 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14175 
14176 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
14177 
14178 	if (result != 0) {
14179 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14180 		    "Read Vendor Specific Inquiry for WORM support failed");
14181 		wrt = RDWR;
14182 		goto out;
14183 	}
14184 
14185 	if ((buf[2] & 1) == 0) {
14186 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14187 		    "Drive is not WORMable\n");
14188 		wrt = RDWR;
14189 		un->un_dp->options &= ~ST_WORMABLE;
14190 		un->un_wormable = st_is_not_wormable;
14191 		goto out;
14192 	} else {
14193 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14194 		    "Drive is WORMable\n");
14195 		un->un_wormable = st_is_dlt_tape_worm;
14196 		wrt = un->un_wormable(un);
14197 	}
14198 out:
14199 	kmem_free(buf, DLT_INQ_SZ);
14200 
14201 	return (wrt);
14202 }
14203 
14204 typedef struct {
14205 	struct modeheader_seq header;
14206 #if defined(_BIT_FIELDS_LTOH) /* X86 */
14207 	uchar_t pagecode	:6,
14208 				:2;
14209 	uchar_t page_len;
14210 	uchar_t syslogalive	:2,
14211 		device		:1,
14212 		abs		:1,
14213 		ulpbot		:1,
14214 		prth		:1,
14215 		ponej		:1,
14216 		ait		:1;
14217 	uchar_t span;
14218 
14219 	uchar_t			:6,
14220 		worm		:1,
14221 		mic		:1;
14222 	uchar_t worm_cap	:1,
14223 				:7;
14224 	uint32_t		:32;
14225 #else /* SPARC */
14226 	uchar_t			:2,
14227 		pagecode	:6;
14228 	uchar_t page_len;
14229 	uchar_t ait		:1,
14230 		device		:1,
14231 		abs		:1,
14232 		ulpbot		:1,
14233 		prth		:1,
14234 		ponej		:1,
14235 		syslogalive	:2;
14236 	uchar_t span;
14237 	uchar_t mic		:1,
14238 		worm		:1,
14239 				:6;
14240 	uchar_t			:7,
14241 		worm_cap	:1;
14242 	uint32_t		:32;
14243 #endif
14244 }ait_dev_con;
14245 
14246 #define	AIT_DEV_PAGE 0x31
14247 static writablity
14248 st_is_sony_worm(struct scsi_tape *un)
14249 {
14250 	int result;
14251 	writablity wrt;
14252 	ait_dev_con *ait_conf;
14253 
14254 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14255 
14256 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
14257 
14258 	result = st_gen_mode_sense(un, st_uscsi_cmd, AIT_DEV_PAGE,
14259 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
14260 
14261 	if (result == 0) {
14262 
14263 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
14264 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14265 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
14266 			    ait_conf->pagecode, AIT_DEV_PAGE);
14267 			wrt = RDWR;
14268 			un->un_wormable = st_is_not_wormable;
14269 
14270 		} else if (ait_conf->worm_cap) {
14271 
14272 			un->un_wormable = st_is_sony_worm;
14273 
14274 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14275 			    "Drives is WORMable\n");
14276 			if (ait_conf->worm) {
14277 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14278 				    "Media is WORM\n");
14279 				wrt = WORM;
14280 			} else {
14281 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14282 				    "Media is not WORM\n");
14283 				wrt = RDWR;
14284 			}
14285 
14286 		} else {
14287 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14288 			    "Drives not is WORMable\n");
14289 			wrt = RDWR;
14290 			/* No further checking required */
14291 			un->un_dp->options &= ~ST_WORMABLE;
14292 		}
14293 
14294 	} else {
14295 
14296 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14297 		    "AIT device config mode sense page read command failed"
14298 		    " result = %d ", result);
14299 		wrt = FAILED;
14300 		un->un_wormable = st_is_not_wormable;
14301 	}
14302 
14303 	kmem_free(ait_conf, sizeof (ait_dev_con));
14304 	return (wrt);
14305 }
14306 
14307 static writablity
14308 st_is_drive_worm(struct scsi_tape *un)
14309 {
14310 	writablity wrt;
14311 
14312 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14313 
14314 	switch (un->un_dp->type) {
14315 	case MT_ISDLT:
14316 		wrt = st_is_dlt_worm(un);
14317 		break;
14318 
14319 	case MT_ISSTK9840:
14320 		wrt = st_is_stk_worm(un);
14321 		break;
14322 
14323 	case MT_IS8MM:
14324 	case MT_ISAIT:
14325 		wrt = st_is_sony_worm(un);
14326 		break;
14327 
14328 	case MT_LTO:
14329 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14330 			wrt = st_is_hp_lto_worm(un);
14331 		} else {
14332 			wrt = st_is_t10_worm(un);
14333 		}
14334 		break;
14335 
14336 	case MT_ISDAT:
14337 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14338 			wrt = st_is_hp_dat_worm(un);
14339 		} else {
14340 			wrt = st_is_t10_worm(un);
14341 		}
14342 		break;
14343 
14344 	default:
14345 		wrt = FAILED;
14346 		break;
14347 	}
14348 
14349 	/*
14350 	 * If any of the above failed try the t10 standard method.
14351 	 */
14352 	if (wrt == FAILED) {
14353 		wrt = st_is_t10_worm(un);
14354 	}
14355 
14356 	/*
14357 	 * Unknown method for detecting WORM media.
14358 	 */
14359 	if (wrt == FAILED) {
14360 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14361 		    "Unknown method for WORM media detection\n");
14362 		wrt = RDWR;
14363 		un->un_dp->options &= ~ST_WORMABLE;
14364 	}
14365 
14366 	return (wrt);
14367 }
14368 
14369 static int
14370 st_read_attributes(struct scsi_tape *un, uint16_t attribute, void *pnt,
14371     size_t size, ubufunc_t bufunc)
14372 {
14373 	char cdb[CDB_GROUP4];
14374 	int result;
14375 	struct uscsi_cmd *cmd;
14376 	struct scsi_arq_status status;
14377 
14378 	caddr_t buf = (caddr_t)pnt;
14379 
14380 	ST_FUNC(ST_DEVINFO, st_read_attributes);
14381 
14382 	if (un->un_sd->sd_inq->inq_ansi < 3) {
14383 		return (ENOTTY);
14384 	}
14385 
14386 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14387 
14388 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
14389 	cdb[1] = 0;
14390 	cdb[2] = 0;
14391 	cdb[3] = 0;
14392 	cdb[4] = 0;
14393 	cdb[5] = 0;
14394 	cdb[6] = 0;
14395 	cdb[7] = 0;
14396 	cdb[8] = (char)(attribute >> 8);
14397 	cdb[9] = (char)(attribute);
14398 	cdb[10] = (char)(size >> 24);
14399 	cdb[11] = (char)(size >> 16);
14400 	cdb[12] = (char)(size >> 8);
14401 	cdb[13] = (char)(size);
14402 	cdb[14] = 0;
14403 	cdb[15] = 0;
14404 
14405 
14406 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE | USCSI_DIAGNOSE;
14407 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14408 	cmd->uscsi_cdb = &cdb[0];
14409 	cmd->uscsi_bufaddr = (caddr_t)buf;
14410 	cmd->uscsi_buflen = size;
14411 	cmd->uscsi_cdblen = sizeof (cdb);
14412 	cmd->uscsi_rqlen = sizeof (status);
14413 	cmd->uscsi_rqbuf = (caddr_t)&status;
14414 
14415 	result = bufunc(un, cmd, FKIOCTL);
14416 
14417 	if (result != 0 || cmd->uscsi_status != 0) {
14418 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
14419 		    "st_read_attribute failed: result %d status %d\n",
14420 		    result, cmd->uscsi_status);
14421 		/*
14422 		 * If this returns invalid operation code don't try again.
14423 		 */
14424 		if (un->un_sd->sd_sense->es_key == KEY_ILLEGAL_REQUEST &&
14425 		    un->un_sd->sd_sense->es_add_code == 0x20) {
14426 			result = ENOTTY;
14427 		} else if (result == 0) {
14428 			result = EIO;
14429 		}
14430 
14431 	} else {
14432 
14433 		/*
14434 		 * The attribute retured should match the attribute requested.
14435 		 */
14436 		if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
14437 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14438 			    "st_read_attribute got wrong data back expected "
14439 			    "0x%x got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
14440 			st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14441 			    "bad? data", buf, size);
14442 			result = EIO;
14443 		}
14444 	}
14445 
14446 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14447 
14448 	return (result);
14449 }
14450 
14451 static int
14452 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
14453     uchar_t page)
14454 {
14455 	char cdb[CDB_GROUP0];
14456 	struct scsi_extended_sense *sense;
14457 	struct uscsi_cmd *cmd;
14458 	int result;
14459 
14460 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
14461 
14462 	cdb[0] = SCMD_INQUIRY;
14463 	cdb[1] = page ? 1 : 0;
14464 	cdb[2] = page;
14465 	cdb[3] = 0;
14466 	cdb[4] = size;
14467 	cdb[5] = 0;
14468 
14469 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14470 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
14471 
14472 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
14473 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14474 	cmd->uscsi_cdb = &cdb[0];
14475 	cmd->uscsi_bufaddr = dest;
14476 	cmd->uscsi_buflen = size;
14477 	cmd->uscsi_cdblen = CDB_GROUP0;
14478 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
14479 	cmd->uscsi_rqbuf = (caddr_t)sense;
14480 
14481 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14482 
14483 	if (result != 0 || cmd->uscsi_status != 0) {
14484 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14485 		    "st_get_special_inquiry() failed for page %x", page);
14486 		if (result == 0) {
14487 			result = EIO;
14488 		}
14489 	}
14490 
14491 	kmem_free(sense, sizeof (struct scsi_extended_sense));
14492 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14493 
14494 	return (result);
14495 }
14496 
14497 
14498 static int
14499 st_update_block_pos(struct scsi_tape *un, bufunc_t bf, int post_space)
14500 {
14501 	int rval = ENOTTY;
14502 	uchar_t status = un->un_status;
14503 	posmode previous_pmode = un->un_running.pmode;
14504 
14505 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
14506 
14507 	while (un->un_read_pos_type != NO_POS) {
14508 		rval = bf(un, SCMD_READ_POSITION, 32, SYNC_CMD);
14509 
14510 		/*
14511 		 * If read position command returned good status
14512 		 * Parse the data to see if the position can be interpreted.
14513 		 */
14514 		if ((rval == 0) &&
14515 		    ((rval = st_interpret_read_pos(un, &un->un_pos,
14516 		    un->un_read_pos_type, 32, (caddr_t)un->un_read_pos_data,
14517 		    post_space)) == 0)) {
14518 			/*
14519 			 * Update the running position as well if un_pos was
14520 			 * ok. But only if recovery is enabled.
14521 			 */
14522 			if (st_recov_sz != sizeof (recov_info)) {
14523 				break;
14524 			}
14525 			rval = st_interpret_read_pos(un, &un->un_running,
14526 			    un->un_read_pos_type, 32,
14527 			    (caddr_t)un->un_read_pos_data, post_space);
14528 			un->un_status = status;
14529 			break;
14530 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
14531 			un->un_running.pmode = previous_pmode;
14532 			continue;
14533 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
14534 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
14535 			    "st_update_block_pos() read position cmd 0x%x"
14536 			    " returned 0x%x un_status = %d",
14537 			    un->un_read_pos_type, rval, un->un_status);
14538 			/* ENOTTY means it read garbage. try something else. */
14539 			if (rval == ENOTTY) {
14540 				rval = EIO; /* so ENOTTY is not final rval */
14541 			} else {
14542 				break;
14543 			}
14544 		} else {
14545 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
14546 			    "st_update_block_pos() read position cmd %x"
14547 			    " returned %x", un->un_read_pos_type, rval);
14548 			un->un_running.pmode = previous_pmode;
14549 		}
14550 
14551 		switch (un->un_read_pos_type) {
14552 		case SHORT_POS:
14553 			un->un_read_pos_type = NO_POS;
14554 			break;
14555 
14556 		case LONG_POS:
14557 			un->un_read_pos_type = EXT_POS;
14558 			break;
14559 
14560 		case EXT_POS:
14561 			un->un_read_pos_type = SHORT_POS;
14562 			break;
14563 
14564 		default:
14565 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14566 			    "Unexpected read position type 0x%x",
14567 			    un->un_read_pos_type);
14568 		}
14569 		un->un_status = KEY_NO_SENSE;
14570 	}
14571 
14572 	return (rval);
14573 }
14574 
14575 static int
14576 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
14577 {
14578 	int result;
14579 	size_t d_sz;
14580 	caddr_t pos_info;
14581 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
14582 
14583 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
14584 
14585 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
14586 		return (0);
14587 	}
14588 
14589 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
14590 
14591 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14592 		    "bp_mapin_common() failed");
14593 
14594 		return (EIO);
14595 	}
14596 
14597 	d_sz = bp->b_bcount - bp->b_resid;
14598 	if (d_sz == 0) {
14599 		bp_mapout(bp);
14600 		return (EIO);
14601 	}
14602 
14603 	/*
14604 	 * Copy the buf to a double-word aligned memory that can hold the
14605 	 * tape_position_t data structure.
14606 	 */
14607 	if ((pos_info = kmem_alloc(d_sz, KM_NOSLEEP)) == NULL) {
14608 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14609 		    "kmem_alloc() failed");
14610 		bp_mapout(bp);
14611 		return (EIO);
14612 	}
14613 	bcopy(bp->b_un.b_addr, pos_info, d_sz);
14614 
14615 #ifdef STDEBUG
14616 	if ((st_debug & 0x7) > 2) {
14617 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14618 		    "st_get_read_pos() position info",
14619 		    pos_info, bp->b_bcount);
14620 	}
14621 #endif
14622 
14623 	result = st_interpret_read_pos(un, &un->un_pos, cmd->uscsi_cdb[1],
14624 	    d_sz, pos_info, 0);
14625 
14626 	COPY_POS(&un->un_running, &un->un_pos);
14627 
14628 	kmem_free(pos_info, d_sz);
14629 	bp_mapout(bp);
14630 
14631 	return (result);
14632 }
14633 
14634 #if defined(_BIG_ENDIAN)
14635 
14636 #define	FIX_ENDIAN16(x)
14637 #define	FIX_ENDIAN32(x)
14638 #define	FIX_ENDIAN64(x)
14639 
14640 #elif defined(_LITTLE_ENDIAN)
14641 
14642 static void
14643 st_swap16(uint16_t *val)
14644 {
14645 	uint16_t tmp;
14646 
14647 	tmp = (*val >>  8) & 0xff;
14648 	tmp |= (*val <<  8) & 0xff00;
14649 
14650 	*val = tmp;
14651 }
14652 
14653 static void
14654 st_swap32(uint32_t *val)
14655 {
14656 	uint32_t tmp;
14657 
14658 	tmp =  (*val >> 24) & 0xff;
14659 	tmp |= (*val >>  8) & 0xff00;
14660 	tmp |= (*val <<  8) & 0xff0000;
14661 	tmp |= (*val << 24) & 0xff000000;
14662 
14663 	*val = tmp;
14664 }
14665 
14666 static void
14667 st_swap64(uint64_t *val)
14668 {
14669 	uint32_t low;
14670 	uint32_t high;
14671 
14672 	low =  (uint32_t)(*val);
14673 	high = (uint32_t)(*val >> 32);
14674 
14675 	st_swap32(&low);
14676 	st_swap32(&high);
14677 
14678 	*val =  high;
14679 	*val |= ((uint64_t)low << 32);
14680 }
14681 
14682 #define	FIX_ENDIAN16(x) st_swap16(x)
14683 #define	FIX_ENDIAN32(x) st_swap32(x)
14684 #define	FIX_ENDIAN64(x) st_swap64(x)
14685 #endif
14686 
14687 /*
14688  * st_interpret_read_pos()
14689  *
14690  * Returns:
14691  *	0	If secsessful.
14692  *	EIO	If read postion responce data was unuseable or invalid.
14693  *	ERANGE	If the position of the drive is too large for the read_p_type.
14694  *	ENOTTY	If the responce data looks invalid for the read position type.
14695  */
14696 
14697 static int
14698 st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
14699     read_p_types type, size_t data_sz, const caddr_t responce, int post_space)
14700 {
14701 	int rval = 0;
14702 	int flag = 0;
14703 	tapepos_t org;
14704 
14705 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
14706 
14707 	/*
14708 	 * We expect the position value to change after a space command.
14709 	 * So if post_space is set we don't print out what has changed.
14710 	 */
14711 	if ((dest != &un->un_pos) && (post_space == 0) &&
14712 	    (st_recov_sz == sizeof (recov_info))) {
14713 		COPY_POS(&org, dest);
14714 		flag = 1;
14715 	}
14716 
14717 	/*
14718 	 * See what kind of read position was requested.
14719 	 */
14720 	switch (type) {
14721 
14722 	case SHORT_POS: /* Short data format */
14723 	{
14724 		tape_position_t *pos_info = (tape_position_t *)responce;
14725 		uint32_t value;
14726 
14727 		/* If reserved fields are non zero don't use the data */
14728 		if (pos_info->reserved0 || pos_info->reserved1 ||
14729 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
14730 		    pos_info->reserved3) {
14731 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14732 			    "Invalid Read Short Position Data returned\n");
14733 			rval = EIO;
14734 			break;
14735 		}
14736 		/*
14737 		 * Position is to large to use this type of read position.
14738 		 */
14739 		if (pos_info->posi_err == 1) {
14740 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14741 			    "Drive reported position error\n");
14742 			rval = ERANGE;
14743 			break;
14744 		}
14745 		/*
14746 		 * If your at the begining of partition and end at the same
14747 		 * time it's very small partition or bad data.
14748 		 */
14749 		if (pos_info->begin_of_part && pos_info->end_of_part) {
14750 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14751 			    "SHORT_POS returned begin and end of"
14752 			    " partition\n");
14753 			rval = EIO;
14754 			break;
14755 		}
14756 
14757 		if (pos_info->blk_posi_unkwn == 0) {
14758 
14759 			value = pos_info->host_block;
14760 			FIX_ENDIAN32(&value);
14761 
14762 			/*
14763 			 * If the tape is rewound the host blcok should be 0.
14764 			 */
14765 			if ((pos_info->begin_of_part == 1) &&
14766 			    (value != 0)) {
14767 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14768 				    "SHORT_POS returned begin of partition"
14769 				    " but host block was 0x%x\n", value);
14770 				rval = EIO;
14771 				break;
14772 			}
14773 
14774 			if (dest->lgclblkno != value) {
14775 				if (flag)
14776 					flag++;
14777 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14778 				    "SHORT_POS current logical 0x%"PRIx64" read"
14779 				    " 0x%x\n", dest->lgclblkno, value);
14780 			}
14781 
14782 			dest->lgclblkno = (uint64_t)value;
14783 
14784 			/*
14785 			 * If the begining of partition is true and the
14786 			 * block number is zero we will beleive that it is
14787 			 * rewound. Promote the pmode to legacy.
14788 			 */
14789 			if ((pos_info->begin_of_part == 1) &&
14790 			    (value == 0)) {
14791 				dest->blkno = 0;
14792 				dest->fileno = 0;
14793 				if (dest->pmode != legacy)
14794 					dest->pmode = legacy;
14795 			/*
14796 			 * otherwise if the pmode was invalid,
14797 			 * promote it to logical.
14798 			 */
14799 			} else if (dest->pmode == invalid) {
14800 				dest->pmode = logical;
14801 			}
14802 
14803 			if (dest->partition != pos_info->partition_number) {
14804 				if (flag)
14805 					flag++;
14806 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14807 				    "SHORT_POS current partition %d read %d\n",
14808 				    dest->partition,
14809 				    pos_info->partition_number);
14810 			}
14811 
14812 			dest->partition = pos_info->partition_number;
14813 
14814 		} else {
14815 			dest->pmode = invalid;
14816 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14817 			    "Tape drive reported block position as unknown\n");
14818 		}
14819 		break;
14820 	}
14821 
14822 	case LONG_POS: /* Long data format */
14823 	{
14824 		uint64_t value;
14825 		tape_position_long_t *long_pos_info =
14826 		    (tape_position_long_t *)responce;
14827 
14828 		/* If reserved fields are non zero don't use the data */
14829 		if ((long_pos_info->reserved0) ||
14830 		    (long_pos_info->reserved1) ||
14831 		    (long_pos_info->reserved2)) {
14832 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14833 			    "Invalid Read Long Position Data returned\n");
14834 			rval = ENOTTY;
14835 			break;
14836 		}
14837 
14838 		/* Is position Valid */
14839 		if (long_pos_info->blk_posi_unkwn == 0) {
14840 			uint32_t part;
14841 
14842 			value = long_pos_info->block_number;
14843 			FIX_ENDIAN64(&value);
14844 
14845 			/*
14846 			 * If it says we are at the begining of partition
14847 			 * the block value better be 0.
14848 			 */
14849 			if ((long_pos_info->begin_of_part == 1) &&
14850 			    (value != 0)) {
14851 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14852 				    "LONG_POS returned begin of partition but"
14853 				    " block number was 0x%"PRIx64"\n", value);
14854 				rval = ENOTTY;
14855 				break;
14856 			}
14857 			/*
14858 			 * Can't be at the start and the end of the partition
14859 			 * at the same time if the partition is larger the 0.
14860 			 */
14861 			if (long_pos_info->begin_of_part &&
14862 			    long_pos_info->end_of_part) {
14863 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14864 				    "LONG_POS returned begin and end of"
14865 				    " partition\n");
14866 				rval = ENOTTY;
14867 				break;
14868 			}
14869 
14870 			/*
14871 			 * If the logical block number is not what we expected.
14872 			 */
14873 			if (dest->lgclblkno != value) {
14874 				if (flag)
14875 					flag++;
14876 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14877 				    "LONG_POS current logical 0x%"PRIx64
14878 				    " read 0x%"PRIx64"\n",
14879 				    dest->lgclblkno, value);
14880 			}
14881 			dest->lgclblkno = value;
14882 
14883 			/*
14884 			 * If the begining of partition is true and the
14885 			 * block number is zero we will beleive that it is
14886 			 * rewound. Promote the pmode to legacy.
14887 			 */
14888 			if ((long_pos_info->begin_of_part == 1) &&
14889 			    (long_pos_info->block_number == 0)) {
14890 				dest->blkno = 0;
14891 				dest->fileno = 0;
14892 				if (dest->pmode != legacy)
14893 					dest->pmode = legacy;
14894 			/*
14895 			 * otherwise if the pmode was invalid,
14896 			 * promote it to logical.
14897 			 */
14898 			} else if (dest->pmode == invalid) {
14899 				dest->pmode = logical;
14900 			}
14901 
14902 			part = long_pos_info->partition;
14903 			FIX_ENDIAN32(&part);
14904 			if (dest->partition != part) {
14905 				if (flag)
14906 					flag++;
14907 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14908 				    "LONG_POS current partition %d"
14909 				    " read %d\n", dest->partition, part);
14910 			}
14911 			dest->partition = part;
14912 		} else {
14913 			/*
14914 			 * If the drive doesn't know location,
14915 			 * we don't either.
14916 			 */
14917 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14918 			    "Tape drive reported block position as unknown\n");
14919 			dest->pmode = invalid;
14920 		}
14921 
14922 		/* Is file position valid */
14923 		if (long_pos_info->mrk_posi_unkwn == 0) {
14924 			value = long_pos_info->file_number;
14925 			FIX_ENDIAN64(&value);
14926 			/*
14927 			 * If it says we are at the begining of partition
14928 			 * the block value better be 0.
14929 			 */
14930 			if ((long_pos_info->begin_of_part == 1) &&
14931 			    (value != 0)) {
14932 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14933 				    "LONG_POS returned begin of partition but"
14934 				    " block number was 0x%"PRIx64"\n", value);
14935 				rval = ENOTTY;
14936 				break;
14937 			}
14938 			if (((dest->pmode == legacy) ||
14939 			    (dest->pmode == logical)) &&
14940 			    (dest->fileno != value)) {
14941 				if (flag)
14942 					flag++;
14943 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14944 				    "LONG_POS fileno 0x%"PRIx64
14945 				    " not un_pos %x\n", value,
14946 				    dest->fileno);
14947 			} else if (dest->pmode == invalid) {
14948 				dest->pmode = logical;
14949 			}
14950 			dest->fileno = (int32_t)value;
14951 		}
14952 
14953 		if (dest->pmode != invalid && long_pos_info->end_of_part) {
14954 			dest->eof = ST_EOT;
14955 		}
14956 
14957 		break;
14958 	}
14959 
14960 	case EXT_POS: /* Extended data format */
14961 	{
14962 		uint64_t value;
14963 		uint16_t len;
14964 		tape_position_ext_t *ext_pos_info =
14965 		    (tape_position_ext_t *)responce;
14966 
14967 		/* Make sure that there is enough data there */
14968 		if (data_sz < 16) {
14969 			break;
14970 		}
14971 
14972 		/* If reserved fields are non zero don't use the data */
14973 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
14974 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14975 			    "EXT_POS reserved fields not zero\n");
14976 			rval = ENOTTY;
14977 			break;
14978 		}
14979 
14980 		/*
14981 		 * In the unlikely event of overflowing 64 bits of position.
14982 		 */
14983 		if (ext_pos_info->posi_err != 0) {
14984 			rval = ERANGE;
14985 			break;
14986 		}
14987 
14988 		len = ext_pos_info->parameter_len;
14989 		FIX_ENDIAN16(&len);
14990 
14991 		if (len != 0x1c) {
14992 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14993 			    "EXT_POS parameter_len should be 0x1c was 0x%x\n",
14994 			    len);
14995 			rval = ENOTTY;
14996 			break;
14997 		}
14998 
14999 		/* Is block position information valid */
15000 		if (ext_pos_info->blk_posi_unkwn == 0) {
15001 
15002 			value = ext_pos_info->host_block;
15003 			FIX_ENDIAN64(&value);
15004 			if ((ext_pos_info->begin_of_part == 1) &&
15005 			    (value != 0)) {
15006 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15007 				    "EXT_POS returned begining of partition but"
15008 				    " the host block was 0x%"PRIx64"\n", value);
15009 				rval = ENOTTY;
15010 				break;
15011 			}
15012 
15013 			if (dest->lgclblkno != value) {
15014 				if (flag)
15015 					flag++;
15016 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15017 				    "EXT_POS current logical 0x%"PRIx64
15018 				    " read 0x%"PRIx64"\n",
15019 				    dest->lgclblkno, value);
15020 			}
15021 			dest->lgclblkno = value;
15022 
15023 			/*
15024 			 * If the begining of partition is true and the
15025 			 * block number is zero we will beleive that it is
15026 			 * rewound. Promote the pmode to legacy.
15027 			 */
15028 			if ((ext_pos_info->begin_of_part == 1) &&
15029 			    (ext_pos_info->host_block == 0)) {
15030 				dest->blkno = 0;
15031 				dest->fileno = 0;
15032 				if (dest->pmode != legacy) {
15033 					dest->pmode = legacy;
15034 				}
15035 			/*
15036 			 * otherwise if the pmode was invalid,
15037 			 * promote it to logical.
15038 			 */
15039 			} else if (dest->pmode == invalid) {
15040 				dest->pmode = logical;
15041 			}
15042 
15043 			if (dest->partition != ext_pos_info->partition) {
15044 				if (flag)
15045 					flag++;
15046 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15047 				    "EXT_POS current partition %d read %d\n",
15048 				    dest->partition,
15049 				    ext_pos_info->partition);
15050 			}
15051 			dest->partition = ext_pos_info->partition;
15052 
15053 		} else {
15054 			dest->pmode = invalid;
15055 		}
15056 		break;
15057 	}
15058 
15059 	default:
15060 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15061 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
15062 		rval = EIO;
15063 	}
15064 
15065 	if ((flag > 1) && (rval == 0) && (org.pmode != invalid)) {
15066 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
15067 		    "position read in", &org);
15068 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
15069 		    "position read out", dest);
15070 	}
15071 
15072 	return (rval);
15073 }
15074 
15075 static int
15076 st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos,
15077     uint64_t lblk, uchar_t partition)
15078 {
15079 	int rval;
15080 	char cdb[CDB_GROUP4];
15081 	struct uscsi_cmd *cmd;
15082 	struct scsi_extended_sense sense;
15083 	bufunc_t bf = (ubf == st_uscsi_cmd) ? st_cmd : st_rcmd;
15084 
15085 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
15086 	/*
15087 	 * Not sure what to do when doing recovery and not wanting
15088 	 * to update un_pos
15089 	 */
15090 
15091 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
15092 
15093 	if (lblk <= INT32_MAX) {
15094 		cmd->uscsi_cdblen = CDB_GROUP1;
15095 		cdb[0] = SCMD_LOCATE;
15096 		cdb[1] = pos->partition == partition ? 0 : 2;
15097 		cdb[2] = 0;
15098 		cdb[3] = (char)(lblk >> 24);
15099 		cdb[4] = (char)(lblk >> 16);
15100 		cdb[5] = (char)(lblk >> 8);
15101 		cdb[6] = (char)(lblk);
15102 		cdb[7] = 0;
15103 		cdb[8] = partition;
15104 		cdb[9] = 0;
15105 	} else {
15106 		/*
15107 		 * If the drive doesn't give a 64 bit read position data
15108 		 * it is unlikely it will accept 64 bit locates.
15109 		 */
15110 		if (un->un_read_pos_type != LONG_POS) {
15111 			kmem_free(cmd, sizeof (struct uscsi_cmd));
15112 			return (ERANGE);
15113 		}
15114 		cmd->uscsi_cdblen = CDB_GROUP4;
15115 		cdb[0] = (char)SCMD_LOCATE_G4;
15116 		cdb[1] = pos->partition == partition ? 0 : 2;
15117 		cdb[2] = 0;
15118 		cdb[3] = partition;
15119 		cdb[4] = (char)(lblk >> 56);
15120 		cdb[5] = (char)(lblk >> 48);
15121 		cdb[6] = (char)(lblk >> 40);
15122 		cdb[7] = (char)(lblk >> 32);
15123 		cdb[8] = (char)(lblk >> 24);
15124 		cdb[9] = (char)(lblk >> 16);
15125 		cdb[10] = (char)(lblk >> 8);
15126 		cdb[11] = (char)(lblk);
15127 		cdb[12] = 0;
15128 		cdb[13] = 0;
15129 		cdb[14] = 0;
15130 		cdb[15] = 0;
15131 	}
15132 
15133 
15134 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
15135 	cmd->uscsi_rqbuf = (caddr_t)&sense;
15136 	cmd->uscsi_rqlen = sizeof (sense);
15137 	cmd->uscsi_timeout = un->un_dp->space_timeout;
15138 	cmd->uscsi_cdb = cdb;
15139 
15140 	rval = ubf(un, cmd, FKIOCTL);
15141 
15142 	pos->pmode = logical;
15143 	pos->eof = ST_NO_EOF;
15144 
15145 	if (lblk > INT32_MAX) {
15146 		/*
15147 		 * XXX This is a work around till we handle Descriptor format
15148 		 * sense data. Since we are sending a command where the standard
15149 		 * sense data can not correctly represent a correct residual in
15150 		 * 4 bytes.
15151 		 */
15152 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
15153 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15154 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
15155 			/* Doesn't like big locate command */
15156 			un->un_status = 0;
15157 			rval = ERANGE;
15158 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
15159 			/* Aborted big locate command */
15160 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15161 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
15162 			    rval);
15163 			un->un_status = 0;
15164 			rval = EIO;
15165 		} else if (st_update_block_pos(un, bf, 1)) {
15166 			/* read position failed */
15167 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15168 			    "Big LOCATE and read pos: rval = %d\n", rval);
15169 			rval = EIO;
15170 		} else if (lblk > un->un_pos.lgclblkno) {
15171 			/* read position worked but position was not expected */
15172 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15173 			    "Big LOCATE and recover read less then desired 0x%"
15174 			    PRIx64"\n", un->un_pos.lgclblkno);
15175 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
15176 			un->un_status = KEY_BLANK_CHECK;
15177 			rval = ESPIPE;
15178 		} else if (lblk == un->un_pos.lgclblkno) {
15179 			/* read position was what was expected */
15180 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15181 			    "Big LOCATE and recover seems to have worked\n");
15182 			un->un_err_resid = 0;
15183 			rval = 0;
15184 		} else {
15185 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15186 			    "BIGLOCATE end up going backwards");
15187 			un->un_err_resid = lblk;
15188 			rval = EIO;
15189 		}
15190 
15191 	} else if (rval == 0) {
15192 		/* Worked as requested */
15193 		pos->lgclblkno = lblk;
15194 
15195 	} else if (((cmd->uscsi_status & ST_STATUS_MASK) == STATUS_CHECK) &&
15196 	    (cmd->uscsi_resid != 0)) {
15197 		/* Got part way there but wasn't enough blocks on tape */
15198 		pos->lgclblkno = lblk - cmd->uscsi_resid;
15199 		un->un_err_resid = cmd->uscsi_resid;
15200 		un->un_status = KEY_BLANK_CHECK;
15201 		rval = ESPIPE;
15202 
15203 	} else if (st_update_block_pos(un, bf, 1) == 0) {
15204 		/* Got part way there but drive didn't tell what we missed by */
15205 		un->un_err_resid = lblk - pos->lgclblkno;
15206 		un->un_status = KEY_BLANK_CHECK;
15207 		rval = ESPIPE;
15208 
15209 	} else {
15210 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15211 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
15212 		    rval, cmd->uscsi_status);
15213 		un->un_err_resid = lblk;
15214 		un->un_status = KEY_ILLEGAL_REQUEST;
15215 		pos->pmode = invalid;
15216 		rval = EIO;
15217 	}
15218 
15219 	kmem_free(cmd, sizeof (struct uscsi_cmd));
15220 
15221 	return (rval);
15222 }
15223 
15224 static int
15225 st_mtfsf_ioctl(struct scsi_tape *un, int64_t files)
15226 {
15227 	int rval;
15228 
15229 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
15230 
15231 
15232 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15233 	    "st_mtfsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15234 #if 0
15235 	if ((IN_EOF(un->un_pos)) && (files == 1)) {
15236 		un->un_pos.fileno++;
15237 		un->un_pos.blkno = 0;
15238 		return (0);
15239 	}
15240 #endif
15241 	/* pmode == invalid already handled */
15242 	if (un->un_pos.pmode == legacy) {
15243 		/*
15244 		 * forward space over filemark
15245 		 *
15246 		 * For ASF we allow a count of 0 on fsf which means
15247 		 * we just want to go to beginning of current file.
15248 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
15249 		 * Allow stepping over double fmk with reel
15250 		 */
15251 		if ((un->un_pos.eof >= ST_EOT) &&
15252 		    (files > 0) &&
15253 		    ((un->un_dp->options & ST_REEL) == 0)) {
15254 			/* we're at EOM */
15255 			un->un_err_resid = files;
15256 			un->un_status = KEY_BLANK_CHECK;
15257 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15258 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
15259 			return (EIO);
15260 		}
15261 
15262 		/*
15263 		 * physical tape position may not be what we've been
15264 		 * telling the user; adjust the request accordingly
15265 		 */
15266 		if (IN_EOF(un->un_pos)) {
15267 			un->un_pos.fileno++;
15268 			un->un_pos.blkno = 0;
15269 			/*
15270 			 * For positive direction case, we're now covered.
15271 			 * For zero or negative direction, we're covered
15272 			 * (almost)
15273 			 */
15274 			files--;
15275 		}
15276 
15277 	}
15278 
15279 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15280 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15281 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
15282 		return (EIO);
15283 	}
15284 
15285 
15286 	/*
15287 	 * Forward space file marks.
15288 	 * We leave ourselves at block zero
15289 	 * of the target file number.
15290 	 */
15291 	if (files < 0) {
15292 		rval = st_backward_space_files(un, -files, 0);
15293 	} else {
15294 		rval = st_forward_space_files(un, files);
15295 	}
15296 
15297 	return (rval);
15298 }
15299 
15300 static int
15301 st_forward_space_files(struct scsi_tape *un, int64_t count)
15302 {
15303 	int rval;
15304 
15305 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
15306 
15307 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15308 	    "fspace: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15309 
15310 	ASSERT(count >= 0);
15311 	ASSERT(un->un_pos.pmode != invalid);
15312 
15313 	/*
15314 	 * A space with a count of zero means take me to the start of file.
15315 	 */
15316 	if (count == 0) {
15317 
15318 		/* Hay look were already there */
15319 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0) {
15320 			un->un_err_resid = 0;
15321 			COPY_POS(&un->un_err_pos, &un->un_pos);
15322 			return (0);
15323 		}
15324 
15325 		/*
15326 		 * Well we are in the first file.
15327 		 * A rewind will get to the start.
15328 		 */
15329 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
15330 			rval = st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
15331 
15332 		/*
15333 		 * Can we backspace to get there?
15334 		 * This should work in logical mode.
15335 		 */
15336 		} else if (un->un_dp->options & ST_BSF) {
15337 			rval = st_space_to_begining_of_file(un);
15338 
15339 		/*
15340 		 * Can't back space but current file number is known,
15341 		 * So rewind and space from the begining of the partition.
15342 		 */
15343 		} else if (un->un_pos.pmode == legacy) {
15344 			rval = st_scenic_route_to_begining_of_file(un,
15345 			    un->un_pos.fileno);
15346 
15347 		/*
15348 		 * pmode is logical and ST_BSF is not set.
15349 		 * The LONG_POS read position contains the fileno.
15350 		 * If the read position works, rewind and space.
15351 		 */
15352 		} else if (un->un_read_pos_type == LONG_POS) {
15353 			rval = st_cmd(un, SCMD_READ_POSITION, 0, SYNC_CMD);
15354 			if (rval) {
15355 				/*
15356 				 * We didn't get the file position from the
15357 				 * read position command.
15358 				 * We are going to trust the drive to backspace
15359 				 * and then position after the filemark.
15360 				 */
15361 				rval = st_space_to_begining_of_file(un);
15362 			}
15363 			rval = st_interpret_read_pos(un, &un->un_pos, LONG_POS,
15364 			    32, (caddr_t)un->un_read_pos_data, 0);
15365 			if ((rval) && (un->un_pos.pmode == invalid)) {
15366 				rval = st_space_to_begining_of_file(un);
15367 			} else {
15368 				rval = st_scenic_route_to_begining_of_file(un,
15369 				    un->un_pos.fileno);
15370 			}
15371 		} else {
15372 			rval = EIO;
15373 		}
15374 		/*
15375 		 * If something didn't work we are lost
15376 		 */
15377 		if (rval != 0) {
15378 			un->un_pos.pmode = invalid;
15379 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15380 			    "st_mtioctop : EIO : fspace pmode invalid");
15381 
15382 			rval = EIO;
15383 		}
15384 
15385 	} else {
15386 		rval = st_space_fmks(un, count);
15387 	}
15388 
15389 	if (rval != EIO && count < 0) {
15390 		/*
15391 		 * we came here with a count < 0; we now need
15392 		 * to skip back to end up before the filemark
15393 		 */
15394 		rval = st_backward_space_files(un, 1, 1);
15395 	}
15396 
15397 	return (rval);
15398 }
15399 
15400 static int
15401 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
15402 {
15403 	int rval;
15404 
15405 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
15406 
15407 	if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15408 		rval = EIO;
15409 	} else if (st_cmd(un, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
15410 		rval = EIO;
15411 	}
15412 
15413 	return (rval);
15414 }
15415 
15416 static int
15417 st_space_to_begining_of_file(struct scsi_tape *un)
15418 {
15419 	int rval;
15420 
15421 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
15422 
15423 	/*
15424 	 * Back space of the file at the begining of the file.
15425 	 */
15426 	rval = st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
15427 	if (rval) {
15428 		rval = EIO;
15429 		return (rval);
15430 	}
15431 
15432 	/*
15433 	 * Other interesting answers might be crashed BOT which isn't bad.
15434 	 */
15435 	if (un->un_status == SUN_KEY_BOT) {
15436 		return (rval);
15437 	}
15438 
15439 	un->un_running.pmode = invalid;
15440 
15441 	/*
15442 	 * Now we are on the BOP side of the filemark. Forward space to
15443 	 * the EOM side and we are at the begining of the file.
15444 	 */
15445 	rval = st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD);
15446 	if (rval) {
15447 		rval = EIO;
15448 	}
15449 
15450 	return (rval);
15451 }
15452 
15453 static int
15454 st_mtfsr_ioctl(struct scsi_tape *un, int64_t count)
15455 {
15456 
15457 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
15458 
15459 	/*
15460 	 * forward space to inter-record gap
15461 	 *
15462 	 */
15463 
15464 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15465 	    "st_ioctl_fsr: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15466 
15467 	if (un->un_pos.pmode == legacy) {
15468 		/*
15469 		 * If were are at end of tape and count is forward.
15470 		 * Return blank check.
15471 		 */
15472 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
15473 			/* we're at EOM */
15474 			un->un_err_resid = count;
15475 			un->un_status = KEY_BLANK_CHECK;
15476 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15477 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
15478 			return (EIO);
15479 		}
15480 
15481 		/*
15482 		 * If count is zero there is nothing to do.
15483 		 */
15484 		if (count == 0) {
15485 			un->un_err_pos.fileno = un->un_pos.fileno;
15486 			un->un_err_pos.blkno = un->un_pos.blkno;
15487 			un->un_err_resid = 0;
15488 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15489 				un->un_status = SUN_KEY_EOF;
15490 			}
15491 			return (0);
15492 		}
15493 
15494 		/*
15495 		 * physical tape position may not be what we've been
15496 		 * telling the user; adjust the position accordingly
15497 		 */
15498 		if (IN_EOF(un->un_pos)) {
15499 			daddr_t blkno = un->un_pos.blkno;
15500 			int fileno = un->un_pos.fileno;
15501 
15502 			optype lastop = un->un_lastop;
15503 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)
15504 			    == -1) {
15505 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15506 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
15507 				return (EIO);
15508 			}
15509 
15510 			un->un_pos.blkno = blkno;
15511 			un->un_pos.fileno = fileno;
15512 			un->un_lastop = lastop;
15513 		}
15514 	}
15515 
15516 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15517 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15518 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
15519 		return (EIO);
15520 	}
15521 
15522 	return (st_space_records(un, count));
15523 }
15524 
15525 static int
15526 st_space_records(struct scsi_tape *un, int64_t count)
15527 {
15528 	int64_t dblk;
15529 	int rval = 0;
15530 
15531 	ST_FUNC(ST_DEVINFO, st_space_records);
15532 
15533 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15534 	    "st_space_records: count=%"PRIx64", eof=%x\n",
15535 	    count, un->un_pos.eof);
15536 
15537 	if (un->un_pos.pmode == logical) {
15538 		rval = st_cmd(un, SCMD_SPACE, Blk(count), SYNC_CMD);
15539 		if (rval != 0) {
15540 			rval = EIO;
15541 		}
15542 		return (rval);
15543 	}
15544 
15545 	dblk = count + un->un_pos.blkno;
15546 
15547 	/* Already there */
15548 	if (dblk == un->un_pos.blkno) {
15549 		un->un_err_resid = 0;
15550 		COPY_POS(&un->un_err_pos, &un->un_pos);
15551 		return (0);
15552 	}
15553 
15554 	/*
15555 	 * If the destination block is forward
15556 	 * or the drive will backspace records.
15557 	 */
15558 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
15559 		/*
15560 		 * If we're spacing forward, or the device can
15561 		 * backspace records, we can just use the SPACE
15562 		 * command.
15563 		 */
15564 		dblk -= un->un_pos.blkno;
15565 		if (st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15566 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15567 			    "st_space_records:EIO:space_records can't spc");
15568 			rval = EIO;
15569 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
15570 			/*
15571 			 * check if we hit BOT/EOT
15572 			 */
15573 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
15574 				un->un_status = SUN_KEY_BOT;
15575 				un->un_pos.eof = ST_NO_EOF;
15576 			} else if (dblk < 0 &&
15577 			    un->un_pos.eof == ST_EOF_PENDING) {
15578 				int residue = un->un_err_resid;
15579 				/*
15580 				 * we skipped over a filemark
15581 				 * and need to go forward again
15582 				 */
15583 				if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
15584 					ST_DEBUG2(ST_DEVINFO, st_label,
15585 					    SCSI_DEBUG, "st_space_records: EIO"
15586 					    " : can't space #2");
15587 					rval = EIO;
15588 				}
15589 				un->un_err_resid = residue;
15590 			}
15591 			if (rval == 0) {
15592 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15593 				    "st_space_records: EIO : space_rec rval"
15594 				    " == 0");
15595 				rval = EIO;
15596 			}
15597 		}
15598 	} else {
15599 		/*
15600 		 * else we rewind, space forward across filemarks to
15601 		 * the desired file, and then space records to the
15602 		 * desired block.
15603 		 */
15604 
15605 		int dfile = un->un_pos.fileno;	/* save current file */
15606 
15607 		if (dblk < 0) {
15608 			/*
15609 			 * Wups - we're backing up over a filemark
15610 			 */
15611 			if (un->un_pos.blkno != 0 &&
15612 			    (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15613 			    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD))) {
15614 				un->un_pos.pmode = invalid;
15615 			}
15616 			un->un_err_resid = -dblk;
15617 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
15618 				un->un_status = SUN_KEY_BOT;
15619 				un->un_pos.eof = ST_NO_EOF;
15620 			} else if (un->un_pos.fileno > 0) {
15621 				un->un_status = SUN_KEY_EOF;
15622 				un->un_pos.eof = ST_NO_EOF;
15623 			}
15624 			COPY_POS(&un->un_err_pos, &un->un_pos);
15625 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15626 			    "st_space_records:EIO:space_records : dblk < 0");
15627 			rval = EIO;
15628 		} else if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15629 		    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
15630 		    st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15631 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15632 			    "st_space_records: EIO :space_records : rewind "
15633 			    "and space failed");
15634 			un->un_pos.pmode = invalid;
15635 			rval = EIO;
15636 		}
15637 	}
15638 
15639 	return (rval);
15640 }
15641 
15642 static int
15643 st_mtbsf_ioctl(struct scsi_tape *un, int64_t files)
15644 {
15645 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
15646 
15647 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15648 	    "st_mtbsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15649 	/*
15650 	 * backward space of file filemark (1/2" and 8mm)
15651 	 * tape position will end on the beginning of tape side
15652 	 * of the desired file mark
15653 	 */
15654 	if ((un->un_dp->options & ST_BSF) == 0) {
15655 		return (ENOTTY);
15656 	}
15657 
15658 	if (un->un_pos.pmode == legacy) {
15659 
15660 		/*
15661 		 * If a negative count (which implies a forward space op)
15662 		 * is specified, and we're at logical or physical eot,
15663 		 * bounce the request.
15664 		 */
15665 
15666 		if (un->un_pos.eof >= ST_EOT && files < 0) {
15667 			un->un_err_resid = files;
15668 			un->un_status = SUN_KEY_EOT;
15669 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15670 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
15671 			return (EIO);
15672 		}
15673 		/*
15674 		 * physical tape position may not be what we've been
15675 		 * telling the user; adjust the request accordingly
15676 		 */
15677 		if (IN_EOF(un->un_pos)) {
15678 			un->un_pos.fileno++;
15679 			un->un_pos.blkno = 0;
15680 			files++;
15681 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15682 			    "st_mtbsf_ioctl in eof: count=%"PRIx64", op=%x\n",
15683 			    files, MTBSF);
15684 
15685 		}
15686 	}
15687 
15688 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15689 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15690 		    "st_ioctl : EIO : MTBSF : check den wfm");
15691 		return (EIO);
15692 	}
15693 
15694 	if (files <= 0) {
15695 		/*
15696 		 * for a negative count, we need to step forward
15697 		 * first and then step back again
15698 		 */
15699 		files = -files + 1;
15700 		return (st_forward_space_files(un, files));
15701 	}
15702 	return (st_backward_space_files(un, files, 1));
15703 }
15704 
15705 static int
15706 st_backward_space_files(struct scsi_tape *un, int64_t count, int infront)
15707 {
15708 	int64_t end_fileno;
15709 	int64_t skip_cnt;
15710 	int rval = 0;
15711 
15712 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
15713 
15714 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15715 	    "st_backward_space_files: count=%"PRIx64" eof=%x\n",
15716 	    count, un->un_pos.eof);
15717 	/*
15718 	 * Backspace files (MTNBSF): infront == 0
15719 	 *
15720 	 *	For tapes that can backspace, backspace
15721 	 *	count+1 filemarks and then run forward over
15722 	 *	a filemark
15723 	 *
15724 	 *	For tapes that can't backspace,
15725 	 *		calculate desired filenumber
15726 	 *		(un->un_pos.fileno - count), rewind,
15727 	 *		and then space forward this amount
15728 	 *
15729 	 * Backspace filemarks (MTBSF) infront == 1
15730 	 *
15731 	 *	For tapes that can backspace, backspace count
15732 	 *	filemarks
15733 	 *
15734 	 *	For tapes that can't backspace, calculate
15735 	 *	desired filenumber (un->un_pos.fileno - count),
15736 	 *	add 1, rewind, space forward this amount,
15737 	 *	and mark state as ST_EOF_PENDING appropriately.
15738 	 */
15739 
15740 	if (un->un_pos.pmode == logical) {
15741 
15742 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15743 		    "st_backward_space_files: mt_op=%x count=%"PRIx64
15744 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
15745 		    un->un_pos.lgclblkno);
15746 
15747 
15748 		/* In case a drive that won't back space gets in logical mode */
15749 		if ((un->un_dp->options & ST_BSF) == 0) {
15750 			rval = EIO;
15751 			return (rval);
15752 		}
15753 		if ((infront == 1) &&
15754 		    (st_cmd(un, SCMD_SPACE, Fmk(-count), SYNC_CMD))) {
15755 			rval = EIO;
15756 			return (rval);
15757 		} else if ((infront == 0) &&
15758 		    (st_cmd(un, SCMD_SPACE, Fmk((-count)-1), SYNC_CMD)) &&
15759 		    (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
15760 			rval = EIO;
15761 			return (rval);
15762 		}
15763 		return (rval);
15764 	}
15765 
15766 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15767 	    "st_backward_space_files: mt_op=%x count=%"PRIx64
15768 	    "fileno=%x blkno=%x\n",
15769 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
15770 
15771 
15772 
15773 	/*
15774 	 * Handle the simple case of BOT
15775 	 * playing a role in these cmds.
15776 	 * We do this by calculating the
15777 	 * ending file number. If the ending
15778 	 * file is < BOT, rewind and set an
15779 	 * error and mark resid appropriately.
15780 	 * If we're backspacing a file (not a
15781 	 * filemark) and the target file is
15782 	 * the first file on the tape, just
15783 	 * rewind.
15784 	 */
15785 
15786 	/* figure expected destination of this SPACE command */
15787 	end_fileno = un->un_pos.fileno - count;
15788 
15789 	/*
15790 	 * Would the end effect of this SPACE be the same as rewinding?
15791 	 * If so just rewind instead.
15792 	 */
15793 	if ((infront != 0) && (end_fileno < 0) ||
15794 	    (infront == 0) && (end_fileno <= 0)) {
15795 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15796 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15797 			    "st_backward_space_files: EIO : "
15798 			    "rewind in lou of BSF failed\n");
15799 			rval = EIO;
15800 		}
15801 		if (end_fileno < 0) {
15802 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15803 			    "st_backward_space_files: EIO : "
15804 			    "back space file greater then fileno\n");
15805 			rval = EIO;
15806 			un->un_err_resid = -end_fileno;
15807 			un->un_status = SUN_KEY_BOT;
15808 		}
15809 		return (rval);
15810 	}
15811 
15812 	if (un->un_dp->options & ST_BSF) {
15813 		skip_cnt = 1 - infront;
15814 		/*
15815 		 * If we are going to end up at the beginning
15816 		 * of the file, we have to space one extra file
15817 		 * first, and then space forward later.
15818 		 */
15819 		end_fileno = -(count + skip_cnt);
15820 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15821 		    "skip_cnt=%"PRIx64", tmp=%"PRIx64"\n",
15822 		    skip_cnt, end_fileno);
15823 		if (st_cmd(un, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
15824 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15825 			    "st_backward_space_files:EIO:back space fm failed");
15826 			rval = EIO;
15827 		}
15828 	} else {
15829 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15830 			rval = EIO;
15831 		} else {
15832 			skip_cnt = end_fileno + infront;
15833 		}
15834 	}
15835 
15836 	/*
15837 	 * If we have to space forward, do so...
15838 	 */
15839 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15840 	    "space forward skip_cnt=%"PRIx64", rval=%x\n", skip_cnt, rval);
15841 
15842 	if (rval == 0 && skip_cnt) {
15843 		if (st_cmd(un, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
15844 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15845 			    "st_backward_space_files:EIO:space fm skip count");
15846 			rval = EIO;
15847 		} else if (infront) {
15848 			/*
15849 			 * If we had to space forward, and we're
15850 			 * not a tape that can backspace, mark state
15851 			 * as if we'd just seen a filemark during a
15852 			 * a read.
15853 			 */
15854 			if ((un->un_dp->options & ST_BSF) == 0) {
15855 				un->un_pos.eof = ST_EOF_PENDING;
15856 				un->un_pos.fileno -= 1;
15857 				un->un_pos.blkno = LASTBLK;
15858 				un->un_running.pmode = invalid;
15859 			}
15860 		}
15861 	}
15862 
15863 	if (rval != 0) {
15864 		un->un_pos.pmode = invalid;
15865 	}
15866 
15867 	return (rval);
15868 }
15869 
15870 static int
15871 st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count)
15872 {
15873 	int rval;
15874 
15875 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
15876 
15877 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15878 	    "nbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15879 
15880 	if (un->un_pos.pmode == legacy) {
15881 		/*
15882 		 * backward space file to beginning of file
15883 		 *
15884 		 * If a negative count (which implies a forward space op)
15885 		 * is specified, and we're at logical or physical eot,
15886 		 * bounce the request.
15887 		 */
15888 
15889 		if (un->un_pos.eof >= ST_EOT && count < 0) {
15890 			un->un_err_resid = count;
15891 			un->un_status = SUN_KEY_EOT;
15892 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15893 			    "st_ioctl : EIO : > EOT and count < 0");
15894 			return (EIO);
15895 		}
15896 		/*
15897 		 * physical tape position may not be what we've been
15898 		 * telling the user; adjust the request accordingly
15899 		 */
15900 		if (IN_EOF(un->un_pos)) {
15901 			un->un_pos.fileno++;
15902 			un->un_pos.blkno = 0;
15903 			count++;
15904 		}
15905 	}
15906 
15907 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15908 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15909 		    "st_ioctl : EIO : MTNBSF check den and wfm");
15910 		return (EIO);
15911 	}
15912 
15913 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15914 	    "mtnbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15915 
15916 	if (count <= 0) {
15917 		rval = st_forward_space_files(un, -count);
15918 	} else {
15919 		rval = st_backward_space_files(un, count, 0);
15920 	}
15921 	return (rval);
15922 }
15923 
15924 static int
15925 st_mtbsr_ioctl(struct scsi_tape *un, int64_t num)
15926 {
15927 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
15928 
15929 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15930 	    "bsr: count=%"PRIx64", eof=%x\n", num, un->un_pos.eof);
15931 
15932 	if (un->un_pos.pmode == legacy) {
15933 		/*
15934 		 * backward space into inter-record gap
15935 		 *
15936 		 * If a negative count (which implies a forward space op)
15937 		 * is specified, and we're at logical or physical eot,
15938 		 * bounce the request.
15939 		 */
15940 		if (un->un_pos.eof >= ST_EOT && num < 0) {
15941 			un->un_err_resid = num;
15942 			un->un_status = SUN_KEY_EOT;
15943 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15944 			    "st_ioctl : EIO : MTBSR > EOT");
15945 			return (EIO);
15946 		}
15947 
15948 		if (num == 0) {
15949 			COPY_POS(&un->un_err_pos, &un->un_pos);
15950 			un->un_err_resid = 0;
15951 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15952 				un->un_status = SUN_KEY_EOF;
15953 			}
15954 			return (0);
15955 		}
15956 
15957 		/*
15958 		 * physical tape position may not be what we've been
15959 		 * telling the user; adjust the position accordingly.
15960 		 * bsr can not skip filemarks and continue to skip records
15961 		 * therefore if we are logically before the filemark but
15962 		 * physically at the EOT side of the filemark, we need to step
15963 		 * back; this allows fsr N where N > number of blocks in file
15964 		 * followed by bsr 1 to position at the beginning of last block
15965 		 */
15966 		if (IN_EOF(un->un_pos)) {
15967 			tapepos_t save;
15968 			optype lastop = un->un_lastop;
15969 
15970 			COPY_POS(&save, &un->un_pos);
15971 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD) == -1) {
15972 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15973 				    "st_mtbsr_ioctl: EIO : MTBSR can't space");
15974 				return (EIO);
15975 			}
15976 
15977 			COPY_POS(&un->un_pos, &save);
15978 			un->un_lastop = lastop;
15979 		}
15980 	}
15981 
15982 	un->un_pos.eof = ST_NO_EOF;
15983 
15984 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15985 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15986 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
15987 		return (EIO);
15988 	}
15989 
15990 	num = -num;
15991 	return (st_space_records(un, num));
15992 }
15993 
15994 static int
15995 st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt)
15996 {
15997 	int rval;
15998 
15999 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
16000 
16001 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
16002 	if (rval == 0) {
16003 		un->un_pos.pmode = logical;
16004 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
16005 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
16006 		/*
16007 		 * Drive says invalid field in cdb.
16008 		 * Doesn't like space multiple. Position isn't lost.
16009 		 */
16010 		un->un_err_resid = cnt;
16011 		un->un_status = 0;
16012 		rval = ENOTTY;
16013 	} else {
16014 		un->un_err_resid = cnt;
16015 		un->un_pos.pmode = invalid;
16016 	}
16017 	return (rval);
16018 }
16019 
16020 static int
16021 st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt)
16022 {
16023 	int rval;
16024 
16025 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
16026 
16027 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
16028 	if (rval == 0) {
16029 		un->un_pos.pmode = logical;
16030 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
16031 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
16032 		/*
16033 		 * Drive says invalid field in cdb.
16034 		 * Doesn't like space multiple. Position isn't lost.
16035 		 */
16036 		un->un_err_resid = cnt;
16037 		un->un_status = 0;
16038 		rval = ENOTTY;
16039 	} else {
16040 		un->un_err_resid = cnt;
16041 		un->un_pos.pmode = invalid;
16042 	}
16043 	return (rval);
16044 }
16045 
16046 #ifdef	__x86
16047 
16048 /*
16049  * release contig_mem and wake up waiting thread, if any
16050  */
16051 static void
16052 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
16053 {
16054 	mutex_enter(ST_MUTEX);
16055 
16056 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
16057 
16058 	cp->cm_next = un->un_contig_mem;
16059 	un->un_contig_mem = cp;
16060 	un->un_contig_mem_available_num++;
16061 	cv_broadcast(&un->un_contig_mem_cv);
16062 
16063 	mutex_exit(ST_MUTEX);
16064 }
16065 
16066 /*
16067  * St_get_contig_mem will return a contig_mem if there is one available
16068  * in current system. Otherwise, it will try to alloc one, if the total
16069  * number of contig_mem is within st_max_contig_mem_num.
16070  * It will sleep, if allowed by caller or return NULL, if no contig_mem
16071  * is available for now.
16072  */
16073 static struct contig_mem *
16074 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
16075 {
16076 	size_t rlen;
16077 	struct contig_mem *cp = NULL;
16078 	ddi_acc_handle_t acc_hdl;
16079 	caddr_t addr;
16080 	int big_enough = 0;
16081 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
16082 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
16083 
16084 	/* Try to get one available contig_mem */
16085 	mutex_enter(ST_MUTEX);
16086 
16087 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
16088 
16089 	if (un->un_contig_mem_available_num > 0) {
16090 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16091 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
16092 		/*
16093 		 * we failed to get one. we're going to
16094 		 * alloc one more contig_mem for this I/O
16095 		 */
16096 		mutex_exit(ST_MUTEX);
16097 		cp = (struct contig_mem *)kmem_zalloc(
16098 		    sizeof (struct contig_mem) + biosize(),
16099 		    alloc_flags);
16100 		if (cp == NULL) {
16101 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16102 			    "alloc contig_mem failure\n");
16103 			return (NULL); /* cannot get one */
16104 		}
16105 		cp->cm_bp = (struct buf *)
16106 		    (((caddr_t)cp) + sizeof (struct contig_mem));
16107 		bioinit(cp->cm_bp);
16108 		mutex_enter(ST_MUTEX);
16109 		un->un_contig_mem_total_num++; /* one more available */
16110 	} else {
16111 		/*
16112 		 * we failed to get one and we're NOT allowed to
16113 		 * alloc more contig_mem
16114 		 */
16115 		if (alloc_flags == KM_SLEEP) {
16116 			while (un->un_contig_mem_available_num <= 0) {
16117 				cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16118 			}
16119 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16120 		} else {
16121 			mutex_exit(ST_MUTEX);
16122 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16123 			    "alloc contig_mem failure\n");
16124 			return (NULL); /* cannot get one */
16125 		}
16126 	}
16127 	mutex_exit(ST_MUTEX);
16128 
16129 	/* We need to check if this block of mem is big enough for this I/O */
16130 	if (cp->cm_len < len) {
16131 		/* not big enough, need to alloc a new one */
16132 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
16133 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
16134 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
16135 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16136 			    "alloc contig_mem failure: not enough mem\n");
16137 			st_release_contig_mem(un, cp);
16138 			cp = NULL;
16139 		} else {
16140 			if (cp->cm_addr) {
16141 				/* release previous one before attach new one */
16142 				ddi_dma_mem_free(&cp->cm_acc_hdl);
16143 			}
16144 			mutex_enter(ST_MUTEX);
16145 			un->un_max_contig_mem_len =
16146 			    un->un_max_contig_mem_len >= len ?
16147 			    un->un_max_contig_mem_len : len;
16148 			mutex_exit(ST_MUTEX);
16149 
16150 			/* attach new mem to this cp */
16151 			cp->cm_addr = addr;
16152 			cp->cm_acc_hdl = acc_hdl;
16153 			cp->cm_len = len;
16154 
16155 			goto alloc_ok; /* get one usable cp */
16156 		}
16157 	} else {
16158 		goto alloc_ok; /* get one usable cp */
16159 	}
16160 
16161 	/* cannot find/alloc a usable cp, when we get here */
16162 
16163 	mutex_enter(ST_MUTEX);
16164 	if ((un->un_max_contig_mem_len < len) ||
16165 	    (alloc_flags != KM_SLEEP)) {
16166 		mutex_exit(ST_MUTEX);
16167 		return (NULL);
16168 	}
16169 
16170 	/*
16171 	 * we're allowed to sleep, and there is one big enough
16172 	 * contig mem in the system, which is currently in use,
16173 	 * wait for it...
16174 	 */
16175 	big_enough = 1;
16176 	do {
16177 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16178 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16179 	} while (cp == NULL);
16180 	mutex_exit(ST_MUTEX);
16181 
16182 	/* we get the big enough contig mem, finally */
16183 
16184 alloc_ok:
16185 	/* init bp attached to this cp */
16186 	bioreset(cp->cm_bp);
16187 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
16188 	cp->cm_bp->b_private = (void *)cp;
16189 
16190 	return (cp);
16191 }
16192 
16193 /*
16194  * this is the biodone func for the bp used in big block I/O
16195  */
16196 static int
16197 st_bigblk_xfer_done(struct buf *bp)
16198 {
16199 	struct contig_mem *cp;
16200 	struct buf *orig_bp;
16201 	int ioerr;
16202 	struct scsi_tape *un;
16203 
16204 	/* sanity check */
16205 	if (bp == NULL) {
16206 		return (DDI_FAILURE);
16207 	}
16208 
16209 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16210 	if (un == NULL) {
16211 		return (DDI_FAILURE);
16212 	}
16213 
16214 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
16215 
16216 	cp = (struct contig_mem *)bp->b_private;
16217 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
16218 	cp->cm_bp = bp;
16219 
16220 	/* special handling for special I/O */
16221 	if (cp->cm_use_sbuf) {
16222 #ifndef __lock_lint
16223 		ASSERT(un->un_sbuf_busy);
16224 #endif
16225 		un->un_sbufp = orig_bp;
16226 		cp->cm_use_sbuf = 0;
16227 	}
16228 
16229 	orig_bp->b_resid = bp->b_resid;
16230 	ioerr = geterror(bp);
16231 	if (ioerr != 0) {
16232 		bioerror(orig_bp, ioerr);
16233 	} else if (orig_bp->b_flags & B_READ) {
16234 		/* copy data back to original bp */
16235 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
16236 		    bp->b_bcount - bp->b_resid);
16237 	}
16238 
16239 	st_release_contig_mem(un, cp);
16240 
16241 	biodone(orig_bp);
16242 
16243 	return (DDI_SUCCESS);
16244 }
16245 
16246 /*
16247  * We use this func to replace original bp that may not be able to do I/O
16248  * in big block size with one that can
16249  */
16250 static struct buf *
16251 st_get_bigblk_bp(struct buf *bp)
16252 {
16253 	struct contig_mem *cp;
16254 	struct scsi_tape *un;
16255 	struct buf *cont_bp;
16256 
16257 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16258 	if (un == NULL) {
16259 		return (bp);
16260 	}
16261 
16262 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
16263 
16264 	/* try to get one contig_mem */
16265 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
16266 	if (!cp) {
16267 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
16268 		    "Cannot alloc contig buf for I/O for %lu blk size",
16269 		    bp->b_bcount);
16270 		return (bp);
16271 	}
16272 	cont_bp = cp->cm_bp;
16273 	cp->cm_bp = bp;
16274 
16275 	/* make sure that we "are" using un_sbufp for special I/O */
16276 	if (bp == un->un_sbufp) {
16277 #ifndef __lock_lint
16278 		ASSERT(un->un_sbuf_busy);
16279 #endif
16280 		un->un_sbufp = cont_bp;
16281 		cp->cm_use_sbuf = 1;
16282 	}
16283 
16284 	/* clone bp */
16285 	cont_bp->b_bcount = bp->b_bcount;
16286 	cont_bp->b_resid = bp->b_resid;
16287 	cont_bp->b_iodone = st_bigblk_xfer_done;
16288 	cont_bp->b_file = bp->b_file;
16289 	cont_bp->b_offset = bp->b_offset;
16290 	cont_bp->b_dip = bp->b_dip;
16291 	cont_bp->b_error = 0;
16292 	cont_bp->b_proc = NULL;
16293 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
16294 	cont_bp->b_shadow = NULL;
16295 	cont_bp->b_pages = NULL;
16296 	cont_bp->b_edev = bp->b_edev;
16297 	cont_bp->b_dev = bp->b_dev;
16298 	cont_bp->b_lblkno = bp->b_lblkno;
16299 	cont_bp->b_forw = bp->b_forw;
16300 	cont_bp->b_back = bp->b_back;
16301 	cont_bp->av_forw = bp->av_forw;
16302 	cont_bp->av_back = bp->av_back;
16303 	cont_bp->b_bufsize = bp->b_bufsize;
16304 
16305 	/* get data in original bp */
16306 	if (bp->b_flags & B_WRITE) {
16307 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
16308 	}
16309 
16310 	return (cont_bp);
16311 }
16312 #else
16313 #ifdef __lock_lint
16314 static int
16315 st_bigblk_xfer_done(struct buf *bp)
16316 {
16317 	return (0);
16318 }
16319 #endif
16320 #endif
16321 
16322 static const char *eof_status[] =
16323 {
16324 	"NO_EOF",
16325 	"EOF_PENDING",
16326 	"EOF",
16327 	"EOT_PENDING",
16328 	"EOT",
16329 	"EOM",
16330 	"AFTER_EOM"
16331 };
16332 static const char *mode[] = {
16333 	"invalid",
16334 	"legacy",
16335 	"logical"
16336 };
16337 
16338 static void
16339 st_print_position(dev_info_t *dev, char *label, uint_t level,
16340 const char *comment, tapepos_t *pos)
16341 {
16342 	ST_FUNC(dev, st_print_position);
16343 
16344 	scsi_log(dev, label, level,
16345 	    "%s Position data:\n", comment);
16346 	scsi_log(dev, label, CE_CONT,
16347 	    "Positioning mode = %s", mode[pos->pmode]);
16348 	scsi_log(dev, label, CE_CONT,
16349 	    "End Of File/Tape = %s", eof_status[pos->eof]);
16350 	scsi_log(dev, label, CE_CONT,
16351 	    "File Number      = 0x%x", pos->fileno);
16352 	scsi_log(dev, label, CE_CONT,
16353 	    "Block Number     = 0x%x", pos->blkno);
16354 	scsi_log(dev, label, CE_CONT,
16355 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
16356 	scsi_log(dev, label, CE_CONT,
16357 	    "Partition Number = 0x%x", pos->partition);
16358 }
16359 static int
16360 st_check_if_media_changed(struct scsi_tape *un, caddr_t data, int size)
16361 {
16362 
16363 	int result = 0;
16364 	int i;
16365 	ST_FUNC(ST_DEVINFO, st_check_if_media_changed);
16366 
16367 	/*
16368 	 * find non alpha numeric working from the end.
16369 	 */
16370 	for (i = size - 1; i >= 0; i--) {
16371 		if (ISALNUM(data[i]) == 0 || data[i] == ' ') {
16372 			data[i] = 0;
16373 			size = i;
16374 		}
16375 	}
16376 
16377 	if (size == 1) {
16378 		/*
16379 		 * Drive seems to think its returning useful data
16380 		 * but it looks like all junk
16381 		 */
16382 		return (result);
16383 	}
16384 
16385 	size++;
16386 
16387 	/*
16388 	 * Actually got a valid serial number.
16389 	 * If never stored one before alloc space for it.
16390 	 */
16391 	if (un->un_media_id_len == 0) {
16392 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16393 		un->un_media_id_len = size;
16394 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16395 		un->un_media_id[min(size, strlen(data))] = 0;
16396 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16397 		    "Found Media Id %s length = %d\n", un->un_media_id, size);
16398 	} else if (size > un->un_media_id_len) {
16399 		if (strncmp(un->un_media_id, data, size) != 0) {
16400 			result = ESPIPE;
16401 		}
16402 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16403 		    "Longer Media Id old ID:%s new ID:%s\n",
16404 		    un->un_media_id, data);
16405 		kmem_free(un->un_media_id, un->un_media_id_len);
16406 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16407 		un->un_media_id_len = size;
16408 		(void) strncpy(un->un_media_id, data, size);
16409 		un->un_media_id[size] = 0;
16410 	} else if (strncmp(data, un->un_media_id,
16411 	    min(size, un->un_media_id_len)) != 0) {
16412 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16413 		    "Old Media Id %s length = %d New %s length = %d\n",
16414 		    un->un_media_id, un->un_media_id_len, data, size);
16415 		bzero(un->un_media_id, un->un_media_id_len);
16416 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16417 		un->un_media_id[min(size, strlen(data))] = 0;
16418 		result = ESPIPE;
16419 	} else {
16420 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
16421 		    "Media Id still %s\n", un->un_media_id);
16422 	}
16423 
16424 	ASSERT(strlen(un->un_media_id) <= size);
16425 
16426 	return (result);
16427 }
16428 #define	ID_SIZE 32
16429 typedef struct
16430 {
16431 	uchar_t avilable_data0;
16432 	uchar_t avilable_data1;
16433 	uchar_t avilable_data2;
16434 	uchar_t avilable_data3;
16435 	uchar_t attribute_msb;
16436 	uchar_t attribute_lsb;
16437 #ifdef _BIT_FIELDS_LTOH
16438 	uchar_t format		: 2,
16439 				: 5,
16440 		read_only	: 1;
16441 #else
16442 	uchar_t read_only	: 1,
16443 				: 5,
16444 		format		: 2;
16445 #endif
16446 	uchar_t attribute_len_msb;
16447 	uchar_t attribute_len_lsb;
16448 }attribute_header;
16449 
16450 typedef struct {
16451 	attribute_header header;
16452 	char data[1];
16453 }mam_attribute;
16454 
16455 static int
16456 st_handle_hex_media_id(struct scsi_tape *un, void *pnt, int size)
16457 {
16458 	int result;
16459 	int newsize = (size << 1) + 3; /* extra for leading 0x and null term */
16460 	int i;
16461 	uchar_t byte;
16462 	char *format;
16463 	uchar_t *data = (uchar_t *)pnt;
16464 	char *buf = kmem_alloc(newsize, KM_SLEEP);
16465 
16466 	ST_FUNC(ST_DEVINFO, st_handle_hex_media_id);
16467 
16468 	(void) sprintf(buf, "0x");
16469 	for (i = 0; i < size; i++) {
16470 		byte = data[i];
16471 		if (byte < 0x10)
16472 			format = "0%x";
16473 		else
16474 			format = "%x";
16475 		(void) sprintf(&buf[(int)strlen(buf)], format, byte);
16476 	}
16477 	result = st_check_if_media_changed(un, buf, newsize);
16478 
16479 	kmem_free(buf, newsize);
16480 
16481 	return (result);
16482 }
16483 
16484 
16485 static int
16486 st_get_media_id_via_read_attribute(struct scsi_tape *un, ubufunc_t bufunc)
16487 {
16488 	int result;
16489 	mam_attribute *buffer;
16490 	int size;
16491 	int newsize;
16492 
16493 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_read_attribute);
16494 	size = sizeof (attribute_header) + max(un->un_media_id_len, ID_SIZE);
16495 again:
16496 	buffer = kmem_zalloc(size, KM_SLEEP);
16497 	result = st_read_attributes(un, 0x0401, buffer, size, bufunc);
16498 	if (result == 0) {
16499 
16500 		newsize = (buffer->header.attribute_len_msb << 8) |
16501 		    buffer->header.attribute_len_lsb;
16502 
16503 		if (newsize + sizeof (attribute_header) > size) {
16504 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
16505 			    "resizing read attribute data from %d to %d format"
16506 			    " %d\n", size, (int)sizeof (attribute_header) +
16507 			    newsize, buffer->header.format);
16508 			kmem_free(buffer, size);
16509 			size = newsize + sizeof (attribute_header);
16510 			goto again;
16511 		}
16512 
16513 		un->un_media_id_method = st_get_media_id_via_read_attribute;
16514 		if (buffer->header.format == 0) {
16515 			result =
16516 			    st_handle_hex_media_id(un, buffer->data, newsize);
16517 		} else {
16518 			result = st_check_if_media_changed(un, buffer->data,
16519 			    newsize);
16520 		}
16521 	} else if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
16522 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
16523 		    "Read Attribute Command for Media Identification is not "
16524 		    "supported on the HBA that this drive is attached to.");
16525 		result = ENOTTY;
16526 	}
16527 
16528 	kmem_free(buffer, size);
16529 	un->un_status = 0;
16530 
16531 	return (result);
16532 }
16533 
16534 
16535 static int
16536 st_get_media_id_via_media_serial_cmd(struct scsi_tape *un, ubufunc_t bufunc)
16537 {
16538 	char cdb[CDB_GROUP5];
16539 	struct uscsi_cmd *ucmd;
16540 	struct scsi_extended_sense sense;
16541 	int rval;
16542 	int size = max(un->un_media_id_len, ID_SIZE);
16543 	caddr_t buf;
16544 
16545 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_media_serial_cmd);
16546 
16547 	if (un->un_sd->sd_inq->inq_ansi < 3) {
16548 		return (ENOTTY);
16549 	}
16550 
16551 	ucmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
16552 upsize:
16553 	buf = kmem_alloc(size, KM_SLEEP);
16554 
16555 	cdb[0] = (char)SCMD_SVC_ACTION_IN_G5;
16556 	cdb[1] = SSVC_ACTION_READ_MEDIA_SERIAL;
16557 	cdb[2] = 0;
16558 	cdb[3] = 0;
16559 	cdb[4] = 0;
16560 	cdb[5] = 0;
16561 	cdb[6] = (char)(size >> 24);
16562 	cdb[7] = (char)(size >> 16);
16563 	cdb[8] = (char)(size >> 8);
16564 	cdb[9] = (char)(size);
16565 	cdb[10] = 0;
16566 	cdb[11] = 0;
16567 
16568 	ucmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
16569 	ucmd->uscsi_timeout = un->un_dp->non_motion_timeout;
16570 	ucmd->uscsi_cdb = &cdb[0];
16571 	ucmd->uscsi_cdblen = sizeof (cdb);
16572 	ucmd->uscsi_bufaddr = buf;
16573 	ucmd->uscsi_buflen = size;
16574 	ucmd->uscsi_rqbuf = (caddr_t)&sense;
16575 	ucmd->uscsi_rqlen = sizeof (sense);
16576 
16577 	rval = bufunc(un, ucmd, FKIOCTL);
16578 
16579 	if (rval || ucmd->uscsi_status != 0) {
16580 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16581 		    "media serial command returned %d scsi_status %d"
16582 		    " rqstatus %d", rval, ucmd->uscsi_status,
16583 		    ucmd->uscsi_rqstatus);
16584 		/*
16585 		 * If this returns invalid operation code don't try again.
16586 		 */
16587 		if (sense.es_key == KEY_ILLEGAL_REQUEST &&
16588 		    sense.es_add_code == 0x20) {
16589 			rval = ENOTTY;
16590 		} else if (rval == 0) {
16591 			rval = EIO;
16592 		}
16593 		un->un_status = 0;
16594 	} else {
16595 		int act_size;
16596 
16597 		/*
16598 		 * get reported size.
16599 		 */
16600 		act_size = (int)buf[3] | (int)(buf[2] << 8) |
16601 		    (int)(buf[1] << 16) | (int)(buf[0] << 24);
16602 
16603 		/* documentation says mod 4. */
16604 		while (act_size & 3) {
16605 			act_size++;
16606 		}
16607 
16608 		/*
16609 		 * If reported size is larger that we our buffer.
16610 		 * Free the old one and allocate one that is larger
16611 		 * enough and re-issuse the command.
16612 		 */
16613 		if (act_size + 4 > size) {
16614 			kmem_free(buf, size);
16615 			size = act_size + 4;
16616 			goto upsize;
16617 		}
16618 
16619 		if (act_size == 0) {
16620 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16621 			    "media serial number is not available");
16622 			un->un_status = 0;
16623 			rval = 0;
16624 		} else {
16625 			/*
16626 			 * set data pointer to point to the start
16627 			 * of that serial number.
16628 			 */
16629 			un->un_media_id_method =
16630 			    st_get_media_id_via_media_serial_cmd;
16631 			rval =
16632 			    st_check_if_media_changed(un, &buf[4], act_size);
16633 		}
16634 	}
16635 
16636 	kmem_free(ucmd, sizeof (struct uscsi_cmd));
16637 	kmem_free(buf, size);
16638 
16639 	return (rval);
16640 }
16641 
16642 
16643 /* ARGSUSED */
16644 static int
16645 st_bogus_media_id(struct scsi_tape *un, ubufunc_t bufunc)
16646 {
16647 	ST_FUNC(ST_DEVINFO, st_bogus_media_id);
16648 
16649 	ASSERT(un->un_media_id == NULL || un->un_media_id == bogusID);
16650 	ASSERT(un->un_media_id_len == 0);
16651 	un->un_media_id = (char *)bogusID;
16652 	un->un_media_id_len = 0;
16653 	return (0);
16654 }
16655 
16656 typedef int (*media_chk_function)(struct scsi_tape *, ubufunc_t bufunc);
16657 
16658 media_chk_function media_chk_functions[] = {
16659 	st_get_media_id_via_media_serial_cmd,
16660 	st_get_media_id_via_read_attribute,
16661 	st_bogus_media_id
16662 };
16663 
16664 static int
16665 st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc)
16666 {
16667 	int result = 0;
16668 	int i;
16669 
16670 	ST_FUNC(ST_DEVINFO, st_get_media_identification);
16671 
16672 	for (i = 0; i < ST_NUM_MEMBERS(media_chk_functions); i++) {
16673 		if (result == ENOTTY) {
16674 			/*
16675 			 * Last operation type not supported by this device.
16676 			 * Make so next time it doesn`t do that again.
16677 			 */
16678 			un->un_media_id_method = media_chk_functions[i];
16679 		} else if (un->un_media_id_method != media_chk_functions[i] &&
16680 		    un->un_media_id_method != st_get_media_identification) {
16681 			continue;
16682 		}
16683 		result = media_chk_functions[i](un, bufunc);
16684 		/*
16685 		 * If result indicates the function was successful or
16686 		 * that the media is not the same as last known, break.
16687 		 */
16688 		if (result == 0 || result == ESPIPE) {
16689 			break;
16690 		}
16691 	}
16692 
16693 	return (result);
16694 }
16695 
16696 static errstate
16697 st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
16698     errstate onentry)
16699 {
16700 
16701 	int ret;
16702 	st_err_info *errinfo;
16703 	recov_info *ri = (recov_info *)pkt->pkt_private;
16704 
16705 	ST_FUNC(ST_DEVINFO, st_command_recovery);
16706 
16707 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16708 
16709 	ASSERT(un->un_recov_buf_busy == 0);
16710 
16711 	/*
16712 	 * Don't try and recover a reset that this device sent.
16713 	 */
16714 	if (un->un_rsvd_status & ST_INITIATED_RESET &&
16715 	    onentry == DEVICE_RESET) {
16716 		return (COMMAND_DONE_ERROR);
16717 	}
16718 
16719 	/*
16720 	 * See if expected position was passed with scsi_pkt.
16721 	 */
16722 	if (ri->privatelen == sizeof (recov_info)) {
16723 
16724 		/*
16725 		 * Not for this command.
16726 		 */
16727 		if (ri->cmd_attrib->do_not_recover) {
16728 			return (COMMAND_DONE_ERROR);
16729 		}
16730 
16731 		/*
16732 		 * Create structure to hold all error state info.
16733 		 */
16734 		errinfo = kmem_zalloc(ST_ERR_INFO_SIZE, KM_SLEEP);
16735 		errinfo->ei_error_type = onentry;
16736 		errinfo->ei_failing_bp = ri->cmd_bp;
16737 		COPY_POS(&errinfo->ei_expected_pos, &ri->pos);
16738 	} else {
16739 		/* disabled */
16740 		return (COMMAND_DONE_ERROR);
16741 	}
16742 
16743 	bcopy(pkt, &errinfo->ei_failed_pkt, scsi_pkt_size());
16744 	bcopy(pkt->pkt_scbp, &errinfo->ei_failing_status, SECMDS_STATUS_SIZE);
16745 	ret = ddi_taskq_dispatch(un->un_recov_taskq, st_recover, errinfo,
16746 	    DDI_NOSLEEP);
16747 	ASSERT(ret == DDI_SUCCESS);
16748 	if (ret != DDI_SUCCESS) {
16749 		kmem_free(errinfo, ST_ERR_INFO_SIZE);
16750 		return (COMMAND_DONE_ERROR);
16751 	}
16752 	return (JUST_RETURN); /* release calling thread */
16753 }
16754 
16755 
16756 static void
16757 st_recov_ret(struct scsi_tape *un, st_err_info *errinfo, errstate err)
16758 {
16759 	int error_number;
16760 	buf_t *bp;
16761 
16762 
16763 	ST_FUNC(ST_DEVINFO, st_recov_ret);
16764 
16765 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16766 #if !defined(lint)
16767 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
16768 #endif
16769 
16770 	bp = errinfo->ei_failing_bp;
16771 	kmem_free(errinfo, ST_ERR_INFO_SIZE);
16772 
16773 	switch (err) {
16774 	case JUST_RETURN:
16775 		mutex_exit(&un->un_sd->sd_mutex);
16776 		return;
16777 
16778 	case COMMAND_DONE:
16779 	case COMMAND_DONE_ERROR_RECOVERED:
16780 		ST_DO_KSTATS(bp, kstat_runq_exit);
16781 		error_number = 0;
16782 		break;
16783 
16784 	default:
16785 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16786 		    "st_recov_ret with unhandled errstat %d\n", err);
16787 		/* FALLTHROUGH */
16788 	case COMMAND_DONE_ERROR:
16789 		un->un_pos.pmode = invalid;
16790 		un->un_running.pmode = invalid;
16791 		/* FALLTHROUGH */
16792 	case COMMAND_DONE_EACCES:
16793 		ST_DO_KSTATS(bp, kstat_waitq_exit);
16794 		ST_DO_ERRSTATS(un, st_transerrs);
16795 		error_number = EIO;
16796 		st_set_pe_flag(un);
16797 		break;
16798 
16799 	}
16800 
16801 	st_bioerror(bp, error_number);
16802 	st_done_and_mutex_exit(un, bp);
16803 }
16804 
16805 
16806 static void
16807 st_recover(void *arg)
16808 {
16809 	st_err_info *const errinfo = (st_err_info *)arg;
16810 	uchar_t com = errinfo->ei_failed_pkt.pkt_cdbp[0];
16811 	struct scsi_tape *un;
16812 	tapepos_t cur_pos;
16813 	int rval;
16814 	errstate status = COMMAND_DONE_ERROR;
16815 	recov_info *rcv;
16816 	buf_t *bp;
16817 
16818 
16819 	rcv = errinfo->ei_failed_pkt.pkt_private;
16820 	ASSERT(rcv->privatelen == sizeof (recov_info));
16821 	bp = rcv->cmd_bp;
16822 
16823 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16824 
16825 	ASSERT(un != NULL);
16826 
16827 	mutex_enter(ST_MUTEX);
16828 
16829 	ST_FUNC(ST_DEVINFO, st_recover);
16830 
16831 	ST_CDB(ST_DEVINFO, "Recovering command",
16832 	    (caddr_t)errinfo->ei_failed_pkt.pkt_cdbp);
16833 	ST_SENSE(ST_DEVINFO, "sense status for failed command",
16834 	    (caddr_t)&errinfo->ei_failing_status,
16835 	    sizeof (struct scsi_arq_status));
16836 	ST_POS(ST_DEVINFO, rcv->cmd_attrib->recov_pos_type == POS_STARTING ?
16837 	    "starting position for recovery command" :
16838 	    "expected position for recovery command",
16839 	    &errinfo->ei_expected_pos);
16840 
16841 	rval = st_test_path_to_device(un);
16842 
16843 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16844 	    "st_recover called with %s, TUR returned %d\n",
16845 	    errstatenames[errinfo->ei_error_type], rval);
16846 	/*
16847 	 * If the drive responed to the TUR lets try and get it to sync
16848 	 * any data it might have in the buffer.
16849 	 */
16850 	if (rval == 0 && rcv->cmd_attrib->chg_tape_data) {
16851 		rval = st_rcmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
16852 		if (rval) {
16853 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16854 			    "st_recover failed to flush, returned %d\n", rval);
16855 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16856 			return;
16857 		}
16858 	}
16859 	switch (errinfo->ei_error_type) {
16860 	case ATTEMPT_RETRY:
16861 	case COMMAND_TIMEOUT:
16862 	case DEVICE_RESET:
16863 	case PATH_FAILED:
16864 		/*
16865 		 * For now if we can't talk to the device we are done.
16866 		 * If the drive is reserved we can try to get it back.
16867 		 */
16868 		if (rval != 0 && rval != EACCES) {
16869 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16870 			return;
16871 		}
16872 
16873 		/*
16874 		 * If reservation conflict and do a preempt, fail it.
16875 		 */
16876 		if ((un->un_rsvd_status &
16877 		    (ST_APPLICATION_RESERVATIONS | ST_RESERVE)) != 0) {
16878 			if ((errinfo->ei_failed_pkt.pkt_cdbp[0] ==
16879 			    SCMD_PERSISTENT_RESERVE_OUT) &&
16880 			    (errinfo->ei_failed_pkt.pkt_cdbp[1] ==
16881 			    ST_SA_SCSI3_PREEMPT) &&
16882 			    (SCBP_C(&errinfo->ei_failed_pkt) ==
16883 			    STATUS_RESERVATION_CONFLICT)) {
16884 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16885 				return;
16886 			}
16887 		}
16888 
16889 		/*
16890 		 * If we have already set a scsi II reserve and get a
16891 		 * conflict on a scsi III type reserve fail without
16892 		 * any attempt to recover.
16893 		 */
16894 		if ((un->un_rsvd_status & ST_RESERVE | ST_PRESERVE_RESERVE) &&
16895 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] ==
16896 		    SCMD_PERSISTENT_RESERVE_OUT) ||
16897 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] ==
16898 		    SCMD_PERSISTENT_RESERVE_IN)) {
16899 			st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16900 			return;
16901 		}
16902 
16903 		/*
16904 		 * If scsi II lost reserve try and get it back.
16905 		 */
16906 		if ((((un->un_rsvd_status &
16907 		    (ST_LOST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
16908 		    ST_LOST_RESERVE)) &&
16909 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] != SCMD_RELEASE)) {
16910 			rval = st_reserve_release(un, ST_RESERVE,
16911 			    st_uscsi_rcmd);
16912 			if (rval != 0) {
16913 				if (st_take_ownership(un, st_uscsi_rcmd) != 0) {
16914 					st_recov_ret(un, errinfo,
16915 					    COMMAND_DONE_EACCES);
16916 					return;
16917 				}
16918 			}
16919 			un->un_rsvd_status |= ST_RESERVE;
16920 			un->un_rsvd_status &= ~(ST_RELEASE | ST_LOST_RESERVE |
16921 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
16922 		}
16923 		rval = st_make_sure_mode_data_is_correct(un, st_uscsi_rcmd);
16924 		if (rval) {
16925 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16926 			return;
16927 		}
16928 		break;
16929 	case DEVICE_TAMPER:
16930 		/*
16931 		 * Check if the ASC/ASCQ says mode data has changed.
16932 		 */
16933 		if ((errinfo->ei_failing_status.sts_sensedata.es_add_code ==
16934 		    0x2a) &&
16935 		    (errinfo->ei_failing_status.sts_sensedata.es_qual_code ==
16936 		    0x01)) {
16937 			/*
16938 			 * See if mode sense changed.
16939 			 */
16940 			rval = st_make_sure_mode_data_is_correct(un,
16941 			    st_uscsi_rcmd);
16942 			if (rval) {
16943 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16944 				return;
16945 			}
16946 		}
16947 		/*
16948 		 * if we have a media id and its not bogus.
16949 		 * Check to see if it the same.
16950 		 */
16951 		if (un->un_media_id != NULL && un->un_media_id != bogusID) {
16952 			rval = st_get_media_identification(un, st_uscsi_rcmd);
16953 			if (rval == ESPIPE) {
16954 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16955 				return;
16956 			}
16957 		}
16958 		break;
16959 	default:
16960 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16961 		    "Unhandled error type %s in st_recover() 0x%x\n",
16962 		    errstatenames[errinfo->ei_error_type], com);
16963 	}
16964 
16965 	/*
16966 	 * if command is retriable retry it.
16967 	 * Special case here. The command attribute for SCMD_REQUEST_SENSE
16968 	 * does not say that it is retriable. That because if you reissue a
16969 	 * request sense and the target responds the sense data will have
16970 	 * been consumed and no long be valid. If we get a busy status on
16971 	 * request sense while the state is ST_STATE_SENSING this will
16972 	 * reissue that pkt.
16973 	 *
16974 	 * XXX If this request sense gets sent to a different port then
16975 	 * the original command that failed was sent on it will not get
16976 	 * valid sense data for that command.
16977 	 */
16978 	if (rcv->cmd_attrib->retriable || un->un_rqs_bp == bp) {
16979 		status = st_recover_reissue_pkt(un, &errinfo->ei_failed_pkt);
16980 
16981 	/*
16982 	 * if drive doesn't support read position we are done
16983 	 */
16984 	} else if (un->un_read_pos_type == NO_POS) {
16985 		status = COMMAND_DONE_ERROR;
16986 	/*
16987 	 * If this command results in a changed tape position,
16988 	 * lets see where we are.
16989 	 */
16990 	} else if (rcv->cmd_attrib->chg_tape_pos) {
16991 		/*
16992 		 * XXX May be a reason to choose a different type here.
16993 		 * Long format has file position information.
16994 		 * Short and Extended have information about whats
16995 		 * in the buffer. St's positioning assumes in the buffer
16996 		 * to be the same as on tape.
16997 		 */
16998 		rval = st_compare_expected_position(un, errinfo,
16999 		    rcv->cmd_attrib, &cur_pos);
17000 		if (rval == 0) {
17001 			status = COMMAND_DONE;
17002 		} else if (rval == EAGAIN) {
17003 			status = st_recover_reissue_pkt(un,
17004 			    &errinfo->ei_failed_pkt);
17005 		} else {
17006 			status = COMMAND_DONE_ERROR;
17007 		}
17008 	} else {
17009 		ASSERT(0);
17010 	}
17011 
17012 	st_recov_ret(un, errinfo, status);
17013 }
17014 
17015 static void
17016 st_recov_cb(struct scsi_pkt *pkt)
17017 {
17018 	struct scsi_tape *un;
17019 	struct buf *bp;
17020 	recov_info *rcv;
17021 	errstate action = COMMAND_DONE_ERROR;
17022 	int timout = ST_TRAN_BUSY_TIMEOUT; /* short (default) timeout */
17023 
17024 	/*
17025 	 * Get the buf from the packet.
17026 	 */
17027 	rcv = pkt->pkt_private;
17028 	ASSERT(rcv->privatelen == sizeof (recov_info));
17029 	bp = rcv->cmd_bp;
17030 
17031 	/*
17032 	 * get the unit from the buf.
17033 	 */
17034 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
17035 	ASSERT(un != NULL);
17036 
17037 	ST_FUNC(ST_DEVINFO, st_recov_cb);
17038 
17039 	mutex_enter(ST_MUTEX);
17040 
17041 	ASSERT(bp == un->un_recov_buf);
17042 
17043 
17044 	switch (pkt->pkt_reason) {
17045 	case CMD_CMPLT:
17046 		if (un->un_arq_enabled && pkt->pkt_state & STATE_ARQ_DONE) {
17047 			action = st_handle_autosense(un, bp, &rcv->pos);
17048 		} else  if ((SCBP(pkt)->sts_busy) ||
17049 		    (SCBP(pkt)->sts_chk) ||
17050 		    (SCBP(pkt)->sts_vu7)) {
17051 			action = st_check_error(un, pkt);
17052 		} else {
17053 			action = COMMAND_DONE;
17054 		}
17055 		break;
17056 	case CMD_TIMEOUT:
17057 		action = COMMAND_TIMEOUT;
17058 		break;
17059 	case CMD_TRAN_ERR:
17060 		action = QUE_COMMAND;
17061 		break;
17062 	case CMD_DEV_GONE:
17063 		if (un->un_multipath)
17064 			action = PATH_FAILED;
17065 		else
17066 			action = COMMAND_DONE_ERROR;
17067 		break;
17068 	default:
17069 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
17070 		    "pkt_reason not handled yet %s",
17071 		    scsi_rname(pkt->pkt_reason));
17072 		action = COMMAND_DONE_ERROR;
17073 	}
17074 
17075 	/*
17076 	 * check for undetected path failover.
17077 	 */
17078 	if (un->un_multipath) {
17079 		if (scsi_pkt_allocated_correctly(pkt) &&
17080 		    (un->un_last_path_instance != pkt->pkt_path_instance)) {
17081 			if (un->un_state > ST_STATE_OPENING) {
17082 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17083 				    "Failover detected in recovery, action is "
17084 				    "%s\n", errstatenames[action]);
17085 			}
17086 			un->un_last_path_instance = pkt->pkt_path_instance;
17087 		}
17088 	}
17089 
17090 	ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
17091 	    "Recovery call back got %s status on %s\n",
17092 	    errstatenames[action], st_print_scsi_cmd(pkt->pkt_cdbp[0]));
17093 
17094 	switch (action) {
17095 	case COMMAND_DONE:
17096 		break;
17097 
17098 	case COMMAND_DONE_EACCES:
17099 		bioerror(bp, EACCES);
17100 		break;
17101 
17102 	case COMMAND_DONE_ERROR_RECOVERED: /* XXX maybe wrong */
17103 		ASSERT(0);
17104 		break;
17105 
17106 	case COMMAND_TIMEOUT:
17107 	case COMMAND_DONE_ERROR:
17108 		bioerror(bp, EIO);
17109 		break;
17110 
17111 	case DEVICE_RESET:
17112 	case QUE_BUSY_COMMAND:
17113 	case PATH_FAILED:
17114 		/* longish timeout */
17115 		timout = ST_STATUS_BUSY_TIMEOUT;
17116 		/* FALLTHRU */
17117 	case QUE_COMMAND:
17118 	case DEVICE_TAMPER:
17119 	case ATTEMPT_RETRY:
17120 		/*
17121 		 * let st_handle_intr_busy put this bp back on waitq and make
17122 		 * checks to see if it is ok to requeue the command.
17123 		 */
17124 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
17125 
17126 		/*
17127 		 * Save the throttle before setting up the timeout
17128 		 */
17129 		if (un->un_throttle) {
17130 			un->un_last_throttle = un->un_throttle;
17131 		}
17132 		mutex_exit(ST_MUTEX);
17133 		if (st_handle_intr_busy(un, bp, timout) == 0) {
17134 			return;		/* timeout is setup again */
17135 		}
17136 		mutex_enter(ST_MUTEX);
17137 		un->un_pos.pmode = invalid;
17138 		un->un_err_resid = bp->b_resid = bp->b_bcount;
17139 		st_bioerror(bp, EIO);
17140 		st_set_pe_flag(un);
17141 		break;
17142 
17143 	default:
17144 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
17145 		    "Unhandled recovery state 0x%x\n", action);
17146 		un->un_pos.pmode = invalid;
17147 		un->un_err_resid = bp->b_resid = bp->b_bcount;
17148 		st_bioerror(bp, EIO);
17149 		st_set_pe_flag(un);
17150 		break;
17151 	}
17152 
17153 	st_done_and_mutex_exit(un, bp);
17154 }
17155 
17156 static int
17157 st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait)
17158 {
17159 	struct buf *bp;
17160 	int err;
17161 
17162 	ST_FUNC(ST_DEVINFO, st_rcmd);
17163 
17164 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
17165 	    "st_rcmd(un = 0x%p, com = 0x%x, count = %"PRIx64", wait = %d)\n",
17166 	    (void *)un, com, count, wait);
17167 
17168 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
17169 	ASSERT(mutex_owned(ST_MUTEX));
17170 
17171 #ifdef STDEBUG
17172 	if ((st_debug & 0x7)) {
17173 		st_debug_cmds(un, com, count, wait);
17174 	}
17175 #endif
17176 
17177 	while (un->un_recov_buf_busy)
17178 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17179 	un->un_recov_buf_busy = 1;
17180 
17181 	bp = un->un_recov_buf;
17182 	bzero(bp, sizeof (buf_t));
17183 
17184 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
17185 
17186 	err = st_setup_cmd(un, bp, com, count);
17187 
17188 	un->un_recov_buf_busy = 0;
17189 
17190 	cv_signal(&un->un_recov_buf_cv);
17191 
17192 	return (err);
17193 }
17194 
17195 /* args used */
17196 static int
17197 st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
17198 {
17199 	int rval;
17200 	buf_t *bp;
17201 
17202 	ST_FUNC(ST_DEVINFO, st_uscsi_rcmd);
17203 	ASSERT(flag == FKIOCTL);
17204 
17205 	/*
17206 	 * Get buffer resources...
17207 	 */
17208 	while (un->un_recov_buf_busy)
17209 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17210 	un->un_recov_buf_busy = 1;
17211 
17212 	bp = un->un_recov_buf;
17213 	bzero(bp, sizeof (buf_t));
17214 
17215 	bp->b_forw = (struct buf *)(uintptr_t)ucmd->uscsi_cdb[0];
17216 	bp->b_back = (struct buf *)ucmd;
17217 
17218 	mutex_exit(ST_MUTEX);
17219 	rval = scsi_uscsi_handle_cmd(un->un_dev, UIO_SYSSPACE, ucmd,
17220 	    st_strategy, bp, NULL);
17221 	mutex_enter(ST_MUTEX);
17222 
17223 	ucmd->uscsi_resid = bp->b_resid;
17224 
17225 	/*
17226 	 * Free resources
17227 	 */
17228 	un->un_recov_buf_busy = 0;
17229 	cv_signal(&un->un_recov_buf_cv);
17230 
17231 	return (rval);
17232 }
17233 
17234 /*
17235  * Add data to scsi_pkt to help know what to do if the command fails.
17236  */
17237 static void
17238 st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
17239     struct scsi_pkt *pkt)
17240 {
17241 	uint64_t count;
17242 	recov_info *rinfo = (recov_info *)pkt->pkt_private;
17243 
17244 	ST_FUNC(ST_DEVINFO, st_add_recovery_info_to_pkt);
17245 
17246 	ASSERT(rinfo->privatelen == sizeof (pkt_info) ||
17247 	    rinfo->privatelen == sizeof (recov_info));
17248 
17249 	SET_BP_PKT(bp, pkt);
17250 	rinfo->cmd_bp = bp;
17251 
17252 	if (rinfo->privatelen != sizeof (recov_info)) {
17253 		return;
17254 	}
17255 
17256 	rinfo->cmd_bp = bp;
17257 
17258 	rinfo->cmd_attrib = NULL;
17259 
17260 	/*
17261 	 * lookup the command attributes and add them to the recovery info.
17262 	 */
17263 	rinfo->cmd_attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
17264 
17265 	ASSERT(rinfo->cmd_attrib);
17266 
17267 	/*
17268 	 * For commands that there is no way to figure the expected position
17269 	 * once completed, we save the position the command was started from
17270 	 * so that if they fail we can position back and try again.
17271 	 * This has already been done in st_cmd() or st_iscsi_cmd().
17272 	 */
17273 	if (rinfo->cmd_attrib->recov_pos_type == POS_STARTING) {
17274 		/* save current position as the starting position. */
17275 		COPY_POS(&rinfo->pos, &un->un_pos);
17276 		un->un_running.pmode = invalid;
17277 		return;
17278 	}
17279 
17280 	/*
17281 	 * Don't want to update the running position for recovery.
17282 	 */
17283 	if (bp == un->un_recov_buf) {
17284 		rinfo->pos.pmode = un->un_running.pmode;
17285 		return;
17286 	}
17287 	/*
17288 	 * If running position is invalid copy the current position.
17289 	 * Running being set invalid means we are not in a read, write
17290 	 * or write filemark sequence.
17291 	 * We'll copy the current position and start from there.
17292 	 */
17293 	if (un->un_running.pmode == invalid) {
17294 		COPY_POS(&un->un_running, &un->un_pos);
17295 		COPY_POS(&rinfo->pos, &un->un_running);
17296 	} else {
17297 		COPY_POS(&rinfo->pos, &un->un_running);
17298 		if (rinfo->pos.pmode == legacy) {
17299 			/*
17300 			 * Always should be more logical blocks then
17301 			 * data blocks and files marks.
17302 			 */
17303 			ASSERT((rinfo->pos.blkno >= 0) ?
17304 			    rinfo->pos.lgclblkno >=
17305 			    (rinfo->pos.blkno + rinfo->pos.fileno) : 1);
17306 		}
17307 	}
17308 
17309 	/*
17310 	 * If the command is not expected to change the drive position
17311 	 * then the running position should be the expected position.
17312 	 */
17313 	if (rinfo->cmd_attrib->chg_tape_pos == 0) {
17314 		ASSERT(rinfo->cmd_attrib->chg_tape_direction == DIR_NONE);
17315 		return;
17316 	}
17317 
17318 	if (rinfo->cmd_attrib->explicit_cmd_set) {
17319 		ASSERT(rinfo->pos.pmode != invalid);
17320 		ASSERT(rinfo->cmd_attrib->get_cnt);
17321 		count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17322 		/*
17323 		 * This is a user generated CDB.
17324 		 */
17325 		if (bp == un->un_sbufp) {
17326 			uint64_t lbn;
17327 
17328 			lbn = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17329 
17330 			/*
17331 			 * See if this CDB will generate a locate or change
17332 			 * partition.
17333 			 */
17334 			if ((lbn != un->un_running.lgclblkno) ||
17335 			    (pkt->pkt_cdbp[3] != un->un_running.partition)) {
17336 				rinfo->pos.partition = pkt->pkt_cdbp[3];
17337 				rinfo->pos.pmode = logical;
17338 				rinfo->pos.lgclblkno = lbn;
17339 				un->un_running.partition = pkt->pkt_cdbp[3];
17340 				un->un_running.pmode = logical;
17341 				un->un_running.lgclblkno = lbn;
17342 			}
17343 		} else {
17344 			uint64_t lbn = un->un_running.lgclblkno;
17345 
17346 			pkt->pkt_cdbp[3]  = (uchar_t)un->un_running.partition;
17347 
17348 			pkt->pkt_cdbp[4]  = (uchar_t)(lbn >> 56);
17349 			pkt->pkt_cdbp[5]  = (uchar_t)(lbn >> 48);
17350 			pkt->pkt_cdbp[6]  = (uchar_t)(lbn >> 40);
17351 			pkt->pkt_cdbp[7]  = (uchar_t)(lbn >> 32);
17352 			pkt->pkt_cdbp[8]  = (uchar_t)(lbn >> 24);
17353 			pkt->pkt_cdbp[9]  = (uchar_t)(lbn >> 16);
17354 			pkt->pkt_cdbp[10] = (uchar_t)(lbn >> 8);
17355 			pkt->pkt_cdbp[11] = (uchar_t)(lbn);
17356 		}
17357 		rinfo->pos.lgclblkno += count;
17358 		rinfo->pos.blkno += count;
17359 		un->un_running.lgclblkno += count;
17360 		return;
17361 	}
17362 
17363 	if (rinfo->cmd_attrib->chg_tape_pos) {
17364 
17365 		/* should not have got an invalid position from running. */
17366 		if (un->un_mediastate == MTIO_INSERTED) {
17367 			ASSERT(rinfo->pos.pmode != invalid);
17368 		}
17369 
17370 		/* should have either a get count or or get lba function */
17371 		ASSERT(rinfo->cmd_attrib->get_cnt != NULL ||
17372 		    rinfo->cmd_attrib->get_lba != NULL);
17373 
17374 		/* only explicit commands have both and they're handled above */
17375 		ASSERT(!(rinfo->cmd_attrib->get_cnt != NULL &&
17376 		    rinfo->cmd_attrib->get_lba != NULL));
17377 
17378 		/* if it has a get count function */
17379 		if (rinfo->cmd_attrib->get_cnt != NULL) {
17380 			count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17381 			if (count == 0) {
17382 				return;
17383 			}
17384 			/*
17385 			 * Changes position but doesn't transfer data.
17386 			 * i.e. rewind, write_file_mark and load.
17387 			 */
17388 			if (rinfo->cmd_attrib->transfers_data == TRAN_NONE) {
17389 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17390 				case DIR_NONE: /* Erase */
17391 					ASSERT(rinfo->cmd_attrib->cmd ==
17392 					    SCMD_ERASE);
17393 					break;
17394 				case DIR_FORW: /* write_file_mark */
17395 					rinfo->pos.fileno += count;
17396 					rinfo->pos.lgclblkno += count;
17397 					rinfo->pos.blkno = 0;
17398 					un->un_running.fileno += count;
17399 					un->un_running.lgclblkno += count;
17400 					un->un_running.blkno = 0;
17401 					break;
17402 				case DIR_REVC: /* rewind */
17403 					rinfo->pos.fileno = 0;
17404 					rinfo->pos.lgclblkno = 0;
17405 					rinfo->pos.blkno = 0;
17406 					rinfo->pos.eof = ST_NO_EOF;
17407 					rinfo->pos.pmode = legacy;
17408 					un->un_running.fileno = 0;
17409 					un->un_running.lgclblkno = 0;
17410 					un->un_running.blkno = 0;
17411 					un->un_running.eof = ST_NO_EOF;
17412 					if (un->un_running.pmode != legacy)
17413 						un->un_running.pmode = legacy;
17414 					break;
17415 				case DIR_EITH: /* Load unload */
17416 					ASSERT(rinfo->cmd_attrib->cmd ==
17417 					    SCMD_LOAD);
17418 					switch (count & (LD_LOAD | LD_RETEN |
17419 					    LD_RETEN | LD_HOLD)) {
17420 					case LD_UNLOAD:
17421 					case LD_RETEN:
17422 					case LD_HOLD:
17423 					case LD_LOAD | LD_HOLD:
17424 					case LD_EOT | LD_HOLD:
17425 					case LD_RETEN | LD_HOLD:
17426 						rinfo->pos.pmode = invalid;
17427 						un->un_running.pmode = invalid;
17428 						break;
17429 					case LD_EOT:
17430 					case LD_LOAD | LD_EOT:
17431 						rinfo->pos.eof = ST_EOT;
17432 						rinfo->pos.pmode = invalid;
17433 						un->un_running.eof = ST_EOT;
17434 						un->un_running.pmode = invalid;
17435 						break;
17436 					case LD_LOAD:
17437 					case LD_RETEN | LD_LOAD:
17438 						rinfo->pos.fileno = 0;
17439 						rinfo->pos.lgclblkno = 0;
17440 						rinfo->pos.blkno = 0;
17441 						rinfo->pos.eof = ST_NO_EOF;
17442 						rinfo->pos.pmode = legacy;
17443 						un->un_running.fileno = 0;
17444 						un->un_running.lgclblkno = 0;
17445 						un->un_running.blkno = 0;
17446 						un->un_running.eof = ST_NO_EOF;
17447 						break;
17448 					default:
17449 						ASSERT(0);
17450 					}
17451 					break;
17452 				default:
17453 					ASSERT(0);
17454 					break;
17455 				}
17456 			} else {
17457 				/*
17458 				 * Changes position and does transfer data.
17459 				 * i.e. read or write.
17460 				 */
17461 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17462 				case DIR_FORW:
17463 					rinfo->pos.lgclblkno += count;
17464 					rinfo->pos.blkno += count;
17465 					un->un_running.lgclblkno += count;
17466 					un->un_running.blkno += count;
17467 					break;
17468 				case DIR_REVC:
17469 					rinfo->pos.lgclblkno -= count;
17470 					rinfo->pos.blkno -= count;
17471 					un->un_running.lgclblkno -= count;
17472 					un->un_running.blkno -= count;
17473 					break;
17474 				default:
17475 					ASSERT(0);
17476 					break;
17477 				}
17478 			}
17479 		} else if (rinfo->cmd_attrib->get_lba != NULL) {
17480 			/* Have a get LBA fuction. i.e. Locate */
17481 			ASSERT(rinfo->cmd_attrib->chg_tape_direction ==
17482 			    DIR_EITH);
17483 			count = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17484 			un->un_running.lgclblkno = count;
17485 			un->un_running.blkno = 0;
17486 			un->un_running.fileno = 0;
17487 			un->un_running.pmode = logical;
17488 			rinfo->pos.lgclblkno = count;
17489 			rinfo->pos.pmode = invalid;
17490 		} else {
17491 			ASSERT(0);
17492 		}
17493 		return;
17494 	}
17495 
17496 	ST_CDB(ST_DEVINFO, "Unhanded CDB for position prediction",
17497 	    (char *)pkt->pkt_cdbp);
17498 
17499 }
17500 
17501 static int
17502 st_make_sure_mode_data_is_correct(struct scsi_tape *un, ubufunc_t ubf)
17503 {
17504 	int rval;
17505 
17506 	ST_FUNC(ST_DEVINFO, st_make_sure_mode_data_is_correct);
17507 
17508 	/*
17509 	 * check to see if mode data has changed.
17510 	 */
17511 	rval = st_check_mode_for_change(un, ubf);
17512 	if (rval) {
17513 		rval = st_gen_mode_select(un, ubf, un->un_mspl,
17514 		    sizeof (struct seq_mode));
17515 	}
17516 	if (un->un_tlr_flag != TLR_NOT_SUPPORTED) {
17517 		rval |= st_set_target_TLR_mode(un, ubf);
17518 	}
17519 	return (rval);
17520 }
17521 
17522 static int
17523 st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf)
17524 {
17525 	struct seq_mode *current;
17526 	int rval;
17527 	int i;
17528 	caddr_t this;
17529 	caddr_t that;
17530 
17531 	ST_FUNC(ST_DEVINFO, st_check_mode_for_change);
17532 
17533 	/* recovery called with mode tamper before mode selection */
17534 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
17535 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17536 		    "Mode Select not done yet");
17537 		return (0);
17538 	}
17539 
17540 	current = kmem_zalloc(sizeof (struct seq_mode), KM_SLEEP);
17541 
17542 	rval = st_gen_mode_sense(un, ubf, un->un_comp_page, current,
17543 	    sizeof (struct seq_mode));
17544 	if (rval != 0) {
17545 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17546 		    "Mode Sense for mode verification failed");
17547 		kmem_free(current, sizeof (struct seq_mode));
17548 		return (rval);
17549 	}
17550 
17551 	this = (caddr_t)current;
17552 	that = (caddr_t)un->un_mspl;
17553 
17554 	rval = bcmp(this, that, sizeof (struct seq_mode));
17555 	if (rval == 0) {
17556 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17557 		    "Found no changes in mode data");
17558 	}
17559 #ifdef STDEBUG
17560 	else {
17561 		for (i = 1; i < sizeof (struct seq_mode); i++) {
17562 			if (this[i] != that[i]) {
17563 				ST_RECOV(ST_DEVINFO, st_label, CE_CONT,
17564 				    "sense data changed at byte %d was "
17565 				    "0x%x now 0x%x", i,
17566 				    (uchar_t)that[i], (uchar_t)this[i]);
17567 			}
17568 		}
17569 	}
17570 #endif
17571 	kmem_free(current, sizeof (struct seq_mode));
17572 
17573 	return (rval);
17574 }
17575 
17576 static int
17577 st_test_path_to_device(struct scsi_tape *un)
17578 {
17579 	int rval = 0;
17580 	int limit = st_retry_count;
17581 
17582 	ST_FUNC(ST_DEVINFO, st_test_path_to_device);
17583 
17584 	/*
17585 	 * XXX Newer drives may not RESEVATION CONFLICT a TUR.
17586 	 */
17587 	do {
17588 		if (rval != 0) {
17589 			mutex_exit(ST_MUTEX);
17590 			delay(drv_usectohz(1000000));
17591 			mutex_enter(ST_MUTEX);
17592 		}
17593 		rval = st_rcmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
17594 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17595 		    "ping TUR returned 0x%x", rval);
17596 		limit--;
17597 	} while (((rval == EACCES) || (rval == EBUSY)) && limit);
17598 
17599 	if (un->un_status == KEY_NOT_READY || un->un_mediastate == MTIO_EJECTED)
17600 		rval = 0;
17601 
17602 	return (rval);
17603 }
17604 
17605 /*
17606  * Does read position using recov_buf and doesn't update un_pos.
17607  * Does what ever kind of read position you want.
17608  */
17609 static int
17610 st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
17611     read_pos_data_t *raw)
17612 {
17613 	int rval;
17614 	struct uscsi_cmd cmd;
17615 	struct scsi_arq_status status;
17616 	char cdb[CDB_GROUP1];
17617 
17618 	ST_FUNC(ST_DEVINFO, st_recovery_read_pos);
17619 	bzero(&cmd, sizeof (cmd));
17620 
17621 	cdb[0] = SCMD_READ_POSITION;
17622 	cdb[1] = type;
17623 	cdb[2] = 0;
17624 	cdb[3] = 0;
17625 	cdb[4] = 0;
17626 	cdb[5] = 0;
17627 	cdb[6] = 0;
17628 	cdb[7] = 0;
17629 	cdb[8] = (type == EXT_POS) ? 28 : 0;
17630 	cdb[9] = 0;
17631 
17632 	cmd.uscsi_flags = USCSI_READ | USCSI_RQENABLE;
17633 	cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
17634 	cmd.uscsi_cdb = cdb;
17635 	cmd.uscsi_cdblen = sizeof (cdb);
17636 	cmd.uscsi_rqlen = sizeof (status);
17637 	cmd.uscsi_rqbuf = (caddr_t)&status;
17638 	cmd.uscsi_bufaddr = (caddr_t)raw;
17639 	switch (type) {
17640 	case SHORT_POS:
17641 		cmd.uscsi_buflen = sizeof (tape_position_t);
17642 		break;
17643 	case LONG_POS:
17644 		cmd.uscsi_buflen = sizeof (tape_position_long_t);
17645 		break;
17646 	case EXT_POS:
17647 		cmd.uscsi_buflen = sizeof (tape_position_ext_t);
17648 		break;
17649 	default:
17650 		ASSERT(0);
17651 	}
17652 
17653 	rval = st_uscsi_rcmd(un, &cmd, FKIOCTL);
17654 	if (cmd.uscsi_status) {
17655 		rval = EIO;
17656 	}
17657 	return (rval);
17658 }
17659 
17660 static int
17661 st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
17662     read_pos_data_t *raw)
17663 {
17664 	int rval;
17665 	read_p_types type = un->un_read_pos_type;
17666 
17667 	ST_FUNC(ST_DEVINFO, st_recovery_get_position);
17668 
17669 	do {
17670 		rval = st_recovery_read_pos(un, type, raw);
17671 		if (rval != 0) {
17672 			switch (type) {
17673 			case SHORT_POS:
17674 				type = NO_POS;
17675 				break;
17676 
17677 			case LONG_POS:
17678 				type = EXT_POS;
17679 				break;
17680 
17681 			case EXT_POS:
17682 				type = SHORT_POS;
17683 				break;
17684 
17685 			default:
17686 				type = LONG_POS;
17687 				break;
17688 
17689 			}
17690 		} else {
17691 			if (type != un->un_read_pos_type) {
17692 				un->un_read_pos_type = type;
17693 			}
17694 			break;
17695 		}
17696 	} while (type != NO_POS);
17697 
17698 	if (rval == 0) {
17699 		rval = st_interpret_read_pos(un, read, type,
17700 		    sizeof (read_pos_data_t), (caddr_t)raw, 1);
17701 	}
17702 	return (rval);
17703 }
17704 
17705 /*
17706  * based on the command do we retry, continue or give up?
17707  * possable return values?
17708  *	zero do nothing looks fine.
17709  *	EAGAIN retry.
17710  *	EIO failed makes no sense.
17711  */
17712 static int
17713 st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
17714     cmd_attribute const * cmd_att, tapepos_t *read)
17715 {
17716 	int rval;
17717 	read_pos_data_t *readp_datap;
17718 
17719 	ST_FUNC(ST_DEVINFO, st_compare_expected_position);
17720 
17721 	ASSERT(un != NULL);
17722 	ASSERT(ei != NULL);
17723 	ASSERT(read != NULL);
17724 	ASSERT(cmd_att->chg_tape_pos);
17725 
17726 	COPY_POS(read, &ei->ei_expected_pos);
17727 
17728 	readp_datap = kmem_zalloc(sizeof (read_pos_data_t), KM_SLEEP);
17729 
17730 	rval = st_recovery_get_position(un, read, readp_datap);
17731 
17732 	kmem_free(readp_datap, sizeof (read_pos_data_t));
17733 
17734 	if (rval != 0) {
17735 		return (EIO);
17736 	}
17737 
17738 	ST_POS(ST_DEVINFO, "st_compare_expected_position", read);
17739 
17740 	if ((read->pmode == invalid) ||
17741 	    (ei->ei_expected_pos.pmode == invalid)) {
17742 		return (EIO);
17743 	}
17744 
17745 	/*
17746 	 * Command that changes tape position and have an expected position
17747 	 * if it were to chave completed sucessfully.
17748 	 */
17749 	if (cmd_att->recov_pos_type == POS_EXPECTED) {
17750 		uint32_t count;
17751 		int64_t difference;
17752 		uchar_t reposition = 0;
17753 
17754 		ASSERT(cmd_att->get_cnt);
17755 		count = cmd_att->get_cnt(ei->ei_failed_pkt.pkt_cdbp);
17756 
17757 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17758 		    "Got count from CDB and it was %d\n", count);
17759 
17760 		/*
17761 		 * At expected?
17762 		 */
17763 		if (read->lgclblkno == ei->ei_expected_pos.lgclblkno) {
17764 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17765 			    "Found drive to be at expected position\n");
17766 
17767 			/*
17768 			 * If the command should move tape and it got a busy
17769 			 * it shouldn't be in the expected position.
17770 			 */
17771 			if (ei->ei_failing_status.sts_status.sts_busy != 0) {
17772 				reposition = 1;
17773 
17774 			/*
17775 			 * If the command doesn't transfer data should be good.
17776 			 */
17777 			} else if (cmd_att->transfers_data == TRAN_NONE) {
17778 				return (0); /* Good */
17779 
17780 			/*
17781 			 * Command transfers data, should have done so.
17782 			 */
17783 			} else if (ei->ei_failed_pkt.pkt_state &
17784 			    STATE_XFERRED_DATA) {
17785 				return (0); /* Good */
17786 			} else {
17787 				reposition = 1;
17788 			}
17789 		}
17790 
17791 		if (cmd_att->chg_tape_direction == DIR_FORW) {
17792 			difference =
17793 			    ei->ei_expected_pos.lgclblkno - read->lgclblkno;
17794 
17795 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17796 			    "difference between expected and actual is %"
17797 			    PRId64"\n", difference);
17798 			if (count == difference && reposition == 0) {
17799 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17800 				    "Found failed FORW command, retrying\n");
17801 				return (EAGAIN);
17802 			}
17803 
17804 			/*
17805 			 * If rewound or somewhere between the starting position
17806 			 * and the expected position (partial read or write).
17807 			 * Locate to the starting position and try the whole
17808 			 * thing over again.
17809 			 */
17810 			if ((read->lgclblkno == 0) ||
17811 			    ((difference > 0) && (difference < count))) {
17812 				rval = st_logical_block_locate(un,
17813 				    st_uscsi_rcmd, read,
17814 				    ei->ei_expected_pos.lgclblkno - count,
17815 				    ei->ei_expected_pos.partition);
17816 				if (rval == 0) {
17817 					ST_RECOV(ST_DEVINFO, st_label,
17818 					    CE_NOTE, "reestablished FORW"
17819 					    " command retrying\n");
17820 					return (EAGAIN);
17821 				}
17822 			/*
17823 			 * This handles flushed read ahead on the drive or
17824 			 * an aborted read that presents as a busy and advanced
17825 			 * the tape position.
17826 			 */
17827 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17828 			    ((difference < 0) || (reposition == 1))) {
17829 				rval = st_logical_block_locate(un,
17830 				    st_uscsi_rcmd, read,
17831 				    ei->ei_expected_pos.lgclblkno - count,
17832 				    ei->ei_expected_pos.partition);
17833 				if (rval == 0) {
17834 					ST_RECOV(ST_DEVINFO, st_label,
17835 					    CE_NOTE, "reestablished FORW"
17836 					    " read command retrying\n");
17837 					return (EAGAIN);
17838 				}
17839 			/*
17840 			 * XXX swag seeing difference of 2 on write filemark.
17841 			 * If the space to the starting position works on a
17842 			 * write that means the previous write made it to tape.
17843 			 * If not we lost data and have to give up.
17844 			 *
17845 			 * The plot thickens. Now I am attempting to cover a
17846 			 * count of 1 and a differance of 2 on a write.
17847 			 */
17848 			} else if ((difference > count) || (reposition == 1)) {
17849 				rval = st_logical_block_locate(un,
17850 				    st_uscsi_rcmd, read,
17851 				    ei->ei_expected_pos.lgclblkno - count,
17852 				    ei->ei_expected_pos.partition);
17853 				if (rval == 0) {
17854 					ST_RECOV(ST_DEVINFO, st_label,
17855 					    CE_NOTE, "reestablished FORW"
17856 					    " write command retrying\n");
17857 					return (EAGAIN);
17858 				}
17859 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17860 				    "Seek to block %"PRId64" returned %d\n",
17861 				    ei->ei_expected_pos.lgclblkno - count,
17862 				    rval);
17863 			} else {
17864 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17865 				    "Not expected transfers_data = %d "
17866 				    "difference = %"PRId64,
17867 				    cmd_att->transfers_data, difference);
17868 			}
17869 
17870 			return (EIO);
17871 
17872 		} else if (cmd_att->chg_tape_direction == DIR_REVC) {
17873 			/* Don't think we can write backwards */
17874 			ASSERT(cmd_att->transfers_data != TRAN_WRTE);
17875 			difference =
17876 			    read->lgclblkno - ei->ei_expected_pos.lgclblkno;
17877 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17878 			    "difference between expected and actual is %"
17879 			    PRId64"\n", difference);
17880 			if (count == difference && reposition == 0) {
17881 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17882 				    "Found failed REVC command, retrying\n");
17883 				return (EAGAIN);
17884 			}
17885 			if ((read->lgclblkno == 0) ||
17886 			    ((difference > 0) && (difference < count))) {
17887 				rval = st_logical_block_locate(un,
17888 				    st_uscsi_rcmd, read,
17889 				    ei->ei_expected_pos.lgclblkno + count,
17890 				    ei->ei_expected_pos.partition);
17891 				if (rval == 0) {
17892 					ST_RECOV(ST_DEVINFO, st_label,
17893 					    CE_NOTE, "reestablished REVC"
17894 					    " command retrying\n");
17895 					return (EAGAIN);
17896 				}
17897 			/* This handles read ahead in reverse direction */
17898 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17899 			    (difference < 0) || (reposition == 1)) {
17900 				rval = st_logical_block_locate(un,
17901 				    st_uscsi_rcmd, read,
17902 				    ei->ei_expected_pos.lgclblkno - count,
17903 				    ei->ei_expected_pos.partition);
17904 				if (rval == 0) {
17905 					ST_RECOV(ST_DEVINFO, st_label,
17906 					    CE_NOTE, "reestablished REVC"
17907 					    " read command retrying\n");
17908 					return (EAGAIN);
17909 				}
17910 			} else {
17911 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17912 				    "Not expected transfers_data = %d "
17913 				    "difference = %"PRId64,
17914 				    cmd_att->transfers_data, difference);
17915 			}
17916 			return (EIO);
17917 
17918 		} else {
17919 			/*
17920 			 * Commands that change tape position either
17921 			 * direction or don't change position should not
17922 			 * get here.
17923 			 */
17924 			ASSERT(0);
17925 		}
17926 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17927 		    "Didn't find a recoverable position, Failing\n");
17928 
17929 	/*
17930 	 * Command that changes tape position and can only be recovered
17931 	 * by going back to the point of origin and retrying.
17932 	 *
17933 	 * Example SCMD_SPACE.
17934 	 */
17935 	} else if (cmd_att->recov_pos_type == POS_STARTING) {
17936 		/*
17937 		 * This type of command stores the starting position.
17938 		 * If the read position is the starting position,
17939 		 * reissue the command.
17940 		 */
17941 		if (ei->ei_expected_pos.lgclblkno == read->lgclblkno) {
17942 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17943 			    "Found Space command at starting position, "
17944 			    "Reissuing\n");
17945 			return (EAGAIN);
17946 		}
17947 		/*
17948 		 * Not in the position that the command was originally issued,
17949 		 * Attempt to locate to that position.
17950 		 */
17951 		rval = st_logical_block_locate(un, st_uscsi_rcmd, read,
17952 		    ei->ei_expected_pos.lgclblkno,
17953 		    ei->ei_expected_pos.partition);
17954 		if (rval) {
17955 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17956 			    "Found Space at an unexpected position and locate "
17957 			    "back to starting position failed\n");
17958 			return (EIO);
17959 		}
17960 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17961 		    "Found Space at an unexpected position and locate "
17962 		    "back to starting position worked, Reissuing\n");
17963 		return (EAGAIN);
17964 	}
17965 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17966 	    "Unhandled attribute/expected position", &ei->ei_expected_pos);
17967 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17968 	    "Read position above did not make sense", read);
17969 	ASSERT(0);
17970 	return (EIO);
17971 }
17972 
17973 static errstate
17974 st_recover_reissue_pkt(struct scsi_tape *un, struct scsi_pkt *oldpkt)
17975 {
17976 	buf_t *bp;
17977 	buf_t *pkt_bp;
17978 	struct scsi_pkt *newpkt;
17979 	cmd_attribute const *attrib;
17980 	recov_info *rcv = oldpkt->pkt_private;
17981 	uint_t cdblen;
17982 	int queued = 0;
17983 	int rval;
17984 	int flags = 0;
17985 	int stat_size =
17986 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
17987 
17988 	ST_FUNC(ST_DEVINFO, st_recover_reissue_pkt);
17989 
17990 	bp = rcv->cmd_bp;
17991 
17992 	if (rcv->privatelen == sizeof (recov_info)) {
17993 		attrib = rcv->cmd_attrib;
17994 	} else {
17995 		attrib = st_lookup_cmd_attribute(oldpkt->pkt_cdbp[0]);
17996 	}
17997 
17998 	/*
17999 	 * Some non-uscsi commands use the b_bcount for values that
18000 	 * have nothing to do with how much data is transfered.
18001 	 * In those cases we need to hide the buf_t from scsi_init_pkt().
18002 	 */
18003 	if ((BP_UCMD(bp)) && (bp->b_bcount)) {
18004 		pkt_bp = bp;
18005 	} else if (attrib->transfers_data == TRAN_NONE) {
18006 		pkt_bp = NULL;
18007 	} else {
18008 		pkt_bp = bp;
18009 	}
18010 
18011 	/*
18012 	 * if this is a queued command make sure it the only one in the
18013 	 * run queue.
18014 	 */
18015 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
18016 		ASSERT(un->un_runqf == un->un_runql);
18017 		ASSERT(un->un_runqf == bp);
18018 		queued = 1;
18019 	}
18020 
18021 	cdblen = scsi_cdb_size[CDB_GROUPID(oldpkt->pkt_cdbp[0])];
18022 
18023 	if (pkt_bp == un->un_rqs_bp) {
18024 		flags |= PKT_CONSISTENT;
18025 		stat_size = 1;
18026 	}
18027 
18028 	newpkt = scsi_init_pkt(ROUTE, NULL, pkt_bp, cdblen,
18029 	    stat_size, rcv->privatelen, flags, NULL_FUNC, NULL);
18030 	if (newpkt == NULL) {
18031 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
18032 		    "Reissue pkt scsi_init_pkt() failure\n");
18033 		return (COMMAND_DONE_ERROR);
18034 	}
18035 
18036 	ASSERT(newpkt->pkt_resid == 0);
18037 	bp->b_flags &= ~(B_DONE);
18038 	bp->b_resid = 0;
18039 	st_bioerror(bp, 0);
18040 
18041 	bcopy(oldpkt->pkt_private, newpkt->pkt_private, rcv->privatelen);
18042 
18043 	newpkt->pkt_comp = oldpkt->pkt_comp;
18044 	newpkt->pkt_time = oldpkt->pkt_time;
18045 
18046 	bzero(newpkt->pkt_scbp, stat_size);
18047 	bcopy(oldpkt->pkt_cdbp, newpkt->pkt_cdbp, cdblen);
18048 
18049 	newpkt->pkt_state = 0;
18050 	newpkt->pkt_statistics = 0;
18051 
18052 	/*
18053 	 * oldpkt passed in was a copy of the original.
18054 	 * to distroy we need the address of the original.
18055 	 */
18056 	oldpkt = BP_PKT(bp);
18057 
18058 	if (oldpkt == un->un_rqs) {
18059 		ASSERT(bp == un->un_rqs_bp);
18060 		un->un_rqs = newpkt;
18061 	}
18062 
18063 	SET_BP_PKT(bp, newpkt);
18064 
18065 	scsi_destroy_pkt(oldpkt);
18066 
18067 	rval = st_transport(un, newpkt);
18068 	if (rval == TRAN_ACCEPT) {
18069 		return (JUST_RETURN);
18070 	}
18071 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
18072 	    "Reissue pkt st_transport(0x%x) failure\n", rval);
18073 	if (rval != TRAN_BUSY) {
18074 		return (COMMAND_DONE_ERROR);
18075 	}
18076 	mutex_exit(ST_MUTEX);
18077 	rval = st_handle_start_busy(un, bp, ST_TRAN_BUSY_TIMEOUT, queued);
18078 	mutex_enter(ST_MUTEX);
18079 	if (rval) {
18080 		return (COMMAND_DONE_ERROR);
18081 	}
18082 
18083 	return (JUST_RETURN);
18084 }
18085 
18086 static int
18087 st_transport(struct scsi_tape *un, struct scsi_pkt *pkt)
18088 {
18089 	int status;
18090 
18091 	ST_FUNC(ST_DEVINFO, st_transport);
18092 
18093 	ST_CDB(ST_DEVINFO, "transport CDB", (caddr_t)pkt->pkt_cdbp);
18094 
18095 	mutex_exit(ST_MUTEX);
18096 
18097 	status = scsi_transport(pkt);
18098 
18099 	mutex_enter(ST_MUTEX);
18100 
18101 	return (status);
18102 }
18103 
18104 /*
18105  * Removed the buf_t bp from the queue referenced to by head and tail.
18106  * Returns the buf_t pointer if it is found in the queue.
18107  * Returns NULL if it is not found.
18108  */
18109 static buf_t *
18110 st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp)
18111 {
18112 	buf_t *runqbp;
18113 	buf_t *prevbp = NULL;
18114 
18115 	for (runqbp = *head; runqbp != 0; runqbp = runqbp->av_forw) {
18116 		if (runqbp == bp) {
18117 			/* found it, is it at the head? */
18118 			if (runqbp == *head) {
18119 				*head = bp->av_forw;
18120 			} else {
18121 				prevbp->av_forw = bp->av_forw;
18122 			}
18123 			if (*tail == bp) {
18124 				*tail = prevbp;
18125 			}
18126 			bp->av_forw = NULL;
18127 			return (bp); /* found and removed */
18128 		}
18129 		prevbp = runqbp;
18130 	}
18131 	return (NULL);
18132 }
18133 
18134 /*
18135  * Adds a buf_t to the queue pointed to by head and tail.
18136  * Adds it either to the head end or the tail end based on which
18137  * the passed variable end (head or tail) points at.
18138  */
18139 static void
18140 st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp)
18141 {
18142 
18143 	bp->av_forw = NULL;
18144 	if (*head) {
18145 		/* Queue is not empty */
18146 		if (end == *head) {
18147 			/* Add at front of queue */
18148 			bp->av_forw = *head;
18149 			*head = bp;
18150 		} else if (end == *tail) {
18151 			/* Add at end of queue */
18152 			(*tail)->av_forw = bp;
18153 			*tail = bp;
18154 		} else {
18155 			ASSERT(0);
18156 		}
18157 	} else {
18158 		/* Queue is empty */
18159 		*head = bp;
18160 		*tail = bp;
18161 	}
18162 }
18163 
18164 
18165 static uint64_t
18166 st_get_cdb_g0_rw_count(uchar_t *cdb)
18167 {
18168 	uint64_t count;
18169 
18170 	if ((cdb[1]) & 1) {
18171 		/* fixed block mode, the count is the number of blocks */
18172 		count =
18173 		    cdb[2] << 16 |
18174 		    cdb[3] << 8 |
18175 		    cdb[4];
18176 	} else {
18177 		/* variable block mode, the count is the block size */
18178 		count = 1;
18179 	}
18180 	return (count);
18181 }
18182 
18183 static uint64_t
18184 st_get_cdb_g0_sign_count(uchar_t *cdb)
18185 {
18186 	uint64_t count;
18187 
18188 	count =
18189 	    cdb[2] << 16 |
18190 	    cdb[3] << 8 |
18191 	    cdb[4];
18192 	/*
18193 	 * If the sign bit of the 3 byte value is set, extended it.
18194 	 */
18195 	if (count & 0x800000) {
18196 		count |= 0xffffffffff000000;
18197 	}
18198 	return (count);
18199 }
18200 
18201 static uint64_t
18202 st_get_cdb_g0_count(uchar_t *cdb)
18203 {
18204 	uint64_t count;
18205 
18206 	count =
18207 	    cdb[2] << 16 |
18208 	    cdb[3] << 8 |
18209 	    cdb[4];
18210 	return (count);
18211 }
18212 
18213 static uint64_t
18214 st_get_cdb_g5_rw_cnt(uchar_t *cdb)
18215 {
18216 	uint64_t count;
18217 
18218 	if ((cdb[1]) & 1) {
18219 		/* fixed block mode */
18220 		count =
18221 		    cdb[12] << 16 |
18222 		    cdb[13] << 8 |
18223 		    cdb[14];
18224 	} else {
18225 		/* variable block mode */
18226 		count = 1;
18227 	}
18228 	return (count);
18229 }
18230 
18231 static uint64_t
18232 st_get_no_count(uchar_t *cdb)
18233 {
18234 	ASSERT(cdb[0] == SCMD_REWIND);
18235 	return ((uint64_t)cdb[0]);
18236 }
18237 
18238 static uint64_t
18239 st_get_load_options(uchar_t *cdb)
18240 {
18241 	return ((uint64_t)(cdb[4] | (LD_HOLD << 1)));
18242 }
18243 
18244 static uint64_t
18245 st_get_erase_options(uchar_t *cdb)
18246 {
18247 	return (cdb[1] | (cdb[0] << 8));
18248 }
18249 
18250 static uint64_t
18251 st_get_cdb_g1_lba(uchar_t *cdb)
18252 {
18253 	uint64_t lba;
18254 
18255 	lba =
18256 	    cdb[3] << 24 |
18257 	    cdb[4] << 16 |
18258 	    cdb[5] << 8 |
18259 	    cdb[6];
18260 	return (lba);
18261 }
18262 
18263 static uint64_t
18264 st_get_cdb_g5_count(uchar_t *cdb)
18265 {
18266 	uint64_t count =
18267 	    cdb[12] << 16 |
18268 	    cdb[13] << 8 |
18269 	    cdb[14];
18270 
18271 	return (count);
18272 }
18273 
18274 static uint64_t
18275 st_get_cdb_g4g5_cnt(uchar_t *cdb)
18276 {
18277 	uint64_t lba;
18278 
18279 	lba =
18280 	    (uint64_t)cdb[4] << 56 |
18281 	    (uint64_t)cdb[5] << 48 |
18282 	    (uint64_t)cdb[6] << 40 |
18283 	    (uint64_t)cdb[7] << 32 |
18284 	    (uint64_t)cdb[8] << 24 |
18285 	    (uint64_t)cdb[9] << 16 |
18286 	    (uint64_t)cdb[10] << 8 |
18287 	    (uint64_t)cdb[11];
18288 	return (lba);
18289 }
18290 
18291 static const cmd_attribute cmd_attributes[] = {
18292 	{ SCMD_READ,
18293 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_READ, POS_EXPECTED,
18294 	    0, 0, 0, st_get_cdb_g0_rw_count },
18295 	{ SCMD_WRITE,
18296 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18297 	    0, 0, 0, st_get_cdb_g0_rw_count },
18298 	{ SCMD_TEST_UNIT_READY,
18299 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18300 	    0, 0, 0 },
18301 	{ SCMD_REWIND,
18302 	    1, 1, 1, 0, 0, DIR_REVC, TRAN_NONE, POS_EXPECTED,
18303 	    0, 0, 0, st_get_no_count },
18304 	{ SCMD_REQUEST_SENSE,
18305 	    0, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18306 	    0, 0, 0 },
18307 	{ SCMD_READ_BLKLIM,
18308 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18309 	    0, 0, 0 },
18310 	{ SCMD_READ_G4,
18311 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_READ, POS_EXPECTED,
18312 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18313 	{ SCMD_WRITE_G4,
18314 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18315 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18316 	{ SCMD_READ_REVERSE,
18317 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18318 	    0, 0, 0, st_get_cdb_g0_rw_count },
18319 	{ SCMD_READ_REVERSE_G4,
18320 	    1, 0, 1, 1, 1, DIR_REVC, TRAN_READ, POS_EXPECTED,
18321 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18322 	{ SCMD_WRITE_FILE_MARK,
18323 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18324 	    0, 0, 0, st_get_cdb_g0_count },
18325 	{ SCMD_WRITE_FILE_MARK_G4,
18326 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18327 	    0, 0, 0, st_get_cdb_g5_count, st_get_cdb_g4g5_cnt },
18328 	{ SCMD_SPACE,
18329 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18330 	    0, 0, 0, st_get_cdb_g0_sign_count },
18331 	{ SCMD_SPACE_G4,
18332 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18333 	    0, 0, 0, st_get_cdb_g4g5_cnt },
18334 	{ SCMD_INQUIRY,
18335 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18336 	    0, 0, 0 },
18337 	{ SCMD_VERIFY_G0,
18338 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18339 	    0, 0, 0, st_get_cdb_g0_rw_count },
18340 	{ SCMD_VERIFY_G4,
18341 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18342 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18343 	{ SCMD_RECOVER_BUF,
18344 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18345 	    0, 0, 0 },
18346 	{ SCMD_MODE_SELECT,
18347 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18348 	    0, 0, 0 },
18349 	{ SCMD_RESERVE,
18350 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18351 	    0, 0, 0 },
18352 	{ SCMD_RELEASE,
18353 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18354 	    0, 0, 0 },
18355 	{ SCMD_ERASE,
18356 	    1, 0, 1, 1, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18357 	    0, 0, 0, st_get_erase_options },
18358 	{ SCMD_MODE_SENSE,
18359 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18360 	    0, 0, 0 },
18361 	{ SCMD_LOAD,
18362 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18363 	    0, 0, 0, st_get_load_options },
18364 	{ SCMD_GDIAG,
18365 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18366 	    1, 0, 0 },
18367 	{ SCMD_SDIAG,
18368 	    1, 0, 1, 1, 0, DIR_EITH, TRAN_WRTE, POS_EXPECTED,
18369 	    1, 0, 0 },
18370 	{ SCMD_DOORLOCK,
18371 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18372 	    0, 4, 3 },
18373 	{ SCMD_LOCATE,
18374 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18375 	    0, 0, 0, NULL, st_get_cdb_g1_lba },
18376 	{ SCMD_READ_POSITION,
18377 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18378 	    0, 0, 0 },
18379 	{ SCMD_WRITE_BUFFER,
18380 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18381 	    1, 0, 0 },
18382 	{ SCMD_READ_BUFFER,
18383 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18384 	    1, 0, 0 },
18385 	{ SCMD_REPORT_DENSITIES,
18386 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18387 	    0, 0, 0 },
18388 	{ SCMD_LOG_SELECT_G1,
18389 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18390 	    0, 0, 0 },
18391 	{ SCMD_LOG_SENSE_G1,
18392 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18393 	    0, 0, 0 },
18394 	{ SCMD_PRIN,
18395 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18396 	    0, 0, 0 },
18397 	{ SCMD_PROUT,
18398 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18399 	    0, 0, 0 },
18400 	{ SCMD_READ_ATTRIBUTE,
18401 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18402 	    0, 0, 0 },
18403 	{ SCMD_WRITE_ATTRIBUTE,
18404 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18405 	    0, 0, 0 },
18406 	{ SCMD_LOCATE_G4,
18407 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18408 	    0, 0, 0, NULL, st_get_cdb_g4g5_cnt },
18409 	{ SCMD_REPORT_LUNS,
18410 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18411 	    0, 0, 0 },
18412 	{ SCMD_SVC_ACTION_IN_G5,
18413 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18414 	    0, 0, 0 },
18415 	{ SCMD_MAINTENANCE_IN,
18416 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18417 	    0, 0, 0 },
18418 	{ SCMD_MAINTENANCE_OUT,
18419 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18420 	    0, 0, 0 },
18421 	{ 0xff, /* Default attribute for unsupported commands */
18422 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_STARTING,
18423 	    1, 0, 0, NULL, NULL }
18424 };
18425 
18426 static const cmd_attribute *
18427 st_lookup_cmd_attribute(unsigned char cmd)
18428 {
18429 	int i;
18430 	cmd_attribute const *attribute;
18431 
18432 	for (i = 0; i < ST_NUM_MEMBERS(cmd_attributes); i++) {
18433 		attribute = &cmd_attributes[i];
18434 		if (attribute->cmd == cmd) {
18435 			return (attribute);
18436 		}
18437 	}
18438 	ASSERT(attribute);
18439 	return (attribute);
18440 }
18441 
18442 static int
18443 st_reset(struct scsi_tape *un, int reset_type)
18444 {
18445 	int rval;
18446 
18447 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
18448 
18449 	ST_FUNC(ST_DEVINFO, st_reset);
18450 	un->un_rsvd_status |= ST_INITIATED_RESET;
18451 	mutex_exit(ST_MUTEX);
18452 	do {
18453 		rval = scsi_reset(&un->un_sd->sd_address, reset_type);
18454 		if (rval == 0) {
18455 			switch (reset_type) {
18456 			case RESET_LUN:
18457 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18458 				    "LUN reset failed trying target reset");
18459 				reset_type = RESET_TARGET;
18460 				break;
18461 			case RESET_TARGET:
18462 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18463 				    "target reset failed trying bus reset");
18464 				reset_type = RESET_BUS;
18465 				break;
18466 			case RESET_BUS:
18467 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18468 				    "bus reset failed trying all reset");
18469 				reset_type = RESET_ALL;
18470 			default:
18471 				mutex_enter(ST_MUTEX);
18472 				return (rval);
18473 			}
18474 		}
18475 	} while (rval == 0);
18476 	mutex_enter(ST_MUTEX);
18477 	return (rval);
18478 }
18479 
18480 #define	SAS_TLR_MOD_LEN sizeof (struct seq_mode)
18481 static int
18482 st_set_target_TLR_mode(struct scsi_tape *un, ubufunc_t ubf)
18483 {
18484 	int ret;
18485 	int amount = SAS_TLR_MOD_LEN;
18486 	struct seq_mode *mode_data;
18487 
18488 	ST_FUNC(ST_DEVINFO, st_set_target_TLR_mode);
18489 
18490 	mode_data = kmem_zalloc(SAS_TLR_MOD_LEN, KM_SLEEP);
18491 	ret = st_gen_mode_sense(un, ubf, 0x18, mode_data, amount);
18492 	if (ret != DDI_SUCCESS) {
18493 		if (ret != EACCES)
18494 			un->un_tlr_flag = TLR_NOT_SUPPORTED;
18495 		goto out;
18496 	}
18497 	if (mode_data->data_len != amount + 1) {
18498 		amount = mode_data->data_len + 1;
18499 	}
18500 	/* Must be SAS protocol */
18501 	if (mode_data->page.saslun.protocol_id != 6) {
18502 		un->un_tlr_flag = TLR_NOT_SUPPORTED;
18503 		ret = ENOTSUP;
18504 		goto out;
18505 	}
18506 	if (un->un_tlr_flag == TLR_SAS_ONE_DEVICE) {
18507 		if (mode_data->page.saslun.tran_layer_ret == 1)
18508 			goto out;
18509 		mode_data->page.saslun.tran_layer_ret = 1;
18510 	} else {
18511 		if (mode_data->page.saslun.tran_layer_ret == 0)
18512 			goto out;
18513 		mode_data->page.saslun.tran_layer_ret = 0;
18514 	}
18515 	ret = st_gen_mode_select(un, ubf, mode_data, amount);
18516 	if (ret != DDI_SUCCESS) {
18517 		if (ret != EACCES)
18518 			un->un_tlr_flag = TLR_NOT_SUPPORTED;
18519 	} else {
18520 		if (mode_data->page.saslun.tran_layer_ret == 0)
18521 			un->un_tlr_flag = TLR_NOT_KNOWN;
18522 		else
18523 			un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
18524 	}
18525 #ifdef STDEBUG
18526 	st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG, "TLR data sent",
18527 	    (char *)mode_data, amount);
18528 #endif
18529 out:
18530 	kmem_free(mode_data, SAS_TLR_MOD_LEN);
18531 	return (ret);
18532 }
18533 
18534 
18535 static void
18536 st_reset_notification(caddr_t arg)
18537 {
18538 	struct scsi_tape *un = (struct scsi_tape *)arg;
18539 
18540 	ST_FUNC(ST_DEVINFO, st_reset_notification);
18541 	mutex_enter(ST_MUTEX);
18542 
18543 	un->un_unit_attention_flags |= 2;
18544 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
18545 	    ST_RESERVE) {
18546 		un->un_rsvd_status |= ST_LOST_RESERVE;
18547 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18548 		    "Lost Reservation notification");
18549 	} else {
18550 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18551 		    "reset notification");
18552 	}
18553 
18554 	if ((un->un_restore_pos == 0) &&
18555 	    (un->un_state == ST_STATE_CLOSED) ||
18556 	    (un->un_state == ST_STATE_OPEN_PENDING_IO) ||
18557 	    (un->un_state == ST_STATE_CLOSING)) {
18558 		un->un_restore_pos = 1;
18559 	}
18560 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
18561 	    "reset and state was %d\n", un->un_state);
18562 	mutex_exit(ST_MUTEX);
18563 }
18564