xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/st.c (revision 3b5ccf6b95a705120c7f7fa193afabfd40dc7342)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  *  Copyright (c) 1990, 2010, Oracle and/or its affiliates. All rights reserved.
24  *  Copyright (c) 2011 Bayard G. Bell. All rights reserved.
25  */
26 
27 /*
28  * SCSI	 SCSA-compliant and not-so-DDI-compliant Tape Driver
29  */
30 
31 #if defined(lint) && !defined(DEBUG)
32 #define	DEBUG	1
33 #endif
34 
35 #include <sys/modctl.h>
36 #include <sys/scsi/scsi.h>
37 #include <sys/mtio.h>
38 #include <sys/scsi/targets/stdef.h>
39 #include <sys/file.h>
40 #include <sys/kstat.h>
41 #include <sys/ddidmareq.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/byteorder.h>
45 
46 #define	IOSP	KSTAT_IO_PTR(un->un_stats)
47 /*
48  * stats maintained only for reads/writes as commands
49  * like rewind etc skew the wait/busy times
50  */
51 #define	IS_RW(bp) 	((bp)->b_bcount > 0)
52 #define	ST_DO_KSTATS(bp, kstat_function) \
53 	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
54 		kstat_function(IOSP); \
55 	}
56 
57 #define	ST_DO_ERRSTATS(un, x)  \
58 	if (un->un_errstats) { \
59 		struct st_errstats *stp; \
60 		stp = (struct st_errstats *)un->un_errstats->ks_data; \
61 		stp->x.value.ul++; \
62 	}
63 
64 #define	FILL_SCSI1_LUN(devp, pkt) 					\
65 	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
66 		int _lun;						\
67 		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
68 		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
69 		if (_lun > 0) {						\
70 			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
71 			    _lun;					\
72 		}							\
73 	}
74 
75 /*
76  * get an available contig mem header, cp.
77  * when big_enough is true, we will return NULL, if no big enough
78  * contig mem is found.
79  * when big_enough is false, we will try to find cp containing big
80  * enough contig mem. if not found, we will ruturn the last cp available.
81  *
82  * used by st_get_contig_mem()
83  */
84 #define	ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough) {		\
85 	struct contig_mem *tmp_cp = NULL;				\
86 	for ((cp) = (un)->un_contig_mem;				\
87 	    (cp) != NULL;						\
88 	    tmp_cp = (cp), (cp) = (cp)->cm_next) { 			\
89 		if (((cp)->cm_len >= (len)) || 				\
90 		    (!(big_enough) && ((cp)->cm_next == NULL))) { 	\
91 			if (tmp_cp == NULL) { 				\
92 				(un)->un_contig_mem = (cp)->cm_next; 	\
93 			} else { 					\
94 				tmp_cp->cm_next = (cp)->cm_next; 	\
95 			} 						\
96 			(cp)->cm_next = NULL; 				\
97 			(un)->un_contig_mem_available_num--; 		\
98 			break; 						\
99 		} 							\
100 	} 								\
101 }
102 
103 #define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
104 #define	COPY_POS(dest, source) bcopy(source, dest, sizeof (tapepos_t))
105 #define	ISALNUM(byte) \
106 	(((byte) >= 'a' && (byte) <= 'z') || \
107 	((byte) >= 'A' && (byte) <= 'Z') || \
108 	((byte) >= '0' && (byte) <= '9'))
109 
110 #define	ONE_K	1024
111 
112 #define	MAX_SPACE_CNT(cnt) if (cnt >= 0) { \
113 		if (cnt > MIN(SP_CNT_MASK, INT32_MAX)) \
114 			return (EINVAL); \
115 	} else { \
116 		if (-(cnt) > MIN(SP_CNT_MASK, INT32_MAX)) \
117 			return (EINVAL); \
118 	} \
119 
120 /*
121  * Global External Data Definitions
122  */
123 extern struct scsi_key_strings scsi_cmds[];
124 extern uchar_t	scsi_cdb_size[];
125 
126 /*
127  * Local Static Data
128  */
129 static void *st_state;
130 static char *const st_label = "st";
131 static volatile int st_recov_sz = sizeof (recov_info);
132 static const char mp_misconf[] = {
133 	"St Tape is misconfigured, MPxIO enabled and "
134 	"tape-command-recovery-disable set in st.conf\n"
135 };
136 
137 #ifdef	__x86
138 /*
139  * We need to use below DMA attr to alloc physically contiguous
140  * memory to do I/O in big block size
141  */
142 static ddi_dma_attr_t st_contig_mem_dma_attr = {
143 	DMA_ATTR_V0,    /* version number */
144 	0x0,		/* lowest usable address */
145 	0xFFFFFFFFull,  /* high DMA address range */
146 	0xFFFFFFFFull,  /* DMA counter register */
147 	1,		/* DMA address alignment */
148 	1,		/* DMA burstsizes */
149 	1,		/* min effective DMA size */
150 	0xFFFFFFFFull,  /* max DMA xfer size */
151 	0xFFFFFFFFull,  /* segment boundary */
152 	1,		/* s/g list length */
153 	1,		/* granularity of device */
154 	0		/* DMA transfer flags */
155 };
156 
157 static ddi_device_acc_attr_t st_acc_attr = {
158 	DDI_DEVICE_ATTR_V0,
159 	DDI_NEVERSWAP_ACC,
160 	DDI_STRICTORDER_ACC
161 };
162 
163 /* set limitation for the number of contig_mem */
164 static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
165 #endif
166 
167 /*
168  * Tunable parameters
169  *
170  * DISCLAIMER
171  * ----------
172  * These parameters are intended for use only in system testing; if you use
173  * them in production systems, you do so at your own risk. Altering any
174  * variable not listed below may cause unpredictable system behavior.
175  *
176  * st_check_media_time
177  *
178  *   Three second state check
179  *
180  * st_allow_large_xfer
181  *
182  *   Gated with ST_NO_RECSIZE_LIMIT
183  *
184  *   0 - Transfers larger than 64KB will not be allowed
185  *       regardless of the setting of ST_NO_RECSIZE_LIMIT
186  *   1 - Transfers larger than 64KB will be allowed
187  *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
188  *
189  * st_report_soft_errors_on_close
190  *
191  *  Gated with ST_SOFT_ERROR_REPORTING
192  *
193  *  0 - Errors will not be reported on close regardless
194  *      of the setting of ST_SOFT_ERROR_REPORTING
195  *
196  *  1 - Errors will be reported on close if
197  *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
198  */
199 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
200 static int st_retry_count	= ST_RETRY_COUNT;
201 
202 static int st_io_time		= ST_IO_TIME;
203 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
204 
205 static int st_space_time	= ST_SPACE_TIME;
206 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
207 
208 static int st_error_level	= SCSI_ERR_RETRYABLE;
209 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
210 
211 static int st_max_throttle	= ST_MAX_THROTTLE;
212 
213 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
214 
215 static int st_allow_large_xfer = 1;
216 static int st_report_soft_errors_on_close = 1;
217 
218 /*
219  * End of tunable parameters list
220  */
221 
222 
223 
224 /*
225  * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
226  *
227  * Asynchronous I/O's main offering is that it is a non-blocking way to do
228  * reads and writes.  The driver will queue up all the requests it gets and
229  * have them ready to transport to the HBA.  Unfortunately, we cannot always
230  * just ship the I/O requests to the HBA, as there errors and exceptions
231  * that may happen when we don't want the HBA to continue.  Therein comes
232  * the flush-on-errors capability.  If the HBA supports it, then st will
233  * send in st_max_throttle I/O requests at the same time.
234  *
235  * Persistent errors : This was also reasonably simple.  In the interrupt
236  * routines, if there was an error or exception (FM, LEOT, media error,
237  * transport error), the persistent error bits are set and shuts everything
238  * down, but setting the throttle to zero.  If we hit and exception in the
239  * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
240  * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
241  * the appropriate error, and this will preserve order. Of course, depending
242  * on the exception we have to show a zero read or write before we show
243  * errors back to the application.
244  */
245 
246 extern const int st_ndrivetypes;	/* defined in st_conf.c */
247 extern const struct st_drivetype st_drivetypes[];
248 extern const char st_conf_version[];
249 
250 #ifdef STDEBUG
251 static int st_soft_error_report_debug = 0;
252 volatile int st_debug = 0;
253 static volatile dev_info_t *st_lastdev;
254 static kmutex_t st_debug_mutex;
255 #endif
256 
257 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
258 
259 static const struct vid_drivetype {
260 	char	*vid;
261 	char	type;
262 } st_vid_dt[] = {
263 	{"LTO-CVE ",	MT_LTO},
264 	{"QUANTUM ",    MT_ISDLT},
265 	{"SONY    ",    MT_ISAIT},
266 	{"STK     ",	MT_ISSTK9840}
267 };
268 
269 static const struct driver_minor_data {
270 	char	*name;
271 	int	minor;
272 } st_minor_data[] = {
273 	/*
274 	 * The top 4 entries are for the default densities,
275 	 * don't alter their position.
276 	 */
277 	{"",	0},
278 	{"n",	MT_NOREWIND},
279 	{"b",	MT_BSD},
280 	{"bn",	MT_NOREWIND | MT_BSD},
281 	{"l",	MT_DENSITY1},
282 	{"m",	MT_DENSITY2},
283 	{"h",	MT_DENSITY3},
284 	{"c",	MT_DENSITY4},
285 	{"u",	MT_DENSITY4},
286 	{"ln",	MT_DENSITY1 | MT_NOREWIND},
287 	{"mn",	MT_DENSITY2 | MT_NOREWIND},
288 	{"hn",	MT_DENSITY3 | MT_NOREWIND},
289 	{"cn",	MT_DENSITY4 | MT_NOREWIND},
290 	{"un",	MT_DENSITY4 | MT_NOREWIND},
291 	{"lb",	MT_DENSITY1 | MT_BSD},
292 	{"mb",	MT_DENSITY2 | MT_BSD},
293 	{"hb",	MT_DENSITY3 | MT_BSD},
294 	{"cb",	MT_DENSITY4 | MT_BSD},
295 	{"ub",	MT_DENSITY4 | MT_BSD},
296 	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
297 	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
298 	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
299 	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
300 	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
301 };
302 
303 /* strings used in many debug and warning messages */
304 static const char wr_str[]  = "write";
305 static const char rd_str[]  = "read";
306 static const char wrg_str[] = "writing";
307 static const char rdg_str[] = "reading";
308 static const char *space_strs[] = {
309 	"records",
310 	"filemarks",
311 	"sequential filemarks",
312 	"eod",
313 	"setmarks",
314 	"sequential setmarks",
315 	"Reserved",
316 	"Reserved"
317 };
318 static const char *load_strs[] = {
319 	"unload",		/* LD_UNLOAD		0 */
320 	"load",			/* LD_LOAD		1 */
321 	"retension",		/* LD_RETEN		2 */
322 	"load reten",		/* LD_LOAD | LD_RETEN	3 */
323 	"eod",			/* LD_EOT		4 */
324 	"load EOD",		/* LD_LOAD | LD_EOT	5 */
325 	"reten EOD",		/* LD_RETEN | LD_EOT	6 */
326 	"load reten EOD"	/* LD_LOAD|LD_RETEN|LD_EOT 7 */
327 	"hold",			/* LD_HOLD		8 */
328 	"load and hold"		/* LD_LOAD | LD_HOLD	9 */
329 };
330 
331 static const char *errstatenames[] = {
332 	"COMMAND_DONE",
333 	"COMMAND_DONE_ERROR",
334 	"COMMAND_DONE_ERROR_RECOVERED",
335 	"QUE_COMMAND",
336 	"QUE_BUSY_COMMAND",
337 	"QUE_SENSE",
338 	"JUST_RETURN",
339 	"COMMAND_DONE_EACCES",
340 	"QUE_LAST_COMMAND",
341 	"COMMAND_TIMEOUT",
342 	"PATH_FAILED",
343 	"DEVICE_RESET",
344 	"DEVICE_TAMPER",
345 	"ATTEMPT_RETRY"
346 };
347 
348 const char *bogusID = "Unknown Media ID";
349 
350 /* default density offsets in the table above */
351 #define	DEF_BLANK	0
352 #define	DEF_NOREWIND	1
353 #define	DEF_BSD		2
354 #define	DEF_BSD_NR	3
355 
356 /* Sense Key, ASC/ASCQ for which tape ejection is needed */
357 
358 static struct tape_failure_code {
359 	uchar_t key;
360 	uchar_t add_code;
361 	uchar_t qual_code;
362 } st_tape_failure_code[] = {
363 	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
364 	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
365 	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
366 	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
367 	{ KEY_NOT_READY, 0x53, 0x00},
368 	{ 0xff}
369 };
370 
371 /*  clean bit position and mask */
372 
373 static struct cln_bit_position {
374 	ushort_t cln_bit_byte;
375 	uchar_t cln_bit_mask;
376 } st_cln_bit_position[] = {
377 	{ 21, 0x08},
378 	{ 70, 0xc0},
379 	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
380 };
381 
382 /*
383  * architecture dependent allocation restrictions. For x86, we'll set
384  * dma_attr_addr_hi to st_max_phys_addr and dma_attr_sgllen to
385  * st_sgl_size during _init().
386  */
387 #if defined(__sparc)
388 static ddi_dma_attr_t st_alloc_attr = {
389 	DMA_ATTR_V0,	/* version number */
390 	0x0,		/* lowest usable address */
391 	0xFFFFFFFFull,	/* high DMA address range */
392 	0xFFFFFFFFull,	/* DMA counter register */
393 	1,		/* DMA address alignment */
394 	1,		/* DMA burstsizes */
395 	1,		/* min effective DMA size */
396 	0xFFFFFFFFull,	/* max DMA xfer size */
397 	0xFFFFFFFFull,	/* segment boundary */
398 	1,		/* s/g list length */
399 	512,		/* granularity of device */
400 	0		/* DMA transfer flags */
401 };
402 #elif defined(__x86)
403 static ddi_dma_attr_t st_alloc_attr = {
404 	DMA_ATTR_V0,	/* version number */
405 	0x0,		/* lowest usable address */
406 	0x0,		/* high DMA address range [set in _init()] */
407 	0xFFFFull,	/* DMA counter register */
408 	512,		/* DMA address alignment */
409 	1,		/* DMA burstsizes */
410 	1,		/* min effective DMA size */
411 	0xFFFFFFFFull,	/* max DMA xfer size */
412 	0xFFFFFFFFull,  /* segment boundary */
413 	0,		/* s/g list length */
414 	512,		/* granularity of device [set in _init()] */
415 	0		/* DMA transfer flags */
416 };
417 uint64_t st_max_phys_addr = 0xFFFFFFFFull;
418 int st_sgl_size = 0xF;
419 
420 #endif
421 
422 /*
423  * Configuration Data:
424  *
425  * Device driver ops vector
426  */
427 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
428 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
429 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
430 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
431 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
432 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
433 static int st_strategy(struct buf *bp);
434 static int st_queued_strategy(buf_t *bp);
435 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
436 	cred_t *cred_p, int *rval_p);
437 extern int nulldev(), nodev();
438 
439 static struct cb_ops st_cb_ops = {
440 	st_open,		/* open */
441 	st_close,		/* close */
442 	st_queued_strategy,	/* strategy Not Block device but async checks */
443 	nodev,			/* print */
444 	nodev,			/* dump */
445 	st_read,		/* read */
446 	st_write,		/* write */
447 	st_ioctl,		/* ioctl */
448 	nodev,			/* devmap */
449 	nodev,			/* mmap */
450 	nodev,			/* segmap */
451 	nochpoll,		/* poll */
452 	ddi_prop_op,		/* cb_prop_op */
453 	0,			/* streamtab  */
454 	D_64BIT | D_MP | D_NEW | D_HOTPLUG |
455 	D_OPEN_RETURNS_EINTR,	/* cb_flag */
456 	CB_REV,			/* cb_rev */
457 	st_aread, 		/* async I/O read entry point */
458 	st_awrite		/* async I/O write entry point */
459 
460 };
461 
462 static int st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
463 		void **result);
464 static int st_probe(dev_info_t *dev);
465 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
466 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
467 
468 static struct dev_ops st_ops = {
469 	DEVO_REV,		/* devo_rev, */
470 	0,			/* refcnt  */
471 	st_info,		/* info */
472 	nulldev,		/* identify */
473 	st_probe,		/* probe */
474 	st_attach,		/* attach */
475 	st_detach,		/* detach */
476 	nodev,			/* reset */
477 	&st_cb_ops,		/* driver operations */
478 	(struct bus_ops *)0,	/* bus operations */
479 	nulldev,		/* power */
480 	ddi_quiesce_not_needed,	/* devo_quiesce */
481 };
482 
483 /*
484  * Local Function Declarations
485  */
486 static char *st_print_scsi_cmd(char cmd);
487 static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
488     char *title, char *cdb);
489 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
490     char *title, char *data, int len);
491 static int st_doattach(struct scsi_device *devp, int (*canwait)());
492 static void st_known_tape_type(struct scsi_tape *un);
493 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
494     struct st_drivetype *);
495 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
496     struct st_drivetype *);
497 static int st_get_conf_from_tape_drive(struct scsi_tape *, char *,
498     struct st_drivetype *);
499 static int st_get_densities_from_tape_drive(struct scsi_tape *,
500     struct st_drivetype *);
501 static int st_get_timeout_values_from_tape_drive(struct scsi_tape *,
502     struct st_drivetype *);
503 static int st_get_timeouts_value(struct scsi_tape *, uchar_t, ushort_t *,
504     ushort_t);
505 static int st_get_default_conf(struct scsi_tape *, char *,
506     struct st_drivetype *);
507 static int st_rw(dev_t dev, struct uio *uio, int flag);
508 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
509 static int st_find_eod(struct scsi_tape *un);
510 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
511 static int st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *, int flag);
512 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
513 static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
514 static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
515 static void st_start(struct scsi_tape *un);
516 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
517     clock_t timeout_interval, int queued);
518 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
519     clock_t timeout_interval);
520 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
521 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
522 static void st_init(struct scsi_tape *un);
523 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
524     int (*func)(caddr_t));
525 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
526     struct buf *bp, int (*func)(caddr_t));
527 static void st_intr(struct scsi_pkt *pkt);
528 static void st_set_state(struct scsi_tape *un, buf_t *bp);
529 static void st_test_append(struct buf *bp);
530 static int st_runout(caddr_t);
531 static int st_cmd(struct scsi_tape *un, int com, int64_t count, int wait);
532 static int st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com,
533     int64_t count);
534 static int st_set_compression(struct scsi_tape *un);
535 static int st_write_fm(dev_t dev, int wfm);
536 static int st_determine_generic(struct scsi_tape *un);
537 static int st_determine_density(struct scsi_tape *un, int rw);
538 static int st_get_density(struct scsi_tape *un);
539 static int st_set_density(struct scsi_tape *un);
540 static int st_loadtape(struct scsi_tape *un);
541 static int st_modesense(struct scsi_tape *un);
542 static int st_modeselect(struct scsi_tape *un);
543 static errstate st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
544 static int st_wrongtapetype(struct scsi_tape *un);
545 static errstate st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
546 static errstate st_handle_sense(struct scsi_tape *un, struct buf *bp,
547     tapepos_t *);
548 static errstate st_handle_autosense(struct scsi_tape *un, struct buf *bp,
549     tapepos_t *);
550 static int st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag);
551 static void st_update_error_stack(struct scsi_tape *un, struct scsi_pkt *pkt,
552     struct scsi_arq_status *cmd);
553 static void st_empty_error_stack(struct scsi_tape *un);
554 static errstate st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
555     struct scsi_arq_status *, tapepos_t *);
556 static int st_report_soft_errors(dev_t dev, int flag);
557 static void st_delayed_cv_broadcast(void *arg);
558 static int st_check_media(dev_t dev, enum mtio_state state);
559 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
560 static void st_intr_restart(void *arg);
561 static void st_start_restart(void *arg);
562 static int st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
563     struct seq_mode *page_data, int page_size);
564 static int st_change_block_size(struct scsi_tape *un, uint32_t nblksz);
565 static int st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
566     struct seq_mode *page_data, int page_size);
567 static int st_read_block_limits(struct scsi_tape *un,
568     struct read_blklim *read_blk);
569 static int st_report_density_support(struct scsi_tape *un,
570     uchar_t *density_data, size_t buflen);
571 static int st_report_supported_operation(struct scsi_tape *un,
572     uchar_t *oper_data, uchar_t option_code, ushort_t service_action);
573 static int st_tape_init(struct scsi_tape *un);
574 static void st_flush(struct scsi_tape *un);
575 static void st_set_pe_errno(struct scsi_tape *un);
576 static void st_hba_unflush(struct scsi_tape *un);
577 static void st_turn_pe_on(struct scsi_tape *un);
578 static void st_turn_pe_off(struct scsi_tape *un);
579 static void st_set_pe_flag(struct scsi_tape *un);
580 static void st_clear_pe(struct scsi_tape *un);
581 static void st_wait_for_io(struct scsi_tape *un);
582 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
583 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
584 static int st_reserve_release(struct scsi_tape *un, int command, ubufunc_t ubf);
585 static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb);
586 static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
587     int count);
588 static int st_take_ownership(struct scsi_tape *un, ubufunc_t ubf);
589 static int st_check_asc_ascq(struct scsi_tape *un);
590 static int st_check_clean_bit(struct scsi_tape *un);
591 static int st_check_alert_flags(struct scsi_tape *un);
592 static int st_check_sequential_clean_bit(struct scsi_tape *un);
593 static int st_check_sense_clean_bit(struct scsi_tape *un);
594 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
595 static void st_calculate_timeouts(struct scsi_tape *un);
596 static writablity st_is_drive_worm(struct scsi_tape *un);
597 static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
598     void *buf, size_t size, ubufunc_t bufunc);
599 static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
600     caddr_t dest, uchar_t page);
601 static int st_update_block_pos(struct scsi_tape *un, bufunc_t bf,
602     int post_space);
603 static int st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
604     read_p_types type, size_t data_sz, const caddr_t responce, int post_space);
605 static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
606 static int st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf,
607     tapepos_t *pos, uint64_t lblk, uchar_t partition);
608 static int st_mtfsf_ioctl(struct scsi_tape *un, int64_t files);
609 static int st_mtfsr_ioctl(struct scsi_tape *un, int64_t count);
610 static int st_mtbsf_ioctl(struct scsi_tape *un, int64_t files);
611 static int st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count);
612 static int st_mtbsr_ioctl(struct scsi_tape *un, int64_t num);
613 static int st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt);
614 static int st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt);
615 static int st_backward_space_files(struct scsi_tape *un, int64_t count,
616     int infront);
617 static int st_forward_space_files(struct scsi_tape *un, int64_t files);
618 static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
619     int32_t fileno);
620 static int st_space_to_begining_of_file(struct scsi_tape *un);
621 static int st_space_records(struct scsi_tape *un, int64_t records);
622 static int st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc);
623 static errstate st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
624     errstate onentry);
625 static void st_recover(void *arg);
626 static void st_recov_cb(struct scsi_pkt *pkt);
627 static int st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait);
628 static int st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
629     int flag);
630 static void st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
631     struct scsi_pkt *cmd);
632 static int st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf);
633 static int st_test_path_to_device(struct scsi_tape *un);
634 static int st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
635     read_pos_data_t *raw);
636 static int st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
637     read_pos_data_t *raw);
638 static int st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
639     cmd_attribute const * cmd_att, tapepos_t *read);
640 static errstate st_recover_reissue_pkt(struct scsi_tape *us,
641     struct scsi_pkt *pkt);
642 static int st_transport(struct scsi_tape *un, struct scsi_pkt *pkt);
643 static buf_t *st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp);
644 static void st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp);
645 static int st_reset(struct scsi_tape *un, int reset_type);
646 static void st_reset_notification(caddr_t arg);
647 static const cmd_attribute *st_lookup_cmd_attribute(unsigned char cmd);
648 
649 static int st_set_target_TLR_mode(struct scsi_tape *un, ubufunc_t ubf);
650 static int st_make_sure_mode_data_is_correct(struct scsi_tape *un,
651     ubufunc_t ubf);
652 
653 #ifdef	__x86
654 /*
655  * routines for I/O in big block size
656  */
657 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
658 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
659     int alloc_flags);
660 static int st_bigblk_xfer_done(struct buf *bp);
661 static struct buf *st_get_bigblk_bp(struct buf *bp);
662 #endif
663 static void st_print_position(dev_info_t *dev, char *label, uint_t level,
664     const char *comment, tapepos_t *pos);
665 
666 /*
667  * error statistics create/update functions
668  */
669 static int st_create_errstats(struct scsi_tape *, int);
670 static int st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf,
671     tapepos_t *pos);
672 
673 #ifdef STDEBUG
674 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
675 #endif /* STDEBUG */
676 static char *st_dev_name(dev_t dev);
677 
678 #if !defined(lint)
679 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
680     scsi_pkt buf uio scsi_cdb uscsi_cmd))
681 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
682 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", recov_info))
683 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
684 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
685 #endif
686 
687 /*
688  * autoconfiguration routines.
689  */
690 
691 static struct modldrv modldrv = {
692 	&mod_driverops,		/* Type of module. This one is a driver */
693 	"SCSI tape Driver", 	/* Name of the module. */
694 	&st_ops			/* driver ops */
695 };
696 
697 static struct modlinkage modlinkage = {
698 	MODREV_1, &modldrv, NULL
699 };
700 
701 /*
702  * Notes on Post Reset Behavior in the tape driver:
703  *
704  * When the tape drive is opened, the driver  attempts  to make sure that
705  * the tape head is positioned exactly where it was left when it was last
706  * closed  provided  the  medium  is not  changed.  If the tape  drive is
707  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
708  * of position due to reset) will happen when the first tape operation or
709  * I/O occurs.  The repositioning (if required) may not be possible under
710  * certain situations such as when the device firmware not able to report
711  * the medium  change in the REQUEST  SENSE data  because of a reset or a
712  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
713  * extraordinary  situations, where the driver fails to position the head
714  * at its  original  position,  it will fail the open the first  time, to
715  * save the applications from overwriting the data.  All further attempts
716  * to open the tape device will result in the driver  attempting  to load
717  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
718  * indicate  that further  attempts to open the tape device may result in
719  * the tape being  loaded at BOT will be printed on the  console.  If the
720  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
721  * original tape head  position,  will result in the failure of the first
722  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
723  * internal tape position  which will  necessitate  the  applications  to
724  * validate the position by using either a tape  positioning  ioctl (such
725  * as MTREW) or closing and reopening the tape device.
726  *
727  */
728 
729 int
730 _init(void)
731 {
732 	int e;
733 
734 	if (((e = ddi_soft_state_init(&st_state,
735 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
736 		return (e);
737 	}
738 
739 	if ((e = mod_install(&modlinkage)) != 0) {
740 		ddi_soft_state_fini(&st_state);
741 	} else {
742 #ifdef STDEBUG
743 		mutex_init(&st_debug_mutex, NULL, MUTEX_DRIVER, NULL);
744 #endif
745 
746 #if defined(__x86)
747 		/* set the max physical address for iob allocs on x86 */
748 		st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
749 
750 		/*
751 		 * set the sgllen for iob allocs on x86. If this is set less
752 		 * than the number of pages the buffer will take
753 		 * (taking into account alignment), it would force the
754 		 * allocator to try and allocate contiguous pages.
755 		 */
756 		st_alloc_attr.dma_attr_sgllen = st_sgl_size;
757 #endif
758 	}
759 
760 	return (e);
761 }
762 
763 int
764 _fini(void)
765 {
766 	int e;
767 
768 	if ((e = mod_remove(&modlinkage)) != 0) {
769 		return (e);
770 	}
771 
772 #ifdef STDEBUG
773 	mutex_destroy(&st_debug_mutex);
774 #endif
775 
776 	ddi_soft_state_fini(&st_state);
777 
778 	return (e);
779 }
780 
781 int
782 _info(struct modinfo *modinfop)
783 {
784 	return (mod_info(&modlinkage, modinfop));
785 }
786 
787 
788 static int
789 st_probe(dev_info_t *devi)
790 {
791 	int instance;
792 	struct scsi_device *devp;
793 	int rval;
794 
795 #if !defined(__sparc)
796 	char    *tape_prop;
797 	int	tape_prop_len;
798 #endif
799 
800 	ST_ENTR(devi, st_probe);
801 
802 	/* If self identifying device */
803 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
804 		return (DDI_PROBE_DONTCARE);
805 	}
806 
807 #if !defined(__sparc)
808 	/*
809 	 * Since some x86 HBAs have devnodes that look like SCSI as
810 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
811 	 * we check for the presence of the "tape" property.
812 	 */
813 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
814 	    DDI_PROP_CANSLEEP, "tape",
815 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
816 		return (DDI_PROBE_FAILURE);
817 	}
818 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
819 		kmem_free(tape_prop, tape_prop_len);
820 		return (DDI_PROBE_FAILURE);
821 	}
822 	kmem_free(tape_prop, tape_prop_len);
823 #endif
824 
825 	devp = ddi_get_driver_private(devi);
826 	instance = ddi_get_instance(devi);
827 
828 	if (ddi_get_soft_state(st_state, instance) != NULL) {
829 		return (DDI_PROBE_PARTIAL);
830 	}
831 
832 
833 	/*
834 	 * Turn around and call probe routine to see whether
835 	 * we actually have a tape at this SCSI nexus.
836 	 */
837 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
838 
839 		/*
840 		 * In checking the whole inq_dtype byte we are looking at both
841 		 * the Peripheral Qualifier and the Peripheral Device Type.
842 		 * For this driver we are only interested in sequential devices
843 		 * that are connected or capable if connecting to this logical
844 		 * unit.
845 		 */
846 		if (devp->sd_inq->inq_dtype ==
847 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
848 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
849 			    "probe exists\n");
850 			rval = DDI_PROBE_SUCCESS;
851 		} else {
852 			rval = DDI_PROBE_FAILURE;
853 		}
854 	} else {
855 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
856 		    "probe failure: nothing there\n");
857 		rval = DDI_PROBE_FAILURE;
858 	}
859 	scsi_unprobe(devp);
860 	return (rval);
861 }
862 
863 static int
864 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
865 {
866 	int 	instance;
867 	int	wide;
868 	int 	dev_instance;
869 	int	ret_status;
870 	struct	scsi_device *devp;
871 	int	node_ix;
872 	struct	scsi_tape *un;
873 
874 	ST_ENTR(devi, st_attach);
875 
876 	devp = ddi_get_driver_private(devi);
877 	instance = ddi_get_instance(devi);
878 
879 	switch (cmd) {
880 		case DDI_ATTACH:
881 			if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
882 			    "tape-command-recovery-disable", 0) != 0) {
883 				st_recov_sz = sizeof (pkt_info);
884 			}
885 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
886 				return (DDI_FAILURE);
887 			}
888 			break;
889 		case DDI_RESUME:
890 			/*
891 			 * Suspend/Resume
892 			 *
893 			 * When the driver suspended, there might be
894 			 * outstanding cmds and therefore we need to
895 			 * reset the suspended flag and resume the scsi
896 			 * watch thread and restart commands and timeouts
897 			 */
898 
899 			if (!(un = ddi_get_soft_state(st_state, instance))) {
900 				return (DDI_FAILURE);
901 			}
902 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
903 			    un->un_dev);
904 
905 			mutex_enter(ST_MUTEX);
906 
907 			un->un_throttle = un->un_max_throttle;
908 			un->un_tids_at_suspend = 0;
909 			un->un_pwr_mgmt = ST_PWR_NORMAL;
910 
911 			if (un->un_swr_token) {
912 				scsi_watch_resume(un->un_swr_token);
913 			}
914 
915 			/*
916 			 * Restart timeouts
917 			 */
918 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
919 				mutex_exit(ST_MUTEX);
920 				un->un_delay_tid = timeout(
921 				    st_delayed_cv_broadcast, un,
922 				    drv_usectohz((clock_t)
923 				    MEDIA_ACCESS_DELAY));
924 				mutex_enter(ST_MUTEX);
925 			}
926 
927 			if (un->un_tids_at_suspend & ST_HIB_TID) {
928 				mutex_exit(ST_MUTEX);
929 				un->un_hib_tid = timeout(st_intr_restart, un,
930 				    ST_STATUS_BUSY_TIMEOUT);
931 				mutex_enter(ST_MUTEX);
932 			}
933 
934 			ret_status = st_clear_unit_attentions(dev_instance, 5);
935 
936 			/*
937 			 * now check if we need to restore the tape position
938 			 */
939 			if ((un->un_suspend_pos.pmode != invalid) &&
940 			    ((un->un_suspend_pos.fileno > 0) ||
941 			    (un->un_suspend_pos.blkno > 0)) ||
942 			    (un->un_suspend_pos.lgclblkno > 0)) {
943 				if (ret_status != 0) {
944 					/*
945 					 * tape didn't get good TUR
946 					 * just print out error messages
947 					 */
948 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
949 					    "st_attach-RESUME: tape failure "
950 					    " tape position will be lost");
951 				} else {
952 					/* this prints errors */
953 					(void) st_validate_tapemarks(un,
954 					    st_uscsi_cmd, &un->un_suspend_pos);
955 				}
956 				/*
957 				 * there are no retries, if there is an error
958 				 * we don't know if the tape has changed
959 				 */
960 				un->un_suspend_pos.pmode = invalid;
961 			}
962 
963 			/* now we are ready to start up any queued I/Os */
964 			if (un->un_ncmds || un->un_quef) {
965 				st_start(un);
966 			}
967 
968 			cv_broadcast(&un->un_suspend_cv);
969 			mutex_exit(ST_MUTEX);
970 			return (DDI_SUCCESS);
971 
972 		default:
973 			return (DDI_FAILURE);
974 	}
975 
976 	un = ddi_get_soft_state(st_state, instance);
977 
978 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
979 	    "st_attach: instance=%x\n", instance);
980 
981 	/*
982 	 * Add a zero-length attribute to tell the world we support
983 	 * kernel ioctls (for layered drivers)
984 	 */
985 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
986 	    DDI_KERNEL_IOCTL, NULL, 0);
987 
988 	ddi_report_dev((dev_info_t *)devi);
989 
990 	/*
991 	 * If it's a SCSI-2 tape drive which supports wide,
992 	 * tell the host adapter to use wide.
993 	 */
994 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
995 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
996 
997 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
998 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
999 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
1000 	}
1001 
1002 	/*
1003 	 * enable autorequest sense; keep the rq packet around in case
1004 	 * the autorequest sense fails because of a busy condition
1005 	 * do a getcap first in case the capability is not variable
1006 	 */
1007 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
1008 		un->un_arq_enabled = 1;
1009 	} else {
1010 		un->un_arq_enabled =
1011 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
1012 	}
1013 
1014 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
1015 	    (un->un_arq_enabled ? "enabled" : "disabled"));
1016 
1017 	un->un_untagged_qing =
1018 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
1019 
1020 	/*
1021 	 * XXX - This is just for 2.6.  to tell users that write buffering
1022 	 *	has gone away.
1023 	 */
1024 	if (un->un_arq_enabled && un->un_untagged_qing) {
1025 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
1026 		    "tape-driver-buffering", 0) != 0) {
1027 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1028 			    "Write Data Buffering has been depricated. Your "
1029 			    "applications should continue to work normally.\n"
1030 			    " But, they should  ported to use Asynchronous "
1031 			    " I/O\n"
1032 			    " For more information, read about "
1033 			    " tape-driver-buffering "
1034 			    "property in the st(7d) man page\n");
1035 		}
1036 	}
1037 
1038 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
1039 	un->un_flush_on_errors = 0;
1040 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
1041 
1042 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
1043 	    "throttle=%x, max_throttle = %x\n",
1044 	    un->un_throttle, un->un_max_throttle);
1045 
1046 	/* initialize persistent errors to nil */
1047 	un->un_persistence = 0;
1048 	un->un_persist_errors = 0;
1049 
1050 	/*
1051 	 * Get dma-max from HBA driver. If it is not defined, use 64k
1052 	 */
1053 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
1054 	if (un->un_maxdma == -1) {
1055 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1056 		    "Received a value that looked like -1. Using 64k maxdma");
1057 		un->un_maxdma = (64 * ONE_K);
1058 	}
1059 
1060 #ifdef	__x86
1061 	/*
1062 	 * for x86, the device may be able to DMA more than the system will
1063 	 * allow under some circumstances. We need account for both the HBA's
1064 	 * and system's contraints.
1065 	 *
1066 	 * Get the maximum DMA under worse case conditions. e.g. looking at the
1067 	 * device constraints, the max copy buffer size, and the worse case
1068 	 * fragmentation. NOTE: this may differ from dma-max since dma-max
1069 	 * doesn't take the worse case framentation into account.
1070 	 *
1071 	 * e.g. a device may be able to DMA 16MBytes, but can only DMA 1MByte
1072 	 * if none of the pages are contiguous. Keeping track of both of these
1073 	 * values allows us to support larger tape block sizes on some devices.
1074 	 */
1075 	un->un_maxdma_arch = scsi_ifgetcap(&devp->sd_address, "dma-max-arch",
1076 	    1);
1077 
1078 	/*
1079 	 * If the dma-max-arch capability is not implemented, or the value
1080 	 * comes back higher than what was reported in dma-max, use dma-max.
1081 	 */
1082 	if ((un->un_maxdma_arch == -1) ||
1083 	    ((uint_t)un->un_maxdma < (uint_t)un->un_maxdma_arch)) {
1084 		un->un_maxdma_arch = un->un_maxdma;
1085 	}
1086 #endif
1087 
1088 	/*
1089 	 * Get the max allowable cdb size
1090 	 */
1091 	un->un_max_cdb_sz =
1092 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
1093 	if (un->un_max_cdb_sz < CDB_GROUP0) {
1094 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1095 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
1096 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
1097 	}
1098 
1099 	if (strcmp(ddi_driver_name(ddi_get_parent(ST_DEVINFO)), "scsi_vhci")) {
1100 		un->un_multipath = 0;
1101 	} else {
1102 		un->un_multipath = 1;
1103 	}
1104 
1105 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1106 
1107 	un->un_mediastate = MTIO_NONE;
1108 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1109 
1110 	/*
1111 	 * initialize kstats
1112 	 */
1113 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1114 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1115 	if (un->un_stats) {
1116 		un->un_stats->ks_lock = ST_MUTEX;
1117 		kstat_install(un->un_stats);
1118 	}
1119 	(void) st_create_errstats(un, instance);
1120 
1121 	/*
1122 	 * find the drive type for this target
1123 	 */
1124 	mutex_enter(ST_MUTEX);
1125 	un->un_dev = MTMINOR(instance);
1126 	st_known_tape_type(un);
1127 	un->un_dev = 0;
1128 	mutex_exit(ST_MUTEX);
1129 
1130 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
1131 		int minor;
1132 		char *name;
1133 
1134 		name  = st_minor_data[node_ix].name;
1135 		minor = st_minor_data[node_ix].minor;
1136 
1137 		/*
1138 		 * For default devices set the density to the
1139 		 * preferred default density for this device.
1140 		 */
1141 		if (node_ix <= DEF_BSD_NR) {
1142 			minor |= un->un_dp->default_density;
1143 		}
1144 		minor |= MTMINOR(instance);
1145 
1146 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
1147 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
1148 			continue;
1149 		}
1150 
1151 		ddi_remove_minor_node(devi, NULL);
1152 
1153 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1154 		    st_reset_notification, (caddr_t)un);
1155 		cv_destroy(&un->un_clscv);
1156 		cv_destroy(&un->un_sbuf_cv);
1157 		cv_destroy(&un->un_queue_cv);
1158 		cv_destroy(&un->un_state_cv);
1159 #ifdef	__x86
1160 		cv_destroy(&un->un_contig_mem_cv);
1161 #endif
1162 		cv_destroy(&un->un_suspend_cv);
1163 		cv_destroy(&un->un_tape_busy_cv);
1164 		cv_destroy(&un->un_recov_buf_cv);
1165 		if (un->un_recov_taskq) {
1166 			ddi_taskq_destroy(un->un_recov_taskq);
1167 		}
1168 		if (un->un_sbufp) {
1169 			freerbuf(un->un_sbufp);
1170 		}
1171 		if (un->un_recov_buf) {
1172 			freerbuf(un->un_recov_buf);
1173 		}
1174 		if (un->un_uscsi_rqs_buf) {
1175 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1176 		}
1177 		if (un->un_mspl) {
1178 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1179 		}
1180 		if (un->un_dp_size) {
1181 			kmem_free(un->un_dp, un->un_dp_size);
1182 		}
1183 		if (un->un_state) {
1184 			kstat_delete(un->un_stats);
1185 		}
1186 		if (un->un_errstats) {
1187 			kstat_delete(un->un_errstats);
1188 		}
1189 
1190 		scsi_destroy_pkt(un->un_rqs);
1191 		scsi_free_consistent_buf(un->un_rqs_bp);
1192 		ddi_soft_state_free(st_state, instance);
1193 		devp->sd_private = NULL;
1194 		devp->sd_sense = NULL;
1195 
1196 		ddi_prop_remove_all(devi);
1197 		return (DDI_FAILURE);
1198 	}
1199 
1200 	return (DDI_SUCCESS);
1201 }
1202 
1203 /*
1204  * st_detach:
1205  *
1206  * we allow a detach if and only if:
1207  *	- no tape is currently inserted
1208  *	- tape position is at BOT or unknown
1209  *		(if it is not at BOT then a no rewind
1210  *		device was opened and we have to preserve state)
1211  *	- it must be in a closed state : no timeouts or scsi_watch requests
1212  *		will exist if it is closed, so we don't need to check for
1213  *		them here.
1214  */
1215 /*ARGSUSED*/
1216 static int
1217 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1218 {
1219 	int instance;
1220 	int result;
1221 	struct scsi_device *devp;
1222 	struct scsi_tape *un;
1223 	clock_t wait_cmds_complete;
1224 
1225 	ST_ENTR(devi, st_detach);
1226 
1227 	instance = ddi_get_instance(devi);
1228 
1229 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1230 		return (DDI_FAILURE);
1231 	}
1232 
1233 	mutex_enter(ST_MUTEX);
1234 
1235 	/*
1236 	 * Clear error entry stack
1237 	 */
1238 	st_empty_error_stack(un);
1239 
1240 	mutex_exit(ST_MUTEX);
1241 
1242 	switch (cmd) {
1243 
1244 	case DDI_DETACH:
1245 		/*
1246 		 * Undo what we did in st_attach & st_doattach,
1247 		 * freeing resources and removing things we installed.
1248 		 * The system framework guarantees we are not active
1249 		 * with this devinfo node in any other entry points at
1250 		 * this time.
1251 		 */
1252 
1253 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1254 		    "st_detach: instance=%x, un=%p\n", instance,
1255 		    (void *)un);
1256 
1257 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1258 		    ((un->un_rsvd_status & ST_APPLICATION_RESERVATIONS) != 0) ||
1259 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1260 		    (un->un_state != ST_STATE_CLOSED)) {
1261 			/*
1262 			 * we cannot unload some targets because the
1263 			 * inquiry returns junk unless immediately
1264 			 * after a reset
1265 			 */
1266 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1267 			    "cannot unload instance %x\n", instance);
1268 			un->un_unit_attention_flags |= 4;
1269 			return (DDI_FAILURE);
1270 		}
1271 
1272 		/*
1273 		 * if the tape has been removed then we may unload;
1274 		 * do a test unit ready and if it returns NOT READY
1275 		 * then we assume that it is safe to unload.
1276 		 * as a side effect, pmode may be set to invalid if the
1277 		 * the test unit ready fails;
1278 		 * also un_state may be set to non-closed, so reset it
1279 		 */
1280 		if ((un->un_dev) &&		/* Been opened since attach */
1281 		    ((un->un_pos.pmode == legacy) &&
1282 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1283 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1284 		    ((un->un_pos.pmode == logical) &&
1285 		    (un->un_pos.lgclblkno > 0))) {
1286 			mutex_enter(ST_MUTEX);
1287 			/*
1288 			 * Send Test Unit Ready in the hopes that if
1289 			 * the drive is not in the state we think it is.
1290 			 * And the state will be changed so it can be detached.
1291 			 * If the command fails to reach the device and
1292 			 * the drive was not rewound or unloaded we want
1293 			 * to fail the detach till a user command fails
1294 			 * where after the detach will succead.
1295 			 */
1296 			result = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
1297 			/*
1298 			 * After TUR un_state may be set to non-closed,
1299 			 * so reset it back.
1300 			 */
1301 			un->un_state = ST_STATE_CLOSED;
1302 			mutex_exit(ST_MUTEX);
1303 		}
1304 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1305 		    "un_status=%x, fileno=%x, blkno=%x\n",
1306 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1307 
1308 		/*
1309 		 * check again:
1310 		 * if we are not at BOT then it is not safe to unload
1311 		 */
1312 		if ((un->un_dev) &&		/* Been opened since attach */
1313 		    (result != EACCES) &&	/* drive is use by somebody */
1314 		    ((((un->un_pos.pmode == legacy) &&
1315 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1316 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1317 		    ((un->un_pos.pmode == logical) &&
1318 		    (un->un_pos.lgclblkno > 0))) &&
1319 		    ((un->un_state == ST_STATE_CLOSED) &&
1320 		    (un->un_laststate == ST_STATE_CLOSING)))) {
1321 
1322 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1323 			    "cannot detach: pmode=%d fileno=0x%x, blkno=0x%x"
1324 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1325 			    un->un_pos.fileno, un->un_pos.blkno,
1326 			    un->un_pos.lgclblkno);
1327 			un->un_unit_attention_flags |= 4;
1328 			return (DDI_FAILURE);
1329 		}
1330 
1331 		/*
1332 		 * Just To make sure that we have released the
1333 		 * tape unit .
1334 		 */
1335 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1336 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1337 			mutex_enter(ST_MUTEX);
1338 			(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
1339 			mutex_exit(ST_MUTEX);
1340 		}
1341 
1342 		/*
1343 		 * now remove other data structures allocated in st_doattach()
1344 		 */
1345 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1346 		    "destroying/freeing\n");
1347 
1348 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1349 		    st_reset_notification, (caddr_t)un);
1350 		cv_destroy(&un->un_clscv);
1351 		cv_destroy(&un->un_sbuf_cv);
1352 		cv_destroy(&un->un_queue_cv);
1353 		cv_destroy(&un->un_suspend_cv);
1354 		cv_destroy(&un->un_tape_busy_cv);
1355 		cv_destroy(&un->un_recov_buf_cv);
1356 
1357 		if (un->un_recov_taskq) {
1358 			ddi_taskq_destroy(un->un_recov_taskq);
1359 		}
1360 
1361 		if (un->un_hib_tid) {
1362 			(void) untimeout(un->un_hib_tid);
1363 			un->un_hib_tid = 0;
1364 		}
1365 
1366 		if (un->un_delay_tid) {
1367 			(void) untimeout(un->un_delay_tid);
1368 			un->un_delay_tid = 0;
1369 		}
1370 		cv_destroy(&un->un_state_cv);
1371 
1372 #ifdef	__x86
1373 		cv_destroy(&un->un_contig_mem_cv);
1374 
1375 		if (un->un_contig_mem_hdl != NULL) {
1376 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1377 		}
1378 #endif
1379 		if (un->un_sbufp) {
1380 			freerbuf(un->un_sbufp);
1381 		}
1382 		if (un->un_recov_buf) {
1383 			freerbuf(un->un_recov_buf);
1384 		}
1385 		if (un->un_uscsi_rqs_buf) {
1386 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1387 		}
1388 		if (un->un_mspl) {
1389 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1390 		}
1391 		if (un->un_rqs) {
1392 			scsi_destroy_pkt(un->un_rqs);
1393 			scsi_free_consistent_buf(un->un_rqs_bp);
1394 		}
1395 		if (un->un_mkr_pkt) {
1396 			scsi_destroy_pkt(un->un_mkr_pkt);
1397 		}
1398 		if (un->un_arq_enabled) {
1399 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1400 		}
1401 		if (un->un_dp_size) {
1402 			kmem_free(un->un_dp, un->un_dp_size);
1403 		}
1404 		if (un->un_stats) {
1405 			kstat_delete(un->un_stats);
1406 			un->un_stats = (kstat_t *)0;
1407 		}
1408 		if (un->un_errstats) {
1409 			kstat_delete(un->un_errstats);
1410 			un->un_errstats = (kstat_t *)0;
1411 		}
1412 		if (un->un_media_id_len) {
1413 			kmem_free(un->un_media_id, un->un_media_id_len);
1414 		}
1415 		devp = ST_SCSI_DEVP;
1416 		ddi_soft_state_free(st_state, instance);
1417 		devp->sd_private = NULL;
1418 		devp->sd_sense = NULL;
1419 		scsi_unprobe(devp);
1420 		ddi_prop_remove_all(devi);
1421 		ddi_remove_minor_node(devi, NULL);
1422 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1423 		return (DDI_SUCCESS);
1424 
1425 	case DDI_SUSPEND:
1426 
1427 		/*
1428 		 * Suspend/Resume
1429 		 *
1430 		 * To process DDI_SUSPEND, we must do the following:
1431 		 *
1432 		 *  - check ddi_removing_power to see if power will be turned
1433 		 *    off. if so, return DDI_FAILURE
1434 		 *  - check if we are already suspended,
1435 		 *    if so, return DDI_FAILURE
1436 		 *  - check if device state is CLOSED,
1437 		 *    if not, return DDI_FAILURE.
1438 		 *  - wait until outstanding operations complete
1439 		 *  - save tape state
1440 		 *  - block new operations
1441 		 *  - cancel pending timeouts
1442 		 *
1443 		 */
1444 
1445 		if (ddi_removing_power(devi)) {
1446 			return (DDI_FAILURE);
1447 		}
1448 
1449 		if (un->un_dev == 0)
1450 			un->un_dev = MTMINOR(instance);
1451 
1452 		mutex_enter(ST_MUTEX);
1453 
1454 		/*
1455 		 * Shouldn't already be suspended, if so return failure
1456 		 */
1457 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1458 			mutex_exit(ST_MUTEX);
1459 			return (DDI_FAILURE);
1460 		}
1461 		if (un->un_state != ST_STATE_CLOSED) {
1462 			mutex_exit(ST_MUTEX);
1463 			return (DDI_FAILURE);
1464 		}
1465 
1466 		/*
1467 		 * Wait for all outstanding I/O's to complete
1468 		 *
1469 		 * we wait on both ncmds and the wait queue for times
1470 		 * when we are flushing after persistent errors are
1471 		 * flagged, which is when ncmds can be 0, and the
1472 		 * queue can still have I/O's.  This way we preserve
1473 		 * order of biodone's.
1474 		 */
1475 		wait_cmds_complete = ddi_get_lbolt();
1476 		wait_cmds_complete +=
1477 		    st_wait_cmds_complete * drv_usectohz(1000000);
1478 		while (un->un_ncmds || un->un_quef ||
1479 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1480 
1481 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1482 			    wait_cmds_complete) == -1) {
1483 				/*
1484 				 * Time expired then cancel the command
1485 				 */
1486 				if (st_reset(un, RESET_LUN) == 0) {
1487 					if (un->un_last_throttle) {
1488 						un->un_throttle =
1489 						    un->un_last_throttle;
1490 					}
1491 					mutex_exit(ST_MUTEX);
1492 					return (DDI_FAILURE);
1493 				} else {
1494 					break;
1495 				}
1496 			}
1497 		}
1498 
1499 		/*
1500 		 * DDI_SUSPEND says that the system "may" power down, we
1501 		 * remember the file and block number before rewinding.
1502 		 * we also need to save state before issuing
1503 		 * any WRITE_FILE_MARK command.
1504 		 */
1505 		(void) st_update_block_pos(un, st_cmd, 0);
1506 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1507 
1508 
1509 		/*
1510 		 * Issue a zero write file fmk command to tell the drive to
1511 		 * flush any buffered tape marks
1512 		 */
1513 		(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1514 
1515 		/*
1516 		 * Because not all tape drives correctly implement buffer
1517 		 * flushing with the zero write file fmk command, issue a
1518 		 * synchronous rewind command to force data flushing.
1519 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1520 		 * anyway.
1521 		 */
1522 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
1523 
1524 		/* stop any new operations */
1525 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1526 		un->un_throttle = 0;
1527 
1528 		/*
1529 		 * cancel any outstanding timeouts
1530 		 */
1531 		if (un->un_delay_tid) {
1532 			timeout_id_t temp_id = un->un_delay_tid;
1533 			un->un_delay_tid = 0;
1534 			un->un_tids_at_suspend |= ST_DELAY_TID;
1535 			mutex_exit(ST_MUTEX);
1536 			(void) untimeout(temp_id);
1537 			mutex_enter(ST_MUTEX);
1538 		}
1539 
1540 		if (un->un_hib_tid) {
1541 			timeout_id_t temp_id = un->un_hib_tid;
1542 			un->un_hib_tid = 0;
1543 			un->un_tids_at_suspend |= ST_HIB_TID;
1544 			mutex_exit(ST_MUTEX);
1545 			(void) untimeout(temp_id);
1546 			mutex_enter(ST_MUTEX);
1547 		}
1548 
1549 		/*
1550 		 * Suspend the scsi_watch_thread
1551 		 */
1552 		if (un->un_swr_token) {
1553 			opaque_t temp_token = un->un_swr_token;
1554 			mutex_exit(ST_MUTEX);
1555 			scsi_watch_suspend(temp_token);
1556 		} else {
1557 			mutex_exit(ST_MUTEX);
1558 		}
1559 
1560 		return (DDI_SUCCESS);
1561 
1562 	default:
1563 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1564 		return (DDI_FAILURE);
1565 	}
1566 }
1567 
1568 
1569 /* ARGSUSED */
1570 static int
1571 st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1572 {
1573 	dev_t dev;
1574 	struct scsi_tape *un;
1575 	int instance, error;
1576 
1577 	ST_ENTR(dip, st_info);
1578 
1579 	switch (infocmd) {
1580 	case DDI_INFO_DEVT2DEVINFO:
1581 		dev = (dev_t)arg;
1582 		instance = MTUNIT(dev);
1583 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1584 			return (DDI_FAILURE);
1585 		*result = (void *) ST_DEVINFO;
1586 		error = DDI_SUCCESS;
1587 		break;
1588 	case DDI_INFO_DEVT2INSTANCE:
1589 		dev = (dev_t)arg;
1590 		instance = MTUNIT(dev);
1591 		*result = (void *)(uintptr_t)instance;
1592 		error = DDI_SUCCESS;
1593 		break;
1594 	default:
1595 		error = DDI_FAILURE;
1596 	}
1597 	return (error);
1598 }
1599 
1600 static int
1601 st_doattach(struct scsi_device *devp, int (*canwait)())
1602 {
1603 	struct scsi_tape *un = NULL;
1604 	recov_info *ri;
1605 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1606 	int instance;
1607 	size_t rlen;
1608 
1609 	ST_FUNC(devp->sd_dev, st_doattach);
1610 	/*
1611 	 * Call the routine scsi_probe to do some of the dirty work.
1612 	 * If the INQUIRY command succeeds, the field sd_inq in the
1613 	 * device structure will be filled in.
1614 	 */
1615 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1616 	    "st_doattach(): probing\n");
1617 
1618 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1619 
1620 		/*
1621 		 * In checking the whole inq_dtype byte we are looking at both
1622 		 * the Peripheral Qualifier and the Peripheral Device Type.
1623 		 * For this driver we are only interested in sequential devices
1624 		 * that are connected or capable if connecting to this logical
1625 		 * unit.
1626 		 */
1627 		if (devp->sd_inq->inq_dtype ==
1628 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1629 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1630 			    "probe exists\n");
1631 		} else {
1632 			/* Something there but not a tape device */
1633 			scsi_unprobe(devp);
1634 			return (DDI_FAILURE);
1635 		}
1636 	} else {
1637 		/* Nothing there */
1638 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1639 		    "probe failure: nothing there\n");
1640 		scsi_unprobe(devp);
1641 		return (DDI_FAILURE);
1642 	}
1643 
1644 
1645 	/*
1646 	 * The actual unit is present.
1647 	 * Now is the time to fill in the rest of our info..
1648 	 */
1649 	instance = ddi_get_instance(devp->sd_dev);
1650 
1651 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1652 		goto error;
1653 	}
1654 	un = ddi_get_soft_state(st_state, instance);
1655 
1656 	ASSERT(un != NULL);
1657 
1658 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
1659 	    MAX_SENSE_LENGTH, B_READ, canwait, NULL);
1660 	if (un->un_rqs_bp == NULL) {
1661 		goto error;
1662 	}
1663 	un->un_rqs = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
1664 	    CDB_GROUP0, 1, st_recov_sz, PKT_CONSISTENT, canwait, NULL);
1665 	if (!un->un_rqs) {
1666 		goto error;
1667 	}
1668 	ASSERT(un->un_rqs->pkt_resid == 0);
1669 	devp->sd_sense =
1670 	    (struct scsi_extended_sense *)un->un_rqs_bp->b_un.b_addr;
1671 	ASSERT(geterror(un->un_rqs_bp) == NULL);
1672 
1673 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs->pkt_cdbp,
1674 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
1675 	FILL_SCSI1_LUN(devp, un->un_rqs);
1676 	un->un_rqs->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1677 	un->un_rqs->pkt_time = st_io_time;
1678 	un->un_rqs->pkt_comp = st_intr;
1679 	ri = (recov_info *)un->un_rqs->pkt_private;
1680 	if (st_recov_sz == sizeof (recov_info)) {
1681 		ri->privatelen = sizeof (recov_info);
1682 	} else {
1683 		ri->privatelen = sizeof (pkt_info);
1684 	}
1685 
1686 	un->un_sbufp = getrbuf(km_flags);
1687 	un->un_recov_buf = getrbuf(km_flags);
1688 
1689 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1690 
1691 	/*
1692 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1693 	 * memory for DMA which doesn't require a DMA handle.
1694 	 */
1695 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1696 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1697 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1698 
1699 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1700 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1701 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1702 
1703 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1704 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1705 		    "probe partial failure: no space\n");
1706 		goto error;
1707 	}
1708 
1709 	bzero(un->un_mspl, sizeof (struct seq_mode));
1710 
1711 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1712 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1713 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1714 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1715 #ifdef	__x86
1716 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1717 #endif
1718 
1719 	/* Initialize power managemnet condition variable */
1720 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1721 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1722 	cv_init(&un->un_recov_buf_cv, NULL, CV_DRIVER, NULL);
1723 
1724 	un->un_recov_taskq = ddi_taskq_create(devp->sd_dev,
1725 	    "un_recov_taskq", 1, TASKQ_DEFAULTPRI, km_flags);
1726 
1727 	ASSERT(un->un_recov_taskq != NULL);
1728 
1729 	un->un_pos.pmode = invalid;
1730 	un->un_sd	= devp;
1731 	un->un_swr_token = (opaque_t)NULL;
1732 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1733 	un->un_wormable = st_is_drive_worm;
1734 	un->un_media_id_method = st_get_media_identification;
1735 	/*
1736 	 * setting long a initial as it contains logical file info.
1737 	 * support for long format is mandatory but many drive don't do it.
1738 	 */
1739 	un->un_read_pos_type = LONG_POS;
1740 
1741 	un->un_suspend_pos.pmode = invalid;
1742 
1743 	st_add_recovery_info_to_pkt(un, un->un_rqs_bp, un->un_rqs);
1744 
1745 #ifdef	__x86
1746 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1747 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1748 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1749 		    "allocation of contiguous memory dma handle failed!");
1750 		un->un_contig_mem_hdl = NULL;
1751 		goto error;
1752 	}
1753 #endif
1754 
1755 	/*
1756 	 * Since this driver manages devices with "remote" hardware,
1757 	 * i.e. the devices themselves have no "reg" properties,
1758 	 * the SUSPEND/RESUME commands in detach/attach will not be
1759 	 * called by the power management framework unless we request
1760 	 * it by creating a "pm-hardware-state" property and setting it
1761 	 * to value "needs-suspend-resume".
1762 	 */
1763 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1764 	    "pm-hardware-state", "needs-suspend-resume") !=
1765 	    DDI_PROP_SUCCESS) {
1766 
1767 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1768 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1769 		goto error;
1770 	}
1771 
1772 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1773 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1774 
1775 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1776 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1777 		    "failed\n");
1778 		goto error;
1779 	}
1780 
1781 	(void) scsi_reset_notify(ROUTE, SCSI_RESET_NOTIFY,
1782 	    st_reset_notification, (caddr_t)un);
1783 
1784 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "attach success\n");
1785 	return (DDI_SUCCESS);
1786 
1787 error:
1788 	devp->sd_sense = NULL;
1789 
1790 	ddi_remove_minor_node(devp->sd_dev, NULL);
1791 	if (un) {
1792 		if (un->un_mspl) {
1793 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1794 		}
1795 		if (un->un_read_pos_data) {
1796 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1797 		}
1798 		if (un->un_sbufp) {
1799 			freerbuf(un->un_sbufp);
1800 		}
1801 		if (un->un_recov_buf) {
1802 			freerbuf(un->un_recov_buf);
1803 		}
1804 		if (un->un_uscsi_rqs_buf) {
1805 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1806 		}
1807 #ifdef	__x86
1808 		if (un->un_contig_mem_hdl != NULL) {
1809 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1810 		}
1811 #endif
1812 		if (un->un_rqs) {
1813 			scsi_destroy_pkt(un->un_rqs);
1814 		}
1815 
1816 		if (un->un_rqs_bp) {
1817 			scsi_free_consistent_buf(un->un_rqs_bp);
1818 		}
1819 
1820 		ddi_soft_state_free(st_state, instance);
1821 		devp->sd_private = NULL;
1822 	}
1823 
1824 	if (devp->sd_inq) {
1825 		scsi_unprobe(devp);
1826 	}
1827 	return (DDI_FAILURE);
1828 }
1829 
1830 typedef int
1831 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1832 
1833 static cfg_functp config_functs[] = {
1834 	st_get_conf_from_st_dot_conf,
1835 	st_get_conf_from_st_conf_dot_c,
1836 	st_get_conf_from_tape_drive,
1837 	st_get_default_conf
1838 };
1839 
1840 
1841 /*
1842  * determine tape type, using tape-config-list or built-in table or
1843  * use a generic tape config entry
1844  */
1845 static void
1846 st_known_tape_type(struct scsi_tape *un)
1847 {
1848 	struct st_drivetype *dp;
1849 	cfg_functp *config_funct;
1850 	uchar_t reserved;
1851 
1852 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1853 
1854 	reserved = (un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1855 	    : ST_RELEASE;
1856 
1857 	/*
1858 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1859 	 *	 no vid & pid inquiry data.  So, we provide one.
1860 	 */
1861 	if (ST_INQUIRY->inq_len == 0 ||
1862 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1863 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1864 	}
1865 
1866 	if (un->un_dp_size == 0) {
1867 		un->un_dp_size = sizeof (struct st_drivetype);
1868 		dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1869 		un->un_dp = dp;
1870 	} else {
1871 		dp = un->un_dp;
1872 	}
1873 
1874 	un->un_dp->non_motion_timeout = st_io_time;
1875 	/*
1876 	 * Loop through the configuration methods till one works.
1877 	 */
1878 	for (config_funct = &config_functs[0]; ; config_funct++) {
1879 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1880 			break;
1881 		}
1882 	}
1883 
1884 	/*
1885 	 * If we didn't just make up this configuration and
1886 	 * all the density codes are the same..
1887 	 * Set Auto Density over ride.
1888 	 */
1889 	if (*config_funct != st_get_default_conf) {
1890 		/*
1891 		 * If this device is one that is configured and all
1892 		 * densities are the same, This saves doing gets and set
1893 		 * that yield nothing.
1894 		 */
1895 		if ((dp->densities[0]) == (dp->densities[1]) &&
1896 		    (dp->densities[0]) == (dp->densities[2]) &&
1897 		    (dp->densities[0]) == (dp->densities[3])) {
1898 
1899 			dp->options |= ST_AUTODEN_OVERRIDE;
1900 		}
1901 	}
1902 
1903 
1904 	/*
1905 	 * Store tape drive characteristics.
1906 	 */
1907 	un->un_status = 0;
1908 	un->un_attached = 1;
1909 	un->un_init_options = dp->options;
1910 
1911 	/* setup operation time-outs based on options */
1912 	st_calculate_timeouts(un);
1913 
1914 	/* TLR support */
1915 	if (un->un_dp->type != ST_TYPE_INVALID) {
1916 		int result;
1917 
1918 		/* try and enable TLR */
1919 		un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
1920 		result = st_set_target_TLR_mode(un, st_uscsi_cmd);
1921 		if (result == EACCES) {
1922 			/*
1923 			 * From attach command failed.
1924 			 * Set dp type so is run again on open.
1925 			 */
1926 			un->un_dp->type = ST_TYPE_INVALID;
1927 			un->un_tlr_flag = TLR_NOT_KNOWN;
1928 		} else if (result == 0) {
1929 			if (scsi_ifgetcap(&un->un_sd->sd_address,
1930 			    "tran-layer-retries", 1) == -1) {
1931 				un->un_tlr_flag = TLR_NOT_SUPPORTED;
1932 				(void) st_set_target_TLR_mode(un, st_uscsi_cmd);
1933 			} else {
1934 				un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
1935 			}
1936 		} else {
1937 			un->un_tlr_flag = TLR_NOT_SUPPORTED;
1938 		}
1939 	}
1940 
1941 	/* make sure if we are supposed to be variable, make it variable */
1942 	if (dp->options & ST_VARIABLE) {
1943 		dp->bsize = 0;
1944 	}
1945 
1946 	if (reserved != ((un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1947 	    : ST_RELEASE)) {
1948 		(void) st_reserve_release(un, reserved, st_uscsi_cmd);
1949 	}
1950 
1951 	un->un_unit_attention_flags |= 1;
1952 
1953 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1954 
1955 }
1956 
1957 
1958 typedef struct {
1959 	int mask;
1960 	int bottom;
1961 	int top;
1962 	char *name;
1963 } conf_limit;
1964 
1965 static const conf_limit conf_limits[] = {
1966 
1967 	-1,		1,		2,		"conf version",
1968 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1969 	-1,		0,		0xffffff,	"block size",
1970 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1971 	-1,		0,		4,		"number of densities",
1972 	-1,		0,		UINT8_MAX,	"density code",
1973 	-1,		0,		3,		"default density",
1974 	-1,		0,		UINT16_MAX,	"non motion timeout",
1975 	-1,		0,		UINT16_MAX,	"I/O timeout",
1976 	-1,		0,		UINT16_MAX,	"space timeout",
1977 	-1,		0,		UINT16_MAX,	"load timeout",
1978 	-1,		0,		UINT16_MAX,	"unload timeout",
1979 	-1,		0,		UINT16_MAX,	"erase timeout",
1980 	0,		0,		0,		NULL
1981 };
1982 
1983 static int
1984 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1985     const char *conf_name)
1986 {
1987 	int dens;
1988 	int ndens;
1989 	int value;
1990 	int type;
1991 	int count;
1992 	const conf_limit *limit = &conf_limits[0];
1993 
1994 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1995 
1996 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1997 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1998 
1999 	count = list_len;
2000 	type = *list;
2001 	for (;  count && limit->name; count--, list++, limit++) {
2002 
2003 		value = *list;
2004 		if (value & ~limit->mask) {
2005 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2006 			    "%s %s value invalid bits set: 0x%X\n",
2007 			    conf_name, limit->name, value & ~limit->mask);
2008 			*list &= limit->mask;
2009 		} else if (value < limit->bottom) {
2010 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2011 			    "%s %s value too low: value = %d limit %d\n",
2012 			    conf_name, limit->name, value, limit->bottom);
2013 		} else if (value > limit->top) {
2014 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2015 			    "%s %s value too high: value = %d limit %d\n",
2016 			    conf_name, limit->name, value, limit->top);
2017 		} else {
2018 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2019 			    "%s %s value = 0x%X\n",
2020 			    conf_name, limit->name, value);
2021 		}
2022 
2023 		/* If not the number of densities continue */
2024 		if (limit != &conf_limits[4]) {
2025 			continue;
2026 		}
2027 
2028 		/* If number of densities is not in range can't use config */
2029 		if (value < limit->bottom || value > limit->top) {
2030 			return (-1);
2031 		}
2032 
2033 		ndens = min(value, NDENSITIES);
2034 		if ((type == 1) && (list_len - ndens) != 6) {
2035 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2036 			    "%s conf version 1 with %d densities has %d items"
2037 			    " should have %d",
2038 			    conf_name, ndens, list_len, 6 + ndens);
2039 		} else if ((type == 2) && (list_len - ndens) != 13) {
2040 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2041 			    "%s conf version 2 with %d densities has %d items"
2042 			    " should have %d",
2043 			    conf_name, ndens, list_len, 13 + ndens);
2044 		}
2045 
2046 		limit++;
2047 		for (dens = 0; dens < ndens && count; dens++) {
2048 			count--;
2049 			list++;
2050 			value = *list;
2051 			if (value < limit->bottom) {
2052 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2053 				    "%s density[%d] value too low: value ="
2054 				    " 0x%X limit 0x%X\n",
2055 				    conf_name, dens, value, limit->bottom);
2056 			} else if (value > limit->top) {
2057 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2058 				    "%s density[%d] value too high: value ="
2059 				    " 0x%X limit 0x%X\n",
2060 				    conf_name, dens, value, limit->top);
2061 			} else {
2062 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2063 				    "%s density[%d] value = 0x%X\n",
2064 				    conf_name, dens, value);
2065 			}
2066 		}
2067 	}
2068 
2069 	return (0);
2070 }
2071 
2072 static int
2073 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
2074     struct st_drivetype *dp)
2075 {
2076 	caddr_t config_list = NULL;
2077 	caddr_t data_list = NULL;
2078 	int	*data_ptr;
2079 	caddr_t vidptr, prettyptr, datanameptr;
2080 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
2081 	int config_list_len, data_list_len, len, i;
2082 	int version;
2083 	int found = 0;
2084 
2085 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
2086 
2087 	/*
2088 	 * Determine type of tape controller. Type is determined by
2089 	 * checking the vendor ids of the earlier inquiry command and
2090 	 * comparing those with vids in tape-config-list defined in st.conf
2091 	 */
2092 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
2093 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
2094 	    != DDI_PROP_SUCCESS) {
2095 		return (found);
2096 	}
2097 
2098 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2099 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
2100 
2101 	/*
2102 	 * Compare vids in each triplet - if it matches, get value for
2103 	 * data_name and contruct a st_drivetype struct
2104 	 * tripletlen is not set yet!
2105 	 */
2106 	for (len = config_list_len, vidptr = config_list;
2107 	    len > 0;
2108 	    vidptr += tripletlen, len -= tripletlen) {
2109 
2110 		vidlen = strlen(vidptr);
2111 		prettyptr = vidptr + vidlen + 1;
2112 		prettylen = strlen(prettyptr);
2113 		datanameptr = prettyptr + prettylen + 1;
2114 		datanamelen = strlen(datanameptr);
2115 		tripletlen = vidlen + prettylen + datanamelen + 3;
2116 
2117 		if (vidlen == 0) {
2118 			continue;
2119 		}
2120 
2121 		/*
2122 		 * If inquiry vid dosen't match this triplets vid,
2123 		 * try the next.
2124 		 */
2125 		if (strncasecmp(vidpid, vidptr, vidlen)) {
2126 			continue;
2127 		}
2128 
2129 		/*
2130 		 * if prettylen is zero then use the vid string
2131 		 */
2132 		if (prettylen == 0) {
2133 			prettyptr = vidptr;
2134 			prettylen = vidlen;
2135 		}
2136 
2137 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2138 		    "vid = %s, pretty=%s, dataname = %s\n",
2139 		    vidptr, prettyptr, datanameptr);
2140 
2141 		/*
2142 		 * get the data list
2143 		 */
2144 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
2145 		    datanameptr, (caddr_t)&data_list,
2146 		    &data_list_len) != DDI_PROP_SUCCESS) {
2147 			/*
2148 			 * Error in getting property value
2149 			 * print warning!
2150 			 */
2151 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2152 			    "data property (%s) has no value\n",
2153 			    datanameptr);
2154 			continue;
2155 		}
2156 
2157 		/*
2158 		 * now initialize the st_drivetype struct
2159 		 */
2160 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
2161 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
2162 		(void) strncpy(dp->vid, vidptr, dp->length);
2163 		data_ptr = (int *)data_list;
2164 		/*
2165 		 * check if data is enough for version, type,
2166 		 * bsize, options, # of densities, density1,
2167 		 * density2, ..., default_density
2168 		 */
2169 		if ((data_list_len < 5 * sizeof (int)) ||
2170 		    (data_list_len < 6 * sizeof (int) +
2171 		    *(data_ptr + 4) * sizeof (int))) {
2172 			/*
2173 			 * print warning and skip to next triplet.
2174 			 */
2175 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2176 			    "data property (%s) incomplete\n",
2177 			    datanameptr);
2178 			kmem_free(data_list, data_list_len);
2179 			continue;
2180 		}
2181 
2182 		if (st_validate_conf_data(un, data_ptr,
2183 		    data_list_len / sizeof (int), datanameptr)) {
2184 			kmem_free(data_list, data_list_len);
2185 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2186 			    "data property (%s) rejected\n",
2187 			    datanameptr);
2188 			continue;
2189 		}
2190 
2191 		/*
2192 		 * check version
2193 		 */
2194 		version = *data_ptr++;
2195 		if (version != 1 && version != 2) {
2196 			/* print warning but accept it */
2197 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2198 			    "Version # for data property (%s) "
2199 			    "not set to 1 or 2\n", datanameptr);
2200 		}
2201 
2202 		dp->type    = *data_ptr++;
2203 		dp->bsize   = *data_ptr++;
2204 		dp->options = *data_ptr++;
2205 		dp->options |= ST_DYNAMIC;
2206 		len = *data_ptr++;
2207 		for (i = 0; i < NDENSITIES; i++) {
2208 			if (i < len) {
2209 				dp->densities[i] = *data_ptr++;
2210 			}
2211 		}
2212 		dp->default_density = *data_ptr << 3;
2213 		if (version == 2 &&
2214 		    data_list_len >= (13 + len) * sizeof (int)) {
2215 			data_ptr++;
2216 			dp->non_motion_timeout	= *data_ptr++;
2217 			dp->io_timeout		= *data_ptr++;
2218 			dp->rewind_timeout	= *data_ptr++;
2219 			dp->space_timeout	= *data_ptr++;
2220 			dp->load_timeout	= *data_ptr++;
2221 			dp->unload_timeout	= *data_ptr++;
2222 			dp->erase_timeout	= *data_ptr++;
2223 		}
2224 		kmem_free(data_list, data_list_len);
2225 		found = 1;
2226 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2227 		    "found in st.conf: vid = %s, pretty=%s\n",
2228 		    dp->vid, dp->name);
2229 		break;
2230 	}
2231 
2232 	/*
2233 	 * free up the memory allocated by ddi_getlongprop
2234 	 */
2235 	if (config_list) {
2236 		kmem_free(config_list, config_list_len);
2237 	}
2238 	return (found);
2239 }
2240 
2241 static int
2242 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2243     struct st_drivetype *dp)
2244 {
2245 	int i;
2246 
2247 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2248 	/*
2249 	 * Determine type of tape controller.  Type is determined by
2250 	 * checking the result of the earlier inquiry command and
2251 	 * comparing vendor ids with strings in a table declared in st_conf.c.
2252 	 */
2253 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2254 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2255 
2256 	for (i = 0; i < st_ndrivetypes; i++) {
2257 		if (st_drivetypes[i].length == 0) {
2258 			continue;
2259 		}
2260 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2261 		    st_drivetypes[i].length)) {
2262 			continue;
2263 		}
2264 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2265 		return (1);
2266 	}
2267 	return (0);
2268 }
2269 
2270 static int
2271 st_get_conf_from_tape_drive(struct scsi_tape *un, char *vidpid,
2272     struct st_drivetype *dp)
2273 {
2274 	int bsize;
2275 	ulong_t maxbsize;
2276 	caddr_t buf;
2277 	struct st_drivetype *tem_dp;
2278 	struct read_blklim *blklim;
2279 	int rval;
2280 	int i;
2281 
2282 	ST_FUNC(ST_DEVINFO, st_get_conf_from_tape_drive);
2283 
2284 	/*
2285 	 * Determine the type of tape controller. Type is determined by
2286 	 * sending SCSI commands to tape drive and deriving the type from
2287 	 * the returned data.
2288 	 */
2289 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2290 	    "st_get_conf_from_tape_drive(): asking tape drive\n");
2291 
2292 	tem_dp = kmem_zalloc(sizeof (struct st_drivetype), KM_SLEEP);
2293 
2294 	/*
2295 	 * Make up a name
2296 	 */
2297 	bcopy(vidpid, tem_dp->name, VIDPIDLEN);
2298 	tem_dp->name[VIDPIDLEN] = '\0';
2299 	tem_dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2300 	(void) strncpy(tem_dp->vid, ST_INQUIRY->inq_vid, tem_dp->length);
2301 	/*
2302 	 * 'clean' vendor and product strings of non-printing chars
2303 	 */
2304 	for (i = 0; i < VIDPIDLEN - 1; i ++) {
2305 		if (tem_dp->name[i] < ' ' || tem_dp->name[i] > '~') {
2306 			tem_dp->name[i] = '.';
2307 		}
2308 	}
2309 
2310 	/*
2311 	 * MODE SENSE to determine block size.
2312 	 */
2313 	un->un_dp->options |= ST_MODE_SEL_COMP | ST_UNLOADABLE;
2314 	rval = st_modesense(un);
2315 	if (rval) {
2316 		if (rval == EACCES) {
2317 			un->un_dp->type = ST_TYPE_INVALID;
2318 			rval = 1;
2319 		} else {
2320 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
2321 			rval = 0;
2322 		}
2323 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2324 		    "st_get_conf_from_tape_drive(): fail to mode sense\n");
2325 		goto exit;
2326 	}
2327 
2328 	/* Can mode sense page 0x10 or 0xf */
2329 	tem_dp->options |= ST_MODE_SEL_COMP;
2330 	bsize = (un->un_mspl->high_bl << 16)	|
2331 	    (un->un_mspl->mid_bl << 8)		|
2332 	    (un->un_mspl->low_bl);
2333 
2334 	if (bsize == 0) {
2335 		tem_dp->options |= ST_VARIABLE;
2336 		tem_dp->bsize = 0;
2337 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
2338 		rval = st_change_block_size(un, 0);
2339 		if (rval) {
2340 			if (rval == EACCES) {
2341 				un->un_dp->type = ST_TYPE_INVALID;
2342 				rval = 1;
2343 			} else {
2344 				rval = 0;
2345 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2346 				    "st_get_conf_from_tape_drive(): "
2347 				    "Fixed record size is too large and"
2348 				    "cannot switch to variable record size");
2349 			}
2350 			goto exit;
2351 		}
2352 		tem_dp->options |= ST_VARIABLE;
2353 	} else {
2354 		rval = st_change_block_size(un, 0);
2355 		if (rval == 0) {
2356 			tem_dp->options |= ST_VARIABLE;
2357 			tem_dp->bsize = 0;
2358 		} else if (rval != EACCES) {
2359 			tem_dp->bsize = bsize;
2360 		} else {
2361 			un->un_dp->type = ST_TYPE_INVALID;
2362 			rval = 1;
2363 			goto exit;
2364 		}
2365 	}
2366 
2367 	/*
2368 	 * If READ BLOCk LIMITS works and upper block size limit is
2369 	 * more than 64K, ST_NO_RECSIZE_LIMIT is supported.
2370 	 */
2371 	blklim = kmem_zalloc(sizeof (struct read_blklim), KM_SLEEP);
2372 	rval = st_read_block_limits(un, blklim);
2373 	if (rval) {
2374 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2375 		    "st_get_conf_from_tape_drive(): "
2376 		    "fail to read block limits.\n");
2377 		rval = 0;
2378 		kmem_free(blklim, sizeof (struct read_blklim));
2379 		goto exit;
2380 	}
2381 	maxbsize = (blklim->max_hi << 16) +
2382 	    (blklim->max_mid << 8) + blklim->max_lo;
2383 	if (maxbsize > ST_MAXRECSIZE_VARIABLE) {
2384 		tem_dp->options |= ST_NO_RECSIZE_LIMIT;
2385 	}
2386 	kmem_free(blklim, sizeof (struct read_blklim));
2387 
2388 	/*
2389 	 * Inquiry VPD page 0xb0 to see if the tape drive supports WORM
2390 	 */
2391 	buf = kmem_zalloc(6, KM_SLEEP);
2392 	rval = st_get_special_inquiry(un, 6, buf, 0xb0);
2393 	if (rval) {
2394 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2395 		    "st_get_conf_from_tape_drive(): "
2396 		    "fail to read vitial inquiry.\n");
2397 		rval = 0;
2398 		kmem_free(buf, 6);
2399 		goto exit;
2400 	}
2401 	if (buf[4] & 1) {
2402 		tem_dp->options |= ST_WORMABLE;
2403 	}
2404 	kmem_free(buf, 6);
2405 
2406 	/* Assume BSD BSR KNOWS_EOD */
2407 	tem_dp->options |= ST_BSF | ST_BSR | ST_KNOWS_EOD | ST_UNLOADABLE;
2408 	tem_dp->max_rretries = -1;
2409 	tem_dp->max_wretries = -1;
2410 
2411 	/*
2412 	 * Decide the densities supported by tape drive by sending
2413 	 * REPORT DENSITY SUPPORT command.
2414 	 */
2415 	if (st_get_densities_from_tape_drive(un, tem_dp) == 0) {
2416 		goto exit;
2417 	}
2418 
2419 	/*
2420 	 * Decide the timeout values for several commands by sending
2421 	 * REPORT SUPPORTED OPERATION CODES command.
2422 	 */
2423 	rval = st_get_timeout_values_from_tape_drive(un, tem_dp);
2424 	if (rval == 0 || ((rval == 1) && (tem_dp->type == ST_TYPE_INVALID))) {
2425 		goto exit;
2426 	}
2427 
2428 	bcopy(tem_dp, dp, sizeof (struct st_drivetype));
2429 	rval = 1;
2430 
2431 exit:
2432 	un->un_status = KEY_NO_SENSE;
2433 	kmem_free(tem_dp, sizeof (struct st_drivetype));
2434 	return (rval);
2435 }
2436 
2437 static int
2438 st_get_densities_from_tape_drive(struct scsi_tape *un,
2439     struct st_drivetype *dp)
2440 {
2441 	int i, p;
2442 	size_t buflen;
2443 	ushort_t des_len;
2444 	uchar_t *den_header;
2445 	uchar_t num_den;
2446 	uchar_t den[NDENSITIES];
2447 	uchar_t deflt[NDENSITIES];
2448 	struct report_density_desc *den_desc;
2449 
2450 	ST_FUNC(ST_DEVINFO, st_get_densities_from_type_drive);
2451 
2452 	/*
2453 	 * Since we have no idea how many densitiy support entries
2454 	 * will be returned, we send the command firstly assuming
2455 	 * there is only one. Then we can decide the number of
2456 	 * entries by available density support length. If multiple
2457 	 * entries exist, we will resend the command with enough
2458 	 * buffer size.
2459 	 */
2460 	buflen = sizeof (struct report_density_header) +
2461 	    sizeof (struct report_density_desc);
2462 	den_header = kmem_zalloc(buflen, KM_SLEEP);
2463 	if (st_report_density_support(un, den_header, buflen) != 0) {
2464 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2465 		    "st_get_conf_from_tape_drive(): fail to report density.\n");
2466 		kmem_free(den_header, buflen);
2467 		return (0);
2468 	}
2469 	des_len =
2470 	    BE_16(((struct report_density_header *)den_header)->ava_dens_len);
2471 	num_den = (des_len - 2) / sizeof (struct report_density_desc);
2472 
2473 	if (num_den > 1) {
2474 		kmem_free(den_header, buflen);
2475 		buflen = sizeof (struct report_density_header) +
2476 		    sizeof (struct report_density_desc) * num_den;
2477 		den_header = kmem_zalloc(buflen, KM_SLEEP);
2478 		if (st_report_density_support(un, den_header, buflen) != 0) {
2479 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2480 			    "st_get_conf_from_tape_drive(): "
2481 			    "fail to report density.\n");
2482 			kmem_free(den_header, buflen);
2483 			return (0);
2484 		}
2485 	}
2486 
2487 	den_desc = (struct report_density_desc *)(den_header
2488 	    + sizeof (struct report_density_header));
2489 
2490 	/*
2491 	 * Decide the drive type by assigning organization
2492 	 */
2493 	for (i = 0; i < ST_NUM_MEMBERS(st_vid_dt); i ++) {
2494 		if (strncmp(st_vid_dt[i].vid, (char *)(den_desc->ass_org),
2495 		    8) == 0) {
2496 			dp->type = st_vid_dt[i].type;
2497 			break;
2498 		}
2499 	}
2500 	if (i == ST_NUM_MEMBERS(st_vid_dt)) {
2501 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2502 		    "st_get_conf_from_tape_drive(): "
2503 		    "can't find match of assigned ort.\n");
2504 		kmem_free(den_header, buflen);
2505 		return (0);
2506 	}
2507 
2508 	/*
2509 	 * The tape drive may support many tape formats, but the st driver
2510 	 * supports only the four highest densities. Since density code
2511 	 * values are returned by ascending sequence, we start from the
2512 	 * last entry of density support data block descriptor.
2513 	 */
2514 	p = 0;
2515 	den_desc += num_den - 1;
2516 	for (i = 0; i < num_den && p < NDENSITIES; i ++, den_desc --) {
2517 		if ((den_desc->pri_den != 0) && (den_desc->wrtok)) {
2518 			if (p != 0) {
2519 				if (den_desc->pri_den >= den[p - 1]) {
2520 					continue;
2521 				}
2522 			}
2523 			den[p] = den_desc->pri_den;
2524 			deflt[p] = den_desc->deflt;
2525 			p ++;
2526 		}
2527 	}
2528 
2529 	switch (p) {
2530 	case 0:
2531 		bzero(dp->densities, NDENSITIES);
2532 		dp->options |= ST_AUTODEN_OVERRIDE;
2533 		dp->default_density = MT_DENSITY4;
2534 		break;
2535 
2536 	case 1:
2537 		(void) memset(dp->densities, den[0], NDENSITIES);
2538 		dp->options |= ST_AUTODEN_OVERRIDE;
2539 		dp->default_density = MT_DENSITY4;
2540 		break;
2541 
2542 	case 2:
2543 		dp->densities[0] = den[1];
2544 		dp->densities[1] = den[1];
2545 		dp->densities[2] = den[0];
2546 		dp->densities[3] = den[0];
2547 		if (deflt[0]) {
2548 			dp->default_density = MT_DENSITY4;
2549 		} else {
2550 			dp->default_density = MT_DENSITY2;
2551 		}
2552 		break;
2553 
2554 	case 3:
2555 		dp->densities[0] = den[2];
2556 		dp->densities[1] = den[1];
2557 		dp->densities[2] = den[0];
2558 		dp->densities[3] = den[0];
2559 		if (deflt[0]) {
2560 			dp->default_density = MT_DENSITY4;
2561 		} else if (deflt[1]) {
2562 			dp->default_density = MT_DENSITY2;
2563 		} else {
2564 			dp->default_density = MT_DENSITY1;
2565 		}
2566 		break;
2567 
2568 	default:
2569 		for (i = p; i > p - NDENSITIES; i --) {
2570 			dp->densities[i - 1] = den[p - i];
2571 		}
2572 		if (deflt[0]) {
2573 			dp->default_density = MT_DENSITY4;
2574 		} else if (deflt[1]) {
2575 			dp->default_density = MT_DENSITY3;
2576 		} else if (deflt[2]) {
2577 			dp->default_density = MT_DENSITY2;
2578 		} else {
2579 			dp->default_density = MT_DENSITY1;
2580 		}
2581 		break;
2582 	}
2583 
2584 	bzero(dp->mediatype, NDENSITIES);
2585 
2586 	kmem_free(den_header, buflen);
2587 	return (1);
2588 }
2589 
2590 static int
2591 st_get_timeout_values_from_tape_drive(struct scsi_tape *un,
2592     struct st_drivetype *dp)
2593 {
2594 	ushort_t timeout;
2595 	int rval;
2596 
2597 	ST_FUNC(ST_DEVINFO, st_get_timeout_values_from_type_drive);
2598 
2599 	rval = st_get_timeouts_value(un, SCMD_ERASE, &timeout, 0);
2600 	if (rval) {
2601 		if (rval == EACCES) {
2602 			un->un_dp->type = ST_TYPE_INVALID;
2603 			dp->type = ST_TYPE_INVALID;
2604 			return (1);
2605 		}
2606 		return (0);
2607 	}
2608 	dp->erase_timeout = timeout;
2609 
2610 	rval = st_get_timeouts_value(un, SCMD_READ, &timeout, 0);
2611 	if (rval) {
2612 		if (rval == EACCES) {
2613 			un->un_dp->type = ST_TYPE_INVALID;
2614 			dp->type = ST_TYPE_INVALID;
2615 			return (1);
2616 		}
2617 		return (0);
2618 	}
2619 	dp->io_timeout = timeout;
2620 
2621 	rval = st_get_timeouts_value(un, SCMD_WRITE, &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->io_timeout = max(dp->io_timeout, timeout);
2631 
2632 	rval = st_get_timeouts_value(un, SCMD_SPACE, &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->space_timeout = timeout;
2642 
2643 	rval = st_get_timeouts_value(un, SCMD_LOAD, &timeout, 0);
2644 	if (rval) {
2645 		if (rval == EACCES) {
2646 			un->un_dp->type = ST_TYPE_INVALID;
2647 			dp->type = ST_TYPE_INVALID;
2648 			return (1);
2649 		}
2650 		return (0);
2651 	}
2652 	dp->load_timeout = timeout;
2653 	dp->unload_timeout = timeout;
2654 
2655 	rval = st_get_timeouts_value(un, SCMD_REWIND, &timeout, 0);
2656 	if (rval) {
2657 		if (rval == EACCES) {
2658 			un->un_dp->type = ST_TYPE_INVALID;
2659 			dp->type = ST_TYPE_INVALID;
2660 			return (1);
2661 		}
2662 		return (0);
2663 	}
2664 	dp->rewind_timeout = timeout;
2665 
2666 	rval = st_get_timeouts_value(un, SCMD_INQUIRY, &timeout, 0);
2667 	if (rval) {
2668 		if (rval == EACCES) {
2669 			un->un_dp->type = ST_TYPE_INVALID;
2670 			dp->type = ST_TYPE_INVALID;
2671 			return (1);
2672 		}
2673 		return (0);
2674 	}
2675 	dp->non_motion_timeout = timeout;
2676 
2677 	return (1);
2678 }
2679 
2680 static int
2681 st_get_timeouts_value(struct scsi_tape *un, uchar_t option_code,
2682     ushort_t *timeout_value, ushort_t service_action)
2683 {
2684 	uchar_t *timeouts;
2685 	uchar_t *oper;
2686 	uchar_t support;
2687 	uchar_t cdbsize;
2688 	uchar_t ctdp;
2689 	size_t buflen;
2690 	int rval;
2691 
2692 	ST_FUNC(ST_DEVINFO, st_get_timeouts_value);
2693 
2694 	buflen = sizeof (struct one_com_des) +
2695 	    sizeof (struct com_timeout_des);
2696 	oper = kmem_zalloc(buflen, KM_SLEEP);
2697 	rval = st_report_supported_operation(un, oper, option_code,
2698 	    service_action);
2699 
2700 	if (rval) {
2701 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2702 		    "st_get_timeouts_value(): "
2703 		    "fail to timeouts value for command %d.\n", option_code);
2704 		kmem_free(oper, buflen);
2705 		return (rval);
2706 	}
2707 
2708 	support = ((struct one_com_des *)oper)->support;
2709 	if ((support != SUPPORT_VALUES_SUPPORT_SCSI) &&
2710 	    (support != SUPPORT_VALUES_SUPPORT_VENDOR)) {
2711 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2712 		    "st_get_timeouts_value(): "
2713 		    "command %d is not supported.\n", option_code);
2714 		kmem_free(oper, buflen);
2715 		return (ENOTSUP);
2716 	}
2717 
2718 	ctdp = ((struct one_com_des *)oper)->ctdp;
2719 	if (!ctdp) {
2720 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2721 		    "st_get_timeouts_value(): "
2722 		    "command timeout is not included.\n");
2723 		kmem_free(oper, buflen);
2724 		return (ENOTSUP);
2725 	}
2726 
2727 	cdbsize = BE_16(((struct one_com_des *)oper)->cdb_size);
2728 	timeouts = (uchar_t *)(oper + cdbsize + 4);
2729 
2730 	/*
2731 	 * Timeout value in seconds is 4 bytes, but we only support the lower 2
2732 	 * bytes. If the higher 2 bytes are not zero, the timeout value is set
2733 	 * to 0xFFFF.
2734 	 */
2735 	if (*(timeouts + 8) != 0 || *(timeouts + 9) != 0) {
2736 		*timeout_value = USHRT_MAX;
2737 	} else {
2738 		*timeout_value = ((*(timeouts + 10)) << 8) |
2739 		    (*(timeouts + 11));
2740 	}
2741 
2742 	kmem_free(oper, buflen);
2743 	return (0);
2744 }
2745 
2746 static int
2747 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2748 {
2749 	int i;
2750 
2751 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2752 
2753 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2754 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2755 
2756 	/*
2757 	 * Make up a name
2758 	 */
2759 	bcopy("Vendor '", dp->name, 8);
2760 	bcopy(vidpid, &dp->name[8], VIDLEN);
2761 	bcopy("' Product '", &dp->name[16], 11);
2762 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2763 	dp->name[ST_NAMESIZE - 2] = '\'';
2764 	dp->name[ST_NAMESIZE - 1] = '\0';
2765 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2766 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2767 	/*
2768 	 * 'clean' vendor and product strings of non-printing chars
2769 	 */
2770 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2771 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2772 			dp->name[i] = '.';
2773 		}
2774 	}
2775 	dp->type = ST_TYPE_INVALID;
2776 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2777 
2778 	return (1); /* Can Not Fail */
2779 }
2780 
2781 /*
2782  * Regular Unix Entry points
2783  */
2784 
2785 
2786 
2787 /* ARGSUSED */
2788 static int
2789 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2790 {
2791 	dev_t dev = *dev_p;
2792 	int rval = 0;
2793 
2794 	GET_SOFT_STATE(dev);
2795 
2796 	ST_ENTR(ST_DEVINFO, st_open);
2797 
2798 	/*
2799 	 * validate that we are addressing a sensible unit
2800 	 */
2801 	mutex_enter(ST_MUTEX);
2802 
2803 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2804 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2805 	    st_dev_name(dev), *dev_p, flag, otyp);
2806 
2807 	/*
2808 	 * All device accesss go thru st_strategy() where we check
2809 	 * suspend status
2810 	 */
2811 
2812 	if (!un->un_attached) {
2813 		st_known_tape_type(un);
2814 		if (!un->un_attached) {
2815 			rval = ENXIO;
2816 			goto exit;
2817 		}
2818 
2819 	}
2820 
2821 	/*
2822 	 * Check for the case of the tape in the middle of closing.
2823 	 * This isn't simply a check of the current state, because
2824 	 * we could be in state of sensing with the previous state
2825 	 * that of closing.
2826 	 *
2827 	 * And don't allow multiple opens.
2828 	 */
2829 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2830 		un->un_laststate = un->un_state;
2831 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2832 		while (IS_CLOSING(un) ||
2833 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2834 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2835 				rval = EINTR;
2836 				un->un_state = un->un_laststate;
2837 				goto exit;
2838 			}
2839 		}
2840 	} else if (un->un_state != ST_STATE_CLOSED) {
2841 		rval = EBUSY;
2842 		goto busy;
2843 	}
2844 
2845 	/*
2846 	 * record current dev
2847 	 */
2848 	un->un_dev = dev;
2849 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2850 	un->un_errno = 0;	/* no errors yet */
2851 	un->un_restore_pos = 0;
2852 	un->un_rqs_state = 0;
2853 
2854 	/*
2855 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2856 	 * anything, leave internal states alone, if fileno >= 0
2857 	 */
2858 	if (flag & (FNDELAY | FNONBLOCK)) {
2859 		switch (un->un_pos.pmode) {
2860 
2861 		case invalid:
2862 			un->un_state = ST_STATE_OFFLINE;
2863 			break;
2864 
2865 		case legacy:
2866 			/*
2867 			 * If position is anything other than rewound.
2868 			 */
2869 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2870 				/*
2871 				 * set un_read_only/write-protect status.
2872 				 *
2873 				 * If the tape is not bot we can assume
2874 				 * that mspl->wp_status is set properly.
2875 				 * else
2876 				 * we need to do a mode sense/Tur once
2877 				 * again to get the actual tape status.(since
2878 				 * user might have replaced the tape)
2879 				 * Hence make the st state OFFLINE so that
2880 				 * we re-intialize the tape once again.
2881 				 */
2882 				un->un_read_only =
2883 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2884 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2885 			} else {
2886 				un->un_state = ST_STATE_OFFLINE;
2887 			}
2888 			break;
2889 		case logical:
2890 			if (un->un_pos.lgclblkno == 0) {
2891 				un->un_state = ST_STATE_OFFLINE;
2892 			} else {
2893 				un->un_read_only =
2894 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2895 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2896 			}
2897 			break;
2898 		}
2899 		rval = 0;
2900 	} else {
2901 		/*
2902 		 * Not opening O_NDELAY.
2903 		 */
2904 		un->un_state = ST_STATE_OPENING;
2905 
2906 		/*
2907 		 * Clear error entry stack
2908 		 */
2909 		st_empty_error_stack(un);
2910 
2911 		rval = st_tape_init(un);
2912 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2913 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2914 			rval = 0; /* so open doesn't fail */
2915 		} else if (rval) {
2916 			/*
2917 			 * Release the tape unit, if reserved and not
2918 			 * preserve reserve.
2919 			 */
2920 			if ((un->un_rsvd_status &
2921 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2922 				(void) st_reserve_release(un, ST_RELEASE,
2923 				    st_uscsi_cmd);
2924 			}
2925 		} else {
2926 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2927 		}
2928 	}
2929 
2930 exit:
2931 	/*
2932 	 * we don't want any uninvited guests scrogging our data when we're
2933 	 * busy with something, so for successful opens or failed opens
2934 	 * (except for EBUSY), reset these counters and state appropriately.
2935 	 */
2936 	if (rval != EBUSY) {
2937 		if (rval) {
2938 			un->un_state = ST_STATE_CLOSED;
2939 		}
2940 		un->un_err_resid = 0;
2941 		un->un_retry_ct = 0;
2942 	}
2943 busy:
2944 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2945 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2946 	mutex_exit(ST_MUTEX);
2947 	return (rval);
2948 
2949 }
2950 
2951 static int
2952 st_tape_init(struct scsi_tape *un)
2953 {
2954 	int err;
2955 	int rval = 0;
2956 
2957 	ST_FUNC(ST_DEVINFO, st_tape_init);
2958 
2959 	ASSERT(mutex_owned(ST_MUTEX));
2960 
2961 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2962 	    "st_tape_init(un = 0x%p, oflags = %d)\n", (void*)un, un->un_oflags);
2963 
2964 	/*
2965 	 * Clean up after any errors left by 'last' close.
2966 	 * This also handles the case of the initial open.
2967 	 */
2968 	if (un->un_state != ST_STATE_INITIALIZING) {
2969 		un->un_laststate = un->un_state;
2970 		un->un_state = ST_STATE_OPENING;
2971 	}
2972 
2973 	un->un_kbytes_xferred = 0;
2974 
2975 	/*
2976 	 * do a throw away TUR to clear check condition
2977 	 */
2978 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2979 
2980 	/*
2981 	 * If test unit ready fails because the drive is reserved
2982 	 * by another host fail the open for no access.
2983 	 */
2984 	if (err) {
2985 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2986 			un->un_state = ST_STATE_CLOSED;
2987 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2988 			    "st_tape_init: RESERVATION CONFLICT\n");
2989 			rval = EACCES;
2990 			goto exit;
2991 		} else if ((un->un_rsvd_status &
2992 		    ST_APPLICATION_RESERVATIONS) != 0) {
2993 			if ((ST_RQSENSE != NULL) &&
2994 			    (ST_RQSENSE->es_add_code == 0x2a &&
2995 			    ST_RQSENSE->es_qual_code == 0x03)) {
2996 				un->un_state = ST_STATE_CLOSED;
2997 				rval = EACCES;
2998 				goto exit;
2999 			}
3000 		}
3001 	}
3002 
3003 	/*
3004 	 * Tape self identification could fail if the tape drive is used by
3005 	 * another host during attach time. We try to get the tape type
3006 	 * again. This is also applied to any posponed configuration methods.
3007 	 */
3008 	if (un->un_dp->type == ST_TYPE_INVALID) {
3009 		un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
3010 		st_known_tape_type(un);
3011 	}
3012 
3013 	/*
3014 	 * If the tape type is still invalid, try to determine the generic
3015 	 * configuration.
3016 	 */
3017 	if (un->un_dp->type == ST_TYPE_INVALID) {
3018 		rval = st_determine_generic(un);
3019 		if (rval) {
3020 			if (rval != EACCES) {
3021 				rval = EIO;
3022 			}
3023 			un->un_state = ST_STATE_CLOSED;
3024 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3025 			    "st_tape_init: %s invalid type\n",
3026 			    rval == EACCES ? "EACCES" : "EIO");
3027 			goto exit;
3028 		}
3029 		/*
3030 		 * If this is a Unknown Type drive,
3031 		 * Use the READ BLOCK LIMITS to determine if
3032 		 * allow large xfer is approprate if not globally
3033 		 * disabled with st_allow_large_xfer.
3034 		 */
3035 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
3036 	} else {
3037 
3038 		/*
3039 		 * If we allow_large_xfer (ie >64k) and have not yet found out
3040 		 * the max block size supported by the drive,
3041 		 * find it by issueing a READ_BLKLIM command.
3042 		 * if READ_BLKLIM cmd fails, assume drive doesn't
3043 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
3044 		 */
3045 		un->un_allow_large_xfer = st_allow_large_xfer &&
3046 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
3047 	}
3048 	/*
3049 	 * if maxbsize is unknown, set the maximum block size.
3050 	 */
3051 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
3052 
3053 		/*
3054 		 * Get the Block limits of the tape drive.
3055 		 * if un->un_allow_large_xfer = 0 , then make sure
3056 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
3057 		 */
3058 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
3059 
3060 		err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3061 		if (err) {
3062 			/* Retry */
3063 			err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3064 		}
3065 		if (!err) {
3066 
3067 			/*
3068 			 * if cmd successful, use limit returned
3069 			 */
3070 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
3071 			    (un->un_rbl->max_mid << 8) +
3072 			    un->un_rbl->max_lo;
3073 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
3074 			    un->un_rbl->min_lo;
3075 			un->un_data_mod = 1 << un->un_rbl->granularity;
3076 			if ((un->un_maxbsize == 0) ||
3077 			    (un->un_allow_large_xfer == 0 &&
3078 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
3079 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3080 
3081 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
3082 				/*
3083 				 * Drive is not one that is configured, But the
3084 				 * READ BLOCK LIMITS tells us it can do large
3085 				 * xfers.
3086 				 */
3087 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
3088 					un->un_dp->options |=
3089 					    ST_NO_RECSIZE_LIMIT;
3090 				}
3091 				/*
3092 				 * If max and mimimum block limits are the
3093 				 * same this is a fixed block size device.
3094 				 */
3095 				if (un->un_maxbsize == un->un_minbsize) {
3096 					un->un_dp->options &= ~ST_VARIABLE;
3097 				}
3098 			}
3099 
3100 			if (un->un_minbsize == 0) {
3101 				un->un_minbsize = 1;
3102 			}
3103 
3104 		} else { /* error on read block limits */
3105 
3106 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3107 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
3108 			    " errno = %d un_rsvd_status = 0x%X\n",
3109 			    err, un->un_rsvd_status);
3110 
3111 			/*
3112 			 * since read block limits cmd failed,
3113 			 * do not allow large xfers.
3114 			 * use old values in st_minphys
3115 			 */
3116 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
3117 				rval = EACCES;
3118 			} else {
3119 				un->un_allow_large_xfer = 0;
3120 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3121 				    "!Disabling large transfers\n");
3122 
3123 				/*
3124 				 * we guess maxbsize and minbsize
3125 				 */
3126 				if (un->un_bsize) {
3127 					un->un_maxbsize = un->un_minbsize =
3128 					    un->un_bsize;
3129 				} else {
3130 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3131 					un->un_minbsize = 1;
3132 				}
3133 				/*
3134 				 * Data Mod must be set,
3135 				 * Even if read block limits fails.
3136 				 * Prevents Divide By Zero in st_rw().
3137 				 */
3138 				un->un_data_mod = 1;
3139 			}
3140 		}
3141 		if (un->un_rbl) {
3142 			kmem_free(un->un_rbl, RBLSIZE);
3143 			un->un_rbl = NULL;
3144 		}
3145 
3146 		if (rval) {
3147 			goto exit;
3148 		}
3149 	}
3150 
3151 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3152 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
3153 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
3154 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
3155 
3156 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
3157 
3158 	if (err != 0) {
3159 		if (err == EINTR) {
3160 			un->un_laststate = un->un_state;
3161 			un->un_state = ST_STATE_CLOSED;
3162 			rval = EINTR;
3163 			goto exit;
3164 		}
3165 		/*
3166 		 * Make sure the tape is ready
3167 		 */
3168 		un->un_pos.pmode = invalid;
3169 		if (un->un_status != KEY_UNIT_ATTENTION) {
3170 			/*
3171 			 * allow open no media.  Subsequent MTIOCSTATE
3172 			 * with media present will complete the open
3173 			 * logic.
3174 			 */
3175 			un->un_laststate = un->un_state;
3176 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
3177 				un->un_mediastate = MTIO_EJECTED;
3178 				un->un_state = ST_STATE_OFFLINE;
3179 				rval = 0;
3180 				goto exit;
3181 			} else {
3182 				un->un_state = ST_STATE_CLOSED;
3183 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3184 				    "st_tape_init EIO no media, not opened "
3185 				    "O_NONBLOCK|O_EXCL\n");
3186 				rval = EIO;
3187 				goto exit;
3188 			}
3189 		}
3190 	}
3191 
3192 	/*
3193 	 * On each open, initialize block size from drivetype struct,
3194 	 * as it could have been changed by MTSRSZ ioctl.
3195 	 * Now, ST_VARIABLE simply means drive is capable of variable
3196 	 * mode. All drives are assumed to support fixed records.
3197 	 * Hence, un_bsize tells what mode the drive is in.
3198 	 *	un_bsize	= 0	- variable record length
3199 	 *			= x	- fixed record length is x
3200 	 */
3201 	un->un_bsize = un->un_dp->bsize;
3202 
3203 	/*
3204 	 * If saved position is valid go there
3205 	 */
3206 	if (un->un_restore_pos) {
3207 		un->un_restore_pos = 0;
3208 		un->un_pos.fileno = un->un_save_fileno;
3209 		un->un_pos.blkno = un->un_save_blkno;
3210 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &un->un_pos);
3211 		if (rval != 0) {
3212 			if (rval != EACCES) {
3213 				rval = EIO;
3214 			}
3215 			un->un_laststate = un->un_state;
3216 			un->un_state = ST_STATE_CLOSED;
3217 			goto exit;
3218 		}
3219 	}
3220 
3221 	if (un->un_pos.pmode == invalid) {
3222 		rval = st_loadtape(un);
3223 		if (rval) {
3224 			if (rval != EACCES) {
3225 				rval = EIO;
3226 			}
3227 			un->un_laststate = un->un_state;
3228 			un->un_state = ST_STATE_CLOSED;
3229 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3230 			    "st_tape_init: %s can't open tape\n",
3231 			    rval == EACCES ? "EACCES" : "EIO");
3232 			goto exit;
3233 		}
3234 	}
3235 
3236 	/*
3237 	 * do a mode sense to pick up state of current write-protect,
3238 	 * Could cause reserve and fail due to conflict.
3239 	 */
3240 	if (un->un_unit_attention_flags) {
3241 		rval = st_modesense(un);
3242 		if (rval == EACCES) {
3243 			goto exit;
3244 		}
3245 	}
3246 
3247 	/*
3248 	 * If we are opening the tape for writing, check
3249 	 * to make sure that the tape can be written.
3250 	 */
3251 	if (un->un_oflags & FWRITE) {
3252 		err = 0;
3253 		if (un->un_mspl->wp) {
3254 			un->un_status = KEY_WRITE_PROTECT;
3255 			un->un_laststate = un->un_state;
3256 			un->un_state = ST_STATE_CLOSED;
3257 			rval = EACCES;
3258 			/*
3259 			 * STK sets the wp bit if volsafe tape is loaded.
3260 			 */
3261 			if ((un->un_dp->type == MT_ISSTK9840) &&
3262 			    (un->un_dp->options & ST_WORMABLE)) {
3263 				un->un_read_only = RDONLY;
3264 			} else {
3265 				goto exit;
3266 			}
3267 		} else {
3268 			un->un_read_only = RDWR;
3269 		}
3270 	} else {
3271 		un->un_read_only = RDONLY;
3272 	}
3273 
3274 	if (un->un_dp->options & ST_WORMABLE &&
3275 	    un->un_unit_attention_flags) {
3276 		un->un_read_only |= un->un_wormable(un);
3277 
3278 		if (((un->un_read_only == WORM) ||
3279 		    (un->un_read_only == RDWORM)) &&
3280 		    ((un->un_oflags & FWRITE) == FWRITE)) {
3281 			un->un_status = KEY_DATA_PROTECT;
3282 			rval = EACCES;
3283 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3284 			    "read_only = %d eof = %d oflag = %d\n",
3285 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3286 		}
3287 	}
3288 
3289 	/*
3290 	 * If we're opening the tape write-only, we need to
3291 	 * write 2 filemarks on the HP 1/2 inch drive, to
3292 	 * create a null file.
3293 	 */
3294 	if ((un->un_read_only == RDWR) ||
3295 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3296 		if (un->un_dp->options & ST_REEL) {
3297 			un->un_fmneeded = 2;
3298 		} else {
3299 			un->un_fmneeded = 1;
3300 		}
3301 	} else {
3302 		un->un_fmneeded = 0;
3303 	}
3304 
3305 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3306 	    "fmneeded = %x\n", un->un_fmneeded);
3307 
3308 	/*
3309 	 * Make sure the density can be selected correctly.
3310 	 * If WORM can only write at the append point which in most cases
3311 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3312 	 * to set and try densities if a BOP.
3313 	 */
3314 	if (st_determine_density(un,
3315 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3316 		un->un_status = KEY_ILLEGAL_REQUEST;
3317 		un->un_laststate = un->un_state;
3318 		un->un_state = ST_STATE_CLOSED;
3319 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3320 		    "st_tape_init: EIO can't determine density\n");
3321 		rval = EIO;
3322 		goto exit;
3323 	}
3324 
3325 	/*
3326 	 * Destroy the knowledge that we have 'determined'
3327 	 * density so that a later read at BOT comes along
3328 	 * does the right density determination.
3329 	 */
3330 
3331 	un->un_density_known = 0;
3332 
3333 
3334 	/*
3335 	 * Okay, the tape is loaded and either at BOT or somewhere past.
3336 	 * Mark the state such that any I/O or tape space operations
3337 	 * will get/set the right density, etc..
3338 	 */
3339 	un->un_laststate = un->un_state;
3340 	un->un_lastop = ST_OP_NIL;
3341 	un->un_mediastate = MTIO_INSERTED;
3342 	cv_broadcast(&un->un_state_cv);
3343 
3344 	/*
3345 	 *  Set test append flag if writing.
3346 	 *  First write must check that tape is positioned correctly.
3347 	 */
3348 	un->un_test_append = (un->un_oflags & FWRITE);
3349 
3350 	/*
3351 	 * if there are pending unit attention flags.
3352 	 * Check that the media has not changed.
3353 	 */
3354 	if (un->un_unit_attention_flags) {
3355 		rval = st_get_media_identification(un, st_uscsi_cmd);
3356 		if (rval != 0 && rval != EACCES) {
3357 			rval = EIO;
3358 		}
3359 		un->un_unit_attention_flags = 0;
3360 	}
3361 
3362 exit:
3363 	un->un_err_resid = 0;
3364 	un->un_last_resid = 0;
3365 	un->un_last_count = 0;
3366 
3367 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3368 	    "st_tape_init: return val = %x\n", rval);
3369 	return (rval);
3370 
3371 }
3372 
3373 
3374 
3375 /* ARGSUSED */
3376 static int
3377 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3378 {
3379 	int err = 0;
3380 	int count, last_state;
3381 	minor_t minor = getminor(dev);
3382 #ifdef	__x86
3383 	struct contig_mem *cp, *cp_temp;
3384 #endif
3385 
3386 	GET_SOFT_STATE(dev);
3387 
3388 	ST_ENTR(ST_DEVINFO, st_close);
3389 
3390 	/*
3391 	 * wait till all cmds in the pipeline have been completed
3392 	 */
3393 	mutex_enter(ST_MUTEX);
3394 
3395 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3396 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3397 
3398 	st_wait_for_io(un);
3399 
3400 	/* turn off persistent errors on close, as we want close to succeed */
3401 	st_turn_pe_off(un);
3402 
3403 	/*
3404 	 * set state to indicate that we are in process of closing
3405 	 */
3406 	last_state = un->un_laststate = un->un_state;
3407 	un->un_state = ST_STATE_CLOSING;
3408 
3409 	ST_POS(ST_DEVINFO, "st_close1:", &un->un_pos);
3410 
3411 	/*
3412 	 * BSD behavior:
3413 	 * a close always causes a silent span to the next file if we've hit
3414 	 * an EOF (but not yet read across it).
3415 	 */
3416 	if ((minor & MT_BSD) && (un->un_pos.eof == ST_EOF)) {
3417 		if (un->un_pos.pmode != invalid) {
3418 			un->un_pos.fileno++;
3419 			un->un_pos.blkno = 0;
3420 		}
3421 		un->un_pos.eof = ST_NO_EOF;
3422 	}
3423 
3424 	/*
3425 	 * SVR4 behavior for skipping to next file:
3426 	 *
3427 	 * If we have not seen a filemark, space to the next file
3428 	 *
3429 	 * If we have already seen the filemark we are physically in the next
3430 	 * file and we only increment the filenumber
3431 	 */
3432 	if (((minor & (MT_BSD | MT_NOREWIND)) == MT_NOREWIND) &&
3433 	    (flag & FREAD) &&		/* reading or at least asked to */
3434 	    (un->un_mediastate == MTIO_INSERTED) &&	/* tape loaded */
3435 	    (un->un_pos.pmode != invalid) &&		/* XXX position known */
3436 	    ((un->un_pos.blkno != 0) && 		/* inside a file */
3437 	    (un->un_lastop != ST_OP_WRITE) &&		/* Didn't just write */
3438 	    (un->un_lastop != ST_OP_WEOF))) {		/* or write filemarks */
3439 		switch (un->un_pos.eof) {
3440 		case ST_NO_EOF:
3441 			/*
3442 			 * if we were reading and did not read the complete file
3443 			 * skip to the next file, leaving the tape correctly
3444 			 * positioned to read the first record of the next file
3445 			 * Check first for REEL if we are at EOT by trying to
3446 			 * read a block
3447 			 */
3448 			if ((un->un_dp->options & ST_REEL) &&
3449 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3450 			    (un->un_pos.blkno == 0)) {
3451 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3452 					ST_DEBUG2(ST_DEVINFO, st_label,
3453 					    SCSI_DEBUG,
3454 					    "st_close : EIO can't space\n");
3455 					err = EIO;
3456 					goto error_out;
3457 				}
3458 				if (un->un_pos.eof >= ST_EOF_PENDING) {
3459 					un->un_pos.eof = ST_EOT_PENDING;
3460 					un->un_pos.fileno += 1;
3461 					un->un_pos.blkno   = 0;
3462 					break;
3463 				}
3464 			}
3465 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3466 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3467 				    "st_close: EIO can't space #2\n");
3468 				err = EIO;
3469 				goto error_out;
3470 			} else {
3471 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3472 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3473 				    un->un_pos.fileno, un->un_pos.blkno,
3474 				    un->un_pos.eof);
3475 				un->un_pos.eof = ST_NO_EOF;
3476 			}
3477 			break;
3478 
3479 		case ST_EOF_PENDING:
3480 		case ST_EOF:
3481 			un->un_pos.fileno += 1;
3482 			un->un_pos.lgclblkno += 1;
3483 			un->un_pos.blkno   = 0;
3484 			un->un_pos.eof = ST_NO_EOF;
3485 			break;
3486 
3487 		case ST_EOT:
3488 		case ST_EOT_PENDING:
3489 		case ST_EOM:
3490 			/* nothing to do */
3491 			break;
3492 		default:
3493 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
3494 			    "Undefined state 0x%x", un->un_pos.eof);
3495 
3496 		}
3497 	}
3498 
3499 
3500 	/*
3501 	 * For performance reasons (HP 88780), the driver should
3502 	 * postpone writing the second tape mark until just before a file
3503 	 * positioning ioctl is issued (e.g., rewind).	This means that
3504 	 * the user must not manually rewind the tape because the tape will
3505 	 * be missing the second tape mark which marks EOM.
3506 	 * However, this small performance improvement is not worth the risk.
3507 	 */
3508 
3509 	/*
3510 	 * We need to back up over the filemark we inadvertently popped
3511 	 * over doing a read in between the two filemarks that constitute
3512 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3513 	 * set while reading.
3514 	 *
3515 	 * If we happen to be at physical eot (ST_EOM) (writing case),
3516 	 * the writing of filemark(s) will clear the ST_EOM state, which
3517 	 * we don't want, so we save this state and restore it later.
3518 	 */
3519 
3520 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3521 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3522 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3523 
3524 	if (un->un_pos.eof == ST_EOT_PENDING) {
3525 		if (minor & MT_NOREWIND) {
3526 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3527 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3528 				    "st_close: EIO can't space #3\n");
3529 				err = EIO;
3530 				goto error_out;
3531 			} else {
3532 				un->un_pos.blkno = 0;
3533 				un->un_pos.eof = ST_EOT;
3534 			}
3535 		} else {
3536 			un->un_pos.eof = ST_NO_EOF;
3537 		}
3538 
3539 	/*
3540 	 * Do we need to write a file mark?
3541 	 *
3542 	 * only write filemarks if there are fmks to be written and
3543 	 *   - open for write (possibly read/write)
3544 	 *   - the last operation was a write
3545 	 * or:
3546 	 *   -	opened for wronly
3547 	 *   -	no data was written
3548 	 */
3549 	} else if ((un->un_pos.pmode != invalid) &&
3550 	    (un->un_fmneeded > 0) &&
3551 	    (((flag & FWRITE) &&
3552 	    ((un->un_lastop == ST_OP_WRITE)||(un->un_lastop == ST_OP_WEOF))) ||
3553 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3554 
3555 		/* save ST_EOM state */
3556 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3557 
3558 		/*
3559 		 * Note that we will write a filemark if we had opened
3560 		 * the tape write only and no data was written, thus
3561 		 * creating a null file.
3562 		 *
3563 		 * If the user already wrote one, we only have to write 1 more.
3564 		 * If they wrote two, we don't have to write any.
3565 		 */
3566 
3567 		count = un->un_fmneeded;
3568 		if (count > 0) {
3569 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, count, SYNC_CMD)) {
3570 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3571 				    "st_close : EIO can't wfm\n");
3572 				err = EIO;
3573 				goto error_out;
3574 			}
3575 			if ((un->un_dp->options & ST_REEL) &&
3576 			    (minor & MT_NOREWIND)) {
3577 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3578 					ST_DEBUG2(ST_DEVINFO, st_label,
3579 					    SCSI_DEBUG,
3580 					    "st_close : EIO space fmk(-1)\n");
3581 					err = EIO;
3582 					goto error_out;
3583 				}
3584 				un->un_pos.eof = ST_NO_EOF;
3585 				/* fix up block number */
3586 				un->un_pos.blkno = 0;
3587 			}
3588 		}
3589 
3590 		/*
3591 		 * If we aren't going to be rewinding, and we were at
3592 		 * physical eot, restore the state that indicates we
3593 		 * are at physical eot. Once you have reached physical
3594 		 * eot, and you close the tape, the only thing you can
3595 		 * do on the next open is to rewind. Access to trailer
3596 		 * records is only allowed without closing the device.
3597 		 */
3598 		if ((minor & MT_NOREWIND) == 0 && was_at_eom) {
3599 			un->un_pos.eof = ST_EOM;
3600 		}
3601 	}
3602 
3603 	/*
3604 	 * report soft errors if enabled and available, if we never accessed
3605 	 * the drive, don't get errors. This will prevent some DAT error
3606 	 * messages upon LOG SENSE.
3607 	 */
3608 	if (st_report_soft_errors_on_close &&
3609 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3610 	    (last_state != ST_STATE_OFFLINE)) {
3611 		if (st_report_soft_errors(dev, flag)) {
3612 			err = EIO;
3613 			goto error_out;
3614 		}
3615 	}
3616 
3617 
3618 	/*
3619 	 * Do we need to rewind? Can we rewind?
3620 	 */
3621 	if ((minor & MT_NOREWIND) == 0 &&
3622 	    un->un_pos.pmode != invalid && err == 0) {
3623 		/*
3624 		 * We'd like to rewind with the
3625 		 * 'immediate' bit set, but this
3626 		 * causes problems on some drives
3627 		 * where subsequent opens get a
3628 		 * 'NOT READY' error condition
3629 		 * back while the tape is rewinding,
3630 		 * which is impossible to distinguish
3631 		 * from the condition of 'no tape loaded'.
3632 		 *
3633 		 * Also, for some targets, if you disconnect
3634 		 * with the 'immediate' bit set, you don't
3635 		 * actually return right away, i.e., the
3636 		 * target ignores your request for immediate
3637 		 * return.
3638 		 *
3639 		 * Instead, we'll fire off an async rewind
3640 		 * command. We'll mark the device as closed,
3641 		 * and any subsequent open will stall on
3642 		 * the first TEST_UNIT_READY until the rewind
3643 		 * completes.
3644 		 */
3645 
3646 		/*
3647 		 * Used to be if reserve was not supported we'd send an
3648 		 * asynchronious rewind. Comments above may be slightly invalid
3649 		 * as the immediate bit was never set. Doing an immedate rewind
3650 		 * makes sense, I think fixes to not ready status might handle
3651 		 * the problems described above.
3652 		 */
3653 		if (un->un_sd->sd_inq->inq_ansi < 2) {
3654 			if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
3655 				err = EIO;
3656 			}
3657 		} else {
3658 			/* flush data for older drives per scsi spec. */
3659 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD)) {
3660 				err = EIO;
3661 			} else {
3662 				/* release the drive before rewind immediate */
3663 				if ((un->un_rsvd_status &
3664 				    (ST_RESERVE | ST_PRESERVE_RESERVE)) ==
3665 				    ST_RESERVE) {
3666 					if (st_reserve_release(un, ST_RELEASE,
3667 					    st_uscsi_cmd)) {
3668 						err = EIO;
3669 					}
3670 				}
3671 
3672 				/* send rewind with immediate bit set */
3673 				if (st_cmd(un, SCMD_REWIND, 1, ASYNC_CMD)) {
3674 					err = EIO;
3675 				}
3676 			}
3677 		}
3678 		/*
3679 		 * Setting positions invalid in case the rewind doesn't
3680 		 * happen. Drives don't like to rewind if resets happen
3681 		 * they will tend to move back to where the rewind was
3682 		 * issued if a reset or something happens so that if a
3683 		 * write happens the data doesn't get clobbered.
3684 		 *
3685 		 * Not a big deal if the position is invalid when the
3686 		 * open occures it will do a read position.
3687 		 */
3688 		un->un_pos.pmode = invalid;
3689 		un->un_running.pmode = invalid;
3690 
3691 		if (err == EIO) {
3692 			goto error_out;
3693 		}
3694 	}
3695 
3696 	/*
3697 	 * eject tape if necessary
3698 	 */
3699 	if (un->un_eject_tape_on_failure) {
3700 		un->un_eject_tape_on_failure = 0;
3701 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3702 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3703 			    "st_close : can't unload tape\n");
3704 			err = EIO;
3705 			goto error_out;
3706 		} else {
3707 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3708 			    "st_close : tape unloaded \n");
3709 			un->un_pos.eof = ST_NO_EOF;
3710 			un->un_mediastate = MTIO_EJECTED;
3711 		}
3712 	}
3713 	/*
3714 	 * Release the tape unit, if default reserve/release
3715 	 * behaviour.
3716 	 */
3717 	if ((un->un_rsvd_status &
3718 	    (ST_RESERVE | ST_PRESERVE_RESERVE |
3719 	    ST_APPLICATION_RESERVATIONS)) == ST_RESERVE) {
3720 		(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
3721 	}
3722 error_out:
3723 	/*
3724 	 * clear up state
3725 	 */
3726 	un->un_laststate = un->un_state;
3727 	un->un_state = ST_STATE_CLOSED;
3728 	un->un_lastop = ST_OP_NIL;
3729 	un->un_throttle = 1;	/* assume one request at time, for now */
3730 	un->un_retry_ct = 0;
3731 	un->un_errno = 0;
3732 	un->un_swr_token = (opaque_t)NULL;
3733 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3734 
3735 	/* Restore the options to the init time settings */
3736 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3737 		un->un_dp->options |= ST_READ_IGNORE_ILI;
3738 	} else {
3739 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3740 	}
3741 
3742 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3743 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3744 	} else {
3745 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3746 	}
3747 
3748 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3749 		un->un_dp->options |= ST_SHORT_FILEMARKS;
3750 	} else {
3751 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3752 	}
3753 
3754 	ASSERT(mutex_owned(ST_MUTEX));
3755 
3756 	/*
3757 	 * Signal anyone awaiting a close operation to complete.
3758 	 */
3759 	cv_signal(&un->un_clscv);
3760 
3761 	/*
3762 	 * any kind of error on closing causes all state to be tossed
3763 	 */
3764 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3765 		/*
3766 		 * note that st_intr has already set
3767 		 * un_pos.pmode to invalid.
3768 		 */
3769 		un->un_density_known = 0;
3770 	}
3771 
3772 #ifdef	__x86
3773 	/*
3774 	 * free any contiguous mem alloc'ed for big block I/O
3775 	 */
3776 	cp = un->un_contig_mem;
3777 	while (cp) {
3778 		if (cp->cm_addr) {
3779 			ddi_dma_mem_free(&cp->cm_acc_hdl);
3780 		}
3781 		cp_temp = cp;
3782 		cp = cp->cm_next;
3783 		kmem_free(cp_temp,
3784 		    sizeof (struct contig_mem) + biosize());
3785 	}
3786 	un->un_contig_mem_total_num = 0;
3787 	un->un_contig_mem_available_num = 0;
3788 	un->un_contig_mem = NULL;
3789 	un->un_max_contig_mem_len = 0;
3790 #endif
3791 
3792 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3793 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3794 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3795 
3796 	mutex_exit(ST_MUTEX);
3797 	return (err);
3798 }
3799 
3800 /*
3801  * These routines perform raw i/o operations.
3802  */
3803 
3804 /* ARGSUSED2 */
3805 static int
3806 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3807 {
3808 #ifdef STDEBUG
3809 	GET_SOFT_STATE(dev);
3810 	ST_ENTR(ST_DEVINFO, st_aread);
3811 #endif
3812 	return (st_arw(dev, aio, B_READ));
3813 }
3814 
3815 
3816 /* ARGSUSED2 */
3817 static int
3818 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3819 {
3820 #ifdef STDEBUG
3821 	GET_SOFT_STATE(dev);
3822 	ST_ENTR(ST_DEVINFO, st_awrite);
3823 #endif
3824 	return (st_arw(dev, aio, B_WRITE));
3825 }
3826 
3827 
3828 
3829 /* ARGSUSED */
3830 static int
3831 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3832 {
3833 #ifdef STDEBUG
3834 	GET_SOFT_STATE(dev);
3835 	ST_ENTR(ST_DEVINFO, st_read);
3836 #endif
3837 	return (st_rw(dev, uiop, B_READ));
3838 }
3839 
3840 /* ARGSUSED */
3841 static int
3842 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3843 {
3844 #ifdef STDEBUG
3845 	GET_SOFT_STATE(dev);
3846 	ST_ENTR(ST_DEVINFO, st_write);
3847 #endif
3848 	return (st_rw(dev, uiop, B_WRITE));
3849 }
3850 
3851 /*
3852  * Due to historical reasons, old limits are: For variable-length devices:
3853  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3854  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3855  * (let it through unmodified. For fixed-length record devices:
3856  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3857  *
3858  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3859  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3860  * command to the drive).
3861  *
3862  */
3863 static void
3864 st_minphys(struct buf *bp)
3865 {
3866 	struct scsi_tape *un;
3867 
3868 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3869 
3870 	ST_FUNC(ST_DEVINFO, st_minphys);
3871 
3872 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3873 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3874 	    bp->b_bcount);
3875 
3876 	if (un->un_allow_large_xfer) {
3877 
3878 		/*
3879 		 * check un_maxbsize for variable length devices only
3880 		 */
3881 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3882 			bp->b_bcount = un->un_maxbsize;
3883 		}
3884 		/*
3885 		 * can't go more that HBA maxdma limit in either fixed-length
3886 		 * or variable-length tape drives.
3887 		 */
3888 		if (bp->b_bcount > un->un_maxdma) {
3889 			bp->b_bcount = un->un_maxdma;
3890 		}
3891 	} else {
3892 
3893 		/*
3894 		 *  use old fixed limits
3895 		 */
3896 		if (un->un_bsize == 0) {
3897 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3898 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3899 			}
3900 		} else {
3901 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3902 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3903 			}
3904 		}
3905 	}
3906 
3907 	/*
3908 	 * For regular raw I/O and Fixed Block length devices, make sure
3909 	 * the adjusted block count is a whole multiple of the device
3910 	 * block size.
3911 	 */
3912 	if (bp != un->un_sbufp && un->un_bsize) {
3913 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3914 	}
3915 }
3916 
3917 static int
3918 st_rw(dev_t dev, struct uio *uio, int flag)
3919 {
3920 	int rval = 0;
3921 	long len;
3922 
3923 	GET_SOFT_STATE(dev);
3924 
3925 	ST_FUNC(ST_DEVINFO, st_rw);
3926 
3927 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3928 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3929 	    (flag == B_READ ? rd_str: wr_str));
3930 
3931 	/* get local copy of transfer length */
3932 	len = uio->uio_iov->iov_len;
3933 
3934 	mutex_enter(ST_MUTEX);
3935 
3936 	/*
3937 	 * Clear error entry stack
3938 	 */
3939 	st_empty_error_stack(un);
3940 
3941 	/*
3942 	 * If in fixed block size mode and requested read or write
3943 	 * is not an even multiple of that block size.
3944 	 */
3945 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3946 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3947 		    "%s: not modulo %d block size\n",
3948 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3949 		rval = EINVAL;
3950 	}
3951 
3952 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3953 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3954 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3955 		    "%s: not modulo %d device granularity\n",
3956 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3957 		rval = EINVAL;
3958 	}
3959 
3960 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
3961 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
3962 		rval = EFAULT;
3963 	}
3964 
3965 	if (rval != 0) {
3966 		un->un_errno = rval;
3967 		mutex_exit(ST_MUTEX);
3968 		return (rval);
3969 	}
3970 
3971 	/*
3972 	 * Reset this so it can be set if Berkeley and read over a filemark.
3973 	 */
3974 	un->un_silent_skip = 0;
3975 	mutex_exit(ST_MUTEX);
3976 
3977 	len = uio->uio_resid;
3978 
3979 	rval = physio(st_queued_strategy, (struct buf *)NULL,
3980 	    dev, flag, st_minphys, uio);
3981 	/*
3982 	 * if we have hit logical EOT during this xfer and there is not a
3983 	 * full residue, then set eof back  to ST_EOM to make sure that
3984 	 * the user will see at least one zero write
3985 	 * after this short write
3986 	 */
3987 	mutex_enter(ST_MUTEX);
3988 	if (un->un_pos.eof > ST_NO_EOF) {
3989 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3990 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3991 	}
3992 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3993 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3994 			un->un_pos.eof = ST_EOM;
3995 		} else if (uio->uio_resid == len) {
3996 			un->un_pos.eof = ST_NO_EOF;
3997 		}
3998 	}
3999 
4000 	if (un->un_silent_skip && uio->uio_resid != len) {
4001 		un->un_pos.eof = ST_EOF;
4002 		un->un_pos.blkno = un->un_save_blkno;
4003 		un->un_pos.fileno--;
4004 	}
4005 
4006 	un->un_errno = rval;
4007 
4008 	mutex_exit(ST_MUTEX);
4009 
4010 	return (rval);
4011 }
4012 
4013 static int
4014 st_arw(dev_t dev, struct aio_req *aio, int flag)
4015 {
4016 	struct uio *uio = aio->aio_uio;
4017 	int rval = 0;
4018 	long len;
4019 
4020 	GET_SOFT_STATE(dev);
4021 
4022 	ST_FUNC(ST_DEVINFO, st_arw);
4023 
4024 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4025 	    "st_arw(dev = 0x%lx, flag = %s)\n", dev,
4026 	    (flag == B_READ ? rd_str: wr_str));
4027 
4028 	/* get local copy of transfer length */
4029 	len = uio->uio_iov->iov_len;
4030 
4031 	mutex_enter(ST_MUTEX);
4032 
4033 	/*
4034 	 * If in fixed block size mode and requested read or write
4035 	 * is not an even multiple of that block size.
4036 	 */
4037 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
4038 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4039 		    "%s: not modulo %d block size\n",
4040 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
4041 		rval = EINVAL;
4042 	}
4043 
4044 	/* If device has set granularity in the READ_BLKLIM we honor it. */
4045 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
4046 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4047 		    "%s: not modulo %d device granularity\n",
4048 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
4049 		rval = EINVAL;
4050 	}
4051 
4052 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
4053 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
4054 		rval = EFAULT;
4055 	}
4056 
4057 	if (rval != 0) {
4058 		un->un_errno = rval;
4059 		mutex_exit(ST_MUTEX);
4060 		return (rval);
4061 	}
4062 
4063 	mutex_exit(ST_MUTEX);
4064 
4065 	len = uio->uio_resid;
4066 
4067 	rval =
4068 	    aphysio(st_queued_strategy, anocancel, dev, flag, st_minphys, aio);
4069 
4070 	/*
4071 	 * if we have hit logical EOT during this xfer and there is not a
4072 	 * full residue, then set eof back  to ST_EOM to make sure that
4073 	 * the user will see at least one zero write
4074 	 * after this short write
4075 	 *
4076 	 * we keep this here just in case the application is not using
4077 	 * persistent errors
4078 	 */
4079 	mutex_enter(ST_MUTEX);
4080 	if (un->un_pos.eof > ST_NO_EOF) {
4081 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4082 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
4083 	}
4084 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
4085 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
4086 			un->un_pos.eof = ST_EOM;
4087 		} else if (uio->uio_resid == len &&
4088 		    !(un->un_persistence && un->un_persist_errors)) {
4089 			un->un_pos.eof = ST_NO_EOF;
4090 		}
4091 	}
4092 	un->un_errno = rval;
4093 	mutex_exit(ST_MUTEX);
4094 
4095 	return (rval);
4096 }
4097 
4098 
4099 
4100 static int
4101 st_queued_strategy(buf_t *bp)
4102 {
4103 	struct scsi_tape *un;
4104 	char reading = bp->b_flags & B_READ;
4105 	int wasopening = 0;
4106 
4107 	/*
4108 	 * validate arguments
4109 	 */
4110 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4111 	if (un == NULL) {
4112 		bp->b_resid = bp->b_bcount;
4113 		bioerror(bp, ENXIO);
4114 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4115 		    "st_queued_strategy: ENXIO error exit\n");
4116 		biodone(bp);
4117 		return (0);
4118 	}
4119 
4120 	ST_ENTR(ST_DEVINFO, st_queued_strategy);
4121 
4122 	mutex_enter(ST_MUTEX);
4123 
4124 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4125 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4126 	}
4127 
4128 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4129 	    "st_queued_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4130 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4131 
4132 	/*
4133 	 * If persistent errors have been flagged, just nix this one. We wait
4134 	 * for any outstanding I/O's below, so we will be in order.
4135 	 */
4136 	if (un->un_persistence && un->un_persist_errors) {
4137 		goto exit;
4138 	}
4139 
4140 	/*
4141 	 * If last command was non queued, wait till it finishes.
4142 	 */
4143 	while (un->un_sbuf_busy) {
4144 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
4145 		/* woke up because of an error */
4146 		if (un->un_persistence && un->un_persist_errors) {
4147 			goto exit;
4148 		}
4149 	}
4150 
4151 	/*
4152 	 * s_buf and recovery commands shouldn't come here.
4153 	 */
4154 	ASSERT(bp != un->un_recov_buf);
4155 	ASSERT(bp != un->un_sbufp);
4156 
4157 	/*
4158 	 * If we haven't done/checked reservation on the tape unit
4159 	 * do it now.
4160 	 */
4161 	if ((un->un_rsvd_status &
4162 	    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
4163 		if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
4164 			if (st_reserve_release(un, ST_RESERVE, st_uscsi_cmd)) {
4165 				st_bioerror(bp, un->un_errno);
4166 				goto exit;
4167 			}
4168 		} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4169 			/*
4170 			 * Enter here to restore position for possible
4171 			 * resets when the device was closed and opened
4172 			 * in O_NDELAY mode subsequently
4173 			 */
4174 			un->un_state = ST_STATE_INITIALIZING;
4175 			(void) st_cmd(un, SCMD_TEST_UNIT_READY,
4176 			    0, SYNC_CMD);
4177 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4178 		}
4179 		un->un_rsvd_status |= ST_INIT_RESERVE;
4180 	}
4181 
4182 	/*
4183 	 * If we are offline, we have to initialize everything first.
4184 	 * This is to handle either when opened with O_NDELAY, or
4185 	 * we just got a new tape in the drive, after an offline.
4186 	 * We don't observe O_NDELAY past the open,
4187 	 * as it will not make sense for tapes.
4188 	 */
4189 	if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
4190 		/*
4191 		 * reset state to avoid recursion
4192 		 */
4193 		un->un_laststate = un->un_state;
4194 		un->un_state = ST_STATE_INITIALIZING;
4195 		if (st_tape_init(un)) {
4196 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4197 			    "stioctl : OFFLINE init failure ");
4198 			un->un_state = ST_STATE_OFFLINE;
4199 			un->un_pos.pmode = invalid;
4200 			goto b_done_err;
4201 		}
4202 		/* un_restore_pos make invalid */
4203 		un->un_state = ST_STATE_OPEN_PENDING_IO;
4204 		un->un_restore_pos = 0;
4205 	}
4206 	/*
4207 	 * Check for legal operations
4208 	 */
4209 	if (un->un_pos.pmode == invalid) {
4210 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4211 		    "strategy with un->un_pos.pmode invalid\n");
4212 		goto b_done_err;
4213 	}
4214 
4215 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4216 	    "st_queued_strategy(): regular io\n");
4217 
4218 	/*
4219 	 * Process this first. If we were reading, and we're pending
4220 	 * logical eot, that means we've bumped one file mark too far.
4221 	 */
4222 
4223 	/*
4224 	 * Recursion warning: st_cmd will route back through here.
4225 	 * Not anymore st_cmd will go through st_strategy()!
4226 	 */
4227 	if (un->un_pos.eof == ST_EOT_PENDING) {
4228 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4229 			un->un_pos.pmode = invalid;
4230 			un->un_density_known = 0;
4231 			goto b_done_err;
4232 		}
4233 		un->un_pos.blkno = 0; /* fix up block number.. */
4234 		un->un_pos.eof = ST_EOT;
4235 	}
4236 
4237 	/*
4238 	 * If we are in the process of opening, we may have to
4239 	 * determine/set the correct density. We also may have
4240 	 * to do a test_append (if QIC) to see whether we are
4241 	 * in a position to append to the end of the tape.
4242 	 *
4243 	 * If we're already at logical eot, we transition
4244 	 * to ST_NO_EOF. If we're at physical eot, we punt
4245 	 * to the switch statement below to handle.
4246 	 */
4247 	if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
4248 	    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
4249 
4250 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4251 			if (st_determine_density(un, (int)reading)) {
4252 				goto b_done_err;
4253 			}
4254 		}
4255 
4256 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4257 		    "pending_io@fileno %d rw %d qic %d eof %d\n",
4258 		    un->un_pos.fileno, (int)reading,
4259 		    (un->un_dp->options & ST_QIC) ? 1 : 0,
4260 		    un->un_pos.eof);
4261 
4262 		if (!reading && un->un_pos.eof != ST_EOM) {
4263 			if (un->un_pos.eof == ST_EOT) {
4264 				un->un_pos.eof = ST_NO_EOF;
4265 			} else if (un->un_pos.pmode != invalid &&
4266 			    (un->un_dp->options & ST_QIC)) {
4267 				/*
4268 				 * st_test_append() will do it all
4269 				 */
4270 				st_test_append(bp);
4271 				mutex_exit(ST_MUTEX);
4272 				return (0);
4273 			}
4274 		}
4275 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4276 			wasopening = 1;
4277 		}
4278 		un->un_laststate = un->un_state;
4279 		un->un_state = ST_STATE_OPEN;
4280 	}
4281 
4282 
4283 	/*
4284 	 * Process rest of END OF FILE and END OF TAPE conditions
4285 	 */
4286 
4287 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4288 	    "eof=%x, wasopening=%x\n",
4289 	    un->un_pos.eof, wasopening);
4290 
4291 	switch (un->un_pos.eof) {
4292 	case ST_EOM:
4293 		/*
4294 		 * This allows writes to proceed past physical
4295 		 * eot. We'll *really* be in trouble if the
4296 		 * user continues blindly writing data too
4297 		 * much past this point (unwind the tape).
4298 		 * Physical eot really means 'early warning
4299 		 * eot' in this context.
4300 		 *
4301 		 * Every other write from now on will succeed
4302 		 * (if sufficient  tape left).
4303 		 * This write will return with resid == count
4304 		 * but the next one should be successful
4305 		 *
4306 		 * Note that we only transition to logical EOT
4307 		 * if the last state wasn't the OPENING state.
4308 		 * We explicitly prohibit running up to physical
4309 		 * eot, closing the device, and then re-opening
4310 		 * to proceed. Trailer records may only be gotten
4311 		 * at by keeping the tape open after hitting eot.
4312 		 *
4313 		 * Also note that ST_EOM cannot be set by reading-
4314 		 * this can only be set during writing. Reading
4315 		 * up to the end of the tape gets a blank check
4316 		 * or a double-filemark indication (ST_EOT_PENDING),
4317 		 * and we prohibit reading after that point.
4318 		 *
4319 		 */
4320 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
4321 		if (wasopening == 0) {
4322 			/*
4323 			 * this allows st_rw() to reset it back to
4324 			 * will see a zero write
4325 			 */
4326 			un->un_pos.eof = ST_WRITE_AFTER_EOM;
4327 		}
4328 		un->un_status = SUN_KEY_EOT;
4329 		goto b_done;
4330 
4331 	case ST_WRITE_AFTER_EOM:
4332 	case ST_EOT:
4333 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
4334 		un->un_status = SUN_KEY_EOT;
4335 		if (SVR4_BEHAVIOR && reading) {
4336 			goto b_done_err;
4337 		}
4338 
4339 		if (reading) {
4340 			goto b_done;
4341 		}
4342 		un->un_pos.eof = ST_NO_EOF;
4343 		break;
4344 
4345 	case ST_EOF_PENDING:
4346 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4347 		    "EOF PENDING\n");
4348 		un->un_status = SUN_KEY_EOF;
4349 		if (SVR4_BEHAVIOR) {
4350 			un->un_pos.eof = ST_EOF;
4351 			goto b_done;
4352 		}
4353 		/* FALLTHROUGH */
4354 	case ST_EOF:
4355 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
4356 		un->un_status = SUN_KEY_EOF;
4357 		if (SVR4_BEHAVIOR) {
4358 			goto b_done_err;
4359 		}
4360 
4361 		if (BSD_BEHAVIOR) {
4362 			un->un_pos.eof = ST_NO_EOF;
4363 			un->un_pos.fileno += 1;
4364 			un->un_pos.blkno   = 0;
4365 		}
4366 
4367 		if (reading) {
4368 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4369 			    "now file %d (read)\n",
4370 			    un->un_pos.fileno);
4371 			goto b_done;
4372 		}
4373 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4374 		    "now file %d (write)\n", un->un_pos.fileno);
4375 		break;
4376 	default:
4377 		un->un_status = 0;
4378 		break;
4379 	}
4380 
4381 	bp->b_flags &= ~(B_DONE);
4382 	st_bioerror(bp, 0);
4383 	bp->av_forw = NULL;
4384 	bp->b_resid = 0;
4385 	SET_BP_PKT(bp, 0);
4386 
4387 
4388 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4389 	    "st_queued_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4390 	    " pkt=0x%p\n",
4391 	    (void *)bp->b_forw, bp->b_bcount,
4392 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4393 
4394 #ifdef	__x86
4395 	/*
4396 	 * We will replace bp with a new bp that can do big blk xfer
4397 	 * if the requested xfer size is bigger than un->un_maxdma_arch
4398 	 *
4399 	 * Also, we need to make sure that we're handling real I/O
4400 	 * by checking group 0/1 SCSI I/O commands, if needed
4401 	 */
4402 	if (bp->b_bcount > un->un_maxdma_arch &&
4403 	    ((uchar_t)(uintptr_t)bp->b_forw == SCMD_READ ||
4404 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G4 ||
4405 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE ||
4406 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G4)) {
4407 		mutex_exit(ST_MUTEX);
4408 		bp = st_get_bigblk_bp(bp);
4409 		mutex_enter(ST_MUTEX);
4410 	}
4411 #endif
4412 
4413 	/* put on wait queue */
4414 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4415 	    "st_queued_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4416 	    (void *)un->un_quef, (void *)bp);
4417 
4418 	st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quel, bp);
4419 
4420 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4421 
4422 	st_start(un);
4423 
4424 	mutex_exit(ST_MUTEX);
4425 	return (0);
4426 
4427 b_done_err:
4428 	st_bioerror(bp, EIO);
4429 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4430 	    "st_queued_strategy : EIO b_done_err\n");
4431 
4432 b_done:
4433 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4434 	    "st_queued_strategy: b_done\n");
4435 
4436 exit:
4437 	/*
4438 	 * make sure no commands are outstanding or waiting before closing,
4439 	 * so we can guarantee order
4440 	 */
4441 	st_wait_for_io(un);
4442 	un->un_err_resid = bp->b_resid = bp->b_bcount;
4443 
4444 	/* override errno here, if persistent errors were flagged */
4445 	if (un->un_persistence && un->un_persist_errors)
4446 		bioerror(bp, un->un_errno);
4447 
4448 	mutex_exit(ST_MUTEX);
4449 
4450 	biodone(bp);
4451 	ASSERT(mutex_owned(ST_MUTEX) == 0);
4452 	return (0);
4453 }
4454 
4455 
4456 static int
4457 st_strategy(struct buf *bp)
4458 {
4459 	struct scsi_tape *un;
4460 
4461 	/*
4462 	 * validate arguments
4463 	 */
4464 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4465 	if (un == NULL) {
4466 		bp->b_resid = bp->b_bcount;
4467 		bioerror(bp, ENXIO);
4468 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4469 		    "st_strategy: ENXIO error exit\n");
4470 
4471 		biodone(bp);
4472 		return (0);
4473 
4474 	}
4475 
4476 	ST_ENTR(ST_DEVINFO, st_strategy);
4477 
4478 	mutex_enter(ST_MUTEX);
4479 
4480 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4481 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4482 	}
4483 
4484 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4485 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4486 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4487 
4488 	ASSERT((bp == un->un_recov_buf) || (bp == un->un_sbufp));
4489 
4490 	bp->b_flags &= ~(B_DONE);
4491 	st_bioerror(bp, 0);
4492 	bp->av_forw = NULL;
4493 	bp->b_resid = 0;
4494 	SET_BP_PKT(bp, 0);
4495 
4496 
4497 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4498 	    "st_strategy: cmd=0x%x  count=%ld  resid=%ld flags=0x%x"
4499 	    " pkt=0x%p\n",
4500 	    (unsigned char)(uintptr_t)bp->b_forw, bp->b_bcount,
4501 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4502 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4503 
4504 	st_start(un);
4505 
4506 	mutex_exit(ST_MUTEX);
4507 	return (0);
4508 }
4509 
4510 /*
4511  * this routine spaces forward over filemarks
4512  */
4513 static int
4514 st_space_fmks(struct scsi_tape *un, int64_t count)
4515 {
4516 	int rval = 0;
4517 
4518 	ST_FUNC(ST_DEVINFO, st_space_fmks);
4519 
4520 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4521 	    "st_space_fmks(dev = 0x%lx, count = %"PRIx64")\n",
4522 	    un->un_dev, count);
4523 
4524 	ASSERT(mutex_owned(ST_MUTEX));
4525 
4526 	/*
4527 	 * the risk with doing only one space operation is that we
4528 	 * may accidentily jump in old data
4529 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4530 	 * because the 8200 does not append a marker; in order not to
4531 	 * sacrifice the fast file skip, we do a slow skip if the low
4532 	 * density device has been opened
4533 	 */
4534 
4535 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4536 	    !((un->un_dp->type == ST_TYPE_EXB8500 &&
4537 	    MT_DENSITY(un->un_dev) == 0))) {
4538 		if (st_cmd(un, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4539 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4540 			    "space_fmks : EIO can't do space cmd #1\n");
4541 			rval = EIO;
4542 		}
4543 	} else {
4544 		while (count > 0) {
4545 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4546 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4547 				    "space_fmks : EIO can't do space cmd #2\n");
4548 				rval = EIO;
4549 				break;
4550 			}
4551 			count -= 1;
4552 			/*
4553 			 * read a block to see if we have reached
4554 			 * end of medium (double filemark for reel or
4555 			 * medium error for others)
4556 			 */
4557 			if (count > 0) {
4558 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
4559 					ST_DEBUG2(ST_DEVINFO, st_label,
4560 					    SCSI_DEBUG,
4561 					    "space_fmks : EIO can't do "
4562 					    "space cmd #3\n");
4563 					rval = EIO;
4564 					break;
4565 				}
4566 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4567 				    (un->un_dp->options & ST_REEL)) {
4568 					un->un_status = SUN_KEY_EOT;
4569 					ST_DEBUG2(ST_DEVINFO, st_label,
4570 					    SCSI_DEBUG,
4571 					    "space_fmks : EIO ST_REEL\n");
4572 					rval = EIO;
4573 					break;
4574 				} else if (IN_EOF(un->un_pos)) {
4575 					un->un_pos.eof = ST_NO_EOF;
4576 					un->un_pos.fileno++;
4577 					un->un_pos.blkno = 0;
4578 					count--;
4579 				} else if (un->un_pos.eof > ST_EOF) {
4580 					ST_DEBUG2(ST_DEVINFO, st_label,
4581 					    SCSI_DEBUG,
4582 					    "space_fmks, EIO > ST_EOF\n");
4583 					rval = EIO;
4584 					break;
4585 				}
4586 
4587 			}
4588 		}
4589 		un->un_err_resid = count;
4590 		COPY_POS(&un->un_pos, &un->un_err_pos);
4591 	}
4592 	ASSERT(mutex_owned(ST_MUTEX));
4593 	return (rval);
4594 }
4595 
4596 /*
4597  * this routine spaces to EOD
4598  *
4599  * it keeps track of the current filenumber and returns the filenumber after
4600  * the last successful space operation, we keep the number high because as
4601  * tapes are getting larger, the possibility of more and more files exist,
4602  * 0x100000 (1 Meg of files) probably will never have to be changed any time
4603  * soon
4604  */
4605 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4606 
4607 static int
4608 st_find_eod(struct scsi_tape *un)
4609 {
4610 	tapepos_t savepos;
4611 	int64_t sp_type;
4612 	int result;
4613 
4614 	if (un == NULL) {
4615 		return (-1);
4616 	}
4617 
4618 	ST_FUNC(ST_DEVINFO, st_find_eod);
4619 
4620 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4621 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", un->un_dev,
4622 	    un->un_pos.fileno);
4623 
4624 	ASSERT(mutex_owned(ST_MUTEX));
4625 
4626 	COPY_POS(&savepos, &un->un_pos);
4627 
4628 	/*
4629 	 * see if the drive is smart enough to do the skips in
4630 	 * one operation; 1/2" use two filemarks
4631 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4632 	 * because the 8200 does not append a marker; in order not to
4633 	 * sacrifice the fast file skip, we do a slow skip if the low
4634 	 * density device has been opened
4635 	 */
4636 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4637 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4638 		    (MT_DENSITY(un->un_dev) == 0)) {
4639 			sp_type = Fmk(1);
4640 		} else if (un->un_pos.pmode == logical) {
4641 			sp_type = SPACE(SP_EOD, 0);
4642 		} else {
4643 			sp_type = Fmk(MAX_SKIP);
4644 		}
4645 	} else {
4646 		sp_type = Fmk(1);
4647 	}
4648 
4649 	for (;;) {
4650 		result = st_cmd(un, SCMD_SPACE, sp_type, SYNC_CMD);
4651 
4652 		if (result == 0) {
4653 			COPY_POS(&savepos, &un->un_pos);
4654 		}
4655 
4656 		if (sp_type == SPACE(SP_EOD, 0)) {
4657 			if (result != 0) {
4658 				sp_type = Fmk(MAX_SKIP);
4659 				continue;
4660 			}
4661 
4662 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4663 			    "st_find_eod: 0x%"PRIx64"\n",
4664 			    savepos.lgclblkno);
4665 			/*
4666 			 * What we return will become the current file position.
4667 			 * After completing the space command with the position
4668 			 * mode that is not invalid a read position command will
4669 			 * be automaticly issued. If the drive support the long
4670 			 * read position format a valid file position can be
4671 			 * returned.
4672 			 */
4673 			return (un->un_pos.fileno);
4674 		}
4675 
4676 		if (result != 0) {
4677 			break;
4678 		}
4679 
4680 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4681 		    "count=%"PRIx64", eof=%x, status=%x\n",
4682 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4683 
4684 		/*
4685 		 * If we're not EOM smart,  space a record
4686 		 * to see whether we're now in the slot between
4687 		 * the two sequential filemarks that logical
4688 		 * EOM consists of (REEL) or hit nowhere land
4689 		 * (8mm).
4690 		 */
4691 		if (sp_type == Fmk(1)) {
4692 			/*
4693 			 * no fast skipping, check a record
4694 			 */
4695 			if (st_cmd(un, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4696 				break;
4697 			}
4698 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4699 			    (un->un_dp->options & ST_REEL)) {
4700 				un->un_status = KEY_BLANK_CHECK;
4701 				un->un_pos.fileno++;
4702 				un->un_pos.blkno = 0;
4703 				break;
4704 			}
4705 			if (IN_EOF(un->un_pos)) {
4706 				un->un_pos.eof = ST_NO_EOF;
4707 				un->un_pos.fileno++;
4708 				un->un_pos.blkno = 0;
4709 			}
4710 			if (un->un_pos.eof > ST_EOF) {
4711 				break;
4712 			}
4713 		} else {
4714 			if (un->un_pos.eof > ST_EOF) {
4715 				break;
4716 			}
4717 		}
4718 	}
4719 
4720 	if (un->un_dp->options & ST_KNOWS_EOD) {
4721 		COPY_POS(&savepos, &un->un_pos);
4722 	}
4723 
4724 	ASSERT(mutex_owned(ST_MUTEX));
4725 
4726 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4727 	    "st_find_eod: %x\n", savepos.fileno);
4728 	return (savepos.fileno);
4729 }
4730 
4731 
4732 /*
4733  * this routine is frequently used in ioctls below;
4734  * it determines whether we know the density and if not will
4735  * determine it
4736  * if we have written the tape before, one or more filemarks are written
4737  *
4738  * depending on the stepflag, the head is repositioned to where it was before
4739  * the filemarks were written in order not to confuse step counts
4740  */
4741 #define	STEPBACK    0
4742 #define	NO_STEPBACK 1
4743 
4744 static int
4745 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4746 {
4747 
4748 	GET_SOFT_STATE(dev);
4749 
4750 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4751 
4752 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4753 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4754 	    "\n", dev, wfm, mode, stepflag);
4755 
4756 	ASSERT(mutex_owned(ST_MUTEX));
4757 
4758 	/*
4759 	 * If we don't yet know the density of the tape we have inserted,
4760 	 * we have to either unconditionally set it (if we're 'writing'),
4761 	 * or we have to determine it. As side effects, check for any
4762 	 * write-protect errors, and for the need to put out any file-marks
4763 	 * before positioning a tape.
4764 	 *
4765 	 * If we are going to be spacing forward, and we haven't determined
4766 	 * the tape density yet, we have to do so now...
4767 	 */
4768 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4769 		if (st_determine_density(un, mode)) {
4770 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4771 			    "check_density_or_wfm : EIO can't determine "
4772 			    "density\n");
4773 			un->un_errno = EIO;
4774 			return (EIO);
4775 		}
4776 		/*
4777 		 * Presumably we are at BOT. If we attempt to write, it will
4778 		 * either work okay, or bomb. We don't do a st_test_append
4779 		 * unless we're past BOT.
4780 		 */
4781 		un->un_laststate = un->un_state;
4782 		un->un_state = ST_STATE_OPEN;
4783 
4784 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4785 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4786 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4787 
4788 		tapepos_t spos;
4789 
4790 		COPY_POS(&spos, &un->un_pos);
4791 
4792 		/*
4793 		 * We need to write one or two filemarks.
4794 		 * In the case of the HP, we need to
4795 		 * position the head between the two
4796 		 * marks.
4797 		 */
4798 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4799 			wfm = un->un_fmneeded;
4800 			un->un_fmneeded = 0;
4801 		}
4802 
4803 		if (st_write_fm(dev, wfm)) {
4804 			un->un_pos.pmode = invalid;
4805 			un->un_density_known = 0;
4806 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4807 			    "check_density_or_wfm : EIO can't write fm\n");
4808 			un->un_errno = EIO;
4809 			return (EIO);
4810 		}
4811 
4812 		if (stepflag == STEPBACK) {
4813 			if (st_cmd(un, SCMD_SPACE, Fmk(-wfm), SYNC_CMD)) {
4814 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4815 				    "check_density_or_wfm : EIO can't space "
4816 				    "(-wfm)\n");
4817 				un->un_errno = EIO;
4818 				return (EIO);
4819 			}
4820 			COPY_POS(&un->un_pos, &spos);
4821 		}
4822 	}
4823 
4824 	/*
4825 	 * Whatever we do at this point clears the state of the eof flag.
4826 	 */
4827 
4828 	un->un_pos.eof = ST_NO_EOF;
4829 
4830 	/*
4831 	 * If writing, let's check that we're positioned correctly
4832 	 * at the end of tape before issuing the next write.
4833 	 */
4834 	if (un->un_read_only == RDWR) {
4835 		un->un_test_append = 1;
4836 	}
4837 
4838 	ASSERT(mutex_owned(ST_MUTEX));
4839 	return (0);
4840 }
4841 
4842 
4843 /*
4844  * Wait for all outstaning I/O's to complete
4845  *
4846  * we wait on both ncmds and the wait queue for times when we are flushing
4847  * after persistent errors are flagged, which is when ncmds can be 0, and the
4848  * queue can still have I/O's.  This way we preserve order of biodone's.
4849  */
4850 static void
4851 st_wait_for_io(struct scsi_tape *un)
4852 {
4853 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4854 	ASSERT(mutex_owned(ST_MUTEX));
4855 	while ((un->un_ncmds) || (un->un_quef) || (un->un_runqf)) {
4856 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4857 	}
4858 }
4859 
4860 /*
4861  * This routine implements the ioctl calls.  It is called
4862  * from the device switch at normal priority.
4863  */
4864 /*ARGSUSED*/
4865 static int
4866 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4867     int *rval_p)
4868 {
4869 	int tmp, rval = 0;
4870 
4871 	GET_SOFT_STATE(dev);
4872 
4873 	ST_ENTR(ST_DEVINFO, st_ioctl);
4874 
4875 	mutex_enter(ST_MUTEX);
4876 
4877 	ASSERT(un->un_recov_buf_busy == 0);
4878 
4879 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4880 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4881 	    "pe_flag = %d\n",
4882 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4883 	    un->un_persistence && un->un_persist_errors);
4884 
4885 	/*
4886 	 * We don't want to block on these, so let them through
4887 	 * and we don't care about setting driver states here.
4888 	 */
4889 	if ((cmd == MTIOCGETDRIVETYPE) ||
4890 	    (cmd == MTIOCGUARANTEEDORDER) ||
4891 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4892 		goto check_commands;
4893 	}
4894 
4895 	/*
4896 	 * We clear error entry stack except command
4897 	 * MTIOCGETERROR and MTIOCGET
4898 	 */
4899 	if ((cmd != MTIOCGETERROR) &&
4900 	    (cmd != MTIOCGET)) {
4901 		st_empty_error_stack(un);
4902 	}
4903 
4904 	/*
4905 	 * wait for all outstanding commands to complete, or be dequeued.
4906 	 * And because ioctl's are synchronous commands, any return value
4907 	 * after this,  will be in order
4908 	 */
4909 	st_wait_for_io(un);
4910 
4911 	/*
4912 	 * allow only a through clear errors and persistent status, and
4913 	 * status
4914 	 */
4915 	if (un->un_persistence && un->un_persist_errors) {
4916 		if ((cmd == MTIOCLRERR) ||
4917 		    (cmd == MTIOCPERSISTENT) ||
4918 		    (cmd == MTIOCGET)) {
4919 			goto check_commands;
4920 		} else {
4921 			rval = un->un_errno;
4922 			goto exit;
4923 		}
4924 	}
4925 
4926 	ASSERT(un->un_throttle != 0);
4927 	un->un_throttle = 1;	/* > 1 will never happen here */
4928 	un->un_errno = 0;	/* start clean from here */
4929 
4930 	/*
4931 	 * first and foremost, handle any ST_EOT_PENDING cases.
4932 	 * That is, if a logical eot is pending notice, notice it.
4933 	 */
4934 	if (un->un_pos.eof == ST_EOT_PENDING) {
4935 		int resid = un->un_err_resid;
4936 		uchar_t status = un->un_status;
4937 		uchar_t lastop = un->un_lastop;
4938 
4939 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4940 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4941 			    "stioctl : EIO can't space fmk(-1)\n");
4942 			rval = EIO;
4943 			goto exit;
4944 		}
4945 		un->un_lastop = lastop; /* restore last operation */
4946 		if (status == SUN_KEY_EOF) {
4947 			un->un_status = SUN_KEY_EOT;
4948 		} else {
4949 			un->un_status = status;
4950 		}
4951 		un->un_err_resid  = resid;
4952 		/* fix up block number */
4953 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4954 		/* now we're at logical eot */
4955 		un->un_pos.eof = ST_EOT;
4956 	}
4957 
4958 	/*
4959 	 * now, handle the rest of the situations
4960 	 */
4961 check_commands:
4962 	switch (cmd) {
4963 	case MTIOCGET:
4964 	{
4965 #ifdef _MULTI_DATAMODEL
4966 		/*
4967 		 * For use when a 32 bit app makes a call into a
4968 		 * 64 bit ioctl
4969 		 */
4970 		struct mtget32		mtg_local32;
4971 		struct mtget32 		*mtget_32 = &mtg_local32;
4972 #endif /* _MULTI_DATAMODEL */
4973 
4974 			/* Get tape status */
4975 		struct mtget mtg_local;
4976 		struct mtget *mtget = &mtg_local;
4977 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4978 		    "st_ioctl: MTIOCGET\n");
4979 
4980 		bzero((caddr_t)mtget, sizeof (struct mtget));
4981 		mtget->mt_erreg = un->un_status;
4982 		mtget->mt_resid = un->un_err_resid;
4983 		mtget->mt_dsreg = un->un_retry_ct;
4984 		if (un->un_err_pos.pmode == legacy) {
4985 			mtget->mt_fileno = un->un_err_pos.fileno;
4986 		} else {
4987 			mtget->mt_fileno = -1;
4988 		}
4989 		/*
4990 		 * If the value is positive fine.
4991 		 * If its negative we need to return a value based on the
4992 		 * old way if counting backwards from INF (1,000,000,000).
4993 		 */
4994 		if (un->un_err_pos.blkno >= 0) {
4995 			mtget->mt_blkno = un->un_err_pos.blkno;
4996 		} else {
4997 			mtget->mt_blkno = INF + 1 - (-un->un_err_pos.blkno);
4998 		}
4999 		mtget->mt_type = un->un_dp->type;
5000 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
5001 		if (un->un_read_pos_type != NO_POS) {
5002 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
5003 		}
5004 		if (un->un_dp->options & ST_REEL) {
5005 			mtget->mt_flags |= MTF_REEL;
5006 			mtget->mt_bf = 20;
5007 		} else {		/* 1/4" cartridges */
5008 			switch (mtget->mt_type) {
5009 			/* Emulex cartridge tape */
5010 			case MT_ISMT02:
5011 				mtget->mt_bf = 40;
5012 				break;
5013 			default:
5014 				mtget->mt_bf = 126;
5015 				break;
5016 			}
5017 		}
5018 
5019 		/*
5020 		 * If large transfers are allowed and drive options
5021 		 * has no record size limit set. Calculate blocking
5022 		 * factor from the lesser of maxbsize and maxdma.
5023 		 */
5024 		if ((un->un_allow_large_xfer) &&
5025 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
5026 			mtget->mt_bf = min(un->un_maxbsize,
5027 			    un->un_maxdma) / SECSIZE;
5028 		}
5029 
5030 		if (un->un_read_only == WORM ||
5031 		    un->un_read_only == RDWORM) {
5032 			mtget->mt_flags |= MTF_WORM_MEDIA;
5033 		}
5034 
5035 		/*
5036 		 * In persistent error mode sending a non-queued can hang
5037 		 * because this ioctl gets to be run without turning off
5038 		 * persistense. Fake the answer based on previous info.
5039 		 */
5040 		if (un->un_persistence) {
5041 			rval = 0;
5042 		} else {
5043 			rval = st_check_clean_bit(un);
5044 		}
5045 		if (rval == 0) {
5046 			/*
5047 			 * If zero is returned or in persistent mode,
5048 			 * use the old data.
5049 			 */
5050 			if ((un->un_HeadClean & (TAPE_ALERT_SUPPORTED |
5051 			    TAPE_SEQUENTIAL_SUPPORTED|TAPE_ALERT_NOT_SUPPORTED))
5052 			    != TAPE_ALERT_NOT_SUPPORTED) {
5053 				mtget->mt_flags |= MTF_TAPE_CLN_SUPPORTED;
5054 			}
5055 			if (un->un_HeadClean & (TAPE_PREVIOUSLY_DIRTY |
5056 			    TAPE_ALERT_STILL_DIRTY)) {
5057 				mtget->mt_flags |= MTF_TAPE_HEAD_DIRTY;
5058 			}
5059 		} else {
5060 			mtget->mt_flags |= (ushort_t)rval;
5061 			rval = 0;
5062 		}
5063 
5064 		un->un_status = 0;		/* Reset status */
5065 		un->un_err_resid = 0;
5066 		tmp = sizeof (struct mtget);
5067 
5068 #ifdef _MULTI_DATAMODEL
5069 
5070 		switch (ddi_model_convert_from(flag & FMODELS)) {
5071 		case DDI_MODEL_ILP32:
5072 			/*
5073 			 * Convert 64 bit back to 32 bit before doing
5074 			 * copyout. This is what the ILP32 app expects.
5075 			 */
5076 			mtget_32->mt_erreg = 	mtget->mt_erreg;
5077 			mtget_32->mt_resid = 	mtget->mt_resid;
5078 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
5079 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
5080 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
5081 			mtget_32->mt_type =  	mtget->mt_type;
5082 			mtget_32->mt_flags = 	mtget->mt_flags;
5083 			mtget_32->mt_bf = 	mtget->mt_bf;
5084 
5085 			if (ddi_copyout(mtget_32, (void *)arg,
5086 			    sizeof (struct mtget32), flag)) {
5087 				rval = EFAULT;
5088 			}
5089 			break;
5090 
5091 		case DDI_MODEL_NONE:
5092 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5093 				rval = EFAULT;
5094 			}
5095 			break;
5096 		}
5097 #else /* ! _MULTI_DATAMODE */
5098 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5099 			rval = EFAULT;
5100 		}
5101 #endif /* _MULTI_DATAMODE */
5102 
5103 		break;
5104 	}
5105 	case MTIOCGETERROR:
5106 			/*
5107 			 * get error entry from error stack
5108 			 */
5109 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5110 			    "st_ioctl: MTIOCGETERROR\n");
5111 
5112 			rval = st_get_error_entry(un, arg, flag);
5113 
5114 			break;
5115 
5116 	case MTIOCSTATE:
5117 		{
5118 			/*
5119 			 * return when media presence matches state
5120 			 */
5121 			enum mtio_state state;
5122 
5123 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5124 			    "st_ioctl: MTIOCSTATE\n");
5125 
5126 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
5127 				rval = EFAULT;
5128 
5129 			mutex_exit(ST_MUTEX);
5130 
5131 			rval = st_check_media(dev, state);
5132 
5133 			mutex_enter(ST_MUTEX);
5134 
5135 			if (rval != 0) {
5136 				break;
5137 			}
5138 
5139 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
5140 			    sizeof (int), flag))
5141 				rval = EFAULT;
5142 			break;
5143 
5144 		}
5145 
5146 	case MTIOCGETDRIVETYPE:
5147 		{
5148 #ifdef _MULTI_DATAMODEL
5149 		/*
5150 		 * For use when a 32 bit app makes a call into a
5151 		 * 64 bit ioctl
5152 		 */
5153 		struct mtdrivetype_request32	mtdtrq32;
5154 #endif /* _MULTI_DATAMODEL */
5155 
5156 			/*
5157 			 * return mtdrivetype
5158 			 */
5159 			struct mtdrivetype_request mtdtrq;
5160 			struct mtdrivetype mtdrtyp;
5161 			struct mtdrivetype *mtdt = &mtdrtyp;
5162 			struct st_drivetype *stdt = un->un_dp;
5163 
5164 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5165 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
5166 
5167 #ifdef _MULTI_DATAMODEL
5168 		switch (ddi_model_convert_from(flag & FMODELS)) {
5169 		case DDI_MODEL_ILP32:
5170 		{
5171 			if (ddi_copyin((void *)arg, &mtdtrq32,
5172 			    sizeof (struct mtdrivetype_request32), flag)) {
5173 				rval = EFAULT;
5174 				break;
5175 			}
5176 			mtdtrq.size = mtdtrq32.size;
5177 			mtdtrq.mtdtp =
5178 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
5179 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5180 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
5181 			break;
5182 		}
5183 		case DDI_MODEL_NONE:
5184 			if (ddi_copyin((void *)arg, &mtdtrq,
5185 			    sizeof (struct mtdrivetype_request), flag)) {
5186 				rval = EFAULT;
5187 				break;
5188 			}
5189 			break;
5190 		}
5191 
5192 #else /* ! _MULTI_DATAMODEL */
5193 		if (ddi_copyin((void *)arg, &mtdtrq,
5194 		    sizeof (struct mtdrivetype_request), flag)) {
5195 			rval = EFAULT;
5196 			break;
5197 		}
5198 #endif /* _MULTI_DATAMODEL */
5199 
5200 			/*
5201 			 * if requested size is < 0 then return
5202 			 * error.
5203 			 */
5204 			if (mtdtrq.size < 0) {
5205 				rval = EINVAL;
5206 				break;
5207 			}
5208 			bzero(mtdt, sizeof (struct mtdrivetype));
5209 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
5210 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
5211 			mtdt->type = stdt->type;
5212 			mtdt->bsize = stdt->bsize;
5213 			mtdt->options = stdt->options;
5214 			mtdt->max_rretries = stdt->max_rretries;
5215 			mtdt->max_wretries = stdt->max_wretries;
5216 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5217 				mtdt->densities[tmp] = stdt->densities[tmp];
5218 			}
5219 			mtdt->default_density = stdt->default_density;
5220 			/*
5221 			 * Speed hasn't been used since the hayday of reel tape.
5222 			 * For all drives not setting the option ST_KNOWS_MEDIA
5223 			 * the speed member renamed to mediatype are zeros.
5224 			 * Those drives that have ST_KNOWS_MEDIA set use the
5225 			 * new mediatype member which is used to figure the
5226 			 * type of media loaded.
5227 			 *
5228 			 * So as to not break applications speed in the
5229 			 * mtdrivetype structure is not renamed.
5230 			 */
5231 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5232 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
5233 			}
5234 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
5235 			mtdt->io_timeout = stdt->io_timeout;
5236 			mtdt->rewind_timeout = stdt->rewind_timeout;
5237 			mtdt->space_timeout = stdt->space_timeout;
5238 			mtdt->load_timeout = stdt->load_timeout;
5239 			mtdt->unload_timeout = stdt->unload_timeout;
5240 			mtdt->erase_timeout = stdt->erase_timeout;
5241 
5242 			/*
5243 			 * Limit the maximum length of the result to
5244 			 * sizeof (struct mtdrivetype).
5245 			 */
5246 			tmp = sizeof (struct mtdrivetype);
5247 			if (mtdtrq.size < tmp)
5248 				tmp = mtdtrq.size;
5249 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
5250 				rval = EFAULT;
5251 			}
5252 			break;
5253 		}
5254 	case MTIOCPERSISTENT:
5255 
5256 		if (ddi_copyin((void *)arg, &tmp, sizeof (tmp), flag)) {
5257 			rval = EFAULT;
5258 			break;
5259 		}
5260 
5261 		if (tmp) {
5262 			st_turn_pe_on(un);
5263 		} else {
5264 			st_turn_pe_off(un);
5265 		}
5266 
5267 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5268 		    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
5269 		    un->un_persistence);
5270 
5271 		break;
5272 
5273 	case MTIOCPERSISTENTSTATUS:
5274 		tmp = (int)un->un_persistence;
5275 
5276 		if (ddi_copyout(&tmp, (void *)arg, sizeof (tmp), flag)) {
5277 			rval = EFAULT;
5278 		}
5279 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5280 		    "st_ioctl: MTIOCPERSISTENTSTATUS:persistence = %d\n",
5281 		    un->un_persistence);
5282 
5283 		break;
5284 
5285 	case MTIOCLRERR:
5286 		{
5287 			/* clear persistent errors */
5288 
5289 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5290 			    "st_ioctl: MTIOCLRERR\n");
5291 
5292 			st_clear_pe(un);
5293 
5294 			break;
5295 		}
5296 
5297 	case MTIOCGUARANTEEDORDER:
5298 		{
5299 			/*
5300 			 * this is just a holder to make a valid ioctl and
5301 			 * it won't be in any earlier release
5302 			 */
5303 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5304 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
5305 
5306 			break;
5307 		}
5308 
5309 	case MTIOCRESERVE:
5310 		{
5311 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5312 			    "st_ioctl: MTIOCRESERVE\n");
5313 
5314 			/*
5315 			 * Check if Reserve/Release is supported.
5316 			 */
5317 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5318 				rval = ENOTTY;
5319 				break;
5320 			}
5321 
5322 			rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5323 
5324 			if (rval == 0) {
5325 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
5326 			}
5327 			break;
5328 		}
5329 
5330 	case MTIOCRELEASE:
5331 		{
5332 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5333 			    "st_ioctl: MTIOCRELEASE\n");
5334 
5335 			/*
5336 			 * Check if Reserve/Release is supported.
5337 			 */
5338 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5339 				rval = ENOTTY;
5340 				break;
5341 			}
5342 
5343 			/*
5344 			 * Used to just clear ST_PRESERVE_RESERVE which
5345 			 * made the reservation release at next close.
5346 			 * As the user may have opened and then done a
5347 			 * persistant reservation we now need to drop
5348 			 * the reservation without closing if the user
5349 			 * attempts to do this.
5350 			 */
5351 			rval = st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
5352 
5353 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5354 
5355 			break;
5356 		}
5357 
5358 	case MTIOCFORCERESERVE:
5359 	{
5360 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5361 		    "st_ioctl: MTIOCFORCERESERVE\n");
5362 
5363 		/*
5364 		 * Check if Reserve/Release is supported.
5365 		 */
5366 		if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5367 			rval = ENOTTY;
5368 			break;
5369 		}
5370 		/*
5371 		 * allow only super user to run this.
5372 		 */
5373 		if (drv_priv(cred_p) != 0) {
5374 			rval = EPERM;
5375 			break;
5376 		}
5377 		/*
5378 		 * Throw away reserve,
5379 		 * not using test-unit-ready
5380 		 * since reserve can succeed without tape being
5381 		 * present in the drive.
5382 		 */
5383 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5384 
5385 		rval = st_take_ownership(un, st_uscsi_cmd);
5386 
5387 		break;
5388 	}
5389 
5390 	case USCSICMD:
5391 	{
5392 		cred_t	*cr;
5393 
5394 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5395 		    "st_ioctl: USCSICMD\n");
5396 
5397 		cr = ddi_get_cred();
5398 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5399 			rval = EPERM;
5400 		} else {
5401 			rval = st_uscsi_cmd(un, (struct uscsi_cmd *)arg, flag);
5402 		}
5403 		break;
5404 	}
5405 	case MTIOCTOP:
5406 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5407 		    "st_ioctl: MTIOCTOP\n");
5408 		rval = st_mtioctop(un, arg, flag);
5409 		break;
5410 
5411 	case MTIOCLTOP:
5412 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5413 		    "st_ioctl: MTIOLCTOP\n");
5414 		rval = st_mtiocltop(un, arg, flag);
5415 		break;
5416 
5417 	case MTIOCREADIGNOREILI:
5418 		{
5419 			int set_ili;
5420 
5421 			if (ddi_copyin((void *)arg, &set_ili,
5422 			    sizeof (set_ili), flag)) {
5423 				rval = EFAULT;
5424 				break;
5425 			}
5426 
5427 			if (un->un_bsize) {
5428 				rval = ENOTTY;
5429 				break;
5430 			}
5431 
5432 			switch (set_ili) {
5433 			case 0:
5434 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5435 				break;
5436 
5437 			case 1:
5438 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5439 				break;
5440 
5441 			default:
5442 				rval = EINVAL;
5443 				break;
5444 			}
5445 			break;
5446 		}
5447 
5448 	case MTIOCREADIGNOREEOFS:
5449 		{
5450 			int ignore_eof;
5451 
5452 			if (ddi_copyin((void *)arg, &ignore_eof,
5453 			    sizeof (ignore_eof), flag)) {
5454 				rval = EFAULT;
5455 				break;
5456 			}
5457 
5458 			if (!(un->un_dp->options & ST_REEL)) {
5459 				rval = ENOTTY;
5460 				break;
5461 			}
5462 
5463 			switch (ignore_eof) {
5464 			case 0:
5465 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5466 				break;
5467 
5468 			case 1:
5469 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5470 				break;
5471 
5472 			default:
5473 				rval = EINVAL;
5474 				break;
5475 			}
5476 			break;
5477 		}
5478 
5479 	case MTIOCSHORTFMK:
5480 	{
5481 		int short_fmk;
5482 
5483 		if (ddi_copyin((void *)arg, &short_fmk,
5484 		    sizeof (short_fmk), flag)) {
5485 			rval = EFAULT;
5486 			break;
5487 		}
5488 
5489 		switch (un->un_dp->type) {
5490 		case ST_TYPE_EXB8500:
5491 		case ST_TYPE_EXABYTE:
5492 			if (!short_fmk) {
5493 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5494 			} else if (short_fmk == 1) {
5495 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5496 			} else {
5497 				rval = EINVAL;
5498 			}
5499 			break;
5500 
5501 		default:
5502 			rval = ENOTTY;
5503 			break;
5504 		}
5505 		break;
5506 	}
5507 
5508 	case MTIOCGETPOS:
5509 		rval = st_update_block_pos(un, st_cmd, 0);
5510 		if (rval == 0) {
5511 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5512 			    sizeof (tapepos_t), flag)) {
5513 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5514 				    "MTIOCGETPOS copy out failed\n");
5515 				rval = EFAULT;
5516 			}
5517 		}
5518 		break;
5519 
5520 	case MTIOCRESTPOS:
5521 	{
5522 		tapepos_t dest;
5523 
5524 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5525 		    flag) != 0) {
5526 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5527 			    "MTIOCRESTPOS copy in failed\n");
5528 			rval = EFAULT;
5529 			break;
5530 		}
5531 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &dest);
5532 		if (rval != 0) {
5533 			rval = EIO;
5534 		}
5535 		break;
5536 	}
5537 	default:
5538 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5539 		    "st_ioctl: unknown ioctl\n");
5540 		rval = ENOTTY;
5541 	}
5542 
5543 exit:
5544 	if (!(un->un_persistence && un->un_persist_errors)) {
5545 		un->un_errno = rval;
5546 	}
5547 
5548 	mutex_exit(ST_MUTEX);
5549 
5550 	return (rval);
5551 }
5552 
5553 
5554 /*
5555  * do some MTIOCTOP tape operations
5556  */
5557 static int
5558 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5559 {
5560 #ifdef _MULTI_DATAMODEL
5561 	/*
5562 	 * For use when a 32 bit app makes a call into a
5563 	 * 64 bit ioctl
5564 	 */
5565 	struct mtop32	mtop_32_for_64;
5566 #endif /* _MULTI_DATAMODEL */
5567 	struct mtop passed;
5568 	struct mtlop local;
5569 	int rval = 0;
5570 
5571 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5572 
5573 	ASSERT(mutex_owned(ST_MUTEX));
5574 
5575 #ifdef _MULTI_DATAMODEL
5576 	switch (ddi_model_convert_from(flag & FMODELS)) {
5577 	case DDI_MODEL_ILP32:
5578 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5579 		    sizeof (struct mtop32), flag)) {
5580 			return (EFAULT);
5581 		}
5582 		local.mt_op = mtop_32_for_64.mt_op;
5583 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5584 		break;
5585 
5586 	case DDI_MODEL_NONE:
5587 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5588 			return (EFAULT);
5589 		}
5590 		local.mt_op = passed.mt_op;
5591 		/* prevent sign extention */
5592 		local.mt_count = (UINT32_MAX & passed.mt_count);
5593 		break;
5594 	}
5595 
5596 #else /* ! _MULTI_DATAMODEL */
5597 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5598 		return (EFAULT);
5599 	}
5600 	local.mt_op = passed.mt_op;
5601 	/* prevent sign extention */
5602 	local.mt_count = (UINT32_MAX & passed.mt_count);
5603 #endif /* _MULTI_DATAMODEL */
5604 
5605 	rval = st_do_mtioctop(un, &local);
5606 
5607 #ifdef _MULTI_DATAMODEL
5608 	switch (ddi_model_convert_from(flag & FMODELS)) {
5609 	case DDI_MODEL_ILP32:
5610 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5611 			rval = ERANGE;
5612 			break;
5613 		}
5614 		/*
5615 		 * Convert 64 bit back to 32 bit before doing
5616 		 * copyout. This is what the ILP32 app expects.
5617 		 */
5618 		mtop_32_for_64.mt_op = local.mt_op;
5619 		mtop_32_for_64.mt_count = local.mt_count;
5620 
5621 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5622 		    sizeof (struct mtop32), flag)) {
5623 			rval = EFAULT;
5624 		}
5625 		break;
5626 
5627 	case DDI_MODEL_NONE:
5628 		passed.mt_count = local.mt_count;
5629 		passed.mt_op = local.mt_op;
5630 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5631 			rval = EFAULT;
5632 		}
5633 		break;
5634 	}
5635 #else /* ! _MULTI_DATAMODE */
5636 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5637 		rval = ERANGE;
5638 	} else {
5639 		passed.mt_op = local.mt_op;
5640 		passed.mt_count = local.mt_count;
5641 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5642 			rval = EFAULT;
5643 		}
5644 	}
5645 #endif /* _MULTI_DATAMODE */
5646 
5647 
5648 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5649 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5650 	    un->un_pos.blkno, un->un_pos.eof);
5651 
5652 	if (un->un_pos.pmode == invalid) {
5653 		un->un_density_known = 0;
5654 	}
5655 
5656 	ASSERT(mutex_owned(ST_MUTEX));
5657 	return (rval);
5658 }
5659 
5660 static int
5661 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5662 {
5663 	struct mtlop local;
5664 	int rval;
5665 
5666 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5667 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5668 		return (EFAULT);
5669 	}
5670 
5671 	rval = st_do_mtioctop(un, &local);
5672 
5673 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5674 		rval = EFAULT;
5675 	}
5676 	return (rval);
5677 }
5678 
5679 
5680 static int
5681 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5682 {
5683 	dev_t dev = un->un_dev;
5684 	int savefile;
5685 	int rval = 0;
5686 
5687 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5688 
5689 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5690 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5691 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5692 	    "fileno=%x, blkno=%x, eof=%x\n",
5693 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5694 
5695 	un->un_status = 0;
5696 
5697 	/*
5698 	 * if we are going to mess with a tape, we have to make sure we have
5699 	 * one and are not offline (i.e. no tape is initialized).  We let
5700 	 * commands pass here that don't actually touch the tape, except for
5701 	 * loading and initialization (rewinding).
5702 	 */
5703 	if (un->un_state == ST_STATE_OFFLINE) {
5704 		switch (mtop->mt_op) {
5705 		case MTLOAD:
5706 		case MTNOP:
5707 			/*
5708 			 * We don't want strategy calling st_tape_init here,
5709 			 * so, change state
5710 			 */
5711 			un->un_state = ST_STATE_INITIALIZING;
5712 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5713 			    "st_do_mtioctop : OFFLINE state = %d\n",
5714 			    un->un_state);
5715 			break;
5716 		default:
5717 			/*
5718 			 * reinitialize by normal means
5719 			 */
5720 			rval = st_tape_init(un);
5721 			if (rval) {
5722 				un->un_state = ST_STATE_INITIALIZING;
5723 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5724 				    "st_do_mtioctop : OFFLINE init failure ");
5725 				un->un_state = ST_STATE_OFFLINE;
5726 				un->un_pos.pmode = invalid;
5727 				if (rval != EACCES) {
5728 					rval = EIO;
5729 				}
5730 				return (rval);
5731 			}
5732 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5733 			break;
5734 		}
5735 	}
5736 
5737 	/*
5738 	 * If the file position is invalid, allow only those
5739 	 * commands that properly position the tape and fail
5740 	 * the rest with EIO
5741 	 */
5742 	if (un->un_pos.pmode == invalid) {
5743 		switch (mtop->mt_op) {
5744 		case MTWEOF:
5745 		case MTRETEN:
5746 		case MTERASE:
5747 		case MTEOM:
5748 		case MTFSF:
5749 		case MTFSR:
5750 		case MTBSF:
5751 		case MTNBSF:
5752 		case MTBSR:
5753 		case MTSRSZ:
5754 		case MTGRSZ:
5755 		case MTSEEK:
5756 		case MTBSSF:
5757 		case MTFSSF:
5758 			return (EIO);
5759 			/* NOTREACHED */
5760 		case MTREW:
5761 		case MTLOAD:
5762 		case MTOFFL:
5763 		case MTNOP:
5764 		case MTTELL:
5765 		case MTLOCK:
5766 		case MTUNLOCK:
5767 			break;
5768 
5769 		default:
5770 			return (ENOTTY);
5771 			/* NOTREACHED */
5772 		}
5773 	}
5774 
5775 	switch (mtop->mt_op) {
5776 	case MTERASE:
5777 		/*
5778 		 * MTERASE rewinds the tape, erase it completely, and returns
5779 		 * to the beginning of the tape
5780 		 */
5781 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5782 			un->un_status = KEY_WRITE_PROTECT;
5783 			un->un_err_resid = mtop->mt_count;
5784 			COPY_POS(&un->un_err_pos, &un->un_pos);
5785 			return (EACCES);
5786 		}
5787 		if (un->un_dp->options & ST_REEL) {
5788 			un->un_fmneeded = 2;
5789 		} else {
5790 			un->un_fmneeded = 1;
5791 		}
5792 		mtop->mt_count = mtop->mt_count ? 1 : 0;
5793 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5794 		    st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
5795 		    st_cmd(un, SCMD_ERASE, mtop->mt_count, SYNC_CMD)) {
5796 			un->un_pos.pmode = invalid;
5797 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5798 			    "st_do_mtioctop : EIO space or erase or "
5799 			    "check den)\n");
5800 			rval = EIO;
5801 		} else {
5802 			/* QIC and helical scan rewind after erase */
5803 			if (un->un_dp->options & ST_REEL) {
5804 				(void) st_cmd(un, SCMD_REWIND, 0, ASYNC_CMD);
5805 			}
5806 		}
5807 		break;
5808 
5809 	case MTWEOF:
5810 		/*
5811 		 * write an end-of-file record
5812 		 */
5813 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5814 			un->un_status = KEY_WRITE_PROTECT;
5815 			un->un_err_resid = mtop->mt_count;
5816 			COPY_POS(&un->un_err_pos, &un->un_pos);
5817 			return (EACCES);
5818 		}
5819 
5820 		/*
5821 		 * zero count means just flush buffers
5822 		 * negative count is not permitted
5823 		 */
5824 		if (mtop->mt_count < 0) {
5825 			return (EINVAL);
5826 		}
5827 
5828 		/* Not on worm */
5829 		if (un->un_read_only == RDWR) {
5830 			un->un_test_append = 1;
5831 		}
5832 
5833 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5834 			if (st_determine_density(un, B_WRITE)) {
5835 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5836 				    "st_do_mtioctop : EIO : MTWEOF can't "
5837 				    "determine density");
5838 				return (EIO);
5839 			}
5840 		}
5841 
5842 		rval = st_write_fm(dev, (int)mtop->mt_count);
5843 		if ((rval != 0) && (rval != EACCES)) {
5844 			/*
5845 			 * Failure due to something other than illegal
5846 			 * request results in loss of state (st_intr).
5847 			 */
5848 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5849 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5850 			    "file mark");
5851 			rval = EIO;
5852 		}
5853 		break;
5854 
5855 	case MTRETEN:
5856 		/*
5857 		 * retension the tape
5858 		 */
5859 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5860 		    st_cmd(un, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5861 			un->un_pos.pmode = invalid;
5862 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5863 			    "st_do_mtioctop : EIO : MTRETEN ");
5864 			rval = EIO;
5865 		}
5866 		break;
5867 
5868 	case MTREW:
5869 		/*
5870 		 * rewind  the tape
5871 		 */
5872 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5873 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5874 			    "st_do_mtioctop : EIO:MTREW check "
5875 			    "density/wfm failed");
5876 			return (EIO);
5877 		}
5878 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
5879 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5880 			    "st_do_mtioctop : EIO : MTREW ");
5881 			rval = EIO;
5882 		}
5883 		break;
5884 
5885 	case MTOFFL:
5886 		/*
5887 		 * rewinds, and, if appropriate, takes the device offline by
5888 		 * unloading the tape
5889 		 */
5890 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5891 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5892 			    "st_do_mtioctop :EIO:MTOFFL check "
5893 			    "density/wfm failed");
5894 			return (EIO);
5895 		}
5896 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
5897 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5898 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5899 			    "st_do_mtioctop : EIO : MTOFFL");
5900 			return (EIO);
5901 		}
5902 		un->un_pos.eof = ST_NO_EOF;
5903 		un->un_laststate = un->un_state;
5904 		un->un_state = ST_STATE_OFFLINE;
5905 		un->un_mediastate = MTIO_EJECTED;
5906 		break;
5907 
5908 	case MTLOAD:
5909 		/*
5910 		 * This is to load a tape into the drive
5911 		 * Note that if the tape is not loaded, the device will have
5912 		 * to be opened via O_NDELAY or O_NONBLOCK.
5913 		 */
5914 		/*
5915 		 * Let's try and clean things up, if we are not
5916 		 * initializing, and then send in the load command, no
5917 		 * matter what.
5918 		 *
5919 		 * load after a media change by the user.
5920 		 */
5921 
5922 		if (un->un_state > ST_STATE_INITIALIZING) {
5923 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5924 		}
5925 		rval = st_cmd(un, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5926 		/* Load command to a drive that doesn't support load */
5927 		if ((rval == EIO) &&
5928 		    ((un->un_status == KEY_NOT_READY) &&
5929 			/* Medium not present */
5930 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5931 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5932 		    (un->un_dp->type == MT_ISSTK9840) &&
5933 			/* CSL not present */
5934 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5935 			rval = ENOTTY;
5936 			break;
5937 		} else if (rval != EACCES && rval != 0) {
5938 			rval = EIO;
5939 		}
5940 		if (rval) {
5941 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5942 			    "st_do_mtioctop : %s : MTLOAD\n",
5943 			    rval == EACCES ? "EACCES" : "EIO");
5944 			/*
5945 			 * If load tape fails, who knows what happened...
5946 			 */
5947 			un->un_pos.pmode = invalid;
5948 			break;
5949 		}
5950 
5951 		/*
5952 		 * reset all counters appropriately using rewind, as if LOAD
5953 		 * succeeds, we are at BOT
5954 		 */
5955 		un->un_state = ST_STATE_INITIALIZING;
5956 
5957 		rval = st_tape_init(un);
5958 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5959 			rval = 0;
5960 			break;
5961 		}
5962 
5963 		if (rval != 0) {
5964 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5965 			    "st_do_mtioctop : EIO : MTLOAD calls "
5966 			    "st_tape_init\n");
5967 			rval = EIO;
5968 			un->un_state = ST_STATE_OFFLINE;
5969 		}
5970 
5971 		break;
5972 
5973 	case MTNOP:
5974 		un->un_status = 0;		/* Reset status */
5975 		un->un_err_resid = 0;
5976 		mtop->mt_count = MTUNIT(dev);
5977 		break;
5978 
5979 	case MTEOM:
5980 		/*
5981 		 * positions the tape at a location just after the last file
5982 		 * written on the tape. For cartridge and 8 mm, this after
5983 		 * the last file mark; for reel, this is inbetween the two
5984 		 * last 2 file marks
5985 		 */
5986 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5987 		    (un->un_lastop == ST_OP_WRITE) ||
5988 		    (un->un_lastop == ST_OP_WEOF)) {
5989 			/*
5990 			 * If the command wants to move to logical end
5991 			 * of media, and we're already there, we're done.
5992 			 * If we were at logical eot, we reset the state
5993 			 * to be *not* at logical eot.
5994 			 *
5995 			 * If we're at physical or logical eot, we prohibit
5996 			 * forward space operations (unconditionally).
5997 			 *
5998 			 * Also if the last operation was a write of any
5999 			 * kind the tape is at EOD.
6000 			 */
6001 			return (0);
6002 		}
6003 		/*
6004 		 * physical tape position may not be what we've been
6005 		 * telling the user; adjust the request accordingly
6006 		 */
6007 		if (IN_EOF(un->un_pos)) {
6008 			un->un_pos.fileno++;
6009 			un->un_pos.blkno = 0;
6010 		}
6011 
6012 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
6013 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6014 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
6015 			    " failed");
6016 			return (EIO);
6017 		}
6018 
6019 		/*
6020 		 * st_find_eod() returns the last fileno we knew about;
6021 		 */
6022 		savefile = st_find_eod(un);
6023 
6024 		if ((un->un_status != KEY_BLANK_CHECK) &&
6025 		    (un->un_status != SUN_KEY_EOT)) {
6026 			un->un_pos.pmode = invalid;
6027 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6028 			    "st_do_mtioctop : EIO : MTEOM status check failed");
6029 			rval = EIO;
6030 		} else {
6031 			/*
6032 			 * For 1/2" reel tapes assume logical EOT marked
6033 			 * by two file marks or we don't care that we may
6034 			 * be extending the last file on the tape.
6035 			 */
6036 			if (un->un_dp->options & ST_REEL) {
6037 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
6038 					un->un_pos.pmode = invalid;
6039 					ST_DEBUG2(ST_DEVINFO, st_label,
6040 					    SCSI_DEBUG,
6041 					    "st_do_mtioctop : EIO : MTEOM space"
6042 					    " cmd failed");
6043 					rval = EIO;
6044 					break;
6045 				}
6046 				/*
6047 				 * Fix up the block number.
6048 				 */
6049 				un->un_pos.blkno = 0;
6050 				un->un_err_pos.blkno = 0;
6051 			}
6052 			un->un_err_resid = 0;
6053 			un->un_pos.fileno = savefile;
6054 			un->un_pos.eof = ST_EOT;
6055 		}
6056 		un->un_status = 0;
6057 		break;
6058 
6059 	case MTFSF:
6060 		MAX_SPACE_CNT(mtop->mt_count);
6061 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
6062 		break;
6063 
6064 	case MTFSR:
6065 		MAX_SPACE_CNT(mtop->mt_count);
6066 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
6067 		break;
6068 
6069 	case MTBSF:
6070 		MAX_SPACE_CNT(mtop->mt_count);
6071 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
6072 		break;
6073 
6074 	case MTNBSF:
6075 		MAX_SPACE_CNT(mtop->mt_count);
6076 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
6077 		break;
6078 
6079 	case MTBSR:
6080 		MAX_SPACE_CNT(mtop->mt_count);
6081 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
6082 		break;
6083 
6084 	case MTBSSF:
6085 		MAX_SPACE_CNT(mtop->mt_count);
6086 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
6087 		break;
6088 
6089 	case MTFSSF:
6090 		MAX_SPACE_CNT(mtop->mt_count);
6091 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
6092 		break;
6093 
6094 	case MTSRSZ:
6095 
6096 		/*
6097 		 * Set record-size to that sent by user
6098 		 * Check to see if there is reason that the requested
6099 		 * block size should not be set.
6100 		 */
6101 
6102 		/* If requesting variable block size is it ok? */
6103 		if ((mtop->mt_count == 0) &&
6104 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
6105 			return (ENOTTY);
6106 		}
6107 
6108 		/*
6109 		 * If requested block size is not variable "0",
6110 		 * is it less then minimum.
6111 		 */
6112 		if ((mtop->mt_count != 0) &&
6113 		    (mtop->mt_count < un->un_minbsize)) {
6114 			return (EINVAL);
6115 		}
6116 
6117 		/* Is the requested block size more then maximum */
6118 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
6119 		    (un->un_maxbsize != 0)) {
6120 			return (EINVAL);
6121 		}
6122 
6123 		/* Is requested block size a modulus the device likes */
6124 		if ((mtop->mt_count % un->un_data_mod) != 0) {
6125 			return (EINVAL);
6126 		}
6127 
6128 		if (st_change_block_size(un, (uint32_t)mtop->mt_count) != 0) {
6129 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6130 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
6131 			return (EIO);
6132 		}
6133 
6134 		return (0);
6135 
6136 	case MTGRSZ:
6137 		/*
6138 		 * Get record-size to the user
6139 		 */
6140 		mtop->mt_count = un->un_bsize;
6141 		rval = 0;
6142 		break;
6143 
6144 	case MTTELL:
6145 		rval = st_update_block_pos(un, st_cmd, 0);
6146 		mtop->mt_count = un->un_pos.lgclblkno;
6147 		break;
6148 
6149 	case MTSEEK:
6150 		rval = st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
6151 		    (uint64_t)mtop->mt_count, un->un_pos.partition);
6152 		/*
6153 		 * This bit of magic make mt print the actual position if
6154 		 * the resulting position was not what was asked for.
6155 		 */
6156 		if (rval == ESPIPE) {
6157 			rval = EIO;
6158 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
6159 				mtop->mt_op = MTTELL;
6160 				mtop->mt_count = un->un_pos.lgclblkno;
6161 			}
6162 		}
6163 		break;
6164 
6165 	case MTLOCK:
6166 		if (st_cmd(un, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
6167 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6168 			    "st_do_mtioctop : EIO : MTLOCK");
6169 			rval = EIO;
6170 		}
6171 		break;
6172 
6173 	case MTUNLOCK:
6174 		if (st_cmd(un, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
6175 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6176 			    "st_do_mtioctop : EIO : MTUNLOCK");
6177 			rval = EIO;
6178 		}
6179 		break;
6180 
6181 	default:
6182 		rval = ENOTTY;
6183 	}
6184 
6185 	return (rval);
6186 }
6187 
6188 
6189 /*
6190  * Run a command for uscsi ioctl.
6191  */
6192 static int
6193 st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
6194 {
6195 	struct uscsi_cmd	*uscmd;
6196 	struct buf	*bp;
6197 	enum uio_seg	uioseg;
6198 	int	offline_state = 0;
6199 	int	err = 0;
6200 	dev_t dev = un->un_dev;
6201 
6202 	ST_FUNC(ST_DEVINFO, st_uscsi_cmd);
6203 
6204 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6205 	    "st_uscsi_cmd(dev = 0x%lx)\n", un->un_dev);
6206 
6207 	ASSERT(mutex_owned(ST_MUTEX));
6208 
6209 	/*
6210 	 * We really don't know what commands are coming in here and
6211 	 * we don't want to limit the commands coming in.
6212 	 *
6213 	 * If st_tape_init() gets called from st_strategy(), then we
6214 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
6215 	 * which it never will, as we set it below.  To prevent
6216 	 * st_tape_init() from getting called, we have to set state to other
6217 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
6218 	 * achieves this purpose already.
6219 	 *
6220 	 * We use offline_state to preserve the OFFLINE state, if it exists,
6221 	 * so other entry points to the driver might have the chance to call
6222 	 * st_tape_init().
6223 	 */
6224 	if (un->un_state == ST_STATE_OFFLINE) {
6225 		un->un_laststate = ST_STATE_OFFLINE;
6226 		un->un_state = ST_STATE_INITIALIZING;
6227 		offline_state = 1;
6228 	}
6229 
6230 	mutex_exit(ST_MUTEX);
6231 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag, ROUTE, &uscmd);
6232 	mutex_enter(ST_MUTEX);
6233 	if (err != 0) {
6234 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6235 		    "st_uscsi_cmd: scsi_uscsi_alloc_and_copyin failed\n");
6236 		goto exit;
6237 	}
6238 
6239 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
6240 
6241 	/* check to see if this command requires the drive to be reserved */
6242 	if (uscmd->uscsi_cdb != NULL) {
6243 		err = st_check_cdb_for_need_to_reserve(un,
6244 		    (uchar_t *)uscmd->uscsi_cdb);
6245 		if (err) {
6246 			goto exit_free;
6247 		}
6248 		/*
6249 		 * If this is a space command we need to save the starting
6250 		 * point so we can retry from there if the command fails.
6251 		 */
6252 		if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6253 		    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) {
6254 			(void) st_update_block_pos(un, st_cmd, 0);
6255 		}
6256 	}
6257 
6258 	/*
6259 	 * Forground should not be doing anything while recovery is active.
6260 	 */
6261 	ASSERT(un->un_recov_buf_busy == 0);
6262 
6263 	/*
6264 	 * Get buffer resources...
6265 	 */
6266 	while (un->un_sbuf_busy)
6267 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6268 	un->un_sbuf_busy = 1;
6269 
6270 #ifdef STDEBUG
6271 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0x7) > 6) {
6272 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
6273 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6274 		    "uscsi cdb", uscmd->uscsi_cdb);
6275 		if (uscmd->uscsi_buflen) {
6276 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6277 			    "uscsi %s of %ld bytes %s %s space\n",
6278 			    (rw == B_READ) ? rd_str : wr_str,
6279 			    uscmd->uscsi_buflen,
6280 			    (rw == B_READ) ? "to" : "from",
6281 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
6282 		}
6283 	}
6284 #endif /* STDEBUG */
6285 
6286 	/*
6287 	 * Although st_uscsi_cmd() never makes use of these
6288 	 * now, we are just being safe and consistent.
6289 	 */
6290 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
6291 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
6292 
6293 	un->un_srqbufp = uscmd->uscsi_rqbuf;
6294 	bp = un->un_sbufp;
6295 	bzero(bp, sizeof (buf_t));
6296 	if (uscmd->uscsi_cdb != NULL) {
6297 		bp->b_forw = (struct buf *)(uintptr_t)uscmd->uscsi_cdb[0];
6298 	}
6299 	bp->b_back = (struct buf *)uscmd;
6300 
6301 	mutex_exit(ST_MUTEX);
6302 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, st_strategy, bp, NULL);
6303 	mutex_enter(ST_MUTEX);
6304 
6305 	/*
6306 	 * If scsi reset successful, don't write any filemarks.
6307 	 */
6308 	if ((err == 0) && (uscmd->uscsi_flags &
6309 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
6310 		un->un_fmneeded = 0;
6311 	}
6312 
6313 exit_free:
6314 	/*
6315 	 * Free resources
6316 	 */
6317 	un->un_sbuf_busy = 0;
6318 	un->un_srqbufp = NULL;
6319 
6320 	/*
6321 	 * If was a space command need to update logical block position.
6322 	 * If the command failed such that positioning is invalid, Don't
6323 	 * update the position as the user must do this to validate the
6324 	 * position for data protection.
6325 	 */
6326 	if ((uscmd->uscsi_cdb != NULL) &&
6327 	    ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6328 	    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) &&
6329 	    (un->un_pos.pmode != invalid)) {
6330 		un->un_running.pmode = invalid;
6331 		(void) st_update_block_pos(un, st_cmd, 1);
6332 		/*
6333 		 * Set running position to invalid so it updates on the
6334 		 * next command.
6335 		 */
6336 		un->un_running.pmode = invalid;
6337 	}
6338 	cv_signal(&un->un_sbuf_cv);
6339 	mutex_exit(ST_MUTEX);
6340 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
6341 	mutex_enter(ST_MUTEX);
6342 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6343 	    "st_uscsi_cmd returns 0x%x\n", err);
6344 
6345 exit:
6346 	/* don't lose offline state */
6347 	if (offline_state) {
6348 		un->un_state = ST_STATE_OFFLINE;
6349 	}
6350 
6351 	ASSERT(mutex_owned(ST_MUTEX));
6352 	return (err);
6353 }
6354 
6355 static int
6356 st_write_fm(dev_t dev, int wfm)
6357 {
6358 	int i;
6359 	int rval;
6360 
6361 	GET_SOFT_STATE(dev);
6362 
6363 	ST_FUNC(ST_DEVINFO, st_write_fm);
6364 
6365 	ASSERT(mutex_owned(ST_MUTEX));
6366 
6367 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6368 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6369 
6370 	/*
6371 	 * write one filemark at the time after EOT
6372 	 */
6373 	if (un->un_pos.eof >= ST_EOT) {
6374 		for (i = 0; i < wfm; i++) {
6375 			rval = st_cmd(un, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6376 			if (rval == EACCES) {
6377 				return (rval);
6378 			}
6379 			if (rval != 0) {
6380 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6381 				    "st_write_fm : EIO : write EOT file mark");
6382 				return (EIO);
6383 			}
6384 		}
6385 	} else {
6386 		rval = st_cmd(un, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6387 		if (rval == EACCES) {
6388 			return (rval);
6389 		}
6390 		if (rval) {
6391 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6392 			    "st_write_fm : EIO : write file mark");
6393 			return (EIO);
6394 		}
6395 	}
6396 
6397 	ASSERT(mutex_owned(ST_MUTEX));
6398 	return (0);
6399 }
6400 
6401 #ifdef STDEBUG
6402 static void
6403 st_start_dump(struct scsi_tape *un, struct buf *bp)
6404 {
6405 	struct scsi_pkt *pkt = BP_PKT(bp);
6406 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6407 
6408 	ST_FUNC(ST_DEVINFO, st_start_dump);
6409 
6410 	if ((st_debug & 0x7) < 6)
6411 		return;
6412 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6413 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6414 	    (void *)bp->b_forw, bp->b_bcount,
6415 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6416 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6417 	    "st_start: cdb",  (caddr_t)cdbp);
6418 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6419 	    "st_start: fileno=%d, blk=%d\n",
6420 	    un->un_pos.fileno, un->un_pos.blkno);
6421 }
6422 #endif
6423 
6424 
6425 /*
6426  * Command start && done functions
6427  */
6428 
6429 /*
6430  * st_start()
6431  *
6432  * Called from:
6433  *  st_strategy() to start a command.
6434  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6435  *  st_attach() when resuming from power down state.
6436  *  st_start_restart() to retry transport when device was previously busy.
6437  *  st_done_and_mutex_exit() to start the next command when previous is done.
6438  *
6439  * On entry:
6440  *  scsi_pkt may or may not be allocated.
6441  *
6442  */
6443 static void
6444 st_start(struct scsi_tape *un)
6445 {
6446 	struct buf *bp;
6447 	int status;
6448 	int queued;
6449 
6450 	ST_FUNC(ST_DEVINFO, st_start);
6451 	ASSERT(mutex_owned(ST_MUTEX));
6452 
6453 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6454 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6455 
6456 	if (un->un_recov_buf_busy) {
6457 		/* recovery commands can happen anytime */
6458 		bp = un->un_recov_buf;
6459 		queued = 0;
6460 	} else if (un->un_sbuf_busy) {
6461 		/* sbuf commands should only happen with an empty queue. */
6462 		ASSERT(un->un_quef == NULL);
6463 		ASSERT(un->un_runqf == NULL);
6464 		bp = un->un_sbufp;
6465 		queued = 0;
6466 	} else if (un->un_quef != NULL) {
6467 		if (un->un_persistence && un->un_persist_errors) {
6468 			return;
6469 		}
6470 		bp = un->un_quef;
6471 		queued = 1;
6472 	} else {
6473 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6474 		    "st_start() returning no buf found\n");
6475 		return;
6476 	}
6477 
6478 	ASSERT((bp->b_flags & B_DONE) == 0);
6479 
6480 	/*
6481 	 * Don't send more than un_throttle commands to the HBA
6482 	 */
6483 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6484 		/*
6485 		 * if doing recovery we know there is outstanding commands.
6486 		 */
6487 		if (bp != un->un_recov_buf) {
6488 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6489 			    "st_start returning throttle = %d or ncmds = %d\n",
6490 			    un->un_throttle, un->un_ncmds);
6491 			if (un->un_ncmds == 0) {
6492 				typedef void (*func)();
6493 				func fnc = (func)st_runout;
6494 
6495 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6496 				    "Sending delayed start to st_runout()\n");
6497 				mutex_exit(ST_MUTEX);
6498 				(void) timeout(fnc, un, drv_usectohz(1000000));
6499 				mutex_enter(ST_MUTEX);
6500 			}
6501 			return;
6502 		}
6503 	}
6504 
6505 	/*
6506 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6507 	 * build the command.
6508 	 */
6509 	if (BP_PKT(bp) == NULL) {
6510 		ASSERT((bp->b_flags & B_DONE) == 0);
6511 		st_make_cmd(un, bp, st_runout);
6512 		ASSERT((bp->b_flags & B_DONE) == 0);
6513 		status = geterror(bp);
6514 
6515 		/*
6516 		 * Some HBA's don't call bioerror() to set an error.
6517 		 * And geterror() returns zero if B_ERROR is not set.
6518 		 * So if we get zero we must check b_error.
6519 		 */
6520 		if (status == 0 && bp->b_error != 0) {
6521 			status = bp->b_error;
6522 			bioerror(bp, status);
6523 		}
6524 
6525 		/*
6526 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6527 		 * In tape ENOMEM has special meaning so we'll change it.
6528 		 */
6529 		if (status == ENOMEM) {
6530 			status = 0;
6531 			bioerror(bp, status);
6532 		}
6533 
6534 		/*
6535 		 * Did it fail and is it retryable?
6536 		 * If so return and wait for the callback through st_runout.
6537 		 * Also looks like scsi_init_pkt() will setup a callback even
6538 		 * if it isn't retryable.
6539 		 */
6540 		if (BP_PKT(bp) == NULL) {
6541 			if (status == 0) {
6542 				/*
6543 				 * If first attempt save state.
6544 				 */
6545 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6546 					un->un_laststate = un->un_state;
6547 					un->un_state = ST_STATE_RESOURCE_WAIT;
6548 				}
6549 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6550 				    "temp no resources for pkt\n");
6551 			} else if (status == EINVAL) {
6552 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6553 				    "scsi_init_pkt rejected pkt as too big\n");
6554 				if (un->un_persistence) {
6555 					st_set_pe_flag(un);
6556 				}
6557 			} else {
6558 				/*
6559 				 * Unlikely that it would be retryable then not.
6560 				 */
6561 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6562 					un->un_state = un->un_laststate;
6563 				}
6564 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6565 				    "perm no resources for pkt errno = 0x%x\n",
6566 				    status);
6567 			}
6568 			return;
6569 		}
6570 		/*
6571 		 * Worked this time set the state back.
6572 		 */
6573 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6574 			un->un_state = un->un_laststate;
6575 		}
6576 	}
6577 
6578 	if (queued) {
6579 		/*
6580 		 * move from waitq to runq
6581 		 */
6582 		(void) st_remove_from_queue(&un->un_quef, &un->un_quel, bp);
6583 		st_add_to_queue(&un->un_runqf, &un->un_runql, un->un_runql, bp);
6584 	}
6585 
6586 
6587 #ifdef STDEBUG
6588 	st_start_dump(un, bp);
6589 #endif
6590 
6591 	/* could not get here if throttle was zero */
6592 	un->un_last_throttle = un->un_throttle;
6593 	un->un_throttle = 0;	/* so nothing else will come in here */
6594 	un->un_ncmds++;
6595 
6596 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6597 
6598 	status = st_transport(un, BP_PKT(bp));
6599 
6600 	if (un->un_last_throttle) {
6601 		un->un_throttle = un->un_last_throttle;
6602 	}
6603 
6604 	if (status != TRAN_ACCEPT) {
6605 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6606 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
6607 		    "Unhappy transport packet status 0x%x\n", status);
6608 
6609 		if (status == TRAN_BUSY) {
6610 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
6611 
6612 			/*
6613 			 * If command recovery is enabled and this isn't
6614 			 * a recovery command try command recovery.
6615 			 */
6616 			if (pkti->privatelen == sizeof (recov_info) &&
6617 			    bp != un->un_recov_buf) {
6618 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
6619 				    "Command Recovery called on busy send\n");
6620 				if (st_command_recovery(un, BP_PKT(bp),
6621 				    ATTEMPT_RETRY) == JUST_RETURN) {
6622 					return;
6623 				}
6624 			} else {
6625 				mutex_exit(ST_MUTEX);
6626 				if (st_handle_start_busy(un, bp,
6627 				    ST_TRAN_BUSY_TIMEOUT, queued) == 0) {
6628 					mutex_enter(ST_MUTEX);
6629 					return;
6630 				}
6631 				/*
6632 				 * if too many retries, fail the transport
6633 				 */
6634 				mutex_enter(ST_MUTEX);
6635 			}
6636 		}
6637 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6638 		    "transport rejected %d\n", status);
6639 		bp->b_resid = bp->b_bcount;
6640 
6641 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6642 		ST_DO_ERRSTATS(un, st_transerrs);
6643 		if ((bp == un->un_recov_buf) && (status == TRAN_BUSY)) {
6644 			st_bioerror(bp, EBUSY);
6645 		} else {
6646 			st_bioerror(bp, EIO);
6647 			st_set_pe_flag(un);
6648 		}
6649 		st_done_and_mutex_exit(un, bp);
6650 		mutex_enter(ST_MUTEX);
6651 	}
6652 
6653 	ASSERT(mutex_owned(ST_MUTEX));
6654 }
6655 
6656 /*
6657  * if the transport is busy, then put this bp back on the waitq
6658  */
6659 static int
6660 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6661     clock_t timeout_interval, int queued)
6662 {
6663 
6664 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
6665 
6666 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6667 
6668 	mutex_enter(ST_MUTEX);
6669 
6670 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6671 	    "st_handle_start_busy()\n");
6672 
6673 	/*
6674 	 * Check to see if we hit the retry timeout and one last check for
6675 	 * making sure this is the last on the runq, if it is not, we have
6676 	 * to fail
6677 	 */
6678 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
6679 	    ((queued) && (un->un_runql != bp))) {
6680 		mutex_exit(ST_MUTEX);
6681 		return (-1);
6682 	}
6683 
6684 	if (queued) {
6685 		/* put the bp back on the waitq */
6686 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
6687 	}
6688 
6689 	/*
6690 	 * Decrement un_ncmds so that this
6691 	 * gets thru' st_start() again.
6692 	 */
6693 	un->un_ncmds--;
6694 
6695 	if (queued) {
6696 		/*
6697 		 * since this is an error case, we won't have to do this list
6698 		 * walking much. We've already made sure this bp was the
6699 		 * last on the runq
6700 		 */
6701 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6702 
6703 		/*
6704 		 * send a marker pkt, if appropriate
6705 		 */
6706 		st_hba_unflush(un);
6707 
6708 	}
6709 	/*
6710 	 * all queues are aligned, we are just waiting to
6711 	 * transport, don't alloc any more buf p's, when
6712 	 * st_start is reentered.
6713 	 */
6714 	(void) timeout(st_start_restart, un, timeout_interval);
6715 
6716 	mutex_exit(ST_MUTEX);
6717 	return (0);
6718 }
6719 
6720 
6721 /*
6722  * st_runout a callback that is called what a resource allocatation failed
6723  */
6724 static int
6725 st_runout(caddr_t arg)
6726 {
6727 	struct scsi_tape *un = (struct scsi_tape *)arg;
6728 	struct buf *bp;
6729 	int queued;
6730 
6731 	ASSERT(un != NULL);
6732 
6733 	ST_FUNC(ST_DEVINFO, st_runout);
6734 
6735 	mutex_enter(ST_MUTEX);
6736 
6737 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6738 
6739 	if (un->un_recov_buf_busy != 0) {
6740 		bp = un->un_recov_buf;
6741 		queued = 0;
6742 	} else if (un->un_sbuf_busy != 0) {
6743 		/* sbuf commands should only happen with an empty queue. */
6744 		ASSERT(un->un_quef == NULL);
6745 		ASSERT(un->un_runqf == NULL);
6746 		bp = un->un_sbufp;
6747 		queued = 0;
6748 	} else if (un->un_quef != NULL) {
6749 		bp = un->un_quef;
6750 		if (un->un_persistence && un->un_persist_errors) {
6751 			mutex_exit(ST_MUTEX);
6752 			bp->b_resid = bp->b_bcount;
6753 			biodone(bp);
6754 			return (1);
6755 		}
6756 		queued = 1;
6757 	} else {
6758 		ASSERT(1 == 0);
6759 		mutex_exit(ST_MUTEX);
6760 		return (1);
6761 	}
6762 
6763 	/*
6764 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6765 	 */
6766 	if ((bp != NULL) && (geterror(bp) != 0)) {
6767 
6768 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6769 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6770 		    bp->b_flags, geterror(bp));
6771 		ASSERT((bp->b_flags & B_DONE) == 0);
6772 
6773 		if (queued) {
6774 			(void) st_remove_from_queue(&un->un_quef, &un->un_quel,
6775 			    bp);
6776 		}
6777 		mutex_exit(ST_MUTEX);
6778 
6779 		ASSERT((bp->b_flags & B_DONE) == 0);
6780 
6781 		/*
6782 		 * Set resid, Error already set, then unblock calling thread.
6783 		 */
6784 		bp->b_resid = bp->b_bcount;
6785 		biodone(bp);
6786 	} else {
6787 		/*
6788 		 * Try Again
6789 		 */
6790 		st_start(un);
6791 		mutex_exit(ST_MUTEX);
6792 	}
6793 
6794 	/*
6795 	 * Comments courtesy of sd.c
6796 	 * The scsi_init_pkt routine allows for the callback function to
6797 	 * return a 0 indicating the callback should be rescheduled or a 1
6798 	 * indicating not to reschedule. This routine always returns 1
6799 	 * because the driver always provides a callback function to
6800 	 * scsi_init_pkt. This results in a callback always being scheduled
6801 	 * (via the scsi_init_pkt callback implementation) if a resource
6802 	 * failure occurs.
6803 	 */
6804 
6805 	return (1);
6806 }
6807 
6808 /*
6809  * st_done_and_mutex_exit()
6810  *	- remove bp from runq
6811  *	- start up the next request
6812  *	- if this was an asynch bp, clean up
6813  *	- exit with released mutex
6814  */
6815 static void
6816 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6817 {
6818 	int pe_flagged = 0;
6819 	struct scsi_pkt *pkt = BP_PKT(bp);
6820 	pkt_info *pktinfo = pkt->pkt_private;
6821 
6822 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6823 #if !defined(lint)
6824 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6825 #endif
6826 
6827 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6828 
6829 	ASSERT(mutex_owned(ST_MUTEX));
6830 
6831 	(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6832 
6833 	un->un_ncmds--;
6834 	cv_signal(&un->un_queue_cv);
6835 
6836 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6837 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6838 	    "0x%x\n", pkt->pkt_cdbp[0], bp->b_bcount,
6839 	    bp->b_resid, bp->b_flags);
6840 
6841 
6842 	/*
6843 	 * update kstats with transfer count info
6844 	 */
6845 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6846 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6847 		if (bp->b_flags & B_READ) {
6848 			IOSP->reads++;
6849 			IOSP->nread += n_done;
6850 		} else {
6851 			IOSP->writes++;
6852 			IOSP->nwritten += n_done;
6853 		}
6854 	}
6855 
6856 	/*
6857 	 * Start the next one before releasing resources on this one, if
6858 	 * there is something on the queue and persistent errors has not been
6859 	 * flagged
6860 	 */
6861 
6862 	if ((pe_flagged = (un->un_persistence && un->un_persist_errors)) != 0) {
6863 		un->un_last_resid = bp->b_resid;
6864 		un->un_last_count = bp->b_bcount;
6865 	}
6866 
6867 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6868 		cv_broadcast(&un->un_tape_busy_cv);
6869 	} else if (un->un_quef && un->un_throttle && !pe_flagged &&
6870 	    (bp != un->un_recov_buf)) {
6871 		st_start(un);
6872 	}
6873 
6874 	un->un_retry_ct = max(pktinfo->pkt_retry_cnt, pktinfo->str_retry_cnt);
6875 
6876 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6877 		/*
6878 		 * Since we marked this ourselves as ASYNC,
6879 		 * there isn't anybody around waiting for
6880 		 * completion any more.
6881 		 */
6882 		uchar_t *cmd = pkt->pkt_cdbp;
6883 		if (*cmd == SCMD_READ || *cmd == SCMD_WRITE) {
6884 			bp->b_un.b_addr = (caddr_t)0;
6885 		}
6886 		ST_DEBUG(ST_DEVINFO, st_label, CE_NOTE,
6887 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6888 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
6889 		    "CDB sent with B_ASYNC",  (caddr_t)cmd);
6890 		if (pkt) {
6891 			scsi_destroy_pkt(pkt);
6892 		}
6893 		un->un_sbuf_busy = 0;
6894 		cv_signal(&un->un_sbuf_cv);
6895 		mutex_exit(ST_MUTEX);
6896 		return;
6897 	}
6898 
6899 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6900 		/*
6901 		 * Copy status from scsi_pkt to uscsi_cmd
6902 		 * since st_uscsi_cmd needs it
6903 		 */
6904 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6905 	}
6906 
6907 
6908 #ifdef STDEBUG
6909 	if (((st_debug & 0x7) >= 4) &&
6910 	    (((un->un_pos.blkno % 100) == 0) ||
6911 	    (un->un_persistence && un->un_persist_errors))) {
6912 
6913 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6914 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6915 		    "un_errno = %d, un_pe = %d\n",
6916 		    un->un_ncmds, un->un_throttle, un->un_errno,
6917 		    un->un_persist_errors);
6918 	}
6919 
6920 #endif
6921 
6922 	mutex_exit(ST_MUTEX);
6923 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6924 	    "st_done_and_mutex_exit: freeing pkt\n");
6925 
6926 	if (pkt) {
6927 		scsi_destroy_pkt(pkt);
6928 	}
6929 
6930 	biodone(bp);
6931 
6932 	/*
6933 	 * now that we biodoned that command, if persistent errors have been
6934 	 * flagged, flush the waitq
6935 	 */
6936 	if (pe_flagged)
6937 		st_flush(un);
6938 }
6939 
6940 
6941 /*
6942  * Tape error, flush tape driver queue.
6943  */
6944 static void
6945 st_flush(struct scsi_tape *un)
6946 {
6947 	struct buf *bp;
6948 
6949 	ST_FUNC(ST_DEVINFO, st_flush);
6950 
6951 	mutex_enter(ST_MUTEX);
6952 
6953 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6954 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6955 	    un->un_ncmds, (void *)un->un_quef);
6956 
6957 	/*
6958 	 * if we still have commands outstanding, wait for them to come in
6959 	 * before flushing the queue, and make sure there is a queue
6960 	 */
6961 	if (un->un_ncmds || !un->un_quef)
6962 		goto exit;
6963 
6964 	/*
6965 	 * we have no more commands outstanding, so let's deal with special
6966 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6967 	 * is 0, then we know there was no error and we return a 0 read or
6968 	 * write before showing errors
6969 	 */
6970 
6971 	/* Flush the wait queue. */
6972 	while ((bp = un->un_quef) != NULL) {
6973 		un->un_quef = bp->b_actf;
6974 
6975 		bp->b_resid = bp->b_bcount;
6976 
6977 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6978 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6979 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6980 
6981 		st_set_pe_errno(un);
6982 
6983 		bioerror(bp, un->un_errno);
6984 
6985 		mutex_exit(ST_MUTEX);
6986 		/* it should have one, but check anyway */
6987 		if (BP_PKT(bp)) {
6988 			scsi_destroy_pkt(BP_PKT(bp));
6989 		}
6990 		biodone(bp);
6991 		mutex_enter(ST_MUTEX);
6992 	}
6993 
6994 	/*
6995 	 * It's not a bad practice to reset the
6996 	 * waitq tail pointer to NULL.
6997 	 */
6998 	un->un_quel = NULL;
6999 
7000 exit:
7001 	/* we mucked with the queue, so let others know about it */
7002 	cv_signal(&un->un_queue_cv);
7003 	mutex_exit(ST_MUTEX);
7004 }
7005 
7006 
7007 /*
7008  * Utility functions
7009  */
7010 static int
7011 st_determine_generic(struct scsi_tape *un)
7012 {
7013 	int bsize;
7014 	static char *cart = "0.25 inch cartridge";
7015 	char *sizestr;
7016 
7017 	ST_FUNC(ST_DEVINFO, st_determine_generic);
7018 
7019 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7020 	    "st_determine_generic(un = 0x%p)\n", (void*)un);
7021 
7022 	ASSERT(mutex_owned(ST_MUTEX));
7023 
7024 	if (st_modesense(un)) {
7025 		return (-1);
7026 	}
7027 
7028 	bsize = (un->un_mspl->high_bl << 16)	|
7029 	    (un->un_mspl->mid_bl << 8)	|
7030 	    (un->un_mspl->low_bl);
7031 
7032 	if (bsize == 0) {
7033 		un->un_dp->options |= ST_VARIABLE;
7034 		un->un_dp->bsize = 0;
7035 		un->un_bsize = 0;
7036 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
7037 		/*
7038 		 * record size of this device too big.
7039 		 * try and convert it to variable record length.
7040 		 *
7041 		 */
7042 		un->un_dp->options |= ST_VARIABLE;
7043 		if (st_change_block_size(un, 0) != 0) {
7044 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7045 			    "Fixed Record Size %d is too large\n", bsize);
7046 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7047 			    "Cannot switch to variable record size\n");
7048 			un->un_dp->options &= ~ST_VARIABLE;
7049 			return (-1);
7050 		}
7051 	} else if (st_change_block_size(un, 0) == 0) {
7052 		/*
7053 		 * If the drive was set to a non zero block size,
7054 		 * See if it can be set to a zero block size.
7055 		 * If it works, ST_VARIABLE so user can set it as they want.
7056 		 */
7057 		un->un_dp->options |= ST_VARIABLE;
7058 		un->un_dp->bsize = 0;
7059 		un->un_bsize = 0;
7060 	} else {
7061 		un->un_dp->bsize = bsize;
7062 		un->un_bsize = bsize;
7063 	}
7064 
7065 
7066 	switch (un->un_mspl->density) {
7067 	default:
7068 	case 0x0:
7069 		/*
7070 		 * default density, cannot determine any other
7071 		 * information.
7072 		 */
7073 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
7074 		un->un_dp->type = ST_TYPE_DEFAULT;
7075 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
7076 		break;
7077 	case 0x1:
7078 	case 0x2:
7079 	case 0x3:
7080 	case 0x6:
7081 		/*
7082 		 * 1/2" reel
7083 		 */
7084 		sizestr = "0.50 inch reel";
7085 		un->un_dp->type = ST_TYPE_REEL;
7086 		un->un_dp->options |= ST_REEL;
7087 		un->un_dp->densities[0] = 0x1;
7088 		un->un_dp->densities[1] = 0x2;
7089 		un->un_dp->densities[2] = 0x6;
7090 		un->un_dp->densities[3] = 0x3;
7091 		break;
7092 	case 0x4:
7093 	case 0x5:
7094 	case 0x7:
7095 	case 0x0b:
7096 
7097 		/*
7098 		 * Quarter inch.
7099 		 */
7100 		sizestr = cart;
7101 		un->un_dp->type = ST_TYPE_DEFAULT;
7102 		un->un_dp->options |= ST_QIC;
7103 
7104 		un->un_dp->densities[1] = 0x4;
7105 		un->un_dp->densities[2] = 0x5;
7106 		un->un_dp->densities[3] = 0x7;
7107 		un->un_dp->densities[0] = 0x0b;
7108 		break;
7109 
7110 	case 0x0f:
7111 	case 0x10:
7112 	case 0x11:
7113 	case 0x12:
7114 		/*
7115 		 * QIC-120, QIC-150, QIC-320, QIC-600
7116 		 */
7117 		sizestr = cart;
7118 		un->un_dp->type = ST_TYPE_DEFAULT;
7119 		un->un_dp->options |= ST_QIC;
7120 		un->un_dp->densities[0] = 0x0f;
7121 		un->un_dp->densities[1] = 0x10;
7122 		un->un_dp->densities[2] = 0x11;
7123 		un->un_dp->densities[3] = 0x12;
7124 		break;
7125 
7126 	case 0x09:
7127 	case 0x0a:
7128 	case 0x0c:
7129 	case 0x0d:
7130 		/*
7131 		 * 1/2" cartridge tapes. Include HI-TC.
7132 		 */
7133 		sizestr = cart;
7134 		sizestr[2] = '5';
7135 		sizestr[3] = '0';
7136 		un->un_dp->type = ST_TYPE_HIC;
7137 		un->un_dp->densities[0] = 0x09;
7138 		un->un_dp->densities[1] = 0x0a;
7139 		un->un_dp->densities[2] = 0x0c;
7140 		un->un_dp->densities[3] = 0x0d;
7141 		break;
7142 
7143 	case 0x13:
7144 			/* DDS-2/DDS-3 scsi spec densities */
7145 	case 0x24:
7146 	case 0x25:
7147 	case 0x26:
7148 		sizestr = "DAT Data Storage (DDS)";
7149 		un->un_dp->type = ST_TYPE_DAT;
7150 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7151 		break;
7152 
7153 	case 0x14:
7154 		/*
7155 		 * Helical Scan (Exabyte) devices
7156 		 */
7157 		sizestr = "8mm helical scan cartridge";
7158 		un->un_dp->type = ST_TYPE_EXABYTE;
7159 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7160 		break;
7161 	}
7162 
7163 	/*
7164 	 * Assume LONG ERASE, BSF and BSR
7165 	 */
7166 
7167 	un->un_dp->options |=
7168 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
7169 
7170 	/*
7171 	 * Only if mode sense data says no buffered write, set NOBUF
7172 	 */
7173 	if (un->un_mspl->bufm == 0)
7174 		un->un_dp->options |= ST_NOBUF;
7175 
7176 	/*
7177 	 * set up large read and write retry counts
7178 	 */
7179 
7180 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
7181 
7182 	/*
7183 	 * If this is a 0.50 inch reel tape, and
7184 	 * it is *not* variable mode, try and
7185 	 * set it to variable record length
7186 	 * mode.
7187 	 */
7188 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
7189 	    (un->un_dp->options & ST_VARIABLE)) {
7190 		if (st_change_block_size(un, 0) == 0) {
7191 			un->un_dp->bsize = 0;
7192 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
7193 			    un->un_mspl->low_bl = 0;
7194 		}
7195 	}
7196 
7197 	/*
7198 	 * Write to console about type of device found
7199 	 */
7200 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
7201 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
7202 	    sizestr);
7203 	if (un->un_dp->options & ST_VARIABLE) {
7204 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7205 		    "!Variable record length I/O\n");
7206 	} else {
7207 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7208 		    "!Fixed record length (%d byte blocks) I/O\n",
7209 		    un->un_dp->bsize);
7210 	}
7211 	ASSERT(mutex_owned(ST_MUTEX));
7212 	return (0);
7213 }
7214 
7215 static int
7216 st_determine_density(struct scsi_tape *un, int rw)
7217 {
7218 	int rval = 0;
7219 
7220 	ST_FUNC(ST_DEVINFO, st_determine_density);
7221 
7222 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7223 	    "st_determine_density(un = 0x%p, rw = %s)\n",
7224 	    (void*)un, (rw == B_WRITE ? wr_str: rd_str));
7225 
7226 	ASSERT(mutex_owned(ST_MUTEX));
7227 
7228 	/*
7229 	 * If we're past BOT, density is determined already.
7230 	 */
7231 	if (un->un_pos.pmode == logical) {
7232 		if (un->un_pos.lgclblkno != 0) {
7233 			goto exit;
7234 		}
7235 	} else if (un->un_pos.pmode == legacy) {
7236 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
7237 			/*
7238 			 * XXX: put in a bitch message about attempting to
7239 			 * XXX: change density past BOT.
7240 			 */
7241 			goto exit;
7242 		}
7243 	} else {
7244 		goto exit;
7245 	}
7246 	if ((un->un_pos.pmode == logical) &&
7247 	    (un->un_pos.lgclblkno != 0)) {
7248 		goto exit;
7249 	}
7250 
7251 
7252 	/*
7253 	 * If we're going to be writing, we set the density
7254 	 */
7255 	if (rw == 0 || rw == B_WRITE) {
7256 		/* un_curdens is used as an index into densities table */
7257 		un->un_curdens = MT_DENSITY(un->un_dev);
7258 		if (st_set_density(un)) {
7259 			rval = -1;
7260 		}
7261 		goto exit;
7262 	}
7263 
7264 	/*
7265 	 * If density is known already,
7266 	 * we don't have to get it again.(?)
7267 	 */
7268 	if (!un->un_density_known) {
7269 		if (st_get_density(un)) {
7270 			rval = -1;
7271 		}
7272 	}
7273 
7274 exit:
7275 	ASSERT(mutex_owned(ST_MUTEX));
7276 	return (rval);
7277 }
7278 
7279 
7280 /*
7281  * Try to determine density. We do this by attempting to read the
7282  * first record off the tape, cycling through the available density
7283  * codes as we go.
7284  */
7285 
7286 static int
7287 st_get_density(struct scsi_tape *un)
7288 {
7289 	int succes = 0, rval = -1, i;
7290 	uint_t size;
7291 	uchar_t dens, olddens;
7292 
7293 	ST_FUNC(ST_DEVINFO, st_get_density);
7294 
7295 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7296 	    "st_get_density(un = 0x%p)\n", (void*)un);
7297 
7298 	ASSERT(mutex_owned(ST_MUTEX));
7299 
7300 	/*
7301 	 * If Auto Density override is enabled The drive has
7302 	 * only one density and there is no point in attempting
7303 	 * find the correct one.
7304 	 *
7305 	 * Since most modern drives auto detect the density
7306 	 * and format of the recorded media before they come
7307 	 * ready. What this function does is a legacy behavior
7308 	 * and modern drives not only don't need it, The backup
7309 	 * utilities that do positioning via uscsi find the un-
7310 	 * expected rewinds problematic.
7311 	 *
7312 	 * The drives that need this are old reel to reel devices.
7313 	 * I took a swag and said they must be scsi-1 or older.
7314 	 * I don't beleave there will any of the newer devices
7315 	 * that need this. There will be some scsi-1 devices that
7316 	 * don't need this but I don't think they will be using the
7317 	 * BIG aftermarket backup and restore utilitys.
7318 	 */
7319 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
7320 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
7321 		un->un_density_known = 1;
7322 		rval = 0;
7323 		goto exit;
7324 	}
7325 
7326 	/*
7327 	 * This will only work on variable record length tapes
7328 	 * if and only if all variable record length tapes autodensity
7329 	 * select.
7330 	 */
7331 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
7332 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
7333 
7334 	/*
7335 	 * Start at the specified density
7336 	 */
7337 
7338 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
7339 
7340 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
7341 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
7342 		/*
7343 		 * If we've done this density before,
7344 		 * don't bother to do it again.
7345 		 */
7346 		dens = un->un_dp->densities[un->un_curdens];
7347 		if (i > 0 && dens == olddens)
7348 			continue;
7349 		olddens = dens;
7350 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7351 		    "trying density 0x%x\n", dens);
7352 		if (st_set_density(un)) {
7353 			continue;
7354 		}
7355 
7356 		/*
7357 		 * XXX - the creates lots of headaches and slowdowns - must
7358 		 * fix.
7359 		 */
7360 		succes = (st_cmd(un, SCMD_READ, (int)size, SYNC_CMD) == 0);
7361 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
7362 			break;
7363 		}
7364 		if (succes) {
7365 			st_init(un);
7366 			rval = 0;
7367 			un->un_density_known = 1;
7368 			break;
7369 		}
7370 	}
7371 	kmem_free(un->un_tmpbuf, size);
7372 	un->un_tmpbuf = 0;
7373 
7374 exit:
7375 	ASSERT(mutex_owned(ST_MUTEX));
7376 	return (rval);
7377 }
7378 
7379 static int
7380 st_set_density(struct scsi_tape *un)
7381 {
7382 	int rval = 0;
7383 
7384 	ST_FUNC(ST_DEVINFO, st_set_density);
7385 
7386 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7387 	    "st_set_density(un = 0x%p): density = 0x%x\n", (void*)un,
7388 	    un->un_dp->densities[un->un_curdens]);
7389 
7390 	ASSERT(mutex_owned(ST_MUTEX));
7391 
7392 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7393 
7394 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
7395 		/*
7396 		 * If auto density override is not set, Use mode select
7397 		 * to set density and compression.
7398 		 */
7399 		if (st_modeselect(un)) {
7400 			rval = -1;
7401 		}
7402 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
7403 		/*
7404 		 * If auto density and mode select compression are set,
7405 		 * This is a drive with one density code but compression
7406 		 * can be enabled or disabled.
7407 		 * Set compression but no need to set density.
7408 		 */
7409 		rval = st_set_compression(un);
7410 		if ((rval != 0) && (rval != EALREADY)) {
7411 			rval = -1;
7412 		} else {
7413 			rval = 0;
7414 		}
7415 	}
7416 
7417 	/* If sucessful set density and/or compression, mark density known */
7418 	if (rval == 0) {
7419 		un->un_density_known = 1;
7420 	}
7421 
7422 	ASSERT(mutex_owned(ST_MUTEX));
7423 	return (rval);
7424 }
7425 
7426 static int
7427 st_loadtape(struct scsi_tape *un)
7428 {
7429 	int rval;
7430 
7431 	ST_FUNC(ST_DEVINFO, st_loadtape);
7432 
7433 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7434 	    "st_loadtape(un = 0x%p)\n", (void*) un);
7435 
7436 	ASSERT(mutex_owned(ST_MUTEX));
7437 
7438 	rval = st_update_block_pos(un, st_cmd, 0);
7439 	if (rval == EACCES) {
7440 		return (rval);
7441 	}
7442 
7443 	/*
7444 	 * 'LOAD' the tape to BOT by rewinding
7445 	 */
7446 	rval = st_cmd(un, SCMD_REWIND, 1, SYNC_CMD);
7447 	if (rval == 0) {
7448 		st_init(un);
7449 		un->un_density_known = 0;
7450 	}
7451 
7452 	ASSERT(mutex_owned(ST_MUTEX));
7453 	return (rval);
7454 }
7455 
7456 
7457 /*
7458  * Note: QIC devices aren't so smart.  If you try to append
7459  * after EOM, the write can fail because the device doesn't know
7460  * it's at EOM.	 In that case, issue a read.  The read should fail
7461  * because there's no data, but the device knows it's at EOM,
7462  * so a subsequent write should succeed.  To further confuse matters,
7463  * the target returns the same error if the tape is positioned
7464  * such that a write would overwrite existing data.  That's why
7465  * we have to do the append test.  A read in the middle of
7466  * recorded data would succeed, thus indicating we're attempting
7467  * something illegal.
7468  */
7469 
7470 
7471 static void
7472 st_test_append(struct buf *bp)
7473 {
7474 	dev_t dev = bp->b_edev;
7475 	struct scsi_tape *un;
7476 	uchar_t status;
7477 	unsigned bcount;
7478 
7479 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7480 
7481 	ST_FUNC(ST_DEVINFO, st_test_append);
7482 
7483 	ASSERT(mutex_owned(ST_MUTEX));
7484 
7485 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7486 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7487 
7488 	un->un_laststate = un->un_state;
7489 	un->un_state = ST_STATE_APPEND_TESTING;
7490 	un->un_test_append = 0;
7491 
7492 	/*
7493 	 * first, map in the buffer, because we're doing a double write --
7494 	 * first into the kernel, then onto the tape.
7495 	 */
7496 	bp_mapin(bp);
7497 
7498 	/*
7499 	 * get a copy of the data....
7500 	 */
7501 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7502 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7503 
7504 	/*
7505 	 * attempt the write..
7506 	 */
7507 
7508 	if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7509 success:
7510 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7511 		    "append write succeeded\n");
7512 		bp->b_resid = un->un_sbufp->b_resid;
7513 		mutex_exit(ST_MUTEX);
7514 		bcount = (unsigned)bp->b_bcount;
7515 		biodone(bp);
7516 		mutex_enter(ST_MUTEX);
7517 		un->un_laststate = un->un_state;
7518 		un->un_state = ST_STATE_OPEN;
7519 		kmem_free(un->un_tmpbuf, bcount);
7520 		un->un_tmpbuf = NULL;
7521 		return;
7522 	}
7523 
7524 	/*
7525 	 * The append failed. Do a short read. If that fails,  we are at EOM
7526 	 * so we can retry the write command. If that succeeds, than we're
7527 	 * all screwed up (the controller reported a real error).
7528 	 *
7529 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7530 	 * XXX: block size?
7531 	 *
7532 	 */
7533 	status = un->un_status;
7534 	un->un_status = 0;
7535 	(void) st_cmd(un, SCMD_READ, SECSIZE, SYNC_CMD);
7536 	if (un->un_status == KEY_BLANK_CHECK) {
7537 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7538 		    "append at EOM\n");
7539 		/*
7540 		 * Okay- the read failed. We should actually have confused
7541 		 * the controller enough to allow writing. In any case, the
7542 		 * i/o is on its own from here on out.
7543 		 */
7544 		un->un_laststate = un->un_state;
7545 		un->un_state = ST_STATE_OPEN;
7546 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7547 		if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount,
7548 		    SYNC_CMD) == 0) {
7549 			goto success;
7550 		}
7551 	}
7552 
7553 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7554 	    "append write failed- not at EOM\n");
7555 	bp->b_resid = bp->b_bcount;
7556 	st_bioerror(bp, EIO);
7557 
7558 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7559 	    "st_test_append : EIO : append write failed - not at EOM");
7560 
7561 	/*
7562 	 * backspace one record to get back to where we were
7563 	 */
7564 	if (st_cmd(un, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7565 		un->un_pos.pmode = invalid;
7566 	}
7567 
7568 	un->un_err_resid = bp->b_resid;
7569 	un->un_status = status;
7570 
7571 	/*
7572 	 * Note: biodone will do a bp_mapout()
7573 	 */
7574 	mutex_exit(ST_MUTEX);
7575 	bcount = (unsigned)bp->b_bcount;
7576 	biodone(bp);
7577 	mutex_enter(ST_MUTEX);
7578 	un->un_laststate = un->un_state;
7579 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7580 	kmem_free(un->un_tmpbuf, bcount);
7581 	un->un_tmpbuf = NULL;
7582 }
7583 
7584 /*
7585  * Special command handler
7586  */
7587 
7588 /*
7589  * common st_cmd code. The fourth parameter states
7590  * whether the caller wishes to await the results
7591  * Note the release of the mutex during most of the function
7592  */
7593 static int
7594 st_cmd(struct scsi_tape *un, int com, int64_t count, int wait)
7595 {
7596 	struct buf *bp;
7597 	int err;
7598 	uint_t last_err_resid;
7599 
7600 	ST_FUNC(ST_DEVINFO, st_cmd);
7601 
7602 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7603 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %"PRIx64", wait = %d)\n",
7604 	    un->un_dev, com, count, wait);
7605 
7606 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7607 	ASSERT(mutex_owned(ST_MUTEX));
7608 
7609 #ifdef STDEBUG
7610 	if ((st_debug & 0x7)) {
7611 		st_debug_cmds(un, com, count, wait);
7612 	}
7613 #endif
7614 
7615 	st_wait_for_io(un);
7616 
7617 	/* check to see if this command requires the drive to be reserved */
7618 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7619 
7620 	if (err) {
7621 		return (err);
7622 	}
7623 
7624 	/*
7625 	 * A space command is not recoverable if we don't know were we
7626 	 * were when it was issued.
7627 	 */
7628 	if ((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) {
7629 		(void) st_update_block_pos(un, st_cmd, 0);
7630 	}
7631 
7632 	/*
7633 	 * Forground should not be doing anything while recovery is active.
7634 	 */
7635 	ASSERT(un->un_recov_buf_busy == 0);
7636 
7637 	while (un->un_sbuf_busy)
7638 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7639 	un->un_sbuf_busy = 1;
7640 
7641 	bp = un->un_sbufp;
7642 	bzero(bp, sizeof (buf_t));
7643 
7644 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7645 
7646 	err = st_setup_cmd(un, bp, com, count);
7647 
7648 	un->un_sbuf_busy = 0;
7649 
7650 	/*
7651 	 * If was a space command need to update logical block position.
7652 	 * Only do this if the command was sucessful or it will mask the fact
7653 	 * that the space command failed by promoting the pmode to logical.
7654 	 */
7655 	if (((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) &&
7656 	    (un->un_pos.pmode != invalid)) {
7657 		un->un_running.pmode = invalid;
7658 		last_err_resid = un->un_err_resid;
7659 		(void) st_update_block_pos(un, st_cmd, 1);
7660 		/*
7661 		 * Set running position to invalid so it updates on the
7662 		 * next command.
7663 		 */
7664 		un->un_running.pmode = invalid;
7665 		un->un_err_resid = last_err_resid;
7666 	}
7667 
7668 	cv_signal(&un->un_sbuf_cv);
7669 
7670 	return (err);
7671 }
7672 
7673 static int
7674 st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com, int64_t count)
7675 {
7676 	int err;
7677 	dev_t dev = un->un_dev;
7678 
7679 	ST_FUNC(ST_DEVINFO, st_setup_cmd);
7680 	/*
7681 	 * Set count to the actual size of the data tranfer.
7682 	 * For commands with no data transfer, set bp->b_bcount
7683 	 * to the value to be used when constructing the
7684 	 * cdb in st_make_cmd().
7685 	 */
7686 	switch (com) {
7687 	case SCMD_READ:
7688 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7689 		    "special read %"PRId64"\n", count);
7690 		bp->b_flags |= B_READ;
7691 		bp->b_un.b_addr = un->un_tmpbuf;
7692 		break;
7693 
7694 	case SCMD_WRITE:
7695 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7696 		    "special write %"PRId64"\n", count);
7697 		bp->b_un.b_addr = un->un_tmpbuf;
7698 		break;
7699 
7700 	case SCMD_WRITE_FILE_MARK:
7701 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7702 		    "write %"PRId64" file marks\n", count);
7703 		bp->b_bcount = count;
7704 		count = 0;
7705 		break;
7706 
7707 	case SCMD_REWIND:
7708 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7709 		bp->b_bcount = count;
7710 		count = 0;
7711 		break;
7712 
7713 	case SCMD_SPACE:
7714 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7715 		/*
7716 		 * If the user could have entered a number that will
7717 		 * not fit in the 12 bit count field of space(8),
7718 		 * use space(16).
7719 		 */
7720 		if (((int64_t)SPACE_CNT(count) > 0x7fffff) ||
7721 		    ((int64_t)SPACE_CNT(count) < -(0x7fffff))) {
7722 			com = SCMD_SPACE_G4;
7723 		}
7724 		bp->b_bcount = count;
7725 		count = 0;
7726 		break;
7727 
7728 	case SCMD_RESERVE:
7729 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7730 		bp->b_bcount = 0;
7731 		count = 0;
7732 		break;
7733 
7734 	case SCMD_RELEASE:
7735 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7736 		bp->b_bcount = 0;
7737 		count = 0;
7738 		break;
7739 
7740 	case SCMD_LOAD:
7741 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7742 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7743 		bp->b_bcount = count;
7744 		count = 0;
7745 		break;
7746 
7747 	case SCMD_ERASE:
7748 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7749 		    "erase tape\n");
7750 		bp->b_bcount = count;
7751 		count = 0;
7752 		break;
7753 
7754 	case SCMD_MODE_SENSE:
7755 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7756 		    "mode sense\n");
7757 		bp->b_flags |= B_READ;
7758 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7759 		break;
7760 
7761 	case SCMD_MODE_SELECT:
7762 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7763 		    "mode select\n");
7764 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7765 		break;
7766 
7767 	case SCMD_READ_BLKLIM:
7768 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7769 		    "read block limits\n");
7770 		bp->b_bcount = count;
7771 		bp->b_flags |= B_READ;
7772 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7773 		break;
7774 
7775 	case SCMD_TEST_UNIT_READY:
7776 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7777 		    "test unit ready\n");
7778 		bp->b_bcount = 0;
7779 		count = 0;
7780 		break;
7781 
7782 	case SCMD_DOORLOCK:
7783 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7784 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7785 		bp->b_bcount = count = 0;
7786 		break;
7787 
7788 	case SCMD_READ_POSITION:
7789 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7790 		    "read position\n");
7791 		switch (un->un_read_pos_type) {
7792 		case LONG_POS:
7793 			count = sizeof (tape_position_long_t);
7794 			break;
7795 		case EXT_POS:
7796 			count = min(count, sizeof (tape_position_ext_t));
7797 			break;
7798 		case SHORT_POS:
7799 			count = sizeof (tape_position_t);
7800 			break;
7801 		default:
7802 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7803 			    "Unknown read position type 0x%x in "
7804 			    "st_make_cmd()\n", un->un_read_pos_type);
7805 		}
7806 		bp->b_bcount = count;
7807 		bp->b_flags |= B_READ;
7808 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7809 		break;
7810 
7811 	default:
7812 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7813 		    "Unhandled scsi command 0x%x in st_setup_cmd()\n", com);
7814 	}
7815 
7816 	mutex_exit(ST_MUTEX);
7817 
7818 	if (count > 0) {
7819 		int flg = (bp->b_flags & B_READ) ? B_READ : B_WRITE;
7820 		/*
7821 		 * We're going to do actual I/O.
7822 		 * Set things up for physio.
7823 		 */
7824 		struct iovec aiov;
7825 		struct uio auio;
7826 		struct uio *uio = &auio;
7827 
7828 		bzero(&auio, sizeof (struct uio));
7829 		bzero(&aiov, sizeof (struct iovec));
7830 		aiov.iov_base = bp->b_un.b_addr;
7831 		aiov.iov_len = count;
7832 
7833 		uio->uio_iov = &aiov;
7834 		uio->uio_iovcnt = 1;
7835 		uio->uio_resid = aiov.iov_len;
7836 		uio->uio_segflg = UIO_SYSSPACE;
7837 
7838 		/*
7839 		 * Let physio do the rest...
7840 		 */
7841 		bp->b_forw = (struct buf *)(uintptr_t)com;
7842 		bp->b_back = NULL;
7843 		err = physio(st_strategy, bp, dev, flg, st_minphys, uio);
7844 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7845 		    "st_setup_cmd: physio returns %d\n", err);
7846 	} else {
7847 		/*
7848 		 * Mimic physio
7849 		 */
7850 		bp->b_forw = (struct buf *)(uintptr_t)com;
7851 		bp->b_back = NULL;
7852 		bp->b_edev = dev;
7853 		bp->b_dev = cmpdev(dev);
7854 		bp->b_blkno = 0;
7855 		bp->b_resid = 0;
7856 		(void) st_strategy(bp);
7857 		if (bp->b_flags & B_ASYNC) {
7858 			/*
7859 			 * This is an async command- the caller won't wait
7860 			 * and doesn't care about errors.
7861 			 */
7862 			mutex_enter(ST_MUTEX);
7863 			return (0);
7864 		}
7865 
7866 		/*
7867 		 * BugTraq #4260046
7868 		 * ----------------
7869 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7870 		 * unconditionally. The old comment said...
7871 		 *
7872 		 * "if strategy was flagged with  persistent errors, we would
7873 		 *  have an error here, and the bp would never be sent, so we
7874 		 *  don't want to wait on a bp that was never sent...or hang"
7875 		 *
7876 		 * The new rationale, courtesy of Chitrank...
7877 		 *
7878 		 * "we should unconditionally biowait() here because
7879 		 *  st_strategy() will do a biodone() in the persistent error
7880 		 *  case and the following biowait() will return immediately.
7881 		 *  If not, in the case of "errors after pkt alloc" in
7882 		 *  st_start(), we will not biowait here which will cause the
7883 		 *  next biowait() to return immediately which will cause
7884 		 *  us to send out the next command. In the case where both of
7885 		 *  these use the sbuf, when the first command completes we'll
7886 		 *  free the packet attached to sbuf and the same pkt will
7887 		 *  get freed again when we complete the second command.
7888 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7889 		 *  st_start() for the pkt alloc failure case because physio()
7890 		 *  does biowait() and will hang if we don't do biodone()"
7891 		 */
7892 
7893 		err = biowait(bp);
7894 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7895 		    "st_setup_cmd: biowait returns %d\n", err);
7896 	}
7897 
7898 	mutex_enter(ST_MUTEX);
7899 
7900 	return (err);
7901 }
7902 
7903 static int
7904 st_set_compression(struct scsi_tape *un)
7905 {
7906 	int rval;
7907 	int turn_compression_on;
7908 	minor_t minor;
7909 
7910 	ST_FUNC(ST_DEVINFO, st_set_compression);
7911 
7912 	/*
7913 	 * Drive either dosn't have compression or it is controlled with
7914 	 * special density codes. Return ENOTTY so caller
7915 	 * knows nothing was done.
7916 	 */
7917 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7918 		un->un_comp_page = 0;
7919 		return (ENOTTY);
7920 	}
7921 
7922 	/* set compression based on minor node opened */
7923 	minor = MT_DENSITY(un->un_dev);
7924 
7925 	/*
7926 	 * If this the compression density or
7927 	 * the drive has two densities and uses mode select for
7928 	 * control of compression turn on compression for MT_DENSITY2
7929 	 * as well.
7930 	 */
7931 	if ((minor == ST_COMPRESSION_DENSITY) ||
7932 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7933 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7934 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7935 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7936 
7937 		turn_compression_on = 1;
7938 	} else {
7939 		turn_compression_on = 0;
7940 	}
7941 
7942 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7943 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7944 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7945 
7946 	/*
7947 	 * Need to determine which page does the device use for compression.
7948 	 * First try the data compression page. If this fails try the device
7949 	 * configuration page
7950 	 */
7951 
7952 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7953 		rval = st_set_datacomp_page(un, turn_compression_on);
7954 		if (rval == EALREADY) {
7955 			return (rval);
7956 		}
7957 		if (rval != 0) {
7958 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7959 				/*
7960 				 * This device does not support data
7961 				 * compression page
7962 				 */
7963 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7964 			} else if (un->un_state >= ST_STATE_OPEN) {
7965 				un->un_pos.pmode = invalid;
7966 				rval = EIO;
7967 			} else {
7968 				rval = -1;
7969 			}
7970 		} else {
7971 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7972 		}
7973 	}
7974 
7975 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7976 		rval = st_set_devconfig_page(un, turn_compression_on);
7977 		if (rval == EALREADY) {
7978 			return (rval);
7979 		}
7980 		if (rval != 0) {
7981 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7982 				/*
7983 				 * This device does not support
7984 				 * compression at all advice the
7985 				 * user and unset ST_MODE_SEL_COMP
7986 				 */
7987 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7988 				un->un_comp_page = 0;
7989 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7990 				    "Device Does Not Support Compression\n");
7991 			} else if (un->un_state >= ST_STATE_OPEN) {
7992 				un->un_pos.pmode = invalid;
7993 				rval = EIO;
7994 			} else {
7995 				rval = -1;
7996 			}
7997 		}
7998 	}
7999 
8000 	return (rval);
8001 }
8002 
8003 /*
8004  * set or unset compression thru device configuration page.
8005  */
8006 static int
8007 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
8008 {
8009 	unsigned char cflag;
8010 	int rval = 0;
8011 
8012 
8013 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
8014 
8015 	ASSERT(mutex_owned(ST_MUTEX));
8016 
8017 	/*
8018 	 * if the mode sense page is not the correct one, load the correct one.
8019 	 */
8020 	if (un->un_mspl->page_code != ST_DEV_CONFIG_PAGE) {
8021 		rval = st_gen_mode_sense(un, st_uscsi_cmd, ST_DEV_CONFIG_PAGE,
8022 		    un->un_mspl, sizeof (struct seq_mode));
8023 		if (rval)
8024 			return (rval);
8025 	}
8026 
8027 	/*
8028 	 * Figure what to set compression flag to.
8029 	 */
8030 	if (compression_on) {
8031 		/* They have selected a compression node */
8032 		if (un->un_dp->type == ST_TYPE_FUJI) {
8033 			cflag = 0x84;   /* use EDRC */
8034 		} else {
8035 			cflag = ST_DEV_CONFIG_DEF_COMP;
8036 		}
8037 	} else {
8038 		cflag = ST_DEV_CONFIG_NO_COMP;
8039 	}
8040 
8041 	/*
8042 	 * If compression is already set the way it was requested.
8043 	 * And if this not the first time we has tried.
8044 	 */
8045 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
8046 	    (un->un_comp_page == ST_DEV_CONFIG_PAGE)) {
8047 		return (EALREADY);
8048 	}
8049 
8050 	un->un_mspl->page.dev.comp_alg = cflag;
8051 	/*
8052 	 * need to send mode select even if correct compression is
8053 	 * already set since need to set density code
8054 	 */
8055 
8056 #ifdef STDEBUG
8057 	if ((st_debug & 0x7) >= 6) {
8058 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8059 		    "st_set_devconfig_page: sense data for mode select",
8060 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8061 	}
8062 #endif
8063 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8064 	    sizeof (struct seq_mode));
8065 
8066 	return (rval);
8067 }
8068 
8069 /*
8070  * set/reset compression bit thru data compression page
8071  */
8072 static int
8073 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
8074 {
8075 	int compression_on_already;
8076 	int rval = 0;
8077 
8078 
8079 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
8080 
8081 	ASSERT(mutex_owned(ST_MUTEX));
8082 
8083 	/*
8084 	 * if the mode sense page is not the correct one, load the correct one.
8085 	 */
8086 	if (un->un_mspl->page_code != ST_DEV_DATACOMP_PAGE) {
8087 		rval = st_gen_mode_sense(un, st_uscsi_cmd, ST_DEV_DATACOMP_PAGE,
8088 		    un->un_mspl, sizeof (struct seq_mode));
8089 		if (rval)
8090 			return (rval);
8091 	}
8092 
8093 	/*
8094 	 * If drive is not capable of compression (at this time)
8095 	 * return EALREADY so caller doesn't think that this page
8096 	 * is not supported. This check is for drives that can
8097 	 * disable compression from the front panel or configuration.
8098 	 * I doubt that a drive that supports this page is not really
8099 	 * capable of compression.
8100 	 */
8101 	if (un->un_mspl->page.comp.dcc == 0) {
8102 		return (EALREADY);
8103 	}
8104 
8105 	/* See if compression currently turned on */
8106 	if (un->un_mspl->page.comp.dce) {
8107 		compression_on_already = 1;
8108 	} else {
8109 		compression_on_already = 0;
8110 	}
8111 
8112 	/*
8113 	 * If compression is already set the way it was requested.
8114 	 * And if this not the first time we has tried.
8115 	 */
8116 	if ((compression_on == compression_on_already) &&
8117 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
8118 		return (EALREADY);
8119 	}
8120 
8121 	/*
8122 	 * if we are already set to the appropriate compression
8123 	 * mode, don't set it again
8124 	 */
8125 	if (compression_on) {
8126 		/* compression selected */
8127 		un->un_mspl->page.comp.dce = 1;
8128 	} else {
8129 		un->un_mspl->page.comp.dce = 0;
8130 	}
8131 
8132 
8133 #ifdef STDEBUG
8134 	if ((st_debug & 0x7) >= 6) {
8135 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8136 		    "st_set_datacomp_page: sense data for mode select",
8137 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8138 	}
8139 #endif
8140 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8141 	    sizeof (struct seq_mode));
8142 
8143 	return (rval);
8144 }
8145 
8146 static int
8147 st_modesense(struct scsi_tape *un)
8148 {
8149 	int rval;
8150 	uchar_t page;
8151 
8152 	ST_FUNC(ST_DEVINFO, st_modesense);
8153 
8154 	page = un->un_comp_page;
8155 
8156 	switch (page) {
8157 	case ST_DEV_DATACOMP_PAGE:
8158 	case ST_DEV_CONFIG_PAGE: /* FALLTHROUGH */
8159 		rval = st_gen_mode_sense(un, st_uscsi_cmd, page, un->un_mspl,
8160 		    sizeof (struct seq_mode));
8161 		break;
8162 
8163 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
8164 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
8165 			page = ST_DEV_DATACOMP_PAGE;
8166 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8167 			    un->un_mspl, sizeof (struct seq_mode));
8168 			if (rval == 0 && un->un_mspl->page_code == page) {
8169 				un->un_comp_page = page;
8170 				break;
8171 			}
8172 			page = ST_DEV_CONFIG_PAGE;
8173 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8174 			    un->un_mspl, sizeof (struct seq_mode));
8175 			if (rval == 0 && un->un_mspl->page_code == page) {
8176 				un->un_comp_page = page;
8177 				break;
8178 			}
8179 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
8180 			un->un_comp_page = 0;
8181 		} else {
8182 			un->un_comp_page = 0;
8183 		}
8184 		/* FALLTHROUGH */
8185 
8186 	default:
8187 		rval = st_cmd(un, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
8188 	}
8189 	return (rval);
8190 }
8191 
8192 static int
8193 st_modeselect(struct scsi_tape *un)
8194 {
8195 	int rval = 0;
8196 	int ix;
8197 
8198 	ST_FUNC(ST_DEVINFO, st_modeselect);
8199 
8200 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8201 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
8202 	    un->un_dev, un->un_mspl->density);
8203 
8204 	ASSERT(mutex_owned(ST_MUTEX));
8205 
8206 	/*
8207 	 * The parameter list should be the same for all of the
8208 	 * cases that follow so set them here
8209 	 *
8210 	 * Try mode select first if if fails set fields manually
8211 	 */
8212 	rval = st_modesense(un);
8213 	if (rval != 0) {
8214 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8215 		    "st_modeselect: First mode sense failed\n");
8216 		un->un_mspl->bd_len  = 8;
8217 		un->un_mspl->high_nb = 0;
8218 		un->un_mspl->mid_nb  = 0;
8219 		un->un_mspl->low_nb  = 0;
8220 	}
8221 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
8222 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
8223 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
8224 
8225 
8226 	/*
8227 	 * If configured to use a specific density code for a media type.
8228 	 * curdens is previously set by the minor node opened.
8229 	 * If the media type doesn't match the minor node we change it so it
8230 	 * looks like the correct one was opened.
8231 	 */
8232 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
8233 		uchar_t best;
8234 
8235 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
8236 			if (un->un_mspl->media_type ==
8237 			    un->un_dp->mediatype[ix]) {
8238 				best = ix;
8239 				/*
8240 				 * It matches but it might not be the only one.
8241 				 * Use the highest matching media type but not
8242 				 * to exceed the density selected by the open.
8243 				 */
8244 				if (ix < un->un_curdens) {
8245 					continue;
8246 				}
8247 				un->un_curdens = ix;
8248 				break;
8249 			}
8250 		}
8251 		/* If a match was found best will not be 0xff any more */
8252 		if (best < NDENSITIES) {
8253 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8254 			    "found media 0x%X using density 0x%X\n",
8255 			    un->un_mspl->media_type,
8256 			    un->un_dp->densities[best]);
8257 			un->un_mspl->density = un->un_dp->densities[best];
8258 		} else {
8259 			/* Otherwise set density based on minor node opened */
8260 			un->un_mspl->density =
8261 			    un->un_dp->densities[un->un_curdens];
8262 		}
8263 	} else {
8264 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
8265 	}
8266 
8267 	if (un->un_dp->options & ST_NOBUF) {
8268 		un->un_mspl->bufm = 0;
8269 	} else {
8270 		un->un_mspl->bufm = 1;
8271 	}
8272 
8273 	rval = st_set_compression(un);
8274 
8275 	/*
8276 	 * If st_set_compression returned invalid or already it
8277 	 * found no need to do the mode select.
8278 	 * So do it here.
8279 	 */
8280 	if ((rval == ENOTTY) || (rval == EALREADY)) {
8281 
8282 		/* Zero non-writeable fields */
8283 		un->un_mspl->data_len = 0;
8284 		un->un_mspl->media_type = 0;
8285 		un->un_mspl->wp = 0;
8286 
8287 		/* need to set the density code */
8288 		rval = st_cmd(un, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
8289 		if (rval != 0) {
8290 			if (un->un_state >= ST_STATE_OPEN) {
8291 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8292 				    "unable to set tape mode\n");
8293 				un->un_pos.pmode = invalid;
8294 				rval = EIO;
8295 			} else {
8296 				rval = -1;
8297 			}
8298 		}
8299 	}
8300 
8301 	/*
8302 	 * The spec recommends to send a mode sense after a mode select
8303 	 */
8304 	(void) st_modesense(un);
8305 
8306 	ASSERT(mutex_owned(ST_MUTEX));
8307 
8308 	return (rval);
8309 }
8310 
8311 /*
8312  * st_gen_mode_sense
8313  *
8314  * generic mode sense.. it allows for any page
8315  */
8316 static int
8317 st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
8318     struct seq_mode *page_data, int page_size)
8319 {
8320 
8321 	int r;
8322 	char	cdb[CDB_GROUP0];
8323 	struct uscsi_cmd *com;
8324 	struct scsi_arq_status status;
8325 
8326 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
8327 
8328 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8329 
8330 	bzero(cdb, CDB_GROUP0);
8331 	cdb[0] = SCMD_MODE_SENSE;
8332 	cdb[2] = (char)page;
8333 	cdb[4] = (char)page_size;
8334 
8335 	com->uscsi_cdb = cdb;
8336 	com->uscsi_cdblen = CDB_GROUP0;
8337 	com->uscsi_bufaddr = (caddr_t)page_data;
8338 	com->uscsi_buflen = page_size;
8339 	com->uscsi_rqlen = sizeof (status);
8340 	com->uscsi_rqbuf = (caddr_t)&status;
8341 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8342 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8343 
8344 	r = ubf(un, com, FKIOCTL);
8345 	kmem_free(com, sizeof (*com));
8346 	return (r);
8347 }
8348 
8349 /*
8350  * st_gen_mode_select
8351  *
8352  * generic mode select.. it allows for any page
8353  */
8354 static int
8355 st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
8356     struct seq_mode *page_data, int page_size)
8357 {
8358 
8359 	int r;
8360 	char cdb[CDB_GROUP0];
8361 	struct uscsi_cmd *com;
8362 	struct scsi_arq_status status;
8363 
8364 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
8365 
8366 	/* Zero non-writeable fields */
8367 	page_data->data_len = 0;
8368 	page_data->media_type = 0;
8369 	page_data->wp = 0;
8370 
8371 	/*
8372 	 * If mode select has any page data, zero the ps (Page Savable) bit.
8373 	 */
8374 	if (page_size > MSIZE) {
8375 		page_data->ps = 0;
8376 	}
8377 
8378 
8379 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8380 
8381 	/*
8382 	 * then, do a mode select to set what ever info
8383 	 */
8384 	bzero(cdb, CDB_GROUP0);
8385 	cdb[0] = SCMD_MODE_SELECT;
8386 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
8387 	cdb[4] = (char)page_size;
8388 
8389 	com->uscsi_cdb = cdb;
8390 	com->uscsi_cdblen = CDB_GROUP0;
8391 	com->uscsi_bufaddr = (caddr_t)page_data;
8392 	com->uscsi_buflen = page_size;
8393 	com->uscsi_rqlen = sizeof (status);
8394 	com->uscsi_rqbuf = (caddr_t)&status;
8395 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8396 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_WRITE;
8397 
8398 	r = ubf(un, com, FKIOCTL);
8399 
8400 	kmem_free(com, sizeof (*com));
8401 	return (r);
8402 }
8403 
8404 static int
8405 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
8406 {
8407 	int rval;
8408 	char cdb[CDB_GROUP0];
8409 	struct uscsi_cmd *com;
8410 	struct scsi_arq_status status;
8411 
8412 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
8413 
8414 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8415 
8416 	bzero(cdb, CDB_GROUP0);
8417 	cdb[0] = SCMD_READ_BLKLIM;
8418 
8419 	com->uscsi_cdb = cdb;
8420 	com->uscsi_cdblen = CDB_GROUP0;
8421 	com->uscsi_bufaddr = (caddr_t)read_blk;
8422 	com->uscsi_buflen = sizeof (struct read_blklim);
8423 	com->uscsi_rqlen = sizeof (status);
8424 	com->uscsi_rqbuf = (caddr_t)&status;
8425 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8426 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8427 
8428 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8429 	if (com->uscsi_status || com->uscsi_resid) {
8430 		rval = -1;
8431 	}
8432 
8433 	kmem_free(com, sizeof (*com));
8434 	return (rval);
8435 }
8436 
8437 static int
8438 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
8439     size_t buflen)
8440 {
8441 	int rval;
8442 	char cdb[CDB_GROUP1];
8443 	struct uscsi_cmd *com;
8444 	struct scsi_arq_status status;
8445 
8446 	ST_FUNC(ST_DEVINFO, st_report_density_support);
8447 
8448 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8449 
8450 	bzero(cdb, CDB_GROUP1);
8451 	cdb[0] = SCMD_REPORT_DENSITIES;
8452 	cdb[7] = (buflen & 0xff00) >> 8;
8453 	cdb[8] = buflen & 0xff;
8454 
8455 	com->uscsi_cdb = cdb;
8456 	com->uscsi_cdblen = CDB_GROUP1;
8457 	com->uscsi_bufaddr = (caddr_t)density_data;
8458 	com->uscsi_buflen = buflen;
8459 	com->uscsi_rqlen = sizeof (status);
8460 	com->uscsi_rqbuf = (caddr_t)&status;
8461 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8462 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8463 
8464 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8465 	if (com->uscsi_status || com->uscsi_resid) {
8466 		rval = -1;
8467 	}
8468 
8469 	kmem_free(com, sizeof (*com));
8470 	return (rval);
8471 }
8472 
8473 static int
8474 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
8475     uchar_t option_code, ushort_t service_action)
8476 {
8477 	int rval;
8478 	char cdb[CDB_GROUP5];
8479 	struct uscsi_cmd *com;
8480 	struct scsi_arq_status status;
8481 	uint32_t allo_length;
8482 
8483 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
8484 
8485 	allo_length = sizeof (struct one_com_des) +
8486 	    sizeof (struct com_timeout_des);
8487 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8488 
8489 	bzero(cdb, CDB_GROUP5);
8490 	cdb[0] = (char)SCMD_MAINTENANCE_IN;
8491 	cdb[1] = SSVC_ACTION_GET_SUPPORTED_OPERATIONS;
8492 	if (service_action) {
8493 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
8494 		cdb[4] = (service_action & 0xff00) >> 8;
8495 		cdb[5] = service_action & 0xff;
8496 	} else {
8497 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
8498 		    0x80); /* RCTD */
8499 	}
8500 	cdb[3] = option_code;
8501 	cdb[6] = (allo_length & 0xff000000) >> 24;
8502 	cdb[7] = (allo_length & 0xff0000) >> 16;
8503 	cdb[8] = (allo_length & 0xff00) >> 8;
8504 	cdb[9] = allo_length & 0xff;
8505 
8506 	com->uscsi_cdb = cdb;
8507 	com->uscsi_cdblen = CDB_GROUP5;
8508 	com->uscsi_bufaddr = (caddr_t)oper_data;
8509 	com->uscsi_buflen = allo_length;
8510 	com->uscsi_rqlen = sizeof (status);
8511 	com->uscsi_rqbuf = (caddr_t)&status;
8512 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8513 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8514 
8515 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8516 	if (com->uscsi_status) {
8517 		rval = -1;
8518 	}
8519 
8520 	kmem_free(com, sizeof (*com));
8521 	return (rval);
8522 }
8523 
8524 /*
8525  * Changes devices blocksize and bsize to requested blocksize nblksz.
8526  * Returns returned value from first failed call or zero on success.
8527  */
8528 static int
8529 st_change_block_size(struct scsi_tape *un, uint32_t nblksz)
8530 {
8531 	struct seq_mode *current;
8532 	int rval;
8533 	uint32_t oldblksz;
8534 
8535 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8536 
8537 	current = kmem_zalloc(MSIZE, KM_SLEEP);
8538 
8539 	/*
8540 	 * If we haven't got the compression page yet, do that first.
8541 	 */
8542 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
8543 		(void) st_modesense(un);
8544 	}
8545 
8546 	/* Read current settings */
8547 	rval = st_gen_mode_sense(un, st_uscsi_cmd, 0, current, MSIZE);
8548 	if (rval != 0) {
8549 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8550 		    "mode sense for change block size failed: rval = %d", rval);
8551 		goto finish;
8552 	}
8553 
8554 	/* Figure the current block size */
8555 	oldblksz =
8556 	    (current->high_bl << 16) |
8557 	    (current->mid_bl << 8) |
8558 	    (current->low_bl);
8559 
8560 	/* If current block size is the same as requested were done */
8561 	if (oldblksz == nblksz) {
8562 		un->un_bsize = nblksz;
8563 		rval = 0;
8564 		goto finish;
8565 	}
8566 
8567 	/* Change to requested block size */
8568 	current->high_bl = (uchar_t)(nblksz >> 16);
8569 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8570 	current->low_bl  = (uchar_t)(nblksz);
8571 
8572 	/* Attempt to change block size */
8573 	rval = st_gen_mode_select(un, st_uscsi_cmd, current, MSIZE);
8574 	if (rval != 0) {
8575 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8576 		    "Set new block size failed: rval = %d", rval);
8577 		goto finish;
8578 	}
8579 
8580 	/* Read back and verify setting */
8581 	rval = st_modesense(un);
8582 	if (rval == 0) {
8583 		un->un_bsize =
8584 		    (un->un_mspl->high_bl << 16) |
8585 		    (un->un_mspl->mid_bl << 8) |
8586 		    (un->un_mspl->low_bl);
8587 
8588 		if (un->un_bsize != nblksz) {
8589 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8590 			    "Blocksize set does not equal requested blocksize"
8591 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8592 			rval = EIO;
8593 		}
8594 	}
8595 finish:
8596 	kmem_free(current, MSIZE);
8597 	return (rval);
8598 }
8599 
8600 
8601 static void
8602 st_init(struct scsi_tape *un)
8603 {
8604 	ST_FUNC(ST_DEVINFO, st_init);
8605 
8606 	ASSERT(mutex_owned(ST_MUTEX));
8607 
8608 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8609 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8610 	    un->un_dev);
8611 
8612 	un->un_pos.blkno = 0;
8613 	un->un_pos.fileno = 0;
8614 	un->un_lastop = ST_OP_NIL;
8615 	un->un_pos.eof = ST_NO_EOF;
8616 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8617 	if (st_error_level != SCSI_ERR_ALL) {
8618 		if (DEBUGGING) {
8619 			st_error_level = SCSI_ERR_ALL;
8620 		} else {
8621 			st_error_level = SCSI_ERR_RETRYABLE;
8622 		}
8623 	}
8624 }
8625 
8626 
8627 static void
8628 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8629 {
8630 	struct scsi_pkt *pkt;
8631 	struct uscsi_cmd *ucmd;
8632 	recov_info *ri;
8633 	int tval = 0;
8634 	int64_t count;
8635 	uint32_t additional = 0;
8636 	uint32_t address = 0;
8637 	union scsi_cdb *ucdb;
8638 	int flags = 0;
8639 	int cdb_len = CDB_GROUP0; /* default */
8640 	uchar_t com;
8641 	char fixbit;
8642 	char short_fm = 0;
8643 	optype prev_op = un->un_lastop;
8644 	int stat_size =
8645 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
8646 
8647 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8648 
8649 	ASSERT(mutex_owned(ST_MUTEX));
8650 
8651 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8652 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8653 
8654 
8655 	/*
8656 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8657 	 * Length Indicator bits on read/write commands, for setting
8658 	 * the Long bit on erase commands, and for setting the Code
8659 	 * Field bits on space commands.
8660 	 */
8661 
8662 	/* regular raw I/O */
8663 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
8664 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8665 		    CDB_GROUP0, stat_size, st_recov_sz, 0, func,
8666 		    (caddr_t)un);
8667 		if (pkt == NULL) {
8668 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8669 			    "Read Write scsi_init_pkt() failure\n");
8670 			goto exit;
8671 		}
8672 		ASSERT(pkt->pkt_resid == 0);
8673 #ifdef STDEBUG
8674 		bzero(pkt->pkt_private, st_recov_sz);
8675 		bzero(pkt->pkt_scbp, stat_size);
8676 #endif
8677 		ri = (recov_info *)pkt->pkt_private;
8678 		ri->privatelen = st_recov_sz;
8679 		if (un->un_bsize == 0) {
8680 			count = bp->b_bcount;
8681 			fixbit = 0;
8682 		} else {
8683 			count = bp->b_bcount / un->un_bsize;
8684 			fixbit = 1;
8685 		}
8686 		if (bp->b_flags & B_READ) {
8687 			com = SCMD_READ;
8688 			un->un_lastop = ST_OP_READ;
8689 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8690 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8691 				fixbit = 2;
8692 			}
8693 		} else {
8694 			com = SCMD_WRITE;
8695 			un->un_lastop = ST_OP_WRITE;
8696 		}
8697 		tval = un->un_dp->io_timeout;
8698 
8699 		/*
8700 		 * For really large xfers, increase timeout
8701 		 */
8702 		if (bp->b_bcount > (10 * ONE_MEG))
8703 			tval *= bp->b_bcount/(10 * ONE_MEG);
8704 
8705 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8706 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8707 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8708 
8709 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8710 		/*
8711 		 * uscsi - build command, allocate scsi resources
8712 		 */
8713 		st_make_uscsi_cmd(un, ucmd, bp, func);
8714 		goto exit;
8715 
8716 	} else {				/* special I/O */
8717 		struct buf *allocbp = NULL;
8718 		com = (uchar_t)(uintptr_t)bp->b_forw;
8719 		count = bp->b_bcount;
8720 
8721 		switch (com) {
8722 		case SCMD_READ:
8723 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8724 			    "special read %"PRId64"\n", count);
8725 			if (un->un_bsize == 0) {
8726 				fixbit = 2;	/* suppress SILI */
8727 			} else {
8728 				fixbit = 1;	/* Fixed Block Mode */
8729 				count /= un->un_bsize;
8730 			}
8731 			allocbp = bp;
8732 			un->un_lastop = ST_OP_READ;
8733 			tval = un->un_dp->io_timeout;
8734 			break;
8735 
8736 		case SCMD_WRITE:
8737 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8738 			    "special write %"PRId64"\n", count);
8739 			if (un->un_bsize != 0) {
8740 				fixbit = 1;	/* Fixed Block Mode */
8741 				count /= un->un_bsize;
8742 			} else {
8743 				fixbit = 0;
8744 			}
8745 			allocbp = bp;
8746 			un->un_lastop = ST_OP_WRITE;
8747 			tval = un->un_dp->io_timeout;
8748 			break;
8749 
8750 		case SCMD_WRITE_FILE_MARK:
8751 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8752 			    "write %"PRId64" file marks\n", count);
8753 			un->un_lastop = ST_OP_WEOF;
8754 			fixbit = 0;
8755 			tval = un->un_dp->io_timeout;
8756 			/*
8757 			 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8758 			 * device, set the Vendor Unique bit to
8759 			 * write Short File Mark.
8760 			 */
8761 			if ((un->un_dp->options & ST_SHORT_FILEMARKS) &&
8762 			    ((un->un_dp->type == ST_TYPE_EXB8500) ||
8763 			    (un->un_dp->type == ST_TYPE_EXABYTE))) {
8764 				/*
8765 				 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8766 				 * is set to to write Short File Mark
8767 				 */
8768 				short_fm = 1;
8769 			}
8770 			break;
8771 
8772 		case SCMD_REWIND:
8773 			/*
8774 			 * In the case of rewind we're gona do the rewind with
8775 			 * the immediate bit set so status will be retured when
8776 			 * the command is accepted by the device. We clear the
8777 			 * B_ASYNC flag so we wait for that acceptance.
8778 			 */
8779 			fixbit = 0;
8780 			if (bp->b_flags & B_ASYNC) {
8781 				allocbp = bp;
8782 				if (count) {
8783 					fixbit = 1;
8784 					bp->b_flags &= ~B_ASYNC;
8785 				}
8786 			}
8787 			count = 0;
8788 			bp->b_bcount = 0;
8789 			un->un_lastop = ST_OP_CTL;
8790 			tval = un->un_dp->rewind_timeout;
8791 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8792 			    "rewind\n");
8793 			break;
8794 
8795 		case SCMD_SPACE_G4:
8796 			cdb_len = CDB_GROUP4;
8797 			fixbit = SPACE_TYPE(bp->b_bcount);
8798 			count = SPACE_CNT(bp->b_bcount);
8799 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8800 			    " %s space %s %"PRId64" from file %d blk %d\n",
8801 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8802 			    space_strs[fixbit & 7], count,
8803 			    un->un_pos.fileno, un->un_pos.blkno);
8804 			address = (count >> 48) & 0x1fff;
8805 			additional = (count >> 16) & 0xffffffff;
8806 			count &= 0xffff;
8807 			count <<= 16;
8808 			un->un_lastop = ST_OP_CTL;
8809 			tval = un->un_dp->space_timeout;
8810 			break;
8811 
8812 		case SCMD_SPACE:
8813 			fixbit = SPACE_TYPE(bp->b_bcount);
8814 			count = SPACE_CNT(bp->b_bcount);
8815 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8816 			    " %s space %s %"PRId64" from file %d blk %d\n",
8817 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8818 			    space_strs[fixbit & 7], count,
8819 			    un->un_pos.fileno, un->un_pos.blkno);
8820 			count &= 0xffffffff;
8821 			un->un_lastop = ST_OP_CTL;
8822 			tval = un->un_dp->space_timeout;
8823 			break;
8824 
8825 		case SCMD_LOAD:
8826 			ASSERT(count < 10);
8827 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8828 			    "%s tape\n", load_strs[count]);
8829 			fixbit = 0;
8830 
8831 			/* Loading or Unloading */
8832 			if (count & LD_LOAD) {
8833 				tval = un->un_dp->load_timeout;
8834 			} else {
8835 				tval = un->un_dp->unload_timeout;
8836 			}
8837 			/* Is Retension requested */
8838 			if (count & LD_RETEN) {
8839 				tval += un->un_dp->rewind_timeout;
8840 			}
8841 			un->un_lastop = ST_OP_CTL;
8842 			break;
8843 
8844 		case SCMD_ERASE:
8845 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8846 			    "erase tape\n");
8847 			ASSERT(count == 1); /* mt sets this */
8848 			if (count == 1) {
8849 				/*
8850 				 * do long erase
8851 				 */
8852 				fixbit = 1; /* Long */
8853 
8854 				/* Drive might not honor immidiate bit */
8855 				tval = un->un_dp->erase_timeout;
8856 			} else {
8857 				/* Short Erase */
8858 				tval = un->un_dp->erase_timeout;
8859 				fixbit = 0;
8860 			}
8861 			un->un_lastop = ST_OP_CTL;
8862 			count = 0;
8863 			break;
8864 
8865 		case SCMD_MODE_SENSE:
8866 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8867 			    "mode sense\n");
8868 			allocbp = bp;
8869 			fixbit = 0;
8870 			tval = un->un_dp->non_motion_timeout;
8871 			un->un_lastop = ST_OP_CTL;
8872 			break;
8873 
8874 		case SCMD_MODE_SELECT:
8875 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8876 			    "mode select\n");
8877 			allocbp = bp;
8878 			fixbit = 0;
8879 			tval = un->un_dp->non_motion_timeout;
8880 			un->un_lastop = ST_OP_CTL;
8881 			break;
8882 
8883 		case SCMD_RESERVE:
8884 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8885 			    "reserve\n");
8886 			fixbit = 0;
8887 			tval = un->un_dp->non_motion_timeout;
8888 			un->un_lastop = ST_OP_CTL;
8889 			break;
8890 
8891 		case SCMD_RELEASE:
8892 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8893 			    "release\n");
8894 			fixbit = 0;
8895 			tval = un->un_dp->non_motion_timeout;
8896 			un->un_lastop = ST_OP_CTL;
8897 			break;
8898 
8899 		case SCMD_READ_BLKLIM:
8900 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8901 			    "read block limits\n");
8902 			allocbp = bp;
8903 			fixbit = count = 0;
8904 			tval = un->un_dp->non_motion_timeout;
8905 			un->un_lastop = ST_OP_CTL;
8906 			break;
8907 
8908 		case SCMD_TEST_UNIT_READY:
8909 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8910 			    "test unit ready\n");
8911 			fixbit = 0;
8912 			tval = un->un_dp->non_motion_timeout;
8913 			un->un_lastop = ST_OP_CTL;
8914 			break;
8915 
8916 		case SCMD_DOORLOCK:
8917 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8918 			    "prevent/allow media removal\n");
8919 			fixbit = 0;
8920 			tval = un->un_dp->non_motion_timeout;
8921 			un->un_lastop = ST_OP_CTL;
8922 			break;
8923 
8924 		case SCMD_READ_POSITION:
8925 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8926 			    "read position\n");
8927 			fixbit = un->un_read_pos_type;
8928 			cdb_len = CDB_GROUP1;
8929 			tval = un->un_dp->non_motion_timeout;
8930 			allocbp = bp;
8931 			un->un_lastop = ST_OP_CTL;
8932 			switch (un->un_read_pos_type) {
8933 			case LONG_POS:
8934 				count = 0;
8935 				break;
8936 			case EXT_POS:
8937 				count = sizeof (tape_position_ext_t);
8938 				break;
8939 			case SHORT_POS:
8940 				count = 0;
8941 				break;
8942 			default:
8943 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8944 				    "Unknown read position type 0x%x in "
8945 				    " st_make_cmd()\n", un->un_read_pos_type);
8946 			}
8947 			break;
8948 
8949 		default:
8950 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8951 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8952 			    com);
8953 		}
8954 
8955 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8956 		    st_recov_sz, 0, func, (caddr_t)un);
8957 		if (pkt == NULL) {
8958 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8959 			    "generic command scsi_init_pkt() failure\n");
8960 			goto exit;
8961 		}
8962 
8963 		ASSERT(pkt->pkt_resid == 0);
8964 #ifdef STDEBUG
8965 		bzero(pkt->pkt_private, st_recov_sz);
8966 		bzero(pkt->pkt_scbp, stat_size);
8967 #endif
8968 		ri = (recov_info *)pkt->pkt_private;
8969 		ri->privatelen = st_recov_sz;
8970 		if (allocbp) {
8971 			ASSERT(geterror(allocbp) == 0);
8972 		}
8973 
8974 	}
8975 
8976 	ucdb = (union scsi_cdb *)pkt->pkt_cdbp;
8977 
8978 	(void) scsi_setup_cdb(ucdb, com, address, (uint_t)count, additional);
8979 	FILL_SCSI1_LUN(un->un_sd, pkt);
8980 	/*
8981 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8982 	 */
8983 	ucdb->t_code = fixbit;
8984 	ucdb->g0_vu_1 = short_fm;
8985 	pkt->pkt_flags = flags;
8986 
8987 	ASSERT(tval);
8988 	pkt->pkt_time = tval;
8989 	if (bp == un->un_recov_buf) {
8990 		pkt->pkt_comp = st_recov_cb;
8991 	} else {
8992 		pkt->pkt_comp = st_intr;
8993 	}
8994 
8995 	st_add_recovery_info_to_pkt(un, bp, pkt);
8996 
8997 	/*
8998 	 * If we just write data to tape and did a command that doesn't
8999 	 * change position, we still need to write a filemark.
9000 	 */
9001 	if ((prev_op == ST_OP_WRITE) || (prev_op == ST_OP_WEOF)) {
9002 		recov_info *rcvi = pkt->pkt_private;
9003 		cmd_attribute const *atrib;
9004 
9005 		if (rcvi->privatelen == sizeof (recov_info)) {
9006 			atrib = rcvi->cmd_attrib;
9007 		} else {
9008 			atrib = st_lookup_cmd_attribute(com);
9009 		}
9010 		if (atrib->chg_tape_direction == DIR_NONE) {
9011 			un->un_lastop = prev_op;
9012 		}
9013 	}
9014 
9015 exit:
9016 	ASSERT(mutex_owned(ST_MUTEX));
9017 }
9018 
9019 
9020 /*
9021  * Build a command based on a uscsi command;
9022  */
9023 static void
9024 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
9025     struct buf *bp, int (*func)(caddr_t))
9026 {
9027 	struct scsi_pkt *pkt;
9028 	recov_info *ri;
9029 	caddr_t cdb;
9030 	int	cdblen;
9031 	int	stat_size = 1;
9032 	int	flags = 0;
9033 
9034 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
9035 
9036 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9037 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
9038 
9039 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
9040 		if (un->un_arq_enabled) {
9041 			if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
9042 				stat_size = (int)(ucmd->uscsi_rqlen) +
9043 				    sizeof (struct scsi_arq_status) -
9044 				    sizeof (struct scsi_extended_sense);
9045 				flags = PKT_XARQ;
9046 			} else {
9047 				stat_size = sizeof (struct scsi_arq_status);
9048 			}
9049 		}
9050 	}
9051 
9052 	ASSERT(mutex_owned(ST_MUTEX));
9053 
9054 	cdb = ucmd->uscsi_cdb;
9055 	cdblen = ucmd->uscsi_cdblen;
9056 
9057 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9058 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
9059 	    ucmd->uscsi_buflen, bp->b_bcount);
9060 	pkt = scsi_init_pkt(ROUTE, NULL,
9061 	    (bp->b_bcount > 0) ? bp : NULL,
9062 	    cdblen, stat_size, st_recov_sz, flags, func, (caddr_t)un);
9063 	if (pkt == NULL) {
9064 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
9065 		    "uscsi command scsi_init_pkt() failure\n");
9066 		goto exit;
9067 	}
9068 
9069 	ASSERT(pkt->pkt_resid == 0);
9070 #ifdef STDEBUG
9071 	bzero(pkt->pkt_private, st_recov_sz);
9072 	bzero(pkt->pkt_scbp, stat_size);
9073 #endif
9074 	ri = (recov_info *)pkt->pkt_private;
9075 	ri->privatelen = st_recov_sz;
9076 
9077 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
9078 
9079 #ifdef STDEBUG
9080 	if ((st_debug & 0x7) >= 6) {
9081 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
9082 		    "pkt_cdbp", (char *)cdb, cdblen);
9083 	}
9084 #endif
9085 
9086 	if (ucmd->uscsi_flags & USCSI_SILENT) {
9087 		pkt->pkt_flags |= FLAG_SILENT;
9088 	}
9089 
9090 	(void) scsi_uscsi_pktinit(ucmd, pkt);
9091 
9092 	pkt->pkt_time = ucmd->uscsi_timeout;
9093 	if (bp == un->un_recov_buf) {
9094 		pkt->pkt_comp = st_recov_cb;
9095 	} else {
9096 		pkt->pkt_comp = st_intr;
9097 	}
9098 
9099 	st_add_recovery_info_to_pkt(un, bp, pkt);
9100 exit:
9101 	ASSERT(mutex_owned(ST_MUTEX));
9102 }
9103 
9104 
9105 /*
9106  * restart cmd currently at the head of the runq
9107  *
9108  * If scsi_transport() succeeds or the retries
9109  * count exhausted, restore the throttle that was
9110  * zeroed out in st_handle_intr_busy().
9111  *
9112  */
9113 static void
9114 st_intr_restart(void *arg)
9115 {
9116 	struct scsi_tape *un = arg;
9117 	struct buf *bp;
9118 	int queued;
9119 	int status = TRAN_ACCEPT;
9120 
9121 	mutex_enter(ST_MUTEX);
9122 
9123 	ST_FUNC(ST_DEVINFO, st_intr_restart);
9124 
9125 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9126 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
9127 
9128 	un->un_hib_tid = 0;
9129 
9130 	if (un->un_recov_buf_busy != 0) {
9131 		bp = un->un_recov_buf;
9132 		queued = 0;
9133 	} else if (un->un_sbuf_busy != 0) {
9134 		bp = un->un_sbufp;
9135 		queued = 0;
9136 	} else if (un->un_quef != NULL) {
9137 		bp = un->un_quef;
9138 		queued = 1;
9139 	} else {
9140 		mutex_exit(ST_MUTEX);
9141 		return;
9142 	}
9143 
9144 	/*
9145 	 * Here we know :
9146 	 *	throttle = 0, via st_handle_intr_busy
9147 	 */
9148 
9149 	if (queued) {
9150 		/*
9151 		 * move from waitq to runq, if there is anything on the waitq
9152 		 */
9153 		(void) st_remove_from_queue(&un->un_quef, &un->un_quef, bp);
9154 
9155 		if (un->un_runqf) {
9156 			/*
9157 			 * not good, we don't want to requeue something after
9158 			 * another.
9159 			 */
9160 			goto done_error;
9161 		} else {
9162 			un->un_runqf = bp;
9163 			un->un_runql = bp;
9164 		}
9165 	}
9166 
9167 	ST_CDB(ST_DEVINFO, "Interrupt restart CDB",
9168 	    (char *)BP_PKT(bp)->pkt_cdbp);
9169 
9170 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
9171 
9172 	status = st_transport(un, BP_PKT(bp));
9173 
9174 	if (status != TRAN_ACCEPT) {
9175 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9176 
9177 		if (status == TRAN_BUSY) {
9178 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
9179 
9180 			if (pkti->privatelen == sizeof (recov_info) &&
9181 			    un->un_unit_attention_flags &&
9182 			    bp != un->un_recov_buf) {
9183 			un->un_unit_attention_flags = 0;
9184 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9185 				    "Command Recovery called on busy resend\n");
9186 				if (st_command_recovery(un, BP_PKT(bp),
9187 				    ATTEMPT_RETRY) == JUST_RETURN) {
9188 					mutex_exit(ST_MUTEX);
9189 					return;
9190 				}
9191 			}
9192 			mutex_exit(ST_MUTEX);
9193 			if (st_handle_intr_busy(un, bp,
9194 			    ST_TRAN_BUSY_TIMEOUT) == 0)
9195 				return;	/* timeout is setup again */
9196 			mutex_enter(ST_MUTEX);
9197 		}
9198 
9199 done_error:
9200 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9201 		    "restart transport rejected\n");
9202 		bp->b_resid = bp->b_bcount;
9203 
9204 		if (un->un_last_throttle) {
9205 			un->un_throttle = un->un_last_throttle;
9206 		}
9207 		if (status != TRAN_ACCEPT) {
9208 			ST_DO_ERRSTATS(un, st_transerrs);
9209 		}
9210 		ST_DO_KSTATS(bp, kstat_waitq_exit);
9211 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9212 		    "busy restart aborted\n");
9213 		st_set_pe_flag(un);
9214 		st_bioerror(bp, EIO);
9215 		st_done_and_mutex_exit(un, bp);
9216 	} else {
9217 		if (un->un_last_throttle) {
9218 			un->un_throttle = un->un_last_throttle;
9219 		}
9220 		mutex_exit(ST_MUTEX);
9221 	}
9222 }
9223 
9224 /*
9225  * st_check_media():
9226  * Periodically check the media state using scsi_watch service;
9227  * this service calls back after TUR and possibly request sense
9228  * the callback handler (st_media_watch_cb()) decodes the request sense
9229  * data (if any)
9230  */
9231 
9232 static int
9233 st_check_media(dev_t dev, enum mtio_state state)
9234 {
9235 	int rval = 0;
9236 	enum mtio_state	prev_state;
9237 	opaque_t token = NULL;
9238 
9239 	GET_SOFT_STATE(dev);
9240 
9241 	ST_FUNC(ST_DEVINFO, st_check_media);
9242 
9243 	mutex_enter(ST_MUTEX);
9244 
9245 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9246 	    "st_check_media:state=%x, mediastate=%x\n",
9247 	    state, un->un_mediastate);
9248 
9249 	prev_state = un->un_mediastate;
9250 
9251 	/*
9252 	 * is there anything to do?
9253 	 */
9254 retry:
9255 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
9256 		/*
9257 		 * submit the request to the scsi_watch service;
9258 		 * scsi_media_watch_cb() does the real work
9259 		 */
9260 		mutex_exit(ST_MUTEX);
9261 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
9262 		    st_check_media_time, SENSE_LENGTH,
9263 		    st_media_watch_cb, (caddr_t)dev);
9264 		if (token == NULL) {
9265 			rval = EAGAIN;
9266 			goto done;
9267 		}
9268 		mutex_enter(ST_MUTEX);
9269 
9270 		un->un_swr_token = token;
9271 		un->un_specified_mediastate = state;
9272 
9273 		/*
9274 		 * now wait for media change
9275 		 * we will not be signalled unless mediastate == state but it
9276 		 * still better to test for this condition, since there
9277 		 * is a 5 sec cv_broadcast delay when
9278 		 *  mediastate == MTIO_INSERTED
9279 		 */
9280 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9281 		    "st_check_media:waiting for media state change\n");
9282 		while (un->un_mediastate == state) {
9283 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
9284 				mutex_exit(ST_MUTEX);
9285 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9286 				    "st_check_media:waiting for media state "
9287 				    "was interrupted\n");
9288 				rval = EINTR;
9289 				goto done;
9290 			}
9291 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9292 			    "st_check_media:received signal, state=%x\n",
9293 			    un->un_mediastate);
9294 		}
9295 	}
9296 
9297 	/*
9298 	 * if we transitioned to MTIO_INSERTED, media has really been
9299 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
9300 	 * Reset and retry the state change.  If everything is ok, replay
9301 	 * the open() logic.
9302 	 */
9303 	if ((un->un_mediastate == MTIO_INSERTED) &&
9304 	    (un->un_state == ST_STATE_OFFLINE)) {
9305 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9306 		    "st_check_media: calling st_cmd to confirm inserted\n");
9307 
9308 		/*
9309 		 * set this early so that TUR will make it through strategy
9310 		 * without triggering a st_tape_init().  We needed it set
9311 		 * before calling st_tape_init() ourselves anyway.  If TUR
9312 		 * fails, set it back
9313 		 */
9314 		un->un_state = ST_STATE_INITIALIZING;
9315 
9316 		/*
9317 		 * If not reserved fail as getting reservation conflict
9318 		 * will make this hang forever.
9319 		 */
9320 		if ((un->un_rsvd_status &
9321 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9322 			mutex_exit(ST_MUTEX);
9323 			rval = EACCES;
9324 			goto done;
9325 		}
9326 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
9327 		if (rval == EACCES) {
9328 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9329 			    "st_check_media: TUR got Reservation Conflict\n");
9330 			mutex_exit(ST_MUTEX);
9331 			goto done;
9332 		}
9333 		if (rval) {
9334 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9335 			    "st_check_media: TUR failed, going to retry\n");
9336 			un->un_mediastate = prev_state;
9337 			un->un_state = ST_STATE_OFFLINE;
9338 			goto retry;
9339 		}
9340 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9341 		    "st_check_media: media inserted\n");
9342 
9343 		/* this also rewinds the tape */
9344 		rval = st_tape_init(un);
9345 		if (rval != 0) {
9346 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9347 			    "st_check_media : OFFLINE init failure ");
9348 			un->un_state = ST_STATE_OFFLINE;
9349 			un->un_pos.pmode = invalid;
9350 		} else {
9351 			un->un_state = ST_STATE_OPEN_PENDING_IO;
9352 		}
9353 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
9354 	    (un->un_state != ST_STATE_OFFLINE)) {
9355 		/*
9356 		 * supported devices must be rewound before ejection
9357 		 * rewind resets fileno & blkno
9358 		 */
9359 		un->un_laststate = un->un_state;
9360 		un->un_state = ST_STATE_OFFLINE;
9361 	}
9362 	mutex_exit(ST_MUTEX);
9363 done:
9364 	if (token) {
9365 		(void) scsi_watch_request_terminate(token,
9366 		    SCSI_WATCH_TERMINATE_WAIT);
9367 		mutex_enter(ST_MUTEX);
9368 		un->un_swr_token = (opaque_t)NULL;
9369 		mutex_exit(ST_MUTEX);
9370 	}
9371 
9372 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
9373 
9374 	return (rval);
9375 }
9376 
9377 /*
9378  * st_media_watch_cb() is called by scsi_watch_thread for
9379  * verifying the request sense data (if any)
9380  */
9381 static int
9382 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
9383 {
9384 	struct scsi_status *statusp = resultp->statusp;
9385 	struct scsi_extended_sense *sensep = resultp->sensep;
9386 	uchar_t actual_sense_length = resultp->actual_sense_length;
9387 	struct scsi_tape *un;
9388 	enum mtio_state state = MTIO_NONE;
9389 	int instance;
9390 	dev_t dev = (dev_t)arg;
9391 
9392 	instance = MTUNIT(dev);
9393 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
9394 		return (-1);
9395 	}
9396 
9397 	mutex_enter(ST_MUTEX);
9398 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
9399 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9400 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
9401 	    *((char *)statusp), (void *)sensep,
9402 	    actual_sense_length);
9403 
9404 
9405 	/*
9406 	 * if there was a check condition then sensep points to valid
9407 	 * sense data
9408 	 * if status was not a check condition but a reservation or busy
9409 	 * status then the new state is MTIO_NONE
9410 	 */
9411 	if (sensep) {
9412 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9413 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
9414 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
9415 
9416 		switch (un->un_dp->type) {
9417 		default:
9418 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9419 			    "st_media_watch_cb: unknown drive type %d, "
9420 			    "default to ST_TYPE_HP\n", un->un_dp->type);
9421 		/* FALLTHROUGH */
9422 
9423 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
9424 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
9425 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
9426 			if (un->un_dp->type == ST_TYPE_FUJI) {
9427 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9428 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
9429 			} else {
9430 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9431 				    "st_media_watch_cb: ST_TYPE_HP\n");
9432 			}
9433 			switch (sensep->es_key) {
9434 			case KEY_UNIT_ATTENTION:
9435 				/* not ready to ready transition */
9436 				/* hp/es_qual_code == 80 on>off>on */
9437 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
9438 				if (sensep->es_add_code == 0x28) {
9439 					state = MTIO_INSERTED;
9440 				}
9441 				break;
9442 			case KEY_NOT_READY:
9443 				/* in process, rewinding or loading */
9444 				if ((sensep->es_add_code == 0x04) &&
9445 				    (sensep->es_qual_code == 0x00)) {
9446 					state = MTIO_EJECTED;
9447 				}
9448 				break;
9449 			}
9450 			break;
9451 
9452 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
9453 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9454 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
9455 			switch (sensep->es_key) {
9456 			case KEY_UNIT_ATTENTION:
9457 				/* operator medium removal request */
9458 				if ((sensep->es_add_code == 0x5a) &&
9459 				    (sensep->es_qual_code == 0x01)) {
9460 					state = MTIO_EJECTED;
9461 				/* not ready to ready transition */
9462 				} else if ((sensep->es_add_code == 0x28) &&
9463 				    (sensep->es_qual_code == 0x00)) {
9464 					state = MTIO_INSERTED;
9465 				}
9466 				break;
9467 			case KEY_NOT_READY:
9468 				/* medium not present */
9469 				if (sensep->es_add_code == 0x3a) {
9470 					state = MTIO_EJECTED;
9471 				}
9472 				break;
9473 			}
9474 			break;
9475 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
9476 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9477 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
9478 			switch (sensep->es_key) {
9479 			case KEY_NOT_READY:
9480 				if ((sensep->es_add_code == 0x04) &&
9481 				    (sensep->es_qual_code == 0x00)) {
9482 					/* volume not mounted? */
9483 					state = MTIO_EJECTED;
9484 				} else if (sensep->es_add_code == 0x3a) {
9485 					state = MTIO_EJECTED;
9486 				}
9487 				break;
9488 			case KEY_UNIT_ATTENTION:
9489 				state = MTIO_EJECTED;
9490 				break;
9491 			}
9492 			break;
9493 
9494 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
9495 			switch (sensep->es_key) {
9496 			case KEY_UNIT_ATTENTION:
9497 				if (sensep->es_add_code == 0x28) {
9498 					state = MTIO_INSERTED;
9499 				}
9500 				break;
9501 			case KEY_NOT_READY:
9502 				if (sensep->es_add_code == 0x04) {
9503 					/* in transition but could be either */
9504 					state = un->un_specified_mediastate;
9505 				} else if ((sensep->es_add_code == 0x3a) &&
9506 				    (sensep->es_qual_code == 0x00)) {
9507 					state = MTIO_EJECTED;
9508 				}
9509 				break;
9510 			}
9511 			break;
9512 		}
9513 	} else if (*((char *)statusp) == STATUS_GOOD) {
9514 		state = MTIO_INSERTED;
9515 	}
9516 
9517 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9518 	    "st_media_watch_cb:state=%x, specified=%x\n",
9519 	    state, un->un_specified_mediastate);
9520 
9521 	/*
9522 	 * now signal the waiting thread if this is *not* the specified state;
9523 	 * delay the signal if the state is MTIO_INSERTED
9524 	 * to allow the target to recover
9525 	 */
9526 	if (state != un->un_specified_mediastate) {
9527 		un->un_mediastate = state;
9528 		if (state == MTIO_INSERTED) {
9529 			/*
9530 			 * delay the signal to give the drive a chance
9531 			 * to do what it apparently needs to do
9532 			 */
9533 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9534 			    "st_media_watch_cb:delayed cv_broadcast\n");
9535 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
9536 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
9537 		} else {
9538 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9539 			    "st_media_watch_cb:immediate cv_broadcast\n");
9540 			cv_broadcast(&un->un_state_cv);
9541 		}
9542 	}
9543 	mutex_exit(ST_MUTEX);
9544 	return (0);
9545 }
9546 
9547 /*
9548  * delayed cv_broadcast to allow for target to recover
9549  * from media insertion
9550  */
9551 static void
9552 st_delayed_cv_broadcast(void *arg)
9553 {
9554 	struct scsi_tape *un = arg;
9555 
9556 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
9557 
9558 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9559 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
9560 
9561 	mutex_enter(ST_MUTEX);
9562 	cv_broadcast(&un->un_state_cv);
9563 	mutex_exit(ST_MUTEX);
9564 }
9565 
9566 /*
9567  * restart cmd currently at the start of the waitq
9568  */
9569 static void
9570 st_start_restart(void *arg)
9571 {
9572 	struct scsi_tape *un = arg;
9573 
9574 	ST_FUNC(ST_DEVINFO, st_start_restart);
9575 
9576 	ASSERT(un != NULL);
9577 
9578 	mutex_enter(ST_MUTEX);
9579 
9580 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_tran_restart()\n");
9581 
9582 	st_start(un);
9583 
9584 	mutex_exit(ST_MUTEX);
9585 }
9586 
9587 
9588 /*
9589  * Command completion processing
9590  *
9591  */
9592 static void
9593 st_intr(struct scsi_pkt *pkt)
9594 {
9595 	recov_info *rcv = pkt->pkt_private;
9596 	struct buf *bp = rcv->cmd_bp;
9597 	struct scsi_tape *un;
9598 	errstate action = COMMAND_DONE;
9599 	clock_t	timout;
9600 	int	status;
9601 
9602 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
9603 
9604 	ST_FUNC(ST_DEVINFO, st_intr);
9605 
9606 	ASSERT(un != NULL);
9607 
9608 	mutex_enter(ST_MUTEX);
9609 
9610 	ASSERT(bp != un->un_recov_buf);
9611 
9612 	un->un_rqs_state &= ~(ST_RQS_ERROR);
9613 
9614 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
9615 
9616 	if (pkt->pkt_reason != CMD_CMPLT) {
9617 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9618 		    "Unhappy packet status reason = %s statistics = 0x%x\n",
9619 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9620 
9621 		/* If device has gone away not much else to do */
9622 		if (pkt->pkt_reason == CMD_DEV_GONE) {
9623 			action = COMMAND_DONE_ERROR;
9624 		} else if ((pkt == un->un_rqs) ||
9625 		    (un->un_state == ST_STATE_SENSING)) {
9626 			ASSERT(pkt == un->un_rqs);
9627 			ASSERT(un->un_state == ST_STATE_SENSING);
9628 			un->un_state = un->un_laststate;
9629 			rcv->cmd_bp = un->un_rqs_bp;
9630 			ST_DO_ERRSTATS(un, st_transerrs);
9631 			action = COMMAND_DONE_ERROR;
9632 		} else {
9633 			action = st_handle_incomplete(un, bp);
9634 		}
9635 	/*
9636 	 * At this point we know that the command was successfully
9637 	 * completed. Now what?
9638 	 */
9639 	} else if ((pkt == un->un_rqs) || (un->un_state == ST_STATE_SENSING)) {
9640 		/*
9641 		 * okay. We were running a REQUEST SENSE. Find
9642 		 * out what to do next.
9643 		 */
9644 		ASSERT(pkt == un->un_rqs);
9645 		ASSERT(un->un_state == ST_STATE_SENSING);
9646 		scsi_sync_pkt(pkt);
9647 		action = st_handle_sense(un, bp, &un->un_pos);
9648 		/*
9649 		 * Make rqs isn't going to be retied.
9650 		 */
9651 		if (action != QUE_BUSY_COMMAND && action != QUE_COMMAND) {
9652 			/*
9653 			 * set pkt back to original packet in case we will have
9654 			 * to requeue it
9655 			 */
9656 			pkt = BP_PKT(bp);
9657 			rcv->cmd_bp = un->un_rqs_bp;
9658 			/*
9659 			 * some actions are based on un_state, hence
9660 			 * restore the state st was in before ST_STATE_SENSING.
9661 			 */
9662 			un->un_state = un->un_laststate;
9663 		}
9664 
9665 	} else if (un->un_arq_enabled && (pkt->pkt_state & STATE_ARQ_DONE)) {
9666 		/*
9667 		 * the transport layer successfully completed an autorqsense
9668 		 */
9669 		action = st_handle_autosense(un, bp, &un->un_pos);
9670 
9671 	} else  if ((SCBP(pkt)->sts_busy) ||
9672 	    (SCBP(pkt)->sts_chk) ||
9673 	    (SCBP(pkt)->sts_vu7)) {
9674 		/*
9675 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9676 		 * to see if the status bits we're okay. If a request sense
9677 		 * is to be run, that will happen.
9678 		 */
9679 		action = st_check_error(un, pkt);
9680 	}
9681 
9682 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9683 		switch (action) {
9684 			case QUE_COMMAND:
9685 				/*
9686 				 * return cmd to head to the queue
9687 				 * since we are suspending so that
9688 				 * it gets restarted during resume
9689 				 */
9690 				st_add_to_queue(&un->un_runqf, &un->un_runql,
9691 				    un->un_runqf, bp);
9692 
9693 				action = JUST_RETURN;
9694 				break;
9695 
9696 			case QUE_SENSE:
9697 				action = COMMAND_DONE_ERROR;
9698 				break;
9699 
9700 			default:
9701 				break;
9702 		}
9703 	}
9704 
9705 	/*
9706 	 * check for undetected path failover.
9707 	 */
9708 	if (un->un_multipath) {
9709 
9710 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
9711 		int pkt_valid = 0;
9712 
9713 		if (ucmd) {
9714 			/*
9715 			 * Also copies path instance to the uscsi structure.
9716 			 */
9717 			pkt_valid = scsi_uscsi_pktfini(pkt, ucmd);
9718 
9719 			/*
9720 			 * scsi_uscsi_pktfini() zeros pkt_path_instance.
9721 			 */
9722 			pkt->pkt_path_instance = ucmd->uscsi_path_instance;
9723 		} else {
9724 			pkt_valid = scsi_pkt_allocated_correctly(pkt);
9725 		}
9726 
9727 		/*
9728 		 * If the scsi_pkt was not allocated correctly the
9729 		 * pkt_path_instance is not even there.
9730 		 */
9731 		if ((pkt_valid != 0) &&
9732 		    (un->un_last_path_instance != pkt->pkt_path_instance)) {
9733 			/*
9734 			 * Don't recover the path change if it was done
9735 			 * intentionally or if the device has not completely
9736 			 * opened yet.
9737 			 */
9738 			if (((pkt->pkt_flags & FLAG_PKT_PATH_INSTANCE) == 0) &&
9739 			    (un->un_state > ST_STATE_OPENING)) {
9740 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
9741 				    "Failover detected, action is %s\n",
9742 				    errstatenames[action]);
9743 				if (action == COMMAND_DONE) {
9744 					action = PATH_FAILED;
9745 				}
9746 			}
9747 			un->un_last_path_instance = pkt->pkt_path_instance;
9748 		}
9749 	}
9750 
9751 	/*
9752 	 * Restore old state if we were sensing.
9753 	 */
9754 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9755 		un->un_state = un->un_laststate;
9756 	}
9757 
9758 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9759 	    "st_intr: pkt=%p, bp=%p, action=%s, status=%x\n",
9760 	    (void *)pkt, (void *)bp, errstatenames[action], SCBP_C(pkt));
9761 
9762 again:
9763 	switch (action) {
9764 	case COMMAND_DONE_EACCES:
9765 		/* this is to report a reservation conflict */
9766 		st_bioerror(bp, EACCES);
9767 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9768 		    "Reservation Conflict \n");
9769 		un->un_pos.pmode = invalid;
9770 
9771 		/*FALLTHROUGH*/
9772 	case COMMAND_DONE_ERROR:
9773 		if (un->un_pos.eof < ST_EOT_PENDING &&
9774 		    un->un_state >= ST_STATE_OPEN) {
9775 			/*
9776 			 * all errors set state of the tape to 'unknown'
9777 			 * unless we're at EOT or are doing append testing.
9778 			 * If sense key was illegal request, preserve state.
9779 			 */
9780 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9781 				un->un_pos.pmode = invalid;
9782 			}
9783 		}
9784 
9785 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9786 		/*
9787 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9788 		 * make sure an error ocurrs, so make sure at least EIO is
9789 		 * returned
9790 		 */
9791 		if (geterror(bp) == 0)
9792 			st_bioerror(bp, EIO);
9793 
9794 		st_set_pe_flag(un);
9795 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9796 		    (un->un_errno == EIO)) {
9797 			un->un_rqs_state &= ~(ST_RQS_VALID);
9798 		}
9799 		break;
9800 
9801 	case COMMAND_DONE_ERROR_RECOVERED:
9802 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9803 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9804 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9805 		if (geterror(bp) == 0) {
9806 			st_bioerror(bp, EIO);
9807 		}
9808 		st_set_pe_flag(un);
9809 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9810 		    (un->un_errno == EIO)) {
9811 			un->un_rqs_state &= ~(ST_RQS_VALID);
9812 		}
9813 		/*FALLTHROUGH*/
9814 	case COMMAND_DONE:
9815 		st_set_state(un, bp);
9816 		break;
9817 
9818 	case QUE_SENSE:
9819 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9820 			goto sense_error;
9821 
9822 		if (un->un_state != ST_STATE_SENSING) {
9823 			un->un_laststate = un->un_state;
9824 			un->un_state = ST_STATE_SENSING;
9825 		}
9826 
9827 		/*
9828 		 * zero the sense data.
9829 		 */
9830 		bzero(un->un_rqs->pkt_scbp, SENSE_LENGTH);
9831 
9832 		/*
9833 		 * If this is not a retry on QUE_SENSE point to the original
9834 		 * bp of the command that got us here.
9835 		 */
9836 		if (pkt != un->un_rqs) {
9837 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp = bp;
9838 		}
9839 
9840 		if (un->un_throttle) {
9841 			un->un_last_throttle = un->un_throttle;
9842 			un->un_throttle = 0;
9843 		}
9844 
9845 		ST_CDB(ST_DEVINFO, "Queue sense CDB",
9846 		    (char *)BP_PKT(bp)->pkt_cdbp);
9847 
9848 		/*
9849 		 * never retry this, some other command will have nuked the
9850 		 * sense, anyway
9851 		 */
9852 		status = st_transport(un, un->un_rqs);
9853 
9854 		if (un->un_last_throttle) {
9855 			un->un_throttle = un->un_last_throttle;
9856 		}
9857 
9858 		if (status == TRAN_ACCEPT) {
9859 			mutex_exit(ST_MUTEX);
9860 			return;
9861 		}
9862 		if (status != TRAN_BUSY)
9863 			ST_DO_ERRSTATS(un, st_transerrs);
9864 sense_error:
9865 		un->un_pos.pmode = invalid;
9866 		st_bioerror(bp, EIO);
9867 		st_set_pe_flag(un);
9868 		break;
9869 
9870 	case QUE_BUSY_COMMAND:
9871 		/* longish timeout */
9872 		timout = ST_STATUS_BUSY_TIMEOUT;
9873 		goto que_it_up;
9874 
9875 	case QUE_COMMAND:
9876 		/* short timeout */
9877 		timout = ST_TRAN_BUSY_TIMEOUT;
9878 que_it_up:
9879 		/*
9880 		 * let st_handle_intr_busy put this bp back on waitq and make
9881 		 * checks to see if it is ok to requeue the command.
9882 		 */
9883 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9884 
9885 		/*
9886 		 * Save the throttle before setting up the timeout
9887 		 */
9888 		if (un->un_throttle) {
9889 			un->un_last_throttle = un->un_throttle;
9890 		}
9891 		mutex_exit(ST_MUTEX);
9892 		if (st_handle_intr_busy(un, bp, timout) == 0)
9893 			return;		/* timeout is setup again */
9894 
9895 		mutex_enter(ST_MUTEX);
9896 		un->un_pos.pmode = invalid;
9897 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9898 		st_bioerror(bp, EIO);
9899 		st_set_pe_flag(un);
9900 		break;
9901 
9902 	case QUE_LAST_COMMAND:
9903 
9904 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9905 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9906 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9907 			goto last_command_error;
9908 		}
9909 		mutex_exit(ST_MUTEX);
9910 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9911 			return;
9912 		mutex_enter(ST_MUTEX);
9913 last_command_error:
9914 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9915 		un->un_pos.pmode = invalid;
9916 		st_bioerror(bp, EIO);
9917 		st_set_pe_flag(un);
9918 		break;
9919 
9920 	case COMMAND_TIMEOUT:
9921 	case DEVICE_RESET:
9922 	case DEVICE_TAMPER:
9923 	case ATTEMPT_RETRY:
9924 	case PATH_FAILED:
9925 		ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9926 		    "Command Recovery called on %s status\n",
9927 		    errstatenames[action]);
9928 		action = st_command_recovery(un, pkt, action);
9929 		goto again;
9930 
9931 	default:
9932 		ASSERT(0);
9933 		/* FALLTHRU */
9934 	case JUST_RETURN:
9935 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9936 		mutex_exit(ST_MUTEX);
9937 		return;
9938 	}
9939 
9940 	ST_DO_KSTATS(bp, kstat_runq_exit);
9941 	st_done_and_mutex_exit(un, bp);
9942 }
9943 
9944 static errstate
9945 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9946 {
9947 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9948 	recov_info *rinfo;
9949 	errstate rval = COMMAND_DONE_ERROR;
9950 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9951 	    un->un_rqs : BP_PKT(bp);
9952 	int result;
9953 
9954 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9955 
9956 	rinfo = (recov_info *)pkt->pkt_private;
9957 
9958 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9959 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9960 
9961 	ASSERT(mutex_owned(ST_MUTEX));
9962 
9963 	/* prevent infinite number of retries */
9964 	if (rinfo->pkt_retry_cnt++ > st_retry_count) {
9965 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
9966 		    "Recovery stopped for incomplete %s command, "
9967 		    "retries exhausted",
9968 		    st_print_scsi_cmd(pkt->pkt_cdbp[0]));
9969 		return (COMMAND_DONE_ERROR);
9970 	}
9971 
9972 	switch (pkt->pkt_reason) {
9973 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9974 		/*
9975 		 * this occurs when accessing a powered down drive, no
9976 		 * need to complain; just fail the open
9977 		 */
9978 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9979 
9980 		/*
9981 		 * if we have commands outstanding in HBA, and a command
9982 		 * comes back incomplete, we're hosed, so reset target
9983 		 * If we have the bus, but cmd_incomplete, we probably just
9984 		 * have a failed selection, so don't reset the target, just
9985 		 * requeue the command and try again
9986 		 */
9987 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9988 			goto reset_target;
9989 		}
9990 
9991 		/*
9992 		 * Retry selection a couple more times if we're
9993 		 * open.  If opening, we only try just once to
9994 		 * reduce probe time for nonexistant devices.
9995 		 */
9996 		if ((un->un_laststate > ST_STATE_OPENING) &&
9997 		    (rinfo->pkt_retry_cnt < st_selection_retry_count)) {
9998 			/* XXX check retriable? */
9999 			rval = QUE_COMMAND;
10000 		}
10001 		ST_DO_ERRSTATS(un, st_transerrs);
10002 		break;
10003 
10004 	case CMD_ABORTED:
10005 		/*
10006 		 * most likely this is caused by flush-on-error support. If
10007 		 * it was not there, the we're in trouble.
10008 		 */
10009 		if (!un->un_flush_on_errors) {
10010 			un->un_status = SUN_KEY_FATAL;
10011 			goto reset_target;
10012 		}
10013 
10014 		st_set_pe_errno(un);
10015 		bioerror(bp, un->un_errno);
10016 		if (un->un_errno)
10017 			return (COMMAND_DONE_ERROR);
10018 		else
10019 			return (COMMAND_DONE);
10020 
10021 	case CMD_TIMEOUT:	/* Command timed out */
10022 		un->un_status = SUN_KEY_TIMEOUT;
10023 		return (COMMAND_TIMEOUT);
10024 
10025 	case CMD_TRAN_ERR:
10026 	case CMD_RESET:
10027 		if (pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET)) {
10028 			if ((un->un_rsvd_status &
10029 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
10030 			    ST_RESERVE) {
10031 				un->un_rsvd_status |= ST_LOST_RESERVE;
10032 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
10033 				    "Lost Reservation\n");
10034 			}
10035 			rval = DEVICE_RESET;
10036 			return (rval);
10037 		}
10038 		if (pkt->pkt_statistics & (STAT_ABORTED | STAT_TERMINATED)) {
10039 			rval = DEVICE_RESET;
10040 			return (rval);
10041 		}
10042 		/*FALLTHROUGH*/
10043 	default:
10044 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10045 		    "Unhandled packet status reason = %s statistics = 0x%x\n",
10046 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
10047 reset_target:
10048 
10049 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10050 		    "transport completed with %s\n",
10051 		    scsi_rname(pkt->pkt_reason));
10052 		ST_DO_ERRSTATS(un, st_transerrs);
10053 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
10054 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
10055 		    STAT_ABORTED)) == 0)) {
10056 
10057 			/*
10058 			 * If we haven't reserved the drive don't reset it.
10059 			 */
10060 			if ((un->un_rsvd_status &
10061 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
10062 				return (rval);
10063 			}
10064 
10065 			/*
10066 			 * if we aren't lost yet we will be soon.
10067 			 */
10068 			un->un_pos.pmode = invalid;
10069 
10070 			result = st_reset(un, RESET_LUN);
10071 
10072 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
10073 				/* no hope left to recover */
10074 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
10075 				    "recovery by resets failed\n");
10076 				return (rval);
10077 			}
10078 		}
10079 	}
10080 
10081 
10082 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
10083 		rval = QUE_COMMAND;
10084 	} else if (bp == un->un_sbufp) {
10085 		if (rinfo->privatelen == sizeof (recov_info)) {
10086 			if (rinfo->cmd_attrib->retriable) {
10087 				/*
10088 				 * These commands can be rerun
10089 				 * with impunity
10090 				 */
10091 				rval = QUE_COMMAND;
10092 			}
10093 		} else {
10094 			cmd_attribute const *attrib;
10095 			attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10096 			if (attrib->retriable) {
10097 				rval = QUE_COMMAND;
10098 			}
10099 		}
10100 	}
10101 
10102 	if (un->un_state >= ST_STATE_OPEN) {
10103 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10104 		    fail, scsi_rname(pkt->pkt_reason),
10105 		    (rval == COMMAND_DONE_ERROR)?
10106 		    "giving up" : "retrying command");
10107 	}
10108 	return (rval);
10109 }
10110 
10111 /*
10112  * if the device is busy, then put this bp back on the waitq, on the
10113  * interrupt thread, where we want the head of the queue and not the
10114  * end
10115  *
10116  * The callers of this routine should take measures to save the
10117  * un_throttle in un_last_throttle which will be restored in
10118  * st_intr_restart(). The only exception should be st_intr_restart()
10119  * calling this routine for which the saving is already done.
10120  */
10121 static int
10122 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
10123 	clock_t timeout_interval)
10124 {
10125 
10126 	int queued;
10127 	int rval = 0;
10128 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
10129 
10130 	mutex_enter(ST_MUTEX);
10131 
10132 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
10133 
10134 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10135 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
10136 
10137 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
10138 		queued = 1;
10139 	} else {
10140 		queued = 0;
10141 	}
10142 
10143 	/*
10144 	 * Check to see if we hit the retry timeout. We check to make sure
10145 	 * this is the first one on the runq and make sure we have not
10146 	 * queued up any more, so this one has to be the last on the list
10147 	 * also. If it is not, we have to fail.  If it is not the first, but
10148 	 * is the last we are in trouble anyway, as we are in the interrupt
10149 	 * context here.
10150 	 */
10151 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
10152 	    ((un->un_runqf != bp) && (un->un_runql != bp) && (queued))) {
10153 		rval = -1;
10154 		goto exit;
10155 	}
10156 
10157 	/* put the bp back on the waitq */
10158 	if (queued) {
10159 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
10160 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
10161 	}
10162 
10163 	/*
10164 	 * We don't want any other commands being started in the mean time.
10165 	 * If start had just released mutex after putting something on the
10166 	 * runq, we won't even get here.
10167 	 */
10168 	un->un_throttle = 0;
10169 
10170 	/*
10171 	 * send a marker pkt, if appropriate
10172 	 */
10173 	st_hba_unflush(un);
10174 
10175 	/*
10176 	 * all queues are aligned, we are just waiting to
10177 	 * transport
10178 	 */
10179 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
10180 
10181 exit:
10182 	mutex_exit(ST_MUTEX);
10183 	return (rval);
10184 }
10185 
10186 /*
10187  * To get one error entry from error stack
10188  */
10189 static int
10190 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
10191 {
10192 #ifdef _MULTI_DATAMODEL
10193 	/*
10194 	 * For use when a 32 bit app makes a call into a
10195 	 * 64 bit ioctl
10196 	 */
10197 	struct mterror_entry32 err_entry32;
10198 #endif /* _MULTI_DATAMODEL */
10199 
10200 	int rval = 0;
10201 	struct mterror_entry err_entry;
10202 	struct mterror_entry_stack *err_link_entry_p;
10203 	size_t arq_status_len_in, arq_status_len_kr;
10204 
10205 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
10206 
10207 	ASSERT(mutex_owned(ST_MUTEX));
10208 
10209 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10210 	    "st_get_error_entry()\n");
10211 
10212 	/*
10213 	 * if error record stack empty, return ENXIO
10214 	 */
10215 	if (un->un_error_entry_stk == NULL) {
10216 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10217 		    "st_get_error_entry: Error Entry Stack Empty!\n");
10218 		rval = ENXIO;
10219 		goto ret;
10220 	}
10221 
10222 	/*
10223 	 * get the top entry from stack
10224 	 */
10225 	err_link_entry_p = un->un_error_entry_stk;
10226 	arq_status_len_kr =
10227 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
10228 
10229 #ifdef _MULTI_DATAMODEL
10230 	switch (ddi_model_convert_from(flag & FMODELS)) {
10231 	case DDI_MODEL_ILP32:
10232 		if (ddi_copyin((void *)arg, &err_entry32,
10233 		    MTERROR_ENTRY_SIZE_32, flag)) {
10234 			rval = EFAULT;
10235 			goto ret;
10236 		}
10237 
10238 		arq_status_len_in =
10239 		    (size_t)err_entry32.mtee_arq_status_len;
10240 
10241 		err_entry32.mtee_cdb_len =
10242 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
10243 
10244 		if (arq_status_len_in > arq_status_len_kr)
10245 			err_entry32.mtee_arq_status_len =
10246 			    (size32_t)arq_status_len_kr;
10247 
10248 		if (ddi_copyout(
10249 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10250 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
10251 		    err_entry32.mtee_cdb_len, flag)) {
10252 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10253 			    "st_get_error_entry: Copy cdb buffer error!");
10254 			rval = EFAULT;
10255 		}
10256 
10257 		if (ddi_copyout(
10258 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10259 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
10260 		    err_entry32.mtee_arq_status_len, flag)) {
10261 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10262 			    "st_get_error_entry: copy arq status error!");
10263 			rval = EFAULT;
10264 		}
10265 
10266 		if (ddi_copyout(&err_entry32, (void *)arg,
10267 		    MTERROR_ENTRY_SIZE_32, flag)) {
10268 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10269 			    "st_get_error_entry: copy arq status out error!");
10270 			rval = EFAULT;
10271 		}
10272 		break;
10273 
10274 	case DDI_MODEL_NONE:
10275 		if (ddi_copyin((void *)arg, &err_entry,
10276 		    MTERROR_ENTRY_SIZE_64, flag)) {
10277 			rval = EFAULT;
10278 			goto ret;
10279 		}
10280 		arq_status_len_in = err_entry.mtee_arq_status_len;
10281 
10282 		err_entry.mtee_cdb_len =
10283 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
10284 
10285 		if (arq_status_len_in > arq_status_len_kr)
10286 			err_entry.mtee_arq_status_len =
10287 			    arq_status_len_kr;
10288 
10289 		if (ddi_copyout(
10290 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10291 		    err_entry.mtee_cdb_buf,
10292 		    err_entry.mtee_cdb_len, flag)) {
10293 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10294 			    "st_get_error_entry: Copy cdb buffer error!");
10295 			rval = EFAULT;
10296 		}
10297 
10298 		if (ddi_copyout(
10299 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10300 		    err_entry.mtee_arq_status,
10301 		    err_entry.mtee_arq_status_len, flag)) {
10302 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10303 			    "st_get_error_entry: copy arq status error!");
10304 			rval = EFAULT;
10305 		}
10306 
10307 		if (ddi_copyout(&err_entry, (void *)arg,
10308 		    MTERROR_ENTRY_SIZE_64, flag)) {
10309 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10310 			    "st_get_error_entry: copy arq status out error!");
10311 			rval = EFAULT;
10312 		}
10313 		break;
10314 	}
10315 #else /* _MULTI_DATAMODEL */
10316 	if (ddi_copyin((void *)arg, &err_entry,
10317 	    MTERROR_ENTRY_SIZE_64, flag)) {
10318 		rval = EFAULT;
10319 		goto ret;
10320 	}
10321 	arq_status_len_in = err_entry.mtee_arq_status_len;
10322 
10323 	err_entry.mtee_cdb_len =
10324 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
10325 
10326 	if (arq_status_len_in > arq_status_len_kr)
10327 		err_entry.mtee_arq_status_len =
10328 		    arq_status_len_kr;
10329 
10330 	if (ddi_copyout(
10331 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10332 	    err_entry.mtee_cdb_buf,
10333 	    err_entry.mtee_cdb_len, flag)) {
10334 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10335 		    "st_get_error_entry: Copy cdb buffer error!");
10336 		rval = EFAULT;
10337 	}
10338 
10339 	if (ddi_copyout(
10340 	    err_link_entry_p->mtees_entry.mtee_arq_status,
10341 	    err_entry.mtee_arq_status,
10342 	    err_entry.mtee_arq_status_len, flag)) {
10343 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10344 		    "st_get_error_entry: copy arq status buffer error!");
10345 		rval = EFAULT;
10346 	}
10347 
10348 	if (ddi_copyout(&err_entry, (void *)arg,
10349 	    MTERROR_ENTRY_SIZE_64, flag)) {
10350 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10351 		    "st_get_error_entry: copy arq status out error!");
10352 		rval = EFAULT;
10353 	}
10354 #endif /* _MULTI_DATAMODEL */
10355 
10356 	/*
10357 	 * update stack
10358 	 */
10359 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
10360 
10361 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
10362 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
10363 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
10364 
10365 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
10366 	    SECMDS_STATUS_SIZE);
10367 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
10368 
10369 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
10370 	err_link_entry_p = NULL;
10371 ret:
10372 	return (rval);
10373 }
10374 
10375 /*
10376  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
10377  * the scsi CDB command which causes the error and generates sense data and
10378  * the scsi status.
10379  *
10380  *      error-record stack
10381  *
10382  *
10383  *             TOP                                     BOTTOM
10384  *              ------------------------------------------
10385  *              |   0   |   1   |   2   |   ...  |   n   |
10386  *              ------------------------------------------
10387  *                  ^
10388  *                  |
10389  *       pointer to error entry
10390  *
10391  * when st driver generates one sense data record, it creates a error-entry
10392  * and pushes it onto the stack.
10393  *
10394  */
10395 
10396 static void
10397 st_update_error_stack(struct scsi_tape *un,
10398 			struct scsi_pkt *pkt,
10399 			struct scsi_arq_status *cmd)
10400 {
10401 	struct mterror_entry_stack *err_entry_tmp;
10402 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
10403 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
10404 
10405 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
10406 
10407 	ASSERT(mutex_owned(ST_MUTEX));
10408 
10409 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10410 	    "st_update_error_stack()\n");
10411 
10412 	ASSERT(cmd);
10413 	ASSERT(cdbp);
10414 	if (cdblen == 0) {
10415 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10416 		    "st_update_error_stack: CDB length error!\n");
10417 		return;
10418 	}
10419 
10420 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
10421 	ASSERT(err_entry_tmp != NULL);
10422 
10423 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
10424 	    kmem_alloc(cdblen, KM_SLEEP);
10425 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
10426 
10427 	err_entry_tmp->mtees_entry.mtee_arq_status =
10428 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
10429 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
10430 
10431 	/*
10432 	 * copy cdb command & length to current error entry
10433 	 */
10434 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
10435 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
10436 
10437 	/*
10438 	 * copy scsi status length to current error entry
10439 	 */
10440 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
10441 	    SECMDS_STATUS_SIZE;
10442 
10443 	/*
10444 	 * copy sense data and scsi status to current error entry
10445 	 */
10446 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
10447 	    SECMDS_STATUS_SIZE);
10448 
10449 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
10450 	un->un_error_entry_stk = err_entry_tmp;
10451 
10452 }
10453 
10454 /*
10455  * Empty all the error entry in stack
10456  */
10457 static void
10458 st_empty_error_stack(struct scsi_tape *un)
10459 {
10460 	struct mterror_entry_stack *linkp;
10461 
10462 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
10463 
10464 	ASSERT(mutex_owned(ST_MUTEX));
10465 
10466 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10467 	    "st_empty_entry_stack()\n");
10468 
10469 	while (un->un_error_entry_stk != NULL) {
10470 		linkp = un->un_error_entry_stk;
10471 		un->un_error_entry_stk =
10472 		    un->un_error_entry_stk->mtees_nextp;
10473 
10474 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
10475 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
10476 			    linkp->mtees_entry.mtee_cdb_len);
10477 
10478 		if (linkp->mtees_entry.mtee_arq_status != NULL)
10479 			kmem_free(linkp->mtees_entry.mtee_arq_status,
10480 			    linkp->mtees_entry.mtee_arq_status_len);
10481 
10482 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
10483 		linkp = NULL;
10484 	}
10485 }
10486 
10487 static errstate
10488 st_handle_sense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10489 {
10490 	struct scsi_pkt *pkt = BP_PKT(bp);
10491 	struct scsi_pkt *rqpkt = un->un_rqs;
10492 	struct scsi_arq_status arqstat;
10493 	recov_info *rcif = pkt->pkt_private;
10494 
10495 	errstate rval = COMMAND_DONE_ERROR;
10496 	int amt;
10497 
10498 	ST_FUNC(ST_DEVINFO, st_handle_sense);
10499 
10500 	ASSERT(mutex_owned(ST_MUTEX));
10501 
10502 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10503 	    "st_handle_sense()\n");
10504 
10505 	if (SCBP(rqpkt)->sts_busy) {
10506 		if (rcif->privatelen == sizeof (recov_info)) {
10507 			ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
10508 			    "Attempt recovery of busy unit on request sense\n");
10509 			rval = ATTEMPT_RETRY;
10510 		} else if (rcif->pkt_retry_cnt++ < st_retry_count) {
10511 			ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10512 			    "Retry busy unit on request sense\n");
10513 			rval = QUE_BUSY_COMMAND;
10514 		}
10515 		return (rval);
10516 	} else if (SCBP(rqpkt)->sts_chk) {
10517 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10518 		    "Check Condition on REQUEST SENSE\n");
10519 		return (rval);
10520 	}
10521 
10522 	/*
10523 	 * Make sure there is sense data to look at.
10524 	 */
10525 	if ((rqpkt->pkt_state & (STATE_GOT_BUS | STATE_GOT_TARGET |
10526 	    STATE_SENT_CMD | STATE_GOT_STATUS)) != (STATE_GOT_BUS |
10527 	    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) {
10528 		return (rval);
10529 	}
10530 
10531 	/* was there enough data? */
10532 	amt = (int)MAX_SENSE_LENGTH - rqpkt->pkt_resid;
10533 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
10534 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10535 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10536 		    "REQUEST SENSE couldn't get sense data\n");
10537 		return (rval);
10538 	}
10539 
10540 	bcopy(SCBP(pkt), &arqstat.sts_status,
10541 	    sizeof (struct scsi_status));
10542 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
10543 	    sizeof (struct scsi_status));
10544 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
10545 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
10546 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
10547 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
10548 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
10549 
10550 	/*
10551 	 * copy one arqstat entry in the sense data buffer
10552 	 */
10553 	st_update_error_stack(un, pkt, &arqstat);
10554 	return (st_decode_sense(un, bp, amt, &arqstat, pos));
10555 }
10556 
10557 static errstate
10558 st_handle_autosense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10559 {
10560 	struct scsi_pkt *pkt = BP_PKT(bp);
10561 	struct scsi_arq_status *arqstat =
10562 	    (struct scsi_arq_status *)pkt->pkt_scbp;
10563 	errstate rval = COMMAND_DONE_ERROR;
10564 	int amt;
10565 
10566 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
10567 
10568 	ASSERT(mutex_owned(ST_MUTEX));
10569 
10570 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10571 	    "st_handle_autosense()\n");
10572 
10573 	if (arqstat->sts_rqpkt_status.sts_busy) {
10574 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10575 		    "busy unit on request sense\n");
10576 		/*
10577 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
10578 		 * the disadvantage is that we do not have any delay for the
10579 		 * second retry of rqsense and we have to keep a packet around
10580 		 */
10581 		return (QUE_SENSE);
10582 
10583 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
10584 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10585 		    "transport error on REQUEST SENSE\n");
10586 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
10587 		    ((arqstat->sts_rqpkt_statistics &
10588 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
10589 			if (st_reset(un, RESET_LUN) == 0) {
10590 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10591 				    "recovery by resets failed\n");
10592 			}
10593 		}
10594 		return (rval);
10595 
10596 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
10597 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10598 		    "Check Condition on REQUEST SENSE\n");
10599 		return (rval);
10600 	}
10601 
10602 
10603 	/* was there enough data? */
10604 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10605 		amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10606 	} else {
10607 		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
10608 			amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10609 		} else {
10610 			amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10611 		}
10612 	}
10613 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
10614 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10615 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10616 		    "REQUEST SENSE couldn't get sense data\n");
10617 		return (rval);
10618 	}
10619 
10620 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10621 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, MAX_SENSE_LENGTH);
10622 	} else {
10623 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
10624 	}
10625 
10626 	/*
10627 	 * copy one arqstat entry in the sense data buffer
10628 	 */
10629 	st_update_error_stack(un, pkt, arqstat);
10630 
10631 	return (st_decode_sense(un, bp, amt, arqstat, pos));
10632 }
10633 
10634 static errstate
10635 st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
10636     struct scsi_arq_status *statusp, tapepos_t *pos)
10637 {
10638 	struct scsi_pkt *pkt = BP_PKT(bp);
10639 	recov_info *ri = pkt->pkt_private;
10640 	errstate rval = COMMAND_DONE_ERROR;
10641 	cmd_attribute const *attrib;
10642 	long resid;
10643 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10644 	int severity;
10645 	int get_error;
10646 
10647 	ST_FUNC(ST_DEVINFO, st_decode_sense);
10648 
10649 	ASSERT(mutex_owned(ST_MUTEX));
10650 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10651 	    "st_decode_sense()\n");
10652 
10653 	/*
10654 	 * For uscsi commands, squirrel away a copy of the
10655 	 * results of the Request Sense.
10656 	 */
10657 	if (USCSI_CMD(bp)) {
10658 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
10659 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
10660 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
10661 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
10662 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
10663 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
10664 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10665 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
10666 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
10667 		}
10668 	}
10669 
10670 	if (ri->privatelen == sizeof (recov_info)) {
10671 		attrib = ri->cmd_attrib;
10672 	} else {
10673 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10674 	}
10675 
10676 	/*
10677 	 * If the drive is an MT-02, reposition the
10678 	 * secondary error code into the proper place.
10679 	 *
10680 	 * XXX	MT-02 is non-CCS tape, so secondary error code
10681 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
10682 	 * so it's in byte 12.
10683 	 */
10684 	if (un->un_dp->type == ST_TYPE_EMULEX) {
10685 		sensep->es_code = sensep->es_add_info[0];
10686 	}
10687 
10688 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
10689 	    (caddr_t)&CDBP(pkt)->scc_cmd);
10690 
10691 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)statusp,
10692 	    sizeof (*statusp));
10693 
10694 	/* for normal I/O check extract the resid values. */
10695 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
10696 		if (sensep->es_valid) {
10697 			resid =
10698 			    (sensep->es_info_1 << 24) |
10699 			    (sensep->es_info_2 << 16) |
10700 			    (sensep->es_info_3 << 8)  |
10701 			    (sensep->es_info_4);
10702 			/* If fixed block */
10703 			if (un->un_bsize) {
10704 				resid *= un->un_bsize;
10705 			}
10706 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
10707 			resid = pkt->pkt_resid;
10708 		} else {
10709 			resid = bp->b_bcount;
10710 		}
10711 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10712 		    "st_decode_sense (rw): xferred bit = %d, resid=%ld (%d), "
10713 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
10714 		    resid,
10715 		    (sensep->es_info_1 << 24) |
10716 		    (sensep->es_info_2 << 16) |
10717 		    (sensep->es_info_3 << 8)  |
10718 		    (sensep->es_info_4),
10719 		    pkt->pkt_resid);
10720 		/*
10721 		 * The problem is, what should we believe?
10722 		 */
10723 		if (resid && (pkt->pkt_resid == 0)) {
10724 			pkt->pkt_resid = resid;
10725 		}
10726 	} else {
10727 		/*
10728 		 * If the command is SCMD_SPACE, we need to get the
10729 		 * residual as returned in the sense data, to adjust
10730 		 * our idea of current tape position correctly
10731 		 */
10732 		if ((sensep->es_valid) &&
10733 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10734 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10735 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
10736 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE_G4) ||
10737 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK)) {
10738 			resid =
10739 			    (sensep->es_info_1 << 24) |
10740 			    (sensep->es_info_2 << 16) |
10741 			    (sensep->es_info_3 << 8)  |
10742 			    (sensep->es_info_4);
10743 			bp->b_resid = resid;
10744 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10745 			    "st_decode_sense(other):	resid=%ld\n", resid);
10746 		} else {
10747 			/*
10748 			 * If the special command is SCMD_READ,
10749 			 * the correct resid will be set later.
10750 			 */
10751 			if (attrib->get_cnt != NULL) {
10752 				resid = attrib->get_cnt(pkt->pkt_cdbp);
10753 			} else {
10754 				resid = bp->b_bcount;
10755 			}
10756 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10757 			    "st_decode_sense(special read):  resid=%ld\n",
10758 			    resid);
10759 		}
10760 	}
10761 
10762 	if ((un->un_state >= ST_STATE_OPEN) &&
10763 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
10764 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
10765 		    "Failed CDB", (char *)pkt->pkt_cdbp);
10766 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10767 		    "sense data", (char *)sensep, amt);
10768 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10769 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10770 		    bp->b_bcount, resid, pkt->pkt_resid);
10771 	}
10772 
10773 	switch (un->un_status = sensep->es_key) {
10774 	case KEY_NO_SENSE:
10775 		severity = SCSI_ERR_INFO;
10776 
10777 		/*
10778 		 * Erase, locate or rewind operation in progress, retry
10779 		 * ASC  ASCQ
10780 		 *  00   18    Erase operation in progress
10781 		 *  00   19    Locate operation in progress
10782 		 *  00   1A    Rewind operation in progress
10783 		 */
10784 		if (sensep->es_add_code == 0 &&
10785 		    ((sensep->es_qual_code == 0x18) ||
10786 		    (sensep->es_qual_code == 0x19) ||
10787 		    (sensep->es_qual_code == 0x1a))) {
10788 			rval = QUE_BUSY_COMMAND;
10789 			break;
10790 		}
10791 
10792 		goto common;
10793 
10794 	case KEY_RECOVERABLE_ERROR:
10795 		severity = SCSI_ERR_RECOVERED;
10796 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10797 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10798 			if (un->un_dp->options &
10799 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10800 				rval = QUE_LAST_COMMAND;
10801 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10802 				    severity, pos->lgclblkno,
10803 				    un->un_err_pos.lgclblkno, scsi_cmds,
10804 				    sensep);
10805 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10806 				    "Command will be retried\n");
10807 			} else {
10808 				severity = SCSI_ERR_FATAL;
10809 				rval = COMMAND_DONE_ERROR_RECOVERED;
10810 				ST_DO_ERRSTATS(un, st_softerrs);
10811 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10812 				    severity, pos->lgclblkno,
10813 				    un->un_err_pos.lgclblkno, scsi_cmds,
10814 				    sensep);
10815 			}
10816 			break;
10817 		}
10818 common:
10819 		/*
10820 		 * XXX only want reads to be stopped by filemarks.
10821 		 * Don't want them to be stopped by EOT.  EOT matters
10822 		 * only on write.
10823 		 */
10824 		if (sensep->es_filmk && !sensep->es_eom) {
10825 			rval = COMMAND_DONE;
10826 		} else if (sensep->es_eom) {
10827 			rval = COMMAND_DONE;
10828 		} else if (sensep->es_ili) {
10829 			/*
10830 			 * Fun with variable length record devices:
10831 			 * for specifying larger blocks sizes than the
10832 			 * actual physical record size.
10833 			 */
10834 			if (un->un_bsize == 0 && resid > 0) {
10835 				/*
10836 				 * XXX! Ugly.
10837 				 * The requested blocksize is > tape blocksize,
10838 				 * so this is ok, so we just return the
10839 				 * actual size xferred.
10840 				 */
10841 				pkt->pkt_resid = resid;
10842 				rval = COMMAND_DONE;
10843 			} else if (un->un_bsize == 0 && resid < 0) {
10844 				/*
10845 				 * The requested blocksize is < tape blocksize,
10846 				 * so this is not ok, so we err with ENOMEM
10847 				 */
10848 				rval = COMMAND_DONE_ERROR_RECOVERED;
10849 				st_bioerror(bp, ENOMEM);
10850 			} else {
10851 				ST_DO_ERRSTATS(un, st_softerrs);
10852 				severity = SCSI_ERR_FATAL;
10853 				rval = COMMAND_DONE_ERROR;
10854 				st_bioerror(bp, EINVAL);
10855 				un->un_running.pmode = invalid;
10856 			}
10857 		} else {
10858 			/*
10859 			 * we hope and pray for this just being
10860 			 * something we can ignore (ie. a
10861 			 * truly recoverable soft error)
10862 			 */
10863 			rval = COMMAND_DONE;
10864 		}
10865 		if (sensep->es_filmk) {
10866 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10867 			    "filemark\n");
10868 			un->un_status = SUN_KEY_EOF;
10869 			pos->eof = ST_EOF_PENDING;
10870 			st_set_pe_flag(un);
10871 		}
10872 
10873 		/*
10874 		 * ignore eom when reading, a fmk should terminate reading
10875 		 */
10876 		if ((sensep->es_eom) &&
10877 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10878 			if ((sensep->es_add_code == 0) &&
10879 			    (sensep->es_qual_code == 4)) {
10880 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10881 				    "bot\n");
10882 				un->un_status = SUN_KEY_BOT;
10883 				pos->eof = ST_NO_EOF;
10884 				pos->lgclblkno = 0;
10885 				pos->fileno = 0;
10886 				pos->blkno = 0;
10887 				if (pos->pmode != legacy)
10888 					pos->pmode = legacy;
10889 			} else {
10890 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10891 				    "eom\n");
10892 				un->un_status = SUN_KEY_EOT;
10893 				pos->eof = ST_EOM;
10894 			}
10895 			st_set_pe_flag(un);
10896 		}
10897 
10898 		break;
10899 
10900 	case KEY_ILLEGAL_REQUEST:
10901 
10902 		if (un->un_laststate >= ST_STATE_OPEN) {
10903 			ST_DO_ERRSTATS(un, st_softerrs);
10904 			severity = SCSI_ERR_FATAL;
10905 		} else {
10906 			severity = SCSI_ERR_INFO;
10907 		}
10908 		break;
10909 
10910 	case KEY_MEDIUM_ERROR:
10911 		ST_DO_ERRSTATS(un, st_harderrs);
10912 		severity = SCSI_ERR_FATAL;
10913 		un->un_pos.pmode = invalid;
10914 		un->un_running.pmode = invalid;
10915 check_keys:
10916 		/*
10917 		 * attempt to process the keys in the presence of
10918 		 * other errors
10919 		 */
10920 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10921 			/*
10922 			 * Fun with variable length record devices:
10923 			 * for specifying larger blocks sizes than the
10924 			 * actual physical record size.
10925 			 */
10926 			if (un->un_bsize == 0 && resid > 0) {
10927 				/*
10928 				 * XXX! Ugly
10929 				 */
10930 				pkt->pkt_resid = resid;
10931 			} else if (un->un_bsize == 0 && resid < 0) {
10932 				st_bioerror(bp, EINVAL);
10933 			} else {
10934 				severity = SCSI_ERR_FATAL;
10935 				rval = COMMAND_DONE_ERROR;
10936 				st_bioerror(bp, EINVAL);
10937 			}
10938 		}
10939 		if (sensep->es_filmk) {
10940 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10941 			    "filemark\n");
10942 			un->un_status = SUN_KEY_EOF;
10943 			pos->eof = ST_EOF_PENDING;
10944 			st_set_pe_flag(un);
10945 		}
10946 
10947 		/*
10948 		 * ignore eom when reading, a fmk should terminate reading
10949 		 */
10950 		if ((sensep->es_eom) &&
10951 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10952 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10953 			un->un_status = SUN_KEY_EOT;
10954 			pos->eof = ST_EOM;
10955 			st_set_pe_flag(un);
10956 		}
10957 
10958 		break;
10959 
10960 	case KEY_VOLUME_OVERFLOW:
10961 		ST_DO_ERRSTATS(un, st_softerrs);
10962 		pos->eof = ST_EOM;
10963 		severity = SCSI_ERR_FATAL;
10964 		rval = COMMAND_DONE_ERROR;
10965 		goto check_keys;
10966 
10967 	case KEY_HARDWARE_ERROR:
10968 		ST_DO_ERRSTATS(un, st_harderrs);
10969 		severity = SCSI_ERR_FATAL;
10970 		rval = COMMAND_DONE_ERROR;
10971 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10972 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10973 		break;
10974 
10975 	case KEY_BLANK_CHECK:
10976 		ST_DO_ERRSTATS(un, st_softerrs);
10977 		severity = SCSI_ERR_INFO;
10978 
10979 		/*
10980 		 * if not a special request and some data was xferred then it
10981 		 * it is not an error yet
10982 		 */
10983 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10984 			/*
10985 			 * no error for read with or without data xferred
10986 			 */
10987 			un->un_status = SUN_KEY_EOT;
10988 			pos->eof = ST_EOT;
10989 			rval = COMMAND_DONE_ERROR;
10990 			un->un_running.pmode = invalid;
10991 			st_set_pe_flag(un);
10992 			goto check_keys;
10993 		} else if (bp != un->un_sbufp &&
10994 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10995 			rval = COMMAND_DONE;
10996 		} else {
10997 			rval = COMMAND_DONE_ERROR_RECOVERED;
10998 		}
10999 
11000 		if (un->un_laststate >= ST_STATE_OPEN) {
11001 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11002 			    "blank check\n");
11003 			pos->eof = ST_EOM;
11004 		}
11005 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
11006 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
11007 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
11008 		    (un->un_dp->options & ST_KNOWS_EOD)) {
11009 			/*
11010 			 * we were doing a fast forward by skipping
11011 			 * multiple fmk at the time
11012 			 */
11013 			st_bioerror(bp, EIO);
11014 			severity = SCSI_ERR_RECOVERED;
11015 			rval	 = COMMAND_DONE;
11016 		}
11017 		st_set_pe_flag(un);
11018 		goto check_keys;
11019 
11020 	case KEY_WRITE_PROTECT:
11021 		if (st_wrongtapetype(un)) {
11022 			un->un_status = SUN_KEY_WRONGMEDIA;
11023 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11024 			    "wrong tape for writing- use DC6150 tape "
11025 			    "(or equivalent)\n");
11026 			severity = SCSI_ERR_UNKNOWN;
11027 		} else {
11028 			severity = SCSI_ERR_FATAL;
11029 		}
11030 		ST_DO_ERRSTATS(un, st_harderrs);
11031 		rval = COMMAND_DONE_ERROR;
11032 		st_bioerror(bp, EACCES);
11033 		break;
11034 
11035 	case KEY_UNIT_ATTENTION:
11036 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11037 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
11038 
11039 		un->un_unit_attention_flags |= 1;
11040 		/*
11041 		 * If we have detected a Bus Reset and the tape
11042 		 * drive has been reserved.
11043 		 */
11044 		if (ST_RQSENSE->es_add_code == 0x29) {
11045 			rval = DEVICE_RESET;
11046 			if ((un->un_rsvd_status &
11047 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
11048 			    ST_RESERVE) {
11049 				un->un_rsvd_status |= ST_LOST_RESERVE;
11050 				ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
11051 				    "st_decode_sense: Lost Reservation\n");
11052 			}
11053 		}
11054 
11055 		/*
11056 		 * If this is a recovery command and retrable, retry.
11057 		 */
11058 		if (bp == un->un_recov_buf) {
11059 			severity = SCSI_ERR_INFO;
11060 			if (attrib->retriable &&
11061 			    ri->pkt_retry_cnt++ < st_retry_count) {
11062 				rval = QUE_COMMAND;
11063 			} else {
11064 				rval = COMMAND_DONE_ERROR;
11065 			}
11066 			break; /* Don't set position invalid */
11067 		}
11068 
11069 		/*
11070 		 * If ST_APPLICATION_RESERVATIONS is set,
11071 		 * If the asc/ascq indicates that the reservation
11072 		 * has been cleared just allow the write to continue
11073 		 * which would force a scsi 2 reserve.
11074 		 * If preempted that persistent reservation
11075 		 * the scsi 2 reserve would get a reservation conflict.
11076 		 */
11077 		if ((un->un_rsvd_status &
11078 		    ST_APPLICATION_RESERVATIONS) != 0) {
11079 			/*
11080 			 * RESERVATIONS PREEMPTED
11081 			 * With MPxIO this could be a fail over? XXX
11082 			 */
11083 			if (ST_RQSENSE->es_add_code == 0x2a &&
11084 			    ST_RQSENSE->es_qual_code == 0x03) {
11085 				severity = SCSI_ERR_INFO;
11086 				rval = COMMAND_DONE_ERROR;
11087 				pos->pmode = invalid;
11088 				break;
11089 			/*
11090 			 * RESERVATIONS RELEASED
11091 			 */
11092 			} else if (ST_RQSENSE->es_add_code == 0x2a &&
11093 			    ST_RQSENSE->es_qual_code == 0x04) {
11094 				severity = SCSI_ERR_INFO;
11095 				rval = COMMAND_DONE;
11096 				break;
11097 			}
11098 		}
11099 
11100 		if (un->un_state <= ST_STATE_OPENING) {
11101 			/*
11102 			 * Look, the tape isn't open yet, now determine
11103 			 * if the cause is a BUS RESET, Save the file
11104 			 * and Block positions for the callers to
11105 			 * recover from the loss of position.
11106 			 */
11107 			severity = SCSI_ERR_INFO;
11108 			if ((pos->pmode != invalid) &&
11109 			    (rval == DEVICE_RESET) &&
11110 			    (un->un_restore_pos != 1)) {
11111 				un->un_save_fileno = pos->fileno;
11112 				un->un_save_blkno = pos->blkno;
11113 				un->un_restore_pos = 1;
11114 			}
11115 
11116 			if (attrib->retriable &&
11117 			    ri->pkt_retry_cnt++ < st_retry_count) {
11118 				rval = QUE_COMMAND;
11119 			} else if (rval == DEVICE_RESET) {
11120 				break;
11121 			} else {
11122 				rval = COMMAND_DONE_ERROR;
11123 			}
11124 		/*
11125 		 * Means it thinks the mode parameters have changed.
11126 		 * This is the result of a reset clearing settings or
11127 		 * another initiator changing what we set.
11128 		 */
11129 		}
11130 		if (ST_RQSENSE->es_add_code == 0x2a) {
11131 			if (ST_RQSENSE->es_qual_code == 0x1) {
11132 				/* Error recovery will modeselect and retry. */
11133 				rval = DEVICE_TAMPER;
11134 				severity = SCSI_ERR_INFO;
11135 				break; /* don't set position invalid */
11136 			}
11137 			if (ST_RQSENSE->es_qual_code == 0x0 ||
11138 			    ST_RQSENSE->es_qual_code == 0x2 ||
11139 			    ST_RQSENSE->es_qual_code == 0x3 ||
11140 			    ST_RQSENSE->es_qual_code == 0x4 ||
11141 			    ST_RQSENSE->es_qual_code == 0x5 ||
11142 			    ST_RQSENSE->es_qual_code == 0x6 ||
11143 			    ST_RQSENSE->es_qual_code == 0x7) {
11144 				rval = DEVICE_TAMPER;
11145 				severity = SCSI_ERR_INFO;
11146 			}
11147 		} else if (ST_RQSENSE->es_add_code == 0x28 &&
11148 		    ((ST_RQSENSE->es_qual_code == 0x0) ||
11149 		    ST_RQSENSE->es_qual_code == 0x5)) {
11150 			/*
11151 			 * Not Ready to Ready change, Media may have changed.
11152 			 */
11153 			rval = DEVICE_TAMPER;
11154 			severity = SCSI_ERR_RETRYABLE;
11155 		} else {
11156 			if (rval != DEVICE_RESET) {
11157 				rval = COMMAND_DONE_ERROR;
11158 			} else {
11159 				/*
11160 				 * Returning DEVICE_RESET will call
11161 				 * error recovery.
11162 				 */
11163 				severity = SCSI_ERR_INFO;
11164 				break; /* don't set position invalid */
11165 			}
11166 			/*
11167 			 * Check if it is an Unexpected Unit Attention.
11168 			 * If state is >= ST_STATE_OPEN, we have
11169 			 * already done the initialization .
11170 			 * In this case it is Fatal Error
11171 			 * since no further reading/writing
11172 			 * can be done with fileno set to < 0.
11173 			 */
11174 			if (un->un_state >= ST_STATE_OPEN) {
11175 				ST_DO_ERRSTATS(un, st_harderrs);
11176 				severity = SCSI_ERR_FATAL;
11177 			} else {
11178 				severity = SCSI_ERR_INFO;
11179 			}
11180 		}
11181 
11182 		pos->pmode = invalid;
11183 
11184 		break;
11185 
11186 	case KEY_NOT_READY:
11187 		/*
11188 		 * If in process of getting ready retry.
11189 		 */
11190 		if (sensep->es_add_code == 0x04) {
11191 			switch (sensep->es_qual_code) {
11192 			case 0x07:
11193 				/*
11194 				 * We get here when the tape is rewinding.
11195 				 * QUE_BUSY_COMMAND retries every 10 seconds.
11196 				 */
11197 				if (ri->pkt_retry_cnt++ <
11198 				    (un->un_dp->rewind_timeout / 10)) {
11199 					rval = QUE_BUSY_COMMAND;
11200 					severity = SCSI_ERR_INFO;
11201 				} else {
11202 					/* give up */
11203 					rval = COMMAND_DONE_ERROR;
11204 					severity = SCSI_ERR_FATAL;
11205 				}
11206 				break;
11207 			case 0x01:
11208 				if (ri->pkt_retry_cnt++ < st_retry_count) {
11209 					rval = QUE_COMMAND;
11210 					severity = SCSI_ERR_INFO;
11211 					break;
11212 				}
11213 				/* FALLTHROUGH */
11214 			default:
11215 				/* give up */
11216 				rval = COMMAND_DONE_ERROR;
11217 				severity = SCSI_ERR_FATAL;
11218 			}
11219 		} else {
11220 			/* give up */
11221 			rval = COMMAND_DONE_ERROR;
11222 			severity = SCSI_ERR_FATAL;
11223 		}
11224 
11225 		/*
11226 		 * If this was an error and after device opened
11227 		 * do error stats.
11228 		 */
11229 		if (rval == COMMAND_DONE_ERROR &&
11230 		    un->un_state > ST_STATE_OPENING) {
11231 			ST_DO_ERRSTATS(un, st_harderrs);
11232 		}
11233 
11234 		if (ST_RQSENSE->es_add_code == 0x3a) {
11235 			if (st_error_level >= SCSI_ERR_FATAL)
11236 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11237 				    "Tape not inserted in drive\n");
11238 			un->un_mediastate = MTIO_EJECTED;
11239 			cv_broadcast(&un->un_state_cv);
11240 		}
11241 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
11242 		    (rval != QUE_COMMAND))
11243 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
11244 		break;
11245 
11246 	case KEY_ABORTED_COMMAND:
11247 		/* XXX Do drives return this when they see a lost light? */
11248 		/* Testing would say yes */
11249 
11250 		if (ri->pkt_retry_cnt++ < st_retry_count) {
11251 			rval = ATTEMPT_RETRY;
11252 			severity = SCSI_ERR_RETRYABLE;
11253 			goto check_keys;
11254 		}
11255 		/*
11256 		 * Probably a parity error...
11257 		 * if we retry here then this may cause data to be
11258 		 * written twice or data skipped during reading
11259 		 */
11260 		ST_DO_ERRSTATS(un, st_harderrs);
11261 		severity = SCSI_ERR_FATAL;
11262 		rval = COMMAND_DONE_ERROR;
11263 		goto check_keys;
11264 
11265 	default:
11266 		/*
11267 		 * Undecoded sense key.	 Try retries and hope
11268 		 * that will fix the problem.  Otherwise, we're
11269 		 * dead.
11270 		 */
11271 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11272 		    "Unhandled Sense Key '%s'\n",
11273 		    sense_keys[un->un_status]);
11274 		ST_DO_ERRSTATS(un, st_harderrs);
11275 		severity = SCSI_ERR_FATAL;
11276 		rval = COMMAND_DONE_ERROR;
11277 		goto check_keys;
11278 	}
11279 
11280 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
11281 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
11282 	    (un->un_laststate > ST_STATE_OPENING) &&
11283 	    (severity >= st_error_level))) {
11284 
11285 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
11286 		    pos->lgclblkno, un->un_err_pos.lgclblkno,
11287 		    scsi_cmds, sensep);
11288 		if (sensep->es_filmk) {
11289 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11290 			    "File Mark Detected\n");
11291 		}
11292 		if (sensep->es_eom) {
11293 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11294 			    "End-of-Media Detected\n");
11295 		}
11296 		if (sensep->es_ili) {
11297 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11298 			    "Incorrect Length Indicator Set\n");
11299 		}
11300 	}
11301 	get_error = geterror(bp);
11302 	if (((rval == COMMAND_DONE_ERROR) ||
11303 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
11304 	    ((get_error == EIO) || (get_error == 0))) {
11305 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
11306 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
11307 		if (un->un_rqs_state & ST_RQS_READ) {
11308 			un->un_rqs_state &= ~(ST_RQS_READ);
11309 		} else {
11310 			un->un_rqs_state |= ST_RQS_OVR;
11311 		}
11312 	}
11313 
11314 	return (rval);
11315 }
11316 
11317 
11318 static int
11319 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
11320 {
11321 	int status = TRAN_ACCEPT;
11322 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
11323 
11324 	mutex_enter(ST_MUTEX);
11325 
11326 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
11327 
11328 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11329 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
11330 
11331 	/*
11332 	 * Check to see if we hit the retry timeout. We check to make sure
11333 	 * this is the first one on the runq and make sure we have not
11334 	 * queued up any more, so this one has to be the last on the list
11335 	 * also. If it is not, we have to fail.  If it is not the first, but
11336 	 * is the last we are in trouble anyway, as we are in the interrupt
11337 	 * context here.
11338 	 */
11339 	if ((pktinfo->pkt_retry_cnt > st_retry_count) ||
11340 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
11341 		goto exit;
11342 	}
11343 
11344 	if (un->un_throttle) {
11345 		un->un_last_throttle = un->un_throttle;
11346 		un->un_throttle = 0;
11347 	}
11348 
11349 	/*
11350 	 * Here we know : bp is the first and last one on the runq
11351 	 * it is not necessary to put it back on the head of the
11352 	 * waitq and then move from waitq to runq. Save this queuing
11353 	 * and call scsi_transport.
11354 	 */
11355 	ST_CDB(ST_DEVINFO, "Retry lcmd CDB", (char *)BP_PKT(bp)->pkt_cdbp);
11356 
11357 	status = st_transport(un, BP_PKT(bp));
11358 
11359 	if (status == TRAN_ACCEPT) {
11360 		if (un->un_last_throttle) {
11361 			un->un_throttle = un->un_last_throttle;
11362 		}
11363 		mutex_exit(ST_MUTEX);
11364 
11365 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11366 		    "restart transport \n");
11367 		return (0);
11368 	}
11369 
11370 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
11371 	mutex_exit(ST_MUTEX);
11372 
11373 	if (status == TRAN_BUSY) {
11374 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
11375 			return (0);
11376 		}
11377 	}
11378 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11379 	    "restart transport rejected\n");
11380 	mutex_enter(ST_MUTEX);
11381 	ST_DO_ERRSTATS(un, st_transerrs);
11382 	if (un->un_last_throttle) {
11383 		un->un_throttle = un->un_last_throttle;
11384 	}
11385 exit:
11386 	mutex_exit(ST_MUTEX);
11387 	return (-1);
11388 }
11389 
11390 static int
11391 st_wrongtapetype(struct scsi_tape *un)
11392 {
11393 
11394 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
11395 
11396 	ASSERT(mutex_owned(ST_MUTEX));
11397 
11398 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
11399 
11400 	/*
11401 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
11402 	 */
11403 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
11404 		switch (un->un_dp->type) {
11405 		case ST_TYPE_WANGTEK:
11406 		case ST_TYPE_ARCHIVE:
11407 			/*
11408 			 * If this really worked, we could go off of
11409 			 * the density codes set in the modesense
11410 			 * page. For this drive, 0x10 == QIC-120,
11411 			 * 0xf == QIC-150, and 0x5 should be for
11412 			 * both QIC-24 and, maybe, QIC-11. However,
11413 			 * the h/w doesn't do what the manual says
11414 			 * that it should, so we'll key off of
11415 			 * getting a WRITE PROTECT error AND wp *not*
11416 			 * set in the mode sense information.
11417 			 */
11418 			/*
11419 			 * XXX but we already know that status is
11420 			 * write protect, so don't check it again.
11421 			 */
11422 
11423 			if (un->un_status == KEY_WRITE_PROTECT &&
11424 			    un->un_mspl->wp == 0) {
11425 				return (1);
11426 			}
11427 			break;
11428 		default:
11429 			break;
11430 		}
11431 	}
11432 	return (0);
11433 }
11434 
11435 static errstate
11436 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
11437 {
11438 	errstate action;
11439 	recov_info *rcvi = pkt->pkt_private;
11440 	buf_t *bp = rcvi->cmd_bp;
11441 	struct scsi_arq_status *stat = (struct scsi_arq_status *)pkt->pkt_scbp;
11442 
11443 	ST_FUNC(ST_DEVINFO, st_check_error);
11444 
11445 	ASSERT(mutex_owned(ST_MUTEX));
11446 
11447 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
11448 
11449 	switch (SCBP_C(pkt)) {
11450 	case STATUS_RESERVATION_CONFLICT:
11451 		/*
11452 		 * Command recovery is enabled, not just opening,
11453 		 * we had the drive reserved and we thing its ours.
11454 		 * Call recovery to attempt to take it back.
11455 		 */
11456 		if ((rcvi->privatelen == sizeof (recov_info)) &&
11457 		    (bp != un->un_recov_buf) &&
11458 		    (un->un_state > ST_STATE_OPEN_PENDING_IO) &&
11459 		    ((un->un_rsvd_status & (ST_RESERVE |
11460 		    ST_APPLICATION_RESERVATIONS)) != 0)) {
11461 			action = ATTEMPT_RETRY;
11462 			un->un_rsvd_status |= ST_LOST_RESERVE;
11463 		} else {
11464 			action = COMMAND_DONE_EACCES;
11465 			un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
11466 		}
11467 		break;
11468 
11469 	case STATUS_BUSY:
11470 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
11471 		if (rcvi->privatelen == sizeof (recov_info) &&
11472 		    un->un_multipath && (pkt->pkt_state == (STATE_GOT_BUS |
11473 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS))) {
11474 			/*
11475 			 * Status returned by scsi_vhci indicating path
11476 			 * has failed over.
11477 			 */
11478 			action = PATH_FAILED;
11479 			break;
11480 		}
11481 		/* FALLTHRU */
11482 	case STATUS_QFULL:
11483 		if (rcvi->privatelen == sizeof (recov_info)) {
11484 			/*
11485 			 * If recovery is inabled use it instead of
11486 			 * blind reties.
11487 			 */
11488 			action = ATTEMPT_RETRY;
11489 		} else if (rcvi->pkt_retry_cnt++ < st_retry_count) {
11490 			action = QUE_BUSY_COMMAND;
11491 		} else if ((un->un_rsvd_status &
11492 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
11493 			/*
11494 			 * If this is a command done before reserve is done
11495 			 * don't reset.
11496 			 */
11497 			action = COMMAND_DONE_ERROR;
11498 		} else {
11499 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11500 			    "unit busy too long\n");
11501 			(void) st_reset(un, RESET_ALL);
11502 			action = COMMAND_DONE_ERROR;
11503 		}
11504 		break;
11505 
11506 	case STATUS_CHECK:
11507 	case STATUS_TERMINATED:
11508 		/*
11509 		 * we should only get here if the auto rqsense failed
11510 		 * thru a uscsi cmd without autorequest sense
11511 		 * so we just try again
11512 		 */
11513 		if (un->un_arq_enabled &&
11514 		    stat->sts_rqpkt_reason == CMD_CMPLT &&
11515 		    (stat->sts_rqpkt_state & (STATE_GOT_BUS |
11516 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) ==
11517 		    (STATE_GOT_BUS | STATE_GOT_TARGET | STATE_SENT_CMD |
11518 		    STATE_GOT_STATUS)) {
11519 
11520 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11521 			    "Really got sense data\n");
11522 			action = st_decode_sense(un, bp, MAX_SENSE_LENGTH -
11523 			    pkt->pkt_resid, stat, &un->un_pos);
11524 		} else {
11525 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11526 			    "Trying to queue sense command\n");
11527 			action = QUE_SENSE;
11528 		}
11529 		break;
11530 
11531 	case STATUS_TASK_ABORT:
11532 		/*
11533 		 * This is an aborted task. This can be a reset on the other
11534 		 * port of a multiport drive. Lets try and recover it.
11535 		 */
11536 		action = DEVICE_RESET;
11537 		break;
11538 
11539 	default:
11540 		action = COMMAND_DONE;
11541 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
11542 		    "Unexpected scsi status byte 0x%x\n", SCBP_C(pkt));
11543 	}
11544 	return (action);
11545 }
11546 
11547 static void
11548 st_calc_bnum(struct scsi_tape *un, struct buf *bp, struct scsi_pkt *pkt)
11549 {
11550 	int nblks;
11551 	int nfiles;
11552 	long count;
11553 	recov_info *ri = pkt->pkt_private;
11554 	cmd_attribute const *attrib;
11555 
11556 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
11557 
11558 	ASSERT(mutex_owned(ST_MUTEX));
11559 
11560 	if (ri->privatelen == sizeof (recov_info)) {
11561 		attrib = ri->cmd_attrib;
11562 		ASSERT(attrib->recov_pos_type == POS_EXPECTED);
11563 		ASSERT(attrib->chg_tape_pos);
11564 	} else {
11565 		ri = NULL;
11566 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
11567 	}
11568 
11569 	count = bp->b_bcount - bp->b_resid;
11570 
11571 	/* Command reads or writes data */
11572 	if (attrib->transfers_data != TRAN_NONE) {
11573 		if (count == 0) {
11574 			if (attrib->transfers_data == TRAN_WRTE) {
11575 				ASSERT(un->un_pos.eof == ST_EOM);
11576 				nblks = 0;
11577 				nfiles = 0;
11578 			} else {
11579 				ASSERT(un->un_pos.eof == ST_EOF_PENDING);
11580 				nblks = 0;
11581 				nfiles = 1;
11582 			}
11583 		} else if (un->un_bsize == 0) {
11584 			/*
11585 			 * If variable block mode.
11586 			 * Fixed bit in CBD should be zero.
11587 			 */
11588 			ASSERT((pkt->pkt_cdbp[1] & 1) == 0);
11589 			nblks = 1;
11590 			un->un_kbytes_xferred += (count / ONE_K);
11591 			nfiles = 0;
11592 		} else {
11593 			/*
11594 			 * If fixed block mode.
11595 			 * Fixed bit in CBD should be one.
11596 			 */
11597 			ASSERT((pkt->pkt_cdbp[1] & 1) == 1);
11598 			nblks = (count / un->un_bsize);
11599 			un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
11600 			nfiles = 0;
11601 		}
11602 		/*
11603 		 * So its possable to read some blocks and hit a filemark.
11604 		 * Example reading in fixed block mode where more then one
11605 		 * block at a time is requested. In this case because the
11606 		 * filemark is hit something less then the requesed number
11607 		 * of blocks is read.
11608 		 */
11609 		if (un->un_pos.eof == ST_EOF_PENDING && bp->b_resid) {
11610 			nfiles = 1;
11611 		}
11612 	} else {
11613 		nblks = 0;
11614 		nfiles = count;
11615 	}
11616 
11617 	/*
11618 	 * If some command failed after this one started and it seems
11619 	 * to have finshed without error count the position.
11620 	 */
11621 	if (un->un_persistence && un->un_persist_errors) {
11622 		ASSERT(un->un_pos.pmode != invalid);
11623 	}
11624 
11625 	if (attrib->chg_tape_direction == DIR_FORW) {
11626 		un->un_pos.blkno += nblks;
11627 		un->un_pos.lgclblkno += nblks;
11628 		un->un_pos.lgclblkno += nfiles;
11629 	} else if (attrib->chg_tape_direction == DIR_REVC) {
11630 		un->un_pos.blkno -= nblks;
11631 		un->un_pos.lgclblkno -= nblks;
11632 		un->un_pos.lgclblkno -= nfiles;
11633 	} else {
11634 		ASSERT(0);
11635 	}
11636 
11637 	/* recovery disabled */
11638 	if (ri == NULL) {
11639 		un->un_running.pmode = invalid;
11640 		return;
11641 	}
11642 
11643 	/*
11644 	 * If we didn't just read a filemark.
11645 	 */
11646 	if (un->un_pos.eof != ST_EOF_PENDING) {
11647 		ASSERT(nblks != 0 && nfiles == 0);
11648 		/*
11649 		 * If Previously calulated expected position does not match
11650 		 * debug the expected position.
11651 		 */
11652 		if ((ri->pos.pmode != invalid) && nblks &&
11653 		    ((un->un_pos.blkno != ri->pos.blkno) ||
11654 		    (un->un_pos.lgclblkno != ri->pos.lgclblkno))) {
11655 #ifdef STDEBUG
11656 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11657 			    "Expected", &ri->pos);
11658 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11659 			    "But Got", &un->un_pos);
11660 #endif
11661 			un->un_running.pmode = invalid;
11662 		}
11663 	} else {
11664 		ASSERT(nfiles != 0);
11665 		if (un->un_running.pmode != invalid) {
11666 			/*
11667 			 * blkno and lgclblkno already counted in
11668 			 * st_add_recovery_info_to_pkt(). Since a block was not
11669 			 * read and a filemark was.
11670 			 */
11671 			if (attrib->chg_tape_direction == DIR_FORW) {
11672 				un->un_running.fileno++;
11673 				un->un_running.blkno = 0;
11674 			} else if (attrib->chg_tape_direction == DIR_REVC) {
11675 				un->un_running.fileno--;
11676 				un->un_running.blkno = LASTBLK;
11677 			}
11678 		}
11679 	}
11680 }
11681 
11682 static void
11683 st_set_state(struct scsi_tape *un, struct buf *bp)
11684 {
11685 	struct scsi_pkt *sp = BP_PKT(bp);
11686 	struct uscsi_cmd *ucmd;
11687 
11688 	ST_FUNC(ST_DEVINFO, st_set_state);
11689 
11690 	ASSERT(mutex_owned(ST_MUTEX));
11691 	ASSERT(bp != un->un_recov_buf);
11692 
11693 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11694 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
11695 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
11696 
11697 	if (bp != un->un_sbufp) {
11698 #ifdef STDEBUG
11699 		if (DEBUGGING && sp->pkt_resid) {
11700 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11701 			    "pkt_resid %ld bcount %ld\n",
11702 			    sp->pkt_resid, bp->b_bcount);
11703 		}
11704 #endif
11705 		bp->b_resid = sp->pkt_resid;
11706 		if (geterror(bp) != EIO) {
11707 			st_calc_bnum(un, bp, sp);
11708 		}
11709 		if (bp->b_flags & B_READ) {
11710 			un->un_lastop = ST_OP_READ;
11711 			un->un_fmneeded = 0;
11712 		} else {
11713 			un->un_lastop = ST_OP_WRITE;
11714 			if (un->un_dp->options & ST_REEL) {
11715 				un->un_fmneeded = 2;
11716 			} else {
11717 				un->un_fmneeded = 1;
11718 			}
11719 		}
11720 		/*
11721 		 * all is honky dory at this point, so let's
11722 		 * readjust the throttle, to increase speed, if we
11723 		 * have not throttled down.
11724 		 */
11725 		if (un->un_throttle) {
11726 			un->un_throttle = un->un_max_throttle;
11727 		}
11728 	} else {
11729 		optype new_lastop = ST_OP_NIL;
11730 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
11731 
11732 		switch (cmd) {
11733 		case SCMD_WRITE:
11734 		case SCMD_WRITE_G4:
11735 			bp->b_resid = sp->pkt_resid;
11736 			new_lastop = ST_OP_WRITE;
11737 			if (geterror(bp) == EIO) {
11738 				break;
11739 			}
11740 			st_calc_bnum(un, bp, sp);
11741 			if (un->un_dp->options & ST_REEL) {
11742 				un->un_fmneeded = 2;
11743 			} else {
11744 				un->un_fmneeded = 1;
11745 			}
11746 			break;
11747 		case SCMD_READ:
11748 		case SCMD_READ_G4:
11749 			bp->b_resid = sp->pkt_resid;
11750 			new_lastop = ST_OP_READ;
11751 			un->un_lastop = ST_OP_READ;
11752 			if (geterror(bp) == EIO) {
11753 				break;
11754 			}
11755 			st_calc_bnum(un, bp, sp);
11756 			un->un_fmneeded = 0;
11757 			break;
11758 		case SCMD_WRITE_FILE_MARK_G4:
11759 		case SCMD_WRITE_FILE_MARK:
11760 		{
11761 			int fmdone;
11762 
11763 			if (un->un_pos.eof != ST_EOM) {
11764 				un->un_pos.eof = ST_NO_EOF;
11765 			}
11766 			fmdone = (bp->b_bcount - bp->b_resid);
11767 			if (fmdone > 0) {
11768 				un->un_lastop = new_lastop = ST_OP_WEOF;
11769 				un->un_pos.lgclblkno += fmdone;
11770 				un->un_pos.fileno += fmdone;
11771 				un->un_pos.blkno = 0;
11772 			} else {
11773 				new_lastop = ST_OP_CTL;
11774 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11775 				    "Flushed buffer\n");
11776 			}
11777 			if (fmdone > un->un_fmneeded) {
11778 				un->un_fmneeded = 0;
11779 			} else {
11780 				un->un_fmneeded -= fmdone;
11781 			}
11782 			break;
11783 		}
11784 		case SCMD_REWIND:
11785 			un->un_pos.eof = ST_NO_EOF;
11786 			un->un_pos.fileno = 0;
11787 			un->un_pos.blkno = 0;
11788 			un->un_pos.lgclblkno = 0;
11789 			if (un->un_pos.pmode != legacy)
11790 				un->un_pos.pmode = legacy;
11791 			new_lastop = ST_OP_CTL;
11792 			un->un_restore_pos = 0;
11793 			break;
11794 
11795 		case SCMD_SPACE:
11796 		case SCMD_SPACE_G4:
11797 		{
11798 			int64_t count;
11799 			int64_t resid;
11800 			int64_t done;
11801 			cmd_attribute const *attrib;
11802 			recov_info *ri = sp->pkt_private;
11803 
11804 			if (ri->privatelen == sizeof (recov_info)) {
11805 				attrib = ri->cmd_attrib;
11806 			} else {
11807 				attrib =
11808 				    st_lookup_cmd_attribute(sp->pkt_cdbp[0]);
11809 			}
11810 
11811 			resid = (int64_t)SPACE_CNT(bp->b_resid);
11812 			count = (int64_t)attrib->get_cnt(sp->pkt_cdbp);
11813 
11814 			if (count >= 0) {
11815 				done = (count - resid);
11816 			} else {
11817 				done = ((-count) - resid);
11818 			}
11819 			if (done > 0) {
11820 				un->un_lastop = new_lastop = ST_OP_CTL;
11821 			} else {
11822 				new_lastop = ST_OP_CTL;
11823 			}
11824 
11825 			ST_SPAC(ST_DEVINFO, st_label, CE_WARN,
11826 			    "space cmd: cdb[1] = %s\n"
11827 			    "space data:       = 0x%lx\n"
11828 			    "space count:      = %"PRId64"\n"
11829 			    "space resid:      = %"PRId64"\n"
11830 			    "spaces done:      = %"PRId64"\n"
11831 			    "fileno before     = %d\n"
11832 			    "blkno before      = %d\n",
11833 			    space_strs[sp->pkt_cdbp[1] & 7],
11834 			    bp->b_bcount,
11835 			    count, resid, done,
11836 			    un->un_pos.fileno, un->un_pos.blkno);
11837 
11838 			switch (sp->pkt_cdbp[1]) {
11839 			case SPACE_TYPE(SP_FLM):
11840 				/* Space file forward */
11841 				if (count >= 0) {
11842 					if (un->un_pos.eof <= ST_EOF) {
11843 						un->un_pos.eof = ST_NO_EOF;
11844 					}
11845 					un->un_pos.fileno += done;
11846 					un->un_pos.blkno = 0;
11847 					break;
11848 				}
11849 				/* Space file backward */
11850 				if (done > un->un_pos.fileno) {
11851 					un->un_pos.fileno = 0;
11852 					un->un_pos.blkno = 0;
11853 				} else {
11854 					un->un_pos.fileno -= done;
11855 					un->un_pos.blkno = LASTBLK;
11856 					un->un_running.pmode = invalid;
11857 				}
11858 				break;
11859 			case SPACE_TYPE(SP_BLK):
11860 				/* Space block forward */
11861 				if (count >= 0) {
11862 					un->un_pos.blkno += done;
11863 					break;
11864 				}
11865 				/* Space block backward */
11866 				if (un->un_pos.eof >= ST_EOF_PENDING) {
11867 				/*
11868 				 * we stepped back into
11869 				 * a previous file; we are not
11870 				 * making an effort to pretend that
11871 				 * we are still in the current file
11872 				 * ie. logical == physical position
11873 				 * and leave it to st_ioctl to correct
11874 				 */
11875 					if (done > un->un_pos.blkno) {
11876 						un->un_pos.blkno = 0;
11877 					} else {
11878 						un->un_pos.fileno--;
11879 						un->un_pos.blkno = LASTBLK;
11880 						un->un_running.pmode = invalid;
11881 					}
11882 				} else {
11883 					un->un_pos.blkno -= done;
11884 				}
11885 				break;
11886 			case SPACE_TYPE(SP_SQFLM):
11887 				un->un_pos.pmode = logical;
11888 				un->un_pos.blkno = 0;
11889 				un->un_lastop = new_lastop = ST_OP_CTL;
11890 				break;
11891 			case SPACE_TYPE(SP_EOD):
11892 				un->un_pos.pmode = logical;
11893 				un->un_pos.eof = ST_EOM;
11894 				un->un_status = KEY_BLANK_CHECK;
11895 				break;
11896 			default:
11897 				un->un_pos.pmode = invalid;
11898 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11899 				    "Unsupported space cmd: %s\n",
11900 				    space_strs[sp->pkt_cdbp[1] & 7]);
11901 
11902 				un->un_lastop = new_lastop = ST_OP_CTL;
11903 			}
11904 
11905 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11906 			    "after_space rs %"PRId64" fil %d blk %d\n",
11907 			    resid, un->un_pos.fileno, un->un_pos.blkno);
11908 
11909 			break;
11910 		}
11911 		case SCMD_LOAD:
11912 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
11913 				un->un_pos.fileno = 0;
11914 				if (un->un_pos.pmode != legacy)
11915 					un->un_pos.pmode = legacy;
11916 			} else {
11917 				un->un_state = ST_STATE_OFFLINE;
11918 				un->un_pos.pmode = invalid;
11919 
11920 			}
11921 			/*
11922 			 * If we are loading or unloading we expect the media id
11923 			 * to change. Lets make it unknown.
11924 			 */
11925 			if (un->un_media_id != bogusID && un->un_media_id_len) {
11926 				kmem_free(un->un_media_id, un->un_media_id_len);
11927 				un->un_media_id = NULL;
11928 				un->un_media_id_len = 0;
11929 			}
11930 			un->un_density_known = 0;
11931 			un->un_pos.eof = ST_NO_EOF;
11932 			un->un_pos.blkno = 0;
11933 			un->un_lastop = new_lastop = ST_OP_CTL;
11934 			break;
11935 		case SCMD_ERASE:
11936 			un->un_pos.eof = ST_NO_EOF;
11937 			un->un_pos.blkno = 0;
11938 			un->un_pos.fileno = 0;
11939 			un->un_pos.lgclblkno = 0;
11940 			if (un->un_pos.pmode != legacy)
11941 				un->un_pos.pmode = legacy;
11942 			new_lastop = ST_OP_CTL;
11943 			break;
11944 		case SCMD_RESERVE:
11945 			un->un_rsvd_status |= ST_RESERVE;
11946 			un->un_rsvd_status &=
11947 			    ~(ST_RELEASE | ST_LOST_RESERVE |
11948 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11949 			new_lastop = ST_OP_CTL;
11950 			break;
11951 		case SCMD_RELEASE:
11952 			un->un_rsvd_status |= ST_RELEASE;
11953 			un->un_rsvd_status &=
11954 			    ~(ST_RESERVE | ST_LOST_RESERVE |
11955 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11956 			new_lastop = ST_OP_CTL;
11957 			break;
11958 		case SCMD_PERSISTENT_RESERVE_IN:
11959 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11960 			    "PGR_IN command\n");
11961 			new_lastop = ST_OP_CTL;
11962 			break;
11963 		case SCMD_PERSISTENT_RESERVE_OUT:
11964 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
11965 			case ST_SA_SCSI3_RESERVE:
11966 			case ST_SA_SCSI3_PREEMPT:
11967 			case ST_SA_SCSI3_PREEMPTANDABORT:
11968 				un->un_rsvd_status |=
11969 				    (ST_APPLICATION_RESERVATIONS | ST_RESERVE);
11970 				un->un_rsvd_status &= ~(ST_RELEASE |
11971 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11972 				    ST_INITIATED_RESET);
11973 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11974 				    "PGR Reserve and set: entering"
11975 				    " ST_APPLICATION_RESERVATIONS mode");
11976 				break;
11977 			case ST_SA_SCSI3_REGISTER:
11978 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11979 				    "PGR Reserve register key");
11980 				un->un_rsvd_status |= ST_INIT_RESERVE;
11981 				break;
11982 			case ST_SA_SCSI3_CLEAR:
11983 				un->un_rsvd_status &= ~ST_INIT_RESERVE;
11984 				/* FALLTHROUGH */
11985 			case ST_SA_SCSI3_RELEASE:
11986 				un->un_rsvd_status &=
11987 				    ~(ST_APPLICATION_RESERVATIONS | ST_RESERVE |
11988 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11989 				    ST_INITIATED_RESET);
11990 				un->un_rsvd_status |= ST_RELEASE;
11991 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11992 				    "PGR Release and reset: exiting"
11993 				    " ST_APPLICATION_RESERVATIONS mode");
11994 				break;
11995 			}
11996 			new_lastop = ST_OP_CTL;
11997 			break;
11998 		case SCMD_TEST_UNIT_READY:
11999 		case SCMD_READ_BLKLIM:
12000 		case SCMD_REQUEST_SENSE:
12001 		case SCMD_INQUIRY:
12002 		case SCMD_RECOVER_BUF:
12003 		case SCMD_MODE_SELECT:
12004 		case SCMD_MODE_SENSE:
12005 		case SCMD_DOORLOCK:
12006 		case SCMD_READ_BUFFER:
12007 		case SCMD_REPORT_DENSITIES:
12008 		case SCMD_LOG_SELECT_G1:
12009 		case SCMD_LOG_SENSE_G1:
12010 		case SCMD_REPORT_LUNS:
12011 		case SCMD_READ_ATTRIBUTE:
12012 		case SCMD_WRITE_ATTRIBUTE:
12013 		case SCMD_SVC_ACTION_IN_G5:
12014 		case SCMD_SECURITY_PROTO_IN:
12015 		case SCMD_SECURITY_PROTO_OUT:
12016 			new_lastop = ST_OP_CTL;
12017 			break;
12018 		case SCMD_READ_POSITION:
12019 			new_lastop = ST_OP_CTL;
12020 			/*
12021 			 * Only if the buf used was un_sbufp.
12022 			 * Among other things the prevents read positions used
12023 			 * as part of error recovery from messing up our
12024 			 * current position as they will use un_recov_buf.
12025 			 */
12026 			if (USCSI_CMD(bp)) {
12027 				(void) st_get_read_pos(un, bp);
12028 			}
12029 			break;
12030 		case SCMD_LOCATE:
12031 		case SCMD_LOCATE_G4:
12032 			/* Locate makes position mode no longer legacy */
12033 			un->un_lastop = new_lastop = ST_OP_CTL;
12034 			break;
12035 		case SCMD_MAINTENANCE_IN:
12036 			switch (sp->pkt_cdbp[1]) {
12037 			case SSVC_ACTION_GET_SUPPORTED_OPERATIONS:
12038 			case SSVC_ACTION_SET_TARGET_PORT_GROUPS:
12039 				new_lastop = ST_OP_CTL;
12040 				break;
12041 			}
12042 			if (new_lastop != ST_OP_NIL) {
12043 				break;
12044 			}
12045 			/* FALLTHROUGH */
12046 		default:
12047 			/*
12048 			 * Unknown command, If was USCSI and USCSI_SILENT
12049 			 * flag was not set, set position to unknown.
12050 			 */
12051 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
12052 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
12053 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
12054 				    "unknown cmd 0x%X caused loss of state\n",
12055 				    cmd);
12056 			} else {
12057 				/*
12058 				 * keep the old agreement to allow unknown
12059 				 * commands with the USCSI_SILENT set.
12060 				 * This prevents ASSERT below.
12061 				 */
12062 				new_lastop = ST_OP_CTL;
12063 				break;
12064 			}
12065 			/* FALLTHROUGH */
12066 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
12067 			un->un_pos.pmode = invalid;
12068 			un->un_lastop = new_lastop = ST_OP_CTL;
12069 			break;
12070 		}
12071 
12072 		/* new_lastop should have been changed */
12073 		ASSERT(new_lastop != ST_OP_NIL);
12074 
12075 		/* If un_lastop should copy new_lastop  */
12076 		if (((un->un_lastop == ST_OP_WRITE) ||
12077 		    (un->un_lastop == ST_OP_WEOF)) &&
12078 		    new_lastop != ST_OP_CTL) {
12079 			un->un_lastop = new_lastop;
12080 		}
12081 	}
12082 
12083 	/*
12084 	 * In the st driver we have a logical and physical file position.
12085 	 * Under BSD behavior, when you get a zero read, the logical position
12086 	 * is before the filemark but after the last record of the file.
12087 	 * The physical position is after the filemark. MTIOCGET should always
12088 	 * return the logical file position.
12089 	 *
12090 	 * The next read gives a silent skip to the next file.
12091 	 * Under SVR4, the logical file position remains before the filemark
12092 	 * until the file is closed or a space operation is performed.
12093 	 * Hence set err_resid and err_file before changing fileno if case
12094 	 * BSD Behaviour.
12095 	 */
12096 	un->un_err_resid = bp->b_resid;
12097 	COPY_POS(&un->un_err_pos, &un->un_pos);
12098 
12099 
12100 	/*
12101 	 * If we've seen a filemark via the last read operation
12102 	 * advance the file counter, but mark things such that
12103 	 * the next read operation gets a zero count. We have
12104 	 * to put this here to handle the case of sitting right
12105 	 * at the end of a tape file having seen the file mark,
12106 	 * but the tape is closed and then re-opened without
12107 	 * any further i/o. That is, the position information
12108 	 * must be updated before a close.
12109 	 */
12110 
12111 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
12112 		/*
12113 		 * If we're a 1/2" tape, and we get a filemark
12114 		 * right on block 0, *AND* we were not in the
12115 		 * first file on the tape, and we've hit logical EOM.
12116 		 * We'll mark the state so that later we do the
12117 		 * right thing (in st_close(), st_strategy() or
12118 		 * st_ioctl()).
12119 		 *
12120 		 */
12121 		if ((un->un_dp->options & ST_REEL) &&
12122 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
12123 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
12124 			un->un_pos.eof = ST_EOT_PENDING;
12125 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12126 			    "eot pending\n");
12127 			un->un_pos.fileno++;
12128 			un->un_pos.blkno = 0;
12129 		} else if (BP_UCMD(bp)) {
12130 			/*
12131 			 * Uscsi reads have no concept of Berkley ver System IV.
12132 			 * Counts here must match raw device.
12133 			 * A non-full resid implies fix block mode where an
12134 			 * attempt to read X blocks resulted in less then X.
12135 			 */
12136 			if (bp->b_resid != bp->b_bcount) {
12137 				un->un_pos.eof = ST_EOF;
12138 			} else {
12139 				/* Read over a file mark */
12140 				un->un_pos.fileno++;
12141 				/* logical block is counted up elsewhere */
12142 				/* we're before the first block in next file */
12143 				un->un_pos.blkno = 0;
12144 				/* EOF is no longer pending */
12145 				un->un_pos.eof = ST_NO_EOF;
12146 			}
12147 		} else if (BSD_BEHAVIOR) {
12148 			/*
12149 			 * If the read of the filemark was a side effect
12150 			 * of reading some blocks (i.e., data was actually
12151 			 * read), then the EOF mark is pending and the
12152 			 * bump into the next file awaits the next read
12153 			 * operation (which will return a zero count), or
12154 			 * a close or a space operation, else the bump
12155 			 * into the next file occurs now.
12156 			 */
12157 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12158 			    "resid=%lx, bcount=%lx\n",
12159 			    bp->b_resid, bp->b_bcount);
12160 
12161 			if (bp->b_resid != bp->b_bcount) {
12162 				un->un_pos.eof = ST_EOF;
12163 			} else {
12164 				un->un_silent_skip = 1;
12165 				un->un_pos.eof = ST_NO_EOF;
12166 				un->un_pos.fileno++;
12167 				un->un_pos.lgclblkno++;
12168 				un->un_save_blkno = un->un_pos.blkno;
12169 				un->un_pos.blkno = 0;
12170 			}
12171 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12172 			    "eof of file %d, eof=%d\n",
12173 			    un->un_pos.fileno, un->un_pos.eof);
12174 		} else if (SVR4_BEHAVIOR) {
12175 			/*
12176 			 * If the read of the filemark was a side effect
12177 			 * of reading some blocks (i.e., data was actually
12178 			 * read), then the next read should return 0
12179 			 */
12180 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12181 			    "resid=%lx, bcount=%lx\n",
12182 			    bp->b_resid, bp->b_bcount);
12183 			if (bp->b_resid == bp->b_bcount) {
12184 				un->un_pos.eof = ST_EOF;
12185 			}
12186 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12187 			    "eof of file=%d, eof=%d\n",
12188 			    un->un_pos.fileno, un->un_pos.eof);
12189 		}
12190 	}
12191 }
12192 
12193 /*
12194  * set the correct un_errno, to take corner cases into consideration
12195  */
12196 static void
12197 st_set_pe_errno(struct scsi_tape *un)
12198 {
12199 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
12200 
12201 	ASSERT(mutex_owned(ST_MUTEX));
12202 
12203 	/* if errno is already set, don't reset it */
12204 	if (un->un_errno)
12205 		return;
12206 
12207 	/* here un_errno == 0 */
12208 	/*
12209 	 * if the last transfer before flushing all the
12210 	 * waiting I/O's, was 0 (resid = count), then we
12211 	 * want to give the user an error on all the rest,
12212 	 * so here.  If there was a transfer, we set the
12213 	 * resid and counts to 0, and let it drop through,
12214 	 * giving a zero return.  the next I/O will then
12215 	 * give an error.
12216 	 */
12217 	if (un->un_last_resid == un->un_last_count) {
12218 		switch (un->un_pos.eof) {
12219 		case ST_EOM:
12220 			un->un_errno = ENOMEM;
12221 			break;
12222 		case ST_EOT:
12223 		case ST_EOF:
12224 			un->un_errno = EIO;
12225 			break;
12226 		}
12227 	} else {
12228 		/*
12229 		 * we know they did not have a zero, so make
12230 		 * sure they get one
12231 		 */
12232 		un->un_last_resid = un->un_last_count = 0;
12233 	}
12234 }
12235 
12236 
12237 /*
12238  * send in a marker pkt to terminate flushing of commands by BBA (via
12239  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
12240  */
12241 static void
12242 st_hba_unflush(struct scsi_tape *un)
12243 {
12244 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
12245 
12246 	ASSERT(mutex_owned(ST_MUTEX));
12247 
12248 	if (!un->un_flush_on_errors)
12249 		return;
12250 
12251 #ifdef FLUSH_ON_ERRORS
12252 
12253 	if (!un->un_mkr_pkt) {
12254 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
12255 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
12256 
12257 		/* we slept, so it must be there */
12258 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
12259 	}
12260 
12261 	st_transport(un, un->un_mkr_pkt);
12262 #endif
12263 }
12264 
12265 static char *
12266 st_print_scsi_cmd(char cmd)
12267 {
12268 	char tmp[64];
12269 	char *cpnt;
12270 
12271 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
12272 	/* tmp goes out of scope on return and caller sees garbage */
12273 	if (cpnt == tmp) {
12274 		cpnt = "Unknown Command";
12275 	}
12276 	return (cpnt);
12277 }
12278 
12279 static void
12280 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
12281     char *title, char *cdb)
12282 {
12283 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
12284 	char buf[256];
12285 	struct scsi_tape *un;
12286 	int instance = ddi_get_instance(dip);
12287 
12288 	un = ddi_get_soft_state(st_state, instance);
12289 
12290 	ST_FUNC(dip, st_print_cdb);
12291 
12292 	/* force one line output so repeated commands are printed once */
12293 	if ((st_debug & 0x180) == 0x100) {
12294 		scsi_log(dip, label, level, "node %s cmd %s\n",
12295 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
12296 		return;
12297 	}
12298 
12299 	/* force one line output so repeated CDB's are printed once */
12300 	if ((st_debug & 0x180) == 0x80) {
12301 		st_clean_print(dip, label, level, NULL, cdb, len);
12302 	} else {
12303 		(void) sprintf(buf, "%s for cmd(%s)", title,
12304 		    st_print_scsi_cmd(*cdb));
12305 		st_clean_print(dip, label, level, buf, cdb, len);
12306 	}
12307 }
12308 
12309 static void
12310 st_clean_print(dev_info_t *dev, char *label, uint_t level,
12311     char *title, char *data, int len)
12312 {
12313 	int	i;
12314 	int 	c;
12315 	char	*format;
12316 	char	buf[256];
12317 	uchar_t	byte;
12318 
12319 	ST_FUNC(dev, st_clean_print);
12320 
12321 
12322 	if (title) {
12323 		(void) sprintf(buf, "%s:\n", title);
12324 		scsi_log(dev, label, level, "%s", buf);
12325 		level = CE_CONT;
12326 	}
12327 
12328 	for (i = 0; i < len; ) {
12329 		buf[0] = 0;
12330 		for (c = 0; c < 8 && i < len; c++, i++) {
12331 			byte = (uchar_t)data[i];
12332 			if (byte < 0x10)
12333 				format = "0x0%x ";
12334 			else
12335 				format = "0x%x ";
12336 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
12337 		}
12338 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
12339 
12340 		scsi_log(dev, label, level, "%s\n", buf);
12341 		level = CE_CONT;
12342 	}
12343 }
12344 
12345 /*
12346  * Conditionally enabled debugging
12347  */
12348 #ifdef	STDEBUG
12349 static void
12350 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
12351 {
12352 	char tmpbuf[64];
12353 
12354 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
12355 
12356 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12357 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
12358 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
12359 	    count, count,
12360 	    wait == ASYNC_CMD ? "a" : "");
12361 }
12362 #endif	/* STDEBUG */
12363 
12364 /*
12365  * Returns pointer to name of minor node name of device 'dev'.
12366  */
12367 static char *
12368 st_dev_name(dev_t dev)
12369 {
12370 	struct scsi_tape *un;
12371 	const char density[] = { 'l', 'm', 'h', 'c' };
12372 	static char name[32];
12373 	minor_t minor;
12374 	int instance;
12375 	int nprt = 0;
12376 
12377 	minor = getminor(dev);
12378 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
12379 	un = ddi_get_soft_state(st_state, instance);
12380 	if (un) {
12381 		ST_FUNC(ST_DEVINFO, st_dev_name);
12382 	}
12383 
12384 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
12385 
12386 	if (minor & MT_BSD) {
12387 		name[++nprt] = 'b';
12388 	}
12389 
12390 	if (minor & MT_NOREWIND) {
12391 		name[++nprt] = 'n';
12392 	}
12393 
12394 	/* NULL terminator */
12395 	name[++nprt] = 0;
12396 
12397 	return (name);
12398 }
12399 
12400 /*
12401  * Soft error reporting, so far unique to each drive
12402  *
12403  * Currently supported: exabyte and DAT soft error reporting
12404  */
12405 static int
12406 st_report_exabyte_soft_errors(dev_t dev, int flag)
12407 {
12408 	uchar_t *sensep;
12409 	int amt;
12410 	int rval = 0;
12411 	char cdb[CDB_GROUP0], *c = cdb;
12412 	struct uscsi_cmd *com;
12413 
12414 	GET_SOFT_STATE(dev);
12415 
12416 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
12417 
12418 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12419 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
12420 	    dev, flag);
12421 
12422 	ASSERT(mutex_owned(ST_MUTEX));
12423 
12424 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12425 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
12426 
12427 	*c++ = SCMD_REQUEST_SENSE;
12428 	*c++ = 0;
12429 	*c++ = 0;
12430 	*c++ = 0;
12431 	*c++ = TAPE_SENSE_LENGTH;
12432 	/*
12433 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
12434 	 */
12435 	*c   = (char)0x80;
12436 
12437 	com->uscsi_cdb = cdb;
12438 	com->uscsi_cdblen = CDB_GROUP0;
12439 	com->uscsi_bufaddr = (caddr_t)sensep;
12440 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
12441 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12442 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12443 
12444 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12445 	if (rval || com->uscsi_status) {
12446 		goto done;
12447 	}
12448 
12449 	/*
12450 	 * was there enough data?
12451 	 */
12452 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
12453 
12454 	if ((amt >= 19) && un->un_kbytes_xferred) {
12455 		uint_t count, error_rate;
12456 		uint_t rate;
12457 
12458 		if (sensep[21] & CLN) {
12459 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12460 			    "Periodic head cleaning required");
12461 		}
12462 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
12463 			goto done;
12464 		}
12465 		/*
12466 		 * check if soft error reporting needs to be done.
12467 		 */
12468 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
12469 		count &= 0xffffff;
12470 		error_rate = (count * 100)/un->un_kbytes_xferred;
12471 
12472 #ifdef	STDEBUG
12473 		if (st_soft_error_report_debug) {
12474 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12475 			    "Exabyte Soft Error Report:\n");
12476 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12477 			    "read/write error counter: %d\n", count);
12478 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12479 			    "number of bytes transferred: %dK\n",
12480 			    un->un_kbytes_xferred);
12481 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12482 			    "error_rate: %d%%\n", error_rate);
12483 
12484 			if (amt >= 22) {
12485 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12486 				    "unit sense: 0x%b 0x%b 0x%b\n",
12487 				    sensep[19], SENSE_19_BITS,
12488 				    sensep[20], SENSE_20_BITS,
12489 				    sensep[21], SENSE_21_BITS);
12490 			}
12491 			if (amt >= 27) {
12492 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12493 				    "tracking retry counter: %d\n",
12494 				    sensep[26]);
12495 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12496 				    "read/write retry counter: %d\n",
12497 				    sensep[27]);
12498 			}
12499 		}
12500 #endif
12501 
12502 		if (flag & FWRITE) {
12503 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
12504 		} else {
12505 			rate = EXABYTE_READ_ERROR_THRESHOLD;
12506 		}
12507 		if (error_rate >= rate) {
12508 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12509 			    "Soft error rate (%d%%) during %s was too high",
12510 			    error_rate,
12511 			    ((flag & FWRITE) ? wrg_str : rdg_str));
12512 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12513 			    "Please, replace tape cartridge\n");
12514 		}
12515 	}
12516 
12517 done:
12518 	kmem_free(com, sizeof (*com));
12519 	kmem_free(sensep, TAPE_SENSE_LENGTH);
12520 
12521 	if (rval != 0) {
12522 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12523 		    "exabyte soft error reporting failed\n");
12524 	}
12525 	return (rval);
12526 }
12527 
12528 /*
12529  * this is very specific to Archive 4mm dat
12530  */
12531 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
12532 
12533 static int
12534 st_report_dat_soft_errors(dev_t dev, int flag)
12535 {
12536 	uchar_t *sensep;
12537 	int amt, i;
12538 	int rval = 0;
12539 	char cdb[CDB_GROUP1], *c = cdb;
12540 	struct uscsi_cmd *com;
12541 	struct scsi_arq_status status;
12542 
12543 	GET_SOFT_STATE(dev);
12544 
12545 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
12546 
12547 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12548 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12549 
12550 	ASSERT(mutex_owned(ST_MUTEX));
12551 
12552 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12553 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12554 
12555 	*c++ = SCMD_LOG_SENSE_G1;
12556 	*c++ = 0;
12557 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
12558 	*c++ = 0;
12559 	*c++ = 0;
12560 	*c++ = 0;
12561 	*c++ = 2;
12562 	*c++ = 0;
12563 	*c++ = (char)LOG_SENSE_LENGTH;
12564 	*c   = 0;
12565 	com->uscsi_cdb    = cdb;
12566 	com->uscsi_cdblen  = CDB_GROUP1;
12567 	com->uscsi_bufaddr = (caddr_t)sensep;
12568 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
12569 	com->uscsi_rqlen = sizeof (status);
12570 	com->uscsi_rqbuf = (caddr_t)&status;
12571 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
12572 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12573 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12574 	if (rval) {
12575 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12576 		    "DAT soft error reporting failed\n");
12577 	}
12578 	if (rval || com->uscsi_status) {
12579 		goto done;
12580 	}
12581 
12582 	/*
12583 	 * was there enough data?
12584 	 */
12585 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
12586 
12587 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
12588 		int total, retries, param_code;
12589 
12590 		total = -1;
12591 		retries = -1;
12592 		amt = sensep[3] + 4;
12593 
12594 
12595 #ifdef STDEBUG
12596 		if (st_soft_error_report_debug) {
12597 			(void) printf("logsense:");
12598 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
12599 				if (i % 16 == 0) {
12600 					(void) printf("\t\n");
12601 				}
12602 				(void) printf(" %x", sensep[i]);
12603 			}
12604 			(void) printf("\n");
12605 		}
12606 #endif
12607 
12608 		/*
12609 		 * parse the param_codes
12610 		 */
12611 		if (sensep[0] == 2 || sensep[0] == 3) {
12612 			for (i = 4; i < amt; i++) {
12613 				param_code = (sensep[i++] << 8);
12614 				param_code += sensep[i++];
12615 				i++; /* skip control byte */
12616 				if (param_code == 5) {
12617 					if (sensep[i++] == 4) {
12618 						total = (sensep[i++] << 24);
12619 						total += (sensep[i++] << 16);
12620 						total += (sensep[i++] << 8);
12621 						total += sensep[i];
12622 					}
12623 				} else if (param_code == 0x8007) {
12624 					if (sensep[i++] == 2) {
12625 						retries = sensep[i++] << 8;
12626 						retries += sensep[i];
12627 					}
12628 				} else {
12629 					i += sensep[i];
12630 				}
12631 			}
12632 		}
12633 
12634 		/*
12635 		 * if the log sense returned valid numbers then determine
12636 		 * the read and write error thresholds based on the amount of
12637 		 * data transferred
12638 		 */
12639 
12640 		if (total > 0 && retries > 0) {
12641 			short normal_retries = 0;
12642 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12643 			    "total xferred (%s) =%x, retries=%x\n",
12644 			    ((flag & FWRITE) ? wrg_str : rdg_str),
12645 			    total, retries);
12646 
12647 			if (flag & FWRITE) {
12648 				if (total <=
12649 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
12650 					normal_retries =
12651 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
12652 				} else {
12653 					normal_retries =
12654 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
12655 				}
12656 			} else {
12657 				if (total <=
12658 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
12659 					normal_retries =
12660 					    DAT_SMALL_READ_ERROR_THRESHOLD;
12661 				} else {
12662 					normal_retries =
12663 					    DAT_LARGE_READ_ERROR_THRESHOLD;
12664 				}
12665 			}
12666 
12667 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12668 			"normal retries=%d\n", normal_retries);
12669 
12670 			if (retries >= normal_retries) {
12671 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12672 				    "Soft error rate (retries = %d) during "
12673 				    "%s was too high",  retries,
12674 				    ((flag & FWRITE) ? wrg_str : rdg_str));
12675 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12676 				    "Periodic head cleaning required "
12677 				    "and/or replace tape cartridge\n");
12678 			}
12679 
12680 		} else if (total == -1 || retries == -1) {
12681 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12682 			    "log sense parameter code does not make sense\n");
12683 		}
12684 	}
12685 
12686 	/*
12687 	 * reset all values
12688 	 */
12689 	c = cdb;
12690 	*c++ = SCMD_LOG_SELECT_G1;
12691 	*c++ = 2;	/* this resets all values */
12692 	*c++ = (char)0xc0;
12693 	*c++ = 0;
12694 	*c++ = 0;
12695 	*c++ = 0;
12696 	*c++ = 0;
12697 	*c++ = 0;
12698 	*c++ = 0;
12699 	*c   = 0;
12700 	com->uscsi_bufaddr = NULL;
12701 	com->uscsi_buflen  = 0;
12702 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
12703 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12704 	if (rval) {
12705 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12706 		    "DAT soft error reset failed\n");
12707 	}
12708 done:
12709 	kmem_free(com, sizeof (*com));
12710 	kmem_free(sensep, LOG_SENSE_LENGTH);
12711 	return (rval);
12712 }
12713 
12714 static int
12715 st_report_soft_errors(dev_t dev, int flag)
12716 {
12717 	GET_SOFT_STATE(dev);
12718 
12719 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
12720 
12721 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12722 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12723 
12724 	ASSERT(mutex_owned(ST_MUTEX));
12725 
12726 	switch (un->un_dp->type) {
12727 	case ST_TYPE_EXB8500:
12728 	case ST_TYPE_EXABYTE:
12729 		return (st_report_exabyte_soft_errors(dev, flag));
12730 		/*NOTREACHED*/
12731 	case ST_TYPE_PYTHON:
12732 		return (st_report_dat_soft_errors(dev, flag));
12733 		/*NOTREACHED*/
12734 	default:
12735 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
12736 		return (-1);
12737 	}
12738 }
12739 
12740 /*
12741  * persistent error routines
12742  */
12743 
12744 /*
12745  * enable persistent errors, and set the throttle appropriately, checking
12746  * for flush-on-errors capability
12747  */
12748 static void
12749 st_turn_pe_on(struct scsi_tape *un)
12750 {
12751 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
12752 
12753 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
12754 	ASSERT(mutex_owned(ST_MUTEX));
12755 
12756 	un->un_persistence = 1;
12757 
12758 	/*
12759 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
12760 	 * enabled.  This will simplify the error handling for request senses
12761 	 */
12762 
12763 	if (un->un_arq_enabled && un->un_untagged_qing) {
12764 		uchar_t f_o_e;
12765 
12766 		mutex_exit(ST_MUTEX);
12767 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
12768 		    1 : 0;
12769 		mutex_enter(ST_MUTEX);
12770 
12771 		un->un_flush_on_errors = f_o_e;
12772 	} else {
12773 		un->un_flush_on_errors = 0;
12774 	}
12775 
12776 	if (un->un_flush_on_errors)
12777 		un->un_max_throttle = (uchar_t)st_max_throttle;
12778 	else
12779 		un->un_max_throttle = 1;
12780 
12781 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
12782 		un->un_max_throttle = 1;
12783 
12784 	/* this will send a marker pkt */
12785 	st_clear_pe(un);
12786 }
12787 
12788 /*
12789  * This turns persistent errors permanently off
12790  */
12791 static void
12792 st_turn_pe_off(struct scsi_tape *un)
12793 {
12794 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
12795 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
12796 	ASSERT(mutex_owned(ST_MUTEX));
12797 
12798 	/* turn it off for good */
12799 	un->un_persistence = 0;
12800 
12801 	/* this will send a marker pkt */
12802 	st_clear_pe(un);
12803 
12804 	/* turn off flush on error capability, if enabled */
12805 	if (un->un_flush_on_errors) {
12806 		mutex_exit(ST_MUTEX);
12807 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
12808 		mutex_enter(ST_MUTEX);
12809 	}
12810 
12811 
12812 	un->un_flush_on_errors = 0;
12813 }
12814 
12815 /*
12816  * This clear persistent errors, allowing more commands through, and also
12817  * sending a marker packet.
12818  */
12819 static void
12820 st_clear_pe(struct scsi_tape *un)
12821 {
12822 	ST_FUNC(ST_DEVINFO, st_clear_pe);
12823 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
12824 	ASSERT(mutex_owned(ST_MUTEX));
12825 
12826 	un->un_persist_errors = 0;
12827 	un->un_throttle = un->un_last_throttle = 1;
12828 	un->un_errno = 0;
12829 	st_hba_unflush(un);
12830 }
12831 
12832 /*
12833  * This will flag persistent errors, shutting everything down, if the
12834  * application had enabled persistent errors via MTIOCPERSISTENT
12835  */
12836 static void
12837 st_set_pe_flag(struct scsi_tape *un)
12838 {
12839 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
12840 	ASSERT(mutex_owned(ST_MUTEX));
12841 
12842 	if (un->un_persistence) {
12843 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
12844 		un->un_persist_errors = 1;
12845 		un->un_throttle = un->un_last_throttle = 0;
12846 		cv_broadcast(&un->un_sbuf_cv);
12847 	}
12848 }
12849 
12850 static int
12851 st_do_reserve(struct scsi_tape *un)
12852 {
12853 	int rval;
12854 	int was_lost = un->un_rsvd_status & ST_LOST_RESERVE;
12855 
12856 	ST_FUNC(ST_DEVINFO, st_do_reserve);
12857 
12858 	/*
12859 	 * Issue a Throw-Away reserve command to clear the
12860 	 * check condition.
12861 	 * If the current behaviour of reserve/release is to
12862 	 * hold reservation across opens , and if a Bus reset
12863 	 * has been issued between opens then this command
12864 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
12865 	 * In this case return an EACCES so that user knows that
12866 	 * reservation has been lost in between opens.
12867 	 * If this error is not returned and we continue with
12868 	 * successful open , then user may think position of the
12869 	 * tape is still the same but inreality we would rewind the
12870 	 * tape and continue from BOT.
12871 	 */
12872 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12873 	if (rval) {
12874 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
12875 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
12876 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
12877 			un->un_errno = EACCES;
12878 			return (EACCES);
12879 		}
12880 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12881 	}
12882 	if (rval == 0) {
12883 		un->un_rsvd_status |= ST_INIT_RESERVE;
12884 	}
12885 	if (was_lost) {
12886 		un->un_running.pmode = invalid;
12887 	}
12888 
12889 	return (rval);
12890 }
12891 
12892 static int
12893 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb)
12894 {
12895 	int rval;
12896 	cmd_attribute const *attrib;
12897 
12898 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
12899 
12900 	/*
12901 	 * If already reserved no need to do it again.
12902 	 * Also if Reserve and Release are disabled Just return.
12903 	 */
12904 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12905 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12906 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12907 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12908 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
12909 		    st_print_scsi_cmd((uchar_t)cdb[0]));
12910 		return (0);
12911 	}
12912 
12913 	/* See if command is on the list */
12914 	attrib = st_lookup_cmd_attribute(cdb[0]);
12915 
12916 	if (attrib == NULL) {
12917 		rval = 1; /* Not found, when in doubt reserve */
12918 	} else if ((attrib->requires_reserve) != 0) {
12919 		rval = 1;
12920 	} else if ((attrib->reserve_byte) != 0) {
12921 		/*
12922 		 * cmd is on list.
12923 		 * if byte is zero always allowed.
12924 		 */
12925 		rval = 1;
12926 	} else if (((cdb[attrib->reserve_byte]) &
12927 	    (attrib->reserve_mask)) != 0) {
12928 		rval = 1;
12929 	} else {
12930 		rval = 0;
12931 	}
12932 
12933 	if (rval) {
12934 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12935 		    "Command %s requires reservation",
12936 		    st_print_scsi_cmd(cdb[0]));
12937 
12938 		rval = st_do_reserve(un);
12939 	}
12940 
12941 	return (rval);
12942 }
12943 
12944 static int
12945 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
12946 {
12947 	int rval;
12948 	cmd_attribute const *attrib;
12949 
12950 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
12951 
12952 	/*
12953 	 * Do not reserve when already reserved, when not supported or when
12954 	 * auto-rewinding on device closure.
12955 	 */
12956 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12957 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12958 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE) ||
12959 	    ((un->un_state == ST_STATE_CLOSING) && (cmd == SCMD_REWIND))) {
12960 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12961 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
12962 		    st_print_scsi_cmd(cmd));
12963 		return (0);
12964 	}
12965 
12966 	/* search for this command on the list */
12967 	attrib = st_lookup_cmd_attribute(cmd);
12968 
12969 	if (attrib == NULL) {
12970 		rval = 1; /* Not found, when in doubt reserve */
12971 	} else if ((attrib->requires_reserve) != 0) {
12972 		rval = 1;
12973 	} else if ((attrib->reserve_byte) != 0) {
12974 		/*
12975 		 * cmd is on list.
12976 		 * if byte is zero always allowed.
12977 		 */
12978 		rval = 1;
12979 	} else if (((attrib->reserve_mask) & cnt) != 0) {
12980 		rval = 1;
12981 	} else {
12982 		rval = 0;
12983 	}
12984 
12985 	if (rval) {
12986 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12987 		    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
12988 
12989 		rval = st_do_reserve(un);
12990 	}
12991 
12992 	return (rval);
12993 }
12994 
12995 static int
12996 st_reserve_release(struct scsi_tape *un, int cmd, ubufunc_t ubf)
12997 {
12998 	struct uscsi_cmd	uscsi_cmd;
12999 	int			rval;
13000 	char			cdb[CDB_GROUP0];
13001 	struct scsi_arq_status	stat;
13002 
13003 
13004 
13005 	ST_FUNC(ST_DEVINFO, st_reserve_release);
13006 
13007 	ASSERT(mutex_owned(ST_MUTEX));
13008 
13009 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13010 	    "st_reserve_release: %s \n",
13011 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
13012 
13013 	bzero(&cdb, CDB_GROUP0);
13014 	if (cmd == ST_RELEASE) {
13015 		cdb[0] = SCMD_RELEASE;
13016 	} else {
13017 		cdb[0] = SCMD_RESERVE;
13018 	}
13019 	bzero(&uscsi_cmd, sizeof (struct uscsi_cmd));
13020 	uscsi_cmd.uscsi_flags = USCSI_WRITE | USCSI_RQENABLE;
13021 	uscsi_cmd.uscsi_cdb = cdb;
13022 	uscsi_cmd.uscsi_cdblen = CDB_GROUP0;
13023 	uscsi_cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
13024 	uscsi_cmd.uscsi_rqbuf = (caddr_t)&stat;
13025 	uscsi_cmd.uscsi_rqlen = sizeof (stat);
13026 
13027 	rval = ubf(un, &uscsi_cmd, FKIOCTL);
13028 
13029 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13030 	    "st_reserve_release: rval(1)=%d\n", rval);
13031 
13032 	if (rval) {
13033 		if (uscsi_cmd.uscsi_status == STATUS_RESERVATION_CONFLICT) {
13034 			rval = EACCES;
13035 		}
13036 		/*
13037 		 * dynamically turn off reserve/release support
13038 		 * in case of drives which do not support
13039 		 * reserve/release command(ATAPI drives).
13040 		 */
13041 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
13042 			if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
13043 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
13044 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13045 				    "Tape unit does not support "
13046 				    "reserve/release \n");
13047 			}
13048 			rval = 0;
13049 		}
13050 	}
13051 	return (rval);
13052 }
13053 
13054 static int
13055 st_take_ownership(struct scsi_tape *un, ubufunc_t ubf)
13056 {
13057 	int rval;
13058 
13059 	ST_FUNC(ST_DEVINFO, st_take_ownership);
13060 
13061 	ASSERT(mutex_owned(ST_MUTEX));
13062 
13063 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13064 	    "st_take_ownership: Entering ...\n");
13065 
13066 
13067 	rval = st_reserve_release(un, ST_RESERVE, ubf);
13068 	/*
13069 	 * XXX -> Should reset be done only if we get EACCES.
13070 	 * .
13071 	 */
13072 	if (rval) {
13073 		if (st_reset(un, RESET_LUN) == 0) {
13074 			return (EIO);
13075 		}
13076 		un->un_rsvd_status &=
13077 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
13078 
13079 		mutex_exit(ST_MUTEX);
13080 		delay(drv_usectohz(ST_RESERVATION_DELAY));
13081 		mutex_enter(ST_MUTEX);
13082 		/*
13083 		 * remove the check condition.
13084 		 */
13085 		(void) st_reserve_release(un, ST_RESERVE, ubf);
13086 		rval = st_reserve_release(un, ST_RESERVE, ubf);
13087 		if (rval != 0) {
13088 			if ((st_reserve_release(un, ST_RESERVE, ubf))
13089 			    != 0) {
13090 				rval = (un->un_rsvd_status &
13091 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
13092 				return (rval);
13093 			}
13094 		}
13095 		/*
13096 		 * Set tape state to ST_STATE_OFFLINE , in case if
13097 		 * the user wants to continue and start using
13098 		 * the tape.
13099 		 */
13100 		un->un_state = ST_STATE_OFFLINE;
13101 		un->un_rsvd_status |= ST_INIT_RESERVE;
13102 	}
13103 	return (rval);
13104 }
13105 
13106 static int
13107 st_create_errstats(struct scsi_tape *un, int instance)
13108 {
13109 	char	kstatname[KSTAT_STRLEN];
13110 
13111 	ST_FUNC(ST_DEVINFO, st_create_errstats);
13112 
13113 	/*
13114 	 * Create device error kstats
13115 	 */
13116 
13117 	if (un->un_errstats == (kstat_t *)0) {
13118 		(void) sprintf(kstatname, "st%d,err", instance);
13119 		un->un_errstats = kstat_create("sterr", instance, kstatname,
13120 		    "device_error", KSTAT_TYPE_NAMED,
13121 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
13122 		    KSTAT_FLAG_PERSISTENT);
13123 
13124 		if (un->un_errstats) {
13125 			struct st_errstats	*stp;
13126 
13127 			stp = (struct st_errstats *)un->un_errstats->ks_data;
13128 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
13129 			    KSTAT_DATA_ULONG);
13130 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
13131 			    KSTAT_DATA_ULONG);
13132 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
13133 			    KSTAT_DATA_ULONG);
13134 			kstat_named_init(&stp->st_vid, "Vendor",
13135 			    KSTAT_DATA_CHAR);
13136 			kstat_named_init(&stp->st_pid, "Product",
13137 			    KSTAT_DATA_CHAR);
13138 			kstat_named_init(&stp->st_revision, "Revision",
13139 			    KSTAT_DATA_CHAR);
13140 			kstat_named_init(&stp->st_serial, "Serial No",
13141 			    KSTAT_DATA_CHAR);
13142 			un->un_errstats->ks_private = un;
13143 			un->un_errstats->ks_update = nulldev;
13144 			kstat_install(un->un_errstats);
13145 			/*
13146 			 * Fill in the static data
13147 			 */
13148 			(void) strncpy(&stp->st_vid.value.c[0],
13149 			    ST_INQUIRY->inq_vid, 8);
13150 			/*
13151 			 * XXX:  Emulex MT-02 (and emulators) predates
13152 			 *	 SCSI-1 and has no vid & pid inquiry data.
13153 			 */
13154 			if (ST_INQUIRY->inq_len != 0) {
13155 				(void) strncpy(&stp->st_pid.value.c[0],
13156 				    ST_INQUIRY->inq_pid, 16);
13157 				(void) strncpy(&stp->st_revision.value.c[0],
13158 				    ST_INQUIRY->inq_revision, 4);
13159 			}
13160 		}
13161 	}
13162 	return (0);
13163 }
13164 
13165 static int
13166 st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos)
13167 {
13168 	int rval;
13169 	bufunc_t bf = (ubf == st_uscsi_rcmd) ? st_rcmd : st_cmd;
13170 
13171 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
13172 
13173 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
13174 	ASSERT(mutex_owned(ST_MUTEX));
13175 
13176 	/* Can't restore an invalid position */
13177 	if (pos->pmode == invalid) {
13178 		return (4);
13179 	}
13180 
13181 	/*
13182 	 * Assumtions:
13183 	 *	If a position was read and is in logical position mode.
13184 	 *	If a drive supports read position it supports locate.
13185 	 *	If the read position type is not NO_POS. even though
13186 	 *	   a read position make not have been attemped yet.
13187 	 *
13188 	 *	The drive can locate to the position.
13189 	 */
13190 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
13191 		/*
13192 		 * If position mode is logical or legacy mode try
13193 		 * to locate there as it is faster.
13194 		 * If it fails try the old way.
13195 		 */
13196 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13197 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
13198 		    pos->lgclblkno);
13199 
13200 		if (st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
13201 		    pos->lgclblkno, pos->partition) == 0) {
13202 			/* Assume we are there copy rest of position back */
13203 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
13204 				COPY_POS(&un->un_pos, pos);
13205 			}
13206 			return (0);
13207 		}
13208 
13209 		/*
13210 		 * If logical block locate failed to restore a logical
13211 		 * position, can't recover.
13212 		 */
13213 		if (pos->pmode == logical) {
13214 			return (-1);
13215 		}
13216 	}
13217 
13218 
13219 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13220 	    "Restoring tape position at fileno=%x, blkno=%x....",
13221 	    pos->fileno, pos->blkno);
13222 
13223 	/*
13224 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
13225 	 * so as not to rewind tape on RESETS: Gee, Has life ever
13226 	 * been simple in tape land ?
13227 	 */
13228 	rval = bf(un, SCMD_REWIND, 0, SYNC_CMD);
13229 	if (rval) {
13230 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
13231 		    "Failed to restore the last file and block position: In"
13232 		    " this state, Tape will be loaded at BOT during next open");
13233 		un->un_pos.pmode = invalid;
13234 		return (rval);
13235 	}
13236 
13237 	/* If the position was as the result of back space file */
13238 	if (pos->blkno > (INF / 2)) {
13239 		/* Go one extra file forward */
13240 		pos->fileno++;
13241 		/* Figure how many blocks to back into the previous file */
13242 		pos->blkno = -(INF - pos->blkno);
13243 	}
13244 
13245 	/* Go to requested fileno */
13246 	if (pos->fileno) {
13247 		rval = st_cmd(un, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
13248 		if (rval) {
13249 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13250 			    "Failed to restore the last file position: In this "
13251 			    " state, Tape will be loaded at BOT during next"
13252 			    " open %d", __LINE__);
13253 			un->un_pos.pmode = invalid;
13254 			pos->pmode = invalid;
13255 			return (rval);
13256 		}
13257 	}
13258 
13259 	/*
13260 	 * If backing into a file we already did an extra file forward.
13261 	 * Now we have to back over the filemark to get to the end of
13262 	 * the previous file. The blkno has been ajusted to a negative
13263 	 * value so we will get to the expected location.
13264 	 */
13265 	if (pos->blkno) {
13266 		rval = bf(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
13267 		if (rval) {
13268 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13269 			    "Failed to restore the last file position: In this "
13270 			    " state, Tape will be loaded at BOT during next"
13271 			    " open %d", __LINE__);
13272 			un->un_pos.pmode = invalid;
13273 			pos->pmode = invalid;
13274 			return (rval);
13275 		}
13276 	}
13277 
13278 	/*
13279 	 * The position mode, block and fileno should be correct,
13280 	 * This updates eof and logical position information.
13281 	 */
13282 	un->un_pos.eof = pos->eof;
13283 	un->un_pos.lgclblkno = pos->lgclblkno;
13284 
13285 	return (0);
13286 }
13287 
13288 /*
13289  * check sense key, ASC, ASCQ in order to determine if the tape needs
13290  * to be ejected
13291  */
13292 
13293 static int
13294 st_check_asc_ascq(struct scsi_tape *un)
13295 {
13296 	struct scsi_extended_sense *sensep = ST_RQSENSE;
13297 	struct tape_failure_code   *code;
13298 
13299 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
13300 
13301 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
13302 		if ((code->key  == sensep->es_key) &&
13303 		    (code->add_code  == sensep->es_add_code) &&
13304 		    (code->qual_code == sensep->es_qual_code))
13305 			return (1);
13306 	}
13307 	return (0);
13308 }
13309 
13310 /*
13311  * st_logpage_supported() sends a Log Sense command with
13312  * page code = 0 = Supported Log Pages Page to the device,
13313  * to see whether the page 'page' is supported.
13314  * Return values are:
13315  * -1 if the Log Sense command fails
13316  * 0 if page is not supported
13317  * 1 if page is supported
13318  */
13319 
13320 static int
13321 st_logpage_supported(struct scsi_tape *un, uchar_t page)
13322 {
13323 	uchar_t *sp, *sensep;
13324 	unsigned length;
13325 	struct uscsi_cmd *com;
13326 	struct scsi_arq_status status;
13327 	int rval;
13328 	char cdb[CDB_GROUP1] = {
13329 		SCMD_LOG_SENSE_G1,
13330 		0,
13331 		SUPPORTED_LOG_PAGES_PAGE,
13332 		0,
13333 		0,
13334 		0,
13335 		0,
13336 		0,
13337 		(char)LOG_SENSE_LENGTH,
13338 		0
13339 	};
13340 
13341 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
13342 
13343 	ASSERT(mutex_owned(ST_MUTEX));
13344 
13345 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13346 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
13347 
13348 	com->uscsi_cdb = cdb;
13349 	com->uscsi_cdblen = CDB_GROUP1;
13350 	com->uscsi_bufaddr = (caddr_t)sensep;
13351 	com->uscsi_buflen = LOG_SENSE_LENGTH;
13352 	com->uscsi_rqlen = sizeof (status);
13353 	com->uscsi_rqbuf = (caddr_t)&status;
13354 	com->uscsi_flags =
13355 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13356 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13357 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13358 	if (rval || com->uscsi_status) {
13359 		/* uscsi-command failed */
13360 		rval = -1;
13361 	} else {
13362 
13363 		sp = sensep + 3;
13364 
13365 		for (length = *sp++; length > 0; length--, sp++) {
13366 
13367 			if (*sp == page) {
13368 				rval = 1;
13369 				break;
13370 			}
13371 		}
13372 	}
13373 	kmem_free(com, sizeof (struct uscsi_cmd));
13374 	kmem_free(sensep, LOG_SENSE_LENGTH);
13375 	return (rval);
13376 }
13377 
13378 
13379 /*
13380  * st_check_clean_bit() gets the status of the tape's cleaning bit.
13381  *
13382  * If the device does support the TapeAlert log page, then the cleaning bit
13383  * information will be read from this page. Otherwise we will see if one of
13384  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
13385  * the device, which means, that we can get the cleaning bit information via
13386  * a RequestSense command.
13387  * If both methods of getting cleaning bit information are not supported
13388  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
13389  * returns with
13390  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
13391  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
13392  * If the call to st_uscsi_cmd() to do the Log Sense or the Request Sense
13393  * command fails, or if the amount of Request Sense data is not enough, then
13394  *  st_check_clean_bit() returns with -1.
13395  */
13396 
13397 static int
13398 st_check_clean_bit(struct scsi_tape *un)
13399 {
13400 	int rval = 0;
13401 
13402 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
13403 
13404 	ASSERT(mutex_owned(ST_MUTEX));
13405 
13406 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
13407 		return (rval);
13408 	}
13409 
13410 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13411 
13412 		rval = st_logpage_supported(un, TAPE_SEQUENTIAL_PAGE);
13413 		if (rval == -1) {
13414 			return (0);
13415 		}
13416 		if (rval == 1) {
13417 
13418 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
13419 		}
13420 
13421 		rval = st_logpage_supported(un, TAPE_ALERT_PAGE);
13422 		if (rval == -1) {
13423 			return (0);
13424 		}
13425 		if (rval == 1) {
13426 
13427 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
13428 		}
13429 
13430 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13431 
13432 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
13433 		}
13434 	}
13435 
13436 	rval = 0;
13437 
13438 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
13439 
13440 		rval = st_check_sequential_clean_bit(un);
13441 		if (rval == -1) {
13442 			return (0);
13443 		}
13444 	}
13445 
13446 	if ((rval == 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
13447 
13448 		rval = st_check_alert_flags(un);
13449 		if (rval == -1) {
13450 			return (0);
13451 		}
13452 	}
13453 
13454 	if ((rval == 0) && (un->un_dp->options & ST_CLN_MASK)) {
13455 
13456 		rval = st_check_sense_clean_bit(un);
13457 		if (rval == -1) {
13458 			return (0);
13459 		}
13460 	}
13461 
13462 	/*
13463 	 * If found a supported means to check need to clean.
13464 	 */
13465 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
13466 
13467 		/*
13468 		 * head needs to be cleaned.
13469 		 */
13470 		if (rval & MTF_TAPE_HEAD_DIRTY) {
13471 
13472 			/*
13473 			 * Print log message only first time
13474 			 * found needing cleaned.
13475 			 */
13476 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
13477 
13478 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
13479 				    "Periodic head cleaning required");
13480 
13481 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
13482 			}
13483 
13484 		} else {
13485 
13486 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
13487 		}
13488 	}
13489 
13490 	return (rval);
13491 }
13492 
13493 
13494 static int
13495 st_check_sequential_clean_bit(struct scsi_tape *un)
13496 {
13497 	int rval;
13498 	int ix;
13499 	ushort_t parameter;
13500 	struct uscsi_cmd *cmd;
13501 	struct log_sequential_page *sp;
13502 	struct log_sequential_page_parameter *prm;
13503 	struct scsi_arq_status status;
13504 	char cdb[CDB_GROUP1] = {
13505 		SCMD_LOG_SENSE_G1,
13506 		0,
13507 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
13508 		0,
13509 		0,
13510 		0,
13511 		0,
13512 		(char)(sizeof (struct log_sequential_page) >> 8),
13513 		(char)(sizeof (struct log_sequential_page)),
13514 		0
13515 	};
13516 
13517 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
13518 
13519 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13520 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
13521 
13522 	cmd->uscsi_flags   =
13523 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13524 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13525 	cmd->uscsi_cdb	   = cdb;
13526 	cmd->uscsi_cdblen  = CDB_GROUP1;
13527 	cmd->uscsi_bufaddr = (caddr_t)sp;
13528 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
13529 	cmd->uscsi_rqlen   = sizeof (status);
13530 	cmd->uscsi_rqbuf   = (caddr_t)&status;
13531 
13532 	rval = st_uscsi_cmd(un, cmd, FKIOCTL);
13533 
13534 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
13535 
13536 		rval = -1;
13537 
13538 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
13539 
13540 		rval = -1;
13541 	}
13542 
13543 	prm = &sp->param[0];
13544 
13545 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
13546 
13547 		if (prm->log_param.length == 0) {
13548 			break;
13549 		}
13550 
13551 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
13552 		    (prm->log_param.pc_lo & 0xff));
13553 
13554 		if (parameter == SEQUENTIAL_NEED_CLN) {
13555 
13556 			rval = MTF_TAPE_CLN_SUPPORTED;
13557 			if (prm->param_value[prm->log_param.length - 1]) {
13558 
13559 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13560 				    "sequential log says head dirty\n");
13561 				rval |= MTF_TAPE_HEAD_DIRTY;
13562 			}
13563 		}
13564 		prm = (struct log_sequential_page_parameter *)
13565 		    &prm->param_value[prm->log_param.length];
13566 	}
13567 
13568 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13569 	kmem_free(sp,  sizeof (struct log_sequential_page));
13570 
13571 	return (rval);
13572 }
13573 
13574 
13575 static int
13576 st_check_alert_flags(struct scsi_tape *un)
13577 {
13578 	struct st_tape_alert *ta;
13579 	struct uscsi_cmd *com;
13580 	struct scsi_arq_status status;
13581 	unsigned ix, length;
13582 	int rval;
13583 	tape_alert_flags flag;
13584 	char cdb[CDB_GROUP1] = {
13585 		SCMD_LOG_SENSE_G1,
13586 		0,
13587 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
13588 		0,
13589 		0,
13590 		0,
13591 		0,
13592 		(char)(sizeof (struct st_tape_alert) >> 8),
13593 		(char)(sizeof (struct st_tape_alert)),
13594 		0
13595 	};
13596 
13597 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
13598 
13599 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13600 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
13601 
13602 	com->uscsi_cdb = cdb;
13603 	com->uscsi_cdblen = CDB_GROUP1;
13604 	com->uscsi_bufaddr = (caddr_t)ta;
13605 	com->uscsi_buflen = sizeof (struct st_tape_alert);
13606 	com->uscsi_rqlen = sizeof (status);
13607 	com->uscsi_rqbuf = (caddr_t)&status;
13608 	com->uscsi_flags =
13609 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13610 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13611 
13612 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13613 
13614 	if (rval || com->uscsi_status || com->uscsi_resid) {
13615 
13616 		rval = -1; /* uscsi-command failed */
13617 
13618 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
13619 
13620 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13621 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
13622 		rval = -1;
13623 	}
13624 
13625 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
13626 
13627 
13628 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
13629 
13630 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13631 		    "TapeAlert length %d\n", length);
13632 	}
13633 
13634 
13635 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
13636 
13637 		/*
13638 		 * if rval is bad before the first pass don't bother
13639 		 */
13640 		if (ix == 0 && rval != 0) {
13641 
13642 			break;
13643 		}
13644 
13645 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
13646 		    ta->param[ix].log_param.pc_lo);
13647 
13648 		if ((ta->param[ix].param_value & 1) == 0) {
13649 			continue;
13650 		}
13651 		/*
13652 		 * check to see if current parameter is of interest.
13653 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
13654 		 */
13655 		if ((flag == TAF_CLEAN_NOW) ||
13656 		    (flag == TAF_CLEAN_PERIODIC) ||
13657 		    ((flag == CLEAN_FOR_ERRORS) &&
13658 		    (un->un_dp->type == ST_TYPE_STK9840))) {
13659 
13660 			rval = MTF_TAPE_CLN_SUPPORTED;
13661 
13662 
13663 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13664 			    "alert_page drive needs clean %d\n", flag);
13665 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
13666 			rval |= MTF_TAPE_HEAD_DIRTY;
13667 
13668 		} else if (flag == TAF_CLEANING_MEDIA) {
13669 
13670 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13671 			    "alert_page drive was cleaned\n");
13672 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
13673 		}
13674 
13675 	}
13676 
13677 	/*
13678 	 * Report it as dirty till we see it cleaned
13679 	 */
13680 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
13681 
13682 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13683 		    "alert_page still dirty\n");
13684 		rval |= MTF_TAPE_HEAD_DIRTY;
13685 	}
13686 
13687 	kmem_free(com, sizeof (struct uscsi_cmd));
13688 	kmem_free(ta,  sizeof (struct st_tape_alert));
13689 
13690 	return (rval);
13691 }
13692 
13693 
13694 static int
13695 st_check_sense_clean_bit(struct scsi_tape *un)
13696 {
13697 	uchar_t *sensep;
13698 	char cdb[CDB_GROUP0];
13699 	struct uscsi_cmd *com;
13700 	ushort_t byte_pos;
13701 	uchar_t bit_mask;
13702 	unsigned length;
13703 	int index;
13704 	int rval;
13705 
13706 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
13707 
13708 	/*
13709 	 * Since this tape does not support Tape Alert,
13710 	 * we now try to get the cleanbit status via
13711 	 * Request Sense.
13712 	 */
13713 
13714 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
13715 
13716 		index = 0;
13717 
13718 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
13719 
13720 		index = 1;
13721 
13722 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
13723 
13724 		index = 2;
13725 
13726 	} else {
13727 
13728 		return (-1);
13729 	}
13730 
13731 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
13732 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
13733 	length = byte_pos + 1;
13734 
13735 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13736 	sensep = kmem_zalloc(length, KM_SLEEP);
13737 
13738 	cdb[0] = SCMD_REQUEST_SENSE;
13739 	cdb[1] = 0;
13740 	cdb[2] = 0;
13741 	cdb[3] = 0;
13742 	cdb[4] = (char)length;
13743 	cdb[5] = 0;
13744 
13745 	com->uscsi_cdb = cdb;
13746 	com->uscsi_cdblen = CDB_GROUP0;
13747 	com->uscsi_bufaddr = (caddr_t)sensep;
13748 	com->uscsi_buflen = length;
13749 	com->uscsi_flags =
13750 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13751 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13752 
13753 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13754 
13755 	if (rval || com->uscsi_status || com->uscsi_resid) {
13756 
13757 		rval = -1;
13758 
13759 	} else {
13760 
13761 		rval = MTF_TAPE_CLN_SUPPORTED;
13762 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
13763 
13764 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13765 			    "sense data says head dirty\n");
13766 			rval |= MTF_TAPE_HEAD_DIRTY;
13767 		}
13768 	}
13769 
13770 	kmem_free(com, sizeof (struct uscsi_cmd));
13771 	kmem_free(sensep, length);
13772 	return (rval);
13773 }
13774 
13775 /*
13776  * st_clear_unit_attention
13777  *
13778  *  	run test unit ready's to clear out outstanding
13779  * 	unit attentions.
13780  * 	returns zero for SUCCESS or the errno from st_cmd call
13781  */
13782 static int
13783 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
13784 {
13785 	int	i    = 0;
13786 	int	rval;
13787 
13788 	GET_SOFT_STATE(dev_instance);
13789 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
13790 
13791 	do {
13792 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
13793 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
13794 	return (rval);
13795 }
13796 
13797 static void
13798 st_calculate_timeouts(struct scsi_tape *un)
13799 {
13800 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
13801 
13802 	if (un->un_dp->non_motion_timeout == 0) {
13803 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13804 			un->un_dp->non_motion_timeout =
13805 			    st_io_time * st_long_timeout_x;
13806 		} else {
13807 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
13808 		}
13809 	}
13810 
13811 	if (un->un_dp->io_timeout == 0) {
13812 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13813 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
13814 		} else {
13815 			un->un_dp->io_timeout = (ushort_t)st_io_time;
13816 		}
13817 	}
13818 
13819 	if (un->un_dp->rewind_timeout == 0) {
13820 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13821 			un->un_dp->rewind_timeout =
13822 			    st_space_time * st_long_timeout_x;
13823 		} else {
13824 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
13825 		}
13826 	}
13827 
13828 	if (un->un_dp->space_timeout == 0) {
13829 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13830 			un->un_dp->space_timeout =
13831 			    st_space_time * st_long_timeout_x;
13832 		} else {
13833 			un->un_dp->space_timeout = (ushort_t)st_space_time;
13834 		}
13835 	}
13836 
13837 	if (un->un_dp->load_timeout == 0) {
13838 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13839 			un->un_dp->load_timeout =
13840 			    st_space_time * st_long_timeout_x;
13841 		} else {
13842 			un->un_dp->load_timeout = (ushort_t)st_space_time;
13843 		}
13844 	}
13845 
13846 	if (un->un_dp->unload_timeout == 0) {
13847 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13848 			un->un_dp->unload_timeout =
13849 			    st_space_time * st_long_timeout_x;
13850 		} else {
13851 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
13852 		}
13853 	}
13854 
13855 	if (un->un_dp->erase_timeout == 0) {
13856 		if (un->un_dp->options & ST_LONG_ERASE) {
13857 			un->un_dp->erase_timeout =
13858 			    st_space_time * st_long_space_time_x;
13859 		} else {
13860 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
13861 		}
13862 	}
13863 }
13864 
13865 
13866 static writablity
13867 st_is_not_wormable(struct scsi_tape *un)
13868 {
13869 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
13870 	return (RDWR);
13871 }
13872 
13873 static writablity
13874 st_is_hp_dat_tape_worm(struct scsi_tape *un)
13875 {
13876 	writablity wrt;
13877 
13878 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
13879 
13880 	/* Mode sense should be current */
13881 	if (un->un_mspl->media_type == 1) {
13882 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13883 		    "Drive has WORM media loaded\n");
13884 		wrt = WORM;
13885 	} else {
13886 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13887 		    "Drive has non WORM media loaded\n");
13888 		wrt = RDWR;
13889 	}
13890 	return (wrt);
13891 }
13892 
13893 #define	HP_DAT_INQUIRY 0x4A
13894 static writablity
13895 st_is_hp_dat_worm(struct scsi_tape *un)
13896 {
13897 	char *buf;
13898 	int result;
13899 	writablity wrt;
13900 
13901 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
13902 
13903 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
13904 
13905 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
13906 
13907 	if (result != 0) {
13908 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13909 		    "Read Standard Inquiry for WORM support failed");
13910 		wrt = FAILED;
13911 	} else if ((buf[40] & 1) == 0) {
13912 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13913 		    "Drive is NOT WORMable\n");
13914 		/* This drive doesn't support it so don't check again */
13915 		un->un_dp->options &= ~ST_WORMABLE;
13916 		wrt = RDWR;
13917 		un->un_wormable = st_is_not_wormable;
13918 	} else {
13919 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13920 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13921 		un->un_wormable = st_is_hp_dat_tape_worm;
13922 		wrt = un->un_wormable(un);
13923 	}
13924 
13925 	kmem_free(buf, HP_DAT_INQUIRY);
13926 
13927 	/*
13928 	 * If drive doesn't support it no point in checking further.
13929 	 */
13930 	return (wrt);
13931 }
13932 
13933 static writablity
13934 st_is_hp_lto_tape_worm(struct scsi_tape *un)
13935 {
13936 	writablity wrt;
13937 
13938 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
13939 
13940 	/* Mode sense should be current */
13941 	switch (un->un_mspl->media_type) {
13942 	case 0x00:
13943 		switch (un->un_mspl->density) {
13944 		case 0x40:
13945 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13946 			    "Drive has standard Gen I media loaded\n");
13947 			break;
13948 		case 0x42:
13949 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13950 			    "Drive has standard Gen II media loaded\n");
13951 			break;
13952 		case 0x44:
13953 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13954 			    "Drive has standard Gen III media loaded\n");
13955 			break;
13956 		case 0x46:
13957 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13958 			    "Drive has standard Gen IV media loaded\n");
13959 			break;
13960 		default:
13961 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13962 			    "Drive has standard unknown 0x%X media loaded\n",
13963 			    un->un_mspl->density);
13964 		}
13965 		wrt = RDWR;
13966 		break;
13967 	case 0x01:
13968 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13969 		    "Drive has WORM medium loaded\n");
13970 		wrt = WORM;
13971 		break;
13972 	case 0x80:
13973 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13974 		    "Drive has CD-ROM emulation medium loaded\n");
13975 		wrt = WORM;
13976 		break;
13977 	default:
13978 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13979 		    "Drive has an unexpected medium type 0x%X loaded\n",
13980 		    un->un_mspl->media_type);
13981 		wrt = RDWR;
13982 	}
13983 
13984 	return (wrt);
13985 }
13986 
13987 #define	LTO_REQ_INQUIRY 44
13988 static writablity
13989 st_is_hp_lto_worm(struct scsi_tape *un)
13990 {
13991 	char *buf;
13992 	int result;
13993 	writablity wrt;
13994 
13995 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
13996 
13997 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
13998 
13999 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
14000 
14001 	if (result != 0) {
14002 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14003 		    "Read Standard Inquiry for WORM support failed");
14004 		wrt = FAILED;
14005 	} else if ((buf[40] & 1) == 0) {
14006 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14007 		    "Drive is NOT WORMable\n");
14008 		/* This drive doesn't support it so don't check again */
14009 		un->un_dp->options &= ~ST_WORMABLE;
14010 		wrt = RDWR;
14011 		un->un_wormable = st_is_not_wormable;
14012 	} else {
14013 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14014 		    "Drive supports WORM version %d\n", buf[40] >> 1);
14015 		un->un_wormable = st_is_hp_lto_tape_worm;
14016 		wrt = un->un_wormable(un);
14017 	}
14018 
14019 	kmem_free(buf, LTO_REQ_INQUIRY);
14020 
14021 	/*
14022 	 * If drive doesn't support it no point in checking further.
14023 	 */
14024 	return (wrt);
14025 }
14026 
14027 static writablity
14028 st_is_t10_worm_device(struct scsi_tape *un)
14029 {
14030 	writablity wrt;
14031 
14032 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
14033 
14034 	if (un->un_mspl->media_type == 0x3c) {
14035 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14036 		    "Drive has WORM media loaded\n");
14037 		wrt = WORM;
14038 	} else {
14039 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14040 		    "Drive has non WORM media loaded\n");
14041 		wrt = RDWR;
14042 	}
14043 	return (wrt);
14044 }
14045 
14046 #define	SEQ_CAP_PAGE	(char)0xb0
14047 static writablity
14048 st_is_t10_worm(struct scsi_tape *un)
14049 {
14050 	char *buf;
14051 	int result;
14052 	writablity wrt;
14053 
14054 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
14055 
14056 	buf = kmem_zalloc(6, KM_SLEEP);
14057 
14058 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
14059 
14060 	if (result != 0) {
14061 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14062 		    "Read Vitial Inquiry for Sequental Capability"
14063 		    " WORM support failed %x", result);
14064 		wrt = FAILED;
14065 	} else if ((buf[4] & 1) == 0) {
14066 		ASSERT(buf[1] == SEQ_CAP_PAGE);
14067 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14068 		    "Drive is NOT WORMable\n");
14069 		/* This drive doesn't support it so don't check again */
14070 		un->un_dp->options &= ~ST_WORMABLE;
14071 		wrt = RDWR;
14072 		un->un_wormable = st_is_not_wormable;
14073 	} else {
14074 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14075 		    "Drive supports WORM\n");
14076 		un->un_wormable = st_is_t10_worm_device;
14077 		wrt = un->un_wormable(un);
14078 	}
14079 
14080 	kmem_free(buf, 6);
14081 
14082 	return (wrt);
14083 }
14084 
14085 
14086 #define	STK_REQ_SENSE 26
14087 
14088 static writablity
14089 st_is_stk_worm(struct scsi_tape *un)
14090 {
14091 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
14092 	struct scsi_extended_sense *sense;
14093 	struct uscsi_cmd *cmd;
14094 	char *buf;
14095 	int result;
14096 	writablity wrt;
14097 
14098 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
14099 
14100 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14101 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
14102 	sense = (struct scsi_extended_sense *)buf;
14103 
14104 	cmd->uscsi_flags = USCSI_READ;
14105 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14106 	cmd->uscsi_cdb = &cdb[0];
14107 	cmd->uscsi_bufaddr = buf;
14108 	cmd->uscsi_buflen = STK_REQ_SENSE;
14109 	cmd->uscsi_cdblen = CDB_GROUP0;
14110 	cmd->uscsi_rqlen = 0;
14111 	cmd->uscsi_rqbuf = NULL;
14112 
14113 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14114 
14115 	if (result != 0 || cmd->uscsi_status != 0) {
14116 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14117 		    "Request Sense for WORM failed");
14118 		wrt = RDWR;
14119 	} else if (sense->es_add_len + 8 < 24) {
14120 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14121 		    "Drive didn't send enough sense data for WORM byte %d\n",
14122 		    sense->es_add_len + 8);
14123 		wrt = RDWR;
14124 		un->un_wormable = st_is_not_wormable;
14125 	} else if ((buf[24]) & 0x02) {
14126 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14127 		    "Drive has WORM tape loaded\n");
14128 		wrt = WORM;
14129 		un->un_wormable = st_is_stk_worm;
14130 	} else {
14131 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14132 		    "Drive has normal tape loaded\n");
14133 		wrt = RDWR;
14134 		un->un_wormable = st_is_stk_worm;
14135 	}
14136 
14137 	kmem_free(buf, STK_REQ_SENSE);
14138 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14139 	return (wrt);
14140 }
14141 
14142 #define	DLT_INQ_SZ 44
14143 
14144 static writablity
14145 st_is_dlt_tape_worm(struct scsi_tape *un)
14146 {
14147 	caddr_t buf;
14148 	int result;
14149 	writablity wrt;
14150 
14151 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
14152 
14153 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14154 
14155 	/* Read Attribute Media Type */
14156 
14157 	result = st_read_attributes(un, 0x0408, buf, 10, st_uscsi_cmd);
14158 
14159 	/*
14160 	 * If this quantum drive is attached via an HBA that cannot
14161 	 * support thr read attributes command return error in the
14162 	 * hope that someday they will support the t10 method.
14163 	 */
14164 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
14165 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14166 		    "Read Attribute Command for WORM Media detection is not "
14167 		    "supported on the HBA that this drive is attached to.");
14168 		wrt = RDWR;
14169 		un->un_wormable = st_is_not_wormable;
14170 		goto out;
14171 	}
14172 
14173 	if (result != 0) {
14174 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14175 		    "Read Attribute Command for WORM Media returned 0x%x",
14176 		    result);
14177 		wrt = RDWR;
14178 		un->un_dp->options &= ~ST_WORMABLE;
14179 		goto out;
14180 	}
14181 
14182 	if ((uchar_t)buf[9] == 0x80) {
14183 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14184 		    "Drive media is WORM\n");
14185 		wrt = WORM;
14186 	} else {
14187 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14188 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
14189 		wrt = RDWR;
14190 	}
14191 
14192 out:
14193 	kmem_free(buf, DLT_INQ_SZ);
14194 	return (wrt);
14195 }
14196 
14197 static writablity
14198 st_is_dlt_worm(struct scsi_tape *un)
14199 {
14200 	caddr_t buf;
14201 	int result;
14202 	writablity wrt;
14203 
14204 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
14205 
14206 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14207 
14208 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
14209 
14210 	if (result != 0) {
14211 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14212 		    "Read Vendor Specific Inquiry for WORM support failed");
14213 		wrt = RDWR;
14214 		goto out;
14215 	}
14216 
14217 	if ((buf[2] & 1) == 0) {
14218 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14219 		    "Drive is not WORMable\n");
14220 		wrt = RDWR;
14221 		un->un_dp->options &= ~ST_WORMABLE;
14222 		un->un_wormable = st_is_not_wormable;
14223 		goto out;
14224 	} else {
14225 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14226 		    "Drive is WORMable\n");
14227 		un->un_wormable = st_is_dlt_tape_worm;
14228 		wrt = un->un_wormable(un);
14229 	}
14230 out:
14231 	kmem_free(buf, DLT_INQ_SZ);
14232 
14233 	return (wrt);
14234 }
14235 
14236 typedef struct {
14237 	struct modeheader_seq header;
14238 #if defined(_BIT_FIELDS_LTOH) /* X86 */
14239 	uchar_t pagecode	:6,
14240 				:2;
14241 	uchar_t page_len;
14242 	uchar_t syslogalive	:2,
14243 		device		:1,
14244 		abs		:1,
14245 		ulpbot		:1,
14246 		prth		:1,
14247 		ponej		:1,
14248 		ait		:1;
14249 	uchar_t span;
14250 
14251 	uchar_t			:6,
14252 		worm		:1,
14253 		mic		:1;
14254 	uchar_t worm_cap	:1,
14255 				:7;
14256 	uint32_t		:32;
14257 #else /* SPARC */
14258 	uchar_t			:2,
14259 		pagecode	:6;
14260 	uchar_t page_len;
14261 	uchar_t ait		:1,
14262 		device		:1,
14263 		abs		:1,
14264 		ulpbot		:1,
14265 		prth		:1,
14266 		ponej		:1,
14267 		syslogalive	:2;
14268 	uchar_t span;
14269 	uchar_t mic		:1,
14270 		worm		:1,
14271 				:6;
14272 	uchar_t			:7,
14273 		worm_cap	:1;
14274 	uint32_t		:32;
14275 #endif
14276 }ait_dev_con;
14277 
14278 #define	AIT_DEV_PAGE 0x31
14279 static writablity
14280 st_is_sony_worm(struct scsi_tape *un)
14281 {
14282 	int result;
14283 	writablity wrt;
14284 	ait_dev_con *ait_conf;
14285 
14286 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14287 
14288 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
14289 
14290 	result = st_gen_mode_sense(un, st_uscsi_cmd, AIT_DEV_PAGE,
14291 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
14292 
14293 	if (result == 0) {
14294 
14295 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
14296 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14297 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
14298 			    ait_conf->pagecode, AIT_DEV_PAGE);
14299 			wrt = RDWR;
14300 			un->un_wormable = st_is_not_wormable;
14301 
14302 		} else if (ait_conf->worm_cap) {
14303 
14304 			un->un_wormable = st_is_sony_worm;
14305 
14306 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14307 			    "Drives is WORMable\n");
14308 			if (ait_conf->worm) {
14309 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14310 				    "Media is WORM\n");
14311 				wrt = WORM;
14312 			} else {
14313 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14314 				    "Media is not WORM\n");
14315 				wrt = RDWR;
14316 			}
14317 
14318 		} else {
14319 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14320 			    "Drives not is WORMable\n");
14321 			wrt = RDWR;
14322 			/* No further checking required */
14323 			un->un_dp->options &= ~ST_WORMABLE;
14324 		}
14325 
14326 	} else {
14327 
14328 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14329 		    "AIT device config mode sense page read command failed"
14330 		    " result = %d ", result);
14331 		wrt = FAILED;
14332 		un->un_wormable = st_is_not_wormable;
14333 	}
14334 
14335 	kmem_free(ait_conf, sizeof (ait_dev_con));
14336 	return (wrt);
14337 }
14338 
14339 static writablity
14340 st_is_drive_worm(struct scsi_tape *un)
14341 {
14342 	writablity wrt;
14343 
14344 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14345 
14346 	switch (un->un_dp->type) {
14347 	case MT_ISDLT:
14348 		wrt = st_is_dlt_worm(un);
14349 		break;
14350 
14351 	case MT_ISSTK9840:
14352 		wrt = st_is_stk_worm(un);
14353 		break;
14354 
14355 	case MT_IS8MM:
14356 	case MT_ISAIT:
14357 		wrt = st_is_sony_worm(un);
14358 		break;
14359 
14360 	case MT_LTO:
14361 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14362 			wrt = st_is_hp_lto_worm(un);
14363 		} else {
14364 			wrt = st_is_t10_worm(un);
14365 		}
14366 		break;
14367 
14368 	case MT_ISDAT:
14369 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14370 			wrt = st_is_hp_dat_worm(un);
14371 		} else {
14372 			wrt = st_is_t10_worm(un);
14373 		}
14374 		break;
14375 
14376 	default:
14377 		wrt = FAILED;
14378 		break;
14379 	}
14380 
14381 	/*
14382 	 * If any of the above failed try the t10 standard method.
14383 	 */
14384 	if (wrt == FAILED) {
14385 		wrt = st_is_t10_worm(un);
14386 	}
14387 
14388 	/*
14389 	 * Unknown method for detecting WORM media.
14390 	 */
14391 	if (wrt == FAILED) {
14392 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14393 		    "Unknown method for WORM media detection\n");
14394 		wrt = RDWR;
14395 		un->un_dp->options &= ~ST_WORMABLE;
14396 	}
14397 
14398 	return (wrt);
14399 }
14400 
14401 static int
14402 st_read_attributes(struct scsi_tape *un, uint16_t attribute, void *pnt,
14403     size_t size, ubufunc_t bufunc)
14404 {
14405 	char cdb[CDB_GROUP4];
14406 	int result;
14407 	struct uscsi_cmd *cmd;
14408 	struct scsi_arq_status status;
14409 
14410 	caddr_t buf = (caddr_t)pnt;
14411 
14412 	ST_FUNC(ST_DEVINFO, st_read_attributes);
14413 
14414 	if (un->un_sd->sd_inq->inq_ansi < 3) {
14415 		return (ENOTTY);
14416 	}
14417 
14418 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14419 
14420 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
14421 	cdb[1] = 0;
14422 	cdb[2] = 0;
14423 	cdb[3] = 0;
14424 	cdb[4] = 0;
14425 	cdb[5] = 0;
14426 	cdb[6] = 0;
14427 	cdb[7] = 0;
14428 	cdb[8] = (char)(attribute >> 8);
14429 	cdb[9] = (char)(attribute);
14430 	cdb[10] = (char)(size >> 24);
14431 	cdb[11] = (char)(size >> 16);
14432 	cdb[12] = (char)(size >> 8);
14433 	cdb[13] = (char)(size);
14434 	cdb[14] = 0;
14435 	cdb[15] = 0;
14436 
14437 
14438 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE | USCSI_DIAGNOSE;
14439 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14440 	cmd->uscsi_cdb = &cdb[0];
14441 	cmd->uscsi_bufaddr = (caddr_t)buf;
14442 	cmd->uscsi_buflen = size;
14443 	cmd->uscsi_cdblen = sizeof (cdb);
14444 	cmd->uscsi_rqlen = sizeof (status);
14445 	cmd->uscsi_rqbuf = (caddr_t)&status;
14446 
14447 	result = bufunc(un, cmd, FKIOCTL);
14448 
14449 	if (result != 0 || cmd->uscsi_status != 0) {
14450 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
14451 		    "st_read_attribute failed: result %d status %d\n",
14452 		    result, cmd->uscsi_status);
14453 		/*
14454 		 * If this returns invalid operation code don't try again.
14455 		 */
14456 		if (un->un_sd->sd_sense->es_key == KEY_ILLEGAL_REQUEST &&
14457 		    un->un_sd->sd_sense->es_add_code == 0x20) {
14458 			result = ENOTTY;
14459 		} else if (result == 0) {
14460 			result = EIO;
14461 		}
14462 
14463 	} else {
14464 
14465 		/*
14466 		 * The attribute retured should match the attribute requested.
14467 		 */
14468 		if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
14469 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14470 			    "st_read_attribute got wrong data back expected "
14471 			    "0x%x got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
14472 			st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14473 			    "bad? data", buf, size);
14474 			result = EIO;
14475 		}
14476 	}
14477 
14478 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14479 
14480 	return (result);
14481 }
14482 
14483 static int
14484 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
14485     uchar_t page)
14486 {
14487 	char cdb[CDB_GROUP0];
14488 	struct scsi_extended_sense *sense;
14489 	struct uscsi_cmd *cmd;
14490 	int result;
14491 
14492 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
14493 
14494 	cdb[0] = SCMD_INQUIRY;
14495 	cdb[1] = page ? 1 : 0;
14496 	cdb[2] = page;
14497 	cdb[3] = 0;
14498 	cdb[4] = size;
14499 	cdb[5] = 0;
14500 
14501 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14502 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
14503 
14504 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
14505 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14506 	cmd->uscsi_cdb = &cdb[0];
14507 	cmd->uscsi_bufaddr = dest;
14508 	cmd->uscsi_buflen = size;
14509 	cmd->uscsi_cdblen = CDB_GROUP0;
14510 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
14511 	cmd->uscsi_rqbuf = (caddr_t)sense;
14512 
14513 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14514 
14515 	if (result != 0 || cmd->uscsi_status != 0) {
14516 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14517 		    "st_get_special_inquiry() failed for page %x", page);
14518 		if (result == 0) {
14519 			result = EIO;
14520 		}
14521 	}
14522 
14523 	kmem_free(sense, sizeof (struct scsi_extended_sense));
14524 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14525 
14526 	return (result);
14527 }
14528 
14529 
14530 static int
14531 st_update_block_pos(struct scsi_tape *un, bufunc_t bf, int post_space)
14532 {
14533 	int rval = ENOTTY;
14534 	uchar_t status = un->un_status;
14535 	posmode previous_pmode = un->un_running.pmode;
14536 
14537 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
14538 
14539 	while (un->un_read_pos_type != NO_POS) {
14540 		rval = bf(un, SCMD_READ_POSITION, 32, SYNC_CMD);
14541 
14542 		/*
14543 		 * If read position command returned good status
14544 		 * Parse the data to see if the position can be interpreted.
14545 		 */
14546 		if ((rval == 0) &&
14547 		    ((rval = st_interpret_read_pos(un, &un->un_pos,
14548 		    un->un_read_pos_type, 32, (caddr_t)un->un_read_pos_data,
14549 		    post_space)) == 0)) {
14550 			/*
14551 			 * Update the running position as well if un_pos was
14552 			 * ok. But only if recovery is enabled.
14553 			 */
14554 			if (st_recov_sz != sizeof (recov_info)) {
14555 				break;
14556 			}
14557 			rval = st_interpret_read_pos(un, &un->un_running,
14558 			    un->un_read_pos_type, 32,
14559 			    (caddr_t)un->un_read_pos_data, post_space);
14560 			un->un_status = status;
14561 			break;
14562 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
14563 			un->un_running.pmode = previous_pmode;
14564 			continue;
14565 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
14566 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
14567 			    "st_update_block_pos() read position cmd 0x%x"
14568 			    " returned 0x%x un_status = %d",
14569 			    un->un_read_pos_type, rval, un->un_status);
14570 			/* ENOTTY means it read garbage. try something else. */
14571 			if (rval == ENOTTY) {
14572 				rval = EIO; /* so ENOTTY is not final rval */
14573 			} else {
14574 				break;
14575 			}
14576 		} else {
14577 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
14578 			    "st_update_block_pos() read position cmd %x"
14579 			    " returned %x", un->un_read_pos_type, rval);
14580 			un->un_running.pmode = previous_pmode;
14581 		}
14582 
14583 		switch (un->un_read_pos_type) {
14584 		case SHORT_POS:
14585 			un->un_read_pos_type = NO_POS;
14586 			break;
14587 
14588 		case LONG_POS:
14589 			un->un_read_pos_type = EXT_POS;
14590 			break;
14591 
14592 		case EXT_POS:
14593 			un->un_read_pos_type = SHORT_POS;
14594 			break;
14595 
14596 		default:
14597 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14598 			    "Unexpected read position type 0x%x",
14599 			    un->un_read_pos_type);
14600 		}
14601 		un->un_status = KEY_NO_SENSE;
14602 	}
14603 
14604 	return (rval);
14605 }
14606 
14607 static int
14608 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
14609 {
14610 	int result;
14611 	size_t d_sz;
14612 	caddr_t pos_info;
14613 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
14614 
14615 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
14616 
14617 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
14618 		return (0);
14619 	}
14620 
14621 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
14622 
14623 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14624 		    "bp_mapin_common() failed");
14625 
14626 		return (EIO);
14627 	}
14628 
14629 	d_sz = bp->b_bcount - bp->b_resid;
14630 	if (d_sz == 0) {
14631 		bp_mapout(bp);
14632 		return (EIO);
14633 	}
14634 
14635 	/*
14636 	 * Copy the buf to a double-word aligned memory that can hold the
14637 	 * tape_position_t data structure.
14638 	 */
14639 	if ((pos_info = kmem_alloc(d_sz, KM_NOSLEEP)) == NULL) {
14640 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14641 		    "kmem_alloc() failed");
14642 		bp_mapout(bp);
14643 		return (EIO);
14644 	}
14645 	bcopy(bp->b_un.b_addr, pos_info, d_sz);
14646 
14647 #ifdef STDEBUG
14648 	if ((st_debug & 0x7) > 2) {
14649 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14650 		    "st_get_read_pos() position info",
14651 		    pos_info, bp->b_bcount);
14652 	}
14653 #endif
14654 
14655 	result = st_interpret_read_pos(un, &un->un_pos, cmd->uscsi_cdb[1],
14656 	    d_sz, pos_info, 0);
14657 
14658 	COPY_POS(&un->un_running, &un->un_pos);
14659 
14660 	kmem_free(pos_info, d_sz);
14661 	bp_mapout(bp);
14662 
14663 	return (result);
14664 }
14665 
14666 #if defined(_BIG_ENDIAN)
14667 
14668 #define	FIX_ENDIAN16(x)
14669 #define	FIX_ENDIAN32(x)
14670 #define	FIX_ENDIAN64(x)
14671 
14672 #elif defined(_LITTLE_ENDIAN)
14673 
14674 static void
14675 st_swap16(uint16_t *val)
14676 {
14677 	uint16_t tmp;
14678 
14679 	tmp = (*val >>  8) & 0xff;
14680 	tmp |= (*val <<  8) & 0xff00;
14681 
14682 	*val = tmp;
14683 }
14684 
14685 static void
14686 st_swap32(uint32_t *val)
14687 {
14688 	uint32_t tmp;
14689 
14690 	tmp =  (*val >> 24) & 0xff;
14691 	tmp |= (*val >>  8) & 0xff00;
14692 	tmp |= (*val <<  8) & 0xff0000;
14693 	tmp |= (*val << 24) & 0xff000000;
14694 
14695 	*val = tmp;
14696 }
14697 
14698 static void
14699 st_swap64(uint64_t *val)
14700 {
14701 	uint32_t low;
14702 	uint32_t high;
14703 
14704 	low =  (uint32_t)(*val);
14705 	high = (uint32_t)(*val >> 32);
14706 
14707 	st_swap32(&low);
14708 	st_swap32(&high);
14709 
14710 	*val =  high;
14711 	*val |= ((uint64_t)low << 32);
14712 }
14713 
14714 #define	FIX_ENDIAN16(x) st_swap16(x)
14715 #define	FIX_ENDIAN32(x) st_swap32(x)
14716 #define	FIX_ENDIAN64(x) st_swap64(x)
14717 #endif
14718 
14719 /*
14720  * st_interpret_read_pos()
14721  *
14722  * Returns:
14723  *	0	If secsessful.
14724  *	EIO	If read postion responce data was unuseable or invalid.
14725  *	ERANGE	If the position of the drive is too large for the read_p_type.
14726  *	ENOTTY	If the responce data looks invalid for the read position type.
14727  */
14728 
14729 static int
14730 st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
14731     read_p_types type, size_t data_sz, const caddr_t responce, int post_space)
14732 {
14733 	int rval = 0;
14734 	int flag = 0;
14735 	tapepos_t org;
14736 
14737 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
14738 
14739 	/*
14740 	 * We expect the position value to change after a space command.
14741 	 * So if post_space is set we don't print out what has changed.
14742 	 */
14743 	if ((dest != &un->un_pos) && (post_space == 0) &&
14744 	    (st_recov_sz == sizeof (recov_info))) {
14745 		COPY_POS(&org, dest);
14746 		flag = 1;
14747 	}
14748 
14749 	/*
14750 	 * See what kind of read position was requested.
14751 	 */
14752 	switch (type) {
14753 
14754 	case SHORT_POS: /* Short data format */
14755 	{
14756 		tape_position_t *pos_info = (tape_position_t *)responce;
14757 		uint32_t value;
14758 
14759 		/* If reserved fields are non zero don't use the data */
14760 		if (pos_info->reserved0 || pos_info->reserved1 ||
14761 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
14762 		    pos_info->reserved3) {
14763 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14764 			    "Invalid Read Short Position Data returned\n");
14765 			rval = EIO;
14766 			break;
14767 		}
14768 		/*
14769 		 * Position is to large to use this type of read position.
14770 		 */
14771 		if (pos_info->posi_err == 1) {
14772 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14773 			    "Drive reported position error\n");
14774 			rval = ERANGE;
14775 			break;
14776 		}
14777 		/*
14778 		 * If your at the begining of partition and end at the same
14779 		 * time it's very small partition or bad data.
14780 		 */
14781 		if (pos_info->begin_of_part && pos_info->end_of_part) {
14782 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14783 			    "SHORT_POS returned begin and end of"
14784 			    " partition\n");
14785 			rval = EIO;
14786 			break;
14787 		}
14788 
14789 		if (pos_info->blk_posi_unkwn == 0) {
14790 
14791 			value = pos_info->host_block;
14792 			FIX_ENDIAN32(&value);
14793 
14794 			/*
14795 			 * If the tape is rewound the host blcok should be 0.
14796 			 */
14797 			if ((pos_info->begin_of_part == 1) &&
14798 			    (value != 0)) {
14799 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14800 				    "SHORT_POS returned begin of partition"
14801 				    " but host block was 0x%x\n", value);
14802 				rval = EIO;
14803 				break;
14804 			}
14805 
14806 			if (dest->lgclblkno != value) {
14807 				if (flag)
14808 					flag++;
14809 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14810 				    "SHORT_POS current logical 0x%"PRIx64" read"
14811 				    " 0x%x\n", dest->lgclblkno, value);
14812 			}
14813 
14814 			dest->lgclblkno = (uint64_t)value;
14815 
14816 			/*
14817 			 * If the begining of partition is true and the
14818 			 * block number is zero we will beleive that it is
14819 			 * rewound. Promote the pmode to legacy.
14820 			 */
14821 			if ((pos_info->begin_of_part == 1) &&
14822 			    (value == 0)) {
14823 				dest->blkno = 0;
14824 				dest->fileno = 0;
14825 				if (dest->pmode != legacy)
14826 					dest->pmode = legacy;
14827 			/*
14828 			 * otherwise if the pmode was invalid,
14829 			 * promote it to logical.
14830 			 */
14831 			} else if (dest->pmode == invalid) {
14832 				dest->pmode = logical;
14833 			}
14834 
14835 			if (dest->partition != pos_info->partition_number) {
14836 				if (flag)
14837 					flag++;
14838 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14839 				    "SHORT_POS current partition %d read %d\n",
14840 				    dest->partition,
14841 				    pos_info->partition_number);
14842 			}
14843 
14844 			dest->partition = pos_info->partition_number;
14845 
14846 		} else {
14847 			dest->pmode = invalid;
14848 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14849 			    "Tape drive reported block position as unknown\n");
14850 		}
14851 		break;
14852 	}
14853 
14854 	case LONG_POS: /* Long data format */
14855 	{
14856 		uint64_t value;
14857 		tape_position_long_t *long_pos_info =
14858 		    (tape_position_long_t *)responce;
14859 
14860 		/* If reserved fields are non zero don't use the data */
14861 		if ((long_pos_info->reserved0) ||
14862 		    (long_pos_info->reserved1) ||
14863 		    (long_pos_info->reserved2)) {
14864 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14865 			    "Invalid Read Long Position Data returned\n");
14866 			rval = ENOTTY;
14867 			break;
14868 		}
14869 
14870 		/* Is position Valid */
14871 		if (long_pos_info->blk_posi_unkwn == 0) {
14872 			uint32_t part;
14873 
14874 			value = long_pos_info->block_number;
14875 			FIX_ENDIAN64(&value);
14876 
14877 			/*
14878 			 * If it says we are at the begining of partition
14879 			 * the block value better be 0.
14880 			 */
14881 			if ((long_pos_info->begin_of_part == 1) &&
14882 			    (value != 0)) {
14883 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14884 				    "LONG_POS returned begin of partition but"
14885 				    " block number was 0x%"PRIx64"\n", value);
14886 				rval = ENOTTY;
14887 				break;
14888 			}
14889 			/*
14890 			 * Can't be at the start and the end of the partition
14891 			 * at the same time if the partition is larger the 0.
14892 			 */
14893 			if (long_pos_info->begin_of_part &&
14894 			    long_pos_info->end_of_part) {
14895 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14896 				    "LONG_POS returned begin and end of"
14897 				    " partition\n");
14898 				rval = ENOTTY;
14899 				break;
14900 			}
14901 
14902 			/*
14903 			 * If the logical block number is not what we expected.
14904 			 */
14905 			if (dest->lgclblkno != value) {
14906 				if (flag)
14907 					flag++;
14908 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14909 				    "LONG_POS current logical 0x%"PRIx64
14910 				    " read 0x%"PRIx64"\n",
14911 				    dest->lgclblkno, value);
14912 			}
14913 			dest->lgclblkno = value;
14914 
14915 			/*
14916 			 * If the begining of partition is true and the
14917 			 * block number is zero we will beleive that it is
14918 			 * rewound. Promote the pmode to legacy.
14919 			 */
14920 			if ((long_pos_info->begin_of_part == 1) &&
14921 			    (long_pos_info->block_number == 0)) {
14922 				dest->blkno = 0;
14923 				dest->fileno = 0;
14924 				if (dest->pmode != legacy)
14925 					dest->pmode = legacy;
14926 			/*
14927 			 * otherwise if the pmode was invalid,
14928 			 * promote it to logical.
14929 			 */
14930 			} else if (dest->pmode == invalid) {
14931 				dest->pmode = logical;
14932 			}
14933 
14934 			part = long_pos_info->partition;
14935 			FIX_ENDIAN32(&part);
14936 			if (dest->partition != part) {
14937 				if (flag)
14938 					flag++;
14939 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14940 				    "LONG_POS current partition %d"
14941 				    " read %d\n", dest->partition, part);
14942 			}
14943 			dest->partition = part;
14944 		} else {
14945 			/*
14946 			 * If the drive doesn't know location,
14947 			 * we don't either.
14948 			 */
14949 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14950 			    "Tape drive reported block position as unknown\n");
14951 			dest->pmode = invalid;
14952 		}
14953 
14954 		/* Is file position valid */
14955 		if (long_pos_info->mrk_posi_unkwn == 0) {
14956 			value = long_pos_info->file_number;
14957 			FIX_ENDIAN64(&value);
14958 			/*
14959 			 * If it says we are at the begining of partition
14960 			 * the block value better be 0.
14961 			 */
14962 			if ((long_pos_info->begin_of_part == 1) &&
14963 			    (value != 0)) {
14964 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14965 				    "LONG_POS returned begin of partition but"
14966 				    " block number was 0x%"PRIx64"\n", value);
14967 				rval = ENOTTY;
14968 				break;
14969 			}
14970 			if (((dest->pmode == legacy) ||
14971 			    (dest->pmode == logical)) &&
14972 			    (dest->fileno != value)) {
14973 				if (flag)
14974 					flag++;
14975 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14976 				    "LONG_POS fileno 0x%"PRIx64
14977 				    " not un_pos %x\n", value,
14978 				    dest->fileno);
14979 			} else if (dest->pmode == invalid) {
14980 				dest->pmode = logical;
14981 			}
14982 			dest->fileno = (int32_t)value;
14983 		}
14984 
14985 		if (dest->pmode != invalid && long_pos_info->end_of_part) {
14986 			dest->eof = ST_EOT;
14987 		}
14988 
14989 		break;
14990 	}
14991 
14992 	case EXT_POS: /* Extended data format */
14993 	{
14994 		uint64_t value;
14995 		uint16_t len;
14996 		tape_position_ext_t *ext_pos_info =
14997 		    (tape_position_ext_t *)responce;
14998 
14999 		/* Make sure that there is enough data there */
15000 		if (data_sz < 16) {
15001 			break;
15002 		}
15003 
15004 		/* If reserved fields are non zero don't use the data */
15005 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
15006 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15007 			    "EXT_POS reserved fields not zero\n");
15008 			rval = ENOTTY;
15009 			break;
15010 		}
15011 
15012 		/*
15013 		 * In the unlikely event of overflowing 64 bits of position.
15014 		 */
15015 		if (ext_pos_info->posi_err != 0) {
15016 			rval = ERANGE;
15017 			break;
15018 		}
15019 
15020 		len = ext_pos_info->parameter_len;
15021 		FIX_ENDIAN16(&len);
15022 
15023 		if (len != 0x1c) {
15024 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15025 			    "EXT_POS parameter_len should be 0x1c was 0x%x\n",
15026 			    len);
15027 			rval = ENOTTY;
15028 			break;
15029 		}
15030 
15031 		/* Is block position information valid */
15032 		if (ext_pos_info->blk_posi_unkwn == 0) {
15033 
15034 			value = ext_pos_info->host_block;
15035 			FIX_ENDIAN64(&value);
15036 			if ((ext_pos_info->begin_of_part == 1) &&
15037 			    (value != 0)) {
15038 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15039 				    "EXT_POS returned begining of partition but"
15040 				    " the host block was 0x%"PRIx64"\n", value);
15041 				rval = ENOTTY;
15042 				break;
15043 			}
15044 
15045 			if (dest->lgclblkno != value) {
15046 				if (flag)
15047 					flag++;
15048 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15049 				    "EXT_POS current logical 0x%"PRIx64
15050 				    " read 0x%"PRIx64"\n",
15051 				    dest->lgclblkno, value);
15052 			}
15053 			dest->lgclblkno = value;
15054 
15055 			/*
15056 			 * If the begining of partition is true and the
15057 			 * block number is zero we will beleive that it is
15058 			 * rewound. Promote the pmode to legacy.
15059 			 */
15060 			if ((ext_pos_info->begin_of_part == 1) &&
15061 			    (ext_pos_info->host_block == 0)) {
15062 				dest->blkno = 0;
15063 				dest->fileno = 0;
15064 				if (dest->pmode != legacy) {
15065 					dest->pmode = legacy;
15066 				}
15067 			/*
15068 			 * otherwise if the pmode was invalid,
15069 			 * promote it to logical.
15070 			 */
15071 			} else if (dest->pmode == invalid) {
15072 				dest->pmode = logical;
15073 			}
15074 
15075 			if (dest->partition != ext_pos_info->partition) {
15076 				if (flag)
15077 					flag++;
15078 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15079 				    "EXT_POS current partition %d read %d\n",
15080 				    dest->partition,
15081 				    ext_pos_info->partition);
15082 			}
15083 			dest->partition = ext_pos_info->partition;
15084 
15085 		} else {
15086 			dest->pmode = invalid;
15087 		}
15088 		break;
15089 	}
15090 
15091 	default:
15092 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15093 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
15094 		rval = EIO;
15095 	}
15096 
15097 	if ((flag > 1) && (rval == 0) && (org.pmode != invalid)) {
15098 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
15099 		    "position read in", &org);
15100 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
15101 		    "position read out", dest);
15102 	}
15103 
15104 	return (rval);
15105 }
15106 
15107 static int
15108 st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos,
15109     uint64_t lblk, uchar_t partition)
15110 {
15111 	int rval;
15112 	char cdb[CDB_GROUP4];
15113 	struct uscsi_cmd *cmd;
15114 	struct scsi_extended_sense sense;
15115 	bufunc_t bf = (ubf == st_uscsi_cmd) ? st_cmd : st_rcmd;
15116 
15117 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
15118 	/*
15119 	 * Not sure what to do when doing recovery and not wanting
15120 	 * to update un_pos
15121 	 */
15122 
15123 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
15124 
15125 	if (lblk <= INT32_MAX) {
15126 		cmd->uscsi_cdblen = CDB_GROUP1;
15127 		cdb[0] = SCMD_LOCATE;
15128 		cdb[1] = pos->partition == partition ? 0 : 2;
15129 		cdb[2] = 0;
15130 		cdb[3] = (char)(lblk >> 24);
15131 		cdb[4] = (char)(lblk >> 16);
15132 		cdb[5] = (char)(lblk >> 8);
15133 		cdb[6] = (char)(lblk);
15134 		cdb[7] = 0;
15135 		cdb[8] = partition;
15136 		cdb[9] = 0;
15137 	} else {
15138 		/*
15139 		 * If the drive doesn't give a 64 bit read position data
15140 		 * it is unlikely it will accept 64 bit locates.
15141 		 */
15142 		if (un->un_read_pos_type != LONG_POS) {
15143 			kmem_free(cmd, sizeof (struct uscsi_cmd));
15144 			return (ERANGE);
15145 		}
15146 		cmd->uscsi_cdblen = CDB_GROUP4;
15147 		cdb[0] = (char)SCMD_LOCATE_G4;
15148 		cdb[1] = pos->partition == partition ? 0 : 2;
15149 		cdb[2] = 0;
15150 		cdb[3] = partition;
15151 		cdb[4] = (char)(lblk >> 56);
15152 		cdb[5] = (char)(lblk >> 48);
15153 		cdb[6] = (char)(lblk >> 40);
15154 		cdb[7] = (char)(lblk >> 32);
15155 		cdb[8] = (char)(lblk >> 24);
15156 		cdb[9] = (char)(lblk >> 16);
15157 		cdb[10] = (char)(lblk >> 8);
15158 		cdb[11] = (char)(lblk);
15159 		cdb[12] = 0;
15160 		cdb[13] = 0;
15161 		cdb[14] = 0;
15162 		cdb[15] = 0;
15163 	}
15164 
15165 
15166 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
15167 	cmd->uscsi_rqbuf = (caddr_t)&sense;
15168 	cmd->uscsi_rqlen = sizeof (sense);
15169 	cmd->uscsi_timeout = un->un_dp->space_timeout;
15170 	cmd->uscsi_cdb = cdb;
15171 
15172 	rval = ubf(un, cmd, FKIOCTL);
15173 
15174 	pos->pmode = logical;
15175 	pos->eof = ST_NO_EOF;
15176 
15177 	if (lblk > INT32_MAX) {
15178 		/*
15179 		 * XXX This is a work around till we handle Descriptor format
15180 		 * sense data. Since we are sending a command where the standard
15181 		 * sense data can not correctly represent a correct residual in
15182 		 * 4 bytes.
15183 		 */
15184 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
15185 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15186 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
15187 			/* Doesn't like big locate command */
15188 			un->un_status = 0;
15189 			rval = ERANGE;
15190 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
15191 			/* Aborted big locate command */
15192 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15193 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
15194 			    rval);
15195 			un->un_status = 0;
15196 			rval = EIO;
15197 		} else if (st_update_block_pos(un, bf, 1)) {
15198 			/* read position failed */
15199 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15200 			    "Big LOCATE and read pos: rval = %d\n", rval);
15201 			rval = EIO;
15202 		} else if (lblk > un->un_pos.lgclblkno) {
15203 			/* read position worked but position was not expected */
15204 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15205 			    "Big LOCATE and recover read less then desired 0x%"
15206 			    PRIx64"\n", un->un_pos.lgclblkno);
15207 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
15208 			un->un_status = KEY_BLANK_CHECK;
15209 			rval = ESPIPE;
15210 		} else if (lblk == un->un_pos.lgclblkno) {
15211 			/* read position was what was expected */
15212 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15213 			    "Big LOCATE and recover seems to have worked\n");
15214 			un->un_err_resid = 0;
15215 			rval = 0;
15216 		} else {
15217 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15218 			    "BIGLOCATE end up going backwards");
15219 			un->un_err_resid = lblk;
15220 			rval = EIO;
15221 		}
15222 
15223 	} else if (rval == 0) {
15224 		/* Worked as requested */
15225 		pos->lgclblkno = lblk;
15226 
15227 	} else if (((cmd->uscsi_status & ST_STATUS_MASK) == STATUS_CHECK) &&
15228 	    (cmd->uscsi_resid != 0)) {
15229 		/* Got part way there but wasn't enough blocks on tape */
15230 		pos->lgclblkno = lblk - cmd->uscsi_resid;
15231 		un->un_err_resid = cmd->uscsi_resid;
15232 		un->un_status = KEY_BLANK_CHECK;
15233 		rval = ESPIPE;
15234 
15235 	} else if (st_update_block_pos(un, bf, 1) == 0) {
15236 		/* Got part way there but drive didn't tell what we missed by */
15237 		un->un_err_resid = lblk - pos->lgclblkno;
15238 		un->un_status = KEY_BLANK_CHECK;
15239 		rval = ESPIPE;
15240 
15241 	} else {
15242 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15243 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
15244 		    rval, cmd->uscsi_status);
15245 		un->un_err_resid = lblk;
15246 		un->un_status = KEY_ILLEGAL_REQUEST;
15247 		pos->pmode = invalid;
15248 		rval = EIO;
15249 	}
15250 
15251 	kmem_free(cmd, sizeof (struct uscsi_cmd));
15252 
15253 	return (rval);
15254 }
15255 
15256 static int
15257 st_mtfsf_ioctl(struct scsi_tape *un, int64_t files)
15258 {
15259 	int rval;
15260 
15261 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
15262 
15263 
15264 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15265 	    "st_mtfsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15266 #if 0
15267 	if ((IN_EOF(un->un_pos)) && (files == 1)) {
15268 		un->un_pos.fileno++;
15269 		un->un_pos.blkno = 0;
15270 		return (0);
15271 	}
15272 #endif
15273 	/* pmode == invalid already handled */
15274 	if (un->un_pos.pmode == legacy) {
15275 		/*
15276 		 * forward space over filemark
15277 		 *
15278 		 * For ASF we allow a count of 0 on fsf which means
15279 		 * we just want to go to beginning of current file.
15280 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
15281 		 * Allow stepping over double fmk with reel
15282 		 */
15283 		if ((un->un_pos.eof >= ST_EOT) &&
15284 		    (files > 0) &&
15285 		    ((un->un_dp->options & ST_REEL) == 0)) {
15286 			/* we're at EOM */
15287 			un->un_err_resid = files;
15288 			un->un_status = KEY_BLANK_CHECK;
15289 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15290 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
15291 			return (EIO);
15292 		}
15293 
15294 		/*
15295 		 * physical tape position may not be what we've been
15296 		 * telling the user; adjust the request accordingly
15297 		 */
15298 		if (IN_EOF(un->un_pos)) {
15299 			un->un_pos.fileno++;
15300 			un->un_pos.blkno = 0;
15301 			/*
15302 			 * For positive direction case, we're now covered.
15303 			 * For zero or negative direction, we're covered
15304 			 * (almost)
15305 			 */
15306 			files--;
15307 		}
15308 
15309 	}
15310 
15311 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15312 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15313 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
15314 		return (EIO);
15315 	}
15316 
15317 
15318 	/*
15319 	 * Forward space file marks.
15320 	 * We leave ourselves at block zero
15321 	 * of the target file number.
15322 	 */
15323 	if (files < 0) {
15324 		rval = st_backward_space_files(un, -files, 0);
15325 	} else {
15326 		rval = st_forward_space_files(un, files);
15327 	}
15328 
15329 	return (rval);
15330 }
15331 
15332 static int
15333 st_forward_space_files(struct scsi_tape *un, int64_t count)
15334 {
15335 	int rval;
15336 
15337 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
15338 
15339 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15340 	    "fspace: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15341 
15342 	ASSERT(count >= 0);
15343 	ASSERT(un->un_pos.pmode != invalid);
15344 
15345 	/*
15346 	 * A space with a count of zero means take me to the start of file.
15347 	 */
15348 	if (count == 0) {
15349 
15350 		/* Hay look were already there */
15351 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0) {
15352 			un->un_err_resid = 0;
15353 			COPY_POS(&un->un_err_pos, &un->un_pos);
15354 			return (0);
15355 		}
15356 
15357 		/*
15358 		 * Well we are in the first file.
15359 		 * A rewind will get to the start.
15360 		 */
15361 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
15362 			rval = st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
15363 
15364 		/*
15365 		 * Can we backspace to get there?
15366 		 * This should work in logical mode.
15367 		 */
15368 		} else if (un->un_dp->options & ST_BSF) {
15369 			rval = st_space_to_begining_of_file(un);
15370 
15371 		/*
15372 		 * Can't back space but current file number is known,
15373 		 * So rewind and space from the begining of the partition.
15374 		 */
15375 		} else if (un->un_pos.pmode == legacy) {
15376 			rval = st_scenic_route_to_begining_of_file(un,
15377 			    un->un_pos.fileno);
15378 
15379 		/*
15380 		 * pmode is logical and ST_BSF is not set.
15381 		 * The LONG_POS read position contains the fileno.
15382 		 * If the read position works, rewind and space.
15383 		 */
15384 		} else if (un->un_read_pos_type == LONG_POS) {
15385 			rval = st_cmd(un, SCMD_READ_POSITION, 0, SYNC_CMD);
15386 			if (rval) {
15387 				/*
15388 				 * We didn't get the file position from the
15389 				 * read position command.
15390 				 * We are going to trust the drive to backspace
15391 				 * and then position after the filemark.
15392 				 */
15393 				rval = st_space_to_begining_of_file(un);
15394 			}
15395 			rval = st_interpret_read_pos(un, &un->un_pos, LONG_POS,
15396 			    32, (caddr_t)un->un_read_pos_data, 0);
15397 			if ((rval) && (un->un_pos.pmode == invalid)) {
15398 				rval = st_space_to_begining_of_file(un);
15399 			} else {
15400 				rval = st_scenic_route_to_begining_of_file(un,
15401 				    un->un_pos.fileno);
15402 			}
15403 		} else {
15404 			rval = EIO;
15405 		}
15406 		/*
15407 		 * If something didn't work we are lost
15408 		 */
15409 		if (rval != 0) {
15410 			un->un_pos.pmode = invalid;
15411 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15412 			    "st_mtioctop : EIO : fspace pmode invalid");
15413 
15414 			rval = EIO;
15415 		}
15416 
15417 	} else {
15418 		rval = st_space_fmks(un, count);
15419 	}
15420 
15421 	if (rval != EIO && count < 0) {
15422 		/*
15423 		 * we came here with a count < 0; we now need
15424 		 * to skip back to end up before the filemark
15425 		 */
15426 		rval = st_backward_space_files(un, 1, 1);
15427 	}
15428 
15429 	return (rval);
15430 }
15431 
15432 static int
15433 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
15434 {
15435 	int rval;
15436 
15437 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
15438 
15439 	if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15440 		rval = EIO;
15441 	} else if (st_cmd(un, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
15442 		rval = EIO;
15443 	}
15444 
15445 	return (rval);
15446 }
15447 
15448 static int
15449 st_space_to_begining_of_file(struct scsi_tape *un)
15450 {
15451 	int rval;
15452 
15453 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
15454 
15455 	/*
15456 	 * Back space of the file at the begining of the file.
15457 	 */
15458 	rval = st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
15459 	if (rval) {
15460 		rval = EIO;
15461 		return (rval);
15462 	}
15463 
15464 	/*
15465 	 * Other interesting answers might be crashed BOT which isn't bad.
15466 	 */
15467 	if (un->un_status == SUN_KEY_BOT) {
15468 		return (rval);
15469 	}
15470 
15471 	un->un_running.pmode = invalid;
15472 
15473 	/*
15474 	 * Now we are on the BOP side of the filemark. Forward space to
15475 	 * the EOM side and we are at the begining of the file.
15476 	 */
15477 	rval = st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD);
15478 	if (rval) {
15479 		rval = EIO;
15480 	}
15481 
15482 	return (rval);
15483 }
15484 
15485 static int
15486 st_mtfsr_ioctl(struct scsi_tape *un, int64_t count)
15487 {
15488 
15489 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
15490 
15491 	/*
15492 	 * forward space to inter-record gap
15493 	 *
15494 	 */
15495 
15496 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15497 	    "st_ioctl_fsr: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15498 
15499 	if (un->un_pos.pmode == legacy) {
15500 		/*
15501 		 * If were are at end of tape and count is forward.
15502 		 * Return blank check.
15503 		 */
15504 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
15505 			/* we're at EOM */
15506 			un->un_err_resid = count;
15507 			un->un_status = KEY_BLANK_CHECK;
15508 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15509 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
15510 			return (EIO);
15511 		}
15512 
15513 		/*
15514 		 * If count is zero there is nothing to do.
15515 		 */
15516 		if (count == 0) {
15517 			un->un_err_pos.fileno = un->un_pos.fileno;
15518 			un->un_err_pos.blkno = un->un_pos.blkno;
15519 			un->un_err_resid = 0;
15520 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15521 				un->un_status = SUN_KEY_EOF;
15522 			}
15523 			return (0);
15524 		}
15525 
15526 		/*
15527 		 * physical tape position may not be what we've been
15528 		 * telling the user; adjust the position accordingly
15529 		 */
15530 		if (IN_EOF(un->un_pos)) {
15531 			daddr_t blkno = un->un_pos.blkno;
15532 			int fileno = un->un_pos.fileno;
15533 
15534 			optype lastop = un->un_lastop;
15535 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)
15536 			    == -1) {
15537 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15538 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
15539 				return (EIO);
15540 			}
15541 
15542 			un->un_pos.blkno = blkno;
15543 			un->un_pos.fileno = fileno;
15544 			un->un_lastop = lastop;
15545 		}
15546 	}
15547 
15548 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15549 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15550 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
15551 		return (EIO);
15552 	}
15553 
15554 	return (st_space_records(un, count));
15555 }
15556 
15557 static int
15558 st_space_records(struct scsi_tape *un, int64_t count)
15559 {
15560 	int64_t dblk;
15561 	int rval = 0;
15562 
15563 	ST_FUNC(ST_DEVINFO, st_space_records);
15564 
15565 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15566 	    "st_space_records: count=%"PRIx64", eof=%x\n",
15567 	    count, un->un_pos.eof);
15568 
15569 	if (un->un_pos.pmode == logical) {
15570 		rval = st_cmd(un, SCMD_SPACE, Blk(count), SYNC_CMD);
15571 		if (rval != 0) {
15572 			rval = EIO;
15573 		}
15574 		return (rval);
15575 	}
15576 
15577 	dblk = count + un->un_pos.blkno;
15578 
15579 	/* Already there */
15580 	if (dblk == un->un_pos.blkno) {
15581 		un->un_err_resid = 0;
15582 		COPY_POS(&un->un_err_pos, &un->un_pos);
15583 		return (0);
15584 	}
15585 
15586 	/*
15587 	 * If the destination block is forward
15588 	 * or the drive will backspace records.
15589 	 */
15590 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
15591 		/*
15592 		 * If we're spacing forward, or the device can
15593 		 * backspace records, we can just use the SPACE
15594 		 * command.
15595 		 */
15596 		dblk -= un->un_pos.blkno;
15597 		if (st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15598 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15599 			    "st_space_records:EIO:space_records can't spc");
15600 			rval = EIO;
15601 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
15602 			/*
15603 			 * check if we hit BOT/EOT
15604 			 */
15605 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
15606 				un->un_status = SUN_KEY_BOT;
15607 				un->un_pos.eof = ST_NO_EOF;
15608 			} else if (dblk < 0 &&
15609 			    un->un_pos.eof == ST_EOF_PENDING) {
15610 				int residue = un->un_err_resid;
15611 				/*
15612 				 * we skipped over a filemark
15613 				 * and need to go forward again
15614 				 */
15615 				if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
15616 					ST_DEBUG2(ST_DEVINFO, st_label,
15617 					    SCSI_DEBUG, "st_space_records: EIO"
15618 					    " : can't space #2");
15619 					rval = EIO;
15620 				}
15621 				un->un_err_resid = residue;
15622 			}
15623 			if (rval == 0) {
15624 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15625 				    "st_space_records: EIO : space_rec rval"
15626 				    " == 0");
15627 				rval = EIO;
15628 			}
15629 		}
15630 	} else {
15631 		/*
15632 		 * else we rewind, space forward across filemarks to
15633 		 * the desired file, and then space records to the
15634 		 * desired block.
15635 		 */
15636 
15637 		int dfile = un->un_pos.fileno;	/* save current file */
15638 
15639 		if (dblk < 0) {
15640 			/*
15641 			 * Wups - we're backing up over a filemark
15642 			 */
15643 			if (un->un_pos.blkno != 0 &&
15644 			    (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15645 			    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD))) {
15646 				un->un_pos.pmode = invalid;
15647 			}
15648 			un->un_err_resid = -dblk;
15649 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
15650 				un->un_status = SUN_KEY_BOT;
15651 				un->un_pos.eof = ST_NO_EOF;
15652 			} else if (un->un_pos.fileno > 0) {
15653 				un->un_status = SUN_KEY_EOF;
15654 				un->un_pos.eof = ST_NO_EOF;
15655 			}
15656 			COPY_POS(&un->un_err_pos, &un->un_pos);
15657 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15658 			    "st_space_records:EIO:space_records : dblk < 0");
15659 			rval = EIO;
15660 		} else if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15661 		    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
15662 		    st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15663 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15664 			    "st_space_records: EIO :space_records : rewind "
15665 			    "and space failed");
15666 			un->un_pos.pmode = invalid;
15667 			rval = EIO;
15668 		}
15669 	}
15670 
15671 	return (rval);
15672 }
15673 
15674 static int
15675 st_mtbsf_ioctl(struct scsi_tape *un, int64_t files)
15676 {
15677 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
15678 
15679 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15680 	    "st_mtbsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15681 	/*
15682 	 * backward space of file filemark (1/2" and 8mm)
15683 	 * tape position will end on the beginning of tape side
15684 	 * of the desired file mark
15685 	 */
15686 	if ((un->un_dp->options & ST_BSF) == 0) {
15687 		return (ENOTTY);
15688 	}
15689 
15690 	if (un->un_pos.pmode == legacy) {
15691 
15692 		/*
15693 		 * If a negative count (which implies a forward space op)
15694 		 * is specified, and we're at logical or physical eot,
15695 		 * bounce the request.
15696 		 */
15697 
15698 		if (un->un_pos.eof >= ST_EOT && files < 0) {
15699 			un->un_err_resid = files;
15700 			un->un_status = SUN_KEY_EOT;
15701 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15702 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
15703 			return (EIO);
15704 		}
15705 		/*
15706 		 * physical tape position may not be what we've been
15707 		 * telling the user; adjust the request accordingly
15708 		 */
15709 		if (IN_EOF(un->un_pos)) {
15710 			un->un_pos.fileno++;
15711 			un->un_pos.blkno = 0;
15712 			files++;
15713 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15714 			    "st_mtbsf_ioctl in eof: count=%"PRIx64", op=%x\n",
15715 			    files, MTBSF);
15716 
15717 		}
15718 	}
15719 
15720 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15721 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15722 		    "st_ioctl : EIO : MTBSF : check den wfm");
15723 		return (EIO);
15724 	}
15725 
15726 	if (files <= 0) {
15727 		/*
15728 		 * for a negative count, we need to step forward
15729 		 * first and then step back again
15730 		 */
15731 		files = -files + 1;
15732 		return (st_forward_space_files(un, files));
15733 	}
15734 	return (st_backward_space_files(un, files, 1));
15735 }
15736 
15737 static int
15738 st_backward_space_files(struct scsi_tape *un, int64_t count, int infront)
15739 {
15740 	int64_t end_fileno;
15741 	int64_t skip_cnt;
15742 	int rval = 0;
15743 
15744 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
15745 
15746 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15747 	    "st_backward_space_files: count=%"PRIx64" eof=%x\n",
15748 	    count, un->un_pos.eof);
15749 	/*
15750 	 * Backspace files (MTNBSF): infront == 0
15751 	 *
15752 	 *	For tapes that can backspace, backspace
15753 	 *	count+1 filemarks and then run forward over
15754 	 *	a filemark
15755 	 *
15756 	 *	For tapes that can't backspace,
15757 	 *		calculate desired filenumber
15758 	 *		(un->un_pos.fileno - count), rewind,
15759 	 *		and then space forward this amount
15760 	 *
15761 	 * Backspace filemarks (MTBSF) infront == 1
15762 	 *
15763 	 *	For tapes that can backspace, backspace count
15764 	 *	filemarks
15765 	 *
15766 	 *	For tapes that can't backspace, calculate
15767 	 *	desired filenumber (un->un_pos.fileno - count),
15768 	 *	add 1, rewind, space forward this amount,
15769 	 *	and mark state as ST_EOF_PENDING appropriately.
15770 	 */
15771 
15772 	if (un->un_pos.pmode == logical) {
15773 
15774 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15775 		    "st_backward_space_files: mt_op=%x count=%"PRIx64
15776 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
15777 		    un->un_pos.lgclblkno);
15778 
15779 
15780 		/* In case a drive that won't back space gets in logical mode */
15781 		if ((un->un_dp->options & ST_BSF) == 0) {
15782 			rval = EIO;
15783 			return (rval);
15784 		}
15785 		if ((infront == 1) &&
15786 		    (st_cmd(un, SCMD_SPACE, Fmk(-count), SYNC_CMD))) {
15787 			rval = EIO;
15788 			return (rval);
15789 		} else if ((infront == 0) &&
15790 		    (st_cmd(un, SCMD_SPACE, Fmk((-count)-1), SYNC_CMD)) &&
15791 		    (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
15792 			rval = EIO;
15793 			return (rval);
15794 		}
15795 		return (rval);
15796 	}
15797 
15798 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15799 	    "st_backward_space_files: mt_op=%x count=%"PRIx64
15800 	    "fileno=%x blkno=%x\n",
15801 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
15802 
15803 
15804 
15805 	/*
15806 	 * Handle the simple case of BOT
15807 	 * playing a role in these cmds.
15808 	 * We do this by calculating the
15809 	 * ending file number. If the ending
15810 	 * file is < BOT, rewind and set an
15811 	 * error and mark resid appropriately.
15812 	 * If we're backspacing a file (not a
15813 	 * filemark) and the target file is
15814 	 * the first file on the tape, just
15815 	 * rewind.
15816 	 */
15817 
15818 	/* figure expected destination of this SPACE command */
15819 	end_fileno = un->un_pos.fileno - count;
15820 
15821 	/*
15822 	 * Would the end effect of this SPACE be the same as rewinding?
15823 	 * If so just rewind instead.
15824 	 */
15825 	if ((infront != 0) && (end_fileno < 0) ||
15826 	    (infront == 0) && (end_fileno <= 0)) {
15827 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15828 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15829 			    "st_backward_space_files: EIO : "
15830 			    "rewind in lou of BSF failed\n");
15831 			rval = EIO;
15832 		}
15833 		if (end_fileno < 0) {
15834 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15835 			    "st_backward_space_files: EIO : "
15836 			    "back space file greater then fileno\n");
15837 			rval = EIO;
15838 			un->un_err_resid = -end_fileno;
15839 			un->un_status = SUN_KEY_BOT;
15840 		}
15841 		return (rval);
15842 	}
15843 
15844 	if (un->un_dp->options & ST_BSF) {
15845 		skip_cnt = 1 - infront;
15846 		/*
15847 		 * If we are going to end up at the beginning
15848 		 * of the file, we have to space one extra file
15849 		 * first, and then space forward later.
15850 		 */
15851 		end_fileno = -(count + skip_cnt);
15852 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15853 		    "skip_cnt=%"PRIx64", tmp=%"PRIx64"\n",
15854 		    skip_cnt, end_fileno);
15855 		if (st_cmd(un, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
15856 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15857 			    "st_backward_space_files:EIO:back space fm failed");
15858 			rval = EIO;
15859 		}
15860 	} else {
15861 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15862 			rval = EIO;
15863 		} else {
15864 			skip_cnt = end_fileno + infront;
15865 		}
15866 	}
15867 
15868 	/*
15869 	 * If we have to space forward, do so...
15870 	 */
15871 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15872 	    "space forward skip_cnt=%"PRIx64", rval=%x\n", skip_cnt, rval);
15873 
15874 	if (rval == 0 && skip_cnt) {
15875 		if (st_cmd(un, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
15876 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15877 			    "st_backward_space_files:EIO:space fm skip count");
15878 			rval = EIO;
15879 		} else if (infront) {
15880 			/*
15881 			 * If we had to space forward, and we're
15882 			 * not a tape that can backspace, mark state
15883 			 * as if we'd just seen a filemark during a
15884 			 * a read.
15885 			 */
15886 			if ((un->un_dp->options & ST_BSF) == 0) {
15887 				un->un_pos.eof = ST_EOF_PENDING;
15888 				un->un_pos.fileno -= 1;
15889 				un->un_pos.blkno = LASTBLK;
15890 				un->un_running.pmode = invalid;
15891 			}
15892 		}
15893 	}
15894 
15895 	if (rval != 0) {
15896 		un->un_pos.pmode = invalid;
15897 	}
15898 
15899 	return (rval);
15900 }
15901 
15902 static int
15903 st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count)
15904 {
15905 	int rval;
15906 
15907 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
15908 
15909 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15910 	    "nbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15911 
15912 	if (un->un_pos.pmode == legacy) {
15913 		/*
15914 		 * backward space file to beginning of file
15915 		 *
15916 		 * If a negative count (which implies a forward space op)
15917 		 * is specified, and we're at logical or physical eot,
15918 		 * bounce the request.
15919 		 */
15920 
15921 		if (un->un_pos.eof >= ST_EOT && count < 0) {
15922 			un->un_err_resid = count;
15923 			un->un_status = SUN_KEY_EOT;
15924 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15925 			    "st_ioctl : EIO : > EOT and count < 0");
15926 			return (EIO);
15927 		}
15928 		/*
15929 		 * physical tape position may not be what we've been
15930 		 * telling the user; adjust the request accordingly
15931 		 */
15932 		if (IN_EOF(un->un_pos)) {
15933 			un->un_pos.fileno++;
15934 			un->un_pos.blkno = 0;
15935 			count++;
15936 		}
15937 	}
15938 
15939 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15940 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15941 		    "st_ioctl : EIO : MTNBSF check den and wfm");
15942 		return (EIO);
15943 	}
15944 
15945 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15946 	    "mtnbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15947 
15948 	if (count <= 0) {
15949 		rval = st_forward_space_files(un, -count);
15950 	} else {
15951 		rval = st_backward_space_files(un, count, 0);
15952 	}
15953 	return (rval);
15954 }
15955 
15956 static int
15957 st_mtbsr_ioctl(struct scsi_tape *un, int64_t num)
15958 {
15959 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
15960 
15961 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15962 	    "bsr: count=%"PRIx64", eof=%x\n", num, un->un_pos.eof);
15963 
15964 	if (un->un_pos.pmode == legacy) {
15965 		/*
15966 		 * backward space into inter-record gap
15967 		 *
15968 		 * If a negative count (which implies a forward space op)
15969 		 * is specified, and we're at logical or physical eot,
15970 		 * bounce the request.
15971 		 */
15972 		if (un->un_pos.eof >= ST_EOT && num < 0) {
15973 			un->un_err_resid = num;
15974 			un->un_status = SUN_KEY_EOT;
15975 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15976 			    "st_ioctl : EIO : MTBSR > EOT");
15977 			return (EIO);
15978 		}
15979 
15980 		if (num == 0) {
15981 			COPY_POS(&un->un_err_pos, &un->un_pos);
15982 			un->un_err_resid = 0;
15983 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15984 				un->un_status = SUN_KEY_EOF;
15985 			}
15986 			return (0);
15987 		}
15988 
15989 		/*
15990 		 * physical tape position may not be what we've been
15991 		 * telling the user; adjust the position accordingly.
15992 		 * bsr can not skip filemarks and continue to skip records
15993 		 * therefore if we are logically before the filemark but
15994 		 * physically at the EOT side of the filemark, we need to step
15995 		 * back; this allows fsr N where N > number of blocks in file
15996 		 * followed by bsr 1 to position at the beginning of last block
15997 		 */
15998 		if (IN_EOF(un->un_pos)) {
15999 			tapepos_t save;
16000 			optype lastop = un->un_lastop;
16001 
16002 			COPY_POS(&save, &un->un_pos);
16003 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD) == -1) {
16004 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16005 				    "st_mtbsr_ioctl: EIO : MTBSR can't space");
16006 				return (EIO);
16007 			}
16008 
16009 			COPY_POS(&un->un_pos, &save);
16010 			un->un_lastop = lastop;
16011 		}
16012 	}
16013 
16014 	un->un_pos.eof = ST_NO_EOF;
16015 
16016 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
16017 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16018 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
16019 		return (EIO);
16020 	}
16021 
16022 	num = -num;
16023 	return (st_space_records(un, num));
16024 }
16025 
16026 static int
16027 st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt)
16028 {
16029 	int rval;
16030 
16031 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
16032 
16033 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
16034 	if (rval == 0) {
16035 		un->un_pos.pmode = logical;
16036 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
16037 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
16038 		/*
16039 		 * Drive says invalid field in cdb.
16040 		 * Doesn't like space multiple. Position isn't lost.
16041 		 */
16042 		un->un_err_resid = cnt;
16043 		un->un_status = 0;
16044 		rval = ENOTTY;
16045 	} else {
16046 		un->un_err_resid = cnt;
16047 		un->un_pos.pmode = invalid;
16048 	}
16049 	return (rval);
16050 }
16051 
16052 static int
16053 st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt)
16054 {
16055 	int rval;
16056 
16057 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
16058 
16059 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
16060 	if (rval == 0) {
16061 		un->un_pos.pmode = logical;
16062 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
16063 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
16064 		/*
16065 		 * Drive says invalid field in cdb.
16066 		 * Doesn't like space multiple. Position isn't lost.
16067 		 */
16068 		un->un_err_resid = cnt;
16069 		un->un_status = 0;
16070 		rval = ENOTTY;
16071 	} else {
16072 		un->un_err_resid = cnt;
16073 		un->un_pos.pmode = invalid;
16074 	}
16075 	return (rval);
16076 }
16077 
16078 #ifdef	__x86
16079 
16080 /*
16081  * release contig_mem and wake up waiting thread, if any
16082  */
16083 static void
16084 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
16085 {
16086 	mutex_enter(ST_MUTEX);
16087 
16088 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
16089 
16090 	cp->cm_next = un->un_contig_mem;
16091 	un->un_contig_mem = cp;
16092 	un->un_contig_mem_available_num++;
16093 	cv_broadcast(&un->un_contig_mem_cv);
16094 
16095 	mutex_exit(ST_MUTEX);
16096 }
16097 
16098 /*
16099  * St_get_contig_mem will return a contig_mem if there is one available
16100  * in current system. Otherwise, it will try to alloc one, if the total
16101  * number of contig_mem is within st_max_contig_mem_num.
16102  * It will sleep, if allowed by caller or return NULL, if no contig_mem
16103  * is available for now.
16104  */
16105 static struct contig_mem *
16106 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
16107 {
16108 	size_t rlen;
16109 	struct contig_mem *cp = NULL;
16110 	ddi_acc_handle_t acc_hdl;
16111 	caddr_t addr;
16112 	int big_enough = 0;
16113 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
16114 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
16115 
16116 	/* Try to get one available contig_mem */
16117 	mutex_enter(ST_MUTEX);
16118 
16119 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
16120 
16121 	if (un->un_contig_mem_available_num > 0) {
16122 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16123 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
16124 		/*
16125 		 * we failed to get one. we're going to
16126 		 * alloc one more contig_mem for this I/O
16127 		 */
16128 		mutex_exit(ST_MUTEX);
16129 		cp = (struct contig_mem *)kmem_zalloc(
16130 		    sizeof (struct contig_mem) + biosize(),
16131 		    alloc_flags);
16132 		if (cp == NULL) {
16133 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16134 			    "alloc contig_mem failure\n");
16135 			return (NULL); /* cannot get one */
16136 		}
16137 		cp->cm_bp = (struct buf *)
16138 		    (((caddr_t)cp) + sizeof (struct contig_mem));
16139 		bioinit(cp->cm_bp);
16140 		mutex_enter(ST_MUTEX);
16141 		un->un_contig_mem_total_num++; /* one more available */
16142 	} else {
16143 		/*
16144 		 * we failed to get one and we're NOT allowed to
16145 		 * alloc more contig_mem
16146 		 */
16147 		if (alloc_flags == KM_SLEEP) {
16148 			while (un->un_contig_mem_available_num <= 0) {
16149 				cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16150 			}
16151 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16152 		} else {
16153 			mutex_exit(ST_MUTEX);
16154 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16155 			    "alloc contig_mem failure\n");
16156 			return (NULL); /* cannot get one */
16157 		}
16158 	}
16159 	mutex_exit(ST_MUTEX);
16160 
16161 	/* We need to check if this block of mem is big enough for this I/O */
16162 	if (cp->cm_len < len) {
16163 		/* not big enough, need to alloc a new one */
16164 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
16165 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
16166 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
16167 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16168 			    "alloc contig_mem failure: not enough mem\n");
16169 			st_release_contig_mem(un, cp);
16170 			cp = NULL;
16171 		} else {
16172 			if (cp->cm_addr) {
16173 				/* release previous one before attach new one */
16174 				ddi_dma_mem_free(&cp->cm_acc_hdl);
16175 			}
16176 			mutex_enter(ST_MUTEX);
16177 			un->un_max_contig_mem_len =
16178 			    un->un_max_contig_mem_len >= len ?
16179 			    un->un_max_contig_mem_len : len;
16180 			mutex_exit(ST_MUTEX);
16181 
16182 			/* attach new mem to this cp */
16183 			cp->cm_addr = addr;
16184 			cp->cm_acc_hdl = acc_hdl;
16185 			cp->cm_len = len;
16186 
16187 			goto alloc_ok; /* get one usable cp */
16188 		}
16189 	} else {
16190 		goto alloc_ok; /* get one usable cp */
16191 	}
16192 
16193 	/* cannot find/alloc a usable cp, when we get here */
16194 
16195 	mutex_enter(ST_MUTEX);
16196 	if ((un->un_max_contig_mem_len < len) ||
16197 	    (alloc_flags != KM_SLEEP)) {
16198 		mutex_exit(ST_MUTEX);
16199 		return (NULL);
16200 	}
16201 
16202 	/*
16203 	 * we're allowed to sleep, and there is one big enough
16204 	 * contig mem in the system, which is currently in use,
16205 	 * wait for it...
16206 	 */
16207 	big_enough = 1;
16208 	do {
16209 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16210 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16211 	} while (cp == NULL);
16212 	mutex_exit(ST_MUTEX);
16213 
16214 	/* we get the big enough contig mem, finally */
16215 
16216 alloc_ok:
16217 	/* init bp attached to this cp */
16218 	bioreset(cp->cm_bp);
16219 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
16220 	cp->cm_bp->b_private = (void *)cp;
16221 
16222 	return (cp);
16223 }
16224 
16225 /*
16226  * this is the biodone func for the bp used in big block I/O
16227  */
16228 static int
16229 st_bigblk_xfer_done(struct buf *bp)
16230 {
16231 	struct contig_mem *cp;
16232 	struct buf *orig_bp;
16233 	int ioerr;
16234 	struct scsi_tape *un;
16235 
16236 	/* sanity check */
16237 	if (bp == NULL) {
16238 		return (DDI_FAILURE);
16239 	}
16240 
16241 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16242 	if (un == NULL) {
16243 		return (DDI_FAILURE);
16244 	}
16245 
16246 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
16247 
16248 	cp = (struct contig_mem *)bp->b_private;
16249 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
16250 	cp->cm_bp = bp;
16251 
16252 	/* special handling for special I/O */
16253 	if (cp->cm_use_sbuf) {
16254 #ifndef __lock_lint
16255 		ASSERT(un->un_sbuf_busy);
16256 #endif
16257 		un->un_sbufp = orig_bp;
16258 		cp->cm_use_sbuf = 0;
16259 	}
16260 
16261 	orig_bp->b_resid = bp->b_resid;
16262 	ioerr = geterror(bp);
16263 	if (ioerr != 0) {
16264 		bioerror(orig_bp, ioerr);
16265 	} else if (orig_bp->b_flags & B_READ) {
16266 		/* copy data back to original bp */
16267 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
16268 		    bp->b_bcount - bp->b_resid);
16269 	}
16270 
16271 	st_release_contig_mem(un, cp);
16272 
16273 	biodone(orig_bp);
16274 
16275 	return (DDI_SUCCESS);
16276 }
16277 
16278 /*
16279  * We use this func to replace original bp that may not be able to do I/O
16280  * in big block size with one that can
16281  */
16282 static struct buf *
16283 st_get_bigblk_bp(struct buf *bp)
16284 {
16285 	struct contig_mem *cp;
16286 	struct scsi_tape *un;
16287 	struct buf *cont_bp;
16288 
16289 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16290 	if (un == NULL) {
16291 		return (bp);
16292 	}
16293 
16294 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
16295 
16296 	/* try to get one contig_mem */
16297 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
16298 	if (!cp) {
16299 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
16300 		    "Cannot alloc contig buf for I/O for %lu blk size",
16301 		    bp->b_bcount);
16302 		return (bp);
16303 	}
16304 	cont_bp = cp->cm_bp;
16305 	cp->cm_bp = bp;
16306 
16307 	/* make sure that we "are" using un_sbufp for special I/O */
16308 	if (bp == un->un_sbufp) {
16309 #ifndef __lock_lint
16310 		ASSERT(un->un_sbuf_busy);
16311 #endif
16312 		un->un_sbufp = cont_bp;
16313 		cp->cm_use_sbuf = 1;
16314 	}
16315 
16316 	/* clone bp */
16317 	cont_bp->b_bcount = bp->b_bcount;
16318 	cont_bp->b_resid = bp->b_resid;
16319 	cont_bp->b_iodone = st_bigblk_xfer_done;
16320 	cont_bp->b_file = bp->b_file;
16321 	cont_bp->b_offset = bp->b_offset;
16322 	cont_bp->b_dip = bp->b_dip;
16323 	cont_bp->b_error = 0;
16324 	cont_bp->b_proc = NULL;
16325 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
16326 	cont_bp->b_shadow = NULL;
16327 	cont_bp->b_pages = NULL;
16328 	cont_bp->b_edev = bp->b_edev;
16329 	cont_bp->b_dev = bp->b_dev;
16330 	cont_bp->b_lblkno = bp->b_lblkno;
16331 	cont_bp->b_forw = bp->b_forw;
16332 	cont_bp->b_back = bp->b_back;
16333 	cont_bp->av_forw = bp->av_forw;
16334 	cont_bp->av_back = bp->av_back;
16335 	cont_bp->b_bufsize = bp->b_bufsize;
16336 
16337 	/* get data in original bp */
16338 	if (bp->b_flags & B_WRITE) {
16339 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
16340 	}
16341 
16342 	return (cont_bp);
16343 }
16344 #else
16345 #ifdef __lock_lint
16346 static int
16347 st_bigblk_xfer_done(struct buf *bp)
16348 {
16349 	return (0);
16350 }
16351 #endif
16352 #endif
16353 
16354 static const char *eof_status[] =
16355 {
16356 	"NO_EOF",
16357 	"EOF_PENDING",
16358 	"EOF",
16359 	"EOT_PENDING",
16360 	"EOT",
16361 	"EOM",
16362 	"AFTER_EOM"
16363 };
16364 static const char *mode[] = {
16365 	"invalid",
16366 	"legacy",
16367 	"logical"
16368 };
16369 
16370 static void
16371 st_print_position(dev_info_t *dev, char *label, uint_t level,
16372 const char *comment, tapepos_t *pos)
16373 {
16374 	ST_FUNC(dev, st_print_position);
16375 
16376 	scsi_log(dev, label, level,
16377 	    "%s Position data:\n", comment);
16378 	scsi_log(dev, label, CE_CONT,
16379 	    "Positioning mode = %s", mode[pos->pmode]);
16380 	scsi_log(dev, label, CE_CONT,
16381 	    "End Of File/Tape = %s", eof_status[pos->eof]);
16382 	scsi_log(dev, label, CE_CONT,
16383 	    "File Number      = 0x%x", pos->fileno);
16384 	scsi_log(dev, label, CE_CONT,
16385 	    "Block Number     = 0x%x", pos->blkno);
16386 	scsi_log(dev, label, CE_CONT,
16387 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
16388 	scsi_log(dev, label, CE_CONT,
16389 	    "Partition Number = 0x%x", pos->partition);
16390 }
16391 static int
16392 st_check_if_media_changed(struct scsi_tape *un, caddr_t data, int size)
16393 {
16394 
16395 	int result = 0;
16396 	int i;
16397 	ST_FUNC(ST_DEVINFO, st_check_if_media_changed);
16398 
16399 	/*
16400 	 * find non alpha numeric working from the end.
16401 	 */
16402 	for (i = size - 1; i >= 0; i--) {
16403 		if (ISALNUM(data[i]) == 0 || data[i] == ' ') {
16404 			data[i] = 0;
16405 			size = i;
16406 		}
16407 	}
16408 
16409 	if (size == 1) {
16410 		/*
16411 		 * Drive seems to think its returning useful data
16412 		 * but it looks like all junk
16413 		 */
16414 		return (result);
16415 	}
16416 
16417 	size++;
16418 
16419 	/*
16420 	 * Actually got a valid serial number.
16421 	 * If never stored one before alloc space for it.
16422 	 */
16423 	if (un->un_media_id_len == 0) {
16424 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16425 		un->un_media_id_len = size;
16426 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16427 		un->un_media_id[min(size, strlen(data))] = 0;
16428 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16429 		    "Found Media Id %s length = %d\n", un->un_media_id, size);
16430 	} else if (size > un->un_media_id_len) {
16431 		if (strncmp(un->un_media_id, data, size) != 0) {
16432 			result = ESPIPE;
16433 		}
16434 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16435 		    "Longer Media Id old ID:%s new ID:%s\n",
16436 		    un->un_media_id, data);
16437 		kmem_free(un->un_media_id, un->un_media_id_len);
16438 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16439 		un->un_media_id_len = size;
16440 		(void) strncpy(un->un_media_id, data, size);
16441 		un->un_media_id[size] = 0;
16442 	} else if (strncmp(data, un->un_media_id,
16443 	    min(size, un->un_media_id_len)) != 0) {
16444 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16445 		    "Old Media Id %s length = %d New %s length = %d\n",
16446 		    un->un_media_id, un->un_media_id_len, data, size);
16447 		bzero(un->un_media_id, un->un_media_id_len);
16448 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16449 		un->un_media_id[min(size, strlen(data))] = 0;
16450 		result = ESPIPE;
16451 	} else {
16452 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
16453 		    "Media Id still %s\n", un->un_media_id);
16454 	}
16455 
16456 	ASSERT(strlen(un->un_media_id) <= size);
16457 
16458 	return (result);
16459 }
16460 #define	ID_SIZE 32
16461 typedef struct
16462 {
16463 	uchar_t avilable_data0;
16464 	uchar_t avilable_data1;
16465 	uchar_t avilable_data2;
16466 	uchar_t avilable_data3;
16467 	uchar_t attribute_msb;
16468 	uchar_t attribute_lsb;
16469 #ifdef _BIT_FIELDS_LTOH
16470 	uchar_t format		: 2,
16471 				: 5,
16472 		read_only	: 1;
16473 #else
16474 	uchar_t read_only	: 1,
16475 				: 5,
16476 		format		: 2;
16477 #endif
16478 	uchar_t attribute_len_msb;
16479 	uchar_t attribute_len_lsb;
16480 }attribute_header;
16481 
16482 typedef struct {
16483 	attribute_header header;
16484 	char data[1];
16485 }mam_attribute;
16486 
16487 static int
16488 st_handle_hex_media_id(struct scsi_tape *un, void *pnt, int size)
16489 {
16490 	int result;
16491 	int newsize = (size << 1) + 3; /* extra for leading 0x and null term */
16492 	int i;
16493 	uchar_t byte;
16494 	char *format;
16495 	uchar_t *data = (uchar_t *)pnt;
16496 	char *buf = kmem_alloc(newsize, KM_SLEEP);
16497 
16498 	ST_FUNC(ST_DEVINFO, st_handle_hex_media_id);
16499 
16500 	(void) sprintf(buf, "0x");
16501 	for (i = 0; i < size; i++) {
16502 		byte = data[i];
16503 		if (byte < 0x10)
16504 			format = "0%x";
16505 		else
16506 			format = "%x";
16507 		(void) sprintf(&buf[(int)strlen(buf)], format, byte);
16508 	}
16509 	result = st_check_if_media_changed(un, buf, newsize);
16510 
16511 	kmem_free(buf, newsize);
16512 
16513 	return (result);
16514 }
16515 
16516 
16517 static int
16518 st_get_media_id_via_read_attribute(struct scsi_tape *un, ubufunc_t bufunc)
16519 {
16520 	int result;
16521 	mam_attribute *buffer;
16522 	int size;
16523 	int newsize;
16524 
16525 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_read_attribute);
16526 	size = sizeof (attribute_header) + max(un->un_media_id_len, ID_SIZE);
16527 again:
16528 	buffer = kmem_zalloc(size, KM_SLEEP);
16529 	result = st_read_attributes(un, 0x0401, buffer, size, bufunc);
16530 	if (result == 0) {
16531 
16532 		newsize = (buffer->header.attribute_len_msb << 8) |
16533 		    buffer->header.attribute_len_lsb;
16534 
16535 		if (newsize + sizeof (attribute_header) > size) {
16536 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
16537 			    "resizing read attribute data from %d to %d format"
16538 			    " %d\n", size, (int)sizeof (attribute_header) +
16539 			    newsize, buffer->header.format);
16540 			kmem_free(buffer, size);
16541 			size = newsize + sizeof (attribute_header);
16542 			goto again;
16543 		}
16544 
16545 		un->un_media_id_method = st_get_media_id_via_read_attribute;
16546 		if (buffer->header.format == 0) {
16547 			result =
16548 			    st_handle_hex_media_id(un, buffer->data, newsize);
16549 		} else {
16550 			result = st_check_if_media_changed(un, buffer->data,
16551 			    newsize);
16552 		}
16553 	} else if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
16554 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
16555 		    "Read Attribute Command for Media Identification is not "
16556 		    "supported on the HBA that this drive is attached to.");
16557 		result = ENOTTY;
16558 	}
16559 
16560 	kmem_free(buffer, size);
16561 	un->un_status = 0;
16562 
16563 	return (result);
16564 }
16565 
16566 
16567 static int
16568 st_get_media_id_via_media_serial_cmd(struct scsi_tape *un, ubufunc_t bufunc)
16569 {
16570 	char cdb[CDB_GROUP5];
16571 	struct uscsi_cmd *ucmd;
16572 	struct scsi_extended_sense sense;
16573 	int rval;
16574 	int size = max(un->un_media_id_len, ID_SIZE);
16575 	caddr_t buf;
16576 
16577 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_media_serial_cmd);
16578 
16579 	if (un->un_sd->sd_inq->inq_ansi < 3) {
16580 		return (ENOTTY);
16581 	}
16582 
16583 	ucmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
16584 upsize:
16585 	buf = kmem_alloc(size, KM_SLEEP);
16586 
16587 	cdb[0] = (char)SCMD_SVC_ACTION_IN_G5;
16588 	cdb[1] = SSVC_ACTION_READ_MEDIA_SERIAL;
16589 	cdb[2] = 0;
16590 	cdb[3] = 0;
16591 	cdb[4] = 0;
16592 	cdb[5] = 0;
16593 	cdb[6] = (char)(size >> 24);
16594 	cdb[7] = (char)(size >> 16);
16595 	cdb[8] = (char)(size >> 8);
16596 	cdb[9] = (char)(size);
16597 	cdb[10] = 0;
16598 	cdb[11] = 0;
16599 
16600 	ucmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
16601 	ucmd->uscsi_timeout = un->un_dp->non_motion_timeout;
16602 	ucmd->uscsi_cdb = &cdb[0];
16603 	ucmd->uscsi_cdblen = sizeof (cdb);
16604 	ucmd->uscsi_bufaddr = buf;
16605 	ucmd->uscsi_buflen = size;
16606 	ucmd->uscsi_rqbuf = (caddr_t)&sense;
16607 	ucmd->uscsi_rqlen = sizeof (sense);
16608 
16609 	rval = bufunc(un, ucmd, FKIOCTL);
16610 
16611 	if (rval || ucmd->uscsi_status != 0) {
16612 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16613 		    "media serial command returned %d scsi_status %d"
16614 		    " rqstatus %d", rval, ucmd->uscsi_status,
16615 		    ucmd->uscsi_rqstatus);
16616 		/*
16617 		 * If this returns invalid operation code don't try again.
16618 		 */
16619 		if (sense.es_key == KEY_ILLEGAL_REQUEST &&
16620 		    sense.es_add_code == 0x20) {
16621 			rval = ENOTTY;
16622 		} else if (rval == 0) {
16623 			rval = EIO;
16624 		}
16625 		un->un_status = 0;
16626 	} else {
16627 		int act_size;
16628 
16629 		/*
16630 		 * get reported size.
16631 		 */
16632 		act_size = (int)buf[3] | (int)(buf[2] << 8) |
16633 		    (int)(buf[1] << 16) | (int)(buf[0] << 24);
16634 
16635 		/* documentation says mod 4. */
16636 		while (act_size & 3) {
16637 			act_size++;
16638 		}
16639 
16640 		/*
16641 		 * If reported size is larger that we our buffer.
16642 		 * Free the old one and allocate one that is larger
16643 		 * enough and re-issuse the command.
16644 		 */
16645 		if (act_size + 4 > size) {
16646 			kmem_free(buf, size);
16647 			size = act_size + 4;
16648 			goto upsize;
16649 		}
16650 
16651 		if (act_size == 0) {
16652 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16653 			    "media serial number is not available");
16654 			un->un_status = 0;
16655 			rval = 0;
16656 		} else {
16657 			/*
16658 			 * set data pointer to point to the start
16659 			 * of that serial number.
16660 			 */
16661 			un->un_media_id_method =
16662 			    st_get_media_id_via_media_serial_cmd;
16663 			rval =
16664 			    st_check_if_media_changed(un, &buf[4], act_size);
16665 		}
16666 	}
16667 
16668 	kmem_free(ucmd, sizeof (struct uscsi_cmd));
16669 	kmem_free(buf, size);
16670 
16671 	return (rval);
16672 }
16673 
16674 
16675 /* ARGSUSED */
16676 static int
16677 st_bogus_media_id(struct scsi_tape *un, ubufunc_t bufunc)
16678 {
16679 	ST_FUNC(ST_DEVINFO, st_bogus_media_id);
16680 
16681 	ASSERT(un->un_media_id == NULL || un->un_media_id == bogusID);
16682 	ASSERT(un->un_media_id_len == 0);
16683 	un->un_media_id = (char *)bogusID;
16684 	un->un_media_id_len = 0;
16685 	return (0);
16686 }
16687 
16688 typedef int (*media_chk_function)(struct scsi_tape *, ubufunc_t bufunc);
16689 
16690 media_chk_function media_chk_functions[] = {
16691 	st_get_media_id_via_media_serial_cmd,
16692 	st_get_media_id_via_read_attribute,
16693 	st_bogus_media_id
16694 };
16695 
16696 static int
16697 st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc)
16698 {
16699 	int result = 0;
16700 	int i;
16701 
16702 	ST_FUNC(ST_DEVINFO, st_get_media_identification);
16703 
16704 	for (i = 0; i < ST_NUM_MEMBERS(media_chk_functions); i++) {
16705 		if (result == ENOTTY) {
16706 			/*
16707 			 * Last operation type not supported by this device.
16708 			 * Make so next time it doesn`t do that again.
16709 			 */
16710 			un->un_media_id_method = media_chk_functions[i];
16711 		} else if (un->un_media_id_method != media_chk_functions[i] &&
16712 		    un->un_media_id_method != st_get_media_identification) {
16713 			continue;
16714 		}
16715 		result = media_chk_functions[i](un, bufunc);
16716 		/*
16717 		 * If result indicates the function was successful or
16718 		 * that the media is not the same as last known, break.
16719 		 */
16720 		if (result == 0 || result == ESPIPE) {
16721 			break;
16722 		}
16723 	}
16724 
16725 	return (result);
16726 }
16727 
16728 static errstate
16729 st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
16730     errstate onentry)
16731 {
16732 
16733 	int ret;
16734 	st_err_info *errinfo;
16735 	recov_info *ri = (recov_info *)pkt->pkt_private;
16736 
16737 	ST_FUNC(ST_DEVINFO, st_command_recovery);
16738 
16739 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16740 
16741 	ASSERT(un->un_recov_buf_busy == 0);
16742 
16743 	/*
16744 	 * Don't try and recover a reset that this device sent.
16745 	 */
16746 	if (un->un_rsvd_status & ST_INITIATED_RESET &&
16747 	    onentry == DEVICE_RESET) {
16748 		return (COMMAND_DONE_ERROR);
16749 	}
16750 
16751 	/*
16752 	 * See if expected position was passed with scsi_pkt.
16753 	 */
16754 	if (ri->privatelen == sizeof (recov_info)) {
16755 
16756 		/*
16757 		 * Not for this command.
16758 		 */
16759 		if (ri->cmd_attrib->do_not_recover) {
16760 			return (COMMAND_DONE_ERROR);
16761 		}
16762 
16763 		/*
16764 		 * Create structure to hold all error state info.
16765 		 */
16766 		errinfo = kmem_zalloc(ST_ERR_INFO_SIZE, KM_SLEEP);
16767 		errinfo->ei_error_type = onentry;
16768 		errinfo->ei_failing_bp = ri->cmd_bp;
16769 		COPY_POS(&errinfo->ei_expected_pos, &ri->pos);
16770 	} else {
16771 		/* disabled */
16772 		return (COMMAND_DONE_ERROR);
16773 	}
16774 
16775 	bcopy(pkt, &errinfo->ei_failed_pkt, scsi_pkt_size());
16776 	bcopy(pkt->pkt_scbp, &errinfo->ei_failing_status, SECMDS_STATUS_SIZE);
16777 	ret = ddi_taskq_dispatch(un->un_recov_taskq, st_recover, errinfo,
16778 	    DDI_NOSLEEP);
16779 	ASSERT(ret == DDI_SUCCESS);
16780 	if (ret != DDI_SUCCESS) {
16781 		kmem_free(errinfo, ST_ERR_INFO_SIZE);
16782 		return (COMMAND_DONE_ERROR);
16783 	}
16784 	return (JUST_RETURN); /* release calling thread */
16785 }
16786 
16787 
16788 static void
16789 st_recov_ret(struct scsi_tape *un, st_err_info *errinfo, errstate err)
16790 {
16791 	int error_number;
16792 	buf_t *bp;
16793 
16794 
16795 	ST_FUNC(ST_DEVINFO, st_recov_ret);
16796 
16797 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16798 #if !defined(lint)
16799 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
16800 #endif
16801 
16802 	bp = errinfo->ei_failing_bp;
16803 	kmem_free(errinfo, ST_ERR_INFO_SIZE);
16804 
16805 	switch (err) {
16806 	case JUST_RETURN:
16807 		mutex_exit(&un->un_sd->sd_mutex);
16808 		return;
16809 
16810 	case COMMAND_DONE:
16811 	case COMMAND_DONE_ERROR_RECOVERED:
16812 		ST_DO_KSTATS(bp, kstat_runq_exit);
16813 		error_number = 0;
16814 		break;
16815 
16816 	default:
16817 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16818 		    "st_recov_ret with unhandled errstat %d\n", err);
16819 		/* FALLTHROUGH */
16820 	case COMMAND_DONE_ERROR:
16821 		un->un_pos.pmode = invalid;
16822 		un->un_running.pmode = invalid;
16823 		/* FALLTHROUGH */
16824 	case COMMAND_DONE_EACCES:
16825 		ST_DO_KSTATS(bp, kstat_waitq_exit);
16826 		ST_DO_ERRSTATS(un, st_transerrs);
16827 		error_number = EIO;
16828 		st_set_pe_flag(un);
16829 		break;
16830 
16831 	}
16832 
16833 	st_bioerror(bp, error_number);
16834 	st_done_and_mutex_exit(un, bp);
16835 }
16836 
16837 
16838 static void
16839 st_recover(void *arg)
16840 {
16841 	st_err_info *const errinfo = (st_err_info *)arg;
16842 	uchar_t com = errinfo->ei_failed_pkt.pkt_cdbp[0];
16843 	struct scsi_tape *un;
16844 	tapepos_t cur_pos;
16845 	int rval;
16846 	errstate status = COMMAND_DONE_ERROR;
16847 	recov_info *rcv;
16848 	buf_t *bp;
16849 
16850 
16851 	rcv = errinfo->ei_failed_pkt.pkt_private;
16852 	ASSERT(rcv->privatelen == sizeof (recov_info));
16853 	bp = rcv->cmd_bp;
16854 
16855 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16856 
16857 	ASSERT(un != NULL);
16858 
16859 	mutex_enter(ST_MUTEX);
16860 
16861 	ST_FUNC(ST_DEVINFO, st_recover);
16862 
16863 	ST_CDB(ST_DEVINFO, "Recovering command",
16864 	    (caddr_t)errinfo->ei_failed_pkt.pkt_cdbp);
16865 	ST_SENSE(ST_DEVINFO, "sense status for failed command",
16866 	    (caddr_t)&errinfo->ei_failing_status,
16867 	    sizeof (struct scsi_arq_status));
16868 	ST_POS(ST_DEVINFO, rcv->cmd_attrib->recov_pos_type == POS_STARTING ?
16869 	    "starting position for recovery command" :
16870 	    "expected position for recovery command",
16871 	    &errinfo->ei_expected_pos);
16872 
16873 	rval = st_test_path_to_device(un);
16874 
16875 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16876 	    "st_recover called with %s, TUR returned %d\n",
16877 	    errstatenames[errinfo->ei_error_type], rval);
16878 	/*
16879 	 * If the drive responed to the TUR lets try and get it to sync
16880 	 * any data it might have in the buffer.
16881 	 */
16882 	if (rval == 0 && rcv->cmd_attrib->chg_tape_data) {
16883 		rval = st_rcmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
16884 		if (rval) {
16885 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16886 			    "st_recover failed to flush, returned %d\n", rval);
16887 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16888 			return;
16889 		}
16890 	}
16891 	switch (errinfo->ei_error_type) {
16892 	case ATTEMPT_RETRY:
16893 	case COMMAND_TIMEOUT:
16894 	case DEVICE_RESET:
16895 	case PATH_FAILED:
16896 		/*
16897 		 * For now if we can't talk to the device we are done.
16898 		 * If the drive is reserved we can try to get it back.
16899 		 */
16900 		if (rval != 0 && rval != EACCES) {
16901 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16902 			return;
16903 		}
16904 
16905 		/*
16906 		 * If reservation conflict and do a preempt, fail it.
16907 		 */
16908 		if ((un->un_rsvd_status &
16909 		    (ST_APPLICATION_RESERVATIONS | ST_RESERVE)) != 0) {
16910 			if ((errinfo->ei_failed_pkt.pkt_cdbp[0] ==
16911 			    SCMD_PERSISTENT_RESERVE_OUT) &&
16912 			    (errinfo->ei_failed_pkt.pkt_cdbp[1] ==
16913 			    ST_SA_SCSI3_PREEMPT) &&
16914 			    (SCBP_C(&errinfo->ei_failed_pkt) ==
16915 			    STATUS_RESERVATION_CONFLICT)) {
16916 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16917 				return;
16918 			}
16919 		}
16920 
16921 		/*
16922 		 * If we have already set a scsi II reserve and get a
16923 		 * conflict on a scsi III type reserve fail without
16924 		 * any attempt to recover.
16925 		 */
16926 		if ((un->un_rsvd_status & ST_RESERVE | ST_PRESERVE_RESERVE) &&
16927 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] ==
16928 		    SCMD_PERSISTENT_RESERVE_OUT) ||
16929 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] ==
16930 		    SCMD_PERSISTENT_RESERVE_IN)) {
16931 			st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16932 			return;
16933 		}
16934 
16935 		/*
16936 		 * If scsi II lost reserve try and get it back.
16937 		 */
16938 		if ((((un->un_rsvd_status &
16939 		    (ST_LOST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
16940 		    ST_LOST_RESERVE)) &&
16941 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] != SCMD_RELEASE)) {
16942 			rval = st_reserve_release(un, ST_RESERVE,
16943 			    st_uscsi_rcmd);
16944 			if (rval != 0) {
16945 				if (st_take_ownership(un, st_uscsi_rcmd) != 0) {
16946 					st_recov_ret(un, errinfo,
16947 					    COMMAND_DONE_EACCES);
16948 					return;
16949 				}
16950 			}
16951 			un->un_rsvd_status |= ST_RESERVE;
16952 			un->un_rsvd_status &= ~(ST_RELEASE | ST_LOST_RESERVE |
16953 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
16954 		}
16955 		rval = st_make_sure_mode_data_is_correct(un, st_uscsi_rcmd);
16956 		if (rval) {
16957 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16958 			return;
16959 		}
16960 		break;
16961 	case DEVICE_TAMPER:
16962 		/*
16963 		 * Check if the ASC/ASCQ says mode data has changed.
16964 		 */
16965 		if ((errinfo->ei_failing_status.sts_sensedata.es_add_code ==
16966 		    0x2a) &&
16967 		    (errinfo->ei_failing_status.sts_sensedata.es_qual_code ==
16968 		    0x01)) {
16969 			/*
16970 			 * See if mode sense changed.
16971 			 */
16972 			rval = st_make_sure_mode_data_is_correct(un,
16973 			    st_uscsi_rcmd);
16974 			if (rval) {
16975 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16976 				return;
16977 			}
16978 		}
16979 		/*
16980 		 * if we have a media id and its not bogus.
16981 		 * Check to see if it the same.
16982 		 */
16983 		if (un->un_media_id != NULL && un->un_media_id != bogusID) {
16984 			rval = st_get_media_identification(un, st_uscsi_rcmd);
16985 			if (rval == ESPIPE) {
16986 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16987 				return;
16988 			}
16989 		}
16990 		break;
16991 	default:
16992 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16993 		    "Unhandled error type %s in st_recover() 0x%x\n",
16994 		    errstatenames[errinfo->ei_error_type], com);
16995 	}
16996 
16997 	/*
16998 	 * if command is retriable retry it.
16999 	 * Special case here. The command attribute for SCMD_REQUEST_SENSE
17000 	 * does not say that it is retriable. That because if you reissue a
17001 	 * request sense and the target responds the sense data will have
17002 	 * been consumed and no long be valid. If we get a busy status on
17003 	 * request sense while the state is ST_STATE_SENSING this will
17004 	 * reissue that pkt.
17005 	 *
17006 	 * XXX If this request sense gets sent to a different port then
17007 	 * the original command that failed was sent on it will not get
17008 	 * valid sense data for that command.
17009 	 */
17010 	if (rcv->cmd_attrib->retriable || un->un_rqs_bp == bp) {
17011 		status = st_recover_reissue_pkt(un, &errinfo->ei_failed_pkt);
17012 
17013 	/*
17014 	 * if drive doesn't support read position we are done
17015 	 */
17016 	} else if (un->un_read_pos_type == NO_POS) {
17017 		status = COMMAND_DONE_ERROR;
17018 	/*
17019 	 * If this command results in a changed tape position,
17020 	 * lets see where we are.
17021 	 */
17022 	} else if (rcv->cmd_attrib->chg_tape_pos) {
17023 		/*
17024 		 * XXX May be a reason to choose a different type here.
17025 		 * Long format has file position information.
17026 		 * Short and Extended have information about whats
17027 		 * in the buffer. St's positioning assumes in the buffer
17028 		 * to be the same as on tape.
17029 		 */
17030 		rval = st_compare_expected_position(un, errinfo,
17031 		    rcv->cmd_attrib, &cur_pos);
17032 		if (rval == 0) {
17033 			status = COMMAND_DONE;
17034 		} else if (rval == EAGAIN) {
17035 			status = st_recover_reissue_pkt(un,
17036 			    &errinfo->ei_failed_pkt);
17037 		} else {
17038 			status = COMMAND_DONE_ERROR;
17039 		}
17040 	} else {
17041 		ASSERT(0);
17042 	}
17043 
17044 	st_recov_ret(un, errinfo, status);
17045 }
17046 
17047 static void
17048 st_recov_cb(struct scsi_pkt *pkt)
17049 {
17050 	struct scsi_tape *un;
17051 	struct buf *bp;
17052 	recov_info *rcv;
17053 	errstate action = COMMAND_DONE_ERROR;
17054 	int timout = ST_TRAN_BUSY_TIMEOUT; /* short (default) timeout */
17055 
17056 	/*
17057 	 * Get the buf from the packet.
17058 	 */
17059 	rcv = pkt->pkt_private;
17060 	ASSERT(rcv->privatelen == sizeof (recov_info));
17061 	bp = rcv->cmd_bp;
17062 
17063 	/*
17064 	 * get the unit from the buf.
17065 	 */
17066 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
17067 	ASSERT(un != NULL);
17068 
17069 	ST_FUNC(ST_DEVINFO, st_recov_cb);
17070 
17071 	mutex_enter(ST_MUTEX);
17072 
17073 	ASSERT(bp == un->un_recov_buf);
17074 
17075 
17076 	switch (pkt->pkt_reason) {
17077 	case CMD_CMPLT:
17078 		if (un->un_arq_enabled && pkt->pkt_state & STATE_ARQ_DONE) {
17079 			action = st_handle_autosense(un, bp, &rcv->pos);
17080 		} else  if ((SCBP(pkt)->sts_busy) ||
17081 		    (SCBP(pkt)->sts_chk) ||
17082 		    (SCBP(pkt)->sts_vu7)) {
17083 			action = st_check_error(un, pkt);
17084 		} else {
17085 			action = COMMAND_DONE;
17086 		}
17087 		break;
17088 	case CMD_TIMEOUT:
17089 		action = COMMAND_TIMEOUT;
17090 		break;
17091 	case CMD_TRAN_ERR:
17092 		action = QUE_COMMAND;
17093 		break;
17094 	case CMD_DEV_GONE:
17095 		if (un->un_multipath)
17096 			action = PATH_FAILED;
17097 		else
17098 			action = COMMAND_DONE_ERROR;
17099 		break;
17100 	default:
17101 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
17102 		    "pkt_reason not handled yet %s",
17103 		    scsi_rname(pkt->pkt_reason));
17104 		action = COMMAND_DONE_ERROR;
17105 	}
17106 
17107 	/*
17108 	 * check for undetected path failover.
17109 	 */
17110 	if (un->un_multipath) {
17111 		if (scsi_pkt_allocated_correctly(pkt) &&
17112 		    (un->un_last_path_instance != pkt->pkt_path_instance)) {
17113 			if (un->un_state > ST_STATE_OPENING) {
17114 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17115 				    "Failover detected in recovery, action is "
17116 				    "%s\n", errstatenames[action]);
17117 			}
17118 			un->un_last_path_instance = pkt->pkt_path_instance;
17119 		}
17120 	}
17121 
17122 	ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
17123 	    "Recovery call back got %s status on %s\n",
17124 	    errstatenames[action], st_print_scsi_cmd(pkt->pkt_cdbp[0]));
17125 
17126 	switch (action) {
17127 	case COMMAND_DONE:
17128 		break;
17129 
17130 	case COMMAND_DONE_EACCES:
17131 		bioerror(bp, EACCES);
17132 		break;
17133 
17134 	case COMMAND_DONE_ERROR_RECOVERED: /* XXX maybe wrong */
17135 		ASSERT(0);
17136 		break;
17137 
17138 	case COMMAND_TIMEOUT:
17139 	case COMMAND_DONE_ERROR:
17140 		bioerror(bp, EIO);
17141 		break;
17142 
17143 	case DEVICE_RESET:
17144 	case QUE_BUSY_COMMAND:
17145 	case PATH_FAILED:
17146 		/* longish timeout */
17147 		timout = ST_STATUS_BUSY_TIMEOUT;
17148 		/* FALLTHRU */
17149 	case QUE_COMMAND:
17150 	case DEVICE_TAMPER:
17151 	case ATTEMPT_RETRY:
17152 		/*
17153 		 * let st_handle_intr_busy put this bp back on waitq and make
17154 		 * checks to see if it is ok to requeue the command.
17155 		 */
17156 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
17157 
17158 		/*
17159 		 * Save the throttle before setting up the timeout
17160 		 */
17161 		if (un->un_throttle) {
17162 			un->un_last_throttle = un->un_throttle;
17163 		}
17164 		mutex_exit(ST_MUTEX);
17165 		if (st_handle_intr_busy(un, bp, timout) == 0) {
17166 			return;		/* timeout is setup again */
17167 		}
17168 		mutex_enter(ST_MUTEX);
17169 		un->un_pos.pmode = invalid;
17170 		un->un_err_resid = bp->b_resid = bp->b_bcount;
17171 		st_bioerror(bp, EIO);
17172 		st_set_pe_flag(un);
17173 		break;
17174 
17175 	default:
17176 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
17177 		    "Unhandled recovery state 0x%x\n", action);
17178 		un->un_pos.pmode = invalid;
17179 		un->un_err_resid = bp->b_resid = bp->b_bcount;
17180 		st_bioerror(bp, EIO);
17181 		st_set_pe_flag(un);
17182 		break;
17183 	}
17184 
17185 	st_done_and_mutex_exit(un, bp);
17186 }
17187 
17188 static int
17189 st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait)
17190 {
17191 	struct buf *bp;
17192 	int err;
17193 
17194 	ST_FUNC(ST_DEVINFO, st_rcmd);
17195 
17196 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
17197 	    "st_rcmd(un = 0x%p, com = 0x%x, count = %"PRIx64", wait = %d)\n",
17198 	    (void *)un, com, count, wait);
17199 
17200 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
17201 	ASSERT(mutex_owned(ST_MUTEX));
17202 
17203 #ifdef STDEBUG
17204 	if ((st_debug & 0x7)) {
17205 		st_debug_cmds(un, com, count, wait);
17206 	}
17207 #endif
17208 
17209 	while (un->un_recov_buf_busy)
17210 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17211 	un->un_recov_buf_busy = 1;
17212 
17213 	bp = un->un_recov_buf;
17214 	bzero(bp, sizeof (buf_t));
17215 
17216 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
17217 
17218 	err = st_setup_cmd(un, bp, com, count);
17219 
17220 	un->un_recov_buf_busy = 0;
17221 
17222 	cv_signal(&un->un_recov_buf_cv);
17223 
17224 	return (err);
17225 }
17226 
17227 /* args used */
17228 static int
17229 st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
17230 {
17231 	int rval;
17232 	buf_t *bp;
17233 
17234 	ST_FUNC(ST_DEVINFO, st_uscsi_rcmd);
17235 	ASSERT(flag == FKIOCTL);
17236 
17237 	/*
17238 	 * Get buffer resources...
17239 	 */
17240 	while (un->un_recov_buf_busy)
17241 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17242 	un->un_recov_buf_busy = 1;
17243 
17244 	bp = un->un_recov_buf;
17245 	bzero(bp, sizeof (buf_t));
17246 
17247 	bp->b_forw = (struct buf *)(uintptr_t)ucmd->uscsi_cdb[0];
17248 	bp->b_back = (struct buf *)ucmd;
17249 
17250 	mutex_exit(ST_MUTEX);
17251 	rval = scsi_uscsi_handle_cmd(un->un_dev, UIO_SYSSPACE, ucmd,
17252 	    st_strategy, bp, NULL);
17253 	mutex_enter(ST_MUTEX);
17254 
17255 	ucmd->uscsi_resid = bp->b_resid;
17256 
17257 	/*
17258 	 * Free resources
17259 	 */
17260 	un->un_recov_buf_busy = 0;
17261 	cv_signal(&un->un_recov_buf_cv);
17262 
17263 	return (rval);
17264 }
17265 
17266 /*
17267  * Add data to scsi_pkt to help know what to do if the command fails.
17268  */
17269 static void
17270 st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
17271     struct scsi_pkt *pkt)
17272 {
17273 	uint64_t count;
17274 	recov_info *rinfo = (recov_info *)pkt->pkt_private;
17275 
17276 	ST_FUNC(ST_DEVINFO, st_add_recovery_info_to_pkt);
17277 
17278 	ASSERT(rinfo->privatelen == sizeof (pkt_info) ||
17279 	    rinfo->privatelen == sizeof (recov_info));
17280 
17281 	SET_BP_PKT(bp, pkt);
17282 	rinfo->cmd_bp = bp;
17283 
17284 	if (rinfo->privatelen != sizeof (recov_info)) {
17285 		return;
17286 	}
17287 
17288 	rinfo->cmd_bp = bp;
17289 
17290 	rinfo->cmd_attrib = NULL;
17291 
17292 	/*
17293 	 * lookup the command attributes and add them to the recovery info.
17294 	 */
17295 	rinfo->cmd_attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
17296 
17297 	ASSERT(rinfo->cmd_attrib);
17298 
17299 	/*
17300 	 * For commands that there is no way to figure the expected position
17301 	 * once completed, we save the position the command was started from
17302 	 * so that if they fail we can position back and try again.
17303 	 * This has already been done in st_cmd() or st_iscsi_cmd().
17304 	 */
17305 	if (rinfo->cmd_attrib->recov_pos_type == POS_STARTING) {
17306 		/* save current position as the starting position. */
17307 		COPY_POS(&rinfo->pos, &un->un_pos);
17308 		un->un_running.pmode = invalid;
17309 		return;
17310 	}
17311 
17312 	/*
17313 	 * Don't want to update the running position for recovery.
17314 	 */
17315 	if (bp == un->un_recov_buf) {
17316 		rinfo->pos.pmode = un->un_running.pmode;
17317 		return;
17318 	}
17319 	/*
17320 	 * If running position is invalid copy the current position.
17321 	 * Running being set invalid means we are not in a read, write
17322 	 * or write filemark sequence.
17323 	 * We'll copy the current position and start from there.
17324 	 */
17325 	if (un->un_running.pmode == invalid) {
17326 		COPY_POS(&un->un_running, &un->un_pos);
17327 		COPY_POS(&rinfo->pos, &un->un_running);
17328 	} else {
17329 		COPY_POS(&rinfo->pos, &un->un_running);
17330 		if (rinfo->pos.pmode == legacy) {
17331 			/*
17332 			 * Always should be more logical blocks then
17333 			 * data blocks and files marks.
17334 			 */
17335 			ASSERT((rinfo->pos.blkno >= 0) ?
17336 			    rinfo->pos.lgclblkno >=
17337 			    (rinfo->pos.blkno + rinfo->pos.fileno) : 1);
17338 		}
17339 	}
17340 
17341 	/*
17342 	 * If the command is not expected to change the drive position
17343 	 * then the running position should be the expected position.
17344 	 */
17345 	if (rinfo->cmd_attrib->chg_tape_pos == 0) {
17346 		ASSERT(rinfo->cmd_attrib->chg_tape_direction == DIR_NONE);
17347 		return;
17348 	}
17349 
17350 	if (rinfo->cmd_attrib->explicit_cmd_set) {
17351 		ASSERT(rinfo->pos.pmode != invalid);
17352 		ASSERT(rinfo->cmd_attrib->get_cnt);
17353 		count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17354 		/*
17355 		 * This is a user generated CDB.
17356 		 */
17357 		if (bp == un->un_sbufp) {
17358 			uint64_t lbn;
17359 
17360 			lbn = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17361 
17362 			/*
17363 			 * See if this CDB will generate a locate or change
17364 			 * partition.
17365 			 */
17366 			if ((lbn != un->un_running.lgclblkno) ||
17367 			    (pkt->pkt_cdbp[3] != un->un_running.partition)) {
17368 				rinfo->pos.partition = pkt->pkt_cdbp[3];
17369 				rinfo->pos.pmode = logical;
17370 				rinfo->pos.lgclblkno = lbn;
17371 				un->un_running.partition = pkt->pkt_cdbp[3];
17372 				un->un_running.pmode = logical;
17373 				un->un_running.lgclblkno = lbn;
17374 			}
17375 		} else {
17376 			uint64_t lbn = un->un_running.lgclblkno;
17377 
17378 			pkt->pkt_cdbp[3]  = (uchar_t)un->un_running.partition;
17379 
17380 			pkt->pkt_cdbp[4]  = (uchar_t)(lbn >> 56);
17381 			pkt->pkt_cdbp[5]  = (uchar_t)(lbn >> 48);
17382 			pkt->pkt_cdbp[6]  = (uchar_t)(lbn >> 40);
17383 			pkt->pkt_cdbp[7]  = (uchar_t)(lbn >> 32);
17384 			pkt->pkt_cdbp[8]  = (uchar_t)(lbn >> 24);
17385 			pkt->pkt_cdbp[9]  = (uchar_t)(lbn >> 16);
17386 			pkt->pkt_cdbp[10] = (uchar_t)(lbn >> 8);
17387 			pkt->pkt_cdbp[11] = (uchar_t)(lbn);
17388 		}
17389 		rinfo->pos.lgclblkno += count;
17390 		rinfo->pos.blkno += count;
17391 		un->un_running.lgclblkno += count;
17392 		return;
17393 	}
17394 
17395 	if (rinfo->cmd_attrib->chg_tape_pos) {
17396 
17397 		/* should not have got an invalid position from running. */
17398 		if (un->un_mediastate == MTIO_INSERTED) {
17399 			ASSERT(rinfo->pos.pmode != invalid);
17400 		}
17401 
17402 		/* should have either a get count or or get lba function */
17403 		ASSERT(rinfo->cmd_attrib->get_cnt != NULL ||
17404 		    rinfo->cmd_attrib->get_lba != NULL);
17405 
17406 		/* only explicit commands have both and they're handled above */
17407 		ASSERT(!(rinfo->cmd_attrib->get_cnt != NULL &&
17408 		    rinfo->cmd_attrib->get_lba != NULL));
17409 
17410 		/* if it has a get count function */
17411 		if (rinfo->cmd_attrib->get_cnt != NULL) {
17412 			count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17413 			if (count == 0) {
17414 				return;
17415 			}
17416 			/*
17417 			 * Changes position but doesn't transfer data.
17418 			 * i.e. rewind, write_file_mark and load.
17419 			 */
17420 			if (rinfo->cmd_attrib->transfers_data == TRAN_NONE) {
17421 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17422 				case DIR_NONE: /* Erase */
17423 					ASSERT(rinfo->cmd_attrib->cmd ==
17424 					    SCMD_ERASE);
17425 					break;
17426 				case DIR_FORW: /* write_file_mark */
17427 					rinfo->pos.fileno += count;
17428 					rinfo->pos.lgclblkno += count;
17429 					rinfo->pos.blkno = 0;
17430 					un->un_running.fileno += count;
17431 					un->un_running.lgclblkno += count;
17432 					un->un_running.blkno = 0;
17433 					break;
17434 				case DIR_REVC: /* rewind */
17435 					rinfo->pos.fileno = 0;
17436 					rinfo->pos.lgclblkno = 0;
17437 					rinfo->pos.blkno = 0;
17438 					rinfo->pos.eof = ST_NO_EOF;
17439 					rinfo->pos.pmode = legacy;
17440 					un->un_running.fileno = 0;
17441 					un->un_running.lgclblkno = 0;
17442 					un->un_running.blkno = 0;
17443 					un->un_running.eof = ST_NO_EOF;
17444 					if (un->un_running.pmode != legacy)
17445 						un->un_running.pmode = legacy;
17446 					break;
17447 				case DIR_EITH: /* Load unload */
17448 					ASSERT(rinfo->cmd_attrib->cmd ==
17449 					    SCMD_LOAD);
17450 					switch (count & (LD_LOAD | LD_RETEN |
17451 					    LD_RETEN | LD_HOLD)) {
17452 					case LD_UNLOAD:
17453 					case LD_RETEN:
17454 					case LD_HOLD:
17455 					case LD_LOAD | LD_HOLD:
17456 					case LD_EOT | LD_HOLD:
17457 					case LD_RETEN | LD_HOLD:
17458 						rinfo->pos.pmode = invalid;
17459 						un->un_running.pmode = invalid;
17460 						break;
17461 					case LD_EOT:
17462 					case LD_LOAD | LD_EOT:
17463 						rinfo->pos.eof = ST_EOT;
17464 						rinfo->pos.pmode = invalid;
17465 						un->un_running.eof = ST_EOT;
17466 						un->un_running.pmode = invalid;
17467 						break;
17468 					case LD_LOAD:
17469 					case LD_RETEN | LD_LOAD:
17470 						rinfo->pos.fileno = 0;
17471 						rinfo->pos.lgclblkno = 0;
17472 						rinfo->pos.blkno = 0;
17473 						rinfo->pos.eof = ST_NO_EOF;
17474 						rinfo->pos.pmode = legacy;
17475 						un->un_running.fileno = 0;
17476 						un->un_running.lgclblkno = 0;
17477 						un->un_running.blkno = 0;
17478 						un->un_running.eof = ST_NO_EOF;
17479 						break;
17480 					default:
17481 						ASSERT(0);
17482 					}
17483 					break;
17484 				default:
17485 					ASSERT(0);
17486 					break;
17487 				}
17488 			} else {
17489 				/*
17490 				 * Changes position and does transfer data.
17491 				 * i.e. read or write.
17492 				 */
17493 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17494 				case DIR_FORW:
17495 					rinfo->pos.lgclblkno += count;
17496 					rinfo->pos.blkno += count;
17497 					un->un_running.lgclblkno += count;
17498 					un->un_running.blkno += count;
17499 					break;
17500 				case DIR_REVC:
17501 					rinfo->pos.lgclblkno -= count;
17502 					rinfo->pos.blkno -= count;
17503 					un->un_running.lgclblkno -= count;
17504 					un->un_running.blkno -= count;
17505 					break;
17506 				default:
17507 					ASSERT(0);
17508 					break;
17509 				}
17510 			}
17511 		} else if (rinfo->cmd_attrib->get_lba != NULL) {
17512 			/* Have a get LBA fuction. i.e. Locate */
17513 			ASSERT(rinfo->cmd_attrib->chg_tape_direction ==
17514 			    DIR_EITH);
17515 			count = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17516 			un->un_running.lgclblkno = count;
17517 			un->un_running.blkno = 0;
17518 			un->un_running.fileno = 0;
17519 			un->un_running.pmode = logical;
17520 			rinfo->pos.lgclblkno = count;
17521 			rinfo->pos.pmode = invalid;
17522 		} else {
17523 			ASSERT(0);
17524 		}
17525 		return;
17526 	}
17527 
17528 	ST_CDB(ST_DEVINFO, "Unhanded CDB for position prediction",
17529 	    (char *)pkt->pkt_cdbp);
17530 
17531 }
17532 
17533 static int
17534 st_make_sure_mode_data_is_correct(struct scsi_tape *un, ubufunc_t ubf)
17535 {
17536 	int rval;
17537 
17538 	ST_FUNC(ST_DEVINFO, st_make_sure_mode_data_is_correct);
17539 
17540 	/*
17541 	 * check to see if mode data has changed.
17542 	 */
17543 	rval = st_check_mode_for_change(un, ubf);
17544 	if (rval) {
17545 		rval = st_gen_mode_select(un, ubf, un->un_mspl,
17546 		    sizeof (struct seq_mode));
17547 	}
17548 	if (un->un_tlr_flag != TLR_NOT_SUPPORTED) {
17549 		rval |= st_set_target_TLR_mode(un, ubf);
17550 	}
17551 	return (rval);
17552 }
17553 
17554 static int
17555 st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf)
17556 {
17557 	struct seq_mode *current;
17558 	int rval;
17559 	int i;
17560 	caddr_t this;
17561 	caddr_t that;
17562 
17563 	ST_FUNC(ST_DEVINFO, st_check_mode_for_change);
17564 
17565 	/* recovery called with mode tamper before mode selection */
17566 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
17567 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17568 		    "Mode Select not done yet");
17569 		return (0);
17570 	}
17571 
17572 	current = kmem_zalloc(sizeof (struct seq_mode), KM_SLEEP);
17573 
17574 	rval = st_gen_mode_sense(un, ubf, un->un_comp_page, current,
17575 	    sizeof (struct seq_mode));
17576 	if (rval != 0) {
17577 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17578 		    "Mode Sense for mode verification failed");
17579 		kmem_free(current, sizeof (struct seq_mode));
17580 		return (rval);
17581 	}
17582 
17583 	this = (caddr_t)current;
17584 	that = (caddr_t)un->un_mspl;
17585 
17586 	rval = bcmp(this, that, sizeof (struct seq_mode));
17587 	if (rval == 0) {
17588 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17589 		    "Found no changes in mode data");
17590 	}
17591 #ifdef STDEBUG
17592 	else {
17593 		for (i = 1; i < sizeof (struct seq_mode); i++) {
17594 			if (this[i] != that[i]) {
17595 				ST_RECOV(ST_DEVINFO, st_label, CE_CONT,
17596 				    "sense data changed at byte %d was "
17597 				    "0x%x now 0x%x", i,
17598 				    (uchar_t)that[i], (uchar_t)this[i]);
17599 			}
17600 		}
17601 	}
17602 #endif
17603 	kmem_free(current, sizeof (struct seq_mode));
17604 
17605 	return (rval);
17606 }
17607 
17608 static int
17609 st_test_path_to_device(struct scsi_tape *un)
17610 {
17611 	int rval = 0;
17612 	int limit = st_retry_count;
17613 
17614 	ST_FUNC(ST_DEVINFO, st_test_path_to_device);
17615 
17616 	/*
17617 	 * XXX Newer drives may not RESEVATION CONFLICT a TUR.
17618 	 */
17619 	do {
17620 		if (rval != 0) {
17621 			mutex_exit(ST_MUTEX);
17622 			delay(drv_usectohz(1000000));
17623 			mutex_enter(ST_MUTEX);
17624 		}
17625 		rval = st_rcmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
17626 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17627 		    "ping TUR returned 0x%x", rval);
17628 		limit--;
17629 	} while (((rval == EACCES) || (rval == EBUSY)) && limit);
17630 
17631 	if (un->un_status == KEY_NOT_READY || un->un_mediastate == MTIO_EJECTED)
17632 		rval = 0;
17633 
17634 	return (rval);
17635 }
17636 
17637 /*
17638  * Does read position using recov_buf and doesn't update un_pos.
17639  * Does what ever kind of read position you want.
17640  */
17641 static int
17642 st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
17643     read_pos_data_t *raw)
17644 {
17645 	int rval;
17646 	struct uscsi_cmd cmd;
17647 	struct scsi_arq_status status;
17648 	char cdb[CDB_GROUP1];
17649 
17650 	ST_FUNC(ST_DEVINFO, st_recovery_read_pos);
17651 	bzero(&cmd, sizeof (cmd));
17652 
17653 	cdb[0] = SCMD_READ_POSITION;
17654 	cdb[1] = type;
17655 	cdb[2] = 0;
17656 	cdb[3] = 0;
17657 	cdb[4] = 0;
17658 	cdb[5] = 0;
17659 	cdb[6] = 0;
17660 	cdb[7] = 0;
17661 	cdb[8] = (type == EXT_POS) ? 28 : 0;
17662 	cdb[9] = 0;
17663 
17664 	cmd.uscsi_flags = USCSI_READ | USCSI_RQENABLE;
17665 	cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
17666 	cmd.uscsi_cdb = cdb;
17667 	cmd.uscsi_cdblen = sizeof (cdb);
17668 	cmd.uscsi_rqlen = sizeof (status);
17669 	cmd.uscsi_rqbuf = (caddr_t)&status;
17670 	cmd.uscsi_bufaddr = (caddr_t)raw;
17671 	switch (type) {
17672 	case SHORT_POS:
17673 		cmd.uscsi_buflen = sizeof (tape_position_t);
17674 		break;
17675 	case LONG_POS:
17676 		cmd.uscsi_buflen = sizeof (tape_position_long_t);
17677 		break;
17678 	case EXT_POS:
17679 		cmd.uscsi_buflen = sizeof (tape_position_ext_t);
17680 		break;
17681 	default:
17682 		ASSERT(0);
17683 	}
17684 
17685 	rval = st_uscsi_rcmd(un, &cmd, FKIOCTL);
17686 	if (cmd.uscsi_status) {
17687 		rval = EIO;
17688 	}
17689 	return (rval);
17690 }
17691 
17692 static int
17693 st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
17694     read_pos_data_t *raw)
17695 {
17696 	int rval;
17697 	read_p_types type = un->un_read_pos_type;
17698 
17699 	ST_FUNC(ST_DEVINFO, st_recovery_get_position);
17700 
17701 	do {
17702 		rval = st_recovery_read_pos(un, type, raw);
17703 		if (rval != 0) {
17704 			switch (type) {
17705 			case SHORT_POS:
17706 				type = NO_POS;
17707 				break;
17708 
17709 			case LONG_POS:
17710 				type = EXT_POS;
17711 				break;
17712 
17713 			case EXT_POS:
17714 				type = SHORT_POS;
17715 				break;
17716 
17717 			default:
17718 				type = LONG_POS;
17719 				break;
17720 
17721 			}
17722 		} else {
17723 			if (type != un->un_read_pos_type) {
17724 				un->un_read_pos_type = type;
17725 			}
17726 			break;
17727 		}
17728 	} while (type != NO_POS);
17729 
17730 	if (rval == 0) {
17731 		rval = st_interpret_read_pos(un, read, type,
17732 		    sizeof (read_pos_data_t), (caddr_t)raw, 1);
17733 	}
17734 	return (rval);
17735 }
17736 
17737 /*
17738  * based on the command do we retry, continue or give up?
17739  * possable return values?
17740  *	zero do nothing looks fine.
17741  *	EAGAIN retry.
17742  *	EIO failed makes no sense.
17743  */
17744 static int
17745 st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
17746     cmd_attribute const * cmd_att, tapepos_t *read)
17747 {
17748 	int rval;
17749 	read_pos_data_t *readp_datap;
17750 
17751 	ST_FUNC(ST_DEVINFO, st_compare_expected_position);
17752 
17753 	ASSERT(un != NULL);
17754 	ASSERT(ei != NULL);
17755 	ASSERT(read != NULL);
17756 	ASSERT(cmd_att->chg_tape_pos);
17757 
17758 	COPY_POS(read, &ei->ei_expected_pos);
17759 
17760 	readp_datap = kmem_zalloc(sizeof (read_pos_data_t), KM_SLEEP);
17761 
17762 	rval = st_recovery_get_position(un, read, readp_datap);
17763 
17764 	kmem_free(readp_datap, sizeof (read_pos_data_t));
17765 
17766 	if (rval != 0) {
17767 		return (EIO);
17768 	}
17769 
17770 	ST_POS(ST_DEVINFO, "st_compare_expected_position", read);
17771 
17772 	if ((read->pmode == invalid) ||
17773 	    (ei->ei_expected_pos.pmode == invalid)) {
17774 		return (EIO);
17775 	}
17776 
17777 	/*
17778 	 * Command that changes tape position and have an expected position
17779 	 * if it were to chave completed sucessfully.
17780 	 */
17781 	if (cmd_att->recov_pos_type == POS_EXPECTED) {
17782 		uint32_t count;
17783 		int64_t difference;
17784 		uchar_t reposition = 0;
17785 
17786 		ASSERT(cmd_att->get_cnt);
17787 		count = cmd_att->get_cnt(ei->ei_failed_pkt.pkt_cdbp);
17788 
17789 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17790 		    "Got count from CDB and it was %d\n", count);
17791 
17792 		/*
17793 		 * At expected?
17794 		 */
17795 		if (read->lgclblkno == ei->ei_expected_pos.lgclblkno) {
17796 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17797 			    "Found drive to be at expected position\n");
17798 
17799 			/*
17800 			 * If the command should move tape and it got a busy
17801 			 * it shouldn't be in the expected position.
17802 			 */
17803 			if (ei->ei_failing_status.sts_status.sts_busy != 0) {
17804 				reposition = 1;
17805 
17806 			/*
17807 			 * If the command doesn't transfer data should be good.
17808 			 */
17809 			} else if (cmd_att->transfers_data == TRAN_NONE) {
17810 				return (0); /* Good */
17811 
17812 			/*
17813 			 * Command transfers data, should have done so.
17814 			 */
17815 			} else if (ei->ei_failed_pkt.pkt_state &
17816 			    STATE_XFERRED_DATA) {
17817 				return (0); /* Good */
17818 			} else {
17819 				reposition = 1;
17820 			}
17821 		}
17822 
17823 		if (cmd_att->chg_tape_direction == DIR_FORW) {
17824 			difference =
17825 			    ei->ei_expected_pos.lgclblkno - read->lgclblkno;
17826 
17827 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17828 			    "difference between expected and actual is %"
17829 			    PRId64"\n", difference);
17830 			if (count == difference && reposition == 0) {
17831 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17832 				    "Found failed FORW command, retrying\n");
17833 				return (EAGAIN);
17834 			}
17835 
17836 			/*
17837 			 * If rewound or somewhere between the starting position
17838 			 * and the expected position (partial read or write).
17839 			 * Locate to the starting position and try the whole
17840 			 * thing over again.
17841 			 */
17842 			if ((read->lgclblkno == 0) ||
17843 			    ((difference > 0) && (difference < count))) {
17844 				rval = st_logical_block_locate(un,
17845 				    st_uscsi_rcmd, read,
17846 				    ei->ei_expected_pos.lgclblkno - count,
17847 				    ei->ei_expected_pos.partition);
17848 				if (rval == 0) {
17849 					ST_RECOV(ST_DEVINFO, st_label,
17850 					    CE_NOTE, "reestablished FORW"
17851 					    " command retrying\n");
17852 					return (EAGAIN);
17853 				}
17854 			/*
17855 			 * This handles flushed read ahead on the drive or
17856 			 * an aborted read that presents as a busy and advanced
17857 			 * the tape position.
17858 			 */
17859 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17860 			    ((difference < 0) || (reposition == 1))) {
17861 				rval = st_logical_block_locate(un,
17862 				    st_uscsi_rcmd, read,
17863 				    ei->ei_expected_pos.lgclblkno - count,
17864 				    ei->ei_expected_pos.partition);
17865 				if (rval == 0) {
17866 					ST_RECOV(ST_DEVINFO, st_label,
17867 					    CE_NOTE, "reestablished FORW"
17868 					    " read command retrying\n");
17869 					return (EAGAIN);
17870 				}
17871 			/*
17872 			 * XXX swag seeing difference of 2 on write filemark.
17873 			 * If the space to the starting position works on a
17874 			 * write that means the previous write made it to tape.
17875 			 * If not we lost data and have to give up.
17876 			 *
17877 			 * The plot thickens. Now I am attempting to cover a
17878 			 * count of 1 and a differance of 2 on a write.
17879 			 */
17880 			} else if ((difference > count) || (reposition == 1)) {
17881 				rval = st_logical_block_locate(un,
17882 				    st_uscsi_rcmd, read,
17883 				    ei->ei_expected_pos.lgclblkno - count,
17884 				    ei->ei_expected_pos.partition);
17885 				if (rval == 0) {
17886 					ST_RECOV(ST_DEVINFO, st_label,
17887 					    CE_NOTE, "reestablished FORW"
17888 					    " write command retrying\n");
17889 					return (EAGAIN);
17890 				}
17891 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17892 				    "Seek to block %"PRId64" returned %d\n",
17893 				    ei->ei_expected_pos.lgclblkno - count,
17894 				    rval);
17895 			} else {
17896 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17897 				    "Not expected transfers_data = %d "
17898 				    "difference = %"PRId64,
17899 				    cmd_att->transfers_data, difference);
17900 			}
17901 
17902 			return (EIO);
17903 
17904 		} else if (cmd_att->chg_tape_direction == DIR_REVC) {
17905 			/* Don't think we can write backwards */
17906 			ASSERT(cmd_att->transfers_data != TRAN_WRTE);
17907 			difference =
17908 			    read->lgclblkno - ei->ei_expected_pos.lgclblkno;
17909 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17910 			    "difference between expected and actual is %"
17911 			    PRId64"\n", difference);
17912 			if (count == difference && reposition == 0) {
17913 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17914 				    "Found failed REVC command, retrying\n");
17915 				return (EAGAIN);
17916 			}
17917 			if ((read->lgclblkno == 0) ||
17918 			    ((difference > 0) && (difference < count))) {
17919 				rval = st_logical_block_locate(un,
17920 				    st_uscsi_rcmd, read,
17921 				    ei->ei_expected_pos.lgclblkno + count,
17922 				    ei->ei_expected_pos.partition);
17923 				if (rval == 0) {
17924 					ST_RECOV(ST_DEVINFO, st_label,
17925 					    CE_NOTE, "reestablished REVC"
17926 					    " command retrying\n");
17927 					return (EAGAIN);
17928 				}
17929 			/* This handles read ahead in reverse direction */
17930 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17931 			    (difference < 0) || (reposition == 1)) {
17932 				rval = st_logical_block_locate(un,
17933 				    st_uscsi_rcmd, read,
17934 				    ei->ei_expected_pos.lgclblkno - count,
17935 				    ei->ei_expected_pos.partition);
17936 				if (rval == 0) {
17937 					ST_RECOV(ST_DEVINFO, st_label,
17938 					    CE_NOTE, "reestablished REVC"
17939 					    " read command retrying\n");
17940 					return (EAGAIN);
17941 				}
17942 			} else {
17943 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17944 				    "Not expected transfers_data = %d "
17945 				    "difference = %"PRId64,
17946 				    cmd_att->transfers_data, difference);
17947 			}
17948 			return (EIO);
17949 
17950 		} else {
17951 			/*
17952 			 * Commands that change tape position either
17953 			 * direction or don't change position should not
17954 			 * get here.
17955 			 */
17956 			ASSERT(0);
17957 		}
17958 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17959 		    "Didn't find a recoverable position, Failing\n");
17960 
17961 	/*
17962 	 * Command that changes tape position and can only be recovered
17963 	 * by going back to the point of origin and retrying.
17964 	 *
17965 	 * Example SCMD_SPACE.
17966 	 */
17967 	} else if (cmd_att->recov_pos_type == POS_STARTING) {
17968 		/*
17969 		 * This type of command stores the starting position.
17970 		 * If the read position is the starting position,
17971 		 * reissue the command.
17972 		 */
17973 		if (ei->ei_expected_pos.lgclblkno == read->lgclblkno) {
17974 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17975 			    "Found Space command at starting position, "
17976 			    "Reissuing\n");
17977 			return (EAGAIN);
17978 		}
17979 		/*
17980 		 * Not in the position that the command was originally issued,
17981 		 * Attempt to locate to that position.
17982 		 */
17983 		rval = st_logical_block_locate(un, st_uscsi_rcmd, read,
17984 		    ei->ei_expected_pos.lgclblkno,
17985 		    ei->ei_expected_pos.partition);
17986 		if (rval) {
17987 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17988 			    "Found Space at an unexpected position and locate "
17989 			    "back to starting position failed\n");
17990 			return (EIO);
17991 		}
17992 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17993 		    "Found Space at an unexpected position and locate "
17994 		    "back to starting position worked, Reissuing\n");
17995 		return (EAGAIN);
17996 	}
17997 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17998 	    "Unhandled attribute/expected position", &ei->ei_expected_pos);
17999 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
18000 	    "Read position above did not make sense", read);
18001 	ASSERT(0);
18002 	return (EIO);
18003 }
18004 
18005 static errstate
18006 st_recover_reissue_pkt(struct scsi_tape *un, struct scsi_pkt *oldpkt)
18007 {
18008 	buf_t *bp;
18009 	buf_t *pkt_bp;
18010 	struct scsi_pkt *newpkt;
18011 	cmd_attribute const *attrib;
18012 	recov_info *rcv = oldpkt->pkt_private;
18013 	uint_t cdblen;
18014 	int queued = 0;
18015 	int rval;
18016 	int flags = 0;
18017 	int stat_size =
18018 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
18019 
18020 	ST_FUNC(ST_DEVINFO, st_recover_reissue_pkt);
18021 
18022 	bp = rcv->cmd_bp;
18023 
18024 	if (rcv->privatelen == sizeof (recov_info)) {
18025 		attrib = rcv->cmd_attrib;
18026 	} else {
18027 		attrib = st_lookup_cmd_attribute(oldpkt->pkt_cdbp[0]);
18028 	}
18029 
18030 	/*
18031 	 * Some non-uscsi commands use the b_bcount for values that
18032 	 * have nothing to do with how much data is transfered.
18033 	 * In those cases we need to hide the buf_t from scsi_init_pkt().
18034 	 */
18035 	if ((BP_UCMD(bp)) && (bp->b_bcount)) {
18036 		pkt_bp = bp;
18037 	} else if (attrib->transfers_data == TRAN_NONE) {
18038 		pkt_bp = NULL;
18039 	} else {
18040 		pkt_bp = bp;
18041 	}
18042 
18043 	/*
18044 	 * if this is a queued command make sure it the only one in the
18045 	 * run queue.
18046 	 */
18047 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
18048 		ASSERT(un->un_runqf == un->un_runql);
18049 		ASSERT(un->un_runqf == bp);
18050 		queued = 1;
18051 	}
18052 
18053 	cdblen = scsi_cdb_size[CDB_GROUPID(oldpkt->pkt_cdbp[0])];
18054 
18055 	if (pkt_bp == un->un_rqs_bp) {
18056 		flags |= PKT_CONSISTENT;
18057 		stat_size = 1;
18058 	}
18059 
18060 	newpkt = scsi_init_pkt(ROUTE, NULL, pkt_bp, cdblen,
18061 	    stat_size, rcv->privatelen, flags, NULL_FUNC, NULL);
18062 	if (newpkt == NULL) {
18063 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
18064 		    "Reissue pkt scsi_init_pkt() failure\n");
18065 		return (COMMAND_DONE_ERROR);
18066 	}
18067 
18068 	ASSERT(newpkt->pkt_resid == 0);
18069 	bp->b_flags &= ~(B_DONE);
18070 	bp->b_resid = 0;
18071 	st_bioerror(bp, 0);
18072 
18073 	bcopy(oldpkt->pkt_private, newpkt->pkt_private, rcv->privatelen);
18074 
18075 	newpkt->pkt_comp = oldpkt->pkt_comp;
18076 	newpkt->pkt_time = oldpkt->pkt_time;
18077 
18078 	bzero(newpkt->pkt_scbp, stat_size);
18079 	bcopy(oldpkt->pkt_cdbp, newpkt->pkt_cdbp, cdblen);
18080 
18081 	newpkt->pkt_state = 0;
18082 	newpkt->pkt_statistics = 0;
18083 
18084 	/*
18085 	 * oldpkt passed in was a copy of the original.
18086 	 * to distroy we need the address of the original.
18087 	 */
18088 	oldpkt = BP_PKT(bp);
18089 
18090 	if (oldpkt == un->un_rqs) {
18091 		ASSERT(bp == un->un_rqs_bp);
18092 		un->un_rqs = newpkt;
18093 	}
18094 
18095 	SET_BP_PKT(bp, newpkt);
18096 
18097 	scsi_destroy_pkt(oldpkt);
18098 
18099 	rval = st_transport(un, newpkt);
18100 	if (rval == TRAN_ACCEPT) {
18101 		return (JUST_RETURN);
18102 	}
18103 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
18104 	    "Reissue pkt st_transport(0x%x) failure\n", rval);
18105 	if (rval != TRAN_BUSY) {
18106 		return (COMMAND_DONE_ERROR);
18107 	}
18108 	mutex_exit(ST_MUTEX);
18109 	rval = st_handle_start_busy(un, bp, ST_TRAN_BUSY_TIMEOUT, queued);
18110 	mutex_enter(ST_MUTEX);
18111 	if (rval) {
18112 		return (COMMAND_DONE_ERROR);
18113 	}
18114 
18115 	return (JUST_RETURN);
18116 }
18117 
18118 static int
18119 st_transport(struct scsi_tape *un, struct scsi_pkt *pkt)
18120 {
18121 	int status;
18122 
18123 	ST_FUNC(ST_DEVINFO, st_transport);
18124 
18125 	ST_CDB(ST_DEVINFO, "transport CDB", (caddr_t)pkt->pkt_cdbp);
18126 
18127 	mutex_exit(ST_MUTEX);
18128 
18129 	status = scsi_transport(pkt);
18130 
18131 	mutex_enter(ST_MUTEX);
18132 
18133 	return (status);
18134 }
18135 
18136 /*
18137  * Removed the buf_t bp from the queue referenced to by head and tail.
18138  * Returns the buf_t pointer if it is found in the queue.
18139  * Returns NULL if it is not found.
18140  */
18141 static buf_t *
18142 st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp)
18143 {
18144 	buf_t *runqbp;
18145 	buf_t *prevbp = NULL;
18146 
18147 	for (runqbp = *head; runqbp != 0; runqbp = runqbp->av_forw) {
18148 		if (runqbp == bp) {
18149 			/* found it, is it at the head? */
18150 			if (runqbp == *head) {
18151 				*head = bp->av_forw;
18152 			} else {
18153 				prevbp->av_forw = bp->av_forw;
18154 			}
18155 			if (*tail == bp) {
18156 				*tail = prevbp;
18157 			}
18158 			bp->av_forw = NULL;
18159 			return (bp); /* found and removed */
18160 		}
18161 		prevbp = runqbp;
18162 	}
18163 	return (NULL);
18164 }
18165 
18166 /*
18167  * Adds a buf_t to the queue pointed to by head and tail.
18168  * Adds it either to the head end or the tail end based on which
18169  * the passed variable end (head or tail) points at.
18170  */
18171 static void
18172 st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp)
18173 {
18174 
18175 	bp->av_forw = NULL;
18176 	if (*head) {
18177 		/* Queue is not empty */
18178 		if (end == *head) {
18179 			/* Add at front of queue */
18180 			bp->av_forw = *head;
18181 			*head = bp;
18182 		} else if (end == *tail) {
18183 			/* Add at end of queue */
18184 			(*tail)->av_forw = bp;
18185 			*tail = bp;
18186 		} else {
18187 			ASSERT(0);
18188 		}
18189 	} else {
18190 		/* Queue is empty */
18191 		*head = bp;
18192 		*tail = bp;
18193 	}
18194 }
18195 
18196 
18197 static uint64_t
18198 st_get_cdb_g0_rw_count(uchar_t *cdb)
18199 {
18200 	uint64_t count;
18201 
18202 	if ((cdb[1]) & 1) {
18203 		/* fixed block mode, the count is the number of blocks */
18204 		count =
18205 		    cdb[2] << 16 |
18206 		    cdb[3] << 8 |
18207 		    cdb[4];
18208 	} else {
18209 		/* variable block mode, the count is the block size */
18210 		count = 1;
18211 	}
18212 	return (count);
18213 }
18214 
18215 static uint64_t
18216 st_get_cdb_g0_sign_count(uchar_t *cdb)
18217 {
18218 	uint64_t count;
18219 
18220 	count =
18221 	    cdb[2] << 16 |
18222 	    cdb[3] << 8 |
18223 	    cdb[4];
18224 	/*
18225 	 * If the sign bit of the 3 byte value is set, extended it.
18226 	 */
18227 	if (count & 0x800000) {
18228 		count |= 0xffffffffff000000;
18229 	}
18230 	return (count);
18231 }
18232 
18233 static uint64_t
18234 st_get_cdb_g0_count(uchar_t *cdb)
18235 {
18236 	uint64_t count;
18237 
18238 	count =
18239 	    cdb[2] << 16 |
18240 	    cdb[3] << 8 |
18241 	    cdb[4];
18242 	return (count);
18243 }
18244 
18245 static uint64_t
18246 st_get_cdb_g5_rw_cnt(uchar_t *cdb)
18247 {
18248 	uint64_t count;
18249 
18250 	if ((cdb[1]) & 1) {
18251 		/* fixed block mode */
18252 		count =
18253 		    cdb[12] << 16 |
18254 		    cdb[13] << 8 |
18255 		    cdb[14];
18256 	} else {
18257 		/* variable block mode */
18258 		count = 1;
18259 	}
18260 	return (count);
18261 }
18262 
18263 static uint64_t
18264 st_get_no_count(uchar_t *cdb)
18265 {
18266 	ASSERT(cdb[0] == SCMD_REWIND);
18267 	return ((uint64_t)cdb[0]);
18268 }
18269 
18270 static uint64_t
18271 st_get_load_options(uchar_t *cdb)
18272 {
18273 	return ((uint64_t)(cdb[4] | (LD_HOLD << 1)));
18274 }
18275 
18276 static uint64_t
18277 st_get_erase_options(uchar_t *cdb)
18278 {
18279 	return (cdb[1] | (cdb[0] << 8));
18280 }
18281 
18282 static uint64_t
18283 st_get_cdb_g1_lba(uchar_t *cdb)
18284 {
18285 	uint64_t lba;
18286 
18287 	lba =
18288 	    cdb[3] << 24 |
18289 	    cdb[4] << 16 |
18290 	    cdb[5] << 8 |
18291 	    cdb[6];
18292 	return (lba);
18293 }
18294 
18295 static uint64_t
18296 st_get_cdb_g5_count(uchar_t *cdb)
18297 {
18298 	uint64_t count =
18299 	    cdb[12] << 16 |
18300 	    cdb[13] << 8 |
18301 	    cdb[14];
18302 
18303 	return (count);
18304 }
18305 
18306 static uint64_t
18307 st_get_cdb_g4g5_cnt(uchar_t *cdb)
18308 {
18309 	uint64_t lba;
18310 
18311 	lba =
18312 	    (uint64_t)cdb[4] << 56 |
18313 	    (uint64_t)cdb[5] << 48 |
18314 	    (uint64_t)cdb[6] << 40 |
18315 	    (uint64_t)cdb[7] << 32 |
18316 	    (uint64_t)cdb[8] << 24 |
18317 	    (uint64_t)cdb[9] << 16 |
18318 	    (uint64_t)cdb[10] << 8 |
18319 	    (uint64_t)cdb[11];
18320 	return (lba);
18321 }
18322 
18323 static const cmd_attribute cmd_attributes[] = {
18324 	{ SCMD_READ,
18325 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_READ, POS_EXPECTED,
18326 	    0, 0, 0, st_get_cdb_g0_rw_count },
18327 	{ SCMD_WRITE,
18328 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18329 	    0, 0, 0, st_get_cdb_g0_rw_count },
18330 	{ SCMD_TEST_UNIT_READY,
18331 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18332 	    0, 0, 0 },
18333 	{ SCMD_REWIND,
18334 	    1, 1, 1, 0, 0, DIR_REVC, TRAN_NONE, POS_EXPECTED,
18335 	    0, 0, 0, st_get_no_count },
18336 	{ SCMD_REQUEST_SENSE,
18337 	    0, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18338 	    0, 0, 0 },
18339 	{ SCMD_READ_BLKLIM,
18340 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18341 	    0, 0, 0 },
18342 	{ SCMD_READ_G4,
18343 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_READ, POS_EXPECTED,
18344 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18345 	{ SCMD_WRITE_G4,
18346 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18347 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18348 	{ SCMD_READ_REVERSE,
18349 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18350 	    0, 0, 0, st_get_cdb_g0_rw_count },
18351 	{ SCMD_READ_REVERSE_G4,
18352 	    1, 0, 1, 1, 1, DIR_REVC, TRAN_READ, POS_EXPECTED,
18353 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18354 	{ SCMD_WRITE_FILE_MARK,
18355 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18356 	    0, 0, 0, st_get_cdb_g0_count },
18357 	{ SCMD_WRITE_FILE_MARK_G4,
18358 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18359 	    0, 0, 0, st_get_cdb_g5_count, st_get_cdb_g4g5_cnt },
18360 	{ SCMD_SPACE,
18361 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18362 	    0, 0, 0, st_get_cdb_g0_sign_count },
18363 	{ SCMD_SPACE_G4,
18364 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18365 	    0, 0, 0, st_get_cdb_g4g5_cnt },
18366 	{ SCMD_INQUIRY,
18367 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18368 	    0, 0, 0 },
18369 	{ SCMD_VERIFY_G0,
18370 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18371 	    0, 0, 0, st_get_cdb_g0_rw_count },
18372 	{ SCMD_VERIFY_G4,
18373 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18374 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18375 	{ SCMD_RECOVER_BUF,
18376 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18377 	    0, 0, 0 },
18378 	{ SCMD_MODE_SELECT,
18379 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18380 	    0, 0, 0 },
18381 	{ SCMD_RESERVE,
18382 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18383 	    0, 0, 0 },
18384 	{ SCMD_RELEASE,
18385 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18386 	    0, 0, 0 },
18387 	{ SCMD_ERASE,
18388 	    1, 0, 1, 1, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18389 	    0, 0, 0, st_get_erase_options },
18390 	{ SCMD_MODE_SENSE,
18391 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18392 	    0, 0, 0 },
18393 	{ SCMD_LOAD,
18394 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18395 	    0, 0, 0, st_get_load_options },
18396 	{ SCMD_GDIAG,
18397 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18398 	    1, 0, 0 },
18399 	{ SCMD_SDIAG,
18400 	    1, 0, 1, 1, 0, DIR_EITH, TRAN_WRTE, POS_EXPECTED,
18401 	    1, 0, 0 },
18402 	{ SCMD_DOORLOCK,
18403 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18404 	    0, 4, 3 },
18405 	{ SCMD_LOCATE,
18406 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18407 	    0, 0, 0, NULL, st_get_cdb_g1_lba },
18408 	{ SCMD_READ_POSITION,
18409 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18410 	    0, 0, 0 },
18411 	{ SCMD_WRITE_BUFFER,
18412 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18413 	    1, 0, 0 },
18414 	{ SCMD_READ_BUFFER,
18415 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18416 	    1, 0, 0 },
18417 	{ SCMD_REPORT_DENSITIES,
18418 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18419 	    0, 0, 0 },
18420 	{ SCMD_LOG_SELECT_G1,
18421 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18422 	    0, 0, 0 },
18423 	{ SCMD_LOG_SENSE_G1,
18424 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18425 	    0, 0, 0 },
18426 	{ SCMD_PRIN,
18427 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18428 	    0, 0, 0 },
18429 	{ SCMD_PROUT,
18430 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18431 	    0, 0, 0 },
18432 	{ SCMD_READ_ATTRIBUTE,
18433 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18434 	    0, 0, 0 },
18435 	{ SCMD_WRITE_ATTRIBUTE,
18436 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18437 	    0, 0, 0 },
18438 	{ SCMD_LOCATE_G4,
18439 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18440 	    0, 0, 0, NULL, st_get_cdb_g4g5_cnt },
18441 	{ SCMD_REPORT_LUNS,
18442 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18443 	    0, 0, 0 },
18444 	{ SCMD_SVC_ACTION_IN_G5,
18445 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18446 	    0, 0, 0 },
18447 	{ SCMD_MAINTENANCE_IN,
18448 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18449 	    0, 0, 0 },
18450 	{ SCMD_MAINTENANCE_OUT,
18451 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18452 	    0, 0, 0 },
18453 	{ 0xff, /* Default attribute for unsupported commands */
18454 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_STARTING,
18455 	    1, 0, 0, NULL, NULL }
18456 };
18457 
18458 static const cmd_attribute *
18459 st_lookup_cmd_attribute(unsigned char cmd)
18460 {
18461 	int i;
18462 	cmd_attribute const *attribute;
18463 
18464 	for (i = 0; i < ST_NUM_MEMBERS(cmd_attributes); i++) {
18465 		attribute = &cmd_attributes[i];
18466 		if (attribute->cmd == cmd) {
18467 			return (attribute);
18468 		}
18469 	}
18470 	ASSERT(attribute);
18471 	return (attribute);
18472 }
18473 
18474 static int
18475 st_reset(struct scsi_tape *un, int reset_type)
18476 {
18477 	int rval;
18478 
18479 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
18480 
18481 	ST_FUNC(ST_DEVINFO, st_reset);
18482 	un->un_rsvd_status |= ST_INITIATED_RESET;
18483 	mutex_exit(ST_MUTEX);
18484 	do {
18485 		rval = scsi_reset(&un->un_sd->sd_address, reset_type);
18486 		if (rval == 0) {
18487 			switch (reset_type) {
18488 			case RESET_LUN:
18489 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18490 				    "LUN reset failed trying target reset");
18491 				reset_type = RESET_TARGET;
18492 				break;
18493 			case RESET_TARGET:
18494 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18495 				    "target reset failed trying bus reset");
18496 				reset_type = RESET_BUS;
18497 				break;
18498 			case RESET_BUS:
18499 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18500 				    "bus reset failed trying all reset");
18501 				reset_type = RESET_ALL;
18502 				break;
18503 			default:
18504 				mutex_enter(ST_MUTEX);
18505 				return (rval);
18506 			}
18507 		}
18508 	} while (rval == 0);
18509 	mutex_enter(ST_MUTEX);
18510 	return (rval);
18511 }
18512 
18513 #define	SAS_TLR_MOD_LEN sizeof (struct seq_mode)
18514 static int
18515 st_set_target_TLR_mode(struct scsi_tape *un, ubufunc_t ubf)
18516 {
18517 	int ret;
18518 	int amount = SAS_TLR_MOD_LEN;
18519 	struct seq_mode *mode_data;
18520 
18521 	ST_FUNC(ST_DEVINFO, st_set_target_TLR_mode);
18522 
18523 	mode_data = kmem_zalloc(SAS_TLR_MOD_LEN, KM_SLEEP);
18524 	ret = st_gen_mode_sense(un, ubf, 0x18, mode_data, amount);
18525 	if (ret != DDI_SUCCESS) {
18526 		if (ret != EACCES)
18527 			un->un_tlr_flag = TLR_NOT_SUPPORTED;
18528 		goto out;
18529 	}
18530 	if (mode_data->data_len != amount + 1) {
18531 		amount = mode_data->data_len + 1;
18532 	}
18533 	/* Must be SAS protocol */
18534 	if (mode_data->page.saslun.protocol_id != 6) {
18535 		un->un_tlr_flag = TLR_NOT_SUPPORTED;
18536 		ret = ENOTSUP;
18537 		goto out;
18538 	}
18539 	if (un->un_tlr_flag == TLR_SAS_ONE_DEVICE) {
18540 		if (mode_data->page.saslun.tran_layer_ret == 1)
18541 			goto out;
18542 		mode_data->page.saslun.tran_layer_ret = 1;
18543 	} else {
18544 		if (mode_data->page.saslun.tran_layer_ret == 0)
18545 			goto out;
18546 		mode_data->page.saslun.tran_layer_ret = 0;
18547 	}
18548 	ret = st_gen_mode_select(un, ubf, mode_data, amount);
18549 	if (ret != DDI_SUCCESS) {
18550 		if (ret != EACCES)
18551 			un->un_tlr_flag = TLR_NOT_SUPPORTED;
18552 	} else {
18553 		if (mode_data->page.saslun.tran_layer_ret == 0)
18554 			un->un_tlr_flag = TLR_NOT_KNOWN;
18555 		else
18556 			un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
18557 	}
18558 #ifdef STDEBUG
18559 	st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG, "TLR data sent",
18560 	    (char *)mode_data, amount);
18561 #endif
18562 out:
18563 	kmem_free(mode_data, SAS_TLR_MOD_LEN);
18564 	return (ret);
18565 }
18566 
18567 
18568 static void
18569 st_reset_notification(caddr_t arg)
18570 {
18571 	struct scsi_tape *un = (struct scsi_tape *)arg;
18572 
18573 	ST_FUNC(ST_DEVINFO, st_reset_notification);
18574 	mutex_enter(ST_MUTEX);
18575 
18576 	un->un_unit_attention_flags |= 2;
18577 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
18578 	    ST_RESERVE) {
18579 		un->un_rsvd_status |= ST_LOST_RESERVE;
18580 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18581 		    "Lost Reservation notification");
18582 	} else {
18583 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18584 		    "reset notification");
18585 	}
18586 
18587 	if ((un->un_restore_pos == 0) &&
18588 	    (un->un_state == ST_STATE_CLOSED) ||
18589 	    (un->un_state == ST_STATE_OPEN_PENDING_IO) ||
18590 	    (un->un_state == ST_STATE_CLOSING)) {
18591 		un->un_restore_pos = 1;
18592 	}
18593 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
18594 	    "reset and state was %d\n", un->un_state);
18595 	mutex_exit(ST_MUTEX);
18596 }
18597