xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/st.c (revision b1593d50e783f7d66722dde093752b74ffa95176)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * SCSI	 SCSA-compliant and not-so-DDI-compliant Tape Driver
29  */
30 
31 #if defined(lint) && !defined(DEBUG)
32 #define	DEBUG	1
33 #endif
34 
35 #include <sys/modctl.h>
36 #include <sys/scsi/scsi.h>
37 #include <sys/mtio.h>
38 #include <sys/scsi/targets/stdef.h>
39 #include <sys/file.h>
40 #include <sys/kstat.h>
41 #include <sys/ddidmareq.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/byteorder.h>
45 
46 #define	IOSP	KSTAT_IO_PTR(un->un_stats)
47 /*
48  * stats maintained only for reads/writes as commands
49  * like rewind etc skew the wait/busy times
50  */
51 #define	IS_RW(bp) 	((bp)->b_bcount > 0)
52 #define	ST_DO_KSTATS(bp, kstat_function) \
53 	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
54 		kstat_function(IOSP); \
55 	}
56 
57 #define	ST_DO_ERRSTATS(un, x)  \
58 	if (un->un_errstats) { \
59 		struct st_errstats *stp; \
60 		stp = (struct st_errstats *)un->un_errstats->ks_data; \
61 		stp->x.value.ul++; \
62 	}
63 
64 #define	FILL_SCSI1_LUN(devp, pkt) 					\
65 	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
66 		int _lun;						\
67 		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
68 		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
69 		if (_lun > 0) {						\
70 			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
71 			    _lun;					\
72 		}							\
73 	}
74 
75 /*
76  * get an available contig mem header, cp.
77  * when big_enough is true, we will return NULL, if no big enough
78  * contig mem is found.
79  * when big_enough is false, we will try to find cp containing big
80  * enough contig mem. if not found, we will ruturn the last cp available.
81  *
82  * used by st_get_contig_mem()
83  */
84 #define	ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough) {		\
85 	struct contig_mem *tmp_cp = NULL;				\
86 	for ((cp) = (un)->un_contig_mem;				\
87 	    (cp) != NULL;						\
88 	    tmp_cp = (cp), (cp) = (cp)->cm_next) { 			\
89 		if (((cp)->cm_len >= (len)) || 				\
90 		    (!(big_enough) && ((cp)->cm_next == NULL))) { 	\
91 			if (tmp_cp == NULL) { 				\
92 				(un)->un_contig_mem = (cp)->cm_next; 	\
93 			} else { 					\
94 				tmp_cp->cm_next = (cp)->cm_next; 	\
95 			} 						\
96 			(cp)->cm_next = NULL; 				\
97 			(un)->un_contig_mem_available_num--; 		\
98 			break; 						\
99 		} 							\
100 	} 								\
101 }
102 
103 #define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
104 #define	COPY_POS(dest, source) bcopy(source, dest, sizeof (tapepos_t))
105 #define	ISALNUM(byte) \
106 	(((byte) >= 'a' && (byte) <= 'z') || \
107 	((byte) >= 'A' && (byte) <= 'Z') || \
108 	((byte) >= '0' && (byte) <= '9'))
109 
110 #define	ONE_K	1024
111 
112 #define	MAX_SPACE_CNT(cnt) if (cnt >= 0) { \
113 		if (cnt > MIN(SP_CNT_MASK, INT32_MAX)) \
114 			return (EINVAL); \
115 	} else { \
116 		if (-(cnt) > MIN(SP_CNT_MASK, INT32_MAX)) \
117 			return (EINVAL); \
118 	} \
119 
120 /*
121  * Global External Data Definitions
122  */
123 extern struct scsi_key_strings scsi_cmds[];
124 extern uchar_t	scsi_cdb_size[];
125 
126 /*
127  * Local Static Data
128  */
129 static void *st_state;
130 static char *const st_label = "st";
131 static volatile int st_recov_sz = sizeof (recov_info);
132 static const char mp_misconf[] = {
133 	"St Tape is misconfigured, MPxIO enabled and "
134 	"tape-command-recovery-disable set in st.conf\n"
135 };
136 
137 #ifdef	__x86
138 /*
139  * We need to use below DMA attr to alloc physically contiguous
140  * memory to do I/O in big block size
141  */
142 static ddi_dma_attr_t st_contig_mem_dma_attr = {
143 	DMA_ATTR_V0,    /* version number */
144 	0x0,		/* lowest usable address */
145 	0xFFFFFFFFull,  /* high DMA address range */
146 	0xFFFFFFFFull,  /* DMA counter register */
147 	1,		/* DMA address alignment */
148 	1,		/* DMA burstsizes */
149 	1,		/* min effective DMA size */
150 	0xFFFFFFFFull,  /* max DMA xfer size */
151 	0xFFFFFFFFull,  /* segment boundary */
152 	1,		/* s/g list length */
153 	1,		/* granularity of device */
154 	0		/* DMA transfer flags */
155 };
156 
157 static ddi_device_acc_attr_t st_acc_attr = {
158 	DDI_DEVICE_ATTR_V0,
159 	DDI_NEVERSWAP_ACC,
160 	DDI_STRICTORDER_ACC
161 };
162 
163 /* set limitation for the number of contig_mem */
164 static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
165 #endif
166 
167 /*
168  * Tunable parameters
169  *
170  * DISCLAIMER
171  * ----------
172  * These parameters are intended for use only in system testing; if you use
173  * them in production systems, you do so at your own risk. Altering any
174  * variable not listed below may cause unpredictable system behavior.
175  *
176  * st_check_media_time
177  *
178  *   Three second state check
179  *
180  * st_allow_large_xfer
181  *
182  *   Gated with ST_NO_RECSIZE_LIMIT
183  *
184  *   0 - Transfers larger than 64KB will not be allowed
185  *       regardless of the setting of ST_NO_RECSIZE_LIMIT
186  *   1 - Transfers larger than 64KB will be allowed
187  *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
188  *
189  * st_report_soft_errors_on_close
190  *
191  *  Gated with ST_SOFT_ERROR_REPORTING
192  *
193  *  0 - Errors will not be reported on close regardless
194  *      of the setting of ST_SOFT_ERROR_REPORTING
195  *
196  *  1 - Errors will be reported on close if
197  *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
198  */
199 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
200 static int st_retry_count	= ST_RETRY_COUNT;
201 
202 static int st_io_time		= ST_IO_TIME;
203 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
204 
205 static int st_space_time	= ST_SPACE_TIME;
206 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
207 
208 static int st_error_level	= SCSI_ERR_RETRYABLE;
209 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
210 
211 static int st_max_throttle	= ST_MAX_THROTTLE;
212 
213 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
214 
215 static int st_allow_large_xfer = 1;
216 static int st_report_soft_errors_on_close = 1;
217 
218 /*
219  * End of tunable parameters list
220  */
221 
222 
223 
224 /*
225  * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
226  *
227  * Asynchronous I/O's main offering is that it is a non-blocking way to do
228  * reads and writes.  The driver will queue up all the requests it gets and
229  * have them ready to transport to the HBA.  Unfortunately, we cannot always
230  * just ship the I/O requests to the HBA, as there errors and exceptions
231  * that may happen when we don't want the HBA to continue.  Therein comes
232  * the flush-on-errors capability.  If the HBA supports it, then st will
233  * send in st_max_throttle I/O requests at the same time.
234  *
235  * Persistent errors : This was also reasonably simple.  In the interrupt
236  * routines, if there was an error or exception (FM, LEOT, media error,
237  * transport error), the persistent error bits are set and shuts everything
238  * down, but setting the throttle to zero.  If we hit and exception in the
239  * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
240  * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
241  * the appropriate error, and this will preserve order. Of course, depending
242  * on the exception we have to show a zero read or write before we show
243  * errors back to the application.
244  */
245 
246 extern const int st_ndrivetypes;	/* defined in st_conf.c */
247 extern const struct st_drivetype st_drivetypes[];
248 extern const char st_conf_version[];
249 
250 #ifdef STDEBUG
251 static int st_soft_error_report_debug = 0;
252 volatile int st_debug = 0;
253 static volatile dev_info_t *st_lastdev;
254 static kmutex_t st_debug_mutex;
255 #endif
256 
257 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
258 
259 static const struct vid_drivetype {
260 	char	*vid;
261 	char	type;
262 } st_vid_dt[] = {
263 	{"LTO-CVE ",	MT_LTO},
264 	{"QUANTUM ",    MT_ISDLT},
265 	{"SONY    ",    MT_ISAIT},
266 	{"STK     ",	MT_ISSTK9840}
267 };
268 
269 static const struct driver_minor_data {
270 	char	*name;
271 	int	minor;
272 } st_minor_data[] = {
273 	/*
274 	 * The top 4 entries are for the default densities,
275 	 * don't alter their position.
276 	 */
277 	{"",	0},
278 	{"n",	MT_NOREWIND},
279 	{"b",	MT_BSD},
280 	{"bn",	MT_NOREWIND | MT_BSD},
281 	{"l",	MT_DENSITY1},
282 	{"m",	MT_DENSITY2},
283 	{"h",	MT_DENSITY3},
284 	{"c",	MT_DENSITY4},
285 	{"u",	MT_DENSITY4},
286 	{"ln",	MT_DENSITY1 | MT_NOREWIND},
287 	{"mn",	MT_DENSITY2 | MT_NOREWIND},
288 	{"hn",	MT_DENSITY3 | MT_NOREWIND},
289 	{"cn",	MT_DENSITY4 | MT_NOREWIND},
290 	{"un",	MT_DENSITY4 | MT_NOREWIND},
291 	{"lb",	MT_DENSITY1 | MT_BSD},
292 	{"mb",	MT_DENSITY2 | MT_BSD},
293 	{"hb",	MT_DENSITY3 | MT_BSD},
294 	{"cb",	MT_DENSITY4 | MT_BSD},
295 	{"ub",	MT_DENSITY4 | MT_BSD},
296 	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
297 	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
298 	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
299 	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
300 	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
301 };
302 
303 /* strings used in many debug and warning messages */
304 static const char wr_str[]  = "write";
305 static const char rd_str[]  = "read";
306 static const char wrg_str[] = "writing";
307 static const char rdg_str[] = "reading";
308 static const char *space_strs[] = {
309 	"records",
310 	"filemarks",
311 	"sequential filemarks",
312 	"eod",
313 	"setmarks",
314 	"sequential setmarks",
315 	"Reserved",
316 	"Reserved"
317 };
318 static const char *load_strs[] = {
319 	"unload",		/* LD_UNLOAD		0 */
320 	"load",			/* LD_LOAD		1 */
321 	"retension",		/* LD_RETEN		2 */
322 	"load reten",		/* LD_LOAD | LD_RETEN	3 */
323 	"eod",			/* LD_EOT		4 */
324 	"load EOD",		/* LD_LOAD | LD_EOT	5 */
325 	"reten EOD",		/* LD_RETEN | LD_EOT	6 */
326 	"load reten EOD"	/* LD_LOAD|LD_RETEN|LD_EOT 7 */
327 	"hold",			/* LD_HOLD		8 */
328 	"load and hold"		/* LD_LOAD | LD_HOLD	9 */
329 };
330 
331 static const char *errstatenames[] = {
332 	"COMMAND_DONE",
333 	"COMMAND_DONE_ERROR",
334 	"COMMAND_DONE_ERROR_RECOVERED",
335 	"QUE_COMMAND",
336 	"QUE_BUSY_COMMAND",
337 	"QUE_SENSE",
338 	"JUST_RETURN",
339 	"COMMAND_DONE_EACCES",
340 	"QUE_LAST_COMMAND",
341 	"COMMAND_TIMEOUT",
342 	"PATH_FAILED",
343 	"DEVICE_RESET",
344 	"DEVICE_TAMPER",
345 	"ATTEMPT_RETRY"
346 };
347 
348 const char *bogusID = "Unknown Media ID";
349 
350 /* default density offsets in the table above */
351 #define	DEF_BLANK	0
352 #define	DEF_NOREWIND	1
353 #define	DEF_BSD		2
354 #define	DEF_BSD_NR	3
355 
356 /* Sense Key, ASC/ASCQ for which tape ejection is needed */
357 
358 static struct tape_failure_code {
359 	uchar_t key;
360 	uchar_t add_code;
361 	uchar_t qual_code;
362 } st_tape_failure_code[] = {
363 	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
364 	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
365 	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
366 	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
367 	{ KEY_NOT_READY, 0x53, 0x00},
368 	{ 0xff}
369 };
370 
371 /*  clean bit position and mask */
372 
373 static struct cln_bit_position {
374 	ushort_t cln_bit_byte;
375 	uchar_t cln_bit_mask;
376 } st_cln_bit_position[] = {
377 	{ 21, 0x08},
378 	{ 70, 0xc0},
379 	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
380 };
381 
382 /*
383  * architecture dependent allocation restrictions. For x86, we'll set
384  * dma_attr_addr_hi to st_max_phys_addr and dma_attr_sgllen to
385  * st_sgl_size during _init().
386  */
387 #if defined(__sparc)
388 static ddi_dma_attr_t st_alloc_attr = {
389 	DMA_ATTR_V0,	/* version number */
390 	0x0,		/* lowest usable address */
391 	0xFFFFFFFFull,	/* high DMA address range */
392 	0xFFFFFFFFull,	/* DMA counter register */
393 	1,		/* DMA address alignment */
394 	1,		/* DMA burstsizes */
395 	1,		/* min effective DMA size */
396 	0xFFFFFFFFull,	/* max DMA xfer size */
397 	0xFFFFFFFFull,	/* segment boundary */
398 	1,		/* s/g list length */
399 	512,		/* granularity of device */
400 	0		/* DMA transfer flags */
401 };
402 #elif defined(__x86)
403 static ddi_dma_attr_t st_alloc_attr = {
404 	DMA_ATTR_V0,	/* version number */
405 	0x0,		/* lowest usable address */
406 	0x0,		/* high DMA address range [set in _init()] */
407 	0xFFFFull,	/* DMA counter register */
408 	512,		/* DMA address alignment */
409 	1,		/* DMA burstsizes */
410 	1,		/* min effective DMA size */
411 	0xFFFFFFFFull,	/* max DMA xfer size */
412 	0xFFFFFFFFull,  /* segment boundary */
413 	0,		/* s/g list length */
414 	512,		/* granularity of device [set in _init()] */
415 	0		/* DMA transfer flags */
416 };
417 uint64_t st_max_phys_addr = 0xFFFFFFFFull;
418 int st_sgl_size = 0xF;
419 
420 #endif
421 
422 /*
423  * Configuration Data:
424  *
425  * Device driver ops vector
426  */
427 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
428 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
429 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
430 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
431 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
432 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
433 static int st_strategy(struct buf *bp);
434 static int st_queued_strategy(buf_t *bp);
435 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
436 	cred_t *cred_p, int *rval_p);
437 extern int nulldev(), nodev();
438 
439 static struct cb_ops st_cb_ops = {
440 	st_open,		/* open */
441 	st_close,		/* close */
442 	st_queued_strategy,	/* strategy Not Block device but async checks */
443 	nodev,			/* print */
444 	nodev,			/* dump */
445 	st_read,		/* read */
446 	st_write,		/* write */
447 	st_ioctl,		/* ioctl */
448 	nodev,			/* devmap */
449 	nodev,			/* mmap */
450 	nodev,			/* segmap */
451 	nochpoll,		/* poll */
452 	ddi_prop_op,		/* cb_prop_op */
453 	0,			/* streamtab  */
454 	D_64BIT | D_MP | D_NEW | D_HOTPLUG |
455 	D_OPEN_RETURNS_EINTR,	/* cb_flag */
456 	CB_REV,			/* cb_rev */
457 	st_aread, 		/* async I/O read entry point */
458 	st_awrite		/* async I/O write entry point */
459 
460 };
461 
462 static int st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
463 		void **result);
464 static int st_probe(dev_info_t *dev);
465 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
466 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
467 
468 static struct dev_ops st_ops = {
469 	DEVO_REV,		/* devo_rev, */
470 	0,			/* refcnt  */
471 	st_info,		/* info */
472 	nulldev,		/* identify */
473 	st_probe,		/* probe */
474 	st_attach,		/* attach */
475 	st_detach,		/* detach */
476 	nodev,			/* reset */
477 	&st_cb_ops,		/* driver operations */
478 	(struct bus_ops *)0,	/* bus operations */
479 	nulldev,		/* power */
480 	ddi_quiesce_not_needed,	/* devo_quiesce */
481 };
482 
483 /*
484  * Local Function Declarations
485  */
486 static char *st_print_scsi_cmd(char cmd);
487 static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
488     char *title, char *cdb);
489 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
490     char *title, char *data, int len);
491 static int st_doattach(struct scsi_device *devp, int (*canwait)());
492 static void st_known_tape_type(struct scsi_tape *un);
493 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
494     struct st_drivetype *);
495 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
496     struct st_drivetype *);
497 static int st_get_conf_from_tape_drive(struct scsi_tape *, char *,
498     struct st_drivetype *);
499 static int st_get_densities_from_tape_drive(struct scsi_tape *,
500     struct st_drivetype *);
501 static int st_get_timeout_values_from_tape_drive(struct scsi_tape *,
502     struct st_drivetype *);
503 static int st_get_timeouts_value(struct scsi_tape *, uchar_t, ushort_t *,
504     ushort_t);
505 static int st_get_default_conf(struct scsi_tape *, char *,
506     struct st_drivetype *);
507 static int st_rw(dev_t dev, struct uio *uio, int flag);
508 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
509 static int st_find_eod(struct scsi_tape *un);
510 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
511 static int st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *, int flag);
512 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
513 static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
514 static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
515 static void st_start(struct scsi_tape *un);
516 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
517     clock_t timeout_interval, int queued);
518 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
519     clock_t timeout_interval);
520 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
521 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
522 static void st_init(struct scsi_tape *un);
523 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
524     int (*func)(caddr_t));
525 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
526     struct buf *bp, int (*func)(caddr_t));
527 static void st_intr(struct scsi_pkt *pkt);
528 static void st_set_state(struct scsi_tape *un, buf_t *bp);
529 static void st_test_append(struct buf *bp);
530 static int st_runout(caddr_t);
531 static int st_cmd(struct scsi_tape *un, int com, int64_t count, int wait);
532 static int st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com,
533     int64_t count);
534 static int st_set_compression(struct scsi_tape *un);
535 static int st_write_fm(dev_t dev, int wfm);
536 static int st_determine_generic(struct scsi_tape *un);
537 static int st_determine_density(struct scsi_tape *un, int rw);
538 static int st_get_density(struct scsi_tape *un);
539 static int st_set_density(struct scsi_tape *un);
540 static int st_loadtape(struct scsi_tape *un);
541 static int st_modesense(struct scsi_tape *un);
542 static int st_modeselect(struct scsi_tape *un);
543 static errstate st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
544 static int st_wrongtapetype(struct scsi_tape *un);
545 static errstate st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
546 static errstate st_handle_sense(struct scsi_tape *un, struct buf *bp,
547     tapepos_t *);
548 static errstate st_handle_autosense(struct scsi_tape *un, struct buf *bp,
549     tapepos_t *);
550 static int st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag);
551 static void st_update_error_stack(struct scsi_tape *un, struct scsi_pkt *pkt,
552     struct scsi_arq_status *cmd);
553 static void st_empty_error_stack(struct scsi_tape *un);
554 static errstate st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
555     struct scsi_arq_status *, tapepos_t *);
556 static int st_report_soft_errors(dev_t dev, int flag);
557 static void st_delayed_cv_broadcast(void *arg);
558 static int st_check_media(dev_t dev, enum mtio_state state);
559 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
560 static void st_intr_restart(void *arg);
561 static void st_start_restart(void *arg);
562 static int st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
563     struct seq_mode *page_data, int page_size);
564 static int st_change_block_size(struct scsi_tape *un, uint32_t nblksz);
565 static int st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
566     struct seq_mode *page_data, int page_size);
567 static int st_read_block_limits(struct scsi_tape *un,
568     struct read_blklim *read_blk);
569 static int st_report_density_support(struct scsi_tape *un,
570     uchar_t *density_data, size_t buflen);
571 static int st_report_supported_operation(struct scsi_tape *un,
572     uchar_t *oper_data, uchar_t option_code, ushort_t service_action);
573 static int st_tape_init(struct scsi_tape *un);
574 static void st_flush(struct scsi_tape *un);
575 static void st_set_pe_errno(struct scsi_tape *un);
576 static void st_hba_unflush(struct scsi_tape *un);
577 static void st_turn_pe_on(struct scsi_tape *un);
578 static void st_turn_pe_off(struct scsi_tape *un);
579 static void st_set_pe_flag(struct scsi_tape *un);
580 static void st_clear_pe(struct scsi_tape *un);
581 static void st_wait_for_io(struct scsi_tape *un);
582 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
583 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
584 static int st_reserve_release(struct scsi_tape *un, int command, ubufunc_t ubf);
585 static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb);
586 static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
587     int count);
588 static int st_take_ownership(struct scsi_tape *un, ubufunc_t ubf);
589 static int st_check_asc_ascq(struct scsi_tape *un);
590 static int st_check_clean_bit(struct scsi_tape *un);
591 static int st_check_alert_flags(struct scsi_tape *un);
592 static int st_check_sequential_clean_bit(struct scsi_tape *un);
593 static int st_check_sense_clean_bit(struct scsi_tape *un);
594 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
595 static void st_calculate_timeouts(struct scsi_tape *un);
596 static writablity st_is_drive_worm(struct scsi_tape *un);
597 static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
598     void *buf, size_t size, ubufunc_t bufunc);
599 static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
600     caddr_t dest, uchar_t page);
601 static int st_update_block_pos(struct scsi_tape *un, bufunc_t bf,
602     int post_space);
603 static int st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
604     read_p_types type, size_t data_sz, const caddr_t responce, int post_space);
605 static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
606 static int st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf,
607     tapepos_t *pos, uint64_t lblk, uchar_t partition);
608 static int st_mtfsf_ioctl(struct scsi_tape *un, int64_t files);
609 static int st_mtfsr_ioctl(struct scsi_tape *un, int64_t count);
610 static int st_mtbsf_ioctl(struct scsi_tape *un, int64_t files);
611 static int st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count);
612 static int st_mtbsr_ioctl(struct scsi_tape *un, int64_t num);
613 static int st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt);
614 static int st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt);
615 static int st_backward_space_files(struct scsi_tape *un, int64_t count,
616     int infront);
617 static int st_forward_space_files(struct scsi_tape *un, int64_t files);
618 static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
619     int32_t fileno);
620 static int st_space_to_begining_of_file(struct scsi_tape *un);
621 static int st_space_records(struct scsi_tape *un, int64_t records);
622 static int st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc);
623 static errstate st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
624     errstate onentry);
625 static void st_recover(void *arg);
626 static void st_recov_cb(struct scsi_pkt *pkt);
627 static int st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait);
628 static int st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
629     int flag);
630 static void st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
631     struct scsi_pkt *cmd);
632 static int st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf);
633 static int st_test_path_to_device(struct scsi_tape *un);
634 static int st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
635     read_pos_data_t *raw);
636 static int st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
637     read_pos_data_t *raw);
638 static int st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
639     cmd_attribute const * cmd_att, tapepos_t *read);
640 static errstate st_recover_reissue_pkt(struct scsi_tape *us,
641     struct scsi_pkt *pkt);
642 static int st_transport(struct scsi_tape *un, struct scsi_pkt *pkt);
643 static buf_t *st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp);
644 static void st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp);
645 static int st_reset(struct scsi_tape *un, int reset_type);
646 static void st_reset_notification(caddr_t arg);
647 static const cmd_attribute *st_lookup_cmd_attribute(unsigned char cmd);
648 
649 #ifdef	__x86
650 /*
651  * routines for I/O in big block size
652  */
653 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
654 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
655     int alloc_flags);
656 static int st_bigblk_xfer_done(struct buf *bp);
657 static struct buf *st_get_bigblk_bp(struct buf *bp);
658 #endif
659 static void st_print_position(dev_info_t *dev, char *label, uint_t level,
660     const char *comment, tapepos_t *pos);
661 
662 /*
663  * error statistics create/update functions
664  */
665 static int st_create_errstats(struct scsi_tape *, int);
666 static int st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf,
667     tapepos_t *pos);
668 
669 #ifdef STDEBUG
670 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
671 #endif /* STDEBUG */
672 static char *st_dev_name(dev_t dev);
673 
674 #if !defined(lint)
675 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
676     scsi_pkt buf uio scsi_cdb uscsi_cmd))
677 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
678 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", recov_info))
679 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
680 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
681 #endif
682 
683 /*
684  * autoconfiguration routines.
685  */
686 char _depends_on[] = "misc/scsi";
687 
688 static struct modldrv modldrv = {
689 	&mod_driverops,		/* Type of module. This one is a driver */
690 	"SCSI tape Driver", 	/* Name of the module. */
691 	&st_ops			/* driver ops */
692 };
693 
694 static struct modlinkage modlinkage = {
695 	MODREV_1, &modldrv, NULL
696 };
697 
698 /*
699  * Notes on Post Reset Behavior in the tape driver:
700  *
701  * When the tape drive is opened, the driver  attempts  to make sure that
702  * the tape head is positioned exactly where it was left when it was last
703  * closed  provided  the  medium  is not  changed.  If the tape  drive is
704  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
705  * of position due to reset) will happen when the first tape operation or
706  * I/O occurs.  The repositioning (if required) may not be possible under
707  * certain situations such as when the device firmware not able to report
708  * the medium  change in the REQUEST  SENSE data  because of a reset or a
709  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
710  * extraordinary  situations, where the driver fails to position the head
711  * at its  original  position,  it will fail the open the first  time, to
712  * save the applications from overwriting the data.  All further attempts
713  * to open the tape device will result in the driver  attempting  to load
714  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
715  * indicate  that further  attempts to open the tape device may result in
716  * the tape being  loaded at BOT will be printed on the  console.  If the
717  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
718  * original tape head  position,  will result in the failure of the first
719  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
720  * internal tape position  which will  necessitate  the  applications  to
721  * validate the position by using either a tape  positioning  ioctl (such
722  * as MTREW) or closing and reopening the tape device.
723  *
724  */
725 
726 int
727 _init(void)
728 {
729 	int e;
730 
731 	if (((e = ddi_soft_state_init(&st_state,
732 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
733 		return (e);
734 	}
735 
736 	if ((e = mod_install(&modlinkage)) != 0) {
737 		ddi_soft_state_fini(&st_state);
738 	} else {
739 #ifdef STDEBUG
740 		mutex_init(&st_debug_mutex, NULL, MUTEX_DRIVER, NULL);
741 #endif
742 
743 #if defined(__x86)
744 		/* set the max physical address for iob allocs on x86 */
745 		st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
746 
747 		/*
748 		 * set the sgllen for iob allocs on x86. If this is set less
749 		 * than the number of pages the buffer will take
750 		 * (taking into account alignment), it would force the
751 		 * allocator to try and allocate contiguous pages.
752 		 */
753 		st_alloc_attr.dma_attr_sgllen = st_sgl_size;
754 #endif
755 	}
756 
757 	return (e);
758 }
759 
760 int
761 _fini(void)
762 {
763 	int e;
764 
765 	if ((e = mod_remove(&modlinkage)) != 0) {
766 		return (e);
767 	}
768 
769 #ifdef STDEBUG
770 	mutex_destroy(&st_debug_mutex);
771 #endif
772 
773 	ddi_soft_state_fini(&st_state);
774 
775 	return (e);
776 }
777 
778 int
779 _info(struct modinfo *modinfop)
780 {
781 	return (mod_info(&modlinkage, modinfop));
782 }
783 
784 
785 static int
786 st_probe(dev_info_t *devi)
787 {
788 	int instance;
789 	struct scsi_device *devp;
790 	int rval;
791 
792 #if !defined(__sparc)
793 	char    *tape_prop;
794 	int	tape_prop_len;
795 #endif
796 
797 	ST_ENTR(devi, st_probe);
798 
799 	/* If self identifying device */
800 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
801 		return (DDI_PROBE_DONTCARE);
802 	}
803 
804 #if !defined(__sparc)
805 	/*
806 	 * Since some x86 HBAs have devnodes that look like SCSI as
807 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
808 	 * we check for the presence of the "tape" property.
809 	 */
810 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
811 	    DDI_PROP_CANSLEEP, "tape",
812 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
813 		return (DDI_PROBE_FAILURE);
814 	}
815 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
816 		kmem_free(tape_prop, tape_prop_len);
817 		return (DDI_PROBE_FAILURE);
818 	}
819 	kmem_free(tape_prop, tape_prop_len);
820 #endif
821 
822 	devp = ddi_get_driver_private(devi);
823 	instance = ddi_get_instance(devi);
824 
825 	if (ddi_get_soft_state(st_state, instance) != NULL) {
826 		return (DDI_PROBE_PARTIAL);
827 	}
828 
829 
830 	/*
831 	 * Turn around and call probe routine to see whether
832 	 * we actually have a tape at this SCSI nexus.
833 	 */
834 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
835 
836 		/*
837 		 * In checking the whole inq_dtype byte we are looking at both
838 		 * the Peripheral Qualifier and the Peripheral Device Type.
839 		 * For this driver we are only interested in sequential devices
840 		 * that are connected or capable if connecting to this logical
841 		 * unit.
842 		 */
843 		if (devp->sd_inq->inq_dtype ==
844 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
845 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
846 			    "probe exists\n");
847 			rval = DDI_PROBE_SUCCESS;
848 		} else {
849 			rval = DDI_PROBE_FAILURE;
850 		}
851 	} else {
852 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
853 		    "probe failure: nothing there\n");
854 		rval = DDI_PROBE_FAILURE;
855 	}
856 	scsi_unprobe(devp);
857 	return (rval);
858 }
859 
860 static int
861 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
862 {
863 	int 	instance;
864 	int	wide;
865 	int 	dev_instance;
866 	int	ret_status;
867 	struct	scsi_device *devp;
868 	int	node_ix;
869 	struct	scsi_tape *un;
870 
871 	ST_ENTR(devi, st_attach);
872 
873 	devp = ddi_get_driver_private(devi);
874 	instance = ddi_get_instance(devi);
875 
876 	switch (cmd) {
877 		case DDI_ATTACH:
878 			if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
879 			    "tape-command-recovery-disable", 0) != 0) {
880 				st_recov_sz = sizeof (pkt_info);
881 			}
882 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
883 				return (DDI_FAILURE);
884 			}
885 			break;
886 		case DDI_RESUME:
887 			/*
888 			 * Suspend/Resume
889 			 *
890 			 * When the driver suspended, there might be
891 			 * outstanding cmds and therefore we need to
892 			 * reset the suspended flag and resume the scsi
893 			 * watch thread and restart commands and timeouts
894 			 */
895 
896 			if (!(un = ddi_get_soft_state(st_state, instance))) {
897 				return (DDI_FAILURE);
898 			}
899 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
900 			    un->un_dev);
901 
902 			mutex_enter(ST_MUTEX);
903 
904 			un->un_throttle = un->un_max_throttle;
905 			un->un_tids_at_suspend = 0;
906 			un->un_pwr_mgmt = ST_PWR_NORMAL;
907 
908 			if (un->un_swr_token) {
909 				scsi_watch_resume(un->un_swr_token);
910 			}
911 
912 			/*
913 			 * Restart timeouts
914 			 */
915 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
916 				mutex_exit(ST_MUTEX);
917 				un->un_delay_tid = timeout(
918 				    st_delayed_cv_broadcast, un,
919 				    drv_usectohz((clock_t)
920 				    MEDIA_ACCESS_DELAY));
921 				mutex_enter(ST_MUTEX);
922 			}
923 
924 			if (un->un_tids_at_suspend & ST_HIB_TID) {
925 				mutex_exit(ST_MUTEX);
926 				un->un_hib_tid = timeout(st_intr_restart, un,
927 				    ST_STATUS_BUSY_TIMEOUT);
928 				mutex_enter(ST_MUTEX);
929 			}
930 
931 			ret_status = st_clear_unit_attentions(dev_instance, 5);
932 
933 			/*
934 			 * now check if we need to restore the tape position
935 			 */
936 			if ((un->un_suspend_pos.pmode != invalid) &&
937 			    ((un->un_suspend_pos.fileno > 0) ||
938 			    (un->un_suspend_pos.blkno > 0)) ||
939 			    (un->un_suspend_pos.lgclblkno > 0)) {
940 				if (ret_status != 0) {
941 					/*
942 					 * tape didn't get good TUR
943 					 * just print out error messages
944 					 */
945 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
946 					    "st_attach-RESUME: tape failure "
947 					    " tape position will be lost");
948 				} else {
949 					/* this prints errors */
950 					(void) st_validate_tapemarks(un,
951 					    st_uscsi_cmd, &un->un_suspend_pos);
952 				}
953 				/*
954 				 * there are no retries, if there is an error
955 				 * we don't know if the tape has changed
956 				 */
957 				un->un_suspend_pos.pmode = invalid;
958 			}
959 
960 			/* now we are ready to start up any queued I/Os */
961 			if (un->un_ncmds || un->un_quef) {
962 				st_start(un);
963 			}
964 
965 			cv_broadcast(&un->un_suspend_cv);
966 			mutex_exit(ST_MUTEX);
967 			return (DDI_SUCCESS);
968 
969 		default:
970 			return (DDI_FAILURE);
971 	}
972 
973 	un = ddi_get_soft_state(st_state, instance);
974 
975 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
976 	    "st_attach: instance=%x\n", instance);
977 
978 	/*
979 	 * Add a zero-length attribute to tell the world we support
980 	 * kernel ioctls (for layered drivers)
981 	 */
982 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
983 	    DDI_KERNEL_IOCTL, NULL, 0);
984 
985 	ddi_report_dev((dev_info_t *)devi);
986 
987 	/*
988 	 * If it's a SCSI-2 tape drive which supports wide,
989 	 * tell the host adapter to use wide.
990 	 */
991 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
992 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
993 
994 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
995 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
996 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
997 	}
998 
999 	/*
1000 	 * enable autorequest sense; keep the rq packet around in case
1001 	 * the autorequest sense fails because of a busy condition
1002 	 * do a getcap first in case the capability is not variable
1003 	 */
1004 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
1005 		un->un_arq_enabled = 1;
1006 	} else {
1007 		un->un_arq_enabled =
1008 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
1009 	}
1010 
1011 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
1012 	    (un->un_arq_enabled ? "enabled" : "disabled"));
1013 
1014 	un->un_untagged_qing =
1015 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
1016 
1017 	/*
1018 	 * XXX - This is just for 2.6.  to tell users that write buffering
1019 	 *	has gone away.
1020 	 */
1021 	if (un->un_arq_enabled && un->un_untagged_qing) {
1022 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
1023 		    "tape-driver-buffering", 0) != 0) {
1024 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1025 			    "Write Data Buffering has been depricated. Your "
1026 			    "applications should continue to work normally.\n"
1027 			    " But, they should  ported to use Asynchronous "
1028 			    " I/O\n"
1029 			    " For more information, read about "
1030 			    " tape-driver-buffering "
1031 			    "property in the st(7d) man page\n");
1032 		}
1033 	}
1034 
1035 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
1036 	un->un_flush_on_errors = 0;
1037 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
1038 
1039 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
1040 	    "throttle=%x, max_throttle = %x\n",
1041 	    un->un_throttle, un->un_max_throttle);
1042 
1043 	/* initialize persistent errors to nil */
1044 	un->un_persistence = 0;
1045 	un->un_persist_errors = 0;
1046 
1047 	/*
1048 	 * Get dma-max from HBA driver. If it is not defined, use 64k
1049 	 */
1050 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
1051 	if (un->un_maxdma == -1) {
1052 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1053 		    "Received a value that looked like -1. Using 64k maxdma");
1054 		un->un_maxdma = (64 * ONE_K);
1055 	}
1056 
1057 #ifdef	__x86
1058 	/*
1059 	 * for x86, the device may be able to DMA more than the system will
1060 	 * allow under some circumstances. We need account for both the HBA's
1061 	 * and system's contraints.
1062 	 *
1063 	 * Get the maximum DMA under worse case conditions. e.g. looking at the
1064 	 * device constraints, the max copy buffer size, and the worse case
1065 	 * fragmentation. NOTE: this may differ from dma-max since dma-max
1066 	 * doesn't take the worse case framentation into account.
1067 	 *
1068 	 * e.g. a device may be able to DMA 16MBytes, but can only DMA 1MByte
1069 	 * if none of the pages are contiguous. Keeping track of both of these
1070 	 * values allows us to support larger tape block sizes on some devices.
1071 	 */
1072 	un->un_maxdma_arch = scsi_ifgetcap(&devp->sd_address, "dma-max-arch",
1073 	    1);
1074 
1075 	/*
1076 	 * If the dma-max-arch capability is not implemented, or the value
1077 	 * comes back higher than what was reported in dma-max, use dma-max.
1078 	 */
1079 	if ((un->un_maxdma_arch == -1) ||
1080 	    ((uint_t)un->un_maxdma < (uint_t)un->un_maxdma_arch)) {
1081 		un->un_maxdma_arch = un->un_maxdma;
1082 	}
1083 #endif
1084 
1085 	/*
1086 	 * Get the max allowable cdb size
1087 	 */
1088 	un->un_max_cdb_sz =
1089 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
1090 	if (un->un_max_cdb_sz < CDB_GROUP0) {
1091 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1092 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
1093 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
1094 	}
1095 
1096 	if (strcmp(ddi_driver_name(ddi_get_parent(ST_DEVINFO)), "scsi_vhci")) {
1097 		un->un_multipath = 0;
1098 	} else {
1099 		un->un_multipath = 1;
1100 	}
1101 
1102 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1103 
1104 	un->un_mediastate = MTIO_NONE;
1105 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1106 
1107 	/*
1108 	 * initialize kstats
1109 	 */
1110 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1111 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1112 	if (un->un_stats) {
1113 		un->un_stats->ks_lock = ST_MUTEX;
1114 		kstat_install(un->un_stats);
1115 	}
1116 	(void) st_create_errstats(un, instance);
1117 
1118 	/*
1119 	 * find the drive type for this target
1120 	 */
1121 	mutex_enter(ST_MUTEX);
1122 	un->un_dev = MTMINOR(instance);
1123 	st_known_tape_type(un);
1124 	un->un_dev = 0;
1125 	mutex_exit(ST_MUTEX);
1126 
1127 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
1128 		int minor;
1129 		char *name;
1130 
1131 		name  = st_minor_data[node_ix].name;
1132 		minor = st_minor_data[node_ix].minor;
1133 
1134 		/*
1135 		 * For default devices set the density to the
1136 		 * preferred default density for this device.
1137 		 */
1138 		if (node_ix <= DEF_BSD_NR) {
1139 			minor |= un->un_dp->default_density;
1140 		}
1141 		minor |= MTMINOR(instance);
1142 
1143 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
1144 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
1145 			continue;
1146 		}
1147 
1148 		ddi_remove_minor_node(devi, NULL);
1149 
1150 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1151 		    st_reset_notification, (caddr_t)un);
1152 		cv_destroy(&un->un_clscv);
1153 		cv_destroy(&un->un_sbuf_cv);
1154 		cv_destroy(&un->un_queue_cv);
1155 		cv_destroy(&un->un_state_cv);
1156 #ifdef	__x86
1157 		cv_destroy(&un->un_contig_mem_cv);
1158 #endif
1159 		cv_destroy(&un->un_suspend_cv);
1160 		cv_destroy(&un->un_tape_busy_cv);
1161 		cv_destroy(&un->un_recov_buf_cv);
1162 		if (un->un_recov_taskq) {
1163 			ddi_taskq_destroy(un->un_recov_taskq);
1164 		}
1165 		if (un->un_sbufp) {
1166 			freerbuf(un->un_sbufp);
1167 		}
1168 		if (un->un_recov_buf) {
1169 			freerbuf(un->un_recov_buf);
1170 		}
1171 		if (un->un_uscsi_rqs_buf) {
1172 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1173 		}
1174 		if (un->un_mspl) {
1175 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1176 		}
1177 		if (un->un_dp_size) {
1178 			kmem_free(un->un_dp, un->un_dp_size);
1179 		}
1180 		if (un->un_state) {
1181 			kstat_delete(un->un_stats);
1182 		}
1183 		if (un->un_errstats) {
1184 			kstat_delete(un->un_errstats);
1185 		}
1186 
1187 		scsi_destroy_pkt(un->un_rqs);
1188 		scsi_free_consistent_buf(un->un_rqs_bp);
1189 		ddi_soft_state_free(st_state, instance);
1190 		devp->sd_private = NULL;
1191 		devp->sd_sense = NULL;
1192 
1193 		ddi_prop_remove_all(devi);
1194 		return (DDI_FAILURE);
1195 	}
1196 
1197 	return (DDI_SUCCESS);
1198 }
1199 
1200 /*
1201  * st_detach:
1202  *
1203  * we allow a detach if and only if:
1204  *	- no tape is currently inserted
1205  *	- tape position is at BOT or unknown
1206  *		(if it is not at BOT then a no rewind
1207  *		device was opened and we have to preserve state)
1208  *	- it must be in a closed state : no timeouts or scsi_watch requests
1209  *		will exist if it is closed, so we don't need to check for
1210  *		them here.
1211  */
1212 /*ARGSUSED*/
1213 static int
1214 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1215 {
1216 	int instance;
1217 	int result;
1218 	struct scsi_device *devp;
1219 	struct scsi_tape *un;
1220 	clock_t wait_cmds_complete;
1221 
1222 	ST_ENTR(devi, st_detach);
1223 
1224 	instance = ddi_get_instance(devi);
1225 
1226 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1227 		return (DDI_FAILURE);
1228 	}
1229 
1230 	mutex_enter(ST_MUTEX);
1231 
1232 	/*
1233 	 * Clear error entry stack
1234 	 */
1235 	st_empty_error_stack(un);
1236 
1237 	mutex_exit(ST_MUTEX);
1238 
1239 	switch (cmd) {
1240 
1241 	case DDI_DETACH:
1242 		/*
1243 		 * Undo what we did in st_attach & st_doattach,
1244 		 * freeing resources and removing things we installed.
1245 		 * The system framework guarantees we are not active
1246 		 * with this devinfo node in any other entry points at
1247 		 * this time.
1248 		 */
1249 
1250 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1251 		    "st_detach: instance=%x, un=%p\n", instance,
1252 		    (void *)un);
1253 
1254 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1255 		    ((un->un_rsvd_status & ST_APPLICATION_RESERVATIONS) != 0) ||
1256 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1257 		    (un->un_state != ST_STATE_CLOSED)) {
1258 			/*
1259 			 * we cannot unload some targets because the
1260 			 * inquiry returns junk unless immediately
1261 			 * after a reset
1262 			 */
1263 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1264 			    "cannot unload instance %x\n", instance);
1265 			un->un_unit_attention_flags |= 4;
1266 			return (DDI_FAILURE);
1267 		}
1268 
1269 		/*
1270 		 * if the tape has been removed then we may unload;
1271 		 * do a test unit ready and if it returns NOT READY
1272 		 * then we assume that it is safe to unload.
1273 		 * as a side effect, pmode may be set to invalid if the
1274 		 * the test unit ready fails;
1275 		 * also un_state may be set to non-closed, so reset it
1276 		 */
1277 		if ((un->un_dev) &&		/* Been opened since attach */
1278 		    ((un->un_pos.pmode == legacy) &&
1279 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1280 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1281 		    ((un->un_pos.pmode == logical) &&
1282 		    (un->un_pos.lgclblkno > 0))) {
1283 			mutex_enter(ST_MUTEX);
1284 			/*
1285 			 * Send Test Unit Ready in the hopes that if
1286 			 * the drive is not in the state we think it is.
1287 			 * And the state will be changed so it can be detached.
1288 			 * If the command fails to reach the device and
1289 			 * the drive was not rewound or unloaded we want
1290 			 * to fail the detach till a user command fails
1291 			 * where after the detach will succead.
1292 			 */
1293 			result = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
1294 			/*
1295 			 * After TUR un_state may be set to non-closed,
1296 			 * so reset it back.
1297 			 */
1298 			un->un_state = ST_STATE_CLOSED;
1299 			mutex_exit(ST_MUTEX);
1300 		}
1301 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1302 		    "un_status=%x, fileno=%x, blkno=%x\n",
1303 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1304 
1305 		/*
1306 		 * check again:
1307 		 * if we are not at BOT then it is not safe to unload
1308 		 */
1309 		if ((un->un_dev) &&		/* Been opened since attach */
1310 		    (result != EACCES) &&	/* drive is use by somebody */
1311 		    (((un->un_pos.pmode == legacy) &&
1312 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1313 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1314 		    ((un->un_pos.pmode == logical) &&
1315 		    (un->un_pos.lgclblkno > 0)))) {
1316 
1317 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1318 			    "cannot detach: pmode=%d fileno=0x%x, blkno=0x%x"
1319 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1320 			    un->un_pos.fileno, un->un_pos.blkno,
1321 			    un->un_pos.lgclblkno);
1322 			un->un_unit_attention_flags |= 4;
1323 			return (DDI_FAILURE);
1324 		}
1325 
1326 		/*
1327 		 * Just To make sure that we have released the
1328 		 * tape unit .
1329 		 */
1330 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1331 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1332 			mutex_enter(ST_MUTEX);
1333 			(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
1334 			mutex_exit(ST_MUTEX);
1335 		}
1336 
1337 		/*
1338 		 * now remove other data structures allocated in st_doattach()
1339 		 */
1340 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1341 		    "destroying/freeing\n");
1342 
1343 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1344 		    st_reset_notification, (caddr_t)un);
1345 		cv_destroy(&un->un_clscv);
1346 		cv_destroy(&un->un_sbuf_cv);
1347 		cv_destroy(&un->un_queue_cv);
1348 		cv_destroy(&un->un_suspend_cv);
1349 		cv_destroy(&un->un_tape_busy_cv);
1350 		cv_destroy(&un->un_recov_buf_cv);
1351 
1352 		if (un->un_recov_taskq) {
1353 			ddi_taskq_destroy(un->un_recov_taskq);
1354 		}
1355 
1356 		if (un->un_hib_tid) {
1357 			(void) untimeout(un->un_hib_tid);
1358 			un->un_hib_tid = 0;
1359 		}
1360 
1361 		if (un->un_delay_tid) {
1362 			(void) untimeout(un->un_delay_tid);
1363 			un->un_delay_tid = 0;
1364 		}
1365 		cv_destroy(&un->un_state_cv);
1366 
1367 #ifdef	__x86
1368 		cv_destroy(&un->un_contig_mem_cv);
1369 
1370 		if (un->un_contig_mem_hdl != NULL) {
1371 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1372 		}
1373 #endif
1374 		if (un->un_sbufp) {
1375 			freerbuf(un->un_sbufp);
1376 		}
1377 		if (un->un_recov_buf) {
1378 			freerbuf(un->un_recov_buf);
1379 		}
1380 		if (un->un_uscsi_rqs_buf) {
1381 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1382 		}
1383 		if (un->un_mspl) {
1384 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1385 		}
1386 		if (un->un_rqs) {
1387 			scsi_destroy_pkt(un->un_rqs);
1388 			scsi_free_consistent_buf(un->un_rqs_bp);
1389 		}
1390 		if (un->un_mkr_pkt) {
1391 			scsi_destroy_pkt(un->un_mkr_pkt);
1392 		}
1393 		if (un->un_arq_enabled) {
1394 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1395 		}
1396 		if (un->un_dp_size) {
1397 			kmem_free(un->un_dp, un->un_dp_size);
1398 		}
1399 		if (un->un_stats) {
1400 			kstat_delete(un->un_stats);
1401 			un->un_stats = (kstat_t *)0;
1402 		}
1403 		if (un->un_errstats) {
1404 			kstat_delete(un->un_errstats);
1405 			un->un_errstats = (kstat_t *)0;
1406 		}
1407 		if (un->un_media_id_len) {
1408 			kmem_free(un->un_media_id, un->un_media_id_len);
1409 		}
1410 		devp = ST_SCSI_DEVP;
1411 		ddi_soft_state_free(st_state, instance);
1412 		devp->sd_private = NULL;
1413 		devp->sd_sense = NULL;
1414 		scsi_unprobe(devp);
1415 		ddi_prop_remove_all(devi);
1416 		ddi_remove_minor_node(devi, NULL);
1417 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1418 		return (DDI_SUCCESS);
1419 
1420 	case DDI_SUSPEND:
1421 
1422 		/*
1423 		 * Suspend/Resume
1424 		 *
1425 		 * To process DDI_SUSPEND, we must do the following:
1426 		 *
1427 		 *  - check ddi_removing_power to see if power will be turned
1428 		 *    off. if so, return DDI_FAILURE
1429 		 *  - check if we are already suspended,
1430 		 *    if so, return DDI_FAILURE
1431 		 *  - check if device state is CLOSED,
1432 		 *    if not, return DDI_FAILURE.
1433 		 *  - wait until outstanding operations complete
1434 		 *  - save tape state
1435 		 *  - block new operations
1436 		 *  - cancel pending timeouts
1437 		 *
1438 		 */
1439 
1440 		if (ddi_removing_power(devi)) {
1441 			return (DDI_FAILURE);
1442 		}
1443 		mutex_enter(ST_MUTEX);
1444 
1445 		/*
1446 		 * Shouldn't already be suspended, if so return failure
1447 		 */
1448 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1449 			mutex_exit(ST_MUTEX);
1450 			return (DDI_FAILURE);
1451 		}
1452 		if (un->un_state != ST_STATE_CLOSED) {
1453 			mutex_exit(ST_MUTEX);
1454 			return (DDI_FAILURE);
1455 		}
1456 
1457 		/*
1458 		 * Wait for all outstanding I/O's to complete
1459 		 *
1460 		 * we wait on both ncmds and the wait queue for times
1461 		 * when we are flushing after persistent errors are
1462 		 * flagged, which is when ncmds can be 0, and the
1463 		 * queue can still have I/O's.  This way we preserve
1464 		 * order of biodone's.
1465 		 */
1466 		wait_cmds_complete = ddi_get_lbolt();
1467 		wait_cmds_complete +=
1468 		    st_wait_cmds_complete * drv_usectohz(1000000);
1469 		while (un->un_ncmds || un->un_quef ||
1470 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1471 
1472 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1473 			    wait_cmds_complete) == -1) {
1474 				/*
1475 				 * Time expired then cancel the command
1476 				 */
1477 				if (st_reset(un, RESET_LUN) == 0) {
1478 					if (un->un_last_throttle) {
1479 						un->un_throttle =
1480 						    un->un_last_throttle;
1481 					}
1482 					mutex_exit(ST_MUTEX);
1483 					return (DDI_FAILURE);
1484 				} else {
1485 					break;
1486 				}
1487 			}
1488 		}
1489 
1490 		/*
1491 		 * DDI_SUSPEND says that the system "may" power down, we
1492 		 * remember the file and block number before rewinding.
1493 		 * we also need to save state before issuing
1494 		 * any WRITE_FILE_MARK command.
1495 		 */
1496 		(void) st_update_block_pos(un, st_cmd, 0);
1497 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1498 
1499 
1500 		/*
1501 		 * Issue a zero write file fmk command to tell the drive to
1502 		 * flush any buffered tape marks
1503 		 */
1504 		(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1505 
1506 		/*
1507 		 * Because not all tape drives correctly implement buffer
1508 		 * flushing with the zero write file fmk command, issue a
1509 		 * synchronous rewind command to force data flushing.
1510 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1511 		 * anyway.
1512 		 */
1513 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
1514 
1515 		/* stop any new operations */
1516 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1517 		un->un_throttle = 0;
1518 
1519 		/*
1520 		 * cancel any outstanding timeouts
1521 		 */
1522 		if (un->un_delay_tid) {
1523 			timeout_id_t temp_id = un->un_delay_tid;
1524 			un->un_delay_tid = 0;
1525 			un->un_tids_at_suspend |= ST_DELAY_TID;
1526 			mutex_exit(ST_MUTEX);
1527 			(void) untimeout(temp_id);
1528 			mutex_enter(ST_MUTEX);
1529 		}
1530 
1531 		if (un->un_hib_tid) {
1532 			timeout_id_t temp_id = un->un_hib_tid;
1533 			un->un_hib_tid = 0;
1534 			un->un_tids_at_suspend |= ST_HIB_TID;
1535 			mutex_exit(ST_MUTEX);
1536 			(void) untimeout(temp_id);
1537 			mutex_enter(ST_MUTEX);
1538 		}
1539 
1540 		/*
1541 		 * Suspend the scsi_watch_thread
1542 		 */
1543 		if (un->un_swr_token) {
1544 			opaque_t temp_token = un->un_swr_token;
1545 			mutex_exit(ST_MUTEX);
1546 			scsi_watch_suspend(temp_token);
1547 		} else {
1548 			mutex_exit(ST_MUTEX);
1549 		}
1550 
1551 		return (DDI_SUCCESS);
1552 
1553 	default:
1554 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1555 		return (DDI_FAILURE);
1556 	}
1557 }
1558 
1559 
1560 /* ARGSUSED */
1561 static int
1562 st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1563 {
1564 	dev_t dev;
1565 	struct scsi_tape *un;
1566 	int instance, error;
1567 
1568 	ST_ENTR(dip, st_info);
1569 
1570 	switch (infocmd) {
1571 	case DDI_INFO_DEVT2DEVINFO:
1572 		dev = (dev_t)arg;
1573 		instance = MTUNIT(dev);
1574 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1575 			return (DDI_FAILURE);
1576 		*result = (void *) ST_DEVINFO;
1577 		error = DDI_SUCCESS;
1578 		break;
1579 	case DDI_INFO_DEVT2INSTANCE:
1580 		dev = (dev_t)arg;
1581 		instance = MTUNIT(dev);
1582 		*result = (void *)(uintptr_t)instance;
1583 		error = DDI_SUCCESS;
1584 		break;
1585 	default:
1586 		error = DDI_FAILURE;
1587 	}
1588 	return (error);
1589 }
1590 
1591 static int
1592 st_doattach(struct scsi_device *devp, int (*canwait)())
1593 {
1594 	struct scsi_tape *un = NULL;
1595 	recov_info *ri;
1596 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1597 	int instance;
1598 	size_t rlen;
1599 
1600 	ST_FUNC(devp->sd_dev, st_doattach);
1601 	/*
1602 	 * Call the routine scsi_probe to do some of the dirty work.
1603 	 * If the INQUIRY command succeeds, the field sd_inq in the
1604 	 * device structure will be filled in.
1605 	 */
1606 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1607 	    "st_doattach(): probing\n");
1608 
1609 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1610 
1611 		/*
1612 		 * In checking the whole inq_dtype byte we are looking at both
1613 		 * the Peripheral Qualifier and the Peripheral Device Type.
1614 		 * For this driver we are only interested in sequential devices
1615 		 * that are connected or capable if connecting to this logical
1616 		 * unit.
1617 		 */
1618 		if (devp->sd_inq->inq_dtype ==
1619 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1620 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1621 			    "probe exists\n");
1622 		} else {
1623 			/* Something there but not a tape device */
1624 			scsi_unprobe(devp);
1625 			return (DDI_FAILURE);
1626 		}
1627 	} else {
1628 		/* Nothing there */
1629 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1630 		    "probe failure: nothing there\n");
1631 		scsi_unprobe(devp);
1632 		return (DDI_FAILURE);
1633 	}
1634 
1635 
1636 	/*
1637 	 * The actual unit is present.
1638 	 * Now is the time to fill in the rest of our info..
1639 	 */
1640 	instance = ddi_get_instance(devp->sd_dev);
1641 
1642 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1643 		goto error;
1644 	}
1645 	un = ddi_get_soft_state(st_state, instance);
1646 
1647 	ASSERT(un != NULL);
1648 
1649 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
1650 	    MAX_SENSE_LENGTH, B_READ, canwait, NULL);
1651 	if (un->un_rqs_bp == NULL) {
1652 		goto error;
1653 	}
1654 	un->un_rqs = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
1655 	    CDB_GROUP0, 1, st_recov_sz, PKT_CONSISTENT, canwait, NULL);
1656 	if (!un->un_rqs) {
1657 		goto error;
1658 	}
1659 	ASSERT(un->un_rqs->pkt_resid == 0);
1660 	devp->sd_sense =
1661 	    (struct scsi_extended_sense *)un->un_rqs_bp->b_un.b_addr;
1662 	ASSERT(geterror(un->un_rqs_bp) == NULL);
1663 
1664 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs->pkt_cdbp,
1665 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
1666 	FILL_SCSI1_LUN(devp, un->un_rqs);
1667 	un->un_rqs->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1668 	un->un_rqs->pkt_time = st_io_time;
1669 	un->un_rqs->pkt_comp = st_intr;
1670 	ri = (recov_info *)un->un_rqs->pkt_private;
1671 	if (st_recov_sz == sizeof (recov_info)) {
1672 		ri->privatelen = sizeof (recov_info);
1673 	} else {
1674 		ri->privatelen = sizeof (pkt_info);
1675 	}
1676 
1677 	un->un_sbufp = getrbuf(km_flags);
1678 	un->un_recov_buf = getrbuf(km_flags);
1679 
1680 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1681 
1682 	/*
1683 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1684 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1685 	 * is obsolete and we want more flexibility in controlling the DMA
1686 	 * address constraints.
1687 	 */
1688 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1689 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1690 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1691 
1692 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1693 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1694 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1695 
1696 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1697 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1698 		    "probe partial failure: no space\n");
1699 		goto error;
1700 	}
1701 
1702 	bzero(un->un_mspl, sizeof (struct seq_mode));
1703 
1704 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1705 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1706 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1707 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1708 #ifdef	__x86
1709 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1710 #endif
1711 
1712 	/* Initialize power managemnet condition variable */
1713 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1714 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1715 	cv_init(&un->un_recov_buf_cv, NULL, CV_DRIVER, NULL);
1716 
1717 	un->un_recov_taskq = ddi_taskq_create(devp->sd_dev,
1718 	    "un_recov_taskq", 1, TASKQ_DEFAULTPRI, km_flags);
1719 
1720 	ASSERT(un->un_recov_taskq != NULL);
1721 
1722 	un->un_pos.pmode = invalid;
1723 	un->un_sd	= devp;
1724 	un->un_swr_token = (opaque_t)NULL;
1725 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1726 	un->un_wormable = st_is_drive_worm;
1727 	un->un_media_id_method = st_get_media_identification;
1728 	/*
1729 	 * setting long a initial as it contains logical file info.
1730 	 * support for long format is mandatory but many drive don't do it.
1731 	 */
1732 	un->un_read_pos_type = LONG_POS;
1733 
1734 	un->un_suspend_pos.pmode = invalid;
1735 
1736 	st_add_recovery_info_to_pkt(un, un->un_rqs_bp, un->un_rqs);
1737 
1738 #ifdef	__x86
1739 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1740 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1741 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1742 		    "allocation of contiguous memory dma handle failed!");
1743 		un->un_contig_mem_hdl = NULL;
1744 		goto error;
1745 	}
1746 #endif
1747 
1748 	/*
1749 	 * Since this driver manages devices with "remote" hardware,
1750 	 * i.e. the devices themselves have no "reg" properties,
1751 	 * the SUSPEND/RESUME commands in detach/attach will not be
1752 	 * called by the power management framework unless we request
1753 	 * it by creating a "pm-hardware-state" property and setting it
1754 	 * to value "needs-suspend-resume".
1755 	 */
1756 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1757 	    "pm-hardware-state", "needs-suspend-resume") !=
1758 	    DDI_PROP_SUCCESS) {
1759 
1760 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1761 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1762 		goto error;
1763 	}
1764 
1765 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1766 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1767 
1768 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1769 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1770 		    "failed\n");
1771 		goto error;
1772 	}
1773 
1774 	(void) scsi_reset_notify(ROUTE, SCSI_RESET_NOTIFY,
1775 	    st_reset_notification, (caddr_t)un);
1776 
1777 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "attach success\n");
1778 	return (DDI_SUCCESS);
1779 
1780 error:
1781 	devp->sd_sense = NULL;
1782 
1783 	ddi_remove_minor_node(devp->sd_dev, NULL);
1784 	if (un) {
1785 		if (un->un_mspl) {
1786 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1787 		}
1788 		if (un->un_read_pos_data) {
1789 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1790 		}
1791 		if (un->un_sbufp) {
1792 			freerbuf(un->un_sbufp);
1793 		}
1794 		if (un->un_recov_buf) {
1795 			freerbuf(un->un_recov_buf);
1796 		}
1797 		if (un->un_uscsi_rqs_buf) {
1798 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1799 		}
1800 #ifdef	__x86
1801 		if (un->un_contig_mem_hdl != NULL) {
1802 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1803 		}
1804 #endif
1805 		if (un->un_rqs) {
1806 			scsi_destroy_pkt(un->un_rqs);
1807 		}
1808 
1809 		if (un->un_rqs_bp) {
1810 			scsi_free_consistent_buf(un->un_rqs_bp);
1811 		}
1812 
1813 		ddi_soft_state_free(st_state, instance);
1814 		devp->sd_private = NULL;
1815 	}
1816 
1817 	if (devp->sd_inq) {
1818 		scsi_unprobe(devp);
1819 	}
1820 	return (DDI_FAILURE);
1821 }
1822 
1823 typedef int
1824 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1825 
1826 static cfg_functp config_functs[] = {
1827 	st_get_conf_from_st_dot_conf,
1828 	st_get_conf_from_st_conf_dot_c,
1829 	st_get_conf_from_tape_drive,
1830 	st_get_default_conf
1831 };
1832 
1833 
1834 /*
1835  * determine tape type, using tape-config-list or built-in table or
1836  * use a generic tape config entry
1837  */
1838 static void
1839 st_known_tape_type(struct scsi_tape *un)
1840 {
1841 	struct st_drivetype *dp;
1842 	cfg_functp *config_funct;
1843 	uchar_t reserved;
1844 
1845 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1846 
1847 	reserved = (un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1848 	    : ST_RELEASE;
1849 
1850 	/*
1851 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1852 	 *	 no vid & pid inquiry data.  So, we provide one.
1853 	 */
1854 	if (ST_INQUIRY->inq_len == 0 ||
1855 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1856 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1857 	}
1858 
1859 	if (un->un_dp_size == 0) {
1860 		un->un_dp_size = sizeof (struct st_drivetype);
1861 		dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1862 		un->un_dp = dp;
1863 	} else {
1864 		dp = un->un_dp;
1865 	}
1866 
1867 	un->un_dp->non_motion_timeout = st_io_time;
1868 	/*
1869 	 * Loop through the configuration methods till one works.
1870 	 */
1871 	for (config_funct = &config_functs[0]; ; config_funct++) {
1872 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1873 			break;
1874 		}
1875 	}
1876 
1877 	/*
1878 	 * If we didn't just make up this configuration and
1879 	 * all the density codes are the same..
1880 	 * Set Auto Density over ride.
1881 	 */
1882 	if (*config_funct != st_get_default_conf) {
1883 		/*
1884 		 * If this device is one that is configured and all
1885 		 * densities are the same, This saves doing gets and set
1886 		 * that yield nothing.
1887 		 */
1888 		if ((dp->densities[0]) == (dp->densities[1]) &&
1889 		    (dp->densities[0]) == (dp->densities[2]) &&
1890 		    (dp->densities[0]) == (dp->densities[3])) {
1891 
1892 			dp->options |= ST_AUTODEN_OVERRIDE;
1893 		}
1894 	}
1895 
1896 
1897 	/*
1898 	 * Store tape drive characteristics.
1899 	 */
1900 	un->un_status = 0;
1901 	un->un_attached = 1;
1902 	un->un_init_options = dp->options;
1903 
1904 	/* setup operation time-outs based on options */
1905 	st_calculate_timeouts(un);
1906 
1907 	/* make sure if we are supposed to be variable, make it variable */
1908 	if (dp->options & ST_VARIABLE) {
1909 		dp->bsize = 0;
1910 	}
1911 
1912 	if (reserved != ((un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1913 	    : ST_RELEASE)) {
1914 		(void) st_reserve_release(un, reserved, st_uscsi_cmd);
1915 	}
1916 
1917 	un->un_unit_attention_flags |= 1;
1918 
1919 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1920 
1921 }
1922 
1923 
1924 typedef struct {
1925 	int mask;
1926 	int bottom;
1927 	int top;
1928 	char *name;
1929 } conf_limit;
1930 
1931 static const conf_limit conf_limits[] = {
1932 
1933 	-1,		1,		2,		"conf version",
1934 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1935 	-1,		0,		0xffffff,	"block size",
1936 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1937 	-1,		0,		4,		"number of densities",
1938 	-1,		0,		UINT8_MAX,	"density code",
1939 	-1,		0,		3,		"default density",
1940 	-1,		0,		UINT16_MAX,	"non motion timeout",
1941 	-1,		0,		UINT16_MAX,	"I/O timeout",
1942 	-1,		0,		UINT16_MAX,	"space timeout",
1943 	-1,		0,		UINT16_MAX,	"load timeout",
1944 	-1,		0,		UINT16_MAX,	"unload timeout",
1945 	-1,		0,		UINT16_MAX,	"erase timeout",
1946 	0,		0,		0,		NULL
1947 };
1948 
1949 static int
1950 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1951     const char *conf_name)
1952 {
1953 	int dens;
1954 	int ndens;
1955 	int value;
1956 	int type;
1957 	int count;
1958 	const conf_limit *limit = &conf_limits[0];
1959 
1960 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1961 
1962 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1963 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1964 
1965 	count = list_len;
1966 	type = *list;
1967 	for (;  count && limit->name; count--, list++, limit++) {
1968 
1969 		value = *list;
1970 		if (value & ~limit->mask) {
1971 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1972 			    "%s %s value invalid bits set: 0x%X\n",
1973 			    conf_name, limit->name, value & ~limit->mask);
1974 			*list &= limit->mask;
1975 		} else if (value < limit->bottom) {
1976 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1977 			    "%s %s value too low: value = %d limit %d\n",
1978 			    conf_name, limit->name, value, limit->bottom);
1979 		} else if (value > limit->top) {
1980 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1981 			    "%s %s value too high: value = %d limit %d\n",
1982 			    conf_name, limit->name, value, limit->top);
1983 		} else {
1984 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1985 			    "%s %s value = 0x%X\n",
1986 			    conf_name, limit->name, value);
1987 		}
1988 
1989 		/* If not the number of densities continue */
1990 		if (limit != &conf_limits[4]) {
1991 			continue;
1992 		}
1993 
1994 		/* If number of densities is not in range can't use config */
1995 		if (value < limit->bottom || value > limit->top) {
1996 			return (-1);
1997 		}
1998 
1999 		ndens = min(value, NDENSITIES);
2000 		if ((type == 1) && (list_len - ndens) != 6) {
2001 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2002 			    "%s conf version 1 with %d densities has %d items"
2003 			    " should have %d",
2004 			    conf_name, ndens, list_len, 6 + ndens);
2005 		} else if ((type == 2) && (list_len - ndens) != 13) {
2006 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2007 			    "%s conf version 2 with %d densities has %d items"
2008 			    " should have %d",
2009 			    conf_name, ndens, list_len, 13 + ndens);
2010 		}
2011 
2012 		limit++;
2013 		for (dens = 0; dens < ndens && count; dens++) {
2014 			count--;
2015 			list++;
2016 			value = *list;
2017 			if (value < limit->bottom) {
2018 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2019 				    "%s density[%d] value too low: value ="
2020 				    " 0x%X limit 0x%X\n",
2021 				    conf_name, dens, value, limit->bottom);
2022 			} else if (value > limit->top) {
2023 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2024 				    "%s density[%d] value too high: value ="
2025 				    " 0x%X limit 0x%X\n",
2026 				    conf_name, dens, value, limit->top);
2027 			} else {
2028 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2029 				    "%s density[%d] value = 0x%X\n",
2030 				    conf_name, dens, value);
2031 			}
2032 		}
2033 	}
2034 
2035 	return (0);
2036 }
2037 
2038 static int
2039 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
2040     struct st_drivetype *dp)
2041 {
2042 	caddr_t config_list = NULL;
2043 	caddr_t data_list = NULL;
2044 	int	*data_ptr;
2045 	caddr_t vidptr, prettyptr, datanameptr;
2046 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
2047 	int config_list_len, data_list_len, len, i;
2048 	int version;
2049 	int found = 0;
2050 
2051 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
2052 
2053 	/*
2054 	 * Determine type of tape controller. Type is determined by
2055 	 * checking the vendor ids of the earlier inquiry command and
2056 	 * comparing those with vids in tape-config-list defined in st.conf
2057 	 */
2058 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
2059 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
2060 	    != DDI_PROP_SUCCESS) {
2061 		return (found);
2062 	}
2063 
2064 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2065 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
2066 
2067 	/*
2068 	 * Compare vids in each triplet - if it matches, get value for
2069 	 * data_name and contruct a st_drivetype struct
2070 	 * tripletlen is not set yet!
2071 	 */
2072 	for (len = config_list_len, vidptr = config_list;
2073 	    len > 0;
2074 	    vidptr += tripletlen, len -= tripletlen) {
2075 
2076 		vidlen = strlen(vidptr);
2077 		prettyptr = vidptr + vidlen + 1;
2078 		prettylen = strlen(prettyptr);
2079 		datanameptr = prettyptr + prettylen + 1;
2080 		datanamelen = strlen(datanameptr);
2081 		tripletlen = vidlen + prettylen + datanamelen + 3;
2082 
2083 		if (vidlen == 0) {
2084 			continue;
2085 		}
2086 
2087 		/*
2088 		 * If inquiry vid dosen't match this triplets vid,
2089 		 * try the next.
2090 		 */
2091 		if (strncasecmp(vidpid, vidptr, vidlen)) {
2092 			continue;
2093 		}
2094 
2095 		/*
2096 		 * if prettylen is zero then use the vid string
2097 		 */
2098 		if (prettylen == 0) {
2099 			prettyptr = vidptr;
2100 			prettylen = vidlen;
2101 		}
2102 
2103 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2104 		    "vid = %s, pretty=%s, dataname = %s\n",
2105 		    vidptr, prettyptr, datanameptr);
2106 
2107 		/*
2108 		 * get the data list
2109 		 */
2110 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
2111 		    datanameptr, (caddr_t)&data_list,
2112 		    &data_list_len) != DDI_PROP_SUCCESS) {
2113 			/*
2114 			 * Error in getting property value
2115 			 * print warning!
2116 			 */
2117 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2118 			    "data property (%s) has no value\n",
2119 			    datanameptr);
2120 			continue;
2121 		}
2122 
2123 		/*
2124 		 * now initialize the st_drivetype struct
2125 		 */
2126 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
2127 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
2128 		(void) strncpy(dp->vid, vidptr, dp->length);
2129 		data_ptr = (int *)data_list;
2130 		/*
2131 		 * check if data is enough for version, type,
2132 		 * bsize, options, # of densities, density1,
2133 		 * density2, ..., default_density
2134 		 */
2135 		if ((data_list_len < 5 * sizeof (int)) ||
2136 		    (data_list_len < 6 * sizeof (int) +
2137 		    *(data_ptr + 4) * sizeof (int))) {
2138 			/*
2139 			 * print warning and skip to next triplet.
2140 			 */
2141 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2142 			    "data property (%s) incomplete\n",
2143 			    datanameptr);
2144 			kmem_free(data_list, data_list_len);
2145 			continue;
2146 		}
2147 
2148 		if (st_validate_conf_data(un, data_ptr,
2149 		    data_list_len / sizeof (int), datanameptr)) {
2150 			kmem_free(data_list, data_list_len);
2151 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2152 			    "data property (%s) rejected\n",
2153 			    datanameptr);
2154 			continue;
2155 		}
2156 
2157 		/*
2158 		 * check version
2159 		 */
2160 		version = *data_ptr++;
2161 		if (version != 1 && version != 2) {
2162 			/* print warning but accept it */
2163 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2164 			    "Version # for data property (%s) "
2165 			    "not set to 1 or 2\n", datanameptr);
2166 		}
2167 
2168 		dp->type    = *data_ptr++;
2169 		dp->bsize   = *data_ptr++;
2170 		dp->options = *data_ptr++;
2171 		dp->options |= ST_DYNAMIC;
2172 		len = *data_ptr++;
2173 		for (i = 0; i < NDENSITIES; i++) {
2174 			if (i < len) {
2175 				dp->densities[i] = *data_ptr++;
2176 			}
2177 		}
2178 		dp->default_density = *data_ptr << 3;
2179 		if (version == 2 &&
2180 		    data_list_len >= (13 + len) * sizeof (int)) {
2181 			data_ptr++;
2182 			dp->non_motion_timeout	= *data_ptr++;
2183 			dp->io_timeout		= *data_ptr++;
2184 			dp->rewind_timeout	= *data_ptr++;
2185 			dp->space_timeout	= *data_ptr++;
2186 			dp->load_timeout	= *data_ptr++;
2187 			dp->unload_timeout	= *data_ptr++;
2188 			dp->erase_timeout	= *data_ptr++;
2189 		}
2190 		kmem_free(data_list, data_list_len);
2191 		found = 1;
2192 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2193 		    "found in st.conf: vid = %s, pretty=%s\n",
2194 		    dp->vid, dp->name);
2195 		break;
2196 	}
2197 
2198 	/*
2199 	 * free up the memory allocated by ddi_getlongprop
2200 	 */
2201 	if (config_list) {
2202 		kmem_free(config_list, config_list_len);
2203 	}
2204 	return (found);
2205 }
2206 
2207 static int
2208 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2209     struct st_drivetype *dp)
2210 {
2211 	int i;
2212 
2213 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2214 	/*
2215 	 * Determine type of tape controller.  Type is determined by
2216 	 * checking the result of the earlier inquiry command and
2217 	 * comparing vendor ids with strings in a table declared in st_conf.c.
2218 	 */
2219 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2220 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2221 
2222 	for (i = 0; i < st_ndrivetypes; i++) {
2223 		if (st_drivetypes[i].length == 0) {
2224 			continue;
2225 		}
2226 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2227 		    st_drivetypes[i].length)) {
2228 			continue;
2229 		}
2230 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2231 		return (1);
2232 	}
2233 	return (0);
2234 }
2235 
2236 static int
2237 st_get_conf_from_tape_drive(struct scsi_tape *un, char *vidpid,
2238     struct st_drivetype *dp)
2239 {
2240 	int bsize;
2241 	ulong_t maxbsize;
2242 	caddr_t buf;
2243 	struct st_drivetype *tem_dp;
2244 	struct read_blklim *blklim;
2245 	int rval;
2246 	int i;
2247 
2248 	ST_FUNC(ST_DEVINFO, st_get_conf_from_tape_drive);
2249 
2250 	/*
2251 	 * Determine the type of tape controller. Type is determined by
2252 	 * sending SCSI commands to tape drive and deriving the type from
2253 	 * the returned data.
2254 	 */
2255 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2256 	    "st_get_conf_from_tape_drive(): asking tape drive\n");
2257 
2258 	tem_dp = kmem_zalloc(sizeof (struct st_drivetype), KM_SLEEP);
2259 
2260 	/*
2261 	 * Make up a name
2262 	 */
2263 	bcopy(vidpid, tem_dp->name, VIDPIDLEN);
2264 	tem_dp->name[VIDPIDLEN] = '\0';
2265 	tem_dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2266 	(void) strncpy(tem_dp->vid, ST_INQUIRY->inq_vid, tem_dp->length);
2267 	/*
2268 	 * 'clean' vendor and product strings of non-printing chars
2269 	 */
2270 	for (i = 0; i < VIDPIDLEN - 1; i ++) {
2271 		if (tem_dp->name[i] < ' ' || tem_dp->name[i] > '~') {
2272 			tem_dp->name[i] = '.';
2273 		}
2274 	}
2275 
2276 	/*
2277 	 * MODE SENSE to determine block size.
2278 	 */
2279 	un->un_dp->options |= ST_MODE_SEL_COMP | ST_UNLOADABLE;
2280 	rval = st_modesense(un);
2281 	if (rval) {
2282 		if (rval == EACCES) {
2283 			un->un_dp->type = ST_TYPE_INVALID;
2284 			rval = 1;
2285 		} else {
2286 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
2287 			rval = 0;
2288 		}
2289 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2290 		    "st_get_conf_from_tape_drive(): fail to mode sense\n");
2291 		goto exit;
2292 	}
2293 
2294 	/* Can mode sense page 0x10 or 0xf */
2295 	tem_dp->options |= ST_MODE_SEL_COMP;
2296 	bsize = (un->un_mspl->high_bl << 16)	|
2297 	    (un->un_mspl->mid_bl << 8)		|
2298 	    (un->un_mspl->low_bl);
2299 
2300 	if (bsize == 0) {
2301 		tem_dp->options |= ST_VARIABLE;
2302 		tem_dp->bsize = 0;
2303 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
2304 		rval = st_change_block_size(un, 0);
2305 		if (rval) {
2306 			if (rval == EACCES) {
2307 				un->un_dp->type = ST_TYPE_INVALID;
2308 				rval = 1;
2309 			} else {
2310 				rval = 0;
2311 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2312 				    "st_get_conf_from_tape_drive(): "
2313 				    "Fixed record size is too large and"
2314 				    "cannot switch to variable record size");
2315 			}
2316 			goto exit;
2317 		}
2318 		tem_dp->options |= ST_VARIABLE;
2319 	} else {
2320 		rval = st_change_block_size(un, 0);
2321 		if (rval == 0) {
2322 			tem_dp->options |= ST_VARIABLE;
2323 			tem_dp->bsize = 0;
2324 		} else if (rval != EACCES) {
2325 			tem_dp->bsize = bsize;
2326 		} else {
2327 			un->un_dp->type = ST_TYPE_INVALID;
2328 			rval = 1;
2329 			goto exit;
2330 		}
2331 	}
2332 
2333 	/*
2334 	 * If READ BLOCk LIMITS works and upper block size limit is
2335 	 * more than 64K, ST_NO_RECSIZE_LIMIT is supported.
2336 	 */
2337 	blklim = kmem_zalloc(sizeof (struct read_blklim), KM_SLEEP);
2338 	rval = st_read_block_limits(un, blklim);
2339 	if (rval) {
2340 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2341 		    "st_get_conf_from_tape_drive(): "
2342 		    "fail to read block limits.\n");
2343 		rval = 0;
2344 		kmem_free(blklim, sizeof (struct read_blklim));
2345 		goto exit;
2346 	}
2347 	maxbsize = (blklim->max_hi << 16) +
2348 	    (blklim->max_mid << 8) + blklim->max_lo;
2349 	if (maxbsize > ST_MAXRECSIZE_VARIABLE) {
2350 		tem_dp->options |= ST_NO_RECSIZE_LIMIT;
2351 	}
2352 	kmem_free(blklim, sizeof (struct read_blklim));
2353 
2354 	/*
2355 	 * Inquiry VPD page 0xb0 to see if the tape drive supports WORM
2356 	 */
2357 	buf = kmem_zalloc(6, KM_SLEEP);
2358 	rval = st_get_special_inquiry(un, 6, buf, 0xb0);
2359 	if (rval) {
2360 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2361 		    "st_get_conf_from_tape_drive(): "
2362 		    "fail to read vitial inquiry.\n");
2363 		rval = 0;
2364 		kmem_free(buf, 6);
2365 		goto exit;
2366 	}
2367 	if (buf[4] & 1) {
2368 		tem_dp->options |= ST_WORMABLE;
2369 	}
2370 	kmem_free(buf, 6);
2371 
2372 	/* Assume BSD BSR KNOWS_EOD */
2373 	tem_dp->options |= ST_BSF | ST_BSR | ST_KNOWS_EOD | ST_UNLOADABLE;
2374 	tem_dp->max_rretries = -1;
2375 	tem_dp->max_wretries = -1;
2376 
2377 	/*
2378 	 * Decide the densities supported by tape drive by sending
2379 	 * REPORT DENSITY SUPPORT command.
2380 	 */
2381 	if (st_get_densities_from_tape_drive(un, tem_dp) == 0) {
2382 		goto exit;
2383 	}
2384 
2385 	/*
2386 	 * Decide the timeout values for several commands by sending
2387 	 * REPORT SUPPORTED OPERATION CODES command.
2388 	 */
2389 	rval = st_get_timeout_values_from_tape_drive(un, tem_dp);
2390 	if (rval == 0 || ((rval == 1) && (tem_dp->type == ST_TYPE_INVALID))) {
2391 		goto exit;
2392 	}
2393 
2394 	bcopy(tem_dp, dp, sizeof (struct st_drivetype));
2395 	rval = 1;
2396 
2397 exit:
2398 	un->un_status = KEY_NO_SENSE;
2399 	kmem_free(tem_dp, sizeof (struct st_drivetype));
2400 	return (rval);
2401 }
2402 
2403 static int
2404 st_get_densities_from_tape_drive(struct scsi_tape *un,
2405     struct st_drivetype *dp)
2406 {
2407 	int i, p;
2408 	size_t buflen;
2409 	ushort_t des_len;
2410 	uchar_t *den_header;
2411 	uchar_t num_den;
2412 	uchar_t den[NDENSITIES];
2413 	uchar_t deflt[NDENSITIES];
2414 	struct report_density_desc *den_desc;
2415 
2416 	ST_FUNC(ST_DEVINFO, st_get_densities_from_type_drive);
2417 
2418 	/*
2419 	 * Since we have no idea how many densitiy support entries
2420 	 * will be returned, we send the command firstly assuming
2421 	 * there is only one. Then we can decide the number of
2422 	 * entries by available density support length. If multiple
2423 	 * entries exist, we will resend the command with enough
2424 	 * buffer size.
2425 	 */
2426 	buflen = sizeof (struct report_density_header) +
2427 	    sizeof (struct report_density_desc);
2428 	den_header = kmem_zalloc(buflen, KM_SLEEP);
2429 	if (st_report_density_support(un, den_header, buflen) != 0) {
2430 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2431 		    "st_get_conf_from_tape_drive(): fail to report density.\n");
2432 		kmem_free(den_header, buflen);
2433 		return (0);
2434 	}
2435 	des_len =
2436 	    BE_16(((struct report_density_header *)den_header)->ava_dens_len);
2437 	num_den = (des_len - 2) / sizeof (struct report_density_desc);
2438 
2439 	if (num_den > 1) {
2440 		kmem_free(den_header, buflen);
2441 		buflen = sizeof (struct report_density_header) +
2442 		    sizeof (struct report_density_desc) * num_den;
2443 		den_header = kmem_zalloc(buflen, KM_SLEEP);
2444 		if (st_report_density_support(un, den_header, buflen) != 0) {
2445 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2446 			    "st_get_conf_from_tape_drive(): "
2447 			    "fail to report density.\n");
2448 			kmem_free(den_header, buflen);
2449 			return (0);
2450 		}
2451 	}
2452 
2453 	den_desc = (struct report_density_desc *)(den_header
2454 	    + sizeof (struct report_density_header));
2455 
2456 	/*
2457 	 * Decide the drive type by assigning organization
2458 	 */
2459 	for (i = 0; i < ST_NUM_MEMBERS(st_vid_dt); i ++) {
2460 		if (strncmp(st_vid_dt[i].vid, (char *)(den_desc->ass_org),
2461 		    8) == 0) {
2462 			dp->type = st_vid_dt[i].type;
2463 			break;
2464 		}
2465 	}
2466 	if (i == ST_NUM_MEMBERS(st_vid_dt)) {
2467 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2468 		    "st_get_conf_from_tape_drive(): "
2469 		    "can't find match of assigned ort.\n");
2470 		kmem_free(den_header, buflen);
2471 		return (0);
2472 	}
2473 
2474 	/*
2475 	 * The tape drive may support many tape formats, but the st driver
2476 	 * supports only the four highest densities. Since density code
2477 	 * values are returned by ascending sequence, we start from the
2478 	 * last entry of density support data block descriptor.
2479 	 */
2480 	p = 0;
2481 	den_desc += num_den - 1;
2482 	for (i = 0; i < num_den && p < NDENSITIES; i ++, den_desc --) {
2483 		if ((den_desc->pri_den != 0) && (den_desc->wrtok)) {
2484 			if (p != 0) {
2485 				if (den_desc->pri_den >= den[p - 1]) {
2486 					continue;
2487 				}
2488 			}
2489 			den[p] = den_desc->pri_den;
2490 			deflt[p] = den_desc->deflt;
2491 			p ++;
2492 		}
2493 	}
2494 
2495 	switch (p) {
2496 	case 0:
2497 		bzero(dp->densities, NDENSITIES);
2498 		dp->options |= ST_AUTODEN_OVERRIDE;
2499 		dp->default_density = MT_DENSITY4;
2500 		break;
2501 
2502 	case 1:
2503 		(void) memset(dp->densities, den[0], NDENSITIES);
2504 		dp->options |= ST_AUTODEN_OVERRIDE;
2505 		dp->default_density = MT_DENSITY4;
2506 		break;
2507 
2508 	case 2:
2509 		dp->densities[0] = den[1];
2510 		dp->densities[1] = den[1];
2511 		dp->densities[2] = den[0];
2512 		dp->densities[3] = den[0];
2513 		if (deflt[0]) {
2514 			dp->default_density = MT_DENSITY4;
2515 		} else {
2516 			dp->default_density = MT_DENSITY2;
2517 		}
2518 		break;
2519 
2520 	case 3:
2521 		dp->densities[0] = den[2];
2522 		dp->densities[1] = den[1];
2523 		dp->densities[2] = den[0];
2524 		dp->densities[3] = den[0];
2525 		if (deflt[0]) {
2526 			dp->default_density = MT_DENSITY4;
2527 		} else if (deflt[1]) {
2528 			dp->default_density = MT_DENSITY2;
2529 		} else {
2530 			dp->default_density = MT_DENSITY1;
2531 		}
2532 		break;
2533 
2534 	default:
2535 		for (i = p; i > p - NDENSITIES; i --) {
2536 			dp->densities[i - 1] = den[p - i];
2537 		}
2538 		if (deflt[0]) {
2539 			dp->default_density = MT_DENSITY4;
2540 		} else if (deflt[1]) {
2541 			dp->default_density = MT_DENSITY3;
2542 		} else if (deflt[2]) {
2543 			dp->default_density = MT_DENSITY2;
2544 		} else {
2545 			dp->default_density = MT_DENSITY1;
2546 		}
2547 		break;
2548 	}
2549 
2550 	bzero(dp->mediatype, NDENSITIES);
2551 
2552 	kmem_free(den_header, buflen);
2553 	return (1);
2554 }
2555 
2556 static int
2557 st_get_timeout_values_from_tape_drive(struct scsi_tape *un,
2558     struct st_drivetype *dp)
2559 {
2560 	ushort_t timeout;
2561 	int rval;
2562 
2563 	ST_FUNC(ST_DEVINFO, st_get_timeout_values_from_type_drive);
2564 
2565 	rval = st_get_timeouts_value(un, SCMD_ERASE, &timeout, 0);
2566 	if (rval) {
2567 		if (rval == EACCES) {
2568 			un->un_dp->type = ST_TYPE_INVALID;
2569 			dp->type = ST_TYPE_INVALID;
2570 			return (1);
2571 		}
2572 		return (0);
2573 	}
2574 	dp->erase_timeout = timeout;
2575 
2576 	rval = st_get_timeouts_value(un, SCMD_READ, &timeout, 0);
2577 	if (rval) {
2578 		if (rval == EACCES) {
2579 			un->un_dp->type = ST_TYPE_INVALID;
2580 			dp->type = ST_TYPE_INVALID;
2581 			return (1);
2582 		}
2583 		return (0);
2584 	}
2585 	dp->io_timeout = timeout;
2586 
2587 	rval = st_get_timeouts_value(un, SCMD_WRITE, &timeout, 0);
2588 	if (rval) {
2589 		if (rval == EACCES) {
2590 			un->un_dp->type = ST_TYPE_INVALID;
2591 			dp->type = ST_TYPE_INVALID;
2592 			return (1);
2593 		}
2594 		return (0);
2595 	}
2596 	dp->io_timeout = max(dp->io_timeout, timeout);
2597 
2598 	rval = st_get_timeouts_value(un, SCMD_SPACE, &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->space_timeout = timeout;
2608 
2609 	rval = st_get_timeouts_value(un, SCMD_LOAD, &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->load_timeout = timeout;
2619 	dp->unload_timeout = timeout;
2620 
2621 	rval = st_get_timeouts_value(un, SCMD_REWIND, &timeout, 0);
2622 	if (rval) {
2623 		if (rval == EACCES) {
2624 			un->un_dp->type = ST_TYPE_INVALID;
2625 			dp->type = ST_TYPE_INVALID;
2626 			return (1);
2627 		}
2628 		return (0);
2629 	}
2630 	dp->rewind_timeout = timeout;
2631 
2632 	rval = st_get_timeouts_value(un, SCMD_INQUIRY, &timeout, 0);
2633 	if (rval) {
2634 		if (rval == EACCES) {
2635 			un->un_dp->type = ST_TYPE_INVALID;
2636 			dp->type = ST_TYPE_INVALID;
2637 			return (1);
2638 		}
2639 		return (0);
2640 	}
2641 	dp->non_motion_timeout = timeout;
2642 
2643 	return (1);
2644 }
2645 
2646 static int
2647 st_get_timeouts_value(struct scsi_tape *un, uchar_t option_code,
2648     ushort_t *timeout_value, ushort_t service_action)
2649 {
2650 	uchar_t *timeouts;
2651 	uchar_t *oper;
2652 	uchar_t support;
2653 	uchar_t cdbsize;
2654 	uchar_t ctdp;
2655 	size_t buflen;
2656 	int rval;
2657 
2658 	ST_FUNC(ST_DEVINFO, st_get_timeouts_value);
2659 
2660 	buflen = sizeof (struct one_com_des) +
2661 	    sizeof (struct com_timeout_des);
2662 	oper = kmem_zalloc(buflen, KM_SLEEP);
2663 	rval = st_report_supported_operation(un, oper, option_code,
2664 	    service_action);
2665 
2666 	if (rval) {
2667 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2668 		    "st_get_timeouts_value(): "
2669 		    "fail to timeouts value for command %d.\n", option_code);
2670 		kmem_free(oper, buflen);
2671 		return (rval);
2672 	}
2673 
2674 	support = ((struct one_com_des *)oper)->support;
2675 	if ((support != SUPPORT_VALUES_SUPPORT_SCSI) &&
2676 	    (support != SUPPORT_VALUES_SUPPORT_VENDOR)) {
2677 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2678 		    "st_get_timeouts_value(): "
2679 		    "command %d is not supported.\n", option_code);
2680 		kmem_free(oper, buflen);
2681 		return (ENOTSUP);
2682 	}
2683 
2684 	ctdp = ((struct one_com_des *)oper)->ctdp;
2685 	if (!ctdp) {
2686 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2687 		    "st_get_timeouts_value(): "
2688 		    "command timeout is not included.\n");
2689 		kmem_free(oper, buflen);
2690 		return (ENOTSUP);
2691 	}
2692 
2693 	cdbsize = BE_16(((struct one_com_des *)oper)->cdb_size);
2694 	timeouts = (uchar_t *)(oper + cdbsize + 4);
2695 
2696 	/*
2697 	 * Timeout value in seconds is 4 bytes, but we only support the lower 2
2698 	 * bytes. If the higher 2 bytes are not zero, the timeout value is set
2699 	 * to 0xFFFF.
2700 	 */
2701 	if (*(timeouts + 8) != 0 || *(timeouts + 9) != 0) {
2702 		*timeout_value = USHRT_MAX;
2703 	} else {
2704 		*timeout_value = ((*(timeouts + 10)) << 8) |
2705 		    (*(timeouts + 11));
2706 	}
2707 
2708 	kmem_free(oper, buflen);
2709 	return (0);
2710 }
2711 
2712 static int
2713 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2714 {
2715 	int i;
2716 
2717 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2718 
2719 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2720 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2721 
2722 	/*
2723 	 * Make up a name
2724 	 */
2725 	bcopy("Vendor '", dp->name, 8);
2726 	bcopy(vidpid, &dp->name[8], VIDLEN);
2727 	bcopy("' Product '", &dp->name[16], 11);
2728 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2729 	dp->name[ST_NAMESIZE - 2] = '\'';
2730 	dp->name[ST_NAMESIZE - 1] = '\0';
2731 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2732 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2733 	/*
2734 	 * 'clean' vendor and product strings of non-printing chars
2735 	 */
2736 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2737 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2738 			dp->name[i] = '.';
2739 		}
2740 	}
2741 	dp->type = ST_TYPE_INVALID;
2742 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2743 
2744 	return (1); /* Can Not Fail */
2745 }
2746 
2747 /*
2748  * Regular Unix Entry points
2749  */
2750 
2751 
2752 
2753 /* ARGSUSED */
2754 static int
2755 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2756 {
2757 	dev_t dev = *dev_p;
2758 	int rval = 0;
2759 
2760 	GET_SOFT_STATE(dev);
2761 
2762 	ST_ENTR(ST_DEVINFO, st_open);
2763 
2764 	/*
2765 	 * validate that we are addressing a sensible unit
2766 	 */
2767 	mutex_enter(ST_MUTEX);
2768 
2769 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2770 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2771 	    st_dev_name(dev), *dev_p, flag, otyp);
2772 
2773 	/*
2774 	 * All device accesss go thru st_strategy() where we check
2775 	 * suspend status
2776 	 */
2777 
2778 	if (!un->un_attached) {
2779 		st_known_tape_type(un);
2780 		if (!un->un_attached) {
2781 			rval = ENXIO;
2782 			goto exit;
2783 		}
2784 
2785 	}
2786 
2787 	/*
2788 	 * Check for the case of the tape in the middle of closing.
2789 	 * This isn't simply a check of the current state, because
2790 	 * we could be in state of sensing with the previous state
2791 	 * that of closing.
2792 	 *
2793 	 * And don't allow multiple opens.
2794 	 */
2795 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2796 		un->un_laststate = un->un_state;
2797 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2798 		while (IS_CLOSING(un) ||
2799 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2800 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2801 				rval = EINTR;
2802 				un->un_state = un->un_laststate;
2803 				goto exit;
2804 			}
2805 		}
2806 	} else if (un->un_state != ST_STATE_CLOSED) {
2807 		rval = EBUSY;
2808 		goto busy;
2809 	}
2810 
2811 	/*
2812 	 * record current dev
2813 	 */
2814 	un->un_dev = dev;
2815 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2816 	un->un_errno = 0;	/* no errors yet */
2817 	un->un_restore_pos = 0;
2818 	un->un_rqs_state = 0;
2819 
2820 	/*
2821 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2822 	 * anything, leave internal states alone, if fileno >= 0
2823 	 */
2824 	if (flag & (FNDELAY | FNONBLOCK)) {
2825 		switch (un->un_pos.pmode) {
2826 
2827 		case invalid:
2828 			un->un_state = ST_STATE_OFFLINE;
2829 			break;
2830 
2831 		case legacy:
2832 			/*
2833 			 * If position is anything other than rewound.
2834 			 */
2835 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2836 				/*
2837 				 * set un_read_only/write-protect status.
2838 				 *
2839 				 * If the tape is not bot we can assume
2840 				 * that mspl->wp_status is set properly.
2841 				 * else
2842 				 * we need to do a mode sense/Tur once
2843 				 * again to get the actual tape status.(since
2844 				 * user might have replaced the tape)
2845 				 * Hence make the st state OFFLINE so that
2846 				 * we re-intialize the tape once again.
2847 				 */
2848 				un->un_read_only =
2849 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2850 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2851 			} else {
2852 				un->un_state = ST_STATE_OFFLINE;
2853 			}
2854 			break;
2855 		case logical:
2856 			if (un->un_pos.lgclblkno == 0) {
2857 				un->un_state = ST_STATE_OFFLINE;
2858 			} else {
2859 				un->un_read_only =
2860 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2861 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2862 			}
2863 			break;
2864 		}
2865 		rval = 0;
2866 	} else {
2867 		/*
2868 		 * Not opening O_NDELAY.
2869 		 */
2870 		un->un_state = ST_STATE_OPENING;
2871 
2872 		/*
2873 		 * Clear error entry stack
2874 		 */
2875 		st_empty_error_stack(un);
2876 
2877 		rval = st_tape_init(un);
2878 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2879 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2880 			rval = 0; /* so open doesn't fail */
2881 		} else if (rval) {
2882 			/*
2883 			 * Release the tape unit, if reserved and not
2884 			 * preserve reserve.
2885 			 */
2886 			if ((un->un_rsvd_status &
2887 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2888 				(void) st_reserve_release(un, ST_RELEASE,
2889 				    st_uscsi_cmd);
2890 			}
2891 		} else {
2892 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2893 		}
2894 	}
2895 
2896 exit:
2897 	/*
2898 	 * we don't want any uninvited guests scrogging our data when we're
2899 	 * busy with something, so for successful opens or failed opens
2900 	 * (except for EBUSY), reset these counters and state appropriately.
2901 	 */
2902 	if (rval != EBUSY) {
2903 		if (rval) {
2904 			un->un_state = ST_STATE_CLOSED;
2905 		}
2906 		un->un_err_resid = 0;
2907 		un->un_retry_ct = 0;
2908 	}
2909 busy:
2910 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2911 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2912 	mutex_exit(ST_MUTEX);
2913 	return (rval);
2914 
2915 }
2916 
2917 static int
2918 st_tape_init(struct scsi_tape *un)
2919 {
2920 	int err;
2921 	int rval = 0;
2922 
2923 	ST_FUNC(ST_DEVINFO, st_tape_init);
2924 
2925 	ASSERT(mutex_owned(ST_MUTEX));
2926 
2927 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2928 	    "st_tape_init(un = 0x%p, oflags = %d)\n", (void*)un, un->un_oflags);
2929 
2930 	/*
2931 	 * Clean up after any errors left by 'last' close.
2932 	 * This also handles the case of the initial open.
2933 	 */
2934 	if (un->un_state != ST_STATE_INITIALIZING) {
2935 		un->un_laststate = un->un_state;
2936 		un->un_state = ST_STATE_OPENING;
2937 	}
2938 
2939 	un->un_kbytes_xferred = 0;
2940 
2941 	/*
2942 	 * do a throw away TUR to clear check condition
2943 	 */
2944 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2945 
2946 	/*
2947 	 * If test unit ready fails because the drive is reserved
2948 	 * by another host fail the open for no access.
2949 	 */
2950 	if (err) {
2951 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2952 			un->un_state = ST_STATE_CLOSED;
2953 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2954 			    "st_tape_init: RESERVATION CONFLICT\n");
2955 			rval = EACCES;
2956 			goto exit;
2957 		} else if ((un->un_rsvd_status &
2958 		    ST_APPLICATION_RESERVATIONS) != 0) {
2959 			if ((ST_RQSENSE != NULL) &&
2960 			    (ST_RQSENSE->es_add_code == 0x2a &&
2961 			    ST_RQSENSE->es_qual_code == 0x03)) {
2962 				un->un_state = ST_STATE_CLOSED;
2963 				rval = EACCES;
2964 				goto exit;
2965 			}
2966 		}
2967 	}
2968 
2969 	/*
2970 	 * Tape self identification could fail if the tape drive is used by
2971 	 * another host during attach time. We try to get the tape type
2972 	 * again. This is also applied to any posponed configuration methods.
2973 	 */
2974 	if (un->un_dp->type == ST_TYPE_INVALID) {
2975 		un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
2976 		st_known_tape_type(un);
2977 	}
2978 
2979 	/*
2980 	 * If the tape type is still invalid, try to determine the generic
2981 	 * configuration.
2982 	 */
2983 	if (un->un_dp->type == ST_TYPE_INVALID) {
2984 		rval = st_determine_generic(un);
2985 		if (rval) {
2986 			if (rval != EACCES) {
2987 				rval = EIO;
2988 			}
2989 			un->un_state = ST_STATE_CLOSED;
2990 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2991 			    "st_tape_init: %s invalid type\n",
2992 			    rval == EACCES ? "EACCES" : "EIO");
2993 			goto exit;
2994 		}
2995 		/*
2996 		 * If this is a Unknown Type drive,
2997 		 * Use the READ BLOCK LIMITS to determine if
2998 		 * allow large xfer is approprate if not globally
2999 		 * disabled with st_allow_large_xfer.
3000 		 */
3001 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
3002 	} else {
3003 
3004 		/*
3005 		 * If we allow_large_xfer (ie >64k) and have not yet found out
3006 		 * the max block size supported by the drive,
3007 		 * find it by issueing a READ_BLKLIM command.
3008 		 * if READ_BLKLIM cmd fails, assume drive doesn't
3009 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
3010 		 */
3011 		un->un_allow_large_xfer = st_allow_large_xfer &&
3012 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
3013 	}
3014 	/*
3015 	 * if maxbsize is unknown, set the maximum block size.
3016 	 */
3017 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
3018 
3019 		/*
3020 		 * Get the Block limits of the tape drive.
3021 		 * if un->un_allow_large_xfer = 0 , then make sure
3022 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
3023 		 */
3024 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
3025 
3026 		err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3027 		if (err) {
3028 			/* Retry */
3029 			err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3030 		}
3031 		if (!err) {
3032 
3033 			/*
3034 			 * if cmd successful, use limit returned
3035 			 */
3036 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
3037 			    (un->un_rbl->max_mid << 8) +
3038 			    un->un_rbl->max_lo;
3039 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
3040 			    un->un_rbl->min_lo;
3041 			un->un_data_mod = 1 << un->un_rbl->granularity;
3042 			if ((un->un_maxbsize == 0) ||
3043 			    (un->un_allow_large_xfer == 0 &&
3044 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
3045 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3046 
3047 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
3048 				/*
3049 				 * Drive is not one that is configured, But the
3050 				 * READ BLOCK LIMITS tells us it can do large
3051 				 * xfers.
3052 				 */
3053 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
3054 					un->un_dp->options |=
3055 					    ST_NO_RECSIZE_LIMIT;
3056 				}
3057 				/*
3058 				 * If max and mimimum block limits are the
3059 				 * same this is a fixed block size device.
3060 				 */
3061 				if (un->un_maxbsize == un->un_minbsize) {
3062 					un->un_dp->options &= ~ST_VARIABLE;
3063 				}
3064 			}
3065 
3066 			if (un->un_minbsize == 0) {
3067 				un->un_minbsize = 1;
3068 			}
3069 
3070 		} else { /* error on read block limits */
3071 
3072 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3073 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
3074 			    " errno = %d un_rsvd_status = 0x%X\n",
3075 			    err, un->un_rsvd_status);
3076 
3077 			/*
3078 			 * since read block limits cmd failed,
3079 			 * do not allow large xfers.
3080 			 * use old values in st_minphys
3081 			 */
3082 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
3083 				rval = EACCES;
3084 			} else {
3085 				un->un_allow_large_xfer = 0;
3086 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3087 				    "!Disabling large transfers\n");
3088 
3089 				/*
3090 				 * we guess maxbsize and minbsize
3091 				 */
3092 				if (un->un_bsize) {
3093 					un->un_maxbsize = un->un_minbsize =
3094 					    un->un_bsize;
3095 				} else {
3096 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3097 					un->un_minbsize = 1;
3098 				}
3099 				/*
3100 				 * Data Mod must be set,
3101 				 * Even if read block limits fails.
3102 				 * Prevents Divide By Zero in st_rw().
3103 				 */
3104 				un->un_data_mod = 1;
3105 			}
3106 		}
3107 		if (un->un_rbl) {
3108 			kmem_free(un->un_rbl, RBLSIZE);
3109 			un->un_rbl = NULL;
3110 		}
3111 
3112 		if (rval) {
3113 			goto exit;
3114 		}
3115 	}
3116 
3117 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3118 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
3119 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
3120 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
3121 
3122 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
3123 
3124 	if (err != 0) {
3125 		if (err == EINTR) {
3126 			un->un_laststate = un->un_state;
3127 			un->un_state = ST_STATE_CLOSED;
3128 			rval = EINTR;
3129 			goto exit;
3130 		}
3131 		/*
3132 		 * Make sure the tape is ready
3133 		 */
3134 		un->un_pos.pmode = invalid;
3135 		if (un->un_status != KEY_UNIT_ATTENTION) {
3136 			/*
3137 			 * allow open no media.  Subsequent MTIOCSTATE
3138 			 * with media present will complete the open
3139 			 * logic.
3140 			 */
3141 			un->un_laststate = un->un_state;
3142 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
3143 				un->un_mediastate = MTIO_EJECTED;
3144 				un->un_state = ST_STATE_OFFLINE;
3145 				rval = 0;
3146 				goto exit;
3147 			} else {
3148 				un->un_state = ST_STATE_CLOSED;
3149 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3150 				    "st_tape_init EIO no media, not opened "
3151 				    "O_NONBLOCK|O_EXCL\n");
3152 				rval = EIO;
3153 				goto exit;
3154 			}
3155 		}
3156 	}
3157 
3158 	/*
3159 	 * On each open, initialize block size from drivetype struct,
3160 	 * as it could have been changed by MTSRSZ ioctl.
3161 	 * Now, ST_VARIABLE simply means drive is capable of variable
3162 	 * mode. All drives are assumed to support fixed records.
3163 	 * Hence, un_bsize tells what mode the drive is in.
3164 	 *	un_bsize	= 0	- variable record length
3165 	 *			= x	- fixed record length is x
3166 	 */
3167 	un->un_bsize = un->un_dp->bsize;
3168 
3169 	/*
3170 	 * If saved position is valid go there
3171 	 */
3172 	if (un->un_restore_pos) {
3173 		un->un_restore_pos = 0;
3174 		un->un_pos.fileno = un->un_save_fileno;
3175 		un->un_pos.blkno = un->un_save_blkno;
3176 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &un->un_pos);
3177 		if (rval != 0) {
3178 			if (rval != EACCES) {
3179 				rval = EIO;
3180 			}
3181 			un->un_laststate = un->un_state;
3182 			un->un_state = ST_STATE_CLOSED;
3183 			goto exit;
3184 		}
3185 	}
3186 
3187 	if (un->un_pos.pmode == invalid) {
3188 		rval = st_loadtape(un);
3189 		if (rval) {
3190 			if (rval != EACCES) {
3191 				rval = EIO;
3192 			}
3193 			un->un_laststate = un->un_state;
3194 			un->un_state = ST_STATE_CLOSED;
3195 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3196 			    "st_tape_init: %s can't open tape\n",
3197 			    rval == EACCES ? "EACCES" : "EIO");
3198 			goto exit;
3199 		}
3200 	}
3201 
3202 	/*
3203 	 * do a mode sense to pick up state of current write-protect,
3204 	 * Could cause reserve and fail due to conflict.
3205 	 */
3206 	if (un->un_unit_attention_flags) {
3207 		rval = st_modesense(un);
3208 		if (rval == EACCES) {
3209 			goto exit;
3210 		}
3211 	}
3212 
3213 	/*
3214 	 * If we are opening the tape for writing, check
3215 	 * to make sure that the tape can be written.
3216 	 */
3217 	if (un->un_oflags & FWRITE) {
3218 		err = 0;
3219 		if (un->un_mspl->wp) {
3220 			un->un_status = KEY_WRITE_PROTECT;
3221 			un->un_laststate = un->un_state;
3222 			un->un_state = ST_STATE_CLOSED;
3223 			rval = EACCES;
3224 			/*
3225 			 * STK sets the wp bit if volsafe tape is loaded.
3226 			 */
3227 			if ((un->un_dp->type == MT_ISSTK9840) &&
3228 			    (un->un_dp->options & ST_WORMABLE)) {
3229 				un->un_read_only = RDONLY;
3230 			} else {
3231 				goto exit;
3232 			}
3233 		} else {
3234 			un->un_read_only = RDWR;
3235 		}
3236 	} else {
3237 		un->un_read_only = RDONLY;
3238 	}
3239 
3240 	if (un->un_dp->options & ST_WORMABLE &&
3241 	    un->un_unit_attention_flags) {
3242 		un->un_read_only |= un->un_wormable(un);
3243 
3244 		if (((un->un_read_only == WORM) ||
3245 		    (un->un_read_only == RDWORM)) &&
3246 		    ((un->un_oflags & FWRITE) == FWRITE)) {
3247 			un->un_status = KEY_DATA_PROTECT;
3248 			rval = EACCES;
3249 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3250 			    "read_only = %d eof = %d oflag = %d\n",
3251 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3252 		}
3253 	}
3254 
3255 	/*
3256 	 * If we're opening the tape write-only, we need to
3257 	 * write 2 filemarks on the HP 1/2 inch drive, to
3258 	 * create a null file.
3259 	 */
3260 	if ((un->un_read_only == RDWR) ||
3261 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3262 		if (un->un_dp->options & ST_REEL) {
3263 			un->un_fmneeded = 2;
3264 		} else {
3265 			un->un_fmneeded = 1;
3266 		}
3267 	} else {
3268 		un->un_fmneeded = 0;
3269 	}
3270 
3271 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3272 	    "fmneeded = %x\n", un->un_fmneeded);
3273 
3274 	/*
3275 	 * Make sure the density can be selected correctly.
3276 	 * If WORM can only write at the append point which in most cases
3277 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3278 	 * to set and try densities if a BOP.
3279 	 */
3280 	if (st_determine_density(un,
3281 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3282 		un->un_status = KEY_ILLEGAL_REQUEST;
3283 		un->un_laststate = un->un_state;
3284 		un->un_state = ST_STATE_CLOSED;
3285 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3286 		    "st_tape_init: EIO can't determine density\n");
3287 		rval = EIO;
3288 		goto exit;
3289 	}
3290 
3291 	/*
3292 	 * Destroy the knowledge that we have 'determined'
3293 	 * density so that a later read at BOT comes along
3294 	 * does the right density determination.
3295 	 */
3296 
3297 	un->un_density_known = 0;
3298 
3299 
3300 	/*
3301 	 * Okay, the tape is loaded and either at BOT or somewhere past.
3302 	 * Mark the state such that any I/O or tape space operations
3303 	 * will get/set the right density, etc..
3304 	 */
3305 	un->un_laststate = un->un_state;
3306 	un->un_lastop = ST_OP_NIL;
3307 	un->un_mediastate = MTIO_INSERTED;
3308 	cv_broadcast(&un->un_state_cv);
3309 
3310 	/*
3311 	 *  Set test append flag if writing.
3312 	 *  First write must check that tape is positioned correctly.
3313 	 */
3314 	un->un_test_append = (un->un_oflags & FWRITE);
3315 
3316 	/*
3317 	 * if there are pending unit attention flags.
3318 	 * Check that the media has not changed.
3319 	 */
3320 	if (un->un_unit_attention_flags) {
3321 		rval = st_get_media_identification(un, st_uscsi_cmd);
3322 		if (rval != 0 && rval != EACCES) {
3323 			rval = EIO;
3324 		}
3325 		un->un_unit_attention_flags = 0;
3326 	}
3327 
3328 exit:
3329 	un->un_err_resid = 0;
3330 	un->un_last_resid = 0;
3331 	un->un_last_count = 0;
3332 
3333 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3334 	    "st_tape_init: return val = %x\n", rval);
3335 	return (rval);
3336 
3337 }
3338 
3339 
3340 
3341 /* ARGSUSED */
3342 static int
3343 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3344 {
3345 	int err = 0;
3346 	int count, last_state;
3347 	minor_t minor = getminor(dev);
3348 #ifdef	__x86
3349 	struct contig_mem *cp, *cp_temp;
3350 #endif
3351 
3352 	GET_SOFT_STATE(dev);
3353 
3354 	ST_ENTR(ST_DEVINFO, st_close);
3355 
3356 	/*
3357 	 * wait till all cmds in the pipeline have been completed
3358 	 */
3359 	mutex_enter(ST_MUTEX);
3360 
3361 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3362 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3363 
3364 	st_wait_for_io(un);
3365 
3366 	/* turn off persistent errors on close, as we want close to succeed */
3367 	st_turn_pe_off(un);
3368 
3369 	/*
3370 	 * set state to indicate that we are in process of closing
3371 	 */
3372 	last_state = un->un_laststate = un->un_state;
3373 	un->un_state = ST_STATE_CLOSING;
3374 
3375 	ST_POS(ST_DEVINFO, "st_close1:", &un->un_pos);
3376 
3377 	/*
3378 	 * BSD behavior:
3379 	 * a close always causes a silent span to the next file if we've hit
3380 	 * an EOF (but not yet read across it).
3381 	 */
3382 	if ((minor & MT_BSD) && (un->un_pos.eof == ST_EOF)) {
3383 		if (un->un_pos.pmode != invalid) {
3384 			un->un_pos.fileno++;
3385 			un->un_pos.blkno = 0;
3386 		}
3387 		un->un_pos.eof = ST_NO_EOF;
3388 	}
3389 
3390 	/*
3391 	 * SVR4 behavior for skipping to next file:
3392 	 *
3393 	 * If we have not seen a filemark, space to the next file
3394 	 *
3395 	 * If we have already seen the filemark we are physically in the next
3396 	 * file and we only increment the filenumber
3397 	 */
3398 	if (((minor & (MT_BSD | MT_NOREWIND)) == MT_NOREWIND) &&
3399 	    (flag & FREAD) &&		/* reading or at least asked to */
3400 	    (un->un_mediastate == MTIO_INSERTED) &&	/* tape loaded */
3401 	    (un->un_pos.pmode != invalid) &&		/* XXX position known */
3402 	    ((un->un_pos.blkno != 0) && 		/* inside a file */
3403 	    (un->un_lastop != ST_OP_WRITE) &&		/* Didn't just write */
3404 	    (un->un_lastop != ST_OP_WEOF))) {		/* or write filemarks */
3405 		switch (un->un_pos.eof) {
3406 		case ST_NO_EOF:
3407 			/*
3408 			 * if we were reading and did not read the complete file
3409 			 * skip to the next file, leaving the tape correctly
3410 			 * positioned to read the first record of the next file
3411 			 * Check first for REEL if we are at EOT by trying to
3412 			 * read a block
3413 			 */
3414 			if ((un->un_dp->options & ST_REEL) &&
3415 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3416 			    (un->un_pos.blkno == 0)) {
3417 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3418 					ST_DEBUG2(ST_DEVINFO, st_label,
3419 					    SCSI_DEBUG,
3420 					    "st_close : EIO can't space\n");
3421 					err = EIO;
3422 					goto error_out;
3423 				}
3424 				if (un->un_pos.eof >= ST_EOF_PENDING) {
3425 					un->un_pos.eof = ST_EOT_PENDING;
3426 					un->un_pos.fileno += 1;
3427 					un->un_pos.blkno   = 0;
3428 					break;
3429 				}
3430 			}
3431 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3432 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3433 				    "st_close: EIO can't space #2\n");
3434 				err = EIO;
3435 				goto error_out;
3436 			} else {
3437 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3438 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3439 				    un->un_pos.fileno, un->un_pos.blkno,
3440 				    un->un_pos.eof);
3441 				un->un_pos.eof = ST_NO_EOF;
3442 			}
3443 			break;
3444 
3445 		case ST_EOF_PENDING:
3446 		case ST_EOF:
3447 			un->un_pos.fileno += 1;
3448 			un->un_pos.lgclblkno += 1;
3449 			un->un_pos.blkno   = 0;
3450 			un->un_pos.eof = ST_NO_EOF;
3451 			break;
3452 
3453 		case ST_EOT:
3454 		case ST_EOT_PENDING:
3455 		case ST_EOM:
3456 			/* nothing to do */
3457 			break;
3458 		default:
3459 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
3460 			    "Undefined state 0x%x", un->un_pos.eof);
3461 
3462 		}
3463 	}
3464 
3465 
3466 	/*
3467 	 * For performance reasons (HP 88780), the driver should
3468 	 * postpone writing the second tape mark until just before a file
3469 	 * positioning ioctl is issued (e.g., rewind).	This means that
3470 	 * the user must not manually rewind the tape because the tape will
3471 	 * be missing the second tape mark which marks EOM.
3472 	 * However, this small performance improvement is not worth the risk.
3473 	 */
3474 
3475 	/*
3476 	 * We need to back up over the filemark we inadvertently popped
3477 	 * over doing a read in between the two filemarks that constitute
3478 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3479 	 * set while reading.
3480 	 *
3481 	 * If we happen to be at physical eot (ST_EOM) (writing case),
3482 	 * the writing of filemark(s) will clear the ST_EOM state, which
3483 	 * we don't want, so we save this state and restore it later.
3484 	 */
3485 
3486 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3487 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3488 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3489 
3490 	if (un->un_pos.eof == ST_EOT_PENDING) {
3491 		if (minor & MT_NOREWIND) {
3492 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3493 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3494 				    "st_close: EIO can't space #3\n");
3495 				err = EIO;
3496 				goto error_out;
3497 			} else {
3498 				un->un_pos.blkno = 0;
3499 				un->un_pos.eof = ST_EOT;
3500 			}
3501 		} else {
3502 			un->un_pos.eof = ST_NO_EOF;
3503 		}
3504 
3505 	/*
3506 	 * Do we need to write a file mark?
3507 	 *
3508 	 * only write filemarks if there are fmks to be written and
3509 	 *   - open for write (possibly read/write)
3510 	 *   - the last operation was a write
3511 	 * or:
3512 	 *   -	opened for wronly
3513 	 *   -	no data was written
3514 	 */
3515 	} else if ((un->un_pos.pmode != invalid) &&
3516 	    (un->un_fmneeded > 0) &&
3517 	    (((flag & FWRITE) &&
3518 	    ((un->un_lastop == ST_OP_WRITE)||(un->un_lastop == ST_OP_WEOF))) ||
3519 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3520 
3521 		/* save ST_EOM state */
3522 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3523 
3524 		/*
3525 		 * Note that we will write a filemark if we had opened
3526 		 * the tape write only and no data was written, thus
3527 		 * creating a null file.
3528 		 *
3529 		 * If the user already wrote one, we only have to write 1 more.
3530 		 * If they wrote two, we don't have to write any.
3531 		 */
3532 
3533 		count = un->un_fmneeded;
3534 		if (count > 0) {
3535 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, count, SYNC_CMD)) {
3536 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3537 				    "st_close : EIO can't wfm\n");
3538 				err = EIO;
3539 				goto error_out;
3540 			}
3541 			if ((un->un_dp->options & ST_REEL) &&
3542 			    (minor & MT_NOREWIND)) {
3543 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3544 					ST_DEBUG2(ST_DEVINFO, st_label,
3545 					    SCSI_DEBUG,
3546 					    "st_close : EIO space fmk(-1)\n");
3547 					err = EIO;
3548 					goto error_out;
3549 				}
3550 				un->un_pos.eof = ST_NO_EOF;
3551 				/* fix up block number */
3552 				un->un_pos.blkno = 0;
3553 			}
3554 		}
3555 
3556 		/*
3557 		 * If we aren't going to be rewinding, and we were at
3558 		 * physical eot, restore the state that indicates we
3559 		 * are at physical eot. Once you have reached physical
3560 		 * eot, and you close the tape, the only thing you can
3561 		 * do on the next open is to rewind. Access to trailer
3562 		 * records is only allowed without closing the device.
3563 		 */
3564 		if ((minor & MT_NOREWIND) == 0 && was_at_eom) {
3565 			un->un_pos.eof = ST_EOM;
3566 		}
3567 	}
3568 
3569 	/*
3570 	 * report soft errors if enabled and available, if we never accessed
3571 	 * the drive, don't get errors. This will prevent some DAT error
3572 	 * messages upon LOG SENSE.
3573 	 */
3574 	if (st_report_soft_errors_on_close &&
3575 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3576 	    (last_state != ST_STATE_OFFLINE)) {
3577 		if (st_report_soft_errors(dev, flag)) {
3578 			err = EIO;
3579 			goto error_out;
3580 		}
3581 	}
3582 
3583 
3584 	/*
3585 	 * Do we need to rewind? Can we rewind?
3586 	 */
3587 	if ((minor & MT_NOREWIND) == 0 &&
3588 	    un->un_pos.pmode != invalid && err == 0) {
3589 		/*
3590 		 * We'd like to rewind with the
3591 		 * 'immediate' bit set, but this
3592 		 * causes problems on some drives
3593 		 * where subsequent opens get a
3594 		 * 'NOT READY' error condition
3595 		 * back while the tape is rewinding,
3596 		 * which is impossible to distinguish
3597 		 * from the condition of 'no tape loaded'.
3598 		 *
3599 		 * Also, for some targets, if you disconnect
3600 		 * with the 'immediate' bit set, you don't
3601 		 * actually return right away, i.e., the
3602 		 * target ignores your request for immediate
3603 		 * return.
3604 		 *
3605 		 * Instead, we'll fire off an async rewind
3606 		 * command. We'll mark the device as closed,
3607 		 * and any subsequent open will stall on
3608 		 * the first TEST_UNIT_READY until the rewind
3609 		 * completes.
3610 		 */
3611 
3612 		/*
3613 		 * Used to be if reserve was not supported we'd send an
3614 		 * asynchronious rewind. Comments above may be slightly invalid
3615 		 * as the immediate bit was never set. Doing an immedate rewind
3616 		 * makes sense, I think fixes to not ready status might handle
3617 		 * the problems described above.
3618 		 */
3619 		if (un->un_sd->sd_inq->inq_ansi < 2) {
3620 			if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
3621 				err = EIO;
3622 			}
3623 		} else {
3624 			/* flush data for older drives per scsi spec. */
3625 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD)) {
3626 				err = EIO;
3627 			} else {
3628 				/* release the drive before rewind immediate */
3629 				if ((un->un_rsvd_status &
3630 				    (ST_RESERVE | ST_PRESERVE_RESERVE)) ==
3631 				    ST_RESERVE) {
3632 					if (st_reserve_release(un, ST_RELEASE,
3633 					    st_uscsi_cmd)) {
3634 						err = EIO;
3635 					}
3636 				}
3637 
3638 				/* send rewind with immediate bit set */
3639 				if (st_cmd(un, SCMD_REWIND, 1, ASYNC_CMD)) {
3640 					err = EIO;
3641 				}
3642 			}
3643 		}
3644 		/*
3645 		 * Setting positions invalid in case the rewind doesn't
3646 		 * happen. Drives don't like to rewind if resets happen
3647 		 * they will tend to move back to where the rewind was
3648 		 * issued if a reset or something happens so that if a
3649 		 * write happens the data doesn't get clobbered.
3650 		 *
3651 		 * Not a big deal if the position is invalid when the
3652 		 * open occures it will do a read position.
3653 		 */
3654 		un->un_pos.pmode = invalid;
3655 		un->un_running.pmode = invalid;
3656 
3657 		if (err == EIO) {
3658 			goto error_out;
3659 		}
3660 	}
3661 
3662 	/*
3663 	 * eject tape if necessary
3664 	 */
3665 	if (un->un_eject_tape_on_failure) {
3666 		un->un_eject_tape_on_failure = 0;
3667 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3668 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3669 			    "st_close : can't unload tape\n");
3670 			err = EIO;
3671 			goto error_out;
3672 		} else {
3673 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3674 			    "st_close : tape unloaded \n");
3675 			un->un_pos.eof = ST_NO_EOF;
3676 			un->un_mediastate = MTIO_EJECTED;
3677 		}
3678 	}
3679 	/*
3680 	 * Release the tape unit, if default reserve/release
3681 	 * behaviour.
3682 	 */
3683 	if ((un->un_rsvd_status &
3684 	    (ST_RESERVE | ST_PRESERVE_RESERVE |
3685 	    ST_APPLICATION_RESERVATIONS)) == ST_RESERVE) {
3686 		(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
3687 	}
3688 error_out:
3689 	/*
3690 	 * clear up state
3691 	 */
3692 	un->un_laststate = un->un_state;
3693 	un->un_state = ST_STATE_CLOSED;
3694 	un->un_lastop = ST_OP_NIL;
3695 	un->un_throttle = 1;	/* assume one request at time, for now */
3696 	un->un_retry_ct = 0;
3697 	un->un_errno = 0;
3698 	un->un_swr_token = (opaque_t)NULL;
3699 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3700 
3701 	/* Restore the options to the init time settings */
3702 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3703 		un->un_dp->options |= ST_READ_IGNORE_ILI;
3704 	} else {
3705 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3706 	}
3707 
3708 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3709 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3710 	} else {
3711 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3712 	}
3713 
3714 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3715 		un->un_dp->options |= ST_SHORT_FILEMARKS;
3716 	} else {
3717 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3718 	}
3719 
3720 	ASSERT(mutex_owned(ST_MUTEX));
3721 
3722 	/*
3723 	 * Signal anyone awaiting a close operation to complete.
3724 	 */
3725 	cv_signal(&un->un_clscv);
3726 
3727 	/*
3728 	 * any kind of error on closing causes all state to be tossed
3729 	 */
3730 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3731 		/*
3732 		 * note that st_intr has already set
3733 		 * un_pos.pmode to invalid.
3734 		 */
3735 		un->un_density_known = 0;
3736 	}
3737 
3738 #ifdef	__x86
3739 	/*
3740 	 * free any contiguous mem alloc'ed for big block I/O
3741 	 */
3742 	cp = un->un_contig_mem;
3743 	while (cp) {
3744 		if (cp->cm_addr) {
3745 			ddi_dma_mem_free(&cp->cm_acc_hdl);
3746 		}
3747 		cp_temp = cp;
3748 		cp = cp->cm_next;
3749 		kmem_free(cp_temp,
3750 		    sizeof (struct contig_mem) + biosize());
3751 	}
3752 	un->un_contig_mem_total_num = 0;
3753 	un->un_contig_mem_available_num = 0;
3754 	un->un_contig_mem = NULL;
3755 	un->un_max_contig_mem_len = 0;
3756 #endif
3757 
3758 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3759 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3760 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3761 
3762 	mutex_exit(ST_MUTEX);
3763 	return (err);
3764 }
3765 
3766 /*
3767  * These routines perform raw i/o operations.
3768  */
3769 
3770 /* ARGSUSED2 */
3771 static int
3772 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3773 {
3774 #ifdef STDEBUG
3775 	GET_SOFT_STATE(dev);
3776 	ST_ENTR(ST_DEVINFO, st_aread);
3777 #endif
3778 	return (st_arw(dev, aio, B_READ));
3779 }
3780 
3781 
3782 /* ARGSUSED2 */
3783 static int
3784 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3785 {
3786 #ifdef STDEBUG
3787 	GET_SOFT_STATE(dev);
3788 	ST_ENTR(ST_DEVINFO, st_awrite);
3789 #endif
3790 	return (st_arw(dev, aio, B_WRITE));
3791 }
3792 
3793 
3794 
3795 /* ARGSUSED */
3796 static int
3797 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3798 {
3799 #ifdef STDEBUG
3800 	GET_SOFT_STATE(dev);
3801 	ST_ENTR(ST_DEVINFO, st_read);
3802 #endif
3803 	return (st_rw(dev, uiop, B_READ));
3804 }
3805 
3806 /* ARGSUSED */
3807 static int
3808 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3809 {
3810 #ifdef STDEBUG
3811 	GET_SOFT_STATE(dev);
3812 	ST_ENTR(ST_DEVINFO, st_write);
3813 #endif
3814 	return (st_rw(dev, uiop, B_WRITE));
3815 }
3816 
3817 /*
3818  * Due to historical reasons, old limits are: For variable-length devices:
3819  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3820  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3821  * (let it through unmodified. For fixed-length record devices:
3822  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3823  *
3824  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3825  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3826  * command to the drive).
3827  *
3828  */
3829 static void
3830 st_minphys(struct buf *bp)
3831 {
3832 	struct scsi_tape *un;
3833 
3834 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3835 
3836 	ST_FUNC(ST_DEVINFO, st_minphys);
3837 
3838 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3839 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3840 	    bp->b_bcount);
3841 
3842 	if (un->un_allow_large_xfer) {
3843 
3844 		/*
3845 		 * check un_maxbsize for variable length devices only
3846 		 */
3847 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3848 			bp->b_bcount = un->un_maxbsize;
3849 		}
3850 		/*
3851 		 * can't go more that HBA maxdma limit in either fixed-length
3852 		 * or variable-length tape drives.
3853 		 */
3854 		if (bp->b_bcount > un->un_maxdma) {
3855 			bp->b_bcount = un->un_maxdma;
3856 		}
3857 	} else {
3858 
3859 		/*
3860 		 *  use old fixed limits
3861 		 */
3862 		if (un->un_bsize == 0) {
3863 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3864 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3865 			}
3866 		} else {
3867 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3868 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3869 			}
3870 		}
3871 	}
3872 
3873 	/*
3874 	 * For regular raw I/O and Fixed Block length devices, make sure
3875 	 * the adjusted block count is a whole multiple of the device
3876 	 * block size.
3877 	 */
3878 	if (bp != un->un_sbufp && un->un_bsize) {
3879 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3880 	}
3881 }
3882 
3883 static int
3884 st_rw(dev_t dev, struct uio *uio, int flag)
3885 {
3886 	int rval = 0;
3887 	long len;
3888 
3889 	GET_SOFT_STATE(dev);
3890 
3891 	ST_FUNC(ST_DEVINFO, st_rw);
3892 
3893 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3894 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3895 	    (flag == B_READ ? rd_str: wr_str));
3896 
3897 	/* get local copy of transfer length */
3898 	len = uio->uio_iov->iov_len;
3899 
3900 	mutex_enter(ST_MUTEX);
3901 
3902 	/*
3903 	 * Clear error entry stack
3904 	 */
3905 	st_empty_error_stack(un);
3906 
3907 	/*
3908 	 * If in fixed block size mode and requested read or write
3909 	 * is not an even multiple of that block size.
3910 	 */
3911 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3912 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3913 		    "%s: not modulo %d block size\n",
3914 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3915 		rval = EINVAL;
3916 	}
3917 
3918 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3919 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3920 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3921 		    "%s: not modulo %d device granularity\n",
3922 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3923 		rval = EINVAL;
3924 	}
3925 
3926 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
3927 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
3928 		rval = EFAULT;
3929 	}
3930 
3931 	if (rval != 0) {
3932 		un->un_errno = rval;
3933 		mutex_exit(ST_MUTEX);
3934 		return (rval);
3935 	}
3936 
3937 	/*
3938 	 * Reset this so it can be set if Berkeley and read over a filemark.
3939 	 */
3940 	un->un_silent_skip = 0;
3941 	mutex_exit(ST_MUTEX);
3942 
3943 	len = uio->uio_resid;
3944 
3945 	rval = physio(st_queued_strategy, (struct buf *)NULL,
3946 	    dev, flag, st_minphys, uio);
3947 	/*
3948 	 * if we have hit logical EOT during this xfer and there is not a
3949 	 * full residue, then set eof back  to ST_EOM to make sure that
3950 	 * the user will see at least one zero write
3951 	 * after this short write
3952 	 */
3953 	mutex_enter(ST_MUTEX);
3954 	if (un->un_pos.eof > ST_NO_EOF) {
3955 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3956 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3957 	}
3958 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3959 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3960 			un->un_pos.eof = ST_EOM;
3961 		} else if (uio->uio_resid == len) {
3962 			un->un_pos.eof = ST_NO_EOF;
3963 		}
3964 	}
3965 
3966 	if (un->un_silent_skip && uio->uio_resid != len) {
3967 		un->un_pos.eof = ST_EOF;
3968 		un->un_pos.blkno = un->un_save_blkno;
3969 		un->un_pos.fileno--;
3970 	}
3971 
3972 	un->un_errno = rval;
3973 
3974 	mutex_exit(ST_MUTEX);
3975 
3976 	return (rval);
3977 }
3978 
3979 static int
3980 st_arw(dev_t dev, struct aio_req *aio, int flag)
3981 {
3982 	struct uio *uio = aio->aio_uio;
3983 	int rval = 0;
3984 	long len;
3985 
3986 	GET_SOFT_STATE(dev);
3987 
3988 	ST_FUNC(ST_DEVINFO, st_arw);
3989 
3990 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3991 	    "st_arw(dev = 0x%lx, flag = %s)\n", dev,
3992 	    (flag == B_READ ? rd_str: wr_str));
3993 
3994 	/* get local copy of transfer length */
3995 	len = uio->uio_iov->iov_len;
3996 
3997 	mutex_enter(ST_MUTEX);
3998 
3999 	/*
4000 	 * If in fixed block size mode and requested read or write
4001 	 * is not an even multiple of that block size.
4002 	 */
4003 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
4004 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4005 		    "%s: not modulo %d block size\n",
4006 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
4007 		rval = EINVAL;
4008 	}
4009 
4010 	/* If device has set granularity in the READ_BLKLIM we honor it. */
4011 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
4012 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4013 		    "%s: not modulo %d device granularity\n",
4014 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
4015 		rval = EINVAL;
4016 	}
4017 
4018 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
4019 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
4020 		rval = EFAULT;
4021 	}
4022 
4023 	if (rval != 0) {
4024 		un->un_errno = rval;
4025 		mutex_exit(ST_MUTEX);
4026 		return (rval);
4027 	}
4028 
4029 	mutex_exit(ST_MUTEX);
4030 
4031 	len = uio->uio_resid;
4032 
4033 	rval =
4034 	    aphysio(st_queued_strategy, anocancel, dev, flag, st_minphys, aio);
4035 
4036 	/*
4037 	 * if we have hit logical EOT during this xfer and there is not a
4038 	 * full residue, then set eof back  to ST_EOM to make sure that
4039 	 * the user will see at least one zero write
4040 	 * after this short write
4041 	 *
4042 	 * we keep this here just in case the application is not using
4043 	 * persistent errors
4044 	 */
4045 	mutex_enter(ST_MUTEX);
4046 	if (un->un_pos.eof > ST_NO_EOF) {
4047 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4048 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
4049 	}
4050 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
4051 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
4052 			un->un_pos.eof = ST_EOM;
4053 		} else if (uio->uio_resid == len &&
4054 		    !(un->un_persistence && un->un_persist_errors)) {
4055 			un->un_pos.eof = ST_NO_EOF;
4056 		}
4057 	}
4058 	un->un_errno = rval;
4059 	mutex_exit(ST_MUTEX);
4060 
4061 	return (rval);
4062 }
4063 
4064 
4065 
4066 static int
4067 st_queued_strategy(buf_t *bp)
4068 {
4069 	struct scsi_tape *un;
4070 	char reading = bp->b_flags & B_READ;
4071 	int wasopening = 0;
4072 
4073 	/*
4074 	 * validate arguments
4075 	 */
4076 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4077 	if (un == NULL) {
4078 		bp->b_resid = bp->b_bcount;
4079 		bioerror(bp, ENXIO);
4080 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4081 		    "st_queued_strategy: ENXIO error exit\n");
4082 		biodone(bp);
4083 		return (0);
4084 	}
4085 
4086 	ST_ENTR(ST_DEVINFO, st_queued_strategy);
4087 
4088 	mutex_enter(ST_MUTEX);
4089 
4090 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4091 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4092 	}
4093 
4094 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4095 	    "st_queued_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4096 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4097 
4098 	/*
4099 	 * If persistent errors have been flagged, just nix this one. We wait
4100 	 * for any outstanding I/O's below, so we will be in order.
4101 	 */
4102 	if (un->un_persistence && un->un_persist_errors) {
4103 		goto exit;
4104 	}
4105 
4106 	/*
4107 	 * If last command was non queued, wait till it finishes.
4108 	 */
4109 	while (un->un_sbuf_busy) {
4110 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
4111 		/* woke up because of an error */
4112 		if (un->un_persistence && un->un_persist_errors) {
4113 			goto exit;
4114 		}
4115 	}
4116 
4117 	/*
4118 	 * s_buf and recovery commands shouldn't come here.
4119 	 */
4120 	ASSERT(bp != un->un_recov_buf);
4121 	ASSERT(bp != un->un_sbufp);
4122 
4123 	/*
4124 	 * If we haven't done/checked reservation on the tape unit
4125 	 * do it now.
4126 	 */
4127 	if ((un->un_rsvd_status &
4128 	    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
4129 		if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
4130 			if (st_reserve_release(un, ST_RESERVE, st_uscsi_cmd)) {
4131 				st_bioerror(bp, un->un_errno);
4132 				goto exit;
4133 			}
4134 		} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4135 			/*
4136 			 * Enter here to restore position for possible
4137 			 * resets when the device was closed and opened
4138 			 * in O_NDELAY mode subsequently
4139 			 */
4140 			un->un_state = ST_STATE_INITIALIZING;
4141 			(void) st_cmd(un, SCMD_TEST_UNIT_READY,
4142 			    0, SYNC_CMD);
4143 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4144 		}
4145 		un->un_rsvd_status |= ST_INIT_RESERVE;
4146 	}
4147 
4148 	/*
4149 	 * If we are offline, we have to initialize everything first.
4150 	 * This is to handle either when opened with O_NDELAY, or
4151 	 * we just got a new tape in the drive, after an offline.
4152 	 * We don't observe O_NDELAY past the open,
4153 	 * as it will not make sense for tapes.
4154 	 */
4155 	if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
4156 		/*
4157 		 * reset state to avoid recursion
4158 		 */
4159 		un->un_laststate = un->un_state;
4160 		un->un_state = ST_STATE_INITIALIZING;
4161 		if (st_tape_init(un)) {
4162 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4163 			    "stioctl : OFFLINE init failure ");
4164 			un->un_state = ST_STATE_OFFLINE;
4165 			un->un_pos.pmode = invalid;
4166 			goto b_done_err;
4167 		}
4168 		/* un_restore_pos make invalid */
4169 		un->un_state = ST_STATE_OPEN_PENDING_IO;
4170 		un->un_restore_pos = 0;
4171 	}
4172 	/*
4173 	 * Check for legal operations
4174 	 */
4175 	if (un->un_pos.pmode == invalid) {
4176 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4177 		    "strategy with un->un_pos.pmode invalid\n");
4178 		goto b_done_err;
4179 	}
4180 
4181 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4182 	    "st_queued_strategy(): regular io\n");
4183 
4184 	/*
4185 	 * Process this first. If we were reading, and we're pending
4186 	 * logical eot, that means we've bumped one file mark too far.
4187 	 */
4188 
4189 	/*
4190 	 * Recursion warning: st_cmd will route back through here.
4191 	 * Not anymore st_cmd will go through st_strategy()!
4192 	 */
4193 	if (un->un_pos.eof == ST_EOT_PENDING) {
4194 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4195 			un->un_pos.pmode = invalid;
4196 			un->un_density_known = 0;
4197 			goto b_done_err;
4198 		}
4199 		un->un_pos.blkno = 0; /* fix up block number.. */
4200 		un->un_pos.eof = ST_EOT;
4201 	}
4202 
4203 	/*
4204 	 * If we are in the process of opening, we may have to
4205 	 * determine/set the correct density. We also may have
4206 	 * to do a test_append (if QIC) to see whether we are
4207 	 * in a position to append to the end of the tape.
4208 	 *
4209 	 * If we're already at logical eot, we transition
4210 	 * to ST_NO_EOF. If we're at physical eot, we punt
4211 	 * to the switch statement below to handle.
4212 	 */
4213 	if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
4214 	    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
4215 
4216 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4217 			if (st_determine_density(un, (int)reading)) {
4218 				goto b_done_err;
4219 			}
4220 		}
4221 
4222 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4223 		    "pending_io@fileno %d rw %d qic %d eof %d\n",
4224 		    un->un_pos.fileno, (int)reading,
4225 		    (un->un_dp->options & ST_QIC) ? 1 : 0,
4226 		    un->un_pos.eof);
4227 
4228 		if (!reading && un->un_pos.eof != ST_EOM) {
4229 			if (un->un_pos.eof == ST_EOT) {
4230 				un->un_pos.eof = ST_NO_EOF;
4231 			} else if (un->un_pos.pmode != invalid &&
4232 			    (un->un_dp->options & ST_QIC)) {
4233 				/*
4234 				 * st_test_append() will do it all
4235 				 */
4236 				st_test_append(bp);
4237 				mutex_exit(ST_MUTEX);
4238 				return (0);
4239 			}
4240 		}
4241 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4242 			wasopening = 1;
4243 		}
4244 		un->un_laststate = un->un_state;
4245 		un->un_state = ST_STATE_OPEN;
4246 	}
4247 
4248 
4249 	/*
4250 	 * Process rest of END OF FILE and END OF TAPE conditions
4251 	 */
4252 
4253 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4254 	    "eof=%x, wasopening=%x\n",
4255 	    un->un_pos.eof, wasopening);
4256 
4257 	switch (un->un_pos.eof) {
4258 	case ST_EOM:
4259 		/*
4260 		 * This allows writes to proceed past physical
4261 		 * eot. We'll *really* be in trouble if the
4262 		 * user continues blindly writing data too
4263 		 * much past this point (unwind the tape).
4264 		 * Physical eot really means 'early warning
4265 		 * eot' in this context.
4266 		 *
4267 		 * Every other write from now on will succeed
4268 		 * (if sufficient  tape left).
4269 		 * This write will return with resid == count
4270 		 * but the next one should be successful
4271 		 *
4272 		 * Note that we only transition to logical EOT
4273 		 * if the last state wasn't the OPENING state.
4274 		 * We explicitly prohibit running up to physical
4275 		 * eot, closing the device, and then re-opening
4276 		 * to proceed. Trailer records may only be gotten
4277 		 * at by keeping the tape open after hitting eot.
4278 		 *
4279 		 * Also note that ST_EOM cannot be set by reading-
4280 		 * this can only be set during writing. Reading
4281 		 * up to the end of the tape gets a blank check
4282 		 * or a double-filemark indication (ST_EOT_PENDING),
4283 		 * and we prohibit reading after that point.
4284 		 *
4285 		 */
4286 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
4287 		if (wasopening == 0) {
4288 			/*
4289 			 * this allows st_rw() to reset it back to
4290 			 * will see a zero write
4291 			 */
4292 			un->un_pos.eof = ST_WRITE_AFTER_EOM;
4293 		}
4294 		un->un_status = SUN_KEY_EOT;
4295 		goto b_done;
4296 
4297 	case ST_WRITE_AFTER_EOM:
4298 	case ST_EOT:
4299 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
4300 		un->un_status = SUN_KEY_EOT;
4301 		if (SVR4_BEHAVIOR && reading) {
4302 			goto b_done_err;
4303 		}
4304 
4305 		if (reading) {
4306 			goto b_done;
4307 		}
4308 		un->un_pos.eof = ST_NO_EOF;
4309 		break;
4310 
4311 	case ST_EOF_PENDING:
4312 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4313 		    "EOF PENDING\n");
4314 		un->un_status = SUN_KEY_EOF;
4315 		if (SVR4_BEHAVIOR) {
4316 			un->un_pos.eof = ST_EOF;
4317 			goto b_done;
4318 		}
4319 		/* FALLTHROUGH */
4320 	case ST_EOF:
4321 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
4322 		un->un_status = SUN_KEY_EOF;
4323 		if (SVR4_BEHAVIOR) {
4324 			goto b_done_err;
4325 		}
4326 
4327 		if (BSD_BEHAVIOR) {
4328 			un->un_pos.eof = ST_NO_EOF;
4329 			un->un_pos.fileno += 1;
4330 			un->un_pos.blkno   = 0;
4331 		}
4332 
4333 		if (reading) {
4334 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4335 			    "now file %d (read)\n",
4336 			    un->un_pos.fileno);
4337 			goto b_done;
4338 		}
4339 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4340 		    "now file %d (write)\n", un->un_pos.fileno);
4341 		break;
4342 	default:
4343 		un->un_status = 0;
4344 		break;
4345 	}
4346 
4347 	bp->b_flags &= ~(B_DONE);
4348 	st_bioerror(bp, 0);
4349 	bp->av_forw = NULL;
4350 	bp->b_resid = 0;
4351 	SET_BP_PKT(bp, 0);
4352 
4353 
4354 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4355 	    "st_queued_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4356 	    " pkt=0x%p\n",
4357 	    (void *)bp->b_forw, bp->b_bcount,
4358 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4359 
4360 #ifdef	__x86
4361 	/*
4362 	 * We will replace bp with a new bp that can do big blk xfer
4363 	 * if the requested xfer size is bigger than un->un_maxdma_arch
4364 	 *
4365 	 * Also, we need to make sure that we're handling real I/O
4366 	 * by checking group 0/1 SCSI I/O commands, if needed
4367 	 */
4368 	if (bp->b_bcount > un->un_maxdma_arch &&
4369 	    ((uchar_t)(uintptr_t)bp->b_forw == SCMD_READ ||
4370 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G4 ||
4371 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE ||
4372 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G4)) {
4373 		mutex_exit(ST_MUTEX);
4374 		bp = st_get_bigblk_bp(bp);
4375 		mutex_enter(ST_MUTEX);
4376 	}
4377 #endif
4378 
4379 	/* put on wait queue */
4380 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4381 	    "st_queued_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4382 	    (void *)un->un_quef, (void *)bp);
4383 
4384 	st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quel, bp);
4385 
4386 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4387 
4388 	st_start(un);
4389 
4390 	mutex_exit(ST_MUTEX);
4391 	return (0);
4392 
4393 b_done_err:
4394 	st_bioerror(bp, EIO);
4395 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4396 	    "st_queued_strategy : EIO b_done_err\n");
4397 
4398 b_done:
4399 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4400 	    "st_queued_strategy: b_done\n");
4401 
4402 exit:
4403 	/*
4404 	 * make sure no commands are outstanding or waiting before closing,
4405 	 * so we can guarantee order
4406 	 */
4407 	st_wait_for_io(un);
4408 	un->un_err_resid = bp->b_resid = bp->b_bcount;
4409 
4410 	/* override errno here, if persistent errors were flagged */
4411 	if (un->un_persistence && un->un_persist_errors)
4412 		bioerror(bp, un->un_errno);
4413 
4414 	mutex_exit(ST_MUTEX);
4415 
4416 	biodone(bp);
4417 	ASSERT(mutex_owned(ST_MUTEX) == 0);
4418 	return (0);
4419 }
4420 
4421 
4422 static int
4423 st_strategy(struct buf *bp)
4424 {
4425 	struct scsi_tape *un;
4426 
4427 	/*
4428 	 * validate arguments
4429 	 */
4430 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4431 	if (un == NULL) {
4432 		bp->b_resid = bp->b_bcount;
4433 		bioerror(bp, ENXIO);
4434 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4435 		    "st_strategy: ENXIO error exit\n");
4436 
4437 		biodone(bp);
4438 		return (0);
4439 
4440 	}
4441 
4442 	ST_ENTR(ST_DEVINFO, st_strategy);
4443 
4444 	mutex_enter(ST_MUTEX);
4445 
4446 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4447 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4448 	}
4449 
4450 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4451 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4452 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4453 
4454 	ASSERT((bp == un->un_recov_buf) || (bp == un->un_sbufp));
4455 
4456 	bp->b_flags &= ~(B_DONE);
4457 	st_bioerror(bp, 0);
4458 	bp->av_forw = NULL;
4459 	bp->b_resid = 0;
4460 	SET_BP_PKT(bp, 0);
4461 
4462 
4463 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4464 	    "st_strategy: cmd=0x%x  count=%ld  resid=%ld flags=0x%x"
4465 	    " pkt=0x%p\n",
4466 	    (unsigned char)(uintptr_t)bp->b_forw, bp->b_bcount,
4467 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4468 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4469 
4470 	st_start(un);
4471 
4472 	mutex_exit(ST_MUTEX);
4473 	return (0);
4474 }
4475 
4476 /*
4477  * this routine spaces forward over filemarks
4478  */
4479 static int
4480 st_space_fmks(struct scsi_tape *un, int64_t count)
4481 {
4482 	int rval = 0;
4483 
4484 	ST_FUNC(ST_DEVINFO, st_space_fmks);
4485 
4486 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4487 	    "st_space_fmks(dev = 0x%lx, count = %"PRIx64")\n",
4488 	    un->un_dev, count);
4489 
4490 	ASSERT(mutex_owned(ST_MUTEX));
4491 
4492 	/*
4493 	 * the risk with doing only one space operation is that we
4494 	 * may accidentily jump in old data
4495 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4496 	 * because the 8200 does not append a marker; in order not to
4497 	 * sacrifice the fast file skip, we do a slow skip if the low
4498 	 * density device has been opened
4499 	 */
4500 
4501 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4502 	    !((un->un_dp->type == ST_TYPE_EXB8500 &&
4503 	    MT_DENSITY(un->un_dev) == 0))) {
4504 		if (st_cmd(un, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4505 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4506 			    "space_fmks : EIO can't do space cmd #1\n");
4507 			rval = EIO;
4508 		}
4509 	} else {
4510 		while (count > 0) {
4511 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4512 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4513 				    "space_fmks : EIO can't do space cmd #2\n");
4514 				rval = EIO;
4515 				break;
4516 			}
4517 			count -= 1;
4518 			/*
4519 			 * read a block to see if we have reached
4520 			 * end of medium (double filemark for reel or
4521 			 * medium error for others)
4522 			 */
4523 			if (count > 0) {
4524 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
4525 					ST_DEBUG2(ST_DEVINFO, st_label,
4526 					    SCSI_DEBUG,
4527 					    "space_fmks : EIO can't do "
4528 					    "space cmd #3\n");
4529 					rval = EIO;
4530 					break;
4531 				}
4532 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4533 				    (un->un_dp->options & ST_REEL)) {
4534 					un->un_status = SUN_KEY_EOT;
4535 					ST_DEBUG2(ST_DEVINFO, st_label,
4536 					    SCSI_DEBUG,
4537 					    "space_fmks : EIO ST_REEL\n");
4538 					rval = EIO;
4539 					break;
4540 				} else if (IN_EOF(un->un_pos)) {
4541 					un->un_pos.eof = ST_NO_EOF;
4542 					un->un_pos.fileno++;
4543 					un->un_pos.blkno = 0;
4544 					count--;
4545 				} else if (un->un_pos.eof > ST_EOF) {
4546 					ST_DEBUG2(ST_DEVINFO, st_label,
4547 					    SCSI_DEBUG,
4548 					    "space_fmks, EIO > ST_EOF\n");
4549 					rval = EIO;
4550 					break;
4551 				}
4552 
4553 			}
4554 		}
4555 		un->un_err_resid = count;
4556 		COPY_POS(&un->un_pos, &un->un_err_pos);
4557 	}
4558 	ASSERT(mutex_owned(ST_MUTEX));
4559 	return (rval);
4560 }
4561 
4562 /*
4563  * this routine spaces to EOD
4564  *
4565  * it keeps track of the current filenumber and returns the filenumber after
4566  * the last successful space operation, we keep the number high because as
4567  * tapes are getting larger, the possibility of more and more files exist,
4568  * 0x100000 (1 Meg of files) probably will never have to be changed any time
4569  * soon
4570  */
4571 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4572 
4573 static int
4574 st_find_eod(struct scsi_tape *un)
4575 {
4576 	tapepos_t savepos;
4577 	int64_t sp_type;
4578 	int result;
4579 
4580 	if (un == NULL) {
4581 		return (-1);
4582 	}
4583 
4584 	ST_FUNC(ST_DEVINFO, st_find_eod);
4585 
4586 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4587 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", un->un_dev,
4588 	    un->un_pos.fileno);
4589 
4590 	ASSERT(mutex_owned(ST_MUTEX));
4591 
4592 	COPY_POS(&savepos, &un->un_pos);
4593 
4594 	/*
4595 	 * see if the drive is smart enough to do the skips in
4596 	 * one operation; 1/2" use two filemarks
4597 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4598 	 * because the 8200 does not append a marker; in order not to
4599 	 * sacrifice the fast file skip, we do a slow skip if the low
4600 	 * density device has been opened
4601 	 */
4602 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4603 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4604 		    (MT_DENSITY(un->un_dev) == 0)) {
4605 			sp_type = Fmk(1);
4606 		} else if (un->un_pos.pmode == logical) {
4607 			sp_type = SPACE(SP_EOD, 0);
4608 		} else {
4609 			sp_type = Fmk(MAX_SKIP);
4610 		}
4611 	} else {
4612 		sp_type = Fmk(1);
4613 	}
4614 
4615 	for (;;) {
4616 		result = st_cmd(un, SCMD_SPACE, sp_type, SYNC_CMD);
4617 
4618 		if (result == 0) {
4619 			COPY_POS(&savepos, &un->un_pos);
4620 		}
4621 
4622 		if (sp_type == SPACE(SP_EOD, 0)) {
4623 			if (result != 0) {
4624 				sp_type = Fmk(MAX_SKIP);
4625 				continue;
4626 			}
4627 
4628 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4629 			    "st_find_eod: 0x%"PRIx64"\n",
4630 			    savepos.lgclblkno);
4631 			/*
4632 			 * What we return will become the current file position.
4633 			 * After completing the space command with the position
4634 			 * mode that is not invalid a read position command will
4635 			 * be automaticly issued. If the drive support the long
4636 			 * read position format a valid file position can be
4637 			 * returned.
4638 			 */
4639 			return (un->un_pos.fileno);
4640 		}
4641 
4642 		if (result != 0) {
4643 			break;
4644 		}
4645 
4646 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4647 		    "count=%"PRIx64", eof=%x, status=%x\n",
4648 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4649 
4650 		/*
4651 		 * If we're not EOM smart,  space a record
4652 		 * to see whether we're now in the slot between
4653 		 * the two sequential filemarks that logical
4654 		 * EOM consists of (REEL) or hit nowhere land
4655 		 * (8mm).
4656 		 */
4657 		if (sp_type == Fmk(1)) {
4658 			/*
4659 			 * no fast skipping, check a record
4660 			 */
4661 			if (st_cmd(un, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4662 				break;
4663 			}
4664 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4665 			    (un->un_dp->options & ST_REEL)) {
4666 				un->un_status = KEY_BLANK_CHECK;
4667 				un->un_pos.fileno++;
4668 				un->un_pos.blkno = 0;
4669 				break;
4670 			}
4671 			if (IN_EOF(un->un_pos)) {
4672 				un->un_pos.eof = ST_NO_EOF;
4673 				un->un_pos.fileno++;
4674 				un->un_pos.blkno = 0;
4675 			}
4676 			if (un->un_pos.eof > ST_EOF) {
4677 				break;
4678 			}
4679 		} else {
4680 			if (un->un_pos.eof > ST_EOF) {
4681 				break;
4682 			}
4683 		}
4684 	}
4685 
4686 	if (un->un_dp->options & ST_KNOWS_EOD) {
4687 		COPY_POS(&savepos, &un->un_pos);
4688 	}
4689 
4690 	ASSERT(mutex_owned(ST_MUTEX));
4691 
4692 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4693 	    "st_find_eod: %x\n", savepos.fileno);
4694 	return (savepos.fileno);
4695 }
4696 
4697 
4698 /*
4699  * this routine is frequently used in ioctls below;
4700  * it determines whether we know the density and if not will
4701  * determine it
4702  * if we have written the tape before, one or more filemarks are written
4703  *
4704  * depending on the stepflag, the head is repositioned to where it was before
4705  * the filemarks were written in order not to confuse step counts
4706  */
4707 #define	STEPBACK    0
4708 #define	NO_STEPBACK 1
4709 
4710 static int
4711 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4712 {
4713 
4714 	GET_SOFT_STATE(dev);
4715 
4716 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4717 
4718 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4719 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4720 	    "\n", dev, wfm, mode, stepflag);
4721 
4722 	ASSERT(mutex_owned(ST_MUTEX));
4723 
4724 	/*
4725 	 * If we don't yet know the density of the tape we have inserted,
4726 	 * we have to either unconditionally set it (if we're 'writing'),
4727 	 * or we have to determine it. As side effects, check for any
4728 	 * write-protect errors, and for the need to put out any file-marks
4729 	 * before positioning a tape.
4730 	 *
4731 	 * If we are going to be spacing forward, and we haven't determined
4732 	 * the tape density yet, we have to do so now...
4733 	 */
4734 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4735 		if (st_determine_density(un, mode)) {
4736 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4737 			    "check_density_or_wfm : EIO can't determine "
4738 			    "density\n");
4739 			un->un_errno = EIO;
4740 			return (EIO);
4741 		}
4742 		/*
4743 		 * Presumably we are at BOT. If we attempt to write, it will
4744 		 * either work okay, or bomb. We don't do a st_test_append
4745 		 * unless we're past BOT.
4746 		 */
4747 		un->un_laststate = un->un_state;
4748 		un->un_state = ST_STATE_OPEN;
4749 
4750 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4751 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4752 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4753 
4754 		tapepos_t spos;
4755 
4756 		COPY_POS(&spos, &un->un_pos);
4757 
4758 		/*
4759 		 * We need to write one or two filemarks.
4760 		 * In the case of the HP, we need to
4761 		 * position the head between the two
4762 		 * marks.
4763 		 */
4764 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4765 			wfm = un->un_fmneeded;
4766 			un->un_fmneeded = 0;
4767 		}
4768 
4769 		if (st_write_fm(dev, wfm)) {
4770 			un->un_pos.pmode = invalid;
4771 			un->un_density_known = 0;
4772 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4773 			    "check_density_or_wfm : EIO can't write fm\n");
4774 			un->un_errno = EIO;
4775 			return (EIO);
4776 		}
4777 
4778 		if (stepflag == STEPBACK) {
4779 			if (st_cmd(un, SCMD_SPACE, Fmk(-wfm), SYNC_CMD)) {
4780 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4781 				    "check_density_or_wfm : EIO can't space "
4782 				    "(-wfm)\n");
4783 				un->un_errno = EIO;
4784 				return (EIO);
4785 			}
4786 			COPY_POS(&un->un_pos, &spos);
4787 		}
4788 	}
4789 
4790 	/*
4791 	 * Whatever we do at this point clears the state of the eof flag.
4792 	 */
4793 
4794 	un->un_pos.eof = ST_NO_EOF;
4795 
4796 	/*
4797 	 * If writing, let's check that we're positioned correctly
4798 	 * at the end of tape before issuing the next write.
4799 	 */
4800 	if (un->un_read_only == RDWR) {
4801 		un->un_test_append = 1;
4802 	}
4803 
4804 	ASSERT(mutex_owned(ST_MUTEX));
4805 	return (0);
4806 }
4807 
4808 
4809 /*
4810  * Wait for all outstaning I/O's to complete
4811  *
4812  * we wait on both ncmds and the wait queue for times when we are flushing
4813  * after persistent errors are flagged, which is when ncmds can be 0, and the
4814  * queue can still have I/O's.  This way we preserve order of biodone's.
4815  */
4816 static void
4817 st_wait_for_io(struct scsi_tape *un)
4818 {
4819 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4820 	ASSERT(mutex_owned(ST_MUTEX));
4821 	while ((un->un_ncmds) || (un->un_quef) || (un->un_runqf)) {
4822 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4823 	}
4824 }
4825 
4826 /*
4827  * This routine implements the ioctl calls.  It is called
4828  * from the device switch at normal priority.
4829  */
4830 /*ARGSUSED*/
4831 static int
4832 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4833     int *rval_p)
4834 {
4835 	int tmp, rval = 0;
4836 
4837 	GET_SOFT_STATE(dev);
4838 
4839 	ST_ENTR(ST_DEVINFO, st_ioctl);
4840 
4841 	mutex_enter(ST_MUTEX);
4842 
4843 	ASSERT(un->un_recov_buf_busy == 0);
4844 
4845 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4846 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4847 	    "pe_flag = %d\n",
4848 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4849 	    un->un_persistence && un->un_persist_errors);
4850 
4851 	/*
4852 	 * We don't want to block on these, so let them through
4853 	 * and we don't care about setting driver states here.
4854 	 */
4855 	if ((cmd == MTIOCGETDRIVETYPE) ||
4856 	    (cmd == MTIOCGUARANTEEDORDER) ||
4857 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4858 		goto check_commands;
4859 	}
4860 
4861 	/*
4862 	 * We clear error entry stack except command
4863 	 * MTIOCGETERROR and MTIOCGET
4864 	 */
4865 	if ((cmd != MTIOCGETERROR) &&
4866 	    (cmd != MTIOCGET)) {
4867 		st_empty_error_stack(un);
4868 	}
4869 
4870 	/*
4871 	 * wait for all outstanding commands to complete, or be dequeued.
4872 	 * And because ioctl's are synchronous commands, any return value
4873 	 * after this,  will be in order
4874 	 */
4875 	st_wait_for_io(un);
4876 
4877 	/*
4878 	 * allow only a through clear errors and persistent status, and
4879 	 * status
4880 	 */
4881 	if (un->un_persistence && un->un_persist_errors) {
4882 		if ((cmd == MTIOCLRERR) ||
4883 		    (cmd == MTIOCPERSISTENT) ||
4884 		    (cmd == MTIOCGET)) {
4885 			goto check_commands;
4886 		} else {
4887 			rval = un->un_errno;
4888 			goto exit;
4889 		}
4890 	}
4891 
4892 	ASSERT(un->un_throttle != 0);
4893 	un->un_throttle = 1;	/* > 1 will never happen here */
4894 	un->un_errno = 0;	/* start clean from here */
4895 
4896 	/*
4897 	 * first and foremost, handle any ST_EOT_PENDING cases.
4898 	 * That is, if a logical eot is pending notice, notice it.
4899 	 */
4900 	if (un->un_pos.eof == ST_EOT_PENDING) {
4901 		int resid = un->un_err_resid;
4902 		uchar_t status = un->un_status;
4903 		uchar_t lastop = un->un_lastop;
4904 
4905 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4906 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4907 			    "stioctl : EIO can't space fmk(-1)\n");
4908 			rval = EIO;
4909 			goto exit;
4910 		}
4911 		un->un_lastop = lastop; /* restore last operation */
4912 		if (status == SUN_KEY_EOF) {
4913 			un->un_status = SUN_KEY_EOT;
4914 		} else {
4915 			un->un_status = status;
4916 		}
4917 		un->un_err_resid  = resid;
4918 		/* fix up block number */
4919 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4920 		/* now we're at logical eot */
4921 		un->un_pos.eof = ST_EOT;
4922 	}
4923 
4924 	/*
4925 	 * now, handle the rest of the situations
4926 	 */
4927 check_commands:
4928 	switch (cmd) {
4929 	case MTIOCGET:
4930 	{
4931 #ifdef _MULTI_DATAMODEL
4932 		/*
4933 		 * For use when a 32 bit app makes a call into a
4934 		 * 64 bit ioctl
4935 		 */
4936 		struct mtget32		mtg_local32;
4937 		struct mtget32 		*mtget_32 = &mtg_local32;
4938 #endif /* _MULTI_DATAMODEL */
4939 
4940 			/* Get tape status */
4941 		struct mtget mtg_local;
4942 		struct mtget *mtget = &mtg_local;
4943 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4944 		    "st_ioctl: MTIOCGET\n");
4945 
4946 		bzero((caddr_t)mtget, sizeof (struct mtget));
4947 		mtget->mt_erreg = un->un_status;
4948 		mtget->mt_resid = un->un_err_resid;
4949 		mtget->mt_dsreg = un->un_retry_ct;
4950 		if (un->un_err_pos.pmode == legacy) {
4951 			mtget->mt_fileno = un->un_err_pos.fileno;
4952 		} else {
4953 			mtget->mt_fileno = -1;
4954 		}
4955 		/*
4956 		 * If the value is positive fine.
4957 		 * If its negative we need to return a value based on the
4958 		 * old way if counting backwards from INF (1,000,000,000).
4959 		 */
4960 		if (un->un_err_pos.blkno >= 0) {
4961 			mtget->mt_blkno = un->un_err_pos.blkno;
4962 		} else {
4963 			mtget->mt_blkno = INF + 1 - (-un->un_err_pos.blkno);
4964 		}
4965 		mtget->mt_type = un->un_dp->type;
4966 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
4967 		if (un->un_read_pos_type != NO_POS) {
4968 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
4969 		}
4970 		if (un->un_dp->options & ST_REEL) {
4971 			mtget->mt_flags |= MTF_REEL;
4972 			mtget->mt_bf = 20;
4973 		} else {		/* 1/4" cartridges */
4974 			switch (mtget->mt_type) {
4975 			/* Emulex cartridge tape */
4976 			case MT_ISMT02:
4977 				mtget->mt_bf = 40;
4978 				break;
4979 			default:
4980 				mtget->mt_bf = 126;
4981 				break;
4982 			}
4983 		}
4984 
4985 		/*
4986 		 * If large transfers are allowed and drive options
4987 		 * has no record size limit set. Calculate blocking
4988 		 * factor from the lesser of maxbsize and maxdma.
4989 		 */
4990 		if ((un->un_allow_large_xfer) &&
4991 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
4992 			mtget->mt_bf = min(un->un_maxbsize,
4993 			    un->un_maxdma) / SECSIZE;
4994 		}
4995 
4996 		if (un->un_read_only == WORM ||
4997 		    un->un_read_only == RDWORM) {
4998 			mtget->mt_flags |= MTF_WORM_MEDIA;
4999 		}
5000 
5001 		/*
5002 		 * In persistent error mode sending a non-queued can hang
5003 		 * because this ioctl gets to be run without turning off
5004 		 * persistense. Fake the answer based on previous info.
5005 		 */
5006 		if (un->un_persistence) {
5007 			rval = 0;
5008 		} else {
5009 			rval = st_check_clean_bit(un);
5010 		}
5011 		if (rval == 0) {
5012 			/*
5013 			 * If zero is returned or in persistent mode,
5014 			 * use the old data.
5015 			 */
5016 			if ((un->un_HeadClean & (TAPE_ALERT_SUPPORTED |
5017 			    TAPE_SEQUENTIAL_SUPPORTED|TAPE_ALERT_NOT_SUPPORTED))
5018 			    != TAPE_ALERT_NOT_SUPPORTED) {
5019 				mtget->mt_flags |= MTF_TAPE_CLN_SUPPORTED;
5020 			}
5021 			if (un->un_HeadClean & (TAPE_PREVIOUSLY_DIRTY |
5022 			    TAPE_ALERT_STILL_DIRTY)) {
5023 				mtget->mt_flags |= MTF_TAPE_HEAD_DIRTY;
5024 			}
5025 		} else {
5026 			mtget->mt_flags |= (ushort_t)rval;
5027 			rval = 0;
5028 		}
5029 
5030 		un->un_status = 0;		/* Reset status */
5031 		un->un_err_resid = 0;
5032 		tmp = sizeof (struct mtget);
5033 
5034 #ifdef _MULTI_DATAMODEL
5035 
5036 		switch (ddi_model_convert_from(flag & FMODELS)) {
5037 		case DDI_MODEL_ILP32:
5038 			/*
5039 			 * Convert 64 bit back to 32 bit before doing
5040 			 * copyout. This is what the ILP32 app expects.
5041 			 */
5042 			mtget_32->mt_erreg = 	mtget->mt_erreg;
5043 			mtget_32->mt_resid = 	mtget->mt_resid;
5044 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
5045 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
5046 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
5047 			mtget_32->mt_type =  	mtget->mt_type;
5048 			mtget_32->mt_flags = 	mtget->mt_flags;
5049 			mtget_32->mt_bf = 	mtget->mt_bf;
5050 
5051 			if (ddi_copyout(mtget_32, (void *)arg,
5052 			    sizeof (struct mtget32), flag)) {
5053 				rval = EFAULT;
5054 			}
5055 			break;
5056 
5057 		case DDI_MODEL_NONE:
5058 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5059 				rval = EFAULT;
5060 			}
5061 			break;
5062 		}
5063 #else /* ! _MULTI_DATAMODE */
5064 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5065 			rval = EFAULT;
5066 		}
5067 #endif /* _MULTI_DATAMODE */
5068 
5069 		break;
5070 	}
5071 	case MTIOCGETERROR:
5072 			/*
5073 			 * get error entry from error stack
5074 			 */
5075 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5076 			    "st_ioctl: MTIOCGETERROR\n");
5077 
5078 			rval = st_get_error_entry(un, arg, flag);
5079 
5080 			break;
5081 
5082 	case MTIOCSTATE:
5083 		{
5084 			/*
5085 			 * return when media presence matches state
5086 			 */
5087 			enum mtio_state state;
5088 
5089 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5090 			    "st_ioctl: MTIOCSTATE\n");
5091 
5092 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
5093 				rval = EFAULT;
5094 
5095 			mutex_exit(ST_MUTEX);
5096 
5097 			rval = st_check_media(dev, state);
5098 
5099 			mutex_enter(ST_MUTEX);
5100 
5101 			if (rval != 0) {
5102 				break;
5103 			}
5104 
5105 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
5106 			    sizeof (int), flag))
5107 				rval = EFAULT;
5108 			break;
5109 
5110 		}
5111 
5112 	case MTIOCGETDRIVETYPE:
5113 		{
5114 #ifdef _MULTI_DATAMODEL
5115 		/*
5116 		 * For use when a 32 bit app makes a call into a
5117 		 * 64 bit ioctl
5118 		 */
5119 		struct mtdrivetype_request32	mtdtrq32;
5120 #endif /* _MULTI_DATAMODEL */
5121 
5122 			/*
5123 			 * return mtdrivetype
5124 			 */
5125 			struct mtdrivetype_request mtdtrq;
5126 			struct mtdrivetype mtdrtyp;
5127 			struct mtdrivetype *mtdt = &mtdrtyp;
5128 			struct st_drivetype *stdt = un->un_dp;
5129 
5130 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5131 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
5132 
5133 #ifdef _MULTI_DATAMODEL
5134 		switch (ddi_model_convert_from(flag & FMODELS)) {
5135 		case DDI_MODEL_ILP32:
5136 		{
5137 			if (ddi_copyin((void *)arg, &mtdtrq32,
5138 			    sizeof (struct mtdrivetype_request32), flag)) {
5139 				rval = EFAULT;
5140 				break;
5141 			}
5142 			mtdtrq.size = mtdtrq32.size;
5143 			mtdtrq.mtdtp =
5144 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
5145 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5146 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
5147 			break;
5148 		}
5149 		case DDI_MODEL_NONE:
5150 			if (ddi_copyin((void *)arg, &mtdtrq,
5151 			    sizeof (struct mtdrivetype_request), flag)) {
5152 				rval = EFAULT;
5153 				break;
5154 			}
5155 			break;
5156 		}
5157 
5158 #else /* ! _MULTI_DATAMODEL */
5159 		if (ddi_copyin((void *)arg, &mtdtrq,
5160 		    sizeof (struct mtdrivetype_request), flag)) {
5161 			rval = EFAULT;
5162 			break;
5163 		}
5164 #endif /* _MULTI_DATAMODEL */
5165 
5166 			/*
5167 			 * if requested size is < 0 then return
5168 			 * error.
5169 			 */
5170 			if (mtdtrq.size < 0) {
5171 				rval = EINVAL;
5172 				break;
5173 			}
5174 			bzero(mtdt, sizeof (struct mtdrivetype));
5175 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
5176 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
5177 			mtdt->type = stdt->type;
5178 			mtdt->bsize = stdt->bsize;
5179 			mtdt->options = stdt->options;
5180 			mtdt->max_rretries = stdt->max_rretries;
5181 			mtdt->max_wretries = stdt->max_wretries;
5182 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5183 				mtdt->densities[tmp] = stdt->densities[tmp];
5184 			}
5185 			mtdt->default_density = stdt->default_density;
5186 			/*
5187 			 * Speed hasn't been used since the hayday of reel tape.
5188 			 * For all drives not setting the option ST_KNOWS_MEDIA
5189 			 * the speed member renamed to mediatype are zeros.
5190 			 * Those drives that have ST_KNOWS_MEDIA set use the
5191 			 * new mediatype member which is used to figure the
5192 			 * type of media loaded.
5193 			 *
5194 			 * So as to not break applications speed in the
5195 			 * mtdrivetype structure is not renamed.
5196 			 */
5197 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5198 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
5199 			}
5200 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
5201 			mtdt->io_timeout = stdt->io_timeout;
5202 			mtdt->rewind_timeout = stdt->rewind_timeout;
5203 			mtdt->space_timeout = stdt->space_timeout;
5204 			mtdt->load_timeout = stdt->load_timeout;
5205 			mtdt->unload_timeout = stdt->unload_timeout;
5206 			mtdt->erase_timeout = stdt->erase_timeout;
5207 
5208 			/*
5209 			 * Limit the maximum length of the result to
5210 			 * sizeof (struct mtdrivetype).
5211 			 */
5212 			tmp = sizeof (struct mtdrivetype);
5213 			if (mtdtrq.size < tmp)
5214 				tmp = mtdtrq.size;
5215 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
5216 				rval = EFAULT;
5217 			}
5218 			break;
5219 		}
5220 	case MTIOCPERSISTENT:
5221 
5222 		if (ddi_copyin((void *)arg, &tmp, sizeof (tmp), flag)) {
5223 			rval = EFAULT;
5224 			break;
5225 		}
5226 
5227 		if (tmp) {
5228 			st_turn_pe_on(un);
5229 		} else {
5230 			st_turn_pe_off(un);
5231 		}
5232 
5233 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5234 		    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
5235 		    un->un_persistence);
5236 
5237 		break;
5238 
5239 	case MTIOCPERSISTENTSTATUS:
5240 		tmp = (int)un->un_persistence;
5241 
5242 		if (ddi_copyout(&tmp, (void *)arg, sizeof (tmp), flag)) {
5243 			rval = EFAULT;
5244 		}
5245 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5246 		    "st_ioctl: MTIOCPERSISTENTSTATUS:persistence = %d\n",
5247 		    un->un_persistence);
5248 
5249 		break;
5250 
5251 	case MTIOCLRERR:
5252 		{
5253 			/* clear persistent errors */
5254 
5255 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5256 			    "st_ioctl: MTIOCLRERR\n");
5257 
5258 			st_clear_pe(un);
5259 
5260 			break;
5261 		}
5262 
5263 	case MTIOCGUARANTEEDORDER:
5264 		{
5265 			/*
5266 			 * this is just a holder to make a valid ioctl and
5267 			 * it won't be in any earlier release
5268 			 */
5269 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5270 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
5271 
5272 			break;
5273 		}
5274 
5275 	case MTIOCRESERVE:
5276 		{
5277 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5278 			    "st_ioctl: MTIOCRESERVE\n");
5279 
5280 			/*
5281 			 * Check if Reserve/Release is supported.
5282 			 */
5283 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5284 				rval = ENOTTY;
5285 				break;
5286 			}
5287 
5288 			rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5289 
5290 			if (rval == 0) {
5291 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
5292 			}
5293 			break;
5294 		}
5295 
5296 	case MTIOCRELEASE:
5297 		{
5298 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5299 			    "st_ioctl: MTIOCRELEASE\n");
5300 
5301 			/*
5302 			 * Check if Reserve/Release is supported.
5303 			 */
5304 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5305 				rval = ENOTTY;
5306 				break;
5307 			}
5308 
5309 			/*
5310 			 * Used to just clear ST_PRESERVE_RESERVE which
5311 			 * made the reservation release at next close.
5312 			 * As the user may have opened and then done a
5313 			 * persistant reservation we now need to drop
5314 			 * the reservation without closing if the user
5315 			 * attempts to do this.
5316 			 */
5317 			rval = st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
5318 
5319 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5320 
5321 			break;
5322 		}
5323 
5324 	case MTIOCFORCERESERVE:
5325 	{
5326 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5327 		    "st_ioctl: MTIOCFORCERESERVE\n");
5328 
5329 		/*
5330 		 * Check if Reserve/Release is supported.
5331 		 */
5332 		if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5333 			rval = ENOTTY;
5334 			break;
5335 		}
5336 		/*
5337 		 * allow only super user to run this.
5338 		 */
5339 		if (drv_priv(cred_p) != 0) {
5340 			rval = EPERM;
5341 			break;
5342 		}
5343 		/*
5344 		 * Throw away reserve,
5345 		 * not using test-unit-ready
5346 		 * since reserve can succeed without tape being
5347 		 * present in the drive.
5348 		 */
5349 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5350 
5351 		rval = st_take_ownership(un, st_uscsi_cmd);
5352 
5353 		break;
5354 	}
5355 
5356 	case USCSICMD:
5357 	{
5358 		cred_t	*cr;
5359 
5360 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5361 		    "st_ioctl: USCSICMD\n");
5362 
5363 		cr = ddi_get_cred();
5364 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5365 			rval = EPERM;
5366 		} else {
5367 			rval = st_uscsi_cmd(un, (struct uscsi_cmd *)arg, flag);
5368 		}
5369 		break;
5370 	}
5371 	case MTIOCTOP:
5372 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5373 		    "st_ioctl: MTIOCTOP\n");
5374 		rval = st_mtioctop(un, arg, flag);
5375 		break;
5376 
5377 	case MTIOCLTOP:
5378 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5379 		    "st_ioctl: MTIOLCTOP\n");
5380 		rval = st_mtiocltop(un, arg, flag);
5381 		break;
5382 
5383 	case MTIOCREADIGNOREILI:
5384 		{
5385 			int set_ili;
5386 
5387 			if (ddi_copyin((void *)arg, &set_ili,
5388 			    sizeof (set_ili), flag)) {
5389 				rval = EFAULT;
5390 				break;
5391 			}
5392 
5393 			if (un->un_bsize) {
5394 				rval = ENOTTY;
5395 				break;
5396 			}
5397 
5398 			switch (set_ili) {
5399 			case 0:
5400 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5401 				break;
5402 
5403 			case 1:
5404 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5405 				break;
5406 
5407 			default:
5408 				rval = EINVAL;
5409 				break;
5410 			}
5411 			break;
5412 		}
5413 
5414 	case MTIOCREADIGNOREEOFS:
5415 		{
5416 			int ignore_eof;
5417 
5418 			if (ddi_copyin((void *)arg, &ignore_eof,
5419 			    sizeof (ignore_eof), flag)) {
5420 				rval = EFAULT;
5421 				break;
5422 			}
5423 
5424 			if (!(un->un_dp->options & ST_REEL)) {
5425 				rval = ENOTTY;
5426 				break;
5427 			}
5428 
5429 			switch (ignore_eof) {
5430 			case 0:
5431 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5432 				break;
5433 
5434 			case 1:
5435 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5436 				break;
5437 
5438 			default:
5439 				rval = EINVAL;
5440 				break;
5441 			}
5442 			break;
5443 		}
5444 
5445 	case MTIOCSHORTFMK:
5446 	{
5447 		int short_fmk;
5448 
5449 		if (ddi_copyin((void *)arg, &short_fmk,
5450 		    sizeof (short_fmk), flag)) {
5451 			rval = EFAULT;
5452 			break;
5453 		}
5454 
5455 		switch (un->un_dp->type) {
5456 		case ST_TYPE_EXB8500:
5457 		case ST_TYPE_EXABYTE:
5458 			if (!short_fmk) {
5459 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5460 			} else if (short_fmk == 1) {
5461 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5462 			} else {
5463 				rval = EINVAL;
5464 			}
5465 			break;
5466 
5467 		default:
5468 			rval = ENOTTY;
5469 			break;
5470 		}
5471 		break;
5472 	}
5473 
5474 	case MTIOCGETPOS:
5475 		rval = st_update_block_pos(un, st_cmd, 0);
5476 		if (rval == 0) {
5477 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5478 			    sizeof (tapepos_t), flag)) {
5479 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5480 				    "MTIOCGETPOS copy out failed\n");
5481 				rval = EFAULT;
5482 			}
5483 		}
5484 		break;
5485 
5486 	case MTIOCRESTPOS:
5487 	{
5488 		tapepos_t dest;
5489 
5490 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5491 		    flag) != 0) {
5492 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5493 			    "MTIOCRESTPOS copy in failed\n");
5494 			rval = EFAULT;
5495 			break;
5496 		}
5497 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &dest);
5498 		if (rval != 0) {
5499 			rval = EIO;
5500 		}
5501 		break;
5502 	}
5503 	default:
5504 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5505 		    "st_ioctl: unknown ioctl\n");
5506 		rval = ENOTTY;
5507 	}
5508 
5509 exit:
5510 	if (!(un->un_persistence && un->un_persist_errors)) {
5511 		un->un_errno = rval;
5512 	}
5513 
5514 	mutex_exit(ST_MUTEX);
5515 
5516 	return (rval);
5517 }
5518 
5519 
5520 /*
5521  * do some MTIOCTOP tape operations
5522  */
5523 static int
5524 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5525 {
5526 #ifdef _MULTI_DATAMODEL
5527 	/*
5528 	 * For use when a 32 bit app makes a call into a
5529 	 * 64 bit ioctl
5530 	 */
5531 	struct mtop32	mtop_32_for_64;
5532 #endif /* _MULTI_DATAMODEL */
5533 	struct mtop passed;
5534 	struct mtlop local;
5535 	int rval = 0;
5536 
5537 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5538 
5539 	ASSERT(mutex_owned(ST_MUTEX));
5540 
5541 #ifdef _MULTI_DATAMODEL
5542 	switch (ddi_model_convert_from(flag & FMODELS)) {
5543 	case DDI_MODEL_ILP32:
5544 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5545 		    sizeof (struct mtop32), flag)) {
5546 			return (EFAULT);
5547 		}
5548 		local.mt_op = mtop_32_for_64.mt_op;
5549 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5550 		break;
5551 
5552 	case DDI_MODEL_NONE:
5553 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5554 			return (EFAULT);
5555 		}
5556 		local.mt_op = passed.mt_op;
5557 		/* prevent sign extention */
5558 		local.mt_count = (UINT32_MAX & passed.mt_count);
5559 		break;
5560 	}
5561 
5562 #else /* ! _MULTI_DATAMODEL */
5563 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5564 		return (EFAULT);
5565 	}
5566 	local.mt_op = passed.mt_op;
5567 	/* prevent sign extention */
5568 	local.mt_count = (UINT32_MAX & passed.mt_count);
5569 #endif /* _MULTI_DATAMODEL */
5570 
5571 	rval = st_do_mtioctop(un, &local);
5572 
5573 #ifdef _MULTI_DATAMODEL
5574 	switch (ddi_model_convert_from(flag & FMODELS)) {
5575 	case DDI_MODEL_ILP32:
5576 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5577 			rval = ERANGE;
5578 			break;
5579 		}
5580 		/*
5581 		 * Convert 64 bit back to 32 bit before doing
5582 		 * copyout. This is what the ILP32 app expects.
5583 		 */
5584 		mtop_32_for_64.mt_op = local.mt_op;
5585 		mtop_32_for_64.mt_count = local.mt_count;
5586 
5587 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5588 		    sizeof (struct mtop32), flag)) {
5589 			rval = EFAULT;
5590 		}
5591 		break;
5592 
5593 	case DDI_MODEL_NONE:
5594 		passed.mt_count = local.mt_count;
5595 		passed.mt_op = local.mt_op;
5596 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5597 			rval = EFAULT;
5598 		}
5599 		break;
5600 	}
5601 #else /* ! _MULTI_DATAMODE */
5602 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5603 		rval = ERANGE;
5604 	} else {
5605 		passed.mt_op = local.mt_op;
5606 		passed.mt_count = local.mt_count;
5607 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5608 			rval = EFAULT;
5609 		}
5610 	}
5611 #endif /* _MULTI_DATAMODE */
5612 
5613 
5614 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5615 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5616 	    un->un_pos.blkno, un->un_pos.eof);
5617 
5618 	if (un->un_pos.pmode == invalid) {
5619 		un->un_density_known = 0;
5620 	}
5621 
5622 	ASSERT(mutex_owned(ST_MUTEX));
5623 	return (rval);
5624 }
5625 
5626 static int
5627 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5628 {
5629 	struct mtlop local;
5630 	int rval;
5631 
5632 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5633 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5634 		return (EFAULT);
5635 	}
5636 
5637 	rval = st_do_mtioctop(un, &local);
5638 
5639 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5640 		rval = EFAULT;
5641 	}
5642 	return (rval);
5643 }
5644 
5645 
5646 static int
5647 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5648 {
5649 	dev_t dev = un->un_dev;
5650 	int savefile;
5651 	int rval = 0;
5652 
5653 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5654 
5655 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5656 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5657 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5658 	    "fileno=%x, blkno=%x, eof=%x\n",
5659 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5660 
5661 	un->un_status = 0;
5662 
5663 	/*
5664 	 * if we are going to mess with a tape, we have to make sure we have
5665 	 * one and are not offline (i.e. no tape is initialized).  We let
5666 	 * commands pass here that don't actually touch the tape, except for
5667 	 * loading and initialization (rewinding).
5668 	 */
5669 	if (un->un_state == ST_STATE_OFFLINE) {
5670 		switch (mtop->mt_op) {
5671 		case MTLOAD:
5672 		case MTNOP:
5673 			/*
5674 			 * We don't want strategy calling st_tape_init here,
5675 			 * so, change state
5676 			 */
5677 			un->un_state = ST_STATE_INITIALIZING;
5678 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5679 			    "st_do_mtioctop : OFFLINE state = %d\n",
5680 			    un->un_state);
5681 			break;
5682 		default:
5683 			/*
5684 			 * reinitialize by normal means
5685 			 */
5686 			rval = st_tape_init(un);
5687 			if (rval) {
5688 				un->un_state = ST_STATE_INITIALIZING;
5689 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5690 				    "st_do_mtioctop : OFFLINE init failure ");
5691 				un->un_state = ST_STATE_OFFLINE;
5692 				un->un_pos.pmode = invalid;
5693 				if (rval != EACCES) {
5694 					rval = EIO;
5695 				}
5696 				return (rval);
5697 			}
5698 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5699 			break;
5700 		}
5701 	}
5702 
5703 	/*
5704 	 * If the file position is invalid, allow only those
5705 	 * commands that properly position the tape and fail
5706 	 * the rest with EIO
5707 	 */
5708 	if (un->un_pos.pmode == invalid) {
5709 		switch (mtop->mt_op) {
5710 		case MTWEOF:
5711 		case MTRETEN:
5712 		case MTERASE:
5713 		case MTEOM:
5714 		case MTFSF:
5715 		case MTFSR:
5716 		case MTBSF:
5717 		case MTNBSF:
5718 		case MTBSR:
5719 		case MTSRSZ:
5720 		case MTGRSZ:
5721 		case MTSEEK:
5722 		case MTBSSF:
5723 		case MTFSSF:
5724 			return (EIO);
5725 			/* NOTREACHED */
5726 		case MTREW:
5727 		case MTLOAD:
5728 		case MTOFFL:
5729 		case MTNOP:
5730 		case MTTELL:
5731 		case MTLOCK:
5732 		case MTUNLOCK:
5733 			break;
5734 
5735 		default:
5736 			return (ENOTTY);
5737 			/* NOTREACHED */
5738 		}
5739 	}
5740 
5741 	switch (mtop->mt_op) {
5742 	case MTERASE:
5743 		/*
5744 		 * MTERASE rewinds the tape, erase it completely, and returns
5745 		 * to the beginning of the tape
5746 		 */
5747 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5748 			un->un_status = KEY_WRITE_PROTECT;
5749 			un->un_err_resid = mtop->mt_count;
5750 			COPY_POS(&un->un_err_pos, &un->un_pos);
5751 			return (EACCES);
5752 		}
5753 		if (un->un_dp->options & ST_REEL) {
5754 			un->un_fmneeded = 2;
5755 		} else {
5756 			un->un_fmneeded = 1;
5757 		}
5758 		mtop->mt_count = mtop->mt_count ? 1 : 0;
5759 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5760 		    st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
5761 		    st_cmd(un, SCMD_ERASE, mtop->mt_count, SYNC_CMD)) {
5762 			un->un_pos.pmode = invalid;
5763 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5764 			    "st_do_mtioctop : EIO space or erase or "
5765 			    "check den)\n");
5766 			rval = EIO;
5767 		} else {
5768 			/* QIC and helical scan rewind after erase */
5769 			if (un->un_dp->options & ST_REEL) {
5770 				(void) st_cmd(un, SCMD_REWIND, 0, ASYNC_CMD);
5771 			}
5772 		}
5773 		break;
5774 
5775 	case MTWEOF:
5776 		/*
5777 		 * write an end-of-file record
5778 		 */
5779 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5780 			un->un_status = KEY_WRITE_PROTECT;
5781 			un->un_err_resid = mtop->mt_count;
5782 			COPY_POS(&un->un_err_pos, &un->un_pos);
5783 			return (EACCES);
5784 		}
5785 
5786 		/*
5787 		 * zero count means just flush buffers
5788 		 * negative count is not permitted
5789 		 */
5790 		if (mtop->mt_count < 0) {
5791 			return (EINVAL);
5792 		}
5793 
5794 		/* Not on worm */
5795 		if (un->un_read_only == RDWR) {
5796 			un->un_test_append = 1;
5797 		}
5798 
5799 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5800 			if (st_determine_density(un, B_WRITE)) {
5801 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5802 				    "st_do_mtioctop : EIO : MTWEOF can't "
5803 				    "determine density");
5804 				return (EIO);
5805 			}
5806 		}
5807 
5808 		rval = st_write_fm(dev, (int)mtop->mt_count);
5809 		if ((rval != 0) && (rval != EACCES)) {
5810 			/*
5811 			 * Failure due to something other than illegal
5812 			 * request results in loss of state (st_intr).
5813 			 */
5814 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5815 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5816 			    "file mark");
5817 			rval = EIO;
5818 		}
5819 		break;
5820 
5821 	case MTRETEN:
5822 		/*
5823 		 * retension the tape
5824 		 */
5825 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5826 		    st_cmd(un, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5827 			un->un_pos.pmode = invalid;
5828 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5829 			    "st_do_mtioctop : EIO : MTRETEN ");
5830 			rval = EIO;
5831 		}
5832 		break;
5833 
5834 	case MTREW:
5835 		/*
5836 		 * rewind  the tape
5837 		 */
5838 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5839 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5840 			    "st_do_mtioctop : EIO:MTREW check "
5841 			    "density/wfm failed");
5842 			return (EIO);
5843 		}
5844 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
5845 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5846 			    "st_do_mtioctop : EIO : MTREW ");
5847 			rval = EIO;
5848 		}
5849 		break;
5850 
5851 	case MTOFFL:
5852 		/*
5853 		 * rewinds, and, if appropriate, takes the device offline by
5854 		 * unloading the tape
5855 		 */
5856 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5857 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5858 			    "st_do_mtioctop :EIO:MTOFFL check "
5859 			    "density/wfm failed");
5860 			return (EIO);
5861 		}
5862 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
5863 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5864 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5865 			    "st_do_mtioctop : EIO : MTOFFL");
5866 			return (EIO);
5867 		}
5868 		un->un_pos.eof = ST_NO_EOF;
5869 		un->un_laststate = un->un_state;
5870 		un->un_state = ST_STATE_OFFLINE;
5871 		un->un_mediastate = MTIO_EJECTED;
5872 		break;
5873 
5874 	case MTLOAD:
5875 		/*
5876 		 * This is to load a tape into the drive
5877 		 * Note that if the tape is not loaded, the device will have
5878 		 * to be opened via O_NDELAY or O_NONBLOCK.
5879 		 */
5880 		/*
5881 		 * Let's try and clean things up, if we are not
5882 		 * initializing, and then send in the load command, no
5883 		 * matter what.
5884 		 *
5885 		 * load after a media change by the user.
5886 		 */
5887 
5888 		if (un->un_state > ST_STATE_INITIALIZING) {
5889 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5890 		}
5891 		rval = st_cmd(un, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5892 		/* Load command to a drive that doesn't support load */
5893 		if ((rval == EIO) &&
5894 		    ((un->un_status == KEY_NOT_READY) &&
5895 			/* Medium not present */
5896 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5897 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5898 		    (un->un_dp->type == MT_ISSTK9840) &&
5899 			/* CSL not present */
5900 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5901 			rval = ENOTTY;
5902 			break;
5903 		} else if (rval != EACCES && rval != 0) {
5904 			rval = EIO;
5905 		}
5906 		if (rval) {
5907 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5908 			    "st_do_mtioctop : %s : MTLOAD\n",
5909 			    rval == EACCES ? "EACCES" : "EIO");
5910 			/*
5911 			 * If load tape fails, who knows what happened...
5912 			 */
5913 			un->un_pos.pmode = invalid;
5914 			break;
5915 		}
5916 
5917 		/*
5918 		 * reset all counters appropriately using rewind, as if LOAD
5919 		 * succeeds, we are at BOT
5920 		 */
5921 		un->un_state = ST_STATE_INITIALIZING;
5922 
5923 		rval = st_tape_init(un);
5924 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5925 			rval = 0;
5926 			break;
5927 		}
5928 
5929 		if (rval != 0) {
5930 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5931 			    "st_do_mtioctop : EIO : MTLOAD calls "
5932 			    "st_tape_init\n");
5933 			rval = EIO;
5934 			un->un_state = ST_STATE_OFFLINE;
5935 		}
5936 
5937 		break;
5938 
5939 	case MTNOP:
5940 		un->un_status = 0;		/* Reset status */
5941 		un->un_err_resid = 0;
5942 		mtop->mt_count = MTUNIT(dev);
5943 		break;
5944 
5945 	case MTEOM:
5946 		/*
5947 		 * positions the tape at a location just after the last file
5948 		 * written on the tape. For cartridge and 8 mm, this after
5949 		 * the last file mark; for reel, this is inbetween the two
5950 		 * last 2 file marks
5951 		 */
5952 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5953 		    (un->un_lastop == ST_OP_WRITE) ||
5954 		    (un->un_lastop == ST_OP_WEOF)) {
5955 			/*
5956 			 * If the command wants to move to logical end
5957 			 * of media, and we're already there, we're done.
5958 			 * If we were at logical eot, we reset the state
5959 			 * to be *not* at logical eot.
5960 			 *
5961 			 * If we're at physical or logical eot, we prohibit
5962 			 * forward space operations (unconditionally).
5963 			 *
5964 			 * Also if the last operation was a write of any
5965 			 * kind the tape is at EOD.
5966 			 */
5967 			return (0);
5968 		}
5969 		/*
5970 		 * physical tape position may not be what we've been
5971 		 * telling the user; adjust the request accordingly
5972 		 */
5973 		if (IN_EOF(un->un_pos)) {
5974 			un->un_pos.fileno++;
5975 			un->un_pos.blkno = 0;
5976 		}
5977 
5978 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
5979 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5980 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
5981 			    " failed");
5982 			return (EIO);
5983 		}
5984 
5985 		/*
5986 		 * st_find_eod() returns the last fileno we knew about;
5987 		 */
5988 		savefile = st_find_eod(un);
5989 
5990 		if ((un->un_status != KEY_BLANK_CHECK) &&
5991 		    (un->un_status != SUN_KEY_EOT)) {
5992 			un->un_pos.pmode = invalid;
5993 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5994 			    "st_do_mtioctop : EIO : MTEOM status check failed");
5995 			rval = EIO;
5996 		} else {
5997 			/*
5998 			 * For 1/2" reel tapes assume logical EOT marked
5999 			 * by two file marks or we don't care that we may
6000 			 * be extending the last file on the tape.
6001 			 */
6002 			if (un->un_dp->options & ST_REEL) {
6003 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
6004 					un->un_pos.pmode = invalid;
6005 					ST_DEBUG2(ST_DEVINFO, st_label,
6006 					    SCSI_DEBUG,
6007 					    "st_do_mtioctop : EIO : MTEOM space"
6008 					    " cmd failed");
6009 					rval = EIO;
6010 					break;
6011 				}
6012 				/*
6013 				 * Fix up the block number.
6014 				 */
6015 				un->un_pos.blkno = 0;
6016 				un->un_err_pos.blkno = 0;
6017 			}
6018 			un->un_err_resid = 0;
6019 			un->un_pos.fileno = savefile;
6020 			un->un_pos.eof = ST_EOT;
6021 		}
6022 		un->un_status = 0;
6023 		break;
6024 
6025 	case MTFSF:
6026 		MAX_SPACE_CNT(mtop->mt_count);
6027 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
6028 		break;
6029 
6030 	case MTFSR:
6031 		MAX_SPACE_CNT(mtop->mt_count);
6032 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
6033 		break;
6034 
6035 	case MTBSF:
6036 		MAX_SPACE_CNT(mtop->mt_count);
6037 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
6038 		break;
6039 
6040 	case MTNBSF:
6041 		MAX_SPACE_CNT(mtop->mt_count);
6042 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
6043 		break;
6044 
6045 	case MTBSR:
6046 		MAX_SPACE_CNT(mtop->mt_count);
6047 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
6048 		break;
6049 
6050 	case MTBSSF:
6051 		MAX_SPACE_CNT(mtop->mt_count);
6052 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
6053 		break;
6054 
6055 	case MTFSSF:
6056 		MAX_SPACE_CNT(mtop->mt_count);
6057 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
6058 		break;
6059 
6060 	case MTSRSZ:
6061 
6062 		/*
6063 		 * Set record-size to that sent by user
6064 		 * Check to see if there is reason that the requested
6065 		 * block size should not be set.
6066 		 */
6067 
6068 		/* If requesting variable block size is it ok? */
6069 		if ((mtop->mt_count == 0) &&
6070 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
6071 			return (ENOTTY);
6072 		}
6073 
6074 		/*
6075 		 * If requested block size is not variable "0",
6076 		 * is it less then minimum.
6077 		 */
6078 		if ((mtop->mt_count != 0) &&
6079 		    (mtop->mt_count < un->un_minbsize)) {
6080 			return (EINVAL);
6081 		}
6082 
6083 		/* Is the requested block size more then maximum */
6084 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
6085 		    (un->un_maxbsize != 0)) {
6086 			return (EINVAL);
6087 		}
6088 
6089 		/* Is requested block size a modulus the device likes */
6090 		if ((mtop->mt_count % un->un_data_mod) != 0) {
6091 			return (EINVAL);
6092 		}
6093 
6094 		if (st_change_block_size(un, (uint32_t)mtop->mt_count) != 0) {
6095 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6096 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
6097 			return (EIO);
6098 		}
6099 
6100 		return (0);
6101 
6102 	case MTGRSZ:
6103 		/*
6104 		 * Get record-size to the user
6105 		 */
6106 		mtop->mt_count = un->un_bsize;
6107 		rval = 0;
6108 		break;
6109 
6110 	case MTTELL:
6111 		rval = st_update_block_pos(un, st_cmd, 0);
6112 		mtop->mt_count = un->un_pos.lgclblkno;
6113 		break;
6114 
6115 	case MTSEEK:
6116 		rval = st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
6117 		    (uint64_t)mtop->mt_count, un->un_pos.partition);
6118 		/*
6119 		 * This bit of magic make mt print the actual position if
6120 		 * the resulting position was not what was asked for.
6121 		 */
6122 		if (rval == ESPIPE) {
6123 			rval = EIO;
6124 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
6125 				mtop->mt_op = MTTELL;
6126 				mtop->mt_count = un->un_pos.lgclblkno;
6127 			}
6128 		}
6129 		break;
6130 
6131 	case MTLOCK:
6132 		if (st_cmd(un, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
6133 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6134 			    "st_do_mtioctop : EIO : MTLOCK");
6135 			rval = EIO;
6136 		}
6137 		break;
6138 
6139 	case MTUNLOCK:
6140 		if (st_cmd(un, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
6141 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6142 			    "st_do_mtioctop : EIO : MTUNLOCK");
6143 			rval = EIO;
6144 		}
6145 		break;
6146 
6147 	default:
6148 		rval = ENOTTY;
6149 	}
6150 
6151 	return (rval);
6152 }
6153 
6154 
6155 /*
6156  * Run a command for uscsi ioctl.
6157  */
6158 static int
6159 st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
6160 {
6161 	struct uscsi_cmd	*uscmd;
6162 	struct buf	*bp;
6163 	enum uio_seg	uioseg;
6164 	int	offline_state = 0;
6165 	int	err = 0;
6166 	dev_t dev = un->un_dev;
6167 
6168 	ST_FUNC(ST_DEVINFO, st_uscsi_cmd);
6169 
6170 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6171 	    "st_uscsi_cmd(dev = 0x%lx)\n", un->un_dev);
6172 
6173 	ASSERT(mutex_owned(ST_MUTEX));
6174 
6175 	/*
6176 	 * We really don't know what commands are coming in here and
6177 	 * we don't want to limit the commands coming in.
6178 	 *
6179 	 * If st_tape_init() gets called from st_strategy(), then we
6180 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
6181 	 * which it never will, as we set it below.  To prevent
6182 	 * st_tape_init() from getting called, we have to set state to other
6183 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
6184 	 * achieves this purpose already.
6185 	 *
6186 	 * We use offline_state to preserve the OFFLINE state, if it exists,
6187 	 * so other entry points to the driver might have the chance to call
6188 	 * st_tape_init().
6189 	 */
6190 	if (un->un_state == ST_STATE_OFFLINE) {
6191 		un->un_laststate = ST_STATE_OFFLINE;
6192 		un->un_state = ST_STATE_INITIALIZING;
6193 		offline_state = 1;
6194 	}
6195 
6196 	mutex_exit(ST_MUTEX);
6197 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag, ROUTE, &uscmd);
6198 	mutex_enter(ST_MUTEX);
6199 	if (err != 0) {
6200 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6201 		    "st_uscsi_cmd: scsi_uscsi_alloc_and_copyin failed\n");
6202 		goto exit;
6203 	}
6204 
6205 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
6206 
6207 	/* check to see if this command requires the drive to be reserved */
6208 	if (uscmd->uscsi_cdb != NULL) {
6209 		err = st_check_cdb_for_need_to_reserve(un,
6210 		    (uchar_t *)uscmd->uscsi_cdb);
6211 		if (err) {
6212 			goto exit_free;
6213 		}
6214 		/*
6215 		 * If this is a space command we need to save the starting
6216 		 * point so we can retry from there if the command fails.
6217 		 */
6218 		if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6219 		    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) {
6220 			(void) st_update_block_pos(un, st_cmd, 0);
6221 		}
6222 	}
6223 
6224 	/*
6225 	 * Forground should not be doing anything while recovery is active.
6226 	 */
6227 	ASSERT(un->un_recov_buf_busy == 0);
6228 
6229 	/*
6230 	 * Get buffer resources...
6231 	 */
6232 	while (un->un_sbuf_busy)
6233 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6234 	un->un_sbuf_busy = 1;
6235 
6236 #ifdef STDEBUG
6237 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0x7) > 6) {
6238 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
6239 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6240 		    "uscsi cdb", uscmd->uscsi_cdb);
6241 		if (uscmd->uscsi_buflen) {
6242 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6243 			    "uscsi %s of %ld bytes %s %s space\n",
6244 			    (rw == B_READ) ? rd_str : wr_str,
6245 			    uscmd->uscsi_buflen,
6246 			    (rw == B_READ) ? "to" : "from",
6247 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
6248 		}
6249 	}
6250 #endif /* STDEBUG */
6251 
6252 	/*
6253 	 * Although st_uscsi_cmd() never makes use of these
6254 	 * now, we are just being safe and consistent.
6255 	 */
6256 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
6257 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
6258 
6259 	un->un_srqbufp = uscmd->uscsi_rqbuf;
6260 	bp = un->un_sbufp;
6261 	bzero(bp, sizeof (buf_t));
6262 	if (uscmd->uscsi_cdb != NULL) {
6263 		bp->b_forw = (struct buf *)(uintptr_t)uscmd->uscsi_cdb[0];
6264 	}
6265 	bp->b_back = (struct buf *)uscmd;
6266 
6267 	mutex_exit(ST_MUTEX);
6268 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, st_strategy, bp, NULL);
6269 	mutex_enter(ST_MUTEX);
6270 
6271 	/*
6272 	 * If scsi reset successful, don't write any filemarks.
6273 	 */
6274 	if ((err == 0) && (uscmd->uscsi_flags &
6275 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
6276 		un->un_fmneeded = 0;
6277 	}
6278 
6279 exit_free:
6280 	/*
6281 	 * Free resources
6282 	 */
6283 	un->un_sbuf_busy = 0;
6284 	un->un_srqbufp = NULL;
6285 
6286 	/*
6287 	 * If was a space command need to update logical block position.
6288 	 * If the command failed such that positioning is invalid, Don't
6289 	 * update the position as the user must do this to validate the
6290 	 * position for data protection.
6291 	 */
6292 	if ((uscmd->uscsi_cdb != NULL) &&
6293 	    ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6294 	    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) &&
6295 	    (un->un_pos.pmode != invalid)) {
6296 		un->un_running.pmode = invalid;
6297 		(void) st_update_block_pos(un, st_cmd, 1);
6298 		/*
6299 		 * Set running position to invalid so it updates on the
6300 		 * next command.
6301 		 */
6302 		un->un_running.pmode = invalid;
6303 	}
6304 	cv_signal(&un->un_sbuf_cv);
6305 	mutex_exit(ST_MUTEX);
6306 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
6307 	mutex_enter(ST_MUTEX);
6308 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6309 	    "st_uscsi_cmd returns 0x%x\n", err);
6310 
6311 exit:
6312 	/* don't lose offline state */
6313 	if (offline_state) {
6314 		un->un_state = ST_STATE_OFFLINE;
6315 	}
6316 
6317 	ASSERT(mutex_owned(ST_MUTEX));
6318 	return (err);
6319 }
6320 
6321 static int
6322 st_write_fm(dev_t dev, int wfm)
6323 {
6324 	int i;
6325 	int rval;
6326 
6327 	GET_SOFT_STATE(dev);
6328 
6329 	ST_FUNC(ST_DEVINFO, st_write_fm);
6330 
6331 	ASSERT(mutex_owned(ST_MUTEX));
6332 
6333 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6334 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6335 
6336 	/*
6337 	 * write one filemark at the time after EOT
6338 	 */
6339 	if (un->un_pos.eof >= ST_EOT) {
6340 		for (i = 0; i < wfm; i++) {
6341 			rval = st_cmd(un, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6342 			if (rval == EACCES) {
6343 				return (rval);
6344 			}
6345 			if (rval != 0) {
6346 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6347 				    "st_write_fm : EIO : write EOT file mark");
6348 				return (EIO);
6349 			}
6350 		}
6351 	} else {
6352 		rval = st_cmd(un, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6353 		if (rval == EACCES) {
6354 			return (rval);
6355 		}
6356 		if (rval) {
6357 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6358 			    "st_write_fm : EIO : write file mark");
6359 			return (EIO);
6360 		}
6361 	}
6362 
6363 	ASSERT(mutex_owned(ST_MUTEX));
6364 	return (0);
6365 }
6366 
6367 #ifdef STDEBUG
6368 static void
6369 st_start_dump(struct scsi_tape *un, struct buf *bp)
6370 {
6371 	struct scsi_pkt *pkt = BP_PKT(bp);
6372 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6373 
6374 	ST_FUNC(ST_DEVINFO, st_start_dump);
6375 
6376 	if ((st_debug & 0x7) < 6)
6377 		return;
6378 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6379 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6380 	    (void *)bp->b_forw, bp->b_bcount,
6381 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6382 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6383 	    "st_start: cdb",  (caddr_t)cdbp);
6384 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6385 	    "st_start: fileno=%d, blk=%d\n",
6386 	    un->un_pos.fileno, un->un_pos.blkno);
6387 }
6388 #endif
6389 
6390 
6391 /*
6392  * Command start && done functions
6393  */
6394 
6395 /*
6396  * st_start()
6397  *
6398  * Called from:
6399  *  st_strategy() to start a command.
6400  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6401  *  st_attach() when resuming from power down state.
6402  *  st_start_restart() to retry transport when device was previously busy.
6403  *  st_done_and_mutex_exit() to start the next command when previous is done.
6404  *
6405  * On entry:
6406  *  scsi_pkt may or may not be allocated.
6407  *
6408  */
6409 static void
6410 st_start(struct scsi_tape *un)
6411 {
6412 	struct buf *bp;
6413 	int status;
6414 	int queued;
6415 
6416 	ST_FUNC(ST_DEVINFO, st_start);
6417 	ASSERT(mutex_owned(ST_MUTEX));
6418 
6419 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6420 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6421 
6422 	if (un->un_recov_buf_busy) {
6423 		/* recovery commands can happen anytime */
6424 		bp = un->un_recov_buf;
6425 		queued = 0;
6426 	} else if (un->un_sbuf_busy) {
6427 		/* sbuf commands should only happen with an empty queue. */
6428 		ASSERT(un->un_quef == NULL);
6429 		ASSERT(un->un_runqf == NULL);
6430 		bp = un->un_sbufp;
6431 		queued = 0;
6432 	} else if (un->un_quef != NULL) {
6433 		if (un->un_persistence && un->un_persist_errors) {
6434 			return;
6435 		}
6436 		bp = un->un_quef;
6437 		queued = 1;
6438 	} else {
6439 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6440 		    "st_start() returning no buf found\n");
6441 		return;
6442 	}
6443 
6444 	ASSERT((bp->b_flags & B_DONE) == 0);
6445 
6446 	/*
6447 	 * Don't send more than un_throttle commands to the HBA
6448 	 */
6449 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6450 		/*
6451 		 * if doing recovery we know there is outstanding commands.
6452 		 */
6453 		if (bp != un->un_recov_buf) {
6454 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6455 			    "st_start returning throttle = %d or ncmds = %d\n",
6456 			    un->un_throttle, un->un_ncmds);
6457 			if (un->un_ncmds == 0) {
6458 				typedef void (*func)();
6459 				func fnc = (func)st_runout;
6460 
6461 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6462 				    "Sending delayed start to st_runout()\n");
6463 				mutex_exit(ST_MUTEX);
6464 				(void) timeout(fnc, un, drv_usectohz(1000000));
6465 				mutex_enter(ST_MUTEX);
6466 			}
6467 			return;
6468 		}
6469 	}
6470 
6471 	/*
6472 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6473 	 * build the command.
6474 	 */
6475 	if (BP_PKT(bp) == NULL) {
6476 		ASSERT((bp->b_flags & B_DONE) == 0);
6477 		st_make_cmd(un, bp, st_runout);
6478 		ASSERT((bp->b_flags & B_DONE) == 0);
6479 		status = geterror(bp);
6480 
6481 		/*
6482 		 * Some HBA's don't call bioerror() to set an error.
6483 		 * And geterror() returns zero if B_ERROR is not set.
6484 		 * So if we get zero we must check b_error.
6485 		 */
6486 		if (status == 0 && bp->b_error != 0) {
6487 			status = bp->b_error;
6488 			bioerror(bp, status);
6489 		}
6490 
6491 		/*
6492 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6493 		 * In tape ENOMEM has special meaning so we'll change it.
6494 		 */
6495 		if (status == ENOMEM) {
6496 			status = 0;
6497 			bioerror(bp, status);
6498 		}
6499 
6500 		/*
6501 		 * Did it fail and is it retryable?
6502 		 * If so return and wait for the callback through st_runout.
6503 		 * Also looks like scsi_init_pkt() will setup a callback even
6504 		 * if it isn't retryable.
6505 		 */
6506 		if (BP_PKT(bp) == NULL) {
6507 			if (status == 0) {
6508 				/*
6509 				 * If first attempt save state.
6510 				 */
6511 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6512 					un->un_laststate = un->un_state;
6513 					un->un_state = ST_STATE_RESOURCE_WAIT;
6514 				}
6515 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6516 				    "temp no resources for pkt\n");
6517 			} else if (status == EINVAL) {
6518 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6519 				    "scsi_init_pkt rejected pkt as too big\n");
6520 				if (un->un_persistence) {
6521 					st_set_pe_flag(un);
6522 				}
6523 			} else {
6524 				/*
6525 				 * Unlikely that it would be retryable then not.
6526 				 */
6527 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6528 					un->un_state = un->un_laststate;
6529 				}
6530 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6531 				    "perm no resources for pkt errno = 0x%x\n",
6532 				    status);
6533 			}
6534 			return;
6535 		}
6536 		/*
6537 		 * Worked this time set the state back.
6538 		 */
6539 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6540 			un->un_state = un->un_laststate;
6541 		}
6542 	}
6543 
6544 	if (queued) {
6545 		/*
6546 		 * move from waitq to runq
6547 		 */
6548 		(void) st_remove_from_queue(&un->un_quef, &un->un_quel, bp);
6549 		st_add_to_queue(&un->un_runqf, &un->un_runql, un->un_runql, bp);
6550 	}
6551 
6552 
6553 #ifdef STDEBUG
6554 	st_start_dump(un, bp);
6555 #endif
6556 
6557 	/* could not get here if throttle was zero */
6558 	un->un_last_throttle = un->un_throttle;
6559 	un->un_throttle = 0;	/* so nothing else will come in here */
6560 	un->un_ncmds++;
6561 
6562 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6563 
6564 	status = st_transport(un, BP_PKT(bp));
6565 
6566 	if (un->un_last_throttle) {
6567 		un->un_throttle = un->un_last_throttle;
6568 	}
6569 
6570 	if (status != TRAN_ACCEPT) {
6571 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6572 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
6573 		    "Unhappy transport packet status 0x%x\n", status);
6574 
6575 		if (status == TRAN_BUSY) {
6576 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
6577 
6578 			/*
6579 			 * If command recovery is enabled and this isn't
6580 			 * a recovery command try command recovery.
6581 			 */
6582 			if (pkti->privatelen == sizeof (recov_info) &&
6583 			    bp != un->un_recov_buf) {
6584 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
6585 				    "Command Recovery called on busy send\n");
6586 				if (st_command_recovery(un, BP_PKT(bp),
6587 				    ATTEMPT_RETRY) == JUST_RETURN) {
6588 					return;
6589 				}
6590 			} else {
6591 				mutex_exit(ST_MUTEX);
6592 				if (st_handle_start_busy(un, bp,
6593 				    ST_TRAN_BUSY_TIMEOUT, queued) == 0) {
6594 					mutex_enter(ST_MUTEX);
6595 					return;
6596 				}
6597 				/*
6598 				 * if too many retries, fail the transport
6599 				 */
6600 				mutex_enter(ST_MUTEX);
6601 			}
6602 		}
6603 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6604 		    "transport rejected %d\n", status);
6605 		bp->b_resid = bp->b_bcount;
6606 
6607 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6608 		ST_DO_ERRSTATS(un, st_transerrs);
6609 		if ((bp == un->un_recov_buf) && (status == TRAN_BUSY)) {
6610 			st_bioerror(bp, EBUSY);
6611 		} else {
6612 			st_bioerror(bp, EIO);
6613 			st_set_pe_flag(un);
6614 		}
6615 		st_done_and_mutex_exit(un, bp);
6616 		mutex_enter(ST_MUTEX);
6617 	}
6618 
6619 	ASSERT(mutex_owned(ST_MUTEX));
6620 }
6621 
6622 /*
6623  * if the transport is busy, then put this bp back on the waitq
6624  */
6625 static int
6626 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6627     clock_t timeout_interval, int queued)
6628 {
6629 
6630 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
6631 
6632 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6633 
6634 	mutex_enter(ST_MUTEX);
6635 
6636 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6637 	    "st_handle_start_busy()\n");
6638 
6639 	/*
6640 	 * Check to see if we hit the retry timeout and one last check for
6641 	 * making sure this is the last on the runq, if it is not, we have
6642 	 * to fail
6643 	 */
6644 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
6645 	    ((queued) && (un->un_runql != bp))) {
6646 		mutex_exit(ST_MUTEX);
6647 		return (-1);
6648 	}
6649 
6650 	if (queued) {
6651 		/* put the bp back on the waitq */
6652 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
6653 	}
6654 
6655 	/*
6656 	 * Decrement un_ncmds so that this
6657 	 * gets thru' st_start() again.
6658 	 */
6659 	un->un_ncmds--;
6660 
6661 	if (queued) {
6662 		/*
6663 		 * since this is an error case, we won't have to do this list
6664 		 * walking much. We've already made sure this bp was the
6665 		 * last on the runq
6666 		 */
6667 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6668 
6669 		/*
6670 		 * send a marker pkt, if appropriate
6671 		 */
6672 		st_hba_unflush(un);
6673 
6674 	}
6675 	/*
6676 	 * all queues are aligned, we are just waiting to
6677 	 * transport, don't alloc any more buf p's, when
6678 	 * st_start is reentered.
6679 	 */
6680 	(void) timeout(st_start_restart, un, timeout_interval);
6681 
6682 	mutex_exit(ST_MUTEX);
6683 	return (0);
6684 }
6685 
6686 
6687 /*
6688  * st_runout a callback that is called what a resource allocatation failed
6689  */
6690 static int
6691 st_runout(caddr_t arg)
6692 {
6693 	struct scsi_tape *un = (struct scsi_tape *)arg;
6694 	struct buf *bp;
6695 	int queued;
6696 
6697 	ASSERT(un != NULL);
6698 
6699 	ST_FUNC(ST_DEVINFO, st_runout);
6700 
6701 	mutex_enter(ST_MUTEX);
6702 
6703 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6704 
6705 	if (un->un_recov_buf_busy != 0) {
6706 		bp = un->un_recov_buf;
6707 		queued = 0;
6708 	} else if (un->un_sbuf_busy != 0) {
6709 		/* sbuf commands should only happen with an empty queue. */
6710 		ASSERT(un->un_quef == NULL);
6711 		ASSERT(un->un_runqf == NULL);
6712 		bp = un->un_sbufp;
6713 		queued = 0;
6714 	} else if (un->un_quef != NULL) {
6715 		bp = un->un_quef;
6716 		if (un->un_persistence && un->un_persist_errors) {
6717 			mutex_exit(ST_MUTEX);
6718 			bp->b_resid = bp->b_bcount;
6719 			biodone(bp);
6720 			return (1);
6721 		}
6722 		queued = 1;
6723 	} else {
6724 		ASSERT(1 == 0);
6725 		mutex_exit(ST_MUTEX);
6726 		return (1);
6727 	}
6728 
6729 	/*
6730 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6731 	 */
6732 	if ((bp != NULL) && (geterror(bp) != 0)) {
6733 
6734 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6735 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6736 		    bp->b_flags, geterror(bp));
6737 		ASSERT((bp->b_flags & B_DONE) == 0);
6738 
6739 		if (queued) {
6740 			(void) st_remove_from_queue(&un->un_quef, &un->un_quel,
6741 			    bp);
6742 		}
6743 		mutex_exit(ST_MUTEX);
6744 
6745 		ASSERT((bp->b_flags & B_DONE) == 0);
6746 
6747 		/*
6748 		 * Set resid, Error already set, then unblock calling thread.
6749 		 */
6750 		bp->b_resid = bp->b_bcount;
6751 		biodone(bp);
6752 	} else {
6753 		/*
6754 		 * Try Again
6755 		 */
6756 		st_start(un);
6757 		mutex_exit(ST_MUTEX);
6758 	}
6759 
6760 	/*
6761 	 * Comments courtesy of sd.c
6762 	 * The scsi_init_pkt routine allows for the callback function to
6763 	 * return a 0 indicating the callback should be rescheduled or a 1
6764 	 * indicating not to reschedule. This routine always returns 1
6765 	 * because the driver always provides a callback function to
6766 	 * scsi_init_pkt. This results in a callback always being scheduled
6767 	 * (via the scsi_init_pkt callback implementation) if a resource
6768 	 * failure occurs.
6769 	 */
6770 
6771 	return (1);
6772 }
6773 
6774 /*
6775  * st_done_and_mutex_exit()
6776  *	- remove bp from runq
6777  *	- start up the next request
6778  *	- if this was an asynch bp, clean up
6779  *	- exit with released mutex
6780  */
6781 static void
6782 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6783 {
6784 	int pe_flagged = 0;
6785 	struct scsi_pkt *pkt = BP_PKT(bp);
6786 	pkt_info *pktinfo = pkt->pkt_private;
6787 
6788 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6789 #if !defined(lint)
6790 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6791 #endif
6792 
6793 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6794 
6795 	ASSERT(mutex_owned(ST_MUTEX));
6796 
6797 	(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6798 
6799 	un->un_ncmds--;
6800 	cv_signal(&un->un_queue_cv);
6801 
6802 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6803 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6804 	    "0x%x\n", pkt->pkt_cdbp[0], bp->b_bcount,
6805 	    bp->b_resid, bp->b_flags);
6806 
6807 
6808 	/*
6809 	 * update kstats with transfer count info
6810 	 */
6811 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6812 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6813 		if (bp->b_flags & B_READ) {
6814 			IOSP->reads++;
6815 			IOSP->nread += n_done;
6816 		} else {
6817 			IOSP->writes++;
6818 			IOSP->nwritten += n_done;
6819 		}
6820 	}
6821 
6822 	/*
6823 	 * Start the next one before releasing resources on this one, if
6824 	 * there is something on the queue and persistent errors has not been
6825 	 * flagged
6826 	 */
6827 
6828 	if ((pe_flagged = (un->un_persistence && un->un_persist_errors)) != 0) {
6829 		un->un_last_resid = bp->b_resid;
6830 		un->un_last_count = bp->b_bcount;
6831 	}
6832 
6833 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6834 		cv_broadcast(&un->un_tape_busy_cv);
6835 	} else if (un->un_quef && un->un_throttle && !pe_flagged &&
6836 	    (bp != un->un_recov_buf)) {
6837 		st_start(un);
6838 	}
6839 
6840 	un->un_retry_ct = max(pktinfo->pkt_retry_cnt, pktinfo->str_retry_cnt);
6841 
6842 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6843 		/*
6844 		 * Since we marked this ourselves as ASYNC,
6845 		 * there isn't anybody around waiting for
6846 		 * completion any more.
6847 		 */
6848 		uchar_t *cmd = pkt->pkt_cdbp;
6849 		if (*cmd == SCMD_READ || *cmd == SCMD_WRITE) {
6850 			bp->b_un.b_addr = (caddr_t)0;
6851 		}
6852 		ST_DEBUG(ST_DEVINFO, st_label, CE_NOTE,
6853 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6854 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
6855 		    "CDB sent with B_ASYNC",  (caddr_t)cmd);
6856 		if (pkt) {
6857 			scsi_destroy_pkt(pkt);
6858 		}
6859 		un->un_sbuf_busy = 0;
6860 		cv_signal(&un->un_sbuf_cv);
6861 		mutex_exit(ST_MUTEX);
6862 		return;
6863 	}
6864 
6865 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6866 		/*
6867 		 * Copy status from scsi_pkt to uscsi_cmd
6868 		 * since st_uscsi_cmd needs it
6869 		 */
6870 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6871 	}
6872 
6873 
6874 #ifdef STDEBUG
6875 	if (((st_debug & 0x7) >= 4) &&
6876 	    (((un->un_pos.blkno % 100) == 0) ||
6877 	    (un->un_persistence && un->un_persist_errors))) {
6878 
6879 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6880 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6881 		    "un_errno = %d, un_pe = %d\n",
6882 		    un->un_ncmds, un->un_throttle, un->un_errno,
6883 		    un->un_persist_errors);
6884 	}
6885 
6886 #endif
6887 
6888 	mutex_exit(ST_MUTEX);
6889 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6890 	    "st_done_and_mutex_exit: freeing pkt\n");
6891 
6892 	if (pkt) {
6893 		scsi_destroy_pkt(pkt);
6894 	}
6895 
6896 	biodone(bp);
6897 
6898 	/*
6899 	 * now that we biodoned that command, if persistent errors have been
6900 	 * flagged, flush the waitq
6901 	 */
6902 	if (pe_flagged)
6903 		st_flush(un);
6904 }
6905 
6906 
6907 /*
6908  * Tape error, flush tape driver queue.
6909  */
6910 static void
6911 st_flush(struct scsi_tape *un)
6912 {
6913 	struct buf *bp;
6914 
6915 	ST_FUNC(ST_DEVINFO, st_flush);
6916 
6917 	mutex_enter(ST_MUTEX);
6918 
6919 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6920 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6921 	    un->un_ncmds, (void *)un->un_quef);
6922 
6923 	/*
6924 	 * if we still have commands outstanding, wait for them to come in
6925 	 * before flushing the queue, and make sure there is a queue
6926 	 */
6927 	if (un->un_ncmds || !un->un_quef)
6928 		goto exit;
6929 
6930 	/*
6931 	 * we have no more commands outstanding, so let's deal with special
6932 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6933 	 * is 0, then we know there was no error and we return a 0 read or
6934 	 * write before showing errors
6935 	 */
6936 
6937 	/* Flush the wait queue. */
6938 	while ((bp = un->un_quef) != NULL) {
6939 		un->un_quef = bp->b_actf;
6940 
6941 		bp->b_resid = bp->b_bcount;
6942 
6943 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6944 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6945 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6946 
6947 		st_set_pe_errno(un);
6948 
6949 		bioerror(bp, un->un_errno);
6950 
6951 		mutex_exit(ST_MUTEX);
6952 		/* it should have one, but check anyway */
6953 		if (BP_PKT(bp)) {
6954 			scsi_destroy_pkt(BP_PKT(bp));
6955 		}
6956 		biodone(bp);
6957 		mutex_enter(ST_MUTEX);
6958 	}
6959 
6960 	/*
6961 	 * It's not a bad practice to reset the
6962 	 * waitq tail pointer to NULL.
6963 	 */
6964 	un->un_quel = NULL;
6965 
6966 exit:
6967 	/* we mucked with the queue, so let others know about it */
6968 	cv_signal(&un->un_queue_cv);
6969 	mutex_exit(ST_MUTEX);
6970 }
6971 
6972 
6973 /*
6974  * Utility functions
6975  */
6976 static int
6977 st_determine_generic(struct scsi_tape *un)
6978 {
6979 	int bsize;
6980 	static char *cart = "0.25 inch cartridge";
6981 	char *sizestr;
6982 
6983 	ST_FUNC(ST_DEVINFO, st_determine_generic);
6984 
6985 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6986 	    "st_determine_generic(un = 0x%p)\n", (void*)un);
6987 
6988 	ASSERT(mutex_owned(ST_MUTEX));
6989 
6990 	if (st_modesense(un)) {
6991 		return (-1);
6992 	}
6993 
6994 	bsize = (un->un_mspl->high_bl << 16)	|
6995 	    (un->un_mspl->mid_bl << 8)	|
6996 	    (un->un_mspl->low_bl);
6997 
6998 	if (bsize == 0) {
6999 		un->un_dp->options |= ST_VARIABLE;
7000 		un->un_dp->bsize = 0;
7001 		un->un_bsize = 0;
7002 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
7003 		/*
7004 		 * record size of this device too big.
7005 		 * try and convert it to variable record length.
7006 		 *
7007 		 */
7008 		un->un_dp->options |= ST_VARIABLE;
7009 		if (st_change_block_size(un, 0) != 0) {
7010 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7011 			    "Fixed Record Size %d is too large\n", bsize);
7012 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7013 			    "Cannot switch to variable record size\n");
7014 			un->un_dp->options &= ~ST_VARIABLE;
7015 			return (-1);
7016 		}
7017 	} else if (st_change_block_size(un, 0) == 0) {
7018 		/*
7019 		 * If the drive was set to a non zero block size,
7020 		 * See if it can be set to a zero block size.
7021 		 * If it works, ST_VARIABLE so user can set it as they want.
7022 		 */
7023 		un->un_dp->options |= ST_VARIABLE;
7024 		un->un_dp->bsize = 0;
7025 		un->un_bsize = 0;
7026 	} else {
7027 		un->un_dp->bsize = bsize;
7028 		un->un_bsize = bsize;
7029 	}
7030 
7031 
7032 	switch (un->un_mspl->density) {
7033 	default:
7034 	case 0x0:
7035 		/*
7036 		 * default density, cannot determine any other
7037 		 * information.
7038 		 */
7039 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
7040 		un->un_dp->type = ST_TYPE_DEFAULT;
7041 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
7042 		break;
7043 	case 0x1:
7044 	case 0x2:
7045 	case 0x3:
7046 	case 0x6:
7047 		/*
7048 		 * 1/2" reel
7049 		 */
7050 		sizestr = "0.50 inch reel";
7051 		un->un_dp->type = ST_TYPE_REEL;
7052 		un->un_dp->options |= ST_REEL;
7053 		un->un_dp->densities[0] = 0x1;
7054 		un->un_dp->densities[1] = 0x2;
7055 		un->un_dp->densities[2] = 0x6;
7056 		un->un_dp->densities[3] = 0x3;
7057 		break;
7058 	case 0x4:
7059 	case 0x5:
7060 	case 0x7:
7061 	case 0x0b:
7062 
7063 		/*
7064 		 * Quarter inch.
7065 		 */
7066 		sizestr = cart;
7067 		un->un_dp->type = ST_TYPE_DEFAULT;
7068 		un->un_dp->options |= ST_QIC;
7069 
7070 		un->un_dp->densities[1] = 0x4;
7071 		un->un_dp->densities[2] = 0x5;
7072 		un->un_dp->densities[3] = 0x7;
7073 		un->un_dp->densities[0] = 0x0b;
7074 		break;
7075 
7076 	case 0x0f:
7077 	case 0x10:
7078 	case 0x11:
7079 	case 0x12:
7080 		/*
7081 		 * QIC-120, QIC-150, QIC-320, QIC-600
7082 		 */
7083 		sizestr = cart;
7084 		un->un_dp->type = ST_TYPE_DEFAULT;
7085 		un->un_dp->options |= ST_QIC;
7086 		un->un_dp->densities[0] = 0x0f;
7087 		un->un_dp->densities[1] = 0x10;
7088 		un->un_dp->densities[2] = 0x11;
7089 		un->un_dp->densities[3] = 0x12;
7090 		break;
7091 
7092 	case 0x09:
7093 	case 0x0a:
7094 	case 0x0c:
7095 	case 0x0d:
7096 		/*
7097 		 * 1/2" cartridge tapes. Include HI-TC.
7098 		 */
7099 		sizestr = cart;
7100 		sizestr[2] = '5';
7101 		sizestr[3] = '0';
7102 		un->un_dp->type = ST_TYPE_HIC;
7103 		un->un_dp->densities[0] = 0x09;
7104 		un->un_dp->densities[1] = 0x0a;
7105 		un->un_dp->densities[2] = 0x0c;
7106 		un->un_dp->densities[3] = 0x0d;
7107 		break;
7108 
7109 	case 0x13:
7110 			/* DDS-2/DDS-3 scsi spec densities */
7111 	case 0x24:
7112 	case 0x25:
7113 	case 0x26:
7114 		sizestr = "DAT Data Storage (DDS)";
7115 		un->un_dp->type = ST_TYPE_DAT;
7116 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7117 		break;
7118 
7119 	case 0x14:
7120 		/*
7121 		 * Helical Scan (Exabyte) devices
7122 		 */
7123 		sizestr = "8mm helical scan cartridge";
7124 		un->un_dp->type = ST_TYPE_EXABYTE;
7125 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7126 		break;
7127 	}
7128 
7129 	/*
7130 	 * Assume LONG ERASE, BSF and BSR
7131 	 */
7132 
7133 	un->un_dp->options |=
7134 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
7135 
7136 	/*
7137 	 * Only if mode sense data says no buffered write, set NOBUF
7138 	 */
7139 	if (un->un_mspl->bufm == 0)
7140 		un->un_dp->options |= ST_NOBUF;
7141 
7142 	/*
7143 	 * set up large read and write retry counts
7144 	 */
7145 
7146 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
7147 
7148 	/*
7149 	 * If this is a 0.50 inch reel tape, and
7150 	 * it is *not* variable mode, try and
7151 	 * set it to variable record length
7152 	 * mode.
7153 	 */
7154 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
7155 	    (un->un_dp->options & ST_VARIABLE)) {
7156 		if (st_change_block_size(un, 0) == 0) {
7157 			un->un_dp->bsize = 0;
7158 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
7159 			    un->un_mspl->low_bl = 0;
7160 		}
7161 	}
7162 
7163 	/*
7164 	 * Write to console about type of device found
7165 	 */
7166 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
7167 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
7168 	    sizestr);
7169 	if (un->un_dp->options & ST_VARIABLE) {
7170 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7171 		    "!Variable record length I/O\n");
7172 	} else {
7173 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7174 		    "!Fixed record length (%d byte blocks) I/O\n",
7175 		    un->un_dp->bsize);
7176 	}
7177 	ASSERT(mutex_owned(ST_MUTEX));
7178 	return (0);
7179 }
7180 
7181 static int
7182 st_determine_density(struct scsi_tape *un, int rw)
7183 {
7184 	int rval = 0;
7185 
7186 	ST_FUNC(ST_DEVINFO, st_determine_density);
7187 
7188 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7189 	    "st_determine_density(un = 0x%p, rw = %s)\n",
7190 	    (void*)un, (rw == B_WRITE ? wr_str: rd_str));
7191 
7192 	ASSERT(mutex_owned(ST_MUTEX));
7193 
7194 	/*
7195 	 * If we're past BOT, density is determined already.
7196 	 */
7197 	if (un->un_pos.pmode == logical) {
7198 		if (un->un_pos.lgclblkno != 0) {
7199 			goto exit;
7200 		}
7201 	} else if (un->un_pos.pmode == legacy) {
7202 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
7203 			/*
7204 			 * XXX: put in a bitch message about attempting to
7205 			 * XXX: change density past BOT.
7206 			 */
7207 			goto exit;
7208 		}
7209 	} else {
7210 		goto exit;
7211 	}
7212 	if ((un->un_pos.pmode == logical) &&
7213 	    (un->un_pos.lgclblkno != 0)) {
7214 		goto exit;
7215 	}
7216 
7217 
7218 	/*
7219 	 * If we're going to be writing, we set the density
7220 	 */
7221 	if (rw == 0 || rw == B_WRITE) {
7222 		/* un_curdens is used as an index into densities table */
7223 		un->un_curdens = MT_DENSITY(un->un_dev);
7224 		if (st_set_density(un)) {
7225 			rval = -1;
7226 		}
7227 		goto exit;
7228 	}
7229 
7230 	/*
7231 	 * If density is known already,
7232 	 * we don't have to get it again.(?)
7233 	 */
7234 	if (!un->un_density_known) {
7235 		if (st_get_density(un)) {
7236 			rval = -1;
7237 		}
7238 	}
7239 
7240 exit:
7241 	ASSERT(mutex_owned(ST_MUTEX));
7242 	return (rval);
7243 }
7244 
7245 
7246 /*
7247  * Try to determine density. We do this by attempting to read the
7248  * first record off the tape, cycling through the available density
7249  * codes as we go.
7250  */
7251 
7252 static int
7253 st_get_density(struct scsi_tape *un)
7254 {
7255 	int succes = 0, rval = -1, i;
7256 	uint_t size;
7257 	uchar_t dens, olddens;
7258 
7259 	ST_FUNC(ST_DEVINFO, st_get_density);
7260 
7261 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7262 	    "st_get_density(un = 0x%p)\n", (void*)un);
7263 
7264 	ASSERT(mutex_owned(ST_MUTEX));
7265 
7266 	/*
7267 	 * If Auto Density override is enabled The drive has
7268 	 * only one density and there is no point in attempting
7269 	 * find the correct one.
7270 	 *
7271 	 * Since most modern drives auto detect the density
7272 	 * and format of the recorded media before they come
7273 	 * ready. What this function does is a legacy behavior
7274 	 * and modern drives not only don't need it, The backup
7275 	 * utilities that do positioning via uscsi find the un-
7276 	 * expected rewinds problematic.
7277 	 *
7278 	 * The drives that need this are old reel to reel devices.
7279 	 * I took a swag and said they must be scsi-1 or older.
7280 	 * I don't beleave there will any of the newer devices
7281 	 * that need this. There will be some scsi-1 devices that
7282 	 * don't need this but I don't think they will be using the
7283 	 * BIG aftermarket backup and restore utilitys.
7284 	 */
7285 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
7286 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
7287 		un->un_density_known = 1;
7288 		rval = 0;
7289 		goto exit;
7290 	}
7291 
7292 	/*
7293 	 * This will only work on variable record length tapes
7294 	 * if and only if all variable record length tapes autodensity
7295 	 * select.
7296 	 */
7297 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
7298 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
7299 
7300 	/*
7301 	 * Start at the specified density
7302 	 */
7303 
7304 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
7305 
7306 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
7307 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
7308 		/*
7309 		 * If we've done this density before,
7310 		 * don't bother to do it again.
7311 		 */
7312 		dens = un->un_dp->densities[un->un_curdens];
7313 		if (i > 0 && dens == olddens)
7314 			continue;
7315 		olddens = dens;
7316 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7317 		    "trying density 0x%x\n", dens);
7318 		if (st_set_density(un)) {
7319 			continue;
7320 		}
7321 
7322 		/*
7323 		 * XXX - the creates lots of headaches and slowdowns - must
7324 		 * fix.
7325 		 */
7326 		succes = (st_cmd(un, SCMD_READ, (int)size, SYNC_CMD) == 0);
7327 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
7328 			break;
7329 		}
7330 		if (succes) {
7331 			st_init(un);
7332 			rval = 0;
7333 			un->un_density_known = 1;
7334 			break;
7335 		}
7336 	}
7337 	kmem_free(un->un_tmpbuf, size);
7338 	un->un_tmpbuf = 0;
7339 
7340 exit:
7341 	ASSERT(mutex_owned(ST_MUTEX));
7342 	return (rval);
7343 }
7344 
7345 static int
7346 st_set_density(struct scsi_tape *un)
7347 {
7348 	int rval = 0;
7349 
7350 	ST_FUNC(ST_DEVINFO, st_set_density);
7351 
7352 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7353 	    "st_set_density(un = 0x%p): density = 0x%x\n", (void*)un,
7354 	    un->un_dp->densities[un->un_curdens]);
7355 
7356 	ASSERT(mutex_owned(ST_MUTEX));
7357 
7358 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7359 
7360 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
7361 		/*
7362 		 * If auto density override is not set, Use mode select
7363 		 * to set density and compression.
7364 		 */
7365 		if (st_modeselect(un)) {
7366 			rval = -1;
7367 		}
7368 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
7369 		/*
7370 		 * If auto density and mode select compression are set,
7371 		 * This is a drive with one density code but compression
7372 		 * can be enabled or disabled.
7373 		 * Set compression but no need to set density.
7374 		 */
7375 		rval = st_set_compression(un);
7376 		if ((rval != 0) && (rval != EALREADY)) {
7377 			rval = -1;
7378 		} else {
7379 			rval = 0;
7380 		}
7381 	}
7382 
7383 	/* If sucessful set density and/or compression, mark density known */
7384 	if (rval == 0) {
7385 		un->un_density_known = 1;
7386 	}
7387 
7388 	ASSERT(mutex_owned(ST_MUTEX));
7389 	return (rval);
7390 }
7391 
7392 static int
7393 st_loadtape(struct scsi_tape *un)
7394 {
7395 	int rval;
7396 
7397 	ST_FUNC(ST_DEVINFO, st_loadtape);
7398 
7399 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7400 	    "st_loadtape(un = 0x%p)\n", (void*) un);
7401 
7402 	ASSERT(mutex_owned(ST_MUTEX));
7403 
7404 	rval = st_update_block_pos(un, st_cmd, 0);
7405 	if (rval == EACCES) {
7406 		return (rval);
7407 	}
7408 
7409 	/*
7410 	 * 'LOAD' the tape to BOT by rewinding
7411 	 */
7412 	rval = st_cmd(un, SCMD_REWIND, 1, SYNC_CMD);
7413 	if (rval == 0) {
7414 		st_init(un);
7415 		un->un_density_known = 0;
7416 	}
7417 
7418 	ASSERT(mutex_owned(ST_MUTEX));
7419 	return (rval);
7420 }
7421 
7422 
7423 /*
7424  * Note: QIC devices aren't so smart.  If you try to append
7425  * after EOM, the write can fail because the device doesn't know
7426  * it's at EOM.	 In that case, issue a read.  The read should fail
7427  * because there's no data, but the device knows it's at EOM,
7428  * so a subsequent write should succeed.  To further confuse matters,
7429  * the target returns the same error if the tape is positioned
7430  * such that a write would overwrite existing data.  That's why
7431  * we have to do the append test.  A read in the middle of
7432  * recorded data would succeed, thus indicating we're attempting
7433  * something illegal.
7434  */
7435 
7436 
7437 static void
7438 st_test_append(struct buf *bp)
7439 {
7440 	dev_t dev = bp->b_edev;
7441 	struct scsi_tape *un;
7442 	uchar_t status;
7443 	unsigned bcount;
7444 
7445 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7446 
7447 	ST_FUNC(ST_DEVINFO, st_test_append);
7448 
7449 	ASSERT(mutex_owned(ST_MUTEX));
7450 
7451 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7452 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7453 
7454 	un->un_laststate = un->un_state;
7455 	un->un_state = ST_STATE_APPEND_TESTING;
7456 	un->un_test_append = 0;
7457 
7458 	/*
7459 	 * first, map in the buffer, because we're doing a double write --
7460 	 * first into the kernel, then onto the tape.
7461 	 */
7462 	bp_mapin(bp);
7463 
7464 	/*
7465 	 * get a copy of the data....
7466 	 */
7467 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7468 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7469 
7470 	/*
7471 	 * attempt the write..
7472 	 */
7473 
7474 	if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7475 success:
7476 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7477 		    "append write succeeded\n");
7478 		bp->b_resid = un->un_sbufp->b_resid;
7479 		mutex_exit(ST_MUTEX);
7480 		bcount = (unsigned)bp->b_bcount;
7481 		biodone(bp);
7482 		mutex_enter(ST_MUTEX);
7483 		un->un_laststate = un->un_state;
7484 		un->un_state = ST_STATE_OPEN;
7485 		kmem_free(un->un_tmpbuf, bcount);
7486 		un->un_tmpbuf = NULL;
7487 		return;
7488 	}
7489 
7490 	/*
7491 	 * The append failed. Do a short read. If that fails,  we are at EOM
7492 	 * so we can retry the write command. If that succeeds, than we're
7493 	 * all screwed up (the controller reported a real error).
7494 	 *
7495 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7496 	 * XXX: block size?
7497 	 *
7498 	 */
7499 	status = un->un_status;
7500 	un->un_status = 0;
7501 	(void) st_cmd(un, SCMD_READ, SECSIZE, SYNC_CMD);
7502 	if (un->un_status == KEY_BLANK_CHECK) {
7503 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7504 		    "append at EOM\n");
7505 		/*
7506 		 * Okay- the read failed. We should actually have confused
7507 		 * the controller enough to allow writing. In any case, the
7508 		 * i/o is on its own from here on out.
7509 		 */
7510 		un->un_laststate = un->un_state;
7511 		un->un_state = ST_STATE_OPEN;
7512 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7513 		if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount,
7514 		    SYNC_CMD) == 0) {
7515 			goto success;
7516 		}
7517 	}
7518 
7519 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7520 	    "append write failed- not at EOM\n");
7521 	bp->b_resid = bp->b_bcount;
7522 	st_bioerror(bp, EIO);
7523 
7524 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7525 	    "st_test_append : EIO : append write failed - not at EOM");
7526 
7527 	/*
7528 	 * backspace one record to get back to where we were
7529 	 */
7530 	if (st_cmd(un, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7531 		un->un_pos.pmode = invalid;
7532 	}
7533 
7534 	un->un_err_resid = bp->b_resid;
7535 	un->un_status = status;
7536 
7537 	/*
7538 	 * Note: biodone will do a bp_mapout()
7539 	 */
7540 	mutex_exit(ST_MUTEX);
7541 	bcount = (unsigned)bp->b_bcount;
7542 	biodone(bp);
7543 	mutex_enter(ST_MUTEX);
7544 	un->un_laststate = un->un_state;
7545 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7546 	kmem_free(un->un_tmpbuf, bcount);
7547 	un->un_tmpbuf = NULL;
7548 }
7549 
7550 /*
7551  * Special command handler
7552  */
7553 
7554 /*
7555  * common st_cmd code. The fourth parameter states
7556  * whether the caller wishes to await the results
7557  * Note the release of the mutex during most of the function
7558  */
7559 static int
7560 st_cmd(struct scsi_tape *un, int com, int64_t count, int wait)
7561 {
7562 	struct buf *bp;
7563 	int err;
7564 	uint_t last_err_resid;
7565 
7566 	ST_FUNC(ST_DEVINFO, st_cmd);
7567 
7568 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7569 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %"PRIx64", wait = %d)\n",
7570 	    un->un_dev, com, count, wait);
7571 
7572 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7573 	ASSERT(mutex_owned(ST_MUTEX));
7574 
7575 #ifdef STDEBUG
7576 	if ((st_debug & 0x7)) {
7577 		st_debug_cmds(un, com, count, wait);
7578 	}
7579 #endif
7580 
7581 	st_wait_for_io(un);
7582 
7583 	/* check to see if this command requires the drive to be reserved */
7584 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7585 
7586 	if (err) {
7587 		return (err);
7588 	}
7589 
7590 	/*
7591 	 * A space command is not recoverable if we don't know were we
7592 	 * were when it was issued.
7593 	 */
7594 	if ((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) {
7595 		(void) st_update_block_pos(un, st_cmd, 0);
7596 	}
7597 
7598 	/*
7599 	 * Forground should not be doing anything while recovery is active.
7600 	 */
7601 	ASSERT(un->un_recov_buf_busy == 0);
7602 
7603 	while (un->un_sbuf_busy)
7604 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7605 	un->un_sbuf_busy = 1;
7606 
7607 	bp = un->un_sbufp;
7608 	bzero(bp, sizeof (buf_t));
7609 
7610 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7611 
7612 	err = st_setup_cmd(un, bp, com, count);
7613 
7614 	un->un_sbuf_busy = 0;
7615 
7616 	/*
7617 	 * If was a space command need to update logical block position.
7618 	 * Only do this if the command was sucessful or it will mask the fact
7619 	 * that the space command failed by promoting the pmode to logical.
7620 	 */
7621 	if (((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) &&
7622 	    (un->un_pos.pmode != invalid)) {
7623 		un->un_running.pmode = invalid;
7624 		last_err_resid = un->un_err_resid;
7625 		(void) st_update_block_pos(un, st_cmd, 1);
7626 		/*
7627 		 * Set running position to invalid so it updates on the
7628 		 * next command.
7629 		 */
7630 		un->un_running.pmode = invalid;
7631 		un->un_err_resid = last_err_resid;
7632 	}
7633 
7634 	cv_signal(&un->un_sbuf_cv);
7635 
7636 	return (err);
7637 }
7638 
7639 static int
7640 st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com, int64_t count)
7641 {
7642 	int err;
7643 	dev_t dev = un->un_dev;
7644 
7645 	ST_FUNC(ST_DEVINFO, st_setup_cmd);
7646 	/*
7647 	 * Set count to the actual size of the data tranfer.
7648 	 * For commands with no data transfer, set bp->b_bcount
7649 	 * to the value to be used when constructing the
7650 	 * cdb in st_make_cmd().
7651 	 */
7652 	switch (com) {
7653 	case SCMD_READ:
7654 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7655 		    "special read %"PRId64"\n", count);
7656 		bp->b_flags |= B_READ;
7657 		bp->b_un.b_addr = un->un_tmpbuf;
7658 		break;
7659 
7660 	case SCMD_WRITE:
7661 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7662 		    "special write %"PRId64"\n", count);
7663 		bp->b_un.b_addr = un->un_tmpbuf;
7664 		break;
7665 
7666 	case SCMD_WRITE_FILE_MARK:
7667 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7668 		    "write %"PRId64" file marks\n", count);
7669 		bp->b_bcount = count;
7670 		count = 0;
7671 		break;
7672 
7673 	case SCMD_REWIND:
7674 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7675 		bp->b_bcount = count;
7676 		count = 0;
7677 		break;
7678 
7679 	case SCMD_SPACE:
7680 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7681 		/*
7682 		 * If the user could have entered a number that will
7683 		 * not fit in the 12 bit count field of space(8),
7684 		 * use space(16).
7685 		 */
7686 		if (((int64_t)SPACE_CNT(count) > 0x7fffff) ||
7687 		    ((int64_t)SPACE_CNT(count) < -(0x7fffff))) {
7688 			com = SCMD_SPACE_G4;
7689 		}
7690 		bp->b_bcount = count;
7691 		count = 0;
7692 		break;
7693 
7694 	case SCMD_RESERVE:
7695 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7696 		bp->b_bcount = 0;
7697 		count = 0;
7698 		break;
7699 
7700 	case SCMD_RELEASE:
7701 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7702 		bp->b_bcount = 0;
7703 		count = 0;
7704 		break;
7705 
7706 	case SCMD_LOAD:
7707 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7708 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7709 		bp->b_bcount = count;
7710 		count = 0;
7711 		break;
7712 
7713 	case SCMD_ERASE:
7714 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7715 		    "erase tape\n");
7716 		bp->b_bcount = count;
7717 		count = 0;
7718 		break;
7719 
7720 	case SCMD_MODE_SENSE:
7721 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7722 		    "mode sense\n");
7723 		bp->b_flags |= B_READ;
7724 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7725 		break;
7726 
7727 	case SCMD_MODE_SELECT:
7728 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7729 		    "mode select\n");
7730 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7731 		break;
7732 
7733 	case SCMD_READ_BLKLIM:
7734 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7735 		    "read block limits\n");
7736 		bp->b_bcount = count;
7737 		bp->b_flags |= B_READ;
7738 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7739 		break;
7740 
7741 	case SCMD_TEST_UNIT_READY:
7742 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7743 		    "test unit ready\n");
7744 		bp->b_bcount = 0;
7745 		count = 0;
7746 		break;
7747 
7748 	case SCMD_DOORLOCK:
7749 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7750 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7751 		bp->b_bcount = count = 0;
7752 		break;
7753 
7754 	case SCMD_READ_POSITION:
7755 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7756 		    "read position\n");
7757 		switch (un->un_read_pos_type) {
7758 		case LONG_POS:
7759 			count = sizeof (tape_position_long_t);
7760 			break;
7761 		case EXT_POS:
7762 			count = min(count, sizeof (tape_position_ext_t));
7763 			break;
7764 		case SHORT_POS:
7765 			count = sizeof (tape_position_t);
7766 			break;
7767 		default:
7768 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7769 			    "Unknown read position type 0x%x in "
7770 			    "st_make_cmd()\n", un->un_read_pos_type);
7771 		}
7772 		bp->b_bcount = count;
7773 		bp->b_flags |= B_READ;
7774 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7775 		break;
7776 
7777 	default:
7778 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7779 		    "Unhandled scsi command 0x%x in st_setup_cmd()\n", com);
7780 	}
7781 
7782 	mutex_exit(ST_MUTEX);
7783 
7784 	if (count > 0) {
7785 		int flg = (bp->b_flags & B_READ) ? B_READ : B_WRITE;
7786 		/*
7787 		 * We're going to do actual I/O.
7788 		 * Set things up for physio.
7789 		 */
7790 		struct iovec aiov;
7791 		struct uio auio;
7792 		struct uio *uio = &auio;
7793 
7794 		bzero(&auio, sizeof (struct uio));
7795 		bzero(&aiov, sizeof (struct iovec));
7796 		aiov.iov_base = bp->b_un.b_addr;
7797 		aiov.iov_len = count;
7798 
7799 		uio->uio_iov = &aiov;
7800 		uio->uio_iovcnt = 1;
7801 		uio->uio_resid = aiov.iov_len;
7802 		uio->uio_segflg = UIO_SYSSPACE;
7803 
7804 		/*
7805 		 * Let physio do the rest...
7806 		 */
7807 		bp->b_forw = (struct buf *)(uintptr_t)com;
7808 		bp->b_back = NULL;
7809 		err = physio(st_strategy, bp, dev, flg, st_minphys, uio);
7810 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7811 		    "st_setup_cmd: physio returns %d\n", err);
7812 	} else {
7813 		/*
7814 		 * Mimic physio
7815 		 */
7816 		bp->b_forw = (struct buf *)(uintptr_t)com;
7817 		bp->b_back = NULL;
7818 		bp->b_edev = dev;
7819 		bp->b_dev = cmpdev(dev);
7820 		bp->b_blkno = 0;
7821 		bp->b_resid = 0;
7822 		(void) st_strategy(bp);
7823 		if (bp->b_flags & B_ASYNC) {
7824 			/*
7825 			 * This is an async command- the caller won't wait
7826 			 * and doesn't care about errors.
7827 			 */
7828 			mutex_enter(ST_MUTEX);
7829 			return (0);
7830 		}
7831 
7832 		/*
7833 		 * BugTraq #4260046
7834 		 * ----------------
7835 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7836 		 * unconditionally. The old comment said...
7837 		 *
7838 		 * "if strategy was flagged with  persistent errors, we would
7839 		 *  have an error here, and the bp would never be sent, so we
7840 		 *  don't want to wait on a bp that was never sent...or hang"
7841 		 *
7842 		 * The new rationale, courtesy of Chitrank...
7843 		 *
7844 		 * "we should unconditionally biowait() here because
7845 		 *  st_strategy() will do a biodone() in the persistent error
7846 		 *  case and the following biowait() will return immediately.
7847 		 *  If not, in the case of "errors after pkt alloc" in
7848 		 *  st_start(), we will not biowait here which will cause the
7849 		 *  next biowait() to return immediately which will cause
7850 		 *  us to send out the next command. In the case where both of
7851 		 *  these use the sbuf, when the first command completes we'll
7852 		 *  free the packet attached to sbuf and the same pkt will
7853 		 *  get freed again when we complete the second command.
7854 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7855 		 *  st_start() for the pkt alloc failure case because physio()
7856 		 *  does biowait() and will hang if we don't do biodone()"
7857 		 */
7858 
7859 		err = biowait(bp);
7860 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7861 		    "st_setup_cmd: biowait returns %d\n", err);
7862 	}
7863 
7864 	mutex_enter(ST_MUTEX);
7865 
7866 	return (err);
7867 }
7868 
7869 static int
7870 st_set_compression(struct scsi_tape *un)
7871 {
7872 	int rval;
7873 	int turn_compression_on;
7874 	minor_t minor;
7875 
7876 	ST_FUNC(ST_DEVINFO, st_set_compression);
7877 
7878 	/*
7879 	 * Drive either dosn't have compression or it is controlled with
7880 	 * special density codes. Return ENOTTY so caller
7881 	 * knows nothing was done.
7882 	 */
7883 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7884 		un->un_comp_page = 0;
7885 		return (ENOTTY);
7886 	}
7887 
7888 	/* set compression based on minor node opened */
7889 	minor = MT_DENSITY(un->un_dev);
7890 
7891 	/*
7892 	 * If this the compression density or
7893 	 * the drive has two densities and uses mode select for
7894 	 * control of compression turn on compression for MT_DENSITY2
7895 	 * as well.
7896 	 */
7897 	if ((minor == ST_COMPRESSION_DENSITY) ||
7898 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7899 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7900 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7901 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7902 
7903 		turn_compression_on = 1;
7904 	} else {
7905 		turn_compression_on = 0;
7906 	}
7907 
7908 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7909 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7910 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7911 
7912 	/*
7913 	 * Need to determine which page does the device use for compression.
7914 	 * First try the data compression page. If this fails try the device
7915 	 * configuration page
7916 	 */
7917 
7918 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7919 		rval = st_set_datacomp_page(un, turn_compression_on);
7920 		if (rval == EALREADY) {
7921 			return (rval);
7922 		}
7923 		if (rval != 0) {
7924 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7925 				/*
7926 				 * This device does not support data
7927 				 * compression page
7928 				 */
7929 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7930 			} else if (un->un_state >= ST_STATE_OPEN) {
7931 				un->un_pos.pmode = invalid;
7932 				rval = EIO;
7933 			} else {
7934 				rval = -1;
7935 			}
7936 		} else {
7937 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7938 		}
7939 	}
7940 
7941 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7942 		rval = st_set_devconfig_page(un, turn_compression_on);
7943 		if (rval == EALREADY) {
7944 			return (rval);
7945 		}
7946 		if (rval != 0) {
7947 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7948 				/*
7949 				 * This device does not support
7950 				 * compression at all advice the
7951 				 * user and unset ST_MODE_SEL_COMP
7952 				 */
7953 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7954 				un->un_comp_page = 0;
7955 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7956 				    "Device Does Not Support Compression\n");
7957 			} else if (un->un_state >= ST_STATE_OPEN) {
7958 				un->un_pos.pmode = invalid;
7959 				rval = EIO;
7960 			} else {
7961 				rval = -1;
7962 			}
7963 		}
7964 	}
7965 
7966 	return (rval);
7967 }
7968 
7969 /*
7970  * set or unset compression thru device configuration page.
7971  */
7972 static int
7973 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
7974 {
7975 	unsigned char cflag;
7976 	int rval = 0;
7977 
7978 
7979 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
7980 
7981 	ASSERT(mutex_owned(ST_MUTEX));
7982 
7983 	/*
7984 	 * if the mode sense page is not the correct one, load the correct one.
7985 	 */
7986 	if (un->un_mspl->page_code != ST_DEV_CONFIG_PAGE) {
7987 		rval = st_gen_mode_sense(un, st_uscsi_cmd, ST_DEV_CONFIG_PAGE,
7988 		    un->un_mspl, sizeof (struct seq_mode));
7989 		if (rval)
7990 			return (rval);
7991 	}
7992 
7993 	/*
7994 	 * Figure what to set compression flag to.
7995 	 */
7996 	if (compression_on) {
7997 		/* They have selected a compression node */
7998 		if (un->un_dp->type == ST_TYPE_FUJI) {
7999 			cflag = 0x84;   /* use EDRC */
8000 		} else {
8001 			cflag = ST_DEV_CONFIG_DEF_COMP;
8002 		}
8003 	} else {
8004 		cflag = ST_DEV_CONFIG_NO_COMP;
8005 	}
8006 
8007 	/*
8008 	 * If compression is already set the way it was requested.
8009 	 * And if this not the first time we has tried.
8010 	 */
8011 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
8012 	    (un->un_comp_page == ST_DEV_CONFIG_PAGE)) {
8013 		return (EALREADY);
8014 	}
8015 
8016 	un->un_mspl->page.dev.comp_alg = cflag;
8017 	/*
8018 	 * need to send mode select even if correct compression is
8019 	 * already set since need to set density code
8020 	 */
8021 
8022 #ifdef STDEBUG
8023 	if ((st_debug & 0x7) >= 6) {
8024 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8025 		    "st_set_devconfig_page: sense data for mode select",
8026 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8027 	}
8028 #endif
8029 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8030 	    sizeof (struct seq_mode));
8031 
8032 	return (rval);
8033 }
8034 
8035 /*
8036  * set/reset compression bit thru data compression page
8037  */
8038 static int
8039 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
8040 {
8041 	int compression_on_already;
8042 	int rval = 0;
8043 
8044 
8045 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
8046 
8047 	ASSERT(mutex_owned(ST_MUTEX));
8048 
8049 	/*
8050 	 * if the mode sense page is not the correct one, load the correct one.
8051 	 */
8052 	if (un->un_mspl->page_code != ST_DEV_DATACOMP_PAGE) {
8053 		rval = st_gen_mode_sense(un, st_uscsi_cmd, ST_DEV_DATACOMP_PAGE,
8054 		    un->un_mspl, sizeof (struct seq_mode));
8055 		if (rval)
8056 			return (rval);
8057 	}
8058 
8059 	/*
8060 	 * If drive is not capable of compression (at this time)
8061 	 * return EALREADY so caller doesn't think that this page
8062 	 * is not supported. This check is for drives that can
8063 	 * disable compression from the front panel or configuration.
8064 	 * I doubt that a drive that supports this page is not really
8065 	 * capable of compression.
8066 	 */
8067 	if (un->un_mspl->page.comp.dcc == 0) {
8068 		return (EALREADY);
8069 	}
8070 
8071 	/* See if compression currently turned on */
8072 	if (un->un_mspl->page.comp.dce) {
8073 		compression_on_already = 1;
8074 	} else {
8075 		compression_on_already = 0;
8076 	}
8077 
8078 	/*
8079 	 * If compression is already set the way it was requested.
8080 	 * And if this not the first time we has tried.
8081 	 */
8082 	if ((compression_on == compression_on_already) &&
8083 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
8084 		return (EALREADY);
8085 	}
8086 
8087 	/*
8088 	 * if we are already set to the appropriate compression
8089 	 * mode, don't set it again
8090 	 */
8091 	if (compression_on) {
8092 		/* compression selected */
8093 		un->un_mspl->page.comp.dce = 1;
8094 	} else {
8095 		un->un_mspl->page.comp.dce = 0;
8096 	}
8097 
8098 
8099 #ifdef STDEBUG
8100 	if ((st_debug & 0x7) >= 6) {
8101 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8102 		    "st_set_datacomp_page: sense data for mode select",
8103 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8104 	}
8105 #endif
8106 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8107 	    sizeof (struct seq_mode));
8108 
8109 	return (rval);
8110 }
8111 
8112 static int
8113 st_modesense(struct scsi_tape *un)
8114 {
8115 	int rval;
8116 	uchar_t page;
8117 
8118 	ST_FUNC(ST_DEVINFO, st_modesense);
8119 
8120 	page = un->un_comp_page;
8121 
8122 	switch (page) {
8123 	case ST_DEV_DATACOMP_PAGE:
8124 	case ST_DEV_CONFIG_PAGE: /* FALLTHROUGH */
8125 		rval = st_gen_mode_sense(un, st_uscsi_cmd, page, un->un_mspl,
8126 		    sizeof (struct seq_mode));
8127 		break;
8128 
8129 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
8130 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
8131 			page = ST_DEV_DATACOMP_PAGE;
8132 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8133 			    un->un_mspl, sizeof (struct seq_mode));
8134 			if (rval == 0 && un->un_mspl->page_code == page) {
8135 				un->un_comp_page = page;
8136 				break;
8137 			}
8138 			page = ST_DEV_CONFIG_PAGE;
8139 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8140 			    un->un_mspl, sizeof (struct seq_mode));
8141 			if (rval == 0 && un->un_mspl->page_code == page) {
8142 				un->un_comp_page = page;
8143 				break;
8144 			}
8145 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
8146 			un->un_comp_page = 0;
8147 		} else {
8148 			un->un_comp_page = 0;
8149 		}
8150 
8151 	default:	/* FALLTHROUGH */
8152 		rval = st_cmd(un, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
8153 	}
8154 	return (rval);
8155 }
8156 
8157 static int
8158 st_modeselect(struct scsi_tape *un)
8159 {
8160 	int rval = 0;
8161 	int ix;
8162 
8163 	ST_FUNC(ST_DEVINFO, st_modeselect);
8164 
8165 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8166 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
8167 	    un->un_dev, un->un_mspl->density);
8168 
8169 	ASSERT(mutex_owned(ST_MUTEX));
8170 
8171 	/*
8172 	 * The parameter list should be the same for all of the
8173 	 * cases that follow so set them here
8174 	 *
8175 	 * Try mode select first if if fails set fields manually
8176 	 */
8177 	rval = st_modesense(un);
8178 	if (rval != 0) {
8179 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8180 		    "st_modeselect: First mode sense failed\n");
8181 		un->un_mspl->bd_len  = 8;
8182 		un->un_mspl->high_nb = 0;
8183 		un->un_mspl->mid_nb  = 0;
8184 		un->un_mspl->low_nb  = 0;
8185 	}
8186 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
8187 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
8188 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
8189 
8190 
8191 	/*
8192 	 * If configured to use a specific density code for a media type.
8193 	 * curdens is previously set by the minor node opened.
8194 	 * If the media type doesn't match the minor node we change it so it
8195 	 * looks like the correct one was opened.
8196 	 */
8197 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
8198 		uchar_t best;
8199 
8200 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
8201 			if (un->un_mspl->media_type ==
8202 			    un->un_dp->mediatype[ix]) {
8203 				best = ix;
8204 				/*
8205 				 * It matches but it might not be the only one.
8206 				 * Use the highest matching media type but not
8207 				 * to exceed the density selected by the open.
8208 				 */
8209 				if (ix < un->un_curdens) {
8210 					continue;
8211 				}
8212 				un->un_curdens = ix;
8213 				break;
8214 			}
8215 		}
8216 		/* If a match was found best will not be 0xff any more */
8217 		if (best < NDENSITIES) {
8218 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8219 			    "found media 0x%X using density 0x%X\n",
8220 			    un->un_mspl->media_type,
8221 			    un->un_dp->densities[best]);
8222 			un->un_mspl->density = un->un_dp->densities[best];
8223 		} else {
8224 			/* Otherwise set density based on minor node opened */
8225 			un->un_mspl->density =
8226 			    un->un_dp->densities[un->un_curdens];
8227 		}
8228 	} else {
8229 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
8230 	}
8231 
8232 	if (un->un_dp->options & ST_NOBUF) {
8233 		un->un_mspl->bufm = 0;
8234 	} else {
8235 		un->un_mspl->bufm = 1;
8236 	}
8237 
8238 	rval = st_set_compression(un);
8239 
8240 	/*
8241 	 * If st_set_compression returned invalid or already it
8242 	 * found no need to do the mode select.
8243 	 * So do it here.
8244 	 */
8245 	if ((rval == ENOTTY) || (rval == EALREADY)) {
8246 
8247 		/* Zero non-writeable fields */
8248 		un->un_mspl->data_len = 0;
8249 		un->un_mspl->media_type = 0;
8250 		un->un_mspl->wp = 0;
8251 
8252 		/* need to set the density code */
8253 		rval = st_cmd(un, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
8254 		if (rval != 0) {
8255 			if (un->un_state >= ST_STATE_OPEN) {
8256 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8257 				    "unable to set tape mode\n");
8258 				un->un_pos.pmode = invalid;
8259 				rval = EIO;
8260 			} else {
8261 				rval = -1;
8262 			}
8263 		}
8264 	}
8265 
8266 	/*
8267 	 * The spec recommends to send a mode sense after a mode select
8268 	 */
8269 	(void) st_modesense(un);
8270 
8271 	ASSERT(mutex_owned(ST_MUTEX));
8272 
8273 	return (rval);
8274 }
8275 
8276 /*
8277  * st_gen_mode_sense
8278  *
8279  * generic mode sense.. it allows for any page
8280  */
8281 static int
8282 st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
8283     struct seq_mode *page_data, int page_size)
8284 {
8285 
8286 	int r;
8287 	char	cdb[CDB_GROUP0];
8288 	struct uscsi_cmd *com;
8289 	struct scsi_arq_status status;
8290 
8291 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
8292 
8293 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8294 
8295 	bzero(cdb, CDB_GROUP0);
8296 	cdb[0] = SCMD_MODE_SENSE;
8297 	cdb[2] = (char)page;
8298 	cdb[4] = (char)page_size;
8299 
8300 	com->uscsi_cdb = cdb;
8301 	com->uscsi_cdblen = CDB_GROUP0;
8302 	com->uscsi_bufaddr = (caddr_t)page_data;
8303 	com->uscsi_buflen = page_size;
8304 	com->uscsi_rqlen = sizeof (status);
8305 	com->uscsi_rqbuf = (caddr_t)&status;
8306 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8307 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8308 
8309 	r = ubf(un, com, FKIOCTL);
8310 	kmem_free(com, sizeof (*com));
8311 	return (r);
8312 }
8313 
8314 /*
8315  * st_gen_mode_select
8316  *
8317  * generic mode select.. it allows for any page
8318  */
8319 static int
8320 st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
8321     struct seq_mode *page_data, int page_size)
8322 {
8323 
8324 	int r;
8325 	char cdb[CDB_GROUP0];
8326 	struct uscsi_cmd *com;
8327 	struct scsi_arq_status status;
8328 
8329 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
8330 
8331 	/* Zero non-writeable fields */
8332 	page_data->data_len = 0;
8333 	page_data->media_type = 0;
8334 	page_data->wp = 0;
8335 
8336 	/*
8337 	 * If mode select has any page data, zero the ps (Page Savable) bit.
8338 	 */
8339 	if (page_size > MSIZE) {
8340 		page_data->ps = 0;
8341 	}
8342 
8343 
8344 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8345 
8346 	/*
8347 	 * then, do a mode select to set what ever info
8348 	 */
8349 	bzero(cdb, CDB_GROUP0);
8350 	cdb[0] = SCMD_MODE_SELECT;
8351 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
8352 	cdb[4] = (char)page_size;
8353 
8354 	com->uscsi_cdb = cdb;
8355 	com->uscsi_cdblen = CDB_GROUP0;
8356 	com->uscsi_bufaddr = (caddr_t)page_data;
8357 	com->uscsi_buflen = page_size;
8358 	com->uscsi_rqlen = sizeof (status);
8359 	com->uscsi_rqbuf = (caddr_t)&status;
8360 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8361 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_WRITE;
8362 
8363 	r = ubf(un, com, FKIOCTL);
8364 
8365 	kmem_free(com, sizeof (*com));
8366 	return (r);
8367 }
8368 
8369 static int
8370 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
8371 {
8372 	int rval;
8373 	char cdb[CDB_GROUP0];
8374 	struct uscsi_cmd *com;
8375 	struct scsi_arq_status status;
8376 
8377 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
8378 
8379 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8380 
8381 	bzero(cdb, CDB_GROUP0);
8382 	cdb[0] = SCMD_READ_BLKLIM;
8383 
8384 	com->uscsi_cdb = cdb;
8385 	com->uscsi_cdblen = CDB_GROUP0;
8386 	com->uscsi_bufaddr = (caddr_t)read_blk;
8387 	com->uscsi_buflen = sizeof (struct read_blklim);
8388 	com->uscsi_rqlen = sizeof (status);
8389 	com->uscsi_rqbuf = (caddr_t)&status;
8390 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8391 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8392 
8393 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8394 	if (com->uscsi_status || com->uscsi_resid) {
8395 		rval = -1;
8396 	}
8397 
8398 	kmem_free(com, sizeof (*com));
8399 	return (rval);
8400 }
8401 
8402 static int
8403 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
8404     size_t buflen)
8405 {
8406 	int rval;
8407 	char cdb[CDB_GROUP1];
8408 	struct uscsi_cmd *com;
8409 	struct scsi_arq_status status;
8410 
8411 	ST_FUNC(ST_DEVINFO, st_report_density_support);
8412 
8413 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8414 
8415 	bzero(cdb, CDB_GROUP1);
8416 	cdb[0] = SCMD_REPORT_DENSITIES;
8417 	cdb[7] = (buflen & 0xff00) >> 8;
8418 	cdb[8] = buflen & 0xff;
8419 
8420 	com->uscsi_cdb = cdb;
8421 	com->uscsi_cdblen = CDB_GROUP1;
8422 	com->uscsi_bufaddr = (caddr_t)density_data;
8423 	com->uscsi_buflen = buflen;
8424 	com->uscsi_rqlen = sizeof (status);
8425 	com->uscsi_rqbuf = (caddr_t)&status;
8426 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8427 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8428 
8429 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8430 	if (com->uscsi_status || com->uscsi_resid) {
8431 		rval = -1;
8432 	}
8433 
8434 	kmem_free(com, sizeof (*com));
8435 	return (rval);
8436 }
8437 
8438 static int
8439 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
8440     uchar_t option_code, ushort_t service_action)
8441 {
8442 	int rval;
8443 	char cdb[CDB_GROUP5];
8444 	struct uscsi_cmd *com;
8445 	struct scsi_arq_status status;
8446 	uint32_t allo_length;
8447 
8448 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
8449 
8450 	allo_length = sizeof (struct one_com_des) +
8451 	    sizeof (struct com_timeout_des);
8452 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8453 
8454 	bzero(cdb, CDB_GROUP5);
8455 	cdb[0] = (char)SCMD_MAINTENANCE_IN;
8456 	cdb[1] = SSVC_ACTION_GET_SUPPORTED_OPERATIONS;
8457 	if (service_action) {
8458 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
8459 		cdb[4] = (service_action & 0xff00) >> 8;
8460 		cdb[5] = service_action & 0xff;
8461 	} else {
8462 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
8463 		    0x80); /* RCTD */
8464 	}
8465 	cdb[3] = option_code;
8466 	cdb[6] = (allo_length & 0xff000000) >> 24;
8467 	cdb[7] = (allo_length & 0xff0000) >> 16;
8468 	cdb[8] = (allo_length & 0xff00) >> 8;
8469 	cdb[9] = allo_length & 0xff;
8470 
8471 	com->uscsi_cdb = cdb;
8472 	com->uscsi_cdblen = CDB_GROUP5;
8473 	com->uscsi_bufaddr = (caddr_t)oper_data;
8474 	com->uscsi_buflen = allo_length;
8475 	com->uscsi_rqlen = sizeof (status);
8476 	com->uscsi_rqbuf = (caddr_t)&status;
8477 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8478 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8479 
8480 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8481 	if (com->uscsi_status) {
8482 		rval = -1;
8483 	}
8484 
8485 	kmem_free(com, sizeof (*com));
8486 	return (rval);
8487 }
8488 
8489 /*
8490  * Changes devices blocksize and bsize to requested blocksize nblksz.
8491  * Returns returned value from first failed call or zero on success.
8492  */
8493 static int
8494 st_change_block_size(struct scsi_tape *un, uint32_t nblksz)
8495 {
8496 	struct seq_mode *current;
8497 	int rval;
8498 	uint32_t oldblksz;
8499 
8500 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8501 
8502 	current = kmem_zalloc(MSIZE, KM_SLEEP);
8503 
8504 	/*
8505 	 * If we haven't got the compression page yet, do that first.
8506 	 */
8507 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
8508 		(void) st_modesense(un);
8509 	}
8510 
8511 	/* Read current settings */
8512 	rval = st_gen_mode_sense(un, st_uscsi_cmd, 0, current, MSIZE);
8513 	if (rval != 0) {
8514 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8515 		    "mode sense for change block size failed: rval = %d", rval);
8516 		goto finish;
8517 	}
8518 
8519 	/* Figure the current block size */
8520 	oldblksz =
8521 	    (current->high_bl << 16) |
8522 	    (current->mid_bl << 8) |
8523 	    (current->low_bl);
8524 
8525 	/* If current block size is the same as requested were done */
8526 	if (oldblksz == nblksz) {
8527 		un->un_bsize = nblksz;
8528 		rval = 0;
8529 		goto finish;
8530 	}
8531 
8532 	/* Change to requested block size */
8533 	current->high_bl = (uchar_t)(nblksz >> 16);
8534 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8535 	current->low_bl  = (uchar_t)(nblksz);
8536 
8537 	/* Attempt to change block size */
8538 	rval = st_gen_mode_select(un, st_uscsi_cmd, current, MSIZE);
8539 	if (rval != 0) {
8540 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8541 		    "Set new block size failed: rval = %d", rval);
8542 		goto finish;
8543 	}
8544 
8545 	/* Read back and verify setting */
8546 	rval = st_modesense(un);
8547 	if (rval == 0) {
8548 		un->un_bsize =
8549 		    (un->un_mspl->high_bl << 16) |
8550 		    (un->un_mspl->mid_bl << 8) |
8551 		    (un->un_mspl->low_bl);
8552 
8553 		if (un->un_bsize != nblksz) {
8554 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8555 			    "Blocksize set does not equal requested blocksize"
8556 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8557 			rval = EIO;
8558 		}
8559 	}
8560 finish:
8561 	kmem_free(current, MSIZE);
8562 	return (rval);
8563 }
8564 
8565 
8566 static void
8567 st_init(struct scsi_tape *un)
8568 {
8569 	ST_FUNC(ST_DEVINFO, st_init);
8570 
8571 	ASSERT(mutex_owned(ST_MUTEX));
8572 
8573 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8574 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8575 	    un->un_dev);
8576 
8577 	un->un_pos.blkno = 0;
8578 	un->un_pos.fileno = 0;
8579 	un->un_lastop = ST_OP_NIL;
8580 	un->un_pos.eof = ST_NO_EOF;
8581 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8582 	if (st_error_level != SCSI_ERR_ALL) {
8583 		if (DEBUGGING) {
8584 			st_error_level = SCSI_ERR_ALL;
8585 		} else {
8586 			st_error_level = SCSI_ERR_RETRYABLE;
8587 		}
8588 	}
8589 }
8590 
8591 
8592 static void
8593 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8594 {
8595 	struct scsi_pkt *pkt;
8596 	struct uscsi_cmd *ucmd;
8597 	recov_info *ri;
8598 	int tval = 0;
8599 	int64_t count;
8600 	uint32_t additional = 0;
8601 	uint32_t address = 0;
8602 	union scsi_cdb *ucdb;
8603 	int flags = 0;
8604 	int cdb_len = CDB_GROUP0; /* default */
8605 	uchar_t com;
8606 	char fixbit;
8607 	char short_fm = 0;
8608 	optype prev_op = un->un_lastop;
8609 	int stat_size =
8610 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
8611 
8612 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8613 
8614 	ASSERT(mutex_owned(ST_MUTEX));
8615 
8616 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8617 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8618 
8619 
8620 	/*
8621 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8622 	 * Length Indicator bits on read/write commands, for setting
8623 	 * the Long bit on erase commands, and for setting the Code
8624 	 * Field bits on space commands.
8625 	 */
8626 
8627 	/* regular raw I/O */
8628 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
8629 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8630 		    CDB_GROUP0, stat_size, st_recov_sz, 0, func,
8631 		    (caddr_t)un);
8632 		if (pkt == NULL) {
8633 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8634 			    "Read Write scsi_init_pkt() failure\n");
8635 			goto exit;
8636 		}
8637 		ASSERT(pkt->pkt_resid == 0);
8638 #ifdef STDEBUG
8639 		bzero(pkt->pkt_private, st_recov_sz);
8640 		bzero(pkt->pkt_scbp, stat_size);
8641 #endif
8642 		ri = (recov_info *)pkt->pkt_private;
8643 		ri->privatelen = st_recov_sz;
8644 		if (un->un_bsize == 0) {
8645 			count = bp->b_bcount;
8646 			fixbit = 0;
8647 		} else {
8648 			count = bp->b_bcount / un->un_bsize;
8649 			fixbit = 1;
8650 		}
8651 		if (bp->b_flags & B_READ) {
8652 			com = SCMD_READ;
8653 			un->un_lastop = ST_OP_READ;
8654 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8655 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8656 				fixbit = 2;
8657 			}
8658 		} else {
8659 			com = SCMD_WRITE;
8660 			un->un_lastop = ST_OP_WRITE;
8661 		}
8662 		tval = un->un_dp->io_timeout;
8663 
8664 		/*
8665 		 * For really large xfers, increase timeout
8666 		 */
8667 		if (bp->b_bcount > (10 * ONE_MEG))
8668 			tval *= bp->b_bcount/(10 * ONE_MEG);
8669 
8670 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8671 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8672 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8673 
8674 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8675 		/*
8676 		 * uscsi - build command, allocate scsi resources
8677 		 */
8678 		st_make_uscsi_cmd(un, ucmd, bp, func);
8679 		goto exit;
8680 
8681 	} else {				/* special I/O */
8682 		struct buf *allocbp = NULL;
8683 		com = (uchar_t)(uintptr_t)bp->b_forw;
8684 		count = bp->b_bcount;
8685 
8686 		switch (com) {
8687 		case SCMD_READ:
8688 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8689 			    "special read %"PRId64"\n", count);
8690 			if (un->un_bsize == 0) {
8691 				fixbit = 2;	/* suppress SILI */
8692 			} else {
8693 				fixbit = 1;	/* Fixed Block Mode */
8694 				count /= un->un_bsize;
8695 			}
8696 			allocbp = bp;
8697 			un->un_lastop = ST_OP_READ;
8698 			tval = un->un_dp->io_timeout;
8699 			break;
8700 
8701 		case SCMD_WRITE:
8702 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8703 			    "special write %"PRId64"\n", count);
8704 			if (un->un_bsize != 0) {
8705 				fixbit = 1;	/* Fixed Block Mode */
8706 				count /= un->un_bsize;
8707 			} else {
8708 				fixbit = 0;
8709 			}
8710 			allocbp = bp;
8711 			un->un_lastop = ST_OP_WRITE;
8712 			tval = un->un_dp->io_timeout;
8713 			break;
8714 
8715 		case SCMD_WRITE_FILE_MARK:
8716 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8717 			    "write %"PRId64" file marks\n", count);
8718 			un->un_lastop = ST_OP_WEOF;
8719 			fixbit = 0;
8720 			tval = un->un_dp->io_timeout;
8721 			/*
8722 			 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8723 			 * device, set the Vendor Unique bit to
8724 			 * write Short File Mark.
8725 			 */
8726 			if ((un->un_dp->options & ST_SHORT_FILEMARKS) &&
8727 			    ((un->un_dp->type == ST_TYPE_EXB8500) ||
8728 			    (un->un_dp->type == ST_TYPE_EXABYTE))) {
8729 				/*
8730 				 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8731 				 * is set to to write Short File Mark
8732 				 */
8733 				short_fm = 1;
8734 			}
8735 			break;
8736 
8737 		case SCMD_REWIND:
8738 			/*
8739 			 * In the case of rewind we're gona do the rewind with
8740 			 * the immediate bit set so status will be retured when
8741 			 * the command is accepted by the device. We clear the
8742 			 * B_ASYNC flag so we wait for that acceptance.
8743 			 */
8744 			fixbit = 0;
8745 			if (bp->b_flags & B_ASYNC) {
8746 				allocbp = bp;
8747 				if (count) {
8748 					fixbit = 1;
8749 					bp->b_flags &= ~B_ASYNC;
8750 				}
8751 			}
8752 			count = 0;
8753 			bp->b_bcount = 0;
8754 			un->un_lastop = ST_OP_CTL;
8755 			tval = un->un_dp->rewind_timeout;
8756 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8757 			    "rewind\n");
8758 			break;
8759 
8760 		case SCMD_SPACE_G4:
8761 			cdb_len = CDB_GROUP4;
8762 			fixbit = SPACE_TYPE(bp->b_bcount);
8763 			count = SPACE_CNT(bp->b_bcount);
8764 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8765 			    " %s space %s %"PRId64" from file %d blk %d\n",
8766 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8767 			    space_strs[fixbit & 7], count,
8768 			    un->un_pos.fileno, un->un_pos.blkno);
8769 			address = (count >> 48) & 0x1fff;
8770 			additional = (count >> 16) & 0xffffffff;
8771 			count &= 0xffff;
8772 			count <<= 16;
8773 			un->un_lastop = ST_OP_CTL;
8774 			tval = un->un_dp->space_timeout;
8775 			break;
8776 
8777 		case SCMD_SPACE:
8778 			fixbit = SPACE_TYPE(bp->b_bcount);
8779 			count = SPACE_CNT(bp->b_bcount);
8780 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8781 			    " %s space %s %"PRId64" from file %d blk %d\n",
8782 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8783 			    space_strs[fixbit & 7], count,
8784 			    un->un_pos.fileno, un->un_pos.blkno);
8785 			count &= 0xffffffff;
8786 			un->un_lastop = ST_OP_CTL;
8787 			tval = un->un_dp->space_timeout;
8788 			break;
8789 
8790 		case SCMD_LOAD:
8791 			ASSERT(count < 10);
8792 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8793 			    "%s tape\n", load_strs[count]);
8794 			fixbit = 0;
8795 
8796 			/* Loading or Unloading */
8797 			if (count & LD_LOAD) {
8798 				tval = un->un_dp->load_timeout;
8799 			} else {
8800 				tval = un->un_dp->unload_timeout;
8801 			}
8802 			/* Is Retension requested */
8803 			if (count & LD_RETEN) {
8804 				tval += un->un_dp->rewind_timeout;
8805 			}
8806 			un->un_lastop = ST_OP_CTL;
8807 			break;
8808 
8809 		case SCMD_ERASE:
8810 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8811 			    "erase tape\n");
8812 			ASSERT(count == 1); /* mt sets this */
8813 			if (count == 1) {
8814 				/*
8815 				 * do long erase
8816 				 */
8817 				fixbit = 1; /* Long */
8818 
8819 				/* Drive might not honor immidiate bit */
8820 				tval = un->un_dp->erase_timeout;
8821 			} else {
8822 				/* Short Erase */
8823 				tval = un->un_dp->erase_timeout;
8824 				fixbit = 0;
8825 			}
8826 			un->un_lastop = ST_OP_CTL;
8827 			count = 0;
8828 			break;
8829 
8830 		case SCMD_MODE_SENSE:
8831 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8832 			    "mode sense\n");
8833 			allocbp = bp;
8834 			fixbit = 0;
8835 			tval = un->un_dp->non_motion_timeout;
8836 			un->un_lastop = ST_OP_CTL;
8837 			break;
8838 
8839 		case SCMD_MODE_SELECT:
8840 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8841 			    "mode select\n");
8842 			allocbp = bp;
8843 			fixbit = 0;
8844 			tval = un->un_dp->non_motion_timeout;
8845 			un->un_lastop = ST_OP_CTL;
8846 			break;
8847 
8848 		case SCMD_RESERVE:
8849 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8850 			    "reserve\n");
8851 			fixbit = 0;
8852 			tval = un->un_dp->non_motion_timeout;
8853 			un->un_lastop = ST_OP_CTL;
8854 			break;
8855 
8856 		case SCMD_RELEASE:
8857 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8858 			    "release\n");
8859 			fixbit = 0;
8860 			tval = un->un_dp->non_motion_timeout;
8861 			un->un_lastop = ST_OP_CTL;
8862 			break;
8863 
8864 		case SCMD_READ_BLKLIM:
8865 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8866 			    "read block limits\n");
8867 			allocbp = bp;
8868 			fixbit = count = 0;
8869 			tval = un->un_dp->non_motion_timeout;
8870 			un->un_lastop = ST_OP_CTL;
8871 			break;
8872 
8873 		case SCMD_TEST_UNIT_READY:
8874 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8875 			    "test unit ready\n");
8876 			fixbit = 0;
8877 			tval = un->un_dp->non_motion_timeout;
8878 			un->un_lastop = ST_OP_CTL;
8879 			break;
8880 
8881 		case SCMD_DOORLOCK:
8882 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8883 			    "prevent/allow media removal\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_READ_POSITION:
8890 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8891 			    "read position\n");
8892 			fixbit = un->un_read_pos_type;
8893 			cdb_len = CDB_GROUP1;
8894 			tval = un->un_dp->non_motion_timeout;
8895 			allocbp = bp;
8896 			un->un_lastop = ST_OP_CTL;
8897 			switch (un->un_read_pos_type) {
8898 			case LONG_POS:
8899 				count = 0;
8900 				break;
8901 			case EXT_POS:
8902 				count = sizeof (tape_position_ext_t);
8903 				break;
8904 			case SHORT_POS:
8905 				count = 0;
8906 				break;
8907 			default:
8908 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8909 				    "Unknown read position type 0x%x in "
8910 				    " st_make_cmd()\n", un->un_read_pos_type);
8911 			}
8912 			break;
8913 
8914 		default:
8915 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8916 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8917 			    com);
8918 		}
8919 
8920 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8921 		    st_recov_sz, 0, func, (caddr_t)un);
8922 		if (pkt == NULL) {
8923 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8924 			    "generic command scsi_init_pkt() failure\n");
8925 			goto exit;
8926 		}
8927 
8928 		ASSERT(pkt->pkt_resid == 0);
8929 #ifdef STDEBUG
8930 		bzero(pkt->pkt_private, st_recov_sz);
8931 		bzero(pkt->pkt_scbp, stat_size);
8932 #endif
8933 		ri = (recov_info *)pkt->pkt_private;
8934 		ri->privatelen = st_recov_sz;
8935 		if (allocbp) {
8936 			ASSERT(geterror(allocbp) == 0);
8937 		}
8938 
8939 	}
8940 
8941 	ucdb = (union scsi_cdb *)pkt->pkt_cdbp;
8942 
8943 	(void) scsi_setup_cdb(ucdb, com, address, (uint_t)count, additional);
8944 	FILL_SCSI1_LUN(un->un_sd, pkt);
8945 	/*
8946 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8947 	 */
8948 	ucdb->t_code = fixbit;
8949 	ucdb->g0_vu_1 = short_fm;
8950 	pkt->pkt_flags = flags;
8951 
8952 	ASSERT(tval);
8953 	pkt->pkt_time = tval;
8954 	if (bp == un->un_recov_buf) {
8955 		pkt->pkt_comp = st_recov_cb;
8956 	} else {
8957 		pkt->pkt_comp = st_intr;
8958 	}
8959 
8960 	st_add_recovery_info_to_pkt(un, bp, pkt);
8961 
8962 	/*
8963 	 * If we just write data to tape and did a command that doesn't
8964 	 * change position, we still need to write a filemark.
8965 	 */
8966 	if ((prev_op == ST_OP_WRITE) || (prev_op == ST_OP_WEOF)) {
8967 		recov_info *rcvi = pkt->pkt_private;
8968 		cmd_attribute const *atrib;
8969 
8970 		if (rcvi->privatelen == sizeof (recov_info)) {
8971 			atrib = rcvi->cmd_attrib;
8972 		} else {
8973 			atrib = st_lookup_cmd_attribute(com);
8974 		}
8975 		if (atrib->chg_tape_direction == DIR_NONE) {
8976 			un->un_lastop = prev_op;
8977 		}
8978 	}
8979 
8980 exit:
8981 	ASSERT(mutex_owned(ST_MUTEX));
8982 }
8983 
8984 
8985 /*
8986  * Build a command based on a uscsi command;
8987  */
8988 static void
8989 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
8990     struct buf *bp, int (*func)(caddr_t))
8991 {
8992 	struct scsi_pkt *pkt;
8993 	recov_info *ri;
8994 	caddr_t cdb;
8995 	int	cdblen;
8996 	int	stat_size = 1;
8997 	int	flags = 0;
8998 
8999 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
9000 
9001 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9002 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
9003 
9004 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
9005 		if (un->un_arq_enabled) {
9006 			if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
9007 				stat_size = (int)(ucmd->uscsi_rqlen) +
9008 				    sizeof (struct scsi_arq_status) -
9009 				    sizeof (struct scsi_extended_sense);
9010 				flags = PKT_XARQ;
9011 			} else {
9012 				stat_size = sizeof (struct scsi_arq_status);
9013 			}
9014 		}
9015 	}
9016 
9017 	ASSERT(mutex_owned(ST_MUTEX));
9018 
9019 	cdb = ucmd->uscsi_cdb;
9020 	cdblen = ucmd->uscsi_cdblen;
9021 
9022 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9023 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
9024 	    ucmd->uscsi_buflen, bp->b_bcount);
9025 	pkt = scsi_init_pkt(ROUTE, NULL,
9026 	    (bp->b_bcount > 0) ? bp : NULL,
9027 	    cdblen, stat_size, st_recov_sz, flags, func, (caddr_t)un);
9028 	if (pkt == NULL) {
9029 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
9030 		    "uscsi command scsi_init_pkt() failure\n");
9031 		goto exit;
9032 	}
9033 
9034 	ASSERT(pkt->pkt_resid == 0);
9035 #ifdef STDEBUG
9036 	bzero(pkt->pkt_private, st_recov_sz);
9037 	bzero(pkt->pkt_scbp, stat_size);
9038 #endif
9039 	ri = (recov_info *)pkt->pkt_private;
9040 	ri->privatelen = st_recov_sz;
9041 
9042 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
9043 
9044 #ifdef STDEBUG
9045 	if ((st_debug & 0x7) >= 6) {
9046 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
9047 		    "pkt_cdbp", (char *)cdb, cdblen);
9048 	}
9049 #endif
9050 
9051 	if (ucmd->uscsi_flags & USCSI_SILENT) {
9052 		pkt->pkt_flags |= FLAG_SILENT;
9053 	}
9054 
9055 	(void) scsi_uscsi_pktinit(ucmd, pkt);
9056 
9057 	pkt->pkt_time = ucmd->uscsi_timeout;
9058 	if (bp == un->un_recov_buf) {
9059 		pkt->pkt_comp = st_recov_cb;
9060 	} else {
9061 		pkt->pkt_comp = st_intr;
9062 	}
9063 	st_add_recovery_info_to_pkt(un, bp, pkt);
9064 exit:
9065 	ASSERT(mutex_owned(ST_MUTEX));
9066 }
9067 
9068 
9069 /*
9070  * restart cmd currently at the head of the runq
9071  *
9072  * If scsi_transport() succeeds or the retries
9073  * count exhausted, restore the throttle that was
9074  * zeroed out in st_handle_intr_busy().
9075  *
9076  */
9077 static void
9078 st_intr_restart(void *arg)
9079 {
9080 	struct scsi_tape *un = arg;
9081 	struct buf *bp;
9082 	int queued;
9083 	int status = TRAN_ACCEPT;
9084 
9085 	mutex_enter(ST_MUTEX);
9086 
9087 	ST_FUNC(ST_DEVINFO, st_intr_restart);
9088 
9089 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9090 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
9091 
9092 	un->un_hib_tid = 0;
9093 
9094 	if (un->un_recov_buf_busy != 0) {
9095 		bp = un->un_recov_buf;
9096 		queued = 0;
9097 	} else if (un->un_sbuf_busy != 0) {
9098 		bp = un->un_sbufp;
9099 		queued = 0;
9100 	} else if (un->un_quef != NULL) {
9101 		bp = un->un_quef;
9102 		queued = 1;
9103 	} else {
9104 		mutex_exit(ST_MUTEX);
9105 		return;
9106 	}
9107 
9108 	/*
9109 	 * Here we know :
9110 	 *	throttle = 0, via st_handle_intr_busy
9111 	 */
9112 
9113 	if (queued) {
9114 		/*
9115 		 * move from waitq to runq, if there is anything on the waitq
9116 		 */
9117 		(void) st_remove_from_queue(&un->un_quef, &un->un_quef, bp);
9118 
9119 		if (un->un_runqf) {
9120 			/*
9121 			 * not good, we don't want to requeue something after
9122 			 * another.
9123 			 */
9124 			goto done_error;
9125 		} else {
9126 			un->un_runqf = bp;
9127 			un->un_runql = bp;
9128 		}
9129 	}
9130 
9131 	ST_CDB(ST_DEVINFO, "Interrupt restart CDB",
9132 	    (char *)BP_PKT(bp)->pkt_cdbp);
9133 
9134 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
9135 
9136 	status = st_transport(un, BP_PKT(bp));
9137 
9138 	if (status != TRAN_ACCEPT) {
9139 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9140 
9141 		if (status == TRAN_BUSY) {
9142 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
9143 
9144 			if (pkti->privatelen == sizeof (recov_info) &&
9145 			    un->un_unit_attention_flags &&
9146 			    bp != un->un_recov_buf) {
9147 			un->un_unit_attention_flags = 0;
9148 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9149 				    "Command Recovery called on busy resend\n");
9150 				if (st_command_recovery(un, BP_PKT(bp),
9151 				    ATTEMPT_RETRY) == JUST_RETURN) {
9152 					mutex_exit(ST_MUTEX);
9153 					return;
9154 				}
9155 			}
9156 			mutex_exit(ST_MUTEX);
9157 			if (st_handle_intr_busy(un, bp,
9158 			    ST_TRAN_BUSY_TIMEOUT) == 0)
9159 				return;	/* timeout is setup again */
9160 			mutex_enter(ST_MUTEX);
9161 		}
9162 
9163 done_error:
9164 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9165 		    "restart transport rejected\n");
9166 		bp->b_resid = bp->b_bcount;
9167 
9168 		if (un->un_last_throttle) {
9169 			un->un_throttle = un->un_last_throttle;
9170 		}
9171 		if (status != TRAN_ACCEPT) {
9172 			ST_DO_ERRSTATS(un, st_transerrs);
9173 		}
9174 		ST_DO_KSTATS(bp, kstat_waitq_exit);
9175 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9176 		    "busy restart aborted\n");
9177 		st_set_pe_flag(un);
9178 		st_bioerror(bp, EIO);
9179 		st_done_and_mutex_exit(un, bp);
9180 	} else {
9181 		if (un->un_last_throttle) {
9182 			un->un_throttle = un->un_last_throttle;
9183 		}
9184 		mutex_exit(ST_MUTEX);
9185 	}
9186 }
9187 
9188 /*
9189  * st_check_media():
9190  * Periodically check the media state using scsi_watch service;
9191  * this service calls back after TUR and possibly request sense
9192  * the callback handler (st_media_watch_cb()) decodes the request sense
9193  * data (if any)
9194  */
9195 
9196 static int
9197 st_check_media(dev_t dev, enum mtio_state state)
9198 {
9199 	int rval = 0;
9200 	enum mtio_state	prev_state;
9201 	opaque_t token = NULL;
9202 
9203 	GET_SOFT_STATE(dev);
9204 
9205 	ST_FUNC(ST_DEVINFO, st_check_media);
9206 
9207 	mutex_enter(ST_MUTEX);
9208 
9209 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9210 	    "st_check_media:state=%x, mediastate=%x\n",
9211 	    state, un->un_mediastate);
9212 
9213 	prev_state = un->un_mediastate;
9214 
9215 	/*
9216 	 * is there anything to do?
9217 	 */
9218 retry:
9219 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
9220 		/*
9221 		 * submit the request to the scsi_watch service;
9222 		 * scsi_media_watch_cb() does the real work
9223 		 */
9224 		mutex_exit(ST_MUTEX);
9225 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
9226 		    st_check_media_time, SENSE_LENGTH,
9227 		    st_media_watch_cb, (caddr_t)dev);
9228 		if (token == NULL) {
9229 			rval = EAGAIN;
9230 			goto done;
9231 		}
9232 		mutex_enter(ST_MUTEX);
9233 
9234 		un->un_swr_token = token;
9235 		un->un_specified_mediastate = state;
9236 
9237 		/*
9238 		 * now wait for media change
9239 		 * we will not be signalled unless mediastate == state but it
9240 		 * still better to test for this condition, since there
9241 		 * is a 5 sec cv_broadcast delay when
9242 		 *  mediastate == MTIO_INSERTED
9243 		 */
9244 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9245 		    "st_check_media:waiting for media state change\n");
9246 		while (un->un_mediastate == state) {
9247 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
9248 				mutex_exit(ST_MUTEX);
9249 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9250 				    "st_check_media:waiting for media state "
9251 				    "was interrupted\n");
9252 				rval = EINTR;
9253 				goto done;
9254 			}
9255 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9256 			    "st_check_media:received signal, state=%x\n",
9257 			    un->un_mediastate);
9258 		}
9259 	}
9260 
9261 	/*
9262 	 * if we transitioned to MTIO_INSERTED, media has really been
9263 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
9264 	 * Reset and retry the state change.  If everything is ok, replay
9265 	 * the open() logic.
9266 	 */
9267 	if ((un->un_mediastate == MTIO_INSERTED) &&
9268 	    (un->un_state == ST_STATE_OFFLINE)) {
9269 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9270 		    "st_check_media: calling st_cmd to confirm inserted\n");
9271 
9272 		/*
9273 		 * set this early so that TUR will make it through strategy
9274 		 * without triggering a st_tape_init().  We needed it set
9275 		 * before calling st_tape_init() ourselves anyway.  If TUR
9276 		 * fails, set it back
9277 		 */
9278 		un->un_state = ST_STATE_INITIALIZING;
9279 
9280 		/*
9281 		 * If not reserved fail as getting reservation conflict
9282 		 * will make this hang forever.
9283 		 */
9284 		if ((un->un_rsvd_status &
9285 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9286 			mutex_exit(ST_MUTEX);
9287 			rval = EACCES;
9288 			goto done;
9289 		}
9290 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
9291 		if (rval == EACCES) {
9292 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9293 			    "st_check_media: TUR got Reservation Conflict\n");
9294 			mutex_exit(ST_MUTEX);
9295 			goto done;
9296 		}
9297 		if (rval) {
9298 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9299 			    "st_check_media: TUR failed, going to retry\n");
9300 			un->un_mediastate = prev_state;
9301 			un->un_state = ST_STATE_OFFLINE;
9302 			goto retry;
9303 		}
9304 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9305 		    "st_check_media: media inserted\n");
9306 
9307 		/* this also rewinds the tape */
9308 		rval = st_tape_init(un);
9309 		if (rval != 0) {
9310 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9311 			    "st_check_media : OFFLINE init failure ");
9312 			un->un_state = ST_STATE_OFFLINE;
9313 			un->un_pos.pmode = invalid;
9314 		} else {
9315 			un->un_state = ST_STATE_OPEN_PENDING_IO;
9316 		}
9317 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
9318 	    (un->un_state != ST_STATE_OFFLINE)) {
9319 		/*
9320 		 * supported devices must be rewound before ejection
9321 		 * rewind resets fileno & blkno
9322 		 */
9323 		un->un_laststate = un->un_state;
9324 		un->un_state = ST_STATE_OFFLINE;
9325 	}
9326 	mutex_exit(ST_MUTEX);
9327 done:
9328 	if (token) {
9329 		(void) scsi_watch_request_terminate(token,
9330 		    SCSI_WATCH_TERMINATE_WAIT);
9331 		mutex_enter(ST_MUTEX);
9332 		un->un_swr_token = (opaque_t)NULL;
9333 		mutex_exit(ST_MUTEX);
9334 	}
9335 
9336 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
9337 
9338 	return (rval);
9339 }
9340 
9341 /*
9342  * st_media_watch_cb() is called by scsi_watch_thread for
9343  * verifying the request sense data (if any)
9344  */
9345 static int
9346 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
9347 {
9348 	struct scsi_status *statusp = resultp->statusp;
9349 	struct scsi_extended_sense *sensep = resultp->sensep;
9350 	uchar_t actual_sense_length = resultp->actual_sense_length;
9351 	struct scsi_tape *un;
9352 	enum mtio_state state = MTIO_NONE;
9353 	int instance;
9354 	dev_t dev = (dev_t)arg;
9355 
9356 	instance = MTUNIT(dev);
9357 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
9358 		return (-1);
9359 	}
9360 
9361 	mutex_enter(ST_MUTEX);
9362 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
9363 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9364 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
9365 	    *((char *)statusp), (void *)sensep,
9366 	    actual_sense_length);
9367 
9368 
9369 	/*
9370 	 * if there was a check condition then sensep points to valid
9371 	 * sense data
9372 	 * if status was not a check condition but a reservation or busy
9373 	 * status then the new state is MTIO_NONE
9374 	 */
9375 	if (sensep) {
9376 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9377 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
9378 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
9379 
9380 		switch (un->un_dp->type) {
9381 		default:
9382 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9383 			    "st_media_watch_cb: unknown drive type %d, "
9384 			    "default to ST_TYPE_HP\n", un->un_dp->type);
9385 		/* FALLTHROUGH */
9386 
9387 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
9388 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
9389 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
9390 			if (un->un_dp->type == ST_TYPE_FUJI) {
9391 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9392 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
9393 			} else {
9394 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9395 				    "st_media_watch_cb: ST_TYPE_HP\n");
9396 			}
9397 			switch (sensep->es_key) {
9398 			case KEY_UNIT_ATTENTION:
9399 				/* not ready to ready transition */
9400 				/* hp/es_qual_code == 80 on>off>on */
9401 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
9402 				if (sensep->es_add_code == 0x28) {
9403 					state = MTIO_INSERTED;
9404 				}
9405 				break;
9406 			case KEY_NOT_READY:
9407 				/* in process, rewinding or loading */
9408 				if ((sensep->es_add_code == 0x04) &&
9409 				    (sensep->es_qual_code == 0x00)) {
9410 					state = MTIO_EJECTED;
9411 				}
9412 				break;
9413 			}
9414 			break;
9415 
9416 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
9417 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9418 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
9419 			switch (sensep->es_key) {
9420 			case KEY_UNIT_ATTENTION:
9421 				/* operator medium removal request */
9422 				if ((sensep->es_add_code == 0x5a) &&
9423 				    (sensep->es_qual_code == 0x01)) {
9424 					state = MTIO_EJECTED;
9425 				/* not ready to ready transition */
9426 				} else if ((sensep->es_add_code == 0x28) &&
9427 				    (sensep->es_qual_code == 0x00)) {
9428 					state = MTIO_INSERTED;
9429 				}
9430 				break;
9431 			case KEY_NOT_READY:
9432 				/* medium not present */
9433 				if (sensep->es_add_code == 0x3a) {
9434 					state = MTIO_EJECTED;
9435 				}
9436 				break;
9437 			}
9438 			break;
9439 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
9440 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9441 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
9442 			switch (sensep->es_key) {
9443 			case KEY_NOT_READY:
9444 				if ((sensep->es_add_code == 0x04) &&
9445 				    (sensep->es_qual_code == 0x00)) {
9446 					/* volume not mounted? */
9447 					state = MTIO_EJECTED;
9448 				} else if (sensep->es_add_code == 0x3a) {
9449 					state = MTIO_EJECTED;
9450 				}
9451 				break;
9452 			case KEY_UNIT_ATTENTION:
9453 				state = MTIO_EJECTED;
9454 				break;
9455 			}
9456 			break;
9457 
9458 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
9459 			switch (sensep->es_key) {
9460 			case KEY_UNIT_ATTENTION:
9461 				if (sensep->es_add_code == 0x28) {
9462 					state = MTIO_INSERTED;
9463 				}
9464 				break;
9465 			case KEY_NOT_READY:
9466 				if (sensep->es_add_code == 0x04) {
9467 					/* in transition but could be either */
9468 					state = un->un_specified_mediastate;
9469 				} else if ((sensep->es_add_code == 0x3a) &&
9470 				    (sensep->es_qual_code == 0x00)) {
9471 					state = MTIO_EJECTED;
9472 				}
9473 				break;
9474 			}
9475 			break;
9476 		}
9477 	} else if (*((char *)statusp) == STATUS_GOOD) {
9478 		state = MTIO_INSERTED;
9479 	}
9480 
9481 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9482 	    "st_media_watch_cb:state=%x, specified=%x\n",
9483 	    state, un->un_specified_mediastate);
9484 
9485 	/*
9486 	 * now signal the waiting thread if this is *not* the specified state;
9487 	 * delay the signal if the state is MTIO_INSERTED
9488 	 * to allow the target to recover
9489 	 */
9490 	if (state != un->un_specified_mediastate) {
9491 		un->un_mediastate = state;
9492 		if (state == MTIO_INSERTED) {
9493 			/*
9494 			 * delay the signal to give the drive a chance
9495 			 * to do what it apparently needs to do
9496 			 */
9497 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9498 			    "st_media_watch_cb:delayed cv_broadcast\n");
9499 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
9500 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
9501 		} else {
9502 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9503 			    "st_media_watch_cb:immediate cv_broadcast\n");
9504 			cv_broadcast(&un->un_state_cv);
9505 		}
9506 	}
9507 	mutex_exit(ST_MUTEX);
9508 	return (0);
9509 }
9510 
9511 /*
9512  * delayed cv_broadcast to allow for target to recover
9513  * from media insertion
9514  */
9515 static void
9516 st_delayed_cv_broadcast(void *arg)
9517 {
9518 	struct scsi_tape *un = arg;
9519 
9520 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
9521 
9522 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9523 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
9524 
9525 	mutex_enter(ST_MUTEX);
9526 	cv_broadcast(&un->un_state_cv);
9527 	mutex_exit(ST_MUTEX);
9528 }
9529 
9530 /*
9531  * restart cmd currently at the start of the waitq
9532  */
9533 static void
9534 st_start_restart(void *arg)
9535 {
9536 	struct scsi_tape *un = arg;
9537 
9538 	ST_FUNC(ST_DEVINFO, st_start_restart);
9539 
9540 	ASSERT(un != NULL);
9541 
9542 	mutex_enter(ST_MUTEX);
9543 
9544 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_tran_restart()\n");
9545 
9546 	st_start(un);
9547 
9548 	mutex_exit(ST_MUTEX);
9549 }
9550 
9551 
9552 /*
9553  * Command completion processing
9554  *
9555  */
9556 static void
9557 st_intr(struct scsi_pkt *pkt)
9558 {
9559 	recov_info *rcv = pkt->pkt_private;
9560 	struct buf *bp = rcv->cmd_bp;
9561 	struct scsi_tape *un;
9562 	errstate action = COMMAND_DONE;
9563 	clock_t	timout;
9564 	int	status;
9565 
9566 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
9567 
9568 	ST_FUNC(ST_DEVINFO, st_intr);
9569 
9570 	ASSERT(un != NULL);
9571 
9572 	mutex_enter(ST_MUTEX);
9573 
9574 	ASSERT(bp != un->un_recov_buf);
9575 
9576 	un->un_rqs_state &= ~(ST_RQS_ERROR);
9577 
9578 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
9579 
9580 	if (pkt->pkt_reason != CMD_CMPLT) {
9581 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9582 		    "Unhappy packet status reason = %s statistics = 0x%x\n",
9583 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9584 
9585 		/* If device has gone away not much else to do */
9586 		if (pkt->pkt_reason == CMD_DEV_GONE) {
9587 			action = COMMAND_DONE_ERROR;
9588 		} else if ((pkt == un->un_rqs) ||
9589 		    (un->un_state == ST_STATE_SENSING)) {
9590 			ASSERT(pkt == un->un_rqs);
9591 			ASSERT(un->un_state == ST_STATE_SENSING);
9592 			un->un_state = un->un_laststate;
9593 			rcv->cmd_bp = un->un_rqs_bp;
9594 			ST_DO_ERRSTATS(un, st_transerrs);
9595 			action = COMMAND_DONE_ERROR;
9596 		} else {
9597 			action = st_handle_incomplete(un, bp);
9598 		}
9599 	/*
9600 	 * At this point we know that the command was successfully
9601 	 * completed. Now what?
9602 	 */
9603 	} else if ((pkt == un->un_rqs) || (un->un_state == ST_STATE_SENSING)) {
9604 		/*
9605 		 * okay. We were running a REQUEST SENSE. Find
9606 		 * out what to do next.
9607 		 */
9608 		ASSERT(pkt == un->un_rqs);
9609 		ASSERT(un->un_state == ST_STATE_SENSING);
9610 		scsi_sync_pkt(pkt);
9611 		action = st_handle_sense(un, bp, &un->un_pos);
9612 		/*
9613 		 * Make rqs isn't going to be retied.
9614 		 */
9615 		if (action != QUE_BUSY_COMMAND && action != QUE_COMMAND) {
9616 			/*
9617 			 * set pkt back to original packet in case we will have
9618 			 * to requeue it
9619 			 */
9620 			pkt = BP_PKT(bp);
9621 			rcv->cmd_bp = un->un_rqs_bp;
9622 			/*
9623 			 * some actions are based on un_state, hence
9624 			 * restore the state st was in before ST_STATE_SENSING.
9625 			 */
9626 			un->un_state = un->un_laststate;
9627 		}
9628 
9629 	} else if (un->un_arq_enabled && (pkt->pkt_state & STATE_ARQ_DONE)) {
9630 		/*
9631 		 * the transport layer successfully completed an autorqsense
9632 		 */
9633 		action = st_handle_autosense(un, bp, &un->un_pos);
9634 
9635 	} else  if ((SCBP(pkt)->sts_busy) ||
9636 	    (SCBP(pkt)->sts_chk) ||
9637 	    (SCBP(pkt)->sts_vu7)) {
9638 		/*
9639 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9640 		 * to see if the status bits we're okay. If a request sense
9641 		 * is to be run, that will happen.
9642 		 */
9643 		action = st_check_error(un, pkt);
9644 	}
9645 
9646 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9647 		switch (action) {
9648 			case QUE_COMMAND:
9649 				/*
9650 				 * return cmd to head to the queue
9651 				 * since we are suspending so that
9652 				 * it gets restarted during resume
9653 				 */
9654 				st_add_to_queue(&un->un_runqf, &un->un_runql,
9655 				    un->un_runqf, bp);
9656 
9657 				action = JUST_RETURN;
9658 				break;
9659 
9660 			case QUE_SENSE:
9661 				action = COMMAND_DONE_ERROR;
9662 				break;
9663 
9664 			default:
9665 				break;
9666 		}
9667 	}
9668 
9669 	/*
9670 	 * check for undetected path failover.
9671 	 */
9672 	if (un->un_multipath) {
9673 
9674 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
9675 		int pkt_valid;
9676 
9677 		if (ucmd) {
9678 			/*
9679 			 * Also copies path instance to the uscsi structure.
9680 			 */
9681 			pkt_valid = scsi_uscsi_pktfini(pkt, ucmd);
9682 
9683 			/*
9684 			 * scsi_uscsi_pktfini() zeros pkt_path_instance.
9685 			 */
9686 			pkt->pkt_path_instance = ucmd->uscsi_path_instance;
9687 		} else {
9688 			pkt_valid = scsi_pkt_allocated_correctly(pkt);
9689 		}
9690 
9691 		/*
9692 		 * If the scsi_pkt was not allocated correctly the
9693 		 * pkt_path_instance is not even there.
9694 		 */
9695 		if ((pkt_valid != 0) &&
9696 		    (un->un_last_path_instance != pkt->pkt_path_instance)) {
9697 			if (un->un_state > ST_STATE_OPENING) {
9698 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
9699 				    "Failover detected, action is %s\n",
9700 				    errstatenames[action]);
9701 				if (action == COMMAND_DONE) {
9702 					action = PATH_FAILED;
9703 				}
9704 			}
9705 			un->un_last_path_instance = pkt->pkt_path_instance;
9706 		}
9707 	}
9708 
9709 	/*
9710 	 * Restore old state if we were sensing.
9711 	 */
9712 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9713 		un->un_state = un->un_laststate;
9714 	}
9715 
9716 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9717 	    "st_intr: pkt=%p, bp=%p, action=%s, status=%x\n",
9718 	    (void *)pkt, (void *)bp, errstatenames[action], SCBP_C(pkt));
9719 
9720 again:
9721 	switch (action) {
9722 	case COMMAND_DONE_EACCES:
9723 		/* this is to report a reservation conflict */
9724 		st_bioerror(bp, EACCES);
9725 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9726 		    "Reservation Conflict \n");
9727 		un->un_pos.pmode = invalid;
9728 
9729 		/*FALLTHROUGH*/
9730 	case COMMAND_DONE_ERROR:
9731 		if (un->un_pos.eof < ST_EOT_PENDING &&
9732 		    un->un_state >= ST_STATE_OPEN) {
9733 			/*
9734 			 * all errors set state of the tape to 'unknown'
9735 			 * unless we're at EOT or are doing append testing.
9736 			 * If sense key was illegal request, preserve state.
9737 			 */
9738 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9739 				un->un_pos.pmode = invalid;
9740 			}
9741 		}
9742 
9743 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9744 		/*
9745 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9746 		 * make sure an error ocurrs, so make sure at least EIO is
9747 		 * returned
9748 		 */
9749 		if (geterror(bp) == 0)
9750 			st_bioerror(bp, EIO);
9751 
9752 		st_set_pe_flag(un);
9753 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9754 		    (un->un_errno == EIO)) {
9755 			un->un_rqs_state &= ~(ST_RQS_VALID);
9756 		}
9757 		break;
9758 
9759 	case COMMAND_DONE_ERROR_RECOVERED:
9760 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9761 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9762 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9763 		if (geterror(bp) == 0) {
9764 			st_bioerror(bp, EIO);
9765 		}
9766 		st_set_pe_flag(un);
9767 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9768 		    (un->un_errno == EIO)) {
9769 			un->un_rqs_state &= ~(ST_RQS_VALID);
9770 		}
9771 		/*FALLTHROUGH*/
9772 	case COMMAND_DONE:
9773 		st_set_state(un, bp);
9774 		break;
9775 
9776 	case QUE_SENSE:
9777 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9778 			goto sense_error;
9779 
9780 		if (un->un_state != ST_STATE_SENSING) {
9781 			un->un_laststate = un->un_state;
9782 			un->un_state = ST_STATE_SENSING;
9783 		}
9784 
9785 		/*
9786 		 * zero the sense data.
9787 		 */
9788 		bzero(un->un_rqs->pkt_scbp, SENSE_LENGTH);
9789 
9790 		/*
9791 		 * If this is not a retry on QUE_SENSE point to the original
9792 		 * bp of the command that got us here.
9793 		 */
9794 		if (pkt != un->un_rqs) {
9795 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp = bp;
9796 		}
9797 
9798 		if (un->un_throttle) {
9799 			un->un_last_throttle = un->un_throttle;
9800 			un->un_throttle = 0;
9801 		}
9802 
9803 		ST_CDB(ST_DEVINFO, "Queue sense CDB",
9804 		    (char *)BP_PKT(bp)->pkt_cdbp);
9805 
9806 		/*
9807 		 * never retry this, some other command will have nuked the
9808 		 * sense, anyway
9809 		 */
9810 		status = st_transport(un, un->un_rqs);
9811 
9812 		if (un->un_last_throttle) {
9813 			un->un_throttle = un->un_last_throttle;
9814 		}
9815 
9816 		if (status == TRAN_ACCEPT) {
9817 			mutex_exit(ST_MUTEX);
9818 			return;
9819 		}
9820 		if (status != TRAN_BUSY)
9821 			ST_DO_ERRSTATS(un, st_transerrs);
9822 sense_error:
9823 		un->un_pos.pmode = invalid;
9824 		st_bioerror(bp, EIO);
9825 		st_set_pe_flag(un);
9826 		break;
9827 
9828 	case QUE_BUSY_COMMAND:
9829 		/* longish timeout */
9830 		timout = ST_STATUS_BUSY_TIMEOUT;
9831 		goto que_it_up;
9832 
9833 	case QUE_COMMAND:
9834 		/* short timeout */
9835 		timout = ST_TRAN_BUSY_TIMEOUT;
9836 que_it_up:
9837 		/*
9838 		 * let st_handle_intr_busy put this bp back on waitq and make
9839 		 * checks to see if it is ok to requeue the command.
9840 		 */
9841 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9842 
9843 		/*
9844 		 * Save the throttle before setting up the timeout
9845 		 */
9846 		if (un->un_throttle) {
9847 			un->un_last_throttle = un->un_throttle;
9848 		}
9849 		mutex_exit(ST_MUTEX);
9850 		if (st_handle_intr_busy(un, bp, timout) == 0)
9851 			return;		/* timeout is setup again */
9852 
9853 		mutex_enter(ST_MUTEX);
9854 		un->un_pos.pmode = invalid;
9855 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9856 		st_bioerror(bp, EIO);
9857 		st_set_pe_flag(un);
9858 		break;
9859 
9860 	case QUE_LAST_COMMAND:
9861 
9862 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9863 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9864 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9865 			goto last_command_error;
9866 		}
9867 		mutex_exit(ST_MUTEX);
9868 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9869 			return;
9870 		mutex_enter(ST_MUTEX);
9871 last_command_error:
9872 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9873 		un->un_pos.pmode = invalid;
9874 		st_bioerror(bp, EIO);
9875 		st_set_pe_flag(un);
9876 		break;
9877 
9878 	case COMMAND_TIMEOUT:
9879 	case DEVICE_RESET:
9880 	case DEVICE_TAMPER:
9881 	case ATTEMPT_RETRY:
9882 	case PATH_FAILED:
9883 		ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9884 		    "Command Recovery called on %s status\n",
9885 		    errstatenames[action]);
9886 		action = st_command_recovery(un, pkt, action);
9887 		goto again;
9888 
9889 	default:
9890 		ASSERT(0);
9891 		/* FALLTHRU */
9892 	case JUST_RETURN:
9893 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9894 		mutex_exit(ST_MUTEX);
9895 		return;
9896 	}
9897 
9898 	ST_DO_KSTATS(bp, kstat_runq_exit);
9899 	st_done_and_mutex_exit(un, bp);
9900 }
9901 
9902 static errstate
9903 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9904 {
9905 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9906 	recov_info *rinfo;
9907 	errstate rval = COMMAND_DONE_ERROR;
9908 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9909 	    un->un_rqs : BP_PKT(bp);
9910 	int result;
9911 
9912 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9913 
9914 	rinfo = (recov_info *)pkt->pkt_private;
9915 
9916 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9917 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9918 
9919 	ASSERT(mutex_owned(ST_MUTEX));
9920 
9921 	switch (pkt->pkt_reason) {
9922 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9923 		/*
9924 		 * this occurs when accessing a powered down drive, no
9925 		 * need to complain; just fail the open
9926 		 */
9927 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9928 
9929 		/*
9930 		 * if we have commands outstanding in HBA, and a command
9931 		 * comes back incomplete, we're hosed, so reset target
9932 		 * If we have the bus, but cmd_incomplete, we probably just
9933 		 * have a failed selection, so don't reset the target, just
9934 		 * requeue the command and try again
9935 		 */
9936 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9937 			goto reset_target;
9938 		}
9939 
9940 		/*
9941 		 * Retry selection a couple more times if we're
9942 		 * open.  If opening, we only try just once to
9943 		 * reduce probe time for nonexistant devices.
9944 		 */
9945 		if ((un->un_laststate > ST_STATE_OPENING) &&
9946 		    (rinfo->pkt_retry_cnt < st_selection_retry_count)) {
9947 			/* XXX check retriable? */
9948 			rval = QUE_COMMAND;
9949 		}
9950 		ST_DO_ERRSTATS(un, st_transerrs);
9951 		break;
9952 
9953 	case CMD_ABORTED:
9954 		/*
9955 		 * most likely this is caused by flush-on-error support. If
9956 		 * it was not there, the we're in trouble.
9957 		 */
9958 		if (!un->un_flush_on_errors) {
9959 			un->un_status = SUN_KEY_FATAL;
9960 			goto reset_target;
9961 		}
9962 
9963 		st_set_pe_errno(un);
9964 		bioerror(bp, un->un_errno);
9965 		if (un->un_errno)
9966 			return (COMMAND_DONE_ERROR);
9967 		else
9968 			return (COMMAND_DONE);
9969 
9970 	case CMD_TIMEOUT:	/* Command timed out */
9971 		un->un_status = SUN_KEY_TIMEOUT;
9972 		return (COMMAND_TIMEOUT);
9973 
9974 	case CMD_TRAN_ERR:
9975 	case CMD_RESET:
9976 		if (pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET)) {
9977 			if ((un->un_rsvd_status &
9978 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
9979 			    ST_RESERVE) {
9980 				un->un_rsvd_status |= ST_LOST_RESERVE;
9981 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
9982 				    "Lost Reservation\n");
9983 			}
9984 			rval = DEVICE_RESET;
9985 			return (rval);
9986 		}
9987 		if (pkt->pkt_statistics & (STAT_ABORTED | STAT_TERMINATED)) {
9988 			rval = DEVICE_RESET;
9989 			return (rval);
9990 		}
9991 		/*FALLTHROUGH*/
9992 	default:
9993 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9994 		    "Unhandled packet status reason = %s statistics = 0x%x\n",
9995 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9996 reset_target:
9997 
9998 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9999 		    "transport completed with %s\n",
10000 		    scsi_rname(pkt->pkt_reason));
10001 		ST_DO_ERRSTATS(un, st_transerrs);
10002 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
10003 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
10004 		    STAT_ABORTED)) == 0)) {
10005 
10006 			/*
10007 			 * If we haven't reserved the drive don't reset it.
10008 			 */
10009 			if ((un->un_rsvd_status &
10010 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
10011 				return (rval);
10012 			}
10013 
10014 			/*
10015 			 * if we aren't lost yet we will be soon.
10016 			 */
10017 			un->un_pos.pmode = invalid;
10018 
10019 			result = st_reset(un, RESET_LUN);
10020 
10021 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
10022 				/* no hope left to recover */
10023 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
10024 				    "recovery by resets failed\n");
10025 				return (rval);
10026 			}
10027 		}
10028 	}
10029 
10030 
10031 	if (rinfo->pkt_retry_cnt++ < st_retry_count) {
10032 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
10033 			rval = QUE_COMMAND;
10034 		} else if (bp == un->un_sbufp) {
10035 			if (rinfo->privatelen == sizeof (recov_info)) {
10036 				if (rinfo->cmd_attrib->retriable) {
10037 					/*
10038 					 * These commands can be rerun
10039 					 * with impunity
10040 					 */
10041 					rval = QUE_COMMAND;
10042 				}
10043 			} else {
10044 				cmd_attribute const *attrib;
10045 				attrib =
10046 				    st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10047 				if (attrib->retriable) {
10048 					rval = QUE_COMMAND;
10049 				}
10050 			}
10051 		}
10052 	} else {
10053 		rval = COMMAND_DONE_ERROR;
10054 	}
10055 
10056 	if (un->un_state >= ST_STATE_OPEN) {
10057 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10058 		    fail, scsi_rname(pkt->pkt_reason),
10059 		    (rval == COMMAND_DONE_ERROR)?
10060 		    "giving up" : "retrying command");
10061 	}
10062 	return (rval);
10063 }
10064 
10065 /*
10066  * if the device is busy, then put this bp back on the waitq, on the
10067  * interrupt thread, where we want the head of the queue and not the
10068  * end
10069  *
10070  * The callers of this routine should take measures to save the
10071  * un_throttle in un_last_throttle which will be restored in
10072  * st_intr_restart(). The only exception should be st_intr_restart()
10073  * calling this routine for which the saving is already done.
10074  */
10075 static int
10076 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
10077 	clock_t timeout_interval)
10078 {
10079 
10080 	int queued;
10081 	int rval = 0;
10082 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
10083 
10084 	mutex_enter(ST_MUTEX);
10085 
10086 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
10087 
10088 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10089 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
10090 
10091 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
10092 		queued = 1;
10093 	} else {
10094 		queued = 0;
10095 	}
10096 
10097 	/*
10098 	 * Check to see if we hit the retry timeout. We check to make sure
10099 	 * this is the first one on the runq and make sure we have not
10100 	 * queued up any more, so this one has to be the last on the list
10101 	 * also. If it is not, we have to fail.  If it is not the first, but
10102 	 * is the last we are in trouble anyway, as we are in the interrupt
10103 	 * context here.
10104 	 */
10105 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
10106 	    ((un->un_runqf != bp) && (un->un_runql != bp) && (queued))) {
10107 		rval = -1;
10108 		goto exit;
10109 	}
10110 
10111 	/* put the bp back on the waitq */
10112 	if (queued) {
10113 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
10114 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
10115 	}
10116 
10117 	/*
10118 	 * We don't want any other commands being started in the mean time.
10119 	 * If start had just released mutex after putting something on the
10120 	 * runq, we won't even get here.
10121 	 */
10122 	un->un_throttle = 0;
10123 
10124 	/*
10125 	 * send a marker pkt, if appropriate
10126 	 */
10127 	st_hba_unflush(un);
10128 
10129 	/*
10130 	 * all queues are aligned, we are just waiting to
10131 	 * transport
10132 	 */
10133 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
10134 
10135 exit:
10136 	mutex_exit(ST_MUTEX);
10137 	return (rval);
10138 }
10139 
10140 /*
10141  * To get one error entry from error stack
10142  */
10143 static int
10144 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
10145 {
10146 #ifdef _MULTI_DATAMODEL
10147 	/*
10148 	 * For use when a 32 bit app makes a call into a
10149 	 * 64 bit ioctl
10150 	 */
10151 	struct mterror_entry32 err_entry32;
10152 #endif /* _MULTI_DATAMODEL */
10153 
10154 	int rval = 0;
10155 	struct mterror_entry err_entry;
10156 	struct mterror_entry_stack *err_link_entry_p;
10157 	size_t arq_status_len_in, arq_status_len_kr;
10158 
10159 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
10160 
10161 	ASSERT(mutex_owned(ST_MUTEX));
10162 
10163 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10164 	    "st_get_error_entry()\n");
10165 
10166 	/*
10167 	 * if error record stack empty, return ENXIO
10168 	 */
10169 	if (un->un_error_entry_stk == NULL) {
10170 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10171 		    "st_get_error_entry: Error Entry Stack Empty!\n");
10172 		rval = ENXIO;
10173 		goto ret;
10174 	}
10175 
10176 	/*
10177 	 * get the top entry from stack
10178 	 */
10179 	err_link_entry_p = un->un_error_entry_stk;
10180 	arq_status_len_kr =
10181 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
10182 
10183 #ifdef _MULTI_DATAMODEL
10184 	switch (ddi_model_convert_from(flag & FMODELS)) {
10185 	case DDI_MODEL_ILP32:
10186 		if (ddi_copyin((void *)arg, &err_entry32,
10187 		    MTERROR_ENTRY_SIZE_32, flag)) {
10188 			rval = EFAULT;
10189 			goto ret;
10190 		}
10191 
10192 		arq_status_len_in =
10193 		    (size_t)err_entry32.mtee_arq_status_len;
10194 
10195 		err_entry32.mtee_cdb_len =
10196 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
10197 
10198 		if (arq_status_len_in > arq_status_len_kr)
10199 			err_entry32.mtee_arq_status_len =
10200 			    (size32_t)arq_status_len_kr;
10201 
10202 		if (ddi_copyout(
10203 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10204 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
10205 		    err_entry32.mtee_cdb_len, flag)) {
10206 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10207 			    "st_get_error_entry: Copy cdb buffer error!");
10208 			rval = EFAULT;
10209 		}
10210 
10211 		if (ddi_copyout(
10212 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10213 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
10214 		    err_entry32.mtee_arq_status_len, flag)) {
10215 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10216 			    "st_get_error_entry: copy arq status error!");
10217 			rval = EFAULT;
10218 		}
10219 
10220 		if (ddi_copyout(&err_entry32, (void *)arg,
10221 		    MTERROR_ENTRY_SIZE_32, flag)) {
10222 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10223 			    "st_get_error_entry: copy arq status out error!");
10224 			rval = EFAULT;
10225 		}
10226 		break;
10227 
10228 	case DDI_MODEL_NONE:
10229 		if (ddi_copyin((void *)arg, &err_entry,
10230 		    MTERROR_ENTRY_SIZE_64, flag)) {
10231 			rval = EFAULT;
10232 			goto ret;
10233 		}
10234 		arq_status_len_in = err_entry.mtee_arq_status_len;
10235 
10236 		err_entry.mtee_cdb_len =
10237 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
10238 
10239 		if (arq_status_len_in > arq_status_len_kr)
10240 			err_entry.mtee_arq_status_len =
10241 			    arq_status_len_kr;
10242 
10243 		if (ddi_copyout(
10244 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10245 		    err_entry.mtee_cdb_buf,
10246 		    err_entry.mtee_cdb_len, flag)) {
10247 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10248 			    "st_get_error_entry: Copy cdb buffer error!");
10249 			rval = EFAULT;
10250 		}
10251 
10252 		if (ddi_copyout(
10253 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10254 		    err_entry.mtee_arq_status,
10255 		    err_entry.mtee_arq_status_len, flag)) {
10256 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10257 			    "st_get_error_entry: copy arq status error!");
10258 			rval = EFAULT;
10259 		}
10260 
10261 		if (ddi_copyout(&err_entry, (void *)arg,
10262 		    MTERROR_ENTRY_SIZE_64, flag)) {
10263 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10264 			    "st_get_error_entry: copy arq status out error!");
10265 			rval = EFAULT;
10266 		}
10267 		break;
10268 	}
10269 #else /* _MULTI_DATAMODEL */
10270 	if (ddi_copyin((void *)arg, &err_entry,
10271 	    MTERROR_ENTRY_SIZE_64, flag)) {
10272 		rval = EFAULT;
10273 		goto ret;
10274 	}
10275 	arq_status_len_in = err_entry.mtee_arq_status_len;
10276 
10277 	err_entry.mtee_cdb_len =
10278 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
10279 
10280 	if (arq_status_len_in > arq_status_len_kr)
10281 		err_entry.mtee_arq_status_len =
10282 		    arq_status_len_kr;
10283 
10284 	if (ddi_copyout(
10285 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10286 	    err_entry.mtee_cdb_buf,
10287 	    err_entry.mtee_cdb_len, flag)) {
10288 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10289 		    "st_get_error_entry: Copy cdb buffer error!");
10290 		rval = EFAULT;
10291 	}
10292 
10293 	if (ddi_copyout(
10294 	    err_link_entry_p->mtees_entry.mtee_arq_status,
10295 	    err_entry.mtee_arq_status,
10296 	    err_entry.mtee_arq_status_len, flag)) {
10297 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10298 		    "st_get_error_entry: copy arq status buffer error!");
10299 		rval = EFAULT;
10300 	}
10301 
10302 	if (ddi_copyout(&err_entry, (void *)arg,
10303 	    MTERROR_ENTRY_SIZE_64, flag)) {
10304 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10305 		    "st_get_error_entry: copy arq status out error!");
10306 		rval = EFAULT;
10307 	}
10308 #endif /* _MULTI_DATAMODEL */
10309 
10310 	/*
10311 	 * update stack
10312 	 */
10313 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
10314 
10315 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
10316 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
10317 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
10318 
10319 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
10320 	    SECMDS_STATUS_SIZE);
10321 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
10322 
10323 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
10324 	err_link_entry_p = NULL;
10325 ret:
10326 	return (rval);
10327 }
10328 
10329 /*
10330  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
10331  * the scsi CDB command which causes the error and generates sense data and
10332  * the scsi status.
10333  *
10334  *      error-record stack
10335  *
10336  *
10337  *             TOP                                     BOTTOM
10338  *              ------------------------------------------
10339  *              |   0   |   1   |   2   |   ...  |   n   |
10340  *              ------------------------------------------
10341  *                  ^
10342  *                  |
10343  *       pointer to error entry
10344  *
10345  * when st driver generates one sense data record, it creates a error-entry
10346  * and pushes it onto the stack.
10347  *
10348  */
10349 
10350 static void
10351 st_update_error_stack(struct scsi_tape *un,
10352 			struct scsi_pkt *pkt,
10353 			struct scsi_arq_status *cmd)
10354 {
10355 	struct mterror_entry_stack *err_entry_tmp;
10356 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
10357 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
10358 
10359 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
10360 
10361 	ASSERT(mutex_owned(ST_MUTEX));
10362 
10363 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10364 	    "st_update_error_stack()\n");
10365 
10366 	ASSERT(cmd);
10367 	ASSERT(cdbp);
10368 	if (cdblen == 0) {
10369 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10370 		    "st_update_error_stack: CDB length error!\n");
10371 		return;
10372 	}
10373 
10374 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
10375 	ASSERT(err_entry_tmp != NULL);
10376 
10377 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
10378 	    kmem_alloc(cdblen, KM_SLEEP);
10379 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
10380 
10381 	err_entry_tmp->mtees_entry.mtee_arq_status =
10382 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
10383 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
10384 
10385 	/*
10386 	 * copy cdb command & length to current error entry
10387 	 */
10388 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
10389 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
10390 
10391 	/*
10392 	 * copy scsi status length to current error entry
10393 	 */
10394 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
10395 	    SECMDS_STATUS_SIZE;
10396 
10397 	/*
10398 	 * copy sense data and scsi status to current error entry
10399 	 */
10400 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
10401 	    SECMDS_STATUS_SIZE);
10402 
10403 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
10404 	un->un_error_entry_stk = err_entry_tmp;
10405 
10406 }
10407 
10408 /*
10409  * Empty all the error entry in stack
10410  */
10411 static void
10412 st_empty_error_stack(struct scsi_tape *un)
10413 {
10414 	struct mterror_entry_stack *linkp;
10415 
10416 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
10417 
10418 	ASSERT(mutex_owned(ST_MUTEX));
10419 
10420 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10421 	    "st_empty_entry_stack()\n");
10422 
10423 	while (un->un_error_entry_stk != NULL) {
10424 		linkp = un->un_error_entry_stk;
10425 		un->un_error_entry_stk =
10426 		    un->un_error_entry_stk->mtees_nextp;
10427 
10428 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
10429 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
10430 			    linkp->mtees_entry.mtee_cdb_len);
10431 
10432 		if (linkp->mtees_entry.mtee_arq_status != NULL)
10433 			kmem_free(linkp->mtees_entry.mtee_arq_status,
10434 			    linkp->mtees_entry.mtee_arq_status_len);
10435 
10436 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
10437 		linkp = NULL;
10438 	}
10439 }
10440 
10441 static errstate
10442 st_handle_sense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10443 {
10444 	struct scsi_pkt *pkt = BP_PKT(bp);
10445 	struct scsi_pkt *rqpkt = un->un_rqs;
10446 	struct scsi_arq_status arqstat;
10447 	recov_info *rcif = pkt->pkt_private;
10448 
10449 	errstate rval = COMMAND_DONE_ERROR;
10450 	int amt;
10451 
10452 	ST_FUNC(ST_DEVINFO, st_handle_sense);
10453 
10454 	ASSERT(mutex_owned(ST_MUTEX));
10455 
10456 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10457 	    "st_handle_sense()\n");
10458 
10459 	if (SCBP(rqpkt)->sts_busy) {
10460 		if (rcif->privatelen == sizeof (recov_info)) {
10461 			ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
10462 			    "Attempt recovery of busy unit on request sense\n");
10463 			rval = ATTEMPT_RETRY;
10464 		} else if (rcif->pkt_retry_cnt++ < st_retry_count) {
10465 			ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10466 			    "Retry busy unit on request sense\n");
10467 			rval = QUE_BUSY_COMMAND;
10468 		}
10469 		return (rval);
10470 	} else if (SCBP(rqpkt)->sts_chk) {
10471 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10472 		    "Check Condition on REQUEST SENSE\n");
10473 		return (rval);
10474 	}
10475 
10476 	/*
10477 	 * Make sure there is sense data to look at.
10478 	 */
10479 	if ((rqpkt->pkt_state & (STATE_GOT_BUS | STATE_GOT_TARGET |
10480 	    STATE_SENT_CMD | STATE_GOT_STATUS)) != (STATE_GOT_BUS |
10481 	    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) {
10482 		return (rval);
10483 	}
10484 
10485 	/* was there enough data? */
10486 	amt = (int)MAX_SENSE_LENGTH - rqpkt->pkt_resid;
10487 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
10488 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10489 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10490 		    "REQUEST SENSE couldn't get sense data\n");
10491 		return (rval);
10492 	}
10493 
10494 	bcopy(SCBP(pkt), &arqstat.sts_status,
10495 	    sizeof (struct scsi_status));
10496 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
10497 	    sizeof (struct scsi_status));
10498 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
10499 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
10500 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
10501 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
10502 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
10503 
10504 	/*
10505 	 * copy one arqstat entry in the sense data buffer
10506 	 */
10507 	st_update_error_stack(un, pkt, &arqstat);
10508 	return (st_decode_sense(un, bp, amt, &arqstat, pos));
10509 }
10510 
10511 static errstate
10512 st_handle_autosense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10513 {
10514 	struct scsi_pkt *pkt = BP_PKT(bp);
10515 	struct scsi_arq_status *arqstat =
10516 	    (struct scsi_arq_status *)pkt->pkt_scbp;
10517 	errstate rval = COMMAND_DONE_ERROR;
10518 	int amt;
10519 
10520 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
10521 
10522 	ASSERT(mutex_owned(ST_MUTEX));
10523 
10524 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10525 	    "st_handle_autosense()\n");
10526 
10527 	if (arqstat->sts_rqpkt_status.sts_busy) {
10528 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10529 		    "busy unit on request sense\n");
10530 		/*
10531 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
10532 		 * the disadvantage is that we do not have any delay for the
10533 		 * second retry of rqsense and we have to keep a packet around
10534 		 */
10535 		return (QUE_SENSE);
10536 
10537 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
10538 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10539 		    "transport error on REQUEST SENSE\n");
10540 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
10541 		    ((arqstat->sts_rqpkt_statistics &
10542 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
10543 			if (st_reset(un, RESET_LUN) == 0) {
10544 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10545 				    "recovery by resets failed\n");
10546 			}
10547 		}
10548 		return (rval);
10549 
10550 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
10551 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10552 		    "Check Condition on REQUEST SENSE\n");
10553 		return (rval);
10554 	}
10555 
10556 
10557 	/* was there enough data? */
10558 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10559 		amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10560 	} else {
10561 		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
10562 			amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10563 		} else {
10564 			amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10565 		}
10566 	}
10567 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
10568 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10569 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10570 		    "REQUEST SENSE couldn't get sense data\n");
10571 		return (rval);
10572 	}
10573 
10574 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10575 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, MAX_SENSE_LENGTH);
10576 	} else {
10577 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
10578 	}
10579 
10580 	/*
10581 	 * copy one arqstat entry in the sense data buffer
10582 	 */
10583 	st_update_error_stack(un, pkt, arqstat);
10584 
10585 	return (st_decode_sense(un, bp, amt, arqstat, pos));
10586 }
10587 
10588 static errstate
10589 st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
10590     struct scsi_arq_status *statusp, tapepos_t *pos)
10591 {
10592 	struct scsi_pkt *pkt = BP_PKT(bp);
10593 	recov_info *ri = pkt->pkt_private;
10594 	errstate rval = COMMAND_DONE_ERROR;
10595 	cmd_attribute const *attrib;
10596 	long resid;
10597 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10598 	int severity;
10599 	int get_error;
10600 
10601 	ST_FUNC(ST_DEVINFO, st_decode_sense);
10602 
10603 	ASSERT(mutex_owned(ST_MUTEX));
10604 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10605 	    "st_decode_sense()\n");
10606 
10607 	/*
10608 	 * For uscsi commands, squirrel away a copy of the
10609 	 * results of the Request Sense.
10610 	 */
10611 	if (USCSI_CMD(bp)) {
10612 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
10613 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
10614 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
10615 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
10616 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
10617 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
10618 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10619 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
10620 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
10621 		}
10622 	}
10623 
10624 	if (ri->privatelen == sizeof (recov_info)) {
10625 		attrib = ri->cmd_attrib;
10626 	} else {
10627 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10628 	}
10629 
10630 	/*
10631 	 * If the drive is an MT-02, reposition the
10632 	 * secondary error code into the proper place.
10633 	 *
10634 	 * XXX	MT-02 is non-CCS tape, so secondary error code
10635 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
10636 	 * so it's in byte 12.
10637 	 */
10638 	if (un->un_dp->type == ST_TYPE_EMULEX) {
10639 		sensep->es_code = sensep->es_add_info[0];
10640 	}
10641 
10642 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
10643 	    (caddr_t)&CDBP(pkt)->scc_cmd);
10644 
10645 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)statusp,
10646 	    sizeof (*statusp));
10647 
10648 	/* for normal I/O check extract the resid values. */
10649 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
10650 		if (sensep->es_valid) {
10651 			resid =
10652 			    (sensep->es_info_1 << 24) |
10653 			    (sensep->es_info_2 << 16) |
10654 			    (sensep->es_info_3 << 8)  |
10655 			    (sensep->es_info_4);
10656 			/* If fixed block */
10657 			if (un->un_bsize) {
10658 				resid *= un->un_bsize;
10659 			}
10660 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
10661 			resid = pkt->pkt_resid;
10662 		} else {
10663 			resid = bp->b_bcount;
10664 		}
10665 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10666 		    "st_decode_sense (rw): xferred bit = %d, resid=%ld (%d), "
10667 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
10668 		    resid,
10669 		    (sensep->es_info_1 << 24) |
10670 		    (sensep->es_info_2 << 16) |
10671 		    (sensep->es_info_3 << 8)  |
10672 		    (sensep->es_info_4),
10673 		    pkt->pkt_resid);
10674 		/*
10675 		 * The problem is, what should we believe?
10676 		 */
10677 		if (resid && (pkt->pkt_resid == 0)) {
10678 			pkt->pkt_resid = resid;
10679 		}
10680 	} else {
10681 		/*
10682 		 * If the command is SCMD_SPACE, we need to get the
10683 		 * residual as returned in the sense data, to adjust
10684 		 * our idea of current tape position correctly
10685 		 */
10686 		if ((sensep->es_valid) &&
10687 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10688 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10689 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
10690 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE_G4) ||
10691 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK)) {
10692 			resid =
10693 			    (sensep->es_info_1 << 24) |
10694 			    (sensep->es_info_2 << 16) |
10695 			    (sensep->es_info_3 << 8)  |
10696 			    (sensep->es_info_4);
10697 			bp->b_resid = resid;
10698 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10699 			    "st_decode_sense(other):	resid=%ld\n", resid);
10700 		} else {
10701 			/*
10702 			 * If the special command is SCMD_READ,
10703 			 * the correct resid will be set later.
10704 			 */
10705 			if (attrib->get_cnt != NULL) {
10706 				resid = attrib->get_cnt(pkt->pkt_cdbp);
10707 			} else {
10708 				resid = bp->b_bcount;
10709 			}
10710 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10711 			    "st_decode_sense(special read):  resid=%ld\n",
10712 			    resid);
10713 		}
10714 	}
10715 
10716 	if ((un->un_state >= ST_STATE_OPEN) &&
10717 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
10718 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
10719 		    "Failed CDB", (char *)pkt->pkt_cdbp);
10720 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10721 		    "sense data", (char *)sensep, amt);
10722 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10723 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10724 		    bp->b_bcount, resid, pkt->pkt_resid);
10725 	}
10726 
10727 	switch (un->un_status = sensep->es_key) {
10728 	case KEY_NO_SENSE:
10729 		severity = SCSI_ERR_INFO;
10730 
10731 		/*
10732 		 * Erase, locate or rewind operation in progress, retry
10733 		 * ASC  ASCQ
10734 		 *  00   18    Erase operation in progress
10735 		 *  00   19    Locate operation in progress
10736 		 *  00   1A    Rewind operation in progress
10737 		 */
10738 		if (sensep->es_add_code == 0 &&
10739 		    ((sensep->es_qual_code == 0x18) ||
10740 		    (sensep->es_qual_code == 0x19) ||
10741 		    (sensep->es_qual_code == 0x1a))) {
10742 			rval = QUE_BUSY_COMMAND;
10743 			break;
10744 		}
10745 
10746 		goto common;
10747 
10748 	case KEY_RECOVERABLE_ERROR:
10749 		severity = SCSI_ERR_RECOVERED;
10750 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10751 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10752 			if (un->un_dp->options &
10753 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10754 				rval = QUE_LAST_COMMAND;
10755 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10756 				    severity, pos->lgclblkno,
10757 				    un->un_err_pos.lgclblkno, scsi_cmds,
10758 				    sensep);
10759 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10760 				    "Command will be retried\n");
10761 			} else {
10762 				severity = SCSI_ERR_FATAL;
10763 				rval = COMMAND_DONE_ERROR_RECOVERED;
10764 				ST_DO_ERRSTATS(un, st_softerrs);
10765 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10766 				    severity, pos->lgclblkno,
10767 				    un->un_err_pos.lgclblkno, scsi_cmds,
10768 				    sensep);
10769 			}
10770 			break;
10771 		}
10772 common:
10773 		/*
10774 		 * XXX only want reads to be stopped by filemarks.
10775 		 * Don't want them to be stopped by EOT.  EOT matters
10776 		 * only on write.
10777 		 */
10778 		if (sensep->es_filmk && !sensep->es_eom) {
10779 			rval = COMMAND_DONE;
10780 		} else if (sensep->es_eom) {
10781 			rval = COMMAND_DONE;
10782 		} else if (sensep->es_ili) {
10783 			/*
10784 			 * Fun with variable length record devices:
10785 			 * for specifying larger blocks sizes than the
10786 			 * actual physical record size.
10787 			 */
10788 			if (un->un_bsize == 0 && resid > 0) {
10789 				/*
10790 				 * XXX! Ugly.
10791 				 * The requested blocksize is > tape blocksize,
10792 				 * so this is ok, so we just return the
10793 				 * actual size xferred.
10794 				 */
10795 				pkt->pkt_resid = resid;
10796 				rval = COMMAND_DONE;
10797 			} else if (un->un_bsize == 0 && resid < 0) {
10798 				/*
10799 				 * The requested blocksize is < tape blocksize,
10800 				 * so this is not ok, so we err with ENOMEM
10801 				 */
10802 				rval = COMMAND_DONE_ERROR_RECOVERED;
10803 				st_bioerror(bp, ENOMEM);
10804 			} else {
10805 				ST_DO_ERRSTATS(un, st_softerrs);
10806 				severity = SCSI_ERR_FATAL;
10807 				rval = COMMAND_DONE_ERROR;
10808 				st_bioerror(bp, EINVAL);
10809 				un->un_running.pmode = invalid;
10810 			}
10811 		} else {
10812 			/*
10813 			 * we hope and pray for this just being
10814 			 * something we can ignore (ie. a
10815 			 * truly recoverable soft error)
10816 			 */
10817 			rval = COMMAND_DONE;
10818 		}
10819 		if (sensep->es_filmk) {
10820 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10821 			    "filemark\n");
10822 			un->un_status = SUN_KEY_EOF;
10823 			pos->eof = ST_EOF_PENDING;
10824 			st_set_pe_flag(un);
10825 		}
10826 
10827 		/*
10828 		 * ignore eom when reading, a fmk should terminate reading
10829 		 */
10830 		if ((sensep->es_eom) &&
10831 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10832 			if ((sensep->es_add_code == 0) &&
10833 			    (sensep->es_qual_code == 4)) {
10834 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10835 				    "bot\n");
10836 				un->un_status = SUN_KEY_BOT;
10837 				pos->eof = ST_NO_EOF;
10838 				pos->lgclblkno = 0;
10839 				pos->fileno = 0;
10840 				pos->blkno = 0;
10841 				if (pos->pmode != legacy)
10842 					pos->pmode = legacy;
10843 			} else {
10844 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10845 				    "eom\n");
10846 				un->un_status = SUN_KEY_EOT;
10847 				pos->eof = ST_EOM;
10848 			}
10849 			st_set_pe_flag(un);
10850 		}
10851 
10852 		break;
10853 
10854 	case KEY_ILLEGAL_REQUEST:
10855 
10856 		if (un->un_laststate >= ST_STATE_OPEN) {
10857 			ST_DO_ERRSTATS(un, st_softerrs);
10858 			severity = SCSI_ERR_FATAL;
10859 		} else {
10860 			severity = SCSI_ERR_INFO;
10861 		}
10862 		break;
10863 
10864 	case KEY_MEDIUM_ERROR:
10865 		ST_DO_ERRSTATS(un, st_harderrs);
10866 		severity = SCSI_ERR_FATAL;
10867 		un->un_pos.pmode = invalid;
10868 		un->un_running.pmode = invalid;
10869 check_keys:
10870 		/*
10871 		 * attempt to process the keys in the presence of
10872 		 * other errors
10873 		 */
10874 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10875 			/*
10876 			 * Fun with variable length record devices:
10877 			 * for specifying larger blocks sizes than the
10878 			 * actual physical record size.
10879 			 */
10880 			if (un->un_bsize == 0 && resid > 0) {
10881 				/*
10882 				 * XXX! Ugly
10883 				 */
10884 				pkt->pkt_resid = resid;
10885 			} else if (un->un_bsize == 0 && resid < 0) {
10886 				st_bioerror(bp, EINVAL);
10887 			} else {
10888 				severity = SCSI_ERR_FATAL;
10889 				rval = COMMAND_DONE_ERROR;
10890 				st_bioerror(bp, EINVAL);
10891 			}
10892 		}
10893 		if (sensep->es_filmk) {
10894 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10895 			    "filemark\n");
10896 			un->un_status = SUN_KEY_EOF;
10897 			pos->eof = ST_EOF_PENDING;
10898 			st_set_pe_flag(un);
10899 		}
10900 
10901 		/*
10902 		 * ignore eom when reading, a fmk should terminate reading
10903 		 */
10904 		if ((sensep->es_eom) &&
10905 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10906 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10907 			un->un_status = SUN_KEY_EOT;
10908 			pos->eof = ST_EOM;
10909 			st_set_pe_flag(un);
10910 		}
10911 
10912 		break;
10913 
10914 	case KEY_VOLUME_OVERFLOW:
10915 		ST_DO_ERRSTATS(un, st_softerrs);
10916 		pos->eof = ST_EOM;
10917 		severity = SCSI_ERR_FATAL;
10918 		rval = COMMAND_DONE_ERROR;
10919 		goto check_keys;
10920 
10921 	case KEY_HARDWARE_ERROR:
10922 		ST_DO_ERRSTATS(un, st_harderrs);
10923 		severity = SCSI_ERR_FATAL;
10924 		rval = COMMAND_DONE_ERROR;
10925 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10926 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10927 		break;
10928 
10929 	case KEY_BLANK_CHECK:
10930 		ST_DO_ERRSTATS(un, st_softerrs);
10931 		severity = SCSI_ERR_INFO;
10932 
10933 		/*
10934 		 * if not a special request and some data was xferred then it
10935 		 * it is not an error yet
10936 		 */
10937 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10938 			/*
10939 			 * no error for read with or without data xferred
10940 			 */
10941 			un->un_status = SUN_KEY_EOT;
10942 			pos->eof = ST_EOT;
10943 			rval = COMMAND_DONE_ERROR;
10944 			un->un_running.pmode = invalid;
10945 			st_set_pe_flag(un);
10946 			goto check_keys;
10947 		} else if (bp != un->un_sbufp &&
10948 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10949 			rval = COMMAND_DONE;
10950 		} else {
10951 			rval = COMMAND_DONE_ERROR_RECOVERED;
10952 		}
10953 
10954 		if (un->un_laststate >= ST_STATE_OPEN) {
10955 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10956 			    "blank check\n");
10957 			pos->eof = ST_EOM;
10958 		}
10959 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10960 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10961 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
10962 		    (un->un_dp->options & ST_KNOWS_EOD)) {
10963 			/*
10964 			 * we were doing a fast forward by skipping
10965 			 * multiple fmk at the time
10966 			 */
10967 			st_bioerror(bp, EIO);
10968 			severity = SCSI_ERR_RECOVERED;
10969 			rval	 = COMMAND_DONE;
10970 		}
10971 		st_set_pe_flag(un);
10972 		goto check_keys;
10973 
10974 	case KEY_WRITE_PROTECT:
10975 		if (st_wrongtapetype(un)) {
10976 			un->un_status = SUN_KEY_WRONGMEDIA;
10977 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10978 			    "wrong tape for writing- use DC6150 tape "
10979 			    "(or equivalent)\n");
10980 			severity = SCSI_ERR_UNKNOWN;
10981 		} else {
10982 			severity = SCSI_ERR_FATAL;
10983 		}
10984 		ST_DO_ERRSTATS(un, st_harderrs);
10985 		rval = COMMAND_DONE_ERROR;
10986 		st_bioerror(bp, EACCES);
10987 		break;
10988 
10989 	case KEY_UNIT_ATTENTION:
10990 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10991 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
10992 
10993 		un->un_unit_attention_flags |= 1;
10994 		/*
10995 		 * If we have detected a Bus Reset and the tape
10996 		 * drive has been reserved.
10997 		 */
10998 		if (ST_RQSENSE->es_add_code == 0x29) {
10999 			rval = DEVICE_RESET;
11000 			if ((un->un_rsvd_status &
11001 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
11002 			    ST_RESERVE) {
11003 				un->un_rsvd_status |= ST_LOST_RESERVE;
11004 				ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
11005 				    "st_decode_sense: Lost Reservation\n");
11006 			}
11007 		}
11008 
11009 		/*
11010 		 * If this is a recovery command and retrable, retry.
11011 		 */
11012 		if (bp == un->un_recov_buf) {
11013 			severity = SCSI_ERR_INFO;
11014 			if (attrib->retriable &&
11015 			    ri->pkt_retry_cnt++ < st_retry_count) {
11016 				rval = QUE_COMMAND;
11017 			} else {
11018 				rval = COMMAND_DONE_ERROR;
11019 			}
11020 			break; /* Don't set position invalid */
11021 		}
11022 
11023 		/*
11024 		 * If ST_APPLICATION_RESERVATIONS is set,
11025 		 * If the asc/ascq indicates that the reservation
11026 		 * has been cleared just allow the write to continue
11027 		 * which would force a scsi 2 reserve.
11028 		 * If preempted that persistent reservation
11029 		 * the scsi 2 reserve would get a reservation conflict.
11030 		 */
11031 		if ((un->un_rsvd_status &
11032 		    ST_APPLICATION_RESERVATIONS) != 0) {
11033 			/*
11034 			 * RESERVATIONS PREEMPTED
11035 			 * With MPxIO this could be a fail over? XXX
11036 			 */
11037 			if (ST_RQSENSE->es_add_code == 0x2a &&
11038 			    ST_RQSENSE->es_qual_code == 0x03) {
11039 				severity = SCSI_ERR_INFO;
11040 				rval = COMMAND_DONE_ERROR;
11041 				pos->pmode = invalid;
11042 				break;
11043 			/*
11044 			 * RESERVATIONS RELEASED
11045 			 */
11046 			} else if (ST_RQSENSE->es_add_code == 0x2a &&
11047 			    ST_RQSENSE->es_qual_code == 0x04) {
11048 				severity = SCSI_ERR_INFO;
11049 				rval = COMMAND_DONE;
11050 				break;
11051 			}
11052 		}
11053 
11054 		if (un->un_state <= ST_STATE_OPENING) {
11055 			/*
11056 			 * Look, the tape isn't open yet, now determine
11057 			 * if the cause is a BUS RESET, Save the file
11058 			 * and Block positions for the callers to
11059 			 * recover from the loss of position.
11060 			 */
11061 			severity = SCSI_ERR_INFO;
11062 			if ((pos->pmode != invalid) &&
11063 			    (rval == DEVICE_RESET) &&
11064 			    (un->un_restore_pos != 1)) {
11065 				un->un_save_fileno = pos->fileno;
11066 				un->un_save_blkno = pos->blkno;
11067 				un->un_restore_pos = 1;
11068 			}
11069 
11070 			if (attrib->retriable &&
11071 			    ri->pkt_retry_cnt++ < st_retry_count) {
11072 				rval = QUE_COMMAND;
11073 			} else if (rval == DEVICE_RESET) {
11074 				break;
11075 			} else {
11076 				rval = COMMAND_DONE_ERROR;
11077 			}
11078 		/*
11079 		 * Means it thinks the mode parameters have changed.
11080 		 * This is the result of a reset clearing settings or
11081 		 * another initiator changing what we set.
11082 		 */
11083 		}
11084 		if (ST_RQSENSE->es_add_code == 0x2a) {
11085 			if (ST_RQSENSE->es_qual_code == 0x1) {
11086 				/* Error recovery will modeselect and retry. */
11087 				rval = DEVICE_TAMPER;
11088 				severity = SCSI_ERR_INFO;
11089 				break; /* don't set position invalid */
11090 			}
11091 			if (ST_RQSENSE->es_qual_code == 0x0 ||
11092 			    ST_RQSENSE->es_qual_code == 0x2 ||
11093 			    ST_RQSENSE->es_qual_code == 0x3 ||
11094 			    ST_RQSENSE->es_qual_code == 0x4 ||
11095 			    ST_RQSENSE->es_qual_code == 0x5 ||
11096 			    ST_RQSENSE->es_qual_code == 0x6 ||
11097 			    ST_RQSENSE->es_qual_code == 0x7) {
11098 				rval = DEVICE_TAMPER;
11099 				severity = SCSI_ERR_INFO;
11100 			}
11101 		} else if (ST_RQSENSE->es_add_code == 0x28 &&
11102 		    ((ST_RQSENSE->es_qual_code == 0x0) ||
11103 		    ST_RQSENSE->es_qual_code == 0x5)) {
11104 			/*
11105 			 * Not Ready to Ready change, Media may have changed.
11106 			 */
11107 			rval = DEVICE_TAMPER;
11108 			severity = SCSI_ERR_RETRYABLE;
11109 		} else {
11110 			if (rval != DEVICE_RESET) {
11111 				rval = COMMAND_DONE_ERROR;
11112 			} else {
11113 				/*
11114 				 * Returning DEVICE_RESET will call
11115 				 * error recovery.
11116 				 */
11117 				severity = SCSI_ERR_INFO;
11118 				break; /* don't set position invalid */
11119 			}
11120 			/*
11121 			 * Check if it is an Unexpected Unit Attention.
11122 			 * If state is >= ST_STATE_OPEN, we have
11123 			 * already done the initialization .
11124 			 * In this case it is Fatal Error
11125 			 * since no further reading/writing
11126 			 * can be done with fileno set to < 0.
11127 			 */
11128 			if (un->un_state >= ST_STATE_OPEN) {
11129 				ST_DO_ERRSTATS(un, st_harderrs);
11130 				severity = SCSI_ERR_FATAL;
11131 			} else {
11132 				severity = SCSI_ERR_INFO;
11133 			}
11134 		}
11135 
11136 		pos->pmode = invalid;
11137 
11138 		break;
11139 
11140 	case KEY_NOT_READY:
11141 		/*
11142 		 * If in process of getting ready retry.
11143 		 */
11144 		if (sensep->es_add_code == 0x04) {
11145 			switch (sensep->es_qual_code) {
11146 			case 0x07:
11147 				/*
11148 				 * We get here when the tape is rewinding.
11149 				 * QUE_BUSY_COMMAND retries every 10 seconds.
11150 				 */
11151 				if (ri->pkt_retry_cnt++ <
11152 				    (un->un_dp->rewind_timeout / 10)) {
11153 					rval = QUE_BUSY_COMMAND;
11154 					severity = SCSI_ERR_INFO;
11155 				} else {
11156 					/* give up */
11157 					rval = COMMAND_DONE_ERROR;
11158 					severity = SCSI_ERR_FATAL;
11159 				}
11160 				break;
11161 			case 0x01:
11162 				if (ri->pkt_retry_cnt++ < st_retry_count) {
11163 					rval = QUE_COMMAND;
11164 					severity = SCSI_ERR_INFO;
11165 					break;
11166 				}
11167 			default: /* FALLTHRU */
11168 				/* give up */
11169 				rval = COMMAND_DONE_ERROR;
11170 				severity = SCSI_ERR_FATAL;
11171 			}
11172 		} else {
11173 			/* give up */
11174 			rval = COMMAND_DONE_ERROR;
11175 			severity = SCSI_ERR_FATAL;
11176 		}
11177 
11178 		/*
11179 		 * If this was an error and after device opened
11180 		 * do error stats.
11181 		 */
11182 		if (rval == COMMAND_DONE_ERROR &&
11183 		    un->un_state > ST_STATE_OPENING) {
11184 			ST_DO_ERRSTATS(un, st_harderrs);
11185 		}
11186 
11187 		if (ST_RQSENSE->es_add_code == 0x3a) {
11188 			if (st_error_level >= SCSI_ERR_FATAL)
11189 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11190 				    "Tape not inserted in drive\n");
11191 			un->un_mediastate = MTIO_EJECTED;
11192 			cv_broadcast(&un->un_state_cv);
11193 		}
11194 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
11195 		    (rval != QUE_COMMAND))
11196 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
11197 		break;
11198 
11199 	case KEY_ABORTED_COMMAND:
11200 		/* XXX Do drives return this when they see a lost light? */
11201 		/* Testing would say yes */
11202 
11203 		if (ri->pkt_retry_cnt++ < st_retry_count) {
11204 			rval = ATTEMPT_RETRY;
11205 			severity = SCSI_ERR_RETRYABLE;
11206 			goto check_keys;
11207 		}
11208 		/*
11209 		 * Probably a parity error...
11210 		 * if we retry here then this may cause data to be
11211 		 * written twice or data skipped during reading
11212 		 */
11213 		ST_DO_ERRSTATS(un, st_harderrs);
11214 		severity = SCSI_ERR_FATAL;
11215 		rval = COMMAND_DONE_ERROR;
11216 		goto check_keys;
11217 
11218 	default:
11219 		/*
11220 		 * Undecoded sense key.	 Try retries and hope
11221 		 * that will fix the problem.  Otherwise, we're
11222 		 * dead.
11223 		 */
11224 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11225 		    "Unhandled Sense Key '%s'\n",
11226 		    sense_keys[un->un_status]);
11227 		ST_DO_ERRSTATS(un, st_harderrs);
11228 		severity = SCSI_ERR_FATAL;
11229 		rval = COMMAND_DONE_ERROR;
11230 		goto check_keys;
11231 	}
11232 
11233 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
11234 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
11235 	    (un->un_laststate > ST_STATE_OPENING) &&
11236 	    (severity >= st_error_level))) {
11237 
11238 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
11239 		    pos->lgclblkno, un->un_err_pos.lgclblkno,
11240 		    scsi_cmds, sensep);
11241 		if (sensep->es_filmk) {
11242 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11243 			    "File Mark Detected\n");
11244 		}
11245 		if (sensep->es_eom) {
11246 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11247 			    "End-of-Media Detected\n");
11248 		}
11249 		if (sensep->es_ili) {
11250 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11251 			    "Incorrect Length Indicator Set\n");
11252 		}
11253 	}
11254 	get_error = geterror(bp);
11255 	if (((rval == COMMAND_DONE_ERROR) ||
11256 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
11257 	    ((get_error == EIO) || (get_error == 0))) {
11258 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
11259 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
11260 		if (un->un_rqs_state & ST_RQS_READ) {
11261 			un->un_rqs_state &= ~(ST_RQS_READ);
11262 		} else {
11263 			un->un_rqs_state |= ST_RQS_OVR;
11264 		}
11265 	}
11266 
11267 	return (rval);
11268 }
11269 
11270 
11271 static int
11272 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
11273 {
11274 	int status = TRAN_ACCEPT;
11275 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
11276 
11277 	mutex_enter(ST_MUTEX);
11278 
11279 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
11280 
11281 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11282 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
11283 
11284 	/*
11285 	 * Check to see if we hit the retry timeout. We check to make sure
11286 	 * this is the first one on the runq and make sure we have not
11287 	 * queued up any more, so this one has to be the last on the list
11288 	 * also. If it is not, we have to fail.  If it is not the first, but
11289 	 * is the last we are in trouble anyway, as we are in the interrupt
11290 	 * context here.
11291 	 */
11292 	if ((pktinfo->pkt_retry_cnt > st_retry_count) ||
11293 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
11294 		goto exit;
11295 	}
11296 
11297 	if (un->un_throttle) {
11298 		un->un_last_throttle = un->un_throttle;
11299 		un->un_throttle = 0;
11300 	}
11301 
11302 	/*
11303 	 * Here we know : bp is the first and last one on the runq
11304 	 * it is not necessary to put it back on the head of the
11305 	 * waitq and then move from waitq to runq. Save this queuing
11306 	 * and call scsi_transport.
11307 	 */
11308 	ST_CDB(ST_DEVINFO, "Retry lcmd CDB", (char *)BP_PKT(bp)->pkt_cdbp);
11309 
11310 	status = st_transport(un, BP_PKT(bp));
11311 
11312 	if (status == TRAN_ACCEPT) {
11313 		if (un->un_last_throttle) {
11314 			un->un_throttle = un->un_last_throttle;
11315 		}
11316 		mutex_exit(ST_MUTEX);
11317 
11318 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11319 		    "restart transport \n");
11320 		return (0);
11321 	}
11322 
11323 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
11324 	mutex_exit(ST_MUTEX);
11325 
11326 	if (status == TRAN_BUSY) {
11327 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
11328 			return (0);
11329 		}
11330 	}
11331 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11332 	    "restart transport rejected\n");
11333 	mutex_enter(ST_MUTEX);
11334 	ST_DO_ERRSTATS(un, st_transerrs);
11335 	if (un->un_last_throttle) {
11336 		un->un_throttle = un->un_last_throttle;
11337 	}
11338 exit:
11339 	mutex_exit(ST_MUTEX);
11340 	return (-1);
11341 }
11342 
11343 static int
11344 st_wrongtapetype(struct scsi_tape *un)
11345 {
11346 
11347 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
11348 
11349 	ASSERT(mutex_owned(ST_MUTEX));
11350 
11351 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
11352 
11353 	/*
11354 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
11355 	 */
11356 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
11357 		switch (un->un_dp->type) {
11358 		case ST_TYPE_WANGTEK:
11359 		case ST_TYPE_ARCHIVE:
11360 			/*
11361 			 * If this really worked, we could go off of
11362 			 * the density codes set in the modesense
11363 			 * page. For this drive, 0x10 == QIC-120,
11364 			 * 0xf == QIC-150, and 0x5 should be for
11365 			 * both QIC-24 and, maybe, QIC-11. However,
11366 			 * the h/w doesn't do what the manual says
11367 			 * that it should, so we'll key off of
11368 			 * getting a WRITE PROTECT error AND wp *not*
11369 			 * set in the mode sense information.
11370 			 */
11371 			/*
11372 			 * XXX but we already know that status is
11373 			 * write protect, so don't check it again.
11374 			 */
11375 
11376 			if (un->un_status == KEY_WRITE_PROTECT &&
11377 			    un->un_mspl->wp == 0) {
11378 				return (1);
11379 			}
11380 			break;
11381 		default:
11382 			break;
11383 		}
11384 	}
11385 	return (0);
11386 }
11387 
11388 static errstate
11389 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
11390 {
11391 	errstate action;
11392 	recov_info *rcvi = pkt->pkt_private;
11393 	buf_t *bp = rcvi->cmd_bp;
11394 	struct scsi_arq_status *stat = (struct scsi_arq_status *)pkt->pkt_scbp;
11395 
11396 	ST_FUNC(ST_DEVINFO, st_check_error);
11397 
11398 	ASSERT(mutex_owned(ST_MUTEX));
11399 
11400 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
11401 
11402 	switch (SCBP_C(pkt)) {
11403 	case STATUS_RESERVATION_CONFLICT:
11404 		/*
11405 		 * Command recovery is enabled, not just opening,
11406 		 * we had the drive reserved and we thing its ours.
11407 		 * Call recovery to attempt to take it back.
11408 		 */
11409 		if ((rcvi->privatelen == sizeof (recov_info)) &&
11410 		    (bp != un->un_recov_buf) &&
11411 		    (un->un_state > ST_STATE_OPEN_PENDING_IO) &&
11412 		    ((un->un_rsvd_status & (ST_RESERVE |
11413 		    ST_APPLICATION_RESERVATIONS)) != 0)) {
11414 			action = ATTEMPT_RETRY;
11415 			un->un_rsvd_status |= ST_LOST_RESERVE;
11416 		} else {
11417 			action = COMMAND_DONE_EACCES;
11418 			un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
11419 		}
11420 		break;
11421 
11422 	case STATUS_BUSY:
11423 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
11424 		if (rcvi->privatelen == sizeof (recov_info) &&
11425 		    un->un_multipath && (pkt->pkt_state == (STATE_GOT_BUS |
11426 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS))) {
11427 			/*
11428 			 * Status returned by scsi_vhci indicating path
11429 			 * has failed over.
11430 			 */
11431 			action = PATH_FAILED;
11432 			break;
11433 		}
11434 		/* FALLTHRU */
11435 	case STATUS_QFULL:
11436 		if (rcvi->privatelen == sizeof (recov_info)) {
11437 			/*
11438 			 * If recovery is inabled use it instead of
11439 			 * blind reties.
11440 			 */
11441 			action = ATTEMPT_RETRY;
11442 		} else if (rcvi->pkt_retry_cnt++ < st_retry_count) {
11443 			action = QUE_BUSY_COMMAND;
11444 		} else if ((un->un_rsvd_status &
11445 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
11446 			/*
11447 			 * If this is a command done before reserve is done
11448 			 * don't reset.
11449 			 */
11450 			action = COMMAND_DONE_ERROR;
11451 		} else {
11452 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11453 			    "unit busy too long\n");
11454 			(void) st_reset(un, RESET_ALL);
11455 			action = COMMAND_DONE_ERROR;
11456 		}
11457 		break;
11458 
11459 	case STATUS_CHECK:
11460 	case STATUS_TERMINATED:
11461 		/*
11462 		 * we should only get here if the auto rqsense failed
11463 		 * thru a uscsi cmd without autorequest sense
11464 		 * so we just try again
11465 		 */
11466 		if (un->un_arq_enabled &&
11467 		    stat->sts_rqpkt_reason == CMD_CMPLT &&
11468 		    (stat->sts_rqpkt_state & (STATE_GOT_BUS |
11469 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) ==
11470 		    (STATE_GOT_BUS | STATE_GOT_TARGET | STATE_SENT_CMD |
11471 		    STATE_GOT_STATUS)) {
11472 
11473 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11474 			    "Really got sense data\n");
11475 			action = st_decode_sense(un, bp, MAX_SENSE_LENGTH -
11476 			    pkt->pkt_resid, stat, &un->un_pos);
11477 		} else {
11478 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11479 			    "Trying to queue sense command\n");
11480 			action = QUE_SENSE;
11481 		}
11482 		break;
11483 
11484 	case STATUS_TASK_ABORT:
11485 		/*
11486 		 * This is an aborted task. This can be a reset on the other
11487 		 * port of a multiport drive. Lets try and recover it.
11488 		 */
11489 		action = DEVICE_RESET;
11490 		break;
11491 
11492 	default:
11493 		action = COMMAND_DONE;
11494 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
11495 		    "Unexpected scsi status byte 0x%x\n", SCBP_C(pkt));
11496 	}
11497 	return (action);
11498 }
11499 
11500 static void
11501 st_calc_bnum(struct scsi_tape *un, struct buf *bp, struct scsi_pkt *pkt)
11502 {
11503 	int nblks;
11504 	int nfiles;
11505 	long count;
11506 	recov_info *ri = pkt->pkt_private;
11507 	cmd_attribute const *attrib;
11508 
11509 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
11510 
11511 	ASSERT(mutex_owned(ST_MUTEX));
11512 
11513 	if (ri->privatelen == sizeof (recov_info)) {
11514 		attrib = ri->cmd_attrib;
11515 		ASSERT(attrib->recov_pos_type == POS_EXPECTED);
11516 		ASSERT(attrib->chg_tape_pos);
11517 	} else {
11518 		ri = NULL;
11519 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
11520 	}
11521 
11522 	count = bp->b_bcount - bp->b_resid;
11523 
11524 	/* Command reads or writes data */
11525 	if (attrib->transfers_data != TRAN_NONE) {
11526 		if (count == 0) {
11527 			/* failed writes should not make it here */
11528 			ASSERT(attrib->transfers_data == TRAN_READ);
11529 			nblks = 0;
11530 			nfiles = 1;
11531 		} else if (un->un_bsize == 0) {
11532 			/*
11533 			 * If variable block mode.
11534 			 * Fixed bit in CBD should be zero.
11535 			 */
11536 			ASSERT((pkt->pkt_cdbp[1] & 1) == 0);
11537 			nblks = 1;
11538 			un->un_kbytes_xferred += (count / ONE_K);
11539 			nfiles = 0;
11540 		} else {
11541 			/*
11542 			 * If fixed block mode.
11543 			 * Fixed bit in CBD should be one.
11544 			 */
11545 			ASSERT((pkt->pkt_cdbp[1] & 1) == 1);
11546 			nblks = (count / un->un_bsize);
11547 			un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
11548 			nfiles = 0;
11549 		}
11550 		/*
11551 		 * So its possable to read some blocks and hit a filemark.
11552 		 * Example reading in fixed block mode where more then one
11553 		 * block at a time is requested. In this case because the
11554 		 * filemark is hit something less then the requesed number
11555 		 * of blocks is read.
11556 		 */
11557 		if (un->un_pos.eof == ST_EOF_PENDING && bp->b_resid) {
11558 			nfiles = 1;
11559 		}
11560 	} else {
11561 		nblks = 0;
11562 		nfiles = count;
11563 	}
11564 
11565 	/*
11566 	 * If some command failed after this one started and it seems
11567 	 * to have finshed without error count the position.
11568 	 */
11569 	if (un->un_persistence && un->un_persist_errors) {
11570 		ASSERT(un->un_pos.pmode != invalid);
11571 	}
11572 
11573 	if (attrib->chg_tape_direction == DIR_FORW) {
11574 		un->un_pos.blkno += nblks;
11575 		un->un_pos.lgclblkno += nblks;
11576 		un->un_pos.lgclblkno += nfiles;
11577 	} else if (attrib->chg_tape_direction == DIR_REVC) {
11578 		un->un_pos.blkno -= nblks;
11579 		un->un_pos.lgclblkno -= nblks;
11580 		un->un_pos.lgclblkno -= nfiles;
11581 	} else {
11582 		ASSERT(0);
11583 	}
11584 
11585 	/* recovery disabled */
11586 	if (ri == NULL) {
11587 		un->un_running.pmode = invalid;
11588 		return;
11589 	}
11590 
11591 	/*
11592 	 * If we didn't just read a filemark.
11593 	 */
11594 	if (un->un_pos.eof != ST_EOF_PENDING) {
11595 		ASSERT(nblks != 0 && nfiles == 0);
11596 		/*
11597 		 * If Previously calulated expected position does not match
11598 		 * debug the expected position.
11599 		 */
11600 		if ((ri->pos.pmode != invalid) && nblks &&
11601 		    ((un->un_pos.blkno != ri->pos.blkno) ||
11602 		    (un->un_pos.lgclblkno != ri->pos.lgclblkno))) {
11603 #ifdef STDEBUG
11604 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11605 			    "Expected", &ri->pos);
11606 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11607 			    "But Got", &un->un_pos);
11608 #endif
11609 			un->un_running.pmode = invalid;
11610 		}
11611 	} else {
11612 		ASSERT(nfiles != 0);
11613 		if (un->un_running.pmode != invalid) {
11614 			/*
11615 			 * blkno and lgclblkno already counted in
11616 			 * st_add_recovery_info_to_pkt(). Since a block was not
11617 			 * read and a filemark was.
11618 			 */
11619 			if (attrib->chg_tape_direction == DIR_FORW) {
11620 				un->un_running.fileno++;
11621 				un->un_running.blkno = 0;
11622 			} else if (attrib->chg_tape_direction == DIR_REVC) {
11623 				un->un_running.fileno--;
11624 				un->un_running.blkno = LASTBLK;
11625 			}
11626 		}
11627 	}
11628 }
11629 
11630 static void
11631 st_set_state(struct scsi_tape *un, struct buf *bp)
11632 {
11633 	struct scsi_pkt *sp = BP_PKT(bp);
11634 	struct uscsi_cmd *ucmd;
11635 
11636 	ST_FUNC(ST_DEVINFO, st_set_state);
11637 
11638 	ASSERT(mutex_owned(ST_MUTEX));
11639 	ASSERT(bp != un->un_recov_buf);
11640 
11641 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11642 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
11643 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
11644 
11645 	if (bp != un->un_sbufp) {
11646 #ifdef STDEBUG
11647 		if (DEBUGGING && sp->pkt_resid) {
11648 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11649 			    "pkt_resid %ld bcount %ld\n",
11650 			    sp->pkt_resid, bp->b_bcount);
11651 		}
11652 #endif
11653 		bp->b_resid = sp->pkt_resid;
11654 		if (geterror(bp) != EIO) {
11655 			st_calc_bnum(un, bp, sp);
11656 		}
11657 		if (bp->b_flags & B_READ) {
11658 			un->un_lastop = ST_OP_READ;
11659 			un->un_fmneeded = 0;
11660 		} else {
11661 			un->un_lastop = ST_OP_WRITE;
11662 			if (un->un_dp->options & ST_REEL) {
11663 				un->un_fmneeded = 2;
11664 			} else {
11665 				un->un_fmneeded = 1;
11666 			}
11667 		}
11668 		/*
11669 		 * all is honky dory at this point, so let's
11670 		 * readjust the throttle, to increase speed, if we
11671 		 * have not throttled down.
11672 		 */
11673 		if (un->un_throttle) {
11674 			un->un_throttle = un->un_max_throttle;
11675 		}
11676 	} else {
11677 		optype new_lastop = ST_OP_NIL;
11678 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
11679 
11680 		switch (cmd) {
11681 		case SCMD_WRITE:
11682 		case SCMD_WRITE_G4:
11683 			bp->b_resid = sp->pkt_resid;
11684 			new_lastop = ST_OP_WRITE;
11685 			if (geterror(bp) == EIO) {
11686 				break;
11687 			}
11688 			st_calc_bnum(un, bp, sp);
11689 			if (un->un_dp->options & ST_REEL) {
11690 				un->un_fmneeded = 2;
11691 			} else {
11692 				un->un_fmneeded = 1;
11693 			}
11694 			break;
11695 		case SCMD_READ:
11696 		case SCMD_READ_G4:
11697 			bp->b_resid = sp->pkt_resid;
11698 			new_lastop = ST_OP_READ;
11699 			if (geterror(bp) == EIO) {
11700 				break;
11701 			}
11702 			st_calc_bnum(un, bp, sp);
11703 			un->un_fmneeded = 0;
11704 			break;
11705 		case SCMD_WRITE_FILE_MARK_G4:
11706 		case SCMD_WRITE_FILE_MARK:
11707 		{
11708 			int fmdone;
11709 
11710 			if (un->un_pos.eof != ST_EOM) {
11711 				un->un_pos.eof = ST_NO_EOF;
11712 			}
11713 			fmdone = (bp->b_bcount - bp->b_resid);
11714 			if (fmdone > 0) {
11715 				un->un_lastop = new_lastop = ST_OP_WEOF;
11716 				un->un_pos.lgclblkno += fmdone;
11717 				un->un_pos.fileno += fmdone;
11718 				un->un_pos.blkno = 0;
11719 			} else {
11720 				new_lastop = ST_OP_CTL;
11721 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11722 				    "Flushed buffer\n");
11723 			}
11724 			if (fmdone > un->un_fmneeded) {
11725 				un->un_fmneeded = 0;
11726 			} else {
11727 				un->un_fmneeded -= fmdone;
11728 			}
11729 			break;
11730 		}
11731 		case SCMD_REWIND:
11732 			un->un_pos.eof = ST_NO_EOF;
11733 			un->un_pos.fileno = 0;
11734 			un->un_pos.blkno = 0;
11735 			un->un_pos.lgclblkno = 0;
11736 			if (un->un_pos.pmode != legacy)
11737 				un->un_pos.pmode = legacy;
11738 			new_lastop = ST_OP_CTL;
11739 			un->un_restore_pos = 0;
11740 			break;
11741 
11742 		case SCMD_SPACE:
11743 		case SCMD_SPACE_G4:
11744 		{
11745 			int64_t count;
11746 			int64_t resid;
11747 			int64_t done;
11748 			cmd_attribute const *attrib;
11749 			recov_info *ri = sp->pkt_private;
11750 
11751 			if (ri->privatelen == sizeof (recov_info)) {
11752 				attrib = ri->cmd_attrib;
11753 			} else {
11754 				attrib =
11755 				    st_lookup_cmd_attribute(sp->pkt_cdbp[0]);
11756 			}
11757 
11758 			resid = (int64_t)SPACE_CNT(bp->b_resid);
11759 			count = (int64_t)attrib->get_cnt(sp->pkt_cdbp);
11760 
11761 			if (count >= 0) {
11762 				done = (count - resid);
11763 			} else {
11764 				done = ((-count) - resid);
11765 			}
11766 			if (done > 0) {
11767 				un->un_lastop = new_lastop = ST_OP_CTL;
11768 			} else {
11769 				new_lastop = ST_OP_CTL;
11770 			}
11771 
11772 			ST_SPAC(ST_DEVINFO, st_label, CE_WARN,
11773 			    "space cmd: cdb[1] = %s\n"
11774 			    "space data:       = 0x%lx\n"
11775 			    "space count:      = %"PRId64"\n"
11776 			    "space resid:      = %"PRId64"\n"
11777 			    "spaces done:      = %"PRId64"\n"
11778 			    "fileno before     = %d\n"
11779 			    "blkno before      = %d\n",
11780 			    space_strs[sp->pkt_cdbp[1] & 7],
11781 			    bp->b_bcount,
11782 			    count, resid, done,
11783 			    un->un_pos.fileno, un->un_pos.blkno);
11784 
11785 			switch (sp->pkt_cdbp[1]) {
11786 			case SPACE_TYPE(SP_FLM):
11787 				/* Space file forward */
11788 				if (count >= 0) {
11789 					if (un->un_pos.eof <= ST_EOF) {
11790 						un->un_pos.eof = ST_NO_EOF;
11791 					}
11792 					un->un_pos.fileno += done;
11793 					un->un_pos.blkno = 0;
11794 					break;
11795 				}
11796 				/* Space file backward */
11797 				if (done > un->un_pos.fileno) {
11798 					un->un_pos.fileno = 0;
11799 					un->un_pos.blkno = 0;
11800 				} else {
11801 					un->un_pos.fileno -= done;
11802 					un->un_pos.blkno = LASTBLK;
11803 					un->un_running.pmode = invalid;
11804 				}
11805 				break;
11806 			case SPACE_TYPE(SP_BLK):
11807 				/* Space block forward */
11808 				if (count >= 0) {
11809 					un->un_pos.blkno += done;
11810 					break;
11811 				}
11812 				/* Space block backward */
11813 				if (un->un_pos.eof >= ST_EOF_PENDING) {
11814 				/*
11815 				 * we stepped back into
11816 				 * a previous file; we are not
11817 				 * making an effort to pretend that
11818 				 * we are still in the current file
11819 				 * ie. logical == physical position
11820 				 * and leave it to st_ioctl to correct
11821 				 */
11822 					if (done > un->un_pos.blkno) {
11823 						un->un_pos.blkno = 0;
11824 					} else {
11825 						un->un_pos.fileno--;
11826 						un->un_pos.blkno = LASTBLK;
11827 						un->un_running.pmode = invalid;
11828 					}
11829 				} else {
11830 					un->un_pos.blkno -= done;
11831 				}
11832 				break;
11833 			case SPACE_TYPE(SP_SQFLM):
11834 				un->un_pos.pmode = logical;
11835 				un->un_pos.blkno = 0;
11836 				un->un_lastop = new_lastop = ST_OP_CTL;
11837 				break;
11838 			case SPACE_TYPE(SP_EOD):
11839 				un->un_pos.pmode = logical;
11840 				un->un_pos.eof = ST_EOM;
11841 				un->un_status = KEY_BLANK_CHECK;
11842 				break;
11843 			default:
11844 				un->un_pos.pmode = invalid;
11845 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11846 				    "Unsupported space cmd: %s\n",
11847 				    space_strs[sp->pkt_cdbp[1] & 7]);
11848 
11849 				un->un_lastop = new_lastop = ST_OP_CTL;
11850 			}
11851 
11852 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11853 			    "after_space rs %"PRId64" fil %d blk %d\n",
11854 			    resid, un->un_pos.fileno, un->un_pos.blkno);
11855 
11856 			break;
11857 		}
11858 		case SCMD_LOAD:
11859 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
11860 				un->un_pos.fileno = 0;
11861 				if (un->un_pos.pmode != legacy)
11862 					un->un_pos.pmode = legacy;
11863 			} else {
11864 				un->un_state = ST_STATE_OFFLINE;
11865 				un->un_pos.pmode = invalid;
11866 
11867 			}
11868 			/*
11869 			 * If we are loading or unloading we expect the media id
11870 			 * to change. Lets make it unknown.
11871 			 */
11872 			if (un->un_media_id != bogusID && un->un_media_id_len) {
11873 				kmem_free(un->un_media_id, un->un_media_id_len);
11874 				un->un_media_id = NULL;
11875 				un->un_media_id_len = 0;
11876 			}
11877 			un->un_density_known = 0;
11878 			un->un_pos.eof = ST_NO_EOF;
11879 			un->un_pos.blkno = 0;
11880 			un->un_lastop = new_lastop = ST_OP_CTL;
11881 			break;
11882 		case SCMD_ERASE:
11883 			un->un_pos.eof = ST_NO_EOF;
11884 			un->un_pos.blkno = 0;
11885 			un->un_pos.fileno = 0;
11886 			un->un_pos.lgclblkno = 0;
11887 			if (un->un_pos.pmode != legacy)
11888 				un->un_pos.pmode = legacy;
11889 			new_lastop = ST_OP_CTL;
11890 			break;
11891 		case SCMD_RESERVE:
11892 			un->un_rsvd_status |= ST_RESERVE;
11893 			un->un_rsvd_status &=
11894 			    ~(ST_RELEASE | ST_LOST_RESERVE |
11895 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11896 			new_lastop = ST_OP_CTL;
11897 			break;
11898 		case SCMD_RELEASE:
11899 			un->un_rsvd_status |= ST_RELEASE;
11900 			un->un_rsvd_status &=
11901 			    ~(ST_RESERVE | ST_LOST_RESERVE |
11902 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11903 			new_lastop = ST_OP_CTL;
11904 			break;
11905 		case SCMD_PERSISTENT_RESERVE_IN:
11906 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11907 			    "PGR_IN command\n");
11908 			new_lastop = ST_OP_CTL;
11909 			break;
11910 		case SCMD_PERSISTENT_RESERVE_OUT:
11911 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
11912 			case ST_SA_SCSI3_RESERVE:
11913 			case ST_SA_SCSI3_PREEMPT:
11914 			case ST_SA_SCSI3_PREEMPTANDABORT:
11915 				un->un_rsvd_status |=
11916 				    (ST_APPLICATION_RESERVATIONS | ST_RESERVE);
11917 				un->un_rsvd_status &= ~(ST_RELEASE |
11918 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11919 				    ST_INITIATED_RESET);
11920 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11921 				    "PGR Reserve and set: entering"
11922 				    " ST_APPLICATION_RESERVATIONS mode");
11923 				break;
11924 			case ST_SA_SCSI3_REGISTER:
11925 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11926 				    "PGR Reserve register key");
11927 				un->un_rsvd_status |= ST_INIT_RESERVE;
11928 				break;
11929 			case ST_SA_SCSI3_CLEAR:
11930 				un->un_rsvd_status &= ~ST_INIT_RESERVE;
11931 				/* FALLTHROUGH */
11932 			case ST_SA_SCSI3_RELEASE:
11933 				un->un_rsvd_status &=
11934 				    ~(ST_APPLICATION_RESERVATIONS | ST_RESERVE |
11935 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11936 				    ST_INITIATED_RESET);
11937 				un->un_rsvd_status |= ST_RELEASE;
11938 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11939 				    "PGR Release and reset: exiting"
11940 				    " ST_APPLICATION_RESERVATIONS mode");
11941 				break;
11942 			}
11943 			new_lastop = ST_OP_CTL;
11944 			break;
11945 		case SCMD_TEST_UNIT_READY:
11946 		case SCMD_READ_BLKLIM:
11947 		case SCMD_REQUEST_SENSE:
11948 		case SCMD_INQUIRY:
11949 		case SCMD_RECOVER_BUF:
11950 		case SCMD_MODE_SELECT:
11951 		case SCMD_MODE_SENSE:
11952 		case SCMD_DOORLOCK:
11953 		case SCMD_READ_BUFFER:
11954 		case SCMD_REPORT_DENSITIES:
11955 		case SCMD_LOG_SELECT_G1:
11956 		case SCMD_LOG_SENSE_G1:
11957 		case SCMD_REPORT_LUNS:
11958 		case SCMD_READ_ATTRIBUTE:
11959 		case SCMD_WRITE_ATTRIBUTE:
11960 		case SCMD_SVC_ACTION_IN_G5:
11961 			new_lastop = ST_OP_CTL;
11962 			break;
11963 		case SCMD_READ_POSITION:
11964 			new_lastop = ST_OP_CTL;
11965 			/*
11966 			 * Only if the buf used was un_sbufp.
11967 			 * Among other things the prevents read positions used
11968 			 * as part of error recovery from messing up our
11969 			 * current position as they will use un_recov_buf.
11970 			 */
11971 			if (USCSI_CMD(bp)) {
11972 				(void) st_get_read_pos(un, bp);
11973 			}
11974 			break;
11975 		case SCMD_LOCATE:
11976 		case SCMD_LOCATE_G4:
11977 			/* Locate makes position mode no longer legacy */
11978 			un->un_lastop = new_lastop = ST_OP_CTL;
11979 			break;
11980 		case SCMD_MAINTENANCE_IN:
11981 			switch (sp->pkt_cdbp[1]) {
11982 			case SSVC_ACTION_GET_SUPPORTED_OPERATIONS:
11983 			case SSVC_ACTION_SET_TARGET_PORT_GROUPS:
11984 				new_lastop = ST_OP_CTL;
11985 				break;
11986 			}
11987 			if (new_lastop != ST_OP_NIL) {
11988 				break;
11989 			}
11990 		default:
11991 			/*
11992 			 * Unknown command, If was USCSI and USCSI_SILENT
11993 			 * flag was not set, set position to unknown.
11994 			 */
11995 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
11996 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
11997 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11998 				    "unknown cmd 0x%X caused loss of state\n",
11999 				    cmd);
12000 			} else {
12001 				/*
12002 				 * keep the old agreement to allow unknown
12003 				 * commands with the USCSI_SILENT set.
12004 				 * This prevents ASSERT below.
12005 				 */
12006 				new_lastop = ST_OP_CTL;
12007 				break;
12008 			}
12009 			/* FALLTHROUGH */
12010 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
12011 			un->un_pos.pmode = invalid;
12012 			un->un_lastop = new_lastop = ST_OP_CTL;
12013 			break;
12014 		}
12015 
12016 		/* new_lastop should have been changed */
12017 		ASSERT(new_lastop != ST_OP_NIL);
12018 
12019 		/* If un_lastop should copy new_lastop  */
12020 		if (((un->un_lastop == ST_OP_WRITE) ||
12021 		    (un->un_lastop == ST_OP_WEOF)) &&
12022 		    new_lastop != ST_OP_CTL) {
12023 			un->un_lastop = new_lastop;
12024 		}
12025 	}
12026 
12027 	/*
12028 	 * In the st driver we have a logical and physical file position.
12029 	 * Under BSD behavior, when you get a zero read, the logical position
12030 	 * is before the filemark but after the last record of the file.
12031 	 * The physical position is after the filemark. MTIOCGET should always
12032 	 * return the logical file position.
12033 	 *
12034 	 * The next read gives a silent skip to the next file.
12035 	 * Under SVR4, the logical file position remains before the filemark
12036 	 * until the file is closed or a space operation is performed.
12037 	 * Hence set err_resid and err_file before changing fileno if case
12038 	 * BSD Behaviour.
12039 	 */
12040 	un->un_err_resid = bp->b_resid;
12041 	COPY_POS(&un->un_err_pos, &un->un_pos);
12042 
12043 
12044 	/*
12045 	 * If we've seen a filemark via the last read operation
12046 	 * advance the file counter, but mark things such that
12047 	 * the next read operation gets a zero count. We have
12048 	 * to put this here to handle the case of sitting right
12049 	 * at the end of a tape file having seen the file mark,
12050 	 * but the tape is closed and then re-opened without
12051 	 * any further i/o. That is, the position information
12052 	 * must be updated before a close.
12053 	 */
12054 
12055 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
12056 		/*
12057 		 * If we're a 1/2" tape, and we get a filemark
12058 		 * right on block 0, *AND* we were not in the
12059 		 * first file on the tape, and we've hit logical EOM.
12060 		 * We'll mark the state so that later we do the
12061 		 * right thing (in st_close(), st_strategy() or
12062 		 * st_ioctl()).
12063 		 *
12064 		 */
12065 		if ((un->un_dp->options & ST_REEL) &&
12066 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
12067 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
12068 			un->un_pos.eof = ST_EOT_PENDING;
12069 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12070 			    "eot pending\n");
12071 			un->un_pos.fileno++;
12072 			un->un_pos.blkno = 0;
12073 		} else if (BSD_BEHAVIOR) {
12074 			/*
12075 			 * If the read of the filemark was a side effect
12076 			 * of reading some blocks (i.e., data was actually
12077 			 * read), then the EOF mark is pending and the
12078 			 * bump into the next file awaits the next read
12079 			 * operation (which will return a zero count), or
12080 			 * a close or a space operation, else the bump
12081 			 * into the next file occurs now.
12082 			 */
12083 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12084 			    "resid=%lx, bcount=%lx\n",
12085 			    bp->b_resid, bp->b_bcount);
12086 
12087 			if (bp->b_resid != bp->b_bcount) {
12088 				un->un_pos.eof = ST_EOF;
12089 			} else {
12090 				un->un_silent_skip = 1;
12091 				un->un_pos.eof = ST_NO_EOF;
12092 				un->un_pos.fileno++;
12093 				un->un_pos.lgclblkno++;
12094 				un->un_save_blkno = un->un_pos.blkno;
12095 				un->un_pos.blkno = 0;
12096 			}
12097 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12098 			    "eof of file %d, eof=%d\n",
12099 			    un->un_pos.fileno, un->un_pos.eof);
12100 		} else if (SVR4_BEHAVIOR) {
12101 			/*
12102 			 * If the read of the filemark was a side effect
12103 			 * of reading some blocks (i.e., data was actually
12104 			 * read), then the next read should return 0
12105 			 */
12106 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12107 			    "resid=%lx, bcount=%lx\n",
12108 			    bp->b_resid, bp->b_bcount);
12109 			if (bp->b_resid == bp->b_bcount) {
12110 				un->un_pos.eof = ST_EOF;
12111 			}
12112 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12113 			    "eof of file=%d, eof=%d\n",
12114 			    un->un_pos.fileno, un->un_pos.eof);
12115 		}
12116 	}
12117 }
12118 
12119 /*
12120  * set the correct un_errno, to take corner cases into consideration
12121  */
12122 static void
12123 st_set_pe_errno(struct scsi_tape *un)
12124 {
12125 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
12126 
12127 	ASSERT(mutex_owned(ST_MUTEX));
12128 
12129 	/* if errno is already set, don't reset it */
12130 	if (un->un_errno)
12131 		return;
12132 
12133 	/* here un_errno == 0 */
12134 	/*
12135 	 * if the last transfer before flushing all the
12136 	 * waiting I/O's, was 0 (resid = count), then we
12137 	 * want to give the user an error on all the rest,
12138 	 * so here.  If there was a transfer, we set the
12139 	 * resid and counts to 0, and let it drop through,
12140 	 * giving a zero return.  the next I/O will then
12141 	 * give an error.
12142 	 */
12143 	if (un->un_last_resid == un->un_last_count) {
12144 		switch (un->un_pos.eof) {
12145 		case ST_EOM:
12146 			un->un_errno = ENOMEM;
12147 			break;
12148 		case ST_EOT:
12149 		case ST_EOF:
12150 			un->un_errno = EIO;
12151 			break;
12152 		}
12153 	} else {
12154 		/*
12155 		 * we know they did not have a zero, so make
12156 		 * sure they get one
12157 		 */
12158 		un->un_last_resid = un->un_last_count = 0;
12159 	}
12160 }
12161 
12162 
12163 /*
12164  * send in a marker pkt to terminate flushing of commands by BBA (via
12165  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
12166  */
12167 static void
12168 st_hba_unflush(struct scsi_tape *un)
12169 {
12170 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
12171 
12172 	ASSERT(mutex_owned(ST_MUTEX));
12173 
12174 	if (!un->un_flush_on_errors)
12175 		return;
12176 
12177 #ifdef FLUSH_ON_ERRORS
12178 
12179 	if (!un->un_mkr_pkt) {
12180 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
12181 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
12182 
12183 		/* we slept, so it must be there */
12184 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
12185 	}
12186 
12187 	st_transport(un, un->un_mkr_pkt);
12188 #endif
12189 }
12190 
12191 static char *
12192 st_print_scsi_cmd(char cmd)
12193 {
12194 	char tmp[64];
12195 	char *cpnt;
12196 
12197 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
12198 	/* tmp goes out of scope on return and caller sees garbage */
12199 	if (cpnt == tmp) {
12200 		cpnt = "Unknown Command";
12201 	}
12202 	return (cpnt);
12203 }
12204 
12205 static void
12206 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
12207     char *title, char *cdb)
12208 {
12209 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
12210 	char buf[256];
12211 	struct scsi_tape *un;
12212 	int instance = ddi_get_instance(dip);
12213 
12214 	un = ddi_get_soft_state(st_state, instance);
12215 
12216 	ST_FUNC(dip, st_print_cdb);
12217 
12218 	/* force one line output so repeated commands are printed once */
12219 	if ((st_debug & 0x180) == 0x100) {
12220 		scsi_log(dip, label, level, "node %s cmd %s\n",
12221 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
12222 		return;
12223 	}
12224 
12225 	/* force one line output so repeated CDB's are printed once */
12226 	if ((st_debug & 0x180) == 0x80) {
12227 		st_clean_print(dip, label, level, NULL, cdb, len);
12228 	} else {
12229 		(void) sprintf(buf, "%s for cmd(%s)", title,
12230 		    st_print_scsi_cmd(*cdb));
12231 		st_clean_print(dip, label, level, buf, cdb, len);
12232 	}
12233 }
12234 
12235 static void
12236 st_clean_print(dev_info_t *dev, char *label, uint_t level,
12237     char *title, char *data, int len)
12238 {
12239 	int	i;
12240 	int 	c;
12241 	char	*format;
12242 	char	buf[256];
12243 	uchar_t	byte;
12244 
12245 	ST_FUNC(dev, st_clean_print);
12246 
12247 
12248 	if (title) {
12249 		(void) sprintf(buf, "%s:\n", title);
12250 		scsi_log(dev, label, level, "%s", buf);
12251 		level = CE_CONT;
12252 	}
12253 
12254 	for (i = 0; i < len; ) {
12255 		buf[0] = 0;
12256 		for (c = 0; c < 8 && i < len; c++, i++) {
12257 			byte = (uchar_t)data[i];
12258 			if (byte < 0x10)
12259 				format = "0x0%x ";
12260 			else
12261 				format = "0x%x ";
12262 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
12263 		}
12264 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
12265 
12266 		scsi_log(dev, label, level, "%s\n", buf);
12267 		level = CE_CONT;
12268 	}
12269 }
12270 
12271 /*
12272  * Conditionally enabled debugging
12273  */
12274 #ifdef	STDEBUG
12275 static void
12276 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
12277 {
12278 	char tmpbuf[64];
12279 
12280 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
12281 
12282 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12283 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
12284 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
12285 	    count, count,
12286 	    wait == ASYNC_CMD ? "a" : "");
12287 }
12288 #endif	/* STDEBUG */
12289 
12290 /*
12291  * Returns pointer to name of minor node name of device 'dev'.
12292  */
12293 static char *
12294 st_dev_name(dev_t dev)
12295 {
12296 	struct scsi_tape *un;
12297 	const char density[] = { 'l', 'm', 'h', 'c' };
12298 	static char name[32];
12299 	minor_t minor;
12300 	int instance;
12301 	int nprt = 0;
12302 
12303 	minor = getminor(dev);
12304 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
12305 	un = ddi_get_soft_state(st_state, instance);
12306 	if (un) {
12307 		ST_FUNC(ST_DEVINFO, st_dev_name);
12308 	}
12309 
12310 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
12311 
12312 	if (minor & MT_BSD) {
12313 		name[++nprt] = 'b';
12314 	}
12315 
12316 	if (minor & MT_NOREWIND) {
12317 		name[++nprt] = 'n';
12318 	}
12319 
12320 	/* NULL terminator */
12321 	name[++nprt] = 0;
12322 
12323 	return (name);
12324 }
12325 
12326 /*
12327  * Soft error reporting, so far unique to each drive
12328  *
12329  * Currently supported: exabyte and DAT soft error reporting
12330  */
12331 static int
12332 st_report_exabyte_soft_errors(dev_t dev, int flag)
12333 {
12334 	uchar_t *sensep;
12335 	int amt;
12336 	int rval = 0;
12337 	char cdb[CDB_GROUP0], *c = cdb;
12338 	struct uscsi_cmd *com;
12339 
12340 	GET_SOFT_STATE(dev);
12341 
12342 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
12343 
12344 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12345 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
12346 	    dev, flag);
12347 
12348 	ASSERT(mutex_owned(ST_MUTEX));
12349 
12350 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12351 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
12352 
12353 	*c++ = SCMD_REQUEST_SENSE;
12354 	*c++ = 0;
12355 	*c++ = 0;
12356 	*c++ = 0;
12357 	*c++ = TAPE_SENSE_LENGTH;
12358 	/*
12359 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
12360 	 */
12361 	*c   = (char)0x80;
12362 
12363 	com->uscsi_cdb = cdb;
12364 	com->uscsi_cdblen = CDB_GROUP0;
12365 	com->uscsi_bufaddr = (caddr_t)sensep;
12366 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
12367 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12368 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12369 
12370 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12371 	if (rval || com->uscsi_status) {
12372 		goto done;
12373 	}
12374 
12375 	/*
12376 	 * was there enough data?
12377 	 */
12378 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
12379 
12380 	if ((amt >= 19) && un->un_kbytes_xferred) {
12381 		uint_t count, error_rate;
12382 		uint_t rate;
12383 
12384 		if (sensep[21] & CLN) {
12385 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12386 			    "Periodic head cleaning required");
12387 		}
12388 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
12389 			goto done;
12390 		}
12391 		/*
12392 		 * check if soft error reporting needs to be done.
12393 		 */
12394 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
12395 		count &= 0xffffff;
12396 		error_rate = (count * 100)/un->un_kbytes_xferred;
12397 
12398 #ifdef	STDEBUG
12399 		if (st_soft_error_report_debug) {
12400 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12401 			    "Exabyte Soft Error Report:\n");
12402 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12403 			    "read/write error counter: %d\n", count);
12404 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12405 			    "number of bytes transferred: %dK\n",
12406 			    un->un_kbytes_xferred);
12407 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12408 			    "error_rate: %d%%\n", error_rate);
12409 
12410 			if (amt >= 22) {
12411 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12412 				    "unit sense: 0x%b 0x%b 0x%b\n",
12413 				    sensep[19], SENSE_19_BITS,
12414 				    sensep[20], SENSE_20_BITS,
12415 				    sensep[21], SENSE_21_BITS);
12416 			}
12417 			if (amt >= 27) {
12418 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12419 				    "tracking retry counter: %d\n",
12420 				    sensep[26]);
12421 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12422 				    "read/write retry counter: %d\n",
12423 				    sensep[27]);
12424 			}
12425 		}
12426 #endif
12427 
12428 		if (flag & FWRITE) {
12429 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
12430 		} else {
12431 			rate = EXABYTE_READ_ERROR_THRESHOLD;
12432 		}
12433 		if (error_rate >= rate) {
12434 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12435 			    "Soft error rate (%d%%) during %s was too high",
12436 			    error_rate,
12437 			    ((flag & FWRITE) ? wrg_str : rdg_str));
12438 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12439 			    "Please, replace tape cartridge\n");
12440 		}
12441 	}
12442 
12443 done:
12444 	kmem_free(com, sizeof (*com));
12445 	kmem_free(sensep, TAPE_SENSE_LENGTH);
12446 
12447 	if (rval != 0) {
12448 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12449 		    "exabyte soft error reporting failed\n");
12450 	}
12451 	return (rval);
12452 }
12453 
12454 /*
12455  * this is very specific to Archive 4mm dat
12456  */
12457 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
12458 
12459 static int
12460 st_report_dat_soft_errors(dev_t dev, int flag)
12461 {
12462 	uchar_t *sensep;
12463 	int amt, i;
12464 	int rval = 0;
12465 	char cdb[CDB_GROUP1], *c = cdb;
12466 	struct uscsi_cmd *com;
12467 	struct scsi_arq_status status;
12468 
12469 	GET_SOFT_STATE(dev);
12470 
12471 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
12472 
12473 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12474 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12475 
12476 	ASSERT(mutex_owned(ST_MUTEX));
12477 
12478 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12479 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12480 
12481 	*c++ = SCMD_LOG_SENSE_G1;
12482 	*c++ = 0;
12483 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
12484 	*c++ = 0;
12485 	*c++ = 0;
12486 	*c++ = 0;
12487 	*c++ = 2;
12488 	*c++ = 0;
12489 	*c++ = (char)LOG_SENSE_LENGTH;
12490 	*c   = 0;
12491 	com->uscsi_cdb    = cdb;
12492 	com->uscsi_cdblen  = CDB_GROUP1;
12493 	com->uscsi_bufaddr = (caddr_t)sensep;
12494 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
12495 	com->uscsi_rqlen = sizeof (status);
12496 	com->uscsi_rqbuf = (caddr_t)&status;
12497 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
12498 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12499 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12500 	if (rval) {
12501 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12502 		    "DAT soft error reporting failed\n");
12503 	}
12504 	if (rval || com->uscsi_status) {
12505 		goto done;
12506 	}
12507 
12508 	/*
12509 	 * was there enough data?
12510 	 */
12511 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
12512 
12513 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
12514 		int total, retries, param_code;
12515 
12516 		total = -1;
12517 		retries = -1;
12518 		amt = sensep[3] + 4;
12519 
12520 
12521 #ifdef STDEBUG
12522 		if (st_soft_error_report_debug) {
12523 			(void) printf("logsense:");
12524 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
12525 				if (i % 16 == 0) {
12526 					(void) printf("\t\n");
12527 				}
12528 				(void) printf(" %x", sensep[i]);
12529 			}
12530 			(void) printf("\n");
12531 		}
12532 #endif
12533 
12534 		/*
12535 		 * parse the param_codes
12536 		 */
12537 		if (sensep[0] == 2 || sensep[0] == 3) {
12538 			for (i = 4; i < amt; i++) {
12539 				param_code = (sensep[i++] << 8);
12540 				param_code += sensep[i++];
12541 				i++; /* skip control byte */
12542 				if (param_code == 5) {
12543 					if (sensep[i++] == 4) {
12544 						total = (sensep[i++] << 24);
12545 						total += (sensep[i++] << 16);
12546 						total += (sensep[i++] << 8);
12547 						total += sensep[i];
12548 					}
12549 				} else if (param_code == 0x8007) {
12550 					if (sensep[i++] == 2) {
12551 						retries = sensep[i++] << 8;
12552 						retries += sensep[i];
12553 					}
12554 				} else {
12555 					i += sensep[i];
12556 				}
12557 			}
12558 		}
12559 
12560 		/*
12561 		 * if the log sense returned valid numbers then determine
12562 		 * the read and write error thresholds based on the amount of
12563 		 * data transferred
12564 		 */
12565 
12566 		if (total > 0 && retries > 0) {
12567 			short normal_retries = 0;
12568 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12569 			    "total xferred (%s) =%x, retries=%x\n",
12570 			    ((flag & FWRITE) ? wrg_str : rdg_str),
12571 			    total, retries);
12572 
12573 			if (flag & FWRITE) {
12574 				if (total <=
12575 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
12576 					normal_retries =
12577 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
12578 				} else {
12579 					normal_retries =
12580 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
12581 				}
12582 			} else {
12583 				if (total <=
12584 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
12585 					normal_retries =
12586 					    DAT_SMALL_READ_ERROR_THRESHOLD;
12587 				} else {
12588 					normal_retries =
12589 					    DAT_LARGE_READ_ERROR_THRESHOLD;
12590 				}
12591 			}
12592 
12593 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12594 			"normal retries=%d\n", normal_retries);
12595 
12596 			if (retries >= normal_retries) {
12597 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12598 				    "Soft error rate (retries = %d) during "
12599 				    "%s was too high",  retries,
12600 				    ((flag & FWRITE) ? wrg_str : rdg_str));
12601 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12602 				    "Periodic head cleaning required "
12603 				    "and/or replace tape cartridge\n");
12604 			}
12605 
12606 		} else if (total == -1 || retries == -1) {
12607 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12608 			    "log sense parameter code does not make sense\n");
12609 		}
12610 	}
12611 
12612 	/*
12613 	 * reset all values
12614 	 */
12615 	c = cdb;
12616 	*c++ = SCMD_LOG_SELECT_G1;
12617 	*c++ = 2;	/* this resets all values */
12618 	*c++ = (char)0xc0;
12619 	*c++ = 0;
12620 	*c++ = 0;
12621 	*c++ = 0;
12622 	*c++ = 0;
12623 	*c++ = 0;
12624 	*c++ = 0;
12625 	*c   = 0;
12626 	com->uscsi_bufaddr = NULL;
12627 	com->uscsi_buflen  = 0;
12628 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
12629 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12630 	if (rval) {
12631 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12632 		    "DAT soft error reset failed\n");
12633 	}
12634 done:
12635 	kmem_free(com, sizeof (*com));
12636 	kmem_free(sensep, LOG_SENSE_LENGTH);
12637 	return (rval);
12638 }
12639 
12640 static int
12641 st_report_soft_errors(dev_t dev, int flag)
12642 {
12643 	GET_SOFT_STATE(dev);
12644 
12645 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
12646 
12647 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12648 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12649 
12650 	ASSERT(mutex_owned(ST_MUTEX));
12651 
12652 	switch (un->un_dp->type) {
12653 	case ST_TYPE_EXB8500:
12654 	case ST_TYPE_EXABYTE:
12655 		return (st_report_exabyte_soft_errors(dev, flag));
12656 		/*NOTREACHED*/
12657 	case ST_TYPE_PYTHON:
12658 		return (st_report_dat_soft_errors(dev, flag));
12659 		/*NOTREACHED*/
12660 	default:
12661 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
12662 		return (-1);
12663 	}
12664 }
12665 
12666 /*
12667  * persistent error routines
12668  */
12669 
12670 /*
12671  * enable persistent errors, and set the throttle appropriately, checking
12672  * for flush-on-errors capability
12673  */
12674 static void
12675 st_turn_pe_on(struct scsi_tape *un)
12676 {
12677 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
12678 
12679 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
12680 	ASSERT(mutex_owned(ST_MUTEX));
12681 
12682 	un->un_persistence = 1;
12683 
12684 	/*
12685 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
12686 	 * enabled.  This will simplify the error handling for request senses
12687 	 */
12688 
12689 	if (un->un_arq_enabled && un->un_untagged_qing) {
12690 		uchar_t f_o_e;
12691 
12692 		mutex_exit(ST_MUTEX);
12693 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
12694 		    1 : 0;
12695 		mutex_enter(ST_MUTEX);
12696 
12697 		un->un_flush_on_errors = f_o_e;
12698 	} else {
12699 		un->un_flush_on_errors = 0;
12700 	}
12701 
12702 	if (un->un_flush_on_errors)
12703 		un->un_max_throttle = (uchar_t)st_max_throttle;
12704 	else
12705 		un->un_max_throttle = 1;
12706 
12707 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
12708 		un->un_max_throttle = 1;
12709 
12710 	/* this will send a marker pkt */
12711 	st_clear_pe(un);
12712 }
12713 
12714 /*
12715  * This turns persistent errors permanently off
12716  */
12717 static void
12718 st_turn_pe_off(struct scsi_tape *un)
12719 {
12720 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
12721 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
12722 	ASSERT(mutex_owned(ST_MUTEX));
12723 
12724 	/* turn it off for good */
12725 	un->un_persistence = 0;
12726 
12727 	/* this will send a marker pkt */
12728 	st_clear_pe(un);
12729 
12730 	/* turn off flush on error capability, if enabled */
12731 	if (un->un_flush_on_errors) {
12732 		mutex_exit(ST_MUTEX);
12733 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
12734 		mutex_enter(ST_MUTEX);
12735 	}
12736 
12737 
12738 	un->un_flush_on_errors = 0;
12739 }
12740 
12741 /*
12742  * This clear persistent errors, allowing more commands through, and also
12743  * sending a marker packet.
12744  */
12745 static void
12746 st_clear_pe(struct scsi_tape *un)
12747 {
12748 	ST_FUNC(ST_DEVINFO, st_clear_pe);
12749 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
12750 	ASSERT(mutex_owned(ST_MUTEX));
12751 
12752 	un->un_persist_errors = 0;
12753 	un->un_throttle = un->un_last_throttle = 1;
12754 	un->un_errno = 0;
12755 	st_hba_unflush(un);
12756 }
12757 
12758 /*
12759  * This will flag persistent errors, shutting everything down, if the
12760  * application had enabled persistent errors via MTIOCPERSISTENT
12761  */
12762 static void
12763 st_set_pe_flag(struct scsi_tape *un)
12764 {
12765 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
12766 	ASSERT(mutex_owned(ST_MUTEX));
12767 
12768 	if (un->un_persistence) {
12769 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
12770 		un->un_persist_errors = 1;
12771 		un->un_throttle = un->un_last_throttle = 0;
12772 		cv_broadcast(&un->un_sbuf_cv);
12773 	}
12774 }
12775 
12776 static int
12777 st_do_reserve(struct scsi_tape *un)
12778 {
12779 	int rval;
12780 	int was_lost = un->un_rsvd_status & ST_LOST_RESERVE;
12781 
12782 	ST_FUNC(ST_DEVINFO, st_do_reserve);
12783 
12784 	/*
12785 	 * Issue a Throw-Away reserve command to clear the
12786 	 * check condition.
12787 	 * If the current behaviour of reserve/release is to
12788 	 * hold reservation across opens , and if a Bus reset
12789 	 * has been issued between opens then this command
12790 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
12791 	 * In this case return an EACCES so that user knows that
12792 	 * reservation has been lost in between opens.
12793 	 * If this error is not returned and we continue with
12794 	 * successful open , then user may think position of the
12795 	 * tape is still the same but inreality we would rewind the
12796 	 * tape and continue from BOT.
12797 	 */
12798 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12799 	if (rval) {
12800 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
12801 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
12802 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
12803 			un->un_errno = EACCES;
12804 			return (EACCES);
12805 		}
12806 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12807 	}
12808 	if (rval == 0) {
12809 		un->un_rsvd_status |= ST_INIT_RESERVE;
12810 	}
12811 	if (was_lost) {
12812 		un->un_running.pmode = invalid;
12813 	}
12814 
12815 	return (rval);
12816 }
12817 
12818 static int
12819 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb)
12820 {
12821 	int rval;
12822 	cmd_attribute const *attrib;
12823 
12824 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
12825 
12826 	/*
12827 	 * If already reserved no need to do it again.
12828 	 * Also if Reserve and Release are disabled Just return.
12829 	 */
12830 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12831 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12832 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12833 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12834 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
12835 		    st_print_scsi_cmd((uchar_t)cdb[0]));
12836 		return (0);
12837 	}
12838 
12839 	/* See if command is on the list */
12840 	attrib = st_lookup_cmd_attribute(cdb[0]);
12841 
12842 	if (attrib == NULL) {
12843 		rval = 1; /* Not found, when in doubt reserve */
12844 	} else if ((attrib->requires_reserve) != 0) {
12845 		rval = 1;
12846 	} else if ((attrib->reserve_byte) != 0) {
12847 		/*
12848 		 * cmd is on list.
12849 		 * if byte is zero always allowed.
12850 		 */
12851 		rval = 1;
12852 	} else if (((cdb[attrib->reserve_byte]) &
12853 	    (attrib->reserve_mask)) != 0) {
12854 		rval = 1;
12855 	} else {
12856 		rval = 0;
12857 	}
12858 
12859 	if (rval) {
12860 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12861 		    "Command %s requires reservation",
12862 		    st_print_scsi_cmd(cdb[0]));
12863 
12864 		rval = st_do_reserve(un);
12865 	}
12866 
12867 	return (rval);
12868 }
12869 
12870 static int
12871 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
12872 {
12873 	int rval;
12874 	cmd_attribute const *attrib;
12875 
12876 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
12877 
12878 	/*
12879 	 * Do not reserve when already reserved, when not supported or when
12880 	 * auto-rewinding on device closure.
12881 	 */
12882 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12883 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12884 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE) ||
12885 	    ((un->un_state == ST_STATE_CLOSING) && (cmd == SCMD_REWIND))) {
12886 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12887 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
12888 		    st_print_scsi_cmd(cmd));
12889 		return (0);
12890 	}
12891 
12892 	/* search for this command on the list */
12893 	attrib = st_lookup_cmd_attribute(cmd);
12894 
12895 	if (attrib == NULL) {
12896 		rval = 1; /* Not found, when in doubt reserve */
12897 	} else if ((attrib->requires_reserve) != 0) {
12898 		rval = 1;
12899 	} else if ((attrib->reserve_byte) != 0) {
12900 		/*
12901 		 * cmd is on list.
12902 		 * if byte is zero always allowed.
12903 		 */
12904 		rval = 1;
12905 	} else if (((attrib->reserve_mask) & cnt) != 0) {
12906 		rval = 1;
12907 	} else {
12908 		rval = 0;
12909 	}
12910 
12911 	if (rval) {
12912 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12913 		    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
12914 
12915 		rval = st_do_reserve(un);
12916 	}
12917 
12918 	return (rval);
12919 }
12920 
12921 static int
12922 st_reserve_release(struct scsi_tape *un, int cmd, ubufunc_t ubf)
12923 {
12924 	struct uscsi_cmd	uscsi_cmd;
12925 	int			rval;
12926 	char			cdb[CDB_GROUP0];
12927 	struct scsi_arq_status	stat;
12928 
12929 
12930 
12931 	ST_FUNC(ST_DEVINFO, st_reserve_release);
12932 
12933 	ASSERT(mutex_owned(ST_MUTEX));
12934 
12935 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12936 	    "st_reserve_release: %s \n",
12937 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
12938 
12939 	bzero(&cdb, CDB_GROUP0);
12940 	if (cmd == ST_RELEASE) {
12941 		cdb[0] = SCMD_RELEASE;
12942 	} else {
12943 		cdb[0] = SCMD_RESERVE;
12944 	}
12945 	bzero(&uscsi_cmd, sizeof (struct uscsi_cmd));
12946 	uscsi_cmd.uscsi_flags = USCSI_WRITE | USCSI_RQENABLE;
12947 	uscsi_cmd.uscsi_cdb = cdb;
12948 	uscsi_cmd.uscsi_cdblen = CDB_GROUP0;
12949 	uscsi_cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
12950 	uscsi_cmd.uscsi_rqbuf = (caddr_t)&stat;
12951 	uscsi_cmd.uscsi_rqlen = sizeof (stat);
12952 
12953 	rval = ubf(un, &uscsi_cmd, FKIOCTL);
12954 
12955 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12956 	    "st_reserve_release: rval(1)=%d\n", rval);
12957 
12958 	if (rval) {
12959 		if (uscsi_cmd.uscsi_status == STATUS_RESERVATION_CONFLICT) {
12960 			rval = EACCES;
12961 		}
12962 		/*
12963 		 * dynamically turn off reserve/release support
12964 		 * in case of drives which do not support
12965 		 * reserve/release command(ATAPI drives).
12966 		 */
12967 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
12968 			if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
12969 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
12970 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12971 				    "Tape unit does not support "
12972 				    "reserve/release \n");
12973 			}
12974 			rval = 0;
12975 		}
12976 	}
12977 	return (rval);
12978 }
12979 
12980 static int
12981 st_take_ownership(struct scsi_tape *un, ubufunc_t ubf)
12982 {
12983 	int rval;
12984 
12985 	ST_FUNC(ST_DEVINFO, st_take_ownership);
12986 
12987 	ASSERT(mutex_owned(ST_MUTEX));
12988 
12989 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12990 	    "st_take_ownership: Entering ...\n");
12991 
12992 
12993 	rval = st_reserve_release(un, ST_RESERVE, ubf);
12994 	/*
12995 	 * XXX -> Should reset be done only if we get EACCES.
12996 	 * .
12997 	 */
12998 	if (rval) {
12999 		if (st_reset(un, RESET_LUN) == 0) {
13000 			return (EIO);
13001 		}
13002 		un->un_rsvd_status &=
13003 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
13004 
13005 		mutex_exit(ST_MUTEX);
13006 		delay(drv_usectohz(ST_RESERVATION_DELAY));
13007 		mutex_enter(ST_MUTEX);
13008 		/*
13009 		 * remove the check condition.
13010 		 */
13011 		(void) st_reserve_release(un, ST_RESERVE, ubf);
13012 		rval = st_reserve_release(un, ST_RESERVE, ubf);
13013 		if (rval != 0) {
13014 			if ((st_reserve_release(un, ST_RESERVE, ubf))
13015 			    != 0) {
13016 				rval = (un->un_rsvd_status &
13017 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
13018 				return (rval);
13019 			}
13020 		}
13021 		/*
13022 		 * Set tape state to ST_STATE_OFFLINE , in case if
13023 		 * the user wants to continue and start using
13024 		 * the tape.
13025 		 */
13026 		un->un_state = ST_STATE_OFFLINE;
13027 		un->un_rsvd_status |= ST_INIT_RESERVE;
13028 	}
13029 	return (rval);
13030 }
13031 
13032 static int
13033 st_create_errstats(struct scsi_tape *un, int instance)
13034 {
13035 	char	kstatname[KSTAT_STRLEN];
13036 
13037 	ST_FUNC(ST_DEVINFO, st_create_errstats);
13038 
13039 	/*
13040 	 * Create device error kstats
13041 	 */
13042 
13043 	if (un->un_errstats == (kstat_t *)0) {
13044 		(void) sprintf(kstatname, "st%d,err", instance);
13045 		un->un_errstats = kstat_create("sterr", instance, kstatname,
13046 		    "device_error", KSTAT_TYPE_NAMED,
13047 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
13048 		    KSTAT_FLAG_PERSISTENT);
13049 
13050 		if (un->un_errstats) {
13051 			struct st_errstats	*stp;
13052 
13053 			stp = (struct st_errstats *)un->un_errstats->ks_data;
13054 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
13055 			    KSTAT_DATA_ULONG);
13056 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
13057 			    KSTAT_DATA_ULONG);
13058 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
13059 			    KSTAT_DATA_ULONG);
13060 			kstat_named_init(&stp->st_vid, "Vendor",
13061 			    KSTAT_DATA_CHAR);
13062 			kstat_named_init(&stp->st_pid, "Product",
13063 			    KSTAT_DATA_CHAR);
13064 			kstat_named_init(&stp->st_revision, "Revision",
13065 			    KSTAT_DATA_CHAR);
13066 			kstat_named_init(&stp->st_serial, "Serial No",
13067 			    KSTAT_DATA_CHAR);
13068 			un->un_errstats->ks_private = un;
13069 			un->un_errstats->ks_update = nulldev;
13070 			kstat_install(un->un_errstats);
13071 			/*
13072 			 * Fill in the static data
13073 			 */
13074 			(void) strncpy(&stp->st_vid.value.c[0],
13075 			    ST_INQUIRY->inq_vid, 8);
13076 			/*
13077 			 * XXX:  Emulex MT-02 (and emulators) predates
13078 			 *	 SCSI-1 and has no vid & pid inquiry data.
13079 			 */
13080 			if (ST_INQUIRY->inq_len != 0) {
13081 				(void) strncpy(&stp->st_pid.value.c[0],
13082 				    ST_INQUIRY->inq_pid, 16);
13083 				(void) strncpy(&stp->st_revision.value.c[0],
13084 				    ST_INQUIRY->inq_revision, 4);
13085 				(void) strncpy(&stp->st_serial.value.c[0],
13086 				    ST_INQUIRY->inq_serial, 12);
13087 			}
13088 		}
13089 	}
13090 	return (0);
13091 }
13092 
13093 static int
13094 st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos)
13095 {
13096 	int rval;
13097 	bufunc_t bf = (ubf == st_uscsi_rcmd) ? st_rcmd : st_cmd;
13098 
13099 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
13100 
13101 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
13102 	ASSERT(mutex_owned(ST_MUTEX));
13103 
13104 	/* Can't restore an invalid position */
13105 	if (pos->pmode == invalid) {
13106 		return (4);
13107 	}
13108 
13109 	/*
13110 	 * Assumtions:
13111 	 *	If a position was read and is in logical position mode.
13112 	 *	If a drive supports read position it supports locate.
13113 	 *	If the read position type is not NO_POS. even though
13114 	 *	   a read position make not have been attemped yet.
13115 	 *
13116 	 *	The drive can locate to the position.
13117 	 */
13118 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
13119 		/*
13120 		 * If position mode is logical or legacy mode try
13121 		 * to locate there as it is faster.
13122 		 * If it fails try the old way.
13123 		 */
13124 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13125 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
13126 		    pos->lgclblkno);
13127 
13128 		if (st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
13129 		    pos->lgclblkno, pos->partition) == 0) {
13130 			/* Assume we are there copy rest of position back */
13131 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
13132 				COPY_POS(&un->un_pos, pos);
13133 			}
13134 			return (0);
13135 		}
13136 
13137 		/*
13138 		 * If logical block locate failed to restore a logical
13139 		 * position, can't recover.
13140 		 */
13141 		if (pos->pmode == logical) {
13142 			return (-1);
13143 		}
13144 	}
13145 
13146 
13147 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13148 	    "Restoring tape position at fileno=%x, blkno=%x....",
13149 	    pos->fileno, pos->blkno);
13150 
13151 	/*
13152 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
13153 	 * so as not to rewind tape on RESETS: Gee, Has life ever
13154 	 * been simple in tape land ?
13155 	 */
13156 	rval = bf(un, SCMD_REWIND, 0, SYNC_CMD);
13157 	if (rval) {
13158 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
13159 		    "Failed to restore the last file and block position: In"
13160 		    " this state, Tape will be loaded at BOT during next open");
13161 		un->un_pos.pmode = invalid;
13162 		return (rval);
13163 	}
13164 
13165 	/* If the position was as the result of back space file */
13166 	if (pos->blkno > (INF / 2)) {
13167 		/* Go one extra file forward */
13168 		pos->fileno++;
13169 		/* Figure how many blocks to back into the previous file */
13170 		pos->blkno = -(INF - pos->blkno);
13171 	}
13172 
13173 	/* Go to requested fileno */
13174 	if (pos->fileno) {
13175 		rval = st_cmd(un, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
13176 		if (rval) {
13177 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13178 			    "Failed to restore the last file position: In this "
13179 			    " state, Tape will be loaded at BOT during next"
13180 			    " open %d", __LINE__);
13181 			un->un_pos.pmode = invalid;
13182 			pos->pmode = invalid;
13183 			return (rval);
13184 		}
13185 	}
13186 
13187 	/*
13188 	 * If backing into a file we already did an extra file forward.
13189 	 * Now we have to back over the filemark to get to the end of
13190 	 * the previous file. The blkno has been ajusted to a negative
13191 	 * value so we will get to the expected location.
13192 	 */
13193 	if (pos->blkno) {
13194 		rval = bf(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
13195 		if (rval) {
13196 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13197 			    "Failed to restore the last file position: In this "
13198 			    " state, Tape will be loaded at BOT during next"
13199 			    " open %d", __LINE__);
13200 			un->un_pos.pmode = invalid;
13201 			pos->pmode = invalid;
13202 			return (rval);
13203 		}
13204 	}
13205 
13206 	/*
13207 	 * The position mode, block and fileno should be correct,
13208 	 * This updates eof and logical position information.
13209 	 */
13210 	un->un_pos.eof = pos->eof;
13211 	un->un_pos.lgclblkno = pos->lgclblkno;
13212 
13213 	return (0);
13214 }
13215 
13216 /*
13217  * check sense key, ASC, ASCQ in order to determine if the tape needs
13218  * to be ejected
13219  */
13220 
13221 static int
13222 st_check_asc_ascq(struct scsi_tape *un)
13223 {
13224 	struct scsi_extended_sense *sensep = ST_RQSENSE;
13225 	struct tape_failure_code   *code;
13226 
13227 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
13228 
13229 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
13230 		if ((code->key  == sensep->es_key) &&
13231 		    (code->add_code  == sensep->es_add_code) &&
13232 		    (code->qual_code == sensep->es_qual_code))
13233 			return (1);
13234 	}
13235 	return (0);
13236 }
13237 
13238 /*
13239  * st_logpage_supported() sends a Log Sense command with
13240  * page code = 0 = Supported Log Pages Page to the device,
13241  * to see whether the page 'page' is supported.
13242  * Return values are:
13243  * -1 if the Log Sense command fails
13244  * 0 if page is not supported
13245  * 1 if page is supported
13246  */
13247 
13248 static int
13249 st_logpage_supported(struct scsi_tape *un, uchar_t page)
13250 {
13251 	uchar_t *sp, *sensep;
13252 	unsigned length;
13253 	struct uscsi_cmd *com;
13254 	struct scsi_arq_status status;
13255 	int rval;
13256 	char cdb[CDB_GROUP1] = {
13257 		SCMD_LOG_SENSE_G1,
13258 		0,
13259 		SUPPORTED_LOG_PAGES_PAGE,
13260 		0,
13261 		0,
13262 		0,
13263 		0,
13264 		0,
13265 		(char)LOG_SENSE_LENGTH,
13266 		0
13267 	};
13268 
13269 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
13270 
13271 	ASSERT(mutex_owned(ST_MUTEX));
13272 
13273 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13274 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
13275 
13276 	com->uscsi_cdb = cdb;
13277 	com->uscsi_cdblen = CDB_GROUP1;
13278 	com->uscsi_bufaddr = (caddr_t)sensep;
13279 	com->uscsi_buflen = LOG_SENSE_LENGTH;
13280 	com->uscsi_rqlen = sizeof (status);
13281 	com->uscsi_rqbuf = (caddr_t)&status;
13282 	com->uscsi_flags =
13283 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13284 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13285 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13286 	if (rval || com->uscsi_status) {
13287 		/* uscsi-command failed */
13288 		rval = -1;
13289 	} else {
13290 
13291 		sp = sensep + 3;
13292 
13293 		for (length = *sp++; length > 0; length--, sp++) {
13294 
13295 			if (*sp == page) {
13296 				rval = 1;
13297 				break;
13298 			}
13299 		}
13300 	}
13301 	kmem_free(com, sizeof (struct uscsi_cmd));
13302 	kmem_free(sensep, LOG_SENSE_LENGTH);
13303 	return (rval);
13304 }
13305 
13306 
13307 /*
13308  * st_check_clean_bit() gets the status of the tape's cleaning bit.
13309  *
13310  * If the device does support the TapeAlert log page, then the cleaning bit
13311  * information will be read from this page. Otherwise we will see if one of
13312  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
13313  * the device, which means, that we can get the cleaning bit information via
13314  * a RequestSense command.
13315  * If both methods of getting cleaning bit information are not supported
13316  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
13317  * returns with
13318  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
13319  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
13320  * If the call to st_uscsi_cmd() to do the Log Sense or the Request Sense
13321  * command fails, or if the amount of Request Sense data is not enough, then
13322  *  st_check_clean_bit() returns with -1.
13323  */
13324 
13325 static int
13326 st_check_clean_bit(struct scsi_tape *un)
13327 {
13328 	int rval = 0;
13329 
13330 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
13331 
13332 	ASSERT(mutex_owned(ST_MUTEX));
13333 
13334 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
13335 		return (rval);
13336 	}
13337 
13338 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13339 
13340 		rval = st_logpage_supported(un, TAPE_SEQUENTIAL_PAGE);
13341 		if (rval == -1) {
13342 			return (0);
13343 		}
13344 		if (rval == 1) {
13345 
13346 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
13347 		}
13348 
13349 		rval = st_logpage_supported(un, TAPE_ALERT_PAGE);
13350 		if (rval == -1) {
13351 			return (0);
13352 		}
13353 		if (rval == 1) {
13354 
13355 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
13356 		}
13357 
13358 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13359 
13360 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
13361 		}
13362 	}
13363 
13364 	rval = 0;
13365 
13366 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
13367 
13368 		rval = st_check_sequential_clean_bit(un);
13369 		if (rval == -1) {
13370 			return (0);
13371 		}
13372 	}
13373 
13374 	if ((rval == 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
13375 
13376 		rval = st_check_alert_flags(un);
13377 		if (rval == -1) {
13378 			return (0);
13379 		}
13380 	}
13381 
13382 	if ((rval == 0) && (un->un_dp->options & ST_CLN_MASK)) {
13383 
13384 		rval = st_check_sense_clean_bit(un);
13385 		if (rval == -1) {
13386 			return (0);
13387 		}
13388 	}
13389 
13390 	/*
13391 	 * If found a supported means to check need to clean.
13392 	 */
13393 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
13394 
13395 		/*
13396 		 * head needs to be cleaned.
13397 		 */
13398 		if (rval & MTF_TAPE_HEAD_DIRTY) {
13399 
13400 			/*
13401 			 * Print log message only first time
13402 			 * found needing cleaned.
13403 			 */
13404 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
13405 
13406 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
13407 				    "Periodic head cleaning required");
13408 
13409 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
13410 			}
13411 
13412 		} else {
13413 
13414 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
13415 		}
13416 	}
13417 
13418 	return (rval);
13419 }
13420 
13421 
13422 static int
13423 st_check_sequential_clean_bit(struct scsi_tape *un)
13424 {
13425 	int rval;
13426 	int ix;
13427 	ushort_t parameter;
13428 	struct uscsi_cmd *cmd;
13429 	struct log_sequential_page *sp;
13430 	struct log_sequential_page_parameter *prm;
13431 	struct scsi_arq_status status;
13432 	char cdb[CDB_GROUP1] = {
13433 		SCMD_LOG_SENSE_G1,
13434 		0,
13435 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
13436 		0,
13437 		0,
13438 		0,
13439 		0,
13440 		(char)(sizeof (struct log_sequential_page) >> 8),
13441 		(char)(sizeof (struct log_sequential_page)),
13442 		0
13443 	};
13444 
13445 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
13446 
13447 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13448 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
13449 
13450 	cmd->uscsi_flags   =
13451 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13452 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13453 	cmd->uscsi_cdb	   = cdb;
13454 	cmd->uscsi_cdblen  = CDB_GROUP1;
13455 	cmd->uscsi_bufaddr = (caddr_t)sp;
13456 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
13457 	cmd->uscsi_rqlen   = sizeof (status);
13458 	cmd->uscsi_rqbuf   = (caddr_t)&status;
13459 
13460 	rval = st_uscsi_cmd(un, cmd, FKIOCTL);
13461 
13462 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
13463 
13464 		rval = -1;
13465 
13466 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
13467 
13468 		rval = -1;
13469 	}
13470 
13471 	prm = &sp->param[0];
13472 
13473 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
13474 
13475 		if (prm->log_param.length == 0) {
13476 			break;
13477 		}
13478 
13479 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
13480 		    (prm->log_param.pc_lo & 0xff));
13481 
13482 		if (parameter == SEQUENTIAL_NEED_CLN) {
13483 
13484 			rval = MTF_TAPE_CLN_SUPPORTED;
13485 			if (prm->param_value[prm->log_param.length - 1]) {
13486 
13487 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13488 				    "sequential log says head dirty\n");
13489 				rval |= MTF_TAPE_HEAD_DIRTY;
13490 			}
13491 		}
13492 		prm = (struct log_sequential_page_parameter *)
13493 		    &prm->param_value[prm->log_param.length];
13494 	}
13495 
13496 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13497 	kmem_free(sp,  sizeof (struct log_sequential_page));
13498 
13499 	return (rval);
13500 }
13501 
13502 
13503 static int
13504 st_check_alert_flags(struct scsi_tape *un)
13505 {
13506 	struct st_tape_alert *ta;
13507 	struct uscsi_cmd *com;
13508 	struct scsi_arq_status status;
13509 	unsigned ix, length;
13510 	int rval;
13511 	tape_alert_flags flag;
13512 	char cdb[CDB_GROUP1] = {
13513 		SCMD_LOG_SENSE_G1,
13514 		0,
13515 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
13516 		0,
13517 		0,
13518 		0,
13519 		0,
13520 		(char)(sizeof (struct st_tape_alert) >> 8),
13521 		(char)(sizeof (struct st_tape_alert)),
13522 		0
13523 	};
13524 
13525 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
13526 
13527 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13528 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
13529 
13530 	com->uscsi_cdb = cdb;
13531 	com->uscsi_cdblen = CDB_GROUP1;
13532 	com->uscsi_bufaddr = (caddr_t)ta;
13533 	com->uscsi_buflen = sizeof (struct st_tape_alert);
13534 	com->uscsi_rqlen = sizeof (status);
13535 	com->uscsi_rqbuf = (caddr_t)&status;
13536 	com->uscsi_flags =
13537 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13538 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13539 
13540 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13541 
13542 	if (rval || com->uscsi_status || com->uscsi_resid) {
13543 
13544 		rval = -1; /* uscsi-command failed */
13545 
13546 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
13547 
13548 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13549 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
13550 		rval = -1;
13551 	}
13552 
13553 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
13554 
13555 
13556 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
13557 
13558 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13559 		    "TapeAlert length %d\n", length);
13560 	}
13561 
13562 
13563 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
13564 
13565 		/*
13566 		 * if rval is bad before the first pass don't bother
13567 		 */
13568 		if (ix == 0 && rval != 0) {
13569 
13570 			break;
13571 		}
13572 
13573 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
13574 		    ta->param[ix].log_param.pc_lo);
13575 
13576 		if ((ta->param[ix].param_value & 1) == 0) {
13577 			continue;
13578 		}
13579 		/*
13580 		 * check to see if current parameter is of interest.
13581 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
13582 		 */
13583 		if ((flag == TAF_CLEAN_NOW) ||
13584 		    (flag == TAF_CLEAN_PERIODIC) ||
13585 		    ((flag == CLEAN_FOR_ERRORS) &&
13586 		    (un->un_dp->type == ST_TYPE_STK9840))) {
13587 
13588 			rval = MTF_TAPE_CLN_SUPPORTED;
13589 
13590 
13591 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13592 			    "alert_page drive needs clean %d\n", flag);
13593 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
13594 			rval |= MTF_TAPE_HEAD_DIRTY;
13595 
13596 		} else if (flag == TAF_CLEANING_MEDIA) {
13597 
13598 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13599 			    "alert_page drive was cleaned\n");
13600 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
13601 		}
13602 
13603 	}
13604 
13605 	/*
13606 	 * Report it as dirty till we see it cleaned
13607 	 */
13608 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
13609 
13610 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13611 		    "alert_page still dirty\n");
13612 		rval |= MTF_TAPE_HEAD_DIRTY;
13613 	}
13614 
13615 	kmem_free(com, sizeof (struct uscsi_cmd));
13616 	kmem_free(ta,  sizeof (struct st_tape_alert));
13617 
13618 	return (rval);
13619 }
13620 
13621 
13622 static int
13623 st_check_sense_clean_bit(struct scsi_tape *un)
13624 {
13625 	uchar_t *sensep;
13626 	char cdb[CDB_GROUP0];
13627 	struct uscsi_cmd *com;
13628 	ushort_t byte_pos;
13629 	uchar_t bit_mask;
13630 	unsigned length;
13631 	int index;
13632 	int rval;
13633 
13634 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
13635 
13636 	/*
13637 	 * Since this tape does not support Tape Alert,
13638 	 * we now try to get the cleanbit status via
13639 	 * Request Sense.
13640 	 */
13641 
13642 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
13643 
13644 		index = 0;
13645 
13646 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
13647 
13648 		index = 1;
13649 
13650 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
13651 
13652 		index = 2;
13653 
13654 	} else {
13655 
13656 		return (-1);
13657 	}
13658 
13659 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
13660 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
13661 	length = byte_pos + 1;
13662 
13663 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13664 	sensep = kmem_zalloc(length, KM_SLEEP);
13665 
13666 	cdb[0] = SCMD_REQUEST_SENSE;
13667 	cdb[1] = 0;
13668 	cdb[2] = 0;
13669 	cdb[3] = 0;
13670 	cdb[4] = (char)length;
13671 	cdb[5] = 0;
13672 
13673 	com->uscsi_cdb = cdb;
13674 	com->uscsi_cdblen = CDB_GROUP0;
13675 	com->uscsi_bufaddr = (caddr_t)sensep;
13676 	com->uscsi_buflen = length;
13677 	com->uscsi_flags =
13678 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13679 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13680 
13681 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13682 
13683 	if (rval || com->uscsi_status || com->uscsi_resid) {
13684 
13685 		rval = -1;
13686 
13687 	} else {
13688 
13689 		rval = MTF_TAPE_CLN_SUPPORTED;
13690 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
13691 
13692 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13693 			    "sense data says head dirty\n");
13694 			rval |= MTF_TAPE_HEAD_DIRTY;
13695 		}
13696 	}
13697 
13698 	kmem_free(com, sizeof (struct uscsi_cmd));
13699 	kmem_free(sensep, length);
13700 	return (rval);
13701 }
13702 
13703 /*
13704  * st_clear_unit_attention
13705  *
13706  *  	run test unit ready's to clear out outstanding
13707  * 	unit attentions.
13708  * 	returns zero for SUCCESS or the errno from st_cmd call
13709  */
13710 static int
13711 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
13712 {
13713 	int	i    = 0;
13714 	int	rval;
13715 
13716 	GET_SOFT_STATE(dev_instance);
13717 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
13718 
13719 	do {
13720 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
13721 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
13722 	return (rval);
13723 }
13724 
13725 static void
13726 st_calculate_timeouts(struct scsi_tape *un)
13727 {
13728 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
13729 
13730 	if (un->un_dp->non_motion_timeout == 0) {
13731 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13732 			un->un_dp->non_motion_timeout =
13733 			    st_io_time * st_long_timeout_x;
13734 		} else {
13735 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
13736 		}
13737 	}
13738 
13739 	if (un->un_dp->io_timeout == 0) {
13740 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13741 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
13742 		} else {
13743 			un->un_dp->io_timeout = (ushort_t)st_io_time;
13744 		}
13745 	}
13746 
13747 	if (un->un_dp->rewind_timeout == 0) {
13748 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13749 			un->un_dp->rewind_timeout =
13750 			    st_space_time * st_long_timeout_x;
13751 		} else {
13752 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
13753 		}
13754 	}
13755 
13756 	if (un->un_dp->space_timeout == 0) {
13757 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13758 			un->un_dp->space_timeout =
13759 			    st_space_time * st_long_timeout_x;
13760 		} else {
13761 			un->un_dp->space_timeout = (ushort_t)st_space_time;
13762 		}
13763 	}
13764 
13765 	if (un->un_dp->load_timeout == 0) {
13766 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13767 			un->un_dp->load_timeout =
13768 			    st_space_time * st_long_timeout_x;
13769 		} else {
13770 			un->un_dp->load_timeout = (ushort_t)st_space_time;
13771 		}
13772 	}
13773 
13774 	if (un->un_dp->unload_timeout == 0) {
13775 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13776 			un->un_dp->unload_timeout =
13777 			    st_space_time * st_long_timeout_x;
13778 		} else {
13779 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
13780 		}
13781 	}
13782 
13783 	if (un->un_dp->erase_timeout == 0) {
13784 		if (un->un_dp->options & ST_LONG_ERASE) {
13785 			un->un_dp->erase_timeout =
13786 			    st_space_time * st_long_space_time_x;
13787 		} else {
13788 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
13789 		}
13790 	}
13791 }
13792 
13793 
13794 static writablity
13795 st_is_not_wormable(struct scsi_tape *un)
13796 {
13797 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
13798 	return (RDWR);
13799 }
13800 
13801 static writablity
13802 st_is_hp_dat_tape_worm(struct scsi_tape *un)
13803 {
13804 	writablity wrt;
13805 
13806 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
13807 
13808 	/* Mode sense should be current */
13809 	if (un->un_mspl->media_type == 1) {
13810 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13811 		    "Drive has WORM media loaded\n");
13812 		wrt = WORM;
13813 	} else {
13814 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13815 		    "Drive has non WORM media loaded\n");
13816 		wrt = RDWR;
13817 	}
13818 	return (wrt);
13819 }
13820 
13821 #define	HP_DAT_INQUIRY 0x4A
13822 static writablity
13823 st_is_hp_dat_worm(struct scsi_tape *un)
13824 {
13825 	char *buf;
13826 	int result;
13827 	writablity wrt;
13828 
13829 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
13830 
13831 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
13832 
13833 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
13834 
13835 	if (result != 0) {
13836 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13837 		    "Read Standard Inquiry for WORM support failed");
13838 		wrt = FAILED;
13839 	} else if ((buf[40] & 1) == 0) {
13840 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13841 		    "Drive is NOT WORMable\n");
13842 		/* This drive doesn't support it so don't check again */
13843 		un->un_dp->options &= ~ST_WORMABLE;
13844 		wrt = RDWR;
13845 		un->un_wormable = st_is_not_wormable;
13846 	} else {
13847 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13848 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13849 		un->un_wormable = st_is_hp_dat_tape_worm;
13850 		wrt = un->un_wormable(un);
13851 	}
13852 
13853 	kmem_free(buf, HP_DAT_INQUIRY);
13854 
13855 	/*
13856 	 * If drive doesn't support it no point in checking further.
13857 	 */
13858 	return (wrt);
13859 }
13860 
13861 static writablity
13862 st_is_hp_lto_tape_worm(struct scsi_tape *un)
13863 {
13864 	writablity wrt;
13865 
13866 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
13867 
13868 	/* Mode sense should be current */
13869 	switch (un->un_mspl->media_type) {
13870 	case 0x00:
13871 		switch (un->un_mspl->density) {
13872 		case 0x40:
13873 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13874 			    "Drive has standard Gen I media loaded\n");
13875 			break;
13876 		case 0x42:
13877 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13878 			    "Drive has standard Gen II media loaded\n");
13879 			break;
13880 		case 0x44:
13881 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13882 			    "Drive has standard Gen III media loaded\n");
13883 			break;
13884 		case 0x46:
13885 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13886 			    "Drive has standard Gen IV media loaded\n");
13887 			break;
13888 		default:
13889 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13890 			    "Drive has standard unknown 0x%X media loaded\n",
13891 			    un->un_mspl->density);
13892 		}
13893 		wrt = RDWR;
13894 		break;
13895 	case 0x01:
13896 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13897 		    "Drive has WORM medium loaded\n");
13898 		wrt = WORM;
13899 		break;
13900 	case 0x80:
13901 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13902 		    "Drive has CD-ROM emulation medium loaded\n");
13903 		wrt = WORM;
13904 		break;
13905 	default:
13906 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13907 		    "Drive has an unexpected medium type 0x%X loaded\n",
13908 		    un->un_mspl->media_type);
13909 		wrt = RDWR;
13910 	}
13911 
13912 	return (wrt);
13913 }
13914 
13915 #define	LTO_REQ_INQUIRY 44
13916 static writablity
13917 st_is_hp_lto_worm(struct scsi_tape *un)
13918 {
13919 	char *buf;
13920 	int result;
13921 	writablity wrt;
13922 
13923 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
13924 
13925 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
13926 
13927 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
13928 
13929 	if (result != 0) {
13930 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13931 		    "Read Standard Inquiry for WORM support failed");
13932 		wrt = FAILED;
13933 	} else if ((buf[40] & 1) == 0) {
13934 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13935 		    "Drive is NOT WORMable\n");
13936 		/* This drive doesn't support it so don't check again */
13937 		un->un_dp->options &= ~ST_WORMABLE;
13938 		wrt = RDWR;
13939 		un->un_wormable = st_is_not_wormable;
13940 	} else {
13941 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13942 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13943 		un->un_wormable = st_is_hp_lto_tape_worm;
13944 		wrt = un->un_wormable(un);
13945 	}
13946 
13947 	kmem_free(buf, LTO_REQ_INQUIRY);
13948 
13949 	/*
13950 	 * If drive doesn't support it no point in checking further.
13951 	 */
13952 	return (wrt);
13953 }
13954 
13955 static writablity
13956 st_is_t10_worm_device(struct scsi_tape *un)
13957 {
13958 	writablity wrt;
13959 
13960 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
13961 
13962 	if (un->un_mspl->media_type == 0x3c) {
13963 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13964 		    "Drive has WORM media loaded\n");
13965 		wrt = WORM;
13966 	} else {
13967 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13968 		    "Drive has non WORM media loaded\n");
13969 		wrt = RDWR;
13970 	}
13971 	return (wrt);
13972 }
13973 
13974 #define	SEQ_CAP_PAGE	(char)0xb0
13975 static writablity
13976 st_is_t10_worm(struct scsi_tape *un)
13977 {
13978 	char *buf;
13979 	int result;
13980 	writablity wrt;
13981 
13982 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
13983 
13984 	buf = kmem_zalloc(6, KM_SLEEP);
13985 
13986 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
13987 
13988 	if (result != 0) {
13989 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13990 		    "Read Vitial Inquiry for Sequental Capability"
13991 		    " WORM support failed %x", result);
13992 		wrt = FAILED;
13993 	} else if ((buf[4] & 1) == 0) {
13994 		ASSERT(buf[1] == SEQ_CAP_PAGE);
13995 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13996 		    "Drive is NOT WORMable\n");
13997 		/* This drive doesn't support it so don't check again */
13998 		un->un_dp->options &= ~ST_WORMABLE;
13999 		wrt = RDWR;
14000 		un->un_wormable = st_is_not_wormable;
14001 	} else {
14002 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14003 		    "Drive supports WORM\n");
14004 		un->un_wormable = st_is_t10_worm_device;
14005 		wrt = un->un_wormable(un);
14006 	}
14007 
14008 	kmem_free(buf, 6);
14009 
14010 	return (wrt);
14011 }
14012 
14013 
14014 #define	STK_REQ_SENSE 26
14015 
14016 static writablity
14017 st_is_stk_worm(struct scsi_tape *un)
14018 {
14019 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
14020 	struct scsi_extended_sense *sense;
14021 	struct uscsi_cmd *cmd;
14022 	char *buf;
14023 	int result;
14024 	writablity wrt;
14025 
14026 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
14027 
14028 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14029 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
14030 	sense = (struct scsi_extended_sense *)buf;
14031 
14032 	cmd->uscsi_flags = USCSI_READ;
14033 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14034 	cmd->uscsi_cdb = &cdb[0];
14035 	cmd->uscsi_bufaddr = buf;
14036 	cmd->uscsi_buflen = STK_REQ_SENSE;
14037 	cmd->uscsi_cdblen = CDB_GROUP0;
14038 	cmd->uscsi_rqlen = 0;
14039 	cmd->uscsi_rqbuf = NULL;
14040 
14041 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14042 
14043 	if (result != 0 || cmd->uscsi_status != 0) {
14044 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14045 		    "Request Sense for WORM failed");
14046 		wrt = RDWR;
14047 	} else if (sense->es_add_len + 8 < 24) {
14048 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14049 		    "Drive didn't send enough sense data for WORM byte %d\n",
14050 		    sense->es_add_len + 8);
14051 		wrt = RDWR;
14052 		un->un_wormable = st_is_not_wormable;
14053 	} else if ((buf[24]) & 0x02) {
14054 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14055 		    "Drive has WORM tape loaded\n");
14056 		wrt = WORM;
14057 		un->un_wormable = st_is_stk_worm;
14058 	} else {
14059 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14060 		    "Drive has normal tape loaded\n");
14061 		wrt = RDWR;
14062 		un->un_wormable = st_is_stk_worm;
14063 	}
14064 
14065 	kmem_free(buf, STK_REQ_SENSE);
14066 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14067 	return (wrt);
14068 }
14069 
14070 #define	DLT_INQ_SZ 44
14071 
14072 static writablity
14073 st_is_dlt_tape_worm(struct scsi_tape *un)
14074 {
14075 	caddr_t buf;
14076 	int result;
14077 	writablity wrt;
14078 
14079 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
14080 
14081 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14082 
14083 	/* Read Attribute Media Type */
14084 
14085 	result = st_read_attributes(un, 0x0408, buf, 10, st_uscsi_cmd);
14086 
14087 	/*
14088 	 * If this quantum drive is attached via an HBA that cannot
14089 	 * support thr read attributes command return error in the
14090 	 * hope that someday they will support the t10 method.
14091 	 */
14092 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
14093 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14094 		    "Read Attribute Command for WORM Media detection is not "
14095 		    "supported on the HBA that this drive is attached to.");
14096 		wrt = RDWR;
14097 		un->un_wormable = st_is_not_wormable;
14098 		goto out;
14099 	}
14100 
14101 	if (result != 0) {
14102 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14103 		    "Read Attribute Command for WORM Media returned 0x%x",
14104 		    result);
14105 		wrt = RDWR;
14106 		un->un_dp->options &= ~ST_WORMABLE;
14107 		goto out;
14108 	}
14109 
14110 	if ((uchar_t)buf[9] == 0x80) {
14111 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14112 		    "Drive media is WORM\n");
14113 		wrt = WORM;
14114 	} else {
14115 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14116 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
14117 		wrt = RDWR;
14118 	}
14119 
14120 out:
14121 	kmem_free(buf, DLT_INQ_SZ);
14122 	return (wrt);
14123 }
14124 
14125 static writablity
14126 st_is_dlt_worm(struct scsi_tape *un)
14127 {
14128 	caddr_t buf;
14129 	int result;
14130 	writablity wrt;
14131 
14132 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
14133 
14134 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14135 
14136 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
14137 
14138 	if (result != 0) {
14139 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14140 		    "Read Vendor Specific Inquiry for WORM support failed");
14141 		wrt = RDWR;
14142 		goto out;
14143 	}
14144 
14145 	if ((buf[2] & 1) == 0) {
14146 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14147 		    "Drive is not WORMable\n");
14148 		wrt = RDWR;
14149 		un->un_dp->options &= ~ST_WORMABLE;
14150 		un->un_wormable = st_is_not_wormable;
14151 		goto out;
14152 	} else {
14153 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14154 		    "Drive is WORMable\n");
14155 		un->un_wormable = st_is_dlt_tape_worm;
14156 		wrt = un->un_wormable(un);
14157 	}
14158 out:
14159 	kmem_free(buf, DLT_INQ_SZ);
14160 
14161 	return (wrt);
14162 }
14163 
14164 typedef struct {
14165 	struct modeheader_seq header;
14166 #if defined(_BIT_FIELDS_LTOH) /* X86 */
14167 	uchar_t pagecode	:6,
14168 				:2;
14169 	uchar_t page_len;
14170 	uchar_t syslogalive	:2,
14171 		device		:1,
14172 		abs		:1,
14173 		ulpbot		:1,
14174 		prth		:1,
14175 		ponej		:1,
14176 		ait		:1;
14177 	uchar_t span;
14178 
14179 	uchar_t			:6,
14180 		worm		:1,
14181 		mic		:1;
14182 	uchar_t worm_cap	:1,
14183 				:7;
14184 	uint32_t		:32;
14185 #else /* SPARC */
14186 	uchar_t			:2,
14187 		pagecode	:6;
14188 	uchar_t page_len;
14189 	uchar_t ait		:1,
14190 		device		:1,
14191 		abs		:1,
14192 		ulpbot		:1,
14193 		prth		:1,
14194 		ponej		:1,
14195 		syslogalive	:2;
14196 	uchar_t span;
14197 	uchar_t mic		:1,
14198 		worm		:1,
14199 				:6;
14200 	uchar_t			:7,
14201 		worm_cap	:1;
14202 	uint32_t		:32;
14203 #endif
14204 }ait_dev_con;
14205 
14206 #define	AIT_DEV_PAGE 0x31
14207 static writablity
14208 st_is_sony_worm(struct scsi_tape *un)
14209 {
14210 	int result;
14211 	writablity wrt;
14212 	ait_dev_con *ait_conf;
14213 
14214 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14215 
14216 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
14217 
14218 	result = st_gen_mode_sense(un, st_uscsi_cmd, AIT_DEV_PAGE,
14219 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
14220 
14221 	if (result == 0) {
14222 
14223 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
14224 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14225 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
14226 			    ait_conf->pagecode, AIT_DEV_PAGE);
14227 			wrt = RDWR;
14228 			un->un_wormable = st_is_not_wormable;
14229 
14230 		} else if (ait_conf->worm_cap) {
14231 
14232 			un->un_wormable = st_is_sony_worm;
14233 
14234 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14235 			    "Drives is WORMable\n");
14236 			if (ait_conf->worm) {
14237 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14238 				    "Media is WORM\n");
14239 				wrt = WORM;
14240 			} else {
14241 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14242 				    "Media is not WORM\n");
14243 				wrt = RDWR;
14244 			}
14245 
14246 		} else {
14247 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14248 			    "Drives not is WORMable\n");
14249 			wrt = RDWR;
14250 			/* No further checking required */
14251 			un->un_dp->options &= ~ST_WORMABLE;
14252 		}
14253 
14254 	} else {
14255 
14256 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14257 		    "AIT device config mode sense page read command failed"
14258 		    " result = %d ", result);
14259 		wrt = FAILED;
14260 		un->un_wormable = st_is_not_wormable;
14261 	}
14262 
14263 	kmem_free(ait_conf, sizeof (ait_dev_con));
14264 	return (wrt);
14265 }
14266 
14267 static writablity
14268 st_is_drive_worm(struct scsi_tape *un)
14269 {
14270 	writablity wrt;
14271 
14272 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14273 
14274 	switch (un->un_dp->type) {
14275 	case MT_ISDLT:
14276 		wrt = st_is_dlt_worm(un);
14277 		break;
14278 
14279 	case MT_ISSTK9840:
14280 		wrt = st_is_stk_worm(un);
14281 		break;
14282 
14283 	case MT_IS8MM:
14284 	case MT_ISAIT:
14285 		wrt = st_is_sony_worm(un);
14286 		break;
14287 
14288 	case MT_LTO:
14289 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14290 			wrt = st_is_hp_lto_worm(un);
14291 		} else {
14292 			wrt = st_is_t10_worm(un);
14293 		}
14294 		break;
14295 
14296 	case MT_ISDAT:
14297 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14298 			wrt = st_is_hp_dat_worm(un);
14299 		} else {
14300 			wrt = st_is_t10_worm(un);
14301 		}
14302 		break;
14303 
14304 	default:
14305 		wrt = FAILED;
14306 		break;
14307 	}
14308 
14309 	/*
14310 	 * If any of the above failed try the t10 standard method.
14311 	 */
14312 	if (wrt == FAILED) {
14313 		wrt = st_is_t10_worm(un);
14314 	}
14315 
14316 	/*
14317 	 * Unknown method for detecting WORM media.
14318 	 */
14319 	if (wrt == FAILED) {
14320 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14321 		    "Unknown method for WORM media detection\n");
14322 		wrt = RDWR;
14323 		un->un_dp->options &= ~ST_WORMABLE;
14324 	}
14325 
14326 	return (wrt);
14327 }
14328 
14329 static int
14330 st_read_attributes(struct scsi_tape *un, uint16_t attribute, void *pnt,
14331     size_t size, ubufunc_t bufunc)
14332 {
14333 	char cdb[CDB_GROUP4];
14334 	int result;
14335 	struct uscsi_cmd *cmd;
14336 	struct scsi_arq_status status;
14337 
14338 	caddr_t buf = (caddr_t)pnt;
14339 
14340 	ST_FUNC(ST_DEVINFO, st_read_attributes);
14341 
14342 	if (un->un_sd->sd_inq->inq_ansi < 3) {
14343 		return (ENOTTY);
14344 	}
14345 
14346 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14347 
14348 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
14349 	cdb[1] = 0;
14350 	cdb[2] = 0;
14351 	cdb[3] = 0;
14352 	cdb[4] = 0;
14353 	cdb[5] = 0;
14354 	cdb[6] = 0;
14355 	cdb[7] = 0;
14356 	cdb[8] = (char)(attribute >> 8);
14357 	cdb[9] = (char)(attribute);
14358 	cdb[10] = (char)(size >> 24);
14359 	cdb[11] = (char)(size >> 16);
14360 	cdb[12] = (char)(size >> 8);
14361 	cdb[13] = (char)(size);
14362 	cdb[14] = 0;
14363 	cdb[15] = 0;
14364 
14365 
14366 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE | USCSI_DIAGNOSE;
14367 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14368 	cmd->uscsi_cdb = &cdb[0];
14369 	cmd->uscsi_bufaddr = (caddr_t)buf;
14370 	cmd->uscsi_buflen = size;
14371 	cmd->uscsi_cdblen = sizeof (cdb);
14372 	cmd->uscsi_rqlen = sizeof (status);
14373 	cmd->uscsi_rqbuf = (caddr_t)&status;
14374 
14375 	result = bufunc(un, cmd, FKIOCTL);
14376 
14377 	if (result != 0 || cmd->uscsi_status != 0) {
14378 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
14379 		    "st_read_attribute failed: result %d status %d\n",
14380 		    result, cmd->uscsi_status);
14381 		/*
14382 		 * If this returns invalid operation code don't try again.
14383 		 */
14384 		if (un->un_sd->sd_sense->es_key == KEY_ILLEGAL_REQUEST &&
14385 		    un->un_sd->sd_sense->es_add_code == 0x20) {
14386 			result = ENOTTY;
14387 		} else if (result == 0) {
14388 			result = EIO;
14389 		}
14390 
14391 	} else {
14392 
14393 		/*
14394 		 * The attribute retured should match the attribute requested.
14395 		 */
14396 		if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
14397 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14398 			    "st_read_attribute got wrong data back expected "
14399 			    "0x%x got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
14400 			st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14401 			    "bad? data", buf, size);
14402 			result = EIO;
14403 		}
14404 	}
14405 
14406 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14407 
14408 	return (result);
14409 }
14410 
14411 static int
14412 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
14413     uchar_t page)
14414 {
14415 	char cdb[CDB_GROUP0];
14416 	struct scsi_extended_sense *sense;
14417 	struct uscsi_cmd *cmd;
14418 	int result;
14419 
14420 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
14421 
14422 	cdb[0] = SCMD_INQUIRY;
14423 	cdb[1] = page ? 1 : 0;
14424 	cdb[2] = page;
14425 	cdb[3] = 0;
14426 	cdb[4] = size;
14427 	cdb[5] = 0;
14428 
14429 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14430 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
14431 
14432 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
14433 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14434 	cmd->uscsi_cdb = &cdb[0];
14435 	cmd->uscsi_bufaddr = dest;
14436 	cmd->uscsi_buflen = size;
14437 	cmd->uscsi_cdblen = CDB_GROUP0;
14438 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
14439 	cmd->uscsi_rqbuf = (caddr_t)sense;
14440 
14441 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14442 
14443 	if (result != 0 || cmd->uscsi_status != 0) {
14444 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14445 		    "st_get_special_inquiry() failed for page %x", page);
14446 		if (result == 0) {
14447 			result = EIO;
14448 		}
14449 	}
14450 
14451 	kmem_free(sense, sizeof (struct scsi_extended_sense));
14452 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14453 
14454 	return (result);
14455 }
14456 
14457 
14458 static int
14459 st_update_block_pos(struct scsi_tape *un, bufunc_t bf, int post_space)
14460 {
14461 	int rval = ENOTTY;
14462 	uchar_t status = un->un_status;
14463 	posmode previous_pmode = un->un_running.pmode;
14464 
14465 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
14466 
14467 	while (un->un_read_pos_type != NO_POS) {
14468 		rval = bf(un, SCMD_READ_POSITION, 32, SYNC_CMD);
14469 
14470 		/*
14471 		 * If read position command returned good status
14472 		 * Parse the data to see if the position can be interpreted.
14473 		 */
14474 		if ((rval == 0) &&
14475 		    ((rval = st_interpret_read_pos(un, &un->un_pos,
14476 		    un->un_read_pos_type, 32, (caddr_t)un->un_read_pos_data,
14477 		    post_space)) == 0)) {
14478 			/*
14479 			 * Update the running position as well if un_pos was
14480 			 * ok. But only if recovery is enabled.
14481 			 */
14482 			if (st_recov_sz != sizeof (recov_info)) {
14483 				break;
14484 			}
14485 			rval = st_interpret_read_pos(un, &un->un_running,
14486 			    un->un_read_pos_type, 32,
14487 			    (caddr_t)un->un_read_pos_data, post_space);
14488 			un->un_status = status;
14489 			break;
14490 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
14491 			un->un_running.pmode = previous_pmode;
14492 			continue;
14493 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
14494 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
14495 			    "st_update_block_pos() read position cmd 0x%x"
14496 			    " returned 0x%x un_status = %d",
14497 			    un->un_read_pos_type, rval, un->un_status);
14498 			/* ENOTTY means it read garbage. try something else. */
14499 			if (rval == ENOTTY) {
14500 				rval = EIO; /* so ENOTTY is not final rval */
14501 			} else {
14502 				break;
14503 			}
14504 		} else {
14505 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
14506 			    "st_update_block_pos() read position cmd %x"
14507 			    " returned %x", un->un_read_pos_type, rval);
14508 			un->un_running.pmode = previous_pmode;
14509 		}
14510 
14511 		switch (un->un_read_pos_type) {
14512 		case SHORT_POS:
14513 			un->un_read_pos_type = NO_POS;
14514 			break;
14515 
14516 		case LONG_POS:
14517 			un->un_read_pos_type = EXT_POS;
14518 			break;
14519 
14520 		case EXT_POS:
14521 			un->un_read_pos_type = SHORT_POS;
14522 			break;
14523 
14524 		default:
14525 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14526 			    "Unexpected read position type 0x%x",
14527 			    un->un_read_pos_type);
14528 		}
14529 		un->un_status = KEY_NO_SENSE;
14530 	}
14531 
14532 	return (rval);
14533 }
14534 
14535 static int
14536 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
14537 {
14538 	int result;
14539 	size_t d_sz;
14540 	caddr_t pos_info;
14541 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
14542 
14543 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
14544 
14545 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
14546 		return (0);
14547 	}
14548 
14549 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
14550 
14551 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14552 		    "bp_mapin_common() failed");
14553 
14554 		return (EIO);
14555 	}
14556 
14557 	d_sz = bp->b_bcount - bp->b_resid;
14558 	if (d_sz == 0) {
14559 		bp_mapout(bp);
14560 		return (EIO);
14561 	}
14562 
14563 	/*
14564 	 * Copy the buf to a double-word aligned memory that can hold the
14565 	 * tape_position_t data structure.
14566 	 */
14567 	if ((pos_info = kmem_alloc(d_sz, KM_NOSLEEP)) == NULL) {
14568 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14569 		    "kmem_alloc() failed");
14570 		bp_mapout(bp);
14571 		return (EIO);
14572 	}
14573 	bcopy(bp->b_un.b_addr, pos_info, d_sz);
14574 
14575 #ifdef STDEBUG
14576 	if ((st_debug & 0x7) > 2) {
14577 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14578 		    "st_get_read_pos() position info",
14579 		    pos_info, bp->b_bcount);
14580 	}
14581 #endif
14582 
14583 	result = st_interpret_read_pos(un, &un->un_pos, cmd->uscsi_cdb[1],
14584 	    d_sz, pos_info, 0);
14585 
14586 	COPY_POS(&un->un_running, &un->un_pos);
14587 
14588 	kmem_free(pos_info, d_sz);
14589 	bp_mapout(bp);
14590 
14591 	return (result);
14592 }
14593 
14594 #if defined(_BIG_ENDIAN)
14595 
14596 #define	FIX_ENDIAN16(x)
14597 #define	FIX_ENDIAN32(x)
14598 #define	FIX_ENDIAN64(x)
14599 
14600 #elif defined(_LITTLE_ENDIAN)
14601 
14602 static void
14603 st_swap16(uint16_t *val)
14604 {
14605 	uint16_t tmp;
14606 
14607 	tmp = (*val >>  8) & 0xff;
14608 	tmp |= (*val <<  8) & 0xff00;
14609 
14610 	*val = tmp;
14611 }
14612 
14613 static void
14614 st_swap32(uint32_t *val)
14615 {
14616 	uint32_t tmp;
14617 
14618 	tmp =  (*val >> 24) & 0xff;
14619 	tmp |= (*val >>  8) & 0xff00;
14620 	tmp |= (*val <<  8) & 0xff0000;
14621 	tmp |= (*val << 24) & 0xff000000;
14622 
14623 	*val = tmp;
14624 }
14625 
14626 static void
14627 st_swap64(uint64_t *val)
14628 {
14629 	uint32_t low;
14630 	uint32_t high;
14631 
14632 	low =  (uint32_t)(*val);
14633 	high = (uint32_t)(*val >> 32);
14634 
14635 	st_swap32(&low);
14636 	st_swap32(&high);
14637 
14638 	*val =  high;
14639 	*val |= ((uint64_t)low << 32);
14640 }
14641 
14642 #define	FIX_ENDIAN16(x) st_swap16(x)
14643 #define	FIX_ENDIAN32(x) st_swap32(x)
14644 #define	FIX_ENDIAN64(x) st_swap64(x)
14645 #endif
14646 
14647 /*
14648  * st_interpret_read_pos()
14649  *
14650  * Returns:
14651  *	0	If secsessful.
14652  *	EIO	If read postion responce data was unuseable or invalid.
14653  *	ERANGE	If the position of the drive is too large for the read_p_type.
14654  *	ENOTTY	If the responce data looks invalid for the read position type.
14655  */
14656 
14657 static int
14658 st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
14659     read_p_types type, size_t data_sz, const caddr_t responce, int post_space)
14660 {
14661 	int rval = 0;
14662 	int flag = 0;
14663 	tapepos_t org;
14664 
14665 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
14666 
14667 	/*
14668 	 * We expect the position value to change after a space command.
14669 	 * So if post_space is set we don't print out what has changed.
14670 	 */
14671 	if ((dest != &un->un_pos) && (post_space == 0) &&
14672 	    (st_recov_sz == sizeof (recov_info))) {
14673 		COPY_POS(&org, dest);
14674 		flag = 1;
14675 	}
14676 
14677 	/*
14678 	 * See what kind of read position was requested.
14679 	 */
14680 	switch (type) {
14681 
14682 	case SHORT_POS: /* Short data format */
14683 	{
14684 		tape_position_t *pos_info = (tape_position_t *)responce;
14685 		uint32_t value;
14686 
14687 		/* If reserved fields are non zero don't use the data */
14688 		if (pos_info->reserved0 || pos_info->reserved1 ||
14689 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
14690 		    pos_info->reserved3) {
14691 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14692 			    "Invalid Read Short Position Data returned\n");
14693 			rval = EIO;
14694 			break;
14695 		}
14696 		/*
14697 		 * Position is to large to use this type of read position.
14698 		 */
14699 		if (pos_info->posi_err == 1) {
14700 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14701 			    "Drive reported position error\n");
14702 			rval = ERANGE;
14703 			break;
14704 		}
14705 		/*
14706 		 * If your at the begining of partition and end at the same
14707 		 * time it's very small partition or bad data.
14708 		 */
14709 		if (pos_info->begin_of_part && pos_info->end_of_part) {
14710 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14711 			    "SHORT_POS returned begin and end of"
14712 			    " partition\n");
14713 			rval = EIO;
14714 			break;
14715 		}
14716 
14717 		if (pos_info->blk_posi_unkwn == 0) {
14718 
14719 			value = pos_info->host_block;
14720 			FIX_ENDIAN32(&value);
14721 
14722 			/*
14723 			 * If the tape is rewound the host blcok should be 0.
14724 			 */
14725 			if ((pos_info->begin_of_part == 1) &&
14726 			    (value != 0)) {
14727 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14728 				    "SHORT_POS returned begin of partition"
14729 				    " but host block was 0x%x\n", value);
14730 				rval = EIO;
14731 				break;
14732 			}
14733 
14734 			if (dest->lgclblkno != value) {
14735 				if (flag)
14736 					flag++;
14737 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14738 				    "SHORT_POS current logical 0x%"PRIx64" read"
14739 				    " 0x%x\n", dest->lgclblkno, value);
14740 			}
14741 
14742 			dest->lgclblkno = (uint64_t)value;
14743 
14744 			/*
14745 			 * If the begining of partition is true and the
14746 			 * block number is zero we will beleive that it is
14747 			 * rewound. Promote the pmode to legacy.
14748 			 */
14749 			if ((pos_info->begin_of_part == 1) &&
14750 			    (value == 0)) {
14751 				dest->blkno = 0;
14752 				dest->fileno = 0;
14753 				if (dest->pmode != legacy)
14754 					dest->pmode = legacy;
14755 			/*
14756 			 * otherwise if the pmode was invalid,
14757 			 * promote it to logical.
14758 			 */
14759 			} else if (dest->pmode == invalid) {
14760 				dest->pmode = logical;
14761 			}
14762 
14763 			if (dest->partition != pos_info->partition_number) {
14764 				if (flag)
14765 					flag++;
14766 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14767 				    "SHORT_POS current partition %d read %d\n",
14768 				    dest->partition,
14769 				    pos_info->partition_number);
14770 			}
14771 
14772 			dest->partition = pos_info->partition_number;
14773 
14774 		} else {
14775 			dest->pmode = invalid;
14776 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14777 			    "Tape drive reported block position as unknown\n");
14778 		}
14779 		break;
14780 	}
14781 
14782 	case LONG_POS: /* Long data format */
14783 	{
14784 		uint64_t value;
14785 		tape_position_long_t *long_pos_info =
14786 		    (tape_position_long_t *)responce;
14787 
14788 		/* If reserved fields are non zero don't use the data */
14789 		if ((long_pos_info->reserved0) ||
14790 		    (long_pos_info->reserved1) ||
14791 		    (long_pos_info->reserved2)) {
14792 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14793 			    "Invalid Read Long Position Data returned\n");
14794 			rval = ENOTTY;
14795 			break;
14796 		}
14797 
14798 		/* Is position Valid */
14799 		if (long_pos_info->blk_posi_unkwn == 0) {
14800 			uint32_t part;
14801 
14802 			value = long_pos_info->block_number;
14803 			FIX_ENDIAN64(&value);
14804 
14805 			/*
14806 			 * If it says we are at the begining of partition
14807 			 * the block value better be 0.
14808 			 */
14809 			if ((long_pos_info->begin_of_part == 1) &&
14810 			    (value != 0)) {
14811 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14812 				    "LONG_POS returned begin of partition but"
14813 				    " block number was 0x%"PRIx64"\n", value);
14814 				rval = ENOTTY;
14815 				break;
14816 			}
14817 			/*
14818 			 * Can't be at the start and the end of the partition
14819 			 * at the same time if the partition is larger the 0.
14820 			 */
14821 			if (long_pos_info->begin_of_part &&
14822 			    long_pos_info->end_of_part) {
14823 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14824 				    "LONG_POS returned begin and end of"
14825 				    " partition\n");
14826 				rval = ENOTTY;
14827 				break;
14828 			}
14829 
14830 			/*
14831 			 * If the logical block number is not what we expected.
14832 			 */
14833 			if (dest->lgclblkno != value) {
14834 				if (flag)
14835 					flag++;
14836 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14837 				    "LONG_POS current logical 0x%"PRIx64
14838 				    " read 0x%"PRIx64"\n",
14839 				    dest->lgclblkno, value);
14840 			}
14841 			dest->lgclblkno = value;
14842 
14843 			/*
14844 			 * If the begining of partition is true and the
14845 			 * block number is zero we will beleive that it is
14846 			 * rewound. Promote the pmode to legacy.
14847 			 */
14848 			if ((long_pos_info->begin_of_part == 1) &&
14849 			    (long_pos_info->block_number == 0)) {
14850 				dest->blkno = 0;
14851 				dest->fileno = 0;
14852 				if (dest->pmode != legacy)
14853 					dest->pmode = legacy;
14854 			/*
14855 			 * otherwise if the pmode was invalid,
14856 			 * promote it to logical.
14857 			 */
14858 			} else if (dest->pmode == invalid) {
14859 				dest->pmode = logical;
14860 			}
14861 
14862 			part = long_pos_info->partition;
14863 			FIX_ENDIAN32(&part);
14864 			if (dest->partition != part) {
14865 				if (flag)
14866 					flag++;
14867 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14868 				    "LONG_POS current partition %d"
14869 				    " read %d\n", dest->partition, part);
14870 			}
14871 			dest->partition = part;
14872 		} else {
14873 			/*
14874 			 * If the drive doesn't know location,
14875 			 * we don't either.
14876 			 */
14877 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14878 			    "Tape drive reported block position as unknown\n");
14879 			dest->pmode = invalid;
14880 		}
14881 
14882 		/* Is file position valid */
14883 		if (long_pos_info->mrk_posi_unkwn == 0) {
14884 			value = long_pos_info->file_number;
14885 			FIX_ENDIAN64(&value);
14886 			/*
14887 			 * If it says we are at the begining of partition
14888 			 * the block value better be 0.
14889 			 */
14890 			if ((long_pos_info->begin_of_part == 1) &&
14891 			    (value != 0)) {
14892 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14893 				    "LONG_POS returned begin of partition but"
14894 				    " block number was 0x%"PRIx64"\n", value);
14895 				rval = ENOTTY;
14896 				break;
14897 			}
14898 			if (((dest->pmode == legacy) ||
14899 			    (dest->pmode == logical)) &&
14900 			    (dest->fileno != value)) {
14901 				if (flag)
14902 					flag++;
14903 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14904 				    "LONG_POS fileno 0x%"PRIx64
14905 				    " not un_pos %x\n", value,
14906 				    dest->fileno);
14907 			} else if (dest->pmode == invalid) {
14908 				dest->pmode = logical;
14909 			}
14910 			dest->fileno = (int32_t)value;
14911 		}
14912 
14913 		if (dest->pmode != invalid && long_pos_info->end_of_part) {
14914 			dest->eof = ST_EOT;
14915 		}
14916 
14917 		break;
14918 	}
14919 
14920 	case EXT_POS: /* Extended data format */
14921 	{
14922 		uint64_t value;
14923 		uint16_t len;
14924 		tape_position_ext_t *ext_pos_info =
14925 		    (tape_position_ext_t *)responce;
14926 
14927 		/* Make sure that there is enough data there */
14928 		if (data_sz < 16) {
14929 			break;
14930 		}
14931 
14932 		/* If reserved fields are non zero don't use the data */
14933 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
14934 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14935 			    "EXT_POS reserved fields not zero\n");
14936 			rval = ENOTTY;
14937 			break;
14938 		}
14939 
14940 		/*
14941 		 * In the unlikely event of overflowing 64 bits of position.
14942 		 */
14943 		if (ext_pos_info->posi_err != 0) {
14944 			rval = ERANGE;
14945 			break;
14946 		}
14947 
14948 		len = ext_pos_info->parameter_len;
14949 		FIX_ENDIAN16(&len);
14950 
14951 		if (len != 0x1c) {
14952 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14953 			    "EXT_POS parameter_len should be 0x1c was 0x%x\n",
14954 			    len);
14955 			rval = ENOTTY;
14956 			break;
14957 		}
14958 
14959 		/* Is block position information valid */
14960 		if (ext_pos_info->blk_posi_unkwn == 0) {
14961 
14962 			value = ext_pos_info->host_block;
14963 			FIX_ENDIAN64(&value);
14964 			if ((ext_pos_info->begin_of_part == 1) &&
14965 			    (value != 0)) {
14966 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14967 				    "EXT_POS returned begining of partition but"
14968 				    " the host block was 0x%"PRIx64"\n", value);
14969 				rval = ENOTTY;
14970 				break;
14971 			}
14972 
14973 			if (dest->lgclblkno != value) {
14974 				if (flag)
14975 					flag++;
14976 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14977 				    "EXT_POS current logical 0x%"PRIx64
14978 				    " read 0x%"PRIx64"\n",
14979 				    dest->lgclblkno, value);
14980 			}
14981 			dest->lgclblkno = value;
14982 
14983 			/*
14984 			 * If the begining of partition is true and the
14985 			 * block number is zero we will beleive that it is
14986 			 * rewound. Promote the pmode to legacy.
14987 			 */
14988 			if ((ext_pos_info->begin_of_part == 1) &&
14989 			    (ext_pos_info->host_block == 0)) {
14990 				dest->blkno = 0;
14991 				dest->fileno = 0;
14992 				if (dest->pmode != legacy) {
14993 					dest->pmode = legacy;
14994 				}
14995 			/*
14996 			 * otherwise if the pmode was invalid,
14997 			 * promote it to logical.
14998 			 */
14999 			} else if (dest->pmode == invalid) {
15000 				dest->pmode = logical;
15001 			}
15002 
15003 			if (dest->partition != ext_pos_info->partition) {
15004 				if (flag)
15005 					flag++;
15006 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15007 				    "EXT_POS current partition %d read %d\n",
15008 				    dest->partition,
15009 				    ext_pos_info->partition);
15010 			}
15011 			dest->partition = ext_pos_info->partition;
15012 
15013 		} else {
15014 			dest->pmode = invalid;
15015 		}
15016 		break;
15017 	}
15018 
15019 	default:
15020 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15021 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
15022 		rval = EIO;
15023 	}
15024 
15025 	if ((flag > 1) && (rval == 0) && (org.pmode != invalid)) {
15026 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
15027 		    "position read in", &org);
15028 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
15029 		    "position read out", dest);
15030 	}
15031 
15032 	return (rval);
15033 }
15034 
15035 static int
15036 st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos,
15037     uint64_t lblk, uchar_t partition)
15038 {
15039 	int rval;
15040 	char cdb[CDB_GROUP4];
15041 	struct uscsi_cmd *cmd;
15042 	struct scsi_extended_sense sense;
15043 	bufunc_t bf = (ubf == st_uscsi_cmd) ? st_cmd : st_rcmd;
15044 
15045 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
15046 	/*
15047 	 * Not sure what to do when doing recovery and not wanting
15048 	 * to update un_pos
15049 	 */
15050 
15051 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
15052 
15053 	if (lblk <= INT32_MAX) {
15054 		cmd->uscsi_cdblen = CDB_GROUP1;
15055 		cdb[0] = SCMD_LOCATE;
15056 		cdb[1] = pos->partition == partition ? 0 : 2;
15057 		cdb[2] = 0;
15058 		cdb[3] = (char)(lblk >> 24);
15059 		cdb[4] = (char)(lblk >> 16);
15060 		cdb[5] = (char)(lblk >> 8);
15061 		cdb[6] = (char)(lblk);
15062 		cdb[7] = 0;
15063 		cdb[8] = partition;
15064 		cdb[9] = 0;
15065 	} else {
15066 		/*
15067 		 * If the drive doesn't give a 64 bit read position data
15068 		 * it is unlikely it will accept 64 bit locates.
15069 		 */
15070 		if (un->un_read_pos_type != LONG_POS) {
15071 			kmem_free(cmd, sizeof (struct uscsi_cmd));
15072 			return (ERANGE);
15073 		}
15074 		cmd->uscsi_cdblen = CDB_GROUP4;
15075 		cdb[0] = (char)SCMD_LOCATE_G4;
15076 		cdb[1] = pos->partition == partition ? 0 : 2;
15077 		cdb[2] = 0;
15078 		cdb[3] = partition;
15079 		cdb[4] = (char)(lblk >> 56);
15080 		cdb[5] = (char)(lblk >> 48);
15081 		cdb[6] = (char)(lblk >> 40);
15082 		cdb[7] = (char)(lblk >> 32);
15083 		cdb[8] = (char)(lblk >> 24);
15084 		cdb[9] = (char)(lblk >> 16);
15085 		cdb[10] = (char)(lblk >> 8);
15086 		cdb[11] = (char)(lblk);
15087 		cdb[12] = 0;
15088 		cdb[13] = 0;
15089 		cdb[14] = 0;
15090 		cdb[15] = 0;
15091 	}
15092 
15093 
15094 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
15095 	cmd->uscsi_rqbuf = (caddr_t)&sense;
15096 	cmd->uscsi_rqlen = sizeof (sense);
15097 	cmd->uscsi_timeout = un->un_dp->space_timeout;
15098 	cmd->uscsi_cdb = cdb;
15099 
15100 	rval = ubf(un, cmd, FKIOCTL);
15101 
15102 	pos->pmode = logical;
15103 	pos->eof = ST_NO_EOF;
15104 
15105 	if (lblk > INT32_MAX) {
15106 		/*
15107 		 * XXX This is a work around till we handle Descriptor format
15108 		 * sense data. Since we are sending a command where the standard
15109 		 * sense data can not correctly represent a correct residual in
15110 		 * 4 bytes.
15111 		 */
15112 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
15113 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15114 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
15115 			/* Doesn't like big locate command */
15116 			un->un_status = 0;
15117 			rval = ERANGE;
15118 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
15119 			/* Aborted big locate command */
15120 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15121 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
15122 			    rval);
15123 			un->un_status = 0;
15124 			rval = EIO;
15125 		} else if (st_update_block_pos(un, bf, 1)) {
15126 			/* read position failed */
15127 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15128 			    "Big LOCATE and read pos: rval = %d\n", rval);
15129 			rval = EIO;
15130 		} else if (lblk > un->un_pos.lgclblkno) {
15131 			/* read position worked but position was not expected */
15132 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15133 			    "Big LOCATE and recover read less then desired 0x%"
15134 			    PRIx64"\n", un->un_pos.lgclblkno);
15135 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
15136 			un->un_status = KEY_BLANK_CHECK;
15137 			rval = ESPIPE;
15138 		} else if (lblk == un->un_pos.lgclblkno) {
15139 			/* read position was what was expected */
15140 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15141 			    "Big LOCATE and recover seems to have worked\n");
15142 			un->un_err_resid = 0;
15143 			rval = 0;
15144 		} else {
15145 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15146 			    "BIGLOCATE end up going backwards");
15147 			un->un_err_resid = lblk;
15148 			rval = EIO;
15149 		}
15150 
15151 	} else if (rval == 0) {
15152 		/* Worked as requested */
15153 		pos->lgclblkno = lblk;
15154 
15155 	} else if (((cmd->uscsi_status & ST_STATUS_MASK) == STATUS_CHECK) &&
15156 	    (cmd->uscsi_resid != 0)) {
15157 		/* Got part way there but wasn't enough blocks on tape */
15158 		pos->lgclblkno = lblk - cmd->uscsi_resid;
15159 		un->un_err_resid = cmd->uscsi_resid;
15160 		un->un_status = KEY_BLANK_CHECK;
15161 		rval = ESPIPE;
15162 
15163 	} else if (st_update_block_pos(un, bf, 1) == 0) {
15164 		/* Got part way there but drive didn't tell what we missed by */
15165 		un->un_err_resid = lblk - pos->lgclblkno;
15166 		un->un_status = KEY_BLANK_CHECK;
15167 		rval = ESPIPE;
15168 
15169 	} else {
15170 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15171 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
15172 		    rval, cmd->uscsi_status);
15173 		un->un_err_resid = lblk;
15174 		un->un_status = KEY_ILLEGAL_REQUEST;
15175 		pos->pmode = invalid;
15176 		rval = EIO;
15177 	}
15178 
15179 	kmem_free(cmd, sizeof (struct uscsi_cmd));
15180 
15181 	return (rval);
15182 }
15183 
15184 static int
15185 st_mtfsf_ioctl(struct scsi_tape *un, int64_t files)
15186 {
15187 	int rval;
15188 
15189 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
15190 
15191 
15192 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15193 	    "st_mtfsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15194 #if 0
15195 	if ((IN_EOF(un->un_pos)) && (files == 1)) {
15196 		un->un_pos.fileno++;
15197 		un->un_pos.blkno = 0;
15198 		return (0);
15199 	}
15200 #endif
15201 	/* pmode == invalid already handled */
15202 	if (un->un_pos.pmode == legacy) {
15203 		/*
15204 		 * forward space over filemark
15205 		 *
15206 		 * For ASF we allow a count of 0 on fsf which means
15207 		 * we just want to go to beginning of current file.
15208 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
15209 		 * Allow stepping over double fmk with reel
15210 		 */
15211 		if ((un->un_pos.eof >= ST_EOT) &&
15212 		    (files > 0) &&
15213 		    ((un->un_dp->options & ST_REEL) == 0)) {
15214 			/* we're at EOM */
15215 			un->un_err_resid = files;
15216 			un->un_status = KEY_BLANK_CHECK;
15217 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15218 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
15219 			return (EIO);
15220 		}
15221 
15222 		/*
15223 		 * physical tape position may not be what we've been
15224 		 * telling the user; adjust the request accordingly
15225 		 */
15226 		if (IN_EOF(un->un_pos)) {
15227 			un->un_pos.fileno++;
15228 			un->un_pos.blkno = 0;
15229 			/*
15230 			 * For positive direction case, we're now covered.
15231 			 * For zero or negative direction, we're covered
15232 			 * (almost)
15233 			 */
15234 			files--;
15235 		}
15236 
15237 	}
15238 
15239 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15240 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15241 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
15242 		return (EIO);
15243 	}
15244 
15245 
15246 	/*
15247 	 * Forward space file marks.
15248 	 * We leave ourselves at block zero
15249 	 * of the target file number.
15250 	 */
15251 	if (files < 0) {
15252 		rval = st_backward_space_files(un, -files, 0);
15253 	} else {
15254 		rval = st_forward_space_files(un, files);
15255 	}
15256 
15257 	return (rval);
15258 }
15259 
15260 static int
15261 st_forward_space_files(struct scsi_tape *un, int64_t count)
15262 {
15263 	int rval;
15264 
15265 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
15266 
15267 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15268 	    "fspace: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15269 
15270 	ASSERT(count >= 0);
15271 	ASSERT(un->un_pos.pmode != invalid);
15272 
15273 	/*
15274 	 * A space with a count of zero means take me to the start of file.
15275 	 */
15276 	if (count == 0) {
15277 
15278 		/* Hay look were already there */
15279 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0) {
15280 			un->un_err_resid = 0;
15281 			COPY_POS(&un->un_err_pos, &un->un_pos);
15282 			return (0);
15283 		}
15284 
15285 		/*
15286 		 * Well we are in the first file.
15287 		 * A rewind will get to the start.
15288 		 */
15289 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
15290 			rval = st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
15291 
15292 		/*
15293 		 * Can we backspace to get there?
15294 		 * This should work in logical mode.
15295 		 */
15296 		} else if (un->un_dp->options & ST_BSF) {
15297 			rval = st_space_to_begining_of_file(un);
15298 
15299 		/*
15300 		 * Can't back space but current file number is known,
15301 		 * So rewind and space from the begining of the partition.
15302 		 */
15303 		} else if (un->un_pos.pmode == legacy) {
15304 			rval = st_scenic_route_to_begining_of_file(un,
15305 			    un->un_pos.fileno);
15306 
15307 		/*
15308 		 * pmode is logical and ST_BSF is not set.
15309 		 * The LONG_POS read position contains the fileno.
15310 		 * If the read position works, rewind and space.
15311 		 */
15312 		} else if (un->un_read_pos_type == LONG_POS) {
15313 			rval = st_cmd(un, SCMD_READ_POSITION, 0, SYNC_CMD);
15314 			if (rval) {
15315 				/*
15316 				 * We didn't get the file position from the
15317 				 * read position command.
15318 				 * We are going to trust the drive to backspace
15319 				 * and then position after the filemark.
15320 				 */
15321 				rval = st_space_to_begining_of_file(un);
15322 			}
15323 			rval = st_interpret_read_pos(un, &un->un_pos, LONG_POS,
15324 			    32, (caddr_t)un->un_read_pos_data, 0);
15325 			if ((rval) && (un->un_pos.pmode == invalid)) {
15326 				rval = st_space_to_begining_of_file(un);
15327 			} else {
15328 				rval = st_scenic_route_to_begining_of_file(un,
15329 				    un->un_pos.fileno);
15330 			}
15331 		} else {
15332 			rval = EIO;
15333 		}
15334 		/*
15335 		 * If something didn't work we are lost
15336 		 */
15337 		if (rval != 0) {
15338 			un->un_pos.pmode = invalid;
15339 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15340 			    "st_mtioctop : EIO : fspace pmode invalid");
15341 
15342 			rval = EIO;
15343 		}
15344 
15345 	} else {
15346 		rval = st_space_fmks(un, count);
15347 	}
15348 
15349 	if (rval != EIO && count < 0) {
15350 		/*
15351 		 * we came here with a count < 0; we now need
15352 		 * to skip back to end up before the filemark
15353 		 */
15354 		rval = st_backward_space_files(un, 1, 1);
15355 	}
15356 
15357 	return (rval);
15358 }
15359 
15360 static int
15361 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
15362 {
15363 	int rval;
15364 
15365 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
15366 
15367 	if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15368 		rval = EIO;
15369 	} else if (st_cmd(un, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
15370 		rval = EIO;
15371 	}
15372 
15373 	return (rval);
15374 }
15375 
15376 static int
15377 st_space_to_begining_of_file(struct scsi_tape *un)
15378 {
15379 	int rval;
15380 
15381 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
15382 
15383 	/*
15384 	 * Back space of the file at the begining of the file.
15385 	 */
15386 	rval = st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
15387 	if (rval) {
15388 		rval = EIO;
15389 		return (rval);
15390 	}
15391 
15392 	/*
15393 	 * Other interesting answers might be crashed BOT which isn't bad.
15394 	 */
15395 	if (un->un_status == SUN_KEY_BOT) {
15396 		return (rval);
15397 	}
15398 
15399 	un->un_running.pmode = invalid;
15400 
15401 	/*
15402 	 * Now we are on the BOP side of the filemark. Forward space to
15403 	 * the EOM side and we are at the begining of the file.
15404 	 */
15405 	rval = st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD);
15406 	if (rval) {
15407 		rval = EIO;
15408 	}
15409 
15410 	return (rval);
15411 }
15412 
15413 static int
15414 st_mtfsr_ioctl(struct scsi_tape *un, int64_t count)
15415 {
15416 
15417 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
15418 
15419 	/*
15420 	 * forward space to inter-record gap
15421 	 *
15422 	 */
15423 
15424 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15425 	    "st_ioctl_fsr: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15426 
15427 	if (un->un_pos.pmode == legacy) {
15428 		/*
15429 		 * If were are at end of tape and count is forward.
15430 		 * Return blank check.
15431 		 */
15432 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
15433 			/* we're at EOM */
15434 			un->un_err_resid = count;
15435 			un->un_status = KEY_BLANK_CHECK;
15436 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15437 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
15438 			return (EIO);
15439 		}
15440 
15441 		/*
15442 		 * If count is zero there is nothing to do.
15443 		 */
15444 		if (count == 0) {
15445 			un->un_err_pos.fileno = un->un_pos.fileno;
15446 			un->un_err_pos.blkno = un->un_pos.blkno;
15447 			un->un_err_resid = 0;
15448 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15449 				un->un_status = SUN_KEY_EOF;
15450 			}
15451 			return (0);
15452 		}
15453 
15454 		/*
15455 		 * physical tape position may not be what we've been
15456 		 * telling the user; adjust the position accordingly
15457 		 */
15458 		if (IN_EOF(un->un_pos)) {
15459 			daddr_t blkno = un->un_pos.blkno;
15460 			int fileno = un->un_pos.fileno;
15461 
15462 			optype lastop = un->un_lastop;
15463 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)
15464 			    == -1) {
15465 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15466 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
15467 				return (EIO);
15468 			}
15469 
15470 			un->un_pos.blkno = blkno;
15471 			un->un_pos.fileno = fileno;
15472 			un->un_lastop = lastop;
15473 		}
15474 	}
15475 
15476 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15477 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15478 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
15479 		return (EIO);
15480 	}
15481 
15482 	return (st_space_records(un, count));
15483 }
15484 
15485 static int
15486 st_space_records(struct scsi_tape *un, int64_t count)
15487 {
15488 	int64_t dblk;
15489 	int rval = 0;
15490 
15491 	ST_FUNC(ST_DEVINFO, st_space_records);
15492 
15493 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15494 	    "st_space_records: count=%"PRIx64", eof=%x\n",
15495 	    count, un->un_pos.eof);
15496 
15497 	if (un->un_pos.pmode == logical) {
15498 		rval = st_cmd(un, SCMD_SPACE, Blk(count), SYNC_CMD);
15499 		if (rval != 0) {
15500 			rval = EIO;
15501 		}
15502 		return (rval);
15503 	}
15504 
15505 	dblk = count + un->un_pos.blkno;
15506 
15507 	/* Already there */
15508 	if (dblk == un->un_pos.blkno) {
15509 		un->un_err_resid = 0;
15510 		COPY_POS(&un->un_err_pos, &un->un_pos);
15511 		return (0);
15512 	}
15513 
15514 	/*
15515 	 * If the destination block is forward
15516 	 * or the drive will backspace records.
15517 	 */
15518 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
15519 		/*
15520 		 * If we're spacing forward, or the device can
15521 		 * backspace records, we can just use the SPACE
15522 		 * command.
15523 		 */
15524 		dblk -= un->un_pos.blkno;
15525 		if (st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15526 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15527 			    "st_space_records:EIO:space_records can't spc");
15528 			rval = EIO;
15529 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
15530 			/*
15531 			 * check if we hit BOT/EOT
15532 			 */
15533 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
15534 				un->un_status = SUN_KEY_BOT;
15535 				un->un_pos.eof = ST_NO_EOF;
15536 			} else if (dblk < 0 &&
15537 			    un->un_pos.eof == ST_EOF_PENDING) {
15538 				int residue = un->un_err_resid;
15539 				/*
15540 				 * we skipped over a filemark
15541 				 * and need to go forward again
15542 				 */
15543 				if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
15544 					ST_DEBUG2(ST_DEVINFO, st_label,
15545 					    SCSI_DEBUG, "st_space_records: EIO"
15546 					    " : can't space #2");
15547 					rval = EIO;
15548 				}
15549 				un->un_err_resid = residue;
15550 			}
15551 			if (rval == 0) {
15552 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15553 				    "st_space_records: EIO : space_rec rval"
15554 				    " == 0");
15555 				rval = EIO;
15556 			}
15557 		}
15558 	} else {
15559 		/*
15560 		 * else we rewind, space forward across filemarks to
15561 		 * the desired file, and then space records to the
15562 		 * desired block.
15563 		 */
15564 
15565 		int dfile = un->un_pos.fileno;	/* save current file */
15566 
15567 		if (dblk < 0) {
15568 			/*
15569 			 * Wups - we're backing up over a filemark
15570 			 */
15571 			if (un->un_pos.blkno != 0 &&
15572 			    (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15573 			    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD))) {
15574 				un->un_pos.pmode = invalid;
15575 			}
15576 			un->un_err_resid = -dblk;
15577 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
15578 				un->un_status = SUN_KEY_BOT;
15579 				un->un_pos.eof = ST_NO_EOF;
15580 			} else if (un->un_pos.fileno > 0) {
15581 				un->un_status = SUN_KEY_EOF;
15582 				un->un_pos.eof = ST_NO_EOF;
15583 			}
15584 			COPY_POS(&un->un_err_pos, &un->un_pos);
15585 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15586 			    "st_space_records:EIO:space_records : dblk < 0");
15587 			rval = EIO;
15588 		} else if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15589 		    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
15590 		    st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15591 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15592 			    "st_space_records: EIO :space_records : rewind "
15593 			    "and space failed");
15594 			un->un_pos.pmode = invalid;
15595 			rval = EIO;
15596 		}
15597 	}
15598 
15599 	return (rval);
15600 }
15601 
15602 static int
15603 st_mtbsf_ioctl(struct scsi_tape *un, int64_t files)
15604 {
15605 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
15606 
15607 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15608 	    "st_mtbsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15609 	/*
15610 	 * backward space of file filemark (1/2" and 8mm)
15611 	 * tape position will end on the beginning of tape side
15612 	 * of the desired file mark
15613 	 */
15614 	if ((un->un_dp->options & ST_BSF) == 0) {
15615 		return (ENOTTY);
15616 	}
15617 
15618 	if (un->un_pos.pmode == legacy) {
15619 
15620 		/*
15621 		 * If a negative count (which implies a forward space op)
15622 		 * is specified, and we're at logical or physical eot,
15623 		 * bounce the request.
15624 		 */
15625 
15626 		if (un->un_pos.eof >= ST_EOT && files < 0) {
15627 			un->un_err_resid = files;
15628 			un->un_status = SUN_KEY_EOT;
15629 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15630 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
15631 			return (EIO);
15632 		}
15633 		/*
15634 		 * physical tape position may not be what we've been
15635 		 * telling the user; adjust the request accordingly
15636 		 */
15637 		if (IN_EOF(un->un_pos)) {
15638 			un->un_pos.fileno++;
15639 			un->un_pos.blkno = 0;
15640 			files++;
15641 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15642 			    "st_mtbsf_ioctl in eof: count=%"PRIx64", op=%x\n",
15643 			    files, MTBSF);
15644 
15645 		}
15646 	}
15647 
15648 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15649 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15650 		    "st_ioctl : EIO : MTBSF : check den wfm");
15651 		return (EIO);
15652 	}
15653 
15654 	if (files <= 0) {
15655 		/*
15656 		 * for a negative count, we need to step forward
15657 		 * first and then step back again
15658 		 */
15659 		files = -files + 1;
15660 		return (st_forward_space_files(un, files));
15661 	}
15662 	return (st_backward_space_files(un, files, 1));
15663 }
15664 
15665 static int
15666 st_backward_space_files(struct scsi_tape *un, int64_t count, int infront)
15667 {
15668 	int64_t end_fileno;
15669 	int64_t skip_cnt;
15670 	int rval = 0;
15671 
15672 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
15673 
15674 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15675 	    "st_backward_space_files: count=%"PRIx64" eof=%x\n",
15676 	    count, un->un_pos.eof);
15677 	/*
15678 	 * Backspace files (MTNBSF): infront == 0
15679 	 *
15680 	 *	For tapes that can backspace, backspace
15681 	 *	count+1 filemarks and then run forward over
15682 	 *	a filemark
15683 	 *
15684 	 *	For tapes that can't backspace,
15685 	 *		calculate desired filenumber
15686 	 *		(un->un_pos.fileno - count), rewind,
15687 	 *		and then space forward this amount
15688 	 *
15689 	 * Backspace filemarks (MTBSF) infront == 1
15690 	 *
15691 	 *	For tapes that can backspace, backspace count
15692 	 *	filemarks
15693 	 *
15694 	 *	For tapes that can't backspace, calculate
15695 	 *	desired filenumber (un->un_pos.fileno - count),
15696 	 *	add 1, rewind, space forward this amount,
15697 	 *	and mark state as ST_EOF_PENDING appropriately.
15698 	 */
15699 
15700 	if (un->un_pos.pmode == logical) {
15701 
15702 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15703 		    "st_backward_space_files: mt_op=%x count=%"PRIx64
15704 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
15705 		    un->un_pos.lgclblkno);
15706 
15707 
15708 		/* In case a drive that won't back space gets in logical mode */
15709 		if ((un->un_dp->options & ST_BSF) == 0) {
15710 			rval = EIO;
15711 			return (rval);
15712 		}
15713 		if ((infront == 1) &&
15714 		    (st_cmd(un, SCMD_SPACE, Fmk(-count), SYNC_CMD))) {
15715 			rval = EIO;
15716 			return (rval);
15717 		} else if ((infront == 0) &&
15718 		    (st_cmd(un, SCMD_SPACE, Fmk((-count)-1), SYNC_CMD)) &&
15719 		    (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
15720 			rval = EIO;
15721 			return (rval);
15722 		}
15723 		return (rval);
15724 	}
15725 
15726 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15727 	    "st_backward_space_files: mt_op=%x count=%"PRIx64
15728 	    "fileno=%x blkno=%x\n",
15729 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
15730 
15731 
15732 
15733 	/*
15734 	 * Handle the simple case of BOT
15735 	 * playing a role in these cmds.
15736 	 * We do this by calculating the
15737 	 * ending file number. If the ending
15738 	 * file is < BOT, rewind and set an
15739 	 * error and mark resid appropriately.
15740 	 * If we're backspacing a file (not a
15741 	 * filemark) and the target file is
15742 	 * the first file on the tape, just
15743 	 * rewind.
15744 	 */
15745 
15746 	/* figure expected destination of this SPACE command */
15747 	end_fileno = un->un_pos.fileno - count;
15748 
15749 	/*
15750 	 * Would the end effect of this SPACE be the same as rewinding?
15751 	 * If so just rewind instead.
15752 	 */
15753 	if ((infront != 0) && (end_fileno < 0) ||
15754 	    (infront == 0) && (end_fileno <= 0)) {
15755 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15756 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15757 			    "st_backward_space_files: EIO : "
15758 			    "rewind in lou of BSF failed\n");
15759 			rval = EIO;
15760 		}
15761 		if (end_fileno < 0) {
15762 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15763 			    "st_backward_space_files: EIO : "
15764 			    "back space file greater then fileno\n");
15765 			rval = EIO;
15766 			un->un_err_resid = -end_fileno;
15767 			un->un_status = SUN_KEY_BOT;
15768 		}
15769 		return (rval);
15770 	}
15771 
15772 	if (un->un_dp->options & ST_BSF) {
15773 		skip_cnt = 1 - infront;
15774 		/*
15775 		 * If we are going to end up at the beginning
15776 		 * of the file, we have to space one extra file
15777 		 * first, and then space forward later.
15778 		 */
15779 		end_fileno = -(count + skip_cnt);
15780 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15781 		    "skip_cnt=%"PRIx64", tmp=%"PRIx64"\n",
15782 		    skip_cnt, end_fileno);
15783 		if (st_cmd(un, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
15784 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15785 			    "st_backward_space_files:EIO:back space fm failed");
15786 			rval = EIO;
15787 		}
15788 	} else {
15789 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15790 			rval = EIO;
15791 		} else {
15792 			skip_cnt = end_fileno + infront;
15793 		}
15794 	}
15795 
15796 	/*
15797 	 * If we have to space forward, do so...
15798 	 */
15799 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15800 	    "space forward skip_cnt=%"PRIx64", rval=%x\n", skip_cnt, rval);
15801 
15802 	if (rval == 0 && skip_cnt) {
15803 		if (st_cmd(un, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
15804 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15805 			    "st_backward_space_files:EIO:space fm skip count");
15806 			rval = EIO;
15807 		} else if (infront) {
15808 			/*
15809 			 * If we had to space forward, and we're
15810 			 * not a tape that can backspace, mark state
15811 			 * as if we'd just seen a filemark during a
15812 			 * a read.
15813 			 */
15814 			if ((un->un_dp->options & ST_BSF) == 0) {
15815 				un->un_pos.eof = ST_EOF_PENDING;
15816 				un->un_pos.fileno -= 1;
15817 				un->un_pos.blkno = LASTBLK;
15818 				un->un_running.pmode = invalid;
15819 			}
15820 		}
15821 	}
15822 
15823 	if (rval != 0) {
15824 		un->un_pos.pmode = invalid;
15825 	}
15826 
15827 	return (rval);
15828 }
15829 
15830 static int
15831 st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count)
15832 {
15833 	int rval;
15834 
15835 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
15836 
15837 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15838 	    "nbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15839 
15840 	if (un->un_pos.pmode == legacy) {
15841 		/*
15842 		 * backward space file to beginning of file
15843 		 *
15844 		 * If a negative count (which implies a forward space op)
15845 		 * is specified, and we're at logical or physical eot,
15846 		 * bounce the request.
15847 		 */
15848 
15849 		if (un->un_pos.eof >= ST_EOT && count < 0) {
15850 			un->un_err_resid = count;
15851 			un->un_status = SUN_KEY_EOT;
15852 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15853 			    "st_ioctl : EIO : > EOT and count < 0");
15854 			return (EIO);
15855 		}
15856 		/*
15857 		 * physical tape position may not be what we've been
15858 		 * telling the user; adjust the request accordingly
15859 		 */
15860 		if (IN_EOF(un->un_pos)) {
15861 			un->un_pos.fileno++;
15862 			un->un_pos.blkno = 0;
15863 			count++;
15864 		}
15865 	}
15866 
15867 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15868 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15869 		    "st_ioctl : EIO : MTNBSF check den and wfm");
15870 		return (EIO);
15871 	}
15872 
15873 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15874 	    "mtnbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15875 
15876 	if (count <= 0) {
15877 		rval = st_forward_space_files(un, -count);
15878 	} else {
15879 		rval = st_backward_space_files(un, count, 0);
15880 	}
15881 	return (rval);
15882 }
15883 
15884 static int
15885 st_mtbsr_ioctl(struct scsi_tape *un, int64_t num)
15886 {
15887 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
15888 
15889 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15890 	    "bsr: count=%"PRIx64", eof=%x\n", num, un->un_pos.eof);
15891 
15892 	if (un->un_pos.pmode == legacy) {
15893 		/*
15894 		 * backward space into inter-record gap
15895 		 *
15896 		 * If a negative count (which implies a forward space op)
15897 		 * is specified, and we're at logical or physical eot,
15898 		 * bounce the request.
15899 		 */
15900 		if (un->un_pos.eof >= ST_EOT && num < 0) {
15901 			un->un_err_resid = num;
15902 			un->un_status = SUN_KEY_EOT;
15903 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15904 			    "st_ioctl : EIO : MTBSR > EOT");
15905 			return (EIO);
15906 		}
15907 
15908 		if (num == 0) {
15909 			COPY_POS(&un->un_err_pos, &un->un_pos);
15910 			un->un_err_resid = 0;
15911 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15912 				un->un_status = SUN_KEY_EOF;
15913 			}
15914 			return (0);
15915 		}
15916 
15917 		/*
15918 		 * physical tape position may not be what we've been
15919 		 * telling the user; adjust the position accordingly.
15920 		 * bsr can not skip filemarks and continue to skip records
15921 		 * therefore if we are logically before the filemark but
15922 		 * physically at the EOT side of the filemark, we need to step
15923 		 * back; this allows fsr N where N > number of blocks in file
15924 		 * followed by bsr 1 to position at the beginning of last block
15925 		 */
15926 		if (IN_EOF(un->un_pos)) {
15927 			tapepos_t save;
15928 			optype lastop = un->un_lastop;
15929 
15930 			COPY_POS(&save, &un->un_pos);
15931 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD) == -1) {
15932 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15933 				    "st_mtbsr_ioctl: EIO : MTBSR can't space");
15934 				return (EIO);
15935 			}
15936 
15937 			COPY_POS(&un->un_pos, &save);
15938 			un->un_lastop = lastop;
15939 		}
15940 	}
15941 
15942 	un->un_pos.eof = ST_NO_EOF;
15943 
15944 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15945 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15946 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
15947 		return (EIO);
15948 	}
15949 
15950 	num = -num;
15951 	return (st_space_records(un, num));
15952 }
15953 
15954 static int
15955 st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt)
15956 {
15957 	int rval;
15958 
15959 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
15960 
15961 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
15962 	if (rval == 0) {
15963 		un->un_pos.pmode = logical;
15964 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15965 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15966 		/*
15967 		 * Drive says invalid field in cdb.
15968 		 * Doesn't like space multiple. Position isn't lost.
15969 		 */
15970 		un->un_err_resid = cnt;
15971 		un->un_status = 0;
15972 		rval = ENOTTY;
15973 	} else {
15974 		un->un_err_resid = cnt;
15975 		un->un_pos.pmode = invalid;
15976 	}
15977 	return (rval);
15978 }
15979 
15980 static int
15981 st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt)
15982 {
15983 	int rval;
15984 
15985 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
15986 
15987 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
15988 	if (rval == 0) {
15989 		un->un_pos.pmode = logical;
15990 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15991 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15992 		/*
15993 		 * Drive says invalid field in cdb.
15994 		 * Doesn't like space multiple. Position isn't lost.
15995 		 */
15996 		un->un_err_resid = cnt;
15997 		un->un_status = 0;
15998 		rval = ENOTTY;
15999 	} else {
16000 		un->un_err_resid = cnt;
16001 		un->un_pos.pmode = invalid;
16002 	}
16003 	return (rval);
16004 }
16005 
16006 #ifdef	__x86
16007 
16008 /*
16009  * release contig_mem and wake up waiting thread, if any
16010  */
16011 static void
16012 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
16013 {
16014 	mutex_enter(ST_MUTEX);
16015 
16016 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
16017 
16018 	cp->cm_next = un->un_contig_mem;
16019 	un->un_contig_mem = cp;
16020 	un->un_contig_mem_available_num++;
16021 	cv_broadcast(&un->un_contig_mem_cv);
16022 
16023 	mutex_exit(ST_MUTEX);
16024 }
16025 
16026 /*
16027  * St_get_contig_mem will return a contig_mem if there is one available
16028  * in current system. Otherwise, it will try to alloc one, if the total
16029  * number of contig_mem is within st_max_contig_mem_num.
16030  * It will sleep, if allowed by caller or return NULL, if no contig_mem
16031  * is available for now.
16032  */
16033 static struct contig_mem *
16034 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
16035 {
16036 	size_t rlen;
16037 	struct contig_mem *cp = NULL;
16038 	ddi_acc_handle_t acc_hdl;
16039 	caddr_t addr;
16040 	int big_enough = 0;
16041 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
16042 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
16043 
16044 	/* Try to get one available contig_mem */
16045 	mutex_enter(ST_MUTEX);
16046 
16047 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
16048 
16049 	if (un->un_contig_mem_available_num > 0) {
16050 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16051 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
16052 		/*
16053 		 * we failed to get one. we're going to
16054 		 * alloc one more contig_mem for this I/O
16055 		 */
16056 		mutex_exit(ST_MUTEX);
16057 		cp = (struct contig_mem *)kmem_zalloc(
16058 		    sizeof (struct contig_mem) + biosize(),
16059 		    alloc_flags);
16060 		if (cp == NULL) {
16061 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16062 			    "alloc contig_mem failure\n");
16063 			return (NULL); /* cannot get one */
16064 		}
16065 		cp->cm_bp = (struct buf *)
16066 		    (((caddr_t)cp) + sizeof (struct contig_mem));
16067 		bioinit(cp->cm_bp);
16068 		mutex_enter(ST_MUTEX);
16069 		un->un_contig_mem_total_num++; /* one more available */
16070 	} else {
16071 		/*
16072 		 * we failed to get one and we're NOT allowed to
16073 		 * alloc more contig_mem
16074 		 */
16075 		if (alloc_flags == KM_SLEEP) {
16076 			while (un->un_contig_mem_available_num <= 0) {
16077 				cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16078 			}
16079 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16080 		} else {
16081 			mutex_exit(ST_MUTEX);
16082 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16083 			    "alloc contig_mem failure\n");
16084 			return (NULL); /* cannot get one */
16085 		}
16086 	}
16087 	mutex_exit(ST_MUTEX);
16088 
16089 	/* We need to check if this block of mem is big enough for this I/O */
16090 	if (cp->cm_len < len) {
16091 		/* not big enough, need to alloc a new one */
16092 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
16093 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
16094 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
16095 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16096 			    "alloc contig_mem failure: not enough mem\n");
16097 			st_release_contig_mem(un, cp);
16098 			cp = NULL;
16099 		} else {
16100 			if (cp->cm_addr) {
16101 				/* release previous one before attach new one */
16102 				ddi_dma_mem_free(&cp->cm_acc_hdl);
16103 			}
16104 			mutex_enter(ST_MUTEX);
16105 			un->un_max_contig_mem_len =
16106 			    un->un_max_contig_mem_len >= len ?
16107 			    un->un_max_contig_mem_len : len;
16108 			mutex_exit(ST_MUTEX);
16109 
16110 			/* attach new mem to this cp */
16111 			cp->cm_addr = addr;
16112 			cp->cm_acc_hdl = acc_hdl;
16113 			cp->cm_len = len;
16114 
16115 			goto alloc_ok; /* get one usable cp */
16116 		}
16117 	} else {
16118 		goto alloc_ok; /* get one usable cp */
16119 	}
16120 
16121 	/* cannot find/alloc a usable cp, when we get here */
16122 
16123 	mutex_enter(ST_MUTEX);
16124 	if ((un->un_max_contig_mem_len < len) ||
16125 	    (alloc_flags != KM_SLEEP)) {
16126 		mutex_exit(ST_MUTEX);
16127 		return (NULL);
16128 	}
16129 
16130 	/*
16131 	 * we're allowed to sleep, and there is one big enough
16132 	 * contig mem in the system, which is currently in use,
16133 	 * wait for it...
16134 	 */
16135 	big_enough = 1;
16136 	do {
16137 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16138 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16139 	} while (cp == NULL);
16140 	mutex_exit(ST_MUTEX);
16141 
16142 	/* we get the big enough contig mem, finally */
16143 
16144 alloc_ok:
16145 	/* init bp attached to this cp */
16146 	bioreset(cp->cm_bp);
16147 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
16148 	cp->cm_bp->b_private = (void *)cp;
16149 
16150 	return (cp);
16151 }
16152 
16153 /*
16154  * this is the biodone func for the bp used in big block I/O
16155  */
16156 static int
16157 st_bigblk_xfer_done(struct buf *bp)
16158 {
16159 	struct contig_mem *cp;
16160 	struct buf *orig_bp;
16161 	int ioerr;
16162 	struct scsi_tape *un;
16163 
16164 	/* sanity check */
16165 	if (bp == NULL) {
16166 		return (DDI_FAILURE);
16167 	}
16168 
16169 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16170 	if (un == NULL) {
16171 		return (DDI_FAILURE);
16172 	}
16173 
16174 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
16175 
16176 	cp = (struct contig_mem *)bp->b_private;
16177 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
16178 	cp->cm_bp = bp;
16179 
16180 	/* special handling for special I/O */
16181 	if (cp->cm_use_sbuf) {
16182 #ifndef __lock_lint
16183 		ASSERT(un->un_sbuf_busy);
16184 #endif
16185 		un->un_sbufp = orig_bp;
16186 		cp->cm_use_sbuf = 0;
16187 	}
16188 
16189 	orig_bp->b_resid = bp->b_resid;
16190 	ioerr = geterror(bp);
16191 	if (ioerr != 0) {
16192 		bioerror(orig_bp, ioerr);
16193 	} else if (orig_bp->b_flags & B_READ) {
16194 		/* copy data back to original bp */
16195 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
16196 		    bp->b_bcount - bp->b_resid);
16197 	}
16198 
16199 	st_release_contig_mem(un, cp);
16200 
16201 	biodone(orig_bp);
16202 
16203 	return (DDI_SUCCESS);
16204 }
16205 
16206 /*
16207  * We use this func to replace original bp that may not be able to do I/O
16208  * in big block size with one that can
16209  */
16210 static struct buf *
16211 st_get_bigblk_bp(struct buf *bp)
16212 {
16213 	struct contig_mem *cp;
16214 	struct scsi_tape *un;
16215 	struct buf *cont_bp;
16216 
16217 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16218 	if (un == NULL) {
16219 		return (bp);
16220 	}
16221 
16222 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
16223 
16224 	/* try to get one contig_mem */
16225 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
16226 	if (!cp) {
16227 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
16228 		    "Cannot alloc contig buf for I/O for %lu blk size",
16229 		    bp->b_bcount);
16230 		return (bp);
16231 	}
16232 	cont_bp = cp->cm_bp;
16233 	cp->cm_bp = bp;
16234 
16235 	/* make sure that we "are" using un_sbufp for special I/O */
16236 	if (bp == un->un_sbufp) {
16237 #ifndef __lock_lint
16238 		ASSERT(un->un_sbuf_busy);
16239 #endif
16240 		un->un_sbufp = cont_bp;
16241 		cp->cm_use_sbuf = 1;
16242 	}
16243 
16244 	/* clone bp */
16245 	cont_bp->b_bcount = bp->b_bcount;
16246 	cont_bp->b_resid = bp->b_resid;
16247 	cont_bp->b_iodone = st_bigblk_xfer_done;
16248 	cont_bp->b_file = bp->b_file;
16249 	cont_bp->b_offset = bp->b_offset;
16250 	cont_bp->b_dip = bp->b_dip;
16251 	cont_bp->b_error = 0;
16252 	cont_bp->b_proc = NULL;
16253 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
16254 	cont_bp->b_shadow = NULL;
16255 	cont_bp->b_pages = NULL;
16256 	cont_bp->b_edev = bp->b_edev;
16257 	cont_bp->b_dev = bp->b_dev;
16258 	cont_bp->b_lblkno = bp->b_lblkno;
16259 	cont_bp->b_forw = bp->b_forw;
16260 	cont_bp->b_back = bp->b_back;
16261 	cont_bp->av_forw = bp->av_forw;
16262 	cont_bp->av_back = bp->av_back;
16263 	cont_bp->b_bufsize = bp->b_bufsize;
16264 
16265 	/* get data in original bp */
16266 	if (bp->b_flags & B_WRITE) {
16267 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
16268 	}
16269 
16270 	return (cont_bp);
16271 }
16272 #else
16273 #ifdef __lock_lint
16274 static int
16275 st_bigblk_xfer_done(struct buf *bp)
16276 {
16277 	return (0);
16278 }
16279 #endif
16280 #endif
16281 
16282 static const char *eof_status[] =
16283 {
16284 	"NO_EOF",
16285 	"EOF_PENDING",
16286 	"EOF",
16287 	"EOT_PENDING",
16288 	"EOT",
16289 	"EOM",
16290 	"AFTER_EOM"
16291 };
16292 static const char *mode[] = {
16293 	"invalid",
16294 	"legacy",
16295 	"logical"
16296 };
16297 
16298 static void
16299 st_print_position(dev_info_t *dev, char *label, uint_t level,
16300 const char *comment, tapepos_t *pos)
16301 {
16302 	ST_FUNC(dev, st_print_position);
16303 
16304 	scsi_log(dev, label, level,
16305 	    "%s Position data:\n", comment);
16306 	scsi_log(dev, label, CE_CONT,
16307 	    "Positioning mode = %s", mode[pos->pmode]);
16308 	scsi_log(dev, label, CE_CONT,
16309 	    "End Of File/Tape = %s", eof_status[pos->eof]);
16310 	scsi_log(dev, label, CE_CONT,
16311 	    "File Number      = 0x%x", pos->fileno);
16312 	scsi_log(dev, label, CE_CONT,
16313 	    "Block Number     = 0x%x", pos->blkno);
16314 	scsi_log(dev, label, CE_CONT,
16315 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
16316 	scsi_log(dev, label, CE_CONT,
16317 	    "Partition Number = 0x%x", pos->partition);
16318 }
16319 static int
16320 st_check_if_media_changed(struct scsi_tape *un, caddr_t data, int size)
16321 {
16322 
16323 	int result = 0;
16324 	int i;
16325 	ST_FUNC(ST_DEVINFO, st_check_if_media_changed);
16326 
16327 	/*
16328 	 * find non alpha numeric working from the end.
16329 	 */
16330 	for (i = size - 1; i >= 0; i--) {
16331 		if (ISALNUM(data[i]) == 0 || data[i] == ' ') {
16332 			data[i] = 0;
16333 			size = i;
16334 		}
16335 	}
16336 
16337 	if (size == 1) {
16338 		/*
16339 		 * Drive seems to think its returning useful data
16340 		 * but it looks like all junk
16341 		 */
16342 		return (result);
16343 	}
16344 
16345 	size++;
16346 
16347 	/*
16348 	 * Actually got a valid serial number.
16349 	 * If never stored one before alloc space for it.
16350 	 */
16351 	if (un->un_media_id_len == 0) {
16352 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16353 		un->un_media_id_len = size;
16354 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16355 		un->un_media_id[min(size, strlen(data))] = 0;
16356 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16357 		    "Found Media Id %s length = %d\n", un->un_media_id, size);
16358 	} else if (size > un->un_media_id_len) {
16359 		if (strncmp(un->un_media_id, data, size) != 0) {
16360 			result = ESPIPE;
16361 		}
16362 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16363 		    "Longer Media Id old ID:%s new ID:%s\n",
16364 		    un->un_media_id, data);
16365 		kmem_free(un->un_media_id, un->un_media_id_len);
16366 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16367 		un->un_media_id_len = size;
16368 		(void) strncpy(un->un_media_id, data, size);
16369 		un->un_media_id[size] = 0;
16370 	} else if (strncmp(data, un->un_media_id,
16371 	    min(size, un->un_media_id_len)) != 0) {
16372 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16373 		    "Old Media Id %s length = %d New %s length = %d\n",
16374 		    un->un_media_id, un->un_media_id_len, data, size);
16375 		bzero(un->un_media_id, un->un_media_id_len);
16376 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16377 		un->un_media_id[min(size, strlen(data))] = 0;
16378 		result = ESPIPE;
16379 	} else {
16380 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
16381 		    "Media Id still %s\n", un->un_media_id);
16382 	}
16383 
16384 	ASSERT(strlen(un->un_media_id) <= size);
16385 
16386 	return (result);
16387 }
16388 #define	ID_SIZE 32
16389 typedef struct
16390 {
16391 	uchar_t avilable_data0;
16392 	uchar_t avilable_data1;
16393 	uchar_t avilable_data2;
16394 	uchar_t avilable_data3;
16395 	uchar_t attribute_msb;
16396 	uchar_t attribute_lsb;
16397 #ifdef _BIT_FIELDS_LTOH
16398 	uchar_t format		: 2,
16399 				: 5,
16400 		read_only	: 1;
16401 #else
16402 	uchar_t read_only	: 1,
16403 				: 5,
16404 		format		: 2;
16405 #endif
16406 	uchar_t attribute_len_msb;
16407 	uchar_t attribute_len_lsb;
16408 }attribute_header;
16409 
16410 typedef struct {
16411 	attribute_header header;
16412 	char data[1];
16413 }mam_attribute;
16414 
16415 static int
16416 st_handle_hex_media_id(struct scsi_tape *un, void *pnt, int size)
16417 {
16418 	int result;
16419 	int newsize = (size << 1) + 3; /* extra for leading 0x and null term */
16420 	int i;
16421 	uchar_t byte;
16422 	char *format;
16423 	uchar_t *data = (uchar_t *)pnt;
16424 	char *buf = kmem_alloc(newsize, KM_SLEEP);
16425 
16426 	ST_FUNC(ST_DEVINFO, st_handle_hex_media_id);
16427 
16428 	(void) sprintf(buf, "0x");
16429 	for (i = 0; i < size; i++) {
16430 		byte = data[i];
16431 		if (byte < 0x10)
16432 			format = "0%x";
16433 		else
16434 			format = "%x";
16435 		(void) sprintf(&buf[(int)strlen(buf)], format, byte);
16436 	}
16437 	result = st_check_if_media_changed(un, buf, newsize);
16438 
16439 	kmem_free(buf, newsize);
16440 
16441 	return (result);
16442 }
16443 
16444 
16445 static int
16446 st_get_media_id_via_read_attribute(struct scsi_tape *un, ubufunc_t bufunc)
16447 {
16448 	int result;
16449 	mam_attribute *buffer;
16450 	int size;
16451 	int newsize;
16452 
16453 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_read_attribute);
16454 	size = sizeof (attribute_header) + max(un->un_media_id_len, ID_SIZE);
16455 again:
16456 	buffer = kmem_zalloc(size, KM_SLEEP);
16457 	result = st_read_attributes(un, 0x0401, buffer, size, bufunc);
16458 	if (result == 0) {
16459 
16460 		newsize = (buffer->header.attribute_len_msb << 8) |
16461 		    buffer->header.attribute_len_lsb;
16462 
16463 		if (newsize + sizeof (attribute_header) > size) {
16464 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
16465 			    "resizing read attribute data from %d to %d format"
16466 			    " %d\n", size, (int)sizeof (attribute_header) +
16467 			    newsize, buffer->header.format);
16468 			kmem_free(buffer, size);
16469 			size = newsize + sizeof (attribute_header);
16470 			goto again;
16471 		}
16472 
16473 		un->un_media_id_method = st_get_media_id_via_read_attribute;
16474 		if (buffer->header.format == 0) {
16475 			result =
16476 			    st_handle_hex_media_id(un, buffer->data, newsize);
16477 		} else {
16478 			result = st_check_if_media_changed(un, buffer->data,
16479 			    newsize);
16480 		}
16481 	} else if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
16482 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
16483 		    "Read Attribute Command for Media Identification is not "
16484 		    "supported on the HBA that this drive is attached to.");
16485 		result = ENOTTY;
16486 	}
16487 
16488 	kmem_free(buffer, size);
16489 	un->un_status = 0;
16490 
16491 	return (result);
16492 }
16493 
16494 
16495 static int
16496 st_get_media_id_via_media_serial_cmd(struct scsi_tape *un, ubufunc_t bufunc)
16497 {
16498 	char cdb[CDB_GROUP5];
16499 	struct uscsi_cmd *ucmd;
16500 	struct scsi_extended_sense sense;
16501 	int rval;
16502 	int size = max(un->un_media_id_len, ID_SIZE);
16503 	caddr_t buf;
16504 
16505 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_media_serial_cmd);
16506 
16507 	if (un->un_sd->sd_inq->inq_ansi < 3) {
16508 		return (ENOTTY);
16509 	}
16510 
16511 	ucmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
16512 upsize:
16513 	buf = kmem_alloc(size, KM_SLEEP);
16514 
16515 	cdb[0] = (char)SCMD_SVC_ACTION_IN_G5;
16516 	cdb[1] = SSVC_ACTION_READ_MEDIA_SERIAL;
16517 	cdb[2] = 0;
16518 	cdb[3] = 0;
16519 	cdb[4] = 0;
16520 	cdb[5] = 0;
16521 	cdb[6] = (char)(size >> 24);
16522 	cdb[7] = (char)(size >> 16);
16523 	cdb[8] = (char)(size >> 8);
16524 	cdb[9] = (char)(size);
16525 	cdb[10] = 0;
16526 	cdb[11] = 0;
16527 
16528 	ucmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
16529 	ucmd->uscsi_timeout = un->un_dp->non_motion_timeout;
16530 	ucmd->uscsi_cdb = &cdb[0];
16531 	ucmd->uscsi_cdblen = sizeof (cdb);
16532 	ucmd->uscsi_bufaddr = buf;
16533 	ucmd->uscsi_buflen = size;
16534 	ucmd->uscsi_rqbuf = (caddr_t)&sense;
16535 	ucmd->uscsi_rqlen = sizeof (sense);
16536 
16537 	rval = bufunc(un, ucmd, FKIOCTL);
16538 
16539 	if (rval || ucmd->uscsi_status != 0) {
16540 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16541 		    "media serial command returned %d scsi_status %d"
16542 		    " rqstatus %d", rval, ucmd->uscsi_status,
16543 		    ucmd->uscsi_rqstatus);
16544 		/*
16545 		 * If this returns invalid operation code don't try again.
16546 		 */
16547 		if (sense.es_key == KEY_ILLEGAL_REQUEST &&
16548 		    sense.es_add_code == 0x20) {
16549 			rval = ENOTTY;
16550 		} else if (rval == 0) {
16551 			rval = EIO;
16552 		}
16553 		un->un_status = 0;
16554 	} else {
16555 		int act_size;
16556 
16557 		/*
16558 		 * get reported size.
16559 		 */
16560 		act_size = (int)buf[3] | (int)(buf[2] << 8) |
16561 		    (int)(buf[1] << 16) | (int)(buf[0] << 24);
16562 
16563 		/* documentation says mod 4. */
16564 		while (act_size & 3) {
16565 			act_size++;
16566 		}
16567 
16568 		/*
16569 		 * If reported size is larger that we our buffer.
16570 		 * Free the old one and allocate one that is larger
16571 		 * enough and re-issuse the command.
16572 		 */
16573 		if (act_size + 4 > size) {
16574 			kmem_free(buf, size);
16575 			size = act_size + 4;
16576 			goto upsize;
16577 		}
16578 
16579 		if (act_size == 0) {
16580 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16581 			    "media serial number is not available");
16582 			un->un_status = 0;
16583 			rval = 0;
16584 		} else {
16585 			/*
16586 			 * set data pointer to point to the start
16587 			 * of that serial number.
16588 			 */
16589 			un->un_media_id_method =
16590 			    st_get_media_id_via_media_serial_cmd;
16591 			rval =
16592 			    st_check_if_media_changed(un, &buf[4], act_size);
16593 		}
16594 	}
16595 
16596 	kmem_free(ucmd, sizeof (struct uscsi_cmd));
16597 	kmem_free(buf, size);
16598 
16599 	return (rval);
16600 }
16601 
16602 
16603 /* ARGSUSED */
16604 static int
16605 st_bogus_media_id(struct scsi_tape *un, ubufunc_t bufunc)
16606 {
16607 	ST_FUNC(ST_DEVINFO, st_bogus_media_id);
16608 
16609 	ASSERT(un->un_media_id == NULL || un->un_media_id == bogusID);
16610 	ASSERT(un->un_media_id_len == 0);
16611 	un->un_media_id = (char *)bogusID;
16612 	un->un_media_id_len = 0;
16613 	return (0);
16614 }
16615 
16616 typedef int (*media_chk_function)(struct scsi_tape *, ubufunc_t bufunc);
16617 
16618 media_chk_function media_chk_functions[] = {
16619 	st_get_media_id_via_media_serial_cmd,
16620 	st_get_media_id_via_read_attribute,
16621 	st_bogus_media_id
16622 };
16623 
16624 static int
16625 st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc)
16626 {
16627 	int result = 0;
16628 	int i;
16629 
16630 	ST_FUNC(ST_DEVINFO, st_get_media_identification);
16631 
16632 	for (i = 0; i < ST_NUM_MEMBERS(media_chk_functions); i++) {
16633 		if (result == ENOTTY) {
16634 			/*
16635 			 * Last operation type not supported by this device.
16636 			 * Make so next time it doesn`t do that again.
16637 			 */
16638 			un->un_media_id_method = media_chk_functions[i];
16639 		} else if (un->un_media_id_method != media_chk_functions[i] &&
16640 		    un->un_media_id_method != st_get_media_identification) {
16641 			continue;
16642 		}
16643 		result = media_chk_functions[i](un, bufunc);
16644 		/*
16645 		 * If result indicates the function was successful or
16646 		 * that the media is not the same as last known, break.
16647 		 */
16648 		if (result == 0 || result == ESPIPE) {
16649 			break;
16650 		}
16651 	}
16652 
16653 	return (result);
16654 }
16655 
16656 static errstate
16657 st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
16658     errstate onentry)
16659 {
16660 
16661 	int ret;
16662 	st_err_info *errinfo;
16663 	recov_info *ri = (recov_info *)pkt->pkt_private;
16664 
16665 	ST_FUNC(ST_DEVINFO, st_command_recovery);
16666 
16667 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16668 
16669 	ASSERT(un->un_recov_buf_busy == 0);
16670 
16671 	/*
16672 	 * Don't try and recover a reset that this device sent.
16673 	 */
16674 	if (un->un_rsvd_status & ST_INITIATED_RESET &&
16675 	    onentry == DEVICE_RESET) {
16676 		return (COMMAND_DONE_ERROR);
16677 	}
16678 
16679 	/*
16680 	 * See if expected position was passed with scsi_pkt.
16681 	 */
16682 	if (ri->privatelen == sizeof (recov_info)) {
16683 
16684 		/*
16685 		 * Not for this command.
16686 		 */
16687 		if (ri->cmd_attrib->do_not_recover) {
16688 			return (COMMAND_DONE_ERROR);
16689 		}
16690 
16691 		/*
16692 		 * Create structure to hold all error state info.
16693 		 */
16694 		errinfo = kmem_zalloc(ST_ERR_INFO_SIZE, KM_SLEEP);
16695 		errinfo->ei_error_type = onentry;
16696 		errinfo->ei_failing_bp = ri->cmd_bp;
16697 		COPY_POS(&errinfo->ei_expected_pos, &ri->pos);
16698 	} else {
16699 		/* disabled */
16700 		return (COMMAND_DONE_ERROR);
16701 	}
16702 
16703 	bcopy(pkt, &errinfo->ei_failed_pkt, scsi_pkt_size());
16704 	bcopy(pkt->pkt_scbp, &errinfo->ei_failing_status, SECMDS_STATUS_SIZE);
16705 	ret = ddi_taskq_dispatch(un->un_recov_taskq, st_recover, errinfo,
16706 	    DDI_NOSLEEP);
16707 	ASSERT(ret == DDI_SUCCESS);
16708 	if (ret != DDI_SUCCESS) {
16709 		kmem_free(errinfo, ST_ERR_INFO_SIZE);
16710 		return (COMMAND_DONE_ERROR);
16711 	}
16712 	return (JUST_RETURN); /* release calling thread */
16713 }
16714 
16715 
16716 static void
16717 st_recov_ret(struct scsi_tape *un, st_err_info *errinfo, errstate err)
16718 {
16719 	int error_number;
16720 	buf_t *bp;
16721 
16722 
16723 	ST_FUNC(ST_DEVINFO, st_recov_ret);
16724 
16725 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16726 #if !defined(lint)
16727 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
16728 #endif
16729 
16730 	bp = errinfo->ei_failing_bp;
16731 	kmem_free(errinfo, ST_ERR_INFO_SIZE);
16732 
16733 	switch (err) {
16734 	case JUST_RETURN:
16735 		mutex_exit(&un->un_sd->sd_mutex);
16736 		return;
16737 
16738 	case COMMAND_DONE:
16739 	case COMMAND_DONE_ERROR_RECOVERED:
16740 		ST_DO_KSTATS(bp, kstat_runq_exit);
16741 		error_number = 0;
16742 		break;
16743 
16744 	default:
16745 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16746 		    "st_recov_ret with unhandled errstat %d\n", err);
16747 		/* FALLTHROUGH */
16748 	case COMMAND_DONE_ERROR:
16749 		un->un_pos.pmode = invalid;
16750 		un->un_running.pmode = invalid;
16751 		/* FALLTHROUGH */
16752 	case COMMAND_DONE_EACCES:
16753 		ST_DO_KSTATS(bp, kstat_waitq_exit);
16754 		ST_DO_ERRSTATS(un, st_transerrs);
16755 		error_number = EIO;
16756 		st_set_pe_flag(un);
16757 		break;
16758 
16759 	}
16760 
16761 	st_bioerror(bp, error_number);
16762 	st_done_and_mutex_exit(un, bp);
16763 }
16764 
16765 
16766 static void
16767 st_recover(void *arg)
16768 {
16769 	st_err_info *const errinfo = (st_err_info *)arg;
16770 	uchar_t com = errinfo->ei_failed_pkt.pkt_cdbp[0];
16771 	struct scsi_tape *un;
16772 	tapepos_t cur_pos;
16773 	int rval;
16774 	errstate status = COMMAND_DONE_ERROR;
16775 	recov_info *rcv;
16776 	buf_t *bp;
16777 
16778 
16779 	rcv = errinfo->ei_failed_pkt.pkt_private;
16780 	ASSERT(rcv->privatelen == sizeof (recov_info));
16781 	bp = rcv->cmd_bp;
16782 
16783 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16784 
16785 	ASSERT(un != NULL);
16786 
16787 	mutex_enter(ST_MUTEX);
16788 
16789 	ST_FUNC(ST_DEVINFO, st_recover);
16790 
16791 	ST_CDB(ST_DEVINFO, "Recovering command",
16792 	    (caddr_t)errinfo->ei_failed_pkt.pkt_cdbp);
16793 	ST_SENSE(ST_DEVINFO, "sense status for failed command",
16794 	    (caddr_t)&errinfo->ei_failing_status,
16795 	    sizeof (struct scsi_arq_status));
16796 	ST_POS(ST_DEVINFO, rcv->cmd_attrib->recov_pos_type == POS_STARTING ?
16797 	    "starting position for recovery command" :
16798 	    "expected position for recovery command",
16799 	    &errinfo->ei_expected_pos);
16800 
16801 	rval = st_test_path_to_device(un);
16802 
16803 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16804 	    "st_recover called with %s, TUR returned %d\n",
16805 	    errstatenames[errinfo->ei_error_type], rval);
16806 	/*
16807 	 * If the drive responed to the TUR lets try and get it to sync
16808 	 * any data it might have in the buffer.
16809 	 */
16810 	if (rval == 0 && rcv->cmd_attrib->chg_tape_data) {
16811 		rval = st_rcmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
16812 		if (rval) {
16813 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16814 			    "st_recover failed to flush, returned %d\n", rval);
16815 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16816 			return;
16817 		}
16818 	}
16819 	switch (errinfo->ei_error_type) {
16820 	case ATTEMPT_RETRY:
16821 	case COMMAND_TIMEOUT:
16822 	case DEVICE_RESET:
16823 	case PATH_FAILED:
16824 		/*
16825 		 * For now if we can't talk to the device we are done.
16826 		 * If the drive is reserved we can try to get it back.
16827 		 */
16828 		if (rval != 0 && rval != EACCES) {
16829 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16830 			return;
16831 		}
16832 
16833 		/*
16834 		 * If reservation conflict and do a preempt, fail it.
16835 		 */
16836 		if ((un->un_rsvd_status &
16837 		    (ST_APPLICATION_RESERVATIONS | ST_RESERVE)) != 0) {
16838 			if ((errinfo->ei_failed_pkt.pkt_cdbp[0] ==
16839 			    SCMD_PERSISTENT_RESERVE_OUT) &&
16840 			    (errinfo->ei_failed_pkt.pkt_cdbp[1] ==
16841 			    ST_SA_SCSI3_PREEMPT) &&
16842 			    (SCBP_C(&errinfo->ei_failed_pkt) ==
16843 			    STATUS_RESERVATION_CONFLICT)) {
16844 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16845 				return;
16846 			}
16847 		}
16848 
16849 		/*
16850 		 * If scsi II lost reserve try and get it back.
16851 		 */
16852 		if ((((un->un_rsvd_status &
16853 		    (ST_LOST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
16854 		    ST_LOST_RESERVE)) &&
16855 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] != SCMD_RELEASE)) {
16856 			rval = st_reserve_release(un, ST_RESERVE,
16857 			    st_uscsi_rcmd);
16858 			if (rval != 0) {
16859 				if (st_take_ownership(un, st_uscsi_rcmd) != 0) {
16860 					st_recov_ret(un, errinfo,
16861 					    COMMAND_DONE_EACCES);
16862 					return;
16863 				}
16864 			}
16865 			un->un_rsvd_status |= ST_RESERVE;
16866 			un->un_rsvd_status &= ~(ST_RELEASE | ST_LOST_RESERVE |
16867 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
16868 		}
16869 		rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16870 		if (rval) {
16871 			rval = st_gen_mode_select(un, st_uscsi_rcmd,
16872 			    un->un_mspl, sizeof (struct seq_mode));
16873 		}
16874 		if (rval) {
16875 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16876 			return;
16877 		}
16878 		break;
16879 	case DEVICE_TAMPER:
16880 		/*
16881 		 * Check if the ASC/ASCQ says mode data has changed.
16882 		 */
16883 		if ((errinfo->ei_failing_status.sts_sensedata.es_add_code ==
16884 		    0x2a) &&
16885 		    (errinfo->ei_failing_status.sts_sensedata.es_qual_code ==
16886 		    0x01)) {
16887 			/*
16888 			 * See if mode sense changed.
16889 			 */
16890 			rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16891 			if (rval) {
16892 				/*
16893 				 * If so change it back.
16894 				 */
16895 				rval = st_gen_mode_select(un, st_uscsi_rcmd,
16896 				    un->un_mspl, sizeof (struct seq_mode));
16897 			}
16898 			if (rval) {
16899 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16900 				return;
16901 			}
16902 		}
16903 		/*
16904 		 * if we have a media id and its not bogus.
16905 		 * Check to see if it the same.
16906 		 */
16907 		if (un->un_media_id != NULL && un->un_media_id != bogusID) {
16908 			rval = st_get_media_identification(un, st_uscsi_rcmd);
16909 			if (rval == ESPIPE) {
16910 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16911 				return;
16912 			}
16913 		}
16914 		break;
16915 	default:
16916 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16917 		    "Unhandled error type %s in st_recover() 0x%x\n",
16918 		    errstatenames[errinfo->ei_error_type], com);
16919 	}
16920 
16921 	/*
16922 	 * if command is retriable retry it.
16923 	 * Special case here. The command attribute for SCMD_REQUEST_SENSE
16924 	 * does not say that it is retriable. That because if you reissue a
16925 	 * request sense and the target responds the sense data will have
16926 	 * been consumed and no long be valid. If we get a busy status on
16927 	 * request sense while the state is ST_STATE_SENSING this will
16928 	 * reissue that pkt.
16929 	 *
16930 	 * XXX If this request sense gets sent to a different port then
16931 	 * the original command that failed was sent on it will not get
16932 	 * valid sense data for that command.
16933 	 */
16934 	if (rcv->cmd_attrib->retriable || un->un_rqs_bp == bp) {
16935 		status = st_recover_reissue_pkt(un, &errinfo->ei_failed_pkt);
16936 
16937 	/*
16938 	 * if drive doesn't support read position we are done
16939 	 */
16940 	} else if (un->un_read_pos_type == NO_POS) {
16941 		status = COMMAND_DONE_ERROR;
16942 	/*
16943 	 * If this command results in a changed tape position,
16944 	 * lets see where we are.
16945 	 */
16946 	} else if (rcv->cmd_attrib->chg_tape_pos) {
16947 		/*
16948 		 * XXX May be a reason to choose a different type here.
16949 		 * Long format has file position information.
16950 		 * Short and Extended have information about whats
16951 		 * in the buffer. St's positioning assumes in the buffer
16952 		 * to be the same as on tape.
16953 		 */
16954 		rval = st_compare_expected_position(un, errinfo,
16955 		    rcv->cmd_attrib, &cur_pos);
16956 		if (rval == 0) {
16957 			status = COMMAND_DONE;
16958 		} else if (rval == EAGAIN) {
16959 			status = st_recover_reissue_pkt(un,
16960 			    &errinfo->ei_failed_pkt);
16961 		} else {
16962 			status = COMMAND_DONE_ERROR;
16963 		}
16964 	} else {
16965 		ASSERT(0);
16966 	}
16967 
16968 	st_recov_ret(un, errinfo, status);
16969 }
16970 
16971 static void
16972 st_recov_cb(struct scsi_pkt *pkt)
16973 {
16974 	struct scsi_tape *un;
16975 	struct buf *bp;
16976 	recov_info *rcv;
16977 	errstate action = COMMAND_DONE_ERROR;
16978 	int timout = ST_TRAN_BUSY_TIMEOUT; /* short (default) timeout */
16979 
16980 	/*
16981 	 * Get the buf from the packet.
16982 	 */
16983 	rcv = pkt->pkt_private;
16984 	ASSERT(rcv->privatelen == sizeof (recov_info));
16985 	bp = rcv->cmd_bp;
16986 
16987 	/*
16988 	 * get the unit from the buf.
16989 	 */
16990 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16991 	ASSERT(un != NULL);
16992 
16993 	ST_FUNC(ST_DEVINFO, st_recov_cb);
16994 
16995 	mutex_enter(ST_MUTEX);
16996 
16997 	ASSERT(bp == un->un_recov_buf);
16998 
16999 
17000 	switch (pkt->pkt_reason) {
17001 	case CMD_CMPLT:
17002 		if (un->un_arq_enabled && pkt->pkt_state & STATE_ARQ_DONE) {
17003 			action = st_handle_autosense(un, bp, &rcv->pos);
17004 		} else  if ((SCBP(pkt)->sts_busy) ||
17005 		    (SCBP(pkt)->sts_chk) ||
17006 		    (SCBP(pkt)->sts_vu7)) {
17007 			action = st_check_error(un, pkt);
17008 		} else {
17009 			action = COMMAND_DONE;
17010 		}
17011 		break;
17012 	case CMD_TIMEOUT:
17013 		action = COMMAND_TIMEOUT;
17014 		break;
17015 	case CMD_TRAN_ERR:
17016 		action = QUE_COMMAND;
17017 		break;
17018 	default:
17019 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
17020 		    "pkt_reason not handled yet %s",
17021 		    scsi_rname(pkt->pkt_reason));
17022 		action = COMMAND_DONE_ERROR;
17023 	}
17024 
17025 	/*
17026 	 * check for undetected path failover.
17027 	 */
17028 	if (un->un_multipath) {
17029 		if (scsi_pkt_allocated_correctly(pkt) &&
17030 		    (un->un_last_path_instance != pkt->pkt_path_instance)) {
17031 			if (un->un_state > ST_STATE_OPENING) {
17032 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17033 				    "Failover detected in recovery, action is "
17034 				    "%s\n", errstatenames[action]);
17035 			}
17036 			un->un_last_path_instance = pkt->pkt_path_instance;
17037 		}
17038 	}
17039 
17040 	ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
17041 	    "Recovery call back got %s status on %s\n",
17042 	    errstatenames[action], st_print_scsi_cmd(pkt->pkt_cdbp[0]));
17043 
17044 	switch (action) {
17045 	case COMMAND_DONE:
17046 		break;
17047 
17048 	case COMMAND_DONE_EACCES:
17049 		bioerror(bp, EACCES);
17050 		break;
17051 
17052 	case COMMAND_DONE_ERROR_RECOVERED: /* XXX maybe wrong */
17053 		ASSERT(0);
17054 		break;
17055 
17056 	case COMMAND_TIMEOUT:
17057 	case COMMAND_DONE_ERROR:
17058 		bioerror(bp, EIO);
17059 		break;
17060 
17061 	case DEVICE_RESET:
17062 	case QUE_BUSY_COMMAND:
17063 	case PATH_FAILED:
17064 		/* longish timeout */
17065 		timout = ST_STATUS_BUSY_TIMEOUT;
17066 		/* FALLTHRU */
17067 	case QUE_COMMAND:
17068 	case DEVICE_TAMPER:
17069 	case ATTEMPT_RETRY:
17070 		/*
17071 		 * let st_handle_intr_busy put this bp back on waitq and make
17072 		 * checks to see if it is ok to requeue the command.
17073 		 */
17074 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
17075 
17076 		/*
17077 		 * Save the throttle before setting up the timeout
17078 		 */
17079 		if (un->un_throttle) {
17080 			un->un_last_throttle = un->un_throttle;
17081 		}
17082 		mutex_exit(ST_MUTEX);
17083 		if (st_handle_intr_busy(un, bp, timout) == 0) {
17084 			return;		/* timeout is setup again */
17085 		}
17086 		mutex_enter(ST_MUTEX);
17087 		un->un_pos.pmode = invalid;
17088 		un->un_err_resid = bp->b_resid = bp->b_bcount;
17089 		st_bioerror(bp, EIO);
17090 		st_set_pe_flag(un);
17091 		break;
17092 
17093 	default:
17094 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
17095 		    "Unhandled recovery state 0x%x\n", action);
17096 		un->un_pos.pmode = invalid;
17097 		un->un_err_resid = bp->b_resid = bp->b_bcount;
17098 		st_bioerror(bp, EIO);
17099 		st_set_pe_flag(un);
17100 		break;
17101 	}
17102 
17103 	st_done_and_mutex_exit(un, bp);
17104 }
17105 
17106 static int
17107 st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait)
17108 {
17109 	struct buf *bp;
17110 	int err;
17111 
17112 	ST_FUNC(ST_DEVINFO, st_rcmd);
17113 
17114 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
17115 	    "st_rcmd(un = 0x%p, com = 0x%x, count = %"PRIx64", wait = %d)\n",
17116 	    (void *)un, com, count, wait);
17117 
17118 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
17119 	ASSERT(mutex_owned(ST_MUTEX));
17120 
17121 #ifdef STDEBUG
17122 	if ((st_debug & 0x7)) {
17123 		st_debug_cmds(un, com, count, wait);
17124 	}
17125 #endif
17126 
17127 	while (un->un_recov_buf_busy)
17128 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17129 	un->un_recov_buf_busy = 1;
17130 
17131 	bp = un->un_recov_buf;
17132 	bzero(bp, sizeof (buf_t));
17133 
17134 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
17135 
17136 	err = st_setup_cmd(un, bp, com, count);
17137 
17138 	un->un_recov_buf_busy = 0;
17139 
17140 	cv_signal(&un->un_recov_buf_cv);
17141 
17142 	return (err);
17143 }
17144 
17145 /* args used */
17146 static int
17147 st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
17148 {
17149 	int rval;
17150 	buf_t *bp;
17151 
17152 	ST_FUNC(ST_DEVINFO, st_uscsi_rcmd);
17153 	ASSERT(flag == FKIOCTL);
17154 
17155 	/*
17156 	 * Get buffer resources...
17157 	 */
17158 	while (un->un_recov_buf_busy)
17159 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17160 	un->un_recov_buf_busy = 1;
17161 
17162 	bp = un->un_recov_buf;
17163 	bzero(bp, sizeof (buf_t));
17164 
17165 	bp->b_forw = (struct buf *)(uintptr_t)ucmd->uscsi_cdb[0];
17166 	bp->b_back = (struct buf *)ucmd;
17167 
17168 	mutex_exit(ST_MUTEX);
17169 	rval = scsi_uscsi_handle_cmd(un->un_dev, UIO_SYSSPACE, ucmd,
17170 	    st_strategy, bp, NULL);
17171 	mutex_enter(ST_MUTEX);
17172 
17173 	ucmd->uscsi_resid = bp->b_resid;
17174 
17175 	/*
17176 	 * Free resources
17177 	 */
17178 	un->un_recov_buf_busy = 0;
17179 	cv_signal(&un->un_recov_buf_cv);
17180 
17181 	return (rval);
17182 }
17183 
17184 /*
17185  * Add data to scsi_pkt to help know what to do if the command fails.
17186  */
17187 static void
17188 st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
17189     struct scsi_pkt *pkt)
17190 {
17191 	uint64_t count;
17192 	recov_info *rinfo = (recov_info *)pkt->pkt_private;
17193 
17194 	ST_FUNC(ST_DEVINFO, st_add_recovery_info_to_pkt);
17195 
17196 	ASSERT(rinfo->privatelen == sizeof (pkt_info) ||
17197 	    rinfo->privatelen == sizeof (recov_info));
17198 
17199 	SET_BP_PKT(bp, pkt);
17200 	rinfo->cmd_bp = bp;
17201 
17202 	if (rinfo->privatelen != sizeof (recov_info)) {
17203 		return;
17204 	}
17205 
17206 	rinfo->cmd_bp = bp;
17207 
17208 	rinfo->cmd_attrib = NULL;
17209 
17210 	/*
17211 	 * lookup the command attributes and add them to the recovery info.
17212 	 */
17213 	rinfo->cmd_attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
17214 
17215 	ASSERT(rinfo->cmd_attrib);
17216 
17217 	/*
17218 	 * For commands that there is no way to figure the expected position
17219 	 * once completed, we save the position the command was started from
17220 	 * so that if they fail we can position back and try again.
17221 	 * This has already been done in st_cmd() or st_iscsi_cmd().
17222 	 */
17223 	if (rinfo->cmd_attrib->recov_pos_type == POS_STARTING) {
17224 		/* save current position as the starting position. */
17225 		COPY_POS(&rinfo->pos, &un->un_pos);
17226 		un->un_running.pmode = invalid;
17227 		return;
17228 	}
17229 
17230 	/*
17231 	 * Don't want to update the running position for recovery.
17232 	 */
17233 	if (bp == un->un_recov_buf) {
17234 		rinfo->pos.pmode = un->un_running.pmode;
17235 		return;
17236 	}
17237 	/*
17238 	 * If running position is invalid copy the current position.
17239 	 * Running being set invalid means we are not in a read, write
17240 	 * or write filemark sequence.
17241 	 * We'll copy the current position and start from there.
17242 	 */
17243 	if (un->un_running.pmode == invalid) {
17244 		COPY_POS(&un->un_running, &un->un_pos);
17245 		COPY_POS(&rinfo->pos, &un->un_running);
17246 	} else {
17247 		COPY_POS(&rinfo->pos, &un->un_running);
17248 		if (rinfo->pos.pmode == legacy) {
17249 			/*
17250 			 * Always should be more logical blocks then
17251 			 * data blocks and files marks.
17252 			 */
17253 			ASSERT((rinfo->pos.blkno >= 0) ?
17254 			    rinfo->pos.lgclblkno >=
17255 			    (rinfo->pos.blkno + rinfo->pos.fileno) : 1);
17256 		}
17257 	}
17258 
17259 	/*
17260 	 * If the command is not expected to change the drive position
17261 	 * then the running position should be the expected position.
17262 	 */
17263 	if (rinfo->cmd_attrib->chg_tape_pos == 0) {
17264 		ASSERT(rinfo->cmd_attrib->chg_tape_direction == DIR_NONE);
17265 		return;
17266 	}
17267 
17268 	if (rinfo->cmd_attrib->explicit_cmd_set) {
17269 		ASSERT(rinfo->pos.pmode != invalid);
17270 		ASSERT(rinfo->cmd_attrib->get_cnt);
17271 		count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17272 		/*
17273 		 * This is a user generated CDB.
17274 		 */
17275 		if (bp == un->un_sbufp) {
17276 			uint64_t lbn;
17277 
17278 			lbn = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17279 
17280 			/*
17281 			 * See if this CDB will generate a locate or change
17282 			 * partition.
17283 			 */
17284 			if ((lbn != un->un_running.lgclblkno) ||
17285 			    (pkt->pkt_cdbp[3] != un->un_running.partition)) {
17286 				rinfo->pos.partition = pkt->pkt_cdbp[3];
17287 				rinfo->pos.pmode = logical;
17288 				rinfo->pos.lgclblkno = lbn;
17289 				un->un_running.partition = pkt->pkt_cdbp[3];
17290 				un->un_running.pmode = logical;
17291 				un->un_running.lgclblkno = lbn;
17292 			}
17293 		} else {
17294 			uint64_t lbn = un->un_running.lgclblkno;
17295 
17296 			pkt->pkt_cdbp[3]  = (uchar_t)un->un_running.partition;
17297 
17298 			pkt->pkt_cdbp[4]  = (uchar_t)(lbn >> 56);
17299 			pkt->pkt_cdbp[5]  = (uchar_t)(lbn >> 48);
17300 			pkt->pkt_cdbp[6]  = (uchar_t)(lbn >> 40);
17301 			pkt->pkt_cdbp[7]  = (uchar_t)(lbn >> 32);
17302 			pkt->pkt_cdbp[8]  = (uchar_t)(lbn >> 24);
17303 			pkt->pkt_cdbp[9]  = (uchar_t)(lbn >> 16);
17304 			pkt->pkt_cdbp[10] = (uchar_t)(lbn >> 8);
17305 			pkt->pkt_cdbp[11] = (uchar_t)(lbn);
17306 		}
17307 		rinfo->pos.lgclblkno += count;
17308 		rinfo->pos.blkno += count;
17309 		un->un_running.lgclblkno += count;
17310 		return;
17311 	}
17312 
17313 	if (rinfo->cmd_attrib->chg_tape_pos) {
17314 
17315 		/* should not have got an invalid position from running. */
17316 		if (un->un_mediastate == MTIO_INSERTED) {
17317 			ASSERT(rinfo->pos.pmode != invalid);
17318 		}
17319 
17320 		/* should have either a get count or or get lba function */
17321 		ASSERT(rinfo->cmd_attrib->get_cnt != NULL ||
17322 		    rinfo->cmd_attrib->get_lba != NULL);
17323 
17324 		/* only explicit commands have both and they're handled above */
17325 		ASSERT(!(rinfo->cmd_attrib->get_cnt != NULL &&
17326 		    rinfo->cmd_attrib->get_lba != NULL));
17327 
17328 		/* if it has a get count function */
17329 		if (rinfo->cmd_attrib->get_cnt != NULL) {
17330 			count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17331 			if (count == 0) {
17332 				return;
17333 			}
17334 			/*
17335 			 * Changes position but doesn't transfer data.
17336 			 * i.e. rewind, write_file_mark and load.
17337 			 */
17338 			if (rinfo->cmd_attrib->transfers_data == TRAN_NONE) {
17339 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17340 				case DIR_NONE: /* Erase */
17341 					ASSERT(rinfo->cmd_attrib->cmd ==
17342 					    SCMD_ERASE);
17343 					break;
17344 				case DIR_FORW: /* write_file_mark */
17345 					rinfo->pos.fileno += count;
17346 					rinfo->pos.lgclblkno += count;
17347 					rinfo->pos.blkno = 0;
17348 					un->un_running.fileno += count;
17349 					un->un_running.lgclblkno += count;
17350 					un->un_running.blkno = 0;
17351 					break;
17352 				case DIR_REVC: /* rewind */
17353 					rinfo->pos.fileno = 0;
17354 					rinfo->pos.lgclblkno = 0;
17355 					rinfo->pos.blkno = 0;
17356 					rinfo->pos.eof = ST_NO_EOF;
17357 					rinfo->pos.pmode = legacy;
17358 					un->un_running.fileno = 0;
17359 					un->un_running.lgclblkno = 0;
17360 					un->un_running.blkno = 0;
17361 					un->un_running.eof = ST_NO_EOF;
17362 					if (un->un_running.pmode != legacy)
17363 						un->un_running.pmode = legacy;
17364 					break;
17365 				case DIR_EITH: /* Load unload */
17366 					ASSERT(rinfo->cmd_attrib->cmd ==
17367 					    SCMD_LOAD);
17368 					switch (count & (LD_LOAD | LD_RETEN |
17369 					    LD_RETEN | LD_HOLD)) {
17370 					case LD_UNLOAD:
17371 					case LD_RETEN:
17372 					case LD_HOLD:
17373 					case LD_LOAD | LD_HOLD:
17374 					case LD_EOT | LD_HOLD:
17375 					case LD_RETEN | LD_HOLD:
17376 						rinfo->pos.pmode = invalid;
17377 						un->un_running.pmode = invalid;
17378 						break;
17379 					case LD_EOT:
17380 					case LD_LOAD | LD_EOT:
17381 						rinfo->pos.eof = ST_EOT;
17382 						rinfo->pos.pmode = invalid;
17383 						un->un_running.eof = ST_EOT;
17384 						un->un_running.pmode = invalid;
17385 						break;
17386 					case LD_LOAD:
17387 					case LD_RETEN | LD_LOAD:
17388 						rinfo->pos.fileno = 0;
17389 						rinfo->pos.lgclblkno = 0;
17390 						rinfo->pos.blkno = 0;
17391 						rinfo->pos.eof = ST_NO_EOF;
17392 						rinfo->pos.pmode = legacy;
17393 						un->un_running.fileno = 0;
17394 						un->un_running.lgclblkno = 0;
17395 						un->un_running.blkno = 0;
17396 						un->un_running.eof = ST_NO_EOF;
17397 						break;
17398 					default:
17399 						ASSERT(0);
17400 					}
17401 					break;
17402 				default:
17403 					ASSERT(0);
17404 					break;
17405 				}
17406 			} else {
17407 				/*
17408 				 * Changes position and does transfer data.
17409 				 * i.e. read or write.
17410 				 */
17411 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17412 				case DIR_FORW:
17413 					rinfo->pos.lgclblkno += count;
17414 					rinfo->pos.blkno += count;
17415 					un->un_running.lgclblkno += count;
17416 					un->un_running.blkno += count;
17417 					break;
17418 				case DIR_REVC:
17419 					rinfo->pos.lgclblkno -= count;
17420 					rinfo->pos.blkno -= count;
17421 					un->un_running.lgclblkno -= count;
17422 					un->un_running.blkno -= count;
17423 					break;
17424 				default:
17425 					ASSERT(0);
17426 					break;
17427 				}
17428 			}
17429 		} else if (rinfo->cmd_attrib->get_lba != NULL) {
17430 			/* Have a get LBA fuction. i.e. Locate */
17431 			ASSERT(rinfo->cmd_attrib->chg_tape_direction ==
17432 			    DIR_EITH);
17433 			count = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17434 			un->un_running.lgclblkno = count;
17435 			un->un_running.blkno = 0;
17436 			un->un_running.fileno = 0;
17437 			un->un_running.pmode = logical;
17438 			rinfo->pos.lgclblkno = count;
17439 			rinfo->pos.pmode = invalid;
17440 		} else {
17441 			ASSERT(0);
17442 		}
17443 		return;
17444 	}
17445 
17446 	ST_CDB(ST_DEVINFO, "Unhanded CDB for position prediction",
17447 	    (char *)pkt->pkt_cdbp);
17448 
17449 }
17450 
17451 static int
17452 st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf)
17453 {
17454 	struct seq_mode *current;
17455 	int rval;
17456 	int i;
17457 	caddr_t this;
17458 	caddr_t that;
17459 
17460 	ST_FUNC(ST_DEVINFO, st_check_mode_for_change);
17461 
17462 	/* recovery called with mode tamper before mode selection */
17463 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
17464 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17465 		    "Mode Select not done yet");
17466 		return (0);
17467 	}
17468 
17469 	current = kmem_zalloc(sizeof (struct seq_mode), KM_SLEEP);
17470 
17471 	rval = st_gen_mode_sense(un, ubf, un->un_comp_page, current,
17472 	    sizeof (struct seq_mode));
17473 	if (rval != 0) {
17474 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17475 		    "Mode Sense for mode verification failed");
17476 		kmem_free(current, sizeof (struct seq_mode));
17477 		return (rval);
17478 	}
17479 
17480 	this = (caddr_t)current;
17481 	that = (caddr_t)un->un_mspl;
17482 
17483 	rval = bcmp(this, that, sizeof (struct seq_mode));
17484 	if (rval == 0) {
17485 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17486 		    "Found no changes in mode data");
17487 	}
17488 #ifdef STDEBUG
17489 	else {
17490 		for (i = 1; i < sizeof (struct seq_mode); i++) {
17491 			if (this[i] != that[i]) {
17492 				ST_RECOV(ST_DEVINFO, st_label, CE_CONT,
17493 				    "sense data changed at byte %d was "
17494 				    "0x%x now 0x%x", i,
17495 				    (uchar_t)that[i], (uchar_t)this[i]);
17496 			}
17497 		}
17498 	}
17499 #endif
17500 	kmem_free(current, sizeof (struct seq_mode));
17501 
17502 	return (rval);
17503 }
17504 
17505 static int
17506 st_test_path_to_device(struct scsi_tape *un)
17507 {
17508 	int rval = 0;
17509 	int limit = st_retry_count;
17510 
17511 	ST_FUNC(ST_DEVINFO, st_test_path_to_device);
17512 
17513 	/*
17514 	 * XXX Newer drives may not RESEVATION CONFLICT a TUR.
17515 	 */
17516 	do {
17517 		if (rval != 0) {
17518 			mutex_exit(ST_MUTEX);
17519 			delay(drv_usectohz(1000000));
17520 			mutex_enter(ST_MUTEX);
17521 		}
17522 		rval = st_rcmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
17523 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17524 		    "ping TUR returned 0x%x", rval);
17525 		limit--;
17526 	} while (((rval == EACCES) || (rval == EBUSY)) && limit);
17527 
17528 	if (un->un_status == KEY_NOT_READY || un->un_mediastate == MTIO_EJECTED)
17529 		rval = 0;
17530 
17531 	return (rval);
17532 }
17533 
17534 /*
17535  * Does read position using recov_buf and doesn't update un_pos.
17536  * Does what ever kind of read position you want.
17537  */
17538 static int
17539 st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
17540     read_pos_data_t *raw)
17541 {
17542 	int rval;
17543 	struct uscsi_cmd cmd;
17544 	struct scsi_arq_status status;
17545 	char cdb[CDB_GROUP1];
17546 
17547 	ST_FUNC(ST_DEVINFO, st_recovery_read_pos);
17548 	bzero(&cmd, sizeof (cmd));
17549 
17550 	cdb[0] = SCMD_READ_POSITION;
17551 	cdb[1] = type;
17552 	cdb[2] = 0;
17553 	cdb[3] = 0;
17554 	cdb[4] = 0;
17555 	cdb[5] = 0;
17556 	cdb[6] = 0;
17557 	cdb[7] = 0;
17558 	cdb[8] = (type == EXT_POS) ? 28 : 0;
17559 	cdb[9] = 0;
17560 
17561 	cmd.uscsi_flags = USCSI_READ | USCSI_RQENABLE;
17562 	cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
17563 	cmd.uscsi_cdb = cdb;
17564 	cmd.uscsi_cdblen = sizeof (cdb);
17565 	cmd.uscsi_rqlen = sizeof (status);
17566 	cmd.uscsi_rqbuf = (caddr_t)&status;
17567 	cmd.uscsi_bufaddr = (caddr_t)raw;
17568 	switch (type) {
17569 	case SHORT_POS:
17570 		cmd.uscsi_buflen = sizeof (tape_position_t);
17571 		break;
17572 	case LONG_POS:
17573 		cmd.uscsi_buflen = sizeof (tape_position_long_t);
17574 		break;
17575 	case EXT_POS:
17576 		cmd.uscsi_buflen = sizeof (tape_position_ext_t);
17577 		break;
17578 	default:
17579 		ASSERT(0);
17580 	}
17581 
17582 	rval = st_uscsi_rcmd(un, &cmd, FKIOCTL);
17583 	if (cmd.uscsi_status) {
17584 		rval = EIO;
17585 	}
17586 	return (rval);
17587 }
17588 
17589 static int
17590 st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
17591     read_pos_data_t *raw)
17592 {
17593 	int rval;
17594 	read_p_types type = un->un_read_pos_type;
17595 
17596 	ST_FUNC(ST_DEVINFO, st_recovery_get_position);
17597 
17598 	do {
17599 		rval = st_recovery_read_pos(un, type, raw);
17600 		if (rval != 0) {
17601 			switch (type) {
17602 			case SHORT_POS:
17603 				type = NO_POS;
17604 				break;
17605 
17606 			case LONG_POS:
17607 				type = EXT_POS;
17608 				break;
17609 
17610 			case EXT_POS:
17611 				type = SHORT_POS;
17612 				break;
17613 
17614 			default:
17615 				type = LONG_POS;
17616 				break;
17617 
17618 			}
17619 		} else {
17620 			if (type != un->un_read_pos_type) {
17621 				un->un_read_pos_type = type;
17622 			}
17623 			break;
17624 		}
17625 	} while (type != NO_POS);
17626 
17627 	if (rval == 0) {
17628 		rval = st_interpret_read_pos(un, read, type,
17629 		    sizeof (read_pos_data_t), (caddr_t)raw, 1);
17630 	}
17631 	return (rval);
17632 }
17633 
17634 /*
17635  * based on the command do we retry, continue or give up?
17636  * possable return values?
17637  *	zero do nothing looks fine.
17638  *	EAGAIN retry.
17639  *	EIO failed makes no sense.
17640  */
17641 static int
17642 st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
17643     cmd_attribute const * cmd_att, tapepos_t *read)
17644 {
17645 	int rval;
17646 	read_pos_data_t *readp_datap;
17647 
17648 	ST_FUNC(ST_DEVINFO, st_compare_expected_position);
17649 
17650 	ASSERT(un != NULL);
17651 	ASSERT(ei != NULL);
17652 	ASSERT(read != NULL);
17653 	ASSERT(cmd_att->chg_tape_pos);
17654 
17655 	COPY_POS(read, &ei->ei_expected_pos);
17656 
17657 	readp_datap = kmem_zalloc(sizeof (read_pos_data_t), KM_SLEEP);
17658 
17659 	rval = st_recovery_get_position(un, read, readp_datap);
17660 
17661 	kmem_free(readp_datap, sizeof (read_pos_data_t));
17662 
17663 	if (rval != 0) {
17664 		return (EIO);
17665 	}
17666 
17667 	ST_POS(ST_DEVINFO, "st_compare_expected_position", read);
17668 
17669 	if ((read->pmode == invalid) ||
17670 	    (ei->ei_expected_pos.pmode == invalid)) {
17671 		return (EIO);
17672 	}
17673 
17674 	/*
17675 	 * Command that changes tape position and have an expected position
17676 	 * if it were to chave completed sucessfully.
17677 	 */
17678 	if (cmd_att->recov_pos_type == POS_EXPECTED) {
17679 		uint32_t count;
17680 		int64_t difference;
17681 		uchar_t reposition = 0;
17682 
17683 		ASSERT(cmd_att->get_cnt);
17684 		count = cmd_att->get_cnt(ei->ei_failed_pkt.pkt_cdbp);
17685 
17686 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17687 		    "Got count from CDB and it was %d\n", count);
17688 
17689 		/*
17690 		 * At expected?
17691 		 */
17692 		if (read->lgclblkno == ei->ei_expected_pos.lgclblkno) {
17693 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17694 			    "Found drive to be at expected position\n");
17695 
17696 			/*
17697 			 * If the command should move tape and it got a busy
17698 			 * it shouldn't be in the expected position.
17699 			 */
17700 			if (ei->ei_failing_status.sts_status.sts_busy != 0) {
17701 				reposition = 1;
17702 
17703 			/*
17704 			 * If the command doesn't transfer data should be good.
17705 			 */
17706 			} else if (cmd_att->transfers_data == TRAN_NONE) {
17707 				return (0); /* Good */
17708 
17709 			/*
17710 			 * Command transfers data, should have done so.
17711 			 */
17712 			} else if (ei->ei_failed_pkt.pkt_state &
17713 			    STATE_XFERRED_DATA) {
17714 				return (0); /* Good */
17715 			} else {
17716 				reposition = 1;
17717 			}
17718 		}
17719 
17720 		if (cmd_att->chg_tape_direction == DIR_FORW) {
17721 			difference =
17722 			    ei->ei_expected_pos.lgclblkno - read->lgclblkno;
17723 
17724 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17725 			    "difference between expected and actual is %"
17726 			    PRId64"\n", difference);
17727 			if (count == difference && reposition == 0) {
17728 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17729 				    "Found failed FORW command, retrying\n");
17730 				return (EAGAIN);
17731 			}
17732 
17733 			/*
17734 			 * If rewound or somewhere between the starting position
17735 			 * and the expected position (partial read or write).
17736 			 * Locate to the starting position and try the whole
17737 			 * thing over again.
17738 			 */
17739 			if ((read->lgclblkno == 0) ||
17740 			    ((difference > 0) && (difference < count))) {
17741 				rval = st_logical_block_locate(un,
17742 				    st_uscsi_rcmd, read,
17743 				    ei->ei_expected_pos.lgclblkno - count,
17744 				    ei->ei_expected_pos.partition);
17745 				if (rval == 0) {
17746 					ST_RECOV(ST_DEVINFO, st_label,
17747 					    CE_NOTE, "reestablished FORW"
17748 					    " command retrying\n");
17749 					return (EAGAIN);
17750 				}
17751 			/*
17752 			 * This handles flushed read ahead on the drive or
17753 			 * an aborted read that presents as a busy and advanced
17754 			 * the tape position.
17755 			 */
17756 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17757 			    ((difference < 0) || (reposition == 1))) {
17758 				rval = st_logical_block_locate(un,
17759 				    st_uscsi_rcmd, read,
17760 				    ei->ei_expected_pos.lgclblkno - count,
17761 				    ei->ei_expected_pos.partition);
17762 				if (rval == 0) {
17763 					ST_RECOV(ST_DEVINFO, st_label,
17764 					    CE_NOTE, "reestablished FORW"
17765 					    " read command retrying\n");
17766 					return (EAGAIN);
17767 				}
17768 			/*
17769 			 * XXX swag seeing difference of 2 on write filemark.
17770 			 * If the space to the starting position works on a
17771 			 * write that means the previous write made it to tape.
17772 			 * If not we lost data and have to give up.
17773 			 *
17774 			 * The plot thickens. Now I am attempting to cover a
17775 			 * count of 1 and a differance of 2 on a write.
17776 			 */
17777 			} else if ((difference > count) || (reposition == 1)) {
17778 				rval = st_logical_block_locate(un,
17779 				    st_uscsi_rcmd, read,
17780 				    ei->ei_expected_pos.lgclblkno - count,
17781 				    ei->ei_expected_pos.partition);
17782 				if (rval == 0) {
17783 					ST_RECOV(ST_DEVINFO, st_label,
17784 					    CE_NOTE, "reestablished FORW"
17785 					    " write command retrying\n");
17786 					return (EAGAIN);
17787 				}
17788 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17789 				    "Seek to block %"PRId64" returned %d\n",
17790 				    ei->ei_expected_pos.lgclblkno - count,
17791 				    rval);
17792 			} else {
17793 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17794 				    "Not expected transfers_data = %d "
17795 				    "difference = %"PRId64,
17796 				    cmd_att->transfers_data, difference);
17797 			}
17798 
17799 			return (EIO);
17800 
17801 		} else if (cmd_att->chg_tape_direction == DIR_REVC) {
17802 			/* Don't think we can write backwards */
17803 			ASSERT(cmd_att->transfers_data != TRAN_WRTE);
17804 			difference =
17805 			    read->lgclblkno - ei->ei_expected_pos.lgclblkno;
17806 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17807 			    "difference between expected and actual is %"
17808 			    PRId64"\n", difference);
17809 			if (count == difference && reposition == 0) {
17810 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17811 				    "Found failed REVC command, retrying\n");
17812 				return (EAGAIN);
17813 			}
17814 			if ((read->lgclblkno == 0) ||
17815 			    ((difference > 0) && (difference < count))) {
17816 				rval = st_logical_block_locate(un,
17817 				    st_uscsi_rcmd, read,
17818 				    ei->ei_expected_pos.lgclblkno + count,
17819 				    ei->ei_expected_pos.partition);
17820 				if (rval == 0) {
17821 					ST_RECOV(ST_DEVINFO, st_label,
17822 					    CE_NOTE, "reestablished REVC"
17823 					    " command retrying\n");
17824 					return (EAGAIN);
17825 				}
17826 			/* This handles read ahead in reverse direction */
17827 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17828 			    (difference < 0) || (reposition == 1)) {
17829 				rval = st_logical_block_locate(un,
17830 				    st_uscsi_rcmd, read,
17831 				    ei->ei_expected_pos.lgclblkno - count,
17832 				    ei->ei_expected_pos.partition);
17833 				if (rval == 0) {
17834 					ST_RECOV(ST_DEVINFO, st_label,
17835 					    CE_NOTE, "reestablished REVC"
17836 					    " read command retrying\n");
17837 					return (EAGAIN);
17838 				}
17839 			} else {
17840 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17841 				    "Not expected transfers_data = %d "
17842 				    "difference = %"PRId64,
17843 				    cmd_att->transfers_data, difference);
17844 			}
17845 			return (EIO);
17846 
17847 		} else {
17848 			/*
17849 			 * Commands that change tape position either
17850 			 * direction or don't change position should not
17851 			 * get here.
17852 			 */
17853 			ASSERT(0);
17854 		}
17855 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17856 		    "Didn't find a recoverable position, Failing\n");
17857 
17858 	/*
17859 	 * Command that changes tape position and can only be recovered
17860 	 * by going back to the point of origin and retrying.
17861 	 *
17862 	 * Example SCMD_SPACE.
17863 	 */
17864 	} else if (cmd_att->recov_pos_type == POS_STARTING) {
17865 		/*
17866 		 * This type of command stores the starting position.
17867 		 * If the read position is the starting position,
17868 		 * reissue the command.
17869 		 */
17870 		if (ei->ei_expected_pos.lgclblkno == read->lgclblkno) {
17871 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17872 			    "Found Space command at starting position, "
17873 			    "Reissuing\n");
17874 			return (EAGAIN);
17875 		}
17876 		/*
17877 		 * Not in the position that the command was originally issued,
17878 		 * Attempt to locate to that position.
17879 		 */
17880 		rval = st_logical_block_locate(un, st_uscsi_rcmd, read,
17881 		    ei->ei_expected_pos.lgclblkno,
17882 		    ei->ei_expected_pos.partition);
17883 		if (rval) {
17884 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17885 			    "Found Space at an unexpected position and locate "
17886 			    "back to starting position failed\n");
17887 			return (EIO);
17888 		}
17889 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17890 		    "Found Space at an unexpected position and locate "
17891 		    "back to starting position worked, Reissuing\n");
17892 		return (EAGAIN);
17893 	}
17894 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17895 	    "Unhandled attribute/expected position", &ei->ei_expected_pos);
17896 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17897 	    "Read position above did not make sense", read);
17898 	ASSERT(0);
17899 	return (EIO);
17900 }
17901 
17902 static errstate
17903 st_recover_reissue_pkt(struct scsi_tape *un, struct scsi_pkt *oldpkt)
17904 {
17905 	buf_t *bp;
17906 	buf_t *pkt_bp;
17907 	struct scsi_pkt *newpkt;
17908 	cmd_attribute const *attrib;
17909 	recov_info *rcv = oldpkt->pkt_private;
17910 	uint_t cdblen;
17911 	int queued = 0;
17912 	int rval;
17913 	int flags = 0;
17914 	int stat_size =
17915 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
17916 
17917 	ST_FUNC(ST_DEVINFO, st_recover_reissue_pkt);
17918 
17919 	bp = rcv->cmd_bp;
17920 
17921 	if (rcv->privatelen == sizeof (recov_info)) {
17922 		attrib = rcv->cmd_attrib;
17923 	} else {
17924 		attrib = st_lookup_cmd_attribute(oldpkt->pkt_cdbp[0]);
17925 	}
17926 
17927 	/*
17928 	 * Some non-uscsi commands use the b_bcount for values that
17929 	 * have nothing to do with how much data is transfered.
17930 	 * In those cases we need to hide the buf_t from scsi_init_pkt().
17931 	 */
17932 	if ((BP_UCMD(bp)) && (bp->b_bcount)) {
17933 		pkt_bp = bp;
17934 	} else if (attrib->transfers_data == TRAN_NONE) {
17935 		pkt_bp = NULL;
17936 	} else {
17937 		pkt_bp = bp;
17938 	}
17939 
17940 	/*
17941 	 * if this is a queued command make sure it the only one in the
17942 	 * run queue.
17943 	 */
17944 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
17945 		ASSERT(un->un_runqf == un->un_runql);
17946 		ASSERT(un->un_runqf == bp);
17947 		queued = 1;
17948 	}
17949 
17950 	cdblen = scsi_cdb_size[CDB_GROUPID(oldpkt->pkt_cdbp[0])];
17951 
17952 	if (pkt_bp == un->un_rqs_bp) {
17953 		flags |= PKT_CONSISTENT;
17954 		stat_size = 1;
17955 	}
17956 
17957 	newpkt = scsi_init_pkt(ROUTE, NULL, pkt_bp, cdblen,
17958 	    stat_size, rcv->privatelen, flags, NULL_FUNC, NULL);
17959 	if (newpkt == NULL) {
17960 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17961 		    "Reissue pkt scsi_init_pkt() failure\n");
17962 		return (COMMAND_DONE_ERROR);
17963 	}
17964 
17965 	ASSERT(newpkt->pkt_resid == 0);
17966 	bp->b_flags &= ~(B_DONE);
17967 	bp->b_resid = 0;
17968 	st_bioerror(bp, 0);
17969 
17970 	bcopy(oldpkt->pkt_private, newpkt->pkt_private, rcv->privatelen);
17971 
17972 	newpkt->pkt_comp = oldpkt->pkt_comp;
17973 	newpkt->pkt_time = oldpkt->pkt_time;
17974 
17975 	bzero(newpkt->pkt_scbp, stat_size);
17976 	bcopy(oldpkt->pkt_cdbp, newpkt->pkt_cdbp, cdblen);
17977 
17978 	newpkt->pkt_state = 0;
17979 	newpkt->pkt_statistics = 0;
17980 
17981 	/*
17982 	 * oldpkt passed in was a copy of the original.
17983 	 * to distroy we need the address of the original.
17984 	 */
17985 	oldpkt = BP_PKT(bp);
17986 
17987 	if (oldpkt == un->un_rqs) {
17988 		ASSERT(bp == un->un_rqs_bp);
17989 		un->un_rqs = newpkt;
17990 	}
17991 
17992 	SET_BP_PKT(bp, newpkt);
17993 
17994 	scsi_destroy_pkt(oldpkt);
17995 
17996 	rval = st_transport(un, newpkt);
17997 	if (rval == TRAN_ACCEPT) {
17998 		return (JUST_RETURN);
17999 	}
18000 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
18001 	    "Reissue pkt st_transport(0x%x) failure\n", rval);
18002 	if (rval != TRAN_BUSY) {
18003 		return (COMMAND_DONE_ERROR);
18004 	}
18005 	mutex_exit(ST_MUTEX);
18006 	rval = st_handle_start_busy(un, bp, ST_TRAN_BUSY_TIMEOUT, queued);
18007 	mutex_enter(ST_MUTEX);
18008 	if (rval) {
18009 		return (COMMAND_DONE_ERROR);
18010 	}
18011 
18012 	return (JUST_RETURN);
18013 }
18014 
18015 static int
18016 st_transport(struct scsi_tape *un, struct scsi_pkt *pkt)
18017 {
18018 	int status;
18019 
18020 	ST_FUNC(ST_DEVINFO, st_transport);
18021 
18022 	ST_CDB(ST_DEVINFO, "transport CDB", (caddr_t)pkt->pkt_cdbp);
18023 
18024 	mutex_exit(ST_MUTEX);
18025 
18026 	status = scsi_transport(pkt);
18027 
18028 	mutex_enter(ST_MUTEX);
18029 
18030 	return (status);
18031 }
18032 
18033 /*
18034  * Removed the buf_t bp from the queue referenced to by head and tail.
18035  * Returns the buf_t pointer if it is found in the queue.
18036  * Returns NULL if it is not found.
18037  */
18038 static buf_t *
18039 st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp)
18040 {
18041 	buf_t *runqbp;
18042 	buf_t *prevbp = NULL;
18043 
18044 	for (runqbp = *head; runqbp != 0; runqbp = runqbp->av_forw) {
18045 		if (runqbp == bp) {
18046 			/* found it, is it at the head? */
18047 			if (runqbp == *head) {
18048 				*head = bp->av_forw;
18049 			} else {
18050 				prevbp->av_forw = bp->av_forw;
18051 			}
18052 			if (*tail == bp) {
18053 				*tail = prevbp;
18054 			}
18055 			bp->av_forw = NULL;
18056 			return (bp); /* found and removed */
18057 		}
18058 		prevbp = runqbp;
18059 	}
18060 	return (NULL);
18061 }
18062 
18063 /*
18064  * Adds a buf_t to the queue pointed to by head and tail.
18065  * Adds it either to the head end or the tail end based on which
18066  * the passed variable end (head or tail) points at.
18067  */
18068 static void
18069 st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp)
18070 {
18071 
18072 	bp->av_forw = NULL;
18073 	if (*head) {
18074 		/* Queue is not empty */
18075 		if (end == *head) {
18076 			/* Add at front of queue */
18077 			bp->av_forw = *head;
18078 			*head = bp;
18079 		} else if (end == *tail) {
18080 			/* Add at end of queue */
18081 			(*tail)->av_forw = bp;
18082 			*tail = bp;
18083 		} else {
18084 			ASSERT(0);
18085 		}
18086 	} else {
18087 		/* Queue is empty */
18088 		*head = bp;
18089 		*tail = bp;
18090 	}
18091 }
18092 
18093 
18094 static uint64_t
18095 st_get_cdb_g0_rw_count(uchar_t *cdb)
18096 {
18097 	uint64_t count;
18098 
18099 	if ((cdb[1]) & 1) {
18100 		/* fixed block mode, the count is the number of blocks */
18101 		count =
18102 		    cdb[2] << 16 |
18103 		    cdb[3] << 8 |
18104 		    cdb[4];
18105 	} else {
18106 		/* variable block mode, the count is the block size */
18107 		count = 1;
18108 	}
18109 	return (count);
18110 }
18111 
18112 static uint64_t
18113 st_get_cdb_g0_sign_count(uchar_t *cdb)
18114 {
18115 	uint64_t count;
18116 
18117 	count =
18118 	    cdb[2] << 16 |
18119 	    cdb[3] << 8 |
18120 	    cdb[4];
18121 	/*
18122 	 * If the sign bit of the 3 byte value is set, extended it.
18123 	 */
18124 	if (count & 0x800000) {
18125 		count |= 0xffffffffff000000;
18126 	}
18127 	return (count);
18128 }
18129 
18130 static uint64_t
18131 st_get_cdb_g0_count(uchar_t *cdb)
18132 {
18133 	uint64_t count;
18134 
18135 	count =
18136 	    cdb[2] << 16 |
18137 	    cdb[3] << 8 |
18138 	    cdb[4];
18139 	return (count);
18140 }
18141 
18142 static uint64_t
18143 st_get_cdb_g5_rw_cnt(uchar_t *cdb)
18144 {
18145 	uint64_t count;
18146 
18147 	if ((cdb[1]) & 1) {
18148 		/* fixed block mode */
18149 		count =
18150 		    cdb[12] << 16 |
18151 		    cdb[13] << 8 |
18152 		    cdb[14];
18153 	} else {
18154 		/* variable block mode */
18155 		count = 1;
18156 	}
18157 	return (count);
18158 }
18159 
18160 static uint64_t
18161 st_get_no_count(uchar_t *cdb)
18162 {
18163 	ASSERT(cdb[0] == SCMD_REWIND);
18164 	return ((uint64_t)cdb[0]);
18165 }
18166 
18167 static uint64_t
18168 st_get_load_options(uchar_t *cdb)
18169 {
18170 	return ((uint64_t)(cdb[4] | (LD_HOLD << 1)));
18171 }
18172 
18173 static uint64_t
18174 st_get_erase_options(uchar_t *cdb)
18175 {
18176 	return (cdb[1] | (cdb[0] << 8));
18177 }
18178 
18179 static uint64_t
18180 st_get_cdb_g1_lba(uchar_t *cdb)
18181 {
18182 	uint64_t lba;
18183 
18184 	lba =
18185 	    cdb[3] << 24 |
18186 	    cdb[4] << 16 |
18187 	    cdb[5] << 8 |
18188 	    cdb[6];
18189 	return (lba);
18190 }
18191 
18192 static uint64_t
18193 st_get_cdb_g5_count(uchar_t *cdb)
18194 {
18195 	uint64_t count =
18196 	    cdb[12] << 16 |
18197 	    cdb[13] << 8 |
18198 	    cdb[14];
18199 
18200 	return (count);
18201 }
18202 
18203 static uint64_t
18204 st_get_cdb_g4g5_cnt(uchar_t *cdb)
18205 {
18206 	uint64_t lba;
18207 
18208 	lba =
18209 	    (uint64_t)cdb[4] << 56 |
18210 	    (uint64_t)cdb[5] << 48 |
18211 	    (uint64_t)cdb[6] << 40 |
18212 	    (uint64_t)cdb[7] << 32 |
18213 	    (uint64_t)cdb[8] << 24 |
18214 	    (uint64_t)cdb[9] << 16 |
18215 	    (uint64_t)cdb[10] << 8 |
18216 	    (uint64_t)cdb[11];
18217 	return (lba);
18218 }
18219 
18220 static const cmd_attribute cmd_attributes[] = {
18221 	{ SCMD_READ,
18222 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_READ, POS_EXPECTED,
18223 	    0, 0, 0, st_get_cdb_g0_rw_count },
18224 	{ SCMD_WRITE,
18225 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18226 	    0, 0, 0, st_get_cdb_g0_rw_count },
18227 	{ SCMD_TEST_UNIT_READY,
18228 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18229 	    0, 0, 0 },
18230 	{ SCMD_REWIND,
18231 	    1, 1, 1, 0, 0, DIR_REVC, TRAN_NONE, POS_EXPECTED,
18232 	    0, 0, 0, st_get_no_count },
18233 	{ SCMD_REQUEST_SENSE,
18234 	    0, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18235 	    0, 0, 0 },
18236 	{ SCMD_READ_BLKLIM,
18237 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18238 	    0, 0, 0 },
18239 	{ SCMD_READ_G4,
18240 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_READ, POS_EXPECTED,
18241 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18242 	{ SCMD_WRITE_G4,
18243 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18244 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18245 	{ SCMD_READ_REVERSE,
18246 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18247 	    0, 0, 0, st_get_cdb_g0_rw_count },
18248 	{ SCMD_READ_REVERSE_G4,
18249 	    1, 0, 1, 1, 1, DIR_REVC, TRAN_READ, POS_EXPECTED,
18250 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18251 	{ SCMD_WRITE_FILE_MARK,
18252 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18253 	    0, 0, 0, st_get_cdb_g0_count },
18254 	{ SCMD_WRITE_FILE_MARK_G4,
18255 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18256 	    0, 0, 0, st_get_cdb_g5_count, st_get_cdb_g4g5_cnt },
18257 	{ SCMD_SPACE,
18258 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18259 	    0, 0, 0, st_get_cdb_g0_sign_count },
18260 	{ SCMD_SPACE_G4,
18261 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18262 	    0, 0, 0, st_get_cdb_g4g5_cnt },
18263 	{ SCMD_INQUIRY,
18264 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18265 	    0, 0, 0 },
18266 	{ SCMD_VERIFY_G0,
18267 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18268 	    0, 0, 0, st_get_cdb_g0_rw_count },
18269 	{ SCMD_VERIFY_G4,
18270 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18271 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18272 	{ SCMD_RECOVER_BUF,
18273 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18274 	    0, 0, 0 },
18275 	{ SCMD_MODE_SELECT,
18276 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18277 	    0, 0, 0 },
18278 	{ SCMD_RESERVE,
18279 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18280 	    0, 0, 0 },
18281 	{ SCMD_RELEASE,
18282 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18283 	    0, 0, 0 },
18284 	{ SCMD_ERASE,
18285 	    1, 0, 1, 1, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18286 	    0, 0, 0, st_get_erase_options },
18287 	{ SCMD_MODE_SENSE,
18288 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18289 	    0, 0, 0 },
18290 	{ SCMD_LOAD,
18291 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18292 	    0, 0, 0, st_get_load_options },
18293 	{ SCMD_GDIAG,
18294 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18295 	    1, 0, 0 },
18296 	{ SCMD_SDIAG,
18297 	    1, 0, 1, 1, 0, DIR_EITH, TRAN_WRTE, POS_EXPECTED,
18298 	    1, 0, 0 },
18299 	{ SCMD_DOORLOCK,
18300 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18301 	    0, 4, 3 },
18302 	{ SCMD_LOCATE,
18303 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18304 	    0, 0, 0, NULL, st_get_cdb_g1_lba },
18305 	{ SCMD_READ_POSITION,
18306 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18307 	    0, 0, 0 },
18308 	{ SCMD_WRITE_BUFFER,
18309 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18310 	    1, 0, 0 },
18311 	{ SCMD_READ_BUFFER,
18312 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18313 	    1, 0, 0 },
18314 	{ SCMD_REPORT_DENSITIES,
18315 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18316 	    0, 0, 0 },
18317 	{ SCMD_LOG_SELECT_G1,
18318 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18319 	    0, 0, 0 },
18320 	{ SCMD_LOG_SENSE_G1,
18321 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18322 	    0, 0, 0 },
18323 	{ SCMD_PRIN,
18324 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18325 	    0, 0, 0 },
18326 	{ SCMD_PROUT,
18327 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18328 	    0, 0, 0 },
18329 	{ SCMD_READ_ATTRIBUTE,
18330 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18331 	    0, 0, 0 },
18332 	{ SCMD_WRITE_ATTRIBUTE,
18333 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18334 	    0, 0, 0 },
18335 	{ SCMD_LOCATE_G4,
18336 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18337 	    0, 0, 0, NULL, st_get_cdb_g4g5_cnt },
18338 	{ SCMD_REPORT_LUNS,
18339 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18340 	    0, 0, 0 },
18341 	{ SCMD_SVC_ACTION_IN_G5,
18342 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18343 	    0, 0, 0 },
18344 	{ SCMD_MAINTENANCE_IN,
18345 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18346 	    0, 0, 0 },
18347 	{ SCMD_MAINTENANCE_OUT,
18348 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18349 	    0, 0, 0 },
18350 	{ 0xff, /* Default attribute for unsupported commands */
18351 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_STARTING,
18352 	    1, 0, 0, NULL, NULL }
18353 };
18354 
18355 static const cmd_attribute *
18356 st_lookup_cmd_attribute(unsigned char cmd)
18357 {
18358 	int i;
18359 	cmd_attribute const *attribute;
18360 
18361 	for (i = 0; i < ST_NUM_MEMBERS(cmd_attributes); i++) {
18362 		attribute = &cmd_attributes[i];
18363 		if (attribute->cmd == cmd) {
18364 			return (attribute);
18365 		}
18366 	}
18367 	ASSERT(attribute);
18368 	return (attribute);
18369 }
18370 
18371 static int
18372 st_reset(struct scsi_tape *un, int reset_type)
18373 {
18374 	int rval;
18375 
18376 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
18377 
18378 	ST_FUNC(ST_DEVINFO, st_reset);
18379 	un->un_rsvd_status |= ST_INITIATED_RESET;
18380 	mutex_exit(ST_MUTEX);
18381 	do {
18382 		rval = scsi_reset(&un->un_sd->sd_address, reset_type);
18383 		if (rval == 0) {
18384 			switch (reset_type) {
18385 			case RESET_LUN:
18386 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18387 				    "LUN reset failed trying target reset");
18388 				reset_type = RESET_TARGET;
18389 				break;
18390 			case RESET_TARGET:
18391 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18392 				    "target reset failed trying bus reset");
18393 				reset_type = RESET_BUS;
18394 				break;
18395 			case RESET_BUS:
18396 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18397 				    "bus reset failed trying all reset");
18398 				reset_type = RESET_ALL;
18399 			default:
18400 				mutex_enter(ST_MUTEX);
18401 				return (rval);
18402 			}
18403 		}
18404 	} while (rval == 0);
18405 	mutex_enter(ST_MUTEX);
18406 	return (rval);
18407 }
18408 
18409 
18410 static void
18411 st_reset_notification(caddr_t arg)
18412 {
18413 	struct scsi_tape *un = (struct scsi_tape *)arg;
18414 
18415 	ST_FUNC(ST_DEVINFO, st_reset_notification);
18416 	mutex_enter(ST_MUTEX);
18417 
18418 	un->un_unit_attention_flags |= 2;
18419 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
18420 	    ST_RESERVE) {
18421 		un->un_rsvd_status |= ST_LOST_RESERVE;
18422 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18423 		    "Lost Reservation notification");
18424 	} else {
18425 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18426 		    "reset notification");
18427 	}
18428 
18429 	if ((un->un_restore_pos == 0) &&
18430 	    (un->un_state == ST_STATE_CLOSED) ||
18431 	    (un->un_state == ST_STATE_OPEN_PENDING_IO) ||
18432 	    (un->un_state == ST_STATE_CLOSING)) {
18433 		un->un_restore_pos = 1;
18434 	}
18435 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
18436 	    "reset and state was %d\n", un->un_state);
18437 	mutex_exit(ST_MUTEX);
18438 }
18439