xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/st.c (revision 922d2c76afbee21520ffa2088c4e60dcb80d3945)
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 				break;
10981 			/*
10982 			 * RESERVATIONS RELEASED
10983 			 */
10984 			} else if (ST_RQSENSE->es_add_code == 0x2a &&
10985 			    ST_RQSENSE->es_qual_code == 0x04) {
10986 				severity = SCSI_ERR_INFO;
10987 				rval = COMMAND_DONE;
10988 				break;
10989 			}
10990 		}
10991 
10992 		if (un->un_state <= ST_STATE_OPENING) {
10993 			/*
10994 			 * Look, the tape isn't open yet, now determine
10995 			 * if the cause is a BUS RESET, Save the file
10996 			 * and Block positions for the callers to
10997 			 * recover from the loss of position.
10998 			 */
10999 			severity = SCSI_ERR_INFO;
11000 			if ((pos->pmode != invalid) &&
11001 			    (rval == DEVICE_RESET) &&
11002 			    (un->un_restore_pos != 1)) {
11003 				un->un_save_fileno = pos->fileno;
11004 				un->un_save_blkno = pos->blkno;
11005 				un->un_restore_pos = 1;
11006 			}
11007 
11008 			if (attrib->retriable &&
11009 			    ri->pkt_retry_cnt++ < st_retry_count) {
11010 				rval = QUE_COMMAND;
11011 			} else if (rval == DEVICE_RESET) {
11012 				break;
11013 			} else {
11014 				rval = COMMAND_DONE_ERROR;
11015 			}
11016 		/*
11017 		 * Means it thinks the mode parameters have changed.
11018 		 * This is the result of a reset clearing settings or
11019 		 * another initiator changing what we set.
11020 		 */
11021 		}
11022 		if (ST_RQSENSE->es_add_code == 0x2a) {
11023 			if (ST_RQSENSE->es_qual_code == 0x1) {
11024 				/* Error recovery will modeselect and retry. */
11025 				rval = DEVICE_TAMPER;
11026 				severity = SCSI_ERR_INFO;
11027 				break; /* don't set position invalid */
11028 			}
11029 			if (ST_RQSENSE->es_qual_code == 0x0 ||
11030 			    ST_RQSENSE->es_qual_code == 0x2 ||
11031 			    ST_RQSENSE->es_qual_code == 0x3 ||
11032 			    ST_RQSENSE->es_qual_code == 0x4 ||
11033 			    ST_RQSENSE->es_qual_code == 0x5 ||
11034 			    ST_RQSENSE->es_qual_code == 0x6 ||
11035 			    ST_RQSENSE->es_qual_code == 0x7) {
11036 				rval = DEVICE_TAMPER;
11037 				severity = SCSI_ERR_INFO;
11038 			}
11039 		} else if (ST_RQSENSE->es_add_code == 0x28 &&
11040 		    ((ST_RQSENSE->es_qual_code == 0x0) ||
11041 		    ST_RQSENSE->es_qual_code == 0x5)) {
11042 			/*
11043 			 * Not Ready to Ready change, Media may have changed.
11044 			 */
11045 			rval = DEVICE_TAMPER;
11046 			severity = SCSI_ERR_RETRYABLE;
11047 		} else {
11048 			if (rval != DEVICE_RESET) {
11049 				rval = COMMAND_DONE_ERROR;
11050 			} else {
11051 				/*
11052 				 * Returning DEVICE_RESET will call
11053 				 * error recovery.
11054 				 */
11055 				severity = SCSI_ERR_INFO;
11056 				break; /* don't set position invalid */
11057 			}
11058 			/*
11059 			 * Check if it is an Unexpected Unit Attention.
11060 			 * If state is >= ST_STATE_OPEN, we have
11061 			 * already done the initialization .
11062 			 * In this case it is Fatal Error
11063 			 * since no further reading/writing
11064 			 * can be done with fileno set to < 0.
11065 			 */
11066 			if (un->un_state >= ST_STATE_OPEN) {
11067 				ST_DO_ERRSTATS(un, st_harderrs);
11068 				severity = SCSI_ERR_FATAL;
11069 			} else {
11070 				severity = SCSI_ERR_INFO;
11071 			}
11072 		}
11073 
11074 		pos->pmode = invalid;
11075 
11076 		break;
11077 
11078 	case KEY_NOT_READY:
11079 		/*
11080 		 * If in process of getting ready retry.
11081 		 */
11082 		if (sensep->es_add_code  == 0x04 &&
11083 		    sensep->es_qual_code == 0x01 &&
11084 		    ri->pkt_retry_cnt++ < st_retry_count) {
11085 			rval = QUE_COMMAND;
11086 			severity = SCSI_ERR_INFO;
11087 		} else {
11088 			/* give up */
11089 			rval = COMMAND_DONE_ERROR;
11090 			severity = SCSI_ERR_FATAL;
11091 		}
11092 
11093 		/*
11094 		 * If this was an error and after device opened
11095 		 * do error stats.
11096 		 */
11097 		if (rval == COMMAND_DONE_ERROR &&
11098 		    un->un_state > ST_STATE_OPENING) {
11099 			ST_DO_ERRSTATS(un, st_harderrs);
11100 		}
11101 
11102 		if (ST_RQSENSE->es_add_code == 0x3a) {
11103 			if (st_error_level >= SCSI_ERR_FATAL)
11104 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11105 				    "Tape not inserted in drive\n");
11106 			un->un_mediastate = MTIO_EJECTED;
11107 			cv_broadcast(&un->un_state_cv);
11108 		}
11109 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
11110 		    (rval != QUE_COMMAND))
11111 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
11112 		break;
11113 
11114 	case KEY_ABORTED_COMMAND:
11115 		/* XXX Do drives return this when they see a lost light? */
11116 		/* Testing would say yes */
11117 
11118 		if (ri->pkt_retry_cnt++ < st_retry_count) {
11119 			rval = ATTEMPT_RETRY;
11120 			severity = SCSI_ERR_RETRYABLE;
11121 			goto check_keys;
11122 		}
11123 		/*
11124 		 * Probably a parity error...
11125 		 * if we retry here then this may cause data to be
11126 		 * written twice or data skipped during reading
11127 		 */
11128 		ST_DO_ERRSTATS(un, st_harderrs);
11129 		severity = SCSI_ERR_FATAL;
11130 		rval = COMMAND_DONE_ERROR;
11131 		goto check_keys;
11132 
11133 	default:
11134 		/*
11135 		 * Undecoded sense key.	 Try retries and hope
11136 		 * that will fix the problem.  Otherwise, we're
11137 		 * dead.
11138 		 */
11139 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11140 		    "Unhandled Sense Key '%s'\n",
11141 		    sense_keys[un->un_status]);
11142 		ST_DO_ERRSTATS(un, st_harderrs);
11143 		severity = SCSI_ERR_FATAL;
11144 		rval = COMMAND_DONE_ERROR;
11145 		goto check_keys;
11146 	}
11147 
11148 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
11149 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
11150 	    (un->un_laststate > ST_STATE_OPENING) &&
11151 	    (severity >= st_error_level))) {
11152 
11153 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
11154 		    pos->lgclblkno, un->un_err_pos.lgclblkno,
11155 		    scsi_cmds, sensep);
11156 		if (sensep->es_filmk) {
11157 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11158 			    "File Mark Detected\n");
11159 		}
11160 		if (sensep->es_eom) {
11161 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11162 			    "End-of-Media Detected\n");
11163 		}
11164 		if (sensep->es_ili) {
11165 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11166 			    "Incorrect Length Indicator Set\n");
11167 		}
11168 	}
11169 	get_error = geterror(bp);
11170 	if (((rval == COMMAND_DONE_ERROR) ||
11171 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
11172 	    ((get_error == EIO) || (get_error == 0))) {
11173 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
11174 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
11175 		if (un->un_rqs_state & ST_RQS_READ) {
11176 			un->un_rqs_state &= ~(ST_RQS_READ);
11177 		} else {
11178 			un->un_rqs_state |= ST_RQS_OVR;
11179 		}
11180 	}
11181 
11182 	return (rval);
11183 }
11184 
11185 
11186 static int
11187 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
11188 {
11189 	int status = TRAN_ACCEPT;
11190 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
11191 
11192 	mutex_enter(ST_MUTEX);
11193 
11194 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
11195 
11196 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11197 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
11198 
11199 	/*
11200 	 * Check to see if we hit the retry timeout. We check to make sure
11201 	 * this is the first one on the runq and make sure we have not
11202 	 * queued up any more, so this one has to be the last on the list
11203 	 * also. If it is not, we have to fail.  If it is not the first, but
11204 	 * is the last we are in trouble anyway, as we are in the interrupt
11205 	 * context here.
11206 	 */
11207 	if ((pktinfo->pkt_retry_cnt > st_retry_count) ||
11208 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
11209 		goto exit;
11210 	}
11211 
11212 	if (un->un_throttle) {
11213 		un->un_last_throttle = un->un_throttle;
11214 		un->un_throttle = 0;
11215 	}
11216 
11217 	/*
11218 	 * Here we know : bp is the first and last one on the runq
11219 	 * it is not necessary to put it back on the head of the
11220 	 * waitq and then move from waitq to runq. Save this queuing
11221 	 * and call scsi_transport.
11222 	 */
11223 	ST_CDB(ST_DEVINFO, "Retry lcmd CDB", (char *)BP_PKT(bp)->pkt_cdbp);
11224 
11225 	status = st_transport(un, BP_PKT(bp));
11226 
11227 	if (status == TRAN_ACCEPT) {
11228 		if (un->un_last_throttle) {
11229 			un->un_throttle = un->un_last_throttle;
11230 		}
11231 		mutex_exit(ST_MUTEX);
11232 
11233 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11234 		    "restart transport \n");
11235 		return (0);
11236 	}
11237 
11238 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
11239 	mutex_exit(ST_MUTEX);
11240 
11241 	if (status == TRAN_BUSY) {
11242 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
11243 			return (0);
11244 		}
11245 	}
11246 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11247 	    "restart transport rejected\n");
11248 	mutex_enter(ST_MUTEX);
11249 	ST_DO_ERRSTATS(un, st_transerrs);
11250 	if (un->un_last_throttle) {
11251 		un->un_throttle = un->un_last_throttle;
11252 	}
11253 exit:
11254 	mutex_exit(ST_MUTEX);
11255 	return (-1);
11256 }
11257 
11258 static int
11259 st_wrongtapetype(struct scsi_tape *un)
11260 {
11261 
11262 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
11263 
11264 	ASSERT(mutex_owned(ST_MUTEX));
11265 
11266 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
11267 
11268 	/*
11269 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
11270 	 */
11271 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
11272 		switch (un->un_dp->type) {
11273 		case ST_TYPE_WANGTEK:
11274 		case ST_TYPE_ARCHIVE:
11275 			/*
11276 			 * If this really worked, we could go off of
11277 			 * the density codes set in the modesense
11278 			 * page. For this drive, 0x10 == QIC-120,
11279 			 * 0xf == QIC-150, and 0x5 should be for
11280 			 * both QIC-24 and, maybe, QIC-11. However,
11281 			 * the h/w doesn't do what the manual says
11282 			 * that it should, so we'll key off of
11283 			 * getting a WRITE PROTECT error AND wp *not*
11284 			 * set in the mode sense information.
11285 			 */
11286 			/*
11287 			 * XXX but we already know that status is
11288 			 * write protect, so don't check it again.
11289 			 */
11290 
11291 			if (un->un_status == KEY_WRITE_PROTECT &&
11292 			    un->un_mspl->wp == 0) {
11293 				return (1);
11294 			}
11295 			break;
11296 		default:
11297 			break;
11298 		}
11299 	}
11300 	return (0);
11301 }
11302 
11303 static errstate
11304 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
11305 {
11306 	errstate action;
11307 	recov_info *rcvi = pkt->pkt_private;
11308 	buf_t *bp = rcvi->cmd_bp;
11309 	struct scsi_arq_status *stat = (struct scsi_arq_status *)pkt->pkt_scbp;
11310 
11311 	ST_FUNC(ST_DEVINFO, st_check_error);
11312 
11313 	ASSERT(mutex_owned(ST_MUTEX));
11314 
11315 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
11316 
11317 	switch (SCBP_C(pkt)) {
11318 	case STATUS_RESERVATION_CONFLICT:
11319 		/*
11320 		 * Command recovery is enabled, not just opening,
11321 		 * we had the drive reserved and we thing its ours.
11322 		 * Call recovery to attempt to take it back.
11323 		 */
11324 		if ((rcvi->privatelen == sizeof (recov_info)) &&
11325 		    (bp != un->un_recov_buf) &&
11326 		    (un->un_state > ST_STATE_OPEN_PENDING_IO) &&
11327 		    ((un->un_rsvd_status & (ST_RESERVE |
11328 		    ST_APPLICATION_RESERVATIONS)) != 0)) {
11329 			action = ATTEMPT_RETRY;
11330 			un->un_rsvd_status |= ST_LOST_RESERVE;
11331 		} else {
11332 			action = COMMAND_DONE_EACCES;
11333 			un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
11334 		}
11335 		break;
11336 
11337 	case STATUS_BUSY:
11338 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
11339 		if (rcvi->privatelen == sizeof (recov_info) &&
11340 		    un->un_multipath && (pkt->pkt_state == (STATE_GOT_BUS |
11341 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS))) {
11342 			/*
11343 			 * Status returned by scsi_vhci indicating path
11344 			 * has failed over.
11345 			 */
11346 			action = PATH_FAILED;
11347 			break;
11348 		}
11349 		/* FALLTHRU */
11350 	case STATUS_QFULL:
11351 		if (rcvi->privatelen == sizeof (recov_info)) {
11352 			/*
11353 			 * If recovery is inabled use it instead of
11354 			 * blind reties.
11355 			 */
11356 			action = ATTEMPT_RETRY;
11357 		} else if (rcvi->pkt_retry_cnt++ < st_retry_count) {
11358 			action = QUE_BUSY_COMMAND;
11359 		} else if ((un->un_rsvd_status &
11360 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
11361 			/*
11362 			 * If this is a command done before reserve is done
11363 			 * don't reset.
11364 			 */
11365 			action = COMMAND_DONE_ERROR;
11366 		} else {
11367 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11368 			    "unit busy too long\n");
11369 			(void) st_reset(un, RESET_ALL);
11370 			action = COMMAND_DONE_ERROR;
11371 		}
11372 		break;
11373 
11374 	case STATUS_CHECK:
11375 	case STATUS_TERMINATED:
11376 		/*
11377 		 * we should only get here if the auto rqsense failed
11378 		 * thru a uscsi cmd without autorequest sense
11379 		 * so we just try again
11380 		 */
11381 		if (un->un_arq_enabled &&
11382 		    stat->sts_rqpkt_reason == CMD_CMPLT &&
11383 		    (stat->sts_rqpkt_state & (STATE_GOT_BUS |
11384 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) ==
11385 		    (STATE_GOT_BUS | STATE_GOT_TARGET | STATE_SENT_CMD |
11386 		    STATE_GOT_STATUS)) {
11387 
11388 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11389 			    "Really got sense data\n");
11390 			action = st_decode_sense(un, bp, MAX_SENSE_LENGTH -
11391 			    pkt->pkt_resid, stat, &un->un_pos);
11392 		} else {
11393 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11394 			    "Trying to queue sense command\n");
11395 			action = QUE_SENSE;
11396 		}
11397 		break;
11398 
11399 	case STATUS_TASK_ABORT:
11400 		/*
11401 		 * This is an aborted task. This can be a reset on the other
11402 		 * port of a multiport drive. Lets try and recover it.
11403 		 */
11404 		action = DEVICE_RESET;
11405 		break;
11406 
11407 	default:
11408 		action = COMMAND_DONE;
11409 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
11410 		    "Unexpected scsi status byte 0x%x\n", SCBP_C(pkt));
11411 	}
11412 	return (action);
11413 }
11414 
11415 static void
11416 st_calc_bnum(struct scsi_tape *un, struct buf *bp, struct scsi_pkt *pkt)
11417 {
11418 	int nblks;
11419 	int nfiles;
11420 	long count;
11421 	recov_info *ri = pkt->pkt_private;
11422 	cmd_attribute const *attrib;
11423 
11424 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
11425 
11426 	ASSERT(mutex_owned(ST_MUTEX));
11427 
11428 	if (ri->privatelen == sizeof (recov_info)) {
11429 		attrib = ri->cmd_attrib;
11430 		ASSERT(attrib->recov_pos_type == POS_EXPECTED);
11431 		ASSERT(attrib->chg_tape_pos);
11432 	} else {
11433 		ri = NULL;
11434 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
11435 	}
11436 
11437 	count = bp->b_bcount - bp->b_resid;
11438 
11439 	/* Command reads or writes data */
11440 	if (attrib->transfers_data != TRAN_NONE) {
11441 		if (count == 0) {
11442 			/* failed writes should not make it here */
11443 			ASSERT(attrib->transfers_data == TRAN_READ);
11444 			nblks = 0;
11445 			nfiles = 1;
11446 		} else if (un->un_bsize == 0) {
11447 			/*
11448 			 * If variable block mode.
11449 			 * Fixed bit in CBD should be zero.
11450 			 */
11451 			ASSERT((pkt->pkt_cdbp[1] & 1) == 0);
11452 			nblks = 1;
11453 			un->un_kbytes_xferred += (count / ONE_K);
11454 			nfiles = 0;
11455 		} else {
11456 			/*
11457 			 * If fixed block mode.
11458 			 * Fixed bit in CBD should be one.
11459 			 */
11460 			ASSERT((pkt->pkt_cdbp[1] & 1) == 1);
11461 			nblks = (count / un->un_bsize);
11462 			un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
11463 			nfiles = 0;
11464 		}
11465 		/*
11466 		 * So its possable to read some blocks and hit a filemark.
11467 		 * Example reading in fixed block mode where more then one
11468 		 * block at a time is requested. In this case because the
11469 		 * filemark is hit something less then the requesed number
11470 		 * of blocks is read.
11471 		 */
11472 		if (un->un_pos.eof == ST_EOF_PENDING && bp->b_resid) {
11473 			nfiles = 1;
11474 		}
11475 	} else {
11476 		nblks = 0;
11477 		nfiles = count;
11478 	}
11479 
11480 	/*
11481 	 * If some command failed after this one started and it seems
11482 	 * to have finshed without error count the position.
11483 	 */
11484 	if (un->un_persistence && un->un_persist_errors) {
11485 		ASSERT(un->un_pos.pmode != invalid);
11486 	}
11487 
11488 	if (attrib->chg_tape_direction == DIR_FORW) {
11489 		un->un_pos.blkno += nblks;
11490 		un->un_pos.lgclblkno += nblks;
11491 		un->un_pos.lgclblkno += nfiles;
11492 	} else if (attrib->chg_tape_direction == DIR_REVC) {
11493 		un->un_pos.blkno -= nblks;
11494 		un->un_pos.lgclblkno -= nblks;
11495 		un->un_pos.lgclblkno -= nfiles;
11496 	} else {
11497 		ASSERT(0);
11498 	}
11499 
11500 	/* recovery disabled */
11501 	if (ri == NULL) {
11502 		un->un_running.pmode = invalid;
11503 		return;
11504 	}
11505 
11506 	/*
11507 	 * If we didn't just read a filemark.
11508 	 */
11509 	if (un->un_pos.eof != ST_EOF_PENDING) {
11510 		ASSERT(nblks != 0 && nfiles == 0);
11511 		/*
11512 		 * If Previously calulated expected position does not match
11513 		 * debug the expected position.
11514 		 */
11515 		if ((ri->pos.pmode != invalid) && nblks &&
11516 		    ((un->un_pos.blkno != ri->pos.blkno) ||
11517 		    (un->un_pos.lgclblkno != ri->pos.lgclblkno))) {
11518 #ifdef STDEBUG
11519 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11520 			    "Expected", &ri->pos);
11521 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11522 			    "But Got", &un->un_pos);
11523 #endif
11524 			un->un_running.pmode = invalid;
11525 		}
11526 	} else {
11527 		ASSERT(nfiles != 0);
11528 		if (un->un_running.pmode != invalid) {
11529 			/*
11530 			 * blkno and lgclblkno already counted in
11531 			 * st_add_recovery_info_to_pkt(). Since a block was not
11532 			 * read and a filemark was.
11533 			 */
11534 			if (attrib->chg_tape_direction == DIR_FORW) {
11535 				un->un_running.fileno++;
11536 				un->un_running.blkno = 0;
11537 			} else if (attrib->chg_tape_direction == DIR_REVC) {
11538 				un->un_running.fileno--;
11539 				un->un_running.blkno = LASTBLK;
11540 			}
11541 		}
11542 	}
11543 }
11544 
11545 static void
11546 st_set_state(struct scsi_tape *un, struct buf *bp)
11547 {
11548 	struct scsi_pkt *sp = BP_PKT(bp);
11549 	struct uscsi_cmd *ucmd;
11550 
11551 	ST_FUNC(ST_DEVINFO, st_set_state);
11552 
11553 	ASSERT(mutex_owned(ST_MUTEX));
11554 	ASSERT(bp != un->un_recov_buf);
11555 
11556 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11557 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
11558 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
11559 
11560 	if (bp != un->un_sbufp) {
11561 #ifdef STDEBUG
11562 		if (DEBUGGING && sp->pkt_resid) {
11563 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11564 			    "pkt_resid %ld bcount %ld\n",
11565 			    sp->pkt_resid, bp->b_bcount);
11566 		}
11567 #endif
11568 		bp->b_resid = sp->pkt_resid;
11569 		if (geterror(bp) != EIO) {
11570 			st_calc_bnum(un, bp, sp);
11571 		}
11572 		if (bp->b_flags & B_READ) {
11573 			un->un_lastop = ST_OP_READ;
11574 			un->un_fmneeded = 0;
11575 		} else {
11576 			un->un_lastop = ST_OP_WRITE;
11577 			if (un->un_dp->options & ST_REEL) {
11578 				un->un_fmneeded = 2;
11579 			} else {
11580 				un->un_fmneeded = 1;
11581 			}
11582 		}
11583 		/*
11584 		 * all is honky dory at this point, so let's
11585 		 * readjust the throttle, to increase speed, if we
11586 		 * have not throttled down.
11587 		 */
11588 		if (un->un_throttle) {
11589 			un->un_throttle = un->un_max_throttle;
11590 		}
11591 	} else {
11592 		optype new_lastop = ST_OP_NIL;
11593 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
11594 
11595 		switch (cmd) {
11596 		case SCMD_WRITE:
11597 		case SCMD_WRITE_G4:
11598 			bp->b_resid = sp->pkt_resid;
11599 			new_lastop = ST_OP_WRITE;
11600 			if (geterror(bp) == EIO) {
11601 				break;
11602 			}
11603 			st_calc_bnum(un, bp, sp);
11604 			if (un->un_dp->options & ST_REEL) {
11605 				un->un_fmneeded = 2;
11606 			} else {
11607 				un->un_fmneeded = 1;
11608 			}
11609 			break;
11610 		case SCMD_READ:
11611 		case SCMD_READ_G4:
11612 			bp->b_resid = sp->pkt_resid;
11613 			new_lastop = ST_OP_READ;
11614 			if (geterror(bp) == EIO) {
11615 				break;
11616 			}
11617 			st_calc_bnum(un, bp, sp);
11618 			un->un_fmneeded = 0;
11619 			break;
11620 		case SCMD_WRITE_FILE_MARK_G4:
11621 		case SCMD_WRITE_FILE_MARK:
11622 		{
11623 			int fmdone;
11624 
11625 			if (un->un_pos.eof != ST_EOM) {
11626 				un->un_pos.eof = ST_NO_EOF;
11627 			}
11628 			fmdone = (bp->b_bcount - bp->b_resid);
11629 			if (fmdone > 0) {
11630 				un->un_lastop = new_lastop = ST_OP_WEOF;
11631 				un->un_pos.lgclblkno += fmdone;
11632 				un->un_pos.fileno += fmdone;
11633 				un->un_pos.blkno = 0;
11634 			} else {
11635 				new_lastop = ST_OP_CTL;
11636 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11637 				    "Flushed buffer\n");
11638 			}
11639 			if (fmdone > un->un_fmneeded) {
11640 				un->un_fmneeded = 0;
11641 			} else {
11642 				un->un_fmneeded -= fmdone;
11643 			}
11644 			break;
11645 		}
11646 		case SCMD_REWIND:
11647 			un->un_pos.eof = ST_NO_EOF;
11648 			un->un_pos.fileno = 0;
11649 			un->un_pos.blkno = 0;
11650 			un->un_pos.lgclblkno = 0;
11651 			if (un->un_pos.pmode != legacy)
11652 				un->un_pos.pmode = legacy;
11653 			new_lastop = ST_OP_CTL;
11654 			un->un_restore_pos = 0;
11655 			break;
11656 
11657 		case SCMD_SPACE:
11658 		case SCMD_SPACE_G4:
11659 		{
11660 			int64_t count;
11661 			int64_t resid;
11662 			int64_t done;
11663 			cmd_attribute const *attrib;
11664 			recov_info *ri = sp->pkt_private;
11665 
11666 			if (ri->privatelen == sizeof (recov_info)) {
11667 				attrib = ri->cmd_attrib;
11668 			} else {
11669 				attrib =
11670 				    st_lookup_cmd_attribute(sp->pkt_cdbp[0]);
11671 			}
11672 
11673 			resid = (int64_t)SPACE_CNT(bp->b_resid);
11674 			count = (int64_t)attrib->get_cnt(sp->pkt_cdbp);
11675 
11676 			if (count >= 0) {
11677 				done = (count - resid);
11678 			} else {
11679 				done = ((-count) - resid);
11680 			}
11681 			if (done > 0) {
11682 				un->un_lastop = new_lastop = ST_OP_CTL;
11683 			} else {
11684 				new_lastop = ST_OP_CTL;
11685 			}
11686 
11687 			ST_SPAC(ST_DEVINFO, st_label, CE_WARN,
11688 			    "space cmd: cdb[1] = %s\n"
11689 			    "space data:       = 0x%lx\n"
11690 			    "space count:      = %"PRId64"\n"
11691 			    "space resid:      = %"PRId64"\n"
11692 			    "spaces done:      = %"PRId64"\n"
11693 			    "fileno before     = %d\n"
11694 			    "blkno before      = %d\n",
11695 			    space_strs[sp->pkt_cdbp[1] & 7],
11696 			    bp->b_bcount,
11697 			    count, resid, done,
11698 			    un->un_pos.fileno, un->un_pos.blkno);
11699 
11700 			switch (sp->pkt_cdbp[1]) {
11701 			case SPACE_TYPE(SP_FLM):
11702 				/* Space file forward */
11703 				if (count >= 0) {
11704 					if (un->un_pos.eof <= ST_EOF) {
11705 						un->un_pos.eof = ST_NO_EOF;
11706 					}
11707 					un->un_pos.fileno += done;
11708 					un->un_pos.blkno = 0;
11709 					break;
11710 				}
11711 				/* Space file backward */
11712 				if (done > un->un_pos.fileno) {
11713 					un->un_pos.fileno = 0;
11714 					un->un_pos.blkno = 0;
11715 				} else {
11716 					un->un_pos.fileno -= done;
11717 					un->un_pos.blkno = LASTBLK;
11718 					un->un_running.pmode = invalid;
11719 				}
11720 				break;
11721 			case SPACE_TYPE(SP_BLK):
11722 				/* Space block forward */
11723 				if (count >= 0) {
11724 					un->un_pos.blkno += done;
11725 					break;
11726 				}
11727 				/* Space block backward */
11728 				if (un->un_pos.eof >= ST_EOF_PENDING) {
11729 				/*
11730 				 * we stepped back into
11731 				 * a previous file; we are not
11732 				 * making an effort to pretend that
11733 				 * we are still in the current file
11734 				 * ie. logical == physical position
11735 				 * and leave it to st_ioctl to correct
11736 				 */
11737 					if (done > un->un_pos.blkno) {
11738 						un->un_pos.blkno = 0;
11739 					} else {
11740 						un->un_pos.fileno--;
11741 						un->un_pos.blkno = LASTBLK;
11742 						un->un_running.pmode = invalid;
11743 					}
11744 				} else {
11745 					un->un_pos.blkno -= done;
11746 				}
11747 				break;
11748 			case SPACE_TYPE(SP_SQFLM):
11749 				un->un_pos.pmode = logical;
11750 				un->un_pos.blkno = 0;
11751 				un->un_lastop = new_lastop = ST_OP_CTL;
11752 				break;
11753 			case SPACE_TYPE(SP_EOD):
11754 				un->un_pos.pmode = logical;
11755 				un->un_pos.eof = ST_EOM;
11756 				un->un_status = KEY_BLANK_CHECK;
11757 				break;
11758 			default:
11759 				un->un_pos.pmode = invalid;
11760 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11761 				    "Unsupported space cmd: %s\n",
11762 				    space_strs[sp->pkt_cdbp[1] & 7]);
11763 
11764 				un->un_lastop = new_lastop = ST_OP_CTL;
11765 			}
11766 
11767 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11768 			    "after_space rs %"PRId64" fil %d blk %d\n",
11769 			    resid, un->un_pos.fileno, un->un_pos.blkno);
11770 
11771 			break;
11772 		}
11773 		case SCMD_LOAD:
11774 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
11775 				un->un_pos.fileno = 0;
11776 				if (un->un_pos.pmode != legacy)
11777 					un->un_pos.pmode = legacy;
11778 			} else {
11779 				un->un_state = ST_STATE_OFFLINE;
11780 				un->un_pos.pmode = invalid;
11781 
11782 			}
11783 			/*
11784 			 * If we are loading or unloading we expect the media id
11785 			 * to change. Lets make it unknown.
11786 			 */
11787 			if (un->un_media_id != bogusID && un->un_media_id_len) {
11788 				kmem_free(un->un_media_id, un->un_media_id_len);
11789 				un->un_media_id = NULL;
11790 				un->un_media_id_len = 0;
11791 			}
11792 			un->un_density_known = 0;
11793 			un->un_pos.eof = ST_NO_EOF;
11794 			un->un_pos.blkno = 0;
11795 			un->un_lastop = new_lastop = ST_OP_CTL;
11796 			break;
11797 		case SCMD_ERASE:
11798 			un->un_pos.eof = ST_NO_EOF;
11799 			un->un_pos.blkno = 0;
11800 			un->un_pos.fileno = 0;
11801 			un->un_pos.lgclblkno = 0;
11802 			if (un->un_pos.pmode != legacy)
11803 				un->un_pos.pmode = legacy;
11804 			new_lastop = ST_OP_CTL;
11805 			break;
11806 		case SCMD_RESERVE:
11807 			un->un_rsvd_status |= ST_RESERVE;
11808 			un->un_rsvd_status &=
11809 			    ~(ST_RELEASE | ST_LOST_RESERVE |
11810 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11811 			new_lastop = ST_OP_CTL;
11812 			break;
11813 		case SCMD_RELEASE:
11814 			un->un_rsvd_status |= ST_RELEASE;
11815 			un->un_rsvd_status &=
11816 			    ~(ST_RESERVE | ST_LOST_RESERVE |
11817 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11818 			new_lastop = ST_OP_CTL;
11819 			break;
11820 		case SCMD_PERSISTENT_RESERVE_IN:
11821 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11822 			    "PGR_IN command\n");
11823 			new_lastop = ST_OP_CTL;
11824 			break;
11825 		case SCMD_PERSISTENT_RESERVE_OUT:
11826 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
11827 			case ST_SA_SCSI3_RESERVE:
11828 			case ST_SA_SCSI3_PREEMPT:
11829 			case ST_SA_SCSI3_PREEMPTANDABORT:
11830 				un->un_rsvd_status |=
11831 				    (ST_APPLICATION_RESERVATIONS | ST_RESERVE);
11832 				un->un_rsvd_status &= ~(ST_RELEASE |
11833 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11834 				    ST_INITIATED_RESET);
11835 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11836 				    "PGR Reserve and set: entering"
11837 				    " ST_APPLICATION_RESERVATIONS mode");
11838 				break;
11839 			case ST_SA_SCSI3_REGISTER:
11840 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11841 				    "PGR Reserve register key");
11842 				un->un_rsvd_status |= ST_INIT_RESERVE;
11843 				break;
11844 			case ST_SA_SCSI3_CLEAR:
11845 				un->un_rsvd_status &= ~ST_INIT_RESERVE;
11846 				/* FALLTHROUGH */
11847 			case ST_SA_SCSI3_RELEASE:
11848 				un->un_rsvd_status &=
11849 				    ~(ST_APPLICATION_RESERVATIONS | ST_RESERVE |
11850 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11851 				    ST_INITIATED_RESET);
11852 				un->un_rsvd_status |= ST_RELEASE;
11853 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11854 				    "PGR Release and reset: exiting"
11855 				    " ST_APPLICATION_RESERVATIONS mode");
11856 				break;
11857 			}
11858 			new_lastop = ST_OP_CTL;
11859 			break;
11860 		case SCMD_TEST_UNIT_READY:
11861 		case SCMD_READ_BLKLIM:
11862 		case SCMD_REQUEST_SENSE:
11863 		case SCMD_INQUIRY:
11864 		case SCMD_RECOVER_BUF:
11865 		case SCMD_MODE_SELECT:
11866 		case SCMD_MODE_SENSE:
11867 		case SCMD_DOORLOCK:
11868 		case SCMD_READ_BUFFER:
11869 		case SCMD_REPORT_DENSITIES:
11870 		case SCMD_LOG_SELECT_G1:
11871 		case SCMD_LOG_SENSE_G1:
11872 		case SCMD_REPORT_LUNS:
11873 		case SCMD_READ_ATTRIBUTE:
11874 		case SCMD_WRITE_ATTRIBUTE:
11875 		case SCMD_SVC_ACTION_IN_G5:
11876 			new_lastop = ST_OP_CTL;
11877 			break;
11878 		case SCMD_READ_POSITION:
11879 			new_lastop = ST_OP_CTL;
11880 			/*
11881 			 * Only if the buf used was un_sbufp.
11882 			 * Among other things the prevents read positions used
11883 			 * as part of error recovery from messing up our
11884 			 * current position as they will use un_recov_buf.
11885 			 */
11886 			if (USCSI_CMD(bp)) {
11887 				(void) st_get_read_pos(un, bp);
11888 			}
11889 			break;
11890 		case SCMD_LOCATE:
11891 		case SCMD_LOCATE_G4:
11892 			/* Locate makes position mode no longer legacy */
11893 			un->un_lastop = new_lastop = ST_OP_CTL;
11894 			break;
11895 		case SCMD_MAINTENANCE_IN:
11896 			switch (sp->pkt_cdbp[1]) {
11897 			case SSVC_ACTION_GET_SUPPORTED_OPERATIONS:
11898 			case SSVC_ACTION_SET_TARGET_PORT_GROUPS:
11899 				new_lastop = ST_OP_CTL;
11900 				break;
11901 			}
11902 			if (new_lastop != ST_OP_NIL) {
11903 				break;
11904 			}
11905 		default:
11906 			/*
11907 			 * Unknown command, If was USCSI and USCSI_SILENT
11908 			 * flag was not set, set position to unknown.
11909 			 */
11910 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
11911 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
11912 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11913 				    "unknown cmd 0x%X caused loss of state\n",
11914 				    cmd);
11915 			} else {
11916 				/*
11917 				 * keep the old agreement to allow unknown
11918 				 * commands with the USCSI_SILENT set.
11919 				 * This prevents ASSERT below.
11920 				 */
11921 				new_lastop = ST_OP_CTL;
11922 				break;
11923 			}
11924 			/* FALLTHROUGH */
11925 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
11926 			un->un_pos.pmode = invalid;
11927 			un->un_lastop = new_lastop = ST_OP_CTL;
11928 			break;
11929 		}
11930 
11931 		/* new_lastop should have been changed */
11932 		ASSERT(new_lastop != ST_OP_NIL);
11933 
11934 		/* If un_lastop should copy new_lastop  */
11935 		if (((un->un_lastop == ST_OP_WRITE) ||
11936 		    (un->un_lastop == ST_OP_WEOF)) &&
11937 		    new_lastop != ST_OP_CTL) {
11938 			un->un_lastop = new_lastop;
11939 		}
11940 	}
11941 
11942 	/*
11943 	 * In the st driver we have a logical and physical file position.
11944 	 * Under BSD behavior, when you get a zero read, the logical position
11945 	 * is before the filemark but after the last record of the file.
11946 	 * The physical position is after the filemark. MTIOCGET should always
11947 	 * return the logical file position.
11948 	 *
11949 	 * The next read gives a silent skip to the next file.
11950 	 * Under SVR4, the logical file position remains before the filemark
11951 	 * until the file is closed or a space operation is performed.
11952 	 * Hence set err_resid and err_file before changing fileno if case
11953 	 * BSD Behaviour.
11954 	 */
11955 	un->un_err_resid = bp->b_resid;
11956 	COPY_POS(&un->un_err_pos, &un->un_pos);
11957 
11958 
11959 	/*
11960 	 * If we've seen a filemark via the last read operation
11961 	 * advance the file counter, but mark things such that
11962 	 * the next read operation gets a zero count. We have
11963 	 * to put this here to handle the case of sitting right
11964 	 * at the end of a tape file having seen the file mark,
11965 	 * but the tape is closed and then re-opened without
11966 	 * any further i/o. That is, the position information
11967 	 * must be updated before a close.
11968 	 */
11969 
11970 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
11971 		/*
11972 		 * If we're a 1/2" tape, and we get a filemark
11973 		 * right on block 0, *AND* we were not in the
11974 		 * first file on the tape, and we've hit logical EOM.
11975 		 * We'll mark the state so that later we do the
11976 		 * right thing (in st_close(), st_strategy() or
11977 		 * st_ioctl()).
11978 		 *
11979 		 */
11980 		if ((un->un_dp->options & ST_REEL) &&
11981 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
11982 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
11983 			un->un_pos.eof = ST_EOT_PENDING;
11984 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11985 			    "eot pending\n");
11986 			un->un_pos.fileno++;
11987 			un->un_pos.blkno = 0;
11988 		} else if (BSD_BEHAVIOR) {
11989 			/*
11990 			 * If the read of the filemark was a side effect
11991 			 * of reading some blocks (i.e., data was actually
11992 			 * read), then the EOF mark is pending and the
11993 			 * bump into the next file awaits the next read
11994 			 * operation (which will return a zero count), or
11995 			 * a close or a space operation, else the bump
11996 			 * into the next file occurs now.
11997 			 */
11998 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11999 			    "resid=%lx, bcount=%lx\n",
12000 			    bp->b_resid, bp->b_bcount);
12001 
12002 			if (bp->b_resid != bp->b_bcount) {
12003 				un->un_pos.eof = ST_EOF;
12004 			} else {
12005 				un->un_silent_skip = 1;
12006 				un->un_pos.eof = ST_NO_EOF;
12007 				un->un_pos.fileno++;
12008 				un->un_pos.lgclblkno++;
12009 				un->un_save_blkno = un->un_pos.blkno;
12010 				un->un_pos.blkno = 0;
12011 			}
12012 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12013 			    "eof of file %d, eof=%d\n",
12014 			    un->un_pos.fileno, un->un_pos.eof);
12015 		} else if (SVR4_BEHAVIOR) {
12016 			/*
12017 			 * If the read of the filemark was a side effect
12018 			 * of reading some blocks (i.e., data was actually
12019 			 * read), then the next read should return 0
12020 			 */
12021 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12022 			    "resid=%lx, bcount=%lx\n",
12023 			    bp->b_resid, bp->b_bcount);
12024 			if (bp->b_resid == bp->b_bcount) {
12025 				un->un_pos.eof = ST_EOF;
12026 			}
12027 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12028 			    "eof of file=%d, eof=%d\n",
12029 			    un->un_pos.fileno, un->un_pos.eof);
12030 		}
12031 	}
12032 }
12033 
12034 /*
12035  * set the correct un_errno, to take corner cases into consideration
12036  */
12037 static void
12038 st_set_pe_errno(struct scsi_tape *un)
12039 {
12040 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
12041 
12042 	ASSERT(mutex_owned(ST_MUTEX));
12043 
12044 	/* if errno is already set, don't reset it */
12045 	if (un->un_errno)
12046 		return;
12047 
12048 	/* here un_errno == 0 */
12049 	/*
12050 	 * if the last transfer before flushing all the
12051 	 * waiting I/O's, was 0 (resid = count), then we
12052 	 * want to give the user an error on all the rest,
12053 	 * so here.  If there was a transfer, we set the
12054 	 * resid and counts to 0, and let it drop through,
12055 	 * giving a zero return.  the next I/O will then
12056 	 * give an error.
12057 	 */
12058 	if (un->un_last_resid == un->un_last_count) {
12059 		switch (un->un_pos.eof) {
12060 		case ST_EOM:
12061 			un->un_errno = ENOMEM;
12062 			break;
12063 		case ST_EOT:
12064 		case ST_EOF:
12065 			un->un_errno = EIO;
12066 			break;
12067 		}
12068 	} else {
12069 		/*
12070 		 * we know they did not have a zero, so make
12071 		 * sure they get one
12072 		 */
12073 		un->un_last_resid = un->un_last_count = 0;
12074 	}
12075 }
12076 
12077 
12078 /*
12079  * send in a marker pkt to terminate flushing of commands by BBA (via
12080  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
12081  */
12082 static void
12083 st_hba_unflush(struct scsi_tape *un)
12084 {
12085 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
12086 
12087 	ASSERT(mutex_owned(ST_MUTEX));
12088 
12089 	if (!un->un_flush_on_errors)
12090 		return;
12091 
12092 #ifdef FLUSH_ON_ERRORS
12093 
12094 	if (!un->un_mkr_pkt) {
12095 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
12096 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
12097 
12098 		/* we slept, so it must be there */
12099 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
12100 	}
12101 
12102 	st_transport(un, un->un_mkr_pkt);
12103 #endif
12104 }
12105 
12106 static char *
12107 st_print_scsi_cmd(char cmd)
12108 {
12109 	char tmp[64];
12110 	char *cpnt;
12111 
12112 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
12113 	/* tmp goes out of scope on return and caller sees garbage */
12114 	if (cpnt == tmp) {
12115 		cpnt = "Unknown Command";
12116 	}
12117 	return (cpnt);
12118 }
12119 
12120 static void
12121 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
12122     char *title, char *cdb)
12123 {
12124 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
12125 	char buf[256];
12126 	struct scsi_tape *un;
12127 	int instance = ddi_get_instance(dip);
12128 
12129 	un = ddi_get_soft_state(st_state, instance);
12130 
12131 	ST_FUNC(dip, st_print_cdb);
12132 
12133 	/* force one line output so repeated commands are printed once */
12134 	if ((st_debug & 0x180) == 0x100) {
12135 		scsi_log(dip, label, level, "node %s cmd %s\n",
12136 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
12137 		return;
12138 	}
12139 
12140 	/* force one line output so repeated CDB's are printed once */
12141 	if ((st_debug & 0x180) == 0x80) {
12142 		st_clean_print(dip, label, level, NULL, cdb, len);
12143 	} else {
12144 		(void) sprintf(buf, "%s for cmd(%s)", title,
12145 		    st_print_scsi_cmd(*cdb));
12146 		st_clean_print(dip, label, level, buf, cdb, len);
12147 	}
12148 }
12149 
12150 static void
12151 st_clean_print(dev_info_t *dev, char *label, uint_t level,
12152     char *title, char *data, int len)
12153 {
12154 	int	i;
12155 	int 	c;
12156 	char	*format;
12157 	char	buf[256];
12158 	uchar_t	byte;
12159 
12160 	ST_FUNC(dev, st_clean_print);
12161 
12162 
12163 	if (title) {
12164 		(void) sprintf(buf, "%s:\n", title);
12165 		scsi_log(dev, label, level, "%s", buf);
12166 		level = CE_CONT;
12167 	}
12168 
12169 	for (i = 0; i < len; ) {
12170 		buf[0] = 0;
12171 		for (c = 0; c < 8 && i < len; c++, i++) {
12172 			byte = (uchar_t)data[i];
12173 			if (byte < 0x10)
12174 				format = "0x0%x ";
12175 			else
12176 				format = "0x%x ";
12177 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
12178 		}
12179 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
12180 
12181 		scsi_log(dev, label, level, "%s\n", buf);
12182 		level = CE_CONT;
12183 	}
12184 }
12185 
12186 /*
12187  * Conditionally enabled debugging
12188  */
12189 #ifdef	STDEBUG
12190 static void
12191 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
12192 {
12193 	char tmpbuf[64];
12194 
12195 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
12196 
12197 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12198 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
12199 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
12200 	    count, count,
12201 	    wait == ASYNC_CMD ? "a" : "");
12202 }
12203 #endif	/* STDEBUG */
12204 
12205 /*
12206  * Returns pointer to name of minor node name of device 'dev'.
12207  */
12208 static char *
12209 st_dev_name(dev_t dev)
12210 {
12211 	struct scsi_tape *un;
12212 	const char density[] = { 'l', 'm', 'h', 'c' };
12213 	static char name[32];
12214 	minor_t minor;
12215 	int instance;
12216 	int nprt = 0;
12217 
12218 	minor = getminor(dev);
12219 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
12220 	un = ddi_get_soft_state(st_state, instance);
12221 	if (un) {
12222 		ST_FUNC(ST_DEVINFO, st_dev_name);
12223 	}
12224 
12225 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
12226 
12227 	if (minor & MT_BSD) {
12228 		name[++nprt] = 'b';
12229 	}
12230 
12231 	if (minor & MT_NOREWIND) {
12232 		name[++nprt] = 'n';
12233 	}
12234 
12235 	/* NULL terminator */
12236 	name[++nprt] = 0;
12237 
12238 	return (name);
12239 }
12240 
12241 /*
12242  * Soft error reporting, so far unique to each drive
12243  *
12244  * Currently supported: exabyte and DAT soft error reporting
12245  */
12246 static int
12247 st_report_exabyte_soft_errors(dev_t dev, int flag)
12248 {
12249 	uchar_t *sensep;
12250 	int amt;
12251 	int rval = 0;
12252 	char cdb[CDB_GROUP0], *c = cdb;
12253 	struct uscsi_cmd *com;
12254 
12255 	GET_SOFT_STATE(dev);
12256 
12257 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
12258 
12259 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12260 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
12261 	    dev, flag);
12262 
12263 	ASSERT(mutex_owned(ST_MUTEX));
12264 
12265 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12266 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
12267 
12268 	*c++ = SCMD_REQUEST_SENSE;
12269 	*c++ = 0;
12270 	*c++ = 0;
12271 	*c++ = 0;
12272 	*c++ = TAPE_SENSE_LENGTH;
12273 	/*
12274 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
12275 	 */
12276 	*c   = (char)0x80;
12277 
12278 	com->uscsi_cdb = cdb;
12279 	com->uscsi_cdblen = CDB_GROUP0;
12280 	com->uscsi_bufaddr = (caddr_t)sensep;
12281 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
12282 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12283 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12284 
12285 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12286 	if (rval || com->uscsi_status) {
12287 		goto done;
12288 	}
12289 
12290 	/*
12291 	 * was there enough data?
12292 	 */
12293 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
12294 
12295 	if ((amt >= 19) && un->un_kbytes_xferred) {
12296 		uint_t count, error_rate;
12297 		uint_t rate;
12298 
12299 		if (sensep[21] & CLN) {
12300 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12301 			    "Periodic head cleaning required");
12302 		}
12303 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
12304 			goto done;
12305 		}
12306 		/*
12307 		 * check if soft error reporting needs to be done.
12308 		 */
12309 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
12310 		count &= 0xffffff;
12311 		error_rate = (count * 100)/un->un_kbytes_xferred;
12312 
12313 #ifdef	STDEBUG
12314 		if (st_soft_error_report_debug) {
12315 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12316 			    "Exabyte Soft Error Report:\n");
12317 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12318 			    "read/write error counter: %d\n", count);
12319 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12320 			    "number of bytes transferred: %dK\n",
12321 			    un->un_kbytes_xferred);
12322 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12323 			    "error_rate: %d%%\n", error_rate);
12324 
12325 			if (amt >= 22) {
12326 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12327 				    "unit sense: 0x%b 0x%b 0x%b\n",
12328 				    sensep[19], SENSE_19_BITS,
12329 				    sensep[20], SENSE_20_BITS,
12330 				    sensep[21], SENSE_21_BITS);
12331 			}
12332 			if (amt >= 27) {
12333 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12334 				    "tracking retry counter: %d\n",
12335 				    sensep[26]);
12336 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12337 				    "read/write retry counter: %d\n",
12338 				    sensep[27]);
12339 			}
12340 		}
12341 #endif
12342 
12343 		if (flag & FWRITE) {
12344 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
12345 		} else {
12346 			rate = EXABYTE_READ_ERROR_THRESHOLD;
12347 		}
12348 		if (error_rate >= rate) {
12349 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12350 			    "Soft error rate (%d%%) during %s was too high",
12351 			    error_rate,
12352 			    ((flag & FWRITE) ? wrg_str : rdg_str));
12353 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12354 			    "Please, replace tape cartridge\n");
12355 		}
12356 	}
12357 
12358 done:
12359 	kmem_free(com, sizeof (*com));
12360 	kmem_free(sensep, TAPE_SENSE_LENGTH);
12361 
12362 	if (rval != 0) {
12363 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12364 		    "exabyte soft error reporting failed\n");
12365 	}
12366 	return (rval);
12367 }
12368 
12369 /*
12370  * this is very specific to Archive 4mm dat
12371  */
12372 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
12373 
12374 static int
12375 st_report_dat_soft_errors(dev_t dev, int flag)
12376 {
12377 	uchar_t *sensep;
12378 	int amt, i;
12379 	int rval = 0;
12380 	char cdb[CDB_GROUP1], *c = cdb;
12381 	struct uscsi_cmd *com;
12382 	struct scsi_arq_status status;
12383 
12384 	GET_SOFT_STATE(dev);
12385 
12386 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
12387 
12388 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12389 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12390 
12391 	ASSERT(mutex_owned(ST_MUTEX));
12392 
12393 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12394 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12395 
12396 	*c++ = SCMD_LOG_SENSE_G1;
12397 	*c++ = 0;
12398 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
12399 	*c++ = 0;
12400 	*c++ = 0;
12401 	*c++ = 0;
12402 	*c++ = 2;
12403 	*c++ = 0;
12404 	*c++ = (char)LOG_SENSE_LENGTH;
12405 	*c   = 0;
12406 	com->uscsi_cdb    = cdb;
12407 	com->uscsi_cdblen  = CDB_GROUP1;
12408 	com->uscsi_bufaddr = (caddr_t)sensep;
12409 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
12410 	com->uscsi_rqlen = sizeof (status);
12411 	com->uscsi_rqbuf = (caddr_t)&status;
12412 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
12413 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12414 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12415 	if (rval) {
12416 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12417 		    "DAT soft error reporting failed\n");
12418 	}
12419 	if (rval || com->uscsi_status) {
12420 		goto done;
12421 	}
12422 
12423 	/*
12424 	 * was there enough data?
12425 	 */
12426 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
12427 
12428 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
12429 		int total, retries, param_code;
12430 
12431 		total = -1;
12432 		retries = -1;
12433 		amt = sensep[3] + 4;
12434 
12435 
12436 #ifdef STDEBUG
12437 		if (st_soft_error_report_debug) {
12438 			(void) printf("logsense:");
12439 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
12440 				if (i % 16 == 0) {
12441 					(void) printf("\t\n");
12442 				}
12443 				(void) printf(" %x", sensep[i]);
12444 			}
12445 			(void) printf("\n");
12446 		}
12447 #endif
12448 
12449 		/*
12450 		 * parse the param_codes
12451 		 */
12452 		if (sensep[0] == 2 || sensep[0] == 3) {
12453 			for (i = 4; i < amt; i++) {
12454 				param_code = (sensep[i++] << 8);
12455 				param_code += sensep[i++];
12456 				i++; /* skip control byte */
12457 				if (param_code == 5) {
12458 					if (sensep[i++] == 4) {
12459 						total = (sensep[i++] << 24);
12460 						total += (sensep[i++] << 16);
12461 						total += (sensep[i++] << 8);
12462 						total += sensep[i];
12463 					}
12464 				} else if (param_code == 0x8007) {
12465 					if (sensep[i++] == 2) {
12466 						retries = sensep[i++] << 8;
12467 						retries += sensep[i];
12468 					}
12469 				} else {
12470 					i += sensep[i];
12471 				}
12472 			}
12473 		}
12474 
12475 		/*
12476 		 * if the log sense returned valid numbers then determine
12477 		 * the read and write error thresholds based on the amount of
12478 		 * data transferred
12479 		 */
12480 
12481 		if (total > 0 && retries > 0) {
12482 			short normal_retries = 0;
12483 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12484 			    "total xferred (%s) =%x, retries=%x\n",
12485 			    ((flag & FWRITE) ? wrg_str : rdg_str),
12486 			    total, retries);
12487 
12488 			if (flag & FWRITE) {
12489 				if (total <=
12490 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
12491 					normal_retries =
12492 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
12493 				} else {
12494 					normal_retries =
12495 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
12496 				}
12497 			} else {
12498 				if (total <=
12499 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
12500 					normal_retries =
12501 					    DAT_SMALL_READ_ERROR_THRESHOLD;
12502 				} else {
12503 					normal_retries =
12504 					    DAT_LARGE_READ_ERROR_THRESHOLD;
12505 				}
12506 			}
12507 
12508 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12509 			"normal retries=%d\n", normal_retries);
12510 
12511 			if (retries >= normal_retries) {
12512 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12513 				    "Soft error rate (retries = %d) during "
12514 				    "%s was too high",  retries,
12515 				    ((flag & FWRITE) ? wrg_str : rdg_str));
12516 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12517 				    "Periodic head cleaning required "
12518 				    "and/or replace tape cartridge\n");
12519 			}
12520 
12521 		} else if (total == -1 || retries == -1) {
12522 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12523 			    "log sense parameter code does not make sense\n");
12524 		}
12525 	}
12526 
12527 	/*
12528 	 * reset all values
12529 	 */
12530 	c = cdb;
12531 	*c++ = SCMD_LOG_SELECT_G1;
12532 	*c++ = 2;	/* this resets all values */
12533 	*c++ = (char)0xc0;
12534 	*c++ = 0;
12535 	*c++ = 0;
12536 	*c++ = 0;
12537 	*c++ = 0;
12538 	*c++ = 0;
12539 	*c++ = 0;
12540 	*c   = 0;
12541 	com->uscsi_bufaddr = NULL;
12542 	com->uscsi_buflen  = 0;
12543 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
12544 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12545 	if (rval) {
12546 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12547 		    "DAT soft error reset failed\n");
12548 	}
12549 done:
12550 	kmem_free(com, sizeof (*com));
12551 	kmem_free(sensep, LOG_SENSE_LENGTH);
12552 	return (rval);
12553 }
12554 
12555 static int
12556 st_report_soft_errors(dev_t dev, int flag)
12557 {
12558 	GET_SOFT_STATE(dev);
12559 
12560 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
12561 
12562 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12563 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12564 
12565 	ASSERT(mutex_owned(ST_MUTEX));
12566 
12567 	switch (un->un_dp->type) {
12568 	case ST_TYPE_EXB8500:
12569 	case ST_TYPE_EXABYTE:
12570 		return (st_report_exabyte_soft_errors(dev, flag));
12571 		/*NOTREACHED*/
12572 	case ST_TYPE_PYTHON:
12573 		return (st_report_dat_soft_errors(dev, flag));
12574 		/*NOTREACHED*/
12575 	default:
12576 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
12577 		return (-1);
12578 	}
12579 }
12580 
12581 /*
12582  * persistent error routines
12583  */
12584 
12585 /*
12586  * enable persistent errors, and set the throttle appropriately, checking
12587  * for flush-on-errors capability
12588  */
12589 static void
12590 st_turn_pe_on(struct scsi_tape *un)
12591 {
12592 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
12593 
12594 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
12595 	ASSERT(mutex_owned(ST_MUTEX));
12596 
12597 	un->un_persistence = 1;
12598 
12599 	/*
12600 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
12601 	 * enabled.  This will simplify the error handling for request senses
12602 	 */
12603 
12604 	if (un->un_arq_enabled && un->un_untagged_qing) {
12605 		uchar_t f_o_e;
12606 
12607 		mutex_exit(ST_MUTEX);
12608 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
12609 		    1 : 0;
12610 		mutex_enter(ST_MUTEX);
12611 
12612 		un->un_flush_on_errors = f_o_e;
12613 	} else {
12614 		un->un_flush_on_errors = 0;
12615 	}
12616 
12617 	if (un->un_flush_on_errors)
12618 		un->un_max_throttle = (uchar_t)st_max_throttle;
12619 	else
12620 		un->un_max_throttle = 1;
12621 
12622 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
12623 		un->un_max_throttle = 1;
12624 
12625 	/* this will send a marker pkt */
12626 	st_clear_pe(un);
12627 }
12628 
12629 /*
12630  * This turns persistent errors permanently off
12631  */
12632 static void
12633 st_turn_pe_off(struct scsi_tape *un)
12634 {
12635 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
12636 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
12637 	ASSERT(mutex_owned(ST_MUTEX));
12638 
12639 	/* turn it off for good */
12640 	un->un_persistence = 0;
12641 
12642 	/* this will send a marker pkt */
12643 	st_clear_pe(un);
12644 
12645 	/* turn off flush on error capability, if enabled */
12646 	if (un->un_flush_on_errors) {
12647 		mutex_exit(ST_MUTEX);
12648 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
12649 		mutex_enter(ST_MUTEX);
12650 	}
12651 
12652 
12653 	un->un_flush_on_errors = 0;
12654 }
12655 
12656 /*
12657  * This clear persistent errors, allowing more commands through, and also
12658  * sending a marker packet.
12659  */
12660 static void
12661 st_clear_pe(struct scsi_tape *un)
12662 {
12663 	ST_FUNC(ST_DEVINFO, st_clear_pe);
12664 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
12665 	ASSERT(mutex_owned(ST_MUTEX));
12666 
12667 	un->un_persist_errors = 0;
12668 	un->un_throttle = un->un_last_throttle = 1;
12669 	un->un_errno = 0;
12670 	st_hba_unflush(un);
12671 }
12672 
12673 /*
12674  * This will flag persistent errors, shutting everything down, if the
12675  * application had enabled persistent errors via MTIOCPERSISTENT
12676  */
12677 static void
12678 st_set_pe_flag(struct scsi_tape *un)
12679 {
12680 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
12681 	ASSERT(mutex_owned(ST_MUTEX));
12682 
12683 	if (un->un_persistence) {
12684 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
12685 		un->un_persist_errors = 1;
12686 		un->un_throttle = un->un_last_throttle = 0;
12687 		cv_broadcast(&un->un_sbuf_cv);
12688 	}
12689 }
12690 
12691 static int
12692 st_do_reserve(struct scsi_tape *un)
12693 {
12694 	int rval;
12695 	int was_lost = un->un_rsvd_status & ST_LOST_RESERVE;
12696 
12697 	ST_FUNC(ST_DEVINFO, st_do_reserve);
12698 
12699 	/*
12700 	 * Issue a Throw-Away reserve command to clear the
12701 	 * check condition.
12702 	 * If the current behaviour of reserve/release is to
12703 	 * hold reservation across opens , and if a Bus reset
12704 	 * has been issued between opens then this command
12705 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
12706 	 * In this case return an EACCES so that user knows that
12707 	 * reservation has been lost in between opens.
12708 	 * If this error is not returned and we continue with
12709 	 * successful open , then user may think position of the
12710 	 * tape is still the same but inreality we would rewind the
12711 	 * tape and continue from BOT.
12712 	 */
12713 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12714 	if (rval) {
12715 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
12716 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
12717 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
12718 			un->un_errno = EACCES;
12719 			return (EACCES);
12720 		}
12721 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12722 	}
12723 	if (rval == 0) {
12724 		un->un_rsvd_status |= ST_INIT_RESERVE;
12725 	}
12726 	if (was_lost) {
12727 		un->un_running.pmode = invalid;
12728 	}
12729 
12730 	return (rval);
12731 }
12732 
12733 static int
12734 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb)
12735 {
12736 	int rval;
12737 	cmd_attribute const *attrib;
12738 
12739 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
12740 
12741 	/*
12742 	 * If already reserved no need to do it again.
12743 	 * Also if Reserve and Release are disabled Just return.
12744 	 */
12745 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12746 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12747 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12748 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12749 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
12750 		    st_print_scsi_cmd((uchar_t)cdb[0]));
12751 		return (0);
12752 	}
12753 
12754 	/* See if command is on the list */
12755 	attrib = st_lookup_cmd_attribute(cdb[0]);
12756 
12757 	if (attrib == NULL) {
12758 		rval = 1; /* Not found, when in doubt reserve */
12759 	} else if ((attrib->requires_reserve) != 0) {
12760 		rval = 1;
12761 	} else if ((attrib->reserve_byte) != 0) {
12762 		/*
12763 		 * cmd is on list.
12764 		 * if byte is zero always allowed.
12765 		 */
12766 		rval = 1;
12767 	} else if (((cdb[attrib->reserve_byte]) &
12768 	    (attrib->reserve_mask)) != 0) {
12769 		rval = 1;
12770 	} else {
12771 		rval = 0;
12772 	}
12773 
12774 	if (rval) {
12775 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12776 		    "Command %s requires reservation",
12777 		    st_print_scsi_cmd(cdb[0]));
12778 
12779 		rval = st_do_reserve(un);
12780 	}
12781 
12782 	return (rval);
12783 }
12784 
12785 static int
12786 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
12787 {
12788 	int rval;
12789 	cmd_attribute const *attrib;
12790 
12791 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
12792 
12793 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12794 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12795 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12796 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12797 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
12798 		    st_print_scsi_cmd(cmd));
12799 		return (0);
12800 	}
12801 
12802 	/* search for this command on the list */
12803 	attrib = st_lookup_cmd_attribute(cmd);
12804 
12805 	if (attrib == NULL) {
12806 		rval = 1; /* Not found, when in doubt reserve */
12807 	} else if ((attrib->requires_reserve) != 0) {
12808 		rval = 1;
12809 	} else if ((attrib->reserve_byte) != 0) {
12810 		/*
12811 		 * cmd is on list.
12812 		 * if byte is zero always allowed.
12813 		 */
12814 		rval = 1;
12815 	} else if (((attrib->reserve_mask) & cnt) != 0) {
12816 		rval = 1;
12817 	} else {
12818 		rval = 0;
12819 	}
12820 
12821 	if (rval) {
12822 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12823 		    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
12824 
12825 		rval = st_do_reserve(un);
12826 	}
12827 
12828 	return (rval);
12829 }
12830 
12831 static int
12832 st_reserve_release(struct scsi_tape *un, int cmd, ubufunc_t ubf)
12833 {
12834 	struct uscsi_cmd	uscsi_cmd;
12835 	int			rval;
12836 	char			cdb[CDB_GROUP0];
12837 	struct scsi_arq_status	stat;
12838 
12839 
12840 
12841 	ST_FUNC(ST_DEVINFO, st_reserve_release);
12842 
12843 	ASSERT(mutex_owned(ST_MUTEX));
12844 
12845 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12846 	    "st_reserve_release: %s \n",
12847 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
12848 
12849 	bzero(&cdb, CDB_GROUP0);
12850 	if (cmd == ST_RELEASE) {
12851 		cdb[0] = SCMD_RELEASE;
12852 	} else {
12853 		cdb[0] = SCMD_RESERVE;
12854 	}
12855 	bzero(&uscsi_cmd, sizeof (struct uscsi_cmd));
12856 	uscsi_cmd.uscsi_flags = USCSI_WRITE | USCSI_RQENABLE;
12857 	uscsi_cmd.uscsi_cdb = cdb;
12858 	uscsi_cmd.uscsi_cdblen = CDB_GROUP0;
12859 	uscsi_cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
12860 	uscsi_cmd.uscsi_rqbuf = (caddr_t)&stat;
12861 	uscsi_cmd.uscsi_rqlen = sizeof (stat);
12862 
12863 	rval = ubf(un, &uscsi_cmd, FKIOCTL);
12864 
12865 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12866 	    "st_reserve_release: rval(1)=%d\n", rval);
12867 
12868 	if (rval) {
12869 		if (uscsi_cmd.uscsi_status == STATUS_RESERVATION_CONFLICT) {
12870 			rval = EACCES;
12871 		}
12872 		/*
12873 		 * dynamically turn off reserve/release support
12874 		 * in case of drives which do not support
12875 		 * reserve/release command(ATAPI drives).
12876 		 */
12877 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
12878 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
12879 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
12880 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12881 				    "Tape unit does not support "
12882 				    "reserve/release \n");
12883 			}
12884 			rval = 0;
12885 		}
12886 	}
12887 	return (rval);
12888 }
12889 
12890 static int
12891 st_take_ownership(struct scsi_tape *un, ubufunc_t ubf)
12892 {
12893 	int rval;
12894 
12895 	ST_FUNC(ST_DEVINFO, st_take_ownership);
12896 
12897 	ASSERT(mutex_owned(ST_MUTEX));
12898 
12899 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12900 	    "st_take_ownership: Entering ...\n");
12901 
12902 
12903 	rval = st_reserve_release(un, ST_RESERVE, ubf);
12904 	/*
12905 	 * XXX -> Should reset be done only if we get EACCES.
12906 	 * .
12907 	 */
12908 	if (rval) {
12909 		if (st_reset(un, RESET_LUN) == 0) {
12910 			return (EIO);
12911 		}
12912 		un->un_rsvd_status &=
12913 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
12914 
12915 		mutex_exit(ST_MUTEX);
12916 		delay(drv_usectohz(ST_RESERVATION_DELAY));
12917 		mutex_enter(ST_MUTEX);
12918 		/*
12919 		 * remove the check condition.
12920 		 */
12921 		(void) st_reserve_release(un, ST_RESERVE, ubf);
12922 		rval = st_reserve_release(un, ST_RESERVE, ubf);
12923 		if (rval != 0) {
12924 			if ((st_reserve_release(un, ST_RESERVE, ubf))
12925 			    != 0) {
12926 				rval = (un->un_rsvd_status &
12927 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
12928 				return (rval);
12929 			}
12930 		}
12931 		/*
12932 		 * Set tape state to ST_STATE_OFFLINE , in case if
12933 		 * the user wants to continue and start using
12934 		 * the tape.
12935 		 */
12936 		un->un_state = ST_STATE_OFFLINE;
12937 		un->un_rsvd_status |= ST_INIT_RESERVE;
12938 	}
12939 	return (rval);
12940 }
12941 
12942 static int
12943 st_create_errstats(struct scsi_tape *un, int instance)
12944 {
12945 	char	kstatname[KSTAT_STRLEN];
12946 
12947 	ST_FUNC(ST_DEVINFO, st_create_errstats);
12948 
12949 	/*
12950 	 * Create device error kstats
12951 	 */
12952 
12953 	if (un->un_errstats == (kstat_t *)0) {
12954 		(void) sprintf(kstatname, "st%d,err", instance);
12955 		un->un_errstats = kstat_create("sterr", instance, kstatname,
12956 		    "device_error", KSTAT_TYPE_NAMED,
12957 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
12958 		    KSTAT_FLAG_PERSISTENT);
12959 
12960 		if (un->un_errstats) {
12961 			struct st_errstats	*stp;
12962 
12963 			stp = (struct st_errstats *)un->un_errstats->ks_data;
12964 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
12965 			    KSTAT_DATA_ULONG);
12966 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
12967 			    KSTAT_DATA_ULONG);
12968 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
12969 			    KSTAT_DATA_ULONG);
12970 			kstat_named_init(&stp->st_vid, "Vendor",
12971 			    KSTAT_DATA_CHAR);
12972 			kstat_named_init(&stp->st_pid, "Product",
12973 			    KSTAT_DATA_CHAR);
12974 			kstat_named_init(&stp->st_revision, "Revision",
12975 			    KSTAT_DATA_CHAR);
12976 			kstat_named_init(&stp->st_serial, "Serial No",
12977 			    KSTAT_DATA_CHAR);
12978 			un->un_errstats->ks_private = un;
12979 			un->un_errstats->ks_update = nulldev;
12980 			kstat_install(un->un_errstats);
12981 			/*
12982 			 * Fill in the static data
12983 			 */
12984 			(void) strncpy(&stp->st_vid.value.c[0],
12985 			    ST_INQUIRY->inq_vid, 8);
12986 			/*
12987 			 * XXX:  Emulex MT-02 (and emulators) predates
12988 			 *	 SCSI-1 and has no vid & pid inquiry data.
12989 			 */
12990 			if (ST_INQUIRY->inq_len != 0) {
12991 				(void) strncpy(&stp->st_pid.value.c[0],
12992 				    ST_INQUIRY->inq_pid, 16);
12993 				(void) strncpy(&stp->st_revision.value.c[0],
12994 				    ST_INQUIRY->inq_revision, 4);
12995 				(void) strncpy(&stp->st_serial.value.c[0],
12996 				    ST_INQUIRY->inq_serial, 12);
12997 			}
12998 		}
12999 	}
13000 	return (0);
13001 }
13002 
13003 static int
13004 st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos)
13005 {
13006 	int rval;
13007 	bufunc_t bf = (ubf == st_uscsi_rcmd) ? st_rcmd : st_cmd;
13008 
13009 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
13010 
13011 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
13012 	ASSERT(mutex_owned(ST_MUTEX));
13013 
13014 	/* Can't restore an invalid position */
13015 	if (pos->pmode == invalid) {
13016 		return (4);
13017 	}
13018 
13019 	/*
13020 	 * Assumtions:
13021 	 *	If a position was read and is in logical position mode.
13022 	 *	If a drive supports read position it supports locate.
13023 	 *	If the read position type is not NO_POS. even though
13024 	 *	   a read position make not have been attemped yet.
13025 	 *
13026 	 *	The drive can locate to the position.
13027 	 */
13028 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
13029 		/*
13030 		 * If position mode is logical or legacy mode try
13031 		 * to locate there as it is faster.
13032 		 * If it fails try the old way.
13033 		 */
13034 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13035 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
13036 		    pos->lgclblkno);
13037 
13038 		if (st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
13039 		    pos->lgclblkno, pos->partition) == 0) {
13040 			/* Assume we are there copy rest of position back */
13041 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
13042 				COPY_POS(&un->un_pos, pos);
13043 			}
13044 			return (0);
13045 		}
13046 
13047 		/*
13048 		 * If logical block locate failed to restore a logical
13049 		 * position, can't recover.
13050 		 */
13051 		if (pos->pmode == logical) {
13052 			return (-1);
13053 		}
13054 	}
13055 
13056 
13057 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13058 	    "Restoring tape position at fileno=%x, blkno=%x....",
13059 	    pos->fileno, pos->blkno);
13060 
13061 	/*
13062 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
13063 	 * so as not to rewind tape on RESETS: Gee, Has life ever
13064 	 * been simple in tape land ?
13065 	 */
13066 	rval = bf(un, SCMD_REWIND, 0, SYNC_CMD);
13067 	if (rval) {
13068 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
13069 		    "Failed to restore the last file and block position: In"
13070 		    " this state, Tape will be loaded at BOT during next open");
13071 		un->un_pos.pmode = invalid;
13072 		return (rval);
13073 	}
13074 
13075 	/* If the position was as the result of back space file */
13076 	if (pos->blkno > (INF / 2)) {
13077 		/* Go one extra file forward */
13078 		pos->fileno++;
13079 		/* Figure how many blocks to back into the previous file */
13080 		pos->blkno = -(INF - pos->blkno);
13081 	}
13082 
13083 	/* Go to requested fileno */
13084 	if (pos->fileno) {
13085 		rval = st_cmd(un, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
13086 		if (rval) {
13087 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13088 			    "Failed to restore the last file position: In this "
13089 			    " state, Tape will be loaded at BOT during next"
13090 			    " open %d", __LINE__);
13091 			un->un_pos.pmode = invalid;
13092 			pos->pmode = invalid;
13093 			return (rval);
13094 		}
13095 	}
13096 
13097 	/*
13098 	 * If backing into a file we already did an extra file forward.
13099 	 * Now we have to back over the filemark to get to the end of
13100 	 * the previous file. The blkno has been ajusted to a negative
13101 	 * value so we will get to the expected location.
13102 	 */
13103 	if (pos->blkno) {
13104 		rval = bf(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
13105 		if (rval) {
13106 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13107 			    "Failed to restore the last file position: In this "
13108 			    " state, Tape will be loaded at BOT during next"
13109 			    " open %d", __LINE__);
13110 			un->un_pos.pmode = invalid;
13111 			pos->pmode = invalid;
13112 			return (rval);
13113 		}
13114 	}
13115 
13116 	/*
13117 	 * The position mode, block and fileno should be correct,
13118 	 * This updates eof and logical position information.
13119 	 */
13120 	un->un_pos.eof = pos->eof;
13121 	un->un_pos.lgclblkno = pos->lgclblkno;
13122 
13123 	return (0);
13124 }
13125 
13126 /*
13127  * check sense key, ASC, ASCQ in order to determine if the tape needs
13128  * to be ejected
13129  */
13130 
13131 static int
13132 st_check_asc_ascq(struct scsi_tape *un)
13133 {
13134 	struct scsi_extended_sense *sensep = ST_RQSENSE;
13135 	struct tape_failure_code   *code;
13136 
13137 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
13138 
13139 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
13140 		if ((code->key  == sensep->es_key) &&
13141 		    (code->add_code  == sensep->es_add_code) &&
13142 		    (code->qual_code == sensep->es_qual_code))
13143 			return (1);
13144 	}
13145 	return (0);
13146 }
13147 
13148 /*
13149  * st_logpage_supported() sends a Log Sense command with
13150  * page code = 0 = Supported Log Pages Page to the device,
13151  * to see whether the page 'page' is supported.
13152  * Return values are:
13153  * -1 if the Log Sense command fails
13154  * 0 if page is not supported
13155  * 1 if page is supported
13156  */
13157 
13158 static int
13159 st_logpage_supported(struct scsi_tape *un, uchar_t page)
13160 {
13161 	uchar_t *sp, *sensep;
13162 	unsigned length;
13163 	struct uscsi_cmd *com;
13164 	struct scsi_arq_status status;
13165 	int rval;
13166 	char cdb[CDB_GROUP1] = {
13167 		SCMD_LOG_SENSE_G1,
13168 		0,
13169 		SUPPORTED_LOG_PAGES_PAGE,
13170 		0,
13171 		0,
13172 		0,
13173 		0,
13174 		0,
13175 		(char)LOG_SENSE_LENGTH,
13176 		0
13177 	};
13178 
13179 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
13180 
13181 	ASSERT(mutex_owned(ST_MUTEX));
13182 
13183 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13184 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
13185 
13186 	com->uscsi_cdb = cdb;
13187 	com->uscsi_cdblen = CDB_GROUP1;
13188 	com->uscsi_bufaddr = (caddr_t)sensep;
13189 	com->uscsi_buflen = LOG_SENSE_LENGTH;
13190 	com->uscsi_rqlen = sizeof (status);
13191 	com->uscsi_rqbuf = (caddr_t)&status;
13192 	com->uscsi_flags =
13193 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13194 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13195 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13196 	if (rval || com->uscsi_status) {
13197 		/* uscsi-command failed */
13198 		rval = -1;
13199 	} else {
13200 
13201 		sp = sensep + 3;
13202 
13203 		for (length = *sp++; length > 0; length--, sp++) {
13204 
13205 			if (*sp == page) {
13206 				rval = 1;
13207 				break;
13208 			}
13209 		}
13210 	}
13211 	kmem_free(com, sizeof (struct uscsi_cmd));
13212 	kmem_free(sensep, LOG_SENSE_LENGTH);
13213 	return (rval);
13214 }
13215 
13216 
13217 /*
13218  * st_check_clean_bit() gets the status of the tape's cleaning bit.
13219  *
13220  * If the device does support the TapeAlert log page, then the cleaning bit
13221  * information will be read from this page. Otherwise we will see if one of
13222  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
13223  * the device, which means, that we can get the cleaning bit information via
13224  * a RequestSense command.
13225  * If both methods of getting cleaning bit information are not supported
13226  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
13227  * returns with
13228  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
13229  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
13230  * If the call to st_uscsi_cmd() to do the Log Sense or the Request Sense
13231  * command fails, or if the amount of Request Sense data is not enough, then
13232  *  st_check_clean_bit() returns with -1.
13233  */
13234 
13235 static int
13236 st_check_clean_bit(struct scsi_tape *un)
13237 {
13238 	int rval = 0;
13239 
13240 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
13241 
13242 	ASSERT(mutex_owned(ST_MUTEX));
13243 
13244 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
13245 		return (rval);
13246 	}
13247 
13248 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13249 
13250 		rval = st_logpage_supported(un, TAPE_SEQUENTIAL_PAGE);
13251 		if (rval == -1) {
13252 			return (0);
13253 		}
13254 		if (rval == 1) {
13255 
13256 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
13257 		}
13258 
13259 		rval = st_logpage_supported(un, TAPE_ALERT_PAGE);
13260 		if (rval == -1) {
13261 			return (0);
13262 		}
13263 		if (rval == 1) {
13264 
13265 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
13266 		}
13267 
13268 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13269 
13270 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
13271 		}
13272 	}
13273 
13274 	rval = 0;
13275 
13276 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
13277 
13278 		rval = st_check_sequential_clean_bit(un);
13279 		if (rval == -1) {
13280 			return (0);
13281 		}
13282 	}
13283 
13284 	if ((rval == 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
13285 
13286 		rval = st_check_alert_flags(un);
13287 		if (rval == -1) {
13288 			return (0);
13289 		}
13290 	}
13291 
13292 	if ((rval == 0) && (un->un_dp->options & ST_CLN_MASK)) {
13293 
13294 		rval = st_check_sense_clean_bit(un);
13295 		if (rval == -1) {
13296 			return (0);
13297 		}
13298 	}
13299 
13300 	/*
13301 	 * If found a supported means to check need to clean.
13302 	 */
13303 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
13304 
13305 		/*
13306 		 * head needs to be cleaned.
13307 		 */
13308 		if (rval & MTF_TAPE_HEAD_DIRTY) {
13309 
13310 			/*
13311 			 * Print log message only first time
13312 			 * found needing cleaned.
13313 			 */
13314 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
13315 
13316 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
13317 				    "Periodic head cleaning required");
13318 
13319 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
13320 			}
13321 
13322 		} else {
13323 
13324 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
13325 		}
13326 	}
13327 
13328 	return (rval);
13329 }
13330 
13331 
13332 static int
13333 st_check_sequential_clean_bit(struct scsi_tape *un)
13334 {
13335 	int rval;
13336 	int ix;
13337 	ushort_t parameter;
13338 	struct uscsi_cmd *cmd;
13339 	struct log_sequential_page *sp;
13340 	struct log_sequential_page_parameter *prm;
13341 	struct scsi_arq_status status;
13342 	char cdb[CDB_GROUP1] = {
13343 		SCMD_LOG_SENSE_G1,
13344 		0,
13345 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
13346 		0,
13347 		0,
13348 		0,
13349 		0,
13350 		(char)(sizeof (struct log_sequential_page) >> 8),
13351 		(char)(sizeof (struct log_sequential_page)),
13352 		0
13353 	};
13354 
13355 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
13356 
13357 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13358 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
13359 
13360 	cmd->uscsi_flags   =
13361 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13362 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13363 	cmd->uscsi_cdb	   = cdb;
13364 	cmd->uscsi_cdblen  = CDB_GROUP1;
13365 	cmd->uscsi_bufaddr = (caddr_t)sp;
13366 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
13367 	cmd->uscsi_rqlen   = sizeof (status);
13368 	cmd->uscsi_rqbuf   = (caddr_t)&status;
13369 
13370 	rval = st_uscsi_cmd(un, cmd, FKIOCTL);
13371 
13372 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
13373 
13374 		rval = -1;
13375 
13376 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
13377 
13378 		rval = -1;
13379 	}
13380 
13381 	prm = &sp->param[0];
13382 
13383 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
13384 
13385 		if (prm->log_param.length == 0) {
13386 			break;
13387 		}
13388 
13389 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
13390 		    (prm->log_param.pc_lo & 0xff));
13391 
13392 		if (parameter == SEQUENTIAL_NEED_CLN) {
13393 
13394 			rval = MTF_TAPE_CLN_SUPPORTED;
13395 			if (prm->param_value[prm->log_param.length - 1]) {
13396 
13397 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13398 				    "sequential log says head dirty\n");
13399 				rval |= MTF_TAPE_HEAD_DIRTY;
13400 			}
13401 		}
13402 		prm = (struct log_sequential_page_parameter *)
13403 		    &prm->param_value[prm->log_param.length];
13404 	}
13405 
13406 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13407 	kmem_free(sp,  sizeof (struct log_sequential_page));
13408 
13409 	return (rval);
13410 }
13411 
13412 
13413 static int
13414 st_check_alert_flags(struct scsi_tape *un)
13415 {
13416 	struct st_tape_alert *ta;
13417 	struct uscsi_cmd *com;
13418 	struct scsi_arq_status status;
13419 	unsigned ix, length;
13420 	int rval;
13421 	tape_alert_flags flag;
13422 	char cdb[CDB_GROUP1] = {
13423 		SCMD_LOG_SENSE_G1,
13424 		0,
13425 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
13426 		0,
13427 		0,
13428 		0,
13429 		0,
13430 		(char)(sizeof (struct st_tape_alert) >> 8),
13431 		(char)(sizeof (struct st_tape_alert)),
13432 		0
13433 	};
13434 
13435 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
13436 
13437 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13438 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
13439 
13440 	com->uscsi_cdb = cdb;
13441 	com->uscsi_cdblen = CDB_GROUP1;
13442 	com->uscsi_bufaddr = (caddr_t)ta;
13443 	com->uscsi_buflen = sizeof (struct st_tape_alert);
13444 	com->uscsi_rqlen = sizeof (status);
13445 	com->uscsi_rqbuf = (caddr_t)&status;
13446 	com->uscsi_flags =
13447 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13448 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13449 
13450 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13451 
13452 	if (rval || com->uscsi_status || com->uscsi_resid) {
13453 
13454 		rval = -1; /* uscsi-command failed */
13455 
13456 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
13457 
13458 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13459 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
13460 		rval = -1;
13461 	}
13462 
13463 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
13464 
13465 
13466 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
13467 
13468 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13469 		    "TapeAlert length %d\n", length);
13470 	}
13471 
13472 
13473 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
13474 
13475 		/*
13476 		 * if rval is bad before the first pass don't bother
13477 		 */
13478 		if (ix == 0 && rval != 0) {
13479 
13480 			break;
13481 		}
13482 
13483 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
13484 		    ta->param[ix].log_param.pc_lo);
13485 
13486 		if ((ta->param[ix].param_value & 1) == 0) {
13487 			continue;
13488 		}
13489 		/*
13490 		 * check to see if current parameter is of interest.
13491 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
13492 		 */
13493 		if ((flag == TAF_CLEAN_NOW) ||
13494 		    (flag == TAF_CLEAN_PERIODIC) ||
13495 		    ((flag == CLEAN_FOR_ERRORS) &&
13496 		    (un->un_dp->type == ST_TYPE_STK9840))) {
13497 
13498 			rval = MTF_TAPE_CLN_SUPPORTED;
13499 
13500 
13501 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13502 			    "alert_page drive needs clean %d\n", flag);
13503 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
13504 			rval |= MTF_TAPE_HEAD_DIRTY;
13505 
13506 		} else if (flag == TAF_CLEANING_MEDIA) {
13507 
13508 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13509 			    "alert_page drive was cleaned\n");
13510 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
13511 		}
13512 
13513 	}
13514 
13515 	/*
13516 	 * Report it as dirty till we see it cleaned
13517 	 */
13518 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
13519 
13520 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13521 		    "alert_page still dirty\n");
13522 		rval |= MTF_TAPE_HEAD_DIRTY;
13523 	}
13524 
13525 	kmem_free(com, sizeof (struct uscsi_cmd));
13526 	kmem_free(ta,  sizeof (struct st_tape_alert));
13527 
13528 	return (rval);
13529 }
13530 
13531 
13532 static int
13533 st_check_sense_clean_bit(struct scsi_tape *un)
13534 {
13535 	uchar_t *sensep;
13536 	char cdb[CDB_GROUP0];
13537 	struct uscsi_cmd *com;
13538 	ushort_t byte_pos;
13539 	uchar_t bit_mask;
13540 	unsigned length;
13541 	int index;
13542 	int rval;
13543 
13544 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
13545 
13546 	/*
13547 	 * Since this tape does not support Tape Alert,
13548 	 * we now try to get the cleanbit status via
13549 	 * Request Sense.
13550 	 */
13551 
13552 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
13553 
13554 		index = 0;
13555 
13556 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
13557 
13558 		index = 1;
13559 
13560 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
13561 
13562 		index = 2;
13563 
13564 	} else {
13565 
13566 		return (-1);
13567 	}
13568 
13569 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
13570 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
13571 	length = byte_pos + 1;
13572 
13573 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13574 	sensep = kmem_zalloc(length, KM_SLEEP);
13575 
13576 	cdb[0] = SCMD_REQUEST_SENSE;
13577 	cdb[1] = 0;
13578 	cdb[2] = 0;
13579 	cdb[3] = 0;
13580 	cdb[4] = (char)length;
13581 	cdb[5] = 0;
13582 
13583 	com->uscsi_cdb = cdb;
13584 	com->uscsi_cdblen = CDB_GROUP0;
13585 	com->uscsi_bufaddr = (caddr_t)sensep;
13586 	com->uscsi_buflen = length;
13587 	com->uscsi_flags =
13588 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13589 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13590 
13591 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13592 
13593 	if (rval || com->uscsi_status || com->uscsi_resid) {
13594 
13595 		rval = -1;
13596 
13597 	} else {
13598 
13599 		rval = MTF_TAPE_CLN_SUPPORTED;
13600 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
13601 
13602 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13603 			    "sense data says head dirty\n");
13604 			rval |= MTF_TAPE_HEAD_DIRTY;
13605 		}
13606 	}
13607 
13608 	kmem_free(com, sizeof (struct uscsi_cmd));
13609 	kmem_free(sensep, length);
13610 	return (rval);
13611 }
13612 
13613 /*
13614  * st_clear_unit_attention
13615  *
13616  *  	run test unit ready's to clear out outstanding
13617  * 	unit attentions.
13618  * 	returns zero for SUCCESS or the errno from st_cmd call
13619  */
13620 static int
13621 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
13622 {
13623 	int	i    = 0;
13624 	int	rval;
13625 
13626 	GET_SOFT_STATE(dev_instance);
13627 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
13628 
13629 	do {
13630 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
13631 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
13632 	return (rval);
13633 }
13634 
13635 static void
13636 st_calculate_timeouts(struct scsi_tape *un)
13637 {
13638 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
13639 
13640 	if (un->un_dp->non_motion_timeout == 0) {
13641 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13642 			un->un_dp->non_motion_timeout =
13643 			    st_io_time * st_long_timeout_x;
13644 		} else {
13645 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
13646 		}
13647 	}
13648 
13649 	if (un->un_dp->io_timeout == 0) {
13650 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13651 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
13652 		} else {
13653 			un->un_dp->io_timeout = (ushort_t)st_io_time;
13654 		}
13655 	}
13656 
13657 	if (un->un_dp->rewind_timeout == 0) {
13658 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13659 			un->un_dp->rewind_timeout =
13660 			    st_space_time * st_long_timeout_x;
13661 		} else {
13662 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
13663 		}
13664 	}
13665 
13666 	if (un->un_dp->space_timeout == 0) {
13667 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13668 			un->un_dp->space_timeout =
13669 			    st_space_time * st_long_timeout_x;
13670 		} else {
13671 			un->un_dp->space_timeout = (ushort_t)st_space_time;
13672 		}
13673 	}
13674 
13675 	if (un->un_dp->load_timeout == 0) {
13676 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13677 			un->un_dp->load_timeout =
13678 			    st_space_time * st_long_timeout_x;
13679 		} else {
13680 			un->un_dp->load_timeout = (ushort_t)st_space_time;
13681 		}
13682 	}
13683 
13684 	if (un->un_dp->unload_timeout == 0) {
13685 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13686 			un->un_dp->unload_timeout =
13687 			    st_space_time * st_long_timeout_x;
13688 		} else {
13689 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
13690 		}
13691 	}
13692 
13693 	if (un->un_dp->erase_timeout == 0) {
13694 		if (un->un_dp->options & ST_LONG_ERASE) {
13695 			un->un_dp->erase_timeout =
13696 			    st_space_time * st_long_space_time_x;
13697 		} else {
13698 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
13699 		}
13700 	}
13701 }
13702 
13703 
13704 static writablity
13705 st_is_not_wormable(struct scsi_tape *un)
13706 {
13707 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
13708 	return (RDWR);
13709 }
13710 
13711 static writablity
13712 st_is_hp_dat_tape_worm(struct scsi_tape *un)
13713 {
13714 	writablity wrt;
13715 
13716 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
13717 
13718 	/* Mode sense should be current */
13719 	if (un->un_mspl->media_type == 1) {
13720 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13721 		    "Drive has WORM media loaded\n");
13722 		wrt = WORM;
13723 	} else {
13724 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13725 		    "Drive has non WORM media loaded\n");
13726 		wrt = RDWR;
13727 	}
13728 	return (wrt);
13729 }
13730 
13731 #define	HP_DAT_INQUIRY 0x4A
13732 static writablity
13733 st_is_hp_dat_worm(struct scsi_tape *un)
13734 {
13735 	char *buf;
13736 	int result;
13737 	writablity wrt;
13738 
13739 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
13740 
13741 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
13742 
13743 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
13744 
13745 	if (result != 0) {
13746 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13747 		    "Read Standard Inquiry for WORM support failed");
13748 		wrt = FAILED;
13749 	} else if ((buf[40] & 1) == 0) {
13750 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13751 		    "Drive is NOT WORMable\n");
13752 		/* This drive doesn't support it so don't check again */
13753 		un->un_dp->options &= ~ST_WORMABLE;
13754 		wrt = RDWR;
13755 		un->un_wormable = st_is_not_wormable;
13756 	} else {
13757 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13758 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13759 		un->un_wormable = st_is_hp_dat_tape_worm;
13760 		wrt = un->un_wormable(un);
13761 	}
13762 
13763 	kmem_free(buf, HP_DAT_INQUIRY);
13764 
13765 	/*
13766 	 * If drive doesn't support it no point in checking further.
13767 	 */
13768 	return (wrt);
13769 }
13770 
13771 static writablity
13772 st_is_hp_lto_tape_worm(struct scsi_tape *un)
13773 {
13774 	writablity wrt;
13775 
13776 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
13777 
13778 	/* Mode sense should be current */
13779 	switch (un->un_mspl->media_type) {
13780 	case 0x00:
13781 		switch (un->un_mspl->density) {
13782 		case 0x40:
13783 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13784 			    "Drive has standard Gen I media loaded\n");
13785 			break;
13786 		case 0x42:
13787 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13788 			    "Drive has standard Gen II media loaded\n");
13789 			break;
13790 		case 0x44:
13791 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13792 			    "Drive has standard Gen III media loaded\n");
13793 			break;
13794 		case 0x46:
13795 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13796 			    "Drive has standard Gen IV media loaded\n");
13797 			break;
13798 		default:
13799 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13800 			    "Drive has standard unknown 0x%X media loaded\n",
13801 			    un->un_mspl->density);
13802 		}
13803 		wrt = RDWR;
13804 		break;
13805 	case 0x01:
13806 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13807 		    "Drive has WORM medium loaded\n");
13808 		wrt = WORM;
13809 		break;
13810 	case 0x80:
13811 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13812 		    "Drive has CD-ROM emulation medium loaded\n");
13813 		wrt = WORM;
13814 		break;
13815 	default:
13816 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13817 		    "Drive has an unexpected medium type 0x%X loaded\n",
13818 		    un->un_mspl->media_type);
13819 		wrt = RDWR;
13820 	}
13821 
13822 	return (wrt);
13823 }
13824 
13825 #define	LTO_REQ_INQUIRY 44
13826 static writablity
13827 st_is_hp_lto_worm(struct scsi_tape *un)
13828 {
13829 	char *buf;
13830 	int result;
13831 	writablity wrt;
13832 
13833 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
13834 
13835 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
13836 
13837 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
13838 
13839 	if (result != 0) {
13840 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13841 		    "Read Standard Inquiry for WORM support failed");
13842 		wrt = FAILED;
13843 	} else if ((buf[40] & 1) == 0) {
13844 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13845 		    "Drive is NOT WORMable\n");
13846 		/* This drive doesn't support it so don't check again */
13847 		un->un_dp->options &= ~ST_WORMABLE;
13848 		wrt = RDWR;
13849 		un->un_wormable = st_is_not_wormable;
13850 	} else {
13851 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13852 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13853 		un->un_wormable = st_is_hp_lto_tape_worm;
13854 		wrt = un->un_wormable(un);
13855 	}
13856 
13857 	kmem_free(buf, LTO_REQ_INQUIRY);
13858 
13859 	/*
13860 	 * If drive doesn't support it no point in checking further.
13861 	 */
13862 	return (wrt);
13863 }
13864 
13865 static writablity
13866 st_is_t10_worm_device(struct scsi_tape *un)
13867 {
13868 	writablity wrt;
13869 
13870 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
13871 
13872 	if (un->un_mspl->media_type == 0x3c) {
13873 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13874 		    "Drive has WORM media loaded\n");
13875 		wrt = WORM;
13876 	} else {
13877 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13878 		    "Drive has non WORM media loaded\n");
13879 		wrt = RDWR;
13880 	}
13881 	return (wrt);
13882 }
13883 
13884 #define	SEQ_CAP_PAGE	(char)0xb0
13885 static writablity
13886 st_is_t10_worm(struct scsi_tape *un)
13887 {
13888 	char *buf;
13889 	int result;
13890 	writablity wrt;
13891 
13892 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
13893 
13894 	buf = kmem_zalloc(6, KM_SLEEP);
13895 
13896 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
13897 
13898 	if (result != 0) {
13899 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13900 		    "Read Vitial Inquiry for Sequental Capability"
13901 		    " WORM support failed %x", result);
13902 		wrt = FAILED;
13903 	} else if ((buf[4] & 1) == 0) {
13904 		ASSERT(buf[1] == SEQ_CAP_PAGE);
13905 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13906 		    "Drive is NOT WORMable\n");
13907 		/* This drive doesn't support it so don't check again */
13908 		un->un_dp->options &= ~ST_WORMABLE;
13909 		wrt = RDWR;
13910 		un->un_wormable = st_is_not_wormable;
13911 	} else {
13912 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13913 		    "Drive supports WORM\n");
13914 		un->un_wormable = st_is_t10_worm_device;
13915 		wrt = un->un_wormable(un);
13916 	}
13917 
13918 	kmem_free(buf, 6);
13919 
13920 	return (wrt);
13921 }
13922 
13923 
13924 #define	STK_REQ_SENSE 26
13925 
13926 static writablity
13927 st_is_stk_worm(struct scsi_tape *un)
13928 {
13929 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
13930 	struct scsi_extended_sense *sense;
13931 	struct uscsi_cmd *cmd;
13932 	char *buf;
13933 	int result;
13934 	writablity wrt;
13935 
13936 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
13937 
13938 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13939 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
13940 	sense = (struct scsi_extended_sense *)buf;
13941 
13942 	cmd->uscsi_flags = USCSI_READ;
13943 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13944 	cmd->uscsi_cdb = &cdb[0];
13945 	cmd->uscsi_bufaddr = buf;
13946 	cmd->uscsi_buflen = STK_REQ_SENSE;
13947 	cmd->uscsi_cdblen = CDB_GROUP0;
13948 	cmd->uscsi_rqlen = 0;
13949 	cmd->uscsi_rqbuf = NULL;
13950 
13951 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
13952 
13953 	if (result != 0 || cmd->uscsi_status != 0) {
13954 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13955 		    "Request Sense for WORM failed");
13956 		wrt = RDWR;
13957 	} else if (sense->es_add_len + 8 < 24) {
13958 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13959 		    "Drive didn't send enough sense data for WORM byte %d\n",
13960 		    sense->es_add_len + 8);
13961 		wrt = RDWR;
13962 		un->un_wormable = st_is_not_wormable;
13963 	} else if ((buf[24]) & 0x02) {
13964 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13965 		    "Drive has WORM tape loaded\n");
13966 		wrt = WORM;
13967 		un->un_wormable = st_is_stk_worm;
13968 	} else {
13969 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13970 		    "Drive has normal tape loaded\n");
13971 		wrt = RDWR;
13972 		un->un_wormable = st_is_stk_worm;
13973 	}
13974 
13975 	kmem_free(buf, STK_REQ_SENSE);
13976 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13977 	return (wrt);
13978 }
13979 
13980 #define	DLT_INQ_SZ 44
13981 
13982 static writablity
13983 st_is_dlt_tape_worm(struct scsi_tape *un)
13984 {
13985 	caddr_t buf;
13986 	int result;
13987 	writablity wrt;
13988 
13989 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
13990 
13991 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
13992 
13993 	/* Read Attribute Media Type */
13994 
13995 	result = st_read_attributes(un, 0x0408, buf, 10, st_uscsi_cmd);
13996 
13997 	/*
13998 	 * If this quantum drive is attached via an HBA that cannot
13999 	 * support thr read attributes command return error in the
14000 	 * hope that someday they will support the t10 method.
14001 	 */
14002 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
14003 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14004 		    "Read Attribute Command for WORM Media detection is not "
14005 		    "supported on the HBA that this drive is attached to.");
14006 		wrt = RDWR;
14007 		un->un_wormable = st_is_not_wormable;
14008 		goto out;
14009 	}
14010 
14011 	if (result != 0) {
14012 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14013 		    "Read Attribute Command for WORM Media returned 0x%x",
14014 		    result);
14015 		wrt = RDWR;
14016 		un->un_dp->options &= ~ST_WORMABLE;
14017 		goto out;
14018 	}
14019 
14020 	if ((uchar_t)buf[9] == 0x80) {
14021 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14022 		    "Drive media is WORM\n");
14023 		wrt = WORM;
14024 	} else {
14025 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14026 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
14027 		wrt = RDWR;
14028 	}
14029 
14030 out:
14031 	kmem_free(buf, DLT_INQ_SZ);
14032 	return (wrt);
14033 }
14034 
14035 static writablity
14036 st_is_dlt_worm(struct scsi_tape *un)
14037 {
14038 	caddr_t buf;
14039 	int result;
14040 	writablity wrt;
14041 
14042 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
14043 
14044 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14045 
14046 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
14047 
14048 	if (result != 0) {
14049 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14050 		    "Read Vendor Specific Inquiry for WORM support failed");
14051 		wrt = RDWR;
14052 		goto out;
14053 	}
14054 
14055 	if ((buf[2] & 1) == 0) {
14056 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14057 		    "Drive is not WORMable\n");
14058 		wrt = RDWR;
14059 		un->un_dp->options &= ~ST_WORMABLE;
14060 		un->un_wormable = st_is_not_wormable;
14061 		goto out;
14062 	} else {
14063 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14064 		    "Drive is WORMable\n");
14065 		un->un_wormable = st_is_dlt_tape_worm;
14066 		wrt = un->un_wormable(un);
14067 	}
14068 out:
14069 	kmem_free(buf, DLT_INQ_SZ);
14070 
14071 	return (wrt);
14072 }
14073 
14074 typedef struct {
14075 	struct modeheader_seq header;
14076 #if defined(_BIT_FIELDS_LTOH) /* X86 */
14077 	uchar_t pagecode	:6,
14078 				:2;
14079 	uchar_t page_len;
14080 	uchar_t syslogalive	:2,
14081 		device		:1,
14082 		abs		:1,
14083 		ulpbot		:1,
14084 		prth		:1,
14085 		ponej		:1,
14086 		ait		:1;
14087 	uchar_t span;
14088 
14089 	uchar_t			:6,
14090 		worm		:1,
14091 		mic		:1;
14092 	uchar_t worm_cap	:1,
14093 				:7;
14094 	uint32_t		:32;
14095 #else /* SPARC */
14096 	uchar_t			:2,
14097 		pagecode	:6;
14098 	uchar_t page_len;
14099 	uchar_t ait		:1,
14100 		device		:1,
14101 		abs		:1,
14102 		ulpbot		:1,
14103 		prth		:1,
14104 		ponej		:1,
14105 		syslogalive	:2;
14106 	uchar_t span;
14107 	uchar_t mic		:1,
14108 		worm		:1,
14109 				:6;
14110 	uchar_t			:7,
14111 		worm_cap	:1;
14112 	uint32_t		:32;
14113 #endif
14114 }ait_dev_con;
14115 
14116 #define	AIT_DEV_PAGE 0x31
14117 static writablity
14118 st_is_sony_worm(struct scsi_tape *un)
14119 {
14120 	int result;
14121 	writablity wrt;
14122 	ait_dev_con *ait_conf;
14123 
14124 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14125 
14126 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
14127 
14128 	result = st_gen_mode_sense(un, st_uscsi_cmd, AIT_DEV_PAGE,
14129 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
14130 
14131 	if (result == 0) {
14132 
14133 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
14134 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14135 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
14136 			    ait_conf->pagecode, AIT_DEV_PAGE);
14137 			wrt = RDWR;
14138 			un->un_wormable = st_is_not_wormable;
14139 
14140 		} else if (ait_conf->worm_cap) {
14141 
14142 			un->un_wormable = st_is_sony_worm;
14143 
14144 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14145 			    "Drives is WORMable\n");
14146 			if (ait_conf->worm) {
14147 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14148 				    "Media is WORM\n");
14149 				wrt = WORM;
14150 			} else {
14151 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14152 				    "Media is not WORM\n");
14153 				wrt = RDWR;
14154 			}
14155 
14156 		} else {
14157 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14158 			    "Drives not is WORMable\n");
14159 			wrt = RDWR;
14160 			/* No further checking required */
14161 			un->un_dp->options &= ~ST_WORMABLE;
14162 		}
14163 
14164 	} else {
14165 
14166 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14167 		    "AIT device config mode sense page read command failed"
14168 		    " result = %d ", result);
14169 		wrt = FAILED;
14170 		un->un_wormable = st_is_not_wormable;
14171 	}
14172 
14173 	kmem_free(ait_conf, sizeof (ait_dev_con));
14174 	return (wrt);
14175 }
14176 
14177 static writablity
14178 st_is_drive_worm(struct scsi_tape *un)
14179 {
14180 	writablity wrt;
14181 
14182 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14183 
14184 	switch (un->un_dp->type) {
14185 	case MT_ISDLT:
14186 		wrt = st_is_dlt_worm(un);
14187 		break;
14188 
14189 	case MT_ISSTK9840:
14190 		wrt = st_is_stk_worm(un);
14191 		break;
14192 
14193 	case MT_IS8MM:
14194 	case MT_ISAIT:
14195 		wrt = st_is_sony_worm(un);
14196 		break;
14197 
14198 	case MT_LTO:
14199 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14200 			wrt = st_is_hp_lto_worm(un);
14201 		} else {
14202 			wrt = st_is_t10_worm(un);
14203 		}
14204 		break;
14205 
14206 	case MT_ISDAT:
14207 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14208 			wrt = st_is_hp_dat_worm(un);
14209 		} else {
14210 			wrt = st_is_t10_worm(un);
14211 		}
14212 		break;
14213 
14214 	default:
14215 		wrt = FAILED;
14216 		break;
14217 	}
14218 
14219 	/*
14220 	 * If any of the above failed try the t10 standard method.
14221 	 */
14222 	if (wrt == FAILED) {
14223 		wrt = st_is_t10_worm(un);
14224 	}
14225 
14226 	/*
14227 	 * Unknown method for detecting WORM media.
14228 	 */
14229 	if (wrt == FAILED) {
14230 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14231 		    "Unknown method for WORM media detection\n");
14232 		wrt = RDWR;
14233 		un->un_dp->options &= ~ST_WORMABLE;
14234 	}
14235 
14236 	return (wrt);
14237 }
14238 
14239 static int
14240 st_read_attributes(struct scsi_tape *un, uint16_t attribute, void *pnt,
14241     size_t size, ubufunc_t bufunc)
14242 {
14243 	char cdb[CDB_GROUP4];
14244 	int result;
14245 	struct uscsi_cmd *cmd;
14246 	struct scsi_arq_status status;
14247 
14248 	caddr_t buf = (caddr_t)pnt;
14249 
14250 	ST_FUNC(ST_DEVINFO, st_read_attributes);
14251 
14252 	if (un->un_sd->sd_inq->inq_ansi < 3) {
14253 		return (ENOTTY);
14254 	}
14255 
14256 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14257 
14258 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
14259 	cdb[1] = 0;
14260 	cdb[2] = 0;
14261 	cdb[3] = 0;
14262 	cdb[4] = 0;
14263 	cdb[5] = 0;
14264 	cdb[6] = 0;
14265 	cdb[7] = 0;
14266 	cdb[8] = (char)(attribute >> 8);
14267 	cdb[9] = (char)(attribute);
14268 	cdb[10] = (char)(size >> 24);
14269 	cdb[11] = (char)(size >> 16);
14270 	cdb[12] = (char)(size >> 8);
14271 	cdb[13] = (char)(size);
14272 	cdb[14] = 0;
14273 	cdb[15] = 0;
14274 
14275 
14276 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE | USCSI_DIAGNOSE;
14277 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14278 	cmd->uscsi_cdb = &cdb[0];
14279 	cmd->uscsi_bufaddr = (caddr_t)buf;
14280 	cmd->uscsi_buflen = size;
14281 	cmd->uscsi_cdblen = sizeof (cdb);
14282 	cmd->uscsi_rqlen = sizeof (status);
14283 	cmd->uscsi_rqbuf = (caddr_t)&status;
14284 
14285 	result = bufunc(un, cmd, FKIOCTL);
14286 
14287 	if (result != 0 || cmd->uscsi_status != 0) {
14288 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
14289 		    "st_read_attribute failed: result %d status %d\n",
14290 		    result, cmd->uscsi_status);
14291 		/*
14292 		 * If this returns invalid operation code don't try again.
14293 		 */
14294 		if (un->un_sd->sd_sense->es_key == KEY_ILLEGAL_REQUEST &&
14295 		    un->un_sd->sd_sense->es_add_code == 0x20) {
14296 			result = ENOTTY;
14297 		} else if (result == 0) {
14298 			result = EIO;
14299 		}
14300 
14301 	} else {
14302 
14303 		/*
14304 		 * The attribute retured should match the attribute requested.
14305 		 */
14306 		if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
14307 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14308 			    "st_read_attribute got wrong data back expected "
14309 			    "0x%x got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
14310 			st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14311 			    "bad? data", buf, size);
14312 			result = EIO;
14313 		}
14314 	}
14315 
14316 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14317 
14318 	return (result);
14319 }
14320 
14321 static int
14322 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
14323     uchar_t page)
14324 {
14325 	char cdb[CDB_GROUP0];
14326 	struct scsi_extended_sense *sense;
14327 	struct uscsi_cmd *cmd;
14328 	int result;
14329 
14330 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
14331 
14332 	cdb[0] = SCMD_INQUIRY;
14333 	cdb[1] = page ? 1 : 0;
14334 	cdb[2] = page;
14335 	cdb[3] = 0;
14336 	cdb[4] = size;
14337 	cdb[5] = 0;
14338 
14339 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14340 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
14341 
14342 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
14343 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14344 	cmd->uscsi_cdb = &cdb[0];
14345 	cmd->uscsi_bufaddr = dest;
14346 	cmd->uscsi_buflen = size;
14347 	cmd->uscsi_cdblen = CDB_GROUP0;
14348 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
14349 	cmd->uscsi_rqbuf = (caddr_t)sense;
14350 
14351 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14352 
14353 	if (result != 0 || cmd->uscsi_status != 0) {
14354 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14355 		    "st_get_special_inquiry() failed for page %x", page);
14356 		if (result == 0) {
14357 			result = EIO;
14358 		}
14359 	}
14360 
14361 	kmem_free(sense, sizeof (struct scsi_extended_sense));
14362 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14363 
14364 	return (result);
14365 }
14366 
14367 
14368 static int
14369 st_update_block_pos(struct scsi_tape *un, bufunc_t bf, int post_space)
14370 {
14371 	int rval = ENOTTY;
14372 	uchar_t status = un->un_status;
14373 	posmode previous_pmode = un->un_running.pmode;
14374 
14375 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
14376 
14377 	while (un->un_read_pos_type != NO_POS) {
14378 		rval = bf(un, SCMD_READ_POSITION, 32, SYNC_CMD);
14379 
14380 		/*
14381 		 * If read position command returned good status
14382 		 * Parse the data to see if the position can be interpreted.
14383 		 */
14384 		if ((rval == 0) &&
14385 		    ((rval = st_interpret_read_pos(un, &un->un_pos,
14386 		    un->un_read_pos_type, 32, (caddr_t)un->un_read_pos_data,
14387 		    post_space)) == 0)) {
14388 			/*
14389 			 * Update the running position as well if un_pos was
14390 			 * ok. But only if recovery is enabled.
14391 			 */
14392 			if (st_recov_sz != sizeof (recov_info)) {
14393 				break;
14394 			}
14395 			rval = st_interpret_read_pos(un, &un->un_running,
14396 			    un->un_read_pos_type, 32,
14397 			    (caddr_t)un->un_read_pos_data, post_space);
14398 			un->un_status = status;
14399 			break;
14400 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
14401 			un->un_running.pmode = previous_pmode;
14402 			continue;
14403 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
14404 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
14405 			    "st_update_block_pos() read position cmd 0x%x"
14406 			    " returned 0x%x un_status = %d",
14407 			    un->un_read_pos_type, rval, un->un_status);
14408 			/* ENOTTY means it read garbage. try something else. */
14409 			if (rval == ENOTTY) {
14410 				rval = EIO; /* so ENOTTY is not final rval */
14411 			} else {
14412 				break;
14413 			}
14414 		} else {
14415 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
14416 			    "st_update_block_pos() read position cmd %x"
14417 			    " returned %x", un->un_read_pos_type, rval);
14418 			un->un_running.pmode = previous_pmode;
14419 		}
14420 
14421 		switch (un->un_read_pos_type) {
14422 		case SHORT_POS:
14423 			un->un_read_pos_type = NO_POS;
14424 			break;
14425 
14426 		case LONG_POS:
14427 			un->un_read_pos_type = EXT_POS;
14428 			break;
14429 
14430 		case EXT_POS:
14431 			un->un_read_pos_type = SHORT_POS;
14432 			break;
14433 
14434 		default:
14435 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14436 			    "Unexpected read position type 0x%x",
14437 			    un->un_read_pos_type);
14438 		}
14439 		un->un_status = KEY_NO_SENSE;
14440 	}
14441 
14442 	return (rval);
14443 }
14444 
14445 static int
14446 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
14447 {
14448 	int result;
14449 	size_t d_sz;
14450 	caddr_t pos_info;
14451 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
14452 
14453 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
14454 
14455 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
14456 		return (0);
14457 	}
14458 
14459 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
14460 
14461 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14462 		    "bp_mapin_common() failed");
14463 
14464 		return (EIO);
14465 	}
14466 
14467 	d_sz = bp->b_bcount - bp->b_resid;
14468 	if (d_sz == 0) {
14469 		bp_mapout(bp);
14470 		return (EIO);
14471 	}
14472 
14473 	/*
14474 	 * Copy the buf to a double-word aligned memory that can hold the
14475 	 * tape_position_t data structure.
14476 	 */
14477 	if ((pos_info = kmem_alloc(d_sz, KM_NOSLEEP)) == NULL) {
14478 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14479 		    "kmem_alloc() failed");
14480 		bp_mapout(bp);
14481 		return (EIO);
14482 	}
14483 	bcopy(bp->b_un.b_addr, pos_info, d_sz);
14484 
14485 #ifdef STDEBUG
14486 	if ((st_debug & 0x7) > 2) {
14487 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14488 		    "st_get_read_pos() position info",
14489 		    pos_info, bp->b_bcount);
14490 	}
14491 #endif
14492 
14493 	result = st_interpret_read_pos(un, &un->un_pos, cmd->uscsi_cdb[1],
14494 	    d_sz, pos_info, 0);
14495 
14496 	COPY_POS(&un->un_running, &un->un_pos);
14497 
14498 	kmem_free(pos_info, d_sz);
14499 	bp_mapout(bp);
14500 
14501 	return (result);
14502 }
14503 
14504 #if defined(_BIG_ENDIAN)
14505 
14506 #define	FIX_ENDIAN16(x)
14507 #define	FIX_ENDIAN32(x)
14508 #define	FIX_ENDIAN64(x)
14509 
14510 #elif defined(_LITTLE_ENDIAN)
14511 
14512 static void
14513 st_swap16(uint16_t *val)
14514 {
14515 	uint16_t tmp;
14516 
14517 	tmp = (*val >>  8) & 0xff;
14518 	tmp |= (*val <<  8) & 0xff00;
14519 
14520 	*val = tmp;
14521 }
14522 
14523 static void
14524 st_swap32(uint32_t *val)
14525 {
14526 	uint32_t tmp;
14527 
14528 	tmp =  (*val >> 24) & 0xff;
14529 	tmp |= (*val >>  8) & 0xff00;
14530 	tmp |= (*val <<  8) & 0xff0000;
14531 	tmp |= (*val << 24) & 0xff000000;
14532 
14533 	*val = tmp;
14534 }
14535 
14536 static void
14537 st_swap64(uint64_t *val)
14538 {
14539 	uint32_t low;
14540 	uint32_t high;
14541 
14542 	low =  (uint32_t)(*val);
14543 	high = (uint32_t)(*val >> 32);
14544 
14545 	st_swap32(&low);
14546 	st_swap32(&high);
14547 
14548 	*val =  high;
14549 	*val |= ((uint64_t)low << 32);
14550 }
14551 
14552 #define	FIX_ENDIAN16(x) st_swap16(x)
14553 #define	FIX_ENDIAN32(x) st_swap32(x)
14554 #define	FIX_ENDIAN64(x) st_swap64(x)
14555 #endif
14556 
14557 /*
14558  * st_interpret_read_pos()
14559  *
14560  * Returns:
14561  *	0	If secsessful.
14562  *	EIO	If read postion responce data was unuseable or invalid.
14563  *	ERANGE	If the position of the drive is too large for the read_p_type.
14564  *	ENOTTY	If the responce data looks invalid for the read position type.
14565  */
14566 
14567 static int
14568 st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
14569     read_p_types type, size_t data_sz, const caddr_t responce, int post_space)
14570 {
14571 	int rval = 0;
14572 	int flag = 0;
14573 	tapepos_t org;
14574 
14575 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
14576 
14577 	/*
14578 	 * We expect the position value to change after a space command.
14579 	 * So if post_space is set we don't print out what has changed.
14580 	 */
14581 	if ((dest != &un->un_pos) && (post_space == 0) &&
14582 	    (st_recov_sz == sizeof (recov_info))) {
14583 		COPY_POS(&org, dest);
14584 		flag = 1;
14585 	}
14586 
14587 	/*
14588 	 * See what kind of read position was requested.
14589 	 */
14590 	switch (type) {
14591 
14592 	case SHORT_POS: /* Short data format */
14593 	{
14594 		tape_position_t *pos_info = (tape_position_t *)responce;
14595 		uint32_t value;
14596 
14597 		/* If reserved fields are non zero don't use the data */
14598 		if (pos_info->reserved0 || pos_info->reserved1 ||
14599 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
14600 		    pos_info->reserved3) {
14601 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14602 			    "Invalid Read Short Position Data returned\n");
14603 			rval = EIO;
14604 			break;
14605 		}
14606 		/*
14607 		 * Position is to large to use this type of read position.
14608 		 */
14609 		if (pos_info->posi_err == 1) {
14610 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14611 			    "Drive reported position error\n");
14612 			rval = ERANGE;
14613 			break;
14614 		}
14615 		/*
14616 		 * If your at the begining of partition and end at the same
14617 		 * time it's very small partition or bad data.
14618 		 */
14619 		if (pos_info->begin_of_part && pos_info->end_of_part) {
14620 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14621 			    "SHORT_POS returned begin and end of"
14622 			    " partition\n");
14623 			rval = EIO;
14624 			break;
14625 		}
14626 
14627 		if (pos_info->blk_posi_unkwn == 0) {
14628 
14629 			value = pos_info->host_block;
14630 			FIX_ENDIAN32(&value);
14631 
14632 			/*
14633 			 * If the tape is rewound the host blcok should be 0.
14634 			 */
14635 			if ((pos_info->begin_of_part == 1) &&
14636 			    (value != 0)) {
14637 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14638 				    "SHORT_POS returned begin of partition"
14639 				    " but host block was 0x%x\n", value);
14640 				rval = EIO;
14641 				break;
14642 			}
14643 
14644 			if (dest->lgclblkno != value) {
14645 				if (flag)
14646 					flag++;
14647 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14648 				    "SHORT_POS current logical 0x%"PRIx64" read"
14649 				    " 0x%x\n", dest->lgclblkno, value);
14650 			}
14651 
14652 			dest->lgclblkno = (uint64_t)value;
14653 
14654 			/*
14655 			 * If the begining of partition is true and the
14656 			 * block number is zero we will beleive that it is
14657 			 * rewound. Promote the pmode to legacy.
14658 			 */
14659 			if ((pos_info->begin_of_part == 1) &&
14660 			    (value == 0)) {
14661 				dest->blkno = 0;
14662 				dest->fileno = 0;
14663 				if (dest->pmode != legacy)
14664 					dest->pmode = legacy;
14665 			/*
14666 			 * otherwise if the pmode was invalid,
14667 			 * promote it to logical.
14668 			 */
14669 			} else if (dest->pmode == invalid) {
14670 				dest->pmode = logical;
14671 			}
14672 
14673 			if (dest->partition != pos_info->partition_number) {
14674 				if (flag)
14675 					flag++;
14676 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14677 				    "SHORT_POS current partition %d read %d\n",
14678 				    dest->partition,
14679 				    pos_info->partition_number);
14680 			}
14681 
14682 			dest->partition = pos_info->partition_number;
14683 
14684 		} else {
14685 			dest->pmode = invalid;
14686 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14687 			    "Tape drive reported block position as unknown\n");
14688 		}
14689 		break;
14690 	}
14691 
14692 	case LONG_POS: /* Long data format */
14693 	{
14694 		uint64_t value;
14695 		tape_position_long_t *long_pos_info =
14696 		    (tape_position_long_t *)responce;
14697 
14698 		/* If reserved fields are non zero don't use the data */
14699 		if ((long_pos_info->reserved0) ||
14700 		    (long_pos_info->reserved1) ||
14701 		    (long_pos_info->reserved2)) {
14702 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14703 			    "Invalid Read Long Position Data returned\n");
14704 			rval = ENOTTY;
14705 			break;
14706 		}
14707 
14708 		/* Is position Valid */
14709 		if (long_pos_info->blk_posi_unkwn == 0) {
14710 			uint32_t part;
14711 
14712 			value = long_pos_info->block_number;
14713 			FIX_ENDIAN64(&value);
14714 
14715 			/*
14716 			 * If it says we are at the begining of partition
14717 			 * the block value better be 0.
14718 			 */
14719 			if ((long_pos_info->begin_of_part == 1) &&
14720 			    (value != 0)) {
14721 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14722 				    "LONG_POS returned begin of partition but"
14723 				    " block number was 0x%"PRIx64"\n", value);
14724 				rval = ENOTTY;
14725 				break;
14726 			}
14727 			/*
14728 			 * Can't be at the start and the end of the partition
14729 			 * at the same time if the partition is larger the 0.
14730 			 */
14731 			if (long_pos_info->begin_of_part &&
14732 			    long_pos_info->end_of_part) {
14733 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14734 				    "LONG_POS returned begin and end of"
14735 				    " partition\n");
14736 				rval = ENOTTY;
14737 				break;
14738 			}
14739 
14740 			/*
14741 			 * If the logical block number is not what we expected.
14742 			 */
14743 			if (dest->lgclblkno != value) {
14744 				if (flag)
14745 					flag++;
14746 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14747 				    "LONG_POS current logical 0x%"PRIx64
14748 				    " read 0x%"PRIx64"\n",
14749 				    dest->lgclblkno, value);
14750 			}
14751 			dest->lgclblkno = value;
14752 
14753 			/*
14754 			 * If the begining of partition is true and the
14755 			 * block number is zero we will beleive that it is
14756 			 * rewound. Promote the pmode to legacy.
14757 			 */
14758 			if ((long_pos_info->begin_of_part == 1) &&
14759 			    (long_pos_info->block_number == 0)) {
14760 				dest->blkno = 0;
14761 				dest->fileno = 0;
14762 				if (dest->pmode != legacy)
14763 					dest->pmode = legacy;
14764 			/*
14765 			 * otherwise if the pmode was invalid,
14766 			 * promote it to logical.
14767 			 */
14768 			} else if (dest->pmode == invalid) {
14769 				dest->pmode = logical;
14770 			}
14771 
14772 			part = long_pos_info->partition;
14773 			FIX_ENDIAN32(&part);
14774 			if (dest->partition != part) {
14775 				if (flag)
14776 					flag++;
14777 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14778 				    "LONG_POS current partition %d"
14779 				    " read %d\n", dest->partition, part);
14780 			}
14781 			dest->partition = part;
14782 		} else {
14783 			/*
14784 			 * If the drive doesn't know location,
14785 			 * we don't either.
14786 			 */
14787 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14788 			    "Tape drive reported block position as unknown\n");
14789 			dest->pmode = invalid;
14790 		}
14791 
14792 		/* Is file position valid */
14793 		if (long_pos_info->mrk_posi_unkwn == 0) {
14794 			value = long_pos_info->file_number;
14795 			FIX_ENDIAN64(&value);
14796 			/*
14797 			 * If it says we are at the begining of partition
14798 			 * the block value better be 0.
14799 			 */
14800 			if ((long_pos_info->begin_of_part == 1) &&
14801 			    (value != 0)) {
14802 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14803 				    "LONG_POS returned begin of partition but"
14804 				    " block number was 0x%"PRIx64"\n", value);
14805 				rval = ENOTTY;
14806 				break;
14807 			}
14808 			if (((dest->pmode == legacy) ||
14809 			    (dest->pmode == logical)) &&
14810 			    (dest->fileno != value)) {
14811 				if (flag)
14812 					flag++;
14813 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14814 				    "LONG_POS fileno 0x%"PRIx64
14815 				    " not un_pos %x\n", value,
14816 				    dest->fileno);
14817 			} else if (dest->pmode == invalid) {
14818 				dest->pmode = logical;
14819 			}
14820 			dest->fileno = (int32_t)value;
14821 		}
14822 
14823 		if (dest->pmode != invalid && long_pos_info->end_of_part) {
14824 			dest->eof = ST_EOT;
14825 		}
14826 
14827 		break;
14828 	}
14829 
14830 	case EXT_POS: /* Extended data format */
14831 	{
14832 		uint64_t value;
14833 		uint16_t len;
14834 		tape_position_ext_t *ext_pos_info =
14835 		    (tape_position_ext_t *)responce;
14836 
14837 		/* Make sure that there is enough data there */
14838 		if (data_sz < 16) {
14839 			break;
14840 		}
14841 
14842 		/* If reserved fields are non zero don't use the data */
14843 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
14844 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14845 			    "EXT_POS reserved fields not zero\n");
14846 			rval = ENOTTY;
14847 			break;
14848 		}
14849 
14850 		/*
14851 		 * In the unlikely event of overflowing 64 bits of position.
14852 		 */
14853 		if (ext_pos_info->posi_err != 0) {
14854 			rval = ERANGE;
14855 			break;
14856 		}
14857 
14858 		len = ext_pos_info->parameter_len;
14859 		FIX_ENDIAN16(&len);
14860 
14861 		if (len != 0x1c) {
14862 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14863 			    "EXT_POS parameter_len should be 0x1c was 0x%x\n",
14864 			    len);
14865 			rval = ENOTTY;
14866 			break;
14867 		}
14868 
14869 		/* Is block position information valid */
14870 		if (ext_pos_info->blk_posi_unkwn == 0) {
14871 
14872 			value = ext_pos_info->host_block;
14873 			FIX_ENDIAN64(&value);
14874 			if ((ext_pos_info->begin_of_part == 1) &&
14875 			    (value != 0)) {
14876 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14877 				    "EXT_POS returned begining of partition but"
14878 				    " the host block was 0x%"PRIx64"\n", value);
14879 				rval = ENOTTY;
14880 				break;
14881 			}
14882 
14883 			if (dest->lgclblkno != value) {
14884 				if (flag)
14885 					flag++;
14886 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14887 				    "EXT_POS current logical 0x%"PRIx64
14888 				    " read 0x%"PRIx64"\n",
14889 				    dest->lgclblkno, value);
14890 			}
14891 			dest->lgclblkno = value;
14892 
14893 			/*
14894 			 * If the begining of partition is true and the
14895 			 * block number is zero we will beleive that it is
14896 			 * rewound. Promote the pmode to legacy.
14897 			 */
14898 			if ((ext_pos_info->begin_of_part == 1) &&
14899 			    (ext_pos_info->host_block == 0)) {
14900 				dest->blkno = 0;
14901 				dest->fileno = 0;
14902 				if (dest->pmode != legacy) {
14903 					dest->pmode = legacy;
14904 				}
14905 			/*
14906 			 * otherwise if the pmode was invalid,
14907 			 * promote it to logical.
14908 			 */
14909 			} else if (dest->pmode == invalid) {
14910 				dest->pmode = logical;
14911 			}
14912 
14913 			if (dest->partition != ext_pos_info->partition) {
14914 				if (flag)
14915 					flag++;
14916 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14917 				    "EXT_POS current partition %d read %d\n",
14918 				    dest->partition,
14919 				    ext_pos_info->partition);
14920 			}
14921 			dest->partition = ext_pos_info->partition;
14922 
14923 		} else {
14924 			dest->pmode = invalid;
14925 		}
14926 		break;
14927 	}
14928 
14929 	default:
14930 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14931 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
14932 		rval = EIO;
14933 	}
14934 
14935 	if ((flag > 1) && (rval == 0) && (org.pmode != invalid)) {
14936 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14937 		    "position read in", &org);
14938 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14939 		    "position read out", dest);
14940 	}
14941 
14942 	return (rval);
14943 }
14944 
14945 static int
14946 st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos,
14947     uint64_t lblk, uchar_t partition)
14948 {
14949 	int rval;
14950 	char cdb[CDB_GROUP4];
14951 	struct uscsi_cmd *cmd;
14952 	struct scsi_extended_sense sense;
14953 	bufunc_t bf = (ubf == st_uscsi_cmd) ? st_cmd : st_rcmd;
14954 
14955 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
14956 	/*
14957 	 * Not sure what to do when doing recovery and not wanting
14958 	 * to update un_pos
14959 	 */
14960 
14961 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14962 
14963 	if (lblk <= INT32_MAX) {
14964 		cmd->uscsi_cdblen = CDB_GROUP1;
14965 		cdb[0] = SCMD_LOCATE;
14966 		cdb[1] = pos->partition == partition ? 0 : 2;
14967 		cdb[2] = 0;
14968 		cdb[3] = (char)(lblk >> 24);
14969 		cdb[4] = (char)(lblk >> 16);
14970 		cdb[5] = (char)(lblk >> 8);
14971 		cdb[6] = (char)(lblk);
14972 		cdb[7] = 0;
14973 		cdb[8] = partition;
14974 		cdb[9] = 0;
14975 	} else {
14976 		/*
14977 		 * If the drive doesn't give a 64 bit read position data
14978 		 * it is unlikely it will accept 64 bit locates.
14979 		 */
14980 		if (un->un_read_pos_type != LONG_POS) {
14981 			kmem_free(cmd, sizeof (struct uscsi_cmd));
14982 			return (ERANGE);
14983 		}
14984 		cmd->uscsi_cdblen = CDB_GROUP4;
14985 		cdb[0] = (char)SCMD_LOCATE_G4;
14986 		cdb[1] = pos->partition == partition ? 0 : 2;
14987 		cdb[2] = 0;
14988 		cdb[3] = partition;
14989 		cdb[4] = (char)(lblk >> 56);
14990 		cdb[5] = (char)(lblk >> 48);
14991 		cdb[6] = (char)(lblk >> 40);
14992 		cdb[7] = (char)(lblk >> 32);
14993 		cdb[8] = (char)(lblk >> 24);
14994 		cdb[9] = (char)(lblk >> 16);
14995 		cdb[10] = (char)(lblk >> 8);
14996 		cdb[11] = (char)(lblk);
14997 		cdb[12] = 0;
14998 		cdb[13] = 0;
14999 		cdb[14] = 0;
15000 		cdb[15] = 0;
15001 	}
15002 
15003 
15004 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
15005 	cmd->uscsi_rqbuf = (caddr_t)&sense;
15006 	cmd->uscsi_rqlen = sizeof (sense);
15007 	cmd->uscsi_timeout = un->un_dp->space_timeout;
15008 	cmd->uscsi_cdb = cdb;
15009 
15010 	rval = ubf(un, cmd, FKIOCTL);
15011 
15012 	pos->pmode = logical;
15013 	pos->eof = ST_NO_EOF;
15014 
15015 	if (lblk > INT32_MAX) {
15016 		/*
15017 		 * XXX This is a work around till we handle Descriptor format
15018 		 * sense data. Since we are sending a command where the standard
15019 		 * sense data can not correctly represent a correct residual in
15020 		 * 4 bytes.
15021 		 */
15022 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
15023 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15024 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
15025 			/* Doesn't like big locate command */
15026 			un->un_status = 0;
15027 			rval = ERANGE;
15028 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
15029 			/* Aborted big locate command */
15030 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15031 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
15032 			    rval);
15033 			un->un_status = 0;
15034 			rval = EIO;
15035 		} else if (st_update_block_pos(un, bf, 1)) {
15036 			/* read position failed */
15037 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15038 			    "Big LOCATE and read pos: rval = %d\n", rval);
15039 			rval = EIO;
15040 		} else if (lblk > un->un_pos.lgclblkno) {
15041 			/* read position worked but position was not expected */
15042 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15043 			    "Big LOCATE and recover read less then desired 0x%"
15044 			    PRIx64"\n", un->un_pos.lgclblkno);
15045 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
15046 			un->un_status = KEY_BLANK_CHECK;
15047 			rval = ESPIPE;
15048 		} else if (lblk == un->un_pos.lgclblkno) {
15049 			/* read position was what was expected */
15050 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15051 			    "Big LOCATE and recover seems to have worked\n");
15052 			un->un_err_resid = 0;
15053 			rval = 0;
15054 		} else {
15055 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15056 			    "BIGLOCATE end up going backwards");
15057 			un->un_err_resid = lblk;
15058 			rval = EIO;
15059 		}
15060 
15061 	} else if (rval == 0) {
15062 		/* Worked as requested */
15063 		pos->lgclblkno = lblk;
15064 
15065 	} else if (((cmd->uscsi_status & ST_STATUS_MASK) == STATUS_CHECK) &&
15066 	    (cmd->uscsi_resid != 0)) {
15067 		/* Got part way there but wasn't enough blocks on tape */
15068 		pos->lgclblkno = lblk - cmd->uscsi_resid;
15069 		un->un_err_resid = cmd->uscsi_resid;
15070 		un->un_status = KEY_BLANK_CHECK;
15071 		rval = ESPIPE;
15072 
15073 	} else if (st_update_block_pos(un, bf, 1) == 0) {
15074 		/* Got part way there but drive didn't tell what we missed by */
15075 		un->un_err_resid = lblk - pos->lgclblkno;
15076 		un->un_status = KEY_BLANK_CHECK;
15077 		rval = ESPIPE;
15078 
15079 	} else {
15080 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15081 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
15082 		    rval, cmd->uscsi_status);
15083 		un->un_err_resid = lblk;
15084 		un->un_status = KEY_ILLEGAL_REQUEST;
15085 		pos->pmode = invalid;
15086 		rval = EIO;
15087 	}
15088 
15089 	kmem_free(cmd, sizeof (struct uscsi_cmd));
15090 
15091 	return (rval);
15092 }
15093 
15094 static int
15095 st_mtfsf_ioctl(struct scsi_tape *un, int64_t files)
15096 {
15097 	int rval;
15098 
15099 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
15100 
15101 
15102 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15103 	    "st_mtfsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15104 #if 0
15105 	if ((IN_EOF(un->un_pos)) && (files == 1)) {
15106 		un->un_pos.fileno++;
15107 		un->un_pos.blkno = 0;
15108 		return (0);
15109 	}
15110 #endif
15111 	/* pmode == invalid already handled */
15112 	if (un->un_pos.pmode == legacy) {
15113 		/*
15114 		 * forward space over filemark
15115 		 *
15116 		 * For ASF we allow a count of 0 on fsf which means
15117 		 * we just want to go to beginning of current file.
15118 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
15119 		 * Allow stepping over double fmk with reel
15120 		 */
15121 		if ((un->un_pos.eof >= ST_EOT) &&
15122 		    (files > 0) &&
15123 		    ((un->un_dp->options & ST_REEL) == 0)) {
15124 			/* we're at EOM */
15125 			un->un_err_resid = files;
15126 			un->un_status = KEY_BLANK_CHECK;
15127 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15128 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
15129 			return (EIO);
15130 		}
15131 
15132 		/*
15133 		 * physical tape position may not be what we've been
15134 		 * telling the user; adjust the request accordingly
15135 		 */
15136 		if (IN_EOF(un->un_pos)) {
15137 			un->un_pos.fileno++;
15138 			un->un_pos.blkno = 0;
15139 			/*
15140 			 * For positive direction case, we're now covered.
15141 			 * For zero or negative direction, we're covered
15142 			 * (almost)
15143 			 */
15144 			files--;
15145 		}
15146 
15147 	}
15148 
15149 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15150 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15151 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
15152 		return (EIO);
15153 	}
15154 
15155 
15156 	/*
15157 	 * Forward space file marks.
15158 	 * We leave ourselves at block zero
15159 	 * of the target file number.
15160 	 */
15161 	if (files < 0) {
15162 		rval = st_backward_space_files(un, -files, 0);
15163 	} else {
15164 		rval = st_forward_space_files(un, files);
15165 	}
15166 
15167 	return (rval);
15168 }
15169 
15170 static int
15171 st_forward_space_files(struct scsi_tape *un, int64_t count)
15172 {
15173 	int rval;
15174 
15175 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
15176 
15177 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15178 	    "fspace: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15179 
15180 	ASSERT(count >= 0);
15181 	ASSERT(un->un_pos.pmode != invalid);
15182 
15183 	/*
15184 	 * A space with a count of zero means take me to the start of file.
15185 	 */
15186 	if (count == 0) {
15187 
15188 		/* Hay look were already there */
15189 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0) {
15190 			un->un_err_resid = 0;
15191 			COPY_POS(&un->un_err_pos, &un->un_pos);
15192 			return (0);
15193 		}
15194 
15195 		/*
15196 		 * Well we are in the first file.
15197 		 * A rewind will get to the start.
15198 		 */
15199 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
15200 			rval = st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
15201 
15202 		/*
15203 		 * Can we backspace to get there?
15204 		 * This should work in logical mode.
15205 		 */
15206 		} else if (un->un_dp->options & ST_BSF) {
15207 			rval = st_space_to_begining_of_file(un);
15208 
15209 		/*
15210 		 * Can't back space but current file number is known,
15211 		 * So rewind and space from the begining of the partition.
15212 		 */
15213 		} else if (un->un_pos.pmode == legacy) {
15214 			rval = st_scenic_route_to_begining_of_file(un,
15215 			    un->un_pos.fileno);
15216 
15217 		/*
15218 		 * pmode is logical and ST_BSF is not set.
15219 		 * The LONG_POS read position contains the fileno.
15220 		 * If the read position works, rewind and space.
15221 		 */
15222 		} else if (un->un_read_pos_type == LONG_POS) {
15223 			rval = st_cmd(un, SCMD_READ_POSITION, 0, SYNC_CMD);
15224 			if (rval) {
15225 				/*
15226 				 * We didn't get the file position from the
15227 				 * read position command.
15228 				 * We are going to trust the drive to backspace
15229 				 * and then position after the filemark.
15230 				 */
15231 				rval = st_space_to_begining_of_file(un);
15232 			}
15233 			rval = st_interpret_read_pos(un, &un->un_pos, LONG_POS,
15234 			    32, (caddr_t)un->un_read_pos_data, 0);
15235 			if ((rval) && (un->un_pos.pmode == invalid)) {
15236 				rval = st_space_to_begining_of_file(un);
15237 			} else {
15238 				rval = st_scenic_route_to_begining_of_file(un,
15239 				    un->un_pos.fileno);
15240 			}
15241 		} else {
15242 			rval = EIO;
15243 		}
15244 		/*
15245 		 * If something didn't work we are lost
15246 		 */
15247 		if (rval != 0) {
15248 			un->un_pos.pmode = invalid;
15249 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15250 			    "st_mtioctop : EIO : fspace pmode invalid");
15251 
15252 			rval = EIO;
15253 		}
15254 
15255 	} else {
15256 		rval = st_space_fmks(un, count);
15257 	}
15258 
15259 	if (rval != EIO && count < 0) {
15260 		/*
15261 		 * we came here with a count < 0; we now need
15262 		 * to skip back to end up before the filemark
15263 		 */
15264 		rval = st_backward_space_files(un, 1, 1);
15265 	}
15266 
15267 	return (rval);
15268 }
15269 
15270 static int
15271 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
15272 {
15273 	int rval;
15274 
15275 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
15276 
15277 	if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15278 		rval = EIO;
15279 	} else if (st_cmd(un, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
15280 		rval = EIO;
15281 	}
15282 
15283 	return (rval);
15284 }
15285 
15286 static int
15287 st_space_to_begining_of_file(struct scsi_tape *un)
15288 {
15289 	int rval;
15290 
15291 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
15292 
15293 	/*
15294 	 * Back space of the file at the begining of the file.
15295 	 */
15296 	rval = st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
15297 	if (rval) {
15298 		rval = EIO;
15299 		return (rval);
15300 	}
15301 
15302 	/*
15303 	 * Other interesting answers might be crashed BOT which isn't bad.
15304 	 */
15305 	if (un->un_status == SUN_KEY_BOT) {
15306 		return (rval);
15307 	}
15308 
15309 	un->un_running.pmode = invalid;
15310 
15311 	/*
15312 	 * Now we are on the BOP side of the filemark. Forward space to
15313 	 * the EOM side and we are at the begining of the file.
15314 	 */
15315 	rval = st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD);
15316 	if (rval) {
15317 		rval = EIO;
15318 	}
15319 
15320 	return (rval);
15321 }
15322 
15323 static int
15324 st_mtfsr_ioctl(struct scsi_tape *un, int64_t count)
15325 {
15326 
15327 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
15328 
15329 	/*
15330 	 * forward space to inter-record gap
15331 	 *
15332 	 */
15333 
15334 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15335 	    "st_ioctl_fsr: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15336 
15337 	if (un->un_pos.pmode == legacy) {
15338 		/*
15339 		 * If were are at end of tape and count is forward.
15340 		 * Return blank check.
15341 		 */
15342 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
15343 			/* we're at EOM */
15344 			un->un_err_resid = count;
15345 			un->un_status = KEY_BLANK_CHECK;
15346 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15347 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
15348 			return (EIO);
15349 		}
15350 
15351 		/*
15352 		 * If count is zero there is nothing to do.
15353 		 */
15354 		if (count == 0) {
15355 			un->un_err_pos.fileno = un->un_pos.fileno;
15356 			un->un_err_pos.blkno = un->un_pos.blkno;
15357 			un->un_err_resid = 0;
15358 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15359 				un->un_status = SUN_KEY_EOF;
15360 			}
15361 			return (0);
15362 		}
15363 
15364 		/*
15365 		 * physical tape position may not be what we've been
15366 		 * telling the user; adjust the position accordingly
15367 		 */
15368 		if (IN_EOF(un->un_pos)) {
15369 			daddr_t blkno = un->un_pos.blkno;
15370 			int fileno = un->un_pos.fileno;
15371 
15372 			optype lastop = un->un_lastop;
15373 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)
15374 			    == -1) {
15375 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15376 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
15377 				return (EIO);
15378 			}
15379 
15380 			un->un_pos.blkno = blkno;
15381 			un->un_pos.fileno = fileno;
15382 			un->un_lastop = lastop;
15383 		}
15384 	}
15385 
15386 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15387 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15388 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
15389 		return (EIO);
15390 	}
15391 
15392 	return (st_space_records(un, count));
15393 }
15394 
15395 static int
15396 st_space_records(struct scsi_tape *un, int64_t count)
15397 {
15398 	int64_t dblk;
15399 	int rval = 0;
15400 
15401 	ST_FUNC(ST_DEVINFO, st_space_records);
15402 
15403 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15404 	    "st_space_records: count=%"PRIx64", eof=%x\n",
15405 	    count, un->un_pos.eof);
15406 
15407 	if (un->un_pos.pmode == logical) {
15408 		rval = st_cmd(un, SCMD_SPACE, Blk(count), SYNC_CMD);
15409 		if (rval != 0) {
15410 			rval = EIO;
15411 		}
15412 		return (rval);
15413 	}
15414 
15415 	dblk = count + un->un_pos.blkno;
15416 
15417 	/* Already there */
15418 	if (dblk == un->un_pos.blkno) {
15419 		un->un_err_resid = 0;
15420 		COPY_POS(&un->un_err_pos, &un->un_pos);
15421 		return (0);
15422 	}
15423 
15424 	/*
15425 	 * If the destination block is forward
15426 	 * or the drive will backspace records.
15427 	 */
15428 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
15429 		/*
15430 		 * If we're spacing forward, or the device can
15431 		 * backspace records, we can just use the SPACE
15432 		 * command.
15433 		 */
15434 		dblk -= un->un_pos.blkno;
15435 		if (st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15436 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15437 			    "st_space_records:EIO:space_records can't spc");
15438 			rval = EIO;
15439 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
15440 			/*
15441 			 * check if we hit BOT/EOT
15442 			 */
15443 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
15444 				un->un_status = SUN_KEY_BOT;
15445 				un->un_pos.eof = ST_NO_EOF;
15446 			} else if (dblk < 0 &&
15447 			    un->un_pos.eof == ST_EOF_PENDING) {
15448 				int residue = un->un_err_resid;
15449 				/*
15450 				 * we skipped over a filemark
15451 				 * and need to go forward again
15452 				 */
15453 				if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
15454 					ST_DEBUG2(ST_DEVINFO, st_label,
15455 					    SCSI_DEBUG, "st_space_records: EIO"
15456 					    " : can't space #2");
15457 					rval = EIO;
15458 				}
15459 				un->un_err_resid = residue;
15460 			}
15461 			if (rval == 0) {
15462 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15463 				    "st_space_records: EIO : space_rec rval"
15464 				    " == 0");
15465 				rval = EIO;
15466 			}
15467 		}
15468 	} else {
15469 		/*
15470 		 * else we rewind, space forward across filemarks to
15471 		 * the desired file, and then space records to the
15472 		 * desired block.
15473 		 */
15474 
15475 		int dfile = un->un_pos.fileno;	/* save current file */
15476 
15477 		if (dblk < 0) {
15478 			/*
15479 			 * Wups - we're backing up over a filemark
15480 			 */
15481 			if (un->un_pos.blkno != 0 &&
15482 			    (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15483 			    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD))) {
15484 				un->un_pos.pmode = invalid;
15485 			}
15486 			un->un_err_resid = -dblk;
15487 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
15488 				un->un_status = SUN_KEY_BOT;
15489 				un->un_pos.eof = ST_NO_EOF;
15490 			} else if (un->un_pos.fileno > 0) {
15491 				un->un_status = SUN_KEY_EOF;
15492 				un->un_pos.eof = ST_NO_EOF;
15493 			}
15494 			COPY_POS(&un->un_err_pos, &un->un_pos);
15495 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15496 			    "st_space_records:EIO:space_records : dblk < 0");
15497 			rval = EIO;
15498 		} else if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15499 		    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
15500 		    st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15501 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15502 			    "st_space_records: EIO :space_records : rewind "
15503 			    "and space failed");
15504 			un->un_pos.pmode = invalid;
15505 			rval = EIO;
15506 		}
15507 	}
15508 
15509 	return (rval);
15510 }
15511 
15512 static int
15513 st_mtbsf_ioctl(struct scsi_tape *un, int64_t files)
15514 {
15515 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
15516 
15517 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15518 	    "st_mtbsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15519 	/*
15520 	 * backward space of file filemark (1/2" and 8mm)
15521 	 * tape position will end on the beginning of tape side
15522 	 * of the desired file mark
15523 	 */
15524 	if ((un->un_dp->options & ST_BSF) == 0) {
15525 		return (ENOTTY);
15526 	}
15527 
15528 	if (un->un_pos.pmode == legacy) {
15529 
15530 		/*
15531 		 * If a negative count (which implies a forward space op)
15532 		 * is specified, and we're at logical or physical eot,
15533 		 * bounce the request.
15534 		 */
15535 
15536 		if (un->un_pos.eof >= ST_EOT && files < 0) {
15537 			un->un_err_resid = files;
15538 			un->un_status = SUN_KEY_EOT;
15539 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15540 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
15541 			return (EIO);
15542 		}
15543 		/*
15544 		 * physical tape position may not be what we've been
15545 		 * telling the user; adjust the request accordingly
15546 		 */
15547 		if (IN_EOF(un->un_pos)) {
15548 			un->un_pos.fileno++;
15549 			un->un_pos.blkno = 0;
15550 			files++;
15551 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15552 			    "st_mtbsf_ioctl in eof: count=%"PRIx64", op=%x\n",
15553 			    files, MTBSF);
15554 
15555 		}
15556 	}
15557 
15558 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15559 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15560 		    "st_ioctl : EIO : MTBSF : check den wfm");
15561 		return (EIO);
15562 	}
15563 
15564 	if (files <= 0) {
15565 		/*
15566 		 * for a negative count, we need to step forward
15567 		 * first and then step back again
15568 		 */
15569 		files = -files + 1;
15570 		return (st_forward_space_files(un, files));
15571 	}
15572 	return (st_backward_space_files(un, files, 1));
15573 }
15574 
15575 static int
15576 st_backward_space_files(struct scsi_tape *un, int64_t count, int infront)
15577 {
15578 	int64_t end_fileno;
15579 	int64_t skip_cnt;
15580 	int rval = 0;
15581 
15582 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
15583 
15584 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15585 	    "st_backward_space_files: count=%"PRIx64" eof=%x\n",
15586 	    count, un->un_pos.eof);
15587 	/*
15588 	 * Backspace files (MTNBSF): infront == 0
15589 	 *
15590 	 *	For tapes that can backspace, backspace
15591 	 *	count+1 filemarks and then run forward over
15592 	 *	a filemark
15593 	 *
15594 	 *	For tapes that can't backspace,
15595 	 *		calculate desired filenumber
15596 	 *		(un->un_pos.fileno - count), rewind,
15597 	 *		and then space forward this amount
15598 	 *
15599 	 * Backspace filemarks (MTBSF) infront == 1
15600 	 *
15601 	 *	For tapes that can backspace, backspace count
15602 	 *	filemarks
15603 	 *
15604 	 *	For tapes that can't backspace, calculate
15605 	 *	desired filenumber (un->un_pos.fileno - count),
15606 	 *	add 1, rewind, space forward this amount,
15607 	 *	and mark state as ST_EOF_PENDING appropriately.
15608 	 */
15609 
15610 	if (un->un_pos.pmode == logical) {
15611 
15612 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15613 		    "st_backward_space_files: mt_op=%x count=%"PRIx64
15614 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
15615 		    un->un_pos.lgclblkno);
15616 
15617 
15618 		/* In case a drive that won't back space gets in logical mode */
15619 		if ((un->un_dp->options & ST_BSF) == 0) {
15620 			rval = EIO;
15621 			return (rval);
15622 		}
15623 		if ((infront == 1) &&
15624 		    (st_cmd(un, SCMD_SPACE, Fmk(-count), SYNC_CMD))) {
15625 			rval = EIO;
15626 			return (rval);
15627 		} else if ((infront == 0) &&
15628 		    (st_cmd(un, SCMD_SPACE, Fmk((-count)-1), SYNC_CMD)) &&
15629 		    (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
15630 			rval = EIO;
15631 			return (rval);
15632 		}
15633 		return (rval);
15634 	}
15635 
15636 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15637 	    "st_backward_space_files: mt_op=%x count=%"PRIx64
15638 	    "fileno=%x blkno=%x\n",
15639 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
15640 
15641 
15642 
15643 	/*
15644 	 * Handle the simple case of BOT
15645 	 * playing a role in these cmds.
15646 	 * We do this by calculating the
15647 	 * ending file number. If the ending
15648 	 * file is < BOT, rewind and set an
15649 	 * error and mark resid appropriately.
15650 	 * If we're backspacing a file (not a
15651 	 * filemark) and the target file is
15652 	 * the first file on the tape, just
15653 	 * rewind.
15654 	 */
15655 
15656 	/* figure expected destination of this SPACE command */
15657 	end_fileno = un->un_pos.fileno - count;
15658 
15659 	/*
15660 	 * Would the end effect of this SPACE be the same as rewinding?
15661 	 * If so just rewind instead.
15662 	 */
15663 	if ((infront != 0) && (end_fileno < 0) ||
15664 	    (infront == 0) && (end_fileno <= 0)) {
15665 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15666 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15667 			    "st_backward_space_files: EIO : "
15668 			    "rewind in lou of BSF failed\n");
15669 			rval = EIO;
15670 		}
15671 		if (end_fileno < 0) {
15672 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15673 			    "st_backward_space_files: EIO : "
15674 			    "back space file greater then fileno\n");
15675 			rval = EIO;
15676 			un->un_err_resid = -end_fileno;
15677 			un->un_status = SUN_KEY_BOT;
15678 		}
15679 		return (rval);
15680 	}
15681 
15682 	if (un->un_dp->options & ST_BSF) {
15683 		skip_cnt = 1 - infront;
15684 		/*
15685 		 * If we are going to end up at the beginning
15686 		 * of the file, we have to space one extra file
15687 		 * first, and then space forward later.
15688 		 */
15689 		end_fileno = -(count + skip_cnt);
15690 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15691 		    "skip_cnt=%"PRIx64", tmp=%"PRIx64"\n",
15692 		    skip_cnt, end_fileno);
15693 		if (st_cmd(un, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
15694 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15695 			    "st_backward_space_files:EIO:back space fm failed");
15696 			rval = EIO;
15697 		}
15698 	} else {
15699 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15700 			rval = EIO;
15701 		} else {
15702 			skip_cnt = end_fileno + infront;
15703 		}
15704 	}
15705 
15706 	/*
15707 	 * If we have to space forward, do so...
15708 	 */
15709 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15710 	    "space forward skip_cnt=%"PRIx64", rval=%x\n", skip_cnt, rval);
15711 
15712 	if (rval == 0 && skip_cnt) {
15713 		if (st_cmd(un, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
15714 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15715 			    "st_backward_space_files:EIO:space fm skip count");
15716 			rval = EIO;
15717 		} else if (infront) {
15718 			/*
15719 			 * If we had to space forward, and we're
15720 			 * not a tape that can backspace, mark state
15721 			 * as if we'd just seen a filemark during a
15722 			 * a read.
15723 			 */
15724 			if ((un->un_dp->options & ST_BSF) == 0) {
15725 				un->un_pos.eof = ST_EOF_PENDING;
15726 				un->un_pos.fileno -= 1;
15727 				un->un_pos.blkno = LASTBLK;
15728 				un->un_running.pmode = invalid;
15729 			}
15730 		}
15731 	}
15732 
15733 	if (rval != 0) {
15734 		un->un_pos.pmode = invalid;
15735 	}
15736 
15737 	return (rval);
15738 }
15739 
15740 static int
15741 st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count)
15742 {
15743 	int rval;
15744 
15745 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
15746 
15747 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15748 	    "nbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15749 
15750 	if (un->un_pos.pmode == legacy) {
15751 		/*
15752 		 * backward space file to beginning of file
15753 		 *
15754 		 * If a negative count (which implies a forward space op)
15755 		 * is specified, and we're at logical or physical eot,
15756 		 * bounce the request.
15757 		 */
15758 
15759 		if (un->un_pos.eof >= ST_EOT && count < 0) {
15760 			un->un_err_resid = count;
15761 			un->un_status = SUN_KEY_EOT;
15762 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15763 			    "st_ioctl : EIO : > EOT and count < 0");
15764 			return (EIO);
15765 		}
15766 		/*
15767 		 * physical tape position may not be what we've been
15768 		 * telling the user; adjust the request accordingly
15769 		 */
15770 		if (IN_EOF(un->un_pos)) {
15771 			un->un_pos.fileno++;
15772 			un->un_pos.blkno = 0;
15773 			count++;
15774 		}
15775 	}
15776 
15777 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15778 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15779 		    "st_ioctl : EIO : MTNBSF check den and wfm");
15780 		return (EIO);
15781 	}
15782 
15783 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15784 	    "mtnbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15785 
15786 	if (count <= 0) {
15787 		rval = st_forward_space_files(un, -count);
15788 	} else {
15789 		rval = st_backward_space_files(un, count, 0);
15790 	}
15791 	return (rval);
15792 }
15793 
15794 static int
15795 st_mtbsr_ioctl(struct scsi_tape *un, int64_t num)
15796 {
15797 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
15798 
15799 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15800 	    "bsr: count=%"PRIx64", eof=%x\n", num, un->un_pos.eof);
15801 
15802 	if (un->un_pos.pmode == legacy) {
15803 		/*
15804 		 * backward space into inter-record gap
15805 		 *
15806 		 * If a negative count (which implies a forward space op)
15807 		 * is specified, and we're at logical or physical eot,
15808 		 * bounce the request.
15809 		 */
15810 		if (un->un_pos.eof >= ST_EOT && num < 0) {
15811 			un->un_err_resid = num;
15812 			un->un_status = SUN_KEY_EOT;
15813 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15814 			    "st_ioctl : EIO : MTBSR > EOT");
15815 			return (EIO);
15816 		}
15817 
15818 		if (num == 0) {
15819 			COPY_POS(&un->un_err_pos, &un->un_pos);
15820 			un->un_err_resid = 0;
15821 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15822 				un->un_status = SUN_KEY_EOF;
15823 			}
15824 			return (0);
15825 		}
15826 
15827 		/*
15828 		 * physical tape position may not be what we've been
15829 		 * telling the user; adjust the position accordingly.
15830 		 * bsr can not skip filemarks and continue to skip records
15831 		 * therefore if we are logically before the filemark but
15832 		 * physically at the EOT side of the filemark, we need to step
15833 		 * back; this allows fsr N where N > number of blocks in file
15834 		 * followed by bsr 1 to position at the beginning of last block
15835 		 */
15836 		if (IN_EOF(un->un_pos)) {
15837 			tapepos_t save;
15838 			optype lastop = un->un_lastop;
15839 
15840 			COPY_POS(&save, &un->un_pos);
15841 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD) == -1) {
15842 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15843 				    "st_mtbsr_ioctl: EIO : MTBSR can't space");
15844 				return (EIO);
15845 			}
15846 
15847 			COPY_POS(&un->un_pos, &save);
15848 			un->un_lastop = lastop;
15849 		}
15850 	}
15851 
15852 	un->un_pos.eof = ST_NO_EOF;
15853 
15854 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15855 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15856 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
15857 		return (EIO);
15858 	}
15859 
15860 	num = -num;
15861 	return (st_space_records(un, num));
15862 }
15863 
15864 static int
15865 st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt)
15866 {
15867 	int rval;
15868 
15869 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
15870 
15871 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
15872 	if (rval == 0) {
15873 		un->un_pos.pmode = logical;
15874 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15875 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15876 		/*
15877 		 * Drive says invalid field in cdb.
15878 		 * Doesn't like space multiple. Position isn't lost.
15879 		 */
15880 		un->un_err_resid = cnt;
15881 		un->un_status = 0;
15882 		rval = ENOTTY;
15883 	} else {
15884 		un->un_err_resid = cnt;
15885 		un->un_pos.pmode = invalid;
15886 	}
15887 	return (rval);
15888 }
15889 
15890 static int
15891 st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt)
15892 {
15893 	int rval;
15894 
15895 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
15896 
15897 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
15898 	if (rval == 0) {
15899 		un->un_pos.pmode = logical;
15900 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15901 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15902 		/*
15903 		 * Drive says invalid field in cdb.
15904 		 * Doesn't like space multiple. Position isn't lost.
15905 		 */
15906 		un->un_err_resid = cnt;
15907 		un->un_status = 0;
15908 		rval = ENOTTY;
15909 	} else {
15910 		un->un_err_resid = cnt;
15911 		un->un_pos.pmode = invalid;
15912 	}
15913 	return (rval);
15914 }
15915 
15916 #ifdef	__x86
15917 
15918 /*
15919  * release contig_mem and wake up waiting thread, if any
15920  */
15921 static void
15922 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
15923 {
15924 	mutex_enter(ST_MUTEX);
15925 
15926 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
15927 
15928 	cp->cm_next = un->un_contig_mem;
15929 	un->un_contig_mem = cp;
15930 	un->un_contig_mem_available_num++;
15931 	cv_broadcast(&un->un_contig_mem_cv);
15932 
15933 	mutex_exit(ST_MUTEX);
15934 }
15935 
15936 /*
15937  * St_get_contig_mem will return a contig_mem if there is one available
15938  * in current system. Otherwise, it will try to alloc one, if the total
15939  * number of contig_mem is within st_max_contig_mem_num.
15940  * It will sleep, if allowed by caller or return NULL, if no contig_mem
15941  * is available for now.
15942  */
15943 static struct contig_mem *
15944 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
15945 {
15946 	size_t rlen;
15947 	struct contig_mem *cp = NULL;
15948 	ddi_acc_handle_t acc_hdl;
15949 	caddr_t addr;
15950 	int big_enough = 0;
15951 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
15952 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
15953 
15954 	/* Try to get one available contig_mem */
15955 	mutex_enter(ST_MUTEX);
15956 
15957 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
15958 
15959 	if (un->un_contig_mem_available_num > 0) {
15960 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15961 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
15962 		/*
15963 		 * we failed to get one. we're going to
15964 		 * alloc one more contig_mem for this I/O
15965 		 */
15966 		mutex_exit(ST_MUTEX);
15967 		cp = (struct contig_mem *)kmem_zalloc(
15968 		    sizeof (struct contig_mem) + biosize(),
15969 		    alloc_flags);
15970 		if (cp == NULL) {
15971 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15972 			    "alloc contig_mem failure\n");
15973 			return (NULL); /* cannot get one */
15974 		}
15975 		cp->cm_bp = (struct buf *)
15976 		    (((caddr_t)cp) + sizeof (struct contig_mem));
15977 		bioinit(cp->cm_bp);
15978 		mutex_enter(ST_MUTEX);
15979 		un->un_contig_mem_total_num++; /* one more available */
15980 	} else {
15981 		/*
15982 		 * we failed to get one and we're NOT allowed to
15983 		 * alloc more contig_mem
15984 		 */
15985 		if (alloc_flags == KM_SLEEP) {
15986 			while (un->un_contig_mem_available_num <= 0) {
15987 				cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
15988 			}
15989 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15990 		} else {
15991 			mutex_exit(ST_MUTEX);
15992 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15993 			    "alloc contig_mem failure\n");
15994 			return (NULL); /* cannot get one */
15995 		}
15996 	}
15997 	mutex_exit(ST_MUTEX);
15998 
15999 	/* We need to check if this block of mem is big enough for this I/O */
16000 	if (cp->cm_len < len) {
16001 		/* not big enough, need to alloc a new one */
16002 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
16003 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
16004 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
16005 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16006 			    "alloc contig_mem failure: not enough mem\n");
16007 			st_release_contig_mem(un, cp);
16008 			cp = NULL;
16009 		} else {
16010 			if (cp->cm_addr) {
16011 				/* release previous one before attach new one */
16012 				ddi_dma_mem_free(&cp->cm_acc_hdl);
16013 			}
16014 			mutex_enter(ST_MUTEX);
16015 			un->un_max_contig_mem_len =
16016 			    un->un_max_contig_mem_len >= len ?
16017 			    un->un_max_contig_mem_len : len;
16018 			mutex_exit(ST_MUTEX);
16019 
16020 			/* attach new mem to this cp */
16021 			cp->cm_addr = addr;
16022 			cp->cm_acc_hdl = acc_hdl;
16023 			cp->cm_len = len;
16024 
16025 			goto alloc_ok; /* get one usable cp */
16026 		}
16027 	} else {
16028 		goto alloc_ok; /* get one usable cp */
16029 	}
16030 
16031 	/* cannot find/alloc a usable cp, when we get here */
16032 
16033 	mutex_enter(ST_MUTEX);
16034 	if ((un->un_max_contig_mem_len < len) ||
16035 	    (alloc_flags != KM_SLEEP)) {
16036 		mutex_exit(ST_MUTEX);
16037 		return (NULL);
16038 	}
16039 
16040 	/*
16041 	 * we're allowed to sleep, and there is one big enough
16042 	 * contig mem in the system, which is currently in use,
16043 	 * wait for it...
16044 	 */
16045 	big_enough = 1;
16046 	do {
16047 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16048 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16049 	} while (cp == NULL);
16050 	mutex_exit(ST_MUTEX);
16051 
16052 	/* we get the big enough contig mem, finally */
16053 
16054 alloc_ok:
16055 	/* init bp attached to this cp */
16056 	bioreset(cp->cm_bp);
16057 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
16058 	cp->cm_bp->b_private = (void *)cp;
16059 
16060 	return (cp);
16061 }
16062 
16063 /*
16064  * this is the biodone func for the bp used in big block I/O
16065  */
16066 static int
16067 st_bigblk_xfer_done(struct buf *bp)
16068 {
16069 	struct contig_mem *cp;
16070 	struct buf *orig_bp;
16071 	int ioerr;
16072 	struct scsi_tape *un;
16073 
16074 	/* sanity check */
16075 	if (bp == NULL) {
16076 		return (DDI_FAILURE);
16077 	}
16078 
16079 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16080 	if (un == NULL) {
16081 		return (DDI_FAILURE);
16082 	}
16083 
16084 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
16085 
16086 	cp = (struct contig_mem *)bp->b_private;
16087 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
16088 	cp->cm_bp = bp;
16089 
16090 	/* special handling for special I/O */
16091 	if (cp->cm_use_sbuf) {
16092 #ifndef __lock_lint
16093 		ASSERT(un->un_sbuf_busy);
16094 #endif
16095 		un->un_sbufp = orig_bp;
16096 		cp->cm_use_sbuf = 0;
16097 	}
16098 
16099 	orig_bp->b_resid = bp->b_resid;
16100 	ioerr = geterror(bp);
16101 	if (ioerr != 0) {
16102 		bioerror(orig_bp, ioerr);
16103 	} else if (orig_bp->b_flags & B_READ) {
16104 		/* copy data back to original bp */
16105 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
16106 		    bp->b_bcount - bp->b_resid);
16107 	}
16108 
16109 	st_release_contig_mem(un, cp);
16110 
16111 	biodone(orig_bp);
16112 
16113 	return (DDI_SUCCESS);
16114 }
16115 
16116 /*
16117  * We use this func to replace original bp that may not be able to do I/O
16118  * in big block size with one that can
16119  */
16120 static struct buf *
16121 st_get_bigblk_bp(struct buf *bp)
16122 {
16123 	struct contig_mem *cp;
16124 	struct scsi_tape *un;
16125 	struct buf *cont_bp;
16126 
16127 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16128 	if (un == NULL) {
16129 		return (bp);
16130 	}
16131 
16132 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
16133 
16134 	/* try to get one contig_mem */
16135 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
16136 	if (!cp) {
16137 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
16138 		    "Cannot alloc contig buf for I/O for %lu blk size",
16139 		    bp->b_bcount);
16140 		return (bp);
16141 	}
16142 	cont_bp = cp->cm_bp;
16143 	cp->cm_bp = bp;
16144 
16145 	/* make sure that we "are" using un_sbufp for special I/O */
16146 	if (bp == un->un_sbufp) {
16147 #ifndef __lock_lint
16148 		ASSERT(un->un_sbuf_busy);
16149 #endif
16150 		un->un_sbufp = cont_bp;
16151 		cp->cm_use_sbuf = 1;
16152 	}
16153 
16154 	/* clone bp */
16155 	cont_bp->b_bcount = bp->b_bcount;
16156 	cont_bp->b_resid = bp->b_resid;
16157 	cont_bp->b_iodone = st_bigblk_xfer_done;
16158 	cont_bp->b_file = bp->b_file;
16159 	cont_bp->b_offset = bp->b_offset;
16160 	cont_bp->b_dip = bp->b_dip;
16161 	cont_bp->b_error = 0;
16162 	cont_bp->b_proc = NULL;
16163 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
16164 	cont_bp->b_shadow = NULL;
16165 	cont_bp->b_pages = NULL;
16166 	cont_bp->b_edev = bp->b_edev;
16167 	cont_bp->b_dev = bp->b_dev;
16168 	cont_bp->b_lblkno = bp->b_lblkno;
16169 	cont_bp->b_forw = bp->b_forw;
16170 	cont_bp->b_back = bp->b_back;
16171 	cont_bp->av_forw = bp->av_forw;
16172 	cont_bp->av_back = bp->av_back;
16173 	cont_bp->b_bufsize = bp->b_bufsize;
16174 
16175 	/* get data in original bp */
16176 	if (bp->b_flags & B_WRITE) {
16177 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
16178 	}
16179 
16180 	return (cont_bp);
16181 }
16182 #else
16183 #ifdef __lock_lint
16184 static int
16185 st_bigblk_xfer_done(struct buf *bp)
16186 {
16187 	return (0);
16188 }
16189 #endif
16190 #endif
16191 
16192 static const char *eof_status[] =
16193 {
16194 	"NO_EOF",
16195 	"EOF_PENDING",
16196 	"EOF",
16197 	"EOT_PENDING",
16198 	"EOT",
16199 	"EOM",
16200 	"AFTER_EOM"
16201 };
16202 static const char *mode[] = {
16203 	"invalid",
16204 	"legacy",
16205 	"logical"
16206 };
16207 
16208 static void
16209 st_print_position(dev_info_t *dev, char *label, uint_t level,
16210 const char *comment, tapepos_t *pos)
16211 {
16212 	ST_FUNC(dev, st_print_position);
16213 
16214 	scsi_log(dev, label, level,
16215 	    "%s Position data:\n", comment);
16216 	scsi_log(dev, label, CE_CONT,
16217 	    "Positioning mode = %s", mode[pos->pmode]);
16218 	scsi_log(dev, label, CE_CONT,
16219 	    "End Of File/Tape = %s", eof_status[pos->eof]);
16220 	scsi_log(dev, label, CE_CONT,
16221 	    "File Number      = 0x%x", pos->fileno);
16222 	scsi_log(dev, label, CE_CONT,
16223 	    "Block Number     = 0x%x", pos->blkno);
16224 	scsi_log(dev, label, CE_CONT,
16225 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
16226 	scsi_log(dev, label, CE_CONT,
16227 	    "Partition Number = 0x%x", pos->partition);
16228 }
16229 static int
16230 st_check_if_media_changed(struct scsi_tape *un, caddr_t data, int size)
16231 {
16232 
16233 	int result = 0;
16234 	int i;
16235 	ST_FUNC(ST_DEVINFO, st_check_if_media_changed);
16236 
16237 	/*
16238 	 * find non alpha numeric working from the end.
16239 	 */
16240 	for (i = size - 1; i; i--) {
16241 		if (ISALNUM(data[i]) == 0 || data[i] == ' ') {
16242 			data[i] = 0;
16243 			size = i;
16244 		}
16245 	}
16246 
16247 	if (size == 1) {
16248 		/*
16249 		 * Drive seems to think its returning useful data
16250 		 * but it looks like all junk
16251 		 */
16252 		return (result);
16253 	}
16254 
16255 	size++;
16256 
16257 	/*
16258 	 * Actually got a valid serial number.
16259 	 * If never stored one before alloc space for it.
16260 	 */
16261 	if (un->un_media_id_len == 0) {
16262 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16263 		un->un_media_id_len = size;
16264 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16265 		un->un_media_id[min(size, strlen(data))] = 0;
16266 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16267 		    "Found Media Id %s length = %d\n", un->un_media_id, size);
16268 	} else if (size > un->un_media_id_len) {
16269 		if (strncmp(un->un_media_id, data, size) != 0) {
16270 			result = ESPIPE;
16271 		}
16272 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16273 		    "Longer Media Id old ID:%s new ID:%s\n",
16274 		    un->un_media_id, data);
16275 		kmem_free(un->un_media_id, un->un_media_id_len);
16276 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16277 		un->un_media_id_len = size;
16278 		(void) strncpy(un->un_media_id, data, size);
16279 		un->un_media_id[size] = 0;
16280 	} else if (strncmp(data, un->un_media_id,
16281 	    min(size, un->un_media_id_len)) != 0) {
16282 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16283 		    "Old Media Id %s length = %d New %s length = %d\n",
16284 		    un->un_media_id, un->un_media_id_len, data, size);
16285 		bzero(un->un_media_id, un->un_media_id_len);
16286 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16287 		un->un_media_id[min(size, strlen(data))] = 0;
16288 		result = ESPIPE;
16289 	} else {
16290 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
16291 		    "Media Id still %s\n", un->un_media_id);
16292 	}
16293 
16294 	ASSERT(strlen(un->un_media_id) <= size);
16295 
16296 	return (result);
16297 }
16298 #define	ID_SIZE 32
16299 typedef struct
16300 {
16301 	uchar_t avilable_data0;
16302 	uchar_t avilable_data1;
16303 	uchar_t avilable_data2;
16304 	uchar_t avilable_data3;
16305 	uchar_t attribute_msb;
16306 	uchar_t attribute_lsb;
16307 #ifdef _BIT_FIELDS_LTOH
16308 	uchar_t format		: 2,
16309 				: 5,
16310 		read_only	: 1;
16311 #else
16312 	uchar_t read_only	: 1,
16313 				: 5,
16314 		format		: 2;
16315 #endif
16316 	uchar_t attribute_len_msb;
16317 	uchar_t attribute_len_lsb;
16318 }attribute_header;
16319 
16320 typedef struct {
16321 	attribute_header header;
16322 	char data[1];
16323 }mam_attribute;
16324 
16325 static int
16326 st_handle_hex_media_id(struct scsi_tape *un, void *pnt, int size)
16327 {
16328 	int result;
16329 	int newsize = (size << 1) + 3; /* extra for leading 0x and null term */
16330 	int i;
16331 	uchar_t byte;
16332 	char *format;
16333 	uchar_t *data = (uchar_t *)pnt;
16334 	char *buf = kmem_alloc(newsize, KM_SLEEP);
16335 
16336 	ST_FUNC(ST_DEVINFO, st_handle_hex_media_id);
16337 
16338 	(void) sprintf(buf, "0x");
16339 	for (i = 0; i < size; i++) {
16340 		byte = data[i];
16341 		if (byte < 0x10)
16342 			format = "0%x";
16343 		else
16344 			format = "%x";
16345 		(void) sprintf(&buf[(int)strlen(buf)], format, byte);
16346 	}
16347 	result = st_check_if_media_changed(un, buf, newsize);
16348 
16349 	kmem_free(buf, newsize);
16350 
16351 	return (result);
16352 }
16353 
16354 
16355 static int
16356 st_get_media_id_via_read_attribute(struct scsi_tape *un, ubufunc_t bufunc)
16357 {
16358 	int result;
16359 	mam_attribute *buffer;
16360 	int size;
16361 	int newsize;
16362 
16363 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_read_attribute);
16364 	size = sizeof (attribute_header) + max(un->un_media_id_len, ID_SIZE);
16365 again:
16366 	buffer = kmem_zalloc(size, KM_SLEEP);
16367 	result = st_read_attributes(un, 0x0401, buffer, size, bufunc);
16368 	if (result == 0) {
16369 
16370 		newsize = (buffer->header.attribute_len_msb << 8) |
16371 		    buffer->header.attribute_len_lsb;
16372 
16373 		if (newsize + sizeof (attribute_header) > size) {
16374 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
16375 			    "resizing read attribute data from %d to %d format"
16376 			    " %d\n", size, (int)sizeof (attribute_header) +
16377 			    newsize, buffer->header.format);
16378 			kmem_free(buffer, size);
16379 			size = newsize + sizeof (attribute_header);
16380 			goto again;
16381 		}
16382 
16383 		un->un_media_id_method = st_get_media_id_via_read_attribute;
16384 		if (buffer->header.format == 0) {
16385 			result =
16386 			    st_handle_hex_media_id(un, buffer->data, newsize);
16387 		} else {
16388 			result = st_check_if_media_changed(un, buffer->data,
16389 			    newsize);
16390 		}
16391 	} else if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
16392 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
16393 		    "Read Attribute Command for Media Identification is not "
16394 		    "supported on the HBA that this drive is attached to.");
16395 		result = ENOTTY;
16396 	}
16397 
16398 	kmem_free(buffer, size);
16399 	un->un_status = 0;
16400 
16401 	return (result);
16402 }
16403 
16404 
16405 static int
16406 st_get_media_id_via_media_serial_cmd(struct scsi_tape *un, ubufunc_t bufunc)
16407 {
16408 	char cdb[CDB_GROUP5];
16409 	struct uscsi_cmd *ucmd;
16410 	struct scsi_extended_sense sense;
16411 	int rval;
16412 	int size = max(un->un_media_id_len, ID_SIZE);
16413 	caddr_t buf;
16414 
16415 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_media_serial_cmd);
16416 
16417 	if (un->un_sd->sd_inq->inq_ansi < 3) {
16418 		return (ENOTTY);
16419 	}
16420 
16421 	ucmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
16422 upsize:
16423 	buf = kmem_alloc(size, KM_SLEEP);
16424 
16425 	cdb[0] = (char)SCMD_SVC_ACTION_IN_G5;
16426 	cdb[1] = SSVC_ACTION_READ_MEDIA_SERIAL;
16427 	cdb[2] = 0;
16428 	cdb[3] = 0;
16429 	cdb[4] = 0;
16430 	cdb[5] = 0;
16431 	cdb[6] = (char)(size >> 24);
16432 	cdb[7] = (char)(size >> 16);
16433 	cdb[8] = (char)(size >> 8);
16434 	cdb[9] = (char)(size);
16435 	cdb[10] = 0;
16436 	cdb[11] = 0;
16437 
16438 	ucmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
16439 	ucmd->uscsi_timeout = un->un_dp->non_motion_timeout;
16440 	ucmd->uscsi_cdb = &cdb[0];
16441 	ucmd->uscsi_cdblen = sizeof (cdb);
16442 	ucmd->uscsi_bufaddr = buf;
16443 	ucmd->uscsi_buflen = size;
16444 	ucmd->uscsi_rqbuf = (caddr_t)&sense;
16445 	ucmd->uscsi_rqlen = sizeof (sense);
16446 
16447 	rval = bufunc(un, ucmd, FKIOCTL);
16448 
16449 	if (rval || ucmd->uscsi_status != 0) {
16450 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16451 		    "media serial command returned %d scsi_status %d"
16452 		    " rqstatus %d", rval, ucmd->uscsi_status,
16453 		    ucmd->uscsi_rqstatus);
16454 		/*
16455 		 * If this returns invalid operation code don't try again.
16456 		 */
16457 		if (sense.es_key == KEY_ILLEGAL_REQUEST &&
16458 		    sense.es_add_code == 0x20) {
16459 			rval = ENOTTY;
16460 		} else if (rval == 0) {
16461 			rval = EIO;
16462 		}
16463 		un->un_status = 0;
16464 	} else {
16465 		int act_size;
16466 
16467 		/*
16468 		 * get reported size.
16469 		 */
16470 		act_size = (int)buf[3] | (int)(buf[2] << 8) |
16471 		    (int)(buf[1] << 16) | (int)(buf[0] << 24);
16472 
16473 		/* documentation says mod 4. */
16474 		while (act_size & 3) {
16475 			act_size++;
16476 		}
16477 
16478 		/*
16479 		 * If reported size is larger that we our buffer.
16480 		 * Free the old one and allocate one that is larger
16481 		 * enough and re-issuse the command.
16482 		 */
16483 		if (act_size + 4 > size) {
16484 			kmem_free(buf, size);
16485 			size = act_size + 4;
16486 			goto upsize;
16487 		}
16488 
16489 		/*
16490 		 * set data pointer to point to the start of that serial number.
16491 		 */
16492 		un->un_media_id_method = st_get_media_id_via_media_serial_cmd;
16493 		rval = st_check_if_media_changed(un, &buf[4], act_size);
16494 	}
16495 
16496 	kmem_free(ucmd, sizeof (struct uscsi_cmd));
16497 	kmem_free(buf, size);
16498 
16499 	return (rval);
16500 }
16501 
16502 
16503 /* ARGSUSED */
16504 static int
16505 st_bogus_media_id(struct scsi_tape *un, ubufunc_t bufunc)
16506 {
16507 	ST_FUNC(ST_DEVINFO, st_bogus_media_id);
16508 
16509 	ASSERT(un->un_media_id == NULL || un->un_media_id == bogusID);
16510 	ASSERT(un->un_media_id_len == 0);
16511 	un->un_media_id = (char *)bogusID;
16512 	un->un_media_id_len = 0;
16513 	return (0);
16514 }
16515 
16516 typedef int (*media_chk_function)(struct scsi_tape *, ubufunc_t bufunc);
16517 
16518 media_chk_function media_chk_functions[] = {
16519 	st_get_media_id_via_media_serial_cmd,
16520 	st_get_media_id_via_read_attribute,
16521 	st_bogus_media_id
16522 };
16523 
16524 static int
16525 st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc)
16526 {
16527 	int result = 0;
16528 	int i;
16529 
16530 	ST_FUNC(ST_DEVINFO, st_get_media_identification);
16531 
16532 	for (i = 0; i < ST_NUM_MEMBERS(media_chk_functions); i++) {
16533 		if (result == ENOTTY) {
16534 			/*
16535 			 * Last operation type not supported by this device.
16536 			 * Make so next time it doesn`t do that again.
16537 			 */
16538 			un->un_media_id_method = media_chk_functions[i];
16539 		} else if (un->un_media_id_method != media_chk_functions[i] &&
16540 		    un->un_media_id_method != st_get_media_identification) {
16541 			continue;
16542 		}
16543 		result = media_chk_functions[i](un, bufunc);
16544 		/*
16545 		 * If result indicates the function was successful or
16546 		 * that the media is not the same as last known, break.
16547 		 */
16548 		if (result == 0 || result == ESPIPE) {
16549 			break;
16550 		}
16551 	}
16552 
16553 	return (result);
16554 }
16555 
16556 static errstate
16557 st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
16558     errstate onentry)
16559 {
16560 
16561 	int ret;
16562 	st_err_info *errinfo;
16563 	recov_info *ri = (recov_info *)pkt->pkt_private;
16564 
16565 	ST_FUNC(ST_DEVINFO, st_command_recovery);
16566 
16567 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16568 
16569 	ASSERT(un->un_recov_buf_busy == 0);
16570 
16571 	/*
16572 	 * Don't try and recover a reset that this device sent.
16573 	 */
16574 	if (un->un_rsvd_status & ST_INITIATED_RESET &&
16575 	    onentry == DEVICE_RESET) {
16576 		return (COMMAND_DONE_ERROR);
16577 	}
16578 
16579 	/*
16580 	 * See if expected position was passed with scsi_pkt.
16581 	 */
16582 	if (ri->privatelen == sizeof (recov_info)) {
16583 
16584 		/*
16585 		 * Not for this command.
16586 		 */
16587 		if (ri->cmd_attrib->do_not_recover) {
16588 			return (COMMAND_DONE_ERROR);
16589 		}
16590 
16591 		/*
16592 		 * Create structure to hold all error state info.
16593 		 */
16594 		errinfo = kmem_zalloc(ST_ERR_INFO_SIZE, KM_SLEEP);
16595 		errinfo->ei_error_type = onentry;
16596 		errinfo->ei_failing_bp = ri->cmd_bp;
16597 		COPY_POS(&errinfo->ei_expected_pos, &ri->pos);
16598 	} else {
16599 		/* disabled */
16600 		return (COMMAND_DONE_ERROR);
16601 	}
16602 
16603 	bcopy(pkt, &errinfo->ei_failed_pkt, scsi_pkt_size());
16604 	bcopy(pkt->pkt_scbp, &errinfo->ei_failing_status, SECMDS_STATUS_SIZE);
16605 	ret = ddi_taskq_dispatch(un->un_recov_taskq, st_recover, errinfo,
16606 	    DDI_NOSLEEP);
16607 	ASSERT(ret == DDI_SUCCESS);
16608 	if (ret != DDI_SUCCESS) {
16609 		kmem_free(errinfo, ST_ERR_INFO_SIZE);
16610 		return (COMMAND_DONE_ERROR);
16611 	}
16612 	return (JUST_RETURN); /* release calling thread */
16613 }
16614 
16615 
16616 static void
16617 st_recov_ret(struct scsi_tape *un, st_err_info *errinfo, errstate err)
16618 {
16619 	int error_number;
16620 	buf_t *bp;
16621 
16622 
16623 	ST_FUNC(ST_DEVINFO, st_recov_ret);
16624 
16625 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16626 #if !defined(lint)
16627 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
16628 #endif
16629 
16630 	bp = errinfo->ei_failing_bp;
16631 	kmem_free(errinfo, ST_ERR_INFO_SIZE);
16632 
16633 	switch (err) {
16634 	case JUST_RETURN:
16635 		mutex_exit(&un->un_sd->sd_mutex);
16636 		return;
16637 
16638 	case COMMAND_DONE:
16639 	case COMMAND_DONE_ERROR_RECOVERED:
16640 		ST_DO_KSTATS(bp, kstat_runq_exit);
16641 		error_number = 0;
16642 		break;
16643 
16644 	default:
16645 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16646 		    "st_recov_ret with unhandled errstat %d\n", err);
16647 		/* FALLTHROUGH */
16648 	case COMMAND_DONE_ERROR:
16649 	case COMMAND_DONE_EACCES:
16650 		ST_DO_KSTATS(bp, kstat_waitq_exit);
16651 		ST_DO_ERRSTATS(un, st_transerrs);
16652 		error_number = EIO;
16653 		st_set_pe_flag(un);
16654 		break;
16655 
16656 	}
16657 
16658 	st_bioerror(bp, error_number);
16659 	st_done_and_mutex_exit(un, bp);
16660 }
16661 
16662 
16663 static void
16664 st_recover(void *arg)
16665 {
16666 	st_err_info *const errinfo = (st_err_info *)arg;
16667 	uchar_t com = errinfo->ei_failed_pkt.pkt_cdbp[0];
16668 	struct scsi_tape *un;
16669 	tapepos_t cur_pos;
16670 	int rval;
16671 	errstate status = COMMAND_DONE_ERROR;
16672 	recov_info *rcv;
16673 	buf_t *bp;
16674 
16675 
16676 	rcv = errinfo->ei_failed_pkt.pkt_private;
16677 	ASSERT(rcv->privatelen == sizeof (recov_info));
16678 	bp = rcv->cmd_bp;
16679 
16680 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16681 
16682 	ASSERT(un != NULL);
16683 
16684 	mutex_enter(ST_MUTEX);
16685 
16686 	ST_FUNC(ST_DEVINFO, st_recover);
16687 
16688 	ST_CDB(ST_DEVINFO, "Recovering command",
16689 	    (caddr_t)errinfo->ei_failed_pkt.pkt_cdbp);
16690 	ST_SENSE(ST_DEVINFO, "sense status for failed command",
16691 	    (caddr_t)&errinfo->ei_failing_status,
16692 	    sizeof (struct scsi_arq_status));
16693 	ST_POS(ST_DEVINFO, rcv->cmd_attrib->recov_pos_type == POS_STARTING ?
16694 	    "starting position for recovery command" :
16695 	    "expected position for recovery command",
16696 	    &errinfo->ei_expected_pos);
16697 
16698 	rval = st_test_path_to_device(un);
16699 
16700 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16701 	    "st_recover called with %s, TUR returned %d\n",
16702 	    errstatenames[errinfo->ei_error_type], rval);
16703 	/*
16704 	 * If the drive responed to the TUR lets try and get it to sync
16705 	 * any data it might have in the buffer.
16706 	 */
16707 	if (rval == 0 && rcv->cmd_attrib->chg_tape_data) {
16708 		(void) st_rcmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
16709 	}
16710 	switch (errinfo->ei_error_type) {
16711 	case ATTEMPT_RETRY:
16712 	case COMMAND_TIMEOUT:
16713 	case DEVICE_RESET:
16714 	case PATH_FAILED:
16715 		/*
16716 		 * For now if we can't talk to the device we are done.
16717 		 * If the drive is reserved we can try to get it back.
16718 		 */
16719 		if (rval != 0 && rval != EACCES) {
16720 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16721 			return;
16722 		}
16723 
16724 		/*
16725 		 * If scsi II lost reserve try and get it back.
16726 		 */
16727 		if ((((un->un_rsvd_status &
16728 		    (ST_LOST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
16729 		    ST_LOST_RESERVE)) &&
16730 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] != SCMD_RELEASE)) {
16731 			rval = st_reserve_release(un, ST_RESERVE,
16732 			    st_uscsi_rcmd);
16733 			if (rval != 0) {
16734 				if (st_take_ownership(un, st_uscsi_rcmd) != 0) {
16735 					st_recov_ret(un, errinfo,
16736 					    COMMAND_DONE_EACCES);
16737 					return;
16738 				}
16739 			}
16740 			un->un_rsvd_status |= ST_RESERVE;
16741 			un->un_rsvd_status &= ~(ST_RELEASE | ST_LOST_RESERVE |
16742 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
16743 		}
16744 		rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16745 		if (rval) {
16746 			rval = st_gen_mode_select(un, st_uscsi_rcmd,
16747 			    un->un_mspl, sizeof (struct seq_mode));
16748 		}
16749 		if (rval) {
16750 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16751 			return;
16752 		}
16753 		break;
16754 	case DEVICE_TAMPER:
16755 		/*
16756 		 * Check if the ASC/ASCQ says mode data has changed.
16757 		 */
16758 		if ((errinfo->ei_failing_status.sts_sensedata.es_add_code ==
16759 		    0x2a) &&
16760 		    (errinfo->ei_failing_status.sts_sensedata.es_qual_code ==
16761 		    0x01)) {
16762 			/*
16763 			 * See if mode sense changed.
16764 			 */
16765 			rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16766 			if (rval) {
16767 				/*
16768 				 * If so change it back.
16769 				 */
16770 				rval = st_gen_mode_select(un, st_uscsi_rcmd,
16771 				    un->un_mspl, sizeof (struct seq_mode));
16772 			}
16773 			if (rval) {
16774 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16775 				return;
16776 			}
16777 		}
16778 		/*
16779 		 * if we have a media id and its not bogus.
16780 		 * Check to see if it the same.
16781 		 */
16782 		if (un->un_media_id != NULL && un->un_media_id != bogusID) {
16783 			rval = st_get_media_identification(un, st_uscsi_rcmd);
16784 			if (rval == ESPIPE) {
16785 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16786 				return;
16787 			}
16788 		}
16789 		break;
16790 	default:
16791 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16792 		    "Unhandled error type %s in st_recover() 0x%x\n",
16793 		    errstatenames[errinfo->ei_error_type], com);
16794 	}
16795 
16796 	/*
16797 	 * if command is retriable retry it.
16798 	 * Special case here. The command attribute for SCMD_REQUEST_SENSE
16799 	 * does not say that it is retriable. That because if you reissue a
16800 	 * request sense and the target responds the sense data will have
16801 	 * been consumed and no long be valid. If we get a busy status on
16802 	 * request sense while the state is ST_STATE_SENSING this will
16803 	 * reissue that pkt.
16804 	 *
16805 	 * XXX If this request sense gets sent to a different port then
16806 	 * the original command that failed was sent on it will not get
16807 	 * valid sense data for that command.
16808 	 */
16809 	if (rcv->cmd_attrib->retriable || un->un_rqs_bp == bp) {
16810 		status = st_recover_reissue_pkt(un, &errinfo->ei_failed_pkt);
16811 
16812 	/*
16813 	 * if drive doesn't support read position we are done
16814 	 */
16815 	} else if (un->un_read_pos_type == NO_POS) {
16816 		status = COMMAND_DONE_ERROR;
16817 	/*
16818 	 * If this command results in a changed tape position,
16819 	 * lets see where we are.
16820 	 */
16821 	} else if (rcv->cmd_attrib->chg_tape_pos) {
16822 		/*
16823 		 * XXX May be a reason to choose a different type here.
16824 		 * Long format has file position information.
16825 		 * Short and Extended have information about whats
16826 		 * in the buffer. St's positioning assumes in the buffer
16827 		 * to be the same as on tape.
16828 		 */
16829 		rval = st_compare_expected_position(un, errinfo,
16830 		    rcv->cmd_attrib, &cur_pos);
16831 		if (rval == 0) {
16832 			status = COMMAND_DONE;
16833 		} else if (rval == EAGAIN) {
16834 			status = st_recover_reissue_pkt(un,
16835 			    &errinfo->ei_failed_pkt);
16836 		} else {
16837 			status = COMMAND_DONE_ERROR;
16838 		}
16839 	} else {
16840 		ASSERT(0);
16841 	}
16842 
16843 	st_recov_ret(un, errinfo, status);
16844 }
16845 
16846 static void
16847 st_recov_cb(struct scsi_pkt *pkt)
16848 {
16849 	struct scsi_tape *un;
16850 	struct buf *bp;
16851 	recov_info *rcv;
16852 	errstate action = COMMAND_DONE_ERROR;
16853 	int timout = ST_TRAN_BUSY_TIMEOUT; /* short (default) timeout */
16854 
16855 	/*
16856 	 * Get the buf from the packet.
16857 	 */
16858 	rcv = pkt->pkt_private;
16859 	ASSERT(rcv->privatelen == sizeof (recov_info));
16860 	bp = rcv->cmd_bp;
16861 
16862 	/*
16863 	 * get the unit from the buf.
16864 	 */
16865 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16866 	ASSERT(un != NULL);
16867 
16868 	ST_FUNC(ST_DEVINFO, st_recov_cb);
16869 
16870 	mutex_enter(ST_MUTEX);
16871 
16872 	ASSERT(bp == un->un_recov_buf);
16873 
16874 
16875 	switch (pkt->pkt_reason) {
16876 	case CMD_CMPLT:
16877 		if (un->un_arq_enabled && pkt->pkt_state & STATE_ARQ_DONE) {
16878 			action = st_handle_autosense(un, bp, &rcv->pos);
16879 		} else  if ((SCBP(pkt)->sts_busy) ||
16880 		    (SCBP(pkt)->sts_chk) ||
16881 		    (SCBP(pkt)->sts_vu7)) {
16882 			action = st_check_error(un, pkt);
16883 		} else {
16884 			action = COMMAND_DONE;
16885 		}
16886 		break;
16887 	case CMD_TIMEOUT:
16888 		action = COMMAND_TIMEOUT;
16889 		break;
16890 	case CMD_TRAN_ERR:
16891 		action = QUE_COMMAND;
16892 		break;
16893 	default:
16894 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16895 		    "pkt_reason not handled yet %s",
16896 		    scsi_rname(pkt->pkt_reason));
16897 		action = COMMAND_DONE_ERROR;
16898 	}
16899 
16900 	/*
16901 	 * check for undetected path failover.
16902 	 */
16903 	if ((un->un_multipath) &&
16904 	    (un->un_last_path_instance != pkt->pkt_path_instance)) {
16905 		if (un->un_state > ST_STATE_OPENING) {
16906 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16907 			    "Failover detected in recovery, action is %s\n",
16908 			    errstatenames[action]);
16909 		}
16910 		un->un_last_path_instance = pkt->pkt_path_instance;
16911 	}
16912 
16913 	ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
16914 	    "Recovery call back got %s status on %s\n",
16915 	    errstatenames[action], st_print_scsi_cmd(pkt->pkt_cdbp[0]));
16916 
16917 	switch (action) {
16918 	case COMMAND_DONE:
16919 		break;
16920 
16921 	case COMMAND_DONE_EACCES:
16922 		bioerror(bp, EACCES);
16923 		break;
16924 
16925 	case COMMAND_DONE_ERROR_RECOVERED: /* XXX maybe wrong */
16926 		ASSERT(0);
16927 		break;
16928 
16929 	case COMMAND_TIMEOUT:
16930 	case COMMAND_DONE_ERROR:
16931 		bioerror(bp, EIO);
16932 		break;
16933 
16934 	case DEVICE_RESET:
16935 	case QUE_BUSY_COMMAND:
16936 	case PATH_FAILED:
16937 		/* longish timeout */
16938 		timout = ST_STATUS_BUSY_TIMEOUT;
16939 		/* FALLTHRU */
16940 	case QUE_COMMAND:
16941 	case DEVICE_TAMPER:
16942 	case ATTEMPT_RETRY:
16943 		/*
16944 		 * let st_handle_intr_busy put this bp back on waitq and make
16945 		 * checks to see if it is ok to requeue the command.
16946 		 */
16947 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
16948 
16949 		/*
16950 		 * Save the throttle before setting up the timeout
16951 		 */
16952 		if (un->un_throttle) {
16953 			un->un_last_throttle = un->un_throttle;
16954 		}
16955 		mutex_exit(ST_MUTEX);
16956 		if (st_handle_intr_busy(un, bp, timout) == 0) {
16957 			return;		/* timeout is setup again */
16958 		}
16959 		mutex_enter(ST_MUTEX);
16960 		un->un_pos.pmode = invalid;
16961 		un->un_err_resid = bp->b_resid = bp->b_bcount;
16962 		st_bioerror(bp, EIO);
16963 		st_set_pe_flag(un);
16964 		break;
16965 
16966 	default:
16967 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16968 		    "Unhandled recovery state 0x%x\n", action);
16969 		un->un_pos.pmode = invalid;
16970 		un->un_err_resid = bp->b_resid = bp->b_bcount;
16971 		st_bioerror(bp, EIO);
16972 		st_set_pe_flag(un);
16973 		break;
16974 	}
16975 
16976 	st_done_and_mutex_exit(un, bp);
16977 }
16978 
16979 static int
16980 st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait)
16981 {
16982 	struct buf *bp;
16983 	int err;
16984 
16985 	ST_FUNC(ST_DEVINFO, st_rcmd);
16986 
16987 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16988 	    "st_rcmd(un = 0x%p, com = 0x%x, count = %"PRIx64", wait = %d)\n",
16989 	    (void *)un, com, count, wait);
16990 
16991 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16992 	ASSERT(mutex_owned(ST_MUTEX));
16993 
16994 #ifdef STDEBUG
16995 	if ((st_debug & 0x7)) {
16996 		st_debug_cmds(un, com, count, wait);
16997 	}
16998 #endif
16999 
17000 	while (un->un_recov_buf_busy)
17001 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17002 	un->un_recov_buf_busy = 1;
17003 
17004 	bp = un->un_recov_buf;
17005 	bzero(bp, sizeof (buf_t));
17006 
17007 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
17008 
17009 	err = st_setup_cmd(un, bp, com, count);
17010 
17011 	un->un_recov_buf_busy = 0;
17012 
17013 	cv_signal(&un->un_recov_buf_cv);
17014 
17015 	return (err);
17016 }
17017 
17018 /* args used */
17019 static int
17020 st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
17021 {
17022 	int rval;
17023 	buf_t *bp;
17024 
17025 	ST_FUNC(ST_DEVINFO, st_uscsi_rcmd);
17026 	ASSERT(flag == FKIOCTL);
17027 
17028 	/*
17029 	 * Get buffer resources...
17030 	 */
17031 	while (un->un_recov_buf_busy)
17032 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17033 	un->un_recov_buf_busy = 1;
17034 
17035 	bp = un->un_recov_buf;
17036 	bzero(bp, sizeof (buf_t));
17037 
17038 	bp->b_forw = (struct buf *)(uintptr_t)ucmd->uscsi_cdb[0];
17039 	bp->b_back = (struct buf *)ucmd;
17040 
17041 	mutex_exit(ST_MUTEX);
17042 	rval = scsi_uscsi_handle_cmd(un->un_dev, UIO_SYSSPACE, ucmd,
17043 	    st_strategy, bp, NULL);
17044 	mutex_enter(ST_MUTEX);
17045 
17046 	ucmd->uscsi_resid = bp->b_resid;
17047 
17048 	/*
17049 	 * Free resources
17050 	 */
17051 	un->un_recov_buf_busy = 0;
17052 	cv_signal(&un->un_recov_buf_cv);
17053 
17054 	return (rval);
17055 }
17056 
17057 /*
17058  * Add data to scsi_pkt to help know what to do if the command fails.
17059  */
17060 static void
17061 st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
17062     struct scsi_pkt *pkt)
17063 {
17064 	uint64_t count;
17065 	recov_info *rinfo = (recov_info *)pkt->pkt_private;
17066 
17067 	ST_FUNC(ST_DEVINFO, st_add_recovery_info_to_pkt);
17068 
17069 	ASSERT(rinfo->privatelen == sizeof (pkt_info) ||
17070 	    rinfo->privatelen == sizeof (recov_info));
17071 
17072 	SET_BP_PKT(bp, pkt);
17073 	rinfo->cmd_bp = bp;
17074 
17075 	if (rinfo->privatelen != sizeof (recov_info)) {
17076 		return;
17077 	}
17078 
17079 	rinfo->cmd_bp = bp;
17080 
17081 	rinfo->cmd_attrib = NULL;
17082 
17083 	/*
17084 	 * lookup the command attributes and add them to the recovery info.
17085 	 */
17086 	rinfo->cmd_attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
17087 
17088 	ASSERT(rinfo->cmd_attrib);
17089 
17090 	/*
17091 	 * For commands that there is no way to figure the expected position
17092 	 * once completed, we save the position the command was started from
17093 	 * so that if they fail we can position back and try again.
17094 	 * This has already been done in st_cmd() or st_iscsi_cmd().
17095 	 */
17096 	if (rinfo->cmd_attrib->recov_pos_type == POS_STARTING) {
17097 		/* save current position as the starting position. */
17098 		COPY_POS(&rinfo->pos, &un->un_pos);
17099 		un->un_running.pmode = invalid;
17100 		return;
17101 	}
17102 
17103 	/*
17104 	 * Don't want to update the running position for recovery.
17105 	 */
17106 	if (bp == un->un_recov_buf) {
17107 		rinfo->pos.pmode = un->un_running.pmode;
17108 		return;
17109 	}
17110 	/*
17111 	 * If running position is invalid copy the current position.
17112 	 * Running being set invalid means we are not in a read, write
17113 	 * or write filemark sequence.
17114 	 * We'll copy the current position and start from there.
17115 	 */
17116 	if (un->un_running.pmode == invalid) {
17117 		COPY_POS(&un->un_running, &un->un_pos);
17118 		COPY_POS(&rinfo->pos, &un->un_running);
17119 	} else {
17120 		COPY_POS(&rinfo->pos, &un->un_running);
17121 		if (rinfo->pos.pmode == legacy) {
17122 			/*
17123 			 * Always should be more logical blocks then
17124 			 * data blocks and files marks.
17125 			 */
17126 			ASSERT((rinfo->pos.blkno >= 0) ?
17127 			    rinfo->pos.lgclblkno >=
17128 			    (rinfo->pos.blkno + rinfo->pos.fileno) : 1);
17129 		}
17130 	}
17131 
17132 	/*
17133 	 * If the command is not expected to change the drive position
17134 	 * then the running position should be the expected position.
17135 	 */
17136 	if (rinfo->cmd_attrib->chg_tape_pos == 0) {
17137 		ASSERT(rinfo->cmd_attrib->chg_tape_direction == DIR_NONE);
17138 		return;
17139 	}
17140 
17141 	if (rinfo->cmd_attrib->explicit) {
17142 		ASSERT(rinfo->pos.pmode != invalid);
17143 		ASSERT(rinfo->cmd_attrib->get_cnt);
17144 		count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17145 		/*
17146 		 * This is a user generated CDB.
17147 		 */
17148 		if (bp == un->un_sbufp) {
17149 			uint64_t lbn;
17150 
17151 			lbn = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17152 
17153 			/*
17154 			 * See if this CDB will generate a locate or change
17155 			 * partition.
17156 			 */
17157 			if ((lbn != un->un_running.lgclblkno) ||
17158 			    (pkt->pkt_cdbp[3] != un->un_running.partition)) {
17159 				rinfo->pos.partition = pkt->pkt_cdbp[3];
17160 				rinfo->pos.pmode = logical;
17161 				rinfo->pos.lgclblkno = lbn;
17162 				un->un_running.partition = pkt->pkt_cdbp[3];
17163 				un->un_running.pmode = logical;
17164 				un->un_running.lgclblkno = lbn;
17165 			}
17166 		} else {
17167 			uint64_t lbn = un->un_running.lgclblkno;
17168 
17169 			pkt->pkt_cdbp[3]  = (uchar_t)un->un_running.partition;
17170 
17171 			pkt->pkt_cdbp[4]  = (uchar_t)(lbn >> 56);
17172 			pkt->pkt_cdbp[5]  = (uchar_t)(lbn >> 48);
17173 			pkt->pkt_cdbp[6]  = (uchar_t)(lbn >> 40);
17174 			pkt->pkt_cdbp[7]  = (uchar_t)(lbn >> 32);
17175 			pkt->pkt_cdbp[8]  = (uchar_t)(lbn >> 24);
17176 			pkt->pkt_cdbp[9]  = (uchar_t)(lbn >> 16);
17177 			pkt->pkt_cdbp[10] = (uchar_t)(lbn >> 8);
17178 			pkt->pkt_cdbp[11] = (uchar_t)(lbn);
17179 		}
17180 		rinfo->pos.lgclblkno += count;
17181 		rinfo->pos.blkno += count;
17182 		un->un_running.lgclblkno += count;
17183 		return;
17184 	}
17185 
17186 	if (rinfo->cmd_attrib->chg_tape_pos) {
17187 
17188 		/* should not have got an invalid position from running. */
17189 		if (un->un_mediastate == MTIO_INSERTED) {
17190 			ASSERT(rinfo->pos.pmode != invalid);
17191 		}
17192 
17193 		/* should have either a get count or or get lba function */
17194 		ASSERT(rinfo->cmd_attrib->get_cnt != NULL ||
17195 		    rinfo->cmd_attrib->get_lba != NULL);
17196 
17197 		/* only explicit commands have both and they're handled above */
17198 		ASSERT(!(rinfo->cmd_attrib->get_cnt != NULL &&
17199 		    rinfo->cmd_attrib->get_lba != NULL));
17200 
17201 		/* if it has a get count function */
17202 		if (rinfo->cmd_attrib->get_cnt != NULL) {
17203 			count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17204 			if (count == 0) {
17205 				return;
17206 			}
17207 			/*
17208 			 * Changes position but doesn't transfer data.
17209 			 * i.e. rewind, write_file_mark and load.
17210 			 */
17211 			if (rinfo->cmd_attrib->transfers_data == TRAN_NONE) {
17212 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17213 				case DIR_NONE: /* Erase */
17214 					ASSERT(rinfo->cmd_attrib->cmd ==
17215 					    SCMD_ERASE);
17216 					break;
17217 				case DIR_FORW: /* write_file_mark */
17218 					rinfo->pos.fileno += count;
17219 					rinfo->pos.lgclblkno += count;
17220 					rinfo->pos.blkno = 0;
17221 					un->un_running.fileno += count;
17222 					un->un_running.lgclblkno += count;
17223 					un->un_running.blkno = 0;
17224 					break;
17225 				case DIR_REVC: /* rewind */
17226 					rinfo->pos.fileno = 0;
17227 					rinfo->pos.lgclblkno = 0;
17228 					rinfo->pos.blkno = 0;
17229 					rinfo->pos.eof = ST_NO_EOF;
17230 					rinfo->pos.pmode = legacy;
17231 					un->un_running.fileno = 0;
17232 					un->un_running.lgclblkno = 0;
17233 					un->un_running.blkno = 0;
17234 					un->un_running.eof = ST_NO_EOF;
17235 					if (un->un_running.pmode != legacy)
17236 						un->un_running.pmode = legacy;
17237 					break;
17238 				case DIR_EITH: /* Load unload */
17239 					ASSERT(rinfo->cmd_attrib->cmd ==
17240 					    SCMD_LOAD);
17241 					switch (count & (LD_LOAD | LD_RETEN |
17242 					    LD_RETEN | LD_HOLD)) {
17243 					case LD_UNLOAD:
17244 					case LD_RETEN:
17245 					case LD_HOLD:
17246 					case LD_LOAD | LD_HOLD:
17247 					case LD_EOT | LD_HOLD:
17248 					case LD_RETEN | LD_HOLD:
17249 						rinfo->pos.pmode = invalid;
17250 						un->un_running.pmode = invalid;
17251 						break;
17252 					case LD_EOT:
17253 					case LD_LOAD | LD_EOT:
17254 						rinfo->pos.eof = ST_EOT;
17255 						rinfo->pos.pmode = invalid;
17256 						un->un_running.eof = ST_EOT;
17257 						un->un_running.pmode = invalid;
17258 						break;
17259 					case LD_LOAD:
17260 					case LD_RETEN | LD_LOAD:
17261 						rinfo->pos.fileno = 0;
17262 						rinfo->pos.lgclblkno = 0;
17263 						rinfo->pos.blkno = 0;
17264 						rinfo->pos.eof = ST_NO_EOF;
17265 						rinfo->pos.pmode = legacy;
17266 						un->un_running.fileno = 0;
17267 						un->un_running.lgclblkno = 0;
17268 						un->un_running.blkno = 0;
17269 						un->un_running.eof = ST_NO_EOF;
17270 						break;
17271 					default:
17272 						ASSERT(0);
17273 					}
17274 					break;
17275 				default:
17276 					ASSERT(0);
17277 					break;
17278 				}
17279 			} else {
17280 				/*
17281 				 * Changes position and does transfer data.
17282 				 * i.e. read or write.
17283 				 */
17284 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17285 				case DIR_FORW:
17286 					rinfo->pos.lgclblkno += count;
17287 					rinfo->pos.blkno += count;
17288 					un->un_running.lgclblkno += count;
17289 					un->un_running.blkno += count;
17290 					break;
17291 				case DIR_REVC:
17292 					rinfo->pos.lgclblkno -= count;
17293 					rinfo->pos.blkno -= count;
17294 					un->un_running.lgclblkno -= count;
17295 					un->un_running.blkno -= count;
17296 					break;
17297 				default:
17298 					ASSERT(0);
17299 					break;
17300 				}
17301 			}
17302 		} else if (rinfo->cmd_attrib->get_lba != NULL) {
17303 			/* Have a get LBA fuction. i.e. Locate */
17304 			ASSERT(rinfo->cmd_attrib->chg_tape_direction ==
17305 			    DIR_EITH);
17306 			count = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17307 			un->un_running.lgclblkno = count;
17308 			un->un_running.blkno = 0;
17309 			un->un_running.fileno = 0;
17310 			un->un_running.pmode = logical;
17311 			rinfo->pos.lgclblkno = count;
17312 			rinfo->pos.pmode = invalid;
17313 		} else {
17314 			ASSERT(0);
17315 		}
17316 		return;
17317 	}
17318 
17319 	ST_CDB(ST_DEVINFO, "Unhanded CDB for position prediction",
17320 	    (char *)pkt->pkt_cdbp);
17321 
17322 }
17323 
17324 static int
17325 st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf)
17326 {
17327 	struct seq_mode *current;
17328 	int rval;
17329 	int i;
17330 	caddr_t this;
17331 	caddr_t that;
17332 
17333 	ST_FUNC(ST_DEVINFO, st_check_mode_for_change);
17334 
17335 	/* recovery called with mode tamper before mode selection */
17336 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
17337 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17338 		    "Mode Select not done yet");
17339 		return (0);
17340 	}
17341 
17342 	current = kmem_zalloc(sizeof (struct seq_mode), KM_SLEEP);
17343 
17344 	rval = st_gen_mode_sense(un, ubf, un->un_comp_page, current,
17345 	    sizeof (struct seq_mode));
17346 	if (rval != 0) {
17347 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17348 		    "Mode Sense for mode verification failed");
17349 		kmem_free(current, sizeof (struct seq_mode));
17350 		return (rval);
17351 	}
17352 
17353 	this = (caddr_t)current;
17354 	that = (caddr_t)un->un_mspl;
17355 
17356 	rval = bcmp(this, that, sizeof (struct seq_mode));
17357 	if (rval == 0) {
17358 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17359 		    "Found no changes in mode data");
17360 	}
17361 #ifdef STDEBUG
17362 	else {
17363 		for (i = 1; i < sizeof (struct seq_mode); i++) {
17364 			if (this[i] != that[i]) {
17365 				ST_RECOV(ST_DEVINFO, st_label, CE_CONT,
17366 				    "sense data changed at byte %d was "
17367 				    "0x%x now 0x%x", i,
17368 				    (uchar_t)that[i], (uchar_t)this[i]);
17369 			}
17370 		}
17371 	}
17372 #endif
17373 	kmem_free(current, sizeof (struct seq_mode));
17374 
17375 	return (rval);
17376 }
17377 
17378 static int
17379 st_test_path_to_device(struct scsi_tape *un)
17380 {
17381 	int rval = 0;
17382 	int limit = st_retry_count;
17383 
17384 	ST_FUNC(ST_DEVINFO, st_test_path_to_device);
17385 
17386 	/*
17387 	 * XXX Newer drives may not RESEVATION CONFLICT a TUR.
17388 	 */
17389 	do {
17390 		if (rval != 0) {
17391 			mutex_exit(ST_MUTEX);
17392 			delay(drv_usectohz(1000000));
17393 			mutex_enter(ST_MUTEX);
17394 		}
17395 		rval = st_rcmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
17396 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17397 		    "ping TUR returned 0x%x", rval);
17398 		limit--;
17399 	} while (((rval == EACCES) || (rval == EBUSY)) && limit);
17400 
17401 	if (un->un_status == KEY_NOT_READY || un->un_mediastate == MTIO_EJECTED)
17402 		rval = 0;
17403 
17404 	return (rval);
17405 }
17406 
17407 /*
17408  * Does read position using recov_buf and doesn't update un_pos.
17409  * Does what ever kind of read position you want.
17410  */
17411 static int
17412 st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
17413     read_pos_data_t *raw)
17414 {
17415 	int rval;
17416 	struct uscsi_cmd cmd;
17417 	struct scsi_arq_status status;
17418 	char cdb[CDB_GROUP1];
17419 
17420 	ST_FUNC(ST_DEVINFO, st_recovery_read_pos);
17421 	bzero(&cmd, sizeof (cmd));
17422 
17423 	cdb[0] = SCMD_READ_POSITION;
17424 	cdb[1] = type;
17425 	cdb[2] = 0;
17426 	cdb[3] = 0;
17427 	cdb[4] = 0;
17428 	cdb[5] = 0;
17429 	cdb[6] = 0;
17430 	cdb[7] = 0;
17431 	cdb[8] = (type == EXT_POS) ? 28 : 0;
17432 	cdb[9] = 0;
17433 
17434 	cmd.uscsi_flags = USCSI_READ | USCSI_RQENABLE;
17435 	cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
17436 	cmd.uscsi_cdb = cdb;
17437 	cmd.uscsi_cdblen = sizeof (cdb);
17438 	cmd.uscsi_rqlen = sizeof (status);
17439 	cmd.uscsi_rqbuf = (caddr_t)&status;
17440 	cmd.uscsi_bufaddr = (caddr_t)raw;
17441 	switch (type) {
17442 	case SHORT_POS:
17443 		cmd.uscsi_buflen = sizeof (tape_position_t);
17444 		break;
17445 	case LONG_POS:
17446 		cmd.uscsi_buflen = sizeof (tape_position_long_t);
17447 		break;
17448 	case EXT_POS:
17449 		cmd.uscsi_buflen = sizeof (tape_position_ext_t);
17450 		break;
17451 	default:
17452 		ASSERT(0);
17453 	}
17454 
17455 	rval = st_uscsi_rcmd(un, &cmd, FKIOCTL);
17456 	if (cmd.uscsi_status) {
17457 		rval = EIO;
17458 	}
17459 	return (rval);
17460 }
17461 
17462 static int
17463 st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
17464     read_pos_data_t *raw)
17465 {
17466 	int rval;
17467 	read_p_types type = un->un_read_pos_type;
17468 
17469 	ST_FUNC(ST_DEVINFO, st_recovery_get_position);
17470 
17471 	do {
17472 		rval = st_recovery_read_pos(un, type, raw);
17473 		if (rval != 0) {
17474 			switch (type) {
17475 			case SHORT_POS:
17476 				type = NO_POS;
17477 				break;
17478 
17479 			case LONG_POS:
17480 				type = EXT_POS;
17481 				break;
17482 
17483 			case EXT_POS:
17484 				type = SHORT_POS;
17485 				break;
17486 
17487 			default:
17488 				type = LONG_POS;
17489 				break;
17490 
17491 			}
17492 		} else {
17493 			if (type != un->un_read_pos_type) {
17494 				un->un_read_pos_type = type;
17495 			}
17496 			break;
17497 		}
17498 	} while (type != NO_POS);
17499 
17500 	if (rval == 0) {
17501 		rval = st_interpret_read_pos(un, read, type,
17502 		    sizeof (read_pos_data_t), (caddr_t)raw, 1);
17503 	}
17504 	return (rval);
17505 }
17506 
17507 /*
17508  * based on the command do we retry, continue or give up?
17509  * possable return values?
17510  *	zero do nothing looks fine.
17511  *	EAGAIN retry.
17512  *	EIO failed makes no sense.
17513  */
17514 static int
17515 st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
17516     cmd_attribute const * cmd_att, tapepos_t *read)
17517 {
17518 	int rval;
17519 	read_pos_data_t *readp_datap;
17520 
17521 	ST_FUNC(ST_DEVINFO, st_compare_expected_position);
17522 
17523 	ASSERT(un != NULL);
17524 	ASSERT(ei != NULL);
17525 	ASSERT(read != NULL);
17526 	ASSERT(cmd_att->chg_tape_pos);
17527 
17528 	COPY_POS(read, &ei->ei_expected_pos);
17529 
17530 	readp_datap = kmem_zalloc(sizeof (read_pos_data_t), KM_SLEEP);
17531 
17532 	rval = st_recovery_get_position(un, read, readp_datap);
17533 
17534 	kmem_free(readp_datap, sizeof (read_pos_data_t));
17535 
17536 	if (rval != 0) {
17537 		return (EIO);
17538 	}
17539 
17540 	ST_POS(ST_DEVINFO, "st_compare_expected_position", read);
17541 
17542 	if ((read->pmode == invalid) ||
17543 	    (ei->ei_expected_pos.pmode == invalid)) {
17544 		return (EIO);
17545 	}
17546 
17547 	/*
17548 	 * Command that changes tape position and have an expected position
17549 	 * if it were to chave completed sucessfully.
17550 	 */
17551 	if (cmd_att->recov_pos_type == POS_EXPECTED) {
17552 		uint32_t count;
17553 		int64_t difference;
17554 		uchar_t reposition = 0;
17555 
17556 		ASSERT(cmd_att->get_cnt);
17557 		count = cmd_att->get_cnt(ei->ei_failed_pkt.pkt_cdbp);
17558 
17559 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17560 		    "Got count from CDB and it was %d\n", count);
17561 
17562 		/*
17563 		 * At expected?
17564 		 */
17565 		if (read->lgclblkno == ei->ei_expected_pos.lgclblkno) {
17566 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17567 			    "Found drive to be at expected position\n");
17568 
17569 			/*
17570 			 * If the command should move tape and it got a busy
17571 			 * it shouldn't be in the expected position.
17572 			 */
17573 			if (ei->ei_failing_status.sts_status.sts_busy != 0) {
17574 				reposition = 1;
17575 
17576 			/*
17577 			 * If the command doesn't transfer data should be good.
17578 			 */
17579 			} else if (cmd_att->transfers_data == TRAN_NONE) {
17580 				return (0); /* Good */
17581 
17582 			/*
17583 			 * Command transfers data, should have done so.
17584 			 */
17585 			} else if (ei->ei_failed_pkt.pkt_state &
17586 			    STATE_XFERRED_DATA) {
17587 				return (0); /* Good */
17588 			} else {
17589 				reposition = 1;
17590 			}
17591 		}
17592 
17593 		if (cmd_att->chg_tape_direction == DIR_FORW) {
17594 			difference =
17595 			    ei->ei_expected_pos.lgclblkno - read->lgclblkno;
17596 
17597 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17598 			    "difference between expected and actual is %"
17599 			    PRId64"\n", difference);
17600 			if (count == difference && reposition == 0) {
17601 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17602 				    "Found failed FORW command, retrying\n");
17603 				return (EAGAIN);
17604 			}
17605 
17606 			/*
17607 			 * If rewound or somewhere between the starting position
17608 			 * and the expected position (partial read or write).
17609 			 * Locate to the starting position and try the whole
17610 			 * thing over again.
17611 			 */
17612 			if ((read->lgclblkno == 0) ||
17613 			    ((difference > 0) && (difference < count))) {
17614 				rval = st_logical_block_locate(un,
17615 				    st_uscsi_rcmd, read,
17616 				    ei->ei_expected_pos.lgclblkno - count,
17617 				    ei->ei_expected_pos.partition);
17618 				if (rval == 0) {
17619 					ST_RECOV(ST_DEVINFO, st_label,
17620 					    CE_NOTE, "reestablished FORW"
17621 					    " command retrying\n");
17622 					return (EAGAIN);
17623 				}
17624 			/*
17625 			 * This handles flushed read ahead on the drive or
17626 			 * an aborted read that presents as a busy and advanced
17627 			 * the tape position.
17628 			 */
17629 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17630 			    ((difference < 0) || (reposition == 1))) {
17631 				rval = st_logical_block_locate(un,
17632 				    st_uscsi_rcmd, read,
17633 				    ei->ei_expected_pos.lgclblkno - count,
17634 				    ei->ei_expected_pos.partition);
17635 				if (rval == 0) {
17636 					ST_RECOV(ST_DEVINFO, st_label,
17637 					    CE_NOTE, "reestablished FORW"
17638 					    " read command retrying\n");
17639 					return (EAGAIN);
17640 				}
17641 			/*
17642 			 * XXX swag seeing difference of 2 on write filemark.
17643 			 * If the space to the starting position works on a
17644 			 * write that means the previous write made it to tape.
17645 			 * If not we lost data and have to give up.
17646 			 *
17647 			 * The plot thickens. Now I am attempting to cover a
17648 			 * count of 1 and a differance of 2 on a write.
17649 			 */
17650 			} else if ((difference > count) || (reposition == 1)) {
17651 				rval = st_logical_block_locate(un,
17652 				    st_uscsi_rcmd, read,
17653 				    ei->ei_expected_pos.lgclblkno - count,
17654 				    ei->ei_expected_pos.partition);
17655 				if (rval == 0) {
17656 					ST_RECOV(ST_DEVINFO, st_label,
17657 					    CE_NOTE, "reestablished FORW"
17658 					    " write command retrying\n");
17659 					return (EAGAIN);
17660 				}
17661 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17662 				    "Seek to block %"PRId64" returned %d\n",
17663 				    ei->ei_expected_pos.lgclblkno - count,
17664 				    rval);
17665 			} else {
17666 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17667 				    "Not expected transfers_data = %d "
17668 				    "difference = %"PRId64,
17669 				    cmd_att->transfers_data, difference);
17670 			}
17671 
17672 			return (EIO);
17673 
17674 		} else if (cmd_att->chg_tape_direction == DIR_REVC) {
17675 			/* Don't think we can write backwards */
17676 			ASSERT(cmd_att->transfers_data != TRAN_WRTE);
17677 			difference =
17678 			    read->lgclblkno - ei->ei_expected_pos.lgclblkno;
17679 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17680 			    "difference between expected and actual is %"
17681 			    PRId64"\n", difference);
17682 			if (count == difference && reposition == 0) {
17683 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17684 				    "Found failed REVC command, retrying\n");
17685 				return (EAGAIN);
17686 			}
17687 			if ((read->lgclblkno == 0) ||
17688 			    ((difference > 0) && (difference < count))) {
17689 				rval = st_logical_block_locate(un,
17690 				    st_uscsi_rcmd, read,
17691 				    ei->ei_expected_pos.lgclblkno + count,
17692 				    ei->ei_expected_pos.partition);
17693 				if (rval == 0) {
17694 					ST_RECOV(ST_DEVINFO, st_label,
17695 					    CE_NOTE, "reestablished REVC"
17696 					    " command retrying\n");
17697 					return (EAGAIN);
17698 				}
17699 			/* This handles read ahead in reverse direction */
17700 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17701 			    (difference < 0) || (reposition == 1)) {
17702 				rval = st_logical_block_locate(un,
17703 				    st_uscsi_rcmd, read,
17704 				    ei->ei_expected_pos.lgclblkno - count,
17705 				    ei->ei_expected_pos.partition);
17706 				if (rval == 0) {
17707 					ST_RECOV(ST_DEVINFO, st_label,
17708 					    CE_NOTE, "reestablished REVC"
17709 					    " read command retrying\n");
17710 					return (EAGAIN);
17711 				}
17712 			} else {
17713 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17714 				    "Not expected transfers_data = %d "
17715 				    "difference = %"PRId64,
17716 				    cmd_att->transfers_data, difference);
17717 			}
17718 			return (EIO);
17719 
17720 		} else {
17721 			/*
17722 			 * Commands that change tape position either
17723 			 * direction or don't change position should not
17724 			 * get here.
17725 			 */
17726 			ASSERT(0);
17727 		}
17728 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17729 		    "Didn't find a recoverable position, Failing\n");
17730 
17731 	/*
17732 	 * Command that changes tape position and can only be recovered
17733 	 * by going back to the point of origin and retrying.
17734 	 *
17735 	 * Example SCMD_SPACE.
17736 	 */
17737 	} else if (cmd_att->recov_pos_type == POS_STARTING) {
17738 		/*
17739 		 * This type of command stores the starting position.
17740 		 * If the read position is the starting position,
17741 		 * reissue the command.
17742 		 */
17743 		if (ei->ei_expected_pos.lgclblkno == read->lgclblkno) {
17744 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17745 			    "Found Space command at starting position, "
17746 			    "Reissuing\n");
17747 			return (EAGAIN);
17748 		}
17749 		/*
17750 		 * Not in the position that the command was originally issued,
17751 		 * Attempt to locate to that position.
17752 		 */
17753 		rval = st_logical_block_locate(un, st_uscsi_rcmd, read,
17754 		    ei->ei_expected_pos.lgclblkno,
17755 		    ei->ei_expected_pos.partition);
17756 		if (rval) {
17757 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17758 			    "Found Space at an unexpected position and locate "
17759 			    "back to starting position failed\n");
17760 			return (EIO);
17761 		}
17762 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17763 		    "Found Space at an unexpected position and locate "
17764 		    "back to starting position worked, Reissuing\n");
17765 		return (EAGAIN);
17766 	}
17767 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17768 	    "Unhandled attribute/expected position", &ei->ei_expected_pos);
17769 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17770 	    "Read position above did not make sense", read);
17771 	ASSERT(0);
17772 	return (EIO);
17773 }
17774 
17775 static errstate
17776 st_recover_reissue_pkt(struct scsi_tape *un, struct scsi_pkt *oldpkt)
17777 {
17778 	buf_t *bp;
17779 	buf_t *pkt_bp;
17780 	struct scsi_pkt *newpkt;
17781 	cmd_attribute const *attrib;
17782 	recov_info *rcv = oldpkt->pkt_private;
17783 	uint_t cdblen;
17784 	int queued = 0;
17785 	int rval;
17786 	int flags = 0;
17787 	int stat_size =
17788 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
17789 
17790 	ST_FUNC(ST_DEVINFO, st_recover_reissue_pkt);
17791 
17792 	bp = rcv->cmd_bp;
17793 
17794 	if (rcv->privatelen == sizeof (recov_info)) {
17795 		attrib = rcv->cmd_attrib;
17796 	} else {
17797 		attrib = st_lookup_cmd_attribute(oldpkt->pkt_cdbp[0]);
17798 	}
17799 
17800 	/*
17801 	 * Some non-uscsi commands use the b_bcount for values that
17802 	 * have nothing to do with how much data is transfered.
17803 	 * In those cases we need to hide the buf_t from scsi_init_pkt().
17804 	 */
17805 	if ((BP_UCMD(bp)) && (bp->b_bcount)) {
17806 		pkt_bp = bp;
17807 	} else if (attrib->transfers_data == TRAN_NONE) {
17808 		pkt_bp = NULL;
17809 	} else {
17810 		pkt_bp = bp;
17811 	}
17812 
17813 	/*
17814 	 * if this is a queued command make sure it the only one in the
17815 	 * run queue.
17816 	 */
17817 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
17818 		ASSERT(un->un_runqf == un->un_runql);
17819 		ASSERT(un->un_runqf == bp);
17820 		queued = 1;
17821 	}
17822 
17823 	cdblen = scsi_cdb_size[CDB_GROUPID(oldpkt->pkt_cdbp[0])];
17824 
17825 	if (pkt_bp == un->un_rqs_bp) {
17826 		flags |= PKT_CONSISTENT;
17827 		stat_size = 1;
17828 	}
17829 
17830 	newpkt = scsi_init_pkt(ROUTE, NULL, pkt_bp, cdblen,
17831 	    stat_size, rcv->privatelen, flags, NULL_FUNC, NULL);
17832 	if (newpkt == NULL) {
17833 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17834 		    "Reissue pkt scsi_init_pkt() failure\n");
17835 		return (COMMAND_DONE_ERROR);
17836 	}
17837 
17838 	ASSERT(newpkt->pkt_resid == 0);
17839 	bp->b_flags &= ~(B_DONE);
17840 	bp->b_resid = 0;
17841 	st_bioerror(bp, 0);
17842 
17843 	bcopy(oldpkt->pkt_private, newpkt->pkt_private, rcv->privatelen);
17844 
17845 	newpkt->pkt_comp = oldpkt->pkt_comp;
17846 	newpkt->pkt_time = oldpkt->pkt_time;
17847 
17848 	bzero(newpkt->pkt_scbp, stat_size);
17849 	bcopy(oldpkt->pkt_cdbp, newpkt->pkt_cdbp, cdblen);
17850 
17851 	newpkt->pkt_state = 0;
17852 	newpkt->pkt_statistics = 0;
17853 
17854 	/*
17855 	 * oldpkt passed in was a copy of the original.
17856 	 * to distroy we need the address of the original.
17857 	 */
17858 	oldpkt = BP_PKT(bp);
17859 
17860 	if (oldpkt == un->un_rqs) {
17861 		ASSERT(bp == un->un_rqs_bp);
17862 		un->un_rqs = newpkt;
17863 	}
17864 
17865 	SET_BP_PKT(bp, newpkt);
17866 
17867 	scsi_destroy_pkt(oldpkt);
17868 
17869 	rval = st_transport(un, newpkt);
17870 	if (rval == TRAN_ACCEPT) {
17871 		return (JUST_RETURN);
17872 	}
17873 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17874 	    "Reissue pkt st_transport(0x%x) failure\n", rval);
17875 	if (rval != TRAN_BUSY) {
17876 		return (COMMAND_DONE_ERROR);
17877 	}
17878 	mutex_exit(ST_MUTEX);
17879 	rval = st_handle_start_busy(un, bp, ST_TRAN_BUSY_TIMEOUT, queued);
17880 	mutex_enter(ST_MUTEX);
17881 	if (rval) {
17882 		return (COMMAND_DONE_ERROR);
17883 	}
17884 
17885 	return (JUST_RETURN);
17886 }
17887 
17888 static int
17889 st_transport(struct scsi_tape *un, struct scsi_pkt *pkt)
17890 {
17891 	int status;
17892 
17893 	ST_FUNC(ST_DEVINFO, st_transport);
17894 
17895 	ST_CDB(ST_DEVINFO, "transport CDB", (caddr_t)pkt->pkt_cdbp);
17896 
17897 	mutex_exit(ST_MUTEX);
17898 
17899 	status = scsi_transport(pkt);
17900 
17901 	mutex_enter(ST_MUTEX);
17902 
17903 	return (status);
17904 }
17905 
17906 /*
17907  * Removed the buf_t bp from the queue referenced to by head and tail.
17908  * Returns the buf_t pointer if it is found in the queue.
17909  * Returns NULL if it is not found.
17910  */
17911 static buf_t *
17912 st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp)
17913 {
17914 	buf_t *runqbp;
17915 	buf_t *prevbp = NULL;
17916 
17917 	for (runqbp = *head; runqbp != 0; runqbp = runqbp->av_forw) {
17918 		if (runqbp == bp) {
17919 			/* found it, is it at the head? */
17920 			if (runqbp == *head) {
17921 				*head = bp->av_forw;
17922 			} else {
17923 				prevbp->av_forw = bp->av_forw;
17924 			}
17925 			if (*tail == bp) {
17926 				*tail = prevbp;
17927 			}
17928 			bp->av_forw = NULL;
17929 			return (bp); /* found and removed */
17930 		}
17931 		prevbp = runqbp;
17932 	}
17933 	return (NULL);
17934 }
17935 
17936 /*
17937  * Adds a buf_t to the queue pointed to by head and tail.
17938  * Adds it either to the head end or the tail end based on which
17939  * the passed variable end (head or tail) points at.
17940  */
17941 static void
17942 st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp)
17943 {
17944 
17945 	bp->av_forw = NULL;
17946 	if (*head) {
17947 		/* Queue is not empty */
17948 		if (end == *head) {
17949 			/* Add at front of queue */
17950 			bp->av_forw = *head;
17951 			*head = bp;
17952 		} else if (end == *tail) {
17953 			/* Add at end of queue */
17954 			(*tail)->av_forw = bp;
17955 			*tail = bp;
17956 		} else {
17957 			ASSERT(0);
17958 		}
17959 	} else {
17960 		/* Queue is empty */
17961 		*head = bp;
17962 		*tail = bp;
17963 	}
17964 }
17965 
17966 
17967 static uint64_t
17968 st_get_cdb_g0_rw_count(uchar_t *cdb)
17969 {
17970 	uint64_t count;
17971 
17972 	if ((cdb[1]) & 1) {
17973 		/* fixed block mode, the count is the number of blocks */
17974 		count =
17975 		    cdb[2] << 16 |
17976 		    cdb[3] << 8 |
17977 		    cdb[4];
17978 	} else {
17979 		/* variable block mode, the count is the block size */
17980 		count = 1;
17981 	}
17982 	return (count);
17983 }
17984 
17985 static uint64_t
17986 st_get_cdb_g0_sign_count(uchar_t *cdb)
17987 {
17988 	uint64_t count;
17989 
17990 	count =
17991 	    cdb[2] << 16 |
17992 	    cdb[3] << 8 |
17993 	    cdb[4];
17994 	/*
17995 	 * If the sign bit of the 3 byte value is set, extended it.
17996 	 */
17997 	if (count & 0x800000) {
17998 		count |= 0xffffffffff000000;
17999 	}
18000 	return (count);
18001 }
18002 
18003 static uint64_t
18004 st_get_cdb_g0_count(uchar_t *cdb)
18005 {
18006 	uint64_t count;
18007 
18008 	count =
18009 	    cdb[2] << 16 |
18010 	    cdb[3] << 8 |
18011 	    cdb[4];
18012 	return (count);
18013 }
18014 
18015 static uint64_t
18016 st_get_cdb_g5_rw_cnt(uchar_t *cdb)
18017 {
18018 	uint64_t count;
18019 
18020 	if ((cdb[1]) & 1) {
18021 		/* fixed block mode */
18022 		count =
18023 		    cdb[12] << 16 |
18024 		    cdb[13] << 8 |
18025 		    cdb[14];
18026 	} else {
18027 		/* variable block mode */
18028 		count = 1;
18029 	}
18030 	return (count);
18031 }
18032 
18033 static uint64_t
18034 st_get_no_count(uchar_t *cdb)
18035 {
18036 	ASSERT(cdb[0] == SCMD_REWIND);
18037 	return ((uint64_t)cdb[0]);
18038 }
18039 
18040 static uint64_t
18041 st_get_load_options(uchar_t *cdb)
18042 {
18043 	return ((uint64_t)(cdb[4] | (LD_HOLD << 1)));
18044 }
18045 
18046 static uint64_t
18047 st_get_erase_options(uchar_t *cdb)
18048 {
18049 	return (cdb[1] | (cdb[0] << 8));
18050 }
18051 
18052 static uint64_t
18053 st_get_cdb_g1_lba(uchar_t *cdb)
18054 {
18055 	uint64_t lba;
18056 
18057 	lba =
18058 	    cdb[3] << 24 |
18059 	    cdb[4] << 16 |
18060 	    cdb[5] << 8 |
18061 	    cdb[6];
18062 	return (lba);
18063 }
18064 
18065 static uint64_t
18066 st_get_cdb_g5_count(uchar_t *cdb)
18067 {
18068 	uint64_t count =
18069 	    cdb[12] << 16 |
18070 	    cdb[13] << 8 |
18071 	    cdb[14];
18072 
18073 	return (count);
18074 }
18075 
18076 static uint64_t
18077 st_get_cdb_g4g5_cnt(uchar_t *cdb)
18078 {
18079 	uint64_t lba;
18080 
18081 	lba =
18082 	    (uint64_t)cdb[4] << 56 |
18083 	    (uint64_t)cdb[5] << 48 |
18084 	    (uint64_t)cdb[6] << 40 |
18085 	    (uint64_t)cdb[7] << 32 |
18086 	    (uint64_t)cdb[8] << 24 |
18087 	    (uint64_t)cdb[9] << 16 |
18088 	    (uint64_t)cdb[10] << 8 |
18089 	    (uint64_t)cdb[11];
18090 	return (lba);
18091 }
18092 
18093 static const cmd_attribute cmd_attributes[] = {
18094 	{ SCMD_READ,
18095 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_READ, POS_EXPECTED,
18096 	    0, 0, 0, st_get_cdb_g0_rw_count },
18097 	{ SCMD_WRITE,
18098 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18099 	    0, 0, 0, st_get_cdb_g0_rw_count },
18100 	{ SCMD_TEST_UNIT_READY,
18101 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18102 	    0, 0, 0 },
18103 	{ SCMD_REWIND,
18104 	    1, 1, 1, 0, 0, DIR_REVC, TRAN_NONE, POS_EXPECTED,
18105 	    0, 0, 0, st_get_no_count },
18106 	{ SCMD_REQUEST_SENSE,
18107 	    0, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18108 	    0, 0, 0 },
18109 	{ SCMD_READ_BLKLIM,
18110 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18111 	    0, 0, 0 },
18112 	{ SCMD_READ_G4,
18113 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_READ, POS_EXPECTED,
18114 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18115 	{ SCMD_WRITE_G4,
18116 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18117 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18118 	{ SCMD_READ_REVERSE,
18119 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18120 	    0, 0, 0, st_get_cdb_g0_rw_count },
18121 	{ SCMD_READ_REVERSE_G4,
18122 	    1, 0, 1, 1, 1, DIR_REVC, TRAN_READ, POS_EXPECTED,
18123 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18124 	{ SCMD_WRITE_FILE_MARK,
18125 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18126 	    0, 0, 0, st_get_cdb_g0_count },
18127 	{ SCMD_WRITE_FILE_MARK_G4,
18128 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18129 	    0, 0, 0, st_get_cdb_g5_count, st_get_cdb_g4g5_cnt },
18130 	{ SCMD_SPACE,
18131 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18132 	    0, 0, 0, st_get_cdb_g0_sign_count },
18133 	{ SCMD_SPACE_G4,
18134 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18135 	    0, 0, 0, st_get_cdb_g4g5_cnt },
18136 	{ SCMD_INQUIRY,
18137 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18138 	    0, 0, 0 },
18139 	{ SCMD_VERIFY_G0,
18140 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18141 	    0, 0, 0, st_get_cdb_g0_rw_count },
18142 	{ SCMD_VERIFY_G4,
18143 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18144 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18145 	{ SCMD_RECOVER_BUF,
18146 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18147 	    0, 0, 0 },
18148 	{ SCMD_MODE_SELECT,
18149 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18150 	    0, 0, 0 },
18151 	{ SCMD_RESERVE,
18152 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18153 	    0, 0, 0 },
18154 	{ SCMD_RELEASE,
18155 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18156 	    0, 0, 0 },
18157 	{ SCMD_ERASE,
18158 	    1, 0, 1, 1, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18159 	    0, 0, 0, st_get_erase_options },
18160 	{ SCMD_MODE_SENSE,
18161 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18162 	    0, 0, 0 },
18163 	{ SCMD_LOAD,
18164 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18165 	    0, 0, 0, st_get_load_options },
18166 	{ SCMD_GDIAG,
18167 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18168 	    1, 0, 0 },
18169 	{ SCMD_SDIAG,
18170 	    1, 0, 1, 1, 0, DIR_EITH, TRAN_WRTE, POS_EXPECTED,
18171 	    1, 0, 0 },
18172 	{ SCMD_DOORLOCK,
18173 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18174 	    0, 4, 3 },
18175 	{ SCMD_LOCATE,
18176 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18177 	    0, 0, 0, NULL, st_get_cdb_g1_lba },
18178 	{ SCMD_READ_POSITION,
18179 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18180 	    0, 0, 0 },
18181 	{ SCMD_WRITE_BUFFER,
18182 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18183 	    1, 0, 0 },
18184 	{ SCMD_READ_BUFFER,
18185 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18186 	    1, 0, 0 },
18187 	{ SCMD_REPORT_DENSITIES,
18188 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18189 	    0, 0, 0 },
18190 	{ SCMD_LOG_SELECT_G1,
18191 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18192 	    0, 0, 0 },
18193 	{ SCMD_LOG_SENSE_G1,
18194 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18195 	    0, 0, 0 },
18196 	{ SCMD_PRIN,
18197 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18198 	    0, 0, 0 },
18199 	{ SCMD_PROUT,
18200 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18201 	    0, 0, 0 },
18202 	{ SCMD_READ_ATTRIBUTE,
18203 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18204 	    0, 0, 0 },
18205 	{ SCMD_WRITE_ATTRIBUTE,
18206 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18207 	    0, 0, 0 },
18208 	{ SCMD_LOCATE_G4,
18209 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18210 	    0, 0, 0, NULL, st_get_cdb_g4g5_cnt },
18211 	{ SCMD_REPORT_LUNS,
18212 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18213 	    0, 0, 0 },
18214 	{ SCMD_SVC_ACTION_IN_G5,
18215 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18216 	    0, 0, 0 },
18217 	{ SCMD_MAINTENANCE_IN,
18218 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18219 	    0, 0, 0 },
18220 	{ SCMD_MAINTENANCE_OUT,
18221 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18222 	    0, 0, 0 },
18223 	{ 0xff, /* Default attribute for unsupported commands */
18224 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_STARTING,
18225 	    1, 0, 0, NULL, NULL }
18226 };
18227 
18228 static const cmd_attribute *
18229 st_lookup_cmd_attribute(unsigned char cmd)
18230 {
18231 	int i;
18232 	cmd_attribute const *attribute;
18233 
18234 	for (i = 0; i < ST_NUM_MEMBERS(cmd_attributes); i++) {
18235 		attribute = &cmd_attributes[i];
18236 		if (attribute->cmd == cmd) {
18237 			return (attribute);
18238 		}
18239 	}
18240 	ASSERT(attribute);
18241 	return (attribute);
18242 }
18243 
18244 static int
18245 st_reset(struct scsi_tape *un, int reset_type)
18246 {
18247 	int rval;
18248 
18249 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
18250 
18251 	ST_FUNC(ST_DEVINFO, st_reset);
18252 	un->un_rsvd_status |= ST_INITIATED_RESET;
18253 	mutex_exit(ST_MUTEX);
18254 	do {
18255 		rval = scsi_reset(&un->un_sd->sd_address, reset_type);
18256 		if (rval == 0) {
18257 			switch (reset_type) {
18258 			case RESET_LUN:
18259 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18260 				    "LUN reset failed trying target reset");
18261 				reset_type = RESET_TARGET;
18262 				break;
18263 			case RESET_TARGET:
18264 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18265 				    "target reset failed trying bus reset");
18266 				reset_type = RESET_BUS;
18267 				break;
18268 			case RESET_BUS:
18269 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18270 				    "bus reset failed trying all reset");
18271 				reset_type = RESET_ALL;
18272 			default:
18273 				mutex_enter(ST_MUTEX);
18274 				return (rval);
18275 			}
18276 		}
18277 	} while (rval == 0);
18278 	mutex_enter(ST_MUTEX);
18279 	return (rval);
18280 }
18281 
18282 
18283 static void
18284 st_reset_notification(caddr_t arg)
18285 {
18286 	struct scsi_tape *un = (struct scsi_tape *)arg;
18287 
18288 	ST_FUNC(ST_DEVINFO, st_reset_notification);
18289 	mutex_enter(ST_MUTEX);
18290 
18291 	un->un_unit_attention_flags |= 2;
18292 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
18293 	    ST_RESERVE) {
18294 		un->un_rsvd_status |= ST_LOST_RESERVE;
18295 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18296 		    "Lost Reservation notification");
18297 	} else {
18298 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18299 		    "reset notification");
18300 	}
18301 
18302 	if ((un->un_restore_pos == 0) &&
18303 	    (un->un_state == ST_STATE_CLOSED) ||
18304 	    (un->un_state == ST_STATE_OPEN_PENDING_IO) ||
18305 	    (un->un_state == ST_STATE_CLOSING)) {
18306 		un->un_restore_pos = 1;
18307 	}
18308 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
18309 	    "reset and state was %d\n", un->un_state);
18310 	mutex_exit(ST_MUTEX);
18311 }
18312