xref: /titanic_50/usr/src/uts/common/io/scsi/targets/st.c (revision c9a6ea2e938727c95af7108c5e00eee4c890c7ae)
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 (c) 1990, 2010, Oracle and/or its affiliates. All rights reserved.
24  */
25 
26 /*
27  * SCSI	 SCSA-compliant and not-so-DDI-compliant Tape Driver
28  */
29 
30 #if defined(lint) && !defined(DEBUG)
31 #define	DEBUG	1
32 #endif
33 
34 #include <sys/modctl.h>
35 #include <sys/scsi/scsi.h>
36 #include <sys/mtio.h>
37 #include <sys/scsi/targets/stdef.h>
38 #include <sys/file.h>
39 #include <sys/kstat.h>
40 #include <sys/ddidmareq.h>
41 #include <sys/ddi.h>
42 #include <sys/sunddi.h>
43 #include <sys/byteorder.h>
44 
45 #define	IOSP	KSTAT_IO_PTR(un->un_stats)
46 /*
47  * stats maintained only for reads/writes as commands
48  * like rewind etc skew the wait/busy times
49  */
50 #define	IS_RW(bp) 	((bp)->b_bcount > 0)
51 #define	ST_DO_KSTATS(bp, kstat_function) \
52 	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
53 		kstat_function(IOSP); \
54 	}
55 
56 #define	ST_DO_ERRSTATS(un, x)  \
57 	if (un->un_errstats) { \
58 		struct st_errstats *stp; \
59 		stp = (struct st_errstats *)un->un_errstats->ks_data; \
60 		stp->x.value.ul++; \
61 	}
62 
63 #define	FILL_SCSI1_LUN(devp, pkt) 					\
64 	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
65 		int _lun;						\
66 		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
67 		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
68 		if (_lun > 0) {						\
69 			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
70 			    _lun;					\
71 		}							\
72 	}
73 
74 /*
75  * get an available contig mem header, cp.
76  * when big_enough is true, we will return NULL, if no big enough
77  * contig mem is found.
78  * when big_enough is false, we will try to find cp containing big
79  * enough contig mem. if not found, we will ruturn the last cp available.
80  *
81  * used by st_get_contig_mem()
82  */
83 #define	ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough) {		\
84 	struct contig_mem *tmp_cp = NULL;				\
85 	for ((cp) = (un)->un_contig_mem;				\
86 	    (cp) != NULL;						\
87 	    tmp_cp = (cp), (cp) = (cp)->cm_next) { 			\
88 		if (((cp)->cm_len >= (len)) || 				\
89 		    (!(big_enough) && ((cp)->cm_next == NULL))) { 	\
90 			if (tmp_cp == NULL) { 				\
91 				(un)->un_contig_mem = (cp)->cm_next; 	\
92 			} else { 					\
93 				tmp_cp->cm_next = (cp)->cm_next; 	\
94 			} 						\
95 			(cp)->cm_next = NULL; 				\
96 			(un)->un_contig_mem_available_num--; 		\
97 			break; 						\
98 		} 							\
99 	} 								\
100 }
101 
102 #define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
103 #define	COPY_POS(dest, source) bcopy(source, dest, sizeof (tapepos_t))
104 #define	ISALNUM(byte) \
105 	(((byte) >= 'a' && (byte) <= 'z') || \
106 	((byte) >= 'A' && (byte) <= 'Z') || \
107 	((byte) >= '0' && (byte) <= '9'))
108 
109 #define	ONE_K	1024
110 
111 #define	MAX_SPACE_CNT(cnt) if (cnt >= 0) { \
112 		if (cnt > MIN(SP_CNT_MASK, INT32_MAX)) \
113 			return (EINVAL); \
114 	} else { \
115 		if (-(cnt) > MIN(SP_CNT_MASK, INT32_MAX)) \
116 			return (EINVAL); \
117 	} \
118 
119 /*
120  * Global External Data Definitions
121  */
122 extern struct scsi_key_strings scsi_cmds[];
123 extern uchar_t	scsi_cdb_size[];
124 
125 /*
126  * Local Static Data
127  */
128 static void *st_state;
129 static char *const st_label = "st";
130 static volatile int st_recov_sz = sizeof (recov_info);
131 static const char mp_misconf[] = {
132 	"St Tape is misconfigured, MPxIO enabled and "
133 	"tape-command-recovery-disable set in st.conf\n"
134 };
135 
136 #ifdef	__x86
137 /*
138  * We need to use below DMA attr to alloc physically contiguous
139  * memory to do I/O in big block size
140  */
141 static ddi_dma_attr_t st_contig_mem_dma_attr = {
142 	DMA_ATTR_V0,    /* version number */
143 	0x0,		/* lowest usable address */
144 	0xFFFFFFFFull,  /* high DMA address range */
145 	0xFFFFFFFFull,  /* DMA counter register */
146 	1,		/* DMA address alignment */
147 	1,		/* DMA burstsizes */
148 	1,		/* min effective DMA size */
149 	0xFFFFFFFFull,  /* max DMA xfer size */
150 	0xFFFFFFFFull,  /* segment boundary */
151 	1,		/* s/g list length */
152 	1,		/* granularity of device */
153 	0		/* DMA transfer flags */
154 };
155 
156 static ddi_device_acc_attr_t st_acc_attr = {
157 	DDI_DEVICE_ATTR_V0,
158 	DDI_NEVERSWAP_ACC,
159 	DDI_STRICTORDER_ACC
160 };
161 
162 /* set limitation for the number of contig_mem */
163 static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
164 #endif
165 
166 /*
167  * Tunable parameters
168  *
169  * DISCLAIMER
170  * ----------
171  * These parameters are intended for use only in system testing; if you use
172  * them in production systems, you do so at your own risk. Altering any
173  * variable not listed below may cause unpredictable system behavior.
174  *
175  * st_check_media_time
176  *
177  *   Three second state check
178  *
179  * st_allow_large_xfer
180  *
181  *   Gated with ST_NO_RECSIZE_LIMIT
182  *
183  *   0 - Transfers larger than 64KB will not be allowed
184  *       regardless of the setting of ST_NO_RECSIZE_LIMIT
185  *   1 - Transfers larger than 64KB will be allowed
186  *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
187  *
188  * st_report_soft_errors_on_close
189  *
190  *  Gated with ST_SOFT_ERROR_REPORTING
191  *
192  *  0 - Errors will not be reported on close regardless
193  *      of the setting of ST_SOFT_ERROR_REPORTING
194  *
195  *  1 - Errors will be reported on close if
196  *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
197  */
198 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
199 static int st_retry_count	= ST_RETRY_COUNT;
200 
201 static int st_io_time		= ST_IO_TIME;
202 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
203 
204 static int st_space_time	= ST_SPACE_TIME;
205 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
206 
207 static int st_error_level	= SCSI_ERR_RETRYABLE;
208 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
209 
210 static int st_max_throttle	= ST_MAX_THROTTLE;
211 
212 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
213 
214 static int st_allow_large_xfer = 1;
215 static int st_report_soft_errors_on_close = 1;
216 
217 /*
218  * End of tunable parameters list
219  */
220 
221 
222 
223 /*
224  * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
225  *
226  * Asynchronous I/O's main offering is that it is a non-blocking way to do
227  * reads and writes.  The driver will queue up all the requests it gets and
228  * have them ready to transport to the HBA.  Unfortunately, we cannot always
229  * just ship the I/O requests to the HBA, as there errors and exceptions
230  * that may happen when we don't want the HBA to continue.  Therein comes
231  * the flush-on-errors capability.  If the HBA supports it, then st will
232  * send in st_max_throttle I/O requests at the same time.
233  *
234  * Persistent errors : This was also reasonably simple.  In the interrupt
235  * routines, if there was an error or exception (FM, LEOT, media error,
236  * transport error), the persistent error bits are set and shuts everything
237  * down, but setting the throttle to zero.  If we hit and exception in the
238  * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
239  * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
240  * the appropriate error, and this will preserve order. Of course, depending
241  * on the exception we have to show a zero read or write before we show
242  * errors back to the application.
243  */
244 
245 extern const int st_ndrivetypes;	/* defined in st_conf.c */
246 extern const struct st_drivetype st_drivetypes[];
247 extern const char st_conf_version[];
248 
249 #ifdef STDEBUG
250 static int st_soft_error_report_debug = 0;
251 volatile int st_debug = 0;
252 static volatile dev_info_t *st_lastdev;
253 static kmutex_t st_debug_mutex;
254 #endif
255 
256 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
257 
258 static const struct vid_drivetype {
259 	char	*vid;
260 	char	type;
261 } st_vid_dt[] = {
262 	{"LTO-CVE ",	MT_LTO},
263 	{"QUANTUM ",    MT_ISDLT},
264 	{"SONY    ",    MT_ISAIT},
265 	{"STK     ",	MT_ISSTK9840}
266 };
267 
268 static const struct driver_minor_data {
269 	char	*name;
270 	int	minor;
271 } st_minor_data[] = {
272 	/*
273 	 * The top 4 entries are for the default densities,
274 	 * don't alter their position.
275 	 */
276 	{"",	0},
277 	{"n",	MT_NOREWIND},
278 	{"b",	MT_BSD},
279 	{"bn",	MT_NOREWIND | MT_BSD},
280 	{"l",	MT_DENSITY1},
281 	{"m",	MT_DENSITY2},
282 	{"h",	MT_DENSITY3},
283 	{"c",	MT_DENSITY4},
284 	{"u",	MT_DENSITY4},
285 	{"ln",	MT_DENSITY1 | MT_NOREWIND},
286 	{"mn",	MT_DENSITY2 | MT_NOREWIND},
287 	{"hn",	MT_DENSITY3 | MT_NOREWIND},
288 	{"cn",	MT_DENSITY4 | MT_NOREWIND},
289 	{"un",	MT_DENSITY4 | MT_NOREWIND},
290 	{"lb",	MT_DENSITY1 | MT_BSD},
291 	{"mb",	MT_DENSITY2 | MT_BSD},
292 	{"hb",	MT_DENSITY3 | MT_BSD},
293 	{"cb",	MT_DENSITY4 | MT_BSD},
294 	{"ub",	MT_DENSITY4 | MT_BSD},
295 	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
296 	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
297 	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
298 	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
299 	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
300 };
301 
302 /* strings used in many debug and warning messages */
303 static const char wr_str[]  = "write";
304 static const char rd_str[]  = "read";
305 static const char wrg_str[] = "writing";
306 static const char rdg_str[] = "reading";
307 static const char *space_strs[] = {
308 	"records",
309 	"filemarks",
310 	"sequential filemarks",
311 	"eod",
312 	"setmarks",
313 	"sequential setmarks",
314 	"Reserved",
315 	"Reserved"
316 };
317 static const char *load_strs[] = {
318 	"unload",		/* LD_UNLOAD		0 */
319 	"load",			/* LD_LOAD		1 */
320 	"retension",		/* LD_RETEN		2 */
321 	"load reten",		/* LD_LOAD | LD_RETEN	3 */
322 	"eod",			/* LD_EOT		4 */
323 	"load EOD",		/* LD_LOAD | LD_EOT	5 */
324 	"reten EOD",		/* LD_RETEN | LD_EOT	6 */
325 	"load reten EOD"	/* LD_LOAD|LD_RETEN|LD_EOT 7 */
326 	"hold",			/* LD_HOLD		8 */
327 	"load and hold"		/* LD_LOAD | LD_HOLD	9 */
328 };
329 
330 static const char *errstatenames[] = {
331 	"COMMAND_DONE",
332 	"COMMAND_DONE_ERROR",
333 	"COMMAND_DONE_ERROR_RECOVERED",
334 	"QUE_COMMAND",
335 	"QUE_BUSY_COMMAND",
336 	"QUE_SENSE",
337 	"JUST_RETURN",
338 	"COMMAND_DONE_EACCES",
339 	"QUE_LAST_COMMAND",
340 	"COMMAND_TIMEOUT",
341 	"PATH_FAILED",
342 	"DEVICE_RESET",
343 	"DEVICE_TAMPER",
344 	"ATTEMPT_RETRY"
345 };
346 
347 const char *bogusID = "Unknown Media ID";
348 
349 /* default density offsets in the table above */
350 #define	DEF_BLANK	0
351 #define	DEF_NOREWIND	1
352 #define	DEF_BSD		2
353 #define	DEF_BSD_NR	3
354 
355 /* Sense Key, ASC/ASCQ for which tape ejection is needed */
356 
357 static struct tape_failure_code {
358 	uchar_t key;
359 	uchar_t add_code;
360 	uchar_t qual_code;
361 } st_tape_failure_code[] = {
362 	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
363 	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
364 	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
365 	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
366 	{ KEY_NOT_READY, 0x53, 0x00},
367 	{ 0xff}
368 };
369 
370 /*  clean bit position and mask */
371 
372 static struct cln_bit_position {
373 	ushort_t cln_bit_byte;
374 	uchar_t cln_bit_mask;
375 } st_cln_bit_position[] = {
376 	{ 21, 0x08},
377 	{ 70, 0xc0},
378 	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
379 };
380 
381 /*
382  * architecture dependent allocation restrictions. For x86, we'll set
383  * dma_attr_addr_hi to st_max_phys_addr and dma_attr_sgllen to
384  * st_sgl_size during _init().
385  */
386 #if defined(__sparc)
387 static ddi_dma_attr_t st_alloc_attr = {
388 	DMA_ATTR_V0,	/* version number */
389 	0x0,		/* lowest usable address */
390 	0xFFFFFFFFull,	/* high DMA address range */
391 	0xFFFFFFFFull,	/* DMA counter register */
392 	1,		/* DMA address alignment */
393 	1,		/* DMA burstsizes */
394 	1,		/* min effective DMA size */
395 	0xFFFFFFFFull,	/* max DMA xfer size */
396 	0xFFFFFFFFull,	/* segment boundary */
397 	1,		/* s/g list length */
398 	512,		/* granularity of device */
399 	0		/* DMA transfer flags */
400 };
401 #elif defined(__x86)
402 static ddi_dma_attr_t st_alloc_attr = {
403 	DMA_ATTR_V0,	/* version number */
404 	0x0,		/* lowest usable address */
405 	0x0,		/* high DMA address range [set in _init()] */
406 	0xFFFFull,	/* DMA counter register */
407 	512,		/* DMA address alignment */
408 	1,		/* DMA burstsizes */
409 	1,		/* min effective DMA size */
410 	0xFFFFFFFFull,	/* max DMA xfer size */
411 	0xFFFFFFFFull,  /* segment boundary */
412 	0,		/* s/g list length */
413 	512,		/* granularity of device [set in _init()] */
414 	0		/* DMA transfer flags */
415 };
416 uint64_t st_max_phys_addr = 0xFFFFFFFFull;
417 int st_sgl_size = 0xF;
418 
419 #endif
420 
421 /*
422  * Configuration Data:
423  *
424  * Device driver ops vector
425  */
426 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
427 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
428 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
429 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
430 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
431 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
432 static int st_strategy(struct buf *bp);
433 static int st_queued_strategy(buf_t *bp);
434 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
435 	cred_t *cred_p, int *rval_p);
436 extern int nulldev(), nodev();
437 
438 static struct cb_ops st_cb_ops = {
439 	st_open,		/* open */
440 	st_close,		/* close */
441 	st_queued_strategy,	/* strategy Not Block device but async checks */
442 	nodev,			/* print */
443 	nodev,			/* dump */
444 	st_read,		/* read */
445 	st_write,		/* write */
446 	st_ioctl,		/* ioctl */
447 	nodev,			/* devmap */
448 	nodev,			/* mmap */
449 	nodev,			/* segmap */
450 	nochpoll,		/* poll */
451 	ddi_prop_op,		/* cb_prop_op */
452 	0,			/* streamtab  */
453 	D_64BIT | D_MP | D_NEW | D_HOTPLUG |
454 	D_OPEN_RETURNS_EINTR,	/* cb_flag */
455 	CB_REV,			/* cb_rev */
456 	st_aread, 		/* async I/O read entry point */
457 	st_awrite		/* async I/O write entry point */
458 
459 };
460 
461 static int st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
462 		void **result);
463 static int st_probe(dev_info_t *dev);
464 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
465 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
466 
467 static struct dev_ops st_ops = {
468 	DEVO_REV,		/* devo_rev, */
469 	0,			/* refcnt  */
470 	st_info,		/* info */
471 	nulldev,		/* identify */
472 	st_probe,		/* probe */
473 	st_attach,		/* attach */
474 	st_detach,		/* detach */
475 	nodev,			/* reset */
476 	&st_cb_ops,		/* driver operations */
477 	(struct bus_ops *)0,	/* bus operations */
478 	nulldev,		/* power */
479 	ddi_quiesce_not_needed,	/* devo_quiesce */
480 };
481 
482 /*
483  * Local Function Declarations
484  */
485 static char *st_print_scsi_cmd(char cmd);
486 static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
487     char *title, char *cdb);
488 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
489     char *title, char *data, int len);
490 static int st_doattach(struct scsi_device *devp, int (*canwait)());
491 static void st_known_tape_type(struct scsi_tape *un);
492 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
493     struct st_drivetype *);
494 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
495     struct st_drivetype *);
496 static int st_get_conf_from_tape_drive(struct scsi_tape *, char *,
497     struct st_drivetype *);
498 static int st_get_densities_from_tape_drive(struct scsi_tape *,
499     struct st_drivetype *);
500 static int st_get_timeout_values_from_tape_drive(struct scsi_tape *,
501     struct st_drivetype *);
502 static int st_get_timeouts_value(struct scsi_tape *, uchar_t, ushort_t *,
503     ushort_t);
504 static int st_get_default_conf(struct scsi_tape *, char *,
505     struct st_drivetype *);
506 static int st_rw(dev_t dev, struct uio *uio, int flag);
507 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
508 static int st_find_eod(struct scsi_tape *un);
509 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
510 static int st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *, int flag);
511 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
512 static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
513 static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
514 static void st_start(struct scsi_tape *un);
515 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
516     clock_t timeout_interval, int queued);
517 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
518     clock_t timeout_interval);
519 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
520 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
521 static void st_init(struct scsi_tape *un);
522 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
523     int (*func)(caddr_t));
524 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
525     struct buf *bp, int (*func)(caddr_t));
526 static void st_intr(struct scsi_pkt *pkt);
527 static void st_set_state(struct scsi_tape *un, buf_t *bp);
528 static void st_test_append(struct buf *bp);
529 static int st_runout(caddr_t);
530 static int st_cmd(struct scsi_tape *un, int com, int64_t count, int wait);
531 static int st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com,
532     int64_t count);
533 static int st_set_compression(struct scsi_tape *un);
534 static int st_write_fm(dev_t dev, int wfm);
535 static int st_determine_generic(struct scsi_tape *un);
536 static int st_determine_density(struct scsi_tape *un, int rw);
537 static int st_get_density(struct scsi_tape *un);
538 static int st_set_density(struct scsi_tape *un);
539 static int st_loadtape(struct scsi_tape *un);
540 static int st_modesense(struct scsi_tape *un);
541 static int st_modeselect(struct scsi_tape *un);
542 static errstate st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
543 static int st_wrongtapetype(struct scsi_tape *un);
544 static errstate st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
545 static errstate st_handle_sense(struct scsi_tape *un, struct buf *bp,
546     tapepos_t *);
547 static errstate st_handle_autosense(struct scsi_tape *un, struct buf *bp,
548     tapepos_t *);
549 static int st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag);
550 static void st_update_error_stack(struct scsi_tape *un, struct scsi_pkt *pkt,
551     struct scsi_arq_status *cmd);
552 static void st_empty_error_stack(struct scsi_tape *un);
553 static errstate st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
554     struct scsi_arq_status *, tapepos_t *);
555 static int st_report_soft_errors(dev_t dev, int flag);
556 static void st_delayed_cv_broadcast(void *arg);
557 static int st_check_media(dev_t dev, enum mtio_state state);
558 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
559 static void st_intr_restart(void *arg);
560 static void st_start_restart(void *arg);
561 static int st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
562     struct seq_mode *page_data, int page_size);
563 static int st_change_block_size(struct scsi_tape *un, uint32_t nblksz);
564 static int st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
565     struct seq_mode *page_data, int page_size);
566 static int st_read_block_limits(struct scsi_tape *un,
567     struct read_blklim *read_blk);
568 static int st_report_density_support(struct scsi_tape *un,
569     uchar_t *density_data, size_t buflen);
570 static int st_report_supported_operation(struct scsi_tape *un,
571     uchar_t *oper_data, uchar_t option_code, ushort_t service_action);
572 static int st_tape_init(struct scsi_tape *un);
573 static void st_flush(struct scsi_tape *un);
574 static void st_set_pe_errno(struct scsi_tape *un);
575 static void st_hba_unflush(struct scsi_tape *un);
576 static void st_turn_pe_on(struct scsi_tape *un);
577 static void st_turn_pe_off(struct scsi_tape *un);
578 static void st_set_pe_flag(struct scsi_tape *un);
579 static void st_clear_pe(struct scsi_tape *un);
580 static void st_wait_for_io(struct scsi_tape *un);
581 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
582 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
583 static int st_reserve_release(struct scsi_tape *un, int command, ubufunc_t ubf);
584 static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb);
585 static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
586     int count);
587 static int st_take_ownership(struct scsi_tape *un, ubufunc_t ubf);
588 static int st_check_asc_ascq(struct scsi_tape *un);
589 static int st_check_clean_bit(struct scsi_tape *un);
590 static int st_check_alert_flags(struct scsi_tape *un);
591 static int st_check_sequential_clean_bit(struct scsi_tape *un);
592 static int st_check_sense_clean_bit(struct scsi_tape *un);
593 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
594 static void st_calculate_timeouts(struct scsi_tape *un);
595 static writablity st_is_drive_worm(struct scsi_tape *un);
596 static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
597     void *buf, size_t size, ubufunc_t bufunc);
598 static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
599     caddr_t dest, uchar_t page);
600 static int st_update_block_pos(struct scsi_tape *un, bufunc_t bf,
601     int post_space);
602 static int st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
603     read_p_types type, size_t data_sz, const caddr_t responce, int post_space);
604 static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
605 static int st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf,
606     tapepos_t *pos, uint64_t lblk, uchar_t partition);
607 static int st_mtfsf_ioctl(struct scsi_tape *un, int64_t files);
608 static int st_mtfsr_ioctl(struct scsi_tape *un, int64_t count);
609 static int st_mtbsf_ioctl(struct scsi_tape *un, int64_t files);
610 static int st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count);
611 static int st_mtbsr_ioctl(struct scsi_tape *un, int64_t num);
612 static int st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt);
613 static int st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt);
614 static int st_backward_space_files(struct scsi_tape *un, int64_t count,
615     int infront);
616 static int st_forward_space_files(struct scsi_tape *un, int64_t files);
617 static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
618     int32_t fileno);
619 static int st_space_to_begining_of_file(struct scsi_tape *un);
620 static int st_space_records(struct scsi_tape *un, int64_t records);
621 static int st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc);
622 static errstate st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
623     errstate onentry);
624 static void st_recover(void *arg);
625 static void st_recov_cb(struct scsi_pkt *pkt);
626 static int st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait);
627 static int st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
628     int flag);
629 static void st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
630     struct scsi_pkt *cmd);
631 static int st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf);
632 static int st_test_path_to_device(struct scsi_tape *un);
633 static int st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
634     read_pos_data_t *raw);
635 static int st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
636     read_pos_data_t *raw);
637 static int st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
638     cmd_attribute const * cmd_att, tapepos_t *read);
639 static errstate st_recover_reissue_pkt(struct scsi_tape *us,
640     struct scsi_pkt *pkt);
641 static int st_transport(struct scsi_tape *un, struct scsi_pkt *pkt);
642 static buf_t *st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp);
643 static void st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp);
644 static int st_reset(struct scsi_tape *un, int reset_type);
645 static void st_reset_notification(caddr_t arg);
646 static const cmd_attribute *st_lookup_cmd_attribute(unsigned char cmd);
647 
648 static int st_set_target_TLR_mode(struct scsi_tape *un, ubufunc_t ubf);
649 static int st_make_sure_mode_data_is_correct(struct scsi_tape *un,
650     ubufunc_t ubf);
651 
652 #ifdef	__x86
653 /*
654  * routines for I/O in big block size
655  */
656 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
657 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
658     int alloc_flags);
659 static int st_bigblk_xfer_done(struct buf *bp);
660 static struct buf *st_get_bigblk_bp(struct buf *bp);
661 #endif
662 static void st_print_position(dev_info_t *dev, char *label, uint_t level,
663     const char *comment, tapepos_t *pos);
664 
665 /*
666  * error statistics create/update functions
667  */
668 static int st_create_errstats(struct scsi_tape *, int);
669 static int st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf,
670     tapepos_t *pos);
671 
672 #ifdef STDEBUG
673 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
674 #endif /* STDEBUG */
675 static char *st_dev_name(dev_t dev);
676 
677 #if !defined(lint)
678 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
679     scsi_pkt buf uio scsi_cdb uscsi_cmd))
680 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
681 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", recov_info))
682 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
683 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
684 #endif
685 
686 /*
687  * autoconfiguration routines.
688  */
689 char _depends_on[] = "misc/scsi";
690 
691 static struct modldrv modldrv = {
692 	&mod_driverops,		/* Type of module. This one is a driver */
693 	"SCSI tape Driver", 	/* Name of the module. */
694 	&st_ops			/* driver ops */
695 };
696 
697 static struct modlinkage modlinkage = {
698 	MODREV_1, &modldrv, NULL
699 };
700 
701 /*
702  * Notes on Post Reset Behavior in the tape driver:
703  *
704  * When the tape drive is opened, the driver  attempts  to make sure that
705  * the tape head is positioned exactly where it was left when it was last
706  * closed  provided  the  medium  is not  changed.  If the tape  drive is
707  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
708  * of position due to reset) will happen when the first tape operation or
709  * I/O occurs.  The repositioning (if required) may not be possible under
710  * certain situations such as when the device firmware not able to report
711  * the medium  change in the REQUEST  SENSE data  because of a reset or a
712  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
713  * extraordinary  situations, where the driver fails to position the head
714  * at its  original  position,  it will fail the open the first  time, to
715  * save the applications from overwriting the data.  All further attempts
716  * to open the tape device will result in the driver  attempting  to load
717  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
718  * indicate  that further  attempts to open the tape device may result in
719  * the tape being  loaded at BOT will be printed on the  console.  If the
720  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
721  * original tape head  position,  will result in the failure of the first
722  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
723  * internal tape position  which will  necessitate  the  applications  to
724  * validate the position by using either a tape  positioning  ioctl (such
725  * as MTREW) or closing and reopening the tape device.
726  *
727  */
728 
729 int
730 _init(void)
731 {
732 	int e;
733 
734 	if (((e = ddi_soft_state_init(&st_state,
735 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
736 		return (e);
737 	}
738 
739 	if ((e = mod_install(&modlinkage)) != 0) {
740 		ddi_soft_state_fini(&st_state);
741 	} else {
742 #ifdef STDEBUG
743 		mutex_init(&st_debug_mutex, NULL, MUTEX_DRIVER, NULL);
744 #endif
745 
746 #if defined(__x86)
747 		/* set the max physical address for iob allocs on x86 */
748 		st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
749 
750 		/*
751 		 * set the sgllen for iob allocs on x86. If this is set less
752 		 * than the number of pages the buffer will take
753 		 * (taking into account alignment), it would force the
754 		 * allocator to try and allocate contiguous pages.
755 		 */
756 		st_alloc_attr.dma_attr_sgllen = st_sgl_size;
757 #endif
758 	}
759 
760 	return (e);
761 }
762 
763 int
764 _fini(void)
765 {
766 	int e;
767 
768 	if ((e = mod_remove(&modlinkage)) != 0) {
769 		return (e);
770 	}
771 
772 #ifdef STDEBUG
773 	mutex_destroy(&st_debug_mutex);
774 #endif
775 
776 	ddi_soft_state_fini(&st_state);
777 
778 	return (e);
779 }
780 
781 int
782 _info(struct modinfo *modinfop)
783 {
784 	return (mod_info(&modlinkage, modinfop));
785 }
786 
787 
788 static int
789 st_probe(dev_info_t *devi)
790 {
791 	int instance;
792 	struct scsi_device *devp;
793 	int rval;
794 
795 #if !defined(__sparc)
796 	char    *tape_prop;
797 	int	tape_prop_len;
798 #endif
799 
800 	ST_ENTR(devi, st_probe);
801 
802 	/* If self identifying device */
803 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
804 		return (DDI_PROBE_DONTCARE);
805 	}
806 
807 #if !defined(__sparc)
808 	/*
809 	 * Since some x86 HBAs have devnodes that look like SCSI as
810 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
811 	 * we check for the presence of the "tape" property.
812 	 */
813 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
814 	    DDI_PROP_CANSLEEP, "tape",
815 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
816 		return (DDI_PROBE_FAILURE);
817 	}
818 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
819 		kmem_free(tape_prop, tape_prop_len);
820 		return (DDI_PROBE_FAILURE);
821 	}
822 	kmem_free(tape_prop, tape_prop_len);
823 #endif
824 
825 	devp = ddi_get_driver_private(devi);
826 	instance = ddi_get_instance(devi);
827 
828 	if (ddi_get_soft_state(st_state, instance) != NULL) {
829 		return (DDI_PROBE_PARTIAL);
830 	}
831 
832 
833 	/*
834 	 * Turn around and call probe routine to see whether
835 	 * we actually have a tape at this SCSI nexus.
836 	 */
837 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
838 
839 		/*
840 		 * In checking the whole inq_dtype byte we are looking at both
841 		 * the Peripheral Qualifier and the Peripheral Device Type.
842 		 * For this driver we are only interested in sequential devices
843 		 * that are connected or capable if connecting to this logical
844 		 * unit.
845 		 */
846 		if (devp->sd_inq->inq_dtype ==
847 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
848 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
849 			    "probe exists\n");
850 			rval = DDI_PROBE_SUCCESS;
851 		} else {
852 			rval = DDI_PROBE_FAILURE;
853 		}
854 	} else {
855 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
856 		    "probe failure: nothing there\n");
857 		rval = DDI_PROBE_FAILURE;
858 	}
859 	scsi_unprobe(devp);
860 	return (rval);
861 }
862 
863 static int
864 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
865 {
866 	int 	instance;
867 	int	wide;
868 	int 	dev_instance;
869 	int	ret_status;
870 	struct	scsi_device *devp;
871 	int	node_ix;
872 	struct	scsi_tape *un;
873 
874 	ST_ENTR(devi, st_attach);
875 
876 	devp = ddi_get_driver_private(devi);
877 	instance = ddi_get_instance(devi);
878 
879 	switch (cmd) {
880 		case DDI_ATTACH:
881 			if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
882 			    "tape-command-recovery-disable", 0) != 0) {
883 				st_recov_sz = sizeof (pkt_info);
884 			}
885 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
886 				return (DDI_FAILURE);
887 			}
888 			break;
889 		case DDI_RESUME:
890 			/*
891 			 * Suspend/Resume
892 			 *
893 			 * When the driver suspended, there might be
894 			 * outstanding cmds and therefore we need to
895 			 * reset the suspended flag and resume the scsi
896 			 * watch thread and restart commands and timeouts
897 			 */
898 
899 			if (!(un = ddi_get_soft_state(st_state, instance))) {
900 				return (DDI_FAILURE);
901 			}
902 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
903 			    un->un_dev);
904 
905 			mutex_enter(ST_MUTEX);
906 
907 			un->un_throttle = un->un_max_throttle;
908 			un->un_tids_at_suspend = 0;
909 			un->un_pwr_mgmt = ST_PWR_NORMAL;
910 
911 			if (un->un_swr_token) {
912 				scsi_watch_resume(un->un_swr_token);
913 			}
914 
915 			/*
916 			 * Restart timeouts
917 			 */
918 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
919 				mutex_exit(ST_MUTEX);
920 				un->un_delay_tid = timeout(
921 				    st_delayed_cv_broadcast, un,
922 				    drv_usectohz((clock_t)
923 				    MEDIA_ACCESS_DELAY));
924 				mutex_enter(ST_MUTEX);
925 			}
926 
927 			if (un->un_tids_at_suspend & ST_HIB_TID) {
928 				mutex_exit(ST_MUTEX);
929 				un->un_hib_tid = timeout(st_intr_restart, un,
930 				    ST_STATUS_BUSY_TIMEOUT);
931 				mutex_enter(ST_MUTEX);
932 			}
933 
934 			ret_status = st_clear_unit_attentions(dev_instance, 5);
935 
936 			/*
937 			 * now check if we need to restore the tape position
938 			 */
939 			if ((un->un_suspend_pos.pmode != invalid) &&
940 			    ((un->un_suspend_pos.fileno > 0) ||
941 			    (un->un_suspend_pos.blkno > 0)) ||
942 			    (un->un_suspend_pos.lgclblkno > 0)) {
943 				if (ret_status != 0) {
944 					/*
945 					 * tape didn't get good TUR
946 					 * just print out error messages
947 					 */
948 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
949 					    "st_attach-RESUME: tape failure "
950 					    " tape position will be lost");
951 				} else {
952 					/* this prints errors */
953 					(void) st_validate_tapemarks(un,
954 					    st_uscsi_cmd, &un->un_suspend_pos);
955 				}
956 				/*
957 				 * there are no retries, if there is an error
958 				 * we don't know if the tape has changed
959 				 */
960 				un->un_suspend_pos.pmode = invalid;
961 			}
962 
963 			/* now we are ready to start up any queued I/Os */
964 			if (un->un_ncmds || un->un_quef) {
965 				st_start(un);
966 			}
967 
968 			cv_broadcast(&un->un_suspend_cv);
969 			mutex_exit(ST_MUTEX);
970 			return (DDI_SUCCESS);
971 
972 		default:
973 			return (DDI_FAILURE);
974 	}
975 
976 	un = ddi_get_soft_state(st_state, instance);
977 
978 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
979 	    "st_attach: instance=%x\n", instance);
980 
981 	/*
982 	 * Add a zero-length attribute to tell the world we support
983 	 * kernel ioctls (for layered drivers)
984 	 */
985 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
986 	    DDI_KERNEL_IOCTL, NULL, 0);
987 
988 	ddi_report_dev((dev_info_t *)devi);
989 
990 	/*
991 	 * If it's a SCSI-2 tape drive which supports wide,
992 	 * tell the host adapter to use wide.
993 	 */
994 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
995 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
996 
997 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
998 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
999 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
1000 	}
1001 
1002 	/*
1003 	 * enable autorequest sense; keep the rq packet around in case
1004 	 * the autorequest sense fails because of a busy condition
1005 	 * do a getcap first in case the capability is not variable
1006 	 */
1007 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
1008 		un->un_arq_enabled = 1;
1009 	} else {
1010 		un->un_arq_enabled =
1011 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
1012 	}
1013 
1014 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
1015 	    (un->un_arq_enabled ? "enabled" : "disabled"));
1016 
1017 	un->un_untagged_qing =
1018 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
1019 
1020 	/*
1021 	 * XXX - This is just for 2.6.  to tell users that write buffering
1022 	 *	has gone away.
1023 	 */
1024 	if (un->un_arq_enabled && un->un_untagged_qing) {
1025 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
1026 		    "tape-driver-buffering", 0) != 0) {
1027 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1028 			    "Write Data Buffering has been depricated. Your "
1029 			    "applications should continue to work normally.\n"
1030 			    " But, they should  ported to use Asynchronous "
1031 			    " I/O\n"
1032 			    " For more information, read about "
1033 			    " tape-driver-buffering "
1034 			    "property in the st(7d) man page\n");
1035 		}
1036 	}
1037 
1038 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
1039 	un->un_flush_on_errors = 0;
1040 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
1041 
1042 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
1043 	    "throttle=%x, max_throttle = %x\n",
1044 	    un->un_throttle, un->un_max_throttle);
1045 
1046 	/* initialize persistent errors to nil */
1047 	un->un_persistence = 0;
1048 	un->un_persist_errors = 0;
1049 
1050 	/*
1051 	 * Get dma-max from HBA driver. If it is not defined, use 64k
1052 	 */
1053 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
1054 	if (un->un_maxdma == -1) {
1055 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1056 		    "Received a value that looked like -1. Using 64k maxdma");
1057 		un->un_maxdma = (64 * ONE_K);
1058 	}
1059 
1060 #ifdef	__x86
1061 	/*
1062 	 * for x86, the device may be able to DMA more than the system will
1063 	 * allow under some circumstances. We need account for both the HBA's
1064 	 * and system's contraints.
1065 	 *
1066 	 * Get the maximum DMA under worse case conditions. e.g. looking at the
1067 	 * device constraints, the max copy buffer size, and the worse case
1068 	 * fragmentation. NOTE: this may differ from dma-max since dma-max
1069 	 * doesn't take the worse case framentation into account.
1070 	 *
1071 	 * e.g. a device may be able to DMA 16MBytes, but can only DMA 1MByte
1072 	 * if none of the pages are contiguous. Keeping track of both of these
1073 	 * values allows us to support larger tape block sizes on some devices.
1074 	 */
1075 	un->un_maxdma_arch = scsi_ifgetcap(&devp->sd_address, "dma-max-arch",
1076 	    1);
1077 
1078 	/*
1079 	 * If the dma-max-arch capability is not implemented, or the value
1080 	 * comes back higher than what was reported in dma-max, use dma-max.
1081 	 */
1082 	if ((un->un_maxdma_arch == -1) ||
1083 	    ((uint_t)un->un_maxdma < (uint_t)un->un_maxdma_arch)) {
1084 		un->un_maxdma_arch = un->un_maxdma;
1085 	}
1086 #endif
1087 
1088 	/*
1089 	 * Get the max allowable cdb size
1090 	 */
1091 	un->un_max_cdb_sz =
1092 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
1093 	if (un->un_max_cdb_sz < CDB_GROUP0) {
1094 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1095 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
1096 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
1097 	}
1098 
1099 	if (strcmp(ddi_driver_name(ddi_get_parent(ST_DEVINFO)), "scsi_vhci")) {
1100 		un->un_multipath = 0;
1101 	} else {
1102 		un->un_multipath = 1;
1103 	}
1104 
1105 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1106 
1107 	un->un_mediastate = MTIO_NONE;
1108 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1109 
1110 	/*
1111 	 * initialize kstats
1112 	 */
1113 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1114 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1115 	if (un->un_stats) {
1116 		un->un_stats->ks_lock = ST_MUTEX;
1117 		kstat_install(un->un_stats);
1118 	}
1119 	(void) st_create_errstats(un, instance);
1120 
1121 	/*
1122 	 * find the drive type for this target
1123 	 */
1124 	mutex_enter(ST_MUTEX);
1125 	un->un_dev = MTMINOR(instance);
1126 	st_known_tape_type(un);
1127 	un->un_dev = 0;
1128 	mutex_exit(ST_MUTEX);
1129 
1130 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
1131 		int minor;
1132 		char *name;
1133 
1134 		name  = st_minor_data[node_ix].name;
1135 		minor = st_minor_data[node_ix].minor;
1136 
1137 		/*
1138 		 * For default devices set the density to the
1139 		 * preferred default density for this device.
1140 		 */
1141 		if (node_ix <= DEF_BSD_NR) {
1142 			minor |= un->un_dp->default_density;
1143 		}
1144 		minor |= MTMINOR(instance);
1145 
1146 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
1147 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
1148 			continue;
1149 		}
1150 
1151 		ddi_remove_minor_node(devi, NULL);
1152 
1153 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1154 		    st_reset_notification, (caddr_t)un);
1155 		cv_destroy(&un->un_clscv);
1156 		cv_destroy(&un->un_sbuf_cv);
1157 		cv_destroy(&un->un_queue_cv);
1158 		cv_destroy(&un->un_state_cv);
1159 #ifdef	__x86
1160 		cv_destroy(&un->un_contig_mem_cv);
1161 #endif
1162 		cv_destroy(&un->un_suspend_cv);
1163 		cv_destroy(&un->un_tape_busy_cv);
1164 		cv_destroy(&un->un_recov_buf_cv);
1165 		if (un->un_recov_taskq) {
1166 			ddi_taskq_destroy(un->un_recov_taskq);
1167 		}
1168 		if (un->un_sbufp) {
1169 			freerbuf(un->un_sbufp);
1170 		}
1171 		if (un->un_recov_buf) {
1172 			freerbuf(un->un_recov_buf);
1173 		}
1174 		if (un->un_uscsi_rqs_buf) {
1175 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1176 		}
1177 		if (un->un_mspl) {
1178 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1179 		}
1180 		if (un->un_dp_size) {
1181 			kmem_free(un->un_dp, un->un_dp_size);
1182 		}
1183 		if (un->un_state) {
1184 			kstat_delete(un->un_stats);
1185 		}
1186 		if (un->un_errstats) {
1187 			kstat_delete(un->un_errstats);
1188 		}
1189 
1190 		scsi_destroy_pkt(un->un_rqs);
1191 		scsi_free_consistent_buf(un->un_rqs_bp);
1192 		ddi_soft_state_free(st_state, instance);
1193 		devp->sd_private = NULL;
1194 		devp->sd_sense = NULL;
1195 
1196 		ddi_prop_remove_all(devi);
1197 		return (DDI_FAILURE);
1198 	}
1199 
1200 	return (DDI_SUCCESS);
1201 }
1202 
1203 /*
1204  * st_detach:
1205  *
1206  * we allow a detach if and only if:
1207  *	- no tape is currently inserted
1208  *	- tape position is at BOT or unknown
1209  *		(if it is not at BOT then a no rewind
1210  *		device was opened and we have to preserve state)
1211  *	- it must be in a closed state : no timeouts or scsi_watch requests
1212  *		will exist if it is closed, so we don't need to check for
1213  *		them here.
1214  */
1215 /*ARGSUSED*/
1216 static int
1217 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1218 {
1219 	int instance;
1220 	int result;
1221 	struct scsi_device *devp;
1222 	struct scsi_tape *un;
1223 	clock_t wait_cmds_complete;
1224 
1225 	ST_ENTR(devi, st_detach);
1226 
1227 	instance = ddi_get_instance(devi);
1228 
1229 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1230 		return (DDI_FAILURE);
1231 	}
1232 
1233 	mutex_enter(ST_MUTEX);
1234 
1235 	/*
1236 	 * Clear error entry stack
1237 	 */
1238 	st_empty_error_stack(un);
1239 
1240 	mutex_exit(ST_MUTEX);
1241 
1242 	switch (cmd) {
1243 
1244 	case DDI_DETACH:
1245 		/*
1246 		 * Undo what we did in st_attach & st_doattach,
1247 		 * freeing resources and removing things we installed.
1248 		 * The system framework guarantees we are not active
1249 		 * with this devinfo node in any other entry points at
1250 		 * this time.
1251 		 */
1252 
1253 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1254 		    "st_detach: instance=%x, un=%p\n", instance,
1255 		    (void *)un);
1256 
1257 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1258 		    ((un->un_rsvd_status & ST_APPLICATION_RESERVATIONS) != 0) ||
1259 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1260 		    (un->un_state != ST_STATE_CLOSED)) {
1261 			/*
1262 			 * we cannot unload some targets because the
1263 			 * inquiry returns junk unless immediately
1264 			 * after a reset
1265 			 */
1266 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1267 			    "cannot unload instance %x\n", instance);
1268 			un->un_unit_attention_flags |= 4;
1269 			return (DDI_FAILURE);
1270 		}
1271 
1272 		/*
1273 		 * if the tape has been removed then we may unload;
1274 		 * do a test unit ready and if it returns NOT READY
1275 		 * then we assume that it is safe to unload.
1276 		 * as a side effect, pmode may be set to invalid if the
1277 		 * the test unit ready fails;
1278 		 * also un_state may be set to non-closed, so reset it
1279 		 */
1280 		if ((un->un_dev) &&		/* Been opened since attach */
1281 		    ((un->un_pos.pmode == legacy) &&
1282 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1283 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1284 		    ((un->un_pos.pmode == logical) &&
1285 		    (un->un_pos.lgclblkno > 0))) {
1286 			mutex_enter(ST_MUTEX);
1287 			/*
1288 			 * Send Test Unit Ready in the hopes that if
1289 			 * the drive is not in the state we think it is.
1290 			 * And the state will be changed so it can be detached.
1291 			 * If the command fails to reach the device and
1292 			 * the drive was not rewound or unloaded we want
1293 			 * to fail the detach till a user command fails
1294 			 * where after the detach will succead.
1295 			 */
1296 			result = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
1297 			/*
1298 			 * After TUR un_state may be set to non-closed,
1299 			 * so reset it back.
1300 			 */
1301 			un->un_state = ST_STATE_CLOSED;
1302 			mutex_exit(ST_MUTEX);
1303 		}
1304 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1305 		    "un_status=%x, fileno=%x, blkno=%x\n",
1306 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1307 
1308 		/*
1309 		 * check again:
1310 		 * if we are not at BOT then it is not safe to unload
1311 		 */
1312 		if ((un->un_dev) &&		/* Been opened since attach */
1313 		    (result != EACCES) &&	/* drive is use by somebody */
1314 		    ((((un->un_pos.pmode == legacy) &&
1315 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1316 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1317 		    ((un->un_pos.pmode == logical) &&
1318 		    (un->un_pos.lgclblkno > 0))) &&
1319 		    ((un->un_state == ST_STATE_CLOSED) &&
1320 		    (un->un_laststate == ST_STATE_CLOSING)))) {
1321 
1322 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1323 			    "cannot detach: pmode=%d fileno=0x%x, blkno=0x%x"
1324 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1325 			    un->un_pos.fileno, un->un_pos.blkno,
1326 			    un->un_pos.lgclblkno);
1327 			un->un_unit_attention_flags |= 4;
1328 			return (DDI_FAILURE);
1329 		}
1330 
1331 		/*
1332 		 * Just To make sure that we have released the
1333 		 * tape unit .
1334 		 */
1335 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1336 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1337 			mutex_enter(ST_MUTEX);
1338 			(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
1339 			mutex_exit(ST_MUTEX);
1340 		}
1341 
1342 		/*
1343 		 * now remove other data structures allocated in st_doattach()
1344 		 */
1345 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1346 		    "destroying/freeing\n");
1347 
1348 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1349 		    st_reset_notification, (caddr_t)un);
1350 		cv_destroy(&un->un_clscv);
1351 		cv_destroy(&un->un_sbuf_cv);
1352 		cv_destroy(&un->un_queue_cv);
1353 		cv_destroy(&un->un_suspend_cv);
1354 		cv_destroy(&un->un_tape_busy_cv);
1355 		cv_destroy(&un->un_recov_buf_cv);
1356 
1357 		if (un->un_recov_taskq) {
1358 			ddi_taskq_destroy(un->un_recov_taskq);
1359 		}
1360 
1361 		if (un->un_hib_tid) {
1362 			(void) untimeout(un->un_hib_tid);
1363 			un->un_hib_tid = 0;
1364 		}
1365 
1366 		if (un->un_delay_tid) {
1367 			(void) untimeout(un->un_delay_tid);
1368 			un->un_delay_tid = 0;
1369 		}
1370 		cv_destroy(&un->un_state_cv);
1371 
1372 #ifdef	__x86
1373 		cv_destroy(&un->un_contig_mem_cv);
1374 
1375 		if (un->un_contig_mem_hdl != NULL) {
1376 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1377 		}
1378 #endif
1379 		if (un->un_sbufp) {
1380 			freerbuf(un->un_sbufp);
1381 		}
1382 		if (un->un_recov_buf) {
1383 			freerbuf(un->un_recov_buf);
1384 		}
1385 		if (un->un_uscsi_rqs_buf) {
1386 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1387 		}
1388 		if (un->un_mspl) {
1389 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1390 		}
1391 		if (un->un_rqs) {
1392 			scsi_destroy_pkt(un->un_rqs);
1393 			scsi_free_consistent_buf(un->un_rqs_bp);
1394 		}
1395 		if (un->un_mkr_pkt) {
1396 			scsi_destroy_pkt(un->un_mkr_pkt);
1397 		}
1398 		if (un->un_arq_enabled) {
1399 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1400 		}
1401 		if (un->un_dp_size) {
1402 			kmem_free(un->un_dp, un->un_dp_size);
1403 		}
1404 		if (un->un_stats) {
1405 			kstat_delete(un->un_stats);
1406 			un->un_stats = (kstat_t *)0;
1407 		}
1408 		if (un->un_errstats) {
1409 			kstat_delete(un->un_errstats);
1410 			un->un_errstats = (kstat_t *)0;
1411 		}
1412 		if (un->un_media_id_len) {
1413 			kmem_free(un->un_media_id, un->un_media_id_len);
1414 		}
1415 		devp = ST_SCSI_DEVP;
1416 		ddi_soft_state_free(st_state, instance);
1417 		devp->sd_private = NULL;
1418 		devp->sd_sense = NULL;
1419 		scsi_unprobe(devp);
1420 		ddi_prop_remove_all(devi);
1421 		ddi_remove_minor_node(devi, NULL);
1422 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1423 		return (DDI_SUCCESS);
1424 
1425 	case DDI_SUSPEND:
1426 
1427 		/*
1428 		 * Suspend/Resume
1429 		 *
1430 		 * To process DDI_SUSPEND, we must do the following:
1431 		 *
1432 		 *  - check ddi_removing_power to see if power will be turned
1433 		 *    off. if so, return DDI_FAILURE
1434 		 *  - check if we are already suspended,
1435 		 *    if so, return DDI_FAILURE
1436 		 *  - check if device state is CLOSED,
1437 		 *    if not, return DDI_FAILURE.
1438 		 *  - wait until outstanding operations complete
1439 		 *  - save tape state
1440 		 *  - block new operations
1441 		 *  - cancel pending timeouts
1442 		 *
1443 		 */
1444 
1445 		if (ddi_removing_power(devi)) {
1446 			return (DDI_FAILURE);
1447 		}
1448 
1449 		if (un->un_dev == 0)
1450 			un->un_dev = MTMINOR(instance);
1451 
1452 		mutex_enter(ST_MUTEX);
1453 
1454 		/*
1455 		 * Shouldn't already be suspended, if so return failure
1456 		 */
1457 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1458 			mutex_exit(ST_MUTEX);
1459 			return (DDI_FAILURE);
1460 		}
1461 		if (un->un_state != ST_STATE_CLOSED) {
1462 			mutex_exit(ST_MUTEX);
1463 			return (DDI_FAILURE);
1464 		}
1465 
1466 		/*
1467 		 * Wait for all outstanding I/O's to complete
1468 		 *
1469 		 * we wait on both ncmds and the wait queue for times
1470 		 * when we are flushing after persistent errors are
1471 		 * flagged, which is when ncmds can be 0, and the
1472 		 * queue can still have I/O's.  This way we preserve
1473 		 * order of biodone's.
1474 		 */
1475 		wait_cmds_complete = ddi_get_lbolt();
1476 		wait_cmds_complete +=
1477 		    st_wait_cmds_complete * drv_usectohz(1000000);
1478 		while (un->un_ncmds || un->un_quef ||
1479 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1480 
1481 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1482 			    wait_cmds_complete) == -1) {
1483 				/*
1484 				 * Time expired then cancel the command
1485 				 */
1486 				if (st_reset(un, RESET_LUN) == 0) {
1487 					if (un->un_last_throttle) {
1488 						un->un_throttle =
1489 						    un->un_last_throttle;
1490 					}
1491 					mutex_exit(ST_MUTEX);
1492 					return (DDI_FAILURE);
1493 				} else {
1494 					break;
1495 				}
1496 			}
1497 		}
1498 
1499 		/*
1500 		 * DDI_SUSPEND says that the system "may" power down, we
1501 		 * remember the file and block number before rewinding.
1502 		 * we also need to save state before issuing
1503 		 * any WRITE_FILE_MARK command.
1504 		 */
1505 		(void) st_update_block_pos(un, st_cmd, 0);
1506 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1507 
1508 
1509 		/*
1510 		 * Issue a zero write file fmk command to tell the drive to
1511 		 * flush any buffered tape marks
1512 		 */
1513 		(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1514 
1515 		/*
1516 		 * Because not all tape drives correctly implement buffer
1517 		 * flushing with the zero write file fmk command, issue a
1518 		 * synchronous rewind command to force data flushing.
1519 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1520 		 * anyway.
1521 		 */
1522 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
1523 
1524 		/* stop any new operations */
1525 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1526 		un->un_throttle = 0;
1527 
1528 		/*
1529 		 * cancel any outstanding timeouts
1530 		 */
1531 		if (un->un_delay_tid) {
1532 			timeout_id_t temp_id = un->un_delay_tid;
1533 			un->un_delay_tid = 0;
1534 			un->un_tids_at_suspend |= ST_DELAY_TID;
1535 			mutex_exit(ST_MUTEX);
1536 			(void) untimeout(temp_id);
1537 			mutex_enter(ST_MUTEX);
1538 		}
1539 
1540 		if (un->un_hib_tid) {
1541 			timeout_id_t temp_id = un->un_hib_tid;
1542 			un->un_hib_tid = 0;
1543 			un->un_tids_at_suspend |= ST_HIB_TID;
1544 			mutex_exit(ST_MUTEX);
1545 			(void) untimeout(temp_id);
1546 			mutex_enter(ST_MUTEX);
1547 		}
1548 
1549 		/*
1550 		 * Suspend the scsi_watch_thread
1551 		 */
1552 		if (un->un_swr_token) {
1553 			opaque_t temp_token = un->un_swr_token;
1554 			mutex_exit(ST_MUTEX);
1555 			scsi_watch_suspend(temp_token);
1556 		} else {
1557 			mutex_exit(ST_MUTEX);
1558 		}
1559 
1560 		return (DDI_SUCCESS);
1561 
1562 	default:
1563 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1564 		return (DDI_FAILURE);
1565 	}
1566 }
1567 
1568 
1569 /* ARGSUSED */
1570 static int
1571 st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1572 {
1573 	dev_t dev;
1574 	struct scsi_tape *un;
1575 	int instance, error;
1576 
1577 	ST_ENTR(dip, st_info);
1578 
1579 	switch (infocmd) {
1580 	case DDI_INFO_DEVT2DEVINFO:
1581 		dev = (dev_t)arg;
1582 		instance = MTUNIT(dev);
1583 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1584 			return (DDI_FAILURE);
1585 		*result = (void *) ST_DEVINFO;
1586 		error = DDI_SUCCESS;
1587 		break;
1588 	case DDI_INFO_DEVT2INSTANCE:
1589 		dev = (dev_t)arg;
1590 		instance = MTUNIT(dev);
1591 		*result = (void *)(uintptr_t)instance;
1592 		error = DDI_SUCCESS;
1593 		break;
1594 	default:
1595 		error = DDI_FAILURE;
1596 	}
1597 	return (error);
1598 }
1599 
1600 static int
1601 st_doattach(struct scsi_device *devp, int (*canwait)())
1602 {
1603 	struct scsi_tape *un = NULL;
1604 	recov_info *ri;
1605 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1606 	int instance;
1607 	size_t rlen;
1608 
1609 	ST_FUNC(devp->sd_dev, st_doattach);
1610 	/*
1611 	 * Call the routine scsi_probe to do some of the dirty work.
1612 	 * If the INQUIRY command succeeds, the field sd_inq in the
1613 	 * device structure will be filled in.
1614 	 */
1615 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1616 	    "st_doattach(): probing\n");
1617 
1618 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1619 
1620 		/*
1621 		 * In checking the whole inq_dtype byte we are looking at both
1622 		 * the Peripheral Qualifier and the Peripheral Device Type.
1623 		 * For this driver we are only interested in sequential devices
1624 		 * that are connected or capable if connecting to this logical
1625 		 * unit.
1626 		 */
1627 		if (devp->sd_inq->inq_dtype ==
1628 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1629 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1630 			    "probe exists\n");
1631 		} else {
1632 			/* Something there but not a tape device */
1633 			scsi_unprobe(devp);
1634 			return (DDI_FAILURE);
1635 		}
1636 	} else {
1637 		/* Nothing there */
1638 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1639 		    "probe failure: nothing there\n");
1640 		scsi_unprobe(devp);
1641 		return (DDI_FAILURE);
1642 	}
1643 
1644 
1645 	/*
1646 	 * The actual unit is present.
1647 	 * Now is the time to fill in the rest of our info..
1648 	 */
1649 	instance = ddi_get_instance(devp->sd_dev);
1650 
1651 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1652 		goto error;
1653 	}
1654 	un = ddi_get_soft_state(st_state, instance);
1655 
1656 	ASSERT(un != NULL);
1657 
1658 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
1659 	    MAX_SENSE_LENGTH, B_READ, canwait, NULL);
1660 	if (un->un_rqs_bp == NULL) {
1661 		goto error;
1662 	}
1663 	un->un_rqs = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
1664 	    CDB_GROUP0, 1, st_recov_sz, PKT_CONSISTENT, canwait, NULL);
1665 	if (!un->un_rqs) {
1666 		goto error;
1667 	}
1668 	ASSERT(un->un_rqs->pkt_resid == 0);
1669 	devp->sd_sense =
1670 	    (struct scsi_extended_sense *)un->un_rqs_bp->b_un.b_addr;
1671 	ASSERT(geterror(un->un_rqs_bp) == NULL);
1672 
1673 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs->pkt_cdbp,
1674 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
1675 	FILL_SCSI1_LUN(devp, un->un_rqs);
1676 	un->un_rqs->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1677 	un->un_rqs->pkt_time = st_io_time;
1678 	un->un_rqs->pkt_comp = st_intr;
1679 	ri = (recov_info *)un->un_rqs->pkt_private;
1680 	if (st_recov_sz == sizeof (recov_info)) {
1681 		ri->privatelen = sizeof (recov_info);
1682 	} else {
1683 		ri->privatelen = sizeof (pkt_info);
1684 	}
1685 
1686 	un->un_sbufp = getrbuf(km_flags);
1687 	un->un_recov_buf = getrbuf(km_flags);
1688 
1689 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1690 
1691 	/*
1692 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1693 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1694 	 * is obsolete and we want more flexibility in controlling the DMA
1695 	 * address constraints.
1696 	 */
1697 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1698 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1699 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1700 
1701 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1702 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1703 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1704 
1705 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1706 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1707 		    "probe partial failure: no space\n");
1708 		goto error;
1709 	}
1710 
1711 	bzero(un->un_mspl, sizeof (struct seq_mode));
1712 
1713 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1714 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1715 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1716 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1717 #ifdef	__x86
1718 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1719 #endif
1720 
1721 	/* Initialize power managemnet condition variable */
1722 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1723 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1724 	cv_init(&un->un_recov_buf_cv, NULL, CV_DRIVER, NULL);
1725 
1726 	un->un_recov_taskq = ddi_taskq_create(devp->sd_dev,
1727 	    "un_recov_taskq", 1, TASKQ_DEFAULTPRI, km_flags);
1728 
1729 	ASSERT(un->un_recov_taskq != NULL);
1730 
1731 	un->un_pos.pmode = invalid;
1732 	un->un_sd	= devp;
1733 	un->un_swr_token = (opaque_t)NULL;
1734 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1735 	un->un_wormable = st_is_drive_worm;
1736 	un->un_media_id_method = st_get_media_identification;
1737 	/*
1738 	 * setting long a initial as it contains logical file info.
1739 	 * support for long format is mandatory but many drive don't do it.
1740 	 */
1741 	un->un_read_pos_type = LONG_POS;
1742 
1743 	un->un_suspend_pos.pmode = invalid;
1744 
1745 	st_add_recovery_info_to_pkt(un, un->un_rqs_bp, un->un_rqs);
1746 
1747 #ifdef	__x86
1748 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1749 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1750 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1751 		    "allocation of contiguous memory dma handle failed!");
1752 		un->un_contig_mem_hdl = NULL;
1753 		goto error;
1754 	}
1755 #endif
1756 
1757 	/*
1758 	 * Since this driver manages devices with "remote" hardware,
1759 	 * i.e. the devices themselves have no "reg" properties,
1760 	 * the SUSPEND/RESUME commands in detach/attach will not be
1761 	 * called by the power management framework unless we request
1762 	 * it by creating a "pm-hardware-state" property and setting it
1763 	 * to value "needs-suspend-resume".
1764 	 */
1765 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1766 	    "pm-hardware-state", "needs-suspend-resume") !=
1767 	    DDI_PROP_SUCCESS) {
1768 
1769 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1770 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1771 		goto error;
1772 	}
1773 
1774 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1775 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1776 
1777 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1778 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1779 		    "failed\n");
1780 		goto error;
1781 	}
1782 
1783 	(void) scsi_reset_notify(ROUTE, SCSI_RESET_NOTIFY,
1784 	    st_reset_notification, (caddr_t)un);
1785 
1786 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "attach success\n");
1787 	return (DDI_SUCCESS);
1788 
1789 error:
1790 	devp->sd_sense = NULL;
1791 
1792 	ddi_remove_minor_node(devp->sd_dev, NULL);
1793 	if (un) {
1794 		if (un->un_mspl) {
1795 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1796 		}
1797 		if (un->un_read_pos_data) {
1798 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1799 		}
1800 		if (un->un_sbufp) {
1801 			freerbuf(un->un_sbufp);
1802 		}
1803 		if (un->un_recov_buf) {
1804 			freerbuf(un->un_recov_buf);
1805 		}
1806 		if (un->un_uscsi_rqs_buf) {
1807 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1808 		}
1809 #ifdef	__x86
1810 		if (un->un_contig_mem_hdl != NULL) {
1811 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1812 		}
1813 #endif
1814 		if (un->un_rqs) {
1815 			scsi_destroy_pkt(un->un_rqs);
1816 		}
1817 
1818 		if (un->un_rqs_bp) {
1819 			scsi_free_consistent_buf(un->un_rqs_bp);
1820 		}
1821 
1822 		ddi_soft_state_free(st_state, instance);
1823 		devp->sd_private = NULL;
1824 	}
1825 
1826 	if (devp->sd_inq) {
1827 		scsi_unprobe(devp);
1828 	}
1829 	return (DDI_FAILURE);
1830 }
1831 
1832 typedef int
1833 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1834 
1835 static cfg_functp config_functs[] = {
1836 	st_get_conf_from_st_dot_conf,
1837 	st_get_conf_from_st_conf_dot_c,
1838 	st_get_conf_from_tape_drive,
1839 	st_get_default_conf
1840 };
1841 
1842 
1843 /*
1844  * determine tape type, using tape-config-list or built-in table or
1845  * use a generic tape config entry
1846  */
1847 static void
1848 st_known_tape_type(struct scsi_tape *un)
1849 {
1850 	struct st_drivetype *dp;
1851 	cfg_functp *config_funct;
1852 	uchar_t reserved;
1853 
1854 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1855 
1856 	reserved = (un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1857 	    : ST_RELEASE;
1858 
1859 	/*
1860 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1861 	 *	 no vid & pid inquiry data.  So, we provide one.
1862 	 */
1863 	if (ST_INQUIRY->inq_len == 0 ||
1864 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1865 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1866 	}
1867 
1868 	if (un->un_dp_size == 0) {
1869 		un->un_dp_size = sizeof (struct st_drivetype);
1870 		dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1871 		un->un_dp = dp;
1872 	} else {
1873 		dp = un->un_dp;
1874 	}
1875 
1876 	un->un_dp->non_motion_timeout = st_io_time;
1877 	/*
1878 	 * Loop through the configuration methods till one works.
1879 	 */
1880 	for (config_funct = &config_functs[0]; ; config_funct++) {
1881 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1882 			break;
1883 		}
1884 	}
1885 
1886 	/*
1887 	 * If we didn't just make up this configuration and
1888 	 * all the density codes are the same..
1889 	 * Set Auto Density over ride.
1890 	 */
1891 	if (*config_funct != st_get_default_conf) {
1892 		/*
1893 		 * If this device is one that is configured and all
1894 		 * densities are the same, This saves doing gets and set
1895 		 * that yield nothing.
1896 		 */
1897 		if ((dp->densities[0]) == (dp->densities[1]) &&
1898 		    (dp->densities[0]) == (dp->densities[2]) &&
1899 		    (dp->densities[0]) == (dp->densities[3])) {
1900 
1901 			dp->options |= ST_AUTODEN_OVERRIDE;
1902 		}
1903 	}
1904 
1905 
1906 	/*
1907 	 * Store tape drive characteristics.
1908 	 */
1909 	un->un_status = 0;
1910 	un->un_attached = 1;
1911 	un->un_init_options = dp->options;
1912 
1913 	/* setup operation time-outs based on options */
1914 	st_calculate_timeouts(un);
1915 
1916 	/* TLR support */
1917 	if (un->un_dp->type != ST_TYPE_INVALID) {
1918 		int result;
1919 
1920 		/* try and enable TLR */
1921 		un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
1922 		result = st_set_target_TLR_mode(un, st_uscsi_cmd);
1923 		if (result == EACCES) {
1924 			/*
1925 			 * From attach command failed.
1926 			 * Set dp type so is run again on open.
1927 			 */
1928 			un->un_dp->type = ST_TYPE_INVALID;
1929 			un->un_tlr_flag = TLR_NOT_KNOWN;
1930 		} else if (result == 0) {
1931 			if (scsi_ifgetcap(&un->un_sd->sd_address,
1932 			    "tran-layer-retries", 1) == -1) {
1933 				un->un_tlr_flag = TLR_NOT_SUPPORTED;
1934 				(void) st_set_target_TLR_mode(un, st_uscsi_cmd);
1935 			} else {
1936 				un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
1937 			}
1938 		} else {
1939 			un->un_tlr_flag = TLR_NOT_SUPPORTED;
1940 		}
1941 	}
1942 
1943 	/* make sure if we are supposed to be variable, make it variable */
1944 	if (dp->options & ST_VARIABLE) {
1945 		dp->bsize = 0;
1946 	}
1947 
1948 	if (reserved != ((un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1949 	    : ST_RELEASE)) {
1950 		(void) st_reserve_release(un, reserved, st_uscsi_cmd);
1951 	}
1952 
1953 	un->un_unit_attention_flags |= 1;
1954 
1955 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1956 
1957 }
1958 
1959 
1960 typedef struct {
1961 	int mask;
1962 	int bottom;
1963 	int top;
1964 	char *name;
1965 } conf_limit;
1966 
1967 static const conf_limit conf_limits[] = {
1968 
1969 	-1,		1,		2,		"conf version",
1970 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1971 	-1,		0,		0xffffff,	"block size",
1972 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1973 	-1,		0,		4,		"number of densities",
1974 	-1,		0,		UINT8_MAX,	"density code",
1975 	-1,		0,		3,		"default density",
1976 	-1,		0,		UINT16_MAX,	"non motion timeout",
1977 	-1,		0,		UINT16_MAX,	"I/O timeout",
1978 	-1,		0,		UINT16_MAX,	"space timeout",
1979 	-1,		0,		UINT16_MAX,	"load timeout",
1980 	-1,		0,		UINT16_MAX,	"unload timeout",
1981 	-1,		0,		UINT16_MAX,	"erase timeout",
1982 	0,		0,		0,		NULL
1983 };
1984 
1985 static int
1986 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1987     const char *conf_name)
1988 {
1989 	int dens;
1990 	int ndens;
1991 	int value;
1992 	int type;
1993 	int count;
1994 	const conf_limit *limit = &conf_limits[0];
1995 
1996 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1997 
1998 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1999 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
2000 
2001 	count = list_len;
2002 	type = *list;
2003 	for (;  count && limit->name; count--, list++, limit++) {
2004 
2005 		value = *list;
2006 		if (value & ~limit->mask) {
2007 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2008 			    "%s %s value invalid bits set: 0x%X\n",
2009 			    conf_name, limit->name, value & ~limit->mask);
2010 			*list &= limit->mask;
2011 		} else if (value < limit->bottom) {
2012 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2013 			    "%s %s value too low: value = %d limit %d\n",
2014 			    conf_name, limit->name, value, limit->bottom);
2015 		} else if (value > limit->top) {
2016 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2017 			    "%s %s value too high: value = %d limit %d\n",
2018 			    conf_name, limit->name, value, limit->top);
2019 		} else {
2020 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2021 			    "%s %s value = 0x%X\n",
2022 			    conf_name, limit->name, value);
2023 		}
2024 
2025 		/* If not the number of densities continue */
2026 		if (limit != &conf_limits[4]) {
2027 			continue;
2028 		}
2029 
2030 		/* If number of densities is not in range can't use config */
2031 		if (value < limit->bottom || value > limit->top) {
2032 			return (-1);
2033 		}
2034 
2035 		ndens = min(value, NDENSITIES);
2036 		if ((type == 1) && (list_len - ndens) != 6) {
2037 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2038 			    "%s conf version 1 with %d densities has %d items"
2039 			    " should have %d",
2040 			    conf_name, ndens, list_len, 6 + ndens);
2041 		} else if ((type == 2) && (list_len - ndens) != 13) {
2042 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2043 			    "%s conf version 2 with %d densities has %d items"
2044 			    " should have %d",
2045 			    conf_name, ndens, list_len, 13 + ndens);
2046 		}
2047 
2048 		limit++;
2049 		for (dens = 0; dens < ndens && count; dens++) {
2050 			count--;
2051 			list++;
2052 			value = *list;
2053 			if (value < limit->bottom) {
2054 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2055 				    "%s density[%d] value too low: value ="
2056 				    " 0x%X limit 0x%X\n",
2057 				    conf_name, dens, value, limit->bottom);
2058 			} else if (value > limit->top) {
2059 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2060 				    "%s density[%d] value too high: value ="
2061 				    " 0x%X limit 0x%X\n",
2062 				    conf_name, dens, value, limit->top);
2063 			} else {
2064 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2065 				    "%s density[%d] value = 0x%X\n",
2066 				    conf_name, dens, value);
2067 			}
2068 		}
2069 	}
2070 
2071 	return (0);
2072 }
2073 
2074 static int
2075 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
2076     struct st_drivetype *dp)
2077 {
2078 	caddr_t config_list = NULL;
2079 	caddr_t data_list = NULL;
2080 	int	*data_ptr;
2081 	caddr_t vidptr, prettyptr, datanameptr;
2082 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
2083 	int config_list_len, data_list_len, len, i;
2084 	int version;
2085 	int found = 0;
2086 
2087 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
2088 
2089 	/*
2090 	 * Determine type of tape controller. Type is determined by
2091 	 * checking the vendor ids of the earlier inquiry command and
2092 	 * comparing those with vids in tape-config-list defined in st.conf
2093 	 */
2094 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
2095 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
2096 	    != DDI_PROP_SUCCESS) {
2097 		return (found);
2098 	}
2099 
2100 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2101 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
2102 
2103 	/*
2104 	 * Compare vids in each triplet - if it matches, get value for
2105 	 * data_name and contruct a st_drivetype struct
2106 	 * tripletlen is not set yet!
2107 	 */
2108 	for (len = config_list_len, vidptr = config_list;
2109 	    len > 0;
2110 	    vidptr += tripletlen, len -= tripletlen) {
2111 
2112 		vidlen = strlen(vidptr);
2113 		prettyptr = vidptr + vidlen + 1;
2114 		prettylen = strlen(prettyptr);
2115 		datanameptr = prettyptr + prettylen + 1;
2116 		datanamelen = strlen(datanameptr);
2117 		tripletlen = vidlen + prettylen + datanamelen + 3;
2118 
2119 		if (vidlen == 0) {
2120 			continue;
2121 		}
2122 
2123 		/*
2124 		 * If inquiry vid dosen't match this triplets vid,
2125 		 * try the next.
2126 		 */
2127 		if (strncasecmp(vidpid, vidptr, vidlen)) {
2128 			continue;
2129 		}
2130 
2131 		/*
2132 		 * if prettylen is zero then use the vid string
2133 		 */
2134 		if (prettylen == 0) {
2135 			prettyptr = vidptr;
2136 			prettylen = vidlen;
2137 		}
2138 
2139 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2140 		    "vid = %s, pretty=%s, dataname = %s\n",
2141 		    vidptr, prettyptr, datanameptr);
2142 
2143 		/*
2144 		 * get the data list
2145 		 */
2146 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
2147 		    datanameptr, (caddr_t)&data_list,
2148 		    &data_list_len) != DDI_PROP_SUCCESS) {
2149 			/*
2150 			 * Error in getting property value
2151 			 * print warning!
2152 			 */
2153 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2154 			    "data property (%s) has no value\n",
2155 			    datanameptr);
2156 			continue;
2157 		}
2158 
2159 		/*
2160 		 * now initialize the st_drivetype struct
2161 		 */
2162 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
2163 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
2164 		(void) strncpy(dp->vid, vidptr, dp->length);
2165 		data_ptr = (int *)data_list;
2166 		/*
2167 		 * check if data is enough for version, type,
2168 		 * bsize, options, # of densities, density1,
2169 		 * density2, ..., default_density
2170 		 */
2171 		if ((data_list_len < 5 * sizeof (int)) ||
2172 		    (data_list_len < 6 * sizeof (int) +
2173 		    *(data_ptr + 4) * sizeof (int))) {
2174 			/*
2175 			 * print warning and skip to next triplet.
2176 			 */
2177 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2178 			    "data property (%s) incomplete\n",
2179 			    datanameptr);
2180 			kmem_free(data_list, data_list_len);
2181 			continue;
2182 		}
2183 
2184 		if (st_validate_conf_data(un, data_ptr,
2185 		    data_list_len / sizeof (int), datanameptr)) {
2186 			kmem_free(data_list, data_list_len);
2187 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2188 			    "data property (%s) rejected\n",
2189 			    datanameptr);
2190 			continue;
2191 		}
2192 
2193 		/*
2194 		 * check version
2195 		 */
2196 		version = *data_ptr++;
2197 		if (version != 1 && version != 2) {
2198 			/* print warning but accept it */
2199 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2200 			    "Version # for data property (%s) "
2201 			    "not set to 1 or 2\n", datanameptr);
2202 		}
2203 
2204 		dp->type    = *data_ptr++;
2205 		dp->bsize   = *data_ptr++;
2206 		dp->options = *data_ptr++;
2207 		dp->options |= ST_DYNAMIC;
2208 		len = *data_ptr++;
2209 		for (i = 0; i < NDENSITIES; i++) {
2210 			if (i < len) {
2211 				dp->densities[i] = *data_ptr++;
2212 			}
2213 		}
2214 		dp->default_density = *data_ptr << 3;
2215 		if (version == 2 &&
2216 		    data_list_len >= (13 + len) * sizeof (int)) {
2217 			data_ptr++;
2218 			dp->non_motion_timeout	= *data_ptr++;
2219 			dp->io_timeout		= *data_ptr++;
2220 			dp->rewind_timeout	= *data_ptr++;
2221 			dp->space_timeout	= *data_ptr++;
2222 			dp->load_timeout	= *data_ptr++;
2223 			dp->unload_timeout	= *data_ptr++;
2224 			dp->erase_timeout	= *data_ptr++;
2225 		}
2226 		kmem_free(data_list, data_list_len);
2227 		found = 1;
2228 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2229 		    "found in st.conf: vid = %s, pretty=%s\n",
2230 		    dp->vid, dp->name);
2231 		break;
2232 	}
2233 
2234 	/*
2235 	 * free up the memory allocated by ddi_getlongprop
2236 	 */
2237 	if (config_list) {
2238 		kmem_free(config_list, config_list_len);
2239 	}
2240 	return (found);
2241 }
2242 
2243 static int
2244 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2245     struct st_drivetype *dp)
2246 {
2247 	int i;
2248 
2249 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2250 	/*
2251 	 * Determine type of tape controller.  Type is determined by
2252 	 * checking the result of the earlier inquiry command and
2253 	 * comparing vendor ids with strings in a table declared in st_conf.c.
2254 	 */
2255 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2256 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2257 
2258 	for (i = 0; i < st_ndrivetypes; i++) {
2259 		if (st_drivetypes[i].length == 0) {
2260 			continue;
2261 		}
2262 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2263 		    st_drivetypes[i].length)) {
2264 			continue;
2265 		}
2266 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2267 		return (1);
2268 	}
2269 	return (0);
2270 }
2271 
2272 static int
2273 st_get_conf_from_tape_drive(struct scsi_tape *un, char *vidpid,
2274     struct st_drivetype *dp)
2275 {
2276 	int bsize;
2277 	ulong_t maxbsize;
2278 	caddr_t buf;
2279 	struct st_drivetype *tem_dp;
2280 	struct read_blklim *blklim;
2281 	int rval;
2282 	int i;
2283 
2284 	ST_FUNC(ST_DEVINFO, st_get_conf_from_tape_drive);
2285 
2286 	/*
2287 	 * Determine the type of tape controller. Type is determined by
2288 	 * sending SCSI commands to tape drive and deriving the type from
2289 	 * the returned data.
2290 	 */
2291 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2292 	    "st_get_conf_from_tape_drive(): asking tape drive\n");
2293 
2294 	tem_dp = kmem_zalloc(sizeof (struct st_drivetype), KM_SLEEP);
2295 
2296 	/*
2297 	 * Make up a name
2298 	 */
2299 	bcopy(vidpid, tem_dp->name, VIDPIDLEN);
2300 	tem_dp->name[VIDPIDLEN] = '\0';
2301 	tem_dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2302 	(void) strncpy(tem_dp->vid, ST_INQUIRY->inq_vid, tem_dp->length);
2303 	/*
2304 	 * 'clean' vendor and product strings of non-printing chars
2305 	 */
2306 	for (i = 0; i < VIDPIDLEN - 1; i ++) {
2307 		if (tem_dp->name[i] < ' ' || tem_dp->name[i] > '~') {
2308 			tem_dp->name[i] = '.';
2309 		}
2310 	}
2311 
2312 	/*
2313 	 * MODE SENSE to determine block size.
2314 	 */
2315 	un->un_dp->options |= ST_MODE_SEL_COMP | ST_UNLOADABLE;
2316 	rval = st_modesense(un);
2317 	if (rval) {
2318 		if (rval == EACCES) {
2319 			un->un_dp->type = ST_TYPE_INVALID;
2320 			rval = 1;
2321 		} else {
2322 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
2323 			rval = 0;
2324 		}
2325 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2326 		    "st_get_conf_from_tape_drive(): fail to mode sense\n");
2327 		goto exit;
2328 	}
2329 
2330 	/* Can mode sense page 0x10 or 0xf */
2331 	tem_dp->options |= ST_MODE_SEL_COMP;
2332 	bsize = (un->un_mspl->high_bl << 16)	|
2333 	    (un->un_mspl->mid_bl << 8)		|
2334 	    (un->un_mspl->low_bl);
2335 
2336 	if (bsize == 0) {
2337 		tem_dp->options |= ST_VARIABLE;
2338 		tem_dp->bsize = 0;
2339 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
2340 		rval = st_change_block_size(un, 0);
2341 		if (rval) {
2342 			if (rval == EACCES) {
2343 				un->un_dp->type = ST_TYPE_INVALID;
2344 				rval = 1;
2345 			} else {
2346 				rval = 0;
2347 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2348 				    "st_get_conf_from_tape_drive(): "
2349 				    "Fixed record size is too large and"
2350 				    "cannot switch to variable record size");
2351 			}
2352 			goto exit;
2353 		}
2354 		tem_dp->options |= ST_VARIABLE;
2355 	} else {
2356 		rval = st_change_block_size(un, 0);
2357 		if (rval == 0) {
2358 			tem_dp->options |= ST_VARIABLE;
2359 			tem_dp->bsize = 0;
2360 		} else if (rval != EACCES) {
2361 			tem_dp->bsize = bsize;
2362 		} else {
2363 			un->un_dp->type = ST_TYPE_INVALID;
2364 			rval = 1;
2365 			goto exit;
2366 		}
2367 	}
2368 
2369 	/*
2370 	 * If READ BLOCk LIMITS works and upper block size limit is
2371 	 * more than 64K, ST_NO_RECSIZE_LIMIT is supported.
2372 	 */
2373 	blklim = kmem_zalloc(sizeof (struct read_blklim), KM_SLEEP);
2374 	rval = st_read_block_limits(un, blklim);
2375 	if (rval) {
2376 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2377 		    "st_get_conf_from_tape_drive(): "
2378 		    "fail to read block limits.\n");
2379 		rval = 0;
2380 		kmem_free(blklim, sizeof (struct read_blklim));
2381 		goto exit;
2382 	}
2383 	maxbsize = (blklim->max_hi << 16) +
2384 	    (blklim->max_mid << 8) + blklim->max_lo;
2385 	if (maxbsize > ST_MAXRECSIZE_VARIABLE) {
2386 		tem_dp->options |= ST_NO_RECSIZE_LIMIT;
2387 	}
2388 	kmem_free(blklim, sizeof (struct read_blklim));
2389 
2390 	/*
2391 	 * Inquiry VPD page 0xb0 to see if the tape drive supports WORM
2392 	 */
2393 	buf = kmem_zalloc(6, KM_SLEEP);
2394 	rval = st_get_special_inquiry(un, 6, buf, 0xb0);
2395 	if (rval) {
2396 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2397 		    "st_get_conf_from_tape_drive(): "
2398 		    "fail to read vitial inquiry.\n");
2399 		rval = 0;
2400 		kmem_free(buf, 6);
2401 		goto exit;
2402 	}
2403 	if (buf[4] & 1) {
2404 		tem_dp->options |= ST_WORMABLE;
2405 	}
2406 	kmem_free(buf, 6);
2407 
2408 	/* Assume BSD BSR KNOWS_EOD */
2409 	tem_dp->options |= ST_BSF | ST_BSR | ST_KNOWS_EOD | ST_UNLOADABLE;
2410 	tem_dp->max_rretries = -1;
2411 	tem_dp->max_wretries = -1;
2412 
2413 	/*
2414 	 * Decide the densities supported by tape drive by sending
2415 	 * REPORT DENSITY SUPPORT command.
2416 	 */
2417 	if (st_get_densities_from_tape_drive(un, tem_dp) == 0) {
2418 		goto exit;
2419 	}
2420 
2421 	/*
2422 	 * Decide the timeout values for several commands by sending
2423 	 * REPORT SUPPORTED OPERATION CODES command.
2424 	 */
2425 	rval = st_get_timeout_values_from_tape_drive(un, tem_dp);
2426 	if (rval == 0 || ((rval == 1) && (tem_dp->type == ST_TYPE_INVALID))) {
2427 		goto exit;
2428 	}
2429 
2430 	bcopy(tem_dp, dp, sizeof (struct st_drivetype));
2431 	rval = 1;
2432 
2433 exit:
2434 	un->un_status = KEY_NO_SENSE;
2435 	kmem_free(tem_dp, sizeof (struct st_drivetype));
2436 	return (rval);
2437 }
2438 
2439 static int
2440 st_get_densities_from_tape_drive(struct scsi_tape *un,
2441     struct st_drivetype *dp)
2442 {
2443 	int i, p;
2444 	size_t buflen;
2445 	ushort_t des_len;
2446 	uchar_t *den_header;
2447 	uchar_t num_den;
2448 	uchar_t den[NDENSITIES];
2449 	uchar_t deflt[NDENSITIES];
2450 	struct report_density_desc *den_desc;
2451 
2452 	ST_FUNC(ST_DEVINFO, st_get_densities_from_type_drive);
2453 
2454 	/*
2455 	 * Since we have no idea how many densitiy support entries
2456 	 * will be returned, we send the command firstly assuming
2457 	 * there is only one. Then we can decide the number of
2458 	 * entries by available density support length. If multiple
2459 	 * entries exist, we will resend the command with enough
2460 	 * buffer size.
2461 	 */
2462 	buflen = sizeof (struct report_density_header) +
2463 	    sizeof (struct report_density_desc);
2464 	den_header = kmem_zalloc(buflen, KM_SLEEP);
2465 	if (st_report_density_support(un, den_header, buflen) != 0) {
2466 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2467 		    "st_get_conf_from_tape_drive(): fail to report density.\n");
2468 		kmem_free(den_header, buflen);
2469 		return (0);
2470 	}
2471 	des_len =
2472 	    BE_16(((struct report_density_header *)den_header)->ava_dens_len);
2473 	num_den = (des_len - 2) / sizeof (struct report_density_desc);
2474 
2475 	if (num_den > 1) {
2476 		kmem_free(den_header, buflen);
2477 		buflen = sizeof (struct report_density_header) +
2478 		    sizeof (struct report_density_desc) * num_den;
2479 		den_header = kmem_zalloc(buflen, KM_SLEEP);
2480 		if (st_report_density_support(un, den_header, buflen) != 0) {
2481 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2482 			    "st_get_conf_from_tape_drive(): "
2483 			    "fail to report density.\n");
2484 			kmem_free(den_header, buflen);
2485 			return (0);
2486 		}
2487 	}
2488 
2489 	den_desc = (struct report_density_desc *)(den_header
2490 	    + sizeof (struct report_density_header));
2491 
2492 	/*
2493 	 * Decide the drive type by assigning organization
2494 	 */
2495 	for (i = 0; i < ST_NUM_MEMBERS(st_vid_dt); i ++) {
2496 		if (strncmp(st_vid_dt[i].vid, (char *)(den_desc->ass_org),
2497 		    8) == 0) {
2498 			dp->type = st_vid_dt[i].type;
2499 			break;
2500 		}
2501 	}
2502 	if (i == ST_NUM_MEMBERS(st_vid_dt)) {
2503 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2504 		    "st_get_conf_from_tape_drive(): "
2505 		    "can't find match of assigned ort.\n");
2506 		kmem_free(den_header, buflen);
2507 		return (0);
2508 	}
2509 
2510 	/*
2511 	 * The tape drive may support many tape formats, but the st driver
2512 	 * supports only the four highest densities. Since density code
2513 	 * values are returned by ascending sequence, we start from the
2514 	 * last entry of density support data block descriptor.
2515 	 */
2516 	p = 0;
2517 	den_desc += num_den - 1;
2518 	for (i = 0; i < num_den && p < NDENSITIES; i ++, den_desc --) {
2519 		if ((den_desc->pri_den != 0) && (den_desc->wrtok)) {
2520 			if (p != 0) {
2521 				if (den_desc->pri_den >= den[p - 1]) {
2522 					continue;
2523 				}
2524 			}
2525 			den[p] = den_desc->pri_den;
2526 			deflt[p] = den_desc->deflt;
2527 			p ++;
2528 		}
2529 	}
2530 
2531 	switch (p) {
2532 	case 0:
2533 		bzero(dp->densities, NDENSITIES);
2534 		dp->options |= ST_AUTODEN_OVERRIDE;
2535 		dp->default_density = MT_DENSITY4;
2536 		break;
2537 
2538 	case 1:
2539 		(void) memset(dp->densities, den[0], NDENSITIES);
2540 		dp->options |= ST_AUTODEN_OVERRIDE;
2541 		dp->default_density = MT_DENSITY4;
2542 		break;
2543 
2544 	case 2:
2545 		dp->densities[0] = den[1];
2546 		dp->densities[1] = den[1];
2547 		dp->densities[2] = den[0];
2548 		dp->densities[3] = den[0];
2549 		if (deflt[0]) {
2550 			dp->default_density = MT_DENSITY4;
2551 		} else {
2552 			dp->default_density = MT_DENSITY2;
2553 		}
2554 		break;
2555 
2556 	case 3:
2557 		dp->densities[0] = den[2];
2558 		dp->densities[1] = den[1];
2559 		dp->densities[2] = den[0];
2560 		dp->densities[3] = den[0];
2561 		if (deflt[0]) {
2562 			dp->default_density = MT_DENSITY4;
2563 		} else if (deflt[1]) {
2564 			dp->default_density = MT_DENSITY2;
2565 		} else {
2566 			dp->default_density = MT_DENSITY1;
2567 		}
2568 		break;
2569 
2570 	default:
2571 		for (i = p; i > p - NDENSITIES; i --) {
2572 			dp->densities[i - 1] = den[p - i];
2573 		}
2574 		if (deflt[0]) {
2575 			dp->default_density = MT_DENSITY4;
2576 		} else if (deflt[1]) {
2577 			dp->default_density = MT_DENSITY3;
2578 		} else if (deflt[2]) {
2579 			dp->default_density = MT_DENSITY2;
2580 		} else {
2581 			dp->default_density = MT_DENSITY1;
2582 		}
2583 		break;
2584 	}
2585 
2586 	bzero(dp->mediatype, NDENSITIES);
2587 
2588 	kmem_free(den_header, buflen);
2589 	return (1);
2590 }
2591 
2592 static int
2593 st_get_timeout_values_from_tape_drive(struct scsi_tape *un,
2594     struct st_drivetype *dp)
2595 {
2596 	ushort_t timeout;
2597 	int rval;
2598 
2599 	ST_FUNC(ST_DEVINFO, st_get_timeout_values_from_type_drive);
2600 
2601 	rval = st_get_timeouts_value(un, SCMD_ERASE, &timeout, 0);
2602 	if (rval) {
2603 		if (rval == EACCES) {
2604 			un->un_dp->type = ST_TYPE_INVALID;
2605 			dp->type = ST_TYPE_INVALID;
2606 			return (1);
2607 		}
2608 		return (0);
2609 	}
2610 	dp->erase_timeout = timeout;
2611 
2612 	rval = st_get_timeouts_value(un, SCMD_READ, &timeout, 0);
2613 	if (rval) {
2614 		if (rval == EACCES) {
2615 			un->un_dp->type = ST_TYPE_INVALID;
2616 			dp->type = ST_TYPE_INVALID;
2617 			return (1);
2618 		}
2619 		return (0);
2620 	}
2621 	dp->io_timeout = timeout;
2622 
2623 	rval = st_get_timeouts_value(un, SCMD_WRITE, &timeout, 0);
2624 	if (rval) {
2625 		if (rval == EACCES) {
2626 			un->un_dp->type = ST_TYPE_INVALID;
2627 			dp->type = ST_TYPE_INVALID;
2628 			return (1);
2629 		}
2630 		return (0);
2631 	}
2632 	dp->io_timeout = max(dp->io_timeout, timeout);
2633 
2634 	rval = st_get_timeouts_value(un, SCMD_SPACE, &timeout, 0);
2635 	if (rval) {
2636 		if (rval == EACCES) {
2637 			un->un_dp->type = ST_TYPE_INVALID;
2638 			dp->type = ST_TYPE_INVALID;
2639 			return (1);
2640 		}
2641 		return (0);
2642 	}
2643 	dp->space_timeout = timeout;
2644 
2645 	rval = st_get_timeouts_value(un, SCMD_LOAD, &timeout, 0);
2646 	if (rval) {
2647 		if (rval == EACCES) {
2648 			un->un_dp->type = ST_TYPE_INVALID;
2649 			dp->type = ST_TYPE_INVALID;
2650 			return (1);
2651 		}
2652 		return (0);
2653 	}
2654 	dp->load_timeout = timeout;
2655 	dp->unload_timeout = timeout;
2656 
2657 	rval = st_get_timeouts_value(un, SCMD_REWIND, &timeout, 0);
2658 	if (rval) {
2659 		if (rval == EACCES) {
2660 			un->un_dp->type = ST_TYPE_INVALID;
2661 			dp->type = ST_TYPE_INVALID;
2662 			return (1);
2663 		}
2664 		return (0);
2665 	}
2666 	dp->rewind_timeout = timeout;
2667 
2668 	rval = st_get_timeouts_value(un, SCMD_INQUIRY, &timeout, 0);
2669 	if (rval) {
2670 		if (rval == EACCES) {
2671 			un->un_dp->type = ST_TYPE_INVALID;
2672 			dp->type = ST_TYPE_INVALID;
2673 			return (1);
2674 		}
2675 		return (0);
2676 	}
2677 	dp->non_motion_timeout = timeout;
2678 
2679 	return (1);
2680 }
2681 
2682 static int
2683 st_get_timeouts_value(struct scsi_tape *un, uchar_t option_code,
2684     ushort_t *timeout_value, ushort_t service_action)
2685 {
2686 	uchar_t *timeouts;
2687 	uchar_t *oper;
2688 	uchar_t support;
2689 	uchar_t cdbsize;
2690 	uchar_t ctdp;
2691 	size_t buflen;
2692 	int rval;
2693 
2694 	ST_FUNC(ST_DEVINFO, st_get_timeouts_value);
2695 
2696 	buflen = sizeof (struct one_com_des) +
2697 	    sizeof (struct com_timeout_des);
2698 	oper = kmem_zalloc(buflen, KM_SLEEP);
2699 	rval = st_report_supported_operation(un, oper, option_code,
2700 	    service_action);
2701 
2702 	if (rval) {
2703 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2704 		    "st_get_timeouts_value(): "
2705 		    "fail to timeouts value for command %d.\n", option_code);
2706 		kmem_free(oper, buflen);
2707 		return (rval);
2708 	}
2709 
2710 	support = ((struct one_com_des *)oper)->support;
2711 	if ((support != SUPPORT_VALUES_SUPPORT_SCSI) &&
2712 	    (support != SUPPORT_VALUES_SUPPORT_VENDOR)) {
2713 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2714 		    "st_get_timeouts_value(): "
2715 		    "command %d is not supported.\n", option_code);
2716 		kmem_free(oper, buflen);
2717 		return (ENOTSUP);
2718 	}
2719 
2720 	ctdp = ((struct one_com_des *)oper)->ctdp;
2721 	if (!ctdp) {
2722 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2723 		    "st_get_timeouts_value(): "
2724 		    "command timeout is not included.\n");
2725 		kmem_free(oper, buflen);
2726 		return (ENOTSUP);
2727 	}
2728 
2729 	cdbsize = BE_16(((struct one_com_des *)oper)->cdb_size);
2730 	timeouts = (uchar_t *)(oper + cdbsize + 4);
2731 
2732 	/*
2733 	 * Timeout value in seconds is 4 bytes, but we only support the lower 2
2734 	 * bytes. If the higher 2 bytes are not zero, the timeout value is set
2735 	 * to 0xFFFF.
2736 	 */
2737 	if (*(timeouts + 8) != 0 || *(timeouts + 9) != 0) {
2738 		*timeout_value = USHRT_MAX;
2739 	} else {
2740 		*timeout_value = ((*(timeouts + 10)) << 8) |
2741 		    (*(timeouts + 11));
2742 	}
2743 
2744 	kmem_free(oper, buflen);
2745 	return (0);
2746 }
2747 
2748 static int
2749 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2750 {
2751 	int i;
2752 
2753 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2754 
2755 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2756 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2757 
2758 	/*
2759 	 * Make up a name
2760 	 */
2761 	bcopy("Vendor '", dp->name, 8);
2762 	bcopy(vidpid, &dp->name[8], VIDLEN);
2763 	bcopy("' Product '", &dp->name[16], 11);
2764 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2765 	dp->name[ST_NAMESIZE - 2] = '\'';
2766 	dp->name[ST_NAMESIZE - 1] = '\0';
2767 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2768 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2769 	/*
2770 	 * 'clean' vendor and product strings of non-printing chars
2771 	 */
2772 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2773 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2774 			dp->name[i] = '.';
2775 		}
2776 	}
2777 	dp->type = ST_TYPE_INVALID;
2778 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2779 
2780 	return (1); /* Can Not Fail */
2781 }
2782 
2783 /*
2784  * Regular Unix Entry points
2785  */
2786 
2787 
2788 
2789 /* ARGSUSED */
2790 static int
2791 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2792 {
2793 	dev_t dev = *dev_p;
2794 	int rval = 0;
2795 
2796 	GET_SOFT_STATE(dev);
2797 
2798 	ST_ENTR(ST_DEVINFO, st_open);
2799 
2800 	/*
2801 	 * validate that we are addressing a sensible unit
2802 	 */
2803 	mutex_enter(ST_MUTEX);
2804 
2805 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2806 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2807 	    st_dev_name(dev), *dev_p, flag, otyp);
2808 
2809 	/*
2810 	 * All device accesss go thru st_strategy() where we check
2811 	 * suspend status
2812 	 */
2813 
2814 	if (!un->un_attached) {
2815 		st_known_tape_type(un);
2816 		if (!un->un_attached) {
2817 			rval = ENXIO;
2818 			goto exit;
2819 		}
2820 
2821 	}
2822 
2823 	/*
2824 	 * Check for the case of the tape in the middle of closing.
2825 	 * This isn't simply a check of the current state, because
2826 	 * we could be in state of sensing with the previous state
2827 	 * that of closing.
2828 	 *
2829 	 * And don't allow multiple opens.
2830 	 */
2831 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2832 		un->un_laststate = un->un_state;
2833 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2834 		while (IS_CLOSING(un) ||
2835 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2836 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2837 				rval = EINTR;
2838 				un->un_state = un->un_laststate;
2839 				goto exit;
2840 			}
2841 		}
2842 	} else if (un->un_state != ST_STATE_CLOSED) {
2843 		rval = EBUSY;
2844 		goto busy;
2845 	}
2846 
2847 	/*
2848 	 * record current dev
2849 	 */
2850 	un->un_dev = dev;
2851 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2852 	un->un_errno = 0;	/* no errors yet */
2853 	un->un_restore_pos = 0;
2854 	un->un_rqs_state = 0;
2855 
2856 	/*
2857 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2858 	 * anything, leave internal states alone, if fileno >= 0
2859 	 */
2860 	if (flag & (FNDELAY | FNONBLOCK)) {
2861 		switch (un->un_pos.pmode) {
2862 
2863 		case invalid:
2864 			un->un_state = ST_STATE_OFFLINE;
2865 			break;
2866 
2867 		case legacy:
2868 			/*
2869 			 * If position is anything other than rewound.
2870 			 */
2871 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2872 				/*
2873 				 * set un_read_only/write-protect status.
2874 				 *
2875 				 * If the tape is not bot we can assume
2876 				 * that mspl->wp_status is set properly.
2877 				 * else
2878 				 * we need to do a mode sense/Tur once
2879 				 * again to get the actual tape status.(since
2880 				 * user might have replaced the tape)
2881 				 * Hence make the st state OFFLINE so that
2882 				 * we re-intialize the tape once again.
2883 				 */
2884 				un->un_read_only =
2885 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2886 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2887 			} else {
2888 				un->un_state = ST_STATE_OFFLINE;
2889 			}
2890 			break;
2891 		case logical:
2892 			if (un->un_pos.lgclblkno == 0) {
2893 				un->un_state = ST_STATE_OFFLINE;
2894 			} else {
2895 				un->un_read_only =
2896 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2897 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2898 			}
2899 			break;
2900 		}
2901 		rval = 0;
2902 	} else {
2903 		/*
2904 		 * Not opening O_NDELAY.
2905 		 */
2906 		un->un_state = ST_STATE_OPENING;
2907 
2908 		/*
2909 		 * Clear error entry stack
2910 		 */
2911 		st_empty_error_stack(un);
2912 
2913 		rval = st_tape_init(un);
2914 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2915 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2916 			rval = 0; /* so open doesn't fail */
2917 		} else if (rval) {
2918 			/*
2919 			 * Release the tape unit, if reserved and not
2920 			 * preserve reserve.
2921 			 */
2922 			if ((un->un_rsvd_status &
2923 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2924 				(void) st_reserve_release(un, ST_RELEASE,
2925 				    st_uscsi_cmd);
2926 			}
2927 		} else {
2928 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2929 		}
2930 	}
2931 
2932 exit:
2933 	/*
2934 	 * we don't want any uninvited guests scrogging our data when we're
2935 	 * busy with something, so for successful opens or failed opens
2936 	 * (except for EBUSY), reset these counters and state appropriately.
2937 	 */
2938 	if (rval != EBUSY) {
2939 		if (rval) {
2940 			un->un_state = ST_STATE_CLOSED;
2941 		}
2942 		un->un_err_resid = 0;
2943 		un->un_retry_ct = 0;
2944 	}
2945 busy:
2946 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2947 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2948 	mutex_exit(ST_MUTEX);
2949 	return (rval);
2950 
2951 }
2952 
2953 static int
2954 st_tape_init(struct scsi_tape *un)
2955 {
2956 	int err;
2957 	int rval = 0;
2958 
2959 	ST_FUNC(ST_DEVINFO, st_tape_init);
2960 
2961 	ASSERT(mutex_owned(ST_MUTEX));
2962 
2963 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2964 	    "st_tape_init(un = 0x%p, oflags = %d)\n", (void*)un, un->un_oflags);
2965 
2966 	/*
2967 	 * Clean up after any errors left by 'last' close.
2968 	 * This also handles the case of the initial open.
2969 	 */
2970 	if (un->un_state != ST_STATE_INITIALIZING) {
2971 		un->un_laststate = un->un_state;
2972 		un->un_state = ST_STATE_OPENING;
2973 	}
2974 
2975 	un->un_kbytes_xferred = 0;
2976 
2977 	/*
2978 	 * do a throw away TUR to clear check condition
2979 	 */
2980 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2981 
2982 	/*
2983 	 * If test unit ready fails because the drive is reserved
2984 	 * by another host fail the open for no access.
2985 	 */
2986 	if (err) {
2987 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2988 			un->un_state = ST_STATE_CLOSED;
2989 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2990 			    "st_tape_init: RESERVATION CONFLICT\n");
2991 			rval = EACCES;
2992 			goto exit;
2993 		} else if ((un->un_rsvd_status &
2994 		    ST_APPLICATION_RESERVATIONS) != 0) {
2995 			if ((ST_RQSENSE != NULL) &&
2996 			    (ST_RQSENSE->es_add_code == 0x2a &&
2997 			    ST_RQSENSE->es_qual_code == 0x03)) {
2998 				un->un_state = ST_STATE_CLOSED;
2999 				rval = EACCES;
3000 				goto exit;
3001 			}
3002 		}
3003 	}
3004 
3005 	/*
3006 	 * Tape self identification could fail if the tape drive is used by
3007 	 * another host during attach time. We try to get the tape type
3008 	 * again. This is also applied to any posponed configuration methods.
3009 	 */
3010 	if (un->un_dp->type == ST_TYPE_INVALID) {
3011 		un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
3012 		st_known_tape_type(un);
3013 	}
3014 
3015 	/*
3016 	 * If the tape type is still invalid, try to determine the generic
3017 	 * configuration.
3018 	 */
3019 	if (un->un_dp->type == ST_TYPE_INVALID) {
3020 		rval = st_determine_generic(un);
3021 		if (rval) {
3022 			if (rval != EACCES) {
3023 				rval = EIO;
3024 			}
3025 			un->un_state = ST_STATE_CLOSED;
3026 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3027 			    "st_tape_init: %s invalid type\n",
3028 			    rval == EACCES ? "EACCES" : "EIO");
3029 			goto exit;
3030 		}
3031 		/*
3032 		 * If this is a Unknown Type drive,
3033 		 * Use the READ BLOCK LIMITS to determine if
3034 		 * allow large xfer is approprate if not globally
3035 		 * disabled with st_allow_large_xfer.
3036 		 */
3037 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
3038 	} else {
3039 
3040 		/*
3041 		 * If we allow_large_xfer (ie >64k) and have not yet found out
3042 		 * the max block size supported by the drive,
3043 		 * find it by issueing a READ_BLKLIM command.
3044 		 * if READ_BLKLIM cmd fails, assume drive doesn't
3045 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
3046 		 */
3047 		un->un_allow_large_xfer = st_allow_large_xfer &&
3048 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
3049 	}
3050 	/*
3051 	 * if maxbsize is unknown, set the maximum block size.
3052 	 */
3053 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
3054 
3055 		/*
3056 		 * Get the Block limits of the tape drive.
3057 		 * if un->un_allow_large_xfer = 0 , then make sure
3058 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
3059 		 */
3060 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
3061 
3062 		err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3063 		if (err) {
3064 			/* Retry */
3065 			err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3066 		}
3067 		if (!err) {
3068 
3069 			/*
3070 			 * if cmd successful, use limit returned
3071 			 */
3072 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
3073 			    (un->un_rbl->max_mid << 8) +
3074 			    un->un_rbl->max_lo;
3075 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
3076 			    un->un_rbl->min_lo;
3077 			un->un_data_mod = 1 << un->un_rbl->granularity;
3078 			if ((un->un_maxbsize == 0) ||
3079 			    (un->un_allow_large_xfer == 0 &&
3080 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
3081 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3082 
3083 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
3084 				/*
3085 				 * Drive is not one that is configured, But the
3086 				 * READ BLOCK LIMITS tells us it can do large
3087 				 * xfers.
3088 				 */
3089 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
3090 					un->un_dp->options |=
3091 					    ST_NO_RECSIZE_LIMIT;
3092 				}
3093 				/*
3094 				 * If max and mimimum block limits are the
3095 				 * same this is a fixed block size device.
3096 				 */
3097 				if (un->un_maxbsize == un->un_minbsize) {
3098 					un->un_dp->options &= ~ST_VARIABLE;
3099 				}
3100 			}
3101 
3102 			if (un->un_minbsize == 0) {
3103 				un->un_minbsize = 1;
3104 			}
3105 
3106 		} else { /* error on read block limits */
3107 
3108 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3109 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
3110 			    " errno = %d un_rsvd_status = 0x%X\n",
3111 			    err, un->un_rsvd_status);
3112 
3113 			/*
3114 			 * since read block limits cmd failed,
3115 			 * do not allow large xfers.
3116 			 * use old values in st_minphys
3117 			 */
3118 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
3119 				rval = EACCES;
3120 			} else {
3121 				un->un_allow_large_xfer = 0;
3122 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3123 				    "!Disabling large transfers\n");
3124 
3125 				/*
3126 				 * we guess maxbsize and minbsize
3127 				 */
3128 				if (un->un_bsize) {
3129 					un->un_maxbsize = un->un_minbsize =
3130 					    un->un_bsize;
3131 				} else {
3132 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3133 					un->un_minbsize = 1;
3134 				}
3135 				/*
3136 				 * Data Mod must be set,
3137 				 * Even if read block limits fails.
3138 				 * Prevents Divide By Zero in st_rw().
3139 				 */
3140 				un->un_data_mod = 1;
3141 			}
3142 		}
3143 		if (un->un_rbl) {
3144 			kmem_free(un->un_rbl, RBLSIZE);
3145 			un->un_rbl = NULL;
3146 		}
3147 
3148 		if (rval) {
3149 			goto exit;
3150 		}
3151 	}
3152 
3153 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3154 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
3155 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
3156 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
3157 
3158 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
3159 
3160 	if (err != 0) {
3161 		if (err == EINTR) {
3162 			un->un_laststate = un->un_state;
3163 			un->un_state = ST_STATE_CLOSED;
3164 			rval = EINTR;
3165 			goto exit;
3166 		}
3167 		/*
3168 		 * Make sure the tape is ready
3169 		 */
3170 		un->un_pos.pmode = invalid;
3171 		if (un->un_status != KEY_UNIT_ATTENTION) {
3172 			/*
3173 			 * allow open no media.  Subsequent MTIOCSTATE
3174 			 * with media present will complete the open
3175 			 * logic.
3176 			 */
3177 			un->un_laststate = un->un_state;
3178 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
3179 				un->un_mediastate = MTIO_EJECTED;
3180 				un->un_state = ST_STATE_OFFLINE;
3181 				rval = 0;
3182 				goto exit;
3183 			} else {
3184 				un->un_state = ST_STATE_CLOSED;
3185 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3186 				    "st_tape_init EIO no media, not opened "
3187 				    "O_NONBLOCK|O_EXCL\n");
3188 				rval = EIO;
3189 				goto exit;
3190 			}
3191 		}
3192 	}
3193 
3194 	/*
3195 	 * On each open, initialize block size from drivetype struct,
3196 	 * as it could have been changed by MTSRSZ ioctl.
3197 	 * Now, ST_VARIABLE simply means drive is capable of variable
3198 	 * mode. All drives are assumed to support fixed records.
3199 	 * Hence, un_bsize tells what mode the drive is in.
3200 	 *	un_bsize	= 0	- variable record length
3201 	 *			= x	- fixed record length is x
3202 	 */
3203 	un->un_bsize = un->un_dp->bsize;
3204 
3205 	/*
3206 	 * If saved position is valid go there
3207 	 */
3208 	if (un->un_restore_pos) {
3209 		un->un_restore_pos = 0;
3210 		un->un_pos.fileno = un->un_save_fileno;
3211 		un->un_pos.blkno = un->un_save_blkno;
3212 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &un->un_pos);
3213 		if (rval != 0) {
3214 			if (rval != EACCES) {
3215 				rval = EIO;
3216 			}
3217 			un->un_laststate = un->un_state;
3218 			un->un_state = ST_STATE_CLOSED;
3219 			goto exit;
3220 		}
3221 	}
3222 
3223 	if (un->un_pos.pmode == invalid) {
3224 		rval = st_loadtape(un);
3225 		if (rval) {
3226 			if (rval != EACCES) {
3227 				rval = EIO;
3228 			}
3229 			un->un_laststate = un->un_state;
3230 			un->un_state = ST_STATE_CLOSED;
3231 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3232 			    "st_tape_init: %s can't open tape\n",
3233 			    rval == EACCES ? "EACCES" : "EIO");
3234 			goto exit;
3235 		}
3236 	}
3237 
3238 	/*
3239 	 * do a mode sense to pick up state of current write-protect,
3240 	 * Could cause reserve and fail due to conflict.
3241 	 */
3242 	if (un->un_unit_attention_flags) {
3243 		rval = st_modesense(un);
3244 		if (rval == EACCES) {
3245 			goto exit;
3246 		}
3247 	}
3248 
3249 	/*
3250 	 * If we are opening the tape for writing, check
3251 	 * to make sure that the tape can be written.
3252 	 */
3253 	if (un->un_oflags & FWRITE) {
3254 		err = 0;
3255 		if (un->un_mspl->wp) {
3256 			un->un_status = KEY_WRITE_PROTECT;
3257 			un->un_laststate = un->un_state;
3258 			un->un_state = ST_STATE_CLOSED;
3259 			rval = EACCES;
3260 			/*
3261 			 * STK sets the wp bit if volsafe tape is loaded.
3262 			 */
3263 			if ((un->un_dp->type == MT_ISSTK9840) &&
3264 			    (un->un_dp->options & ST_WORMABLE)) {
3265 				un->un_read_only = RDONLY;
3266 			} else {
3267 				goto exit;
3268 			}
3269 		} else {
3270 			un->un_read_only = RDWR;
3271 		}
3272 	} else {
3273 		un->un_read_only = RDONLY;
3274 	}
3275 
3276 	if (un->un_dp->options & ST_WORMABLE &&
3277 	    un->un_unit_attention_flags) {
3278 		un->un_read_only |= un->un_wormable(un);
3279 
3280 		if (((un->un_read_only == WORM) ||
3281 		    (un->un_read_only == RDWORM)) &&
3282 		    ((un->un_oflags & FWRITE) == FWRITE)) {
3283 			un->un_status = KEY_DATA_PROTECT;
3284 			rval = EACCES;
3285 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3286 			    "read_only = %d eof = %d oflag = %d\n",
3287 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3288 		}
3289 	}
3290 
3291 	/*
3292 	 * If we're opening the tape write-only, we need to
3293 	 * write 2 filemarks on the HP 1/2 inch drive, to
3294 	 * create a null file.
3295 	 */
3296 	if ((un->un_read_only == RDWR) ||
3297 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3298 		if (un->un_dp->options & ST_REEL) {
3299 			un->un_fmneeded = 2;
3300 		} else {
3301 			un->un_fmneeded = 1;
3302 		}
3303 	} else {
3304 		un->un_fmneeded = 0;
3305 	}
3306 
3307 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3308 	    "fmneeded = %x\n", un->un_fmneeded);
3309 
3310 	/*
3311 	 * Make sure the density can be selected correctly.
3312 	 * If WORM can only write at the append point which in most cases
3313 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3314 	 * to set and try densities if a BOP.
3315 	 */
3316 	if (st_determine_density(un,
3317 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3318 		un->un_status = KEY_ILLEGAL_REQUEST;
3319 		un->un_laststate = un->un_state;
3320 		un->un_state = ST_STATE_CLOSED;
3321 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3322 		    "st_tape_init: EIO can't determine density\n");
3323 		rval = EIO;
3324 		goto exit;
3325 	}
3326 
3327 	/*
3328 	 * Destroy the knowledge that we have 'determined'
3329 	 * density so that a later read at BOT comes along
3330 	 * does the right density determination.
3331 	 */
3332 
3333 	un->un_density_known = 0;
3334 
3335 
3336 	/*
3337 	 * Okay, the tape is loaded and either at BOT or somewhere past.
3338 	 * Mark the state such that any I/O or tape space operations
3339 	 * will get/set the right density, etc..
3340 	 */
3341 	un->un_laststate = un->un_state;
3342 	un->un_lastop = ST_OP_NIL;
3343 	un->un_mediastate = MTIO_INSERTED;
3344 	cv_broadcast(&un->un_state_cv);
3345 
3346 	/*
3347 	 *  Set test append flag if writing.
3348 	 *  First write must check that tape is positioned correctly.
3349 	 */
3350 	un->un_test_append = (un->un_oflags & FWRITE);
3351 
3352 	/*
3353 	 * if there are pending unit attention flags.
3354 	 * Check that the media has not changed.
3355 	 */
3356 	if (un->un_unit_attention_flags) {
3357 		rval = st_get_media_identification(un, st_uscsi_cmd);
3358 		if (rval != 0 && rval != EACCES) {
3359 			rval = EIO;
3360 		}
3361 		un->un_unit_attention_flags = 0;
3362 	}
3363 
3364 exit:
3365 	un->un_err_resid = 0;
3366 	un->un_last_resid = 0;
3367 	un->un_last_count = 0;
3368 
3369 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3370 	    "st_tape_init: return val = %x\n", rval);
3371 	return (rval);
3372 
3373 }
3374 
3375 
3376 
3377 /* ARGSUSED */
3378 static int
3379 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3380 {
3381 	int err = 0;
3382 	int count, last_state;
3383 	minor_t minor = getminor(dev);
3384 #ifdef	__x86
3385 	struct contig_mem *cp, *cp_temp;
3386 #endif
3387 
3388 	GET_SOFT_STATE(dev);
3389 
3390 	ST_ENTR(ST_DEVINFO, st_close);
3391 
3392 	/*
3393 	 * wait till all cmds in the pipeline have been completed
3394 	 */
3395 	mutex_enter(ST_MUTEX);
3396 
3397 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3398 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3399 
3400 	st_wait_for_io(un);
3401 
3402 	/* turn off persistent errors on close, as we want close to succeed */
3403 	st_turn_pe_off(un);
3404 
3405 	/*
3406 	 * set state to indicate that we are in process of closing
3407 	 */
3408 	last_state = un->un_laststate = un->un_state;
3409 	un->un_state = ST_STATE_CLOSING;
3410 
3411 	ST_POS(ST_DEVINFO, "st_close1:", &un->un_pos);
3412 
3413 	/*
3414 	 * BSD behavior:
3415 	 * a close always causes a silent span to the next file if we've hit
3416 	 * an EOF (but not yet read across it).
3417 	 */
3418 	if ((minor & MT_BSD) && (un->un_pos.eof == ST_EOF)) {
3419 		if (un->un_pos.pmode != invalid) {
3420 			un->un_pos.fileno++;
3421 			un->un_pos.blkno = 0;
3422 		}
3423 		un->un_pos.eof = ST_NO_EOF;
3424 	}
3425 
3426 	/*
3427 	 * SVR4 behavior for skipping to next file:
3428 	 *
3429 	 * If we have not seen a filemark, space to the next file
3430 	 *
3431 	 * If we have already seen the filemark we are physically in the next
3432 	 * file and we only increment the filenumber
3433 	 */
3434 	if (((minor & (MT_BSD | MT_NOREWIND)) == MT_NOREWIND) &&
3435 	    (flag & FREAD) &&		/* reading or at least asked to */
3436 	    (un->un_mediastate == MTIO_INSERTED) &&	/* tape loaded */
3437 	    (un->un_pos.pmode != invalid) &&		/* XXX position known */
3438 	    ((un->un_pos.blkno != 0) && 		/* inside a file */
3439 	    (un->un_lastop != ST_OP_WRITE) &&		/* Didn't just write */
3440 	    (un->un_lastop != ST_OP_WEOF))) {		/* or write filemarks */
3441 		switch (un->un_pos.eof) {
3442 		case ST_NO_EOF:
3443 			/*
3444 			 * if we were reading and did not read the complete file
3445 			 * skip to the next file, leaving the tape correctly
3446 			 * positioned to read the first record of the next file
3447 			 * Check first for REEL if we are at EOT by trying to
3448 			 * read a block
3449 			 */
3450 			if ((un->un_dp->options & ST_REEL) &&
3451 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3452 			    (un->un_pos.blkno == 0)) {
3453 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3454 					ST_DEBUG2(ST_DEVINFO, st_label,
3455 					    SCSI_DEBUG,
3456 					    "st_close : EIO can't space\n");
3457 					err = EIO;
3458 					goto error_out;
3459 				}
3460 				if (un->un_pos.eof >= ST_EOF_PENDING) {
3461 					un->un_pos.eof = ST_EOT_PENDING;
3462 					un->un_pos.fileno += 1;
3463 					un->un_pos.blkno   = 0;
3464 					break;
3465 				}
3466 			}
3467 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3468 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3469 				    "st_close: EIO can't space #2\n");
3470 				err = EIO;
3471 				goto error_out;
3472 			} else {
3473 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3474 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3475 				    un->un_pos.fileno, un->un_pos.blkno,
3476 				    un->un_pos.eof);
3477 				un->un_pos.eof = ST_NO_EOF;
3478 			}
3479 			break;
3480 
3481 		case ST_EOF_PENDING:
3482 		case ST_EOF:
3483 			un->un_pos.fileno += 1;
3484 			un->un_pos.lgclblkno += 1;
3485 			un->un_pos.blkno   = 0;
3486 			un->un_pos.eof = ST_NO_EOF;
3487 			break;
3488 
3489 		case ST_EOT:
3490 		case ST_EOT_PENDING:
3491 		case ST_EOM:
3492 			/* nothing to do */
3493 			break;
3494 		default:
3495 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
3496 			    "Undefined state 0x%x", un->un_pos.eof);
3497 
3498 		}
3499 	}
3500 
3501 
3502 	/*
3503 	 * For performance reasons (HP 88780), the driver should
3504 	 * postpone writing the second tape mark until just before a file
3505 	 * positioning ioctl is issued (e.g., rewind).	This means that
3506 	 * the user must not manually rewind the tape because the tape will
3507 	 * be missing the second tape mark which marks EOM.
3508 	 * However, this small performance improvement is not worth the risk.
3509 	 */
3510 
3511 	/*
3512 	 * We need to back up over the filemark we inadvertently popped
3513 	 * over doing a read in between the two filemarks that constitute
3514 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3515 	 * set while reading.
3516 	 *
3517 	 * If we happen to be at physical eot (ST_EOM) (writing case),
3518 	 * the writing of filemark(s) will clear the ST_EOM state, which
3519 	 * we don't want, so we save this state and restore it later.
3520 	 */
3521 
3522 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3523 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3524 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3525 
3526 	if (un->un_pos.eof == ST_EOT_PENDING) {
3527 		if (minor & MT_NOREWIND) {
3528 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3529 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3530 				    "st_close: EIO can't space #3\n");
3531 				err = EIO;
3532 				goto error_out;
3533 			} else {
3534 				un->un_pos.blkno = 0;
3535 				un->un_pos.eof = ST_EOT;
3536 			}
3537 		} else {
3538 			un->un_pos.eof = ST_NO_EOF;
3539 		}
3540 
3541 	/*
3542 	 * Do we need to write a file mark?
3543 	 *
3544 	 * only write filemarks if there are fmks to be written and
3545 	 *   - open for write (possibly read/write)
3546 	 *   - the last operation was a write
3547 	 * or:
3548 	 *   -	opened for wronly
3549 	 *   -	no data was written
3550 	 */
3551 	} else if ((un->un_pos.pmode != invalid) &&
3552 	    (un->un_fmneeded > 0) &&
3553 	    (((flag & FWRITE) &&
3554 	    ((un->un_lastop == ST_OP_WRITE)||(un->un_lastop == ST_OP_WEOF))) ||
3555 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3556 
3557 		/* save ST_EOM state */
3558 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3559 
3560 		/*
3561 		 * Note that we will write a filemark if we had opened
3562 		 * the tape write only and no data was written, thus
3563 		 * creating a null file.
3564 		 *
3565 		 * If the user already wrote one, we only have to write 1 more.
3566 		 * If they wrote two, we don't have to write any.
3567 		 */
3568 
3569 		count = un->un_fmneeded;
3570 		if (count > 0) {
3571 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, count, SYNC_CMD)) {
3572 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3573 				    "st_close : EIO can't wfm\n");
3574 				err = EIO;
3575 				goto error_out;
3576 			}
3577 			if ((un->un_dp->options & ST_REEL) &&
3578 			    (minor & MT_NOREWIND)) {
3579 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3580 					ST_DEBUG2(ST_DEVINFO, st_label,
3581 					    SCSI_DEBUG,
3582 					    "st_close : EIO space fmk(-1)\n");
3583 					err = EIO;
3584 					goto error_out;
3585 				}
3586 				un->un_pos.eof = ST_NO_EOF;
3587 				/* fix up block number */
3588 				un->un_pos.blkno = 0;
3589 			}
3590 		}
3591 
3592 		/*
3593 		 * If we aren't going to be rewinding, and we were at
3594 		 * physical eot, restore the state that indicates we
3595 		 * are at physical eot. Once you have reached physical
3596 		 * eot, and you close the tape, the only thing you can
3597 		 * do on the next open is to rewind. Access to trailer
3598 		 * records is only allowed without closing the device.
3599 		 */
3600 		if ((minor & MT_NOREWIND) == 0 && was_at_eom) {
3601 			un->un_pos.eof = ST_EOM;
3602 		}
3603 	}
3604 
3605 	/*
3606 	 * report soft errors if enabled and available, if we never accessed
3607 	 * the drive, don't get errors. This will prevent some DAT error
3608 	 * messages upon LOG SENSE.
3609 	 */
3610 	if (st_report_soft_errors_on_close &&
3611 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3612 	    (last_state != ST_STATE_OFFLINE)) {
3613 		if (st_report_soft_errors(dev, flag)) {
3614 			err = EIO;
3615 			goto error_out;
3616 		}
3617 	}
3618 
3619 
3620 	/*
3621 	 * Do we need to rewind? Can we rewind?
3622 	 */
3623 	if ((minor & MT_NOREWIND) == 0 &&
3624 	    un->un_pos.pmode != invalid && err == 0) {
3625 		/*
3626 		 * We'd like to rewind with the
3627 		 * 'immediate' bit set, but this
3628 		 * causes problems on some drives
3629 		 * where subsequent opens get a
3630 		 * 'NOT READY' error condition
3631 		 * back while the tape is rewinding,
3632 		 * which is impossible to distinguish
3633 		 * from the condition of 'no tape loaded'.
3634 		 *
3635 		 * Also, for some targets, if you disconnect
3636 		 * with the 'immediate' bit set, you don't
3637 		 * actually return right away, i.e., the
3638 		 * target ignores your request for immediate
3639 		 * return.
3640 		 *
3641 		 * Instead, we'll fire off an async rewind
3642 		 * command. We'll mark the device as closed,
3643 		 * and any subsequent open will stall on
3644 		 * the first TEST_UNIT_READY until the rewind
3645 		 * completes.
3646 		 */
3647 
3648 		/*
3649 		 * Used to be if reserve was not supported we'd send an
3650 		 * asynchronious rewind. Comments above may be slightly invalid
3651 		 * as the immediate bit was never set. Doing an immedate rewind
3652 		 * makes sense, I think fixes to not ready status might handle
3653 		 * the problems described above.
3654 		 */
3655 		if (un->un_sd->sd_inq->inq_ansi < 2) {
3656 			if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
3657 				err = EIO;
3658 			}
3659 		} else {
3660 			/* flush data for older drives per scsi spec. */
3661 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD)) {
3662 				err = EIO;
3663 			} else {
3664 				/* release the drive before rewind immediate */
3665 				if ((un->un_rsvd_status &
3666 				    (ST_RESERVE | ST_PRESERVE_RESERVE)) ==
3667 				    ST_RESERVE) {
3668 					if (st_reserve_release(un, ST_RELEASE,
3669 					    st_uscsi_cmd)) {
3670 						err = EIO;
3671 					}
3672 				}
3673 
3674 				/* send rewind with immediate bit set */
3675 				if (st_cmd(un, SCMD_REWIND, 1, ASYNC_CMD)) {
3676 					err = EIO;
3677 				}
3678 			}
3679 		}
3680 		/*
3681 		 * Setting positions invalid in case the rewind doesn't
3682 		 * happen. Drives don't like to rewind if resets happen
3683 		 * they will tend to move back to where the rewind was
3684 		 * issued if a reset or something happens so that if a
3685 		 * write happens the data doesn't get clobbered.
3686 		 *
3687 		 * Not a big deal if the position is invalid when the
3688 		 * open occures it will do a read position.
3689 		 */
3690 		un->un_pos.pmode = invalid;
3691 		un->un_running.pmode = invalid;
3692 
3693 		if (err == EIO) {
3694 			goto error_out;
3695 		}
3696 	}
3697 
3698 	/*
3699 	 * eject tape if necessary
3700 	 */
3701 	if (un->un_eject_tape_on_failure) {
3702 		un->un_eject_tape_on_failure = 0;
3703 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3704 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3705 			    "st_close : can't unload tape\n");
3706 			err = EIO;
3707 			goto error_out;
3708 		} else {
3709 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3710 			    "st_close : tape unloaded \n");
3711 			un->un_pos.eof = ST_NO_EOF;
3712 			un->un_mediastate = MTIO_EJECTED;
3713 		}
3714 	}
3715 	/*
3716 	 * Release the tape unit, if default reserve/release
3717 	 * behaviour.
3718 	 */
3719 	if ((un->un_rsvd_status &
3720 	    (ST_RESERVE | ST_PRESERVE_RESERVE |
3721 	    ST_APPLICATION_RESERVATIONS)) == ST_RESERVE) {
3722 		(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
3723 	}
3724 error_out:
3725 	/*
3726 	 * clear up state
3727 	 */
3728 	un->un_laststate = un->un_state;
3729 	un->un_state = ST_STATE_CLOSED;
3730 	un->un_lastop = ST_OP_NIL;
3731 	un->un_throttle = 1;	/* assume one request at time, for now */
3732 	un->un_retry_ct = 0;
3733 	un->un_errno = 0;
3734 	un->un_swr_token = (opaque_t)NULL;
3735 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3736 
3737 	/* Restore the options to the init time settings */
3738 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3739 		un->un_dp->options |= ST_READ_IGNORE_ILI;
3740 	} else {
3741 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3742 	}
3743 
3744 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3745 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3746 	} else {
3747 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3748 	}
3749 
3750 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3751 		un->un_dp->options |= ST_SHORT_FILEMARKS;
3752 	} else {
3753 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3754 	}
3755 
3756 	ASSERT(mutex_owned(ST_MUTEX));
3757 
3758 	/*
3759 	 * Signal anyone awaiting a close operation to complete.
3760 	 */
3761 	cv_signal(&un->un_clscv);
3762 
3763 	/*
3764 	 * any kind of error on closing causes all state to be tossed
3765 	 */
3766 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3767 		/*
3768 		 * note that st_intr has already set
3769 		 * un_pos.pmode to invalid.
3770 		 */
3771 		un->un_density_known = 0;
3772 	}
3773 
3774 #ifdef	__x86
3775 	/*
3776 	 * free any contiguous mem alloc'ed for big block I/O
3777 	 */
3778 	cp = un->un_contig_mem;
3779 	while (cp) {
3780 		if (cp->cm_addr) {
3781 			ddi_dma_mem_free(&cp->cm_acc_hdl);
3782 		}
3783 		cp_temp = cp;
3784 		cp = cp->cm_next;
3785 		kmem_free(cp_temp,
3786 		    sizeof (struct contig_mem) + biosize());
3787 	}
3788 	un->un_contig_mem_total_num = 0;
3789 	un->un_contig_mem_available_num = 0;
3790 	un->un_contig_mem = NULL;
3791 	un->un_max_contig_mem_len = 0;
3792 #endif
3793 
3794 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3795 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3796 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3797 
3798 	mutex_exit(ST_MUTEX);
3799 	return (err);
3800 }
3801 
3802 /*
3803  * These routines perform raw i/o operations.
3804  */
3805 
3806 /* ARGSUSED2 */
3807 static int
3808 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3809 {
3810 #ifdef STDEBUG
3811 	GET_SOFT_STATE(dev);
3812 	ST_ENTR(ST_DEVINFO, st_aread);
3813 #endif
3814 	return (st_arw(dev, aio, B_READ));
3815 }
3816 
3817 
3818 /* ARGSUSED2 */
3819 static int
3820 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3821 {
3822 #ifdef STDEBUG
3823 	GET_SOFT_STATE(dev);
3824 	ST_ENTR(ST_DEVINFO, st_awrite);
3825 #endif
3826 	return (st_arw(dev, aio, B_WRITE));
3827 }
3828 
3829 
3830 
3831 /* ARGSUSED */
3832 static int
3833 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3834 {
3835 #ifdef STDEBUG
3836 	GET_SOFT_STATE(dev);
3837 	ST_ENTR(ST_DEVINFO, st_read);
3838 #endif
3839 	return (st_rw(dev, uiop, B_READ));
3840 }
3841 
3842 /* ARGSUSED */
3843 static int
3844 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3845 {
3846 #ifdef STDEBUG
3847 	GET_SOFT_STATE(dev);
3848 	ST_ENTR(ST_DEVINFO, st_write);
3849 #endif
3850 	return (st_rw(dev, uiop, B_WRITE));
3851 }
3852 
3853 /*
3854  * Due to historical reasons, old limits are: For variable-length devices:
3855  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3856  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3857  * (let it through unmodified. For fixed-length record devices:
3858  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3859  *
3860  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3861  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3862  * command to the drive).
3863  *
3864  */
3865 static void
3866 st_minphys(struct buf *bp)
3867 {
3868 	struct scsi_tape *un;
3869 
3870 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3871 
3872 	ST_FUNC(ST_DEVINFO, st_minphys);
3873 
3874 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3875 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3876 	    bp->b_bcount);
3877 
3878 	if (un->un_allow_large_xfer) {
3879 
3880 		/*
3881 		 * check un_maxbsize for variable length devices only
3882 		 */
3883 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3884 			bp->b_bcount = un->un_maxbsize;
3885 		}
3886 		/*
3887 		 * can't go more that HBA maxdma limit in either fixed-length
3888 		 * or variable-length tape drives.
3889 		 */
3890 		if (bp->b_bcount > un->un_maxdma) {
3891 			bp->b_bcount = un->un_maxdma;
3892 		}
3893 	} else {
3894 
3895 		/*
3896 		 *  use old fixed limits
3897 		 */
3898 		if (un->un_bsize == 0) {
3899 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3900 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3901 			}
3902 		} else {
3903 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3904 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3905 			}
3906 		}
3907 	}
3908 
3909 	/*
3910 	 * For regular raw I/O and Fixed Block length devices, make sure
3911 	 * the adjusted block count is a whole multiple of the device
3912 	 * block size.
3913 	 */
3914 	if (bp != un->un_sbufp && un->un_bsize) {
3915 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3916 	}
3917 }
3918 
3919 static int
3920 st_rw(dev_t dev, struct uio *uio, int flag)
3921 {
3922 	int rval = 0;
3923 	long len;
3924 
3925 	GET_SOFT_STATE(dev);
3926 
3927 	ST_FUNC(ST_DEVINFO, st_rw);
3928 
3929 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3930 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3931 	    (flag == B_READ ? rd_str: wr_str));
3932 
3933 	/* get local copy of transfer length */
3934 	len = uio->uio_iov->iov_len;
3935 
3936 	mutex_enter(ST_MUTEX);
3937 
3938 	/*
3939 	 * Clear error entry stack
3940 	 */
3941 	st_empty_error_stack(un);
3942 
3943 	/*
3944 	 * If in fixed block size mode and requested read or write
3945 	 * is not an even multiple of that block size.
3946 	 */
3947 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3948 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3949 		    "%s: not modulo %d block size\n",
3950 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3951 		rval = EINVAL;
3952 	}
3953 
3954 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3955 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3956 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3957 		    "%s: not modulo %d device granularity\n",
3958 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3959 		rval = EINVAL;
3960 	}
3961 
3962 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
3963 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
3964 		rval = EFAULT;
3965 	}
3966 
3967 	if (rval != 0) {
3968 		un->un_errno = rval;
3969 		mutex_exit(ST_MUTEX);
3970 		return (rval);
3971 	}
3972 
3973 	/*
3974 	 * Reset this so it can be set if Berkeley and read over a filemark.
3975 	 */
3976 	un->un_silent_skip = 0;
3977 	mutex_exit(ST_MUTEX);
3978 
3979 	len = uio->uio_resid;
3980 
3981 	rval = physio(st_queued_strategy, (struct buf *)NULL,
3982 	    dev, flag, st_minphys, uio);
3983 	/*
3984 	 * if we have hit logical EOT during this xfer and there is not a
3985 	 * full residue, then set eof back  to ST_EOM to make sure that
3986 	 * the user will see at least one zero write
3987 	 * after this short write
3988 	 */
3989 	mutex_enter(ST_MUTEX);
3990 	if (un->un_pos.eof > ST_NO_EOF) {
3991 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3992 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3993 	}
3994 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3995 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3996 			un->un_pos.eof = ST_EOM;
3997 		} else if (uio->uio_resid == len) {
3998 			un->un_pos.eof = ST_NO_EOF;
3999 		}
4000 	}
4001 
4002 	if (un->un_silent_skip && uio->uio_resid != len) {
4003 		un->un_pos.eof = ST_EOF;
4004 		un->un_pos.blkno = un->un_save_blkno;
4005 		un->un_pos.fileno--;
4006 	}
4007 
4008 	un->un_errno = rval;
4009 
4010 	mutex_exit(ST_MUTEX);
4011 
4012 	return (rval);
4013 }
4014 
4015 static int
4016 st_arw(dev_t dev, struct aio_req *aio, int flag)
4017 {
4018 	struct uio *uio = aio->aio_uio;
4019 	int rval = 0;
4020 	long len;
4021 
4022 	GET_SOFT_STATE(dev);
4023 
4024 	ST_FUNC(ST_DEVINFO, st_arw);
4025 
4026 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4027 	    "st_arw(dev = 0x%lx, flag = %s)\n", dev,
4028 	    (flag == B_READ ? rd_str: wr_str));
4029 
4030 	/* get local copy of transfer length */
4031 	len = uio->uio_iov->iov_len;
4032 
4033 	mutex_enter(ST_MUTEX);
4034 
4035 	/*
4036 	 * If in fixed block size mode and requested read or write
4037 	 * is not an even multiple of that block size.
4038 	 */
4039 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
4040 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4041 		    "%s: not modulo %d block size\n",
4042 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
4043 		rval = EINVAL;
4044 	}
4045 
4046 	/* If device has set granularity in the READ_BLKLIM we honor it. */
4047 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
4048 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4049 		    "%s: not modulo %d device granularity\n",
4050 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
4051 		rval = EINVAL;
4052 	}
4053 
4054 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
4055 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
4056 		rval = EFAULT;
4057 	}
4058 
4059 	if (rval != 0) {
4060 		un->un_errno = rval;
4061 		mutex_exit(ST_MUTEX);
4062 		return (rval);
4063 	}
4064 
4065 	mutex_exit(ST_MUTEX);
4066 
4067 	len = uio->uio_resid;
4068 
4069 	rval =
4070 	    aphysio(st_queued_strategy, anocancel, dev, flag, st_minphys, aio);
4071 
4072 	/*
4073 	 * if we have hit logical EOT during this xfer and there is not a
4074 	 * full residue, then set eof back  to ST_EOM to make sure that
4075 	 * the user will see at least one zero write
4076 	 * after this short write
4077 	 *
4078 	 * we keep this here just in case the application is not using
4079 	 * persistent errors
4080 	 */
4081 	mutex_enter(ST_MUTEX);
4082 	if (un->un_pos.eof > ST_NO_EOF) {
4083 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4084 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
4085 	}
4086 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
4087 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
4088 			un->un_pos.eof = ST_EOM;
4089 		} else if (uio->uio_resid == len &&
4090 		    !(un->un_persistence && un->un_persist_errors)) {
4091 			un->un_pos.eof = ST_NO_EOF;
4092 		}
4093 	}
4094 	un->un_errno = rval;
4095 	mutex_exit(ST_MUTEX);
4096 
4097 	return (rval);
4098 }
4099 
4100 
4101 
4102 static int
4103 st_queued_strategy(buf_t *bp)
4104 {
4105 	struct scsi_tape *un;
4106 	char reading = bp->b_flags & B_READ;
4107 	int wasopening = 0;
4108 
4109 	/*
4110 	 * validate arguments
4111 	 */
4112 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4113 	if (un == NULL) {
4114 		bp->b_resid = bp->b_bcount;
4115 		bioerror(bp, ENXIO);
4116 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4117 		    "st_queued_strategy: ENXIO error exit\n");
4118 		biodone(bp);
4119 		return (0);
4120 	}
4121 
4122 	ST_ENTR(ST_DEVINFO, st_queued_strategy);
4123 
4124 	mutex_enter(ST_MUTEX);
4125 
4126 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4127 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4128 	}
4129 
4130 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4131 	    "st_queued_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4132 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4133 
4134 	/*
4135 	 * If persistent errors have been flagged, just nix this one. We wait
4136 	 * for any outstanding I/O's below, so we will be in order.
4137 	 */
4138 	if (un->un_persistence && un->un_persist_errors) {
4139 		goto exit;
4140 	}
4141 
4142 	/*
4143 	 * If last command was non queued, wait till it finishes.
4144 	 */
4145 	while (un->un_sbuf_busy) {
4146 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
4147 		/* woke up because of an error */
4148 		if (un->un_persistence && un->un_persist_errors) {
4149 			goto exit;
4150 		}
4151 	}
4152 
4153 	/*
4154 	 * s_buf and recovery commands shouldn't come here.
4155 	 */
4156 	ASSERT(bp != un->un_recov_buf);
4157 	ASSERT(bp != un->un_sbufp);
4158 
4159 	/*
4160 	 * If we haven't done/checked reservation on the tape unit
4161 	 * do it now.
4162 	 */
4163 	if ((un->un_rsvd_status &
4164 	    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
4165 		if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
4166 			if (st_reserve_release(un, ST_RESERVE, st_uscsi_cmd)) {
4167 				st_bioerror(bp, un->un_errno);
4168 				goto exit;
4169 			}
4170 		} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4171 			/*
4172 			 * Enter here to restore position for possible
4173 			 * resets when the device was closed and opened
4174 			 * in O_NDELAY mode subsequently
4175 			 */
4176 			un->un_state = ST_STATE_INITIALIZING;
4177 			(void) st_cmd(un, SCMD_TEST_UNIT_READY,
4178 			    0, SYNC_CMD);
4179 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4180 		}
4181 		un->un_rsvd_status |= ST_INIT_RESERVE;
4182 	}
4183 
4184 	/*
4185 	 * If we are offline, we have to initialize everything first.
4186 	 * This is to handle either when opened with O_NDELAY, or
4187 	 * we just got a new tape in the drive, after an offline.
4188 	 * We don't observe O_NDELAY past the open,
4189 	 * as it will not make sense for tapes.
4190 	 */
4191 	if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
4192 		/*
4193 		 * reset state to avoid recursion
4194 		 */
4195 		un->un_laststate = un->un_state;
4196 		un->un_state = ST_STATE_INITIALIZING;
4197 		if (st_tape_init(un)) {
4198 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4199 			    "stioctl : OFFLINE init failure ");
4200 			un->un_state = ST_STATE_OFFLINE;
4201 			un->un_pos.pmode = invalid;
4202 			goto b_done_err;
4203 		}
4204 		/* un_restore_pos make invalid */
4205 		un->un_state = ST_STATE_OPEN_PENDING_IO;
4206 		un->un_restore_pos = 0;
4207 	}
4208 	/*
4209 	 * Check for legal operations
4210 	 */
4211 	if (un->un_pos.pmode == invalid) {
4212 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4213 		    "strategy with un->un_pos.pmode invalid\n");
4214 		goto b_done_err;
4215 	}
4216 
4217 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4218 	    "st_queued_strategy(): regular io\n");
4219 
4220 	/*
4221 	 * Process this first. If we were reading, and we're pending
4222 	 * logical eot, that means we've bumped one file mark too far.
4223 	 */
4224 
4225 	/*
4226 	 * Recursion warning: st_cmd will route back through here.
4227 	 * Not anymore st_cmd will go through st_strategy()!
4228 	 */
4229 	if (un->un_pos.eof == ST_EOT_PENDING) {
4230 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4231 			un->un_pos.pmode = invalid;
4232 			un->un_density_known = 0;
4233 			goto b_done_err;
4234 		}
4235 		un->un_pos.blkno = 0; /* fix up block number.. */
4236 		un->un_pos.eof = ST_EOT;
4237 	}
4238 
4239 	/*
4240 	 * If we are in the process of opening, we may have to
4241 	 * determine/set the correct density. We also may have
4242 	 * to do a test_append (if QIC) to see whether we are
4243 	 * in a position to append to the end of the tape.
4244 	 *
4245 	 * If we're already at logical eot, we transition
4246 	 * to ST_NO_EOF. If we're at physical eot, we punt
4247 	 * to the switch statement below to handle.
4248 	 */
4249 	if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
4250 	    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
4251 
4252 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4253 			if (st_determine_density(un, (int)reading)) {
4254 				goto b_done_err;
4255 			}
4256 		}
4257 
4258 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4259 		    "pending_io@fileno %d rw %d qic %d eof %d\n",
4260 		    un->un_pos.fileno, (int)reading,
4261 		    (un->un_dp->options & ST_QIC) ? 1 : 0,
4262 		    un->un_pos.eof);
4263 
4264 		if (!reading && un->un_pos.eof != ST_EOM) {
4265 			if (un->un_pos.eof == ST_EOT) {
4266 				un->un_pos.eof = ST_NO_EOF;
4267 			} else if (un->un_pos.pmode != invalid &&
4268 			    (un->un_dp->options & ST_QIC)) {
4269 				/*
4270 				 * st_test_append() will do it all
4271 				 */
4272 				st_test_append(bp);
4273 				mutex_exit(ST_MUTEX);
4274 				return (0);
4275 			}
4276 		}
4277 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4278 			wasopening = 1;
4279 		}
4280 		un->un_laststate = un->un_state;
4281 		un->un_state = ST_STATE_OPEN;
4282 	}
4283 
4284 
4285 	/*
4286 	 * Process rest of END OF FILE and END OF TAPE conditions
4287 	 */
4288 
4289 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4290 	    "eof=%x, wasopening=%x\n",
4291 	    un->un_pos.eof, wasopening);
4292 
4293 	switch (un->un_pos.eof) {
4294 	case ST_EOM:
4295 		/*
4296 		 * This allows writes to proceed past physical
4297 		 * eot. We'll *really* be in trouble if the
4298 		 * user continues blindly writing data too
4299 		 * much past this point (unwind the tape).
4300 		 * Physical eot really means 'early warning
4301 		 * eot' in this context.
4302 		 *
4303 		 * Every other write from now on will succeed
4304 		 * (if sufficient  tape left).
4305 		 * This write will return with resid == count
4306 		 * but the next one should be successful
4307 		 *
4308 		 * Note that we only transition to logical EOT
4309 		 * if the last state wasn't the OPENING state.
4310 		 * We explicitly prohibit running up to physical
4311 		 * eot, closing the device, and then re-opening
4312 		 * to proceed. Trailer records may only be gotten
4313 		 * at by keeping the tape open after hitting eot.
4314 		 *
4315 		 * Also note that ST_EOM cannot be set by reading-
4316 		 * this can only be set during writing. Reading
4317 		 * up to the end of the tape gets a blank check
4318 		 * or a double-filemark indication (ST_EOT_PENDING),
4319 		 * and we prohibit reading after that point.
4320 		 *
4321 		 */
4322 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
4323 		if (wasopening == 0) {
4324 			/*
4325 			 * this allows st_rw() to reset it back to
4326 			 * will see a zero write
4327 			 */
4328 			un->un_pos.eof = ST_WRITE_AFTER_EOM;
4329 		}
4330 		un->un_status = SUN_KEY_EOT;
4331 		goto b_done;
4332 
4333 	case ST_WRITE_AFTER_EOM:
4334 	case ST_EOT:
4335 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
4336 		un->un_status = SUN_KEY_EOT;
4337 		if (SVR4_BEHAVIOR && reading) {
4338 			goto b_done_err;
4339 		}
4340 
4341 		if (reading) {
4342 			goto b_done;
4343 		}
4344 		un->un_pos.eof = ST_NO_EOF;
4345 		break;
4346 
4347 	case ST_EOF_PENDING:
4348 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4349 		    "EOF PENDING\n");
4350 		un->un_status = SUN_KEY_EOF;
4351 		if (SVR4_BEHAVIOR) {
4352 			un->un_pos.eof = ST_EOF;
4353 			goto b_done;
4354 		}
4355 		/* FALLTHROUGH */
4356 	case ST_EOF:
4357 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
4358 		un->un_status = SUN_KEY_EOF;
4359 		if (SVR4_BEHAVIOR) {
4360 			goto b_done_err;
4361 		}
4362 
4363 		if (BSD_BEHAVIOR) {
4364 			un->un_pos.eof = ST_NO_EOF;
4365 			un->un_pos.fileno += 1;
4366 			un->un_pos.blkno   = 0;
4367 		}
4368 
4369 		if (reading) {
4370 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4371 			    "now file %d (read)\n",
4372 			    un->un_pos.fileno);
4373 			goto b_done;
4374 		}
4375 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4376 		    "now file %d (write)\n", un->un_pos.fileno);
4377 		break;
4378 	default:
4379 		un->un_status = 0;
4380 		break;
4381 	}
4382 
4383 	bp->b_flags &= ~(B_DONE);
4384 	st_bioerror(bp, 0);
4385 	bp->av_forw = NULL;
4386 	bp->b_resid = 0;
4387 	SET_BP_PKT(bp, 0);
4388 
4389 
4390 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4391 	    "st_queued_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4392 	    " pkt=0x%p\n",
4393 	    (void *)bp->b_forw, bp->b_bcount,
4394 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4395 
4396 #ifdef	__x86
4397 	/*
4398 	 * We will replace bp with a new bp that can do big blk xfer
4399 	 * if the requested xfer size is bigger than un->un_maxdma_arch
4400 	 *
4401 	 * Also, we need to make sure that we're handling real I/O
4402 	 * by checking group 0/1 SCSI I/O commands, if needed
4403 	 */
4404 	if (bp->b_bcount > un->un_maxdma_arch &&
4405 	    ((uchar_t)(uintptr_t)bp->b_forw == SCMD_READ ||
4406 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G4 ||
4407 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE ||
4408 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G4)) {
4409 		mutex_exit(ST_MUTEX);
4410 		bp = st_get_bigblk_bp(bp);
4411 		mutex_enter(ST_MUTEX);
4412 	}
4413 #endif
4414 
4415 	/* put on wait queue */
4416 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4417 	    "st_queued_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4418 	    (void *)un->un_quef, (void *)bp);
4419 
4420 	st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quel, bp);
4421 
4422 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4423 
4424 	st_start(un);
4425 
4426 	mutex_exit(ST_MUTEX);
4427 	return (0);
4428 
4429 b_done_err:
4430 	st_bioerror(bp, EIO);
4431 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4432 	    "st_queued_strategy : EIO b_done_err\n");
4433 
4434 b_done:
4435 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4436 	    "st_queued_strategy: b_done\n");
4437 
4438 exit:
4439 	/*
4440 	 * make sure no commands are outstanding or waiting before closing,
4441 	 * so we can guarantee order
4442 	 */
4443 	st_wait_for_io(un);
4444 	un->un_err_resid = bp->b_resid = bp->b_bcount;
4445 
4446 	/* override errno here, if persistent errors were flagged */
4447 	if (un->un_persistence && un->un_persist_errors)
4448 		bioerror(bp, un->un_errno);
4449 
4450 	mutex_exit(ST_MUTEX);
4451 
4452 	biodone(bp);
4453 	ASSERT(mutex_owned(ST_MUTEX) == 0);
4454 	return (0);
4455 }
4456 
4457 
4458 static int
4459 st_strategy(struct buf *bp)
4460 {
4461 	struct scsi_tape *un;
4462 
4463 	/*
4464 	 * validate arguments
4465 	 */
4466 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4467 	if (un == NULL) {
4468 		bp->b_resid = bp->b_bcount;
4469 		bioerror(bp, ENXIO);
4470 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4471 		    "st_strategy: ENXIO error exit\n");
4472 
4473 		biodone(bp);
4474 		return (0);
4475 
4476 	}
4477 
4478 	ST_ENTR(ST_DEVINFO, st_strategy);
4479 
4480 	mutex_enter(ST_MUTEX);
4481 
4482 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4483 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4484 	}
4485 
4486 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4487 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4488 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4489 
4490 	ASSERT((bp == un->un_recov_buf) || (bp == un->un_sbufp));
4491 
4492 	bp->b_flags &= ~(B_DONE);
4493 	st_bioerror(bp, 0);
4494 	bp->av_forw = NULL;
4495 	bp->b_resid = 0;
4496 	SET_BP_PKT(bp, 0);
4497 
4498 
4499 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4500 	    "st_strategy: cmd=0x%x  count=%ld  resid=%ld flags=0x%x"
4501 	    " pkt=0x%p\n",
4502 	    (unsigned char)(uintptr_t)bp->b_forw, bp->b_bcount,
4503 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4504 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4505 
4506 	st_start(un);
4507 
4508 	mutex_exit(ST_MUTEX);
4509 	return (0);
4510 }
4511 
4512 /*
4513  * this routine spaces forward over filemarks
4514  */
4515 static int
4516 st_space_fmks(struct scsi_tape *un, int64_t count)
4517 {
4518 	int rval = 0;
4519 
4520 	ST_FUNC(ST_DEVINFO, st_space_fmks);
4521 
4522 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4523 	    "st_space_fmks(dev = 0x%lx, count = %"PRIx64")\n",
4524 	    un->un_dev, count);
4525 
4526 	ASSERT(mutex_owned(ST_MUTEX));
4527 
4528 	/*
4529 	 * the risk with doing only one space operation is that we
4530 	 * may accidentily jump in old data
4531 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4532 	 * because the 8200 does not append a marker; in order not to
4533 	 * sacrifice the fast file skip, we do a slow skip if the low
4534 	 * density device has been opened
4535 	 */
4536 
4537 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4538 	    !((un->un_dp->type == ST_TYPE_EXB8500 &&
4539 	    MT_DENSITY(un->un_dev) == 0))) {
4540 		if (st_cmd(un, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4541 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4542 			    "space_fmks : EIO can't do space cmd #1\n");
4543 			rval = EIO;
4544 		}
4545 	} else {
4546 		while (count > 0) {
4547 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4548 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4549 				    "space_fmks : EIO can't do space cmd #2\n");
4550 				rval = EIO;
4551 				break;
4552 			}
4553 			count -= 1;
4554 			/*
4555 			 * read a block to see if we have reached
4556 			 * end of medium (double filemark for reel or
4557 			 * medium error for others)
4558 			 */
4559 			if (count > 0) {
4560 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
4561 					ST_DEBUG2(ST_DEVINFO, st_label,
4562 					    SCSI_DEBUG,
4563 					    "space_fmks : EIO can't do "
4564 					    "space cmd #3\n");
4565 					rval = EIO;
4566 					break;
4567 				}
4568 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4569 				    (un->un_dp->options & ST_REEL)) {
4570 					un->un_status = SUN_KEY_EOT;
4571 					ST_DEBUG2(ST_DEVINFO, st_label,
4572 					    SCSI_DEBUG,
4573 					    "space_fmks : EIO ST_REEL\n");
4574 					rval = EIO;
4575 					break;
4576 				} else if (IN_EOF(un->un_pos)) {
4577 					un->un_pos.eof = ST_NO_EOF;
4578 					un->un_pos.fileno++;
4579 					un->un_pos.blkno = 0;
4580 					count--;
4581 				} else if (un->un_pos.eof > ST_EOF) {
4582 					ST_DEBUG2(ST_DEVINFO, st_label,
4583 					    SCSI_DEBUG,
4584 					    "space_fmks, EIO > ST_EOF\n");
4585 					rval = EIO;
4586 					break;
4587 				}
4588 
4589 			}
4590 		}
4591 		un->un_err_resid = count;
4592 		COPY_POS(&un->un_pos, &un->un_err_pos);
4593 	}
4594 	ASSERT(mutex_owned(ST_MUTEX));
4595 	return (rval);
4596 }
4597 
4598 /*
4599  * this routine spaces to EOD
4600  *
4601  * it keeps track of the current filenumber and returns the filenumber after
4602  * the last successful space operation, we keep the number high because as
4603  * tapes are getting larger, the possibility of more and more files exist,
4604  * 0x100000 (1 Meg of files) probably will never have to be changed any time
4605  * soon
4606  */
4607 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4608 
4609 static int
4610 st_find_eod(struct scsi_tape *un)
4611 {
4612 	tapepos_t savepos;
4613 	int64_t sp_type;
4614 	int result;
4615 
4616 	if (un == NULL) {
4617 		return (-1);
4618 	}
4619 
4620 	ST_FUNC(ST_DEVINFO, st_find_eod);
4621 
4622 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4623 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", un->un_dev,
4624 	    un->un_pos.fileno);
4625 
4626 	ASSERT(mutex_owned(ST_MUTEX));
4627 
4628 	COPY_POS(&savepos, &un->un_pos);
4629 
4630 	/*
4631 	 * see if the drive is smart enough to do the skips in
4632 	 * one operation; 1/2" use two filemarks
4633 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4634 	 * because the 8200 does not append a marker; in order not to
4635 	 * sacrifice the fast file skip, we do a slow skip if the low
4636 	 * density device has been opened
4637 	 */
4638 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4639 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4640 		    (MT_DENSITY(un->un_dev) == 0)) {
4641 			sp_type = Fmk(1);
4642 		} else if (un->un_pos.pmode == logical) {
4643 			sp_type = SPACE(SP_EOD, 0);
4644 		} else {
4645 			sp_type = Fmk(MAX_SKIP);
4646 		}
4647 	} else {
4648 		sp_type = Fmk(1);
4649 	}
4650 
4651 	for (;;) {
4652 		result = st_cmd(un, SCMD_SPACE, sp_type, SYNC_CMD);
4653 
4654 		if (result == 0) {
4655 			COPY_POS(&savepos, &un->un_pos);
4656 		}
4657 
4658 		if (sp_type == SPACE(SP_EOD, 0)) {
4659 			if (result != 0) {
4660 				sp_type = Fmk(MAX_SKIP);
4661 				continue;
4662 			}
4663 
4664 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4665 			    "st_find_eod: 0x%"PRIx64"\n",
4666 			    savepos.lgclblkno);
4667 			/*
4668 			 * What we return will become the current file position.
4669 			 * After completing the space command with the position
4670 			 * mode that is not invalid a read position command will
4671 			 * be automaticly issued. If the drive support the long
4672 			 * read position format a valid file position can be
4673 			 * returned.
4674 			 */
4675 			return (un->un_pos.fileno);
4676 		}
4677 
4678 		if (result != 0) {
4679 			break;
4680 		}
4681 
4682 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4683 		    "count=%"PRIx64", eof=%x, status=%x\n",
4684 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4685 
4686 		/*
4687 		 * If we're not EOM smart,  space a record
4688 		 * to see whether we're now in the slot between
4689 		 * the two sequential filemarks that logical
4690 		 * EOM consists of (REEL) or hit nowhere land
4691 		 * (8mm).
4692 		 */
4693 		if (sp_type == Fmk(1)) {
4694 			/*
4695 			 * no fast skipping, check a record
4696 			 */
4697 			if (st_cmd(un, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4698 				break;
4699 			}
4700 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4701 			    (un->un_dp->options & ST_REEL)) {
4702 				un->un_status = KEY_BLANK_CHECK;
4703 				un->un_pos.fileno++;
4704 				un->un_pos.blkno = 0;
4705 				break;
4706 			}
4707 			if (IN_EOF(un->un_pos)) {
4708 				un->un_pos.eof = ST_NO_EOF;
4709 				un->un_pos.fileno++;
4710 				un->un_pos.blkno = 0;
4711 			}
4712 			if (un->un_pos.eof > ST_EOF) {
4713 				break;
4714 			}
4715 		} else {
4716 			if (un->un_pos.eof > ST_EOF) {
4717 				break;
4718 			}
4719 		}
4720 	}
4721 
4722 	if (un->un_dp->options & ST_KNOWS_EOD) {
4723 		COPY_POS(&savepos, &un->un_pos);
4724 	}
4725 
4726 	ASSERT(mutex_owned(ST_MUTEX));
4727 
4728 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4729 	    "st_find_eod: %x\n", savepos.fileno);
4730 	return (savepos.fileno);
4731 }
4732 
4733 
4734 /*
4735  * this routine is frequently used in ioctls below;
4736  * it determines whether we know the density and if not will
4737  * determine it
4738  * if we have written the tape before, one or more filemarks are written
4739  *
4740  * depending on the stepflag, the head is repositioned to where it was before
4741  * the filemarks were written in order not to confuse step counts
4742  */
4743 #define	STEPBACK    0
4744 #define	NO_STEPBACK 1
4745 
4746 static int
4747 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4748 {
4749 
4750 	GET_SOFT_STATE(dev);
4751 
4752 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4753 
4754 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4755 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4756 	    "\n", dev, wfm, mode, stepflag);
4757 
4758 	ASSERT(mutex_owned(ST_MUTEX));
4759 
4760 	/*
4761 	 * If we don't yet know the density of the tape we have inserted,
4762 	 * we have to either unconditionally set it (if we're 'writing'),
4763 	 * or we have to determine it. As side effects, check for any
4764 	 * write-protect errors, and for the need to put out any file-marks
4765 	 * before positioning a tape.
4766 	 *
4767 	 * If we are going to be spacing forward, and we haven't determined
4768 	 * the tape density yet, we have to do so now...
4769 	 */
4770 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4771 		if (st_determine_density(un, mode)) {
4772 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4773 			    "check_density_or_wfm : EIO can't determine "
4774 			    "density\n");
4775 			un->un_errno = EIO;
4776 			return (EIO);
4777 		}
4778 		/*
4779 		 * Presumably we are at BOT. If we attempt to write, it will
4780 		 * either work okay, or bomb. We don't do a st_test_append
4781 		 * unless we're past BOT.
4782 		 */
4783 		un->un_laststate = un->un_state;
4784 		un->un_state = ST_STATE_OPEN;
4785 
4786 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4787 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4788 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4789 
4790 		tapepos_t spos;
4791 
4792 		COPY_POS(&spos, &un->un_pos);
4793 
4794 		/*
4795 		 * We need to write one or two filemarks.
4796 		 * In the case of the HP, we need to
4797 		 * position the head between the two
4798 		 * marks.
4799 		 */
4800 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4801 			wfm = un->un_fmneeded;
4802 			un->un_fmneeded = 0;
4803 		}
4804 
4805 		if (st_write_fm(dev, wfm)) {
4806 			un->un_pos.pmode = invalid;
4807 			un->un_density_known = 0;
4808 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4809 			    "check_density_or_wfm : EIO can't write fm\n");
4810 			un->un_errno = EIO;
4811 			return (EIO);
4812 		}
4813 
4814 		if (stepflag == STEPBACK) {
4815 			if (st_cmd(un, SCMD_SPACE, Fmk(-wfm), SYNC_CMD)) {
4816 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4817 				    "check_density_or_wfm : EIO can't space "
4818 				    "(-wfm)\n");
4819 				un->un_errno = EIO;
4820 				return (EIO);
4821 			}
4822 			COPY_POS(&un->un_pos, &spos);
4823 		}
4824 	}
4825 
4826 	/*
4827 	 * Whatever we do at this point clears the state of the eof flag.
4828 	 */
4829 
4830 	un->un_pos.eof = ST_NO_EOF;
4831 
4832 	/*
4833 	 * If writing, let's check that we're positioned correctly
4834 	 * at the end of tape before issuing the next write.
4835 	 */
4836 	if (un->un_read_only == RDWR) {
4837 		un->un_test_append = 1;
4838 	}
4839 
4840 	ASSERT(mutex_owned(ST_MUTEX));
4841 	return (0);
4842 }
4843 
4844 
4845 /*
4846  * Wait for all outstaning I/O's to complete
4847  *
4848  * we wait on both ncmds and the wait queue for times when we are flushing
4849  * after persistent errors are flagged, which is when ncmds can be 0, and the
4850  * queue can still have I/O's.  This way we preserve order of biodone's.
4851  */
4852 static void
4853 st_wait_for_io(struct scsi_tape *un)
4854 {
4855 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4856 	ASSERT(mutex_owned(ST_MUTEX));
4857 	while ((un->un_ncmds) || (un->un_quef) || (un->un_runqf)) {
4858 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4859 	}
4860 }
4861 
4862 /*
4863  * This routine implements the ioctl calls.  It is called
4864  * from the device switch at normal priority.
4865  */
4866 /*ARGSUSED*/
4867 static int
4868 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4869     int *rval_p)
4870 {
4871 	int tmp, rval = 0;
4872 
4873 	GET_SOFT_STATE(dev);
4874 
4875 	ST_ENTR(ST_DEVINFO, st_ioctl);
4876 
4877 	mutex_enter(ST_MUTEX);
4878 
4879 	ASSERT(un->un_recov_buf_busy == 0);
4880 
4881 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4882 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4883 	    "pe_flag = %d\n",
4884 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4885 	    un->un_persistence && un->un_persist_errors);
4886 
4887 	/*
4888 	 * We don't want to block on these, so let them through
4889 	 * and we don't care about setting driver states here.
4890 	 */
4891 	if ((cmd == MTIOCGETDRIVETYPE) ||
4892 	    (cmd == MTIOCGUARANTEEDORDER) ||
4893 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4894 		goto check_commands;
4895 	}
4896 
4897 	/*
4898 	 * We clear error entry stack except command
4899 	 * MTIOCGETERROR and MTIOCGET
4900 	 */
4901 	if ((cmd != MTIOCGETERROR) &&
4902 	    (cmd != MTIOCGET)) {
4903 		st_empty_error_stack(un);
4904 	}
4905 
4906 	/*
4907 	 * wait for all outstanding commands to complete, or be dequeued.
4908 	 * And because ioctl's are synchronous commands, any return value
4909 	 * after this,  will be in order
4910 	 */
4911 	st_wait_for_io(un);
4912 
4913 	/*
4914 	 * allow only a through clear errors and persistent status, and
4915 	 * status
4916 	 */
4917 	if (un->un_persistence && un->un_persist_errors) {
4918 		if ((cmd == MTIOCLRERR) ||
4919 		    (cmd == MTIOCPERSISTENT) ||
4920 		    (cmd == MTIOCGET)) {
4921 			goto check_commands;
4922 		} else {
4923 			rval = un->un_errno;
4924 			goto exit;
4925 		}
4926 	}
4927 
4928 	ASSERT(un->un_throttle != 0);
4929 	un->un_throttle = 1;	/* > 1 will never happen here */
4930 	un->un_errno = 0;	/* start clean from here */
4931 
4932 	/*
4933 	 * first and foremost, handle any ST_EOT_PENDING cases.
4934 	 * That is, if a logical eot is pending notice, notice it.
4935 	 */
4936 	if (un->un_pos.eof == ST_EOT_PENDING) {
4937 		int resid = un->un_err_resid;
4938 		uchar_t status = un->un_status;
4939 		uchar_t lastop = un->un_lastop;
4940 
4941 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4942 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4943 			    "stioctl : EIO can't space fmk(-1)\n");
4944 			rval = EIO;
4945 			goto exit;
4946 		}
4947 		un->un_lastop = lastop; /* restore last operation */
4948 		if (status == SUN_KEY_EOF) {
4949 			un->un_status = SUN_KEY_EOT;
4950 		} else {
4951 			un->un_status = status;
4952 		}
4953 		un->un_err_resid  = resid;
4954 		/* fix up block number */
4955 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4956 		/* now we're at logical eot */
4957 		un->un_pos.eof = ST_EOT;
4958 	}
4959 
4960 	/*
4961 	 * now, handle the rest of the situations
4962 	 */
4963 check_commands:
4964 	switch (cmd) {
4965 	case MTIOCGET:
4966 	{
4967 #ifdef _MULTI_DATAMODEL
4968 		/*
4969 		 * For use when a 32 bit app makes a call into a
4970 		 * 64 bit ioctl
4971 		 */
4972 		struct mtget32		mtg_local32;
4973 		struct mtget32 		*mtget_32 = &mtg_local32;
4974 #endif /* _MULTI_DATAMODEL */
4975 
4976 			/* Get tape status */
4977 		struct mtget mtg_local;
4978 		struct mtget *mtget = &mtg_local;
4979 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4980 		    "st_ioctl: MTIOCGET\n");
4981 
4982 		bzero((caddr_t)mtget, sizeof (struct mtget));
4983 		mtget->mt_erreg = un->un_status;
4984 		mtget->mt_resid = un->un_err_resid;
4985 		mtget->mt_dsreg = un->un_retry_ct;
4986 		if (un->un_err_pos.pmode == legacy) {
4987 			mtget->mt_fileno = un->un_err_pos.fileno;
4988 		} else {
4989 			mtget->mt_fileno = -1;
4990 		}
4991 		/*
4992 		 * If the value is positive fine.
4993 		 * If its negative we need to return a value based on the
4994 		 * old way if counting backwards from INF (1,000,000,000).
4995 		 */
4996 		if (un->un_err_pos.blkno >= 0) {
4997 			mtget->mt_blkno = un->un_err_pos.blkno;
4998 		} else {
4999 			mtget->mt_blkno = INF + 1 - (-un->un_err_pos.blkno);
5000 		}
5001 		mtget->mt_type = un->un_dp->type;
5002 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
5003 		if (un->un_read_pos_type != NO_POS) {
5004 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
5005 		}
5006 		if (un->un_dp->options & ST_REEL) {
5007 			mtget->mt_flags |= MTF_REEL;
5008 			mtget->mt_bf = 20;
5009 		} else {		/* 1/4" cartridges */
5010 			switch (mtget->mt_type) {
5011 			/* Emulex cartridge tape */
5012 			case MT_ISMT02:
5013 				mtget->mt_bf = 40;
5014 				break;
5015 			default:
5016 				mtget->mt_bf = 126;
5017 				break;
5018 			}
5019 		}
5020 
5021 		/*
5022 		 * If large transfers are allowed and drive options
5023 		 * has no record size limit set. Calculate blocking
5024 		 * factor from the lesser of maxbsize and maxdma.
5025 		 */
5026 		if ((un->un_allow_large_xfer) &&
5027 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
5028 			mtget->mt_bf = min(un->un_maxbsize,
5029 			    un->un_maxdma) / SECSIZE;
5030 		}
5031 
5032 		if (un->un_read_only == WORM ||
5033 		    un->un_read_only == RDWORM) {
5034 			mtget->mt_flags |= MTF_WORM_MEDIA;
5035 		}
5036 
5037 		/*
5038 		 * In persistent error mode sending a non-queued can hang
5039 		 * because this ioctl gets to be run without turning off
5040 		 * persistense. Fake the answer based on previous info.
5041 		 */
5042 		if (un->un_persistence) {
5043 			rval = 0;
5044 		} else {
5045 			rval = st_check_clean_bit(un);
5046 		}
5047 		if (rval == 0) {
5048 			/*
5049 			 * If zero is returned or in persistent mode,
5050 			 * use the old data.
5051 			 */
5052 			if ((un->un_HeadClean & (TAPE_ALERT_SUPPORTED |
5053 			    TAPE_SEQUENTIAL_SUPPORTED|TAPE_ALERT_NOT_SUPPORTED))
5054 			    != TAPE_ALERT_NOT_SUPPORTED) {
5055 				mtget->mt_flags |= MTF_TAPE_CLN_SUPPORTED;
5056 			}
5057 			if (un->un_HeadClean & (TAPE_PREVIOUSLY_DIRTY |
5058 			    TAPE_ALERT_STILL_DIRTY)) {
5059 				mtget->mt_flags |= MTF_TAPE_HEAD_DIRTY;
5060 			}
5061 		} else {
5062 			mtget->mt_flags |= (ushort_t)rval;
5063 			rval = 0;
5064 		}
5065 
5066 		un->un_status = 0;		/* Reset status */
5067 		un->un_err_resid = 0;
5068 		tmp = sizeof (struct mtget);
5069 
5070 #ifdef _MULTI_DATAMODEL
5071 
5072 		switch (ddi_model_convert_from(flag & FMODELS)) {
5073 		case DDI_MODEL_ILP32:
5074 			/*
5075 			 * Convert 64 bit back to 32 bit before doing
5076 			 * copyout. This is what the ILP32 app expects.
5077 			 */
5078 			mtget_32->mt_erreg = 	mtget->mt_erreg;
5079 			mtget_32->mt_resid = 	mtget->mt_resid;
5080 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
5081 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
5082 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
5083 			mtget_32->mt_type =  	mtget->mt_type;
5084 			mtget_32->mt_flags = 	mtget->mt_flags;
5085 			mtget_32->mt_bf = 	mtget->mt_bf;
5086 
5087 			if (ddi_copyout(mtget_32, (void *)arg,
5088 			    sizeof (struct mtget32), flag)) {
5089 				rval = EFAULT;
5090 			}
5091 			break;
5092 
5093 		case DDI_MODEL_NONE:
5094 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5095 				rval = EFAULT;
5096 			}
5097 			break;
5098 		}
5099 #else /* ! _MULTI_DATAMODE */
5100 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5101 			rval = EFAULT;
5102 		}
5103 #endif /* _MULTI_DATAMODE */
5104 
5105 		break;
5106 	}
5107 	case MTIOCGETERROR:
5108 			/*
5109 			 * get error entry from error stack
5110 			 */
5111 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5112 			    "st_ioctl: MTIOCGETERROR\n");
5113 
5114 			rval = st_get_error_entry(un, arg, flag);
5115 
5116 			break;
5117 
5118 	case MTIOCSTATE:
5119 		{
5120 			/*
5121 			 * return when media presence matches state
5122 			 */
5123 			enum mtio_state state;
5124 
5125 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5126 			    "st_ioctl: MTIOCSTATE\n");
5127 
5128 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
5129 				rval = EFAULT;
5130 
5131 			mutex_exit(ST_MUTEX);
5132 
5133 			rval = st_check_media(dev, state);
5134 
5135 			mutex_enter(ST_MUTEX);
5136 
5137 			if (rval != 0) {
5138 				break;
5139 			}
5140 
5141 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
5142 			    sizeof (int), flag))
5143 				rval = EFAULT;
5144 			break;
5145 
5146 		}
5147 
5148 	case MTIOCGETDRIVETYPE:
5149 		{
5150 #ifdef _MULTI_DATAMODEL
5151 		/*
5152 		 * For use when a 32 bit app makes a call into a
5153 		 * 64 bit ioctl
5154 		 */
5155 		struct mtdrivetype_request32	mtdtrq32;
5156 #endif /* _MULTI_DATAMODEL */
5157 
5158 			/*
5159 			 * return mtdrivetype
5160 			 */
5161 			struct mtdrivetype_request mtdtrq;
5162 			struct mtdrivetype mtdrtyp;
5163 			struct mtdrivetype *mtdt = &mtdrtyp;
5164 			struct st_drivetype *stdt = un->un_dp;
5165 
5166 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5167 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
5168 
5169 #ifdef _MULTI_DATAMODEL
5170 		switch (ddi_model_convert_from(flag & FMODELS)) {
5171 		case DDI_MODEL_ILP32:
5172 		{
5173 			if (ddi_copyin((void *)arg, &mtdtrq32,
5174 			    sizeof (struct mtdrivetype_request32), flag)) {
5175 				rval = EFAULT;
5176 				break;
5177 			}
5178 			mtdtrq.size = mtdtrq32.size;
5179 			mtdtrq.mtdtp =
5180 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
5181 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5182 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
5183 			break;
5184 		}
5185 		case DDI_MODEL_NONE:
5186 			if (ddi_copyin((void *)arg, &mtdtrq,
5187 			    sizeof (struct mtdrivetype_request), flag)) {
5188 				rval = EFAULT;
5189 				break;
5190 			}
5191 			break;
5192 		}
5193 
5194 #else /* ! _MULTI_DATAMODEL */
5195 		if (ddi_copyin((void *)arg, &mtdtrq,
5196 		    sizeof (struct mtdrivetype_request), flag)) {
5197 			rval = EFAULT;
5198 			break;
5199 		}
5200 #endif /* _MULTI_DATAMODEL */
5201 
5202 			/*
5203 			 * if requested size is < 0 then return
5204 			 * error.
5205 			 */
5206 			if (mtdtrq.size < 0) {
5207 				rval = EINVAL;
5208 				break;
5209 			}
5210 			bzero(mtdt, sizeof (struct mtdrivetype));
5211 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
5212 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
5213 			mtdt->type = stdt->type;
5214 			mtdt->bsize = stdt->bsize;
5215 			mtdt->options = stdt->options;
5216 			mtdt->max_rretries = stdt->max_rretries;
5217 			mtdt->max_wretries = stdt->max_wretries;
5218 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5219 				mtdt->densities[tmp] = stdt->densities[tmp];
5220 			}
5221 			mtdt->default_density = stdt->default_density;
5222 			/*
5223 			 * Speed hasn't been used since the hayday of reel tape.
5224 			 * For all drives not setting the option ST_KNOWS_MEDIA
5225 			 * the speed member renamed to mediatype are zeros.
5226 			 * Those drives that have ST_KNOWS_MEDIA set use the
5227 			 * new mediatype member which is used to figure the
5228 			 * type of media loaded.
5229 			 *
5230 			 * So as to not break applications speed in the
5231 			 * mtdrivetype structure is not renamed.
5232 			 */
5233 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5234 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
5235 			}
5236 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
5237 			mtdt->io_timeout = stdt->io_timeout;
5238 			mtdt->rewind_timeout = stdt->rewind_timeout;
5239 			mtdt->space_timeout = stdt->space_timeout;
5240 			mtdt->load_timeout = stdt->load_timeout;
5241 			mtdt->unload_timeout = stdt->unload_timeout;
5242 			mtdt->erase_timeout = stdt->erase_timeout;
5243 
5244 			/*
5245 			 * Limit the maximum length of the result to
5246 			 * sizeof (struct mtdrivetype).
5247 			 */
5248 			tmp = sizeof (struct mtdrivetype);
5249 			if (mtdtrq.size < tmp)
5250 				tmp = mtdtrq.size;
5251 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
5252 				rval = EFAULT;
5253 			}
5254 			break;
5255 		}
5256 	case MTIOCPERSISTENT:
5257 
5258 		if (ddi_copyin((void *)arg, &tmp, sizeof (tmp), flag)) {
5259 			rval = EFAULT;
5260 			break;
5261 		}
5262 
5263 		if (tmp) {
5264 			st_turn_pe_on(un);
5265 		} else {
5266 			st_turn_pe_off(un);
5267 		}
5268 
5269 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5270 		    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
5271 		    un->un_persistence);
5272 
5273 		break;
5274 
5275 	case MTIOCPERSISTENTSTATUS:
5276 		tmp = (int)un->un_persistence;
5277 
5278 		if (ddi_copyout(&tmp, (void *)arg, sizeof (tmp), flag)) {
5279 			rval = EFAULT;
5280 		}
5281 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5282 		    "st_ioctl: MTIOCPERSISTENTSTATUS:persistence = %d\n",
5283 		    un->un_persistence);
5284 
5285 		break;
5286 
5287 	case MTIOCLRERR:
5288 		{
5289 			/* clear persistent errors */
5290 
5291 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5292 			    "st_ioctl: MTIOCLRERR\n");
5293 
5294 			st_clear_pe(un);
5295 
5296 			break;
5297 		}
5298 
5299 	case MTIOCGUARANTEEDORDER:
5300 		{
5301 			/*
5302 			 * this is just a holder to make a valid ioctl and
5303 			 * it won't be in any earlier release
5304 			 */
5305 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5306 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
5307 
5308 			break;
5309 		}
5310 
5311 	case MTIOCRESERVE:
5312 		{
5313 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5314 			    "st_ioctl: MTIOCRESERVE\n");
5315 
5316 			/*
5317 			 * Check if Reserve/Release is supported.
5318 			 */
5319 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5320 				rval = ENOTTY;
5321 				break;
5322 			}
5323 
5324 			rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5325 
5326 			if (rval == 0) {
5327 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
5328 			}
5329 			break;
5330 		}
5331 
5332 	case MTIOCRELEASE:
5333 		{
5334 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5335 			    "st_ioctl: MTIOCRELEASE\n");
5336 
5337 			/*
5338 			 * Check if Reserve/Release is supported.
5339 			 */
5340 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5341 				rval = ENOTTY;
5342 				break;
5343 			}
5344 
5345 			/*
5346 			 * Used to just clear ST_PRESERVE_RESERVE which
5347 			 * made the reservation release at next close.
5348 			 * As the user may have opened and then done a
5349 			 * persistant reservation we now need to drop
5350 			 * the reservation without closing if the user
5351 			 * attempts to do this.
5352 			 */
5353 			rval = st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
5354 
5355 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5356 
5357 			break;
5358 		}
5359 
5360 	case MTIOCFORCERESERVE:
5361 	{
5362 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5363 		    "st_ioctl: MTIOCFORCERESERVE\n");
5364 
5365 		/*
5366 		 * Check if Reserve/Release is supported.
5367 		 */
5368 		if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5369 			rval = ENOTTY;
5370 			break;
5371 		}
5372 		/*
5373 		 * allow only super user to run this.
5374 		 */
5375 		if (drv_priv(cred_p) != 0) {
5376 			rval = EPERM;
5377 			break;
5378 		}
5379 		/*
5380 		 * Throw away reserve,
5381 		 * not using test-unit-ready
5382 		 * since reserve can succeed without tape being
5383 		 * present in the drive.
5384 		 */
5385 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5386 
5387 		rval = st_take_ownership(un, st_uscsi_cmd);
5388 
5389 		break;
5390 	}
5391 
5392 	case USCSICMD:
5393 	{
5394 		cred_t	*cr;
5395 
5396 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5397 		    "st_ioctl: USCSICMD\n");
5398 
5399 		cr = ddi_get_cred();
5400 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5401 			rval = EPERM;
5402 		} else {
5403 			rval = st_uscsi_cmd(un, (struct uscsi_cmd *)arg, flag);
5404 		}
5405 		break;
5406 	}
5407 	case MTIOCTOP:
5408 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5409 		    "st_ioctl: MTIOCTOP\n");
5410 		rval = st_mtioctop(un, arg, flag);
5411 		break;
5412 
5413 	case MTIOCLTOP:
5414 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5415 		    "st_ioctl: MTIOLCTOP\n");
5416 		rval = st_mtiocltop(un, arg, flag);
5417 		break;
5418 
5419 	case MTIOCREADIGNOREILI:
5420 		{
5421 			int set_ili;
5422 
5423 			if (ddi_copyin((void *)arg, &set_ili,
5424 			    sizeof (set_ili), flag)) {
5425 				rval = EFAULT;
5426 				break;
5427 			}
5428 
5429 			if (un->un_bsize) {
5430 				rval = ENOTTY;
5431 				break;
5432 			}
5433 
5434 			switch (set_ili) {
5435 			case 0:
5436 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5437 				break;
5438 
5439 			case 1:
5440 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5441 				break;
5442 
5443 			default:
5444 				rval = EINVAL;
5445 				break;
5446 			}
5447 			break;
5448 		}
5449 
5450 	case MTIOCREADIGNOREEOFS:
5451 		{
5452 			int ignore_eof;
5453 
5454 			if (ddi_copyin((void *)arg, &ignore_eof,
5455 			    sizeof (ignore_eof), flag)) {
5456 				rval = EFAULT;
5457 				break;
5458 			}
5459 
5460 			if (!(un->un_dp->options & ST_REEL)) {
5461 				rval = ENOTTY;
5462 				break;
5463 			}
5464 
5465 			switch (ignore_eof) {
5466 			case 0:
5467 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5468 				break;
5469 
5470 			case 1:
5471 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5472 				break;
5473 
5474 			default:
5475 				rval = EINVAL;
5476 				break;
5477 			}
5478 			break;
5479 		}
5480 
5481 	case MTIOCSHORTFMK:
5482 	{
5483 		int short_fmk;
5484 
5485 		if (ddi_copyin((void *)arg, &short_fmk,
5486 		    sizeof (short_fmk), flag)) {
5487 			rval = EFAULT;
5488 			break;
5489 		}
5490 
5491 		switch (un->un_dp->type) {
5492 		case ST_TYPE_EXB8500:
5493 		case ST_TYPE_EXABYTE:
5494 			if (!short_fmk) {
5495 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5496 			} else if (short_fmk == 1) {
5497 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5498 			} else {
5499 				rval = EINVAL;
5500 			}
5501 			break;
5502 
5503 		default:
5504 			rval = ENOTTY;
5505 			break;
5506 		}
5507 		break;
5508 	}
5509 
5510 	case MTIOCGETPOS:
5511 		rval = st_update_block_pos(un, st_cmd, 0);
5512 		if (rval == 0) {
5513 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5514 			    sizeof (tapepos_t), flag)) {
5515 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5516 				    "MTIOCGETPOS copy out failed\n");
5517 				rval = EFAULT;
5518 			}
5519 		}
5520 		break;
5521 
5522 	case MTIOCRESTPOS:
5523 	{
5524 		tapepos_t dest;
5525 
5526 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5527 		    flag) != 0) {
5528 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5529 			    "MTIOCRESTPOS copy in failed\n");
5530 			rval = EFAULT;
5531 			break;
5532 		}
5533 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &dest);
5534 		if (rval != 0) {
5535 			rval = EIO;
5536 		}
5537 		break;
5538 	}
5539 	default:
5540 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5541 		    "st_ioctl: unknown ioctl\n");
5542 		rval = ENOTTY;
5543 	}
5544 
5545 exit:
5546 	if (!(un->un_persistence && un->un_persist_errors)) {
5547 		un->un_errno = rval;
5548 	}
5549 
5550 	mutex_exit(ST_MUTEX);
5551 
5552 	return (rval);
5553 }
5554 
5555 
5556 /*
5557  * do some MTIOCTOP tape operations
5558  */
5559 static int
5560 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5561 {
5562 #ifdef _MULTI_DATAMODEL
5563 	/*
5564 	 * For use when a 32 bit app makes a call into a
5565 	 * 64 bit ioctl
5566 	 */
5567 	struct mtop32	mtop_32_for_64;
5568 #endif /* _MULTI_DATAMODEL */
5569 	struct mtop passed;
5570 	struct mtlop local;
5571 	int rval = 0;
5572 
5573 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5574 
5575 	ASSERT(mutex_owned(ST_MUTEX));
5576 
5577 #ifdef _MULTI_DATAMODEL
5578 	switch (ddi_model_convert_from(flag & FMODELS)) {
5579 	case DDI_MODEL_ILP32:
5580 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5581 		    sizeof (struct mtop32), flag)) {
5582 			return (EFAULT);
5583 		}
5584 		local.mt_op = mtop_32_for_64.mt_op;
5585 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5586 		break;
5587 
5588 	case DDI_MODEL_NONE:
5589 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5590 			return (EFAULT);
5591 		}
5592 		local.mt_op = passed.mt_op;
5593 		/* prevent sign extention */
5594 		local.mt_count = (UINT32_MAX & passed.mt_count);
5595 		break;
5596 	}
5597 
5598 #else /* ! _MULTI_DATAMODEL */
5599 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5600 		return (EFAULT);
5601 	}
5602 	local.mt_op = passed.mt_op;
5603 	/* prevent sign extention */
5604 	local.mt_count = (UINT32_MAX & passed.mt_count);
5605 #endif /* _MULTI_DATAMODEL */
5606 
5607 	rval = st_do_mtioctop(un, &local);
5608 
5609 #ifdef _MULTI_DATAMODEL
5610 	switch (ddi_model_convert_from(flag & FMODELS)) {
5611 	case DDI_MODEL_ILP32:
5612 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5613 			rval = ERANGE;
5614 			break;
5615 		}
5616 		/*
5617 		 * Convert 64 bit back to 32 bit before doing
5618 		 * copyout. This is what the ILP32 app expects.
5619 		 */
5620 		mtop_32_for_64.mt_op = local.mt_op;
5621 		mtop_32_for_64.mt_count = local.mt_count;
5622 
5623 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5624 		    sizeof (struct mtop32), flag)) {
5625 			rval = EFAULT;
5626 		}
5627 		break;
5628 
5629 	case DDI_MODEL_NONE:
5630 		passed.mt_count = local.mt_count;
5631 		passed.mt_op = local.mt_op;
5632 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5633 			rval = EFAULT;
5634 		}
5635 		break;
5636 	}
5637 #else /* ! _MULTI_DATAMODE */
5638 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5639 		rval = ERANGE;
5640 	} else {
5641 		passed.mt_op = local.mt_op;
5642 		passed.mt_count = local.mt_count;
5643 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5644 			rval = EFAULT;
5645 		}
5646 	}
5647 #endif /* _MULTI_DATAMODE */
5648 
5649 
5650 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5651 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5652 	    un->un_pos.blkno, un->un_pos.eof);
5653 
5654 	if (un->un_pos.pmode == invalid) {
5655 		un->un_density_known = 0;
5656 	}
5657 
5658 	ASSERT(mutex_owned(ST_MUTEX));
5659 	return (rval);
5660 }
5661 
5662 static int
5663 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5664 {
5665 	struct mtlop local;
5666 	int rval;
5667 
5668 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5669 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5670 		return (EFAULT);
5671 	}
5672 
5673 	rval = st_do_mtioctop(un, &local);
5674 
5675 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5676 		rval = EFAULT;
5677 	}
5678 	return (rval);
5679 }
5680 
5681 
5682 static int
5683 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5684 {
5685 	dev_t dev = un->un_dev;
5686 	int savefile;
5687 	int rval = 0;
5688 
5689 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5690 
5691 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5692 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5693 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5694 	    "fileno=%x, blkno=%x, eof=%x\n",
5695 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5696 
5697 	un->un_status = 0;
5698 
5699 	/*
5700 	 * if we are going to mess with a tape, we have to make sure we have
5701 	 * one and are not offline (i.e. no tape is initialized).  We let
5702 	 * commands pass here that don't actually touch the tape, except for
5703 	 * loading and initialization (rewinding).
5704 	 */
5705 	if (un->un_state == ST_STATE_OFFLINE) {
5706 		switch (mtop->mt_op) {
5707 		case MTLOAD:
5708 		case MTNOP:
5709 			/*
5710 			 * We don't want strategy calling st_tape_init here,
5711 			 * so, change state
5712 			 */
5713 			un->un_state = ST_STATE_INITIALIZING;
5714 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5715 			    "st_do_mtioctop : OFFLINE state = %d\n",
5716 			    un->un_state);
5717 			break;
5718 		default:
5719 			/*
5720 			 * reinitialize by normal means
5721 			 */
5722 			rval = st_tape_init(un);
5723 			if (rval) {
5724 				un->un_state = ST_STATE_INITIALIZING;
5725 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5726 				    "st_do_mtioctop : OFFLINE init failure ");
5727 				un->un_state = ST_STATE_OFFLINE;
5728 				un->un_pos.pmode = invalid;
5729 				if (rval != EACCES) {
5730 					rval = EIO;
5731 				}
5732 				return (rval);
5733 			}
5734 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5735 			break;
5736 		}
5737 	}
5738 
5739 	/*
5740 	 * If the file position is invalid, allow only those
5741 	 * commands that properly position the tape and fail
5742 	 * the rest with EIO
5743 	 */
5744 	if (un->un_pos.pmode == invalid) {
5745 		switch (mtop->mt_op) {
5746 		case MTWEOF:
5747 		case MTRETEN:
5748 		case MTERASE:
5749 		case MTEOM:
5750 		case MTFSF:
5751 		case MTFSR:
5752 		case MTBSF:
5753 		case MTNBSF:
5754 		case MTBSR:
5755 		case MTSRSZ:
5756 		case MTGRSZ:
5757 		case MTSEEK:
5758 		case MTBSSF:
5759 		case MTFSSF:
5760 			return (EIO);
5761 			/* NOTREACHED */
5762 		case MTREW:
5763 		case MTLOAD:
5764 		case MTOFFL:
5765 		case MTNOP:
5766 		case MTTELL:
5767 		case MTLOCK:
5768 		case MTUNLOCK:
5769 			break;
5770 
5771 		default:
5772 			return (ENOTTY);
5773 			/* NOTREACHED */
5774 		}
5775 	}
5776 
5777 	switch (mtop->mt_op) {
5778 	case MTERASE:
5779 		/*
5780 		 * MTERASE rewinds the tape, erase it completely, and returns
5781 		 * to the beginning of the tape
5782 		 */
5783 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5784 			un->un_status = KEY_WRITE_PROTECT;
5785 			un->un_err_resid = mtop->mt_count;
5786 			COPY_POS(&un->un_err_pos, &un->un_pos);
5787 			return (EACCES);
5788 		}
5789 		if (un->un_dp->options & ST_REEL) {
5790 			un->un_fmneeded = 2;
5791 		} else {
5792 			un->un_fmneeded = 1;
5793 		}
5794 		mtop->mt_count = mtop->mt_count ? 1 : 0;
5795 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5796 		    st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
5797 		    st_cmd(un, SCMD_ERASE, mtop->mt_count, SYNC_CMD)) {
5798 			un->un_pos.pmode = invalid;
5799 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5800 			    "st_do_mtioctop : EIO space or erase or "
5801 			    "check den)\n");
5802 			rval = EIO;
5803 		} else {
5804 			/* QIC and helical scan rewind after erase */
5805 			if (un->un_dp->options & ST_REEL) {
5806 				(void) st_cmd(un, SCMD_REWIND, 0, ASYNC_CMD);
5807 			}
5808 		}
5809 		break;
5810 
5811 	case MTWEOF:
5812 		/*
5813 		 * write an end-of-file record
5814 		 */
5815 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5816 			un->un_status = KEY_WRITE_PROTECT;
5817 			un->un_err_resid = mtop->mt_count;
5818 			COPY_POS(&un->un_err_pos, &un->un_pos);
5819 			return (EACCES);
5820 		}
5821 
5822 		/*
5823 		 * zero count means just flush buffers
5824 		 * negative count is not permitted
5825 		 */
5826 		if (mtop->mt_count < 0) {
5827 			return (EINVAL);
5828 		}
5829 
5830 		/* Not on worm */
5831 		if (un->un_read_only == RDWR) {
5832 			un->un_test_append = 1;
5833 		}
5834 
5835 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5836 			if (st_determine_density(un, B_WRITE)) {
5837 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5838 				    "st_do_mtioctop : EIO : MTWEOF can't "
5839 				    "determine density");
5840 				return (EIO);
5841 			}
5842 		}
5843 
5844 		rval = st_write_fm(dev, (int)mtop->mt_count);
5845 		if ((rval != 0) && (rval != EACCES)) {
5846 			/*
5847 			 * Failure due to something other than illegal
5848 			 * request results in loss of state (st_intr).
5849 			 */
5850 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5851 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5852 			    "file mark");
5853 			rval = EIO;
5854 		}
5855 		break;
5856 
5857 	case MTRETEN:
5858 		/*
5859 		 * retension the tape
5860 		 */
5861 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5862 		    st_cmd(un, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5863 			un->un_pos.pmode = invalid;
5864 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5865 			    "st_do_mtioctop : EIO : MTRETEN ");
5866 			rval = EIO;
5867 		}
5868 		break;
5869 
5870 	case MTREW:
5871 		/*
5872 		 * rewind  the tape
5873 		 */
5874 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5875 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5876 			    "st_do_mtioctop : EIO:MTREW check "
5877 			    "density/wfm failed");
5878 			return (EIO);
5879 		}
5880 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
5881 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5882 			    "st_do_mtioctop : EIO : MTREW ");
5883 			rval = EIO;
5884 		}
5885 		break;
5886 
5887 	case MTOFFL:
5888 		/*
5889 		 * rewinds, and, if appropriate, takes the device offline by
5890 		 * unloading the tape
5891 		 */
5892 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5893 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5894 			    "st_do_mtioctop :EIO:MTOFFL check "
5895 			    "density/wfm failed");
5896 			return (EIO);
5897 		}
5898 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
5899 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5900 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5901 			    "st_do_mtioctop : EIO : MTOFFL");
5902 			return (EIO);
5903 		}
5904 		un->un_pos.eof = ST_NO_EOF;
5905 		un->un_laststate = un->un_state;
5906 		un->un_state = ST_STATE_OFFLINE;
5907 		un->un_mediastate = MTIO_EJECTED;
5908 		break;
5909 
5910 	case MTLOAD:
5911 		/*
5912 		 * This is to load a tape into the drive
5913 		 * Note that if the tape is not loaded, the device will have
5914 		 * to be opened via O_NDELAY or O_NONBLOCK.
5915 		 */
5916 		/*
5917 		 * Let's try and clean things up, if we are not
5918 		 * initializing, and then send in the load command, no
5919 		 * matter what.
5920 		 *
5921 		 * load after a media change by the user.
5922 		 */
5923 
5924 		if (un->un_state > ST_STATE_INITIALIZING) {
5925 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5926 		}
5927 		rval = st_cmd(un, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5928 		/* Load command to a drive that doesn't support load */
5929 		if ((rval == EIO) &&
5930 		    ((un->un_status == KEY_NOT_READY) &&
5931 			/* Medium not present */
5932 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5933 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5934 		    (un->un_dp->type == MT_ISSTK9840) &&
5935 			/* CSL not present */
5936 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5937 			rval = ENOTTY;
5938 			break;
5939 		} else if (rval != EACCES && rval != 0) {
5940 			rval = EIO;
5941 		}
5942 		if (rval) {
5943 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5944 			    "st_do_mtioctop : %s : MTLOAD\n",
5945 			    rval == EACCES ? "EACCES" : "EIO");
5946 			/*
5947 			 * If load tape fails, who knows what happened...
5948 			 */
5949 			un->un_pos.pmode = invalid;
5950 			break;
5951 		}
5952 
5953 		/*
5954 		 * reset all counters appropriately using rewind, as if LOAD
5955 		 * succeeds, we are at BOT
5956 		 */
5957 		un->un_state = ST_STATE_INITIALIZING;
5958 
5959 		rval = st_tape_init(un);
5960 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5961 			rval = 0;
5962 			break;
5963 		}
5964 
5965 		if (rval != 0) {
5966 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5967 			    "st_do_mtioctop : EIO : MTLOAD calls "
5968 			    "st_tape_init\n");
5969 			rval = EIO;
5970 			un->un_state = ST_STATE_OFFLINE;
5971 		}
5972 
5973 		break;
5974 
5975 	case MTNOP:
5976 		un->un_status = 0;		/* Reset status */
5977 		un->un_err_resid = 0;
5978 		mtop->mt_count = MTUNIT(dev);
5979 		break;
5980 
5981 	case MTEOM:
5982 		/*
5983 		 * positions the tape at a location just after the last file
5984 		 * written on the tape. For cartridge and 8 mm, this after
5985 		 * the last file mark; for reel, this is inbetween the two
5986 		 * last 2 file marks
5987 		 */
5988 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5989 		    (un->un_lastop == ST_OP_WRITE) ||
5990 		    (un->un_lastop == ST_OP_WEOF)) {
5991 			/*
5992 			 * If the command wants to move to logical end
5993 			 * of media, and we're already there, we're done.
5994 			 * If we were at logical eot, we reset the state
5995 			 * to be *not* at logical eot.
5996 			 *
5997 			 * If we're at physical or logical eot, we prohibit
5998 			 * forward space operations (unconditionally).
5999 			 *
6000 			 * Also if the last operation was a write of any
6001 			 * kind the tape is at EOD.
6002 			 */
6003 			return (0);
6004 		}
6005 		/*
6006 		 * physical tape position may not be what we've been
6007 		 * telling the user; adjust the request accordingly
6008 		 */
6009 		if (IN_EOF(un->un_pos)) {
6010 			un->un_pos.fileno++;
6011 			un->un_pos.blkno = 0;
6012 		}
6013 
6014 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
6015 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6016 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
6017 			    " failed");
6018 			return (EIO);
6019 		}
6020 
6021 		/*
6022 		 * st_find_eod() returns the last fileno we knew about;
6023 		 */
6024 		savefile = st_find_eod(un);
6025 
6026 		if ((un->un_status != KEY_BLANK_CHECK) &&
6027 		    (un->un_status != SUN_KEY_EOT)) {
6028 			un->un_pos.pmode = invalid;
6029 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6030 			    "st_do_mtioctop : EIO : MTEOM status check failed");
6031 			rval = EIO;
6032 		} else {
6033 			/*
6034 			 * For 1/2" reel tapes assume logical EOT marked
6035 			 * by two file marks or we don't care that we may
6036 			 * be extending the last file on the tape.
6037 			 */
6038 			if (un->un_dp->options & ST_REEL) {
6039 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
6040 					un->un_pos.pmode = invalid;
6041 					ST_DEBUG2(ST_DEVINFO, st_label,
6042 					    SCSI_DEBUG,
6043 					    "st_do_mtioctop : EIO : MTEOM space"
6044 					    " cmd failed");
6045 					rval = EIO;
6046 					break;
6047 				}
6048 				/*
6049 				 * Fix up the block number.
6050 				 */
6051 				un->un_pos.blkno = 0;
6052 				un->un_err_pos.blkno = 0;
6053 			}
6054 			un->un_err_resid = 0;
6055 			un->un_pos.fileno = savefile;
6056 			un->un_pos.eof = ST_EOT;
6057 		}
6058 		un->un_status = 0;
6059 		break;
6060 
6061 	case MTFSF:
6062 		MAX_SPACE_CNT(mtop->mt_count);
6063 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
6064 		break;
6065 
6066 	case MTFSR:
6067 		MAX_SPACE_CNT(mtop->mt_count);
6068 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
6069 		break;
6070 
6071 	case MTBSF:
6072 		MAX_SPACE_CNT(mtop->mt_count);
6073 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
6074 		break;
6075 
6076 	case MTNBSF:
6077 		MAX_SPACE_CNT(mtop->mt_count);
6078 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
6079 		break;
6080 
6081 	case MTBSR:
6082 		MAX_SPACE_CNT(mtop->mt_count);
6083 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
6084 		break;
6085 
6086 	case MTBSSF:
6087 		MAX_SPACE_CNT(mtop->mt_count);
6088 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
6089 		break;
6090 
6091 	case MTFSSF:
6092 		MAX_SPACE_CNT(mtop->mt_count);
6093 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
6094 		break;
6095 
6096 	case MTSRSZ:
6097 
6098 		/*
6099 		 * Set record-size to that sent by user
6100 		 * Check to see if there is reason that the requested
6101 		 * block size should not be set.
6102 		 */
6103 
6104 		/* If requesting variable block size is it ok? */
6105 		if ((mtop->mt_count == 0) &&
6106 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
6107 			return (ENOTTY);
6108 		}
6109 
6110 		/*
6111 		 * If requested block size is not variable "0",
6112 		 * is it less then minimum.
6113 		 */
6114 		if ((mtop->mt_count != 0) &&
6115 		    (mtop->mt_count < un->un_minbsize)) {
6116 			return (EINVAL);
6117 		}
6118 
6119 		/* Is the requested block size more then maximum */
6120 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
6121 		    (un->un_maxbsize != 0)) {
6122 			return (EINVAL);
6123 		}
6124 
6125 		/* Is requested block size a modulus the device likes */
6126 		if ((mtop->mt_count % un->un_data_mod) != 0) {
6127 			return (EINVAL);
6128 		}
6129 
6130 		if (st_change_block_size(un, (uint32_t)mtop->mt_count) != 0) {
6131 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6132 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
6133 			return (EIO);
6134 		}
6135 
6136 		return (0);
6137 
6138 	case MTGRSZ:
6139 		/*
6140 		 * Get record-size to the user
6141 		 */
6142 		mtop->mt_count = un->un_bsize;
6143 		rval = 0;
6144 		break;
6145 
6146 	case MTTELL:
6147 		rval = st_update_block_pos(un, st_cmd, 0);
6148 		mtop->mt_count = un->un_pos.lgclblkno;
6149 		break;
6150 
6151 	case MTSEEK:
6152 		rval = st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
6153 		    (uint64_t)mtop->mt_count, un->un_pos.partition);
6154 		/*
6155 		 * This bit of magic make mt print the actual position if
6156 		 * the resulting position was not what was asked for.
6157 		 */
6158 		if (rval == ESPIPE) {
6159 			rval = EIO;
6160 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
6161 				mtop->mt_op = MTTELL;
6162 				mtop->mt_count = un->un_pos.lgclblkno;
6163 			}
6164 		}
6165 		break;
6166 
6167 	case MTLOCK:
6168 		if (st_cmd(un, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
6169 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6170 			    "st_do_mtioctop : EIO : MTLOCK");
6171 			rval = EIO;
6172 		}
6173 		break;
6174 
6175 	case MTUNLOCK:
6176 		if (st_cmd(un, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
6177 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6178 			    "st_do_mtioctop : EIO : MTUNLOCK");
6179 			rval = EIO;
6180 		}
6181 		break;
6182 
6183 	default:
6184 		rval = ENOTTY;
6185 	}
6186 
6187 	return (rval);
6188 }
6189 
6190 
6191 /*
6192  * Run a command for uscsi ioctl.
6193  */
6194 static int
6195 st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
6196 {
6197 	struct uscsi_cmd	*uscmd;
6198 	struct buf	*bp;
6199 	enum uio_seg	uioseg;
6200 	int	offline_state = 0;
6201 	int	err = 0;
6202 	dev_t dev = un->un_dev;
6203 
6204 	ST_FUNC(ST_DEVINFO, st_uscsi_cmd);
6205 
6206 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6207 	    "st_uscsi_cmd(dev = 0x%lx)\n", un->un_dev);
6208 
6209 	ASSERT(mutex_owned(ST_MUTEX));
6210 
6211 	/*
6212 	 * We really don't know what commands are coming in here and
6213 	 * we don't want to limit the commands coming in.
6214 	 *
6215 	 * If st_tape_init() gets called from st_strategy(), then we
6216 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
6217 	 * which it never will, as we set it below.  To prevent
6218 	 * st_tape_init() from getting called, we have to set state to other
6219 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
6220 	 * achieves this purpose already.
6221 	 *
6222 	 * We use offline_state to preserve the OFFLINE state, if it exists,
6223 	 * so other entry points to the driver might have the chance to call
6224 	 * st_tape_init().
6225 	 */
6226 	if (un->un_state == ST_STATE_OFFLINE) {
6227 		un->un_laststate = ST_STATE_OFFLINE;
6228 		un->un_state = ST_STATE_INITIALIZING;
6229 		offline_state = 1;
6230 	}
6231 
6232 	mutex_exit(ST_MUTEX);
6233 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag, ROUTE, &uscmd);
6234 	mutex_enter(ST_MUTEX);
6235 	if (err != 0) {
6236 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6237 		    "st_uscsi_cmd: scsi_uscsi_alloc_and_copyin failed\n");
6238 		goto exit;
6239 	}
6240 
6241 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
6242 
6243 	/* check to see if this command requires the drive to be reserved */
6244 	if (uscmd->uscsi_cdb != NULL) {
6245 		err = st_check_cdb_for_need_to_reserve(un,
6246 		    (uchar_t *)uscmd->uscsi_cdb);
6247 		if (err) {
6248 			goto exit_free;
6249 		}
6250 		/*
6251 		 * If this is a space command we need to save the starting
6252 		 * point so we can retry from there if the command fails.
6253 		 */
6254 		if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6255 		    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) {
6256 			(void) st_update_block_pos(un, st_cmd, 0);
6257 		}
6258 	}
6259 
6260 	/*
6261 	 * Forground should not be doing anything while recovery is active.
6262 	 */
6263 	ASSERT(un->un_recov_buf_busy == 0);
6264 
6265 	/*
6266 	 * Get buffer resources...
6267 	 */
6268 	while (un->un_sbuf_busy)
6269 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6270 	un->un_sbuf_busy = 1;
6271 
6272 #ifdef STDEBUG
6273 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0x7) > 6) {
6274 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
6275 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6276 		    "uscsi cdb", uscmd->uscsi_cdb);
6277 		if (uscmd->uscsi_buflen) {
6278 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6279 			    "uscsi %s of %ld bytes %s %s space\n",
6280 			    (rw == B_READ) ? rd_str : wr_str,
6281 			    uscmd->uscsi_buflen,
6282 			    (rw == B_READ) ? "to" : "from",
6283 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
6284 		}
6285 	}
6286 #endif /* STDEBUG */
6287 
6288 	/*
6289 	 * Although st_uscsi_cmd() never makes use of these
6290 	 * now, we are just being safe and consistent.
6291 	 */
6292 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
6293 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
6294 
6295 	un->un_srqbufp = uscmd->uscsi_rqbuf;
6296 	bp = un->un_sbufp;
6297 	bzero(bp, sizeof (buf_t));
6298 	if (uscmd->uscsi_cdb != NULL) {
6299 		bp->b_forw = (struct buf *)(uintptr_t)uscmd->uscsi_cdb[0];
6300 	}
6301 	bp->b_back = (struct buf *)uscmd;
6302 
6303 	mutex_exit(ST_MUTEX);
6304 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, st_strategy, bp, NULL);
6305 	mutex_enter(ST_MUTEX);
6306 
6307 	/*
6308 	 * If scsi reset successful, don't write any filemarks.
6309 	 */
6310 	if ((err == 0) && (uscmd->uscsi_flags &
6311 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
6312 		un->un_fmneeded = 0;
6313 	}
6314 
6315 exit_free:
6316 	/*
6317 	 * Free resources
6318 	 */
6319 	un->un_sbuf_busy = 0;
6320 	un->un_srqbufp = NULL;
6321 
6322 	/*
6323 	 * If was a space command need to update logical block position.
6324 	 * If the command failed such that positioning is invalid, Don't
6325 	 * update the position as the user must do this to validate the
6326 	 * position for data protection.
6327 	 */
6328 	if ((uscmd->uscsi_cdb != NULL) &&
6329 	    ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6330 	    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) &&
6331 	    (un->un_pos.pmode != invalid)) {
6332 		un->un_running.pmode = invalid;
6333 		(void) st_update_block_pos(un, st_cmd, 1);
6334 		/*
6335 		 * Set running position to invalid so it updates on the
6336 		 * next command.
6337 		 */
6338 		un->un_running.pmode = invalid;
6339 	}
6340 	cv_signal(&un->un_sbuf_cv);
6341 	mutex_exit(ST_MUTEX);
6342 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
6343 	mutex_enter(ST_MUTEX);
6344 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6345 	    "st_uscsi_cmd returns 0x%x\n", err);
6346 
6347 exit:
6348 	/* don't lose offline state */
6349 	if (offline_state) {
6350 		un->un_state = ST_STATE_OFFLINE;
6351 	}
6352 
6353 	ASSERT(mutex_owned(ST_MUTEX));
6354 	return (err);
6355 }
6356 
6357 static int
6358 st_write_fm(dev_t dev, int wfm)
6359 {
6360 	int i;
6361 	int rval;
6362 
6363 	GET_SOFT_STATE(dev);
6364 
6365 	ST_FUNC(ST_DEVINFO, st_write_fm);
6366 
6367 	ASSERT(mutex_owned(ST_MUTEX));
6368 
6369 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6370 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6371 
6372 	/*
6373 	 * write one filemark at the time after EOT
6374 	 */
6375 	if (un->un_pos.eof >= ST_EOT) {
6376 		for (i = 0; i < wfm; i++) {
6377 			rval = st_cmd(un, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6378 			if (rval == EACCES) {
6379 				return (rval);
6380 			}
6381 			if (rval != 0) {
6382 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6383 				    "st_write_fm : EIO : write EOT file mark");
6384 				return (EIO);
6385 			}
6386 		}
6387 	} else {
6388 		rval = st_cmd(un, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6389 		if (rval == EACCES) {
6390 			return (rval);
6391 		}
6392 		if (rval) {
6393 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6394 			    "st_write_fm : EIO : write file mark");
6395 			return (EIO);
6396 		}
6397 	}
6398 
6399 	ASSERT(mutex_owned(ST_MUTEX));
6400 	return (0);
6401 }
6402 
6403 #ifdef STDEBUG
6404 static void
6405 st_start_dump(struct scsi_tape *un, struct buf *bp)
6406 {
6407 	struct scsi_pkt *pkt = BP_PKT(bp);
6408 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6409 
6410 	ST_FUNC(ST_DEVINFO, st_start_dump);
6411 
6412 	if ((st_debug & 0x7) < 6)
6413 		return;
6414 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6415 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6416 	    (void *)bp->b_forw, bp->b_bcount,
6417 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6418 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6419 	    "st_start: cdb",  (caddr_t)cdbp);
6420 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6421 	    "st_start: fileno=%d, blk=%d\n",
6422 	    un->un_pos.fileno, un->un_pos.blkno);
6423 }
6424 #endif
6425 
6426 
6427 /*
6428  * Command start && done functions
6429  */
6430 
6431 /*
6432  * st_start()
6433  *
6434  * Called from:
6435  *  st_strategy() to start a command.
6436  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6437  *  st_attach() when resuming from power down state.
6438  *  st_start_restart() to retry transport when device was previously busy.
6439  *  st_done_and_mutex_exit() to start the next command when previous is done.
6440  *
6441  * On entry:
6442  *  scsi_pkt may or may not be allocated.
6443  *
6444  */
6445 static void
6446 st_start(struct scsi_tape *un)
6447 {
6448 	struct buf *bp;
6449 	int status;
6450 	int queued;
6451 
6452 	ST_FUNC(ST_DEVINFO, st_start);
6453 	ASSERT(mutex_owned(ST_MUTEX));
6454 
6455 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6456 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6457 
6458 	if (un->un_recov_buf_busy) {
6459 		/* recovery commands can happen anytime */
6460 		bp = un->un_recov_buf;
6461 		queued = 0;
6462 	} else if (un->un_sbuf_busy) {
6463 		/* sbuf commands should only happen with an empty queue. */
6464 		ASSERT(un->un_quef == NULL);
6465 		ASSERT(un->un_runqf == NULL);
6466 		bp = un->un_sbufp;
6467 		queued = 0;
6468 	} else if (un->un_quef != NULL) {
6469 		if (un->un_persistence && un->un_persist_errors) {
6470 			return;
6471 		}
6472 		bp = un->un_quef;
6473 		queued = 1;
6474 	} else {
6475 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6476 		    "st_start() returning no buf found\n");
6477 		return;
6478 	}
6479 
6480 	ASSERT((bp->b_flags & B_DONE) == 0);
6481 
6482 	/*
6483 	 * Don't send more than un_throttle commands to the HBA
6484 	 */
6485 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6486 		/*
6487 		 * if doing recovery we know there is outstanding commands.
6488 		 */
6489 		if (bp != un->un_recov_buf) {
6490 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6491 			    "st_start returning throttle = %d or ncmds = %d\n",
6492 			    un->un_throttle, un->un_ncmds);
6493 			if (un->un_ncmds == 0) {
6494 				typedef void (*func)();
6495 				func fnc = (func)st_runout;
6496 
6497 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6498 				    "Sending delayed start to st_runout()\n");
6499 				mutex_exit(ST_MUTEX);
6500 				(void) timeout(fnc, un, drv_usectohz(1000000));
6501 				mutex_enter(ST_MUTEX);
6502 			}
6503 			return;
6504 		}
6505 	}
6506 
6507 	/*
6508 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6509 	 * build the command.
6510 	 */
6511 	if (BP_PKT(bp) == NULL) {
6512 		ASSERT((bp->b_flags & B_DONE) == 0);
6513 		st_make_cmd(un, bp, st_runout);
6514 		ASSERT((bp->b_flags & B_DONE) == 0);
6515 		status = geterror(bp);
6516 
6517 		/*
6518 		 * Some HBA's don't call bioerror() to set an error.
6519 		 * And geterror() returns zero if B_ERROR is not set.
6520 		 * So if we get zero we must check b_error.
6521 		 */
6522 		if (status == 0 && bp->b_error != 0) {
6523 			status = bp->b_error;
6524 			bioerror(bp, status);
6525 		}
6526 
6527 		/*
6528 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6529 		 * In tape ENOMEM has special meaning so we'll change it.
6530 		 */
6531 		if (status == ENOMEM) {
6532 			status = 0;
6533 			bioerror(bp, status);
6534 		}
6535 
6536 		/*
6537 		 * Did it fail and is it retryable?
6538 		 * If so return and wait for the callback through st_runout.
6539 		 * Also looks like scsi_init_pkt() will setup a callback even
6540 		 * if it isn't retryable.
6541 		 */
6542 		if (BP_PKT(bp) == NULL) {
6543 			if (status == 0) {
6544 				/*
6545 				 * If first attempt save state.
6546 				 */
6547 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6548 					un->un_laststate = un->un_state;
6549 					un->un_state = ST_STATE_RESOURCE_WAIT;
6550 				}
6551 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6552 				    "temp no resources for pkt\n");
6553 			} else if (status == EINVAL) {
6554 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6555 				    "scsi_init_pkt rejected pkt as too big\n");
6556 				if (un->un_persistence) {
6557 					st_set_pe_flag(un);
6558 				}
6559 			} else {
6560 				/*
6561 				 * Unlikely that it would be retryable then not.
6562 				 */
6563 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6564 					un->un_state = un->un_laststate;
6565 				}
6566 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6567 				    "perm no resources for pkt errno = 0x%x\n",
6568 				    status);
6569 			}
6570 			return;
6571 		}
6572 		/*
6573 		 * Worked this time set the state back.
6574 		 */
6575 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6576 			un->un_state = un->un_laststate;
6577 		}
6578 	}
6579 
6580 	if (queued) {
6581 		/*
6582 		 * move from waitq to runq
6583 		 */
6584 		(void) st_remove_from_queue(&un->un_quef, &un->un_quel, bp);
6585 		st_add_to_queue(&un->un_runqf, &un->un_runql, un->un_runql, bp);
6586 	}
6587 
6588 
6589 #ifdef STDEBUG
6590 	st_start_dump(un, bp);
6591 #endif
6592 
6593 	/* could not get here if throttle was zero */
6594 	un->un_last_throttle = un->un_throttle;
6595 	un->un_throttle = 0;	/* so nothing else will come in here */
6596 	un->un_ncmds++;
6597 
6598 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6599 
6600 	status = st_transport(un, BP_PKT(bp));
6601 
6602 	if (un->un_last_throttle) {
6603 		un->un_throttle = un->un_last_throttle;
6604 	}
6605 
6606 	if (status != TRAN_ACCEPT) {
6607 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6608 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
6609 		    "Unhappy transport packet status 0x%x\n", status);
6610 
6611 		if (status == TRAN_BUSY) {
6612 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
6613 
6614 			/*
6615 			 * If command recovery is enabled and this isn't
6616 			 * a recovery command try command recovery.
6617 			 */
6618 			if (pkti->privatelen == sizeof (recov_info) &&
6619 			    bp != un->un_recov_buf) {
6620 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
6621 				    "Command Recovery called on busy send\n");
6622 				if (st_command_recovery(un, BP_PKT(bp),
6623 				    ATTEMPT_RETRY) == JUST_RETURN) {
6624 					return;
6625 				}
6626 			} else {
6627 				mutex_exit(ST_MUTEX);
6628 				if (st_handle_start_busy(un, bp,
6629 				    ST_TRAN_BUSY_TIMEOUT, queued) == 0) {
6630 					mutex_enter(ST_MUTEX);
6631 					return;
6632 				}
6633 				/*
6634 				 * if too many retries, fail the transport
6635 				 */
6636 				mutex_enter(ST_MUTEX);
6637 			}
6638 		}
6639 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6640 		    "transport rejected %d\n", status);
6641 		bp->b_resid = bp->b_bcount;
6642 
6643 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6644 		ST_DO_ERRSTATS(un, st_transerrs);
6645 		if ((bp == un->un_recov_buf) && (status == TRAN_BUSY)) {
6646 			st_bioerror(bp, EBUSY);
6647 		} else {
6648 			st_bioerror(bp, EIO);
6649 			st_set_pe_flag(un);
6650 		}
6651 		st_done_and_mutex_exit(un, bp);
6652 		mutex_enter(ST_MUTEX);
6653 	}
6654 
6655 	ASSERT(mutex_owned(ST_MUTEX));
6656 }
6657 
6658 /*
6659  * if the transport is busy, then put this bp back on the waitq
6660  */
6661 static int
6662 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6663     clock_t timeout_interval, int queued)
6664 {
6665 
6666 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
6667 
6668 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6669 
6670 	mutex_enter(ST_MUTEX);
6671 
6672 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6673 	    "st_handle_start_busy()\n");
6674 
6675 	/*
6676 	 * Check to see if we hit the retry timeout and one last check for
6677 	 * making sure this is the last on the runq, if it is not, we have
6678 	 * to fail
6679 	 */
6680 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
6681 	    ((queued) && (un->un_runql != bp))) {
6682 		mutex_exit(ST_MUTEX);
6683 		return (-1);
6684 	}
6685 
6686 	if (queued) {
6687 		/* put the bp back on the waitq */
6688 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
6689 	}
6690 
6691 	/*
6692 	 * Decrement un_ncmds so that this
6693 	 * gets thru' st_start() again.
6694 	 */
6695 	un->un_ncmds--;
6696 
6697 	if (queued) {
6698 		/*
6699 		 * since this is an error case, we won't have to do this list
6700 		 * walking much. We've already made sure this bp was the
6701 		 * last on the runq
6702 		 */
6703 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6704 
6705 		/*
6706 		 * send a marker pkt, if appropriate
6707 		 */
6708 		st_hba_unflush(un);
6709 
6710 	}
6711 	/*
6712 	 * all queues are aligned, we are just waiting to
6713 	 * transport, don't alloc any more buf p's, when
6714 	 * st_start is reentered.
6715 	 */
6716 	(void) timeout(st_start_restart, un, timeout_interval);
6717 
6718 	mutex_exit(ST_MUTEX);
6719 	return (0);
6720 }
6721 
6722 
6723 /*
6724  * st_runout a callback that is called what a resource allocatation failed
6725  */
6726 static int
6727 st_runout(caddr_t arg)
6728 {
6729 	struct scsi_tape *un = (struct scsi_tape *)arg;
6730 	struct buf *bp;
6731 	int queued;
6732 
6733 	ASSERT(un != NULL);
6734 
6735 	ST_FUNC(ST_DEVINFO, st_runout);
6736 
6737 	mutex_enter(ST_MUTEX);
6738 
6739 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6740 
6741 	if (un->un_recov_buf_busy != 0) {
6742 		bp = un->un_recov_buf;
6743 		queued = 0;
6744 	} else if (un->un_sbuf_busy != 0) {
6745 		/* sbuf commands should only happen with an empty queue. */
6746 		ASSERT(un->un_quef == NULL);
6747 		ASSERT(un->un_runqf == NULL);
6748 		bp = un->un_sbufp;
6749 		queued = 0;
6750 	} else if (un->un_quef != NULL) {
6751 		bp = un->un_quef;
6752 		if (un->un_persistence && un->un_persist_errors) {
6753 			mutex_exit(ST_MUTEX);
6754 			bp->b_resid = bp->b_bcount;
6755 			biodone(bp);
6756 			return (1);
6757 		}
6758 		queued = 1;
6759 	} else {
6760 		ASSERT(1 == 0);
6761 		mutex_exit(ST_MUTEX);
6762 		return (1);
6763 	}
6764 
6765 	/*
6766 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6767 	 */
6768 	if ((bp != NULL) && (geterror(bp) != 0)) {
6769 
6770 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6771 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6772 		    bp->b_flags, geterror(bp));
6773 		ASSERT((bp->b_flags & B_DONE) == 0);
6774 
6775 		if (queued) {
6776 			(void) st_remove_from_queue(&un->un_quef, &un->un_quel,
6777 			    bp);
6778 		}
6779 		mutex_exit(ST_MUTEX);
6780 
6781 		ASSERT((bp->b_flags & B_DONE) == 0);
6782 
6783 		/*
6784 		 * Set resid, Error already set, then unblock calling thread.
6785 		 */
6786 		bp->b_resid = bp->b_bcount;
6787 		biodone(bp);
6788 	} else {
6789 		/*
6790 		 * Try Again
6791 		 */
6792 		st_start(un);
6793 		mutex_exit(ST_MUTEX);
6794 	}
6795 
6796 	/*
6797 	 * Comments courtesy of sd.c
6798 	 * The scsi_init_pkt routine allows for the callback function to
6799 	 * return a 0 indicating the callback should be rescheduled or a 1
6800 	 * indicating not to reschedule. This routine always returns 1
6801 	 * because the driver always provides a callback function to
6802 	 * scsi_init_pkt. This results in a callback always being scheduled
6803 	 * (via the scsi_init_pkt callback implementation) if a resource
6804 	 * failure occurs.
6805 	 */
6806 
6807 	return (1);
6808 }
6809 
6810 /*
6811  * st_done_and_mutex_exit()
6812  *	- remove bp from runq
6813  *	- start up the next request
6814  *	- if this was an asynch bp, clean up
6815  *	- exit with released mutex
6816  */
6817 static void
6818 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6819 {
6820 	int pe_flagged = 0;
6821 	struct scsi_pkt *pkt = BP_PKT(bp);
6822 	pkt_info *pktinfo = pkt->pkt_private;
6823 
6824 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6825 #if !defined(lint)
6826 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6827 #endif
6828 
6829 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6830 
6831 	ASSERT(mutex_owned(ST_MUTEX));
6832 
6833 	(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6834 
6835 	un->un_ncmds--;
6836 	cv_signal(&un->un_queue_cv);
6837 
6838 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6839 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6840 	    "0x%x\n", pkt->pkt_cdbp[0], bp->b_bcount,
6841 	    bp->b_resid, bp->b_flags);
6842 
6843 
6844 	/*
6845 	 * update kstats with transfer count info
6846 	 */
6847 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6848 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6849 		if (bp->b_flags & B_READ) {
6850 			IOSP->reads++;
6851 			IOSP->nread += n_done;
6852 		} else {
6853 			IOSP->writes++;
6854 			IOSP->nwritten += n_done;
6855 		}
6856 	}
6857 
6858 	/*
6859 	 * Start the next one before releasing resources on this one, if
6860 	 * there is something on the queue and persistent errors has not been
6861 	 * flagged
6862 	 */
6863 
6864 	if ((pe_flagged = (un->un_persistence && un->un_persist_errors)) != 0) {
6865 		un->un_last_resid = bp->b_resid;
6866 		un->un_last_count = bp->b_bcount;
6867 	}
6868 
6869 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6870 		cv_broadcast(&un->un_tape_busy_cv);
6871 	} else if (un->un_quef && un->un_throttle && !pe_flagged &&
6872 	    (bp != un->un_recov_buf)) {
6873 		st_start(un);
6874 	}
6875 
6876 	un->un_retry_ct = max(pktinfo->pkt_retry_cnt, pktinfo->str_retry_cnt);
6877 
6878 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6879 		/*
6880 		 * Since we marked this ourselves as ASYNC,
6881 		 * there isn't anybody around waiting for
6882 		 * completion any more.
6883 		 */
6884 		uchar_t *cmd = pkt->pkt_cdbp;
6885 		if (*cmd == SCMD_READ || *cmd == SCMD_WRITE) {
6886 			bp->b_un.b_addr = (caddr_t)0;
6887 		}
6888 		ST_DEBUG(ST_DEVINFO, st_label, CE_NOTE,
6889 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6890 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
6891 		    "CDB sent with B_ASYNC",  (caddr_t)cmd);
6892 		if (pkt) {
6893 			scsi_destroy_pkt(pkt);
6894 		}
6895 		un->un_sbuf_busy = 0;
6896 		cv_signal(&un->un_sbuf_cv);
6897 		mutex_exit(ST_MUTEX);
6898 		return;
6899 	}
6900 
6901 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6902 		/*
6903 		 * Copy status from scsi_pkt to uscsi_cmd
6904 		 * since st_uscsi_cmd needs it
6905 		 */
6906 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6907 	}
6908 
6909 
6910 #ifdef STDEBUG
6911 	if (((st_debug & 0x7) >= 4) &&
6912 	    (((un->un_pos.blkno % 100) == 0) ||
6913 	    (un->un_persistence && un->un_persist_errors))) {
6914 
6915 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6916 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6917 		    "un_errno = %d, un_pe = %d\n",
6918 		    un->un_ncmds, un->un_throttle, un->un_errno,
6919 		    un->un_persist_errors);
6920 	}
6921 
6922 #endif
6923 
6924 	mutex_exit(ST_MUTEX);
6925 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6926 	    "st_done_and_mutex_exit: freeing pkt\n");
6927 
6928 	if (pkt) {
6929 		scsi_destroy_pkt(pkt);
6930 	}
6931 
6932 	biodone(bp);
6933 
6934 	/*
6935 	 * now that we biodoned that command, if persistent errors have been
6936 	 * flagged, flush the waitq
6937 	 */
6938 	if (pe_flagged)
6939 		st_flush(un);
6940 }
6941 
6942 
6943 /*
6944  * Tape error, flush tape driver queue.
6945  */
6946 static void
6947 st_flush(struct scsi_tape *un)
6948 {
6949 	struct buf *bp;
6950 
6951 	ST_FUNC(ST_DEVINFO, st_flush);
6952 
6953 	mutex_enter(ST_MUTEX);
6954 
6955 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6956 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6957 	    un->un_ncmds, (void *)un->un_quef);
6958 
6959 	/*
6960 	 * if we still have commands outstanding, wait for them to come in
6961 	 * before flushing the queue, and make sure there is a queue
6962 	 */
6963 	if (un->un_ncmds || !un->un_quef)
6964 		goto exit;
6965 
6966 	/*
6967 	 * we have no more commands outstanding, so let's deal with special
6968 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6969 	 * is 0, then we know there was no error and we return a 0 read or
6970 	 * write before showing errors
6971 	 */
6972 
6973 	/* Flush the wait queue. */
6974 	while ((bp = un->un_quef) != NULL) {
6975 		un->un_quef = bp->b_actf;
6976 
6977 		bp->b_resid = bp->b_bcount;
6978 
6979 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6980 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6981 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6982 
6983 		st_set_pe_errno(un);
6984 
6985 		bioerror(bp, un->un_errno);
6986 
6987 		mutex_exit(ST_MUTEX);
6988 		/* it should have one, but check anyway */
6989 		if (BP_PKT(bp)) {
6990 			scsi_destroy_pkt(BP_PKT(bp));
6991 		}
6992 		biodone(bp);
6993 		mutex_enter(ST_MUTEX);
6994 	}
6995 
6996 	/*
6997 	 * It's not a bad practice to reset the
6998 	 * waitq tail pointer to NULL.
6999 	 */
7000 	un->un_quel = NULL;
7001 
7002 exit:
7003 	/* we mucked with the queue, so let others know about it */
7004 	cv_signal(&un->un_queue_cv);
7005 	mutex_exit(ST_MUTEX);
7006 }
7007 
7008 
7009 /*
7010  * Utility functions
7011  */
7012 static int
7013 st_determine_generic(struct scsi_tape *un)
7014 {
7015 	int bsize;
7016 	static char *cart = "0.25 inch cartridge";
7017 	char *sizestr;
7018 
7019 	ST_FUNC(ST_DEVINFO, st_determine_generic);
7020 
7021 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7022 	    "st_determine_generic(un = 0x%p)\n", (void*)un);
7023 
7024 	ASSERT(mutex_owned(ST_MUTEX));
7025 
7026 	if (st_modesense(un)) {
7027 		return (-1);
7028 	}
7029 
7030 	bsize = (un->un_mspl->high_bl << 16)	|
7031 	    (un->un_mspl->mid_bl << 8)	|
7032 	    (un->un_mspl->low_bl);
7033 
7034 	if (bsize == 0) {
7035 		un->un_dp->options |= ST_VARIABLE;
7036 		un->un_dp->bsize = 0;
7037 		un->un_bsize = 0;
7038 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
7039 		/*
7040 		 * record size of this device too big.
7041 		 * try and convert it to variable record length.
7042 		 *
7043 		 */
7044 		un->un_dp->options |= ST_VARIABLE;
7045 		if (st_change_block_size(un, 0) != 0) {
7046 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7047 			    "Fixed Record Size %d is too large\n", bsize);
7048 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7049 			    "Cannot switch to variable record size\n");
7050 			un->un_dp->options &= ~ST_VARIABLE;
7051 			return (-1);
7052 		}
7053 	} else if (st_change_block_size(un, 0) == 0) {
7054 		/*
7055 		 * If the drive was set to a non zero block size,
7056 		 * See if it can be set to a zero block size.
7057 		 * If it works, ST_VARIABLE so user can set it as they want.
7058 		 */
7059 		un->un_dp->options |= ST_VARIABLE;
7060 		un->un_dp->bsize = 0;
7061 		un->un_bsize = 0;
7062 	} else {
7063 		un->un_dp->bsize = bsize;
7064 		un->un_bsize = bsize;
7065 	}
7066 
7067 
7068 	switch (un->un_mspl->density) {
7069 	default:
7070 	case 0x0:
7071 		/*
7072 		 * default density, cannot determine any other
7073 		 * information.
7074 		 */
7075 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
7076 		un->un_dp->type = ST_TYPE_DEFAULT;
7077 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
7078 		break;
7079 	case 0x1:
7080 	case 0x2:
7081 	case 0x3:
7082 	case 0x6:
7083 		/*
7084 		 * 1/2" reel
7085 		 */
7086 		sizestr = "0.50 inch reel";
7087 		un->un_dp->type = ST_TYPE_REEL;
7088 		un->un_dp->options |= ST_REEL;
7089 		un->un_dp->densities[0] = 0x1;
7090 		un->un_dp->densities[1] = 0x2;
7091 		un->un_dp->densities[2] = 0x6;
7092 		un->un_dp->densities[3] = 0x3;
7093 		break;
7094 	case 0x4:
7095 	case 0x5:
7096 	case 0x7:
7097 	case 0x0b:
7098 
7099 		/*
7100 		 * Quarter inch.
7101 		 */
7102 		sizestr = cart;
7103 		un->un_dp->type = ST_TYPE_DEFAULT;
7104 		un->un_dp->options |= ST_QIC;
7105 
7106 		un->un_dp->densities[1] = 0x4;
7107 		un->un_dp->densities[2] = 0x5;
7108 		un->un_dp->densities[3] = 0x7;
7109 		un->un_dp->densities[0] = 0x0b;
7110 		break;
7111 
7112 	case 0x0f:
7113 	case 0x10:
7114 	case 0x11:
7115 	case 0x12:
7116 		/*
7117 		 * QIC-120, QIC-150, QIC-320, QIC-600
7118 		 */
7119 		sizestr = cart;
7120 		un->un_dp->type = ST_TYPE_DEFAULT;
7121 		un->un_dp->options |= ST_QIC;
7122 		un->un_dp->densities[0] = 0x0f;
7123 		un->un_dp->densities[1] = 0x10;
7124 		un->un_dp->densities[2] = 0x11;
7125 		un->un_dp->densities[3] = 0x12;
7126 		break;
7127 
7128 	case 0x09:
7129 	case 0x0a:
7130 	case 0x0c:
7131 	case 0x0d:
7132 		/*
7133 		 * 1/2" cartridge tapes. Include HI-TC.
7134 		 */
7135 		sizestr = cart;
7136 		sizestr[2] = '5';
7137 		sizestr[3] = '0';
7138 		un->un_dp->type = ST_TYPE_HIC;
7139 		un->un_dp->densities[0] = 0x09;
7140 		un->un_dp->densities[1] = 0x0a;
7141 		un->un_dp->densities[2] = 0x0c;
7142 		un->un_dp->densities[3] = 0x0d;
7143 		break;
7144 
7145 	case 0x13:
7146 			/* DDS-2/DDS-3 scsi spec densities */
7147 	case 0x24:
7148 	case 0x25:
7149 	case 0x26:
7150 		sizestr = "DAT Data Storage (DDS)";
7151 		un->un_dp->type = ST_TYPE_DAT;
7152 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7153 		break;
7154 
7155 	case 0x14:
7156 		/*
7157 		 * Helical Scan (Exabyte) devices
7158 		 */
7159 		sizestr = "8mm helical scan cartridge";
7160 		un->un_dp->type = ST_TYPE_EXABYTE;
7161 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7162 		break;
7163 	}
7164 
7165 	/*
7166 	 * Assume LONG ERASE, BSF and BSR
7167 	 */
7168 
7169 	un->un_dp->options |=
7170 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
7171 
7172 	/*
7173 	 * Only if mode sense data says no buffered write, set NOBUF
7174 	 */
7175 	if (un->un_mspl->bufm == 0)
7176 		un->un_dp->options |= ST_NOBUF;
7177 
7178 	/*
7179 	 * set up large read and write retry counts
7180 	 */
7181 
7182 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
7183 
7184 	/*
7185 	 * If this is a 0.50 inch reel tape, and
7186 	 * it is *not* variable mode, try and
7187 	 * set it to variable record length
7188 	 * mode.
7189 	 */
7190 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
7191 	    (un->un_dp->options & ST_VARIABLE)) {
7192 		if (st_change_block_size(un, 0) == 0) {
7193 			un->un_dp->bsize = 0;
7194 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
7195 			    un->un_mspl->low_bl = 0;
7196 		}
7197 	}
7198 
7199 	/*
7200 	 * Write to console about type of device found
7201 	 */
7202 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
7203 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
7204 	    sizestr);
7205 	if (un->un_dp->options & ST_VARIABLE) {
7206 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7207 		    "!Variable record length I/O\n");
7208 	} else {
7209 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7210 		    "!Fixed record length (%d byte blocks) I/O\n",
7211 		    un->un_dp->bsize);
7212 	}
7213 	ASSERT(mutex_owned(ST_MUTEX));
7214 	return (0);
7215 }
7216 
7217 static int
7218 st_determine_density(struct scsi_tape *un, int rw)
7219 {
7220 	int rval = 0;
7221 
7222 	ST_FUNC(ST_DEVINFO, st_determine_density);
7223 
7224 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7225 	    "st_determine_density(un = 0x%p, rw = %s)\n",
7226 	    (void*)un, (rw == B_WRITE ? wr_str: rd_str));
7227 
7228 	ASSERT(mutex_owned(ST_MUTEX));
7229 
7230 	/*
7231 	 * If we're past BOT, density is determined already.
7232 	 */
7233 	if (un->un_pos.pmode == logical) {
7234 		if (un->un_pos.lgclblkno != 0) {
7235 			goto exit;
7236 		}
7237 	} else if (un->un_pos.pmode == legacy) {
7238 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
7239 			/*
7240 			 * XXX: put in a bitch message about attempting to
7241 			 * XXX: change density past BOT.
7242 			 */
7243 			goto exit;
7244 		}
7245 	} else {
7246 		goto exit;
7247 	}
7248 	if ((un->un_pos.pmode == logical) &&
7249 	    (un->un_pos.lgclblkno != 0)) {
7250 		goto exit;
7251 	}
7252 
7253 
7254 	/*
7255 	 * If we're going to be writing, we set the density
7256 	 */
7257 	if (rw == 0 || rw == B_WRITE) {
7258 		/* un_curdens is used as an index into densities table */
7259 		un->un_curdens = MT_DENSITY(un->un_dev);
7260 		if (st_set_density(un)) {
7261 			rval = -1;
7262 		}
7263 		goto exit;
7264 	}
7265 
7266 	/*
7267 	 * If density is known already,
7268 	 * we don't have to get it again.(?)
7269 	 */
7270 	if (!un->un_density_known) {
7271 		if (st_get_density(un)) {
7272 			rval = -1;
7273 		}
7274 	}
7275 
7276 exit:
7277 	ASSERT(mutex_owned(ST_MUTEX));
7278 	return (rval);
7279 }
7280 
7281 
7282 /*
7283  * Try to determine density. We do this by attempting to read the
7284  * first record off the tape, cycling through the available density
7285  * codes as we go.
7286  */
7287 
7288 static int
7289 st_get_density(struct scsi_tape *un)
7290 {
7291 	int succes = 0, rval = -1, i;
7292 	uint_t size;
7293 	uchar_t dens, olddens;
7294 
7295 	ST_FUNC(ST_DEVINFO, st_get_density);
7296 
7297 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7298 	    "st_get_density(un = 0x%p)\n", (void*)un);
7299 
7300 	ASSERT(mutex_owned(ST_MUTEX));
7301 
7302 	/*
7303 	 * If Auto Density override is enabled The drive has
7304 	 * only one density and there is no point in attempting
7305 	 * find the correct one.
7306 	 *
7307 	 * Since most modern drives auto detect the density
7308 	 * and format of the recorded media before they come
7309 	 * ready. What this function does is a legacy behavior
7310 	 * and modern drives not only don't need it, The backup
7311 	 * utilities that do positioning via uscsi find the un-
7312 	 * expected rewinds problematic.
7313 	 *
7314 	 * The drives that need this are old reel to reel devices.
7315 	 * I took a swag and said they must be scsi-1 or older.
7316 	 * I don't beleave there will any of the newer devices
7317 	 * that need this. There will be some scsi-1 devices that
7318 	 * don't need this but I don't think they will be using the
7319 	 * BIG aftermarket backup and restore utilitys.
7320 	 */
7321 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
7322 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
7323 		un->un_density_known = 1;
7324 		rval = 0;
7325 		goto exit;
7326 	}
7327 
7328 	/*
7329 	 * This will only work on variable record length tapes
7330 	 * if and only if all variable record length tapes autodensity
7331 	 * select.
7332 	 */
7333 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
7334 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
7335 
7336 	/*
7337 	 * Start at the specified density
7338 	 */
7339 
7340 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
7341 
7342 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
7343 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
7344 		/*
7345 		 * If we've done this density before,
7346 		 * don't bother to do it again.
7347 		 */
7348 		dens = un->un_dp->densities[un->un_curdens];
7349 		if (i > 0 && dens == olddens)
7350 			continue;
7351 		olddens = dens;
7352 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7353 		    "trying density 0x%x\n", dens);
7354 		if (st_set_density(un)) {
7355 			continue;
7356 		}
7357 
7358 		/*
7359 		 * XXX - the creates lots of headaches and slowdowns - must
7360 		 * fix.
7361 		 */
7362 		succes = (st_cmd(un, SCMD_READ, (int)size, SYNC_CMD) == 0);
7363 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
7364 			break;
7365 		}
7366 		if (succes) {
7367 			st_init(un);
7368 			rval = 0;
7369 			un->un_density_known = 1;
7370 			break;
7371 		}
7372 	}
7373 	kmem_free(un->un_tmpbuf, size);
7374 	un->un_tmpbuf = 0;
7375 
7376 exit:
7377 	ASSERT(mutex_owned(ST_MUTEX));
7378 	return (rval);
7379 }
7380 
7381 static int
7382 st_set_density(struct scsi_tape *un)
7383 {
7384 	int rval = 0;
7385 
7386 	ST_FUNC(ST_DEVINFO, st_set_density);
7387 
7388 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7389 	    "st_set_density(un = 0x%p): density = 0x%x\n", (void*)un,
7390 	    un->un_dp->densities[un->un_curdens]);
7391 
7392 	ASSERT(mutex_owned(ST_MUTEX));
7393 
7394 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7395 
7396 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
7397 		/*
7398 		 * If auto density override is not set, Use mode select
7399 		 * to set density and compression.
7400 		 */
7401 		if (st_modeselect(un)) {
7402 			rval = -1;
7403 		}
7404 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
7405 		/*
7406 		 * If auto density and mode select compression are set,
7407 		 * This is a drive with one density code but compression
7408 		 * can be enabled or disabled.
7409 		 * Set compression but no need to set density.
7410 		 */
7411 		rval = st_set_compression(un);
7412 		if ((rval != 0) && (rval != EALREADY)) {
7413 			rval = -1;
7414 		} else {
7415 			rval = 0;
7416 		}
7417 	}
7418 
7419 	/* If sucessful set density and/or compression, mark density known */
7420 	if (rval == 0) {
7421 		un->un_density_known = 1;
7422 	}
7423 
7424 	ASSERT(mutex_owned(ST_MUTEX));
7425 	return (rval);
7426 }
7427 
7428 static int
7429 st_loadtape(struct scsi_tape *un)
7430 {
7431 	int rval;
7432 
7433 	ST_FUNC(ST_DEVINFO, st_loadtape);
7434 
7435 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7436 	    "st_loadtape(un = 0x%p)\n", (void*) un);
7437 
7438 	ASSERT(mutex_owned(ST_MUTEX));
7439 
7440 	rval = st_update_block_pos(un, st_cmd, 0);
7441 	if (rval == EACCES) {
7442 		return (rval);
7443 	}
7444 
7445 	/*
7446 	 * 'LOAD' the tape to BOT by rewinding
7447 	 */
7448 	rval = st_cmd(un, SCMD_REWIND, 1, SYNC_CMD);
7449 	if (rval == 0) {
7450 		st_init(un);
7451 		un->un_density_known = 0;
7452 	}
7453 
7454 	ASSERT(mutex_owned(ST_MUTEX));
7455 	return (rval);
7456 }
7457 
7458 
7459 /*
7460  * Note: QIC devices aren't so smart.  If you try to append
7461  * after EOM, the write can fail because the device doesn't know
7462  * it's at EOM.	 In that case, issue a read.  The read should fail
7463  * because there's no data, but the device knows it's at EOM,
7464  * so a subsequent write should succeed.  To further confuse matters,
7465  * the target returns the same error if the tape is positioned
7466  * such that a write would overwrite existing data.  That's why
7467  * we have to do the append test.  A read in the middle of
7468  * recorded data would succeed, thus indicating we're attempting
7469  * something illegal.
7470  */
7471 
7472 
7473 static void
7474 st_test_append(struct buf *bp)
7475 {
7476 	dev_t dev = bp->b_edev;
7477 	struct scsi_tape *un;
7478 	uchar_t status;
7479 	unsigned bcount;
7480 
7481 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7482 
7483 	ST_FUNC(ST_DEVINFO, st_test_append);
7484 
7485 	ASSERT(mutex_owned(ST_MUTEX));
7486 
7487 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7488 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7489 
7490 	un->un_laststate = un->un_state;
7491 	un->un_state = ST_STATE_APPEND_TESTING;
7492 	un->un_test_append = 0;
7493 
7494 	/*
7495 	 * first, map in the buffer, because we're doing a double write --
7496 	 * first into the kernel, then onto the tape.
7497 	 */
7498 	bp_mapin(bp);
7499 
7500 	/*
7501 	 * get a copy of the data....
7502 	 */
7503 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7504 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7505 
7506 	/*
7507 	 * attempt the write..
7508 	 */
7509 
7510 	if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7511 success:
7512 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7513 		    "append write succeeded\n");
7514 		bp->b_resid = un->un_sbufp->b_resid;
7515 		mutex_exit(ST_MUTEX);
7516 		bcount = (unsigned)bp->b_bcount;
7517 		biodone(bp);
7518 		mutex_enter(ST_MUTEX);
7519 		un->un_laststate = un->un_state;
7520 		un->un_state = ST_STATE_OPEN;
7521 		kmem_free(un->un_tmpbuf, bcount);
7522 		un->un_tmpbuf = NULL;
7523 		return;
7524 	}
7525 
7526 	/*
7527 	 * The append failed. Do a short read. If that fails,  we are at EOM
7528 	 * so we can retry the write command. If that succeeds, than we're
7529 	 * all screwed up (the controller reported a real error).
7530 	 *
7531 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7532 	 * XXX: block size?
7533 	 *
7534 	 */
7535 	status = un->un_status;
7536 	un->un_status = 0;
7537 	(void) st_cmd(un, SCMD_READ, SECSIZE, SYNC_CMD);
7538 	if (un->un_status == KEY_BLANK_CHECK) {
7539 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7540 		    "append at EOM\n");
7541 		/*
7542 		 * Okay- the read failed. We should actually have confused
7543 		 * the controller enough to allow writing. In any case, the
7544 		 * i/o is on its own from here on out.
7545 		 */
7546 		un->un_laststate = un->un_state;
7547 		un->un_state = ST_STATE_OPEN;
7548 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7549 		if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount,
7550 		    SYNC_CMD) == 0) {
7551 			goto success;
7552 		}
7553 	}
7554 
7555 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7556 	    "append write failed- not at EOM\n");
7557 	bp->b_resid = bp->b_bcount;
7558 	st_bioerror(bp, EIO);
7559 
7560 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7561 	    "st_test_append : EIO : append write failed - not at EOM");
7562 
7563 	/*
7564 	 * backspace one record to get back to where we were
7565 	 */
7566 	if (st_cmd(un, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7567 		un->un_pos.pmode = invalid;
7568 	}
7569 
7570 	un->un_err_resid = bp->b_resid;
7571 	un->un_status = status;
7572 
7573 	/*
7574 	 * Note: biodone will do a bp_mapout()
7575 	 */
7576 	mutex_exit(ST_MUTEX);
7577 	bcount = (unsigned)bp->b_bcount;
7578 	biodone(bp);
7579 	mutex_enter(ST_MUTEX);
7580 	un->un_laststate = un->un_state;
7581 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7582 	kmem_free(un->un_tmpbuf, bcount);
7583 	un->un_tmpbuf = NULL;
7584 }
7585 
7586 /*
7587  * Special command handler
7588  */
7589 
7590 /*
7591  * common st_cmd code. The fourth parameter states
7592  * whether the caller wishes to await the results
7593  * Note the release of the mutex during most of the function
7594  */
7595 static int
7596 st_cmd(struct scsi_tape *un, int com, int64_t count, int wait)
7597 {
7598 	struct buf *bp;
7599 	int err;
7600 	uint_t last_err_resid;
7601 
7602 	ST_FUNC(ST_DEVINFO, st_cmd);
7603 
7604 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7605 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %"PRIx64", wait = %d)\n",
7606 	    un->un_dev, com, count, wait);
7607 
7608 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7609 	ASSERT(mutex_owned(ST_MUTEX));
7610 
7611 #ifdef STDEBUG
7612 	if ((st_debug & 0x7)) {
7613 		st_debug_cmds(un, com, count, wait);
7614 	}
7615 #endif
7616 
7617 	st_wait_for_io(un);
7618 
7619 	/* check to see if this command requires the drive to be reserved */
7620 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7621 
7622 	if (err) {
7623 		return (err);
7624 	}
7625 
7626 	/*
7627 	 * A space command is not recoverable if we don't know were we
7628 	 * were when it was issued.
7629 	 */
7630 	if ((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) {
7631 		(void) st_update_block_pos(un, st_cmd, 0);
7632 	}
7633 
7634 	/*
7635 	 * Forground should not be doing anything while recovery is active.
7636 	 */
7637 	ASSERT(un->un_recov_buf_busy == 0);
7638 
7639 	while (un->un_sbuf_busy)
7640 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7641 	un->un_sbuf_busy = 1;
7642 
7643 	bp = un->un_sbufp;
7644 	bzero(bp, sizeof (buf_t));
7645 
7646 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7647 
7648 	err = st_setup_cmd(un, bp, com, count);
7649 
7650 	un->un_sbuf_busy = 0;
7651 
7652 	/*
7653 	 * If was a space command need to update logical block position.
7654 	 * Only do this if the command was sucessful or it will mask the fact
7655 	 * that the space command failed by promoting the pmode to logical.
7656 	 */
7657 	if (((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) &&
7658 	    (un->un_pos.pmode != invalid)) {
7659 		un->un_running.pmode = invalid;
7660 		last_err_resid = un->un_err_resid;
7661 		(void) st_update_block_pos(un, st_cmd, 1);
7662 		/*
7663 		 * Set running position to invalid so it updates on the
7664 		 * next command.
7665 		 */
7666 		un->un_running.pmode = invalid;
7667 		un->un_err_resid = last_err_resid;
7668 	}
7669 
7670 	cv_signal(&un->un_sbuf_cv);
7671 
7672 	return (err);
7673 }
7674 
7675 static int
7676 st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com, int64_t count)
7677 {
7678 	int err;
7679 	dev_t dev = un->un_dev;
7680 
7681 	ST_FUNC(ST_DEVINFO, st_setup_cmd);
7682 	/*
7683 	 * Set count to the actual size of the data tranfer.
7684 	 * For commands with no data transfer, set bp->b_bcount
7685 	 * to the value to be used when constructing the
7686 	 * cdb in st_make_cmd().
7687 	 */
7688 	switch (com) {
7689 	case SCMD_READ:
7690 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7691 		    "special read %"PRId64"\n", count);
7692 		bp->b_flags |= B_READ;
7693 		bp->b_un.b_addr = un->un_tmpbuf;
7694 		break;
7695 
7696 	case SCMD_WRITE:
7697 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7698 		    "special write %"PRId64"\n", count);
7699 		bp->b_un.b_addr = un->un_tmpbuf;
7700 		break;
7701 
7702 	case SCMD_WRITE_FILE_MARK:
7703 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7704 		    "write %"PRId64" file marks\n", count);
7705 		bp->b_bcount = count;
7706 		count = 0;
7707 		break;
7708 
7709 	case SCMD_REWIND:
7710 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7711 		bp->b_bcount = count;
7712 		count = 0;
7713 		break;
7714 
7715 	case SCMD_SPACE:
7716 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7717 		/*
7718 		 * If the user could have entered a number that will
7719 		 * not fit in the 12 bit count field of space(8),
7720 		 * use space(16).
7721 		 */
7722 		if (((int64_t)SPACE_CNT(count) > 0x7fffff) ||
7723 		    ((int64_t)SPACE_CNT(count) < -(0x7fffff))) {
7724 			com = SCMD_SPACE_G4;
7725 		}
7726 		bp->b_bcount = count;
7727 		count = 0;
7728 		break;
7729 
7730 	case SCMD_RESERVE:
7731 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7732 		bp->b_bcount = 0;
7733 		count = 0;
7734 		break;
7735 
7736 	case SCMD_RELEASE:
7737 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7738 		bp->b_bcount = 0;
7739 		count = 0;
7740 		break;
7741 
7742 	case SCMD_LOAD:
7743 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7744 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7745 		bp->b_bcount = count;
7746 		count = 0;
7747 		break;
7748 
7749 	case SCMD_ERASE:
7750 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7751 		    "erase tape\n");
7752 		bp->b_bcount = count;
7753 		count = 0;
7754 		break;
7755 
7756 	case SCMD_MODE_SENSE:
7757 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7758 		    "mode sense\n");
7759 		bp->b_flags |= B_READ;
7760 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7761 		break;
7762 
7763 	case SCMD_MODE_SELECT:
7764 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7765 		    "mode select\n");
7766 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7767 		break;
7768 
7769 	case SCMD_READ_BLKLIM:
7770 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7771 		    "read block limits\n");
7772 		bp->b_bcount = count;
7773 		bp->b_flags |= B_READ;
7774 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7775 		break;
7776 
7777 	case SCMD_TEST_UNIT_READY:
7778 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7779 		    "test unit ready\n");
7780 		bp->b_bcount = 0;
7781 		count = 0;
7782 		break;
7783 
7784 	case SCMD_DOORLOCK:
7785 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7786 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7787 		bp->b_bcount = count = 0;
7788 		break;
7789 
7790 	case SCMD_READ_POSITION:
7791 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7792 		    "read position\n");
7793 		switch (un->un_read_pos_type) {
7794 		case LONG_POS:
7795 			count = sizeof (tape_position_long_t);
7796 			break;
7797 		case EXT_POS:
7798 			count = min(count, sizeof (tape_position_ext_t));
7799 			break;
7800 		case SHORT_POS:
7801 			count = sizeof (tape_position_t);
7802 			break;
7803 		default:
7804 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7805 			    "Unknown read position type 0x%x in "
7806 			    "st_make_cmd()\n", un->un_read_pos_type);
7807 		}
7808 		bp->b_bcount = count;
7809 		bp->b_flags |= B_READ;
7810 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7811 		break;
7812 
7813 	default:
7814 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7815 		    "Unhandled scsi command 0x%x in st_setup_cmd()\n", com);
7816 	}
7817 
7818 	mutex_exit(ST_MUTEX);
7819 
7820 	if (count > 0) {
7821 		int flg = (bp->b_flags & B_READ) ? B_READ : B_WRITE;
7822 		/*
7823 		 * We're going to do actual I/O.
7824 		 * Set things up for physio.
7825 		 */
7826 		struct iovec aiov;
7827 		struct uio auio;
7828 		struct uio *uio = &auio;
7829 
7830 		bzero(&auio, sizeof (struct uio));
7831 		bzero(&aiov, sizeof (struct iovec));
7832 		aiov.iov_base = bp->b_un.b_addr;
7833 		aiov.iov_len = count;
7834 
7835 		uio->uio_iov = &aiov;
7836 		uio->uio_iovcnt = 1;
7837 		uio->uio_resid = aiov.iov_len;
7838 		uio->uio_segflg = UIO_SYSSPACE;
7839 
7840 		/*
7841 		 * Let physio do the rest...
7842 		 */
7843 		bp->b_forw = (struct buf *)(uintptr_t)com;
7844 		bp->b_back = NULL;
7845 		err = physio(st_strategy, bp, dev, flg, st_minphys, uio);
7846 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7847 		    "st_setup_cmd: physio returns %d\n", err);
7848 	} else {
7849 		/*
7850 		 * Mimic physio
7851 		 */
7852 		bp->b_forw = (struct buf *)(uintptr_t)com;
7853 		bp->b_back = NULL;
7854 		bp->b_edev = dev;
7855 		bp->b_dev = cmpdev(dev);
7856 		bp->b_blkno = 0;
7857 		bp->b_resid = 0;
7858 		(void) st_strategy(bp);
7859 		if (bp->b_flags & B_ASYNC) {
7860 			/*
7861 			 * This is an async command- the caller won't wait
7862 			 * and doesn't care about errors.
7863 			 */
7864 			mutex_enter(ST_MUTEX);
7865 			return (0);
7866 		}
7867 
7868 		/*
7869 		 * BugTraq #4260046
7870 		 * ----------------
7871 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7872 		 * unconditionally. The old comment said...
7873 		 *
7874 		 * "if strategy was flagged with  persistent errors, we would
7875 		 *  have an error here, and the bp would never be sent, so we
7876 		 *  don't want to wait on a bp that was never sent...or hang"
7877 		 *
7878 		 * The new rationale, courtesy of Chitrank...
7879 		 *
7880 		 * "we should unconditionally biowait() here because
7881 		 *  st_strategy() will do a biodone() in the persistent error
7882 		 *  case and the following biowait() will return immediately.
7883 		 *  If not, in the case of "errors after pkt alloc" in
7884 		 *  st_start(), we will not biowait here which will cause the
7885 		 *  next biowait() to return immediately which will cause
7886 		 *  us to send out the next command. In the case where both of
7887 		 *  these use the sbuf, when the first command completes we'll
7888 		 *  free the packet attached to sbuf and the same pkt will
7889 		 *  get freed again when we complete the second command.
7890 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7891 		 *  st_start() for the pkt alloc failure case because physio()
7892 		 *  does biowait() and will hang if we don't do biodone()"
7893 		 */
7894 
7895 		err = biowait(bp);
7896 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7897 		    "st_setup_cmd: biowait returns %d\n", err);
7898 	}
7899 
7900 	mutex_enter(ST_MUTEX);
7901 
7902 	return (err);
7903 }
7904 
7905 static int
7906 st_set_compression(struct scsi_tape *un)
7907 {
7908 	int rval;
7909 	int turn_compression_on;
7910 	minor_t minor;
7911 
7912 	ST_FUNC(ST_DEVINFO, st_set_compression);
7913 
7914 	/*
7915 	 * Drive either dosn't have compression or it is controlled with
7916 	 * special density codes. Return ENOTTY so caller
7917 	 * knows nothing was done.
7918 	 */
7919 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7920 		un->un_comp_page = 0;
7921 		return (ENOTTY);
7922 	}
7923 
7924 	/* set compression based on minor node opened */
7925 	minor = MT_DENSITY(un->un_dev);
7926 
7927 	/*
7928 	 * If this the compression density or
7929 	 * the drive has two densities and uses mode select for
7930 	 * control of compression turn on compression for MT_DENSITY2
7931 	 * as well.
7932 	 */
7933 	if ((minor == ST_COMPRESSION_DENSITY) ||
7934 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7935 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7936 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7937 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7938 
7939 		turn_compression_on = 1;
7940 	} else {
7941 		turn_compression_on = 0;
7942 	}
7943 
7944 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7945 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7946 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7947 
7948 	/*
7949 	 * Need to determine which page does the device use for compression.
7950 	 * First try the data compression page. If this fails try the device
7951 	 * configuration page
7952 	 */
7953 
7954 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7955 		rval = st_set_datacomp_page(un, turn_compression_on);
7956 		if (rval == EALREADY) {
7957 			return (rval);
7958 		}
7959 		if (rval != 0) {
7960 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7961 				/*
7962 				 * This device does not support data
7963 				 * compression page
7964 				 */
7965 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7966 			} else if (un->un_state >= ST_STATE_OPEN) {
7967 				un->un_pos.pmode = invalid;
7968 				rval = EIO;
7969 			} else {
7970 				rval = -1;
7971 			}
7972 		} else {
7973 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7974 		}
7975 	}
7976 
7977 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7978 		rval = st_set_devconfig_page(un, turn_compression_on);
7979 		if (rval == EALREADY) {
7980 			return (rval);
7981 		}
7982 		if (rval != 0) {
7983 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7984 				/*
7985 				 * This device does not support
7986 				 * compression at all advice the
7987 				 * user and unset ST_MODE_SEL_COMP
7988 				 */
7989 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7990 				un->un_comp_page = 0;
7991 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7992 				    "Device Does Not Support Compression\n");
7993 			} else if (un->un_state >= ST_STATE_OPEN) {
7994 				un->un_pos.pmode = invalid;
7995 				rval = EIO;
7996 			} else {
7997 				rval = -1;
7998 			}
7999 		}
8000 	}
8001 
8002 	return (rval);
8003 }
8004 
8005 /*
8006  * set or unset compression thru device configuration page.
8007  */
8008 static int
8009 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
8010 {
8011 	unsigned char cflag;
8012 	int rval = 0;
8013 
8014 
8015 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
8016 
8017 	ASSERT(mutex_owned(ST_MUTEX));
8018 
8019 	/*
8020 	 * if the mode sense page is not the correct one, load the correct one.
8021 	 */
8022 	if (un->un_mspl->page_code != ST_DEV_CONFIG_PAGE) {
8023 		rval = st_gen_mode_sense(un, st_uscsi_cmd, ST_DEV_CONFIG_PAGE,
8024 		    un->un_mspl, sizeof (struct seq_mode));
8025 		if (rval)
8026 			return (rval);
8027 	}
8028 
8029 	/*
8030 	 * Figure what to set compression flag to.
8031 	 */
8032 	if (compression_on) {
8033 		/* They have selected a compression node */
8034 		if (un->un_dp->type == ST_TYPE_FUJI) {
8035 			cflag = 0x84;   /* use EDRC */
8036 		} else {
8037 			cflag = ST_DEV_CONFIG_DEF_COMP;
8038 		}
8039 	} else {
8040 		cflag = ST_DEV_CONFIG_NO_COMP;
8041 	}
8042 
8043 	/*
8044 	 * If compression is already set the way it was requested.
8045 	 * And if this not the first time we has tried.
8046 	 */
8047 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
8048 	    (un->un_comp_page == ST_DEV_CONFIG_PAGE)) {
8049 		return (EALREADY);
8050 	}
8051 
8052 	un->un_mspl->page.dev.comp_alg = cflag;
8053 	/*
8054 	 * need to send mode select even if correct compression is
8055 	 * already set since need to set density code
8056 	 */
8057 
8058 #ifdef STDEBUG
8059 	if ((st_debug & 0x7) >= 6) {
8060 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8061 		    "st_set_devconfig_page: sense data for mode select",
8062 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8063 	}
8064 #endif
8065 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8066 	    sizeof (struct seq_mode));
8067 
8068 	return (rval);
8069 }
8070 
8071 /*
8072  * set/reset compression bit thru data compression page
8073  */
8074 static int
8075 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
8076 {
8077 	int compression_on_already;
8078 	int rval = 0;
8079 
8080 
8081 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
8082 
8083 	ASSERT(mutex_owned(ST_MUTEX));
8084 
8085 	/*
8086 	 * if the mode sense page is not the correct one, load the correct one.
8087 	 */
8088 	if (un->un_mspl->page_code != ST_DEV_DATACOMP_PAGE) {
8089 		rval = st_gen_mode_sense(un, st_uscsi_cmd, ST_DEV_DATACOMP_PAGE,
8090 		    un->un_mspl, sizeof (struct seq_mode));
8091 		if (rval)
8092 			return (rval);
8093 	}
8094 
8095 	/*
8096 	 * If drive is not capable of compression (at this time)
8097 	 * return EALREADY so caller doesn't think that this page
8098 	 * is not supported. This check is for drives that can
8099 	 * disable compression from the front panel or configuration.
8100 	 * I doubt that a drive that supports this page is not really
8101 	 * capable of compression.
8102 	 */
8103 	if (un->un_mspl->page.comp.dcc == 0) {
8104 		return (EALREADY);
8105 	}
8106 
8107 	/* See if compression currently turned on */
8108 	if (un->un_mspl->page.comp.dce) {
8109 		compression_on_already = 1;
8110 	} else {
8111 		compression_on_already = 0;
8112 	}
8113 
8114 	/*
8115 	 * If compression is already set the way it was requested.
8116 	 * And if this not the first time we has tried.
8117 	 */
8118 	if ((compression_on == compression_on_already) &&
8119 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
8120 		return (EALREADY);
8121 	}
8122 
8123 	/*
8124 	 * if we are already set to the appropriate compression
8125 	 * mode, don't set it again
8126 	 */
8127 	if (compression_on) {
8128 		/* compression selected */
8129 		un->un_mspl->page.comp.dce = 1;
8130 	} else {
8131 		un->un_mspl->page.comp.dce = 0;
8132 	}
8133 
8134 
8135 #ifdef STDEBUG
8136 	if ((st_debug & 0x7) >= 6) {
8137 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8138 		    "st_set_datacomp_page: sense data for mode select",
8139 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8140 	}
8141 #endif
8142 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8143 	    sizeof (struct seq_mode));
8144 
8145 	return (rval);
8146 }
8147 
8148 static int
8149 st_modesense(struct scsi_tape *un)
8150 {
8151 	int rval;
8152 	uchar_t page;
8153 
8154 	ST_FUNC(ST_DEVINFO, st_modesense);
8155 
8156 	page = un->un_comp_page;
8157 
8158 	switch (page) {
8159 	case ST_DEV_DATACOMP_PAGE:
8160 	case ST_DEV_CONFIG_PAGE: /* FALLTHROUGH */
8161 		rval = st_gen_mode_sense(un, st_uscsi_cmd, page, un->un_mspl,
8162 		    sizeof (struct seq_mode));
8163 		break;
8164 
8165 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
8166 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
8167 			page = ST_DEV_DATACOMP_PAGE;
8168 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8169 			    un->un_mspl, sizeof (struct seq_mode));
8170 			if (rval == 0 && un->un_mspl->page_code == page) {
8171 				un->un_comp_page = page;
8172 				break;
8173 			}
8174 			page = ST_DEV_CONFIG_PAGE;
8175 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8176 			    un->un_mspl, sizeof (struct seq_mode));
8177 			if (rval == 0 && un->un_mspl->page_code == page) {
8178 				un->un_comp_page = page;
8179 				break;
8180 			}
8181 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
8182 			un->un_comp_page = 0;
8183 		} else {
8184 			un->un_comp_page = 0;
8185 		}
8186 
8187 	default:	/* FALLTHROUGH */
8188 		rval = st_cmd(un, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
8189 	}
8190 	return (rval);
8191 }
8192 
8193 static int
8194 st_modeselect(struct scsi_tape *un)
8195 {
8196 	int rval = 0;
8197 	int ix;
8198 
8199 	ST_FUNC(ST_DEVINFO, st_modeselect);
8200 
8201 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8202 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
8203 	    un->un_dev, un->un_mspl->density);
8204 
8205 	ASSERT(mutex_owned(ST_MUTEX));
8206 
8207 	/*
8208 	 * The parameter list should be the same for all of the
8209 	 * cases that follow so set them here
8210 	 *
8211 	 * Try mode select first if if fails set fields manually
8212 	 */
8213 	rval = st_modesense(un);
8214 	if (rval != 0) {
8215 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8216 		    "st_modeselect: First mode sense failed\n");
8217 		un->un_mspl->bd_len  = 8;
8218 		un->un_mspl->high_nb = 0;
8219 		un->un_mspl->mid_nb  = 0;
8220 		un->un_mspl->low_nb  = 0;
8221 	}
8222 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
8223 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
8224 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
8225 
8226 
8227 	/*
8228 	 * If configured to use a specific density code for a media type.
8229 	 * curdens is previously set by the minor node opened.
8230 	 * If the media type doesn't match the minor node we change it so it
8231 	 * looks like the correct one was opened.
8232 	 */
8233 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
8234 		uchar_t best;
8235 
8236 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
8237 			if (un->un_mspl->media_type ==
8238 			    un->un_dp->mediatype[ix]) {
8239 				best = ix;
8240 				/*
8241 				 * It matches but it might not be the only one.
8242 				 * Use the highest matching media type but not
8243 				 * to exceed the density selected by the open.
8244 				 */
8245 				if (ix < un->un_curdens) {
8246 					continue;
8247 				}
8248 				un->un_curdens = ix;
8249 				break;
8250 			}
8251 		}
8252 		/* If a match was found best will not be 0xff any more */
8253 		if (best < NDENSITIES) {
8254 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8255 			    "found media 0x%X using density 0x%X\n",
8256 			    un->un_mspl->media_type,
8257 			    un->un_dp->densities[best]);
8258 			un->un_mspl->density = un->un_dp->densities[best];
8259 		} else {
8260 			/* Otherwise set density based on minor node opened */
8261 			un->un_mspl->density =
8262 			    un->un_dp->densities[un->un_curdens];
8263 		}
8264 	} else {
8265 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
8266 	}
8267 
8268 	if (un->un_dp->options & ST_NOBUF) {
8269 		un->un_mspl->bufm = 0;
8270 	} else {
8271 		un->un_mspl->bufm = 1;
8272 	}
8273 
8274 	rval = st_set_compression(un);
8275 
8276 	/*
8277 	 * If st_set_compression returned invalid or already it
8278 	 * found no need to do the mode select.
8279 	 * So do it here.
8280 	 */
8281 	if ((rval == ENOTTY) || (rval == EALREADY)) {
8282 
8283 		/* Zero non-writeable fields */
8284 		un->un_mspl->data_len = 0;
8285 		un->un_mspl->media_type = 0;
8286 		un->un_mspl->wp = 0;
8287 
8288 		/* need to set the density code */
8289 		rval = st_cmd(un, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
8290 		if (rval != 0) {
8291 			if (un->un_state >= ST_STATE_OPEN) {
8292 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8293 				    "unable to set tape mode\n");
8294 				un->un_pos.pmode = invalid;
8295 				rval = EIO;
8296 			} else {
8297 				rval = -1;
8298 			}
8299 		}
8300 	}
8301 
8302 	/*
8303 	 * The spec recommends to send a mode sense after a mode select
8304 	 */
8305 	(void) st_modesense(un);
8306 
8307 	ASSERT(mutex_owned(ST_MUTEX));
8308 
8309 	return (rval);
8310 }
8311 
8312 /*
8313  * st_gen_mode_sense
8314  *
8315  * generic mode sense.. it allows for any page
8316  */
8317 static int
8318 st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
8319     struct seq_mode *page_data, int page_size)
8320 {
8321 
8322 	int r;
8323 	char	cdb[CDB_GROUP0];
8324 	struct uscsi_cmd *com;
8325 	struct scsi_arq_status status;
8326 
8327 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
8328 
8329 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8330 
8331 	bzero(cdb, CDB_GROUP0);
8332 	cdb[0] = SCMD_MODE_SENSE;
8333 	cdb[2] = (char)page;
8334 	cdb[4] = (char)page_size;
8335 
8336 	com->uscsi_cdb = cdb;
8337 	com->uscsi_cdblen = CDB_GROUP0;
8338 	com->uscsi_bufaddr = (caddr_t)page_data;
8339 	com->uscsi_buflen = page_size;
8340 	com->uscsi_rqlen = sizeof (status);
8341 	com->uscsi_rqbuf = (caddr_t)&status;
8342 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8343 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8344 
8345 	r = ubf(un, com, FKIOCTL);
8346 	kmem_free(com, sizeof (*com));
8347 	return (r);
8348 }
8349 
8350 /*
8351  * st_gen_mode_select
8352  *
8353  * generic mode select.. it allows for any page
8354  */
8355 static int
8356 st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
8357     struct seq_mode *page_data, int page_size)
8358 {
8359 
8360 	int r;
8361 	char cdb[CDB_GROUP0];
8362 	struct uscsi_cmd *com;
8363 	struct scsi_arq_status status;
8364 
8365 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
8366 
8367 	/* Zero non-writeable fields */
8368 	page_data->data_len = 0;
8369 	page_data->media_type = 0;
8370 	page_data->wp = 0;
8371 
8372 	/*
8373 	 * If mode select has any page data, zero the ps (Page Savable) bit.
8374 	 */
8375 	if (page_size > MSIZE) {
8376 		page_data->ps = 0;
8377 	}
8378 
8379 
8380 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8381 
8382 	/*
8383 	 * then, do a mode select to set what ever info
8384 	 */
8385 	bzero(cdb, CDB_GROUP0);
8386 	cdb[0] = SCMD_MODE_SELECT;
8387 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
8388 	cdb[4] = (char)page_size;
8389 
8390 	com->uscsi_cdb = cdb;
8391 	com->uscsi_cdblen = CDB_GROUP0;
8392 	com->uscsi_bufaddr = (caddr_t)page_data;
8393 	com->uscsi_buflen = page_size;
8394 	com->uscsi_rqlen = sizeof (status);
8395 	com->uscsi_rqbuf = (caddr_t)&status;
8396 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8397 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_WRITE;
8398 
8399 	r = ubf(un, com, FKIOCTL);
8400 
8401 	kmem_free(com, sizeof (*com));
8402 	return (r);
8403 }
8404 
8405 static int
8406 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
8407 {
8408 	int rval;
8409 	char cdb[CDB_GROUP0];
8410 	struct uscsi_cmd *com;
8411 	struct scsi_arq_status status;
8412 
8413 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
8414 
8415 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8416 
8417 	bzero(cdb, CDB_GROUP0);
8418 	cdb[0] = SCMD_READ_BLKLIM;
8419 
8420 	com->uscsi_cdb = cdb;
8421 	com->uscsi_cdblen = CDB_GROUP0;
8422 	com->uscsi_bufaddr = (caddr_t)read_blk;
8423 	com->uscsi_buflen = sizeof (struct read_blklim);
8424 	com->uscsi_rqlen = sizeof (status);
8425 	com->uscsi_rqbuf = (caddr_t)&status;
8426 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8427 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8428 
8429 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8430 	if (com->uscsi_status || com->uscsi_resid) {
8431 		rval = -1;
8432 	}
8433 
8434 	kmem_free(com, sizeof (*com));
8435 	return (rval);
8436 }
8437 
8438 static int
8439 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
8440     size_t buflen)
8441 {
8442 	int rval;
8443 	char cdb[CDB_GROUP1];
8444 	struct uscsi_cmd *com;
8445 	struct scsi_arq_status status;
8446 
8447 	ST_FUNC(ST_DEVINFO, st_report_density_support);
8448 
8449 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8450 
8451 	bzero(cdb, CDB_GROUP1);
8452 	cdb[0] = SCMD_REPORT_DENSITIES;
8453 	cdb[7] = (buflen & 0xff00) >> 8;
8454 	cdb[8] = buflen & 0xff;
8455 
8456 	com->uscsi_cdb = cdb;
8457 	com->uscsi_cdblen = CDB_GROUP1;
8458 	com->uscsi_bufaddr = (caddr_t)density_data;
8459 	com->uscsi_buflen = buflen;
8460 	com->uscsi_rqlen = sizeof (status);
8461 	com->uscsi_rqbuf = (caddr_t)&status;
8462 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8463 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8464 
8465 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8466 	if (com->uscsi_status || com->uscsi_resid) {
8467 		rval = -1;
8468 	}
8469 
8470 	kmem_free(com, sizeof (*com));
8471 	return (rval);
8472 }
8473 
8474 static int
8475 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
8476     uchar_t option_code, ushort_t service_action)
8477 {
8478 	int rval;
8479 	char cdb[CDB_GROUP5];
8480 	struct uscsi_cmd *com;
8481 	struct scsi_arq_status status;
8482 	uint32_t allo_length;
8483 
8484 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
8485 
8486 	allo_length = sizeof (struct one_com_des) +
8487 	    sizeof (struct com_timeout_des);
8488 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8489 
8490 	bzero(cdb, CDB_GROUP5);
8491 	cdb[0] = (char)SCMD_MAINTENANCE_IN;
8492 	cdb[1] = SSVC_ACTION_GET_SUPPORTED_OPERATIONS;
8493 	if (service_action) {
8494 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
8495 		cdb[4] = (service_action & 0xff00) >> 8;
8496 		cdb[5] = service_action & 0xff;
8497 	} else {
8498 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
8499 		    0x80); /* RCTD */
8500 	}
8501 	cdb[3] = option_code;
8502 	cdb[6] = (allo_length & 0xff000000) >> 24;
8503 	cdb[7] = (allo_length & 0xff0000) >> 16;
8504 	cdb[8] = (allo_length & 0xff00) >> 8;
8505 	cdb[9] = allo_length & 0xff;
8506 
8507 	com->uscsi_cdb = cdb;
8508 	com->uscsi_cdblen = CDB_GROUP5;
8509 	com->uscsi_bufaddr = (caddr_t)oper_data;
8510 	com->uscsi_buflen = allo_length;
8511 	com->uscsi_rqlen = sizeof (status);
8512 	com->uscsi_rqbuf = (caddr_t)&status;
8513 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8514 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8515 
8516 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8517 	if (com->uscsi_status) {
8518 		rval = -1;
8519 	}
8520 
8521 	kmem_free(com, sizeof (*com));
8522 	return (rval);
8523 }
8524 
8525 /*
8526  * Changes devices blocksize and bsize to requested blocksize nblksz.
8527  * Returns returned value from first failed call or zero on success.
8528  */
8529 static int
8530 st_change_block_size(struct scsi_tape *un, uint32_t nblksz)
8531 {
8532 	struct seq_mode *current;
8533 	int rval;
8534 	uint32_t oldblksz;
8535 
8536 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8537 
8538 	current = kmem_zalloc(MSIZE, KM_SLEEP);
8539 
8540 	/*
8541 	 * If we haven't got the compression page yet, do that first.
8542 	 */
8543 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
8544 		(void) st_modesense(un);
8545 	}
8546 
8547 	/* Read current settings */
8548 	rval = st_gen_mode_sense(un, st_uscsi_cmd, 0, current, MSIZE);
8549 	if (rval != 0) {
8550 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8551 		    "mode sense for change block size failed: rval = %d", rval);
8552 		goto finish;
8553 	}
8554 
8555 	/* Figure the current block size */
8556 	oldblksz =
8557 	    (current->high_bl << 16) |
8558 	    (current->mid_bl << 8) |
8559 	    (current->low_bl);
8560 
8561 	/* If current block size is the same as requested were done */
8562 	if (oldblksz == nblksz) {
8563 		un->un_bsize = nblksz;
8564 		rval = 0;
8565 		goto finish;
8566 	}
8567 
8568 	/* Change to requested block size */
8569 	current->high_bl = (uchar_t)(nblksz >> 16);
8570 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8571 	current->low_bl  = (uchar_t)(nblksz);
8572 
8573 	/* Attempt to change block size */
8574 	rval = st_gen_mode_select(un, st_uscsi_cmd, current, MSIZE);
8575 	if (rval != 0) {
8576 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8577 		    "Set new block size failed: rval = %d", rval);
8578 		goto finish;
8579 	}
8580 
8581 	/* Read back and verify setting */
8582 	rval = st_modesense(un);
8583 	if (rval == 0) {
8584 		un->un_bsize =
8585 		    (un->un_mspl->high_bl << 16) |
8586 		    (un->un_mspl->mid_bl << 8) |
8587 		    (un->un_mspl->low_bl);
8588 
8589 		if (un->un_bsize != nblksz) {
8590 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8591 			    "Blocksize set does not equal requested blocksize"
8592 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8593 			rval = EIO;
8594 		}
8595 	}
8596 finish:
8597 	kmem_free(current, MSIZE);
8598 	return (rval);
8599 }
8600 
8601 
8602 static void
8603 st_init(struct scsi_tape *un)
8604 {
8605 	ST_FUNC(ST_DEVINFO, st_init);
8606 
8607 	ASSERT(mutex_owned(ST_MUTEX));
8608 
8609 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8610 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8611 	    un->un_dev);
8612 
8613 	un->un_pos.blkno = 0;
8614 	un->un_pos.fileno = 0;
8615 	un->un_lastop = ST_OP_NIL;
8616 	un->un_pos.eof = ST_NO_EOF;
8617 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8618 	if (st_error_level != SCSI_ERR_ALL) {
8619 		if (DEBUGGING) {
8620 			st_error_level = SCSI_ERR_ALL;
8621 		} else {
8622 			st_error_level = SCSI_ERR_RETRYABLE;
8623 		}
8624 	}
8625 }
8626 
8627 
8628 static void
8629 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8630 {
8631 	struct scsi_pkt *pkt;
8632 	struct uscsi_cmd *ucmd;
8633 	recov_info *ri;
8634 	int tval = 0;
8635 	int64_t count;
8636 	uint32_t additional = 0;
8637 	uint32_t address = 0;
8638 	union scsi_cdb *ucdb;
8639 	int flags = 0;
8640 	int cdb_len = CDB_GROUP0; /* default */
8641 	uchar_t com;
8642 	char fixbit;
8643 	char short_fm = 0;
8644 	optype prev_op = un->un_lastop;
8645 	int stat_size =
8646 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
8647 
8648 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8649 
8650 	ASSERT(mutex_owned(ST_MUTEX));
8651 
8652 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8653 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8654 
8655 
8656 	/*
8657 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8658 	 * Length Indicator bits on read/write commands, for setting
8659 	 * the Long bit on erase commands, and for setting the Code
8660 	 * Field bits on space commands.
8661 	 */
8662 
8663 	/* regular raw I/O */
8664 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
8665 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8666 		    CDB_GROUP0, stat_size, st_recov_sz, 0, func,
8667 		    (caddr_t)un);
8668 		if (pkt == NULL) {
8669 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8670 			    "Read Write scsi_init_pkt() failure\n");
8671 			goto exit;
8672 		}
8673 		ASSERT(pkt->pkt_resid == 0);
8674 #ifdef STDEBUG
8675 		bzero(pkt->pkt_private, st_recov_sz);
8676 		bzero(pkt->pkt_scbp, stat_size);
8677 #endif
8678 		ri = (recov_info *)pkt->pkt_private;
8679 		ri->privatelen = st_recov_sz;
8680 		if (un->un_bsize == 0) {
8681 			count = bp->b_bcount;
8682 			fixbit = 0;
8683 		} else {
8684 			count = bp->b_bcount / un->un_bsize;
8685 			fixbit = 1;
8686 		}
8687 		if (bp->b_flags & B_READ) {
8688 			com = SCMD_READ;
8689 			un->un_lastop = ST_OP_READ;
8690 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8691 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8692 				fixbit = 2;
8693 			}
8694 		} else {
8695 			com = SCMD_WRITE;
8696 			un->un_lastop = ST_OP_WRITE;
8697 		}
8698 		tval = un->un_dp->io_timeout;
8699 
8700 		/*
8701 		 * For really large xfers, increase timeout
8702 		 */
8703 		if (bp->b_bcount > (10 * ONE_MEG))
8704 			tval *= bp->b_bcount/(10 * ONE_MEG);
8705 
8706 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8707 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8708 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8709 
8710 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8711 		/*
8712 		 * uscsi - build command, allocate scsi resources
8713 		 */
8714 		st_make_uscsi_cmd(un, ucmd, bp, func);
8715 		goto exit;
8716 
8717 	} else {				/* special I/O */
8718 		struct buf *allocbp = NULL;
8719 		com = (uchar_t)(uintptr_t)bp->b_forw;
8720 		count = bp->b_bcount;
8721 
8722 		switch (com) {
8723 		case SCMD_READ:
8724 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8725 			    "special read %"PRId64"\n", count);
8726 			if (un->un_bsize == 0) {
8727 				fixbit = 2;	/* suppress SILI */
8728 			} else {
8729 				fixbit = 1;	/* Fixed Block Mode */
8730 				count /= un->un_bsize;
8731 			}
8732 			allocbp = bp;
8733 			un->un_lastop = ST_OP_READ;
8734 			tval = un->un_dp->io_timeout;
8735 			break;
8736 
8737 		case SCMD_WRITE:
8738 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8739 			    "special write %"PRId64"\n", count);
8740 			if (un->un_bsize != 0) {
8741 				fixbit = 1;	/* Fixed Block Mode */
8742 				count /= un->un_bsize;
8743 			} else {
8744 				fixbit = 0;
8745 			}
8746 			allocbp = bp;
8747 			un->un_lastop = ST_OP_WRITE;
8748 			tval = un->un_dp->io_timeout;
8749 			break;
8750 
8751 		case SCMD_WRITE_FILE_MARK:
8752 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8753 			    "write %"PRId64" file marks\n", count);
8754 			un->un_lastop = ST_OP_WEOF;
8755 			fixbit = 0;
8756 			tval = un->un_dp->io_timeout;
8757 			/*
8758 			 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8759 			 * device, set the Vendor Unique bit to
8760 			 * write Short File Mark.
8761 			 */
8762 			if ((un->un_dp->options & ST_SHORT_FILEMARKS) &&
8763 			    ((un->un_dp->type == ST_TYPE_EXB8500) ||
8764 			    (un->un_dp->type == ST_TYPE_EXABYTE))) {
8765 				/*
8766 				 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8767 				 * is set to to write Short File Mark
8768 				 */
8769 				short_fm = 1;
8770 			}
8771 			break;
8772 
8773 		case SCMD_REWIND:
8774 			/*
8775 			 * In the case of rewind we're gona do the rewind with
8776 			 * the immediate bit set so status will be retured when
8777 			 * the command is accepted by the device. We clear the
8778 			 * B_ASYNC flag so we wait for that acceptance.
8779 			 */
8780 			fixbit = 0;
8781 			if (bp->b_flags & B_ASYNC) {
8782 				allocbp = bp;
8783 				if (count) {
8784 					fixbit = 1;
8785 					bp->b_flags &= ~B_ASYNC;
8786 				}
8787 			}
8788 			count = 0;
8789 			bp->b_bcount = 0;
8790 			un->un_lastop = ST_OP_CTL;
8791 			tval = un->un_dp->rewind_timeout;
8792 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8793 			    "rewind\n");
8794 			break;
8795 
8796 		case SCMD_SPACE_G4:
8797 			cdb_len = CDB_GROUP4;
8798 			fixbit = SPACE_TYPE(bp->b_bcount);
8799 			count = SPACE_CNT(bp->b_bcount);
8800 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8801 			    " %s space %s %"PRId64" from file %d blk %d\n",
8802 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8803 			    space_strs[fixbit & 7], count,
8804 			    un->un_pos.fileno, un->un_pos.blkno);
8805 			address = (count >> 48) & 0x1fff;
8806 			additional = (count >> 16) & 0xffffffff;
8807 			count &= 0xffff;
8808 			count <<= 16;
8809 			un->un_lastop = ST_OP_CTL;
8810 			tval = un->un_dp->space_timeout;
8811 			break;
8812 
8813 		case SCMD_SPACE:
8814 			fixbit = SPACE_TYPE(bp->b_bcount);
8815 			count = SPACE_CNT(bp->b_bcount);
8816 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8817 			    " %s space %s %"PRId64" from file %d blk %d\n",
8818 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8819 			    space_strs[fixbit & 7], count,
8820 			    un->un_pos.fileno, un->un_pos.blkno);
8821 			count &= 0xffffffff;
8822 			un->un_lastop = ST_OP_CTL;
8823 			tval = un->un_dp->space_timeout;
8824 			break;
8825 
8826 		case SCMD_LOAD:
8827 			ASSERT(count < 10);
8828 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8829 			    "%s tape\n", load_strs[count]);
8830 			fixbit = 0;
8831 
8832 			/* Loading or Unloading */
8833 			if (count & LD_LOAD) {
8834 				tval = un->un_dp->load_timeout;
8835 			} else {
8836 				tval = un->un_dp->unload_timeout;
8837 			}
8838 			/* Is Retension requested */
8839 			if (count & LD_RETEN) {
8840 				tval += un->un_dp->rewind_timeout;
8841 			}
8842 			un->un_lastop = ST_OP_CTL;
8843 			break;
8844 
8845 		case SCMD_ERASE:
8846 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8847 			    "erase tape\n");
8848 			ASSERT(count == 1); /* mt sets this */
8849 			if (count == 1) {
8850 				/*
8851 				 * do long erase
8852 				 */
8853 				fixbit = 1; /* Long */
8854 
8855 				/* Drive might not honor immidiate bit */
8856 				tval = un->un_dp->erase_timeout;
8857 			} else {
8858 				/* Short Erase */
8859 				tval = un->un_dp->erase_timeout;
8860 				fixbit = 0;
8861 			}
8862 			un->un_lastop = ST_OP_CTL;
8863 			count = 0;
8864 			break;
8865 
8866 		case SCMD_MODE_SENSE:
8867 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8868 			    "mode sense\n");
8869 			allocbp = bp;
8870 			fixbit = 0;
8871 			tval = un->un_dp->non_motion_timeout;
8872 			un->un_lastop = ST_OP_CTL;
8873 			break;
8874 
8875 		case SCMD_MODE_SELECT:
8876 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8877 			    "mode select\n");
8878 			allocbp = bp;
8879 			fixbit = 0;
8880 			tval = un->un_dp->non_motion_timeout;
8881 			un->un_lastop = ST_OP_CTL;
8882 			break;
8883 
8884 		case SCMD_RESERVE:
8885 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8886 			    "reserve\n");
8887 			fixbit = 0;
8888 			tval = un->un_dp->non_motion_timeout;
8889 			un->un_lastop = ST_OP_CTL;
8890 			break;
8891 
8892 		case SCMD_RELEASE:
8893 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8894 			    "release\n");
8895 			fixbit = 0;
8896 			tval = un->un_dp->non_motion_timeout;
8897 			un->un_lastop = ST_OP_CTL;
8898 			break;
8899 
8900 		case SCMD_READ_BLKLIM:
8901 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8902 			    "read block limits\n");
8903 			allocbp = bp;
8904 			fixbit = count = 0;
8905 			tval = un->un_dp->non_motion_timeout;
8906 			un->un_lastop = ST_OP_CTL;
8907 			break;
8908 
8909 		case SCMD_TEST_UNIT_READY:
8910 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8911 			    "test unit ready\n");
8912 			fixbit = 0;
8913 			tval = un->un_dp->non_motion_timeout;
8914 			un->un_lastop = ST_OP_CTL;
8915 			break;
8916 
8917 		case SCMD_DOORLOCK:
8918 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8919 			    "prevent/allow media removal\n");
8920 			fixbit = 0;
8921 			tval = un->un_dp->non_motion_timeout;
8922 			un->un_lastop = ST_OP_CTL;
8923 			break;
8924 
8925 		case SCMD_READ_POSITION:
8926 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8927 			    "read position\n");
8928 			fixbit = un->un_read_pos_type;
8929 			cdb_len = CDB_GROUP1;
8930 			tval = un->un_dp->non_motion_timeout;
8931 			allocbp = bp;
8932 			un->un_lastop = ST_OP_CTL;
8933 			switch (un->un_read_pos_type) {
8934 			case LONG_POS:
8935 				count = 0;
8936 				break;
8937 			case EXT_POS:
8938 				count = sizeof (tape_position_ext_t);
8939 				break;
8940 			case SHORT_POS:
8941 				count = 0;
8942 				break;
8943 			default:
8944 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8945 				    "Unknown read position type 0x%x in "
8946 				    " st_make_cmd()\n", un->un_read_pos_type);
8947 			}
8948 			break;
8949 
8950 		default:
8951 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8952 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8953 			    com);
8954 		}
8955 
8956 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8957 		    st_recov_sz, 0, func, (caddr_t)un);
8958 		if (pkt == NULL) {
8959 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8960 			    "generic command scsi_init_pkt() failure\n");
8961 			goto exit;
8962 		}
8963 
8964 		ASSERT(pkt->pkt_resid == 0);
8965 #ifdef STDEBUG
8966 		bzero(pkt->pkt_private, st_recov_sz);
8967 		bzero(pkt->pkt_scbp, stat_size);
8968 #endif
8969 		ri = (recov_info *)pkt->pkt_private;
8970 		ri->privatelen = st_recov_sz;
8971 		if (allocbp) {
8972 			ASSERT(geterror(allocbp) == 0);
8973 		}
8974 
8975 	}
8976 
8977 	ucdb = (union scsi_cdb *)pkt->pkt_cdbp;
8978 
8979 	(void) scsi_setup_cdb(ucdb, com, address, (uint_t)count, additional);
8980 	FILL_SCSI1_LUN(un->un_sd, pkt);
8981 	/*
8982 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8983 	 */
8984 	ucdb->t_code = fixbit;
8985 	ucdb->g0_vu_1 = short_fm;
8986 	pkt->pkt_flags = flags;
8987 
8988 	ASSERT(tval);
8989 	pkt->pkt_time = tval;
8990 	if (bp == un->un_recov_buf) {
8991 		pkt->pkt_comp = st_recov_cb;
8992 	} else {
8993 		pkt->pkt_comp = st_intr;
8994 	}
8995 
8996 	st_add_recovery_info_to_pkt(un, bp, pkt);
8997 
8998 	/*
8999 	 * If we just write data to tape and did a command that doesn't
9000 	 * change position, we still need to write a filemark.
9001 	 */
9002 	if ((prev_op == ST_OP_WRITE) || (prev_op == ST_OP_WEOF)) {
9003 		recov_info *rcvi = pkt->pkt_private;
9004 		cmd_attribute const *atrib;
9005 
9006 		if (rcvi->privatelen == sizeof (recov_info)) {
9007 			atrib = rcvi->cmd_attrib;
9008 		} else {
9009 			atrib = st_lookup_cmd_attribute(com);
9010 		}
9011 		if (atrib->chg_tape_direction == DIR_NONE) {
9012 			un->un_lastop = prev_op;
9013 		}
9014 	}
9015 
9016 exit:
9017 	ASSERT(mutex_owned(ST_MUTEX));
9018 }
9019 
9020 
9021 /*
9022  * Build a command based on a uscsi command;
9023  */
9024 static void
9025 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
9026     struct buf *bp, int (*func)(caddr_t))
9027 {
9028 	struct scsi_pkt *pkt;
9029 	recov_info *ri;
9030 	caddr_t cdb;
9031 	int	cdblen;
9032 	int	stat_size = 1;
9033 	int	flags = 0;
9034 
9035 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
9036 
9037 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9038 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
9039 
9040 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
9041 		if (un->un_arq_enabled) {
9042 			if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
9043 				stat_size = (int)(ucmd->uscsi_rqlen) +
9044 				    sizeof (struct scsi_arq_status) -
9045 				    sizeof (struct scsi_extended_sense);
9046 				flags = PKT_XARQ;
9047 			} else {
9048 				stat_size = sizeof (struct scsi_arq_status);
9049 			}
9050 		}
9051 	}
9052 
9053 	ASSERT(mutex_owned(ST_MUTEX));
9054 
9055 	cdb = ucmd->uscsi_cdb;
9056 	cdblen = ucmd->uscsi_cdblen;
9057 
9058 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9059 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
9060 	    ucmd->uscsi_buflen, bp->b_bcount);
9061 	pkt = scsi_init_pkt(ROUTE, NULL,
9062 	    (bp->b_bcount > 0) ? bp : NULL,
9063 	    cdblen, stat_size, st_recov_sz, flags, func, (caddr_t)un);
9064 	if (pkt == NULL) {
9065 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
9066 		    "uscsi command scsi_init_pkt() failure\n");
9067 		goto exit;
9068 	}
9069 
9070 	ASSERT(pkt->pkt_resid == 0);
9071 #ifdef STDEBUG
9072 	bzero(pkt->pkt_private, st_recov_sz);
9073 	bzero(pkt->pkt_scbp, stat_size);
9074 #endif
9075 	ri = (recov_info *)pkt->pkt_private;
9076 	ri->privatelen = st_recov_sz;
9077 
9078 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
9079 
9080 #ifdef STDEBUG
9081 	if ((st_debug & 0x7) >= 6) {
9082 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
9083 		    "pkt_cdbp", (char *)cdb, cdblen);
9084 	}
9085 #endif
9086 
9087 	if (ucmd->uscsi_flags & USCSI_SILENT) {
9088 		pkt->pkt_flags |= FLAG_SILENT;
9089 	}
9090 
9091 	(void) scsi_uscsi_pktinit(ucmd, pkt);
9092 
9093 	pkt->pkt_time = ucmd->uscsi_timeout;
9094 	if (bp == un->un_recov_buf) {
9095 		pkt->pkt_comp = st_recov_cb;
9096 	} else {
9097 		pkt->pkt_comp = st_intr;
9098 	}
9099 
9100 	st_add_recovery_info_to_pkt(un, bp, pkt);
9101 exit:
9102 	ASSERT(mutex_owned(ST_MUTEX));
9103 }
9104 
9105 
9106 /*
9107  * restart cmd currently at the head of the runq
9108  *
9109  * If scsi_transport() succeeds or the retries
9110  * count exhausted, restore the throttle that was
9111  * zeroed out in st_handle_intr_busy().
9112  *
9113  */
9114 static void
9115 st_intr_restart(void *arg)
9116 {
9117 	struct scsi_tape *un = arg;
9118 	struct buf *bp;
9119 	int queued;
9120 	int status = TRAN_ACCEPT;
9121 
9122 	mutex_enter(ST_MUTEX);
9123 
9124 	ST_FUNC(ST_DEVINFO, st_intr_restart);
9125 
9126 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9127 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
9128 
9129 	un->un_hib_tid = 0;
9130 
9131 	if (un->un_recov_buf_busy != 0) {
9132 		bp = un->un_recov_buf;
9133 		queued = 0;
9134 	} else if (un->un_sbuf_busy != 0) {
9135 		bp = un->un_sbufp;
9136 		queued = 0;
9137 	} else if (un->un_quef != NULL) {
9138 		bp = un->un_quef;
9139 		queued = 1;
9140 	} else {
9141 		mutex_exit(ST_MUTEX);
9142 		return;
9143 	}
9144 
9145 	/*
9146 	 * Here we know :
9147 	 *	throttle = 0, via st_handle_intr_busy
9148 	 */
9149 
9150 	if (queued) {
9151 		/*
9152 		 * move from waitq to runq, if there is anything on the waitq
9153 		 */
9154 		(void) st_remove_from_queue(&un->un_quef, &un->un_quef, bp);
9155 
9156 		if (un->un_runqf) {
9157 			/*
9158 			 * not good, we don't want to requeue something after
9159 			 * another.
9160 			 */
9161 			goto done_error;
9162 		} else {
9163 			un->un_runqf = bp;
9164 			un->un_runql = bp;
9165 		}
9166 	}
9167 
9168 	ST_CDB(ST_DEVINFO, "Interrupt restart CDB",
9169 	    (char *)BP_PKT(bp)->pkt_cdbp);
9170 
9171 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
9172 
9173 	status = st_transport(un, BP_PKT(bp));
9174 
9175 	if (status != TRAN_ACCEPT) {
9176 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9177 
9178 		if (status == TRAN_BUSY) {
9179 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
9180 
9181 			if (pkti->privatelen == sizeof (recov_info) &&
9182 			    un->un_unit_attention_flags &&
9183 			    bp != un->un_recov_buf) {
9184 			un->un_unit_attention_flags = 0;
9185 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9186 				    "Command Recovery called on busy resend\n");
9187 				if (st_command_recovery(un, BP_PKT(bp),
9188 				    ATTEMPT_RETRY) == JUST_RETURN) {
9189 					mutex_exit(ST_MUTEX);
9190 					return;
9191 				}
9192 			}
9193 			mutex_exit(ST_MUTEX);
9194 			if (st_handle_intr_busy(un, bp,
9195 			    ST_TRAN_BUSY_TIMEOUT) == 0)
9196 				return;	/* timeout is setup again */
9197 			mutex_enter(ST_MUTEX);
9198 		}
9199 
9200 done_error:
9201 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9202 		    "restart transport rejected\n");
9203 		bp->b_resid = bp->b_bcount;
9204 
9205 		if (un->un_last_throttle) {
9206 			un->un_throttle = un->un_last_throttle;
9207 		}
9208 		if (status != TRAN_ACCEPT) {
9209 			ST_DO_ERRSTATS(un, st_transerrs);
9210 		}
9211 		ST_DO_KSTATS(bp, kstat_waitq_exit);
9212 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9213 		    "busy restart aborted\n");
9214 		st_set_pe_flag(un);
9215 		st_bioerror(bp, EIO);
9216 		st_done_and_mutex_exit(un, bp);
9217 	} else {
9218 		if (un->un_last_throttle) {
9219 			un->un_throttle = un->un_last_throttle;
9220 		}
9221 		mutex_exit(ST_MUTEX);
9222 	}
9223 }
9224 
9225 /*
9226  * st_check_media():
9227  * Periodically check the media state using scsi_watch service;
9228  * this service calls back after TUR and possibly request sense
9229  * the callback handler (st_media_watch_cb()) decodes the request sense
9230  * data (if any)
9231  */
9232 
9233 static int
9234 st_check_media(dev_t dev, enum mtio_state state)
9235 {
9236 	int rval = 0;
9237 	enum mtio_state	prev_state;
9238 	opaque_t token = NULL;
9239 
9240 	GET_SOFT_STATE(dev);
9241 
9242 	ST_FUNC(ST_DEVINFO, st_check_media);
9243 
9244 	mutex_enter(ST_MUTEX);
9245 
9246 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9247 	    "st_check_media:state=%x, mediastate=%x\n",
9248 	    state, un->un_mediastate);
9249 
9250 	prev_state = un->un_mediastate;
9251 
9252 	/*
9253 	 * is there anything to do?
9254 	 */
9255 retry:
9256 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
9257 		/*
9258 		 * submit the request to the scsi_watch service;
9259 		 * scsi_media_watch_cb() does the real work
9260 		 */
9261 		mutex_exit(ST_MUTEX);
9262 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
9263 		    st_check_media_time, SENSE_LENGTH,
9264 		    st_media_watch_cb, (caddr_t)dev);
9265 		if (token == NULL) {
9266 			rval = EAGAIN;
9267 			goto done;
9268 		}
9269 		mutex_enter(ST_MUTEX);
9270 
9271 		un->un_swr_token = token;
9272 		un->un_specified_mediastate = state;
9273 
9274 		/*
9275 		 * now wait for media change
9276 		 * we will not be signalled unless mediastate == state but it
9277 		 * still better to test for this condition, since there
9278 		 * is a 5 sec cv_broadcast delay when
9279 		 *  mediastate == MTIO_INSERTED
9280 		 */
9281 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9282 		    "st_check_media:waiting for media state change\n");
9283 		while (un->un_mediastate == state) {
9284 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
9285 				mutex_exit(ST_MUTEX);
9286 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9287 				    "st_check_media:waiting for media state "
9288 				    "was interrupted\n");
9289 				rval = EINTR;
9290 				goto done;
9291 			}
9292 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9293 			    "st_check_media:received signal, state=%x\n",
9294 			    un->un_mediastate);
9295 		}
9296 	}
9297 
9298 	/*
9299 	 * if we transitioned to MTIO_INSERTED, media has really been
9300 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
9301 	 * Reset and retry the state change.  If everything is ok, replay
9302 	 * the open() logic.
9303 	 */
9304 	if ((un->un_mediastate == MTIO_INSERTED) &&
9305 	    (un->un_state == ST_STATE_OFFLINE)) {
9306 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9307 		    "st_check_media: calling st_cmd to confirm inserted\n");
9308 
9309 		/*
9310 		 * set this early so that TUR will make it through strategy
9311 		 * without triggering a st_tape_init().  We needed it set
9312 		 * before calling st_tape_init() ourselves anyway.  If TUR
9313 		 * fails, set it back
9314 		 */
9315 		un->un_state = ST_STATE_INITIALIZING;
9316 
9317 		/*
9318 		 * If not reserved fail as getting reservation conflict
9319 		 * will make this hang forever.
9320 		 */
9321 		if ((un->un_rsvd_status &
9322 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9323 			mutex_exit(ST_MUTEX);
9324 			rval = EACCES;
9325 			goto done;
9326 		}
9327 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
9328 		if (rval == EACCES) {
9329 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9330 			    "st_check_media: TUR got Reservation Conflict\n");
9331 			mutex_exit(ST_MUTEX);
9332 			goto done;
9333 		}
9334 		if (rval) {
9335 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9336 			    "st_check_media: TUR failed, going to retry\n");
9337 			un->un_mediastate = prev_state;
9338 			un->un_state = ST_STATE_OFFLINE;
9339 			goto retry;
9340 		}
9341 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9342 		    "st_check_media: media inserted\n");
9343 
9344 		/* this also rewinds the tape */
9345 		rval = st_tape_init(un);
9346 		if (rval != 0) {
9347 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9348 			    "st_check_media : OFFLINE init failure ");
9349 			un->un_state = ST_STATE_OFFLINE;
9350 			un->un_pos.pmode = invalid;
9351 		} else {
9352 			un->un_state = ST_STATE_OPEN_PENDING_IO;
9353 		}
9354 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
9355 	    (un->un_state != ST_STATE_OFFLINE)) {
9356 		/*
9357 		 * supported devices must be rewound before ejection
9358 		 * rewind resets fileno & blkno
9359 		 */
9360 		un->un_laststate = un->un_state;
9361 		un->un_state = ST_STATE_OFFLINE;
9362 	}
9363 	mutex_exit(ST_MUTEX);
9364 done:
9365 	if (token) {
9366 		(void) scsi_watch_request_terminate(token,
9367 		    SCSI_WATCH_TERMINATE_WAIT);
9368 		mutex_enter(ST_MUTEX);
9369 		un->un_swr_token = (opaque_t)NULL;
9370 		mutex_exit(ST_MUTEX);
9371 	}
9372 
9373 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
9374 
9375 	return (rval);
9376 }
9377 
9378 /*
9379  * st_media_watch_cb() is called by scsi_watch_thread for
9380  * verifying the request sense data (if any)
9381  */
9382 static int
9383 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
9384 {
9385 	struct scsi_status *statusp = resultp->statusp;
9386 	struct scsi_extended_sense *sensep = resultp->sensep;
9387 	uchar_t actual_sense_length = resultp->actual_sense_length;
9388 	struct scsi_tape *un;
9389 	enum mtio_state state = MTIO_NONE;
9390 	int instance;
9391 	dev_t dev = (dev_t)arg;
9392 
9393 	instance = MTUNIT(dev);
9394 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
9395 		return (-1);
9396 	}
9397 
9398 	mutex_enter(ST_MUTEX);
9399 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
9400 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9401 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
9402 	    *((char *)statusp), (void *)sensep,
9403 	    actual_sense_length);
9404 
9405 
9406 	/*
9407 	 * if there was a check condition then sensep points to valid
9408 	 * sense data
9409 	 * if status was not a check condition but a reservation or busy
9410 	 * status then the new state is MTIO_NONE
9411 	 */
9412 	if (sensep) {
9413 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9414 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
9415 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
9416 
9417 		switch (un->un_dp->type) {
9418 		default:
9419 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9420 			    "st_media_watch_cb: unknown drive type %d, "
9421 			    "default to ST_TYPE_HP\n", un->un_dp->type);
9422 		/* FALLTHROUGH */
9423 
9424 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
9425 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
9426 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
9427 			if (un->un_dp->type == ST_TYPE_FUJI) {
9428 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9429 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
9430 			} else {
9431 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9432 				    "st_media_watch_cb: ST_TYPE_HP\n");
9433 			}
9434 			switch (sensep->es_key) {
9435 			case KEY_UNIT_ATTENTION:
9436 				/* not ready to ready transition */
9437 				/* hp/es_qual_code == 80 on>off>on */
9438 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
9439 				if (sensep->es_add_code == 0x28) {
9440 					state = MTIO_INSERTED;
9441 				}
9442 				break;
9443 			case KEY_NOT_READY:
9444 				/* in process, rewinding or loading */
9445 				if ((sensep->es_add_code == 0x04) &&
9446 				    (sensep->es_qual_code == 0x00)) {
9447 					state = MTIO_EJECTED;
9448 				}
9449 				break;
9450 			}
9451 			break;
9452 
9453 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
9454 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9455 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
9456 			switch (sensep->es_key) {
9457 			case KEY_UNIT_ATTENTION:
9458 				/* operator medium removal request */
9459 				if ((sensep->es_add_code == 0x5a) &&
9460 				    (sensep->es_qual_code == 0x01)) {
9461 					state = MTIO_EJECTED;
9462 				/* not ready to ready transition */
9463 				} else if ((sensep->es_add_code == 0x28) &&
9464 				    (sensep->es_qual_code == 0x00)) {
9465 					state = MTIO_INSERTED;
9466 				}
9467 				break;
9468 			case KEY_NOT_READY:
9469 				/* medium not present */
9470 				if (sensep->es_add_code == 0x3a) {
9471 					state = MTIO_EJECTED;
9472 				}
9473 				break;
9474 			}
9475 			break;
9476 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
9477 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9478 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
9479 			switch (sensep->es_key) {
9480 			case KEY_NOT_READY:
9481 				if ((sensep->es_add_code == 0x04) &&
9482 				    (sensep->es_qual_code == 0x00)) {
9483 					/* volume not mounted? */
9484 					state = MTIO_EJECTED;
9485 				} else if (sensep->es_add_code == 0x3a) {
9486 					state = MTIO_EJECTED;
9487 				}
9488 				break;
9489 			case KEY_UNIT_ATTENTION:
9490 				state = MTIO_EJECTED;
9491 				break;
9492 			}
9493 			break;
9494 
9495 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
9496 			switch (sensep->es_key) {
9497 			case KEY_UNIT_ATTENTION:
9498 				if (sensep->es_add_code == 0x28) {
9499 					state = MTIO_INSERTED;
9500 				}
9501 				break;
9502 			case KEY_NOT_READY:
9503 				if (sensep->es_add_code == 0x04) {
9504 					/* in transition but could be either */
9505 					state = un->un_specified_mediastate;
9506 				} else if ((sensep->es_add_code == 0x3a) &&
9507 				    (sensep->es_qual_code == 0x00)) {
9508 					state = MTIO_EJECTED;
9509 				}
9510 				break;
9511 			}
9512 			break;
9513 		}
9514 	} else if (*((char *)statusp) == STATUS_GOOD) {
9515 		state = MTIO_INSERTED;
9516 	}
9517 
9518 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9519 	    "st_media_watch_cb:state=%x, specified=%x\n",
9520 	    state, un->un_specified_mediastate);
9521 
9522 	/*
9523 	 * now signal the waiting thread if this is *not* the specified state;
9524 	 * delay the signal if the state is MTIO_INSERTED
9525 	 * to allow the target to recover
9526 	 */
9527 	if (state != un->un_specified_mediastate) {
9528 		un->un_mediastate = state;
9529 		if (state == MTIO_INSERTED) {
9530 			/*
9531 			 * delay the signal to give the drive a chance
9532 			 * to do what it apparently needs to do
9533 			 */
9534 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9535 			    "st_media_watch_cb:delayed cv_broadcast\n");
9536 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
9537 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
9538 		} else {
9539 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9540 			    "st_media_watch_cb:immediate cv_broadcast\n");
9541 			cv_broadcast(&un->un_state_cv);
9542 		}
9543 	}
9544 	mutex_exit(ST_MUTEX);
9545 	return (0);
9546 }
9547 
9548 /*
9549  * delayed cv_broadcast to allow for target to recover
9550  * from media insertion
9551  */
9552 static void
9553 st_delayed_cv_broadcast(void *arg)
9554 {
9555 	struct scsi_tape *un = arg;
9556 
9557 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
9558 
9559 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9560 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
9561 
9562 	mutex_enter(ST_MUTEX);
9563 	cv_broadcast(&un->un_state_cv);
9564 	mutex_exit(ST_MUTEX);
9565 }
9566 
9567 /*
9568  * restart cmd currently at the start of the waitq
9569  */
9570 static void
9571 st_start_restart(void *arg)
9572 {
9573 	struct scsi_tape *un = arg;
9574 
9575 	ST_FUNC(ST_DEVINFO, st_start_restart);
9576 
9577 	ASSERT(un != NULL);
9578 
9579 	mutex_enter(ST_MUTEX);
9580 
9581 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_tran_restart()\n");
9582 
9583 	st_start(un);
9584 
9585 	mutex_exit(ST_MUTEX);
9586 }
9587 
9588 
9589 /*
9590  * Command completion processing
9591  *
9592  */
9593 static void
9594 st_intr(struct scsi_pkt *pkt)
9595 {
9596 	recov_info *rcv = pkt->pkt_private;
9597 	struct buf *bp = rcv->cmd_bp;
9598 	struct scsi_tape *un;
9599 	errstate action = COMMAND_DONE;
9600 	clock_t	timout;
9601 	int	status;
9602 
9603 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
9604 
9605 	ST_FUNC(ST_DEVINFO, st_intr);
9606 
9607 	ASSERT(un != NULL);
9608 
9609 	mutex_enter(ST_MUTEX);
9610 
9611 	ASSERT(bp != un->un_recov_buf);
9612 
9613 	un->un_rqs_state &= ~(ST_RQS_ERROR);
9614 
9615 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
9616 
9617 	if (pkt->pkt_reason != CMD_CMPLT) {
9618 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9619 		    "Unhappy packet status reason = %s statistics = 0x%x\n",
9620 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9621 
9622 		/* If device has gone away not much else to do */
9623 		if (pkt->pkt_reason == CMD_DEV_GONE) {
9624 			action = COMMAND_DONE_ERROR;
9625 		} else if ((pkt == un->un_rqs) ||
9626 		    (un->un_state == ST_STATE_SENSING)) {
9627 			ASSERT(pkt == un->un_rqs);
9628 			ASSERT(un->un_state == ST_STATE_SENSING);
9629 			un->un_state = un->un_laststate;
9630 			rcv->cmd_bp = un->un_rqs_bp;
9631 			ST_DO_ERRSTATS(un, st_transerrs);
9632 			action = COMMAND_DONE_ERROR;
9633 		} else {
9634 			action = st_handle_incomplete(un, bp);
9635 		}
9636 	/*
9637 	 * At this point we know that the command was successfully
9638 	 * completed. Now what?
9639 	 */
9640 	} else if ((pkt == un->un_rqs) || (un->un_state == ST_STATE_SENSING)) {
9641 		/*
9642 		 * okay. We were running a REQUEST SENSE. Find
9643 		 * out what to do next.
9644 		 */
9645 		ASSERT(pkt == un->un_rqs);
9646 		ASSERT(un->un_state == ST_STATE_SENSING);
9647 		scsi_sync_pkt(pkt);
9648 		action = st_handle_sense(un, bp, &un->un_pos);
9649 		/*
9650 		 * Make rqs isn't going to be retied.
9651 		 */
9652 		if (action != QUE_BUSY_COMMAND && action != QUE_COMMAND) {
9653 			/*
9654 			 * set pkt back to original packet in case we will have
9655 			 * to requeue it
9656 			 */
9657 			pkt = BP_PKT(bp);
9658 			rcv->cmd_bp = un->un_rqs_bp;
9659 			/*
9660 			 * some actions are based on un_state, hence
9661 			 * restore the state st was in before ST_STATE_SENSING.
9662 			 */
9663 			un->un_state = un->un_laststate;
9664 		}
9665 
9666 	} else if (un->un_arq_enabled && (pkt->pkt_state & STATE_ARQ_DONE)) {
9667 		/*
9668 		 * the transport layer successfully completed an autorqsense
9669 		 */
9670 		action = st_handle_autosense(un, bp, &un->un_pos);
9671 
9672 	} else  if ((SCBP(pkt)->sts_busy) ||
9673 	    (SCBP(pkt)->sts_chk) ||
9674 	    (SCBP(pkt)->sts_vu7)) {
9675 		/*
9676 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9677 		 * to see if the status bits we're okay. If a request sense
9678 		 * is to be run, that will happen.
9679 		 */
9680 		action = st_check_error(un, pkt);
9681 	}
9682 
9683 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9684 		switch (action) {
9685 			case QUE_COMMAND:
9686 				/*
9687 				 * return cmd to head to the queue
9688 				 * since we are suspending so that
9689 				 * it gets restarted during resume
9690 				 */
9691 				st_add_to_queue(&un->un_runqf, &un->un_runql,
9692 				    un->un_runqf, bp);
9693 
9694 				action = JUST_RETURN;
9695 				break;
9696 
9697 			case QUE_SENSE:
9698 				action = COMMAND_DONE_ERROR;
9699 				break;
9700 
9701 			default:
9702 				break;
9703 		}
9704 	}
9705 
9706 	/*
9707 	 * check for undetected path failover.
9708 	 */
9709 	if (un->un_multipath) {
9710 
9711 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
9712 		int pkt_valid = 0;
9713 
9714 		if (ucmd) {
9715 			/*
9716 			 * Also copies path instance to the uscsi structure.
9717 			 */
9718 			pkt_valid = scsi_uscsi_pktfini(pkt, ucmd);
9719 
9720 			/*
9721 			 * scsi_uscsi_pktfini() zeros pkt_path_instance.
9722 			 */
9723 			pkt->pkt_path_instance = ucmd->uscsi_path_instance;
9724 		} else {
9725 			pkt_valid = scsi_pkt_allocated_correctly(pkt);
9726 		}
9727 
9728 		/*
9729 		 * If the scsi_pkt was not allocated correctly the
9730 		 * pkt_path_instance is not even there.
9731 		 */
9732 		if ((pkt_valid != 0) &&
9733 		    (un->un_last_path_instance != pkt->pkt_path_instance)) {
9734 			/*
9735 			 * Don't recover the path change if it was done
9736 			 * intentionally or if the device has not completely
9737 			 * opened yet.
9738 			 */
9739 			if (((pkt->pkt_flags & FLAG_PKT_PATH_INSTANCE) == 0) &&
9740 			    (un->un_state > ST_STATE_OPENING)) {
9741 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
9742 				    "Failover detected, action is %s\n",
9743 				    errstatenames[action]);
9744 				if (action == COMMAND_DONE) {
9745 					action = PATH_FAILED;
9746 				}
9747 			}
9748 			un->un_last_path_instance = pkt->pkt_path_instance;
9749 		}
9750 	}
9751 
9752 	/*
9753 	 * Restore old state if we were sensing.
9754 	 */
9755 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9756 		un->un_state = un->un_laststate;
9757 	}
9758 
9759 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9760 	    "st_intr: pkt=%p, bp=%p, action=%s, status=%x\n",
9761 	    (void *)pkt, (void *)bp, errstatenames[action], SCBP_C(pkt));
9762 
9763 again:
9764 	switch (action) {
9765 	case COMMAND_DONE_EACCES:
9766 		/* this is to report a reservation conflict */
9767 		st_bioerror(bp, EACCES);
9768 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9769 		    "Reservation Conflict \n");
9770 		un->un_pos.pmode = invalid;
9771 
9772 		/*FALLTHROUGH*/
9773 	case COMMAND_DONE_ERROR:
9774 		if (un->un_pos.eof < ST_EOT_PENDING &&
9775 		    un->un_state >= ST_STATE_OPEN) {
9776 			/*
9777 			 * all errors set state of the tape to 'unknown'
9778 			 * unless we're at EOT or are doing append testing.
9779 			 * If sense key was illegal request, preserve state.
9780 			 */
9781 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9782 				un->un_pos.pmode = invalid;
9783 			}
9784 		}
9785 
9786 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9787 		/*
9788 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9789 		 * make sure an error ocurrs, so make sure at least EIO is
9790 		 * returned
9791 		 */
9792 		if (geterror(bp) == 0)
9793 			st_bioerror(bp, EIO);
9794 
9795 		st_set_pe_flag(un);
9796 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9797 		    (un->un_errno == EIO)) {
9798 			un->un_rqs_state &= ~(ST_RQS_VALID);
9799 		}
9800 		break;
9801 
9802 	case COMMAND_DONE_ERROR_RECOVERED:
9803 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9804 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9805 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9806 		if (geterror(bp) == 0) {
9807 			st_bioerror(bp, EIO);
9808 		}
9809 		st_set_pe_flag(un);
9810 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9811 		    (un->un_errno == EIO)) {
9812 			un->un_rqs_state &= ~(ST_RQS_VALID);
9813 		}
9814 		/*FALLTHROUGH*/
9815 	case COMMAND_DONE:
9816 		st_set_state(un, bp);
9817 		break;
9818 
9819 	case QUE_SENSE:
9820 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9821 			goto sense_error;
9822 
9823 		if (un->un_state != ST_STATE_SENSING) {
9824 			un->un_laststate = un->un_state;
9825 			un->un_state = ST_STATE_SENSING;
9826 		}
9827 
9828 		/*
9829 		 * zero the sense data.
9830 		 */
9831 		bzero(un->un_rqs->pkt_scbp, SENSE_LENGTH);
9832 
9833 		/*
9834 		 * If this is not a retry on QUE_SENSE point to the original
9835 		 * bp of the command that got us here.
9836 		 */
9837 		if (pkt != un->un_rqs) {
9838 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp = bp;
9839 		}
9840 
9841 		if (un->un_throttle) {
9842 			un->un_last_throttle = un->un_throttle;
9843 			un->un_throttle = 0;
9844 		}
9845 
9846 		ST_CDB(ST_DEVINFO, "Queue sense CDB",
9847 		    (char *)BP_PKT(bp)->pkt_cdbp);
9848 
9849 		/*
9850 		 * never retry this, some other command will have nuked the
9851 		 * sense, anyway
9852 		 */
9853 		status = st_transport(un, un->un_rqs);
9854 
9855 		if (un->un_last_throttle) {
9856 			un->un_throttle = un->un_last_throttle;
9857 		}
9858 
9859 		if (status == TRAN_ACCEPT) {
9860 			mutex_exit(ST_MUTEX);
9861 			return;
9862 		}
9863 		if (status != TRAN_BUSY)
9864 			ST_DO_ERRSTATS(un, st_transerrs);
9865 sense_error:
9866 		un->un_pos.pmode = invalid;
9867 		st_bioerror(bp, EIO);
9868 		st_set_pe_flag(un);
9869 		break;
9870 
9871 	case QUE_BUSY_COMMAND:
9872 		/* longish timeout */
9873 		timout = ST_STATUS_BUSY_TIMEOUT;
9874 		goto que_it_up;
9875 
9876 	case QUE_COMMAND:
9877 		/* short timeout */
9878 		timout = ST_TRAN_BUSY_TIMEOUT;
9879 que_it_up:
9880 		/*
9881 		 * let st_handle_intr_busy put this bp back on waitq and make
9882 		 * checks to see if it is ok to requeue the command.
9883 		 */
9884 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9885 
9886 		/*
9887 		 * Save the throttle before setting up the timeout
9888 		 */
9889 		if (un->un_throttle) {
9890 			un->un_last_throttle = un->un_throttle;
9891 		}
9892 		mutex_exit(ST_MUTEX);
9893 		if (st_handle_intr_busy(un, bp, timout) == 0)
9894 			return;		/* timeout is setup again */
9895 
9896 		mutex_enter(ST_MUTEX);
9897 		un->un_pos.pmode = invalid;
9898 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9899 		st_bioerror(bp, EIO);
9900 		st_set_pe_flag(un);
9901 		break;
9902 
9903 	case QUE_LAST_COMMAND:
9904 
9905 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9906 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9907 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9908 			goto last_command_error;
9909 		}
9910 		mutex_exit(ST_MUTEX);
9911 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9912 			return;
9913 		mutex_enter(ST_MUTEX);
9914 last_command_error:
9915 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9916 		un->un_pos.pmode = invalid;
9917 		st_bioerror(bp, EIO);
9918 		st_set_pe_flag(un);
9919 		break;
9920 
9921 	case COMMAND_TIMEOUT:
9922 	case DEVICE_RESET:
9923 	case DEVICE_TAMPER:
9924 	case ATTEMPT_RETRY:
9925 	case PATH_FAILED:
9926 		ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9927 		    "Command Recovery called on %s status\n",
9928 		    errstatenames[action]);
9929 		action = st_command_recovery(un, pkt, action);
9930 		goto again;
9931 
9932 	default:
9933 		ASSERT(0);
9934 		/* FALLTHRU */
9935 	case JUST_RETURN:
9936 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9937 		mutex_exit(ST_MUTEX);
9938 		return;
9939 	}
9940 
9941 	ST_DO_KSTATS(bp, kstat_runq_exit);
9942 	st_done_and_mutex_exit(un, bp);
9943 }
9944 
9945 static errstate
9946 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9947 {
9948 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9949 	recov_info *rinfo;
9950 	errstate rval = COMMAND_DONE_ERROR;
9951 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9952 	    un->un_rqs : BP_PKT(bp);
9953 	int result;
9954 
9955 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9956 
9957 	rinfo = (recov_info *)pkt->pkt_private;
9958 
9959 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9960 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9961 
9962 	ASSERT(mutex_owned(ST_MUTEX));
9963 
9964 	/* prevent infinite number of retries */
9965 	if (rinfo->pkt_retry_cnt++ > st_retry_count) {
9966 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
9967 		    "Recovery stopped for incomplete %s command, "
9968 		    "retries exhausted",
9969 		    st_print_scsi_cmd(pkt->pkt_cdbp[0]));
9970 		return (COMMAND_DONE_ERROR);
9971 	}
9972 
9973 	switch (pkt->pkt_reason) {
9974 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9975 		/*
9976 		 * this occurs when accessing a powered down drive, no
9977 		 * need to complain; just fail the open
9978 		 */
9979 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9980 
9981 		/*
9982 		 * if we have commands outstanding in HBA, and a command
9983 		 * comes back incomplete, we're hosed, so reset target
9984 		 * If we have the bus, but cmd_incomplete, we probably just
9985 		 * have a failed selection, so don't reset the target, just
9986 		 * requeue the command and try again
9987 		 */
9988 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9989 			goto reset_target;
9990 		}
9991 
9992 		/*
9993 		 * Retry selection a couple more times if we're
9994 		 * open.  If opening, we only try just once to
9995 		 * reduce probe time for nonexistant devices.
9996 		 */
9997 		if ((un->un_laststate > ST_STATE_OPENING) &&
9998 		    (rinfo->pkt_retry_cnt < st_selection_retry_count)) {
9999 			/* XXX check retriable? */
10000 			rval = QUE_COMMAND;
10001 		}
10002 		ST_DO_ERRSTATS(un, st_transerrs);
10003 		break;
10004 
10005 	case CMD_ABORTED:
10006 		/*
10007 		 * most likely this is caused by flush-on-error support. If
10008 		 * it was not there, the we're in trouble.
10009 		 */
10010 		if (!un->un_flush_on_errors) {
10011 			un->un_status = SUN_KEY_FATAL;
10012 			goto reset_target;
10013 		}
10014 
10015 		st_set_pe_errno(un);
10016 		bioerror(bp, un->un_errno);
10017 		if (un->un_errno)
10018 			return (COMMAND_DONE_ERROR);
10019 		else
10020 			return (COMMAND_DONE);
10021 
10022 	case CMD_TIMEOUT:	/* Command timed out */
10023 		un->un_status = SUN_KEY_TIMEOUT;
10024 		return (COMMAND_TIMEOUT);
10025 
10026 	case CMD_TRAN_ERR:
10027 	case CMD_RESET:
10028 		if (pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET)) {
10029 			if ((un->un_rsvd_status &
10030 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
10031 			    ST_RESERVE) {
10032 				un->un_rsvd_status |= ST_LOST_RESERVE;
10033 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
10034 				    "Lost Reservation\n");
10035 			}
10036 			rval = DEVICE_RESET;
10037 			return (rval);
10038 		}
10039 		if (pkt->pkt_statistics & (STAT_ABORTED | STAT_TERMINATED)) {
10040 			rval = DEVICE_RESET;
10041 			return (rval);
10042 		}
10043 		/*FALLTHROUGH*/
10044 	default:
10045 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10046 		    "Unhandled packet status reason = %s statistics = 0x%x\n",
10047 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
10048 reset_target:
10049 
10050 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10051 		    "transport completed with %s\n",
10052 		    scsi_rname(pkt->pkt_reason));
10053 		ST_DO_ERRSTATS(un, st_transerrs);
10054 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
10055 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
10056 		    STAT_ABORTED)) == 0)) {
10057 
10058 			/*
10059 			 * If we haven't reserved the drive don't reset it.
10060 			 */
10061 			if ((un->un_rsvd_status &
10062 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
10063 				return (rval);
10064 			}
10065 
10066 			/*
10067 			 * if we aren't lost yet we will be soon.
10068 			 */
10069 			un->un_pos.pmode = invalid;
10070 
10071 			result = st_reset(un, RESET_LUN);
10072 
10073 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
10074 				/* no hope left to recover */
10075 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
10076 				    "recovery by resets failed\n");
10077 				return (rval);
10078 			}
10079 		}
10080 	}
10081 
10082 
10083 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
10084 		rval = QUE_COMMAND;
10085 	} else if (bp == un->un_sbufp) {
10086 		if (rinfo->privatelen == sizeof (recov_info)) {
10087 			if (rinfo->cmd_attrib->retriable) {
10088 				/*
10089 				 * These commands can be rerun
10090 				 * with impunity
10091 				 */
10092 				rval = QUE_COMMAND;
10093 			}
10094 		} else {
10095 			cmd_attribute const *attrib;
10096 			attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10097 			if (attrib->retriable) {
10098 				rval = QUE_COMMAND;
10099 			}
10100 		}
10101 	}
10102 
10103 	if (un->un_state >= ST_STATE_OPEN) {
10104 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10105 		    fail, scsi_rname(pkt->pkt_reason),
10106 		    (rval == COMMAND_DONE_ERROR)?
10107 		    "giving up" : "retrying command");
10108 	}
10109 	return (rval);
10110 }
10111 
10112 /*
10113  * if the device is busy, then put this bp back on the waitq, on the
10114  * interrupt thread, where we want the head of the queue and not the
10115  * end
10116  *
10117  * The callers of this routine should take measures to save the
10118  * un_throttle in un_last_throttle which will be restored in
10119  * st_intr_restart(). The only exception should be st_intr_restart()
10120  * calling this routine for which the saving is already done.
10121  */
10122 static int
10123 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
10124 	clock_t timeout_interval)
10125 {
10126 
10127 	int queued;
10128 	int rval = 0;
10129 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
10130 
10131 	mutex_enter(ST_MUTEX);
10132 
10133 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
10134 
10135 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10136 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
10137 
10138 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
10139 		queued = 1;
10140 	} else {
10141 		queued = 0;
10142 	}
10143 
10144 	/*
10145 	 * Check to see if we hit the retry timeout. We check to make sure
10146 	 * this is the first one on the runq and make sure we have not
10147 	 * queued up any more, so this one has to be the last on the list
10148 	 * also. If it is not, we have to fail.  If it is not the first, but
10149 	 * is the last we are in trouble anyway, as we are in the interrupt
10150 	 * context here.
10151 	 */
10152 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
10153 	    ((un->un_runqf != bp) && (un->un_runql != bp) && (queued))) {
10154 		rval = -1;
10155 		goto exit;
10156 	}
10157 
10158 	/* put the bp back on the waitq */
10159 	if (queued) {
10160 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
10161 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
10162 	}
10163 
10164 	/*
10165 	 * We don't want any other commands being started in the mean time.
10166 	 * If start had just released mutex after putting something on the
10167 	 * runq, we won't even get here.
10168 	 */
10169 	un->un_throttle = 0;
10170 
10171 	/*
10172 	 * send a marker pkt, if appropriate
10173 	 */
10174 	st_hba_unflush(un);
10175 
10176 	/*
10177 	 * all queues are aligned, we are just waiting to
10178 	 * transport
10179 	 */
10180 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
10181 
10182 exit:
10183 	mutex_exit(ST_MUTEX);
10184 	return (rval);
10185 }
10186 
10187 /*
10188  * To get one error entry from error stack
10189  */
10190 static int
10191 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
10192 {
10193 #ifdef _MULTI_DATAMODEL
10194 	/*
10195 	 * For use when a 32 bit app makes a call into a
10196 	 * 64 bit ioctl
10197 	 */
10198 	struct mterror_entry32 err_entry32;
10199 #endif /* _MULTI_DATAMODEL */
10200 
10201 	int rval = 0;
10202 	struct mterror_entry err_entry;
10203 	struct mterror_entry_stack *err_link_entry_p;
10204 	size_t arq_status_len_in, arq_status_len_kr;
10205 
10206 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
10207 
10208 	ASSERT(mutex_owned(ST_MUTEX));
10209 
10210 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10211 	    "st_get_error_entry()\n");
10212 
10213 	/*
10214 	 * if error record stack empty, return ENXIO
10215 	 */
10216 	if (un->un_error_entry_stk == NULL) {
10217 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10218 		    "st_get_error_entry: Error Entry Stack Empty!\n");
10219 		rval = ENXIO;
10220 		goto ret;
10221 	}
10222 
10223 	/*
10224 	 * get the top entry from stack
10225 	 */
10226 	err_link_entry_p = un->un_error_entry_stk;
10227 	arq_status_len_kr =
10228 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
10229 
10230 #ifdef _MULTI_DATAMODEL
10231 	switch (ddi_model_convert_from(flag & FMODELS)) {
10232 	case DDI_MODEL_ILP32:
10233 		if (ddi_copyin((void *)arg, &err_entry32,
10234 		    MTERROR_ENTRY_SIZE_32, flag)) {
10235 			rval = EFAULT;
10236 			goto ret;
10237 		}
10238 
10239 		arq_status_len_in =
10240 		    (size_t)err_entry32.mtee_arq_status_len;
10241 
10242 		err_entry32.mtee_cdb_len =
10243 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
10244 
10245 		if (arq_status_len_in > arq_status_len_kr)
10246 			err_entry32.mtee_arq_status_len =
10247 			    (size32_t)arq_status_len_kr;
10248 
10249 		if (ddi_copyout(
10250 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10251 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
10252 		    err_entry32.mtee_cdb_len, flag)) {
10253 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10254 			    "st_get_error_entry: Copy cdb buffer error!");
10255 			rval = EFAULT;
10256 		}
10257 
10258 		if (ddi_copyout(
10259 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10260 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
10261 		    err_entry32.mtee_arq_status_len, flag)) {
10262 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10263 			    "st_get_error_entry: copy arq status error!");
10264 			rval = EFAULT;
10265 		}
10266 
10267 		if (ddi_copyout(&err_entry32, (void *)arg,
10268 		    MTERROR_ENTRY_SIZE_32, flag)) {
10269 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10270 			    "st_get_error_entry: copy arq status out error!");
10271 			rval = EFAULT;
10272 		}
10273 		break;
10274 
10275 	case DDI_MODEL_NONE:
10276 		if (ddi_copyin((void *)arg, &err_entry,
10277 		    MTERROR_ENTRY_SIZE_64, flag)) {
10278 			rval = EFAULT;
10279 			goto ret;
10280 		}
10281 		arq_status_len_in = err_entry.mtee_arq_status_len;
10282 
10283 		err_entry.mtee_cdb_len =
10284 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
10285 
10286 		if (arq_status_len_in > arq_status_len_kr)
10287 			err_entry.mtee_arq_status_len =
10288 			    arq_status_len_kr;
10289 
10290 		if (ddi_copyout(
10291 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10292 		    err_entry.mtee_cdb_buf,
10293 		    err_entry.mtee_cdb_len, flag)) {
10294 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10295 			    "st_get_error_entry: Copy cdb buffer error!");
10296 			rval = EFAULT;
10297 		}
10298 
10299 		if (ddi_copyout(
10300 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10301 		    err_entry.mtee_arq_status,
10302 		    err_entry.mtee_arq_status_len, flag)) {
10303 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10304 			    "st_get_error_entry: copy arq status error!");
10305 			rval = EFAULT;
10306 		}
10307 
10308 		if (ddi_copyout(&err_entry, (void *)arg,
10309 		    MTERROR_ENTRY_SIZE_64, flag)) {
10310 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10311 			    "st_get_error_entry: copy arq status out error!");
10312 			rval = EFAULT;
10313 		}
10314 		break;
10315 	}
10316 #else /* _MULTI_DATAMODEL */
10317 	if (ddi_copyin((void *)arg, &err_entry,
10318 	    MTERROR_ENTRY_SIZE_64, flag)) {
10319 		rval = EFAULT;
10320 		goto ret;
10321 	}
10322 	arq_status_len_in = err_entry.mtee_arq_status_len;
10323 
10324 	err_entry.mtee_cdb_len =
10325 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
10326 
10327 	if (arq_status_len_in > arq_status_len_kr)
10328 		err_entry.mtee_arq_status_len =
10329 		    arq_status_len_kr;
10330 
10331 	if (ddi_copyout(
10332 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10333 	    err_entry.mtee_cdb_buf,
10334 	    err_entry.mtee_cdb_len, flag)) {
10335 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10336 		    "st_get_error_entry: Copy cdb buffer error!");
10337 		rval = EFAULT;
10338 	}
10339 
10340 	if (ddi_copyout(
10341 	    err_link_entry_p->mtees_entry.mtee_arq_status,
10342 	    err_entry.mtee_arq_status,
10343 	    err_entry.mtee_arq_status_len, flag)) {
10344 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10345 		    "st_get_error_entry: copy arq status buffer error!");
10346 		rval = EFAULT;
10347 	}
10348 
10349 	if (ddi_copyout(&err_entry, (void *)arg,
10350 	    MTERROR_ENTRY_SIZE_64, flag)) {
10351 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10352 		    "st_get_error_entry: copy arq status out error!");
10353 		rval = EFAULT;
10354 	}
10355 #endif /* _MULTI_DATAMODEL */
10356 
10357 	/*
10358 	 * update stack
10359 	 */
10360 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
10361 
10362 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
10363 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
10364 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
10365 
10366 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
10367 	    SECMDS_STATUS_SIZE);
10368 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
10369 
10370 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
10371 	err_link_entry_p = NULL;
10372 ret:
10373 	return (rval);
10374 }
10375 
10376 /*
10377  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
10378  * the scsi CDB command which causes the error and generates sense data and
10379  * the scsi status.
10380  *
10381  *      error-record stack
10382  *
10383  *
10384  *             TOP                                     BOTTOM
10385  *              ------------------------------------------
10386  *              |   0   |   1   |   2   |   ...  |   n   |
10387  *              ------------------------------------------
10388  *                  ^
10389  *                  |
10390  *       pointer to error entry
10391  *
10392  * when st driver generates one sense data record, it creates a error-entry
10393  * and pushes it onto the stack.
10394  *
10395  */
10396 
10397 static void
10398 st_update_error_stack(struct scsi_tape *un,
10399 			struct scsi_pkt *pkt,
10400 			struct scsi_arq_status *cmd)
10401 {
10402 	struct mterror_entry_stack *err_entry_tmp;
10403 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
10404 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
10405 
10406 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
10407 
10408 	ASSERT(mutex_owned(ST_MUTEX));
10409 
10410 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10411 	    "st_update_error_stack()\n");
10412 
10413 	ASSERT(cmd);
10414 	ASSERT(cdbp);
10415 	if (cdblen == 0) {
10416 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10417 		    "st_update_error_stack: CDB length error!\n");
10418 		return;
10419 	}
10420 
10421 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
10422 	ASSERT(err_entry_tmp != NULL);
10423 
10424 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
10425 	    kmem_alloc(cdblen, KM_SLEEP);
10426 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
10427 
10428 	err_entry_tmp->mtees_entry.mtee_arq_status =
10429 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
10430 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
10431 
10432 	/*
10433 	 * copy cdb command & length to current error entry
10434 	 */
10435 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
10436 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
10437 
10438 	/*
10439 	 * copy scsi status length to current error entry
10440 	 */
10441 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
10442 	    SECMDS_STATUS_SIZE;
10443 
10444 	/*
10445 	 * copy sense data and scsi status to current error entry
10446 	 */
10447 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
10448 	    SECMDS_STATUS_SIZE);
10449 
10450 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
10451 	un->un_error_entry_stk = err_entry_tmp;
10452 
10453 }
10454 
10455 /*
10456  * Empty all the error entry in stack
10457  */
10458 static void
10459 st_empty_error_stack(struct scsi_tape *un)
10460 {
10461 	struct mterror_entry_stack *linkp;
10462 
10463 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
10464 
10465 	ASSERT(mutex_owned(ST_MUTEX));
10466 
10467 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10468 	    "st_empty_entry_stack()\n");
10469 
10470 	while (un->un_error_entry_stk != NULL) {
10471 		linkp = un->un_error_entry_stk;
10472 		un->un_error_entry_stk =
10473 		    un->un_error_entry_stk->mtees_nextp;
10474 
10475 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
10476 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
10477 			    linkp->mtees_entry.mtee_cdb_len);
10478 
10479 		if (linkp->mtees_entry.mtee_arq_status != NULL)
10480 			kmem_free(linkp->mtees_entry.mtee_arq_status,
10481 			    linkp->mtees_entry.mtee_arq_status_len);
10482 
10483 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
10484 		linkp = NULL;
10485 	}
10486 }
10487 
10488 static errstate
10489 st_handle_sense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10490 {
10491 	struct scsi_pkt *pkt = BP_PKT(bp);
10492 	struct scsi_pkt *rqpkt = un->un_rqs;
10493 	struct scsi_arq_status arqstat;
10494 	recov_info *rcif = pkt->pkt_private;
10495 
10496 	errstate rval = COMMAND_DONE_ERROR;
10497 	int amt;
10498 
10499 	ST_FUNC(ST_DEVINFO, st_handle_sense);
10500 
10501 	ASSERT(mutex_owned(ST_MUTEX));
10502 
10503 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10504 	    "st_handle_sense()\n");
10505 
10506 	if (SCBP(rqpkt)->sts_busy) {
10507 		if (rcif->privatelen == sizeof (recov_info)) {
10508 			ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
10509 			    "Attempt recovery of busy unit on request sense\n");
10510 			rval = ATTEMPT_RETRY;
10511 		} else if (rcif->pkt_retry_cnt++ < st_retry_count) {
10512 			ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10513 			    "Retry busy unit on request sense\n");
10514 			rval = QUE_BUSY_COMMAND;
10515 		}
10516 		return (rval);
10517 	} else if (SCBP(rqpkt)->sts_chk) {
10518 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10519 		    "Check Condition on REQUEST SENSE\n");
10520 		return (rval);
10521 	}
10522 
10523 	/*
10524 	 * Make sure there is sense data to look at.
10525 	 */
10526 	if ((rqpkt->pkt_state & (STATE_GOT_BUS | STATE_GOT_TARGET |
10527 	    STATE_SENT_CMD | STATE_GOT_STATUS)) != (STATE_GOT_BUS |
10528 	    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) {
10529 		return (rval);
10530 	}
10531 
10532 	/* was there enough data? */
10533 	amt = (int)MAX_SENSE_LENGTH - rqpkt->pkt_resid;
10534 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
10535 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10536 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10537 		    "REQUEST SENSE couldn't get sense data\n");
10538 		return (rval);
10539 	}
10540 
10541 	bcopy(SCBP(pkt), &arqstat.sts_status,
10542 	    sizeof (struct scsi_status));
10543 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
10544 	    sizeof (struct scsi_status));
10545 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
10546 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
10547 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
10548 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
10549 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
10550 
10551 	/*
10552 	 * copy one arqstat entry in the sense data buffer
10553 	 */
10554 	st_update_error_stack(un, pkt, &arqstat);
10555 	return (st_decode_sense(un, bp, amt, &arqstat, pos));
10556 }
10557 
10558 static errstate
10559 st_handle_autosense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10560 {
10561 	struct scsi_pkt *pkt = BP_PKT(bp);
10562 	struct scsi_arq_status *arqstat =
10563 	    (struct scsi_arq_status *)pkt->pkt_scbp;
10564 	errstate rval = COMMAND_DONE_ERROR;
10565 	int amt;
10566 
10567 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
10568 
10569 	ASSERT(mutex_owned(ST_MUTEX));
10570 
10571 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10572 	    "st_handle_autosense()\n");
10573 
10574 	if (arqstat->sts_rqpkt_status.sts_busy) {
10575 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10576 		    "busy unit on request sense\n");
10577 		/*
10578 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
10579 		 * the disadvantage is that we do not have any delay for the
10580 		 * second retry of rqsense and we have to keep a packet around
10581 		 */
10582 		return (QUE_SENSE);
10583 
10584 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
10585 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10586 		    "transport error on REQUEST SENSE\n");
10587 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
10588 		    ((arqstat->sts_rqpkt_statistics &
10589 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
10590 			if (st_reset(un, RESET_LUN) == 0) {
10591 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10592 				    "recovery by resets failed\n");
10593 			}
10594 		}
10595 		return (rval);
10596 
10597 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
10598 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10599 		    "Check Condition on REQUEST SENSE\n");
10600 		return (rval);
10601 	}
10602 
10603 
10604 	/* was there enough data? */
10605 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10606 		amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10607 	} else {
10608 		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
10609 			amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10610 		} else {
10611 			amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10612 		}
10613 	}
10614 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
10615 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10616 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10617 		    "REQUEST SENSE couldn't get sense data\n");
10618 		return (rval);
10619 	}
10620 
10621 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10622 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, MAX_SENSE_LENGTH);
10623 	} else {
10624 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
10625 	}
10626 
10627 	/*
10628 	 * copy one arqstat entry in the sense data buffer
10629 	 */
10630 	st_update_error_stack(un, pkt, arqstat);
10631 
10632 	return (st_decode_sense(un, bp, amt, arqstat, pos));
10633 }
10634 
10635 static errstate
10636 st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
10637     struct scsi_arq_status *statusp, tapepos_t *pos)
10638 {
10639 	struct scsi_pkt *pkt = BP_PKT(bp);
10640 	recov_info *ri = pkt->pkt_private;
10641 	errstate rval = COMMAND_DONE_ERROR;
10642 	cmd_attribute const *attrib;
10643 	long resid;
10644 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10645 	int severity;
10646 	int get_error;
10647 
10648 	ST_FUNC(ST_DEVINFO, st_decode_sense);
10649 
10650 	ASSERT(mutex_owned(ST_MUTEX));
10651 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10652 	    "st_decode_sense()\n");
10653 
10654 	/*
10655 	 * For uscsi commands, squirrel away a copy of the
10656 	 * results of the Request Sense.
10657 	 */
10658 	if (USCSI_CMD(bp)) {
10659 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
10660 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
10661 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
10662 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
10663 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
10664 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
10665 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10666 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
10667 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
10668 		}
10669 	}
10670 
10671 	if (ri->privatelen == sizeof (recov_info)) {
10672 		attrib = ri->cmd_attrib;
10673 	} else {
10674 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10675 	}
10676 
10677 	/*
10678 	 * If the drive is an MT-02, reposition the
10679 	 * secondary error code into the proper place.
10680 	 *
10681 	 * XXX	MT-02 is non-CCS tape, so secondary error code
10682 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
10683 	 * so it's in byte 12.
10684 	 */
10685 	if (un->un_dp->type == ST_TYPE_EMULEX) {
10686 		sensep->es_code = sensep->es_add_info[0];
10687 	}
10688 
10689 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
10690 	    (caddr_t)&CDBP(pkt)->scc_cmd);
10691 
10692 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)statusp,
10693 	    sizeof (*statusp));
10694 
10695 	/* for normal I/O check extract the resid values. */
10696 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
10697 		if (sensep->es_valid) {
10698 			resid =
10699 			    (sensep->es_info_1 << 24) |
10700 			    (sensep->es_info_2 << 16) |
10701 			    (sensep->es_info_3 << 8)  |
10702 			    (sensep->es_info_4);
10703 			/* If fixed block */
10704 			if (un->un_bsize) {
10705 				resid *= un->un_bsize;
10706 			}
10707 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
10708 			resid = pkt->pkt_resid;
10709 		} else {
10710 			resid = bp->b_bcount;
10711 		}
10712 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10713 		    "st_decode_sense (rw): xferred bit = %d, resid=%ld (%d), "
10714 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
10715 		    resid,
10716 		    (sensep->es_info_1 << 24) |
10717 		    (sensep->es_info_2 << 16) |
10718 		    (sensep->es_info_3 << 8)  |
10719 		    (sensep->es_info_4),
10720 		    pkt->pkt_resid);
10721 		/*
10722 		 * The problem is, what should we believe?
10723 		 */
10724 		if (resid && (pkt->pkt_resid == 0)) {
10725 			pkt->pkt_resid = resid;
10726 		}
10727 	} else {
10728 		/*
10729 		 * If the command is SCMD_SPACE, we need to get the
10730 		 * residual as returned in the sense data, to adjust
10731 		 * our idea of current tape position correctly
10732 		 */
10733 		if ((sensep->es_valid) &&
10734 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10735 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10736 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
10737 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE_G4) ||
10738 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK)) {
10739 			resid =
10740 			    (sensep->es_info_1 << 24) |
10741 			    (sensep->es_info_2 << 16) |
10742 			    (sensep->es_info_3 << 8)  |
10743 			    (sensep->es_info_4);
10744 			bp->b_resid = resid;
10745 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10746 			    "st_decode_sense(other):	resid=%ld\n", resid);
10747 		} else {
10748 			/*
10749 			 * If the special command is SCMD_READ,
10750 			 * the correct resid will be set later.
10751 			 */
10752 			if (attrib->get_cnt != NULL) {
10753 				resid = attrib->get_cnt(pkt->pkt_cdbp);
10754 			} else {
10755 				resid = bp->b_bcount;
10756 			}
10757 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10758 			    "st_decode_sense(special read):  resid=%ld\n",
10759 			    resid);
10760 		}
10761 	}
10762 
10763 	if ((un->un_state >= ST_STATE_OPEN) &&
10764 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
10765 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
10766 		    "Failed CDB", (char *)pkt->pkt_cdbp);
10767 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10768 		    "sense data", (char *)sensep, amt);
10769 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10770 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10771 		    bp->b_bcount, resid, pkt->pkt_resid);
10772 	}
10773 
10774 	switch (un->un_status = sensep->es_key) {
10775 	case KEY_NO_SENSE:
10776 		severity = SCSI_ERR_INFO;
10777 
10778 		/*
10779 		 * Erase, locate or rewind operation in progress, retry
10780 		 * ASC  ASCQ
10781 		 *  00   18    Erase operation in progress
10782 		 *  00   19    Locate operation in progress
10783 		 *  00   1A    Rewind operation in progress
10784 		 */
10785 		if (sensep->es_add_code == 0 &&
10786 		    ((sensep->es_qual_code == 0x18) ||
10787 		    (sensep->es_qual_code == 0x19) ||
10788 		    (sensep->es_qual_code == 0x1a))) {
10789 			rval = QUE_BUSY_COMMAND;
10790 			break;
10791 		}
10792 
10793 		goto common;
10794 
10795 	case KEY_RECOVERABLE_ERROR:
10796 		severity = SCSI_ERR_RECOVERED;
10797 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10798 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10799 			if (un->un_dp->options &
10800 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10801 				rval = QUE_LAST_COMMAND;
10802 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10803 				    severity, pos->lgclblkno,
10804 				    un->un_err_pos.lgclblkno, scsi_cmds,
10805 				    sensep);
10806 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10807 				    "Command will be retried\n");
10808 			} else {
10809 				severity = SCSI_ERR_FATAL;
10810 				rval = COMMAND_DONE_ERROR_RECOVERED;
10811 				ST_DO_ERRSTATS(un, st_softerrs);
10812 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10813 				    severity, pos->lgclblkno,
10814 				    un->un_err_pos.lgclblkno, scsi_cmds,
10815 				    sensep);
10816 			}
10817 			break;
10818 		}
10819 common:
10820 		/*
10821 		 * XXX only want reads to be stopped by filemarks.
10822 		 * Don't want them to be stopped by EOT.  EOT matters
10823 		 * only on write.
10824 		 */
10825 		if (sensep->es_filmk && !sensep->es_eom) {
10826 			rval = COMMAND_DONE;
10827 		} else if (sensep->es_eom) {
10828 			rval = COMMAND_DONE;
10829 		} else if (sensep->es_ili) {
10830 			/*
10831 			 * Fun with variable length record devices:
10832 			 * for specifying larger blocks sizes than the
10833 			 * actual physical record size.
10834 			 */
10835 			if (un->un_bsize == 0 && resid > 0) {
10836 				/*
10837 				 * XXX! Ugly.
10838 				 * The requested blocksize is > tape blocksize,
10839 				 * so this is ok, so we just return the
10840 				 * actual size xferred.
10841 				 */
10842 				pkt->pkt_resid = resid;
10843 				rval = COMMAND_DONE;
10844 			} else if (un->un_bsize == 0 && resid < 0) {
10845 				/*
10846 				 * The requested blocksize is < tape blocksize,
10847 				 * so this is not ok, so we err with ENOMEM
10848 				 */
10849 				rval = COMMAND_DONE_ERROR_RECOVERED;
10850 				st_bioerror(bp, ENOMEM);
10851 			} else {
10852 				ST_DO_ERRSTATS(un, st_softerrs);
10853 				severity = SCSI_ERR_FATAL;
10854 				rval = COMMAND_DONE_ERROR;
10855 				st_bioerror(bp, EINVAL);
10856 				un->un_running.pmode = invalid;
10857 			}
10858 		} else {
10859 			/*
10860 			 * we hope and pray for this just being
10861 			 * something we can ignore (ie. a
10862 			 * truly recoverable soft error)
10863 			 */
10864 			rval = COMMAND_DONE;
10865 		}
10866 		if (sensep->es_filmk) {
10867 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10868 			    "filemark\n");
10869 			un->un_status = SUN_KEY_EOF;
10870 			pos->eof = ST_EOF_PENDING;
10871 			st_set_pe_flag(un);
10872 		}
10873 
10874 		/*
10875 		 * ignore eom when reading, a fmk should terminate reading
10876 		 */
10877 		if ((sensep->es_eom) &&
10878 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10879 			if ((sensep->es_add_code == 0) &&
10880 			    (sensep->es_qual_code == 4)) {
10881 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10882 				    "bot\n");
10883 				un->un_status = SUN_KEY_BOT;
10884 				pos->eof = ST_NO_EOF;
10885 				pos->lgclblkno = 0;
10886 				pos->fileno = 0;
10887 				pos->blkno = 0;
10888 				if (pos->pmode != legacy)
10889 					pos->pmode = legacy;
10890 			} else {
10891 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10892 				    "eom\n");
10893 				un->un_status = SUN_KEY_EOT;
10894 				pos->eof = ST_EOM;
10895 			}
10896 			st_set_pe_flag(un);
10897 		}
10898 
10899 		break;
10900 
10901 	case KEY_ILLEGAL_REQUEST:
10902 
10903 		if (un->un_laststate >= ST_STATE_OPEN) {
10904 			ST_DO_ERRSTATS(un, st_softerrs);
10905 			severity = SCSI_ERR_FATAL;
10906 		} else {
10907 			severity = SCSI_ERR_INFO;
10908 		}
10909 		break;
10910 
10911 	case KEY_MEDIUM_ERROR:
10912 		ST_DO_ERRSTATS(un, st_harderrs);
10913 		severity = SCSI_ERR_FATAL;
10914 		un->un_pos.pmode = invalid;
10915 		un->un_running.pmode = invalid;
10916 check_keys:
10917 		/*
10918 		 * attempt to process the keys in the presence of
10919 		 * other errors
10920 		 */
10921 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10922 			/*
10923 			 * Fun with variable length record devices:
10924 			 * for specifying larger blocks sizes than the
10925 			 * actual physical record size.
10926 			 */
10927 			if (un->un_bsize == 0 && resid > 0) {
10928 				/*
10929 				 * XXX! Ugly
10930 				 */
10931 				pkt->pkt_resid = resid;
10932 			} else if (un->un_bsize == 0 && resid < 0) {
10933 				st_bioerror(bp, EINVAL);
10934 			} else {
10935 				severity = SCSI_ERR_FATAL;
10936 				rval = COMMAND_DONE_ERROR;
10937 				st_bioerror(bp, EINVAL);
10938 			}
10939 		}
10940 		if (sensep->es_filmk) {
10941 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10942 			    "filemark\n");
10943 			un->un_status = SUN_KEY_EOF;
10944 			pos->eof = ST_EOF_PENDING;
10945 			st_set_pe_flag(un);
10946 		}
10947 
10948 		/*
10949 		 * ignore eom when reading, a fmk should terminate reading
10950 		 */
10951 		if ((sensep->es_eom) &&
10952 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10953 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10954 			un->un_status = SUN_KEY_EOT;
10955 			pos->eof = ST_EOM;
10956 			st_set_pe_flag(un);
10957 		}
10958 
10959 		break;
10960 
10961 	case KEY_VOLUME_OVERFLOW:
10962 		ST_DO_ERRSTATS(un, st_softerrs);
10963 		pos->eof = ST_EOM;
10964 		severity = SCSI_ERR_FATAL;
10965 		rval = COMMAND_DONE_ERROR;
10966 		goto check_keys;
10967 
10968 	case KEY_HARDWARE_ERROR:
10969 		ST_DO_ERRSTATS(un, st_harderrs);
10970 		severity = SCSI_ERR_FATAL;
10971 		rval = COMMAND_DONE_ERROR;
10972 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10973 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10974 		break;
10975 
10976 	case KEY_BLANK_CHECK:
10977 		ST_DO_ERRSTATS(un, st_softerrs);
10978 		severity = SCSI_ERR_INFO;
10979 
10980 		/*
10981 		 * if not a special request and some data was xferred then it
10982 		 * it is not an error yet
10983 		 */
10984 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10985 			/*
10986 			 * no error for read with or without data xferred
10987 			 */
10988 			un->un_status = SUN_KEY_EOT;
10989 			pos->eof = ST_EOT;
10990 			rval = COMMAND_DONE_ERROR;
10991 			un->un_running.pmode = invalid;
10992 			st_set_pe_flag(un);
10993 			goto check_keys;
10994 		} else if (bp != un->un_sbufp &&
10995 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10996 			rval = COMMAND_DONE;
10997 		} else {
10998 			rval = COMMAND_DONE_ERROR_RECOVERED;
10999 		}
11000 
11001 		if (un->un_laststate >= ST_STATE_OPEN) {
11002 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11003 			    "blank check\n");
11004 			pos->eof = ST_EOM;
11005 		}
11006 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
11007 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
11008 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
11009 		    (un->un_dp->options & ST_KNOWS_EOD)) {
11010 			/*
11011 			 * we were doing a fast forward by skipping
11012 			 * multiple fmk at the time
11013 			 */
11014 			st_bioerror(bp, EIO);
11015 			severity = SCSI_ERR_RECOVERED;
11016 			rval	 = COMMAND_DONE;
11017 		}
11018 		st_set_pe_flag(un);
11019 		goto check_keys;
11020 
11021 	case KEY_WRITE_PROTECT:
11022 		if (st_wrongtapetype(un)) {
11023 			un->un_status = SUN_KEY_WRONGMEDIA;
11024 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11025 			    "wrong tape for writing- use DC6150 tape "
11026 			    "(or equivalent)\n");
11027 			severity = SCSI_ERR_UNKNOWN;
11028 		} else {
11029 			severity = SCSI_ERR_FATAL;
11030 		}
11031 		ST_DO_ERRSTATS(un, st_harderrs);
11032 		rval = COMMAND_DONE_ERROR;
11033 		st_bioerror(bp, EACCES);
11034 		break;
11035 
11036 	case KEY_UNIT_ATTENTION:
11037 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11038 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
11039 
11040 		un->un_unit_attention_flags |= 1;
11041 		/*
11042 		 * If we have detected a Bus Reset and the tape
11043 		 * drive has been reserved.
11044 		 */
11045 		if (ST_RQSENSE->es_add_code == 0x29) {
11046 			rval = DEVICE_RESET;
11047 			if ((un->un_rsvd_status &
11048 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
11049 			    ST_RESERVE) {
11050 				un->un_rsvd_status |= ST_LOST_RESERVE;
11051 				ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
11052 				    "st_decode_sense: Lost Reservation\n");
11053 			}
11054 		}
11055 
11056 		/*
11057 		 * If this is a recovery command and retrable, retry.
11058 		 */
11059 		if (bp == un->un_recov_buf) {
11060 			severity = SCSI_ERR_INFO;
11061 			if (attrib->retriable &&
11062 			    ri->pkt_retry_cnt++ < st_retry_count) {
11063 				rval = QUE_COMMAND;
11064 			} else {
11065 				rval = COMMAND_DONE_ERROR;
11066 			}
11067 			break; /* Don't set position invalid */
11068 		}
11069 
11070 		/*
11071 		 * If ST_APPLICATION_RESERVATIONS is set,
11072 		 * If the asc/ascq indicates that the reservation
11073 		 * has been cleared just allow the write to continue
11074 		 * which would force a scsi 2 reserve.
11075 		 * If preempted that persistent reservation
11076 		 * the scsi 2 reserve would get a reservation conflict.
11077 		 */
11078 		if ((un->un_rsvd_status &
11079 		    ST_APPLICATION_RESERVATIONS) != 0) {
11080 			/*
11081 			 * RESERVATIONS PREEMPTED
11082 			 * With MPxIO this could be a fail over? XXX
11083 			 */
11084 			if (ST_RQSENSE->es_add_code == 0x2a &&
11085 			    ST_RQSENSE->es_qual_code == 0x03) {
11086 				severity = SCSI_ERR_INFO;
11087 				rval = COMMAND_DONE_ERROR;
11088 				pos->pmode = invalid;
11089 				break;
11090 			/*
11091 			 * RESERVATIONS RELEASED
11092 			 */
11093 			} else if (ST_RQSENSE->es_add_code == 0x2a &&
11094 			    ST_RQSENSE->es_qual_code == 0x04) {
11095 				severity = SCSI_ERR_INFO;
11096 				rval = COMMAND_DONE;
11097 				break;
11098 			}
11099 		}
11100 
11101 		if (un->un_state <= ST_STATE_OPENING) {
11102 			/*
11103 			 * Look, the tape isn't open yet, now determine
11104 			 * if the cause is a BUS RESET, Save the file
11105 			 * and Block positions for the callers to
11106 			 * recover from the loss of position.
11107 			 */
11108 			severity = SCSI_ERR_INFO;
11109 			if ((pos->pmode != invalid) &&
11110 			    (rval == DEVICE_RESET) &&
11111 			    (un->un_restore_pos != 1)) {
11112 				un->un_save_fileno = pos->fileno;
11113 				un->un_save_blkno = pos->blkno;
11114 				un->un_restore_pos = 1;
11115 			}
11116 
11117 			if (attrib->retriable &&
11118 			    ri->pkt_retry_cnt++ < st_retry_count) {
11119 				rval = QUE_COMMAND;
11120 			} else if (rval == DEVICE_RESET) {
11121 				break;
11122 			} else {
11123 				rval = COMMAND_DONE_ERROR;
11124 			}
11125 		/*
11126 		 * Means it thinks the mode parameters have changed.
11127 		 * This is the result of a reset clearing settings or
11128 		 * another initiator changing what we set.
11129 		 */
11130 		}
11131 		if (ST_RQSENSE->es_add_code == 0x2a) {
11132 			if (ST_RQSENSE->es_qual_code == 0x1) {
11133 				/* Error recovery will modeselect and retry. */
11134 				rval = DEVICE_TAMPER;
11135 				severity = SCSI_ERR_INFO;
11136 				break; /* don't set position invalid */
11137 			}
11138 			if (ST_RQSENSE->es_qual_code == 0x0 ||
11139 			    ST_RQSENSE->es_qual_code == 0x2 ||
11140 			    ST_RQSENSE->es_qual_code == 0x3 ||
11141 			    ST_RQSENSE->es_qual_code == 0x4 ||
11142 			    ST_RQSENSE->es_qual_code == 0x5 ||
11143 			    ST_RQSENSE->es_qual_code == 0x6 ||
11144 			    ST_RQSENSE->es_qual_code == 0x7) {
11145 				rval = DEVICE_TAMPER;
11146 				severity = SCSI_ERR_INFO;
11147 			}
11148 		} else if (ST_RQSENSE->es_add_code == 0x28 &&
11149 		    ((ST_RQSENSE->es_qual_code == 0x0) ||
11150 		    ST_RQSENSE->es_qual_code == 0x5)) {
11151 			/*
11152 			 * Not Ready to Ready change, Media may have changed.
11153 			 */
11154 			rval = DEVICE_TAMPER;
11155 			severity = SCSI_ERR_RETRYABLE;
11156 		} else {
11157 			if (rval != DEVICE_RESET) {
11158 				rval = COMMAND_DONE_ERROR;
11159 			} else {
11160 				/*
11161 				 * Returning DEVICE_RESET will call
11162 				 * error recovery.
11163 				 */
11164 				severity = SCSI_ERR_INFO;
11165 				break; /* don't set position invalid */
11166 			}
11167 			/*
11168 			 * Check if it is an Unexpected Unit Attention.
11169 			 * If state is >= ST_STATE_OPEN, we have
11170 			 * already done the initialization .
11171 			 * In this case it is Fatal Error
11172 			 * since no further reading/writing
11173 			 * can be done with fileno set to < 0.
11174 			 */
11175 			if (un->un_state >= ST_STATE_OPEN) {
11176 				ST_DO_ERRSTATS(un, st_harderrs);
11177 				severity = SCSI_ERR_FATAL;
11178 			} else {
11179 				severity = SCSI_ERR_INFO;
11180 			}
11181 		}
11182 
11183 		pos->pmode = invalid;
11184 
11185 		break;
11186 
11187 	case KEY_NOT_READY:
11188 		/*
11189 		 * If in process of getting ready retry.
11190 		 */
11191 		if (sensep->es_add_code == 0x04) {
11192 			switch (sensep->es_qual_code) {
11193 			case 0x07:
11194 				/*
11195 				 * We get here when the tape is rewinding.
11196 				 * QUE_BUSY_COMMAND retries every 10 seconds.
11197 				 */
11198 				if (ri->pkt_retry_cnt++ <
11199 				    (un->un_dp->rewind_timeout / 10)) {
11200 					rval = QUE_BUSY_COMMAND;
11201 					severity = SCSI_ERR_INFO;
11202 				} else {
11203 					/* give up */
11204 					rval = COMMAND_DONE_ERROR;
11205 					severity = SCSI_ERR_FATAL;
11206 				}
11207 				break;
11208 			case 0x01:
11209 				if (ri->pkt_retry_cnt++ < st_retry_count) {
11210 					rval = QUE_COMMAND;
11211 					severity = SCSI_ERR_INFO;
11212 					break;
11213 				}
11214 			default: /* FALLTHRU */
11215 				/* give up */
11216 				rval = COMMAND_DONE_ERROR;
11217 				severity = SCSI_ERR_FATAL;
11218 			}
11219 		} else {
11220 			/* give up */
11221 			rval = COMMAND_DONE_ERROR;
11222 			severity = SCSI_ERR_FATAL;
11223 		}
11224 
11225 		/*
11226 		 * If this was an error and after device opened
11227 		 * do error stats.
11228 		 */
11229 		if (rval == COMMAND_DONE_ERROR &&
11230 		    un->un_state > ST_STATE_OPENING) {
11231 			ST_DO_ERRSTATS(un, st_harderrs);
11232 		}
11233 
11234 		if (ST_RQSENSE->es_add_code == 0x3a) {
11235 			if (st_error_level >= SCSI_ERR_FATAL)
11236 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11237 				    "Tape not inserted in drive\n");
11238 			un->un_mediastate = MTIO_EJECTED;
11239 			cv_broadcast(&un->un_state_cv);
11240 		}
11241 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
11242 		    (rval != QUE_COMMAND))
11243 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
11244 		break;
11245 
11246 	case KEY_ABORTED_COMMAND:
11247 		/* XXX Do drives return this when they see a lost light? */
11248 		/* Testing would say yes */
11249 
11250 		if (ri->pkt_retry_cnt++ < st_retry_count) {
11251 			rval = ATTEMPT_RETRY;
11252 			severity = SCSI_ERR_RETRYABLE;
11253 			goto check_keys;
11254 		}
11255 		/*
11256 		 * Probably a parity error...
11257 		 * if we retry here then this may cause data to be
11258 		 * written twice or data skipped during reading
11259 		 */
11260 		ST_DO_ERRSTATS(un, st_harderrs);
11261 		severity = SCSI_ERR_FATAL;
11262 		rval = COMMAND_DONE_ERROR;
11263 		goto check_keys;
11264 
11265 	default:
11266 		/*
11267 		 * Undecoded sense key.	 Try retries and hope
11268 		 * that will fix the problem.  Otherwise, we're
11269 		 * dead.
11270 		 */
11271 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11272 		    "Unhandled Sense Key '%s'\n",
11273 		    sense_keys[un->un_status]);
11274 		ST_DO_ERRSTATS(un, st_harderrs);
11275 		severity = SCSI_ERR_FATAL;
11276 		rval = COMMAND_DONE_ERROR;
11277 		goto check_keys;
11278 	}
11279 
11280 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
11281 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
11282 	    (un->un_laststate > ST_STATE_OPENING) &&
11283 	    (severity >= st_error_level))) {
11284 
11285 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
11286 		    pos->lgclblkno, un->un_err_pos.lgclblkno,
11287 		    scsi_cmds, sensep);
11288 		if (sensep->es_filmk) {
11289 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11290 			    "File Mark Detected\n");
11291 		}
11292 		if (sensep->es_eom) {
11293 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11294 			    "End-of-Media Detected\n");
11295 		}
11296 		if (sensep->es_ili) {
11297 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11298 			    "Incorrect Length Indicator Set\n");
11299 		}
11300 	}
11301 	get_error = geterror(bp);
11302 	if (((rval == COMMAND_DONE_ERROR) ||
11303 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
11304 	    ((get_error == EIO) || (get_error == 0))) {
11305 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
11306 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
11307 		if (un->un_rqs_state & ST_RQS_READ) {
11308 			un->un_rqs_state &= ~(ST_RQS_READ);
11309 		} else {
11310 			un->un_rqs_state |= ST_RQS_OVR;
11311 		}
11312 	}
11313 
11314 	return (rval);
11315 }
11316 
11317 
11318 static int
11319 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
11320 {
11321 	int status = TRAN_ACCEPT;
11322 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
11323 
11324 	mutex_enter(ST_MUTEX);
11325 
11326 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
11327 
11328 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11329 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
11330 
11331 	/*
11332 	 * Check to see if we hit the retry timeout. We check to make sure
11333 	 * this is the first one on the runq and make sure we have not
11334 	 * queued up any more, so this one has to be the last on the list
11335 	 * also. If it is not, we have to fail.  If it is not the first, but
11336 	 * is the last we are in trouble anyway, as we are in the interrupt
11337 	 * context here.
11338 	 */
11339 	if ((pktinfo->pkt_retry_cnt > st_retry_count) ||
11340 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
11341 		goto exit;
11342 	}
11343 
11344 	if (un->un_throttle) {
11345 		un->un_last_throttle = un->un_throttle;
11346 		un->un_throttle = 0;
11347 	}
11348 
11349 	/*
11350 	 * Here we know : bp is the first and last one on the runq
11351 	 * it is not necessary to put it back on the head of the
11352 	 * waitq and then move from waitq to runq. Save this queuing
11353 	 * and call scsi_transport.
11354 	 */
11355 	ST_CDB(ST_DEVINFO, "Retry lcmd CDB", (char *)BP_PKT(bp)->pkt_cdbp);
11356 
11357 	status = st_transport(un, BP_PKT(bp));
11358 
11359 	if (status == TRAN_ACCEPT) {
11360 		if (un->un_last_throttle) {
11361 			un->un_throttle = un->un_last_throttle;
11362 		}
11363 		mutex_exit(ST_MUTEX);
11364 
11365 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11366 		    "restart transport \n");
11367 		return (0);
11368 	}
11369 
11370 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
11371 	mutex_exit(ST_MUTEX);
11372 
11373 	if (status == TRAN_BUSY) {
11374 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
11375 			return (0);
11376 		}
11377 	}
11378 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11379 	    "restart transport rejected\n");
11380 	mutex_enter(ST_MUTEX);
11381 	ST_DO_ERRSTATS(un, st_transerrs);
11382 	if (un->un_last_throttle) {
11383 		un->un_throttle = un->un_last_throttle;
11384 	}
11385 exit:
11386 	mutex_exit(ST_MUTEX);
11387 	return (-1);
11388 }
11389 
11390 static int
11391 st_wrongtapetype(struct scsi_tape *un)
11392 {
11393 
11394 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
11395 
11396 	ASSERT(mutex_owned(ST_MUTEX));
11397 
11398 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
11399 
11400 	/*
11401 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
11402 	 */
11403 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
11404 		switch (un->un_dp->type) {
11405 		case ST_TYPE_WANGTEK:
11406 		case ST_TYPE_ARCHIVE:
11407 			/*
11408 			 * If this really worked, we could go off of
11409 			 * the density codes set in the modesense
11410 			 * page. For this drive, 0x10 == QIC-120,
11411 			 * 0xf == QIC-150, and 0x5 should be for
11412 			 * both QIC-24 and, maybe, QIC-11. However,
11413 			 * the h/w doesn't do what the manual says
11414 			 * that it should, so we'll key off of
11415 			 * getting a WRITE PROTECT error AND wp *not*
11416 			 * set in the mode sense information.
11417 			 */
11418 			/*
11419 			 * XXX but we already know that status is
11420 			 * write protect, so don't check it again.
11421 			 */
11422 
11423 			if (un->un_status == KEY_WRITE_PROTECT &&
11424 			    un->un_mspl->wp == 0) {
11425 				return (1);
11426 			}
11427 			break;
11428 		default:
11429 			break;
11430 		}
11431 	}
11432 	return (0);
11433 }
11434 
11435 static errstate
11436 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
11437 {
11438 	errstate action;
11439 	recov_info *rcvi = pkt->pkt_private;
11440 	buf_t *bp = rcvi->cmd_bp;
11441 	struct scsi_arq_status *stat = (struct scsi_arq_status *)pkt->pkt_scbp;
11442 
11443 	ST_FUNC(ST_DEVINFO, st_check_error);
11444 
11445 	ASSERT(mutex_owned(ST_MUTEX));
11446 
11447 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
11448 
11449 	switch (SCBP_C(pkt)) {
11450 	case STATUS_RESERVATION_CONFLICT:
11451 		/*
11452 		 * Command recovery is enabled, not just opening,
11453 		 * we had the drive reserved and we thing its ours.
11454 		 * Call recovery to attempt to take it back.
11455 		 */
11456 		if ((rcvi->privatelen == sizeof (recov_info)) &&
11457 		    (bp != un->un_recov_buf) &&
11458 		    (un->un_state > ST_STATE_OPEN_PENDING_IO) &&
11459 		    ((un->un_rsvd_status & (ST_RESERVE |
11460 		    ST_APPLICATION_RESERVATIONS)) != 0)) {
11461 			action = ATTEMPT_RETRY;
11462 			un->un_rsvd_status |= ST_LOST_RESERVE;
11463 		} else {
11464 			action = COMMAND_DONE_EACCES;
11465 			un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
11466 		}
11467 		break;
11468 
11469 	case STATUS_BUSY:
11470 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
11471 		if (rcvi->privatelen == sizeof (recov_info) &&
11472 		    un->un_multipath && (pkt->pkt_state == (STATE_GOT_BUS |
11473 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS))) {
11474 			/*
11475 			 * Status returned by scsi_vhci indicating path
11476 			 * has failed over.
11477 			 */
11478 			action = PATH_FAILED;
11479 			break;
11480 		}
11481 		/* FALLTHRU */
11482 	case STATUS_QFULL:
11483 		if (rcvi->privatelen == sizeof (recov_info)) {
11484 			/*
11485 			 * If recovery is inabled use it instead of
11486 			 * blind reties.
11487 			 */
11488 			action = ATTEMPT_RETRY;
11489 		} else if (rcvi->pkt_retry_cnt++ < st_retry_count) {
11490 			action = QUE_BUSY_COMMAND;
11491 		} else if ((un->un_rsvd_status &
11492 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
11493 			/*
11494 			 * If this is a command done before reserve is done
11495 			 * don't reset.
11496 			 */
11497 			action = COMMAND_DONE_ERROR;
11498 		} else {
11499 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11500 			    "unit busy too long\n");
11501 			(void) st_reset(un, RESET_ALL);
11502 			action = COMMAND_DONE_ERROR;
11503 		}
11504 		break;
11505 
11506 	case STATUS_CHECK:
11507 	case STATUS_TERMINATED:
11508 		/*
11509 		 * we should only get here if the auto rqsense failed
11510 		 * thru a uscsi cmd without autorequest sense
11511 		 * so we just try again
11512 		 */
11513 		if (un->un_arq_enabled &&
11514 		    stat->sts_rqpkt_reason == CMD_CMPLT &&
11515 		    (stat->sts_rqpkt_state & (STATE_GOT_BUS |
11516 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) ==
11517 		    (STATE_GOT_BUS | STATE_GOT_TARGET | STATE_SENT_CMD |
11518 		    STATE_GOT_STATUS)) {
11519 
11520 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11521 			    "Really got sense data\n");
11522 			action = st_decode_sense(un, bp, MAX_SENSE_LENGTH -
11523 			    pkt->pkt_resid, stat, &un->un_pos);
11524 		} else {
11525 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11526 			    "Trying to queue sense command\n");
11527 			action = QUE_SENSE;
11528 		}
11529 		break;
11530 
11531 	case STATUS_TASK_ABORT:
11532 		/*
11533 		 * This is an aborted task. This can be a reset on the other
11534 		 * port of a multiport drive. Lets try and recover it.
11535 		 */
11536 		action = DEVICE_RESET;
11537 		break;
11538 
11539 	default:
11540 		action = COMMAND_DONE;
11541 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
11542 		    "Unexpected scsi status byte 0x%x\n", SCBP_C(pkt));
11543 	}
11544 	return (action);
11545 }
11546 
11547 static void
11548 st_calc_bnum(struct scsi_tape *un, struct buf *bp, struct scsi_pkt *pkt)
11549 {
11550 	int nblks;
11551 	int nfiles;
11552 	long count;
11553 	recov_info *ri = pkt->pkt_private;
11554 	cmd_attribute const *attrib;
11555 
11556 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
11557 
11558 	ASSERT(mutex_owned(ST_MUTEX));
11559 
11560 	if (ri->privatelen == sizeof (recov_info)) {
11561 		attrib = ri->cmd_attrib;
11562 		ASSERT(attrib->recov_pos_type == POS_EXPECTED);
11563 		ASSERT(attrib->chg_tape_pos);
11564 	} else {
11565 		ri = NULL;
11566 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
11567 	}
11568 
11569 	count = bp->b_bcount - bp->b_resid;
11570 
11571 	/* Command reads or writes data */
11572 	if (attrib->transfers_data != TRAN_NONE) {
11573 		if (count == 0) {
11574 			/* failed writes should not make it here */
11575 			ASSERT(attrib->transfers_data == TRAN_READ);
11576 			nblks = 0;
11577 			nfiles = 1;
11578 		} else if (un->un_bsize == 0) {
11579 			/*
11580 			 * If variable block mode.
11581 			 * Fixed bit in CBD should be zero.
11582 			 */
11583 			ASSERT((pkt->pkt_cdbp[1] & 1) == 0);
11584 			nblks = 1;
11585 			un->un_kbytes_xferred += (count / ONE_K);
11586 			nfiles = 0;
11587 		} else {
11588 			/*
11589 			 * If fixed block mode.
11590 			 * Fixed bit in CBD should be one.
11591 			 */
11592 			ASSERT((pkt->pkt_cdbp[1] & 1) == 1);
11593 			nblks = (count / un->un_bsize);
11594 			un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
11595 			nfiles = 0;
11596 		}
11597 		/*
11598 		 * So its possable to read some blocks and hit a filemark.
11599 		 * Example reading in fixed block mode where more then one
11600 		 * block at a time is requested. In this case because the
11601 		 * filemark is hit something less then the requesed number
11602 		 * of blocks is read.
11603 		 */
11604 		if (un->un_pos.eof == ST_EOF_PENDING && bp->b_resid) {
11605 			nfiles = 1;
11606 		}
11607 	} else {
11608 		nblks = 0;
11609 		nfiles = count;
11610 	}
11611 
11612 	/*
11613 	 * If some command failed after this one started and it seems
11614 	 * to have finshed without error count the position.
11615 	 */
11616 	if (un->un_persistence && un->un_persist_errors) {
11617 		ASSERT(un->un_pos.pmode != invalid);
11618 	}
11619 
11620 	if (attrib->chg_tape_direction == DIR_FORW) {
11621 		un->un_pos.blkno += nblks;
11622 		un->un_pos.lgclblkno += nblks;
11623 		un->un_pos.lgclblkno += nfiles;
11624 	} else if (attrib->chg_tape_direction == DIR_REVC) {
11625 		un->un_pos.blkno -= nblks;
11626 		un->un_pos.lgclblkno -= nblks;
11627 		un->un_pos.lgclblkno -= nfiles;
11628 	} else {
11629 		ASSERT(0);
11630 	}
11631 
11632 	/* recovery disabled */
11633 	if (ri == NULL) {
11634 		un->un_running.pmode = invalid;
11635 		return;
11636 	}
11637 
11638 	/*
11639 	 * If we didn't just read a filemark.
11640 	 */
11641 	if (un->un_pos.eof != ST_EOF_PENDING) {
11642 		ASSERT(nblks != 0 && nfiles == 0);
11643 		/*
11644 		 * If Previously calulated expected position does not match
11645 		 * debug the expected position.
11646 		 */
11647 		if ((ri->pos.pmode != invalid) && nblks &&
11648 		    ((un->un_pos.blkno != ri->pos.blkno) ||
11649 		    (un->un_pos.lgclblkno != ri->pos.lgclblkno))) {
11650 #ifdef STDEBUG
11651 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11652 			    "Expected", &ri->pos);
11653 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11654 			    "But Got", &un->un_pos);
11655 #endif
11656 			un->un_running.pmode = invalid;
11657 		}
11658 	} else {
11659 		ASSERT(nfiles != 0);
11660 		if (un->un_running.pmode != invalid) {
11661 			/*
11662 			 * blkno and lgclblkno already counted in
11663 			 * st_add_recovery_info_to_pkt(). Since a block was not
11664 			 * read and a filemark was.
11665 			 */
11666 			if (attrib->chg_tape_direction == DIR_FORW) {
11667 				un->un_running.fileno++;
11668 				un->un_running.blkno = 0;
11669 			} else if (attrib->chg_tape_direction == DIR_REVC) {
11670 				un->un_running.fileno--;
11671 				un->un_running.blkno = LASTBLK;
11672 			}
11673 		}
11674 	}
11675 }
11676 
11677 static void
11678 st_set_state(struct scsi_tape *un, struct buf *bp)
11679 {
11680 	struct scsi_pkt *sp = BP_PKT(bp);
11681 	struct uscsi_cmd *ucmd;
11682 
11683 	ST_FUNC(ST_DEVINFO, st_set_state);
11684 
11685 	ASSERT(mutex_owned(ST_MUTEX));
11686 	ASSERT(bp != un->un_recov_buf);
11687 
11688 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11689 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
11690 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
11691 
11692 	if (bp != un->un_sbufp) {
11693 #ifdef STDEBUG
11694 		if (DEBUGGING && sp->pkt_resid) {
11695 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11696 			    "pkt_resid %ld bcount %ld\n",
11697 			    sp->pkt_resid, bp->b_bcount);
11698 		}
11699 #endif
11700 		bp->b_resid = sp->pkt_resid;
11701 		if (geterror(bp) != EIO) {
11702 			st_calc_bnum(un, bp, sp);
11703 		}
11704 		if (bp->b_flags & B_READ) {
11705 			un->un_lastop = ST_OP_READ;
11706 			un->un_fmneeded = 0;
11707 		} else {
11708 			un->un_lastop = ST_OP_WRITE;
11709 			if (un->un_dp->options & ST_REEL) {
11710 				un->un_fmneeded = 2;
11711 			} else {
11712 				un->un_fmneeded = 1;
11713 			}
11714 		}
11715 		/*
11716 		 * all is honky dory at this point, so let's
11717 		 * readjust the throttle, to increase speed, if we
11718 		 * have not throttled down.
11719 		 */
11720 		if (un->un_throttle) {
11721 			un->un_throttle = un->un_max_throttle;
11722 		}
11723 	} else {
11724 		optype new_lastop = ST_OP_NIL;
11725 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
11726 
11727 		switch (cmd) {
11728 		case SCMD_WRITE:
11729 		case SCMD_WRITE_G4:
11730 			bp->b_resid = sp->pkt_resid;
11731 			new_lastop = ST_OP_WRITE;
11732 			if (geterror(bp) == EIO) {
11733 				break;
11734 			}
11735 			st_calc_bnum(un, bp, sp);
11736 			if (un->un_dp->options & ST_REEL) {
11737 				un->un_fmneeded = 2;
11738 			} else {
11739 				un->un_fmneeded = 1;
11740 			}
11741 			break;
11742 		case SCMD_READ:
11743 		case SCMD_READ_G4:
11744 			bp->b_resid = sp->pkt_resid;
11745 			new_lastop = ST_OP_READ;
11746 			un->un_lastop = ST_OP_READ;
11747 			if (geterror(bp) == EIO) {
11748 				break;
11749 			}
11750 			st_calc_bnum(un, bp, sp);
11751 			un->un_fmneeded = 0;
11752 			break;
11753 		case SCMD_WRITE_FILE_MARK_G4:
11754 		case SCMD_WRITE_FILE_MARK:
11755 		{
11756 			int fmdone;
11757 
11758 			if (un->un_pos.eof != ST_EOM) {
11759 				un->un_pos.eof = ST_NO_EOF;
11760 			}
11761 			fmdone = (bp->b_bcount - bp->b_resid);
11762 			if (fmdone > 0) {
11763 				un->un_lastop = new_lastop = ST_OP_WEOF;
11764 				un->un_pos.lgclblkno += fmdone;
11765 				un->un_pos.fileno += fmdone;
11766 				un->un_pos.blkno = 0;
11767 			} else {
11768 				new_lastop = ST_OP_CTL;
11769 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11770 				    "Flushed buffer\n");
11771 			}
11772 			if (fmdone > un->un_fmneeded) {
11773 				un->un_fmneeded = 0;
11774 			} else {
11775 				un->un_fmneeded -= fmdone;
11776 			}
11777 			break;
11778 		}
11779 		case SCMD_REWIND:
11780 			un->un_pos.eof = ST_NO_EOF;
11781 			un->un_pos.fileno = 0;
11782 			un->un_pos.blkno = 0;
11783 			un->un_pos.lgclblkno = 0;
11784 			if (un->un_pos.pmode != legacy)
11785 				un->un_pos.pmode = legacy;
11786 			new_lastop = ST_OP_CTL;
11787 			un->un_restore_pos = 0;
11788 			break;
11789 
11790 		case SCMD_SPACE:
11791 		case SCMD_SPACE_G4:
11792 		{
11793 			int64_t count;
11794 			int64_t resid;
11795 			int64_t done;
11796 			cmd_attribute const *attrib;
11797 			recov_info *ri = sp->pkt_private;
11798 
11799 			if (ri->privatelen == sizeof (recov_info)) {
11800 				attrib = ri->cmd_attrib;
11801 			} else {
11802 				attrib =
11803 				    st_lookup_cmd_attribute(sp->pkt_cdbp[0]);
11804 			}
11805 
11806 			resid = (int64_t)SPACE_CNT(bp->b_resid);
11807 			count = (int64_t)attrib->get_cnt(sp->pkt_cdbp);
11808 
11809 			if (count >= 0) {
11810 				done = (count - resid);
11811 			} else {
11812 				done = ((-count) - resid);
11813 			}
11814 			if (done > 0) {
11815 				un->un_lastop = new_lastop = ST_OP_CTL;
11816 			} else {
11817 				new_lastop = ST_OP_CTL;
11818 			}
11819 
11820 			ST_SPAC(ST_DEVINFO, st_label, CE_WARN,
11821 			    "space cmd: cdb[1] = %s\n"
11822 			    "space data:       = 0x%lx\n"
11823 			    "space count:      = %"PRId64"\n"
11824 			    "space resid:      = %"PRId64"\n"
11825 			    "spaces done:      = %"PRId64"\n"
11826 			    "fileno before     = %d\n"
11827 			    "blkno before      = %d\n",
11828 			    space_strs[sp->pkt_cdbp[1] & 7],
11829 			    bp->b_bcount,
11830 			    count, resid, done,
11831 			    un->un_pos.fileno, un->un_pos.blkno);
11832 
11833 			switch (sp->pkt_cdbp[1]) {
11834 			case SPACE_TYPE(SP_FLM):
11835 				/* Space file forward */
11836 				if (count >= 0) {
11837 					if (un->un_pos.eof <= ST_EOF) {
11838 						un->un_pos.eof = ST_NO_EOF;
11839 					}
11840 					un->un_pos.fileno += done;
11841 					un->un_pos.blkno = 0;
11842 					break;
11843 				}
11844 				/* Space file backward */
11845 				if (done > un->un_pos.fileno) {
11846 					un->un_pos.fileno = 0;
11847 					un->un_pos.blkno = 0;
11848 				} else {
11849 					un->un_pos.fileno -= done;
11850 					un->un_pos.blkno = LASTBLK;
11851 					un->un_running.pmode = invalid;
11852 				}
11853 				break;
11854 			case SPACE_TYPE(SP_BLK):
11855 				/* Space block forward */
11856 				if (count >= 0) {
11857 					un->un_pos.blkno += done;
11858 					break;
11859 				}
11860 				/* Space block backward */
11861 				if (un->un_pos.eof >= ST_EOF_PENDING) {
11862 				/*
11863 				 * we stepped back into
11864 				 * a previous file; we are not
11865 				 * making an effort to pretend that
11866 				 * we are still in the current file
11867 				 * ie. logical == physical position
11868 				 * and leave it to st_ioctl to correct
11869 				 */
11870 					if (done > un->un_pos.blkno) {
11871 						un->un_pos.blkno = 0;
11872 					} else {
11873 						un->un_pos.fileno--;
11874 						un->un_pos.blkno = LASTBLK;
11875 						un->un_running.pmode = invalid;
11876 					}
11877 				} else {
11878 					un->un_pos.blkno -= done;
11879 				}
11880 				break;
11881 			case SPACE_TYPE(SP_SQFLM):
11882 				un->un_pos.pmode = logical;
11883 				un->un_pos.blkno = 0;
11884 				un->un_lastop = new_lastop = ST_OP_CTL;
11885 				break;
11886 			case SPACE_TYPE(SP_EOD):
11887 				un->un_pos.pmode = logical;
11888 				un->un_pos.eof = ST_EOM;
11889 				un->un_status = KEY_BLANK_CHECK;
11890 				break;
11891 			default:
11892 				un->un_pos.pmode = invalid;
11893 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11894 				    "Unsupported space cmd: %s\n",
11895 				    space_strs[sp->pkt_cdbp[1] & 7]);
11896 
11897 				un->un_lastop = new_lastop = ST_OP_CTL;
11898 			}
11899 
11900 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11901 			    "after_space rs %"PRId64" fil %d blk %d\n",
11902 			    resid, un->un_pos.fileno, un->un_pos.blkno);
11903 
11904 			break;
11905 		}
11906 		case SCMD_LOAD:
11907 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
11908 				un->un_pos.fileno = 0;
11909 				if (un->un_pos.pmode != legacy)
11910 					un->un_pos.pmode = legacy;
11911 			} else {
11912 				un->un_state = ST_STATE_OFFLINE;
11913 				un->un_pos.pmode = invalid;
11914 
11915 			}
11916 			/*
11917 			 * If we are loading or unloading we expect the media id
11918 			 * to change. Lets make it unknown.
11919 			 */
11920 			if (un->un_media_id != bogusID && un->un_media_id_len) {
11921 				kmem_free(un->un_media_id, un->un_media_id_len);
11922 				un->un_media_id = NULL;
11923 				un->un_media_id_len = 0;
11924 			}
11925 			un->un_density_known = 0;
11926 			un->un_pos.eof = ST_NO_EOF;
11927 			un->un_pos.blkno = 0;
11928 			un->un_lastop = new_lastop = ST_OP_CTL;
11929 			break;
11930 		case SCMD_ERASE:
11931 			un->un_pos.eof = ST_NO_EOF;
11932 			un->un_pos.blkno = 0;
11933 			un->un_pos.fileno = 0;
11934 			un->un_pos.lgclblkno = 0;
11935 			if (un->un_pos.pmode != legacy)
11936 				un->un_pos.pmode = legacy;
11937 			new_lastop = ST_OP_CTL;
11938 			break;
11939 		case SCMD_RESERVE:
11940 			un->un_rsvd_status |= ST_RESERVE;
11941 			un->un_rsvd_status &=
11942 			    ~(ST_RELEASE | ST_LOST_RESERVE |
11943 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11944 			new_lastop = ST_OP_CTL;
11945 			break;
11946 		case SCMD_RELEASE:
11947 			un->un_rsvd_status |= ST_RELEASE;
11948 			un->un_rsvd_status &=
11949 			    ~(ST_RESERVE | ST_LOST_RESERVE |
11950 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11951 			new_lastop = ST_OP_CTL;
11952 			break;
11953 		case SCMD_PERSISTENT_RESERVE_IN:
11954 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11955 			    "PGR_IN command\n");
11956 			new_lastop = ST_OP_CTL;
11957 			break;
11958 		case SCMD_PERSISTENT_RESERVE_OUT:
11959 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
11960 			case ST_SA_SCSI3_RESERVE:
11961 			case ST_SA_SCSI3_PREEMPT:
11962 			case ST_SA_SCSI3_PREEMPTANDABORT:
11963 				un->un_rsvd_status |=
11964 				    (ST_APPLICATION_RESERVATIONS | ST_RESERVE);
11965 				un->un_rsvd_status &= ~(ST_RELEASE |
11966 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11967 				    ST_INITIATED_RESET);
11968 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11969 				    "PGR Reserve and set: entering"
11970 				    " ST_APPLICATION_RESERVATIONS mode");
11971 				break;
11972 			case ST_SA_SCSI3_REGISTER:
11973 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11974 				    "PGR Reserve register key");
11975 				un->un_rsvd_status |= ST_INIT_RESERVE;
11976 				break;
11977 			case ST_SA_SCSI3_CLEAR:
11978 				un->un_rsvd_status &= ~ST_INIT_RESERVE;
11979 				/* FALLTHROUGH */
11980 			case ST_SA_SCSI3_RELEASE:
11981 				un->un_rsvd_status &=
11982 				    ~(ST_APPLICATION_RESERVATIONS | ST_RESERVE |
11983 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11984 				    ST_INITIATED_RESET);
11985 				un->un_rsvd_status |= ST_RELEASE;
11986 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11987 				    "PGR Release and reset: exiting"
11988 				    " ST_APPLICATION_RESERVATIONS mode");
11989 				break;
11990 			}
11991 			new_lastop = ST_OP_CTL;
11992 			break;
11993 		case SCMD_TEST_UNIT_READY:
11994 		case SCMD_READ_BLKLIM:
11995 		case SCMD_REQUEST_SENSE:
11996 		case SCMD_INQUIRY:
11997 		case SCMD_RECOVER_BUF:
11998 		case SCMD_MODE_SELECT:
11999 		case SCMD_MODE_SENSE:
12000 		case SCMD_DOORLOCK:
12001 		case SCMD_READ_BUFFER:
12002 		case SCMD_REPORT_DENSITIES:
12003 		case SCMD_LOG_SELECT_G1:
12004 		case SCMD_LOG_SENSE_G1:
12005 		case SCMD_REPORT_LUNS:
12006 		case SCMD_READ_ATTRIBUTE:
12007 		case SCMD_WRITE_ATTRIBUTE:
12008 		case SCMD_SVC_ACTION_IN_G5:
12009 		case SCMD_SECURITY_PROTO_IN:
12010 		case SCMD_SECURITY_PROTO_OUT:
12011 			new_lastop = ST_OP_CTL;
12012 			break;
12013 		case SCMD_READ_POSITION:
12014 			new_lastop = ST_OP_CTL;
12015 			/*
12016 			 * Only if the buf used was un_sbufp.
12017 			 * Among other things the prevents read positions used
12018 			 * as part of error recovery from messing up our
12019 			 * current position as they will use un_recov_buf.
12020 			 */
12021 			if (USCSI_CMD(bp)) {
12022 				(void) st_get_read_pos(un, bp);
12023 			}
12024 			break;
12025 		case SCMD_LOCATE:
12026 		case SCMD_LOCATE_G4:
12027 			/* Locate makes position mode no longer legacy */
12028 			un->un_lastop = new_lastop = ST_OP_CTL;
12029 			break;
12030 		case SCMD_MAINTENANCE_IN:
12031 			switch (sp->pkt_cdbp[1]) {
12032 			case SSVC_ACTION_GET_SUPPORTED_OPERATIONS:
12033 			case SSVC_ACTION_SET_TARGET_PORT_GROUPS:
12034 				new_lastop = ST_OP_CTL;
12035 				break;
12036 			}
12037 			if (new_lastop != ST_OP_NIL) {
12038 				break;
12039 			}
12040 		default:
12041 			/*
12042 			 * Unknown command, If was USCSI and USCSI_SILENT
12043 			 * flag was not set, set position to unknown.
12044 			 */
12045 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
12046 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
12047 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
12048 				    "unknown cmd 0x%X caused loss of state\n",
12049 				    cmd);
12050 			} else {
12051 				/*
12052 				 * keep the old agreement to allow unknown
12053 				 * commands with the USCSI_SILENT set.
12054 				 * This prevents ASSERT below.
12055 				 */
12056 				new_lastop = ST_OP_CTL;
12057 				break;
12058 			}
12059 			/* FALLTHROUGH */
12060 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
12061 			un->un_pos.pmode = invalid;
12062 			un->un_lastop = new_lastop = ST_OP_CTL;
12063 			break;
12064 		}
12065 
12066 		/* new_lastop should have been changed */
12067 		ASSERT(new_lastop != ST_OP_NIL);
12068 
12069 		/* If un_lastop should copy new_lastop  */
12070 		if (((un->un_lastop == ST_OP_WRITE) ||
12071 		    (un->un_lastop == ST_OP_WEOF)) &&
12072 		    new_lastop != ST_OP_CTL) {
12073 			un->un_lastop = new_lastop;
12074 		}
12075 	}
12076 
12077 	/*
12078 	 * In the st driver we have a logical and physical file position.
12079 	 * Under BSD behavior, when you get a zero read, the logical position
12080 	 * is before the filemark but after the last record of the file.
12081 	 * The physical position is after the filemark. MTIOCGET should always
12082 	 * return the logical file position.
12083 	 *
12084 	 * The next read gives a silent skip to the next file.
12085 	 * Under SVR4, the logical file position remains before the filemark
12086 	 * until the file is closed or a space operation is performed.
12087 	 * Hence set err_resid and err_file before changing fileno if case
12088 	 * BSD Behaviour.
12089 	 */
12090 	un->un_err_resid = bp->b_resid;
12091 	COPY_POS(&un->un_err_pos, &un->un_pos);
12092 
12093 
12094 	/*
12095 	 * If we've seen a filemark via the last read operation
12096 	 * advance the file counter, but mark things such that
12097 	 * the next read operation gets a zero count. We have
12098 	 * to put this here to handle the case of sitting right
12099 	 * at the end of a tape file having seen the file mark,
12100 	 * but the tape is closed and then re-opened without
12101 	 * any further i/o. That is, the position information
12102 	 * must be updated before a close.
12103 	 */
12104 
12105 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
12106 		/*
12107 		 * If we're a 1/2" tape, and we get a filemark
12108 		 * right on block 0, *AND* we were not in the
12109 		 * first file on the tape, and we've hit logical EOM.
12110 		 * We'll mark the state so that later we do the
12111 		 * right thing (in st_close(), st_strategy() or
12112 		 * st_ioctl()).
12113 		 *
12114 		 */
12115 		if ((un->un_dp->options & ST_REEL) &&
12116 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
12117 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
12118 			un->un_pos.eof = ST_EOT_PENDING;
12119 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12120 			    "eot pending\n");
12121 			un->un_pos.fileno++;
12122 			un->un_pos.blkno = 0;
12123 		} else if (BP_UCMD(bp)) {
12124 			/*
12125 			 * Uscsi reads have no concept of Berkley ver System IV.
12126 			 * Counts here must match raw device.
12127 			 * A non-full resid implies fix block mode where an
12128 			 * attempt to read X blocks resulted in less then X.
12129 			 */
12130 			if (bp->b_resid != bp->b_bcount) {
12131 				un->un_pos.eof = ST_EOF;
12132 			} else {
12133 				/* Read over a file mark */
12134 				un->un_pos.fileno++;
12135 				/* logical block is counted up elsewhere */
12136 				/* we're before the first block in next file */
12137 				un->un_pos.blkno = 0;
12138 				/* EOF is no longer pending */
12139 				un->un_pos.eof = ST_NO_EOF;
12140 			}
12141 		} else if (BSD_BEHAVIOR) {
12142 			/*
12143 			 * If the read of the filemark was a side effect
12144 			 * of reading some blocks (i.e., data was actually
12145 			 * read), then the EOF mark is pending and the
12146 			 * bump into the next file awaits the next read
12147 			 * operation (which will return a zero count), or
12148 			 * a close or a space operation, else the bump
12149 			 * into the next file occurs now.
12150 			 */
12151 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12152 			    "resid=%lx, bcount=%lx\n",
12153 			    bp->b_resid, bp->b_bcount);
12154 
12155 			if (bp->b_resid != bp->b_bcount) {
12156 				un->un_pos.eof = ST_EOF;
12157 			} else {
12158 				un->un_silent_skip = 1;
12159 				un->un_pos.eof = ST_NO_EOF;
12160 				un->un_pos.fileno++;
12161 				un->un_pos.lgclblkno++;
12162 				un->un_save_blkno = un->un_pos.blkno;
12163 				un->un_pos.blkno = 0;
12164 			}
12165 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12166 			    "eof of file %d, eof=%d\n",
12167 			    un->un_pos.fileno, un->un_pos.eof);
12168 		} else if (SVR4_BEHAVIOR) {
12169 			/*
12170 			 * If the read of the filemark was a side effect
12171 			 * of reading some blocks (i.e., data was actually
12172 			 * read), then the next read should return 0
12173 			 */
12174 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12175 			    "resid=%lx, bcount=%lx\n",
12176 			    bp->b_resid, bp->b_bcount);
12177 			if (bp->b_resid == bp->b_bcount) {
12178 				un->un_pos.eof = ST_EOF;
12179 			}
12180 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12181 			    "eof of file=%d, eof=%d\n",
12182 			    un->un_pos.fileno, un->un_pos.eof);
12183 		}
12184 	}
12185 }
12186 
12187 /*
12188  * set the correct un_errno, to take corner cases into consideration
12189  */
12190 static void
12191 st_set_pe_errno(struct scsi_tape *un)
12192 {
12193 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
12194 
12195 	ASSERT(mutex_owned(ST_MUTEX));
12196 
12197 	/* if errno is already set, don't reset it */
12198 	if (un->un_errno)
12199 		return;
12200 
12201 	/* here un_errno == 0 */
12202 	/*
12203 	 * if the last transfer before flushing all the
12204 	 * waiting I/O's, was 0 (resid = count), then we
12205 	 * want to give the user an error on all the rest,
12206 	 * so here.  If there was a transfer, we set the
12207 	 * resid and counts to 0, and let it drop through,
12208 	 * giving a zero return.  the next I/O will then
12209 	 * give an error.
12210 	 */
12211 	if (un->un_last_resid == un->un_last_count) {
12212 		switch (un->un_pos.eof) {
12213 		case ST_EOM:
12214 			un->un_errno = ENOMEM;
12215 			break;
12216 		case ST_EOT:
12217 		case ST_EOF:
12218 			un->un_errno = EIO;
12219 			break;
12220 		}
12221 	} else {
12222 		/*
12223 		 * we know they did not have a zero, so make
12224 		 * sure they get one
12225 		 */
12226 		un->un_last_resid = un->un_last_count = 0;
12227 	}
12228 }
12229 
12230 
12231 /*
12232  * send in a marker pkt to terminate flushing of commands by BBA (via
12233  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
12234  */
12235 static void
12236 st_hba_unflush(struct scsi_tape *un)
12237 {
12238 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
12239 
12240 	ASSERT(mutex_owned(ST_MUTEX));
12241 
12242 	if (!un->un_flush_on_errors)
12243 		return;
12244 
12245 #ifdef FLUSH_ON_ERRORS
12246 
12247 	if (!un->un_mkr_pkt) {
12248 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
12249 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
12250 
12251 		/* we slept, so it must be there */
12252 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
12253 	}
12254 
12255 	st_transport(un, un->un_mkr_pkt);
12256 #endif
12257 }
12258 
12259 static char *
12260 st_print_scsi_cmd(char cmd)
12261 {
12262 	char tmp[64];
12263 	char *cpnt;
12264 
12265 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
12266 	/* tmp goes out of scope on return and caller sees garbage */
12267 	if (cpnt == tmp) {
12268 		cpnt = "Unknown Command";
12269 	}
12270 	return (cpnt);
12271 }
12272 
12273 static void
12274 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
12275     char *title, char *cdb)
12276 {
12277 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
12278 	char buf[256];
12279 	struct scsi_tape *un;
12280 	int instance = ddi_get_instance(dip);
12281 
12282 	un = ddi_get_soft_state(st_state, instance);
12283 
12284 	ST_FUNC(dip, st_print_cdb);
12285 
12286 	/* force one line output so repeated commands are printed once */
12287 	if ((st_debug & 0x180) == 0x100) {
12288 		scsi_log(dip, label, level, "node %s cmd %s\n",
12289 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
12290 		return;
12291 	}
12292 
12293 	/* force one line output so repeated CDB's are printed once */
12294 	if ((st_debug & 0x180) == 0x80) {
12295 		st_clean_print(dip, label, level, NULL, cdb, len);
12296 	} else {
12297 		(void) sprintf(buf, "%s for cmd(%s)", title,
12298 		    st_print_scsi_cmd(*cdb));
12299 		st_clean_print(dip, label, level, buf, cdb, len);
12300 	}
12301 }
12302 
12303 static void
12304 st_clean_print(dev_info_t *dev, char *label, uint_t level,
12305     char *title, char *data, int len)
12306 {
12307 	int	i;
12308 	int 	c;
12309 	char	*format;
12310 	char	buf[256];
12311 	uchar_t	byte;
12312 
12313 	ST_FUNC(dev, st_clean_print);
12314 
12315 
12316 	if (title) {
12317 		(void) sprintf(buf, "%s:\n", title);
12318 		scsi_log(dev, label, level, "%s", buf);
12319 		level = CE_CONT;
12320 	}
12321 
12322 	for (i = 0; i < len; ) {
12323 		buf[0] = 0;
12324 		for (c = 0; c < 8 && i < len; c++, i++) {
12325 			byte = (uchar_t)data[i];
12326 			if (byte < 0x10)
12327 				format = "0x0%x ";
12328 			else
12329 				format = "0x%x ";
12330 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
12331 		}
12332 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
12333 
12334 		scsi_log(dev, label, level, "%s\n", buf);
12335 		level = CE_CONT;
12336 	}
12337 }
12338 
12339 /*
12340  * Conditionally enabled debugging
12341  */
12342 #ifdef	STDEBUG
12343 static void
12344 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
12345 {
12346 	char tmpbuf[64];
12347 
12348 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
12349 
12350 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12351 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
12352 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
12353 	    count, count,
12354 	    wait == ASYNC_CMD ? "a" : "");
12355 }
12356 #endif	/* STDEBUG */
12357 
12358 /*
12359  * Returns pointer to name of minor node name of device 'dev'.
12360  */
12361 static char *
12362 st_dev_name(dev_t dev)
12363 {
12364 	struct scsi_tape *un;
12365 	const char density[] = { 'l', 'm', 'h', 'c' };
12366 	static char name[32];
12367 	minor_t minor;
12368 	int instance;
12369 	int nprt = 0;
12370 
12371 	minor = getminor(dev);
12372 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
12373 	un = ddi_get_soft_state(st_state, instance);
12374 	if (un) {
12375 		ST_FUNC(ST_DEVINFO, st_dev_name);
12376 	}
12377 
12378 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
12379 
12380 	if (minor & MT_BSD) {
12381 		name[++nprt] = 'b';
12382 	}
12383 
12384 	if (minor & MT_NOREWIND) {
12385 		name[++nprt] = 'n';
12386 	}
12387 
12388 	/* NULL terminator */
12389 	name[++nprt] = 0;
12390 
12391 	return (name);
12392 }
12393 
12394 /*
12395  * Soft error reporting, so far unique to each drive
12396  *
12397  * Currently supported: exabyte and DAT soft error reporting
12398  */
12399 static int
12400 st_report_exabyte_soft_errors(dev_t dev, int flag)
12401 {
12402 	uchar_t *sensep;
12403 	int amt;
12404 	int rval = 0;
12405 	char cdb[CDB_GROUP0], *c = cdb;
12406 	struct uscsi_cmd *com;
12407 
12408 	GET_SOFT_STATE(dev);
12409 
12410 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
12411 
12412 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12413 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
12414 	    dev, flag);
12415 
12416 	ASSERT(mutex_owned(ST_MUTEX));
12417 
12418 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12419 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
12420 
12421 	*c++ = SCMD_REQUEST_SENSE;
12422 	*c++ = 0;
12423 	*c++ = 0;
12424 	*c++ = 0;
12425 	*c++ = TAPE_SENSE_LENGTH;
12426 	/*
12427 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
12428 	 */
12429 	*c   = (char)0x80;
12430 
12431 	com->uscsi_cdb = cdb;
12432 	com->uscsi_cdblen = CDB_GROUP0;
12433 	com->uscsi_bufaddr = (caddr_t)sensep;
12434 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
12435 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12436 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12437 
12438 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12439 	if (rval || com->uscsi_status) {
12440 		goto done;
12441 	}
12442 
12443 	/*
12444 	 * was there enough data?
12445 	 */
12446 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
12447 
12448 	if ((amt >= 19) && un->un_kbytes_xferred) {
12449 		uint_t count, error_rate;
12450 		uint_t rate;
12451 
12452 		if (sensep[21] & CLN) {
12453 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12454 			    "Periodic head cleaning required");
12455 		}
12456 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
12457 			goto done;
12458 		}
12459 		/*
12460 		 * check if soft error reporting needs to be done.
12461 		 */
12462 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
12463 		count &= 0xffffff;
12464 		error_rate = (count * 100)/un->un_kbytes_xferred;
12465 
12466 #ifdef	STDEBUG
12467 		if (st_soft_error_report_debug) {
12468 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12469 			    "Exabyte Soft Error Report:\n");
12470 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12471 			    "read/write error counter: %d\n", count);
12472 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12473 			    "number of bytes transferred: %dK\n",
12474 			    un->un_kbytes_xferred);
12475 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12476 			    "error_rate: %d%%\n", error_rate);
12477 
12478 			if (amt >= 22) {
12479 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12480 				    "unit sense: 0x%b 0x%b 0x%b\n",
12481 				    sensep[19], SENSE_19_BITS,
12482 				    sensep[20], SENSE_20_BITS,
12483 				    sensep[21], SENSE_21_BITS);
12484 			}
12485 			if (amt >= 27) {
12486 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12487 				    "tracking retry counter: %d\n",
12488 				    sensep[26]);
12489 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12490 				    "read/write retry counter: %d\n",
12491 				    sensep[27]);
12492 			}
12493 		}
12494 #endif
12495 
12496 		if (flag & FWRITE) {
12497 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
12498 		} else {
12499 			rate = EXABYTE_READ_ERROR_THRESHOLD;
12500 		}
12501 		if (error_rate >= rate) {
12502 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12503 			    "Soft error rate (%d%%) during %s was too high",
12504 			    error_rate,
12505 			    ((flag & FWRITE) ? wrg_str : rdg_str));
12506 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12507 			    "Please, replace tape cartridge\n");
12508 		}
12509 	}
12510 
12511 done:
12512 	kmem_free(com, sizeof (*com));
12513 	kmem_free(sensep, TAPE_SENSE_LENGTH);
12514 
12515 	if (rval != 0) {
12516 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12517 		    "exabyte soft error reporting failed\n");
12518 	}
12519 	return (rval);
12520 }
12521 
12522 /*
12523  * this is very specific to Archive 4mm dat
12524  */
12525 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
12526 
12527 static int
12528 st_report_dat_soft_errors(dev_t dev, int flag)
12529 {
12530 	uchar_t *sensep;
12531 	int amt, i;
12532 	int rval = 0;
12533 	char cdb[CDB_GROUP1], *c = cdb;
12534 	struct uscsi_cmd *com;
12535 	struct scsi_arq_status status;
12536 
12537 	GET_SOFT_STATE(dev);
12538 
12539 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
12540 
12541 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12542 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12543 
12544 	ASSERT(mutex_owned(ST_MUTEX));
12545 
12546 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12547 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12548 
12549 	*c++ = SCMD_LOG_SENSE_G1;
12550 	*c++ = 0;
12551 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
12552 	*c++ = 0;
12553 	*c++ = 0;
12554 	*c++ = 0;
12555 	*c++ = 2;
12556 	*c++ = 0;
12557 	*c++ = (char)LOG_SENSE_LENGTH;
12558 	*c   = 0;
12559 	com->uscsi_cdb    = cdb;
12560 	com->uscsi_cdblen  = CDB_GROUP1;
12561 	com->uscsi_bufaddr = (caddr_t)sensep;
12562 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
12563 	com->uscsi_rqlen = sizeof (status);
12564 	com->uscsi_rqbuf = (caddr_t)&status;
12565 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
12566 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12567 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12568 	if (rval) {
12569 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12570 		    "DAT soft error reporting failed\n");
12571 	}
12572 	if (rval || com->uscsi_status) {
12573 		goto done;
12574 	}
12575 
12576 	/*
12577 	 * was there enough data?
12578 	 */
12579 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
12580 
12581 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
12582 		int total, retries, param_code;
12583 
12584 		total = -1;
12585 		retries = -1;
12586 		amt = sensep[3] + 4;
12587 
12588 
12589 #ifdef STDEBUG
12590 		if (st_soft_error_report_debug) {
12591 			(void) printf("logsense:");
12592 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
12593 				if (i % 16 == 0) {
12594 					(void) printf("\t\n");
12595 				}
12596 				(void) printf(" %x", sensep[i]);
12597 			}
12598 			(void) printf("\n");
12599 		}
12600 #endif
12601 
12602 		/*
12603 		 * parse the param_codes
12604 		 */
12605 		if (sensep[0] == 2 || sensep[0] == 3) {
12606 			for (i = 4; i < amt; i++) {
12607 				param_code = (sensep[i++] << 8);
12608 				param_code += sensep[i++];
12609 				i++; /* skip control byte */
12610 				if (param_code == 5) {
12611 					if (sensep[i++] == 4) {
12612 						total = (sensep[i++] << 24);
12613 						total += (sensep[i++] << 16);
12614 						total += (sensep[i++] << 8);
12615 						total += sensep[i];
12616 					}
12617 				} else if (param_code == 0x8007) {
12618 					if (sensep[i++] == 2) {
12619 						retries = sensep[i++] << 8;
12620 						retries += sensep[i];
12621 					}
12622 				} else {
12623 					i += sensep[i];
12624 				}
12625 			}
12626 		}
12627 
12628 		/*
12629 		 * if the log sense returned valid numbers then determine
12630 		 * the read and write error thresholds based on the amount of
12631 		 * data transferred
12632 		 */
12633 
12634 		if (total > 0 && retries > 0) {
12635 			short normal_retries = 0;
12636 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12637 			    "total xferred (%s) =%x, retries=%x\n",
12638 			    ((flag & FWRITE) ? wrg_str : rdg_str),
12639 			    total, retries);
12640 
12641 			if (flag & FWRITE) {
12642 				if (total <=
12643 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
12644 					normal_retries =
12645 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
12646 				} else {
12647 					normal_retries =
12648 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
12649 				}
12650 			} else {
12651 				if (total <=
12652 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
12653 					normal_retries =
12654 					    DAT_SMALL_READ_ERROR_THRESHOLD;
12655 				} else {
12656 					normal_retries =
12657 					    DAT_LARGE_READ_ERROR_THRESHOLD;
12658 				}
12659 			}
12660 
12661 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12662 			"normal retries=%d\n", normal_retries);
12663 
12664 			if (retries >= normal_retries) {
12665 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12666 				    "Soft error rate (retries = %d) during "
12667 				    "%s was too high",  retries,
12668 				    ((flag & FWRITE) ? wrg_str : rdg_str));
12669 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12670 				    "Periodic head cleaning required "
12671 				    "and/or replace tape cartridge\n");
12672 			}
12673 
12674 		} else if (total == -1 || retries == -1) {
12675 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12676 			    "log sense parameter code does not make sense\n");
12677 		}
12678 	}
12679 
12680 	/*
12681 	 * reset all values
12682 	 */
12683 	c = cdb;
12684 	*c++ = SCMD_LOG_SELECT_G1;
12685 	*c++ = 2;	/* this resets all values */
12686 	*c++ = (char)0xc0;
12687 	*c++ = 0;
12688 	*c++ = 0;
12689 	*c++ = 0;
12690 	*c++ = 0;
12691 	*c++ = 0;
12692 	*c++ = 0;
12693 	*c   = 0;
12694 	com->uscsi_bufaddr = NULL;
12695 	com->uscsi_buflen  = 0;
12696 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
12697 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12698 	if (rval) {
12699 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12700 		    "DAT soft error reset failed\n");
12701 	}
12702 done:
12703 	kmem_free(com, sizeof (*com));
12704 	kmem_free(sensep, LOG_SENSE_LENGTH);
12705 	return (rval);
12706 }
12707 
12708 static int
12709 st_report_soft_errors(dev_t dev, int flag)
12710 {
12711 	GET_SOFT_STATE(dev);
12712 
12713 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
12714 
12715 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12716 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12717 
12718 	ASSERT(mutex_owned(ST_MUTEX));
12719 
12720 	switch (un->un_dp->type) {
12721 	case ST_TYPE_EXB8500:
12722 	case ST_TYPE_EXABYTE:
12723 		return (st_report_exabyte_soft_errors(dev, flag));
12724 		/*NOTREACHED*/
12725 	case ST_TYPE_PYTHON:
12726 		return (st_report_dat_soft_errors(dev, flag));
12727 		/*NOTREACHED*/
12728 	default:
12729 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
12730 		return (-1);
12731 	}
12732 }
12733 
12734 /*
12735  * persistent error routines
12736  */
12737 
12738 /*
12739  * enable persistent errors, and set the throttle appropriately, checking
12740  * for flush-on-errors capability
12741  */
12742 static void
12743 st_turn_pe_on(struct scsi_tape *un)
12744 {
12745 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
12746 
12747 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
12748 	ASSERT(mutex_owned(ST_MUTEX));
12749 
12750 	un->un_persistence = 1;
12751 
12752 	/*
12753 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
12754 	 * enabled.  This will simplify the error handling for request senses
12755 	 */
12756 
12757 	if (un->un_arq_enabled && un->un_untagged_qing) {
12758 		uchar_t f_o_e;
12759 
12760 		mutex_exit(ST_MUTEX);
12761 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
12762 		    1 : 0;
12763 		mutex_enter(ST_MUTEX);
12764 
12765 		un->un_flush_on_errors = f_o_e;
12766 	} else {
12767 		un->un_flush_on_errors = 0;
12768 	}
12769 
12770 	if (un->un_flush_on_errors)
12771 		un->un_max_throttle = (uchar_t)st_max_throttle;
12772 	else
12773 		un->un_max_throttle = 1;
12774 
12775 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
12776 		un->un_max_throttle = 1;
12777 
12778 	/* this will send a marker pkt */
12779 	st_clear_pe(un);
12780 }
12781 
12782 /*
12783  * This turns persistent errors permanently off
12784  */
12785 static void
12786 st_turn_pe_off(struct scsi_tape *un)
12787 {
12788 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
12789 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
12790 	ASSERT(mutex_owned(ST_MUTEX));
12791 
12792 	/* turn it off for good */
12793 	un->un_persistence = 0;
12794 
12795 	/* this will send a marker pkt */
12796 	st_clear_pe(un);
12797 
12798 	/* turn off flush on error capability, if enabled */
12799 	if (un->un_flush_on_errors) {
12800 		mutex_exit(ST_MUTEX);
12801 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
12802 		mutex_enter(ST_MUTEX);
12803 	}
12804 
12805 
12806 	un->un_flush_on_errors = 0;
12807 }
12808 
12809 /*
12810  * This clear persistent errors, allowing more commands through, and also
12811  * sending a marker packet.
12812  */
12813 static void
12814 st_clear_pe(struct scsi_tape *un)
12815 {
12816 	ST_FUNC(ST_DEVINFO, st_clear_pe);
12817 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
12818 	ASSERT(mutex_owned(ST_MUTEX));
12819 
12820 	un->un_persist_errors = 0;
12821 	un->un_throttle = un->un_last_throttle = 1;
12822 	un->un_errno = 0;
12823 	st_hba_unflush(un);
12824 }
12825 
12826 /*
12827  * This will flag persistent errors, shutting everything down, if the
12828  * application had enabled persistent errors via MTIOCPERSISTENT
12829  */
12830 static void
12831 st_set_pe_flag(struct scsi_tape *un)
12832 {
12833 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
12834 	ASSERT(mutex_owned(ST_MUTEX));
12835 
12836 	if (un->un_persistence) {
12837 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
12838 		un->un_persist_errors = 1;
12839 		un->un_throttle = un->un_last_throttle = 0;
12840 		cv_broadcast(&un->un_sbuf_cv);
12841 	}
12842 }
12843 
12844 static int
12845 st_do_reserve(struct scsi_tape *un)
12846 {
12847 	int rval;
12848 	int was_lost = un->un_rsvd_status & ST_LOST_RESERVE;
12849 
12850 	ST_FUNC(ST_DEVINFO, st_do_reserve);
12851 
12852 	/*
12853 	 * Issue a Throw-Away reserve command to clear the
12854 	 * check condition.
12855 	 * If the current behaviour of reserve/release is to
12856 	 * hold reservation across opens , and if a Bus reset
12857 	 * has been issued between opens then this command
12858 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
12859 	 * In this case return an EACCES so that user knows that
12860 	 * reservation has been lost in between opens.
12861 	 * If this error is not returned and we continue with
12862 	 * successful open , then user may think position of the
12863 	 * tape is still the same but inreality we would rewind the
12864 	 * tape and continue from BOT.
12865 	 */
12866 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12867 	if (rval) {
12868 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
12869 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
12870 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
12871 			un->un_errno = EACCES;
12872 			return (EACCES);
12873 		}
12874 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12875 	}
12876 	if (rval == 0) {
12877 		un->un_rsvd_status |= ST_INIT_RESERVE;
12878 	}
12879 	if (was_lost) {
12880 		un->un_running.pmode = invalid;
12881 	}
12882 
12883 	return (rval);
12884 }
12885 
12886 static int
12887 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb)
12888 {
12889 	int rval;
12890 	cmd_attribute const *attrib;
12891 
12892 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
12893 
12894 	/*
12895 	 * If already reserved no need to do it again.
12896 	 * Also if Reserve and Release are disabled Just return.
12897 	 */
12898 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12899 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12900 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12901 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12902 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
12903 		    st_print_scsi_cmd((uchar_t)cdb[0]));
12904 		return (0);
12905 	}
12906 
12907 	/* See if command is on the list */
12908 	attrib = st_lookup_cmd_attribute(cdb[0]);
12909 
12910 	if (attrib == NULL) {
12911 		rval = 1; /* Not found, when in doubt reserve */
12912 	} else if ((attrib->requires_reserve) != 0) {
12913 		rval = 1;
12914 	} else if ((attrib->reserve_byte) != 0) {
12915 		/*
12916 		 * cmd is on list.
12917 		 * if byte is zero always allowed.
12918 		 */
12919 		rval = 1;
12920 	} else if (((cdb[attrib->reserve_byte]) &
12921 	    (attrib->reserve_mask)) != 0) {
12922 		rval = 1;
12923 	} else {
12924 		rval = 0;
12925 	}
12926 
12927 	if (rval) {
12928 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12929 		    "Command %s requires reservation",
12930 		    st_print_scsi_cmd(cdb[0]));
12931 
12932 		rval = st_do_reserve(un);
12933 	}
12934 
12935 	return (rval);
12936 }
12937 
12938 static int
12939 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
12940 {
12941 	int rval;
12942 	cmd_attribute const *attrib;
12943 
12944 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
12945 
12946 	/*
12947 	 * Do not reserve when already reserved, when not supported or when
12948 	 * auto-rewinding on device closure.
12949 	 */
12950 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12951 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12952 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE) ||
12953 	    ((un->un_state == ST_STATE_CLOSING) && (cmd == SCMD_REWIND))) {
12954 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12955 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
12956 		    st_print_scsi_cmd(cmd));
12957 		return (0);
12958 	}
12959 
12960 	/* search for this command on the list */
12961 	attrib = st_lookup_cmd_attribute(cmd);
12962 
12963 	if (attrib == NULL) {
12964 		rval = 1; /* Not found, when in doubt reserve */
12965 	} else if ((attrib->requires_reserve) != 0) {
12966 		rval = 1;
12967 	} else if ((attrib->reserve_byte) != 0) {
12968 		/*
12969 		 * cmd is on list.
12970 		 * if byte is zero always allowed.
12971 		 */
12972 		rval = 1;
12973 	} else if (((attrib->reserve_mask) & cnt) != 0) {
12974 		rval = 1;
12975 	} else {
12976 		rval = 0;
12977 	}
12978 
12979 	if (rval) {
12980 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12981 		    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
12982 
12983 		rval = st_do_reserve(un);
12984 	}
12985 
12986 	return (rval);
12987 }
12988 
12989 static int
12990 st_reserve_release(struct scsi_tape *un, int cmd, ubufunc_t ubf)
12991 {
12992 	struct uscsi_cmd	uscsi_cmd;
12993 	int			rval;
12994 	char			cdb[CDB_GROUP0];
12995 	struct scsi_arq_status	stat;
12996 
12997 
12998 
12999 	ST_FUNC(ST_DEVINFO, st_reserve_release);
13000 
13001 	ASSERT(mutex_owned(ST_MUTEX));
13002 
13003 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13004 	    "st_reserve_release: %s \n",
13005 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
13006 
13007 	bzero(&cdb, CDB_GROUP0);
13008 	if (cmd == ST_RELEASE) {
13009 		cdb[0] = SCMD_RELEASE;
13010 	} else {
13011 		cdb[0] = SCMD_RESERVE;
13012 	}
13013 	bzero(&uscsi_cmd, sizeof (struct uscsi_cmd));
13014 	uscsi_cmd.uscsi_flags = USCSI_WRITE | USCSI_RQENABLE;
13015 	uscsi_cmd.uscsi_cdb = cdb;
13016 	uscsi_cmd.uscsi_cdblen = CDB_GROUP0;
13017 	uscsi_cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
13018 	uscsi_cmd.uscsi_rqbuf = (caddr_t)&stat;
13019 	uscsi_cmd.uscsi_rqlen = sizeof (stat);
13020 
13021 	rval = ubf(un, &uscsi_cmd, FKIOCTL);
13022 
13023 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13024 	    "st_reserve_release: rval(1)=%d\n", rval);
13025 
13026 	if (rval) {
13027 		if (uscsi_cmd.uscsi_status == STATUS_RESERVATION_CONFLICT) {
13028 			rval = EACCES;
13029 		}
13030 		/*
13031 		 * dynamically turn off reserve/release support
13032 		 * in case of drives which do not support
13033 		 * reserve/release command(ATAPI drives).
13034 		 */
13035 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
13036 			if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
13037 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
13038 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13039 				    "Tape unit does not support "
13040 				    "reserve/release \n");
13041 			}
13042 			rval = 0;
13043 		}
13044 	}
13045 	return (rval);
13046 }
13047 
13048 static int
13049 st_take_ownership(struct scsi_tape *un, ubufunc_t ubf)
13050 {
13051 	int rval;
13052 
13053 	ST_FUNC(ST_DEVINFO, st_take_ownership);
13054 
13055 	ASSERT(mutex_owned(ST_MUTEX));
13056 
13057 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13058 	    "st_take_ownership: Entering ...\n");
13059 
13060 
13061 	rval = st_reserve_release(un, ST_RESERVE, ubf);
13062 	/*
13063 	 * XXX -> Should reset be done only if we get EACCES.
13064 	 * .
13065 	 */
13066 	if (rval) {
13067 		if (st_reset(un, RESET_LUN) == 0) {
13068 			return (EIO);
13069 		}
13070 		un->un_rsvd_status &=
13071 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
13072 
13073 		mutex_exit(ST_MUTEX);
13074 		delay(drv_usectohz(ST_RESERVATION_DELAY));
13075 		mutex_enter(ST_MUTEX);
13076 		/*
13077 		 * remove the check condition.
13078 		 */
13079 		(void) st_reserve_release(un, ST_RESERVE, ubf);
13080 		rval = st_reserve_release(un, ST_RESERVE, ubf);
13081 		if (rval != 0) {
13082 			if ((st_reserve_release(un, ST_RESERVE, ubf))
13083 			    != 0) {
13084 				rval = (un->un_rsvd_status &
13085 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
13086 				return (rval);
13087 			}
13088 		}
13089 		/*
13090 		 * Set tape state to ST_STATE_OFFLINE , in case if
13091 		 * the user wants to continue and start using
13092 		 * the tape.
13093 		 */
13094 		un->un_state = ST_STATE_OFFLINE;
13095 		un->un_rsvd_status |= ST_INIT_RESERVE;
13096 	}
13097 	return (rval);
13098 }
13099 
13100 static int
13101 st_create_errstats(struct scsi_tape *un, int instance)
13102 {
13103 	char	kstatname[KSTAT_STRLEN];
13104 
13105 	ST_FUNC(ST_DEVINFO, st_create_errstats);
13106 
13107 	/*
13108 	 * Create device error kstats
13109 	 */
13110 
13111 	if (un->un_errstats == (kstat_t *)0) {
13112 		(void) sprintf(kstatname, "st%d,err", instance);
13113 		un->un_errstats = kstat_create("sterr", instance, kstatname,
13114 		    "device_error", KSTAT_TYPE_NAMED,
13115 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
13116 		    KSTAT_FLAG_PERSISTENT);
13117 
13118 		if (un->un_errstats) {
13119 			struct st_errstats	*stp;
13120 
13121 			stp = (struct st_errstats *)un->un_errstats->ks_data;
13122 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
13123 			    KSTAT_DATA_ULONG);
13124 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
13125 			    KSTAT_DATA_ULONG);
13126 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
13127 			    KSTAT_DATA_ULONG);
13128 			kstat_named_init(&stp->st_vid, "Vendor",
13129 			    KSTAT_DATA_CHAR);
13130 			kstat_named_init(&stp->st_pid, "Product",
13131 			    KSTAT_DATA_CHAR);
13132 			kstat_named_init(&stp->st_revision, "Revision",
13133 			    KSTAT_DATA_CHAR);
13134 			kstat_named_init(&stp->st_serial, "Serial No",
13135 			    KSTAT_DATA_CHAR);
13136 			un->un_errstats->ks_private = un;
13137 			un->un_errstats->ks_update = nulldev;
13138 			kstat_install(un->un_errstats);
13139 			/*
13140 			 * Fill in the static data
13141 			 */
13142 			(void) strncpy(&stp->st_vid.value.c[0],
13143 			    ST_INQUIRY->inq_vid, 8);
13144 			/*
13145 			 * XXX:  Emulex MT-02 (and emulators) predates
13146 			 *	 SCSI-1 and has no vid & pid inquiry data.
13147 			 */
13148 			if (ST_INQUIRY->inq_len != 0) {
13149 				(void) strncpy(&stp->st_pid.value.c[0],
13150 				    ST_INQUIRY->inq_pid, 16);
13151 				(void) strncpy(&stp->st_revision.value.c[0],
13152 				    ST_INQUIRY->inq_revision, 4);
13153 			}
13154 		}
13155 	}
13156 	return (0);
13157 }
13158 
13159 static int
13160 st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos)
13161 {
13162 	int rval;
13163 	bufunc_t bf = (ubf == st_uscsi_rcmd) ? st_rcmd : st_cmd;
13164 
13165 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
13166 
13167 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
13168 	ASSERT(mutex_owned(ST_MUTEX));
13169 
13170 	/* Can't restore an invalid position */
13171 	if (pos->pmode == invalid) {
13172 		return (4);
13173 	}
13174 
13175 	/*
13176 	 * Assumtions:
13177 	 *	If a position was read and is in logical position mode.
13178 	 *	If a drive supports read position it supports locate.
13179 	 *	If the read position type is not NO_POS. even though
13180 	 *	   a read position make not have been attemped yet.
13181 	 *
13182 	 *	The drive can locate to the position.
13183 	 */
13184 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
13185 		/*
13186 		 * If position mode is logical or legacy mode try
13187 		 * to locate there as it is faster.
13188 		 * If it fails try the old way.
13189 		 */
13190 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13191 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
13192 		    pos->lgclblkno);
13193 
13194 		if (st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
13195 		    pos->lgclblkno, pos->partition) == 0) {
13196 			/* Assume we are there copy rest of position back */
13197 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
13198 				COPY_POS(&un->un_pos, pos);
13199 			}
13200 			return (0);
13201 		}
13202 
13203 		/*
13204 		 * If logical block locate failed to restore a logical
13205 		 * position, can't recover.
13206 		 */
13207 		if (pos->pmode == logical) {
13208 			return (-1);
13209 		}
13210 	}
13211 
13212 
13213 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13214 	    "Restoring tape position at fileno=%x, blkno=%x....",
13215 	    pos->fileno, pos->blkno);
13216 
13217 	/*
13218 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
13219 	 * so as not to rewind tape on RESETS: Gee, Has life ever
13220 	 * been simple in tape land ?
13221 	 */
13222 	rval = bf(un, SCMD_REWIND, 0, SYNC_CMD);
13223 	if (rval) {
13224 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
13225 		    "Failed to restore the last file and block position: In"
13226 		    " this state, Tape will be loaded at BOT during next open");
13227 		un->un_pos.pmode = invalid;
13228 		return (rval);
13229 	}
13230 
13231 	/* If the position was as the result of back space file */
13232 	if (pos->blkno > (INF / 2)) {
13233 		/* Go one extra file forward */
13234 		pos->fileno++;
13235 		/* Figure how many blocks to back into the previous file */
13236 		pos->blkno = -(INF - pos->blkno);
13237 	}
13238 
13239 	/* Go to requested fileno */
13240 	if (pos->fileno) {
13241 		rval = st_cmd(un, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
13242 		if (rval) {
13243 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13244 			    "Failed to restore the last file position: In this "
13245 			    " state, Tape will be loaded at BOT during next"
13246 			    " open %d", __LINE__);
13247 			un->un_pos.pmode = invalid;
13248 			pos->pmode = invalid;
13249 			return (rval);
13250 		}
13251 	}
13252 
13253 	/*
13254 	 * If backing into a file we already did an extra file forward.
13255 	 * Now we have to back over the filemark to get to the end of
13256 	 * the previous file. The blkno has been ajusted to a negative
13257 	 * value so we will get to the expected location.
13258 	 */
13259 	if (pos->blkno) {
13260 		rval = bf(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
13261 		if (rval) {
13262 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13263 			    "Failed to restore the last file position: In this "
13264 			    " state, Tape will be loaded at BOT during next"
13265 			    " open %d", __LINE__);
13266 			un->un_pos.pmode = invalid;
13267 			pos->pmode = invalid;
13268 			return (rval);
13269 		}
13270 	}
13271 
13272 	/*
13273 	 * The position mode, block and fileno should be correct,
13274 	 * This updates eof and logical position information.
13275 	 */
13276 	un->un_pos.eof = pos->eof;
13277 	un->un_pos.lgclblkno = pos->lgclblkno;
13278 
13279 	return (0);
13280 }
13281 
13282 /*
13283  * check sense key, ASC, ASCQ in order to determine if the tape needs
13284  * to be ejected
13285  */
13286 
13287 static int
13288 st_check_asc_ascq(struct scsi_tape *un)
13289 {
13290 	struct scsi_extended_sense *sensep = ST_RQSENSE;
13291 	struct tape_failure_code   *code;
13292 
13293 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
13294 
13295 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
13296 		if ((code->key  == sensep->es_key) &&
13297 		    (code->add_code  == sensep->es_add_code) &&
13298 		    (code->qual_code == sensep->es_qual_code))
13299 			return (1);
13300 	}
13301 	return (0);
13302 }
13303 
13304 /*
13305  * st_logpage_supported() sends a Log Sense command with
13306  * page code = 0 = Supported Log Pages Page to the device,
13307  * to see whether the page 'page' is supported.
13308  * Return values are:
13309  * -1 if the Log Sense command fails
13310  * 0 if page is not supported
13311  * 1 if page is supported
13312  */
13313 
13314 static int
13315 st_logpage_supported(struct scsi_tape *un, uchar_t page)
13316 {
13317 	uchar_t *sp, *sensep;
13318 	unsigned length;
13319 	struct uscsi_cmd *com;
13320 	struct scsi_arq_status status;
13321 	int rval;
13322 	char cdb[CDB_GROUP1] = {
13323 		SCMD_LOG_SENSE_G1,
13324 		0,
13325 		SUPPORTED_LOG_PAGES_PAGE,
13326 		0,
13327 		0,
13328 		0,
13329 		0,
13330 		0,
13331 		(char)LOG_SENSE_LENGTH,
13332 		0
13333 	};
13334 
13335 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
13336 
13337 	ASSERT(mutex_owned(ST_MUTEX));
13338 
13339 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13340 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
13341 
13342 	com->uscsi_cdb = cdb;
13343 	com->uscsi_cdblen = CDB_GROUP1;
13344 	com->uscsi_bufaddr = (caddr_t)sensep;
13345 	com->uscsi_buflen = LOG_SENSE_LENGTH;
13346 	com->uscsi_rqlen = sizeof (status);
13347 	com->uscsi_rqbuf = (caddr_t)&status;
13348 	com->uscsi_flags =
13349 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13350 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13351 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13352 	if (rval || com->uscsi_status) {
13353 		/* uscsi-command failed */
13354 		rval = -1;
13355 	} else {
13356 
13357 		sp = sensep + 3;
13358 
13359 		for (length = *sp++; length > 0; length--, sp++) {
13360 
13361 			if (*sp == page) {
13362 				rval = 1;
13363 				break;
13364 			}
13365 		}
13366 	}
13367 	kmem_free(com, sizeof (struct uscsi_cmd));
13368 	kmem_free(sensep, LOG_SENSE_LENGTH);
13369 	return (rval);
13370 }
13371 
13372 
13373 /*
13374  * st_check_clean_bit() gets the status of the tape's cleaning bit.
13375  *
13376  * If the device does support the TapeAlert log page, then the cleaning bit
13377  * information will be read from this page. Otherwise we will see if one of
13378  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
13379  * the device, which means, that we can get the cleaning bit information via
13380  * a RequestSense command.
13381  * If both methods of getting cleaning bit information are not supported
13382  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
13383  * returns with
13384  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
13385  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
13386  * If the call to st_uscsi_cmd() to do the Log Sense or the Request Sense
13387  * command fails, or if the amount of Request Sense data is not enough, then
13388  *  st_check_clean_bit() returns with -1.
13389  */
13390 
13391 static int
13392 st_check_clean_bit(struct scsi_tape *un)
13393 {
13394 	int rval = 0;
13395 
13396 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
13397 
13398 	ASSERT(mutex_owned(ST_MUTEX));
13399 
13400 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
13401 		return (rval);
13402 	}
13403 
13404 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13405 
13406 		rval = st_logpage_supported(un, TAPE_SEQUENTIAL_PAGE);
13407 		if (rval == -1) {
13408 			return (0);
13409 		}
13410 		if (rval == 1) {
13411 
13412 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
13413 		}
13414 
13415 		rval = st_logpage_supported(un, TAPE_ALERT_PAGE);
13416 		if (rval == -1) {
13417 			return (0);
13418 		}
13419 		if (rval == 1) {
13420 
13421 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
13422 		}
13423 
13424 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13425 
13426 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
13427 		}
13428 	}
13429 
13430 	rval = 0;
13431 
13432 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
13433 
13434 		rval = st_check_sequential_clean_bit(un);
13435 		if (rval == -1) {
13436 			return (0);
13437 		}
13438 	}
13439 
13440 	if ((rval == 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
13441 
13442 		rval = st_check_alert_flags(un);
13443 		if (rval == -1) {
13444 			return (0);
13445 		}
13446 	}
13447 
13448 	if ((rval == 0) && (un->un_dp->options & ST_CLN_MASK)) {
13449 
13450 		rval = st_check_sense_clean_bit(un);
13451 		if (rval == -1) {
13452 			return (0);
13453 		}
13454 	}
13455 
13456 	/*
13457 	 * If found a supported means to check need to clean.
13458 	 */
13459 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
13460 
13461 		/*
13462 		 * head needs to be cleaned.
13463 		 */
13464 		if (rval & MTF_TAPE_HEAD_DIRTY) {
13465 
13466 			/*
13467 			 * Print log message only first time
13468 			 * found needing cleaned.
13469 			 */
13470 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
13471 
13472 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
13473 				    "Periodic head cleaning required");
13474 
13475 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
13476 			}
13477 
13478 		} else {
13479 
13480 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
13481 		}
13482 	}
13483 
13484 	return (rval);
13485 }
13486 
13487 
13488 static int
13489 st_check_sequential_clean_bit(struct scsi_tape *un)
13490 {
13491 	int rval;
13492 	int ix;
13493 	ushort_t parameter;
13494 	struct uscsi_cmd *cmd;
13495 	struct log_sequential_page *sp;
13496 	struct log_sequential_page_parameter *prm;
13497 	struct scsi_arq_status status;
13498 	char cdb[CDB_GROUP1] = {
13499 		SCMD_LOG_SENSE_G1,
13500 		0,
13501 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
13502 		0,
13503 		0,
13504 		0,
13505 		0,
13506 		(char)(sizeof (struct log_sequential_page) >> 8),
13507 		(char)(sizeof (struct log_sequential_page)),
13508 		0
13509 	};
13510 
13511 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
13512 
13513 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13514 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
13515 
13516 	cmd->uscsi_flags   =
13517 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13518 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13519 	cmd->uscsi_cdb	   = cdb;
13520 	cmd->uscsi_cdblen  = CDB_GROUP1;
13521 	cmd->uscsi_bufaddr = (caddr_t)sp;
13522 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
13523 	cmd->uscsi_rqlen   = sizeof (status);
13524 	cmd->uscsi_rqbuf   = (caddr_t)&status;
13525 
13526 	rval = st_uscsi_cmd(un, cmd, FKIOCTL);
13527 
13528 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
13529 
13530 		rval = -1;
13531 
13532 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
13533 
13534 		rval = -1;
13535 	}
13536 
13537 	prm = &sp->param[0];
13538 
13539 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
13540 
13541 		if (prm->log_param.length == 0) {
13542 			break;
13543 		}
13544 
13545 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
13546 		    (prm->log_param.pc_lo & 0xff));
13547 
13548 		if (parameter == SEQUENTIAL_NEED_CLN) {
13549 
13550 			rval = MTF_TAPE_CLN_SUPPORTED;
13551 			if (prm->param_value[prm->log_param.length - 1]) {
13552 
13553 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13554 				    "sequential log says head dirty\n");
13555 				rval |= MTF_TAPE_HEAD_DIRTY;
13556 			}
13557 		}
13558 		prm = (struct log_sequential_page_parameter *)
13559 		    &prm->param_value[prm->log_param.length];
13560 	}
13561 
13562 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13563 	kmem_free(sp,  sizeof (struct log_sequential_page));
13564 
13565 	return (rval);
13566 }
13567 
13568 
13569 static int
13570 st_check_alert_flags(struct scsi_tape *un)
13571 {
13572 	struct st_tape_alert *ta;
13573 	struct uscsi_cmd *com;
13574 	struct scsi_arq_status status;
13575 	unsigned ix, length;
13576 	int rval;
13577 	tape_alert_flags flag;
13578 	char cdb[CDB_GROUP1] = {
13579 		SCMD_LOG_SENSE_G1,
13580 		0,
13581 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
13582 		0,
13583 		0,
13584 		0,
13585 		0,
13586 		(char)(sizeof (struct st_tape_alert) >> 8),
13587 		(char)(sizeof (struct st_tape_alert)),
13588 		0
13589 	};
13590 
13591 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
13592 
13593 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13594 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
13595 
13596 	com->uscsi_cdb = cdb;
13597 	com->uscsi_cdblen = CDB_GROUP1;
13598 	com->uscsi_bufaddr = (caddr_t)ta;
13599 	com->uscsi_buflen = sizeof (struct st_tape_alert);
13600 	com->uscsi_rqlen = sizeof (status);
13601 	com->uscsi_rqbuf = (caddr_t)&status;
13602 	com->uscsi_flags =
13603 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13604 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13605 
13606 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13607 
13608 	if (rval || com->uscsi_status || com->uscsi_resid) {
13609 
13610 		rval = -1; /* uscsi-command failed */
13611 
13612 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
13613 
13614 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13615 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
13616 		rval = -1;
13617 	}
13618 
13619 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
13620 
13621 
13622 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
13623 
13624 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13625 		    "TapeAlert length %d\n", length);
13626 	}
13627 
13628 
13629 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
13630 
13631 		/*
13632 		 * if rval is bad before the first pass don't bother
13633 		 */
13634 		if (ix == 0 && rval != 0) {
13635 
13636 			break;
13637 		}
13638 
13639 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
13640 		    ta->param[ix].log_param.pc_lo);
13641 
13642 		if ((ta->param[ix].param_value & 1) == 0) {
13643 			continue;
13644 		}
13645 		/*
13646 		 * check to see if current parameter is of interest.
13647 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
13648 		 */
13649 		if ((flag == TAF_CLEAN_NOW) ||
13650 		    (flag == TAF_CLEAN_PERIODIC) ||
13651 		    ((flag == CLEAN_FOR_ERRORS) &&
13652 		    (un->un_dp->type == ST_TYPE_STK9840))) {
13653 
13654 			rval = MTF_TAPE_CLN_SUPPORTED;
13655 
13656 
13657 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13658 			    "alert_page drive needs clean %d\n", flag);
13659 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
13660 			rval |= MTF_TAPE_HEAD_DIRTY;
13661 
13662 		} else if (flag == TAF_CLEANING_MEDIA) {
13663 
13664 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13665 			    "alert_page drive was cleaned\n");
13666 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
13667 		}
13668 
13669 	}
13670 
13671 	/*
13672 	 * Report it as dirty till we see it cleaned
13673 	 */
13674 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
13675 
13676 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13677 		    "alert_page still dirty\n");
13678 		rval |= MTF_TAPE_HEAD_DIRTY;
13679 	}
13680 
13681 	kmem_free(com, sizeof (struct uscsi_cmd));
13682 	kmem_free(ta,  sizeof (struct st_tape_alert));
13683 
13684 	return (rval);
13685 }
13686 
13687 
13688 static int
13689 st_check_sense_clean_bit(struct scsi_tape *un)
13690 {
13691 	uchar_t *sensep;
13692 	char cdb[CDB_GROUP0];
13693 	struct uscsi_cmd *com;
13694 	ushort_t byte_pos;
13695 	uchar_t bit_mask;
13696 	unsigned length;
13697 	int index;
13698 	int rval;
13699 
13700 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
13701 
13702 	/*
13703 	 * Since this tape does not support Tape Alert,
13704 	 * we now try to get the cleanbit status via
13705 	 * Request Sense.
13706 	 */
13707 
13708 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
13709 
13710 		index = 0;
13711 
13712 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
13713 
13714 		index = 1;
13715 
13716 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
13717 
13718 		index = 2;
13719 
13720 	} else {
13721 
13722 		return (-1);
13723 	}
13724 
13725 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
13726 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
13727 	length = byte_pos + 1;
13728 
13729 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13730 	sensep = kmem_zalloc(length, KM_SLEEP);
13731 
13732 	cdb[0] = SCMD_REQUEST_SENSE;
13733 	cdb[1] = 0;
13734 	cdb[2] = 0;
13735 	cdb[3] = 0;
13736 	cdb[4] = (char)length;
13737 	cdb[5] = 0;
13738 
13739 	com->uscsi_cdb = cdb;
13740 	com->uscsi_cdblen = CDB_GROUP0;
13741 	com->uscsi_bufaddr = (caddr_t)sensep;
13742 	com->uscsi_buflen = length;
13743 	com->uscsi_flags =
13744 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13745 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13746 
13747 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13748 
13749 	if (rval || com->uscsi_status || com->uscsi_resid) {
13750 
13751 		rval = -1;
13752 
13753 	} else {
13754 
13755 		rval = MTF_TAPE_CLN_SUPPORTED;
13756 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
13757 
13758 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13759 			    "sense data says head dirty\n");
13760 			rval |= MTF_TAPE_HEAD_DIRTY;
13761 		}
13762 	}
13763 
13764 	kmem_free(com, sizeof (struct uscsi_cmd));
13765 	kmem_free(sensep, length);
13766 	return (rval);
13767 }
13768 
13769 /*
13770  * st_clear_unit_attention
13771  *
13772  *  	run test unit ready's to clear out outstanding
13773  * 	unit attentions.
13774  * 	returns zero for SUCCESS or the errno from st_cmd call
13775  */
13776 static int
13777 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
13778 {
13779 	int	i    = 0;
13780 	int	rval;
13781 
13782 	GET_SOFT_STATE(dev_instance);
13783 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
13784 
13785 	do {
13786 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
13787 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
13788 	return (rval);
13789 }
13790 
13791 static void
13792 st_calculate_timeouts(struct scsi_tape *un)
13793 {
13794 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
13795 
13796 	if (un->un_dp->non_motion_timeout == 0) {
13797 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13798 			un->un_dp->non_motion_timeout =
13799 			    st_io_time * st_long_timeout_x;
13800 		} else {
13801 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
13802 		}
13803 	}
13804 
13805 	if (un->un_dp->io_timeout == 0) {
13806 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13807 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
13808 		} else {
13809 			un->un_dp->io_timeout = (ushort_t)st_io_time;
13810 		}
13811 	}
13812 
13813 	if (un->un_dp->rewind_timeout == 0) {
13814 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13815 			un->un_dp->rewind_timeout =
13816 			    st_space_time * st_long_timeout_x;
13817 		} else {
13818 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
13819 		}
13820 	}
13821 
13822 	if (un->un_dp->space_timeout == 0) {
13823 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13824 			un->un_dp->space_timeout =
13825 			    st_space_time * st_long_timeout_x;
13826 		} else {
13827 			un->un_dp->space_timeout = (ushort_t)st_space_time;
13828 		}
13829 	}
13830 
13831 	if (un->un_dp->load_timeout == 0) {
13832 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13833 			un->un_dp->load_timeout =
13834 			    st_space_time * st_long_timeout_x;
13835 		} else {
13836 			un->un_dp->load_timeout = (ushort_t)st_space_time;
13837 		}
13838 	}
13839 
13840 	if (un->un_dp->unload_timeout == 0) {
13841 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13842 			un->un_dp->unload_timeout =
13843 			    st_space_time * st_long_timeout_x;
13844 		} else {
13845 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
13846 		}
13847 	}
13848 
13849 	if (un->un_dp->erase_timeout == 0) {
13850 		if (un->un_dp->options & ST_LONG_ERASE) {
13851 			un->un_dp->erase_timeout =
13852 			    st_space_time * st_long_space_time_x;
13853 		} else {
13854 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
13855 		}
13856 	}
13857 }
13858 
13859 
13860 static writablity
13861 st_is_not_wormable(struct scsi_tape *un)
13862 {
13863 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
13864 	return (RDWR);
13865 }
13866 
13867 static writablity
13868 st_is_hp_dat_tape_worm(struct scsi_tape *un)
13869 {
13870 	writablity wrt;
13871 
13872 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
13873 
13874 	/* Mode sense should be current */
13875 	if (un->un_mspl->media_type == 1) {
13876 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13877 		    "Drive has WORM media loaded\n");
13878 		wrt = WORM;
13879 	} else {
13880 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13881 		    "Drive has non WORM media loaded\n");
13882 		wrt = RDWR;
13883 	}
13884 	return (wrt);
13885 }
13886 
13887 #define	HP_DAT_INQUIRY 0x4A
13888 static writablity
13889 st_is_hp_dat_worm(struct scsi_tape *un)
13890 {
13891 	char *buf;
13892 	int result;
13893 	writablity wrt;
13894 
13895 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
13896 
13897 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
13898 
13899 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
13900 
13901 	if (result != 0) {
13902 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13903 		    "Read Standard Inquiry for WORM support failed");
13904 		wrt = FAILED;
13905 	} else if ((buf[40] & 1) == 0) {
13906 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13907 		    "Drive is NOT WORMable\n");
13908 		/* This drive doesn't support it so don't check again */
13909 		un->un_dp->options &= ~ST_WORMABLE;
13910 		wrt = RDWR;
13911 		un->un_wormable = st_is_not_wormable;
13912 	} else {
13913 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13914 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13915 		un->un_wormable = st_is_hp_dat_tape_worm;
13916 		wrt = un->un_wormable(un);
13917 	}
13918 
13919 	kmem_free(buf, HP_DAT_INQUIRY);
13920 
13921 	/*
13922 	 * If drive doesn't support it no point in checking further.
13923 	 */
13924 	return (wrt);
13925 }
13926 
13927 static writablity
13928 st_is_hp_lto_tape_worm(struct scsi_tape *un)
13929 {
13930 	writablity wrt;
13931 
13932 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
13933 
13934 	/* Mode sense should be current */
13935 	switch (un->un_mspl->media_type) {
13936 	case 0x00:
13937 		switch (un->un_mspl->density) {
13938 		case 0x40:
13939 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13940 			    "Drive has standard Gen I media loaded\n");
13941 			break;
13942 		case 0x42:
13943 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13944 			    "Drive has standard Gen II media loaded\n");
13945 			break;
13946 		case 0x44:
13947 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13948 			    "Drive has standard Gen III media loaded\n");
13949 			break;
13950 		case 0x46:
13951 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13952 			    "Drive has standard Gen IV media loaded\n");
13953 			break;
13954 		default:
13955 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13956 			    "Drive has standard unknown 0x%X media loaded\n",
13957 			    un->un_mspl->density);
13958 		}
13959 		wrt = RDWR;
13960 		break;
13961 	case 0x01:
13962 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13963 		    "Drive has WORM medium loaded\n");
13964 		wrt = WORM;
13965 		break;
13966 	case 0x80:
13967 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13968 		    "Drive has CD-ROM emulation medium loaded\n");
13969 		wrt = WORM;
13970 		break;
13971 	default:
13972 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13973 		    "Drive has an unexpected medium type 0x%X loaded\n",
13974 		    un->un_mspl->media_type);
13975 		wrt = RDWR;
13976 	}
13977 
13978 	return (wrt);
13979 }
13980 
13981 #define	LTO_REQ_INQUIRY 44
13982 static writablity
13983 st_is_hp_lto_worm(struct scsi_tape *un)
13984 {
13985 	char *buf;
13986 	int result;
13987 	writablity wrt;
13988 
13989 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
13990 
13991 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
13992 
13993 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
13994 
13995 	if (result != 0) {
13996 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13997 		    "Read Standard Inquiry for WORM support failed");
13998 		wrt = FAILED;
13999 	} else if ((buf[40] & 1) == 0) {
14000 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14001 		    "Drive is NOT WORMable\n");
14002 		/* This drive doesn't support it so don't check again */
14003 		un->un_dp->options &= ~ST_WORMABLE;
14004 		wrt = RDWR;
14005 		un->un_wormable = st_is_not_wormable;
14006 	} else {
14007 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14008 		    "Drive supports WORM version %d\n", buf[40] >> 1);
14009 		un->un_wormable = st_is_hp_lto_tape_worm;
14010 		wrt = un->un_wormable(un);
14011 	}
14012 
14013 	kmem_free(buf, LTO_REQ_INQUIRY);
14014 
14015 	/*
14016 	 * If drive doesn't support it no point in checking further.
14017 	 */
14018 	return (wrt);
14019 }
14020 
14021 static writablity
14022 st_is_t10_worm_device(struct scsi_tape *un)
14023 {
14024 	writablity wrt;
14025 
14026 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
14027 
14028 	if (un->un_mspl->media_type == 0x3c) {
14029 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14030 		    "Drive has WORM media loaded\n");
14031 		wrt = WORM;
14032 	} else {
14033 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14034 		    "Drive has non WORM media loaded\n");
14035 		wrt = RDWR;
14036 	}
14037 	return (wrt);
14038 }
14039 
14040 #define	SEQ_CAP_PAGE	(char)0xb0
14041 static writablity
14042 st_is_t10_worm(struct scsi_tape *un)
14043 {
14044 	char *buf;
14045 	int result;
14046 	writablity wrt;
14047 
14048 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
14049 
14050 	buf = kmem_zalloc(6, KM_SLEEP);
14051 
14052 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
14053 
14054 	if (result != 0) {
14055 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14056 		    "Read Vitial Inquiry for Sequental Capability"
14057 		    " WORM support failed %x", result);
14058 		wrt = FAILED;
14059 	} else if ((buf[4] & 1) == 0) {
14060 		ASSERT(buf[1] == SEQ_CAP_PAGE);
14061 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14062 		    "Drive is NOT WORMable\n");
14063 		/* This drive doesn't support it so don't check again */
14064 		un->un_dp->options &= ~ST_WORMABLE;
14065 		wrt = RDWR;
14066 		un->un_wormable = st_is_not_wormable;
14067 	} else {
14068 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14069 		    "Drive supports WORM\n");
14070 		un->un_wormable = st_is_t10_worm_device;
14071 		wrt = un->un_wormable(un);
14072 	}
14073 
14074 	kmem_free(buf, 6);
14075 
14076 	return (wrt);
14077 }
14078 
14079 
14080 #define	STK_REQ_SENSE 26
14081 
14082 static writablity
14083 st_is_stk_worm(struct scsi_tape *un)
14084 {
14085 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
14086 	struct scsi_extended_sense *sense;
14087 	struct uscsi_cmd *cmd;
14088 	char *buf;
14089 	int result;
14090 	writablity wrt;
14091 
14092 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
14093 
14094 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14095 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
14096 	sense = (struct scsi_extended_sense *)buf;
14097 
14098 	cmd->uscsi_flags = USCSI_READ;
14099 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14100 	cmd->uscsi_cdb = &cdb[0];
14101 	cmd->uscsi_bufaddr = buf;
14102 	cmd->uscsi_buflen = STK_REQ_SENSE;
14103 	cmd->uscsi_cdblen = CDB_GROUP0;
14104 	cmd->uscsi_rqlen = 0;
14105 	cmd->uscsi_rqbuf = NULL;
14106 
14107 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14108 
14109 	if (result != 0 || cmd->uscsi_status != 0) {
14110 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14111 		    "Request Sense for WORM failed");
14112 		wrt = RDWR;
14113 	} else if (sense->es_add_len + 8 < 24) {
14114 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14115 		    "Drive didn't send enough sense data for WORM byte %d\n",
14116 		    sense->es_add_len + 8);
14117 		wrt = RDWR;
14118 		un->un_wormable = st_is_not_wormable;
14119 	} else if ((buf[24]) & 0x02) {
14120 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14121 		    "Drive has WORM tape loaded\n");
14122 		wrt = WORM;
14123 		un->un_wormable = st_is_stk_worm;
14124 	} else {
14125 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14126 		    "Drive has normal tape loaded\n");
14127 		wrt = RDWR;
14128 		un->un_wormable = st_is_stk_worm;
14129 	}
14130 
14131 	kmem_free(buf, STK_REQ_SENSE);
14132 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14133 	return (wrt);
14134 }
14135 
14136 #define	DLT_INQ_SZ 44
14137 
14138 static writablity
14139 st_is_dlt_tape_worm(struct scsi_tape *un)
14140 {
14141 	caddr_t buf;
14142 	int result;
14143 	writablity wrt;
14144 
14145 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
14146 
14147 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14148 
14149 	/* Read Attribute Media Type */
14150 
14151 	result = st_read_attributes(un, 0x0408, buf, 10, st_uscsi_cmd);
14152 
14153 	/*
14154 	 * If this quantum drive is attached via an HBA that cannot
14155 	 * support thr read attributes command return error in the
14156 	 * hope that someday they will support the t10 method.
14157 	 */
14158 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
14159 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14160 		    "Read Attribute Command for WORM Media detection is not "
14161 		    "supported on the HBA that this drive is attached to.");
14162 		wrt = RDWR;
14163 		un->un_wormable = st_is_not_wormable;
14164 		goto out;
14165 	}
14166 
14167 	if (result != 0) {
14168 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14169 		    "Read Attribute Command for WORM Media returned 0x%x",
14170 		    result);
14171 		wrt = RDWR;
14172 		un->un_dp->options &= ~ST_WORMABLE;
14173 		goto out;
14174 	}
14175 
14176 	if ((uchar_t)buf[9] == 0x80) {
14177 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14178 		    "Drive media is WORM\n");
14179 		wrt = WORM;
14180 	} else {
14181 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14182 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
14183 		wrt = RDWR;
14184 	}
14185 
14186 out:
14187 	kmem_free(buf, DLT_INQ_SZ);
14188 	return (wrt);
14189 }
14190 
14191 static writablity
14192 st_is_dlt_worm(struct scsi_tape *un)
14193 {
14194 	caddr_t buf;
14195 	int result;
14196 	writablity wrt;
14197 
14198 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
14199 
14200 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14201 
14202 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
14203 
14204 	if (result != 0) {
14205 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14206 		    "Read Vendor Specific Inquiry for WORM support failed");
14207 		wrt = RDWR;
14208 		goto out;
14209 	}
14210 
14211 	if ((buf[2] & 1) == 0) {
14212 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14213 		    "Drive is not WORMable\n");
14214 		wrt = RDWR;
14215 		un->un_dp->options &= ~ST_WORMABLE;
14216 		un->un_wormable = st_is_not_wormable;
14217 		goto out;
14218 	} else {
14219 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14220 		    "Drive is WORMable\n");
14221 		un->un_wormable = st_is_dlt_tape_worm;
14222 		wrt = un->un_wormable(un);
14223 	}
14224 out:
14225 	kmem_free(buf, DLT_INQ_SZ);
14226 
14227 	return (wrt);
14228 }
14229 
14230 typedef struct {
14231 	struct modeheader_seq header;
14232 #if defined(_BIT_FIELDS_LTOH) /* X86 */
14233 	uchar_t pagecode	:6,
14234 				:2;
14235 	uchar_t page_len;
14236 	uchar_t syslogalive	:2,
14237 		device		:1,
14238 		abs		:1,
14239 		ulpbot		:1,
14240 		prth		:1,
14241 		ponej		:1,
14242 		ait		:1;
14243 	uchar_t span;
14244 
14245 	uchar_t			:6,
14246 		worm		:1,
14247 		mic		:1;
14248 	uchar_t worm_cap	:1,
14249 				:7;
14250 	uint32_t		:32;
14251 #else /* SPARC */
14252 	uchar_t			:2,
14253 		pagecode	:6;
14254 	uchar_t page_len;
14255 	uchar_t ait		:1,
14256 		device		:1,
14257 		abs		:1,
14258 		ulpbot		:1,
14259 		prth		:1,
14260 		ponej		:1,
14261 		syslogalive	:2;
14262 	uchar_t span;
14263 	uchar_t mic		:1,
14264 		worm		:1,
14265 				:6;
14266 	uchar_t			:7,
14267 		worm_cap	:1;
14268 	uint32_t		:32;
14269 #endif
14270 }ait_dev_con;
14271 
14272 #define	AIT_DEV_PAGE 0x31
14273 static writablity
14274 st_is_sony_worm(struct scsi_tape *un)
14275 {
14276 	int result;
14277 	writablity wrt;
14278 	ait_dev_con *ait_conf;
14279 
14280 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14281 
14282 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
14283 
14284 	result = st_gen_mode_sense(un, st_uscsi_cmd, AIT_DEV_PAGE,
14285 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
14286 
14287 	if (result == 0) {
14288 
14289 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
14290 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14291 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
14292 			    ait_conf->pagecode, AIT_DEV_PAGE);
14293 			wrt = RDWR;
14294 			un->un_wormable = st_is_not_wormable;
14295 
14296 		} else if (ait_conf->worm_cap) {
14297 
14298 			un->un_wormable = st_is_sony_worm;
14299 
14300 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14301 			    "Drives is WORMable\n");
14302 			if (ait_conf->worm) {
14303 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14304 				    "Media is WORM\n");
14305 				wrt = WORM;
14306 			} else {
14307 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14308 				    "Media is not WORM\n");
14309 				wrt = RDWR;
14310 			}
14311 
14312 		} else {
14313 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14314 			    "Drives not is WORMable\n");
14315 			wrt = RDWR;
14316 			/* No further checking required */
14317 			un->un_dp->options &= ~ST_WORMABLE;
14318 		}
14319 
14320 	} else {
14321 
14322 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14323 		    "AIT device config mode sense page read command failed"
14324 		    " result = %d ", result);
14325 		wrt = FAILED;
14326 		un->un_wormable = st_is_not_wormable;
14327 	}
14328 
14329 	kmem_free(ait_conf, sizeof (ait_dev_con));
14330 	return (wrt);
14331 }
14332 
14333 static writablity
14334 st_is_drive_worm(struct scsi_tape *un)
14335 {
14336 	writablity wrt;
14337 
14338 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14339 
14340 	switch (un->un_dp->type) {
14341 	case MT_ISDLT:
14342 		wrt = st_is_dlt_worm(un);
14343 		break;
14344 
14345 	case MT_ISSTK9840:
14346 		wrt = st_is_stk_worm(un);
14347 		break;
14348 
14349 	case MT_IS8MM:
14350 	case MT_ISAIT:
14351 		wrt = st_is_sony_worm(un);
14352 		break;
14353 
14354 	case MT_LTO:
14355 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14356 			wrt = st_is_hp_lto_worm(un);
14357 		} else {
14358 			wrt = st_is_t10_worm(un);
14359 		}
14360 		break;
14361 
14362 	case MT_ISDAT:
14363 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14364 			wrt = st_is_hp_dat_worm(un);
14365 		} else {
14366 			wrt = st_is_t10_worm(un);
14367 		}
14368 		break;
14369 
14370 	default:
14371 		wrt = FAILED;
14372 		break;
14373 	}
14374 
14375 	/*
14376 	 * If any of the above failed try the t10 standard method.
14377 	 */
14378 	if (wrt == FAILED) {
14379 		wrt = st_is_t10_worm(un);
14380 	}
14381 
14382 	/*
14383 	 * Unknown method for detecting WORM media.
14384 	 */
14385 	if (wrt == FAILED) {
14386 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14387 		    "Unknown method for WORM media detection\n");
14388 		wrt = RDWR;
14389 		un->un_dp->options &= ~ST_WORMABLE;
14390 	}
14391 
14392 	return (wrt);
14393 }
14394 
14395 static int
14396 st_read_attributes(struct scsi_tape *un, uint16_t attribute, void *pnt,
14397     size_t size, ubufunc_t bufunc)
14398 {
14399 	char cdb[CDB_GROUP4];
14400 	int result;
14401 	struct uscsi_cmd *cmd;
14402 	struct scsi_arq_status status;
14403 
14404 	caddr_t buf = (caddr_t)pnt;
14405 
14406 	ST_FUNC(ST_DEVINFO, st_read_attributes);
14407 
14408 	if (un->un_sd->sd_inq->inq_ansi < 3) {
14409 		return (ENOTTY);
14410 	}
14411 
14412 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14413 
14414 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
14415 	cdb[1] = 0;
14416 	cdb[2] = 0;
14417 	cdb[3] = 0;
14418 	cdb[4] = 0;
14419 	cdb[5] = 0;
14420 	cdb[6] = 0;
14421 	cdb[7] = 0;
14422 	cdb[8] = (char)(attribute >> 8);
14423 	cdb[9] = (char)(attribute);
14424 	cdb[10] = (char)(size >> 24);
14425 	cdb[11] = (char)(size >> 16);
14426 	cdb[12] = (char)(size >> 8);
14427 	cdb[13] = (char)(size);
14428 	cdb[14] = 0;
14429 	cdb[15] = 0;
14430 
14431 
14432 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE | USCSI_DIAGNOSE;
14433 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14434 	cmd->uscsi_cdb = &cdb[0];
14435 	cmd->uscsi_bufaddr = (caddr_t)buf;
14436 	cmd->uscsi_buflen = size;
14437 	cmd->uscsi_cdblen = sizeof (cdb);
14438 	cmd->uscsi_rqlen = sizeof (status);
14439 	cmd->uscsi_rqbuf = (caddr_t)&status;
14440 
14441 	result = bufunc(un, cmd, FKIOCTL);
14442 
14443 	if (result != 0 || cmd->uscsi_status != 0) {
14444 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
14445 		    "st_read_attribute failed: result %d status %d\n",
14446 		    result, cmd->uscsi_status);
14447 		/*
14448 		 * If this returns invalid operation code don't try again.
14449 		 */
14450 		if (un->un_sd->sd_sense->es_key == KEY_ILLEGAL_REQUEST &&
14451 		    un->un_sd->sd_sense->es_add_code == 0x20) {
14452 			result = ENOTTY;
14453 		} else if (result == 0) {
14454 			result = EIO;
14455 		}
14456 
14457 	} else {
14458 
14459 		/*
14460 		 * The attribute retured should match the attribute requested.
14461 		 */
14462 		if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
14463 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14464 			    "st_read_attribute got wrong data back expected "
14465 			    "0x%x got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
14466 			st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14467 			    "bad? data", buf, size);
14468 			result = EIO;
14469 		}
14470 	}
14471 
14472 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14473 
14474 	return (result);
14475 }
14476 
14477 static int
14478 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
14479     uchar_t page)
14480 {
14481 	char cdb[CDB_GROUP0];
14482 	struct scsi_extended_sense *sense;
14483 	struct uscsi_cmd *cmd;
14484 	int result;
14485 
14486 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
14487 
14488 	cdb[0] = SCMD_INQUIRY;
14489 	cdb[1] = page ? 1 : 0;
14490 	cdb[2] = page;
14491 	cdb[3] = 0;
14492 	cdb[4] = size;
14493 	cdb[5] = 0;
14494 
14495 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14496 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
14497 
14498 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
14499 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14500 	cmd->uscsi_cdb = &cdb[0];
14501 	cmd->uscsi_bufaddr = dest;
14502 	cmd->uscsi_buflen = size;
14503 	cmd->uscsi_cdblen = CDB_GROUP0;
14504 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
14505 	cmd->uscsi_rqbuf = (caddr_t)sense;
14506 
14507 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14508 
14509 	if (result != 0 || cmd->uscsi_status != 0) {
14510 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14511 		    "st_get_special_inquiry() failed for page %x", page);
14512 		if (result == 0) {
14513 			result = EIO;
14514 		}
14515 	}
14516 
14517 	kmem_free(sense, sizeof (struct scsi_extended_sense));
14518 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14519 
14520 	return (result);
14521 }
14522 
14523 
14524 static int
14525 st_update_block_pos(struct scsi_tape *un, bufunc_t bf, int post_space)
14526 {
14527 	int rval = ENOTTY;
14528 	uchar_t status = un->un_status;
14529 	posmode previous_pmode = un->un_running.pmode;
14530 
14531 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
14532 
14533 	while (un->un_read_pos_type != NO_POS) {
14534 		rval = bf(un, SCMD_READ_POSITION, 32, SYNC_CMD);
14535 
14536 		/*
14537 		 * If read position command returned good status
14538 		 * Parse the data to see if the position can be interpreted.
14539 		 */
14540 		if ((rval == 0) &&
14541 		    ((rval = st_interpret_read_pos(un, &un->un_pos,
14542 		    un->un_read_pos_type, 32, (caddr_t)un->un_read_pos_data,
14543 		    post_space)) == 0)) {
14544 			/*
14545 			 * Update the running position as well if un_pos was
14546 			 * ok. But only if recovery is enabled.
14547 			 */
14548 			if (st_recov_sz != sizeof (recov_info)) {
14549 				break;
14550 			}
14551 			rval = st_interpret_read_pos(un, &un->un_running,
14552 			    un->un_read_pos_type, 32,
14553 			    (caddr_t)un->un_read_pos_data, post_space);
14554 			un->un_status = status;
14555 			break;
14556 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
14557 			un->un_running.pmode = previous_pmode;
14558 			continue;
14559 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
14560 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
14561 			    "st_update_block_pos() read position cmd 0x%x"
14562 			    " returned 0x%x un_status = %d",
14563 			    un->un_read_pos_type, rval, un->un_status);
14564 			/* ENOTTY means it read garbage. try something else. */
14565 			if (rval == ENOTTY) {
14566 				rval = EIO; /* so ENOTTY is not final rval */
14567 			} else {
14568 				break;
14569 			}
14570 		} else {
14571 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
14572 			    "st_update_block_pos() read position cmd %x"
14573 			    " returned %x", un->un_read_pos_type, rval);
14574 			un->un_running.pmode = previous_pmode;
14575 		}
14576 
14577 		switch (un->un_read_pos_type) {
14578 		case SHORT_POS:
14579 			un->un_read_pos_type = NO_POS;
14580 			break;
14581 
14582 		case LONG_POS:
14583 			un->un_read_pos_type = EXT_POS;
14584 			break;
14585 
14586 		case EXT_POS:
14587 			un->un_read_pos_type = SHORT_POS;
14588 			break;
14589 
14590 		default:
14591 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14592 			    "Unexpected read position type 0x%x",
14593 			    un->un_read_pos_type);
14594 		}
14595 		un->un_status = KEY_NO_SENSE;
14596 	}
14597 
14598 	return (rval);
14599 }
14600 
14601 static int
14602 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
14603 {
14604 	int result;
14605 	size_t d_sz;
14606 	caddr_t pos_info;
14607 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
14608 
14609 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
14610 
14611 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
14612 		return (0);
14613 	}
14614 
14615 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
14616 
14617 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14618 		    "bp_mapin_common() failed");
14619 
14620 		return (EIO);
14621 	}
14622 
14623 	d_sz = bp->b_bcount - bp->b_resid;
14624 	if (d_sz == 0) {
14625 		bp_mapout(bp);
14626 		return (EIO);
14627 	}
14628 
14629 	/*
14630 	 * Copy the buf to a double-word aligned memory that can hold the
14631 	 * tape_position_t data structure.
14632 	 */
14633 	if ((pos_info = kmem_alloc(d_sz, KM_NOSLEEP)) == NULL) {
14634 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14635 		    "kmem_alloc() failed");
14636 		bp_mapout(bp);
14637 		return (EIO);
14638 	}
14639 	bcopy(bp->b_un.b_addr, pos_info, d_sz);
14640 
14641 #ifdef STDEBUG
14642 	if ((st_debug & 0x7) > 2) {
14643 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14644 		    "st_get_read_pos() position info",
14645 		    pos_info, bp->b_bcount);
14646 	}
14647 #endif
14648 
14649 	result = st_interpret_read_pos(un, &un->un_pos, cmd->uscsi_cdb[1],
14650 	    d_sz, pos_info, 0);
14651 
14652 	COPY_POS(&un->un_running, &un->un_pos);
14653 
14654 	kmem_free(pos_info, d_sz);
14655 	bp_mapout(bp);
14656 
14657 	return (result);
14658 }
14659 
14660 #if defined(_BIG_ENDIAN)
14661 
14662 #define	FIX_ENDIAN16(x)
14663 #define	FIX_ENDIAN32(x)
14664 #define	FIX_ENDIAN64(x)
14665 
14666 #elif defined(_LITTLE_ENDIAN)
14667 
14668 static void
14669 st_swap16(uint16_t *val)
14670 {
14671 	uint16_t tmp;
14672 
14673 	tmp = (*val >>  8) & 0xff;
14674 	tmp |= (*val <<  8) & 0xff00;
14675 
14676 	*val = tmp;
14677 }
14678 
14679 static void
14680 st_swap32(uint32_t *val)
14681 {
14682 	uint32_t tmp;
14683 
14684 	tmp =  (*val >> 24) & 0xff;
14685 	tmp |= (*val >>  8) & 0xff00;
14686 	tmp |= (*val <<  8) & 0xff0000;
14687 	tmp |= (*val << 24) & 0xff000000;
14688 
14689 	*val = tmp;
14690 }
14691 
14692 static void
14693 st_swap64(uint64_t *val)
14694 {
14695 	uint32_t low;
14696 	uint32_t high;
14697 
14698 	low =  (uint32_t)(*val);
14699 	high = (uint32_t)(*val >> 32);
14700 
14701 	st_swap32(&low);
14702 	st_swap32(&high);
14703 
14704 	*val =  high;
14705 	*val |= ((uint64_t)low << 32);
14706 }
14707 
14708 #define	FIX_ENDIAN16(x) st_swap16(x)
14709 #define	FIX_ENDIAN32(x) st_swap32(x)
14710 #define	FIX_ENDIAN64(x) st_swap64(x)
14711 #endif
14712 
14713 /*
14714  * st_interpret_read_pos()
14715  *
14716  * Returns:
14717  *	0	If secsessful.
14718  *	EIO	If read postion responce data was unuseable or invalid.
14719  *	ERANGE	If the position of the drive is too large for the read_p_type.
14720  *	ENOTTY	If the responce data looks invalid for the read position type.
14721  */
14722 
14723 static int
14724 st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
14725     read_p_types type, size_t data_sz, const caddr_t responce, int post_space)
14726 {
14727 	int rval = 0;
14728 	int flag = 0;
14729 	tapepos_t org;
14730 
14731 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
14732 
14733 	/*
14734 	 * We expect the position value to change after a space command.
14735 	 * So if post_space is set we don't print out what has changed.
14736 	 */
14737 	if ((dest != &un->un_pos) && (post_space == 0) &&
14738 	    (st_recov_sz == sizeof (recov_info))) {
14739 		COPY_POS(&org, dest);
14740 		flag = 1;
14741 	}
14742 
14743 	/*
14744 	 * See what kind of read position was requested.
14745 	 */
14746 	switch (type) {
14747 
14748 	case SHORT_POS: /* Short data format */
14749 	{
14750 		tape_position_t *pos_info = (tape_position_t *)responce;
14751 		uint32_t value;
14752 
14753 		/* If reserved fields are non zero don't use the data */
14754 		if (pos_info->reserved0 || pos_info->reserved1 ||
14755 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
14756 		    pos_info->reserved3) {
14757 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14758 			    "Invalid Read Short Position Data returned\n");
14759 			rval = EIO;
14760 			break;
14761 		}
14762 		/*
14763 		 * Position is to large to use this type of read position.
14764 		 */
14765 		if (pos_info->posi_err == 1) {
14766 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14767 			    "Drive reported position error\n");
14768 			rval = ERANGE;
14769 			break;
14770 		}
14771 		/*
14772 		 * If your at the begining of partition and end at the same
14773 		 * time it's very small partition or bad data.
14774 		 */
14775 		if (pos_info->begin_of_part && pos_info->end_of_part) {
14776 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14777 			    "SHORT_POS returned begin and end of"
14778 			    " partition\n");
14779 			rval = EIO;
14780 			break;
14781 		}
14782 
14783 		if (pos_info->blk_posi_unkwn == 0) {
14784 
14785 			value = pos_info->host_block;
14786 			FIX_ENDIAN32(&value);
14787 
14788 			/*
14789 			 * If the tape is rewound the host blcok should be 0.
14790 			 */
14791 			if ((pos_info->begin_of_part == 1) &&
14792 			    (value != 0)) {
14793 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14794 				    "SHORT_POS returned begin of partition"
14795 				    " but host block was 0x%x\n", value);
14796 				rval = EIO;
14797 				break;
14798 			}
14799 
14800 			if (dest->lgclblkno != value) {
14801 				if (flag)
14802 					flag++;
14803 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14804 				    "SHORT_POS current logical 0x%"PRIx64" read"
14805 				    " 0x%x\n", dest->lgclblkno, value);
14806 			}
14807 
14808 			dest->lgclblkno = (uint64_t)value;
14809 
14810 			/*
14811 			 * If the begining of partition is true and the
14812 			 * block number is zero we will beleive that it is
14813 			 * rewound. Promote the pmode to legacy.
14814 			 */
14815 			if ((pos_info->begin_of_part == 1) &&
14816 			    (value == 0)) {
14817 				dest->blkno = 0;
14818 				dest->fileno = 0;
14819 				if (dest->pmode != legacy)
14820 					dest->pmode = legacy;
14821 			/*
14822 			 * otherwise if the pmode was invalid,
14823 			 * promote it to logical.
14824 			 */
14825 			} else if (dest->pmode == invalid) {
14826 				dest->pmode = logical;
14827 			}
14828 
14829 			if (dest->partition != pos_info->partition_number) {
14830 				if (flag)
14831 					flag++;
14832 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14833 				    "SHORT_POS current partition %d read %d\n",
14834 				    dest->partition,
14835 				    pos_info->partition_number);
14836 			}
14837 
14838 			dest->partition = pos_info->partition_number;
14839 
14840 		} else {
14841 			dest->pmode = invalid;
14842 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14843 			    "Tape drive reported block position as unknown\n");
14844 		}
14845 		break;
14846 	}
14847 
14848 	case LONG_POS: /* Long data format */
14849 	{
14850 		uint64_t value;
14851 		tape_position_long_t *long_pos_info =
14852 		    (tape_position_long_t *)responce;
14853 
14854 		/* If reserved fields are non zero don't use the data */
14855 		if ((long_pos_info->reserved0) ||
14856 		    (long_pos_info->reserved1) ||
14857 		    (long_pos_info->reserved2)) {
14858 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14859 			    "Invalid Read Long Position Data returned\n");
14860 			rval = ENOTTY;
14861 			break;
14862 		}
14863 
14864 		/* Is position Valid */
14865 		if (long_pos_info->blk_posi_unkwn == 0) {
14866 			uint32_t part;
14867 
14868 			value = long_pos_info->block_number;
14869 			FIX_ENDIAN64(&value);
14870 
14871 			/*
14872 			 * If it says we are at the begining of partition
14873 			 * the block value better be 0.
14874 			 */
14875 			if ((long_pos_info->begin_of_part == 1) &&
14876 			    (value != 0)) {
14877 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14878 				    "LONG_POS returned begin of partition but"
14879 				    " block number was 0x%"PRIx64"\n", value);
14880 				rval = ENOTTY;
14881 				break;
14882 			}
14883 			/*
14884 			 * Can't be at the start and the end of the partition
14885 			 * at the same time if the partition is larger the 0.
14886 			 */
14887 			if (long_pos_info->begin_of_part &&
14888 			    long_pos_info->end_of_part) {
14889 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14890 				    "LONG_POS returned begin and end of"
14891 				    " partition\n");
14892 				rval = ENOTTY;
14893 				break;
14894 			}
14895 
14896 			/*
14897 			 * If the logical block number is not what we expected.
14898 			 */
14899 			if (dest->lgclblkno != value) {
14900 				if (flag)
14901 					flag++;
14902 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14903 				    "LONG_POS current logical 0x%"PRIx64
14904 				    " read 0x%"PRIx64"\n",
14905 				    dest->lgclblkno, value);
14906 			}
14907 			dest->lgclblkno = value;
14908 
14909 			/*
14910 			 * If the begining of partition is true and the
14911 			 * block number is zero we will beleive that it is
14912 			 * rewound. Promote the pmode to legacy.
14913 			 */
14914 			if ((long_pos_info->begin_of_part == 1) &&
14915 			    (long_pos_info->block_number == 0)) {
14916 				dest->blkno = 0;
14917 				dest->fileno = 0;
14918 				if (dest->pmode != legacy)
14919 					dest->pmode = legacy;
14920 			/*
14921 			 * otherwise if the pmode was invalid,
14922 			 * promote it to logical.
14923 			 */
14924 			} else if (dest->pmode == invalid) {
14925 				dest->pmode = logical;
14926 			}
14927 
14928 			part = long_pos_info->partition;
14929 			FIX_ENDIAN32(&part);
14930 			if (dest->partition != part) {
14931 				if (flag)
14932 					flag++;
14933 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14934 				    "LONG_POS current partition %d"
14935 				    " read %d\n", dest->partition, part);
14936 			}
14937 			dest->partition = part;
14938 		} else {
14939 			/*
14940 			 * If the drive doesn't know location,
14941 			 * we don't either.
14942 			 */
14943 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14944 			    "Tape drive reported block position as unknown\n");
14945 			dest->pmode = invalid;
14946 		}
14947 
14948 		/* Is file position valid */
14949 		if (long_pos_info->mrk_posi_unkwn == 0) {
14950 			value = long_pos_info->file_number;
14951 			FIX_ENDIAN64(&value);
14952 			/*
14953 			 * If it says we are at the begining of partition
14954 			 * the block value better be 0.
14955 			 */
14956 			if ((long_pos_info->begin_of_part == 1) &&
14957 			    (value != 0)) {
14958 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14959 				    "LONG_POS returned begin of partition but"
14960 				    " block number was 0x%"PRIx64"\n", value);
14961 				rval = ENOTTY;
14962 				break;
14963 			}
14964 			if (((dest->pmode == legacy) ||
14965 			    (dest->pmode == logical)) &&
14966 			    (dest->fileno != value)) {
14967 				if (flag)
14968 					flag++;
14969 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14970 				    "LONG_POS fileno 0x%"PRIx64
14971 				    " not un_pos %x\n", value,
14972 				    dest->fileno);
14973 			} else if (dest->pmode == invalid) {
14974 				dest->pmode = logical;
14975 			}
14976 			dest->fileno = (int32_t)value;
14977 		}
14978 
14979 		if (dest->pmode != invalid && long_pos_info->end_of_part) {
14980 			dest->eof = ST_EOT;
14981 		}
14982 
14983 		break;
14984 	}
14985 
14986 	case EXT_POS: /* Extended data format */
14987 	{
14988 		uint64_t value;
14989 		uint16_t len;
14990 		tape_position_ext_t *ext_pos_info =
14991 		    (tape_position_ext_t *)responce;
14992 
14993 		/* Make sure that there is enough data there */
14994 		if (data_sz < 16) {
14995 			break;
14996 		}
14997 
14998 		/* If reserved fields are non zero don't use the data */
14999 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
15000 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15001 			    "EXT_POS reserved fields not zero\n");
15002 			rval = ENOTTY;
15003 			break;
15004 		}
15005 
15006 		/*
15007 		 * In the unlikely event of overflowing 64 bits of position.
15008 		 */
15009 		if (ext_pos_info->posi_err != 0) {
15010 			rval = ERANGE;
15011 			break;
15012 		}
15013 
15014 		len = ext_pos_info->parameter_len;
15015 		FIX_ENDIAN16(&len);
15016 
15017 		if (len != 0x1c) {
15018 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15019 			    "EXT_POS parameter_len should be 0x1c was 0x%x\n",
15020 			    len);
15021 			rval = ENOTTY;
15022 			break;
15023 		}
15024 
15025 		/* Is block position information valid */
15026 		if (ext_pos_info->blk_posi_unkwn == 0) {
15027 
15028 			value = ext_pos_info->host_block;
15029 			FIX_ENDIAN64(&value);
15030 			if ((ext_pos_info->begin_of_part == 1) &&
15031 			    (value != 0)) {
15032 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15033 				    "EXT_POS returned begining of partition but"
15034 				    " the host block was 0x%"PRIx64"\n", value);
15035 				rval = ENOTTY;
15036 				break;
15037 			}
15038 
15039 			if (dest->lgclblkno != value) {
15040 				if (flag)
15041 					flag++;
15042 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15043 				    "EXT_POS current logical 0x%"PRIx64
15044 				    " read 0x%"PRIx64"\n",
15045 				    dest->lgclblkno, value);
15046 			}
15047 			dest->lgclblkno = value;
15048 
15049 			/*
15050 			 * If the begining of partition is true and the
15051 			 * block number is zero we will beleive that it is
15052 			 * rewound. Promote the pmode to legacy.
15053 			 */
15054 			if ((ext_pos_info->begin_of_part == 1) &&
15055 			    (ext_pos_info->host_block == 0)) {
15056 				dest->blkno = 0;
15057 				dest->fileno = 0;
15058 				if (dest->pmode != legacy) {
15059 					dest->pmode = legacy;
15060 				}
15061 			/*
15062 			 * otherwise if the pmode was invalid,
15063 			 * promote it to logical.
15064 			 */
15065 			} else if (dest->pmode == invalid) {
15066 				dest->pmode = logical;
15067 			}
15068 
15069 			if (dest->partition != ext_pos_info->partition) {
15070 				if (flag)
15071 					flag++;
15072 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15073 				    "EXT_POS current partition %d read %d\n",
15074 				    dest->partition,
15075 				    ext_pos_info->partition);
15076 			}
15077 			dest->partition = ext_pos_info->partition;
15078 
15079 		} else {
15080 			dest->pmode = invalid;
15081 		}
15082 		break;
15083 	}
15084 
15085 	default:
15086 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15087 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
15088 		rval = EIO;
15089 	}
15090 
15091 	if ((flag > 1) && (rval == 0) && (org.pmode != invalid)) {
15092 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
15093 		    "position read in", &org);
15094 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
15095 		    "position read out", dest);
15096 	}
15097 
15098 	return (rval);
15099 }
15100 
15101 static int
15102 st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos,
15103     uint64_t lblk, uchar_t partition)
15104 {
15105 	int rval;
15106 	char cdb[CDB_GROUP4];
15107 	struct uscsi_cmd *cmd;
15108 	struct scsi_extended_sense sense;
15109 	bufunc_t bf = (ubf == st_uscsi_cmd) ? st_cmd : st_rcmd;
15110 
15111 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
15112 	/*
15113 	 * Not sure what to do when doing recovery and not wanting
15114 	 * to update un_pos
15115 	 */
15116 
15117 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
15118 
15119 	if (lblk <= INT32_MAX) {
15120 		cmd->uscsi_cdblen = CDB_GROUP1;
15121 		cdb[0] = SCMD_LOCATE;
15122 		cdb[1] = pos->partition == partition ? 0 : 2;
15123 		cdb[2] = 0;
15124 		cdb[3] = (char)(lblk >> 24);
15125 		cdb[4] = (char)(lblk >> 16);
15126 		cdb[5] = (char)(lblk >> 8);
15127 		cdb[6] = (char)(lblk);
15128 		cdb[7] = 0;
15129 		cdb[8] = partition;
15130 		cdb[9] = 0;
15131 	} else {
15132 		/*
15133 		 * If the drive doesn't give a 64 bit read position data
15134 		 * it is unlikely it will accept 64 bit locates.
15135 		 */
15136 		if (un->un_read_pos_type != LONG_POS) {
15137 			kmem_free(cmd, sizeof (struct uscsi_cmd));
15138 			return (ERANGE);
15139 		}
15140 		cmd->uscsi_cdblen = CDB_GROUP4;
15141 		cdb[0] = (char)SCMD_LOCATE_G4;
15142 		cdb[1] = pos->partition == partition ? 0 : 2;
15143 		cdb[2] = 0;
15144 		cdb[3] = partition;
15145 		cdb[4] = (char)(lblk >> 56);
15146 		cdb[5] = (char)(lblk >> 48);
15147 		cdb[6] = (char)(lblk >> 40);
15148 		cdb[7] = (char)(lblk >> 32);
15149 		cdb[8] = (char)(lblk >> 24);
15150 		cdb[9] = (char)(lblk >> 16);
15151 		cdb[10] = (char)(lblk >> 8);
15152 		cdb[11] = (char)(lblk);
15153 		cdb[12] = 0;
15154 		cdb[13] = 0;
15155 		cdb[14] = 0;
15156 		cdb[15] = 0;
15157 	}
15158 
15159 
15160 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
15161 	cmd->uscsi_rqbuf = (caddr_t)&sense;
15162 	cmd->uscsi_rqlen = sizeof (sense);
15163 	cmd->uscsi_timeout = un->un_dp->space_timeout;
15164 	cmd->uscsi_cdb = cdb;
15165 
15166 	rval = ubf(un, cmd, FKIOCTL);
15167 
15168 	pos->pmode = logical;
15169 	pos->eof = ST_NO_EOF;
15170 
15171 	if (lblk > INT32_MAX) {
15172 		/*
15173 		 * XXX This is a work around till we handle Descriptor format
15174 		 * sense data. Since we are sending a command where the standard
15175 		 * sense data can not correctly represent a correct residual in
15176 		 * 4 bytes.
15177 		 */
15178 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
15179 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15180 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
15181 			/* Doesn't like big locate command */
15182 			un->un_status = 0;
15183 			rval = ERANGE;
15184 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
15185 			/* Aborted big locate command */
15186 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15187 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
15188 			    rval);
15189 			un->un_status = 0;
15190 			rval = EIO;
15191 		} else if (st_update_block_pos(un, bf, 1)) {
15192 			/* read position failed */
15193 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15194 			    "Big LOCATE and read pos: rval = %d\n", rval);
15195 			rval = EIO;
15196 		} else if (lblk > un->un_pos.lgclblkno) {
15197 			/* read position worked but position was not expected */
15198 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15199 			    "Big LOCATE and recover read less then desired 0x%"
15200 			    PRIx64"\n", un->un_pos.lgclblkno);
15201 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
15202 			un->un_status = KEY_BLANK_CHECK;
15203 			rval = ESPIPE;
15204 		} else if (lblk == un->un_pos.lgclblkno) {
15205 			/* read position was what was expected */
15206 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15207 			    "Big LOCATE and recover seems to have worked\n");
15208 			un->un_err_resid = 0;
15209 			rval = 0;
15210 		} else {
15211 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15212 			    "BIGLOCATE end up going backwards");
15213 			un->un_err_resid = lblk;
15214 			rval = EIO;
15215 		}
15216 
15217 	} else if (rval == 0) {
15218 		/* Worked as requested */
15219 		pos->lgclblkno = lblk;
15220 
15221 	} else if (((cmd->uscsi_status & ST_STATUS_MASK) == STATUS_CHECK) &&
15222 	    (cmd->uscsi_resid != 0)) {
15223 		/* Got part way there but wasn't enough blocks on tape */
15224 		pos->lgclblkno = lblk - cmd->uscsi_resid;
15225 		un->un_err_resid = cmd->uscsi_resid;
15226 		un->un_status = KEY_BLANK_CHECK;
15227 		rval = ESPIPE;
15228 
15229 	} else if (st_update_block_pos(un, bf, 1) == 0) {
15230 		/* Got part way there but drive didn't tell what we missed by */
15231 		un->un_err_resid = lblk - pos->lgclblkno;
15232 		un->un_status = KEY_BLANK_CHECK;
15233 		rval = ESPIPE;
15234 
15235 	} else {
15236 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15237 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
15238 		    rval, cmd->uscsi_status);
15239 		un->un_err_resid = lblk;
15240 		un->un_status = KEY_ILLEGAL_REQUEST;
15241 		pos->pmode = invalid;
15242 		rval = EIO;
15243 	}
15244 
15245 	kmem_free(cmd, sizeof (struct uscsi_cmd));
15246 
15247 	return (rval);
15248 }
15249 
15250 static int
15251 st_mtfsf_ioctl(struct scsi_tape *un, int64_t files)
15252 {
15253 	int rval;
15254 
15255 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
15256 
15257 
15258 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15259 	    "st_mtfsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15260 #if 0
15261 	if ((IN_EOF(un->un_pos)) && (files == 1)) {
15262 		un->un_pos.fileno++;
15263 		un->un_pos.blkno = 0;
15264 		return (0);
15265 	}
15266 #endif
15267 	/* pmode == invalid already handled */
15268 	if (un->un_pos.pmode == legacy) {
15269 		/*
15270 		 * forward space over filemark
15271 		 *
15272 		 * For ASF we allow a count of 0 on fsf which means
15273 		 * we just want to go to beginning of current file.
15274 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
15275 		 * Allow stepping over double fmk with reel
15276 		 */
15277 		if ((un->un_pos.eof >= ST_EOT) &&
15278 		    (files > 0) &&
15279 		    ((un->un_dp->options & ST_REEL) == 0)) {
15280 			/* we're at EOM */
15281 			un->un_err_resid = files;
15282 			un->un_status = KEY_BLANK_CHECK;
15283 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15284 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
15285 			return (EIO);
15286 		}
15287 
15288 		/*
15289 		 * physical tape position may not be what we've been
15290 		 * telling the user; adjust the request accordingly
15291 		 */
15292 		if (IN_EOF(un->un_pos)) {
15293 			un->un_pos.fileno++;
15294 			un->un_pos.blkno = 0;
15295 			/*
15296 			 * For positive direction case, we're now covered.
15297 			 * For zero or negative direction, we're covered
15298 			 * (almost)
15299 			 */
15300 			files--;
15301 		}
15302 
15303 	}
15304 
15305 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15306 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15307 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
15308 		return (EIO);
15309 	}
15310 
15311 
15312 	/*
15313 	 * Forward space file marks.
15314 	 * We leave ourselves at block zero
15315 	 * of the target file number.
15316 	 */
15317 	if (files < 0) {
15318 		rval = st_backward_space_files(un, -files, 0);
15319 	} else {
15320 		rval = st_forward_space_files(un, files);
15321 	}
15322 
15323 	return (rval);
15324 }
15325 
15326 static int
15327 st_forward_space_files(struct scsi_tape *un, int64_t count)
15328 {
15329 	int rval;
15330 
15331 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
15332 
15333 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15334 	    "fspace: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15335 
15336 	ASSERT(count >= 0);
15337 	ASSERT(un->un_pos.pmode != invalid);
15338 
15339 	/*
15340 	 * A space with a count of zero means take me to the start of file.
15341 	 */
15342 	if (count == 0) {
15343 
15344 		/* Hay look were already there */
15345 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0) {
15346 			un->un_err_resid = 0;
15347 			COPY_POS(&un->un_err_pos, &un->un_pos);
15348 			return (0);
15349 		}
15350 
15351 		/*
15352 		 * Well we are in the first file.
15353 		 * A rewind will get to the start.
15354 		 */
15355 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
15356 			rval = st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
15357 
15358 		/*
15359 		 * Can we backspace to get there?
15360 		 * This should work in logical mode.
15361 		 */
15362 		} else if (un->un_dp->options & ST_BSF) {
15363 			rval = st_space_to_begining_of_file(un);
15364 
15365 		/*
15366 		 * Can't back space but current file number is known,
15367 		 * So rewind and space from the begining of the partition.
15368 		 */
15369 		} else if (un->un_pos.pmode == legacy) {
15370 			rval = st_scenic_route_to_begining_of_file(un,
15371 			    un->un_pos.fileno);
15372 
15373 		/*
15374 		 * pmode is logical and ST_BSF is not set.
15375 		 * The LONG_POS read position contains the fileno.
15376 		 * If the read position works, rewind and space.
15377 		 */
15378 		} else if (un->un_read_pos_type == LONG_POS) {
15379 			rval = st_cmd(un, SCMD_READ_POSITION, 0, SYNC_CMD);
15380 			if (rval) {
15381 				/*
15382 				 * We didn't get the file position from the
15383 				 * read position command.
15384 				 * We are going to trust the drive to backspace
15385 				 * and then position after the filemark.
15386 				 */
15387 				rval = st_space_to_begining_of_file(un);
15388 			}
15389 			rval = st_interpret_read_pos(un, &un->un_pos, LONG_POS,
15390 			    32, (caddr_t)un->un_read_pos_data, 0);
15391 			if ((rval) && (un->un_pos.pmode == invalid)) {
15392 				rval = st_space_to_begining_of_file(un);
15393 			} else {
15394 				rval = st_scenic_route_to_begining_of_file(un,
15395 				    un->un_pos.fileno);
15396 			}
15397 		} else {
15398 			rval = EIO;
15399 		}
15400 		/*
15401 		 * If something didn't work we are lost
15402 		 */
15403 		if (rval != 0) {
15404 			un->un_pos.pmode = invalid;
15405 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15406 			    "st_mtioctop : EIO : fspace pmode invalid");
15407 
15408 			rval = EIO;
15409 		}
15410 
15411 	} else {
15412 		rval = st_space_fmks(un, count);
15413 	}
15414 
15415 	if (rval != EIO && count < 0) {
15416 		/*
15417 		 * we came here with a count < 0; we now need
15418 		 * to skip back to end up before the filemark
15419 		 */
15420 		rval = st_backward_space_files(un, 1, 1);
15421 	}
15422 
15423 	return (rval);
15424 }
15425 
15426 static int
15427 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
15428 {
15429 	int rval;
15430 
15431 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
15432 
15433 	if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15434 		rval = EIO;
15435 	} else if (st_cmd(un, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
15436 		rval = EIO;
15437 	}
15438 
15439 	return (rval);
15440 }
15441 
15442 static int
15443 st_space_to_begining_of_file(struct scsi_tape *un)
15444 {
15445 	int rval;
15446 
15447 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
15448 
15449 	/*
15450 	 * Back space of the file at the begining of the file.
15451 	 */
15452 	rval = st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
15453 	if (rval) {
15454 		rval = EIO;
15455 		return (rval);
15456 	}
15457 
15458 	/*
15459 	 * Other interesting answers might be crashed BOT which isn't bad.
15460 	 */
15461 	if (un->un_status == SUN_KEY_BOT) {
15462 		return (rval);
15463 	}
15464 
15465 	un->un_running.pmode = invalid;
15466 
15467 	/*
15468 	 * Now we are on the BOP side of the filemark. Forward space to
15469 	 * the EOM side and we are at the begining of the file.
15470 	 */
15471 	rval = st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD);
15472 	if (rval) {
15473 		rval = EIO;
15474 	}
15475 
15476 	return (rval);
15477 }
15478 
15479 static int
15480 st_mtfsr_ioctl(struct scsi_tape *un, int64_t count)
15481 {
15482 
15483 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
15484 
15485 	/*
15486 	 * forward space to inter-record gap
15487 	 *
15488 	 */
15489 
15490 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15491 	    "st_ioctl_fsr: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15492 
15493 	if (un->un_pos.pmode == legacy) {
15494 		/*
15495 		 * If were are at end of tape and count is forward.
15496 		 * Return blank check.
15497 		 */
15498 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
15499 			/* we're at EOM */
15500 			un->un_err_resid = count;
15501 			un->un_status = KEY_BLANK_CHECK;
15502 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15503 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
15504 			return (EIO);
15505 		}
15506 
15507 		/*
15508 		 * If count is zero there is nothing to do.
15509 		 */
15510 		if (count == 0) {
15511 			un->un_err_pos.fileno = un->un_pos.fileno;
15512 			un->un_err_pos.blkno = un->un_pos.blkno;
15513 			un->un_err_resid = 0;
15514 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15515 				un->un_status = SUN_KEY_EOF;
15516 			}
15517 			return (0);
15518 		}
15519 
15520 		/*
15521 		 * physical tape position may not be what we've been
15522 		 * telling the user; adjust the position accordingly
15523 		 */
15524 		if (IN_EOF(un->un_pos)) {
15525 			daddr_t blkno = un->un_pos.blkno;
15526 			int fileno = un->un_pos.fileno;
15527 
15528 			optype lastop = un->un_lastop;
15529 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)
15530 			    == -1) {
15531 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15532 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
15533 				return (EIO);
15534 			}
15535 
15536 			un->un_pos.blkno = blkno;
15537 			un->un_pos.fileno = fileno;
15538 			un->un_lastop = lastop;
15539 		}
15540 	}
15541 
15542 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15543 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15544 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
15545 		return (EIO);
15546 	}
15547 
15548 	return (st_space_records(un, count));
15549 }
15550 
15551 static int
15552 st_space_records(struct scsi_tape *un, int64_t count)
15553 {
15554 	int64_t dblk;
15555 	int rval = 0;
15556 
15557 	ST_FUNC(ST_DEVINFO, st_space_records);
15558 
15559 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15560 	    "st_space_records: count=%"PRIx64", eof=%x\n",
15561 	    count, un->un_pos.eof);
15562 
15563 	if (un->un_pos.pmode == logical) {
15564 		rval = st_cmd(un, SCMD_SPACE, Blk(count), SYNC_CMD);
15565 		if (rval != 0) {
15566 			rval = EIO;
15567 		}
15568 		return (rval);
15569 	}
15570 
15571 	dblk = count + un->un_pos.blkno;
15572 
15573 	/* Already there */
15574 	if (dblk == un->un_pos.blkno) {
15575 		un->un_err_resid = 0;
15576 		COPY_POS(&un->un_err_pos, &un->un_pos);
15577 		return (0);
15578 	}
15579 
15580 	/*
15581 	 * If the destination block is forward
15582 	 * or the drive will backspace records.
15583 	 */
15584 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
15585 		/*
15586 		 * If we're spacing forward, or the device can
15587 		 * backspace records, we can just use the SPACE
15588 		 * command.
15589 		 */
15590 		dblk -= un->un_pos.blkno;
15591 		if (st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15592 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15593 			    "st_space_records:EIO:space_records can't spc");
15594 			rval = EIO;
15595 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
15596 			/*
15597 			 * check if we hit BOT/EOT
15598 			 */
15599 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
15600 				un->un_status = SUN_KEY_BOT;
15601 				un->un_pos.eof = ST_NO_EOF;
15602 			} else if (dblk < 0 &&
15603 			    un->un_pos.eof == ST_EOF_PENDING) {
15604 				int residue = un->un_err_resid;
15605 				/*
15606 				 * we skipped over a filemark
15607 				 * and need to go forward again
15608 				 */
15609 				if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
15610 					ST_DEBUG2(ST_DEVINFO, st_label,
15611 					    SCSI_DEBUG, "st_space_records: EIO"
15612 					    " : can't space #2");
15613 					rval = EIO;
15614 				}
15615 				un->un_err_resid = residue;
15616 			}
15617 			if (rval == 0) {
15618 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15619 				    "st_space_records: EIO : space_rec rval"
15620 				    " == 0");
15621 				rval = EIO;
15622 			}
15623 		}
15624 	} else {
15625 		/*
15626 		 * else we rewind, space forward across filemarks to
15627 		 * the desired file, and then space records to the
15628 		 * desired block.
15629 		 */
15630 
15631 		int dfile = un->un_pos.fileno;	/* save current file */
15632 
15633 		if (dblk < 0) {
15634 			/*
15635 			 * Wups - we're backing up over a filemark
15636 			 */
15637 			if (un->un_pos.blkno != 0 &&
15638 			    (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15639 			    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD))) {
15640 				un->un_pos.pmode = invalid;
15641 			}
15642 			un->un_err_resid = -dblk;
15643 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
15644 				un->un_status = SUN_KEY_BOT;
15645 				un->un_pos.eof = ST_NO_EOF;
15646 			} else if (un->un_pos.fileno > 0) {
15647 				un->un_status = SUN_KEY_EOF;
15648 				un->un_pos.eof = ST_NO_EOF;
15649 			}
15650 			COPY_POS(&un->un_err_pos, &un->un_pos);
15651 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15652 			    "st_space_records:EIO:space_records : dblk < 0");
15653 			rval = EIO;
15654 		} else if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15655 		    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
15656 		    st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15657 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15658 			    "st_space_records: EIO :space_records : rewind "
15659 			    "and space failed");
15660 			un->un_pos.pmode = invalid;
15661 			rval = EIO;
15662 		}
15663 	}
15664 
15665 	return (rval);
15666 }
15667 
15668 static int
15669 st_mtbsf_ioctl(struct scsi_tape *un, int64_t files)
15670 {
15671 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
15672 
15673 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15674 	    "st_mtbsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15675 	/*
15676 	 * backward space of file filemark (1/2" and 8mm)
15677 	 * tape position will end on the beginning of tape side
15678 	 * of the desired file mark
15679 	 */
15680 	if ((un->un_dp->options & ST_BSF) == 0) {
15681 		return (ENOTTY);
15682 	}
15683 
15684 	if (un->un_pos.pmode == legacy) {
15685 
15686 		/*
15687 		 * If a negative count (which implies a forward space op)
15688 		 * is specified, and we're at logical or physical eot,
15689 		 * bounce the request.
15690 		 */
15691 
15692 		if (un->un_pos.eof >= ST_EOT && files < 0) {
15693 			un->un_err_resid = files;
15694 			un->un_status = SUN_KEY_EOT;
15695 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15696 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
15697 			return (EIO);
15698 		}
15699 		/*
15700 		 * physical tape position may not be what we've been
15701 		 * telling the user; adjust the request accordingly
15702 		 */
15703 		if (IN_EOF(un->un_pos)) {
15704 			un->un_pos.fileno++;
15705 			un->un_pos.blkno = 0;
15706 			files++;
15707 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15708 			    "st_mtbsf_ioctl in eof: count=%"PRIx64", op=%x\n",
15709 			    files, MTBSF);
15710 
15711 		}
15712 	}
15713 
15714 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15715 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15716 		    "st_ioctl : EIO : MTBSF : check den wfm");
15717 		return (EIO);
15718 	}
15719 
15720 	if (files <= 0) {
15721 		/*
15722 		 * for a negative count, we need to step forward
15723 		 * first and then step back again
15724 		 */
15725 		files = -files + 1;
15726 		return (st_forward_space_files(un, files));
15727 	}
15728 	return (st_backward_space_files(un, files, 1));
15729 }
15730 
15731 static int
15732 st_backward_space_files(struct scsi_tape *un, int64_t count, int infront)
15733 {
15734 	int64_t end_fileno;
15735 	int64_t skip_cnt;
15736 	int rval = 0;
15737 
15738 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
15739 
15740 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15741 	    "st_backward_space_files: count=%"PRIx64" eof=%x\n",
15742 	    count, un->un_pos.eof);
15743 	/*
15744 	 * Backspace files (MTNBSF): infront == 0
15745 	 *
15746 	 *	For tapes that can backspace, backspace
15747 	 *	count+1 filemarks and then run forward over
15748 	 *	a filemark
15749 	 *
15750 	 *	For tapes that can't backspace,
15751 	 *		calculate desired filenumber
15752 	 *		(un->un_pos.fileno - count), rewind,
15753 	 *		and then space forward this amount
15754 	 *
15755 	 * Backspace filemarks (MTBSF) infront == 1
15756 	 *
15757 	 *	For tapes that can backspace, backspace count
15758 	 *	filemarks
15759 	 *
15760 	 *	For tapes that can't backspace, calculate
15761 	 *	desired filenumber (un->un_pos.fileno - count),
15762 	 *	add 1, rewind, space forward this amount,
15763 	 *	and mark state as ST_EOF_PENDING appropriately.
15764 	 */
15765 
15766 	if (un->un_pos.pmode == logical) {
15767 
15768 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15769 		    "st_backward_space_files: mt_op=%x count=%"PRIx64
15770 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
15771 		    un->un_pos.lgclblkno);
15772 
15773 
15774 		/* In case a drive that won't back space gets in logical mode */
15775 		if ((un->un_dp->options & ST_BSF) == 0) {
15776 			rval = EIO;
15777 			return (rval);
15778 		}
15779 		if ((infront == 1) &&
15780 		    (st_cmd(un, SCMD_SPACE, Fmk(-count), SYNC_CMD))) {
15781 			rval = EIO;
15782 			return (rval);
15783 		} else if ((infront == 0) &&
15784 		    (st_cmd(un, SCMD_SPACE, Fmk((-count)-1), SYNC_CMD)) &&
15785 		    (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
15786 			rval = EIO;
15787 			return (rval);
15788 		}
15789 		return (rval);
15790 	}
15791 
15792 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15793 	    "st_backward_space_files: mt_op=%x count=%"PRIx64
15794 	    "fileno=%x blkno=%x\n",
15795 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
15796 
15797 
15798 
15799 	/*
15800 	 * Handle the simple case of BOT
15801 	 * playing a role in these cmds.
15802 	 * We do this by calculating the
15803 	 * ending file number. If the ending
15804 	 * file is < BOT, rewind and set an
15805 	 * error and mark resid appropriately.
15806 	 * If we're backspacing a file (not a
15807 	 * filemark) and the target file is
15808 	 * the first file on the tape, just
15809 	 * rewind.
15810 	 */
15811 
15812 	/* figure expected destination of this SPACE command */
15813 	end_fileno = un->un_pos.fileno - count;
15814 
15815 	/*
15816 	 * Would the end effect of this SPACE be the same as rewinding?
15817 	 * If so just rewind instead.
15818 	 */
15819 	if ((infront != 0) && (end_fileno < 0) ||
15820 	    (infront == 0) && (end_fileno <= 0)) {
15821 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15822 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15823 			    "st_backward_space_files: EIO : "
15824 			    "rewind in lou of BSF failed\n");
15825 			rval = EIO;
15826 		}
15827 		if (end_fileno < 0) {
15828 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15829 			    "st_backward_space_files: EIO : "
15830 			    "back space file greater then fileno\n");
15831 			rval = EIO;
15832 			un->un_err_resid = -end_fileno;
15833 			un->un_status = SUN_KEY_BOT;
15834 		}
15835 		return (rval);
15836 	}
15837 
15838 	if (un->un_dp->options & ST_BSF) {
15839 		skip_cnt = 1 - infront;
15840 		/*
15841 		 * If we are going to end up at the beginning
15842 		 * of the file, we have to space one extra file
15843 		 * first, and then space forward later.
15844 		 */
15845 		end_fileno = -(count + skip_cnt);
15846 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15847 		    "skip_cnt=%"PRIx64", tmp=%"PRIx64"\n",
15848 		    skip_cnt, end_fileno);
15849 		if (st_cmd(un, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
15850 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15851 			    "st_backward_space_files:EIO:back space fm failed");
15852 			rval = EIO;
15853 		}
15854 	} else {
15855 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15856 			rval = EIO;
15857 		} else {
15858 			skip_cnt = end_fileno + infront;
15859 		}
15860 	}
15861 
15862 	/*
15863 	 * If we have to space forward, do so...
15864 	 */
15865 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15866 	    "space forward skip_cnt=%"PRIx64", rval=%x\n", skip_cnt, rval);
15867 
15868 	if (rval == 0 && skip_cnt) {
15869 		if (st_cmd(un, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
15870 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15871 			    "st_backward_space_files:EIO:space fm skip count");
15872 			rval = EIO;
15873 		} else if (infront) {
15874 			/*
15875 			 * If we had to space forward, and we're
15876 			 * not a tape that can backspace, mark state
15877 			 * as if we'd just seen a filemark during a
15878 			 * a read.
15879 			 */
15880 			if ((un->un_dp->options & ST_BSF) == 0) {
15881 				un->un_pos.eof = ST_EOF_PENDING;
15882 				un->un_pos.fileno -= 1;
15883 				un->un_pos.blkno = LASTBLK;
15884 				un->un_running.pmode = invalid;
15885 			}
15886 		}
15887 	}
15888 
15889 	if (rval != 0) {
15890 		un->un_pos.pmode = invalid;
15891 	}
15892 
15893 	return (rval);
15894 }
15895 
15896 static int
15897 st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count)
15898 {
15899 	int rval;
15900 
15901 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
15902 
15903 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15904 	    "nbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15905 
15906 	if (un->un_pos.pmode == legacy) {
15907 		/*
15908 		 * backward space file to beginning of file
15909 		 *
15910 		 * If a negative count (which implies a forward space op)
15911 		 * is specified, and we're at logical or physical eot,
15912 		 * bounce the request.
15913 		 */
15914 
15915 		if (un->un_pos.eof >= ST_EOT && count < 0) {
15916 			un->un_err_resid = count;
15917 			un->un_status = SUN_KEY_EOT;
15918 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15919 			    "st_ioctl : EIO : > EOT and count < 0");
15920 			return (EIO);
15921 		}
15922 		/*
15923 		 * physical tape position may not be what we've been
15924 		 * telling the user; adjust the request accordingly
15925 		 */
15926 		if (IN_EOF(un->un_pos)) {
15927 			un->un_pos.fileno++;
15928 			un->un_pos.blkno = 0;
15929 			count++;
15930 		}
15931 	}
15932 
15933 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15934 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15935 		    "st_ioctl : EIO : MTNBSF check den and wfm");
15936 		return (EIO);
15937 	}
15938 
15939 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15940 	    "mtnbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15941 
15942 	if (count <= 0) {
15943 		rval = st_forward_space_files(un, -count);
15944 	} else {
15945 		rval = st_backward_space_files(un, count, 0);
15946 	}
15947 	return (rval);
15948 }
15949 
15950 static int
15951 st_mtbsr_ioctl(struct scsi_tape *un, int64_t num)
15952 {
15953 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
15954 
15955 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15956 	    "bsr: count=%"PRIx64", eof=%x\n", num, un->un_pos.eof);
15957 
15958 	if (un->un_pos.pmode == legacy) {
15959 		/*
15960 		 * backward space into inter-record gap
15961 		 *
15962 		 * If a negative count (which implies a forward space op)
15963 		 * is specified, and we're at logical or physical eot,
15964 		 * bounce the request.
15965 		 */
15966 		if (un->un_pos.eof >= ST_EOT && num < 0) {
15967 			un->un_err_resid = num;
15968 			un->un_status = SUN_KEY_EOT;
15969 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15970 			    "st_ioctl : EIO : MTBSR > EOT");
15971 			return (EIO);
15972 		}
15973 
15974 		if (num == 0) {
15975 			COPY_POS(&un->un_err_pos, &un->un_pos);
15976 			un->un_err_resid = 0;
15977 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15978 				un->un_status = SUN_KEY_EOF;
15979 			}
15980 			return (0);
15981 		}
15982 
15983 		/*
15984 		 * physical tape position may not be what we've been
15985 		 * telling the user; adjust the position accordingly.
15986 		 * bsr can not skip filemarks and continue to skip records
15987 		 * therefore if we are logically before the filemark but
15988 		 * physically at the EOT side of the filemark, we need to step
15989 		 * back; this allows fsr N where N > number of blocks in file
15990 		 * followed by bsr 1 to position at the beginning of last block
15991 		 */
15992 		if (IN_EOF(un->un_pos)) {
15993 			tapepos_t save;
15994 			optype lastop = un->un_lastop;
15995 
15996 			COPY_POS(&save, &un->un_pos);
15997 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD) == -1) {
15998 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15999 				    "st_mtbsr_ioctl: EIO : MTBSR can't space");
16000 				return (EIO);
16001 			}
16002 
16003 			COPY_POS(&un->un_pos, &save);
16004 			un->un_lastop = lastop;
16005 		}
16006 	}
16007 
16008 	un->un_pos.eof = ST_NO_EOF;
16009 
16010 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
16011 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16012 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
16013 		return (EIO);
16014 	}
16015 
16016 	num = -num;
16017 	return (st_space_records(un, num));
16018 }
16019 
16020 static int
16021 st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt)
16022 {
16023 	int rval;
16024 
16025 	ST_FUNC(ST_DEVINFO, st_mtfsfm_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 static int
16047 st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt)
16048 {
16049 	int rval;
16050 
16051 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
16052 
16053 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
16054 	if (rval == 0) {
16055 		un->un_pos.pmode = logical;
16056 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
16057 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
16058 		/*
16059 		 * Drive says invalid field in cdb.
16060 		 * Doesn't like space multiple. Position isn't lost.
16061 		 */
16062 		un->un_err_resid = cnt;
16063 		un->un_status = 0;
16064 		rval = ENOTTY;
16065 	} else {
16066 		un->un_err_resid = cnt;
16067 		un->un_pos.pmode = invalid;
16068 	}
16069 	return (rval);
16070 }
16071 
16072 #ifdef	__x86
16073 
16074 /*
16075  * release contig_mem and wake up waiting thread, if any
16076  */
16077 static void
16078 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
16079 {
16080 	mutex_enter(ST_MUTEX);
16081 
16082 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
16083 
16084 	cp->cm_next = un->un_contig_mem;
16085 	un->un_contig_mem = cp;
16086 	un->un_contig_mem_available_num++;
16087 	cv_broadcast(&un->un_contig_mem_cv);
16088 
16089 	mutex_exit(ST_MUTEX);
16090 }
16091 
16092 /*
16093  * St_get_contig_mem will return a contig_mem if there is one available
16094  * in current system. Otherwise, it will try to alloc one, if the total
16095  * number of contig_mem is within st_max_contig_mem_num.
16096  * It will sleep, if allowed by caller or return NULL, if no contig_mem
16097  * is available for now.
16098  */
16099 static struct contig_mem *
16100 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
16101 {
16102 	size_t rlen;
16103 	struct contig_mem *cp = NULL;
16104 	ddi_acc_handle_t acc_hdl;
16105 	caddr_t addr;
16106 	int big_enough = 0;
16107 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
16108 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
16109 
16110 	/* Try to get one available contig_mem */
16111 	mutex_enter(ST_MUTEX);
16112 
16113 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
16114 
16115 	if (un->un_contig_mem_available_num > 0) {
16116 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16117 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
16118 		/*
16119 		 * we failed to get one. we're going to
16120 		 * alloc one more contig_mem for this I/O
16121 		 */
16122 		mutex_exit(ST_MUTEX);
16123 		cp = (struct contig_mem *)kmem_zalloc(
16124 		    sizeof (struct contig_mem) + biosize(),
16125 		    alloc_flags);
16126 		if (cp == NULL) {
16127 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16128 			    "alloc contig_mem failure\n");
16129 			return (NULL); /* cannot get one */
16130 		}
16131 		cp->cm_bp = (struct buf *)
16132 		    (((caddr_t)cp) + sizeof (struct contig_mem));
16133 		bioinit(cp->cm_bp);
16134 		mutex_enter(ST_MUTEX);
16135 		un->un_contig_mem_total_num++; /* one more available */
16136 	} else {
16137 		/*
16138 		 * we failed to get one and we're NOT allowed to
16139 		 * alloc more contig_mem
16140 		 */
16141 		if (alloc_flags == KM_SLEEP) {
16142 			while (un->un_contig_mem_available_num <= 0) {
16143 				cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16144 			}
16145 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16146 		} else {
16147 			mutex_exit(ST_MUTEX);
16148 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16149 			    "alloc contig_mem failure\n");
16150 			return (NULL); /* cannot get one */
16151 		}
16152 	}
16153 	mutex_exit(ST_MUTEX);
16154 
16155 	/* We need to check if this block of mem is big enough for this I/O */
16156 	if (cp->cm_len < len) {
16157 		/* not big enough, need to alloc a new one */
16158 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
16159 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
16160 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
16161 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16162 			    "alloc contig_mem failure: not enough mem\n");
16163 			st_release_contig_mem(un, cp);
16164 			cp = NULL;
16165 		} else {
16166 			if (cp->cm_addr) {
16167 				/* release previous one before attach new one */
16168 				ddi_dma_mem_free(&cp->cm_acc_hdl);
16169 			}
16170 			mutex_enter(ST_MUTEX);
16171 			un->un_max_contig_mem_len =
16172 			    un->un_max_contig_mem_len >= len ?
16173 			    un->un_max_contig_mem_len : len;
16174 			mutex_exit(ST_MUTEX);
16175 
16176 			/* attach new mem to this cp */
16177 			cp->cm_addr = addr;
16178 			cp->cm_acc_hdl = acc_hdl;
16179 			cp->cm_len = len;
16180 
16181 			goto alloc_ok; /* get one usable cp */
16182 		}
16183 	} else {
16184 		goto alloc_ok; /* get one usable cp */
16185 	}
16186 
16187 	/* cannot find/alloc a usable cp, when we get here */
16188 
16189 	mutex_enter(ST_MUTEX);
16190 	if ((un->un_max_contig_mem_len < len) ||
16191 	    (alloc_flags != KM_SLEEP)) {
16192 		mutex_exit(ST_MUTEX);
16193 		return (NULL);
16194 	}
16195 
16196 	/*
16197 	 * we're allowed to sleep, and there is one big enough
16198 	 * contig mem in the system, which is currently in use,
16199 	 * wait for it...
16200 	 */
16201 	big_enough = 1;
16202 	do {
16203 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16204 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16205 	} while (cp == NULL);
16206 	mutex_exit(ST_MUTEX);
16207 
16208 	/* we get the big enough contig mem, finally */
16209 
16210 alloc_ok:
16211 	/* init bp attached to this cp */
16212 	bioreset(cp->cm_bp);
16213 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
16214 	cp->cm_bp->b_private = (void *)cp;
16215 
16216 	return (cp);
16217 }
16218 
16219 /*
16220  * this is the biodone func for the bp used in big block I/O
16221  */
16222 static int
16223 st_bigblk_xfer_done(struct buf *bp)
16224 {
16225 	struct contig_mem *cp;
16226 	struct buf *orig_bp;
16227 	int ioerr;
16228 	struct scsi_tape *un;
16229 
16230 	/* sanity check */
16231 	if (bp == NULL) {
16232 		return (DDI_FAILURE);
16233 	}
16234 
16235 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16236 	if (un == NULL) {
16237 		return (DDI_FAILURE);
16238 	}
16239 
16240 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
16241 
16242 	cp = (struct contig_mem *)bp->b_private;
16243 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
16244 	cp->cm_bp = bp;
16245 
16246 	/* special handling for special I/O */
16247 	if (cp->cm_use_sbuf) {
16248 #ifndef __lock_lint
16249 		ASSERT(un->un_sbuf_busy);
16250 #endif
16251 		un->un_sbufp = orig_bp;
16252 		cp->cm_use_sbuf = 0;
16253 	}
16254 
16255 	orig_bp->b_resid = bp->b_resid;
16256 	ioerr = geterror(bp);
16257 	if (ioerr != 0) {
16258 		bioerror(orig_bp, ioerr);
16259 	} else if (orig_bp->b_flags & B_READ) {
16260 		/* copy data back to original bp */
16261 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
16262 		    bp->b_bcount - bp->b_resid);
16263 	}
16264 
16265 	st_release_contig_mem(un, cp);
16266 
16267 	biodone(orig_bp);
16268 
16269 	return (DDI_SUCCESS);
16270 }
16271 
16272 /*
16273  * We use this func to replace original bp that may not be able to do I/O
16274  * in big block size with one that can
16275  */
16276 static struct buf *
16277 st_get_bigblk_bp(struct buf *bp)
16278 {
16279 	struct contig_mem *cp;
16280 	struct scsi_tape *un;
16281 	struct buf *cont_bp;
16282 
16283 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16284 	if (un == NULL) {
16285 		return (bp);
16286 	}
16287 
16288 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
16289 
16290 	/* try to get one contig_mem */
16291 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
16292 	if (!cp) {
16293 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
16294 		    "Cannot alloc contig buf for I/O for %lu blk size",
16295 		    bp->b_bcount);
16296 		return (bp);
16297 	}
16298 	cont_bp = cp->cm_bp;
16299 	cp->cm_bp = bp;
16300 
16301 	/* make sure that we "are" using un_sbufp for special I/O */
16302 	if (bp == un->un_sbufp) {
16303 #ifndef __lock_lint
16304 		ASSERT(un->un_sbuf_busy);
16305 #endif
16306 		un->un_sbufp = cont_bp;
16307 		cp->cm_use_sbuf = 1;
16308 	}
16309 
16310 	/* clone bp */
16311 	cont_bp->b_bcount = bp->b_bcount;
16312 	cont_bp->b_resid = bp->b_resid;
16313 	cont_bp->b_iodone = st_bigblk_xfer_done;
16314 	cont_bp->b_file = bp->b_file;
16315 	cont_bp->b_offset = bp->b_offset;
16316 	cont_bp->b_dip = bp->b_dip;
16317 	cont_bp->b_error = 0;
16318 	cont_bp->b_proc = NULL;
16319 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
16320 	cont_bp->b_shadow = NULL;
16321 	cont_bp->b_pages = NULL;
16322 	cont_bp->b_edev = bp->b_edev;
16323 	cont_bp->b_dev = bp->b_dev;
16324 	cont_bp->b_lblkno = bp->b_lblkno;
16325 	cont_bp->b_forw = bp->b_forw;
16326 	cont_bp->b_back = bp->b_back;
16327 	cont_bp->av_forw = bp->av_forw;
16328 	cont_bp->av_back = bp->av_back;
16329 	cont_bp->b_bufsize = bp->b_bufsize;
16330 
16331 	/* get data in original bp */
16332 	if (bp->b_flags & B_WRITE) {
16333 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
16334 	}
16335 
16336 	return (cont_bp);
16337 }
16338 #else
16339 #ifdef __lock_lint
16340 static int
16341 st_bigblk_xfer_done(struct buf *bp)
16342 {
16343 	return (0);
16344 }
16345 #endif
16346 #endif
16347 
16348 static const char *eof_status[] =
16349 {
16350 	"NO_EOF",
16351 	"EOF_PENDING",
16352 	"EOF",
16353 	"EOT_PENDING",
16354 	"EOT",
16355 	"EOM",
16356 	"AFTER_EOM"
16357 };
16358 static const char *mode[] = {
16359 	"invalid",
16360 	"legacy",
16361 	"logical"
16362 };
16363 
16364 static void
16365 st_print_position(dev_info_t *dev, char *label, uint_t level,
16366 const char *comment, tapepos_t *pos)
16367 {
16368 	ST_FUNC(dev, st_print_position);
16369 
16370 	scsi_log(dev, label, level,
16371 	    "%s Position data:\n", comment);
16372 	scsi_log(dev, label, CE_CONT,
16373 	    "Positioning mode = %s", mode[pos->pmode]);
16374 	scsi_log(dev, label, CE_CONT,
16375 	    "End Of File/Tape = %s", eof_status[pos->eof]);
16376 	scsi_log(dev, label, CE_CONT,
16377 	    "File Number      = 0x%x", pos->fileno);
16378 	scsi_log(dev, label, CE_CONT,
16379 	    "Block Number     = 0x%x", pos->blkno);
16380 	scsi_log(dev, label, CE_CONT,
16381 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
16382 	scsi_log(dev, label, CE_CONT,
16383 	    "Partition Number = 0x%x", pos->partition);
16384 }
16385 static int
16386 st_check_if_media_changed(struct scsi_tape *un, caddr_t data, int size)
16387 {
16388 
16389 	int result = 0;
16390 	int i;
16391 	ST_FUNC(ST_DEVINFO, st_check_if_media_changed);
16392 
16393 	/*
16394 	 * find non alpha numeric working from the end.
16395 	 */
16396 	for (i = size - 1; i >= 0; i--) {
16397 		if (ISALNUM(data[i]) == 0 || data[i] == ' ') {
16398 			data[i] = 0;
16399 			size = i;
16400 		}
16401 	}
16402 
16403 	if (size == 1) {
16404 		/*
16405 		 * Drive seems to think its returning useful data
16406 		 * but it looks like all junk
16407 		 */
16408 		return (result);
16409 	}
16410 
16411 	size++;
16412 
16413 	/*
16414 	 * Actually got a valid serial number.
16415 	 * If never stored one before alloc space for it.
16416 	 */
16417 	if (un->un_media_id_len == 0) {
16418 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16419 		un->un_media_id_len = size;
16420 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16421 		un->un_media_id[min(size, strlen(data))] = 0;
16422 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16423 		    "Found Media Id %s length = %d\n", un->un_media_id, size);
16424 	} else if (size > un->un_media_id_len) {
16425 		if (strncmp(un->un_media_id, data, size) != 0) {
16426 			result = ESPIPE;
16427 		}
16428 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16429 		    "Longer Media Id old ID:%s new ID:%s\n",
16430 		    un->un_media_id, data);
16431 		kmem_free(un->un_media_id, un->un_media_id_len);
16432 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16433 		un->un_media_id_len = size;
16434 		(void) strncpy(un->un_media_id, data, size);
16435 		un->un_media_id[size] = 0;
16436 	} else if (strncmp(data, un->un_media_id,
16437 	    min(size, un->un_media_id_len)) != 0) {
16438 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16439 		    "Old Media Id %s length = %d New %s length = %d\n",
16440 		    un->un_media_id, un->un_media_id_len, data, size);
16441 		bzero(un->un_media_id, un->un_media_id_len);
16442 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16443 		un->un_media_id[min(size, strlen(data))] = 0;
16444 		result = ESPIPE;
16445 	} else {
16446 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
16447 		    "Media Id still %s\n", un->un_media_id);
16448 	}
16449 
16450 	ASSERT(strlen(un->un_media_id) <= size);
16451 
16452 	return (result);
16453 }
16454 #define	ID_SIZE 32
16455 typedef struct
16456 {
16457 	uchar_t avilable_data0;
16458 	uchar_t avilable_data1;
16459 	uchar_t avilable_data2;
16460 	uchar_t avilable_data3;
16461 	uchar_t attribute_msb;
16462 	uchar_t attribute_lsb;
16463 #ifdef _BIT_FIELDS_LTOH
16464 	uchar_t format		: 2,
16465 				: 5,
16466 		read_only	: 1;
16467 #else
16468 	uchar_t read_only	: 1,
16469 				: 5,
16470 		format		: 2;
16471 #endif
16472 	uchar_t attribute_len_msb;
16473 	uchar_t attribute_len_lsb;
16474 }attribute_header;
16475 
16476 typedef struct {
16477 	attribute_header header;
16478 	char data[1];
16479 }mam_attribute;
16480 
16481 static int
16482 st_handle_hex_media_id(struct scsi_tape *un, void *pnt, int size)
16483 {
16484 	int result;
16485 	int newsize = (size << 1) + 3; /* extra for leading 0x and null term */
16486 	int i;
16487 	uchar_t byte;
16488 	char *format;
16489 	uchar_t *data = (uchar_t *)pnt;
16490 	char *buf = kmem_alloc(newsize, KM_SLEEP);
16491 
16492 	ST_FUNC(ST_DEVINFO, st_handle_hex_media_id);
16493 
16494 	(void) sprintf(buf, "0x");
16495 	for (i = 0; i < size; i++) {
16496 		byte = data[i];
16497 		if (byte < 0x10)
16498 			format = "0%x";
16499 		else
16500 			format = "%x";
16501 		(void) sprintf(&buf[(int)strlen(buf)], format, byte);
16502 	}
16503 	result = st_check_if_media_changed(un, buf, newsize);
16504 
16505 	kmem_free(buf, newsize);
16506 
16507 	return (result);
16508 }
16509 
16510 
16511 static int
16512 st_get_media_id_via_read_attribute(struct scsi_tape *un, ubufunc_t bufunc)
16513 {
16514 	int result;
16515 	mam_attribute *buffer;
16516 	int size;
16517 	int newsize;
16518 
16519 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_read_attribute);
16520 	size = sizeof (attribute_header) + max(un->un_media_id_len, ID_SIZE);
16521 again:
16522 	buffer = kmem_zalloc(size, KM_SLEEP);
16523 	result = st_read_attributes(un, 0x0401, buffer, size, bufunc);
16524 	if (result == 0) {
16525 
16526 		newsize = (buffer->header.attribute_len_msb << 8) |
16527 		    buffer->header.attribute_len_lsb;
16528 
16529 		if (newsize + sizeof (attribute_header) > size) {
16530 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
16531 			    "resizing read attribute data from %d to %d format"
16532 			    " %d\n", size, (int)sizeof (attribute_header) +
16533 			    newsize, buffer->header.format);
16534 			kmem_free(buffer, size);
16535 			size = newsize + sizeof (attribute_header);
16536 			goto again;
16537 		}
16538 
16539 		un->un_media_id_method = st_get_media_id_via_read_attribute;
16540 		if (buffer->header.format == 0) {
16541 			result =
16542 			    st_handle_hex_media_id(un, buffer->data, newsize);
16543 		} else {
16544 			result = st_check_if_media_changed(un, buffer->data,
16545 			    newsize);
16546 		}
16547 	} else if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
16548 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
16549 		    "Read Attribute Command for Media Identification is not "
16550 		    "supported on the HBA that this drive is attached to.");
16551 		result = ENOTTY;
16552 	}
16553 
16554 	kmem_free(buffer, size);
16555 	un->un_status = 0;
16556 
16557 	return (result);
16558 }
16559 
16560 
16561 static int
16562 st_get_media_id_via_media_serial_cmd(struct scsi_tape *un, ubufunc_t bufunc)
16563 {
16564 	char cdb[CDB_GROUP5];
16565 	struct uscsi_cmd *ucmd;
16566 	struct scsi_extended_sense sense;
16567 	int rval;
16568 	int size = max(un->un_media_id_len, ID_SIZE);
16569 	caddr_t buf;
16570 
16571 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_media_serial_cmd);
16572 
16573 	if (un->un_sd->sd_inq->inq_ansi < 3) {
16574 		return (ENOTTY);
16575 	}
16576 
16577 	ucmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
16578 upsize:
16579 	buf = kmem_alloc(size, KM_SLEEP);
16580 
16581 	cdb[0] = (char)SCMD_SVC_ACTION_IN_G5;
16582 	cdb[1] = SSVC_ACTION_READ_MEDIA_SERIAL;
16583 	cdb[2] = 0;
16584 	cdb[3] = 0;
16585 	cdb[4] = 0;
16586 	cdb[5] = 0;
16587 	cdb[6] = (char)(size >> 24);
16588 	cdb[7] = (char)(size >> 16);
16589 	cdb[8] = (char)(size >> 8);
16590 	cdb[9] = (char)(size);
16591 	cdb[10] = 0;
16592 	cdb[11] = 0;
16593 
16594 	ucmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
16595 	ucmd->uscsi_timeout = un->un_dp->non_motion_timeout;
16596 	ucmd->uscsi_cdb = &cdb[0];
16597 	ucmd->uscsi_cdblen = sizeof (cdb);
16598 	ucmd->uscsi_bufaddr = buf;
16599 	ucmd->uscsi_buflen = size;
16600 	ucmd->uscsi_rqbuf = (caddr_t)&sense;
16601 	ucmd->uscsi_rqlen = sizeof (sense);
16602 
16603 	rval = bufunc(un, ucmd, FKIOCTL);
16604 
16605 	if (rval || ucmd->uscsi_status != 0) {
16606 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16607 		    "media serial command returned %d scsi_status %d"
16608 		    " rqstatus %d", rval, ucmd->uscsi_status,
16609 		    ucmd->uscsi_rqstatus);
16610 		/*
16611 		 * If this returns invalid operation code don't try again.
16612 		 */
16613 		if (sense.es_key == KEY_ILLEGAL_REQUEST &&
16614 		    sense.es_add_code == 0x20) {
16615 			rval = ENOTTY;
16616 		} else if (rval == 0) {
16617 			rval = EIO;
16618 		}
16619 		un->un_status = 0;
16620 	} else {
16621 		int act_size;
16622 
16623 		/*
16624 		 * get reported size.
16625 		 */
16626 		act_size = (int)buf[3] | (int)(buf[2] << 8) |
16627 		    (int)(buf[1] << 16) | (int)(buf[0] << 24);
16628 
16629 		/* documentation says mod 4. */
16630 		while (act_size & 3) {
16631 			act_size++;
16632 		}
16633 
16634 		/*
16635 		 * If reported size is larger that we our buffer.
16636 		 * Free the old one and allocate one that is larger
16637 		 * enough and re-issuse the command.
16638 		 */
16639 		if (act_size + 4 > size) {
16640 			kmem_free(buf, size);
16641 			size = act_size + 4;
16642 			goto upsize;
16643 		}
16644 
16645 		if (act_size == 0) {
16646 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16647 			    "media serial number is not available");
16648 			un->un_status = 0;
16649 			rval = 0;
16650 		} else {
16651 			/*
16652 			 * set data pointer to point to the start
16653 			 * of that serial number.
16654 			 */
16655 			un->un_media_id_method =
16656 			    st_get_media_id_via_media_serial_cmd;
16657 			rval =
16658 			    st_check_if_media_changed(un, &buf[4], act_size);
16659 		}
16660 	}
16661 
16662 	kmem_free(ucmd, sizeof (struct uscsi_cmd));
16663 	kmem_free(buf, size);
16664 
16665 	return (rval);
16666 }
16667 
16668 
16669 /* ARGSUSED */
16670 static int
16671 st_bogus_media_id(struct scsi_tape *un, ubufunc_t bufunc)
16672 {
16673 	ST_FUNC(ST_DEVINFO, st_bogus_media_id);
16674 
16675 	ASSERT(un->un_media_id == NULL || un->un_media_id == bogusID);
16676 	ASSERT(un->un_media_id_len == 0);
16677 	un->un_media_id = (char *)bogusID;
16678 	un->un_media_id_len = 0;
16679 	return (0);
16680 }
16681 
16682 typedef int (*media_chk_function)(struct scsi_tape *, ubufunc_t bufunc);
16683 
16684 media_chk_function media_chk_functions[] = {
16685 	st_get_media_id_via_media_serial_cmd,
16686 	st_get_media_id_via_read_attribute,
16687 	st_bogus_media_id
16688 };
16689 
16690 static int
16691 st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc)
16692 {
16693 	int result = 0;
16694 	int i;
16695 
16696 	ST_FUNC(ST_DEVINFO, st_get_media_identification);
16697 
16698 	for (i = 0; i < ST_NUM_MEMBERS(media_chk_functions); i++) {
16699 		if (result == ENOTTY) {
16700 			/*
16701 			 * Last operation type not supported by this device.
16702 			 * Make so next time it doesn`t do that again.
16703 			 */
16704 			un->un_media_id_method = media_chk_functions[i];
16705 		} else if (un->un_media_id_method != media_chk_functions[i] &&
16706 		    un->un_media_id_method != st_get_media_identification) {
16707 			continue;
16708 		}
16709 		result = media_chk_functions[i](un, bufunc);
16710 		/*
16711 		 * If result indicates the function was successful or
16712 		 * that the media is not the same as last known, break.
16713 		 */
16714 		if (result == 0 || result == ESPIPE) {
16715 			break;
16716 		}
16717 	}
16718 
16719 	return (result);
16720 }
16721 
16722 static errstate
16723 st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
16724     errstate onentry)
16725 {
16726 
16727 	int ret;
16728 	st_err_info *errinfo;
16729 	recov_info *ri = (recov_info *)pkt->pkt_private;
16730 
16731 	ST_FUNC(ST_DEVINFO, st_command_recovery);
16732 
16733 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16734 
16735 	ASSERT(un->un_recov_buf_busy == 0);
16736 
16737 	/*
16738 	 * Don't try and recover a reset that this device sent.
16739 	 */
16740 	if (un->un_rsvd_status & ST_INITIATED_RESET &&
16741 	    onentry == DEVICE_RESET) {
16742 		return (COMMAND_DONE_ERROR);
16743 	}
16744 
16745 	/*
16746 	 * See if expected position was passed with scsi_pkt.
16747 	 */
16748 	if (ri->privatelen == sizeof (recov_info)) {
16749 
16750 		/*
16751 		 * Not for this command.
16752 		 */
16753 		if (ri->cmd_attrib->do_not_recover) {
16754 			return (COMMAND_DONE_ERROR);
16755 		}
16756 
16757 		/*
16758 		 * Create structure to hold all error state info.
16759 		 */
16760 		errinfo = kmem_zalloc(ST_ERR_INFO_SIZE, KM_SLEEP);
16761 		errinfo->ei_error_type = onentry;
16762 		errinfo->ei_failing_bp = ri->cmd_bp;
16763 		COPY_POS(&errinfo->ei_expected_pos, &ri->pos);
16764 	} else {
16765 		/* disabled */
16766 		return (COMMAND_DONE_ERROR);
16767 	}
16768 
16769 	bcopy(pkt, &errinfo->ei_failed_pkt, scsi_pkt_size());
16770 	bcopy(pkt->pkt_scbp, &errinfo->ei_failing_status, SECMDS_STATUS_SIZE);
16771 	ret = ddi_taskq_dispatch(un->un_recov_taskq, st_recover, errinfo,
16772 	    DDI_NOSLEEP);
16773 	ASSERT(ret == DDI_SUCCESS);
16774 	if (ret != DDI_SUCCESS) {
16775 		kmem_free(errinfo, ST_ERR_INFO_SIZE);
16776 		return (COMMAND_DONE_ERROR);
16777 	}
16778 	return (JUST_RETURN); /* release calling thread */
16779 }
16780 
16781 
16782 static void
16783 st_recov_ret(struct scsi_tape *un, st_err_info *errinfo, errstate err)
16784 {
16785 	int error_number;
16786 	buf_t *bp;
16787 
16788 
16789 	ST_FUNC(ST_DEVINFO, st_recov_ret);
16790 
16791 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16792 #if !defined(lint)
16793 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
16794 #endif
16795 
16796 	bp = errinfo->ei_failing_bp;
16797 	kmem_free(errinfo, ST_ERR_INFO_SIZE);
16798 
16799 	switch (err) {
16800 	case JUST_RETURN:
16801 		mutex_exit(&un->un_sd->sd_mutex);
16802 		return;
16803 
16804 	case COMMAND_DONE:
16805 	case COMMAND_DONE_ERROR_RECOVERED:
16806 		ST_DO_KSTATS(bp, kstat_runq_exit);
16807 		error_number = 0;
16808 		break;
16809 
16810 	default:
16811 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16812 		    "st_recov_ret with unhandled errstat %d\n", err);
16813 		/* FALLTHROUGH */
16814 	case COMMAND_DONE_ERROR:
16815 		un->un_pos.pmode = invalid;
16816 		un->un_running.pmode = invalid;
16817 		/* FALLTHROUGH */
16818 	case COMMAND_DONE_EACCES:
16819 		ST_DO_KSTATS(bp, kstat_waitq_exit);
16820 		ST_DO_ERRSTATS(un, st_transerrs);
16821 		error_number = EIO;
16822 		st_set_pe_flag(un);
16823 		break;
16824 
16825 	}
16826 
16827 	st_bioerror(bp, error_number);
16828 	st_done_and_mutex_exit(un, bp);
16829 }
16830 
16831 
16832 static void
16833 st_recover(void *arg)
16834 {
16835 	st_err_info *const errinfo = (st_err_info *)arg;
16836 	uchar_t com = errinfo->ei_failed_pkt.pkt_cdbp[0];
16837 	struct scsi_tape *un;
16838 	tapepos_t cur_pos;
16839 	int rval;
16840 	errstate status = COMMAND_DONE_ERROR;
16841 	recov_info *rcv;
16842 	buf_t *bp;
16843 
16844 
16845 	rcv = errinfo->ei_failed_pkt.pkt_private;
16846 	ASSERT(rcv->privatelen == sizeof (recov_info));
16847 	bp = rcv->cmd_bp;
16848 
16849 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16850 
16851 	ASSERT(un != NULL);
16852 
16853 	mutex_enter(ST_MUTEX);
16854 
16855 	ST_FUNC(ST_DEVINFO, st_recover);
16856 
16857 	ST_CDB(ST_DEVINFO, "Recovering command",
16858 	    (caddr_t)errinfo->ei_failed_pkt.pkt_cdbp);
16859 	ST_SENSE(ST_DEVINFO, "sense status for failed command",
16860 	    (caddr_t)&errinfo->ei_failing_status,
16861 	    sizeof (struct scsi_arq_status));
16862 	ST_POS(ST_DEVINFO, rcv->cmd_attrib->recov_pos_type == POS_STARTING ?
16863 	    "starting position for recovery command" :
16864 	    "expected position for recovery command",
16865 	    &errinfo->ei_expected_pos);
16866 
16867 	rval = st_test_path_to_device(un);
16868 
16869 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16870 	    "st_recover called with %s, TUR returned %d\n",
16871 	    errstatenames[errinfo->ei_error_type], rval);
16872 	/*
16873 	 * If the drive responed to the TUR lets try and get it to sync
16874 	 * any data it might have in the buffer.
16875 	 */
16876 	if (rval == 0 && rcv->cmd_attrib->chg_tape_data) {
16877 		rval = st_rcmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
16878 		if (rval) {
16879 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16880 			    "st_recover failed to flush, returned %d\n", rval);
16881 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16882 			return;
16883 		}
16884 	}
16885 	switch (errinfo->ei_error_type) {
16886 	case ATTEMPT_RETRY:
16887 	case COMMAND_TIMEOUT:
16888 	case DEVICE_RESET:
16889 	case PATH_FAILED:
16890 		/*
16891 		 * For now if we can't talk to the device we are done.
16892 		 * If the drive is reserved we can try to get it back.
16893 		 */
16894 		if (rval != 0 && rval != EACCES) {
16895 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16896 			return;
16897 		}
16898 
16899 		/*
16900 		 * If reservation conflict and do a preempt, fail it.
16901 		 */
16902 		if ((un->un_rsvd_status &
16903 		    (ST_APPLICATION_RESERVATIONS | ST_RESERVE)) != 0) {
16904 			if ((errinfo->ei_failed_pkt.pkt_cdbp[0] ==
16905 			    SCMD_PERSISTENT_RESERVE_OUT) &&
16906 			    (errinfo->ei_failed_pkt.pkt_cdbp[1] ==
16907 			    ST_SA_SCSI3_PREEMPT) &&
16908 			    (SCBP_C(&errinfo->ei_failed_pkt) ==
16909 			    STATUS_RESERVATION_CONFLICT)) {
16910 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16911 				return;
16912 			}
16913 		}
16914 
16915 		/*
16916 		 * If we have already set a scsi II reserve and get a
16917 		 * conflict on a scsi III type reserve fail without
16918 		 * any attempt to recover.
16919 		 */
16920 		if ((un->un_rsvd_status & ST_RESERVE | ST_PRESERVE_RESERVE) &&
16921 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] ==
16922 		    SCMD_PERSISTENT_RESERVE_OUT) ||
16923 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] ==
16924 		    SCMD_PERSISTENT_RESERVE_IN)) {
16925 			st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16926 			return;
16927 		}
16928 
16929 		/*
16930 		 * If scsi II lost reserve try and get it back.
16931 		 */
16932 		if ((((un->un_rsvd_status &
16933 		    (ST_LOST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
16934 		    ST_LOST_RESERVE)) &&
16935 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] != SCMD_RELEASE)) {
16936 			rval = st_reserve_release(un, ST_RESERVE,
16937 			    st_uscsi_rcmd);
16938 			if (rval != 0) {
16939 				if (st_take_ownership(un, st_uscsi_rcmd) != 0) {
16940 					st_recov_ret(un, errinfo,
16941 					    COMMAND_DONE_EACCES);
16942 					return;
16943 				}
16944 			}
16945 			un->un_rsvd_status |= ST_RESERVE;
16946 			un->un_rsvd_status &= ~(ST_RELEASE | ST_LOST_RESERVE |
16947 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
16948 		}
16949 		rval = st_make_sure_mode_data_is_correct(un, st_uscsi_rcmd);
16950 		if (rval) {
16951 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16952 			return;
16953 		}
16954 		break;
16955 	case DEVICE_TAMPER:
16956 		/*
16957 		 * Check if the ASC/ASCQ says mode data has changed.
16958 		 */
16959 		if ((errinfo->ei_failing_status.sts_sensedata.es_add_code ==
16960 		    0x2a) &&
16961 		    (errinfo->ei_failing_status.sts_sensedata.es_qual_code ==
16962 		    0x01)) {
16963 			/*
16964 			 * See if mode sense changed.
16965 			 */
16966 			rval = st_make_sure_mode_data_is_correct(un,
16967 			    st_uscsi_rcmd);
16968 			if (rval) {
16969 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16970 				return;
16971 			}
16972 		}
16973 		/*
16974 		 * if we have a media id and its not bogus.
16975 		 * Check to see if it the same.
16976 		 */
16977 		if (un->un_media_id != NULL && un->un_media_id != bogusID) {
16978 			rval = st_get_media_identification(un, st_uscsi_rcmd);
16979 			if (rval == ESPIPE) {
16980 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16981 				return;
16982 			}
16983 		}
16984 		break;
16985 	default:
16986 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16987 		    "Unhandled error type %s in st_recover() 0x%x\n",
16988 		    errstatenames[errinfo->ei_error_type], com);
16989 	}
16990 
16991 	/*
16992 	 * if command is retriable retry it.
16993 	 * Special case here. The command attribute for SCMD_REQUEST_SENSE
16994 	 * does not say that it is retriable. That because if you reissue a
16995 	 * request sense and the target responds the sense data will have
16996 	 * been consumed and no long be valid. If we get a busy status on
16997 	 * request sense while the state is ST_STATE_SENSING this will
16998 	 * reissue that pkt.
16999 	 *
17000 	 * XXX If this request sense gets sent to a different port then
17001 	 * the original command that failed was sent on it will not get
17002 	 * valid sense data for that command.
17003 	 */
17004 	if (rcv->cmd_attrib->retriable || un->un_rqs_bp == bp) {
17005 		status = st_recover_reissue_pkt(un, &errinfo->ei_failed_pkt);
17006 
17007 	/*
17008 	 * if drive doesn't support read position we are done
17009 	 */
17010 	} else if (un->un_read_pos_type == NO_POS) {
17011 		status = COMMAND_DONE_ERROR;
17012 	/*
17013 	 * If this command results in a changed tape position,
17014 	 * lets see where we are.
17015 	 */
17016 	} else if (rcv->cmd_attrib->chg_tape_pos) {
17017 		/*
17018 		 * XXX May be a reason to choose a different type here.
17019 		 * Long format has file position information.
17020 		 * Short and Extended have information about whats
17021 		 * in the buffer. St's positioning assumes in the buffer
17022 		 * to be the same as on tape.
17023 		 */
17024 		rval = st_compare_expected_position(un, errinfo,
17025 		    rcv->cmd_attrib, &cur_pos);
17026 		if (rval == 0) {
17027 			status = COMMAND_DONE;
17028 		} else if (rval == EAGAIN) {
17029 			status = st_recover_reissue_pkt(un,
17030 			    &errinfo->ei_failed_pkt);
17031 		} else {
17032 			status = COMMAND_DONE_ERROR;
17033 		}
17034 	} else {
17035 		ASSERT(0);
17036 	}
17037 
17038 	st_recov_ret(un, errinfo, status);
17039 }
17040 
17041 static void
17042 st_recov_cb(struct scsi_pkt *pkt)
17043 {
17044 	struct scsi_tape *un;
17045 	struct buf *bp;
17046 	recov_info *rcv;
17047 	errstate action = COMMAND_DONE_ERROR;
17048 	int timout = ST_TRAN_BUSY_TIMEOUT; /* short (default) timeout */
17049 
17050 	/*
17051 	 * Get the buf from the packet.
17052 	 */
17053 	rcv = pkt->pkt_private;
17054 	ASSERT(rcv->privatelen == sizeof (recov_info));
17055 	bp = rcv->cmd_bp;
17056 
17057 	/*
17058 	 * get the unit from the buf.
17059 	 */
17060 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
17061 	ASSERT(un != NULL);
17062 
17063 	ST_FUNC(ST_DEVINFO, st_recov_cb);
17064 
17065 	mutex_enter(ST_MUTEX);
17066 
17067 	ASSERT(bp == un->un_recov_buf);
17068 
17069 
17070 	switch (pkt->pkt_reason) {
17071 	case CMD_CMPLT:
17072 		if (un->un_arq_enabled && pkt->pkt_state & STATE_ARQ_DONE) {
17073 			action = st_handle_autosense(un, bp, &rcv->pos);
17074 		} else  if ((SCBP(pkt)->sts_busy) ||
17075 		    (SCBP(pkt)->sts_chk) ||
17076 		    (SCBP(pkt)->sts_vu7)) {
17077 			action = st_check_error(un, pkt);
17078 		} else {
17079 			action = COMMAND_DONE;
17080 		}
17081 		break;
17082 	case CMD_TIMEOUT:
17083 		action = COMMAND_TIMEOUT;
17084 		break;
17085 	case CMD_TRAN_ERR:
17086 		action = QUE_COMMAND;
17087 		break;
17088 	case CMD_DEV_GONE:
17089 		if (un->un_multipath)
17090 			action = PATH_FAILED;
17091 		else
17092 			action = COMMAND_DONE_ERROR;
17093 		break;
17094 	default:
17095 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
17096 		    "pkt_reason not handled yet %s",
17097 		    scsi_rname(pkt->pkt_reason));
17098 		action = COMMAND_DONE_ERROR;
17099 	}
17100 
17101 	/*
17102 	 * check for undetected path failover.
17103 	 */
17104 	if (un->un_multipath) {
17105 		if (scsi_pkt_allocated_correctly(pkt) &&
17106 		    (un->un_last_path_instance != pkt->pkt_path_instance)) {
17107 			if (un->un_state > ST_STATE_OPENING) {
17108 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17109 				    "Failover detected in recovery, action is "
17110 				    "%s\n", errstatenames[action]);
17111 			}
17112 			un->un_last_path_instance = pkt->pkt_path_instance;
17113 		}
17114 	}
17115 
17116 	ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
17117 	    "Recovery call back got %s status on %s\n",
17118 	    errstatenames[action], st_print_scsi_cmd(pkt->pkt_cdbp[0]));
17119 
17120 	switch (action) {
17121 	case COMMAND_DONE:
17122 		break;
17123 
17124 	case COMMAND_DONE_EACCES:
17125 		bioerror(bp, EACCES);
17126 		break;
17127 
17128 	case COMMAND_DONE_ERROR_RECOVERED: /* XXX maybe wrong */
17129 		ASSERT(0);
17130 		break;
17131 
17132 	case COMMAND_TIMEOUT:
17133 	case COMMAND_DONE_ERROR:
17134 		bioerror(bp, EIO);
17135 		break;
17136 
17137 	case DEVICE_RESET:
17138 	case QUE_BUSY_COMMAND:
17139 	case PATH_FAILED:
17140 		/* longish timeout */
17141 		timout = ST_STATUS_BUSY_TIMEOUT;
17142 		/* FALLTHRU */
17143 	case QUE_COMMAND:
17144 	case DEVICE_TAMPER:
17145 	case ATTEMPT_RETRY:
17146 		/*
17147 		 * let st_handle_intr_busy put this bp back on waitq and make
17148 		 * checks to see if it is ok to requeue the command.
17149 		 */
17150 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
17151 
17152 		/*
17153 		 * Save the throttle before setting up the timeout
17154 		 */
17155 		if (un->un_throttle) {
17156 			un->un_last_throttle = un->un_throttle;
17157 		}
17158 		mutex_exit(ST_MUTEX);
17159 		if (st_handle_intr_busy(un, bp, timout) == 0) {
17160 			return;		/* timeout is setup again */
17161 		}
17162 		mutex_enter(ST_MUTEX);
17163 		un->un_pos.pmode = invalid;
17164 		un->un_err_resid = bp->b_resid = bp->b_bcount;
17165 		st_bioerror(bp, EIO);
17166 		st_set_pe_flag(un);
17167 		break;
17168 
17169 	default:
17170 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
17171 		    "Unhandled recovery state 0x%x\n", action);
17172 		un->un_pos.pmode = invalid;
17173 		un->un_err_resid = bp->b_resid = bp->b_bcount;
17174 		st_bioerror(bp, EIO);
17175 		st_set_pe_flag(un);
17176 		break;
17177 	}
17178 
17179 	st_done_and_mutex_exit(un, bp);
17180 }
17181 
17182 static int
17183 st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait)
17184 {
17185 	struct buf *bp;
17186 	int err;
17187 
17188 	ST_FUNC(ST_DEVINFO, st_rcmd);
17189 
17190 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
17191 	    "st_rcmd(un = 0x%p, com = 0x%x, count = %"PRIx64", wait = %d)\n",
17192 	    (void *)un, com, count, wait);
17193 
17194 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
17195 	ASSERT(mutex_owned(ST_MUTEX));
17196 
17197 #ifdef STDEBUG
17198 	if ((st_debug & 0x7)) {
17199 		st_debug_cmds(un, com, count, wait);
17200 	}
17201 #endif
17202 
17203 	while (un->un_recov_buf_busy)
17204 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17205 	un->un_recov_buf_busy = 1;
17206 
17207 	bp = un->un_recov_buf;
17208 	bzero(bp, sizeof (buf_t));
17209 
17210 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
17211 
17212 	err = st_setup_cmd(un, bp, com, count);
17213 
17214 	un->un_recov_buf_busy = 0;
17215 
17216 	cv_signal(&un->un_recov_buf_cv);
17217 
17218 	return (err);
17219 }
17220 
17221 /* args used */
17222 static int
17223 st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
17224 {
17225 	int rval;
17226 	buf_t *bp;
17227 
17228 	ST_FUNC(ST_DEVINFO, st_uscsi_rcmd);
17229 	ASSERT(flag == FKIOCTL);
17230 
17231 	/*
17232 	 * Get buffer resources...
17233 	 */
17234 	while (un->un_recov_buf_busy)
17235 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17236 	un->un_recov_buf_busy = 1;
17237 
17238 	bp = un->un_recov_buf;
17239 	bzero(bp, sizeof (buf_t));
17240 
17241 	bp->b_forw = (struct buf *)(uintptr_t)ucmd->uscsi_cdb[0];
17242 	bp->b_back = (struct buf *)ucmd;
17243 
17244 	mutex_exit(ST_MUTEX);
17245 	rval = scsi_uscsi_handle_cmd(un->un_dev, UIO_SYSSPACE, ucmd,
17246 	    st_strategy, bp, NULL);
17247 	mutex_enter(ST_MUTEX);
17248 
17249 	ucmd->uscsi_resid = bp->b_resid;
17250 
17251 	/*
17252 	 * Free resources
17253 	 */
17254 	un->un_recov_buf_busy = 0;
17255 	cv_signal(&un->un_recov_buf_cv);
17256 
17257 	return (rval);
17258 }
17259 
17260 /*
17261  * Add data to scsi_pkt to help know what to do if the command fails.
17262  */
17263 static void
17264 st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
17265     struct scsi_pkt *pkt)
17266 {
17267 	uint64_t count;
17268 	recov_info *rinfo = (recov_info *)pkt->pkt_private;
17269 
17270 	ST_FUNC(ST_DEVINFO, st_add_recovery_info_to_pkt);
17271 
17272 	ASSERT(rinfo->privatelen == sizeof (pkt_info) ||
17273 	    rinfo->privatelen == sizeof (recov_info));
17274 
17275 	SET_BP_PKT(bp, pkt);
17276 	rinfo->cmd_bp = bp;
17277 
17278 	if (rinfo->privatelen != sizeof (recov_info)) {
17279 		return;
17280 	}
17281 
17282 	rinfo->cmd_bp = bp;
17283 
17284 	rinfo->cmd_attrib = NULL;
17285 
17286 	/*
17287 	 * lookup the command attributes and add them to the recovery info.
17288 	 */
17289 	rinfo->cmd_attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
17290 
17291 	ASSERT(rinfo->cmd_attrib);
17292 
17293 	/*
17294 	 * For commands that there is no way to figure the expected position
17295 	 * once completed, we save the position the command was started from
17296 	 * so that if they fail we can position back and try again.
17297 	 * This has already been done in st_cmd() or st_iscsi_cmd().
17298 	 */
17299 	if (rinfo->cmd_attrib->recov_pos_type == POS_STARTING) {
17300 		/* save current position as the starting position. */
17301 		COPY_POS(&rinfo->pos, &un->un_pos);
17302 		un->un_running.pmode = invalid;
17303 		return;
17304 	}
17305 
17306 	/*
17307 	 * Don't want to update the running position for recovery.
17308 	 */
17309 	if (bp == un->un_recov_buf) {
17310 		rinfo->pos.pmode = un->un_running.pmode;
17311 		return;
17312 	}
17313 	/*
17314 	 * If running position is invalid copy the current position.
17315 	 * Running being set invalid means we are not in a read, write
17316 	 * or write filemark sequence.
17317 	 * We'll copy the current position and start from there.
17318 	 */
17319 	if (un->un_running.pmode == invalid) {
17320 		COPY_POS(&un->un_running, &un->un_pos);
17321 		COPY_POS(&rinfo->pos, &un->un_running);
17322 	} else {
17323 		COPY_POS(&rinfo->pos, &un->un_running);
17324 		if (rinfo->pos.pmode == legacy) {
17325 			/*
17326 			 * Always should be more logical blocks then
17327 			 * data blocks and files marks.
17328 			 */
17329 			ASSERT((rinfo->pos.blkno >= 0) ?
17330 			    rinfo->pos.lgclblkno >=
17331 			    (rinfo->pos.blkno + rinfo->pos.fileno) : 1);
17332 		}
17333 	}
17334 
17335 	/*
17336 	 * If the command is not expected to change the drive position
17337 	 * then the running position should be the expected position.
17338 	 */
17339 	if (rinfo->cmd_attrib->chg_tape_pos == 0) {
17340 		ASSERT(rinfo->cmd_attrib->chg_tape_direction == DIR_NONE);
17341 		return;
17342 	}
17343 
17344 	if (rinfo->cmd_attrib->explicit_cmd_set) {
17345 		ASSERT(rinfo->pos.pmode != invalid);
17346 		ASSERT(rinfo->cmd_attrib->get_cnt);
17347 		count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17348 		/*
17349 		 * This is a user generated CDB.
17350 		 */
17351 		if (bp == un->un_sbufp) {
17352 			uint64_t lbn;
17353 
17354 			lbn = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17355 
17356 			/*
17357 			 * See if this CDB will generate a locate or change
17358 			 * partition.
17359 			 */
17360 			if ((lbn != un->un_running.lgclblkno) ||
17361 			    (pkt->pkt_cdbp[3] != un->un_running.partition)) {
17362 				rinfo->pos.partition = pkt->pkt_cdbp[3];
17363 				rinfo->pos.pmode = logical;
17364 				rinfo->pos.lgclblkno = lbn;
17365 				un->un_running.partition = pkt->pkt_cdbp[3];
17366 				un->un_running.pmode = logical;
17367 				un->un_running.lgclblkno = lbn;
17368 			}
17369 		} else {
17370 			uint64_t lbn = un->un_running.lgclblkno;
17371 
17372 			pkt->pkt_cdbp[3]  = (uchar_t)un->un_running.partition;
17373 
17374 			pkt->pkt_cdbp[4]  = (uchar_t)(lbn >> 56);
17375 			pkt->pkt_cdbp[5]  = (uchar_t)(lbn >> 48);
17376 			pkt->pkt_cdbp[6]  = (uchar_t)(lbn >> 40);
17377 			pkt->pkt_cdbp[7]  = (uchar_t)(lbn >> 32);
17378 			pkt->pkt_cdbp[8]  = (uchar_t)(lbn >> 24);
17379 			pkt->pkt_cdbp[9]  = (uchar_t)(lbn >> 16);
17380 			pkt->pkt_cdbp[10] = (uchar_t)(lbn >> 8);
17381 			pkt->pkt_cdbp[11] = (uchar_t)(lbn);
17382 		}
17383 		rinfo->pos.lgclblkno += count;
17384 		rinfo->pos.blkno += count;
17385 		un->un_running.lgclblkno += count;
17386 		return;
17387 	}
17388 
17389 	if (rinfo->cmd_attrib->chg_tape_pos) {
17390 
17391 		/* should not have got an invalid position from running. */
17392 		if (un->un_mediastate == MTIO_INSERTED) {
17393 			ASSERT(rinfo->pos.pmode != invalid);
17394 		}
17395 
17396 		/* should have either a get count or or get lba function */
17397 		ASSERT(rinfo->cmd_attrib->get_cnt != NULL ||
17398 		    rinfo->cmd_attrib->get_lba != NULL);
17399 
17400 		/* only explicit commands have both and they're handled above */
17401 		ASSERT(!(rinfo->cmd_attrib->get_cnt != NULL &&
17402 		    rinfo->cmd_attrib->get_lba != NULL));
17403 
17404 		/* if it has a get count function */
17405 		if (rinfo->cmd_attrib->get_cnt != NULL) {
17406 			count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17407 			if (count == 0) {
17408 				return;
17409 			}
17410 			/*
17411 			 * Changes position but doesn't transfer data.
17412 			 * i.e. rewind, write_file_mark and load.
17413 			 */
17414 			if (rinfo->cmd_attrib->transfers_data == TRAN_NONE) {
17415 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17416 				case DIR_NONE: /* Erase */
17417 					ASSERT(rinfo->cmd_attrib->cmd ==
17418 					    SCMD_ERASE);
17419 					break;
17420 				case DIR_FORW: /* write_file_mark */
17421 					rinfo->pos.fileno += count;
17422 					rinfo->pos.lgclblkno += count;
17423 					rinfo->pos.blkno = 0;
17424 					un->un_running.fileno += count;
17425 					un->un_running.lgclblkno += count;
17426 					un->un_running.blkno = 0;
17427 					break;
17428 				case DIR_REVC: /* rewind */
17429 					rinfo->pos.fileno = 0;
17430 					rinfo->pos.lgclblkno = 0;
17431 					rinfo->pos.blkno = 0;
17432 					rinfo->pos.eof = ST_NO_EOF;
17433 					rinfo->pos.pmode = legacy;
17434 					un->un_running.fileno = 0;
17435 					un->un_running.lgclblkno = 0;
17436 					un->un_running.blkno = 0;
17437 					un->un_running.eof = ST_NO_EOF;
17438 					if (un->un_running.pmode != legacy)
17439 						un->un_running.pmode = legacy;
17440 					break;
17441 				case DIR_EITH: /* Load unload */
17442 					ASSERT(rinfo->cmd_attrib->cmd ==
17443 					    SCMD_LOAD);
17444 					switch (count & (LD_LOAD | LD_RETEN |
17445 					    LD_RETEN | LD_HOLD)) {
17446 					case LD_UNLOAD:
17447 					case LD_RETEN:
17448 					case LD_HOLD:
17449 					case LD_LOAD | LD_HOLD:
17450 					case LD_EOT | LD_HOLD:
17451 					case LD_RETEN | LD_HOLD:
17452 						rinfo->pos.pmode = invalid;
17453 						un->un_running.pmode = invalid;
17454 						break;
17455 					case LD_EOT:
17456 					case LD_LOAD | LD_EOT:
17457 						rinfo->pos.eof = ST_EOT;
17458 						rinfo->pos.pmode = invalid;
17459 						un->un_running.eof = ST_EOT;
17460 						un->un_running.pmode = invalid;
17461 						break;
17462 					case LD_LOAD:
17463 					case LD_RETEN | LD_LOAD:
17464 						rinfo->pos.fileno = 0;
17465 						rinfo->pos.lgclblkno = 0;
17466 						rinfo->pos.blkno = 0;
17467 						rinfo->pos.eof = ST_NO_EOF;
17468 						rinfo->pos.pmode = legacy;
17469 						un->un_running.fileno = 0;
17470 						un->un_running.lgclblkno = 0;
17471 						un->un_running.blkno = 0;
17472 						un->un_running.eof = ST_NO_EOF;
17473 						break;
17474 					default:
17475 						ASSERT(0);
17476 					}
17477 					break;
17478 				default:
17479 					ASSERT(0);
17480 					break;
17481 				}
17482 			} else {
17483 				/*
17484 				 * Changes position and does transfer data.
17485 				 * i.e. read or write.
17486 				 */
17487 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17488 				case DIR_FORW:
17489 					rinfo->pos.lgclblkno += count;
17490 					rinfo->pos.blkno += count;
17491 					un->un_running.lgclblkno += count;
17492 					un->un_running.blkno += count;
17493 					break;
17494 				case DIR_REVC:
17495 					rinfo->pos.lgclblkno -= count;
17496 					rinfo->pos.blkno -= count;
17497 					un->un_running.lgclblkno -= count;
17498 					un->un_running.blkno -= count;
17499 					break;
17500 				default:
17501 					ASSERT(0);
17502 					break;
17503 				}
17504 			}
17505 		} else if (rinfo->cmd_attrib->get_lba != NULL) {
17506 			/* Have a get LBA fuction. i.e. Locate */
17507 			ASSERT(rinfo->cmd_attrib->chg_tape_direction ==
17508 			    DIR_EITH);
17509 			count = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17510 			un->un_running.lgclblkno = count;
17511 			un->un_running.blkno = 0;
17512 			un->un_running.fileno = 0;
17513 			un->un_running.pmode = logical;
17514 			rinfo->pos.lgclblkno = count;
17515 			rinfo->pos.pmode = invalid;
17516 		} else {
17517 			ASSERT(0);
17518 		}
17519 		return;
17520 	}
17521 
17522 	ST_CDB(ST_DEVINFO, "Unhanded CDB for position prediction",
17523 	    (char *)pkt->pkt_cdbp);
17524 
17525 }
17526 
17527 static int
17528 st_make_sure_mode_data_is_correct(struct scsi_tape *un, ubufunc_t ubf)
17529 {
17530 	int rval;
17531 
17532 	ST_FUNC(ST_DEVINFO, st_make_sure_mode_data_is_correct);
17533 
17534 	/*
17535 	 * check to see if mode data has changed.
17536 	 */
17537 	rval = st_check_mode_for_change(un, ubf);
17538 	if (rval) {
17539 		rval = st_gen_mode_select(un, ubf, un->un_mspl,
17540 		    sizeof (struct seq_mode));
17541 	}
17542 	if (un->un_tlr_flag != TLR_NOT_SUPPORTED) {
17543 		rval |= st_set_target_TLR_mode(un, ubf);
17544 	}
17545 	return (rval);
17546 }
17547 
17548 static int
17549 st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf)
17550 {
17551 	struct seq_mode *current;
17552 	int rval;
17553 	int i;
17554 	caddr_t this;
17555 	caddr_t that;
17556 
17557 	ST_FUNC(ST_DEVINFO, st_check_mode_for_change);
17558 
17559 	/* recovery called with mode tamper before mode selection */
17560 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
17561 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17562 		    "Mode Select not done yet");
17563 		return (0);
17564 	}
17565 
17566 	current = kmem_zalloc(sizeof (struct seq_mode), KM_SLEEP);
17567 
17568 	rval = st_gen_mode_sense(un, ubf, un->un_comp_page, current,
17569 	    sizeof (struct seq_mode));
17570 	if (rval != 0) {
17571 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17572 		    "Mode Sense for mode verification failed");
17573 		kmem_free(current, sizeof (struct seq_mode));
17574 		return (rval);
17575 	}
17576 
17577 	this = (caddr_t)current;
17578 	that = (caddr_t)un->un_mspl;
17579 
17580 	rval = bcmp(this, that, sizeof (struct seq_mode));
17581 	if (rval == 0) {
17582 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17583 		    "Found no changes in mode data");
17584 	}
17585 #ifdef STDEBUG
17586 	else {
17587 		for (i = 1; i < sizeof (struct seq_mode); i++) {
17588 			if (this[i] != that[i]) {
17589 				ST_RECOV(ST_DEVINFO, st_label, CE_CONT,
17590 				    "sense data changed at byte %d was "
17591 				    "0x%x now 0x%x", i,
17592 				    (uchar_t)that[i], (uchar_t)this[i]);
17593 			}
17594 		}
17595 	}
17596 #endif
17597 	kmem_free(current, sizeof (struct seq_mode));
17598 
17599 	return (rval);
17600 }
17601 
17602 static int
17603 st_test_path_to_device(struct scsi_tape *un)
17604 {
17605 	int rval = 0;
17606 	int limit = st_retry_count;
17607 
17608 	ST_FUNC(ST_DEVINFO, st_test_path_to_device);
17609 
17610 	/*
17611 	 * XXX Newer drives may not RESEVATION CONFLICT a TUR.
17612 	 */
17613 	do {
17614 		if (rval != 0) {
17615 			mutex_exit(ST_MUTEX);
17616 			delay(drv_usectohz(1000000));
17617 			mutex_enter(ST_MUTEX);
17618 		}
17619 		rval = st_rcmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
17620 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17621 		    "ping TUR returned 0x%x", rval);
17622 		limit--;
17623 	} while (((rval == EACCES) || (rval == EBUSY)) && limit);
17624 
17625 	if (un->un_status == KEY_NOT_READY || un->un_mediastate == MTIO_EJECTED)
17626 		rval = 0;
17627 
17628 	return (rval);
17629 }
17630 
17631 /*
17632  * Does read position using recov_buf and doesn't update un_pos.
17633  * Does what ever kind of read position you want.
17634  */
17635 static int
17636 st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
17637     read_pos_data_t *raw)
17638 {
17639 	int rval;
17640 	struct uscsi_cmd cmd;
17641 	struct scsi_arq_status status;
17642 	char cdb[CDB_GROUP1];
17643 
17644 	ST_FUNC(ST_DEVINFO, st_recovery_read_pos);
17645 	bzero(&cmd, sizeof (cmd));
17646 
17647 	cdb[0] = SCMD_READ_POSITION;
17648 	cdb[1] = type;
17649 	cdb[2] = 0;
17650 	cdb[3] = 0;
17651 	cdb[4] = 0;
17652 	cdb[5] = 0;
17653 	cdb[6] = 0;
17654 	cdb[7] = 0;
17655 	cdb[8] = (type == EXT_POS) ? 28 : 0;
17656 	cdb[9] = 0;
17657 
17658 	cmd.uscsi_flags = USCSI_READ | USCSI_RQENABLE;
17659 	cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
17660 	cmd.uscsi_cdb = cdb;
17661 	cmd.uscsi_cdblen = sizeof (cdb);
17662 	cmd.uscsi_rqlen = sizeof (status);
17663 	cmd.uscsi_rqbuf = (caddr_t)&status;
17664 	cmd.uscsi_bufaddr = (caddr_t)raw;
17665 	switch (type) {
17666 	case SHORT_POS:
17667 		cmd.uscsi_buflen = sizeof (tape_position_t);
17668 		break;
17669 	case LONG_POS:
17670 		cmd.uscsi_buflen = sizeof (tape_position_long_t);
17671 		break;
17672 	case EXT_POS:
17673 		cmd.uscsi_buflen = sizeof (tape_position_ext_t);
17674 		break;
17675 	default:
17676 		ASSERT(0);
17677 	}
17678 
17679 	rval = st_uscsi_rcmd(un, &cmd, FKIOCTL);
17680 	if (cmd.uscsi_status) {
17681 		rval = EIO;
17682 	}
17683 	return (rval);
17684 }
17685 
17686 static int
17687 st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
17688     read_pos_data_t *raw)
17689 {
17690 	int rval;
17691 	read_p_types type = un->un_read_pos_type;
17692 
17693 	ST_FUNC(ST_DEVINFO, st_recovery_get_position);
17694 
17695 	do {
17696 		rval = st_recovery_read_pos(un, type, raw);
17697 		if (rval != 0) {
17698 			switch (type) {
17699 			case SHORT_POS:
17700 				type = NO_POS;
17701 				break;
17702 
17703 			case LONG_POS:
17704 				type = EXT_POS;
17705 				break;
17706 
17707 			case EXT_POS:
17708 				type = SHORT_POS;
17709 				break;
17710 
17711 			default:
17712 				type = LONG_POS;
17713 				break;
17714 
17715 			}
17716 		} else {
17717 			if (type != un->un_read_pos_type) {
17718 				un->un_read_pos_type = type;
17719 			}
17720 			break;
17721 		}
17722 	} while (type != NO_POS);
17723 
17724 	if (rval == 0) {
17725 		rval = st_interpret_read_pos(un, read, type,
17726 		    sizeof (read_pos_data_t), (caddr_t)raw, 1);
17727 	}
17728 	return (rval);
17729 }
17730 
17731 /*
17732  * based on the command do we retry, continue or give up?
17733  * possable return values?
17734  *	zero do nothing looks fine.
17735  *	EAGAIN retry.
17736  *	EIO failed makes no sense.
17737  */
17738 static int
17739 st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
17740     cmd_attribute const * cmd_att, tapepos_t *read)
17741 {
17742 	int rval;
17743 	read_pos_data_t *readp_datap;
17744 
17745 	ST_FUNC(ST_DEVINFO, st_compare_expected_position);
17746 
17747 	ASSERT(un != NULL);
17748 	ASSERT(ei != NULL);
17749 	ASSERT(read != NULL);
17750 	ASSERT(cmd_att->chg_tape_pos);
17751 
17752 	COPY_POS(read, &ei->ei_expected_pos);
17753 
17754 	readp_datap = kmem_zalloc(sizeof (read_pos_data_t), KM_SLEEP);
17755 
17756 	rval = st_recovery_get_position(un, read, readp_datap);
17757 
17758 	kmem_free(readp_datap, sizeof (read_pos_data_t));
17759 
17760 	if (rval != 0) {
17761 		return (EIO);
17762 	}
17763 
17764 	ST_POS(ST_DEVINFO, "st_compare_expected_position", read);
17765 
17766 	if ((read->pmode == invalid) ||
17767 	    (ei->ei_expected_pos.pmode == invalid)) {
17768 		return (EIO);
17769 	}
17770 
17771 	/*
17772 	 * Command that changes tape position and have an expected position
17773 	 * if it were to chave completed sucessfully.
17774 	 */
17775 	if (cmd_att->recov_pos_type == POS_EXPECTED) {
17776 		uint32_t count;
17777 		int64_t difference;
17778 		uchar_t reposition = 0;
17779 
17780 		ASSERT(cmd_att->get_cnt);
17781 		count = cmd_att->get_cnt(ei->ei_failed_pkt.pkt_cdbp);
17782 
17783 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17784 		    "Got count from CDB and it was %d\n", count);
17785 
17786 		/*
17787 		 * At expected?
17788 		 */
17789 		if (read->lgclblkno == ei->ei_expected_pos.lgclblkno) {
17790 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17791 			    "Found drive to be at expected position\n");
17792 
17793 			/*
17794 			 * If the command should move tape and it got a busy
17795 			 * it shouldn't be in the expected position.
17796 			 */
17797 			if (ei->ei_failing_status.sts_status.sts_busy != 0) {
17798 				reposition = 1;
17799 
17800 			/*
17801 			 * If the command doesn't transfer data should be good.
17802 			 */
17803 			} else if (cmd_att->transfers_data == TRAN_NONE) {
17804 				return (0); /* Good */
17805 
17806 			/*
17807 			 * Command transfers data, should have done so.
17808 			 */
17809 			} else if (ei->ei_failed_pkt.pkt_state &
17810 			    STATE_XFERRED_DATA) {
17811 				return (0); /* Good */
17812 			} else {
17813 				reposition = 1;
17814 			}
17815 		}
17816 
17817 		if (cmd_att->chg_tape_direction == DIR_FORW) {
17818 			difference =
17819 			    ei->ei_expected_pos.lgclblkno - read->lgclblkno;
17820 
17821 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17822 			    "difference between expected and actual is %"
17823 			    PRId64"\n", difference);
17824 			if (count == difference && reposition == 0) {
17825 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17826 				    "Found failed FORW command, retrying\n");
17827 				return (EAGAIN);
17828 			}
17829 
17830 			/*
17831 			 * If rewound or somewhere between the starting position
17832 			 * and the expected position (partial read or write).
17833 			 * Locate to the starting position and try the whole
17834 			 * thing over again.
17835 			 */
17836 			if ((read->lgclblkno == 0) ||
17837 			    ((difference > 0) && (difference < count))) {
17838 				rval = st_logical_block_locate(un,
17839 				    st_uscsi_rcmd, read,
17840 				    ei->ei_expected_pos.lgclblkno - count,
17841 				    ei->ei_expected_pos.partition);
17842 				if (rval == 0) {
17843 					ST_RECOV(ST_DEVINFO, st_label,
17844 					    CE_NOTE, "reestablished FORW"
17845 					    " command retrying\n");
17846 					return (EAGAIN);
17847 				}
17848 			/*
17849 			 * This handles flushed read ahead on the drive or
17850 			 * an aborted read that presents as a busy and advanced
17851 			 * the tape position.
17852 			 */
17853 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17854 			    ((difference < 0) || (reposition == 1))) {
17855 				rval = st_logical_block_locate(un,
17856 				    st_uscsi_rcmd, read,
17857 				    ei->ei_expected_pos.lgclblkno - count,
17858 				    ei->ei_expected_pos.partition);
17859 				if (rval == 0) {
17860 					ST_RECOV(ST_DEVINFO, st_label,
17861 					    CE_NOTE, "reestablished FORW"
17862 					    " read command retrying\n");
17863 					return (EAGAIN);
17864 				}
17865 			/*
17866 			 * XXX swag seeing difference of 2 on write filemark.
17867 			 * If the space to the starting position works on a
17868 			 * write that means the previous write made it to tape.
17869 			 * If not we lost data and have to give up.
17870 			 *
17871 			 * The plot thickens. Now I am attempting to cover a
17872 			 * count of 1 and a differance of 2 on a write.
17873 			 */
17874 			} else if ((difference > count) || (reposition == 1)) {
17875 				rval = st_logical_block_locate(un,
17876 				    st_uscsi_rcmd, read,
17877 				    ei->ei_expected_pos.lgclblkno - count,
17878 				    ei->ei_expected_pos.partition);
17879 				if (rval == 0) {
17880 					ST_RECOV(ST_DEVINFO, st_label,
17881 					    CE_NOTE, "reestablished FORW"
17882 					    " write command retrying\n");
17883 					return (EAGAIN);
17884 				}
17885 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17886 				    "Seek to block %"PRId64" returned %d\n",
17887 				    ei->ei_expected_pos.lgclblkno - count,
17888 				    rval);
17889 			} else {
17890 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17891 				    "Not expected transfers_data = %d "
17892 				    "difference = %"PRId64,
17893 				    cmd_att->transfers_data, difference);
17894 			}
17895 
17896 			return (EIO);
17897 
17898 		} else if (cmd_att->chg_tape_direction == DIR_REVC) {
17899 			/* Don't think we can write backwards */
17900 			ASSERT(cmd_att->transfers_data != TRAN_WRTE);
17901 			difference =
17902 			    read->lgclblkno - ei->ei_expected_pos.lgclblkno;
17903 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17904 			    "difference between expected and actual is %"
17905 			    PRId64"\n", difference);
17906 			if (count == difference && reposition == 0) {
17907 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17908 				    "Found failed REVC command, retrying\n");
17909 				return (EAGAIN);
17910 			}
17911 			if ((read->lgclblkno == 0) ||
17912 			    ((difference > 0) && (difference < count))) {
17913 				rval = st_logical_block_locate(un,
17914 				    st_uscsi_rcmd, read,
17915 				    ei->ei_expected_pos.lgclblkno + count,
17916 				    ei->ei_expected_pos.partition);
17917 				if (rval == 0) {
17918 					ST_RECOV(ST_DEVINFO, st_label,
17919 					    CE_NOTE, "reestablished REVC"
17920 					    " command retrying\n");
17921 					return (EAGAIN);
17922 				}
17923 			/* This handles read ahead in reverse direction */
17924 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17925 			    (difference < 0) || (reposition == 1)) {
17926 				rval = st_logical_block_locate(un,
17927 				    st_uscsi_rcmd, read,
17928 				    ei->ei_expected_pos.lgclblkno - count,
17929 				    ei->ei_expected_pos.partition);
17930 				if (rval == 0) {
17931 					ST_RECOV(ST_DEVINFO, st_label,
17932 					    CE_NOTE, "reestablished REVC"
17933 					    " read command retrying\n");
17934 					return (EAGAIN);
17935 				}
17936 			} else {
17937 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17938 				    "Not expected transfers_data = %d "
17939 				    "difference = %"PRId64,
17940 				    cmd_att->transfers_data, difference);
17941 			}
17942 			return (EIO);
17943 
17944 		} else {
17945 			/*
17946 			 * Commands that change tape position either
17947 			 * direction or don't change position should not
17948 			 * get here.
17949 			 */
17950 			ASSERT(0);
17951 		}
17952 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17953 		    "Didn't find a recoverable position, Failing\n");
17954 
17955 	/*
17956 	 * Command that changes tape position and can only be recovered
17957 	 * by going back to the point of origin and retrying.
17958 	 *
17959 	 * Example SCMD_SPACE.
17960 	 */
17961 	} else if (cmd_att->recov_pos_type == POS_STARTING) {
17962 		/*
17963 		 * This type of command stores the starting position.
17964 		 * If the read position is the starting position,
17965 		 * reissue the command.
17966 		 */
17967 		if (ei->ei_expected_pos.lgclblkno == read->lgclblkno) {
17968 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17969 			    "Found Space command at starting position, "
17970 			    "Reissuing\n");
17971 			return (EAGAIN);
17972 		}
17973 		/*
17974 		 * Not in the position that the command was originally issued,
17975 		 * Attempt to locate to that position.
17976 		 */
17977 		rval = st_logical_block_locate(un, st_uscsi_rcmd, read,
17978 		    ei->ei_expected_pos.lgclblkno,
17979 		    ei->ei_expected_pos.partition);
17980 		if (rval) {
17981 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17982 			    "Found Space at an unexpected position and locate "
17983 			    "back to starting position failed\n");
17984 			return (EIO);
17985 		}
17986 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17987 		    "Found Space at an unexpected position and locate "
17988 		    "back to starting position worked, Reissuing\n");
17989 		return (EAGAIN);
17990 	}
17991 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17992 	    "Unhandled attribute/expected position", &ei->ei_expected_pos);
17993 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17994 	    "Read position above did not make sense", read);
17995 	ASSERT(0);
17996 	return (EIO);
17997 }
17998 
17999 static errstate
18000 st_recover_reissue_pkt(struct scsi_tape *un, struct scsi_pkt *oldpkt)
18001 {
18002 	buf_t *bp;
18003 	buf_t *pkt_bp;
18004 	struct scsi_pkt *newpkt;
18005 	cmd_attribute const *attrib;
18006 	recov_info *rcv = oldpkt->pkt_private;
18007 	uint_t cdblen;
18008 	int queued = 0;
18009 	int rval;
18010 	int flags = 0;
18011 	int stat_size =
18012 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
18013 
18014 	ST_FUNC(ST_DEVINFO, st_recover_reissue_pkt);
18015 
18016 	bp = rcv->cmd_bp;
18017 
18018 	if (rcv->privatelen == sizeof (recov_info)) {
18019 		attrib = rcv->cmd_attrib;
18020 	} else {
18021 		attrib = st_lookup_cmd_attribute(oldpkt->pkt_cdbp[0]);
18022 	}
18023 
18024 	/*
18025 	 * Some non-uscsi commands use the b_bcount for values that
18026 	 * have nothing to do with how much data is transfered.
18027 	 * In those cases we need to hide the buf_t from scsi_init_pkt().
18028 	 */
18029 	if ((BP_UCMD(bp)) && (bp->b_bcount)) {
18030 		pkt_bp = bp;
18031 	} else if (attrib->transfers_data == TRAN_NONE) {
18032 		pkt_bp = NULL;
18033 	} else {
18034 		pkt_bp = bp;
18035 	}
18036 
18037 	/*
18038 	 * if this is a queued command make sure it the only one in the
18039 	 * run queue.
18040 	 */
18041 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
18042 		ASSERT(un->un_runqf == un->un_runql);
18043 		ASSERT(un->un_runqf == bp);
18044 		queued = 1;
18045 	}
18046 
18047 	cdblen = scsi_cdb_size[CDB_GROUPID(oldpkt->pkt_cdbp[0])];
18048 
18049 	if (pkt_bp == un->un_rqs_bp) {
18050 		flags |= PKT_CONSISTENT;
18051 		stat_size = 1;
18052 	}
18053 
18054 	newpkt = scsi_init_pkt(ROUTE, NULL, pkt_bp, cdblen,
18055 	    stat_size, rcv->privatelen, flags, NULL_FUNC, NULL);
18056 	if (newpkt == NULL) {
18057 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
18058 		    "Reissue pkt scsi_init_pkt() failure\n");
18059 		return (COMMAND_DONE_ERROR);
18060 	}
18061 
18062 	ASSERT(newpkt->pkt_resid == 0);
18063 	bp->b_flags &= ~(B_DONE);
18064 	bp->b_resid = 0;
18065 	st_bioerror(bp, 0);
18066 
18067 	bcopy(oldpkt->pkt_private, newpkt->pkt_private, rcv->privatelen);
18068 
18069 	newpkt->pkt_comp = oldpkt->pkt_comp;
18070 	newpkt->pkt_time = oldpkt->pkt_time;
18071 
18072 	bzero(newpkt->pkt_scbp, stat_size);
18073 	bcopy(oldpkt->pkt_cdbp, newpkt->pkt_cdbp, cdblen);
18074 
18075 	newpkt->pkt_state = 0;
18076 	newpkt->pkt_statistics = 0;
18077 
18078 	/*
18079 	 * oldpkt passed in was a copy of the original.
18080 	 * to distroy we need the address of the original.
18081 	 */
18082 	oldpkt = BP_PKT(bp);
18083 
18084 	if (oldpkt == un->un_rqs) {
18085 		ASSERT(bp == un->un_rqs_bp);
18086 		un->un_rqs = newpkt;
18087 	}
18088 
18089 	SET_BP_PKT(bp, newpkt);
18090 
18091 	scsi_destroy_pkt(oldpkt);
18092 
18093 	rval = st_transport(un, newpkt);
18094 	if (rval == TRAN_ACCEPT) {
18095 		return (JUST_RETURN);
18096 	}
18097 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
18098 	    "Reissue pkt st_transport(0x%x) failure\n", rval);
18099 	if (rval != TRAN_BUSY) {
18100 		return (COMMAND_DONE_ERROR);
18101 	}
18102 	mutex_exit(ST_MUTEX);
18103 	rval = st_handle_start_busy(un, bp, ST_TRAN_BUSY_TIMEOUT, queued);
18104 	mutex_enter(ST_MUTEX);
18105 	if (rval) {
18106 		return (COMMAND_DONE_ERROR);
18107 	}
18108 
18109 	return (JUST_RETURN);
18110 }
18111 
18112 static int
18113 st_transport(struct scsi_tape *un, struct scsi_pkt *pkt)
18114 {
18115 	int status;
18116 
18117 	ST_FUNC(ST_DEVINFO, st_transport);
18118 
18119 	ST_CDB(ST_DEVINFO, "transport CDB", (caddr_t)pkt->pkt_cdbp);
18120 
18121 	mutex_exit(ST_MUTEX);
18122 
18123 	status = scsi_transport(pkt);
18124 
18125 	mutex_enter(ST_MUTEX);
18126 
18127 	return (status);
18128 }
18129 
18130 /*
18131  * Removed the buf_t bp from the queue referenced to by head and tail.
18132  * Returns the buf_t pointer if it is found in the queue.
18133  * Returns NULL if it is not found.
18134  */
18135 static buf_t *
18136 st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp)
18137 {
18138 	buf_t *runqbp;
18139 	buf_t *prevbp = NULL;
18140 
18141 	for (runqbp = *head; runqbp != 0; runqbp = runqbp->av_forw) {
18142 		if (runqbp == bp) {
18143 			/* found it, is it at the head? */
18144 			if (runqbp == *head) {
18145 				*head = bp->av_forw;
18146 			} else {
18147 				prevbp->av_forw = bp->av_forw;
18148 			}
18149 			if (*tail == bp) {
18150 				*tail = prevbp;
18151 			}
18152 			bp->av_forw = NULL;
18153 			return (bp); /* found and removed */
18154 		}
18155 		prevbp = runqbp;
18156 	}
18157 	return (NULL);
18158 }
18159 
18160 /*
18161  * Adds a buf_t to the queue pointed to by head and tail.
18162  * Adds it either to the head end or the tail end based on which
18163  * the passed variable end (head or tail) points at.
18164  */
18165 static void
18166 st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp)
18167 {
18168 
18169 	bp->av_forw = NULL;
18170 	if (*head) {
18171 		/* Queue is not empty */
18172 		if (end == *head) {
18173 			/* Add at front of queue */
18174 			bp->av_forw = *head;
18175 			*head = bp;
18176 		} else if (end == *tail) {
18177 			/* Add at end of queue */
18178 			(*tail)->av_forw = bp;
18179 			*tail = bp;
18180 		} else {
18181 			ASSERT(0);
18182 		}
18183 	} else {
18184 		/* Queue is empty */
18185 		*head = bp;
18186 		*tail = bp;
18187 	}
18188 }
18189 
18190 
18191 static uint64_t
18192 st_get_cdb_g0_rw_count(uchar_t *cdb)
18193 {
18194 	uint64_t count;
18195 
18196 	if ((cdb[1]) & 1) {
18197 		/* fixed block mode, the count is the number of blocks */
18198 		count =
18199 		    cdb[2] << 16 |
18200 		    cdb[3] << 8 |
18201 		    cdb[4];
18202 	} else {
18203 		/* variable block mode, the count is the block size */
18204 		count = 1;
18205 	}
18206 	return (count);
18207 }
18208 
18209 static uint64_t
18210 st_get_cdb_g0_sign_count(uchar_t *cdb)
18211 {
18212 	uint64_t count;
18213 
18214 	count =
18215 	    cdb[2] << 16 |
18216 	    cdb[3] << 8 |
18217 	    cdb[4];
18218 	/*
18219 	 * If the sign bit of the 3 byte value is set, extended it.
18220 	 */
18221 	if (count & 0x800000) {
18222 		count |= 0xffffffffff000000;
18223 	}
18224 	return (count);
18225 }
18226 
18227 static uint64_t
18228 st_get_cdb_g0_count(uchar_t *cdb)
18229 {
18230 	uint64_t count;
18231 
18232 	count =
18233 	    cdb[2] << 16 |
18234 	    cdb[3] << 8 |
18235 	    cdb[4];
18236 	return (count);
18237 }
18238 
18239 static uint64_t
18240 st_get_cdb_g5_rw_cnt(uchar_t *cdb)
18241 {
18242 	uint64_t count;
18243 
18244 	if ((cdb[1]) & 1) {
18245 		/* fixed block mode */
18246 		count =
18247 		    cdb[12] << 16 |
18248 		    cdb[13] << 8 |
18249 		    cdb[14];
18250 	} else {
18251 		/* variable block mode */
18252 		count = 1;
18253 	}
18254 	return (count);
18255 }
18256 
18257 static uint64_t
18258 st_get_no_count(uchar_t *cdb)
18259 {
18260 	ASSERT(cdb[0] == SCMD_REWIND);
18261 	return ((uint64_t)cdb[0]);
18262 }
18263 
18264 static uint64_t
18265 st_get_load_options(uchar_t *cdb)
18266 {
18267 	return ((uint64_t)(cdb[4] | (LD_HOLD << 1)));
18268 }
18269 
18270 static uint64_t
18271 st_get_erase_options(uchar_t *cdb)
18272 {
18273 	return (cdb[1] | (cdb[0] << 8));
18274 }
18275 
18276 static uint64_t
18277 st_get_cdb_g1_lba(uchar_t *cdb)
18278 {
18279 	uint64_t lba;
18280 
18281 	lba =
18282 	    cdb[3] << 24 |
18283 	    cdb[4] << 16 |
18284 	    cdb[5] << 8 |
18285 	    cdb[6];
18286 	return (lba);
18287 }
18288 
18289 static uint64_t
18290 st_get_cdb_g5_count(uchar_t *cdb)
18291 {
18292 	uint64_t count =
18293 	    cdb[12] << 16 |
18294 	    cdb[13] << 8 |
18295 	    cdb[14];
18296 
18297 	return (count);
18298 }
18299 
18300 static uint64_t
18301 st_get_cdb_g4g5_cnt(uchar_t *cdb)
18302 {
18303 	uint64_t lba;
18304 
18305 	lba =
18306 	    (uint64_t)cdb[4] << 56 |
18307 	    (uint64_t)cdb[5] << 48 |
18308 	    (uint64_t)cdb[6] << 40 |
18309 	    (uint64_t)cdb[7] << 32 |
18310 	    (uint64_t)cdb[8] << 24 |
18311 	    (uint64_t)cdb[9] << 16 |
18312 	    (uint64_t)cdb[10] << 8 |
18313 	    (uint64_t)cdb[11];
18314 	return (lba);
18315 }
18316 
18317 static const cmd_attribute cmd_attributes[] = {
18318 	{ SCMD_READ,
18319 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_READ, POS_EXPECTED,
18320 	    0, 0, 0, st_get_cdb_g0_rw_count },
18321 	{ SCMD_WRITE,
18322 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18323 	    0, 0, 0, st_get_cdb_g0_rw_count },
18324 	{ SCMD_TEST_UNIT_READY,
18325 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18326 	    0, 0, 0 },
18327 	{ SCMD_REWIND,
18328 	    1, 1, 1, 0, 0, DIR_REVC, TRAN_NONE, POS_EXPECTED,
18329 	    0, 0, 0, st_get_no_count },
18330 	{ SCMD_REQUEST_SENSE,
18331 	    0, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18332 	    0, 0, 0 },
18333 	{ SCMD_READ_BLKLIM,
18334 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18335 	    0, 0, 0 },
18336 	{ SCMD_READ_G4,
18337 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_READ, POS_EXPECTED,
18338 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18339 	{ SCMD_WRITE_G4,
18340 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18341 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18342 	{ SCMD_READ_REVERSE,
18343 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18344 	    0, 0, 0, st_get_cdb_g0_rw_count },
18345 	{ SCMD_READ_REVERSE_G4,
18346 	    1, 0, 1, 1, 1, DIR_REVC, TRAN_READ, POS_EXPECTED,
18347 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18348 	{ SCMD_WRITE_FILE_MARK,
18349 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18350 	    0, 0, 0, st_get_cdb_g0_count },
18351 	{ SCMD_WRITE_FILE_MARK_G4,
18352 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18353 	    0, 0, 0, st_get_cdb_g5_count, st_get_cdb_g4g5_cnt },
18354 	{ SCMD_SPACE,
18355 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18356 	    0, 0, 0, st_get_cdb_g0_sign_count },
18357 	{ SCMD_SPACE_G4,
18358 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18359 	    0, 0, 0, st_get_cdb_g4g5_cnt },
18360 	{ SCMD_INQUIRY,
18361 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18362 	    0, 0, 0 },
18363 	{ SCMD_VERIFY_G0,
18364 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18365 	    0, 0, 0, st_get_cdb_g0_rw_count },
18366 	{ SCMD_VERIFY_G4,
18367 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18368 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18369 	{ SCMD_RECOVER_BUF,
18370 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18371 	    0, 0, 0 },
18372 	{ SCMD_MODE_SELECT,
18373 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18374 	    0, 0, 0 },
18375 	{ SCMD_RESERVE,
18376 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18377 	    0, 0, 0 },
18378 	{ SCMD_RELEASE,
18379 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18380 	    0, 0, 0 },
18381 	{ SCMD_ERASE,
18382 	    1, 0, 1, 1, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18383 	    0, 0, 0, st_get_erase_options },
18384 	{ SCMD_MODE_SENSE,
18385 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18386 	    0, 0, 0 },
18387 	{ SCMD_LOAD,
18388 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18389 	    0, 0, 0, st_get_load_options },
18390 	{ SCMD_GDIAG,
18391 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18392 	    1, 0, 0 },
18393 	{ SCMD_SDIAG,
18394 	    1, 0, 1, 1, 0, DIR_EITH, TRAN_WRTE, POS_EXPECTED,
18395 	    1, 0, 0 },
18396 	{ SCMD_DOORLOCK,
18397 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18398 	    0, 4, 3 },
18399 	{ SCMD_LOCATE,
18400 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18401 	    0, 0, 0, NULL, st_get_cdb_g1_lba },
18402 	{ SCMD_READ_POSITION,
18403 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18404 	    0, 0, 0 },
18405 	{ SCMD_WRITE_BUFFER,
18406 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18407 	    1, 0, 0 },
18408 	{ SCMD_READ_BUFFER,
18409 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18410 	    1, 0, 0 },
18411 	{ SCMD_REPORT_DENSITIES,
18412 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18413 	    0, 0, 0 },
18414 	{ SCMD_LOG_SELECT_G1,
18415 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18416 	    0, 0, 0 },
18417 	{ SCMD_LOG_SENSE_G1,
18418 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18419 	    0, 0, 0 },
18420 	{ SCMD_PRIN,
18421 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18422 	    0, 0, 0 },
18423 	{ SCMD_PROUT,
18424 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18425 	    0, 0, 0 },
18426 	{ SCMD_READ_ATTRIBUTE,
18427 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18428 	    0, 0, 0 },
18429 	{ SCMD_WRITE_ATTRIBUTE,
18430 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18431 	    0, 0, 0 },
18432 	{ SCMD_LOCATE_G4,
18433 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18434 	    0, 0, 0, NULL, st_get_cdb_g4g5_cnt },
18435 	{ SCMD_REPORT_LUNS,
18436 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18437 	    0, 0, 0 },
18438 	{ SCMD_SVC_ACTION_IN_G5,
18439 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18440 	    0, 0, 0 },
18441 	{ SCMD_MAINTENANCE_IN,
18442 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18443 	    0, 0, 0 },
18444 	{ SCMD_MAINTENANCE_OUT,
18445 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18446 	    0, 0, 0 },
18447 	{ 0xff, /* Default attribute for unsupported commands */
18448 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_STARTING,
18449 	    1, 0, 0, NULL, NULL }
18450 };
18451 
18452 static const cmd_attribute *
18453 st_lookup_cmd_attribute(unsigned char cmd)
18454 {
18455 	int i;
18456 	cmd_attribute const *attribute;
18457 
18458 	for (i = 0; i < ST_NUM_MEMBERS(cmd_attributes); i++) {
18459 		attribute = &cmd_attributes[i];
18460 		if (attribute->cmd == cmd) {
18461 			return (attribute);
18462 		}
18463 	}
18464 	ASSERT(attribute);
18465 	return (attribute);
18466 }
18467 
18468 static int
18469 st_reset(struct scsi_tape *un, int reset_type)
18470 {
18471 	int rval;
18472 
18473 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
18474 
18475 	ST_FUNC(ST_DEVINFO, st_reset);
18476 	un->un_rsvd_status |= ST_INITIATED_RESET;
18477 	mutex_exit(ST_MUTEX);
18478 	do {
18479 		rval = scsi_reset(&un->un_sd->sd_address, reset_type);
18480 		if (rval == 0) {
18481 			switch (reset_type) {
18482 			case RESET_LUN:
18483 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18484 				    "LUN reset failed trying target reset");
18485 				reset_type = RESET_TARGET;
18486 				break;
18487 			case RESET_TARGET:
18488 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18489 				    "target reset failed trying bus reset");
18490 				reset_type = RESET_BUS;
18491 				break;
18492 			case RESET_BUS:
18493 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18494 				    "bus reset failed trying all reset");
18495 				reset_type = RESET_ALL;
18496 			default:
18497 				mutex_enter(ST_MUTEX);
18498 				return (rval);
18499 			}
18500 		}
18501 	} while (rval == 0);
18502 	mutex_enter(ST_MUTEX);
18503 	return (rval);
18504 }
18505 
18506 #define	SAS_TLR_MOD_LEN sizeof (struct seq_mode)
18507 static int
18508 st_set_target_TLR_mode(struct scsi_tape *un, ubufunc_t ubf)
18509 {
18510 	int ret;
18511 	int amount = SAS_TLR_MOD_LEN;
18512 	struct seq_mode *mode_data;
18513 
18514 	ST_FUNC(ST_DEVINFO, st_set_target_TLR_mode);
18515 
18516 	mode_data = kmem_zalloc(SAS_TLR_MOD_LEN, KM_SLEEP);
18517 	ret = st_gen_mode_sense(un, ubf, 0x18, mode_data, amount);
18518 	if (ret != DDI_SUCCESS) {
18519 		if (ret != EACCES)
18520 			un->un_tlr_flag = TLR_NOT_SUPPORTED;
18521 		goto out;
18522 	}
18523 	if (mode_data->data_len != amount + 1) {
18524 		amount = mode_data->data_len + 1;
18525 	}
18526 	/* Must be SAS protocol */
18527 	if (mode_data->page.saslun.protocol_id != 6) {
18528 		un->un_tlr_flag = TLR_NOT_SUPPORTED;
18529 		ret = ENOTSUP;
18530 		goto out;
18531 	}
18532 	if (un->un_tlr_flag == TLR_SAS_ONE_DEVICE) {
18533 		if (mode_data->page.saslun.tran_layer_ret == 1)
18534 			goto out;
18535 		mode_data->page.saslun.tran_layer_ret = 1;
18536 	} else {
18537 		if (mode_data->page.saslun.tran_layer_ret == 0)
18538 			goto out;
18539 		mode_data->page.saslun.tran_layer_ret = 0;
18540 	}
18541 	ret = st_gen_mode_select(un, ubf, mode_data, amount);
18542 	if (ret != DDI_SUCCESS) {
18543 		if (ret != EACCES)
18544 			un->un_tlr_flag = TLR_NOT_SUPPORTED;
18545 	} else {
18546 		if (mode_data->page.saslun.tran_layer_ret == 0)
18547 			un->un_tlr_flag = TLR_NOT_KNOWN;
18548 		else
18549 			un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
18550 	}
18551 #ifdef STDEBUG
18552 	st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG, "TLR data sent",
18553 	    (char *)mode_data, amount);
18554 #endif
18555 out:
18556 	kmem_free(mode_data, SAS_TLR_MOD_LEN);
18557 	return (ret);
18558 }
18559 
18560 
18561 static void
18562 st_reset_notification(caddr_t arg)
18563 {
18564 	struct scsi_tape *un = (struct scsi_tape *)arg;
18565 
18566 	ST_FUNC(ST_DEVINFO, st_reset_notification);
18567 	mutex_enter(ST_MUTEX);
18568 
18569 	un->un_unit_attention_flags |= 2;
18570 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
18571 	    ST_RESERVE) {
18572 		un->un_rsvd_status |= ST_LOST_RESERVE;
18573 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18574 		    "Lost Reservation notification");
18575 	} else {
18576 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18577 		    "reset notification");
18578 	}
18579 
18580 	if ((un->un_restore_pos == 0) &&
18581 	    (un->un_state == ST_STATE_CLOSED) ||
18582 	    (un->un_state == ST_STATE_OPEN_PENDING_IO) ||
18583 	    (un->un_state == ST_STATE_CLOSING)) {
18584 		un->un_restore_pos = 1;
18585 	}
18586 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
18587 	    "reset and state was %d\n", un->un_state);
18588 	mutex_exit(ST_MUTEX);
18589 }
18590