xref: /titanic_41/usr/src/uts/common/io/scsi/targets/st.c (revision 837c1ac4e72b7d86278cca88b1075af557f7d161)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * SCSI	 SCSA-compliant and not-so-DDI-compliant Tape Driver
29  */
30 
31 #if defined(lint) && !defined(DEBUG)
32 #define	DEBUG	1
33 #endif
34 
35 #include <sys/modctl.h>
36 #include <sys/scsi/scsi.h>
37 #include <sys/mtio.h>
38 #include <sys/scsi/targets/stdef.h>
39 #include <sys/file.h>
40 #include <sys/kstat.h>
41 #include <sys/ddidmareq.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/byteorder.h>
45 
46 #define	IOSP	KSTAT_IO_PTR(un->un_stats)
47 /*
48  * stats maintained only for reads/writes as commands
49  * like rewind etc skew the wait/busy times
50  */
51 #define	IS_RW(bp) 	((bp)->b_bcount > 0)
52 #define	ST_DO_KSTATS(bp, kstat_function) \
53 	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
54 		kstat_function(IOSP); \
55 	}
56 
57 #define	ST_DO_ERRSTATS(un, x)  \
58 	if (un->un_errstats) { \
59 		struct st_errstats *stp; \
60 		stp = (struct st_errstats *)un->un_errstats->ks_data; \
61 		stp->x.value.ul++; \
62 	}
63 
64 #define	FILL_SCSI1_LUN(devp, pkt) 					\
65 	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
66 		int _lun;						\
67 		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
68 		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
69 		if (_lun > 0) {						\
70 			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
71 			    _lun;					\
72 		}							\
73 	}
74 
75 /*
76  * get an available contig mem header, cp.
77  * when big_enough is true, we will return NULL, if no big enough
78  * contig mem is found.
79  * when big_enough is false, we will try to find cp containing big
80  * enough contig mem. if not found, we will ruturn the last cp available.
81  *
82  * used by st_get_contig_mem()
83  */
84 #define	ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough) {		\
85 	struct contig_mem *tmp_cp = NULL;				\
86 	for ((cp) = (un)->un_contig_mem;				\
87 	    (cp) != NULL;						\
88 	    tmp_cp = (cp), (cp) = (cp)->cm_next) { 			\
89 		if (((cp)->cm_len >= (len)) || 				\
90 		    (!(big_enough) && ((cp)->cm_next == NULL))) { 	\
91 			if (tmp_cp == NULL) { 				\
92 				(un)->un_contig_mem = (cp)->cm_next; 	\
93 			} else { 					\
94 				tmp_cp->cm_next = (cp)->cm_next; 	\
95 			} 						\
96 			(cp)->cm_next = NULL; 				\
97 			(un)->un_contig_mem_available_num--; 		\
98 			break; 						\
99 		} 							\
100 	} 								\
101 }
102 
103 #define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
104 #define	COPY_POS(dest, source) bcopy(source, dest, sizeof (tapepos_t))
105 #define	ISALNUM(byte) \
106 	(((byte) >= 'a' && (byte) <= 'z') || \
107 	((byte) >= 'A' && (byte) <= 'Z') || \
108 	((byte) >= '0' && (byte) <= '9'))
109 
110 #define	ONE_K	1024
111 
112 #define	MAX_SPACE_CNT(cnt) if (cnt >= 0) { \
113 		if (cnt > MIN(SP_CNT_MASK, INT32_MAX)) \
114 			return (EINVAL); \
115 	} else { \
116 		if (-(cnt) > MIN(SP_CNT_MASK, INT32_MAX)) \
117 			return (EINVAL); \
118 	} \
119 
120 /*
121  * Global External Data Definitions
122  */
123 extern struct scsi_key_strings scsi_cmds[];
124 extern uchar_t	scsi_cdb_size[];
125 
126 /*
127  * Local Static Data
128  */
129 static void *st_state;
130 static char *const st_label = "st";
131 static volatile int st_recov_sz = sizeof (recov_info);
132 static const char mp_misconf[] = {
133 	"St Tape is misconfigured, MPxIO enabled and "
134 	"tape-command-recovery-disable set in st.conf\n"
135 };
136 
137 #ifdef	__x86
138 /*
139  * We need to use below DMA attr to alloc physically contiguous
140  * memory to do I/O in big block size
141  */
142 static ddi_dma_attr_t st_contig_mem_dma_attr = {
143 	DMA_ATTR_V0,    /* version number */
144 	0x0,		/* lowest usable address */
145 	0xFFFFFFFFull,  /* high DMA address range */
146 	0xFFFFFFFFull,  /* DMA counter register */
147 	1,		/* DMA address alignment */
148 	1,		/* DMA burstsizes */
149 	1,		/* min effective DMA size */
150 	0xFFFFFFFFull,  /* max DMA xfer size */
151 	0xFFFFFFFFull,  /* segment boundary */
152 	1,		/* s/g list length */
153 	1,		/* granularity of device */
154 	0		/* DMA transfer flags */
155 };
156 
157 static ddi_device_acc_attr_t st_acc_attr = {
158 	DDI_DEVICE_ATTR_V0,
159 	DDI_NEVERSWAP_ACC,
160 	DDI_STRICTORDER_ACC
161 };
162 
163 /* set limitation for the number of contig_mem */
164 static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
165 #endif
166 
167 /*
168  * Tunable parameters
169  *
170  * DISCLAIMER
171  * ----------
172  * These parameters are intended for use only in system testing; if you use
173  * them in production systems, you do so at your own risk. Altering any
174  * variable not listed below may cause unpredictable system behavior.
175  *
176  * st_check_media_time
177  *
178  *   Three second state check
179  *
180  * st_allow_large_xfer
181  *
182  *   Gated with ST_NO_RECSIZE_LIMIT
183  *
184  *   0 - Transfers larger than 64KB will not be allowed
185  *       regardless of the setting of ST_NO_RECSIZE_LIMIT
186  *   1 - Transfers larger than 64KB will be allowed
187  *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
188  *
189  * st_report_soft_errors_on_close
190  *
191  *  Gated with ST_SOFT_ERROR_REPORTING
192  *
193  *  0 - Errors will not be reported on close regardless
194  *      of the setting of ST_SOFT_ERROR_REPORTING
195  *
196  *  1 - Errors will be reported on close if
197  *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
198  */
199 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
200 static int st_retry_count	= ST_RETRY_COUNT;
201 
202 static int st_io_time		= ST_IO_TIME;
203 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
204 
205 static int st_space_time	= ST_SPACE_TIME;
206 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
207 
208 static int st_error_level	= SCSI_ERR_RETRYABLE;
209 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
210 
211 static int st_max_throttle	= ST_MAX_THROTTLE;
212 
213 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
214 
215 static int st_allow_large_xfer = 1;
216 static int st_report_soft_errors_on_close = 1;
217 
218 /*
219  * End of tunable parameters list
220  */
221 
222 
223 
224 /*
225  * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
226  *
227  * Asynchronous I/O's main offering is that it is a non-blocking way to do
228  * reads and writes.  The driver will queue up all the requests it gets and
229  * have them ready to transport to the HBA.  Unfortunately, we cannot always
230  * just ship the I/O requests to the HBA, as there errors and exceptions
231  * that may happen when we don't want the HBA to continue.  Therein comes
232  * the flush-on-errors capability.  If the HBA supports it, then st will
233  * send in st_max_throttle I/O requests at the same time.
234  *
235  * Persistent errors : This was also reasonably simple.  In the interrupt
236  * routines, if there was an error or exception (FM, LEOT, media error,
237  * transport error), the persistent error bits are set and shuts everything
238  * down, but setting the throttle to zero.  If we hit and exception in the
239  * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
240  * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
241  * the appropriate error, and this will preserve order. Of course, depending
242  * on the exception we have to show a zero read or write before we show
243  * errors back to the application.
244  */
245 
246 extern const int st_ndrivetypes;	/* defined in st_conf.c */
247 extern const struct st_drivetype st_drivetypes[];
248 extern const char st_conf_version[];
249 
250 #ifdef STDEBUG
251 static int st_soft_error_report_debug = 0;
252 volatile int st_debug = 0;
253 static volatile dev_info_t *st_lastdev;
254 static kmutex_t st_debug_mutex;
255 #endif
256 
257 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
258 
259 static const struct vid_drivetype {
260 	char	*vid;
261 	char	type;
262 } st_vid_dt[] = {
263 	{"LTO-CVE ",	MT_LTO},
264 	{"QUANTUM ",    MT_ISDLT},
265 	{"SONY    ",    MT_ISAIT},
266 	{"STK     ",	MT_ISSTK9840}
267 };
268 
269 static const struct driver_minor_data {
270 	char	*name;
271 	int	minor;
272 } st_minor_data[] = {
273 	/*
274 	 * The top 4 entries are for the default densities,
275 	 * don't alter their position.
276 	 */
277 	{"",	0},
278 	{"n",	MT_NOREWIND},
279 	{"b",	MT_BSD},
280 	{"bn",	MT_NOREWIND | MT_BSD},
281 	{"l",	MT_DENSITY1},
282 	{"m",	MT_DENSITY2},
283 	{"h",	MT_DENSITY3},
284 	{"c",	MT_DENSITY4},
285 	{"u",	MT_DENSITY4},
286 	{"ln",	MT_DENSITY1 | MT_NOREWIND},
287 	{"mn",	MT_DENSITY2 | MT_NOREWIND},
288 	{"hn",	MT_DENSITY3 | MT_NOREWIND},
289 	{"cn",	MT_DENSITY4 | MT_NOREWIND},
290 	{"un",	MT_DENSITY4 | MT_NOREWIND},
291 	{"lb",	MT_DENSITY1 | MT_BSD},
292 	{"mb",	MT_DENSITY2 | MT_BSD},
293 	{"hb",	MT_DENSITY3 | MT_BSD},
294 	{"cb",	MT_DENSITY4 | MT_BSD},
295 	{"ub",	MT_DENSITY4 | MT_BSD},
296 	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
297 	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
298 	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
299 	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
300 	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
301 };
302 
303 /* strings used in many debug and warning messages */
304 static const char wr_str[]  = "write";
305 static const char rd_str[]  = "read";
306 static const char wrg_str[] = "writing";
307 static const char rdg_str[] = "reading";
308 static const char *space_strs[] = {
309 	"records",
310 	"filemarks",
311 	"sequential filemarks",
312 	"eod",
313 	"setmarks",
314 	"sequential setmarks",
315 	"Reserved",
316 	"Reserved"
317 };
318 static const char *load_strs[] = {
319 	"unload",		/* LD_UNLOAD		0 */
320 	"load",			/* LD_LOAD		1 */
321 	"retension",		/* LD_RETEN		2 */
322 	"load reten",		/* LD_LOAD | LD_RETEN	3 */
323 	"eod",			/* LD_EOT		4 */
324 	"load EOD",		/* LD_LOAD | LD_EOT	5 */
325 	"reten EOD",		/* LD_RETEN | LD_EOT	6 */
326 	"load reten EOD"	/* LD_LOAD|LD_RETEN|LD_EOT 7 */
327 	"hold",			/* LD_HOLD		8 */
328 	"load and hold"		/* LD_LOAD | LD_HOLD	9 */
329 };
330 
331 static const char *errstatenames[] = {
332 	"COMMAND_DONE",
333 	"COMMAND_DONE_ERROR",
334 	"COMMAND_DONE_ERROR_RECOVERED",
335 	"QUE_COMMAND",
336 	"QUE_BUSY_COMMAND",
337 	"QUE_SENSE",
338 	"JUST_RETURN",
339 	"COMMAND_DONE_EACCES",
340 	"QUE_LAST_COMMAND",
341 	"COMMAND_TIMEOUT",
342 	"PATH_FAILED",
343 	"DEVICE_RESET",
344 	"DEVICE_TAMPER",
345 	"ATTEMPT_RETRY"
346 };
347 
348 const char *bogusID = "Unknown Media ID";
349 
350 /* default density offsets in the table above */
351 #define	DEF_BLANK	0
352 #define	DEF_NOREWIND	1
353 #define	DEF_BSD		2
354 #define	DEF_BSD_NR	3
355 
356 /* Sense Key, ASC/ASCQ for which tape ejection is needed */
357 
358 static struct tape_failure_code {
359 	uchar_t key;
360 	uchar_t add_code;
361 	uchar_t qual_code;
362 } st_tape_failure_code[] = {
363 	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
364 	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
365 	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
366 	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
367 	{ KEY_NOT_READY, 0x53, 0x00},
368 	{ 0xff}
369 };
370 
371 /*  clean bit position and mask */
372 
373 static struct cln_bit_position {
374 	ushort_t cln_bit_byte;
375 	uchar_t cln_bit_mask;
376 } st_cln_bit_position[] = {
377 	{ 21, 0x08},
378 	{ 70, 0xc0},
379 	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
380 };
381 
382 /*
383  * architecture dependent allocation restrictions. For x86, we'll set
384  * dma_attr_addr_hi to st_max_phys_addr and dma_attr_sgllen to
385  * st_sgl_size during _init().
386  */
387 #if defined(__sparc)
388 static ddi_dma_attr_t st_alloc_attr = {
389 	DMA_ATTR_V0,	/* version number */
390 	0x0,		/* lowest usable address */
391 	0xFFFFFFFFull,	/* high DMA address range */
392 	0xFFFFFFFFull,	/* DMA counter register */
393 	1,		/* DMA address alignment */
394 	1,		/* DMA burstsizes */
395 	1,		/* min effective DMA size */
396 	0xFFFFFFFFull,	/* max DMA xfer size */
397 	0xFFFFFFFFull,	/* segment boundary */
398 	1,		/* s/g list length */
399 	512,		/* granularity of device */
400 	0		/* DMA transfer flags */
401 };
402 #elif defined(__x86)
403 static ddi_dma_attr_t st_alloc_attr = {
404 	DMA_ATTR_V0,	/* version number */
405 	0x0,		/* lowest usable address */
406 	0x0,		/* high DMA address range [set in _init()] */
407 	0xFFFFull,	/* DMA counter register */
408 	512,		/* DMA address alignment */
409 	1,		/* DMA burstsizes */
410 	1,		/* min effective DMA size */
411 	0xFFFFFFFFull,	/* max DMA xfer size */
412 	0xFFFFFFFFull,  /* segment boundary */
413 	0,		/* s/g list length */
414 	512,		/* granularity of device [set in _init()] */
415 	0		/* DMA transfer flags */
416 };
417 uint64_t st_max_phys_addr = 0xFFFFFFFFull;
418 int st_sgl_size = 0xF;
419 
420 #endif
421 
422 /*
423  * Configuration Data:
424  *
425  * Device driver ops vector
426  */
427 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
428 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
429 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
430 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
431 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
432 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
433 static int st_strategy(struct buf *bp);
434 static int st_queued_strategy(buf_t *bp);
435 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
436 	cred_t *cred_p, int *rval_p);
437 extern int nulldev(), nodev();
438 
439 static struct cb_ops st_cb_ops = {
440 	st_open,		/* open */
441 	st_close,		/* close */
442 	st_queued_strategy,	/* strategy Not Block device but async checks */
443 	nodev,			/* print */
444 	nodev,			/* dump */
445 	st_read,		/* read */
446 	st_write,		/* write */
447 	st_ioctl,		/* ioctl */
448 	nodev,			/* devmap */
449 	nodev,			/* mmap */
450 	nodev,			/* segmap */
451 	nochpoll,		/* poll */
452 	ddi_prop_op,		/* cb_prop_op */
453 	0,			/* streamtab  */
454 	D_64BIT | D_MP | D_NEW | D_HOTPLUG |
455 	D_OPEN_RETURNS_EINTR,	/* cb_flag */
456 	CB_REV,			/* cb_rev */
457 	st_aread, 		/* async I/O read entry point */
458 	st_awrite		/* async I/O write entry point */
459 
460 };
461 
462 static int st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
463 		void **result);
464 static int st_probe(dev_info_t *dev);
465 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
466 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
467 
468 static struct dev_ops st_ops = {
469 	DEVO_REV,		/* devo_rev, */
470 	0,			/* refcnt  */
471 	st_info,		/* info */
472 	nulldev,		/* identify */
473 	st_probe,		/* probe */
474 	st_attach,		/* attach */
475 	st_detach,		/* detach */
476 	nodev,			/* reset */
477 	&st_cb_ops,		/* driver operations */
478 	(struct bus_ops *)0,	/* bus operations */
479 	nulldev,		/* power */
480 	ddi_quiesce_not_needed,	/* devo_quiesce */
481 };
482 
483 /*
484  * Local Function Declarations
485  */
486 static char *st_print_scsi_cmd(char cmd);
487 static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
488     char *title, char *cdb);
489 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
490     char *title, char *data, int len);
491 static int st_doattach(struct scsi_device *devp, int (*canwait)());
492 static void st_known_tape_type(struct scsi_tape *un);
493 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
494     struct st_drivetype *);
495 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
496     struct st_drivetype *);
497 static int st_get_conf_from_tape_drive(struct scsi_tape *, char *,
498     struct st_drivetype *);
499 static int st_get_densities_from_tape_drive(struct scsi_tape *,
500     struct st_drivetype *);
501 static int st_get_timeout_values_from_tape_drive(struct scsi_tape *,
502     struct st_drivetype *);
503 static int st_get_timeouts_value(struct scsi_tape *, uchar_t, ushort_t *,
504     ushort_t);
505 static int st_get_default_conf(struct scsi_tape *, char *,
506     struct st_drivetype *);
507 static int st_rw(dev_t dev, struct uio *uio, int flag);
508 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
509 static int st_find_eod(struct scsi_tape *un);
510 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
511 static int st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *, int flag);
512 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
513 static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
514 static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
515 static void st_start(struct scsi_tape *un);
516 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
517     clock_t timeout_interval, int queued);
518 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
519     clock_t timeout_interval);
520 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
521 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
522 static void st_init(struct scsi_tape *un);
523 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
524     int (*func)(caddr_t));
525 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
526     struct buf *bp, int (*func)(caddr_t));
527 static void st_intr(struct scsi_pkt *pkt);
528 static void st_set_state(struct scsi_tape *un, buf_t *bp);
529 static void st_test_append(struct buf *bp);
530 static int st_runout(caddr_t);
531 static int st_cmd(struct scsi_tape *un, int com, int64_t count, int wait);
532 static int st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com,
533     int64_t count);
534 static int st_set_compression(struct scsi_tape *un);
535 static int st_write_fm(dev_t dev, int wfm);
536 static int st_determine_generic(struct scsi_tape *un);
537 static int st_determine_density(struct scsi_tape *un, int rw);
538 static int st_get_density(struct scsi_tape *un);
539 static int st_set_density(struct scsi_tape *un);
540 static int st_loadtape(struct scsi_tape *un);
541 static int st_modesense(struct scsi_tape *un);
542 static int st_modeselect(struct scsi_tape *un);
543 static errstate st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
544 static int st_wrongtapetype(struct scsi_tape *un);
545 static errstate st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
546 static errstate st_handle_sense(struct scsi_tape *un, struct buf *bp,
547     tapepos_t *);
548 static errstate st_handle_autosense(struct scsi_tape *un, struct buf *bp,
549     tapepos_t *);
550 static int st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag);
551 static void st_update_error_stack(struct scsi_tape *un, struct scsi_pkt *pkt,
552     struct scsi_arq_status *cmd);
553 static void st_empty_error_stack(struct scsi_tape *un);
554 static errstate st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
555     struct scsi_arq_status *, tapepos_t *);
556 static int st_report_soft_errors(dev_t dev, int flag);
557 static void st_delayed_cv_broadcast(void *arg);
558 static int st_check_media(dev_t dev, enum mtio_state state);
559 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
560 static void st_intr_restart(void *arg);
561 static void st_start_restart(void *arg);
562 static int st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
563     struct seq_mode *page_data, int page_size);
564 static int st_change_block_size(struct scsi_tape *un, uint32_t nblksz);
565 static int st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
566     struct seq_mode *page_data, int page_size);
567 static int st_read_block_limits(struct scsi_tape *un,
568     struct read_blklim *read_blk);
569 static int st_report_density_support(struct scsi_tape *un,
570     uchar_t *density_data, size_t buflen);
571 static int st_report_supported_operation(struct scsi_tape *un,
572     uchar_t *oper_data, uchar_t option_code, ushort_t service_action);
573 static int st_tape_init(struct scsi_tape *un);
574 static void st_flush(struct scsi_tape *un);
575 static void st_set_pe_errno(struct scsi_tape *un);
576 static void st_hba_unflush(struct scsi_tape *un);
577 static void st_turn_pe_on(struct scsi_tape *un);
578 static void st_turn_pe_off(struct scsi_tape *un);
579 static void st_set_pe_flag(struct scsi_tape *un);
580 static void st_clear_pe(struct scsi_tape *un);
581 static void st_wait_for_io(struct scsi_tape *un);
582 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
583 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
584 static int st_reserve_release(struct scsi_tape *un, int command, ubufunc_t ubf);
585 static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb);
586 static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
587     int count);
588 static int st_take_ownership(struct scsi_tape *un, ubufunc_t ubf);
589 static int st_check_asc_ascq(struct scsi_tape *un);
590 static int st_check_clean_bit(struct scsi_tape *un);
591 static int st_check_alert_flags(struct scsi_tape *un);
592 static int st_check_sequential_clean_bit(struct scsi_tape *un);
593 static int st_check_sense_clean_bit(struct scsi_tape *un);
594 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
595 static void st_calculate_timeouts(struct scsi_tape *un);
596 static writablity st_is_drive_worm(struct scsi_tape *un);
597 static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
598     void *buf, size_t size, ubufunc_t bufunc);
599 static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
600     caddr_t dest, uchar_t page);
601 static int st_update_block_pos(struct scsi_tape *un, bufunc_t bf,
602     int post_space);
603 static int st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
604     read_p_types type, size_t data_sz, const caddr_t responce, int post_space);
605 static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
606 static int st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf,
607     tapepos_t *pos, uint64_t lblk, uchar_t partition);
608 static int st_mtfsf_ioctl(struct scsi_tape *un, int64_t files);
609 static int st_mtfsr_ioctl(struct scsi_tape *un, int64_t count);
610 static int st_mtbsf_ioctl(struct scsi_tape *un, int64_t files);
611 static int st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count);
612 static int st_mtbsr_ioctl(struct scsi_tape *un, int64_t num);
613 static int st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt);
614 static int st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt);
615 static int st_backward_space_files(struct scsi_tape *un, int64_t count,
616     int infront);
617 static int st_forward_space_files(struct scsi_tape *un, int64_t files);
618 static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
619     int32_t fileno);
620 static int st_space_to_begining_of_file(struct scsi_tape *un);
621 static int st_space_records(struct scsi_tape *un, int64_t records);
622 static int st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc);
623 static errstate st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
624     errstate onentry);
625 static void st_recover(void *arg);
626 static void st_recov_cb(struct scsi_pkt *pkt);
627 static int st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait);
628 static int st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
629     int flag);
630 static void st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
631     struct scsi_pkt *cmd);
632 static int st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf);
633 static int st_test_path_to_device(struct scsi_tape *un);
634 static int st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
635     read_pos_data_t *raw);
636 static int st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
637     read_pos_data_t *raw);
638 static int st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
639     cmd_attribute const * cmd_att, tapepos_t *read);
640 static errstate st_recover_reissue_pkt(struct scsi_tape *us,
641     struct scsi_pkt *pkt);
642 static int st_transport(struct scsi_tape *un, struct scsi_pkt *pkt);
643 static buf_t *st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp);
644 static void st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp);
645 static int st_reset(struct scsi_tape *un, int reset_type);
646 static void st_reset_notification(caddr_t arg);
647 static const cmd_attribute *st_lookup_cmd_attribute(unsigned char cmd);
648 
649 static int st_set_target_TLR_mode(struct scsi_tape *un, ubufunc_t ubf);
650 static int st_make_sure_mode_data_is_correct(struct scsi_tape *un,
651     ubufunc_t ubf);
652 
653 #ifdef	__x86
654 /*
655  * routines for I/O in big block size
656  */
657 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
658 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
659     int alloc_flags);
660 static int st_bigblk_xfer_done(struct buf *bp);
661 static struct buf *st_get_bigblk_bp(struct buf *bp);
662 #endif
663 static void st_print_position(dev_info_t *dev, char *label, uint_t level,
664     const char *comment, tapepos_t *pos);
665 
666 /*
667  * error statistics create/update functions
668  */
669 static int st_create_errstats(struct scsi_tape *, int);
670 static int st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf,
671     tapepos_t *pos);
672 
673 #ifdef STDEBUG
674 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
675 #endif /* STDEBUG */
676 static char *st_dev_name(dev_t dev);
677 
678 #if !defined(lint)
679 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
680     scsi_pkt buf uio scsi_cdb uscsi_cmd))
681 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
682 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", recov_info))
683 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
684 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
685 #endif
686 
687 /*
688  * autoconfiguration routines.
689  */
690 char _depends_on[] = "misc/scsi";
691 
692 static struct modldrv modldrv = {
693 	&mod_driverops,		/* Type of module. This one is a driver */
694 	"SCSI tape Driver", 	/* Name of the module. */
695 	&st_ops			/* driver ops */
696 };
697 
698 static struct modlinkage modlinkage = {
699 	MODREV_1, &modldrv, NULL
700 };
701 
702 /*
703  * Notes on Post Reset Behavior in the tape driver:
704  *
705  * When the tape drive is opened, the driver  attempts  to make sure that
706  * the tape head is positioned exactly where it was left when it was last
707  * closed  provided  the  medium  is not  changed.  If the tape  drive is
708  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
709  * of position due to reset) will happen when the first tape operation or
710  * I/O occurs.  The repositioning (if required) may not be possible under
711  * certain situations such as when the device firmware not able to report
712  * the medium  change in the REQUEST  SENSE data  because of a reset or a
713  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
714  * extraordinary  situations, where the driver fails to position the head
715  * at its  original  position,  it will fail the open the first  time, to
716  * save the applications from overwriting the data.  All further attempts
717  * to open the tape device will result in the driver  attempting  to load
718  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
719  * indicate  that further  attempts to open the tape device may result in
720  * the tape being  loaded at BOT will be printed on the  console.  If the
721  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
722  * original tape head  position,  will result in the failure of the first
723  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
724  * internal tape position  which will  necessitate  the  applications  to
725  * validate the position by using either a tape  positioning  ioctl (such
726  * as MTREW) or closing and reopening the tape device.
727  *
728  */
729 
730 int
731 _init(void)
732 {
733 	int e;
734 
735 	if (((e = ddi_soft_state_init(&st_state,
736 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
737 		return (e);
738 	}
739 
740 	if ((e = mod_install(&modlinkage)) != 0) {
741 		ddi_soft_state_fini(&st_state);
742 	} else {
743 #ifdef STDEBUG
744 		mutex_init(&st_debug_mutex, NULL, MUTEX_DRIVER, NULL);
745 #endif
746 
747 #if defined(__x86)
748 		/* set the max physical address for iob allocs on x86 */
749 		st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
750 
751 		/*
752 		 * set the sgllen for iob allocs on x86. If this is set less
753 		 * than the number of pages the buffer will take
754 		 * (taking into account alignment), it would force the
755 		 * allocator to try and allocate contiguous pages.
756 		 */
757 		st_alloc_attr.dma_attr_sgllen = st_sgl_size;
758 #endif
759 	}
760 
761 	return (e);
762 }
763 
764 int
765 _fini(void)
766 {
767 	int e;
768 
769 	if ((e = mod_remove(&modlinkage)) != 0) {
770 		return (e);
771 	}
772 
773 #ifdef STDEBUG
774 	mutex_destroy(&st_debug_mutex);
775 #endif
776 
777 	ddi_soft_state_fini(&st_state);
778 
779 	return (e);
780 }
781 
782 int
783 _info(struct modinfo *modinfop)
784 {
785 	return (mod_info(&modlinkage, modinfop));
786 }
787 
788 
789 static int
790 st_probe(dev_info_t *devi)
791 {
792 	int instance;
793 	struct scsi_device *devp;
794 	int rval;
795 
796 #if !defined(__sparc)
797 	char    *tape_prop;
798 	int	tape_prop_len;
799 #endif
800 
801 	ST_ENTR(devi, st_probe);
802 
803 	/* If self identifying device */
804 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
805 		return (DDI_PROBE_DONTCARE);
806 	}
807 
808 #if !defined(__sparc)
809 	/*
810 	 * Since some x86 HBAs have devnodes that look like SCSI as
811 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
812 	 * we check for the presence of the "tape" property.
813 	 */
814 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
815 	    DDI_PROP_CANSLEEP, "tape",
816 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
817 		return (DDI_PROBE_FAILURE);
818 	}
819 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
820 		kmem_free(tape_prop, tape_prop_len);
821 		return (DDI_PROBE_FAILURE);
822 	}
823 	kmem_free(tape_prop, tape_prop_len);
824 #endif
825 
826 	devp = ddi_get_driver_private(devi);
827 	instance = ddi_get_instance(devi);
828 
829 	if (ddi_get_soft_state(st_state, instance) != NULL) {
830 		return (DDI_PROBE_PARTIAL);
831 	}
832 
833 
834 	/*
835 	 * Turn around and call probe routine to see whether
836 	 * we actually have a tape at this SCSI nexus.
837 	 */
838 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
839 
840 		/*
841 		 * In checking the whole inq_dtype byte we are looking at both
842 		 * the Peripheral Qualifier and the Peripheral Device Type.
843 		 * For this driver we are only interested in sequential devices
844 		 * that are connected or capable if connecting to this logical
845 		 * unit.
846 		 */
847 		if (devp->sd_inq->inq_dtype ==
848 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
849 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
850 			    "probe exists\n");
851 			rval = DDI_PROBE_SUCCESS;
852 		} else {
853 			rval = DDI_PROBE_FAILURE;
854 		}
855 	} else {
856 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
857 		    "probe failure: nothing there\n");
858 		rval = DDI_PROBE_FAILURE;
859 	}
860 	scsi_unprobe(devp);
861 	return (rval);
862 }
863 
864 static int
865 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
866 {
867 	int 	instance;
868 	int	wide;
869 	int 	dev_instance;
870 	int	ret_status;
871 	struct	scsi_device *devp;
872 	int	node_ix;
873 	struct	scsi_tape *un;
874 
875 	ST_ENTR(devi, st_attach);
876 
877 	devp = ddi_get_driver_private(devi);
878 	instance = ddi_get_instance(devi);
879 
880 	switch (cmd) {
881 		case DDI_ATTACH:
882 			if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
883 			    "tape-command-recovery-disable", 0) != 0) {
884 				st_recov_sz = sizeof (pkt_info);
885 			}
886 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
887 				return (DDI_FAILURE);
888 			}
889 			break;
890 		case DDI_RESUME:
891 			/*
892 			 * Suspend/Resume
893 			 *
894 			 * When the driver suspended, there might be
895 			 * outstanding cmds and therefore we need to
896 			 * reset the suspended flag and resume the scsi
897 			 * watch thread and restart commands and timeouts
898 			 */
899 
900 			if (!(un = ddi_get_soft_state(st_state, instance))) {
901 				return (DDI_FAILURE);
902 			}
903 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
904 			    un->un_dev);
905 
906 			mutex_enter(ST_MUTEX);
907 
908 			un->un_throttle = un->un_max_throttle;
909 			un->un_tids_at_suspend = 0;
910 			un->un_pwr_mgmt = ST_PWR_NORMAL;
911 
912 			if (un->un_swr_token) {
913 				scsi_watch_resume(un->un_swr_token);
914 			}
915 
916 			/*
917 			 * Restart timeouts
918 			 */
919 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
920 				mutex_exit(ST_MUTEX);
921 				un->un_delay_tid = timeout(
922 				    st_delayed_cv_broadcast, un,
923 				    drv_usectohz((clock_t)
924 				    MEDIA_ACCESS_DELAY));
925 				mutex_enter(ST_MUTEX);
926 			}
927 
928 			if (un->un_tids_at_suspend & ST_HIB_TID) {
929 				mutex_exit(ST_MUTEX);
930 				un->un_hib_tid = timeout(st_intr_restart, un,
931 				    ST_STATUS_BUSY_TIMEOUT);
932 				mutex_enter(ST_MUTEX);
933 			}
934 
935 			ret_status = st_clear_unit_attentions(dev_instance, 5);
936 
937 			/*
938 			 * now check if we need to restore the tape position
939 			 */
940 			if ((un->un_suspend_pos.pmode != invalid) &&
941 			    ((un->un_suspend_pos.fileno > 0) ||
942 			    (un->un_suspend_pos.blkno > 0)) ||
943 			    (un->un_suspend_pos.lgclblkno > 0)) {
944 				if (ret_status != 0) {
945 					/*
946 					 * tape didn't get good TUR
947 					 * just print out error messages
948 					 */
949 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
950 					    "st_attach-RESUME: tape failure "
951 					    " tape position will be lost");
952 				} else {
953 					/* this prints errors */
954 					(void) st_validate_tapemarks(un,
955 					    st_uscsi_cmd, &un->un_suspend_pos);
956 				}
957 				/*
958 				 * there are no retries, if there is an error
959 				 * we don't know if the tape has changed
960 				 */
961 				un->un_suspend_pos.pmode = invalid;
962 			}
963 
964 			/* now we are ready to start up any queued I/Os */
965 			if (un->un_ncmds || un->un_quef) {
966 				st_start(un);
967 			}
968 
969 			cv_broadcast(&un->un_suspend_cv);
970 			mutex_exit(ST_MUTEX);
971 			return (DDI_SUCCESS);
972 
973 		default:
974 			return (DDI_FAILURE);
975 	}
976 
977 	un = ddi_get_soft_state(st_state, instance);
978 
979 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
980 	    "st_attach: instance=%x\n", instance);
981 
982 	/*
983 	 * Add a zero-length attribute to tell the world we support
984 	 * kernel ioctls (for layered drivers)
985 	 */
986 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
987 	    DDI_KERNEL_IOCTL, NULL, 0);
988 
989 	ddi_report_dev((dev_info_t *)devi);
990 
991 	/*
992 	 * If it's a SCSI-2 tape drive which supports wide,
993 	 * tell the host adapter to use wide.
994 	 */
995 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
996 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
997 
998 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
999 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1000 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
1001 	}
1002 
1003 	/*
1004 	 * enable autorequest sense; keep the rq packet around in case
1005 	 * the autorequest sense fails because of a busy condition
1006 	 * do a getcap first in case the capability is not variable
1007 	 */
1008 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
1009 		un->un_arq_enabled = 1;
1010 	} else {
1011 		un->un_arq_enabled =
1012 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
1013 	}
1014 
1015 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
1016 	    (un->un_arq_enabled ? "enabled" : "disabled"));
1017 
1018 	un->un_untagged_qing =
1019 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
1020 
1021 	/*
1022 	 * XXX - This is just for 2.6.  to tell users that write buffering
1023 	 *	has gone away.
1024 	 */
1025 	if (un->un_arq_enabled && un->un_untagged_qing) {
1026 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
1027 		    "tape-driver-buffering", 0) != 0) {
1028 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1029 			    "Write Data Buffering has been depricated. Your "
1030 			    "applications should continue to work normally.\n"
1031 			    " But, they should  ported to use Asynchronous "
1032 			    " I/O\n"
1033 			    " For more information, read about "
1034 			    " tape-driver-buffering "
1035 			    "property in the st(7d) man page\n");
1036 		}
1037 	}
1038 
1039 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
1040 	un->un_flush_on_errors = 0;
1041 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
1042 
1043 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
1044 	    "throttle=%x, max_throttle = %x\n",
1045 	    un->un_throttle, un->un_max_throttle);
1046 
1047 	/* initialize persistent errors to nil */
1048 	un->un_persistence = 0;
1049 	un->un_persist_errors = 0;
1050 
1051 	/*
1052 	 * Get dma-max from HBA driver. If it is not defined, use 64k
1053 	 */
1054 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
1055 	if (un->un_maxdma == -1) {
1056 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1057 		    "Received a value that looked like -1. Using 64k maxdma");
1058 		un->un_maxdma = (64 * ONE_K);
1059 	}
1060 
1061 #ifdef	__x86
1062 	/*
1063 	 * for x86, the device may be able to DMA more than the system will
1064 	 * allow under some circumstances. We need account for both the HBA's
1065 	 * and system's contraints.
1066 	 *
1067 	 * Get the maximum DMA under worse case conditions. e.g. looking at the
1068 	 * device constraints, the max copy buffer size, and the worse case
1069 	 * fragmentation. NOTE: this may differ from dma-max since dma-max
1070 	 * doesn't take the worse case framentation into account.
1071 	 *
1072 	 * e.g. a device may be able to DMA 16MBytes, but can only DMA 1MByte
1073 	 * if none of the pages are contiguous. Keeping track of both of these
1074 	 * values allows us to support larger tape block sizes on some devices.
1075 	 */
1076 	un->un_maxdma_arch = scsi_ifgetcap(&devp->sd_address, "dma-max-arch",
1077 	    1);
1078 
1079 	/*
1080 	 * If the dma-max-arch capability is not implemented, or the value
1081 	 * comes back higher than what was reported in dma-max, use dma-max.
1082 	 */
1083 	if ((un->un_maxdma_arch == -1) ||
1084 	    ((uint_t)un->un_maxdma < (uint_t)un->un_maxdma_arch)) {
1085 		un->un_maxdma_arch = un->un_maxdma;
1086 	}
1087 #endif
1088 
1089 	/*
1090 	 * Get the max allowable cdb size
1091 	 */
1092 	un->un_max_cdb_sz =
1093 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
1094 	if (un->un_max_cdb_sz < CDB_GROUP0) {
1095 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1096 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
1097 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
1098 	}
1099 
1100 	if (strcmp(ddi_driver_name(ddi_get_parent(ST_DEVINFO)), "scsi_vhci")) {
1101 		un->un_multipath = 0;
1102 	} else {
1103 		un->un_multipath = 1;
1104 	}
1105 
1106 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1107 
1108 	un->un_mediastate = MTIO_NONE;
1109 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1110 
1111 	/*
1112 	 * initialize kstats
1113 	 */
1114 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1115 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1116 	if (un->un_stats) {
1117 		un->un_stats->ks_lock = ST_MUTEX;
1118 		kstat_install(un->un_stats);
1119 	}
1120 	(void) st_create_errstats(un, instance);
1121 
1122 	/*
1123 	 * find the drive type for this target
1124 	 */
1125 	mutex_enter(ST_MUTEX);
1126 	un->un_dev = MTMINOR(instance);
1127 	st_known_tape_type(un);
1128 	un->un_dev = 0;
1129 	mutex_exit(ST_MUTEX);
1130 
1131 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
1132 		int minor;
1133 		char *name;
1134 
1135 		name  = st_minor_data[node_ix].name;
1136 		minor = st_minor_data[node_ix].minor;
1137 
1138 		/*
1139 		 * For default devices set the density to the
1140 		 * preferred default density for this device.
1141 		 */
1142 		if (node_ix <= DEF_BSD_NR) {
1143 			minor |= un->un_dp->default_density;
1144 		}
1145 		minor |= MTMINOR(instance);
1146 
1147 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
1148 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
1149 			continue;
1150 		}
1151 
1152 		ddi_remove_minor_node(devi, NULL);
1153 
1154 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1155 		    st_reset_notification, (caddr_t)un);
1156 		cv_destroy(&un->un_clscv);
1157 		cv_destroy(&un->un_sbuf_cv);
1158 		cv_destroy(&un->un_queue_cv);
1159 		cv_destroy(&un->un_state_cv);
1160 #ifdef	__x86
1161 		cv_destroy(&un->un_contig_mem_cv);
1162 #endif
1163 		cv_destroy(&un->un_suspend_cv);
1164 		cv_destroy(&un->un_tape_busy_cv);
1165 		cv_destroy(&un->un_recov_buf_cv);
1166 		if (un->un_recov_taskq) {
1167 			ddi_taskq_destroy(un->un_recov_taskq);
1168 		}
1169 		if (un->un_sbufp) {
1170 			freerbuf(un->un_sbufp);
1171 		}
1172 		if (un->un_recov_buf) {
1173 			freerbuf(un->un_recov_buf);
1174 		}
1175 		if (un->un_uscsi_rqs_buf) {
1176 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1177 		}
1178 		if (un->un_mspl) {
1179 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1180 		}
1181 		if (un->un_dp_size) {
1182 			kmem_free(un->un_dp, un->un_dp_size);
1183 		}
1184 		if (un->un_state) {
1185 			kstat_delete(un->un_stats);
1186 		}
1187 		if (un->un_errstats) {
1188 			kstat_delete(un->un_errstats);
1189 		}
1190 
1191 		scsi_destroy_pkt(un->un_rqs);
1192 		scsi_free_consistent_buf(un->un_rqs_bp);
1193 		ddi_soft_state_free(st_state, instance);
1194 		devp->sd_private = NULL;
1195 		devp->sd_sense = NULL;
1196 
1197 		ddi_prop_remove_all(devi);
1198 		return (DDI_FAILURE);
1199 	}
1200 
1201 	return (DDI_SUCCESS);
1202 }
1203 
1204 /*
1205  * st_detach:
1206  *
1207  * we allow a detach if and only if:
1208  *	- no tape is currently inserted
1209  *	- tape position is at BOT or unknown
1210  *		(if it is not at BOT then a no rewind
1211  *		device was opened and we have to preserve state)
1212  *	- it must be in a closed state : no timeouts or scsi_watch requests
1213  *		will exist if it is closed, so we don't need to check for
1214  *		them here.
1215  */
1216 /*ARGSUSED*/
1217 static int
1218 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1219 {
1220 	int instance;
1221 	int result;
1222 	struct scsi_device *devp;
1223 	struct scsi_tape *un;
1224 	clock_t wait_cmds_complete;
1225 
1226 	ST_ENTR(devi, st_detach);
1227 
1228 	instance = ddi_get_instance(devi);
1229 
1230 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1231 		return (DDI_FAILURE);
1232 	}
1233 
1234 	mutex_enter(ST_MUTEX);
1235 
1236 	/*
1237 	 * Clear error entry stack
1238 	 */
1239 	st_empty_error_stack(un);
1240 
1241 	mutex_exit(ST_MUTEX);
1242 
1243 	switch (cmd) {
1244 
1245 	case DDI_DETACH:
1246 		/*
1247 		 * Undo what we did in st_attach & st_doattach,
1248 		 * freeing resources and removing things we installed.
1249 		 * The system framework guarantees we are not active
1250 		 * with this devinfo node in any other entry points at
1251 		 * this time.
1252 		 */
1253 
1254 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1255 		    "st_detach: instance=%x, un=%p\n", instance,
1256 		    (void *)un);
1257 
1258 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1259 		    ((un->un_rsvd_status & ST_APPLICATION_RESERVATIONS) != 0) ||
1260 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1261 		    (un->un_state != ST_STATE_CLOSED)) {
1262 			/*
1263 			 * we cannot unload some targets because the
1264 			 * inquiry returns junk unless immediately
1265 			 * after a reset
1266 			 */
1267 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1268 			    "cannot unload instance %x\n", instance);
1269 			un->un_unit_attention_flags |= 4;
1270 			return (DDI_FAILURE);
1271 		}
1272 
1273 		/*
1274 		 * if the tape has been removed then we may unload;
1275 		 * do a test unit ready and if it returns NOT READY
1276 		 * then we assume that it is safe to unload.
1277 		 * as a side effect, pmode may be set to invalid if the
1278 		 * the test unit ready fails;
1279 		 * also un_state may be set to non-closed, so reset it
1280 		 */
1281 		if ((un->un_dev) &&		/* Been opened since attach */
1282 		    ((un->un_pos.pmode == legacy) &&
1283 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1284 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1285 		    ((un->un_pos.pmode == logical) &&
1286 		    (un->un_pos.lgclblkno > 0))) {
1287 			mutex_enter(ST_MUTEX);
1288 			/*
1289 			 * Send Test Unit Ready in the hopes that if
1290 			 * the drive is not in the state we think it is.
1291 			 * And the state will be changed so it can be detached.
1292 			 * If the command fails to reach the device and
1293 			 * the drive was not rewound or unloaded we want
1294 			 * to fail the detach till a user command fails
1295 			 * where after the detach will succead.
1296 			 */
1297 			result = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
1298 			/*
1299 			 * After TUR un_state may be set to non-closed,
1300 			 * so reset it back.
1301 			 */
1302 			un->un_state = ST_STATE_CLOSED;
1303 			mutex_exit(ST_MUTEX);
1304 		}
1305 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1306 		    "un_status=%x, fileno=%x, blkno=%x\n",
1307 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1308 
1309 		/*
1310 		 * check again:
1311 		 * if we are not at BOT then it is not safe to unload
1312 		 */
1313 		if ((un->un_dev) &&		/* Been opened since attach */
1314 		    (result != EACCES) &&	/* drive is use by somebody */
1315 		    ((((un->un_pos.pmode == legacy) &&
1316 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1317 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1318 		    ((un->un_pos.pmode == logical) &&
1319 		    (un->un_pos.lgclblkno > 0))) &&
1320 		    ((un->un_state == ST_STATE_CLOSED) &&
1321 		    (un->un_laststate == ST_STATE_CLOSING)))) {
1322 
1323 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1324 			    "cannot detach: pmode=%d fileno=0x%x, blkno=0x%x"
1325 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1326 			    un->un_pos.fileno, un->un_pos.blkno,
1327 			    un->un_pos.lgclblkno);
1328 			un->un_unit_attention_flags |= 4;
1329 			return (DDI_FAILURE);
1330 		}
1331 
1332 		/*
1333 		 * Just To make sure that we have released the
1334 		 * tape unit .
1335 		 */
1336 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1337 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1338 			mutex_enter(ST_MUTEX);
1339 			(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
1340 			mutex_exit(ST_MUTEX);
1341 		}
1342 
1343 		/*
1344 		 * now remove other data structures allocated in st_doattach()
1345 		 */
1346 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1347 		    "destroying/freeing\n");
1348 
1349 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1350 		    st_reset_notification, (caddr_t)un);
1351 		cv_destroy(&un->un_clscv);
1352 		cv_destroy(&un->un_sbuf_cv);
1353 		cv_destroy(&un->un_queue_cv);
1354 		cv_destroy(&un->un_suspend_cv);
1355 		cv_destroy(&un->un_tape_busy_cv);
1356 		cv_destroy(&un->un_recov_buf_cv);
1357 
1358 		if (un->un_recov_taskq) {
1359 			ddi_taskq_destroy(un->un_recov_taskq);
1360 		}
1361 
1362 		if (un->un_hib_tid) {
1363 			(void) untimeout(un->un_hib_tid);
1364 			un->un_hib_tid = 0;
1365 		}
1366 
1367 		if (un->un_delay_tid) {
1368 			(void) untimeout(un->un_delay_tid);
1369 			un->un_delay_tid = 0;
1370 		}
1371 		cv_destroy(&un->un_state_cv);
1372 
1373 #ifdef	__x86
1374 		cv_destroy(&un->un_contig_mem_cv);
1375 
1376 		if (un->un_contig_mem_hdl != NULL) {
1377 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1378 		}
1379 #endif
1380 		if (un->un_sbufp) {
1381 			freerbuf(un->un_sbufp);
1382 		}
1383 		if (un->un_recov_buf) {
1384 			freerbuf(un->un_recov_buf);
1385 		}
1386 		if (un->un_uscsi_rqs_buf) {
1387 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1388 		}
1389 		if (un->un_mspl) {
1390 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1391 		}
1392 		if (un->un_rqs) {
1393 			scsi_destroy_pkt(un->un_rqs);
1394 			scsi_free_consistent_buf(un->un_rqs_bp);
1395 		}
1396 		if (un->un_mkr_pkt) {
1397 			scsi_destroy_pkt(un->un_mkr_pkt);
1398 		}
1399 		if (un->un_arq_enabled) {
1400 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1401 		}
1402 		if (un->un_dp_size) {
1403 			kmem_free(un->un_dp, un->un_dp_size);
1404 		}
1405 		if (un->un_stats) {
1406 			kstat_delete(un->un_stats);
1407 			un->un_stats = (kstat_t *)0;
1408 		}
1409 		if (un->un_errstats) {
1410 			kstat_delete(un->un_errstats);
1411 			un->un_errstats = (kstat_t *)0;
1412 		}
1413 		if (un->un_media_id_len) {
1414 			kmem_free(un->un_media_id, un->un_media_id_len);
1415 		}
1416 		devp = ST_SCSI_DEVP;
1417 		ddi_soft_state_free(st_state, instance);
1418 		devp->sd_private = NULL;
1419 		devp->sd_sense = NULL;
1420 		scsi_unprobe(devp);
1421 		ddi_prop_remove_all(devi);
1422 		ddi_remove_minor_node(devi, NULL);
1423 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1424 		return (DDI_SUCCESS);
1425 
1426 	case DDI_SUSPEND:
1427 
1428 		/*
1429 		 * Suspend/Resume
1430 		 *
1431 		 * To process DDI_SUSPEND, we must do the following:
1432 		 *
1433 		 *  - check ddi_removing_power to see if power will be turned
1434 		 *    off. if so, return DDI_FAILURE
1435 		 *  - check if we are already suspended,
1436 		 *    if so, return DDI_FAILURE
1437 		 *  - check if device state is CLOSED,
1438 		 *    if not, return DDI_FAILURE.
1439 		 *  - wait until outstanding operations complete
1440 		 *  - save tape state
1441 		 *  - block new operations
1442 		 *  - cancel pending timeouts
1443 		 *
1444 		 */
1445 
1446 		if (ddi_removing_power(devi)) {
1447 			return (DDI_FAILURE);
1448 		}
1449 		mutex_enter(ST_MUTEX);
1450 
1451 		/*
1452 		 * Shouldn't already be suspended, if so return failure
1453 		 */
1454 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1455 			mutex_exit(ST_MUTEX);
1456 			return (DDI_FAILURE);
1457 		}
1458 		if (un->un_state != ST_STATE_CLOSED) {
1459 			mutex_exit(ST_MUTEX);
1460 			return (DDI_FAILURE);
1461 		}
1462 
1463 		/*
1464 		 * Wait for all outstanding I/O's to complete
1465 		 *
1466 		 * we wait on both ncmds and the wait queue for times
1467 		 * when we are flushing after persistent errors are
1468 		 * flagged, which is when ncmds can be 0, and the
1469 		 * queue can still have I/O's.  This way we preserve
1470 		 * order of biodone's.
1471 		 */
1472 		wait_cmds_complete = ddi_get_lbolt();
1473 		wait_cmds_complete +=
1474 		    st_wait_cmds_complete * drv_usectohz(1000000);
1475 		while (un->un_ncmds || un->un_quef ||
1476 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1477 
1478 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1479 			    wait_cmds_complete) == -1) {
1480 				/*
1481 				 * Time expired then cancel the command
1482 				 */
1483 				if (st_reset(un, RESET_LUN) == 0) {
1484 					if (un->un_last_throttle) {
1485 						un->un_throttle =
1486 						    un->un_last_throttle;
1487 					}
1488 					mutex_exit(ST_MUTEX);
1489 					return (DDI_FAILURE);
1490 				} else {
1491 					break;
1492 				}
1493 			}
1494 		}
1495 
1496 		/*
1497 		 * DDI_SUSPEND says that the system "may" power down, we
1498 		 * remember the file and block number before rewinding.
1499 		 * we also need to save state before issuing
1500 		 * any WRITE_FILE_MARK command.
1501 		 */
1502 		(void) st_update_block_pos(un, st_cmd, 0);
1503 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1504 
1505 
1506 		/*
1507 		 * Issue a zero write file fmk command to tell the drive to
1508 		 * flush any buffered tape marks
1509 		 */
1510 		(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1511 
1512 		/*
1513 		 * Because not all tape drives correctly implement buffer
1514 		 * flushing with the zero write file fmk command, issue a
1515 		 * synchronous rewind command to force data flushing.
1516 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1517 		 * anyway.
1518 		 */
1519 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
1520 
1521 		/* stop any new operations */
1522 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1523 		un->un_throttle = 0;
1524 
1525 		/*
1526 		 * cancel any outstanding timeouts
1527 		 */
1528 		if (un->un_delay_tid) {
1529 			timeout_id_t temp_id = un->un_delay_tid;
1530 			un->un_delay_tid = 0;
1531 			un->un_tids_at_suspend |= ST_DELAY_TID;
1532 			mutex_exit(ST_MUTEX);
1533 			(void) untimeout(temp_id);
1534 			mutex_enter(ST_MUTEX);
1535 		}
1536 
1537 		if (un->un_hib_tid) {
1538 			timeout_id_t temp_id = un->un_hib_tid;
1539 			un->un_hib_tid = 0;
1540 			un->un_tids_at_suspend |= ST_HIB_TID;
1541 			mutex_exit(ST_MUTEX);
1542 			(void) untimeout(temp_id);
1543 			mutex_enter(ST_MUTEX);
1544 		}
1545 
1546 		/*
1547 		 * Suspend the scsi_watch_thread
1548 		 */
1549 		if (un->un_swr_token) {
1550 			opaque_t temp_token = un->un_swr_token;
1551 			mutex_exit(ST_MUTEX);
1552 			scsi_watch_suspend(temp_token);
1553 		} else {
1554 			mutex_exit(ST_MUTEX);
1555 		}
1556 
1557 		return (DDI_SUCCESS);
1558 
1559 	default:
1560 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1561 		return (DDI_FAILURE);
1562 	}
1563 }
1564 
1565 
1566 /* ARGSUSED */
1567 static int
1568 st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1569 {
1570 	dev_t dev;
1571 	struct scsi_tape *un;
1572 	int instance, error;
1573 
1574 	ST_ENTR(dip, st_info);
1575 
1576 	switch (infocmd) {
1577 	case DDI_INFO_DEVT2DEVINFO:
1578 		dev = (dev_t)arg;
1579 		instance = MTUNIT(dev);
1580 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1581 			return (DDI_FAILURE);
1582 		*result = (void *) ST_DEVINFO;
1583 		error = DDI_SUCCESS;
1584 		break;
1585 	case DDI_INFO_DEVT2INSTANCE:
1586 		dev = (dev_t)arg;
1587 		instance = MTUNIT(dev);
1588 		*result = (void *)(uintptr_t)instance;
1589 		error = DDI_SUCCESS;
1590 		break;
1591 	default:
1592 		error = DDI_FAILURE;
1593 	}
1594 	return (error);
1595 }
1596 
1597 static int
1598 st_doattach(struct scsi_device *devp, int (*canwait)())
1599 {
1600 	struct scsi_tape *un = NULL;
1601 	recov_info *ri;
1602 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1603 	int instance;
1604 	size_t rlen;
1605 
1606 	ST_FUNC(devp->sd_dev, st_doattach);
1607 	/*
1608 	 * Call the routine scsi_probe to do some of the dirty work.
1609 	 * If the INQUIRY command succeeds, the field sd_inq in the
1610 	 * device structure will be filled in.
1611 	 */
1612 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1613 	    "st_doattach(): probing\n");
1614 
1615 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1616 
1617 		/*
1618 		 * In checking the whole inq_dtype byte we are looking at both
1619 		 * the Peripheral Qualifier and the Peripheral Device Type.
1620 		 * For this driver we are only interested in sequential devices
1621 		 * that are connected or capable if connecting to this logical
1622 		 * unit.
1623 		 */
1624 		if (devp->sd_inq->inq_dtype ==
1625 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1626 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1627 			    "probe exists\n");
1628 		} else {
1629 			/* Something there but not a tape device */
1630 			scsi_unprobe(devp);
1631 			return (DDI_FAILURE);
1632 		}
1633 	} else {
1634 		/* Nothing there */
1635 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1636 		    "probe failure: nothing there\n");
1637 		scsi_unprobe(devp);
1638 		return (DDI_FAILURE);
1639 	}
1640 
1641 
1642 	/*
1643 	 * The actual unit is present.
1644 	 * Now is the time to fill in the rest of our info..
1645 	 */
1646 	instance = ddi_get_instance(devp->sd_dev);
1647 
1648 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1649 		goto error;
1650 	}
1651 	un = ddi_get_soft_state(st_state, instance);
1652 
1653 	ASSERT(un != NULL);
1654 
1655 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
1656 	    MAX_SENSE_LENGTH, B_READ, canwait, NULL);
1657 	if (un->un_rqs_bp == NULL) {
1658 		goto error;
1659 	}
1660 	un->un_rqs = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
1661 	    CDB_GROUP0, 1, st_recov_sz, PKT_CONSISTENT, canwait, NULL);
1662 	if (!un->un_rqs) {
1663 		goto error;
1664 	}
1665 	ASSERT(un->un_rqs->pkt_resid == 0);
1666 	devp->sd_sense =
1667 	    (struct scsi_extended_sense *)un->un_rqs_bp->b_un.b_addr;
1668 	ASSERT(geterror(un->un_rqs_bp) == NULL);
1669 
1670 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs->pkt_cdbp,
1671 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
1672 	FILL_SCSI1_LUN(devp, un->un_rqs);
1673 	un->un_rqs->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1674 	un->un_rqs->pkt_time = st_io_time;
1675 	un->un_rqs->pkt_comp = st_intr;
1676 	ri = (recov_info *)un->un_rqs->pkt_private;
1677 	if (st_recov_sz == sizeof (recov_info)) {
1678 		ri->privatelen = sizeof (recov_info);
1679 	} else {
1680 		ri->privatelen = sizeof (pkt_info);
1681 	}
1682 
1683 	un->un_sbufp = getrbuf(km_flags);
1684 	un->un_recov_buf = getrbuf(km_flags);
1685 
1686 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1687 
1688 	/*
1689 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1690 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1691 	 * is obsolete and we want more flexibility in controlling the DMA
1692 	 * address constraints.
1693 	 */
1694 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1695 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1696 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1697 
1698 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1699 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1700 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1701 
1702 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1703 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1704 		    "probe partial failure: no space\n");
1705 		goto error;
1706 	}
1707 
1708 	bzero(un->un_mspl, sizeof (struct seq_mode));
1709 
1710 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1711 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1712 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1713 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1714 #ifdef	__x86
1715 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1716 #endif
1717 
1718 	/* Initialize power managemnet condition variable */
1719 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1720 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1721 	cv_init(&un->un_recov_buf_cv, NULL, CV_DRIVER, NULL);
1722 
1723 	un->un_recov_taskq = ddi_taskq_create(devp->sd_dev,
1724 	    "un_recov_taskq", 1, TASKQ_DEFAULTPRI, km_flags);
1725 
1726 	ASSERT(un->un_recov_taskq != NULL);
1727 
1728 	un->un_pos.pmode = invalid;
1729 	un->un_sd	= devp;
1730 	un->un_swr_token = (opaque_t)NULL;
1731 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1732 	un->un_wormable = st_is_drive_worm;
1733 	un->un_media_id_method = st_get_media_identification;
1734 	/*
1735 	 * setting long a initial as it contains logical file info.
1736 	 * support for long format is mandatory but many drive don't do it.
1737 	 */
1738 	un->un_read_pos_type = LONG_POS;
1739 
1740 	un->un_suspend_pos.pmode = invalid;
1741 
1742 	st_add_recovery_info_to_pkt(un, un->un_rqs_bp, un->un_rqs);
1743 
1744 #ifdef	__x86
1745 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1746 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1747 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1748 		    "allocation of contiguous memory dma handle failed!");
1749 		un->un_contig_mem_hdl = NULL;
1750 		goto error;
1751 	}
1752 #endif
1753 
1754 	/*
1755 	 * Since this driver manages devices with "remote" hardware,
1756 	 * i.e. the devices themselves have no "reg" properties,
1757 	 * the SUSPEND/RESUME commands in detach/attach will not be
1758 	 * called by the power management framework unless we request
1759 	 * it by creating a "pm-hardware-state" property and setting it
1760 	 * to value "needs-suspend-resume".
1761 	 */
1762 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1763 	    "pm-hardware-state", "needs-suspend-resume") !=
1764 	    DDI_PROP_SUCCESS) {
1765 
1766 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1767 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1768 		goto error;
1769 	}
1770 
1771 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1772 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1773 
1774 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1775 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1776 		    "failed\n");
1777 		goto error;
1778 	}
1779 
1780 	(void) scsi_reset_notify(ROUTE, SCSI_RESET_NOTIFY,
1781 	    st_reset_notification, (caddr_t)un);
1782 
1783 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "attach success\n");
1784 	return (DDI_SUCCESS);
1785 
1786 error:
1787 	devp->sd_sense = NULL;
1788 
1789 	ddi_remove_minor_node(devp->sd_dev, NULL);
1790 	if (un) {
1791 		if (un->un_mspl) {
1792 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1793 		}
1794 		if (un->un_read_pos_data) {
1795 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1796 		}
1797 		if (un->un_sbufp) {
1798 			freerbuf(un->un_sbufp);
1799 		}
1800 		if (un->un_recov_buf) {
1801 			freerbuf(un->un_recov_buf);
1802 		}
1803 		if (un->un_uscsi_rqs_buf) {
1804 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1805 		}
1806 #ifdef	__x86
1807 		if (un->un_contig_mem_hdl != NULL) {
1808 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1809 		}
1810 #endif
1811 		if (un->un_rqs) {
1812 			scsi_destroy_pkt(un->un_rqs);
1813 		}
1814 
1815 		if (un->un_rqs_bp) {
1816 			scsi_free_consistent_buf(un->un_rqs_bp);
1817 		}
1818 
1819 		ddi_soft_state_free(st_state, instance);
1820 		devp->sd_private = NULL;
1821 	}
1822 
1823 	if (devp->sd_inq) {
1824 		scsi_unprobe(devp);
1825 	}
1826 	return (DDI_FAILURE);
1827 }
1828 
1829 typedef int
1830 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1831 
1832 static cfg_functp config_functs[] = {
1833 	st_get_conf_from_st_dot_conf,
1834 	st_get_conf_from_st_conf_dot_c,
1835 	st_get_conf_from_tape_drive,
1836 	st_get_default_conf
1837 };
1838 
1839 
1840 /*
1841  * determine tape type, using tape-config-list or built-in table or
1842  * use a generic tape config entry
1843  */
1844 static void
1845 st_known_tape_type(struct scsi_tape *un)
1846 {
1847 	struct st_drivetype *dp;
1848 	cfg_functp *config_funct;
1849 	uchar_t reserved;
1850 
1851 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1852 
1853 	reserved = (un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1854 	    : ST_RELEASE;
1855 
1856 	/*
1857 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1858 	 *	 no vid & pid inquiry data.  So, we provide one.
1859 	 */
1860 	if (ST_INQUIRY->inq_len == 0 ||
1861 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1862 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1863 	}
1864 
1865 	if (un->un_dp_size == 0) {
1866 		un->un_dp_size = sizeof (struct st_drivetype);
1867 		dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1868 		un->un_dp = dp;
1869 	} else {
1870 		dp = un->un_dp;
1871 	}
1872 
1873 	un->un_dp->non_motion_timeout = st_io_time;
1874 	/*
1875 	 * Loop through the configuration methods till one works.
1876 	 */
1877 	for (config_funct = &config_functs[0]; ; config_funct++) {
1878 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1879 			break;
1880 		}
1881 	}
1882 
1883 	/*
1884 	 * If we didn't just make up this configuration and
1885 	 * all the density codes are the same..
1886 	 * Set Auto Density over ride.
1887 	 */
1888 	if (*config_funct != st_get_default_conf) {
1889 		/*
1890 		 * If this device is one that is configured and all
1891 		 * densities are the same, This saves doing gets and set
1892 		 * that yield nothing.
1893 		 */
1894 		if ((dp->densities[0]) == (dp->densities[1]) &&
1895 		    (dp->densities[0]) == (dp->densities[2]) &&
1896 		    (dp->densities[0]) == (dp->densities[3])) {
1897 
1898 			dp->options |= ST_AUTODEN_OVERRIDE;
1899 		}
1900 	}
1901 
1902 
1903 	/*
1904 	 * Store tape drive characteristics.
1905 	 */
1906 	un->un_status = 0;
1907 	un->un_attached = 1;
1908 	un->un_init_options = dp->options;
1909 
1910 	/* setup operation time-outs based on options */
1911 	st_calculate_timeouts(un);
1912 
1913 	/* TLR support */
1914 	if (un->un_dp->type != ST_TYPE_INVALID) {
1915 		int result;
1916 
1917 		/* try and enable TLR */
1918 		un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
1919 		result = st_set_target_TLR_mode(un, st_uscsi_cmd);
1920 		if (result == EACCES) {
1921 			/*
1922 			 * From attach command failed.
1923 			 * Set dp type so is run again on open.
1924 			 */
1925 			un->un_dp->type = ST_TYPE_INVALID;
1926 			un->un_tlr_flag = TLR_NOT_KNOWN;
1927 		} else if (result == 0) {
1928 			if (scsi_ifgetcap(&un->un_sd->sd_address,
1929 			    "tran-layer-retries", 1) == -1) {
1930 				un->un_tlr_flag = TLR_NOT_SUPPORTED;
1931 				(void) st_set_target_TLR_mode(un, st_uscsi_cmd);
1932 			} else {
1933 				un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
1934 			}
1935 		} else {
1936 			un->un_tlr_flag = TLR_NOT_SUPPORTED;
1937 		}
1938 	}
1939 
1940 	/* make sure if we are supposed to be variable, make it variable */
1941 	if (dp->options & ST_VARIABLE) {
1942 		dp->bsize = 0;
1943 	}
1944 
1945 	if (reserved != ((un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1946 	    : ST_RELEASE)) {
1947 		(void) st_reserve_release(un, reserved, st_uscsi_cmd);
1948 	}
1949 
1950 	un->un_unit_attention_flags |= 1;
1951 
1952 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1953 
1954 }
1955 
1956 
1957 typedef struct {
1958 	int mask;
1959 	int bottom;
1960 	int top;
1961 	char *name;
1962 } conf_limit;
1963 
1964 static const conf_limit conf_limits[] = {
1965 
1966 	-1,		1,		2,		"conf version",
1967 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1968 	-1,		0,		0xffffff,	"block size",
1969 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1970 	-1,		0,		4,		"number of densities",
1971 	-1,		0,		UINT8_MAX,	"density code",
1972 	-1,		0,		3,		"default density",
1973 	-1,		0,		UINT16_MAX,	"non motion timeout",
1974 	-1,		0,		UINT16_MAX,	"I/O timeout",
1975 	-1,		0,		UINT16_MAX,	"space timeout",
1976 	-1,		0,		UINT16_MAX,	"load timeout",
1977 	-1,		0,		UINT16_MAX,	"unload timeout",
1978 	-1,		0,		UINT16_MAX,	"erase timeout",
1979 	0,		0,		0,		NULL
1980 };
1981 
1982 static int
1983 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1984     const char *conf_name)
1985 {
1986 	int dens;
1987 	int ndens;
1988 	int value;
1989 	int type;
1990 	int count;
1991 	const conf_limit *limit = &conf_limits[0];
1992 
1993 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1994 
1995 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1996 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1997 
1998 	count = list_len;
1999 	type = *list;
2000 	for (;  count && limit->name; count--, list++, limit++) {
2001 
2002 		value = *list;
2003 		if (value & ~limit->mask) {
2004 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2005 			    "%s %s value invalid bits set: 0x%X\n",
2006 			    conf_name, limit->name, value & ~limit->mask);
2007 			*list &= limit->mask;
2008 		} else if (value < limit->bottom) {
2009 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2010 			    "%s %s value too low: value = %d limit %d\n",
2011 			    conf_name, limit->name, value, limit->bottom);
2012 		} else if (value > limit->top) {
2013 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2014 			    "%s %s value too high: value = %d limit %d\n",
2015 			    conf_name, limit->name, value, limit->top);
2016 		} else {
2017 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2018 			    "%s %s value = 0x%X\n",
2019 			    conf_name, limit->name, value);
2020 		}
2021 
2022 		/* If not the number of densities continue */
2023 		if (limit != &conf_limits[4]) {
2024 			continue;
2025 		}
2026 
2027 		/* If number of densities is not in range can't use config */
2028 		if (value < limit->bottom || value > limit->top) {
2029 			return (-1);
2030 		}
2031 
2032 		ndens = min(value, NDENSITIES);
2033 		if ((type == 1) && (list_len - ndens) != 6) {
2034 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2035 			    "%s conf version 1 with %d densities has %d items"
2036 			    " should have %d",
2037 			    conf_name, ndens, list_len, 6 + ndens);
2038 		} else if ((type == 2) && (list_len - ndens) != 13) {
2039 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2040 			    "%s conf version 2 with %d densities has %d items"
2041 			    " should have %d",
2042 			    conf_name, ndens, list_len, 13 + ndens);
2043 		}
2044 
2045 		limit++;
2046 		for (dens = 0; dens < ndens && count; dens++) {
2047 			count--;
2048 			list++;
2049 			value = *list;
2050 			if (value < limit->bottom) {
2051 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2052 				    "%s density[%d] value too low: value ="
2053 				    " 0x%X limit 0x%X\n",
2054 				    conf_name, dens, value, limit->bottom);
2055 			} else if (value > limit->top) {
2056 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2057 				    "%s density[%d] value too high: value ="
2058 				    " 0x%X limit 0x%X\n",
2059 				    conf_name, dens, value, limit->top);
2060 			} else {
2061 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2062 				    "%s density[%d] value = 0x%X\n",
2063 				    conf_name, dens, value);
2064 			}
2065 		}
2066 	}
2067 
2068 	return (0);
2069 }
2070 
2071 static int
2072 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
2073     struct st_drivetype *dp)
2074 {
2075 	caddr_t config_list = NULL;
2076 	caddr_t data_list = NULL;
2077 	int	*data_ptr;
2078 	caddr_t vidptr, prettyptr, datanameptr;
2079 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
2080 	int config_list_len, data_list_len, len, i;
2081 	int version;
2082 	int found = 0;
2083 
2084 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
2085 
2086 	/*
2087 	 * Determine type of tape controller. Type is determined by
2088 	 * checking the vendor ids of the earlier inquiry command and
2089 	 * comparing those with vids in tape-config-list defined in st.conf
2090 	 */
2091 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
2092 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
2093 	    != DDI_PROP_SUCCESS) {
2094 		return (found);
2095 	}
2096 
2097 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2098 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
2099 
2100 	/*
2101 	 * Compare vids in each triplet - if it matches, get value for
2102 	 * data_name and contruct a st_drivetype struct
2103 	 * tripletlen is not set yet!
2104 	 */
2105 	for (len = config_list_len, vidptr = config_list;
2106 	    len > 0;
2107 	    vidptr += tripletlen, len -= tripletlen) {
2108 
2109 		vidlen = strlen(vidptr);
2110 		prettyptr = vidptr + vidlen + 1;
2111 		prettylen = strlen(prettyptr);
2112 		datanameptr = prettyptr + prettylen + 1;
2113 		datanamelen = strlen(datanameptr);
2114 		tripletlen = vidlen + prettylen + datanamelen + 3;
2115 
2116 		if (vidlen == 0) {
2117 			continue;
2118 		}
2119 
2120 		/*
2121 		 * If inquiry vid dosen't match this triplets vid,
2122 		 * try the next.
2123 		 */
2124 		if (strncasecmp(vidpid, vidptr, vidlen)) {
2125 			continue;
2126 		}
2127 
2128 		/*
2129 		 * if prettylen is zero then use the vid string
2130 		 */
2131 		if (prettylen == 0) {
2132 			prettyptr = vidptr;
2133 			prettylen = vidlen;
2134 		}
2135 
2136 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2137 		    "vid = %s, pretty=%s, dataname = %s\n",
2138 		    vidptr, prettyptr, datanameptr);
2139 
2140 		/*
2141 		 * get the data list
2142 		 */
2143 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
2144 		    datanameptr, (caddr_t)&data_list,
2145 		    &data_list_len) != DDI_PROP_SUCCESS) {
2146 			/*
2147 			 * Error in getting property value
2148 			 * print warning!
2149 			 */
2150 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2151 			    "data property (%s) has no value\n",
2152 			    datanameptr);
2153 			continue;
2154 		}
2155 
2156 		/*
2157 		 * now initialize the st_drivetype struct
2158 		 */
2159 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
2160 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
2161 		(void) strncpy(dp->vid, vidptr, dp->length);
2162 		data_ptr = (int *)data_list;
2163 		/*
2164 		 * check if data is enough for version, type,
2165 		 * bsize, options, # of densities, density1,
2166 		 * density2, ..., default_density
2167 		 */
2168 		if ((data_list_len < 5 * sizeof (int)) ||
2169 		    (data_list_len < 6 * sizeof (int) +
2170 		    *(data_ptr + 4) * sizeof (int))) {
2171 			/*
2172 			 * print warning and skip to next triplet.
2173 			 */
2174 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2175 			    "data property (%s) incomplete\n",
2176 			    datanameptr);
2177 			kmem_free(data_list, data_list_len);
2178 			continue;
2179 		}
2180 
2181 		if (st_validate_conf_data(un, data_ptr,
2182 		    data_list_len / sizeof (int), datanameptr)) {
2183 			kmem_free(data_list, data_list_len);
2184 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2185 			    "data property (%s) rejected\n",
2186 			    datanameptr);
2187 			continue;
2188 		}
2189 
2190 		/*
2191 		 * check version
2192 		 */
2193 		version = *data_ptr++;
2194 		if (version != 1 && version != 2) {
2195 			/* print warning but accept it */
2196 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2197 			    "Version # for data property (%s) "
2198 			    "not set to 1 or 2\n", datanameptr);
2199 		}
2200 
2201 		dp->type    = *data_ptr++;
2202 		dp->bsize   = *data_ptr++;
2203 		dp->options = *data_ptr++;
2204 		dp->options |= ST_DYNAMIC;
2205 		len = *data_ptr++;
2206 		for (i = 0; i < NDENSITIES; i++) {
2207 			if (i < len) {
2208 				dp->densities[i] = *data_ptr++;
2209 			}
2210 		}
2211 		dp->default_density = *data_ptr << 3;
2212 		if (version == 2 &&
2213 		    data_list_len >= (13 + len) * sizeof (int)) {
2214 			data_ptr++;
2215 			dp->non_motion_timeout	= *data_ptr++;
2216 			dp->io_timeout		= *data_ptr++;
2217 			dp->rewind_timeout	= *data_ptr++;
2218 			dp->space_timeout	= *data_ptr++;
2219 			dp->load_timeout	= *data_ptr++;
2220 			dp->unload_timeout	= *data_ptr++;
2221 			dp->erase_timeout	= *data_ptr++;
2222 		}
2223 		kmem_free(data_list, data_list_len);
2224 		found = 1;
2225 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2226 		    "found in st.conf: vid = %s, pretty=%s\n",
2227 		    dp->vid, dp->name);
2228 		break;
2229 	}
2230 
2231 	/*
2232 	 * free up the memory allocated by ddi_getlongprop
2233 	 */
2234 	if (config_list) {
2235 		kmem_free(config_list, config_list_len);
2236 	}
2237 	return (found);
2238 }
2239 
2240 static int
2241 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2242     struct st_drivetype *dp)
2243 {
2244 	int i;
2245 
2246 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2247 	/*
2248 	 * Determine type of tape controller.  Type is determined by
2249 	 * checking the result of the earlier inquiry command and
2250 	 * comparing vendor ids with strings in a table declared in st_conf.c.
2251 	 */
2252 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2253 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2254 
2255 	for (i = 0; i < st_ndrivetypes; i++) {
2256 		if (st_drivetypes[i].length == 0) {
2257 			continue;
2258 		}
2259 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2260 		    st_drivetypes[i].length)) {
2261 			continue;
2262 		}
2263 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2264 		return (1);
2265 	}
2266 	return (0);
2267 }
2268 
2269 static int
2270 st_get_conf_from_tape_drive(struct scsi_tape *un, char *vidpid,
2271     struct st_drivetype *dp)
2272 {
2273 	int bsize;
2274 	ulong_t maxbsize;
2275 	caddr_t buf;
2276 	struct st_drivetype *tem_dp;
2277 	struct read_blklim *blklim;
2278 	int rval;
2279 	int i;
2280 
2281 	ST_FUNC(ST_DEVINFO, st_get_conf_from_tape_drive);
2282 
2283 	/*
2284 	 * Determine the type of tape controller. Type is determined by
2285 	 * sending SCSI commands to tape drive and deriving the type from
2286 	 * the returned data.
2287 	 */
2288 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2289 	    "st_get_conf_from_tape_drive(): asking tape drive\n");
2290 
2291 	tem_dp = kmem_zalloc(sizeof (struct st_drivetype), KM_SLEEP);
2292 
2293 	/*
2294 	 * Make up a name
2295 	 */
2296 	bcopy(vidpid, tem_dp->name, VIDPIDLEN);
2297 	tem_dp->name[VIDPIDLEN] = '\0';
2298 	tem_dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2299 	(void) strncpy(tem_dp->vid, ST_INQUIRY->inq_vid, tem_dp->length);
2300 	/*
2301 	 * 'clean' vendor and product strings of non-printing chars
2302 	 */
2303 	for (i = 0; i < VIDPIDLEN - 1; i ++) {
2304 		if (tem_dp->name[i] < ' ' || tem_dp->name[i] > '~') {
2305 			tem_dp->name[i] = '.';
2306 		}
2307 	}
2308 
2309 	/*
2310 	 * MODE SENSE to determine block size.
2311 	 */
2312 	un->un_dp->options |= ST_MODE_SEL_COMP | ST_UNLOADABLE;
2313 	rval = st_modesense(un);
2314 	if (rval) {
2315 		if (rval == EACCES) {
2316 			un->un_dp->type = ST_TYPE_INVALID;
2317 			rval = 1;
2318 		} else {
2319 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
2320 			rval = 0;
2321 		}
2322 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2323 		    "st_get_conf_from_tape_drive(): fail to mode sense\n");
2324 		goto exit;
2325 	}
2326 
2327 	/* Can mode sense page 0x10 or 0xf */
2328 	tem_dp->options |= ST_MODE_SEL_COMP;
2329 	bsize = (un->un_mspl->high_bl << 16)	|
2330 	    (un->un_mspl->mid_bl << 8)		|
2331 	    (un->un_mspl->low_bl);
2332 
2333 	if (bsize == 0) {
2334 		tem_dp->options |= ST_VARIABLE;
2335 		tem_dp->bsize = 0;
2336 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
2337 		rval = st_change_block_size(un, 0);
2338 		if (rval) {
2339 			if (rval == EACCES) {
2340 				un->un_dp->type = ST_TYPE_INVALID;
2341 				rval = 1;
2342 			} else {
2343 				rval = 0;
2344 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2345 				    "st_get_conf_from_tape_drive(): "
2346 				    "Fixed record size is too large and"
2347 				    "cannot switch to variable record size");
2348 			}
2349 			goto exit;
2350 		}
2351 		tem_dp->options |= ST_VARIABLE;
2352 	} else {
2353 		rval = st_change_block_size(un, 0);
2354 		if (rval == 0) {
2355 			tem_dp->options |= ST_VARIABLE;
2356 			tem_dp->bsize = 0;
2357 		} else if (rval != EACCES) {
2358 			tem_dp->bsize = bsize;
2359 		} else {
2360 			un->un_dp->type = ST_TYPE_INVALID;
2361 			rval = 1;
2362 			goto exit;
2363 		}
2364 	}
2365 
2366 	/*
2367 	 * If READ BLOCk LIMITS works and upper block size limit is
2368 	 * more than 64K, ST_NO_RECSIZE_LIMIT is supported.
2369 	 */
2370 	blklim = kmem_zalloc(sizeof (struct read_blklim), KM_SLEEP);
2371 	rval = st_read_block_limits(un, blklim);
2372 	if (rval) {
2373 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2374 		    "st_get_conf_from_tape_drive(): "
2375 		    "fail to read block limits.\n");
2376 		rval = 0;
2377 		kmem_free(blklim, sizeof (struct read_blklim));
2378 		goto exit;
2379 	}
2380 	maxbsize = (blklim->max_hi << 16) +
2381 	    (blklim->max_mid << 8) + blklim->max_lo;
2382 	if (maxbsize > ST_MAXRECSIZE_VARIABLE) {
2383 		tem_dp->options |= ST_NO_RECSIZE_LIMIT;
2384 	}
2385 	kmem_free(blklim, sizeof (struct read_blklim));
2386 
2387 	/*
2388 	 * Inquiry VPD page 0xb0 to see if the tape drive supports WORM
2389 	 */
2390 	buf = kmem_zalloc(6, KM_SLEEP);
2391 	rval = st_get_special_inquiry(un, 6, buf, 0xb0);
2392 	if (rval) {
2393 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2394 		    "st_get_conf_from_tape_drive(): "
2395 		    "fail to read vitial inquiry.\n");
2396 		rval = 0;
2397 		kmem_free(buf, 6);
2398 		goto exit;
2399 	}
2400 	if (buf[4] & 1) {
2401 		tem_dp->options |= ST_WORMABLE;
2402 	}
2403 	kmem_free(buf, 6);
2404 
2405 	/* Assume BSD BSR KNOWS_EOD */
2406 	tem_dp->options |= ST_BSF | ST_BSR | ST_KNOWS_EOD | ST_UNLOADABLE;
2407 	tem_dp->max_rretries = -1;
2408 	tem_dp->max_wretries = -1;
2409 
2410 	/*
2411 	 * Decide the densities supported by tape drive by sending
2412 	 * REPORT DENSITY SUPPORT command.
2413 	 */
2414 	if (st_get_densities_from_tape_drive(un, tem_dp) == 0) {
2415 		goto exit;
2416 	}
2417 
2418 	/*
2419 	 * Decide the timeout values for several commands by sending
2420 	 * REPORT SUPPORTED OPERATION CODES command.
2421 	 */
2422 	rval = st_get_timeout_values_from_tape_drive(un, tem_dp);
2423 	if (rval == 0 || ((rval == 1) && (tem_dp->type == ST_TYPE_INVALID))) {
2424 		goto exit;
2425 	}
2426 
2427 	bcopy(tem_dp, dp, sizeof (struct st_drivetype));
2428 	rval = 1;
2429 
2430 exit:
2431 	un->un_status = KEY_NO_SENSE;
2432 	kmem_free(tem_dp, sizeof (struct st_drivetype));
2433 	return (rval);
2434 }
2435 
2436 static int
2437 st_get_densities_from_tape_drive(struct scsi_tape *un,
2438     struct st_drivetype *dp)
2439 {
2440 	int i, p;
2441 	size_t buflen;
2442 	ushort_t des_len;
2443 	uchar_t *den_header;
2444 	uchar_t num_den;
2445 	uchar_t den[NDENSITIES];
2446 	uchar_t deflt[NDENSITIES];
2447 	struct report_density_desc *den_desc;
2448 
2449 	ST_FUNC(ST_DEVINFO, st_get_densities_from_type_drive);
2450 
2451 	/*
2452 	 * Since we have no idea how many densitiy support entries
2453 	 * will be returned, we send the command firstly assuming
2454 	 * there is only one. Then we can decide the number of
2455 	 * entries by available density support length. If multiple
2456 	 * entries exist, we will resend the command with enough
2457 	 * buffer size.
2458 	 */
2459 	buflen = sizeof (struct report_density_header) +
2460 	    sizeof (struct report_density_desc);
2461 	den_header = kmem_zalloc(buflen, KM_SLEEP);
2462 	if (st_report_density_support(un, den_header, buflen) != 0) {
2463 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2464 		    "st_get_conf_from_tape_drive(): fail to report density.\n");
2465 		kmem_free(den_header, buflen);
2466 		return (0);
2467 	}
2468 	des_len =
2469 	    BE_16(((struct report_density_header *)den_header)->ava_dens_len);
2470 	num_den = (des_len - 2) / sizeof (struct report_density_desc);
2471 
2472 	if (num_den > 1) {
2473 		kmem_free(den_header, buflen);
2474 		buflen = sizeof (struct report_density_header) +
2475 		    sizeof (struct report_density_desc) * num_den;
2476 		den_header = kmem_zalloc(buflen, KM_SLEEP);
2477 		if (st_report_density_support(un, den_header, buflen) != 0) {
2478 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2479 			    "st_get_conf_from_tape_drive(): "
2480 			    "fail to report density.\n");
2481 			kmem_free(den_header, buflen);
2482 			return (0);
2483 		}
2484 	}
2485 
2486 	den_desc = (struct report_density_desc *)(den_header
2487 	    + sizeof (struct report_density_header));
2488 
2489 	/*
2490 	 * Decide the drive type by assigning organization
2491 	 */
2492 	for (i = 0; i < ST_NUM_MEMBERS(st_vid_dt); i ++) {
2493 		if (strncmp(st_vid_dt[i].vid, (char *)(den_desc->ass_org),
2494 		    8) == 0) {
2495 			dp->type = st_vid_dt[i].type;
2496 			break;
2497 		}
2498 	}
2499 	if (i == ST_NUM_MEMBERS(st_vid_dt)) {
2500 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2501 		    "st_get_conf_from_tape_drive(): "
2502 		    "can't find match of assigned ort.\n");
2503 		kmem_free(den_header, buflen);
2504 		return (0);
2505 	}
2506 
2507 	/*
2508 	 * The tape drive may support many tape formats, but the st driver
2509 	 * supports only the four highest densities. Since density code
2510 	 * values are returned by ascending sequence, we start from the
2511 	 * last entry of density support data block descriptor.
2512 	 */
2513 	p = 0;
2514 	den_desc += num_den - 1;
2515 	for (i = 0; i < num_den && p < NDENSITIES; i ++, den_desc --) {
2516 		if ((den_desc->pri_den != 0) && (den_desc->wrtok)) {
2517 			if (p != 0) {
2518 				if (den_desc->pri_den >= den[p - 1]) {
2519 					continue;
2520 				}
2521 			}
2522 			den[p] = den_desc->pri_den;
2523 			deflt[p] = den_desc->deflt;
2524 			p ++;
2525 		}
2526 	}
2527 
2528 	switch (p) {
2529 	case 0:
2530 		bzero(dp->densities, NDENSITIES);
2531 		dp->options |= ST_AUTODEN_OVERRIDE;
2532 		dp->default_density = MT_DENSITY4;
2533 		break;
2534 
2535 	case 1:
2536 		(void) memset(dp->densities, den[0], NDENSITIES);
2537 		dp->options |= ST_AUTODEN_OVERRIDE;
2538 		dp->default_density = MT_DENSITY4;
2539 		break;
2540 
2541 	case 2:
2542 		dp->densities[0] = den[1];
2543 		dp->densities[1] = den[1];
2544 		dp->densities[2] = den[0];
2545 		dp->densities[3] = den[0];
2546 		if (deflt[0]) {
2547 			dp->default_density = MT_DENSITY4;
2548 		} else {
2549 			dp->default_density = MT_DENSITY2;
2550 		}
2551 		break;
2552 
2553 	case 3:
2554 		dp->densities[0] = den[2];
2555 		dp->densities[1] = den[1];
2556 		dp->densities[2] = den[0];
2557 		dp->densities[3] = den[0];
2558 		if (deflt[0]) {
2559 			dp->default_density = MT_DENSITY4;
2560 		} else if (deflt[1]) {
2561 			dp->default_density = MT_DENSITY2;
2562 		} else {
2563 			dp->default_density = MT_DENSITY1;
2564 		}
2565 		break;
2566 
2567 	default:
2568 		for (i = p; i > p - NDENSITIES; i --) {
2569 			dp->densities[i - 1] = den[p - i];
2570 		}
2571 		if (deflt[0]) {
2572 			dp->default_density = MT_DENSITY4;
2573 		} else if (deflt[1]) {
2574 			dp->default_density = MT_DENSITY3;
2575 		} else if (deflt[2]) {
2576 			dp->default_density = MT_DENSITY2;
2577 		} else {
2578 			dp->default_density = MT_DENSITY1;
2579 		}
2580 		break;
2581 	}
2582 
2583 	bzero(dp->mediatype, NDENSITIES);
2584 
2585 	kmem_free(den_header, buflen);
2586 	return (1);
2587 }
2588 
2589 static int
2590 st_get_timeout_values_from_tape_drive(struct scsi_tape *un,
2591     struct st_drivetype *dp)
2592 {
2593 	ushort_t timeout;
2594 	int rval;
2595 
2596 	ST_FUNC(ST_DEVINFO, st_get_timeout_values_from_type_drive);
2597 
2598 	rval = st_get_timeouts_value(un, SCMD_ERASE, &timeout, 0);
2599 	if (rval) {
2600 		if (rval == EACCES) {
2601 			un->un_dp->type = ST_TYPE_INVALID;
2602 			dp->type = ST_TYPE_INVALID;
2603 			return (1);
2604 		}
2605 		return (0);
2606 	}
2607 	dp->erase_timeout = timeout;
2608 
2609 	rval = st_get_timeouts_value(un, SCMD_READ, &timeout, 0);
2610 	if (rval) {
2611 		if (rval == EACCES) {
2612 			un->un_dp->type = ST_TYPE_INVALID;
2613 			dp->type = ST_TYPE_INVALID;
2614 			return (1);
2615 		}
2616 		return (0);
2617 	}
2618 	dp->io_timeout = timeout;
2619 
2620 	rval = st_get_timeouts_value(un, SCMD_WRITE, &timeout, 0);
2621 	if (rval) {
2622 		if (rval == EACCES) {
2623 			un->un_dp->type = ST_TYPE_INVALID;
2624 			dp->type = ST_TYPE_INVALID;
2625 			return (1);
2626 		}
2627 		return (0);
2628 	}
2629 	dp->io_timeout = max(dp->io_timeout, timeout);
2630 
2631 	rval = st_get_timeouts_value(un, SCMD_SPACE, &timeout, 0);
2632 	if (rval) {
2633 		if (rval == EACCES) {
2634 			un->un_dp->type = ST_TYPE_INVALID;
2635 			dp->type = ST_TYPE_INVALID;
2636 			return (1);
2637 		}
2638 		return (0);
2639 	}
2640 	dp->space_timeout = timeout;
2641 
2642 	rval = st_get_timeouts_value(un, SCMD_LOAD, &timeout, 0);
2643 	if (rval) {
2644 		if (rval == EACCES) {
2645 			un->un_dp->type = ST_TYPE_INVALID;
2646 			dp->type = ST_TYPE_INVALID;
2647 			return (1);
2648 		}
2649 		return (0);
2650 	}
2651 	dp->load_timeout = timeout;
2652 	dp->unload_timeout = timeout;
2653 
2654 	rval = st_get_timeouts_value(un, SCMD_REWIND, &timeout, 0);
2655 	if (rval) {
2656 		if (rval == EACCES) {
2657 			un->un_dp->type = ST_TYPE_INVALID;
2658 			dp->type = ST_TYPE_INVALID;
2659 			return (1);
2660 		}
2661 		return (0);
2662 	}
2663 	dp->rewind_timeout = timeout;
2664 
2665 	rval = st_get_timeouts_value(un, SCMD_INQUIRY, &timeout, 0);
2666 	if (rval) {
2667 		if (rval == EACCES) {
2668 			un->un_dp->type = ST_TYPE_INVALID;
2669 			dp->type = ST_TYPE_INVALID;
2670 			return (1);
2671 		}
2672 		return (0);
2673 	}
2674 	dp->non_motion_timeout = timeout;
2675 
2676 	return (1);
2677 }
2678 
2679 static int
2680 st_get_timeouts_value(struct scsi_tape *un, uchar_t option_code,
2681     ushort_t *timeout_value, ushort_t service_action)
2682 {
2683 	uchar_t *timeouts;
2684 	uchar_t *oper;
2685 	uchar_t support;
2686 	uchar_t cdbsize;
2687 	uchar_t ctdp;
2688 	size_t buflen;
2689 	int rval;
2690 
2691 	ST_FUNC(ST_DEVINFO, st_get_timeouts_value);
2692 
2693 	buflen = sizeof (struct one_com_des) +
2694 	    sizeof (struct com_timeout_des);
2695 	oper = kmem_zalloc(buflen, KM_SLEEP);
2696 	rval = st_report_supported_operation(un, oper, option_code,
2697 	    service_action);
2698 
2699 	if (rval) {
2700 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2701 		    "st_get_timeouts_value(): "
2702 		    "fail to timeouts value for command %d.\n", option_code);
2703 		kmem_free(oper, buflen);
2704 		return (rval);
2705 	}
2706 
2707 	support = ((struct one_com_des *)oper)->support;
2708 	if ((support != SUPPORT_VALUES_SUPPORT_SCSI) &&
2709 	    (support != SUPPORT_VALUES_SUPPORT_VENDOR)) {
2710 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2711 		    "st_get_timeouts_value(): "
2712 		    "command %d is not supported.\n", option_code);
2713 		kmem_free(oper, buflen);
2714 		return (ENOTSUP);
2715 	}
2716 
2717 	ctdp = ((struct one_com_des *)oper)->ctdp;
2718 	if (!ctdp) {
2719 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2720 		    "st_get_timeouts_value(): "
2721 		    "command timeout is not included.\n");
2722 		kmem_free(oper, buflen);
2723 		return (ENOTSUP);
2724 	}
2725 
2726 	cdbsize = BE_16(((struct one_com_des *)oper)->cdb_size);
2727 	timeouts = (uchar_t *)(oper + cdbsize + 4);
2728 
2729 	/*
2730 	 * Timeout value in seconds is 4 bytes, but we only support the lower 2
2731 	 * bytes. If the higher 2 bytes are not zero, the timeout value is set
2732 	 * to 0xFFFF.
2733 	 */
2734 	if (*(timeouts + 8) != 0 || *(timeouts + 9) != 0) {
2735 		*timeout_value = USHRT_MAX;
2736 	} else {
2737 		*timeout_value = ((*(timeouts + 10)) << 8) |
2738 		    (*(timeouts + 11));
2739 	}
2740 
2741 	kmem_free(oper, buflen);
2742 	return (0);
2743 }
2744 
2745 static int
2746 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2747 {
2748 	int i;
2749 
2750 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2751 
2752 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2753 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2754 
2755 	/*
2756 	 * Make up a name
2757 	 */
2758 	bcopy("Vendor '", dp->name, 8);
2759 	bcopy(vidpid, &dp->name[8], VIDLEN);
2760 	bcopy("' Product '", &dp->name[16], 11);
2761 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2762 	dp->name[ST_NAMESIZE - 2] = '\'';
2763 	dp->name[ST_NAMESIZE - 1] = '\0';
2764 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2765 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2766 	/*
2767 	 * 'clean' vendor and product strings of non-printing chars
2768 	 */
2769 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2770 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2771 			dp->name[i] = '.';
2772 		}
2773 	}
2774 	dp->type = ST_TYPE_INVALID;
2775 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2776 
2777 	return (1); /* Can Not Fail */
2778 }
2779 
2780 /*
2781  * Regular Unix Entry points
2782  */
2783 
2784 
2785 
2786 /* ARGSUSED */
2787 static int
2788 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2789 {
2790 	dev_t dev = *dev_p;
2791 	int rval = 0;
2792 
2793 	GET_SOFT_STATE(dev);
2794 
2795 	ST_ENTR(ST_DEVINFO, st_open);
2796 
2797 	/*
2798 	 * validate that we are addressing a sensible unit
2799 	 */
2800 	mutex_enter(ST_MUTEX);
2801 
2802 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2803 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2804 	    st_dev_name(dev), *dev_p, flag, otyp);
2805 
2806 	/*
2807 	 * All device accesss go thru st_strategy() where we check
2808 	 * suspend status
2809 	 */
2810 
2811 	if (!un->un_attached) {
2812 		st_known_tape_type(un);
2813 		if (!un->un_attached) {
2814 			rval = ENXIO;
2815 			goto exit;
2816 		}
2817 
2818 	}
2819 
2820 	/*
2821 	 * Check for the case of the tape in the middle of closing.
2822 	 * This isn't simply a check of the current state, because
2823 	 * we could be in state of sensing with the previous state
2824 	 * that of closing.
2825 	 *
2826 	 * And don't allow multiple opens.
2827 	 */
2828 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2829 		un->un_laststate = un->un_state;
2830 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2831 		while (IS_CLOSING(un) ||
2832 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2833 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2834 				rval = EINTR;
2835 				un->un_state = un->un_laststate;
2836 				goto exit;
2837 			}
2838 		}
2839 	} else if (un->un_state != ST_STATE_CLOSED) {
2840 		rval = EBUSY;
2841 		goto busy;
2842 	}
2843 
2844 	/*
2845 	 * record current dev
2846 	 */
2847 	un->un_dev = dev;
2848 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2849 	un->un_errno = 0;	/* no errors yet */
2850 	un->un_restore_pos = 0;
2851 	un->un_rqs_state = 0;
2852 
2853 	/*
2854 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2855 	 * anything, leave internal states alone, if fileno >= 0
2856 	 */
2857 	if (flag & (FNDELAY | FNONBLOCK)) {
2858 		switch (un->un_pos.pmode) {
2859 
2860 		case invalid:
2861 			un->un_state = ST_STATE_OFFLINE;
2862 			break;
2863 
2864 		case legacy:
2865 			/*
2866 			 * If position is anything other than rewound.
2867 			 */
2868 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2869 				/*
2870 				 * set un_read_only/write-protect status.
2871 				 *
2872 				 * If the tape is not bot we can assume
2873 				 * that mspl->wp_status is set properly.
2874 				 * else
2875 				 * we need to do a mode sense/Tur once
2876 				 * again to get the actual tape status.(since
2877 				 * user might have replaced the tape)
2878 				 * Hence make the st state OFFLINE so that
2879 				 * we re-intialize the tape once again.
2880 				 */
2881 				un->un_read_only =
2882 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2883 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2884 			} else {
2885 				un->un_state = ST_STATE_OFFLINE;
2886 			}
2887 			break;
2888 		case logical:
2889 			if (un->un_pos.lgclblkno == 0) {
2890 				un->un_state = ST_STATE_OFFLINE;
2891 			} else {
2892 				un->un_read_only =
2893 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2894 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2895 			}
2896 			break;
2897 		}
2898 		rval = 0;
2899 	} else {
2900 		/*
2901 		 * Not opening O_NDELAY.
2902 		 */
2903 		un->un_state = ST_STATE_OPENING;
2904 
2905 		/*
2906 		 * Clear error entry stack
2907 		 */
2908 		st_empty_error_stack(un);
2909 
2910 		rval = st_tape_init(un);
2911 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2912 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2913 			rval = 0; /* so open doesn't fail */
2914 		} else if (rval) {
2915 			/*
2916 			 * Release the tape unit, if reserved and not
2917 			 * preserve reserve.
2918 			 */
2919 			if ((un->un_rsvd_status &
2920 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2921 				(void) st_reserve_release(un, ST_RELEASE,
2922 				    st_uscsi_cmd);
2923 			}
2924 		} else {
2925 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2926 		}
2927 	}
2928 
2929 exit:
2930 	/*
2931 	 * we don't want any uninvited guests scrogging our data when we're
2932 	 * busy with something, so for successful opens or failed opens
2933 	 * (except for EBUSY), reset these counters and state appropriately.
2934 	 */
2935 	if (rval != EBUSY) {
2936 		if (rval) {
2937 			un->un_state = ST_STATE_CLOSED;
2938 		}
2939 		un->un_err_resid = 0;
2940 		un->un_retry_ct = 0;
2941 	}
2942 busy:
2943 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2944 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2945 	mutex_exit(ST_MUTEX);
2946 	return (rval);
2947 
2948 }
2949 
2950 static int
2951 st_tape_init(struct scsi_tape *un)
2952 {
2953 	int err;
2954 	int rval = 0;
2955 
2956 	ST_FUNC(ST_DEVINFO, st_tape_init);
2957 
2958 	ASSERT(mutex_owned(ST_MUTEX));
2959 
2960 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2961 	    "st_tape_init(un = 0x%p, oflags = %d)\n", (void*)un, un->un_oflags);
2962 
2963 	/*
2964 	 * Clean up after any errors left by 'last' close.
2965 	 * This also handles the case of the initial open.
2966 	 */
2967 	if (un->un_state != ST_STATE_INITIALIZING) {
2968 		un->un_laststate = un->un_state;
2969 		un->un_state = ST_STATE_OPENING;
2970 	}
2971 
2972 	un->un_kbytes_xferred = 0;
2973 
2974 	/*
2975 	 * do a throw away TUR to clear check condition
2976 	 */
2977 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2978 
2979 	/*
2980 	 * If test unit ready fails because the drive is reserved
2981 	 * by another host fail the open for no access.
2982 	 */
2983 	if (err) {
2984 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2985 			un->un_state = ST_STATE_CLOSED;
2986 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2987 			    "st_tape_init: RESERVATION CONFLICT\n");
2988 			rval = EACCES;
2989 			goto exit;
2990 		} else if ((un->un_rsvd_status &
2991 		    ST_APPLICATION_RESERVATIONS) != 0) {
2992 			if ((ST_RQSENSE != NULL) &&
2993 			    (ST_RQSENSE->es_add_code == 0x2a &&
2994 			    ST_RQSENSE->es_qual_code == 0x03)) {
2995 				un->un_state = ST_STATE_CLOSED;
2996 				rval = EACCES;
2997 				goto exit;
2998 			}
2999 		}
3000 	}
3001 
3002 	/*
3003 	 * Tape self identification could fail if the tape drive is used by
3004 	 * another host during attach time. We try to get the tape type
3005 	 * again. This is also applied to any posponed configuration methods.
3006 	 */
3007 	if (un->un_dp->type == ST_TYPE_INVALID) {
3008 		un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
3009 		st_known_tape_type(un);
3010 	}
3011 
3012 	/*
3013 	 * If the tape type is still invalid, try to determine the generic
3014 	 * configuration.
3015 	 */
3016 	if (un->un_dp->type == ST_TYPE_INVALID) {
3017 		rval = st_determine_generic(un);
3018 		if (rval) {
3019 			if (rval != EACCES) {
3020 				rval = EIO;
3021 			}
3022 			un->un_state = ST_STATE_CLOSED;
3023 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3024 			    "st_tape_init: %s invalid type\n",
3025 			    rval == EACCES ? "EACCES" : "EIO");
3026 			goto exit;
3027 		}
3028 		/*
3029 		 * If this is a Unknown Type drive,
3030 		 * Use the READ BLOCK LIMITS to determine if
3031 		 * allow large xfer is approprate if not globally
3032 		 * disabled with st_allow_large_xfer.
3033 		 */
3034 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
3035 	} else {
3036 
3037 		/*
3038 		 * If we allow_large_xfer (ie >64k) and have not yet found out
3039 		 * the max block size supported by the drive,
3040 		 * find it by issueing a READ_BLKLIM command.
3041 		 * if READ_BLKLIM cmd fails, assume drive doesn't
3042 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
3043 		 */
3044 		un->un_allow_large_xfer = st_allow_large_xfer &&
3045 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
3046 	}
3047 	/*
3048 	 * if maxbsize is unknown, set the maximum block size.
3049 	 */
3050 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
3051 
3052 		/*
3053 		 * Get the Block limits of the tape drive.
3054 		 * if un->un_allow_large_xfer = 0 , then make sure
3055 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
3056 		 */
3057 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
3058 
3059 		err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3060 		if (err) {
3061 			/* Retry */
3062 			err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3063 		}
3064 		if (!err) {
3065 
3066 			/*
3067 			 * if cmd successful, use limit returned
3068 			 */
3069 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
3070 			    (un->un_rbl->max_mid << 8) +
3071 			    un->un_rbl->max_lo;
3072 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
3073 			    un->un_rbl->min_lo;
3074 			un->un_data_mod = 1 << un->un_rbl->granularity;
3075 			if ((un->un_maxbsize == 0) ||
3076 			    (un->un_allow_large_xfer == 0 &&
3077 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
3078 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3079 
3080 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
3081 				/*
3082 				 * Drive is not one that is configured, But the
3083 				 * READ BLOCK LIMITS tells us it can do large
3084 				 * xfers.
3085 				 */
3086 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
3087 					un->un_dp->options |=
3088 					    ST_NO_RECSIZE_LIMIT;
3089 				}
3090 				/*
3091 				 * If max and mimimum block limits are the
3092 				 * same this is a fixed block size device.
3093 				 */
3094 				if (un->un_maxbsize == un->un_minbsize) {
3095 					un->un_dp->options &= ~ST_VARIABLE;
3096 				}
3097 			}
3098 
3099 			if (un->un_minbsize == 0) {
3100 				un->un_minbsize = 1;
3101 			}
3102 
3103 		} else { /* error on read block limits */
3104 
3105 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3106 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
3107 			    " errno = %d un_rsvd_status = 0x%X\n",
3108 			    err, un->un_rsvd_status);
3109 
3110 			/*
3111 			 * since read block limits cmd failed,
3112 			 * do not allow large xfers.
3113 			 * use old values in st_minphys
3114 			 */
3115 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
3116 				rval = EACCES;
3117 			} else {
3118 				un->un_allow_large_xfer = 0;
3119 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3120 				    "!Disabling large transfers\n");
3121 
3122 				/*
3123 				 * we guess maxbsize and minbsize
3124 				 */
3125 				if (un->un_bsize) {
3126 					un->un_maxbsize = un->un_minbsize =
3127 					    un->un_bsize;
3128 				} else {
3129 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3130 					un->un_minbsize = 1;
3131 				}
3132 				/*
3133 				 * Data Mod must be set,
3134 				 * Even if read block limits fails.
3135 				 * Prevents Divide By Zero in st_rw().
3136 				 */
3137 				un->un_data_mod = 1;
3138 			}
3139 		}
3140 		if (un->un_rbl) {
3141 			kmem_free(un->un_rbl, RBLSIZE);
3142 			un->un_rbl = NULL;
3143 		}
3144 
3145 		if (rval) {
3146 			goto exit;
3147 		}
3148 	}
3149 
3150 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3151 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
3152 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
3153 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
3154 
3155 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
3156 
3157 	if (err != 0) {
3158 		if (err == EINTR) {
3159 			un->un_laststate = un->un_state;
3160 			un->un_state = ST_STATE_CLOSED;
3161 			rval = EINTR;
3162 			goto exit;
3163 		}
3164 		/*
3165 		 * Make sure the tape is ready
3166 		 */
3167 		un->un_pos.pmode = invalid;
3168 		if (un->un_status != KEY_UNIT_ATTENTION) {
3169 			/*
3170 			 * allow open no media.  Subsequent MTIOCSTATE
3171 			 * with media present will complete the open
3172 			 * logic.
3173 			 */
3174 			un->un_laststate = un->un_state;
3175 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
3176 				un->un_mediastate = MTIO_EJECTED;
3177 				un->un_state = ST_STATE_OFFLINE;
3178 				rval = 0;
3179 				goto exit;
3180 			} else {
3181 				un->un_state = ST_STATE_CLOSED;
3182 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3183 				    "st_tape_init EIO no media, not opened "
3184 				    "O_NONBLOCK|O_EXCL\n");
3185 				rval = EIO;
3186 				goto exit;
3187 			}
3188 		}
3189 	}
3190 
3191 	/*
3192 	 * On each open, initialize block size from drivetype struct,
3193 	 * as it could have been changed by MTSRSZ ioctl.
3194 	 * Now, ST_VARIABLE simply means drive is capable of variable
3195 	 * mode. All drives are assumed to support fixed records.
3196 	 * Hence, un_bsize tells what mode the drive is in.
3197 	 *	un_bsize	= 0	- variable record length
3198 	 *			= x	- fixed record length is x
3199 	 */
3200 	un->un_bsize = un->un_dp->bsize;
3201 
3202 	/*
3203 	 * If saved position is valid go there
3204 	 */
3205 	if (un->un_restore_pos) {
3206 		un->un_restore_pos = 0;
3207 		un->un_pos.fileno = un->un_save_fileno;
3208 		un->un_pos.blkno = un->un_save_blkno;
3209 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &un->un_pos);
3210 		if (rval != 0) {
3211 			if (rval != EACCES) {
3212 				rval = EIO;
3213 			}
3214 			un->un_laststate = un->un_state;
3215 			un->un_state = ST_STATE_CLOSED;
3216 			goto exit;
3217 		}
3218 	}
3219 
3220 	if (un->un_pos.pmode == invalid) {
3221 		rval = st_loadtape(un);
3222 		if (rval) {
3223 			if (rval != EACCES) {
3224 				rval = EIO;
3225 			}
3226 			un->un_laststate = un->un_state;
3227 			un->un_state = ST_STATE_CLOSED;
3228 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3229 			    "st_tape_init: %s can't open tape\n",
3230 			    rval == EACCES ? "EACCES" : "EIO");
3231 			goto exit;
3232 		}
3233 	}
3234 
3235 	/*
3236 	 * do a mode sense to pick up state of current write-protect,
3237 	 * Could cause reserve and fail due to conflict.
3238 	 */
3239 	if (un->un_unit_attention_flags) {
3240 		rval = st_modesense(un);
3241 		if (rval == EACCES) {
3242 			goto exit;
3243 		}
3244 	}
3245 
3246 	/*
3247 	 * If we are opening the tape for writing, check
3248 	 * to make sure that the tape can be written.
3249 	 */
3250 	if (un->un_oflags & FWRITE) {
3251 		err = 0;
3252 		if (un->un_mspl->wp) {
3253 			un->un_status = KEY_WRITE_PROTECT;
3254 			un->un_laststate = un->un_state;
3255 			un->un_state = ST_STATE_CLOSED;
3256 			rval = EACCES;
3257 			/*
3258 			 * STK sets the wp bit if volsafe tape is loaded.
3259 			 */
3260 			if ((un->un_dp->type == MT_ISSTK9840) &&
3261 			    (un->un_dp->options & ST_WORMABLE)) {
3262 				un->un_read_only = RDONLY;
3263 			} else {
3264 				goto exit;
3265 			}
3266 		} else {
3267 			un->un_read_only = RDWR;
3268 		}
3269 	} else {
3270 		un->un_read_only = RDONLY;
3271 	}
3272 
3273 	if (un->un_dp->options & ST_WORMABLE &&
3274 	    un->un_unit_attention_flags) {
3275 		un->un_read_only |= un->un_wormable(un);
3276 
3277 		if (((un->un_read_only == WORM) ||
3278 		    (un->un_read_only == RDWORM)) &&
3279 		    ((un->un_oflags & FWRITE) == FWRITE)) {
3280 			un->un_status = KEY_DATA_PROTECT;
3281 			rval = EACCES;
3282 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3283 			    "read_only = %d eof = %d oflag = %d\n",
3284 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3285 		}
3286 	}
3287 
3288 	/*
3289 	 * If we're opening the tape write-only, we need to
3290 	 * write 2 filemarks on the HP 1/2 inch drive, to
3291 	 * create a null file.
3292 	 */
3293 	if ((un->un_read_only == RDWR) ||
3294 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3295 		if (un->un_dp->options & ST_REEL) {
3296 			un->un_fmneeded = 2;
3297 		} else {
3298 			un->un_fmneeded = 1;
3299 		}
3300 	} else {
3301 		un->un_fmneeded = 0;
3302 	}
3303 
3304 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3305 	    "fmneeded = %x\n", un->un_fmneeded);
3306 
3307 	/*
3308 	 * Make sure the density can be selected correctly.
3309 	 * If WORM can only write at the append point which in most cases
3310 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3311 	 * to set and try densities if a BOP.
3312 	 */
3313 	if (st_determine_density(un,
3314 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3315 		un->un_status = KEY_ILLEGAL_REQUEST;
3316 		un->un_laststate = un->un_state;
3317 		un->un_state = ST_STATE_CLOSED;
3318 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3319 		    "st_tape_init: EIO can't determine density\n");
3320 		rval = EIO;
3321 		goto exit;
3322 	}
3323 
3324 	/*
3325 	 * Destroy the knowledge that we have 'determined'
3326 	 * density so that a later read at BOT comes along
3327 	 * does the right density determination.
3328 	 */
3329 
3330 	un->un_density_known = 0;
3331 
3332 
3333 	/*
3334 	 * Okay, the tape is loaded and either at BOT or somewhere past.
3335 	 * Mark the state such that any I/O or tape space operations
3336 	 * will get/set the right density, etc..
3337 	 */
3338 	un->un_laststate = un->un_state;
3339 	un->un_lastop = ST_OP_NIL;
3340 	un->un_mediastate = MTIO_INSERTED;
3341 	cv_broadcast(&un->un_state_cv);
3342 
3343 	/*
3344 	 *  Set test append flag if writing.
3345 	 *  First write must check that tape is positioned correctly.
3346 	 */
3347 	un->un_test_append = (un->un_oflags & FWRITE);
3348 
3349 	/*
3350 	 * if there are pending unit attention flags.
3351 	 * Check that the media has not changed.
3352 	 */
3353 	if (un->un_unit_attention_flags) {
3354 		rval = st_get_media_identification(un, st_uscsi_cmd);
3355 		if (rval != 0 && rval != EACCES) {
3356 			rval = EIO;
3357 		}
3358 		un->un_unit_attention_flags = 0;
3359 	}
3360 
3361 exit:
3362 	un->un_err_resid = 0;
3363 	un->un_last_resid = 0;
3364 	un->un_last_count = 0;
3365 
3366 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3367 	    "st_tape_init: return val = %x\n", rval);
3368 	return (rval);
3369 
3370 }
3371 
3372 
3373 
3374 /* ARGSUSED */
3375 static int
3376 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3377 {
3378 	int err = 0;
3379 	int count, last_state;
3380 	minor_t minor = getminor(dev);
3381 #ifdef	__x86
3382 	struct contig_mem *cp, *cp_temp;
3383 #endif
3384 
3385 	GET_SOFT_STATE(dev);
3386 
3387 	ST_ENTR(ST_DEVINFO, st_close);
3388 
3389 	/*
3390 	 * wait till all cmds in the pipeline have been completed
3391 	 */
3392 	mutex_enter(ST_MUTEX);
3393 
3394 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3395 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3396 
3397 	st_wait_for_io(un);
3398 
3399 	/* turn off persistent errors on close, as we want close to succeed */
3400 	st_turn_pe_off(un);
3401 
3402 	/*
3403 	 * set state to indicate that we are in process of closing
3404 	 */
3405 	last_state = un->un_laststate = un->un_state;
3406 	un->un_state = ST_STATE_CLOSING;
3407 
3408 	ST_POS(ST_DEVINFO, "st_close1:", &un->un_pos);
3409 
3410 	/*
3411 	 * BSD behavior:
3412 	 * a close always causes a silent span to the next file if we've hit
3413 	 * an EOF (but not yet read across it).
3414 	 */
3415 	if ((minor & MT_BSD) && (un->un_pos.eof == ST_EOF)) {
3416 		if (un->un_pos.pmode != invalid) {
3417 			un->un_pos.fileno++;
3418 			un->un_pos.blkno = 0;
3419 		}
3420 		un->un_pos.eof = ST_NO_EOF;
3421 	}
3422 
3423 	/*
3424 	 * SVR4 behavior for skipping to next file:
3425 	 *
3426 	 * If we have not seen a filemark, space to the next file
3427 	 *
3428 	 * If we have already seen the filemark we are physically in the next
3429 	 * file and we only increment the filenumber
3430 	 */
3431 	if (((minor & (MT_BSD | MT_NOREWIND)) == MT_NOREWIND) &&
3432 	    (flag & FREAD) &&		/* reading or at least asked to */
3433 	    (un->un_mediastate == MTIO_INSERTED) &&	/* tape loaded */
3434 	    (un->un_pos.pmode != invalid) &&		/* XXX position known */
3435 	    ((un->un_pos.blkno != 0) && 		/* inside a file */
3436 	    (un->un_lastop != ST_OP_WRITE) &&		/* Didn't just write */
3437 	    (un->un_lastop != ST_OP_WEOF))) {		/* or write filemarks */
3438 		switch (un->un_pos.eof) {
3439 		case ST_NO_EOF:
3440 			/*
3441 			 * if we were reading and did not read the complete file
3442 			 * skip to the next file, leaving the tape correctly
3443 			 * positioned to read the first record of the next file
3444 			 * Check first for REEL if we are at EOT by trying to
3445 			 * read a block
3446 			 */
3447 			if ((un->un_dp->options & ST_REEL) &&
3448 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3449 			    (un->un_pos.blkno == 0)) {
3450 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3451 					ST_DEBUG2(ST_DEVINFO, st_label,
3452 					    SCSI_DEBUG,
3453 					    "st_close : EIO can't space\n");
3454 					err = EIO;
3455 					goto error_out;
3456 				}
3457 				if (un->un_pos.eof >= ST_EOF_PENDING) {
3458 					un->un_pos.eof = ST_EOT_PENDING;
3459 					un->un_pos.fileno += 1;
3460 					un->un_pos.blkno   = 0;
3461 					break;
3462 				}
3463 			}
3464 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3465 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3466 				    "st_close: EIO can't space #2\n");
3467 				err = EIO;
3468 				goto error_out;
3469 			} else {
3470 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3471 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3472 				    un->un_pos.fileno, un->un_pos.blkno,
3473 				    un->un_pos.eof);
3474 				un->un_pos.eof = ST_NO_EOF;
3475 			}
3476 			break;
3477 
3478 		case ST_EOF_PENDING:
3479 		case ST_EOF:
3480 			un->un_pos.fileno += 1;
3481 			un->un_pos.lgclblkno += 1;
3482 			un->un_pos.blkno   = 0;
3483 			un->un_pos.eof = ST_NO_EOF;
3484 			break;
3485 
3486 		case ST_EOT:
3487 		case ST_EOT_PENDING:
3488 		case ST_EOM:
3489 			/* nothing to do */
3490 			break;
3491 		default:
3492 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
3493 			    "Undefined state 0x%x", un->un_pos.eof);
3494 
3495 		}
3496 	}
3497 
3498 
3499 	/*
3500 	 * For performance reasons (HP 88780), the driver should
3501 	 * postpone writing the second tape mark until just before a file
3502 	 * positioning ioctl is issued (e.g., rewind).	This means that
3503 	 * the user must not manually rewind the tape because the tape will
3504 	 * be missing the second tape mark which marks EOM.
3505 	 * However, this small performance improvement is not worth the risk.
3506 	 */
3507 
3508 	/*
3509 	 * We need to back up over the filemark we inadvertently popped
3510 	 * over doing a read in between the two filemarks that constitute
3511 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3512 	 * set while reading.
3513 	 *
3514 	 * If we happen to be at physical eot (ST_EOM) (writing case),
3515 	 * the writing of filemark(s) will clear the ST_EOM state, which
3516 	 * we don't want, so we save this state and restore it later.
3517 	 */
3518 
3519 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3520 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3521 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3522 
3523 	if (un->un_pos.eof == ST_EOT_PENDING) {
3524 		if (minor & MT_NOREWIND) {
3525 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3526 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3527 				    "st_close: EIO can't space #3\n");
3528 				err = EIO;
3529 				goto error_out;
3530 			} else {
3531 				un->un_pos.blkno = 0;
3532 				un->un_pos.eof = ST_EOT;
3533 			}
3534 		} else {
3535 			un->un_pos.eof = ST_NO_EOF;
3536 		}
3537 
3538 	/*
3539 	 * Do we need to write a file mark?
3540 	 *
3541 	 * only write filemarks if there are fmks to be written and
3542 	 *   - open for write (possibly read/write)
3543 	 *   - the last operation was a write
3544 	 * or:
3545 	 *   -	opened for wronly
3546 	 *   -	no data was written
3547 	 */
3548 	} else if ((un->un_pos.pmode != invalid) &&
3549 	    (un->un_fmneeded > 0) &&
3550 	    (((flag & FWRITE) &&
3551 	    ((un->un_lastop == ST_OP_WRITE)||(un->un_lastop == ST_OP_WEOF))) ||
3552 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3553 
3554 		/* save ST_EOM state */
3555 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3556 
3557 		/*
3558 		 * Note that we will write a filemark if we had opened
3559 		 * the tape write only and no data was written, thus
3560 		 * creating a null file.
3561 		 *
3562 		 * If the user already wrote one, we only have to write 1 more.
3563 		 * If they wrote two, we don't have to write any.
3564 		 */
3565 
3566 		count = un->un_fmneeded;
3567 		if (count > 0) {
3568 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, count, SYNC_CMD)) {
3569 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3570 				    "st_close : EIO can't wfm\n");
3571 				err = EIO;
3572 				goto error_out;
3573 			}
3574 			if ((un->un_dp->options & ST_REEL) &&
3575 			    (minor & MT_NOREWIND)) {
3576 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3577 					ST_DEBUG2(ST_DEVINFO, st_label,
3578 					    SCSI_DEBUG,
3579 					    "st_close : EIO space fmk(-1)\n");
3580 					err = EIO;
3581 					goto error_out;
3582 				}
3583 				un->un_pos.eof = ST_NO_EOF;
3584 				/* fix up block number */
3585 				un->un_pos.blkno = 0;
3586 			}
3587 		}
3588 
3589 		/*
3590 		 * If we aren't going to be rewinding, and we were at
3591 		 * physical eot, restore the state that indicates we
3592 		 * are at physical eot. Once you have reached physical
3593 		 * eot, and you close the tape, the only thing you can
3594 		 * do on the next open is to rewind. Access to trailer
3595 		 * records is only allowed without closing the device.
3596 		 */
3597 		if ((minor & MT_NOREWIND) == 0 && was_at_eom) {
3598 			un->un_pos.eof = ST_EOM;
3599 		}
3600 	}
3601 
3602 	/*
3603 	 * report soft errors if enabled and available, if we never accessed
3604 	 * the drive, don't get errors. This will prevent some DAT error
3605 	 * messages upon LOG SENSE.
3606 	 */
3607 	if (st_report_soft_errors_on_close &&
3608 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3609 	    (last_state != ST_STATE_OFFLINE)) {
3610 		if (st_report_soft_errors(dev, flag)) {
3611 			err = EIO;
3612 			goto error_out;
3613 		}
3614 	}
3615 
3616 
3617 	/*
3618 	 * Do we need to rewind? Can we rewind?
3619 	 */
3620 	if ((minor & MT_NOREWIND) == 0 &&
3621 	    un->un_pos.pmode != invalid && err == 0) {
3622 		/*
3623 		 * We'd like to rewind with the
3624 		 * 'immediate' bit set, but this
3625 		 * causes problems on some drives
3626 		 * where subsequent opens get a
3627 		 * 'NOT READY' error condition
3628 		 * back while the tape is rewinding,
3629 		 * which is impossible to distinguish
3630 		 * from the condition of 'no tape loaded'.
3631 		 *
3632 		 * Also, for some targets, if you disconnect
3633 		 * with the 'immediate' bit set, you don't
3634 		 * actually return right away, i.e., the
3635 		 * target ignores your request for immediate
3636 		 * return.
3637 		 *
3638 		 * Instead, we'll fire off an async rewind
3639 		 * command. We'll mark the device as closed,
3640 		 * and any subsequent open will stall on
3641 		 * the first TEST_UNIT_READY until the rewind
3642 		 * completes.
3643 		 */
3644 
3645 		/*
3646 		 * Used to be if reserve was not supported we'd send an
3647 		 * asynchronious rewind. Comments above may be slightly invalid
3648 		 * as the immediate bit was never set. Doing an immedate rewind
3649 		 * makes sense, I think fixes to not ready status might handle
3650 		 * the problems described above.
3651 		 */
3652 		if (un->un_sd->sd_inq->inq_ansi < 2) {
3653 			if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
3654 				err = EIO;
3655 			}
3656 		} else {
3657 			/* flush data for older drives per scsi spec. */
3658 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD)) {
3659 				err = EIO;
3660 			} else {
3661 				/* release the drive before rewind immediate */
3662 				if ((un->un_rsvd_status &
3663 				    (ST_RESERVE | ST_PRESERVE_RESERVE)) ==
3664 				    ST_RESERVE) {
3665 					if (st_reserve_release(un, ST_RELEASE,
3666 					    st_uscsi_cmd)) {
3667 						err = EIO;
3668 					}
3669 				}
3670 
3671 				/* send rewind with immediate bit set */
3672 				if (st_cmd(un, SCMD_REWIND, 1, ASYNC_CMD)) {
3673 					err = EIO;
3674 				}
3675 			}
3676 		}
3677 		/*
3678 		 * Setting positions invalid in case the rewind doesn't
3679 		 * happen. Drives don't like to rewind if resets happen
3680 		 * they will tend to move back to where the rewind was
3681 		 * issued if a reset or something happens so that if a
3682 		 * write happens the data doesn't get clobbered.
3683 		 *
3684 		 * Not a big deal if the position is invalid when the
3685 		 * open occures it will do a read position.
3686 		 */
3687 		un->un_pos.pmode = invalid;
3688 		un->un_running.pmode = invalid;
3689 
3690 		if (err == EIO) {
3691 			goto error_out;
3692 		}
3693 	}
3694 
3695 	/*
3696 	 * eject tape if necessary
3697 	 */
3698 	if (un->un_eject_tape_on_failure) {
3699 		un->un_eject_tape_on_failure = 0;
3700 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3701 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3702 			    "st_close : can't unload tape\n");
3703 			err = EIO;
3704 			goto error_out;
3705 		} else {
3706 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3707 			    "st_close : tape unloaded \n");
3708 			un->un_pos.eof = ST_NO_EOF;
3709 			un->un_mediastate = MTIO_EJECTED;
3710 		}
3711 	}
3712 	/*
3713 	 * Release the tape unit, if default reserve/release
3714 	 * behaviour.
3715 	 */
3716 	if ((un->un_rsvd_status &
3717 	    (ST_RESERVE | ST_PRESERVE_RESERVE |
3718 	    ST_APPLICATION_RESERVATIONS)) == ST_RESERVE) {
3719 		(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
3720 	}
3721 error_out:
3722 	/*
3723 	 * clear up state
3724 	 */
3725 	un->un_laststate = un->un_state;
3726 	un->un_state = ST_STATE_CLOSED;
3727 	un->un_lastop = ST_OP_NIL;
3728 	un->un_throttle = 1;	/* assume one request at time, for now */
3729 	un->un_retry_ct = 0;
3730 	un->un_errno = 0;
3731 	un->un_swr_token = (opaque_t)NULL;
3732 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3733 
3734 	/* Restore the options to the init time settings */
3735 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3736 		un->un_dp->options |= ST_READ_IGNORE_ILI;
3737 	} else {
3738 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3739 	}
3740 
3741 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3742 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3743 	} else {
3744 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3745 	}
3746 
3747 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3748 		un->un_dp->options |= ST_SHORT_FILEMARKS;
3749 	} else {
3750 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3751 	}
3752 
3753 	ASSERT(mutex_owned(ST_MUTEX));
3754 
3755 	/*
3756 	 * Signal anyone awaiting a close operation to complete.
3757 	 */
3758 	cv_signal(&un->un_clscv);
3759 
3760 	/*
3761 	 * any kind of error on closing causes all state to be tossed
3762 	 */
3763 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3764 		/*
3765 		 * note that st_intr has already set
3766 		 * un_pos.pmode to invalid.
3767 		 */
3768 		un->un_density_known = 0;
3769 	}
3770 
3771 #ifdef	__x86
3772 	/*
3773 	 * free any contiguous mem alloc'ed for big block I/O
3774 	 */
3775 	cp = un->un_contig_mem;
3776 	while (cp) {
3777 		if (cp->cm_addr) {
3778 			ddi_dma_mem_free(&cp->cm_acc_hdl);
3779 		}
3780 		cp_temp = cp;
3781 		cp = cp->cm_next;
3782 		kmem_free(cp_temp,
3783 		    sizeof (struct contig_mem) + biosize());
3784 	}
3785 	un->un_contig_mem_total_num = 0;
3786 	un->un_contig_mem_available_num = 0;
3787 	un->un_contig_mem = NULL;
3788 	un->un_max_contig_mem_len = 0;
3789 #endif
3790 
3791 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3792 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3793 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3794 
3795 	mutex_exit(ST_MUTEX);
3796 	return (err);
3797 }
3798 
3799 /*
3800  * These routines perform raw i/o operations.
3801  */
3802 
3803 /* ARGSUSED2 */
3804 static int
3805 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3806 {
3807 #ifdef STDEBUG
3808 	GET_SOFT_STATE(dev);
3809 	ST_ENTR(ST_DEVINFO, st_aread);
3810 #endif
3811 	return (st_arw(dev, aio, B_READ));
3812 }
3813 
3814 
3815 /* ARGSUSED2 */
3816 static int
3817 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3818 {
3819 #ifdef STDEBUG
3820 	GET_SOFT_STATE(dev);
3821 	ST_ENTR(ST_DEVINFO, st_awrite);
3822 #endif
3823 	return (st_arw(dev, aio, B_WRITE));
3824 }
3825 
3826 
3827 
3828 /* ARGSUSED */
3829 static int
3830 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3831 {
3832 #ifdef STDEBUG
3833 	GET_SOFT_STATE(dev);
3834 	ST_ENTR(ST_DEVINFO, st_read);
3835 #endif
3836 	return (st_rw(dev, uiop, B_READ));
3837 }
3838 
3839 /* ARGSUSED */
3840 static int
3841 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3842 {
3843 #ifdef STDEBUG
3844 	GET_SOFT_STATE(dev);
3845 	ST_ENTR(ST_DEVINFO, st_write);
3846 #endif
3847 	return (st_rw(dev, uiop, B_WRITE));
3848 }
3849 
3850 /*
3851  * Due to historical reasons, old limits are: For variable-length devices:
3852  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3853  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3854  * (let it through unmodified. For fixed-length record devices:
3855  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3856  *
3857  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3858  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3859  * command to the drive).
3860  *
3861  */
3862 static void
3863 st_minphys(struct buf *bp)
3864 {
3865 	struct scsi_tape *un;
3866 
3867 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3868 
3869 	ST_FUNC(ST_DEVINFO, st_minphys);
3870 
3871 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3872 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3873 	    bp->b_bcount);
3874 
3875 	if (un->un_allow_large_xfer) {
3876 
3877 		/*
3878 		 * check un_maxbsize for variable length devices only
3879 		 */
3880 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3881 			bp->b_bcount = un->un_maxbsize;
3882 		}
3883 		/*
3884 		 * can't go more that HBA maxdma limit in either fixed-length
3885 		 * or variable-length tape drives.
3886 		 */
3887 		if (bp->b_bcount > un->un_maxdma) {
3888 			bp->b_bcount = un->un_maxdma;
3889 		}
3890 	} else {
3891 
3892 		/*
3893 		 *  use old fixed limits
3894 		 */
3895 		if (un->un_bsize == 0) {
3896 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3897 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3898 			}
3899 		} else {
3900 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3901 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3902 			}
3903 		}
3904 	}
3905 
3906 	/*
3907 	 * For regular raw I/O and Fixed Block length devices, make sure
3908 	 * the adjusted block count is a whole multiple of the device
3909 	 * block size.
3910 	 */
3911 	if (bp != un->un_sbufp && un->un_bsize) {
3912 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3913 	}
3914 }
3915 
3916 static int
3917 st_rw(dev_t dev, struct uio *uio, int flag)
3918 {
3919 	int rval = 0;
3920 	long len;
3921 
3922 	GET_SOFT_STATE(dev);
3923 
3924 	ST_FUNC(ST_DEVINFO, st_rw);
3925 
3926 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3927 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3928 	    (flag == B_READ ? rd_str: wr_str));
3929 
3930 	/* get local copy of transfer length */
3931 	len = uio->uio_iov->iov_len;
3932 
3933 	mutex_enter(ST_MUTEX);
3934 
3935 	/*
3936 	 * Clear error entry stack
3937 	 */
3938 	st_empty_error_stack(un);
3939 
3940 	/*
3941 	 * If in fixed block size mode and requested read or write
3942 	 * is not an even multiple of that block size.
3943 	 */
3944 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3945 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3946 		    "%s: not modulo %d block size\n",
3947 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3948 		rval = EINVAL;
3949 	}
3950 
3951 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3952 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3953 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3954 		    "%s: not modulo %d device granularity\n",
3955 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3956 		rval = EINVAL;
3957 	}
3958 
3959 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
3960 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
3961 		rval = EFAULT;
3962 	}
3963 
3964 	if (rval != 0) {
3965 		un->un_errno = rval;
3966 		mutex_exit(ST_MUTEX);
3967 		return (rval);
3968 	}
3969 
3970 	/*
3971 	 * Reset this so it can be set if Berkeley and read over a filemark.
3972 	 */
3973 	un->un_silent_skip = 0;
3974 	mutex_exit(ST_MUTEX);
3975 
3976 	len = uio->uio_resid;
3977 
3978 	rval = physio(st_queued_strategy, (struct buf *)NULL,
3979 	    dev, flag, st_minphys, uio);
3980 	/*
3981 	 * if we have hit logical EOT during this xfer and there is not a
3982 	 * full residue, then set eof back  to ST_EOM to make sure that
3983 	 * the user will see at least one zero write
3984 	 * after this short write
3985 	 */
3986 	mutex_enter(ST_MUTEX);
3987 	if (un->un_pos.eof > ST_NO_EOF) {
3988 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3989 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3990 	}
3991 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3992 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3993 			un->un_pos.eof = ST_EOM;
3994 		} else if (uio->uio_resid == len) {
3995 			un->un_pos.eof = ST_NO_EOF;
3996 		}
3997 	}
3998 
3999 	if (un->un_silent_skip && uio->uio_resid != len) {
4000 		un->un_pos.eof = ST_EOF;
4001 		un->un_pos.blkno = un->un_save_blkno;
4002 		un->un_pos.fileno--;
4003 	}
4004 
4005 	un->un_errno = rval;
4006 
4007 	mutex_exit(ST_MUTEX);
4008 
4009 	return (rval);
4010 }
4011 
4012 static int
4013 st_arw(dev_t dev, struct aio_req *aio, int flag)
4014 {
4015 	struct uio *uio = aio->aio_uio;
4016 	int rval = 0;
4017 	long len;
4018 
4019 	GET_SOFT_STATE(dev);
4020 
4021 	ST_FUNC(ST_DEVINFO, st_arw);
4022 
4023 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4024 	    "st_arw(dev = 0x%lx, flag = %s)\n", dev,
4025 	    (flag == B_READ ? rd_str: wr_str));
4026 
4027 	/* get local copy of transfer length */
4028 	len = uio->uio_iov->iov_len;
4029 
4030 	mutex_enter(ST_MUTEX);
4031 
4032 	/*
4033 	 * If in fixed block size mode and requested read or write
4034 	 * is not an even multiple of that block size.
4035 	 */
4036 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
4037 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4038 		    "%s: not modulo %d block size\n",
4039 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
4040 		rval = EINVAL;
4041 	}
4042 
4043 	/* If device has set granularity in the READ_BLKLIM we honor it. */
4044 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
4045 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4046 		    "%s: not modulo %d device granularity\n",
4047 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
4048 		rval = EINVAL;
4049 	}
4050 
4051 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
4052 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
4053 		rval = EFAULT;
4054 	}
4055 
4056 	if (rval != 0) {
4057 		un->un_errno = rval;
4058 		mutex_exit(ST_MUTEX);
4059 		return (rval);
4060 	}
4061 
4062 	mutex_exit(ST_MUTEX);
4063 
4064 	len = uio->uio_resid;
4065 
4066 	rval =
4067 	    aphysio(st_queued_strategy, anocancel, dev, flag, st_minphys, aio);
4068 
4069 	/*
4070 	 * if we have hit logical EOT during this xfer and there is not a
4071 	 * full residue, then set eof back  to ST_EOM to make sure that
4072 	 * the user will see at least one zero write
4073 	 * after this short write
4074 	 *
4075 	 * we keep this here just in case the application is not using
4076 	 * persistent errors
4077 	 */
4078 	mutex_enter(ST_MUTEX);
4079 	if (un->un_pos.eof > ST_NO_EOF) {
4080 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4081 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
4082 	}
4083 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
4084 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
4085 			un->un_pos.eof = ST_EOM;
4086 		} else if (uio->uio_resid == len &&
4087 		    !(un->un_persistence && un->un_persist_errors)) {
4088 			un->un_pos.eof = ST_NO_EOF;
4089 		}
4090 	}
4091 	un->un_errno = rval;
4092 	mutex_exit(ST_MUTEX);
4093 
4094 	return (rval);
4095 }
4096 
4097 
4098 
4099 static int
4100 st_queued_strategy(buf_t *bp)
4101 {
4102 	struct scsi_tape *un;
4103 	char reading = bp->b_flags & B_READ;
4104 	int wasopening = 0;
4105 
4106 	/*
4107 	 * validate arguments
4108 	 */
4109 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4110 	if (un == NULL) {
4111 		bp->b_resid = bp->b_bcount;
4112 		bioerror(bp, ENXIO);
4113 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4114 		    "st_queued_strategy: ENXIO error exit\n");
4115 		biodone(bp);
4116 		return (0);
4117 	}
4118 
4119 	ST_ENTR(ST_DEVINFO, st_queued_strategy);
4120 
4121 	mutex_enter(ST_MUTEX);
4122 
4123 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4124 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4125 	}
4126 
4127 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4128 	    "st_queued_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4129 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4130 
4131 	/*
4132 	 * If persistent errors have been flagged, just nix this one. We wait
4133 	 * for any outstanding I/O's below, so we will be in order.
4134 	 */
4135 	if (un->un_persistence && un->un_persist_errors) {
4136 		goto exit;
4137 	}
4138 
4139 	/*
4140 	 * If last command was non queued, wait till it finishes.
4141 	 */
4142 	while (un->un_sbuf_busy) {
4143 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
4144 		/* woke up because of an error */
4145 		if (un->un_persistence && un->un_persist_errors) {
4146 			goto exit;
4147 		}
4148 	}
4149 
4150 	/*
4151 	 * s_buf and recovery commands shouldn't come here.
4152 	 */
4153 	ASSERT(bp != un->un_recov_buf);
4154 	ASSERT(bp != un->un_sbufp);
4155 
4156 	/*
4157 	 * If we haven't done/checked reservation on the tape unit
4158 	 * do it now.
4159 	 */
4160 	if ((un->un_rsvd_status &
4161 	    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
4162 		if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
4163 			if (st_reserve_release(un, ST_RESERVE, st_uscsi_cmd)) {
4164 				st_bioerror(bp, un->un_errno);
4165 				goto exit;
4166 			}
4167 		} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4168 			/*
4169 			 * Enter here to restore position for possible
4170 			 * resets when the device was closed and opened
4171 			 * in O_NDELAY mode subsequently
4172 			 */
4173 			un->un_state = ST_STATE_INITIALIZING;
4174 			(void) st_cmd(un, SCMD_TEST_UNIT_READY,
4175 			    0, SYNC_CMD);
4176 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4177 		}
4178 		un->un_rsvd_status |= ST_INIT_RESERVE;
4179 	}
4180 
4181 	/*
4182 	 * If we are offline, we have to initialize everything first.
4183 	 * This is to handle either when opened with O_NDELAY, or
4184 	 * we just got a new tape in the drive, after an offline.
4185 	 * We don't observe O_NDELAY past the open,
4186 	 * as it will not make sense for tapes.
4187 	 */
4188 	if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
4189 		/*
4190 		 * reset state to avoid recursion
4191 		 */
4192 		un->un_laststate = un->un_state;
4193 		un->un_state = ST_STATE_INITIALIZING;
4194 		if (st_tape_init(un)) {
4195 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4196 			    "stioctl : OFFLINE init failure ");
4197 			un->un_state = ST_STATE_OFFLINE;
4198 			un->un_pos.pmode = invalid;
4199 			goto b_done_err;
4200 		}
4201 		/* un_restore_pos make invalid */
4202 		un->un_state = ST_STATE_OPEN_PENDING_IO;
4203 		un->un_restore_pos = 0;
4204 	}
4205 	/*
4206 	 * Check for legal operations
4207 	 */
4208 	if (un->un_pos.pmode == invalid) {
4209 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4210 		    "strategy with un->un_pos.pmode invalid\n");
4211 		goto b_done_err;
4212 	}
4213 
4214 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4215 	    "st_queued_strategy(): regular io\n");
4216 
4217 	/*
4218 	 * Process this first. If we were reading, and we're pending
4219 	 * logical eot, that means we've bumped one file mark too far.
4220 	 */
4221 
4222 	/*
4223 	 * Recursion warning: st_cmd will route back through here.
4224 	 * Not anymore st_cmd will go through st_strategy()!
4225 	 */
4226 	if (un->un_pos.eof == ST_EOT_PENDING) {
4227 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4228 			un->un_pos.pmode = invalid;
4229 			un->un_density_known = 0;
4230 			goto b_done_err;
4231 		}
4232 		un->un_pos.blkno = 0; /* fix up block number.. */
4233 		un->un_pos.eof = ST_EOT;
4234 	}
4235 
4236 	/*
4237 	 * If we are in the process of opening, we may have to
4238 	 * determine/set the correct density. We also may have
4239 	 * to do a test_append (if QIC) to see whether we are
4240 	 * in a position to append to the end of the tape.
4241 	 *
4242 	 * If we're already at logical eot, we transition
4243 	 * to ST_NO_EOF. If we're at physical eot, we punt
4244 	 * to the switch statement below to handle.
4245 	 */
4246 	if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
4247 	    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
4248 
4249 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4250 			if (st_determine_density(un, (int)reading)) {
4251 				goto b_done_err;
4252 			}
4253 		}
4254 
4255 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4256 		    "pending_io@fileno %d rw %d qic %d eof %d\n",
4257 		    un->un_pos.fileno, (int)reading,
4258 		    (un->un_dp->options & ST_QIC) ? 1 : 0,
4259 		    un->un_pos.eof);
4260 
4261 		if (!reading && un->un_pos.eof != ST_EOM) {
4262 			if (un->un_pos.eof == ST_EOT) {
4263 				un->un_pos.eof = ST_NO_EOF;
4264 			} else if (un->un_pos.pmode != invalid &&
4265 			    (un->un_dp->options & ST_QIC)) {
4266 				/*
4267 				 * st_test_append() will do it all
4268 				 */
4269 				st_test_append(bp);
4270 				mutex_exit(ST_MUTEX);
4271 				return (0);
4272 			}
4273 		}
4274 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4275 			wasopening = 1;
4276 		}
4277 		un->un_laststate = un->un_state;
4278 		un->un_state = ST_STATE_OPEN;
4279 	}
4280 
4281 
4282 	/*
4283 	 * Process rest of END OF FILE and END OF TAPE conditions
4284 	 */
4285 
4286 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4287 	    "eof=%x, wasopening=%x\n",
4288 	    un->un_pos.eof, wasopening);
4289 
4290 	switch (un->un_pos.eof) {
4291 	case ST_EOM:
4292 		/*
4293 		 * This allows writes to proceed past physical
4294 		 * eot. We'll *really* be in trouble if the
4295 		 * user continues blindly writing data too
4296 		 * much past this point (unwind the tape).
4297 		 * Physical eot really means 'early warning
4298 		 * eot' in this context.
4299 		 *
4300 		 * Every other write from now on will succeed
4301 		 * (if sufficient  tape left).
4302 		 * This write will return with resid == count
4303 		 * but the next one should be successful
4304 		 *
4305 		 * Note that we only transition to logical EOT
4306 		 * if the last state wasn't the OPENING state.
4307 		 * We explicitly prohibit running up to physical
4308 		 * eot, closing the device, and then re-opening
4309 		 * to proceed. Trailer records may only be gotten
4310 		 * at by keeping the tape open after hitting eot.
4311 		 *
4312 		 * Also note that ST_EOM cannot be set by reading-
4313 		 * this can only be set during writing. Reading
4314 		 * up to the end of the tape gets a blank check
4315 		 * or a double-filemark indication (ST_EOT_PENDING),
4316 		 * and we prohibit reading after that point.
4317 		 *
4318 		 */
4319 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
4320 		if (wasopening == 0) {
4321 			/*
4322 			 * this allows st_rw() to reset it back to
4323 			 * will see a zero write
4324 			 */
4325 			un->un_pos.eof = ST_WRITE_AFTER_EOM;
4326 		}
4327 		un->un_status = SUN_KEY_EOT;
4328 		goto b_done;
4329 
4330 	case ST_WRITE_AFTER_EOM:
4331 	case ST_EOT:
4332 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
4333 		un->un_status = SUN_KEY_EOT;
4334 		if (SVR4_BEHAVIOR && reading) {
4335 			goto b_done_err;
4336 		}
4337 
4338 		if (reading) {
4339 			goto b_done;
4340 		}
4341 		un->un_pos.eof = ST_NO_EOF;
4342 		break;
4343 
4344 	case ST_EOF_PENDING:
4345 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4346 		    "EOF PENDING\n");
4347 		un->un_status = SUN_KEY_EOF;
4348 		if (SVR4_BEHAVIOR) {
4349 			un->un_pos.eof = ST_EOF;
4350 			goto b_done;
4351 		}
4352 		/* FALLTHROUGH */
4353 	case ST_EOF:
4354 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
4355 		un->un_status = SUN_KEY_EOF;
4356 		if (SVR4_BEHAVIOR) {
4357 			goto b_done_err;
4358 		}
4359 
4360 		if (BSD_BEHAVIOR) {
4361 			un->un_pos.eof = ST_NO_EOF;
4362 			un->un_pos.fileno += 1;
4363 			un->un_pos.blkno   = 0;
4364 		}
4365 
4366 		if (reading) {
4367 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4368 			    "now file %d (read)\n",
4369 			    un->un_pos.fileno);
4370 			goto b_done;
4371 		}
4372 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4373 		    "now file %d (write)\n", un->un_pos.fileno);
4374 		break;
4375 	default:
4376 		un->un_status = 0;
4377 		break;
4378 	}
4379 
4380 	bp->b_flags &= ~(B_DONE);
4381 	st_bioerror(bp, 0);
4382 	bp->av_forw = NULL;
4383 	bp->b_resid = 0;
4384 	SET_BP_PKT(bp, 0);
4385 
4386 
4387 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4388 	    "st_queued_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4389 	    " pkt=0x%p\n",
4390 	    (void *)bp->b_forw, bp->b_bcount,
4391 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4392 
4393 #ifdef	__x86
4394 	/*
4395 	 * We will replace bp with a new bp that can do big blk xfer
4396 	 * if the requested xfer size is bigger than un->un_maxdma_arch
4397 	 *
4398 	 * Also, we need to make sure that we're handling real I/O
4399 	 * by checking group 0/1 SCSI I/O commands, if needed
4400 	 */
4401 	if (bp->b_bcount > un->un_maxdma_arch &&
4402 	    ((uchar_t)(uintptr_t)bp->b_forw == SCMD_READ ||
4403 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G4 ||
4404 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE ||
4405 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G4)) {
4406 		mutex_exit(ST_MUTEX);
4407 		bp = st_get_bigblk_bp(bp);
4408 		mutex_enter(ST_MUTEX);
4409 	}
4410 #endif
4411 
4412 	/* put on wait queue */
4413 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4414 	    "st_queued_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4415 	    (void *)un->un_quef, (void *)bp);
4416 
4417 	st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quel, bp);
4418 
4419 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4420 
4421 	st_start(un);
4422 
4423 	mutex_exit(ST_MUTEX);
4424 	return (0);
4425 
4426 b_done_err:
4427 	st_bioerror(bp, EIO);
4428 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4429 	    "st_queued_strategy : EIO b_done_err\n");
4430 
4431 b_done:
4432 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4433 	    "st_queued_strategy: b_done\n");
4434 
4435 exit:
4436 	/*
4437 	 * make sure no commands are outstanding or waiting before closing,
4438 	 * so we can guarantee order
4439 	 */
4440 	st_wait_for_io(un);
4441 	un->un_err_resid = bp->b_resid = bp->b_bcount;
4442 
4443 	/* override errno here, if persistent errors were flagged */
4444 	if (un->un_persistence && un->un_persist_errors)
4445 		bioerror(bp, un->un_errno);
4446 
4447 	mutex_exit(ST_MUTEX);
4448 
4449 	biodone(bp);
4450 	ASSERT(mutex_owned(ST_MUTEX) == 0);
4451 	return (0);
4452 }
4453 
4454 
4455 static int
4456 st_strategy(struct buf *bp)
4457 {
4458 	struct scsi_tape *un;
4459 
4460 	/*
4461 	 * validate arguments
4462 	 */
4463 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4464 	if (un == NULL) {
4465 		bp->b_resid = bp->b_bcount;
4466 		bioerror(bp, ENXIO);
4467 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4468 		    "st_strategy: ENXIO error exit\n");
4469 
4470 		biodone(bp);
4471 		return (0);
4472 
4473 	}
4474 
4475 	ST_ENTR(ST_DEVINFO, st_strategy);
4476 
4477 	mutex_enter(ST_MUTEX);
4478 
4479 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4480 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4481 	}
4482 
4483 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4484 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4485 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4486 
4487 	ASSERT((bp == un->un_recov_buf) || (bp == un->un_sbufp));
4488 
4489 	bp->b_flags &= ~(B_DONE);
4490 	st_bioerror(bp, 0);
4491 	bp->av_forw = NULL;
4492 	bp->b_resid = 0;
4493 	SET_BP_PKT(bp, 0);
4494 
4495 
4496 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4497 	    "st_strategy: cmd=0x%x  count=%ld  resid=%ld flags=0x%x"
4498 	    " pkt=0x%p\n",
4499 	    (unsigned char)(uintptr_t)bp->b_forw, bp->b_bcount,
4500 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4501 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4502 
4503 	st_start(un);
4504 
4505 	mutex_exit(ST_MUTEX);
4506 	return (0);
4507 }
4508 
4509 /*
4510  * this routine spaces forward over filemarks
4511  */
4512 static int
4513 st_space_fmks(struct scsi_tape *un, int64_t count)
4514 {
4515 	int rval = 0;
4516 
4517 	ST_FUNC(ST_DEVINFO, st_space_fmks);
4518 
4519 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4520 	    "st_space_fmks(dev = 0x%lx, count = %"PRIx64")\n",
4521 	    un->un_dev, count);
4522 
4523 	ASSERT(mutex_owned(ST_MUTEX));
4524 
4525 	/*
4526 	 * the risk with doing only one space operation is that we
4527 	 * may accidentily jump in old data
4528 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4529 	 * because the 8200 does not append a marker; in order not to
4530 	 * sacrifice the fast file skip, we do a slow skip if the low
4531 	 * density device has been opened
4532 	 */
4533 
4534 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4535 	    !((un->un_dp->type == ST_TYPE_EXB8500 &&
4536 	    MT_DENSITY(un->un_dev) == 0))) {
4537 		if (st_cmd(un, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4538 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4539 			    "space_fmks : EIO can't do space cmd #1\n");
4540 			rval = EIO;
4541 		}
4542 	} else {
4543 		while (count > 0) {
4544 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4545 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4546 				    "space_fmks : EIO can't do space cmd #2\n");
4547 				rval = EIO;
4548 				break;
4549 			}
4550 			count -= 1;
4551 			/*
4552 			 * read a block to see if we have reached
4553 			 * end of medium (double filemark for reel or
4554 			 * medium error for others)
4555 			 */
4556 			if (count > 0) {
4557 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
4558 					ST_DEBUG2(ST_DEVINFO, st_label,
4559 					    SCSI_DEBUG,
4560 					    "space_fmks : EIO can't do "
4561 					    "space cmd #3\n");
4562 					rval = EIO;
4563 					break;
4564 				}
4565 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4566 				    (un->un_dp->options & ST_REEL)) {
4567 					un->un_status = SUN_KEY_EOT;
4568 					ST_DEBUG2(ST_DEVINFO, st_label,
4569 					    SCSI_DEBUG,
4570 					    "space_fmks : EIO ST_REEL\n");
4571 					rval = EIO;
4572 					break;
4573 				} else if (IN_EOF(un->un_pos)) {
4574 					un->un_pos.eof = ST_NO_EOF;
4575 					un->un_pos.fileno++;
4576 					un->un_pos.blkno = 0;
4577 					count--;
4578 				} else if (un->un_pos.eof > ST_EOF) {
4579 					ST_DEBUG2(ST_DEVINFO, st_label,
4580 					    SCSI_DEBUG,
4581 					    "space_fmks, EIO > ST_EOF\n");
4582 					rval = EIO;
4583 					break;
4584 				}
4585 
4586 			}
4587 		}
4588 		un->un_err_resid = count;
4589 		COPY_POS(&un->un_pos, &un->un_err_pos);
4590 	}
4591 	ASSERT(mutex_owned(ST_MUTEX));
4592 	return (rval);
4593 }
4594 
4595 /*
4596  * this routine spaces to EOD
4597  *
4598  * it keeps track of the current filenumber and returns the filenumber after
4599  * the last successful space operation, we keep the number high because as
4600  * tapes are getting larger, the possibility of more and more files exist,
4601  * 0x100000 (1 Meg of files) probably will never have to be changed any time
4602  * soon
4603  */
4604 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4605 
4606 static int
4607 st_find_eod(struct scsi_tape *un)
4608 {
4609 	tapepos_t savepos;
4610 	int64_t sp_type;
4611 	int result;
4612 
4613 	if (un == NULL) {
4614 		return (-1);
4615 	}
4616 
4617 	ST_FUNC(ST_DEVINFO, st_find_eod);
4618 
4619 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4620 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", un->un_dev,
4621 	    un->un_pos.fileno);
4622 
4623 	ASSERT(mutex_owned(ST_MUTEX));
4624 
4625 	COPY_POS(&savepos, &un->un_pos);
4626 
4627 	/*
4628 	 * see if the drive is smart enough to do the skips in
4629 	 * one operation; 1/2" use two filemarks
4630 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4631 	 * because the 8200 does not append a marker; in order not to
4632 	 * sacrifice the fast file skip, we do a slow skip if the low
4633 	 * density device has been opened
4634 	 */
4635 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4636 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4637 		    (MT_DENSITY(un->un_dev) == 0)) {
4638 			sp_type = Fmk(1);
4639 		} else if (un->un_pos.pmode == logical) {
4640 			sp_type = SPACE(SP_EOD, 0);
4641 		} else {
4642 			sp_type = Fmk(MAX_SKIP);
4643 		}
4644 	} else {
4645 		sp_type = Fmk(1);
4646 	}
4647 
4648 	for (;;) {
4649 		result = st_cmd(un, SCMD_SPACE, sp_type, SYNC_CMD);
4650 
4651 		if (result == 0) {
4652 			COPY_POS(&savepos, &un->un_pos);
4653 		}
4654 
4655 		if (sp_type == SPACE(SP_EOD, 0)) {
4656 			if (result != 0) {
4657 				sp_type = Fmk(MAX_SKIP);
4658 				continue;
4659 			}
4660 
4661 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4662 			    "st_find_eod: 0x%"PRIx64"\n",
4663 			    savepos.lgclblkno);
4664 			/*
4665 			 * What we return will become the current file position.
4666 			 * After completing the space command with the position
4667 			 * mode that is not invalid a read position command will
4668 			 * be automaticly issued. If the drive support the long
4669 			 * read position format a valid file position can be
4670 			 * returned.
4671 			 */
4672 			return (un->un_pos.fileno);
4673 		}
4674 
4675 		if (result != 0) {
4676 			break;
4677 		}
4678 
4679 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4680 		    "count=%"PRIx64", eof=%x, status=%x\n",
4681 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4682 
4683 		/*
4684 		 * If we're not EOM smart,  space a record
4685 		 * to see whether we're now in the slot between
4686 		 * the two sequential filemarks that logical
4687 		 * EOM consists of (REEL) or hit nowhere land
4688 		 * (8mm).
4689 		 */
4690 		if (sp_type == Fmk(1)) {
4691 			/*
4692 			 * no fast skipping, check a record
4693 			 */
4694 			if (st_cmd(un, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4695 				break;
4696 			}
4697 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4698 			    (un->un_dp->options & ST_REEL)) {
4699 				un->un_status = KEY_BLANK_CHECK;
4700 				un->un_pos.fileno++;
4701 				un->un_pos.blkno = 0;
4702 				break;
4703 			}
4704 			if (IN_EOF(un->un_pos)) {
4705 				un->un_pos.eof = ST_NO_EOF;
4706 				un->un_pos.fileno++;
4707 				un->un_pos.blkno = 0;
4708 			}
4709 			if (un->un_pos.eof > ST_EOF) {
4710 				break;
4711 			}
4712 		} else {
4713 			if (un->un_pos.eof > ST_EOF) {
4714 				break;
4715 			}
4716 		}
4717 	}
4718 
4719 	if (un->un_dp->options & ST_KNOWS_EOD) {
4720 		COPY_POS(&savepos, &un->un_pos);
4721 	}
4722 
4723 	ASSERT(mutex_owned(ST_MUTEX));
4724 
4725 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4726 	    "st_find_eod: %x\n", savepos.fileno);
4727 	return (savepos.fileno);
4728 }
4729 
4730 
4731 /*
4732  * this routine is frequently used in ioctls below;
4733  * it determines whether we know the density and if not will
4734  * determine it
4735  * if we have written the tape before, one or more filemarks are written
4736  *
4737  * depending on the stepflag, the head is repositioned to where it was before
4738  * the filemarks were written in order not to confuse step counts
4739  */
4740 #define	STEPBACK    0
4741 #define	NO_STEPBACK 1
4742 
4743 static int
4744 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4745 {
4746 
4747 	GET_SOFT_STATE(dev);
4748 
4749 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4750 
4751 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4752 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4753 	    "\n", dev, wfm, mode, stepflag);
4754 
4755 	ASSERT(mutex_owned(ST_MUTEX));
4756 
4757 	/*
4758 	 * If we don't yet know the density of the tape we have inserted,
4759 	 * we have to either unconditionally set it (if we're 'writing'),
4760 	 * or we have to determine it. As side effects, check for any
4761 	 * write-protect errors, and for the need to put out any file-marks
4762 	 * before positioning a tape.
4763 	 *
4764 	 * If we are going to be spacing forward, and we haven't determined
4765 	 * the tape density yet, we have to do so now...
4766 	 */
4767 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4768 		if (st_determine_density(un, mode)) {
4769 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4770 			    "check_density_or_wfm : EIO can't determine "
4771 			    "density\n");
4772 			un->un_errno = EIO;
4773 			return (EIO);
4774 		}
4775 		/*
4776 		 * Presumably we are at BOT. If we attempt to write, it will
4777 		 * either work okay, or bomb. We don't do a st_test_append
4778 		 * unless we're past BOT.
4779 		 */
4780 		un->un_laststate = un->un_state;
4781 		un->un_state = ST_STATE_OPEN;
4782 
4783 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4784 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4785 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4786 
4787 		tapepos_t spos;
4788 
4789 		COPY_POS(&spos, &un->un_pos);
4790 
4791 		/*
4792 		 * We need to write one or two filemarks.
4793 		 * In the case of the HP, we need to
4794 		 * position the head between the two
4795 		 * marks.
4796 		 */
4797 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4798 			wfm = un->un_fmneeded;
4799 			un->un_fmneeded = 0;
4800 		}
4801 
4802 		if (st_write_fm(dev, wfm)) {
4803 			un->un_pos.pmode = invalid;
4804 			un->un_density_known = 0;
4805 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4806 			    "check_density_or_wfm : EIO can't write fm\n");
4807 			un->un_errno = EIO;
4808 			return (EIO);
4809 		}
4810 
4811 		if (stepflag == STEPBACK) {
4812 			if (st_cmd(un, SCMD_SPACE, Fmk(-wfm), SYNC_CMD)) {
4813 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4814 				    "check_density_or_wfm : EIO can't space "
4815 				    "(-wfm)\n");
4816 				un->un_errno = EIO;
4817 				return (EIO);
4818 			}
4819 			COPY_POS(&un->un_pos, &spos);
4820 		}
4821 	}
4822 
4823 	/*
4824 	 * Whatever we do at this point clears the state of the eof flag.
4825 	 */
4826 
4827 	un->un_pos.eof = ST_NO_EOF;
4828 
4829 	/*
4830 	 * If writing, let's check that we're positioned correctly
4831 	 * at the end of tape before issuing the next write.
4832 	 */
4833 	if (un->un_read_only == RDWR) {
4834 		un->un_test_append = 1;
4835 	}
4836 
4837 	ASSERT(mutex_owned(ST_MUTEX));
4838 	return (0);
4839 }
4840 
4841 
4842 /*
4843  * Wait for all outstaning I/O's to complete
4844  *
4845  * we wait on both ncmds and the wait queue for times when we are flushing
4846  * after persistent errors are flagged, which is when ncmds can be 0, and the
4847  * queue can still have I/O's.  This way we preserve order of biodone's.
4848  */
4849 static void
4850 st_wait_for_io(struct scsi_tape *un)
4851 {
4852 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4853 	ASSERT(mutex_owned(ST_MUTEX));
4854 	while ((un->un_ncmds) || (un->un_quef) || (un->un_runqf)) {
4855 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4856 	}
4857 }
4858 
4859 /*
4860  * This routine implements the ioctl calls.  It is called
4861  * from the device switch at normal priority.
4862  */
4863 /*ARGSUSED*/
4864 static int
4865 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4866     int *rval_p)
4867 {
4868 	int tmp, rval = 0;
4869 
4870 	GET_SOFT_STATE(dev);
4871 
4872 	ST_ENTR(ST_DEVINFO, st_ioctl);
4873 
4874 	mutex_enter(ST_MUTEX);
4875 
4876 	ASSERT(un->un_recov_buf_busy == 0);
4877 
4878 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4879 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4880 	    "pe_flag = %d\n",
4881 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4882 	    un->un_persistence && un->un_persist_errors);
4883 
4884 	/*
4885 	 * We don't want to block on these, so let them through
4886 	 * and we don't care about setting driver states here.
4887 	 */
4888 	if ((cmd == MTIOCGETDRIVETYPE) ||
4889 	    (cmd == MTIOCGUARANTEEDORDER) ||
4890 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4891 		goto check_commands;
4892 	}
4893 
4894 	/*
4895 	 * We clear error entry stack except command
4896 	 * MTIOCGETERROR and MTIOCGET
4897 	 */
4898 	if ((cmd != MTIOCGETERROR) &&
4899 	    (cmd != MTIOCGET)) {
4900 		st_empty_error_stack(un);
4901 	}
4902 
4903 	/*
4904 	 * wait for all outstanding commands to complete, or be dequeued.
4905 	 * And because ioctl's are synchronous commands, any return value
4906 	 * after this,  will be in order
4907 	 */
4908 	st_wait_for_io(un);
4909 
4910 	/*
4911 	 * allow only a through clear errors and persistent status, and
4912 	 * status
4913 	 */
4914 	if (un->un_persistence && un->un_persist_errors) {
4915 		if ((cmd == MTIOCLRERR) ||
4916 		    (cmd == MTIOCPERSISTENT) ||
4917 		    (cmd == MTIOCGET)) {
4918 			goto check_commands;
4919 		} else {
4920 			rval = un->un_errno;
4921 			goto exit;
4922 		}
4923 	}
4924 
4925 	ASSERT(un->un_throttle != 0);
4926 	un->un_throttle = 1;	/* > 1 will never happen here */
4927 	un->un_errno = 0;	/* start clean from here */
4928 
4929 	/*
4930 	 * first and foremost, handle any ST_EOT_PENDING cases.
4931 	 * That is, if a logical eot is pending notice, notice it.
4932 	 */
4933 	if (un->un_pos.eof == ST_EOT_PENDING) {
4934 		int resid = un->un_err_resid;
4935 		uchar_t status = un->un_status;
4936 		uchar_t lastop = un->un_lastop;
4937 
4938 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4939 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4940 			    "stioctl : EIO can't space fmk(-1)\n");
4941 			rval = EIO;
4942 			goto exit;
4943 		}
4944 		un->un_lastop = lastop; /* restore last operation */
4945 		if (status == SUN_KEY_EOF) {
4946 			un->un_status = SUN_KEY_EOT;
4947 		} else {
4948 			un->un_status = status;
4949 		}
4950 		un->un_err_resid  = resid;
4951 		/* fix up block number */
4952 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4953 		/* now we're at logical eot */
4954 		un->un_pos.eof = ST_EOT;
4955 	}
4956 
4957 	/*
4958 	 * now, handle the rest of the situations
4959 	 */
4960 check_commands:
4961 	switch (cmd) {
4962 	case MTIOCGET:
4963 	{
4964 #ifdef _MULTI_DATAMODEL
4965 		/*
4966 		 * For use when a 32 bit app makes a call into a
4967 		 * 64 bit ioctl
4968 		 */
4969 		struct mtget32		mtg_local32;
4970 		struct mtget32 		*mtget_32 = &mtg_local32;
4971 #endif /* _MULTI_DATAMODEL */
4972 
4973 			/* Get tape status */
4974 		struct mtget mtg_local;
4975 		struct mtget *mtget = &mtg_local;
4976 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4977 		    "st_ioctl: MTIOCGET\n");
4978 
4979 		bzero((caddr_t)mtget, sizeof (struct mtget));
4980 		mtget->mt_erreg = un->un_status;
4981 		mtget->mt_resid = un->un_err_resid;
4982 		mtget->mt_dsreg = un->un_retry_ct;
4983 		if (un->un_err_pos.pmode == legacy) {
4984 			mtget->mt_fileno = un->un_err_pos.fileno;
4985 		} else {
4986 			mtget->mt_fileno = -1;
4987 		}
4988 		/*
4989 		 * If the value is positive fine.
4990 		 * If its negative we need to return a value based on the
4991 		 * old way if counting backwards from INF (1,000,000,000).
4992 		 */
4993 		if (un->un_err_pos.blkno >= 0) {
4994 			mtget->mt_blkno = un->un_err_pos.blkno;
4995 		} else {
4996 			mtget->mt_blkno = INF + 1 - (-un->un_err_pos.blkno);
4997 		}
4998 		mtget->mt_type = un->un_dp->type;
4999 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
5000 		if (un->un_read_pos_type != NO_POS) {
5001 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
5002 		}
5003 		if (un->un_dp->options & ST_REEL) {
5004 			mtget->mt_flags |= MTF_REEL;
5005 			mtget->mt_bf = 20;
5006 		} else {		/* 1/4" cartridges */
5007 			switch (mtget->mt_type) {
5008 			/* Emulex cartridge tape */
5009 			case MT_ISMT02:
5010 				mtget->mt_bf = 40;
5011 				break;
5012 			default:
5013 				mtget->mt_bf = 126;
5014 				break;
5015 			}
5016 		}
5017 
5018 		/*
5019 		 * If large transfers are allowed and drive options
5020 		 * has no record size limit set. Calculate blocking
5021 		 * factor from the lesser of maxbsize and maxdma.
5022 		 */
5023 		if ((un->un_allow_large_xfer) &&
5024 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
5025 			mtget->mt_bf = min(un->un_maxbsize,
5026 			    un->un_maxdma) / SECSIZE;
5027 		}
5028 
5029 		if (un->un_read_only == WORM ||
5030 		    un->un_read_only == RDWORM) {
5031 			mtget->mt_flags |= MTF_WORM_MEDIA;
5032 		}
5033 
5034 		/*
5035 		 * In persistent error mode sending a non-queued can hang
5036 		 * because this ioctl gets to be run without turning off
5037 		 * persistense. Fake the answer based on previous info.
5038 		 */
5039 		if (un->un_persistence) {
5040 			rval = 0;
5041 		} else {
5042 			rval = st_check_clean_bit(un);
5043 		}
5044 		if (rval == 0) {
5045 			/*
5046 			 * If zero is returned or in persistent mode,
5047 			 * use the old data.
5048 			 */
5049 			if ((un->un_HeadClean & (TAPE_ALERT_SUPPORTED |
5050 			    TAPE_SEQUENTIAL_SUPPORTED|TAPE_ALERT_NOT_SUPPORTED))
5051 			    != TAPE_ALERT_NOT_SUPPORTED) {
5052 				mtget->mt_flags |= MTF_TAPE_CLN_SUPPORTED;
5053 			}
5054 			if (un->un_HeadClean & (TAPE_PREVIOUSLY_DIRTY |
5055 			    TAPE_ALERT_STILL_DIRTY)) {
5056 				mtget->mt_flags |= MTF_TAPE_HEAD_DIRTY;
5057 			}
5058 		} else {
5059 			mtget->mt_flags |= (ushort_t)rval;
5060 			rval = 0;
5061 		}
5062 
5063 		un->un_status = 0;		/* Reset status */
5064 		un->un_err_resid = 0;
5065 		tmp = sizeof (struct mtget);
5066 
5067 #ifdef _MULTI_DATAMODEL
5068 
5069 		switch (ddi_model_convert_from(flag & FMODELS)) {
5070 		case DDI_MODEL_ILP32:
5071 			/*
5072 			 * Convert 64 bit back to 32 bit before doing
5073 			 * copyout. This is what the ILP32 app expects.
5074 			 */
5075 			mtget_32->mt_erreg = 	mtget->mt_erreg;
5076 			mtget_32->mt_resid = 	mtget->mt_resid;
5077 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
5078 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
5079 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
5080 			mtget_32->mt_type =  	mtget->mt_type;
5081 			mtget_32->mt_flags = 	mtget->mt_flags;
5082 			mtget_32->mt_bf = 	mtget->mt_bf;
5083 
5084 			if (ddi_copyout(mtget_32, (void *)arg,
5085 			    sizeof (struct mtget32), flag)) {
5086 				rval = EFAULT;
5087 			}
5088 			break;
5089 
5090 		case DDI_MODEL_NONE:
5091 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5092 				rval = EFAULT;
5093 			}
5094 			break;
5095 		}
5096 #else /* ! _MULTI_DATAMODE */
5097 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5098 			rval = EFAULT;
5099 		}
5100 #endif /* _MULTI_DATAMODE */
5101 
5102 		break;
5103 	}
5104 	case MTIOCGETERROR:
5105 			/*
5106 			 * get error entry from error stack
5107 			 */
5108 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5109 			    "st_ioctl: MTIOCGETERROR\n");
5110 
5111 			rval = st_get_error_entry(un, arg, flag);
5112 
5113 			break;
5114 
5115 	case MTIOCSTATE:
5116 		{
5117 			/*
5118 			 * return when media presence matches state
5119 			 */
5120 			enum mtio_state state;
5121 
5122 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5123 			    "st_ioctl: MTIOCSTATE\n");
5124 
5125 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
5126 				rval = EFAULT;
5127 
5128 			mutex_exit(ST_MUTEX);
5129 
5130 			rval = st_check_media(dev, state);
5131 
5132 			mutex_enter(ST_MUTEX);
5133 
5134 			if (rval != 0) {
5135 				break;
5136 			}
5137 
5138 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
5139 			    sizeof (int), flag))
5140 				rval = EFAULT;
5141 			break;
5142 
5143 		}
5144 
5145 	case MTIOCGETDRIVETYPE:
5146 		{
5147 #ifdef _MULTI_DATAMODEL
5148 		/*
5149 		 * For use when a 32 bit app makes a call into a
5150 		 * 64 bit ioctl
5151 		 */
5152 		struct mtdrivetype_request32	mtdtrq32;
5153 #endif /* _MULTI_DATAMODEL */
5154 
5155 			/*
5156 			 * return mtdrivetype
5157 			 */
5158 			struct mtdrivetype_request mtdtrq;
5159 			struct mtdrivetype mtdrtyp;
5160 			struct mtdrivetype *mtdt = &mtdrtyp;
5161 			struct st_drivetype *stdt = un->un_dp;
5162 
5163 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5164 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
5165 
5166 #ifdef _MULTI_DATAMODEL
5167 		switch (ddi_model_convert_from(flag & FMODELS)) {
5168 		case DDI_MODEL_ILP32:
5169 		{
5170 			if (ddi_copyin((void *)arg, &mtdtrq32,
5171 			    sizeof (struct mtdrivetype_request32), flag)) {
5172 				rval = EFAULT;
5173 				break;
5174 			}
5175 			mtdtrq.size = mtdtrq32.size;
5176 			mtdtrq.mtdtp =
5177 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
5178 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5179 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
5180 			break;
5181 		}
5182 		case DDI_MODEL_NONE:
5183 			if (ddi_copyin((void *)arg, &mtdtrq,
5184 			    sizeof (struct mtdrivetype_request), flag)) {
5185 				rval = EFAULT;
5186 				break;
5187 			}
5188 			break;
5189 		}
5190 
5191 #else /* ! _MULTI_DATAMODEL */
5192 		if (ddi_copyin((void *)arg, &mtdtrq,
5193 		    sizeof (struct mtdrivetype_request), flag)) {
5194 			rval = EFAULT;
5195 			break;
5196 		}
5197 #endif /* _MULTI_DATAMODEL */
5198 
5199 			/*
5200 			 * if requested size is < 0 then return
5201 			 * error.
5202 			 */
5203 			if (mtdtrq.size < 0) {
5204 				rval = EINVAL;
5205 				break;
5206 			}
5207 			bzero(mtdt, sizeof (struct mtdrivetype));
5208 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
5209 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
5210 			mtdt->type = stdt->type;
5211 			mtdt->bsize = stdt->bsize;
5212 			mtdt->options = stdt->options;
5213 			mtdt->max_rretries = stdt->max_rretries;
5214 			mtdt->max_wretries = stdt->max_wretries;
5215 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5216 				mtdt->densities[tmp] = stdt->densities[tmp];
5217 			}
5218 			mtdt->default_density = stdt->default_density;
5219 			/*
5220 			 * Speed hasn't been used since the hayday of reel tape.
5221 			 * For all drives not setting the option ST_KNOWS_MEDIA
5222 			 * the speed member renamed to mediatype are zeros.
5223 			 * Those drives that have ST_KNOWS_MEDIA set use the
5224 			 * new mediatype member which is used to figure the
5225 			 * type of media loaded.
5226 			 *
5227 			 * So as to not break applications speed in the
5228 			 * mtdrivetype structure is not renamed.
5229 			 */
5230 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5231 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
5232 			}
5233 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
5234 			mtdt->io_timeout = stdt->io_timeout;
5235 			mtdt->rewind_timeout = stdt->rewind_timeout;
5236 			mtdt->space_timeout = stdt->space_timeout;
5237 			mtdt->load_timeout = stdt->load_timeout;
5238 			mtdt->unload_timeout = stdt->unload_timeout;
5239 			mtdt->erase_timeout = stdt->erase_timeout;
5240 
5241 			/*
5242 			 * Limit the maximum length of the result to
5243 			 * sizeof (struct mtdrivetype).
5244 			 */
5245 			tmp = sizeof (struct mtdrivetype);
5246 			if (mtdtrq.size < tmp)
5247 				tmp = mtdtrq.size;
5248 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
5249 				rval = EFAULT;
5250 			}
5251 			break;
5252 		}
5253 	case MTIOCPERSISTENT:
5254 
5255 		if (ddi_copyin((void *)arg, &tmp, sizeof (tmp), flag)) {
5256 			rval = EFAULT;
5257 			break;
5258 		}
5259 
5260 		if (tmp) {
5261 			st_turn_pe_on(un);
5262 		} else {
5263 			st_turn_pe_off(un);
5264 		}
5265 
5266 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5267 		    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
5268 		    un->un_persistence);
5269 
5270 		break;
5271 
5272 	case MTIOCPERSISTENTSTATUS:
5273 		tmp = (int)un->un_persistence;
5274 
5275 		if (ddi_copyout(&tmp, (void *)arg, sizeof (tmp), flag)) {
5276 			rval = EFAULT;
5277 		}
5278 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5279 		    "st_ioctl: MTIOCPERSISTENTSTATUS:persistence = %d\n",
5280 		    un->un_persistence);
5281 
5282 		break;
5283 
5284 	case MTIOCLRERR:
5285 		{
5286 			/* clear persistent errors */
5287 
5288 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5289 			    "st_ioctl: MTIOCLRERR\n");
5290 
5291 			st_clear_pe(un);
5292 
5293 			break;
5294 		}
5295 
5296 	case MTIOCGUARANTEEDORDER:
5297 		{
5298 			/*
5299 			 * this is just a holder to make a valid ioctl and
5300 			 * it won't be in any earlier release
5301 			 */
5302 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5303 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
5304 
5305 			break;
5306 		}
5307 
5308 	case MTIOCRESERVE:
5309 		{
5310 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5311 			    "st_ioctl: MTIOCRESERVE\n");
5312 
5313 			/*
5314 			 * Check if Reserve/Release is supported.
5315 			 */
5316 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5317 				rval = ENOTTY;
5318 				break;
5319 			}
5320 
5321 			rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5322 
5323 			if (rval == 0) {
5324 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
5325 			}
5326 			break;
5327 		}
5328 
5329 	case MTIOCRELEASE:
5330 		{
5331 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5332 			    "st_ioctl: MTIOCRELEASE\n");
5333 
5334 			/*
5335 			 * Check if Reserve/Release is supported.
5336 			 */
5337 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5338 				rval = ENOTTY;
5339 				break;
5340 			}
5341 
5342 			/*
5343 			 * Used to just clear ST_PRESERVE_RESERVE which
5344 			 * made the reservation release at next close.
5345 			 * As the user may have opened and then done a
5346 			 * persistant reservation we now need to drop
5347 			 * the reservation without closing if the user
5348 			 * attempts to do this.
5349 			 */
5350 			rval = st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
5351 
5352 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5353 
5354 			break;
5355 		}
5356 
5357 	case MTIOCFORCERESERVE:
5358 	{
5359 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5360 		    "st_ioctl: MTIOCFORCERESERVE\n");
5361 
5362 		/*
5363 		 * Check if Reserve/Release is supported.
5364 		 */
5365 		if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5366 			rval = ENOTTY;
5367 			break;
5368 		}
5369 		/*
5370 		 * allow only super user to run this.
5371 		 */
5372 		if (drv_priv(cred_p) != 0) {
5373 			rval = EPERM;
5374 			break;
5375 		}
5376 		/*
5377 		 * Throw away reserve,
5378 		 * not using test-unit-ready
5379 		 * since reserve can succeed without tape being
5380 		 * present in the drive.
5381 		 */
5382 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5383 
5384 		rval = st_take_ownership(un, st_uscsi_cmd);
5385 
5386 		break;
5387 	}
5388 
5389 	case USCSICMD:
5390 	{
5391 		cred_t	*cr;
5392 
5393 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5394 		    "st_ioctl: USCSICMD\n");
5395 
5396 		cr = ddi_get_cred();
5397 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5398 			rval = EPERM;
5399 		} else {
5400 			rval = st_uscsi_cmd(un, (struct uscsi_cmd *)arg, flag);
5401 		}
5402 		break;
5403 	}
5404 	case MTIOCTOP:
5405 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5406 		    "st_ioctl: MTIOCTOP\n");
5407 		rval = st_mtioctop(un, arg, flag);
5408 		break;
5409 
5410 	case MTIOCLTOP:
5411 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5412 		    "st_ioctl: MTIOLCTOP\n");
5413 		rval = st_mtiocltop(un, arg, flag);
5414 		break;
5415 
5416 	case MTIOCREADIGNOREILI:
5417 		{
5418 			int set_ili;
5419 
5420 			if (ddi_copyin((void *)arg, &set_ili,
5421 			    sizeof (set_ili), flag)) {
5422 				rval = EFAULT;
5423 				break;
5424 			}
5425 
5426 			if (un->un_bsize) {
5427 				rval = ENOTTY;
5428 				break;
5429 			}
5430 
5431 			switch (set_ili) {
5432 			case 0:
5433 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5434 				break;
5435 
5436 			case 1:
5437 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5438 				break;
5439 
5440 			default:
5441 				rval = EINVAL;
5442 				break;
5443 			}
5444 			break;
5445 		}
5446 
5447 	case MTIOCREADIGNOREEOFS:
5448 		{
5449 			int ignore_eof;
5450 
5451 			if (ddi_copyin((void *)arg, &ignore_eof,
5452 			    sizeof (ignore_eof), flag)) {
5453 				rval = EFAULT;
5454 				break;
5455 			}
5456 
5457 			if (!(un->un_dp->options & ST_REEL)) {
5458 				rval = ENOTTY;
5459 				break;
5460 			}
5461 
5462 			switch (ignore_eof) {
5463 			case 0:
5464 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5465 				break;
5466 
5467 			case 1:
5468 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5469 				break;
5470 
5471 			default:
5472 				rval = EINVAL;
5473 				break;
5474 			}
5475 			break;
5476 		}
5477 
5478 	case MTIOCSHORTFMK:
5479 	{
5480 		int short_fmk;
5481 
5482 		if (ddi_copyin((void *)arg, &short_fmk,
5483 		    sizeof (short_fmk), flag)) {
5484 			rval = EFAULT;
5485 			break;
5486 		}
5487 
5488 		switch (un->un_dp->type) {
5489 		case ST_TYPE_EXB8500:
5490 		case ST_TYPE_EXABYTE:
5491 			if (!short_fmk) {
5492 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5493 			} else if (short_fmk == 1) {
5494 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5495 			} else {
5496 				rval = EINVAL;
5497 			}
5498 			break;
5499 
5500 		default:
5501 			rval = ENOTTY;
5502 			break;
5503 		}
5504 		break;
5505 	}
5506 
5507 	case MTIOCGETPOS:
5508 		rval = st_update_block_pos(un, st_cmd, 0);
5509 		if (rval == 0) {
5510 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5511 			    sizeof (tapepos_t), flag)) {
5512 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5513 				    "MTIOCGETPOS copy out failed\n");
5514 				rval = EFAULT;
5515 			}
5516 		}
5517 		break;
5518 
5519 	case MTIOCRESTPOS:
5520 	{
5521 		tapepos_t dest;
5522 
5523 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5524 		    flag) != 0) {
5525 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5526 			    "MTIOCRESTPOS copy in failed\n");
5527 			rval = EFAULT;
5528 			break;
5529 		}
5530 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &dest);
5531 		if (rval != 0) {
5532 			rval = EIO;
5533 		}
5534 		break;
5535 	}
5536 	default:
5537 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5538 		    "st_ioctl: unknown ioctl\n");
5539 		rval = ENOTTY;
5540 	}
5541 
5542 exit:
5543 	if (!(un->un_persistence && un->un_persist_errors)) {
5544 		un->un_errno = rval;
5545 	}
5546 
5547 	mutex_exit(ST_MUTEX);
5548 
5549 	return (rval);
5550 }
5551 
5552 
5553 /*
5554  * do some MTIOCTOP tape operations
5555  */
5556 static int
5557 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5558 {
5559 #ifdef _MULTI_DATAMODEL
5560 	/*
5561 	 * For use when a 32 bit app makes a call into a
5562 	 * 64 bit ioctl
5563 	 */
5564 	struct mtop32	mtop_32_for_64;
5565 #endif /* _MULTI_DATAMODEL */
5566 	struct mtop passed;
5567 	struct mtlop local;
5568 	int rval = 0;
5569 
5570 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5571 
5572 	ASSERT(mutex_owned(ST_MUTEX));
5573 
5574 #ifdef _MULTI_DATAMODEL
5575 	switch (ddi_model_convert_from(flag & FMODELS)) {
5576 	case DDI_MODEL_ILP32:
5577 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5578 		    sizeof (struct mtop32), flag)) {
5579 			return (EFAULT);
5580 		}
5581 		local.mt_op = mtop_32_for_64.mt_op;
5582 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5583 		break;
5584 
5585 	case DDI_MODEL_NONE:
5586 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5587 			return (EFAULT);
5588 		}
5589 		local.mt_op = passed.mt_op;
5590 		/* prevent sign extention */
5591 		local.mt_count = (UINT32_MAX & passed.mt_count);
5592 		break;
5593 	}
5594 
5595 #else /* ! _MULTI_DATAMODEL */
5596 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5597 		return (EFAULT);
5598 	}
5599 	local.mt_op = passed.mt_op;
5600 	/* prevent sign extention */
5601 	local.mt_count = (UINT32_MAX & passed.mt_count);
5602 #endif /* _MULTI_DATAMODEL */
5603 
5604 	rval = st_do_mtioctop(un, &local);
5605 
5606 #ifdef _MULTI_DATAMODEL
5607 	switch (ddi_model_convert_from(flag & FMODELS)) {
5608 	case DDI_MODEL_ILP32:
5609 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5610 			rval = ERANGE;
5611 			break;
5612 		}
5613 		/*
5614 		 * Convert 64 bit back to 32 bit before doing
5615 		 * copyout. This is what the ILP32 app expects.
5616 		 */
5617 		mtop_32_for_64.mt_op = local.mt_op;
5618 		mtop_32_for_64.mt_count = local.mt_count;
5619 
5620 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5621 		    sizeof (struct mtop32), flag)) {
5622 			rval = EFAULT;
5623 		}
5624 		break;
5625 
5626 	case DDI_MODEL_NONE:
5627 		passed.mt_count = local.mt_count;
5628 		passed.mt_op = local.mt_op;
5629 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5630 			rval = EFAULT;
5631 		}
5632 		break;
5633 	}
5634 #else /* ! _MULTI_DATAMODE */
5635 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5636 		rval = ERANGE;
5637 	} else {
5638 		passed.mt_op = local.mt_op;
5639 		passed.mt_count = local.mt_count;
5640 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5641 			rval = EFAULT;
5642 		}
5643 	}
5644 #endif /* _MULTI_DATAMODE */
5645 
5646 
5647 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5648 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5649 	    un->un_pos.blkno, un->un_pos.eof);
5650 
5651 	if (un->un_pos.pmode == invalid) {
5652 		un->un_density_known = 0;
5653 	}
5654 
5655 	ASSERT(mutex_owned(ST_MUTEX));
5656 	return (rval);
5657 }
5658 
5659 static int
5660 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5661 {
5662 	struct mtlop local;
5663 	int rval;
5664 
5665 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5666 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5667 		return (EFAULT);
5668 	}
5669 
5670 	rval = st_do_mtioctop(un, &local);
5671 
5672 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5673 		rval = EFAULT;
5674 	}
5675 	return (rval);
5676 }
5677 
5678 
5679 static int
5680 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5681 {
5682 	dev_t dev = un->un_dev;
5683 	int savefile;
5684 	int rval = 0;
5685 
5686 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5687 
5688 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5689 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5690 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5691 	    "fileno=%x, blkno=%x, eof=%x\n",
5692 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5693 
5694 	un->un_status = 0;
5695 
5696 	/*
5697 	 * if we are going to mess with a tape, we have to make sure we have
5698 	 * one and are not offline (i.e. no tape is initialized).  We let
5699 	 * commands pass here that don't actually touch the tape, except for
5700 	 * loading and initialization (rewinding).
5701 	 */
5702 	if (un->un_state == ST_STATE_OFFLINE) {
5703 		switch (mtop->mt_op) {
5704 		case MTLOAD:
5705 		case MTNOP:
5706 			/*
5707 			 * We don't want strategy calling st_tape_init here,
5708 			 * so, change state
5709 			 */
5710 			un->un_state = ST_STATE_INITIALIZING;
5711 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5712 			    "st_do_mtioctop : OFFLINE state = %d\n",
5713 			    un->un_state);
5714 			break;
5715 		default:
5716 			/*
5717 			 * reinitialize by normal means
5718 			 */
5719 			rval = st_tape_init(un);
5720 			if (rval) {
5721 				un->un_state = ST_STATE_INITIALIZING;
5722 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5723 				    "st_do_mtioctop : OFFLINE init failure ");
5724 				un->un_state = ST_STATE_OFFLINE;
5725 				un->un_pos.pmode = invalid;
5726 				if (rval != EACCES) {
5727 					rval = EIO;
5728 				}
5729 				return (rval);
5730 			}
5731 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5732 			break;
5733 		}
5734 	}
5735 
5736 	/*
5737 	 * If the file position is invalid, allow only those
5738 	 * commands that properly position the tape and fail
5739 	 * the rest with EIO
5740 	 */
5741 	if (un->un_pos.pmode == invalid) {
5742 		switch (mtop->mt_op) {
5743 		case MTWEOF:
5744 		case MTRETEN:
5745 		case MTERASE:
5746 		case MTEOM:
5747 		case MTFSF:
5748 		case MTFSR:
5749 		case MTBSF:
5750 		case MTNBSF:
5751 		case MTBSR:
5752 		case MTSRSZ:
5753 		case MTGRSZ:
5754 		case MTSEEK:
5755 		case MTBSSF:
5756 		case MTFSSF:
5757 			return (EIO);
5758 			/* NOTREACHED */
5759 		case MTREW:
5760 		case MTLOAD:
5761 		case MTOFFL:
5762 		case MTNOP:
5763 		case MTTELL:
5764 		case MTLOCK:
5765 		case MTUNLOCK:
5766 			break;
5767 
5768 		default:
5769 			return (ENOTTY);
5770 			/* NOTREACHED */
5771 		}
5772 	}
5773 
5774 	switch (mtop->mt_op) {
5775 	case MTERASE:
5776 		/*
5777 		 * MTERASE rewinds the tape, erase it completely, and returns
5778 		 * to the beginning of the tape
5779 		 */
5780 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5781 			un->un_status = KEY_WRITE_PROTECT;
5782 			un->un_err_resid = mtop->mt_count;
5783 			COPY_POS(&un->un_err_pos, &un->un_pos);
5784 			return (EACCES);
5785 		}
5786 		if (un->un_dp->options & ST_REEL) {
5787 			un->un_fmneeded = 2;
5788 		} else {
5789 			un->un_fmneeded = 1;
5790 		}
5791 		mtop->mt_count = mtop->mt_count ? 1 : 0;
5792 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5793 		    st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
5794 		    st_cmd(un, SCMD_ERASE, mtop->mt_count, SYNC_CMD)) {
5795 			un->un_pos.pmode = invalid;
5796 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5797 			    "st_do_mtioctop : EIO space or erase or "
5798 			    "check den)\n");
5799 			rval = EIO;
5800 		} else {
5801 			/* QIC and helical scan rewind after erase */
5802 			if (un->un_dp->options & ST_REEL) {
5803 				(void) st_cmd(un, SCMD_REWIND, 0, ASYNC_CMD);
5804 			}
5805 		}
5806 		break;
5807 
5808 	case MTWEOF:
5809 		/*
5810 		 * write an end-of-file record
5811 		 */
5812 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5813 			un->un_status = KEY_WRITE_PROTECT;
5814 			un->un_err_resid = mtop->mt_count;
5815 			COPY_POS(&un->un_err_pos, &un->un_pos);
5816 			return (EACCES);
5817 		}
5818 
5819 		/*
5820 		 * zero count means just flush buffers
5821 		 * negative count is not permitted
5822 		 */
5823 		if (mtop->mt_count < 0) {
5824 			return (EINVAL);
5825 		}
5826 
5827 		/* Not on worm */
5828 		if (un->un_read_only == RDWR) {
5829 			un->un_test_append = 1;
5830 		}
5831 
5832 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5833 			if (st_determine_density(un, B_WRITE)) {
5834 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5835 				    "st_do_mtioctop : EIO : MTWEOF can't "
5836 				    "determine density");
5837 				return (EIO);
5838 			}
5839 		}
5840 
5841 		rval = st_write_fm(dev, (int)mtop->mt_count);
5842 		if ((rval != 0) && (rval != EACCES)) {
5843 			/*
5844 			 * Failure due to something other than illegal
5845 			 * request results in loss of state (st_intr).
5846 			 */
5847 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5848 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5849 			    "file mark");
5850 			rval = EIO;
5851 		}
5852 		break;
5853 
5854 	case MTRETEN:
5855 		/*
5856 		 * retension the tape
5857 		 */
5858 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5859 		    st_cmd(un, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5860 			un->un_pos.pmode = invalid;
5861 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5862 			    "st_do_mtioctop : EIO : MTRETEN ");
5863 			rval = EIO;
5864 		}
5865 		break;
5866 
5867 	case MTREW:
5868 		/*
5869 		 * rewind  the tape
5870 		 */
5871 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5872 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5873 			    "st_do_mtioctop : EIO:MTREW check "
5874 			    "density/wfm failed");
5875 			return (EIO);
5876 		}
5877 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
5878 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5879 			    "st_do_mtioctop : EIO : MTREW ");
5880 			rval = EIO;
5881 		}
5882 		break;
5883 
5884 	case MTOFFL:
5885 		/*
5886 		 * rewinds, and, if appropriate, takes the device offline by
5887 		 * unloading the tape
5888 		 */
5889 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5890 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5891 			    "st_do_mtioctop :EIO:MTOFFL check "
5892 			    "density/wfm failed");
5893 			return (EIO);
5894 		}
5895 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
5896 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5897 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5898 			    "st_do_mtioctop : EIO : MTOFFL");
5899 			return (EIO);
5900 		}
5901 		un->un_pos.eof = ST_NO_EOF;
5902 		un->un_laststate = un->un_state;
5903 		un->un_state = ST_STATE_OFFLINE;
5904 		un->un_mediastate = MTIO_EJECTED;
5905 		break;
5906 
5907 	case MTLOAD:
5908 		/*
5909 		 * This is to load a tape into the drive
5910 		 * Note that if the tape is not loaded, the device will have
5911 		 * to be opened via O_NDELAY or O_NONBLOCK.
5912 		 */
5913 		/*
5914 		 * Let's try and clean things up, if we are not
5915 		 * initializing, and then send in the load command, no
5916 		 * matter what.
5917 		 *
5918 		 * load after a media change by the user.
5919 		 */
5920 
5921 		if (un->un_state > ST_STATE_INITIALIZING) {
5922 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5923 		}
5924 		rval = st_cmd(un, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5925 		/* Load command to a drive that doesn't support load */
5926 		if ((rval == EIO) &&
5927 		    ((un->un_status == KEY_NOT_READY) &&
5928 			/* Medium not present */
5929 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5930 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5931 		    (un->un_dp->type == MT_ISSTK9840) &&
5932 			/* CSL not present */
5933 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5934 			rval = ENOTTY;
5935 			break;
5936 		} else if (rval != EACCES && rval != 0) {
5937 			rval = EIO;
5938 		}
5939 		if (rval) {
5940 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5941 			    "st_do_mtioctop : %s : MTLOAD\n",
5942 			    rval == EACCES ? "EACCES" : "EIO");
5943 			/*
5944 			 * If load tape fails, who knows what happened...
5945 			 */
5946 			un->un_pos.pmode = invalid;
5947 			break;
5948 		}
5949 
5950 		/*
5951 		 * reset all counters appropriately using rewind, as if LOAD
5952 		 * succeeds, we are at BOT
5953 		 */
5954 		un->un_state = ST_STATE_INITIALIZING;
5955 
5956 		rval = st_tape_init(un);
5957 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5958 			rval = 0;
5959 			break;
5960 		}
5961 
5962 		if (rval != 0) {
5963 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5964 			    "st_do_mtioctop : EIO : MTLOAD calls "
5965 			    "st_tape_init\n");
5966 			rval = EIO;
5967 			un->un_state = ST_STATE_OFFLINE;
5968 		}
5969 
5970 		break;
5971 
5972 	case MTNOP:
5973 		un->un_status = 0;		/* Reset status */
5974 		un->un_err_resid = 0;
5975 		mtop->mt_count = MTUNIT(dev);
5976 		break;
5977 
5978 	case MTEOM:
5979 		/*
5980 		 * positions the tape at a location just after the last file
5981 		 * written on the tape. For cartridge and 8 mm, this after
5982 		 * the last file mark; for reel, this is inbetween the two
5983 		 * last 2 file marks
5984 		 */
5985 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5986 		    (un->un_lastop == ST_OP_WRITE) ||
5987 		    (un->un_lastop == ST_OP_WEOF)) {
5988 			/*
5989 			 * If the command wants to move to logical end
5990 			 * of media, and we're already there, we're done.
5991 			 * If we were at logical eot, we reset the state
5992 			 * to be *not* at logical eot.
5993 			 *
5994 			 * If we're at physical or logical eot, we prohibit
5995 			 * forward space operations (unconditionally).
5996 			 *
5997 			 * Also if the last operation was a write of any
5998 			 * kind the tape is at EOD.
5999 			 */
6000 			return (0);
6001 		}
6002 		/*
6003 		 * physical tape position may not be what we've been
6004 		 * telling the user; adjust the request accordingly
6005 		 */
6006 		if (IN_EOF(un->un_pos)) {
6007 			un->un_pos.fileno++;
6008 			un->un_pos.blkno = 0;
6009 		}
6010 
6011 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
6012 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6013 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
6014 			    " failed");
6015 			return (EIO);
6016 		}
6017 
6018 		/*
6019 		 * st_find_eod() returns the last fileno we knew about;
6020 		 */
6021 		savefile = st_find_eod(un);
6022 
6023 		if ((un->un_status != KEY_BLANK_CHECK) &&
6024 		    (un->un_status != SUN_KEY_EOT)) {
6025 			un->un_pos.pmode = invalid;
6026 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6027 			    "st_do_mtioctop : EIO : MTEOM status check failed");
6028 			rval = EIO;
6029 		} else {
6030 			/*
6031 			 * For 1/2" reel tapes assume logical EOT marked
6032 			 * by two file marks or we don't care that we may
6033 			 * be extending the last file on the tape.
6034 			 */
6035 			if (un->un_dp->options & ST_REEL) {
6036 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
6037 					un->un_pos.pmode = invalid;
6038 					ST_DEBUG2(ST_DEVINFO, st_label,
6039 					    SCSI_DEBUG,
6040 					    "st_do_mtioctop : EIO : MTEOM space"
6041 					    " cmd failed");
6042 					rval = EIO;
6043 					break;
6044 				}
6045 				/*
6046 				 * Fix up the block number.
6047 				 */
6048 				un->un_pos.blkno = 0;
6049 				un->un_err_pos.blkno = 0;
6050 			}
6051 			un->un_err_resid = 0;
6052 			un->un_pos.fileno = savefile;
6053 			un->un_pos.eof = ST_EOT;
6054 		}
6055 		un->un_status = 0;
6056 		break;
6057 
6058 	case MTFSF:
6059 		MAX_SPACE_CNT(mtop->mt_count);
6060 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
6061 		break;
6062 
6063 	case MTFSR:
6064 		MAX_SPACE_CNT(mtop->mt_count);
6065 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
6066 		break;
6067 
6068 	case MTBSF:
6069 		MAX_SPACE_CNT(mtop->mt_count);
6070 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
6071 		break;
6072 
6073 	case MTNBSF:
6074 		MAX_SPACE_CNT(mtop->mt_count);
6075 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
6076 		break;
6077 
6078 	case MTBSR:
6079 		MAX_SPACE_CNT(mtop->mt_count);
6080 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
6081 		break;
6082 
6083 	case MTBSSF:
6084 		MAX_SPACE_CNT(mtop->mt_count);
6085 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
6086 		break;
6087 
6088 	case MTFSSF:
6089 		MAX_SPACE_CNT(mtop->mt_count);
6090 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
6091 		break;
6092 
6093 	case MTSRSZ:
6094 
6095 		/*
6096 		 * Set record-size to that sent by user
6097 		 * Check to see if there is reason that the requested
6098 		 * block size should not be set.
6099 		 */
6100 
6101 		/* If requesting variable block size is it ok? */
6102 		if ((mtop->mt_count == 0) &&
6103 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
6104 			return (ENOTTY);
6105 		}
6106 
6107 		/*
6108 		 * If requested block size is not variable "0",
6109 		 * is it less then minimum.
6110 		 */
6111 		if ((mtop->mt_count != 0) &&
6112 		    (mtop->mt_count < un->un_minbsize)) {
6113 			return (EINVAL);
6114 		}
6115 
6116 		/* Is the requested block size more then maximum */
6117 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
6118 		    (un->un_maxbsize != 0)) {
6119 			return (EINVAL);
6120 		}
6121 
6122 		/* Is requested block size a modulus the device likes */
6123 		if ((mtop->mt_count % un->un_data_mod) != 0) {
6124 			return (EINVAL);
6125 		}
6126 
6127 		if (st_change_block_size(un, (uint32_t)mtop->mt_count) != 0) {
6128 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6129 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
6130 			return (EIO);
6131 		}
6132 
6133 		return (0);
6134 
6135 	case MTGRSZ:
6136 		/*
6137 		 * Get record-size to the user
6138 		 */
6139 		mtop->mt_count = un->un_bsize;
6140 		rval = 0;
6141 		break;
6142 
6143 	case MTTELL:
6144 		rval = st_update_block_pos(un, st_cmd, 0);
6145 		mtop->mt_count = un->un_pos.lgclblkno;
6146 		break;
6147 
6148 	case MTSEEK:
6149 		rval = st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
6150 		    (uint64_t)mtop->mt_count, un->un_pos.partition);
6151 		/*
6152 		 * This bit of magic make mt print the actual position if
6153 		 * the resulting position was not what was asked for.
6154 		 */
6155 		if (rval == ESPIPE) {
6156 			rval = EIO;
6157 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
6158 				mtop->mt_op = MTTELL;
6159 				mtop->mt_count = un->un_pos.lgclblkno;
6160 			}
6161 		}
6162 		break;
6163 
6164 	case MTLOCK:
6165 		if (st_cmd(un, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
6166 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6167 			    "st_do_mtioctop : EIO : MTLOCK");
6168 			rval = EIO;
6169 		}
6170 		break;
6171 
6172 	case MTUNLOCK:
6173 		if (st_cmd(un, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
6174 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6175 			    "st_do_mtioctop : EIO : MTUNLOCK");
6176 			rval = EIO;
6177 		}
6178 		break;
6179 
6180 	default:
6181 		rval = ENOTTY;
6182 	}
6183 
6184 	return (rval);
6185 }
6186 
6187 
6188 /*
6189  * Run a command for uscsi ioctl.
6190  */
6191 static int
6192 st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
6193 {
6194 	struct uscsi_cmd	*uscmd;
6195 	struct buf	*bp;
6196 	enum uio_seg	uioseg;
6197 	int	offline_state = 0;
6198 	int	err = 0;
6199 	dev_t dev = un->un_dev;
6200 
6201 	ST_FUNC(ST_DEVINFO, st_uscsi_cmd);
6202 
6203 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6204 	    "st_uscsi_cmd(dev = 0x%lx)\n", un->un_dev);
6205 
6206 	ASSERT(mutex_owned(ST_MUTEX));
6207 
6208 	/*
6209 	 * We really don't know what commands are coming in here and
6210 	 * we don't want to limit the commands coming in.
6211 	 *
6212 	 * If st_tape_init() gets called from st_strategy(), then we
6213 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
6214 	 * which it never will, as we set it below.  To prevent
6215 	 * st_tape_init() from getting called, we have to set state to other
6216 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
6217 	 * achieves this purpose already.
6218 	 *
6219 	 * We use offline_state to preserve the OFFLINE state, if it exists,
6220 	 * so other entry points to the driver might have the chance to call
6221 	 * st_tape_init().
6222 	 */
6223 	if (un->un_state == ST_STATE_OFFLINE) {
6224 		un->un_laststate = ST_STATE_OFFLINE;
6225 		un->un_state = ST_STATE_INITIALIZING;
6226 		offline_state = 1;
6227 	}
6228 
6229 	mutex_exit(ST_MUTEX);
6230 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag, ROUTE, &uscmd);
6231 	mutex_enter(ST_MUTEX);
6232 	if (err != 0) {
6233 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6234 		    "st_uscsi_cmd: scsi_uscsi_alloc_and_copyin failed\n");
6235 		goto exit;
6236 	}
6237 
6238 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
6239 
6240 	/* check to see if this command requires the drive to be reserved */
6241 	if (uscmd->uscsi_cdb != NULL) {
6242 		err = st_check_cdb_for_need_to_reserve(un,
6243 		    (uchar_t *)uscmd->uscsi_cdb);
6244 		if (err) {
6245 			goto exit_free;
6246 		}
6247 		/*
6248 		 * If this is a space command we need to save the starting
6249 		 * point so we can retry from there if the command fails.
6250 		 */
6251 		if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6252 		    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) {
6253 			(void) st_update_block_pos(un, st_cmd, 0);
6254 		}
6255 	}
6256 
6257 	/*
6258 	 * Forground should not be doing anything while recovery is active.
6259 	 */
6260 	ASSERT(un->un_recov_buf_busy == 0);
6261 
6262 	/*
6263 	 * Get buffer resources...
6264 	 */
6265 	while (un->un_sbuf_busy)
6266 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6267 	un->un_sbuf_busy = 1;
6268 
6269 #ifdef STDEBUG
6270 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0x7) > 6) {
6271 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
6272 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6273 		    "uscsi cdb", uscmd->uscsi_cdb);
6274 		if (uscmd->uscsi_buflen) {
6275 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6276 			    "uscsi %s of %ld bytes %s %s space\n",
6277 			    (rw == B_READ) ? rd_str : wr_str,
6278 			    uscmd->uscsi_buflen,
6279 			    (rw == B_READ) ? "to" : "from",
6280 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
6281 		}
6282 	}
6283 #endif /* STDEBUG */
6284 
6285 	/*
6286 	 * Although st_uscsi_cmd() never makes use of these
6287 	 * now, we are just being safe and consistent.
6288 	 */
6289 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
6290 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
6291 
6292 	un->un_srqbufp = uscmd->uscsi_rqbuf;
6293 	bp = un->un_sbufp;
6294 	bzero(bp, sizeof (buf_t));
6295 	if (uscmd->uscsi_cdb != NULL) {
6296 		bp->b_forw = (struct buf *)(uintptr_t)uscmd->uscsi_cdb[0];
6297 	}
6298 	bp->b_back = (struct buf *)uscmd;
6299 
6300 	mutex_exit(ST_MUTEX);
6301 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, st_strategy, bp, NULL);
6302 	mutex_enter(ST_MUTEX);
6303 
6304 	/*
6305 	 * If scsi reset successful, don't write any filemarks.
6306 	 */
6307 	if ((err == 0) && (uscmd->uscsi_flags &
6308 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
6309 		un->un_fmneeded = 0;
6310 	}
6311 
6312 exit_free:
6313 	/*
6314 	 * Free resources
6315 	 */
6316 	un->un_sbuf_busy = 0;
6317 	un->un_srqbufp = NULL;
6318 
6319 	/*
6320 	 * If was a space command need to update logical block position.
6321 	 * If the command failed such that positioning is invalid, Don't
6322 	 * update the position as the user must do this to validate the
6323 	 * position for data protection.
6324 	 */
6325 	if ((uscmd->uscsi_cdb != NULL) &&
6326 	    ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6327 	    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) &&
6328 	    (un->un_pos.pmode != invalid)) {
6329 		un->un_running.pmode = invalid;
6330 		(void) st_update_block_pos(un, st_cmd, 1);
6331 		/*
6332 		 * Set running position to invalid so it updates on the
6333 		 * next command.
6334 		 */
6335 		un->un_running.pmode = invalid;
6336 	}
6337 	cv_signal(&un->un_sbuf_cv);
6338 	mutex_exit(ST_MUTEX);
6339 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
6340 	mutex_enter(ST_MUTEX);
6341 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6342 	    "st_uscsi_cmd returns 0x%x\n", err);
6343 
6344 exit:
6345 	/* don't lose offline state */
6346 	if (offline_state) {
6347 		un->un_state = ST_STATE_OFFLINE;
6348 	}
6349 
6350 	ASSERT(mutex_owned(ST_MUTEX));
6351 	return (err);
6352 }
6353 
6354 static int
6355 st_write_fm(dev_t dev, int wfm)
6356 {
6357 	int i;
6358 	int rval;
6359 
6360 	GET_SOFT_STATE(dev);
6361 
6362 	ST_FUNC(ST_DEVINFO, st_write_fm);
6363 
6364 	ASSERT(mutex_owned(ST_MUTEX));
6365 
6366 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6367 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6368 
6369 	/*
6370 	 * write one filemark at the time after EOT
6371 	 */
6372 	if (un->un_pos.eof >= ST_EOT) {
6373 		for (i = 0; i < wfm; i++) {
6374 			rval = st_cmd(un, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6375 			if (rval == EACCES) {
6376 				return (rval);
6377 			}
6378 			if (rval != 0) {
6379 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6380 				    "st_write_fm : EIO : write EOT file mark");
6381 				return (EIO);
6382 			}
6383 		}
6384 	} else {
6385 		rval = st_cmd(un, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6386 		if (rval == EACCES) {
6387 			return (rval);
6388 		}
6389 		if (rval) {
6390 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6391 			    "st_write_fm : EIO : write file mark");
6392 			return (EIO);
6393 		}
6394 	}
6395 
6396 	ASSERT(mutex_owned(ST_MUTEX));
6397 	return (0);
6398 }
6399 
6400 #ifdef STDEBUG
6401 static void
6402 st_start_dump(struct scsi_tape *un, struct buf *bp)
6403 {
6404 	struct scsi_pkt *pkt = BP_PKT(bp);
6405 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6406 
6407 	ST_FUNC(ST_DEVINFO, st_start_dump);
6408 
6409 	if ((st_debug & 0x7) < 6)
6410 		return;
6411 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6412 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6413 	    (void *)bp->b_forw, bp->b_bcount,
6414 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6415 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6416 	    "st_start: cdb",  (caddr_t)cdbp);
6417 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6418 	    "st_start: fileno=%d, blk=%d\n",
6419 	    un->un_pos.fileno, un->un_pos.blkno);
6420 }
6421 #endif
6422 
6423 
6424 /*
6425  * Command start && done functions
6426  */
6427 
6428 /*
6429  * st_start()
6430  *
6431  * Called from:
6432  *  st_strategy() to start a command.
6433  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6434  *  st_attach() when resuming from power down state.
6435  *  st_start_restart() to retry transport when device was previously busy.
6436  *  st_done_and_mutex_exit() to start the next command when previous is done.
6437  *
6438  * On entry:
6439  *  scsi_pkt may or may not be allocated.
6440  *
6441  */
6442 static void
6443 st_start(struct scsi_tape *un)
6444 {
6445 	struct buf *bp;
6446 	int status;
6447 	int queued;
6448 
6449 	ST_FUNC(ST_DEVINFO, st_start);
6450 	ASSERT(mutex_owned(ST_MUTEX));
6451 
6452 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6453 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6454 
6455 	if (un->un_recov_buf_busy) {
6456 		/* recovery commands can happen anytime */
6457 		bp = un->un_recov_buf;
6458 		queued = 0;
6459 	} else if (un->un_sbuf_busy) {
6460 		/* sbuf commands should only happen with an empty queue. */
6461 		ASSERT(un->un_quef == NULL);
6462 		ASSERT(un->un_runqf == NULL);
6463 		bp = un->un_sbufp;
6464 		queued = 0;
6465 	} else if (un->un_quef != NULL) {
6466 		if (un->un_persistence && un->un_persist_errors) {
6467 			return;
6468 		}
6469 		bp = un->un_quef;
6470 		queued = 1;
6471 	} else {
6472 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6473 		    "st_start() returning no buf found\n");
6474 		return;
6475 	}
6476 
6477 	ASSERT((bp->b_flags & B_DONE) == 0);
6478 
6479 	/*
6480 	 * Don't send more than un_throttle commands to the HBA
6481 	 */
6482 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6483 		/*
6484 		 * if doing recovery we know there is outstanding commands.
6485 		 */
6486 		if (bp != un->un_recov_buf) {
6487 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6488 			    "st_start returning throttle = %d or ncmds = %d\n",
6489 			    un->un_throttle, un->un_ncmds);
6490 			if (un->un_ncmds == 0) {
6491 				typedef void (*func)();
6492 				func fnc = (func)st_runout;
6493 
6494 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6495 				    "Sending delayed start to st_runout()\n");
6496 				mutex_exit(ST_MUTEX);
6497 				(void) timeout(fnc, un, drv_usectohz(1000000));
6498 				mutex_enter(ST_MUTEX);
6499 			}
6500 			return;
6501 		}
6502 	}
6503 
6504 	/*
6505 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6506 	 * build the command.
6507 	 */
6508 	if (BP_PKT(bp) == NULL) {
6509 		ASSERT((bp->b_flags & B_DONE) == 0);
6510 		st_make_cmd(un, bp, st_runout);
6511 		ASSERT((bp->b_flags & B_DONE) == 0);
6512 		status = geterror(bp);
6513 
6514 		/*
6515 		 * Some HBA's don't call bioerror() to set an error.
6516 		 * And geterror() returns zero if B_ERROR is not set.
6517 		 * So if we get zero we must check b_error.
6518 		 */
6519 		if (status == 0 && bp->b_error != 0) {
6520 			status = bp->b_error;
6521 			bioerror(bp, status);
6522 		}
6523 
6524 		/*
6525 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6526 		 * In tape ENOMEM has special meaning so we'll change it.
6527 		 */
6528 		if (status == ENOMEM) {
6529 			status = 0;
6530 			bioerror(bp, status);
6531 		}
6532 
6533 		/*
6534 		 * Did it fail and is it retryable?
6535 		 * If so return and wait for the callback through st_runout.
6536 		 * Also looks like scsi_init_pkt() will setup a callback even
6537 		 * if it isn't retryable.
6538 		 */
6539 		if (BP_PKT(bp) == NULL) {
6540 			if (status == 0) {
6541 				/*
6542 				 * If first attempt save state.
6543 				 */
6544 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6545 					un->un_laststate = un->un_state;
6546 					un->un_state = ST_STATE_RESOURCE_WAIT;
6547 				}
6548 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6549 				    "temp no resources for pkt\n");
6550 			} else if (status == EINVAL) {
6551 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6552 				    "scsi_init_pkt rejected pkt as too big\n");
6553 				if (un->un_persistence) {
6554 					st_set_pe_flag(un);
6555 				}
6556 			} else {
6557 				/*
6558 				 * Unlikely that it would be retryable then not.
6559 				 */
6560 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6561 					un->un_state = un->un_laststate;
6562 				}
6563 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6564 				    "perm no resources for pkt errno = 0x%x\n",
6565 				    status);
6566 			}
6567 			return;
6568 		}
6569 		/*
6570 		 * Worked this time set the state back.
6571 		 */
6572 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6573 			un->un_state = un->un_laststate;
6574 		}
6575 	}
6576 
6577 	if (queued) {
6578 		/*
6579 		 * move from waitq to runq
6580 		 */
6581 		(void) st_remove_from_queue(&un->un_quef, &un->un_quel, bp);
6582 		st_add_to_queue(&un->un_runqf, &un->un_runql, un->un_runql, bp);
6583 	}
6584 
6585 
6586 #ifdef STDEBUG
6587 	st_start_dump(un, bp);
6588 #endif
6589 
6590 	/* could not get here if throttle was zero */
6591 	un->un_last_throttle = un->un_throttle;
6592 	un->un_throttle = 0;	/* so nothing else will come in here */
6593 	un->un_ncmds++;
6594 
6595 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6596 
6597 	status = st_transport(un, BP_PKT(bp));
6598 
6599 	if (un->un_last_throttle) {
6600 		un->un_throttle = un->un_last_throttle;
6601 	}
6602 
6603 	if (status != TRAN_ACCEPT) {
6604 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6605 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
6606 		    "Unhappy transport packet status 0x%x\n", status);
6607 
6608 		if (status == TRAN_BUSY) {
6609 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
6610 
6611 			/*
6612 			 * If command recovery is enabled and this isn't
6613 			 * a recovery command try command recovery.
6614 			 */
6615 			if (pkti->privatelen == sizeof (recov_info) &&
6616 			    bp != un->un_recov_buf) {
6617 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
6618 				    "Command Recovery called on busy send\n");
6619 				if (st_command_recovery(un, BP_PKT(bp),
6620 				    ATTEMPT_RETRY) == JUST_RETURN) {
6621 					return;
6622 				}
6623 			} else {
6624 				mutex_exit(ST_MUTEX);
6625 				if (st_handle_start_busy(un, bp,
6626 				    ST_TRAN_BUSY_TIMEOUT, queued) == 0) {
6627 					mutex_enter(ST_MUTEX);
6628 					return;
6629 				}
6630 				/*
6631 				 * if too many retries, fail the transport
6632 				 */
6633 				mutex_enter(ST_MUTEX);
6634 			}
6635 		}
6636 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6637 		    "transport rejected %d\n", status);
6638 		bp->b_resid = bp->b_bcount;
6639 
6640 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6641 		ST_DO_ERRSTATS(un, st_transerrs);
6642 		if ((bp == un->un_recov_buf) && (status == TRAN_BUSY)) {
6643 			st_bioerror(bp, EBUSY);
6644 		} else {
6645 			st_bioerror(bp, EIO);
6646 			st_set_pe_flag(un);
6647 		}
6648 		st_done_and_mutex_exit(un, bp);
6649 		mutex_enter(ST_MUTEX);
6650 	}
6651 
6652 	ASSERT(mutex_owned(ST_MUTEX));
6653 }
6654 
6655 /*
6656  * if the transport is busy, then put this bp back on the waitq
6657  */
6658 static int
6659 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6660     clock_t timeout_interval, int queued)
6661 {
6662 
6663 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
6664 
6665 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6666 
6667 	mutex_enter(ST_MUTEX);
6668 
6669 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6670 	    "st_handle_start_busy()\n");
6671 
6672 	/*
6673 	 * Check to see if we hit the retry timeout and one last check for
6674 	 * making sure this is the last on the runq, if it is not, we have
6675 	 * to fail
6676 	 */
6677 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
6678 	    ((queued) && (un->un_runql != bp))) {
6679 		mutex_exit(ST_MUTEX);
6680 		return (-1);
6681 	}
6682 
6683 	if (queued) {
6684 		/* put the bp back on the waitq */
6685 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
6686 	}
6687 
6688 	/*
6689 	 * Decrement un_ncmds so that this
6690 	 * gets thru' st_start() again.
6691 	 */
6692 	un->un_ncmds--;
6693 
6694 	if (queued) {
6695 		/*
6696 		 * since this is an error case, we won't have to do this list
6697 		 * walking much. We've already made sure this bp was the
6698 		 * last on the runq
6699 		 */
6700 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6701 
6702 		/*
6703 		 * send a marker pkt, if appropriate
6704 		 */
6705 		st_hba_unflush(un);
6706 
6707 	}
6708 	/*
6709 	 * all queues are aligned, we are just waiting to
6710 	 * transport, don't alloc any more buf p's, when
6711 	 * st_start is reentered.
6712 	 */
6713 	(void) timeout(st_start_restart, un, timeout_interval);
6714 
6715 	mutex_exit(ST_MUTEX);
6716 	return (0);
6717 }
6718 
6719 
6720 /*
6721  * st_runout a callback that is called what a resource allocatation failed
6722  */
6723 static int
6724 st_runout(caddr_t arg)
6725 {
6726 	struct scsi_tape *un = (struct scsi_tape *)arg;
6727 	struct buf *bp;
6728 	int queued;
6729 
6730 	ASSERT(un != NULL);
6731 
6732 	ST_FUNC(ST_DEVINFO, st_runout);
6733 
6734 	mutex_enter(ST_MUTEX);
6735 
6736 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6737 
6738 	if (un->un_recov_buf_busy != 0) {
6739 		bp = un->un_recov_buf;
6740 		queued = 0;
6741 	} else if (un->un_sbuf_busy != 0) {
6742 		/* sbuf commands should only happen with an empty queue. */
6743 		ASSERT(un->un_quef == NULL);
6744 		ASSERT(un->un_runqf == NULL);
6745 		bp = un->un_sbufp;
6746 		queued = 0;
6747 	} else if (un->un_quef != NULL) {
6748 		bp = un->un_quef;
6749 		if (un->un_persistence && un->un_persist_errors) {
6750 			mutex_exit(ST_MUTEX);
6751 			bp->b_resid = bp->b_bcount;
6752 			biodone(bp);
6753 			return (1);
6754 		}
6755 		queued = 1;
6756 	} else {
6757 		ASSERT(1 == 0);
6758 		mutex_exit(ST_MUTEX);
6759 		return (1);
6760 	}
6761 
6762 	/*
6763 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6764 	 */
6765 	if ((bp != NULL) && (geterror(bp) != 0)) {
6766 
6767 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6768 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6769 		    bp->b_flags, geterror(bp));
6770 		ASSERT((bp->b_flags & B_DONE) == 0);
6771 
6772 		if (queued) {
6773 			(void) st_remove_from_queue(&un->un_quef, &un->un_quel,
6774 			    bp);
6775 		}
6776 		mutex_exit(ST_MUTEX);
6777 
6778 		ASSERT((bp->b_flags & B_DONE) == 0);
6779 
6780 		/*
6781 		 * Set resid, Error already set, then unblock calling thread.
6782 		 */
6783 		bp->b_resid = bp->b_bcount;
6784 		biodone(bp);
6785 	} else {
6786 		/*
6787 		 * Try Again
6788 		 */
6789 		st_start(un);
6790 		mutex_exit(ST_MUTEX);
6791 	}
6792 
6793 	/*
6794 	 * Comments courtesy of sd.c
6795 	 * The scsi_init_pkt routine allows for the callback function to
6796 	 * return a 0 indicating the callback should be rescheduled or a 1
6797 	 * indicating not to reschedule. This routine always returns 1
6798 	 * because the driver always provides a callback function to
6799 	 * scsi_init_pkt. This results in a callback always being scheduled
6800 	 * (via the scsi_init_pkt callback implementation) if a resource
6801 	 * failure occurs.
6802 	 */
6803 
6804 	return (1);
6805 }
6806 
6807 /*
6808  * st_done_and_mutex_exit()
6809  *	- remove bp from runq
6810  *	- start up the next request
6811  *	- if this was an asynch bp, clean up
6812  *	- exit with released mutex
6813  */
6814 static void
6815 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6816 {
6817 	int pe_flagged = 0;
6818 	struct scsi_pkt *pkt = BP_PKT(bp);
6819 	pkt_info *pktinfo = pkt->pkt_private;
6820 
6821 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6822 #if !defined(lint)
6823 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6824 #endif
6825 
6826 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6827 
6828 	ASSERT(mutex_owned(ST_MUTEX));
6829 
6830 	(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6831 
6832 	un->un_ncmds--;
6833 	cv_signal(&un->un_queue_cv);
6834 
6835 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6836 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6837 	    "0x%x\n", pkt->pkt_cdbp[0], bp->b_bcount,
6838 	    bp->b_resid, bp->b_flags);
6839 
6840 
6841 	/*
6842 	 * update kstats with transfer count info
6843 	 */
6844 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6845 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6846 		if (bp->b_flags & B_READ) {
6847 			IOSP->reads++;
6848 			IOSP->nread += n_done;
6849 		} else {
6850 			IOSP->writes++;
6851 			IOSP->nwritten += n_done;
6852 		}
6853 	}
6854 
6855 	/*
6856 	 * Start the next one before releasing resources on this one, if
6857 	 * there is something on the queue and persistent errors has not been
6858 	 * flagged
6859 	 */
6860 
6861 	if ((pe_flagged = (un->un_persistence && un->un_persist_errors)) != 0) {
6862 		un->un_last_resid = bp->b_resid;
6863 		un->un_last_count = bp->b_bcount;
6864 	}
6865 
6866 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6867 		cv_broadcast(&un->un_tape_busy_cv);
6868 	} else if (un->un_quef && un->un_throttle && !pe_flagged &&
6869 	    (bp != un->un_recov_buf)) {
6870 		st_start(un);
6871 	}
6872 
6873 	un->un_retry_ct = max(pktinfo->pkt_retry_cnt, pktinfo->str_retry_cnt);
6874 
6875 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6876 		/*
6877 		 * Since we marked this ourselves as ASYNC,
6878 		 * there isn't anybody around waiting for
6879 		 * completion any more.
6880 		 */
6881 		uchar_t *cmd = pkt->pkt_cdbp;
6882 		if (*cmd == SCMD_READ || *cmd == SCMD_WRITE) {
6883 			bp->b_un.b_addr = (caddr_t)0;
6884 		}
6885 		ST_DEBUG(ST_DEVINFO, st_label, CE_NOTE,
6886 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6887 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
6888 		    "CDB sent with B_ASYNC",  (caddr_t)cmd);
6889 		if (pkt) {
6890 			scsi_destroy_pkt(pkt);
6891 		}
6892 		un->un_sbuf_busy = 0;
6893 		cv_signal(&un->un_sbuf_cv);
6894 		mutex_exit(ST_MUTEX);
6895 		return;
6896 	}
6897 
6898 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6899 		/*
6900 		 * Copy status from scsi_pkt to uscsi_cmd
6901 		 * since st_uscsi_cmd needs it
6902 		 */
6903 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6904 	}
6905 
6906 
6907 #ifdef STDEBUG
6908 	if (((st_debug & 0x7) >= 4) &&
6909 	    (((un->un_pos.blkno % 100) == 0) ||
6910 	    (un->un_persistence && un->un_persist_errors))) {
6911 
6912 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6913 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6914 		    "un_errno = %d, un_pe = %d\n",
6915 		    un->un_ncmds, un->un_throttle, un->un_errno,
6916 		    un->un_persist_errors);
6917 	}
6918 
6919 #endif
6920 
6921 	mutex_exit(ST_MUTEX);
6922 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6923 	    "st_done_and_mutex_exit: freeing pkt\n");
6924 
6925 	if (pkt) {
6926 		scsi_destroy_pkt(pkt);
6927 	}
6928 
6929 	biodone(bp);
6930 
6931 	/*
6932 	 * now that we biodoned that command, if persistent errors have been
6933 	 * flagged, flush the waitq
6934 	 */
6935 	if (pe_flagged)
6936 		st_flush(un);
6937 }
6938 
6939 
6940 /*
6941  * Tape error, flush tape driver queue.
6942  */
6943 static void
6944 st_flush(struct scsi_tape *un)
6945 {
6946 	struct buf *bp;
6947 
6948 	ST_FUNC(ST_DEVINFO, st_flush);
6949 
6950 	mutex_enter(ST_MUTEX);
6951 
6952 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6953 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6954 	    un->un_ncmds, (void *)un->un_quef);
6955 
6956 	/*
6957 	 * if we still have commands outstanding, wait for them to come in
6958 	 * before flushing the queue, and make sure there is a queue
6959 	 */
6960 	if (un->un_ncmds || !un->un_quef)
6961 		goto exit;
6962 
6963 	/*
6964 	 * we have no more commands outstanding, so let's deal with special
6965 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6966 	 * is 0, then we know there was no error and we return a 0 read or
6967 	 * write before showing errors
6968 	 */
6969 
6970 	/* Flush the wait queue. */
6971 	while ((bp = un->un_quef) != NULL) {
6972 		un->un_quef = bp->b_actf;
6973 
6974 		bp->b_resid = bp->b_bcount;
6975 
6976 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6977 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6978 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6979 
6980 		st_set_pe_errno(un);
6981 
6982 		bioerror(bp, un->un_errno);
6983 
6984 		mutex_exit(ST_MUTEX);
6985 		/* it should have one, but check anyway */
6986 		if (BP_PKT(bp)) {
6987 			scsi_destroy_pkt(BP_PKT(bp));
6988 		}
6989 		biodone(bp);
6990 		mutex_enter(ST_MUTEX);
6991 	}
6992 
6993 	/*
6994 	 * It's not a bad practice to reset the
6995 	 * waitq tail pointer to NULL.
6996 	 */
6997 	un->un_quel = NULL;
6998 
6999 exit:
7000 	/* we mucked with the queue, so let others know about it */
7001 	cv_signal(&un->un_queue_cv);
7002 	mutex_exit(ST_MUTEX);
7003 }
7004 
7005 
7006 /*
7007  * Utility functions
7008  */
7009 static int
7010 st_determine_generic(struct scsi_tape *un)
7011 {
7012 	int bsize;
7013 	static char *cart = "0.25 inch cartridge";
7014 	char *sizestr;
7015 
7016 	ST_FUNC(ST_DEVINFO, st_determine_generic);
7017 
7018 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7019 	    "st_determine_generic(un = 0x%p)\n", (void*)un);
7020 
7021 	ASSERT(mutex_owned(ST_MUTEX));
7022 
7023 	if (st_modesense(un)) {
7024 		return (-1);
7025 	}
7026 
7027 	bsize = (un->un_mspl->high_bl << 16)	|
7028 	    (un->un_mspl->mid_bl << 8)	|
7029 	    (un->un_mspl->low_bl);
7030 
7031 	if (bsize == 0) {
7032 		un->un_dp->options |= ST_VARIABLE;
7033 		un->un_dp->bsize = 0;
7034 		un->un_bsize = 0;
7035 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
7036 		/*
7037 		 * record size of this device too big.
7038 		 * try and convert it to variable record length.
7039 		 *
7040 		 */
7041 		un->un_dp->options |= ST_VARIABLE;
7042 		if (st_change_block_size(un, 0) != 0) {
7043 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7044 			    "Fixed Record Size %d is too large\n", bsize);
7045 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7046 			    "Cannot switch to variable record size\n");
7047 			un->un_dp->options &= ~ST_VARIABLE;
7048 			return (-1);
7049 		}
7050 	} else if (st_change_block_size(un, 0) == 0) {
7051 		/*
7052 		 * If the drive was set to a non zero block size,
7053 		 * See if it can be set to a zero block size.
7054 		 * If it works, ST_VARIABLE so user can set it as they want.
7055 		 */
7056 		un->un_dp->options |= ST_VARIABLE;
7057 		un->un_dp->bsize = 0;
7058 		un->un_bsize = 0;
7059 	} else {
7060 		un->un_dp->bsize = bsize;
7061 		un->un_bsize = bsize;
7062 	}
7063 
7064 
7065 	switch (un->un_mspl->density) {
7066 	default:
7067 	case 0x0:
7068 		/*
7069 		 * default density, cannot determine any other
7070 		 * information.
7071 		 */
7072 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
7073 		un->un_dp->type = ST_TYPE_DEFAULT;
7074 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
7075 		break;
7076 	case 0x1:
7077 	case 0x2:
7078 	case 0x3:
7079 	case 0x6:
7080 		/*
7081 		 * 1/2" reel
7082 		 */
7083 		sizestr = "0.50 inch reel";
7084 		un->un_dp->type = ST_TYPE_REEL;
7085 		un->un_dp->options |= ST_REEL;
7086 		un->un_dp->densities[0] = 0x1;
7087 		un->un_dp->densities[1] = 0x2;
7088 		un->un_dp->densities[2] = 0x6;
7089 		un->un_dp->densities[3] = 0x3;
7090 		break;
7091 	case 0x4:
7092 	case 0x5:
7093 	case 0x7:
7094 	case 0x0b:
7095 
7096 		/*
7097 		 * Quarter inch.
7098 		 */
7099 		sizestr = cart;
7100 		un->un_dp->type = ST_TYPE_DEFAULT;
7101 		un->un_dp->options |= ST_QIC;
7102 
7103 		un->un_dp->densities[1] = 0x4;
7104 		un->un_dp->densities[2] = 0x5;
7105 		un->un_dp->densities[3] = 0x7;
7106 		un->un_dp->densities[0] = 0x0b;
7107 		break;
7108 
7109 	case 0x0f:
7110 	case 0x10:
7111 	case 0x11:
7112 	case 0x12:
7113 		/*
7114 		 * QIC-120, QIC-150, QIC-320, QIC-600
7115 		 */
7116 		sizestr = cart;
7117 		un->un_dp->type = ST_TYPE_DEFAULT;
7118 		un->un_dp->options |= ST_QIC;
7119 		un->un_dp->densities[0] = 0x0f;
7120 		un->un_dp->densities[1] = 0x10;
7121 		un->un_dp->densities[2] = 0x11;
7122 		un->un_dp->densities[3] = 0x12;
7123 		break;
7124 
7125 	case 0x09:
7126 	case 0x0a:
7127 	case 0x0c:
7128 	case 0x0d:
7129 		/*
7130 		 * 1/2" cartridge tapes. Include HI-TC.
7131 		 */
7132 		sizestr = cart;
7133 		sizestr[2] = '5';
7134 		sizestr[3] = '0';
7135 		un->un_dp->type = ST_TYPE_HIC;
7136 		un->un_dp->densities[0] = 0x09;
7137 		un->un_dp->densities[1] = 0x0a;
7138 		un->un_dp->densities[2] = 0x0c;
7139 		un->un_dp->densities[3] = 0x0d;
7140 		break;
7141 
7142 	case 0x13:
7143 			/* DDS-2/DDS-3 scsi spec densities */
7144 	case 0x24:
7145 	case 0x25:
7146 	case 0x26:
7147 		sizestr = "DAT Data Storage (DDS)";
7148 		un->un_dp->type = ST_TYPE_DAT;
7149 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7150 		break;
7151 
7152 	case 0x14:
7153 		/*
7154 		 * Helical Scan (Exabyte) devices
7155 		 */
7156 		sizestr = "8mm helical scan cartridge";
7157 		un->un_dp->type = ST_TYPE_EXABYTE;
7158 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7159 		break;
7160 	}
7161 
7162 	/*
7163 	 * Assume LONG ERASE, BSF and BSR
7164 	 */
7165 
7166 	un->un_dp->options |=
7167 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
7168 
7169 	/*
7170 	 * Only if mode sense data says no buffered write, set NOBUF
7171 	 */
7172 	if (un->un_mspl->bufm == 0)
7173 		un->un_dp->options |= ST_NOBUF;
7174 
7175 	/*
7176 	 * set up large read and write retry counts
7177 	 */
7178 
7179 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
7180 
7181 	/*
7182 	 * If this is a 0.50 inch reel tape, and
7183 	 * it is *not* variable mode, try and
7184 	 * set it to variable record length
7185 	 * mode.
7186 	 */
7187 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
7188 	    (un->un_dp->options & ST_VARIABLE)) {
7189 		if (st_change_block_size(un, 0) == 0) {
7190 			un->un_dp->bsize = 0;
7191 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
7192 			    un->un_mspl->low_bl = 0;
7193 		}
7194 	}
7195 
7196 	/*
7197 	 * Write to console about type of device found
7198 	 */
7199 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
7200 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
7201 	    sizestr);
7202 	if (un->un_dp->options & ST_VARIABLE) {
7203 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7204 		    "!Variable record length I/O\n");
7205 	} else {
7206 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7207 		    "!Fixed record length (%d byte blocks) I/O\n",
7208 		    un->un_dp->bsize);
7209 	}
7210 	ASSERT(mutex_owned(ST_MUTEX));
7211 	return (0);
7212 }
7213 
7214 static int
7215 st_determine_density(struct scsi_tape *un, int rw)
7216 {
7217 	int rval = 0;
7218 
7219 	ST_FUNC(ST_DEVINFO, st_determine_density);
7220 
7221 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7222 	    "st_determine_density(un = 0x%p, rw = %s)\n",
7223 	    (void*)un, (rw == B_WRITE ? wr_str: rd_str));
7224 
7225 	ASSERT(mutex_owned(ST_MUTEX));
7226 
7227 	/*
7228 	 * If we're past BOT, density is determined already.
7229 	 */
7230 	if (un->un_pos.pmode == logical) {
7231 		if (un->un_pos.lgclblkno != 0) {
7232 			goto exit;
7233 		}
7234 	} else if (un->un_pos.pmode == legacy) {
7235 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
7236 			/*
7237 			 * XXX: put in a bitch message about attempting to
7238 			 * XXX: change density past BOT.
7239 			 */
7240 			goto exit;
7241 		}
7242 	} else {
7243 		goto exit;
7244 	}
7245 	if ((un->un_pos.pmode == logical) &&
7246 	    (un->un_pos.lgclblkno != 0)) {
7247 		goto exit;
7248 	}
7249 
7250 
7251 	/*
7252 	 * If we're going to be writing, we set the density
7253 	 */
7254 	if (rw == 0 || rw == B_WRITE) {
7255 		/* un_curdens is used as an index into densities table */
7256 		un->un_curdens = MT_DENSITY(un->un_dev);
7257 		if (st_set_density(un)) {
7258 			rval = -1;
7259 		}
7260 		goto exit;
7261 	}
7262 
7263 	/*
7264 	 * If density is known already,
7265 	 * we don't have to get it again.(?)
7266 	 */
7267 	if (!un->un_density_known) {
7268 		if (st_get_density(un)) {
7269 			rval = -1;
7270 		}
7271 	}
7272 
7273 exit:
7274 	ASSERT(mutex_owned(ST_MUTEX));
7275 	return (rval);
7276 }
7277 
7278 
7279 /*
7280  * Try to determine density. We do this by attempting to read the
7281  * first record off the tape, cycling through the available density
7282  * codes as we go.
7283  */
7284 
7285 static int
7286 st_get_density(struct scsi_tape *un)
7287 {
7288 	int succes = 0, rval = -1, i;
7289 	uint_t size;
7290 	uchar_t dens, olddens;
7291 
7292 	ST_FUNC(ST_DEVINFO, st_get_density);
7293 
7294 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7295 	    "st_get_density(un = 0x%p)\n", (void*)un);
7296 
7297 	ASSERT(mutex_owned(ST_MUTEX));
7298 
7299 	/*
7300 	 * If Auto Density override is enabled The drive has
7301 	 * only one density and there is no point in attempting
7302 	 * find the correct one.
7303 	 *
7304 	 * Since most modern drives auto detect the density
7305 	 * and format of the recorded media before they come
7306 	 * ready. What this function does is a legacy behavior
7307 	 * and modern drives not only don't need it, The backup
7308 	 * utilities that do positioning via uscsi find the un-
7309 	 * expected rewinds problematic.
7310 	 *
7311 	 * The drives that need this are old reel to reel devices.
7312 	 * I took a swag and said they must be scsi-1 or older.
7313 	 * I don't beleave there will any of the newer devices
7314 	 * that need this. There will be some scsi-1 devices that
7315 	 * don't need this but I don't think they will be using the
7316 	 * BIG aftermarket backup and restore utilitys.
7317 	 */
7318 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
7319 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
7320 		un->un_density_known = 1;
7321 		rval = 0;
7322 		goto exit;
7323 	}
7324 
7325 	/*
7326 	 * This will only work on variable record length tapes
7327 	 * if and only if all variable record length tapes autodensity
7328 	 * select.
7329 	 */
7330 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
7331 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
7332 
7333 	/*
7334 	 * Start at the specified density
7335 	 */
7336 
7337 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
7338 
7339 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
7340 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
7341 		/*
7342 		 * If we've done this density before,
7343 		 * don't bother to do it again.
7344 		 */
7345 		dens = un->un_dp->densities[un->un_curdens];
7346 		if (i > 0 && dens == olddens)
7347 			continue;
7348 		olddens = dens;
7349 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7350 		    "trying density 0x%x\n", dens);
7351 		if (st_set_density(un)) {
7352 			continue;
7353 		}
7354 
7355 		/*
7356 		 * XXX - the creates lots of headaches and slowdowns - must
7357 		 * fix.
7358 		 */
7359 		succes = (st_cmd(un, SCMD_READ, (int)size, SYNC_CMD) == 0);
7360 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
7361 			break;
7362 		}
7363 		if (succes) {
7364 			st_init(un);
7365 			rval = 0;
7366 			un->un_density_known = 1;
7367 			break;
7368 		}
7369 	}
7370 	kmem_free(un->un_tmpbuf, size);
7371 	un->un_tmpbuf = 0;
7372 
7373 exit:
7374 	ASSERT(mutex_owned(ST_MUTEX));
7375 	return (rval);
7376 }
7377 
7378 static int
7379 st_set_density(struct scsi_tape *un)
7380 {
7381 	int rval = 0;
7382 
7383 	ST_FUNC(ST_DEVINFO, st_set_density);
7384 
7385 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7386 	    "st_set_density(un = 0x%p): density = 0x%x\n", (void*)un,
7387 	    un->un_dp->densities[un->un_curdens]);
7388 
7389 	ASSERT(mutex_owned(ST_MUTEX));
7390 
7391 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7392 
7393 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
7394 		/*
7395 		 * If auto density override is not set, Use mode select
7396 		 * to set density and compression.
7397 		 */
7398 		if (st_modeselect(un)) {
7399 			rval = -1;
7400 		}
7401 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
7402 		/*
7403 		 * If auto density and mode select compression are set,
7404 		 * This is a drive with one density code but compression
7405 		 * can be enabled or disabled.
7406 		 * Set compression but no need to set density.
7407 		 */
7408 		rval = st_set_compression(un);
7409 		if ((rval != 0) && (rval != EALREADY)) {
7410 			rval = -1;
7411 		} else {
7412 			rval = 0;
7413 		}
7414 	}
7415 
7416 	/* If sucessful set density and/or compression, mark density known */
7417 	if (rval == 0) {
7418 		un->un_density_known = 1;
7419 	}
7420 
7421 	ASSERT(mutex_owned(ST_MUTEX));
7422 	return (rval);
7423 }
7424 
7425 static int
7426 st_loadtape(struct scsi_tape *un)
7427 {
7428 	int rval;
7429 
7430 	ST_FUNC(ST_DEVINFO, st_loadtape);
7431 
7432 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7433 	    "st_loadtape(un = 0x%p)\n", (void*) un);
7434 
7435 	ASSERT(mutex_owned(ST_MUTEX));
7436 
7437 	rval = st_update_block_pos(un, st_cmd, 0);
7438 	if (rval == EACCES) {
7439 		return (rval);
7440 	}
7441 
7442 	/*
7443 	 * 'LOAD' the tape to BOT by rewinding
7444 	 */
7445 	rval = st_cmd(un, SCMD_REWIND, 1, SYNC_CMD);
7446 	if (rval == 0) {
7447 		st_init(un);
7448 		un->un_density_known = 0;
7449 	}
7450 
7451 	ASSERT(mutex_owned(ST_MUTEX));
7452 	return (rval);
7453 }
7454 
7455 
7456 /*
7457  * Note: QIC devices aren't so smart.  If you try to append
7458  * after EOM, the write can fail because the device doesn't know
7459  * it's at EOM.	 In that case, issue a read.  The read should fail
7460  * because there's no data, but the device knows it's at EOM,
7461  * so a subsequent write should succeed.  To further confuse matters,
7462  * the target returns the same error if the tape is positioned
7463  * such that a write would overwrite existing data.  That's why
7464  * we have to do the append test.  A read in the middle of
7465  * recorded data would succeed, thus indicating we're attempting
7466  * something illegal.
7467  */
7468 
7469 
7470 static void
7471 st_test_append(struct buf *bp)
7472 {
7473 	dev_t dev = bp->b_edev;
7474 	struct scsi_tape *un;
7475 	uchar_t status;
7476 	unsigned bcount;
7477 
7478 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7479 
7480 	ST_FUNC(ST_DEVINFO, st_test_append);
7481 
7482 	ASSERT(mutex_owned(ST_MUTEX));
7483 
7484 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7485 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7486 
7487 	un->un_laststate = un->un_state;
7488 	un->un_state = ST_STATE_APPEND_TESTING;
7489 	un->un_test_append = 0;
7490 
7491 	/*
7492 	 * first, map in the buffer, because we're doing a double write --
7493 	 * first into the kernel, then onto the tape.
7494 	 */
7495 	bp_mapin(bp);
7496 
7497 	/*
7498 	 * get a copy of the data....
7499 	 */
7500 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7501 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7502 
7503 	/*
7504 	 * attempt the write..
7505 	 */
7506 
7507 	if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7508 success:
7509 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7510 		    "append write succeeded\n");
7511 		bp->b_resid = un->un_sbufp->b_resid;
7512 		mutex_exit(ST_MUTEX);
7513 		bcount = (unsigned)bp->b_bcount;
7514 		biodone(bp);
7515 		mutex_enter(ST_MUTEX);
7516 		un->un_laststate = un->un_state;
7517 		un->un_state = ST_STATE_OPEN;
7518 		kmem_free(un->un_tmpbuf, bcount);
7519 		un->un_tmpbuf = NULL;
7520 		return;
7521 	}
7522 
7523 	/*
7524 	 * The append failed. Do a short read. If that fails,  we are at EOM
7525 	 * so we can retry the write command. If that succeeds, than we're
7526 	 * all screwed up (the controller reported a real error).
7527 	 *
7528 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7529 	 * XXX: block size?
7530 	 *
7531 	 */
7532 	status = un->un_status;
7533 	un->un_status = 0;
7534 	(void) st_cmd(un, SCMD_READ, SECSIZE, SYNC_CMD);
7535 	if (un->un_status == KEY_BLANK_CHECK) {
7536 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7537 		    "append at EOM\n");
7538 		/*
7539 		 * Okay- the read failed. We should actually have confused
7540 		 * the controller enough to allow writing. In any case, the
7541 		 * i/o is on its own from here on out.
7542 		 */
7543 		un->un_laststate = un->un_state;
7544 		un->un_state = ST_STATE_OPEN;
7545 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7546 		if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount,
7547 		    SYNC_CMD) == 0) {
7548 			goto success;
7549 		}
7550 	}
7551 
7552 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7553 	    "append write failed- not at EOM\n");
7554 	bp->b_resid = bp->b_bcount;
7555 	st_bioerror(bp, EIO);
7556 
7557 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7558 	    "st_test_append : EIO : append write failed - not at EOM");
7559 
7560 	/*
7561 	 * backspace one record to get back to where we were
7562 	 */
7563 	if (st_cmd(un, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7564 		un->un_pos.pmode = invalid;
7565 	}
7566 
7567 	un->un_err_resid = bp->b_resid;
7568 	un->un_status = status;
7569 
7570 	/*
7571 	 * Note: biodone will do a bp_mapout()
7572 	 */
7573 	mutex_exit(ST_MUTEX);
7574 	bcount = (unsigned)bp->b_bcount;
7575 	biodone(bp);
7576 	mutex_enter(ST_MUTEX);
7577 	un->un_laststate = un->un_state;
7578 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7579 	kmem_free(un->un_tmpbuf, bcount);
7580 	un->un_tmpbuf = NULL;
7581 }
7582 
7583 /*
7584  * Special command handler
7585  */
7586 
7587 /*
7588  * common st_cmd code. The fourth parameter states
7589  * whether the caller wishes to await the results
7590  * Note the release of the mutex during most of the function
7591  */
7592 static int
7593 st_cmd(struct scsi_tape *un, int com, int64_t count, int wait)
7594 {
7595 	struct buf *bp;
7596 	int err;
7597 	uint_t last_err_resid;
7598 
7599 	ST_FUNC(ST_DEVINFO, st_cmd);
7600 
7601 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7602 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %"PRIx64", wait = %d)\n",
7603 	    un->un_dev, com, count, wait);
7604 
7605 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7606 	ASSERT(mutex_owned(ST_MUTEX));
7607 
7608 #ifdef STDEBUG
7609 	if ((st_debug & 0x7)) {
7610 		st_debug_cmds(un, com, count, wait);
7611 	}
7612 #endif
7613 
7614 	st_wait_for_io(un);
7615 
7616 	/* check to see if this command requires the drive to be reserved */
7617 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7618 
7619 	if (err) {
7620 		return (err);
7621 	}
7622 
7623 	/*
7624 	 * A space command is not recoverable if we don't know were we
7625 	 * were when it was issued.
7626 	 */
7627 	if ((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) {
7628 		(void) st_update_block_pos(un, st_cmd, 0);
7629 	}
7630 
7631 	/*
7632 	 * Forground should not be doing anything while recovery is active.
7633 	 */
7634 	ASSERT(un->un_recov_buf_busy == 0);
7635 
7636 	while (un->un_sbuf_busy)
7637 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7638 	un->un_sbuf_busy = 1;
7639 
7640 	bp = un->un_sbufp;
7641 	bzero(bp, sizeof (buf_t));
7642 
7643 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7644 
7645 	err = st_setup_cmd(un, bp, com, count);
7646 
7647 	un->un_sbuf_busy = 0;
7648 
7649 	/*
7650 	 * If was a space command need to update logical block position.
7651 	 * Only do this if the command was sucessful or it will mask the fact
7652 	 * that the space command failed by promoting the pmode to logical.
7653 	 */
7654 	if (((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) &&
7655 	    (un->un_pos.pmode != invalid)) {
7656 		un->un_running.pmode = invalid;
7657 		last_err_resid = un->un_err_resid;
7658 		(void) st_update_block_pos(un, st_cmd, 1);
7659 		/*
7660 		 * Set running position to invalid so it updates on the
7661 		 * next command.
7662 		 */
7663 		un->un_running.pmode = invalid;
7664 		un->un_err_resid = last_err_resid;
7665 	}
7666 
7667 	cv_signal(&un->un_sbuf_cv);
7668 
7669 	return (err);
7670 }
7671 
7672 static int
7673 st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com, int64_t count)
7674 {
7675 	int err;
7676 	dev_t dev = un->un_dev;
7677 
7678 	ST_FUNC(ST_DEVINFO, st_setup_cmd);
7679 	/*
7680 	 * Set count to the actual size of the data tranfer.
7681 	 * For commands with no data transfer, set bp->b_bcount
7682 	 * to the value to be used when constructing the
7683 	 * cdb in st_make_cmd().
7684 	 */
7685 	switch (com) {
7686 	case SCMD_READ:
7687 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7688 		    "special read %"PRId64"\n", count);
7689 		bp->b_flags |= B_READ;
7690 		bp->b_un.b_addr = un->un_tmpbuf;
7691 		break;
7692 
7693 	case SCMD_WRITE:
7694 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7695 		    "special write %"PRId64"\n", count);
7696 		bp->b_un.b_addr = un->un_tmpbuf;
7697 		break;
7698 
7699 	case SCMD_WRITE_FILE_MARK:
7700 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7701 		    "write %"PRId64" file marks\n", count);
7702 		bp->b_bcount = count;
7703 		count = 0;
7704 		break;
7705 
7706 	case SCMD_REWIND:
7707 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7708 		bp->b_bcount = count;
7709 		count = 0;
7710 		break;
7711 
7712 	case SCMD_SPACE:
7713 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7714 		/*
7715 		 * If the user could have entered a number that will
7716 		 * not fit in the 12 bit count field of space(8),
7717 		 * use space(16).
7718 		 */
7719 		if (((int64_t)SPACE_CNT(count) > 0x7fffff) ||
7720 		    ((int64_t)SPACE_CNT(count) < -(0x7fffff))) {
7721 			com = SCMD_SPACE_G4;
7722 		}
7723 		bp->b_bcount = count;
7724 		count = 0;
7725 		break;
7726 
7727 	case SCMD_RESERVE:
7728 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7729 		bp->b_bcount = 0;
7730 		count = 0;
7731 		break;
7732 
7733 	case SCMD_RELEASE:
7734 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7735 		bp->b_bcount = 0;
7736 		count = 0;
7737 		break;
7738 
7739 	case SCMD_LOAD:
7740 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7741 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7742 		bp->b_bcount = count;
7743 		count = 0;
7744 		break;
7745 
7746 	case SCMD_ERASE:
7747 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7748 		    "erase tape\n");
7749 		bp->b_bcount = count;
7750 		count = 0;
7751 		break;
7752 
7753 	case SCMD_MODE_SENSE:
7754 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7755 		    "mode sense\n");
7756 		bp->b_flags |= B_READ;
7757 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7758 		break;
7759 
7760 	case SCMD_MODE_SELECT:
7761 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7762 		    "mode select\n");
7763 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7764 		break;
7765 
7766 	case SCMD_READ_BLKLIM:
7767 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7768 		    "read block limits\n");
7769 		bp->b_bcount = count;
7770 		bp->b_flags |= B_READ;
7771 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7772 		break;
7773 
7774 	case SCMD_TEST_UNIT_READY:
7775 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7776 		    "test unit ready\n");
7777 		bp->b_bcount = 0;
7778 		count = 0;
7779 		break;
7780 
7781 	case SCMD_DOORLOCK:
7782 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7783 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7784 		bp->b_bcount = count = 0;
7785 		break;
7786 
7787 	case SCMD_READ_POSITION:
7788 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7789 		    "read position\n");
7790 		switch (un->un_read_pos_type) {
7791 		case LONG_POS:
7792 			count = sizeof (tape_position_long_t);
7793 			break;
7794 		case EXT_POS:
7795 			count = min(count, sizeof (tape_position_ext_t));
7796 			break;
7797 		case SHORT_POS:
7798 			count = sizeof (tape_position_t);
7799 			break;
7800 		default:
7801 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7802 			    "Unknown read position type 0x%x in "
7803 			    "st_make_cmd()\n", un->un_read_pos_type);
7804 		}
7805 		bp->b_bcount = count;
7806 		bp->b_flags |= B_READ;
7807 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7808 		break;
7809 
7810 	default:
7811 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7812 		    "Unhandled scsi command 0x%x in st_setup_cmd()\n", com);
7813 	}
7814 
7815 	mutex_exit(ST_MUTEX);
7816 
7817 	if (count > 0) {
7818 		int flg = (bp->b_flags & B_READ) ? B_READ : B_WRITE;
7819 		/*
7820 		 * We're going to do actual I/O.
7821 		 * Set things up for physio.
7822 		 */
7823 		struct iovec aiov;
7824 		struct uio auio;
7825 		struct uio *uio = &auio;
7826 
7827 		bzero(&auio, sizeof (struct uio));
7828 		bzero(&aiov, sizeof (struct iovec));
7829 		aiov.iov_base = bp->b_un.b_addr;
7830 		aiov.iov_len = count;
7831 
7832 		uio->uio_iov = &aiov;
7833 		uio->uio_iovcnt = 1;
7834 		uio->uio_resid = aiov.iov_len;
7835 		uio->uio_segflg = UIO_SYSSPACE;
7836 
7837 		/*
7838 		 * Let physio do the rest...
7839 		 */
7840 		bp->b_forw = (struct buf *)(uintptr_t)com;
7841 		bp->b_back = NULL;
7842 		err = physio(st_strategy, bp, dev, flg, st_minphys, uio);
7843 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7844 		    "st_setup_cmd: physio returns %d\n", err);
7845 	} else {
7846 		/*
7847 		 * Mimic physio
7848 		 */
7849 		bp->b_forw = (struct buf *)(uintptr_t)com;
7850 		bp->b_back = NULL;
7851 		bp->b_edev = dev;
7852 		bp->b_dev = cmpdev(dev);
7853 		bp->b_blkno = 0;
7854 		bp->b_resid = 0;
7855 		(void) st_strategy(bp);
7856 		if (bp->b_flags & B_ASYNC) {
7857 			/*
7858 			 * This is an async command- the caller won't wait
7859 			 * and doesn't care about errors.
7860 			 */
7861 			mutex_enter(ST_MUTEX);
7862 			return (0);
7863 		}
7864 
7865 		/*
7866 		 * BugTraq #4260046
7867 		 * ----------------
7868 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7869 		 * unconditionally. The old comment said...
7870 		 *
7871 		 * "if strategy was flagged with  persistent errors, we would
7872 		 *  have an error here, and the bp would never be sent, so we
7873 		 *  don't want to wait on a bp that was never sent...or hang"
7874 		 *
7875 		 * The new rationale, courtesy of Chitrank...
7876 		 *
7877 		 * "we should unconditionally biowait() here because
7878 		 *  st_strategy() will do a biodone() in the persistent error
7879 		 *  case and the following biowait() will return immediately.
7880 		 *  If not, in the case of "errors after pkt alloc" in
7881 		 *  st_start(), we will not biowait here which will cause the
7882 		 *  next biowait() to return immediately which will cause
7883 		 *  us to send out the next command. In the case where both of
7884 		 *  these use the sbuf, when the first command completes we'll
7885 		 *  free the packet attached to sbuf and the same pkt will
7886 		 *  get freed again when we complete the second command.
7887 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7888 		 *  st_start() for the pkt alloc failure case because physio()
7889 		 *  does biowait() and will hang if we don't do biodone()"
7890 		 */
7891 
7892 		err = biowait(bp);
7893 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7894 		    "st_setup_cmd: biowait returns %d\n", err);
7895 	}
7896 
7897 	mutex_enter(ST_MUTEX);
7898 
7899 	return (err);
7900 }
7901 
7902 static int
7903 st_set_compression(struct scsi_tape *un)
7904 {
7905 	int rval;
7906 	int turn_compression_on;
7907 	minor_t minor;
7908 
7909 	ST_FUNC(ST_DEVINFO, st_set_compression);
7910 
7911 	/*
7912 	 * Drive either dosn't have compression or it is controlled with
7913 	 * special density codes. Return ENOTTY so caller
7914 	 * knows nothing was done.
7915 	 */
7916 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7917 		un->un_comp_page = 0;
7918 		return (ENOTTY);
7919 	}
7920 
7921 	/* set compression based on minor node opened */
7922 	minor = MT_DENSITY(un->un_dev);
7923 
7924 	/*
7925 	 * If this the compression density or
7926 	 * the drive has two densities and uses mode select for
7927 	 * control of compression turn on compression for MT_DENSITY2
7928 	 * as well.
7929 	 */
7930 	if ((minor == ST_COMPRESSION_DENSITY) ||
7931 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7932 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7933 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7934 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7935 
7936 		turn_compression_on = 1;
7937 	} else {
7938 		turn_compression_on = 0;
7939 	}
7940 
7941 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7942 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7943 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7944 
7945 	/*
7946 	 * Need to determine which page does the device use for compression.
7947 	 * First try the data compression page. If this fails try the device
7948 	 * configuration page
7949 	 */
7950 
7951 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7952 		rval = st_set_datacomp_page(un, turn_compression_on);
7953 		if (rval == EALREADY) {
7954 			return (rval);
7955 		}
7956 		if (rval != 0) {
7957 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7958 				/*
7959 				 * This device does not support data
7960 				 * compression page
7961 				 */
7962 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7963 			} else if (un->un_state >= ST_STATE_OPEN) {
7964 				un->un_pos.pmode = invalid;
7965 				rval = EIO;
7966 			} else {
7967 				rval = -1;
7968 			}
7969 		} else {
7970 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7971 		}
7972 	}
7973 
7974 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7975 		rval = st_set_devconfig_page(un, turn_compression_on);
7976 		if (rval == EALREADY) {
7977 			return (rval);
7978 		}
7979 		if (rval != 0) {
7980 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7981 				/*
7982 				 * This device does not support
7983 				 * compression at all advice the
7984 				 * user and unset ST_MODE_SEL_COMP
7985 				 */
7986 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7987 				un->un_comp_page = 0;
7988 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7989 				    "Device Does Not Support Compression\n");
7990 			} else if (un->un_state >= ST_STATE_OPEN) {
7991 				un->un_pos.pmode = invalid;
7992 				rval = EIO;
7993 			} else {
7994 				rval = -1;
7995 			}
7996 		}
7997 	}
7998 
7999 	return (rval);
8000 }
8001 
8002 /*
8003  * set or unset compression thru device configuration page.
8004  */
8005 static int
8006 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
8007 {
8008 	unsigned char cflag;
8009 	int rval = 0;
8010 
8011 
8012 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
8013 
8014 	ASSERT(mutex_owned(ST_MUTEX));
8015 
8016 	/*
8017 	 * if the mode sense page is not the correct one, load the correct one.
8018 	 */
8019 	if (un->un_mspl->page_code != ST_DEV_CONFIG_PAGE) {
8020 		rval = st_gen_mode_sense(un, st_uscsi_cmd, ST_DEV_CONFIG_PAGE,
8021 		    un->un_mspl, sizeof (struct seq_mode));
8022 		if (rval)
8023 			return (rval);
8024 	}
8025 
8026 	/*
8027 	 * Figure what to set compression flag to.
8028 	 */
8029 	if (compression_on) {
8030 		/* They have selected a compression node */
8031 		if (un->un_dp->type == ST_TYPE_FUJI) {
8032 			cflag = 0x84;   /* use EDRC */
8033 		} else {
8034 			cflag = ST_DEV_CONFIG_DEF_COMP;
8035 		}
8036 	} else {
8037 		cflag = ST_DEV_CONFIG_NO_COMP;
8038 	}
8039 
8040 	/*
8041 	 * If compression is already set the way it was requested.
8042 	 * And if this not the first time we has tried.
8043 	 */
8044 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
8045 	    (un->un_comp_page == ST_DEV_CONFIG_PAGE)) {
8046 		return (EALREADY);
8047 	}
8048 
8049 	un->un_mspl->page.dev.comp_alg = cflag;
8050 	/*
8051 	 * need to send mode select even if correct compression is
8052 	 * already set since need to set density code
8053 	 */
8054 
8055 #ifdef STDEBUG
8056 	if ((st_debug & 0x7) >= 6) {
8057 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8058 		    "st_set_devconfig_page: sense data for mode select",
8059 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8060 	}
8061 #endif
8062 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8063 	    sizeof (struct seq_mode));
8064 
8065 	return (rval);
8066 }
8067 
8068 /*
8069  * set/reset compression bit thru data compression page
8070  */
8071 static int
8072 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
8073 {
8074 	int compression_on_already;
8075 	int rval = 0;
8076 
8077 
8078 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
8079 
8080 	ASSERT(mutex_owned(ST_MUTEX));
8081 
8082 	/*
8083 	 * if the mode sense page is not the correct one, load the correct one.
8084 	 */
8085 	if (un->un_mspl->page_code != ST_DEV_DATACOMP_PAGE) {
8086 		rval = st_gen_mode_sense(un, st_uscsi_cmd, ST_DEV_DATACOMP_PAGE,
8087 		    un->un_mspl, sizeof (struct seq_mode));
8088 		if (rval)
8089 			return (rval);
8090 	}
8091 
8092 	/*
8093 	 * If drive is not capable of compression (at this time)
8094 	 * return EALREADY so caller doesn't think that this page
8095 	 * is not supported. This check is for drives that can
8096 	 * disable compression from the front panel or configuration.
8097 	 * I doubt that a drive that supports this page is not really
8098 	 * capable of compression.
8099 	 */
8100 	if (un->un_mspl->page.comp.dcc == 0) {
8101 		return (EALREADY);
8102 	}
8103 
8104 	/* See if compression currently turned on */
8105 	if (un->un_mspl->page.comp.dce) {
8106 		compression_on_already = 1;
8107 	} else {
8108 		compression_on_already = 0;
8109 	}
8110 
8111 	/*
8112 	 * If compression is already set the way it was requested.
8113 	 * And if this not the first time we has tried.
8114 	 */
8115 	if ((compression_on == compression_on_already) &&
8116 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
8117 		return (EALREADY);
8118 	}
8119 
8120 	/*
8121 	 * if we are already set to the appropriate compression
8122 	 * mode, don't set it again
8123 	 */
8124 	if (compression_on) {
8125 		/* compression selected */
8126 		un->un_mspl->page.comp.dce = 1;
8127 	} else {
8128 		un->un_mspl->page.comp.dce = 0;
8129 	}
8130 
8131 
8132 #ifdef STDEBUG
8133 	if ((st_debug & 0x7) >= 6) {
8134 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8135 		    "st_set_datacomp_page: sense data for mode select",
8136 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8137 	}
8138 #endif
8139 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8140 	    sizeof (struct seq_mode));
8141 
8142 	return (rval);
8143 }
8144 
8145 static int
8146 st_modesense(struct scsi_tape *un)
8147 {
8148 	int rval;
8149 	uchar_t page;
8150 
8151 	ST_FUNC(ST_DEVINFO, st_modesense);
8152 
8153 	page = un->un_comp_page;
8154 
8155 	switch (page) {
8156 	case ST_DEV_DATACOMP_PAGE:
8157 	case ST_DEV_CONFIG_PAGE: /* FALLTHROUGH */
8158 		rval = st_gen_mode_sense(un, st_uscsi_cmd, page, un->un_mspl,
8159 		    sizeof (struct seq_mode));
8160 		break;
8161 
8162 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
8163 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
8164 			page = ST_DEV_DATACOMP_PAGE;
8165 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8166 			    un->un_mspl, sizeof (struct seq_mode));
8167 			if (rval == 0 && un->un_mspl->page_code == page) {
8168 				un->un_comp_page = page;
8169 				break;
8170 			}
8171 			page = ST_DEV_CONFIG_PAGE;
8172 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8173 			    un->un_mspl, sizeof (struct seq_mode));
8174 			if (rval == 0 && un->un_mspl->page_code == page) {
8175 				un->un_comp_page = page;
8176 				break;
8177 			}
8178 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
8179 			un->un_comp_page = 0;
8180 		} else {
8181 			un->un_comp_page = 0;
8182 		}
8183 
8184 	default:	/* FALLTHROUGH */
8185 		rval = st_cmd(un, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
8186 	}
8187 	return (rval);
8188 }
8189 
8190 static int
8191 st_modeselect(struct scsi_tape *un)
8192 {
8193 	int rval = 0;
8194 	int ix;
8195 
8196 	ST_FUNC(ST_DEVINFO, st_modeselect);
8197 
8198 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8199 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
8200 	    un->un_dev, un->un_mspl->density);
8201 
8202 	ASSERT(mutex_owned(ST_MUTEX));
8203 
8204 	/*
8205 	 * The parameter list should be the same for all of the
8206 	 * cases that follow so set them here
8207 	 *
8208 	 * Try mode select first if if fails set fields manually
8209 	 */
8210 	rval = st_modesense(un);
8211 	if (rval != 0) {
8212 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8213 		    "st_modeselect: First mode sense failed\n");
8214 		un->un_mspl->bd_len  = 8;
8215 		un->un_mspl->high_nb = 0;
8216 		un->un_mspl->mid_nb  = 0;
8217 		un->un_mspl->low_nb  = 0;
8218 	}
8219 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
8220 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
8221 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
8222 
8223 
8224 	/*
8225 	 * If configured to use a specific density code for a media type.
8226 	 * curdens is previously set by the minor node opened.
8227 	 * If the media type doesn't match the minor node we change it so it
8228 	 * looks like the correct one was opened.
8229 	 */
8230 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
8231 		uchar_t best;
8232 
8233 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
8234 			if (un->un_mspl->media_type ==
8235 			    un->un_dp->mediatype[ix]) {
8236 				best = ix;
8237 				/*
8238 				 * It matches but it might not be the only one.
8239 				 * Use the highest matching media type but not
8240 				 * to exceed the density selected by the open.
8241 				 */
8242 				if (ix < un->un_curdens) {
8243 					continue;
8244 				}
8245 				un->un_curdens = ix;
8246 				break;
8247 			}
8248 		}
8249 		/* If a match was found best will not be 0xff any more */
8250 		if (best < NDENSITIES) {
8251 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8252 			    "found media 0x%X using density 0x%X\n",
8253 			    un->un_mspl->media_type,
8254 			    un->un_dp->densities[best]);
8255 			un->un_mspl->density = un->un_dp->densities[best];
8256 		} else {
8257 			/* Otherwise set density based on minor node opened */
8258 			un->un_mspl->density =
8259 			    un->un_dp->densities[un->un_curdens];
8260 		}
8261 	} else {
8262 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
8263 	}
8264 
8265 	if (un->un_dp->options & ST_NOBUF) {
8266 		un->un_mspl->bufm = 0;
8267 	} else {
8268 		un->un_mspl->bufm = 1;
8269 	}
8270 
8271 	rval = st_set_compression(un);
8272 
8273 	/*
8274 	 * If st_set_compression returned invalid or already it
8275 	 * found no need to do the mode select.
8276 	 * So do it here.
8277 	 */
8278 	if ((rval == ENOTTY) || (rval == EALREADY)) {
8279 
8280 		/* Zero non-writeable fields */
8281 		un->un_mspl->data_len = 0;
8282 		un->un_mspl->media_type = 0;
8283 		un->un_mspl->wp = 0;
8284 
8285 		/* need to set the density code */
8286 		rval = st_cmd(un, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
8287 		if (rval != 0) {
8288 			if (un->un_state >= ST_STATE_OPEN) {
8289 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8290 				    "unable to set tape mode\n");
8291 				un->un_pos.pmode = invalid;
8292 				rval = EIO;
8293 			} else {
8294 				rval = -1;
8295 			}
8296 		}
8297 	}
8298 
8299 	/*
8300 	 * The spec recommends to send a mode sense after a mode select
8301 	 */
8302 	(void) st_modesense(un);
8303 
8304 	ASSERT(mutex_owned(ST_MUTEX));
8305 
8306 	return (rval);
8307 }
8308 
8309 /*
8310  * st_gen_mode_sense
8311  *
8312  * generic mode sense.. it allows for any page
8313  */
8314 static int
8315 st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
8316     struct seq_mode *page_data, int page_size)
8317 {
8318 
8319 	int r;
8320 	char	cdb[CDB_GROUP0];
8321 	struct uscsi_cmd *com;
8322 	struct scsi_arq_status status;
8323 
8324 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
8325 
8326 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8327 
8328 	bzero(cdb, CDB_GROUP0);
8329 	cdb[0] = SCMD_MODE_SENSE;
8330 	cdb[2] = (char)page;
8331 	cdb[4] = (char)page_size;
8332 
8333 	com->uscsi_cdb = cdb;
8334 	com->uscsi_cdblen = CDB_GROUP0;
8335 	com->uscsi_bufaddr = (caddr_t)page_data;
8336 	com->uscsi_buflen = page_size;
8337 	com->uscsi_rqlen = sizeof (status);
8338 	com->uscsi_rqbuf = (caddr_t)&status;
8339 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8340 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8341 
8342 	r = ubf(un, com, FKIOCTL);
8343 	kmem_free(com, sizeof (*com));
8344 	return (r);
8345 }
8346 
8347 /*
8348  * st_gen_mode_select
8349  *
8350  * generic mode select.. it allows for any page
8351  */
8352 static int
8353 st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
8354     struct seq_mode *page_data, int page_size)
8355 {
8356 
8357 	int r;
8358 	char cdb[CDB_GROUP0];
8359 	struct uscsi_cmd *com;
8360 	struct scsi_arq_status status;
8361 
8362 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
8363 
8364 	/* Zero non-writeable fields */
8365 	page_data->data_len = 0;
8366 	page_data->media_type = 0;
8367 	page_data->wp = 0;
8368 
8369 	/*
8370 	 * If mode select has any page data, zero the ps (Page Savable) bit.
8371 	 */
8372 	if (page_size > MSIZE) {
8373 		page_data->ps = 0;
8374 	}
8375 
8376 
8377 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8378 
8379 	/*
8380 	 * then, do a mode select to set what ever info
8381 	 */
8382 	bzero(cdb, CDB_GROUP0);
8383 	cdb[0] = SCMD_MODE_SELECT;
8384 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
8385 	cdb[4] = (char)page_size;
8386 
8387 	com->uscsi_cdb = cdb;
8388 	com->uscsi_cdblen = CDB_GROUP0;
8389 	com->uscsi_bufaddr = (caddr_t)page_data;
8390 	com->uscsi_buflen = page_size;
8391 	com->uscsi_rqlen = sizeof (status);
8392 	com->uscsi_rqbuf = (caddr_t)&status;
8393 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8394 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_WRITE;
8395 
8396 	r = ubf(un, com, FKIOCTL);
8397 
8398 	kmem_free(com, sizeof (*com));
8399 	return (r);
8400 }
8401 
8402 static int
8403 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
8404 {
8405 	int rval;
8406 	char cdb[CDB_GROUP0];
8407 	struct uscsi_cmd *com;
8408 	struct scsi_arq_status status;
8409 
8410 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
8411 
8412 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8413 
8414 	bzero(cdb, CDB_GROUP0);
8415 	cdb[0] = SCMD_READ_BLKLIM;
8416 
8417 	com->uscsi_cdb = cdb;
8418 	com->uscsi_cdblen = CDB_GROUP0;
8419 	com->uscsi_bufaddr = (caddr_t)read_blk;
8420 	com->uscsi_buflen = sizeof (struct read_blklim);
8421 	com->uscsi_rqlen = sizeof (status);
8422 	com->uscsi_rqbuf = (caddr_t)&status;
8423 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8424 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8425 
8426 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8427 	if (com->uscsi_status || com->uscsi_resid) {
8428 		rval = -1;
8429 	}
8430 
8431 	kmem_free(com, sizeof (*com));
8432 	return (rval);
8433 }
8434 
8435 static int
8436 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
8437     size_t buflen)
8438 {
8439 	int rval;
8440 	char cdb[CDB_GROUP1];
8441 	struct uscsi_cmd *com;
8442 	struct scsi_arq_status status;
8443 
8444 	ST_FUNC(ST_DEVINFO, st_report_density_support);
8445 
8446 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8447 
8448 	bzero(cdb, CDB_GROUP1);
8449 	cdb[0] = SCMD_REPORT_DENSITIES;
8450 	cdb[7] = (buflen & 0xff00) >> 8;
8451 	cdb[8] = buflen & 0xff;
8452 
8453 	com->uscsi_cdb = cdb;
8454 	com->uscsi_cdblen = CDB_GROUP1;
8455 	com->uscsi_bufaddr = (caddr_t)density_data;
8456 	com->uscsi_buflen = buflen;
8457 	com->uscsi_rqlen = sizeof (status);
8458 	com->uscsi_rqbuf = (caddr_t)&status;
8459 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8460 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8461 
8462 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8463 	if (com->uscsi_status || com->uscsi_resid) {
8464 		rval = -1;
8465 	}
8466 
8467 	kmem_free(com, sizeof (*com));
8468 	return (rval);
8469 }
8470 
8471 static int
8472 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
8473     uchar_t option_code, ushort_t service_action)
8474 {
8475 	int rval;
8476 	char cdb[CDB_GROUP5];
8477 	struct uscsi_cmd *com;
8478 	struct scsi_arq_status status;
8479 	uint32_t allo_length;
8480 
8481 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
8482 
8483 	allo_length = sizeof (struct one_com_des) +
8484 	    sizeof (struct com_timeout_des);
8485 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8486 
8487 	bzero(cdb, CDB_GROUP5);
8488 	cdb[0] = (char)SCMD_MAINTENANCE_IN;
8489 	cdb[1] = SSVC_ACTION_GET_SUPPORTED_OPERATIONS;
8490 	if (service_action) {
8491 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
8492 		cdb[4] = (service_action & 0xff00) >> 8;
8493 		cdb[5] = service_action & 0xff;
8494 	} else {
8495 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
8496 		    0x80); /* RCTD */
8497 	}
8498 	cdb[3] = option_code;
8499 	cdb[6] = (allo_length & 0xff000000) >> 24;
8500 	cdb[7] = (allo_length & 0xff0000) >> 16;
8501 	cdb[8] = (allo_length & 0xff00) >> 8;
8502 	cdb[9] = allo_length & 0xff;
8503 
8504 	com->uscsi_cdb = cdb;
8505 	com->uscsi_cdblen = CDB_GROUP5;
8506 	com->uscsi_bufaddr = (caddr_t)oper_data;
8507 	com->uscsi_buflen = allo_length;
8508 	com->uscsi_rqlen = sizeof (status);
8509 	com->uscsi_rqbuf = (caddr_t)&status;
8510 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8511 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8512 
8513 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8514 	if (com->uscsi_status) {
8515 		rval = -1;
8516 	}
8517 
8518 	kmem_free(com, sizeof (*com));
8519 	return (rval);
8520 }
8521 
8522 /*
8523  * Changes devices blocksize and bsize to requested blocksize nblksz.
8524  * Returns returned value from first failed call or zero on success.
8525  */
8526 static int
8527 st_change_block_size(struct scsi_tape *un, uint32_t nblksz)
8528 {
8529 	struct seq_mode *current;
8530 	int rval;
8531 	uint32_t oldblksz;
8532 
8533 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8534 
8535 	current = kmem_zalloc(MSIZE, KM_SLEEP);
8536 
8537 	/*
8538 	 * If we haven't got the compression page yet, do that first.
8539 	 */
8540 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
8541 		(void) st_modesense(un);
8542 	}
8543 
8544 	/* Read current settings */
8545 	rval = st_gen_mode_sense(un, st_uscsi_cmd, 0, current, MSIZE);
8546 	if (rval != 0) {
8547 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8548 		    "mode sense for change block size failed: rval = %d", rval);
8549 		goto finish;
8550 	}
8551 
8552 	/* Figure the current block size */
8553 	oldblksz =
8554 	    (current->high_bl << 16) |
8555 	    (current->mid_bl << 8) |
8556 	    (current->low_bl);
8557 
8558 	/* If current block size is the same as requested were done */
8559 	if (oldblksz == nblksz) {
8560 		un->un_bsize = nblksz;
8561 		rval = 0;
8562 		goto finish;
8563 	}
8564 
8565 	/* Change to requested block size */
8566 	current->high_bl = (uchar_t)(nblksz >> 16);
8567 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8568 	current->low_bl  = (uchar_t)(nblksz);
8569 
8570 	/* Attempt to change block size */
8571 	rval = st_gen_mode_select(un, st_uscsi_cmd, current, MSIZE);
8572 	if (rval != 0) {
8573 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8574 		    "Set new block size failed: rval = %d", rval);
8575 		goto finish;
8576 	}
8577 
8578 	/* Read back and verify setting */
8579 	rval = st_modesense(un);
8580 	if (rval == 0) {
8581 		un->un_bsize =
8582 		    (un->un_mspl->high_bl << 16) |
8583 		    (un->un_mspl->mid_bl << 8) |
8584 		    (un->un_mspl->low_bl);
8585 
8586 		if (un->un_bsize != nblksz) {
8587 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8588 			    "Blocksize set does not equal requested blocksize"
8589 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8590 			rval = EIO;
8591 		}
8592 	}
8593 finish:
8594 	kmem_free(current, MSIZE);
8595 	return (rval);
8596 }
8597 
8598 
8599 static void
8600 st_init(struct scsi_tape *un)
8601 {
8602 	ST_FUNC(ST_DEVINFO, st_init);
8603 
8604 	ASSERT(mutex_owned(ST_MUTEX));
8605 
8606 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8607 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8608 	    un->un_dev);
8609 
8610 	un->un_pos.blkno = 0;
8611 	un->un_pos.fileno = 0;
8612 	un->un_lastop = ST_OP_NIL;
8613 	un->un_pos.eof = ST_NO_EOF;
8614 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8615 	if (st_error_level != SCSI_ERR_ALL) {
8616 		if (DEBUGGING) {
8617 			st_error_level = SCSI_ERR_ALL;
8618 		} else {
8619 			st_error_level = SCSI_ERR_RETRYABLE;
8620 		}
8621 	}
8622 }
8623 
8624 
8625 static void
8626 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8627 {
8628 	struct scsi_pkt *pkt;
8629 	struct uscsi_cmd *ucmd;
8630 	recov_info *ri;
8631 	int tval = 0;
8632 	int64_t count;
8633 	uint32_t additional = 0;
8634 	uint32_t address = 0;
8635 	union scsi_cdb *ucdb;
8636 	int flags = 0;
8637 	int cdb_len = CDB_GROUP0; /* default */
8638 	uchar_t com;
8639 	char fixbit;
8640 	char short_fm = 0;
8641 	optype prev_op = un->un_lastop;
8642 	int stat_size =
8643 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
8644 
8645 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8646 
8647 	ASSERT(mutex_owned(ST_MUTEX));
8648 
8649 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8650 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8651 
8652 
8653 	/*
8654 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8655 	 * Length Indicator bits on read/write commands, for setting
8656 	 * the Long bit on erase commands, and for setting the Code
8657 	 * Field bits on space commands.
8658 	 */
8659 
8660 	/* regular raw I/O */
8661 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
8662 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8663 		    CDB_GROUP0, stat_size, st_recov_sz, 0, func,
8664 		    (caddr_t)un);
8665 		if (pkt == NULL) {
8666 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8667 			    "Read Write scsi_init_pkt() failure\n");
8668 			goto exit;
8669 		}
8670 		ASSERT(pkt->pkt_resid == 0);
8671 #ifdef STDEBUG
8672 		bzero(pkt->pkt_private, st_recov_sz);
8673 		bzero(pkt->pkt_scbp, stat_size);
8674 #endif
8675 		ri = (recov_info *)pkt->pkt_private;
8676 		ri->privatelen = st_recov_sz;
8677 		if (un->un_bsize == 0) {
8678 			count = bp->b_bcount;
8679 			fixbit = 0;
8680 		} else {
8681 			count = bp->b_bcount / un->un_bsize;
8682 			fixbit = 1;
8683 		}
8684 		if (bp->b_flags & B_READ) {
8685 			com = SCMD_READ;
8686 			un->un_lastop = ST_OP_READ;
8687 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8688 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8689 				fixbit = 2;
8690 			}
8691 		} else {
8692 			com = SCMD_WRITE;
8693 			un->un_lastop = ST_OP_WRITE;
8694 		}
8695 		tval = un->un_dp->io_timeout;
8696 
8697 		/*
8698 		 * For really large xfers, increase timeout
8699 		 */
8700 		if (bp->b_bcount > (10 * ONE_MEG))
8701 			tval *= bp->b_bcount/(10 * ONE_MEG);
8702 
8703 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8704 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8705 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8706 
8707 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8708 		/*
8709 		 * uscsi - build command, allocate scsi resources
8710 		 */
8711 		st_make_uscsi_cmd(un, ucmd, bp, func);
8712 		goto exit;
8713 
8714 	} else {				/* special I/O */
8715 		struct buf *allocbp = NULL;
8716 		com = (uchar_t)(uintptr_t)bp->b_forw;
8717 		count = bp->b_bcount;
8718 
8719 		switch (com) {
8720 		case SCMD_READ:
8721 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8722 			    "special read %"PRId64"\n", count);
8723 			if (un->un_bsize == 0) {
8724 				fixbit = 2;	/* suppress SILI */
8725 			} else {
8726 				fixbit = 1;	/* Fixed Block Mode */
8727 				count /= un->un_bsize;
8728 			}
8729 			allocbp = bp;
8730 			un->un_lastop = ST_OP_READ;
8731 			tval = un->un_dp->io_timeout;
8732 			break;
8733 
8734 		case SCMD_WRITE:
8735 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8736 			    "special write %"PRId64"\n", count);
8737 			if (un->un_bsize != 0) {
8738 				fixbit = 1;	/* Fixed Block Mode */
8739 				count /= un->un_bsize;
8740 			} else {
8741 				fixbit = 0;
8742 			}
8743 			allocbp = bp;
8744 			un->un_lastop = ST_OP_WRITE;
8745 			tval = un->un_dp->io_timeout;
8746 			break;
8747 
8748 		case SCMD_WRITE_FILE_MARK:
8749 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8750 			    "write %"PRId64" file marks\n", count);
8751 			un->un_lastop = ST_OP_WEOF;
8752 			fixbit = 0;
8753 			tval = un->un_dp->io_timeout;
8754 			/*
8755 			 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8756 			 * device, set the Vendor Unique bit to
8757 			 * write Short File Mark.
8758 			 */
8759 			if ((un->un_dp->options & ST_SHORT_FILEMARKS) &&
8760 			    ((un->un_dp->type == ST_TYPE_EXB8500) ||
8761 			    (un->un_dp->type == ST_TYPE_EXABYTE))) {
8762 				/*
8763 				 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8764 				 * is set to to write Short File Mark
8765 				 */
8766 				short_fm = 1;
8767 			}
8768 			break;
8769 
8770 		case SCMD_REWIND:
8771 			/*
8772 			 * In the case of rewind we're gona do the rewind with
8773 			 * the immediate bit set so status will be retured when
8774 			 * the command is accepted by the device. We clear the
8775 			 * B_ASYNC flag so we wait for that acceptance.
8776 			 */
8777 			fixbit = 0;
8778 			if (bp->b_flags & B_ASYNC) {
8779 				allocbp = bp;
8780 				if (count) {
8781 					fixbit = 1;
8782 					bp->b_flags &= ~B_ASYNC;
8783 				}
8784 			}
8785 			count = 0;
8786 			bp->b_bcount = 0;
8787 			un->un_lastop = ST_OP_CTL;
8788 			tval = un->un_dp->rewind_timeout;
8789 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8790 			    "rewind\n");
8791 			break;
8792 
8793 		case SCMD_SPACE_G4:
8794 			cdb_len = CDB_GROUP4;
8795 			fixbit = SPACE_TYPE(bp->b_bcount);
8796 			count = SPACE_CNT(bp->b_bcount);
8797 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8798 			    " %s space %s %"PRId64" from file %d blk %d\n",
8799 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8800 			    space_strs[fixbit & 7], count,
8801 			    un->un_pos.fileno, un->un_pos.blkno);
8802 			address = (count >> 48) & 0x1fff;
8803 			additional = (count >> 16) & 0xffffffff;
8804 			count &= 0xffff;
8805 			count <<= 16;
8806 			un->un_lastop = ST_OP_CTL;
8807 			tval = un->un_dp->space_timeout;
8808 			break;
8809 
8810 		case SCMD_SPACE:
8811 			fixbit = SPACE_TYPE(bp->b_bcount);
8812 			count = SPACE_CNT(bp->b_bcount);
8813 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8814 			    " %s space %s %"PRId64" from file %d blk %d\n",
8815 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8816 			    space_strs[fixbit & 7], count,
8817 			    un->un_pos.fileno, un->un_pos.blkno);
8818 			count &= 0xffffffff;
8819 			un->un_lastop = ST_OP_CTL;
8820 			tval = un->un_dp->space_timeout;
8821 			break;
8822 
8823 		case SCMD_LOAD:
8824 			ASSERT(count < 10);
8825 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8826 			    "%s tape\n", load_strs[count]);
8827 			fixbit = 0;
8828 
8829 			/* Loading or Unloading */
8830 			if (count & LD_LOAD) {
8831 				tval = un->un_dp->load_timeout;
8832 			} else {
8833 				tval = un->un_dp->unload_timeout;
8834 			}
8835 			/* Is Retension requested */
8836 			if (count & LD_RETEN) {
8837 				tval += un->un_dp->rewind_timeout;
8838 			}
8839 			un->un_lastop = ST_OP_CTL;
8840 			break;
8841 
8842 		case SCMD_ERASE:
8843 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8844 			    "erase tape\n");
8845 			ASSERT(count == 1); /* mt sets this */
8846 			if (count == 1) {
8847 				/*
8848 				 * do long erase
8849 				 */
8850 				fixbit = 1; /* Long */
8851 
8852 				/* Drive might not honor immidiate bit */
8853 				tval = un->un_dp->erase_timeout;
8854 			} else {
8855 				/* Short Erase */
8856 				tval = un->un_dp->erase_timeout;
8857 				fixbit = 0;
8858 			}
8859 			un->un_lastop = ST_OP_CTL;
8860 			count = 0;
8861 			break;
8862 
8863 		case SCMD_MODE_SENSE:
8864 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8865 			    "mode sense\n");
8866 			allocbp = bp;
8867 			fixbit = 0;
8868 			tval = un->un_dp->non_motion_timeout;
8869 			un->un_lastop = ST_OP_CTL;
8870 			break;
8871 
8872 		case SCMD_MODE_SELECT:
8873 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8874 			    "mode select\n");
8875 			allocbp = bp;
8876 			fixbit = 0;
8877 			tval = un->un_dp->non_motion_timeout;
8878 			un->un_lastop = ST_OP_CTL;
8879 			break;
8880 
8881 		case SCMD_RESERVE:
8882 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8883 			    "reserve\n");
8884 			fixbit = 0;
8885 			tval = un->un_dp->non_motion_timeout;
8886 			un->un_lastop = ST_OP_CTL;
8887 			break;
8888 
8889 		case SCMD_RELEASE:
8890 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8891 			    "release\n");
8892 			fixbit = 0;
8893 			tval = un->un_dp->non_motion_timeout;
8894 			un->un_lastop = ST_OP_CTL;
8895 			break;
8896 
8897 		case SCMD_READ_BLKLIM:
8898 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8899 			    "read block limits\n");
8900 			allocbp = bp;
8901 			fixbit = count = 0;
8902 			tval = un->un_dp->non_motion_timeout;
8903 			un->un_lastop = ST_OP_CTL;
8904 			break;
8905 
8906 		case SCMD_TEST_UNIT_READY:
8907 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8908 			    "test unit ready\n");
8909 			fixbit = 0;
8910 			tval = un->un_dp->non_motion_timeout;
8911 			un->un_lastop = ST_OP_CTL;
8912 			break;
8913 
8914 		case SCMD_DOORLOCK:
8915 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8916 			    "prevent/allow media removal\n");
8917 			fixbit = 0;
8918 			tval = un->un_dp->non_motion_timeout;
8919 			un->un_lastop = ST_OP_CTL;
8920 			break;
8921 
8922 		case SCMD_READ_POSITION:
8923 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8924 			    "read position\n");
8925 			fixbit = un->un_read_pos_type;
8926 			cdb_len = CDB_GROUP1;
8927 			tval = un->un_dp->non_motion_timeout;
8928 			allocbp = bp;
8929 			un->un_lastop = ST_OP_CTL;
8930 			switch (un->un_read_pos_type) {
8931 			case LONG_POS:
8932 				count = 0;
8933 				break;
8934 			case EXT_POS:
8935 				count = sizeof (tape_position_ext_t);
8936 				break;
8937 			case SHORT_POS:
8938 				count = 0;
8939 				break;
8940 			default:
8941 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8942 				    "Unknown read position type 0x%x in "
8943 				    " st_make_cmd()\n", un->un_read_pos_type);
8944 			}
8945 			break;
8946 
8947 		default:
8948 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8949 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8950 			    com);
8951 		}
8952 
8953 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8954 		    st_recov_sz, 0, func, (caddr_t)un);
8955 		if (pkt == NULL) {
8956 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8957 			    "generic command scsi_init_pkt() failure\n");
8958 			goto exit;
8959 		}
8960 
8961 		ASSERT(pkt->pkt_resid == 0);
8962 #ifdef STDEBUG
8963 		bzero(pkt->pkt_private, st_recov_sz);
8964 		bzero(pkt->pkt_scbp, stat_size);
8965 #endif
8966 		ri = (recov_info *)pkt->pkt_private;
8967 		ri->privatelen = st_recov_sz;
8968 		if (allocbp) {
8969 			ASSERT(geterror(allocbp) == 0);
8970 		}
8971 
8972 	}
8973 
8974 	ucdb = (union scsi_cdb *)pkt->pkt_cdbp;
8975 
8976 	(void) scsi_setup_cdb(ucdb, com, address, (uint_t)count, additional);
8977 	FILL_SCSI1_LUN(un->un_sd, pkt);
8978 	/*
8979 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8980 	 */
8981 	ucdb->t_code = fixbit;
8982 	ucdb->g0_vu_1 = short_fm;
8983 	pkt->pkt_flags = flags;
8984 
8985 	ASSERT(tval);
8986 	pkt->pkt_time = tval;
8987 	if (bp == un->un_recov_buf) {
8988 		pkt->pkt_comp = st_recov_cb;
8989 	} else {
8990 		pkt->pkt_comp = st_intr;
8991 	}
8992 
8993 	st_add_recovery_info_to_pkt(un, bp, pkt);
8994 
8995 	/*
8996 	 * If we just write data to tape and did a command that doesn't
8997 	 * change position, we still need to write a filemark.
8998 	 */
8999 	if ((prev_op == ST_OP_WRITE) || (prev_op == ST_OP_WEOF)) {
9000 		recov_info *rcvi = pkt->pkt_private;
9001 		cmd_attribute const *atrib;
9002 
9003 		if (rcvi->privatelen == sizeof (recov_info)) {
9004 			atrib = rcvi->cmd_attrib;
9005 		} else {
9006 			atrib = st_lookup_cmd_attribute(com);
9007 		}
9008 		if (atrib->chg_tape_direction == DIR_NONE) {
9009 			un->un_lastop = prev_op;
9010 		}
9011 	}
9012 
9013 exit:
9014 	ASSERT(mutex_owned(ST_MUTEX));
9015 }
9016 
9017 
9018 /*
9019  * Build a command based on a uscsi command;
9020  */
9021 static void
9022 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
9023     struct buf *bp, int (*func)(caddr_t))
9024 {
9025 	struct scsi_pkt *pkt;
9026 	recov_info *ri;
9027 	caddr_t cdb;
9028 	int	cdblen;
9029 	int	stat_size = 1;
9030 	int	flags = 0;
9031 
9032 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
9033 
9034 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9035 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
9036 
9037 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
9038 		if (un->un_arq_enabled) {
9039 			if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
9040 				stat_size = (int)(ucmd->uscsi_rqlen) +
9041 				    sizeof (struct scsi_arq_status) -
9042 				    sizeof (struct scsi_extended_sense);
9043 				flags = PKT_XARQ;
9044 			} else {
9045 				stat_size = sizeof (struct scsi_arq_status);
9046 			}
9047 		}
9048 	}
9049 
9050 	ASSERT(mutex_owned(ST_MUTEX));
9051 
9052 	cdb = ucmd->uscsi_cdb;
9053 	cdblen = ucmd->uscsi_cdblen;
9054 
9055 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9056 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
9057 	    ucmd->uscsi_buflen, bp->b_bcount);
9058 	pkt = scsi_init_pkt(ROUTE, NULL,
9059 	    (bp->b_bcount > 0) ? bp : NULL,
9060 	    cdblen, stat_size, st_recov_sz, flags, func, (caddr_t)un);
9061 	if (pkt == NULL) {
9062 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
9063 		    "uscsi command scsi_init_pkt() failure\n");
9064 		goto exit;
9065 	}
9066 
9067 	ASSERT(pkt->pkt_resid == 0);
9068 #ifdef STDEBUG
9069 	bzero(pkt->pkt_private, st_recov_sz);
9070 	bzero(pkt->pkt_scbp, stat_size);
9071 #endif
9072 	ri = (recov_info *)pkt->pkt_private;
9073 	ri->privatelen = st_recov_sz;
9074 
9075 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
9076 
9077 #ifdef STDEBUG
9078 	if ((st_debug & 0x7) >= 6) {
9079 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
9080 		    "pkt_cdbp", (char *)cdb, cdblen);
9081 	}
9082 #endif
9083 
9084 	if (ucmd->uscsi_flags & USCSI_SILENT) {
9085 		pkt->pkt_flags |= FLAG_SILENT;
9086 	}
9087 
9088 	(void) scsi_uscsi_pktinit(ucmd, pkt);
9089 
9090 	pkt->pkt_time = ucmd->uscsi_timeout;
9091 	if (bp == un->un_recov_buf) {
9092 		pkt->pkt_comp = st_recov_cb;
9093 	} else {
9094 		pkt->pkt_comp = st_intr;
9095 	}
9096 
9097 	st_add_recovery_info_to_pkt(un, bp, pkt);
9098 exit:
9099 	ASSERT(mutex_owned(ST_MUTEX));
9100 }
9101 
9102 
9103 /*
9104  * restart cmd currently at the head of the runq
9105  *
9106  * If scsi_transport() succeeds or the retries
9107  * count exhausted, restore the throttle that was
9108  * zeroed out in st_handle_intr_busy().
9109  *
9110  */
9111 static void
9112 st_intr_restart(void *arg)
9113 {
9114 	struct scsi_tape *un = arg;
9115 	struct buf *bp;
9116 	int queued;
9117 	int status = TRAN_ACCEPT;
9118 
9119 	mutex_enter(ST_MUTEX);
9120 
9121 	ST_FUNC(ST_DEVINFO, st_intr_restart);
9122 
9123 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9124 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
9125 
9126 	un->un_hib_tid = 0;
9127 
9128 	if (un->un_recov_buf_busy != 0) {
9129 		bp = un->un_recov_buf;
9130 		queued = 0;
9131 	} else if (un->un_sbuf_busy != 0) {
9132 		bp = un->un_sbufp;
9133 		queued = 0;
9134 	} else if (un->un_quef != NULL) {
9135 		bp = un->un_quef;
9136 		queued = 1;
9137 	} else {
9138 		mutex_exit(ST_MUTEX);
9139 		return;
9140 	}
9141 
9142 	/*
9143 	 * Here we know :
9144 	 *	throttle = 0, via st_handle_intr_busy
9145 	 */
9146 
9147 	if (queued) {
9148 		/*
9149 		 * move from waitq to runq, if there is anything on the waitq
9150 		 */
9151 		(void) st_remove_from_queue(&un->un_quef, &un->un_quef, bp);
9152 
9153 		if (un->un_runqf) {
9154 			/*
9155 			 * not good, we don't want to requeue something after
9156 			 * another.
9157 			 */
9158 			goto done_error;
9159 		} else {
9160 			un->un_runqf = bp;
9161 			un->un_runql = bp;
9162 		}
9163 	}
9164 
9165 	ST_CDB(ST_DEVINFO, "Interrupt restart CDB",
9166 	    (char *)BP_PKT(bp)->pkt_cdbp);
9167 
9168 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
9169 
9170 	status = st_transport(un, BP_PKT(bp));
9171 
9172 	if (status != TRAN_ACCEPT) {
9173 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9174 
9175 		if (status == TRAN_BUSY) {
9176 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
9177 
9178 			if (pkti->privatelen == sizeof (recov_info) &&
9179 			    un->un_unit_attention_flags &&
9180 			    bp != un->un_recov_buf) {
9181 			un->un_unit_attention_flags = 0;
9182 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9183 				    "Command Recovery called on busy resend\n");
9184 				if (st_command_recovery(un, BP_PKT(bp),
9185 				    ATTEMPT_RETRY) == JUST_RETURN) {
9186 					mutex_exit(ST_MUTEX);
9187 					return;
9188 				}
9189 			}
9190 			mutex_exit(ST_MUTEX);
9191 			if (st_handle_intr_busy(un, bp,
9192 			    ST_TRAN_BUSY_TIMEOUT) == 0)
9193 				return;	/* timeout is setup again */
9194 			mutex_enter(ST_MUTEX);
9195 		}
9196 
9197 done_error:
9198 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9199 		    "restart transport rejected\n");
9200 		bp->b_resid = bp->b_bcount;
9201 
9202 		if (un->un_last_throttle) {
9203 			un->un_throttle = un->un_last_throttle;
9204 		}
9205 		if (status != TRAN_ACCEPT) {
9206 			ST_DO_ERRSTATS(un, st_transerrs);
9207 		}
9208 		ST_DO_KSTATS(bp, kstat_waitq_exit);
9209 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9210 		    "busy restart aborted\n");
9211 		st_set_pe_flag(un);
9212 		st_bioerror(bp, EIO);
9213 		st_done_and_mutex_exit(un, bp);
9214 	} else {
9215 		if (un->un_last_throttle) {
9216 			un->un_throttle = un->un_last_throttle;
9217 		}
9218 		mutex_exit(ST_MUTEX);
9219 	}
9220 }
9221 
9222 /*
9223  * st_check_media():
9224  * Periodically check the media state using scsi_watch service;
9225  * this service calls back after TUR and possibly request sense
9226  * the callback handler (st_media_watch_cb()) decodes the request sense
9227  * data (if any)
9228  */
9229 
9230 static int
9231 st_check_media(dev_t dev, enum mtio_state state)
9232 {
9233 	int rval = 0;
9234 	enum mtio_state	prev_state;
9235 	opaque_t token = NULL;
9236 
9237 	GET_SOFT_STATE(dev);
9238 
9239 	ST_FUNC(ST_DEVINFO, st_check_media);
9240 
9241 	mutex_enter(ST_MUTEX);
9242 
9243 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9244 	    "st_check_media:state=%x, mediastate=%x\n",
9245 	    state, un->un_mediastate);
9246 
9247 	prev_state = un->un_mediastate;
9248 
9249 	/*
9250 	 * is there anything to do?
9251 	 */
9252 retry:
9253 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
9254 		/*
9255 		 * submit the request to the scsi_watch service;
9256 		 * scsi_media_watch_cb() does the real work
9257 		 */
9258 		mutex_exit(ST_MUTEX);
9259 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
9260 		    st_check_media_time, SENSE_LENGTH,
9261 		    st_media_watch_cb, (caddr_t)dev);
9262 		if (token == NULL) {
9263 			rval = EAGAIN;
9264 			goto done;
9265 		}
9266 		mutex_enter(ST_MUTEX);
9267 
9268 		un->un_swr_token = token;
9269 		un->un_specified_mediastate = state;
9270 
9271 		/*
9272 		 * now wait for media change
9273 		 * we will not be signalled unless mediastate == state but it
9274 		 * still better to test for this condition, since there
9275 		 * is a 5 sec cv_broadcast delay when
9276 		 *  mediastate == MTIO_INSERTED
9277 		 */
9278 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9279 		    "st_check_media:waiting for media state change\n");
9280 		while (un->un_mediastate == state) {
9281 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
9282 				mutex_exit(ST_MUTEX);
9283 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9284 				    "st_check_media:waiting for media state "
9285 				    "was interrupted\n");
9286 				rval = EINTR;
9287 				goto done;
9288 			}
9289 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9290 			    "st_check_media:received signal, state=%x\n",
9291 			    un->un_mediastate);
9292 		}
9293 	}
9294 
9295 	/*
9296 	 * if we transitioned to MTIO_INSERTED, media has really been
9297 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
9298 	 * Reset and retry the state change.  If everything is ok, replay
9299 	 * the open() logic.
9300 	 */
9301 	if ((un->un_mediastate == MTIO_INSERTED) &&
9302 	    (un->un_state == ST_STATE_OFFLINE)) {
9303 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9304 		    "st_check_media: calling st_cmd to confirm inserted\n");
9305 
9306 		/*
9307 		 * set this early so that TUR will make it through strategy
9308 		 * without triggering a st_tape_init().  We needed it set
9309 		 * before calling st_tape_init() ourselves anyway.  If TUR
9310 		 * fails, set it back
9311 		 */
9312 		un->un_state = ST_STATE_INITIALIZING;
9313 
9314 		/*
9315 		 * If not reserved fail as getting reservation conflict
9316 		 * will make this hang forever.
9317 		 */
9318 		if ((un->un_rsvd_status &
9319 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9320 			mutex_exit(ST_MUTEX);
9321 			rval = EACCES;
9322 			goto done;
9323 		}
9324 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
9325 		if (rval == EACCES) {
9326 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9327 			    "st_check_media: TUR got Reservation Conflict\n");
9328 			mutex_exit(ST_MUTEX);
9329 			goto done;
9330 		}
9331 		if (rval) {
9332 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9333 			    "st_check_media: TUR failed, going to retry\n");
9334 			un->un_mediastate = prev_state;
9335 			un->un_state = ST_STATE_OFFLINE;
9336 			goto retry;
9337 		}
9338 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9339 		    "st_check_media: media inserted\n");
9340 
9341 		/* this also rewinds the tape */
9342 		rval = st_tape_init(un);
9343 		if (rval != 0) {
9344 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9345 			    "st_check_media : OFFLINE init failure ");
9346 			un->un_state = ST_STATE_OFFLINE;
9347 			un->un_pos.pmode = invalid;
9348 		} else {
9349 			un->un_state = ST_STATE_OPEN_PENDING_IO;
9350 		}
9351 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
9352 	    (un->un_state != ST_STATE_OFFLINE)) {
9353 		/*
9354 		 * supported devices must be rewound before ejection
9355 		 * rewind resets fileno & blkno
9356 		 */
9357 		un->un_laststate = un->un_state;
9358 		un->un_state = ST_STATE_OFFLINE;
9359 	}
9360 	mutex_exit(ST_MUTEX);
9361 done:
9362 	if (token) {
9363 		(void) scsi_watch_request_terminate(token,
9364 		    SCSI_WATCH_TERMINATE_WAIT);
9365 		mutex_enter(ST_MUTEX);
9366 		un->un_swr_token = (opaque_t)NULL;
9367 		mutex_exit(ST_MUTEX);
9368 	}
9369 
9370 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
9371 
9372 	return (rval);
9373 }
9374 
9375 /*
9376  * st_media_watch_cb() is called by scsi_watch_thread for
9377  * verifying the request sense data (if any)
9378  */
9379 static int
9380 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
9381 {
9382 	struct scsi_status *statusp = resultp->statusp;
9383 	struct scsi_extended_sense *sensep = resultp->sensep;
9384 	uchar_t actual_sense_length = resultp->actual_sense_length;
9385 	struct scsi_tape *un;
9386 	enum mtio_state state = MTIO_NONE;
9387 	int instance;
9388 	dev_t dev = (dev_t)arg;
9389 
9390 	instance = MTUNIT(dev);
9391 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
9392 		return (-1);
9393 	}
9394 
9395 	mutex_enter(ST_MUTEX);
9396 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
9397 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9398 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
9399 	    *((char *)statusp), (void *)sensep,
9400 	    actual_sense_length);
9401 
9402 
9403 	/*
9404 	 * if there was a check condition then sensep points to valid
9405 	 * sense data
9406 	 * if status was not a check condition but a reservation or busy
9407 	 * status then the new state is MTIO_NONE
9408 	 */
9409 	if (sensep) {
9410 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9411 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
9412 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
9413 
9414 		switch (un->un_dp->type) {
9415 		default:
9416 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9417 			    "st_media_watch_cb: unknown drive type %d, "
9418 			    "default to ST_TYPE_HP\n", un->un_dp->type);
9419 		/* FALLTHROUGH */
9420 
9421 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
9422 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
9423 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
9424 			if (un->un_dp->type == ST_TYPE_FUJI) {
9425 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9426 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
9427 			} else {
9428 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9429 				    "st_media_watch_cb: ST_TYPE_HP\n");
9430 			}
9431 			switch (sensep->es_key) {
9432 			case KEY_UNIT_ATTENTION:
9433 				/* not ready to ready transition */
9434 				/* hp/es_qual_code == 80 on>off>on */
9435 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
9436 				if (sensep->es_add_code == 0x28) {
9437 					state = MTIO_INSERTED;
9438 				}
9439 				break;
9440 			case KEY_NOT_READY:
9441 				/* in process, rewinding or loading */
9442 				if ((sensep->es_add_code == 0x04) &&
9443 				    (sensep->es_qual_code == 0x00)) {
9444 					state = MTIO_EJECTED;
9445 				}
9446 				break;
9447 			}
9448 			break;
9449 
9450 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
9451 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9452 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
9453 			switch (sensep->es_key) {
9454 			case KEY_UNIT_ATTENTION:
9455 				/* operator medium removal request */
9456 				if ((sensep->es_add_code == 0x5a) &&
9457 				    (sensep->es_qual_code == 0x01)) {
9458 					state = MTIO_EJECTED;
9459 				/* not ready to ready transition */
9460 				} else if ((sensep->es_add_code == 0x28) &&
9461 				    (sensep->es_qual_code == 0x00)) {
9462 					state = MTIO_INSERTED;
9463 				}
9464 				break;
9465 			case KEY_NOT_READY:
9466 				/* medium not present */
9467 				if (sensep->es_add_code == 0x3a) {
9468 					state = MTIO_EJECTED;
9469 				}
9470 				break;
9471 			}
9472 			break;
9473 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
9474 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9475 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
9476 			switch (sensep->es_key) {
9477 			case KEY_NOT_READY:
9478 				if ((sensep->es_add_code == 0x04) &&
9479 				    (sensep->es_qual_code == 0x00)) {
9480 					/* volume not mounted? */
9481 					state = MTIO_EJECTED;
9482 				} else if (sensep->es_add_code == 0x3a) {
9483 					state = MTIO_EJECTED;
9484 				}
9485 				break;
9486 			case KEY_UNIT_ATTENTION:
9487 				state = MTIO_EJECTED;
9488 				break;
9489 			}
9490 			break;
9491 
9492 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
9493 			switch (sensep->es_key) {
9494 			case KEY_UNIT_ATTENTION:
9495 				if (sensep->es_add_code == 0x28) {
9496 					state = MTIO_INSERTED;
9497 				}
9498 				break;
9499 			case KEY_NOT_READY:
9500 				if (sensep->es_add_code == 0x04) {
9501 					/* in transition but could be either */
9502 					state = un->un_specified_mediastate;
9503 				} else if ((sensep->es_add_code == 0x3a) &&
9504 				    (sensep->es_qual_code == 0x00)) {
9505 					state = MTIO_EJECTED;
9506 				}
9507 				break;
9508 			}
9509 			break;
9510 		}
9511 	} else if (*((char *)statusp) == STATUS_GOOD) {
9512 		state = MTIO_INSERTED;
9513 	}
9514 
9515 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9516 	    "st_media_watch_cb:state=%x, specified=%x\n",
9517 	    state, un->un_specified_mediastate);
9518 
9519 	/*
9520 	 * now signal the waiting thread if this is *not* the specified state;
9521 	 * delay the signal if the state is MTIO_INSERTED
9522 	 * to allow the target to recover
9523 	 */
9524 	if (state != un->un_specified_mediastate) {
9525 		un->un_mediastate = state;
9526 		if (state == MTIO_INSERTED) {
9527 			/*
9528 			 * delay the signal to give the drive a chance
9529 			 * to do what it apparently needs to do
9530 			 */
9531 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9532 			    "st_media_watch_cb:delayed cv_broadcast\n");
9533 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
9534 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
9535 		} else {
9536 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9537 			    "st_media_watch_cb:immediate cv_broadcast\n");
9538 			cv_broadcast(&un->un_state_cv);
9539 		}
9540 	}
9541 	mutex_exit(ST_MUTEX);
9542 	return (0);
9543 }
9544 
9545 /*
9546  * delayed cv_broadcast to allow for target to recover
9547  * from media insertion
9548  */
9549 static void
9550 st_delayed_cv_broadcast(void *arg)
9551 {
9552 	struct scsi_tape *un = arg;
9553 
9554 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
9555 
9556 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9557 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
9558 
9559 	mutex_enter(ST_MUTEX);
9560 	cv_broadcast(&un->un_state_cv);
9561 	mutex_exit(ST_MUTEX);
9562 }
9563 
9564 /*
9565  * restart cmd currently at the start of the waitq
9566  */
9567 static void
9568 st_start_restart(void *arg)
9569 {
9570 	struct scsi_tape *un = arg;
9571 
9572 	ST_FUNC(ST_DEVINFO, st_start_restart);
9573 
9574 	ASSERT(un != NULL);
9575 
9576 	mutex_enter(ST_MUTEX);
9577 
9578 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_tran_restart()\n");
9579 
9580 	st_start(un);
9581 
9582 	mutex_exit(ST_MUTEX);
9583 }
9584 
9585 
9586 /*
9587  * Command completion processing
9588  *
9589  */
9590 static void
9591 st_intr(struct scsi_pkt *pkt)
9592 {
9593 	recov_info *rcv = pkt->pkt_private;
9594 	struct buf *bp = rcv->cmd_bp;
9595 	struct scsi_tape *un;
9596 	errstate action = COMMAND_DONE;
9597 	clock_t	timout;
9598 	int	status;
9599 
9600 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
9601 
9602 	ST_FUNC(ST_DEVINFO, st_intr);
9603 
9604 	ASSERT(un != NULL);
9605 
9606 	mutex_enter(ST_MUTEX);
9607 
9608 	ASSERT(bp != un->un_recov_buf);
9609 
9610 	un->un_rqs_state &= ~(ST_RQS_ERROR);
9611 
9612 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
9613 
9614 	if (pkt->pkt_reason != CMD_CMPLT) {
9615 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9616 		    "Unhappy packet status reason = %s statistics = 0x%x\n",
9617 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9618 
9619 		/* If device has gone away not much else to do */
9620 		if (pkt->pkt_reason == CMD_DEV_GONE) {
9621 			action = COMMAND_DONE_ERROR;
9622 		} else if ((pkt == un->un_rqs) ||
9623 		    (un->un_state == ST_STATE_SENSING)) {
9624 			ASSERT(pkt == un->un_rqs);
9625 			ASSERT(un->un_state == ST_STATE_SENSING);
9626 			un->un_state = un->un_laststate;
9627 			rcv->cmd_bp = un->un_rqs_bp;
9628 			ST_DO_ERRSTATS(un, st_transerrs);
9629 			action = COMMAND_DONE_ERROR;
9630 		} else {
9631 			action = st_handle_incomplete(un, bp);
9632 		}
9633 	/*
9634 	 * At this point we know that the command was successfully
9635 	 * completed. Now what?
9636 	 */
9637 	} else if ((pkt == un->un_rqs) || (un->un_state == ST_STATE_SENSING)) {
9638 		/*
9639 		 * okay. We were running a REQUEST SENSE. Find
9640 		 * out what to do next.
9641 		 */
9642 		ASSERT(pkt == un->un_rqs);
9643 		ASSERT(un->un_state == ST_STATE_SENSING);
9644 		scsi_sync_pkt(pkt);
9645 		action = st_handle_sense(un, bp, &un->un_pos);
9646 		/*
9647 		 * Make rqs isn't going to be retied.
9648 		 */
9649 		if (action != QUE_BUSY_COMMAND && action != QUE_COMMAND) {
9650 			/*
9651 			 * set pkt back to original packet in case we will have
9652 			 * to requeue it
9653 			 */
9654 			pkt = BP_PKT(bp);
9655 			rcv->cmd_bp = un->un_rqs_bp;
9656 			/*
9657 			 * some actions are based on un_state, hence
9658 			 * restore the state st was in before ST_STATE_SENSING.
9659 			 */
9660 			un->un_state = un->un_laststate;
9661 		}
9662 
9663 	} else if (un->un_arq_enabled && (pkt->pkt_state & STATE_ARQ_DONE)) {
9664 		/*
9665 		 * the transport layer successfully completed an autorqsense
9666 		 */
9667 		action = st_handle_autosense(un, bp, &un->un_pos);
9668 
9669 	} else  if ((SCBP(pkt)->sts_busy) ||
9670 	    (SCBP(pkt)->sts_chk) ||
9671 	    (SCBP(pkt)->sts_vu7)) {
9672 		/*
9673 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9674 		 * to see if the status bits we're okay. If a request sense
9675 		 * is to be run, that will happen.
9676 		 */
9677 		action = st_check_error(un, pkt);
9678 	}
9679 
9680 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9681 		switch (action) {
9682 			case QUE_COMMAND:
9683 				/*
9684 				 * return cmd to head to the queue
9685 				 * since we are suspending so that
9686 				 * it gets restarted during resume
9687 				 */
9688 				st_add_to_queue(&un->un_runqf, &un->un_runql,
9689 				    un->un_runqf, bp);
9690 
9691 				action = JUST_RETURN;
9692 				break;
9693 
9694 			case QUE_SENSE:
9695 				action = COMMAND_DONE_ERROR;
9696 				break;
9697 
9698 			default:
9699 				break;
9700 		}
9701 	}
9702 
9703 	/*
9704 	 * check for undetected path failover.
9705 	 */
9706 	if (un->un_multipath) {
9707 
9708 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
9709 		int pkt_valid = 0;
9710 
9711 		if (ucmd) {
9712 			/*
9713 			 * Also copies path instance to the uscsi structure.
9714 			 */
9715 			pkt_valid = scsi_uscsi_pktfini(pkt, ucmd);
9716 
9717 			/*
9718 			 * scsi_uscsi_pktfini() zeros pkt_path_instance.
9719 			 */
9720 			pkt->pkt_path_instance = ucmd->uscsi_path_instance;
9721 		} else {
9722 			pkt_valid = scsi_pkt_allocated_correctly(pkt);
9723 		}
9724 
9725 		/*
9726 		 * If the scsi_pkt was not allocated correctly the
9727 		 * pkt_path_instance is not even there.
9728 		 */
9729 		if ((pkt_valid != 0) &&
9730 		    (un->un_last_path_instance != pkt->pkt_path_instance)) {
9731 			/*
9732 			 * Don't recover the path change if it was done
9733 			 * intentionally or if the device has not completely
9734 			 * opened yet.
9735 			 */
9736 			if (((pkt->pkt_flags & FLAG_PKT_PATH_INSTANCE) == 0) &&
9737 			    (un->un_state > ST_STATE_OPENING)) {
9738 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
9739 				    "Failover detected, action is %s\n",
9740 				    errstatenames[action]);
9741 				if (action == COMMAND_DONE) {
9742 					action = PATH_FAILED;
9743 				}
9744 			}
9745 			un->un_last_path_instance = pkt->pkt_path_instance;
9746 		}
9747 	}
9748 
9749 	/*
9750 	 * Restore old state if we were sensing.
9751 	 */
9752 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9753 		un->un_state = un->un_laststate;
9754 	}
9755 
9756 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9757 	    "st_intr: pkt=%p, bp=%p, action=%s, status=%x\n",
9758 	    (void *)pkt, (void *)bp, errstatenames[action], SCBP_C(pkt));
9759 
9760 again:
9761 	switch (action) {
9762 	case COMMAND_DONE_EACCES:
9763 		/* this is to report a reservation conflict */
9764 		st_bioerror(bp, EACCES);
9765 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9766 		    "Reservation Conflict \n");
9767 		un->un_pos.pmode = invalid;
9768 
9769 		/*FALLTHROUGH*/
9770 	case COMMAND_DONE_ERROR:
9771 		if (un->un_pos.eof < ST_EOT_PENDING &&
9772 		    un->un_state >= ST_STATE_OPEN) {
9773 			/*
9774 			 * all errors set state of the tape to 'unknown'
9775 			 * unless we're at EOT or are doing append testing.
9776 			 * If sense key was illegal request, preserve state.
9777 			 */
9778 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9779 				un->un_pos.pmode = invalid;
9780 			}
9781 		}
9782 
9783 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9784 		/*
9785 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9786 		 * make sure an error ocurrs, so make sure at least EIO is
9787 		 * returned
9788 		 */
9789 		if (geterror(bp) == 0)
9790 			st_bioerror(bp, EIO);
9791 
9792 		st_set_pe_flag(un);
9793 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9794 		    (un->un_errno == EIO)) {
9795 			un->un_rqs_state &= ~(ST_RQS_VALID);
9796 		}
9797 		break;
9798 
9799 	case COMMAND_DONE_ERROR_RECOVERED:
9800 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9801 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9802 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9803 		if (geterror(bp) == 0) {
9804 			st_bioerror(bp, EIO);
9805 		}
9806 		st_set_pe_flag(un);
9807 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9808 		    (un->un_errno == EIO)) {
9809 			un->un_rqs_state &= ~(ST_RQS_VALID);
9810 		}
9811 		/*FALLTHROUGH*/
9812 	case COMMAND_DONE:
9813 		st_set_state(un, bp);
9814 		break;
9815 
9816 	case QUE_SENSE:
9817 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9818 			goto sense_error;
9819 
9820 		if (un->un_state != ST_STATE_SENSING) {
9821 			un->un_laststate = un->un_state;
9822 			un->un_state = ST_STATE_SENSING;
9823 		}
9824 
9825 		/*
9826 		 * zero the sense data.
9827 		 */
9828 		bzero(un->un_rqs->pkt_scbp, SENSE_LENGTH);
9829 
9830 		/*
9831 		 * If this is not a retry on QUE_SENSE point to the original
9832 		 * bp of the command that got us here.
9833 		 */
9834 		if (pkt != un->un_rqs) {
9835 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp = bp;
9836 		}
9837 
9838 		if (un->un_throttle) {
9839 			un->un_last_throttle = un->un_throttle;
9840 			un->un_throttle = 0;
9841 		}
9842 
9843 		ST_CDB(ST_DEVINFO, "Queue sense CDB",
9844 		    (char *)BP_PKT(bp)->pkt_cdbp);
9845 
9846 		/*
9847 		 * never retry this, some other command will have nuked the
9848 		 * sense, anyway
9849 		 */
9850 		status = st_transport(un, un->un_rqs);
9851 
9852 		if (un->un_last_throttle) {
9853 			un->un_throttle = un->un_last_throttle;
9854 		}
9855 
9856 		if (status == TRAN_ACCEPT) {
9857 			mutex_exit(ST_MUTEX);
9858 			return;
9859 		}
9860 		if (status != TRAN_BUSY)
9861 			ST_DO_ERRSTATS(un, st_transerrs);
9862 sense_error:
9863 		un->un_pos.pmode = invalid;
9864 		st_bioerror(bp, EIO);
9865 		st_set_pe_flag(un);
9866 		break;
9867 
9868 	case QUE_BUSY_COMMAND:
9869 		/* longish timeout */
9870 		timout = ST_STATUS_BUSY_TIMEOUT;
9871 		goto que_it_up;
9872 
9873 	case QUE_COMMAND:
9874 		/* short timeout */
9875 		timout = ST_TRAN_BUSY_TIMEOUT;
9876 que_it_up:
9877 		/*
9878 		 * let st_handle_intr_busy put this bp back on waitq and make
9879 		 * checks to see if it is ok to requeue the command.
9880 		 */
9881 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9882 
9883 		/*
9884 		 * Save the throttle before setting up the timeout
9885 		 */
9886 		if (un->un_throttle) {
9887 			un->un_last_throttle = un->un_throttle;
9888 		}
9889 		mutex_exit(ST_MUTEX);
9890 		if (st_handle_intr_busy(un, bp, timout) == 0)
9891 			return;		/* timeout is setup again */
9892 
9893 		mutex_enter(ST_MUTEX);
9894 		un->un_pos.pmode = invalid;
9895 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9896 		st_bioerror(bp, EIO);
9897 		st_set_pe_flag(un);
9898 		break;
9899 
9900 	case QUE_LAST_COMMAND:
9901 
9902 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9903 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9904 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9905 			goto last_command_error;
9906 		}
9907 		mutex_exit(ST_MUTEX);
9908 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9909 			return;
9910 		mutex_enter(ST_MUTEX);
9911 last_command_error:
9912 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9913 		un->un_pos.pmode = invalid;
9914 		st_bioerror(bp, EIO);
9915 		st_set_pe_flag(un);
9916 		break;
9917 
9918 	case COMMAND_TIMEOUT:
9919 	case DEVICE_RESET:
9920 	case DEVICE_TAMPER:
9921 	case ATTEMPT_RETRY:
9922 	case PATH_FAILED:
9923 		ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9924 		    "Command Recovery called on %s status\n",
9925 		    errstatenames[action]);
9926 		action = st_command_recovery(un, pkt, action);
9927 		goto again;
9928 
9929 	default:
9930 		ASSERT(0);
9931 		/* FALLTHRU */
9932 	case JUST_RETURN:
9933 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9934 		mutex_exit(ST_MUTEX);
9935 		return;
9936 	}
9937 
9938 	ST_DO_KSTATS(bp, kstat_runq_exit);
9939 	st_done_and_mutex_exit(un, bp);
9940 }
9941 
9942 static errstate
9943 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9944 {
9945 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9946 	recov_info *rinfo;
9947 	errstate rval = COMMAND_DONE_ERROR;
9948 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9949 	    un->un_rqs : BP_PKT(bp);
9950 	int result;
9951 
9952 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9953 
9954 	rinfo = (recov_info *)pkt->pkt_private;
9955 
9956 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9957 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9958 
9959 	ASSERT(mutex_owned(ST_MUTEX));
9960 
9961 	switch (pkt->pkt_reason) {
9962 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9963 		/*
9964 		 * this occurs when accessing a powered down drive, no
9965 		 * need to complain; just fail the open
9966 		 */
9967 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9968 
9969 		/*
9970 		 * if we have commands outstanding in HBA, and a command
9971 		 * comes back incomplete, we're hosed, so reset target
9972 		 * If we have the bus, but cmd_incomplete, we probably just
9973 		 * have a failed selection, so don't reset the target, just
9974 		 * requeue the command and try again
9975 		 */
9976 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9977 			goto reset_target;
9978 		}
9979 
9980 		/*
9981 		 * Retry selection a couple more times if we're
9982 		 * open.  If opening, we only try just once to
9983 		 * reduce probe time for nonexistant devices.
9984 		 */
9985 		if ((un->un_laststate > ST_STATE_OPENING) &&
9986 		    (rinfo->pkt_retry_cnt < st_selection_retry_count)) {
9987 			/* XXX check retriable? */
9988 			rval = QUE_COMMAND;
9989 		}
9990 		ST_DO_ERRSTATS(un, st_transerrs);
9991 		break;
9992 
9993 	case CMD_ABORTED:
9994 		/*
9995 		 * most likely this is caused by flush-on-error support. If
9996 		 * it was not there, the we're in trouble.
9997 		 */
9998 		if (!un->un_flush_on_errors) {
9999 			un->un_status = SUN_KEY_FATAL;
10000 			goto reset_target;
10001 		}
10002 
10003 		st_set_pe_errno(un);
10004 		bioerror(bp, un->un_errno);
10005 		if (un->un_errno)
10006 			return (COMMAND_DONE_ERROR);
10007 		else
10008 			return (COMMAND_DONE);
10009 
10010 	case CMD_TIMEOUT:	/* Command timed out */
10011 		un->un_status = SUN_KEY_TIMEOUT;
10012 		return (COMMAND_TIMEOUT);
10013 
10014 	case CMD_TRAN_ERR:
10015 	case CMD_RESET:
10016 		if (pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET)) {
10017 			if ((un->un_rsvd_status &
10018 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
10019 			    ST_RESERVE) {
10020 				un->un_rsvd_status |= ST_LOST_RESERVE;
10021 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
10022 				    "Lost Reservation\n");
10023 			}
10024 			rval = DEVICE_RESET;
10025 			return (rval);
10026 		}
10027 		if (pkt->pkt_statistics & (STAT_ABORTED | STAT_TERMINATED)) {
10028 			rval = DEVICE_RESET;
10029 			return (rval);
10030 		}
10031 		/*FALLTHROUGH*/
10032 	default:
10033 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10034 		    "Unhandled packet status reason = %s statistics = 0x%x\n",
10035 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
10036 reset_target:
10037 
10038 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10039 		    "transport completed with %s\n",
10040 		    scsi_rname(pkt->pkt_reason));
10041 		ST_DO_ERRSTATS(un, st_transerrs);
10042 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
10043 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
10044 		    STAT_ABORTED)) == 0)) {
10045 
10046 			/*
10047 			 * If we haven't reserved the drive don't reset it.
10048 			 */
10049 			if ((un->un_rsvd_status &
10050 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
10051 				return (rval);
10052 			}
10053 
10054 			/*
10055 			 * if we aren't lost yet we will be soon.
10056 			 */
10057 			un->un_pos.pmode = invalid;
10058 
10059 			result = st_reset(un, RESET_LUN);
10060 
10061 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
10062 				/* no hope left to recover */
10063 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
10064 				    "recovery by resets failed\n");
10065 				return (rval);
10066 			}
10067 		}
10068 	}
10069 
10070 
10071 	if (rinfo->pkt_retry_cnt++ < st_retry_count) {
10072 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
10073 			rval = QUE_COMMAND;
10074 		} else if (bp == un->un_sbufp) {
10075 			if (rinfo->privatelen == sizeof (recov_info)) {
10076 				if (rinfo->cmd_attrib->retriable) {
10077 					/*
10078 					 * These commands can be rerun
10079 					 * with impunity
10080 					 */
10081 					rval = QUE_COMMAND;
10082 				}
10083 			} else {
10084 				cmd_attribute const *attrib;
10085 				attrib =
10086 				    st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10087 				if (attrib->retriable) {
10088 					rval = QUE_COMMAND;
10089 				}
10090 			}
10091 		}
10092 	} else {
10093 		rval = COMMAND_DONE_ERROR;
10094 	}
10095 
10096 	if (un->un_state >= ST_STATE_OPEN) {
10097 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10098 		    fail, scsi_rname(pkt->pkt_reason),
10099 		    (rval == COMMAND_DONE_ERROR)?
10100 		    "giving up" : "retrying command");
10101 	}
10102 	return (rval);
10103 }
10104 
10105 /*
10106  * if the device is busy, then put this bp back on the waitq, on the
10107  * interrupt thread, where we want the head of the queue and not the
10108  * end
10109  *
10110  * The callers of this routine should take measures to save the
10111  * un_throttle in un_last_throttle which will be restored in
10112  * st_intr_restart(). The only exception should be st_intr_restart()
10113  * calling this routine for which the saving is already done.
10114  */
10115 static int
10116 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
10117 	clock_t timeout_interval)
10118 {
10119 
10120 	int queued;
10121 	int rval = 0;
10122 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
10123 
10124 	mutex_enter(ST_MUTEX);
10125 
10126 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
10127 
10128 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10129 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
10130 
10131 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
10132 		queued = 1;
10133 	} else {
10134 		queued = 0;
10135 	}
10136 
10137 	/*
10138 	 * Check to see if we hit the retry timeout. We check to make sure
10139 	 * this is the first one on the runq and make sure we have not
10140 	 * queued up any more, so this one has to be the last on the list
10141 	 * also. If it is not, we have to fail.  If it is not the first, but
10142 	 * is the last we are in trouble anyway, as we are in the interrupt
10143 	 * context here.
10144 	 */
10145 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
10146 	    ((un->un_runqf != bp) && (un->un_runql != bp) && (queued))) {
10147 		rval = -1;
10148 		goto exit;
10149 	}
10150 
10151 	/* put the bp back on the waitq */
10152 	if (queued) {
10153 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
10154 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
10155 	}
10156 
10157 	/*
10158 	 * We don't want any other commands being started in the mean time.
10159 	 * If start had just released mutex after putting something on the
10160 	 * runq, we won't even get here.
10161 	 */
10162 	un->un_throttle = 0;
10163 
10164 	/*
10165 	 * send a marker pkt, if appropriate
10166 	 */
10167 	st_hba_unflush(un);
10168 
10169 	/*
10170 	 * all queues are aligned, we are just waiting to
10171 	 * transport
10172 	 */
10173 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
10174 
10175 exit:
10176 	mutex_exit(ST_MUTEX);
10177 	return (rval);
10178 }
10179 
10180 /*
10181  * To get one error entry from error stack
10182  */
10183 static int
10184 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
10185 {
10186 #ifdef _MULTI_DATAMODEL
10187 	/*
10188 	 * For use when a 32 bit app makes a call into a
10189 	 * 64 bit ioctl
10190 	 */
10191 	struct mterror_entry32 err_entry32;
10192 #endif /* _MULTI_DATAMODEL */
10193 
10194 	int rval = 0;
10195 	struct mterror_entry err_entry;
10196 	struct mterror_entry_stack *err_link_entry_p;
10197 	size_t arq_status_len_in, arq_status_len_kr;
10198 
10199 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
10200 
10201 	ASSERT(mutex_owned(ST_MUTEX));
10202 
10203 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10204 	    "st_get_error_entry()\n");
10205 
10206 	/*
10207 	 * if error record stack empty, return ENXIO
10208 	 */
10209 	if (un->un_error_entry_stk == NULL) {
10210 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10211 		    "st_get_error_entry: Error Entry Stack Empty!\n");
10212 		rval = ENXIO;
10213 		goto ret;
10214 	}
10215 
10216 	/*
10217 	 * get the top entry from stack
10218 	 */
10219 	err_link_entry_p = un->un_error_entry_stk;
10220 	arq_status_len_kr =
10221 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
10222 
10223 #ifdef _MULTI_DATAMODEL
10224 	switch (ddi_model_convert_from(flag & FMODELS)) {
10225 	case DDI_MODEL_ILP32:
10226 		if (ddi_copyin((void *)arg, &err_entry32,
10227 		    MTERROR_ENTRY_SIZE_32, flag)) {
10228 			rval = EFAULT;
10229 			goto ret;
10230 		}
10231 
10232 		arq_status_len_in =
10233 		    (size_t)err_entry32.mtee_arq_status_len;
10234 
10235 		err_entry32.mtee_cdb_len =
10236 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
10237 
10238 		if (arq_status_len_in > arq_status_len_kr)
10239 			err_entry32.mtee_arq_status_len =
10240 			    (size32_t)arq_status_len_kr;
10241 
10242 		if (ddi_copyout(
10243 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10244 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
10245 		    err_entry32.mtee_cdb_len, flag)) {
10246 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10247 			    "st_get_error_entry: Copy cdb buffer error!");
10248 			rval = EFAULT;
10249 		}
10250 
10251 		if (ddi_copyout(
10252 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10253 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
10254 		    err_entry32.mtee_arq_status_len, flag)) {
10255 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10256 			    "st_get_error_entry: copy arq status error!");
10257 			rval = EFAULT;
10258 		}
10259 
10260 		if (ddi_copyout(&err_entry32, (void *)arg,
10261 		    MTERROR_ENTRY_SIZE_32, flag)) {
10262 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10263 			    "st_get_error_entry: copy arq status out error!");
10264 			rval = EFAULT;
10265 		}
10266 		break;
10267 
10268 	case DDI_MODEL_NONE:
10269 		if (ddi_copyin((void *)arg, &err_entry,
10270 		    MTERROR_ENTRY_SIZE_64, flag)) {
10271 			rval = EFAULT;
10272 			goto ret;
10273 		}
10274 		arq_status_len_in = err_entry.mtee_arq_status_len;
10275 
10276 		err_entry.mtee_cdb_len =
10277 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
10278 
10279 		if (arq_status_len_in > arq_status_len_kr)
10280 			err_entry.mtee_arq_status_len =
10281 			    arq_status_len_kr;
10282 
10283 		if (ddi_copyout(
10284 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10285 		    err_entry.mtee_cdb_buf,
10286 		    err_entry.mtee_cdb_len, flag)) {
10287 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10288 			    "st_get_error_entry: Copy cdb buffer error!");
10289 			rval = EFAULT;
10290 		}
10291 
10292 		if (ddi_copyout(
10293 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10294 		    err_entry.mtee_arq_status,
10295 		    err_entry.mtee_arq_status_len, flag)) {
10296 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10297 			    "st_get_error_entry: copy arq status error!");
10298 			rval = EFAULT;
10299 		}
10300 
10301 		if (ddi_copyout(&err_entry, (void *)arg,
10302 		    MTERROR_ENTRY_SIZE_64, flag)) {
10303 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10304 			    "st_get_error_entry: copy arq status out error!");
10305 			rval = EFAULT;
10306 		}
10307 		break;
10308 	}
10309 #else /* _MULTI_DATAMODEL */
10310 	if (ddi_copyin((void *)arg, &err_entry,
10311 	    MTERROR_ENTRY_SIZE_64, flag)) {
10312 		rval = EFAULT;
10313 		goto ret;
10314 	}
10315 	arq_status_len_in = err_entry.mtee_arq_status_len;
10316 
10317 	err_entry.mtee_cdb_len =
10318 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
10319 
10320 	if (arq_status_len_in > arq_status_len_kr)
10321 		err_entry.mtee_arq_status_len =
10322 		    arq_status_len_kr;
10323 
10324 	if (ddi_copyout(
10325 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10326 	    err_entry.mtee_cdb_buf,
10327 	    err_entry.mtee_cdb_len, flag)) {
10328 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10329 		    "st_get_error_entry: Copy cdb buffer error!");
10330 		rval = EFAULT;
10331 	}
10332 
10333 	if (ddi_copyout(
10334 	    err_link_entry_p->mtees_entry.mtee_arq_status,
10335 	    err_entry.mtee_arq_status,
10336 	    err_entry.mtee_arq_status_len, flag)) {
10337 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10338 		    "st_get_error_entry: copy arq status buffer error!");
10339 		rval = EFAULT;
10340 	}
10341 
10342 	if (ddi_copyout(&err_entry, (void *)arg,
10343 	    MTERROR_ENTRY_SIZE_64, flag)) {
10344 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10345 		    "st_get_error_entry: copy arq status out error!");
10346 		rval = EFAULT;
10347 	}
10348 #endif /* _MULTI_DATAMODEL */
10349 
10350 	/*
10351 	 * update stack
10352 	 */
10353 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
10354 
10355 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
10356 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
10357 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
10358 
10359 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
10360 	    SECMDS_STATUS_SIZE);
10361 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
10362 
10363 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
10364 	err_link_entry_p = NULL;
10365 ret:
10366 	return (rval);
10367 }
10368 
10369 /*
10370  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
10371  * the scsi CDB command which causes the error and generates sense data and
10372  * the scsi status.
10373  *
10374  *      error-record stack
10375  *
10376  *
10377  *             TOP                                     BOTTOM
10378  *              ------------------------------------------
10379  *              |   0   |   1   |   2   |   ...  |   n   |
10380  *              ------------------------------------------
10381  *                  ^
10382  *                  |
10383  *       pointer to error entry
10384  *
10385  * when st driver generates one sense data record, it creates a error-entry
10386  * and pushes it onto the stack.
10387  *
10388  */
10389 
10390 static void
10391 st_update_error_stack(struct scsi_tape *un,
10392 			struct scsi_pkt *pkt,
10393 			struct scsi_arq_status *cmd)
10394 {
10395 	struct mterror_entry_stack *err_entry_tmp;
10396 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
10397 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
10398 
10399 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
10400 
10401 	ASSERT(mutex_owned(ST_MUTEX));
10402 
10403 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10404 	    "st_update_error_stack()\n");
10405 
10406 	ASSERT(cmd);
10407 	ASSERT(cdbp);
10408 	if (cdblen == 0) {
10409 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10410 		    "st_update_error_stack: CDB length error!\n");
10411 		return;
10412 	}
10413 
10414 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
10415 	ASSERT(err_entry_tmp != NULL);
10416 
10417 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
10418 	    kmem_alloc(cdblen, KM_SLEEP);
10419 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
10420 
10421 	err_entry_tmp->mtees_entry.mtee_arq_status =
10422 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
10423 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
10424 
10425 	/*
10426 	 * copy cdb command & length to current error entry
10427 	 */
10428 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
10429 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
10430 
10431 	/*
10432 	 * copy scsi status length to current error entry
10433 	 */
10434 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
10435 	    SECMDS_STATUS_SIZE;
10436 
10437 	/*
10438 	 * copy sense data and scsi status to current error entry
10439 	 */
10440 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
10441 	    SECMDS_STATUS_SIZE);
10442 
10443 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
10444 	un->un_error_entry_stk = err_entry_tmp;
10445 
10446 }
10447 
10448 /*
10449  * Empty all the error entry in stack
10450  */
10451 static void
10452 st_empty_error_stack(struct scsi_tape *un)
10453 {
10454 	struct mterror_entry_stack *linkp;
10455 
10456 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
10457 
10458 	ASSERT(mutex_owned(ST_MUTEX));
10459 
10460 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10461 	    "st_empty_entry_stack()\n");
10462 
10463 	while (un->un_error_entry_stk != NULL) {
10464 		linkp = un->un_error_entry_stk;
10465 		un->un_error_entry_stk =
10466 		    un->un_error_entry_stk->mtees_nextp;
10467 
10468 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
10469 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
10470 			    linkp->mtees_entry.mtee_cdb_len);
10471 
10472 		if (linkp->mtees_entry.mtee_arq_status != NULL)
10473 			kmem_free(linkp->mtees_entry.mtee_arq_status,
10474 			    linkp->mtees_entry.mtee_arq_status_len);
10475 
10476 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
10477 		linkp = NULL;
10478 	}
10479 }
10480 
10481 static errstate
10482 st_handle_sense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10483 {
10484 	struct scsi_pkt *pkt = BP_PKT(bp);
10485 	struct scsi_pkt *rqpkt = un->un_rqs;
10486 	struct scsi_arq_status arqstat;
10487 	recov_info *rcif = pkt->pkt_private;
10488 
10489 	errstate rval = COMMAND_DONE_ERROR;
10490 	int amt;
10491 
10492 	ST_FUNC(ST_DEVINFO, st_handle_sense);
10493 
10494 	ASSERT(mutex_owned(ST_MUTEX));
10495 
10496 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10497 	    "st_handle_sense()\n");
10498 
10499 	if (SCBP(rqpkt)->sts_busy) {
10500 		if (rcif->privatelen == sizeof (recov_info)) {
10501 			ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
10502 			    "Attempt recovery of busy unit on request sense\n");
10503 			rval = ATTEMPT_RETRY;
10504 		} else if (rcif->pkt_retry_cnt++ < st_retry_count) {
10505 			ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10506 			    "Retry busy unit on request sense\n");
10507 			rval = QUE_BUSY_COMMAND;
10508 		}
10509 		return (rval);
10510 	} else if (SCBP(rqpkt)->sts_chk) {
10511 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10512 		    "Check Condition on REQUEST SENSE\n");
10513 		return (rval);
10514 	}
10515 
10516 	/*
10517 	 * Make sure there is sense data to look at.
10518 	 */
10519 	if ((rqpkt->pkt_state & (STATE_GOT_BUS | STATE_GOT_TARGET |
10520 	    STATE_SENT_CMD | STATE_GOT_STATUS)) != (STATE_GOT_BUS |
10521 	    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) {
10522 		return (rval);
10523 	}
10524 
10525 	/* was there enough data? */
10526 	amt = (int)MAX_SENSE_LENGTH - rqpkt->pkt_resid;
10527 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
10528 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10529 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10530 		    "REQUEST SENSE couldn't get sense data\n");
10531 		return (rval);
10532 	}
10533 
10534 	bcopy(SCBP(pkt), &arqstat.sts_status,
10535 	    sizeof (struct scsi_status));
10536 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
10537 	    sizeof (struct scsi_status));
10538 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
10539 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
10540 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
10541 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
10542 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
10543 
10544 	/*
10545 	 * copy one arqstat entry in the sense data buffer
10546 	 */
10547 	st_update_error_stack(un, pkt, &arqstat);
10548 	return (st_decode_sense(un, bp, amt, &arqstat, pos));
10549 }
10550 
10551 static errstate
10552 st_handle_autosense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10553 {
10554 	struct scsi_pkt *pkt = BP_PKT(bp);
10555 	struct scsi_arq_status *arqstat =
10556 	    (struct scsi_arq_status *)pkt->pkt_scbp;
10557 	errstate rval = COMMAND_DONE_ERROR;
10558 	int amt;
10559 
10560 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
10561 
10562 	ASSERT(mutex_owned(ST_MUTEX));
10563 
10564 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10565 	    "st_handle_autosense()\n");
10566 
10567 	if (arqstat->sts_rqpkt_status.sts_busy) {
10568 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10569 		    "busy unit on request sense\n");
10570 		/*
10571 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
10572 		 * the disadvantage is that we do not have any delay for the
10573 		 * second retry of rqsense and we have to keep a packet around
10574 		 */
10575 		return (QUE_SENSE);
10576 
10577 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
10578 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10579 		    "transport error on REQUEST SENSE\n");
10580 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
10581 		    ((arqstat->sts_rqpkt_statistics &
10582 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
10583 			if (st_reset(un, RESET_LUN) == 0) {
10584 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10585 				    "recovery by resets failed\n");
10586 			}
10587 		}
10588 		return (rval);
10589 
10590 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
10591 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10592 		    "Check Condition on REQUEST SENSE\n");
10593 		return (rval);
10594 	}
10595 
10596 
10597 	/* was there enough data? */
10598 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10599 		amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10600 	} else {
10601 		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
10602 			amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10603 		} else {
10604 			amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10605 		}
10606 	}
10607 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
10608 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10609 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10610 		    "REQUEST SENSE couldn't get sense data\n");
10611 		return (rval);
10612 	}
10613 
10614 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10615 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, MAX_SENSE_LENGTH);
10616 	} else {
10617 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
10618 	}
10619 
10620 	/*
10621 	 * copy one arqstat entry in the sense data buffer
10622 	 */
10623 	st_update_error_stack(un, pkt, arqstat);
10624 
10625 	return (st_decode_sense(un, bp, amt, arqstat, pos));
10626 }
10627 
10628 static errstate
10629 st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
10630     struct scsi_arq_status *statusp, tapepos_t *pos)
10631 {
10632 	struct scsi_pkt *pkt = BP_PKT(bp);
10633 	recov_info *ri = pkt->pkt_private;
10634 	errstate rval = COMMAND_DONE_ERROR;
10635 	cmd_attribute const *attrib;
10636 	long resid;
10637 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10638 	int severity;
10639 	int get_error;
10640 
10641 	ST_FUNC(ST_DEVINFO, st_decode_sense);
10642 
10643 	ASSERT(mutex_owned(ST_MUTEX));
10644 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10645 	    "st_decode_sense()\n");
10646 
10647 	/*
10648 	 * For uscsi commands, squirrel away a copy of the
10649 	 * results of the Request Sense.
10650 	 */
10651 	if (USCSI_CMD(bp)) {
10652 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
10653 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
10654 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
10655 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
10656 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
10657 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
10658 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10659 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
10660 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
10661 		}
10662 	}
10663 
10664 	if (ri->privatelen == sizeof (recov_info)) {
10665 		attrib = ri->cmd_attrib;
10666 	} else {
10667 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10668 	}
10669 
10670 	/*
10671 	 * If the drive is an MT-02, reposition the
10672 	 * secondary error code into the proper place.
10673 	 *
10674 	 * XXX	MT-02 is non-CCS tape, so secondary error code
10675 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
10676 	 * so it's in byte 12.
10677 	 */
10678 	if (un->un_dp->type == ST_TYPE_EMULEX) {
10679 		sensep->es_code = sensep->es_add_info[0];
10680 	}
10681 
10682 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
10683 	    (caddr_t)&CDBP(pkt)->scc_cmd);
10684 
10685 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)statusp,
10686 	    sizeof (*statusp));
10687 
10688 	/* for normal I/O check extract the resid values. */
10689 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
10690 		if (sensep->es_valid) {
10691 			resid =
10692 			    (sensep->es_info_1 << 24) |
10693 			    (sensep->es_info_2 << 16) |
10694 			    (sensep->es_info_3 << 8)  |
10695 			    (sensep->es_info_4);
10696 			/* If fixed block */
10697 			if (un->un_bsize) {
10698 				resid *= un->un_bsize;
10699 			}
10700 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
10701 			resid = pkt->pkt_resid;
10702 		} else {
10703 			resid = bp->b_bcount;
10704 		}
10705 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10706 		    "st_decode_sense (rw): xferred bit = %d, resid=%ld (%d), "
10707 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
10708 		    resid,
10709 		    (sensep->es_info_1 << 24) |
10710 		    (sensep->es_info_2 << 16) |
10711 		    (sensep->es_info_3 << 8)  |
10712 		    (sensep->es_info_4),
10713 		    pkt->pkt_resid);
10714 		/*
10715 		 * The problem is, what should we believe?
10716 		 */
10717 		if (resid && (pkt->pkt_resid == 0)) {
10718 			pkt->pkt_resid = resid;
10719 		}
10720 	} else {
10721 		/*
10722 		 * If the command is SCMD_SPACE, we need to get the
10723 		 * residual as returned in the sense data, to adjust
10724 		 * our idea of current tape position correctly
10725 		 */
10726 		if ((sensep->es_valid) &&
10727 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10728 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10729 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
10730 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE_G4) ||
10731 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK)) {
10732 			resid =
10733 			    (sensep->es_info_1 << 24) |
10734 			    (sensep->es_info_2 << 16) |
10735 			    (sensep->es_info_3 << 8)  |
10736 			    (sensep->es_info_4);
10737 			bp->b_resid = resid;
10738 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10739 			    "st_decode_sense(other):	resid=%ld\n", resid);
10740 		} else {
10741 			/*
10742 			 * If the special command is SCMD_READ,
10743 			 * the correct resid will be set later.
10744 			 */
10745 			if (attrib->get_cnt != NULL) {
10746 				resid = attrib->get_cnt(pkt->pkt_cdbp);
10747 			} else {
10748 				resid = bp->b_bcount;
10749 			}
10750 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10751 			    "st_decode_sense(special read):  resid=%ld\n",
10752 			    resid);
10753 		}
10754 	}
10755 
10756 	if ((un->un_state >= ST_STATE_OPEN) &&
10757 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
10758 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
10759 		    "Failed CDB", (char *)pkt->pkt_cdbp);
10760 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10761 		    "sense data", (char *)sensep, amt);
10762 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10763 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10764 		    bp->b_bcount, resid, pkt->pkt_resid);
10765 	}
10766 
10767 	switch (un->un_status = sensep->es_key) {
10768 	case KEY_NO_SENSE:
10769 		severity = SCSI_ERR_INFO;
10770 
10771 		/*
10772 		 * Erase, locate or rewind operation in progress, retry
10773 		 * ASC  ASCQ
10774 		 *  00   18    Erase operation in progress
10775 		 *  00   19    Locate operation in progress
10776 		 *  00   1A    Rewind operation in progress
10777 		 */
10778 		if (sensep->es_add_code == 0 &&
10779 		    ((sensep->es_qual_code == 0x18) ||
10780 		    (sensep->es_qual_code == 0x19) ||
10781 		    (sensep->es_qual_code == 0x1a))) {
10782 			rval = QUE_BUSY_COMMAND;
10783 			break;
10784 		}
10785 
10786 		goto common;
10787 
10788 	case KEY_RECOVERABLE_ERROR:
10789 		severity = SCSI_ERR_RECOVERED;
10790 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10791 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10792 			if (un->un_dp->options &
10793 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10794 				rval = QUE_LAST_COMMAND;
10795 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10796 				    severity, pos->lgclblkno,
10797 				    un->un_err_pos.lgclblkno, scsi_cmds,
10798 				    sensep);
10799 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10800 				    "Command will be retried\n");
10801 			} else {
10802 				severity = SCSI_ERR_FATAL;
10803 				rval = COMMAND_DONE_ERROR_RECOVERED;
10804 				ST_DO_ERRSTATS(un, st_softerrs);
10805 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10806 				    severity, pos->lgclblkno,
10807 				    un->un_err_pos.lgclblkno, scsi_cmds,
10808 				    sensep);
10809 			}
10810 			break;
10811 		}
10812 common:
10813 		/*
10814 		 * XXX only want reads to be stopped by filemarks.
10815 		 * Don't want them to be stopped by EOT.  EOT matters
10816 		 * only on write.
10817 		 */
10818 		if (sensep->es_filmk && !sensep->es_eom) {
10819 			rval = COMMAND_DONE;
10820 		} else if (sensep->es_eom) {
10821 			rval = COMMAND_DONE;
10822 		} else if (sensep->es_ili) {
10823 			/*
10824 			 * Fun with variable length record devices:
10825 			 * for specifying larger blocks sizes than the
10826 			 * actual physical record size.
10827 			 */
10828 			if (un->un_bsize == 0 && resid > 0) {
10829 				/*
10830 				 * XXX! Ugly.
10831 				 * The requested blocksize is > tape blocksize,
10832 				 * so this is ok, so we just return the
10833 				 * actual size xferred.
10834 				 */
10835 				pkt->pkt_resid = resid;
10836 				rval = COMMAND_DONE;
10837 			} else if (un->un_bsize == 0 && resid < 0) {
10838 				/*
10839 				 * The requested blocksize is < tape blocksize,
10840 				 * so this is not ok, so we err with ENOMEM
10841 				 */
10842 				rval = COMMAND_DONE_ERROR_RECOVERED;
10843 				st_bioerror(bp, ENOMEM);
10844 			} else {
10845 				ST_DO_ERRSTATS(un, st_softerrs);
10846 				severity = SCSI_ERR_FATAL;
10847 				rval = COMMAND_DONE_ERROR;
10848 				st_bioerror(bp, EINVAL);
10849 				un->un_running.pmode = invalid;
10850 			}
10851 		} else {
10852 			/*
10853 			 * we hope and pray for this just being
10854 			 * something we can ignore (ie. a
10855 			 * truly recoverable soft error)
10856 			 */
10857 			rval = COMMAND_DONE;
10858 		}
10859 		if (sensep->es_filmk) {
10860 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10861 			    "filemark\n");
10862 			un->un_status = SUN_KEY_EOF;
10863 			pos->eof = ST_EOF_PENDING;
10864 			st_set_pe_flag(un);
10865 		}
10866 
10867 		/*
10868 		 * ignore eom when reading, a fmk should terminate reading
10869 		 */
10870 		if ((sensep->es_eom) &&
10871 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10872 			if ((sensep->es_add_code == 0) &&
10873 			    (sensep->es_qual_code == 4)) {
10874 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10875 				    "bot\n");
10876 				un->un_status = SUN_KEY_BOT;
10877 				pos->eof = ST_NO_EOF;
10878 				pos->lgclblkno = 0;
10879 				pos->fileno = 0;
10880 				pos->blkno = 0;
10881 				if (pos->pmode != legacy)
10882 					pos->pmode = legacy;
10883 			} else {
10884 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10885 				    "eom\n");
10886 				un->un_status = SUN_KEY_EOT;
10887 				pos->eof = ST_EOM;
10888 			}
10889 			st_set_pe_flag(un);
10890 		}
10891 
10892 		break;
10893 
10894 	case KEY_ILLEGAL_REQUEST:
10895 
10896 		if (un->un_laststate >= ST_STATE_OPEN) {
10897 			ST_DO_ERRSTATS(un, st_softerrs);
10898 			severity = SCSI_ERR_FATAL;
10899 		} else {
10900 			severity = SCSI_ERR_INFO;
10901 		}
10902 		break;
10903 
10904 	case KEY_MEDIUM_ERROR:
10905 		ST_DO_ERRSTATS(un, st_harderrs);
10906 		severity = SCSI_ERR_FATAL;
10907 		un->un_pos.pmode = invalid;
10908 		un->un_running.pmode = invalid;
10909 check_keys:
10910 		/*
10911 		 * attempt to process the keys in the presence of
10912 		 * other errors
10913 		 */
10914 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10915 			/*
10916 			 * Fun with variable length record devices:
10917 			 * for specifying larger blocks sizes than the
10918 			 * actual physical record size.
10919 			 */
10920 			if (un->un_bsize == 0 && resid > 0) {
10921 				/*
10922 				 * XXX! Ugly
10923 				 */
10924 				pkt->pkt_resid = resid;
10925 			} else if (un->un_bsize == 0 && resid < 0) {
10926 				st_bioerror(bp, EINVAL);
10927 			} else {
10928 				severity = SCSI_ERR_FATAL;
10929 				rval = COMMAND_DONE_ERROR;
10930 				st_bioerror(bp, EINVAL);
10931 			}
10932 		}
10933 		if (sensep->es_filmk) {
10934 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10935 			    "filemark\n");
10936 			un->un_status = SUN_KEY_EOF;
10937 			pos->eof = ST_EOF_PENDING;
10938 			st_set_pe_flag(un);
10939 		}
10940 
10941 		/*
10942 		 * ignore eom when reading, a fmk should terminate reading
10943 		 */
10944 		if ((sensep->es_eom) &&
10945 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10946 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10947 			un->un_status = SUN_KEY_EOT;
10948 			pos->eof = ST_EOM;
10949 			st_set_pe_flag(un);
10950 		}
10951 
10952 		break;
10953 
10954 	case KEY_VOLUME_OVERFLOW:
10955 		ST_DO_ERRSTATS(un, st_softerrs);
10956 		pos->eof = ST_EOM;
10957 		severity = SCSI_ERR_FATAL;
10958 		rval = COMMAND_DONE_ERROR;
10959 		goto check_keys;
10960 
10961 	case KEY_HARDWARE_ERROR:
10962 		ST_DO_ERRSTATS(un, st_harderrs);
10963 		severity = SCSI_ERR_FATAL;
10964 		rval = COMMAND_DONE_ERROR;
10965 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10966 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10967 		break;
10968 
10969 	case KEY_BLANK_CHECK:
10970 		ST_DO_ERRSTATS(un, st_softerrs);
10971 		severity = SCSI_ERR_INFO;
10972 
10973 		/*
10974 		 * if not a special request and some data was xferred then it
10975 		 * it is not an error yet
10976 		 */
10977 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10978 			/*
10979 			 * no error for read with or without data xferred
10980 			 */
10981 			un->un_status = SUN_KEY_EOT;
10982 			pos->eof = ST_EOT;
10983 			rval = COMMAND_DONE_ERROR;
10984 			un->un_running.pmode = invalid;
10985 			st_set_pe_flag(un);
10986 			goto check_keys;
10987 		} else if (bp != un->un_sbufp &&
10988 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10989 			rval = COMMAND_DONE;
10990 		} else {
10991 			rval = COMMAND_DONE_ERROR_RECOVERED;
10992 		}
10993 
10994 		if (un->un_laststate >= ST_STATE_OPEN) {
10995 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10996 			    "blank check\n");
10997 			pos->eof = ST_EOM;
10998 		}
10999 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
11000 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
11001 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
11002 		    (un->un_dp->options & ST_KNOWS_EOD)) {
11003 			/*
11004 			 * we were doing a fast forward by skipping
11005 			 * multiple fmk at the time
11006 			 */
11007 			st_bioerror(bp, EIO);
11008 			severity = SCSI_ERR_RECOVERED;
11009 			rval	 = COMMAND_DONE;
11010 		}
11011 		st_set_pe_flag(un);
11012 		goto check_keys;
11013 
11014 	case KEY_WRITE_PROTECT:
11015 		if (st_wrongtapetype(un)) {
11016 			un->un_status = SUN_KEY_WRONGMEDIA;
11017 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11018 			    "wrong tape for writing- use DC6150 tape "
11019 			    "(or equivalent)\n");
11020 			severity = SCSI_ERR_UNKNOWN;
11021 		} else {
11022 			severity = SCSI_ERR_FATAL;
11023 		}
11024 		ST_DO_ERRSTATS(un, st_harderrs);
11025 		rval = COMMAND_DONE_ERROR;
11026 		st_bioerror(bp, EACCES);
11027 		break;
11028 
11029 	case KEY_UNIT_ATTENTION:
11030 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11031 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
11032 
11033 		un->un_unit_attention_flags |= 1;
11034 		/*
11035 		 * If we have detected a Bus Reset and the tape
11036 		 * drive has been reserved.
11037 		 */
11038 		if (ST_RQSENSE->es_add_code == 0x29) {
11039 			rval = DEVICE_RESET;
11040 			if ((un->un_rsvd_status &
11041 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
11042 			    ST_RESERVE) {
11043 				un->un_rsvd_status |= ST_LOST_RESERVE;
11044 				ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
11045 				    "st_decode_sense: Lost Reservation\n");
11046 			}
11047 		}
11048 
11049 		/*
11050 		 * If this is a recovery command and retrable, retry.
11051 		 */
11052 		if (bp == un->un_recov_buf) {
11053 			severity = SCSI_ERR_INFO;
11054 			if (attrib->retriable &&
11055 			    ri->pkt_retry_cnt++ < st_retry_count) {
11056 				rval = QUE_COMMAND;
11057 			} else {
11058 				rval = COMMAND_DONE_ERROR;
11059 			}
11060 			break; /* Don't set position invalid */
11061 		}
11062 
11063 		/*
11064 		 * If ST_APPLICATION_RESERVATIONS is set,
11065 		 * If the asc/ascq indicates that the reservation
11066 		 * has been cleared just allow the write to continue
11067 		 * which would force a scsi 2 reserve.
11068 		 * If preempted that persistent reservation
11069 		 * the scsi 2 reserve would get a reservation conflict.
11070 		 */
11071 		if ((un->un_rsvd_status &
11072 		    ST_APPLICATION_RESERVATIONS) != 0) {
11073 			/*
11074 			 * RESERVATIONS PREEMPTED
11075 			 * With MPxIO this could be a fail over? XXX
11076 			 */
11077 			if (ST_RQSENSE->es_add_code == 0x2a &&
11078 			    ST_RQSENSE->es_qual_code == 0x03) {
11079 				severity = SCSI_ERR_INFO;
11080 				rval = COMMAND_DONE_ERROR;
11081 				pos->pmode = invalid;
11082 				break;
11083 			/*
11084 			 * RESERVATIONS RELEASED
11085 			 */
11086 			} else if (ST_RQSENSE->es_add_code == 0x2a &&
11087 			    ST_RQSENSE->es_qual_code == 0x04) {
11088 				severity = SCSI_ERR_INFO;
11089 				rval = COMMAND_DONE;
11090 				break;
11091 			}
11092 		}
11093 
11094 		if (un->un_state <= ST_STATE_OPENING) {
11095 			/*
11096 			 * Look, the tape isn't open yet, now determine
11097 			 * if the cause is a BUS RESET, Save the file
11098 			 * and Block positions for the callers to
11099 			 * recover from the loss of position.
11100 			 */
11101 			severity = SCSI_ERR_INFO;
11102 			if ((pos->pmode != invalid) &&
11103 			    (rval == DEVICE_RESET) &&
11104 			    (un->un_restore_pos != 1)) {
11105 				un->un_save_fileno = pos->fileno;
11106 				un->un_save_blkno = pos->blkno;
11107 				un->un_restore_pos = 1;
11108 			}
11109 
11110 			if (attrib->retriable &&
11111 			    ri->pkt_retry_cnt++ < st_retry_count) {
11112 				rval = QUE_COMMAND;
11113 			} else if (rval == DEVICE_RESET) {
11114 				break;
11115 			} else {
11116 				rval = COMMAND_DONE_ERROR;
11117 			}
11118 		/*
11119 		 * Means it thinks the mode parameters have changed.
11120 		 * This is the result of a reset clearing settings or
11121 		 * another initiator changing what we set.
11122 		 */
11123 		}
11124 		if (ST_RQSENSE->es_add_code == 0x2a) {
11125 			if (ST_RQSENSE->es_qual_code == 0x1) {
11126 				/* Error recovery will modeselect and retry. */
11127 				rval = DEVICE_TAMPER;
11128 				severity = SCSI_ERR_INFO;
11129 				break; /* don't set position invalid */
11130 			}
11131 			if (ST_RQSENSE->es_qual_code == 0x0 ||
11132 			    ST_RQSENSE->es_qual_code == 0x2 ||
11133 			    ST_RQSENSE->es_qual_code == 0x3 ||
11134 			    ST_RQSENSE->es_qual_code == 0x4 ||
11135 			    ST_RQSENSE->es_qual_code == 0x5 ||
11136 			    ST_RQSENSE->es_qual_code == 0x6 ||
11137 			    ST_RQSENSE->es_qual_code == 0x7) {
11138 				rval = DEVICE_TAMPER;
11139 				severity = SCSI_ERR_INFO;
11140 			}
11141 		} else if (ST_RQSENSE->es_add_code == 0x28 &&
11142 		    ((ST_RQSENSE->es_qual_code == 0x0) ||
11143 		    ST_RQSENSE->es_qual_code == 0x5)) {
11144 			/*
11145 			 * Not Ready to Ready change, Media may have changed.
11146 			 */
11147 			rval = DEVICE_TAMPER;
11148 			severity = SCSI_ERR_RETRYABLE;
11149 		} else {
11150 			if (rval != DEVICE_RESET) {
11151 				rval = COMMAND_DONE_ERROR;
11152 			} else {
11153 				/*
11154 				 * Returning DEVICE_RESET will call
11155 				 * error recovery.
11156 				 */
11157 				severity = SCSI_ERR_INFO;
11158 				break; /* don't set position invalid */
11159 			}
11160 			/*
11161 			 * Check if it is an Unexpected Unit Attention.
11162 			 * If state is >= ST_STATE_OPEN, we have
11163 			 * already done the initialization .
11164 			 * In this case it is Fatal Error
11165 			 * since no further reading/writing
11166 			 * can be done with fileno set to < 0.
11167 			 */
11168 			if (un->un_state >= ST_STATE_OPEN) {
11169 				ST_DO_ERRSTATS(un, st_harderrs);
11170 				severity = SCSI_ERR_FATAL;
11171 			} else {
11172 				severity = SCSI_ERR_INFO;
11173 			}
11174 		}
11175 
11176 		pos->pmode = invalid;
11177 
11178 		break;
11179 
11180 	case KEY_NOT_READY:
11181 		/*
11182 		 * If in process of getting ready retry.
11183 		 */
11184 		if (sensep->es_add_code == 0x04) {
11185 			switch (sensep->es_qual_code) {
11186 			case 0x07:
11187 				/*
11188 				 * We get here when the tape is rewinding.
11189 				 * QUE_BUSY_COMMAND retries every 10 seconds.
11190 				 */
11191 				if (ri->pkt_retry_cnt++ <
11192 				    (un->un_dp->rewind_timeout / 10)) {
11193 					rval = QUE_BUSY_COMMAND;
11194 					severity = SCSI_ERR_INFO;
11195 				} else {
11196 					/* give up */
11197 					rval = COMMAND_DONE_ERROR;
11198 					severity = SCSI_ERR_FATAL;
11199 				}
11200 				break;
11201 			case 0x01:
11202 				if (ri->pkt_retry_cnt++ < st_retry_count) {
11203 					rval = QUE_COMMAND;
11204 					severity = SCSI_ERR_INFO;
11205 					break;
11206 				}
11207 			default: /* FALLTHRU */
11208 				/* give up */
11209 				rval = COMMAND_DONE_ERROR;
11210 				severity = SCSI_ERR_FATAL;
11211 			}
11212 		} else {
11213 			/* give up */
11214 			rval = COMMAND_DONE_ERROR;
11215 			severity = SCSI_ERR_FATAL;
11216 		}
11217 
11218 		/*
11219 		 * If this was an error and after device opened
11220 		 * do error stats.
11221 		 */
11222 		if (rval == COMMAND_DONE_ERROR &&
11223 		    un->un_state > ST_STATE_OPENING) {
11224 			ST_DO_ERRSTATS(un, st_harderrs);
11225 		}
11226 
11227 		if (ST_RQSENSE->es_add_code == 0x3a) {
11228 			if (st_error_level >= SCSI_ERR_FATAL)
11229 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11230 				    "Tape not inserted in drive\n");
11231 			un->un_mediastate = MTIO_EJECTED;
11232 			cv_broadcast(&un->un_state_cv);
11233 		}
11234 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
11235 		    (rval != QUE_COMMAND))
11236 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
11237 		break;
11238 
11239 	case KEY_ABORTED_COMMAND:
11240 		/* XXX Do drives return this when they see a lost light? */
11241 		/* Testing would say yes */
11242 
11243 		if (ri->pkt_retry_cnt++ < st_retry_count) {
11244 			rval = ATTEMPT_RETRY;
11245 			severity = SCSI_ERR_RETRYABLE;
11246 			goto check_keys;
11247 		}
11248 		/*
11249 		 * Probably a parity error...
11250 		 * if we retry here then this may cause data to be
11251 		 * written twice or data skipped during reading
11252 		 */
11253 		ST_DO_ERRSTATS(un, st_harderrs);
11254 		severity = SCSI_ERR_FATAL;
11255 		rval = COMMAND_DONE_ERROR;
11256 		goto check_keys;
11257 
11258 	default:
11259 		/*
11260 		 * Undecoded sense key.	 Try retries and hope
11261 		 * that will fix the problem.  Otherwise, we're
11262 		 * dead.
11263 		 */
11264 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11265 		    "Unhandled Sense Key '%s'\n",
11266 		    sense_keys[un->un_status]);
11267 		ST_DO_ERRSTATS(un, st_harderrs);
11268 		severity = SCSI_ERR_FATAL;
11269 		rval = COMMAND_DONE_ERROR;
11270 		goto check_keys;
11271 	}
11272 
11273 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
11274 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
11275 	    (un->un_laststate > ST_STATE_OPENING) &&
11276 	    (severity >= st_error_level))) {
11277 
11278 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
11279 		    pos->lgclblkno, un->un_err_pos.lgclblkno,
11280 		    scsi_cmds, sensep);
11281 		if (sensep->es_filmk) {
11282 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11283 			    "File Mark Detected\n");
11284 		}
11285 		if (sensep->es_eom) {
11286 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11287 			    "End-of-Media Detected\n");
11288 		}
11289 		if (sensep->es_ili) {
11290 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11291 			    "Incorrect Length Indicator Set\n");
11292 		}
11293 	}
11294 	get_error = geterror(bp);
11295 	if (((rval == COMMAND_DONE_ERROR) ||
11296 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
11297 	    ((get_error == EIO) || (get_error == 0))) {
11298 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
11299 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
11300 		if (un->un_rqs_state & ST_RQS_READ) {
11301 			un->un_rqs_state &= ~(ST_RQS_READ);
11302 		} else {
11303 			un->un_rqs_state |= ST_RQS_OVR;
11304 		}
11305 	}
11306 
11307 	return (rval);
11308 }
11309 
11310 
11311 static int
11312 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
11313 {
11314 	int status = TRAN_ACCEPT;
11315 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
11316 
11317 	mutex_enter(ST_MUTEX);
11318 
11319 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
11320 
11321 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11322 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
11323 
11324 	/*
11325 	 * Check to see if we hit the retry timeout. We check to make sure
11326 	 * this is the first one on the runq and make sure we have not
11327 	 * queued up any more, so this one has to be the last on the list
11328 	 * also. If it is not, we have to fail.  If it is not the first, but
11329 	 * is the last we are in trouble anyway, as we are in the interrupt
11330 	 * context here.
11331 	 */
11332 	if ((pktinfo->pkt_retry_cnt > st_retry_count) ||
11333 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
11334 		goto exit;
11335 	}
11336 
11337 	if (un->un_throttle) {
11338 		un->un_last_throttle = un->un_throttle;
11339 		un->un_throttle = 0;
11340 	}
11341 
11342 	/*
11343 	 * Here we know : bp is the first and last one on the runq
11344 	 * it is not necessary to put it back on the head of the
11345 	 * waitq and then move from waitq to runq. Save this queuing
11346 	 * and call scsi_transport.
11347 	 */
11348 	ST_CDB(ST_DEVINFO, "Retry lcmd CDB", (char *)BP_PKT(bp)->pkt_cdbp);
11349 
11350 	status = st_transport(un, BP_PKT(bp));
11351 
11352 	if (status == TRAN_ACCEPT) {
11353 		if (un->un_last_throttle) {
11354 			un->un_throttle = un->un_last_throttle;
11355 		}
11356 		mutex_exit(ST_MUTEX);
11357 
11358 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11359 		    "restart transport \n");
11360 		return (0);
11361 	}
11362 
11363 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
11364 	mutex_exit(ST_MUTEX);
11365 
11366 	if (status == TRAN_BUSY) {
11367 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
11368 			return (0);
11369 		}
11370 	}
11371 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11372 	    "restart transport rejected\n");
11373 	mutex_enter(ST_MUTEX);
11374 	ST_DO_ERRSTATS(un, st_transerrs);
11375 	if (un->un_last_throttle) {
11376 		un->un_throttle = un->un_last_throttle;
11377 	}
11378 exit:
11379 	mutex_exit(ST_MUTEX);
11380 	return (-1);
11381 }
11382 
11383 static int
11384 st_wrongtapetype(struct scsi_tape *un)
11385 {
11386 
11387 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
11388 
11389 	ASSERT(mutex_owned(ST_MUTEX));
11390 
11391 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
11392 
11393 	/*
11394 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
11395 	 */
11396 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
11397 		switch (un->un_dp->type) {
11398 		case ST_TYPE_WANGTEK:
11399 		case ST_TYPE_ARCHIVE:
11400 			/*
11401 			 * If this really worked, we could go off of
11402 			 * the density codes set in the modesense
11403 			 * page. For this drive, 0x10 == QIC-120,
11404 			 * 0xf == QIC-150, and 0x5 should be for
11405 			 * both QIC-24 and, maybe, QIC-11. However,
11406 			 * the h/w doesn't do what the manual says
11407 			 * that it should, so we'll key off of
11408 			 * getting a WRITE PROTECT error AND wp *not*
11409 			 * set in the mode sense information.
11410 			 */
11411 			/*
11412 			 * XXX but we already know that status is
11413 			 * write protect, so don't check it again.
11414 			 */
11415 
11416 			if (un->un_status == KEY_WRITE_PROTECT &&
11417 			    un->un_mspl->wp == 0) {
11418 				return (1);
11419 			}
11420 			break;
11421 		default:
11422 			break;
11423 		}
11424 	}
11425 	return (0);
11426 }
11427 
11428 static errstate
11429 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
11430 {
11431 	errstate action;
11432 	recov_info *rcvi = pkt->pkt_private;
11433 	buf_t *bp = rcvi->cmd_bp;
11434 	struct scsi_arq_status *stat = (struct scsi_arq_status *)pkt->pkt_scbp;
11435 
11436 	ST_FUNC(ST_DEVINFO, st_check_error);
11437 
11438 	ASSERT(mutex_owned(ST_MUTEX));
11439 
11440 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
11441 
11442 	switch (SCBP_C(pkt)) {
11443 	case STATUS_RESERVATION_CONFLICT:
11444 		/*
11445 		 * Command recovery is enabled, not just opening,
11446 		 * we had the drive reserved and we thing its ours.
11447 		 * Call recovery to attempt to take it back.
11448 		 */
11449 		if ((rcvi->privatelen == sizeof (recov_info)) &&
11450 		    (bp != un->un_recov_buf) &&
11451 		    (un->un_state > ST_STATE_OPEN_PENDING_IO) &&
11452 		    ((un->un_rsvd_status & (ST_RESERVE |
11453 		    ST_APPLICATION_RESERVATIONS)) != 0)) {
11454 			action = ATTEMPT_RETRY;
11455 			un->un_rsvd_status |= ST_LOST_RESERVE;
11456 		} else {
11457 			action = COMMAND_DONE_EACCES;
11458 			un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
11459 		}
11460 		break;
11461 
11462 	case STATUS_BUSY:
11463 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
11464 		if (rcvi->privatelen == sizeof (recov_info) &&
11465 		    un->un_multipath && (pkt->pkt_state == (STATE_GOT_BUS |
11466 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS))) {
11467 			/*
11468 			 * Status returned by scsi_vhci indicating path
11469 			 * has failed over.
11470 			 */
11471 			action = PATH_FAILED;
11472 			break;
11473 		}
11474 		/* FALLTHRU */
11475 	case STATUS_QFULL:
11476 		if (rcvi->privatelen == sizeof (recov_info)) {
11477 			/*
11478 			 * If recovery is inabled use it instead of
11479 			 * blind reties.
11480 			 */
11481 			action = ATTEMPT_RETRY;
11482 		} else if (rcvi->pkt_retry_cnt++ < st_retry_count) {
11483 			action = QUE_BUSY_COMMAND;
11484 		} else if ((un->un_rsvd_status &
11485 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
11486 			/*
11487 			 * If this is a command done before reserve is done
11488 			 * don't reset.
11489 			 */
11490 			action = COMMAND_DONE_ERROR;
11491 		} else {
11492 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11493 			    "unit busy too long\n");
11494 			(void) st_reset(un, RESET_ALL);
11495 			action = COMMAND_DONE_ERROR;
11496 		}
11497 		break;
11498 
11499 	case STATUS_CHECK:
11500 	case STATUS_TERMINATED:
11501 		/*
11502 		 * we should only get here if the auto rqsense failed
11503 		 * thru a uscsi cmd without autorequest sense
11504 		 * so we just try again
11505 		 */
11506 		if (un->un_arq_enabled &&
11507 		    stat->sts_rqpkt_reason == CMD_CMPLT &&
11508 		    (stat->sts_rqpkt_state & (STATE_GOT_BUS |
11509 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) ==
11510 		    (STATE_GOT_BUS | STATE_GOT_TARGET | STATE_SENT_CMD |
11511 		    STATE_GOT_STATUS)) {
11512 
11513 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11514 			    "Really got sense data\n");
11515 			action = st_decode_sense(un, bp, MAX_SENSE_LENGTH -
11516 			    pkt->pkt_resid, stat, &un->un_pos);
11517 		} else {
11518 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11519 			    "Trying to queue sense command\n");
11520 			action = QUE_SENSE;
11521 		}
11522 		break;
11523 
11524 	case STATUS_TASK_ABORT:
11525 		/*
11526 		 * This is an aborted task. This can be a reset on the other
11527 		 * port of a multiport drive. Lets try and recover it.
11528 		 */
11529 		action = DEVICE_RESET;
11530 		break;
11531 
11532 	default:
11533 		action = COMMAND_DONE;
11534 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
11535 		    "Unexpected scsi status byte 0x%x\n", SCBP_C(pkt));
11536 	}
11537 	return (action);
11538 }
11539 
11540 static void
11541 st_calc_bnum(struct scsi_tape *un, struct buf *bp, struct scsi_pkt *pkt)
11542 {
11543 	int nblks;
11544 	int nfiles;
11545 	long count;
11546 	recov_info *ri = pkt->pkt_private;
11547 	cmd_attribute const *attrib;
11548 
11549 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
11550 
11551 	ASSERT(mutex_owned(ST_MUTEX));
11552 
11553 	if (ri->privatelen == sizeof (recov_info)) {
11554 		attrib = ri->cmd_attrib;
11555 		ASSERT(attrib->recov_pos_type == POS_EXPECTED);
11556 		ASSERT(attrib->chg_tape_pos);
11557 	} else {
11558 		ri = NULL;
11559 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
11560 	}
11561 
11562 	count = bp->b_bcount - bp->b_resid;
11563 
11564 	/* Command reads or writes data */
11565 	if (attrib->transfers_data != TRAN_NONE) {
11566 		if (count == 0) {
11567 			/* failed writes should not make it here */
11568 			ASSERT(attrib->transfers_data == TRAN_READ);
11569 			nblks = 0;
11570 			nfiles = 1;
11571 		} else if (un->un_bsize == 0) {
11572 			/*
11573 			 * If variable block mode.
11574 			 * Fixed bit in CBD should be zero.
11575 			 */
11576 			ASSERT((pkt->pkt_cdbp[1] & 1) == 0);
11577 			nblks = 1;
11578 			un->un_kbytes_xferred += (count / ONE_K);
11579 			nfiles = 0;
11580 		} else {
11581 			/*
11582 			 * If fixed block mode.
11583 			 * Fixed bit in CBD should be one.
11584 			 */
11585 			ASSERT((pkt->pkt_cdbp[1] & 1) == 1);
11586 			nblks = (count / un->un_bsize);
11587 			un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
11588 			nfiles = 0;
11589 		}
11590 		/*
11591 		 * So its possable to read some blocks and hit a filemark.
11592 		 * Example reading in fixed block mode where more then one
11593 		 * block at a time is requested. In this case because the
11594 		 * filemark is hit something less then the requesed number
11595 		 * of blocks is read.
11596 		 */
11597 		if (un->un_pos.eof == ST_EOF_PENDING && bp->b_resid) {
11598 			nfiles = 1;
11599 		}
11600 	} else {
11601 		nblks = 0;
11602 		nfiles = count;
11603 	}
11604 
11605 	/*
11606 	 * If some command failed after this one started and it seems
11607 	 * to have finshed without error count the position.
11608 	 */
11609 	if (un->un_persistence && un->un_persist_errors) {
11610 		ASSERT(un->un_pos.pmode != invalid);
11611 	}
11612 
11613 	if (attrib->chg_tape_direction == DIR_FORW) {
11614 		un->un_pos.blkno += nblks;
11615 		un->un_pos.lgclblkno += nblks;
11616 		un->un_pos.lgclblkno += nfiles;
11617 	} else if (attrib->chg_tape_direction == DIR_REVC) {
11618 		un->un_pos.blkno -= nblks;
11619 		un->un_pos.lgclblkno -= nblks;
11620 		un->un_pos.lgclblkno -= nfiles;
11621 	} else {
11622 		ASSERT(0);
11623 	}
11624 
11625 	/* recovery disabled */
11626 	if (ri == NULL) {
11627 		un->un_running.pmode = invalid;
11628 		return;
11629 	}
11630 
11631 	/*
11632 	 * If we didn't just read a filemark.
11633 	 */
11634 	if (un->un_pos.eof != ST_EOF_PENDING) {
11635 		ASSERT(nblks != 0 && nfiles == 0);
11636 		/*
11637 		 * If Previously calulated expected position does not match
11638 		 * debug the expected position.
11639 		 */
11640 		if ((ri->pos.pmode != invalid) && nblks &&
11641 		    ((un->un_pos.blkno != ri->pos.blkno) ||
11642 		    (un->un_pos.lgclblkno != ri->pos.lgclblkno))) {
11643 #ifdef STDEBUG
11644 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11645 			    "Expected", &ri->pos);
11646 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11647 			    "But Got", &un->un_pos);
11648 #endif
11649 			un->un_running.pmode = invalid;
11650 		}
11651 	} else {
11652 		ASSERT(nfiles != 0);
11653 		if (un->un_running.pmode != invalid) {
11654 			/*
11655 			 * blkno and lgclblkno already counted in
11656 			 * st_add_recovery_info_to_pkt(). Since a block was not
11657 			 * read and a filemark was.
11658 			 */
11659 			if (attrib->chg_tape_direction == DIR_FORW) {
11660 				un->un_running.fileno++;
11661 				un->un_running.blkno = 0;
11662 			} else if (attrib->chg_tape_direction == DIR_REVC) {
11663 				un->un_running.fileno--;
11664 				un->un_running.blkno = LASTBLK;
11665 			}
11666 		}
11667 	}
11668 }
11669 
11670 static void
11671 st_set_state(struct scsi_tape *un, struct buf *bp)
11672 {
11673 	struct scsi_pkt *sp = BP_PKT(bp);
11674 	struct uscsi_cmd *ucmd;
11675 
11676 	ST_FUNC(ST_DEVINFO, st_set_state);
11677 
11678 	ASSERT(mutex_owned(ST_MUTEX));
11679 	ASSERT(bp != un->un_recov_buf);
11680 
11681 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11682 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
11683 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
11684 
11685 	if (bp != un->un_sbufp) {
11686 #ifdef STDEBUG
11687 		if (DEBUGGING && sp->pkt_resid) {
11688 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11689 			    "pkt_resid %ld bcount %ld\n",
11690 			    sp->pkt_resid, bp->b_bcount);
11691 		}
11692 #endif
11693 		bp->b_resid = sp->pkt_resid;
11694 		if (geterror(bp) != EIO) {
11695 			st_calc_bnum(un, bp, sp);
11696 		}
11697 		if (bp->b_flags & B_READ) {
11698 			un->un_lastop = ST_OP_READ;
11699 			un->un_fmneeded = 0;
11700 		} else {
11701 			un->un_lastop = ST_OP_WRITE;
11702 			if (un->un_dp->options & ST_REEL) {
11703 				un->un_fmneeded = 2;
11704 			} else {
11705 				un->un_fmneeded = 1;
11706 			}
11707 		}
11708 		/*
11709 		 * all is honky dory at this point, so let's
11710 		 * readjust the throttle, to increase speed, if we
11711 		 * have not throttled down.
11712 		 */
11713 		if (un->un_throttle) {
11714 			un->un_throttle = un->un_max_throttle;
11715 		}
11716 	} else {
11717 		optype new_lastop = ST_OP_NIL;
11718 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
11719 
11720 		switch (cmd) {
11721 		case SCMD_WRITE:
11722 		case SCMD_WRITE_G4:
11723 			bp->b_resid = sp->pkt_resid;
11724 			new_lastop = ST_OP_WRITE;
11725 			if (geterror(bp) == EIO) {
11726 				break;
11727 			}
11728 			st_calc_bnum(un, bp, sp);
11729 			if (un->un_dp->options & ST_REEL) {
11730 				un->un_fmneeded = 2;
11731 			} else {
11732 				un->un_fmneeded = 1;
11733 			}
11734 			break;
11735 		case SCMD_READ:
11736 		case SCMD_READ_G4:
11737 			bp->b_resid = sp->pkt_resid;
11738 			new_lastop = ST_OP_READ;
11739 			if (geterror(bp) == EIO) {
11740 				break;
11741 			}
11742 			st_calc_bnum(un, bp, sp);
11743 			un->un_fmneeded = 0;
11744 			break;
11745 		case SCMD_WRITE_FILE_MARK_G4:
11746 		case SCMD_WRITE_FILE_MARK:
11747 		{
11748 			int fmdone;
11749 
11750 			if (un->un_pos.eof != ST_EOM) {
11751 				un->un_pos.eof = ST_NO_EOF;
11752 			}
11753 			fmdone = (bp->b_bcount - bp->b_resid);
11754 			if (fmdone > 0) {
11755 				un->un_lastop = new_lastop = ST_OP_WEOF;
11756 				un->un_pos.lgclblkno += fmdone;
11757 				un->un_pos.fileno += fmdone;
11758 				un->un_pos.blkno = 0;
11759 			} else {
11760 				new_lastop = ST_OP_CTL;
11761 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11762 				    "Flushed buffer\n");
11763 			}
11764 			if (fmdone > un->un_fmneeded) {
11765 				un->un_fmneeded = 0;
11766 			} else {
11767 				un->un_fmneeded -= fmdone;
11768 			}
11769 			break;
11770 		}
11771 		case SCMD_REWIND:
11772 			un->un_pos.eof = ST_NO_EOF;
11773 			un->un_pos.fileno = 0;
11774 			un->un_pos.blkno = 0;
11775 			un->un_pos.lgclblkno = 0;
11776 			if (un->un_pos.pmode != legacy)
11777 				un->un_pos.pmode = legacy;
11778 			new_lastop = ST_OP_CTL;
11779 			un->un_restore_pos = 0;
11780 			break;
11781 
11782 		case SCMD_SPACE:
11783 		case SCMD_SPACE_G4:
11784 		{
11785 			int64_t count;
11786 			int64_t resid;
11787 			int64_t done;
11788 			cmd_attribute const *attrib;
11789 			recov_info *ri = sp->pkt_private;
11790 
11791 			if (ri->privatelen == sizeof (recov_info)) {
11792 				attrib = ri->cmd_attrib;
11793 			} else {
11794 				attrib =
11795 				    st_lookup_cmd_attribute(sp->pkt_cdbp[0]);
11796 			}
11797 
11798 			resid = (int64_t)SPACE_CNT(bp->b_resid);
11799 			count = (int64_t)attrib->get_cnt(sp->pkt_cdbp);
11800 
11801 			if (count >= 0) {
11802 				done = (count - resid);
11803 			} else {
11804 				done = ((-count) - resid);
11805 			}
11806 			if (done > 0) {
11807 				un->un_lastop = new_lastop = ST_OP_CTL;
11808 			} else {
11809 				new_lastop = ST_OP_CTL;
11810 			}
11811 
11812 			ST_SPAC(ST_DEVINFO, st_label, CE_WARN,
11813 			    "space cmd: cdb[1] = %s\n"
11814 			    "space data:       = 0x%lx\n"
11815 			    "space count:      = %"PRId64"\n"
11816 			    "space resid:      = %"PRId64"\n"
11817 			    "spaces done:      = %"PRId64"\n"
11818 			    "fileno before     = %d\n"
11819 			    "blkno before      = %d\n",
11820 			    space_strs[sp->pkt_cdbp[1] & 7],
11821 			    bp->b_bcount,
11822 			    count, resid, done,
11823 			    un->un_pos.fileno, un->un_pos.blkno);
11824 
11825 			switch (sp->pkt_cdbp[1]) {
11826 			case SPACE_TYPE(SP_FLM):
11827 				/* Space file forward */
11828 				if (count >= 0) {
11829 					if (un->un_pos.eof <= ST_EOF) {
11830 						un->un_pos.eof = ST_NO_EOF;
11831 					}
11832 					un->un_pos.fileno += done;
11833 					un->un_pos.blkno = 0;
11834 					break;
11835 				}
11836 				/* Space file backward */
11837 				if (done > un->un_pos.fileno) {
11838 					un->un_pos.fileno = 0;
11839 					un->un_pos.blkno = 0;
11840 				} else {
11841 					un->un_pos.fileno -= done;
11842 					un->un_pos.blkno = LASTBLK;
11843 					un->un_running.pmode = invalid;
11844 				}
11845 				break;
11846 			case SPACE_TYPE(SP_BLK):
11847 				/* Space block forward */
11848 				if (count >= 0) {
11849 					un->un_pos.blkno += done;
11850 					break;
11851 				}
11852 				/* Space block backward */
11853 				if (un->un_pos.eof >= ST_EOF_PENDING) {
11854 				/*
11855 				 * we stepped back into
11856 				 * a previous file; we are not
11857 				 * making an effort to pretend that
11858 				 * we are still in the current file
11859 				 * ie. logical == physical position
11860 				 * and leave it to st_ioctl to correct
11861 				 */
11862 					if (done > un->un_pos.blkno) {
11863 						un->un_pos.blkno = 0;
11864 					} else {
11865 						un->un_pos.fileno--;
11866 						un->un_pos.blkno = LASTBLK;
11867 						un->un_running.pmode = invalid;
11868 					}
11869 				} else {
11870 					un->un_pos.blkno -= done;
11871 				}
11872 				break;
11873 			case SPACE_TYPE(SP_SQFLM):
11874 				un->un_pos.pmode = logical;
11875 				un->un_pos.blkno = 0;
11876 				un->un_lastop = new_lastop = ST_OP_CTL;
11877 				break;
11878 			case SPACE_TYPE(SP_EOD):
11879 				un->un_pos.pmode = logical;
11880 				un->un_pos.eof = ST_EOM;
11881 				un->un_status = KEY_BLANK_CHECK;
11882 				break;
11883 			default:
11884 				un->un_pos.pmode = invalid;
11885 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11886 				    "Unsupported space cmd: %s\n",
11887 				    space_strs[sp->pkt_cdbp[1] & 7]);
11888 
11889 				un->un_lastop = new_lastop = ST_OP_CTL;
11890 			}
11891 
11892 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11893 			    "after_space rs %"PRId64" fil %d blk %d\n",
11894 			    resid, un->un_pos.fileno, un->un_pos.blkno);
11895 
11896 			break;
11897 		}
11898 		case SCMD_LOAD:
11899 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
11900 				un->un_pos.fileno = 0;
11901 				if (un->un_pos.pmode != legacy)
11902 					un->un_pos.pmode = legacy;
11903 			} else {
11904 				un->un_state = ST_STATE_OFFLINE;
11905 				un->un_pos.pmode = invalid;
11906 
11907 			}
11908 			/*
11909 			 * If we are loading or unloading we expect the media id
11910 			 * to change. Lets make it unknown.
11911 			 */
11912 			if (un->un_media_id != bogusID && un->un_media_id_len) {
11913 				kmem_free(un->un_media_id, un->un_media_id_len);
11914 				un->un_media_id = NULL;
11915 				un->un_media_id_len = 0;
11916 			}
11917 			un->un_density_known = 0;
11918 			un->un_pos.eof = ST_NO_EOF;
11919 			un->un_pos.blkno = 0;
11920 			un->un_lastop = new_lastop = ST_OP_CTL;
11921 			break;
11922 		case SCMD_ERASE:
11923 			un->un_pos.eof = ST_NO_EOF;
11924 			un->un_pos.blkno = 0;
11925 			un->un_pos.fileno = 0;
11926 			un->un_pos.lgclblkno = 0;
11927 			if (un->un_pos.pmode != legacy)
11928 				un->un_pos.pmode = legacy;
11929 			new_lastop = ST_OP_CTL;
11930 			break;
11931 		case SCMD_RESERVE:
11932 			un->un_rsvd_status |= ST_RESERVE;
11933 			un->un_rsvd_status &=
11934 			    ~(ST_RELEASE | ST_LOST_RESERVE |
11935 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11936 			new_lastop = ST_OP_CTL;
11937 			break;
11938 		case SCMD_RELEASE:
11939 			un->un_rsvd_status |= ST_RELEASE;
11940 			un->un_rsvd_status &=
11941 			    ~(ST_RESERVE | ST_LOST_RESERVE |
11942 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11943 			new_lastop = ST_OP_CTL;
11944 			break;
11945 		case SCMD_PERSISTENT_RESERVE_IN:
11946 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11947 			    "PGR_IN command\n");
11948 			new_lastop = ST_OP_CTL;
11949 			break;
11950 		case SCMD_PERSISTENT_RESERVE_OUT:
11951 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
11952 			case ST_SA_SCSI3_RESERVE:
11953 			case ST_SA_SCSI3_PREEMPT:
11954 			case ST_SA_SCSI3_PREEMPTANDABORT:
11955 				un->un_rsvd_status |=
11956 				    (ST_APPLICATION_RESERVATIONS | ST_RESERVE);
11957 				un->un_rsvd_status &= ~(ST_RELEASE |
11958 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11959 				    ST_INITIATED_RESET);
11960 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11961 				    "PGR Reserve and set: entering"
11962 				    " ST_APPLICATION_RESERVATIONS mode");
11963 				break;
11964 			case ST_SA_SCSI3_REGISTER:
11965 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11966 				    "PGR Reserve register key");
11967 				un->un_rsvd_status |= ST_INIT_RESERVE;
11968 				break;
11969 			case ST_SA_SCSI3_CLEAR:
11970 				un->un_rsvd_status &= ~ST_INIT_RESERVE;
11971 				/* FALLTHROUGH */
11972 			case ST_SA_SCSI3_RELEASE:
11973 				un->un_rsvd_status &=
11974 				    ~(ST_APPLICATION_RESERVATIONS | ST_RESERVE |
11975 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11976 				    ST_INITIATED_RESET);
11977 				un->un_rsvd_status |= ST_RELEASE;
11978 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11979 				    "PGR Release and reset: exiting"
11980 				    " ST_APPLICATION_RESERVATIONS mode");
11981 				break;
11982 			}
11983 			new_lastop = ST_OP_CTL;
11984 			break;
11985 		case SCMD_TEST_UNIT_READY:
11986 		case SCMD_READ_BLKLIM:
11987 		case SCMD_REQUEST_SENSE:
11988 		case SCMD_INQUIRY:
11989 		case SCMD_RECOVER_BUF:
11990 		case SCMD_MODE_SELECT:
11991 		case SCMD_MODE_SENSE:
11992 		case SCMD_DOORLOCK:
11993 		case SCMD_READ_BUFFER:
11994 		case SCMD_REPORT_DENSITIES:
11995 		case SCMD_LOG_SELECT_G1:
11996 		case SCMD_LOG_SENSE_G1:
11997 		case SCMD_REPORT_LUNS:
11998 		case SCMD_READ_ATTRIBUTE:
11999 		case SCMD_WRITE_ATTRIBUTE:
12000 		case SCMD_SVC_ACTION_IN_G5:
12001 			new_lastop = ST_OP_CTL;
12002 			break;
12003 		case SCMD_READ_POSITION:
12004 			new_lastop = ST_OP_CTL;
12005 			/*
12006 			 * Only if the buf used was un_sbufp.
12007 			 * Among other things the prevents read positions used
12008 			 * as part of error recovery from messing up our
12009 			 * current position as they will use un_recov_buf.
12010 			 */
12011 			if (USCSI_CMD(bp)) {
12012 				(void) st_get_read_pos(un, bp);
12013 			}
12014 			break;
12015 		case SCMD_LOCATE:
12016 		case SCMD_LOCATE_G4:
12017 			/* Locate makes position mode no longer legacy */
12018 			un->un_lastop = new_lastop = ST_OP_CTL;
12019 			break;
12020 		case SCMD_MAINTENANCE_IN:
12021 			switch (sp->pkt_cdbp[1]) {
12022 			case SSVC_ACTION_GET_SUPPORTED_OPERATIONS:
12023 			case SSVC_ACTION_SET_TARGET_PORT_GROUPS:
12024 				new_lastop = ST_OP_CTL;
12025 				break;
12026 			}
12027 			if (new_lastop != ST_OP_NIL) {
12028 				break;
12029 			}
12030 		default:
12031 			/*
12032 			 * Unknown command, If was USCSI and USCSI_SILENT
12033 			 * flag was not set, set position to unknown.
12034 			 */
12035 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
12036 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
12037 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
12038 				    "unknown cmd 0x%X caused loss of state\n",
12039 				    cmd);
12040 			} else {
12041 				/*
12042 				 * keep the old agreement to allow unknown
12043 				 * commands with the USCSI_SILENT set.
12044 				 * This prevents ASSERT below.
12045 				 */
12046 				new_lastop = ST_OP_CTL;
12047 				break;
12048 			}
12049 			/* FALLTHROUGH */
12050 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
12051 			un->un_pos.pmode = invalid;
12052 			un->un_lastop = new_lastop = ST_OP_CTL;
12053 			break;
12054 		}
12055 
12056 		/* new_lastop should have been changed */
12057 		ASSERT(new_lastop != ST_OP_NIL);
12058 
12059 		/* If un_lastop should copy new_lastop  */
12060 		if (((un->un_lastop == ST_OP_WRITE) ||
12061 		    (un->un_lastop == ST_OP_WEOF)) &&
12062 		    new_lastop != ST_OP_CTL) {
12063 			un->un_lastop = new_lastop;
12064 		}
12065 	}
12066 
12067 	/*
12068 	 * In the st driver we have a logical and physical file position.
12069 	 * Under BSD behavior, when you get a zero read, the logical position
12070 	 * is before the filemark but after the last record of the file.
12071 	 * The physical position is after the filemark. MTIOCGET should always
12072 	 * return the logical file position.
12073 	 *
12074 	 * The next read gives a silent skip to the next file.
12075 	 * Under SVR4, the logical file position remains before the filemark
12076 	 * until the file is closed or a space operation is performed.
12077 	 * Hence set err_resid and err_file before changing fileno if case
12078 	 * BSD Behaviour.
12079 	 */
12080 	un->un_err_resid = bp->b_resid;
12081 	COPY_POS(&un->un_err_pos, &un->un_pos);
12082 
12083 
12084 	/*
12085 	 * If we've seen a filemark via the last read operation
12086 	 * advance the file counter, but mark things such that
12087 	 * the next read operation gets a zero count. We have
12088 	 * to put this here to handle the case of sitting right
12089 	 * at the end of a tape file having seen the file mark,
12090 	 * but the tape is closed and then re-opened without
12091 	 * any further i/o. That is, the position information
12092 	 * must be updated before a close.
12093 	 */
12094 
12095 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
12096 		/*
12097 		 * If we're a 1/2" tape, and we get a filemark
12098 		 * right on block 0, *AND* we were not in the
12099 		 * first file on the tape, and we've hit logical EOM.
12100 		 * We'll mark the state so that later we do the
12101 		 * right thing (in st_close(), st_strategy() or
12102 		 * st_ioctl()).
12103 		 *
12104 		 */
12105 		if ((un->un_dp->options & ST_REEL) &&
12106 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
12107 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
12108 			un->un_pos.eof = ST_EOT_PENDING;
12109 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12110 			    "eot pending\n");
12111 			un->un_pos.fileno++;
12112 			un->un_pos.blkno = 0;
12113 		} else if (BSD_BEHAVIOR) {
12114 			/*
12115 			 * If the read of the filemark was a side effect
12116 			 * of reading some blocks (i.e., data was actually
12117 			 * read), then the EOF mark is pending and the
12118 			 * bump into the next file awaits the next read
12119 			 * operation (which will return a zero count), or
12120 			 * a close or a space operation, else the bump
12121 			 * into the next file occurs now.
12122 			 */
12123 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12124 			    "resid=%lx, bcount=%lx\n",
12125 			    bp->b_resid, bp->b_bcount);
12126 
12127 			if (bp->b_resid != bp->b_bcount) {
12128 				un->un_pos.eof = ST_EOF;
12129 			} else {
12130 				un->un_silent_skip = 1;
12131 				un->un_pos.eof = ST_NO_EOF;
12132 				un->un_pos.fileno++;
12133 				un->un_pos.lgclblkno++;
12134 				un->un_save_blkno = un->un_pos.blkno;
12135 				un->un_pos.blkno = 0;
12136 			}
12137 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12138 			    "eof of file %d, eof=%d\n",
12139 			    un->un_pos.fileno, un->un_pos.eof);
12140 		} else if (SVR4_BEHAVIOR) {
12141 			/*
12142 			 * If the read of the filemark was a side effect
12143 			 * of reading some blocks (i.e., data was actually
12144 			 * read), then the next read should return 0
12145 			 */
12146 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12147 			    "resid=%lx, bcount=%lx\n",
12148 			    bp->b_resid, bp->b_bcount);
12149 			if (bp->b_resid == bp->b_bcount) {
12150 				un->un_pos.eof = ST_EOF;
12151 			}
12152 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12153 			    "eof of file=%d, eof=%d\n",
12154 			    un->un_pos.fileno, un->un_pos.eof);
12155 		}
12156 	}
12157 }
12158 
12159 /*
12160  * set the correct un_errno, to take corner cases into consideration
12161  */
12162 static void
12163 st_set_pe_errno(struct scsi_tape *un)
12164 {
12165 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
12166 
12167 	ASSERT(mutex_owned(ST_MUTEX));
12168 
12169 	/* if errno is already set, don't reset it */
12170 	if (un->un_errno)
12171 		return;
12172 
12173 	/* here un_errno == 0 */
12174 	/*
12175 	 * if the last transfer before flushing all the
12176 	 * waiting I/O's, was 0 (resid = count), then we
12177 	 * want to give the user an error on all the rest,
12178 	 * so here.  If there was a transfer, we set the
12179 	 * resid and counts to 0, and let it drop through,
12180 	 * giving a zero return.  the next I/O will then
12181 	 * give an error.
12182 	 */
12183 	if (un->un_last_resid == un->un_last_count) {
12184 		switch (un->un_pos.eof) {
12185 		case ST_EOM:
12186 			un->un_errno = ENOMEM;
12187 			break;
12188 		case ST_EOT:
12189 		case ST_EOF:
12190 			un->un_errno = EIO;
12191 			break;
12192 		}
12193 	} else {
12194 		/*
12195 		 * we know they did not have a zero, so make
12196 		 * sure they get one
12197 		 */
12198 		un->un_last_resid = un->un_last_count = 0;
12199 	}
12200 }
12201 
12202 
12203 /*
12204  * send in a marker pkt to terminate flushing of commands by BBA (via
12205  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
12206  */
12207 static void
12208 st_hba_unflush(struct scsi_tape *un)
12209 {
12210 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
12211 
12212 	ASSERT(mutex_owned(ST_MUTEX));
12213 
12214 	if (!un->un_flush_on_errors)
12215 		return;
12216 
12217 #ifdef FLUSH_ON_ERRORS
12218 
12219 	if (!un->un_mkr_pkt) {
12220 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
12221 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
12222 
12223 		/* we slept, so it must be there */
12224 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
12225 	}
12226 
12227 	st_transport(un, un->un_mkr_pkt);
12228 #endif
12229 }
12230 
12231 static char *
12232 st_print_scsi_cmd(char cmd)
12233 {
12234 	char tmp[64];
12235 	char *cpnt;
12236 
12237 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
12238 	/* tmp goes out of scope on return and caller sees garbage */
12239 	if (cpnt == tmp) {
12240 		cpnt = "Unknown Command";
12241 	}
12242 	return (cpnt);
12243 }
12244 
12245 static void
12246 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
12247     char *title, char *cdb)
12248 {
12249 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
12250 	char buf[256];
12251 	struct scsi_tape *un;
12252 	int instance = ddi_get_instance(dip);
12253 
12254 	un = ddi_get_soft_state(st_state, instance);
12255 
12256 	ST_FUNC(dip, st_print_cdb);
12257 
12258 	/* force one line output so repeated commands are printed once */
12259 	if ((st_debug & 0x180) == 0x100) {
12260 		scsi_log(dip, label, level, "node %s cmd %s\n",
12261 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
12262 		return;
12263 	}
12264 
12265 	/* force one line output so repeated CDB's are printed once */
12266 	if ((st_debug & 0x180) == 0x80) {
12267 		st_clean_print(dip, label, level, NULL, cdb, len);
12268 	} else {
12269 		(void) sprintf(buf, "%s for cmd(%s)", title,
12270 		    st_print_scsi_cmd(*cdb));
12271 		st_clean_print(dip, label, level, buf, cdb, len);
12272 	}
12273 }
12274 
12275 static void
12276 st_clean_print(dev_info_t *dev, char *label, uint_t level,
12277     char *title, char *data, int len)
12278 {
12279 	int	i;
12280 	int 	c;
12281 	char	*format;
12282 	char	buf[256];
12283 	uchar_t	byte;
12284 
12285 	ST_FUNC(dev, st_clean_print);
12286 
12287 
12288 	if (title) {
12289 		(void) sprintf(buf, "%s:\n", title);
12290 		scsi_log(dev, label, level, "%s", buf);
12291 		level = CE_CONT;
12292 	}
12293 
12294 	for (i = 0; i < len; ) {
12295 		buf[0] = 0;
12296 		for (c = 0; c < 8 && i < len; c++, i++) {
12297 			byte = (uchar_t)data[i];
12298 			if (byte < 0x10)
12299 				format = "0x0%x ";
12300 			else
12301 				format = "0x%x ";
12302 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
12303 		}
12304 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
12305 
12306 		scsi_log(dev, label, level, "%s\n", buf);
12307 		level = CE_CONT;
12308 	}
12309 }
12310 
12311 /*
12312  * Conditionally enabled debugging
12313  */
12314 #ifdef	STDEBUG
12315 static void
12316 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
12317 {
12318 	char tmpbuf[64];
12319 
12320 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
12321 
12322 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12323 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
12324 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
12325 	    count, count,
12326 	    wait == ASYNC_CMD ? "a" : "");
12327 }
12328 #endif	/* STDEBUG */
12329 
12330 /*
12331  * Returns pointer to name of minor node name of device 'dev'.
12332  */
12333 static char *
12334 st_dev_name(dev_t dev)
12335 {
12336 	struct scsi_tape *un;
12337 	const char density[] = { 'l', 'm', 'h', 'c' };
12338 	static char name[32];
12339 	minor_t minor;
12340 	int instance;
12341 	int nprt = 0;
12342 
12343 	minor = getminor(dev);
12344 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
12345 	un = ddi_get_soft_state(st_state, instance);
12346 	if (un) {
12347 		ST_FUNC(ST_DEVINFO, st_dev_name);
12348 	}
12349 
12350 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
12351 
12352 	if (minor & MT_BSD) {
12353 		name[++nprt] = 'b';
12354 	}
12355 
12356 	if (minor & MT_NOREWIND) {
12357 		name[++nprt] = 'n';
12358 	}
12359 
12360 	/* NULL terminator */
12361 	name[++nprt] = 0;
12362 
12363 	return (name);
12364 }
12365 
12366 /*
12367  * Soft error reporting, so far unique to each drive
12368  *
12369  * Currently supported: exabyte and DAT soft error reporting
12370  */
12371 static int
12372 st_report_exabyte_soft_errors(dev_t dev, int flag)
12373 {
12374 	uchar_t *sensep;
12375 	int amt;
12376 	int rval = 0;
12377 	char cdb[CDB_GROUP0], *c = cdb;
12378 	struct uscsi_cmd *com;
12379 
12380 	GET_SOFT_STATE(dev);
12381 
12382 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
12383 
12384 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12385 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
12386 	    dev, flag);
12387 
12388 	ASSERT(mutex_owned(ST_MUTEX));
12389 
12390 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12391 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
12392 
12393 	*c++ = SCMD_REQUEST_SENSE;
12394 	*c++ = 0;
12395 	*c++ = 0;
12396 	*c++ = 0;
12397 	*c++ = TAPE_SENSE_LENGTH;
12398 	/*
12399 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
12400 	 */
12401 	*c   = (char)0x80;
12402 
12403 	com->uscsi_cdb = cdb;
12404 	com->uscsi_cdblen = CDB_GROUP0;
12405 	com->uscsi_bufaddr = (caddr_t)sensep;
12406 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
12407 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12408 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12409 
12410 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12411 	if (rval || com->uscsi_status) {
12412 		goto done;
12413 	}
12414 
12415 	/*
12416 	 * was there enough data?
12417 	 */
12418 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
12419 
12420 	if ((amt >= 19) && un->un_kbytes_xferred) {
12421 		uint_t count, error_rate;
12422 		uint_t rate;
12423 
12424 		if (sensep[21] & CLN) {
12425 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12426 			    "Periodic head cleaning required");
12427 		}
12428 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
12429 			goto done;
12430 		}
12431 		/*
12432 		 * check if soft error reporting needs to be done.
12433 		 */
12434 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
12435 		count &= 0xffffff;
12436 		error_rate = (count * 100)/un->un_kbytes_xferred;
12437 
12438 #ifdef	STDEBUG
12439 		if (st_soft_error_report_debug) {
12440 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12441 			    "Exabyte Soft Error Report:\n");
12442 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12443 			    "read/write error counter: %d\n", count);
12444 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12445 			    "number of bytes transferred: %dK\n",
12446 			    un->un_kbytes_xferred);
12447 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12448 			    "error_rate: %d%%\n", error_rate);
12449 
12450 			if (amt >= 22) {
12451 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12452 				    "unit sense: 0x%b 0x%b 0x%b\n",
12453 				    sensep[19], SENSE_19_BITS,
12454 				    sensep[20], SENSE_20_BITS,
12455 				    sensep[21], SENSE_21_BITS);
12456 			}
12457 			if (amt >= 27) {
12458 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12459 				    "tracking retry counter: %d\n",
12460 				    sensep[26]);
12461 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12462 				    "read/write retry counter: %d\n",
12463 				    sensep[27]);
12464 			}
12465 		}
12466 #endif
12467 
12468 		if (flag & FWRITE) {
12469 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
12470 		} else {
12471 			rate = EXABYTE_READ_ERROR_THRESHOLD;
12472 		}
12473 		if (error_rate >= rate) {
12474 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12475 			    "Soft error rate (%d%%) during %s was too high",
12476 			    error_rate,
12477 			    ((flag & FWRITE) ? wrg_str : rdg_str));
12478 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12479 			    "Please, replace tape cartridge\n");
12480 		}
12481 	}
12482 
12483 done:
12484 	kmem_free(com, sizeof (*com));
12485 	kmem_free(sensep, TAPE_SENSE_LENGTH);
12486 
12487 	if (rval != 0) {
12488 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12489 		    "exabyte soft error reporting failed\n");
12490 	}
12491 	return (rval);
12492 }
12493 
12494 /*
12495  * this is very specific to Archive 4mm dat
12496  */
12497 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
12498 
12499 static int
12500 st_report_dat_soft_errors(dev_t dev, int flag)
12501 {
12502 	uchar_t *sensep;
12503 	int amt, i;
12504 	int rval = 0;
12505 	char cdb[CDB_GROUP1], *c = cdb;
12506 	struct uscsi_cmd *com;
12507 	struct scsi_arq_status status;
12508 
12509 	GET_SOFT_STATE(dev);
12510 
12511 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
12512 
12513 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12514 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12515 
12516 	ASSERT(mutex_owned(ST_MUTEX));
12517 
12518 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12519 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12520 
12521 	*c++ = SCMD_LOG_SENSE_G1;
12522 	*c++ = 0;
12523 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
12524 	*c++ = 0;
12525 	*c++ = 0;
12526 	*c++ = 0;
12527 	*c++ = 2;
12528 	*c++ = 0;
12529 	*c++ = (char)LOG_SENSE_LENGTH;
12530 	*c   = 0;
12531 	com->uscsi_cdb    = cdb;
12532 	com->uscsi_cdblen  = CDB_GROUP1;
12533 	com->uscsi_bufaddr = (caddr_t)sensep;
12534 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
12535 	com->uscsi_rqlen = sizeof (status);
12536 	com->uscsi_rqbuf = (caddr_t)&status;
12537 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
12538 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12539 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12540 	if (rval) {
12541 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12542 		    "DAT soft error reporting failed\n");
12543 	}
12544 	if (rval || com->uscsi_status) {
12545 		goto done;
12546 	}
12547 
12548 	/*
12549 	 * was there enough data?
12550 	 */
12551 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
12552 
12553 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
12554 		int total, retries, param_code;
12555 
12556 		total = -1;
12557 		retries = -1;
12558 		amt = sensep[3] + 4;
12559 
12560 
12561 #ifdef STDEBUG
12562 		if (st_soft_error_report_debug) {
12563 			(void) printf("logsense:");
12564 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
12565 				if (i % 16 == 0) {
12566 					(void) printf("\t\n");
12567 				}
12568 				(void) printf(" %x", sensep[i]);
12569 			}
12570 			(void) printf("\n");
12571 		}
12572 #endif
12573 
12574 		/*
12575 		 * parse the param_codes
12576 		 */
12577 		if (sensep[0] == 2 || sensep[0] == 3) {
12578 			for (i = 4; i < amt; i++) {
12579 				param_code = (sensep[i++] << 8);
12580 				param_code += sensep[i++];
12581 				i++; /* skip control byte */
12582 				if (param_code == 5) {
12583 					if (sensep[i++] == 4) {
12584 						total = (sensep[i++] << 24);
12585 						total += (sensep[i++] << 16);
12586 						total += (sensep[i++] << 8);
12587 						total += sensep[i];
12588 					}
12589 				} else if (param_code == 0x8007) {
12590 					if (sensep[i++] == 2) {
12591 						retries = sensep[i++] << 8;
12592 						retries += sensep[i];
12593 					}
12594 				} else {
12595 					i += sensep[i];
12596 				}
12597 			}
12598 		}
12599 
12600 		/*
12601 		 * if the log sense returned valid numbers then determine
12602 		 * the read and write error thresholds based on the amount of
12603 		 * data transferred
12604 		 */
12605 
12606 		if (total > 0 && retries > 0) {
12607 			short normal_retries = 0;
12608 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12609 			    "total xferred (%s) =%x, retries=%x\n",
12610 			    ((flag & FWRITE) ? wrg_str : rdg_str),
12611 			    total, retries);
12612 
12613 			if (flag & FWRITE) {
12614 				if (total <=
12615 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
12616 					normal_retries =
12617 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
12618 				} else {
12619 					normal_retries =
12620 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
12621 				}
12622 			} else {
12623 				if (total <=
12624 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
12625 					normal_retries =
12626 					    DAT_SMALL_READ_ERROR_THRESHOLD;
12627 				} else {
12628 					normal_retries =
12629 					    DAT_LARGE_READ_ERROR_THRESHOLD;
12630 				}
12631 			}
12632 
12633 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12634 			"normal retries=%d\n", normal_retries);
12635 
12636 			if (retries >= normal_retries) {
12637 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12638 				    "Soft error rate (retries = %d) during "
12639 				    "%s was too high",  retries,
12640 				    ((flag & FWRITE) ? wrg_str : rdg_str));
12641 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12642 				    "Periodic head cleaning required "
12643 				    "and/or replace tape cartridge\n");
12644 			}
12645 
12646 		} else if (total == -1 || retries == -1) {
12647 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12648 			    "log sense parameter code does not make sense\n");
12649 		}
12650 	}
12651 
12652 	/*
12653 	 * reset all values
12654 	 */
12655 	c = cdb;
12656 	*c++ = SCMD_LOG_SELECT_G1;
12657 	*c++ = 2;	/* this resets all values */
12658 	*c++ = (char)0xc0;
12659 	*c++ = 0;
12660 	*c++ = 0;
12661 	*c++ = 0;
12662 	*c++ = 0;
12663 	*c++ = 0;
12664 	*c++ = 0;
12665 	*c   = 0;
12666 	com->uscsi_bufaddr = NULL;
12667 	com->uscsi_buflen  = 0;
12668 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
12669 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12670 	if (rval) {
12671 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12672 		    "DAT soft error reset failed\n");
12673 	}
12674 done:
12675 	kmem_free(com, sizeof (*com));
12676 	kmem_free(sensep, LOG_SENSE_LENGTH);
12677 	return (rval);
12678 }
12679 
12680 static int
12681 st_report_soft_errors(dev_t dev, int flag)
12682 {
12683 	GET_SOFT_STATE(dev);
12684 
12685 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
12686 
12687 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12688 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12689 
12690 	ASSERT(mutex_owned(ST_MUTEX));
12691 
12692 	switch (un->un_dp->type) {
12693 	case ST_TYPE_EXB8500:
12694 	case ST_TYPE_EXABYTE:
12695 		return (st_report_exabyte_soft_errors(dev, flag));
12696 		/*NOTREACHED*/
12697 	case ST_TYPE_PYTHON:
12698 		return (st_report_dat_soft_errors(dev, flag));
12699 		/*NOTREACHED*/
12700 	default:
12701 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
12702 		return (-1);
12703 	}
12704 }
12705 
12706 /*
12707  * persistent error routines
12708  */
12709 
12710 /*
12711  * enable persistent errors, and set the throttle appropriately, checking
12712  * for flush-on-errors capability
12713  */
12714 static void
12715 st_turn_pe_on(struct scsi_tape *un)
12716 {
12717 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
12718 
12719 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
12720 	ASSERT(mutex_owned(ST_MUTEX));
12721 
12722 	un->un_persistence = 1;
12723 
12724 	/*
12725 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
12726 	 * enabled.  This will simplify the error handling for request senses
12727 	 */
12728 
12729 	if (un->un_arq_enabled && un->un_untagged_qing) {
12730 		uchar_t f_o_e;
12731 
12732 		mutex_exit(ST_MUTEX);
12733 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
12734 		    1 : 0;
12735 		mutex_enter(ST_MUTEX);
12736 
12737 		un->un_flush_on_errors = f_o_e;
12738 	} else {
12739 		un->un_flush_on_errors = 0;
12740 	}
12741 
12742 	if (un->un_flush_on_errors)
12743 		un->un_max_throttle = (uchar_t)st_max_throttle;
12744 	else
12745 		un->un_max_throttle = 1;
12746 
12747 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
12748 		un->un_max_throttle = 1;
12749 
12750 	/* this will send a marker pkt */
12751 	st_clear_pe(un);
12752 }
12753 
12754 /*
12755  * This turns persistent errors permanently off
12756  */
12757 static void
12758 st_turn_pe_off(struct scsi_tape *un)
12759 {
12760 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
12761 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
12762 	ASSERT(mutex_owned(ST_MUTEX));
12763 
12764 	/* turn it off for good */
12765 	un->un_persistence = 0;
12766 
12767 	/* this will send a marker pkt */
12768 	st_clear_pe(un);
12769 
12770 	/* turn off flush on error capability, if enabled */
12771 	if (un->un_flush_on_errors) {
12772 		mutex_exit(ST_MUTEX);
12773 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
12774 		mutex_enter(ST_MUTEX);
12775 	}
12776 
12777 
12778 	un->un_flush_on_errors = 0;
12779 }
12780 
12781 /*
12782  * This clear persistent errors, allowing more commands through, and also
12783  * sending a marker packet.
12784  */
12785 static void
12786 st_clear_pe(struct scsi_tape *un)
12787 {
12788 	ST_FUNC(ST_DEVINFO, st_clear_pe);
12789 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
12790 	ASSERT(mutex_owned(ST_MUTEX));
12791 
12792 	un->un_persist_errors = 0;
12793 	un->un_throttle = un->un_last_throttle = 1;
12794 	un->un_errno = 0;
12795 	st_hba_unflush(un);
12796 }
12797 
12798 /*
12799  * This will flag persistent errors, shutting everything down, if the
12800  * application had enabled persistent errors via MTIOCPERSISTENT
12801  */
12802 static void
12803 st_set_pe_flag(struct scsi_tape *un)
12804 {
12805 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
12806 	ASSERT(mutex_owned(ST_MUTEX));
12807 
12808 	if (un->un_persistence) {
12809 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
12810 		un->un_persist_errors = 1;
12811 		un->un_throttle = un->un_last_throttle = 0;
12812 		cv_broadcast(&un->un_sbuf_cv);
12813 	}
12814 }
12815 
12816 static int
12817 st_do_reserve(struct scsi_tape *un)
12818 {
12819 	int rval;
12820 	int was_lost = un->un_rsvd_status & ST_LOST_RESERVE;
12821 
12822 	ST_FUNC(ST_DEVINFO, st_do_reserve);
12823 
12824 	/*
12825 	 * Issue a Throw-Away reserve command to clear the
12826 	 * check condition.
12827 	 * If the current behaviour of reserve/release is to
12828 	 * hold reservation across opens , and if a Bus reset
12829 	 * has been issued between opens then this command
12830 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
12831 	 * In this case return an EACCES so that user knows that
12832 	 * reservation has been lost in between opens.
12833 	 * If this error is not returned and we continue with
12834 	 * successful open , then user may think position of the
12835 	 * tape is still the same but inreality we would rewind the
12836 	 * tape and continue from BOT.
12837 	 */
12838 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12839 	if (rval) {
12840 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
12841 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
12842 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
12843 			un->un_errno = EACCES;
12844 			return (EACCES);
12845 		}
12846 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12847 	}
12848 	if (rval == 0) {
12849 		un->un_rsvd_status |= ST_INIT_RESERVE;
12850 	}
12851 	if (was_lost) {
12852 		un->un_running.pmode = invalid;
12853 	}
12854 
12855 	return (rval);
12856 }
12857 
12858 static int
12859 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb)
12860 {
12861 	int rval;
12862 	cmd_attribute const *attrib;
12863 
12864 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
12865 
12866 	/*
12867 	 * If already reserved no need to do it again.
12868 	 * Also if Reserve and Release are disabled Just return.
12869 	 */
12870 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12871 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12872 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12873 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12874 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
12875 		    st_print_scsi_cmd((uchar_t)cdb[0]));
12876 		return (0);
12877 	}
12878 
12879 	/* See if command is on the list */
12880 	attrib = st_lookup_cmd_attribute(cdb[0]);
12881 
12882 	if (attrib == NULL) {
12883 		rval = 1; /* Not found, when in doubt reserve */
12884 	} else if ((attrib->requires_reserve) != 0) {
12885 		rval = 1;
12886 	} else if ((attrib->reserve_byte) != 0) {
12887 		/*
12888 		 * cmd is on list.
12889 		 * if byte is zero always allowed.
12890 		 */
12891 		rval = 1;
12892 	} else if (((cdb[attrib->reserve_byte]) &
12893 	    (attrib->reserve_mask)) != 0) {
12894 		rval = 1;
12895 	} else {
12896 		rval = 0;
12897 	}
12898 
12899 	if (rval) {
12900 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12901 		    "Command %s requires reservation",
12902 		    st_print_scsi_cmd(cdb[0]));
12903 
12904 		rval = st_do_reserve(un);
12905 	}
12906 
12907 	return (rval);
12908 }
12909 
12910 static int
12911 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
12912 {
12913 	int rval;
12914 	cmd_attribute const *attrib;
12915 
12916 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
12917 
12918 	/*
12919 	 * Do not reserve when already reserved, when not supported or when
12920 	 * auto-rewinding on device closure.
12921 	 */
12922 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12923 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12924 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE) ||
12925 	    ((un->un_state == ST_STATE_CLOSING) && (cmd == SCMD_REWIND))) {
12926 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12927 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
12928 		    st_print_scsi_cmd(cmd));
12929 		return (0);
12930 	}
12931 
12932 	/* search for this command on the list */
12933 	attrib = st_lookup_cmd_attribute(cmd);
12934 
12935 	if (attrib == NULL) {
12936 		rval = 1; /* Not found, when in doubt reserve */
12937 	} else if ((attrib->requires_reserve) != 0) {
12938 		rval = 1;
12939 	} else if ((attrib->reserve_byte) != 0) {
12940 		/*
12941 		 * cmd is on list.
12942 		 * if byte is zero always allowed.
12943 		 */
12944 		rval = 1;
12945 	} else if (((attrib->reserve_mask) & cnt) != 0) {
12946 		rval = 1;
12947 	} else {
12948 		rval = 0;
12949 	}
12950 
12951 	if (rval) {
12952 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12953 		    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
12954 
12955 		rval = st_do_reserve(un);
12956 	}
12957 
12958 	return (rval);
12959 }
12960 
12961 static int
12962 st_reserve_release(struct scsi_tape *un, int cmd, ubufunc_t ubf)
12963 {
12964 	struct uscsi_cmd	uscsi_cmd;
12965 	int			rval;
12966 	char			cdb[CDB_GROUP0];
12967 	struct scsi_arq_status	stat;
12968 
12969 
12970 
12971 	ST_FUNC(ST_DEVINFO, st_reserve_release);
12972 
12973 	ASSERT(mutex_owned(ST_MUTEX));
12974 
12975 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12976 	    "st_reserve_release: %s \n",
12977 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
12978 
12979 	bzero(&cdb, CDB_GROUP0);
12980 	if (cmd == ST_RELEASE) {
12981 		cdb[0] = SCMD_RELEASE;
12982 	} else {
12983 		cdb[0] = SCMD_RESERVE;
12984 	}
12985 	bzero(&uscsi_cmd, sizeof (struct uscsi_cmd));
12986 	uscsi_cmd.uscsi_flags = USCSI_WRITE | USCSI_RQENABLE;
12987 	uscsi_cmd.uscsi_cdb = cdb;
12988 	uscsi_cmd.uscsi_cdblen = CDB_GROUP0;
12989 	uscsi_cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
12990 	uscsi_cmd.uscsi_rqbuf = (caddr_t)&stat;
12991 	uscsi_cmd.uscsi_rqlen = sizeof (stat);
12992 
12993 	rval = ubf(un, &uscsi_cmd, FKIOCTL);
12994 
12995 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12996 	    "st_reserve_release: rval(1)=%d\n", rval);
12997 
12998 	if (rval) {
12999 		if (uscsi_cmd.uscsi_status == STATUS_RESERVATION_CONFLICT) {
13000 			rval = EACCES;
13001 		}
13002 		/*
13003 		 * dynamically turn off reserve/release support
13004 		 * in case of drives which do not support
13005 		 * reserve/release command(ATAPI drives).
13006 		 */
13007 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
13008 			if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
13009 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
13010 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13011 				    "Tape unit does not support "
13012 				    "reserve/release \n");
13013 			}
13014 			rval = 0;
13015 		}
13016 	}
13017 	return (rval);
13018 }
13019 
13020 static int
13021 st_take_ownership(struct scsi_tape *un, ubufunc_t ubf)
13022 {
13023 	int rval;
13024 
13025 	ST_FUNC(ST_DEVINFO, st_take_ownership);
13026 
13027 	ASSERT(mutex_owned(ST_MUTEX));
13028 
13029 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13030 	    "st_take_ownership: Entering ...\n");
13031 
13032 
13033 	rval = st_reserve_release(un, ST_RESERVE, ubf);
13034 	/*
13035 	 * XXX -> Should reset be done only if we get EACCES.
13036 	 * .
13037 	 */
13038 	if (rval) {
13039 		if (st_reset(un, RESET_LUN) == 0) {
13040 			return (EIO);
13041 		}
13042 		un->un_rsvd_status &=
13043 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
13044 
13045 		mutex_exit(ST_MUTEX);
13046 		delay(drv_usectohz(ST_RESERVATION_DELAY));
13047 		mutex_enter(ST_MUTEX);
13048 		/*
13049 		 * remove the check condition.
13050 		 */
13051 		(void) st_reserve_release(un, ST_RESERVE, ubf);
13052 		rval = st_reserve_release(un, ST_RESERVE, ubf);
13053 		if (rval != 0) {
13054 			if ((st_reserve_release(un, ST_RESERVE, ubf))
13055 			    != 0) {
13056 				rval = (un->un_rsvd_status &
13057 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
13058 				return (rval);
13059 			}
13060 		}
13061 		/*
13062 		 * Set tape state to ST_STATE_OFFLINE , in case if
13063 		 * the user wants to continue and start using
13064 		 * the tape.
13065 		 */
13066 		un->un_state = ST_STATE_OFFLINE;
13067 		un->un_rsvd_status |= ST_INIT_RESERVE;
13068 	}
13069 	return (rval);
13070 }
13071 
13072 static int
13073 st_create_errstats(struct scsi_tape *un, int instance)
13074 {
13075 	char	kstatname[KSTAT_STRLEN];
13076 
13077 	ST_FUNC(ST_DEVINFO, st_create_errstats);
13078 
13079 	/*
13080 	 * Create device error kstats
13081 	 */
13082 
13083 	if (un->un_errstats == (kstat_t *)0) {
13084 		(void) sprintf(kstatname, "st%d,err", instance);
13085 		un->un_errstats = kstat_create("sterr", instance, kstatname,
13086 		    "device_error", KSTAT_TYPE_NAMED,
13087 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
13088 		    KSTAT_FLAG_PERSISTENT);
13089 
13090 		if (un->un_errstats) {
13091 			struct st_errstats	*stp;
13092 
13093 			stp = (struct st_errstats *)un->un_errstats->ks_data;
13094 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
13095 			    KSTAT_DATA_ULONG);
13096 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
13097 			    KSTAT_DATA_ULONG);
13098 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
13099 			    KSTAT_DATA_ULONG);
13100 			kstat_named_init(&stp->st_vid, "Vendor",
13101 			    KSTAT_DATA_CHAR);
13102 			kstat_named_init(&stp->st_pid, "Product",
13103 			    KSTAT_DATA_CHAR);
13104 			kstat_named_init(&stp->st_revision, "Revision",
13105 			    KSTAT_DATA_CHAR);
13106 			kstat_named_init(&stp->st_serial, "Serial No",
13107 			    KSTAT_DATA_CHAR);
13108 			un->un_errstats->ks_private = un;
13109 			un->un_errstats->ks_update = nulldev;
13110 			kstat_install(un->un_errstats);
13111 			/*
13112 			 * Fill in the static data
13113 			 */
13114 			(void) strncpy(&stp->st_vid.value.c[0],
13115 			    ST_INQUIRY->inq_vid, 8);
13116 			/*
13117 			 * XXX:  Emulex MT-02 (and emulators) predates
13118 			 *	 SCSI-1 and has no vid & pid inquiry data.
13119 			 */
13120 			if (ST_INQUIRY->inq_len != 0) {
13121 				(void) strncpy(&stp->st_pid.value.c[0],
13122 				    ST_INQUIRY->inq_pid, 16);
13123 				(void) strncpy(&stp->st_revision.value.c[0],
13124 				    ST_INQUIRY->inq_revision, 4);
13125 			}
13126 		}
13127 	}
13128 	return (0);
13129 }
13130 
13131 static int
13132 st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos)
13133 {
13134 	int rval;
13135 	bufunc_t bf = (ubf == st_uscsi_rcmd) ? st_rcmd : st_cmd;
13136 
13137 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
13138 
13139 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
13140 	ASSERT(mutex_owned(ST_MUTEX));
13141 
13142 	/* Can't restore an invalid position */
13143 	if (pos->pmode == invalid) {
13144 		return (4);
13145 	}
13146 
13147 	/*
13148 	 * Assumtions:
13149 	 *	If a position was read and is in logical position mode.
13150 	 *	If a drive supports read position it supports locate.
13151 	 *	If the read position type is not NO_POS. even though
13152 	 *	   a read position make not have been attemped yet.
13153 	 *
13154 	 *	The drive can locate to the position.
13155 	 */
13156 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
13157 		/*
13158 		 * If position mode is logical or legacy mode try
13159 		 * to locate there as it is faster.
13160 		 * If it fails try the old way.
13161 		 */
13162 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13163 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
13164 		    pos->lgclblkno);
13165 
13166 		if (st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
13167 		    pos->lgclblkno, pos->partition) == 0) {
13168 			/* Assume we are there copy rest of position back */
13169 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
13170 				COPY_POS(&un->un_pos, pos);
13171 			}
13172 			return (0);
13173 		}
13174 
13175 		/*
13176 		 * If logical block locate failed to restore a logical
13177 		 * position, can't recover.
13178 		 */
13179 		if (pos->pmode == logical) {
13180 			return (-1);
13181 		}
13182 	}
13183 
13184 
13185 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13186 	    "Restoring tape position at fileno=%x, blkno=%x....",
13187 	    pos->fileno, pos->blkno);
13188 
13189 	/*
13190 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
13191 	 * so as not to rewind tape on RESETS: Gee, Has life ever
13192 	 * been simple in tape land ?
13193 	 */
13194 	rval = bf(un, SCMD_REWIND, 0, SYNC_CMD);
13195 	if (rval) {
13196 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
13197 		    "Failed to restore the last file and block position: In"
13198 		    " this state, Tape will be loaded at BOT during next open");
13199 		un->un_pos.pmode = invalid;
13200 		return (rval);
13201 	}
13202 
13203 	/* If the position was as the result of back space file */
13204 	if (pos->blkno > (INF / 2)) {
13205 		/* Go one extra file forward */
13206 		pos->fileno++;
13207 		/* Figure how many blocks to back into the previous file */
13208 		pos->blkno = -(INF - pos->blkno);
13209 	}
13210 
13211 	/* Go to requested fileno */
13212 	if (pos->fileno) {
13213 		rval = st_cmd(un, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
13214 		if (rval) {
13215 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13216 			    "Failed to restore the last file position: In this "
13217 			    " state, Tape will be loaded at BOT during next"
13218 			    " open %d", __LINE__);
13219 			un->un_pos.pmode = invalid;
13220 			pos->pmode = invalid;
13221 			return (rval);
13222 		}
13223 	}
13224 
13225 	/*
13226 	 * If backing into a file we already did an extra file forward.
13227 	 * Now we have to back over the filemark to get to the end of
13228 	 * the previous file. The blkno has been ajusted to a negative
13229 	 * value so we will get to the expected location.
13230 	 */
13231 	if (pos->blkno) {
13232 		rval = bf(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
13233 		if (rval) {
13234 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13235 			    "Failed to restore the last file position: In this "
13236 			    " state, Tape will be loaded at BOT during next"
13237 			    " open %d", __LINE__);
13238 			un->un_pos.pmode = invalid;
13239 			pos->pmode = invalid;
13240 			return (rval);
13241 		}
13242 	}
13243 
13244 	/*
13245 	 * The position mode, block and fileno should be correct,
13246 	 * This updates eof and logical position information.
13247 	 */
13248 	un->un_pos.eof = pos->eof;
13249 	un->un_pos.lgclblkno = pos->lgclblkno;
13250 
13251 	return (0);
13252 }
13253 
13254 /*
13255  * check sense key, ASC, ASCQ in order to determine if the tape needs
13256  * to be ejected
13257  */
13258 
13259 static int
13260 st_check_asc_ascq(struct scsi_tape *un)
13261 {
13262 	struct scsi_extended_sense *sensep = ST_RQSENSE;
13263 	struct tape_failure_code   *code;
13264 
13265 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
13266 
13267 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
13268 		if ((code->key  == sensep->es_key) &&
13269 		    (code->add_code  == sensep->es_add_code) &&
13270 		    (code->qual_code == sensep->es_qual_code))
13271 			return (1);
13272 	}
13273 	return (0);
13274 }
13275 
13276 /*
13277  * st_logpage_supported() sends a Log Sense command with
13278  * page code = 0 = Supported Log Pages Page to the device,
13279  * to see whether the page 'page' is supported.
13280  * Return values are:
13281  * -1 if the Log Sense command fails
13282  * 0 if page is not supported
13283  * 1 if page is supported
13284  */
13285 
13286 static int
13287 st_logpage_supported(struct scsi_tape *un, uchar_t page)
13288 {
13289 	uchar_t *sp, *sensep;
13290 	unsigned length;
13291 	struct uscsi_cmd *com;
13292 	struct scsi_arq_status status;
13293 	int rval;
13294 	char cdb[CDB_GROUP1] = {
13295 		SCMD_LOG_SENSE_G1,
13296 		0,
13297 		SUPPORTED_LOG_PAGES_PAGE,
13298 		0,
13299 		0,
13300 		0,
13301 		0,
13302 		0,
13303 		(char)LOG_SENSE_LENGTH,
13304 		0
13305 	};
13306 
13307 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
13308 
13309 	ASSERT(mutex_owned(ST_MUTEX));
13310 
13311 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13312 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
13313 
13314 	com->uscsi_cdb = cdb;
13315 	com->uscsi_cdblen = CDB_GROUP1;
13316 	com->uscsi_bufaddr = (caddr_t)sensep;
13317 	com->uscsi_buflen = LOG_SENSE_LENGTH;
13318 	com->uscsi_rqlen = sizeof (status);
13319 	com->uscsi_rqbuf = (caddr_t)&status;
13320 	com->uscsi_flags =
13321 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13322 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13323 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13324 	if (rval || com->uscsi_status) {
13325 		/* uscsi-command failed */
13326 		rval = -1;
13327 	} else {
13328 
13329 		sp = sensep + 3;
13330 
13331 		for (length = *sp++; length > 0; length--, sp++) {
13332 
13333 			if (*sp == page) {
13334 				rval = 1;
13335 				break;
13336 			}
13337 		}
13338 	}
13339 	kmem_free(com, sizeof (struct uscsi_cmd));
13340 	kmem_free(sensep, LOG_SENSE_LENGTH);
13341 	return (rval);
13342 }
13343 
13344 
13345 /*
13346  * st_check_clean_bit() gets the status of the tape's cleaning bit.
13347  *
13348  * If the device does support the TapeAlert log page, then the cleaning bit
13349  * information will be read from this page. Otherwise we will see if one of
13350  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
13351  * the device, which means, that we can get the cleaning bit information via
13352  * a RequestSense command.
13353  * If both methods of getting cleaning bit information are not supported
13354  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
13355  * returns with
13356  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
13357  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
13358  * If the call to st_uscsi_cmd() to do the Log Sense or the Request Sense
13359  * command fails, or if the amount of Request Sense data is not enough, then
13360  *  st_check_clean_bit() returns with -1.
13361  */
13362 
13363 static int
13364 st_check_clean_bit(struct scsi_tape *un)
13365 {
13366 	int rval = 0;
13367 
13368 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
13369 
13370 	ASSERT(mutex_owned(ST_MUTEX));
13371 
13372 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
13373 		return (rval);
13374 	}
13375 
13376 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13377 
13378 		rval = st_logpage_supported(un, TAPE_SEQUENTIAL_PAGE);
13379 		if (rval == -1) {
13380 			return (0);
13381 		}
13382 		if (rval == 1) {
13383 
13384 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
13385 		}
13386 
13387 		rval = st_logpage_supported(un, TAPE_ALERT_PAGE);
13388 		if (rval == -1) {
13389 			return (0);
13390 		}
13391 		if (rval == 1) {
13392 
13393 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
13394 		}
13395 
13396 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13397 
13398 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
13399 		}
13400 	}
13401 
13402 	rval = 0;
13403 
13404 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
13405 
13406 		rval = st_check_sequential_clean_bit(un);
13407 		if (rval == -1) {
13408 			return (0);
13409 		}
13410 	}
13411 
13412 	if ((rval == 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
13413 
13414 		rval = st_check_alert_flags(un);
13415 		if (rval == -1) {
13416 			return (0);
13417 		}
13418 	}
13419 
13420 	if ((rval == 0) && (un->un_dp->options & ST_CLN_MASK)) {
13421 
13422 		rval = st_check_sense_clean_bit(un);
13423 		if (rval == -1) {
13424 			return (0);
13425 		}
13426 	}
13427 
13428 	/*
13429 	 * If found a supported means to check need to clean.
13430 	 */
13431 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
13432 
13433 		/*
13434 		 * head needs to be cleaned.
13435 		 */
13436 		if (rval & MTF_TAPE_HEAD_DIRTY) {
13437 
13438 			/*
13439 			 * Print log message only first time
13440 			 * found needing cleaned.
13441 			 */
13442 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
13443 
13444 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
13445 				    "Periodic head cleaning required");
13446 
13447 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
13448 			}
13449 
13450 		} else {
13451 
13452 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
13453 		}
13454 	}
13455 
13456 	return (rval);
13457 }
13458 
13459 
13460 static int
13461 st_check_sequential_clean_bit(struct scsi_tape *un)
13462 {
13463 	int rval;
13464 	int ix;
13465 	ushort_t parameter;
13466 	struct uscsi_cmd *cmd;
13467 	struct log_sequential_page *sp;
13468 	struct log_sequential_page_parameter *prm;
13469 	struct scsi_arq_status status;
13470 	char cdb[CDB_GROUP1] = {
13471 		SCMD_LOG_SENSE_G1,
13472 		0,
13473 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
13474 		0,
13475 		0,
13476 		0,
13477 		0,
13478 		(char)(sizeof (struct log_sequential_page) >> 8),
13479 		(char)(sizeof (struct log_sequential_page)),
13480 		0
13481 	};
13482 
13483 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
13484 
13485 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13486 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
13487 
13488 	cmd->uscsi_flags   =
13489 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13490 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13491 	cmd->uscsi_cdb	   = cdb;
13492 	cmd->uscsi_cdblen  = CDB_GROUP1;
13493 	cmd->uscsi_bufaddr = (caddr_t)sp;
13494 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
13495 	cmd->uscsi_rqlen   = sizeof (status);
13496 	cmd->uscsi_rqbuf   = (caddr_t)&status;
13497 
13498 	rval = st_uscsi_cmd(un, cmd, FKIOCTL);
13499 
13500 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
13501 
13502 		rval = -1;
13503 
13504 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
13505 
13506 		rval = -1;
13507 	}
13508 
13509 	prm = &sp->param[0];
13510 
13511 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
13512 
13513 		if (prm->log_param.length == 0) {
13514 			break;
13515 		}
13516 
13517 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
13518 		    (prm->log_param.pc_lo & 0xff));
13519 
13520 		if (parameter == SEQUENTIAL_NEED_CLN) {
13521 
13522 			rval = MTF_TAPE_CLN_SUPPORTED;
13523 			if (prm->param_value[prm->log_param.length - 1]) {
13524 
13525 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13526 				    "sequential log says head dirty\n");
13527 				rval |= MTF_TAPE_HEAD_DIRTY;
13528 			}
13529 		}
13530 		prm = (struct log_sequential_page_parameter *)
13531 		    &prm->param_value[prm->log_param.length];
13532 	}
13533 
13534 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13535 	kmem_free(sp,  sizeof (struct log_sequential_page));
13536 
13537 	return (rval);
13538 }
13539 
13540 
13541 static int
13542 st_check_alert_flags(struct scsi_tape *un)
13543 {
13544 	struct st_tape_alert *ta;
13545 	struct uscsi_cmd *com;
13546 	struct scsi_arq_status status;
13547 	unsigned ix, length;
13548 	int rval;
13549 	tape_alert_flags flag;
13550 	char cdb[CDB_GROUP1] = {
13551 		SCMD_LOG_SENSE_G1,
13552 		0,
13553 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
13554 		0,
13555 		0,
13556 		0,
13557 		0,
13558 		(char)(sizeof (struct st_tape_alert) >> 8),
13559 		(char)(sizeof (struct st_tape_alert)),
13560 		0
13561 	};
13562 
13563 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
13564 
13565 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13566 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
13567 
13568 	com->uscsi_cdb = cdb;
13569 	com->uscsi_cdblen = CDB_GROUP1;
13570 	com->uscsi_bufaddr = (caddr_t)ta;
13571 	com->uscsi_buflen = sizeof (struct st_tape_alert);
13572 	com->uscsi_rqlen = sizeof (status);
13573 	com->uscsi_rqbuf = (caddr_t)&status;
13574 	com->uscsi_flags =
13575 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13576 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13577 
13578 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13579 
13580 	if (rval || com->uscsi_status || com->uscsi_resid) {
13581 
13582 		rval = -1; /* uscsi-command failed */
13583 
13584 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
13585 
13586 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13587 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
13588 		rval = -1;
13589 	}
13590 
13591 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
13592 
13593 
13594 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
13595 
13596 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13597 		    "TapeAlert length %d\n", length);
13598 	}
13599 
13600 
13601 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
13602 
13603 		/*
13604 		 * if rval is bad before the first pass don't bother
13605 		 */
13606 		if (ix == 0 && rval != 0) {
13607 
13608 			break;
13609 		}
13610 
13611 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
13612 		    ta->param[ix].log_param.pc_lo);
13613 
13614 		if ((ta->param[ix].param_value & 1) == 0) {
13615 			continue;
13616 		}
13617 		/*
13618 		 * check to see if current parameter is of interest.
13619 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
13620 		 */
13621 		if ((flag == TAF_CLEAN_NOW) ||
13622 		    (flag == TAF_CLEAN_PERIODIC) ||
13623 		    ((flag == CLEAN_FOR_ERRORS) &&
13624 		    (un->un_dp->type == ST_TYPE_STK9840))) {
13625 
13626 			rval = MTF_TAPE_CLN_SUPPORTED;
13627 
13628 
13629 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13630 			    "alert_page drive needs clean %d\n", flag);
13631 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
13632 			rval |= MTF_TAPE_HEAD_DIRTY;
13633 
13634 		} else if (flag == TAF_CLEANING_MEDIA) {
13635 
13636 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13637 			    "alert_page drive was cleaned\n");
13638 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
13639 		}
13640 
13641 	}
13642 
13643 	/*
13644 	 * Report it as dirty till we see it cleaned
13645 	 */
13646 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
13647 
13648 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13649 		    "alert_page still dirty\n");
13650 		rval |= MTF_TAPE_HEAD_DIRTY;
13651 	}
13652 
13653 	kmem_free(com, sizeof (struct uscsi_cmd));
13654 	kmem_free(ta,  sizeof (struct st_tape_alert));
13655 
13656 	return (rval);
13657 }
13658 
13659 
13660 static int
13661 st_check_sense_clean_bit(struct scsi_tape *un)
13662 {
13663 	uchar_t *sensep;
13664 	char cdb[CDB_GROUP0];
13665 	struct uscsi_cmd *com;
13666 	ushort_t byte_pos;
13667 	uchar_t bit_mask;
13668 	unsigned length;
13669 	int index;
13670 	int rval;
13671 
13672 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
13673 
13674 	/*
13675 	 * Since this tape does not support Tape Alert,
13676 	 * we now try to get the cleanbit status via
13677 	 * Request Sense.
13678 	 */
13679 
13680 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
13681 
13682 		index = 0;
13683 
13684 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
13685 
13686 		index = 1;
13687 
13688 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
13689 
13690 		index = 2;
13691 
13692 	} else {
13693 
13694 		return (-1);
13695 	}
13696 
13697 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
13698 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
13699 	length = byte_pos + 1;
13700 
13701 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13702 	sensep = kmem_zalloc(length, KM_SLEEP);
13703 
13704 	cdb[0] = SCMD_REQUEST_SENSE;
13705 	cdb[1] = 0;
13706 	cdb[2] = 0;
13707 	cdb[3] = 0;
13708 	cdb[4] = (char)length;
13709 	cdb[5] = 0;
13710 
13711 	com->uscsi_cdb = cdb;
13712 	com->uscsi_cdblen = CDB_GROUP0;
13713 	com->uscsi_bufaddr = (caddr_t)sensep;
13714 	com->uscsi_buflen = length;
13715 	com->uscsi_flags =
13716 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13717 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13718 
13719 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13720 
13721 	if (rval || com->uscsi_status || com->uscsi_resid) {
13722 
13723 		rval = -1;
13724 
13725 	} else {
13726 
13727 		rval = MTF_TAPE_CLN_SUPPORTED;
13728 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
13729 
13730 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13731 			    "sense data says head dirty\n");
13732 			rval |= MTF_TAPE_HEAD_DIRTY;
13733 		}
13734 	}
13735 
13736 	kmem_free(com, sizeof (struct uscsi_cmd));
13737 	kmem_free(sensep, length);
13738 	return (rval);
13739 }
13740 
13741 /*
13742  * st_clear_unit_attention
13743  *
13744  *  	run test unit ready's to clear out outstanding
13745  * 	unit attentions.
13746  * 	returns zero for SUCCESS or the errno from st_cmd call
13747  */
13748 static int
13749 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
13750 {
13751 	int	i    = 0;
13752 	int	rval;
13753 
13754 	GET_SOFT_STATE(dev_instance);
13755 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
13756 
13757 	do {
13758 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
13759 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
13760 	return (rval);
13761 }
13762 
13763 static void
13764 st_calculate_timeouts(struct scsi_tape *un)
13765 {
13766 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
13767 
13768 	if (un->un_dp->non_motion_timeout == 0) {
13769 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13770 			un->un_dp->non_motion_timeout =
13771 			    st_io_time * st_long_timeout_x;
13772 		} else {
13773 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
13774 		}
13775 	}
13776 
13777 	if (un->un_dp->io_timeout == 0) {
13778 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13779 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
13780 		} else {
13781 			un->un_dp->io_timeout = (ushort_t)st_io_time;
13782 		}
13783 	}
13784 
13785 	if (un->un_dp->rewind_timeout == 0) {
13786 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13787 			un->un_dp->rewind_timeout =
13788 			    st_space_time * st_long_timeout_x;
13789 		} else {
13790 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
13791 		}
13792 	}
13793 
13794 	if (un->un_dp->space_timeout == 0) {
13795 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13796 			un->un_dp->space_timeout =
13797 			    st_space_time * st_long_timeout_x;
13798 		} else {
13799 			un->un_dp->space_timeout = (ushort_t)st_space_time;
13800 		}
13801 	}
13802 
13803 	if (un->un_dp->load_timeout == 0) {
13804 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13805 			un->un_dp->load_timeout =
13806 			    st_space_time * st_long_timeout_x;
13807 		} else {
13808 			un->un_dp->load_timeout = (ushort_t)st_space_time;
13809 		}
13810 	}
13811 
13812 	if (un->un_dp->unload_timeout == 0) {
13813 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13814 			un->un_dp->unload_timeout =
13815 			    st_space_time * st_long_timeout_x;
13816 		} else {
13817 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
13818 		}
13819 	}
13820 
13821 	if (un->un_dp->erase_timeout == 0) {
13822 		if (un->un_dp->options & ST_LONG_ERASE) {
13823 			un->un_dp->erase_timeout =
13824 			    st_space_time * st_long_space_time_x;
13825 		} else {
13826 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
13827 		}
13828 	}
13829 }
13830 
13831 
13832 static writablity
13833 st_is_not_wormable(struct scsi_tape *un)
13834 {
13835 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
13836 	return (RDWR);
13837 }
13838 
13839 static writablity
13840 st_is_hp_dat_tape_worm(struct scsi_tape *un)
13841 {
13842 	writablity wrt;
13843 
13844 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
13845 
13846 	/* Mode sense should be current */
13847 	if (un->un_mspl->media_type == 1) {
13848 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13849 		    "Drive has WORM media loaded\n");
13850 		wrt = WORM;
13851 	} else {
13852 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13853 		    "Drive has non WORM media loaded\n");
13854 		wrt = RDWR;
13855 	}
13856 	return (wrt);
13857 }
13858 
13859 #define	HP_DAT_INQUIRY 0x4A
13860 static writablity
13861 st_is_hp_dat_worm(struct scsi_tape *un)
13862 {
13863 	char *buf;
13864 	int result;
13865 	writablity wrt;
13866 
13867 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
13868 
13869 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
13870 
13871 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
13872 
13873 	if (result != 0) {
13874 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13875 		    "Read Standard Inquiry for WORM support failed");
13876 		wrt = FAILED;
13877 	} else if ((buf[40] & 1) == 0) {
13878 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13879 		    "Drive is NOT WORMable\n");
13880 		/* This drive doesn't support it so don't check again */
13881 		un->un_dp->options &= ~ST_WORMABLE;
13882 		wrt = RDWR;
13883 		un->un_wormable = st_is_not_wormable;
13884 	} else {
13885 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13886 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13887 		un->un_wormable = st_is_hp_dat_tape_worm;
13888 		wrt = un->un_wormable(un);
13889 	}
13890 
13891 	kmem_free(buf, HP_DAT_INQUIRY);
13892 
13893 	/*
13894 	 * If drive doesn't support it no point in checking further.
13895 	 */
13896 	return (wrt);
13897 }
13898 
13899 static writablity
13900 st_is_hp_lto_tape_worm(struct scsi_tape *un)
13901 {
13902 	writablity wrt;
13903 
13904 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
13905 
13906 	/* Mode sense should be current */
13907 	switch (un->un_mspl->media_type) {
13908 	case 0x00:
13909 		switch (un->un_mspl->density) {
13910 		case 0x40:
13911 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13912 			    "Drive has standard Gen I media loaded\n");
13913 			break;
13914 		case 0x42:
13915 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13916 			    "Drive has standard Gen II media loaded\n");
13917 			break;
13918 		case 0x44:
13919 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13920 			    "Drive has standard Gen III media loaded\n");
13921 			break;
13922 		case 0x46:
13923 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13924 			    "Drive has standard Gen IV media loaded\n");
13925 			break;
13926 		default:
13927 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13928 			    "Drive has standard unknown 0x%X media loaded\n",
13929 			    un->un_mspl->density);
13930 		}
13931 		wrt = RDWR;
13932 		break;
13933 	case 0x01:
13934 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13935 		    "Drive has WORM medium loaded\n");
13936 		wrt = WORM;
13937 		break;
13938 	case 0x80:
13939 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13940 		    "Drive has CD-ROM emulation medium loaded\n");
13941 		wrt = WORM;
13942 		break;
13943 	default:
13944 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13945 		    "Drive has an unexpected medium type 0x%X loaded\n",
13946 		    un->un_mspl->media_type);
13947 		wrt = RDWR;
13948 	}
13949 
13950 	return (wrt);
13951 }
13952 
13953 #define	LTO_REQ_INQUIRY 44
13954 static writablity
13955 st_is_hp_lto_worm(struct scsi_tape *un)
13956 {
13957 	char *buf;
13958 	int result;
13959 	writablity wrt;
13960 
13961 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
13962 
13963 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
13964 
13965 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
13966 
13967 	if (result != 0) {
13968 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13969 		    "Read Standard Inquiry for WORM support failed");
13970 		wrt = FAILED;
13971 	} else if ((buf[40] & 1) == 0) {
13972 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13973 		    "Drive is NOT WORMable\n");
13974 		/* This drive doesn't support it so don't check again */
13975 		un->un_dp->options &= ~ST_WORMABLE;
13976 		wrt = RDWR;
13977 		un->un_wormable = st_is_not_wormable;
13978 	} else {
13979 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13980 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13981 		un->un_wormable = st_is_hp_lto_tape_worm;
13982 		wrt = un->un_wormable(un);
13983 	}
13984 
13985 	kmem_free(buf, LTO_REQ_INQUIRY);
13986 
13987 	/*
13988 	 * If drive doesn't support it no point in checking further.
13989 	 */
13990 	return (wrt);
13991 }
13992 
13993 static writablity
13994 st_is_t10_worm_device(struct scsi_tape *un)
13995 {
13996 	writablity wrt;
13997 
13998 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
13999 
14000 	if (un->un_mspl->media_type == 0x3c) {
14001 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14002 		    "Drive has WORM media loaded\n");
14003 		wrt = WORM;
14004 	} else {
14005 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14006 		    "Drive has non WORM media loaded\n");
14007 		wrt = RDWR;
14008 	}
14009 	return (wrt);
14010 }
14011 
14012 #define	SEQ_CAP_PAGE	(char)0xb0
14013 static writablity
14014 st_is_t10_worm(struct scsi_tape *un)
14015 {
14016 	char *buf;
14017 	int result;
14018 	writablity wrt;
14019 
14020 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
14021 
14022 	buf = kmem_zalloc(6, KM_SLEEP);
14023 
14024 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
14025 
14026 	if (result != 0) {
14027 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14028 		    "Read Vitial Inquiry for Sequental Capability"
14029 		    " WORM support failed %x", result);
14030 		wrt = FAILED;
14031 	} else if ((buf[4] & 1) == 0) {
14032 		ASSERT(buf[1] == SEQ_CAP_PAGE);
14033 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14034 		    "Drive is NOT WORMable\n");
14035 		/* This drive doesn't support it so don't check again */
14036 		un->un_dp->options &= ~ST_WORMABLE;
14037 		wrt = RDWR;
14038 		un->un_wormable = st_is_not_wormable;
14039 	} else {
14040 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14041 		    "Drive supports WORM\n");
14042 		un->un_wormable = st_is_t10_worm_device;
14043 		wrt = un->un_wormable(un);
14044 	}
14045 
14046 	kmem_free(buf, 6);
14047 
14048 	return (wrt);
14049 }
14050 
14051 
14052 #define	STK_REQ_SENSE 26
14053 
14054 static writablity
14055 st_is_stk_worm(struct scsi_tape *un)
14056 {
14057 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
14058 	struct scsi_extended_sense *sense;
14059 	struct uscsi_cmd *cmd;
14060 	char *buf;
14061 	int result;
14062 	writablity wrt;
14063 
14064 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
14065 
14066 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14067 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
14068 	sense = (struct scsi_extended_sense *)buf;
14069 
14070 	cmd->uscsi_flags = USCSI_READ;
14071 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14072 	cmd->uscsi_cdb = &cdb[0];
14073 	cmd->uscsi_bufaddr = buf;
14074 	cmd->uscsi_buflen = STK_REQ_SENSE;
14075 	cmd->uscsi_cdblen = CDB_GROUP0;
14076 	cmd->uscsi_rqlen = 0;
14077 	cmd->uscsi_rqbuf = NULL;
14078 
14079 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14080 
14081 	if (result != 0 || cmd->uscsi_status != 0) {
14082 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14083 		    "Request Sense for WORM failed");
14084 		wrt = RDWR;
14085 	} else if (sense->es_add_len + 8 < 24) {
14086 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14087 		    "Drive didn't send enough sense data for WORM byte %d\n",
14088 		    sense->es_add_len + 8);
14089 		wrt = RDWR;
14090 		un->un_wormable = st_is_not_wormable;
14091 	} else if ((buf[24]) & 0x02) {
14092 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14093 		    "Drive has WORM tape loaded\n");
14094 		wrt = WORM;
14095 		un->un_wormable = st_is_stk_worm;
14096 	} else {
14097 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14098 		    "Drive has normal tape loaded\n");
14099 		wrt = RDWR;
14100 		un->un_wormable = st_is_stk_worm;
14101 	}
14102 
14103 	kmem_free(buf, STK_REQ_SENSE);
14104 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14105 	return (wrt);
14106 }
14107 
14108 #define	DLT_INQ_SZ 44
14109 
14110 static writablity
14111 st_is_dlt_tape_worm(struct scsi_tape *un)
14112 {
14113 	caddr_t buf;
14114 	int result;
14115 	writablity wrt;
14116 
14117 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
14118 
14119 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14120 
14121 	/* Read Attribute Media Type */
14122 
14123 	result = st_read_attributes(un, 0x0408, buf, 10, st_uscsi_cmd);
14124 
14125 	/*
14126 	 * If this quantum drive is attached via an HBA that cannot
14127 	 * support thr read attributes command return error in the
14128 	 * hope that someday they will support the t10 method.
14129 	 */
14130 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
14131 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14132 		    "Read Attribute Command for WORM Media detection is not "
14133 		    "supported on the HBA that this drive is attached to.");
14134 		wrt = RDWR;
14135 		un->un_wormable = st_is_not_wormable;
14136 		goto out;
14137 	}
14138 
14139 	if (result != 0) {
14140 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14141 		    "Read Attribute Command for WORM Media returned 0x%x",
14142 		    result);
14143 		wrt = RDWR;
14144 		un->un_dp->options &= ~ST_WORMABLE;
14145 		goto out;
14146 	}
14147 
14148 	if ((uchar_t)buf[9] == 0x80) {
14149 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14150 		    "Drive media is WORM\n");
14151 		wrt = WORM;
14152 	} else {
14153 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14154 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
14155 		wrt = RDWR;
14156 	}
14157 
14158 out:
14159 	kmem_free(buf, DLT_INQ_SZ);
14160 	return (wrt);
14161 }
14162 
14163 static writablity
14164 st_is_dlt_worm(struct scsi_tape *un)
14165 {
14166 	caddr_t buf;
14167 	int result;
14168 	writablity wrt;
14169 
14170 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
14171 
14172 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14173 
14174 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
14175 
14176 	if (result != 0) {
14177 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14178 		    "Read Vendor Specific Inquiry for WORM support failed");
14179 		wrt = RDWR;
14180 		goto out;
14181 	}
14182 
14183 	if ((buf[2] & 1) == 0) {
14184 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14185 		    "Drive is not WORMable\n");
14186 		wrt = RDWR;
14187 		un->un_dp->options &= ~ST_WORMABLE;
14188 		un->un_wormable = st_is_not_wormable;
14189 		goto out;
14190 	} else {
14191 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14192 		    "Drive is WORMable\n");
14193 		un->un_wormable = st_is_dlt_tape_worm;
14194 		wrt = un->un_wormable(un);
14195 	}
14196 out:
14197 	kmem_free(buf, DLT_INQ_SZ);
14198 
14199 	return (wrt);
14200 }
14201 
14202 typedef struct {
14203 	struct modeheader_seq header;
14204 #if defined(_BIT_FIELDS_LTOH) /* X86 */
14205 	uchar_t pagecode	:6,
14206 				:2;
14207 	uchar_t page_len;
14208 	uchar_t syslogalive	:2,
14209 		device		:1,
14210 		abs		:1,
14211 		ulpbot		:1,
14212 		prth		:1,
14213 		ponej		:1,
14214 		ait		:1;
14215 	uchar_t span;
14216 
14217 	uchar_t			:6,
14218 		worm		:1,
14219 		mic		:1;
14220 	uchar_t worm_cap	:1,
14221 				:7;
14222 	uint32_t		:32;
14223 #else /* SPARC */
14224 	uchar_t			:2,
14225 		pagecode	:6;
14226 	uchar_t page_len;
14227 	uchar_t ait		:1,
14228 		device		:1,
14229 		abs		:1,
14230 		ulpbot		:1,
14231 		prth		:1,
14232 		ponej		:1,
14233 		syslogalive	:2;
14234 	uchar_t span;
14235 	uchar_t mic		:1,
14236 		worm		:1,
14237 				:6;
14238 	uchar_t			:7,
14239 		worm_cap	:1;
14240 	uint32_t		:32;
14241 #endif
14242 }ait_dev_con;
14243 
14244 #define	AIT_DEV_PAGE 0x31
14245 static writablity
14246 st_is_sony_worm(struct scsi_tape *un)
14247 {
14248 	int result;
14249 	writablity wrt;
14250 	ait_dev_con *ait_conf;
14251 
14252 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14253 
14254 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
14255 
14256 	result = st_gen_mode_sense(un, st_uscsi_cmd, AIT_DEV_PAGE,
14257 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
14258 
14259 	if (result == 0) {
14260 
14261 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
14262 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14263 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
14264 			    ait_conf->pagecode, AIT_DEV_PAGE);
14265 			wrt = RDWR;
14266 			un->un_wormable = st_is_not_wormable;
14267 
14268 		} else if (ait_conf->worm_cap) {
14269 
14270 			un->un_wormable = st_is_sony_worm;
14271 
14272 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14273 			    "Drives is WORMable\n");
14274 			if (ait_conf->worm) {
14275 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14276 				    "Media is WORM\n");
14277 				wrt = WORM;
14278 			} else {
14279 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14280 				    "Media is not WORM\n");
14281 				wrt = RDWR;
14282 			}
14283 
14284 		} else {
14285 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14286 			    "Drives not is WORMable\n");
14287 			wrt = RDWR;
14288 			/* No further checking required */
14289 			un->un_dp->options &= ~ST_WORMABLE;
14290 		}
14291 
14292 	} else {
14293 
14294 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14295 		    "AIT device config mode sense page read command failed"
14296 		    " result = %d ", result);
14297 		wrt = FAILED;
14298 		un->un_wormable = st_is_not_wormable;
14299 	}
14300 
14301 	kmem_free(ait_conf, sizeof (ait_dev_con));
14302 	return (wrt);
14303 }
14304 
14305 static writablity
14306 st_is_drive_worm(struct scsi_tape *un)
14307 {
14308 	writablity wrt;
14309 
14310 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14311 
14312 	switch (un->un_dp->type) {
14313 	case MT_ISDLT:
14314 		wrt = st_is_dlt_worm(un);
14315 		break;
14316 
14317 	case MT_ISSTK9840:
14318 		wrt = st_is_stk_worm(un);
14319 		break;
14320 
14321 	case MT_IS8MM:
14322 	case MT_ISAIT:
14323 		wrt = st_is_sony_worm(un);
14324 		break;
14325 
14326 	case MT_LTO:
14327 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14328 			wrt = st_is_hp_lto_worm(un);
14329 		} else {
14330 			wrt = st_is_t10_worm(un);
14331 		}
14332 		break;
14333 
14334 	case MT_ISDAT:
14335 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14336 			wrt = st_is_hp_dat_worm(un);
14337 		} else {
14338 			wrt = st_is_t10_worm(un);
14339 		}
14340 		break;
14341 
14342 	default:
14343 		wrt = FAILED;
14344 		break;
14345 	}
14346 
14347 	/*
14348 	 * If any of the above failed try the t10 standard method.
14349 	 */
14350 	if (wrt == FAILED) {
14351 		wrt = st_is_t10_worm(un);
14352 	}
14353 
14354 	/*
14355 	 * Unknown method for detecting WORM media.
14356 	 */
14357 	if (wrt == FAILED) {
14358 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14359 		    "Unknown method for WORM media detection\n");
14360 		wrt = RDWR;
14361 		un->un_dp->options &= ~ST_WORMABLE;
14362 	}
14363 
14364 	return (wrt);
14365 }
14366 
14367 static int
14368 st_read_attributes(struct scsi_tape *un, uint16_t attribute, void *pnt,
14369     size_t size, ubufunc_t bufunc)
14370 {
14371 	char cdb[CDB_GROUP4];
14372 	int result;
14373 	struct uscsi_cmd *cmd;
14374 	struct scsi_arq_status status;
14375 
14376 	caddr_t buf = (caddr_t)pnt;
14377 
14378 	ST_FUNC(ST_DEVINFO, st_read_attributes);
14379 
14380 	if (un->un_sd->sd_inq->inq_ansi < 3) {
14381 		return (ENOTTY);
14382 	}
14383 
14384 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14385 
14386 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
14387 	cdb[1] = 0;
14388 	cdb[2] = 0;
14389 	cdb[3] = 0;
14390 	cdb[4] = 0;
14391 	cdb[5] = 0;
14392 	cdb[6] = 0;
14393 	cdb[7] = 0;
14394 	cdb[8] = (char)(attribute >> 8);
14395 	cdb[9] = (char)(attribute);
14396 	cdb[10] = (char)(size >> 24);
14397 	cdb[11] = (char)(size >> 16);
14398 	cdb[12] = (char)(size >> 8);
14399 	cdb[13] = (char)(size);
14400 	cdb[14] = 0;
14401 	cdb[15] = 0;
14402 
14403 
14404 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE | USCSI_DIAGNOSE;
14405 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14406 	cmd->uscsi_cdb = &cdb[0];
14407 	cmd->uscsi_bufaddr = (caddr_t)buf;
14408 	cmd->uscsi_buflen = size;
14409 	cmd->uscsi_cdblen = sizeof (cdb);
14410 	cmd->uscsi_rqlen = sizeof (status);
14411 	cmd->uscsi_rqbuf = (caddr_t)&status;
14412 
14413 	result = bufunc(un, cmd, FKIOCTL);
14414 
14415 	if (result != 0 || cmd->uscsi_status != 0) {
14416 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
14417 		    "st_read_attribute failed: result %d status %d\n",
14418 		    result, cmd->uscsi_status);
14419 		/*
14420 		 * If this returns invalid operation code don't try again.
14421 		 */
14422 		if (un->un_sd->sd_sense->es_key == KEY_ILLEGAL_REQUEST &&
14423 		    un->un_sd->sd_sense->es_add_code == 0x20) {
14424 			result = ENOTTY;
14425 		} else if (result == 0) {
14426 			result = EIO;
14427 		}
14428 
14429 	} else {
14430 
14431 		/*
14432 		 * The attribute retured should match the attribute requested.
14433 		 */
14434 		if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
14435 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14436 			    "st_read_attribute got wrong data back expected "
14437 			    "0x%x got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
14438 			st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14439 			    "bad? data", buf, size);
14440 			result = EIO;
14441 		}
14442 	}
14443 
14444 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14445 
14446 	return (result);
14447 }
14448 
14449 static int
14450 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
14451     uchar_t page)
14452 {
14453 	char cdb[CDB_GROUP0];
14454 	struct scsi_extended_sense *sense;
14455 	struct uscsi_cmd *cmd;
14456 	int result;
14457 
14458 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
14459 
14460 	cdb[0] = SCMD_INQUIRY;
14461 	cdb[1] = page ? 1 : 0;
14462 	cdb[2] = page;
14463 	cdb[3] = 0;
14464 	cdb[4] = size;
14465 	cdb[5] = 0;
14466 
14467 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14468 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
14469 
14470 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
14471 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14472 	cmd->uscsi_cdb = &cdb[0];
14473 	cmd->uscsi_bufaddr = dest;
14474 	cmd->uscsi_buflen = size;
14475 	cmd->uscsi_cdblen = CDB_GROUP0;
14476 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
14477 	cmd->uscsi_rqbuf = (caddr_t)sense;
14478 
14479 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14480 
14481 	if (result != 0 || cmd->uscsi_status != 0) {
14482 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14483 		    "st_get_special_inquiry() failed for page %x", page);
14484 		if (result == 0) {
14485 			result = EIO;
14486 		}
14487 	}
14488 
14489 	kmem_free(sense, sizeof (struct scsi_extended_sense));
14490 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14491 
14492 	return (result);
14493 }
14494 
14495 
14496 static int
14497 st_update_block_pos(struct scsi_tape *un, bufunc_t bf, int post_space)
14498 {
14499 	int rval = ENOTTY;
14500 	uchar_t status = un->un_status;
14501 	posmode previous_pmode = un->un_running.pmode;
14502 
14503 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
14504 
14505 	while (un->un_read_pos_type != NO_POS) {
14506 		rval = bf(un, SCMD_READ_POSITION, 32, SYNC_CMD);
14507 
14508 		/*
14509 		 * If read position command returned good status
14510 		 * Parse the data to see if the position can be interpreted.
14511 		 */
14512 		if ((rval == 0) &&
14513 		    ((rval = st_interpret_read_pos(un, &un->un_pos,
14514 		    un->un_read_pos_type, 32, (caddr_t)un->un_read_pos_data,
14515 		    post_space)) == 0)) {
14516 			/*
14517 			 * Update the running position as well if un_pos was
14518 			 * ok. But only if recovery is enabled.
14519 			 */
14520 			if (st_recov_sz != sizeof (recov_info)) {
14521 				break;
14522 			}
14523 			rval = st_interpret_read_pos(un, &un->un_running,
14524 			    un->un_read_pos_type, 32,
14525 			    (caddr_t)un->un_read_pos_data, post_space);
14526 			un->un_status = status;
14527 			break;
14528 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
14529 			un->un_running.pmode = previous_pmode;
14530 			continue;
14531 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
14532 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
14533 			    "st_update_block_pos() read position cmd 0x%x"
14534 			    " returned 0x%x un_status = %d",
14535 			    un->un_read_pos_type, rval, un->un_status);
14536 			/* ENOTTY means it read garbage. try something else. */
14537 			if (rval == ENOTTY) {
14538 				rval = EIO; /* so ENOTTY is not final rval */
14539 			} else {
14540 				break;
14541 			}
14542 		} else {
14543 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
14544 			    "st_update_block_pos() read position cmd %x"
14545 			    " returned %x", un->un_read_pos_type, rval);
14546 			un->un_running.pmode = previous_pmode;
14547 		}
14548 
14549 		switch (un->un_read_pos_type) {
14550 		case SHORT_POS:
14551 			un->un_read_pos_type = NO_POS;
14552 			break;
14553 
14554 		case LONG_POS:
14555 			un->un_read_pos_type = EXT_POS;
14556 			break;
14557 
14558 		case EXT_POS:
14559 			un->un_read_pos_type = SHORT_POS;
14560 			break;
14561 
14562 		default:
14563 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14564 			    "Unexpected read position type 0x%x",
14565 			    un->un_read_pos_type);
14566 		}
14567 		un->un_status = KEY_NO_SENSE;
14568 	}
14569 
14570 	return (rval);
14571 }
14572 
14573 static int
14574 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
14575 {
14576 	int result;
14577 	size_t d_sz;
14578 	caddr_t pos_info;
14579 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
14580 
14581 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
14582 
14583 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
14584 		return (0);
14585 	}
14586 
14587 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
14588 
14589 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14590 		    "bp_mapin_common() failed");
14591 
14592 		return (EIO);
14593 	}
14594 
14595 	d_sz = bp->b_bcount - bp->b_resid;
14596 	if (d_sz == 0) {
14597 		bp_mapout(bp);
14598 		return (EIO);
14599 	}
14600 
14601 	/*
14602 	 * Copy the buf to a double-word aligned memory that can hold the
14603 	 * tape_position_t data structure.
14604 	 */
14605 	if ((pos_info = kmem_alloc(d_sz, KM_NOSLEEP)) == NULL) {
14606 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14607 		    "kmem_alloc() failed");
14608 		bp_mapout(bp);
14609 		return (EIO);
14610 	}
14611 	bcopy(bp->b_un.b_addr, pos_info, d_sz);
14612 
14613 #ifdef STDEBUG
14614 	if ((st_debug & 0x7) > 2) {
14615 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14616 		    "st_get_read_pos() position info",
14617 		    pos_info, bp->b_bcount);
14618 	}
14619 #endif
14620 
14621 	result = st_interpret_read_pos(un, &un->un_pos, cmd->uscsi_cdb[1],
14622 	    d_sz, pos_info, 0);
14623 
14624 	COPY_POS(&un->un_running, &un->un_pos);
14625 
14626 	kmem_free(pos_info, d_sz);
14627 	bp_mapout(bp);
14628 
14629 	return (result);
14630 }
14631 
14632 #if defined(_BIG_ENDIAN)
14633 
14634 #define	FIX_ENDIAN16(x)
14635 #define	FIX_ENDIAN32(x)
14636 #define	FIX_ENDIAN64(x)
14637 
14638 #elif defined(_LITTLE_ENDIAN)
14639 
14640 static void
14641 st_swap16(uint16_t *val)
14642 {
14643 	uint16_t tmp;
14644 
14645 	tmp = (*val >>  8) & 0xff;
14646 	tmp |= (*val <<  8) & 0xff00;
14647 
14648 	*val = tmp;
14649 }
14650 
14651 static void
14652 st_swap32(uint32_t *val)
14653 {
14654 	uint32_t tmp;
14655 
14656 	tmp =  (*val >> 24) & 0xff;
14657 	tmp |= (*val >>  8) & 0xff00;
14658 	tmp |= (*val <<  8) & 0xff0000;
14659 	tmp |= (*val << 24) & 0xff000000;
14660 
14661 	*val = tmp;
14662 }
14663 
14664 static void
14665 st_swap64(uint64_t *val)
14666 {
14667 	uint32_t low;
14668 	uint32_t high;
14669 
14670 	low =  (uint32_t)(*val);
14671 	high = (uint32_t)(*val >> 32);
14672 
14673 	st_swap32(&low);
14674 	st_swap32(&high);
14675 
14676 	*val =  high;
14677 	*val |= ((uint64_t)low << 32);
14678 }
14679 
14680 #define	FIX_ENDIAN16(x) st_swap16(x)
14681 #define	FIX_ENDIAN32(x) st_swap32(x)
14682 #define	FIX_ENDIAN64(x) st_swap64(x)
14683 #endif
14684 
14685 /*
14686  * st_interpret_read_pos()
14687  *
14688  * Returns:
14689  *	0	If secsessful.
14690  *	EIO	If read postion responce data was unuseable or invalid.
14691  *	ERANGE	If the position of the drive is too large for the read_p_type.
14692  *	ENOTTY	If the responce data looks invalid for the read position type.
14693  */
14694 
14695 static int
14696 st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
14697     read_p_types type, size_t data_sz, const caddr_t responce, int post_space)
14698 {
14699 	int rval = 0;
14700 	int flag = 0;
14701 	tapepos_t org;
14702 
14703 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
14704 
14705 	/*
14706 	 * We expect the position value to change after a space command.
14707 	 * So if post_space is set we don't print out what has changed.
14708 	 */
14709 	if ((dest != &un->un_pos) && (post_space == 0) &&
14710 	    (st_recov_sz == sizeof (recov_info))) {
14711 		COPY_POS(&org, dest);
14712 		flag = 1;
14713 	}
14714 
14715 	/*
14716 	 * See what kind of read position was requested.
14717 	 */
14718 	switch (type) {
14719 
14720 	case SHORT_POS: /* Short data format */
14721 	{
14722 		tape_position_t *pos_info = (tape_position_t *)responce;
14723 		uint32_t value;
14724 
14725 		/* If reserved fields are non zero don't use the data */
14726 		if (pos_info->reserved0 || pos_info->reserved1 ||
14727 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
14728 		    pos_info->reserved3) {
14729 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14730 			    "Invalid Read Short Position Data returned\n");
14731 			rval = EIO;
14732 			break;
14733 		}
14734 		/*
14735 		 * Position is to large to use this type of read position.
14736 		 */
14737 		if (pos_info->posi_err == 1) {
14738 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14739 			    "Drive reported position error\n");
14740 			rval = ERANGE;
14741 			break;
14742 		}
14743 		/*
14744 		 * If your at the begining of partition and end at the same
14745 		 * time it's very small partition or bad data.
14746 		 */
14747 		if (pos_info->begin_of_part && pos_info->end_of_part) {
14748 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14749 			    "SHORT_POS returned begin and end of"
14750 			    " partition\n");
14751 			rval = EIO;
14752 			break;
14753 		}
14754 
14755 		if (pos_info->blk_posi_unkwn == 0) {
14756 
14757 			value = pos_info->host_block;
14758 			FIX_ENDIAN32(&value);
14759 
14760 			/*
14761 			 * If the tape is rewound the host blcok should be 0.
14762 			 */
14763 			if ((pos_info->begin_of_part == 1) &&
14764 			    (value != 0)) {
14765 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14766 				    "SHORT_POS returned begin of partition"
14767 				    " but host block was 0x%x\n", value);
14768 				rval = EIO;
14769 				break;
14770 			}
14771 
14772 			if (dest->lgclblkno != value) {
14773 				if (flag)
14774 					flag++;
14775 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14776 				    "SHORT_POS current logical 0x%"PRIx64" read"
14777 				    " 0x%x\n", dest->lgclblkno, value);
14778 			}
14779 
14780 			dest->lgclblkno = (uint64_t)value;
14781 
14782 			/*
14783 			 * If the begining of partition is true and the
14784 			 * block number is zero we will beleive that it is
14785 			 * rewound. Promote the pmode to legacy.
14786 			 */
14787 			if ((pos_info->begin_of_part == 1) &&
14788 			    (value == 0)) {
14789 				dest->blkno = 0;
14790 				dest->fileno = 0;
14791 				if (dest->pmode != legacy)
14792 					dest->pmode = legacy;
14793 			/*
14794 			 * otherwise if the pmode was invalid,
14795 			 * promote it to logical.
14796 			 */
14797 			} else if (dest->pmode == invalid) {
14798 				dest->pmode = logical;
14799 			}
14800 
14801 			if (dest->partition != pos_info->partition_number) {
14802 				if (flag)
14803 					flag++;
14804 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14805 				    "SHORT_POS current partition %d read %d\n",
14806 				    dest->partition,
14807 				    pos_info->partition_number);
14808 			}
14809 
14810 			dest->partition = pos_info->partition_number;
14811 
14812 		} else {
14813 			dest->pmode = invalid;
14814 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14815 			    "Tape drive reported block position as unknown\n");
14816 		}
14817 		break;
14818 	}
14819 
14820 	case LONG_POS: /* Long data format */
14821 	{
14822 		uint64_t value;
14823 		tape_position_long_t *long_pos_info =
14824 		    (tape_position_long_t *)responce;
14825 
14826 		/* If reserved fields are non zero don't use the data */
14827 		if ((long_pos_info->reserved0) ||
14828 		    (long_pos_info->reserved1) ||
14829 		    (long_pos_info->reserved2)) {
14830 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14831 			    "Invalid Read Long Position Data returned\n");
14832 			rval = ENOTTY;
14833 			break;
14834 		}
14835 
14836 		/* Is position Valid */
14837 		if (long_pos_info->blk_posi_unkwn == 0) {
14838 			uint32_t part;
14839 
14840 			value = long_pos_info->block_number;
14841 			FIX_ENDIAN64(&value);
14842 
14843 			/*
14844 			 * If it says we are at the begining of partition
14845 			 * the block value better be 0.
14846 			 */
14847 			if ((long_pos_info->begin_of_part == 1) &&
14848 			    (value != 0)) {
14849 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14850 				    "LONG_POS returned begin of partition but"
14851 				    " block number was 0x%"PRIx64"\n", value);
14852 				rval = ENOTTY;
14853 				break;
14854 			}
14855 			/*
14856 			 * Can't be at the start and the end of the partition
14857 			 * at the same time if the partition is larger the 0.
14858 			 */
14859 			if (long_pos_info->begin_of_part &&
14860 			    long_pos_info->end_of_part) {
14861 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14862 				    "LONG_POS returned begin and end of"
14863 				    " partition\n");
14864 				rval = ENOTTY;
14865 				break;
14866 			}
14867 
14868 			/*
14869 			 * If the logical block number is not what we expected.
14870 			 */
14871 			if (dest->lgclblkno != value) {
14872 				if (flag)
14873 					flag++;
14874 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14875 				    "LONG_POS current logical 0x%"PRIx64
14876 				    " read 0x%"PRIx64"\n",
14877 				    dest->lgclblkno, value);
14878 			}
14879 			dest->lgclblkno = value;
14880 
14881 			/*
14882 			 * If the begining of partition is true and the
14883 			 * block number is zero we will beleive that it is
14884 			 * rewound. Promote the pmode to legacy.
14885 			 */
14886 			if ((long_pos_info->begin_of_part == 1) &&
14887 			    (long_pos_info->block_number == 0)) {
14888 				dest->blkno = 0;
14889 				dest->fileno = 0;
14890 				if (dest->pmode != legacy)
14891 					dest->pmode = legacy;
14892 			/*
14893 			 * otherwise if the pmode was invalid,
14894 			 * promote it to logical.
14895 			 */
14896 			} else if (dest->pmode == invalid) {
14897 				dest->pmode = logical;
14898 			}
14899 
14900 			part = long_pos_info->partition;
14901 			FIX_ENDIAN32(&part);
14902 			if (dest->partition != part) {
14903 				if (flag)
14904 					flag++;
14905 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14906 				    "LONG_POS current partition %d"
14907 				    " read %d\n", dest->partition, part);
14908 			}
14909 			dest->partition = part;
14910 		} else {
14911 			/*
14912 			 * If the drive doesn't know location,
14913 			 * we don't either.
14914 			 */
14915 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14916 			    "Tape drive reported block position as unknown\n");
14917 			dest->pmode = invalid;
14918 		}
14919 
14920 		/* Is file position valid */
14921 		if (long_pos_info->mrk_posi_unkwn == 0) {
14922 			value = long_pos_info->file_number;
14923 			FIX_ENDIAN64(&value);
14924 			/*
14925 			 * If it says we are at the begining of partition
14926 			 * the block value better be 0.
14927 			 */
14928 			if ((long_pos_info->begin_of_part == 1) &&
14929 			    (value != 0)) {
14930 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14931 				    "LONG_POS returned begin of partition but"
14932 				    " block number was 0x%"PRIx64"\n", value);
14933 				rval = ENOTTY;
14934 				break;
14935 			}
14936 			if (((dest->pmode == legacy) ||
14937 			    (dest->pmode == logical)) &&
14938 			    (dest->fileno != value)) {
14939 				if (flag)
14940 					flag++;
14941 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14942 				    "LONG_POS fileno 0x%"PRIx64
14943 				    " not un_pos %x\n", value,
14944 				    dest->fileno);
14945 			} else if (dest->pmode == invalid) {
14946 				dest->pmode = logical;
14947 			}
14948 			dest->fileno = (int32_t)value;
14949 		}
14950 
14951 		if (dest->pmode != invalid && long_pos_info->end_of_part) {
14952 			dest->eof = ST_EOT;
14953 		}
14954 
14955 		break;
14956 	}
14957 
14958 	case EXT_POS: /* Extended data format */
14959 	{
14960 		uint64_t value;
14961 		uint16_t len;
14962 		tape_position_ext_t *ext_pos_info =
14963 		    (tape_position_ext_t *)responce;
14964 
14965 		/* Make sure that there is enough data there */
14966 		if (data_sz < 16) {
14967 			break;
14968 		}
14969 
14970 		/* If reserved fields are non zero don't use the data */
14971 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
14972 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14973 			    "EXT_POS reserved fields not zero\n");
14974 			rval = ENOTTY;
14975 			break;
14976 		}
14977 
14978 		/*
14979 		 * In the unlikely event of overflowing 64 bits of position.
14980 		 */
14981 		if (ext_pos_info->posi_err != 0) {
14982 			rval = ERANGE;
14983 			break;
14984 		}
14985 
14986 		len = ext_pos_info->parameter_len;
14987 		FIX_ENDIAN16(&len);
14988 
14989 		if (len != 0x1c) {
14990 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14991 			    "EXT_POS parameter_len should be 0x1c was 0x%x\n",
14992 			    len);
14993 			rval = ENOTTY;
14994 			break;
14995 		}
14996 
14997 		/* Is block position information valid */
14998 		if (ext_pos_info->blk_posi_unkwn == 0) {
14999 
15000 			value = ext_pos_info->host_block;
15001 			FIX_ENDIAN64(&value);
15002 			if ((ext_pos_info->begin_of_part == 1) &&
15003 			    (value != 0)) {
15004 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15005 				    "EXT_POS returned begining of partition but"
15006 				    " the host block was 0x%"PRIx64"\n", value);
15007 				rval = ENOTTY;
15008 				break;
15009 			}
15010 
15011 			if (dest->lgclblkno != value) {
15012 				if (flag)
15013 					flag++;
15014 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15015 				    "EXT_POS current logical 0x%"PRIx64
15016 				    " read 0x%"PRIx64"\n",
15017 				    dest->lgclblkno, value);
15018 			}
15019 			dest->lgclblkno = value;
15020 
15021 			/*
15022 			 * If the begining of partition is true and the
15023 			 * block number is zero we will beleive that it is
15024 			 * rewound. Promote the pmode to legacy.
15025 			 */
15026 			if ((ext_pos_info->begin_of_part == 1) &&
15027 			    (ext_pos_info->host_block == 0)) {
15028 				dest->blkno = 0;
15029 				dest->fileno = 0;
15030 				if (dest->pmode != legacy) {
15031 					dest->pmode = legacy;
15032 				}
15033 			/*
15034 			 * otherwise if the pmode was invalid,
15035 			 * promote it to logical.
15036 			 */
15037 			} else if (dest->pmode == invalid) {
15038 				dest->pmode = logical;
15039 			}
15040 
15041 			if (dest->partition != ext_pos_info->partition) {
15042 				if (flag)
15043 					flag++;
15044 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15045 				    "EXT_POS current partition %d read %d\n",
15046 				    dest->partition,
15047 				    ext_pos_info->partition);
15048 			}
15049 			dest->partition = ext_pos_info->partition;
15050 
15051 		} else {
15052 			dest->pmode = invalid;
15053 		}
15054 		break;
15055 	}
15056 
15057 	default:
15058 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15059 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
15060 		rval = EIO;
15061 	}
15062 
15063 	if ((flag > 1) && (rval == 0) && (org.pmode != invalid)) {
15064 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
15065 		    "position read in", &org);
15066 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
15067 		    "position read out", dest);
15068 	}
15069 
15070 	return (rval);
15071 }
15072 
15073 static int
15074 st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos,
15075     uint64_t lblk, uchar_t partition)
15076 {
15077 	int rval;
15078 	char cdb[CDB_GROUP4];
15079 	struct uscsi_cmd *cmd;
15080 	struct scsi_extended_sense sense;
15081 	bufunc_t bf = (ubf == st_uscsi_cmd) ? st_cmd : st_rcmd;
15082 
15083 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
15084 	/*
15085 	 * Not sure what to do when doing recovery and not wanting
15086 	 * to update un_pos
15087 	 */
15088 
15089 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
15090 
15091 	if (lblk <= INT32_MAX) {
15092 		cmd->uscsi_cdblen = CDB_GROUP1;
15093 		cdb[0] = SCMD_LOCATE;
15094 		cdb[1] = pos->partition == partition ? 0 : 2;
15095 		cdb[2] = 0;
15096 		cdb[3] = (char)(lblk >> 24);
15097 		cdb[4] = (char)(lblk >> 16);
15098 		cdb[5] = (char)(lblk >> 8);
15099 		cdb[6] = (char)(lblk);
15100 		cdb[7] = 0;
15101 		cdb[8] = partition;
15102 		cdb[9] = 0;
15103 	} else {
15104 		/*
15105 		 * If the drive doesn't give a 64 bit read position data
15106 		 * it is unlikely it will accept 64 bit locates.
15107 		 */
15108 		if (un->un_read_pos_type != LONG_POS) {
15109 			kmem_free(cmd, sizeof (struct uscsi_cmd));
15110 			return (ERANGE);
15111 		}
15112 		cmd->uscsi_cdblen = CDB_GROUP4;
15113 		cdb[0] = (char)SCMD_LOCATE_G4;
15114 		cdb[1] = pos->partition == partition ? 0 : 2;
15115 		cdb[2] = 0;
15116 		cdb[3] = partition;
15117 		cdb[4] = (char)(lblk >> 56);
15118 		cdb[5] = (char)(lblk >> 48);
15119 		cdb[6] = (char)(lblk >> 40);
15120 		cdb[7] = (char)(lblk >> 32);
15121 		cdb[8] = (char)(lblk >> 24);
15122 		cdb[9] = (char)(lblk >> 16);
15123 		cdb[10] = (char)(lblk >> 8);
15124 		cdb[11] = (char)(lblk);
15125 		cdb[12] = 0;
15126 		cdb[13] = 0;
15127 		cdb[14] = 0;
15128 		cdb[15] = 0;
15129 	}
15130 
15131 
15132 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
15133 	cmd->uscsi_rqbuf = (caddr_t)&sense;
15134 	cmd->uscsi_rqlen = sizeof (sense);
15135 	cmd->uscsi_timeout = un->un_dp->space_timeout;
15136 	cmd->uscsi_cdb = cdb;
15137 
15138 	rval = ubf(un, cmd, FKIOCTL);
15139 
15140 	pos->pmode = logical;
15141 	pos->eof = ST_NO_EOF;
15142 
15143 	if (lblk > INT32_MAX) {
15144 		/*
15145 		 * XXX This is a work around till we handle Descriptor format
15146 		 * sense data. Since we are sending a command where the standard
15147 		 * sense data can not correctly represent a correct residual in
15148 		 * 4 bytes.
15149 		 */
15150 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
15151 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15152 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
15153 			/* Doesn't like big locate command */
15154 			un->un_status = 0;
15155 			rval = ERANGE;
15156 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
15157 			/* Aborted big locate command */
15158 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15159 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
15160 			    rval);
15161 			un->un_status = 0;
15162 			rval = EIO;
15163 		} else if (st_update_block_pos(un, bf, 1)) {
15164 			/* read position failed */
15165 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15166 			    "Big LOCATE and read pos: rval = %d\n", rval);
15167 			rval = EIO;
15168 		} else if (lblk > un->un_pos.lgclblkno) {
15169 			/* read position worked but position was not expected */
15170 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15171 			    "Big LOCATE and recover read less then desired 0x%"
15172 			    PRIx64"\n", un->un_pos.lgclblkno);
15173 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
15174 			un->un_status = KEY_BLANK_CHECK;
15175 			rval = ESPIPE;
15176 		} else if (lblk == un->un_pos.lgclblkno) {
15177 			/* read position was what was expected */
15178 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15179 			    "Big LOCATE and recover seems to have worked\n");
15180 			un->un_err_resid = 0;
15181 			rval = 0;
15182 		} else {
15183 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15184 			    "BIGLOCATE end up going backwards");
15185 			un->un_err_resid = lblk;
15186 			rval = EIO;
15187 		}
15188 
15189 	} else if (rval == 0) {
15190 		/* Worked as requested */
15191 		pos->lgclblkno = lblk;
15192 
15193 	} else if (((cmd->uscsi_status & ST_STATUS_MASK) == STATUS_CHECK) &&
15194 	    (cmd->uscsi_resid != 0)) {
15195 		/* Got part way there but wasn't enough blocks on tape */
15196 		pos->lgclblkno = lblk - cmd->uscsi_resid;
15197 		un->un_err_resid = cmd->uscsi_resid;
15198 		un->un_status = KEY_BLANK_CHECK;
15199 		rval = ESPIPE;
15200 
15201 	} else if (st_update_block_pos(un, bf, 1) == 0) {
15202 		/* Got part way there but drive didn't tell what we missed by */
15203 		un->un_err_resid = lblk - pos->lgclblkno;
15204 		un->un_status = KEY_BLANK_CHECK;
15205 		rval = ESPIPE;
15206 
15207 	} else {
15208 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15209 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
15210 		    rval, cmd->uscsi_status);
15211 		un->un_err_resid = lblk;
15212 		un->un_status = KEY_ILLEGAL_REQUEST;
15213 		pos->pmode = invalid;
15214 		rval = EIO;
15215 	}
15216 
15217 	kmem_free(cmd, sizeof (struct uscsi_cmd));
15218 
15219 	return (rval);
15220 }
15221 
15222 static int
15223 st_mtfsf_ioctl(struct scsi_tape *un, int64_t files)
15224 {
15225 	int rval;
15226 
15227 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
15228 
15229 
15230 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15231 	    "st_mtfsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15232 #if 0
15233 	if ((IN_EOF(un->un_pos)) && (files == 1)) {
15234 		un->un_pos.fileno++;
15235 		un->un_pos.blkno = 0;
15236 		return (0);
15237 	}
15238 #endif
15239 	/* pmode == invalid already handled */
15240 	if (un->un_pos.pmode == legacy) {
15241 		/*
15242 		 * forward space over filemark
15243 		 *
15244 		 * For ASF we allow a count of 0 on fsf which means
15245 		 * we just want to go to beginning of current file.
15246 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
15247 		 * Allow stepping over double fmk with reel
15248 		 */
15249 		if ((un->un_pos.eof >= ST_EOT) &&
15250 		    (files > 0) &&
15251 		    ((un->un_dp->options & ST_REEL) == 0)) {
15252 			/* we're at EOM */
15253 			un->un_err_resid = files;
15254 			un->un_status = KEY_BLANK_CHECK;
15255 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15256 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
15257 			return (EIO);
15258 		}
15259 
15260 		/*
15261 		 * physical tape position may not be what we've been
15262 		 * telling the user; adjust the request accordingly
15263 		 */
15264 		if (IN_EOF(un->un_pos)) {
15265 			un->un_pos.fileno++;
15266 			un->un_pos.blkno = 0;
15267 			/*
15268 			 * For positive direction case, we're now covered.
15269 			 * For zero or negative direction, we're covered
15270 			 * (almost)
15271 			 */
15272 			files--;
15273 		}
15274 
15275 	}
15276 
15277 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15278 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15279 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
15280 		return (EIO);
15281 	}
15282 
15283 
15284 	/*
15285 	 * Forward space file marks.
15286 	 * We leave ourselves at block zero
15287 	 * of the target file number.
15288 	 */
15289 	if (files < 0) {
15290 		rval = st_backward_space_files(un, -files, 0);
15291 	} else {
15292 		rval = st_forward_space_files(un, files);
15293 	}
15294 
15295 	return (rval);
15296 }
15297 
15298 static int
15299 st_forward_space_files(struct scsi_tape *un, int64_t count)
15300 {
15301 	int rval;
15302 
15303 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
15304 
15305 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15306 	    "fspace: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15307 
15308 	ASSERT(count >= 0);
15309 	ASSERT(un->un_pos.pmode != invalid);
15310 
15311 	/*
15312 	 * A space with a count of zero means take me to the start of file.
15313 	 */
15314 	if (count == 0) {
15315 
15316 		/* Hay look were already there */
15317 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0) {
15318 			un->un_err_resid = 0;
15319 			COPY_POS(&un->un_err_pos, &un->un_pos);
15320 			return (0);
15321 		}
15322 
15323 		/*
15324 		 * Well we are in the first file.
15325 		 * A rewind will get to the start.
15326 		 */
15327 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
15328 			rval = st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
15329 
15330 		/*
15331 		 * Can we backspace to get there?
15332 		 * This should work in logical mode.
15333 		 */
15334 		} else if (un->un_dp->options & ST_BSF) {
15335 			rval = st_space_to_begining_of_file(un);
15336 
15337 		/*
15338 		 * Can't back space but current file number is known,
15339 		 * So rewind and space from the begining of the partition.
15340 		 */
15341 		} else if (un->un_pos.pmode == legacy) {
15342 			rval = st_scenic_route_to_begining_of_file(un,
15343 			    un->un_pos.fileno);
15344 
15345 		/*
15346 		 * pmode is logical and ST_BSF is not set.
15347 		 * The LONG_POS read position contains the fileno.
15348 		 * If the read position works, rewind and space.
15349 		 */
15350 		} else if (un->un_read_pos_type == LONG_POS) {
15351 			rval = st_cmd(un, SCMD_READ_POSITION, 0, SYNC_CMD);
15352 			if (rval) {
15353 				/*
15354 				 * We didn't get the file position from the
15355 				 * read position command.
15356 				 * We are going to trust the drive to backspace
15357 				 * and then position after the filemark.
15358 				 */
15359 				rval = st_space_to_begining_of_file(un);
15360 			}
15361 			rval = st_interpret_read_pos(un, &un->un_pos, LONG_POS,
15362 			    32, (caddr_t)un->un_read_pos_data, 0);
15363 			if ((rval) && (un->un_pos.pmode == invalid)) {
15364 				rval = st_space_to_begining_of_file(un);
15365 			} else {
15366 				rval = st_scenic_route_to_begining_of_file(un,
15367 				    un->un_pos.fileno);
15368 			}
15369 		} else {
15370 			rval = EIO;
15371 		}
15372 		/*
15373 		 * If something didn't work we are lost
15374 		 */
15375 		if (rval != 0) {
15376 			un->un_pos.pmode = invalid;
15377 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15378 			    "st_mtioctop : EIO : fspace pmode invalid");
15379 
15380 			rval = EIO;
15381 		}
15382 
15383 	} else {
15384 		rval = st_space_fmks(un, count);
15385 	}
15386 
15387 	if (rval != EIO && count < 0) {
15388 		/*
15389 		 * we came here with a count < 0; we now need
15390 		 * to skip back to end up before the filemark
15391 		 */
15392 		rval = st_backward_space_files(un, 1, 1);
15393 	}
15394 
15395 	return (rval);
15396 }
15397 
15398 static int
15399 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
15400 {
15401 	int rval;
15402 
15403 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
15404 
15405 	if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15406 		rval = EIO;
15407 	} else if (st_cmd(un, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
15408 		rval = EIO;
15409 	}
15410 
15411 	return (rval);
15412 }
15413 
15414 static int
15415 st_space_to_begining_of_file(struct scsi_tape *un)
15416 {
15417 	int rval;
15418 
15419 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
15420 
15421 	/*
15422 	 * Back space of the file at the begining of the file.
15423 	 */
15424 	rval = st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
15425 	if (rval) {
15426 		rval = EIO;
15427 		return (rval);
15428 	}
15429 
15430 	/*
15431 	 * Other interesting answers might be crashed BOT which isn't bad.
15432 	 */
15433 	if (un->un_status == SUN_KEY_BOT) {
15434 		return (rval);
15435 	}
15436 
15437 	un->un_running.pmode = invalid;
15438 
15439 	/*
15440 	 * Now we are on the BOP side of the filemark. Forward space to
15441 	 * the EOM side and we are at the begining of the file.
15442 	 */
15443 	rval = st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD);
15444 	if (rval) {
15445 		rval = EIO;
15446 	}
15447 
15448 	return (rval);
15449 }
15450 
15451 static int
15452 st_mtfsr_ioctl(struct scsi_tape *un, int64_t count)
15453 {
15454 
15455 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
15456 
15457 	/*
15458 	 * forward space to inter-record gap
15459 	 *
15460 	 */
15461 
15462 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15463 	    "st_ioctl_fsr: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15464 
15465 	if (un->un_pos.pmode == legacy) {
15466 		/*
15467 		 * If were are at end of tape and count is forward.
15468 		 * Return blank check.
15469 		 */
15470 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
15471 			/* we're at EOM */
15472 			un->un_err_resid = count;
15473 			un->un_status = KEY_BLANK_CHECK;
15474 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15475 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
15476 			return (EIO);
15477 		}
15478 
15479 		/*
15480 		 * If count is zero there is nothing to do.
15481 		 */
15482 		if (count == 0) {
15483 			un->un_err_pos.fileno = un->un_pos.fileno;
15484 			un->un_err_pos.blkno = un->un_pos.blkno;
15485 			un->un_err_resid = 0;
15486 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15487 				un->un_status = SUN_KEY_EOF;
15488 			}
15489 			return (0);
15490 		}
15491 
15492 		/*
15493 		 * physical tape position may not be what we've been
15494 		 * telling the user; adjust the position accordingly
15495 		 */
15496 		if (IN_EOF(un->un_pos)) {
15497 			daddr_t blkno = un->un_pos.blkno;
15498 			int fileno = un->un_pos.fileno;
15499 
15500 			optype lastop = un->un_lastop;
15501 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)
15502 			    == -1) {
15503 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15504 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
15505 				return (EIO);
15506 			}
15507 
15508 			un->un_pos.blkno = blkno;
15509 			un->un_pos.fileno = fileno;
15510 			un->un_lastop = lastop;
15511 		}
15512 	}
15513 
15514 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15515 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15516 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
15517 		return (EIO);
15518 	}
15519 
15520 	return (st_space_records(un, count));
15521 }
15522 
15523 static int
15524 st_space_records(struct scsi_tape *un, int64_t count)
15525 {
15526 	int64_t dblk;
15527 	int rval = 0;
15528 
15529 	ST_FUNC(ST_DEVINFO, st_space_records);
15530 
15531 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15532 	    "st_space_records: count=%"PRIx64", eof=%x\n",
15533 	    count, un->un_pos.eof);
15534 
15535 	if (un->un_pos.pmode == logical) {
15536 		rval = st_cmd(un, SCMD_SPACE, Blk(count), SYNC_CMD);
15537 		if (rval != 0) {
15538 			rval = EIO;
15539 		}
15540 		return (rval);
15541 	}
15542 
15543 	dblk = count + un->un_pos.blkno;
15544 
15545 	/* Already there */
15546 	if (dblk == un->un_pos.blkno) {
15547 		un->un_err_resid = 0;
15548 		COPY_POS(&un->un_err_pos, &un->un_pos);
15549 		return (0);
15550 	}
15551 
15552 	/*
15553 	 * If the destination block is forward
15554 	 * or the drive will backspace records.
15555 	 */
15556 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
15557 		/*
15558 		 * If we're spacing forward, or the device can
15559 		 * backspace records, we can just use the SPACE
15560 		 * command.
15561 		 */
15562 		dblk -= un->un_pos.blkno;
15563 		if (st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15564 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15565 			    "st_space_records:EIO:space_records can't spc");
15566 			rval = EIO;
15567 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
15568 			/*
15569 			 * check if we hit BOT/EOT
15570 			 */
15571 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
15572 				un->un_status = SUN_KEY_BOT;
15573 				un->un_pos.eof = ST_NO_EOF;
15574 			} else if (dblk < 0 &&
15575 			    un->un_pos.eof == ST_EOF_PENDING) {
15576 				int residue = un->un_err_resid;
15577 				/*
15578 				 * we skipped over a filemark
15579 				 * and need to go forward again
15580 				 */
15581 				if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
15582 					ST_DEBUG2(ST_DEVINFO, st_label,
15583 					    SCSI_DEBUG, "st_space_records: EIO"
15584 					    " : can't space #2");
15585 					rval = EIO;
15586 				}
15587 				un->un_err_resid = residue;
15588 			}
15589 			if (rval == 0) {
15590 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15591 				    "st_space_records: EIO : space_rec rval"
15592 				    " == 0");
15593 				rval = EIO;
15594 			}
15595 		}
15596 	} else {
15597 		/*
15598 		 * else we rewind, space forward across filemarks to
15599 		 * the desired file, and then space records to the
15600 		 * desired block.
15601 		 */
15602 
15603 		int dfile = un->un_pos.fileno;	/* save current file */
15604 
15605 		if (dblk < 0) {
15606 			/*
15607 			 * Wups - we're backing up over a filemark
15608 			 */
15609 			if (un->un_pos.blkno != 0 &&
15610 			    (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15611 			    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD))) {
15612 				un->un_pos.pmode = invalid;
15613 			}
15614 			un->un_err_resid = -dblk;
15615 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
15616 				un->un_status = SUN_KEY_BOT;
15617 				un->un_pos.eof = ST_NO_EOF;
15618 			} else if (un->un_pos.fileno > 0) {
15619 				un->un_status = SUN_KEY_EOF;
15620 				un->un_pos.eof = ST_NO_EOF;
15621 			}
15622 			COPY_POS(&un->un_err_pos, &un->un_pos);
15623 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15624 			    "st_space_records:EIO:space_records : dblk < 0");
15625 			rval = EIO;
15626 		} else if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15627 		    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
15628 		    st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15629 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15630 			    "st_space_records: EIO :space_records : rewind "
15631 			    "and space failed");
15632 			un->un_pos.pmode = invalid;
15633 			rval = EIO;
15634 		}
15635 	}
15636 
15637 	return (rval);
15638 }
15639 
15640 static int
15641 st_mtbsf_ioctl(struct scsi_tape *un, int64_t files)
15642 {
15643 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
15644 
15645 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15646 	    "st_mtbsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15647 	/*
15648 	 * backward space of file filemark (1/2" and 8mm)
15649 	 * tape position will end on the beginning of tape side
15650 	 * of the desired file mark
15651 	 */
15652 	if ((un->un_dp->options & ST_BSF) == 0) {
15653 		return (ENOTTY);
15654 	}
15655 
15656 	if (un->un_pos.pmode == legacy) {
15657 
15658 		/*
15659 		 * If a negative count (which implies a forward space op)
15660 		 * is specified, and we're at logical or physical eot,
15661 		 * bounce the request.
15662 		 */
15663 
15664 		if (un->un_pos.eof >= ST_EOT && files < 0) {
15665 			un->un_err_resid = files;
15666 			un->un_status = SUN_KEY_EOT;
15667 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15668 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
15669 			return (EIO);
15670 		}
15671 		/*
15672 		 * physical tape position may not be what we've been
15673 		 * telling the user; adjust the request accordingly
15674 		 */
15675 		if (IN_EOF(un->un_pos)) {
15676 			un->un_pos.fileno++;
15677 			un->un_pos.blkno = 0;
15678 			files++;
15679 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15680 			    "st_mtbsf_ioctl in eof: count=%"PRIx64", op=%x\n",
15681 			    files, MTBSF);
15682 
15683 		}
15684 	}
15685 
15686 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15687 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15688 		    "st_ioctl : EIO : MTBSF : check den wfm");
15689 		return (EIO);
15690 	}
15691 
15692 	if (files <= 0) {
15693 		/*
15694 		 * for a negative count, we need to step forward
15695 		 * first and then step back again
15696 		 */
15697 		files = -files + 1;
15698 		return (st_forward_space_files(un, files));
15699 	}
15700 	return (st_backward_space_files(un, files, 1));
15701 }
15702 
15703 static int
15704 st_backward_space_files(struct scsi_tape *un, int64_t count, int infront)
15705 {
15706 	int64_t end_fileno;
15707 	int64_t skip_cnt;
15708 	int rval = 0;
15709 
15710 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
15711 
15712 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15713 	    "st_backward_space_files: count=%"PRIx64" eof=%x\n",
15714 	    count, un->un_pos.eof);
15715 	/*
15716 	 * Backspace files (MTNBSF): infront == 0
15717 	 *
15718 	 *	For tapes that can backspace, backspace
15719 	 *	count+1 filemarks and then run forward over
15720 	 *	a filemark
15721 	 *
15722 	 *	For tapes that can't backspace,
15723 	 *		calculate desired filenumber
15724 	 *		(un->un_pos.fileno - count), rewind,
15725 	 *		and then space forward this amount
15726 	 *
15727 	 * Backspace filemarks (MTBSF) infront == 1
15728 	 *
15729 	 *	For tapes that can backspace, backspace count
15730 	 *	filemarks
15731 	 *
15732 	 *	For tapes that can't backspace, calculate
15733 	 *	desired filenumber (un->un_pos.fileno - count),
15734 	 *	add 1, rewind, space forward this amount,
15735 	 *	and mark state as ST_EOF_PENDING appropriately.
15736 	 */
15737 
15738 	if (un->un_pos.pmode == logical) {
15739 
15740 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15741 		    "st_backward_space_files: mt_op=%x count=%"PRIx64
15742 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
15743 		    un->un_pos.lgclblkno);
15744 
15745 
15746 		/* In case a drive that won't back space gets in logical mode */
15747 		if ((un->un_dp->options & ST_BSF) == 0) {
15748 			rval = EIO;
15749 			return (rval);
15750 		}
15751 		if ((infront == 1) &&
15752 		    (st_cmd(un, SCMD_SPACE, Fmk(-count), SYNC_CMD))) {
15753 			rval = EIO;
15754 			return (rval);
15755 		} else if ((infront == 0) &&
15756 		    (st_cmd(un, SCMD_SPACE, Fmk((-count)-1), SYNC_CMD)) &&
15757 		    (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
15758 			rval = EIO;
15759 			return (rval);
15760 		}
15761 		return (rval);
15762 	}
15763 
15764 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15765 	    "st_backward_space_files: mt_op=%x count=%"PRIx64
15766 	    "fileno=%x blkno=%x\n",
15767 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
15768 
15769 
15770 
15771 	/*
15772 	 * Handle the simple case of BOT
15773 	 * playing a role in these cmds.
15774 	 * We do this by calculating the
15775 	 * ending file number. If the ending
15776 	 * file is < BOT, rewind and set an
15777 	 * error and mark resid appropriately.
15778 	 * If we're backspacing a file (not a
15779 	 * filemark) and the target file is
15780 	 * the first file on the tape, just
15781 	 * rewind.
15782 	 */
15783 
15784 	/* figure expected destination of this SPACE command */
15785 	end_fileno = un->un_pos.fileno - count;
15786 
15787 	/*
15788 	 * Would the end effect of this SPACE be the same as rewinding?
15789 	 * If so just rewind instead.
15790 	 */
15791 	if ((infront != 0) && (end_fileno < 0) ||
15792 	    (infront == 0) && (end_fileno <= 0)) {
15793 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15794 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15795 			    "st_backward_space_files: EIO : "
15796 			    "rewind in lou of BSF failed\n");
15797 			rval = EIO;
15798 		}
15799 		if (end_fileno < 0) {
15800 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15801 			    "st_backward_space_files: EIO : "
15802 			    "back space file greater then fileno\n");
15803 			rval = EIO;
15804 			un->un_err_resid = -end_fileno;
15805 			un->un_status = SUN_KEY_BOT;
15806 		}
15807 		return (rval);
15808 	}
15809 
15810 	if (un->un_dp->options & ST_BSF) {
15811 		skip_cnt = 1 - infront;
15812 		/*
15813 		 * If we are going to end up at the beginning
15814 		 * of the file, we have to space one extra file
15815 		 * first, and then space forward later.
15816 		 */
15817 		end_fileno = -(count + skip_cnt);
15818 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15819 		    "skip_cnt=%"PRIx64", tmp=%"PRIx64"\n",
15820 		    skip_cnt, end_fileno);
15821 		if (st_cmd(un, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
15822 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15823 			    "st_backward_space_files:EIO:back space fm failed");
15824 			rval = EIO;
15825 		}
15826 	} else {
15827 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15828 			rval = EIO;
15829 		} else {
15830 			skip_cnt = end_fileno + infront;
15831 		}
15832 	}
15833 
15834 	/*
15835 	 * If we have to space forward, do so...
15836 	 */
15837 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15838 	    "space forward skip_cnt=%"PRIx64", rval=%x\n", skip_cnt, rval);
15839 
15840 	if (rval == 0 && skip_cnt) {
15841 		if (st_cmd(un, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
15842 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15843 			    "st_backward_space_files:EIO:space fm skip count");
15844 			rval = EIO;
15845 		} else if (infront) {
15846 			/*
15847 			 * If we had to space forward, and we're
15848 			 * not a tape that can backspace, mark state
15849 			 * as if we'd just seen a filemark during a
15850 			 * a read.
15851 			 */
15852 			if ((un->un_dp->options & ST_BSF) == 0) {
15853 				un->un_pos.eof = ST_EOF_PENDING;
15854 				un->un_pos.fileno -= 1;
15855 				un->un_pos.blkno = LASTBLK;
15856 				un->un_running.pmode = invalid;
15857 			}
15858 		}
15859 	}
15860 
15861 	if (rval != 0) {
15862 		un->un_pos.pmode = invalid;
15863 	}
15864 
15865 	return (rval);
15866 }
15867 
15868 static int
15869 st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count)
15870 {
15871 	int rval;
15872 
15873 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
15874 
15875 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15876 	    "nbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15877 
15878 	if (un->un_pos.pmode == legacy) {
15879 		/*
15880 		 * backward space file to beginning of file
15881 		 *
15882 		 * If a negative count (which implies a forward space op)
15883 		 * is specified, and we're at logical or physical eot,
15884 		 * bounce the request.
15885 		 */
15886 
15887 		if (un->un_pos.eof >= ST_EOT && count < 0) {
15888 			un->un_err_resid = count;
15889 			un->un_status = SUN_KEY_EOT;
15890 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15891 			    "st_ioctl : EIO : > EOT and count < 0");
15892 			return (EIO);
15893 		}
15894 		/*
15895 		 * physical tape position may not be what we've been
15896 		 * telling the user; adjust the request accordingly
15897 		 */
15898 		if (IN_EOF(un->un_pos)) {
15899 			un->un_pos.fileno++;
15900 			un->un_pos.blkno = 0;
15901 			count++;
15902 		}
15903 	}
15904 
15905 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15906 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15907 		    "st_ioctl : EIO : MTNBSF check den and wfm");
15908 		return (EIO);
15909 	}
15910 
15911 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15912 	    "mtnbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15913 
15914 	if (count <= 0) {
15915 		rval = st_forward_space_files(un, -count);
15916 	} else {
15917 		rval = st_backward_space_files(un, count, 0);
15918 	}
15919 	return (rval);
15920 }
15921 
15922 static int
15923 st_mtbsr_ioctl(struct scsi_tape *un, int64_t num)
15924 {
15925 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
15926 
15927 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15928 	    "bsr: count=%"PRIx64", eof=%x\n", num, un->un_pos.eof);
15929 
15930 	if (un->un_pos.pmode == legacy) {
15931 		/*
15932 		 * backward space into inter-record gap
15933 		 *
15934 		 * If a negative count (which implies a forward space op)
15935 		 * is specified, and we're at logical or physical eot,
15936 		 * bounce the request.
15937 		 */
15938 		if (un->un_pos.eof >= ST_EOT && num < 0) {
15939 			un->un_err_resid = num;
15940 			un->un_status = SUN_KEY_EOT;
15941 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15942 			    "st_ioctl : EIO : MTBSR > EOT");
15943 			return (EIO);
15944 		}
15945 
15946 		if (num == 0) {
15947 			COPY_POS(&un->un_err_pos, &un->un_pos);
15948 			un->un_err_resid = 0;
15949 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15950 				un->un_status = SUN_KEY_EOF;
15951 			}
15952 			return (0);
15953 		}
15954 
15955 		/*
15956 		 * physical tape position may not be what we've been
15957 		 * telling the user; adjust the position accordingly.
15958 		 * bsr can not skip filemarks and continue to skip records
15959 		 * therefore if we are logically before the filemark but
15960 		 * physically at the EOT side of the filemark, we need to step
15961 		 * back; this allows fsr N where N > number of blocks in file
15962 		 * followed by bsr 1 to position at the beginning of last block
15963 		 */
15964 		if (IN_EOF(un->un_pos)) {
15965 			tapepos_t save;
15966 			optype lastop = un->un_lastop;
15967 
15968 			COPY_POS(&save, &un->un_pos);
15969 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD) == -1) {
15970 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15971 				    "st_mtbsr_ioctl: EIO : MTBSR can't space");
15972 				return (EIO);
15973 			}
15974 
15975 			COPY_POS(&un->un_pos, &save);
15976 			un->un_lastop = lastop;
15977 		}
15978 	}
15979 
15980 	un->un_pos.eof = ST_NO_EOF;
15981 
15982 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15983 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15984 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
15985 		return (EIO);
15986 	}
15987 
15988 	num = -num;
15989 	return (st_space_records(un, num));
15990 }
15991 
15992 static int
15993 st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt)
15994 {
15995 	int rval;
15996 
15997 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
15998 
15999 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
16000 	if (rval == 0) {
16001 		un->un_pos.pmode = logical;
16002 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
16003 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
16004 		/*
16005 		 * Drive says invalid field in cdb.
16006 		 * Doesn't like space multiple. Position isn't lost.
16007 		 */
16008 		un->un_err_resid = cnt;
16009 		un->un_status = 0;
16010 		rval = ENOTTY;
16011 	} else {
16012 		un->un_err_resid = cnt;
16013 		un->un_pos.pmode = invalid;
16014 	}
16015 	return (rval);
16016 }
16017 
16018 static int
16019 st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt)
16020 {
16021 	int rval;
16022 
16023 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
16024 
16025 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
16026 	if (rval == 0) {
16027 		un->un_pos.pmode = logical;
16028 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
16029 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
16030 		/*
16031 		 * Drive says invalid field in cdb.
16032 		 * Doesn't like space multiple. Position isn't lost.
16033 		 */
16034 		un->un_err_resid = cnt;
16035 		un->un_status = 0;
16036 		rval = ENOTTY;
16037 	} else {
16038 		un->un_err_resid = cnt;
16039 		un->un_pos.pmode = invalid;
16040 	}
16041 	return (rval);
16042 }
16043 
16044 #ifdef	__x86
16045 
16046 /*
16047  * release contig_mem and wake up waiting thread, if any
16048  */
16049 static void
16050 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
16051 {
16052 	mutex_enter(ST_MUTEX);
16053 
16054 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
16055 
16056 	cp->cm_next = un->un_contig_mem;
16057 	un->un_contig_mem = cp;
16058 	un->un_contig_mem_available_num++;
16059 	cv_broadcast(&un->un_contig_mem_cv);
16060 
16061 	mutex_exit(ST_MUTEX);
16062 }
16063 
16064 /*
16065  * St_get_contig_mem will return a contig_mem if there is one available
16066  * in current system. Otherwise, it will try to alloc one, if the total
16067  * number of contig_mem is within st_max_contig_mem_num.
16068  * It will sleep, if allowed by caller or return NULL, if no contig_mem
16069  * is available for now.
16070  */
16071 static struct contig_mem *
16072 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
16073 {
16074 	size_t rlen;
16075 	struct contig_mem *cp = NULL;
16076 	ddi_acc_handle_t acc_hdl;
16077 	caddr_t addr;
16078 	int big_enough = 0;
16079 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
16080 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
16081 
16082 	/* Try to get one available contig_mem */
16083 	mutex_enter(ST_MUTEX);
16084 
16085 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
16086 
16087 	if (un->un_contig_mem_available_num > 0) {
16088 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16089 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
16090 		/*
16091 		 * we failed to get one. we're going to
16092 		 * alloc one more contig_mem for this I/O
16093 		 */
16094 		mutex_exit(ST_MUTEX);
16095 		cp = (struct contig_mem *)kmem_zalloc(
16096 		    sizeof (struct contig_mem) + biosize(),
16097 		    alloc_flags);
16098 		if (cp == NULL) {
16099 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16100 			    "alloc contig_mem failure\n");
16101 			return (NULL); /* cannot get one */
16102 		}
16103 		cp->cm_bp = (struct buf *)
16104 		    (((caddr_t)cp) + sizeof (struct contig_mem));
16105 		bioinit(cp->cm_bp);
16106 		mutex_enter(ST_MUTEX);
16107 		un->un_contig_mem_total_num++; /* one more available */
16108 	} else {
16109 		/*
16110 		 * we failed to get one and we're NOT allowed to
16111 		 * alloc more contig_mem
16112 		 */
16113 		if (alloc_flags == KM_SLEEP) {
16114 			while (un->un_contig_mem_available_num <= 0) {
16115 				cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16116 			}
16117 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16118 		} else {
16119 			mutex_exit(ST_MUTEX);
16120 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16121 			    "alloc contig_mem failure\n");
16122 			return (NULL); /* cannot get one */
16123 		}
16124 	}
16125 	mutex_exit(ST_MUTEX);
16126 
16127 	/* We need to check if this block of mem is big enough for this I/O */
16128 	if (cp->cm_len < len) {
16129 		/* not big enough, need to alloc a new one */
16130 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
16131 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
16132 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
16133 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16134 			    "alloc contig_mem failure: not enough mem\n");
16135 			st_release_contig_mem(un, cp);
16136 			cp = NULL;
16137 		} else {
16138 			if (cp->cm_addr) {
16139 				/* release previous one before attach new one */
16140 				ddi_dma_mem_free(&cp->cm_acc_hdl);
16141 			}
16142 			mutex_enter(ST_MUTEX);
16143 			un->un_max_contig_mem_len =
16144 			    un->un_max_contig_mem_len >= len ?
16145 			    un->un_max_contig_mem_len : len;
16146 			mutex_exit(ST_MUTEX);
16147 
16148 			/* attach new mem to this cp */
16149 			cp->cm_addr = addr;
16150 			cp->cm_acc_hdl = acc_hdl;
16151 			cp->cm_len = len;
16152 
16153 			goto alloc_ok; /* get one usable cp */
16154 		}
16155 	} else {
16156 		goto alloc_ok; /* get one usable cp */
16157 	}
16158 
16159 	/* cannot find/alloc a usable cp, when we get here */
16160 
16161 	mutex_enter(ST_MUTEX);
16162 	if ((un->un_max_contig_mem_len < len) ||
16163 	    (alloc_flags != KM_SLEEP)) {
16164 		mutex_exit(ST_MUTEX);
16165 		return (NULL);
16166 	}
16167 
16168 	/*
16169 	 * we're allowed to sleep, and there is one big enough
16170 	 * contig mem in the system, which is currently in use,
16171 	 * wait for it...
16172 	 */
16173 	big_enough = 1;
16174 	do {
16175 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16176 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16177 	} while (cp == NULL);
16178 	mutex_exit(ST_MUTEX);
16179 
16180 	/* we get the big enough contig mem, finally */
16181 
16182 alloc_ok:
16183 	/* init bp attached to this cp */
16184 	bioreset(cp->cm_bp);
16185 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
16186 	cp->cm_bp->b_private = (void *)cp;
16187 
16188 	return (cp);
16189 }
16190 
16191 /*
16192  * this is the biodone func for the bp used in big block I/O
16193  */
16194 static int
16195 st_bigblk_xfer_done(struct buf *bp)
16196 {
16197 	struct contig_mem *cp;
16198 	struct buf *orig_bp;
16199 	int ioerr;
16200 	struct scsi_tape *un;
16201 
16202 	/* sanity check */
16203 	if (bp == NULL) {
16204 		return (DDI_FAILURE);
16205 	}
16206 
16207 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16208 	if (un == NULL) {
16209 		return (DDI_FAILURE);
16210 	}
16211 
16212 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
16213 
16214 	cp = (struct contig_mem *)bp->b_private;
16215 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
16216 	cp->cm_bp = bp;
16217 
16218 	/* special handling for special I/O */
16219 	if (cp->cm_use_sbuf) {
16220 #ifndef __lock_lint
16221 		ASSERT(un->un_sbuf_busy);
16222 #endif
16223 		un->un_sbufp = orig_bp;
16224 		cp->cm_use_sbuf = 0;
16225 	}
16226 
16227 	orig_bp->b_resid = bp->b_resid;
16228 	ioerr = geterror(bp);
16229 	if (ioerr != 0) {
16230 		bioerror(orig_bp, ioerr);
16231 	} else if (orig_bp->b_flags & B_READ) {
16232 		/* copy data back to original bp */
16233 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
16234 		    bp->b_bcount - bp->b_resid);
16235 	}
16236 
16237 	st_release_contig_mem(un, cp);
16238 
16239 	biodone(orig_bp);
16240 
16241 	return (DDI_SUCCESS);
16242 }
16243 
16244 /*
16245  * We use this func to replace original bp that may not be able to do I/O
16246  * in big block size with one that can
16247  */
16248 static struct buf *
16249 st_get_bigblk_bp(struct buf *bp)
16250 {
16251 	struct contig_mem *cp;
16252 	struct scsi_tape *un;
16253 	struct buf *cont_bp;
16254 
16255 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16256 	if (un == NULL) {
16257 		return (bp);
16258 	}
16259 
16260 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
16261 
16262 	/* try to get one contig_mem */
16263 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
16264 	if (!cp) {
16265 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
16266 		    "Cannot alloc contig buf for I/O for %lu blk size",
16267 		    bp->b_bcount);
16268 		return (bp);
16269 	}
16270 	cont_bp = cp->cm_bp;
16271 	cp->cm_bp = bp;
16272 
16273 	/* make sure that we "are" using un_sbufp for special I/O */
16274 	if (bp == un->un_sbufp) {
16275 #ifndef __lock_lint
16276 		ASSERT(un->un_sbuf_busy);
16277 #endif
16278 		un->un_sbufp = cont_bp;
16279 		cp->cm_use_sbuf = 1;
16280 	}
16281 
16282 	/* clone bp */
16283 	cont_bp->b_bcount = bp->b_bcount;
16284 	cont_bp->b_resid = bp->b_resid;
16285 	cont_bp->b_iodone = st_bigblk_xfer_done;
16286 	cont_bp->b_file = bp->b_file;
16287 	cont_bp->b_offset = bp->b_offset;
16288 	cont_bp->b_dip = bp->b_dip;
16289 	cont_bp->b_error = 0;
16290 	cont_bp->b_proc = NULL;
16291 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
16292 	cont_bp->b_shadow = NULL;
16293 	cont_bp->b_pages = NULL;
16294 	cont_bp->b_edev = bp->b_edev;
16295 	cont_bp->b_dev = bp->b_dev;
16296 	cont_bp->b_lblkno = bp->b_lblkno;
16297 	cont_bp->b_forw = bp->b_forw;
16298 	cont_bp->b_back = bp->b_back;
16299 	cont_bp->av_forw = bp->av_forw;
16300 	cont_bp->av_back = bp->av_back;
16301 	cont_bp->b_bufsize = bp->b_bufsize;
16302 
16303 	/* get data in original bp */
16304 	if (bp->b_flags & B_WRITE) {
16305 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
16306 	}
16307 
16308 	return (cont_bp);
16309 }
16310 #else
16311 #ifdef __lock_lint
16312 static int
16313 st_bigblk_xfer_done(struct buf *bp)
16314 {
16315 	return (0);
16316 }
16317 #endif
16318 #endif
16319 
16320 static const char *eof_status[] =
16321 {
16322 	"NO_EOF",
16323 	"EOF_PENDING",
16324 	"EOF",
16325 	"EOT_PENDING",
16326 	"EOT",
16327 	"EOM",
16328 	"AFTER_EOM"
16329 };
16330 static const char *mode[] = {
16331 	"invalid",
16332 	"legacy",
16333 	"logical"
16334 };
16335 
16336 static void
16337 st_print_position(dev_info_t *dev, char *label, uint_t level,
16338 const char *comment, tapepos_t *pos)
16339 {
16340 	ST_FUNC(dev, st_print_position);
16341 
16342 	scsi_log(dev, label, level,
16343 	    "%s Position data:\n", comment);
16344 	scsi_log(dev, label, CE_CONT,
16345 	    "Positioning mode = %s", mode[pos->pmode]);
16346 	scsi_log(dev, label, CE_CONT,
16347 	    "End Of File/Tape = %s", eof_status[pos->eof]);
16348 	scsi_log(dev, label, CE_CONT,
16349 	    "File Number      = 0x%x", pos->fileno);
16350 	scsi_log(dev, label, CE_CONT,
16351 	    "Block Number     = 0x%x", pos->blkno);
16352 	scsi_log(dev, label, CE_CONT,
16353 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
16354 	scsi_log(dev, label, CE_CONT,
16355 	    "Partition Number = 0x%x", pos->partition);
16356 }
16357 static int
16358 st_check_if_media_changed(struct scsi_tape *un, caddr_t data, int size)
16359 {
16360 
16361 	int result = 0;
16362 	int i;
16363 	ST_FUNC(ST_DEVINFO, st_check_if_media_changed);
16364 
16365 	/*
16366 	 * find non alpha numeric working from the end.
16367 	 */
16368 	for (i = size - 1; i >= 0; i--) {
16369 		if (ISALNUM(data[i]) == 0 || data[i] == ' ') {
16370 			data[i] = 0;
16371 			size = i;
16372 		}
16373 	}
16374 
16375 	if (size == 1) {
16376 		/*
16377 		 * Drive seems to think its returning useful data
16378 		 * but it looks like all junk
16379 		 */
16380 		return (result);
16381 	}
16382 
16383 	size++;
16384 
16385 	/*
16386 	 * Actually got a valid serial number.
16387 	 * If never stored one before alloc space for it.
16388 	 */
16389 	if (un->un_media_id_len == 0) {
16390 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16391 		un->un_media_id_len = size;
16392 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16393 		un->un_media_id[min(size, strlen(data))] = 0;
16394 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16395 		    "Found Media Id %s length = %d\n", un->un_media_id, size);
16396 	} else if (size > un->un_media_id_len) {
16397 		if (strncmp(un->un_media_id, data, size) != 0) {
16398 			result = ESPIPE;
16399 		}
16400 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16401 		    "Longer Media Id old ID:%s new ID:%s\n",
16402 		    un->un_media_id, data);
16403 		kmem_free(un->un_media_id, un->un_media_id_len);
16404 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16405 		un->un_media_id_len = size;
16406 		(void) strncpy(un->un_media_id, data, size);
16407 		un->un_media_id[size] = 0;
16408 	} else if (strncmp(data, un->un_media_id,
16409 	    min(size, un->un_media_id_len)) != 0) {
16410 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16411 		    "Old Media Id %s length = %d New %s length = %d\n",
16412 		    un->un_media_id, un->un_media_id_len, data, size);
16413 		bzero(un->un_media_id, un->un_media_id_len);
16414 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16415 		un->un_media_id[min(size, strlen(data))] = 0;
16416 		result = ESPIPE;
16417 	} else {
16418 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
16419 		    "Media Id still %s\n", un->un_media_id);
16420 	}
16421 
16422 	ASSERT(strlen(un->un_media_id) <= size);
16423 
16424 	return (result);
16425 }
16426 #define	ID_SIZE 32
16427 typedef struct
16428 {
16429 	uchar_t avilable_data0;
16430 	uchar_t avilable_data1;
16431 	uchar_t avilable_data2;
16432 	uchar_t avilable_data3;
16433 	uchar_t attribute_msb;
16434 	uchar_t attribute_lsb;
16435 #ifdef _BIT_FIELDS_LTOH
16436 	uchar_t format		: 2,
16437 				: 5,
16438 		read_only	: 1;
16439 #else
16440 	uchar_t read_only	: 1,
16441 				: 5,
16442 		format		: 2;
16443 #endif
16444 	uchar_t attribute_len_msb;
16445 	uchar_t attribute_len_lsb;
16446 }attribute_header;
16447 
16448 typedef struct {
16449 	attribute_header header;
16450 	char data[1];
16451 }mam_attribute;
16452 
16453 static int
16454 st_handle_hex_media_id(struct scsi_tape *un, void *pnt, int size)
16455 {
16456 	int result;
16457 	int newsize = (size << 1) + 3; /* extra for leading 0x and null term */
16458 	int i;
16459 	uchar_t byte;
16460 	char *format;
16461 	uchar_t *data = (uchar_t *)pnt;
16462 	char *buf = kmem_alloc(newsize, KM_SLEEP);
16463 
16464 	ST_FUNC(ST_DEVINFO, st_handle_hex_media_id);
16465 
16466 	(void) sprintf(buf, "0x");
16467 	for (i = 0; i < size; i++) {
16468 		byte = data[i];
16469 		if (byte < 0x10)
16470 			format = "0%x";
16471 		else
16472 			format = "%x";
16473 		(void) sprintf(&buf[(int)strlen(buf)], format, byte);
16474 	}
16475 	result = st_check_if_media_changed(un, buf, newsize);
16476 
16477 	kmem_free(buf, newsize);
16478 
16479 	return (result);
16480 }
16481 
16482 
16483 static int
16484 st_get_media_id_via_read_attribute(struct scsi_tape *un, ubufunc_t bufunc)
16485 {
16486 	int result;
16487 	mam_attribute *buffer;
16488 	int size;
16489 	int newsize;
16490 
16491 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_read_attribute);
16492 	size = sizeof (attribute_header) + max(un->un_media_id_len, ID_SIZE);
16493 again:
16494 	buffer = kmem_zalloc(size, KM_SLEEP);
16495 	result = st_read_attributes(un, 0x0401, buffer, size, bufunc);
16496 	if (result == 0) {
16497 
16498 		newsize = (buffer->header.attribute_len_msb << 8) |
16499 		    buffer->header.attribute_len_lsb;
16500 
16501 		if (newsize + sizeof (attribute_header) > size) {
16502 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
16503 			    "resizing read attribute data from %d to %d format"
16504 			    " %d\n", size, (int)sizeof (attribute_header) +
16505 			    newsize, buffer->header.format);
16506 			kmem_free(buffer, size);
16507 			size = newsize + sizeof (attribute_header);
16508 			goto again;
16509 		}
16510 
16511 		un->un_media_id_method = st_get_media_id_via_read_attribute;
16512 		if (buffer->header.format == 0) {
16513 			result =
16514 			    st_handle_hex_media_id(un, buffer->data, newsize);
16515 		} else {
16516 			result = st_check_if_media_changed(un, buffer->data,
16517 			    newsize);
16518 		}
16519 	} else if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
16520 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
16521 		    "Read Attribute Command for Media Identification is not "
16522 		    "supported on the HBA that this drive is attached to.");
16523 		result = ENOTTY;
16524 	}
16525 
16526 	kmem_free(buffer, size);
16527 	un->un_status = 0;
16528 
16529 	return (result);
16530 }
16531 
16532 
16533 static int
16534 st_get_media_id_via_media_serial_cmd(struct scsi_tape *un, ubufunc_t bufunc)
16535 {
16536 	char cdb[CDB_GROUP5];
16537 	struct uscsi_cmd *ucmd;
16538 	struct scsi_extended_sense sense;
16539 	int rval;
16540 	int size = max(un->un_media_id_len, ID_SIZE);
16541 	caddr_t buf;
16542 
16543 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_media_serial_cmd);
16544 
16545 	if (un->un_sd->sd_inq->inq_ansi < 3) {
16546 		return (ENOTTY);
16547 	}
16548 
16549 	ucmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
16550 upsize:
16551 	buf = kmem_alloc(size, KM_SLEEP);
16552 
16553 	cdb[0] = (char)SCMD_SVC_ACTION_IN_G5;
16554 	cdb[1] = SSVC_ACTION_READ_MEDIA_SERIAL;
16555 	cdb[2] = 0;
16556 	cdb[3] = 0;
16557 	cdb[4] = 0;
16558 	cdb[5] = 0;
16559 	cdb[6] = (char)(size >> 24);
16560 	cdb[7] = (char)(size >> 16);
16561 	cdb[8] = (char)(size >> 8);
16562 	cdb[9] = (char)(size);
16563 	cdb[10] = 0;
16564 	cdb[11] = 0;
16565 
16566 	ucmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
16567 	ucmd->uscsi_timeout = un->un_dp->non_motion_timeout;
16568 	ucmd->uscsi_cdb = &cdb[0];
16569 	ucmd->uscsi_cdblen = sizeof (cdb);
16570 	ucmd->uscsi_bufaddr = buf;
16571 	ucmd->uscsi_buflen = size;
16572 	ucmd->uscsi_rqbuf = (caddr_t)&sense;
16573 	ucmd->uscsi_rqlen = sizeof (sense);
16574 
16575 	rval = bufunc(un, ucmd, FKIOCTL);
16576 
16577 	if (rval || ucmd->uscsi_status != 0) {
16578 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16579 		    "media serial command returned %d scsi_status %d"
16580 		    " rqstatus %d", rval, ucmd->uscsi_status,
16581 		    ucmd->uscsi_rqstatus);
16582 		/*
16583 		 * If this returns invalid operation code don't try again.
16584 		 */
16585 		if (sense.es_key == KEY_ILLEGAL_REQUEST &&
16586 		    sense.es_add_code == 0x20) {
16587 			rval = ENOTTY;
16588 		} else if (rval == 0) {
16589 			rval = EIO;
16590 		}
16591 		un->un_status = 0;
16592 	} else {
16593 		int act_size;
16594 
16595 		/*
16596 		 * get reported size.
16597 		 */
16598 		act_size = (int)buf[3] | (int)(buf[2] << 8) |
16599 		    (int)(buf[1] << 16) | (int)(buf[0] << 24);
16600 
16601 		/* documentation says mod 4. */
16602 		while (act_size & 3) {
16603 			act_size++;
16604 		}
16605 
16606 		/*
16607 		 * If reported size is larger that we our buffer.
16608 		 * Free the old one and allocate one that is larger
16609 		 * enough and re-issuse the command.
16610 		 */
16611 		if (act_size + 4 > size) {
16612 			kmem_free(buf, size);
16613 			size = act_size + 4;
16614 			goto upsize;
16615 		}
16616 
16617 		if (act_size == 0) {
16618 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16619 			    "media serial number is not available");
16620 			un->un_status = 0;
16621 			rval = 0;
16622 		} else {
16623 			/*
16624 			 * set data pointer to point to the start
16625 			 * of that serial number.
16626 			 */
16627 			un->un_media_id_method =
16628 			    st_get_media_id_via_media_serial_cmd;
16629 			rval =
16630 			    st_check_if_media_changed(un, &buf[4], act_size);
16631 		}
16632 	}
16633 
16634 	kmem_free(ucmd, sizeof (struct uscsi_cmd));
16635 	kmem_free(buf, size);
16636 
16637 	return (rval);
16638 }
16639 
16640 
16641 /* ARGSUSED */
16642 static int
16643 st_bogus_media_id(struct scsi_tape *un, ubufunc_t bufunc)
16644 {
16645 	ST_FUNC(ST_DEVINFO, st_bogus_media_id);
16646 
16647 	ASSERT(un->un_media_id == NULL || un->un_media_id == bogusID);
16648 	ASSERT(un->un_media_id_len == 0);
16649 	un->un_media_id = (char *)bogusID;
16650 	un->un_media_id_len = 0;
16651 	return (0);
16652 }
16653 
16654 typedef int (*media_chk_function)(struct scsi_tape *, ubufunc_t bufunc);
16655 
16656 media_chk_function media_chk_functions[] = {
16657 	st_get_media_id_via_media_serial_cmd,
16658 	st_get_media_id_via_read_attribute,
16659 	st_bogus_media_id
16660 };
16661 
16662 static int
16663 st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc)
16664 {
16665 	int result = 0;
16666 	int i;
16667 
16668 	ST_FUNC(ST_DEVINFO, st_get_media_identification);
16669 
16670 	for (i = 0; i < ST_NUM_MEMBERS(media_chk_functions); i++) {
16671 		if (result == ENOTTY) {
16672 			/*
16673 			 * Last operation type not supported by this device.
16674 			 * Make so next time it doesn`t do that again.
16675 			 */
16676 			un->un_media_id_method = media_chk_functions[i];
16677 		} else if (un->un_media_id_method != media_chk_functions[i] &&
16678 		    un->un_media_id_method != st_get_media_identification) {
16679 			continue;
16680 		}
16681 		result = media_chk_functions[i](un, bufunc);
16682 		/*
16683 		 * If result indicates the function was successful or
16684 		 * that the media is not the same as last known, break.
16685 		 */
16686 		if (result == 0 || result == ESPIPE) {
16687 			break;
16688 		}
16689 	}
16690 
16691 	return (result);
16692 }
16693 
16694 static errstate
16695 st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
16696     errstate onentry)
16697 {
16698 
16699 	int ret;
16700 	st_err_info *errinfo;
16701 	recov_info *ri = (recov_info *)pkt->pkt_private;
16702 
16703 	ST_FUNC(ST_DEVINFO, st_command_recovery);
16704 
16705 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16706 
16707 	ASSERT(un->un_recov_buf_busy == 0);
16708 
16709 	/*
16710 	 * Don't try and recover a reset that this device sent.
16711 	 */
16712 	if (un->un_rsvd_status & ST_INITIATED_RESET &&
16713 	    onentry == DEVICE_RESET) {
16714 		return (COMMAND_DONE_ERROR);
16715 	}
16716 
16717 	/*
16718 	 * See if expected position was passed with scsi_pkt.
16719 	 */
16720 	if (ri->privatelen == sizeof (recov_info)) {
16721 
16722 		/*
16723 		 * Not for this command.
16724 		 */
16725 		if (ri->cmd_attrib->do_not_recover) {
16726 			return (COMMAND_DONE_ERROR);
16727 		}
16728 
16729 		/*
16730 		 * Create structure to hold all error state info.
16731 		 */
16732 		errinfo = kmem_zalloc(ST_ERR_INFO_SIZE, KM_SLEEP);
16733 		errinfo->ei_error_type = onentry;
16734 		errinfo->ei_failing_bp = ri->cmd_bp;
16735 		COPY_POS(&errinfo->ei_expected_pos, &ri->pos);
16736 	} else {
16737 		/* disabled */
16738 		return (COMMAND_DONE_ERROR);
16739 	}
16740 
16741 	bcopy(pkt, &errinfo->ei_failed_pkt, scsi_pkt_size());
16742 	bcopy(pkt->pkt_scbp, &errinfo->ei_failing_status, SECMDS_STATUS_SIZE);
16743 	ret = ddi_taskq_dispatch(un->un_recov_taskq, st_recover, errinfo,
16744 	    DDI_NOSLEEP);
16745 	ASSERT(ret == DDI_SUCCESS);
16746 	if (ret != DDI_SUCCESS) {
16747 		kmem_free(errinfo, ST_ERR_INFO_SIZE);
16748 		return (COMMAND_DONE_ERROR);
16749 	}
16750 	return (JUST_RETURN); /* release calling thread */
16751 }
16752 
16753 
16754 static void
16755 st_recov_ret(struct scsi_tape *un, st_err_info *errinfo, errstate err)
16756 {
16757 	int error_number;
16758 	buf_t *bp;
16759 
16760 
16761 	ST_FUNC(ST_DEVINFO, st_recov_ret);
16762 
16763 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16764 #if !defined(lint)
16765 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
16766 #endif
16767 
16768 	bp = errinfo->ei_failing_bp;
16769 	kmem_free(errinfo, ST_ERR_INFO_SIZE);
16770 
16771 	switch (err) {
16772 	case JUST_RETURN:
16773 		mutex_exit(&un->un_sd->sd_mutex);
16774 		return;
16775 
16776 	case COMMAND_DONE:
16777 	case COMMAND_DONE_ERROR_RECOVERED:
16778 		ST_DO_KSTATS(bp, kstat_runq_exit);
16779 		error_number = 0;
16780 		break;
16781 
16782 	default:
16783 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16784 		    "st_recov_ret with unhandled errstat %d\n", err);
16785 		/* FALLTHROUGH */
16786 	case COMMAND_DONE_ERROR:
16787 		un->un_pos.pmode = invalid;
16788 		un->un_running.pmode = invalid;
16789 		/* FALLTHROUGH */
16790 	case COMMAND_DONE_EACCES:
16791 		ST_DO_KSTATS(bp, kstat_waitq_exit);
16792 		ST_DO_ERRSTATS(un, st_transerrs);
16793 		error_number = EIO;
16794 		st_set_pe_flag(un);
16795 		break;
16796 
16797 	}
16798 
16799 	st_bioerror(bp, error_number);
16800 	st_done_and_mutex_exit(un, bp);
16801 }
16802 
16803 
16804 static void
16805 st_recover(void *arg)
16806 {
16807 	st_err_info *const errinfo = (st_err_info *)arg;
16808 	uchar_t com = errinfo->ei_failed_pkt.pkt_cdbp[0];
16809 	struct scsi_tape *un;
16810 	tapepos_t cur_pos;
16811 	int rval;
16812 	errstate status = COMMAND_DONE_ERROR;
16813 	recov_info *rcv;
16814 	buf_t *bp;
16815 
16816 
16817 	rcv = errinfo->ei_failed_pkt.pkt_private;
16818 	ASSERT(rcv->privatelen == sizeof (recov_info));
16819 	bp = rcv->cmd_bp;
16820 
16821 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16822 
16823 	ASSERT(un != NULL);
16824 
16825 	mutex_enter(ST_MUTEX);
16826 
16827 	ST_FUNC(ST_DEVINFO, st_recover);
16828 
16829 	ST_CDB(ST_DEVINFO, "Recovering command",
16830 	    (caddr_t)errinfo->ei_failed_pkt.pkt_cdbp);
16831 	ST_SENSE(ST_DEVINFO, "sense status for failed command",
16832 	    (caddr_t)&errinfo->ei_failing_status,
16833 	    sizeof (struct scsi_arq_status));
16834 	ST_POS(ST_DEVINFO, rcv->cmd_attrib->recov_pos_type == POS_STARTING ?
16835 	    "starting position for recovery command" :
16836 	    "expected position for recovery command",
16837 	    &errinfo->ei_expected_pos);
16838 
16839 	rval = st_test_path_to_device(un);
16840 
16841 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16842 	    "st_recover called with %s, TUR returned %d\n",
16843 	    errstatenames[errinfo->ei_error_type], rval);
16844 	/*
16845 	 * If the drive responed to the TUR lets try and get it to sync
16846 	 * any data it might have in the buffer.
16847 	 */
16848 	if (rval == 0 && rcv->cmd_attrib->chg_tape_data) {
16849 		rval = st_rcmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
16850 		if (rval) {
16851 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16852 			    "st_recover failed to flush, returned %d\n", rval);
16853 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16854 			return;
16855 		}
16856 	}
16857 	switch (errinfo->ei_error_type) {
16858 	case ATTEMPT_RETRY:
16859 	case COMMAND_TIMEOUT:
16860 	case DEVICE_RESET:
16861 	case PATH_FAILED:
16862 		/*
16863 		 * For now if we can't talk to the device we are done.
16864 		 * If the drive is reserved we can try to get it back.
16865 		 */
16866 		if (rval != 0 && rval != EACCES) {
16867 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16868 			return;
16869 		}
16870 
16871 		/*
16872 		 * If reservation conflict and do a preempt, fail it.
16873 		 */
16874 		if ((un->un_rsvd_status &
16875 		    (ST_APPLICATION_RESERVATIONS | ST_RESERVE)) != 0) {
16876 			if ((errinfo->ei_failed_pkt.pkt_cdbp[0] ==
16877 			    SCMD_PERSISTENT_RESERVE_OUT) &&
16878 			    (errinfo->ei_failed_pkt.pkt_cdbp[1] ==
16879 			    ST_SA_SCSI3_PREEMPT) &&
16880 			    (SCBP_C(&errinfo->ei_failed_pkt) ==
16881 			    STATUS_RESERVATION_CONFLICT)) {
16882 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16883 				return;
16884 			}
16885 		}
16886 
16887 		/*
16888 		 * If we have already set a scsi II reserve and get a
16889 		 * conflict on a scsi III type reserve fail without
16890 		 * any attempt to recover.
16891 		 */
16892 		if ((un->un_rsvd_status & ST_RESERVE | ST_PRESERVE_RESERVE) &&
16893 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] ==
16894 		    SCMD_PERSISTENT_RESERVE_OUT) ||
16895 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] ==
16896 		    SCMD_PERSISTENT_RESERVE_IN)) {
16897 			st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16898 			return;
16899 		}
16900 
16901 		/*
16902 		 * If scsi II lost reserve try and get it back.
16903 		 */
16904 		if ((((un->un_rsvd_status &
16905 		    (ST_LOST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
16906 		    ST_LOST_RESERVE)) &&
16907 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] != SCMD_RELEASE)) {
16908 			rval = st_reserve_release(un, ST_RESERVE,
16909 			    st_uscsi_rcmd);
16910 			if (rval != 0) {
16911 				if (st_take_ownership(un, st_uscsi_rcmd) != 0) {
16912 					st_recov_ret(un, errinfo,
16913 					    COMMAND_DONE_EACCES);
16914 					return;
16915 				}
16916 			}
16917 			un->un_rsvd_status |= ST_RESERVE;
16918 			un->un_rsvd_status &= ~(ST_RELEASE | ST_LOST_RESERVE |
16919 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
16920 		}
16921 		rval = st_make_sure_mode_data_is_correct(un, st_uscsi_rcmd);
16922 		if (rval) {
16923 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16924 			return;
16925 		}
16926 		break;
16927 	case DEVICE_TAMPER:
16928 		/*
16929 		 * Check if the ASC/ASCQ says mode data has changed.
16930 		 */
16931 		if ((errinfo->ei_failing_status.sts_sensedata.es_add_code ==
16932 		    0x2a) &&
16933 		    (errinfo->ei_failing_status.sts_sensedata.es_qual_code ==
16934 		    0x01)) {
16935 			/*
16936 			 * See if mode sense changed.
16937 			 */
16938 			rval = st_make_sure_mode_data_is_correct(un,
16939 			    st_uscsi_rcmd);
16940 			if (rval) {
16941 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16942 				return;
16943 			}
16944 		}
16945 		/*
16946 		 * if we have a media id and its not bogus.
16947 		 * Check to see if it the same.
16948 		 */
16949 		if (un->un_media_id != NULL && un->un_media_id != bogusID) {
16950 			rval = st_get_media_identification(un, st_uscsi_rcmd);
16951 			if (rval == ESPIPE) {
16952 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16953 				return;
16954 			}
16955 		}
16956 		break;
16957 	default:
16958 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16959 		    "Unhandled error type %s in st_recover() 0x%x\n",
16960 		    errstatenames[errinfo->ei_error_type], com);
16961 	}
16962 
16963 	/*
16964 	 * if command is retriable retry it.
16965 	 * Special case here. The command attribute for SCMD_REQUEST_SENSE
16966 	 * does not say that it is retriable. That because if you reissue a
16967 	 * request sense and the target responds the sense data will have
16968 	 * been consumed and no long be valid. If we get a busy status on
16969 	 * request sense while the state is ST_STATE_SENSING this will
16970 	 * reissue that pkt.
16971 	 *
16972 	 * XXX If this request sense gets sent to a different port then
16973 	 * the original command that failed was sent on it will not get
16974 	 * valid sense data for that command.
16975 	 */
16976 	if (rcv->cmd_attrib->retriable || un->un_rqs_bp == bp) {
16977 		status = st_recover_reissue_pkt(un, &errinfo->ei_failed_pkt);
16978 
16979 	/*
16980 	 * if drive doesn't support read position we are done
16981 	 */
16982 	} else if (un->un_read_pos_type == NO_POS) {
16983 		status = COMMAND_DONE_ERROR;
16984 	/*
16985 	 * If this command results in a changed tape position,
16986 	 * lets see where we are.
16987 	 */
16988 	} else if (rcv->cmd_attrib->chg_tape_pos) {
16989 		/*
16990 		 * XXX May be a reason to choose a different type here.
16991 		 * Long format has file position information.
16992 		 * Short and Extended have information about whats
16993 		 * in the buffer. St's positioning assumes in the buffer
16994 		 * to be the same as on tape.
16995 		 */
16996 		rval = st_compare_expected_position(un, errinfo,
16997 		    rcv->cmd_attrib, &cur_pos);
16998 		if (rval == 0) {
16999 			status = COMMAND_DONE;
17000 		} else if (rval == EAGAIN) {
17001 			status = st_recover_reissue_pkt(un,
17002 			    &errinfo->ei_failed_pkt);
17003 		} else {
17004 			status = COMMAND_DONE_ERROR;
17005 		}
17006 	} else {
17007 		ASSERT(0);
17008 	}
17009 
17010 	st_recov_ret(un, errinfo, status);
17011 }
17012 
17013 static void
17014 st_recov_cb(struct scsi_pkt *pkt)
17015 {
17016 	struct scsi_tape *un;
17017 	struct buf *bp;
17018 	recov_info *rcv;
17019 	errstate action = COMMAND_DONE_ERROR;
17020 	int timout = ST_TRAN_BUSY_TIMEOUT; /* short (default) timeout */
17021 
17022 	/*
17023 	 * Get the buf from the packet.
17024 	 */
17025 	rcv = pkt->pkt_private;
17026 	ASSERT(rcv->privatelen == sizeof (recov_info));
17027 	bp = rcv->cmd_bp;
17028 
17029 	/*
17030 	 * get the unit from the buf.
17031 	 */
17032 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
17033 	ASSERT(un != NULL);
17034 
17035 	ST_FUNC(ST_DEVINFO, st_recov_cb);
17036 
17037 	mutex_enter(ST_MUTEX);
17038 
17039 	ASSERT(bp == un->un_recov_buf);
17040 
17041 
17042 	switch (pkt->pkt_reason) {
17043 	case CMD_CMPLT:
17044 		if (un->un_arq_enabled && pkt->pkt_state & STATE_ARQ_DONE) {
17045 			action = st_handle_autosense(un, bp, &rcv->pos);
17046 		} else  if ((SCBP(pkt)->sts_busy) ||
17047 		    (SCBP(pkt)->sts_chk) ||
17048 		    (SCBP(pkt)->sts_vu7)) {
17049 			action = st_check_error(un, pkt);
17050 		} else {
17051 			action = COMMAND_DONE;
17052 		}
17053 		break;
17054 	case CMD_TIMEOUT:
17055 		action = COMMAND_TIMEOUT;
17056 		break;
17057 	case CMD_TRAN_ERR:
17058 		action = QUE_COMMAND;
17059 		break;
17060 	case CMD_DEV_GONE:
17061 		if (un->un_multipath)
17062 			action = PATH_FAILED;
17063 		else
17064 			action = COMMAND_DONE_ERROR;
17065 		break;
17066 	default:
17067 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
17068 		    "pkt_reason not handled yet %s",
17069 		    scsi_rname(pkt->pkt_reason));
17070 		action = COMMAND_DONE_ERROR;
17071 	}
17072 
17073 	/*
17074 	 * check for undetected path failover.
17075 	 */
17076 	if (un->un_multipath) {
17077 		if (scsi_pkt_allocated_correctly(pkt) &&
17078 		    (un->un_last_path_instance != pkt->pkt_path_instance)) {
17079 			if (un->un_state > ST_STATE_OPENING) {
17080 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17081 				    "Failover detected in recovery, action is "
17082 				    "%s\n", errstatenames[action]);
17083 			}
17084 			un->un_last_path_instance = pkt->pkt_path_instance;
17085 		}
17086 	}
17087 
17088 	ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
17089 	    "Recovery call back got %s status on %s\n",
17090 	    errstatenames[action], st_print_scsi_cmd(pkt->pkt_cdbp[0]));
17091 
17092 	switch (action) {
17093 	case COMMAND_DONE:
17094 		break;
17095 
17096 	case COMMAND_DONE_EACCES:
17097 		bioerror(bp, EACCES);
17098 		break;
17099 
17100 	case COMMAND_DONE_ERROR_RECOVERED: /* XXX maybe wrong */
17101 		ASSERT(0);
17102 		break;
17103 
17104 	case COMMAND_TIMEOUT:
17105 	case COMMAND_DONE_ERROR:
17106 		bioerror(bp, EIO);
17107 		break;
17108 
17109 	case DEVICE_RESET:
17110 	case QUE_BUSY_COMMAND:
17111 	case PATH_FAILED:
17112 		/* longish timeout */
17113 		timout = ST_STATUS_BUSY_TIMEOUT;
17114 		/* FALLTHRU */
17115 	case QUE_COMMAND:
17116 	case DEVICE_TAMPER:
17117 	case ATTEMPT_RETRY:
17118 		/*
17119 		 * let st_handle_intr_busy put this bp back on waitq and make
17120 		 * checks to see if it is ok to requeue the command.
17121 		 */
17122 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
17123 
17124 		/*
17125 		 * Save the throttle before setting up the timeout
17126 		 */
17127 		if (un->un_throttle) {
17128 			un->un_last_throttle = un->un_throttle;
17129 		}
17130 		mutex_exit(ST_MUTEX);
17131 		if (st_handle_intr_busy(un, bp, timout) == 0) {
17132 			return;		/* timeout is setup again */
17133 		}
17134 		mutex_enter(ST_MUTEX);
17135 		un->un_pos.pmode = invalid;
17136 		un->un_err_resid = bp->b_resid = bp->b_bcount;
17137 		st_bioerror(bp, EIO);
17138 		st_set_pe_flag(un);
17139 		break;
17140 
17141 	default:
17142 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
17143 		    "Unhandled recovery state 0x%x\n", action);
17144 		un->un_pos.pmode = invalid;
17145 		un->un_err_resid = bp->b_resid = bp->b_bcount;
17146 		st_bioerror(bp, EIO);
17147 		st_set_pe_flag(un);
17148 		break;
17149 	}
17150 
17151 	st_done_and_mutex_exit(un, bp);
17152 }
17153 
17154 static int
17155 st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait)
17156 {
17157 	struct buf *bp;
17158 	int err;
17159 
17160 	ST_FUNC(ST_DEVINFO, st_rcmd);
17161 
17162 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
17163 	    "st_rcmd(un = 0x%p, com = 0x%x, count = %"PRIx64", wait = %d)\n",
17164 	    (void *)un, com, count, wait);
17165 
17166 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
17167 	ASSERT(mutex_owned(ST_MUTEX));
17168 
17169 #ifdef STDEBUG
17170 	if ((st_debug & 0x7)) {
17171 		st_debug_cmds(un, com, count, wait);
17172 	}
17173 #endif
17174 
17175 	while (un->un_recov_buf_busy)
17176 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17177 	un->un_recov_buf_busy = 1;
17178 
17179 	bp = un->un_recov_buf;
17180 	bzero(bp, sizeof (buf_t));
17181 
17182 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
17183 
17184 	err = st_setup_cmd(un, bp, com, count);
17185 
17186 	un->un_recov_buf_busy = 0;
17187 
17188 	cv_signal(&un->un_recov_buf_cv);
17189 
17190 	return (err);
17191 }
17192 
17193 /* args used */
17194 static int
17195 st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
17196 {
17197 	int rval;
17198 	buf_t *bp;
17199 
17200 	ST_FUNC(ST_DEVINFO, st_uscsi_rcmd);
17201 	ASSERT(flag == FKIOCTL);
17202 
17203 	/*
17204 	 * Get buffer resources...
17205 	 */
17206 	while (un->un_recov_buf_busy)
17207 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17208 	un->un_recov_buf_busy = 1;
17209 
17210 	bp = un->un_recov_buf;
17211 	bzero(bp, sizeof (buf_t));
17212 
17213 	bp->b_forw = (struct buf *)(uintptr_t)ucmd->uscsi_cdb[0];
17214 	bp->b_back = (struct buf *)ucmd;
17215 
17216 	mutex_exit(ST_MUTEX);
17217 	rval = scsi_uscsi_handle_cmd(un->un_dev, UIO_SYSSPACE, ucmd,
17218 	    st_strategy, bp, NULL);
17219 	mutex_enter(ST_MUTEX);
17220 
17221 	ucmd->uscsi_resid = bp->b_resid;
17222 
17223 	/*
17224 	 * Free resources
17225 	 */
17226 	un->un_recov_buf_busy = 0;
17227 	cv_signal(&un->un_recov_buf_cv);
17228 
17229 	return (rval);
17230 }
17231 
17232 /*
17233  * Add data to scsi_pkt to help know what to do if the command fails.
17234  */
17235 static void
17236 st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
17237     struct scsi_pkt *pkt)
17238 {
17239 	uint64_t count;
17240 	recov_info *rinfo = (recov_info *)pkt->pkt_private;
17241 
17242 	ST_FUNC(ST_DEVINFO, st_add_recovery_info_to_pkt);
17243 
17244 	ASSERT(rinfo->privatelen == sizeof (pkt_info) ||
17245 	    rinfo->privatelen == sizeof (recov_info));
17246 
17247 	SET_BP_PKT(bp, pkt);
17248 	rinfo->cmd_bp = bp;
17249 
17250 	if (rinfo->privatelen != sizeof (recov_info)) {
17251 		return;
17252 	}
17253 
17254 	rinfo->cmd_bp = bp;
17255 
17256 	rinfo->cmd_attrib = NULL;
17257 
17258 	/*
17259 	 * lookup the command attributes and add them to the recovery info.
17260 	 */
17261 	rinfo->cmd_attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
17262 
17263 	ASSERT(rinfo->cmd_attrib);
17264 
17265 	/*
17266 	 * For commands that there is no way to figure the expected position
17267 	 * once completed, we save the position the command was started from
17268 	 * so that if they fail we can position back and try again.
17269 	 * This has already been done in st_cmd() or st_iscsi_cmd().
17270 	 */
17271 	if (rinfo->cmd_attrib->recov_pos_type == POS_STARTING) {
17272 		/* save current position as the starting position. */
17273 		COPY_POS(&rinfo->pos, &un->un_pos);
17274 		un->un_running.pmode = invalid;
17275 		return;
17276 	}
17277 
17278 	/*
17279 	 * Don't want to update the running position for recovery.
17280 	 */
17281 	if (bp == un->un_recov_buf) {
17282 		rinfo->pos.pmode = un->un_running.pmode;
17283 		return;
17284 	}
17285 	/*
17286 	 * If running position is invalid copy the current position.
17287 	 * Running being set invalid means we are not in a read, write
17288 	 * or write filemark sequence.
17289 	 * We'll copy the current position and start from there.
17290 	 */
17291 	if (un->un_running.pmode == invalid) {
17292 		COPY_POS(&un->un_running, &un->un_pos);
17293 		COPY_POS(&rinfo->pos, &un->un_running);
17294 	} else {
17295 		COPY_POS(&rinfo->pos, &un->un_running);
17296 		if (rinfo->pos.pmode == legacy) {
17297 			/*
17298 			 * Always should be more logical blocks then
17299 			 * data blocks and files marks.
17300 			 */
17301 			ASSERT((rinfo->pos.blkno >= 0) ?
17302 			    rinfo->pos.lgclblkno >=
17303 			    (rinfo->pos.blkno + rinfo->pos.fileno) : 1);
17304 		}
17305 	}
17306 
17307 	/*
17308 	 * If the command is not expected to change the drive position
17309 	 * then the running position should be the expected position.
17310 	 */
17311 	if (rinfo->cmd_attrib->chg_tape_pos == 0) {
17312 		ASSERT(rinfo->cmd_attrib->chg_tape_direction == DIR_NONE);
17313 		return;
17314 	}
17315 
17316 	if (rinfo->cmd_attrib->explicit_cmd_set) {
17317 		ASSERT(rinfo->pos.pmode != invalid);
17318 		ASSERT(rinfo->cmd_attrib->get_cnt);
17319 		count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17320 		/*
17321 		 * This is a user generated CDB.
17322 		 */
17323 		if (bp == un->un_sbufp) {
17324 			uint64_t lbn;
17325 
17326 			lbn = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17327 
17328 			/*
17329 			 * See if this CDB will generate a locate or change
17330 			 * partition.
17331 			 */
17332 			if ((lbn != un->un_running.lgclblkno) ||
17333 			    (pkt->pkt_cdbp[3] != un->un_running.partition)) {
17334 				rinfo->pos.partition = pkt->pkt_cdbp[3];
17335 				rinfo->pos.pmode = logical;
17336 				rinfo->pos.lgclblkno = lbn;
17337 				un->un_running.partition = pkt->pkt_cdbp[3];
17338 				un->un_running.pmode = logical;
17339 				un->un_running.lgclblkno = lbn;
17340 			}
17341 		} else {
17342 			uint64_t lbn = un->un_running.lgclblkno;
17343 
17344 			pkt->pkt_cdbp[3]  = (uchar_t)un->un_running.partition;
17345 
17346 			pkt->pkt_cdbp[4]  = (uchar_t)(lbn >> 56);
17347 			pkt->pkt_cdbp[5]  = (uchar_t)(lbn >> 48);
17348 			pkt->pkt_cdbp[6]  = (uchar_t)(lbn >> 40);
17349 			pkt->pkt_cdbp[7]  = (uchar_t)(lbn >> 32);
17350 			pkt->pkt_cdbp[8]  = (uchar_t)(lbn >> 24);
17351 			pkt->pkt_cdbp[9]  = (uchar_t)(lbn >> 16);
17352 			pkt->pkt_cdbp[10] = (uchar_t)(lbn >> 8);
17353 			pkt->pkt_cdbp[11] = (uchar_t)(lbn);
17354 		}
17355 		rinfo->pos.lgclblkno += count;
17356 		rinfo->pos.blkno += count;
17357 		un->un_running.lgclblkno += count;
17358 		return;
17359 	}
17360 
17361 	if (rinfo->cmd_attrib->chg_tape_pos) {
17362 
17363 		/* should not have got an invalid position from running. */
17364 		if (un->un_mediastate == MTIO_INSERTED) {
17365 			ASSERT(rinfo->pos.pmode != invalid);
17366 		}
17367 
17368 		/* should have either a get count or or get lba function */
17369 		ASSERT(rinfo->cmd_attrib->get_cnt != NULL ||
17370 		    rinfo->cmd_attrib->get_lba != NULL);
17371 
17372 		/* only explicit commands have both and they're handled above */
17373 		ASSERT(!(rinfo->cmd_attrib->get_cnt != NULL &&
17374 		    rinfo->cmd_attrib->get_lba != NULL));
17375 
17376 		/* if it has a get count function */
17377 		if (rinfo->cmd_attrib->get_cnt != NULL) {
17378 			count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17379 			if (count == 0) {
17380 				return;
17381 			}
17382 			/*
17383 			 * Changes position but doesn't transfer data.
17384 			 * i.e. rewind, write_file_mark and load.
17385 			 */
17386 			if (rinfo->cmd_attrib->transfers_data == TRAN_NONE) {
17387 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17388 				case DIR_NONE: /* Erase */
17389 					ASSERT(rinfo->cmd_attrib->cmd ==
17390 					    SCMD_ERASE);
17391 					break;
17392 				case DIR_FORW: /* write_file_mark */
17393 					rinfo->pos.fileno += count;
17394 					rinfo->pos.lgclblkno += count;
17395 					rinfo->pos.blkno = 0;
17396 					un->un_running.fileno += count;
17397 					un->un_running.lgclblkno += count;
17398 					un->un_running.blkno = 0;
17399 					break;
17400 				case DIR_REVC: /* rewind */
17401 					rinfo->pos.fileno = 0;
17402 					rinfo->pos.lgclblkno = 0;
17403 					rinfo->pos.blkno = 0;
17404 					rinfo->pos.eof = ST_NO_EOF;
17405 					rinfo->pos.pmode = legacy;
17406 					un->un_running.fileno = 0;
17407 					un->un_running.lgclblkno = 0;
17408 					un->un_running.blkno = 0;
17409 					un->un_running.eof = ST_NO_EOF;
17410 					if (un->un_running.pmode != legacy)
17411 						un->un_running.pmode = legacy;
17412 					break;
17413 				case DIR_EITH: /* Load unload */
17414 					ASSERT(rinfo->cmd_attrib->cmd ==
17415 					    SCMD_LOAD);
17416 					switch (count & (LD_LOAD | LD_RETEN |
17417 					    LD_RETEN | LD_HOLD)) {
17418 					case LD_UNLOAD:
17419 					case LD_RETEN:
17420 					case LD_HOLD:
17421 					case LD_LOAD | LD_HOLD:
17422 					case LD_EOT | LD_HOLD:
17423 					case LD_RETEN | LD_HOLD:
17424 						rinfo->pos.pmode = invalid;
17425 						un->un_running.pmode = invalid;
17426 						break;
17427 					case LD_EOT:
17428 					case LD_LOAD | LD_EOT:
17429 						rinfo->pos.eof = ST_EOT;
17430 						rinfo->pos.pmode = invalid;
17431 						un->un_running.eof = ST_EOT;
17432 						un->un_running.pmode = invalid;
17433 						break;
17434 					case LD_LOAD:
17435 					case LD_RETEN | LD_LOAD:
17436 						rinfo->pos.fileno = 0;
17437 						rinfo->pos.lgclblkno = 0;
17438 						rinfo->pos.blkno = 0;
17439 						rinfo->pos.eof = ST_NO_EOF;
17440 						rinfo->pos.pmode = legacy;
17441 						un->un_running.fileno = 0;
17442 						un->un_running.lgclblkno = 0;
17443 						un->un_running.blkno = 0;
17444 						un->un_running.eof = ST_NO_EOF;
17445 						break;
17446 					default:
17447 						ASSERT(0);
17448 					}
17449 					break;
17450 				default:
17451 					ASSERT(0);
17452 					break;
17453 				}
17454 			} else {
17455 				/*
17456 				 * Changes position and does transfer data.
17457 				 * i.e. read or write.
17458 				 */
17459 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17460 				case DIR_FORW:
17461 					rinfo->pos.lgclblkno += count;
17462 					rinfo->pos.blkno += count;
17463 					un->un_running.lgclblkno += count;
17464 					un->un_running.blkno += count;
17465 					break;
17466 				case DIR_REVC:
17467 					rinfo->pos.lgclblkno -= count;
17468 					rinfo->pos.blkno -= count;
17469 					un->un_running.lgclblkno -= count;
17470 					un->un_running.blkno -= count;
17471 					break;
17472 				default:
17473 					ASSERT(0);
17474 					break;
17475 				}
17476 			}
17477 		} else if (rinfo->cmd_attrib->get_lba != NULL) {
17478 			/* Have a get LBA fuction. i.e. Locate */
17479 			ASSERT(rinfo->cmd_attrib->chg_tape_direction ==
17480 			    DIR_EITH);
17481 			count = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17482 			un->un_running.lgclblkno = count;
17483 			un->un_running.blkno = 0;
17484 			un->un_running.fileno = 0;
17485 			un->un_running.pmode = logical;
17486 			rinfo->pos.lgclblkno = count;
17487 			rinfo->pos.pmode = invalid;
17488 		} else {
17489 			ASSERT(0);
17490 		}
17491 		return;
17492 	}
17493 
17494 	ST_CDB(ST_DEVINFO, "Unhanded CDB for position prediction",
17495 	    (char *)pkt->pkt_cdbp);
17496 
17497 }
17498 
17499 static int
17500 st_make_sure_mode_data_is_correct(struct scsi_tape *un, ubufunc_t ubf)
17501 {
17502 	int rval;
17503 
17504 	ST_FUNC(ST_DEVINFO, st_make_sure_mode_data_is_correct);
17505 
17506 	/*
17507 	 * check to see if mode data has changed.
17508 	 */
17509 	rval = st_check_mode_for_change(un, ubf);
17510 	if (rval) {
17511 		rval = st_gen_mode_select(un, ubf, un->un_mspl,
17512 		    sizeof (struct seq_mode));
17513 	}
17514 	if (un->un_tlr_flag != TLR_NOT_SUPPORTED) {
17515 		rval |= st_set_target_TLR_mode(un, ubf);
17516 	}
17517 	return (rval);
17518 }
17519 
17520 static int
17521 st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf)
17522 {
17523 	struct seq_mode *current;
17524 	int rval;
17525 	int i;
17526 	caddr_t this;
17527 	caddr_t that;
17528 
17529 	ST_FUNC(ST_DEVINFO, st_check_mode_for_change);
17530 
17531 	/* recovery called with mode tamper before mode selection */
17532 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
17533 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17534 		    "Mode Select not done yet");
17535 		return (0);
17536 	}
17537 
17538 	current = kmem_zalloc(sizeof (struct seq_mode), KM_SLEEP);
17539 
17540 	rval = st_gen_mode_sense(un, ubf, un->un_comp_page, current,
17541 	    sizeof (struct seq_mode));
17542 	if (rval != 0) {
17543 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17544 		    "Mode Sense for mode verification failed");
17545 		kmem_free(current, sizeof (struct seq_mode));
17546 		return (rval);
17547 	}
17548 
17549 	this = (caddr_t)current;
17550 	that = (caddr_t)un->un_mspl;
17551 
17552 	rval = bcmp(this, that, sizeof (struct seq_mode));
17553 	if (rval == 0) {
17554 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17555 		    "Found no changes in mode data");
17556 	}
17557 #ifdef STDEBUG
17558 	else {
17559 		for (i = 1; i < sizeof (struct seq_mode); i++) {
17560 			if (this[i] != that[i]) {
17561 				ST_RECOV(ST_DEVINFO, st_label, CE_CONT,
17562 				    "sense data changed at byte %d was "
17563 				    "0x%x now 0x%x", i,
17564 				    (uchar_t)that[i], (uchar_t)this[i]);
17565 			}
17566 		}
17567 	}
17568 #endif
17569 	kmem_free(current, sizeof (struct seq_mode));
17570 
17571 	return (rval);
17572 }
17573 
17574 static int
17575 st_test_path_to_device(struct scsi_tape *un)
17576 {
17577 	int rval = 0;
17578 	int limit = st_retry_count;
17579 
17580 	ST_FUNC(ST_DEVINFO, st_test_path_to_device);
17581 
17582 	/*
17583 	 * XXX Newer drives may not RESEVATION CONFLICT a TUR.
17584 	 */
17585 	do {
17586 		if (rval != 0) {
17587 			mutex_exit(ST_MUTEX);
17588 			delay(drv_usectohz(1000000));
17589 			mutex_enter(ST_MUTEX);
17590 		}
17591 		rval = st_rcmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
17592 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17593 		    "ping TUR returned 0x%x", rval);
17594 		limit--;
17595 	} while (((rval == EACCES) || (rval == EBUSY)) && limit);
17596 
17597 	if (un->un_status == KEY_NOT_READY || un->un_mediastate == MTIO_EJECTED)
17598 		rval = 0;
17599 
17600 	return (rval);
17601 }
17602 
17603 /*
17604  * Does read position using recov_buf and doesn't update un_pos.
17605  * Does what ever kind of read position you want.
17606  */
17607 static int
17608 st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
17609     read_pos_data_t *raw)
17610 {
17611 	int rval;
17612 	struct uscsi_cmd cmd;
17613 	struct scsi_arq_status status;
17614 	char cdb[CDB_GROUP1];
17615 
17616 	ST_FUNC(ST_DEVINFO, st_recovery_read_pos);
17617 	bzero(&cmd, sizeof (cmd));
17618 
17619 	cdb[0] = SCMD_READ_POSITION;
17620 	cdb[1] = type;
17621 	cdb[2] = 0;
17622 	cdb[3] = 0;
17623 	cdb[4] = 0;
17624 	cdb[5] = 0;
17625 	cdb[6] = 0;
17626 	cdb[7] = 0;
17627 	cdb[8] = (type == EXT_POS) ? 28 : 0;
17628 	cdb[9] = 0;
17629 
17630 	cmd.uscsi_flags = USCSI_READ | USCSI_RQENABLE;
17631 	cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
17632 	cmd.uscsi_cdb = cdb;
17633 	cmd.uscsi_cdblen = sizeof (cdb);
17634 	cmd.uscsi_rqlen = sizeof (status);
17635 	cmd.uscsi_rqbuf = (caddr_t)&status;
17636 	cmd.uscsi_bufaddr = (caddr_t)raw;
17637 	switch (type) {
17638 	case SHORT_POS:
17639 		cmd.uscsi_buflen = sizeof (tape_position_t);
17640 		break;
17641 	case LONG_POS:
17642 		cmd.uscsi_buflen = sizeof (tape_position_long_t);
17643 		break;
17644 	case EXT_POS:
17645 		cmd.uscsi_buflen = sizeof (tape_position_ext_t);
17646 		break;
17647 	default:
17648 		ASSERT(0);
17649 	}
17650 
17651 	rval = st_uscsi_rcmd(un, &cmd, FKIOCTL);
17652 	if (cmd.uscsi_status) {
17653 		rval = EIO;
17654 	}
17655 	return (rval);
17656 }
17657 
17658 static int
17659 st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
17660     read_pos_data_t *raw)
17661 {
17662 	int rval;
17663 	read_p_types type = un->un_read_pos_type;
17664 
17665 	ST_FUNC(ST_DEVINFO, st_recovery_get_position);
17666 
17667 	do {
17668 		rval = st_recovery_read_pos(un, type, raw);
17669 		if (rval != 0) {
17670 			switch (type) {
17671 			case SHORT_POS:
17672 				type = NO_POS;
17673 				break;
17674 
17675 			case LONG_POS:
17676 				type = EXT_POS;
17677 				break;
17678 
17679 			case EXT_POS:
17680 				type = SHORT_POS;
17681 				break;
17682 
17683 			default:
17684 				type = LONG_POS;
17685 				break;
17686 
17687 			}
17688 		} else {
17689 			if (type != un->un_read_pos_type) {
17690 				un->un_read_pos_type = type;
17691 			}
17692 			break;
17693 		}
17694 	} while (type != NO_POS);
17695 
17696 	if (rval == 0) {
17697 		rval = st_interpret_read_pos(un, read, type,
17698 		    sizeof (read_pos_data_t), (caddr_t)raw, 1);
17699 	}
17700 	return (rval);
17701 }
17702 
17703 /*
17704  * based on the command do we retry, continue or give up?
17705  * possable return values?
17706  *	zero do nothing looks fine.
17707  *	EAGAIN retry.
17708  *	EIO failed makes no sense.
17709  */
17710 static int
17711 st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
17712     cmd_attribute const * cmd_att, tapepos_t *read)
17713 {
17714 	int rval;
17715 	read_pos_data_t *readp_datap;
17716 
17717 	ST_FUNC(ST_DEVINFO, st_compare_expected_position);
17718 
17719 	ASSERT(un != NULL);
17720 	ASSERT(ei != NULL);
17721 	ASSERT(read != NULL);
17722 	ASSERT(cmd_att->chg_tape_pos);
17723 
17724 	COPY_POS(read, &ei->ei_expected_pos);
17725 
17726 	readp_datap = kmem_zalloc(sizeof (read_pos_data_t), KM_SLEEP);
17727 
17728 	rval = st_recovery_get_position(un, read, readp_datap);
17729 
17730 	kmem_free(readp_datap, sizeof (read_pos_data_t));
17731 
17732 	if (rval != 0) {
17733 		return (EIO);
17734 	}
17735 
17736 	ST_POS(ST_DEVINFO, "st_compare_expected_position", read);
17737 
17738 	if ((read->pmode == invalid) ||
17739 	    (ei->ei_expected_pos.pmode == invalid)) {
17740 		return (EIO);
17741 	}
17742 
17743 	/*
17744 	 * Command that changes tape position and have an expected position
17745 	 * if it were to chave completed sucessfully.
17746 	 */
17747 	if (cmd_att->recov_pos_type == POS_EXPECTED) {
17748 		uint32_t count;
17749 		int64_t difference;
17750 		uchar_t reposition = 0;
17751 
17752 		ASSERT(cmd_att->get_cnt);
17753 		count = cmd_att->get_cnt(ei->ei_failed_pkt.pkt_cdbp);
17754 
17755 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17756 		    "Got count from CDB and it was %d\n", count);
17757 
17758 		/*
17759 		 * At expected?
17760 		 */
17761 		if (read->lgclblkno == ei->ei_expected_pos.lgclblkno) {
17762 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17763 			    "Found drive to be at expected position\n");
17764 
17765 			/*
17766 			 * If the command should move tape and it got a busy
17767 			 * it shouldn't be in the expected position.
17768 			 */
17769 			if (ei->ei_failing_status.sts_status.sts_busy != 0) {
17770 				reposition = 1;
17771 
17772 			/*
17773 			 * If the command doesn't transfer data should be good.
17774 			 */
17775 			} else if (cmd_att->transfers_data == TRAN_NONE) {
17776 				return (0); /* Good */
17777 
17778 			/*
17779 			 * Command transfers data, should have done so.
17780 			 */
17781 			} else if (ei->ei_failed_pkt.pkt_state &
17782 			    STATE_XFERRED_DATA) {
17783 				return (0); /* Good */
17784 			} else {
17785 				reposition = 1;
17786 			}
17787 		}
17788 
17789 		if (cmd_att->chg_tape_direction == DIR_FORW) {
17790 			difference =
17791 			    ei->ei_expected_pos.lgclblkno - read->lgclblkno;
17792 
17793 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17794 			    "difference between expected and actual is %"
17795 			    PRId64"\n", difference);
17796 			if (count == difference && reposition == 0) {
17797 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17798 				    "Found failed FORW command, retrying\n");
17799 				return (EAGAIN);
17800 			}
17801 
17802 			/*
17803 			 * If rewound or somewhere between the starting position
17804 			 * and the expected position (partial read or write).
17805 			 * Locate to the starting position and try the whole
17806 			 * thing over again.
17807 			 */
17808 			if ((read->lgclblkno == 0) ||
17809 			    ((difference > 0) && (difference < count))) {
17810 				rval = st_logical_block_locate(un,
17811 				    st_uscsi_rcmd, read,
17812 				    ei->ei_expected_pos.lgclblkno - count,
17813 				    ei->ei_expected_pos.partition);
17814 				if (rval == 0) {
17815 					ST_RECOV(ST_DEVINFO, st_label,
17816 					    CE_NOTE, "reestablished FORW"
17817 					    " command retrying\n");
17818 					return (EAGAIN);
17819 				}
17820 			/*
17821 			 * This handles flushed read ahead on the drive or
17822 			 * an aborted read that presents as a busy and advanced
17823 			 * the tape position.
17824 			 */
17825 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17826 			    ((difference < 0) || (reposition == 1))) {
17827 				rval = st_logical_block_locate(un,
17828 				    st_uscsi_rcmd, read,
17829 				    ei->ei_expected_pos.lgclblkno - count,
17830 				    ei->ei_expected_pos.partition);
17831 				if (rval == 0) {
17832 					ST_RECOV(ST_DEVINFO, st_label,
17833 					    CE_NOTE, "reestablished FORW"
17834 					    " read command retrying\n");
17835 					return (EAGAIN);
17836 				}
17837 			/*
17838 			 * XXX swag seeing difference of 2 on write filemark.
17839 			 * If the space to the starting position works on a
17840 			 * write that means the previous write made it to tape.
17841 			 * If not we lost data and have to give up.
17842 			 *
17843 			 * The plot thickens. Now I am attempting to cover a
17844 			 * count of 1 and a differance of 2 on a write.
17845 			 */
17846 			} else if ((difference > count) || (reposition == 1)) {
17847 				rval = st_logical_block_locate(un,
17848 				    st_uscsi_rcmd, read,
17849 				    ei->ei_expected_pos.lgclblkno - count,
17850 				    ei->ei_expected_pos.partition);
17851 				if (rval == 0) {
17852 					ST_RECOV(ST_DEVINFO, st_label,
17853 					    CE_NOTE, "reestablished FORW"
17854 					    " write command retrying\n");
17855 					return (EAGAIN);
17856 				}
17857 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17858 				    "Seek to block %"PRId64" returned %d\n",
17859 				    ei->ei_expected_pos.lgclblkno - count,
17860 				    rval);
17861 			} else {
17862 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17863 				    "Not expected transfers_data = %d "
17864 				    "difference = %"PRId64,
17865 				    cmd_att->transfers_data, difference);
17866 			}
17867 
17868 			return (EIO);
17869 
17870 		} else if (cmd_att->chg_tape_direction == DIR_REVC) {
17871 			/* Don't think we can write backwards */
17872 			ASSERT(cmd_att->transfers_data != TRAN_WRTE);
17873 			difference =
17874 			    read->lgclblkno - ei->ei_expected_pos.lgclblkno;
17875 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17876 			    "difference between expected and actual is %"
17877 			    PRId64"\n", difference);
17878 			if (count == difference && reposition == 0) {
17879 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17880 				    "Found failed REVC command, retrying\n");
17881 				return (EAGAIN);
17882 			}
17883 			if ((read->lgclblkno == 0) ||
17884 			    ((difference > 0) && (difference < count))) {
17885 				rval = st_logical_block_locate(un,
17886 				    st_uscsi_rcmd, read,
17887 				    ei->ei_expected_pos.lgclblkno + count,
17888 				    ei->ei_expected_pos.partition);
17889 				if (rval == 0) {
17890 					ST_RECOV(ST_DEVINFO, st_label,
17891 					    CE_NOTE, "reestablished REVC"
17892 					    " command retrying\n");
17893 					return (EAGAIN);
17894 				}
17895 			/* This handles read ahead in reverse direction */
17896 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17897 			    (difference < 0) || (reposition == 1)) {
17898 				rval = st_logical_block_locate(un,
17899 				    st_uscsi_rcmd, read,
17900 				    ei->ei_expected_pos.lgclblkno - count,
17901 				    ei->ei_expected_pos.partition);
17902 				if (rval == 0) {
17903 					ST_RECOV(ST_DEVINFO, st_label,
17904 					    CE_NOTE, "reestablished REVC"
17905 					    " read command retrying\n");
17906 					return (EAGAIN);
17907 				}
17908 			} else {
17909 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17910 				    "Not expected transfers_data = %d "
17911 				    "difference = %"PRId64,
17912 				    cmd_att->transfers_data, difference);
17913 			}
17914 			return (EIO);
17915 
17916 		} else {
17917 			/*
17918 			 * Commands that change tape position either
17919 			 * direction or don't change position should not
17920 			 * get here.
17921 			 */
17922 			ASSERT(0);
17923 		}
17924 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17925 		    "Didn't find a recoverable position, Failing\n");
17926 
17927 	/*
17928 	 * Command that changes tape position and can only be recovered
17929 	 * by going back to the point of origin and retrying.
17930 	 *
17931 	 * Example SCMD_SPACE.
17932 	 */
17933 	} else if (cmd_att->recov_pos_type == POS_STARTING) {
17934 		/*
17935 		 * This type of command stores the starting position.
17936 		 * If the read position is the starting position,
17937 		 * reissue the command.
17938 		 */
17939 		if (ei->ei_expected_pos.lgclblkno == read->lgclblkno) {
17940 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17941 			    "Found Space command at starting position, "
17942 			    "Reissuing\n");
17943 			return (EAGAIN);
17944 		}
17945 		/*
17946 		 * Not in the position that the command was originally issued,
17947 		 * Attempt to locate to that position.
17948 		 */
17949 		rval = st_logical_block_locate(un, st_uscsi_rcmd, read,
17950 		    ei->ei_expected_pos.lgclblkno,
17951 		    ei->ei_expected_pos.partition);
17952 		if (rval) {
17953 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17954 			    "Found Space at an unexpected position and locate "
17955 			    "back to starting position failed\n");
17956 			return (EIO);
17957 		}
17958 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17959 		    "Found Space at an unexpected position and locate "
17960 		    "back to starting position worked, Reissuing\n");
17961 		return (EAGAIN);
17962 	}
17963 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17964 	    "Unhandled attribute/expected position", &ei->ei_expected_pos);
17965 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17966 	    "Read position above did not make sense", read);
17967 	ASSERT(0);
17968 	return (EIO);
17969 }
17970 
17971 static errstate
17972 st_recover_reissue_pkt(struct scsi_tape *un, struct scsi_pkt *oldpkt)
17973 {
17974 	buf_t *bp;
17975 	buf_t *pkt_bp;
17976 	struct scsi_pkt *newpkt;
17977 	cmd_attribute const *attrib;
17978 	recov_info *rcv = oldpkt->pkt_private;
17979 	uint_t cdblen;
17980 	int queued = 0;
17981 	int rval;
17982 	int flags = 0;
17983 	int stat_size =
17984 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
17985 
17986 	ST_FUNC(ST_DEVINFO, st_recover_reissue_pkt);
17987 
17988 	bp = rcv->cmd_bp;
17989 
17990 	if (rcv->privatelen == sizeof (recov_info)) {
17991 		attrib = rcv->cmd_attrib;
17992 	} else {
17993 		attrib = st_lookup_cmd_attribute(oldpkt->pkt_cdbp[0]);
17994 	}
17995 
17996 	/*
17997 	 * Some non-uscsi commands use the b_bcount for values that
17998 	 * have nothing to do with how much data is transfered.
17999 	 * In those cases we need to hide the buf_t from scsi_init_pkt().
18000 	 */
18001 	if ((BP_UCMD(bp)) && (bp->b_bcount)) {
18002 		pkt_bp = bp;
18003 	} else if (attrib->transfers_data == TRAN_NONE) {
18004 		pkt_bp = NULL;
18005 	} else {
18006 		pkt_bp = bp;
18007 	}
18008 
18009 	/*
18010 	 * if this is a queued command make sure it the only one in the
18011 	 * run queue.
18012 	 */
18013 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
18014 		ASSERT(un->un_runqf == un->un_runql);
18015 		ASSERT(un->un_runqf == bp);
18016 		queued = 1;
18017 	}
18018 
18019 	cdblen = scsi_cdb_size[CDB_GROUPID(oldpkt->pkt_cdbp[0])];
18020 
18021 	if (pkt_bp == un->un_rqs_bp) {
18022 		flags |= PKT_CONSISTENT;
18023 		stat_size = 1;
18024 	}
18025 
18026 	newpkt = scsi_init_pkt(ROUTE, NULL, pkt_bp, cdblen,
18027 	    stat_size, rcv->privatelen, flags, NULL_FUNC, NULL);
18028 	if (newpkt == NULL) {
18029 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
18030 		    "Reissue pkt scsi_init_pkt() failure\n");
18031 		return (COMMAND_DONE_ERROR);
18032 	}
18033 
18034 	ASSERT(newpkt->pkt_resid == 0);
18035 	bp->b_flags &= ~(B_DONE);
18036 	bp->b_resid = 0;
18037 	st_bioerror(bp, 0);
18038 
18039 	bcopy(oldpkt->pkt_private, newpkt->pkt_private, rcv->privatelen);
18040 
18041 	newpkt->pkt_comp = oldpkt->pkt_comp;
18042 	newpkt->pkt_time = oldpkt->pkt_time;
18043 
18044 	bzero(newpkt->pkt_scbp, stat_size);
18045 	bcopy(oldpkt->pkt_cdbp, newpkt->pkt_cdbp, cdblen);
18046 
18047 	newpkt->pkt_state = 0;
18048 	newpkt->pkt_statistics = 0;
18049 
18050 	/*
18051 	 * oldpkt passed in was a copy of the original.
18052 	 * to distroy we need the address of the original.
18053 	 */
18054 	oldpkt = BP_PKT(bp);
18055 
18056 	if (oldpkt == un->un_rqs) {
18057 		ASSERT(bp == un->un_rqs_bp);
18058 		un->un_rqs = newpkt;
18059 	}
18060 
18061 	SET_BP_PKT(bp, newpkt);
18062 
18063 	scsi_destroy_pkt(oldpkt);
18064 
18065 	rval = st_transport(un, newpkt);
18066 	if (rval == TRAN_ACCEPT) {
18067 		return (JUST_RETURN);
18068 	}
18069 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
18070 	    "Reissue pkt st_transport(0x%x) failure\n", rval);
18071 	if (rval != TRAN_BUSY) {
18072 		return (COMMAND_DONE_ERROR);
18073 	}
18074 	mutex_exit(ST_MUTEX);
18075 	rval = st_handle_start_busy(un, bp, ST_TRAN_BUSY_TIMEOUT, queued);
18076 	mutex_enter(ST_MUTEX);
18077 	if (rval) {
18078 		return (COMMAND_DONE_ERROR);
18079 	}
18080 
18081 	return (JUST_RETURN);
18082 }
18083 
18084 static int
18085 st_transport(struct scsi_tape *un, struct scsi_pkt *pkt)
18086 {
18087 	int status;
18088 
18089 	ST_FUNC(ST_DEVINFO, st_transport);
18090 
18091 	ST_CDB(ST_DEVINFO, "transport CDB", (caddr_t)pkt->pkt_cdbp);
18092 
18093 	mutex_exit(ST_MUTEX);
18094 
18095 	status = scsi_transport(pkt);
18096 
18097 	mutex_enter(ST_MUTEX);
18098 
18099 	return (status);
18100 }
18101 
18102 /*
18103  * Removed the buf_t bp from the queue referenced to by head and tail.
18104  * Returns the buf_t pointer if it is found in the queue.
18105  * Returns NULL if it is not found.
18106  */
18107 static buf_t *
18108 st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp)
18109 {
18110 	buf_t *runqbp;
18111 	buf_t *prevbp = NULL;
18112 
18113 	for (runqbp = *head; runqbp != 0; runqbp = runqbp->av_forw) {
18114 		if (runqbp == bp) {
18115 			/* found it, is it at the head? */
18116 			if (runqbp == *head) {
18117 				*head = bp->av_forw;
18118 			} else {
18119 				prevbp->av_forw = bp->av_forw;
18120 			}
18121 			if (*tail == bp) {
18122 				*tail = prevbp;
18123 			}
18124 			bp->av_forw = NULL;
18125 			return (bp); /* found and removed */
18126 		}
18127 		prevbp = runqbp;
18128 	}
18129 	return (NULL);
18130 }
18131 
18132 /*
18133  * Adds a buf_t to the queue pointed to by head and tail.
18134  * Adds it either to the head end or the tail end based on which
18135  * the passed variable end (head or tail) points at.
18136  */
18137 static void
18138 st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp)
18139 {
18140 
18141 	bp->av_forw = NULL;
18142 	if (*head) {
18143 		/* Queue is not empty */
18144 		if (end == *head) {
18145 			/* Add at front of queue */
18146 			bp->av_forw = *head;
18147 			*head = bp;
18148 		} else if (end == *tail) {
18149 			/* Add at end of queue */
18150 			(*tail)->av_forw = bp;
18151 			*tail = bp;
18152 		} else {
18153 			ASSERT(0);
18154 		}
18155 	} else {
18156 		/* Queue is empty */
18157 		*head = bp;
18158 		*tail = bp;
18159 	}
18160 }
18161 
18162 
18163 static uint64_t
18164 st_get_cdb_g0_rw_count(uchar_t *cdb)
18165 {
18166 	uint64_t count;
18167 
18168 	if ((cdb[1]) & 1) {
18169 		/* fixed block mode, the count is the number of blocks */
18170 		count =
18171 		    cdb[2] << 16 |
18172 		    cdb[3] << 8 |
18173 		    cdb[4];
18174 	} else {
18175 		/* variable block mode, the count is the block size */
18176 		count = 1;
18177 	}
18178 	return (count);
18179 }
18180 
18181 static uint64_t
18182 st_get_cdb_g0_sign_count(uchar_t *cdb)
18183 {
18184 	uint64_t count;
18185 
18186 	count =
18187 	    cdb[2] << 16 |
18188 	    cdb[3] << 8 |
18189 	    cdb[4];
18190 	/*
18191 	 * If the sign bit of the 3 byte value is set, extended it.
18192 	 */
18193 	if (count & 0x800000) {
18194 		count |= 0xffffffffff000000;
18195 	}
18196 	return (count);
18197 }
18198 
18199 static uint64_t
18200 st_get_cdb_g0_count(uchar_t *cdb)
18201 {
18202 	uint64_t count;
18203 
18204 	count =
18205 	    cdb[2] << 16 |
18206 	    cdb[3] << 8 |
18207 	    cdb[4];
18208 	return (count);
18209 }
18210 
18211 static uint64_t
18212 st_get_cdb_g5_rw_cnt(uchar_t *cdb)
18213 {
18214 	uint64_t count;
18215 
18216 	if ((cdb[1]) & 1) {
18217 		/* fixed block mode */
18218 		count =
18219 		    cdb[12] << 16 |
18220 		    cdb[13] << 8 |
18221 		    cdb[14];
18222 	} else {
18223 		/* variable block mode */
18224 		count = 1;
18225 	}
18226 	return (count);
18227 }
18228 
18229 static uint64_t
18230 st_get_no_count(uchar_t *cdb)
18231 {
18232 	ASSERT(cdb[0] == SCMD_REWIND);
18233 	return ((uint64_t)cdb[0]);
18234 }
18235 
18236 static uint64_t
18237 st_get_load_options(uchar_t *cdb)
18238 {
18239 	return ((uint64_t)(cdb[4] | (LD_HOLD << 1)));
18240 }
18241 
18242 static uint64_t
18243 st_get_erase_options(uchar_t *cdb)
18244 {
18245 	return (cdb[1] | (cdb[0] << 8));
18246 }
18247 
18248 static uint64_t
18249 st_get_cdb_g1_lba(uchar_t *cdb)
18250 {
18251 	uint64_t lba;
18252 
18253 	lba =
18254 	    cdb[3] << 24 |
18255 	    cdb[4] << 16 |
18256 	    cdb[5] << 8 |
18257 	    cdb[6];
18258 	return (lba);
18259 }
18260 
18261 static uint64_t
18262 st_get_cdb_g5_count(uchar_t *cdb)
18263 {
18264 	uint64_t count =
18265 	    cdb[12] << 16 |
18266 	    cdb[13] << 8 |
18267 	    cdb[14];
18268 
18269 	return (count);
18270 }
18271 
18272 static uint64_t
18273 st_get_cdb_g4g5_cnt(uchar_t *cdb)
18274 {
18275 	uint64_t lba;
18276 
18277 	lba =
18278 	    (uint64_t)cdb[4] << 56 |
18279 	    (uint64_t)cdb[5] << 48 |
18280 	    (uint64_t)cdb[6] << 40 |
18281 	    (uint64_t)cdb[7] << 32 |
18282 	    (uint64_t)cdb[8] << 24 |
18283 	    (uint64_t)cdb[9] << 16 |
18284 	    (uint64_t)cdb[10] << 8 |
18285 	    (uint64_t)cdb[11];
18286 	return (lba);
18287 }
18288 
18289 static const cmd_attribute cmd_attributes[] = {
18290 	{ SCMD_READ,
18291 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_READ, POS_EXPECTED,
18292 	    0, 0, 0, st_get_cdb_g0_rw_count },
18293 	{ SCMD_WRITE,
18294 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18295 	    0, 0, 0, st_get_cdb_g0_rw_count },
18296 	{ SCMD_TEST_UNIT_READY,
18297 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18298 	    0, 0, 0 },
18299 	{ SCMD_REWIND,
18300 	    1, 1, 1, 0, 0, DIR_REVC, TRAN_NONE, POS_EXPECTED,
18301 	    0, 0, 0, st_get_no_count },
18302 	{ SCMD_REQUEST_SENSE,
18303 	    0, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18304 	    0, 0, 0 },
18305 	{ SCMD_READ_BLKLIM,
18306 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18307 	    0, 0, 0 },
18308 	{ SCMD_READ_G4,
18309 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_READ, POS_EXPECTED,
18310 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18311 	{ SCMD_WRITE_G4,
18312 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18313 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18314 	{ SCMD_READ_REVERSE,
18315 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18316 	    0, 0, 0, st_get_cdb_g0_rw_count },
18317 	{ SCMD_READ_REVERSE_G4,
18318 	    1, 0, 1, 1, 1, DIR_REVC, TRAN_READ, POS_EXPECTED,
18319 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18320 	{ SCMD_WRITE_FILE_MARK,
18321 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18322 	    0, 0, 0, st_get_cdb_g0_count },
18323 	{ SCMD_WRITE_FILE_MARK_G4,
18324 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18325 	    0, 0, 0, st_get_cdb_g5_count, st_get_cdb_g4g5_cnt },
18326 	{ SCMD_SPACE,
18327 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18328 	    0, 0, 0, st_get_cdb_g0_sign_count },
18329 	{ SCMD_SPACE_G4,
18330 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18331 	    0, 0, 0, st_get_cdb_g4g5_cnt },
18332 	{ SCMD_INQUIRY,
18333 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18334 	    0, 0, 0 },
18335 	{ SCMD_VERIFY_G0,
18336 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18337 	    0, 0, 0, st_get_cdb_g0_rw_count },
18338 	{ SCMD_VERIFY_G4,
18339 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18340 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18341 	{ SCMD_RECOVER_BUF,
18342 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18343 	    0, 0, 0 },
18344 	{ SCMD_MODE_SELECT,
18345 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18346 	    0, 0, 0 },
18347 	{ SCMD_RESERVE,
18348 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18349 	    0, 0, 0 },
18350 	{ SCMD_RELEASE,
18351 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18352 	    0, 0, 0 },
18353 	{ SCMD_ERASE,
18354 	    1, 0, 1, 1, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18355 	    0, 0, 0, st_get_erase_options },
18356 	{ SCMD_MODE_SENSE,
18357 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18358 	    0, 0, 0 },
18359 	{ SCMD_LOAD,
18360 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18361 	    0, 0, 0, st_get_load_options },
18362 	{ SCMD_GDIAG,
18363 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18364 	    1, 0, 0 },
18365 	{ SCMD_SDIAG,
18366 	    1, 0, 1, 1, 0, DIR_EITH, TRAN_WRTE, POS_EXPECTED,
18367 	    1, 0, 0 },
18368 	{ SCMD_DOORLOCK,
18369 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18370 	    0, 4, 3 },
18371 	{ SCMD_LOCATE,
18372 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18373 	    0, 0, 0, NULL, st_get_cdb_g1_lba },
18374 	{ SCMD_READ_POSITION,
18375 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18376 	    0, 0, 0 },
18377 	{ SCMD_WRITE_BUFFER,
18378 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18379 	    1, 0, 0 },
18380 	{ SCMD_READ_BUFFER,
18381 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18382 	    1, 0, 0 },
18383 	{ SCMD_REPORT_DENSITIES,
18384 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18385 	    0, 0, 0 },
18386 	{ SCMD_LOG_SELECT_G1,
18387 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18388 	    0, 0, 0 },
18389 	{ SCMD_LOG_SENSE_G1,
18390 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18391 	    0, 0, 0 },
18392 	{ SCMD_PRIN,
18393 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18394 	    0, 0, 0 },
18395 	{ SCMD_PROUT,
18396 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18397 	    0, 0, 0 },
18398 	{ SCMD_READ_ATTRIBUTE,
18399 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18400 	    0, 0, 0 },
18401 	{ SCMD_WRITE_ATTRIBUTE,
18402 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18403 	    0, 0, 0 },
18404 	{ SCMD_LOCATE_G4,
18405 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18406 	    0, 0, 0, NULL, st_get_cdb_g4g5_cnt },
18407 	{ SCMD_REPORT_LUNS,
18408 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18409 	    0, 0, 0 },
18410 	{ SCMD_SVC_ACTION_IN_G5,
18411 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18412 	    0, 0, 0 },
18413 	{ SCMD_MAINTENANCE_IN,
18414 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18415 	    0, 0, 0 },
18416 	{ SCMD_MAINTENANCE_OUT,
18417 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18418 	    0, 0, 0 },
18419 	{ 0xff, /* Default attribute for unsupported commands */
18420 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_STARTING,
18421 	    1, 0, 0, NULL, NULL }
18422 };
18423 
18424 static const cmd_attribute *
18425 st_lookup_cmd_attribute(unsigned char cmd)
18426 {
18427 	int i;
18428 	cmd_attribute const *attribute;
18429 
18430 	for (i = 0; i < ST_NUM_MEMBERS(cmd_attributes); i++) {
18431 		attribute = &cmd_attributes[i];
18432 		if (attribute->cmd == cmd) {
18433 			return (attribute);
18434 		}
18435 	}
18436 	ASSERT(attribute);
18437 	return (attribute);
18438 }
18439 
18440 static int
18441 st_reset(struct scsi_tape *un, int reset_type)
18442 {
18443 	int rval;
18444 
18445 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
18446 
18447 	ST_FUNC(ST_DEVINFO, st_reset);
18448 	un->un_rsvd_status |= ST_INITIATED_RESET;
18449 	mutex_exit(ST_MUTEX);
18450 	do {
18451 		rval = scsi_reset(&un->un_sd->sd_address, reset_type);
18452 		if (rval == 0) {
18453 			switch (reset_type) {
18454 			case RESET_LUN:
18455 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18456 				    "LUN reset failed trying target reset");
18457 				reset_type = RESET_TARGET;
18458 				break;
18459 			case RESET_TARGET:
18460 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18461 				    "target reset failed trying bus reset");
18462 				reset_type = RESET_BUS;
18463 				break;
18464 			case RESET_BUS:
18465 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18466 				    "bus reset failed trying all reset");
18467 				reset_type = RESET_ALL;
18468 			default:
18469 				mutex_enter(ST_MUTEX);
18470 				return (rval);
18471 			}
18472 		}
18473 	} while (rval == 0);
18474 	mutex_enter(ST_MUTEX);
18475 	return (rval);
18476 }
18477 
18478 #define	SAS_TLR_MOD_LEN sizeof (struct seq_mode)
18479 static int
18480 st_set_target_TLR_mode(struct scsi_tape *un, ubufunc_t ubf)
18481 {
18482 	int ret;
18483 	int amount = SAS_TLR_MOD_LEN;
18484 	struct seq_mode *mode_data;
18485 
18486 	ST_FUNC(ST_DEVINFO, st_set_target_TLR_mode);
18487 
18488 	mode_data = kmem_zalloc(SAS_TLR_MOD_LEN, KM_SLEEP);
18489 	ret = st_gen_mode_sense(un, ubf, 0x18, mode_data, amount);
18490 	if (ret != DDI_SUCCESS) {
18491 		if (ret != EACCES)
18492 			un->un_tlr_flag = TLR_NOT_SUPPORTED;
18493 		goto out;
18494 	}
18495 	if (mode_data->data_len != amount + 1) {
18496 		amount = mode_data->data_len + 1;
18497 	}
18498 	/* Must be SAS protocol */
18499 	if (mode_data->page.saslun.protocol_id != 6) {
18500 		un->un_tlr_flag = TLR_NOT_SUPPORTED;
18501 		ret = ENOTSUP;
18502 		goto out;
18503 	}
18504 	if (un->un_tlr_flag == TLR_SAS_ONE_DEVICE) {
18505 		if (mode_data->page.saslun.tran_layer_ret == 1)
18506 			goto out;
18507 		mode_data->page.saslun.tran_layer_ret = 1;
18508 	} else {
18509 		if (mode_data->page.saslun.tran_layer_ret == 0)
18510 			goto out;
18511 		mode_data->page.saslun.tran_layer_ret = 0;
18512 	}
18513 	ret = st_gen_mode_select(un, ubf, mode_data, amount);
18514 	if (ret != DDI_SUCCESS) {
18515 		if (ret != EACCES)
18516 			un->un_tlr_flag = TLR_NOT_SUPPORTED;
18517 	} else {
18518 		if (mode_data->page.saslun.tran_layer_ret == 0)
18519 			un->un_tlr_flag = TLR_NOT_KNOWN;
18520 		else
18521 			un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
18522 	}
18523 #ifdef STDEBUG
18524 	st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG, "TLR data sent",
18525 	    (char *)mode_data, amount);
18526 #endif
18527 out:
18528 	kmem_free(mode_data, SAS_TLR_MOD_LEN);
18529 	return (ret);
18530 }
18531 
18532 
18533 static void
18534 st_reset_notification(caddr_t arg)
18535 {
18536 	struct scsi_tape *un = (struct scsi_tape *)arg;
18537 
18538 	ST_FUNC(ST_DEVINFO, st_reset_notification);
18539 	mutex_enter(ST_MUTEX);
18540 
18541 	un->un_unit_attention_flags |= 2;
18542 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
18543 	    ST_RESERVE) {
18544 		un->un_rsvd_status |= ST_LOST_RESERVE;
18545 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18546 		    "Lost Reservation notification");
18547 	} else {
18548 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18549 		    "reset notification");
18550 	}
18551 
18552 	if ((un->un_restore_pos == 0) &&
18553 	    (un->un_state == ST_STATE_CLOSED) ||
18554 	    (un->un_state == ST_STATE_OPEN_PENDING_IO) ||
18555 	    (un->un_state == ST_STATE_CLOSING)) {
18556 		un->un_restore_pos = 1;
18557 	}
18558 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
18559 	    "reset and state was %d\n", un->un_state);
18560 	mutex_exit(ST_MUTEX);
18561 }
18562