xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/st.c (revision 0205780bc43902d17f94f07ceacb0cd8d5eab20f)
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 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * SCSI	 SCSA-compliant and not-so-DDI-compliant Tape Driver
31  */
32 
33 #if defined(lint) && !defined(DEBUG)
34 #define	DEBUG	1
35 #endif
36 
37 #include <sys/modctl.h>
38 #include <sys/scsi/scsi.h>
39 #include <sys/mtio.h>
40 #include <sys/scsi/targets/stdef.h>
41 #include <sys/file.h>
42 #include <sys/kstat.h>
43 #include <sys/ddidmareq.h>
44 #include <sys/ddi.h>
45 #include <sys/sunddi.h>
46 #include <sys/byteorder.h>
47 
48 #define	IOSP	KSTAT_IO_PTR(un->un_stats)
49 /*
50  * stats maintained only for reads/writes as commands
51  * like rewind etc skew the wait/busy times
52  */
53 #define	IS_RW(bp) 	((bp)->b_bcount > 0)
54 #define	ST_DO_KSTATS(bp, kstat_function) \
55 	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
56 		kstat_function(IOSP); \
57 	}
58 
59 #define	ST_DO_ERRSTATS(un, x)  \
60 	if (un->un_errstats) { \
61 		struct st_errstats *stp; \
62 		stp = (struct st_errstats *)un->un_errstats->ks_data; \
63 		stp->x.value.ul++; \
64 	}
65 
66 #define	FILL_SCSI1_LUN(devp, pkt) 					\
67 	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
68 		int _lun;						\
69 		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
70 		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
71 		if (_lun > 0) {						\
72 			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
73 			    _lun;					\
74 		}							\
75 	}
76 
77 /*
78  * get an available contig mem header, cp.
79  * when big_enough is true, we will return NULL, if no big enough
80  * contig mem is found.
81  * when big_enough is false, we will try to find cp containing big
82  * enough contig mem. if not found, we will ruturn the last cp available.
83  *
84  * used by st_get_contig_mem()
85  */
86 #define	ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough) {		\
87 	struct contig_mem *tmp_cp = NULL;				\
88 	for ((cp) = (un)->un_contig_mem;				\
89 	    (cp) != NULL;						\
90 	    tmp_cp = (cp), (cp) = (cp)->cm_next) { 			\
91 		if (((cp)->cm_len >= (len)) || 				\
92 		    (!(big_enough) && ((cp)->cm_next == NULL))) { 	\
93 			if (tmp_cp == NULL) { 				\
94 				(un)->un_contig_mem = (cp)->cm_next; 	\
95 			} else { 					\
96 				tmp_cp->cm_next = (cp)->cm_next; 	\
97 			} 						\
98 			(cp)->cm_next = NULL; 				\
99 			(un)->un_contig_mem_available_num--; 		\
100 			break; 						\
101 		} 							\
102 	} 								\
103 }
104 
105 #define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
106 #define	COPY_POS(dest, source) bcopy(source, dest, sizeof (tapepos_t))
107 #define	ISALNUM(byte) \
108 	(((byte) >= 'a' && (byte) <= 'z') || \
109 	((byte) >= 'A' && (byte) <= 'Z') || \
110 	((byte) >= '0' && (byte) <= '9'))
111 
112 #define	ONE_K	1024
113 
114 #define	MAX_SPACE_CNT(cnt) if (cnt >= 0) { \
115 		if (cnt > MIN(SP_CNT_MASK, INT32_MAX)) \
116 			return (EINVAL); \
117 	} else { \
118 		if (-(cnt) > MIN(SP_CNT_MASK, INT32_MAX)) \
119 			return (EINVAL); \
120 	} \
121 
122 /*
123  * Global External Data Definitions
124  */
125 extern struct scsi_key_strings scsi_cmds[];
126 extern uchar_t	scsi_cdb_size[];
127 
128 /*
129  * Local Static Data
130  */
131 static void *st_state;
132 static char *const st_label = "st";
133 static volatile int st_recov_sz = sizeof (recov_info);
134 static const char mp_misconf[] = {
135 	"St Tape is misconfigured, MPxIO enabled and "
136 	"tape-command-recovery-disable set in st.conf\n"
137 };
138 
139 #ifdef	__x86
140 /*
141  * We need to use below DMA attr to alloc physically contiguous
142  * memory to do I/O in big block size
143  */
144 static ddi_dma_attr_t st_contig_mem_dma_attr = {
145 	DMA_ATTR_V0,    /* version number */
146 	0x0,		/* lowest usable address */
147 	0xFFFFFFFFull,  /* high DMA address range */
148 	0xFFFFFFFFull,  /* DMA counter register */
149 	1,		/* DMA address alignment */
150 	1,		/* DMA burstsizes */
151 	1,		/* min effective DMA size */
152 	0xFFFFFFFFull,  /* max DMA xfer size */
153 	0xFFFFFFFFull,  /* segment boundary */
154 	1,		/* s/g list length */
155 	1,		/* granularity of device */
156 	0		/* DMA transfer flags */
157 };
158 
159 static ddi_device_acc_attr_t st_acc_attr = {
160 	DDI_DEVICE_ATTR_V0,
161 	DDI_NEVERSWAP_ACC,
162 	DDI_STRICTORDER_ACC
163 };
164 
165 /* set limitation for the number of contig_mem */
166 static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
167 #endif
168 
169 /*
170  * Tunable parameters
171  *
172  * DISCLAIMER
173  * ----------
174  * These parameters are intended for use only in system testing; if you use
175  * them in production systems, you do so at your own risk. Altering any
176  * variable not listed below may cause unpredictable system behavior.
177  *
178  * st_check_media_time
179  *
180  *   Three second state check
181  *
182  * st_allow_large_xfer
183  *
184  *   Gated with ST_NO_RECSIZE_LIMIT
185  *
186  *   0 - Transfers larger than 64KB will not be allowed
187  *       regardless of the setting of ST_NO_RECSIZE_LIMIT
188  *   1 - Transfers larger than 64KB will be allowed
189  *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
190  *
191  * st_report_soft_errors_on_close
192  *
193  *  Gated with ST_SOFT_ERROR_REPORTING
194  *
195  *  0 - Errors will not be reported on close regardless
196  *      of the setting of ST_SOFT_ERROR_REPORTING
197  *
198  *  1 - Errors will be reported on close if
199  *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
200  */
201 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
202 static int st_retry_count	= ST_RETRY_COUNT;
203 
204 static int st_io_time		= ST_IO_TIME;
205 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
206 
207 static int st_space_time	= ST_SPACE_TIME;
208 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
209 
210 static int st_error_level	= SCSI_ERR_RETRYABLE;
211 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
212 
213 static int st_max_throttle	= ST_MAX_THROTTLE;
214 
215 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
216 
217 static int st_allow_large_xfer = 1;
218 static int st_report_soft_errors_on_close = 1;
219 
220 /*
221  * End of tunable parameters list
222  */
223 
224 
225 
226 /*
227  * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
228  *
229  * Asynchronous I/O's main offering is that it is a non-blocking way to do
230  * reads and writes.  The driver will queue up all the requests it gets and
231  * have them ready to transport to the HBA.  Unfortunately, we cannot always
232  * just ship the I/O requests to the HBA, as there errors and exceptions
233  * that may happen when we don't want the HBA to continue.  Therein comes
234  * the flush-on-errors capability.  If the HBA supports it, then st will
235  * send in st_max_throttle I/O requests at the same time.
236  *
237  * Persistent errors : This was also reasonably simple.  In the interrupt
238  * routines, if there was an error or exception (FM, LEOT, media error,
239  * transport error), the persistent error bits are set and shuts everything
240  * down, but setting the throttle to zero.  If we hit and exception in the
241  * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
242  * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
243  * the appropriate error, and this will preserve order. Of course, depending
244  * on the exception we have to show a zero read or write before we show
245  * errors back to the application.
246  */
247 
248 extern const int st_ndrivetypes;	/* defined in st_conf.c */
249 extern const struct st_drivetype st_drivetypes[];
250 extern const char st_conf_version[];
251 
252 #ifdef STDEBUG
253 static int st_soft_error_report_debug = 0;
254 volatile int st_debug = 0;
255 static volatile dev_info_t *st_lastdev;
256 static kmutex_t st_debug_mutex;
257 #endif
258 
259 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
260 
261 static const struct vid_drivetype {
262 	char	*vid;
263 	char	type;
264 } st_vid_dt[] = {
265 	{"LTO-CVE ",	MT_LTO},
266 	{"QUANTUM ",    MT_ISDLT},
267 	{"SONY    ",    MT_ISAIT},
268 	{"STK     ",	MT_ISSTK9840}
269 };
270 
271 static const struct driver_minor_data {
272 	char	*name;
273 	int	minor;
274 } st_minor_data[] = {
275 	/*
276 	 * The top 4 entries are for the default densities,
277 	 * don't alter their position.
278 	 */
279 	{"",	0},
280 	{"n",	MT_NOREWIND},
281 	{"b",	MT_BSD},
282 	{"bn",	MT_NOREWIND | MT_BSD},
283 	{"l",	MT_DENSITY1},
284 	{"m",	MT_DENSITY2},
285 	{"h",	MT_DENSITY3},
286 	{"c",	MT_DENSITY4},
287 	{"u",	MT_DENSITY4},
288 	{"ln",	MT_DENSITY1 | MT_NOREWIND},
289 	{"mn",	MT_DENSITY2 | MT_NOREWIND},
290 	{"hn",	MT_DENSITY3 | MT_NOREWIND},
291 	{"cn",	MT_DENSITY4 | MT_NOREWIND},
292 	{"un",	MT_DENSITY4 | MT_NOREWIND},
293 	{"lb",	MT_DENSITY1 | MT_BSD},
294 	{"mb",	MT_DENSITY2 | MT_BSD},
295 	{"hb",	MT_DENSITY3 | MT_BSD},
296 	{"cb",	MT_DENSITY4 | MT_BSD},
297 	{"ub",	MT_DENSITY4 | MT_BSD},
298 	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
299 	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
300 	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
301 	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
302 	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
303 };
304 
305 /* strings used in many debug and warning messages */
306 static const char wr_str[]  = "write";
307 static const char rd_str[]  = "read";
308 static const char wrg_str[] = "writing";
309 static const char rdg_str[] = "reading";
310 static const char *space_strs[] = {
311 	"records",
312 	"filemarks",
313 	"sequential filemarks",
314 	"eod",
315 	"setmarks",
316 	"sequential setmarks",
317 	"Reserved",
318 	"Reserved"
319 };
320 static const char *load_strs[] = {
321 	"unload",		/* LD_UNLOAD		0 */
322 	"load",			/* LD_LOAD		1 */
323 	"retension",		/* LD_RETEN		2 */
324 	"load reten",		/* LD_LOAD | LD_RETEN	3 */
325 	"eod",			/* LD_EOT		4 */
326 	"load EOD",		/* LD_LOAD | LD_EOT	5 */
327 	"reten EOD",		/* LD_RETEN | LD_EOT	6 */
328 	"load reten EOD"	/* LD_LOAD|LD_RETEN|LD_EOT 7 */
329 	"hold",			/* LD_HOLD		8 */
330 	"load and hold"		/* LD_LOAD | LD_HOLD	9 */
331 };
332 
333 static const char *errstatenames[] = {
334 	"COMMAND_DONE",
335 	"COMMAND_DONE_ERROR",
336 	"COMMAND_DONE_ERROR_RECOVERED",
337 	"QUE_COMMAND",
338 	"QUE_BUSY_COMMAND",
339 	"QUE_SENSE",
340 	"JUST_RETURN",
341 	"COMMAND_DONE_EACCES",
342 	"QUE_LAST_COMMAND",
343 	"COMMAND_TIMEOUT",
344 	"PATH_FAILED",
345 	"DEVICE_RESET",
346 	"DEVICE_TAMPER",
347 	"ATTEMPT_RETRY"
348 };
349 
350 const char *bogusID = "Unknown Media ID";
351 
352 /* default density offsets in the table above */
353 #define	DEF_BLANK	0
354 #define	DEF_NOREWIND	1
355 #define	DEF_BSD		2
356 #define	DEF_BSD_NR	3
357 
358 /* Sense Key, ASC/ASCQ for which tape ejection is needed */
359 
360 static struct tape_failure_code {
361 	uchar_t key;
362 	uchar_t add_code;
363 	uchar_t qual_code;
364 } st_tape_failure_code[] = {
365 	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
366 	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
367 	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
368 	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
369 	{ KEY_NOT_READY, 0x53, 0x00},
370 	{ 0xff}
371 };
372 
373 /*  clean bit position and mask */
374 
375 static struct cln_bit_position {
376 	ushort_t cln_bit_byte;
377 	uchar_t cln_bit_mask;
378 } st_cln_bit_position[] = {
379 	{ 21, 0x08},
380 	{ 70, 0xc0},
381 	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
382 };
383 
384 /*
385  * architecture dependent allocation restrictions. For x86, we'll set
386  * dma_attr_addr_hi to st_max_phys_addr and dma_attr_sgllen to
387  * st_sgl_size during _init().
388  */
389 #if defined(__sparc)
390 static ddi_dma_attr_t st_alloc_attr = {
391 	DMA_ATTR_V0,	/* version number */
392 	0x0,		/* lowest usable address */
393 	0xFFFFFFFFull,	/* high DMA address range */
394 	0xFFFFFFFFull,	/* DMA counter register */
395 	1,		/* DMA address alignment */
396 	1,		/* DMA burstsizes */
397 	1,		/* min effective DMA size */
398 	0xFFFFFFFFull,	/* max DMA xfer size */
399 	0xFFFFFFFFull,	/* segment boundary */
400 	1,		/* s/g list length */
401 	512,		/* granularity of device */
402 	0		/* DMA transfer flags */
403 };
404 #elif defined(__x86)
405 static ddi_dma_attr_t st_alloc_attr = {
406 	DMA_ATTR_V0,	/* version number */
407 	0x0,		/* lowest usable address */
408 	0x0,		/* high DMA address range [set in _init()] */
409 	0xFFFFull,	/* DMA counter register */
410 	512,		/* DMA address alignment */
411 	1,		/* DMA burstsizes */
412 	1,		/* min effective DMA size */
413 	0xFFFFFFFFull,	/* max DMA xfer size */
414 	0xFFFFFFFFull,  /* segment boundary */
415 	0,		/* s/g list length */
416 	512,		/* granularity of device [set in _init()] */
417 	0		/* DMA transfer flags */
418 };
419 uint64_t st_max_phys_addr = 0xFFFFFFFFull;
420 int st_sgl_size = 0xF;
421 
422 #endif
423 
424 /*
425  * Configuration Data:
426  *
427  * Device driver ops vector
428  */
429 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
430 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
431 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
432 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
433 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
434 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
435 static int st_strategy(struct buf *bp);
436 static int st_queued_strategy(buf_t *bp);
437 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
438 	cred_t *cred_p, int *rval_p);
439 extern int nulldev(), nodev();
440 
441 static struct cb_ops st_cb_ops = {
442 	st_open,		/* open */
443 	st_close,		/* close */
444 	st_queued_strategy,	/* strategy Not Block device but async checks */
445 	nodev,			/* print */
446 	nodev,			/* dump */
447 	st_read,		/* read */
448 	st_write,		/* write */
449 	st_ioctl,		/* ioctl */
450 	nodev,			/* devmap */
451 	nodev,			/* mmap */
452 	nodev,			/* segmap */
453 	nochpoll,		/* poll */
454 	ddi_prop_op,		/* cb_prop_op */
455 	0,			/* streamtab  */
456 	D_64BIT | D_MP | D_NEW | D_HOTPLUG |
457 	D_OPEN_RETURNS_EINTR,	/* cb_flag */
458 	CB_REV,			/* cb_rev */
459 	st_aread, 		/* async I/O read entry point */
460 	st_awrite		/* async I/O write entry point */
461 
462 };
463 
464 static int st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
465 		void **result);
466 static int st_probe(dev_info_t *dev);
467 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
468 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
469 
470 static struct dev_ops st_ops = {
471 	DEVO_REV,		/* devo_rev, */
472 	0,			/* refcnt  */
473 	st_info,		/* info */
474 	nulldev,		/* identify */
475 	st_probe,		/* probe */
476 	st_attach,		/* attach */
477 	st_detach,		/* detach */
478 	nodev,			/* reset */
479 	&st_cb_ops,		/* driver operations */
480 	(struct bus_ops *)0,	/* bus operations */
481 	nulldev			/* power */
482 };
483 
484 /*
485  * Local Function Declarations
486  */
487 static char *st_print_scsi_cmd(char cmd);
488 static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
489     char *title, char *cdb);
490 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
491     char *title, char *data, int len);
492 static int st_doattach(struct scsi_device *devp, int (*canwait)());
493 static void st_known_tape_type(struct scsi_tape *un);
494 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
495     struct st_drivetype *);
496 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
497     struct st_drivetype *);
498 static int st_get_conf_from_tape_drive(struct scsi_tape *, char *,
499     struct st_drivetype *);
500 static int st_get_densities_from_tape_drive(struct scsi_tape *,
501     struct st_drivetype *);
502 static int st_get_timeout_values_from_tape_drive(struct scsi_tape *,
503     struct st_drivetype *);
504 static int st_get_timeouts_value(struct scsi_tape *, uchar_t, ushort_t *,
505     ushort_t);
506 static int st_get_default_conf(struct scsi_tape *, char *,
507     struct st_drivetype *);
508 static int st_rw(dev_t dev, struct uio *uio, int flag);
509 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
510 static int st_find_eod(struct scsi_tape *un);
511 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
512 static int st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *, int flag);
513 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
514 static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
515 static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
516 static void st_start(struct scsi_tape *un);
517 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
518     clock_t timeout_interval, int queued);
519 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
520     clock_t timeout_interval);
521 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
522 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
523 static void st_init(struct scsi_tape *un);
524 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
525     int (*func)(caddr_t));
526 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
527     struct buf *bp, int (*func)(caddr_t));
528 static void st_intr(struct scsi_pkt *pkt);
529 static void st_set_state(struct scsi_tape *un, buf_t *bp);
530 static void st_test_append(struct buf *bp);
531 static int st_runout(caddr_t);
532 static int st_cmd(struct scsi_tape *un, int com, int64_t count, int wait);
533 static int st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com,
534     int64_t count);
535 static int st_set_compression(struct scsi_tape *un);
536 static int st_write_fm(dev_t dev, int wfm);
537 static int st_determine_generic(struct scsi_tape *un);
538 static int st_determine_density(struct scsi_tape *un, int rw);
539 static int st_get_density(struct scsi_tape *un);
540 static int st_set_density(struct scsi_tape *un);
541 static int st_loadtape(struct scsi_tape *un);
542 static int st_modesense(struct scsi_tape *un);
543 static int st_modeselect(struct scsi_tape *un);
544 static errstate st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
545 static int st_wrongtapetype(struct scsi_tape *un);
546 static errstate st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
547 static errstate st_handle_sense(struct scsi_tape *un, struct buf *bp,
548     tapepos_t *);
549 static errstate st_handle_autosense(struct scsi_tape *un, struct buf *bp,
550     tapepos_t *);
551 static int st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag);
552 static void st_update_error_stack(struct scsi_tape *un, struct scsi_pkt *pkt,
553     struct scsi_arq_status *cmd);
554 static void st_empty_error_stack(struct scsi_tape *un);
555 static errstate st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
556     struct scsi_arq_status *, tapepos_t *);
557 static int st_report_soft_errors(dev_t dev, int flag);
558 static void st_delayed_cv_broadcast(void *arg);
559 static int st_check_media(dev_t dev, enum mtio_state state);
560 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
561 static void st_intr_restart(void *arg);
562 static void st_start_restart(void *arg);
563 static int st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
564     struct seq_mode *page_data, int page_size);
565 static int st_change_block_size(struct scsi_tape *un, uint32_t nblksz);
566 static int st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
567     struct seq_mode *page_data, int page_size);
568 static int st_read_block_limits(struct scsi_tape *un,
569     struct read_blklim *read_blk);
570 static int st_report_density_support(struct scsi_tape *un,
571     uchar_t *density_data, size_t buflen);
572 static int st_report_supported_operation(struct scsi_tape *un,
573     uchar_t *oper_data, uchar_t option_code, ushort_t service_action);
574 static int st_tape_init(struct scsi_tape *un);
575 static void st_flush(struct scsi_tape *un);
576 static void st_set_pe_errno(struct scsi_tape *un);
577 static void st_hba_unflush(struct scsi_tape *un);
578 static void st_turn_pe_on(struct scsi_tape *un);
579 static void st_turn_pe_off(struct scsi_tape *un);
580 static void st_set_pe_flag(struct scsi_tape *un);
581 static void st_clear_pe(struct scsi_tape *un);
582 static void st_wait_for_io(struct scsi_tape *un);
583 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
584 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
585 static int st_reserve_release(struct scsi_tape *un, int command, ubufunc_t ubf);
586 static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb);
587 static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
588     int count);
589 static int st_take_ownership(struct scsi_tape *un, ubufunc_t ubf);
590 static int st_check_asc_ascq(struct scsi_tape *un);
591 static int st_check_clean_bit(struct scsi_tape *un);
592 static int st_check_alert_flags(struct scsi_tape *un);
593 static int st_check_sequential_clean_bit(struct scsi_tape *un);
594 static int st_check_sense_clean_bit(struct scsi_tape *un);
595 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
596 static void st_calculate_timeouts(struct scsi_tape *un);
597 static writablity st_is_drive_worm(struct scsi_tape *un);
598 static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
599     void *buf, size_t size, ubufunc_t bufunc);
600 static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
601     caddr_t dest, uchar_t page);
602 static int st_update_block_pos(struct scsi_tape *un, bufunc_t bf,
603     int post_space);
604 static int st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
605     read_p_types type, size_t data_sz, const caddr_t responce, int post_space);
606 static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
607 static int st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf,
608     tapepos_t *pos, uint64_t lblk, uchar_t partition);
609 static int st_mtfsf_ioctl(struct scsi_tape *un, int64_t files);
610 static int st_mtfsr_ioctl(struct scsi_tape *un, int64_t count);
611 static int st_mtbsf_ioctl(struct scsi_tape *un, int64_t files);
612 static int st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count);
613 static int st_mtbsr_ioctl(struct scsi_tape *un, int64_t num);
614 static int st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt);
615 static int st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt);
616 static int st_backward_space_files(struct scsi_tape *un, int64_t count,
617     int infront);
618 static int st_forward_space_files(struct scsi_tape *un, int64_t files);
619 static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
620     int32_t fileno);
621 static int st_space_to_begining_of_file(struct scsi_tape *un);
622 static int st_space_records(struct scsi_tape *un, int64_t records);
623 static int st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc);
624 static errstate st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
625     errstate onentry);
626 static void st_recover(void *arg);
627 static void st_recov_cb(struct scsi_pkt *pkt);
628 static int st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait);
629 static int st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
630     int flag);
631 static void st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
632     struct scsi_pkt *cmd);
633 static int st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf);
634 static int st_test_path_to_device(struct scsi_tape *un);
635 static int st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
636     read_pos_data_t *raw);
637 static int st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
638     read_pos_data_t *raw);
639 static int st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
640     cmd_attribute const * cmd_att, tapepos_t *read);
641 static errstate st_recover_reissue_pkt(struct scsi_tape *us,
642     struct scsi_pkt *pkt);
643 static int st_transport(struct scsi_tape *un, struct scsi_pkt *pkt);
644 static buf_t *st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp);
645 static void st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp);
646 static int st_reset(struct scsi_tape *un, int reset_type);
647 static void st_reset_notification(caddr_t arg);
648 static const cmd_attribute *st_lookup_cmd_attribute(unsigned char cmd);
649 
650 #ifdef	__x86
651 /*
652  * routines for I/O in big block size
653  */
654 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
655 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
656     int alloc_flags);
657 static int st_bigblk_xfer_done(struct buf *bp);
658 static struct buf *st_get_bigblk_bp(struct buf *bp);
659 #endif
660 static void st_print_position(dev_info_t *dev, char *label, uint_t level,
661     const char *comment, tapepos_t *pos);
662 
663 /*
664  * error statistics create/update functions
665  */
666 static int st_create_errstats(struct scsi_tape *, int);
667 static int st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf,
668     tapepos_t *pos);
669 
670 #ifdef STDEBUG
671 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
672 #endif /* STDEBUG */
673 static char *st_dev_name(dev_t dev);
674 
675 #if !defined(lint)
676 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
677     scsi_pkt buf uio scsi_cdb uscsi_cmd))
678 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
679 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", recov_info))
680 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
681 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
682 #endif
683 
684 /*
685  * autoconfiguration routines.
686  */
687 char _depends_on[] = "misc/scsi";
688 
689 static struct modldrv modldrv = {
690 	&mod_driverops,		/* Type of module. This one is a driver */
691 	"SCSI tape Driver %I%", /* Name of the module. */
692 	&st_ops			/* driver ops */
693 };
694 
695 static struct modlinkage modlinkage = {
696 	MODREV_1, &modldrv, NULL
697 };
698 
699 /*
700  * Notes on Post Reset Behavior in the tape driver:
701  *
702  * When the tape drive is opened, the driver  attempts  to make sure that
703  * the tape head is positioned exactly where it was left when it was last
704  * closed  provided  the  medium  is not  changed.  If the tape  drive is
705  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
706  * of position due to reset) will happen when the first tape operation or
707  * I/O occurs.  The repositioning (if required) may not be possible under
708  * certain situations such as when the device firmware not able to report
709  * the medium  change in the REQUEST  SENSE data  because of a reset or a
710  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
711  * extraordinary  situations, where the driver fails to position the head
712  * at its  original  position,  it will fail the open the first  time, to
713  * save the applications from overwriting the data.  All further attempts
714  * to open the tape device will result in the driver  attempting  to load
715  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
716  * indicate  that further  attempts to open the tape device may result in
717  * the tape being  loaded at BOT will be printed on the  console.  If the
718  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
719  * original tape head  position,  will result in the failure of the first
720  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
721  * internal tape position  which will  necessitate  the  applications  to
722  * validate the position by using either a tape  positioning  ioctl (such
723  * as MTREW) or closing and reopening the tape device.
724  *
725  */
726 
727 int
728 _init(void)
729 {
730 	int e;
731 
732 	if (((e = ddi_soft_state_init(&st_state,
733 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
734 		return (e);
735 	}
736 
737 	if ((e = mod_install(&modlinkage)) != 0) {
738 		ddi_soft_state_fini(&st_state);
739 	} else {
740 #ifdef STDEBUG
741 		mutex_init(&st_debug_mutex, NULL, MUTEX_DRIVER, NULL);
742 #endif
743 
744 #if defined(__x86)
745 		/* set the max physical address for iob allocs on x86 */
746 		st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
747 
748 		/*
749 		 * set the sgllen for iob allocs on x86. If this is set less
750 		 * than the number of pages the buffer will take
751 		 * (taking into account alignment), it would force the
752 		 * allocator to try and allocate contiguous pages.
753 		 */
754 		st_alloc_attr.dma_attr_sgllen = st_sgl_size;
755 #endif
756 	}
757 
758 	return (e);
759 }
760 
761 int
762 _fini(void)
763 {
764 	int e;
765 
766 	if ((e = mod_remove(&modlinkage)) != 0) {
767 		return (e);
768 	}
769 
770 #ifdef STDEBUG
771 	mutex_destroy(&st_debug_mutex);
772 #endif
773 
774 	ddi_soft_state_fini(&st_state);
775 
776 	return (e);
777 }
778 
779 int
780 _info(struct modinfo *modinfop)
781 {
782 	return (mod_info(&modlinkage, modinfop));
783 }
784 
785 
786 static int
787 st_probe(dev_info_t *devi)
788 {
789 	int instance;
790 	struct scsi_device *devp;
791 	int rval;
792 
793 #if !defined(__sparc)
794 	char    *tape_prop;
795 	int	tape_prop_len;
796 #endif
797 
798 	ST_ENTR(devi, st_probe);
799 
800 	/* If self identifying device */
801 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
802 		return (DDI_PROBE_DONTCARE);
803 	}
804 
805 #if !defined(__sparc)
806 	/*
807 	 * Since some x86 HBAs have devnodes that look like SCSI as
808 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
809 	 * we check for the presence of the "tape" property.
810 	 */
811 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
812 	    DDI_PROP_CANSLEEP, "tape",
813 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
814 		return (DDI_PROBE_FAILURE);
815 	}
816 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
817 		kmem_free(tape_prop, tape_prop_len);
818 		return (DDI_PROBE_FAILURE);
819 	}
820 	kmem_free(tape_prop, tape_prop_len);
821 #endif
822 
823 	devp = ddi_get_driver_private(devi);
824 	instance = ddi_get_instance(devi);
825 
826 	if (ddi_get_soft_state(st_state, instance) != NULL) {
827 		return (DDI_PROBE_PARTIAL);
828 	}
829 
830 
831 	/*
832 	 * Turn around and call probe routine to see whether
833 	 * we actually have a tape at this SCSI nexus.
834 	 */
835 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
836 
837 		/*
838 		 * In checking the whole inq_dtype byte we are looking at both
839 		 * the Peripheral Qualifier and the Peripheral Device Type.
840 		 * For this driver we are only interested in sequential devices
841 		 * that are connected or capable if connecting to this logical
842 		 * unit.
843 		 */
844 		if (devp->sd_inq->inq_dtype ==
845 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
846 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
847 			    "probe exists\n");
848 			rval = DDI_PROBE_SUCCESS;
849 		} else {
850 			rval = DDI_PROBE_FAILURE;
851 		}
852 	} else {
853 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
854 		    "probe failure: nothing there\n");
855 		rval = DDI_PROBE_FAILURE;
856 	}
857 	scsi_unprobe(devp);
858 	return (rval);
859 }
860 
861 static int
862 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
863 {
864 	int 	instance;
865 	int	wide;
866 	int 	dev_instance;
867 	int	ret_status;
868 	struct	scsi_device *devp;
869 	int	node_ix;
870 	struct	scsi_tape *un;
871 
872 	ST_ENTR(devi, st_attach);
873 
874 	devp = ddi_get_driver_private(devi);
875 	instance = ddi_get_instance(devi);
876 
877 	switch (cmd) {
878 		case DDI_ATTACH:
879 			if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
880 			    "tape-command-recovery-disable", 0) != 0) {
881 				st_recov_sz = sizeof (pkt_info);
882 			}
883 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
884 				return (DDI_FAILURE);
885 			}
886 			break;
887 		case DDI_RESUME:
888 			/*
889 			 * Suspend/Resume
890 			 *
891 			 * When the driver suspended, there might be
892 			 * outstanding cmds and therefore we need to
893 			 * reset the suspended flag and resume the scsi
894 			 * watch thread and restart commands and timeouts
895 			 */
896 
897 			if (!(un = ddi_get_soft_state(st_state, instance))) {
898 				return (DDI_FAILURE);
899 			}
900 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
901 			    un->un_dev);
902 
903 			mutex_enter(ST_MUTEX);
904 
905 			un->un_throttle = un->un_max_throttle;
906 			un->un_tids_at_suspend = 0;
907 			un->un_pwr_mgmt = ST_PWR_NORMAL;
908 
909 			if (un->un_swr_token) {
910 				scsi_watch_resume(un->un_swr_token);
911 			}
912 
913 			/*
914 			 * Restart timeouts
915 			 */
916 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
917 				mutex_exit(ST_MUTEX);
918 				un->un_delay_tid = timeout(
919 				    st_delayed_cv_broadcast, un,
920 				    drv_usectohz((clock_t)
921 				    MEDIA_ACCESS_DELAY));
922 				mutex_enter(ST_MUTEX);
923 			}
924 
925 			if (un->un_tids_at_suspend & ST_HIB_TID) {
926 				mutex_exit(ST_MUTEX);
927 				un->un_hib_tid = timeout(st_intr_restart, un,
928 				    ST_STATUS_BUSY_TIMEOUT);
929 				mutex_enter(ST_MUTEX);
930 			}
931 
932 			ret_status = st_clear_unit_attentions(dev_instance, 5);
933 
934 			/*
935 			 * now check if we need to restore the tape position
936 			 */
937 			if ((un->un_suspend_pos.pmode != invalid) &&
938 			    ((un->un_suspend_pos.fileno > 0) ||
939 			    (un->un_suspend_pos.blkno > 0)) ||
940 			    (un->un_suspend_pos.lgclblkno > 0)) {
941 				if (ret_status != 0) {
942 					/*
943 					 * tape didn't get good TUR
944 					 * just print out error messages
945 					 */
946 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
947 					    "st_attach-RESUME: tape failure "
948 					    " tape position will be lost");
949 				} else {
950 					/* this prints errors */
951 					(void) st_validate_tapemarks(un,
952 					    st_uscsi_cmd, &un->un_suspend_pos);
953 				}
954 				/*
955 				 * there are no retries, if there is an error
956 				 * we don't know if the tape has changed
957 				 */
958 				un->un_suspend_pos.pmode = invalid;
959 			}
960 
961 			/* now we are ready to start up any queued I/Os */
962 			if (un->un_ncmds || un->un_quef) {
963 				st_start(un);
964 			}
965 
966 			cv_broadcast(&un->un_suspend_cv);
967 			mutex_exit(ST_MUTEX);
968 			return (DDI_SUCCESS);
969 
970 		default:
971 			return (DDI_FAILURE);
972 	}
973 
974 	un = ddi_get_soft_state(st_state, instance);
975 
976 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
977 	    "st_attach: instance=%x\n", instance);
978 
979 	/*
980 	 * Add a zero-length attribute to tell the world we support
981 	 * kernel ioctls (for layered drivers)
982 	 */
983 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
984 	    DDI_KERNEL_IOCTL, NULL, 0);
985 
986 	ddi_report_dev((dev_info_t *)devi);
987 
988 	/*
989 	 * If it's a SCSI-2 tape drive which supports wide,
990 	 * tell the host adapter to use wide.
991 	 */
992 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
993 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
994 
995 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
996 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
997 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
998 	}
999 
1000 	/*
1001 	 * enable autorequest sense; keep the rq packet around in case
1002 	 * the autorequest sense fails because of a busy condition
1003 	 * do a getcap first in case the capability is not variable
1004 	 */
1005 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
1006 		un->un_arq_enabled = 1;
1007 	} else {
1008 		un->un_arq_enabled =
1009 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
1010 	}
1011 
1012 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
1013 	    (un->un_arq_enabled ? "enabled" : "disabled"));
1014 
1015 	un->un_untagged_qing =
1016 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
1017 
1018 	/*
1019 	 * XXX - This is just for 2.6.  to tell users that write buffering
1020 	 *	has gone away.
1021 	 */
1022 	if (un->un_arq_enabled && un->un_untagged_qing) {
1023 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
1024 		    "tape-driver-buffering", 0) != 0) {
1025 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1026 			    "Write Data Buffering has been depricated. Your "
1027 			    "applications should continue to work normally.\n"
1028 			    " But, they should  ported to use Asynchronous "
1029 			    " I/O\n"
1030 			    " For more information, read about "
1031 			    " tape-driver-buffering "
1032 			    "property in the st(7d) man page\n");
1033 		}
1034 	}
1035 
1036 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
1037 	un->un_flush_on_errors = 0;
1038 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
1039 
1040 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
1041 	    "throttle=%x, max_throttle = %x\n",
1042 	    un->un_throttle, un->un_max_throttle);
1043 
1044 	/* initialize persistent errors to nil */
1045 	un->un_persistence = 0;
1046 	un->un_persist_errors = 0;
1047 
1048 	/*
1049 	 * Get dma-max from HBA driver. If it is not defined, use 64k
1050 	 */
1051 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
1052 	if (un->un_maxdma == -1) {
1053 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1054 		    "Received a value that looked like -1. Using 64k maxdma");
1055 		un->un_maxdma = (64 * ONE_K);
1056 	}
1057 
1058 #ifdef	__x86
1059 	/*
1060 	 * for x86, the device may be able to DMA more than the system will
1061 	 * allow under some circumstances. We need account for both the HBA's
1062 	 * and system's contraints.
1063 	 *
1064 	 * Get the maximum DMA under worse case conditions. e.g. looking at the
1065 	 * device constraints, the max copy buffer size, and the worse case
1066 	 * fragmentation. NOTE: this may differ from dma-max since dma-max
1067 	 * doesn't take the worse case framentation into account.
1068 	 *
1069 	 * e.g. a device may be able to DMA 16MBytes, but can only DMA 1MByte
1070 	 * if none of the pages are contiguous. Keeping track of both of these
1071 	 * values allows us to support larger tape block sizes on some devices.
1072 	 */
1073 	un->un_maxdma_arch = scsi_ifgetcap(&devp->sd_address, "dma-max-arch",
1074 	    1);
1075 
1076 	/*
1077 	 * If the dma-max-arch capability is not implemented, or the value
1078 	 * comes back higher than what was reported in dma-max, use dma-max.
1079 	 */
1080 	if ((un->un_maxdma_arch == -1) ||
1081 	    ((uint_t)un->un_maxdma < (uint_t)un->un_maxdma_arch)) {
1082 		un->un_maxdma_arch = un->un_maxdma;
1083 	}
1084 #endif
1085 
1086 	/*
1087 	 * Get the max allowable cdb size
1088 	 */
1089 	un->un_max_cdb_sz =
1090 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
1091 	if (un->un_max_cdb_sz < CDB_GROUP0) {
1092 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1093 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
1094 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
1095 	}
1096 
1097 	if (strcmp(ddi_driver_name(ddi_get_parent(ST_DEVINFO)), "scsi_vhci")) {
1098 		un->un_multipath = 0;
1099 	} else {
1100 		un->un_multipath = 1;
1101 	}
1102 
1103 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1104 
1105 	un->un_mediastate = MTIO_NONE;
1106 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1107 
1108 	/*
1109 	 * initialize kstats
1110 	 */
1111 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1112 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1113 	if (un->un_stats) {
1114 		un->un_stats->ks_lock = ST_MUTEX;
1115 		kstat_install(un->un_stats);
1116 	}
1117 	(void) st_create_errstats(un, instance);
1118 
1119 	/*
1120 	 * find the drive type for this target
1121 	 */
1122 	mutex_enter(ST_MUTEX);
1123 	un->un_dev = MTMINOR(instance);
1124 	st_known_tape_type(un);
1125 	un->un_dev = 0;
1126 	mutex_exit(ST_MUTEX);
1127 
1128 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
1129 		int minor;
1130 		char *name;
1131 
1132 		name  = st_minor_data[node_ix].name;
1133 		minor = st_minor_data[node_ix].minor;
1134 
1135 		/*
1136 		 * For default devices set the density to the
1137 		 * preferred default density for this device.
1138 		 */
1139 		if (node_ix <= DEF_BSD_NR) {
1140 			minor |= un->un_dp->default_density;
1141 		}
1142 		minor |= MTMINOR(instance);
1143 
1144 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
1145 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
1146 			continue;
1147 		}
1148 
1149 		ddi_remove_minor_node(devi, NULL);
1150 
1151 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1152 		    st_reset_notification, (caddr_t)un);
1153 		cv_destroy(&un->un_clscv);
1154 		cv_destroy(&un->un_sbuf_cv);
1155 		cv_destroy(&un->un_queue_cv);
1156 		cv_destroy(&un->un_state_cv);
1157 #ifdef	__x86
1158 		cv_destroy(&un->un_contig_mem_cv);
1159 #endif
1160 		cv_destroy(&un->un_suspend_cv);
1161 		cv_destroy(&un->un_tape_busy_cv);
1162 		cv_destroy(&un->un_recov_buf_cv);
1163 		if (un->un_recov_taskq) {
1164 			ddi_taskq_destroy(un->un_recov_taskq);
1165 		}
1166 		if (un->un_sbufp) {
1167 			freerbuf(un->un_sbufp);
1168 		}
1169 		if (un->un_recov_buf) {
1170 			freerbuf(un->un_recov_buf);
1171 		}
1172 		if (un->un_uscsi_rqs_buf) {
1173 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1174 		}
1175 		if (un->un_mspl) {
1176 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1177 		}
1178 		if (un->un_dp_size) {
1179 			kmem_free(un->un_dp, un->un_dp_size);
1180 		}
1181 		if (un->un_state) {
1182 			kstat_delete(un->un_stats);
1183 		}
1184 		if (un->un_errstats) {
1185 			kstat_delete(un->un_errstats);
1186 		}
1187 
1188 		scsi_destroy_pkt(un->un_rqs);
1189 		scsi_free_consistent_buf(un->un_rqs_bp);
1190 		ddi_soft_state_free(st_state, instance);
1191 		devp->sd_private = NULL;
1192 		devp->sd_sense = NULL;
1193 
1194 		ddi_prop_remove_all(devi);
1195 		return (DDI_FAILURE);
1196 	}
1197 
1198 	return (DDI_SUCCESS);
1199 }
1200 
1201 /*
1202  * st_detach:
1203  *
1204  * we allow a detach if and only if:
1205  *	- no tape is currently inserted
1206  *	- tape position is at BOT or unknown
1207  *		(if it is not at BOT then a no rewind
1208  *		device was opened and we have to preserve state)
1209  *	- it must be in a closed state : no timeouts or scsi_watch requests
1210  *		will exist if it is closed, so we don't need to check for
1211  *		them here.
1212  */
1213 /*ARGSUSED*/
1214 static int
1215 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1216 {
1217 	int instance;
1218 	int result;
1219 	struct scsi_device *devp;
1220 	struct scsi_tape *un;
1221 	clock_t wait_cmds_complete;
1222 
1223 	ST_ENTR(devi, st_detach);
1224 
1225 	instance = ddi_get_instance(devi);
1226 
1227 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1228 		return (DDI_FAILURE);
1229 	}
1230 
1231 	mutex_enter(ST_MUTEX);
1232 
1233 	/*
1234 	 * Clear error entry stack
1235 	 */
1236 	st_empty_error_stack(un);
1237 
1238 	mutex_exit(ST_MUTEX);
1239 
1240 	switch (cmd) {
1241 
1242 	case DDI_DETACH:
1243 		/*
1244 		 * Undo what we did in st_attach & st_doattach,
1245 		 * freeing resources and removing things we installed.
1246 		 * The system framework guarantees we are not active
1247 		 * with this devinfo node in any other entry points at
1248 		 * this time.
1249 		 */
1250 
1251 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1252 		    "st_detach: instance=%x, un=%p\n", instance,
1253 		    (void *)un);
1254 
1255 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1256 		    ((un->un_rsvd_status & ST_APPLICATION_RESERVATIONS) != 0) ||
1257 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1258 		    (un->un_state != ST_STATE_CLOSED)) {
1259 			/*
1260 			 * we cannot unload some targets because the
1261 			 * inquiry returns junk unless immediately
1262 			 * after a reset
1263 			 */
1264 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1265 			    "cannot unload instance %x\n", instance);
1266 			un->un_unit_attention_flags |= 4;
1267 			return (DDI_FAILURE);
1268 		}
1269 
1270 		/*
1271 		 * if the tape has been removed then we may unload;
1272 		 * do a test unit ready and if it returns NOT READY
1273 		 * then we assume that it is safe to unload.
1274 		 * as a side effect, pmode may be set to invalid if the
1275 		 * the test unit ready fails;
1276 		 * also un_state may be set to non-closed, so reset it
1277 		 */
1278 		if ((un->un_dev) &&		/* Been opened since attach */
1279 		    ((un->un_pos.pmode == legacy) &&
1280 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1281 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1282 		    ((un->un_pos.pmode == logical) &&
1283 		    (un->un_pos.lgclblkno > 0))) {
1284 			mutex_enter(ST_MUTEX);
1285 			/*
1286 			 * Send Test Unit Ready in the hopes that if
1287 			 * the drive is not in the state we think it is.
1288 			 * And the state will be changed so it can be detached.
1289 			 * If the command fails to reach the device and
1290 			 * the drive was not rewound or unloaded we want
1291 			 * to fail the detach till a user command fails
1292 			 * where after the detach will succead.
1293 			 */
1294 			result = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
1295 			/*
1296 			 * After TUR un_state may be set to non-closed,
1297 			 * so reset it back.
1298 			 */
1299 			un->un_state = ST_STATE_CLOSED;
1300 			mutex_exit(ST_MUTEX);
1301 		}
1302 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1303 		    "un_status=%x, fileno=%x, blkno=%x\n",
1304 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1305 
1306 		/*
1307 		 * check again:
1308 		 * if we are not at BOT then it is not safe to unload
1309 		 */
1310 		if ((un->un_dev) &&		/* Been opened since attach */
1311 		    (result != EACCES) &&	/* drive is use by somebody */
1312 		    (((un->un_pos.pmode == legacy) &&
1313 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1314 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1315 		    ((un->un_pos.pmode == logical) &&
1316 		    (un->un_pos.lgclblkno > 0)))) {
1317 
1318 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1319 			    "cannot detach: pmode=%d fileno=0x%x, blkno=0x%x"
1320 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1321 			    un->un_pos.fileno, un->un_pos.blkno,
1322 			    un->un_pos.lgclblkno);
1323 			un->un_unit_attention_flags |= 4;
1324 			return (DDI_FAILURE);
1325 		}
1326 
1327 		/*
1328 		 * Just To make sure that we have released the
1329 		 * tape unit .
1330 		 */
1331 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1332 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1333 			mutex_enter(ST_MUTEX);
1334 			(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
1335 			mutex_exit(ST_MUTEX);
1336 		}
1337 
1338 		/*
1339 		 * now remove other data structures allocated in st_doattach()
1340 		 */
1341 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1342 		    "destroying/freeing\n");
1343 
1344 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1345 		    st_reset_notification, (caddr_t)un);
1346 		cv_destroy(&un->un_clscv);
1347 		cv_destroy(&un->un_sbuf_cv);
1348 		cv_destroy(&un->un_queue_cv);
1349 		cv_destroy(&un->un_suspend_cv);
1350 		cv_destroy(&un->un_tape_busy_cv);
1351 		cv_destroy(&un->un_recov_buf_cv);
1352 
1353 		if (un->un_recov_taskq) {
1354 			ddi_taskq_destroy(un->un_recov_taskq);
1355 		}
1356 
1357 		if (un->un_hib_tid) {
1358 			(void) untimeout(un->un_hib_tid);
1359 			un->un_hib_tid = 0;
1360 		}
1361 
1362 		if (un->un_delay_tid) {
1363 			(void) untimeout(un->un_delay_tid);
1364 			un->un_delay_tid = 0;
1365 		}
1366 		cv_destroy(&un->un_state_cv);
1367 
1368 #ifdef	__x86
1369 		cv_destroy(&un->un_contig_mem_cv);
1370 
1371 		if (un->un_contig_mem_hdl != NULL) {
1372 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1373 		}
1374 #endif
1375 		if (un->un_sbufp) {
1376 			freerbuf(un->un_sbufp);
1377 		}
1378 		if (un->un_recov_buf) {
1379 			freerbuf(un->un_recov_buf);
1380 		}
1381 		if (un->un_uscsi_rqs_buf) {
1382 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1383 		}
1384 		if (un->un_mspl) {
1385 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1386 		}
1387 		if (un->un_rqs) {
1388 			scsi_destroy_pkt(un->un_rqs);
1389 			scsi_free_consistent_buf(un->un_rqs_bp);
1390 		}
1391 		if (un->un_mkr_pkt) {
1392 			scsi_destroy_pkt(un->un_mkr_pkt);
1393 		}
1394 		if (un->un_arq_enabled) {
1395 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1396 		}
1397 		if (un->un_dp_size) {
1398 			kmem_free(un->un_dp, un->un_dp_size);
1399 		}
1400 		if (un->un_stats) {
1401 			kstat_delete(un->un_stats);
1402 			un->un_stats = (kstat_t *)0;
1403 		}
1404 		if (un->un_errstats) {
1405 			kstat_delete(un->un_errstats);
1406 			un->un_errstats = (kstat_t *)0;
1407 		}
1408 		if (un->un_media_id_len) {
1409 			kmem_free(un->un_media_id, un->un_media_id_len);
1410 		}
1411 		devp = ST_SCSI_DEVP;
1412 		ddi_soft_state_free(st_state, instance);
1413 		devp->sd_private = NULL;
1414 		devp->sd_sense = NULL;
1415 		scsi_unprobe(devp);
1416 		ddi_prop_remove_all(devi);
1417 		ddi_remove_minor_node(devi, NULL);
1418 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1419 		return (DDI_SUCCESS);
1420 
1421 	case DDI_SUSPEND:
1422 
1423 		/*
1424 		 * Suspend/Resume
1425 		 *
1426 		 * To process DDI_SUSPEND, we must do the following:
1427 		 *
1428 		 *  - check ddi_removing_power to see if power will be turned
1429 		 *    off. if so, return DDI_FAILURE
1430 		 *  - check if we are already suspended,
1431 		 *    if so, return DDI_FAILURE
1432 		 *  - check if device state is CLOSED,
1433 		 *    if not, return DDI_FAILURE.
1434 		 *  - wait until outstanding operations complete
1435 		 *  - save tape state
1436 		 *  - block new operations
1437 		 *  - cancel pending timeouts
1438 		 *
1439 		 */
1440 
1441 		if (ddi_removing_power(devi)) {
1442 			return (DDI_FAILURE);
1443 		}
1444 		mutex_enter(ST_MUTEX);
1445 
1446 		/*
1447 		 * Shouldn't already be suspended, if so return failure
1448 		 */
1449 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1450 			mutex_exit(ST_MUTEX);
1451 			return (DDI_FAILURE);
1452 		}
1453 		if (un->un_state != ST_STATE_CLOSED) {
1454 			mutex_exit(ST_MUTEX);
1455 			return (DDI_FAILURE);
1456 		}
1457 
1458 		/*
1459 		 * Wait for all outstanding I/O's to complete
1460 		 *
1461 		 * we wait on both ncmds and the wait queue for times
1462 		 * when we are flushing after persistent errors are
1463 		 * flagged, which is when ncmds can be 0, and the
1464 		 * queue can still have I/O's.  This way we preserve
1465 		 * order of biodone's.
1466 		 */
1467 		wait_cmds_complete = ddi_get_lbolt();
1468 		wait_cmds_complete +=
1469 		    st_wait_cmds_complete * drv_usectohz(1000000);
1470 		while (un->un_ncmds || un->un_quef ||
1471 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1472 
1473 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1474 			    wait_cmds_complete) == -1) {
1475 				/*
1476 				 * Time expired then cancel the command
1477 				 */
1478 				if (st_reset(un, RESET_LUN) == 0) {
1479 					if (un->un_last_throttle) {
1480 						un->un_throttle =
1481 						    un->un_last_throttle;
1482 					}
1483 					mutex_exit(ST_MUTEX);
1484 					return (DDI_FAILURE);
1485 				} else {
1486 					break;
1487 				}
1488 			}
1489 		}
1490 
1491 		/*
1492 		 * DDI_SUSPEND says that the system "may" power down, we
1493 		 * remember the file and block number before rewinding.
1494 		 * we also need to save state before issuing
1495 		 * any WRITE_FILE_MARK command.
1496 		 */
1497 		(void) st_update_block_pos(un, st_cmd, 0);
1498 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1499 
1500 
1501 		/*
1502 		 * Issue a zero write file fmk command to tell the drive to
1503 		 * flush any buffered tape marks
1504 		 */
1505 		(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1506 
1507 		/*
1508 		 * Because not all tape drives correctly implement buffer
1509 		 * flushing with the zero write file fmk command, issue a
1510 		 * synchronous rewind command to force data flushing.
1511 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1512 		 * anyway.
1513 		 */
1514 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
1515 
1516 		/* stop any new operations */
1517 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1518 		un->un_throttle = 0;
1519 
1520 		/*
1521 		 * cancel any outstanding timeouts
1522 		 */
1523 		if (un->un_delay_tid) {
1524 			timeout_id_t temp_id = un->un_delay_tid;
1525 			un->un_delay_tid = 0;
1526 			un->un_tids_at_suspend |= ST_DELAY_TID;
1527 			mutex_exit(ST_MUTEX);
1528 			(void) untimeout(temp_id);
1529 			mutex_enter(ST_MUTEX);
1530 		}
1531 
1532 		if (un->un_hib_tid) {
1533 			timeout_id_t temp_id = un->un_hib_tid;
1534 			un->un_hib_tid = 0;
1535 			un->un_tids_at_suspend |= ST_HIB_TID;
1536 			mutex_exit(ST_MUTEX);
1537 			(void) untimeout(temp_id);
1538 			mutex_enter(ST_MUTEX);
1539 		}
1540 
1541 		/*
1542 		 * Suspend the scsi_watch_thread
1543 		 */
1544 		if (un->un_swr_token) {
1545 			opaque_t temp_token = un->un_swr_token;
1546 			mutex_exit(ST_MUTEX);
1547 			scsi_watch_suspend(temp_token);
1548 		} else {
1549 			mutex_exit(ST_MUTEX);
1550 		}
1551 
1552 		return (DDI_SUCCESS);
1553 
1554 	default:
1555 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1556 		return (DDI_FAILURE);
1557 	}
1558 }
1559 
1560 
1561 /* ARGSUSED */
1562 static int
1563 st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1564 {
1565 	dev_t dev;
1566 	struct scsi_tape *un;
1567 	int instance, error;
1568 
1569 	ST_ENTR(dip, st_info);
1570 
1571 	switch (infocmd) {
1572 	case DDI_INFO_DEVT2DEVINFO:
1573 		dev = (dev_t)arg;
1574 		instance = MTUNIT(dev);
1575 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1576 			return (DDI_FAILURE);
1577 		*result = (void *) ST_DEVINFO;
1578 		error = DDI_SUCCESS;
1579 		break;
1580 	case DDI_INFO_DEVT2INSTANCE:
1581 		dev = (dev_t)arg;
1582 		instance = MTUNIT(dev);
1583 		*result = (void *)(uintptr_t)instance;
1584 		error = DDI_SUCCESS;
1585 		break;
1586 	default:
1587 		error = DDI_FAILURE;
1588 	}
1589 	return (error);
1590 }
1591 
1592 static int
1593 st_doattach(struct scsi_device *devp, int (*canwait)())
1594 {
1595 	struct scsi_tape *un = NULL;
1596 	recov_info *ri;
1597 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1598 	int instance;
1599 	size_t rlen;
1600 
1601 	ST_FUNC(devp->sd_dev, st_doattach);
1602 	/*
1603 	 * Call the routine scsi_probe to do some of the dirty work.
1604 	 * If the INQUIRY command succeeds, the field sd_inq in the
1605 	 * device structure will be filled in.
1606 	 */
1607 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1608 	    "st_doattach(): probing\n");
1609 
1610 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1611 
1612 		/*
1613 		 * In checking the whole inq_dtype byte we are looking at both
1614 		 * the Peripheral Qualifier and the Peripheral Device Type.
1615 		 * For this driver we are only interested in sequential devices
1616 		 * that are connected or capable if connecting to this logical
1617 		 * unit.
1618 		 */
1619 		if (devp->sd_inq->inq_dtype ==
1620 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1621 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1622 			    "probe exists\n");
1623 		} else {
1624 			/* Something there but not a tape device */
1625 			scsi_unprobe(devp);
1626 			return (DDI_FAILURE);
1627 		}
1628 	} else {
1629 		/* Nothing there */
1630 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1631 		    "probe failure: nothing there\n");
1632 		scsi_unprobe(devp);
1633 		return (DDI_FAILURE);
1634 	}
1635 
1636 
1637 	/*
1638 	 * The actual unit is present.
1639 	 * Now is the time to fill in the rest of our info..
1640 	 */
1641 	instance = ddi_get_instance(devp->sd_dev);
1642 
1643 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1644 		goto error;
1645 	}
1646 	un = ddi_get_soft_state(st_state, instance);
1647 
1648 	ASSERT(un != NULL);
1649 
1650 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
1651 	    MAX_SENSE_LENGTH, B_READ, canwait, NULL);
1652 	if (un->un_rqs_bp == NULL) {
1653 		goto error;
1654 	}
1655 	un->un_rqs = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
1656 	    CDB_GROUP0, 1, st_recov_sz, PKT_CONSISTENT, canwait, NULL);
1657 	if (!un->un_rqs) {
1658 		goto error;
1659 	}
1660 	ASSERT(un->un_rqs->pkt_resid == 0);
1661 	devp->sd_sense =
1662 	    (struct scsi_extended_sense *)un->un_rqs_bp->b_un.b_addr;
1663 	ASSERT(geterror(un->un_rqs_bp) == NULL);
1664 
1665 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs->pkt_cdbp,
1666 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
1667 	FILL_SCSI1_LUN(devp, un->un_rqs);
1668 	un->un_rqs->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1669 	un->un_rqs->pkt_time = st_io_time;
1670 	un->un_rqs->pkt_comp = st_intr;
1671 	ri = (recov_info *)un->un_rqs->pkt_private;
1672 	if (st_recov_sz == sizeof (recov_info)) {
1673 		ri->privatelen = sizeof (recov_info);
1674 	} else {
1675 		ri->privatelen = sizeof (pkt_info);
1676 	}
1677 
1678 	un->un_sbufp = getrbuf(km_flags);
1679 	un->un_recov_buf = getrbuf(km_flags);
1680 
1681 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1682 
1683 	/*
1684 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1685 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1686 	 * is obsolete and we want more flexibility in controlling the DMA
1687 	 * address constraints.
1688 	 */
1689 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1690 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1691 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1692 
1693 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1694 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1695 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1696 
1697 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1698 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1699 		    "probe partial failure: no space\n");
1700 		goto error;
1701 	}
1702 
1703 	bzero(un->un_mspl, sizeof (struct seq_mode));
1704 
1705 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1706 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1707 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1708 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1709 #ifdef	__x86
1710 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1711 #endif
1712 
1713 	/* Initialize power managemnet condition variable */
1714 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1715 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1716 	cv_init(&un->un_recov_buf_cv, NULL, CV_DRIVER, NULL);
1717 
1718 	un->un_recov_taskq = ddi_taskq_create(devp->sd_dev,
1719 	    "un_recov_taskq", 1, TASKQ_DEFAULTPRI, km_flags);
1720 
1721 	ASSERT(un->un_recov_taskq != NULL);
1722 
1723 	un->un_pos.pmode = invalid;
1724 	un->un_sd	= devp;
1725 	un->un_swr_token = (opaque_t)NULL;
1726 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1727 	un->un_wormable = st_is_drive_worm;
1728 	un->un_media_id_method = st_get_media_identification;
1729 	/*
1730 	 * setting long a initial as it contains logical file info.
1731 	 * support for long format is mandatory but many drive don't do it.
1732 	 */
1733 	un->un_read_pos_type = LONG_POS;
1734 
1735 	un->un_suspend_pos.pmode = invalid;
1736 
1737 	st_add_recovery_info_to_pkt(un, un->un_rqs_bp, un->un_rqs);
1738 
1739 #ifdef	__x86
1740 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1741 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1742 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1743 		    "allocation of contiguous memory dma handle failed!");
1744 		un->un_contig_mem_hdl = NULL;
1745 		goto error;
1746 	}
1747 #endif
1748 
1749 	/*
1750 	 * Since this driver manages devices with "remote" hardware,
1751 	 * i.e. the devices themselves have no "reg" properties,
1752 	 * the SUSPEND/RESUME commands in detach/attach will not be
1753 	 * called by the power management framework unless we request
1754 	 * it by creating a "pm-hardware-state" property and setting it
1755 	 * to value "needs-suspend-resume".
1756 	 */
1757 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1758 	    "pm-hardware-state", "needs-suspend-resume") !=
1759 	    DDI_PROP_SUCCESS) {
1760 
1761 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1762 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1763 		goto error;
1764 	}
1765 
1766 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1767 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1768 
1769 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1770 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1771 		    "failed\n");
1772 		goto error;
1773 	}
1774 
1775 	(void) scsi_reset_notify(ROUTE, SCSI_RESET_NOTIFY,
1776 	    st_reset_notification, (caddr_t)un);
1777 
1778 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "attach success\n");
1779 	return (DDI_SUCCESS);
1780 
1781 error:
1782 	devp->sd_sense = NULL;
1783 
1784 	ddi_remove_minor_node(devp->sd_dev, NULL);
1785 	if (un) {
1786 		if (un->un_mspl) {
1787 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1788 		}
1789 		if (un->un_read_pos_data) {
1790 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1791 		}
1792 		if (un->un_sbufp) {
1793 			freerbuf(un->un_sbufp);
1794 		}
1795 		if (un->un_recov_buf) {
1796 			freerbuf(un->un_recov_buf);
1797 		}
1798 		if (un->un_uscsi_rqs_buf) {
1799 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1800 		}
1801 #ifdef	__x86
1802 		if (un->un_contig_mem_hdl != NULL) {
1803 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1804 		}
1805 #endif
1806 		if (un->un_rqs) {
1807 			scsi_destroy_pkt(un->un_rqs);
1808 		}
1809 
1810 		if (un->un_rqs_bp) {
1811 			scsi_free_consistent_buf(un->un_rqs_bp);
1812 		}
1813 
1814 		ddi_soft_state_free(st_state, instance);
1815 		devp->sd_private = NULL;
1816 	}
1817 
1818 	if (devp->sd_inq) {
1819 		scsi_unprobe(devp);
1820 	}
1821 	return (DDI_FAILURE);
1822 }
1823 
1824 typedef int
1825 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1826 
1827 static cfg_functp config_functs[] = {
1828 	st_get_conf_from_st_dot_conf,
1829 	st_get_conf_from_st_conf_dot_c,
1830 	st_get_conf_from_tape_drive,
1831 	st_get_default_conf
1832 };
1833 
1834 
1835 /*
1836  * determine tape type, using tape-config-list or built-in table or
1837  * use a generic tape config entry
1838  */
1839 static void
1840 st_known_tape_type(struct scsi_tape *un)
1841 {
1842 	struct st_drivetype *dp;
1843 	cfg_functp *config_funct;
1844 	uchar_t reserved;
1845 
1846 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1847 
1848 	reserved = (un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1849 	    : ST_RELEASE;
1850 
1851 	/*
1852 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1853 	 *	 no vid & pid inquiry data.  So, we provide one.
1854 	 */
1855 	if (ST_INQUIRY->inq_len == 0 ||
1856 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1857 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1858 	}
1859 
1860 	if (un->un_dp_size == 0) {
1861 		un->un_dp_size = sizeof (struct st_drivetype);
1862 		dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1863 		un->un_dp = dp;
1864 	} else {
1865 		dp = un->un_dp;
1866 	}
1867 
1868 	un->un_dp->non_motion_timeout = st_io_time;
1869 	/*
1870 	 * Loop through the configuration methods till one works.
1871 	 */
1872 	for (config_funct = &config_functs[0]; ; config_funct++) {
1873 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1874 			break;
1875 		}
1876 	}
1877 
1878 	/*
1879 	 * If we didn't just make up this configuration and
1880 	 * all the density codes are the same..
1881 	 * Set Auto Density over ride.
1882 	 */
1883 	if (*config_funct != st_get_default_conf) {
1884 		/*
1885 		 * If this device is one that is configured and all
1886 		 * densities are the same, This saves doing gets and set
1887 		 * that yield nothing.
1888 		 */
1889 		if ((dp->densities[0]) == (dp->densities[1]) &&
1890 		    (dp->densities[0]) == (dp->densities[2]) &&
1891 		    (dp->densities[0]) == (dp->densities[3])) {
1892 
1893 			dp->options |= ST_AUTODEN_OVERRIDE;
1894 		}
1895 	}
1896 
1897 
1898 	/*
1899 	 * Store tape drive characteristics.
1900 	 */
1901 	un->un_status = 0;
1902 	un->un_attached = 1;
1903 	un->un_init_options = dp->options;
1904 
1905 	/* setup operation time-outs based on options */
1906 	st_calculate_timeouts(un);
1907 
1908 	/* make sure if we are supposed to be variable, make it variable */
1909 	if (dp->options & ST_VARIABLE) {
1910 		dp->bsize = 0;
1911 	}
1912 
1913 	if (reserved != ((un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1914 	    : ST_RELEASE)) {
1915 		(void) st_reserve_release(un, reserved, st_uscsi_cmd);
1916 	}
1917 
1918 	un->un_unit_attention_flags |= 1;
1919 
1920 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1921 
1922 }
1923 
1924 
1925 typedef struct {
1926 	int mask;
1927 	int bottom;
1928 	int top;
1929 	char *name;
1930 } conf_limit;
1931 
1932 static const conf_limit conf_limits[] = {
1933 
1934 	-1,		1,		2,		"conf version",
1935 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1936 	-1,		0,		0xffffff,	"block size",
1937 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1938 	-1,		0,		4,		"number of densities",
1939 	-1,		0,		UINT8_MAX,	"density code",
1940 	-1,		0,		3,		"default density",
1941 	-1,		0,		UINT16_MAX,	"non motion timeout",
1942 	-1,		0,		UINT16_MAX,	"I/O timeout",
1943 	-1,		0,		UINT16_MAX,	"space timeout",
1944 	-1,		0,		UINT16_MAX,	"load timeout",
1945 	-1,		0,		UINT16_MAX,	"unload timeout",
1946 	-1,		0,		UINT16_MAX,	"erase timeout",
1947 	0,		0,		0,		NULL
1948 };
1949 
1950 static int
1951 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1952     const char *conf_name)
1953 {
1954 	int dens;
1955 	int ndens;
1956 	int value;
1957 	int type;
1958 	int count;
1959 	const conf_limit *limit = &conf_limits[0];
1960 
1961 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1962 
1963 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1964 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1965 
1966 	count = list_len;
1967 	type = *list;
1968 	for (;  count && limit->name; count--, list++, limit++) {
1969 
1970 		value = *list;
1971 		if (value & ~limit->mask) {
1972 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1973 			    "%s %s value invalid bits set: 0x%X\n",
1974 			    conf_name, limit->name, value & ~limit->mask);
1975 			*list &= limit->mask;
1976 		} else if (value < limit->bottom) {
1977 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1978 			    "%s %s value too low: value = %d limit %d\n",
1979 			    conf_name, limit->name, value, limit->bottom);
1980 		} else if (value > limit->top) {
1981 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1982 			    "%s %s value too high: value = %d limit %d\n",
1983 			    conf_name, limit->name, value, limit->top);
1984 		} else {
1985 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1986 			    "%s %s value = 0x%X\n",
1987 			    conf_name, limit->name, value);
1988 		}
1989 
1990 		/* If not the number of densities continue */
1991 		if (limit != &conf_limits[4]) {
1992 			continue;
1993 		}
1994 
1995 		/* If number of densities is not in range can't use config */
1996 		if (value < limit->bottom || value > limit->top) {
1997 			return (-1);
1998 		}
1999 
2000 		ndens = min(value, NDENSITIES);
2001 		if ((type == 1) && (list_len - ndens) != 6) {
2002 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2003 			    "%s conf version 1 with %d densities has %d items"
2004 			    " should have %d",
2005 			    conf_name, ndens, list_len, 6 + ndens);
2006 		} else if ((type == 2) && (list_len - ndens) != 13) {
2007 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2008 			    "%s conf version 2 with %d densities has %d items"
2009 			    " should have %d",
2010 			    conf_name, ndens, list_len, 13 + ndens);
2011 		}
2012 
2013 		limit++;
2014 		for (dens = 0; dens < ndens && count; dens++) {
2015 			count--;
2016 			list++;
2017 			value = *list;
2018 			if (value < limit->bottom) {
2019 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2020 				    "%s density[%d] value too low: value ="
2021 				    " 0x%X limit 0x%X\n",
2022 				    conf_name, dens, value, limit->bottom);
2023 			} else if (value > limit->top) {
2024 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2025 				    "%s density[%d] value too high: value ="
2026 				    " 0x%X limit 0x%X\n",
2027 				    conf_name, dens, value, limit->top);
2028 			} else {
2029 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2030 				    "%s density[%d] value = 0x%X\n",
2031 				    conf_name, dens, value);
2032 			}
2033 		}
2034 	}
2035 
2036 	return (0);
2037 }
2038 
2039 static int
2040 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
2041     struct st_drivetype *dp)
2042 {
2043 	caddr_t config_list = NULL;
2044 	caddr_t data_list = NULL;
2045 	int	*data_ptr;
2046 	caddr_t vidptr, prettyptr, datanameptr;
2047 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
2048 	int config_list_len, data_list_len, len, i;
2049 	int version;
2050 	int found = 0;
2051 
2052 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
2053 
2054 	/*
2055 	 * Determine type of tape controller. Type is determined by
2056 	 * checking the vendor ids of the earlier inquiry command and
2057 	 * comparing those with vids in tape-config-list defined in st.conf
2058 	 */
2059 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
2060 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
2061 	    != DDI_PROP_SUCCESS) {
2062 		return (found);
2063 	}
2064 
2065 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2066 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
2067 
2068 	/*
2069 	 * Compare vids in each triplet - if it matches, get value for
2070 	 * data_name and contruct a st_drivetype struct
2071 	 * tripletlen is not set yet!
2072 	 */
2073 	for (len = config_list_len, vidptr = config_list;
2074 	    len > 0;
2075 	    vidptr += tripletlen, len -= tripletlen) {
2076 
2077 		vidlen = strlen(vidptr);
2078 		prettyptr = vidptr + vidlen + 1;
2079 		prettylen = strlen(prettyptr);
2080 		datanameptr = prettyptr + prettylen + 1;
2081 		datanamelen = strlen(datanameptr);
2082 		tripletlen = vidlen + prettylen + datanamelen + 3;
2083 
2084 		if (vidlen == 0) {
2085 			continue;
2086 		}
2087 
2088 		/*
2089 		 * If inquiry vid dosen't match this triplets vid,
2090 		 * try the next.
2091 		 */
2092 		if (strncasecmp(vidpid, vidptr, vidlen)) {
2093 			continue;
2094 		}
2095 
2096 		/*
2097 		 * if prettylen is zero then use the vid string
2098 		 */
2099 		if (prettylen == 0) {
2100 			prettyptr = vidptr;
2101 			prettylen = vidlen;
2102 		}
2103 
2104 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2105 		    "vid = %s, pretty=%s, dataname = %s\n",
2106 		    vidptr, prettyptr, datanameptr);
2107 
2108 		/*
2109 		 * get the data list
2110 		 */
2111 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
2112 		    datanameptr, (caddr_t)&data_list,
2113 		    &data_list_len) != DDI_PROP_SUCCESS) {
2114 			/*
2115 			 * Error in getting property value
2116 			 * print warning!
2117 			 */
2118 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2119 			    "data property (%s) has no value\n",
2120 			    datanameptr);
2121 			continue;
2122 		}
2123 
2124 		/*
2125 		 * now initialize the st_drivetype struct
2126 		 */
2127 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
2128 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
2129 		(void) strncpy(dp->vid, vidptr, dp->length);
2130 		data_ptr = (int *)data_list;
2131 		/*
2132 		 * check if data is enough for version, type,
2133 		 * bsize, options, # of densities, density1,
2134 		 * density2, ..., default_density
2135 		 */
2136 		if ((data_list_len < 5 * sizeof (int)) ||
2137 		    (data_list_len < 6 * sizeof (int) +
2138 		    *(data_ptr + 4) * sizeof (int))) {
2139 			/*
2140 			 * print warning and skip to next triplet.
2141 			 */
2142 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2143 			    "data property (%s) incomplete\n",
2144 			    datanameptr);
2145 			kmem_free(data_list, data_list_len);
2146 			continue;
2147 		}
2148 
2149 		if (st_validate_conf_data(un, data_ptr,
2150 		    data_list_len / sizeof (int), datanameptr)) {
2151 			kmem_free(data_list, data_list_len);
2152 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2153 			    "data property (%s) rejected\n",
2154 			    datanameptr);
2155 			continue;
2156 		}
2157 
2158 		/*
2159 		 * check version
2160 		 */
2161 		version = *data_ptr++;
2162 		if (version != 1 && version != 2) {
2163 			/* print warning but accept it */
2164 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2165 			    "Version # for data property (%s) "
2166 			    "not set to 1 or 2\n", datanameptr);
2167 		}
2168 
2169 		dp->type    = *data_ptr++;
2170 		dp->bsize   = *data_ptr++;
2171 		dp->options = *data_ptr++;
2172 		dp->options |= ST_DYNAMIC;
2173 		len = *data_ptr++;
2174 		for (i = 0; i < NDENSITIES; i++) {
2175 			if (i < len) {
2176 				dp->densities[i] = *data_ptr++;
2177 			}
2178 		}
2179 		dp->default_density = *data_ptr << 3;
2180 		if (version == 2 &&
2181 		    data_list_len >= (13 + len) * sizeof (int)) {
2182 			data_ptr++;
2183 			dp->non_motion_timeout	= *data_ptr++;
2184 			dp->io_timeout		= *data_ptr++;
2185 			dp->rewind_timeout	= *data_ptr++;
2186 			dp->space_timeout	= *data_ptr++;
2187 			dp->load_timeout	= *data_ptr++;
2188 			dp->unload_timeout	= *data_ptr++;
2189 			dp->erase_timeout	= *data_ptr++;
2190 		}
2191 		kmem_free(data_list, data_list_len);
2192 		found = 1;
2193 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2194 		    "found in st.conf: vid = %s, pretty=%s\n",
2195 		    dp->vid, dp->name);
2196 		break;
2197 	}
2198 
2199 	/*
2200 	 * free up the memory allocated by ddi_getlongprop
2201 	 */
2202 	if (config_list) {
2203 		kmem_free(config_list, config_list_len);
2204 	}
2205 	return (found);
2206 }
2207 
2208 static int
2209 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2210     struct st_drivetype *dp)
2211 {
2212 	int i;
2213 
2214 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2215 	/*
2216 	 * Determine type of tape controller.  Type is determined by
2217 	 * checking the result of the earlier inquiry command and
2218 	 * comparing vendor ids with strings in a table declared in st_conf.c.
2219 	 */
2220 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2221 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2222 
2223 	for (i = 0; i < st_ndrivetypes; i++) {
2224 		if (st_drivetypes[i].length == 0) {
2225 			continue;
2226 		}
2227 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2228 		    st_drivetypes[i].length)) {
2229 			continue;
2230 		}
2231 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2232 		return (1);
2233 	}
2234 	return (0);
2235 }
2236 
2237 static int
2238 st_get_conf_from_tape_drive(struct scsi_tape *un, char *vidpid,
2239     struct st_drivetype *dp)
2240 {
2241 	int bsize;
2242 	ulong_t maxbsize;
2243 	caddr_t buf;
2244 	struct st_drivetype *tem_dp;
2245 	struct read_blklim *blklim;
2246 	int rval;
2247 	int i;
2248 
2249 	ST_FUNC(ST_DEVINFO, st_get_conf_from_tape_drive);
2250 
2251 	/*
2252 	 * Determine the type of tape controller. Type is determined by
2253 	 * sending SCSI commands to tape drive and deriving the type from
2254 	 * the returned data.
2255 	 */
2256 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2257 	    "st_get_conf_from_tape_drive(): asking tape drive\n");
2258 
2259 	tem_dp = kmem_zalloc(sizeof (struct st_drivetype), KM_SLEEP);
2260 
2261 	/*
2262 	 * Make up a name
2263 	 */
2264 	bcopy(vidpid, tem_dp->name, VIDPIDLEN);
2265 	tem_dp->name[VIDPIDLEN] = '\0';
2266 	tem_dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2267 	(void) strncpy(tem_dp->vid, ST_INQUIRY->inq_vid, tem_dp->length);
2268 	/*
2269 	 * 'clean' vendor and product strings of non-printing chars
2270 	 */
2271 	for (i = 0; i < VIDPIDLEN - 1; i ++) {
2272 		if (tem_dp->name[i] < ' ' || tem_dp->name[i] > '~') {
2273 			tem_dp->name[i] = '.';
2274 		}
2275 	}
2276 
2277 	/*
2278 	 * MODE SENSE to determine block size.
2279 	 */
2280 	un->un_dp->options |= ST_MODE_SEL_COMP | ST_UNLOADABLE;
2281 	rval = st_modesense(un);
2282 	if (rval) {
2283 		if (rval == EACCES) {
2284 			un->un_dp->type = ST_TYPE_INVALID;
2285 			rval = 1;
2286 		} else {
2287 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
2288 			rval = 0;
2289 		}
2290 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2291 		    "st_get_conf_from_tape_drive(): fail to mode sense\n");
2292 		goto exit;
2293 	}
2294 
2295 	/* Can mode sense page 0x10 or 0xf */
2296 	tem_dp->options |= ST_MODE_SEL_COMP;
2297 	bsize = (un->un_mspl->high_bl << 16)	|
2298 	    (un->un_mspl->mid_bl << 8)		|
2299 	    (un->un_mspl->low_bl);
2300 
2301 	if (bsize == 0) {
2302 		tem_dp->options |= ST_VARIABLE;
2303 		tem_dp->bsize = 0;
2304 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
2305 		rval = st_change_block_size(un, 0);
2306 		if (rval) {
2307 			if (rval == EACCES) {
2308 				un->un_dp->type = ST_TYPE_INVALID;
2309 				rval = 1;
2310 			} else {
2311 				rval = 0;
2312 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2313 				    "st_get_conf_from_tape_drive(): "
2314 				    "Fixed record size is too large and"
2315 				    "cannot switch to variable record size");
2316 			}
2317 			goto exit;
2318 		}
2319 		tem_dp->options |= ST_VARIABLE;
2320 	} else {
2321 		rval = st_change_block_size(un, 0);
2322 		if (rval == 0) {
2323 			tem_dp->options |= ST_VARIABLE;
2324 			tem_dp->bsize = 0;
2325 		} else if (rval != EACCES) {
2326 			tem_dp->bsize = bsize;
2327 		} else {
2328 			un->un_dp->type = ST_TYPE_INVALID;
2329 			rval = 1;
2330 			goto exit;
2331 		}
2332 	}
2333 
2334 	/*
2335 	 * If READ BLOCk LIMITS works and upper block size limit is
2336 	 * more than 64K, ST_NO_RECSIZE_LIMIT is supported.
2337 	 */
2338 	blklim = kmem_zalloc(sizeof (struct read_blklim), KM_SLEEP);
2339 	rval = st_read_block_limits(un, blklim);
2340 	if (rval) {
2341 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2342 		    "st_get_conf_from_tape_drive(): "
2343 		    "fail to read block limits.\n");
2344 		rval = 0;
2345 		kmem_free(blklim, sizeof (struct read_blklim));
2346 		goto exit;
2347 	}
2348 	maxbsize = (blklim->max_hi << 16) +
2349 	    (blklim->max_mid << 8) + blklim->max_lo;
2350 	if (maxbsize > ST_MAXRECSIZE_VARIABLE) {
2351 		tem_dp->options |= ST_NO_RECSIZE_LIMIT;
2352 	}
2353 	kmem_free(blklim, sizeof (struct read_blklim));
2354 
2355 	/*
2356 	 * Inquiry VPD page 0xb0 to see if the tape drive supports WORM
2357 	 */
2358 	buf = kmem_zalloc(6, KM_SLEEP);
2359 	rval = st_get_special_inquiry(un, 6, buf, 0xb0);
2360 	if (rval) {
2361 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2362 		    "st_get_conf_from_tape_drive(): "
2363 		    "fail to read vitial inquiry.\n");
2364 		rval = 0;
2365 		kmem_free(buf, 6);
2366 		goto exit;
2367 	}
2368 	if (buf[4] & 1) {
2369 		tem_dp->options |= ST_WORMABLE;
2370 	}
2371 	kmem_free(buf, 6);
2372 
2373 	/* Assume BSD BSR KNOWS_EOD */
2374 	tem_dp->options |= ST_BSF | ST_BSR | ST_KNOWS_EOD | ST_UNLOADABLE;
2375 	tem_dp->max_rretries = -1;
2376 	tem_dp->max_wretries = -1;
2377 
2378 	/*
2379 	 * Decide the densities supported by tape drive by sending
2380 	 * REPORT DENSITY SUPPORT command.
2381 	 */
2382 	if (st_get_densities_from_tape_drive(un, tem_dp) == 0) {
2383 		goto exit;
2384 	}
2385 
2386 	/*
2387 	 * Decide the timeout values for several commands by sending
2388 	 * REPORT SUPPORTED OPERATION CODES command.
2389 	 */
2390 	rval = st_get_timeout_values_from_tape_drive(un, tem_dp);
2391 	if (rval == 0 || ((rval == 1) && (tem_dp->type == ST_TYPE_INVALID))) {
2392 		goto exit;
2393 	}
2394 
2395 	bcopy(tem_dp, dp, sizeof (struct st_drivetype));
2396 	rval = 1;
2397 
2398 exit:
2399 	un->un_status = KEY_NO_SENSE;
2400 	kmem_free(tem_dp, sizeof (struct st_drivetype));
2401 	return (rval);
2402 }
2403 
2404 static int
2405 st_get_densities_from_tape_drive(struct scsi_tape *un,
2406     struct st_drivetype *dp)
2407 {
2408 	int i, p;
2409 	size_t buflen;
2410 	ushort_t des_len;
2411 	uchar_t *den_header;
2412 	uchar_t num_den;
2413 	uchar_t den[NDENSITIES];
2414 	uchar_t deflt[NDENSITIES];
2415 	struct report_density_desc *den_desc;
2416 
2417 	ST_FUNC(ST_DEVINFO, st_get_densities_from_type_drive);
2418 
2419 	/*
2420 	 * Since we have no idea how many densitiy support entries
2421 	 * will be returned, we send the command firstly assuming
2422 	 * there is only one. Then we can decide the number of
2423 	 * entries by available density support length. If multiple
2424 	 * entries exist, we will resend the command with enough
2425 	 * buffer size.
2426 	 */
2427 	buflen = sizeof (struct report_density_header) +
2428 	    sizeof (struct report_density_desc);
2429 	den_header = kmem_zalloc(buflen, KM_SLEEP);
2430 	if (st_report_density_support(un, den_header, buflen) != 0) {
2431 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2432 		    "st_get_conf_from_tape_drive(): fail to report density.\n");
2433 		kmem_free(den_header, buflen);
2434 		return (0);
2435 	}
2436 	des_len =
2437 	    BE_16(((struct report_density_header *)den_header)->ava_dens_len);
2438 	num_den = (des_len - 2) / sizeof (struct report_density_desc);
2439 
2440 	if (num_den > 1) {
2441 		kmem_free(den_header, buflen);
2442 		buflen = sizeof (struct report_density_header) +
2443 		    sizeof (struct report_density_desc) * num_den;
2444 		den_header = kmem_zalloc(buflen, KM_SLEEP);
2445 		if (st_report_density_support(un, den_header, buflen) != 0) {
2446 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2447 			    "st_get_conf_from_tape_drive(): "
2448 			    "fail to report density.\n");
2449 			kmem_free(den_header, buflen);
2450 			return (0);
2451 		}
2452 	}
2453 
2454 	den_desc = (struct report_density_desc *)(den_header
2455 	    + sizeof (struct report_density_header));
2456 
2457 	/*
2458 	 * Decide the drive type by assigning organization
2459 	 */
2460 	for (i = 0; i < ST_NUM_MEMBERS(st_vid_dt); i ++) {
2461 		if (strncmp(st_vid_dt[i].vid, (char *)(den_desc->ass_org),
2462 		    8) == 0) {
2463 			dp->type = st_vid_dt[i].type;
2464 			break;
2465 		}
2466 	}
2467 	if (i == ST_NUM_MEMBERS(st_vid_dt)) {
2468 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2469 		    "st_get_conf_from_tape_drive(): "
2470 		    "can't find match of assigned ort.\n");
2471 		kmem_free(den_header, buflen);
2472 		return (0);
2473 	}
2474 
2475 	/*
2476 	 * The tape drive may support many tape formats, but the st driver
2477 	 * supports only the four highest densities. Since density code
2478 	 * values are returned by ascending sequence, we start from the
2479 	 * last entry of density support data block descriptor.
2480 	 */
2481 	p = 0;
2482 	den_desc += num_den - 1;
2483 	for (i = 0; i < num_den && p < NDENSITIES; i ++, den_desc --) {
2484 		if ((den_desc->pri_den != 0) && (den_desc->wrtok)) {
2485 			if (p != 0) {
2486 				if (den_desc->pri_den >= den[p - 1]) {
2487 					continue;
2488 				}
2489 			}
2490 			den[p] = den_desc->pri_den;
2491 			deflt[p] = den_desc->deflt;
2492 			p ++;
2493 		}
2494 	}
2495 
2496 	switch (p) {
2497 	case 0:
2498 		bzero(dp->densities, NDENSITIES);
2499 		dp->options |= ST_AUTODEN_OVERRIDE;
2500 		dp->default_density = MT_DENSITY4;
2501 		break;
2502 
2503 	case 1:
2504 		(void) memset(dp->densities, den[0], NDENSITIES);
2505 		dp->options |= ST_AUTODEN_OVERRIDE;
2506 		dp->default_density = MT_DENSITY4;
2507 		break;
2508 
2509 	case 2:
2510 		dp->densities[0] = den[1];
2511 		dp->densities[1] = den[1];
2512 		dp->densities[2] = den[0];
2513 		dp->densities[3] = den[0];
2514 		if (deflt[0]) {
2515 			dp->default_density = MT_DENSITY4;
2516 		} else {
2517 			dp->default_density = MT_DENSITY2;
2518 		}
2519 		break;
2520 
2521 	case 3:
2522 		dp->densities[0] = den[2];
2523 		dp->densities[1] = den[1];
2524 		dp->densities[2] = den[0];
2525 		dp->densities[3] = den[0];
2526 		if (deflt[0]) {
2527 			dp->default_density = MT_DENSITY4;
2528 		} else if (deflt[1]) {
2529 			dp->default_density = MT_DENSITY2;
2530 		} else {
2531 			dp->default_density = MT_DENSITY1;
2532 		}
2533 		break;
2534 
2535 	default:
2536 		for (i = p; i > p - NDENSITIES; i --) {
2537 			dp->densities[i - 1] = den[p - i];
2538 		}
2539 		if (deflt[0]) {
2540 			dp->default_density = MT_DENSITY4;
2541 		} else if (deflt[1]) {
2542 			dp->default_density = MT_DENSITY3;
2543 		} else if (deflt[2]) {
2544 			dp->default_density = MT_DENSITY2;
2545 		} else {
2546 			dp->default_density = MT_DENSITY1;
2547 		}
2548 		break;
2549 	}
2550 
2551 	bzero(dp->mediatype, NDENSITIES);
2552 
2553 	kmem_free(den_header, buflen);
2554 	return (1);
2555 }
2556 
2557 static int
2558 st_get_timeout_values_from_tape_drive(struct scsi_tape *un,
2559     struct st_drivetype *dp)
2560 {
2561 	ushort_t timeout;
2562 	int rval;
2563 
2564 	ST_FUNC(ST_DEVINFO, st_get_timeout_values_from_type_drive);
2565 
2566 	rval = st_get_timeouts_value(un, SCMD_ERASE, &timeout, 0);
2567 	if (rval) {
2568 		if (rval == EACCES) {
2569 			un->un_dp->type = ST_TYPE_INVALID;
2570 			dp->type = ST_TYPE_INVALID;
2571 			return (1);
2572 		}
2573 		return (0);
2574 	}
2575 	dp->erase_timeout = timeout;
2576 
2577 	rval = st_get_timeouts_value(un, SCMD_READ, &timeout, 0);
2578 	if (rval) {
2579 		if (rval == EACCES) {
2580 			un->un_dp->type = ST_TYPE_INVALID;
2581 			dp->type = ST_TYPE_INVALID;
2582 			return (1);
2583 		}
2584 		return (0);
2585 	}
2586 	dp->io_timeout = timeout;
2587 
2588 	rval = st_get_timeouts_value(un, SCMD_WRITE, &timeout, 0);
2589 	if (rval) {
2590 		if (rval == EACCES) {
2591 			un->un_dp->type = ST_TYPE_INVALID;
2592 			dp->type = ST_TYPE_INVALID;
2593 			return (1);
2594 		}
2595 		return (0);
2596 	}
2597 	dp->io_timeout = max(dp->io_timeout, timeout);
2598 
2599 	rval = st_get_timeouts_value(un, SCMD_SPACE, &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->space_timeout = timeout;
2609 
2610 	rval = st_get_timeouts_value(un, SCMD_LOAD, &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->load_timeout = timeout;
2620 	dp->unload_timeout = timeout;
2621 
2622 	rval = st_get_timeouts_value(un, SCMD_REWIND, &timeout, 0);
2623 	if (rval) {
2624 		if (rval == EACCES) {
2625 			un->un_dp->type = ST_TYPE_INVALID;
2626 			dp->type = ST_TYPE_INVALID;
2627 			return (1);
2628 		}
2629 		return (0);
2630 	}
2631 	dp->rewind_timeout = timeout;
2632 
2633 	rval = st_get_timeouts_value(un, SCMD_INQUIRY, &timeout, 0);
2634 	if (rval) {
2635 		if (rval == EACCES) {
2636 			un->un_dp->type = ST_TYPE_INVALID;
2637 			dp->type = ST_TYPE_INVALID;
2638 			return (1);
2639 		}
2640 		return (0);
2641 	}
2642 	dp->non_motion_timeout = timeout;
2643 
2644 	return (1);
2645 }
2646 
2647 static int
2648 st_get_timeouts_value(struct scsi_tape *un, uchar_t option_code,
2649     ushort_t *timeout_value, ushort_t service_action)
2650 {
2651 	uchar_t *timeouts;
2652 	uchar_t *oper;
2653 	uchar_t support;
2654 	uchar_t cdbsize;
2655 	uchar_t ctdp;
2656 	size_t buflen;
2657 	int rval;
2658 
2659 	ST_FUNC(ST_DEVINFO, st_get_timeouts_value);
2660 
2661 	buflen = sizeof (struct one_com_des) +
2662 	    sizeof (struct com_timeout_des);
2663 	oper = kmem_zalloc(buflen, KM_SLEEP);
2664 	rval = st_report_supported_operation(un, oper, option_code,
2665 	    service_action);
2666 
2667 	if (rval) {
2668 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2669 		    "st_get_timeouts_value(): "
2670 		    "fail to timeouts value for command %d.\n", option_code);
2671 		kmem_free(oper, buflen);
2672 		return (rval);
2673 	}
2674 
2675 	support = ((struct one_com_des *)oper)->support;
2676 	if ((support != SUPPORT_VALUES_SUPPORT_SCSI) &&
2677 	    (support != SUPPORT_VALUES_SUPPORT_VENDOR)) {
2678 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2679 		    "st_get_timeouts_value(): "
2680 		    "command %d is not supported.\n", option_code);
2681 		kmem_free(oper, buflen);
2682 		return (ENOTSUP);
2683 	}
2684 
2685 	ctdp = ((struct one_com_des *)oper)->ctdp;
2686 	if (!ctdp) {
2687 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2688 		    "st_get_timeouts_value(): "
2689 		    "command timeout is not included.\n");
2690 		kmem_free(oper, buflen);
2691 		return (ENOTSUP);
2692 	}
2693 
2694 	cdbsize = BE_16(((struct one_com_des *)oper)->cdb_size);
2695 	timeouts = (uchar_t *)(oper + cdbsize + 4);
2696 
2697 	/*
2698 	 * Timeout value in seconds is 4 bytes, but we only support the lower 2
2699 	 * bytes. If the higher 2 bytes are not zero, the timeout value is set
2700 	 * to 0xFFFF.
2701 	 */
2702 	if (*(timeouts + 8) != 0 || *(timeouts + 9) != 0) {
2703 		*timeout_value = USHRT_MAX;
2704 	} else {
2705 		*timeout_value = ((*(timeouts + 10)) << 8) |
2706 		    (*(timeouts + 11));
2707 	}
2708 
2709 	kmem_free(oper, buflen);
2710 	return (0);
2711 }
2712 
2713 static int
2714 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2715 {
2716 	int i;
2717 
2718 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2719 
2720 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2721 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2722 
2723 	/*
2724 	 * Make up a name
2725 	 */
2726 	bcopy("Vendor '", dp->name, 8);
2727 	bcopy(vidpid, &dp->name[8], VIDLEN);
2728 	bcopy("' Product '", &dp->name[16], 11);
2729 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2730 	dp->name[ST_NAMESIZE - 2] = '\'';
2731 	dp->name[ST_NAMESIZE - 1] = '\0';
2732 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2733 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2734 	/*
2735 	 * 'clean' vendor and product strings of non-printing chars
2736 	 */
2737 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2738 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2739 			dp->name[i] = '.';
2740 		}
2741 	}
2742 	dp->type = ST_TYPE_INVALID;
2743 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2744 
2745 	return (1); /* Can Not Fail */
2746 }
2747 
2748 /*
2749  * Regular Unix Entry points
2750  */
2751 
2752 
2753 
2754 /* ARGSUSED */
2755 static int
2756 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2757 {
2758 	dev_t dev = *dev_p;
2759 	int rval = 0;
2760 
2761 	GET_SOFT_STATE(dev);
2762 
2763 	ST_ENTR(ST_DEVINFO, st_open);
2764 
2765 	/*
2766 	 * validate that we are addressing a sensible unit
2767 	 */
2768 	mutex_enter(ST_MUTEX);
2769 
2770 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2771 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2772 	    st_dev_name(dev), *dev_p, flag, otyp);
2773 
2774 	/*
2775 	 * All device accesss go thru st_strategy() where we check
2776 	 * suspend status
2777 	 */
2778 
2779 	if (!un->un_attached) {
2780 		st_known_tape_type(un);
2781 		if (!un->un_attached) {
2782 			rval = ENXIO;
2783 			goto exit;
2784 		}
2785 
2786 	}
2787 
2788 	/*
2789 	 * Check for the case of the tape in the middle of closing.
2790 	 * This isn't simply a check of the current state, because
2791 	 * we could be in state of sensing with the previous state
2792 	 * that of closing.
2793 	 *
2794 	 * And don't allow multiple opens.
2795 	 */
2796 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2797 		un->un_laststate = un->un_state;
2798 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2799 		while (IS_CLOSING(un) ||
2800 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2801 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2802 				rval = EINTR;
2803 				un->un_state = un->un_laststate;
2804 				goto exit;
2805 			}
2806 		}
2807 	} else if (un->un_state != ST_STATE_CLOSED) {
2808 		rval = EBUSY;
2809 		goto busy;
2810 	}
2811 
2812 	/*
2813 	 * record current dev
2814 	 */
2815 	un->un_dev = dev;
2816 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2817 	un->un_errno = 0;	/* no errors yet */
2818 	un->un_restore_pos = 0;
2819 	un->un_rqs_state = 0;
2820 
2821 	/*
2822 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2823 	 * anything, leave internal states alone, if fileno >= 0
2824 	 */
2825 	if (flag & (FNDELAY | FNONBLOCK)) {
2826 		switch (un->un_pos.pmode) {
2827 
2828 		case invalid:
2829 			un->un_state = ST_STATE_OFFLINE;
2830 			break;
2831 
2832 		case legacy:
2833 			/*
2834 			 * If position is anything other than rewound.
2835 			 */
2836 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2837 				/*
2838 				 * set un_read_only/write-protect status.
2839 				 *
2840 				 * If the tape is not bot we can assume
2841 				 * that mspl->wp_status is set properly.
2842 				 * else
2843 				 * we need to do a mode sense/Tur once
2844 				 * again to get the actual tape status.(since
2845 				 * user might have replaced the tape)
2846 				 * Hence make the st state OFFLINE so that
2847 				 * we re-intialize the tape once again.
2848 				 */
2849 				un->un_read_only =
2850 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2851 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2852 			} else {
2853 				un->un_state = ST_STATE_OFFLINE;
2854 			}
2855 			break;
2856 		case logical:
2857 			if (un->un_pos.lgclblkno == 0) {
2858 				un->un_state = ST_STATE_OFFLINE;
2859 			} else {
2860 				un->un_read_only =
2861 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2862 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2863 			}
2864 			break;
2865 		}
2866 		rval = 0;
2867 	} else {
2868 		/*
2869 		 * Not opening O_NDELAY.
2870 		 */
2871 		un->un_state = ST_STATE_OPENING;
2872 
2873 		/*
2874 		 * Clear error entry stack
2875 		 */
2876 		st_empty_error_stack(un);
2877 
2878 		rval = st_tape_init(un);
2879 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2880 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2881 			rval = 0; /* so open doesn't fail */
2882 		} else if (rval) {
2883 			/*
2884 			 * Release the tape unit, if reserved and not
2885 			 * preserve reserve.
2886 			 */
2887 			if ((un->un_rsvd_status &
2888 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2889 				(void) st_reserve_release(un, ST_RELEASE,
2890 				    st_uscsi_cmd);
2891 			}
2892 		} else {
2893 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2894 		}
2895 	}
2896 
2897 exit:
2898 	/*
2899 	 * we don't want any uninvited guests scrogging our data when we're
2900 	 * busy with something, so for successful opens or failed opens
2901 	 * (except for EBUSY), reset these counters and state appropriately.
2902 	 */
2903 	if (rval != EBUSY) {
2904 		if (rval) {
2905 			un->un_state = ST_STATE_CLOSED;
2906 		}
2907 		un->un_err_resid = 0;
2908 		un->un_retry_ct = 0;
2909 	}
2910 busy:
2911 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2912 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2913 	mutex_exit(ST_MUTEX);
2914 	return (rval);
2915 
2916 }
2917 
2918 static int
2919 st_tape_init(struct scsi_tape *un)
2920 {
2921 	int err;
2922 	int rval = 0;
2923 
2924 	ST_FUNC(ST_DEVINFO, st_tape_init);
2925 
2926 	ASSERT(mutex_owned(ST_MUTEX));
2927 
2928 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2929 	    "st_tape_init(un = 0x%p, oflags = %d)\n", (void*)un, un->un_oflags);
2930 
2931 	/*
2932 	 * Clean up after any errors left by 'last' close.
2933 	 * This also handles the case of the initial open.
2934 	 */
2935 	if (un->un_state != ST_STATE_INITIALIZING) {
2936 		un->un_laststate = un->un_state;
2937 		un->un_state = ST_STATE_OPENING;
2938 	}
2939 
2940 	un->un_kbytes_xferred = 0;
2941 
2942 	/*
2943 	 * do a throw away TUR to clear check condition
2944 	 */
2945 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2946 
2947 	/*
2948 	 * If test unit ready fails because the drive is reserved
2949 	 * by another host fail the open for no access.
2950 	 */
2951 	if (err) {
2952 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2953 			un->un_state = ST_STATE_CLOSED;
2954 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2955 			    "st_tape_init: RESERVATION CONFLICT\n");
2956 			rval = EACCES;
2957 			goto exit;
2958 		} else if ((un->un_rsvd_status &
2959 		    ST_APPLICATION_RESERVATIONS) != 0) {
2960 			if ((ST_RQSENSE != NULL) &&
2961 			    (ST_RQSENSE->es_add_code == 0x2a &&
2962 			    ST_RQSENSE->es_qual_code == 0x03)) {
2963 				un->un_state = ST_STATE_CLOSED;
2964 				rval = EACCES;
2965 				goto exit;
2966 			}
2967 		}
2968 	}
2969 
2970 	/*
2971 	 * Tape self identification could fail if the tape drive is used by
2972 	 * another host during attach time. We try to get the tape type
2973 	 * again. This is also applied to any posponed configuration methods.
2974 	 */
2975 	if (un->un_dp->type == ST_TYPE_INVALID) {
2976 		un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
2977 		st_known_tape_type(un);
2978 	}
2979 
2980 	/*
2981 	 * If the tape type is still invalid, try to determine the generic
2982 	 * configuration.
2983 	 */
2984 	if (un->un_dp->type == ST_TYPE_INVALID) {
2985 		rval = st_determine_generic(un);
2986 		if (rval) {
2987 			if (rval != EACCES) {
2988 				rval = EIO;
2989 			}
2990 			un->un_state = ST_STATE_CLOSED;
2991 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2992 			    "st_tape_init: %s invalid type\n",
2993 			    rval == EACCES ? "EACCES" : "EIO");
2994 			goto exit;
2995 		}
2996 		/*
2997 		 * If this is a Unknown Type drive,
2998 		 * Use the READ BLOCK LIMITS to determine if
2999 		 * allow large xfer is approprate if not globally
3000 		 * disabled with st_allow_large_xfer.
3001 		 */
3002 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
3003 	} else {
3004 
3005 		/*
3006 		 * If we allow_large_xfer (ie >64k) and have not yet found out
3007 		 * the max block size supported by the drive,
3008 		 * find it by issueing a READ_BLKLIM command.
3009 		 * if READ_BLKLIM cmd fails, assume drive doesn't
3010 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
3011 		 */
3012 		un->un_allow_large_xfer = st_allow_large_xfer &&
3013 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
3014 	}
3015 	/*
3016 	 * if maxbsize is unknown, set the maximum block size.
3017 	 */
3018 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
3019 
3020 		/*
3021 		 * Get the Block limits of the tape drive.
3022 		 * if un->un_allow_large_xfer = 0 , then make sure
3023 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
3024 		 */
3025 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
3026 
3027 		err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3028 		if (err) {
3029 			/* Retry */
3030 			err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3031 		}
3032 		if (!err) {
3033 
3034 			/*
3035 			 * if cmd successful, use limit returned
3036 			 */
3037 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
3038 			    (un->un_rbl->max_mid << 8) +
3039 			    un->un_rbl->max_lo;
3040 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
3041 			    un->un_rbl->min_lo;
3042 			un->un_data_mod = 1 << un->un_rbl->granularity;
3043 			if ((un->un_maxbsize == 0) ||
3044 			    (un->un_allow_large_xfer == 0 &&
3045 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
3046 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3047 
3048 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
3049 				/*
3050 				 * Drive is not one that is configured, But the
3051 				 * READ BLOCK LIMITS tells us it can do large
3052 				 * xfers.
3053 				 */
3054 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
3055 					un->un_dp->options |=
3056 					    ST_NO_RECSIZE_LIMIT;
3057 				}
3058 				/*
3059 				 * If max and mimimum block limits are the
3060 				 * same this is a fixed block size device.
3061 				 */
3062 				if (un->un_maxbsize == un->un_minbsize) {
3063 					un->un_dp->options &= ~ST_VARIABLE;
3064 				}
3065 			}
3066 
3067 			if (un->un_minbsize == 0) {
3068 				un->un_minbsize = 1;
3069 			}
3070 
3071 		} else { /* error on read block limits */
3072 
3073 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3074 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
3075 			    " errno = %d un_rsvd_status = 0x%X\n",
3076 			    err, un->un_rsvd_status);
3077 
3078 			/*
3079 			 * since read block limits cmd failed,
3080 			 * do not allow large xfers.
3081 			 * use old values in st_minphys
3082 			 */
3083 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
3084 				rval = EACCES;
3085 			} else {
3086 				un->un_allow_large_xfer = 0;
3087 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3088 				    "!Disabling large transfers\n");
3089 
3090 				/*
3091 				 * we guess maxbsize and minbsize
3092 				 */
3093 				if (un->un_bsize) {
3094 					un->un_maxbsize = un->un_minbsize =
3095 					    un->un_bsize;
3096 				} else {
3097 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3098 					un->un_minbsize = 1;
3099 				}
3100 				/*
3101 				 * Data Mod must be set,
3102 				 * Even if read block limits fails.
3103 				 * Prevents Divide By Zero in st_rw().
3104 				 */
3105 				un->un_data_mod = 1;
3106 			}
3107 		}
3108 		if (un->un_rbl) {
3109 			kmem_free(un->un_rbl, RBLSIZE);
3110 			un->un_rbl = NULL;
3111 		}
3112 
3113 		if (rval) {
3114 			goto exit;
3115 		}
3116 	}
3117 
3118 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3119 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
3120 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
3121 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
3122 
3123 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
3124 
3125 	if (err != 0) {
3126 		if (err == EINTR) {
3127 			un->un_laststate = un->un_state;
3128 			un->un_state = ST_STATE_CLOSED;
3129 			rval = EINTR;
3130 			goto exit;
3131 		}
3132 		/*
3133 		 * Make sure the tape is ready
3134 		 */
3135 		un->un_pos.pmode = invalid;
3136 		if (un->un_status != KEY_UNIT_ATTENTION) {
3137 			/*
3138 			 * allow open no media.  Subsequent MTIOCSTATE
3139 			 * with media present will complete the open
3140 			 * logic.
3141 			 */
3142 			un->un_laststate = un->un_state;
3143 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
3144 				un->un_mediastate = MTIO_EJECTED;
3145 				un->un_state = ST_STATE_OFFLINE;
3146 				rval = 0;
3147 				goto exit;
3148 			} else {
3149 				un->un_state = ST_STATE_CLOSED;
3150 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3151 				    "st_tape_init EIO no media, not opened "
3152 				    "O_NONBLOCK|O_EXCL\n");
3153 				rval = EIO;
3154 				goto exit;
3155 			}
3156 		}
3157 	}
3158 
3159 	/*
3160 	 * On each open, initialize block size from drivetype struct,
3161 	 * as it could have been changed by MTSRSZ ioctl.
3162 	 * Now, ST_VARIABLE simply means drive is capable of variable
3163 	 * mode. All drives are assumed to support fixed records.
3164 	 * Hence, un_bsize tells what mode the drive is in.
3165 	 *	un_bsize	= 0	- variable record length
3166 	 *			= x	- fixed record length is x
3167 	 */
3168 	un->un_bsize = un->un_dp->bsize;
3169 
3170 	/*
3171 	 * If saved position is valid go there
3172 	 */
3173 	if (un->un_restore_pos) {
3174 		un->un_restore_pos = 0;
3175 		un->un_pos.fileno = un->un_save_fileno;
3176 		un->un_pos.blkno = un->un_save_blkno;
3177 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &un->un_pos);
3178 		if (rval != 0) {
3179 			if (rval != EACCES) {
3180 				rval = EIO;
3181 			}
3182 			un->un_laststate = un->un_state;
3183 			un->un_state = ST_STATE_CLOSED;
3184 			goto exit;
3185 		}
3186 	}
3187 
3188 	if (un->un_pos.pmode == invalid) {
3189 		rval = st_loadtape(un);
3190 		if (rval) {
3191 			if (rval != EACCES) {
3192 				rval = EIO;
3193 			}
3194 			un->un_laststate = un->un_state;
3195 			un->un_state = ST_STATE_CLOSED;
3196 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3197 			    "st_tape_init: %s can't open tape\n",
3198 			    rval == EACCES ? "EACCES" : "EIO");
3199 			goto exit;
3200 		}
3201 	}
3202 
3203 	/*
3204 	 * do a mode sense to pick up state of current write-protect,
3205 	 * Could cause reserve and fail due to conflict.
3206 	 */
3207 	if (un->un_unit_attention_flags) {
3208 		rval = st_modesense(un);
3209 		if (rval == EACCES) {
3210 			goto exit;
3211 		}
3212 	}
3213 
3214 	/*
3215 	 * If we are opening the tape for writing, check
3216 	 * to make sure that the tape can be written.
3217 	 */
3218 	if (un->un_oflags & FWRITE) {
3219 		err = 0;
3220 		if (un->un_mspl->wp) {
3221 			un->un_status = KEY_WRITE_PROTECT;
3222 			un->un_laststate = un->un_state;
3223 			un->un_state = ST_STATE_CLOSED;
3224 			rval = EACCES;
3225 			/*
3226 			 * STK sets the wp bit if volsafe tape is loaded.
3227 			 */
3228 			if ((un->un_dp->type == MT_ISSTK9840) &&
3229 			    (un->un_dp->options & ST_WORMABLE)) {
3230 				un->un_read_only = RDONLY;
3231 			} else {
3232 				goto exit;
3233 			}
3234 		} else {
3235 			un->un_read_only = RDWR;
3236 		}
3237 	} else {
3238 		un->un_read_only = RDONLY;
3239 	}
3240 
3241 	if (un->un_dp->options & ST_WORMABLE &&
3242 	    un->un_unit_attention_flags) {
3243 		un->un_read_only |= un->un_wormable(un);
3244 
3245 		if (((un->un_read_only == WORM) ||
3246 		    (un->un_read_only == RDWORM)) &&
3247 		    ((un->un_oflags & FWRITE) == FWRITE)) {
3248 			un->un_status = KEY_DATA_PROTECT;
3249 			rval = EACCES;
3250 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3251 			    "read_only = %d eof = %d oflag = %d\n",
3252 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3253 		}
3254 	}
3255 
3256 	/*
3257 	 * If we're opening the tape write-only, we need to
3258 	 * write 2 filemarks on the HP 1/2 inch drive, to
3259 	 * create a null file.
3260 	 */
3261 	if ((un->un_read_only == RDWR) ||
3262 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3263 		if (un->un_dp->options & ST_REEL) {
3264 			un->un_fmneeded = 2;
3265 		} else {
3266 			un->un_fmneeded = 1;
3267 		}
3268 	} else {
3269 		un->un_fmneeded = 0;
3270 	}
3271 
3272 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3273 	    "fmneeded = %x\n", un->un_fmneeded);
3274 
3275 	/*
3276 	 * Make sure the density can be selected correctly.
3277 	 * If WORM can only write at the append point which in most cases
3278 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3279 	 * to set and try densities if a BOP.
3280 	 */
3281 	if (st_determine_density(un,
3282 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3283 		un->un_status = KEY_ILLEGAL_REQUEST;
3284 		un->un_laststate = un->un_state;
3285 		un->un_state = ST_STATE_CLOSED;
3286 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3287 		    "st_tape_init: EIO can't determine density\n");
3288 		rval = EIO;
3289 		goto exit;
3290 	}
3291 
3292 	/*
3293 	 * Destroy the knowledge that we have 'determined'
3294 	 * density so that a later read at BOT comes along
3295 	 * does the right density determination.
3296 	 */
3297 
3298 	un->un_density_known = 0;
3299 
3300 
3301 	/*
3302 	 * Okay, the tape is loaded and either at BOT or somewhere past.
3303 	 * Mark the state such that any I/O or tape space operations
3304 	 * will get/set the right density, etc..
3305 	 */
3306 	un->un_laststate = un->un_state;
3307 	un->un_lastop = ST_OP_NIL;
3308 	un->un_mediastate = MTIO_INSERTED;
3309 	cv_broadcast(&un->un_state_cv);
3310 
3311 	/*
3312 	 *  Set test append flag if writing.
3313 	 *  First write must check that tape is positioned correctly.
3314 	 */
3315 	un->un_test_append = (un->un_oflags & FWRITE);
3316 
3317 	/*
3318 	 * if there are pending unit attention flags.
3319 	 * Check that the media has not changed.
3320 	 */
3321 	if (un->un_unit_attention_flags) {
3322 		rval = st_get_media_identification(un, st_uscsi_cmd);
3323 		if (rval != 0 && rval != EACCES) {
3324 			rval = EIO;
3325 		}
3326 		un->un_unit_attention_flags = 0;
3327 	}
3328 
3329 exit:
3330 	un->un_err_resid = 0;
3331 	un->un_last_resid = 0;
3332 	un->un_last_count = 0;
3333 
3334 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3335 	    "st_tape_init: return val = %x\n", rval);
3336 	return (rval);
3337 
3338 }
3339 
3340 
3341 
3342 /* ARGSUSED */
3343 static int
3344 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3345 {
3346 	int err = 0;
3347 	int count, last_state;
3348 	minor_t minor = getminor(dev);
3349 #ifdef	__x86
3350 	struct contig_mem *cp, *cp_temp;
3351 #endif
3352 
3353 	GET_SOFT_STATE(dev);
3354 
3355 	ST_ENTR(ST_DEVINFO, st_close);
3356 
3357 	/*
3358 	 * wait till all cmds in the pipeline have been completed
3359 	 */
3360 	mutex_enter(ST_MUTEX);
3361 
3362 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3363 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3364 
3365 	st_wait_for_io(un);
3366 
3367 	/* turn off persistent errors on close, as we want close to succeed */
3368 	st_turn_pe_off(un);
3369 
3370 	/*
3371 	 * set state to indicate that we are in process of closing
3372 	 */
3373 	last_state = un->un_laststate = un->un_state;
3374 	un->un_state = ST_STATE_CLOSING;
3375 
3376 	ST_POS(ST_DEVINFO, "st_close1:", &un->un_pos);
3377 
3378 	/*
3379 	 * BSD behavior:
3380 	 * a close always causes a silent span to the next file if we've hit
3381 	 * an EOF (but not yet read across it).
3382 	 */
3383 	if ((minor & MT_BSD) && (un->un_pos.eof == ST_EOF)) {
3384 		if (un->un_pos.pmode != invalid) {
3385 			un->un_pos.fileno++;
3386 			un->un_pos.blkno = 0;
3387 		}
3388 		un->un_pos.eof = ST_NO_EOF;
3389 	}
3390 
3391 	/*
3392 	 * SVR4 behavior for skipping to next file:
3393 	 *
3394 	 * If we have not seen a filemark, space to the next file
3395 	 *
3396 	 * If we have already seen the filemark we are physically in the next
3397 	 * file and we only increment the filenumber
3398 	 */
3399 	if (((minor & (MT_BSD | MT_NOREWIND)) == MT_NOREWIND) &&
3400 	    (flag & FREAD) &&		/* reading or at least asked to */
3401 	    (un->un_mediastate == MTIO_INSERTED) &&	/* tape loaded */
3402 	    (un->un_pos.pmode != invalid) &&		/* XXX position known */
3403 	    ((un->un_pos.blkno != 0) && 		/* inside a file */
3404 	    (un->un_lastop != ST_OP_WRITE) &&		/* Didn't just write */
3405 	    (un->un_lastop != ST_OP_WEOF))) {		/* or write filemarks */
3406 		switch (un->un_pos.eof) {
3407 		case ST_NO_EOF:
3408 			/*
3409 			 * if we were reading and did not read the complete file
3410 			 * skip to the next file, leaving the tape correctly
3411 			 * positioned to read the first record of the next file
3412 			 * Check first for REEL if we are at EOT by trying to
3413 			 * read a block
3414 			 */
3415 			if ((un->un_dp->options & ST_REEL) &&
3416 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3417 			    (un->un_pos.blkno == 0)) {
3418 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3419 					ST_DEBUG2(ST_DEVINFO, st_label,
3420 					    SCSI_DEBUG,
3421 					    "st_close : EIO can't space\n");
3422 					err = EIO;
3423 					goto error_out;
3424 				}
3425 				if (un->un_pos.eof >= ST_EOF_PENDING) {
3426 					un->un_pos.eof = ST_EOT_PENDING;
3427 					un->un_pos.fileno += 1;
3428 					un->un_pos.blkno   = 0;
3429 					break;
3430 				}
3431 			}
3432 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3433 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3434 				    "st_close: EIO can't space #2\n");
3435 				err = EIO;
3436 				goto error_out;
3437 			} else {
3438 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3439 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3440 				    un->un_pos.fileno, un->un_pos.blkno,
3441 				    un->un_pos.eof);
3442 				un->un_pos.eof = ST_NO_EOF;
3443 			}
3444 			break;
3445 
3446 		case ST_EOF_PENDING:
3447 		case ST_EOF:
3448 			un->un_pos.fileno += 1;
3449 			un->un_pos.lgclblkno += 1;
3450 			un->un_pos.blkno   = 0;
3451 			un->un_pos.eof = ST_NO_EOF;
3452 			break;
3453 
3454 		case ST_EOT:
3455 		case ST_EOT_PENDING:
3456 		case ST_EOM:
3457 			/* nothing to do */
3458 			break;
3459 		default:
3460 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
3461 			    "Undefined state 0x%x", un->un_pos.eof);
3462 
3463 		}
3464 	}
3465 
3466 
3467 	/*
3468 	 * For performance reasons (HP 88780), the driver should
3469 	 * postpone writing the second tape mark until just before a file
3470 	 * positioning ioctl is issued (e.g., rewind).	This means that
3471 	 * the user must not manually rewind the tape because the tape will
3472 	 * be missing the second tape mark which marks EOM.
3473 	 * However, this small performance improvement is not worth the risk.
3474 	 */
3475 
3476 	/*
3477 	 * We need to back up over the filemark we inadvertently popped
3478 	 * over doing a read in between the two filemarks that constitute
3479 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3480 	 * set while reading.
3481 	 *
3482 	 * If we happen to be at physical eot (ST_EOM) (writing case),
3483 	 * the writing of filemark(s) will clear the ST_EOM state, which
3484 	 * we don't want, so we save this state and restore it later.
3485 	 */
3486 
3487 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3488 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3489 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3490 
3491 	if (un->un_pos.eof == ST_EOT_PENDING) {
3492 		if (minor & MT_NOREWIND) {
3493 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3494 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3495 				    "st_close: EIO can't space #3\n");
3496 				err = EIO;
3497 				goto error_out;
3498 			} else {
3499 				un->un_pos.blkno = 0;
3500 				un->un_pos.eof = ST_EOT;
3501 			}
3502 		} else {
3503 			un->un_pos.eof = ST_NO_EOF;
3504 		}
3505 
3506 	/*
3507 	 * Do we need to write a file mark?
3508 	 *
3509 	 * only write filemarks if there are fmks to be written and
3510 	 *   - open for write (possibly read/write)
3511 	 *   - the last operation was a write
3512 	 * or:
3513 	 *   -	opened for wronly
3514 	 *   -	no data was written
3515 	 */
3516 	} else if ((un->un_pos.pmode != invalid) &&
3517 	    (un->un_fmneeded > 0) &&
3518 	    (((flag & FWRITE) &&
3519 	    ((un->un_lastop == ST_OP_WRITE)||(un->un_lastop == ST_OP_WEOF))) ||
3520 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3521 
3522 		/* save ST_EOM state */
3523 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3524 
3525 		/*
3526 		 * Note that we will write a filemark if we had opened
3527 		 * the tape write only and no data was written, thus
3528 		 * creating a null file.
3529 		 *
3530 		 * If the user already wrote one, we only have to write 1 more.
3531 		 * If they wrote two, we don't have to write any.
3532 		 */
3533 
3534 		count = un->un_fmneeded;
3535 		if (count > 0) {
3536 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, count, SYNC_CMD)) {
3537 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3538 				    "st_close : EIO can't wfm\n");
3539 				err = EIO;
3540 				goto error_out;
3541 			}
3542 			if ((un->un_dp->options & ST_REEL) &&
3543 			    (minor & MT_NOREWIND)) {
3544 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3545 					ST_DEBUG2(ST_DEVINFO, st_label,
3546 					    SCSI_DEBUG,
3547 					    "st_close : EIO space fmk(-1)\n");
3548 					err = EIO;
3549 					goto error_out;
3550 				}
3551 				un->un_pos.eof = ST_NO_EOF;
3552 				/* fix up block number */
3553 				un->un_pos.blkno = 0;
3554 			}
3555 		}
3556 
3557 		/*
3558 		 * If we aren't going to be rewinding, and we were at
3559 		 * physical eot, restore the state that indicates we
3560 		 * are at physical eot. Once you have reached physical
3561 		 * eot, and you close the tape, the only thing you can
3562 		 * do on the next open is to rewind. Access to trailer
3563 		 * records is only allowed without closing the device.
3564 		 */
3565 		if ((minor & MT_NOREWIND) == 0 && was_at_eom) {
3566 			un->un_pos.eof = ST_EOM;
3567 		}
3568 	}
3569 
3570 	/*
3571 	 * report soft errors if enabled and available, if we never accessed
3572 	 * the drive, don't get errors. This will prevent some DAT error
3573 	 * messages upon LOG SENSE.
3574 	 */
3575 	if (st_report_soft_errors_on_close &&
3576 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3577 	    (last_state != ST_STATE_OFFLINE)) {
3578 		if (st_report_soft_errors(dev, flag)) {
3579 			err = EIO;
3580 			goto error_out;
3581 		}
3582 	}
3583 
3584 
3585 	/*
3586 	 * Do we need to rewind? Can we rewind?
3587 	 */
3588 	if ((minor & MT_NOREWIND) == 0 &&
3589 	    un->un_pos.pmode != invalid && err == 0) {
3590 		/*
3591 		 * We'd like to rewind with the
3592 		 * 'immediate' bit set, but this
3593 		 * causes problems on some drives
3594 		 * where subsequent opens get a
3595 		 * 'NOT READY' error condition
3596 		 * back while the tape is rewinding,
3597 		 * which is impossible to distinguish
3598 		 * from the condition of 'no tape loaded'.
3599 		 *
3600 		 * Also, for some targets, if you disconnect
3601 		 * with the 'immediate' bit set, you don't
3602 		 * actually return right away, i.e., the
3603 		 * target ignores your request for immediate
3604 		 * return.
3605 		 *
3606 		 * Instead, we'll fire off an async rewind
3607 		 * command. We'll mark the device as closed,
3608 		 * and any subsequent open will stall on
3609 		 * the first TEST_UNIT_READY until the rewind
3610 		 * completes.
3611 		 */
3612 
3613 		/*
3614 		 * Used to be if reserve was not supported we'd send an
3615 		 * asynchronious rewind. Comments above may be slightly invalid
3616 		 * as the immediate bit was never set. Doing an immedate rewind
3617 		 * makes sense, I think fixes to not ready status might handle
3618 		 * the problems described above.
3619 		 */
3620 		if (un->un_sd->sd_inq->inq_ansi < 2) {
3621 			if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
3622 				err = EIO;
3623 			}
3624 		} else {
3625 			/* flush data for older drives per scsi spec. */
3626 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD)) {
3627 				err = EIO;
3628 			} else if (st_cmd(un, SCMD_REWIND, 1, ASYNC_CMD)) {
3629 				err = EIO;
3630 			}
3631 		}
3632 		/*
3633 		 * Setting positions invalid in case the rewind doesn't
3634 		 * happen. Drives don't like to rewind if resets happen
3635 		 * they will tend to move back to where the rewind was
3636 		 * issued if a reset or something happens so that if a
3637 		 * write happens the data doesn't get clobbered.
3638 		 *
3639 		 * Not a big deal if the position is invalid when the
3640 		 * open occures it will do a read position.
3641 		 */
3642 		un->un_pos.pmode = invalid;
3643 		un->un_running.pmode = invalid;
3644 
3645 		if (err == EIO) {
3646 			goto error_out;
3647 		}
3648 	}
3649 
3650 	/*
3651 	 * eject tape if necessary
3652 	 */
3653 	if (un->un_eject_tape_on_failure) {
3654 		un->un_eject_tape_on_failure = 0;
3655 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3656 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3657 			    "st_close : can't unload tape\n");
3658 			err = EIO;
3659 			goto error_out;
3660 		} else {
3661 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3662 			    "st_close : tape unloaded \n");
3663 			un->un_pos.eof = ST_NO_EOF;
3664 			un->un_mediastate = MTIO_EJECTED;
3665 		}
3666 	}
3667 	/*
3668 	 * Release the tape unit, if default reserve/release
3669 	 * behaviour.
3670 	 */
3671 	if ((un->un_rsvd_status &
3672 	    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
3673 		(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
3674 	}
3675 error_out:
3676 	/*
3677 	 * clear up state
3678 	 */
3679 	un->un_laststate = un->un_state;
3680 	un->un_state = ST_STATE_CLOSED;
3681 	un->un_lastop = ST_OP_NIL;
3682 	un->un_throttle = 1;	/* assume one request at time, for now */
3683 	un->un_retry_ct = 0;
3684 	un->un_errno = 0;
3685 	un->un_swr_token = (opaque_t)NULL;
3686 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3687 
3688 	/* Restore the options to the init time settings */
3689 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3690 		un->un_dp->options |= ST_READ_IGNORE_ILI;
3691 	} else {
3692 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3693 	}
3694 
3695 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3696 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3697 	} else {
3698 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3699 	}
3700 
3701 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3702 		un->un_dp->options |= ST_SHORT_FILEMARKS;
3703 	} else {
3704 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3705 	}
3706 
3707 	ASSERT(mutex_owned(ST_MUTEX));
3708 
3709 	/*
3710 	 * Signal anyone awaiting a close operation to complete.
3711 	 */
3712 	cv_signal(&un->un_clscv);
3713 
3714 	/*
3715 	 * any kind of error on closing causes all state to be tossed
3716 	 */
3717 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3718 		/*
3719 		 * note that st_intr has already set
3720 		 * un_pos.pmode to invalid.
3721 		 */
3722 		un->un_density_known = 0;
3723 	}
3724 
3725 #ifdef	__x86
3726 	/*
3727 	 * free any contiguous mem alloc'ed for big block I/O
3728 	 */
3729 	cp = un->un_contig_mem;
3730 	while (cp) {
3731 		if (cp->cm_addr) {
3732 			ddi_dma_mem_free(&cp->cm_acc_hdl);
3733 		}
3734 		cp_temp = cp;
3735 		cp = cp->cm_next;
3736 		kmem_free(cp_temp,
3737 		    sizeof (struct contig_mem) + biosize());
3738 	}
3739 	un->un_contig_mem_total_num = 0;
3740 	un->un_contig_mem_available_num = 0;
3741 	un->un_contig_mem = NULL;
3742 	un->un_max_contig_mem_len = 0;
3743 #endif
3744 
3745 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3746 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3747 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3748 
3749 	mutex_exit(ST_MUTEX);
3750 	return (err);
3751 }
3752 
3753 /*
3754  * These routines perform raw i/o operations.
3755  */
3756 
3757 /* ARGSUSED2 */
3758 static int
3759 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3760 {
3761 #ifdef STDEBUG
3762 	GET_SOFT_STATE(dev);
3763 	ST_ENTR(ST_DEVINFO, st_aread);
3764 #endif
3765 	return (st_arw(dev, aio, B_READ));
3766 }
3767 
3768 
3769 /* ARGSUSED2 */
3770 static int
3771 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3772 {
3773 #ifdef STDEBUG
3774 	GET_SOFT_STATE(dev);
3775 	ST_ENTR(ST_DEVINFO, st_awrite);
3776 #endif
3777 	return (st_arw(dev, aio, B_WRITE));
3778 }
3779 
3780 
3781 
3782 /* ARGSUSED */
3783 static int
3784 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3785 {
3786 #ifdef STDEBUG
3787 	GET_SOFT_STATE(dev);
3788 	ST_ENTR(ST_DEVINFO, st_read);
3789 #endif
3790 	return (st_rw(dev, uiop, B_READ));
3791 }
3792 
3793 /* ARGSUSED */
3794 static int
3795 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3796 {
3797 #ifdef STDEBUG
3798 	GET_SOFT_STATE(dev);
3799 	ST_ENTR(ST_DEVINFO, st_write);
3800 #endif
3801 	return (st_rw(dev, uiop, B_WRITE));
3802 }
3803 
3804 /*
3805  * Due to historical reasons, old limits are: For variable-length devices:
3806  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3807  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3808  * (let it through unmodified. For fixed-length record devices:
3809  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3810  *
3811  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3812  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3813  * command to the drive).
3814  *
3815  */
3816 static void
3817 st_minphys(struct buf *bp)
3818 {
3819 	struct scsi_tape *un;
3820 
3821 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3822 
3823 	ST_FUNC(ST_DEVINFO, st_minphys);
3824 
3825 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3826 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3827 	    bp->b_bcount);
3828 
3829 	if (un->un_allow_large_xfer) {
3830 
3831 		/*
3832 		 * check un_maxbsize for variable length devices only
3833 		 */
3834 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3835 			bp->b_bcount = un->un_maxbsize;
3836 		}
3837 		/*
3838 		 * can't go more that HBA maxdma limit in either fixed-length
3839 		 * or variable-length tape drives.
3840 		 */
3841 		if (bp->b_bcount > un->un_maxdma) {
3842 			bp->b_bcount = un->un_maxdma;
3843 		}
3844 	} else {
3845 
3846 		/*
3847 		 *  use old fixed limits
3848 		 */
3849 		if (un->un_bsize == 0) {
3850 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3851 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3852 			}
3853 		} else {
3854 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3855 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3856 			}
3857 		}
3858 	}
3859 
3860 	/*
3861 	 * For regular raw I/O and Fixed Block length devices, make sure
3862 	 * the adjusted block count is a whole multiple of the device
3863 	 * block size.
3864 	 */
3865 	if (bp != un->un_sbufp && un->un_bsize) {
3866 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3867 	}
3868 }
3869 
3870 static int
3871 st_rw(dev_t dev, struct uio *uio, int flag)
3872 {
3873 	int rval = 0;
3874 	long len;
3875 
3876 	GET_SOFT_STATE(dev);
3877 
3878 	ST_FUNC(ST_DEVINFO, st_rw);
3879 
3880 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3881 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3882 	    (flag == B_READ ? rd_str: wr_str));
3883 
3884 	/* get local copy of transfer length */
3885 	len = uio->uio_iov->iov_len;
3886 
3887 	mutex_enter(ST_MUTEX);
3888 
3889 	/*
3890 	 * Clear error entry stack
3891 	 */
3892 	st_empty_error_stack(un);
3893 
3894 	/*
3895 	 * If in fixed block size mode and requested read or write
3896 	 * is not an even multiple of that block size.
3897 	 */
3898 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3899 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3900 		    "%s: not modulo %d block size\n",
3901 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3902 		rval = EINVAL;
3903 	}
3904 
3905 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3906 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3907 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3908 		    "%s: not modulo %d device granularity\n",
3909 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3910 		rval = EINVAL;
3911 	}
3912 
3913 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
3914 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
3915 		rval = EFAULT;
3916 	}
3917 
3918 	if (rval != 0) {
3919 		un->un_errno = rval;
3920 		mutex_exit(ST_MUTEX);
3921 		return (rval);
3922 	}
3923 
3924 	/*
3925 	 * Reset this so it can be set if Berkeley and read over a filemark.
3926 	 */
3927 	un->un_silent_skip = 0;
3928 	mutex_exit(ST_MUTEX);
3929 
3930 	len = uio->uio_resid;
3931 
3932 	rval = physio(st_queued_strategy, (struct buf *)NULL,
3933 	    dev, flag, st_minphys, uio);
3934 	/*
3935 	 * if we have hit logical EOT during this xfer and there is not a
3936 	 * full residue, then set eof back  to ST_EOM to make sure that
3937 	 * the user will see at least one zero write
3938 	 * after this short write
3939 	 */
3940 	mutex_enter(ST_MUTEX);
3941 	if (un->un_pos.eof > ST_NO_EOF) {
3942 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3943 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3944 	}
3945 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3946 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3947 			un->un_pos.eof = ST_EOM;
3948 		} else if (uio->uio_resid == len) {
3949 			un->un_pos.eof = ST_NO_EOF;
3950 		}
3951 	}
3952 
3953 	if (un->un_silent_skip && uio->uio_resid != len) {
3954 		un->un_pos.eof = ST_EOF;
3955 		un->un_pos.blkno = un->un_save_blkno;
3956 		un->un_pos.fileno--;
3957 	}
3958 
3959 	un->un_errno = rval;
3960 
3961 	mutex_exit(ST_MUTEX);
3962 
3963 	return (rval);
3964 }
3965 
3966 static int
3967 st_arw(dev_t dev, struct aio_req *aio, int flag)
3968 {
3969 	struct uio *uio = aio->aio_uio;
3970 	int rval = 0;
3971 	long len;
3972 
3973 	GET_SOFT_STATE(dev);
3974 
3975 	ST_FUNC(ST_DEVINFO, st_arw);
3976 
3977 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3978 	    "st_arw(dev = 0x%lx, flag = %s)\n", dev,
3979 	    (flag == B_READ ? rd_str: wr_str));
3980 
3981 	/* get local copy of transfer length */
3982 	len = uio->uio_iov->iov_len;
3983 
3984 	mutex_enter(ST_MUTEX);
3985 
3986 	/*
3987 	 * If in fixed block size mode and requested read or write
3988 	 * is not an even multiple of that block size.
3989 	 */
3990 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3991 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3992 		    "%s: not modulo %d block size\n",
3993 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3994 		rval = EINVAL;
3995 	}
3996 
3997 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3998 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3999 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4000 		    "%s: not modulo %d device granularity\n",
4001 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
4002 		rval = EINVAL;
4003 	}
4004 
4005 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
4006 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
4007 		rval = EFAULT;
4008 	}
4009 
4010 	if (rval != 0) {
4011 		un->un_errno = rval;
4012 		mutex_exit(ST_MUTEX);
4013 		return (rval);
4014 	}
4015 
4016 	mutex_exit(ST_MUTEX);
4017 
4018 	len = uio->uio_resid;
4019 
4020 	rval =
4021 	    aphysio(st_queued_strategy, anocancel, dev, flag, st_minphys, aio);
4022 
4023 	/*
4024 	 * if we have hit logical EOT during this xfer and there is not a
4025 	 * full residue, then set eof back  to ST_EOM to make sure that
4026 	 * the user will see at least one zero write
4027 	 * after this short write
4028 	 *
4029 	 * we keep this here just in case the application is not using
4030 	 * persistent errors
4031 	 */
4032 	mutex_enter(ST_MUTEX);
4033 	if (un->un_pos.eof > ST_NO_EOF) {
4034 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4035 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
4036 	}
4037 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
4038 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
4039 			un->un_pos.eof = ST_EOM;
4040 		} else if (uio->uio_resid == len &&
4041 		    !(un->un_persistence && un->un_persist_errors)) {
4042 			un->un_pos.eof = ST_NO_EOF;
4043 		}
4044 	}
4045 	un->un_errno = rval;
4046 	mutex_exit(ST_MUTEX);
4047 
4048 	return (rval);
4049 }
4050 
4051 
4052 
4053 static int
4054 st_queued_strategy(buf_t *bp)
4055 {
4056 	struct scsi_tape *un;
4057 	char reading = bp->b_flags & B_READ;
4058 	int wasopening = 0;
4059 
4060 	/*
4061 	 * validate arguments
4062 	 */
4063 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4064 	if (un == NULL) {
4065 		bp->b_resid = bp->b_bcount;
4066 		bioerror(bp, ENXIO);
4067 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4068 		    "st_queued_strategy: ENXIO error exit\n");
4069 		biodone(bp);
4070 		return (0);
4071 	}
4072 
4073 	ST_ENTR(ST_DEVINFO, st_queued_strategy);
4074 
4075 	mutex_enter(ST_MUTEX);
4076 
4077 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4078 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4079 	}
4080 
4081 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4082 	    "st_queued_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4083 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4084 
4085 	/*
4086 	 * If persistent errors have been flagged, just nix this one. We wait
4087 	 * for any outstanding I/O's below, so we will be in order.
4088 	 */
4089 	if (un->un_persistence && un->un_persist_errors) {
4090 		goto exit;
4091 	}
4092 
4093 	/*
4094 	 * If last command was non queued, wait till it finishes.
4095 	 */
4096 	while (un->un_sbuf_busy) {
4097 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
4098 		/* woke up because of an error */
4099 		if (un->un_persistence && un->un_persist_errors) {
4100 			goto exit;
4101 		}
4102 	}
4103 
4104 	/*
4105 	 * s_buf and recovery commands shouldn't come here.
4106 	 */
4107 	ASSERT(bp != un->un_recov_buf);
4108 	ASSERT(bp != un->un_sbufp);
4109 
4110 	/*
4111 	 * If we haven't done/checked reservation on the tape unit
4112 	 * do it now.
4113 	 */
4114 	if ((un->un_rsvd_status &
4115 	    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
4116 		if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
4117 			if (st_reserve_release(un, ST_RESERVE, st_uscsi_cmd)) {
4118 				st_bioerror(bp, un->un_errno);
4119 				goto exit;
4120 			}
4121 		} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4122 			/*
4123 			 * Enter here to restore position for possible
4124 			 * resets when the device was closed and opened
4125 			 * in O_NDELAY mode subsequently
4126 			 */
4127 			un->un_state = ST_STATE_INITIALIZING;
4128 			(void) st_cmd(un, SCMD_TEST_UNIT_READY,
4129 			    0, SYNC_CMD);
4130 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4131 		}
4132 		un->un_rsvd_status |= ST_INIT_RESERVE;
4133 	}
4134 
4135 	/*
4136 	 * If we are offline, we have to initialize everything first.
4137 	 * This is to handle either when opened with O_NDELAY, or
4138 	 * we just got a new tape in the drive, after an offline.
4139 	 * We don't observe O_NDELAY past the open,
4140 	 * as it will not make sense for tapes.
4141 	 */
4142 	if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
4143 		/*
4144 		 * reset state to avoid recursion
4145 		 */
4146 		un->un_laststate = un->un_state;
4147 		un->un_state = ST_STATE_INITIALIZING;
4148 		if (st_tape_init(un)) {
4149 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4150 			    "stioctl : OFFLINE init failure ");
4151 			un->un_state = ST_STATE_OFFLINE;
4152 			un->un_pos.pmode = invalid;
4153 			goto b_done_err;
4154 		}
4155 		/* un_restore_pos make invalid */
4156 		un->un_state = ST_STATE_OPEN_PENDING_IO;
4157 		un->un_restore_pos = 0;
4158 	}
4159 	/*
4160 	 * Check for legal operations
4161 	 */
4162 	if (un->un_pos.pmode == invalid) {
4163 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4164 		    "strategy with un->un_pos.pmode invalid\n");
4165 		goto b_done_err;
4166 	}
4167 
4168 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4169 	    "st_queued_strategy(): regular io\n");
4170 
4171 	/*
4172 	 * Process this first. If we were reading, and we're pending
4173 	 * logical eot, that means we've bumped one file mark too far.
4174 	 */
4175 
4176 	/*
4177 	 * Recursion warning: st_cmd will route back through here.
4178 	 * Not anymore st_cmd will go through st_strategy()!
4179 	 */
4180 	if (un->un_pos.eof == ST_EOT_PENDING) {
4181 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4182 			un->un_pos.pmode = invalid;
4183 			un->un_density_known = 0;
4184 			goto b_done_err;
4185 		}
4186 		un->un_pos.blkno = 0; /* fix up block number.. */
4187 		un->un_pos.eof = ST_EOT;
4188 	}
4189 
4190 	/*
4191 	 * If we are in the process of opening, we may have to
4192 	 * determine/set the correct density. We also may have
4193 	 * to do a test_append (if QIC) to see whether we are
4194 	 * in a position to append to the end of the tape.
4195 	 *
4196 	 * If we're already at logical eot, we transition
4197 	 * to ST_NO_EOF. If we're at physical eot, we punt
4198 	 * to the switch statement below to handle.
4199 	 */
4200 	if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
4201 	    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
4202 
4203 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4204 			if (st_determine_density(un, (int)reading)) {
4205 				goto b_done_err;
4206 			}
4207 		}
4208 
4209 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4210 		    "pending_io@fileno %d rw %d qic %d eof %d\n",
4211 		    un->un_pos.fileno, (int)reading,
4212 		    (un->un_dp->options & ST_QIC) ? 1 : 0,
4213 		    un->un_pos.eof);
4214 
4215 		if (!reading && un->un_pos.eof != ST_EOM) {
4216 			if (un->un_pos.eof == ST_EOT) {
4217 				un->un_pos.eof = ST_NO_EOF;
4218 			} else if (un->un_pos.pmode != invalid &&
4219 			    (un->un_dp->options & ST_QIC)) {
4220 				/*
4221 				 * st_test_append() will do it all
4222 				 */
4223 				st_test_append(bp);
4224 				mutex_exit(ST_MUTEX);
4225 				return (0);
4226 			}
4227 		}
4228 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4229 			wasopening = 1;
4230 		}
4231 		un->un_laststate = un->un_state;
4232 		un->un_state = ST_STATE_OPEN;
4233 	}
4234 
4235 
4236 	/*
4237 	 * Process rest of END OF FILE and END OF TAPE conditions
4238 	 */
4239 
4240 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4241 	    "eof=%x, wasopening=%x\n",
4242 	    un->un_pos.eof, wasopening);
4243 
4244 	switch (un->un_pos.eof) {
4245 	case ST_EOM:
4246 		/*
4247 		 * This allows writes to proceed past physical
4248 		 * eot. We'll *really* be in trouble if the
4249 		 * user continues blindly writing data too
4250 		 * much past this point (unwind the tape).
4251 		 * Physical eot really means 'early warning
4252 		 * eot' in this context.
4253 		 *
4254 		 * Every other write from now on will succeed
4255 		 * (if sufficient  tape left).
4256 		 * This write will return with resid == count
4257 		 * but the next one should be successful
4258 		 *
4259 		 * Note that we only transition to logical EOT
4260 		 * if the last state wasn't the OPENING state.
4261 		 * We explicitly prohibit running up to physical
4262 		 * eot, closing the device, and then re-opening
4263 		 * to proceed. Trailer records may only be gotten
4264 		 * at by keeping the tape open after hitting eot.
4265 		 *
4266 		 * Also note that ST_EOM cannot be set by reading-
4267 		 * this can only be set during writing. Reading
4268 		 * up to the end of the tape gets a blank check
4269 		 * or a double-filemark indication (ST_EOT_PENDING),
4270 		 * and we prohibit reading after that point.
4271 		 *
4272 		 */
4273 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
4274 		if (wasopening == 0) {
4275 			/*
4276 			 * this allows st_rw() to reset it back to
4277 			 * will see a zero write
4278 			 */
4279 			un->un_pos.eof = ST_WRITE_AFTER_EOM;
4280 		}
4281 		un->un_status = SUN_KEY_EOT;
4282 		goto b_done;
4283 
4284 	case ST_WRITE_AFTER_EOM:
4285 	case ST_EOT:
4286 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
4287 		un->un_status = SUN_KEY_EOT;
4288 		if (SVR4_BEHAVIOR && reading) {
4289 			goto b_done_err;
4290 		}
4291 
4292 		if (reading) {
4293 			goto b_done;
4294 		}
4295 		un->un_pos.eof = ST_NO_EOF;
4296 		break;
4297 
4298 	case ST_EOF_PENDING:
4299 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4300 		    "EOF PENDING\n");
4301 		un->un_status = SUN_KEY_EOF;
4302 		if (SVR4_BEHAVIOR) {
4303 			un->un_pos.eof = ST_EOF;
4304 			goto b_done;
4305 		}
4306 		/* FALLTHROUGH */
4307 	case ST_EOF:
4308 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
4309 		un->un_status = SUN_KEY_EOF;
4310 		if (SVR4_BEHAVIOR) {
4311 			goto b_done_err;
4312 		}
4313 
4314 		if (BSD_BEHAVIOR) {
4315 			un->un_pos.eof = ST_NO_EOF;
4316 			un->un_pos.fileno += 1;
4317 			un->un_pos.blkno   = 0;
4318 		}
4319 
4320 		if (reading) {
4321 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4322 			    "now file %d (read)\n",
4323 			    un->un_pos.fileno);
4324 			goto b_done;
4325 		}
4326 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4327 		    "now file %d (write)\n", un->un_pos.fileno);
4328 		break;
4329 	default:
4330 		un->un_status = 0;
4331 		break;
4332 	}
4333 
4334 	bp->b_flags &= ~(B_DONE);
4335 	st_bioerror(bp, 0);
4336 	bp->av_forw = NULL;
4337 	bp->b_resid = 0;
4338 	SET_BP_PKT(bp, 0);
4339 
4340 
4341 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4342 	    "st_queued_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4343 	    " pkt=0x%p\n",
4344 	    (void *)bp->b_forw, bp->b_bcount,
4345 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4346 
4347 #ifdef	__x86
4348 	/*
4349 	 * We will replace bp with a new bp that can do big blk xfer
4350 	 * if the requested xfer size is bigger than un->un_maxdma_arch
4351 	 *
4352 	 * Also, we need to make sure that we're handling real I/O
4353 	 * by checking group 0/1 SCSI I/O commands, if needed
4354 	 */
4355 	if (bp->b_bcount > un->un_maxdma_arch &&
4356 	    ((uchar_t)(uintptr_t)bp->b_forw == SCMD_READ ||
4357 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G4 ||
4358 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE ||
4359 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G4)) {
4360 		mutex_exit(ST_MUTEX);
4361 		bp = st_get_bigblk_bp(bp);
4362 		mutex_enter(ST_MUTEX);
4363 	}
4364 #endif
4365 
4366 	/* put on wait queue */
4367 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4368 	    "st_queued_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4369 	    (void *)un->un_quef, (void *)bp);
4370 
4371 	st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quel, bp);
4372 
4373 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4374 
4375 	st_start(un);
4376 
4377 	mutex_exit(ST_MUTEX);
4378 	return (0);
4379 
4380 b_done_err:
4381 	st_bioerror(bp, EIO);
4382 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4383 	    "st_queued_strategy : EIO b_done_err\n");
4384 
4385 b_done:
4386 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4387 	    "st_queued_strategy: b_done\n");
4388 
4389 exit:
4390 	/*
4391 	 * make sure no commands are outstanding or waiting before closing,
4392 	 * so we can guarantee order
4393 	 */
4394 	st_wait_for_io(un);
4395 	un->un_err_resid = bp->b_resid = bp->b_bcount;
4396 
4397 	/* override errno here, if persistent errors were flagged */
4398 	if (un->un_persistence && un->un_persist_errors)
4399 		bioerror(bp, un->un_errno);
4400 
4401 	mutex_exit(ST_MUTEX);
4402 
4403 	biodone(bp);
4404 	ASSERT(mutex_owned(ST_MUTEX) == 0);
4405 	return (0);
4406 }
4407 
4408 
4409 static int
4410 st_strategy(struct buf *bp)
4411 {
4412 	struct scsi_tape *un;
4413 
4414 	/*
4415 	 * validate arguments
4416 	 */
4417 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4418 	if (un == NULL) {
4419 		bp->b_resid = bp->b_bcount;
4420 		bioerror(bp, ENXIO);
4421 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4422 		    "st_strategy: ENXIO error exit\n");
4423 
4424 		biodone(bp);
4425 		return (0);
4426 
4427 	}
4428 
4429 	ST_ENTR(ST_DEVINFO, st_strategy);
4430 
4431 	mutex_enter(ST_MUTEX);
4432 
4433 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4434 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4435 	}
4436 
4437 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4438 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4439 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4440 
4441 	ASSERT((bp == un->un_recov_buf) || (bp == un->un_sbufp));
4442 
4443 	bp->b_flags &= ~(B_DONE);
4444 	st_bioerror(bp, 0);
4445 	bp->av_forw = NULL;
4446 	bp->b_resid = 0;
4447 	SET_BP_PKT(bp, 0);
4448 
4449 
4450 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4451 	    "st_strategy: cmd=0x%x  count=%ld  resid=%ld flags=0x%x"
4452 	    " pkt=0x%p\n",
4453 	    (unsigned char)(uintptr_t)bp->b_forw, bp->b_bcount,
4454 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4455 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4456 
4457 	st_start(un);
4458 
4459 	mutex_exit(ST_MUTEX);
4460 	return (0);
4461 }
4462 
4463 /*
4464  * this routine spaces forward over filemarks
4465  */
4466 static int
4467 st_space_fmks(struct scsi_tape *un, int64_t count)
4468 {
4469 	int rval = 0;
4470 
4471 	ST_FUNC(ST_DEVINFO, st_space_fmks);
4472 
4473 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4474 	    "st_space_fmks(dev = 0x%lx, count = %"PRIx64")\n",
4475 	    un->un_dev, count);
4476 
4477 	ASSERT(mutex_owned(ST_MUTEX));
4478 
4479 	/*
4480 	 * the risk with doing only one space operation is that we
4481 	 * may accidentily jump in old data
4482 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4483 	 * because the 8200 does not append a marker; in order not to
4484 	 * sacrifice the fast file skip, we do a slow skip if the low
4485 	 * density device has been opened
4486 	 */
4487 
4488 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4489 	    !((un->un_dp->type == ST_TYPE_EXB8500 &&
4490 	    MT_DENSITY(un->un_dev) == 0))) {
4491 		if (st_cmd(un, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4492 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4493 			    "space_fmks : EIO can't do space cmd #1\n");
4494 			rval = EIO;
4495 		}
4496 	} else {
4497 		while (count > 0) {
4498 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4499 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4500 				    "space_fmks : EIO can't do space cmd #2\n");
4501 				rval = EIO;
4502 				break;
4503 			}
4504 			count -= 1;
4505 			/*
4506 			 * read a block to see if we have reached
4507 			 * end of medium (double filemark for reel or
4508 			 * medium error for others)
4509 			 */
4510 			if (count > 0) {
4511 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
4512 					ST_DEBUG2(ST_DEVINFO, st_label,
4513 					    SCSI_DEBUG,
4514 					    "space_fmks : EIO can't do "
4515 					    "space cmd #3\n");
4516 					rval = EIO;
4517 					break;
4518 				}
4519 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4520 				    (un->un_dp->options & ST_REEL)) {
4521 					un->un_status = SUN_KEY_EOT;
4522 					ST_DEBUG2(ST_DEVINFO, st_label,
4523 					    SCSI_DEBUG,
4524 					    "space_fmks : EIO ST_REEL\n");
4525 					rval = EIO;
4526 					break;
4527 				} else if (IN_EOF(un->un_pos)) {
4528 					un->un_pos.eof = ST_NO_EOF;
4529 					un->un_pos.fileno++;
4530 					un->un_pos.blkno = 0;
4531 					count--;
4532 				} else if (un->un_pos.eof > ST_EOF) {
4533 					ST_DEBUG2(ST_DEVINFO, st_label,
4534 					    SCSI_DEBUG,
4535 					    "space_fmks, EIO > ST_EOF\n");
4536 					rval = EIO;
4537 					break;
4538 				}
4539 
4540 			}
4541 		}
4542 		un->un_err_resid = count;
4543 		COPY_POS(&un->un_pos, &un->un_err_pos);
4544 	}
4545 	ASSERT(mutex_owned(ST_MUTEX));
4546 	return (rval);
4547 }
4548 
4549 /*
4550  * this routine spaces to EOD
4551  *
4552  * it keeps track of the current filenumber and returns the filenumber after
4553  * the last successful space operation, we keep the number high because as
4554  * tapes are getting larger, the possibility of more and more files exist,
4555  * 0x100000 (1 Meg of files) probably will never have to be changed any time
4556  * soon
4557  */
4558 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4559 
4560 static int
4561 st_find_eod(struct scsi_tape *un)
4562 {
4563 	tapepos_t savepos;
4564 	int64_t sp_type;
4565 	int result;
4566 
4567 	if (un == NULL) {
4568 		return (-1);
4569 	}
4570 
4571 	ST_FUNC(ST_DEVINFO, st_find_eod);
4572 
4573 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4574 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", un->un_dev,
4575 	    un->un_pos.fileno);
4576 
4577 	ASSERT(mutex_owned(ST_MUTEX));
4578 
4579 	COPY_POS(&savepos, &un->un_pos);
4580 
4581 	/*
4582 	 * see if the drive is smart enough to do the skips in
4583 	 * one operation; 1/2" use two filemarks
4584 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4585 	 * because the 8200 does not append a marker; in order not to
4586 	 * sacrifice the fast file skip, we do a slow skip if the low
4587 	 * density device has been opened
4588 	 */
4589 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4590 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4591 		    (MT_DENSITY(un->un_dev) == 0)) {
4592 			sp_type = Fmk(1);
4593 		} else if (un->un_pos.pmode == logical) {
4594 			sp_type = SPACE(SP_EOD, 0);
4595 		} else {
4596 			sp_type = Fmk(MAX_SKIP);
4597 		}
4598 	} else {
4599 		sp_type = Fmk(1);
4600 	}
4601 
4602 	for (;;) {
4603 		result = st_cmd(un, SCMD_SPACE, sp_type, SYNC_CMD);
4604 
4605 		if (result == 0) {
4606 			COPY_POS(&savepos, &un->un_pos);
4607 		}
4608 
4609 		if (sp_type == SPACE(SP_EOD, 0)) {
4610 			if (result != 0) {
4611 				sp_type = Fmk(MAX_SKIP);
4612 				continue;
4613 			}
4614 
4615 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4616 			    "st_find_eod: 0x%"PRIx64"\n",
4617 			    savepos.lgclblkno);
4618 			/*
4619 			 * What we return will become the current file position.
4620 			 * After completing the space command with the position
4621 			 * mode that is not invalid a read position command will
4622 			 * be automaticly issued. If the drive support the long
4623 			 * read position format a valid file position can be
4624 			 * returned.
4625 			 */
4626 			return (un->un_pos.fileno);
4627 		}
4628 
4629 		if (result != 0) {
4630 			break;
4631 		}
4632 
4633 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4634 		    "count=%"PRIx64", eof=%x, status=%x\n",
4635 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4636 
4637 		/*
4638 		 * If we're not EOM smart,  space a record
4639 		 * to see whether we're now in the slot between
4640 		 * the two sequential filemarks that logical
4641 		 * EOM consists of (REEL) or hit nowhere land
4642 		 * (8mm).
4643 		 */
4644 		if (sp_type == Fmk(1)) {
4645 			/*
4646 			 * no fast skipping, check a record
4647 			 */
4648 			if (st_cmd(un, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4649 				break;
4650 			}
4651 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4652 			    (un->un_dp->options & ST_REEL)) {
4653 				un->un_status = KEY_BLANK_CHECK;
4654 				un->un_pos.fileno++;
4655 				un->un_pos.blkno = 0;
4656 				break;
4657 			}
4658 			if (IN_EOF(un->un_pos)) {
4659 				un->un_pos.eof = ST_NO_EOF;
4660 				un->un_pos.fileno++;
4661 				un->un_pos.blkno = 0;
4662 			}
4663 			if (un->un_pos.eof > ST_EOF) {
4664 				break;
4665 			}
4666 		} else {
4667 			if (un->un_pos.eof > ST_EOF) {
4668 				break;
4669 			}
4670 		}
4671 	}
4672 
4673 	if (un->un_dp->options & ST_KNOWS_EOD) {
4674 		COPY_POS(&savepos, &un->un_pos);
4675 	}
4676 
4677 	ASSERT(mutex_owned(ST_MUTEX));
4678 
4679 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4680 	    "st_find_eod: %x\n", savepos.fileno);
4681 	return (savepos.fileno);
4682 }
4683 
4684 
4685 /*
4686  * this routine is frequently used in ioctls below;
4687  * it determines whether we know the density and if not will
4688  * determine it
4689  * if we have written the tape before, one or more filemarks are written
4690  *
4691  * depending on the stepflag, the head is repositioned to where it was before
4692  * the filemarks were written in order not to confuse step counts
4693  */
4694 #define	STEPBACK    0
4695 #define	NO_STEPBACK 1
4696 
4697 static int
4698 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4699 {
4700 
4701 	GET_SOFT_STATE(dev);
4702 
4703 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4704 
4705 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4706 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4707 	    "\n", dev, wfm, mode, stepflag);
4708 
4709 	ASSERT(mutex_owned(ST_MUTEX));
4710 
4711 	/*
4712 	 * If we don't yet know the density of the tape we have inserted,
4713 	 * we have to either unconditionally set it (if we're 'writing'),
4714 	 * or we have to determine it. As side effects, check for any
4715 	 * write-protect errors, and for the need to put out any file-marks
4716 	 * before positioning a tape.
4717 	 *
4718 	 * If we are going to be spacing forward, and we haven't determined
4719 	 * the tape density yet, we have to do so now...
4720 	 */
4721 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4722 		if (st_determine_density(un, mode)) {
4723 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4724 			    "check_density_or_wfm : EIO can't determine "
4725 			    "density\n");
4726 			un->un_errno = EIO;
4727 			return (EIO);
4728 		}
4729 		/*
4730 		 * Presumably we are at BOT. If we attempt to write, it will
4731 		 * either work okay, or bomb. We don't do a st_test_append
4732 		 * unless we're past BOT.
4733 		 */
4734 		un->un_laststate = un->un_state;
4735 		un->un_state = ST_STATE_OPEN;
4736 
4737 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4738 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4739 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4740 
4741 		tapepos_t spos;
4742 
4743 		COPY_POS(&spos, &un->un_pos);
4744 
4745 		/*
4746 		 * We need to write one or two filemarks.
4747 		 * In the case of the HP, we need to
4748 		 * position the head between the two
4749 		 * marks.
4750 		 */
4751 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4752 			wfm = un->un_fmneeded;
4753 			un->un_fmneeded = 0;
4754 		}
4755 
4756 		if (st_write_fm(dev, wfm)) {
4757 			un->un_pos.pmode = invalid;
4758 			un->un_density_known = 0;
4759 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4760 			    "check_density_or_wfm : EIO can't write fm\n");
4761 			un->un_errno = EIO;
4762 			return (EIO);
4763 		}
4764 
4765 		if (stepflag == STEPBACK) {
4766 			if (st_cmd(un, SCMD_SPACE, Fmk(-wfm), SYNC_CMD)) {
4767 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4768 				    "check_density_or_wfm : EIO can't space "
4769 				    "(-wfm)\n");
4770 				un->un_errno = EIO;
4771 				return (EIO);
4772 			}
4773 			COPY_POS(&un->un_pos, &spos);
4774 		}
4775 	}
4776 
4777 	/*
4778 	 * Whatever we do at this point clears the state of the eof flag.
4779 	 */
4780 
4781 	un->un_pos.eof = ST_NO_EOF;
4782 
4783 	/*
4784 	 * If writing, let's check that we're positioned correctly
4785 	 * at the end of tape before issuing the next write.
4786 	 */
4787 	if (un->un_read_only == RDWR) {
4788 		un->un_test_append = 1;
4789 	}
4790 
4791 	ASSERT(mutex_owned(ST_MUTEX));
4792 	return (0);
4793 }
4794 
4795 
4796 /*
4797  * Wait for all outstaning I/O's to complete
4798  *
4799  * we wait on both ncmds and the wait queue for times when we are flushing
4800  * after persistent errors are flagged, which is when ncmds can be 0, and the
4801  * queue can still have I/O's.  This way we preserve order of biodone's.
4802  */
4803 static void
4804 st_wait_for_io(struct scsi_tape *un)
4805 {
4806 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4807 	ASSERT(mutex_owned(ST_MUTEX));
4808 	while ((un->un_ncmds) || (un->un_quef) || (un->un_runqf)) {
4809 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4810 	}
4811 }
4812 
4813 /*
4814  * This routine implements the ioctl calls.  It is called
4815  * from the device switch at normal priority.
4816  */
4817 /*ARGSUSED*/
4818 static int
4819 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4820     int *rval_p)
4821 {
4822 	int tmp, rval = 0;
4823 
4824 	GET_SOFT_STATE(dev);
4825 
4826 	ST_ENTR(ST_DEVINFO, st_ioctl);
4827 
4828 	mutex_enter(ST_MUTEX);
4829 
4830 	ASSERT(un->un_recov_buf_busy == 0);
4831 
4832 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4833 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4834 	    "pe_flag = %d\n",
4835 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4836 	    un->un_persistence && un->un_persist_errors);
4837 
4838 	/*
4839 	 * We don't want to block on these, so let them through
4840 	 * and we don't care about setting driver states here.
4841 	 */
4842 	if ((cmd == MTIOCGETDRIVETYPE) ||
4843 	    (cmd == MTIOCGUARANTEEDORDER) ||
4844 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4845 		goto check_commands;
4846 	}
4847 
4848 	/*
4849 	 * We clear error entry stack except command
4850 	 * MTIOCGETERROR and MTIOCGET
4851 	 */
4852 	if ((cmd != MTIOCGETERROR) &&
4853 	    (cmd != MTIOCGET)) {
4854 		st_empty_error_stack(un);
4855 	}
4856 
4857 	/*
4858 	 * wait for all outstanding commands to complete, or be dequeued.
4859 	 * And because ioctl's are synchronous commands, any return value
4860 	 * after this,  will be in order
4861 	 */
4862 	st_wait_for_io(un);
4863 
4864 	/*
4865 	 * allow only a through clear errors and persistent status, and
4866 	 * status
4867 	 */
4868 	if (un->un_persistence && un->un_persist_errors) {
4869 		if ((cmd == MTIOCLRERR) ||
4870 		    (cmd == MTIOCPERSISTENT) ||
4871 		    (cmd == MTIOCGET)) {
4872 			goto check_commands;
4873 		} else {
4874 			rval = un->un_errno;
4875 			goto exit;
4876 		}
4877 	}
4878 
4879 	ASSERT(un->un_throttle != 0);
4880 	un->un_throttle = 1;	/* > 1 will never happen here */
4881 	un->un_errno = 0;	/* start clean from here */
4882 
4883 	/*
4884 	 * first and foremost, handle any ST_EOT_PENDING cases.
4885 	 * That is, if a logical eot is pending notice, notice it.
4886 	 */
4887 	if (un->un_pos.eof == ST_EOT_PENDING) {
4888 		int resid = un->un_err_resid;
4889 		uchar_t status = un->un_status;
4890 		uchar_t lastop = un->un_lastop;
4891 
4892 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4893 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4894 			    "stioctl : EIO can't space fmk(-1)\n");
4895 			rval = EIO;
4896 			goto exit;
4897 		}
4898 		un->un_lastop = lastop; /* restore last operation */
4899 		if (status == SUN_KEY_EOF) {
4900 			un->un_status = SUN_KEY_EOT;
4901 		} else {
4902 			un->un_status = status;
4903 		}
4904 		un->un_err_resid  = resid;
4905 		/* fix up block number */
4906 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4907 		/* now we're at logical eot */
4908 		un->un_pos.eof = ST_EOT;
4909 	}
4910 
4911 	/*
4912 	 * now, handle the rest of the situations
4913 	 */
4914 check_commands:
4915 	switch (cmd) {
4916 	case MTIOCGET:
4917 	{
4918 #ifdef _MULTI_DATAMODEL
4919 		/*
4920 		 * For use when a 32 bit app makes a call into a
4921 		 * 64 bit ioctl
4922 		 */
4923 		struct mtget32		mtg_local32;
4924 		struct mtget32 		*mtget_32 = &mtg_local32;
4925 #endif /* _MULTI_DATAMODEL */
4926 
4927 			/* Get tape status */
4928 		struct mtget mtg_local;
4929 		struct mtget *mtget = &mtg_local;
4930 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4931 		    "st_ioctl: MTIOCGET\n");
4932 
4933 		bzero((caddr_t)mtget, sizeof (struct mtget));
4934 		mtget->mt_erreg = un->un_status;
4935 		mtget->mt_resid = un->un_err_resid;
4936 		mtget->mt_dsreg = un->un_retry_ct;
4937 		if (un->un_err_pos.pmode == legacy) {
4938 			mtget->mt_fileno = un->un_err_pos.fileno;
4939 		} else {
4940 			mtget->mt_fileno = -1;
4941 		}
4942 		/*
4943 		 * If the value is positive fine.
4944 		 * If its negative we need to return a value based on the
4945 		 * old way if counting backwards from INF (1,000,000,000).
4946 		 */
4947 		if (un->un_err_pos.blkno >= 0) {
4948 			mtget->mt_blkno = un->un_err_pos.blkno;
4949 		} else {
4950 			mtget->mt_blkno = INF + 1 - (-un->un_err_pos.blkno);
4951 		}
4952 		mtget->mt_type = un->un_dp->type;
4953 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
4954 		if (un->un_read_pos_type != NO_POS) {
4955 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
4956 		}
4957 		if (un->un_dp->options & ST_REEL) {
4958 			mtget->mt_flags |= MTF_REEL;
4959 			mtget->mt_bf = 20;
4960 		} else {		/* 1/4" cartridges */
4961 			switch (mtget->mt_type) {
4962 			/* Emulex cartridge tape */
4963 			case MT_ISMT02:
4964 				mtget->mt_bf = 40;
4965 				break;
4966 			default:
4967 				mtget->mt_bf = 126;
4968 				break;
4969 			}
4970 		}
4971 
4972 		/*
4973 		 * If large transfers are allowed and drive options
4974 		 * has no record size limit set. Calculate blocking
4975 		 * factor from the lesser of maxbsize and maxdma.
4976 		 */
4977 		if ((un->un_allow_large_xfer) &&
4978 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
4979 			mtget->mt_bf = min(un->un_maxbsize,
4980 			    un->un_maxdma) / SECSIZE;
4981 		}
4982 
4983 		if (un->un_read_only == WORM ||
4984 		    un->un_read_only == RDWORM) {
4985 			mtget->mt_flags |= MTF_WORM_MEDIA;
4986 		}
4987 
4988 		/*
4989 		 * In persistent error mode sending a non-queued can hang
4990 		 * because this ioctl gets to be run without turning off
4991 		 * persistense. Fake the answer based on previous info.
4992 		 */
4993 		if (un->un_persistence) {
4994 			rval = 0;
4995 		} else {
4996 			rval = st_check_clean_bit(un);
4997 		}
4998 		if (rval == 0) {
4999 			/*
5000 			 * If zero is returned or in persistent mode,
5001 			 * use the old data.
5002 			 */
5003 			if ((un->un_HeadClean & (TAPE_ALERT_SUPPORTED |
5004 			    TAPE_SEQUENTIAL_SUPPORTED|TAPE_ALERT_NOT_SUPPORTED))
5005 			    != TAPE_ALERT_NOT_SUPPORTED) {
5006 				mtget->mt_flags |= MTF_TAPE_CLN_SUPPORTED;
5007 			}
5008 			if (un->un_HeadClean & (TAPE_PREVIOUSLY_DIRTY |
5009 			    TAPE_ALERT_STILL_DIRTY)) {
5010 				mtget->mt_flags |= MTF_TAPE_HEAD_DIRTY;
5011 			}
5012 		} else {
5013 			mtget->mt_flags |= (ushort_t)rval;
5014 			rval = 0;
5015 		}
5016 
5017 		un->un_status = 0;		/* Reset status */
5018 		un->un_err_resid = 0;
5019 		tmp = sizeof (struct mtget);
5020 
5021 #ifdef _MULTI_DATAMODEL
5022 
5023 		switch (ddi_model_convert_from(flag & FMODELS)) {
5024 		case DDI_MODEL_ILP32:
5025 			/*
5026 			 * Convert 64 bit back to 32 bit before doing
5027 			 * copyout. This is what the ILP32 app expects.
5028 			 */
5029 			mtget_32->mt_erreg = 	mtget->mt_erreg;
5030 			mtget_32->mt_resid = 	mtget->mt_resid;
5031 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
5032 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
5033 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
5034 			mtget_32->mt_type =  	mtget->mt_type;
5035 			mtget_32->mt_flags = 	mtget->mt_flags;
5036 			mtget_32->mt_bf = 	mtget->mt_bf;
5037 
5038 			if (ddi_copyout(mtget_32, (void *)arg,
5039 			    sizeof (struct mtget32), flag)) {
5040 				rval = EFAULT;
5041 			}
5042 			break;
5043 
5044 		case DDI_MODEL_NONE:
5045 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5046 				rval = EFAULT;
5047 			}
5048 			break;
5049 		}
5050 #else /* ! _MULTI_DATAMODE */
5051 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5052 			rval = EFAULT;
5053 		}
5054 #endif /* _MULTI_DATAMODE */
5055 
5056 		break;
5057 	}
5058 	case MTIOCGETERROR:
5059 			/*
5060 			 * get error entry from error stack
5061 			 */
5062 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5063 			    "st_ioctl: MTIOCGETERROR\n");
5064 
5065 			rval = st_get_error_entry(un, arg, flag);
5066 
5067 			break;
5068 
5069 	case MTIOCSTATE:
5070 		{
5071 			/*
5072 			 * return when media presence matches state
5073 			 */
5074 			enum mtio_state state;
5075 
5076 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5077 			    "st_ioctl: MTIOCSTATE\n");
5078 
5079 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
5080 				rval = EFAULT;
5081 
5082 			mutex_exit(ST_MUTEX);
5083 
5084 			rval = st_check_media(dev, state);
5085 
5086 			mutex_enter(ST_MUTEX);
5087 
5088 			if (rval != 0) {
5089 				break;
5090 			}
5091 
5092 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
5093 			    sizeof (int), flag))
5094 				rval = EFAULT;
5095 			break;
5096 
5097 		}
5098 
5099 	case MTIOCGETDRIVETYPE:
5100 		{
5101 #ifdef _MULTI_DATAMODEL
5102 		/*
5103 		 * For use when a 32 bit app makes a call into a
5104 		 * 64 bit ioctl
5105 		 */
5106 		struct mtdrivetype_request32	mtdtrq32;
5107 #endif /* _MULTI_DATAMODEL */
5108 
5109 			/*
5110 			 * return mtdrivetype
5111 			 */
5112 			struct mtdrivetype_request mtdtrq;
5113 			struct mtdrivetype mtdrtyp;
5114 			struct mtdrivetype *mtdt = &mtdrtyp;
5115 			struct st_drivetype *stdt = un->un_dp;
5116 
5117 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5118 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
5119 
5120 #ifdef _MULTI_DATAMODEL
5121 		switch (ddi_model_convert_from(flag & FMODELS)) {
5122 		case DDI_MODEL_ILP32:
5123 		{
5124 			if (ddi_copyin((void *)arg, &mtdtrq32,
5125 			    sizeof (struct mtdrivetype_request32), flag)) {
5126 				rval = EFAULT;
5127 				break;
5128 			}
5129 			mtdtrq.size = mtdtrq32.size;
5130 			mtdtrq.mtdtp =
5131 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
5132 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5133 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
5134 			break;
5135 		}
5136 		case DDI_MODEL_NONE:
5137 			if (ddi_copyin((void *)arg, &mtdtrq,
5138 			    sizeof (struct mtdrivetype_request), flag)) {
5139 				rval = EFAULT;
5140 				break;
5141 			}
5142 			break;
5143 		}
5144 
5145 #else /* ! _MULTI_DATAMODEL */
5146 		if (ddi_copyin((void *)arg, &mtdtrq,
5147 		    sizeof (struct mtdrivetype_request), flag)) {
5148 			rval = EFAULT;
5149 			break;
5150 		}
5151 #endif /* _MULTI_DATAMODEL */
5152 
5153 			/*
5154 			 * if requested size is < 0 then return
5155 			 * error.
5156 			 */
5157 			if (mtdtrq.size < 0) {
5158 				rval = EINVAL;
5159 				break;
5160 			}
5161 			bzero(mtdt, sizeof (struct mtdrivetype));
5162 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
5163 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
5164 			mtdt->type = stdt->type;
5165 			mtdt->bsize = stdt->bsize;
5166 			mtdt->options = stdt->options;
5167 			mtdt->max_rretries = stdt->max_rretries;
5168 			mtdt->max_wretries = stdt->max_wretries;
5169 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5170 				mtdt->densities[tmp] = stdt->densities[tmp];
5171 			}
5172 			mtdt->default_density = stdt->default_density;
5173 			/*
5174 			 * Speed hasn't been used since the hayday of reel tape.
5175 			 * For all drives not setting the option ST_KNOWS_MEDIA
5176 			 * the speed member renamed to mediatype are zeros.
5177 			 * Those drives that have ST_KNOWS_MEDIA set use the
5178 			 * new mediatype member which is used to figure the
5179 			 * type of media loaded.
5180 			 *
5181 			 * So as to not break applications speed in the
5182 			 * mtdrivetype structure is not renamed.
5183 			 */
5184 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5185 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
5186 			}
5187 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
5188 			mtdt->io_timeout = stdt->io_timeout;
5189 			mtdt->rewind_timeout = stdt->rewind_timeout;
5190 			mtdt->space_timeout = stdt->space_timeout;
5191 			mtdt->load_timeout = stdt->load_timeout;
5192 			mtdt->unload_timeout = stdt->unload_timeout;
5193 			mtdt->erase_timeout = stdt->erase_timeout;
5194 
5195 			/*
5196 			 * Limit the maximum length of the result to
5197 			 * sizeof (struct mtdrivetype).
5198 			 */
5199 			tmp = sizeof (struct mtdrivetype);
5200 			if (mtdtrq.size < tmp)
5201 				tmp = mtdtrq.size;
5202 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
5203 				rval = EFAULT;
5204 			}
5205 			break;
5206 		}
5207 	case MTIOCPERSISTENT:
5208 
5209 		if (ddi_copyin((void *)arg, &tmp, sizeof (tmp), flag)) {
5210 			rval = EFAULT;
5211 			break;
5212 		}
5213 
5214 		if (tmp) {
5215 			st_turn_pe_on(un);
5216 		} else {
5217 			st_turn_pe_off(un);
5218 		}
5219 
5220 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5221 		    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
5222 		    un->un_persistence);
5223 
5224 		break;
5225 
5226 	case MTIOCPERSISTENTSTATUS:
5227 		tmp = (int)un->un_persistence;
5228 
5229 		if (ddi_copyout(&tmp, (void *)arg, sizeof (tmp), flag)) {
5230 			rval = EFAULT;
5231 		}
5232 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5233 		    "st_ioctl: MTIOCPERSISTENTSTATUS:persistence = %d\n",
5234 		    un->un_persistence);
5235 
5236 		break;
5237 
5238 	case MTIOCLRERR:
5239 		{
5240 			/* clear persistent errors */
5241 
5242 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5243 			    "st_ioctl: MTIOCLRERR\n");
5244 
5245 			st_clear_pe(un);
5246 
5247 			break;
5248 		}
5249 
5250 	case MTIOCGUARANTEEDORDER:
5251 		{
5252 			/*
5253 			 * this is just a holder to make a valid ioctl and
5254 			 * it won't be in any earlier release
5255 			 */
5256 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5257 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
5258 
5259 			break;
5260 		}
5261 
5262 	case MTIOCRESERVE:
5263 		{
5264 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5265 			    "st_ioctl: MTIOCRESERVE\n");
5266 
5267 			/*
5268 			 * Check if Reserve/Release is supported.
5269 			 */
5270 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5271 				rval = ENOTTY;
5272 				break;
5273 			}
5274 
5275 			rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5276 
5277 			if (rval == 0) {
5278 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
5279 			}
5280 			break;
5281 		}
5282 
5283 	case MTIOCRELEASE:
5284 		{
5285 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5286 			    "st_ioctl: MTIOCRELEASE\n");
5287 
5288 			/*
5289 			 * Check if Reserve/Release is supported.
5290 			 */
5291 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5292 				rval = ENOTTY;
5293 				break;
5294 			}
5295 
5296 			/*
5297 			 * Used to just clear ST_PRESERVE_RESERVE which
5298 			 * made the reservation release at next close.
5299 			 * As the user may have opened and then done a
5300 			 * persistant reservation we now need to drop
5301 			 * the reservation without closing if the user
5302 			 * attempts to do this.
5303 			 */
5304 			rval = st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
5305 
5306 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5307 
5308 			break;
5309 		}
5310 
5311 	case MTIOCFORCERESERVE:
5312 	{
5313 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5314 		    "st_ioctl: MTIOCFORCERESERVE\n");
5315 
5316 		/*
5317 		 * Check if Reserve/Release is supported.
5318 		 */
5319 		if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5320 			rval = ENOTTY;
5321 			break;
5322 		}
5323 		/*
5324 		 * allow only super user to run this.
5325 		 */
5326 		if (drv_priv(cred_p) != 0) {
5327 			rval = EPERM;
5328 			break;
5329 		}
5330 		/*
5331 		 * Throw away reserve,
5332 		 * not using test-unit-ready
5333 		 * since reserve can succeed without tape being
5334 		 * present in the drive.
5335 		 */
5336 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5337 
5338 		rval = st_take_ownership(un, st_uscsi_cmd);
5339 
5340 		break;
5341 	}
5342 
5343 	case USCSICMD:
5344 	{
5345 		cred_t	*cr;
5346 
5347 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5348 		    "st_ioctl: USCSICMD\n");
5349 
5350 		cr = ddi_get_cred();
5351 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5352 			rval = EPERM;
5353 		} else {
5354 			rval = st_uscsi_cmd(un, (struct uscsi_cmd *)arg, flag);
5355 		}
5356 		break;
5357 	}
5358 	case MTIOCTOP:
5359 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5360 		    "st_ioctl: MTIOCTOP\n");
5361 		rval = st_mtioctop(un, arg, flag);
5362 		break;
5363 
5364 	case MTIOCLTOP:
5365 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5366 		    "st_ioctl: MTIOLCTOP\n");
5367 		rval = st_mtiocltop(un, arg, flag);
5368 		break;
5369 
5370 	case MTIOCREADIGNOREILI:
5371 		{
5372 			int set_ili;
5373 
5374 			if (ddi_copyin((void *)arg, &set_ili,
5375 			    sizeof (set_ili), flag)) {
5376 				rval = EFAULT;
5377 				break;
5378 			}
5379 
5380 			if (un->un_bsize) {
5381 				rval = ENOTTY;
5382 				break;
5383 			}
5384 
5385 			switch (set_ili) {
5386 			case 0:
5387 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5388 				break;
5389 
5390 			case 1:
5391 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5392 				break;
5393 
5394 			default:
5395 				rval = EINVAL;
5396 				break;
5397 			}
5398 			break;
5399 		}
5400 
5401 	case MTIOCREADIGNOREEOFS:
5402 		{
5403 			int ignore_eof;
5404 
5405 			if (ddi_copyin((void *)arg, &ignore_eof,
5406 			    sizeof (ignore_eof), flag)) {
5407 				rval = EFAULT;
5408 				break;
5409 			}
5410 
5411 			if (!(un->un_dp->options & ST_REEL)) {
5412 				rval = ENOTTY;
5413 				break;
5414 			}
5415 
5416 			switch (ignore_eof) {
5417 			case 0:
5418 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5419 				break;
5420 
5421 			case 1:
5422 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5423 				break;
5424 
5425 			default:
5426 				rval = EINVAL;
5427 				break;
5428 			}
5429 			break;
5430 		}
5431 
5432 	case MTIOCSHORTFMK:
5433 	{
5434 		int short_fmk;
5435 
5436 		if (ddi_copyin((void *)arg, &short_fmk,
5437 		    sizeof (short_fmk), flag)) {
5438 			rval = EFAULT;
5439 			break;
5440 		}
5441 
5442 		switch (un->un_dp->type) {
5443 		case ST_TYPE_EXB8500:
5444 		case ST_TYPE_EXABYTE:
5445 			if (!short_fmk) {
5446 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5447 			} else if (short_fmk == 1) {
5448 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5449 			} else {
5450 				rval = EINVAL;
5451 			}
5452 			break;
5453 
5454 		default:
5455 			rval = ENOTTY;
5456 			break;
5457 		}
5458 		break;
5459 	}
5460 
5461 	case MTIOCGETPOS:
5462 		rval = st_update_block_pos(un, st_cmd, 0);
5463 		if (rval == 0) {
5464 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5465 			    sizeof (tapepos_t), flag)) {
5466 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5467 				    "MTIOCGETPOS copy out failed\n");
5468 				rval = EFAULT;
5469 			}
5470 		}
5471 		break;
5472 
5473 	case MTIOCRESTPOS:
5474 	{
5475 		tapepos_t dest;
5476 
5477 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5478 		    flag) != 0) {
5479 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5480 			    "MTIOCRESTPOS copy in failed\n");
5481 			rval = EFAULT;
5482 			break;
5483 		}
5484 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &dest);
5485 		if (rval != 0) {
5486 			rval = EIO;
5487 		}
5488 		break;
5489 	}
5490 	default:
5491 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5492 		    "st_ioctl: unknown ioctl\n");
5493 		rval = ENOTTY;
5494 	}
5495 
5496 exit:
5497 	if (!(un->un_persistence && un->un_persist_errors)) {
5498 		un->un_errno = rval;
5499 	}
5500 
5501 	mutex_exit(ST_MUTEX);
5502 
5503 	return (rval);
5504 }
5505 
5506 
5507 /*
5508  * do some MTIOCTOP tape operations
5509  */
5510 static int
5511 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5512 {
5513 #ifdef _MULTI_DATAMODEL
5514 	/*
5515 	 * For use when a 32 bit app makes a call into a
5516 	 * 64 bit ioctl
5517 	 */
5518 	struct mtop32	mtop_32_for_64;
5519 #endif /* _MULTI_DATAMODEL */
5520 	struct mtop passed;
5521 	struct mtlop local;
5522 	int rval = 0;
5523 
5524 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5525 
5526 	ASSERT(mutex_owned(ST_MUTEX));
5527 
5528 #ifdef _MULTI_DATAMODEL
5529 	switch (ddi_model_convert_from(flag & FMODELS)) {
5530 	case DDI_MODEL_ILP32:
5531 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5532 		    sizeof (struct mtop32), flag)) {
5533 			return (EFAULT);
5534 		}
5535 		local.mt_op = mtop_32_for_64.mt_op;
5536 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5537 		break;
5538 
5539 	case DDI_MODEL_NONE:
5540 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5541 			return (EFAULT);
5542 		}
5543 		local.mt_op = passed.mt_op;
5544 		/* prevent sign extention */
5545 		local.mt_count = (UINT32_MAX & passed.mt_count);
5546 		break;
5547 	}
5548 
5549 #else /* ! _MULTI_DATAMODEL */
5550 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5551 		return (EFAULT);
5552 	}
5553 	local.mt_op = passed.mt_op;
5554 	/* prevent sign extention */
5555 	local.mt_count = (UINT32_MAX & passed.mt_count);
5556 #endif /* _MULTI_DATAMODEL */
5557 
5558 	rval = st_do_mtioctop(un, &local);
5559 
5560 #ifdef _MULTI_DATAMODEL
5561 	switch (ddi_model_convert_from(flag & FMODELS)) {
5562 	case DDI_MODEL_ILP32:
5563 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5564 			rval = ERANGE;
5565 			break;
5566 		}
5567 		/*
5568 		 * Convert 64 bit back to 32 bit before doing
5569 		 * copyout. This is what the ILP32 app expects.
5570 		 */
5571 		mtop_32_for_64.mt_op = local.mt_op;
5572 		mtop_32_for_64.mt_count = local.mt_count;
5573 
5574 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5575 		    sizeof (struct mtop32), flag)) {
5576 			rval = EFAULT;
5577 		}
5578 		break;
5579 
5580 	case DDI_MODEL_NONE:
5581 		passed.mt_count = local.mt_count;
5582 		passed.mt_op = local.mt_op;
5583 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5584 			rval = EFAULT;
5585 		}
5586 		break;
5587 	}
5588 #else /* ! _MULTI_DATAMODE */
5589 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5590 		rval = ERANGE;
5591 	} else {
5592 		passed.mt_op = local.mt_op;
5593 		passed.mt_count = local.mt_count;
5594 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5595 			rval = EFAULT;
5596 		}
5597 	}
5598 #endif /* _MULTI_DATAMODE */
5599 
5600 
5601 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5602 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5603 	    un->un_pos.blkno, un->un_pos.eof);
5604 
5605 	if (un->un_pos.pmode == invalid) {
5606 		un->un_density_known = 0;
5607 	}
5608 
5609 	ASSERT(mutex_owned(ST_MUTEX));
5610 	return (rval);
5611 }
5612 
5613 static int
5614 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5615 {
5616 	struct mtlop local;
5617 	int rval;
5618 
5619 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5620 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5621 		return (EFAULT);
5622 	}
5623 
5624 	rval = st_do_mtioctop(un, &local);
5625 
5626 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5627 		rval = EFAULT;
5628 	}
5629 	return (rval);
5630 }
5631 
5632 
5633 static int
5634 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5635 {
5636 	dev_t dev = un->un_dev;
5637 	int savefile;
5638 	int rval = 0;
5639 
5640 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5641 
5642 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5643 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5644 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5645 	    "fileno=%x, blkno=%x, eof=%x\n",
5646 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5647 
5648 	un->un_status = 0;
5649 
5650 	/*
5651 	 * if we are going to mess with a tape, we have to make sure we have
5652 	 * one and are not offline (i.e. no tape is initialized).  We let
5653 	 * commands pass here that don't actually touch the tape, except for
5654 	 * loading and initialization (rewinding).
5655 	 */
5656 	if (un->un_state == ST_STATE_OFFLINE) {
5657 		switch (mtop->mt_op) {
5658 		case MTLOAD:
5659 		case MTNOP:
5660 			/*
5661 			 * We don't want strategy calling st_tape_init here,
5662 			 * so, change state
5663 			 */
5664 			un->un_state = ST_STATE_INITIALIZING;
5665 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5666 			    "st_do_mtioctop : OFFLINE state = %d\n",
5667 			    un->un_state);
5668 			break;
5669 		default:
5670 			/*
5671 			 * reinitialize by normal means
5672 			 */
5673 			rval = st_tape_init(un);
5674 			if (rval) {
5675 				un->un_state = ST_STATE_INITIALIZING;
5676 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5677 				    "st_do_mtioctop : OFFLINE init failure ");
5678 				un->un_state = ST_STATE_OFFLINE;
5679 				un->un_pos.pmode = invalid;
5680 				if (rval != EACCES) {
5681 					rval = EIO;
5682 				}
5683 				return (rval);
5684 			}
5685 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5686 			break;
5687 		}
5688 	}
5689 
5690 	/*
5691 	 * If the file position is invalid, allow only those
5692 	 * commands that properly position the tape and fail
5693 	 * the rest with EIO
5694 	 */
5695 	if (un->un_pos.pmode == invalid) {
5696 		switch (mtop->mt_op) {
5697 		case MTWEOF:
5698 		case MTRETEN:
5699 		case MTERASE:
5700 		case MTEOM:
5701 		case MTFSF:
5702 		case MTFSR:
5703 		case MTBSF:
5704 		case MTNBSF:
5705 		case MTBSR:
5706 		case MTSRSZ:
5707 		case MTGRSZ:
5708 		case MTSEEK:
5709 		case MTBSSF:
5710 		case MTFSSF:
5711 			return (EIO);
5712 			/* NOTREACHED */
5713 		case MTREW:
5714 		case MTLOAD:
5715 		case MTOFFL:
5716 		case MTNOP:
5717 		case MTTELL:
5718 		case MTLOCK:
5719 		case MTUNLOCK:
5720 			break;
5721 
5722 		default:
5723 			return (ENOTTY);
5724 			/* NOTREACHED */
5725 		}
5726 	}
5727 
5728 	switch (mtop->mt_op) {
5729 	case MTERASE:
5730 		/*
5731 		 * MTERASE rewinds the tape, erase it completely, and returns
5732 		 * to the beginning of the tape
5733 		 */
5734 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5735 			un->un_status = KEY_WRITE_PROTECT;
5736 			un->un_err_resid = mtop->mt_count;
5737 			COPY_POS(&un->un_err_pos, &un->un_pos);
5738 			return (EACCES);
5739 		}
5740 		if (un->un_dp->options & ST_REEL) {
5741 			un->un_fmneeded = 2;
5742 		} else {
5743 			un->un_fmneeded = 1;
5744 		}
5745 		mtop->mt_count = mtop->mt_count ? 1 : 0;
5746 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5747 		    st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
5748 		    st_cmd(un, SCMD_ERASE, mtop->mt_count, SYNC_CMD)) {
5749 			un->un_pos.pmode = invalid;
5750 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5751 			    "st_do_mtioctop : EIO space or erase or "
5752 			    "check den)\n");
5753 			rval = EIO;
5754 		} else {
5755 			/* QIC and helical scan rewind after erase */
5756 			if (un->un_dp->options & ST_REEL) {
5757 				(void) st_cmd(un, SCMD_REWIND, 0, ASYNC_CMD);
5758 			}
5759 		}
5760 		break;
5761 
5762 	case MTWEOF:
5763 		/*
5764 		 * write an end-of-file record
5765 		 */
5766 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5767 			un->un_status = KEY_WRITE_PROTECT;
5768 			un->un_err_resid = mtop->mt_count;
5769 			COPY_POS(&un->un_err_pos, &un->un_pos);
5770 			return (EACCES);
5771 		}
5772 
5773 		/*
5774 		 * zero count means just flush buffers
5775 		 * negative count is not permitted
5776 		 */
5777 		if (mtop->mt_count < 0) {
5778 			return (EINVAL);
5779 		}
5780 
5781 		/* Not on worm */
5782 		if (un->un_read_only == RDWR) {
5783 			un->un_test_append = 1;
5784 		}
5785 
5786 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5787 			if (st_determine_density(un, B_WRITE)) {
5788 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5789 				    "st_do_mtioctop : EIO : MTWEOF can't "
5790 				    "determine density");
5791 				return (EIO);
5792 			}
5793 		}
5794 
5795 		rval = st_write_fm(dev, (int)mtop->mt_count);
5796 		if ((rval != 0) && (rval != EACCES)) {
5797 			/*
5798 			 * Failure due to something other than illegal
5799 			 * request results in loss of state (st_intr).
5800 			 */
5801 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5802 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5803 			    "file mark");
5804 			rval = EIO;
5805 		}
5806 		break;
5807 
5808 	case MTRETEN:
5809 		/*
5810 		 * retension the tape
5811 		 */
5812 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5813 		    st_cmd(un, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5814 			un->un_pos.pmode = invalid;
5815 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5816 			    "st_do_mtioctop : EIO : MTRETEN ");
5817 			rval = EIO;
5818 		}
5819 		break;
5820 
5821 	case MTREW:
5822 		/*
5823 		 * rewind  the tape
5824 		 */
5825 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5826 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5827 			    "st_do_mtioctop : EIO:MTREW check "
5828 			    "density/wfm failed");
5829 			return (EIO);
5830 		}
5831 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
5832 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5833 			    "st_do_mtioctop : EIO : MTREW ");
5834 			rval = EIO;
5835 		}
5836 		break;
5837 
5838 	case MTOFFL:
5839 		/*
5840 		 * rewinds, and, if appropriate, takes the device offline by
5841 		 * unloading the tape
5842 		 */
5843 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5844 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5845 			    "st_do_mtioctop :EIO:MTOFFL check "
5846 			    "density/wfm failed");
5847 			return (EIO);
5848 		}
5849 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
5850 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5851 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5852 			    "st_do_mtioctop : EIO : MTOFFL");
5853 			return (EIO);
5854 		}
5855 		un->un_pos.eof = ST_NO_EOF;
5856 		un->un_laststate = un->un_state;
5857 		un->un_state = ST_STATE_OFFLINE;
5858 		un->un_mediastate = MTIO_EJECTED;
5859 		break;
5860 
5861 	case MTLOAD:
5862 		/*
5863 		 * This is to load a tape into the drive
5864 		 * Note that if the tape is not loaded, the device will have
5865 		 * to be opened via O_NDELAY or O_NONBLOCK.
5866 		 */
5867 		/*
5868 		 * Let's try and clean things up, if we are not
5869 		 * initializing, and then send in the load command, no
5870 		 * matter what.
5871 		 *
5872 		 * load after a media change by the user.
5873 		 */
5874 
5875 		if (un->un_state > ST_STATE_INITIALIZING) {
5876 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5877 		}
5878 		rval = st_cmd(un, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5879 		/* Load command to a drive that doesn't support load */
5880 		if ((rval == EIO) &&
5881 		    ((un->un_status == KEY_NOT_READY) &&
5882 			/* Medium not present */
5883 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5884 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5885 		    (un->un_dp->type == MT_ISSTK9840) &&
5886 			/* CSL not present */
5887 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5888 			rval = ENOTTY;
5889 			break;
5890 		} else if (rval != EACCES && rval != 0) {
5891 			rval = EIO;
5892 		}
5893 		if (rval) {
5894 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5895 			    "st_do_mtioctop : %s : MTLOAD\n",
5896 			    rval == EACCES ? "EACCES" : "EIO");
5897 			/*
5898 			 * If load tape fails, who knows what happened...
5899 			 */
5900 			un->un_pos.pmode = invalid;
5901 			break;
5902 		}
5903 
5904 		/*
5905 		 * reset all counters appropriately using rewind, as if LOAD
5906 		 * succeeds, we are at BOT
5907 		 */
5908 		un->un_state = ST_STATE_INITIALIZING;
5909 
5910 		rval = st_tape_init(un);
5911 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5912 			rval = 0;
5913 			break;
5914 		}
5915 
5916 		if (rval != 0) {
5917 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5918 			    "st_do_mtioctop : EIO : MTLOAD calls "
5919 			    "st_tape_init\n");
5920 			rval = EIO;
5921 			un->un_state = ST_STATE_OFFLINE;
5922 		}
5923 
5924 		break;
5925 
5926 	case MTNOP:
5927 		un->un_status = 0;		/* Reset status */
5928 		un->un_err_resid = 0;
5929 		mtop->mt_count = MTUNIT(dev);
5930 		break;
5931 
5932 	case MTEOM:
5933 		/*
5934 		 * positions the tape at a location just after the last file
5935 		 * written on the tape. For cartridge and 8 mm, this after
5936 		 * the last file mark; for reel, this is inbetween the two
5937 		 * last 2 file marks
5938 		 */
5939 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5940 		    (un->un_lastop == ST_OP_WRITE) ||
5941 		    (un->un_lastop == ST_OP_WEOF)) {
5942 			/*
5943 			 * If the command wants to move to logical end
5944 			 * of media, and we're already there, we're done.
5945 			 * If we were at logical eot, we reset the state
5946 			 * to be *not* at logical eot.
5947 			 *
5948 			 * If we're at physical or logical eot, we prohibit
5949 			 * forward space operations (unconditionally).
5950 			 *
5951 			 * Also if the last operation was a write of any
5952 			 * kind the tape is at EOD.
5953 			 */
5954 			return (0);
5955 		}
5956 		/*
5957 		 * physical tape position may not be what we've been
5958 		 * telling the user; adjust the request accordingly
5959 		 */
5960 		if (IN_EOF(un->un_pos)) {
5961 			un->un_pos.fileno++;
5962 			un->un_pos.blkno = 0;
5963 		}
5964 
5965 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
5966 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5967 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
5968 			    " failed");
5969 			return (EIO);
5970 		}
5971 
5972 		/*
5973 		 * st_find_eod() returns the last fileno we knew about;
5974 		 */
5975 		savefile = st_find_eod(un);
5976 
5977 		if ((un->un_status != KEY_BLANK_CHECK) &&
5978 		    (un->un_status != SUN_KEY_EOT)) {
5979 			un->un_pos.pmode = invalid;
5980 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5981 			    "st_do_mtioctop : EIO : MTEOM status check failed");
5982 			rval = EIO;
5983 		} else {
5984 			/*
5985 			 * For 1/2" reel tapes assume logical EOT marked
5986 			 * by two file marks or we don't care that we may
5987 			 * be extending the last file on the tape.
5988 			 */
5989 			if (un->un_dp->options & ST_REEL) {
5990 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
5991 					un->un_pos.pmode = invalid;
5992 					ST_DEBUG2(ST_DEVINFO, st_label,
5993 					    SCSI_DEBUG,
5994 					    "st_do_mtioctop : EIO : MTEOM space"
5995 					    " cmd failed");
5996 					rval = EIO;
5997 					break;
5998 				}
5999 				/*
6000 				 * Fix up the block number.
6001 				 */
6002 				un->un_pos.blkno = 0;
6003 				un->un_err_pos.blkno = 0;
6004 			}
6005 			un->un_err_resid = 0;
6006 			un->un_pos.fileno = savefile;
6007 			un->un_pos.eof = ST_EOT;
6008 		}
6009 		un->un_status = 0;
6010 		break;
6011 
6012 	case MTFSF:
6013 		MAX_SPACE_CNT(mtop->mt_count);
6014 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
6015 		break;
6016 
6017 	case MTFSR:
6018 		MAX_SPACE_CNT(mtop->mt_count);
6019 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
6020 		break;
6021 
6022 	case MTBSF:
6023 		MAX_SPACE_CNT(mtop->mt_count);
6024 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
6025 		break;
6026 
6027 	case MTNBSF:
6028 		MAX_SPACE_CNT(mtop->mt_count);
6029 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
6030 		break;
6031 
6032 	case MTBSR:
6033 		MAX_SPACE_CNT(mtop->mt_count);
6034 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
6035 		break;
6036 
6037 	case MTBSSF:
6038 		MAX_SPACE_CNT(mtop->mt_count);
6039 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
6040 		break;
6041 
6042 	case MTFSSF:
6043 		MAX_SPACE_CNT(mtop->mt_count);
6044 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
6045 		break;
6046 
6047 	case MTSRSZ:
6048 
6049 		/*
6050 		 * Set record-size to that sent by user
6051 		 * Check to see if there is reason that the requested
6052 		 * block size should not be set.
6053 		 */
6054 
6055 		/* If requesting variable block size is it ok? */
6056 		if ((mtop->mt_count == 0) &&
6057 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
6058 			return (ENOTTY);
6059 		}
6060 
6061 		/*
6062 		 * If requested block size is not variable "0",
6063 		 * is it less then minimum.
6064 		 */
6065 		if ((mtop->mt_count != 0) &&
6066 		    (mtop->mt_count < un->un_minbsize)) {
6067 			return (EINVAL);
6068 		}
6069 
6070 		/* Is the requested block size more then maximum */
6071 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
6072 		    (un->un_maxbsize != 0)) {
6073 			return (EINVAL);
6074 		}
6075 
6076 		/* Is requested block size a modulus the device likes */
6077 		if ((mtop->mt_count % un->un_data_mod) != 0) {
6078 			return (EINVAL);
6079 		}
6080 
6081 		if (st_change_block_size(un, (uint32_t)mtop->mt_count) != 0) {
6082 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6083 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
6084 			return (EIO);
6085 		}
6086 
6087 		return (0);
6088 
6089 	case MTGRSZ:
6090 		/*
6091 		 * Get record-size to the user
6092 		 */
6093 		mtop->mt_count = un->un_bsize;
6094 		rval = 0;
6095 		break;
6096 
6097 	case MTTELL:
6098 		rval = st_update_block_pos(un, st_cmd, 0);
6099 		mtop->mt_count = un->un_pos.lgclblkno;
6100 		break;
6101 
6102 	case MTSEEK:
6103 		rval = st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
6104 		    (uint64_t)mtop->mt_count, un->un_pos.partition);
6105 		/*
6106 		 * This bit of magic make mt print the actual position if
6107 		 * the resulting position was not what was asked for.
6108 		 */
6109 		if (rval == ESPIPE) {
6110 			rval = EIO;
6111 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
6112 				mtop->mt_op = MTTELL;
6113 				mtop->mt_count = un->un_pos.lgclblkno;
6114 			}
6115 		}
6116 		break;
6117 
6118 	case MTLOCK:
6119 		if (st_cmd(un, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
6120 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6121 			    "st_do_mtioctop : EIO : MTLOCK");
6122 			rval = EIO;
6123 		}
6124 		break;
6125 
6126 	case MTUNLOCK:
6127 		if (st_cmd(un, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
6128 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6129 			    "st_do_mtioctop : EIO : MTUNLOCK");
6130 			rval = EIO;
6131 		}
6132 		break;
6133 
6134 	default:
6135 		rval = ENOTTY;
6136 	}
6137 
6138 	return (rval);
6139 }
6140 
6141 
6142 /*
6143  * Run a command for uscsi ioctl.
6144  */
6145 static int
6146 st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
6147 {
6148 	struct uscsi_cmd	*uscmd;
6149 	struct buf	*bp;
6150 	enum uio_seg	uioseg;
6151 	int	offline_state = 0;
6152 	int	err = 0;
6153 	dev_t dev = un->un_dev;
6154 
6155 	ST_FUNC(ST_DEVINFO, st_uscsi_cmd);
6156 
6157 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6158 	    "st_uscsi_cmd(dev = 0x%lx)\n", un->un_dev);
6159 
6160 	ASSERT(mutex_owned(ST_MUTEX));
6161 
6162 	/*
6163 	 * We really don't know what commands are coming in here and
6164 	 * we don't want to limit the commands coming in.
6165 	 *
6166 	 * If st_tape_init() gets called from st_strategy(), then we
6167 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
6168 	 * which it never will, as we set it below.  To prevent
6169 	 * st_tape_init() from getting called, we have to set state to other
6170 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
6171 	 * achieves this purpose already.
6172 	 *
6173 	 * We use offline_state to preserve the OFFLINE state, if it exists,
6174 	 * so other entry points to the driver might have the chance to call
6175 	 * st_tape_init().
6176 	 */
6177 	if (un->un_state == ST_STATE_OFFLINE) {
6178 		un->un_laststate = ST_STATE_OFFLINE;
6179 		un->un_state = ST_STATE_INITIALIZING;
6180 		offline_state = 1;
6181 	}
6182 
6183 	mutex_exit(ST_MUTEX);
6184 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag, ROUTE, &uscmd);
6185 	mutex_enter(ST_MUTEX);
6186 	if (err != 0) {
6187 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6188 		    "st_uscsi_cmd: scsi_uscsi_alloc_and_copyin failed\n");
6189 		goto exit;
6190 	}
6191 
6192 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
6193 
6194 	/* check to see if this command requires the drive to be reserved */
6195 	if (uscmd->uscsi_cdb != NULL) {
6196 		err = st_check_cdb_for_need_to_reserve(un,
6197 		    (uchar_t *)uscmd->uscsi_cdb);
6198 		if (err) {
6199 			goto exit_free;
6200 		}
6201 		/*
6202 		 * If this is a space command we need to save the starting
6203 		 * point so we can retry from there if the command fails.
6204 		 */
6205 		if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6206 		    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) {
6207 			(void) st_update_block_pos(un, st_cmd, 0);
6208 		}
6209 	}
6210 
6211 	/*
6212 	 * Forground should not be doing anything while recovery is active.
6213 	 */
6214 	ASSERT(un->un_recov_buf_busy == 0);
6215 
6216 	/*
6217 	 * Get buffer resources...
6218 	 */
6219 	while (un->un_sbuf_busy)
6220 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6221 	un->un_sbuf_busy = 1;
6222 
6223 #ifdef STDEBUG
6224 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0x7) > 6) {
6225 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
6226 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6227 		    "uscsi cdb", uscmd->uscsi_cdb);
6228 		if (uscmd->uscsi_buflen) {
6229 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6230 			    "uscsi %s of %ld bytes %s %s space\n",
6231 			    (rw == B_READ) ? rd_str : wr_str,
6232 			    uscmd->uscsi_buflen,
6233 			    (rw == B_READ) ? "to" : "from",
6234 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
6235 		}
6236 	}
6237 #endif /* STDEBUG */
6238 
6239 	/*
6240 	 * Although st_uscsi_cmd() never makes use of these
6241 	 * now, we are just being safe and consistent.
6242 	 */
6243 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
6244 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
6245 
6246 	un->un_srqbufp = uscmd->uscsi_rqbuf;
6247 	bp = un->un_sbufp;
6248 	bzero(bp, sizeof (buf_t));
6249 	if (uscmd->uscsi_cdb != NULL) {
6250 		bp->b_forw = (struct buf *)(uintptr_t)uscmd->uscsi_cdb[0];
6251 	}
6252 	bp->b_back = (struct buf *)uscmd;
6253 
6254 	mutex_exit(ST_MUTEX);
6255 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, st_strategy, bp, NULL);
6256 	mutex_enter(ST_MUTEX);
6257 
6258 	/*
6259 	 * If scsi reset successful, don't write any filemarks.
6260 	 */
6261 	if ((err == 0) && (uscmd->uscsi_flags &
6262 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
6263 		un->un_fmneeded = 0;
6264 	}
6265 
6266 exit_free:
6267 	/*
6268 	 * Free resources
6269 	 */
6270 	un->un_sbuf_busy = 0;
6271 	un->un_srqbufp = NULL;
6272 
6273 	/*
6274 	 * If was a space command need to update logical block position.
6275 	 * If the command failed such that positioning is invalid, Don't
6276 	 * update the position as the user must do this to validate the
6277 	 * position for data protection.
6278 	 */
6279 	if ((uscmd->uscsi_cdb != NULL) &&
6280 	    ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6281 	    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) &&
6282 	    (un->un_pos.pmode != invalid)) {
6283 		un->un_running.pmode = invalid;
6284 		(void) st_update_block_pos(un, st_cmd, 1);
6285 		/*
6286 		 * Set running position to invalid so it updates on the
6287 		 * next command.
6288 		 */
6289 		un->un_running.pmode = invalid;
6290 	}
6291 	cv_signal(&un->un_sbuf_cv);
6292 	mutex_exit(ST_MUTEX);
6293 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
6294 	mutex_enter(ST_MUTEX);
6295 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6296 	    "st_uscsi_cmd returns 0x%x\n", err);
6297 
6298 exit:
6299 	/* don't lose offline state */
6300 	if (offline_state) {
6301 		un->un_state = ST_STATE_OFFLINE;
6302 	}
6303 
6304 	ASSERT(mutex_owned(ST_MUTEX));
6305 	return (err);
6306 }
6307 
6308 static int
6309 st_write_fm(dev_t dev, int wfm)
6310 {
6311 	int i;
6312 	int rval;
6313 
6314 	GET_SOFT_STATE(dev);
6315 
6316 	ST_FUNC(ST_DEVINFO, st_write_fm);
6317 
6318 	ASSERT(mutex_owned(ST_MUTEX));
6319 
6320 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6321 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6322 
6323 	/*
6324 	 * write one filemark at the time after EOT
6325 	 */
6326 	if (un->un_pos.eof >= ST_EOT) {
6327 		for (i = 0; i < wfm; i++) {
6328 			rval = st_cmd(un, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6329 			if (rval == EACCES) {
6330 				return (rval);
6331 			}
6332 			if (rval != 0) {
6333 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6334 				    "st_write_fm : EIO : write EOT file mark");
6335 				return (EIO);
6336 			}
6337 		}
6338 	} else {
6339 		rval = st_cmd(un, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6340 		if (rval == EACCES) {
6341 			return (rval);
6342 		}
6343 		if (rval) {
6344 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6345 			    "st_write_fm : EIO : write file mark");
6346 			return (EIO);
6347 		}
6348 	}
6349 
6350 	ASSERT(mutex_owned(ST_MUTEX));
6351 	return (0);
6352 }
6353 
6354 #ifdef STDEBUG
6355 static void
6356 st_start_dump(struct scsi_tape *un, struct buf *bp)
6357 {
6358 	struct scsi_pkt *pkt = BP_PKT(bp);
6359 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6360 
6361 	ST_FUNC(ST_DEVINFO, st_start_dump);
6362 
6363 	if ((st_debug & 0x7) < 6)
6364 		return;
6365 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6366 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6367 	    (void *)bp->b_forw, bp->b_bcount,
6368 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6369 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6370 	    "st_start: cdb",  (caddr_t)cdbp);
6371 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6372 	    "st_start: fileno=%d, blk=%d\n",
6373 	    un->un_pos.fileno, un->un_pos.blkno);
6374 }
6375 #endif
6376 
6377 
6378 /*
6379  * Command start && done functions
6380  */
6381 
6382 /*
6383  * st_start()
6384  *
6385  * Called from:
6386  *  st_strategy() to start a command.
6387  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6388  *  st_attach() when resuming from power down state.
6389  *  st_start_restart() to retry transport when device was previously busy.
6390  *  st_done_and_mutex_exit() to start the next command when previous is done.
6391  *
6392  * On entry:
6393  *  scsi_pkt may or may not be allocated.
6394  *
6395  */
6396 static void
6397 st_start(struct scsi_tape *un)
6398 {
6399 	struct buf *bp;
6400 	int status;
6401 	int queued;
6402 
6403 	ST_FUNC(ST_DEVINFO, st_start);
6404 	ASSERT(mutex_owned(ST_MUTEX));
6405 
6406 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6407 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6408 
6409 	if (un->un_recov_buf_busy) {
6410 		/* recovery commands can happen anytime */
6411 		bp = un->un_recov_buf;
6412 		queued = 0;
6413 	} else if (un->un_sbuf_busy) {
6414 		/* sbuf commands should only happen with an empty queue. */
6415 		ASSERT(un->un_quef == NULL);
6416 		ASSERT(un->un_runqf == NULL);
6417 		bp = un->un_sbufp;
6418 		queued = 0;
6419 	} else if (un->un_quef != NULL) {
6420 		if (un->un_persistence && un->un_persist_errors) {
6421 			return;
6422 		}
6423 		bp = un->un_quef;
6424 		queued = 1;
6425 	} else {
6426 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6427 		    "st_start() returning no buf found\n");
6428 		return;
6429 	}
6430 
6431 	ASSERT((bp->b_flags & B_DONE) == 0);
6432 
6433 	/*
6434 	 * Don't send more than un_throttle commands to the HBA
6435 	 */
6436 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6437 		/*
6438 		 * if doing recovery we know there is outstanding commands.
6439 		 */
6440 		if (bp != un->un_recov_buf) {
6441 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6442 			    "st_start returning throttle = %d or ncmds = %d\n",
6443 			    un->un_throttle, un->un_ncmds);
6444 			if (un->un_ncmds == 0) {
6445 				typedef void (*func)();
6446 				func fnc = (func)st_runout;
6447 
6448 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6449 				    "Sending delayed start to st_runout()\n");
6450 				mutex_exit(ST_MUTEX);
6451 				(void) timeout(fnc, un, drv_usectohz(1000000));
6452 				mutex_enter(ST_MUTEX);
6453 			}
6454 			return;
6455 		}
6456 	}
6457 
6458 	/*
6459 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6460 	 * build the command.
6461 	 */
6462 	if (BP_PKT(bp) == NULL) {
6463 		ASSERT((bp->b_flags & B_DONE) == 0);
6464 		st_make_cmd(un, bp, st_runout);
6465 		ASSERT((bp->b_flags & B_DONE) == 0);
6466 		status = geterror(bp);
6467 
6468 		/*
6469 		 * Some HBA's don't call bioerror() to set an error.
6470 		 * And geterror() returns zero if B_ERROR is not set.
6471 		 * So if we get zero we must check b_error.
6472 		 */
6473 		if (status == 0 && bp->b_error != 0) {
6474 			status = bp->b_error;
6475 			bioerror(bp, status);
6476 		}
6477 
6478 		/*
6479 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6480 		 * In tape ENOMEM has special meaning so we'll change it.
6481 		 */
6482 		if (status == ENOMEM) {
6483 			status = 0;
6484 			bioerror(bp, status);
6485 		}
6486 
6487 		/*
6488 		 * Did it fail and is it retryable?
6489 		 * If so return and wait for the callback through st_runout.
6490 		 * Also looks like scsi_init_pkt() will setup a callback even
6491 		 * if it isn't retryable.
6492 		 */
6493 		if (BP_PKT(bp) == NULL) {
6494 			if (status == 0) {
6495 				/*
6496 				 * If first attempt save state.
6497 				 */
6498 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6499 					un->un_laststate = un->un_state;
6500 					un->un_state = ST_STATE_RESOURCE_WAIT;
6501 				}
6502 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6503 				    "temp no resources for pkt\n");
6504 			} else if (status == EINVAL) {
6505 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6506 				    "scsi_init_pkt rejected pkt as too big\n");
6507 				if (un->un_persistence) {
6508 					st_set_pe_flag(un);
6509 				}
6510 			} else {
6511 				/*
6512 				 * Unlikely that it would be retryable then not.
6513 				 */
6514 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6515 					un->un_state = un->un_laststate;
6516 				}
6517 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6518 				    "perm no resources for pkt errno = 0x%x\n",
6519 				    status);
6520 			}
6521 			return;
6522 		}
6523 		/*
6524 		 * Worked this time set the state back.
6525 		 */
6526 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6527 			un->un_state = un->un_laststate;
6528 		}
6529 	}
6530 
6531 	if (queued) {
6532 		/*
6533 		 * move from waitq to runq
6534 		 */
6535 		(void) st_remove_from_queue(&un->un_quef, &un->un_quel, bp);
6536 		st_add_to_queue(&un->un_runqf, &un->un_runql, un->un_runql, bp);
6537 	}
6538 
6539 
6540 #ifdef STDEBUG
6541 	st_start_dump(un, bp);
6542 #endif
6543 
6544 	/* could not get here if throttle was zero */
6545 	un->un_last_throttle = un->un_throttle;
6546 	un->un_throttle = 0;	/* so nothing else will come in here */
6547 	un->un_ncmds++;
6548 
6549 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6550 
6551 	status = st_transport(un, BP_PKT(bp));
6552 
6553 	if (un->un_last_throttle) {
6554 		un->un_throttle = un->un_last_throttle;
6555 	}
6556 
6557 	if (status != TRAN_ACCEPT) {
6558 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6559 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
6560 		    "Unhappy transport packet status 0x%x\n", status);
6561 
6562 		if (status == TRAN_BUSY) {
6563 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
6564 
6565 			/*
6566 			 * If command recovery is enabled and this isn't
6567 			 * a recovery command try command recovery.
6568 			 */
6569 			if (pkti->privatelen == sizeof (recov_info) &&
6570 			    bp != un->un_recov_buf) {
6571 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
6572 				    "Command Recovery called on busy send\n");
6573 				if (st_command_recovery(un, BP_PKT(bp),
6574 				    ATTEMPT_RETRY) == JUST_RETURN) {
6575 					return;
6576 				}
6577 			} else {
6578 				mutex_exit(ST_MUTEX);
6579 				if (st_handle_start_busy(un, bp,
6580 				    ST_TRAN_BUSY_TIMEOUT, queued) == 0) {
6581 					mutex_enter(ST_MUTEX);
6582 					return;
6583 				}
6584 				/*
6585 				 * if too many retries, fail the transport
6586 				 */
6587 				mutex_enter(ST_MUTEX);
6588 			}
6589 		}
6590 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6591 		    "transport rejected %d\n", status);
6592 		bp->b_resid = bp->b_bcount;
6593 
6594 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6595 		ST_DO_ERRSTATS(un, st_transerrs);
6596 		if ((bp == un->un_recov_buf) && (status == TRAN_BUSY)) {
6597 			st_bioerror(bp, EBUSY);
6598 		} else {
6599 			st_bioerror(bp, EIO);
6600 			st_set_pe_flag(un);
6601 		}
6602 		st_done_and_mutex_exit(un, bp);
6603 		mutex_enter(ST_MUTEX);
6604 	}
6605 
6606 	ASSERT(mutex_owned(ST_MUTEX));
6607 }
6608 
6609 /*
6610  * if the transport is busy, then put this bp back on the waitq
6611  */
6612 static int
6613 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6614     clock_t timeout_interval, int queued)
6615 {
6616 
6617 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
6618 
6619 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6620 
6621 	mutex_enter(ST_MUTEX);
6622 
6623 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6624 	    "st_handle_start_busy()\n");
6625 
6626 	/*
6627 	 * Check to see if we hit the retry timeout and one last check for
6628 	 * making sure this is the last on the runq, if it is not, we have
6629 	 * to fail
6630 	 */
6631 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
6632 	    ((queued) && (un->un_runql != bp))) {
6633 		mutex_exit(ST_MUTEX);
6634 		return (-1);
6635 	}
6636 
6637 	if (queued) {
6638 		/* put the bp back on the waitq */
6639 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
6640 	}
6641 
6642 	/*
6643 	 * Decrement un_ncmds so that this
6644 	 * gets thru' st_start() again.
6645 	 */
6646 	un->un_ncmds--;
6647 
6648 	if (queued) {
6649 		/*
6650 		 * since this is an error case, we won't have to do this list
6651 		 * walking much. We've already made sure this bp was the
6652 		 * last on the runq
6653 		 */
6654 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6655 
6656 		/*
6657 		 * send a marker pkt, if appropriate
6658 		 */
6659 		st_hba_unflush(un);
6660 
6661 	}
6662 	/*
6663 	 * all queues are aligned, we are just waiting to
6664 	 * transport, don't alloc any more buf p's, when
6665 	 * st_start is reentered.
6666 	 */
6667 	(void) timeout(st_start_restart, un, timeout_interval);
6668 
6669 	mutex_exit(ST_MUTEX);
6670 	return (0);
6671 }
6672 
6673 
6674 /*
6675  * st_runout a callback that is called what a resource allocatation failed
6676  */
6677 static int
6678 st_runout(caddr_t arg)
6679 {
6680 	struct scsi_tape *un = (struct scsi_tape *)arg;
6681 	struct buf *bp;
6682 	int queued;
6683 
6684 	ASSERT(un != NULL);
6685 
6686 	ST_FUNC(ST_DEVINFO, st_runout);
6687 
6688 	mutex_enter(ST_MUTEX);
6689 
6690 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6691 
6692 	if (un->un_recov_buf_busy != 0) {
6693 		bp = un->un_recov_buf;
6694 		queued = 0;
6695 	} else if (un->un_sbuf_busy != 0) {
6696 		/* sbuf commands should only happen with an empty queue. */
6697 		ASSERT(un->un_quef == NULL);
6698 		ASSERT(un->un_runqf == NULL);
6699 		bp = un->un_sbufp;
6700 		queued = 0;
6701 	} else if (un->un_quef != NULL) {
6702 		bp = un->un_quef;
6703 		if (un->un_persistence && un->un_persist_errors) {
6704 			mutex_exit(ST_MUTEX);
6705 			bp->b_resid = bp->b_bcount;
6706 			biodone(bp);
6707 			return (1);
6708 		}
6709 		queued = 1;
6710 	} else {
6711 		ASSERT(1 == 0);
6712 		mutex_exit(ST_MUTEX);
6713 		return (1);
6714 	}
6715 
6716 	/*
6717 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6718 	 */
6719 	if ((bp != NULL) && (geterror(bp) != 0)) {
6720 
6721 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6722 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6723 		    bp->b_flags, geterror(bp));
6724 		ASSERT((bp->b_flags & B_DONE) == 0);
6725 
6726 		if (queued) {
6727 			(void) st_remove_from_queue(&un->un_quef, &un->un_quel,
6728 			    bp);
6729 		}
6730 		mutex_exit(ST_MUTEX);
6731 
6732 		ASSERT((bp->b_flags & B_DONE) == 0);
6733 
6734 		/*
6735 		 * Set resid, Error already set, then unblock calling thread.
6736 		 */
6737 		bp->b_resid = bp->b_bcount;
6738 		biodone(bp);
6739 	} else {
6740 		/*
6741 		 * Try Again
6742 		 */
6743 		st_start(un);
6744 		mutex_exit(ST_MUTEX);
6745 	}
6746 
6747 	/*
6748 	 * Comments courtesy of sd.c
6749 	 * The scsi_init_pkt routine allows for the callback function to
6750 	 * return a 0 indicating the callback should be rescheduled or a 1
6751 	 * indicating not to reschedule. This routine always returns 1
6752 	 * because the driver always provides a callback function to
6753 	 * scsi_init_pkt. This results in a callback always being scheduled
6754 	 * (via the scsi_init_pkt callback implementation) if a resource
6755 	 * failure occurs.
6756 	 */
6757 
6758 	return (1);
6759 }
6760 
6761 /*
6762  * st_done_and_mutex_exit()
6763  *	- remove bp from runq
6764  *	- start up the next request
6765  *	- if this was an asynch bp, clean up
6766  *	- exit with released mutex
6767  */
6768 static void
6769 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6770 {
6771 	int pe_flagged = 0;
6772 	struct scsi_pkt *pkt = BP_PKT(bp);
6773 	pkt_info *pktinfo = pkt->pkt_private;
6774 
6775 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6776 #if !defined(lint)
6777 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6778 #endif
6779 
6780 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6781 
6782 	ASSERT(mutex_owned(ST_MUTEX));
6783 
6784 	(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6785 
6786 	un->un_ncmds--;
6787 	cv_signal(&un->un_queue_cv);
6788 
6789 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6790 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6791 	    "0x%x\n", pkt->pkt_cdbp[0], bp->b_bcount,
6792 	    bp->b_resid, bp->b_flags);
6793 
6794 
6795 	/*
6796 	 * update kstats with transfer count info
6797 	 */
6798 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6799 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6800 		if (bp->b_flags & B_READ) {
6801 			IOSP->reads++;
6802 			IOSP->nread += n_done;
6803 		} else {
6804 			IOSP->writes++;
6805 			IOSP->nwritten += n_done;
6806 		}
6807 	}
6808 
6809 	/*
6810 	 * Start the next one before releasing resources on this one, if
6811 	 * there is something on the queue and persistent errors has not been
6812 	 * flagged
6813 	 */
6814 
6815 	if ((pe_flagged = (un->un_persistence && un->un_persist_errors)) != 0) {
6816 		un->un_last_resid = bp->b_resid;
6817 		un->un_last_count = bp->b_bcount;
6818 	}
6819 
6820 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6821 		cv_broadcast(&un->un_tape_busy_cv);
6822 	} else if (un->un_quef && un->un_throttle && !pe_flagged &&
6823 	    (bp != un->un_recov_buf)) {
6824 		st_start(un);
6825 	}
6826 
6827 	un->un_retry_ct = max(pktinfo->pkt_retry_cnt, pktinfo->str_retry_cnt);
6828 
6829 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6830 		/*
6831 		 * Since we marked this ourselves as ASYNC,
6832 		 * there isn't anybody around waiting for
6833 		 * completion any more.
6834 		 */
6835 		uchar_t *cmd = pkt->pkt_cdbp;
6836 		if (*cmd == SCMD_READ || *cmd == SCMD_WRITE) {
6837 			bp->b_un.b_addr = (caddr_t)0;
6838 		}
6839 		ST_DEBUG(ST_DEVINFO, st_label, CE_NOTE,
6840 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6841 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
6842 		    "CDB sent with B_ASYNC",  (caddr_t)cmd);
6843 		if (pkt) {
6844 			scsi_destroy_pkt(pkt);
6845 		}
6846 		un->un_sbuf_busy = 0;
6847 		cv_signal(&un->un_sbuf_cv);
6848 		mutex_exit(ST_MUTEX);
6849 		return;
6850 	}
6851 
6852 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6853 		/*
6854 		 * Copy status from scsi_pkt to uscsi_cmd
6855 		 * since st_uscsi_cmd needs it
6856 		 */
6857 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6858 	}
6859 
6860 
6861 #ifdef STDEBUG
6862 	if (((st_debug & 0x7) >= 4) &&
6863 	    (((un->un_pos.blkno % 100) == 0) ||
6864 	    (un->un_persistence && un->un_persist_errors))) {
6865 
6866 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6867 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6868 		    "un_errno = %d, un_pe = %d\n",
6869 		    un->un_ncmds, un->un_throttle, un->un_errno,
6870 		    un->un_persist_errors);
6871 	}
6872 
6873 #endif
6874 
6875 	mutex_exit(ST_MUTEX);
6876 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6877 	    "st_done_and_mutex_exit: freeing pkt\n");
6878 
6879 	if (pkt) {
6880 		scsi_destroy_pkt(pkt);
6881 	}
6882 
6883 	biodone(bp);
6884 
6885 	/*
6886 	 * now that we biodoned that command, if persistent errors have been
6887 	 * flagged, flush the waitq
6888 	 */
6889 	if (pe_flagged)
6890 		st_flush(un);
6891 }
6892 
6893 
6894 /*
6895  * Tape error, flush tape driver queue.
6896  */
6897 static void
6898 st_flush(struct scsi_tape *un)
6899 {
6900 	struct buf *bp;
6901 
6902 	ST_FUNC(ST_DEVINFO, st_flush);
6903 
6904 	mutex_enter(ST_MUTEX);
6905 
6906 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6907 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6908 	    un->un_ncmds, (void *)un->un_quef);
6909 
6910 	/*
6911 	 * if we still have commands outstanding, wait for them to come in
6912 	 * before flushing the queue, and make sure there is a queue
6913 	 */
6914 	if (un->un_ncmds || !un->un_quef)
6915 		goto exit;
6916 
6917 	/*
6918 	 * we have no more commands outstanding, so let's deal with special
6919 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6920 	 * is 0, then we know there was no error and we return a 0 read or
6921 	 * write before showing errors
6922 	 */
6923 
6924 	/* Flush the wait queue. */
6925 	while ((bp = un->un_quef) != NULL) {
6926 		un->un_quef = bp->b_actf;
6927 
6928 		bp->b_resid = bp->b_bcount;
6929 
6930 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6931 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6932 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6933 
6934 		st_set_pe_errno(un);
6935 
6936 		bioerror(bp, un->un_errno);
6937 
6938 		mutex_exit(ST_MUTEX);
6939 		/* it should have one, but check anyway */
6940 		if (BP_PKT(bp)) {
6941 			scsi_destroy_pkt(BP_PKT(bp));
6942 		}
6943 		biodone(bp);
6944 		mutex_enter(ST_MUTEX);
6945 	}
6946 
6947 	/*
6948 	 * It's not a bad practice to reset the
6949 	 * waitq tail pointer to NULL.
6950 	 */
6951 	un->un_quel = NULL;
6952 
6953 exit:
6954 	/* we mucked with the queue, so let others know about it */
6955 	cv_signal(&un->un_queue_cv);
6956 	mutex_exit(ST_MUTEX);
6957 }
6958 
6959 
6960 /*
6961  * Utility functions
6962  */
6963 static int
6964 st_determine_generic(struct scsi_tape *un)
6965 {
6966 	int bsize;
6967 	static char *cart = "0.25 inch cartridge";
6968 	char *sizestr;
6969 
6970 	ST_FUNC(ST_DEVINFO, st_determine_generic);
6971 
6972 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6973 	    "st_determine_generic(un = 0x%p)\n", (void*)un);
6974 
6975 	ASSERT(mutex_owned(ST_MUTEX));
6976 
6977 	if (st_modesense(un)) {
6978 		return (-1);
6979 	}
6980 
6981 	bsize = (un->un_mspl->high_bl << 16)	|
6982 	    (un->un_mspl->mid_bl << 8)	|
6983 	    (un->un_mspl->low_bl);
6984 
6985 	if (bsize == 0) {
6986 		un->un_dp->options |= ST_VARIABLE;
6987 		un->un_dp->bsize = 0;
6988 		un->un_bsize = 0;
6989 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
6990 		/*
6991 		 * record size of this device too big.
6992 		 * try and convert it to variable record length.
6993 		 *
6994 		 */
6995 		un->un_dp->options |= ST_VARIABLE;
6996 		if (st_change_block_size(un, 0) != 0) {
6997 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6998 			    "Fixed Record Size %d is too large\n", bsize);
6999 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7000 			    "Cannot switch to variable record size\n");
7001 			un->un_dp->options &= ~ST_VARIABLE;
7002 			return (-1);
7003 		}
7004 	} else if (st_change_block_size(un, 0) == 0) {
7005 		/*
7006 		 * If the drive was set to a non zero block size,
7007 		 * See if it can be set to a zero block size.
7008 		 * If it works, ST_VARIABLE so user can set it as they want.
7009 		 */
7010 		un->un_dp->options |= ST_VARIABLE;
7011 		un->un_dp->bsize = 0;
7012 		un->un_bsize = 0;
7013 	} else {
7014 		un->un_dp->bsize = bsize;
7015 		un->un_bsize = bsize;
7016 	}
7017 
7018 
7019 	switch (un->un_mspl->density) {
7020 	default:
7021 	case 0x0:
7022 		/*
7023 		 * default density, cannot determine any other
7024 		 * information.
7025 		 */
7026 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
7027 		un->un_dp->type = ST_TYPE_DEFAULT;
7028 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
7029 		break;
7030 	case 0x1:
7031 	case 0x2:
7032 	case 0x3:
7033 	case 0x6:
7034 		/*
7035 		 * 1/2" reel
7036 		 */
7037 		sizestr = "0.50 inch reel";
7038 		un->un_dp->type = ST_TYPE_REEL;
7039 		un->un_dp->options |= ST_REEL;
7040 		un->un_dp->densities[0] = 0x1;
7041 		un->un_dp->densities[1] = 0x2;
7042 		un->un_dp->densities[2] = 0x6;
7043 		un->un_dp->densities[3] = 0x3;
7044 		break;
7045 	case 0x4:
7046 	case 0x5:
7047 	case 0x7:
7048 	case 0x0b:
7049 
7050 		/*
7051 		 * Quarter inch.
7052 		 */
7053 		sizestr = cart;
7054 		un->un_dp->type = ST_TYPE_DEFAULT;
7055 		un->un_dp->options |= ST_QIC;
7056 
7057 		un->un_dp->densities[1] = 0x4;
7058 		un->un_dp->densities[2] = 0x5;
7059 		un->un_dp->densities[3] = 0x7;
7060 		un->un_dp->densities[0] = 0x0b;
7061 		break;
7062 
7063 	case 0x0f:
7064 	case 0x10:
7065 	case 0x11:
7066 	case 0x12:
7067 		/*
7068 		 * QIC-120, QIC-150, QIC-320, QIC-600
7069 		 */
7070 		sizestr = cart;
7071 		un->un_dp->type = ST_TYPE_DEFAULT;
7072 		un->un_dp->options |= ST_QIC;
7073 		un->un_dp->densities[0] = 0x0f;
7074 		un->un_dp->densities[1] = 0x10;
7075 		un->un_dp->densities[2] = 0x11;
7076 		un->un_dp->densities[3] = 0x12;
7077 		break;
7078 
7079 	case 0x09:
7080 	case 0x0a:
7081 	case 0x0c:
7082 	case 0x0d:
7083 		/*
7084 		 * 1/2" cartridge tapes. Include HI-TC.
7085 		 */
7086 		sizestr = cart;
7087 		sizestr[2] = '5';
7088 		sizestr[3] = '0';
7089 		un->un_dp->type = ST_TYPE_HIC;
7090 		un->un_dp->densities[0] = 0x09;
7091 		un->un_dp->densities[1] = 0x0a;
7092 		un->un_dp->densities[2] = 0x0c;
7093 		un->un_dp->densities[3] = 0x0d;
7094 		break;
7095 
7096 	case 0x13:
7097 			/* DDS-2/DDS-3 scsi spec densities */
7098 	case 0x24:
7099 	case 0x25:
7100 	case 0x26:
7101 		sizestr = "DAT Data Storage (DDS)";
7102 		un->un_dp->type = ST_TYPE_DAT;
7103 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7104 		break;
7105 
7106 	case 0x14:
7107 		/*
7108 		 * Helical Scan (Exabyte) devices
7109 		 */
7110 		sizestr = "8mm helical scan cartridge";
7111 		un->un_dp->type = ST_TYPE_EXABYTE;
7112 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7113 		break;
7114 	}
7115 
7116 	/*
7117 	 * Assume LONG ERASE, BSF and BSR
7118 	 */
7119 
7120 	un->un_dp->options |=
7121 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
7122 
7123 	/*
7124 	 * Only if mode sense data says no buffered write, set NOBUF
7125 	 */
7126 	if (un->un_mspl->bufm == 0)
7127 		un->un_dp->options |= ST_NOBUF;
7128 
7129 	/*
7130 	 * set up large read and write retry counts
7131 	 */
7132 
7133 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
7134 
7135 	/*
7136 	 * If this is a 0.50 inch reel tape, and
7137 	 * it is *not* variable mode, try and
7138 	 * set it to variable record length
7139 	 * mode.
7140 	 */
7141 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
7142 	    (un->un_dp->options & ST_VARIABLE)) {
7143 		if (st_change_block_size(un, 0) == 0) {
7144 			un->un_dp->bsize = 0;
7145 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
7146 			    un->un_mspl->low_bl = 0;
7147 		}
7148 	}
7149 
7150 	/*
7151 	 * Write to console about type of device found
7152 	 */
7153 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
7154 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
7155 	    sizestr);
7156 	if (un->un_dp->options & ST_VARIABLE) {
7157 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7158 		    "!Variable record length I/O\n");
7159 	} else {
7160 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7161 		    "!Fixed record length (%d byte blocks) I/O\n",
7162 		    un->un_dp->bsize);
7163 	}
7164 	ASSERT(mutex_owned(ST_MUTEX));
7165 	return (0);
7166 }
7167 
7168 static int
7169 st_determine_density(struct scsi_tape *un, int rw)
7170 {
7171 	int rval = 0;
7172 
7173 	ST_FUNC(ST_DEVINFO, st_determine_density);
7174 
7175 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7176 	    "st_determine_density(un = 0x%p, rw = %s)\n",
7177 	    (void*)un, (rw == B_WRITE ? wr_str: rd_str));
7178 
7179 	ASSERT(mutex_owned(ST_MUTEX));
7180 
7181 	/*
7182 	 * If we're past BOT, density is determined already.
7183 	 */
7184 	if (un->un_pos.pmode == logical) {
7185 		if (un->un_pos.lgclblkno != 0) {
7186 			goto exit;
7187 		}
7188 	} else if (un->un_pos.pmode == legacy) {
7189 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
7190 			/*
7191 			 * XXX: put in a bitch message about attempting to
7192 			 * XXX: change density past BOT.
7193 			 */
7194 			goto exit;
7195 		}
7196 	} else {
7197 		goto exit;
7198 	}
7199 	if ((un->un_pos.pmode == logical) &&
7200 	    (un->un_pos.lgclblkno != 0)) {
7201 		goto exit;
7202 	}
7203 
7204 
7205 	/*
7206 	 * If we're going to be writing, we set the density
7207 	 */
7208 	if (rw == 0 || rw == B_WRITE) {
7209 		/* un_curdens is used as an index into densities table */
7210 		un->un_curdens = MT_DENSITY(un->un_dev);
7211 		if (st_set_density(un)) {
7212 			rval = -1;
7213 		}
7214 		goto exit;
7215 	}
7216 
7217 	/*
7218 	 * If density is known already,
7219 	 * we don't have to get it again.(?)
7220 	 */
7221 	if (!un->un_density_known) {
7222 		if (st_get_density(un)) {
7223 			rval = -1;
7224 		}
7225 	}
7226 
7227 exit:
7228 	ASSERT(mutex_owned(ST_MUTEX));
7229 	return (rval);
7230 }
7231 
7232 
7233 /*
7234  * Try to determine density. We do this by attempting to read the
7235  * first record off the tape, cycling through the available density
7236  * codes as we go.
7237  */
7238 
7239 static int
7240 st_get_density(struct scsi_tape *un)
7241 {
7242 	int succes = 0, rval = -1, i;
7243 	uint_t size;
7244 	uchar_t dens, olddens;
7245 
7246 	ST_FUNC(ST_DEVINFO, st_get_density);
7247 
7248 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7249 	    "st_get_density(un = 0x%p)\n", (void*)un);
7250 
7251 	ASSERT(mutex_owned(ST_MUTEX));
7252 
7253 	/*
7254 	 * If Auto Density override is enabled The drive has
7255 	 * only one density and there is no point in attempting
7256 	 * find the correct one.
7257 	 *
7258 	 * Since most modern drives auto detect the density
7259 	 * and format of the recorded media before they come
7260 	 * ready. What this function does is a legacy behavior
7261 	 * and modern drives not only don't need it, The backup
7262 	 * utilities that do positioning via uscsi find the un-
7263 	 * expected rewinds problematic.
7264 	 *
7265 	 * The drives that need this are old reel to reel devices.
7266 	 * I took a swag and said they must be scsi-1 or older.
7267 	 * I don't beleave there will any of the newer devices
7268 	 * that need this. There will be some scsi-1 devices that
7269 	 * don't need this but I don't think they will be using the
7270 	 * BIG aftermarket backup and restore utilitys.
7271 	 */
7272 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
7273 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
7274 		un->un_density_known = 1;
7275 		rval = 0;
7276 		goto exit;
7277 	}
7278 
7279 	/*
7280 	 * This will only work on variable record length tapes
7281 	 * if and only if all variable record length tapes autodensity
7282 	 * select.
7283 	 */
7284 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
7285 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
7286 
7287 	/*
7288 	 * Start at the specified density
7289 	 */
7290 
7291 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
7292 
7293 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
7294 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
7295 		/*
7296 		 * If we've done this density before,
7297 		 * don't bother to do it again.
7298 		 */
7299 		dens = un->un_dp->densities[un->un_curdens];
7300 		if (i > 0 && dens == olddens)
7301 			continue;
7302 		olddens = dens;
7303 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7304 		    "trying density 0x%x\n", dens);
7305 		if (st_set_density(un)) {
7306 			continue;
7307 		}
7308 
7309 		/*
7310 		 * XXX - the creates lots of headaches and slowdowns - must
7311 		 * fix.
7312 		 */
7313 		succes = (st_cmd(un, SCMD_READ, (int)size, SYNC_CMD) == 0);
7314 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
7315 			break;
7316 		}
7317 		if (succes) {
7318 			st_init(un);
7319 			rval = 0;
7320 			un->un_density_known = 1;
7321 			break;
7322 		}
7323 	}
7324 	kmem_free(un->un_tmpbuf, size);
7325 	un->un_tmpbuf = 0;
7326 
7327 exit:
7328 	ASSERT(mutex_owned(ST_MUTEX));
7329 	return (rval);
7330 }
7331 
7332 static int
7333 st_set_density(struct scsi_tape *un)
7334 {
7335 	int rval = 0;
7336 
7337 	ST_FUNC(ST_DEVINFO, st_set_density);
7338 
7339 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7340 	    "st_set_density(un = 0x%p): density = 0x%x\n", (void*)un,
7341 	    un->un_dp->densities[un->un_curdens]);
7342 
7343 	ASSERT(mutex_owned(ST_MUTEX));
7344 
7345 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7346 
7347 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
7348 		/*
7349 		 * If auto density override is not set, Use mode select
7350 		 * to set density and compression.
7351 		 */
7352 		if (st_modeselect(un)) {
7353 			rval = -1;
7354 		}
7355 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
7356 		/*
7357 		 * If auto density and mode select compression are set,
7358 		 * This is a drive with one density code but compression
7359 		 * can be enabled or disabled.
7360 		 * Set compression but no need to set density.
7361 		 */
7362 		rval = st_set_compression(un);
7363 		if ((rval != 0) && (rval != EALREADY)) {
7364 			rval = -1;
7365 		} else {
7366 			rval = 0;
7367 		}
7368 	}
7369 
7370 	/* If sucessful set density and/or compression, mark density known */
7371 	if (rval == 0) {
7372 		un->un_density_known = 1;
7373 	}
7374 
7375 	ASSERT(mutex_owned(ST_MUTEX));
7376 	return (rval);
7377 }
7378 
7379 static int
7380 st_loadtape(struct scsi_tape *un)
7381 {
7382 	int rval;
7383 
7384 	ST_FUNC(ST_DEVINFO, st_loadtape);
7385 
7386 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7387 	    "st_loadtape(un = 0x%p)\n", (void*) un);
7388 
7389 	ASSERT(mutex_owned(ST_MUTEX));
7390 
7391 	rval = st_update_block_pos(un, st_cmd, 0);
7392 	if (rval == EACCES) {
7393 		return (rval);
7394 	}
7395 
7396 	/*
7397 	 * 'LOAD' the tape to BOT by rewinding
7398 	 */
7399 	rval = st_cmd(un, SCMD_REWIND, 1, SYNC_CMD);
7400 	if (rval == 0) {
7401 		st_init(un);
7402 		un->un_density_known = 0;
7403 	}
7404 
7405 	ASSERT(mutex_owned(ST_MUTEX));
7406 	return (rval);
7407 }
7408 
7409 
7410 /*
7411  * Note: QIC devices aren't so smart.  If you try to append
7412  * after EOM, the write can fail because the device doesn't know
7413  * it's at EOM.	 In that case, issue a read.  The read should fail
7414  * because there's no data, but the device knows it's at EOM,
7415  * so a subsequent write should succeed.  To further confuse matters,
7416  * the target returns the same error if the tape is positioned
7417  * such that a write would overwrite existing data.  That's why
7418  * we have to do the append test.  A read in the middle of
7419  * recorded data would succeed, thus indicating we're attempting
7420  * something illegal.
7421  */
7422 
7423 
7424 static void
7425 st_test_append(struct buf *bp)
7426 {
7427 	dev_t dev = bp->b_edev;
7428 	struct scsi_tape *un;
7429 	uchar_t status;
7430 	unsigned bcount;
7431 
7432 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7433 
7434 	ST_FUNC(ST_DEVINFO, st_test_append);
7435 
7436 	ASSERT(mutex_owned(ST_MUTEX));
7437 
7438 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7439 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7440 
7441 	un->un_laststate = un->un_state;
7442 	un->un_state = ST_STATE_APPEND_TESTING;
7443 	un->un_test_append = 0;
7444 
7445 	/*
7446 	 * first, map in the buffer, because we're doing a double write --
7447 	 * first into the kernel, then onto the tape.
7448 	 */
7449 	bp_mapin(bp);
7450 
7451 	/*
7452 	 * get a copy of the data....
7453 	 */
7454 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7455 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7456 
7457 	/*
7458 	 * attempt the write..
7459 	 */
7460 
7461 	if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7462 success:
7463 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7464 		    "append write succeeded\n");
7465 		bp->b_resid = un->un_sbufp->b_resid;
7466 		mutex_exit(ST_MUTEX);
7467 		bcount = (unsigned)bp->b_bcount;
7468 		biodone(bp);
7469 		mutex_enter(ST_MUTEX);
7470 		un->un_laststate = un->un_state;
7471 		un->un_state = ST_STATE_OPEN;
7472 		kmem_free(un->un_tmpbuf, bcount);
7473 		un->un_tmpbuf = NULL;
7474 		return;
7475 	}
7476 
7477 	/*
7478 	 * The append failed. Do a short read. If that fails,  we are at EOM
7479 	 * so we can retry the write command. If that succeeds, than we're
7480 	 * all screwed up (the controller reported a real error).
7481 	 *
7482 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7483 	 * XXX: block size?
7484 	 *
7485 	 */
7486 	status = un->un_status;
7487 	un->un_status = 0;
7488 	(void) st_cmd(un, SCMD_READ, SECSIZE, SYNC_CMD);
7489 	if (un->un_status == KEY_BLANK_CHECK) {
7490 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7491 		    "append at EOM\n");
7492 		/*
7493 		 * Okay- the read failed. We should actually have confused
7494 		 * the controller enough to allow writing. In any case, the
7495 		 * i/o is on its own from here on out.
7496 		 */
7497 		un->un_laststate = un->un_state;
7498 		un->un_state = ST_STATE_OPEN;
7499 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7500 		if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount,
7501 		    SYNC_CMD) == 0) {
7502 			goto success;
7503 		}
7504 	}
7505 
7506 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7507 	    "append write failed- not at EOM\n");
7508 	bp->b_resid = bp->b_bcount;
7509 	st_bioerror(bp, EIO);
7510 
7511 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7512 	    "st_test_append : EIO : append write failed - not at EOM");
7513 
7514 	/*
7515 	 * backspace one record to get back to where we were
7516 	 */
7517 	if (st_cmd(un, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7518 		un->un_pos.pmode = invalid;
7519 	}
7520 
7521 	un->un_err_resid = bp->b_resid;
7522 	un->un_status = status;
7523 
7524 	/*
7525 	 * Note: biodone will do a bp_mapout()
7526 	 */
7527 	mutex_exit(ST_MUTEX);
7528 	bcount = (unsigned)bp->b_bcount;
7529 	biodone(bp);
7530 	mutex_enter(ST_MUTEX);
7531 	un->un_laststate = un->un_state;
7532 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7533 	kmem_free(un->un_tmpbuf, bcount);
7534 	un->un_tmpbuf = NULL;
7535 }
7536 
7537 /*
7538  * Special command handler
7539  */
7540 
7541 /*
7542  * common st_cmd code. The fourth parameter states
7543  * whether the caller wishes to await the results
7544  * Note the release of the mutex during most of the function
7545  */
7546 static int
7547 st_cmd(struct scsi_tape *un, int com, int64_t count, int wait)
7548 {
7549 	struct buf *bp;
7550 	int err;
7551 	uint_t last_err_resid;
7552 
7553 	ST_FUNC(ST_DEVINFO, st_cmd);
7554 
7555 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7556 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %"PRIx64", wait = %d)\n",
7557 	    un->un_dev, com, count, wait);
7558 
7559 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7560 	ASSERT(mutex_owned(ST_MUTEX));
7561 
7562 #ifdef STDEBUG
7563 	if ((st_debug & 0x7)) {
7564 		st_debug_cmds(un, com, count, wait);
7565 	}
7566 #endif
7567 
7568 	st_wait_for_io(un);
7569 
7570 	/* check to see if this command requires the drive to be reserved */
7571 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7572 
7573 	if (err) {
7574 		return (err);
7575 	}
7576 
7577 	/*
7578 	 * A space command is not recoverable if we don't know were we
7579 	 * were when it was issued.
7580 	 */
7581 	if ((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) {
7582 		(void) st_update_block_pos(un, st_cmd, 0);
7583 	}
7584 
7585 	/*
7586 	 * Forground should not be doing anything while recovery is active.
7587 	 */
7588 	ASSERT(un->un_recov_buf_busy == 0);
7589 
7590 	while (un->un_sbuf_busy)
7591 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7592 	un->un_sbuf_busy = 1;
7593 
7594 	bp = un->un_sbufp;
7595 	bzero(bp, sizeof (buf_t));
7596 
7597 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7598 
7599 	err = st_setup_cmd(un, bp, com, count);
7600 
7601 	un->un_sbuf_busy = 0;
7602 
7603 	/*
7604 	 * If was a space command need to update logical block position.
7605 	 * Only do this if the command was sucessful or it will mask the fact
7606 	 * that the space command failed by promoting the pmode to logical.
7607 	 */
7608 	if (((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) &&
7609 	    (un->un_pos.pmode != invalid)) {
7610 		un->un_running.pmode = invalid;
7611 		last_err_resid = un->un_err_resid;
7612 		(void) st_update_block_pos(un, st_cmd, 1);
7613 		/*
7614 		 * Set running position to invalid so it updates on the
7615 		 * next command.
7616 		 */
7617 		un->un_running.pmode = invalid;
7618 		un->un_err_resid = last_err_resid;
7619 	}
7620 
7621 	cv_signal(&un->un_sbuf_cv);
7622 
7623 	return (err);
7624 }
7625 
7626 static int
7627 st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com, int64_t count)
7628 {
7629 	int err;
7630 	dev_t dev = un->un_dev;
7631 
7632 	ST_FUNC(ST_DEVINFO, st_setup_cmd);
7633 	/*
7634 	 * Set count to the actual size of the data tranfer.
7635 	 * For commands with no data transfer, set bp->b_bcount
7636 	 * to the value to be used when constructing the
7637 	 * cdb in st_make_cmd().
7638 	 */
7639 	switch (com) {
7640 	case SCMD_READ:
7641 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7642 		    "special read %"PRId64"\n", count);
7643 		bp->b_flags |= B_READ;
7644 		bp->b_un.b_addr = un->un_tmpbuf;
7645 		break;
7646 
7647 	case SCMD_WRITE:
7648 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7649 		    "special write %"PRId64"\n", count);
7650 		bp->b_un.b_addr = un->un_tmpbuf;
7651 		break;
7652 
7653 	case SCMD_WRITE_FILE_MARK:
7654 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7655 		    "write %"PRId64" file marks\n", count);
7656 		bp->b_bcount = count;
7657 		count = 0;
7658 		break;
7659 
7660 	case SCMD_REWIND:
7661 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7662 		bp->b_bcount = count;
7663 		count = 0;
7664 		break;
7665 
7666 	case SCMD_SPACE:
7667 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7668 		/*
7669 		 * If the user could have entered a number that will
7670 		 * not fit in the 12 bit count field of space(8),
7671 		 * use space(16).
7672 		 */
7673 		if (((int64_t)SPACE_CNT(count) > 0x7fffff) ||
7674 		    ((int64_t)SPACE_CNT(count) < -(0x7fffff))) {
7675 			com = SCMD_SPACE_G4;
7676 		}
7677 		bp->b_bcount = count;
7678 		count = 0;
7679 		break;
7680 
7681 	case SCMD_RESERVE:
7682 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7683 		bp->b_bcount = 0;
7684 		count = 0;
7685 		break;
7686 
7687 	case SCMD_RELEASE:
7688 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7689 		bp->b_bcount = 0;
7690 		count = 0;
7691 		break;
7692 
7693 	case SCMD_LOAD:
7694 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7695 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7696 		bp->b_bcount = count;
7697 		count = 0;
7698 		break;
7699 
7700 	case SCMD_ERASE:
7701 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7702 		    "erase tape\n");
7703 		bp->b_bcount = count;
7704 		count = 0;
7705 		break;
7706 
7707 	case SCMD_MODE_SENSE:
7708 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7709 		    "mode sense\n");
7710 		bp->b_flags |= B_READ;
7711 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7712 		break;
7713 
7714 	case SCMD_MODE_SELECT:
7715 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7716 		    "mode select\n");
7717 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7718 		break;
7719 
7720 	case SCMD_READ_BLKLIM:
7721 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7722 		    "read block limits\n");
7723 		bp->b_bcount = count;
7724 		bp->b_flags |= B_READ;
7725 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7726 		break;
7727 
7728 	case SCMD_TEST_UNIT_READY:
7729 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7730 		    "test unit ready\n");
7731 		bp->b_bcount = 0;
7732 		count = 0;
7733 		break;
7734 
7735 	case SCMD_DOORLOCK:
7736 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7737 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7738 		bp->b_bcount = count = 0;
7739 		break;
7740 
7741 	case SCMD_READ_POSITION:
7742 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7743 		    "read position\n");
7744 		switch (un->un_read_pos_type) {
7745 		case LONG_POS:
7746 			count = sizeof (tape_position_long_t);
7747 			break;
7748 		case EXT_POS:
7749 			count = min(count, sizeof (tape_position_ext_t));
7750 			break;
7751 		case SHORT_POS:
7752 			count = sizeof (tape_position_t);
7753 			break;
7754 		default:
7755 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7756 			    "Unknown read position type 0x%x in "
7757 			    "st_make_cmd()\n", un->un_read_pos_type);
7758 		}
7759 		bp->b_bcount = count;
7760 		bp->b_flags |= B_READ;
7761 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7762 		break;
7763 
7764 	default:
7765 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7766 		    "Unhandled scsi command 0x%x in st_setup_cmd()\n", com);
7767 	}
7768 
7769 	mutex_exit(ST_MUTEX);
7770 
7771 	if (count > 0) {
7772 		int flg = (bp->b_flags & B_READ) ? B_READ : B_WRITE;
7773 		/*
7774 		 * We're going to do actual I/O.
7775 		 * Set things up for physio.
7776 		 */
7777 		struct iovec aiov;
7778 		struct uio auio;
7779 		struct uio *uio = &auio;
7780 
7781 		bzero(&auio, sizeof (struct uio));
7782 		bzero(&aiov, sizeof (struct iovec));
7783 		aiov.iov_base = bp->b_un.b_addr;
7784 		aiov.iov_len = count;
7785 
7786 		uio->uio_iov = &aiov;
7787 		uio->uio_iovcnt = 1;
7788 		uio->uio_resid = aiov.iov_len;
7789 		uio->uio_segflg = UIO_SYSSPACE;
7790 
7791 		/*
7792 		 * Let physio do the rest...
7793 		 */
7794 		bp->b_forw = (struct buf *)(uintptr_t)com;
7795 		bp->b_back = NULL;
7796 		err = physio(st_strategy, bp, dev, flg, st_minphys, uio);
7797 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7798 		    "st_setup_cmd: physio returns %d\n", err);
7799 	} else {
7800 		/*
7801 		 * Mimic physio
7802 		 */
7803 		bp->b_forw = (struct buf *)(uintptr_t)com;
7804 		bp->b_back = NULL;
7805 		bp->b_edev = dev;
7806 		bp->b_dev = cmpdev(dev);
7807 		bp->b_blkno = 0;
7808 		bp->b_resid = 0;
7809 		(void) st_strategy(bp);
7810 		if (bp->b_flags & B_ASYNC) {
7811 			/*
7812 			 * This is an async command- the caller won't wait
7813 			 * and doesn't care about errors.
7814 			 */
7815 			mutex_enter(ST_MUTEX);
7816 			return (0);
7817 		}
7818 
7819 		/*
7820 		 * BugTraq #4260046
7821 		 * ----------------
7822 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7823 		 * unconditionally. The old comment said...
7824 		 *
7825 		 * "if strategy was flagged with  persistent errors, we would
7826 		 *  have an error here, and the bp would never be sent, so we
7827 		 *  don't want to wait on a bp that was never sent...or hang"
7828 		 *
7829 		 * The new rationale, courtesy of Chitrank...
7830 		 *
7831 		 * "we should unconditionally biowait() here because
7832 		 *  st_strategy() will do a biodone() in the persistent error
7833 		 *  case and the following biowait() will return immediately.
7834 		 *  If not, in the case of "errors after pkt alloc" in
7835 		 *  st_start(), we will not biowait here which will cause the
7836 		 *  next biowait() to return immediately which will cause
7837 		 *  us to send out the next command. In the case where both of
7838 		 *  these use the sbuf, when the first command completes we'll
7839 		 *  free the packet attached to sbuf and the same pkt will
7840 		 *  get freed again when we complete the second command.
7841 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7842 		 *  st_start() for the pkt alloc failure case because physio()
7843 		 *  does biowait() and will hang if we don't do biodone()"
7844 		 */
7845 
7846 		err = biowait(bp);
7847 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7848 		    "st_setup_cmd: biowait returns %d\n", err);
7849 	}
7850 
7851 	mutex_enter(ST_MUTEX);
7852 
7853 	return (err);
7854 }
7855 
7856 static int
7857 st_set_compression(struct scsi_tape *un)
7858 {
7859 	int rval;
7860 	int turn_compression_on;
7861 	minor_t minor;
7862 
7863 	ST_FUNC(ST_DEVINFO, st_set_compression);
7864 
7865 	/*
7866 	 * Drive either dosn't have compression or it is controlled with
7867 	 * special density codes. Return ENOTTY so caller
7868 	 * knows nothing was done.
7869 	 */
7870 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7871 		un->un_comp_page = 0;
7872 		return (ENOTTY);
7873 	}
7874 
7875 	/* set compression based on minor node opened */
7876 	minor = MT_DENSITY(un->un_dev);
7877 
7878 	/*
7879 	 * If this the compression density or
7880 	 * the drive has two densities and uses mode select for
7881 	 * control of compression turn on compression for MT_DENSITY2
7882 	 * as well.
7883 	 */
7884 	if ((minor == ST_COMPRESSION_DENSITY) ||
7885 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7886 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7887 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7888 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7889 
7890 		turn_compression_on = 1;
7891 	} else {
7892 		turn_compression_on = 0;
7893 	}
7894 
7895 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7896 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7897 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7898 
7899 	/*
7900 	 * Need to determine which page does the device use for compression.
7901 	 * First try the data compression page. If this fails try the device
7902 	 * configuration page
7903 	 */
7904 
7905 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7906 		rval = st_set_datacomp_page(un, turn_compression_on);
7907 		if (rval == EALREADY) {
7908 			return (rval);
7909 		}
7910 		if (rval != 0) {
7911 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7912 				/*
7913 				 * This device does not support data
7914 				 * compression page
7915 				 */
7916 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7917 			} else if (un->un_state >= ST_STATE_OPEN) {
7918 				un->un_pos.pmode = invalid;
7919 				rval = EIO;
7920 			} else {
7921 				rval = -1;
7922 			}
7923 		} else {
7924 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7925 		}
7926 	}
7927 
7928 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7929 		rval = st_set_devconfig_page(un, turn_compression_on);
7930 		if (rval == EALREADY) {
7931 			return (rval);
7932 		}
7933 		if (rval != 0) {
7934 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7935 				/*
7936 				 * This device does not support
7937 				 * compression at all advice the
7938 				 * user and unset ST_MODE_SEL_COMP
7939 				 */
7940 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7941 				un->un_comp_page = 0;
7942 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7943 				    "Device Does Not Support Compression\n");
7944 			} else if (un->un_state >= ST_STATE_OPEN) {
7945 				un->un_pos.pmode = invalid;
7946 				rval = EIO;
7947 			} else {
7948 				rval = -1;
7949 			}
7950 		}
7951 	}
7952 
7953 	return (rval);
7954 }
7955 
7956 /*
7957  * set or unset compression thru device configuration page.
7958  */
7959 static int
7960 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
7961 {
7962 	unsigned char cflag;
7963 	int rval = 0;
7964 
7965 
7966 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
7967 
7968 	ASSERT(mutex_owned(ST_MUTEX));
7969 	/*
7970 	 * Figure what to set compression flag to.
7971 	 */
7972 	if (compression_on) {
7973 		/* They have selected a compression node */
7974 		if (un->un_dp->type == ST_TYPE_FUJI) {
7975 			cflag = 0x84;   /* use EDRC */
7976 		} else {
7977 			cflag = ST_DEV_CONFIG_DEF_COMP;
7978 		}
7979 	} else {
7980 		cflag = ST_DEV_CONFIG_NO_COMP;
7981 	}
7982 
7983 	/*
7984 	 * If compression is already set the way it was requested.
7985 	 * And if this not the first time we has tried.
7986 	 */
7987 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
7988 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7989 		return (EALREADY);
7990 	}
7991 
7992 	un->un_mspl->page.dev.comp_alg = cflag;
7993 	/*
7994 	 * need to send mode select even if correct compression is
7995 	 * already set since need to set density code
7996 	 */
7997 
7998 #ifdef STDEBUG
7999 	if ((st_debug & 0x7) >= 6) {
8000 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8001 		    "st_set_devconfig_page: sense data for mode select",
8002 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8003 	}
8004 #endif
8005 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8006 	    sizeof (struct seq_mode));
8007 
8008 	return (rval);
8009 }
8010 
8011 /*
8012  * set/reset compression bit thru data compression page
8013  */
8014 static int
8015 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
8016 {
8017 	int compression_on_already;
8018 	int rval = 0;
8019 
8020 
8021 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
8022 
8023 	ASSERT(mutex_owned(ST_MUTEX));
8024 	/*
8025 	 * If drive is not capable of compression (at this time)
8026 	 * return EALREADY so caller doesn't think that this page
8027 	 * is not supported. This check is for drives that can
8028 	 * disable compression from the front panel or configuration.
8029 	 * I doubt that a drive that supports this page is not really
8030 	 * capable of compression.
8031 	 */
8032 	if (un->un_mspl->page.comp.dcc == 0) {
8033 		return (EALREADY);
8034 	}
8035 
8036 	/* See if compression currently turned on */
8037 	if (un->un_mspl->page.comp.dce) {
8038 		compression_on_already = 1;
8039 	} else {
8040 		compression_on_already = 0;
8041 	}
8042 
8043 	/*
8044 	 * If compression is already set the way it was requested.
8045 	 * And if this not the first time we has tried.
8046 	 */
8047 	if ((compression_on == compression_on_already) &&
8048 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
8049 		return (EALREADY);
8050 	}
8051 
8052 	/*
8053 	 * if we are already set to the appropriate compression
8054 	 * mode, don't set it again
8055 	 */
8056 	if (compression_on) {
8057 		/* compression selected */
8058 		un->un_mspl->page.comp.dce = 1;
8059 	} else {
8060 		un->un_mspl->page.comp.dce = 0;
8061 	}
8062 
8063 
8064 #ifdef STDEBUG
8065 	if ((st_debug & 0x7) >= 6) {
8066 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8067 		    "st_set_datacomp_page: sense data for mode select",
8068 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8069 	}
8070 #endif
8071 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8072 	    sizeof (struct seq_mode));
8073 
8074 	return (rval);
8075 }
8076 
8077 static int
8078 st_modesense(struct scsi_tape *un)
8079 {
8080 	int rval;
8081 	uchar_t page;
8082 
8083 	ST_FUNC(ST_DEVINFO, st_modesense);
8084 
8085 	page = un->un_comp_page;
8086 
8087 	switch (page) {
8088 	case ST_DEV_DATACOMP_PAGE:
8089 	case ST_DEV_CONFIG_PAGE: /* FALLTHROUGH */
8090 		rval = st_gen_mode_sense(un, st_uscsi_cmd, page, un->un_mspl,
8091 		    sizeof (struct seq_mode));
8092 		break;
8093 
8094 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
8095 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
8096 			page = ST_DEV_CONFIG_PAGE;
8097 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8098 			    un->un_mspl, sizeof (struct seq_mode));
8099 			if (rval == 0 && un->un_mspl->page_code == page) {
8100 				un->un_comp_page = page;
8101 				break;
8102 			}
8103 			page = ST_DEV_DATACOMP_PAGE;
8104 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8105 			    un->un_mspl, sizeof (struct seq_mode));
8106 			if (rval == 0 && un->un_mspl->page_code == page) {
8107 				un->un_comp_page = page;
8108 				break;
8109 			}
8110 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
8111 			un->un_comp_page = 0;
8112 		} else {
8113 			un->un_comp_page = 0;
8114 		}
8115 
8116 	default:	/* FALLTHROUGH */
8117 		rval = st_cmd(un, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
8118 	}
8119 	return (rval);
8120 }
8121 
8122 static int
8123 st_modeselect(struct scsi_tape *un)
8124 {
8125 	int rval = 0;
8126 	int ix;
8127 
8128 	ST_FUNC(ST_DEVINFO, st_modeselect);
8129 
8130 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8131 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
8132 	    un->un_dev, un->un_mspl->density);
8133 
8134 	ASSERT(mutex_owned(ST_MUTEX));
8135 
8136 	/*
8137 	 * The parameter list should be the same for all of the
8138 	 * cases that follow so set them here
8139 	 *
8140 	 * Try mode select first if if fails set fields manually
8141 	 */
8142 	rval = st_modesense(un);
8143 	if (rval != 0) {
8144 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8145 		    "st_modeselect: First mode sense failed\n");
8146 		un->un_mspl->bd_len  = 8;
8147 		un->un_mspl->high_nb = 0;
8148 		un->un_mspl->mid_nb  = 0;
8149 		un->un_mspl->low_nb  = 0;
8150 	}
8151 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
8152 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
8153 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
8154 
8155 
8156 	/*
8157 	 * If configured to use a specific density code for a media type.
8158 	 * curdens is previously set by the minor node opened.
8159 	 * If the media type doesn't match the minor node we change it so it
8160 	 * looks like the correct one was opened.
8161 	 */
8162 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
8163 		uchar_t best;
8164 
8165 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
8166 			if (un->un_mspl->media_type ==
8167 			    un->un_dp->mediatype[ix]) {
8168 				best = ix;
8169 				/*
8170 				 * It matches but it might not be the only one.
8171 				 * Use the highest matching media type but not
8172 				 * to exceed the density selected by the open.
8173 				 */
8174 				if (ix < un->un_curdens) {
8175 					continue;
8176 				}
8177 				un->un_curdens = ix;
8178 				break;
8179 			}
8180 		}
8181 		/* If a match was found best will not be 0xff any more */
8182 		if (best < NDENSITIES) {
8183 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8184 			    "found media 0x%X using density 0x%X\n",
8185 			    un->un_mspl->media_type,
8186 			    un->un_dp->densities[best]);
8187 			un->un_mspl->density = un->un_dp->densities[best];
8188 		} else {
8189 			/* Otherwise set density based on minor node opened */
8190 			un->un_mspl->density =
8191 			    un->un_dp->densities[un->un_curdens];
8192 		}
8193 	} else {
8194 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
8195 	}
8196 
8197 	if (un->un_dp->options & ST_NOBUF) {
8198 		un->un_mspl->bufm = 0;
8199 	} else {
8200 		un->un_mspl->bufm = 1;
8201 	}
8202 
8203 	rval = st_set_compression(un);
8204 
8205 	/*
8206 	 * If st_set_compression returned invalid or already it
8207 	 * found no need to do the mode select.
8208 	 * So do it here.
8209 	 */
8210 	if ((rval == ENOTTY) || (rval == EALREADY)) {
8211 
8212 		/* Zero non-writeable fields */
8213 		un->un_mspl->data_len = 0;
8214 		un->un_mspl->media_type = 0;
8215 		un->un_mspl->wp = 0;
8216 
8217 		/* need to set the density code */
8218 		rval = st_cmd(un, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
8219 		if (rval != 0) {
8220 			if (un->un_state >= ST_STATE_OPEN) {
8221 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8222 				    "unable to set tape mode\n");
8223 				un->un_pos.pmode = invalid;
8224 				rval = EIO;
8225 			} else {
8226 				rval = -1;
8227 			}
8228 		}
8229 	}
8230 
8231 	/*
8232 	 * The spec recommends to send a mode sense after a mode select
8233 	 */
8234 	(void) st_modesense(un);
8235 
8236 	ASSERT(mutex_owned(ST_MUTEX));
8237 
8238 	return (rval);
8239 }
8240 
8241 /*
8242  * st_gen_mode_sense
8243  *
8244  * generic mode sense.. it allows for any page
8245  */
8246 static int
8247 st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
8248     struct seq_mode *page_data, int page_size)
8249 {
8250 
8251 	int r;
8252 	char	cdb[CDB_GROUP0];
8253 	struct uscsi_cmd *com;
8254 	struct scsi_arq_status status;
8255 
8256 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
8257 
8258 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8259 
8260 	bzero(cdb, CDB_GROUP0);
8261 	cdb[0] = SCMD_MODE_SENSE;
8262 	cdb[2] = (char)page;
8263 	cdb[4] = (char)page_size;
8264 
8265 	com->uscsi_cdb = cdb;
8266 	com->uscsi_cdblen = CDB_GROUP0;
8267 	com->uscsi_bufaddr = (caddr_t)page_data;
8268 	com->uscsi_buflen = page_size;
8269 	com->uscsi_rqlen = sizeof (status);
8270 	com->uscsi_rqbuf = (caddr_t)&status;
8271 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8272 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8273 
8274 	r = ubf(un, com, FKIOCTL);
8275 	kmem_free(com, sizeof (*com));
8276 	return (r);
8277 }
8278 
8279 /*
8280  * st_gen_mode_select
8281  *
8282  * generic mode select.. it allows for any page
8283  */
8284 static int
8285 st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
8286     struct seq_mode *page_data, int page_size)
8287 {
8288 
8289 	int r;
8290 	char cdb[CDB_GROUP0];
8291 	struct uscsi_cmd *com;
8292 	struct scsi_arq_status status;
8293 
8294 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
8295 
8296 	/* Zero non-writeable fields */
8297 	page_data->data_len = 0;
8298 	page_data->media_type = 0;
8299 	page_data->wp = 0;
8300 
8301 	/*
8302 	 * If mode select has any page data, zero the ps (Page Savable) bit.
8303 	 */
8304 	if (page_size > MSIZE) {
8305 		page_data->ps = 0;
8306 	}
8307 
8308 
8309 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8310 
8311 	/*
8312 	 * then, do a mode select to set what ever info
8313 	 */
8314 	bzero(cdb, CDB_GROUP0);
8315 	cdb[0] = SCMD_MODE_SELECT;
8316 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
8317 	cdb[4] = (char)page_size;
8318 
8319 	com->uscsi_cdb = cdb;
8320 	com->uscsi_cdblen = CDB_GROUP0;
8321 	com->uscsi_bufaddr = (caddr_t)page_data;
8322 	com->uscsi_buflen = page_size;
8323 	com->uscsi_rqlen = sizeof (status);
8324 	com->uscsi_rqbuf = (caddr_t)&status;
8325 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8326 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_WRITE;
8327 
8328 	r = ubf(un, com, FKIOCTL);
8329 
8330 	kmem_free(com, sizeof (*com));
8331 	return (r);
8332 }
8333 
8334 static int
8335 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
8336 {
8337 	int rval;
8338 	char cdb[CDB_GROUP0];
8339 	struct uscsi_cmd *com;
8340 	struct scsi_arq_status status;
8341 
8342 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
8343 
8344 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8345 
8346 	bzero(cdb, CDB_GROUP0);
8347 	cdb[0] = SCMD_READ_BLKLIM;
8348 
8349 	com->uscsi_cdb = cdb;
8350 	com->uscsi_cdblen = CDB_GROUP0;
8351 	com->uscsi_bufaddr = (caddr_t)read_blk;
8352 	com->uscsi_buflen = sizeof (struct read_blklim);
8353 	com->uscsi_rqlen = sizeof (status);
8354 	com->uscsi_rqbuf = (caddr_t)&status;
8355 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8356 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8357 
8358 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8359 	if (com->uscsi_status || com->uscsi_resid) {
8360 		rval = -1;
8361 	}
8362 
8363 	kmem_free(com, sizeof (*com));
8364 	return (rval);
8365 }
8366 
8367 static int
8368 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
8369     size_t buflen)
8370 {
8371 	int rval;
8372 	char cdb[CDB_GROUP1];
8373 	struct uscsi_cmd *com;
8374 	struct scsi_arq_status status;
8375 
8376 	ST_FUNC(ST_DEVINFO, st_report_density_support);
8377 
8378 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8379 
8380 	bzero(cdb, CDB_GROUP1);
8381 	cdb[0] = SCMD_REPORT_DENSITIES;
8382 	cdb[7] = (buflen & 0xff00) >> 8;
8383 	cdb[8] = buflen & 0xff;
8384 
8385 	com->uscsi_cdb = cdb;
8386 	com->uscsi_cdblen = CDB_GROUP1;
8387 	com->uscsi_bufaddr = (caddr_t)density_data;
8388 	com->uscsi_buflen = buflen;
8389 	com->uscsi_rqlen = sizeof (status);
8390 	com->uscsi_rqbuf = (caddr_t)&status;
8391 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8392 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8393 
8394 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8395 	if (com->uscsi_status || com->uscsi_resid) {
8396 		rval = -1;
8397 	}
8398 
8399 	kmem_free(com, sizeof (*com));
8400 	return (rval);
8401 }
8402 
8403 static int
8404 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
8405     uchar_t option_code, ushort_t service_action)
8406 {
8407 	int rval;
8408 	char cdb[CDB_GROUP5];
8409 	struct uscsi_cmd *com;
8410 	struct scsi_arq_status status;
8411 	uint32_t allo_length;
8412 
8413 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
8414 
8415 	allo_length = sizeof (struct one_com_des) +
8416 	    sizeof (struct com_timeout_des);
8417 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8418 
8419 	bzero(cdb, CDB_GROUP5);
8420 	cdb[0] = (char)SCMD_MAINTENANCE_IN;
8421 	cdb[1] = SSVC_ACTION_GET_SUPPORTED_OPERATIONS;
8422 	if (service_action) {
8423 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
8424 		cdb[4] = (service_action & 0xff00) >> 8;
8425 		cdb[5] = service_action & 0xff;
8426 	} else {
8427 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
8428 		    0x80); /* RCTD */
8429 	}
8430 	cdb[3] = option_code;
8431 	cdb[6] = (allo_length & 0xff000000) >> 24;
8432 	cdb[7] = (allo_length & 0xff0000) >> 16;
8433 	cdb[8] = (allo_length & 0xff00) >> 8;
8434 	cdb[9] = allo_length & 0xff;
8435 
8436 	com->uscsi_cdb = cdb;
8437 	com->uscsi_cdblen = CDB_GROUP5;
8438 	com->uscsi_bufaddr = (caddr_t)oper_data;
8439 	com->uscsi_buflen = allo_length;
8440 	com->uscsi_rqlen = sizeof (status);
8441 	com->uscsi_rqbuf = (caddr_t)&status;
8442 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8443 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8444 
8445 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8446 	if (com->uscsi_status) {
8447 		rval = -1;
8448 	}
8449 
8450 	kmem_free(com, sizeof (*com));
8451 	return (rval);
8452 }
8453 
8454 /*
8455  * Changes devices blocksize and bsize to requested blocksize nblksz.
8456  * Returns returned value from first failed call or zero on success.
8457  */
8458 static int
8459 st_change_block_size(struct scsi_tape *un, uint32_t nblksz)
8460 {
8461 	struct seq_mode *current;
8462 	int rval;
8463 	uint32_t oldblksz;
8464 
8465 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8466 
8467 	current = kmem_zalloc(MSIZE, KM_SLEEP);
8468 
8469 	/*
8470 	 * If we haven't got the compression page yet, do that first.
8471 	 */
8472 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
8473 		(void) st_modesense(un);
8474 	}
8475 
8476 	/* Read current settings */
8477 	rval = st_gen_mode_sense(un, st_uscsi_cmd, 0, current, MSIZE);
8478 	if (rval != 0) {
8479 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8480 		    "mode sense for change block size failed: rval = %d", rval);
8481 		goto finish;
8482 	}
8483 
8484 	/* Figure the current block size */
8485 	oldblksz =
8486 	    (current->high_bl << 16) |
8487 	    (current->mid_bl << 8) |
8488 	    (current->low_bl);
8489 
8490 	/* If current block size is the same as requested were done */
8491 	if (oldblksz == nblksz) {
8492 		un->un_bsize = nblksz;
8493 		rval = 0;
8494 		goto finish;
8495 	}
8496 
8497 	/* Change to requested block size */
8498 	current->high_bl = (uchar_t)(nblksz >> 16);
8499 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8500 	current->low_bl  = (uchar_t)(nblksz);
8501 
8502 	/* Attempt to change block size */
8503 	rval = st_gen_mode_select(un, st_uscsi_cmd, current, MSIZE);
8504 	if (rval != 0) {
8505 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8506 		    "Set new block size failed: rval = %d", rval);
8507 		goto finish;
8508 	}
8509 
8510 	/* Read back and verify setting */
8511 	rval = st_modesense(un);
8512 	if (rval == 0) {
8513 		un->un_bsize =
8514 		    (un->un_mspl->high_bl << 16) |
8515 		    (un->un_mspl->mid_bl << 8) |
8516 		    (un->un_mspl->low_bl);
8517 
8518 		if (un->un_bsize != nblksz) {
8519 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8520 			    "Blocksize set does not equal requested blocksize"
8521 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8522 			rval = EIO;
8523 		}
8524 	}
8525 finish:
8526 	kmem_free(current, MSIZE);
8527 	return (rval);
8528 }
8529 
8530 
8531 static void
8532 st_init(struct scsi_tape *un)
8533 {
8534 	ST_FUNC(ST_DEVINFO, st_init);
8535 
8536 	ASSERT(mutex_owned(ST_MUTEX));
8537 
8538 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8539 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8540 	    un->un_dev);
8541 
8542 	un->un_pos.blkno = 0;
8543 	un->un_pos.fileno = 0;
8544 	un->un_lastop = ST_OP_NIL;
8545 	un->un_pos.eof = ST_NO_EOF;
8546 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8547 	if (st_error_level != SCSI_ERR_ALL) {
8548 		if (DEBUGGING) {
8549 			st_error_level = SCSI_ERR_ALL;
8550 		} else {
8551 			st_error_level = SCSI_ERR_RETRYABLE;
8552 		}
8553 	}
8554 }
8555 
8556 
8557 static void
8558 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8559 {
8560 	struct scsi_pkt *pkt;
8561 	struct uscsi_cmd *ucmd;
8562 	recov_info *ri;
8563 	int tval = 0;
8564 	int64_t count;
8565 	uint32_t additional = 0;
8566 	uint32_t address = 0;
8567 	union scsi_cdb *ucdb;
8568 	int flags = 0;
8569 	int cdb_len = CDB_GROUP0; /* default */
8570 	uchar_t com;
8571 	char fixbit;
8572 	char short_fm = 0;
8573 	optype prev_op = un->un_lastop;
8574 	int stat_size =
8575 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
8576 
8577 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8578 
8579 	ASSERT(mutex_owned(ST_MUTEX));
8580 
8581 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8582 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8583 
8584 
8585 	/*
8586 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8587 	 * Length Indicator bits on read/write commands, for setting
8588 	 * the Long bit on erase commands, and for setting the Code
8589 	 * Field bits on space commands.
8590 	 */
8591 
8592 	/* regular raw I/O */
8593 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
8594 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8595 		    CDB_GROUP0, stat_size, st_recov_sz, 0, func,
8596 		    (caddr_t)un);
8597 		if (pkt == NULL) {
8598 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8599 			    "Read Write scsi_init_pkt() failure\n");
8600 			goto exit;
8601 		}
8602 		ASSERT(pkt->pkt_resid == 0);
8603 #ifdef STDEBUG
8604 		bzero(pkt->pkt_private, st_recov_sz);
8605 		bzero(pkt->pkt_scbp, stat_size);
8606 #endif
8607 		ri = (recov_info *)pkt->pkt_private;
8608 		ri->privatelen = st_recov_sz;
8609 		if (un->un_bsize == 0) {
8610 			count = bp->b_bcount;
8611 			fixbit = 0;
8612 		} else {
8613 			count = bp->b_bcount / un->un_bsize;
8614 			fixbit = 1;
8615 		}
8616 		if (bp->b_flags & B_READ) {
8617 			com = SCMD_READ;
8618 			un->un_lastop = ST_OP_READ;
8619 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8620 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8621 				fixbit = 2;
8622 			}
8623 		} else {
8624 			com = SCMD_WRITE;
8625 			un->un_lastop = ST_OP_WRITE;
8626 		}
8627 		tval = un->un_dp->io_timeout;
8628 
8629 		/*
8630 		 * For really large xfers, increase timeout
8631 		 */
8632 		if (bp->b_bcount > (10 * ONE_MEG))
8633 			tval *= bp->b_bcount/(10 * ONE_MEG);
8634 
8635 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8636 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8637 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8638 
8639 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8640 		/*
8641 		 * uscsi - build command, allocate scsi resources
8642 		 */
8643 		st_make_uscsi_cmd(un, ucmd, bp, func);
8644 		goto exit;
8645 
8646 	} else {				/* special I/O */
8647 		struct buf *allocbp = NULL;
8648 		com = (uchar_t)(uintptr_t)bp->b_forw;
8649 		count = bp->b_bcount;
8650 
8651 		switch (com) {
8652 		case SCMD_READ:
8653 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8654 			    "special read %"PRId64"\n", count);
8655 			if (un->un_bsize == 0) {
8656 				fixbit = 2;	/* suppress SILI */
8657 			} else {
8658 				fixbit = 1;	/* Fixed Block Mode */
8659 				count /= un->un_bsize;
8660 			}
8661 			allocbp = bp;
8662 			un->un_lastop = ST_OP_READ;
8663 			tval = un->un_dp->io_timeout;
8664 			break;
8665 
8666 		case SCMD_WRITE:
8667 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8668 			    "special write %"PRId64"\n", count);
8669 			if (un->un_bsize != 0) {
8670 				fixbit = 1;	/* Fixed Block Mode */
8671 				count /= un->un_bsize;
8672 			} else {
8673 				fixbit = 0;
8674 			}
8675 			allocbp = bp;
8676 			un->un_lastop = ST_OP_WRITE;
8677 			tval = un->un_dp->io_timeout;
8678 			break;
8679 
8680 		case SCMD_WRITE_FILE_MARK:
8681 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8682 			    "write %"PRId64" file marks\n", count);
8683 			un->un_lastop = ST_OP_WEOF;
8684 			fixbit = 0;
8685 			tval = un->un_dp->io_timeout;
8686 			/*
8687 			 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8688 			 * device, set the Vendor Unique bit to
8689 			 * write Short File Mark.
8690 			 */
8691 			if ((un->un_dp->options & ST_SHORT_FILEMARKS) &&
8692 			    ((un->un_dp->type == ST_TYPE_EXB8500) ||
8693 			    (un->un_dp->type == ST_TYPE_EXABYTE))) {
8694 				/*
8695 				 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8696 				 * is set to to write Short File Mark
8697 				 */
8698 				short_fm = 1;
8699 			}
8700 			break;
8701 
8702 		case SCMD_REWIND:
8703 			/*
8704 			 * In the case of rewind we're gona do the rewind with
8705 			 * the immediate bit set so status will be retured when
8706 			 * the command is accepted by the device. We clear the
8707 			 * B_ASYNC flag so we wait for that acceptance.
8708 			 */
8709 			if (bp->b_flags & B_ASYNC) {
8710 				allocbp = bp;
8711 				if (count) {
8712 					fixbit = 1;
8713 					bp->b_flags &= ~B_ASYNC;
8714 				}
8715 			} else {
8716 				fixbit = 0;
8717 			}
8718 			count = 0;
8719 			bp->b_bcount = 0;
8720 			un->un_lastop = ST_OP_CTL;
8721 			tval = un->un_dp->rewind_timeout;
8722 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8723 			    "rewind\n");
8724 			break;
8725 
8726 		case SCMD_SPACE_G4:
8727 			cdb_len = CDB_GROUP4;
8728 			fixbit = SPACE_TYPE(bp->b_bcount);
8729 			count = SPACE_CNT(bp->b_bcount);
8730 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8731 			    " %s space %s %"PRId64" from file %d blk %d\n",
8732 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8733 			    space_strs[fixbit & 7], count,
8734 			    un->un_pos.fileno, un->un_pos.blkno);
8735 			address = (count >> 48) & 0x1fff;
8736 			additional = (count >> 16) & 0xffffffff;
8737 			count &= 0xffff;
8738 			count <<= 16;
8739 			un->un_lastop = ST_OP_CTL;
8740 			tval = un->un_dp->space_timeout;
8741 			break;
8742 
8743 		case SCMD_SPACE:
8744 			fixbit = SPACE_TYPE(bp->b_bcount);
8745 			count = SPACE_CNT(bp->b_bcount);
8746 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8747 			    " %s space %s %"PRId64" from file %d blk %d\n",
8748 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8749 			    space_strs[fixbit & 7], count,
8750 			    un->un_pos.fileno, un->un_pos.blkno);
8751 			count &= 0xffffffff;
8752 			un->un_lastop = ST_OP_CTL;
8753 			tval = un->un_dp->space_timeout;
8754 			break;
8755 
8756 		case SCMD_LOAD:
8757 			ASSERT(count < 10);
8758 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8759 			    "%s tape\n", load_strs[count]);
8760 			fixbit = 0;
8761 
8762 			/* Loading or Unloading */
8763 			if (count & LD_LOAD) {
8764 				tval = un->un_dp->load_timeout;
8765 			} else {
8766 				tval = un->un_dp->unload_timeout;
8767 			}
8768 			/* Is Retension requested */
8769 			if (count & LD_RETEN) {
8770 				tval += un->un_dp->rewind_timeout;
8771 			}
8772 			un->un_lastop = ST_OP_CTL;
8773 			break;
8774 
8775 		case SCMD_ERASE:
8776 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8777 			    "erase tape\n");
8778 			ASSERT(count == 1); /* mt sets this */
8779 			if (count == 1) {
8780 				/*
8781 				 * do long erase
8782 				 */
8783 				fixbit = 1; /* Long */
8784 
8785 				/* Drive might not honor immidiate bit */
8786 				tval = un->un_dp->erase_timeout;
8787 			} else {
8788 				/* Short Erase */
8789 				tval = un->un_dp->erase_timeout;
8790 				fixbit = 0;
8791 			}
8792 			un->un_lastop = ST_OP_CTL;
8793 			count = 0;
8794 			break;
8795 
8796 		case SCMD_MODE_SENSE:
8797 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8798 			    "mode sense\n");
8799 			allocbp = bp;
8800 			fixbit = 0;
8801 			tval = un->un_dp->non_motion_timeout;
8802 			un->un_lastop = ST_OP_CTL;
8803 			break;
8804 
8805 		case SCMD_MODE_SELECT:
8806 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8807 			    "mode select\n");
8808 			allocbp = bp;
8809 			fixbit = 0;
8810 			tval = un->un_dp->non_motion_timeout;
8811 			un->un_lastop = ST_OP_CTL;
8812 			break;
8813 
8814 		case SCMD_RESERVE:
8815 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8816 			    "reserve\n");
8817 			fixbit = 0;
8818 			tval = un->un_dp->non_motion_timeout;
8819 			un->un_lastop = ST_OP_CTL;
8820 			break;
8821 
8822 		case SCMD_RELEASE:
8823 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8824 			    "release\n");
8825 			fixbit = 0;
8826 			tval = un->un_dp->non_motion_timeout;
8827 			un->un_lastop = ST_OP_CTL;
8828 			break;
8829 
8830 		case SCMD_READ_BLKLIM:
8831 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8832 			    "read block limits\n");
8833 			allocbp = bp;
8834 			fixbit = count = 0;
8835 			tval = un->un_dp->non_motion_timeout;
8836 			un->un_lastop = ST_OP_CTL;
8837 			break;
8838 
8839 		case SCMD_TEST_UNIT_READY:
8840 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8841 			    "test unit ready\n");
8842 			fixbit = 0;
8843 			tval = un->un_dp->non_motion_timeout;
8844 			un->un_lastop = ST_OP_CTL;
8845 			break;
8846 
8847 		case SCMD_DOORLOCK:
8848 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8849 			    "prevent/allow media removal\n");
8850 			fixbit = 0;
8851 			tval = un->un_dp->non_motion_timeout;
8852 			un->un_lastop = ST_OP_CTL;
8853 			break;
8854 
8855 		case SCMD_READ_POSITION:
8856 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8857 			    "read position\n");
8858 			fixbit = un->un_read_pos_type;
8859 			cdb_len = CDB_GROUP1;
8860 			tval = un->un_dp->non_motion_timeout;
8861 			allocbp = bp;
8862 			un->un_lastop = ST_OP_CTL;
8863 			switch (un->un_read_pos_type) {
8864 			case LONG_POS:
8865 				count = 0;
8866 				break;
8867 			case EXT_POS:
8868 				count = sizeof (tape_position_ext_t);
8869 				break;
8870 			case SHORT_POS:
8871 				count = 0;
8872 				break;
8873 			default:
8874 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8875 				    "Unknown read position type 0x%x in "
8876 				    " st_make_cmd()\n", un->un_read_pos_type);
8877 			}
8878 			break;
8879 
8880 		default:
8881 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8882 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8883 			    com);
8884 		}
8885 
8886 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8887 		    st_recov_sz, 0, func, (caddr_t)un);
8888 		if (pkt == NULL) {
8889 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8890 			    "generic command scsi_init_pkt() failure\n");
8891 			goto exit;
8892 		}
8893 
8894 		ASSERT(pkt->pkt_resid == 0);
8895 #ifdef STDEBUG
8896 		bzero(pkt->pkt_private, st_recov_sz);
8897 		bzero(pkt->pkt_scbp, stat_size);
8898 #endif
8899 		ri = (recov_info *)pkt->pkt_private;
8900 		ri->privatelen = st_recov_sz;
8901 		if (allocbp) {
8902 			ASSERT(geterror(allocbp) == 0);
8903 		}
8904 
8905 	}
8906 
8907 	ucdb = (union scsi_cdb *)pkt->pkt_cdbp;
8908 
8909 	(void) scsi_setup_cdb(ucdb, com, address, (uint_t)count, additional);
8910 	FILL_SCSI1_LUN(un->un_sd, pkt);
8911 	/*
8912 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8913 	 */
8914 	ucdb->t_code = fixbit;
8915 	ucdb->g0_vu_1 = short_fm;
8916 	pkt->pkt_flags = flags;
8917 
8918 	ASSERT(tval);
8919 	pkt->pkt_time = tval;
8920 	if (bp == un->un_recov_buf) {
8921 		pkt->pkt_comp = st_recov_cb;
8922 	} else {
8923 		pkt->pkt_comp = st_intr;
8924 	}
8925 
8926 	st_add_recovery_info_to_pkt(un, bp, pkt);
8927 
8928 	/*
8929 	 * If we just write data to tape and did a command that doesn't
8930 	 * change position, we still need to write a filemark.
8931 	 */
8932 	if ((prev_op == ST_OP_WRITE) || (prev_op == ST_OP_WEOF)) {
8933 		recov_info *rcvi = pkt->pkt_private;
8934 		cmd_attribute const *atrib;
8935 
8936 		if (rcvi->privatelen == sizeof (recov_info)) {
8937 			atrib = rcvi->cmd_attrib;
8938 		} else {
8939 			atrib = st_lookup_cmd_attribute(com);
8940 		}
8941 		if (atrib->chg_tape_direction == DIR_NONE) {
8942 			un->un_lastop = prev_op;
8943 		}
8944 	}
8945 
8946 exit:
8947 	ASSERT(mutex_owned(ST_MUTEX));
8948 }
8949 
8950 
8951 /*
8952  * Build a command based on a uscsi command;
8953  */
8954 static void
8955 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
8956     struct buf *bp, int (*func)(caddr_t))
8957 {
8958 	struct scsi_pkt *pkt;
8959 	recov_info *ri;
8960 	caddr_t cdb;
8961 	int	cdblen;
8962 	int	stat_size = 1;
8963 	int	flags = 0;
8964 
8965 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
8966 
8967 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8968 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
8969 
8970 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
8971 		if (un->un_arq_enabled) {
8972 			if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
8973 				stat_size = (int)(ucmd->uscsi_rqlen) +
8974 				    sizeof (struct scsi_arq_status) -
8975 				    sizeof (struct scsi_extended_sense);
8976 				flags = PKT_XARQ;
8977 			} else {
8978 				stat_size = sizeof (struct scsi_arq_status);
8979 			}
8980 		}
8981 	}
8982 
8983 	ASSERT(mutex_owned(ST_MUTEX));
8984 
8985 	cdb = ucmd->uscsi_cdb;
8986 	cdblen = ucmd->uscsi_cdblen;
8987 
8988 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8989 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
8990 	    ucmd->uscsi_buflen, bp->b_bcount);
8991 	pkt = scsi_init_pkt(ROUTE, NULL,
8992 	    (bp->b_bcount > 0) ? bp : NULL,
8993 	    cdblen, stat_size, st_recov_sz, flags, func, (caddr_t)un);
8994 	if (pkt == NULL) {
8995 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8996 		    "uscsi command scsi_init_pkt() failure\n");
8997 		goto exit;
8998 	}
8999 
9000 	ASSERT(pkt->pkt_resid == 0);
9001 #ifdef STDEBUG
9002 	bzero(pkt->pkt_private, st_recov_sz);
9003 	bzero(pkt->pkt_scbp, stat_size);
9004 #endif
9005 	ri = (recov_info *)pkt->pkt_private;
9006 	ri->privatelen = st_recov_sz;
9007 
9008 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
9009 
9010 #ifdef STDEBUG
9011 	if ((st_debug & 0x7) >= 6) {
9012 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
9013 		    "pkt_cdbp", (char *)cdb, cdblen);
9014 	}
9015 #endif
9016 
9017 	if (ucmd->uscsi_flags & USCSI_SILENT) {
9018 		pkt->pkt_flags |= FLAG_SILENT;
9019 	}
9020 
9021 	pkt->pkt_time = ucmd->uscsi_timeout;
9022 	if (bp == un->un_recov_buf) {
9023 		pkt->pkt_comp = st_recov_cb;
9024 	} else {
9025 		pkt->pkt_comp = st_intr;
9026 	}
9027 	st_add_recovery_info_to_pkt(un, bp, pkt);
9028 exit:
9029 	ASSERT(mutex_owned(ST_MUTEX));
9030 }
9031 
9032 
9033 /*
9034  * restart cmd currently at the head of the runq
9035  *
9036  * If scsi_transport() succeeds or the retries
9037  * count exhausted, restore the throttle that was
9038  * zeroed out in st_handle_intr_busy().
9039  *
9040  */
9041 static void
9042 st_intr_restart(void *arg)
9043 {
9044 	struct scsi_tape *un = arg;
9045 	struct buf *bp;
9046 	int queued;
9047 	int status = TRAN_ACCEPT;
9048 
9049 	mutex_enter(ST_MUTEX);
9050 
9051 	ST_FUNC(ST_DEVINFO, st_intr_restart);
9052 
9053 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9054 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
9055 
9056 	un->un_hib_tid = 0;
9057 
9058 	if (un->un_recov_buf_busy != 0) {
9059 		bp = un->un_recov_buf;
9060 		queued = 0;
9061 	} else if (un->un_sbuf_busy != 0) {
9062 		bp = un->un_sbufp;
9063 		queued = 0;
9064 	} else if (un->un_quef != NULL) {
9065 		bp = un->un_quef;
9066 		queued = 1;
9067 	} else {
9068 		mutex_exit(ST_MUTEX);
9069 		return;
9070 	}
9071 
9072 	/*
9073 	 * Here we know :
9074 	 *	throttle = 0, via st_handle_intr_busy
9075 	 */
9076 
9077 	if (queued) {
9078 		/*
9079 		 * move from waitq to runq, if there is anything on the waitq
9080 		 */
9081 		(void) st_remove_from_queue(&un->un_quef, &un->un_quef, bp);
9082 
9083 		if (un->un_runqf) {
9084 			/*
9085 			 * not good, we don't want to requeue something after
9086 			 * another.
9087 			 */
9088 			goto done_error;
9089 		} else {
9090 			un->un_runqf = bp;
9091 			un->un_runql = bp;
9092 		}
9093 	}
9094 
9095 	ST_CDB(ST_DEVINFO, "Interrupt restart CDB",
9096 	    (char *)BP_PKT(bp)->pkt_cdbp);
9097 
9098 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
9099 
9100 	status = st_transport(un, BP_PKT(bp));
9101 
9102 	if (status != TRAN_ACCEPT) {
9103 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9104 
9105 		if (status == TRAN_BUSY) {
9106 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
9107 
9108 			if (pkti->privatelen == sizeof (recov_info) &&
9109 			    un->un_unit_attention_flags &&
9110 			    bp != un->un_recov_buf) {
9111 			un->un_unit_attention_flags = 0;
9112 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9113 				    "Command Recovery called on busy resend\n");
9114 				if (st_command_recovery(un, BP_PKT(bp),
9115 				    ATTEMPT_RETRY) == JUST_RETURN) {
9116 					mutex_exit(ST_MUTEX);
9117 					return;
9118 				}
9119 			}
9120 			mutex_exit(ST_MUTEX);
9121 			if (st_handle_intr_busy(un, bp,
9122 			    ST_TRAN_BUSY_TIMEOUT) == 0)
9123 				return;	/* timeout is setup again */
9124 			mutex_enter(ST_MUTEX);
9125 		}
9126 
9127 done_error:
9128 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9129 		    "restart transport rejected\n");
9130 		bp->b_resid = bp->b_bcount;
9131 
9132 		if (un->un_last_throttle) {
9133 			un->un_throttle = un->un_last_throttle;
9134 		}
9135 		if (status != TRAN_ACCEPT) {
9136 			ST_DO_ERRSTATS(un, st_transerrs);
9137 		}
9138 		ST_DO_KSTATS(bp, kstat_waitq_exit);
9139 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9140 		    "busy restart aborted\n");
9141 		st_set_pe_flag(un);
9142 		st_bioerror(bp, EIO);
9143 		st_done_and_mutex_exit(un, bp);
9144 	} else {
9145 		if (un->un_last_throttle) {
9146 			un->un_throttle = un->un_last_throttle;
9147 		}
9148 		mutex_exit(ST_MUTEX);
9149 	}
9150 }
9151 
9152 /*
9153  * st_check_media():
9154  * Periodically check the media state using scsi_watch service;
9155  * this service calls back after TUR and possibly request sense
9156  * the callback handler (st_media_watch_cb()) decodes the request sense
9157  * data (if any)
9158  */
9159 
9160 static int
9161 st_check_media(dev_t dev, enum mtio_state state)
9162 {
9163 	int rval = 0;
9164 	enum mtio_state	prev_state;
9165 	opaque_t token = NULL;
9166 
9167 	GET_SOFT_STATE(dev);
9168 
9169 	ST_FUNC(ST_DEVINFO, st_check_media);
9170 
9171 	mutex_enter(ST_MUTEX);
9172 
9173 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9174 	    "st_check_media:state=%x, mediastate=%x\n",
9175 	    state, un->un_mediastate);
9176 
9177 	prev_state = un->un_mediastate;
9178 
9179 	/*
9180 	 * is there anything to do?
9181 	 */
9182 retry:
9183 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
9184 		/*
9185 		 * submit the request to the scsi_watch service;
9186 		 * scsi_media_watch_cb() does the real work
9187 		 */
9188 		mutex_exit(ST_MUTEX);
9189 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
9190 		    st_check_media_time, SENSE_LENGTH,
9191 		    st_media_watch_cb, (caddr_t)dev);
9192 		if (token == NULL) {
9193 			rval = EAGAIN;
9194 			goto done;
9195 		}
9196 		mutex_enter(ST_MUTEX);
9197 
9198 		un->un_swr_token = token;
9199 		un->un_specified_mediastate = state;
9200 
9201 		/*
9202 		 * now wait for media change
9203 		 * we will not be signalled unless mediastate == state but it
9204 		 * still better to test for this condition, since there
9205 		 * is a 5 sec cv_broadcast delay when
9206 		 *  mediastate == MTIO_INSERTED
9207 		 */
9208 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9209 		    "st_check_media:waiting for media state change\n");
9210 		while (un->un_mediastate == state) {
9211 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
9212 				mutex_exit(ST_MUTEX);
9213 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9214 				    "st_check_media:waiting for media state "
9215 				    "was interrupted\n");
9216 				rval = EINTR;
9217 				goto done;
9218 			}
9219 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9220 			    "st_check_media:received signal, state=%x\n",
9221 			    un->un_mediastate);
9222 		}
9223 	}
9224 
9225 	/*
9226 	 * if we transitioned to MTIO_INSERTED, media has really been
9227 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
9228 	 * Reset and retry the state change.  If everything is ok, replay
9229 	 * the open() logic.
9230 	 */
9231 	if ((un->un_mediastate == MTIO_INSERTED) &&
9232 	    (un->un_state == ST_STATE_OFFLINE)) {
9233 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9234 		    "st_check_media: calling st_cmd to confirm inserted\n");
9235 
9236 		/*
9237 		 * set this early so that TUR will make it through strategy
9238 		 * without triggering a st_tape_init().  We needed it set
9239 		 * before calling st_tape_init() ourselves anyway.  If TUR
9240 		 * fails, set it back
9241 		 */
9242 		un->un_state = ST_STATE_INITIALIZING;
9243 
9244 		/*
9245 		 * If not reserved fail as getting reservation conflict
9246 		 * will make this hang forever.
9247 		 */
9248 		if ((un->un_rsvd_status &
9249 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9250 			mutex_exit(ST_MUTEX);
9251 			rval = EACCES;
9252 			goto done;
9253 		}
9254 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
9255 		if (rval == EACCES) {
9256 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9257 			    "st_check_media: TUR got Reservation Conflict\n");
9258 			mutex_exit(ST_MUTEX);
9259 			goto done;
9260 		}
9261 		if (rval) {
9262 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9263 			    "st_check_media: TUR failed, going to retry\n");
9264 			un->un_mediastate = prev_state;
9265 			un->un_state = ST_STATE_OFFLINE;
9266 			goto retry;
9267 		}
9268 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9269 		    "st_check_media: media inserted\n");
9270 
9271 		/* this also rewinds the tape */
9272 		rval = st_tape_init(un);
9273 		if (rval != 0) {
9274 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9275 			    "st_check_media : OFFLINE init failure ");
9276 			un->un_state = ST_STATE_OFFLINE;
9277 			un->un_pos.pmode = invalid;
9278 		} else {
9279 			un->un_state = ST_STATE_OPEN_PENDING_IO;
9280 		}
9281 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
9282 	    (un->un_state != ST_STATE_OFFLINE)) {
9283 		/*
9284 		 * supported devices must be rewound before ejection
9285 		 * rewind resets fileno & blkno
9286 		 */
9287 		un->un_laststate = un->un_state;
9288 		un->un_state = ST_STATE_OFFLINE;
9289 	}
9290 	mutex_exit(ST_MUTEX);
9291 done:
9292 	if (token) {
9293 		(void) scsi_watch_request_terminate(token,
9294 		    SCSI_WATCH_TERMINATE_WAIT);
9295 		mutex_enter(ST_MUTEX);
9296 		un->un_swr_token = (opaque_t)NULL;
9297 		mutex_exit(ST_MUTEX);
9298 	}
9299 
9300 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
9301 
9302 	return (rval);
9303 }
9304 
9305 /*
9306  * st_media_watch_cb() is called by scsi_watch_thread for
9307  * verifying the request sense data (if any)
9308  */
9309 static int
9310 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
9311 {
9312 	struct scsi_status *statusp = resultp->statusp;
9313 	struct scsi_extended_sense *sensep = resultp->sensep;
9314 	uchar_t actual_sense_length = resultp->actual_sense_length;
9315 	struct scsi_tape *un;
9316 	enum mtio_state state = MTIO_NONE;
9317 	int instance;
9318 	dev_t dev = (dev_t)arg;
9319 
9320 	instance = MTUNIT(dev);
9321 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
9322 		return (-1);
9323 	}
9324 
9325 	mutex_enter(ST_MUTEX);
9326 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
9327 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9328 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
9329 	    *((char *)statusp), (void *)sensep,
9330 	    actual_sense_length);
9331 
9332 
9333 	/*
9334 	 * if there was a check condition then sensep points to valid
9335 	 * sense data
9336 	 * if status was not a check condition but a reservation or busy
9337 	 * status then the new state is MTIO_NONE
9338 	 */
9339 	if (sensep) {
9340 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9341 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
9342 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
9343 
9344 		switch (un->un_dp->type) {
9345 		default:
9346 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9347 			    "st_media_watch_cb: unknown drive type %d, "
9348 			    "default to ST_TYPE_HP\n", un->un_dp->type);
9349 		/* FALLTHROUGH */
9350 
9351 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
9352 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
9353 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
9354 			if (un->un_dp->type == ST_TYPE_FUJI) {
9355 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9356 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
9357 			} else {
9358 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9359 				    "st_media_watch_cb: ST_TYPE_HP\n");
9360 			}
9361 			switch (sensep->es_key) {
9362 			case KEY_UNIT_ATTENTION:
9363 				/* not ready to ready transition */
9364 				/* hp/es_qual_code == 80 on>off>on */
9365 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
9366 				if (sensep->es_add_code == 0x28) {
9367 					state = MTIO_INSERTED;
9368 				}
9369 				break;
9370 			case KEY_NOT_READY:
9371 				/* in process, rewinding or loading */
9372 				if ((sensep->es_add_code == 0x04) &&
9373 				    (sensep->es_qual_code == 0x00)) {
9374 					state = MTIO_EJECTED;
9375 				}
9376 				break;
9377 			}
9378 			break;
9379 
9380 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
9381 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9382 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
9383 			switch (sensep->es_key) {
9384 			case KEY_UNIT_ATTENTION:
9385 				/* operator medium removal request */
9386 				if ((sensep->es_add_code == 0x5a) &&
9387 				    (sensep->es_qual_code == 0x01)) {
9388 					state = MTIO_EJECTED;
9389 				/* not ready to ready transition */
9390 				} else if ((sensep->es_add_code == 0x28) &&
9391 				    (sensep->es_qual_code == 0x00)) {
9392 					state = MTIO_INSERTED;
9393 				}
9394 				break;
9395 			case KEY_NOT_READY:
9396 				/* medium not present */
9397 				if (sensep->es_add_code == 0x3a) {
9398 					state = MTIO_EJECTED;
9399 				}
9400 				break;
9401 			}
9402 			break;
9403 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
9404 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9405 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
9406 			switch (sensep->es_key) {
9407 			case KEY_NOT_READY:
9408 				if ((sensep->es_add_code == 0x04) &&
9409 				    (sensep->es_qual_code == 0x00)) {
9410 					/* volume not mounted? */
9411 					state = MTIO_EJECTED;
9412 				} else if (sensep->es_add_code == 0x3a) {
9413 					state = MTIO_EJECTED;
9414 				}
9415 				break;
9416 			case KEY_UNIT_ATTENTION:
9417 				state = MTIO_EJECTED;
9418 				break;
9419 			}
9420 			break;
9421 
9422 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
9423 			switch (sensep->es_key) {
9424 			case KEY_UNIT_ATTENTION:
9425 				if (sensep->es_add_code == 0x28) {
9426 					state = MTIO_INSERTED;
9427 				}
9428 				break;
9429 			case KEY_NOT_READY:
9430 				if (sensep->es_add_code == 0x04) {
9431 					/* in transition but could be either */
9432 					state = un->un_specified_mediastate;
9433 				} else if ((sensep->es_add_code == 0x3a) &&
9434 				    (sensep->es_qual_code == 0x00)) {
9435 					state = MTIO_EJECTED;
9436 				}
9437 				break;
9438 			}
9439 			break;
9440 		}
9441 	} else if (*((char *)statusp) == STATUS_GOOD) {
9442 		state = MTIO_INSERTED;
9443 	}
9444 
9445 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9446 	    "st_media_watch_cb:state=%x, specified=%x\n",
9447 	    state, un->un_specified_mediastate);
9448 
9449 	/*
9450 	 * now signal the waiting thread if this is *not* the specified state;
9451 	 * delay the signal if the state is MTIO_INSERTED
9452 	 * to allow the target to recover
9453 	 */
9454 	if (state != un->un_specified_mediastate) {
9455 		un->un_mediastate = state;
9456 		if (state == MTIO_INSERTED) {
9457 			/*
9458 			 * delay the signal to give the drive a chance
9459 			 * to do what it apparently needs to do
9460 			 */
9461 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9462 			    "st_media_watch_cb:delayed cv_broadcast\n");
9463 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
9464 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
9465 		} else {
9466 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9467 			    "st_media_watch_cb:immediate cv_broadcast\n");
9468 			cv_broadcast(&un->un_state_cv);
9469 		}
9470 	}
9471 	mutex_exit(ST_MUTEX);
9472 	return (0);
9473 }
9474 
9475 /*
9476  * delayed cv_broadcast to allow for target to recover
9477  * from media insertion
9478  */
9479 static void
9480 st_delayed_cv_broadcast(void *arg)
9481 {
9482 	struct scsi_tape *un = arg;
9483 
9484 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
9485 
9486 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9487 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
9488 
9489 	mutex_enter(ST_MUTEX);
9490 	cv_broadcast(&un->un_state_cv);
9491 	mutex_exit(ST_MUTEX);
9492 }
9493 
9494 /*
9495  * restart cmd currently at the start of the waitq
9496  */
9497 static void
9498 st_start_restart(void *arg)
9499 {
9500 	struct scsi_tape *un = arg;
9501 
9502 	ST_FUNC(ST_DEVINFO, st_start_restart);
9503 
9504 	ASSERT(un != NULL);
9505 
9506 	mutex_enter(ST_MUTEX);
9507 
9508 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_tran_restart()\n");
9509 
9510 	st_start(un);
9511 
9512 	mutex_exit(ST_MUTEX);
9513 }
9514 
9515 
9516 /*
9517  * Command completion processing
9518  *
9519  */
9520 static void
9521 st_intr(struct scsi_pkt *pkt)
9522 {
9523 	recov_info *rcv = pkt->pkt_private;
9524 	struct buf *bp = rcv->cmd_bp;
9525 	struct scsi_tape *un;
9526 	errstate action = COMMAND_DONE;
9527 	clock_t	timout;
9528 	int	status;
9529 
9530 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
9531 
9532 	ST_FUNC(ST_DEVINFO, st_intr);
9533 
9534 	ASSERT(un != NULL);
9535 
9536 	mutex_enter(ST_MUTEX);
9537 
9538 	ASSERT(bp != un->un_recov_buf);
9539 
9540 	un->un_rqs_state &= ~(ST_RQS_ERROR);
9541 
9542 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
9543 
9544 	if (pkt->pkt_reason != CMD_CMPLT) {
9545 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9546 		    "Unhappy packet status reason = %s statistics = 0x%x\n",
9547 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9548 
9549 		/* If device has gone away not much else to do */
9550 		if (pkt->pkt_reason == CMD_DEV_GONE) {
9551 			action = COMMAND_DONE_ERROR;
9552 		} else if ((pkt == un->un_rqs) ||
9553 		    (un->un_state == ST_STATE_SENSING)) {
9554 			ASSERT(pkt == un->un_rqs);
9555 			ASSERT(un->un_state == ST_STATE_SENSING);
9556 			un->un_state = un->un_laststate;
9557 			rcv->cmd_bp = un->un_rqs_bp;
9558 			ST_DO_ERRSTATS(un, st_transerrs);
9559 			action = COMMAND_DONE_ERROR;
9560 		} else {
9561 			action = st_handle_incomplete(un, bp);
9562 		}
9563 	/*
9564 	 * At this point we know that the command was successfully
9565 	 * completed. Now what?
9566 	 */
9567 	} else if ((pkt == un->un_rqs) || (un->un_state == ST_STATE_SENSING)) {
9568 		/*
9569 		 * okay. We were running a REQUEST SENSE. Find
9570 		 * out what to do next.
9571 		 */
9572 		ASSERT(pkt == un->un_rqs);
9573 		ASSERT(un->un_state == ST_STATE_SENSING);
9574 		scsi_sync_pkt(pkt);
9575 		action = st_handle_sense(un, bp, &un->un_pos);
9576 		/*
9577 		 * Make rqs isn't going to be retied.
9578 		 */
9579 		if (action != QUE_BUSY_COMMAND && action != QUE_COMMAND) {
9580 			/*
9581 			 * set pkt back to original packet in case we will have
9582 			 * to requeue it
9583 			 */
9584 			pkt = BP_PKT(bp);
9585 			rcv->cmd_bp = un->un_rqs_bp;
9586 			/*
9587 			 * some actions are based on un_state, hence
9588 			 * restore the state st was in before ST_STATE_SENSING.
9589 			 */
9590 			un->un_state = un->un_laststate;
9591 		}
9592 
9593 	} else if (un->un_arq_enabled && (pkt->pkt_state & STATE_ARQ_DONE)) {
9594 		/*
9595 		 * the transport layer successfully completed an autorqsense
9596 		 */
9597 		action = st_handle_autosense(un, bp, &un->un_pos);
9598 
9599 	} else  if ((SCBP(pkt)->sts_busy) ||
9600 	    (SCBP(pkt)->sts_chk) ||
9601 	    (SCBP(pkt)->sts_vu7)) {
9602 		/*
9603 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9604 		 * to see if the status bits we're okay. If a request sense
9605 		 * is to be run, that will happen.
9606 		 */
9607 		action = st_check_error(un, pkt);
9608 	}
9609 
9610 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9611 		switch (action) {
9612 			case QUE_COMMAND:
9613 				/*
9614 				 * return cmd to head to the queue
9615 				 * since we are suspending so that
9616 				 * it gets restarted during resume
9617 				 */
9618 				st_add_to_queue(&un->un_runqf, &un->un_runql,
9619 				    un->un_runqf, bp);
9620 
9621 				action = JUST_RETURN;
9622 				break;
9623 
9624 			case QUE_SENSE:
9625 				action = COMMAND_DONE_ERROR;
9626 				break;
9627 
9628 			default:
9629 				break;
9630 		}
9631 	}
9632 
9633 	/*
9634 	 * check for undetected path failover.
9635 	 */
9636 	if ((un->un_multipath) &&
9637 	    (un->un_last_path_instance != pkt->pkt_path_instance)) {
9638 		if (un->un_state > ST_STATE_OPENING) {
9639 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
9640 			    "Failover detected, action is %s\n",
9641 			    errstatenames[action]);
9642 			if (action == COMMAND_DONE) {
9643 				action = PATH_FAILED;
9644 			}
9645 		}
9646 		un->un_last_path_instance = pkt->pkt_path_instance;
9647 	}
9648 
9649 	/*
9650 	 * Restore old state if we were sensing.
9651 	 */
9652 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9653 		un->un_state = un->un_laststate;
9654 	}
9655 
9656 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9657 	    "st_intr: pkt=%p, bp=%p, action=%s, status=%x\n",
9658 	    (void *)pkt, (void *)bp, errstatenames[action], SCBP_C(pkt));
9659 
9660 again:
9661 	switch (action) {
9662 	case COMMAND_DONE_EACCES:
9663 		/* this is to report a reservation conflict */
9664 		st_bioerror(bp, EACCES);
9665 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9666 		    "Reservation Conflict \n");
9667 		un->un_pos.pmode = invalid;
9668 
9669 		/*FALLTHROUGH*/
9670 	case COMMAND_DONE_ERROR:
9671 		if (un->un_pos.eof < ST_EOT_PENDING &&
9672 		    un->un_state >= ST_STATE_OPEN) {
9673 			/*
9674 			 * all errors set state of the tape to 'unknown'
9675 			 * unless we're at EOT or are doing append testing.
9676 			 * If sense key was illegal request, preserve state.
9677 			 */
9678 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9679 				un->un_pos.pmode = invalid;
9680 			}
9681 		}
9682 
9683 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9684 		/*
9685 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9686 		 * make sure an error ocurrs, so make sure at least EIO is
9687 		 * returned
9688 		 */
9689 		if (geterror(bp) == 0)
9690 			st_bioerror(bp, EIO);
9691 
9692 		st_set_pe_flag(un);
9693 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9694 		    (un->un_errno == EIO)) {
9695 			un->un_rqs_state &= ~(ST_RQS_VALID);
9696 		}
9697 		break;
9698 
9699 	case COMMAND_DONE_ERROR_RECOVERED:
9700 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9701 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9702 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9703 		if (geterror(bp) == 0) {
9704 			st_bioerror(bp, EIO);
9705 		}
9706 		st_set_pe_flag(un);
9707 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9708 		    (un->un_errno == EIO)) {
9709 			un->un_rqs_state &= ~(ST_RQS_VALID);
9710 		}
9711 		/*FALLTHROUGH*/
9712 	case COMMAND_DONE:
9713 		st_set_state(un, bp);
9714 		break;
9715 
9716 	case QUE_SENSE:
9717 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9718 			goto sense_error;
9719 
9720 		if (un->un_state != ST_STATE_SENSING) {
9721 			un->un_laststate = un->un_state;
9722 			un->un_state = ST_STATE_SENSING;
9723 		}
9724 
9725 		/*
9726 		 * zero the sense data.
9727 		 */
9728 		bzero(un->un_rqs->pkt_scbp, SENSE_LENGTH);
9729 
9730 		/*
9731 		 * If this is not a retry on QUE_SENSE point to the original
9732 		 * bp of the command that got us here.
9733 		 */
9734 		if (pkt != un->un_rqs) {
9735 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp = bp;
9736 		}
9737 
9738 		if (un->un_throttle) {
9739 			un->un_last_throttle = un->un_throttle;
9740 			un->un_throttle = 0;
9741 		}
9742 
9743 		ST_CDB(ST_DEVINFO, "Queue sense CDB",
9744 		    (char *)BP_PKT(bp)->pkt_cdbp);
9745 
9746 		/*
9747 		 * never retry this, some other command will have nuked the
9748 		 * sense, anyway
9749 		 */
9750 		status = st_transport(un, un->un_rqs);
9751 
9752 		if (un->un_last_throttle) {
9753 			un->un_throttle = un->un_last_throttle;
9754 		}
9755 
9756 		if (status == TRAN_ACCEPT) {
9757 			mutex_exit(ST_MUTEX);
9758 			return;
9759 		}
9760 		if (status != TRAN_BUSY)
9761 			ST_DO_ERRSTATS(un, st_transerrs);
9762 sense_error:
9763 		un->un_pos.pmode = invalid;
9764 		st_bioerror(bp, EIO);
9765 		st_set_pe_flag(un);
9766 		break;
9767 
9768 	case QUE_BUSY_COMMAND:
9769 		/* longish timeout */
9770 		timout = ST_STATUS_BUSY_TIMEOUT;
9771 		goto que_it_up;
9772 
9773 	case QUE_COMMAND:
9774 		/* short timeout */
9775 		timout = ST_TRAN_BUSY_TIMEOUT;
9776 que_it_up:
9777 		/*
9778 		 * let st_handle_intr_busy put this bp back on waitq and make
9779 		 * checks to see if it is ok to requeue the command.
9780 		 */
9781 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9782 
9783 		/*
9784 		 * Save the throttle before setting up the timeout
9785 		 */
9786 		if (un->un_throttle) {
9787 			un->un_last_throttle = un->un_throttle;
9788 		}
9789 		mutex_exit(ST_MUTEX);
9790 		if (st_handle_intr_busy(un, bp, timout) == 0)
9791 			return;		/* timeout is setup again */
9792 
9793 		mutex_enter(ST_MUTEX);
9794 		un->un_pos.pmode = invalid;
9795 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9796 		st_bioerror(bp, EIO);
9797 		st_set_pe_flag(un);
9798 		break;
9799 
9800 	case QUE_LAST_COMMAND:
9801 
9802 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9803 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9804 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9805 			goto last_command_error;
9806 		}
9807 		mutex_exit(ST_MUTEX);
9808 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9809 			return;
9810 		mutex_enter(ST_MUTEX);
9811 last_command_error:
9812 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9813 		un->un_pos.pmode = invalid;
9814 		st_bioerror(bp, EIO);
9815 		st_set_pe_flag(un);
9816 		break;
9817 
9818 	case COMMAND_TIMEOUT:
9819 	case DEVICE_RESET:
9820 	case DEVICE_TAMPER:
9821 	case ATTEMPT_RETRY:
9822 	case PATH_FAILED:
9823 		ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9824 		    "Command Recovery called on %s status\n",
9825 		    errstatenames[action]);
9826 		action = st_command_recovery(un, pkt, action);
9827 		goto again;
9828 
9829 	default:
9830 		ASSERT(0);
9831 		/* FALLTHRU */
9832 	case JUST_RETURN:
9833 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9834 		mutex_exit(ST_MUTEX);
9835 		return;
9836 	}
9837 
9838 	ST_DO_KSTATS(bp, kstat_runq_exit);
9839 	st_done_and_mutex_exit(un, bp);
9840 }
9841 
9842 static errstate
9843 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9844 {
9845 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9846 	recov_info *rinfo;
9847 	errstate rval = COMMAND_DONE_ERROR;
9848 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9849 	    un->un_rqs : BP_PKT(bp);
9850 	int result;
9851 
9852 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9853 
9854 	rinfo = (recov_info *)pkt->pkt_private;
9855 
9856 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9857 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9858 
9859 	ASSERT(mutex_owned(ST_MUTEX));
9860 
9861 	switch (pkt->pkt_reason) {
9862 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9863 		/*
9864 		 * this occurs when accessing a powered down drive, no
9865 		 * need to complain; just fail the open
9866 		 */
9867 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9868 
9869 		/*
9870 		 * if we have commands outstanding in HBA, and a command
9871 		 * comes back incomplete, we're hosed, so reset target
9872 		 * If we have the bus, but cmd_incomplete, we probably just
9873 		 * have a failed selection, so don't reset the target, just
9874 		 * requeue the command and try again
9875 		 */
9876 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9877 			goto reset_target;
9878 		}
9879 
9880 		/*
9881 		 * Retry selection a couple more times if we're
9882 		 * open.  If opening, we only try just once to
9883 		 * reduce probe time for nonexistant devices.
9884 		 */
9885 		if ((un->un_laststate > ST_STATE_OPENING) &&
9886 		    (rinfo->pkt_retry_cnt < st_selection_retry_count)) {
9887 			/* XXX check retriable? */
9888 			rval = QUE_COMMAND;
9889 		}
9890 		ST_DO_ERRSTATS(un, st_transerrs);
9891 		break;
9892 
9893 	case CMD_ABORTED:
9894 		/*
9895 		 * most likely this is caused by flush-on-error support. If
9896 		 * it was not there, the we're in trouble.
9897 		 */
9898 		if (!un->un_flush_on_errors) {
9899 			un->un_status = SUN_KEY_FATAL;
9900 			goto reset_target;
9901 		}
9902 
9903 		st_set_pe_errno(un);
9904 		bioerror(bp, un->un_errno);
9905 		if (un->un_errno)
9906 			return (COMMAND_DONE_ERROR);
9907 		else
9908 			return (COMMAND_DONE);
9909 
9910 	case CMD_TIMEOUT:	/* Command timed out */
9911 		un->un_status = SUN_KEY_TIMEOUT;
9912 		return (COMMAND_TIMEOUT);
9913 
9914 	case CMD_TRAN_ERR:
9915 	case CMD_RESET:
9916 		if (pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET)) {
9917 			if ((un->un_rsvd_status &
9918 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
9919 			    ST_RESERVE) {
9920 				un->un_rsvd_status |= ST_LOST_RESERVE;
9921 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
9922 				    "Lost Reservation\n");
9923 			}
9924 			rval = DEVICE_RESET;
9925 			return (rval);
9926 		}
9927 		if (pkt->pkt_statistics & (STAT_ABORTED | STAT_TERMINATED)) {
9928 			rval = DEVICE_RESET;
9929 			return (rval);
9930 		}
9931 		/*FALLTHROUGH*/
9932 	default:
9933 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9934 		    "Unhandled packet status reason = %s statistics = 0x%x\n",
9935 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9936 reset_target:
9937 
9938 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9939 		    "transport completed with %s\n",
9940 		    scsi_rname(pkt->pkt_reason));
9941 		ST_DO_ERRSTATS(un, st_transerrs);
9942 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
9943 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
9944 		    STAT_ABORTED)) == 0)) {
9945 
9946 			/*
9947 			 * If we haven't reserved the drive don't reset it.
9948 			 */
9949 			if ((un->un_rsvd_status &
9950 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9951 				return (rval);
9952 			}
9953 
9954 			/*
9955 			 * if we aren't lost yet we will be soon.
9956 			 */
9957 			un->un_pos.pmode = invalid;
9958 
9959 			result = st_reset(un, RESET_LUN);
9960 
9961 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
9962 				/* no hope left to recover */
9963 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
9964 				    "recovery by resets failed\n");
9965 				return (rval);
9966 			}
9967 		}
9968 	}
9969 
9970 
9971 	if (rinfo->pkt_retry_cnt++ < st_retry_count) {
9972 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9973 			rval = QUE_COMMAND;
9974 		} else if (bp == un->un_sbufp) {
9975 			if (rinfo->privatelen == sizeof (recov_info)) {
9976 				if (rinfo->cmd_attrib->retriable) {
9977 					/*
9978 					 * These commands can be rerun
9979 					 * with impunity
9980 					 */
9981 					rval = QUE_COMMAND;
9982 				}
9983 			} else {
9984 				cmd_attribute const *attrib;
9985 				attrib =
9986 				    st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
9987 				if (attrib->retriable) {
9988 					rval = QUE_COMMAND;
9989 				}
9990 			}
9991 		}
9992 	} else {
9993 		rval = COMMAND_DONE_ERROR;
9994 	}
9995 
9996 	if (un->un_state >= ST_STATE_OPEN) {
9997 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9998 		    fail, scsi_rname(pkt->pkt_reason),
9999 		    (rval == COMMAND_DONE_ERROR)?
10000 		    "giving up" : "retrying command");
10001 	}
10002 	return (rval);
10003 }
10004 
10005 /*
10006  * if the device is busy, then put this bp back on the waitq, on the
10007  * interrupt thread, where we want the head of the queue and not the
10008  * end
10009  *
10010  * The callers of this routine should take measures to save the
10011  * un_throttle in un_last_throttle which will be restored in
10012  * st_intr_restart(). The only exception should be st_intr_restart()
10013  * calling this routine for which the saving is already done.
10014  */
10015 static int
10016 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
10017 	clock_t timeout_interval)
10018 {
10019 
10020 	int queued;
10021 	int rval = 0;
10022 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
10023 
10024 	mutex_enter(ST_MUTEX);
10025 
10026 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
10027 
10028 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10029 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
10030 
10031 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
10032 		queued = 1;
10033 	} else {
10034 		queued = 0;
10035 	}
10036 
10037 	/*
10038 	 * Check to see if we hit the retry timeout. We check to make sure
10039 	 * this is the first one on the runq and make sure we have not
10040 	 * queued up any more, so this one has to be the last on the list
10041 	 * also. If it is not, we have to fail.  If it is not the first, but
10042 	 * is the last we are in trouble anyway, as we are in the interrupt
10043 	 * context here.
10044 	 */
10045 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
10046 	    ((un->un_runqf != bp) && (un->un_runql != bp) && (queued))) {
10047 		rval = -1;
10048 		goto exit;
10049 	}
10050 
10051 	/* put the bp back on the waitq */
10052 	if (queued) {
10053 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
10054 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
10055 	}
10056 
10057 	/*
10058 	 * We don't want any other commands being started in the mean time.
10059 	 * If start had just released mutex after putting something on the
10060 	 * runq, we won't even get here.
10061 	 */
10062 	un->un_throttle = 0;
10063 
10064 	/*
10065 	 * send a marker pkt, if appropriate
10066 	 */
10067 	st_hba_unflush(un);
10068 
10069 	/*
10070 	 * all queues are aligned, we are just waiting to
10071 	 * transport
10072 	 */
10073 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
10074 
10075 exit:
10076 	mutex_exit(ST_MUTEX);
10077 	return (rval);
10078 }
10079 
10080 /*
10081  * To get one error entry from error stack
10082  */
10083 static int
10084 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
10085 {
10086 #ifdef _MULTI_DATAMODEL
10087 	/*
10088 	 * For use when a 32 bit app makes a call into a
10089 	 * 64 bit ioctl
10090 	 */
10091 	struct mterror_entry32 err_entry32;
10092 #endif /* _MULTI_DATAMODEL */
10093 
10094 	int rval = 0;
10095 	struct mterror_entry err_entry;
10096 	struct mterror_entry_stack *err_link_entry_p;
10097 	size_t arq_status_len_in, arq_status_len_kr;
10098 
10099 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
10100 
10101 	ASSERT(mutex_owned(ST_MUTEX));
10102 
10103 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10104 	    "st_get_error_entry()\n");
10105 
10106 	/*
10107 	 * if error record stack empty, return ENXIO
10108 	 */
10109 	if (un->un_error_entry_stk == NULL) {
10110 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10111 		    "st_get_error_entry: Error Entry Stack Empty!\n");
10112 		rval = ENXIO;
10113 		goto ret;
10114 	}
10115 
10116 	/*
10117 	 * get the top entry from stack
10118 	 */
10119 	err_link_entry_p = un->un_error_entry_stk;
10120 	arq_status_len_kr =
10121 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
10122 
10123 #ifdef _MULTI_DATAMODEL
10124 	switch (ddi_model_convert_from(flag & FMODELS)) {
10125 	case DDI_MODEL_ILP32:
10126 		if (ddi_copyin((void *)arg, &err_entry32,
10127 		    MTERROR_ENTRY_SIZE_32, flag)) {
10128 			rval = EFAULT;
10129 			goto ret;
10130 		}
10131 
10132 		arq_status_len_in =
10133 		    (size_t)err_entry32.mtee_arq_status_len;
10134 
10135 		err_entry32.mtee_cdb_len =
10136 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
10137 
10138 		if (arq_status_len_in > arq_status_len_kr)
10139 			err_entry32.mtee_arq_status_len =
10140 			    (size32_t)arq_status_len_kr;
10141 
10142 		if (ddi_copyout(
10143 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10144 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
10145 		    err_entry32.mtee_cdb_len, flag)) {
10146 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10147 			    "st_get_error_entry: Copy cdb buffer error!");
10148 			rval = EFAULT;
10149 		}
10150 
10151 		if (ddi_copyout(
10152 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10153 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
10154 		    err_entry32.mtee_arq_status_len, flag)) {
10155 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10156 			    "st_get_error_entry: copy arq status error!");
10157 			rval = EFAULT;
10158 		}
10159 
10160 		if (ddi_copyout(&err_entry32, (void *)arg,
10161 		    MTERROR_ENTRY_SIZE_32, flag)) {
10162 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10163 			    "st_get_error_entry: copy arq status out error!");
10164 			rval = EFAULT;
10165 		}
10166 		break;
10167 
10168 	case DDI_MODEL_NONE:
10169 		if (ddi_copyin((void *)arg, &err_entry,
10170 		    MTERROR_ENTRY_SIZE_64, flag)) {
10171 			rval = EFAULT;
10172 			goto ret;
10173 		}
10174 		arq_status_len_in = err_entry.mtee_arq_status_len;
10175 
10176 		err_entry.mtee_cdb_len =
10177 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
10178 
10179 		if (arq_status_len_in > arq_status_len_kr)
10180 			err_entry.mtee_arq_status_len =
10181 			    arq_status_len_kr;
10182 
10183 		if (ddi_copyout(
10184 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10185 		    err_entry.mtee_cdb_buf,
10186 		    err_entry.mtee_cdb_len, flag)) {
10187 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10188 			    "st_get_error_entry: Copy cdb buffer error!");
10189 			rval = EFAULT;
10190 		}
10191 
10192 		if (ddi_copyout(
10193 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10194 		    err_entry.mtee_arq_status,
10195 		    err_entry.mtee_arq_status_len, flag)) {
10196 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10197 			    "st_get_error_entry: copy arq status error!");
10198 			rval = EFAULT;
10199 		}
10200 
10201 		if (ddi_copyout(&err_entry, (void *)arg,
10202 		    MTERROR_ENTRY_SIZE_64, flag)) {
10203 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10204 			    "st_get_error_entry: copy arq status out error!");
10205 			rval = EFAULT;
10206 		}
10207 		break;
10208 	}
10209 #else /* _MULTI_DATAMODEL */
10210 	if (ddi_copyin((void *)arg, &err_entry,
10211 	    MTERROR_ENTRY_SIZE_64, flag)) {
10212 		rval = EFAULT;
10213 		goto ret;
10214 	}
10215 	arq_status_len_in = err_entry.mtee_arq_status_len;
10216 
10217 	err_entry.mtee_cdb_len =
10218 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
10219 
10220 	if (arq_status_len_in > arq_status_len_kr)
10221 		err_entry.mtee_arq_status_len =
10222 		    arq_status_len_kr;
10223 
10224 	if (ddi_copyout(
10225 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10226 	    err_entry.mtee_cdb_buf,
10227 	    err_entry.mtee_cdb_len, flag)) {
10228 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10229 		    "st_get_error_entry: Copy cdb buffer error!");
10230 		rval = EFAULT;
10231 	}
10232 
10233 	if (ddi_copyout(
10234 	    err_link_entry_p->mtees_entry.mtee_arq_status,
10235 	    err_entry.mtee_arq_status,
10236 	    err_entry.mtee_arq_status_len, flag)) {
10237 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10238 		    "st_get_error_entry: copy arq status buffer error!");
10239 		rval = EFAULT;
10240 	}
10241 
10242 	if (ddi_copyout(&err_entry, (void *)arg,
10243 	    MTERROR_ENTRY_SIZE_64, flag)) {
10244 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10245 		    "st_get_error_entry: copy arq status out error!");
10246 		rval = EFAULT;
10247 	}
10248 #endif /* _MULTI_DATAMODEL */
10249 
10250 	/*
10251 	 * update stack
10252 	 */
10253 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
10254 
10255 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
10256 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
10257 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
10258 
10259 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
10260 	    SECMDS_STATUS_SIZE);
10261 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
10262 
10263 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
10264 	err_link_entry_p = NULL;
10265 ret:
10266 	return (rval);
10267 }
10268 
10269 /*
10270  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
10271  * the scsi CDB command which causes the error and generates sense data and
10272  * the scsi status.
10273  *
10274  *      error-record stack
10275  *
10276  *
10277  *             TOP                                     BOTTOM
10278  *              ------------------------------------------
10279  *              |   0   |   1   |   2   |   ...  |   n   |
10280  *              ------------------------------------------
10281  *                  ^
10282  *                  |
10283  *       pointer to error entry
10284  *
10285  * when st driver generates one sense data record, it creates a error-entry
10286  * and pushes it onto the stack.
10287  *
10288  */
10289 
10290 static void
10291 st_update_error_stack(struct scsi_tape *un,
10292 			struct scsi_pkt *pkt,
10293 			struct scsi_arq_status *cmd)
10294 {
10295 	struct mterror_entry_stack *err_entry_tmp;
10296 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
10297 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
10298 
10299 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
10300 
10301 	ASSERT(mutex_owned(ST_MUTEX));
10302 
10303 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10304 	    "st_update_error_stack()\n");
10305 
10306 	ASSERT(cmd);
10307 	ASSERT(cdbp);
10308 	if (cdblen == 0) {
10309 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10310 		    "st_update_error_stack: CDB length error!\n");
10311 		return;
10312 	}
10313 
10314 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
10315 	ASSERT(err_entry_tmp != NULL);
10316 
10317 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
10318 	    kmem_alloc(cdblen, KM_SLEEP);
10319 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
10320 
10321 	err_entry_tmp->mtees_entry.mtee_arq_status =
10322 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
10323 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
10324 
10325 	/*
10326 	 * copy cdb command & length to current error entry
10327 	 */
10328 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
10329 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
10330 
10331 	/*
10332 	 * copy scsi status length to current error entry
10333 	 */
10334 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
10335 	    SECMDS_STATUS_SIZE;
10336 
10337 	/*
10338 	 * copy sense data and scsi status to current error entry
10339 	 */
10340 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
10341 	    SECMDS_STATUS_SIZE);
10342 
10343 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
10344 	un->un_error_entry_stk = err_entry_tmp;
10345 
10346 }
10347 
10348 /*
10349  * Empty all the error entry in stack
10350  */
10351 static void
10352 st_empty_error_stack(struct scsi_tape *un)
10353 {
10354 	struct mterror_entry_stack *linkp;
10355 
10356 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
10357 
10358 	ASSERT(mutex_owned(ST_MUTEX));
10359 
10360 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10361 	    "st_empty_entry_stack()\n");
10362 
10363 	while (un->un_error_entry_stk != NULL) {
10364 		linkp = un->un_error_entry_stk;
10365 		un->un_error_entry_stk =
10366 		    un->un_error_entry_stk->mtees_nextp;
10367 
10368 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
10369 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
10370 			    linkp->mtees_entry.mtee_cdb_len);
10371 
10372 		if (linkp->mtees_entry.mtee_arq_status != NULL)
10373 			kmem_free(linkp->mtees_entry.mtee_arq_status,
10374 			    linkp->mtees_entry.mtee_arq_status_len);
10375 
10376 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
10377 		linkp = NULL;
10378 	}
10379 }
10380 
10381 static errstate
10382 st_handle_sense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10383 {
10384 	struct scsi_pkt *pkt = BP_PKT(bp);
10385 	struct scsi_pkt *rqpkt = un->un_rqs;
10386 	struct scsi_arq_status arqstat;
10387 	recov_info *rcif = pkt->pkt_private;
10388 
10389 	errstate rval = COMMAND_DONE_ERROR;
10390 	int amt;
10391 
10392 	ST_FUNC(ST_DEVINFO, st_handle_sense);
10393 
10394 	ASSERT(mutex_owned(ST_MUTEX));
10395 
10396 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10397 	    "st_handle_sense()\n");
10398 
10399 	if (SCBP(rqpkt)->sts_busy) {
10400 		if (rcif->privatelen == sizeof (recov_info)) {
10401 			ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
10402 			    "Attempt recovery of busy unit on request sense\n");
10403 			rval = ATTEMPT_RETRY;
10404 		} else if (rcif->pkt_retry_cnt++ < st_retry_count) {
10405 			ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10406 			    "Retry busy unit on request sense\n");
10407 			rval = QUE_BUSY_COMMAND;
10408 		}
10409 		return (rval);
10410 	} else if (SCBP(rqpkt)->sts_chk) {
10411 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10412 		    "Check Condition on REQUEST SENSE\n");
10413 		return (rval);
10414 	}
10415 
10416 	/*
10417 	 * Make sure there is sense data to look at.
10418 	 */
10419 	if ((rqpkt->pkt_state & (STATE_GOT_BUS | STATE_GOT_TARGET |
10420 	    STATE_SENT_CMD | STATE_GOT_STATUS)) != (STATE_GOT_BUS |
10421 	    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) {
10422 		return (rval);
10423 	}
10424 
10425 	/* was there enough data? */
10426 	amt = (int)MAX_SENSE_LENGTH - rqpkt->pkt_resid;
10427 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
10428 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10429 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10430 		    "REQUEST SENSE couldn't get sense data\n");
10431 		return (rval);
10432 	}
10433 
10434 	bcopy(SCBP(pkt), &arqstat.sts_status,
10435 	    sizeof (struct scsi_status));
10436 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
10437 	    sizeof (struct scsi_status));
10438 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
10439 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
10440 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
10441 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
10442 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
10443 
10444 	/*
10445 	 * copy one arqstat entry in the sense data buffer
10446 	 */
10447 	st_update_error_stack(un, pkt, &arqstat);
10448 	return (st_decode_sense(un, bp, amt, &arqstat, pos));
10449 }
10450 
10451 static errstate
10452 st_handle_autosense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10453 {
10454 	struct scsi_pkt *pkt = BP_PKT(bp);
10455 	struct scsi_arq_status *arqstat =
10456 	    (struct scsi_arq_status *)pkt->pkt_scbp;
10457 	errstate rval = COMMAND_DONE_ERROR;
10458 	int amt;
10459 
10460 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
10461 
10462 	ASSERT(mutex_owned(ST_MUTEX));
10463 
10464 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10465 	    "st_handle_autosense()\n");
10466 
10467 	if (arqstat->sts_rqpkt_status.sts_busy) {
10468 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10469 		    "busy unit on request sense\n");
10470 		/*
10471 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
10472 		 * the disadvantage is that we do not have any delay for the
10473 		 * second retry of rqsense and we have to keep a packet around
10474 		 */
10475 		return (QUE_SENSE);
10476 
10477 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
10478 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10479 		    "transport error on REQUEST SENSE\n");
10480 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
10481 		    ((arqstat->sts_rqpkt_statistics &
10482 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
10483 			if (st_reset(un, RESET_LUN) == 0) {
10484 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10485 				    "recovery by resets failed\n");
10486 			}
10487 		}
10488 		return (rval);
10489 
10490 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
10491 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10492 		    "Check Condition on REQUEST SENSE\n");
10493 		return (rval);
10494 	}
10495 
10496 
10497 	/* was there enough data? */
10498 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10499 		amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10500 	} else {
10501 		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
10502 			amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10503 		} else {
10504 			amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10505 		}
10506 	}
10507 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
10508 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10509 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10510 		    "REQUEST SENSE couldn't get sense data\n");
10511 		return (rval);
10512 	}
10513 
10514 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10515 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, MAX_SENSE_LENGTH);
10516 	} else {
10517 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
10518 	}
10519 
10520 	/*
10521 	 * copy one arqstat entry in the sense data buffer
10522 	 */
10523 	st_update_error_stack(un, pkt, arqstat);
10524 
10525 	return (st_decode_sense(un, bp, amt, arqstat, pos));
10526 }
10527 
10528 static errstate
10529 st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
10530     struct scsi_arq_status *statusp, tapepos_t *pos)
10531 {
10532 	struct scsi_pkt *pkt = BP_PKT(bp);
10533 	recov_info *ri = pkt->pkt_private;
10534 	errstate rval = COMMAND_DONE_ERROR;
10535 	cmd_attribute const *attrib;
10536 	long resid;
10537 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10538 	int severity;
10539 	int get_error;
10540 
10541 	ST_FUNC(ST_DEVINFO, st_decode_sense);
10542 
10543 	ASSERT(mutex_owned(ST_MUTEX));
10544 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10545 	    "st_decode_sense()\n");
10546 
10547 	/*
10548 	 * For uscsi commands, squirrel away a copy of the
10549 	 * results of the Request Sense.
10550 	 */
10551 	if (USCSI_CMD(bp)) {
10552 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
10553 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
10554 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
10555 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
10556 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
10557 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
10558 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10559 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
10560 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
10561 		}
10562 	}
10563 
10564 	if (ri->privatelen == sizeof (recov_info)) {
10565 		attrib = ri->cmd_attrib;
10566 	} else {
10567 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10568 	}
10569 
10570 	/*
10571 	 * If the drive is an MT-02, reposition the
10572 	 * secondary error code into the proper place.
10573 	 *
10574 	 * XXX	MT-02 is non-CCS tape, so secondary error code
10575 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
10576 	 * so it's in byte 12.
10577 	 */
10578 	if (un->un_dp->type == ST_TYPE_EMULEX) {
10579 		sensep->es_code = sensep->es_add_info[0];
10580 	}
10581 
10582 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
10583 	    (caddr_t)&CDBP(pkt)->scc_cmd);
10584 
10585 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)statusp,
10586 	    sizeof (*statusp));
10587 
10588 	/* for normal I/O check extract the resid values. */
10589 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
10590 		if (sensep->es_valid) {
10591 			resid =
10592 			    (sensep->es_info_1 << 24) |
10593 			    (sensep->es_info_2 << 16) |
10594 			    (sensep->es_info_3 << 8)  |
10595 			    (sensep->es_info_4);
10596 			/* If fixed block */
10597 			if (un->un_bsize) {
10598 				resid *= un->un_bsize;
10599 			}
10600 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
10601 			resid = pkt->pkt_resid;
10602 		} else {
10603 			resid = bp->b_bcount;
10604 		}
10605 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10606 		    "st_decode_sense (rw): xferred bit = %d, resid=%ld (%d), "
10607 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
10608 		    resid,
10609 		    (sensep->es_info_1 << 24) |
10610 		    (sensep->es_info_2 << 16) |
10611 		    (sensep->es_info_3 << 8)  |
10612 		    (sensep->es_info_4),
10613 		    pkt->pkt_resid);
10614 		/*
10615 		 * The problem is, what should we believe?
10616 		 */
10617 		if (resid && (pkt->pkt_resid == 0)) {
10618 			pkt->pkt_resid = resid;
10619 		}
10620 	} else {
10621 		/*
10622 		 * If the command is SCMD_SPACE, we need to get the
10623 		 * residual as returned in the sense data, to adjust
10624 		 * our idea of current tape position correctly
10625 		 */
10626 		if ((sensep->es_valid) &&
10627 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10628 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10629 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
10630 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE_G4) ||
10631 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK)) {
10632 			resid =
10633 			    (sensep->es_info_1 << 24) |
10634 			    (sensep->es_info_2 << 16) |
10635 			    (sensep->es_info_3 << 8)  |
10636 			    (sensep->es_info_4);
10637 			bp->b_resid = resid;
10638 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10639 			    "st_decode_sense(other):	resid=%ld\n", resid);
10640 		} else {
10641 			/*
10642 			 * If the special command is SCMD_READ,
10643 			 * the correct resid will be set later.
10644 			 */
10645 			if (attrib->get_cnt != NULL) {
10646 				resid = attrib->get_cnt(pkt->pkt_cdbp);
10647 			} else {
10648 				resid = bp->b_bcount;
10649 			}
10650 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10651 			    "st_decode_sense(special read):  resid=%ld\n",
10652 			    resid);
10653 		}
10654 	}
10655 
10656 	if ((un->un_state >= ST_STATE_OPEN) &&
10657 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
10658 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
10659 		    "Failed CDB", (char *)pkt->pkt_cdbp);
10660 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10661 		    "sense data", (char *)sensep, amt);
10662 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10663 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10664 		    bp->b_bcount, resid, pkt->pkt_resid);
10665 	}
10666 
10667 	switch (un->un_status = sensep->es_key) {
10668 	case KEY_NO_SENSE:
10669 		severity = SCSI_ERR_INFO;
10670 
10671 		/*
10672 		 * Erase, locate or rewind operation in progress, retry
10673 		 * ASC  ASCQ
10674 		 *  00   18    Erase operation in progress
10675 		 *  00   19    Locate operation in progress
10676 		 *  00   1A    Rewind operation in progress
10677 		 */
10678 		if (sensep->es_add_code == 0 &&
10679 		    ((sensep->es_qual_code == 0x18) ||
10680 		    (sensep->es_qual_code == 0x19) ||
10681 		    (sensep->es_qual_code == 0x1a))) {
10682 			rval = QUE_BUSY_COMMAND;
10683 			break;
10684 		}
10685 
10686 		goto common;
10687 
10688 	case KEY_RECOVERABLE_ERROR:
10689 		severity = SCSI_ERR_RECOVERED;
10690 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10691 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10692 			if (un->un_dp->options &
10693 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10694 				rval = QUE_LAST_COMMAND;
10695 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10696 				    severity, pos->lgclblkno,
10697 				    un->un_err_pos.lgclblkno, scsi_cmds,
10698 				    sensep);
10699 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10700 				    "Command will be retried\n");
10701 			} else {
10702 				severity = SCSI_ERR_FATAL;
10703 				rval = COMMAND_DONE_ERROR_RECOVERED;
10704 				ST_DO_ERRSTATS(un, st_softerrs);
10705 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10706 				    severity, pos->lgclblkno,
10707 				    un->un_err_pos.lgclblkno, scsi_cmds,
10708 				    sensep);
10709 			}
10710 			break;
10711 		}
10712 common:
10713 		/*
10714 		 * XXX only want reads to be stopped by filemarks.
10715 		 * Don't want them to be stopped by EOT.  EOT matters
10716 		 * only on write.
10717 		 */
10718 		if (sensep->es_filmk && !sensep->es_eom) {
10719 			rval = COMMAND_DONE;
10720 		} else if (sensep->es_eom) {
10721 			rval = COMMAND_DONE;
10722 		} else if (sensep->es_ili) {
10723 			/*
10724 			 * Fun with variable length record devices:
10725 			 * for specifying larger blocks sizes than the
10726 			 * actual physical record size.
10727 			 */
10728 			if (un->un_bsize == 0 && resid > 0) {
10729 				/*
10730 				 * XXX! Ugly.
10731 				 * The requested blocksize is > tape blocksize,
10732 				 * so this is ok, so we just return the
10733 				 * actual size xferred.
10734 				 */
10735 				pkt->pkt_resid = resid;
10736 				rval = COMMAND_DONE;
10737 			} else if (un->un_bsize == 0 && resid < 0) {
10738 				/*
10739 				 * The requested blocksize is < tape blocksize,
10740 				 * so this is not ok, so we err with ENOMEM
10741 				 */
10742 				rval = COMMAND_DONE_ERROR_RECOVERED;
10743 				st_bioerror(bp, ENOMEM);
10744 			} else {
10745 				ST_DO_ERRSTATS(un, st_softerrs);
10746 				severity = SCSI_ERR_FATAL;
10747 				rval = COMMAND_DONE_ERROR;
10748 				st_bioerror(bp, EINVAL);
10749 				un->un_running.pmode = invalid;
10750 			}
10751 		} else {
10752 			/*
10753 			 * we hope and pray for this just being
10754 			 * something we can ignore (ie. a
10755 			 * truly recoverable soft error)
10756 			 */
10757 			rval = COMMAND_DONE;
10758 		}
10759 		if (sensep->es_filmk) {
10760 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10761 			    "filemark\n");
10762 			un->un_status = SUN_KEY_EOF;
10763 			pos->eof = ST_EOF_PENDING;
10764 			st_set_pe_flag(un);
10765 		}
10766 
10767 		/*
10768 		 * ignore eom when reading, a fmk should terminate reading
10769 		 */
10770 		if ((sensep->es_eom) &&
10771 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10772 			if ((sensep->es_add_code == 0) &&
10773 			    (sensep->es_qual_code == 4)) {
10774 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10775 				    "bot\n");
10776 				un->un_status = SUN_KEY_BOT;
10777 				pos->eof = ST_NO_EOF;
10778 				pos->lgclblkno = 0;
10779 				pos->fileno = 0;
10780 				pos->blkno = 0;
10781 				if (pos->pmode != legacy)
10782 					pos->pmode = legacy;
10783 			} else {
10784 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10785 				    "eom\n");
10786 				un->un_status = SUN_KEY_EOT;
10787 				pos->eof = ST_EOM;
10788 			}
10789 			st_set_pe_flag(un);
10790 		}
10791 
10792 		break;
10793 
10794 	case KEY_ILLEGAL_REQUEST:
10795 
10796 		if (un->un_laststate >= ST_STATE_OPEN) {
10797 			ST_DO_ERRSTATS(un, st_softerrs);
10798 			severity = SCSI_ERR_FATAL;
10799 		} else {
10800 			severity = SCSI_ERR_INFO;
10801 		}
10802 		break;
10803 
10804 	case KEY_MEDIUM_ERROR:
10805 		ST_DO_ERRSTATS(un, st_harderrs);
10806 		severity = SCSI_ERR_FATAL;
10807 check_keys:
10808 		/*
10809 		 * attempt to process the keys in the presence of
10810 		 * other errors
10811 		 */
10812 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10813 			/*
10814 			 * Fun with variable length record devices:
10815 			 * for specifying larger blocks sizes than the
10816 			 * actual physical record size.
10817 			 */
10818 			if (un->un_bsize == 0 && resid > 0) {
10819 				/*
10820 				 * XXX! Ugly
10821 				 */
10822 				pkt->pkt_resid = resid;
10823 			} else if (un->un_bsize == 0 && resid < 0) {
10824 				st_bioerror(bp, EINVAL);
10825 			} else {
10826 				severity = SCSI_ERR_FATAL;
10827 				rval = COMMAND_DONE_ERROR;
10828 				st_bioerror(bp, EINVAL);
10829 			}
10830 		}
10831 		if (sensep->es_filmk) {
10832 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10833 			    "filemark\n");
10834 			un->un_status = SUN_KEY_EOF;
10835 			pos->eof = ST_EOF_PENDING;
10836 			st_set_pe_flag(un);
10837 		}
10838 
10839 		/*
10840 		 * ignore eom when reading, a fmk should terminate reading
10841 		 */
10842 		if ((sensep->es_eom) &&
10843 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10844 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10845 			un->un_status = SUN_KEY_EOT;
10846 			pos->eof = ST_EOM;
10847 			st_set_pe_flag(un);
10848 		}
10849 
10850 		break;
10851 
10852 	case KEY_VOLUME_OVERFLOW:
10853 		ST_DO_ERRSTATS(un, st_softerrs);
10854 		pos->eof = ST_EOM;
10855 		severity = SCSI_ERR_FATAL;
10856 		rval = COMMAND_DONE_ERROR;
10857 		goto check_keys;
10858 
10859 	case KEY_HARDWARE_ERROR:
10860 		ST_DO_ERRSTATS(un, st_harderrs);
10861 		severity = SCSI_ERR_FATAL;
10862 		rval = COMMAND_DONE_ERROR;
10863 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10864 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10865 		break;
10866 
10867 	case KEY_BLANK_CHECK:
10868 		ST_DO_ERRSTATS(un, st_softerrs);
10869 		severity = SCSI_ERR_INFO;
10870 
10871 		/*
10872 		 * if not a special request and some data was xferred then it
10873 		 * it is not an error yet
10874 		 */
10875 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10876 			/*
10877 			 * no error for read with or without data xferred
10878 			 */
10879 			un->un_status = SUN_KEY_EOT;
10880 			pos->eof = ST_EOT;
10881 			rval = COMMAND_DONE_ERROR;
10882 			un->un_running.pmode = invalid;
10883 			st_set_pe_flag(un);
10884 			goto check_keys;
10885 		} else if (bp != un->un_sbufp &&
10886 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10887 			rval = COMMAND_DONE;
10888 		} else {
10889 			rval = COMMAND_DONE_ERROR_RECOVERED;
10890 		}
10891 
10892 		if (un->un_laststate >= ST_STATE_OPEN) {
10893 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10894 			    "blank check\n");
10895 			pos->eof = ST_EOM;
10896 		}
10897 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10898 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10899 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
10900 		    (un->un_dp->options & ST_KNOWS_EOD)) {
10901 			/*
10902 			 * we were doing a fast forward by skipping
10903 			 * multiple fmk at the time
10904 			 */
10905 			st_bioerror(bp, EIO);
10906 			severity = SCSI_ERR_RECOVERED;
10907 			rval	 = COMMAND_DONE;
10908 		}
10909 		st_set_pe_flag(un);
10910 		goto check_keys;
10911 
10912 	case KEY_WRITE_PROTECT:
10913 		if (st_wrongtapetype(un)) {
10914 			un->un_status = SUN_KEY_WRONGMEDIA;
10915 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10916 			    "wrong tape for writing- use DC6150 tape "
10917 			    "(or equivalent)\n");
10918 			severity = SCSI_ERR_UNKNOWN;
10919 		} else {
10920 			severity = SCSI_ERR_FATAL;
10921 		}
10922 		ST_DO_ERRSTATS(un, st_harderrs);
10923 		rval = COMMAND_DONE_ERROR;
10924 		st_bioerror(bp, EACCES);
10925 		break;
10926 
10927 	case KEY_UNIT_ATTENTION:
10928 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10929 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
10930 
10931 		un->un_unit_attention_flags |= 1;
10932 		/*
10933 		 * If we have detected a Bus Reset and the tape
10934 		 * drive has been reserved.
10935 		 */
10936 		if (ST_RQSENSE->es_add_code == 0x29) {
10937 			rval = DEVICE_RESET;
10938 			if ((un->un_rsvd_status &
10939 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
10940 			    ST_RESERVE) {
10941 				un->un_rsvd_status |= ST_LOST_RESERVE;
10942 				ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
10943 				    "st_decode_sense: Lost Reservation\n");
10944 			}
10945 		}
10946 
10947 		/*
10948 		 * If this is a recovery command and retrable, retry.
10949 		 */
10950 		if (bp == un->un_recov_buf) {
10951 			severity = SCSI_ERR_INFO;
10952 			if (attrib->retriable &&
10953 			    ri->pkt_retry_cnt++ < st_retry_count) {
10954 				rval = QUE_COMMAND;
10955 			} else {
10956 				rval = COMMAND_DONE_ERROR;
10957 			}
10958 			break; /* Don't set position invalid */
10959 		}
10960 
10961 		/*
10962 		 * If ST_APPLICATION_RESERVATIONS is set,
10963 		 * If the asc/ascq indicates that the reservation
10964 		 * has been cleared just allow the write to continue
10965 		 * which would force a scsi 2 reserve.
10966 		 * If preempted that persistent reservation
10967 		 * the scsi 2 reserve would get a reservation conflict.
10968 		 */
10969 		if ((un->un_rsvd_status &
10970 		    ST_APPLICATION_RESERVATIONS) != 0) {
10971 			/*
10972 			 * RESERVATIONS PREEMPTED
10973 			 * With MPxIO this could be a fail over? XXX
10974 			 */
10975 			if (ST_RQSENSE->es_add_code == 0x2a &&
10976 			    ST_RQSENSE->es_qual_code == 0x03) {
10977 				severity = SCSI_ERR_INFO;
10978 				rval = COMMAND_DONE_ERROR;
10979 				pos->pmode = invalid;
10980 			/*
10981 			 * RESERVATIONS RELEASED
10982 			 */
10983 			} else if (ST_RQSENSE->es_add_code == 0x2a &&
10984 			    ST_RQSENSE->es_qual_code == 0x04) {
10985 				rval = COMMAND_DONE;
10986 			}
10987 			break;
10988 		}
10989 
10990 		if (un->un_state <= ST_STATE_OPENING) {
10991 			/*
10992 			 * Look, the tape isn't open yet, now determine
10993 			 * if the cause is a BUS RESET, Save the file
10994 			 * and Block positions for the callers to
10995 			 * recover from the loss of position.
10996 			 */
10997 			severity = SCSI_ERR_INFO;
10998 			if ((pos->pmode != invalid) &&
10999 			    (rval == DEVICE_RESET) &&
11000 			    (un->un_restore_pos != 1)) {
11001 				un->un_save_fileno = pos->fileno;
11002 				un->un_save_blkno = pos->blkno;
11003 				un->un_restore_pos = 1;
11004 			}
11005 
11006 			if (attrib->retriable &&
11007 			    ri->pkt_retry_cnt++ < st_retry_count) {
11008 				rval = QUE_COMMAND;
11009 			} else if (rval == DEVICE_RESET) {
11010 				break;
11011 			} else {
11012 				rval = COMMAND_DONE_ERROR;
11013 			}
11014 		/*
11015 		 * Means it thinks the mode parameters have changed.
11016 		 * This is the result of a reset clearing settings or
11017 		 * another initiator changing what we set.
11018 		 */
11019 		}
11020 		if (ST_RQSENSE->es_add_code == 0x2a) {
11021 			if (ST_RQSENSE->es_qual_code == 0x1) {
11022 				/* Error recovery will modeselect and retry. */
11023 				rval = DEVICE_TAMPER;
11024 				severity = SCSI_ERR_INFO;
11025 				break; /* don't set position invalid */
11026 			}
11027 			if (ST_RQSENSE->es_qual_code == 0x0 ||
11028 			    ST_RQSENSE->es_qual_code == 0x2 ||
11029 			    ST_RQSENSE->es_qual_code == 0x3 ||
11030 			    ST_RQSENSE->es_qual_code == 0x4 ||
11031 			    ST_RQSENSE->es_qual_code == 0x5 ||
11032 			    ST_RQSENSE->es_qual_code == 0x6 ||
11033 			    ST_RQSENSE->es_qual_code == 0x7) {
11034 				rval = DEVICE_TAMPER;
11035 				severity = SCSI_ERR_INFO;
11036 			}
11037 		} else if (ST_RQSENSE->es_add_code == 0x28 &&
11038 		    ((ST_RQSENSE->es_qual_code == 0x0) ||
11039 		    ST_RQSENSE->es_qual_code == 0x5)) {
11040 			/*
11041 			 * Not Ready to Ready change, Media may have changed.
11042 			 */
11043 			rval = DEVICE_TAMPER;
11044 			severity = SCSI_ERR_RETRYABLE;
11045 		} else {
11046 			if (rval != DEVICE_RESET) {
11047 				rval = COMMAND_DONE_ERROR;
11048 			} else {
11049 				/*
11050 				 * Returning DEVICE_RESET will call
11051 				 * error recovery.
11052 				 */
11053 				severity = SCSI_ERR_INFO;
11054 				break; /* don't set position invalid */
11055 			}
11056 			/*
11057 			 * Check if it is an Unexpected Unit Attention.
11058 			 * If state is >= ST_STATE_OPEN, we have
11059 			 * already done the initialization .
11060 			 * In this case it is Fatal Error
11061 			 * since no further reading/writing
11062 			 * can be done with fileno set to < 0.
11063 			 */
11064 			if (un->un_state >= ST_STATE_OPEN) {
11065 				ST_DO_ERRSTATS(un, st_harderrs);
11066 				severity = SCSI_ERR_FATAL;
11067 			} else {
11068 				severity = SCSI_ERR_INFO;
11069 			}
11070 		}
11071 
11072 		pos->pmode = invalid;
11073 
11074 		break;
11075 
11076 	case KEY_NOT_READY:
11077 		/*
11078 		 * If in process of getting ready retry.
11079 		 */
11080 		if (sensep->es_add_code  == 0x04 &&
11081 		    sensep->es_qual_code == 0x01 &&
11082 		    ri->pkt_retry_cnt++ < st_retry_count) {
11083 			rval = QUE_COMMAND;
11084 			severity = SCSI_ERR_INFO;
11085 		} else {
11086 			/* give up */
11087 			rval = COMMAND_DONE_ERROR;
11088 			severity = SCSI_ERR_FATAL;
11089 		}
11090 
11091 		/*
11092 		 * If this was an error and after device opened
11093 		 * do error stats.
11094 		 */
11095 		if (rval == COMMAND_DONE_ERROR &&
11096 		    un->un_state > ST_STATE_OPENING) {
11097 			ST_DO_ERRSTATS(un, st_harderrs);
11098 		}
11099 
11100 		if (ST_RQSENSE->es_add_code == 0x3a) {
11101 			if (st_error_level >= SCSI_ERR_FATAL)
11102 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11103 				    "Tape not inserted in drive\n");
11104 			un->un_mediastate = MTIO_EJECTED;
11105 			cv_broadcast(&un->un_state_cv);
11106 		}
11107 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
11108 		    (rval != QUE_COMMAND))
11109 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
11110 		break;
11111 
11112 	case KEY_ABORTED_COMMAND:
11113 		/* XXX Do drives return this when they see a lost light? */
11114 		/* Testing would say yes */
11115 
11116 		if (ri->pkt_retry_cnt++ < st_retry_count) {
11117 			rval = ATTEMPT_RETRY;
11118 			severity = SCSI_ERR_RETRYABLE;
11119 			goto check_keys;
11120 		}
11121 		/*
11122 		 * Probably a parity error...
11123 		 * if we retry here then this may cause data to be
11124 		 * written twice or data skipped during reading
11125 		 */
11126 		ST_DO_ERRSTATS(un, st_harderrs);
11127 		severity = SCSI_ERR_FATAL;
11128 		rval = COMMAND_DONE_ERROR;
11129 		goto check_keys;
11130 
11131 	default:
11132 		/*
11133 		 * Undecoded sense key.	 Try retries and hope
11134 		 * that will fix the problem.  Otherwise, we're
11135 		 * dead.
11136 		 */
11137 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11138 		    "Unhandled Sense Key '%s'\n",
11139 		    sense_keys[un->un_status]);
11140 		ST_DO_ERRSTATS(un, st_harderrs);
11141 		severity = SCSI_ERR_FATAL;
11142 		rval = COMMAND_DONE_ERROR;
11143 		goto check_keys;
11144 	}
11145 
11146 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
11147 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
11148 	    (un->un_laststate > ST_STATE_OPENING) &&
11149 	    (severity >= st_error_level))) {
11150 
11151 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
11152 		    pos->lgclblkno, un->un_err_pos.lgclblkno,
11153 		    scsi_cmds, sensep);
11154 		if (sensep->es_filmk) {
11155 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11156 			    "File Mark Detected\n");
11157 		}
11158 		if (sensep->es_eom) {
11159 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11160 			    "End-of-Media Detected\n");
11161 		}
11162 		if (sensep->es_ili) {
11163 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11164 			    "Incorrect Length Indicator Set\n");
11165 		}
11166 	}
11167 	get_error = geterror(bp);
11168 	if (((rval == COMMAND_DONE_ERROR) ||
11169 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
11170 	    ((get_error == EIO) || (get_error == 0))) {
11171 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
11172 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
11173 		if (un->un_rqs_state & ST_RQS_READ) {
11174 			un->un_rqs_state &= ~(ST_RQS_READ);
11175 		} else {
11176 			un->un_rqs_state |= ST_RQS_OVR;
11177 		}
11178 	}
11179 
11180 	return (rval);
11181 }
11182 
11183 
11184 static int
11185 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
11186 {
11187 	int status = TRAN_ACCEPT;
11188 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
11189 
11190 	mutex_enter(ST_MUTEX);
11191 
11192 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
11193 
11194 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11195 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
11196 
11197 	/*
11198 	 * Check to see if we hit the retry timeout. We check to make sure
11199 	 * this is the first one on the runq and make sure we have not
11200 	 * queued up any more, so this one has to be the last on the list
11201 	 * also. If it is not, we have to fail.  If it is not the first, but
11202 	 * is the last we are in trouble anyway, as we are in the interrupt
11203 	 * context here.
11204 	 */
11205 	if ((pktinfo->pkt_retry_cnt > st_retry_count) ||
11206 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
11207 		goto exit;
11208 	}
11209 
11210 	if (un->un_throttle) {
11211 		un->un_last_throttle = un->un_throttle;
11212 		un->un_throttle = 0;
11213 	}
11214 
11215 	/*
11216 	 * Here we know : bp is the first and last one on the runq
11217 	 * it is not necessary to put it back on the head of the
11218 	 * waitq and then move from waitq to runq. Save this queuing
11219 	 * and call scsi_transport.
11220 	 */
11221 	ST_CDB(ST_DEVINFO, "Retry lcmd CDB", (char *)BP_PKT(bp)->pkt_cdbp);
11222 
11223 	status = st_transport(un, BP_PKT(bp));
11224 
11225 	if (status == TRAN_ACCEPT) {
11226 		if (un->un_last_throttle) {
11227 			un->un_throttle = un->un_last_throttle;
11228 		}
11229 		mutex_exit(ST_MUTEX);
11230 
11231 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11232 		    "restart transport \n");
11233 		return (0);
11234 	}
11235 
11236 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
11237 	mutex_exit(ST_MUTEX);
11238 
11239 	if (status == TRAN_BUSY) {
11240 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
11241 			return (0);
11242 		}
11243 	}
11244 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11245 	    "restart transport rejected\n");
11246 	mutex_enter(ST_MUTEX);
11247 	ST_DO_ERRSTATS(un, st_transerrs);
11248 	if (un->un_last_throttle) {
11249 		un->un_throttle = un->un_last_throttle;
11250 	}
11251 exit:
11252 	mutex_exit(ST_MUTEX);
11253 	return (-1);
11254 }
11255 
11256 static int
11257 st_wrongtapetype(struct scsi_tape *un)
11258 {
11259 
11260 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
11261 
11262 	ASSERT(mutex_owned(ST_MUTEX));
11263 
11264 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
11265 
11266 	/*
11267 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
11268 	 */
11269 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
11270 		switch (un->un_dp->type) {
11271 		case ST_TYPE_WANGTEK:
11272 		case ST_TYPE_ARCHIVE:
11273 			/*
11274 			 * If this really worked, we could go off of
11275 			 * the density codes set in the modesense
11276 			 * page. For this drive, 0x10 == QIC-120,
11277 			 * 0xf == QIC-150, and 0x5 should be for
11278 			 * both QIC-24 and, maybe, QIC-11. However,
11279 			 * the h/w doesn't do what the manual says
11280 			 * that it should, so we'll key off of
11281 			 * getting a WRITE PROTECT error AND wp *not*
11282 			 * set in the mode sense information.
11283 			 */
11284 			/*
11285 			 * XXX but we already know that status is
11286 			 * write protect, so don't check it again.
11287 			 */
11288 
11289 			if (un->un_status == KEY_WRITE_PROTECT &&
11290 			    un->un_mspl->wp == 0) {
11291 				return (1);
11292 			}
11293 			break;
11294 		default:
11295 			break;
11296 		}
11297 	}
11298 	return (0);
11299 }
11300 
11301 static errstate
11302 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
11303 {
11304 	errstate action;
11305 	recov_info *rcvi = pkt->pkt_private;
11306 	buf_t *bp = rcvi->cmd_bp;
11307 	struct scsi_arq_status *stat = (struct scsi_arq_status *)pkt->pkt_scbp;
11308 
11309 	ST_FUNC(ST_DEVINFO, st_check_error);
11310 
11311 	ASSERT(mutex_owned(ST_MUTEX));
11312 
11313 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
11314 
11315 	switch (SCBP_C(pkt)) {
11316 	case STATUS_RESERVATION_CONFLICT:
11317 		/*
11318 		 * Command recovery is enabled, not just opening,
11319 		 * we had the drive reserved and we thing its ours.
11320 		 * Call recovery to attempt to take it back.
11321 		 */
11322 		if ((rcvi->privatelen == sizeof (recov_info)) &&
11323 		    (bp != un->un_recov_buf) &&
11324 		    (un->un_state > ST_STATE_OPEN_PENDING_IO) &&
11325 		    ((un->un_rsvd_status & (ST_RESERVE |
11326 		    ST_APPLICATION_RESERVATIONS)) != 0)) {
11327 			action = ATTEMPT_RETRY;
11328 			un->un_rsvd_status |= ST_LOST_RESERVE;
11329 		} else {
11330 			action = COMMAND_DONE_EACCES;
11331 			un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
11332 		}
11333 		break;
11334 
11335 	case STATUS_BUSY:
11336 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
11337 		if (rcvi->privatelen == sizeof (recov_info) &&
11338 		    un->un_multipath && (pkt->pkt_state == (STATE_GOT_BUS |
11339 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS))) {
11340 			/*
11341 			 * Status returned by scsi_vhci indicating path
11342 			 * has failed over.
11343 			 */
11344 			action = PATH_FAILED;
11345 			break;
11346 		}
11347 		/* FALLTHRU */
11348 	case STATUS_QFULL:
11349 		if (rcvi->privatelen == sizeof (recov_info)) {
11350 			/*
11351 			 * If recovery is inabled use it instead of
11352 			 * blind reties.
11353 			 */
11354 			action = ATTEMPT_RETRY;
11355 		} else if (rcvi->pkt_retry_cnt++ < st_retry_count) {
11356 			action = QUE_BUSY_COMMAND;
11357 		} else if ((un->un_rsvd_status &
11358 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
11359 			/*
11360 			 * If this is a command done before reserve is done
11361 			 * don't reset.
11362 			 */
11363 			action = COMMAND_DONE_ERROR;
11364 		} else {
11365 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11366 			    "unit busy too long\n");
11367 			(void) st_reset(un, RESET_ALL);
11368 			action = COMMAND_DONE_ERROR;
11369 		}
11370 		break;
11371 
11372 	case STATUS_CHECK:
11373 	case STATUS_TERMINATED:
11374 		/*
11375 		 * we should only get here if the auto rqsense failed
11376 		 * thru a uscsi cmd without autorequest sense
11377 		 * so we just try again
11378 		 */
11379 		if (un->un_arq_enabled &&
11380 		    stat->sts_rqpkt_reason == CMD_CMPLT &&
11381 		    (stat->sts_rqpkt_state & (STATE_GOT_BUS |
11382 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) ==
11383 		    (STATE_GOT_BUS | STATE_GOT_TARGET | STATE_SENT_CMD |
11384 		    STATE_GOT_STATUS)) {
11385 
11386 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11387 			    "Really got sense data\n");
11388 			action = st_decode_sense(un, bp, MAX_SENSE_LENGTH -
11389 			    pkt->pkt_resid, stat, &un->un_pos);
11390 		} else {
11391 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11392 			    "Trying to queue sense command\n");
11393 			action = QUE_SENSE;
11394 		}
11395 		break;
11396 
11397 	case STATUS_TASK_ABORT:
11398 		/*
11399 		 * This is an aborted task. This can be a reset on the other
11400 		 * port of a multiport drive. Lets try and recover it.
11401 		 */
11402 		action = DEVICE_RESET;
11403 		break;
11404 
11405 	default:
11406 		action = COMMAND_DONE;
11407 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
11408 		    "Unexpected scsi status byte 0x%x\n", SCBP_C(pkt));
11409 	}
11410 	return (action);
11411 }
11412 
11413 static void
11414 st_calc_bnum(struct scsi_tape *un, struct buf *bp, struct scsi_pkt *pkt)
11415 {
11416 	int nblks;
11417 	int nfiles;
11418 	long count;
11419 	recov_info *ri = pkt->pkt_private;
11420 	cmd_attribute const *attrib;
11421 
11422 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
11423 
11424 	ASSERT(mutex_owned(ST_MUTEX));
11425 
11426 	if (ri->privatelen == sizeof (recov_info)) {
11427 		attrib = ri->cmd_attrib;
11428 		ASSERT(attrib->recov_pos_type == POS_EXPECTED);
11429 		ASSERT(attrib->chg_tape_pos);
11430 	} else {
11431 		ri = NULL;
11432 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
11433 	}
11434 
11435 	count = bp->b_bcount - bp->b_resid;
11436 
11437 	/* Command reads or writes data */
11438 	if (attrib->transfers_data != TRAN_NONE) {
11439 		if (count == 0) {
11440 			/* failed writes should not make it here */
11441 			ASSERT(attrib->transfers_data == TRAN_READ);
11442 			nblks = 0;
11443 			nfiles = 1;
11444 		} else if (un->un_bsize == 0) {
11445 			/*
11446 			 * If variable block mode.
11447 			 * Fixed bit in CBD should be zero.
11448 			 */
11449 			ASSERT((pkt->pkt_cdbp[1] & 1) == 0);
11450 			nblks = 1;
11451 			un->un_kbytes_xferred += (count / ONE_K);
11452 			nfiles = 0;
11453 		} else {
11454 			/*
11455 			 * If fixed block mode.
11456 			 * Fixed bit in CBD should be one.
11457 			 */
11458 			ASSERT((pkt->pkt_cdbp[1] & 1) == 1);
11459 			nblks = (count / un->un_bsize);
11460 			un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
11461 			nfiles = 0;
11462 		}
11463 		/*
11464 		 * So its possable to read some blocks and hit a filemark.
11465 		 * Example reading in fixed block mode where more then one
11466 		 * block at a time is requested. In this case because the
11467 		 * filemark is hit something less then the requesed number
11468 		 * of blocks is read.
11469 		 */
11470 		if (un->un_pos.eof == ST_EOF_PENDING && bp->b_resid) {
11471 			nfiles = 1;
11472 		}
11473 	} else {
11474 		nblks = 0;
11475 		nfiles = count;
11476 	}
11477 
11478 	/*
11479 	 * If some command failed after this one started and it seems
11480 	 * to have finshed without error count the position.
11481 	 */
11482 	if (un->un_persistence && un->un_persist_errors) {
11483 		ASSERT(un->un_pos.pmode != invalid);
11484 	}
11485 
11486 	if (attrib->chg_tape_direction == DIR_FORW) {
11487 		un->un_pos.blkno += nblks;
11488 		un->un_pos.lgclblkno += nblks;
11489 		un->un_pos.lgclblkno += nfiles;
11490 	} else if (attrib->chg_tape_direction == DIR_REVC) {
11491 		un->un_pos.blkno -= nblks;
11492 		un->un_pos.lgclblkno -= nblks;
11493 		un->un_pos.lgclblkno -= nfiles;
11494 	} else {
11495 		ASSERT(0);
11496 	}
11497 
11498 	/* recovery disabled */
11499 	if (ri == NULL) {
11500 		un->un_running.pmode = invalid;
11501 		return;
11502 	}
11503 
11504 	/*
11505 	 * If we didn't just read a filemark.
11506 	 */
11507 	if (un->un_pos.eof != ST_EOF_PENDING) {
11508 		ASSERT(nblks != 0 && nfiles == 0);
11509 		/*
11510 		 * If Previously calulated expected position does not match
11511 		 * debug the expected position.
11512 		 */
11513 		if ((ri->pos.pmode != invalid) && nblks &&
11514 		    ((un->un_pos.blkno != ri->pos.blkno) ||
11515 		    (un->un_pos.lgclblkno != ri->pos.lgclblkno))) {
11516 #ifdef STDEBUG
11517 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11518 			    "Expected", &ri->pos);
11519 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11520 			    "But Got", &un->un_pos);
11521 #endif
11522 			un->un_running.pmode = invalid;
11523 		}
11524 	} else {
11525 		ASSERT(nfiles != 0);
11526 		if (un->un_running.pmode != invalid) {
11527 			/*
11528 			 * blkno and lgclblkno already counted in
11529 			 * st_add_recovery_info_to_pkt(). Since a block was not
11530 			 * read and a filemark was.
11531 			 */
11532 			if (attrib->chg_tape_direction == DIR_FORW) {
11533 				un->un_running.fileno++;
11534 				un->un_running.blkno = 0;
11535 			} else if (attrib->chg_tape_direction == DIR_REVC) {
11536 				un->un_running.fileno--;
11537 				un->un_running.blkno = LASTBLK;
11538 			}
11539 		}
11540 	}
11541 }
11542 
11543 static void
11544 st_set_state(struct scsi_tape *un, struct buf *bp)
11545 {
11546 	struct scsi_pkt *sp = BP_PKT(bp);
11547 	struct uscsi_cmd *ucmd;
11548 
11549 	ST_FUNC(ST_DEVINFO, st_set_state);
11550 
11551 	ASSERT(mutex_owned(ST_MUTEX));
11552 	ASSERT(bp != un->un_recov_buf);
11553 
11554 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11555 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
11556 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
11557 
11558 	if (bp != un->un_sbufp) {
11559 #ifdef STDEBUG
11560 		if (DEBUGGING && sp->pkt_resid) {
11561 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11562 			    "pkt_resid %ld bcount %ld\n",
11563 			    sp->pkt_resid, bp->b_bcount);
11564 		}
11565 #endif
11566 		bp->b_resid = sp->pkt_resid;
11567 		if (geterror(bp) != EIO) {
11568 			st_calc_bnum(un, bp, sp);
11569 		}
11570 		if (bp->b_flags & B_READ) {
11571 			un->un_lastop = ST_OP_READ;
11572 			un->un_fmneeded = 0;
11573 		} else {
11574 			un->un_lastop = ST_OP_WRITE;
11575 			if (un->un_dp->options & ST_REEL) {
11576 				un->un_fmneeded = 2;
11577 			} else {
11578 				un->un_fmneeded = 1;
11579 			}
11580 		}
11581 		/*
11582 		 * all is honky dory at this point, so let's
11583 		 * readjust the throttle, to increase speed, if we
11584 		 * have not throttled down.
11585 		 */
11586 		if (un->un_throttle) {
11587 			un->un_throttle = un->un_max_throttle;
11588 		}
11589 	} else {
11590 		optype new_lastop = ST_OP_NIL;
11591 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
11592 
11593 		switch (cmd) {
11594 		case SCMD_WRITE:
11595 		case SCMD_WRITE_G4:
11596 			bp->b_resid = sp->pkt_resid;
11597 			new_lastop = ST_OP_WRITE;
11598 			if (geterror(bp) == EIO) {
11599 				break;
11600 			}
11601 			st_calc_bnum(un, bp, sp);
11602 			if (un->un_dp->options & ST_REEL) {
11603 				un->un_fmneeded = 2;
11604 			} else {
11605 				un->un_fmneeded = 1;
11606 			}
11607 			break;
11608 		case SCMD_READ:
11609 		case SCMD_READ_G4:
11610 			bp->b_resid = sp->pkt_resid;
11611 			new_lastop = ST_OP_READ;
11612 			if (geterror(bp) == EIO) {
11613 				break;
11614 			}
11615 			st_calc_bnum(un, bp, sp);
11616 			un->un_fmneeded = 0;
11617 			break;
11618 		case SCMD_WRITE_FILE_MARK_G4:
11619 		case SCMD_WRITE_FILE_MARK:
11620 		{
11621 			int fmdone;
11622 
11623 			if (un->un_pos.eof != ST_EOM) {
11624 				un->un_pos.eof = ST_NO_EOF;
11625 			}
11626 			fmdone = (bp->b_bcount - bp->b_resid);
11627 			if (fmdone > 0) {
11628 				un->un_lastop = new_lastop = ST_OP_WEOF;
11629 				un->un_pos.lgclblkno += fmdone;
11630 				un->un_pos.fileno += fmdone;
11631 				un->un_pos.blkno = 0;
11632 			} else {
11633 				new_lastop = ST_OP_CTL;
11634 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11635 				    "Flushed buffer\n");
11636 			}
11637 			if (fmdone > un->un_fmneeded) {
11638 				un->un_fmneeded = 0;
11639 			} else {
11640 				un->un_fmneeded -= fmdone;
11641 			}
11642 			break;
11643 		}
11644 		case SCMD_REWIND:
11645 			un->un_pos.eof = ST_NO_EOF;
11646 			un->un_pos.fileno = 0;
11647 			un->un_pos.blkno = 0;
11648 			un->un_pos.lgclblkno = 0;
11649 			if (un->un_pos.pmode != legacy)
11650 				un->un_pos.pmode = legacy;
11651 			new_lastop = ST_OP_CTL;
11652 			un->un_restore_pos = 0;
11653 			break;
11654 
11655 		case SCMD_SPACE:
11656 		case SCMD_SPACE_G4:
11657 		{
11658 			int64_t count;
11659 			int64_t resid;
11660 			int64_t done;
11661 			cmd_attribute const *attrib;
11662 			recov_info *ri = sp->pkt_private;
11663 
11664 			if (ri->privatelen == sizeof (recov_info)) {
11665 				attrib = ri->cmd_attrib;
11666 			} else {
11667 				attrib =
11668 				    st_lookup_cmd_attribute(sp->pkt_cdbp[0]);
11669 			}
11670 
11671 			resid = (int64_t)SPACE_CNT(bp->b_resid);
11672 			count = (int64_t)attrib->get_cnt(sp->pkt_cdbp);
11673 
11674 			if (count >= 0) {
11675 				done = (count - resid);
11676 			} else {
11677 				done = ((-count) - resid);
11678 			}
11679 			if (done > 0) {
11680 				un->un_lastop = new_lastop = ST_OP_CTL;
11681 			} else {
11682 				new_lastop = ST_OP_CTL;
11683 			}
11684 
11685 			ST_SPAC(ST_DEVINFO, st_label, CE_WARN,
11686 			    "space cmd: cdb[1] = %s\n"
11687 			    "space data:       = 0x%lx\n"
11688 			    "space count:      = %"PRId64"\n"
11689 			    "space resid:      = %"PRId64"\n"
11690 			    "spaces done:      = %"PRId64"\n"
11691 			    "fileno before     = %d\n"
11692 			    "blkno before      = %d\n",
11693 			    space_strs[sp->pkt_cdbp[1] & 7],
11694 			    bp->b_bcount,
11695 			    count, resid, done,
11696 			    un->un_pos.fileno, un->un_pos.blkno);
11697 
11698 			switch (sp->pkt_cdbp[1]) {
11699 			case SPACE_TYPE(SP_FLM):
11700 				/* Space file forward */
11701 				if (count >= 0) {
11702 					if (un->un_pos.eof <= ST_EOF) {
11703 						un->un_pos.eof = ST_NO_EOF;
11704 					}
11705 					un->un_pos.fileno += done;
11706 					un->un_pos.blkno = 0;
11707 					break;
11708 				}
11709 				/* Space file backward */
11710 				if (done > un->un_pos.fileno) {
11711 					un->un_pos.fileno = 0;
11712 					un->un_pos.blkno = 0;
11713 				} else {
11714 					un->un_pos.fileno -= done;
11715 					un->un_pos.blkno = LASTBLK;
11716 					un->un_running.pmode = invalid;
11717 				}
11718 				break;
11719 			case SPACE_TYPE(SP_BLK):
11720 				/* Space block forward */
11721 				if (count >= 0) {
11722 					un->un_pos.blkno += done;
11723 					break;
11724 				}
11725 				/* Space block backward */
11726 				if (un->un_pos.eof >= ST_EOF_PENDING) {
11727 				/*
11728 				 * we stepped back into
11729 				 * a previous file; we are not
11730 				 * making an effort to pretend that
11731 				 * we are still in the current file
11732 				 * ie. logical == physical position
11733 				 * and leave it to st_ioctl to correct
11734 				 */
11735 					if (done > un->un_pos.blkno) {
11736 						un->un_pos.blkno = 0;
11737 					} else {
11738 						un->un_pos.fileno--;
11739 						un->un_pos.blkno = LASTBLK;
11740 						un->un_running.pmode = invalid;
11741 					}
11742 				} else {
11743 					un->un_pos.blkno -= done;
11744 				}
11745 				break;
11746 			case SPACE_TYPE(SP_SQFLM):
11747 				un->un_pos.pmode = logical;
11748 				un->un_pos.blkno = 0;
11749 				un->un_lastop = new_lastop = ST_OP_CTL;
11750 				break;
11751 			case SPACE_TYPE(SP_EOD):
11752 				un->un_pos.pmode = logical;
11753 				un->un_pos.eof = ST_EOM;
11754 				un->un_status = KEY_BLANK_CHECK;
11755 				break;
11756 			default:
11757 				un->un_pos.pmode = invalid;
11758 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11759 				    "Unsupported space cmd: %s\n",
11760 				    space_strs[sp->pkt_cdbp[1] & 7]);
11761 
11762 				un->un_lastop = new_lastop = ST_OP_CTL;
11763 			}
11764 
11765 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11766 			    "after_space rs %"PRId64" fil %d blk %d\n",
11767 			    resid, un->un_pos.fileno, un->un_pos.blkno);
11768 
11769 			break;
11770 		}
11771 		case SCMD_LOAD:
11772 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
11773 				un->un_pos.fileno = 0;
11774 				if (un->un_pos.pmode != legacy)
11775 					un->un_pos.pmode = legacy;
11776 			} else {
11777 				un->un_state = ST_STATE_OFFLINE;
11778 				un->un_pos.pmode = invalid;
11779 
11780 			}
11781 			/*
11782 			 * If we are loading or unloading we expect the media id
11783 			 * to change. Lets make it unknown.
11784 			 */
11785 			if (un->un_media_id != bogusID && un->un_media_id_len) {
11786 				kmem_free(un->un_media_id, un->un_media_id_len);
11787 				un->un_media_id = NULL;
11788 				un->un_media_id_len = 0;
11789 			}
11790 			un->un_density_known = 0;
11791 			un->un_pos.eof = ST_NO_EOF;
11792 			un->un_pos.blkno = 0;
11793 			un->un_lastop = new_lastop = ST_OP_CTL;
11794 			break;
11795 		case SCMD_ERASE:
11796 			un->un_pos.eof = ST_NO_EOF;
11797 			un->un_pos.blkno = 0;
11798 			un->un_pos.fileno = 0;
11799 			un->un_pos.lgclblkno = 0;
11800 			if (un->un_pos.pmode != legacy)
11801 				un->un_pos.pmode = legacy;
11802 			new_lastop = ST_OP_CTL;
11803 			break;
11804 		case SCMD_RESERVE:
11805 			un->un_rsvd_status |= ST_RESERVE;
11806 			un->un_rsvd_status &=
11807 			    ~(ST_RELEASE | ST_LOST_RESERVE |
11808 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11809 			new_lastop = ST_OP_CTL;
11810 			break;
11811 		case SCMD_RELEASE:
11812 			un->un_rsvd_status |= ST_RELEASE;
11813 			un->un_rsvd_status &=
11814 			    ~(ST_RESERVE | ST_LOST_RESERVE |
11815 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11816 			new_lastop = ST_OP_CTL;
11817 			break;
11818 		case SCMD_PERSISTENT_RESERVE_IN:
11819 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11820 			    "PGR_IN command\n");
11821 			new_lastop = ST_OP_CTL;
11822 			break;
11823 		case SCMD_PERSISTENT_RESERVE_OUT:
11824 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
11825 			case ST_SA_SCSI3_RESERVE:
11826 			case ST_SA_SCSI3_PREEMPT:
11827 			case ST_SA_SCSI3_PREEMPTANDABORT:
11828 				un->un_rsvd_status |=
11829 				    (ST_APPLICATION_RESERVATIONS | ST_RESERVE);
11830 				un->un_rsvd_status &= ~(ST_RELEASE |
11831 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11832 				    ST_INITIATED_RESET);
11833 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11834 				    "PGR Reserve and set: entering"
11835 				    " ST_APPLICATION_RESERVATIONS mode");
11836 				break;
11837 			case ST_SA_SCSI3_REGISTER:
11838 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11839 				    "PGR Reserve register key");
11840 				un->un_rsvd_status |= ST_INIT_RESERVE;
11841 				break;
11842 			case ST_SA_SCSI3_CLEAR:
11843 				un->un_rsvd_status &= ~ST_INIT_RESERVE;
11844 				/* FALLTHROUGH */
11845 			case ST_SA_SCSI3_RELEASE:
11846 				un->un_rsvd_status &=
11847 				    ~(ST_APPLICATION_RESERVATIONS | ST_RESERVE |
11848 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11849 				    ST_INITIATED_RESET);
11850 				un->un_rsvd_status |= ST_RELEASE;
11851 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11852 				    "PGR Release and reset: exiting"
11853 				    " ST_APPLICATION_RESERVATIONS mode");
11854 				break;
11855 			}
11856 			new_lastop = ST_OP_CTL;
11857 			break;
11858 		case SCMD_TEST_UNIT_READY:
11859 		case SCMD_READ_BLKLIM:
11860 		case SCMD_REQUEST_SENSE:
11861 		case SCMD_INQUIRY:
11862 		case SCMD_RECOVER_BUF:
11863 		case SCMD_MODE_SELECT:
11864 		case SCMD_MODE_SENSE:
11865 		case SCMD_DOORLOCK:
11866 		case SCMD_READ_BUFFER:
11867 		case SCMD_REPORT_DENSITIES:
11868 		case SCMD_LOG_SELECT_G1:
11869 		case SCMD_LOG_SENSE_G1:
11870 		case SCMD_REPORT_LUNS:
11871 		case SCMD_READ_ATTRIBUTE:
11872 		case SCMD_WRITE_ATTRIBUTE:
11873 		case SCMD_SVC_ACTION_IN_G5:
11874 			new_lastop = ST_OP_CTL;
11875 			break;
11876 		case SCMD_READ_POSITION:
11877 			new_lastop = ST_OP_CTL;
11878 			/*
11879 			 * Only if the buf used was un_sbufp.
11880 			 * Among other things the prevents read positions used
11881 			 * as part of error recovery from messing up our
11882 			 * current position as they will use un_recov_buf.
11883 			 */
11884 			if (USCSI_CMD(bp)) {
11885 				(void) st_get_read_pos(un, bp);
11886 			}
11887 			break;
11888 		case SCMD_LOCATE:
11889 		case SCMD_LOCATE_G4:
11890 			/* Locate makes position mode no longer legacy */
11891 			un->un_lastop = new_lastop = ST_OP_CTL;
11892 			break;
11893 		case SCMD_MAINTENANCE_IN:
11894 			switch (sp->pkt_cdbp[1]) {
11895 			case SSVC_ACTION_GET_SUPPORTED_OPERATIONS:
11896 			case SSVC_ACTION_SET_TARGET_PORT_GROUPS:
11897 				new_lastop = ST_OP_CTL;
11898 				break;
11899 			}
11900 			if (new_lastop != ST_OP_NIL) {
11901 				break;
11902 			}
11903 		default:
11904 			/*
11905 			 * Unknown command, If was USCSI and USCSI_SILENT
11906 			 * flag was not set, set position to unknown.
11907 			 */
11908 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
11909 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
11910 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11911 				    "unknown cmd 0x%X caused loss of state\n",
11912 				    cmd);
11913 			} else {
11914 				/*
11915 				 * keep the old agreement to allow unknown
11916 				 * commands with the USCSI_SILENT set.
11917 				 * This prevents ASSERT below.
11918 				 */
11919 				new_lastop = ST_OP_CTL;
11920 				break;
11921 			}
11922 			/* FALLTHROUGH */
11923 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
11924 			un->un_pos.pmode = invalid;
11925 			un->un_lastop = new_lastop = ST_OP_CTL;
11926 			break;
11927 		}
11928 
11929 		/* new_lastop should have been changed */
11930 		ASSERT(new_lastop != ST_OP_NIL);
11931 
11932 		/* If un_lastop should copy new_lastop  */
11933 		if (((un->un_lastop == ST_OP_WRITE) ||
11934 		    (un->un_lastop == ST_OP_WEOF)) &&
11935 		    new_lastop != ST_OP_CTL) {
11936 			un->un_lastop = new_lastop;
11937 		}
11938 	}
11939 
11940 	/*
11941 	 * In the st driver we have a logical and physical file position.
11942 	 * Under BSD behavior, when you get a zero read, the logical position
11943 	 * is before the filemark but after the last record of the file.
11944 	 * The physical position is after the filemark. MTIOCGET should always
11945 	 * return the logical file position.
11946 	 *
11947 	 * The next read gives a silent skip to the next file.
11948 	 * Under SVR4, the logical file position remains before the filemark
11949 	 * until the file is closed or a space operation is performed.
11950 	 * Hence set err_resid and err_file before changing fileno if case
11951 	 * BSD Behaviour.
11952 	 */
11953 	un->un_err_resid = bp->b_resid;
11954 	COPY_POS(&un->un_err_pos, &un->un_pos);
11955 
11956 
11957 	/*
11958 	 * If we've seen a filemark via the last read operation
11959 	 * advance the file counter, but mark things such that
11960 	 * the next read operation gets a zero count. We have
11961 	 * to put this here to handle the case of sitting right
11962 	 * at the end of a tape file having seen the file mark,
11963 	 * but the tape is closed and then re-opened without
11964 	 * any further i/o. That is, the position information
11965 	 * must be updated before a close.
11966 	 */
11967 
11968 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
11969 		/*
11970 		 * If we're a 1/2" tape, and we get a filemark
11971 		 * right on block 0, *AND* we were not in the
11972 		 * first file on the tape, and we've hit logical EOM.
11973 		 * We'll mark the state so that later we do the
11974 		 * right thing (in st_close(), st_strategy() or
11975 		 * st_ioctl()).
11976 		 *
11977 		 */
11978 		if ((un->un_dp->options & ST_REEL) &&
11979 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
11980 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
11981 			un->un_pos.eof = ST_EOT_PENDING;
11982 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11983 			    "eot pending\n");
11984 			un->un_pos.fileno++;
11985 			un->un_pos.blkno = 0;
11986 		} else if (BSD_BEHAVIOR) {
11987 			/*
11988 			 * If the read of the filemark was a side effect
11989 			 * of reading some blocks (i.e., data was actually
11990 			 * read), then the EOF mark is pending and the
11991 			 * bump into the next file awaits the next read
11992 			 * operation (which will return a zero count), or
11993 			 * a close or a space operation, else the bump
11994 			 * into the next file occurs now.
11995 			 */
11996 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11997 			    "resid=%lx, bcount=%lx\n",
11998 			    bp->b_resid, bp->b_bcount);
11999 
12000 			if (bp->b_resid != bp->b_bcount) {
12001 				un->un_pos.eof = ST_EOF;
12002 			} else {
12003 				un->un_silent_skip = 1;
12004 				un->un_pos.eof = ST_NO_EOF;
12005 				un->un_pos.fileno++;
12006 				un->un_pos.lgclblkno++;
12007 				un->un_save_blkno = un->un_pos.blkno;
12008 				un->un_pos.blkno = 0;
12009 			}
12010 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12011 			    "eof of file %d, eof=%d\n",
12012 			    un->un_pos.fileno, un->un_pos.eof);
12013 		} else if (SVR4_BEHAVIOR) {
12014 			/*
12015 			 * If the read of the filemark was a side effect
12016 			 * of reading some blocks (i.e., data was actually
12017 			 * read), then the next read should return 0
12018 			 */
12019 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12020 			    "resid=%lx, bcount=%lx\n",
12021 			    bp->b_resid, bp->b_bcount);
12022 			if (bp->b_resid == bp->b_bcount) {
12023 				un->un_pos.eof = ST_EOF;
12024 			}
12025 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12026 			    "eof of file=%d, eof=%d\n",
12027 			    un->un_pos.fileno, un->un_pos.eof);
12028 		}
12029 	}
12030 }
12031 
12032 /*
12033  * set the correct un_errno, to take corner cases into consideration
12034  */
12035 static void
12036 st_set_pe_errno(struct scsi_tape *un)
12037 {
12038 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
12039 
12040 	ASSERT(mutex_owned(ST_MUTEX));
12041 
12042 	/* if errno is already set, don't reset it */
12043 	if (un->un_errno)
12044 		return;
12045 
12046 	/* here un_errno == 0 */
12047 	/*
12048 	 * if the last transfer before flushing all the
12049 	 * waiting I/O's, was 0 (resid = count), then we
12050 	 * want to give the user an error on all the rest,
12051 	 * so here.  If there was a transfer, we set the
12052 	 * resid and counts to 0, and let it drop through,
12053 	 * giving a zero return.  the next I/O will then
12054 	 * give an error.
12055 	 */
12056 	if (un->un_last_resid == un->un_last_count) {
12057 		switch (un->un_pos.eof) {
12058 		case ST_EOM:
12059 			un->un_errno = ENOMEM;
12060 			break;
12061 		case ST_EOT:
12062 		case ST_EOF:
12063 			un->un_errno = EIO;
12064 			break;
12065 		}
12066 	} else {
12067 		/*
12068 		 * we know they did not have a zero, so make
12069 		 * sure they get one
12070 		 */
12071 		un->un_last_resid = un->un_last_count = 0;
12072 	}
12073 }
12074 
12075 
12076 /*
12077  * send in a marker pkt to terminate flushing of commands by BBA (via
12078  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
12079  */
12080 static void
12081 st_hba_unflush(struct scsi_tape *un)
12082 {
12083 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
12084 
12085 	ASSERT(mutex_owned(ST_MUTEX));
12086 
12087 	if (!un->un_flush_on_errors)
12088 		return;
12089 
12090 #ifdef FLUSH_ON_ERRORS
12091 
12092 	if (!un->un_mkr_pkt) {
12093 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
12094 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
12095 
12096 		/* we slept, so it must be there */
12097 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
12098 	}
12099 
12100 	st_transport(un, un->un_mkr_pkt);
12101 #endif
12102 }
12103 
12104 static char *
12105 st_print_scsi_cmd(char cmd)
12106 {
12107 	char tmp[64];
12108 	char *cpnt;
12109 
12110 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
12111 	/* tmp goes out of scope on return and caller sees garbage */
12112 	if (cpnt == tmp) {
12113 		cpnt = "Unknown Command";
12114 	}
12115 	return (cpnt);
12116 }
12117 
12118 static void
12119 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
12120     char *title, char *cdb)
12121 {
12122 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
12123 	char buf[256];
12124 	struct scsi_tape *un;
12125 	int instance = ddi_get_instance(dip);
12126 
12127 	un = ddi_get_soft_state(st_state, instance);
12128 
12129 	ST_FUNC(dip, st_print_cdb);
12130 
12131 	/* force one line output so repeated commands are printed once */
12132 	if ((st_debug & 0x180) == 0x100) {
12133 		scsi_log(dip, label, level, "node %s cmd %s\n",
12134 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
12135 		return;
12136 	}
12137 
12138 	/* force one line output so repeated CDB's are printed once */
12139 	if ((st_debug & 0x180) == 0x80) {
12140 		st_clean_print(dip, label, level, NULL, cdb, len);
12141 	} else {
12142 		(void) sprintf(buf, "%s for cmd(%s)", title,
12143 		    st_print_scsi_cmd(*cdb));
12144 		st_clean_print(dip, label, level, buf, cdb, len);
12145 	}
12146 }
12147 
12148 static void
12149 st_clean_print(dev_info_t *dev, char *label, uint_t level,
12150     char *title, char *data, int len)
12151 {
12152 	int	i;
12153 	int 	c;
12154 	char	*format;
12155 	char	buf[256];
12156 	uchar_t	byte;
12157 
12158 	ST_FUNC(dev, st_clean_print);
12159 
12160 
12161 	if (title) {
12162 		(void) sprintf(buf, "%s:\n", title);
12163 		scsi_log(dev, label, level, "%s", buf);
12164 		level = CE_CONT;
12165 	}
12166 
12167 	for (i = 0; i < len; ) {
12168 		buf[0] = 0;
12169 		for (c = 0; c < 8 && i < len; c++, i++) {
12170 			byte = (uchar_t)data[i];
12171 			if (byte < 0x10)
12172 				format = "0x0%x ";
12173 			else
12174 				format = "0x%x ";
12175 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
12176 		}
12177 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
12178 
12179 		scsi_log(dev, label, level, "%s\n", buf);
12180 		level = CE_CONT;
12181 	}
12182 }
12183 
12184 /*
12185  * Conditionally enabled debugging
12186  */
12187 #ifdef	STDEBUG
12188 static void
12189 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
12190 {
12191 	char tmpbuf[64];
12192 
12193 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
12194 
12195 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12196 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
12197 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
12198 	    count, count,
12199 	    wait == ASYNC_CMD ? "a" : "");
12200 }
12201 #endif	/* STDEBUG */
12202 
12203 /*
12204  * Returns pointer to name of minor node name of device 'dev'.
12205  */
12206 static char *
12207 st_dev_name(dev_t dev)
12208 {
12209 	struct scsi_tape *un;
12210 	const char density[] = { 'l', 'm', 'h', 'c' };
12211 	static char name[32];
12212 	minor_t minor;
12213 	int instance;
12214 	int nprt = 0;
12215 
12216 	minor = getminor(dev);
12217 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
12218 	un = ddi_get_soft_state(st_state, instance);
12219 	if (un) {
12220 		ST_FUNC(ST_DEVINFO, st_dev_name);
12221 	}
12222 
12223 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
12224 
12225 	if (minor & MT_BSD) {
12226 		name[++nprt] = 'b';
12227 	}
12228 
12229 	if (minor & MT_NOREWIND) {
12230 		name[++nprt] = 'n';
12231 	}
12232 
12233 	/* NULL terminator */
12234 	name[++nprt] = 0;
12235 
12236 	return (name);
12237 }
12238 
12239 /*
12240  * Soft error reporting, so far unique to each drive
12241  *
12242  * Currently supported: exabyte and DAT soft error reporting
12243  */
12244 static int
12245 st_report_exabyte_soft_errors(dev_t dev, int flag)
12246 {
12247 	uchar_t *sensep;
12248 	int amt;
12249 	int rval = 0;
12250 	char cdb[CDB_GROUP0], *c = cdb;
12251 	struct uscsi_cmd *com;
12252 
12253 	GET_SOFT_STATE(dev);
12254 
12255 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
12256 
12257 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12258 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
12259 	    dev, flag);
12260 
12261 	ASSERT(mutex_owned(ST_MUTEX));
12262 
12263 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12264 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
12265 
12266 	*c++ = SCMD_REQUEST_SENSE;
12267 	*c++ = 0;
12268 	*c++ = 0;
12269 	*c++ = 0;
12270 	*c++ = TAPE_SENSE_LENGTH;
12271 	/*
12272 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
12273 	 */
12274 	*c   = (char)0x80;
12275 
12276 	com->uscsi_cdb = cdb;
12277 	com->uscsi_cdblen = CDB_GROUP0;
12278 	com->uscsi_bufaddr = (caddr_t)sensep;
12279 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
12280 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12281 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12282 
12283 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12284 	if (rval || com->uscsi_status) {
12285 		goto done;
12286 	}
12287 
12288 	/*
12289 	 * was there enough data?
12290 	 */
12291 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
12292 
12293 	if ((amt >= 19) && un->un_kbytes_xferred) {
12294 		uint_t count, error_rate;
12295 		uint_t rate;
12296 
12297 		if (sensep[21] & CLN) {
12298 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12299 			    "Periodic head cleaning required");
12300 		}
12301 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
12302 			goto done;
12303 		}
12304 		/*
12305 		 * check if soft error reporting needs to be done.
12306 		 */
12307 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
12308 		count &= 0xffffff;
12309 		error_rate = (count * 100)/un->un_kbytes_xferred;
12310 
12311 #ifdef	STDEBUG
12312 		if (st_soft_error_report_debug) {
12313 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12314 			    "Exabyte Soft Error Report:\n");
12315 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12316 			    "read/write error counter: %d\n", count);
12317 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12318 			    "number of bytes transferred: %dK\n",
12319 			    un->un_kbytes_xferred);
12320 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12321 			    "error_rate: %d%%\n", error_rate);
12322 
12323 			if (amt >= 22) {
12324 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12325 				    "unit sense: 0x%b 0x%b 0x%b\n",
12326 				    sensep[19], SENSE_19_BITS,
12327 				    sensep[20], SENSE_20_BITS,
12328 				    sensep[21], SENSE_21_BITS);
12329 			}
12330 			if (amt >= 27) {
12331 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12332 				    "tracking retry counter: %d\n",
12333 				    sensep[26]);
12334 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12335 				    "read/write retry counter: %d\n",
12336 				    sensep[27]);
12337 			}
12338 		}
12339 #endif
12340 
12341 		if (flag & FWRITE) {
12342 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
12343 		} else {
12344 			rate = EXABYTE_READ_ERROR_THRESHOLD;
12345 		}
12346 		if (error_rate >= rate) {
12347 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12348 			    "Soft error rate (%d%%) during %s was too high",
12349 			    error_rate,
12350 			    ((flag & FWRITE) ? wrg_str : rdg_str));
12351 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12352 			    "Please, replace tape cartridge\n");
12353 		}
12354 	}
12355 
12356 done:
12357 	kmem_free(com, sizeof (*com));
12358 	kmem_free(sensep, TAPE_SENSE_LENGTH);
12359 
12360 	if (rval != 0) {
12361 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12362 		    "exabyte soft error reporting failed\n");
12363 	}
12364 	return (rval);
12365 }
12366 
12367 /*
12368  * this is very specific to Archive 4mm dat
12369  */
12370 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
12371 
12372 static int
12373 st_report_dat_soft_errors(dev_t dev, int flag)
12374 {
12375 	uchar_t *sensep;
12376 	int amt, i;
12377 	int rval = 0;
12378 	char cdb[CDB_GROUP1], *c = cdb;
12379 	struct uscsi_cmd *com;
12380 	struct scsi_arq_status status;
12381 
12382 	GET_SOFT_STATE(dev);
12383 
12384 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
12385 
12386 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12387 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12388 
12389 	ASSERT(mutex_owned(ST_MUTEX));
12390 
12391 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12392 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12393 
12394 	*c++ = SCMD_LOG_SENSE_G1;
12395 	*c++ = 0;
12396 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
12397 	*c++ = 0;
12398 	*c++ = 0;
12399 	*c++ = 0;
12400 	*c++ = 2;
12401 	*c++ = 0;
12402 	*c++ = (char)LOG_SENSE_LENGTH;
12403 	*c   = 0;
12404 	com->uscsi_cdb    = cdb;
12405 	com->uscsi_cdblen  = CDB_GROUP1;
12406 	com->uscsi_bufaddr = (caddr_t)sensep;
12407 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
12408 	com->uscsi_rqlen = sizeof (status);
12409 	com->uscsi_rqbuf = (caddr_t)&status;
12410 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
12411 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12412 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12413 	if (rval) {
12414 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12415 		    "DAT soft error reporting failed\n");
12416 	}
12417 	if (rval || com->uscsi_status) {
12418 		goto done;
12419 	}
12420 
12421 	/*
12422 	 * was there enough data?
12423 	 */
12424 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
12425 
12426 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
12427 		int total, retries, param_code;
12428 
12429 		total = -1;
12430 		retries = -1;
12431 		amt = sensep[3] + 4;
12432 
12433 
12434 #ifdef STDEBUG
12435 		if (st_soft_error_report_debug) {
12436 			(void) printf("logsense:");
12437 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
12438 				if (i % 16 == 0) {
12439 					(void) printf("\t\n");
12440 				}
12441 				(void) printf(" %x", sensep[i]);
12442 			}
12443 			(void) printf("\n");
12444 		}
12445 #endif
12446 
12447 		/*
12448 		 * parse the param_codes
12449 		 */
12450 		if (sensep[0] == 2 || sensep[0] == 3) {
12451 			for (i = 4; i < amt; i++) {
12452 				param_code = (sensep[i++] << 8);
12453 				param_code += sensep[i++];
12454 				i++; /* skip control byte */
12455 				if (param_code == 5) {
12456 					if (sensep[i++] == 4) {
12457 						total = (sensep[i++] << 24);
12458 						total += (sensep[i++] << 16);
12459 						total += (sensep[i++] << 8);
12460 						total += sensep[i];
12461 					}
12462 				} else if (param_code == 0x8007) {
12463 					if (sensep[i++] == 2) {
12464 						retries = sensep[i++] << 8;
12465 						retries += sensep[i];
12466 					}
12467 				} else {
12468 					i += sensep[i];
12469 				}
12470 			}
12471 		}
12472 
12473 		/*
12474 		 * if the log sense returned valid numbers then determine
12475 		 * the read and write error thresholds based on the amount of
12476 		 * data transferred
12477 		 */
12478 
12479 		if (total > 0 && retries > 0) {
12480 			short normal_retries = 0;
12481 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12482 			    "total xferred (%s) =%x, retries=%x\n",
12483 			    ((flag & FWRITE) ? wrg_str : rdg_str),
12484 			    total, retries);
12485 
12486 			if (flag & FWRITE) {
12487 				if (total <=
12488 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
12489 					normal_retries =
12490 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
12491 				} else {
12492 					normal_retries =
12493 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
12494 				}
12495 			} else {
12496 				if (total <=
12497 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
12498 					normal_retries =
12499 					    DAT_SMALL_READ_ERROR_THRESHOLD;
12500 				} else {
12501 					normal_retries =
12502 					    DAT_LARGE_READ_ERROR_THRESHOLD;
12503 				}
12504 			}
12505 
12506 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12507 			"normal retries=%d\n", normal_retries);
12508 
12509 			if (retries >= normal_retries) {
12510 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12511 				    "Soft error rate (retries = %d) during "
12512 				    "%s was too high",  retries,
12513 				    ((flag & FWRITE) ? wrg_str : rdg_str));
12514 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12515 				    "Periodic head cleaning required "
12516 				    "and/or replace tape cartridge\n");
12517 			}
12518 
12519 		} else if (total == -1 || retries == -1) {
12520 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12521 			    "log sense parameter code does not make sense\n");
12522 		}
12523 	}
12524 
12525 	/*
12526 	 * reset all values
12527 	 */
12528 	c = cdb;
12529 	*c++ = SCMD_LOG_SELECT_G1;
12530 	*c++ = 2;	/* this resets all values */
12531 	*c++ = (char)0xc0;
12532 	*c++ = 0;
12533 	*c++ = 0;
12534 	*c++ = 0;
12535 	*c++ = 0;
12536 	*c++ = 0;
12537 	*c++ = 0;
12538 	*c   = 0;
12539 	com->uscsi_bufaddr = NULL;
12540 	com->uscsi_buflen  = 0;
12541 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
12542 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12543 	if (rval) {
12544 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12545 		    "DAT soft error reset failed\n");
12546 	}
12547 done:
12548 	kmem_free(com, sizeof (*com));
12549 	kmem_free(sensep, LOG_SENSE_LENGTH);
12550 	return (rval);
12551 }
12552 
12553 static int
12554 st_report_soft_errors(dev_t dev, int flag)
12555 {
12556 	GET_SOFT_STATE(dev);
12557 
12558 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
12559 
12560 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12561 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12562 
12563 	ASSERT(mutex_owned(ST_MUTEX));
12564 
12565 	switch (un->un_dp->type) {
12566 	case ST_TYPE_EXB8500:
12567 	case ST_TYPE_EXABYTE:
12568 		return (st_report_exabyte_soft_errors(dev, flag));
12569 		/*NOTREACHED*/
12570 	case ST_TYPE_PYTHON:
12571 		return (st_report_dat_soft_errors(dev, flag));
12572 		/*NOTREACHED*/
12573 	default:
12574 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
12575 		return (-1);
12576 	}
12577 }
12578 
12579 /*
12580  * persistent error routines
12581  */
12582 
12583 /*
12584  * enable persistent errors, and set the throttle appropriately, checking
12585  * for flush-on-errors capability
12586  */
12587 static void
12588 st_turn_pe_on(struct scsi_tape *un)
12589 {
12590 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
12591 
12592 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
12593 	ASSERT(mutex_owned(ST_MUTEX));
12594 
12595 	un->un_persistence = 1;
12596 
12597 	/*
12598 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
12599 	 * enabled.  This will simplify the error handling for request senses
12600 	 */
12601 
12602 	if (un->un_arq_enabled && un->un_untagged_qing) {
12603 		uchar_t f_o_e;
12604 
12605 		mutex_exit(ST_MUTEX);
12606 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
12607 		    1 : 0;
12608 		mutex_enter(ST_MUTEX);
12609 
12610 		un->un_flush_on_errors = f_o_e;
12611 	} else {
12612 		un->un_flush_on_errors = 0;
12613 	}
12614 
12615 	if (un->un_flush_on_errors)
12616 		un->un_max_throttle = (uchar_t)st_max_throttle;
12617 	else
12618 		un->un_max_throttle = 1;
12619 
12620 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
12621 		un->un_max_throttle = 1;
12622 
12623 	/* this will send a marker pkt */
12624 	st_clear_pe(un);
12625 }
12626 
12627 /*
12628  * This turns persistent errors permanently off
12629  */
12630 static void
12631 st_turn_pe_off(struct scsi_tape *un)
12632 {
12633 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
12634 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
12635 	ASSERT(mutex_owned(ST_MUTEX));
12636 
12637 	/* turn it off for good */
12638 	un->un_persistence = 0;
12639 
12640 	/* this will send a marker pkt */
12641 	st_clear_pe(un);
12642 
12643 	/* turn off flush on error capability, if enabled */
12644 	if (un->un_flush_on_errors) {
12645 		mutex_exit(ST_MUTEX);
12646 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
12647 		mutex_enter(ST_MUTEX);
12648 	}
12649 
12650 
12651 	un->un_flush_on_errors = 0;
12652 }
12653 
12654 /*
12655  * This clear persistent errors, allowing more commands through, and also
12656  * sending a marker packet.
12657  */
12658 static void
12659 st_clear_pe(struct scsi_tape *un)
12660 {
12661 	ST_FUNC(ST_DEVINFO, st_clear_pe);
12662 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
12663 	ASSERT(mutex_owned(ST_MUTEX));
12664 
12665 	un->un_persist_errors = 0;
12666 	un->un_throttle = un->un_last_throttle = 1;
12667 	un->un_errno = 0;
12668 	st_hba_unflush(un);
12669 }
12670 
12671 /*
12672  * This will flag persistent errors, shutting everything down, if the
12673  * application had enabled persistent errors via MTIOCPERSISTENT
12674  */
12675 static void
12676 st_set_pe_flag(struct scsi_tape *un)
12677 {
12678 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
12679 	ASSERT(mutex_owned(ST_MUTEX));
12680 
12681 	if (un->un_persistence) {
12682 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
12683 		un->un_persist_errors = 1;
12684 		un->un_throttle = un->un_last_throttle = 0;
12685 		cv_broadcast(&un->un_sbuf_cv);
12686 	}
12687 }
12688 
12689 static int
12690 st_do_reserve(struct scsi_tape *un)
12691 {
12692 	int rval;
12693 	int was_lost = un->un_rsvd_status & ST_LOST_RESERVE;
12694 
12695 	ST_FUNC(ST_DEVINFO, st_do_reserve);
12696 
12697 	/*
12698 	 * Issue a Throw-Away reserve command to clear the
12699 	 * check condition.
12700 	 * If the current behaviour of reserve/release is to
12701 	 * hold reservation across opens , and if a Bus reset
12702 	 * has been issued between opens then this command
12703 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
12704 	 * In this case return an EACCES so that user knows that
12705 	 * reservation has been lost in between opens.
12706 	 * If this error is not returned and we continue with
12707 	 * successful open , then user may think position of the
12708 	 * tape is still the same but inreality we would rewind the
12709 	 * tape and continue from BOT.
12710 	 */
12711 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12712 	if (rval) {
12713 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
12714 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
12715 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
12716 			un->un_errno = EACCES;
12717 			return (EACCES);
12718 		}
12719 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12720 	}
12721 	if (rval == 0) {
12722 		un->un_rsvd_status |= ST_INIT_RESERVE;
12723 	}
12724 	if (was_lost) {
12725 		un->un_running.pmode = invalid;
12726 	}
12727 
12728 	return (rval);
12729 }
12730 
12731 static int
12732 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb)
12733 {
12734 	int rval;
12735 	cmd_attribute const *attrib;
12736 
12737 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
12738 
12739 	/*
12740 	 * If already reserved no need to do it again.
12741 	 * Also if Reserve and Release are disabled Just return.
12742 	 */
12743 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12744 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12745 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12746 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12747 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
12748 		    st_print_scsi_cmd((uchar_t)cdb[0]));
12749 		return (0);
12750 	}
12751 
12752 	/* See if command is on the list */
12753 	attrib = st_lookup_cmd_attribute(cdb[0]);
12754 
12755 	if (attrib == NULL) {
12756 		rval = 1; /* Not found, when in doubt reserve */
12757 	} else if ((attrib->requires_reserve) != 0) {
12758 		rval = 1;
12759 	} else if ((attrib->reserve_byte) != 0) {
12760 		/*
12761 		 * cmd is on list.
12762 		 * if byte is zero always allowed.
12763 		 */
12764 		rval = 1;
12765 	} else if (((cdb[attrib->reserve_byte]) &
12766 	    (attrib->reserve_mask)) != 0) {
12767 		rval = 1;
12768 	} else {
12769 		rval = 0;
12770 	}
12771 
12772 	if (rval) {
12773 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12774 		    "Command %s requires reservation",
12775 		    st_print_scsi_cmd(cdb[0]));
12776 
12777 		rval = st_do_reserve(un);
12778 	}
12779 
12780 	return (rval);
12781 }
12782 
12783 static int
12784 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
12785 {
12786 	int rval;
12787 	cmd_attribute const *attrib;
12788 
12789 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
12790 
12791 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12792 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12793 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12794 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12795 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
12796 		    st_print_scsi_cmd(cmd));
12797 		return (0);
12798 	}
12799 
12800 	/* search for this command on the list */
12801 	attrib = st_lookup_cmd_attribute(cmd);
12802 
12803 	if (attrib == NULL) {
12804 		rval = 1; /* Not found, when in doubt reserve */
12805 	} else if ((attrib->requires_reserve) != 0) {
12806 		rval = 1;
12807 	} else if ((attrib->reserve_byte) != 0) {
12808 		/*
12809 		 * cmd is on list.
12810 		 * if byte is zero always allowed.
12811 		 */
12812 		rval = 1;
12813 	} else if (((attrib->reserve_mask) & cnt) != 0) {
12814 		rval = 1;
12815 	} else {
12816 		rval = 0;
12817 	}
12818 
12819 	if (rval) {
12820 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12821 		    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
12822 
12823 		rval = st_do_reserve(un);
12824 	}
12825 
12826 	return (rval);
12827 }
12828 
12829 static int
12830 st_reserve_release(struct scsi_tape *un, int cmd, ubufunc_t ubf)
12831 {
12832 	struct uscsi_cmd	uscsi_cmd;
12833 	int			rval;
12834 	char			cdb[CDB_GROUP0];
12835 	struct scsi_arq_status	stat;
12836 
12837 
12838 
12839 	ST_FUNC(ST_DEVINFO, st_reserve_release);
12840 
12841 	ASSERT(mutex_owned(ST_MUTEX));
12842 
12843 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12844 	    "st_reserve_release: %s \n",
12845 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
12846 
12847 	bzero(&cdb, CDB_GROUP0);
12848 	if (cmd == ST_RELEASE) {
12849 		cdb[0] = SCMD_RELEASE;
12850 	} else {
12851 		cdb[0] = SCMD_RESERVE;
12852 	}
12853 	bzero(&uscsi_cmd, sizeof (struct uscsi_cmd));
12854 	uscsi_cmd.uscsi_flags = USCSI_WRITE | USCSI_RQENABLE;
12855 	uscsi_cmd.uscsi_cdb = cdb;
12856 	uscsi_cmd.uscsi_cdblen = CDB_GROUP0;
12857 	uscsi_cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
12858 	uscsi_cmd.uscsi_rqbuf = (caddr_t)&stat;
12859 	uscsi_cmd.uscsi_rqlen = sizeof (stat);
12860 
12861 	rval = ubf(un, &uscsi_cmd, FKIOCTL);
12862 
12863 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12864 	    "st_reserve_release: rval(1)=%d\n", rval);
12865 
12866 	if (rval) {
12867 		if (uscsi_cmd.uscsi_status == STATUS_RESERVATION_CONFLICT) {
12868 			rval = EACCES;
12869 		}
12870 		/*
12871 		 * dynamically turn off reserve/release support
12872 		 * in case of drives which do not support
12873 		 * reserve/release command(ATAPI drives).
12874 		 */
12875 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
12876 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
12877 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
12878 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12879 				    "Tape unit does not support "
12880 				    "reserve/release \n");
12881 			}
12882 			rval = 0;
12883 		}
12884 	}
12885 	return (rval);
12886 }
12887 
12888 static int
12889 st_take_ownership(struct scsi_tape *un, ubufunc_t ubf)
12890 {
12891 	int rval;
12892 
12893 	ST_FUNC(ST_DEVINFO, st_take_ownership);
12894 
12895 	ASSERT(mutex_owned(ST_MUTEX));
12896 
12897 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12898 	    "st_take_ownership: Entering ...\n");
12899 
12900 
12901 	rval = st_reserve_release(un, ST_RESERVE, ubf);
12902 	/*
12903 	 * XXX -> Should reset be done only if we get EACCES.
12904 	 * .
12905 	 */
12906 	if (rval) {
12907 		if (st_reset(un, RESET_LUN) == 0) {
12908 			return (EIO);
12909 		}
12910 		un->un_rsvd_status &=
12911 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
12912 
12913 		mutex_exit(ST_MUTEX);
12914 		delay(drv_usectohz(ST_RESERVATION_DELAY));
12915 		mutex_enter(ST_MUTEX);
12916 		/*
12917 		 * remove the check condition.
12918 		 */
12919 		(void) st_reserve_release(un, ST_RESERVE, ubf);
12920 		rval = st_reserve_release(un, ST_RESERVE, ubf);
12921 		if (rval != 0) {
12922 			if ((st_reserve_release(un, ST_RESERVE, ubf))
12923 			    != 0) {
12924 				rval = (un->un_rsvd_status &
12925 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
12926 				return (rval);
12927 			}
12928 		}
12929 		/*
12930 		 * Set tape state to ST_STATE_OFFLINE , in case if
12931 		 * the user wants to continue and start using
12932 		 * the tape.
12933 		 */
12934 		un->un_state = ST_STATE_OFFLINE;
12935 		un->un_rsvd_status |= ST_INIT_RESERVE;
12936 	}
12937 	return (rval);
12938 }
12939 
12940 static int
12941 st_create_errstats(struct scsi_tape *un, int instance)
12942 {
12943 	char	kstatname[KSTAT_STRLEN];
12944 
12945 	ST_FUNC(ST_DEVINFO, st_create_errstats);
12946 
12947 	/*
12948 	 * Create device error kstats
12949 	 */
12950 
12951 	if (un->un_errstats == (kstat_t *)0) {
12952 		(void) sprintf(kstatname, "st%d,err", instance);
12953 		un->un_errstats = kstat_create("sterr", instance, kstatname,
12954 		    "device_error", KSTAT_TYPE_NAMED,
12955 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
12956 		    KSTAT_FLAG_PERSISTENT);
12957 
12958 		if (un->un_errstats) {
12959 			struct st_errstats	*stp;
12960 
12961 			stp = (struct st_errstats *)un->un_errstats->ks_data;
12962 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
12963 			    KSTAT_DATA_ULONG);
12964 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
12965 			    KSTAT_DATA_ULONG);
12966 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
12967 			    KSTAT_DATA_ULONG);
12968 			kstat_named_init(&stp->st_vid, "Vendor",
12969 			    KSTAT_DATA_CHAR);
12970 			kstat_named_init(&stp->st_pid, "Product",
12971 			    KSTAT_DATA_CHAR);
12972 			kstat_named_init(&stp->st_revision, "Revision",
12973 			    KSTAT_DATA_CHAR);
12974 			kstat_named_init(&stp->st_serial, "Serial No",
12975 			    KSTAT_DATA_CHAR);
12976 			un->un_errstats->ks_private = un;
12977 			un->un_errstats->ks_update = nulldev;
12978 			kstat_install(un->un_errstats);
12979 			/*
12980 			 * Fill in the static data
12981 			 */
12982 			(void) strncpy(&stp->st_vid.value.c[0],
12983 			    ST_INQUIRY->inq_vid, 8);
12984 			/*
12985 			 * XXX:  Emulex MT-02 (and emulators) predates
12986 			 *	 SCSI-1 and has no vid & pid inquiry data.
12987 			 */
12988 			if (ST_INQUIRY->inq_len != 0) {
12989 				(void) strncpy(&stp->st_pid.value.c[0],
12990 				    ST_INQUIRY->inq_pid, 16);
12991 				(void) strncpy(&stp->st_revision.value.c[0],
12992 				    ST_INQUIRY->inq_revision, 4);
12993 				(void) strncpy(&stp->st_serial.value.c[0],
12994 				    ST_INQUIRY->inq_serial, 12);
12995 			}
12996 		}
12997 	}
12998 	return (0);
12999 }
13000 
13001 static int
13002 st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos)
13003 {
13004 	int rval;
13005 	bufunc_t bf = (ubf == st_uscsi_rcmd) ? st_rcmd : st_cmd;
13006 
13007 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
13008 
13009 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
13010 	ASSERT(mutex_owned(ST_MUTEX));
13011 
13012 	/* Can't restore an invalid position */
13013 	if (pos->pmode == invalid) {
13014 		return (4);
13015 	}
13016 
13017 	/*
13018 	 * Assumtions:
13019 	 *	If a position was read and is in logical position mode.
13020 	 *	If a drive supports read position it supports locate.
13021 	 *	If the read position type is not NO_POS. even though
13022 	 *	   a read position make not have been attemped yet.
13023 	 *
13024 	 *	The drive can locate to the position.
13025 	 */
13026 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
13027 		/*
13028 		 * If position mode is logical or legacy mode try
13029 		 * to locate there as it is faster.
13030 		 * If it fails try the old way.
13031 		 */
13032 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13033 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
13034 		    pos->lgclblkno);
13035 
13036 		if (st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
13037 		    pos->lgclblkno, pos->partition) == 0) {
13038 			/* Assume we are there copy rest of position back */
13039 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
13040 				COPY_POS(&un->un_pos, pos);
13041 			}
13042 			return (0);
13043 		}
13044 
13045 		/*
13046 		 * If logical block locate failed to restore a logical
13047 		 * position, can't recover.
13048 		 */
13049 		if (pos->pmode == logical) {
13050 			return (-1);
13051 		}
13052 	}
13053 
13054 
13055 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13056 	    "Restoring tape position at fileno=%x, blkno=%x....",
13057 	    pos->fileno, pos->blkno);
13058 
13059 	/*
13060 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
13061 	 * so as not to rewind tape on RESETS: Gee, Has life ever
13062 	 * been simple in tape land ?
13063 	 */
13064 	rval = bf(un, SCMD_REWIND, 0, SYNC_CMD);
13065 	if (rval) {
13066 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
13067 		    "Failed to restore the last file and block position: In"
13068 		    " this state, Tape will be loaded at BOT during next open");
13069 		un->un_pos.pmode = invalid;
13070 		return (rval);
13071 	}
13072 
13073 	/* If the position was as the result of back space file */
13074 	if (pos->blkno > (INF / 2)) {
13075 		/* Go one extra file forward */
13076 		pos->fileno++;
13077 		/* Figure how many blocks to back into the previous file */
13078 		pos->blkno = -(INF - pos->blkno);
13079 	}
13080 
13081 	/* Go to requested fileno */
13082 	if (pos->fileno) {
13083 		rval = st_cmd(un, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
13084 		if (rval) {
13085 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13086 			    "Failed to restore the last file position: In this "
13087 			    " state, Tape will be loaded at BOT during next"
13088 			    " open %d", __LINE__);
13089 			un->un_pos.pmode = invalid;
13090 			pos->pmode = invalid;
13091 			return (rval);
13092 		}
13093 	}
13094 
13095 	/*
13096 	 * If backing into a file we already did an extra file forward.
13097 	 * Now we have to back over the filemark to get to the end of
13098 	 * the previous file. The blkno has been ajusted to a negative
13099 	 * value so we will get to the expected location.
13100 	 */
13101 	if (pos->blkno) {
13102 		rval = bf(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
13103 		if (rval) {
13104 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13105 			    "Failed to restore the last file position: In this "
13106 			    " state, Tape will be loaded at BOT during next"
13107 			    " open %d", __LINE__);
13108 			un->un_pos.pmode = invalid;
13109 			pos->pmode = invalid;
13110 			return (rval);
13111 		}
13112 	}
13113 
13114 	/*
13115 	 * The position mode, block and fileno should be correct,
13116 	 * This updates eof and logical position information.
13117 	 */
13118 	un->un_pos.eof = pos->eof;
13119 	un->un_pos.lgclblkno = pos->lgclblkno;
13120 
13121 	return (0);
13122 }
13123 
13124 /*
13125  * check sense key, ASC, ASCQ in order to determine if the tape needs
13126  * to be ejected
13127  */
13128 
13129 static int
13130 st_check_asc_ascq(struct scsi_tape *un)
13131 {
13132 	struct scsi_extended_sense *sensep = ST_RQSENSE;
13133 	struct tape_failure_code   *code;
13134 
13135 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
13136 
13137 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
13138 		if ((code->key  == sensep->es_key) &&
13139 		    (code->add_code  == sensep->es_add_code) &&
13140 		    (code->qual_code == sensep->es_qual_code))
13141 			return (1);
13142 	}
13143 	return (0);
13144 }
13145 
13146 /*
13147  * st_logpage_supported() sends a Log Sense command with
13148  * page code = 0 = Supported Log Pages Page to the device,
13149  * to see whether the page 'page' is supported.
13150  * Return values are:
13151  * -1 if the Log Sense command fails
13152  * 0 if page is not supported
13153  * 1 if page is supported
13154  */
13155 
13156 static int
13157 st_logpage_supported(struct scsi_tape *un, uchar_t page)
13158 {
13159 	uchar_t *sp, *sensep;
13160 	unsigned length;
13161 	struct uscsi_cmd *com;
13162 	struct scsi_arq_status status;
13163 	int rval;
13164 	char cdb[CDB_GROUP1] = {
13165 		SCMD_LOG_SENSE_G1,
13166 		0,
13167 		SUPPORTED_LOG_PAGES_PAGE,
13168 		0,
13169 		0,
13170 		0,
13171 		0,
13172 		0,
13173 		(char)LOG_SENSE_LENGTH,
13174 		0
13175 	};
13176 
13177 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
13178 
13179 	ASSERT(mutex_owned(ST_MUTEX));
13180 
13181 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13182 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
13183 
13184 	com->uscsi_cdb = cdb;
13185 	com->uscsi_cdblen = CDB_GROUP1;
13186 	com->uscsi_bufaddr = (caddr_t)sensep;
13187 	com->uscsi_buflen = LOG_SENSE_LENGTH;
13188 	com->uscsi_rqlen = sizeof (status);
13189 	com->uscsi_rqbuf = (caddr_t)&status;
13190 	com->uscsi_flags =
13191 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13192 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13193 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13194 	if (rval || com->uscsi_status) {
13195 		/* uscsi-command failed */
13196 		rval = -1;
13197 	} else {
13198 
13199 		sp = sensep + 3;
13200 
13201 		for (length = *sp++; length > 0; length--, sp++) {
13202 
13203 			if (*sp == page) {
13204 				rval = 1;
13205 				break;
13206 			}
13207 		}
13208 	}
13209 	kmem_free(com, sizeof (struct uscsi_cmd));
13210 	kmem_free(sensep, LOG_SENSE_LENGTH);
13211 	return (rval);
13212 }
13213 
13214 
13215 /*
13216  * st_check_clean_bit() gets the status of the tape's cleaning bit.
13217  *
13218  * If the device does support the TapeAlert log page, then the cleaning bit
13219  * information will be read from this page. Otherwise we will see if one of
13220  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
13221  * the device, which means, that we can get the cleaning bit information via
13222  * a RequestSense command.
13223  * If both methods of getting cleaning bit information are not supported
13224  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
13225  * returns with
13226  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
13227  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
13228  * If the call to st_uscsi_cmd() to do the Log Sense or the Request Sense
13229  * command fails, or if the amount of Request Sense data is not enough, then
13230  *  st_check_clean_bit() returns with -1.
13231  */
13232 
13233 static int
13234 st_check_clean_bit(struct scsi_tape *un)
13235 {
13236 	int rval = 0;
13237 
13238 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
13239 
13240 	ASSERT(mutex_owned(ST_MUTEX));
13241 
13242 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
13243 		return (rval);
13244 	}
13245 
13246 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13247 
13248 		rval = st_logpage_supported(un, TAPE_SEQUENTIAL_PAGE);
13249 		if (rval == -1) {
13250 			return (0);
13251 		}
13252 		if (rval == 1) {
13253 
13254 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
13255 		}
13256 
13257 		rval = st_logpage_supported(un, TAPE_ALERT_PAGE);
13258 		if (rval == -1) {
13259 			return (0);
13260 		}
13261 		if (rval == 1) {
13262 
13263 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
13264 		}
13265 
13266 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13267 
13268 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
13269 		}
13270 	}
13271 
13272 	rval = 0;
13273 
13274 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
13275 
13276 		rval = st_check_sequential_clean_bit(un);
13277 		if (rval == -1) {
13278 			return (0);
13279 		}
13280 	}
13281 
13282 	if ((rval == 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
13283 
13284 		rval = st_check_alert_flags(un);
13285 		if (rval == -1) {
13286 			return (0);
13287 		}
13288 	}
13289 
13290 	if ((rval == 0) && (un->un_dp->options & ST_CLN_MASK)) {
13291 
13292 		rval = st_check_sense_clean_bit(un);
13293 		if (rval == -1) {
13294 			return (0);
13295 		}
13296 	}
13297 
13298 	/*
13299 	 * If found a supported means to check need to clean.
13300 	 */
13301 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
13302 
13303 		/*
13304 		 * head needs to be cleaned.
13305 		 */
13306 		if (rval & MTF_TAPE_HEAD_DIRTY) {
13307 
13308 			/*
13309 			 * Print log message only first time
13310 			 * found needing cleaned.
13311 			 */
13312 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
13313 
13314 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
13315 				    "Periodic head cleaning required");
13316 
13317 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
13318 			}
13319 
13320 		} else {
13321 
13322 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
13323 		}
13324 	}
13325 
13326 	return (rval);
13327 }
13328 
13329 
13330 static int
13331 st_check_sequential_clean_bit(struct scsi_tape *un)
13332 {
13333 	int rval;
13334 	int ix;
13335 	ushort_t parameter;
13336 	struct uscsi_cmd *cmd;
13337 	struct log_sequential_page *sp;
13338 	struct log_sequential_page_parameter *prm;
13339 	struct scsi_arq_status status;
13340 	char cdb[CDB_GROUP1] = {
13341 		SCMD_LOG_SENSE_G1,
13342 		0,
13343 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
13344 		0,
13345 		0,
13346 		0,
13347 		0,
13348 		(char)(sizeof (struct log_sequential_page) >> 8),
13349 		(char)(sizeof (struct log_sequential_page)),
13350 		0
13351 	};
13352 
13353 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
13354 
13355 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13356 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
13357 
13358 	cmd->uscsi_flags   =
13359 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13360 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13361 	cmd->uscsi_cdb	   = cdb;
13362 	cmd->uscsi_cdblen  = CDB_GROUP1;
13363 	cmd->uscsi_bufaddr = (caddr_t)sp;
13364 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
13365 	cmd->uscsi_rqlen   = sizeof (status);
13366 	cmd->uscsi_rqbuf   = (caddr_t)&status;
13367 
13368 	rval = st_uscsi_cmd(un, cmd, FKIOCTL);
13369 
13370 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
13371 
13372 		rval = -1;
13373 
13374 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
13375 
13376 		rval = -1;
13377 	}
13378 
13379 	prm = &sp->param[0];
13380 
13381 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
13382 
13383 		if (prm->log_param.length == 0) {
13384 			break;
13385 		}
13386 
13387 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
13388 		    (prm->log_param.pc_lo & 0xff));
13389 
13390 		if (parameter == SEQUENTIAL_NEED_CLN) {
13391 
13392 			rval = MTF_TAPE_CLN_SUPPORTED;
13393 			if (prm->param_value[prm->log_param.length - 1]) {
13394 
13395 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13396 				    "sequential log says head dirty\n");
13397 				rval |= MTF_TAPE_HEAD_DIRTY;
13398 			}
13399 		}
13400 		prm = (struct log_sequential_page_parameter *)
13401 		    &prm->param_value[prm->log_param.length];
13402 	}
13403 
13404 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13405 	kmem_free(sp,  sizeof (struct log_sequential_page));
13406 
13407 	return (rval);
13408 }
13409 
13410 
13411 static int
13412 st_check_alert_flags(struct scsi_tape *un)
13413 {
13414 	struct st_tape_alert *ta;
13415 	struct uscsi_cmd *com;
13416 	struct scsi_arq_status status;
13417 	unsigned ix, length;
13418 	int rval;
13419 	tape_alert_flags flag;
13420 	char cdb[CDB_GROUP1] = {
13421 		SCMD_LOG_SENSE_G1,
13422 		0,
13423 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
13424 		0,
13425 		0,
13426 		0,
13427 		0,
13428 		(char)(sizeof (struct st_tape_alert) >> 8),
13429 		(char)(sizeof (struct st_tape_alert)),
13430 		0
13431 	};
13432 
13433 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
13434 
13435 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13436 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
13437 
13438 	com->uscsi_cdb = cdb;
13439 	com->uscsi_cdblen = CDB_GROUP1;
13440 	com->uscsi_bufaddr = (caddr_t)ta;
13441 	com->uscsi_buflen = sizeof (struct st_tape_alert);
13442 	com->uscsi_rqlen = sizeof (status);
13443 	com->uscsi_rqbuf = (caddr_t)&status;
13444 	com->uscsi_flags =
13445 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13446 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13447 
13448 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13449 
13450 	if (rval || com->uscsi_status || com->uscsi_resid) {
13451 
13452 		rval = -1; /* uscsi-command failed */
13453 
13454 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
13455 
13456 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13457 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
13458 		rval = -1;
13459 	}
13460 
13461 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
13462 
13463 
13464 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
13465 
13466 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13467 		    "TapeAlert length %d\n", length);
13468 	}
13469 
13470 
13471 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
13472 
13473 		/*
13474 		 * if rval is bad before the first pass don't bother
13475 		 */
13476 		if (ix == 0 && rval != 0) {
13477 
13478 			break;
13479 		}
13480 
13481 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
13482 		    ta->param[ix].log_param.pc_lo);
13483 
13484 		if ((ta->param[ix].param_value & 1) == 0) {
13485 			continue;
13486 		}
13487 		/*
13488 		 * check to see if current parameter is of interest.
13489 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
13490 		 */
13491 		if ((flag == TAF_CLEAN_NOW) ||
13492 		    (flag == TAF_CLEAN_PERIODIC) ||
13493 		    ((flag == CLEAN_FOR_ERRORS) &&
13494 		    (un->un_dp->type == ST_TYPE_STK9840))) {
13495 
13496 			rval = MTF_TAPE_CLN_SUPPORTED;
13497 
13498 
13499 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13500 			    "alert_page drive needs clean %d\n", flag);
13501 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
13502 			rval |= MTF_TAPE_HEAD_DIRTY;
13503 
13504 		} else if (flag == TAF_CLEANING_MEDIA) {
13505 
13506 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13507 			    "alert_page drive was cleaned\n");
13508 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
13509 		}
13510 
13511 	}
13512 
13513 	/*
13514 	 * Report it as dirty till we see it cleaned
13515 	 */
13516 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
13517 
13518 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13519 		    "alert_page still dirty\n");
13520 		rval |= MTF_TAPE_HEAD_DIRTY;
13521 	}
13522 
13523 	kmem_free(com, sizeof (struct uscsi_cmd));
13524 	kmem_free(ta,  sizeof (struct st_tape_alert));
13525 
13526 	return (rval);
13527 }
13528 
13529 
13530 static int
13531 st_check_sense_clean_bit(struct scsi_tape *un)
13532 {
13533 	uchar_t *sensep;
13534 	char cdb[CDB_GROUP0];
13535 	struct uscsi_cmd *com;
13536 	ushort_t byte_pos;
13537 	uchar_t bit_mask;
13538 	unsigned length;
13539 	int index;
13540 	int rval;
13541 
13542 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
13543 
13544 	/*
13545 	 * Since this tape does not support Tape Alert,
13546 	 * we now try to get the cleanbit status via
13547 	 * Request Sense.
13548 	 */
13549 
13550 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
13551 
13552 		index = 0;
13553 
13554 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
13555 
13556 		index = 1;
13557 
13558 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
13559 
13560 		index = 2;
13561 
13562 	} else {
13563 
13564 		return (-1);
13565 	}
13566 
13567 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
13568 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
13569 	length = byte_pos + 1;
13570 
13571 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13572 	sensep = kmem_zalloc(length, KM_SLEEP);
13573 
13574 	cdb[0] = SCMD_REQUEST_SENSE;
13575 	cdb[1] = 0;
13576 	cdb[2] = 0;
13577 	cdb[3] = 0;
13578 	cdb[4] = (char)length;
13579 	cdb[5] = 0;
13580 
13581 	com->uscsi_cdb = cdb;
13582 	com->uscsi_cdblen = CDB_GROUP0;
13583 	com->uscsi_bufaddr = (caddr_t)sensep;
13584 	com->uscsi_buflen = length;
13585 	com->uscsi_flags =
13586 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13587 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13588 
13589 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13590 
13591 	if (rval || com->uscsi_status || com->uscsi_resid) {
13592 
13593 		rval = -1;
13594 
13595 	} else {
13596 
13597 		rval = MTF_TAPE_CLN_SUPPORTED;
13598 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
13599 
13600 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13601 			    "sense data says head dirty\n");
13602 			rval |= MTF_TAPE_HEAD_DIRTY;
13603 		}
13604 	}
13605 
13606 	kmem_free(com, sizeof (struct uscsi_cmd));
13607 	kmem_free(sensep, length);
13608 	return (rval);
13609 }
13610 
13611 /*
13612  * st_clear_unit_attention
13613  *
13614  *  	run test unit ready's to clear out outstanding
13615  * 	unit attentions.
13616  * 	returns zero for SUCCESS or the errno from st_cmd call
13617  */
13618 static int
13619 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
13620 {
13621 	int	i    = 0;
13622 	int	rval;
13623 
13624 	GET_SOFT_STATE(dev_instance);
13625 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
13626 
13627 	do {
13628 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
13629 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
13630 	return (rval);
13631 }
13632 
13633 static void
13634 st_calculate_timeouts(struct scsi_tape *un)
13635 {
13636 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
13637 
13638 	if (un->un_dp->non_motion_timeout == 0) {
13639 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13640 			un->un_dp->non_motion_timeout =
13641 			    st_io_time * st_long_timeout_x;
13642 		} else {
13643 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
13644 		}
13645 	}
13646 
13647 	if (un->un_dp->io_timeout == 0) {
13648 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13649 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
13650 		} else {
13651 			un->un_dp->io_timeout = (ushort_t)st_io_time;
13652 		}
13653 	}
13654 
13655 	if (un->un_dp->rewind_timeout == 0) {
13656 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13657 			un->un_dp->rewind_timeout =
13658 			    st_space_time * st_long_timeout_x;
13659 		} else {
13660 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
13661 		}
13662 	}
13663 
13664 	if (un->un_dp->space_timeout == 0) {
13665 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13666 			un->un_dp->space_timeout =
13667 			    st_space_time * st_long_timeout_x;
13668 		} else {
13669 			un->un_dp->space_timeout = (ushort_t)st_space_time;
13670 		}
13671 	}
13672 
13673 	if (un->un_dp->load_timeout == 0) {
13674 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13675 			un->un_dp->load_timeout =
13676 			    st_space_time * st_long_timeout_x;
13677 		} else {
13678 			un->un_dp->load_timeout = (ushort_t)st_space_time;
13679 		}
13680 	}
13681 
13682 	if (un->un_dp->unload_timeout == 0) {
13683 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13684 			un->un_dp->unload_timeout =
13685 			    st_space_time * st_long_timeout_x;
13686 		} else {
13687 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
13688 		}
13689 	}
13690 
13691 	if (un->un_dp->erase_timeout == 0) {
13692 		if (un->un_dp->options & ST_LONG_ERASE) {
13693 			un->un_dp->erase_timeout =
13694 			    st_space_time * st_long_space_time_x;
13695 		} else {
13696 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
13697 		}
13698 	}
13699 }
13700 
13701 
13702 static writablity
13703 st_is_not_wormable(struct scsi_tape *un)
13704 {
13705 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
13706 	return (RDWR);
13707 }
13708 
13709 static writablity
13710 st_is_hp_dat_tape_worm(struct scsi_tape *un)
13711 {
13712 	writablity wrt;
13713 
13714 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
13715 
13716 	/* Mode sense should be current */
13717 	if (un->un_mspl->media_type == 1) {
13718 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13719 		    "Drive has WORM media loaded\n");
13720 		wrt = WORM;
13721 	} else {
13722 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13723 		    "Drive has non WORM media loaded\n");
13724 		wrt = RDWR;
13725 	}
13726 	return (wrt);
13727 }
13728 
13729 #define	HP_DAT_INQUIRY 0x4A
13730 static writablity
13731 st_is_hp_dat_worm(struct scsi_tape *un)
13732 {
13733 	char *buf;
13734 	int result;
13735 	writablity wrt;
13736 
13737 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
13738 
13739 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
13740 
13741 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
13742 
13743 	if (result != 0) {
13744 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13745 		    "Read Standard Inquiry for WORM support failed");
13746 		wrt = FAILED;
13747 	} else if ((buf[40] & 1) == 0) {
13748 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13749 		    "Drive is NOT WORMable\n");
13750 		/* This drive doesn't support it so don't check again */
13751 		un->un_dp->options &= ~ST_WORMABLE;
13752 		wrt = RDWR;
13753 		un->un_wormable = st_is_not_wormable;
13754 	} else {
13755 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13756 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13757 		un->un_wormable = st_is_hp_dat_tape_worm;
13758 		wrt = un->un_wormable(un);
13759 	}
13760 
13761 	kmem_free(buf, HP_DAT_INQUIRY);
13762 
13763 	/*
13764 	 * If drive doesn't support it no point in checking further.
13765 	 */
13766 	return (wrt);
13767 }
13768 
13769 static writablity
13770 st_is_hp_lto_tape_worm(struct scsi_tape *un)
13771 {
13772 	writablity wrt;
13773 
13774 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
13775 
13776 	/* Mode sense should be current */
13777 	switch (un->un_mspl->media_type) {
13778 	case 0x00:
13779 		switch (un->un_mspl->density) {
13780 		case 0x40:
13781 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13782 			    "Drive has standard Gen I media loaded\n");
13783 			break;
13784 		case 0x42:
13785 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13786 			    "Drive has standard Gen II media loaded\n");
13787 			break;
13788 		case 0x44:
13789 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13790 			    "Drive has standard Gen III media loaded\n");
13791 			break;
13792 		case 0x46:
13793 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13794 			    "Drive has standard Gen IV media loaded\n");
13795 			break;
13796 		default:
13797 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13798 			    "Drive has standard unknown 0x%X media loaded\n",
13799 			    un->un_mspl->density);
13800 		}
13801 		wrt = RDWR;
13802 		break;
13803 	case 0x01:
13804 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13805 		    "Drive has WORM medium loaded\n");
13806 		wrt = WORM;
13807 		break;
13808 	case 0x80:
13809 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13810 		    "Drive has CD-ROM emulation medium loaded\n");
13811 		wrt = WORM;
13812 		break;
13813 	default:
13814 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13815 		    "Drive has an unexpected medium type 0x%X loaded\n",
13816 		    un->un_mspl->media_type);
13817 		wrt = RDWR;
13818 	}
13819 
13820 	return (wrt);
13821 }
13822 
13823 #define	LTO_REQ_INQUIRY 44
13824 static writablity
13825 st_is_hp_lto_worm(struct scsi_tape *un)
13826 {
13827 	char *buf;
13828 	int result;
13829 	writablity wrt;
13830 
13831 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
13832 
13833 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
13834 
13835 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
13836 
13837 	if (result != 0) {
13838 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13839 		    "Read Standard Inquiry for WORM support failed");
13840 		wrt = FAILED;
13841 	} else if ((buf[40] & 1) == 0) {
13842 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13843 		    "Drive is NOT WORMable\n");
13844 		/* This drive doesn't support it so don't check again */
13845 		un->un_dp->options &= ~ST_WORMABLE;
13846 		wrt = RDWR;
13847 		un->un_wormable = st_is_not_wormable;
13848 	} else {
13849 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13850 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13851 		un->un_wormable = st_is_hp_lto_tape_worm;
13852 		wrt = un->un_wormable(un);
13853 	}
13854 
13855 	kmem_free(buf, LTO_REQ_INQUIRY);
13856 
13857 	/*
13858 	 * If drive doesn't support it no point in checking further.
13859 	 */
13860 	return (wrt);
13861 }
13862 
13863 static writablity
13864 st_is_t10_worm_device(struct scsi_tape *un)
13865 {
13866 	writablity wrt;
13867 
13868 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
13869 
13870 	if (un->un_mspl->media_type == 0x3c) {
13871 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13872 		    "Drive has WORM media loaded\n");
13873 		wrt = WORM;
13874 	} else {
13875 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13876 		    "Drive has non WORM media loaded\n");
13877 		wrt = RDWR;
13878 	}
13879 	return (wrt);
13880 }
13881 
13882 #define	SEQ_CAP_PAGE	(char)0xb0
13883 static writablity
13884 st_is_t10_worm(struct scsi_tape *un)
13885 {
13886 	char *buf;
13887 	int result;
13888 	writablity wrt;
13889 
13890 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
13891 
13892 	buf = kmem_zalloc(6, KM_SLEEP);
13893 
13894 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
13895 
13896 	if (result != 0) {
13897 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13898 		    "Read Vitial Inquiry for Sequental Capability"
13899 		    " WORM support failed %x", result);
13900 		wrt = FAILED;
13901 	} else if ((buf[4] & 1) == 0) {
13902 		ASSERT(buf[1] == SEQ_CAP_PAGE);
13903 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13904 		    "Drive is NOT WORMable\n");
13905 		/* This drive doesn't support it so don't check again */
13906 		un->un_dp->options &= ~ST_WORMABLE;
13907 		wrt = RDWR;
13908 		un->un_wormable = st_is_not_wormable;
13909 	} else {
13910 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13911 		    "Drive supports WORM\n");
13912 		un->un_wormable = st_is_t10_worm_device;
13913 		wrt = un->un_wormable(un);
13914 	}
13915 
13916 	kmem_free(buf, 6);
13917 
13918 	return (wrt);
13919 }
13920 
13921 
13922 #define	STK_REQ_SENSE 26
13923 
13924 static writablity
13925 st_is_stk_worm(struct scsi_tape *un)
13926 {
13927 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
13928 	struct scsi_extended_sense *sense;
13929 	struct uscsi_cmd *cmd;
13930 	char *buf;
13931 	int result;
13932 	writablity wrt;
13933 
13934 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
13935 
13936 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13937 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
13938 	sense = (struct scsi_extended_sense *)buf;
13939 
13940 	cmd->uscsi_flags = USCSI_READ;
13941 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13942 	cmd->uscsi_cdb = &cdb[0];
13943 	cmd->uscsi_bufaddr = buf;
13944 	cmd->uscsi_buflen = STK_REQ_SENSE;
13945 	cmd->uscsi_cdblen = CDB_GROUP0;
13946 	cmd->uscsi_rqlen = 0;
13947 	cmd->uscsi_rqbuf = NULL;
13948 
13949 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
13950 
13951 	if (result != 0 || cmd->uscsi_status != 0) {
13952 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13953 		    "Request Sense for WORM failed");
13954 		wrt = RDWR;
13955 	} else if (sense->es_add_len + 8 < 24) {
13956 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13957 		    "Drive didn't send enough sense data for WORM byte %d\n",
13958 		    sense->es_add_len + 8);
13959 		wrt = RDWR;
13960 		un->un_wormable = st_is_not_wormable;
13961 	} else if ((buf[24]) & 0x02) {
13962 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13963 		    "Drive has WORM tape loaded\n");
13964 		wrt = WORM;
13965 		un->un_wormable = st_is_stk_worm;
13966 	} else {
13967 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13968 		    "Drive has normal tape loaded\n");
13969 		wrt = RDWR;
13970 		un->un_wormable = st_is_stk_worm;
13971 	}
13972 
13973 	kmem_free(buf, STK_REQ_SENSE);
13974 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13975 	return (wrt);
13976 }
13977 
13978 #define	DLT_INQ_SZ 44
13979 
13980 static writablity
13981 st_is_dlt_tape_worm(struct scsi_tape *un)
13982 {
13983 	caddr_t buf;
13984 	int result;
13985 	writablity wrt;
13986 
13987 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
13988 
13989 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
13990 
13991 	/* Read Attribute Media Type */
13992 
13993 	result = st_read_attributes(un, 0x0408, buf, 10, st_uscsi_cmd);
13994 
13995 	/*
13996 	 * If this quantum drive is attached via an HBA that cannot
13997 	 * support thr read attributes command return error in the
13998 	 * hope that someday they will support the t10 method.
13999 	 */
14000 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
14001 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14002 		    "Read Attribute Command for WORM Media detection is not "
14003 		    "supported on the HBA that this drive is attached to.");
14004 		wrt = RDWR;
14005 		un->un_wormable = st_is_not_wormable;
14006 		goto out;
14007 	}
14008 
14009 	if (result != 0) {
14010 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14011 		    "Read Attribute Command for WORM Media returned 0x%x",
14012 		    result);
14013 		wrt = RDWR;
14014 		un->un_dp->options &= ~ST_WORMABLE;
14015 		goto out;
14016 	}
14017 
14018 	if ((uchar_t)buf[9] == 0x80) {
14019 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14020 		    "Drive media is WORM\n");
14021 		wrt = WORM;
14022 	} else {
14023 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14024 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
14025 		wrt = RDWR;
14026 	}
14027 
14028 out:
14029 	kmem_free(buf, DLT_INQ_SZ);
14030 	return (wrt);
14031 }
14032 
14033 static writablity
14034 st_is_dlt_worm(struct scsi_tape *un)
14035 {
14036 	caddr_t buf;
14037 	int result;
14038 	writablity wrt;
14039 
14040 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
14041 
14042 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14043 
14044 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
14045 
14046 	if (result != 0) {
14047 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14048 		    "Read Vendor Specific Inquiry for WORM support failed");
14049 		wrt = RDWR;
14050 		goto out;
14051 	}
14052 
14053 	if ((buf[2] & 1) == 0) {
14054 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14055 		    "Drive is not WORMable\n");
14056 		wrt = RDWR;
14057 		un->un_dp->options &= ~ST_WORMABLE;
14058 		un->un_wormable = st_is_not_wormable;
14059 		goto out;
14060 	} else {
14061 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14062 		    "Drive is WORMable\n");
14063 		un->un_wormable = st_is_dlt_tape_worm;
14064 		wrt = un->un_wormable(un);
14065 	}
14066 out:
14067 	kmem_free(buf, DLT_INQ_SZ);
14068 
14069 	return (wrt);
14070 }
14071 
14072 typedef struct {
14073 	struct modeheader_seq header;
14074 #if defined(_BIT_FIELDS_LTOH) /* X86 */
14075 	uchar_t pagecode	:6,
14076 				:2;
14077 	uchar_t page_len;
14078 	uchar_t syslogalive	:2,
14079 		device		:1,
14080 		abs		:1,
14081 		ulpbot		:1,
14082 		prth		:1,
14083 		ponej		:1,
14084 		ait		:1;
14085 	uchar_t span;
14086 
14087 	uchar_t			:6,
14088 		worm		:1,
14089 		mic		:1;
14090 	uchar_t worm_cap	:1,
14091 				:7;
14092 	uint32_t		:32;
14093 #else /* SPARC */
14094 	uchar_t			:2,
14095 		pagecode	:6;
14096 	uchar_t page_len;
14097 	uchar_t ait		:1,
14098 		device		:1,
14099 		abs		:1,
14100 		ulpbot		:1,
14101 		prth		:1,
14102 		ponej		:1,
14103 		syslogalive	:2;
14104 	uchar_t span;
14105 	uchar_t mic		:1,
14106 		worm		:1,
14107 				:6;
14108 	uchar_t			:7,
14109 		worm_cap	:1;
14110 	uint32_t		:32;
14111 #endif
14112 }ait_dev_con;
14113 
14114 #define	AIT_DEV_PAGE 0x31
14115 static writablity
14116 st_is_sony_worm(struct scsi_tape *un)
14117 {
14118 	int result;
14119 	writablity wrt;
14120 	ait_dev_con *ait_conf;
14121 
14122 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14123 
14124 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
14125 
14126 	result = st_gen_mode_sense(un, st_uscsi_cmd, AIT_DEV_PAGE,
14127 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
14128 
14129 	if (result == 0) {
14130 
14131 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
14132 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14133 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
14134 			    ait_conf->pagecode, AIT_DEV_PAGE);
14135 			wrt = RDWR;
14136 			un->un_wormable = st_is_not_wormable;
14137 
14138 		} else if (ait_conf->worm_cap) {
14139 
14140 			un->un_wormable = st_is_sony_worm;
14141 
14142 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14143 			    "Drives is WORMable\n");
14144 			if (ait_conf->worm) {
14145 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14146 				    "Media is WORM\n");
14147 				wrt = WORM;
14148 			} else {
14149 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14150 				    "Media is not WORM\n");
14151 				wrt = RDWR;
14152 			}
14153 
14154 		} else {
14155 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14156 			    "Drives not is WORMable\n");
14157 			wrt = RDWR;
14158 			/* No further checking required */
14159 			un->un_dp->options &= ~ST_WORMABLE;
14160 		}
14161 
14162 	} else {
14163 
14164 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14165 		    "AIT device config mode sense page read command failed"
14166 		    " result = %d ", result);
14167 		wrt = FAILED;
14168 		un->un_wormable = st_is_not_wormable;
14169 	}
14170 
14171 	kmem_free(ait_conf, sizeof (ait_dev_con));
14172 	return (wrt);
14173 }
14174 
14175 static writablity
14176 st_is_drive_worm(struct scsi_tape *un)
14177 {
14178 	writablity wrt;
14179 
14180 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14181 
14182 	switch (un->un_dp->type) {
14183 	case MT_ISDLT:
14184 		wrt = st_is_dlt_worm(un);
14185 		break;
14186 
14187 	case MT_ISSTK9840:
14188 		wrt = st_is_stk_worm(un);
14189 		break;
14190 
14191 	case MT_IS8MM:
14192 	case MT_ISAIT:
14193 		wrt = st_is_sony_worm(un);
14194 		break;
14195 
14196 	case MT_LTO:
14197 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14198 			wrt = st_is_hp_lto_worm(un);
14199 		} else {
14200 			wrt = st_is_t10_worm(un);
14201 		}
14202 		break;
14203 
14204 	case MT_ISDAT:
14205 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14206 			wrt = st_is_hp_dat_worm(un);
14207 		} else {
14208 			wrt = st_is_t10_worm(un);
14209 		}
14210 		break;
14211 
14212 	default:
14213 		wrt = FAILED;
14214 		break;
14215 	}
14216 
14217 	/*
14218 	 * If any of the above failed try the t10 standard method.
14219 	 */
14220 	if (wrt == FAILED) {
14221 		wrt = st_is_t10_worm(un);
14222 	}
14223 
14224 	/*
14225 	 * Unknown method for detecting WORM media.
14226 	 */
14227 	if (wrt == FAILED) {
14228 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14229 		    "Unknown method for WORM media detection\n");
14230 		wrt = RDWR;
14231 		un->un_dp->options &= ~ST_WORMABLE;
14232 	}
14233 
14234 	return (wrt);
14235 }
14236 
14237 static int
14238 st_read_attributes(struct scsi_tape *un, uint16_t attribute, void *pnt,
14239     size_t size, ubufunc_t bufunc)
14240 {
14241 	char cdb[CDB_GROUP4];
14242 	int result;
14243 	struct uscsi_cmd *cmd;
14244 	struct scsi_arq_status status;
14245 
14246 	caddr_t buf = (caddr_t)pnt;
14247 
14248 	ST_FUNC(ST_DEVINFO, st_read_attributes);
14249 
14250 	if (un->un_sd->sd_inq->inq_ansi < 3) {
14251 		return (ENOTTY);
14252 	}
14253 
14254 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14255 
14256 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
14257 	cdb[1] = 0;
14258 	cdb[2] = 0;
14259 	cdb[3] = 0;
14260 	cdb[4] = 0;
14261 	cdb[5] = 0;
14262 	cdb[6] = 0;
14263 	cdb[7] = 0;
14264 	cdb[8] = (char)(attribute >> 8);
14265 	cdb[9] = (char)(attribute);
14266 	cdb[10] = (char)(size >> 24);
14267 	cdb[11] = (char)(size >> 16);
14268 	cdb[12] = (char)(size >> 8);
14269 	cdb[13] = (char)(size);
14270 	cdb[14] = 0;
14271 	cdb[15] = 0;
14272 
14273 
14274 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE | USCSI_DIAGNOSE;
14275 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14276 	cmd->uscsi_cdb = &cdb[0];
14277 	cmd->uscsi_bufaddr = (caddr_t)buf;
14278 	cmd->uscsi_buflen = size;
14279 	cmd->uscsi_cdblen = sizeof (cdb);
14280 	cmd->uscsi_rqlen = sizeof (status);
14281 	cmd->uscsi_rqbuf = (caddr_t)&status;
14282 
14283 	result = bufunc(un, cmd, FKIOCTL);
14284 
14285 	if (result != 0 || cmd->uscsi_status != 0) {
14286 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
14287 		    "st_read_attribute failed: result %d status %d\n",
14288 		    result, cmd->uscsi_status);
14289 		/*
14290 		 * If this returns invalid operation code don't try again.
14291 		 */
14292 		if (un->un_sd->sd_sense->es_key == KEY_ILLEGAL_REQUEST &&
14293 		    un->un_sd->sd_sense->es_add_code == 0x20) {
14294 			result = ENOTTY;
14295 		} else if (result == 0) {
14296 			result = EIO;
14297 		}
14298 
14299 	} else {
14300 
14301 		/*
14302 		 * The attribute retured should match the attribute requested.
14303 		 */
14304 		if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
14305 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14306 			    "st_read_attribute got wrong data back expected "
14307 			    "0x%x got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
14308 			st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14309 			    "bad? data", buf, size);
14310 			result = EIO;
14311 		}
14312 	}
14313 
14314 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14315 
14316 	return (result);
14317 }
14318 
14319 static int
14320 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
14321     uchar_t page)
14322 {
14323 	char cdb[CDB_GROUP0];
14324 	struct scsi_extended_sense *sense;
14325 	struct uscsi_cmd *cmd;
14326 	int result;
14327 
14328 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
14329 
14330 	cdb[0] = SCMD_INQUIRY;
14331 	cdb[1] = page ? 1 : 0;
14332 	cdb[2] = page;
14333 	cdb[3] = 0;
14334 	cdb[4] = size;
14335 	cdb[5] = 0;
14336 
14337 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14338 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
14339 
14340 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
14341 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14342 	cmd->uscsi_cdb = &cdb[0];
14343 	cmd->uscsi_bufaddr = dest;
14344 	cmd->uscsi_buflen = size;
14345 	cmd->uscsi_cdblen = CDB_GROUP0;
14346 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
14347 	cmd->uscsi_rqbuf = (caddr_t)sense;
14348 
14349 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14350 
14351 	if (result != 0 || cmd->uscsi_status != 0) {
14352 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14353 		    "st_get_special_inquiry() failed for page %x", page);
14354 		if (result == 0) {
14355 			result = EIO;
14356 		}
14357 	}
14358 
14359 	kmem_free(sense, sizeof (struct scsi_extended_sense));
14360 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14361 
14362 	return (result);
14363 }
14364 
14365 
14366 static int
14367 st_update_block_pos(struct scsi_tape *un, bufunc_t bf, int post_space)
14368 {
14369 	int rval = ENOTTY;
14370 	uchar_t status = un->un_status;
14371 	posmode previous_pmode = un->un_running.pmode;
14372 
14373 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
14374 
14375 	while (un->un_read_pos_type != NO_POS) {
14376 		rval = bf(un, SCMD_READ_POSITION, 32, SYNC_CMD);
14377 
14378 		/*
14379 		 * If read position command returned good status
14380 		 * Parse the data to see if the position can be interpreted.
14381 		 */
14382 		if ((rval == 0) &&
14383 		    ((rval = st_interpret_read_pos(un, &un->un_pos,
14384 		    un->un_read_pos_type, 32, (caddr_t)un->un_read_pos_data,
14385 		    post_space)) == 0)) {
14386 			/*
14387 			 * Update the running position as well if un_pos was
14388 			 * ok. But only if recovery is enabled.
14389 			 */
14390 			if (st_recov_sz != sizeof (recov_info)) {
14391 				break;
14392 			}
14393 			rval = st_interpret_read_pos(un, &un->un_running,
14394 			    un->un_read_pos_type, 32,
14395 			    (caddr_t)un->un_read_pos_data, post_space);
14396 			un->un_status = status;
14397 			break;
14398 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
14399 			un->un_running.pmode = previous_pmode;
14400 			continue;
14401 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
14402 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
14403 			    "st_update_block_pos() read position cmd 0x%x"
14404 			    " returned 0x%x un_status = %d",
14405 			    un->un_read_pos_type, rval, un->un_status);
14406 			/* ENOTTY means it read garbage. try something else. */
14407 			if (rval == ENOTTY) {
14408 				rval = EIO; /* so ENOTTY is not final rval */
14409 			} else {
14410 				break;
14411 			}
14412 		} else {
14413 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
14414 			    "st_update_block_pos() read position cmd %x"
14415 			    " returned %x", un->un_read_pos_type, rval);
14416 			un->un_running.pmode = previous_pmode;
14417 		}
14418 
14419 		switch (un->un_read_pos_type) {
14420 		case SHORT_POS:
14421 			un->un_read_pos_type = NO_POS;
14422 			break;
14423 
14424 		case LONG_POS:
14425 			un->un_read_pos_type = EXT_POS;
14426 			break;
14427 
14428 		case EXT_POS:
14429 			un->un_read_pos_type = SHORT_POS;
14430 			break;
14431 
14432 		default:
14433 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14434 			    "Unexpected read position type 0x%x",
14435 			    un->un_read_pos_type);
14436 		}
14437 		un->un_status = KEY_NO_SENSE;
14438 	}
14439 
14440 	return (rval);
14441 }
14442 
14443 static int
14444 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
14445 {
14446 	int result;
14447 	size_t d_sz;
14448 	caddr_t pos_info;
14449 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
14450 
14451 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
14452 
14453 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
14454 		return (0);
14455 	}
14456 
14457 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
14458 
14459 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14460 		    "bp_mapin_common() failed");
14461 
14462 		return (EIO);
14463 	}
14464 
14465 	d_sz = bp->b_bcount - bp->b_resid;
14466 	if (d_sz == 0) {
14467 		bp_mapout(bp);
14468 		return (EIO);
14469 	}
14470 
14471 	/*
14472 	 * Copy the buf to a double-word aligned memory that can hold the
14473 	 * tape_position_t data structure.
14474 	 */
14475 	if ((pos_info = kmem_alloc(d_sz, KM_NOSLEEP)) == NULL) {
14476 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14477 		    "kmem_alloc() failed");
14478 		bp_mapout(bp);
14479 		return (EIO);
14480 	}
14481 	bcopy(bp->b_un.b_addr, pos_info, d_sz);
14482 
14483 #ifdef STDEBUG
14484 	if ((st_debug & 0x7) > 2) {
14485 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14486 		    "st_get_read_pos() position info",
14487 		    pos_info, bp->b_bcount);
14488 	}
14489 #endif
14490 
14491 	result = st_interpret_read_pos(un, &un->un_pos, cmd->uscsi_cdb[1],
14492 	    d_sz, pos_info, 0);
14493 
14494 	COPY_POS(&un->un_running, &un->un_pos);
14495 
14496 	kmem_free(pos_info, d_sz);
14497 	bp_mapout(bp);
14498 
14499 	return (result);
14500 }
14501 
14502 #if defined(_BIG_ENDIAN)
14503 
14504 #define	FIX_ENDIAN16(x)
14505 #define	FIX_ENDIAN32(x)
14506 #define	FIX_ENDIAN64(x)
14507 
14508 #elif defined(_LITTLE_ENDIAN)
14509 
14510 static void
14511 st_swap16(uint16_t *val)
14512 {
14513 	uint16_t tmp;
14514 
14515 	tmp = (*val >>  8) & 0xff;
14516 	tmp |= (*val <<  8) & 0xff00;
14517 
14518 	*val = tmp;
14519 }
14520 
14521 static void
14522 st_swap32(uint32_t *val)
14523 {
14524 	uint32_t tmp;
14525 
14526 	tmp =  (*val >> 24) & 0xff;
14527 	tmp |= (*val >>  8) & 0xff00;
14528 	tmp |= (*val <<  8) & 0xff0000;
14529 	tmp |= (*val << 24) & 0xff000000;
14530 
14531 	*val = tmp;
14532 }
14533 
14534 static void
14535 st_swap64(uint64_t *val)
14536 {
14537 	uint32_t low;
14538 	uint32_t high;
14539 
14540 	low =  (uint32_t)(*val);
14541 	high = (uint32_t)(*val >> 32);
14542 
14543 	st_swap32(&low);
14544 	st_swap32(&high);
14545 
14546 	*val =  high;
14547 	*val |= ((uint64_t)low << 32);
14548 }
14549 
14550 #define	FIX_ENDIAN16(x) st_swap16(x)
14551 #define	FIX_ENDIAN32(x) st_swap32(x)
14552 #define	FIX_ENDIAN64(x) st_swap64(x)
14553 #endif
14554 
14555 /*
14556  * st_interpret_read_pos()
14557  *
14558  * Returns:
14559  *	0	If secsessful.
14560  *	EIO	If read postion responce data was unuseable or invalid.
14561  *	ERANGE	If the position of the drive is too large for the read_p_type.
14562  *	ENOTTY	If the responce data looks invalid for the read position type.
14563  */
14564 
14565 static int
14566 st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
14567     read_p_types type, size_t data_sz, const caddr_t responce, int post_space)
14568 {
14569 	int rval = 0;
14570 	int flag = 0;
14571 	tapepos_t org;
14572 
14573 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
14574 
14575 	/*
14576 	 * We expect the position value to change after a space command.
14577 	 * So if post_space is set we don't print out what has changed.
14578 	 */
14579 	if ((dest != &un->un_pos) && (post_space == 0) &&
14580 	    (st_recov_sz == sizeof (recov_info))) {
14581 		COPY_POS(&org, dest);
14582 		flag = 1;
14583 	}
14584 
14585 	/*
14586 	 * See what kind of read position was requested.
14587 	 */
14588 	switch (type) {
14589 
14590 	case SHORT_POS: /* Short data format */
14591 	{
14592 		tape_position_t *pos_info = (tape_position_t *)responce;
14593 		uint32_t value;
14594 
14595 		/* If reserved fields are non zero don't use the data */
14596 		if (pos_info->reserved0 || pos_info->reserved1 ||
14597 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
14598 		    pos_info->reserved3) {
14599 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14600 			    "Invalid Read Short Position Data returned\n");
14601 			rval = EIO;
14602 			break;
14603 		}
14604 		/*
14605 		 * Position is to large to use this type of read position.
14606 		 */
14607 		if (pos_info->posi_err == 1) {
14608 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14609 			    "Drive reported position error\n");
14610 			rval = ERANGE;
14611 			break;
14612 		}
14613 		/*
14614 		 * If your at the begining of partition and end at the same
14615 		 * time it's very small partition or bad data.
14616 		 */
14617 		if (pos_info->begin_of_part && pos_info->end_of_part) {
14618 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14619 			    "SHORT_POS returned begin and end of"
14620 			    " partition\n");
14621 			rval = EIO;
14622 			break;
14623 		}
14624 
14625 		if (pos_info->blk_posi_unkwn == 0) {
14626 
14627 			value = pos_info->host_block;
14628 			FIX_ENDIAN32(&value);
14629 
14630 			/*
14631 			 * If the tape is rewound the host blcok should be 0.
14632 			 */
14633 			if ((pos_info->begin_of_part == 1) &&
14634 			    (value != 0)) {
14635 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14636 				    "SHORT_POS returned begin of partition"
14637 				    " but host block was 0x%x\n", value);
14638 				rval = EIO;
14639 				break;
14640 			}
14641 
14642 			if (dest->lgclblkno != value) {
14643 				if (flag)
14644 					flag++;
14645 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14646 				    "SHORT_POS current logical 0x%"PRIx64" read"
14647 				    " 0x%x\n", dest->lgclblkno, value);
14648 			}
14649 
14650 			dest->lgclblkno = (uint64_t)value;
14651 
14652 			/*
14653 			 * If the begining of partition is true and the
14654 			 * block number is zero we will beleive that it is
14655 			 * rewound. Promote the pmode to legacy.
14656 			 */
14657 			if ((pos_info->begin_of_part == 1) &&
14658 			    (value == 0)) {
14659 				dest->blkno = 0;
14660 				dest->fileno = 0;
14661 				if (dest->pmode != legacy)
14662 					dest->pmode = legacy;
14663 			/*
14664 			 * otherwise if the pmode was invalid,
14665 			 * promote it to logical.
14666 			 */
14667 			} else if (dest->pmode == invalid) {
14668 				dest->pmode = logical;
14669 			}
14670 
14671 			if (dest->partition != pos_info->partition_number) {
14672 				if (flag)
14673 					flag++;
14674 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14675 				    "SHORT_POS current partition %d read %d\n",
14676 				    dest->partition,
14677 				    pos_info->partition_number);
14678 			}
14679 
14680 			dest->partition = pos_info->partition_number;
14681 
14682 		} else {
14683 			dest->pmode = invalid;
14684 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14685 			    "Tape drive reported block position as unknown\n");
14686 		}
14687 		break;
14688 	}
14689 
14690 	case LONG_POS: /* Long data format */
14691 	{
14692 		uint64_t value;
14693 		tape_position_long_t *long_pos_info =
14694 		    (tape_position_long_t *)responce;
14695 
14696 		/* If reserved fields are non zero don't use the data */
14697 		if ((long_pos_info->reserved0) ||
14698 		    (long_pos_info->reserved1) ||
14699 		    (long_pos_info->reserved2)) {
14700 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14701 			    "Invalid Read Long Position Data returned\n");
14702 			rval = ENOTTY;
14703 			break;
14704 		}
14705 
14706 		/* Is position Valid */
14707 		if (long_pos_info->blk_posi_unkwn == 0) {
14708 			uint32_t part;
14709 
14710 			value = long_pos_info->block_number;
14711 			FIX_ENDIAN64(&value);
14712 
14713 			/*
14714 			 * If it says we are at the begining of partition
14715 			 * the block value better be 0.
14716 			 */
14717 			if ((long_pos_info->begin_of_part == 1) &&
14718 			    (value != 0)) {
14719 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14720 				    "LONG_POS returned begin of partition but"
14721 				    " block number was 0x%"PRIx64"\n", value);
14722 				rval = ENOTTY;
14723 				break;
14724 			}
14725 			/*
14726 			 * Can't be at the start and the end of the partition
14727 			 * at the same time if the partition is larger the 0.
14728 			 */
14729 			if (long_pos_info->begin_of_part &&
14730 			    long_pos_info->end_of_part) {
14731 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14732 				    "LONG_POS returned begin and end of"
14733 				    " partition\n");
14734 				rval = ENOTTY;
14735 				break;
14736 			}
14737 
14738 			/*
14739 			 * If the logical block number is not what we expected.
14740 			 */
14741 			if (dest->lgclblkno != value) {
14742 				if (flag)
14743 					flag++;
14744 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14745 				    "LONG_POS current logical 0x%"PRIx64
14746 				    " read 0x%"PRIx64"\n",
14747 				    dest->lgclblkno, value);
14748 			}
14749 			dest->lgclblkno = value;
14750 
14751 			/*
14752 			 * If the begining of partition is true and the
14753 			 * block number is zero we will beleive that it is
14754 			 * rewound. Promote the pmode to legacy.
14755 			 */
14756 			if ((long_pos_info->begin_of_part == 1) &&
14757 			    (long_pos_info->block_number == 0)) {
14758 				dest->blkno = 0;
14759 				dest->fileno = 0;
14760 				if (dest->pmode != legacy)
14761 					dest->pmode = legacy;
14762 			/*
14763 			 * otherwise if the pmode was invalid,
14764 			 * promote it to logical.
14765 			 */
14766 			} else if (dest->pmode == invalid) {
14767 				dest->pmode = logical;
14768 			}
14769 
14770 			part = long_pos_info->partition;
14771 			FIX_ENDIAN32(&part);
14772 			if (dest->partition != part) {
14773 				if (flag)
14774 					flag++;
14775 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14776 				    "LONG_POS current partition %d"
14777 				    " read %d\n", dest->partition, part);
14778 			}
14779 			dest->partition = part;
14780 		} else {
14781 			/*
14782 			 * If the drive doesn't know location,
14783 			 * we don't either.
14784 			 */
14785 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14786 			    "Tape drive reported block position as unknown\n");
14787 			dest->pmode = invalid;
14788 		}
14789 
14790 		/* Is file position valid */
14791 		if (long_pos_info->mrk_posi_unkwn == 0) {
14792 			value = long_pos_info->file_number;
14793 			FIX_ENDIAN64(&value);
14794 			/*
14795 			 * If it says we are at the begining of partition
14796 			 * the block value better be 0.
14797 			 */
14798 			if ((long_pos_info->begin_of_part == 1) &&
14799 			    (value != 0)) {
14800 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14801 				    "LONG_POS returned begin of partition but"
14802 				    " block number was 0x%"PRIx64"\n", value);
14803 				rval = ENOTTY;
14804 				break;
14805 			}
14806 			if (((dest->pmode == legacy) ||
14807 			    (dest->pmode == logical)) &&
14808 			    (dest->fileno != value)) {
14809 				if (flag)
14810 					flag++;
14811 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14812 				    "LONG_POS fileno 0x%"PRIx64
14813 				    " not un_pos %x\n", value,
14814 				    dest->fileno);
14815 			} else if (dest->pmode == invalid) {
14816 				dest->pmode = logical;
14817 			}
14818 			dest->fileno = (int32_t)value;
14819 		} else {
14820 			/*
14821 			 * If the drive doesn't know its position,
14822 			 * we don't either.
14823 			 */
14824 			dest->pmode = invalid;
14825 		}
14826 		if (dest->pmode != invalid && long_pos_info->end_of_part) {
14827 			dest->eof = ST_EOT;
14828 		}
14829 
14830 		break;
14831 	}
14832 
14833 	case EXT_POS: /* Extended data format */
14834 	{
14835 		uint64_t value;
14836 		uint16_t len;
14837 		tape_position_ext_t *ext_pos_info =
14838 		    (tape_position_ext_t *)responce;
14839 
14840 		/* Make sure that there is enough data there */
14841 		if (data_sz < 16) {
14842 			break;
14843 		}
14844 
14845 		/* If reserved fields are non zero don't use the data */
14846 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
14847 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14848 			    "EXT_POS reserved fields not zero\n");
14849 			rval = ENOTTY;
14850 			break;
14851 		}
14852 
14853 		/*
14854 		 * In the unlikely event of overflowing 64 bits of position.
14855 		 */
14856 		if (ext_pos_info->posi_err != 0) {
14857 			rval = ERANGE;
14858 			break;
14859 		}
14860 
14861 		len = ext_pos_info->parameter_len;
14862 		FIX_ENDIAN16(&len);
14863 
14864 		if (len != 0x1c) {
14865 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14866 			    "EXT_POS parameter_len should be 0x1c was 0x%x\n",
14867 			    len);
14868 			rval = ENOTTY;
14869 			break;
14870 		}
14871 
14872 		/* Is block position information valid */
14873 		if (ext_pos_info->blk_posi_unkwn == 0) {
14874 
14875 			value = ext_pos_info->host_block;
14876 			FIX_ENDIAN64(&value);
14877 			if ((ext_pos_info->begin_of_part == 1) &&
14878 			    (value != 0)) {
14879 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14880 				    "EXT_POS returned begining of partition but"
14881 				    " the host block was 0x%"PRIx64"\n", value);
14882 				rval = ENOTTY;
14883 				break;
14884 			}
14885 
14886 			if (dest->lgclblkno != value) {
14887 				if (flag)
14888 					flag++;
14889 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14890 				    "EXT_POS current logical 0x%"PRIx64
14891 				    " read 0x%"PRIx64"\n",
14892 				    dest->lgclblkno, value);
14893 			}
14894 			dest->lgclblkno = value;
14895 
14896 			/*
14897 			 * If the begining of partition is true and the
14898 			 * block number is zero we will beleive that it is
14899 			 * rewound. Promote the pmode to legacy.
14900 			 */
14901 			if ((ext_pos_info->begin_of_part == 1) &&
14902 			    (ext_pos_info->host_block == 0)) {
14903 				dest->blkno = 0;
14904 				dest->fileno = 0;
14905 				if (dest->pmode != legacy) {
14906 					dest->pmode = legacy;
14907 				}
14908 			/*
14909 			 * otherwise if the pmode was invalid,
14910 			 * promote it to logical.
14911 			 */
14912 			} else if (dest->pmode == invalid) {
14913 				dest->pmode = logical;
14914 			}
14915 
14916 			if (dest->partition != ext_pos_info->partition) {
14917 				if (flag)
14918 					flag++;
14919 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14920 				    "EXT_POS current partition %d read %d\n",
14921 				    dest->partition,
14922 				    ext_pos_info->partition);
14923 			}
14924 			dest->partition = ext_pos_info->partition;
14925 
14926 		} else {
14927 			dest->pmode = invalid;
14928 		}
14929 		break;
14930 	}
14931 
14932 	default:
14933 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14934 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
14935 		rval = EIO;
14936 	}
14937 
14938 	if ((flag > 1) && (rval == 0) && (org.pmode != invalid)) {
14939 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14940 		    "position read in", &org);
14941 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14942 		    "position read out", dest);
14943 	}
14944 
14945 	return (rval);
14946 }
14947 
14948 static int
14949 st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos,
14950     uint64_t lblk, uchar_t partition)
14951 {
14952 	int rval;
14953 	char cdb[CDB_GROUP4];
14954 	struct uscsi_cmd *cmd;
14955 	struct scsi_extended_sense sense;
14956 	bufunc_t bf = (ubf == st_uscsi_cmd) ? st_cmd : st_rcmd;
14957 
14958 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
14959 	/*
14960 	 * Not sure what to do when doing recovery and not wanting
14961 	 * to update un_pos
14962 	 */
14963 
14964 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14965 
14966 	if (lblk <= INT32_MAX) {
14967 		cmd->uscsi_cdblen = CDB_GROUP1;
14968 		cdb[0] = SCMD_LOCATE;
14969 		cdb[1] = pos->partition == partition ? 0 : 2;
14970 		cdb[2] = 0;
14971 		cdb[3] = (char)(lblk >> 24);
14972 		cdb[4] = (char)(lblk >> 16);
14973 		cdb[5] = (char)(lblk >> 8);
14974 		cdb[6] = (char)(lblk);
14975 		cdb[7] = 0;
14976 		cdb[8] = partition;
14977 		cdb[9] = 0;
14978 	} else {
14979 		/*
14980 		 * If the drive doesn't give a 64 bit read position data
14981 		 * it is unlikely it will accept 64 bit locates.
14982 		 */
14983 		if (un->un_read_pos_type != LONG_POS) {
14984 			kmem_free(cmd, sizeof (struct uscsi_cmd));
14985 			return (ERANGE);
14986 		}
14987 		cmd->uscsi_cdblen = CDB_GROUP4;
14988 		cdb[0] = (char)SCMD_LOCATE_G4;
14989 		cdb[1] = pos->partition == partition ? 0 : 2;
14990 		cdb[2] = 0;
14991 		cdb[3] = partition;
14992 		cdb[4] = (char)(lblk >> 56);
14993 		cdb[5] = (char)(lblk >> 48);
14994 		cdb[6] = (char)(lblk >> 40);
14995 		cdb[7] = (char)(lblk >> 32);
14996 		cdb[8] = (char)(lblk >> 24);
14997 		cdb[9] = (char)(lblk >> 16);
14998 		cdb[10] = (char)(lblk >> 8);
14999 		cdb[11] = (char)(lblk);
15000 		cdb[12] = 0;
15001 		cdb[13] = 0;
15002 		cdb[14] = 0;
15003 		cdb[15] = 0;
15004 	}
15005 
15006 
15007 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
15008 	cmd->uscsi_rqbuf = (caddr_t)&sense;
15009 	cmd->uscsi_rqlen = sizeof (sense);
15010 	cmd->uscsi_timeout = un->un_dp->space_timeout;
15011 	cmd->uscsi_cdb = cdb;
15012 
15013 	rval = ubf(un, cmd, FKIOCTL);
15014 
15015 	pos->pmode = logical;
15016 	pos->eof = ST_NO_EOF;
15017 
15018 	if (lblk > INT32_MAX) {
15019 		/*
15020 		 * XXX This is a work around till we handle Descriptor format
15021 		 * sense data. Since we are sending a command where the standard
15022 		 * sense data can not correctly represent a correct residual in
15023 		 * 4 bytes.
15024 		 */
15025 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
15026 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15027 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
15028 			/* Doesn't like big locate command */
15029 			un->un_status = 0;
15030 			rval = ERANGE;
15031 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
15032 			/* Aborted big locate command */
15033 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15034 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
15035 			    rval);
15036 			un->un_status = 0;
15037 			rval = EIO;
15038 		} else if (st_update_block_pos(un, bf, 1)) {
15039 			/* read position failed */
15040 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15041 			    "Big LOCATE and read pos: rval = %d\n", rval);
15042 			rval = EIO;
15043 		} else if (lblk > un->un_pos.lgclblkno) {
15044 			/* read position worked but position was not expected */
15045 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15046 			    "Big LOCATE and recover read less then desired 0x%"
15047 			    PRIx64"\n", un->un_pos.lgclblkno);
15048 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
15049 			un->un_status = KEY_BLANK_CHECK;
15050 			rval = ESPIPE;
15051 		} else if (lblk == un->un_pos.lgclblkno) {
15052 			/* read position was what was expected */
15053 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15054 			    "Big LOCATE and recover seems to have worked\n");
15055 			un->un_err_resid = 0;
15056 			rval = 0;
15057 		} else {
15058 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15059 			    "BIGLOCATE end up going backwards");
15060 			un->un_err_resid = lblk;
15061 			rval = EIO;
15062 		}
15063 
15064 	} else if (rval == 0) {
15065 		/* Worked as requested */
15066 		pos->lgclblkno = lblk;
15067 
15068 	} else if (((cmd->uscsi_status & ST_STATUS_MASK) == STATUS_CHECK) &&
15069 	    (cmd->uscsi_resid != 0)) {
15070 		/* Got part way there but wasn't enough blocks on tape */
15071 		pos->lgclblkno = lblk - cmd->uscsi_resid;
15072 		un->un_err_resid = cmd->uscsi_resid;
15073 		un->un_status = KEY_BLANK_CHECK;
15074 		rval = ESPIPE;
15075 
15076 	} else if (st_update_block_pos(un, bf, 1) == 0) {
15077 		/* Got part way there but drive didn't tell what we missed by */
15078 		un->un_err_resid = lblk - pos->lgclblkno;
15079 		un->un_status = KEY_BLANK_CHECK;
15080 		rval = ESPIPE;
15081 
15082 	} else {
15083 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15084 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
15085 		    rval, cmd->uscsi_status);
15086 		un->un_err_resid = lblk;
15087 		un->un_status = KEY_ILLEGAL_REQUEST;
15088 		pos->pmode = invalid;
15089 		rval = EIO;
15090 	}
15091 
15092 	kmem_free(cmd, sizeof (struct uscsi_cmd));
15093 
15094 	return (rval);
15095 }
15096 
15097 static int
15098 st_mtfsf_ioctl(struct scsi_tape *un, int64_t files)
15099 {
15100 	int rval;
15101 
15102 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
15103 
15104 
15105 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15106 	    "st_mtfsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15107 #if 0
15108 	if ((IN_EOF(un->un_pos)) && (files == 1)) {
15109 		un->un_pos.fileno++;
15110 		un->un_pos.blkno = 0;
15111 		return (0);
15112 	}
15113 #endif
15114 	/* pmode == invalid already handled */
15115 	if (un->un_pos.pmode == legacy) {
15116 		/*
15117 		 * forward space over filemark
15118 		 *
15119 		 * For ASF we allow a count of 0 on fsf which means
15120 		 * we just want to go to beginning of current file.
15121 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
15122 		 * Allow stepping over double fmk with reel
15123 		 */
15124 		if ((un->un_pos.eof >= ST_EOT) &&
15125 		    (files > 0) &&
15126 		    ((un->un_dp->options & ST_REEL) == 0)) {
15127 			/* we're at EOM */
15128 			un->un_err_resid = files;
15129 			un->un_status = KEY_BLANK_CHECK;
15130 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15131 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
15132 			return (EIO);
15133 		}
15134 
15135 		/*
15136 		 * physical tape position may not be what we've been
15137 		 * telling the user; adjust the request accordingly
15138 		 */
15139 		if (IN_EOF(un->un_pos)) {
15140 			un->un_pos.fileno++;
15141 			un->un_pos.blkno = 0;
15142 			/*
15143 			 * For positive direction case, we're now covered.
15144 			 * For zero or negative direction, we're covered
15145 			 * (almost)
15146 			 */
15147 			files--;
15148 		}
15149 
15150 	}
15151 
15152 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15153 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15154 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
15155 		return (EIO);
15156 	}
15157 
15158 
15159 	/*
15160 	 * Forward space file marks.
15161 	 * We leave ourselves at block zero
15162 	 * of the target file number.
15163 	 */
15164 	if (files < 0) {
15165 		rval = st_backward_space_files(un, -files, 0);
15166 	} else {
15167 		rval = st_forward_space_files(un, files);
15168 	}
15169 
15170 	return (rval);
15171 }
15172 
15173 static int
15174 st_forward_space_files(struct scsi_tape *un, int64_t count)
15175 {
15176 	int rval;
15177 
15178 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
15179 
15180 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15181 	    "fspace: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15182 
15183 	ASSERT(count >= 0);
15184 	ASSERT(un->un_pos.pmode != invalid);
15185 
15186 	/*
15187 	 * A space with a count of zero means take me to the start of file.
15188 	 */
15189 	if (count == 0) {
15190 
15191 		/* Hay look were already there */
15192 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0) {
15193 			un->un_err_resid = 0;
15194 			COPY_POS(&un->un_err_pos, &un->un_pos);
15195 			return (0);
15196 		}
15197 
15198 		/*
15199 		 * Well we are in the first file.
15200 		 * A rewind will get to the start.
15201 		 */
15202 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
15203 			rval = st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
15204 
15205 		/*
15206 		 * Can we backspace to get there?
15207 		 * This should work in logical mode.
15208 		 */
15209 		} else if (un->un_dp->options & ST_BSF) {
15210 			rval = st_space_to_begining_of_file(un);
15211 
15212 		/*
15213 		 * Can't back space but current file number is known,
15214 		 * So rewind and space from the begining of the partition.
15215 		 */
15216 		} else if (un->un_pos.pmode == legacy) {
15217 			rval = st_scenic_route_to_begining_of_file(un,
15218 			    un->un_pos.fileno);
15219 
15220 		/*
15221 		 * pmode is logical and ST_BSF is not set.
15222 		 * The LONG_POS read position contains the fileno.
15223 		 * If the read position works, rewind and space.
15224 		 */
15225 		} else if (un->un_read_pos_type == LONG_POS) {
15226 			rval = st_cmd(un, SCMD_READ_POSITION, 0, SYNC_CMD);
15227 			if (rval) {
15228 				/*
15229 				 * We didn't get the file position from the
15230 				 * read position command.
15231 				 * We are going to trust the drive to backspace
15232 				 * and then position after the filemark.
15233 				 */
15234 				rval = st_space_to_begining_of_file(un);
15235 			}
15236 			rval = st_interpret_read_pos(un, &un->un_pos, LONG_POS,
15237 			    32, (caddr_t)un->un_read_pos_data, 0);
15238 			if ((rval) && (un->un_pos.pmode == invalid)) {
15239 				rval = st_space_to_begining_of_file(un);
15240 			} else {
15241 				rval = st_scenic_route_to_begining_of_file(un,
15242 				    un->un_pos.fileno);
15243 			}
15244 		} else {
15245 			rval = EIO;
15246 		}
15247 		/*
15248 		 * If something didn't work we are lost
15249 		 */
15250 		if (rval != 0) {
15251 			un->un_pos.pmode = invalid;
15252 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15253 			    "st_mtioctop : EIO : fspace pmode invalid");
15254 
15255 			rval = EIO;
15256 		}
15257 
15258 	} else {
15259 		rval = st_space_fmks(un, count);
15260 	}
15261 
15262 	if (rval != EIO && count < 0) {
15263 		/*
15264 		 * we came here with a count < 0; we now need
15265 		 * to skip back to end up before the filemark
15266 		 */
15267 		rval = st_backward_space_files(un, 1, 1);
15268 	}
15269 
15270 	return (rval);
15271 }
15272 
15273 static int
15274 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
15275 {
15276 	int rval;
15277 
15278 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
15279 
15280 	if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15281 		rval = EIO;
15282 	} else if (st_cmd(un, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
15283 		rval = EIO;
15284 	}
15285 
15286 	return (rval);
15287 }
15288 
15289 static int
15290 st_space_to_begining_of_file(struct scsi_tape *un)
15291 {
15292 	int rval;
15293 
15294 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
15295 
15296 	/*
15297 	 * Back space of the file at the begining of the file.
15298 	 */
15299 	rval = st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
15300 	if (rval) {
15301 		rval = EIO;
15302 		return (rval);
15303 	}
15304 
15305 	/*
15306 	 * Other interesting answers might be crashed BOT which isn't bad.
15307 	 */
15308 	if (un->un_status == SUN_KEY_BOT) {
15309 		return (rval);
15310 	}
15311 
15312 	un->un_running.pmode = invalid;
15313 
15314 	/*
15315 	 * Now we are on the BOP side of the filemark. Forward space to
15316 	 * the EOM side and we are at the begining of the file.
15317 	 */
15318 	rval = st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD);
15319 	if (rval) {
15320 		rval = EIO;
15321 	}
15322 
15323 	return (rval);
15324 }
15325 
15326 static int
15327 st_mtfsr_ioctl(struct scsi_tape *un, int64_t count)
15328 {
15329 
15330 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
15331 
15332 	/*
15333 	 * forward space to inter-record gap
15334 	 *
15335 	 */
15336 
15337 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15338 	    "st_ioctl_fsr: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15339 
15340 	if (un->un_pos.pmode == legacy) {
15341 		/*
15342 		 * If were are at end of tape and count is forward.
15343 		 * Return blank check.
15344 		 */
15345 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
15346 			/* we're at EOM */
15347 			un->un_err_resid = count;
15348 			un->un_status = KEY_BLANK_CHECK;
15349 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15350 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
15351 			return (EIO);
15352 		}
15353 
15354 		/*
15355 		 * If count is zero there is nothing to do.
15356 		 */
15357 		if (count == 0) {
15358 			un->un_err_pos.fileno = un->un_pos.fileno;
15359 			un->un_err_pos.blkno = un->un_pos.blkno;
15360 			un->un_err_resid = 0;
15361 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15362 				un->un_status = SUN_KEY_EOF;
15363 			}
15364 			return (0);
15365 		}
15366 
15367 		/*
15368 		 * physical tape position may not be what we've been
15369 		 * telling the user; adjust the position accordingly
15370 		 */
15371 		if (IN_EOF(un->un_pos)) {
15372 			daddr_t blkno = un->un_pos.blkno;
15373 			int fileno = un->un_pos.fileno;
15374 
15375 			optype lastop = un->un_lastop;
15376 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)
15377 			    == -1) {
15378 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15379 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
15380 				return (EIO);
15381 			}
15382 
15383 			un->un_pos.blkno = blkno;
15384 			un->un_pos.fileno = fileno;
15385 			un->un_lastop = lastop;
15386 		}
15387 	}
15388 
15389 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15390 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15391 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
15392 		return (EIO);
15393 	}
15394 
15395 	return (st_space_records(un, count));
15396 }
15397 
15398 static int
15399 st_space_records(struct scsi_tape *un, int64_t count)
15400 {
15401 	int64_t dblk;
15402 	int rval = 0;
15403 
15404 	ST_FUNC(ST_DEVINFO, st_space_records);
15405 
15406 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15407 	    "st_space_records: count=%"PRIx64", eof=%x\n",
15408 	    count, un->un_pos.eof);
15409 
15410 	if (un->un_pos.pmode == logical) {
15411 		rval = st_cmd(un, SCMD_SPACE, Blk(count), SYNC_CMD);
15412 		if (rval != 0) {
15413 			rval = EIO;
15414 		}
15415 		return (rval);
15416 	}
15417 
15418 	dblk = count + un->un_pos.blkno;
15419 
15420 	/* Already there */
15421 	if (dblk == un->un_pos.blkno) {
15422 		un->un_err_resid = 0;
15423 		COPY_POS(&un->un_err_pos, &un->un_pos);
15424 		return (0);
15425 	}
15426 
15427 	/*
15428 	 * If the destination block is forward
15429 	 * or the drive will backspace records.
15430 	 */
15431 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
15432 		/*
15433 		 * If we're spacing forward, or the device can
15434 		 * backspace records, we can just use the SPACE
15435 		 * command.
15436 		 */
15437 		dblk -= un->un_pos.blkno;
15438 		if (st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15439 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15440 			    "st_space_records:EIO:space_records can't spc");
15441 			rval = EIO;
15442 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
15443 			/*
15444 			 * check if we hit BOT/EOT
15445 			 */
15446 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
15447 				un->un_status = SUN_KEY_BOT;
15448 				un->un_pos.eof = ST_NO_EOF;
15449 			} else if (dblk < 0 &&
15450 			    un->un_pos.eof == ST_EOF_PENDING) {
15451 				int residue = un->un_err_resid;
15452 				/*
15453 				 * we skipped over a filemark
15454 				 * and need to go forward again
15455 				 */
15456 				if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
15457 					ST_DEBUG2(ST_DEVINFO, st_label,
15458 					    SCSI_DEBUG, "st_space_records: EIO"
15459 					    " : can't space #2");
15460 					rval = EIO;
15461 				}
15462 				un->un_err_resid = residue;
15463 			}
15464 			if (rval == 0) {
15465 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15466 				    "st_space_records: EIO : space_rec rval"
15467 				    " == 0");
15468 				rval = EIO;
15469 			}
15470 		}
15471 	} else {
15472 		/*
15473 		 * else we rewind, space forward across filemarks to
15474 		 * the desired file, and then space records to the
15475 		 * desired block.
15476 		 */
15477 
15478 		int dfile = un->un_pos.fileno;	/* save current file */
15479 
15480 		if (dblk < 0) {
15481 			/*
15482 			 * Wups - we're backing up over a filemark
15483 			 */
15484 			if (un->un_pos.blkno != 0 &&
15485 			    (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15486 			    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD))) {
15487 				un->un_pos.pmode = invalid;
15488 			}
15489 			un->un_err_resid = -dblk;
15490 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
15491 				un->un_status = SUN_KEY_BOT;
15492 				un->un_pos.eof = ST_NO_EOF;
15493 			} else if (un->un_pos.fileno > 0) {
15494 				un->un_status = SUN_KEY_EOF;
15495 				un->un_pos.eof = ST_NO_EOF;
15496 			}
15497 			COPY_POS(&un->un_err_pos, &un->un_pos);
15498 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15499 			    "st_space_records:EIO:space_records : dblk < 0");
15500 			rval = EIO;
15501 		} else if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15502 		    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
15503 		    st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15504 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15505 			    "st_space_records: EIO :space_records : rewind "
15506 			    "and space failed");
15507 			un->un_pos.pmode = invalid;
15508 			rval = EIO;
15509 		}
15510 	}
15511 
15512 	return (rval);
15513 }
15514 
15515 static int
15516 st_mtbsf_ioctl(struct scsi_tape *un, int64_t files)
15517 {
15518 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
15519 
15520 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15521 	    "st_mtbsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15522 	/*
15523 	 * backward space of file filemark (1/2" and 8mm)
15524 	 * tape position will end on the beginning of tape side
15525 	 * of the desired file mark
15526 	 */
15527 	if ((un->un_dp->options & ST_BSF) == 0) {
15528 		return (ENOTTY);
15529 	}
15530 
15531 	if (un->un_pos.pmode == legacy) {
15532 
15533 		/*
15534 		 * If a negative count (which implies a forward space op)
15535 		 * is specified, and we're at logical or physical eot,
15536 		 * bounce the request.
15537 		 */
15538 
15539 		if (un->un_pos.eof >= ST_EOT && files < 0) {
15540 			un->un_err_resid = files;
15541 			un->un_status = SUN_KEY_EOT;
15542 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15543 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
15544 			return (EIO);
15545 		}
15546 		/*
15547 		 * physical tape position may not be what we've been
15548 		 * telling the user; adjust the request accordingly
15549 		 */
15550 		if (IN_EOF(un->un_pos)) {
15551 			un->un_pos.fileno++;
15552 			un->un_pos.blkno = 0;
15553 			files++;
15554 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15555 			    "st_mtbsf_ioctl in eof: count=%"PRIx64", op=%x\n",
15556 			    files, MTBSF);
15557 
15558 		}
15559 	}
15560 
15561 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15562 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15563 		    "st_ioctl : EIO : MTBSF : check den wfm");
15564 		return (EIO);
15565 	}
15566 
15567 	if (files <= 0) {
15568 		/*
15569 		 * for a negative count, we need to step forward
15570 		 * first and then step back again
15571 		 */
15572 		files = -files + 1;
15573 		return (st_forward_space_files(un, files));
15574 	}
15575 	return (st_backward_space_files(un, files, 1));
15576 }
15577 
15578 static int
15579 st_backward_space_files(struct scsi_tape *un, int64_t count, int infront)
15580 {
15581 	int64_t end_fileno;
15582 	int64_t skip_cnt;
15583 	int rval = 0;
15584 
15585 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
15586 
15587 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15588 	    "st_backward_space_files: count=%"PRIx64" eof=%x\n",
15589 	    count, un->un_pos.eof);
15590 	/*
15591 	 * Backspace files (MTNBSF): infront == 0
15592 	 *
15593 	 *	For tapes that can backspace, backspace
15594 	 *	count+1 filemarks and then run forward over
15595 	 *	a filemark
15596 	 *
15597 	 *	For tapes that can't backspace,
15598 	 *		calculate desired filenumber
15599 	 *		(un->un_pos.fileno - count), rewind,
15600 	 *		and then space forward this amount
15601 	 *
15602 	 * Backspace filemarks (MTBSF) infront == 1
15603 	 *
15604 	 *	For tapes that can backspace, backspace count
15605 	 *	filemarks
15606 	 *
15607 	 *	For tapes that can't backspace, calculate
15608 	 *	desired filenumber (un->un_pos.fileno - count),
15609 	 *	add 1, rewind, space forward this amount,
15610 	 *	and mark state as ST_EOF_PENDING appropriately.
15611 	 */
15612 
15613 	if (un->un_pos.pmode == logical) {
15614 
15615 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15616 		    "st_backward_space_files: mt_op=%x count=%"PRIx64
15617 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
15618 		    un->un_pos.lgclblkno);
15619 
15620 
15621 		/* In case a drive that won't back space gets in logical mode */
15622 		if ((un->un_dp->options & ST_BSF) == 0) {
15623 			rval = EIO;
15624 			return (rval);
15625 		}
15626 		if ((infront == 1) &&
15627 		    (st_cmd(un, SCMD_SPACE, Fmk(-count), SYNC_CMD))) {
15628 			rval = EIO;
15629 			return (rval);
15630 		} else if ((infront == 0) &&
15631 		    (st_cmd(un, SCMD_SPACE, Fmk((-count)-1), SYNC_CMD)) &&
15632 		    (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
15633 			rval = EIO;
15634 			return (rval);
15635 		}
15636 		return (rval);
15637 	}
15638 
15639 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15640 	    "st_backward_space_files: mt_op=%x count=%"PRIx64
15641 	    "fileno=%x blkno=%x\n",
15642 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
15643 
15644 
15645 
15646 	/*
15647 	 * Handle the simple case of BOT
15648 	 * playing a role in these cmds.
15649 	 * We do this by calculating the
15650 	 * ending file number. If the ending
15651 	 * file is < BOT, rewind and set an
15652 	 * error and mark resid appropriately.
15653 	 * If we're backspacing a file (not a
15654 	 * filemark) and the target file is
15655 	 * the first file on the tape, just
15656 	 * rewind.
15657 	 */
15658 
15659 	/* figure expected destination of this SPACE command */
15660 	end_fileno = un->un_pos.fileno - count;
15661 
15662 	/*
15663 	 * Would the end effect of this SPACE be the same as rewinding?
15664 	 * If so just rewind instead.
15665 	 */
15666 	if ((infront != 0) && (end_fileno < 0) ||
15667 	    (infront == 0) && (end_fileno <= 0)) {
15668 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15669 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15670 			    "st_backward_space_files: EIO : "
15671 			    "rewind in lou of BSF failed\n");
15672 			rval = EIO;
15673 		}
15674 		if (end_fileno < 0) {
15675 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15676 			    "st_backward_space_files: EIO : "
15677 			    "back space file greater then fileno\n");
15678 			rval = EIO;
15679 			un->un_err_resid = -end_fileno;
15680 			un->un_status = SUN_KEY_BOT;
15681 		}
15682 		return (rval);
15683 	}
15684 
15685 	if (un->un_dp->options & ST_BSF) {
15686 		skip_cnt = 1 - infront;
15687 		/*
15688 		 * If we are going to end up at the beginning
15689 		 * of the file, we have to space one extra file
15690 		 * first, and then space forward later.
15691 		 */
15692 		end_fileno = -(count + skip_cnt);
15693 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15694 		    "skip_cnt=%"PRIx64", tmp=%"PRIx64"\n",
15695 		    skip_cnt, end_fileno);
15696 		if (st_cmd(un, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
15697 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15698 			    "st_backward_space_files:EIO:back space fm failed");
15699 			rval = EIO;
15700 		}
15701 	} else {
15702 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15703 			rval = EIO;
15704 		} else {
15705 			skip_cnt = end_fileno + infront;
15706 		}
15707 	}
15708 
15709 	/*
15710 	 * If we have to space forward, do so...
15711 	 */
15712 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15713 	    "space forward skip_cnt=%"PRIx64", rval=%x\n", skip_cnt, rval);
15714 
15715 	if (rval == 0 && skip_cnt) {
15716 		if (st_cmd(un, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
15717 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15718 			    "st_backward_space_files:EIO:space fm skip count");
15719 			rval = EIO;
15720 		} else if (infront) {
15721 			/*
15722 			 * If we had to space forward, and we're
15723 			 * not a tape that can backspace, mark state
15724 			 * as if we'd just seen a filemark during a
15725 			 * a read.
15726 			 */
15727 			if ((un->un_dp->options & ST_BSF) == 0) {
15728 				un->un_pos.eof = ST_EOF_PENDING;
15729 				un->un_pos.fileno -= 1;
15730 				un->un_pos.blkno = LASTBLK;
15731 				un->un_running.pmode = invalid;
15732 			}
15733 		}
15734 	}
15735 
15736 	if (rval != 0) {
15737 		un->un_pos.pmode = invalid;
15738 	}
15739 
15740 	return (rval);
15741 }
15742 
15743 static int
15744 st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count)
15745 {
15746 	int rval;
15747 
15748 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
15749 
15750 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15751 	    "nbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15752 
15753 	if (un->un_pos.pmode == legacy) {
15754 		/*
15755 		 * backward space file to beginning of file
15756 		 *
15757 		 * If a negative count (which implies a forward space op)
15758 		 * is specified, and we're at logical or physical eot,
15759 		 * bounce the request.
15760 		 */
15761 
15762 		if (un->un_pos.eof >= ST_EOT && count < 0) {
15763 			un->un_err_resid = count;
15764 			un->un_status = SUN_KEY_EOT;
15765 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15766 			    "st_ioctl : EIO : > EOT and count < 0");
15767 			return (EIO);
15768 		}
15769 		/*
15770 		 * physical tape position may not be what we've been
15771 		 * telling the user; adjust the request accordingly
15772 		 */
15773 		if (IN_EOF(un->un_pos)) {
15774 			un->un_pos.fileno++;
15775 			un->un_pos.blkno = 0;
15776 			count++;
15777 		}
15778 	}
15779 
15780 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15781 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15782 		    "st_ioctl : EIO : MTNBSF check den and wfm");
15783 		return (EIO);
15784 	}
15785 
15786 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15787 	    "mtnbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15788 
15789 	if (count <= 0) {
15790 		rval = st_forward_space_files(un, -count);
15791 	} else {
15792 		rval = st_backward_space_files(un, count, 0);
15793 	}
15794 	return (rval);
15795 }
15796 
15797 static int
15798 st_mtbsr_ioctl(struct scsi_tape *un, int64_t num)
15799 {
15800 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
15801 
15802 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15803 	    "bsr: count=%"PRIx64", eof=%x\n", num, un->un_pos.eof);
15804 
15805 	if (un->un_pos.pmode == legacy) {
15806 		/*
15807 		 * backward space into inter-record gap
15808 		 *
15809 		 * If a negative count (which implies a forward space op)
15810 		 * is specified, and we're at logical or physical eot,
15811 		 * bounce the request.
15812 		 */
15813 		if (un->un_pos.eof >= ST_EOT && num < 0) {
15814 			un->un_err_resid = num;
15815 			un->un_status = SUN_KEY_EOT;
15816 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15817 			    "st_ioctl : EIO : MTBSR > EOT");
15818 			return (EIO);
15819 		}
15820 
15821 		if (num == 0) {
15822 			COPY_POS(&un->un_err_pos, &un->un_pos);
15823 			un->un_err_resid = 0;
15824 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15825 				un->un_status = SUN_KEY_EOF;
15826 			}
15827 			return (0);
15828 		}
15829 
15830 		/*
15831 		 * physical tape position may not be what we've been
15832 		 * telling the user; adjust the position accordingly.
15833 		 * bsr can not skip filemarks and continue to skip records
15834 		 * therefore if we are logically before the filemark but
15835 		 * physically at the EOT side of the filemark, we need to step
15836 		 * back; this allows fsr N where N > number of blocks in file
15837 		 * followed by bsr 1 to position at the beginning of last block
15838 		 */
15839 		if (IN_EOF(un->un_pos)) {
15840 			tapepos_t save;
15841 			optype lastop = un->un_lastop;
15842 
15843 			COPY_POS(&save, &un->un_pos);
15844 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD) == -1) {
15845 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15846 				    "st_mtbsr_ioctl: EIO : MTBSR can't space");
15847 				return (EIO);
15848 			}
15849 
15850 			COPY_POS(&un->un_pos, &save);
15851 			un->un_lastop = lastop;
15852 		}
15853 	}
15854 
15855 	un->un_pos.eof = ST_NO_EOF;
15856 
15857 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15858 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15859 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
15860 		return (EIO);
15861 	}
15862 
15863 	num = -num;
15864 	return (st_space_records(un, num));
15865 }
15866 
15867 static int
15868 st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt)
15869 {
15870 	int rval;
15871 
15872 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
15873 
15874 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
15875 	if (rval == 0) {
15876 		un->un_pos.pmode = logical;
15877 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15878 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15879 		/*
15880 		 * Drive says invalid field in cdb.
15881 		 * Doesn't like space multiple. Position isn't lost.
15882 		 */
15883 		un->un_err_resid = cnt;
15884 		un->un_status = 0;
15885 		rval = ENOTTY;
15886 	} else {
15887 		un->un_err_resid = cnt;
15888 		un->un_pos.pmode = invalid;
15889 	}
15890 	return (rval);
15891 }
15892 
15893 static int
15894 st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt)
15895 {
15896 	int rval;
15897 
15898 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
15899 
15900 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
15901 	if (rval == 0) {
15902 		un->un_pos.pmode = logical;
15903 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15904 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15905 		/*
15906 		 * Drive says invalid field in cdb.
15907 		 * Doesn't like space multiple. Position isn't lost.
15908 		 */
15909 		un->un_err_resid = cnt;
15910 		un->un_status = 0;
15911 		rval = ENOTTY;
15912 	} else {
15913 		un->un_err_resid = cnt;
15914 		un->un_pos.pmode = invalid;
15915 	}
15916 	return (rval);
15917 }
15918 
15919 #ifdef	__x86
15920 
15921 /*
15922  * release contig_mem and wake up waiting thread, if any
15923  */
15924 static void
15925 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
15926 {
15927 	mutex_enter(ST_MUTEX);
15928 
15929 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
15930 
15931 	cp->cm_next = un->un_contig_mem;
15932 	un->un_contig_mem = cp;
15933 	un->un_contig_mem_available_num++;
15934 	cv_broadcast(&un->un_contig_mem_cv);
15935 
15936 	mutex_exit(ST_MUTEX);
15937 }
15938 
15939 /*
15940  * St_get_contig_mem will return a contig_mem if there is one available
15941  * in current system. Otherwise, it will try to alloc one, if the total
15942  * number of contig_mem is within st_max_contig_mem_num.
15943  * It will sleep, if allowed by caller or return NULL, if no contig_mem
15944  * is available for now.
15945  */
15946 static struct contig_mem *
15947 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
15948 {
15949 	size_t rlen;
15950 	struct contig_mem *cp = NULL;
15951 	ddi_acc_handle_t acc_hdl;
15952 	caddr_t addr;
15953 	int big_enough = 0;
15954 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
15955 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
15956 
15957 	/* Try to get one available contig_mem */
15958 	mutex_enter(ST_MUTEX);
15959 
15960 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
15961 
15962 	if (un->un_contig_mem_available_num > 0) {
15963 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15964 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
15965 		/*
15966 		 * we failed to get one. we're going to
15967 		 * alloc one more contig_mem for this I/O
15968 		 */
15969 		mutex_exit(ST_MUTEX);
15970 		cp = (struct contig_mem *)kmem_zalloc(
15971 		    sizeof (struct contig_mem) + biosize(),
15972 		    alloc_flags);
15973 		if (cp == NULL) {
15974 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15975 			    "alloc contig_mem failure\n");
15976 			return (NULL); /* cannot get one */
15977 		}
15978 		cp->cm_bp = (struct buf *)
15979 		    (((caddr_t)cp) + sizeof (struct contig_mem));
15980 		bioinit(cp->cm_bp);
15981 		mutex_enter(ST_MUTEX);
15982 		un->un_contig_mem_total_num++; /* one more available */
15983 	} else {
15984 		/*
15985 		 * we failed to get one and we're NOT allowed to
15986 		 * alloc more contig_mem
15987 		 */
15988 		if (alloc_flags == KM_SLEEP) {
15989 			while (un->un_contig_mem_available_num <= 0) {
15990 				cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
15991 			}
15992 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15993 		} else {
15994 			mutex_exit(ST_MUTEX);
15995 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15996 			    "alloc contig_mem failure\n");
15997 			return (NULL); /* cannot get one */
15998 		}
15999 	}
16000 	mutex_exit(ST_MUTEX);
16001 
16002 	/* We need to check if this block of mem is big enough for this I/O */
16003 	if (cp->cm_len < len) {
16004 		/* not big enough, need to alloc a new one */
16005 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
16006 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
16007 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
16008 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16009 			    "alloc contig_mem failure: not enough mem\n");
16010 			st_release_contig_mem(un, cp);
16011 			cp = NULL;
16012 		} else {
16013 			if (cp->cm_addr) {
16014 				/* release previous one before attach new one */
16015 				ddi_dma_mem_free(&cp->cm_acc_hdl);
16016 			}
16017 			mutex_enter(ST_MUTEX);
16018 			un->un_max_contig_mem_len =
16019 			    un->un_max_contig_mem_len >= len ?
16020 			    un->un_max_contig_mem_len : len;
16021 			mutex_exit(ST_MUTEX);
16022 
16023 			/* attach new mem to this cp */
16024 			cp->cm_addr = addr;
16025 			cp->cm_acc_hdl = acc_hdl;
16026 			cp->cm_len = len;
16027 
16028 			goto alloc_ok; /* get one usable cp */
16029 		}
16030 	} else {
16031 		goto alloc_ok; /* get one usable cp */
16032 	}
16033 
16034 	/* cannot find/alloc a usable cp, when we get here */
16035 
16036 	mutex_enter(ST_MUTEX);
16037 	if ((un->un_max_contig_mem_len < len) ||
16038 	    (alloc_flags != KM_SLEEP)) {
16039 		mutex_exit(ST_MUTEX);
16040 		return (NULL);
16041 	}
16042 
16043 	/*
16044 	 * we're allowed to sleep, and there is one big enough
16045 	 * contig mem in the system, which is currently in use,
16046 	 * wait for it...
16047 	 */
16048 	big_enough = 1;
16049 	do {
16050 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16051 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16052 	} while (cp == NULL);
16053 	mutex_exit(ST_MUTEX);
16054 
16055 	/* we get the big enough contig mem, finally */
16056 
16057 alloc_ok:
16058 	/* init bp attached to this cp */
16059 	bioreset(cp->cm_bp);
16060 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
16061 	cp->cm_bp->b_private = (void *)cp;
16062 
16063 	return (cp);
16064 }
16065 
16066 /*
16067  * this is the biodone func for the bp used in big block I/O
16068  */
16069 static int
16070 st_bigblk_xfer_done(struct buf *bp)
16071 {
16072 	struct contig_mem *cp;
16073 	struct buf *orig_bp;
16074 	int ioerr;
16075 	struct scsi_tape *un;
16076 
16077 	/* sanity check */
16078 	if (bp == NULL) {
16079 		return (DDI_FAILURE);
16080 	}
16081 
16082 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16083 	if (un == NULL) {
16084 		return (DDI_FAILURE);
16085 	}
16086 
16087 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
16088 
16089 	cp = (struct contig_mem *)bp->b_private;
16090 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
16091 	cp->cm_bp = bp;
16092 
16093 	/* special handling for special I/O */
16094 	if (cp->cm_use_sbuf) {
16095 #ifndef __lock_lint
16096 		ASSERT(un->un_sbuf_busy);
16097 #endif
16098 		un->un_sbufp = orig_bp;
16099 		cp->cm_use_sbuf = 0;
16100 	}
16101 
16102 	orig_bp->b_resid = bp->b_resid;
16103 	ioerr = geterror(bp);
16104 	if (ioerr != 0) {
16105 		bioerror(orig_bp, ioerr);
16106 	} else if (orig_bp->b_flags & B_READ) {
16107 		/* copy data back to original bp */
16108 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
16109 		    bp->b_bcount - bp->b_resid);
16110 	}
16111 
16112 	st_release_contig_mem(un, cp);
16113 
16114 	biodone(orig_bp);
16115 
16116 	return (DDI_SUCCESS);
16117 }
16118 
16119 /*
16120  * We use this func to replace original bp that may not be able to do I/O
16121  * in big block size with one that can
16122  */
16123 static struct buf *
16124 st_get_bigblk_bp(struct buf *bp)
16125 {
16126 	struct contig_mem *cp;
16127 	struct scsi_tape *un;
16128 	struct buf *cont_bp;
16129 
16130 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16131 	if (un == NULL) {
16132 		return (bp);
16133 	}
16134 
16135 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
16136 
16137 	/* try to get one contig_mem */
16138 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
16139 	if (!cp) {
16140 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
16141 		    "Cannot alloc contig buf for I/O for %lu blk size",
16142 		    bp->b_bcount);
16143 		return (bp);
16144 	}
16145 	cont_bp = cp->cm_bp;
16146 	cp->cm_bp = bp;
16147 
16148 	/* make sure that we "are" using un_sbufp for special I/O */
16149 	if (bp == un->un_sbufp) {
16150 #ifndef __lock_lint
16151 		ASSERT(un->un_sbuf_busy);
16152 #endif
16153 		un->un_sbufp = cont_bp;
16154 		cp->cm_use_sbuf = 1;
16155 	}
16156 
16157 	/* clone bp */
16158 	cont_bp->b_bcount = bp->b_bcount;
16159 	cont_bp->b_resid = bp->b_resid;
16160 	cont_bp->b_iodone = st_bigblk_xfer_done;
16161 	cont_bp->b_file = bp->b_file;
16162 	cont_bp->b_offset = bp->b_offset;
16163 	cont_bp->b_dip = bp->b_dip;
16164 	cont_bp->b_error = 0;
16165 	cont_bp->b_proc = NULL;
16166 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
16167 	cont_bp->b_shadow = NULL;
16168 	cont_bp->b_pages = NULL;
16169 	cont_bp->b_edev = bp->b_edev;
16170 	cont_bp->b_dev = bp->b_dev;
16171 	cont_bp->b_lblkno = bp->b_lblkno;
16172 	cont_bp->b_forw = bp->b_forw;
16173 	cont_bp->b_back = bp->b_back;
16174 	cont_bp->av_forw = bp->av_forw;
16175 	cont_bp->av_back = bp->av_back;
16176 	cont_bp->b_bufsize = bp->b_bufsize;
16177 
16178 	/* get data in original bp */
16179 	if (bp->b_flags & B_WRITE) {
16180 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
16181 	}
16182 
16183 	return (cont_bp);
16184 }
16185 #else
16186 #ifdef __lock_lint
16187 static int
16188 st_bigblk_xfer_done(struct buf *bp)
16189 {
16190 	return (0);
16191 }
16192 #endif
16193 #endif
16194 
16195 static const char *eof_status[] =
16196 {
16197 	"NO_EOF",
16198 	"EOF_PENDING",
16199 	"EOF",
16200 	"EOT_PENDING",
16201 	"EOT",
16202 	"EOM",
16203 	"AFTER_EOM"
16204 };
16205 static const char *mode[] = {
16206 	"invalid",
16207 	"legacy",
16208 	"logical"
16209 };
16210 
16211 static void
16212 st_print_position(dev_info_t *dev, char *label, uint_t level,
16213 const char *comment, tapepos_t *pos)
16214 {
16215 	ST_FUNC(dev, st_print_position);
16216 
16217 	scsi_log(dev, label, level,
16218 	    "%s Position data:\n", comment);
16219 	scsi_log(dev, label, CE_CONT,
16220 	    "Positioning mode = %s", mode[pos->pmode]);
16221 	scsi_log(dev, label, CE_CONT,
16222 	    "End Of File/Tape = %s", eof_status[pos->eof]);
16223 	scsi_log(dev, label, CE_CONT,
16224 	    "File Number      = 0x%x", pos->fileno);
16225 	scsi_log(dev, label, CE_CONT,
16226 	    "Block Number     = 0x%x", pos->blkno);
16227 	scsi_log(dev, label, CE_CONT,
16228 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
16229 	scsi_log(dev, label, CE_CONT,
16230 	    "Partition Number = 0x%x", pos->partition);
16231 }
16232 static int
16233 st_check_if_media_changed(struct scsi_tape *un, caddr_t data, int size)
16234 {
16235 
16236 	int result = 0;
16237 	int i;
16238 	ST_FUNC(ST_DEVINFO, st_check_if_media_changed);
16239 
16240 	/*
16241 	 * find non alpha numeric working from the end.
16242 	 */
16243 	for (i = size - 1; i; i--) {
16244 		if (ISALNUM(data[i]) == 0 || data[i] == ' ') {
16245 			data[i] = 0;
16246 			size = i;
16247 		}
16248 	}
16249 
16250 	if (size == 1) {
16251 		/*
16252 		 * Drive seems to think its returning useful data
16253 		 * but it looks like all junk
16254 		 */
16255 		return (result);
16256 	}
16257 
16258 	size++;
16259 
16260 	/*
16261 	 * Actually got a valid serial number.
16262 	 * If never stored one before alloc space for it.
16263 	 */
16264 	if (un->un_media_id_len == 0) {
16265 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16266 		un->un_media_id_len = size;
16267 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16268 		un->un_media_id[min(size, strlen(data))] = 0;
16269 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16270 		    "Found Media Id %s length = %d\n", un->un_media_id, size);
16271 	} else if (size > un->un_media_id_len) {
16272 		if (strncmp(un->un_media_id, data, size) != 0) {
16273 			result = ESPIPE;
16274 		}
16275 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16276 		    "Longer Media Id old ID:%s new ID:%s\n",
16277 		    un->un_media_id, data);
16278 		kmem_free(un->un_media_id, un->un_media_id_len);
16279 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16280 		un->un_media_id_len = size;
16281 		(void) strncpy(un->un_media_id, data, size);
16282 		un->un_media_id[size] = 0;
16283 	} else if (strncmp(data, un->un_media_id,
16284 	    min(size, un->un_media_id_len)) != 0) {
16285 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16286 		    "Old Media Id %s length = %d New %s length = %d\n",
16287 		    un->un_media_id, un->un_media_id_len, data, size);
16288 		bzero(un->un_media_id, un->un_media_id_len);
16289 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16290 		un->un_media_id[min(size, strlen(data))] = 0;
16291 		result = ESPIPE;
16292 	} else {
16293 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
16294 		    "Media Id still %s\n", un->un_media_id);
16295 	}
16296 
16297 	ASSERT(strlen(un->un_media_id) <= size);
16298 
16299 	return (result);
16300 }
16301 #define	ID_SIZE 32
16302 typedef struct
16303 {
16304 	uchar_t avilable_data0;
16305 	uchar_t avilable_data1;
16306 	uchar_t avilable_data2;
16307 	uchar_t avilable_data3;
16308 	uchar_t attribute_msb;
16309 	uchar_t attribute_lsb;
16310 #ifdef _BIT_FIELDS_LTOH
16311 	uchar_t format		: 2,
16312 				: 5,
16313 		read_only	: 1;
16314 #else
16315 	uchar_t read_only	: 1,
16316 				: 5,
16317 		format		: 2;
16318 #endif
16319 	uchar_t attribute_len_msb;
16320 	uchar_t attribute_len_lsb;
16321 }attribute_header;
16322 
16323 typedef struct {
16324 	attribute_header header;
16325 	char data[1];
16326 }mam_attribute;
16327 
16328 static int
16329 st_handle_hex_media_id(struct scsi_tape *un, void *pnt, int size)
16330 {
16331 	int result;
16332 	int newsize = (size << 1) + 3; /* extra for leading 0x and null term */
16333 	int i;
16334 	uchar_t byte;
16335 	char *format;
16336 	uchar_t *data = (uchar_t *)pnt;
16337 	char *buf = kmem_alloc(newsize, KM_SLEEP);
16338 
16339 	ST_FUNC(ST_DEVINFO, st_handle_hex_media_id);
16340 
16341 	(void) sprintf(buf, "0x");
16342 	for (i = 0; i < size; i++) {
16343 		byte = data[i];
16344 		if (byte < 0x10)
16345 			format = "0%x";
16346 		else
16347 			format = "%x";
16348 		(void) sprintf(&buf[(int)strlen(buf)], format, byte);
16349 	}
16350 	result = st_check_if_media_changed(un, buf, newsize);
16351 
16352 	kmem_free(buf, newsize);
16353 
16354 	return (result);
16355 }
16356 
16357 
16358 static int
16359 st_get_media_id_via_read_attribute(struct scsi_tape *un, ubufunc_t bufunc)
16360 {
16361 	int result;
16362 	mam_attribute *buffer;
16363 	int size;
16364 	int newsize;
16365 
16366 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_read_attribute);
16367 	size = sizeof (attribute_header) + max(un->un_media_id_len, ID_SIZE);
16368 again:
16369 	buffer = kmem_zalloc(size, KM_SLEEP);
16370 	result = st_read_attributes(un, 0x0401, buffer, size, bufunc);
16371 	if (result == 0) {
16372 
16373 		newsize = (buffer->header.attribute_len_msb << 8) |
16374 		    buffer->header.attribute_len_lsb;
16375 
16376 		if (newsize + sizeof (attribute_header) > size) {
16377 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
16378 			    "resizing read attribute data from %d to %d format"
16379 			    " %d\n", size, (int)sizeof (attribute_header) +
16380 			    newsize, buffer->header.format);
16381 			kmem_free(buffer, size);
16382 			size = newsize + sizeof (attribute_header);
16383 			goto again;
16384 		}
16385 
16386 		un->un_media_id_method = st_get_media_id_via_read_attribute;
16387 		if (buffer->header.format == 0) {
16388 			result =
16389 			    st_handle_hex_media_id(un, buffer->data, newsize);
16390 		} else {
16391 			result = st_check_if_media_changed(un, buffer->data,
16392 			    newsize);
16393 		}
16394 	} else if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
16395 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
16396 		    "Read Attribute Command for Media Identification is not "
16397 		    "supported on the HBA that this drive is attached to.");
16398 		result = ENOTTY;
16399 	}
16400 
16401 	kmem_free(buffer, size);
16402 	un->un_status = 0;
16403 
16404 	return (result);
16405 }
16406 
16407 
16408 static int
16409 st_get_media_id_via_media_serial_cmd(struct scsi_tape *un, ubufunc_t bufunc)
16410 {
16411 	char cdb[CDB_GROUP5];
16412 	struct uscsi_cmd *ucmd;
16413 	struct scsi_extended_sense sense;
16414 	int rval;
16415 	int size = max(un->un_media_id_len, ID_SIZE);
16416 	caddr_t buf;
16417 
16418 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_media_serial_cmd);
16419 
16420 	if (un->un_sd->sd_inq->inq_ansi < 3) {
16421 		return (ENOTTY);
16422 	}
16423 
16424 	ucmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
16425 upsize:
16426 	buf = kmem_alloc(size, KM_SLEEP);
16427 
16428 	cdb[0] = (char)SCMD_SVC_ACTION_IN_G5;
16429 	cdb[1] = SSVC_ACTION_READ_MEDIA_SERIAL;
16430 	cdb[2] = 0;
16431 	cdb[3] = 0;
16432 	cdb[4] = 0;
16433 	cdb[5] = 0;
16434 	cdb[6] = (char)(size >> 24);
16435 	cdb[7] = (char)(size >> 16);
16436 	cdb[8] = (char)(size >> 8);
16437 	cdb[9] = (char)(size);
16438 	cdb[10] = 0;
16439 	cdb[11] = 0;
16440 
16441 	ucmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
16442 	ucmd->uscsi_timeout = un->un_dp->non_motion_timeout;
16443 	ucmd->uscsi_cdb = &cdb[0];
16444 	ucmd->uscsi_cdblen = sizeof (cdb);
16445 	ucmd->uscsi_bufaddr = buf;
16446 	ucmd->uscsi_buflen = size;
16447 	ucmd->uscsi_rqbuf = (caddr_t)&sense;
16448 	ucmd->uscsi_rqlen = sizeof (sense);
16449 
16450 	rval = bufunc(un, ucmd, FKIOCTL);
16451 
16452 	if (rval || ucmd->uscsi_status != 0) {
16453 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16454 		    "media serial command returned %d scsi_status %d"
16455 		    " rqstatus %d", rval, ucmd->uscsi_status,
16456 		    ucmd->uscsi_rqstatus);
16457 		/*
16458 		 * If this returns invalid operation code don't try again.
16459 		 */
16460 		if (sense.es_key == KEY_ILLEGAL_REQUEST &&
16461 		    sense.es_add_code == 0x20) {
16462 			rval = ENOTTY;
16463 		} else if (rval == 0) {
16464 			rval = EIO;
16465 		}
16466 		un->un_status = 0;
16467 	} else {
16468 		int act_size;
16469 
16470 		/*
16471 		 * get reported size.
16472 		 */
16473 		act_size = (int)buf[3] | (int)(buf[2] << 8) |
16474 		    (int)(buf[1] << 16) | (int)(buf[0] << 24);
16475 
16476 		/* documentation says mod 4. */
16477 		while (act_size & 3) {
16478 			act_size++;
16479 		}
16480 
16481 		/*
16482 		 * If reported size is larger that we our buffer.
16483 		 * Free the old one and allocate one that is larger
16484 		 * enough and re-issuse the command.
16485 		 */
16486 		if (act_size + 4 > size) {
16487 			kmem_free(buf, size);
16488 			size = act_size + 4;
16489 			goto upsize;
16490 		}
16491 
16492 		/*
16493 		 * set data pointer to point to the start of that serial number.
16494 		 */
16495 		un->un_media_id_method = st_get_media_id_via_media_serial_cmd;
16496 		rval = st_check_if_media_changed(un, &buf[4], act_size);
16497 	}
16498 
16499 	kmem_free(ucmd, sizeof (struct uscsi_cmd));
16500 	kmem_free(buf, size);
16501 
16502 	return (rval);
16503 }
16504 
16505 
16506 /* ARGSUSED */
16507 static int
16508 st_bogus_media_id(struct scsi_tape *un, ubufunc_t bufunc)
16509 {
16510 	ST_FUNC(ST_DEVINFO, st_bogus_media_id);
16511 
16512 	ASSERT(un->un_media_id == NULL || un->un_media_id == bogusID);
16513 	ASSERT(un->un_media_id_len == 0);
16514 	un->un_media_id = (char *)bogusID;
16515 	un->un_media_id_len = 0;
16516 	return (0);
16517 }
16518 
16519 typedef int (*media_chk_function)(struct scsi_tape *, ubufunc_t bufunc);
16520 
16521 media_chk_function media_chk_functions[] = {
16522 	st_get_media_id_via_media_serial_cmd,
16523 	st_get_media_id_via_read_attribute,
16524 	st_bogus_media_id
16525 };
16526 
16527 static int
16528 st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc)
16529 {
16530 	int result = 0;
16531 	int i;
16532 
16533 	ST_FUNC(ST_DEVINFO, st_get_media_identification);
16534 
16535 	for (i = 0; i < ST_NUM_MEMBERS(media_chk_functions); i++) {
16536 		if (result == ENOTTY) {
16537 			/*
16538 			 * Last operation type not supported by this device.
16539 			 * Make so next time it doesn`t do that again.
16540 			 */
16541 			un->un_media_id_method = media_chk_functions[i];
16542 		} else if (un->un_media_id_method != media_chk_functions[i] &&
16543 		    un->un_media_id_method != st_get_media_identification) {
16544 			continue;
16545 		}
16546 		result = media_chk_functions[i](un, bufunc);
16547 		/*
16548 		 * If result indicates the function was successful or
16549 		 * that the media is not the same as last known, break.
16550 		 */
16551 		if (result == 0 || result == ESPIPE) {
16552 			break;
16553 		}
16554 	}
16555 
16556 	return (result);
16557 }
16558 
16559 static errstate
16560 st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
16561     errstate onentry)
16562 {
16563 
16564 	int ret;
16565 	st_err_info *errinfo;
16566 	recov_info *ri = (recov_info *)pkt->pkt_private;
16567 
16568 	ST_FUNC(ST_DEVINFO, st_command_recovery);
16569 
16570 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16571 
16572 	ASSERT(un->un_recov_buf_busy == 0);
16573 
16574 	/*
16575 	 * Don't try and recover a reset that this device sent.
16576 	 */
16577 	if (un->un_rsvd_status & ST_INITIATED_RESET &&
16578 	    onentry == DEVICE_RESET) {
16579 		return (COMMAND_DONE_ERROR);
16580 	}
16581 
16582 	/*
16583 	 * See if expected position was passed with scsi_pkt.
16584 	 */
16585 	if (ri->privatelen == sizeof (recov_info)) {
16586 
16587 		/*
16588 		 * Not for this command.
16589 		 */
16590 		if (ri->cmd_attrib->do_not_recover) {
16591 			return (COMMAND_DONE_ERROR);
16592 		}
16593 
16594 		/*
16595 		 * Create structure to hold all error state info.
16596 		 */
16597 		errinfo = kmem_zalloc(ST_ERR_INFO_SIZE, KM_SLEEP);
16598 		errinfo->ei_error_type = onentry;
16599 		errinfo->ei_failing_bp = ri->cmd_bp;
16600 		COPY_POS(&errinfo->ei_expected_pos, &ri->pos);
16601 	} else {
16602 		/* disabled */
16603 		return (COMMAND_DONE_ERROR);
16604 	}
16605 
16606 	bcopy(pkt, &errinfo->ei_failed_pkt, scsi_pkt_size());
16607 	bcopy(pkt->pkt_scbp, &errinfo->ei_failing_status, SECMDS_STATUS_SIZE);
16608 	ret = ddi_taskq_dispatch(un->un_recov_taskq, st_recover, errinfo,
16609 	    DDI_NOSLEEP);
16610 	ASSERT(ret == DDI_SUCCESS);
16611 	if (ret != DDI_SUCCESS) {
16612 		kmem_free(errinfo, ST_ERR_INFO_SIZE);
16613 		return (COMMAND_DONE_ERROR);
16614 	}
16615 	return (JUST_RETURN); /* release calling thread */
16616 }
16617 
16618 
16619 static void
16620 st_recov_ret(struct scsi_tape *un, st_err_info *errinfo, errstate err)
16621 {
16622 	int error_number;
16623 	buf_t *bp;
16624 
16625 
16626 	ST_FUNC(ST_DEVINFO, st_recov_ret);
16627 
16628 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16629 #if !defined(lint)
16630 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
16631 #endif
16632 
16633 	bp = errinfo->ei_failing_bp;
16634 	kmem_free(errinfo, ST_ERR_INFO_SIZE);
16635 
16636 	switch (err) {
16637 	case JUST_RETURN:
16638 		mutex_exit(&un->un_sd->sd_mutex);
16639 		return;
16640 
16641 	case COMMAND_DONE:
16642 	case COMMAND_DONE_ERROR_RECOVERED:
16643 		ST_DO_KSTATS(bp, kstat_runq_exit);
16644 		error_number = 0;
16645 		break;
16646 
16647 	default:
16648 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16649 		    "st_recov_ret with unhandled errstat %d\n", err);
16650 		/* FALLTHROUGH */
16651 	case COMMAND_DONE_ERROR:
16652 	case COMMAND_DONE_EACCES:
16653 		ST_DO_KSTATS(bp, kstat_waitq_exit);
16654 		ST_DO_ERRSTATS(un, st_transerrs);
16655 		error_number = EIO;
16656 		st_set_pe_flag(un);
16657 		break;
16658 
16659 	}
16660 
16661 	st_bioerror(bp, error_number);
16662 	st_done_and_mutex_exit(un, bp);
16663 }
16664 
16665 
16666 static void
16667 st_recover(void *arg)
16668 {
16669 	st_err_info *const errinfo = (st_err_info *)arg;
16670 	uchar_t com = errinfo->ei_failed_pkt.pkt_cdbp[0];
16671 	struct scsi_tape *un;
16672 	tapepos_t cur_pos;
16673 	int rval;
16674 	errstate status = COMMAND_DONE_ERROR;
16675 	recov_info *rcv;
16676 	buf_t *bp;
16677 
16678 
16679 	rcv = errinfo->ei_failed_pkt.pkt_private;
16680 	ASSERT(rcv->privatelen == sizeof (recov_info));
16681 	bp = rcv->cmd_bp;
16682 
16683 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16684 
16685 	ASSERT(un != NULL);
16686 
16687 	mutex_enter(ST_MUTEX);
16688 
16689 	ST_FUNC(ST_DEVINFO, st_recover);
16690 
16691 	ST_CDB(ST_DEVINFO, "Recovering command",
16692 	    (caddr_t)errinfo->ei_failed_pkt.pkt_cdbp);
16693 	ST_SENSE(ST_DEVINFO, "sense status for failed command",
16694 	    (caddr_t)&errinfo->ei_failing_status,
16695 	    sizeof (struct scsi_arq_status));
16696 	ST_POS(ST_DEVINFO, rcv->cmd_attrib->recov_pos_type == POS_STARTING ?
16697 	    "starting position for recovery command" :
16698 	    "expected position for recovery command",
16699 	    &errinfo->ei_expected_pos);
16700 
16701 	rval = st_test_path_to_device(un);
16702 
16703 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16704 	    "st_recover called with %s, TUR returned %d\n",
16705 	    errstatenames[errinfo->ei_error_type], rval);
16706 	/*
16707 	 * If the drive responed to the TUR lets try and get it to sync
16708 	 * any data it might have in the buffer.
16709 	 */
16710 	if (rval == 0 && rcv->cmd_attrib->chg_tape_data) {
16711 		(void) st_rcmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
16712 	}
16713 	switch (errinfo->ei_error_type) {
16714 	case ATTEMPT_RETRY:
16715 	case COMMAND_TIMEOUT:
16716 	case DEVICE_RESET:
16717 	case PATH_FAILED:
16718 		/*
16719 		 * For now if we can't talk to the device we are done.
16720 		 * If the drive is reserved we can try to get it back.
16721 		 */
16722 		if (rval != 0 && rval != EACCES) {
16723 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16724 			return;
16725 		}
16726 
16727 		/*
16728 		 * If scsi II lost reserve try and get it back.
16729 		 */
16730 		if ((((un->un_rsvd_status &
16731 		    (ST_LOST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
16732 		    ST_LOST_RESERVE)) &&
16733 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] != SCMD_RELEASE)) {
16734 			rval = st_reserve_release(un, ST_RESERVE,
16735 			    st_uscsi_rcmd);
16736 			if (rval != 0) {
16737 				if (st_take_ownership(un, st_uscsi_rcmd) != 0) {
16738 					st_recov_ret(un, errinfo,
16739 					    COMMAND_DONE_EACCES);
16740 					return;
16741 				}
16742 			}
16743 			un->un_rsvd_status |= ST_RESERVE;
16744 			un->un_rsvd_status &= ~(ST_RELEASE | ST_LOST_RESERVE |
16745 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
16746 		}
16747 		rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16748 		if (rval) {
16749 			rval = st_gen_mode_select(un, st_uscsi_rcmd,
16750 			    un->un_mspl, sizeof (struct seq_mode));
16751 		}
16752 		if (rval) {
16753 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16754 			return;
16755 		}
16756 		break;
16757 	case DEVICE_TAMPER:
16758 		/*
16759 		 * Check if the ASC/ASCQ says mode data has changed.
16760 		 */
16761 		if ((errinfo->ei_failing_status.sts_sensedata.es_add_code ==
16762 		    0x2a) &&
16763 		    (errinfo->ei_failing_status.sts_sensedata.es_qual_code ==
16764 		    0x01)) {
16765 			/*
16766 			 * See if mode sense changed.
16767 			 */
16768 			rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16769 			if (rval) {
16770 				/*
16771 				 * If so change it back.
16772 				 */
16773 				rval = st_gen_mode_select(un, st_uscsi_rcmd,
16774 				    un->un_mspl, sizeof (struct seq_mode));
16775 			}
16776 			if (rval) {
16777 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16778 				return;
16779 			}
16780 		}
16781 		/*
16782 		 * if we have a media id and its not bogus.
16783 		 * Check to see if it the same.
16784 		 */
16785 		if (un->un_media_id != NULL && un->un_media_id != bogusID) {
16786 			rval = st_get_media_identification(un, st_uscsi_rcmd);
16787 			if (rval == ESPIPE) {
16788 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16789 				return;
16790 			}
16791 		}
16792 		break;
16793 	default:
16794 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16795 		    "Unhandled error type %s in st_recover() 0x%x\n",
16796 		    errstatenames[errinfo->ei_error_type], com);
16797 	}
16798 
16799 	/*
16800 	 * if command is retriable retry it.
16801 	 * Special case here. The command attribute for SCMD_REQUEST_SENSE
16802 	 * does not say that it is retriable. That because if you reissue a
16803 	 * request sense and the target responds the sense data will have
16804 	 * been consumed and no long be valid. If we get a busy status on
16805 	 * request sense while the state is ST_STATE_SENSING this will
16806 	 * reissue that pkt.
16807 	 *
16808 	 * XXX If this request sense gets sent to a different port then
16809 	 * the original command that failed was sent on it will not get
16810 	 * valid sense data for that command.
16811 	 */
16812 	if (rcv->cmd_attrib->retriable || un->un_rqs_bp == bp) {
16813 		status = st_recover_reissue_pkt(un, &errinfo->ei_failed_pkt);
16814 
16815 	/*
16816 	 * if drive doesn't support read position we are done
16817 	 */
16818 	} else if (un->un_read_pos_type == NO_POS) {
16819 		status = COMMAND_DONE_ERROR;
16820 	/*
16821 	 * If this command results in a changed tape position,
16822 	 * lets see where we are.
16823 	 */
16824 	} else if (rcv->cmd_attrib->chg_tape_pos) {
16825 		/*
16826 		 * XXX May be a reason to choose a different type here.
16827 		 * Long format has file position information.
16828 		 * Short and Extended have information about whats
16829 		 * in the buffer. St's positioning assumes in the buffer
16830 		 * to be the same as on tape.
16831 		 */
16832 		rval = st_compare_expected_position(un, errinfo,
16833 		    rcv->cmd_attrib, &cur_pos);
16834 		if (rval == 0) {
16835 			status = COMMAND_DONE;
16836 		} else if (rval == EAGAIN) {
16837 			status = st_recover_reissue_pkt(un,
16838 			    &errinfo->ei_failed_pkt);
16839 		} else {
16840 			status = COMMAND_DONE_ERROR;
16841 		}
16842 	} else {
16843 		ASSERT(0);
16844 	}
16845 
16846 	st_recov_ret(un, errinfo, status);
16847 }
16848 
16849 static void
16850 st_recov_cb(struct scsi_pkt *pkt)
16851 {
16852 	struct scsi_tape *un;
16853 	struct buf *bp;
16854 	recov_info *rcv;
16855 	errstate action = COMMAND_DONE_ERROR;
16856 	int timout = ST_TRAN_BUSY_TIMEOUT; /* short (default) timeout */
16857 
16858 	/*
16859 	 * Get the buf from the packet.
16860 	 */
16861 	rcv = pkt->pkt_private;
16862 	ASSERT(rcv->privatelen == sizeof (recov_info));
16863 	bp = rcv->cmd_bp;
16864 
16865 	/*
16866 	 * get the unit from the buf.
16867 	 */
16868 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16869 	ASSERT(un != NULL);
16870 
16871 	ST_FUNC(ST_DEVINFO, st_recov_cb);
16872 
16873 	mutex_enter(ST_MUTEX);
16874 
16875 	ASSERT(bp == un->un_recov_buf);
16876 
16877 
16878 	switch (pkt->pkt_reason) {
16879 	case CMD_CMPLT:
16880 		if (un->un_arq_enabled && pkt->pkt_state & STATE_ARQ_DONE) {
16881 			action = st_handle_autosense(un, bp, &rcv->pos);
16882 		} else  if ((SCBP(pkt)->sts_busy) ||
16883 		    (SCBP(pkt)->sts_chk) ||
16884 		    (SCBP(pkt)->sts_vu7)) {
16885 			action = st_check_error(un, pkt);
16886 		} else {
16887 			action = COMMAND_DONE;
16888 		}
16889 		break;
16890 	case CMD_TIMEOUT:
16891 		action = COMMAND_TIMEOUT;
16892 		break;
16893 	case CMD_TRAN_ERR:
16894 		action = QUE_COMMAND;
16895 		break;
16896 	default:
16897 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16898 		    "pkt_reason not handled yet %s",
16899 		    scsi_rname(pkt->pkt_reason));
16900 		action = COMMAND_DONE_ERROR;
16901 	}
16902 
16903 	/*
16904 	 * check for undetected path failover.
16905 	 */
16906 	if ((un->un_multipath) &&
16907 	    (un->un_last_path_instance != pkt->pkt_path_instance)) {
16908 		if (un->un_state > ST_STATE_OPENING) {
16909 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16910 			    "Failover detected in recovery, action is %s\n",
16911 			    errstatenames[action]);
16912 		}
16913 		un->un_last_path_instance = pkt->pkt_path_instance;
16914 	}
16915 
16916 	ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
16917 	    "Recovery call back got %s status on %s\n",
16918 	    errstatenames[action], st_print_scsi_cmd(pkt->pkt_cdbp[0]));
16919 
16920 	switch (action) {
16921 	case COMMAND_DONE:
16922 		break;
16923 
16924 	case COMMAND_DONE_EACCES:
16925 		bioerror(bp, EACCES);
16926 		break;
16927 
16928 	case COMMAND_DONE_ERROR_RECOVERED: /* XXX maybe wrong */
16929 		ASSERT(0);
16930 		break;
16931 
16932 	case COMMAND_TIMEOUT:
16933 	case COMMAND_DONE_ERROR:
16934 		bioerror(bp, EIO);
16935 		break;
16936 
16937 	case DEVICE_RESET:
16938 	case QUE_BUSY_COMMAND:
16939 	case PATH_FAILED:
16940 		/* longish timeout */
16941 		timout = ST_STATUS_BUSY_TIMEOUT;
16942 		/* FALLTHRU */
16943 	case QUE_COMMAND:
16944 	case DEVICE_TAMPER:
16945 	case ATTEMPT_RETRY:
16946 		/*
16947 		 * let st_handle_intr_busy put this bp back on waitq and make
16948 		 * checks to see if it is ok to requeue the command.
16949 		 */
16950 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
16951 
16952 		/*
16953 		 * Save the throttle before setting up the timeout
16954 		 */
16955 		if (un->un_throttle) {
16956 			un->un_last_throttle = un->un_throttle;
16957 		}
16958 		mutex_exit(ST_MUTEX);
16959 		if (st_handle_intr_busy(un, bp, timout) == 0) {
16960 			return;		/* timeout is setup again */
16961 		}
16962 		mutex_enter(ST_MUTEX);
16963 		un->un_pos.pmode = invalid;
16964 		un->un_err_resid = bp->b_resid = bp->b_bcount;
16965 		st_bioerror(bp, EIO);
16966 		st_set_pe_flag(un);
16967 		break;
16968 
16969 	default:
16970 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16971 		    "Unhandled recovery state 0x%x\n", action);
16972 		un->un_pos.pmode = invalid;
16973 		un->un_err_resid = bp->b_resid = bp->b_bcount;
16974 		st_bioerror(bp, EIO);
16975 		st_set_pe_flag(un);
16976 		break;
16977 	}
16978 
16979 	st_done_and_mutex_exit(un, bp);
16980 }
16981 
16982 static int
16983 st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait)
16984 {
16985 	struct buf *bp;
16986 	int err;
16987 
16988 	ST_FUNC(ST_DEVINFO, st_rcmd);
16989 
16990 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16991 	    "st_rcmd(un = 0x%p, com = 0x%x, count = %"PRIx64", wait = %d)\n",
16992 	    (void *)un, com, count, wait);
16993 
16994 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16995 	ASSERT(mutex_owned(ST_MUTEX));
16996 
16997 #ifdef STDEBUG
16998 	if ((st_debug & 0x7)) {
16999 		st_debug_cmds(un, com, count, wait);
17000 	}
17001 #endif
17002 
17003 	while (un->un_recov_buf_busy)
17004 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17005 	un->un_recov_buf_busy = 1;
17006 
17007 	bp = un->un_recov_buf;
17008 	bzero(bp, sizeof (buf_t));
17009 
17010 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
17011 
17012 	err = st_setup_cmd(un, bp, com, count);
17013 
17014 	un->un_recov_buf_busy = 0;
17015 
17016 	cv_signal(&un->un_recov_buf_cv);
17017 
17018 	return (err);
17019 }
17020 
17021 /* args used */
17022 static int
17023 st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
17024 {
17025 	int rval;
17026 	buf_t *bp;
17027 
17028 	ST_FUNC(ST_DEVINFO, st_uscsi_rcmd);
17029 	ASSERT(flag == FKIOCTL);
17030 
17031 	/*
17032 	 * Get buffer resources...
17033 	 */
17034 	while (un->un_recov_buf_busy)
17035 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17036 	un->un_recov_buf_busy = 1;
17037 
17038 	bp = un->un_recov_buf;
17039 	bzero(bp, sizeof (buf_t));
17040 
17041 	bp->b_forw = (struct buf *)(uintptr_t)ucmd->uscsi_cdb[0];
17042 	bp->b_back = (struct buf *)ucmd;
17043 
17044 	mutex_exit(ST_MUTEX);
17045 	rval = scsi_uscsi_handle_cmd(un->un_dev, UIO_SYSSPACE, ucmd,
17046 	    st_strategy, bp, NULL);
17047 	mutex_enter(ST_MUTEX);
17048 
17049 	ucmd->uscsi_resid = bp->b_resid;
17050 
17051 	/*
17052 	 * Free resources
17053 	 */
17054 	un->un_recov_buf_busy = 0;
17055 	cv_signal(&un->un_recov_buf_cv);
17056 
17057 	return (rval);
17058 }
17059 
17060 /*
17061  * Add data to scsi_pkt to help know what to do if the command fails.
17062  */
17063 static void
17064 st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
17065     struct scsi_pkt *pkt)
17066 {
17067 	uint64_t count;
17068 	recov_info *rinfo = (recov_info *)pkt->pkt_private;
17069 
17070 	ST_FUNC(ST_DEVINFO, st_add_recovery_info_to_pkt);
17071 
17072 	ASSERT(rinfo->privatelen == sizeof (pkt_info) ||
17073 	    rinfo->privatelen == sizeof (recov_info));
17074 
17075 	SET_BP_PKT(bp, pkt);
17076 	rinfo->cmd_bp = bp;
17077 
17078 	if (rinfo->privatelen != sizeof (recov_info)) {
17079 		return;
17080 	}
17081 
17082 	rinfo->cmd_bp = bp;
17083 
17084 	rinfo->cmd_attrib = NULL;
17085 
17086 	/*
17087 	 * lookup the command attributes and add them to the recovery info.
17088 	 */
17089 	rinfo->cmd_attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
17090 
17091 	ASSERT(rinfo->cmd_attrib);
17092 
17093 	/*
17094 	 * For commands that there is no way to figure the expected position
17095 	 * once completed, we save the position the command was started from
17096 	 * so that if they fail we can position back and try again.
17097 	 * This has already been done in st_cmd() or st_iscsi_cmd().
17098 	 */
17099 	if (rinfo->cmd_attrib->recov_pos_type == POS_STARTING) {
17100 		/* save current position as the starting position. */
17101 		COPY_POS(&rinfo->pos, &un->un_pos);
17102 		un->un_running.pmode = invalid;
17103 		return;
17104 	}
17105 
17106 	/*
17107 	 * Don't want to update the running position for recovery.
17108 	 */
17109 	if (bp == un->un_recov_buf) {
17110 		rinfo->pos.pmode = un->un_running.pmode;
17111 		return;
17112 	}
17113 	/*
17114 	 * If running position is invalid copy the current position.
17115 	 * Running being set invalid means we are not in a read, write
17116 	 * or write filemark sequence.
17117 	 * We'll copy the current position and start from there.
17118 	 */
17119 	if (un->un_running.pmode == invalid) {
17120 		COPY_POS(&un->un_running, &un->un_pos);
17121 		COPY_POS(&rinfo->pos, &un->un_running);
17122 	} else {
17123 		COPY_POS(&rinfo->pos, &un->un_running);
17124 		if (rinfo->pos.pmode == legacy) {
17125 			/*
17126 			 * Always should be more logical blocks then
17127 			 * data blocks and files marks.
17128 			 */
17129 			ASSERT((rinfo->pos.blkno >= 0) ?
17130 			    rinfo->pos.lgclblkno >=
17131 			    (rinfo->pos.blkno + rinfo->pos.fileno) : 1);
17132 		}
17133 	}
17134 
17135 	/*
17136 	 * If the command is not expected to change the drive position
17137 	 * then the running position should be the expected position.
17138 	 */
17139 	if (rinfo->cmd_attrib->chg_tape_pos == 0) {
17140 		ASSERT(rinfo->cmd_attrib->chg_tape_direction == DIR_NONE);
17141 		return;
17142 	}
17143 
17144 	if (rinfo->cmd_attrib->explicit) {
17145 		ASSERT(rinfo->pos.pmode != invalid);
17146 		ASSERT(rinfo->cmd_attrib->get_cnt);
17147 		count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17148 		/*
17149 		 * This is a user generated CDB.
17150 		 */
17151 		if (bp == un->un_sbufp) {
17152 			uint64_t lbn;
17153 
17154 			lbn = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17155 
17156 			/*
17157 			 * See if this CDB will generate a locate or change
17158 			 * partition.
17159 			 */
17160 			if ((lbn != un->un_running.lgclblkno) ||
17161 			    (pkt->pkt_cdbp[3] != un->un_running.partition)) {
17162 				rinfo->pos.partition = pkt->pkt_cdbp[3];
17163 				rinfo->pos.pmode = logical;
17164 				rinfo->pos.lgclblkno = lbn;
17165 				un->un_running.partition = pkt->pkt_cdbp[3];
17166 				un->un_running.pmode = logical;
17167 				un->un_running.lgclblkno = lbn;
17168 			}
17169 		} else {
17170 			uint64_t lbn = un->un_running.lgclblkno;
17171 
17172 			pkt->pkt_cdbp[3]  = (uchar_t)un->un_running.partition;
17173 
17174 			pkt->pkt_cdbp[4]  = (uchar_t)(lbn >> 56);
17175 			pkt->pkt_cdbp[5]  = (uchar_t)(lbn >> 48);
17176 			pkt->pkt_cdbp[6]  = (uchar_t)(lbn >> 40);
17177 			pkt->pkt_cdbp[7]  = (uchar_t)(lbn >> 32);
17178 			pkt->pkt_cdbp[8]  = (uchar_t)(lbn >> 24);
17179 			pkt->pkt_cdbp[9]  = (uchar_t)(lbn >> 16);
17180 			pkt->pkt_cdbp[10] = (uchar_t)(lbn >> 8);
17181 			pkt->pkt_cdbp[11] = (uchar_t)(lbn);
17182 		}
17183 		rinfo->pos.lgclblkno += count;
17184 		rinfo->pos.blkno += count;
17185 		un->un_running.lgclblkno += count;
17186 		return;
17187 	}
17188 
17189 	if (rinfo->cmd_attrib->chg_tape_pos) {
17190 
17191 		/* should not have got an invalid position from running. */
17192 		if (un->un_mediastate == MTIO_INSERTED) {
17193 			ASSERT(rinfo->pos.pmode != invalid);
17194 		}
17195 
17196 		/* should have either a get count or or get lba function */
17197 		ASSERT(rinfo->cmd_attrib->get_cnt != NULL ||
17198 		    rinfo->cmd_attrib->get_lba != NULL);
17199 
17200 		/* only explicit commands have both and they're handled above */
17201 		ASSERT(!(rinfo->cmd_attrib->get_cnt != NULL &&
17202 		    rinfo->cmd_attrib->get_lba != NULL));
17203 
17204 		/* if it has a get count function */
17205 		if (rinfo->cmd_attrib->get_cnt != NULL) {
17206 			count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17207 			if (count == 0) {
17208 				return;
17209 			}
17210 			/*
17211 			 * Changes position but doesn't transfer data.
17212 			 * i.e. rewind, write_file_mark and load.
17213 			 */
17214 			if (rinfo->cmd_attrib->transfers_data == TRAN_NONE) {
17215 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17216 				case DIR_NONE: /* Erase */
17217 					ASSERT(rinfo->cmd_attrib->cmd ==
17218 					    SCMD_ERASE);
17219 					break;
17220 				case DIR_FORW: /* write_file_mark */
17221 					rinfo->pos.fileno += count;
17222 					rinfo->pos.lgclblkno += count;
17223 					rinfo->pos.blkno = 0;
17224 					un->un_running.fileno += count;
17225 					un->un_running.lgclblkno += count;
17226 					un->un_running.blkno = 0;
17227 					break;
17228 				case DIR_REVC: /* rewind */
17229 					rinfo->pos.fileno = 0;
17230 					rinfo->pos.lgclblkno = 0;
17231 					rinfo->pos.blkno = 0;
17232 					rinfo->pos.eof = ST_NO_EOF;
17233 					rinfo->pos.pmode = legacy;
17234 					un->un_running.fileno = 0;
17235 					un->un_running.lgclblkno = 0;
17236 					un->un_running.blkno = 0;
17237 					un->un_running.eof = ST_NO_EOF;
17238 					if (un->un_running.pmode != legacy)
17239 						un->un_running.pmode = legacy;
17240 					break;
17241 				case DIR_EITH: /* Load unload */
17242 					ASSERT(rinfo->cmd_attrib->cmd ==
17243 					    SCMD_LOAD);
17244 					switch (count & (LD_LOAD | LD_RETEN |
17245 					    LD_RETEN | LD_HOLD)) {
17246 					case LD_UNLOAD:
17247 					case LD_RETEN:
17248 					case LD_HOLD:
17249 					case LD_LOAD | LD_HOLD:
17250 					case LD_EOT | LD_HOLD:
17251 					case LD_RETEN | LD_HOLD:
17252 						rinfo->pos.pmode = invalid;
17253 						un->un_running.pmode = invalid;
17254 						break;
17255 					case LD_EOT:
17256 					case LD_LOAD | LD_EOT:
17257 						rinfo->pos.eof = ST_EOT;
17258 						rinfo->pos.pmode = invalid;
17259 						un->un_running.eof = ST_EOT;
17260 						un->un_running.pmode = invalid;
17261 						break;
17262 					case LD_LOAD:
17263 					case LD_RETEN | LD_LOAD:
17264 						rinfo->pos.fileno = 0;
17265 						rinfo->pos.lgclblkno = 0;
17266 						rinfo->pos.blkno = 0;
17267 						rinfo->pos.eof = ST_NO_EOF;
17268 						rinfo->pos.pmode = legacy;
17269 						un->un_running.fileno = 0;
17270 						un->un_running.lgclblkno = 0;
17271 						un->un_running.blkno = 0;
17272 						un->un_running.eof = ST_NO_EOF;
17273 						break;
17274 					default:
17275 						ASSERT(0);
17276 					}
17277 					break;
17278 				default:
17279 					ASSERT(0);
17280 					break;
17281 				}
17282 			} else {
17283 				/*
17284 				 * Changes position and does transfer data.
17285 				 * i.e. read or write.
17286 				 */
17287 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17288 				case DIR_FORW:
17289 					rinfo->pos.lgclblkno += count;
17290 					rinfo->pos.blkno += count;
17291 					un->un_running.lgclblkno += count;
17292 					un->un_running.blkno += count;
17293 					break;
17294 				case DIR_REVC:
17295 					rinfo->pos.lgclblkno -= count;
17296 					rinfo->pos.blkno -= count;
17297 					un->un_running.lgclblkno -= count;
17298 					un->un_running.blkno -= count;
17299 					break;
17300 				default:
17301 					ASSERT(0);
17302 					break;
17303 				}
17304 			}
17305 		} else if (rinfo->cmd_attrib->get_lba != NULL) {
17306 			/* Have a get LBA fuction. i.e. Locate */
17307 			ASSERT(rinfo->cmd_attrib->chg_tape_direction ==
17308 			    DIR_EITH);
17309 			count = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17310 			un->un_running.lgclblkno = count;
17311 			un->un_running.blkno = 0;
17312 			un->un_running.fileno = 0;
17313 			un->un_running.pmode = logical;
17314 			rinfo->pos.lgclblkno = count;
17315 			rinfo->pos.pmode = invalid;
17316 		} else {
17317 			ASSERT(0);
17318 		}
17319 		return;
17320 	}
17321 
17322 	ST_CDB(ST_DEVINFO, "Unhanded CDB for position prediction",
17323 	    (char *)pkt->pkt_cdbp);
17324 
17325 }
17326 
17327 static int
17328 st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf)
17329 {
17330 	struct seq_mode *current;
17331 	int rval;
17332 	int i;
17333 	caddr_t this;
17334 	caddr_t that;
17335 
17336 	ST_FUNC(ST_DEVINFO, st_check_mode_for_change);
17337 
17338 	/* recovery called with mode tamper before mode selection */
17339 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
17340 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17341 		    "Mode Select not done yet");
17342 		return (0);
17343 	}
17344 
17345 	current = kmem_zalloc(sizeof (struct seq_mode), KM_SLEEP);
17346 
17347 	rval = st_gen_mode_sense(un, ubf, un->un_comp_page, current,
17348 	    sizeof (struct seq_mode));
17349 	if (rval != 0) {
17350 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17351 		    "Mode Sense for mode verification failed");
17352 		kmem_free(current, sizeof (struct seq_mode));
17353 		return (rval);
17354 	}
17355 
17356 	this = (caddr_t)current;
17357 	that = (caddr_t)un->un_mspl;
17358 
17359 	rval = bcmp(this, that, sizeof (struct seq_mode));
17360 	if (rval == 0) {
17361 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17362 		    "Found no changes in mode data");
17363 	}
17364 #ifdef STDEBUG
17365 	else {
17366 		for (i = 1; i < sizeof (struct seq_mode); i++) {
17367 			if (this[i] != that[i]) {
17368 				ST_RECOV(ST_DEVINFO, st_label, CE_CONT,
17369 				    "sense data changed at byte %d was "
17370 				    "0x%x now 0x%x", i,
17371 				    (uchar_t)that[i], (uchar_t)this[i]);
17372 			}
17373 		}
17374 	}
17375 #endif
17376 	kmem_free(current, sizeof (struct seq_mode));
17377 
17378 	return (rval);
17379 }
17380 
17381 static int
17382 st_test_path_to_device(struct scsi_tape *un)
17383 {
17384 	int rval = 0;
17385 	int limit = st_retry_count;
17386 
17387 	ST_FUNC(ST_DEVINFO, st_test_path_to_device);
17388 
17389 	/*
17390 	 * XXX Newer drives may not RESEVATION CONFLICT a TUR.
17391 	 */
17392 	do {
17393 		if (rval != 0) {
17394 			mutex_exit(ST_MUTEX);
17395 			delay(drv_usectohz(1000000));
17396 			mutex_enter(ST_MUTEX);
17397 		}
17398 		rval = st_rcmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
17399 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17400 		    "ping TUR returned 0x%x", rval);
17401 		limit--;
17402 	} while (((rval == EACCES) || (rval == EBUSY)) && limit);
17403 
17404 	if (un->un_status == KEY_NOT_READY || un->un_mediastate == MTIO_EJECTED)
17405 		rval = 0;
17406 
17407 	return (rval);
17408 }
17409 
17410 /*
17411  * Does read position using recov_buf and doesn't update un_pos.
17412  * Does what ever kind of read position you want.
17413  */
17414 static int
17415 st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
17416     read_pos_data_t *raw)
17417 {
17418 	int rval;
17419 	struct uscsi_cmd cmd;
17420 	struct scsi_arq_status status;
17421 	char cdb[CDB_GROUP1];
17422 
17423 	ST_FUNC(ST_DEVINFO, st_recovery_read_pos);
17424 	bzero(&cmd, sizeof (cmd));
17425 
17426 	cdb[0] = SCMD_READ_POSITION;
17427 	cdb[1] = type;
17428 	cdb[2] = 0;
17429 	cdb[3] = 0;
17430 	cdb[4] = 0;
17431 	cdb[5] = 0;
17432 	cdb[6] = 0;
17433 	cdb[7] = 0;
17434 	cdb[8] = (type == EXT_POS) ? 28 : 0;
17435 	cdb[9] = 0;
17436 
17437 	cmd.uscsi_flags = USCSI_READ | USCSI_RQENABLE;
17438 	cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
17439 	cmd.uscsi_cdb = cdb;
17440 	cmd.uscsi_cdblen = sizeof (cdb);
17441 	cmd.uscsi_rqlen = sizeof (status);
17442 	cmd.uscsi_rqbuf = (caddr_t)&status;
17443 	cmd.uscsi_bufaddr = (caddr_t)raw;
17444 	switch (type) {
17445 	case SHORT_POS:
17446 		cmd.uscsi_buflen = sizeof (tape_position_t);
17447 		break;
17448 	case LONG_POS:
17449 		cmd.uscsi_buflen = sizeof (tape_position_long_t);
17450 		break;
17451 	case EXT_POS:
17452 		cmd.uscsi_buflen = sizeof (tape_position_ext_t);
17453 		break;
17454 	default:
17455 		ASSERT(0);
17456 	}
17457 
17458 	rval = st_uscsi_rcmd(un, &cmd, FKIOCTL);
17459 	if (cmd.uscsi_status) {
17460 		rval = EIO;
17461 	}
17462 	return (rval);
17463 }
17464 
17465 static int
17466 st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
17467     read_pos_data_t *raw)
17468 {
17469 	int rval;
17470 	read_p_types type = un->un_read_pos_type;
17471 
17472 	ST_FUNC(ST_DEVINFO, st_recovery_get_position);
17473 
17474 	do {
17475 		rval = st_recovery_read_pos(un, type, raw);
17476 		if (rval != 0) {
17477 			switch (type) {
17478 			case SHORT_POS:
17479 				type = NO_POS;
17480 				break;
17481 
17482 			case LONG_POS:
17483 				type = EXT_POS;
17484 				break;
17485 
17486 			case EXT_POS:
17487 				type = SHORT_POS;
17488 				break;
17489 
17490 			default:
17491 				type = LONG_POS;
17492 				break;
17493 
17494 			}
17495 		} else {
17496 			if (type != un->un_read_pos_type) {
17497 				un->un_read_pos_type = type;
17498 			}
17499 			break;
17500 		}
17501 	} while (type != NO_POS);
17502 
17503 	if (rval == 0) {
17504 		rval = st_interpret_read_pos(un, read, type,
17505 		    sizeof (read_pos_data_t), (caddr_t)raw, 1);
17506 	}
17507 	return (rval);
17508 }
17509 
17510 /*
17511  * based on the command do we retry, continue or give up?
17512  * possable return values?
17513  *	zero do nothing looks fine.
17514  *	EAGAIN retry.
17515  *	EIO failed makes no sense.
17516  */
17517 static int
17518 st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
17519     cmd_attribute const * cmd_att, tapepos_t *read)
17520 {
17521 	int rval;
17522 	read_pos_data_t *readp_datap;
17523 
17524 	ST_FUNC(ST_DEVINFO, st_compare_expected_position);
17525 
17526 	ASSERT(un != NULL);
17527 	ASSERT(ei != NULL);
17528 	ASSERT(read != NULL);
17529 	ASSERT(cmd_att->chg_tape_pos);
17530 
17531 	COPY_POS(read, &ei->ei_expected_pos);
17532 
17533 	readp_datap = kmem_zalloc(sizeof (read_pos_data_t), KM_SLEEP);
17534 
17535 	rval = st_recovery_get_position(un, read, readp_datap);
17536 
17537 	kmem_free(readp_datap, sizeof (read_pos_data_t));
17538 
17539 	if (rval != 0) {
17540 		return (EIO);
17541 	}
17542 
17543 	ST_POS(ST_DEVINFO, "st_compare_expected_position", read);
17544 
17545 	if ((read->pmode == invalid) ||
17546 	    (ei->ei_expected_pos.pmode == invalid)) {
17547 		return (EIO);
17548 	}
17549 
17550 	/*
17551 	 * Command that changes tape position and have an expected position
17552 	 * if it were to chave completed sucessfully.
17553 	 */
17554 	if (cmd_att->recov_pos_type == POS_EXPECTED) {
17555 		uint32_t count;
17556 		int64_t difference;
17557 		uchar_t reposition = 0;
17558 
17559 		ASSERT(cmd_att->get_cnt);
17560 		count = cmd_att->get_cnt(ei->ei_failed_pkt.pkt_cdbp);
17561 
17562 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17563 		    "Got count from CDB and it was %d\n", count);
17564 
17565 		/*
17566 		 * At expected?
17567 		 */
17568 		if (read->lgclblkno == ei->ei_expected_pos.lgclblkno) {
17569 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17570 			    "Found drive to be at expected position\n");
17571 
17572 			/*
17573 			 * If the command should move tape and it got a busy
17574 			 * it shouldn't be in the expected position.
17575 			 */
17576 			if (ei->ei_failing_status.sts_status.sts_busy != 0) {
17577 				reposition = 1;
17578 
17579 			/*
17580 			 * If the command doesn't transfer data should be good.
17581 			 */
17582 			} else if (cmd_att->transfers_data == TRAN_NONE) {
17583 				return (0); /* Good */
17584 
17585 			/*
17586 			 * Command transfers data, should have done so.
17587 			 */
17588 			} else if (ei->ei_failed_pkt.pkt_state &
17589 			    STATE_XFERRED_DATA) {
17590 				return (0); /* Good */
17591 			} else {
17592 				reposition = 1;
17593 			}
17594 		}
17595 
17596 		if (cmd_att->chg_tape_direction == DIR_FORW) {
17597 			difference =
17598 			    ei->ei_expected_pos.lgclblkno - read->lgclblkno;
17599 
17600 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17601 			    "difference between expected and actual is %"
17602 			    PRId64"\n", difference);
17603 			if (count == difference && reposition == 0) {
17604 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17605 				    "Found failed FORW command, retrying\n");
17606 				return (EAGAIN);
17607 			}
17608 
17609 			/*
17610 			 * If rewound or somewhere between the starting position
17611 			 * and the expected position (partial read or write).
17612 			 * Locate to the starting position and try the whole
17613 			 * thing over again.
17614 			 */
17615 			if ((read->lgclblkno == 0) ||
17616 			    ((difference > 0) && (difference < count))) {
17617 				rval = st_logical_block_locate(un,
17618 				    st_uscsi_rcmd, read,
17619 				    ei->ei_expected_pos.lgclblkno - count,
17620 				    ei->ei_expected_pos.partition);
17621 				if (rval == 0) {
17622 					ST_RECOV(ST_DEVINFO, st_label,
17623 					    CE_NOTE, "reestablished FORW"
17624 					    " command retrying\n");
17625 					return (EAGAIN);
17626 				}
17627 			/*
17628 			 * This handles flushed read ahead on the drive or
17629 			 * an aborted read that presents as a busy and advanced
17630 			 * the tape position.
17631 			 */
17632 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17633 			    ((difference < 0) || (reposition == 1))) {
17634 				rval = st_logical_block_locate(un,
17635 				    st_uscsi_rcmd, read,
17636 				    ei->ei_expected_pos.lgclblkno - count,
17637 				    ei->ei_expected_pos.partition);
17638 				if (rval == 0) {
17639 					ST_RECOV(ST_DEVINFO, st_label,
17640 					    CE_NOTE, "reestablished FORW"
17641 					    " read command retrying\n");
17642 					return (EAGAIN);
17643 				}
17644 			/*
17645 			 * XXX swag seeing difference of 2 on write filemark.
17646 			 * If the space to the starting position works on a
17647 			 * write that means the previous write made it to tape.
17648 			 * If not we lost data and have to give up.
17649 			 *
17650 			 * The plot thickens. Now I am attempting to cover a
17651 			 * count of 1 and a differance of 2 on a write.
17652 			 */
17653 			} else if ((difference > count) || (reposition == 1)) {
17654 				rval = st_logical_block_locate(un,
17655 				    st_uscsi_rcmd, read,
17656 				    ei->ei_expected_pos.lgclblkno - count,
17657 				    ei->ei_expected_pos.partition);
17658 				if (rval == 0) {
17659 					ST_RECOV(ST_DEVINFO, st_label,
17660 					    CE_NOTE, "reestablished FORW"
17661 					    " write command retrying\n");
17662 					return (EAGAIN);
17663 				}
17664 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17665 				    "Seek to block %"PRId64" returned %d\n",
17666 				    ei->ei_expected_pos.lgclblkno - count,
17667 				    rval);
17668 			} else {
17669 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17670 				    "Not expected transfers_data = %d "
17671 				    "difference = %"PRId64,
17672 				    cmd_att->transfers_data, difference);
17673 			}
17674 
17675 			return (EIO);
17676 
17677 		} else if (cmd_att->chg_tape_direction == DIR_REVC) {
17678 			/* Don't think we can write backwards */
17679 			ASSERT(cmd_att->transfers_data != TRAN_WRTE);
17680 			difference =
17681 			    read->lgclblkno - ei->ei_expected_pos.lgclblkno;
17682 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17683 			    "difference between expected and actual is %"
17684 			    PRId64"\n", difference);
17685 			if (count == difference && reposition == 0) {
17686 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17687 				    "Found failed REVC command, retrying\n");
17688 				return (EAGAIN);
17689 			}
17690 			if ((read->lgclblkno == 0) ||
17691 			    ((difference > 0) && (difference < count))) {
17692 				rval = st_logical_block_locate(un,
17693 				    st_uscsi_rcmd, read,
17694 				    ei->ei_expected_pos.lgclblkno + count,
17695 				    ei->ei_expected_pos.partition);
17696 				if (rval == 0) {
17697 					ST_RECOV(ST_DEVINFO, st_label,
17698 					    CE_NOTE, "reestablished REVC"
17699 					    " command retrying\n");
17700 					return (EAGAIN);
17701 				}
17702 			/* This handles read ahead in reverse direction */
17703 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17704 			    (difference < 0) || (reposition == 1)) {
17705 				rval = st_logical_block_locate(un,
17706 				    st_uscsi_rcmd, read,
17707 				    ei->ei_expected_pos.lgclblkno - count,
17708 				    ei->ei_expected_pos.partition);
17709 				if (rval == 0) {
17710 					ST_RECOV(ST_DEVINFO, st_label,
17711 					    CE_NOTE, "reestablished REVC"
17712 					    " read command retrying\n");
17713 					return (EAGAIN);
17714 				}
17715 			} else {
17716 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17717 				    "Not expected transfers_data = %d "
17718 				    "difference = %"PRId64,
17719 				    cmd_att->transfers_data, difference);
17720 			}
17721 			return (EIO);
17722 
17723 		} else {
17724 			/*
17725 			 * Commands that change tape position either
17726 			 * direction or don't change position should not
17727 			 * get here.
17728 			 */
17729 			ASSERT(0);
17730 		}
17731 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17732 		    "Didn't find a recoverable position, Failing\n");
17733 
17734 	/*
17735 	 * Command that changes tape position and can only be recovered
17736 	 * by going back to the point of origin and retrying.
17737 	 *
17738 	 * Example SCMD_SPACE.
17739 	 */
17740 	} else if (cmd_att->recov_pos_type == POS_STARTING) {
17741 		/*
17742 		 * This type of command stores the starting position.
17743 		 * If the read position is the starting position,
17744 		 * reissue the command.
17745 		 */
17746 		if (ei->ei_expected_pos.lgclblkno == read->lgclblkno) {
17747 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17748 			    "Found Space command at starting position, "
17749 			    "Reissuing\n");
17750 			return (EAGAIN);
17751 		}
17752 		/*
17753 		 * Not in the position that the command was originally issued,
17754 		 * Attempt to locate to that position.
17755 		 */
17756 		rval = st_logical_block_locate(un, st_uscsi_rcmd, read,
17757 		    ei->ei_expected_pos.lgclblkno,
17758 		    ei->ei_expected_pos.partition);
17759 		if (rval) {
17760 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17761 			    "Found Space at an unexpected position and locate "
17762 			    "back to starting position failed\n");
17763 			return (EIO);
17764 		}
17765 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17766 		    "Found Space at an unexpected position and locate "
17767 		    "back to starting position worked, Reissuing\n");
17768 		return (EAGAIN);
17769 	}
17770 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17771 	    "Unhandled attribute/expected position", &ei->ei_expected_pos);
17772 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17773 	    "Read position above did not make sense", read);
17774 	ASSERT(0);
17775 	return (EIO);
17776 }
17777 
17778 static errstate
17779 st_recover_reissue_pkt(struct scsi_tape *un, struct scsi_pkt *oldpkt)
17780 {
17781 	buf_t *bp;
17782 	buf_t *pkt_bp;
17783 	struct scsi_pkt *newpkt;
17784 	cmd_attribute const *attrib;
17785 	recov_info *rcv = oldpkt->pkt_private;
17786 	uint_t cdblen;
17787 	int queued = 0;
17788 	int rval;
17789 	int flags = 0;
17790 	int stat_size =
17791 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
17792 
17793 	ST_FUNC(ST_DEVINFO, st_recover_reissue_pkt);
17794 
17795 	bp = rcv->cmd_bp;
17796 
17797 	if (rcv->privatelen == sizeof (recov_info)) {
17798 		attrib = rcv->cmd_attrib;
17799 	} else {
17800 		attrib = st_lookup_cmd_attribute(oldpkt->pkt_cdbp[0]);
17801 	}
17802 
17803 	/*
17804 	 * Some non-uscsi commands use the b_bcount for values that
17805 	 * have nothing to do with how much data is transfered.
17806 	 * In those cases we need to hide the buf_t from scsi_init_pkt().
17807 	 */
17808 	if ((BP_UCMD(bp)) && (bp->b_bcount)) {
17809 		pkt_bp = bp;
17810 	} else if (attrib->transfers_data == TRAN_NONE) {
17811 		pkt_bp = NULL;
17812 	} else {
17813 		pkt_bp = bp;
17814 	}
17815 
17816 	/*
17817 	 * if this is a queued command make sure it the only one in the
17818 	 * run queue.
17819 	 */
17820 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
17821 		ASSERT(un->un_runqf == un->un_runql);
17822 		ASSERT(un->un_runqf == bp);
17823 		queued = 1;
17824 	}
17825 
17826 	cdblen = scsi_cdb_size[CDB_GROUPID(oldpkt->pkt_cdbp[0])];
17827 
17828 	if (pkt_bp == un->un_rqs_bp) {
17829 		flags |= PKT_CONSISTENT;
17830 		stat_size = 1;
17831 	}
17832 
17833 	newpkt = scsi_init_pkt(ROUTE, NULL, pkt_bp, cdblen,
17834 	    stat_size, rcv->privatelen, flags, NULL_FUNC, NULL);
17835 	if (newpkt == NULL) {
17836 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17837 		    "Reissue pkt scsi_init_pkt() failure\n");
17838 		return (COMMAND_DONE_ERROR);
17839 	}
17840 
17841 	ASSERT(newpkt->pkt_resid == 0);
17842 	bp->b_flags &= ~(B_DONE);
17843 	bp->b_resid = 0;
17844 	st_bioerror(bp, 0);
17845 
17846 	bcopy(oldpkt->pkt_private, newpkt->pkt_private, rcv->privatelen);
17847 
17848 	newpkt->pkt_comp = oldpkt->pkt_comp;
17849 	newpkt->pkt_time = oldpkt->pkt_time;
17850 
17851 	bzero(newpkt->pkt_scbp, stat_size);
17852 	bcopy(oldpkt->pkt_cdbp, newpkt->pkt_cdbp, cdblen);
17853 
17854 	newpkt->pkt_state = 0;
17855 	newpkt->pkt_statistics = 0;
17856 
17857 	/*
17858 	 * oldpkt passed in was a copy of the original.
17859 	 * to distroy we need the address of the original.
17860 	 */
17861 	oldpkt = BP_PKT(bp);
17862 
17863 	if (oldpkt == un->un_rqs) {
17864 		ASSERT(bp == un->un_rqs_bp);
17865 		un->un_rqs = newpkt;
17866 	}
17867 
17868 	SET_BP_PKT(bp, newpkt);
17869 
17870 	scsi_destroy_pkt(oldpkt);
17871 
17872 	rval = st_transport(un, newpkt);
17873 	if (rval == TRAN_ACCEPT) {
17874 		return (JUST_RETURN);
17875 	}
17876 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17877 	    "Reissue pkt st_transport(0x%x) failure\n", rval);
17878 	if (rval != TRAN_BUSY) {
17879 		return (COMMAND_DONE_ERROR);
17880 	}
17881 	mutex_exit(ST_MUTEX);
17882 	rval = st_handle_start_busy(un, bp, ST_TRAN_BUSY_TIMEOUT, queued);
17883 	mutex_enter(ST_MUTEX);
17884 	if (rval) {
17885 		return (COMMAND_DONE_ERROR);
17886 	}
17887 
17888 	return (JUST_RETURN);
17889 }
17890 
17891 static int
17892 st_transport(struct scsi_tape *un, struct scsi_pkt *pkt)
17893 {
17894 	int status;
17895 
17896 	ST_FUNC(ST_DEVINFO, st_transport);
17897 
17898 	ST_CDB(ST_DEVINFO, "transport CDB", (caddr_t)pkt->pkt_cdbp);
17899 
17900 	mutex_exit(ST_MUTEX);
17901 
17902 	status = scsi_transport(pkt);
17903 
17904 	mutex_enter(ST_MUTEX);
17905 
17906 	return (status);
17907 }
17908 
17909 /*
17910  * Removed the buf_t bp from the queue referenced to by head and tail.
17911  * Returns the buf_t pointer if it is found in the queue.
17912  * Returns NULL if it is not found.
17913  */
17914 static buf_t *
17915 st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp)
17916 {
17917 	buf_t *runqbp;
17918 	buf_t *prevbp = NULL;
17919 
17920 	for (runqbp = *head; runqbp != 0; runqbp = runqbp->av_forw) {
17921 		if (runqbp == bp) {
17922 			/* found it, is it at the head? */
17923 			if (runqbp == *head) {
17924 				*head = bp->av_forw;
17925 			} else {
17926 				prevbp->av_forw = bp->av_forw;
17927 			}
17928 			if (*tail == bp) {
17929 				*tail = prevbp;
17930 			}
17931 			bp->av_forw = NULL;
17932 			return (bp); /* found and removed */
17933 		}
17934 		prevbp = runqbp;
17935 	}
17936 	return (NULL);
17937 }
17938 
17939 /*
17940  * Adds a buf_t to the queue pointed to by head and tail.
17941  * Adds it either to the head end or the tail end based on which
17942  * the passed variable end (head or tail) points at.
17943  */
17944 static void
17945 st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp)
17946 {
17947 
17948 	bp->av_forw = NULL;
17949 	if (*head) {
17950 		/* Queue is not empty */
17951 		if (end == *head) {
17952 			/* Add at front of queue */
17953 			bp->av_forw = *head;
17954 			*head = bp;
17955 		} else if (end == *tail) {
17956 			/* Add at end of queue */
17957 			(*tail)->av_forw = bp;
17958 			*tail = bp;
17959 		} else {
17960 			ASSERT(0);
17961 		}
17962 	} else {
17963 		/* Queue is empty */
17964 		*head = bp;
17965 		*tail = bp;
17966 	}
17967 }
17968 
17969 
17970 static uint64_t
17971 st_get_cdb_g0_rw_count(uchar_t *cdb)
17972 {
17973 	uint64_t count;
17974 
17975 	if ((cdb[1]) & 1) {
17976 		/* fixed block mode, the count is the number of blocks */
17977 		count =
17978 		    cdb[2] << 16 |
17979 		    cdb[3] << 8 |
17980 		    cdb[4];
17981 	} else {
17982 		/* variable block mode, the count is the block size */
17983 		count = 1;
17984 	}
17985 	return (count);
17986 }
17987 
17988 static uint64_t
17989 st_get_cdb_g0_sign_count(uchar_t *cdb)
17990 {
17991 	uint64_t count;
17992 
17993 	count =
17994 	    cdb[2] << 16 |
17995 	    cdb[3] << 8 |
17996 	    cdb[4];
17997 	/*
17998 	 * If the sign bit of the 3 byte value is set, extended it.
17999 	 */
18000 	if (count & 0x800000) {
18001 		count |= 0xffffffffff000000;
18002 	}
18003 	return (count);
18004 }
18005 
18006 static uint64_t
18007 st_get_cdb_g0_count(uchar_t *cdb)
18008 {
18009 	uint64_t count;
18010 
18011 	count =
18012 	    cdb[2] << 16 |
18013 	    cdb[3] << 8 |
18014 	    cdb[4];
18015 	return (count);
18016 }
18017 
18018 static uint64_t
18019 st_get_cdb_g5_rw_cnt(uchar_t *cdb)
18020 {
18021 	uint64_t count;
18022 
18023 	if ((cdb[1]) & 1) {
18024 		/* fixed block mode */
18025 		count =
18026 		    cdb[12] << 16 |
18027 		    cdb[13] << 8 |
18028 		    cdb[14];
18029 	} else {
18030 		/* variable block mode */
18031 		count = 1;
18032 	}
18033 	return (count);
18034 }
18035 
18036 static uint64_t
18037 st_get_no_count(uchar_t *cdb)
18038 {
18039 	ASSERT(cdb[0] == SCMD_REWIND);
18040 	return ((uint64_t)cdb[0]);
18041 }
18042 
18043 static uint64_t
18044 st_get_load_options(uchar_t *cdb)
18045 {
18046 	return ((uint64_t)(cdb[4] | (LD_HOLD << 1)));
18047 }
18048 
18049 static uint64_t
18050 st_get_erase_options(uchar_t *cdb)
18051 {
18052 	return (cdb[1] | (cdb[0] << 8));
18053 }
18054 
18055 static uint64_t
18056 st_get_cdb_g1_lba(uchar_t *cdb)
18057 {
18058 	uint64_t lba;
18059 
18060 	lba =
18061 	    cdb[3] << 24 |
18062 	    cdb[4] << 16 |
18063 	    cdb[5] << 8 |
18064 	    cdb[6];
18065 	return (lba);
18066 }
18067 
18068 static uint64_t
18069 st_get_cdb_g5_count(uchar_t *cdb)
18070 {
18071 	uint64_t count =
18072 	    cdb[12] << 16 |
18073 	    cdb[13] << 8 |
18074 	    cdb[14];
18075 
18076 	return (count);
18077 }
18078 
18079 static uint64_t
18080 st_get_cdb_g4g5_cnt(uchar_t *cdb)
18081 {
18082 	uint64_t lba;
18083 
18084 	lba =
18085 	    (uint64_t)cdb[4] << 56 |
18086 	    (uint64_t)cdb[5] << 48 |
18087 	    (uint64_t)cdb[6] << 40 |
18088 	    (uint64_t)cdb[7] << 32 |
18089 	    (uint64_t)cdb[8] << 24 |
18090 	    (uint64_t)cdb[9] << 16 |
18091 	    (uint64_t)cdb[10] << 8 |
18092 	    (uint64_t)cdb[11];
18093 	return (lba);
18094 }
18095 
18096 static const cmd_attribute cmd_attributes[] = {
18097 	{ SCMD_READ,
18098 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_READ, POS_EXPECTED,
18099 	    0, 0, 0, st_get_cdb_g0_rw_count },
18100 	{ SCMD_WRITE,
18101 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18102 	    0, 0, 0, st_get_cdb_g0_rw_count },
18103 	{ SCMD_TEST_UNIT_READY,
18104 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18105 	    0, 0, 0 },
18106 	{ SCMD_REWIND,
18107 	    1, 1, 1, 0, 0, DIR_REVC, TRAN_NONE, POS_EXPECTED,
18108 	    0, 0, 0, st_get_no_count },
18109 	{ SCMD_REQUEST_SENSE,
18110 	    0, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18111 	    0, 0, 0 },
18112 	{ SCMD_READ_BLKLIM,
18113 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18114 	    0, 0, 0 },
18115 	{ SCMD_READ_G4,
18116 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_READ, POS_EXPECTED,
18117 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18118 	{ SCMD_WRITE_G4,
18119 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18120 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18121 	{ SCMD_READ_REVERSE,
18122 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18123 	    0, 0, 0, st_get_cdb_g0_rw_count },
18124 	{ SCMD_READ_REVERSE_G4,
18125 	    1, 0, 1, 1, 1, DIR_REVC, TRAN_READ, POS_EXPECTED,
18126 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18127 	{ SCMD_WRITE_FILE_MARK,
18128 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18129 	    0, 0, 0, st_get_cdb_g0_count },
18130 	{ SCMD_WRITE_FILE_MARK_G4,
18131 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18132 	    0, 0, 0, st_get_cdb_g5_count, st_get_cdb_g4g5_cnt },
18133 	{ SCMD_SPACE,
18134 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18135 	    0, 0, 0, st_get_cdb_g0_sign_count },
18136 	{ SCMD_SPACE_G4,
18137 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18138 	    0, 0, 0, st_get_cdb_g4g5_cnt },
18139 	{ SCMD_INQUIRY,
18140 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18141 	    0, 0, 0 },
18142 	{ SCMD_VERIFY_G0,
18143 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18144 	    0, 0, 0, st_get_cdb_g0_rw_count },
18145 	{ SCMD_VERIFY_G4,
18146 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18147 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18148 	{ SCMD_RECOVER_BUF,
18149 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18150 	    0, 0, 0 },
18151 	{ SCMD_MODE_SELECT,
18152 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18153 	    0, 0, 0 },
18154 	{ SCMD_RESERVE,
18155 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18156 	    0, 0, 0 },
18157 	{ SCMD_RELEASE,
18158 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18159 	    0, 0, 0 },
18160 	{ SCMD_ERASE,
18161 	    1, 0, 1, 1, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18162 	    0, 0, 0, st_get_erase_options },
18163 	{ SCMD_MODE_SENSE,
18164 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18165 	    0, 0, 0 },
18166 	{ SCMD_LOAD,
18167 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18168 	    0, 0, 0, st_get_load_options },
18169 	{ SCMD_GDIAG,
18170 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18171 	    1, 0, 0 },
18172 	{ SCMD_SDIAG,
18173 	    1, 0, 1, 1, 0, DIR_EITH, TRAN_WRTE, POS_EXPECTED,
18174 	    1, 0, 0 },
18175 	{ SCMD_DOORLOCK,
18176 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18177 	    0, 4, 3 },
18178 	{ SCMD_LOCATE,
18179 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18180 	    0, 0, 0, NULL, st_get_cdb_g1_lba },
18181 	{ SCMD_READ_POSITION,
18182 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18183 	    0, 0, 0 },
18184 	{ SCMD_WRITE_BUFFER,
18185 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18186 	    1, 0, 0 },
18187 	{ SCMD_READ_BUFFER,
18188 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18189 	    1, 0, 0 },
18190 	{ SCMD_REPORT_DENSITIES,
18191 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18192 	    0, 0, 0 },
18193 	{ SCMD_LOG_SELECT_G1,
18194 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18195 	    0, 0, 0 },
18196 	{ SCMD_LOG_SENSE_G1,
18197 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18198 	    0, 0, 0 },
18199 	{ SCMD_PRIN,
18200 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18201 	    0, 0, 0 },
18202 	{ SCMD_PROUT,
18203 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18204 	    0, 0, 0 },
18205 	{ SCMD_READ_ATTRIBUTE,
18206 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18207 	    0, 0, 0 },
18208 	{ SCMD_WRITE_ATTRIBUTE,
18209 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18210 	    0, 0, 0 },
18211 	{ SCMD_LOCATE_G4,
18212 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18213 	    0, 0, 0, NULL, st_get_cdb_g4g5_cnt },
18214 	{ SCMD_REPORT_LUNS,
18215 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18216 	    0, 0, 0 },
18217 	{ SCMD_SVC_ACTION_IN_G5,
18218 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18219 	    0, 0, 0 },
18220 	{ SCMD_MAINTENANCE_IN,
18221 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18222 	    0, 0, 0 },
18223 	{ SCMD_MAINTENANCE_OUT,
18224 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18225 	    0, 0, 0 },
18226 	{ 0xff, /* Default attribute for unsupported commands */
18227 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_STARTING,
18228 	    1, 0, 0, NULL, NULL }
18229 };
18230 
18231 static const cmd_attribute *
18232 st_lookup_cmd_attribute(unsigned char cmd)
18233 {
18234 	int i;
18235 	cmd_attribute const *attribute;
18236 
18237 	for (i = 0; i < ST_NUM_MEMBERS(cmd_attributes); i++) {
18238 		attribute = &cmd_attributes[i];
18239 		if (attribute->cmd == cmd) {
18240 			return (attribute);
18241 		}
18242 	}
18243 	ASSERT(attribute);
18244 	return (attribute);
18245 }
18246 
18247 static int
18248 st_reset(struct scsi_tape *un, int reset_type)
18249 {
18250 	int rval;
18251 
18252 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
18253 
18254 	ST_FUNC(ST_DEVINFO, st_reset);
18255 	un->un_rsvd_status |= ST_INITIATED_RESET;
18256 	mutex_exit(ST_MUTEX);
18257 	do {
18258 		rval = scsi_reset(&un->un_sd->sd_address, reset_type);
18259 		if (rval == 0) {
18260 			switch (reset_type) {
18261 			case RESET_LUN:
18262 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18263 				    "LUN reset failed trying target reset");
18264 				reset_type = RESET_TARGET;
18265 				break;
18266 			case RESET_TARGET:
18267 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18268 				    "target reset failed trying bus reset");
18269 				reset_type = RESET_BUS;
18270 				break;
18271 			case RESET_BUS:
18272 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18273 				    "bus reset failed trying all reset");
18274 				reset_type = RESET_ALL;
18275 			default:
18276 				mutex_enter(ST_MUTEX);
18277 				return (rval);
18278 			}
18279 		}
18280 	} while (rval == 0);
18281 	mutex_enter(ST_MUTEX);
18282 	return (rval);
18283 }
18284 
18285 
18286 static void
18287 st_reset_notification(caddr_t arg)
18288 {
18289 	struct scsi_tape *un = (struct scsi_tape *)arg;
18290 
18291 	ST_FUNC(ST_DEVINFO, st_reset_notification);
18292 	mutex_enter(ST_MUTEX);
18293 
18294 	un->un_unit_attention_flags |= 2;
18295 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
18296 	    ST_RESERVE) {
18297 		un->un_rsvd_status |= ST_LOST_RESERVE;
18298 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18299 		    "Lost Reservation notification");
18300 	} else {
18301 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18302 		    "reset notification");
18303 	}
18304 
18305 	if ((un->un_restore_pos == 0) &&
18306 	    (un->un_state == ST_STATE_CLOSED) ||
18307 	    (un->un_state == ST_STATE_OPEN_PENDING_IO) ||
18308 	    (un->un_state == ST_STATE_CLOSING)) {
18309 		un->un_restore_pos = 1;
18310 	}
18311 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
18312 	    "reset and state was %d\n", un->un_state);
18313 	mutex_exit(ST_MUTEX);
18314 }
18315