xref: /titanic_44/usr/src/uts/common/io/scsi/targets/st.c (revision 9c9af2590af49bb395bc8d2eace0f2d4ea16d165)
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 /*
28  * SCSI	 SCSA-compliant and not-so-DDI-compliant Tape Driver
29  */
30 
31 #if defined(lint) && !defined(DEBUG)
32 #define	DEBUG	1
33 #endif
34 
35 #include <sys/modctl.h>
36 #include <sys/scsi/scsi.h>
37 #include <sys/mtio.h>
38 #include <sys/scsi/targets/stdef.h>
39 #include <sys/file.h>
40 #include <sys/kstat.h>
41 #include <sys/ddidmareq.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/byteorder.h>
45 
46 #define	IOSP	KSTAT_IO_PTR(un->un_stats)
47 /*
48  * stats maintained only for reads/writes as commands
49  * like rewind etc skew the wait/busy times
50  */
51 #define	IS_RW(bp) 	((bp)->b_bcount > 0)
52 #define	ST_DO_KSTATS(bp, kstat_function) \
53 	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
54 		kstat_function(IOSP); \
55 	}
56 
57 #define	ST_DO_ERRSTATS(un, x)  \
58 	if (un->un_errstats) { \
59 		struct st_errstats *stp; \
60 		stp = (struct st_errstats *)un->un_errstats->ks_data; \
61 		stp->x.value.ul++; \
62 	}
63 
64 #define	FILL_SCSI1_LUN(devp, pkt) 					\
65 	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
66 		int _lun;						\
67 		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
68 		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
69 		if (_lun > 0) {						\
70 			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
71 			    _lun;					\
72 		}							\
73 	}
74 
75 /*
76  * get an available contig mem header, cp.
77  * when big_enough is true, we will return NULL, if no big enough
78  * contig mem is found.
79  * when big_enough is false, we will try to find cp containing big
80  * enough contig mem. if not found, we will ruturn the last cp available.
81  *
82  * used by st_get_contig_mem()
83  */
84 #define	ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough) {		\
85 	struct contig_mem *tmp_cp = NULL;				\
86 	for ((cp) = (un)->un_contig_mem;				\
87 	    (cp) != NULL;						\
88 	    tmp_cp = (cp), (cp) = (cp)->cm_next) { 			\
89 		if (((cp)->cm_len >= (len)) || 				\
90 		    (!(big_enough) && ((cp)->cm_next == NULL))) { 	\
91 			if (tmp_cp == NULL) { 				\
92 				(un)->un_contig_mem = (cp)->cm_next; 	\
93 			} else { 					\
94 				tmp_cp->cm_next = (cp)->cm_next; 	\
95 			} 						\
96 			(cp)->cm_next = NULL; 				\
97 			(un)->un_contig_mem_available_num--; 		\
98 			break; 						\
99 		} 							\
100 	} 								\
101 }
102 
103 #define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
104 #define	COPY_POS(dest, source) bcopy(source, dest, sizeof (tapepos_t))
105 #define	ISALNUM(byte) \
106 	(((byte) >= 'a' && (byte) <= 'z') || \
107 	((byte) >= 'A' && (byte) <= 'Z') || \
108 	((byte) >= '0' && (byte) <= '9'))
109 
110 #define	ONE_K	1024
111 
112 #define	MAX_SPACE_CNT(cnt) if (cnt >= 0) { \
113 		if (cnt > MIN(SP_CNT_MASK, INT32_MAX)) \
114 			return (EINVAL); \
115 	} else { \
116 		if (-(cnt) > MIN(SP_CNT_MASK, INT32_MAX)) \
117 			return (EINVAL); \
118 	} \
119 
120 /*
121  * Global External Data Definitions
122  */
123 extern struct scsi_key_strings scsi_cmds[];
124 extern uchar_t	scsi_cdb_size[];
125 
126 /*
127  * Local Static Data
128  */
129 static void *st_state;
130 static char *const st_label = "st";
131 static volatile int st_recov_sz = sizeof (recov_info);
132 static const char mp_misconf[] = {
133 	"St Tape is misconfigured, MPxIO enabled and "
134 	"tape-command-recovery-disable set in st.conf\n"
135 };
136 
137 #ifdef	__x86
138 /*
139  * We need to use below DMA attr to alloc physically contiguous
140  * memory to do I/O in big block size
141  */
142 static ddi_dma_attr_t st_contig_mem_dma_attr = {
143 	DMA_ATTR_V0,    /* version number */
144 	0x0,		/* lowest usable address */
145 	0xFFFFFFFFull,  /* high DMA address range */
146 	0xFFFFFFFFull,  /* DMA counter register */
147 	1,		/* DMA address alignment */
148 	1,		/* DMA burstsizes */
149 	1,		/* min effective DMA size */
150 	0xFFFFFFFFull,  /* max DMA xfer size */
151 	0xFFFFFFFFull,  /* segment boundary */
152 	1,		/* s/g list length */
153 	1,		/* granularity of device */
154 	0		/* DMA transfer flags */
155 };
156 
157 static ddi_device_acc_attr_t st_acc_attr = {
158 	DDI_DEVICE_ATTR_V0,
159 	DDI_NEVERSWAP_ACC,
160 	DDI_STRICTORDER_ACC
161 };
162 
163 /* set limitation for the number of contig_mem */
164 static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
165 #endif
166 
167 /*
168  * Tunable parameters
169  *
170  * DISCLAIMER
171  * ----------
172  * These parameters are intended for use only in system testing; if you use
173  * them in production systems, you do so at your own risk. Altering any
174  * variable not listed below may cause unpredictable system behavior.
175  *
176  * st_check_media_time
177  *
178  *   Three second state check
179  *
180  * st_allow_large_xfer
181  *
182  *   Gated with ST_NO_RECSIZE_LIMIT
183  *
184  *   0 - Transfers larger than 64KB will not be allowed
185  *       regardless of the setting of ST_NO_RECSIZE_LIMIT
186  *   1 - Transfers larger than 64KB will be allowed
187  *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
188  *
189  * st_report_soft_errors_on_close
190  *
191  *  Gated with ST_SOFT_ERROR_REPORTING
192  *
193  *  0 - Errors will not be reported on close regardless
194  *      of the setting of ST_SOFT_ERROR_REPORTING
195  *
196  *  1 - Errors will be reported on close if
197  *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
198  */
199 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
200 static int st_retry_count	= ST_RETRY_COUNT;
201 
202 static int st_io_time		= ST_IO_TIME;
203 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
204 
205 static int st_space_time	= ST_SPACE_TIME;
206 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
207 
208 static int st_error_level	= SCSI_ERR_RETRYABLE;
209 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
210 
211 static int st_max_throttle	= ST_MAX_THROTTLE;
212 
213 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
214 
215 static int st_allow_large_xfer = 1;
216 static int st_report_soft_errors_on_close = 1;
217 
218 /*
219  * End of tunable parameters list
220  */
221 
222 
223 
224 /*
225  * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
226  *
227  * Asynchronous I/O's main offering is that it is a non-blocking way to do
228  * reads and writes.  The driver will queue up all the requests it gets and
229  * have them ready to transport to the HBA.  Unfortunately, we cannot always
230  * just ship the I/O requests to the HBA, as there errors and exceptions
231  * that may happen when we don't want the HBA to continue.  Therein comes
232  * the flush-on-errors capability.  If the HBA supports it, then st will
233  * send in st_max_throttle I/O requests at the same time.
234  *
235  * Persistent errors : This was also reasonably simple.  In the interrupt
236  * routines, if there was an error or exception (FM, LEOT, media error,
237  * transport error), the persistent error bits are set and shuts everything
238  * down, but setting the throttle to zero.  If we hit and exception in the
239  * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
240  * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
241  * the appropriate error, and this will preserve order. Of course, depending
242  * on the exception we have to show a zero read or write before we show
243  * errors back to the application.
244  */
245 
246 extern const int st_ndrivetypes;	/* defined in st_conf.c */
247 extern const struct st_drivetype st_drivetypes[];
248 extern const char st_conf_version[];
249 
250 #ifdef STDEBUG
251 static int st_soft_error_report_debug = 0;
252 volatile int st_debug = 0;
253 static volatile dev_info_t *st_lastdev;
254 static kmutex_t st_debug_mutex;
255 #endif
256 
257 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
258 
259 static const struct vid_drivetype {
260 	char	*vid;
261 	char	type;
262 } st_vid_dt[] = {
263 	{"LTO-CVE ",	MT_LTO},
264 	{"QUANTUM ",    MT_ISDLT},
265 	{"SONY    ",    MT_ISAIT},
266 	{"STK     ",	MT_ISSTK9840}
267 };
268 
269 static const struct driver_minor_data {
270 	char	*name;
271 	int	minor;
272 } st_minor_data[] = {
273 	/*
274 	 * The top 4 entries are for the default densities,
275 	 * don't alter their position.
276 	 */
277 	{"",	0},
278 	{"n",	MT_NOREWIND},
279 	{"b",	MT_BSD},
280 	{"bn",	MT_NOREWIND | MT_BSD},
281 	{"l",	MT_DENSITY1},
282 	{"m",	MT_DENSITY2},
283 	{"h",	MT_DENSITY3},
284 	{"c",	MT_DENSITY4},
285 	{"u",	MT_DENSITY4},
286 	{"ln",	MT_DENSITY1 | MT_NOREWIND},
287 	{"mn",	MT_DENSITY2 | MT_NOREWIND},
288 	{"hn",	MT_DENSITY3 | MT_NOREWIND},
289 	{"cn",	MT_DENSITY4 | MT_NOREWIND},
290 	{"un",	MT_DENSITY4 | MT_NOREWIND},
291 	{"lb",	MT_DENSITY1 | MT_BSD},
292 	{"mb",	MT_DENSITY2 | MT_BSD},
293 	{"hb",	MT_DENSITY3 | MT_BSD},
294 	{"cb",	MT_DENSITY4 | MT_BSD},
295 	{"ub",	MT_DENSITY4 | MT_BSD},
296 	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
297 	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
298 	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
299 	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
300 	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
301 };
302 
303 /* strings used in many debug and warning messages */
304 static const char wr_str[]  = "write";
305 static const char rd_str[]  = "read";
306 static const char wrg_str[] = "writing";
307 static const char rdg_str[] = "reading";
308 static const char *space_strs[] = {
309 	"records",
310 	"filemarks",
311 	"sequential filemarks",
312 	"eod",
313 	"setmarks",
314 	"sequential setmarks",
315 	"Reserved",
316 	"Reserved"
317 };
318 static const char *load_strs[] = {
319 	"unload",		/* LD_UNLOAD		0 */
320 	"load",			/* LD_LOAD		1 */
321 	"retension",		/* LD_RETEN		2 */
322 	"load reten",		/* LD_LOAD | LD_RETEN	3 */
323 	"eod",			/* LD_EOT		4 */
324 	"load EOD",		/* LD_LOAD | LD_EOT	5 */
325 	"reten EOD",		/* LD_RETEN | LD_EOT	6 */
326 	"load reten EOD"	/* LD_LOAD|LD_RETEN|LD_EOT 7 */
327 	"hold",			/* LD_HOLD		8 */
328 	"load and hold"		/* LD_LOAD | LD_HOLD	9 */
329 };
330 
331 static const char *errstatenames[] = {
332 	"COMMAND_DONE",
333 	"COMMAND_DONE_ERROR",
334 	"COMMAND_DONE_ERROR_RECOVERED",
335 	"QUE_COMMAND",
336 	"QUE_BUSY_COMMAND",
337 	"QUE_SENSE",
338 	"JUST_RETURN",
339 	"COMMAND_DONE_EACCES",
340 	"QUE_LAST_COMMAND",
341 	"COMMAND_TIMEOUT",
342 	"PATH_FAILED",
343 	"DEVICE_RESET",
344 	"DEVICE_TAMPER",
345 	"ATTEMPT_RETRY"
346 };
347 
348 const char *bogusID = "Unknown Media ID";
349 
350 /* default density offsets in the table above */
351 #define	DEF_BLANK	0
352 #define	DEF_NOREWIND	1
353 #define	DEF_BSD		2
354 #define	DEF_BSD_NR	3
355 
356 /* Sense Key, ASC/ASCQ for which tape ejection is needed */
357 
358 static struct tape_failure_code {
359 	uchar_t key;
360 	uchar_t add_code;
361 	uchar_t qual_code;
362 } st_tape_failure_code[] = {
363 	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
364 	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
365 	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
366 	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
367 	{ KEY_NOT_READY, 0x53, 0x00},
368 	{ 0xff}
369 };
370 
371 /*  clean bit position and mask */
372 
373 static struct cln_bit_position {
374 	ushort_t cln_bit_byte;
375 	uchar_t cln_bit_mask;
376 } st_cln_bit_position[] = {
377 	{ 21, 0x08},
378 	{ 70, 0xc0},
379 	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
380 };
381 
382 /*
383  * architecture dependent allocation restrictions. For x86, we'll set
384  * dma_attr_addr_hi to st_max_phys_addr and dma_attr_sgllen to
385  * st_sgl_size during _init().
386  */
387 #if defined(__sparc)
388 static ddi_dma_attr_t st_alloc_attr = {
389 	DMA_ATTR_V0,	/* version number */
390 	0x0,		/* lowest usable address */
391 	0xFFFFFFFFull,	/* high DMA address range */
392 	0xFFFFFFFFull,	/* DMA counter register */
393 	1,		/* DMA address alignment */
394 	1,		/* DMA burstsizes */
395 	1,		/* min effective DMA size */
396 	0xFFFFFFFFull,	/* max DMA xfer size */
397 	0xFFFFFFFFull,	/* segment boundary */
398 	1,		/* s/g list length */
399 	512,		/* granularity of device */
400 	0		/* DMA transfer flags */
401 };
402 #elif defined(__x86)
403 static ddi_dma_attr_t st_alloc_attr = {
404 	DMA_ATTR_V0,	/* version number */
405 	0x0,		/* lowest usable address */
406 	0x0,		/* high DMA address range [set in _init()] */
407 	0xFFFFull,	/* DMA counter register */
408 	512,		/* DMA address alignment */
409 	1,		/* DMA burstsizes */
410 	1,		/* min effective DMA size */
411 	0xFFFFFFFFull,	/* max DMA xfer size */
412 	0xFFFFFFFFull,  /* segment boundary */
413 	0,		/* s/g list length */
414 	512,		/* granularity of device [set in _init()] */
415 	0		/* DMA transfer flags */
416 };
417 uint64_t st_max_phys_addr = 0xFFFFFFFFull;
418 int st_sgl_size = 0xF;
419 
420 #endif
421 
422 /*
423  * Configuration Data:
424  *
425  * Device driver ops vector
426  */
427 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
428 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
429 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
430 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
431 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
432 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
433 static int st_strategy(struct buf *bp);
434 static int st_queued_strategy(buf_t *bp);
435 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
436 	cred_t *cred_p, int *rval_p);
437 extern int nulldev(), nodev();
438 
439 static struct cb_ops st_cb_ops = {
440 	st_open,		/* open */
441 	st_close,		/* close */
442 	st_queued_strategy,	/* strategy Not Block device but async checks */
443 	nodev,			/* print */
444 	nodev,			/* dump */
445 	st_read,		/* read */
446 	st_write,		/* write */
447 	st_ioctl,		/* ioctl */
448 	nodev,			/* devmap */
449 	nodev,			/* mmap */
450 	nodev,			/* segmap */
451 	nochpoll,		/* poll */
452 	ddi_prop_op,		/* cb_prop_op */
453 	0,			/* streamtab  */
454 	D_64BIT | D_MP | D_NEW | D_HOTPLUG |
455 	D_OPEN_RETURNS_EINTR,	/* cb_flag */
456 	CB_REV,			/* cb_rev */
457 	st_aread, 		/* async I/O read entry point */
458 	st_awrite		/* async I/O write entry point */
459 
460 };
461 
462 static int st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
463 		void **result);
464 static int st_probe(dev_info_t *dev);
465 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
466 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
467 
468 static struct dev_ops st_ops = {
469 	DEVO_REV,		/* devo_rev, */
470 	0,			/* refcnt  */
471 	st_info,		/* info */
472 	nulldev,		/* identify */
473 	st_probe,		/* probe */
474 	st_attach,		/* attach */
475 	st_detach,		/* detach */
476 	nodev,			/* reset */
477 	&st_cb_ops,		/* driver operations */
478 	(struct bus_ops *)0,	/* bus operations */
479 	nulldev,		/* power */
480 	ddi_quiesce_not_needed,	/* devo_quiesce */
481 };
482 
483 /*
484  * Local Function Declarations
485  */
486 static char *st_print_scsi_cmd(char cmd);
487 static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
488     char *title, char *cdb);
489 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
490     char *title, char *data, int len);
491 static int st_doattach(struct scsi_device *devp, int (*canwait)());
492 static void st_known_tape_type(struct scsi_tape *un);
493 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
494     struct st_drivetype *);
495 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
496     struct st_drivetype *);
497 static int st_get_conf_from_tape_drive(struct scsi_tape *, char *,
498     struct st_drivetype *);
499 static int st_get_densities_from_tape_drive(struct scsi_tape *,
500     struct st_drivetype *);
501 static int st_get_timeout_values_from_tape_drive(struct scsi_tape *,
502     struct st_drivetype *);
503 static int st_get_timeouts_value(struct scsi_tape *, uchar_t, ushort_t *,
504     ushort_t);
505 static int st_get_default_conf(struct scsi_tape *, char *,
506     struct st_drivetype *);
507 static int st_rw(dev_t dev, struct uio *uio, int flag);
508 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
509 static int st_find_eod(struct scsi_tape *un);
510 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
511 static int st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *, int flag);
512 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
513 static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
514 static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
515 static void st_start(struct scsi_tape *un);
516 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
517     clock_t timeout_interval, int queued);
518 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
519     clock_t timeout_interval);
520 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
521 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
522 static void st_init(struct scsi_tape *un);
523 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
524     int (*func)(caddr_t));
525 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
526     struct buf *bp, int (*func)(caddr_t));
527 static void st_intr(struct scsi_pkt *pkt);
528 static void st_set_state(struct scsi_tape *un, buf_t *bp);
529 static void st_test_append(struct buf *bp);
530 static int st_runout(caddr_t);
531 static int st_cmd(struct scsi_tape *un, int com, int64_t count, int wait);
532 static int st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com,
533     int64_t count);
534 static int st_set_compression(struct scsi_tape *un);
535 static int st_write_fm(dev_t dev, int wfm);
536 static int st_determine_generic(struct scsi_tape *un);
537 static int st_determine_density(struct scsi_tape *un, int rw);
538 static int st_get_density(struct scsi_tape *un);
539 static int st_set_density(struct scsi_tape *un);
540 static int st_loadtape(struct scsi_tape *un);
541 static int st_modesense(struct scsi_tape *un);
542 static int st_modeselect(struct scsi_tape *un);
543 static errstate st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
544 static int st_wrongtapetype(struct scsi_tape *un);
545 static errstate st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
546 static errstate st_handle_sense(struct scsi_tape *un, struct buf *bp,
547     tapepos_t *);
548 static errstate st_handle_autosense(struct scsi_tape *un, struct buf *bp,
549     tapepos_t *);
550 static int st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag);
551 static void st_update_error_stack(struct scsi_tape *un, struct scsi_pkt *pkt,
552     struct scsi_arq_status *cmd);
553 static void st_empty_error_stack(struct scsi_tape *un);
554 static errstate st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
555     struct scsi_arq_status *, tapepos_t *);
556 static int st_report_soft_errors(dev_t dev, int flag);
557 static void st_delayed_cv_broadcast(void *arg);
558 static int st_check_media(dev_t dev, enum mtio_state state);
559 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
560 static void st_intr_restart(void *arg);
561 static void st_start_restart(void *arg);
562 static int st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
563     struct seq_mode *page_data, int page_size);
564 static int st_change_block_size(struct scsi_tape *un, uint32_t nblksz);
565 static int st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
566     struct seq_mode *page_data, int page_size);
567 static int st_read_block_limits(struct scsi_tape *un,
568     struct read_blklim *read_blk);
569 static int st_report_density_support(struct scsi_tape *un,
570     uchar_t *density_data, size_t buflen);
571 static int st_report_supported_operation(struct scsi_tape *un,
572     uchar_t *oper_data, uchar_t option_code, ushort_t service_action);
573 static int st_tape_init(struct scsi_tape *un);
574 static void st_flush(struct scsi_tape *un);
575 static void st_set_pe_errno(struct scsi_tape *un);
576 static void st_hba_unflush(struct scsi_tape *un);
577 static void st_turn_pe_on(struct scsi_tape *un);
578 static void st_turn_pe_off(struct scsi_tape *un);
579 static void st_set_pe_flag(struct scsi_tape *un);
580 static void st_clear_pe(struct scsi_tape *un);
581 static void st_wait_for_io(struct scsi_tape *un);
582 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
583 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
584 static int st_reserve_release(struct scsi_tape *un, int command, ubufunc_t ubf);
585 static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb);
586 static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
587     int count);
588 static int st_take_ownership(struct scsi_tape *un, ubufunc_t ubf);
589 static int st_check_asc_ascq(struct scsi_tape *un);
590 static int st_check_clean_bit(struct scsi_tape *un);
591 static int st_check_alert_flags(struct scsi_tape *un);
592 static int st_check_sequential_clean_bit(struct scsi_tape *un);
593 static int st_check_sense_clean_bit(struct scsi_tape *un);
594 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
595 static void st_calculate_timeouts(struct scsi_tape *un);
596 static writablity st_is_drive_worm(struct scsi_tape *un);
597 static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
598     void *buf, size_t size, ubufunc_t bufunc);
599 static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
600     caddr_t dest, uchar_t page);
601 static int st_update_block_pos(struct scsi_tape *un, bufunc_t bf,
602     int post_space);
603 static int st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
604     read_p_types type, size_t data_sz, const caddr_t responce, int post_space);
605 static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
606 static int st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf,
607     tapepos_t *pos, uint64_t lblk, uchar_t partition);
608 static int st_mtfsf_ioctl(struct scsi_tape *un, int64_t files);
609 static int st_mtfsr_ioctl(struct scsi_tape *un, int64_t count);
610 static int st_mtbsf_ioctl(struct scsi_tape *un, int64_t files);
611 static int st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count);
612 static int st_mtbsr_ioctl(struct scsi_tape *un, int64_t num);
613 static int st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt);
614 static int st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt);
615 static int st_backward_space_files(struct scsi_tape *un, int64_t count,
616     int infront);
617 static int st_forward_space_files(struct scsi_tape *un, int64_t files);
618 static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
619     int32_t fileno);
620 static int st_space_to_begining_of_file(struct scsi_tape *un);
621 static int st_space_records(struct scsi_tape *un, int64_t records);
622 static int st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc);
623 static errstate st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
624     errstate onentry);
625 static void st_recover(void *arg);
626 static void st_recov_cb(struct scsi_pkt *pkt);
627 static int st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait);
628 static int st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
629     int flag);
630 static void st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
631     struct scsi_pkt *cmd);
632 static int st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf);
633 static int st_test_path_to_device(struct scsi_tape *un);
634 static int st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
635     read_pos_data_t *raw);
636 static int st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
637     read_pos_data_t *raw);
638 static int st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
639     cmd_attribute const * cmd_att, tapepos_t *read);
640 static errstate st_recover_reissue_pkt(struct scsi_tape *us,
641     struct scsi_pkt *pkt);
642 static int st_transport(struct scsi_tape *un, struct scsi_pkt *pkt);
643 static buf_t *st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp);
644 static void st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp);
645 static int st_reset(struct scsi_tape *un, int reset_type);
646 static void st_reset_notification(caddr_t arg);
647 static const cmd_attribute *st_lookup_cmd_attribute(unsigned char cmd);
648 
649 #ifdef	__x86
650 /*
651  * routines for I/O in big block size
652  */
653 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
654 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
655     int alloc_flags);
656 static int st_bigblk_xfer_done(struct buf *bp);
657 static struct buf *st_get_bigblk_bp(struct buf *bp);
658 #endif
659 static void st_print_position(dev_info_t *dev, char *label, uint_t level,
660     const char *comment, tapepos_t *pos);
661 
662 /*
663  * error statistics create/update functions
664  */
665 static int st_create_errstats(struct scsi_tape *, int);
666 static int st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf,
667     tapepos_t *pos);
668 
669 #ifdef STDEBUG
670 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
671 #endif /* STDEBUG */
672 static char *st_dev_name(dev_t dev);
673 
674 #if !defined(lint)
675 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
676     scsi_pkt buf uio scsi_cdb uscsi_cmd))
677 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
678 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", recov_info))
679 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
680 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
681 #endif
682 
683 /*
684  * autoconfiguration routines.
685  */
686 char _depends_on[] = "misc/scsi";
687 
688 static struct modldrv modldrv = {
689 	&mod_driverops,		/* Type of module. This one is a driver */
690 	"SCSI tape Driver", 	/* Name of the module. */
691 	&st_ops			/* driver ops */
692 };
693 
694 static struct modlinkage modlinkage = {
695 	MODREV_1, &modldrv, NULL
696 };
697 
698 /*
699  * Notes on Post Reset Behavior in the tape driver:
700  *
701  * When the tape drive is opened, the driver  attempts  to make sure that
702  * the tape head is positioned exactly where it was left when it was last
703  * closed  provided  the  medium  is not  changed.  If the tape  drive is
704  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
705  * of position due to reset) will happen when the first tape operation or
706  * I/O occurs.  The repositioning (if required) may not be possible under
707  * certain situations such as when the device firmware not able to report
708  * the medium  change in the REQUEST  SENSE data  because of a reset or a
709  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
710  * extraordinary  situations, where the driver fails to position the head
711  * at its  original  position,  it will fail the open the first  time, to
712  * save the applications from overwriting the data.  All further attempts
713  * to open the tape device will result in the driver  attempting  to load
714  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
715  * indicate  that further  attempts to open the tape device may result in
716  * the tape being  loaded at BOT will be printed on the  console.  If the
717  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
718  * original tape head  position,  will result in the failure of the first
719  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
720  * internal tape position  which will  necessitate  the  applications  to
721  * validate the position by using either a tape  positioning  ioctl (such
722  * as MTREW) or closing and reopening the tape device.
723  *
724  */
725 
726 int
727 _init(void)
728 {
729 	int e;
730 
731 	if (((e = ddi_soft_state_init(&st_state,
732 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
733 		return (e);
734 	}
735 
736 	if ((e = mod_install(&modlinkage)) != 0) {
737 		ddi_soft_state_fini(&st_state);
738 	} else {
739 #ifdef STDEBUG
740 		mutex_init(&st_debug_mutex, NULL, MUTEX_DRIVER, NULL);
741 #endif
742 
743 #if defined(__x86)
744 		/* set the max physical address for iob allocs on x86 */
745 		st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
746 
747 		/*
748 		 * set the sgllen for iob allocs on x86. If this is set less
749 		 * than the number of pages the buffer will take
750 		 * (taking into account alignment), it would force the
751 		 * allocator to try and allocate contiguous pages.
752 		 */
753 		st_alloc_attr.dma_attr_sgllen = st_sgl_size;
754 #endif
755 	}
756 
757 	return (e);
758 }
759 
760 int
761 _fini(void)
762 {
763 	int e;
764 
765 	if ((e = mod_remove(&modlinkage)) != 0) {
766 		return (e);
767 	}
768 
769 #ifdef STDEBUG
770 	mutex_destroy(&st_debug_mutex);
771 #endif
772 
773 	ddi_soft_state_fini(&st_state);
774 
775 	return (e);
776 }
777 
778 int
779 _info(struct modinfo *modinfop)
780 {
781 	return (mod_info(&modlinkage, modinfop));
782 }
783 
784 
785 static int
786 st_probe(dev_info_t *devi)
787 {
788 	int instance;
789 	struct scsi_device *devp;
790 	int rval;
791 
792 #if !defined(__sparc)
793 	char    *tape_prop;
794 	int	tape_prop_len;
795 #endif
796 
797 	ST_ENTR(devi, st_probe);
798 
799 	/* If self identifying device */
800 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
801 		return (DDI_PROBE_DONTCARE);
802 	}
803 
804 #if !defined(__sparc)
805 	/*
806 	 * Since some x86 HBAs have devnodes that look like SCSI as
807 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
808 	 * we check for the presence of the "tape" property.
809 	 */
810 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
811 	    DDI_PROP_CANSLEEP, "tape",
812 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
813 		return (DDI_PROBE_FAILURE);
814 	}
815 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
816 		kmem_free(tape_prop, tape_prop_len);
817 		return (DDI_PROBE_FAILURE);
818 	}
819 	kmem_free(tape_prop, tape_prop_len);
820 #endif
821 
822 	devp = ddi_get_driver_private(devi);
823 	instance = ddi_get_instance(devi);
824 
825 	if (ddi_get_soft_state(st_state, instance) != NULL) {
826 		return (DDI_PROBE_PARTIAL);
827 	}
828 
829 
830 	/*
831 	 * Turn around and call probe routine to see whether
832 	 * we actually have a tape at this SCSI nexus.
833 	 */
834 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
835 
836 		/*
837 		 * In checking the whole inq_dtype byte we are looking at both
838 		 * the Peripheral Qualifier and the Peripheral Device Type.
839 		 * For this driver we are only interested in sequential devices
840 		 * that are connected or capable if connecting to this logical
841 		 * unit.
842 		 */
843 		if (devp->sd_inq->inq_dtype ==
844 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
845 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
846 			    "probe exists\n");
847 			rval = DDI_PROBE_SUCCESS;
848 		} else {
849 			rval = DDI_PROBE_FAILURE;
850 		}
851 	} else {
852 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
853 		    "probe failure: nothing there\n");
854 		rval = DDI_PROBE_FAILURE;
855 	}
856 	scsi_unprobe(devp);
857 	return (rval);
858 }
859 
860 static int
861 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
862 {
863 	int 	instance;
864 	int	wide;
865 	int 	dev_instance;
866 	int	ret_status;
867 	struct	scsi_device *devp;
868 	int	node_ix;
869 	struct	scsi_tape *un;
870 
871 	ST_ENTR(devi, st_attach);
872 
873 	devp = ddi_get_driver_private(devi);
874 	instance = ddi_get_instance(devi);
875 
876 	switch (cmd) {
877 		case DDI_ATTACH:
878 			if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
879 			    "tape-command-recovery-disable", 0) != 0) {
880 				st_recov_sz = sizeof (pkt_info);
881 			}
882 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
883 				return (DDI_FAILURE);
884 			}
885 			break;
886 		case DDI_RESUME:
887 			/*
888 			 * Suspend/Resume
889 			 *
890 			 * When the driver suspended, there might be
891 			 * outstanding cmds and therefore we need to
892 			 * reset the suspended flag and resume the scsi
893 			 * watch thread and restart commands and timeouts
894 			 */
895 
896 			if (!(un = ddi_get_soft_state(st_state, instance))) {
897 				return (DDI_FAILURE);
898 			}
899 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
900 			    un->un_dev);
901 
902 			mutex_enter(ST_MUTEX);
903 
904 			un->un_throttle = un->un_max_throttle;
905 			un->un_tids_at_suspend = 0;
906 			un->un_pwr_mgmt = ST_PWR_NORMAL;
907 
908 			if (un->un_swr_token) {
909 				scsi_watch_resume(un->un_swr_token);
910 			}
911 
912 			/*
913 			 * Restart timeouts
914 			 */
915 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
916 				mutex_exit(ST_MUTEX);
917 				un->un_delay_tid = timeout(
918 				    st_delayed_cv_broadcast, un,
919 				    drv_usectohz((clock_t)
920 				    MEDIA_ACCESS_DELAY));
921 				mutex_enter(ST_MUTEX);
922 			}
923 
924 			if (un->un_tids_at_suspend & ST_HIB_TID) {
925 				mutex_exit(ST_MUTEX);
926 				un->un_hib_tid = timeout(st_intr_restart, un,
927 				    ST_STATUS_BUSY_TIMEOUT);
928 				mutex_enter(ST_MUTEX);
929 			}
930 
931 			ret_status = st_clear_unit_attentions(dev_instance, 5);
932 
933 			/*
934 			 * now check if we need to restore the tape position
935 			 */
936 			if ((un->un_suspend_pos.pmode != invalid) &&
937 			    ((un->un_suspend_pos.fileno > 0) ||
938 			    (un->un_suspend_pos.blkno > 0)) ||
939 			    (un->un_suspend_pos.lgclblkno > 0)) {
940 				if (ret_status != 0) {
941 					/*
942 					 * tape didn't get good TUR
943 					 * just print out error messages
944 					 */
945 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
946 					    "st_attach-RESUME: tape failure "
947 					    " tape position will be lost");
948 				} else {
949 					/* this prints errors */
950 					(void) st_validate_tapemarks(un,
951 					    st_uscsi_cmd, &un->un_suspend_pos);
952 				}
953 				/*
954 				 * there are no retries, if there is an error
955 				 * we don't know if the tape has changed
956 				 */
957 				un->un_suspend_pos.pmode = invalid;
958 			}
959 
960 			/* now we are ready to start up any queued I/Os */
961 			if (un->un_ncmds || un->un_quef) {
962 				st_start(un);
963 			}
964 
965 			cv_broadcast(&un->un_suspend_cv);
966 			mutex_exit(ST_MUTEX);
967 			return (DDI_SUCCESS);
968 
969 		default:
970 			return (DDI_FAILURE);
971 	}
972 
973 	un = ddi_get_soft_state(st_state, instance);
974 
975 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
976 	    "st_attach: instance=%x\n", instance);
977 
978 	/*
979 	 * Add a zero-length attribute to tell the world we support
980 	 * kernel ioctls (for layered drivers)
981 	 */
982 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
983 	    DDI_KERNEL_IOCTL, NULL, 0);
984 
985 	ddi_report_dev((dev_info_t *)devi);
986 
987 	/*
988 	 * If it's a SCSI-2 tape drive which supports wide,
989 	 * tell the host adapter to use wide.
990 	 */
991 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
992 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
993 
994 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
995 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
996 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
997 	}
998 
999 	/*
1000 	 * enable autorequest sense; keep the rq packet around in case
1001 	 * the autorequest sense fails because of a busy condition
1002 	 * do a getcap first in case the capability is not variable
1003 	 */
1004 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
1005 		un->un_arq_enabled = 1;
1006 	} else {
1007 		un->un_arq_enabled =
1008 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
1009 	}
1010 
1011 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
1012 	    (un->un_arq_enabled ? "enabled" : "disabled"));
1013 
1014 	un->un_untagged_qing =
1015 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
1016 
1017 	/*
1018 	 * XXX - This is just for 2.6.  to tell users that write buffering
1019 	 *	has gone away.
1020 	 */
1021 	if (un->un_arq_enabled && un->un_untagged_qing) {
1022 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
1023 		    "tape-driver-buffering", 0) != 0) {
1024 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1025 			    "Write Data Buffering has been depricated. Your "
1026 			    "applications should continue to work normally.\n"
1027 			    " But, they should  ported to use Asynchronous "
1028 			    " I/O\n"
1029 			    " For more information, read about "
1030 			    " tape-driver-buffering "
1031 			    "property in the st(7d) man page\n");
1032 		}
1033 	}
1034 
1035 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
1036 	un->un_flush_on_errors = 0;
1037 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
1038 
1039 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
1040 	    "throttle=%x, max_throttle = %x\n",
1041 	    un->un_throttle, un->un_max_throttle);
1042 
1043 	/* initialize persistent errors to nil */
1044 	un->un_persistence = 0;
1045 	un->un_persist_errors = 0;
1046 
1047 	/*
1048 	 * Get dma-max from HBA driver. If it is not defined, use 64k
1049 	 */
1050 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
1051 	if (un->un_maxdma == -1) {
1052 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1053 		    "Received a value that looked like -1. Using 64k maxdma");
1054 		un->un_maxdma = (64 * ONE_K);
1055 	}
1056 
1057 #ifdef	__x86
1058 	/*
1059 	 * for x86, the device may be able to DMA more than the system will
1060 	 * allow under some circumstances. We need account for both the HBA's
1061 	 * and system's contraints.
1062 	 *
1063 	 * Get the maximum DMA under worse case conditions. e.g. looking at the
1064 	 * device constraints, the max copy buffer size, and the worse case
1065 	 * fragmentation. NOTE: this may differ from dma-max since dma-max
1066 	 * doesn't take the worse case framentation into account.
1067 	 *
1068 	 * e.g. a device may be able to DMA 16MBytes, but can only DMA 1MByte
1069 	 * if none of the pages are contiguous. Keeping track of both of these
1070 	 * values allows us to support larger tape block sizes on some devices.
1071 	 */
1072 	un->un_maxdma_arch = scsi_ifgetcap(&devp->sd_address, "dma-max-arch",
1073 	    1);
1074 
1075 	/*
1076 	 * If the dma-max-arch capability is not implemented, or the value
1077 	 * comes back higher than what was reported in dma-max, use dma-max.
1078 	 */
1079 	if ((un->un_maxdma_arch == -1) ||
1080 	    ((uint_t)un->un_maxdma < (uint_t)un->un_maxdma_arch)) {
1081 		un->un_maxdma_arch = un->un_maxdma;
1082 	}
1083 #endif
1084 
1085 	/*
1086 	 * Get the max allowable cdb size
1087 	 */
1088 	un->un_max_cdb_sz =
1089 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
1090 	if (un->un_max_cdb_sz < CDB_GROUP0) {
1091 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1092 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
1093 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
1094 	}
1095 
1096 	if (strcmp(ddi_driver_name(ddi_get_parent(ST_DEVINFO)), "scsi_vhci")) {
1097 		un->un_multipath = 0;
1098 	} else {
1099 		un->un_multipath = 1;
1100 	}
1101 
1102 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1103 
1104 	un->un_mediastate = MTIO_NONE;
1105 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1106 
1107 	/*
1108 	 * initialize kstats
1109 	 */
1110 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1111 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1112 	if (un->un_stats) {
1113 		un->un_stats->ks_lock = ST_MUTEX;
1114 		kstat_install(un->un_stats);
1115 	}
1116 	(void) st_create_errstats(un, instance);
1117 
1118 	/*
1119 	 * find the drive type for this target
1120 	 */
1121 	mutex_enter(ST_MUTEX);
1122 	un->un_dev = MTMINOR(instance);
1123 	st_known_tape_type(un);
1124 	un->un_dev = 0;
1125 	mutex_exit(ST_MUTEX);
1126 
1127 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
1128 		int minor;
1129 		char *name;
1130 
1131 		name  = st_minor_data[node_ix].name;
1132 		minor = st_minor_data[node_ix].minor;
1133 
1134 		/*
1135 		 * For default devices set the density to the
1136 		 * preferred default density for this device.
1137 		 */
1138 		if (node_ix <= DEF_BSD_NR) {
1139 			minor |= un->un_dp->default_density;
1140 		}
1141 		minor |= MTMINOR(instance);
1142 
1143 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
1144 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
1145 			continue;
1146 		}
1147 
1148 		ddi_remove_minor_node(devi, NULL);
1149 
1150 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1151 		    st_reset_notification, (caddr_t)un);
1152 		cv_destroy(&un->un_clscv);
1153 		cv_destroy(&un->un_sbuf_cv);
1154 		cv_destroy(&un->un_queue_cv);
1155 		cv_destroy(&un->un_state_cv);
1156 #ifdef	__x86
1157 		cv_destroy(&un->un_contig_mem_cv);
1158 #endif
1159 		cv_destroy(&un->un_suspend_cv);
1160 		cv_destroy(&un->un_tape_busy_cv);
1161 		cv_destroy(&un->un_recov_buf_cv);
1162 		if (un->un_recov_taskq) {
1163 			ddi_taskq_destroy(un->un_recov_taskq);
1164 		}
1165 		if (un->un_sbufp) {
1166 			freerbuf(un->un_sbufp);
1167 		}
1168 		if (un->un_recov_buf) {
1169 			freerbuf(un->un_recov_buf);
1170 		}
1171 		if (un->un_uscsi_rqs_buf) {
1172 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1173 		}
1174 		if (un->un_mspl) {
1175 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1176 		}
1177 		if (un->un_dp_size) {
1178 			kmem_free(un->un_dp, un->un_dp_size);
1179 		}
1180 		if (un->un_state) {
1181 			kstat_delete(un->un_stats);
1182 		}
1183 		if (un->un_errstats) {
1184 			kstat_delete(un->un_errstats);
1185 		}
1186 
1187 		scsi_destroy_pkt(un->un_rqs);
1188 		scsi_free_consistent_buf(un->un_rqs_bp);
1189 		ddi_soft_state_free(st_state, instance);
1190 		devp->sd_private = NULL;
1191 		devp->sd_sense = NULL;
1192 
1193 		ddi_prop_remove_all(devi);
1194 		return (DDI_FAILURE);
1195 	}
1196 
1197 	return (DDI_SUCCESS);
1198 }
1199 
1200 /*
1201  * st_detach:
1202  *
1203  * we allow a detach if and only if:
1204  *	- no tape is currently inserted
1205  *	- tape position is at BOT or unknown
1206  *		(if it is not at BOT then a no rewind
1207  *		device was opened and we have to preserve state)
1208  *	- it must be in a closed state : no timeouts or scsi_watch requests
1209  *		will exist if it is closed, so we don't need to check for
1210  *		them here.
1211  */
1212 /*ARGSUSED*/
1213 static int
1214 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1215 {
1216 	int instance;
1217 	int result;
1218 	struct scsi_device *devp;
1219 	struct scsi_tape *un;
1220 	clock_t wait_cmds_complete;
1221 
1222 	ST_ENTR(devi, st_detach);
1223 
1224 	instance = ddi_get_instance(devi);
1225 
1226 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1227 		return (DDI_FAILURE);
1228 	}
1229 
1230 	mutex_enter(ST_MUTEX);
1231 
1232 	/*
1233 	 * Clear error entry stack
1234 	 */
1235 	st_empty_error_stack(un);
1236 
1237 	mutex_exit(ST_MUTEX);
1238 
1239 	switch (cmd) {
1240 
1241 	case DDI_DETACH:
1242 		/*
1243 		 * Undo what we did in st_attach & st_doattach,
1244 		 * freeing resources and removing things we installed.
1245 		 * The system framework guarantees we are not active
1246 		 * with this devinfo node in any other entry points at
1247 		 * this time.
1248 		 */
1249 
1250 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1251 		    "st_detach: instance=%x, un=%p\n", instance,
1252 		    (void *)un);
1253 
1254 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1255 		    ((un->un_rsvd_status & ST_APPLICATION_RESERVATIONS) != 0) ||
1256 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1257 		    (un->un_state != ST_STATE_CLOSED)) {
1258 			/*
1259 			 * we cannot unload some targets because the
1260 			 * inquiry returns junk unless immediately
1261 			 * after a reset
1262 			 */
1263 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1264 			    "cannot unload instance %x\n", instance);
1265 			un->un_unit_attention_flags |= 4;
1266 			return (DDI_FAILURE);
1267 		}
1268 
1269 		/*
1270 		 * if the tape has been removed then we may unload;
1271 		 * do a test unit ready and if it returns NOT READY
1272 		 * then we assume that it is safe to unload.
1273 		 * as a side effect, pmode may be set to invalid if the
1274 		 * the test unit ready fails;
1275 		 * also un_state may be set to non-closed, so reset it
1276 		 */
1277 		if ((un->un_dev) &&		/* Been opened since attach */
1278 		    ((un->un_pos.pmode == legacy) &&
1279 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1280 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1281 		    ((un->un_pos.pmode == logical) &&
1282 		    (un->un_pos.lgclblkno > 0))) {
1283 			mutex_enter(ST_MUTEX);
1284 			/*
1285 			 * Send Test Unit Ready in the hopes that if
1286 			 * the drive is not in the state we think it is.
1287 			 * And the state will be changed so it can be detached.
1288 			 * If the command fails to reach the device and
1289 			 * the drive was not rewound or unloaded we want
1290 			 * to fail the detach till a user command fails
1291 			 * where after the detach will succead.
1292 			 */
1293 			result = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
1294 			/*
1295 			 * After TUR un_state may be set to non-closed,
1296 			 * so reset it back.
1297 			 */
1298 			un->un_state = ST_STATE_CLOSED;
1299 			mutex_exit(ST_MUTEX);
1300 		}
1301 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1302 		    "un_status=%x, fileno=%x, blkno=%x\n",
1303 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1304 
1305 		/*
1306 		 * check again:
1307 		 * if we are not at BOT then it is not safe to unload
1308 		 */
1309 		if ((un->un_dev) &&		/* Been opened since attach */
1310 		    (result != EACCES) &&	/* drive is use by somebody */
1311 		    (((un->un_pos.pmode == legacy) &&
1312 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1313 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1314 		    ((un->un_pos.pmode == logical) &&
1315 		    (un->un_pos.lgclblkno > 0)))) {
1316 
1317 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1318 			    "cannot detach: pmode=%d fileno=0x%x, blkno=0x%x"
1319 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1320 			    un->un_pos.fileno, un->un_pos.blkno,
1321 			    un->un_pos.lgclblkno);
1322 			un->un_unit_attention_flags |= 4;
1323 			return (DDI_FAILURE);
1324 		}
1325 
1326 		/*
1327 		 * Just To make sure that we have released the
1328 		 * tape unit .
1329 		 */
1330 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1331 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1332 			mutex_enter(ST_MUTEX);
1333 			(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
1334 			mutex_exit(ST_MUTEX);
1335 		}
1336 
1337 		/*
1338 		 * now remove other data structures allocated in st_doattach()
1339 		 */
1340 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1341 		    "destroying/freeing\n");
1342 
1343 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1344 		    st_reset_notification, (caddr_t)un);
1345 		cv_destroy(&un->un_clscv);
1346 		cv_destroy(&un->un_sbuf_cv);
1347 		cv_destroy(&un->un_queue_cv);
1348 		cv_destroy(&un->un_suspend_cv);
1349 		cv_destroy(&un->un_tape_busy_cv);
1350 		cv_destroy(&un->un_recov_buf_cv);
1351 
1352 		if (un->un_recov_taskq) {
1353 			ddi_taskq_destroy(un->un_recov_taskq);
1354 		}
1355 
1356 		if (un->un_hib_tid) {
1357 			(void) untimeout(un->un_hib_tid);
1358 			un->un_hib_tid = 0;
1359 		}
1360 
1361 		if (un->un_delay_tid) {
1362 			(void) untimeout(un->un_delay_tid);
1363 			un->un_delay_tid = 0;
1364 		}
1365 		cv_destroy(&un->un_state_cv);
1366 
1367 #ifdef	__x86
1368 		cv_destroy(&un->un_contig_mem_cv);
1369 
1370 		if (un->un_contig_mem_hdl != NULL) {
1371 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1372 		}
1373 #endif
1374 		if (un->un_sbufp) {
1375 			freerbuf(un->un_sbufp);
1376 		}
1377 		if (un->un_recov_buf) {
1378 			freerbuf(un->un_recov_buf);
1379 		}
1380 		if (un->un_uscsi_rqs_buf) {
1381 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1382 		}
1383 		if (un->un_mspl) {
1384 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1385 		}
1386 		if (un->un_rqs) {
1387 			scsi_destroy_pkt(un->un_rqs);
1388 			scsi_free_consistent_buf(un->un_rqs_bp);
1389 		}
1390 		if (un->un_mkr_pkt) {
1391 			scsi_destroy_pkt(un->un_mkr_pkt);
1392 		}
1393 		if (un->un_arq_enabled) {
1394 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1395 		}
1396 		if (un->un_dp_size) {
1397 			kmem_free(un->un_dp, un->un_dp_size);
1398 		}
1399 		if (un->un_stats) {
1400 			kstat_delete(un->un_stats);
1401 			un->un_stats = (kstat_t *)0;
1402 		}
1403 		if (un->un_errstats) {
1404 			kstat_delete(un->un_errstats);
1405 			un->un_errstats = (kstat_t *)0;
1406 		}
1407 		if (un->un_media_id_len) {
1408 			kmem_free(un->un_media_id, un->un_media_id_len);
1409 		}
1410 		devp = ST_SCSI_DEVP;
1411 		ddi_soft_state_free(st_state, instance);
1412 		devp->sd_private = NULL;
1413 		devp->sd_sense = NULL;
1414 		scsi_unprobe(devp);
1415 		ddi_prop_remove_all(devi);
1416 		ddi_remove_minor_node(devi, NULL);
1417 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1418 		return (DDI_SUCCESS);
1419 
1420 	case DDI_SUSPEND:
1421 
1422 		/*
1423 		 * Suspend/Resume
1424 		 *
1425 		 * To process DDI_SUSPEND, we must do the following:
1426 		 *
1427 		 *  - check ddi_removing_power to see if power will be turned
1428 		 *    off. if so, return DDI_FAILURE
1429 		 *  - check if we are already suspended,
1430 		 *    if so, return DDI_FAILURE
1431 		 *  - check if device state is CLOSED,
1432 		 *    if not, return DDI_FAILURE.
1433 		 *  - wait until outstanding operations complete
1434 		 *  - save tape state
1435 		 *  - block new operations
1436 		 *  - cancel pending timeouts
1437 		 *
1438 		 */
1439 
1440 		if (ddi_removing_power(devi)) {
1441 			return (DDI_FAILURE);
1442 		}
1443 		mutex_enter(ST_MUTEX);
1444 
1445 		/*
1446 		 * Shouldn't already be suspended, if so return failure
1447 		 */
1448 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1449 			mutex_exit(ST_MUTEX);
1450 			return (DDI_FAILURE);
1451 		}
1452 		if (un->un_state != ST_STATE_CLOSED) {
1453 			mutex_exit(ST_MUTEX);
1454 			return (DDI_FAILURE);
1455 		}
1456 
1457 		/*
1458 		 * Wait for all outstanding I/O's to complete
1459 		 *
1460 		 * we wait on both ncmds and the wait queue for times
1461 		 * when we are flushing after persistent errors are
1462 		 * flagged, which is when ncmds can be 0, and the
1463 		 * queue can still have I/O's.  This way we preserve
1464 		 * order of biodone's.
1465 		 */
1466 		wait_cmds_complete = ddi_get_lbolt();
1467 		wait_cmds_complete +=
1468 		    st_wait_cmds_complete * drv_usectohz(1000000);
1469 		while (un->un_ncmds || un->un_quef ||
1470 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1471 
1472 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1473 			    wait_cmds_complete) == -1) {
1474 				/*
1475 				 * Time expired then cancel the command
1476 				 */
1477 				if (st_reset(un, RESET_LUN) == 0) {
1478 					if (un->un_last_throttle) {
1479 						un->un_throttle =
1480 						    un->un_last_throttle;
1481 					}
1482 					mutex_exit(ST_MUTEX);
1483 					return (DDI_FAILURE);
1484 				} else {
1485 					break;
1486 				}
1487 			}
1488 		}
1489 
1490 		/*
1491 		 * DDI_SUSPEND says that the system "may" power down, we
1492 		 * remember the file and block number before rewinding.
1493 		 * we also need to save state before issuing
1494 		 * any WRITE_FILE_MARK command.
1495 		 */
1496 		(void) st_update_block_pos(un, st_cmd, 0);
1497 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1498 
1499 
1500 		/*
1501 		 * Issue a zero write file fmk command to tell the drive to
1502 		 * flush any buffered tape marks
1503 		 */
1504 		(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1505 
1506 		/*
1507 		 * Because not all tape drives correctly implement buffer
1508 		 * flushing with the zero write file fmk command, issue a
1509 		 * synchronous rewind command to force data flushing.
1510 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1511 		 * anyway.
1512 		 */
1513 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
1514 
1515 		/* stop any new operations */
1516 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1517 		un->un_throttle = 0;
1518 
1519 		/*
1520 		 * cancel any outstanding timeouts
1521 		 */
1522 		if (un->un_delay_tid) {
1523 			timeout_id_t temp_id = un->un_delay_tid;
1524 			un->un_delay_tid = 0;
1525 			un->un_tids_at_suspend |= ST_DELAY_TID;
1526 			mutex_exit(ST_MUTEX);
1527 			(void) untimeout(temp_id);
1528 			mutex_enter(ST_MUTEX);
1529 		}
1530 
1531 		if (un->un_hib_tid) {
1532 			timeout_id_t temp_id = un->un_hib_tid;
1533 			un->un_hib_tid = 0;
1534 			un->un_tids_at_suspend |= ST_HIB_TID;
1535 			mutex_exit(ST_MUTEX);
1536 			(void) untimeout(temp_id);
1537 			mutex_enter(ST_MUTEX);
1538 		}
1539 
1540 		/*
1541 		 * Suspend the scsi_watch_thread
1542 		 */
1543 		if (un->un_swr_token) {
1544 			opaque_t temp_token = un->un_swr_token;
1545 			mutex_exit(ST_MUTEX);
1546 			scsi_watch_suspend(temp_token);
1547 		} else {
1548 			mutex_exit(ST_MUTEX);
1549 		}
1550 
1551 		return (DDI_SUCCESS);
1552 
1553 	default:
1554 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1555 		return (DDI_FAILURE);
1556 	}
1557 }
1558 
1559 
1560 /* ARGSUSED */
1561 static int
1562 st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1563 {
1564 	dev_t dev;
1565 	struct scsi_tape *un;
1566 	int instance, error;
1567 
1568 	ST_ENTR(dip, st_info);
1569 
1570 	switch (infocmd) {
1571 	case DDI_INFO_DEVT2DEVINFO:
1572 		dev = (dev_t)arg;
1573 		instance = MTUNIT(dev);
1574 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1575 			return (DDI_FAILURE);
1576 		*result = (void *) ST_DEVINFO;
1577 		error = DDI_SUCCESS;
1578 		break;
1579 	case DDI_INFO_DEVT2INSTANCE:
1580 		dev = (dev_t)arg;
1581 		instance = MTUNIT(dev);
1582 		*result = (void *)(uintptr_t)instance;
1583 		error = DDI_SUCCESS;
1584 		break;
1585 	default:
1586 		error = DDI_FAILURE;
1587 	}
1588 	return (error);
1589 }
1590 
1591 static int
1592 st_doattach(struct scsi_device *devp, int (*canwait)())
1593 {
1594 	struct scsi_tape *un = NULL;
1595 	recov_info *ri;
1596 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1597 	int instance;
1598 	size_t rlen;
1599 
1600 	ST_FUNC(devp->sd_dev, st_doattach);
1601 	/*
1602 	 * Call the routine scsi_probe to do some of the dirty work.
1603 	 * If the INQUIRY command succeeds, the field sd_inq in the
1604 	 * device structure will be filled in.
1605 	 */
1606 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1607 	    "st_doattach(): probing\n");
1608 
1609 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1610 
1611 		/*
1612 		 * In checking the whole inq_dtype byte we are looking at both
1613 		 * the Peripheral Qualifier and the Peripheral Device Type.
1614 		 * For this driver we are only interested in sequential devices
1615 		 * that are connected or capable if connecting to this logical
1616 		 * unit.
1617 		 */
1618 		if (devp->sd_inq->inq_dtype ==
1619 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1620 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1621 			    "probe exists\n");
1622 		} else {
1623 			/* Something there but not a tape device */
1624 			scsi_unprobe(devp);
1625 			return (DDI_FAILURE);
1626 		}
1627 	} else {
1628 		/* Nothing there */
1629 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1630 		    "probe failure: nothing there\n");
1631 		scsi_unprobe(devp);
1632 		return (DDI_FAILURE);
1633 	}
1634 
1635 
1636 	/*
1637 	 * The actual unit is present.
1638 	 * Now is the time to fill in the rest of our info..
1639 	 */
1640 	instance = ddi_get_instance(devp->sd_dev);
1641 
1642 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1643 		goto error;
1644 	}
1645 	un = ddi_get_soft_state(st_state, instance);
1646 
1647 	ASSERT(un != NULL);
1648 
1649 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
1650 	    MAX_SENSE_LENGTH, B_READ, canwait, NULL);
1651 	if (un->un_rqs_bp == NULL) {
1652 		goto error;
1653 	}
1654 	un->un_rqs = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
1655 	    CDB_GROUP0, 1, st_recov_sz, PKT_CONSISTENT, canwait, NULL);
1656 	if (!un->un_rqs) {
1657 		goto error;
1658 	}
1659 	ASSERT(un->un_rqs->pkt_resid == 0);
1660 	devp->sd_sense =
1661 	    (struct scsi_extended_sense *)un->un_rqs_bp->b_un.b_addr;
1662 	ASSERT(geterror(un->un_rqs_bp) == NULL);
1663 
1664 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs->pkt_cdbp,
1665 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
1666 	FILL_SCSI1_LUN(devp, un->un_rqs);
1667 	un->un_rqs->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1668 	un->un_rqs->pkt_time = st_io_time;
1669 	un->un_rqs->pkt_comp = st_intr;
1670 	ri = (recov_info *)un->un_rqs->pkt_private;
1671 	if (st_recov_sz == sizeof (recov_info)) {
1672 		ri->privatelen = sizeof (recov_info);
1673 	} else {
1674 		ri->privatelen = sizeof (pkt_info);
1675 	}
1676 
1677 	un->un_sbufp = getrbuf(km_flags);
1678 	un->un_recov_buf = getrbuf(km_flags);
1679 
1680 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1681 
1682 	/*
1683 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1684 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1685 	 * is obsolete and we want more flexibility in controlling the DMA
1686 	 * address constraints.
1687 	 */
1688 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1689 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1690 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1691 
1692 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1693 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1694 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1695 
1696 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1697 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1698 		    "probe partial failure: no space\n");
1699 		goto error;
1700 	}
1701 
1702 	bzero(un->un_mspl, sizeof (struct seq_mode));
1703 
1704 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1705 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1706 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1707 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1708 #ifdef	__x86
1709 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1710 #endif
1711 
1712 	/* Initialize power managemnet condition variable */
1713 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1714 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1715 	cv_init(&un->un_recov_buf_cv, NULL, CV_DRIVER, NULL);
1716 
1717 	un->un_recov_taskq = ddi_taskq_create(devp->sd_dev,
1718 	    "un_recov_taskq", 1, TASKQ_DEFAULTPRI, km_flags);
1719 
1720 	ASSERT(un->un_recov_taskq != NULL);
1721 
1722 	un->un_pos.pmode = invalid;
1723 	un->un_sd	= devp;
1724 	un->un_swr_token = (opaque_t)NULL;
1725 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1726 	un->un_wormable = st_is_drive_worm;
1727 	un->un_media_id_method = st_get_media_identification;
1728 	/*
1729 	 * setting long a initial as it contains logical file info.
1730 	 * support for long format is mandatory but many drive don't do it.
1731 	 */
1732 	un->un_read_pos_type = LONG_POS;
1733 
1734 	un->un_suspend_pos.pmode = invalid;
1735 
1736 	st_add_recovery_info_to_pkt(un, un->un_rqs_bp, un->un_rqs);
1737 
1738 #ifdef	__x86
1739 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1740 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1741 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1742 		    "allocation of contiguous memory dma handle failed!");
1743 		un->un_contig_mem_hdl = NULL;
1744 		goto error;
1745 	}
1746 #endif
1747 
1748 	/*
1749 	 * Since this driver manages devices with "remote" hardware,
1750 	 * i.e. the devices themselves have no "reg" properties,
1751 	 * the SUSPEND/RESUME commands in detach/attach will not be
1752 	 * called by the power management framework unless we request
1753 	 * it by creating a "pm-hardware-state" property and setting it
1754 	 * to value "needs-suspend-resume".
1755 	 */
1756 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1757 	    "pm-hardware-state", "needs-suspend-resume") !=
1758 	    DDI_PROP_SUCCESS) {
1759 
1760 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1761 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1762 		goto error;
1763 	}
1764 
1765 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1766 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1767 
1768 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1769 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1770 		    "failed\n");
1771 		goto error;
1772 	}
1773 
1774 	(void) scsi_reset_notify(ROUTE, SCSI_RESET_NOTIFY,
1775 	    st_reset_notification, (caddr_t)un);
1776 
1777 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "attach success\n");
1778 	return (DDI_SUCCESS);
1779 
1780 error:
1781 	devp->sd_sense = NULL;
1782 
1783 	ddi_remove_minor_node(devp->sd_dev, NULL);
1784 	if (un) {
1785 		if (un->un_mspl) {
1786 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1787 		}
1788 		if (un->un_read_pos_data) {
1789 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1790 		}
1791 		if (un->un_sbufp) {
1792 			freerbuf(un->un_sbufp);
1793 		}
1794 		if (un->un_recov_buf) {
1795 			freerbuf(un->un_recov_buf);
1796 		}
1797 		if (un->un_uscsi_rqs_buf) {
1798 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1799 		}
1800 #ifdef	__x86
1801 		if (un->un_contig_mem_hdl != NULL) {
1802 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1803 		}
1804 #endif
1805 		if (un->un_rqs) {
1806 			scsi_destroy_pkt(un->un_rqs);
1807 		}
1808 
1809 		if (un->un_rqs_bp) {
1810 			scsi_free_consistent_buf(un->un_rqs_bp);
1811 		}
1812 
1813 		ddi_soft_state_free(st_state, instance);
1814 		devp->sd_private = NULL;
1815 	}
1816 
1817 	if (devp->sd_inq) {
1818 		scsi_unprobe(devp);
1819 	}
1820 	return (DDI_FAILURE);
1821 }
1822 
1823 typedef int
1824 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1825 
1826 static cfg_functp config_functs[] = {
1827 	st_get_conf_from_st_dot_conf,
1828 	st_get_conf_from_st_conf_dot_c,
1829 	st_get_conf_from_tape_drive,
1830 	st_get_default_conf
1831 };
1832 
1833 
1834 /*
1835  * determine tape type, using tape-config-list or built-in table or
1836  * use a generic tape config entry
1837  */
1838 static void
1839 st_known_tape_type(struct scsi_tape *un)
1840 {
1841 	struct st_drivetype *dp;
1842 	cfg_functp *config_funct;
1843 	uchar_t reserved;
1844 
1845 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1846 
1847 	reserved = (un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1848 	    : ST_RELEASE;
1849 
1850 	/*
1851 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1852 	 *	 no vid & pid inquiry data.  So, we provide one.
1853 	 */
1854 	if (ST_INQUIRY->inq_len == 0 ||
1855 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1856 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1857 	}
1858 
1859 	if (un->un_dp_size == 0) {
1860 		un->un_dp_size = sizeof (struct st_drivetype);
1861 		dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1862 		un->un_dp = dp;
1863 	} else {
1864 		dp = un->un_dp;
1865 	}
1866 
1867 	un->un_dp->non_motion_timeout = st_io_time;
1868 	/*
1869 	 * Loop through the configuration methods till one works.
1870 	 */
1871 	for (config_funct = &config_functs[0]; ; config_funct++) {
1872 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1873 			break;
1874 		}
1875 	}
1876 
1877 	/*
1878 	 * If we didn't just make up this configuration and
1879 	 * all the density codes are the same..
1880 	 * Set Auto Density over ride.
1881 	 */
1882 	if (*config_funct != st_get_default_conf) {
1883 		/*
1884 		 * If this device is one that is configured and all
1885 		 * densities are the same, This saves doing gets and set
1886 		 * that yield nothing.
1887 		 */
1888 		if ((dp->densities[0]) == (dp->densities[1]) &&
1889 		    (dp->densities[0]) == (dp->densities[2]) &&
1890 		    (dp->densities[0]) == (dp->densities[3])) {
1891 
1892 			dp->options |= ST_AUTODEN_OVERRIDE;
1893 		}
1894 	}
1895 
1896 
1897 	/*
1898 	 * Store tape drive characteristics.
1899 	 */
1900 	un->un_status = 0;
1901 	un->un_attached = 1;
1902 	un->un_init_options = dp->options;
1903 
1904 	/* setup operation time-outs based on options */
1905 	st_calculate_timeouts(un);
1906 
1907 	/* make sure if we are supposed to be variable, make it variable */
1908 	if (dp->options & ST_VARIABLE) {
1909 		dp->bsize = 0;
1910 	}
1911 
1912 	if (reserved != ((un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1913 	    : ST_RELEASE)) {
1914 		(void) st_reserve_release(un, reserved, st_uscsi_cmd);
1915 	}
1916 
1917 	un->un_unit_attention_flags |= 1;
1918 
1919 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1920 
1921 }
1922 
1923 
1924 typedef struct {
1925 	int mask;
1926 	int bottom;
1927 	int top;
1928 	char *name;
1929 } conf_limit;
1930 
1931 static const conf_limit conf_limits[] = {
1932 
1933 	-1,		1,		2,		"conf version",
1934 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1935 	-1,		0,		0xffffff,	"block size",
1936 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1937 	-1,		0,		4,		"number of densities",
1938 	-1,		0,		UINT8_MAX,	"density code",
1939 	-1,		0,		3,		"default density",
1940 	-1,		0,		UINT16_MAX,	"non motion timeout",
1941 	-1,		0,		UINT16_MAX,	"I/O timeout",
1942 	-1,		0,		UINT16_MAX,	"space timeout",
1943 	-1,		0,		UINT16_MAX,	"load timeout",
1944 	-1,		0,		UINT16_MAX,	"unload timeout",
1945 	-1,		0,		UINT16_MAX,	"erase timeout",
1946 	0,		0,		0,		NULL
1947 };
1948 
1949 static int
1950 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1951     const char *conf_name)
1952 {
1953 	int dens;
1954 	int ndens;
1955 	int value;
1956 	int type;
1957 	int count;
1958 	const conf_limit *limit = &conf_limits[0];
1959 
1960 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1961 
1962 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1963 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1964 
1965 	count = list_len;
1966 	type = *list;
1967 	for (;  count && limit->name; count--, list++, limit++) {
1968 
1969 		value = *list;
1970 		if (value & ~limit->mask) {
1971 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1972 			    "%s %s value invalid bits set: 0x%X\n",
1973 			    conf_name, limit->name, value & ~limit->mask);
1974 			*list &= limit->mask;
1975 		} else if (value < limit->bottom) {
1976 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1977 			    "%s %s value too low: value = %d limit %d\n",
1978 			    conf_name, limit->name, value, limit->bottom);
1979 		} else if (value > limit->top) {
1980 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1981 			    "%s %s value too high: value = %d limit %d\n",
1982 			    conf_name, limit->name, value, limit->top);
1983 		} else {
1984 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1985 			    "%s %s value = 0x%X\n",
1986 			    conf_name, limit->name, value);
1987 		}
1988 
1989 		/* If not the number of densities continue */
1990 		if (limit != &conf_limits[4]) {
1991 			continue;
1992 		}
1993 
1994 		/* If number of densities is not in range can't use config */
1995 		if (value < limit->bottom || value > limit->top) {
1996 			return (-1);
1997 		}
1998 
1999 		ndens = min(value, NDENSITIES);
2000 		if ((type == 1) && (list_len - ndens) != 6) {
2001 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2002 			    "%s conf version 1 with %d densities has %d items"
2003 			    " should have %d",
2004 			    conf_name, ndens, list_len, 6 + ndens);
2005 		} else if ((type == 2) && (list_len - ndens) != 13) {
2006 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2007 			    "%s conf version 2 with %d densities has %d items"
2008 			    " should have %d",
2009 			    conf_name, ndens, list_len, 13 + ndens);
2010 		}
2011 
2012 		limit++;
2013 		for (dens = 0; dens < ndens && count; dens++) {
2014 			count--;
2015 			list++;
2016 			value = *list;
2017 			if (value < limit->bottom) {
2018 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2019 				    "%s density[%d] value too low: value ="
2020 				    " 0x%X limit 0x%X\n",
2021 				    conf_name, dens, value, limit->bottom);
2022 			} else if (value > limit->top) {
2023 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2024 				    "%s density[%d] value too high: value ="
2025 				    " 0x%X limit 0x%X\n",
2026 				    conf_name, dens, value, limit->top);
2027 			} else {
2028 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2029 				    "%s density[%d] value = 0x%X\n",
2030 				    conf_name, dens, value);
2031 			}
2032 		}
2033 	}
2034 
2035 	return (0);
2036 }
2037 
2038 static int
2039 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
2040     struct st_drivetype *dp)
2041 {
2042 	caddr_t config_list = NULL;
2043 	caddr_t data_list = NULL;
2044 	int	*data_ptr;
2045 	caddr_t vidptr, prettyptr, datanameptr;
2046 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
2047 	int config_list_len, data_list_len, len, i;
2048 	int version;
2049 	int found = 0;
2050 
2051 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
2052 
2053 	/*
2054 	 * Determine type of tape controller. Type is determined by
2055 	 * checking the vendor ids of the earlier inquiry command and
2056 	 * comparing those with vids in tape-config-list defined in st.conf
2057 	 */
2058 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
2059 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
2060 	    != DDI_PROP_SUCCESS) {
2061 		return (found);
2062 	}
2063 
2064 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2065 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
2066 
2067 	/*
2068 	 * Compare vids in each triplet - if it matches, get value for
2069 	 * data_name and contruct a st_drivetype struct
2070 	 * tripletlen is not set yet!
2071 	 */
2072 	for (len = config_list_len, vidptr = config_list;
2073 	    len > 0;
2074 	    vidptr += tripletlen, len -= tripletlen) {
2075 
2076 		vidlen = strlen(vidptr);
2077 		prettyptr = vidptr + vidlen + 1;
2078 		prettylen = strlen(prettyptr);
2079 		datanameptr = prettyptr + prettylen + 1;
2080 		datanamelen = strlen(datanameptr);
2081 		tripletlen = vidlen + prettylen + datanamelen + 3;
2082 
2083 		if (vidlen == 0) {
2084 			continue;
2085 		}
2086 
2087 		/*
2088 		 * If inquiry vid dosen't match this triplets vid,
2089 		 * try the next.
2090 		 */
2091 		if (strncasecmp(vidpid, vidptr, vidlen)) {
2092 			continue;
2093 		}
2094 
2095 		/*
2096 		 * if prettylen is zero then use the vid string
2097 		 */
2098 		if (prettylen == 0) {
2099 			prettyptr = vidptr;
2100 			prettylen = vidlen;
2101 		}
2102 
2103 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2104 		    "vid = %s, pretty=%s, dataname = %s\n",
2105 		    vidptr, prettyptr, datanameptr);
2106 
2107 		/*
2108 		 * get the data list
2109 		 */
2110 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
2111 		    datanameptr, (caddr_t)&data_list,
2112 		    &data_list_len) != DDI_PROP_SUCCESS) {
2113 			/*
2114 			 * Error in getting property value
2115 			 * print warning!
2116 			 */
2117 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2118 			    "data property (%s) has no value\n",
2119 			    datanameptr);
2120 			continue;
2121 		}
2122 
2123 		/*
2124 		 * now initialize the st_drivetype struct
2125 		 */
2126 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
2127 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
2128 		(void) strncpy(dp->vid, vidptr, dp->length);
2129 		data_ptr = (int *)data_list;
2130 		/*
2131 		 * check if data is enough for version, type,
2132 		 * bsize, options, # of densities, density1,
2133 		 * density2, ..., default_density
2134 		 */
2135 		if ((data_list_len < 5 * sizeof (int)) ||
2136 		    (data_list_len < 6 * sizeof (int) +
2137 		    *(data_ptr + 4) * sizeof (int))) {
2138 			/*
2139 			 * print warning and skip to next triplet.
2140 			 */
2141 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2142 			    "data property (%s) incomplete\n",
2143 			    datanameptr);
2144 			kmem_free(data_list, data_list_len);
2145 			continue;
2146 		}
2147 
2148 		if (st_validate_conf_data(un, data_ptr,
2149 		    data_list_len / sizeof (int), datanameptr)) {
2150 			kmem_free(data_list, data_list_len);
2151 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2152 			    "data property (%s) rejected\n",
2153 			    datanameptr);
2154 			continue;
2155 		}
2156 
2157 		/*
2158 		 * check version
2159 		 */
2160 		version = *data_ptr++;
2161 		if (version != 1 && version != 2) {
2162 			/* print warning but accept it */
2163 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2164 			    "Version # for data property (%s) "
2165 			    "not set to 1 or 2\n", datanameptr);
2166 		}
2167 
2168 		dp->type    = *data_ptr++;
2169 		dp->bsize   = *data_ptr++;
2170 		dp->options = *data_ptr++;
2171 		dp->options |= ST_DYNAMIC;
2172 		len = *data_ptr++;
2173 		for (i = 0; i < NDENSITIES; i++) {
2174 			if (i < len) {
2175 				dp->densities[i] = *data_ptr++;
2176 			}
2177 		}
2178 		dp->default_density = *data_ptr << 3;
2179 		if (version == 2 &&
2180 		    data_list_len >= (13 + len) * sizeof (int)) {
2181 			data_ptr++;
2182 			dp->non_motion_timeout	= *data_ptr++;
2183 			dp->io_timeout		= *data_ptr++;
2184 			dp->rewind_timeout	= *data_ptr++;
2185 			dp->space_timeout	= *data_ptr++;
2186 			dp->load_timeout	= *data_ptr++;
2187 			dp->unload_timeout	= *data_ptr++;
2188 			dp->erase_timeout	= *data_ptr++;
2189 		}
2190 		kmem_free(data_list, data_list_len);
2191 		found = 1;
2192 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2193 		    "found in st.conf: vid = %s, pretty=%s\n",
2194 		    dp->vid, dp->name);
2195 		break;
2196 	}
2197 
2198 	/*
2199 	 * free up the memory allocated by ddi_getlongprop
2200 	 */
2201 	if (config_list) {
2202 		kmem_free(config_list, config_list_len);
2203 	}
2204 	return (found);
2205 }
2206 
2207 static int
2208 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2209     struct st_drivetype *dp)
2210 {
2211 	int i;
2212 
2213 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2214 	/*
2215 	 * Determine type of tape controller.  Type is determined by
2216 	 * checking the result of the earlier inquiry command and
2217 	 * comparing vendor ids with strings in a table declared in st_conf.c.
2218 	 */
2219 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2220 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2221 
2222 	for (i = 0; i < st_ndrivetypes; i++) {
2223 		if (st_drivetypes[i].length == 0) {
2224 			continue;
2225 		}
2226 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2227 		    st_drivetypes[i].length)) {
2228 			continue;
2229 		}
2230 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2231 		return (1);
2232 	}
2233 	return (0);
2234 }
2235 
2236 static int
2237 st_get_conf_from_tape_drive(struct scsi_tape *un, char *vidpid,
2238     struct st_drivetype *dp)
2239 {
2240 	int bsize;
2241 	ulong_t maxbsize;
2242 	caddr_t buf;
2243 	struct st_drivetype *tem_dp;
2244 	struct read_blklim *blklim;
2245 	int rval;
2246 	int i;
2247 
2248 	ST_FUNC(ST_DEVINFO, st_get_conf_from_tape_drive);
2249 
2250 	/*
2251 	 * Determine the type of tape controller. Type is determined by
2252 	 * sending SCSI commands to tape drive and deriving the type from
2253 	 * the returned data.
2254 	 */
2255 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2256 	    "st_get_conf_from_tape_drive(): asking tape drive\n");
2257 
2258 	tem_dp = kmem_zalloc(sizeof (struct st_drivetype), KM_SLEEP);
2259 
2260 	/*
2261 	 * Make up a name
2262 	 */
2263 	bcopy(vidpid, tem_dp->name, VIDPIDLEN);
2264 	tem_dp->name[VIDPIDLEN] = '\0';
2265 	tem_dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2266 	(void) strncpy(tem_dp->vid, ST_INQUIRY->inq_vid, tem_dp->length);
2267 	/*
2268 	 * 'clean' vendor and product strings of non-printing chars
2269 	 */
2270 	for (i = 0; i < VIDPIDLEN - 1; i ++) {
2271 		if (tem_dp->name[i] < ' ' || tem_dp->name[i] > '~') {
2272 			tem_dp->name[i] = '.';
2273 		}
2274 	}
2275 
2276 	/*
2277 	 * MODE SENSE to determine block size.
2278 	 */
2279 	un->un_dp->options |= ST_MODE_SEL_COMP | ST_UNLOADABLE;
2280 	rval = st_modesense(un);
2281 	if (rval) {
2282 		if (rval == EACCES) {
2283 			un->un_dp->type = ST_TYPE_INVALID;
2284 			rval = 1;
2285 		} else {
2286 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
2287 			rval = 0;
2288 		}
2289 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2290 		    "st_get_conf_from_tape_drive(): fail to mode sense\n");
2291 		goto exit;
2292 	}
2293 
2294 	/* Can mode sense page 0x10 or 0xf */
2295 	tem_dp->options |= ST_MODE_SEL_COMP;
2296 	bsize = (un->un_mspl->high_bl << 16)	|
2297 	    (un->un_mspl->mid_bl << 8)		|
2298 	    (un->un_mspl->low_bl);
2299 
2300 	if (bsize == 0) {
2301 		tem_dp->options |= ST_VARIABLE;
2302 		tem_dp->bsize = 0;
2303 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
2304 		rval = st_change_block_size(un, 0);
2305 		if (rval) {
2306 			if (rval == EACCES) {
2307 				un->un_dp->type = ST_TYPE_INVALID;
2308 				rval = 1;
2309 			} else {
2310 				rval = 0;
2311 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2312 				    "st_get_conf_from_tape_drive(): "
2313 				    "Fixed record size is too large and"
2314 				    "cannot switch to variable record size");
2315 			}
2316 			goto exit;
2317 		}
2318 		tem_dp->options |= ST_VARIABLE;
2319 	} else {
2320 		rval = st_change_block_size(un, 0);
2321 		if (rval == 0) {
2322 			tem_dp->options |= ST_VARIABLE;
2323 			tem_dp->bsize = 0;
2324 		} else if (rval != EACCES) {
2325 			tem_dp->bsize = bsize;
2326 		} else {
2327 			un->un_dp->type = ST_TYPE_INVALID;
2328 			rval = 1;
2329 			goto exit;
2330 		}
2331 	}
2332 
2333 	/*
2334 	 * If READ BLOCk LIMITS works and upper block size limit is
2335 	 * more than 64K, ST_NO_RECSIZE_LIMIT is supported.
2336 	 */
2337 	blklim = kmem_zalloc(sizeof (struct read_blklim), KM_SLEEP);
2338 	rval = st_read_block_limits(un, blklim);
2339 	if (rval) {
2340 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2341 		    "st_get_conf_from_tape_drive(): "
2342 		    "fail to read block limits.\n");
2343 		rval = 0;
2344 		kmem_free(blklim, sizeof (struct read_blklim));
2345 		goto exit;
2346 	}
2347 	maxbsize = (blklim->max_hi << 16) +
2348 	    (blklim->max_mid << 8) + blklim->max_lo;
2349 	if (maxbsize > ST_MAXRECSIZE_VARIABLE) {
2350 		tem_dp->options |= ST_NO_RECSIZE_LIMIT;
2351 	}
2352 	kmem_free(blklim, sizeof (struct read_blklim));
2353 
2354 	/*
2355 	 * Inquiry VPD page 0xb0 to see if the tape drive supports WORM
2356 	 */
2357 	buf = kmem_zalloc(6, KM_SLEEP);
2358 	rval = st_get_special_inquiry(un, 6, buf, 0xb0);
2359 	if (rval) {
2360 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2361 		    "st_get_conf_from_tape_drive(): "
2362 		    "fail to read vitial inquiry.\n");
2363 		rval = 0;
2364 		kmem_free(buf, 6);
2365 		goto exit;
2366 	}
2367 	if (buf[4] & 1) {
2368 		tem_dp->options |= ST_WORMABLE;
2369 	}
2370 	kmem_free(buf, 6);
2371 
2372 	/* Assume BSD BSR KNOWS_EOD */
2373 	tem_dp->options |= ST_BSF | ST_BSR | ST_KNOWS_EOD | ST_UNLOADABLE;
2374 	tem_dp->max_rretries = -1;
2375 	tem_dp->max_wretries = -1;
2376 
2377 	/*
2378 	 * Decide the densities supported by tape drive by sending
2379 	 * REPORT DENSITY SUPPORT command.
2380 	 */
2381 	if (st_get_densities_from_tape_drive(un, tem_dp) == 0) {
2382 		goto exit;
2383 	}
2384 
2385 	/*
2386 	 * Decide the timeout values for several commands by sending
2387 	 * REPORT SUPPORTED OPERATION CODES command.
2388 	 */
2389 	rval = st_get_timeout_values_from_tape_drive(un, tem_dp);
2390 	if (rval == 0 || ((rval == 1) && (tem_dp->type == ST_TYPE_INVALID))) {
2391 		goto exit;
2392 	}
2393 
2394 	bcopy(tem_dp, dp, sizeof (struct st_drivetype));
2395 	rval = 1;
2396 
2397 exit:
2398 	un->un_status = KEY_NO_SENSE;
2399 	kmem_free(tem_dp, sizeof (struct st_drivetype));
2400 	return (rval);
2401 }
2402 
2403 static int
2404 st_get_densities_from_tape_drive(struct scsi_tape *un,
2405     struct st_drivetype *dp)
2406 {
2407 	int i, p;
2408 	size_t buflen;
2409 	ushort_t des_len;
2410 	uchar_t *den_header;
2411 	uchar_t num_den;
2412 	uchar_t den[NDENSITIES];
2413 	uchar_t deflt[NDENSITIES];
2414 	struct report_density_desc *den_desc;
2415 
2416 	ST_FUNC(ST_DEVINFO, st_get_densities_from_type_drive);
2417 
2418 	/*
2419 	 * Since we have no idea how many densitiy support entries
2420 	 * will be returned, we send the command firstly assuming
2421 	 * there is only one. Then we can decide the number of
2422 	 * entries by available density support length. If multiple
2423 	 * entries exist, we will resend the command with enough
2424 	 * buffer size.
2425 	 */
2426 	buflen = sizeof (struct report_density_header) +
2427 	    sizeof (struct report_density_desc);
2428 	den_header = kmem_zalloc(buflen, KM_SLEEP);
2429 	if (st_report_density_support(un, den_header, buflen) != 0) {
2430 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2431 		    "st_get_conf_from_tape_drive(): fail to report density.\n");
2432 		kmem_free(den_header, buflen);
2433 		return (0);
2434 	}
2435 	des_len =
2436 	    BE_16(((struct report_density_header *)den_header)->ava_dens_len);
2437 	num_den = (des_len - 2) / sizeof (struct report_density_desc);
2438 
2439 	if (num_den > 1) {
2440 		kmem_free(den_header, buflen);
2441 		buflen = sizeof (struct report_density_header) +
2442 		    sizeof (struct report_density_desc) * num_den;
2443 		den_header = kmem_zalloc(buflen, KM_SLEEP);
2444 		if (st_report_density_support(un, den_header, buflen) != 0) {
2445 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2446 			    "st_get_conf_from_tape_drive(): "
2447 			    "fail to report density.\n");
2448 			kmem_free(den_header, buflen);
2449 			return (0);
2450 		}
2451 	}
2452 
2453 	den_desc = (struct report_density_desc *)(den_header
2454 	    + sizeof (struct report_density_header));
2455 
2456 	/*
2457 	 * Decide the drive type by assigning organization
2458 	 */
2459 	for (i = 0; i < ST_NUM_MEMBERS(st_vid_dt); i ++) {
2460 		if (strncmp(st_vid_dt[i].vid, (char *)(den_desc->ass_org),
2461 		    8) == 0) {
2462 			dp->type = st_vid_dt[i].type;
2463 			break;
2464 		}
2465 	}
2466 	if (i == ST_NUM_MEMBERS(st_vid_dt)) {
2467 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2468 		    "st_get_conf_from_tape_drive(): "
2469 		    "can't find match of assigned ort.\n");
2470 		kmem_free(den_header, buflen);
2471 		return (0);
2472 	}
2473 
2474 	/*
2475 	 * The tape drive may support many tape formats, but the st driver
2476 	 * supports only the four highest densities. Since density code
2477 	 * values are returned by ascending sequence, we start from the
2478 	 * last entry of density support data block descriptor.
2479 	 */
2480 	p = 0;
2481 	den_desc += num_den - 1;
2482 	for (i = 0; i < num_den && p < NDENSITIES; i ++, den_desc --) {
2483 		if ((den_desc->pri_den != 0) && (den_desc->wrtok)) {
2484 			if (p != 0) {
2485 				if (den_desc->pri_den >= den[p - 1]) {
2486 					continue;
2487 				}
2488 			}
2489 			den[p] = den_desc->pri_den;
2490 			deflt[p] = den_desc->deflt;
2491 			p ++;
2492 		}
2493 	}
2494 
2495 	switch (p) {
2496 	case 0:
2497 		bzero(dp->densities, NDENSITIES);
2498 		dp->options |= ST_AUTODEN_OVERRIDE;
2499 		dp->default_density = MT_DENSITY4;
2500 		break;
2501 
2502 	case 1:
2503 		(void) memset(dp->densities, den[0], NDENSITIES);
2504 		dp->options |= ST_AUTODEN_OVERRIDE;
2505 		dp->default_density = MT_DENSITY4;
2506 		break;
2507 
2508 	case 2:
2509 		dp->densities[0] = den[1];
2510 		dp->densities[1] = den[1];
2511 		dp->densities[2] = den[0];
2512 		dp->densities[3] = den[0];
2513 		if (deflt[0]) {
2514 			dp->default_density = MT_DENSITY4;
2515 		} else {
2516 			dp->default_density = MT_DENSITY2;
2517 		}
2518 		break;
2519 
2520 	case 3:
2521 		dp->densities[0] = den[2];
2522 		dp->densities[1] = den[1];
2523 		dp->densities[2] = den[0];
2524 		dp->densities[3] = den[0];
2525 		if (deflt[0]) {
2526 			dp->default_density = MT_DENSITY4;
2527 		} else if (deflt[1]) {
2528 			dp->default_density = MT_DENSITY2;
2529 		} else {
2530 			dp->default_density = MT_DENSITY1;
2531 		}
2532 		break;
2533 
2534 	default:
2535 		for (i = p; i > p - NDENSITIES; i --) {
2536 			dp->densities[i - 1] = den[p - i];
2537 		}
2538 		if (deflt[0]) {
2539 			dp->default_density = MT_DENSITY4;
2540 		} else if (deflt[1]) {
2541 			dp->default_density = MT_DENSITY3;
2542 		} else if (deflt[2]) {
2543 			dp->default_density = MT_DENSITY2;
2544 		} else {
2545 			dp->default_density = MT_DENSITY1;
2546 		}
2547 		break;
2548 	}
2549 
2550 	bzero(dp->mediatype, NDENSITIES);
2551 
2552 	kmem_free(den_header, buflen);
2553 	return (1);
2554 }
2555 
2556 static int
2557 st_get_timeout_values_from_tape_drive(struct scsi_tape *un,
2558     struct st_drivetype *dp)
2559 {
2560 	ushort_t timeout;
2561 	int rval;
2562 
2563 	ST_FUNC(ST_DEVINFO, st_get_timeout_values_from_type_drive);
2564 
2565 	rval = st_get_timeouts_value(un, SCMD_ERASE, &timeout, 0);
2566 	if (rval) {
2567 		if (rval == EACCES) {
2568 			un->un_dp->type = ST_TYPE_INVALID;
2569 			dp->type = ST_TYPE_INVALID;
2570 			return (1);
2571 		}
2572 		return (0);
2573 	}
2574 	dp->erase_timeout = timeout;
2575 
2576 	rval = st_get_timeouts_value(un, SCMD_READ, &timeout, 0);
2577 	if (rval) {
2578 		if (rval == EACCES) {
2579 			un->un_dp->type = ST_TYPE_INVALID;
2580 			dp->type = ST_TYPE_INVALID;
2581 			return (1);
2582 		}
2583 		return (0);
2584 	}
2585 	dp->io_timeout = timeout;
2586 
2587 	rval = st_get_timeouts_value(un, SCMD_WRITE, &timeout, 0);
2588 	if (rval) {
2589 		if (rval == EACCES) {
2590 			un->un_dp->type = ST_TYPE_INVALID;
2591 			dp->type = ST_TYPE_INVALID;
2592 			return (1);
2593 		}
2594 		return (0);
2595 	}
2596 	dp->io_timeout = max(dp->io_timeout, timeout);
2597 
2598 	rval = st_get_timeouts_value(un, SCMD_SPACE, &timeout, 0);
2599 	if (rval) {
2600 		if (rval == EACCES) {
2601 			un->un_dp->type = ST_TYPE_INVALID;
2602 			dp->type = ST_TYPE_INVALID;
2603 			return (1);
2604 		}
2605 		return (0);
2606 	}
2607 	dp->space_timeout = timeout;
2608 
2609 	rval = st_get_timeouts_value(un, SCMD_LOAD, &timeout, 0);
2610 	if (rval) {
2611 		if (rval == EACCES) {
2612 			un->un_dp->type = ST_TYPE_INVALID;
2613 			dp->type = ST_TYPE_INVALID;
2614 			return (1);
2615 		}
2616 		return (0);
2617 	}
2618 	dp->load_timeout = timeout;
2619 	dp->unload_timeout = timeout;
2620 
2621 	rval = st_get_timeouts_value(un, SCMD_REWIND, &timeout, 0);
2622 	if (rval) {
2623 		if (rval == EACCES) {
2624 			un->un_dp->type = ST_TYPE_INVALID;
2625 			dp->type = ST_TYPE_INVALID;
2626 			return (1);
2627 		}
2628 		return (0);
2629 	}
2630 	dp->rewind_timeout = timeout;
2631 
2632 	rval = st_get_timeouts_value(un, SCMD_INQUIRY, &timeout, 0);
2633 	if (rval) {
2634 		if (rval == EACCES) {
2635 			un->un_dp->type = ST_TYPE_INVALID;
2636 			dp->type = ST_TYPE_INVALID;
2637 			return (1);
2638 		}
2639 		return (0);
2640 	}
2641 	dp->non_motion_timeout = timeout;
2642 
2643 	return (1);
2644 }
2645 
2646 static int
2647 st_get_timeouts_value(struct scsi_tape *un, uchar_t option_code,
2648     ushort_t *timeout_value, ushort_t service_action)
2649 {
2650 	uchar_t *timeouts;
2651 	uchar_t *oper;
2652 	uchar_t support;
2653 	uchar_t cdbsize;
2654 	uchar_t ctdp;
2655 	size_t buflen;
2656 	int rval;
2657 
2658 	ST_FUNC(ST_DEVINFO, st_get_timeouts_value);
2659 
2660 	buflen = sizeof (struct one_com_des) +
2661 	    sizeof (struct com_timeout_des);
2662 	oper = kmem_zalloc(buflen, KM_SLEEP);
2663 	rval = st_report_supported_operation(un, oper, option_code,
2664 	    service_action);
2665 
2666 	if (rval) {
2667 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2668 		    "st_get_timeouts_value(): "
2669 		    "fail to timeouts value for command %d.\n", option_code);
2670 		kmem_free(oper, buflen);
2671 		return (rval);
2672 	}
2673 
2674 	support = ((struct one_com_des *)oper)->support;
2675 	if ((support != SUPPORT_VALUES_SUPPORT_SCSI) &&
2676 	    (support != SUPPORT_VALUES_SUPPORT_VENDOR)) {
2677 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2678 		    "st_get_timeouts_value(): "
2679 		    "command %d is not supported.\n", option_code);
2680 		kmem_free(oper, buflen);
2681 		return (ENOTSUP);
2682 	}
2683 
2684 	ctdp = ((struct one_com_des *)oper)->ctdp;
2685 	if (!ctdp) {
2686 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2687 		    "st_get_timeouts_value(): "
2688 		    "command timeout is not included.\n");
2689 		kmem_free(oper, buflen);
2690 		return (ENOTSUP);
2691 	}
2692 
2693 	cdbsize = BE_16(((struct one_com_des *)oper)->cdb_size);
2694 	timeouts = (uchar_t *)(oper + cdbsize + 4);
2695 
2696 	/*
2697 	 * Timeout value in seconds is 4 bytes, but we only support the lower 2
2698 	 * bytes. If the higher 2 bytes are not zero, the timeout value is set
2699 	 * to 0xFFFF.
2700 	 */
2701 	if (*(timeouts + 8) != 0 || *(timeouts + 9) != 0) {
2702 		*timeout_value = USHRT_MAX;
2703 	} else {
2704 		*timeout_value = ((*(timeouts + 10)) << 8) |
2705 		    (*(timeouts + 11));
2706 	}
2707 
2708 	kmem_free(oper, buflen);
2709 	return (0);
2710 }
2711 
2712 static int
2713 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2714 {
2715 	int i;
2716 
2717 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2718 
2719 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2720 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2721 
2722 	/*
2723 	 * Make up a name
2724 	 */
2725 	bcopy("Vendor '", dp->name, 8);
2726 	bcopy(vidpid, &dp->name[8], VIDLEN);
2727 	bcopy("' Product '", &dp->name[16], 11);
2728 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2729 	dp->name[ST_NAMESIZE - 2] = '\'';
2730 	dp->name[ST_NAMESIZE - 1] = '\0';
2731 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2732 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2733 	/*
2734 	 * 'clean' vendor and product strings of non-printing chars
2735 	 */
2736 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2737 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2738 			dp->name[i] = '.';
2739 		}
2740 	}
2741 	dp->type = ST_TYPE_INVALID;
2742 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2743 
2744 	return (1); /* Can Not Fail */
2745 }
2746 
2747 /*
2748  * Regular Unix Entry points
2749  */
2750 
2751 
2752 
2753 /* ARGSUSED */
2754 static int
2755 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2756 {
2757 	dev_t dev = *dev_p;
2758 	int rval = 0;
2759 
2760 	GET_SOFT_STATE(dev);
2761 
2762 	ST_ENTR(ST_DEVINFO, st_open);
2763 
2764 	/*
2765 	 * validate that we are addressing a sensible unit
2766 	 */
2767 	mutex_enter(ST_MUTEX);
2768 
2769 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2770 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2771 	    st_dev_name(dev), *dev_p, flag, otyp);
2772 
2773 	/*
2774 	 * All device accesss go thru st_strategy() where we check
2775 	 * suspend status
2776 	 */
2777 
2778 	if (!un->un_attached) {
2779 		st_known_tape_type(un);
2780 		if (!un->un_attached) {
2781 			rval = ENXIO;
2782 			goto exit;
2783 		}
2784 
2785 	}
2786 
2787 	/*
2788 	 * Check for the case of the tape in the middle of closing.
2789 	 * This isn't simply a check of the current state, because
2790 	 * we could be in state of sensing with the previous state
2791 	 * that of closing.
2792 	 *
2793 	 * And don't allow multiple opens.
2794 	 */
2795 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2796 		un->un_laststate = un->un_state;
2797 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2798 		while (IS_CLOSING(un) ||
2799 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2800 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2801 				rval = EINTR;
2802 				un->un_state = un->un_laststate;
2803 				goto exit;
2804 			}
2805 		}
2806 	} else if (un->un_state != ST_STATE_CLOSED) {
2807 		rval = EBUSY;
2808 		goto busy;
2809 	}
2810 
2811 	/*
2812 	 * record current dev
2813 	 */
2814 	un->un_dev = dev;
2815 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2816 	un->un_errno = 0;	/* no errors yet */
2817 	un->un_restore_pos = 0;
2818 	un->un_rqs_state = 0;
2819 
2820 	/*
2821 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2822 	 * anything, leave internal states alone, if fileno >= 0
2823 	 */
2824 	if (flag & (FNDELAY | FNONBLOCK)) {
2825 		switch (un->un_pos.pmode) {
2826 
2827 		case invalid:
2828 			un->un_state = ST_STATE_OFFLINE;
2829 			break;
2830 
2831 		case legacy:
2832 			/*
2833 			 * If position is anything other than rewound.
2834 			 */
2835 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2836 				/*
2837 				 * set un_read_only/write-protect status.
2838 				 *
2839 				 * If the tape is not bot we can assume
2840 				 * that mspl->wp_status is set properly.
2841 				 * else
2842 				 * we need to do a mode sense/Tur once
2843 				 * again to get the actual tape status.(since
2844 				 * user might have replaced the tape)
2845 				 * Hence make the st state OFFLINE so that
2846 				 * we re-intialize the tape once again.
2847 				 */
2848 				un->un_read_only =
2849 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2850 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2851 			} else {
2852 				un->un_state = ST_STATE_OFFLINE;
2853 			}
2854 			break;
2855 		case logical:
2856 			if (un->un_pos.lgclblkno == 0) {
2857 				un->un_state = ST_STATE_OFFLINE;
2858 			} else {
2859 				un->un_read_only =
2860 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2861 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2862 			}
2863 			break;
2864 		}
2865 		rval = 0;
2866 	} else {
2867 		/*
2868 		 * Not opening O_NDELAY.
2869 		 */
2870 		un->un_state = ST_STATE_OPENING;
2871 
2872 		/*
2873 		 * Clear error entry stack
2874 		 */
2875 		st_empty_error_stack(un);
2876 
2877 		rval = st_tape_init(un);
2878 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2879 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2880 			rval = 0; /* so open doesn't fail */
2881 		} else if (rval) {
2882 			/*
2883 			 * Release the tape unit, if reserved and not
2884 			 * preserve reserve.
2885 			 */
2886 			if ((un->un_rsvd_status &
2887 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2888 				(void) st_reserve_release(un, ST_RELEASE,
2889 				    st_uscsi_cmd);
2890 			}
2891 		} else {
2892 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2893 		}
2894 	}
2895 
2896 exit:
2897 	/*
2898 	 * we don't want any uninvited guests scrogging our data when we're
2899 	 * busy with something, so for successful opens or failed opens
2900 	 * (except for EBUSY), reset these counters and state appropriately.
2901 	 */
2902 	if (rval != EBUSY) {
2903 		if (rval) {
2904 			un->un_state = ST_STATE_CLOSED;
2905 		}
2906 		un->un_err_resid = 0;
2907 		un->un_retry_ct = 0;
2908 	}
2909 busy:
2910 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2911 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2912 	mutex_exit(ST_MUTEX);
2913 	return (rval);
2914 
2915 }
2916 
2917 static int
2918 st_tape_init(struct scsi_tape *un)
2919 {
2920 	int err;
2921 	int rval = 0;
2922 
2923 	ST_FUNC(ST_DEVINFO, st_tape_init);
2924 
2925 	ASSERT(mutex_owned(ST_MUTEX));
2926 
2927 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2928 	    "st_tape_init(un = 0x%p, oflags = %d)\n", (void*)un, un->un_oflags);
2929 
2930 	/*
2931 	 * Clean up after any errors left by 'last' close.
2932 	 * This also handles the case of the initial open.
2933 	 */
2934 	if (un->un_state != ST_STATE_INITIALIZING) {
2935 		un->un_laststate = un->un_state;
2936 		un->un_state = ST_STATE_OPENING;
2937 	}
2938 
2939 	un->un_kbytes_xferred = 0;
2940 
2941 	/*
2942 	 * do a throw away TUR to clear check condition
2943 	 */
2944 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2945 
2946 	/*
2947 	 * If test unit ready fails because the drive is reserved
2948 	 * by another host fail the open for no access.
2949 	 */
2950 	if (err) {
2951 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2952 			un->un_state = ST_STATE_CLOSED;
2953 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2954 			    "st_tape_init: RESERVATION CONFLICT\n");
2955 			rval = EACCES;
2956 			goto exit;
2957 		} else if ((un->un_rsvd_status &
2958 		    ST_APPLICATION_RESERVATIONS) != 0) {
2959 			if ((ST_RQSENSE != NULL) &&
2960 			    (ST_RQSENSE->es_add_code == 0x2a &&
2961 			    ST_RQSENSE->es_qual_code == 0x03)) {
2962 				un->un_state = ST_STATE_CLOSED;
2963 				rval = EACCES;
2964 				goto exit;
2965 			}
2966 		}
2967 	}
2968 
2969 	/*
2970 	 * Tape self identification could fail if the tape drive is used by
2971 	 * another host during attach time. We try to get the tape type
2972 	 * again. This is also applied to any posponed configuration methods.
2973 	 */
2974 	if (un->un_dp->type == ST_TYPE_INVALID) {
2975 		un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
2976 		st_known_tape_type(un);
2977 	}
2978 
2979 	/*
2980 	 * If the tape type is still invalid, try to determine the generic
2981 	 * configuration.
2982 	 */
2983 	if (un->un_dp->type == ST_TYPE_INVALID) {
2984 		rval = st_determine_generic(un);
2985 		if (rval) {
2986 			if (rval != EACCES) {
2987 				rval = EIO;
2988 			}
2989 			un->un_state = ST_STATE_CLOSED;
2990 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2991 			    "st_tape_init: %s invalid type\n",
2992 			    rval == EACCES ? "EACCES" : "EIO");
2993 			goto exit;
2994 		}
2995 		/*
2996 		 * If this is a Unknown Type drive,
2997 		 * Use the READ BLOCK LIMITS to determine if
2998 		 * allow large xfer is approprate if not globally
2999 		 * disabled with st_allow_large_xfer.
3000 		 */
3001 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
3002 	} else {
3003 
3004 		/*
3005 		 * If we allow_large_xfer (ie >64k) and have not yet found out
3006 		 * the max block size supported by the drive,
3007 		 * find it by issueing a READ_BLKLIM command.
3008 		 * if READ_BLKLIM cmd fails, assume drive doesn't
3009 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
3010 		 */
3011 		un->un_allow_large_xfer = st_allow_large_xfer &&
3012 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
3013 	}
3014 	/*
3015 	 * if maxbsize is unknown, set the maximum block size.
3016 	 */
3017 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
3018 
3019 		/*
3020 		 * Get the Block limits of the tape drive.
3021 		 * if un->un_allow_large_xfer = 0 , then make sure
3022 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
3023 		 */
3024 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
3025 
3026 		err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3027 		if (err) {
3028 			/* Retry */
3029 			err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3030 		}
3031 		if (!err) {
3032 
3033 			/*
3034 			 * if cmd successful, use limit returned
3035 			 */
3036 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
3037 			    (un->un_rbl->max_mid << 8) +
3038 			    un->un_rbl->max_lo;
3039 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
3040 			    un->un_rbl->min_lo;
3041 			un->un_data_mod = 1 << un->un_rbl->granularity;
3042 			if ((un->un_maxbsize == 0) ||
3043 			    (un->un_allow_large_xfer == 0 &&
3044 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
3045 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3046 
3047 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
3048 				/*
3049 				 * Drive is not one that is configured, But the
3050 				 * READ BLOCK LIMITS tells us it can do large
3051 				 * xfers.
3052 				 */
3053 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
3054 					un->un_dp->options |=
3055 					    ST_NO_RECSIZE_LIMIT;
3056 				}
3057 				/*
3058 				 * If max and mimimum block limits are the
3059 				 * same this is a fixed block size device.
3060 				 */
3061 				if (un->un_maxbsize == un->un_minbsize) {
3062 					un->un_dp->options &= ~ST_VARIABLE;
3063 				}
3064 			}
3065 
3066 			if (un->un_minbsize == 0) {
3067 				un->un_minbsize = 1;
3068 			}
3069 
3070 		} else { /* error on read block limits */
3071 
3072 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3073 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
3074 			    " errno = %d un_rsvd_status = 0x%X\n",
3075 			    err, un->un_rsvd_status);
3076 
3077 			/*
3078 			 * since read block limits cmd failed,
3079 			 * do not allow large xfers.
3080 			 * use old values in st_minphys
3081 			 */
3082 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
3083 				rval = EACCES;
3084 			} else {
3085 				un->un_allow_large_xfer = 0;
3086 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3087 				    "!Disabling large transfers\n");
3088 
3089 				/*
3090 				 * we guess maxbsize and minbsize
3091 				 */
3092 				if (un->un_bsize) {
3093 					un->un_maxbsize = un->un_minbsize =
3094 					    un->un_bsize;
3095 				} else {
3096 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3097 					un->un_minbsize = 1;
3098 				}
3099 				/*
3100 				 * Data Mod must be set,
3101 				 * Even if read block limits fails.
3102 				 * Prevents Divide By Zero in st_rw().
3103 				 */
3104 				un->un_data_mod = 1;
3105 			}
3106 		}
3107 		if (un->un_rbl) {
3108 			kmem_free(un->un_rbl, RBLSIZE);
3109 			un->un_rbl = NULL;
3110 		}
3111 
3112 		if (rval) {
3113 			goto exit;
3114 		}
3115 	}
3116 
3117 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3118 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
3119 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
3120 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
3121 
3122 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
3123 
3124 	if (err != 0) {
3125 		if (err == EINTR) {
3126 			un->un_laststate = un->un_state;
3127 			un->un_state = ST_STATE_CLOSED;
3128 			rval = EINTR;
3129 			goto exit;
3130 		}
3131 		/*
3132 		 * Make sure the tape is ready
3133 		 */
3134 		un->un_pos.pmode = invalid;
3135 		if (un->un_status != KEY_UNIT_ATTENTION) {
3136 			/*
3137 			 * allow open no media.  Subsequent MTIOCSTATE
3138 			 * with media present will complete the open
3139 			 * logic.
3140 			 */
3141 			un->un_laststate = un->un_state;
3142 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
3143 				un->un_mediastate = MTIO_EJECTED;
3144 				un->un_state = ST_STATE_OFFLINE;
3145 				rval = 0;
3146 				goto exit;
3147 			} else {
3148 				un->un_state = ST_STATE_CLOSED;
3149 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3150 				    "st_tape_init EIO no media, not opened "
3151 				    "O_NONBLOCK|O_EXCL\n");
3152 				rval = EIO;
3153 				goto exit;
3154 			}
3155 		}
3156 	}
3157 
3158 	/*
3159 	 * On each open, initialize block size from drivetype struct,
3160 	 * as it could have been changed by MTSRSZ ioctl.
3161 	 * Now, ST_VARIABLE simply means drive is capable of variable
3162 	 * mode. All drives are assumed to support fixed records.
3163 	 * Hence, un_bsize tells what mode the drive is in.
3164 	 *	un_bsize	= 0	- variable record length
3165 	 *			= x	- fixed record length is x
3166 	 */
3167 	un->un_bsize = un->un_dp->bsize;
3168 
3169 	/*
3170 	 * If saved position is valid go there
3171 	 */
3172 	if (un->un_restore_pos) {
3173 		un->un_restore_pos = 0;
3174 		un->un_pos.fileno = un->un_save_fileno;
3175 		un->un_pos.blkno = un->un_save_blkno;
3176 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &un->un_pos);
3177 		if (rval != 0) {
3178 			if (rval != EACCES) {
3179 				rval = EIO;
3180 			}
3181 			un->un_laststate = un->un_state;
3182 			un->un_state = ST_STATE_CLOSED;
3183 			goto exit;
3184 		}
3185 	}
3186 
3187 	if (un->un_pos.pmode == invalid) {
3188 		rval = st_loadtape(un);
3189 		if (rval) {
3190 			if (rval != EACCES) {
3191 				rval = EIO;
3192 			}
3193 			un->un_laststate = un->un_state;
3194 			un->un_state = ST_STATE_CLOSED;
3195 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3196 			    "st_tape_init: %s can't open tape\n",
3197 			    rval == EACCES ? "EACCES" : "EIO");
3198 			goto exit;
3199 		}
3200 	}
3201 
3202 	/*
3203 	 * do a mode sense to pick up state of current write-protect,
3204 	 * Could cause reserve and fail due to conflict.
3205 	 */
3206 	if (un->un_unit_attention_flags) {
3207 		rval = st_modesense(un);
3208 		if (rval == EACCES) {
3209 			goto exit;
3210 		}
3211 	}
3212 
3213 	/*
3214 	 * If we are opening the tape for writing, check
3215 	 * to make sure that the tape can be written.
3216 	 */
3217 	if (un->un_oflags & FWRITE) {
3218 		err = 0;
3219 		if (un->un_mspl->wp) {
3220 			un->un_status = KEY_WRITE_PROTECT;
3221 			un->un_laststate = un->un_state;
3222 			un->un_state = ST_STATE_CLOSED;
3223 			rval = EACCES;
3224 			/*
3225 			 * STK sets the wp bit if volsafe tape is loaded.
3226 			 */
3227 			if ((un->un_dp->type == MT_ISSTK9840) &&
3228 			    (un->un_dp->options & ST_WORMABLE)) {
3229 				un->un_read_only = RDONLY;
3230 			} else {
3231 				goto exit;
3232 			}
3233 		} else {
3234 			un->un_read_only = RDWR;
3235 		}
3236 	} else {
3237 		un->un_read_only = RDONLY;
3238 	}
3239 
3240 	if (un->un_dp->options & ST_WORMABLE &&
3241 	    un->un_unit_attention_flags) {
3242 		un->un_read_only |= un->un_wormable(un);
3243 
3244 		if (((un->un_read_only == WORM) ||
3245 		    (un->un_read_only == RDWORM)) &&
3246 		    ((un->un_oflags & FWRITE) == FWRITE)) {
3247 			un->un_status = KEY_DATA_PROTECT;
3248 			rval = EACCES;
3249 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3250 			    "read_only = %d eof = %d oflag = %d\n",
3251 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3252 		}
3253 	}
3254 
3255 	/*
3256 	 * If we're opening the tape write-only, we need to
3257 	 * write 2 filemarks on the HP 1/2 inch drive, to
3258 	 * create a null file.
3259 	 */
3260 	if ((un->un_read_only == RDWR) ||
3261 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3262 		if (un->un_dp->options & ST_REEL) {
3263 			un->un_fmneeded = 2;
3264 		} else {
3265 			un->un_fmneeded = 1;
3266 		}
3267 	} else {
3268 		un->un_fmneeded = 0;
3269 	}
3270 
3271 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3272 	    "fmneeded = %x\n", un->un_fmneeded);
3273 
3274 	/*
3275 	 * Make sure the density can be selected correctly.
3276 	 * If WORM can only write at the append point which in most cases
3277 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3278 	 * to set and try densities if a BOP.
3279 	 */
3280 	if (st_determine_density(un,
3281 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3282 		un->un_status = KEY_ILLEGAL_REQUEST;
3283 		un->un_laststate = un->un_state;
3284 		un->un_state = ST_STATE_CLOSED;
3285 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3286 		    "st_tape_init: EIO can't determine density\n");
3287 		rval = EIO;
3288 		goto exit;
3289 	}
3290 
3291 	/*
3292 	 * Destroy the knowledge that we have 'determined'
3293 	 * density so that a later read at BOT comes along
3294 	 * does the right density determination.
3295 	 */
3296 
3297 	un->un_density_known = 0;
3298 
3299 
3300 	/*
3301 	 * Okay, the tape is loaded and either at BOT or somewhere past.
3302 	 * Mark the state such that any I/O or tape space operations
3303 	 * will get/set the right density, etc..
3304 	 */
3305 	un->un_laststate = un->un_state;
3306 	un->un_lastop = ST_OP_NIL;
3307 	un->un_mediastate = MTIO_INSERTED;
3308 	cv_broadcast(&un->un_state_cv);
3309 
3310 	/*
3311 	 *  Set test append flag if writing.
3312 	 *  First write must check that tape is positioned correctly.
3313 	 */
3314 	un->un_test_append = (un->un_oflags & FWRITE);
3315 
3316 	/*
3317 	 * if there are pending unit attention flags.
3318 	 * Check that the media has not changed.
3319 	 */
3320 	if (un->un_unit_attention_flags) {
3321 		rval = st_get_media_identification(un, st_uscsi_cmd);
3322 		if (rval != 0 && rval != EACCES) {
3323 			rval = EIO;
3324 		}
3325 		un->un_unit_attention_flags = 0;
3326 	}
3327 
3328 exit:
3329 	un->un_err_resid = 0;
3330 	un->un_last_resid = 0;
3331 	un->un_last_count = 0;
3332 
3333 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3334 	    "st_tape_init: return val = %x\n", rval);
3335 	return (rval);
3336 
3337 }
3338 
3339 
3340 
3341 /* ARGSUSED */
3342 static int
3343 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3344 {
3345 	int err = 0;
3346 	int count, last_state;
3347 	minor_t minor = getminor(dev);
3348 #ifdef	__x86
3349 	struct contig_mem *cp, *cp_temp;
3350 #endif
3351 
3352 	GET_SOFT_STATE(dev);
3353 
3354 	ST_ENTR(ST_DEVINFO, st_close);
3355 
3356 	/*
3357 	 * wait till all cmds in the pipeline have been completed
3358 	 */
3359 	mutex_enter(ST_MUTEX);
3360 
3361 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3362 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3363 
3364 	st_wait_for_io(un);
3365 
3366 	/* turn off persistent errors on close, as we want close to succeed */
3367 	st_turn_pe_off(un);
3368 
3369 	/*
3370 	 * set state to indicate that we are in process of closing
3371 	 */
3372 	last_state = un->un_laststate = un->un_state;
3373 	un->un_state = ST_STATE_CLOSING;
3374 
3375 	ST_POS(ST_DEVINFO, "st_close1:", &un->un_pos);
3376 
3377 	/*
3378 	 * BSD behavior:
3379 	 * a close always causes a silent span to the next file if we've hit
3380 	 * an EOF (but not yet read across it).
3381 	 */
3382 	if ((minor & MT_BSD) && (un->un_pos.eof == ST_EOF)) {
3383 		if (un->un_pos.pmode != invalid) {
3384 			un->un_pos.fileno++;
3385 			un->un_pos.blkno = 0;
3386 		}
3387 		un->un_pos.eof = ST_NO_EOF;
3388 	}
3389 
3390 	/*
3391 	 * SVR4 behavior for skipping to next file:
3392 	 *
3393 	 * If we have not seen a filemark, space to the next file
3394 	 *
3395 	 * If we have already seen the filemark we are physically in the next
3396 	 * file and we only increment the filenumber
3397 	 */
3398 	if (((minor & (MT_BSD | MT_NOREWIND)) == MT_NOREWIND) &&
3399 	    (flag & FREAD) &&		/* reading or at least asked to */
3400 	    (un->un_mediastate == MTIO_INSERTED) &&	/* tape loaded */
3401 	    (un->un_pos.pmode != invalid) &&		/* XXX position known */
3402 	    ((un->un_pos.blkno != 0) && 		/* inside a file */
3403 	    (un->un_lastop != ST_OP_WRITE) &&		/* Didn't just write */
3404 	    (un->un_lastop != ST_OP_WEOF))) {		/* or write filemarks */
3405 		switch (un->un_pos.eof) {
3406 		case ST_NO_EOF:
3407 			/*
3408 			 * if we were reading and did not read the complete file
3409 			 * skip to the next file, leaving the tape correctly
3410 			 * positioned to read the first record of the next file
3411 			 * Check first for REEL if we are at EOT by trying to
3412 			 * read a block
3413 			 */
3414 			if ((un->un_dp->options & ST_REEL) &&
3415 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3416 			    (un->un_pos.blkno == 0)) {
3417 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3418 					ST_DEBUG2(ST_DEVINFO, st_label,
3419 					    SCSI_DEBUG,
3420 					    "st_close : EIO can't space\n");
3421 					err = EIO;
3422 					goto error_out;
3423 				}
3424 				if (un->un_pos.eof >= ST_EOF_PENDING) {
3425 					un->un_pos.eof = ST_EOT_PENDING;
3426 					un->un_pos.fileno += 1;
3427 					un->un_pos.blkno   = 0;
3428 					break;
3429 				}
3430 			}
3431 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3432 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3433 				    "st_close: EIO can't space #2\n");
3434 				err = EIO;
3435 				goto error_out;
3436 			} else {
3437 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3438 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3439 				    un->un_pos.fileno, un->un_pos.blkno,
3440 				    un->un_pos.eof);
3441 				un->un_pos.eof = ST_NO_EOF;
3442 			}
3443 			break;
3444 
3445 		case ST_EOF_PENDING:
3446 		case ST_EOF:
3447 			un->un_pos.fileno += 1;
3448 			un->un_pos.lgclblkno += 1;
3449 			un->un_pos.blkno   = 0;
3450 			un->un_pos.eof = ST_NO_EOF;
3451 			break;
3452 
3453 		case ST_EOT:
3454 		case ST_EOT_PENDING:
3455 		case ST_EOM:
3456 			/* nothing to do */
3457 			break;
3458 		default:
3459 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
3460 			    "Undefined state 0x%x", un->un_pos.eof);
3461 
3462 		}
3463 	}
3464 
3465 
3466 	/*
3467 	 * For performance reasons (HP 88780), the driver should
3468 	 * postpone writing the second tape mark until just before a file
3469 	 * positioning ioctl is issued (e.g., rewind).	This means that
3470 	 * the user must not manually rewind the tape because the tape will
3471 	 * be missing the second tape mark which marks EOM.
3472 	 * However, this small performance improvement is not worth the risk.
3473 	 */
3474 
3475 	/*
3476 	 * We need to back up over the filemark we inadvertently popped
3477 	 * over doing a read in between the two filemarks that constitute
3478 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3479 	 * set while reading.
3480 	 *
3481 	 * If we happen to be at physical eot (ST_EOM) (writing case),
3482 	 * the writing of filemark(s) will clear the ST_EOM state, which
3483 	 * we don't want, so we save this state and restore it later.
3484 	 */
3485 
3486 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3487 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3488 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3489 
3490 	if (un->un_pos.eof == ST_EOT_PENDING) {
3491 		if (minor & MT_NOREWIND) {
3492 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3493 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3494 				    "st_close: EIO can't space #3\n");
3495 				err = EIO;
3496 				goto error_out;
3497 			} else {
3498 				un->un_pos.blkno = 0;
3499 				un->un_pos.eof = ST_EOT;
3500 			}
3501 		} else {
3502 			un->un_pos.eof = ST_NO_EOF;
3503 		}
3504 
3505 	/*
3506 	 * Do we need to write a file mark?
3507 	 *
3508 	 * only write filemarks if there are fmks to be written and
3509 	 *   - open for write (possibly read/write)
3510 	 *   - the last operation was a write
3511 	 * or:
3512 	 *   -	opened for wronly
3513 	 *   -	no data was written
3514 	 */
3515 	} else if ((un->un_pos.pmode != invalid) &&
3516 	    (un->un_fmneeded > 0) &&
3517 	    (((flag & FWRITE) &&
3518 	    ((un->un_lastop == ST_OP_WRITE)||(un->un_lastop == ST_OP_WEOF))) ||
3519 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3520 
3521 		/* save ST_EOM state */
3522 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3523 
3524 		/*
3525 		 * Note that we will write a filemark if we had opened
3526 		 * the tape write only and no data was written, thus
3527 		 * creating a null file.
3528 		 *
3529 		 * If the user already wrote one, we only have to write 1 more.
3530 		 * If they wrote two, we don't have to write any.
3531 		 */
3532 
3533 		count = un->un_fmneeded;
3534 		if (count > 0) {
3535 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, count, SYNC_CMD)) {
3536 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3537 				    "st_close : EIO can't wfm\n");
3538 				err = EIO;
3539 				goto error_out;
3540 			}
3541 			if ((un->un_dp->options & ST_REEL) &&
3542 			    (minor & MT_NOREWIND)) {
3543 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3544 					ST_DEBUG2(ST_DEVINFO, st_label,
3545 					    SCSI_DEBUG,
3546 					    "st_close : EIO space fmk(-1)\n");
3547 					err = EIO;
3548 					goto error_out;
3549 				}
3550 				un->un_pos.eof = ST_NO_EOF;
3551 				/* fix up block number */
3552 				un->un_pos.blkno = 0;
3553 			}
3554 		}
3555 
3556 		/*
3557 		 * If we aren't going to be rewinding, and we were at
3558 		 * physical eot, restore the state that indicates we
3559 		 * are at physical eot. Once you have reached physical
3560 		 * eot, and you close the tape, the only thing you can
3561 		 * do on the next open is to rewind. Access to trailer
3562 		 * records is only allowed without closing the device.
3563 		 */
3564 		if ((minor & MT_NOREWIND) == 0 && was_at_eom) {
3565 			un->un_pos.eof = ST_EOM;
3566 		}
3567 	}
3568 
3569 	/*
3570 	 * report soft errors if enabled and available, if we never accessed
3571 	 * the drive, don't get errors. This will prevent some DAT error
3572 	 * messages upon LOG SENSE.
3573 	 */
3574 	if (st_report_soft_errors_on_close &&
3575 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3576 	    (last_state != ST_STATE_OFFLINE)) {
3577 		if (st_report_soft_errors(dev, flag)) {
3578 			err = EIO;
3579 			goto error_out;
3580 		}
3581 	}
3582 
3583 
3584 	/*
3585 	 * Do we need to rewind? Can we rewind?
3586 	 */
3587 	if ((minor & MT_NOREWIND) == 0 &&
3588 	    un->un_pos.pmode != invalid && err == 0) {
3589 		/*
3590 		 * We'd like to rewind with the
3591 		 * 'immediate' bit set, but this
3592 		 * causes problems on some drives
3593 		 * where subsequent opens get a
3594 		 * 'NOT READY' error condition
3595 		 * back while the tape is rewinding,
3596 		 * which is impossible to distinguish
3597 		 * from the condition of 'no tape loaded'.
3598 		 *
3599 		 * Also, for some targets, if you disconnect
3600 		 * with the 'immediate' bit set, you don't
3601 		 * actually return right away, i.e., the
3602 		 * target ignores your request for immediate
3603 		 * return.
3604 		 *
3605 		 * Instead, we'll fire off an async rewind
3606 		 * command. We'll mark the device as closed,
3607 		 * and any subsequent open will stall on
3608 		 * the first TEST_UNIT_READY until the rewind
3609 		 * completes.
3610 		 */
3611 
3612 		/*
3613 		 * Used to be if reserve was not supported we'd send an
3614 		 * asynchronious rewind. Comments above may be slightly invalid
3615 		 * as the immediate bit was never set. Doing an immedate rewind
3616 		 * makes sense, I think fixes to not ready status might handle
3617 		 * the problems described above.
3618 		 */
3619 		if (un->un_sd->sd_inq->inq_ansi < 2) {
3620 			if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
3621 				err = EIO;
3622 			}
3623 		} else {
3624 			/* flush data for older drives per scsi spec. */
3625 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD)) {
3626 				err = EIO;
3627 			} else {
3628 				/* release the drive before rewind immediate */
3629 				if ((un->un_rsvd_status &
3630 				    (ST_RESERVE | ST_PRESERVE_RESERVE)) ==
3631 				    ST_RESERVE) {
3632 					if (st_reserve_release(un, ST_RELEASE,
3633 					    st_uscsi_cmd)) {
3634 						err = EIO;
3635 					}
3636 				}
3637 
3638 				/* send rewind with immediate bit set */
3639 				if (st_cmd(un, SCMD_REWIND, 1, ASYNC_CMD)) {
3640 					err = EIO;
3641 				}
3642 			}
3643 		}
3644 		/*
3645 		 * Setting positions invalid in case the rewind doesn't
3646 		 * happen. Drives don't like to rewind if resets happen
3647 		 * they will tend to move back to where the rewind was
3648 		 * issued if a reset or something happens so that if a
3649 		 * write happens the data doesn't get clobbered.
3650 		 *
3651 		 * Not a big deal if the position is invalid when the
3652 		 * open occures it will do a read position.
3653 		 */
3654 		un->un_pos.pmode = invalid;
3655 		un->un_running.pmode = invalid;
3656 
3657 		if (err == EIO) {
3658 			goto error_out;
3659 		}
3660 	}
3661 
3662 	/*
3663 	 * eject tape if necessary
3664 	 */
3665 	if (un->un_eject_tape_on_failure) {
3666 		un->un_eject_tape_on_failure = 0;
3667 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3668 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3669 			    "st_close : can't unload tape\n");
3670 			err = EIO;
3671 			goto error_out;
3672 		} else {
3673 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3674 			    "st_close : tape unloaded \n");
3675 			un->un_pos.eof = ST_NO_EOF;
3676 			un->un_mediastate = MTIO_EJECTED;
3677 		}
3678 	}
3679 	/*
3680 	 * Release the tape unit, if default reserve/release
3681 	 * behaviour.
3682 	 */
3683 	if ((un->un_rsvd_status &
3684 	    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
3685 		(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
3686 	}
3687 error_out:
3688 	/*
3689 	 * clear up state
3690 	 */
3691 	un->un_laststate = un->un_state;
3692 	un->un_state = ST_STATE_CLOSED;
3693 	un->un_lastop = ST_OP_NIL;
3694 	un->un_throttle = 1;	/* assume one request at time, for now */
3695 	un->un_retry_ct = 0;
3696 	un->un_errno = 0;
3697 	un->un_swr_token = (opaque_t)NULL;
3698 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3699 
3700 	/* Restore the options to the init time settings */
3701 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3702 		un->un_dp->options |= ST_READ_IGNORE_ILI;
3703 	} else {
3704 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3705 	}
3706 
3707 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3708 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3709 	} else {
3710 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3711 	}
3712 
3713 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3714 		un->un_dp->options |= ST_SHORT_FILEMARKS;
3715 	} else {
3716 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3717 	}
3718 
3719 	ASSERT(mutex_owned(ST_MUTEX));
3720 
3721 	/*
3722 	 * Signal anyone awaiting a close operation to complete.
3723 	 */
3724 	cv_signal(&un->un_clscv);
3725 
3726 	/*
3727 	 * any kind of error on closing causes all state to be tossed
3728 	 */
3729 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3730 		/*
3731 		 * note that st_intr has already set
3732 		 * un_pos.pmode to invalid.
3733 		 */
3734 		un->un_density_known = 0;
3735 	}
3736 
3737 #ifdef	__x86
3738 	/*
3739 	 * free any contiguous mem alloc'ed for big block I/O
3740 	 */
3741 	cp = un->un_contig_mem;
3742 	while (cp) {
3743 		if (cp->cm_addr) {
3744 			ddi_dma_mem_free(&cp->cm_acc_hdl);
3745 		}
3746 		cp_temp = cp;
3747 		cp = cp->cm_next;
3748 		kmem_free(cp_temp,
3749 		    sizeof (struct contig_mem) + biosize());
3750 	}
3751 	un->un_contig_mem_total_num = 0;
3752 	un->un_contig_mem_available_num = 0;
3753 	un->un_contig_mem = NULL;
3754 	un->un_max_contig_mem_len = 0;
3755 #endif
3756 
3757 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3758 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3759 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3760 
3761 	mutex_exit(ST_MUTEX);
3762 	return (err);
3763 }
3764 
3765 /*
3766  * These routines perform raw i/o operations.
3767  */
3768 
3769 /* ARGSUSED2 */
3770 static int
3771 st_aread(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_aread);
3776 #endif
3777 	return (st_arw(dev, aio, B_READ));
3778 }
3779 
3780 
3781 /* ARGSUSED2 */
3782 static int
3783 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3784 {
3785 #ifdef STDEBUG
3786 	GET_SOFT_STATE(dev);
3787 	ST_ENTR(ST_DEVINFO, st_awrite);
3788 #endif
3789 	return (st_arw(dev, aio, B_WRITE));
3790 }
3791 
3792 
3793 
3794 /* ARGSUSED */
3795 static int
3796 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3797 {
3798 #ifdef STDEBUG
3799 	GET_SOFT_STATE(dev);
3800 	ST_ENTR(ST_DEVINFO, st_read);
3801 #endif
3802 	return (st_rw(dev, uiop, B_READ));
3803 }
3804 
3805 /* ARGSUSED */
3806 static int
3807 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3808 {
3809 #ifdef STDEBUG
3810 	GET_SOFT_STATE(dev);
3811 	ST_ENTR(ST_DEVINFO, st_write);
3812 #endif
3813 	return (st_rw(dev, uiop, B_WRITE));
3814 }
3815 
3816 /*
3817  * Due to historical reasons, old limits are: For variable-length devices:
3818  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3819  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3820  * (let it through unmodified. For fixed-length record devices:
3821  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3822  *
3823  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3824  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3825  * command to the drive).
3826  *
3827  */
3828 static void
3829 st_minphys(struct buf *bp)
3830 {
3831 	struct scsi_tape *un;
3832 
3833 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3834 
3835 	ST_FUNC(ST_DEVINFO, st_minphys);
3836 
3837 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3838 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3839 	    bp->b_bcount);
3840 
3841 	if (un->un_allow_large_xfer) {
3842 
3843 		/*
3844 		 * check un_maxbsize for variable length devices only
3845 		 */
3846 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3847 			bp->b_bcount = un->un_maxbsize;
3848 		}
3849 		/*
3850 		 * can't go more that HBA maxdma limit in either fixed-length
3851 		 * or variable-length tape drives.
3852 		 */
3853 		if (bp->b_bcount > un->un_maxdma) {
3854 			bp->b_bcount = un->un_maxdma;
3855 		}
3856 	} else {
3857 
3858 		/*
3859 		 *  use old fixed limits
3860 		 */
3861 		if (un->un_bsize == 0) {
3862 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3863 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3864 			}
3865 		} else {
3866 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3867 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3868 			}
3869 		}
3870 	}
3871 
3872 	/*
3873 	 * For regular raw I/O and Fixed Block length devices, make sure
3874 	 * the adjusted block count is a whole multiple of the device
3875 	 * block size.
3876 	 */
3877 	if (bp != un->un_sbufp && un->un_bsize) {
3878 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3879 	}
3880 }
3881 
3882 static int
3883 st_rw(dev_t dev, struct uio *uio, int flag)
3884 {
3885 	int rval = 0;
3886 	long len;
3887 
3888 	GET_SOFT_STATE(dev);
3889 
3890 	ST_FUNC(ST_DEVINFO, st_rw);
3891 
3892 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3893 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3894 	    (flag == B_READ ? rd_str: wr_str));
3895 
3896 	/* get local copy of transfer length */
3897 	len = uio->uio_iov->iov_len;
3898 
3899 	mutex_enter(ST_MUTEX);
3900 
3901 	/*
3902 	 * Clear error entry stack
3903 	 */
3904 	st_empty_error_stack(un);
3905 
3906 	/*
3907 	 * If in fixed block size mode and requested read or write
3908 	 * is not an even multiple of that block size.
3909 	 */
3910 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3911 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3912 		    "%s: not modulo %d block size\n",
3913 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3914 		rval = EINVAL;
3915 	}
3916 
3917 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3918 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3919 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3920 		    "%s: not modulo %d device granularity\n",
3921 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3922 		rval = EINVAL;
3923 	}
3924 
3925 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
3926 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
3927 		rval = EFAULT;
3928 	}
3929 
3930 	if (rval != 0) {
3931 		un->un_errno = rval;
3932 		mutex_exit(ST_MUTEX);
3933 		return (rval);
3934 	}
3935 
3936 	/*
3937 	 * Reset this so it can be set if Berkeley and read over a filemark.
3938 	 */
3939 	un->un_silent_skip = 0;
3940 	mutex_exit(ST_MUTEX);
3941 
3942 	len = uio->uio_resid;
3943 
3944 	rval = physio(st_queued_strategy, (struct buf *)NULL,
3945 	    dev, flag, st_minphys, uio);
3946 	/*
3947 	 * if we have hit logical EOT during this xfer and there is not a
3948 	 * full residue, then set eof back  to ST_EOM to make sure that
3949 	 * the user will see at least one zero write
3950 	 * after this short write
3951 	 */
3952 	mutex_enter(ST_MUTEX);
3953 	if (un->un_pos.eof > ST_NO_EOF) {
3954 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3955 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3956 	}
3957 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3958 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3959 			un->un_pos.eof = ST_EOM;
3960 		} else if (uio->uio_resid == len) {
3961 			un->un_pos.eof = ST_NO_EOF;
3962 		}
3963 	}
3964 
3965 	if (un->un_silent_skip && uio->uio_resid != len) {
3966 		un->un_pos.eof = ST_EOF;
3967 		un->un_pos.blkno = un->un_save_blkno;
3968 		un->un_pos.fileno--;
3969 	}
3970 
3971 	un->un_errno = rval;
3972 
3973 	mutex_exit(ST_MUTEX);
3974 
3975 	return (rval);
3976 }
3977 
3978 static int
3979 st_arw(dev_t dev, struct aio_req *aio, int flag)
3980 {
3981 	struct uio *uio = aio->aio_uio;
3982 	int rval = 0;
3983 	long len;
3984 
3985 	GET_SOFT_STATE(dev);
3986 
3987 	ST_FUNC(ST_DEVINFO, st_arw);
3988 
3989 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3990 	    "st_arw(dev = 0x%lx, flag = %s)\n", dev,
3991 	    (flag == B_READ ? rd_str: wr_str));
3992 
3993 	/* get local copy of transfer length */
3994 	len = uio->uio_iov->iov_len;
3995 
3996 	mutex_enter(ST_MUTEX);
3997 
3998 	/*
3999 	 * If in fixed block size mode and requested read or write
4000 	 * is not an even multiple of that block size.
4001 	 */
4002 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
4003 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4004 		    "%s: not modulo %d block size\n",
4005 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
4006 		rval = EINVAL;
4007 	}
4008 
4009 	/* If device has set granularity in the READ_BLKLIM we honor it. */
4010 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
4011 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4012 		    "%s: not modulo %d device granularity\n",
4013 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
4014 		rval = EINVAL;
4015 	}
4016 
4017 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
4018 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
4019 		rval = EFAULT;
4020 	}
4021 
4022 	if (rval != 0) {
4023 		un->un_errno = rval;
4024 		mutex_exit(ST_MUTEX);
4025 		return (rval);
4026 	}
4027 
4028 	mutex_exit(ST_MUTEX);
4029 
4030 	len = uio->uio_resid;
4031 
4032 	rval =
4033 	    aphysio(st_queued_strategy, anocancel, dev, flag, st_minphys, aio);
4034 
4035 	/*
4036 	 * if we have hit logical EOT during this xfer and there is not a
4037 	 * full residue, then set eof back  to ST_EOM to make sure that
4038 	 * the user will see at least one zero write
4039 	 * after this short write
4040 	 *
4041 	 * we keep this here just in case the application is not using
4042 	 * persistent errors
4043 	 */
4044 	mutex_enter(ST_MUTEX);
4045 	if (un->un_pos.eof > ST_NO_EOF) {
4046 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4047 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
4048 	}
4049 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
4050 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
4051 			un->un_pos.eof = ST_EOM;
4052 		} else if (uio->uio_resid == len &&
4053 		    !(un->un_persistence && un->un_persist_errors)) {
4054 			un->un_pos.eof = ST_NO_EOF;
4055 		}
4056 	}
4057 	un->un_errno = rval;
4058 	mutex_exit(ST_MUTEX);
4059 
4060 	return (rval);
4061 }
4062 
4063 
4064 
4065 static int
4066 st_queued_strategy(buf_t *bp)
4067 {
4068 	struct scsi_tape *un;
4069 	char reading = bp->b_flags & B_READ;
4070 	int wasopening = 0;
4071 
4072 	/*
4073 	 * validate arguments
4074 	 */
4075 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4076 	if (un == NULL) {
4077 		bp->b_resid = bp->b_bcount;
4078 		bioerror(bp, ENXIO);
4079 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4080 		    "st_queued_strategy: ENXIO error exit\n");
4081 		biodone(bp);
4082 		return (0);
4083 	}
4084 
4085 	ST_ENTR(ST_DEVINFO, st_queued_strategy);
4086 
4087 	mutex_enter(ST_MUTEX);
4088 
4089 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4090 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4091 	}
4092 
4093 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4094 	    "st_queued_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4095 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4096 
4097 	/*
4098 	 * If persistent errors have been flagged, just nix this one. We wait
4099 	 * for any outstanding I/O's below, so we will be in order.
4100 	 */
4101 	if (un->un_persistence && un->un_persist_errors) {
4102 		goto exit;
4103 	}
4104 
4105 	/*
4106 	 * If last command was non queued, wait till it finishes.
4107 	 */
4108 	while (un->un_sbuf_busy) {
4109 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
4110 		/* woke up because of an error */
4111 		if (un->un_persistence && un->un_persist_errors) {
4112 			goto exit;
4113 		}
4114 	}
4115 
4116 	/*
4117 	 * s_buf and recovery commands shouldn't come here.
4118 	 */
4119 	ASSERT(bp != un->un_recov_buf);
4120 	ASSERT(bp != un->un_sbufp);
4121 
4122 	/*
4123 	 * If we haven't done/checked reservation on the tape unit
4124 	 * do it now.
4125 	 */
4126 	if ((un->un_rsvd_status &
4127 	    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
4128 		if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
4129 			if (st_reserve_release(un, ST_RESERVE, st_uscsi_cmd)) {
4130 				st_bioerror(bp, un->un_errno);
4131 				goto exit;
4132 			}
4133 		} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4134 			/*
4135 			 * Enter here to restore position for possible
4136 			 * resets when the device was closed and opened
4137 			 * in O_NDELAY mode subsequently
4138 			 */
4139 			un->un_state = ST_STATE_INITIALIZING;
4140 			(void) st_cmd(un, SCMD_TEST_UNIT_READY,
4141 			    0, SYNC_CMD);
4142 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4143 		}
4144 		un->un_rsvd_status |= ST_INIT_RESERVE;
4145 	}
4146 
4147 	/*
4148 	 * If we are offline, we have to initialize everything first.
4149 	 * This is to handle either when opened with O_NDELAY, or
4150 	 * we just got a new tape in the drive, after an offline.
4151 	 * We don't observe O_NDELAY past the open,
4152 	 * as it will not make sense for tapes.
4153 	 */
4154 	if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
4155 		/*
4156 		 * reset state to avoid recursion
4157 		 */
4158 		un->un_laststate = un->un_state;
4159 		un->un_state = ST_STATE_INITIALIZING;
4160 		if (st_tape_init(un)) {
4161 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4162 			    "stioctl : OFFLINE init failure ");
4163 			un->un_state = ST_STATE_OFFLINE;
4164 			un->un_pos.pmode = invalid;
4165 			goto b_done_err;
4166 		}
4167 		/* un_restore_pos make invalid */
4168 		un->un_state = ST_STATE_OPEN_PENDING_IO;
4169 		un->un_restore_pos = 0;
4170 	}
4171 	/*
4172 	 * Check for legal operations
4173 	 */
4174 	if (un->un_pos.pmode == invalid) {
4175 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4176 		    "strategy with un->un_pos.pmode invalid\n");
4177 		goto b_done_err;
4178 	}
4179 
4180 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4181 	    "st_queued_strategy(): regular io\n");
4182 
4183 	/*
4184 	 * Process this first. If we were reading, and we're pending
4185 	 * logical eot, that means we've bumped one file mark too far.
4186 	 */
4187 
4188 	/*
4189 	 * Recursion warning: st_cmd will route back through here.
4190 	 * Not anymore st_cmd will go through st_strategy()!
4191 	 */
4192 	if (un->un_pos.eof == ST_EOT_PENDING) {
4193 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4194 			un->un_pos.pmode = invalid;
4195 			un->un_density_known = 0;
4196 			goto b_done_err;
4197 		}
4198 		un->un_pos.blkno = 0; /* fix up block number.. */
4199 		un->un_pos.eof = ST_EOT;
4200 	}
4201 
4202 	/*
4203 	 * If we are in the process of opening, we may have to
4204 	 * determine/set the correct density. We also may have
4205 	 * to do a test_append (if QIC) to see whether we are
4206 	 * in a position to append to the end of the tape.
4207 	 *
4208 	 * If we're already at logical eot, we transition
4209 	 * to ST_NO_EOF. If we're at physical eot, we punt
4210 	 * to the switch statement below to handle.
4211 	 */
4212 	if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
4213 	    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
4214 
4215 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4216 			if (st_determine_density(un, (int)reading)) {
4217 				goto b_done_err;
4218 			}
4219 		}
4220 
4221 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4222 		    "pending_io@fileno %d rw %d qic %d eof %d\n",
4223 		    un->un_pos.fileno, (int)reading,
4224 		    (un->un_dp->options & ST_QIC) ? 1 : 0,
4225 		    un->un_pos.eof);
4226 
4227 		if (!reading && un->un_pos.eof != ST_EOM) {
4228 			if (un->un_pos.eof == ST_EOT) {
4229 				un->un_pos.eof = ST_NO_EOF;
4230 			} else if (un->un_pos.pmode != invalid &&
4231 			    (un->un_dp->options & ST_QIC)) {
4232 				/*
4233 				 * st_test_append() will do it all
4234 				 */
4235 				st_test_append(bp);
4236 				mutex_exit(ST_MUTEX);
4237 				return (0);
4238 			}
4239 		}
4240 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4241 			wasopening = 1;
4242 		}
4243 		un->un_laststate = un->un_state;
4244 		un->un_state = ST_STATE_OPEN;
4245 	}
4246 
4247 
4248 	/*
4249 	 * Process rest of END OF FILE and END OF TAPE conditions
4250 	 */
4251 
4252 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4253 	    "eof=%x, wasopening=%x\n",
4254 	    un->un_pos.eof, wasopening);
4255 
4256 	switch (un->un_pos.eof) {
4257 	case ST_EOM:
4258 		/*
4259 		 * This allows writes to proceed past physical
4260 		 * eot. We'll *really* be in trouble if the
4261 		 * user continues blindly writing data too
4262 		 * much past this point (unwind the tape).
4263 		 * Physical eot really means 'early warning
4264 		 * eot' in this context.
4265 		 *
4266 		 * Every other write from now on will succeed
4267 		 * (if sufficient  tape left).
4268 		 * This write will return with resid == count
4269 		 * but the next one should be successful
4270 		 *
4271 		 * Note that we only transition to logical EOT
4272 		 * if the last state wasn't the OPENING state.
4273 		 * We explicitly prohibit running up to physical
4274 		 * eot, closing the device, and then re-opening
4275 		 * to proceed. Trailer records may only be gotten
4276 		 * at by keeping the tape open after hitting eot.
4277 		 *
4278 		 * Also note that ST_EOM cannot be set by reading-
4279 		 * this can only be set during writing. Reading
4280 		 * up to the end of the tape gets a blank check
4281 		 * or a double-filemark indication (ST_EOT_PENDING),
4282 		 * and we prohibit reading after that point.
4283 		 *
4284 		 */
4285 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
4286 		if (wasopening == 0) {
4287 			/*
4288 			 * this allows st_rw() to reset it back to
4289 			 * will see a zero write
4290 			 */
4291 			un->un_pos.eof = ST_WRITE_AFTER_EOM;
4292 		}
4293 		un->un_status = SUN_KEY_EOT;
4294 		goto b_done;
4295 
4296 	case ST_WRITE_AFTER_EOM:
4297 	case ST_EOT:
4298 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
4299 		un->un_status = SUN_KEY_EOT;
4300 		if (SVR4_BEHAVIOR && reading) {
4301 			goto b_done_err;
4302 		}
4303 
4304 		if (reading) {
4305 			goto b_done;
4306 		}
4307 		un->un_pos.eof = ST_NO_EOF;
4308 		break;
4309 
4310 	case ST_EOF_PENDING:
4311 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4312 		    "EOF PENDING\n");
4313 		un->un_status = SUN_KEY_EOF;
4314 		if (SVR4_BEHAVIOR) {
4315 			un->un_pos.eof = ST_EOF;
4316 			goto b_done;
4317 		}
4318 		/* FALLTHROUGH */
4319 	case ST_EOF:
4320 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
4321 		un->un_status = SUN_KEY_EOF;
4322 		if (SVR4_BEHAVIOR) {
4323 			goto b_done_err;
4324 		}
4325 
4326 		if (BSD_BEHAVIOR) {
4327 			un->un_pos.eof = ST_NO_EOF;
4328 			un->un_pos.fileno += 1;
4329 			un->un_pos.blkno   = 0;
4330 		}
4331 
4332 		if (reading) {
4333 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4334 			    "now file %d (read)\n",
4335 			    un->un_pos.fileno);
4336 			goto b_done;
4337 		}
4338 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4339 		    "now file %d (write)\n", un->un_pos.fileno);
4340 		break;
4341 	default:
4342 		un->un_status = 0;
4343 		break;
4344 	}
4345 
4346 	bp->b_flags &= ~(B_DONE);
4347 	st_bioerror(bp, 0);
4348 	bp->av_forw = NULL;
4349 	bp->b_resid = 0;
4350 	SET_BP_PKT(bp, 0);
4351 
4352 
4353 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4354 	    "st_queued_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4355 	    " pkt=0x%p\n",
4356 	    (void *)bp->b_forw, bp->b_bcount,
4357 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4358 
4359 #ifdef	__x86
4360 	/*
4361 	 * We will replace bp with a new bp that can do big blk xfer
4362 	 * if the requested xfer size is bigger than un->un_maxdma_arch
4363 	 *
4364 	 * Also, we need to make sure that we're handling real I/O
4365 	 * by checking group 0/1 SCSI I/O commands, if needed
4366 	 */
4367 	if (bp->b_bcount > un->un_maxdma_arch &&
4368 	    ((uchar_t)(uintptr_t)bp->b_forw == SCMD_READ ||
4369 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G4 ||
4370 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE ||
4371 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G4)) {
4372 		mutex_exit(ST_MUTEX);
4373 		bp = st_get_bigblk_bp(bp);
4374 		mutex_enter(ST_MUTEX);
4375 	}
4376 #endif
4377 
4378 	/* put on wait queue */
4379 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4380 	    "st_queued_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4381 	    (void *)un->un_quef, (void *)bp);
4382 
4383 	st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quel, bp);
4384 
4385 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4386 
4387 	st_start(un);
4388 
4389 	mutex_exit(ST_MUTEX);
4390 	return (0);
4391 
4392 b_done_err:
4393 	st_bioerror(bp, EIO);
4394 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4395 	    "st_queued_strategy : EIO b_done_err\n");
4396 
4397 b_done:
4398 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4399 	    "st_queued_strategy: b_done\n");
4400 
4401 exit:
4402 	/*
4403 	 * make sure no commands are outstanding or waiting before closing,
4404 	 * so we can guarantee order
4405 	 */
4406 	st_wait_for_io(un);
4407 	un->un_err_resid = bp->b_resid = bp->b_bcount;
4408 
4409 	/* override errno here, if persistent errors were flagged */
4410 	if (un->un_persistence && un->un_persist_errors)
4411 		bioerror(bp, un->un_errno);
4412 
4413 	mutex_exit(ST_MUTEX);
4414 
4415 	biodone(bp);
4416 	ASSERT(mutex_owned(ST_MUTEX) == 0);
4417 	return (0);
4418 }
4419 
4420 
4421 static int
4422 st_strategy(struct buf *bp)
4423 {
4424 	struct scsi_tape *un;
4425 
4426 	/*
4427 	 * validate arguments
4428 	 */
4429 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4430 	if (un == NULL) {
4431 		bp->b_resid = bp->b_bcount;
4432 		bioerror(bp, ENXIO);
4433 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4434 		    "st_strategy: ENXIO error exit\n");
4435 
4436 		biodone(bp);
4437 		return (0);
4438 
4439 	}
4440 
4441 	ST_ENTR(ST_DEVINFO, st_strategy);
4442 
4443 	mutex_enter(ST_MUTEX);
4444 
4445 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4446 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4447 	}
4448 
4449 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4450 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4451 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4452 
4453 	ASSERT((bp == un->un_recov_buf) || (bp == un->un_sbufp));
4454 
4455 	bp->b_flags &= ~(B_DONE);
4456 	st_bioerror(bp, 0);
4457 	bp->av_forw = NULL;
4458 	bp->b_resid = 0;
4459 	SET_BP_PKT(bp, 0);
4460 
4461 
4462 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4463 	    "st_strategy: cmd=0x%x  count=%ld  resid=%ld flags=0x%x"
4464 	    " pkt=0x%p\n",
4465 	    (unsigned char)(uintptr_t)bp->b_forw, bp->b_bcount,
4466 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4467 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4468 
4469 	st_start(un);
4470 
4471 	mutex_exit(ST_MUTEX);
4472 	return (0);
4473 }
4474 
4475 /*
4476  * this routine spaces forward over filemarks
4477  */
4478 static int
4479 st_space_fmks(struct scsi_tape *un, int64_t count)
4480 {
4481 	int rval = 0;
4482 
4483 	ST_FUNC(ST_DEVINFO, st_space_fmks);
4484 
4485 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4486 	    "st_space_fmks(dev = 0x%lx, count = %"PRIx64")\n",
4487 	    un->un_dev, count);
4488 
4489 	ASSERT(mutex_owned(ST_MUTEX));
4490 
4491 	/*
4492 	 * the risk with doing only one space operation is that we
4493 	 * may accidentily jump in old data
4494 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4495 	 * because the 8200 does not append a marker; in order not to
4496 	 * sacrifice the fast file skip, we do a slow skip if the low
4497 	 * density device has been opened
4498 	 */
4499 
4500 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4501 	    !((un->un_dp->type == ST_TYPE_EXB8500 &&
4502 	    MT_DENSITY(un->un_dev) == 0))) {
4503 		if (st_cmd(un, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4504 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4505 			    "space_fmks : EIO can't do space cmd #1\n");
4506 			rval = EIO;
4507 		}
4508 	} else {
4509 		while (count > 0) {
4510 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4511 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4512 				    "space_fmks : EIO can't do space cmd #2\n");
4513 				rval = EIO;
4514 				break;
4515 			}
4516 			count -= 1;
4517 			/*
4518 			 * read a block to see if we have reached
4519 			 * end of medium (double filemark for reel or
4520 			 * medium error for others)
4521 			 */
4522 			if (count > 0) {
4523 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
4524 					ST_DEBUG2(ST_DEVINFO, st_label,
4525 					    SCSI_DEBUG,
4526 					    "space_fmks : EIO can't do "
4527 					    "space cmd #3\n");
4528 					rval = EIO;
4529 					break;
4530 				}
4531 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4532 				    (un->un_dp->options & ST_REEL)) {
4533 					un->un_status = SUN_KEY_EOT;
4534 					ST_DEBUG2(ST_DEVINFO, st_label,
4535 					    SCSI_DEBUG,
4536 					    "space_fmks : EIO ST_REEL\n");
4537 					rval = EIO;
4538 					break;
4539 				} else if (IN_EOF(un->un_pos)) {
4540 					un->un_pos.eof = ST_NO_EOF;
4541 					un->un_pos.fileno++;
4542 					un->un_pos.blkno = 0;
4543 					count--;
4544 				} else if (un->un_pos.eof > ST_EOF) {
4545 					ST_DEBUG2(ST_DEVINFO, st_label,
4546 					    SCSI_DEBUG,
4547 					    "space_fmks, EIO > ST_EOF\n");
4548 					rval = EIO;
4549 					break;
4550 				}
4551 
4552 			}
4553 		}
4554 		un->un_err_resid = count;
4555 		COPY_POS(&un->un_pos, &un->un_err_pos);
4556 	}
4557 	ASSERT(mutex_owned(ST_MUTEX));
4558 	return (rval);
4559 }
4560 
4561 /*
4562  * this routine spaces to EOD
4563  *
4564  * it keeps track of the current filenumber and returns the filenumber after
4565  * the last successful space operation, we keep the number high because as
4566  * tapes are getting larger, the possibility of more and more files exist,
4567  * 0x100000 (1 Meg of files) probably will never have to be changed any time
4568  * soon
4569  */
4570 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4571 
4572 static int
4573 st_find_eod(struct scsi_tape *un)
4574 {
4575 	tapepos_t savepos;
4576 	int64_t sp_type;
4577 	int result;
4578 
4579 	if (un == NULL) {
4580 		return (-1);
4581 	}
4582 
4583 	ST_FUNC(ST_DEVINFO, st_find_eod);
4584 
4585 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4586 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", un->un_dev,
4587 	    un->un_pos.fileno);
4588 
4589 	ASSERT(mutex_owned(ST_MUTEX));
4590 
4591 	COPY_POS(&savepos, &un->un_pos);
4592 
4593 	/*
4594 	 * see if the drive is smart enough to do the skips in
4595 	 * one operation; 1/2" use two filemarks
4596 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4597 	 * because the 8200 does not append a marker; in order not to
4598 	 * sacrifice the fast file skip, we do a slow skip if the low
4599 	 * density device has been opened
4600 	 */
4601 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4602 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4603 		    (MT_DENSITY(un->un_dev) == 0)) {
4604 			sp_type = Fmk(1);
4605 		} else if (un->un_pos.pmode == logical) {
4606 			sp_type = SPACE(SP_EOD, 0);
4607 		} else {
4608 			sp_type = Fmk(MAX_SKIP);
4609 		}
4610 	} else {
4611 		sp_type = Fmk(1);
4612 	}
4613 
4614 	for (;;) {
4615 		result = st_cmd(un, SCMD_SPACE, sp_type, SYNC_CMD);
4616 
4617 		if (result == 0) {
4618 			COPY_POS(&savepos, &un->un_pos);
4619 		}
4620 
4621 		if (sp_type == SPACE(SP_EOD, 0)) {
4622 			if (result != 0) {
4623 				sp_type = Fmk(MAX_SKIP);
4624 				continue;
4625 			}
4626 
4627 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4628 			    "st_find_eod: 0x%"PRIx64"\n",
4629 			    savepos.lgclblkno);
4630 			/*
4631 			 * What we return will become the current file position.
4632 			 * After completing the space command with the position
4633 			 * mode that is not invalid a read position command will
4634 			 * be automaticly issued. If the drive support the long
4635 			 * read position format a valid file position can be
4636 			 * returned.
4637 			 */
4638 			return (un->un_pos.fileno);
4639 		}
4640 
4641 		if (result != 0) {
4642 			break;
4643 		}
4644 
4645 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4646 		    "count=%"PRIx64", eof=%x, status=%x\n",
4647 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4648 
4649 		/*
4650 		 * If we're not EOM smart,  space a record
4651 		 * to see whether we're now in the slot between
4652 		 * the two sequential filemarks that logical
4653 		 * EOM consists of (REEL) or hit nowhere land
4654 		 * (8mm).
4655 		 */
4656 		if (sp_type == Fmk(1)) {
4657 			/*
4658 			 * no fast skipping, check a record
4659 			 */
4660 			if (st_cmd(un, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4661 				break;
4662 			}
4663 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4664 			    (un->un_dp->options & ST_REEL)) {
4665 				un->un_status = KEY_BLANK_CHECK;
4666 				un->un_pos.fileno++;
4667 				un->un_pos.blkno = 0;
4668 				break;
4669 			}
4670 			if (IN_EOF(un->un_pos)) {
4671 				un->un_pos.eof = ST_NO_EOF;
4672 				un->un_pos.fileno++;
4673 				un->un_pos.blkno = 0;
4674 			}
4675 			if (un->un_pos.eof > ST_EOF) {
4676 				break;
4677 			}
4678 		} else {
4679 			if (un->un_pos.eof > ST_EOF) {
4680 				break;
4681 			}
4682 		}
4683 	}
4684 
4685 	if (un->un_dp->options & ST_KNOWS_EOD) {
4686 		COPY_POS(&savepos, &un->un_pos);
4687 	}
4688 
4689 	ASSERT(mutex_owned(ST_MUTEX));
4690 
4691 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4692 	    "st_find_eod: %x\n", savepos.fileno);
4693 	return (savepos.fileno);
4694 }
4695 
4696 
4697 /*
4698  * this routine is frequently used in ioctls below;
4699  * it determines whether we know the density and if not will
4700  * determine it
4701  * if we have written the tape before, one or more filemarks are written
4702  *
4703  * depending on the stepflag, the head is repositioned to where it was before
4704  * the filemarks were written in order not to confuse step counts
4705  */
4706 #define	STEPBACK    0
4707 #define	NO_STEPBACK 1
4708 
4709 static int
4710 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4711 {
4712 
4713 	GET_SOFT_STATE(dev);
4714 
4715 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4716 
4717 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4718 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4719 	    "\n", dev, wfm, mode, stepflag);
4720 
4721 	ASSERT(mutex_owned(ST_MUTEX));
4722 
4723 	/*
4724 	 * If we don't yet know the density of the tape we have inserted,
4725 	 * we have to either unconditionally set it (if we're 'writing'),
4726 	 * or we have to determine it. As side effects, check for any
4727 	 * write-protect errors, and for the need to put out any file-marks
4728 	 * before positioning a tape.
4729 	 *
4730 	 * If we are going to be spacing forward, and we haven't determined
4731 	 * the tape density yet, we have to do so now...
4732 	 */
4733 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4734 		if (st_determine_density(un, mode)) {
4735 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4736 			    "check_density_or_wfm : EIO can't determine "
4737 			    "density\n");
4738 			un->un_errno = EIO;
4739 			return (EIO);
4740 		}
4741 		/*
4742 		 * Presumably we are at BOT. If we attempt to write, it will
4743 		 * either work okay, or bomb. We don't do a st_test_append
4744 		 * unless we're past BOT.
4745 		 */
4746 		un->un_laststate = un->un_state;
4747 		un->un_state = ST_STATE_OPEN;
4748 
4749 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4750 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4751 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4752 
4753 		tapepos_t spos;
4754 
4755 		COPY_POS(&spos, &un->un_pos);
4756 
4757 		/*
4758 		 * We need to write one or two filemarks.
4759 		 * In the case of the HP, we need to
4760 		 * position the head between the two
4761 		 * marks.
4762 		 */
4763 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4764 			wfm = un->un_fmneeded;
4765 			un->un_fmneeded = 0;
4766 		}
4767 
4768 		if (st_write_fm(dev, wfm)) {
4769 			un->un_pos.pmode = invalid;
4770 			un->un_density_known = 0;
4771 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4772 			    "check_density_or_wfm : EIO can't write fm\n");
4773 			un->un_errno = EIO;
4774 			return (EIO);
4775 		}
4776 
4777 		if (stepflag == STEPBACK) {
4778 			if (st_cmd(un, SCMD_SPACE, Fmk(-wfm), SYNC_CMD)) {
4779 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4780 				    "check_density_or_wfm : EIO can't space "
4781 				    "(-wfm)\n");
4782 				un->un_errno = EIO;
4783 				return (EIO);
4784 			}
4785 			COPY_POS(&un->un_pos, &spos);
4786 		}
4787 	}
4788 
4789 	/*
4790 	 * Whatever we do at this point clears the state of the eof flag.
4791 	 */
4792 
4793 	un->un_pos.eof = ST_NO_EOF;
4794 
4795 	/*
4796 	 * If writing, let's check that we're positioned correctly
4797 	 * at the end of tape before issuing the next write.
4798 	 */
4799 	if (un->un_read_only == RDWR) {
4800 		un->un_test_append = 1;
4801 	}
4802 
4803 	ASSERT(mutex_owned(ST_MUTEX));
4804 	return (0);
4805 }
4806 
4807 
4808 /*
4809  * Wait for all outstaning I/O's to complete
4810  *
4811  * we wait on both ncmds and the wait queue for times when we are flushing
4812  * after persistent errors are flagged, which is when ncmds can be 0, and the
4813  * queue can still have I/O's.  This way we preserve order of biodone's.
4814  */
4815 static void
4816 st_wait_for_io(struct scsi_tape *un)
4817 {
4818 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4819 	ASSERT(mutex_owned(ST_MUTEX));
4820 	while ((un->un_ncmds) || (un->un_quef) || (un->un_runqf)) {
4821 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4822 	}
4823 }
4824 
4825 /*
4826  * This routine implements the ioctl calls.  It is called
4827  * from the device switch at normal priority.
4828  */
4829 /*ARGSUSED*/
4830 static int
4831 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4832     int *rval_p)
4833 {
4834 	int tmp, rval = 0;
4835 
4836 	GET_SOFT_STATE(dev);
4837 
4838 	ST_ENTR(ST_DEVINFO, st_ioctl);
4839 
4840 	mutex_enter(ST_MUTEX);
4841 
4842 	ASSERT(un->un_recov_buf_busy == 0);
4843 
4844 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4845 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4846 	    "pe_flag = %d\n",
4847 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4848 	    un->un_persistence && un->un_persist_errors);
4849 
4850 	/*
4851 	 * We don't want to block on these, so let them through
4852 	 * and we don't care about setting driver states here.
4853 	 */
4854 	if ((cmd == MTIOCGETDRIVETYPE) ||
4855 	    (cmd == MTIOCGUARANTEEDORDER) ||
4856 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4857 		goto check_commands;
4858 	}
4859 
4860 	/*
4861 	 * We clear error entry stack except command
4862 	 * MTIOCGETERROR and MTIOCGET
4863 	 */
4864 	if ((cmd != MTIOCGETERROR) &&
4865 	    (cmd != MTIOCGET)) {
4866 		st_empty_error_stack(un);
4867 	}
4868 
4869 	/*
4870 	 * wait for all outstanding commands to complete, or be dequeued.
4871 	 * And because ioctl's are synchronous commands, any return value
4872 	 * after this,  will be in order
4873 	 */
4874 	st_wait_for_io(un);
4875 
4876 	/*
4877 	 * allow only a through clear errors and persistent status, and
4878 	 * status
4879 	 */
4880 	if (un->un_persistence && un->un_persist_errors) {
4881 		if ((cmd == MTIOCLRERR) ||
4882 		    (cmd == MTIOCPERSISTENT) ||
4883 		    (cmd == MTIOCGET)) {
4884 			goto check_commands;
4885 		} else {
4886 			rval = un->un_errno;
4887 			goto exit;
4888 		}
4889 	}
4890 
4891 	ASSERT(un->un_throttle != 0);
4892 	un->un_throttle = 1;	/* > 1 will never happen here */
4893 	un->un_errno = 0;	/* start clean from here */
4894 
4895 	/*
4896 	 * first and foremost, handle any ST_EOT_PENDING cases.
4897 	 * That is, if a logical eot is pending notice, notice it.
4898 	 */
4899 	if (un->un_pos.eof == ST_EOT_PENDING) {
4900 		int resid = un->un_err_resid;
4901 		uchar_t status = un->un_status;
4902 		uchar_t lastop = un->un_lastop;
4903 
4904 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4905 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4906 			    "stioctl : EIO can't space fmk(-1)\n");
4907 			rval = EIO;
4908 			goto exit;
4909 		}
4910 		un->un_lastop = lastop; /* restore last operation */
4911 		if (status == SUN_KEY_EOF) {
4912 			un->un_status = SUN_KEY_EOT;
4913 		} else {
4914 			un->un_status = status;
4915 		}
4916 		un->un_err_resid  = resid;
4917 		/* fix up block number */
4918 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4919 		/* now we're at logical eot */
4920 		un->un_pos.eof = ST_EOT;
4921 	}
4922 
4923 	/*
4924 	 * now, handle the rest of the situations
4925 	 */
4926 check_commands:
4927 	switch (cmd) {
4928 	case MTIOCGET:
4929 	{
4930 #ifdef _MULTI_DATAMODEL
4931 		/*
4932 		 * For use when a 32 bit app makes a call into a
4933 		 * 64 bit ioctl
4934 		 */
4935 		struct mtget32		mtg_local32;
4936 		struct mtget32 		*mtget_32 = &mtg_local32;
4937 #endif /* _MULTI_DATAMODEL */
4938 
4939 			/* Get tape status */
4940 		struct mtget mtg_local;
4941 		struct mtget *mtget = &mtg_local;
4942 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4943 		    "st_ioctl: MTIOCGET\n");
4944 
4945 		bzero((caddr_t)mtget, sizeof (struct mtget));
4946 		mtget->mt_erreg = un->un_status;
4947 		mtget->mt_resid = un->un_err_resid;
4948 		mtget->mt_dsreg = un->un_retry_ct;
4949 		if (un->un_err_pos.pmode == legacy) {
4950 			mtget->mt_fileno = un->un_err_pos.fileno;
4951 		} else {
4952 			mtget->mt_fileno = -1;
4953 		}
4954 		/*
4955 		 * If the value is positive fine.
4956 		 * If its negative we need to return a value based on the
4957 		 * old way if counting backwards from INF (1,000,000,000).
4958 		 */
4959 		if (un->un_err_pos.blkno >= 0) {
4960 			mtget->mt_blkno = un->un_err_pos.blkno;
4961 		} else {
4962 			mtget->mt_blkno = INF + 1 - (-un->un_err_pos.blkno);
4963 		}
4964 		mtget->mt_type = un->un_dp->type;
4965 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
4966 		if (un->un_read_pos_type != NO_POS) {
4967 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
4968 		}
4969 		if (un->un_dp->options & ST_REEL) {
4970 			mtget->mt_flags |= MTF_REEL;
4971 			mtget->mt_bf = 20;
4972 		} else {		/* 1/4" cartridges */
4973 			switch (mtget->mt_type) {
4974 			/* Emulex cartridge tape */
4975 			case MT_ISMT02:
4976 				mtget->mt_bf = 40;
4977 				break;
4978 			default:
4979 				mtget->mt_bf = 126;
4980 				break;
4981 			}
4982 		}
4983 
4984 		/*
4985 		 * If large transfers are allowed and drive options
4986 		 * has no record size limit set. Calculate blocking
4987 		 * factor from the lesser of maxbsize and maxdma.
4988 		 */
4989 		if ((un->un_allow_large_xfer) &&
4990 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
4991 			mtget->mt_bf = min(un->un_maxbsize,
4992 			    un->un_maxdma) / SECSIZE;
4993 		}
4994 
4995 		if (un->un_read_only == WORM ||
4996 		    un->un_read_only == RDWORM) {
4997 			mtget->mt_flags |= MTF_WORM_MEDIA;
4998 		}
4999 
5000 		/*
5001 		 * In persistent error mode sending a non-queued can hang
5002 		 * because this ioctl gets to be run without turning off
5003 		 * persistense. Fake the answer based on previous info.
5004 		 */
5005 		if (un->un_persistence) {
5006 			rval = 0;
5007 		} else {
5008 			rval = st_check_clean_bit(un);
5009 		}
5010 		if (rval == 0) {
5011 			/*
5012 			 * If zero is returned or in persistent mode,
5013 			 * use the old data.
5014 			 */
5015 			if ((un->un_HeadClean & (TAPE_ALERT_SUPPORTED |
5016 			    TAPE_SEQUENTIAL_SUPPORTED|TAPE_ALERT_NOT_SUPPORTED))
5017 			    != TAPE_ALERT_NOT_SUPPORTED) {
5018 				mtget->mt_flags |= MTF_TAPE_CLN_SUPPORTED;
5019 			}
5020 			if (un->un_HeadClean & (TAPE_PREVIOUSLY_DIRTY |
5021 			    TAPE_ALERT_STILL_DIRTY)) {
5022 				mtget->mt_flags |= MTF_TAPE_HEAD_DIRTY;
5023 			}
5024 		} else {
5025 			mtget->mt_flags |= (ushort_t)rval;
5026 			rval = 0;
5027 		}
5028 
5029 		un->un_status = 0;		/* Reset status */
5030 		un->un_err_resid = 0;
5031 		tmp = sizeof (struct mtget);
5032 
5033 #ifdef _MULTI_DATAMODEL
5034 
5035 		switch (ddi_model_convert_from(flag & FMODELS)) {
5036 		case DDI_MODEL_ILP32:
5037 			/*
5038 			 * Convert 64 bit back to 32 bit before doing
5039 			 * copyout. This is what the ILP32 app expects.
5040 			 */
5041 			mtget_32->mt_erreg = 	mtget->mt_erreg;
5042 			mtget_32->mt_resid = 	mtget->mt_resid;
5043 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
5044 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
5045 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
5046 			mtget_32->mt_type =  	mtget->mt_type;
5047 			mtget_32->mt_flags = 	mtget->mt_flags;
5048 			mtget_32->mt_bf = 	mtget->mt_bf;
5049 
5050 			if (ddi_copyout(mtget_32, (void *)arg,
5051 			    sizeof (struct mtget32), flag)) {
5052 				rval = EFAULT;
5053 			}
5054 			break;
5055 
5056 		case DDI_MODEL_NONE:
5057 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5058 				rval = EFAULT;
5059 			}
5060 			break;
5061 		}
5062 #else /* ! _MULTI_DATAMODE */
5063 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5064 			rval = EFAULT;
5065 		}
5066 #endif /* _MULTI_DATAMODE */
5067 
5068 		break;
5069 	}
5070 	case MTIOCGETERROR:
5071 			/*
5072 			 * get error entry from error stack
5073 			 */
5074 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5075 			    "st_ioctl: MTIOCGETERROR\n");
5076 
5077 			rval = st_get_error_entry(un, arg, flag);
5078 
5079 			break;
5080 
5081 	case MTIOCSTATE:
5082 		{
5083 			/*
5084 			 * return when media presence matches state
5085 			 */
5086 			enum mtio_state state;
5087 
5088 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5089 			    "st_ioctl: MTIOCSTATE\n");
5090 
5091 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
5092 				rval = EFAULT;
5093 
5094 			mutex_exit(ST_MUTEX);
5095 
5096 			rval = st_check_media(dev, state);
5097 
5098 			mutex_enter(ST_MUTEX);
5099 
5100 			if (rval != 0) {
5101 				break;
5102 			}
5103 
5104 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
5105 			    sizeof (int), flag))
5106 				rval = EFAULT;
5107 			break;
5108 
5109 		}
5110 
5111 	case MTIOCGETDRIVETYPE:
5112 		{
5113 #ifdef _MULTI_DATAMODEL
5114 		/*
5115 		 * For use when a 32 bit app makes a call into a
5116 		 * 64 bit ioctl
5117 		 */
5118 		struct mtdrivetype_request32	mtdtrq32;
5119 #endif /* _MULTI_DATAMODEL */
5120 
5121 			/*
5122 			 * return mtdrivetype
5123 			 */
5124 			struct mtdrivetype_request mtdtrq;
5125 			struct mtdrivetype mtdrtyp;
5126 			struct mtdrivetype *mtdt = &mtdrtyp;
5127 			struct st_drivetype *stdt = un->un_dp;
5128 
5129 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5130 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
5131 
5132 #ifdef _MULTI_DATAMODEL
5133 		switch (ddi_model_convert_from(flag & FMODELS)) {
5134 		case DDI_MODEL_ILP32:
5135 		{
5136 			if (ddi_copyin((void *)arg, &mtdtrq32,
5137 			    sizeof (struct mtdrivetype_request32), flag)) {
5138 				rval = EFAULT;
5139 				break;
5140 			}
5141 			mtdtrq.size = mtdtrq32.size;
5142 			mtdtrq.mtdtp =
5143 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
5144 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5145 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
5146 			break;
5147 		}
5148 		case DDI_MODEL_NONE:
5149 			if (ddi_copyin((void *)arg, &mtdtrq,
5150 			    sizeof (struct mtdrivetype_request), flag)) {
5151 				rval = EFAULT;
5152 				break;
5153 			}
5154 			break;
5155 		}
5156 
5157 #else /* ! _MULTI_DATAMODEL */
5158 		if (ddi_copyin((void *)arg, &mtdtrq,
5159 		    sizeof (struct mtdrivetype_request), flag)) {
5160 			rval = EFAULT;
5161 			break;
5162 		}
5163 #endif /* _MULTI_DATAMODEL */
5164 
5165 			/*
5166 			 * if requested size is < 0 then return
5167 			 * error.
5168 			 */
5169 			if (mtdtrq.size < 0) {
5170 				rval = EINVAL;
5171 				break;
5172 			}
5173 			bzero(mtdt, sizeof (struct mtdrivetype));
5174 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
5175 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
5176 			mtdt->type = stdt->type;
5177 			mtdt->bsize = stdt->bsize;
5178 			mtdt->options = stdt->options;
5179 			mtdt->max_rretries = stdt->max_rretries;
5180 			mtdt->max_wretries = stdt->max_wretries;
5181 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5182 				mtdt->densities[tmp] = stdt->densities[tmp];
5183 			}
5184 			mtdt->default_density = stdt->default_density;
5185 			/*
5186 			 * Speed hasn't been used since the hayday of reel tape.
5187 			 * For all drives not setting the option ST_KNOWS_MEDIA
5188 			 * the speed member renamed to mediatype are zeros.
5189 			 * Those drives that have ST_KNOWS_MEDIA set use the
5190 			 * new mediatype member which is used to figure the
5191 			 * type of media loaded.
5192 			 *
5193 			 * So as to not break applications speed in the
5194 			 * mtdrivetype structure is not renamed.
5195 			 */
5196 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5197 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
5198 			}
5199 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
5200 			mtdt->io_timeout = stdt->io_timeout;
5201 			mtdt->rewind_timeout = stdt->rewind_timeout;
5202 			mtdt->space_timeout = stdt->space_timeout;
5203 			mtdt->load_timeout = stdt->load_timeout;
5204 			mtdt->unload_timeout = stdt->unload_timeout;
5205 			mtdt->erase_timeout = stdt->erase_timeout;
5206 
5207 			/*
5208 			 * Limit the maximum length of the result to
5209 			 * sizeof (struct mtdrivetype).
5210 			 */
5211 			tmp = sizeof (struct mtdrivetype);
5212 			if (mtdtrq.size < tmp)
5213 				tmp = mtdtrq.size;
5214 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
5215 				rval = EFAULT;
5216 			}
5217 			break;
5218 		}
5219 	case MTIOCPERSISTENT:
5220 
5221 		if (ddi_copyin((void *)arg, &tmp, sizeof (tmp), flag)) {
5222 			rval = EFAULT;
5223 			break;
5224 		}
5225 
5226 		if (tmp) {
5227 			st_turn_pe_on(un);
5228 		} else {
5229 			st_turn_pe_off(un);
5230 		}
5231 
5232 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5233 		    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
5234 		    un->un_persistence);
5235 
5236 		break;
5237 
5238 	case MTIOCPERSISTENTSTATUS:
5239 		tmp = (int)un->un_persistence;
5240 
5241 		if (ddi_copyout(&tmp, (void *)arg, sizeof (tmp), flag)) {
5242 			rval = EFAULT;
5243 		}
5244 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5245 		    "st_ioctl: MTIOCPERSISTENTSTATUS:persistence = %d\n",
5246 		    un->un_persistence);
5247 
5248 		break;
5249 
5250 	case MTIOCLRERR:
5251 		{
5252 			/* clear persistent errors */
5253 
5254 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5255 			    "st_ioctl: MTIOCLRERR\n");
5256 
5257 			st_clear_pe(un);
5258 
5259 			break;
5260 		}
5261 
5262 	case MTIOCGUARANTEEDORDER:
5263 		{
5264 			/*
5265 			 * this is just a holder to make a valid ioctl and
5266 			 * it won't be in any earlier release
5267 			 */
5268 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5269 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
5270 
5271 			break;
5272 		}
5273 
5274 	case MTIOCRESERVE:
5275 		{
5276 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5277 			    "st_ioctl: MTIOCRESERVE\n");
5278 
5279 			/*
5280 			 * Check if Reserve/Release is supported.
5281 			 */
5282 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5283 				rval = ENOTTY;
5284 				break;
5285 			}
5286 
5287 			rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5288 
5289 			if (rval == 0) {
5290 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
5291 			}
5292 			break;
5293 		}
5294 
5295 	case MTIOCRELEASE:
5296 		{
5297 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5298 			    "st_ioctl: MTIOCRELEASE\n");
5299 
5300 			/*
5301 			 * Check if Reserve/Release is supported.
5302 			 */
5303 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5304 				rval = ENOTTY;
5305 				break;
5306 			}
5307 
5308 			/*
5309 			 * Used to just clear ST_PRESERVE_RESERVE which
5310 			 * made the reservation release at next close.
5311 			 * As the user may have opened and then done a
5312 			 * persistant reservation we now need to drop
5313 			 * the reservation without closing if the user
5314 			 * attempts to do this.
5315 			 */
5316 			rval = st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
5317 
5318 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5319 
5320 			break;
5321 		}
5322 
5323 	case MTIOCFORCERESERVE:
5324 	{
5325 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5326 		    "st_ioctl: MTIOCFORCERESERVE\n");
5327 
5328 		/*
5329 		 * Check if Reserve/Release is supported.
5330 		 */
5331 		if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5332 			rval = ENOTTY;
5333 			break;
5334 		}
5335 		/*
5336 		 * allow only super user to run this.
5337 		 */
5338 		if (drv_priv(cred_p) != 0) {
5339 			rval = EPERM;
5340 			break;
5341 		}
5342 		/*
5343 		 * Throw away reserve,
5344 		 * not using test-unit-ready
5345 		 * since reserve can succeed without tape being
5346 		 * present in the drive.
5347 		 */
5348 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5349 
5350 		rval = st_take_ownership(un, st_uscsi_cmd);
5351 
5352 		break;
5353 	}
5354 
5355 	case USCSICMD:
5356 	{
5357 		cred_t	*cr;
5358 
5359 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5360 		    "st_ioctl: USCSICMD\n");
5361 
5362 		cr = ddi_get_cred();
5363 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5364 			rval = EPERM;
5365 		} else {
5366 			rval = st_uscsi_cmd(un, (struct uscsi_cmd *)arg, flag);
5367 		}
5368 		break;
5369 	}
5370 	case MTIOCTOP:
5371 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5372 		    "st_ioctl: MTIOCTOP\n");
5373 		rval = st_mtioctop(un, arg, flag);
5374 		break;
5375 
5376 	case MTIOCLTOP:
5377 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5378 		    "st_ioctl: MTIOLCTOP\n");
5379 		rval = st_mtiocltop(un, arg, flag);
5380 		break;
5381 
5382 	case MTIOCREADIGNOREILI:
5383 		{
5384 			int set_ili;
5385 
5386 			if (ddi_copyin((void *)arg, &set_ili,
5387 			    sizeof (set_ili), flag)) {
5388 				rval = EFAULT;
5389 				break;
5390 			}
5391 
5392 			if (un->un_bsize) {
5393 				rval = ENOTTY;
5394 				break;
5395 			}
5396 
5397 			switch (set_ili) {
5398 			case 0:
5399 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5400 				break;
5401 
5402 			case 1:
5403 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5404 				break;
5405 
5406 			default:
5407 				rval = EINVAL;
5408 				break;
5409 			}
5410 			break;
5411 		}
5412 
5413 	case MTIOCREADIGNOREEOFS:
5414 		{
5415 			int ignore_eof;
5416 
5417 			if (ddi_copyin((void *)arg, &ignore_eof,
5418 			    sizeof (ignore_eof), flag)) {
5419 				rval = EFAULT;
5420 				break;
5421 			}
5422 
5423 			if (!(un->un_dp->options & ST_REEL)) {
5424 				rval = ENOTTY;
5425 				break;
5426 			}
5427 
5428 			switch (ignore_eof) {
5429 			case 0:
5430 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5431 				break;
5432 
5433 			case 1:
5434 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5435 				break;
5436 
5437 			default:
5438 				rval = EINVAL;
5439 				break;
5440 			}
5441 			break;
5442 		}
5443 
5444 	case MTIOCSHORTFMK:
5445 	{
5446 		int short_fmk;
5447 
5448 		if (ddi_copyin((void *)arg, &short_fmk,
5449 		    sizeof (short_fmk), flag)) {
5450 			rval = EFAULT;
5451 			break;
5452 		}
5453 
5454 		switch (un->un_dp->type) {
5455 		case ST_TYPE_EXB8500:
5456 		case ST_TYPE_EXABYTE:
5457 			if (!short_fmk) {
5458 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5459 			} else if (short_fmk == 1) {
5460 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5461 			} else {
5462 				rval = EINVAL;
5463 			}
5464 			break;
5465 
5466 		default:
5467 			rval = ENOTTY;
5468 			break;
5469 		}
5470 		break;
5471 	}
5472 
5473 	case MTIOCGETPOS:
5474 		rval = st_update_block_pos(un, st_cmd, 0);
5475 		if (rval == 0) {
5476 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5477 			    sizeof (tapepos_t), flag)) {
5478 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5479 				    "MTIOCGETPOS copy out failed\n");
5480 				rval = EFAULT;
5481 			}
5482 		}
5483 		break;
5484 
5485 	case MTIOCRESTPOS:
5486 	{
5487 		tapepos_t dest;
5488 
5489 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5490 		    flag) != 0) {
5491 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5492 			    "MTIOCRESTPOS copy in failed\n");
5493 			rval = EFAULT;
5494 			break;
5495 		}
5496 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &dest);
5497 		if (rval != 0) {
5498 			rval = EIO;
5499 		}
5500 		break;
5501 	}
5502 	default:
5503 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5504 		    "st_ioctl: unknown ioctl\n");
5505 		rval = ENOTTY;
5506 	}
5507 
5508 exit:
5509 	if (!(un->un_persistence && un->un_persist_errors)) {
5510 		un->un_errno = rval;
5511 	}
5512 
5513 	mutex_exit(ST_MUTEX);
5514 
5515 	return (rval);
5516 }
5517 
5518 
5519 /*
5520  * do some MTIOCTOP tape operations
5521  */
5522 static int
5523 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5524 {
5525 #ifdef _MULTI_DATAMODEL
5526 	/*
5527 	 * For use when a 32 bit app makes a call into a
5528 	 * 64 bit ioctl
5529 	 */
5530 	struct mtop32	mtop_32_for_64;
5531 #endif /* _MULTI_DATAMODEL */
5532 	struct mtop passed;
5533 	struct mtlop local;
5534 	int rval = 0;
5535 
5536 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5537 
5538 	ASSERT(mutex_owned(ST_MUTEX));
5539 
5540 #ifdef _MULTI_DATAMODEL
5541 	switch (ddi_model_convert_from(flag & FMODELS)) {
5542 	case DDI_MODEL_ILP32:
5543 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5544 		    sizeof (struct mtop32), flag)) {
5545 			return (EFAULT);
5546 		}
5547 		local.mt_op = mtop_32_for_64.mt_op;
5548 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5549 		break;
5550 
5551 	case DDI_MODEL_NONE:
5552 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5553 			return (EFAULT);
5554 		}
5555 		local.mt_op = passed.mt_op;
5556 		/* prevent sign extention */
5557 		local.mt_count = (UINT32_MAX & passed.mt_count);
5558 		break;
5559 	}
5560 
5561 #else /* ! _MULTI_DATAMODEL */
5562 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5563 		return (EFAULT);
5564 	}
5565 	local.mt_op = passed.mt_op;
5566 	/* prevent sign extention */
5567 	local.mt_count = (UINT32_MAX & passed.mt_count);
5568 #endif /* _MULTI_DATAMODEL */
5569 
5570 	rval = st_do_mtioctop(un, &local);
5571 
5572 #ifdef _MULTI_DATAMODEL
5573 	switch (ddi_model_convert_from(flag & FMODELS)) {
5574 	case DDI_MODEL_ILP32:
5575 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5576 			rval = ERANGE;
5577 			break;
5578 		}
5579 		/*
5580 		 * Convert 64 bit back to 32 bit before doing
5581 		 * copyout. This is what the ILP32 app expects.
5582 		 */
5583 		mtop_32_for_64.mt_op = local.mt_op;
5584 		mtop_32_for_64.mt_count = local.mt_count;
5585 
5586 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5587 		    sizeof (struct mtop32), flag)) {
5588 			rval = EFAULT;
5589 		}
5590 		break;
5591 
5592 	case DDI_MODEL_NONE:
5593 		passed.mt_count = local.mt_count;
5594 		passed.mt_op = local.mt_op;
5595 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5596 			rval = EFAULT;
5597 		}
5598 		break;
5599 	}
5600 #else /* ! _MULTI_DATAMODE */
5601 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5602 		rval = ERANGE;
5603 	} else {
5604 		passed.mt_op = local.mt_op;
5605 		passed.mt_count = local.mt_count;
5606 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5607 			rval = EFAULT;
5608 		}
5609 	}
5610 #endif /* _MULTI_DATAMODE */
5611 
5612 
5613 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5614 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5615 	    un->un_pos.blkno, un->un_pos.eof);
5616 
5617 	if (un->un_pos.pmode == invalid) {
5618 		un->un_density_known = 0;
5619 	}
5620 
5621 	ASSERT(mutex_owned(ST_MUTEX));
5622 	return (rval);
5623 }
5624 
5625 static int
5626 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5627 {
5628 	struct mtlop local;
5629 	int rval;
5630 
5631 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5632 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5633 		return (EFAULT);
5634 	}
5635 
5636 	rval = st_do_mtioctop(un, &local);
5637 
5638 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5639 		rval = EFAULT;
5640 	}
5641 	return (rval);
5642 }
5643 
5644 
5645 static int
5646 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5647 {
5648 	dev_t dev = un->un_dev;
5649 	int savefile;
5650 	int rval = 0;
5651 
5652 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5653 
5654 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5655 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5656 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5657 	    "fileno=%x, blkno=%x, eof=%x\n",
5658 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5659 
5660 	un->un_status = 0;
5661 
5662 	/*
5663 	 * if we are going to mess with a tape, we have to make sure we have
5664 	 * one and are not offline (i.e. no tape is initialized).  We let
5665 	 * commands pass here that don't actually touch the tape, except for
5666 	 * loading and initialization (rewinding).
5667 	 */
5668 	if (un->un_state == ST_STATE_OFFLINE) {
5669 		switch (mtop->mt_op) {
5670 		case MTLOAD:
5671 		case MTNOP:
5672 			/*
5673 			 * We don't want strategy calling st_tape_init here,
5674 			 * so, change state
5675 			 */
5676 			un->un_state = ST_STATE_INITIALIZING;
5677 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5678 			    "st_do_mtioctop : OFFLINE state = %d\n",
5679 			    un->un_state);
5680 			break;
5681 		default:
5682 			/*
5683 			 * reinitialize by normal means
5684 			 */
5685 			rval = st_tape_init(un);
5686 			if (rval) {
5687 				un->un_state = ST_STATE_INITIALIZING;
5688 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5689 				    "st_do_mtioctop : OFFLINE init failure ");
5690 				un->un_state = ST_STATE_OFFLINE;
5691 				un->un_pos.pmode = invalid;
5692 				if (rval != EACCES) {
5693 					rval = EIO;
5694 				}
5695 				return (rval);
5696 			}
5697 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5698 			break;
5699 		}
5700 	}
5701 
5702 	/*
5703 	 * If the file position is invalid, allow only those
5704 	 * commands that properly position the tape and fail
5705 	 * the rest with EIO
5706 	 */
5707 	if (un->un_pos.pmode == invalid) {
5708 		switch (mtop->mt_op) {
5709 		case MTWEOF:
5710 		case MTRETEN:
5711 		case MTERASE:
5712 		case MTEOM:
5713 		case MTFSF:
5714 		case MTFSR:
5715 		case MTBSF:
5716 		case MTNBSF:
5717 		case MTBSR:
5718 		case MTSRSZ:
5719 		case MTGRSZ:
5720 		case MTSEEK:
5721 		case MTBSSF:
5722 		case MTFSSF:
5723 			return (EIO);
5724 			/* NOTREACHED */
5725 		case MTREW:
5726 		case MTLOAD:
5727 		case MTOFFL:
5728 		case MTNOP:
5729 		case MTTELL:
5730 		case MTLOCK:
5731 		case MTUNLOCK:
5732 			break;
5733 
5734 		default:
5735 			return (ENOTTY);
5736 			/* NOTREACHED */
5737 		}
5738 	}
5739 
5740 	switch (mtop->mt_op) {
5741 	case MTERASE:
5742 		/*
5743 		 * MTERASE rewinds the tape, erase it completely, and returns
5744 		 * to the beginning of the tape
5745 		 */
5746 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5747 			un->un_status = KEY_WRITE_PROTECT;
5748 			un->un_err_resid = mtop->mt_count;
5749 			COPY_POS(&un->un_err_pos, &un->un_pos);
5750 			return (EACCES);
5751 		}
5752 		if (un->un_dp->options & ST_REEL) {
5753 			un->un_fmneeded = 2;
5754 		} else {
5755 			un->un_fmneeded = 1;
5756 		}
5757 		mtop->mt_count = mtop->mt_count ? 1 : 0;
5758 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5759 		    st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
5760 		    st_cmd(un, SCMD_ERASE, mtop->mt_count, SYNC_CMD)) {
5761 			un->un_pos.pmode = invalid;
5762 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5763 			    "st_do_mtioctop : EIO space or erase or "
5764 			    "check den)\n");
5765 			rval = EIO;
5766 		} else {
5767 			/* QIC and helical scan rewind after erase */
5768 			if (un->un_dp->options & ST_REEL) {
5769 				(void) st_cmd(un, SCMD_REWIND, 0, ASYNC_CMD);
5770 			}
5771 		}
5772 		break;
5773 
5774 	case MTWEOF:
5775 		/*
5776 		 * write an end-of-file record
5777 		 */
5778 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5779 			un->un_status = KEY_WRITE_PROTECT;
5780 			un->un_err_resid = mtop->mt_count;
5781 			COPY_POS(&un->un_err_pos, &un->un_pos);
5782 			return (EACCES);
5783 		}
5784 
5785 		/*
5786 		 * zero count means just flush buffers
5787 		 * negative count is not permitted
5788 		 */
5789 		if (mtop->mt_count < 0) {
5790 			return (EINVAL);
5791 		}
5792 
5793 		/* Not on worm */
5794 		if (un->un_read_only == RDWR) {
5795 			un->un_test_append = 1;
5796 		}
5797 
5798 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5799 			if (st_determine_density(un, B_WRITE)) {
5800 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5801 				    "st_do_mtioctop : EIO : MTWEOF can't "
5802 				    "determine density");
5803 				return (EIO);
5804 			}
5805 		}
5806 
5807 		rval = st_write_fm(dev, (int)mtop->mt_count);
5808 		if ((rval != 0) && (rval != EACCES)) {
5809 			/*
5810 			 * Failure due to something other than illegal
5811 			 * request results in loss of state (st_intr).
5812 			 */
5813 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5814 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5815 			    "file mark");
5816 			rval = EIO;
5817 		}
5818 		break;
5819 
5820 	case MTRETEN:
5821 		/*
5822 		 * retension the tape
5823 		 */
5824 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5825 		    st_cmd(un, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5826 			un->un_pos.pmode = invalid;
5827 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5828 			    "st_do_mtioctop : EIO : MTRETEN ");
5829 			rval = EIO;
5830 		}
5831 		break;
5832 
5833 	case MTREW:
5834 		/*
5835 		 * rewind  the tape
5836 		 */
5837 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5838 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5839 			    "st_do_mtioctop : EIO:MTREW check "
5840 			    "density/wfm failed");
5841 			return (EIO);
5842 		}
5843 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
5844 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5845 			    "st_do_mtioctop : EIO : MTREW ");
5846 			rval = EIO;
5847 		}
5848 		break;
5849 
5850 	case MTOFFL:
5851 		/*
5852 		 * rewinds, and, if appropriate, takes the device offline by
5853 		 * unloading the tape
5854 		 */
5855 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5856 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5857 			    "st_do_mtioctop :EIO:MTOFFL check "
5858 			    "density/wfm failed");
5859 			return (EIO);
5860 		}
5861 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
5862 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5863 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5864 			    "st_do_mtioctop : EIO : MTOFFL");
5865 			return (EIO);
5866 		}
5867 		un->un_pos.eof = ST_NO_EOF;
5868 		un->un_laststate = un->un_state;
5869 		un->un_state = ST_STATE_OFFLINE;
5870 		un->un_mediastate = MTIO_EJECTED;
5871 		break;
5872 
5873 	case MTLOAD:
5874 		/*
5875 		 * This is to load a tape into the drive
5876 		 * Note that if the tape is not loaded, the device will have
5877 		 * to be opened via O_NDELAY or O_NONBLOCK.
5878 		 */
5879 		/*
5880 		 * Let's try and clean things up, if we are not
5881 		 * initializing, and then send in the load command, no
5882 		 * matter what.
5883 		 *
5884 		 * load after a media change by the user.
5885 		 */
5886 
5887 		if (un->un_state > ST_STATE_INITIALIZING) {
5888 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5889 		}
5890 		rval = st_cmd(un, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5891 		/* Load command to a drive that doesn't support load */
5892 		if ((rval == EIO) &&
5893 		    ((un->un_status == KEY_NOT_READY) &&
5894 			/* Medium not present */
5895 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5896 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5897 		    (un->un_dp->type == MT_ISSTK9840) &&
5898 			/* CSL not present */
5899 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5900 			rval = ENOTTY;
5901 			break;
5902 		} else if (rval != EACCES && rval != 0) {
5903 			rval = EIO;
5904 		}
5905 		if (rval) {
5906 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5907 			    "st_do_mtioctop : %s : MTLOAD\n",
5908 			    rval == EACCES ? "EACCES" : "EIO");
5909 			/*
5910 			 * If load tape fails, who knows what happened...
5911 			 */
5912 			un->un_pos.pmode = invalid;
5913 			break;
5914 		}
5915 
5916 		/*
5917 		 * reset all counters appropriately using rewind, as if LOAD
5918 		 * succeeds, we are at BOT
5919 		 */
5920 		un->un_state = ST_STATE_INITIALIZING;
5921 
5922 		rval = st_tape_init(un);
5923 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5924 			rval = 0;
5925 			break;
5926 		}
5927 
5928 		if (rval != 0) {
5929 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5930 			    "st_do_mtioctop : EIO : MTLOAD calls "
5931 			    "st_tape_init\n");
5932 			rval = EIO;
5933 			un->un_state = ST_STATE_OFFLINE;
5934 		}
5935 
5936 		break;
5937 
5938 	case MTNOP:
5939 		un->un_status = 0;		/* Reset status */
5940 		un->un_err_resid = 0;
5941 		mtop->mt_count = MTUNIT(dev);
5942 		break;
5943 
5944 	case MTEOM:
5945 		/*
5946 		 * positions the tape at a location just after the last file
5947 		 * written on the tape. For cartridge and 8 mm, this after
5948 		 * the last file mark; for reel, this is inbetween the two
5949 		 * last 2 file marks
5950 		 */
5951 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5952 		    (un->un_lastop == ST_OP_WRITE) ||
5953 		    (un->un_lastop == ST_OP_WEOF)) {
5954 			/*
5955 			 * If the command wants to move to logical end
5956 			 * of media, and we're already there, we're done.
5957 			 * If we were at logical eot, we reset the state
5958 			 * to be *not* at logical eot.
5959 			 *
5960 			 * If we're at physical or logical eot, we prohibit
5961 			 * forward space operations (unconditionally).
5962 			 *
5963 			 * Also if the last operation was a write of any
5964 			 * kind the tape is at EOD.
5965 			 */
5966 			return (0);
5967 		}
5968 		/*
5969 		 * physical tape position may not be what we've been
5970 		 * telling the user; adjust the request accordingly
5971 		 */
5972 		if (IN_EOF(un->un_pos)) {
5973 			un->un_pos.fileno++;
5974 			un->un_pos.blkno = 0;
5975 		}
5976 
5977 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
5978 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5979 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
5980 			    " failed");
5981 			return (EIO);
5982 		}
5983 
5984 		/*
5985 		 * st_find_eod() returns the last fileno we knew about;
5986 		 */
5987 		savefile = st_find_eod(un);
5988 
5989 		if ((un->un_status != KEY_BLANK_CHECK) &&
5990 		    (un->un_status != SUN_KEY_EOT)) {
5991 			un->un_pos.pmode = invalid;
5992 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5993 			    "st_do_mtioctop : EIO : MTEOM status check failed");
5994 			rval = EIO;
5995 		} else {
5996 			/*
5997 			 * For 1/2" reel tapes assume logical EOT marked
5998 			 * by two file marks or we don't care that we may
5999 			 * be extending the last file on the tape.
6000 			 */
6001 			if (un->un_dp->options & ST_REEL) {
6002 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
6003 					un->un_pos.pmode = invalid;
6004 					ST_DEBUG2(ST_DEVINFO, st_label,
6005 					    SCSI_DEBUG,
6006 					    "st_do_mtioctop : EIO : MTEOM space"
6007 					    " cmd failed");
6008 					rval = EIO;
6009 					break;
6010 				}
6011 				/*
6012 				 * Fix up the block number.
6013 				 */
6014 				un->un_pos.blkno = 0;
6015 				un->un_err_pos.blkno = 0;
6016 			}
6017 			un->un_err_resid = 0;
6018 			un->un_pos.fileno = savefile;
6019 			un->un_pos.eof = ST_EOT;
6020 		}
6021 		un->un_status = 0;
6022 		break;
6023 
6024 	case MTFSF:
6025 		MAX_SPACE_CNT(mtop->mt_count);
6026 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
6027 		break;
6028 
6029 	case MTFSR:
6030 		MAX_SPACE_CNT(mtop->mt_count);
6031 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
6032 		break;
6033 
6034 	case MTBSF:
6035 		MAX_SPACE_CNT(mtop->mt_count);
6036 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
6037 		break;
6038 
6039 	case MTNBSF:
6040 		MAX_SPACE_CNT(mtop->mt_count);
6041 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
6042 		break;
6043 
6044 	case MTBSR:
6045 		MAX_SPACE_CNT(mtop->mt_count);
6046 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
6047 		break;
6048 
6049 	case MTBSSF:
6050 		MAX_SPACE_CNT(mtop->mt_count);
6051 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
6052 		break;
6053 
6054 	case MTFSSF:
6055 		MAX_SPACE_CNT(mtop->mt_count);
6056 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
6057 		break;
6058 
6059 	case MTSRSZ:
6060 
6061 		/*
6062 		 * Set record-size to that sent by user
6063 		 * Check to see if there is reason that the requested
6064 		 * block size should not be set.
6065 		 */
6066 
6067 		/* If requesting variable block size is it ok? */
6068 		if ((mtop->mt_count == 0) &&
6069 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
6070 			return (ENOTTY);
6071 		}
6072 
6073 		/*
6074 		 * If requested block size is not variable "0",
6075 		 * is it less then minimum.
6076 		 */
6077 		if ((mtop->mt_count != 0) &&
6078 		    (mtop->mt_count < un->un_minbsize)) {
6079 			return (EINVAL);
6080 		}
6081 
6082 		/* Is the requested block size more then maximum */
6083 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
6084 		    (un->un_maxbsize != 0)) {
6085 			return (EINVAL);
6086 		}
6087 
6088 		/* Is requested block size a modulus the device likes */
6089 		if ((mtop->mt_count % un->un_data_mod) != 0) {
6090 			return (EINVAL);
6091 		}
6092 
6093 		if (st_change_block_size(un, (uint32_t)mtop->mt_count) != 0) {
6094 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6095 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
6096 			return (EIO);
6097 		}
6098 
6099 		return (0);
6100 
6101 	case MTGRSZ:
6102 		/*
6103 		 * Get record-size to the user
6104 		 */
6105 		mtop->mt_count = un->un_bsize;
6106 		rval = 0;
6107 		break;
6108 
6109 	case MTTELL:
6110 		rval = st_update_block_pos(un, st_cmd, 0);
6111 		mtop->mt_count = un->un_pos.lgclblkno;
6112 		break;
6113 
6114 	case MTSEEK:
6115 		rval = st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
6116 		    (uint64_t)mtop->mt_count, un->un_pos.partition);
6117 		/*
6118 		 * This bit of magic make mt print the actual position if
6119 		 * the resulting position was not what was asked for.
6120 		 */
6121 		if (rval == ESPIPE) {
6122 			rval = EIO;
6123 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
6124 				mtop->mt_op = MTTELL;
6125 				mtop->mt_count = un->un_pos.lgclblkno;
6126 			}
6127 		}
6128 		break;
6129 
6130 	case MTLOCK:
6131 		if (st_cmd(un, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
6132 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6133 			    "st_do_mtioctop : EIO : MTLOCK");
6134 			rval = EIO;
6135 		}
6136 		break;
6137 
6138 	case MTUNLOCK:
6139 		if (st_cmd(un, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
6140 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6141 			    "st_do_mtioctop : EIO : MTUNLOCK");
6142 			rval = EIO;
6143 		}
6144 		break;
6145 
6146 	default:
6147 		rval = ENOTTY;
6148 	}
6149 
6150 	return (rval);
6151 }
6152 
6153 
6154 /*
6155  * Run a command for uscsi ioctl.
6156  */
6157 static int
6158 st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
6159 {
6160 	struct uscsi_cmd	*uscmd;
6161 	struct buf	*bp;
6162 	enum uio_seg	uioseg;
6163 	int	offline_state = 0;
6164 	int	err = 0;
6165 	dev_t dev = un->un_dev;
6166 
6167 	ST_FUNC(ST_DEVINFO, st_uscsi_cmd);
6168 
6169 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6170 	    "st_uscsi_cmd(dev = 0x%lx)\n", un->un_dev);
6171 
6172 	ASSERT(mutex_owned(ST_MUTEX));
6173 
6174 	/*
6175 	 * We really don't know what commands are coming in here and
6176 	 * we don't want to limit the commands coming in.
6177 	 *
6178 	 * If st_tape_init() gets called from st_strategy(), then we
6179 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
6180 	 * which it never will, as we set it below.  To prevent
6181 	 * st_tape_init() from getting called, we have to set state to other
6182 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
6183 	 * achieves this purpose already.
6184 	 *
6185 	 * We use offline_state to preserve the OFFLINE state, if it exists,
6186 	 * so other entry points to the driver might have the chance to call
6187 	 * st_tape_init().
6188 	 */
6189 	if (un->un_state == ST_STATE_OFFLINE) {
6190 		un->un_laststate = ST_STATE_OFFLINE;
6191 		un->un_state = ST_STATE_INITIALIZING;
6192 		offline_state = 1;
6193 	}
6194 
6195 	mutex_exit(ST_MUTEX);
6196 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag, ROUTE, &uscmd);
6197 	mutex_enter(ST_MUTEX);
6198 	if (err != 0) {
6199 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6200 		    "st_uscsi_cmd: scsi_uscsi_alloc_and_copyin failed\n");
6201 		goto exit;
6202 	}
6203 
6204 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
6205 
6206 	/* check to see if this command requires the drive to be reserved */
6207 	if (uscmd->uscsi_cdb != NULL) {
6208 		err = st_check_cdb_for_need_to_reserve(un,
6209 		    (uchar_t *)uscmd->uscsi_cdb);
6210 		if (err) {
6211 			goto exit_free;
6212 		}
6213 		/*
6214 		 * If this is a space command we need to save the starting
6215 		 * point so we can retry from there if the command fails.
6216 		 */
6217 		if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6218 		    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) {
6219 			(void) st_update_block_pos(un, st_cmd, 0);
6220 		}
6221 	}
6222 
6223 	/*
6224 	 * Forground should not be doing anything while recovery is active.
6225 	 */
6226 	ASSERT(un->un_recov_buf_busy == 0);
6227 
6228 	/*
6229 	 * Get buffer resources...
6230 	 */
6231 	while (un->un_sbuf_busy)
6232 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6233 	un->un_sbuf_busy = 1;
6234 
6235 #ifdef STDEBUG
6236 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0x7) > 6) {
6237 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
6238 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6239 		    "uscsi cdb", uscmd->uscsi_cdb);
6240 		if (uscmd->uscsi_buflen) {
6241 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6242 			    "uscsi %s of %ld bytes %s %s space\n",
6243 			    (rw == B_READ) ? rd_str : wr_str,
6244 			    uscmd->uscsi_buflen,
6245 			    (rw == B_READ) ? "to" : "from",
6246 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
6247 		}
6248 	}
6249 #endif /* STDEBUG */
6250 
6251 	/*
6252 	 * Although st_uscsi_cmd() never makes use of these
6253 	 * now, we are just being safe and consistent.
6254 	 */
6255 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
6256 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
6257 
6258 	un->un_srqbufp = uscmd->uscsi_rqbuf;
6259 	bp = un->un_sbufp;
6260 	bzero(bp, sizeof (buf_t));
6261 	if (uscmd->uscsi_cdb != NULL) {
6262 		bp->b_forw = (struct buf *)(uintptr_t)uscmd->uscsi_cdb[0];
6263 	}
6264 	bp->b_back = (struct buf *)uscmd;
6265 
6266 	mutex_exit(ST_MUTEX);
6267 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, st_strategy, bp, NULL);
6268 	mutex_enter(ST_MUTEX);
6269 
6270 	/*
6271 	 * If scsi reset successful, don't write any filemarks.
6272 	 */
6273 	if ((err == 0) && (uscmd->uscsi_flags &
6274 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
6275 		un->un_fmneeded = 0;
6276 	}
6277 
6278 exit_free:
6279 	/*
6280 	 * Free resources
6281 	 */
6282 	un->un_sbuf_busy = 0;
6283 	un->un_srqbufp = NULL;
6284 
6285 	/*
6286 	 * If was a space command need to update logical block position.
6287 	 * If the command failed such that positioning is invalid, Don't
6288 	 * update the position as the user must do this to validate the
6289 	 * position for data protection.
6290 	 */
6291 	if ((uscmd->uscsi_cdb != NULL) &&
6292 	    ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6293 	    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) &&
6294 	    (un->un_pos.pmode != invalid)) {
6295 		un->un_running.pmode = invalid;
6296 		(void) st_update_block_pos(un, st_cmd, 1);
6297 		/*
6298 		 * Set running position to invalid so it updates on the
6299 		 * next command.
6300 		 */
6301 		un->un_running.pmode = invalid;
6302 	}
6303 	cv_signal(&un->un_sbuf_cv);
6304 	mutex_exit(ST_MUTEX);
6305 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
6306 	mutex_enter(ST_MUTEX);
6307 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6308 	    "st_uscsi_cmd returns 0x%x\n", err);
6309 
6310 exit:
6311 	/* don't lose offline state */
6312 	if (offline_state) {
6313 		un->un_state = ST_STATE_OFFLINE;
6314 	}
6315 
6316 	ASSERT(mutex_owned(ST_MUTEX));
6317 	return (err);
6318 }
6319 
6320 static int
6321 st_write_fm(dev_t dev, int wfm)
6322 {
6323 	int i;
6324 	int rval;
6325 
6326 	GET_SOFT_STATE(dev);
6327 
6328 	ST_FUNC(ST_DEVINFO, st_write_fm);
6329 
6330 	ASSERT(mutex_owned(ST_MUTEX));
6331 
6332 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6333 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6334 
6335 	/*
6336 	 * write one filemark at the time after EOT
6337 	 */
6338 	if (un->un_pos.eof >= ST_EOT) {
6339 		for (i = 0; i < wfm; i++) {
6340 			rval = st_cmd(un, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6341 			if (rval == EACCES) {
6342 				return (rval);
6343 			}
6344 			if (rval != 0) {
6345 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6346 				    "st_write_fm : EIO : write EOT file mark");
6347 				return (EIO);
6348 			}
6349 		}
6350 	} else {
6351 		rval = st_cmd(un, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6352 		if (rval == EACCES) {
6353 			return (rval);
6354 		}
6355 		if (rval) {
6356 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6357 			    "st_write_fm : EIO : write file mark");
6358 			return (EIO);
6359 		}
6360 	}
6361 
6362 	ASSERT(mutex_owned(ST_MUTEX));
6363 	return (0);
6364 }
6365 
6366 #ifdef STDEBUG
6367 static void
6368 st_start_dump(struct scsi_tape *un, struct buf *bp)
6369 {
6370 	struct scsi_pkt *pkt = BP_PKT(bp);
6371 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6372 
6373 	ST_FUNC(ST_DEVINFO, st_start_dump);
6374 
6375 	if ((st_debug & 0x7) < 6)
6376 		return;
6377 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6378 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6379 	    (void *)bp->b_forw, bp->b_bcount,
6380 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6381 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6382 	    "st_start: cdb",  (caddr_t)cdbp);
6383 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6384 	    "st_start: fileno=%d, blk=%d\n",
6385 	    un->un_pos.fileno, un->un_pos.blkno);
6386 }
6387 #endif
6388 
6389 
6390 /*
6391  * Command start && done functions
6392  */
6393 
6394 /*
6395  * st_start()
6396  *
6397  * Called from:
6398  *  st_strategy() to start a command.
6399  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6400  *  st_attach() when resuming from power down state.
6401  *  st_start_restart() to retry transport when device was previously busy.
6402  *  st_done_and_mutex_exit() to start the next command when previous is done.
6403  *
6404  * On entry:
6405  *  scsi_pkt may or may not be allocated.
6406  *
6407  */
6408 static void
6409 st_start(struct scsi_tape *un)
6410 {
6411 	struct buf *bp;
6412 	int status;
6413 	int queued;
6414 
6415 	ST_FUNC(ST_DEVINFO, st_start);
6416 	ASSERT(mutex_owned(ST_MUTEX));
6417 
6418 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6419 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6420 
6421 	if (un->un_recov_buf_busy) {
6422 		/* recovery commands can happen anytime */
6423 		bp = un->un_recov_buf;
6424 		queued = 0;
6425 	} else if (un->un_sbuf_busy) {
6426 		/* sbuf commands should only happen with an empty queue. */
6427 		ASSERT(un->un_quef == NULL);
6428 		ASSERT(un->un_runqf == NULL);
6429 		bp = un->un_sbufp;
6430 		queued = 0;
6431 	} else if (un->un_quef != NULL) {
6432 		if (un->un_persistence && un->un_persist_errors) {
6433 			return;
6434 		}
6435 		bp = un->un_quef;
6436 		queued = 1;
6437 	} else {
6438 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6439 		    "st_start() returning no buf found\n");
6440 		return;
6441 	}
6442 
6443 	ASSERT((bp->b_flags & B_DONE) == 0);
6444 
6445 	/*
6446 	 * Don't send more than un_throttle commands to the HBA
6447 	 */
6448 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6449 		/*
6450 		 * if doing recovery we know there is outstanding commands.
6451 		 */
6452 		if (bp != un->un_recov_buf) {
6453 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6454 			    "st_start returning throttle = %d or ncmds = %d\n",
6455 			    un->un_throttle, un->un_ncmds);
6456 			if (un->un_ncmds == 0) {
6457 				typedef void (*func)();
6458 				func fnc = (func)st_runout;
6459 
6460 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6461 				    "Sending delayed start to st_runout()\n");
6462 				mutex_exit(ST_MUTEX);
6463 				(void) timeout(fnc, un, drv_usectohz(1000000));
6464 				mutex_enter(ST_MUTEX);
6465 			}
6466 			return;
6467 		}
6468 	}
6469 
6470 	/*
6471 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6472 	 * build the command.
6473 	 */
6474 	if (BP_PKT(bp) == NULL) {
6475 		ASSERT((bp->b_flags & B_DONE) == 0);
6476 		st_make_cmd(un, bp, st_runout);
6477 		ASSERT((bp->b_flags & B_DONE) == 0);
6478 		status = geterror(bp);
6479 
6480 		/*
6481 		 * Some HBA's don't call bioerror() to set an error.
6482 		 * And geterror() returns zero if B_ERROR is not set.
6483 		 * So if we get zero we must check b_error.
6484 		 */
6485 		if (status == 0 && bp->b_error != 0) {
6486 			status = bp->b_error;
6487 			bioerror(bp, status);
6488 		}
6489 
6490 		/*
6491 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6492 		 * In tape ENOMEM has special meaning so we'll change it.
6493 		 */
6494 		if (status == ENOMEM) {
6495 			status = 0;
6496 			bioerror(bp, status);
6497 		}
6498 
6499 		/*
6500 		 * Did it fail and is it retryable?
6501 		 * If so return and wait for the callback through st_runout.
6502 		 * Also looks like scsi_init_pkt() will setup a callback even
6503 		 * if it isn't retryable.
6504 		 */
6505 		if (BP_PKT(bp) == NULL) {
6506 			if (status == 0) {
6507 				/*
6508 				 * If first attempt save state.
6509 				 */
6510 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6511 					un->un_laststate = un->un_state;
6512 					un->un_state = ST_STATE_RESOURCE_WAIT;
6513 				}
6514 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6515 				    "temp no resources for pkt\n");
6516 			} else if (status == EINVAL) {
6517 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6518 				    "scsi_init_pkt rejected pkt as too big\n");
6519 				if (un->un_persistence) {
6520 					st_set_pe_flag(un);
6521 				}
6522 			} else {
6523 				/*
6524 				 * Unlikely that it would be retryable then not.
6525 				 */
6526 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6527 					un->un_state = un->un_laststate;
6528 				}
6529 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6530 				    "perm no resources for pkt errno = 0x%x\n",
6531 				    status);
6532 			}
6533 			return;
6534 		}
6535 		/*
6536 		 * Worked this time set the state back.
6537 		 */
6538 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6539 			un->un_state = un->un_laststate;
6540 		}
6541 	}
6542 
6543 	if (queued) {
6544 		/*
6545 		 * move from waitq to runq
6546 		 */
6547 		(void) st_remove_from_queue(&un->un_quef, &un->un_quel, bp);
6548 		st_add_to_queue(&un->un_runqf, &un->un_runql, un->un_runql, bp);
6549 	}
6550 
6551 
6552 #ifdef STDEBUG
6553 	st_start_dump(un, bp);
6554 #endif
6555 
6556 	/* could not get here if throttle was zero */
6557 	un->un_last_throttle = un->un_throttle;
6558 	un->un_throttle = 0;	/* so nothing else will come in here */
6559 	un->un_ncmds++;
6560 
6561 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6562 
6563 	status = st_transport(un, BP_PKT(bp));
6564 
6565 	if (un->un_last_throttle) {
6566 		un->un_throttle = un->un_last_throttle;
6567 	}
6568 
6569 	if (status != TRAN_ACCEPT) {
6570 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6571 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
6572 		    "Unhappy transport packet status 0x%x\n", status);
6573 
6574 		if (status == TRAN_BUSY) {
6575 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
6576 
6577 			/*
6578 			 * If command recovery is enabled and this isn't
6579 			 * a recovery command try command recovery.
6580 			 */
6581 			if (pkti->privatelen == sizeof (recov_info) &&
6582 			    bp != un->un_recov_buf) {
6583 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
6584 				    "Command Recovery called on busy send\n");
6585 				if (st_command_recovery(un, BP_PKT(bp),
6586 				    ATTEMPT_RETRY) == JUST_RETURN) {
6587 					return;
6588 				}
6589 			} else {
6590 				mutex_exit(ST_MUTEX);
6591 				if (st_handle_start_busy(un, bp,
6592 				    ST_TRAN_BUSY_TIMEOUT, queued) == 0) {
6593 					mutex_enter(ST_MUTEX);
6594 					return;
6595 				}
6596 				/*
6597 				 * if too many retries, fail the transport
6598 				 */
6599 				mutex_enter(ST_MUTEX);
6600 			}
6601 		}
6602 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6603 		    "transport rejected %d\n", status);
6604 		bp->b_resid = bp->b_bcount;
6605 
6606 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6607 		ST_DO_ERRSTATS(un, st_transerrs);
6608 		if ((bp == un->un_recov_buf) && (status == TRAN_BUSY)) {
6609 			st_bioerror(bp, EBUSY);
6610 		} else {
6611 			st_bioerror(bp, EIO);
6612 			st_set_pe_flag(un);
6613 		}
6614 		st_done_and_mutex_exit(un, bp);
6615 		mutex_enter(ST_MUTEX);
6616 	}
6617 
6618 	ASSERT(mutex_owned(ST_MUTEX));
6619 }
6620 
6621 /*
6622  * if the transport is busy, then put this bp back on the waitq
6623  */
6624 static int
6625 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6626     clock_t timeout_interval, int queued)
6627 {
6628 
6629 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
6630 
6631 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6632 
6633 	mutex_enter(ST_MUTEX);
6634 
6635 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6636 	    "st_handle_start_busy()\n");
6637 
6638 	/*
6639 	 * Check to see if we hit the retry timeout and one last check for
6640 	 * making sure this is the last on the runq, if it is not, we have
6641 	 * to fail
6642 	 */
6643 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
6644 	    ((queued) && (un->un_runql != bp))) {
6645 		mutex_exit(ST_MUTEX);
6646 		return (-1);
6647 	}
6648 
6649 	if (queued) {
6650 		/* put the bp back on the waitq */
6651 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
6652 	}
6653 
6654 	/*
6655 	 * Decrement un_ncmds so that this
6656 	 * gets thru' st_start() again.
6657 	 */
6658 	un->un_ncmds--;
6659 
6660 	if (queued) {
6661 		/*
6662 		 * since this is an error case, we won't have to do this list
6663 		 * walking much. We've already made sure this bp was the
6664 		 * last on the runq
6665 		 */
6666 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6667 
6668 		/*
6669 		 * send a marker pkt, if appropriate
6670 		 */
6671 		st_hba_unflush(un);
6672 
6673 	}
6674 	/*
6675 	 * all queues are aligned, we are just waiting to
6676 	 * transport, don't alloc any more buf p's, when
6677 	 * st_start is reentered.
6678 	 */
6679 	(void) timeout(st_start_restart, un, timeout_interval);
6680 
6681 	mutex_exit(ST_MUTEX);
6682 	return (0);
6683 }
6684 
6685 
6686 /*
6687  * st_runout a callback that is called what a resource allocatation failed
6688  */
6689 static int
6690 st_runout(caddr_t arg)
6691 {
6692 	struct scsi_tape *un = (struct scsi_tape *)arg;
6693 	struct buf *bp;
6694 	int queued;
6695 
6696 	ASSERT(un != NULL);
6697 
6698 	ST_FUNC(ST_DEVINFO, st_runout);
6699 
6700 	mutex_enter(ST_MUTEX);
6701 
6702 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6703 
6704 	if (un->un_recov_buf_busy != 0) {
6705 		bp = un->un_recov_buf;
6706 		queued = 0;
6707 	} else if (un->un_sbuf_busy != 0) {
6708 		/* sbuf commands should only happen with an empty queue. */
6709 		ASSERT(un->un_quef == NULL);
6710 		ASSERT(un->un_runqf == NULL);
6711 		bp = un->un_sbufp;
6712 		queued = 0;
6713 	} else if (un->un_quef != NULL) {
6714 		bp = un->un_quef;
6715 		if (un->un_persistence && un->un_persist_errors) {
6716 			mutex_exit(ST_MUTEX);
6717 			bp->b_resid = bp->b_bcount;
6718 			biodone(bp);
6719 			return (1);
6720 		}
6721 		queued = 1;
6722 	} else {
6723 		ASSERT(1 == 0);
6724 		mutex_exit(ST_MUTEX);
6725 		return (1);
6726 	}
6727 
6728 	/*
6729 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6730 	 */
6731 	if ((bp != NULL) && (geterror(bp) != 0)) {
6732 
6733 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6734 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6735 		    bp->b_flags, geterror(bp));
6736 		ASSERT((bp->b_flags & B_DONE) == 0);
6737 
6738 		if (queued) {
6739 			(void) st_remove_from_queue(&un->un_quef, &un->un_quel,
6740 			    bp);
6741 		}
6742 		mutex_exit(ST_MUTEX);
6743 
6744 		ASSERT((bp->b_flags & B_DONE) == 0);
6745 
6746 		/*
6747 		 * Set resid, Error already set, then unblock calling thread.
6748 		 */
6749 		bp->b_resid = bp->b_bcount;
6750 		biodone(bp);
6751 	} else {
6752 		/*
6753 		 * Try Again
6754 		 */
6755 		st_start(un);
6756 		mutex_exit(ST_MUTEX);
6757 	}
6758 
6759 	/*
6760 	 * Comments courtesy of sd.c
6761 	 * The scsi_init_pkt routine allows for the callback function to
6762 	 * return a 0 indicating the callback should be rescheduled or a 1
6763 	 * indicating not to reschedule. This routine always returns 1
6764 	 * because the driver always provides a callback function to
6765 	 * scsi_init_pkt. This results in a callback always being scheduled
6766 	 * (via the scsi_init_pkt callback implementation) if a resource
6767 	 * failure occurs.
6768 	 */
6769 
6770 	return (1);
6771 }
6772 
6773 /*
6774  * st_done_and_mutex_exit()
6775  *	- remove bp from runq
6776  *	- start up the next request
6777  *	- if this was an asynch bp, clean up
6778  *	- exit with released mutex
6779  */
6780 static void
6781 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6782 {
6783 	int pe_flagged = 0;
6784 	struct scsi_pkt *pkt = BP_PKT(bp);
6785 	pkt_info *pktinfo = pkt->pkt_private;
6786 
6787 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6788 #if !defined(lint)
6789 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6790 #endif
6791 
6792 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6793 
6794 	ASSERT(mutex_owned(ST_MUTEX));
6795 
6796 	(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6797 
6798 	un->un_ncmds--;
6799 	cv_signal(&un->un_queue_cv);
6800 
6801 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6802 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6803 	    "0x%x\n", pkt->pkt_cdbp[0], bp->b_bcount,
6804 	    bp->b_resid, bp->b_flags);
6805 
6806 
6807 	/*
6808 	 * update kstats with transfer count info
6809 	 */
6810 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6811 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6812 		if (bp->b_flags & B_READ) {
6813 			IOSP->reads++;
6814 			IOSP->nread += n_done;
6815 		} else {
6816 			IOSP->writes++;
6817 			IOSP->nwritten += n_done;
6818 		}
6819 	}
6820 
6821 	/*
6822 	 * Start the next one before releasing resources on this one, if
6823 	 * there is something on the queue and persistent errors has not been
6824 	 * flagged
6825 	 */
6826 
6827 	if ((pe_flagged = (un->un_persistence && un->un_persist_errors)) != 0) {
6828 		un->un_last_resid = bp->b_resid;
6829 		un->un_last_count = bp->b_bcount;
6830 	}
6831 
6832 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6833 		cv_broadcast(&un->un_tape_busy_cv);
6834 	} else if (un->un_quef && un->un_throttle && !pe_flagged &&
6835 	    (bp != un->un_recov_buf)) {
6836 		st_start(un);
6837 	}
6838 
6839 	un->un_retry_ct = max(pktinfo->pkt_retry_cnt, pktinfo->str_retry_cnt);
6840 
6841 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6842 		/*
6843 		 * Since we marked this ourselves as ASYNC,
6844 		 * there isn't anybody around waiting for
6845 		 * completion any more.
6846 		 */
6847 		uchar_t *cmd = pkt->pkt_cdbp;
6848 		if (*cmd == SCMD_READ || *cmd == SCMD_WRITE) {
6849 			bp->b_un.b_addr = (caddr_t)0;
6850 		}
6851 		ST_DEBUG(ST_DEVINFO, st_label, CE_NOTE,
6852 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6853 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
6854 		    "CDB sent with B_ASYNC",  (caddr_t)cmd);
6855 		if (pkt) {
6856 			scsi_destroy_pkt(pkt);
6857 		}
6858 		un->un_sbuf_busy = 0;
6859 		cv_signal(&un->un_sbuf_cv);
6860 		mutex_exit(ST_MUTEX);
6861 		return;
6862 	}
6863 
6864 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6865 		/*
6866 		 * Copy status from scsi_pkt to uscsi_cmd
6867 		 * since st_uscsi_cmd needs it
6868 		 */
6869 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6870 	}
6871 
6872 
6873 #ifdef STDEBUG
6874 	if (((st_debug & 0x7) >= 4) &&
6875 	    (((un->un_pos.blkno % 100) == 0) ||
6876 	    (un->un_persistence && un->un_persist_errors))) {
6877 
6878 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6879 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6880 		    "un_errno = %d, un_pe = %d\n",
6881 		    un->un_ncmds, un->un_throttle, un->un_errno,
6882 		    un->un_persist_errors);
6883 	}
6884 
6885 #endif
6886 
6887 	mutex_exit(ST_MUTEX);
6888 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6889 	    "st_done_and_mutex_exit: freeing pkt\n");
6890 
6891 	if (pkt) {
6892 		scsi_destroy_pkt(pkt);
6893 	}
6894 
6895 	biodone(bp);
6896 
6897 	/*
6898 	 * now that we biodoned that command, if persistent errors have been
6899 	 * flagged, flush the waitq
6900 	 */
6901 	if (pe_flagged)
6902 		st_flush(un);
6903 }
6904 
6905 
6906 /*
6907  * Tape error, flush tape driver queue.
6908  */
6909 static void
6910 st_flush(struct scsi_tape *un)
6911 {
6912 	struct buf *bp;
6913 
6914 	ST_FUNC(ST_DEVINFO, st_flush);
6915 
6916 	mutex_enter(ST_MUTEX);
6917 
6918 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6919 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6920 	    un->un_ncmds, (void *)un->un_quef);
6921 
6922 	/*
6923 	 * if we still have commands outstanding, wait for them to come in
6924 	 * before flushing the queue, and make sure there is a queue
6925 	 */
6926 	if (un->un_ncmds || !un->un_quef)
6927 		goto exit;
6928 
6929 	/*
6930 	 * we have no more commands outstanding, so let's deal with special
6931 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6932 	 * is 0, then we know there was no error and we return a 0 read or
6933 	 * write before showing errors
6934 	 */
6935 
6936 	/* Flush the wait queue. */
6937 	while ((bp = un->un_quef) != NULL) {
6938 		un->un_quef = bp->b_actf;
6939 
6940 		bp->b_resid = bp->b_bcount;
6941 
6942 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6943 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6944 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6945 
6946 		st_set_pe_errno(un);
6947 
6948 		bioerror(bp, un->un_errno);
6949 
6950 		mutex_exit(ST_MUTEX);
6951 		/* it should have one, but check anyway */
6952 		if (BP_PKT(bp)) {
6953 			scsi_destroy_pkt(BP_PKT(bp));
6954 		}
6955 		biodone(bp);
6956 		mutex_enter(ST_MUTEX);
6957 	}
6958 
6959 	/*
6960 	 * It's not a bad practice to reset the
6961 	 * waitq tail pointer to NULL.
6962 	 */
6963 	un->un_quel = NULL;
6964 
6965 exit:
6966 	/* we mucked with the queue, so let others know about it */
6967 	cv_signal(&un->un_queue_cv);
6968 	mutex_exit(ST_MUTEX);
6969 }
6970 
6971 
6972 /*
6973  * Utility functions
6974  */
6975 static int
6976 st_determine_generic(struct scsi_tape *un)
6977 {
6978 	int bsize;
6979 	static char *cart = "0.25 inch cartridge";
6980 	char *sizestr;
6981 
6982 	ST_FUNC(ST_DEVINFO, st_determine_generic);
6983 
6984 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6985 	    "st_determine_generic(un = 0x%p)\n", (void*)un);
6986 
6987 	ASSERT(mutex_owned(ST_MUTEX));
6988 
6989 	if (st_modesense(un)) {
6990 		return (-1);
6991 	}
6992 
6993 	bsize = (un->un_mspl->high_bl << 16)	|
6994 	    (un->un_mspl->mid_bl << 8)	|
6995 	    (un->un_mspl->low_bl);
6996 
6997 	if (bsize == 0) {
6998 		un->un_dp->options |= ST_VARIABLE;
6999 		un->un_dp->bsize = 0;
7000 		un->un_bsize = 0;
7001 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
7002 		/*
7003 		 * record size of this device too big.
7004 		 * try and convert it to variable record length.
7005 		 *
7006 		 */
7007 		un->un_dp->options |= ST_VARIABLE;
7008 		if (st_change_block_size(un, 0) != 0) {
7009 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7010 			    "Fixed Record Size %d is too large\n", bsize);
7011 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7012 			    "Cannot switch to variable record size\n");
7013 			un->un_dp->options &= ~ST_VARIABLE;
7014 			return (-1);
7015 		}
7016 	} else if (st_change_block_size(un, 0) == 0) {
7017 		/*
7018 		 * If the drive was set to a non zero block size,
7019 		 * See if it can be set to a zero block size.
7020 		 * If it works, ST_VARIABLE so user can set it as they want.
7021 		 */
7022 		un->un_dp->options |= ST_VARIABLE;
7023 		un->un_dp->bsize = 0;
7024 		un->un_bsize = 0;
7025 	} else {
7026 		un->un_dp->bsize = bsize;
7027 		un->un_bsize = bsize;
7028 	}
7029 
7030 
7031 	switch (un->un_mspl->density) {
7032 	default:
7033 	case 0x0:
7034 		/*
7035 		 * default density, cannot determine any other
7036 		 * information.
7037 		 */
7038 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
7039 		un->un_dp->type = ST_TYPE_DEFAULT;
7040 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
7041 		break;
7042 	case 0x1:
7043 	case 0x2:
7044 	case 0x3:
7045 	case 0x6:
7046 		/*
7047 		 * 1/2" reel
7048 		 */
7049 		sizestr = "0.50 inch reel";
7050 		un->un_dp->type = ST_TYPE_REEL;
7051 		un->un_dp->options |= ST_REEL;
7052 		un->un_dp->densities[0] = 0x1;
7053 		un->un_dp->densities[1] = 0x2;
7054 		un->un_dp->densities[2] = 0x6;
7055 		un->un_dp->densities[3] = 0x3;
7056 		break;
7057 	case 0x4:
7058 	case 0x5:
7059 	case 0x7:
7060 	case 0x0b:
7061 
7062 		/*
7063 		 * Quarter inch.
7064 		 */
7065 		sizestr = cart;
7066 		un->un_dp->type = ST_TYPE_DEFAULT;
7067 		un->un_dp->options |= ST_QIC;
7068 
7069 		un->un_dp->densities[1] = 0x4;
7070 		un->un_dp->densities[2] = 0x5;
7071 		un->un_dp->densities[3] = 0x7;
7072 		un->un_dp->densities[0] = 0x0b;
7073 		break;
7074 
7075 	case 0x0f:
7076 	case 0x10:
7077 	case 0x11:
7078 	case 0x12:
7079 		/*
7080 		 * QIC-120, QIC-150, QIC-320, QIC-600
7081 		 */
7082 		sizestr = cart;
7083 		un->un_dp->type = ST_TYPE_DEFAULT;
7084 		un->un_dp->options |= ST_QIC;
7085 		un->un_dp->densities[0] = 0x0f;
7086 		un->un_dp->densities[1] = 0x10;
7087 		un->un_dp->densities[2] = 0x11;
7088 		un->un_dp->densities[3] = 0x12;
7089 		break;
7090 
7091 	case 0x09:
7092 	case 0x0a:
7093 	case 0x0c:
7094 	case 0x0d:
7095 		/*
7096 		 * 1/2" cartridge tapes. Include HI-TC.
7097 		 */
7098 		sizestr = cart;
7099 		sizestr[2] = '5';
7100 		sizestr[3] = '0';
7101 		un->un_dp->type = ST_TYPE_HIC;
7102 		un->un_dp->densities[0] = 0x09;
7103 		un->un_dp->densities[1] = 0x0a;
7104 		un->un_dp->densities[2] = 0x0c;
7105 		un->un_dp->densities[3] = 0x0d;
7106 		break;
7107 
7108 	case 0x13:
7109 			/* DDS-2/DDS-3 scsi spec densities */
7110 	case 0x24:
7111 	case 0x25:
7112 	case 0x26:
7113 		sizestr = "DAT Data Storage (DDS)";
7114 		un->un_dp->type = ST_TYPE_DAT;
7115 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7116 		break;
7117 
7118 	case 0x14:
7119 		/*
7120 		 * Helical Scan (Exabyte) devices
7121 		 */
7122 		sizestr = "8mm helical scan cartridge";
7123 		un->un_dp->type = ST_TYPE_EXABYTE;
7124 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7125 		break;
7126 	}
7127 
7128 	/*
7129 	 * Assume LONG ERASE, BSF and BSR
7130 	 */
7131 
7132 	un->un_dp->options |=
7133 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
7134 
7135 	/*
7136 	 * Only if mode sense data says no buffered write, set NOBUF
7137 	 */
7138 	if (un->un_mspl->bufm == 0)
7139 		un->un_dp->options |= ST_NOBUF;
7140 
7141 	/*
7142 	 * set up large read and write retry counts
7143 	 */
7144 
7145 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
7146 
7147 	/*
7148 	 * If this is a 0.50 inch reel tape, and
7149 	 * it is *not* variable mode, try and
7150 	 * set it to variable record length
7151 	 * mode.
7152 	 */
7153 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
7154 	    (un->un_dp->options & ST_VARIABLE)) {
7155 		if (st_change_block_size(un, 0) == 0) {
7156 			un->un_dp->bsize = 0;
7157 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
7158 			    un->un_mspl->low_bl = 0;
7159 		}
7160 	}
7161 
7162 	/*
7163 	 * Write to console about type of device found
7164 	 */
7165 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
7166 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
7167 	    sizestr);
7168 	if (un->un_dp->options & ST_VARIABLE) {
7169 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7170 		    "!Variable record length I/O\n");
7171 	} else {
7172 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7173 		    "!Fixed record length (%d byte blocks) I/O\n",
7174 		    un->un_dp->bsize);
7175 	}
7176 	ASSERT(mutex_owned(ST_MUTEX));
7177 	return (0);
7178 }
7179 
7180 static int
7181 st_determine_density(struct scsi_tape *un, int rw)
7182 {
7183 	int rval = 0;
7184 
7185 	ST_FUNC(ST_DEVINFO, st_determine_density);
7186 
7187 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7188 	    "st_determine_density(un = 0x%p, rw = %s)\n",
7189 	    (void*)un, (rw == B_WRITE ? wr_str: rd_str));
7190 
7191 	ASSERT(mutex_owned(ST_MUTEX));
7192 
7193 	/*
7194 	 * If we're past BOT, density is determined already.
7195 	 */
7196 	if (un->un_pos.pmode == logical) {
7197 		if (un->un_pos.lgclblkno != 0) {
7198 			goto exit;
7199 		}
7200 	} else if (un->un_pos.pmode == legacy) {
7201 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
7202 			/*
7203 			 * XXX: put in a bitch message about attempting to
7204 			 * XXX: change density past BOT.
7205 			 */
7206 			goto exit;
7207 		}
7208 	} else {
7209 		goto exit;
7210 	}
7211 	if ((un->un_pos.pmode == logical) &&
7212 	    (un->un_pos.lgclblkno != 0)) {
7213 		goto exit;
7214 	}
7215 
7216 
7217 	/*
7218 	 * If we're going to be writing, we set the density
7219 	 */
7220 	if (rw == 0 || rw == B_WRITE) {
7221 		/* un_curdens is used as an index into densities table */
7222 		un->un_curdens = MT_DENSITY(un->un_dev);
7223 		if (st_set_density(un)) {
7224 			rval = -1;
7225 		}
7226 		goto exit;
7227 	}
7228 
7229 	/*
7230 	 * If density is known already,
7231 	 * we don't have to get it again.(?)
7232 	 */
7233 	if (!un->un_density_known) {
7234 		if (st_get_density(un)) {
7235 			rval = -1;
7236 		}
7237 	}
7238 
7239 exit:
7240 	ASSERT(mutex_owned(ST_MUTEX));
7241 	return (rval);
7242 }
7243 
7244 
7245 /*
7246  * Try to determine density. We do this by attempting to read the
7247  * first record off the tape, cycling through the available density
7248  * codes as we go.
7249  */
7250 
7251 static int
7252 st_get_density(struct scsi_tape *un)
7253 {
7254 	int succes = 0, rval = -1, i;
7255 	uint_t size;
7256 	uchar_t dens, olddens;
7257 
7258 	ST_FUNC(ST_DEVINFO, st_get_density);
7259 
7260 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7261 	    "st_get_density(un = 0x%p)\n", (void*)un);
7262 
7263 	ASSERT(mutex_owned(ST_MUTEX));
7264 
7265 	/*
7266 	 * If Auto Density override is enabled The drive has
7267 	 * only one density and there is no point in attempting
7268 	 * find the correct one.
7269 	 *
7270 	 * Since most modern drives auto detect the density
7271 	 * and format of the recorded media before they come
7272 	 * ready. What this function does is a legacy behavior
7273 	 * and modern drives not only don't need it, The backup
7274 	 * utilities that do positioning via uscsi find the un-
7275 	 * expected rewinds problematic.
7276 	 *
7277 	 * The drives that need this are old reel to reel devices.
7278 	 * I took a swag and said they must be scsi-1 or older.
7279 	 * I don't beleave there will any of the newer devices
7280 	 * that need this. There will be some scsi-1 devices that
7281 	 * don't need this but I don't think they will be using the
7282 	 * BIG aftermarket backup and restore utilitys.
7283 	 */
7284 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
7285 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
7286 		un->un_density_known = 1;
7287 		rval = 0;
7288 		goto exit;
7289 	}
7290 
7291 	/*
7292 	 * This will only work on variable record length tapes
7293 	 * if and only if all variable record length tapes autodensity
7294 	 * select.
7295 	 */
7296 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
7297 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
7298 
7299 	/*
7300 	 * Start at the specified density
7301 	 */
7302 
7303 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
7304 
7305 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
7306 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
7307 		/*
7308 		 * If we've done this density before,
7309 		 * don't bother to do it again.
7310 		 */
7311 		dens = un->un_dp->densities[un->un_curdens];
7312 		if (i > 0 && dens == olddens)
7313 			continue;
7314 		olddens = dens;
7315 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7316 		    "trying density 0x%x\n", dens);
7317 		if (st_set_density(un)) {
7318 			continue;
7319 		}
7320 
7321 		/*
7322 		 * XXX - the creates lots of headaches and slowdowns - must
7323 		 * fix.
7324 		 */
7325 		succes = (st_cmd(un, SCMD_READ, (int)size, SYNC_CMD) == 0);
7326 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
7327 			break;
7328 		}
7329 		if (succes) {
7330 			st_init(un);
7331 			rval = 0;
7332 			un->un_density_known = 1;
7333 			break;
7334 		}
7335 	}
7336 	kmem_free(un->un_tmpbuf, size);
7337 	un->un_tmpbuf = 0;
7338 
7339 exit:
7340 	ASSERT(mutex_owned(ST_MUTEX));
7341 	return (rval);
7342 }
7343 
7344 static int
7345 st_set_density(struct scsi_tape *un)
7346 {
7347 	int rval = 0;
7348 
7349 	ST_FUNC(ST_DEVINFO, st_set_density);
7350 
7351 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7352 	    "st_set_density(un = 0x%p): density = 0x%x\n", (void*)un,
7353 	    un->un_dp->densities[un->un_curdens]);
7354 
7355 	ASSERT(mutex_owned(ST_MUTEX));
7356 
7357 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7358 
7359 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
7360 		/*
7361 		 * If auto density override is not set, Use mode select
7362 		 * to set density and compression.
7363 		 */
7364 		if (st_modeselect(un)) {
7365 			rval = -1;
7366 		}
7367 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
7368 		/*
7369 		 * If auto density and mode select compression are set,
7370 		 * This is a drive with one density code but compression
7371 		 * can be enabled or disabled.
7372 		 * Set compression but no need to set density.
7373 		 */
7374 		rval = st_set_compression(un);
7375 		if ((rval != 0) && (rval != EALREADY)) {
7376 			rval = -1;
7377 		} else {
7378 			rval = 0;
7379 		}
7380 	}
7381 
7382 	/* If sucessful set density and/or compression, mark density known */
7383 	if (rval == 0) {
7384 		un->un_density_known = 1;
7385 	}
7386 
7387 	ASSERT(mutex_owned(ST_MUTEX));
7388 	return (rval);
7389 }
7390 
7391 static int
7392 st_loadtape(struct scsi_tape *un)
7393 {
7394 	int rval;
7395 
7396 	ST_FUNC(ST_DEVINFO, st_loadtape);
7397 
7398 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7399 	    "st_loadtape(un = 0x%p)\n", (void*) un);
7400 
7401 	ASSERT(mutex_owned(ST_MUTEX));
7402 
7403 	rval = st_update_block_pos(un, st_cmd, 0);
7404 	if (rval == EACCES) {
7405 		return (rval);
7406 	}
7407 
7408 	/*
7409 	 * 'LOAD' the tape to BOT by rewinding
7410 	 */
7411 	rval = st_cmd(un, SCMD_REWIND, 1, SYNC_CMD);
7412 	if (rval == 0) {
7413 		st_init(un);
7414 		un->un_density_known = 0;
7415 	}
7416 
7417 	ASSERT(mutex_owned(ST_MUTEX));
7418 	return (rval);
7419 }
7420 
7421 
7422 /*
7423  * Note: QIC devices aren't so smart.  If you try to append
7424  * after EOM, the write can fail because the device doesn't know
7425  * it's at EOM.	 In that case, issue a read.  The read should fail
7426  * because there's no data, but the device knows it's at EOM,
7427  * so a subsequent write should succeed.  To further confuse matters,
7428  * the target returns the same error if the tape is positioned
7429  * such that a write would overwrite existing data.  That's why
7430  * we have to do the append test.  A read in the middle of
7431  * recorded data would succeed, thus indicating we're attempting
7432  * something illegal.
7433  */
7434 
7435 
7436 static void
7437 st_test_append(struct buf *bp)
7438 {
7439 	dev_t dev = bp->b_edev;
7440 	struct scsi_tape *un;
7441 	uchar_t status;
7442 	unsigned bcount;
7443 
7444 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7445 
7446 	ST_FUNC(ST_DEVINFO, st_test_append);
7447 
7448 	ASSERT(mutex_owned(ST_MUTEX));
7449 
7450 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7451 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7452 
7453 	un->un_laststate = un->un_state;
7454 	un->un_state = ST_STATE_APPEND_TESTING;
7455 	un->un_test_append = 0;
7456 
7457 	/*
7458 	 * first, map in the buffer, because we're doing a double write --
7459 	 * first into the kernel, then onto the tape.
7460 	 */
7461 	bp_mapin(bp);
7462 
7463 	/*
7464 	 * get a copy of the data....
7465 	 */
7466 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7467 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7468 
7469 	/*
7470 	 * attempt the write..
7471 	 */
7472 
7473 	if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7474 success:
7475 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7476 		    "append write succeeded\n");
7477 		bp->b_resid = un->un_sbufp->b_resid;
7478 		mutex_exit(ST_MUTEX);
7479 		bcount = (unsigned)bp->b_bcount;
7480 		biodone(bp);
7481 		mutex_enter(ST_MUTEX);
7482 		un->un_laststate = un->un_state;
7483 		un->un_state = ST_STATE_OPEN;
7484 		kmem_free(un->un_tmpbuf, bcount);
7485 		un->un_tmpbuf = NULL;
7486 		return;
7487 	}
7488 
7489 	/*
7490 	 * The append failed. Do a short read. If that fails,  we are at EOM
7491 	 * so we can retry the write command. If that succeeds, than we're
7492 	 * all screwed up (the controller reported a real error).
7493 	 *
7494 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7495 	 * XXX: block size?
7496 	 *
7497 	 */
7498 	status = un->un_status;
7499 	un->un_status = 0;
7500 	(void) st_cmd(un, SCMD_READ, SECSIZE, SYNC_CMD);
7501 	if (un->un_status == KEY_BLANK_CHECK) {
7502 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7503 		    "append at EOM\n");
7504 		/*
7505 		 * Okay- the read failed. We should actually have confused
7506 		 * the controller enough to allow writing. In any case, the
7507 		 * i/o is on its own from here on out.
7508 		 */
7509 		un->un_laststate = un->un_state;
7510 		un->un_state = ST_STATE_OPEN;
7511 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7512 		if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount,
7513 		    SYNC_CMD) == 0) {
7514 			goto success;
7515 		}
7516 	}
7517 
7518 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7519 	    "append write failed- not at EOM\n");
7520 	bp->b_resid = bp->b_bcount;
7521 	st_bioerror(bp, EIO);
7522 
7523 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7524 	    "st_test_append : EIO : append write failed - not at EOM");
7525 
7526 	/*
7527 	 * backspace one record to get back to where we were
7528 	 */
7529 	if (st_cmd(un, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7530 		un->un_pos.pmode = invalid;
7531 	}
7532 
7533 	un->un_err_resid = bp->b_resid;
7534 	un->un_status = status;
7535 
7536 	/*
7537 	 * Note: biodone will do a bp_mapout()
7538 	 */
7539 	mutex_exit(ST_MUTEX);
7540 	bcount = (unsigned)bp->b_bcount;
7541 	biodone(bp);
7542 	mutex_enter(ST_MUTEX);
7543 	un->un_laststate = un->un_state;
7544 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7545 	kmem_free(un->un_tmpbuf, bcount);
7546 	un->un_tmpbuf = NULL;
7547 }
7548 
7549 /*
7550  * Special command handler
7551  */
7552 
7553 /*
7554  * common st_cmd code. The fourth parameter states
7555  * whether the caller wishes to await the results
7556  * Note the release of the mutex during most of the function
7557  */
7558 static int
7559 st_cmd(struct scsi_tape *un, int com, int64_t count, int wait)
7560 {
7561 	struct buf *bp;
7562 	int err;
7563 	uint_t last_err_resid;
7564 
7565 	ST_FUNC(ST_DEVINFO, st_cmd);
7566 
7567 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7568 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %"PRIx64", wait = %d)\n",
7569 	    un->un_dev, com, count, wait);
7570 
7571 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7572 	ASSERT(mutex_owned(ST_MUTEX));
7573 
7574 #ifdef STDEBUG
7575 	if ((st_debug & 0x7)) {
7576 		st_debug_cmds(un, com, count, wait);
7577 	}
7578 #endif
7579 
7580 	st_wait_for_io(un);
7581 
7582 	/* check to see if this command requires the drive to be reserved */
7583 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7584 
7585 	if (err) {
7586 		return (err);
7587 	}
7588 
7589 	/*
7590 	 * A space command is not recoverable if we don't know were we
7591 	 * were when it was issued.
7592 	 */
7593 	if ((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) {
7594 		(void) st_update_block_pos(un, st_cmd, 0);
7595 	}
7596 
7597 	/*
7598 	 * Forground should not be doing anything while recovery is active.
7599 	 */
7600 	ASSERT(un->un_recov_buf_busy == 0);
7601 
7602 	while (un->un_sbuf_busy)
7603 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7604 	un->un_sbuf_busy = 1;
7605 
7606 	bp = un->un_sbufp;
7607 	bzero(bp, sizeof (buf_t));
7608 
7609 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7610 
7611 	err = st_setup_cmd(un, bp, com, count);
7612 
7613 	un->un_sbuf_busy = 0;
7614 
7615 	/*
7616 	 * If was a space command need to update logical block position.
7617 	 * Only do this if the command was sucessful or it will mask the fact
7618 	 * that the space command failed by promoting the pmode to logical.
7619 	 */
7620 	if (((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) &&
7621 	    (un->un_pos.pmode != invalid)) {
7622 		un->un_running.pmode = invalid;
7623 		last_err_resid = un->un_err_resid;
7624 		(void) st_update_block_pos(un, st_cmd, 1);
7625 		/*
7626 		 * Set running position to invalid so it updates on the
7627 		 * next command.
7628 		 */
7629 		un->un_running.pmode = invalid;
7630 		un->un_err_resid = last_err_resid;
7631 	}
7632 
7633 	cv_signal(&un->un_sbuf_cv);
7634 
7635 	return (err);
7636 }
7637 
7638 static int
7639 st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com, int64_t count)
7640 {
7641 	int err;
7642 	dev_t dev = un->un_dev;
7643 
7644 	ST_FUNC(ST_DEVINFO, st_setup_cmd);
7645 	/*
7646 	 * Set count to the actual size of the data tranfer.
7647 	 * For commands with no data transfer, set bp->b_bcount
7648 	 * to the value to be used when constructing the
7649 	 * cdb in st_make_cmd().
7650 	 */
7651 	switch (com) {
7652 	case SCMD_READ:
7653 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7654 		    "special read %"PRId64"\n", count);
7655 		bp->b_flags |= B_READ;
7656 		bp->b_un.b_addr = un->un_tmpbuf;
7657 		break;
7658 
7659 	case SCMD_WRITE:
7660 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7661 		    "special write %"PRId64"\n", count);
7662 		bp->b_un.b_addr = un->un_tmpbuf;
7663 		break;
7664 
7665 	case SCMD_WRITE_FILE_MARK:
7666 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7667 		    "write %"PRId64" file marks\n", count);
7668 		bp->b_bcount = count;
7669 		count = 0;
7670 		break;
7671 
7672 	case SCMD_REWIND:
7673 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7674 		bp->b_bcount = count;
7675 		count = 0;
7676 		break;
7677 
7678 	case SCMD_SPACE:
7679 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7680 		/*
7681 		 * If the user could have entered a number that will
7682 		 * not fit in the 12 bit count field of space(8),
7683 		 * use space(16).
7684 		 */
7685 		if (((int64_t)SPACE_CNT(count) > 0x7fffff) ||
7686 		    ((int64_t)SPACE_CNT(count) < -(0x7fffff))) {
7687 			com = SCMD_SPACE_G4;
7688 		}
7689 		bp->b_bcount = count;
7690 		count = 0;
7691 		break;
7692 
7693 	case SCMD_RESERVE:
7694 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7695 		bp->b_bcount = 0;
7696 		count = 0;
7697 		break;
7698 
7699 	case SCMD_RELEASE:
7700 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7701 		bp->b_bcount = 0;
7702 		count = 0;
7703 		break;
7704 
7705 	case SCMD_LOAD:
7706 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7707 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7708 		bp->b_bcount = count;
7709 		count = 0;
7710 		break;
7711 
7712 	case SCMD_ERASE:
7713 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7714 		    "erase tape\n");
7715 		bp->b_bcount = count;
7716 		count = 0;
7717 		break;
7718 
7719 	case SCMD_MODE_SENSE:
7720 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7721 		    "mode sense\n");
7722 		bp->b_flags |= B_READ;
7723 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7724 		break;
7725 
7726 	case SCMD_MODE_SELECT:
7727 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7728 		    "mode select\n");
7729 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7730 		break;
7731 
7732 	case SCMD_READ_BLKLIM:
7733 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7734 		    "read block limits\n");
7735 		bp->b_bcount = count;
7736 		bp->b_flags |= B_READ;
7737 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7738 		break;
7739 
7740 	case SCMD_TEST_UNIT_READY:
7741 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7742 		    "test unit ready\n");
7743 		bp->b_bcount = 0;
7744 		count = 0;
7745 		break;
7746 
7747 	case SCMD_DOORLOCK:
7748 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7749 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7750 		bp->b_bcount = count = 0;
7751 		break;
7752 
7753 	case SCMD_READ_POSITION:
7754 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7755 		    "read position\n");
7756 		switch (un->un_read_pos_type) {
7757 		case LONG_POS:
7758 			count = sizeof (tape_position_long_t);
7759 			break;
7760 		case EXT_POS:
7761 			count = min(count, sizeof (tape_position_ext_t));
7762 			break;
7763 		case SHORT_POS:
7764 			count = sizeof (tape_position_t);
7765 			break;
7766 		default:
7767 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7768 			    "Unknown read position type 0x%x in "
7769 			    "st_make_cmd()\n", un->un_read_pos_type);
7770 		}
7771 		bp->b_bcount = count;
7772 		bp->b_flags |= B_READ;
7773 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7774 		break;
7775 
7776 	default:
7777 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7778 		    "Unhandled scsi command 0x%x in st_setup_cmd()\n", com);
7779 	}
7780 
7781 	mutex_exit(ST_MUTEX);
7782 
7783 	if (count > 0) {
7784 		int flg = (bp->b_flags & B_READ) ? B_READ : B_WRITE;
7785 		/*
7786 		 * We're going to do actual I/O.
7787 		 * Set things up for physio.
7788 		 */
7789 		struct iovec aiov;
7790 		struct uio auio;
7791 		struct uio *uio = &auio;
7792 
7793 		bzero(&auio, sizeof (struct uio));
7794 		bzero(&aiov, sizeof (struct iovec));
7795 		aiov.iov_base = bp->b_un.b_addr;
7796 		aiov.iov_len = count;
7797 
7798 		uio->uio_iov = &aiov;
7799 		uio->uio_iovcnt = 1;
7800 		uio->uio_resid = aiov.iov_len;
7801 		uio->uio_segflg = UIO_SYSSPACE;
7802 
7803 		/*
7804 		 * Let physio do the rest...
7805 		 */
7806 		bp->b_forw = (struct buf *)(uintptr_t)com;
7807 		bp->b_back = NULL;
7808 		err = physio(st_strategy, bp, dev, flg, st_minphys, uio);
7809 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7810 		    "st_setup_cmd: physio returns %d\n", err);
7811 	} else {
7812 		/*
7813 		 * Mimic physio
7814 		 */
7815 		bp->b_forw = (struct buf *)(uintptr_t)com;
7816 		bp->b_back = NULL;
7817 		bp->b_edev = dev;
7818 		bp->b_dev = cmpdev(dev);
7819 		bp->b_blkno = 0;
7820 		bp->b_resid = 0;
7821 		(void) st_strategy(bp);
7822 		if (bp->b_flags & B_ASYNC) {
7823 			/*
7824 			 * This is an async command- the caller won't wait
7825 			 * and doesn't care about errors.
7826 			 */
7827 			mutex_enter(ST_MUTEX);
7828 			return (0);
7829 		}
7830 
7831 		/*
7832 		 * BugTraq #4260046
7833 		 * ----------------
7834 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7835 		 * unconditionally. The old comment said...
7836 		 *
7837 		 * "if strategy was flagged with  persistent errors, we would
7838 		 *  have an error here, and the bp would never be sent, so we
7839 		 *  don't want to wait on a bp that was never sent...or hang"
7840 		 *
7841 		 * The new rationale, courtesy of Chitrank...
7842 		 *
7843 		 * "we should unconditionally biowait() here because
7844 		 *  st_strategy() will do a biodone() in the persistent error
7845 		 *  case and the following biowait() will return immediately.
7846 		 *  If not, in the case of "errors after pkt alloc" in
7847 		 *  st_start(), we will not biowait here which will cause the
7848 		 *  next biowait() to return immediately which will cause
7849 		 *  us to send out the next command. In the case where both of
7850 		 *  these use the sbuf, when the first command completes we'll
7851 		 *  free the packet attached to sbuf and the same pkt will
7852 		 *  get freed again when we complete the second command.
7853 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7854 		 *  st_start() for the pkt alloc failure case because physio()
7855 		 *  does biowait() and will hang if we don't do biodone()"
7856 		 */
7857 
7858 		err = biowait(bp);
7859 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7860 		    "st_setup_cmd: biowait returns %d\n", err);
7861 	}
7862 
7863 	mutex_enter(ST_MUTEX);
7864 
7865 	return (err);
7866 }
7867 
7868 static int
7869 st_set_compression(struct scsi_tape *un)
7870 {
7871 	int rval;
7872 	int turn_compression_on;
7873 	minor_t minor;
7874 
7875 	ST_FUNC(ST_DEVINFO, st_set_compression);
7876 
7877 	/*
7878 	 * Drive either dosn't have compression or it is controlled with
7879 	 * special density codes. Return ENOTTY so caller
7880 	 * knows nothing was done.
7881 	 */
7882 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7883 		un->un_comp_page = 0;
7884 		return (ENOTTY);
7885 	}
7886 
7887 	/* set compression based on minor node opened */
7888 	minor = MT_DENSITY(un->un_dev);
7889 
7890 	/*
7891 	 * If this the compression density or
7892 	 * the drive has two densities and uses mode select for
7893 	 * control of compression turn on compression for MT_DENSITY2
7894 	 * as well.
7895 	 */
7896 	if ((minor == ST_COMPRESSION_DENSITY) ||
7897 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7898 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7899 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7900 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7901 
7902 		turn_compression_on = 1;
7903 	} else {
7904 		turn_compression_on = 0;
7905 	}
7906 
7907 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7908 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7909 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7910 
7911 	/*
7912 	 * Need to determine which page does the device use for compression.
7913 	 * First try the data compression page. If this fails try the device
7914 	 * configuration page
7915 	 */
7916 
7917 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7918 		rval = st_set_datacomp_page(un, turn_compression_on);
7919 		if (rval == EALREADY) {
7920 			return (rval);
7921 		}
7922 		if (rval != 0) {
7923 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7924 				/*
7925 				 * This device does not support data
7926 				 * compression page
7927 				 */
7928 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7929 			} else if (un->un_state >= ST_STATE_OPEN) {
7930 				un->un_pos.pmode = invalid;
7931 				rval = EIO;
7932 			} else {
7933 				rval = -1;
7934 			}
7935 		} else {
7936 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7937 		}
7938 	}
7939 
7940 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7941 		rval = st_set_devconfig_page(un, turn_compression_on);
7942 		if (rval == EALREADY) {
7943 			return (rval);
7944 		}
7945 		if (rval != 0) {
7946 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7947 				/*
7948 				 * This device does not support
7949 				 * compression at all advice the
7950 				 * user and unset ST_MODE_SEL_COMP
7951 				 */
7952 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7953 				un->un_comp_page = 0;
7954 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7955 				    "Device Does Not Support Compression\n");
7956 			} else if (un->un_state >= ST_STATE_OPEN) {
7957 				un->un_pos.pmode = invalid;
7958 				rval = EIO;
7959 			} else {
7960 				rval = -1;
7961 			}
7962 		}
7963 	}
7964 
7965 	return (rval);
7966 }
7967 
7968 /*
7969  * set or unset compression thru device configuration page.
7970  */
7971 static int
7972 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
7973 {
7974 	unsigned char cflag;
7975 	int rval = 0;
7976 
7977 
7978 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
7979 
7980 	ASSERT(mutex_owned(ST_MUTEX));
7981 	/*
7982 	 * Figure what to set compression flag to.
7983 	 */
7984 	if (compression_on) {
7985 		/* They have selected a compression node */
7986 		if (un->un_dp->type == ST_TYPE_FUJI) {
7987 			cflag = 0x84;   /* use EDRC */
7988 		} else {
7989 			cflag = ST_DEV_CONFIG_DEF_COMP;
7990 		}
7991 	} else {
7992 		cflag = ST_DEV_CONFIG_NO_COMP;
7993 	}
7994 
7995 	/*
7996 	 * If compression is already set the way it was requested.
7997 	 * And if this not the first time we has tried.
7998 	 */
7999 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
8000 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
8001 		return (EALREADY);
8002 	}
8003 
8004 	un->un_mspl->page.dev.comp_alg = cflag;
8005 	/*
8006 	 * need to send mode select even if correct compression is
8007 	 * already set since need to set density code
8008 	 */
8009 
8010 #ifdef STDEBUG
8011 	if ((st_debug & 0x7) >= 6) {
8012 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8013 		    "st_set_devconfig_page: sense data for mode select",
8014 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8015 	}
8016 #endif
8017 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8018 	    sizeof (struct seq_mode));
8019 
8020 	return (rval);
8021 }
8022 
8023 /*
8024  * set/reset compression bit thru data compression page
8025  */
8026 static int
8027 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
8028 {
8029 	int compression_on_already;
8030 	int rval = 0;
8031 
8032 
8033 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
8034 
8035 	ASSERT(mutex_owned(ST_MUTEX));
8036 	/*
8037 	 * If drive is not capable of compression (at this time)
8038 	 * return EALREADY so caller doesn't think that this page
8039 	 * is not supported. This check is for drives that can
8040 	 * disable compression from the front panel or configuration.
8041 	 * I doubt that a drive that supports this page is not really
8042 	 * capable of compression.
8043 	 */
8044 	if (un->un_mspl->page.comp.dcc == 0) {
8045 		return (EALREADY);
8046 	}
8047 
8048 	/* See if compression currently turned on */
8049 	if (un->un_mspl->page.comp.dce) {
8050 		compression_on_already = 1;
8051 	} else {
8052 		compression_on_already = 0;
8053 	}
8054 
8055 	/*
8056 	 * If compression is already set the way it was requested.
8057 	 * And if this not the first time we has tried.
8058 	 */
8059 	if ((compression_on == compression_on_already) &&
8060 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
8061 		return (EALREADY);
8062 	}
8063 
8064 	/*
8065 	 * if we are already set to the appropriate compression
8066 	 * mode, don't set it again
8067 	 */
8068 	if (compression_on) {
8069 		/* compression selected */
8070 		un->un_mspl->page.comp.dce = 1;
8071 	} else {
8072 		un->un_mspl->page.comp.dce = 0;
8073 	}
8074 
8075 
8076 #ifdef STDEBUG
8077 	if ((st_debug & 0x7) >= 6) {
8078 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8079 		    "st_set_datacomp_page: sense data for mode select",
8080 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8081 	}
8082 #endif
8083 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8084 	    sizeof (struct seq_mode));
8085 
8086 	return (rval);
8087 }
8088 
8089 static int
8090 st_modesense(struct scsi_tape *un)
8091 {
8092 	int rval;
8093 	uchar_t page;
8094 
8095 	ST_FUNC(ST_DEVINFO, st_modesense);
8096 
8097 	page = un->un_comp_page;
8098 
8099 	switch (page) {
8100 	case ST_DEV_DATACOMP_PAGE:
8101 	case ST_DEV_CONFIG_PAGE: /* FALLTHROUGH */
8102 		rval = st_gen_mode_sense(un, st_uscsi_cmd, page, un->un_mspl,
8103 		    sizeof (struct seq_mode));
8104 		break;
8105 
8106 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
8107 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
8108 			page = ST_DEV_CONFIG_PAGE;
8109 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8110 			    un->un_mspl, sizeof (struct seq_mode));
8111 			if (rval == 0 && un->un_mspl->page_code == page) {
8112 				un->un_comp_page = page;
8113 				break;
8114 			}
8115 			page = ST_DEV_DATACOMP_PAGE;
8116 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8117 			    un->un_mspl, sizeof (struct seq_mode));
8118 			if (rval == 0 && un->un_mspl->page_code == page) {
8119 				un->un_comp_page = page;
8120 				break;
8121 			}
8122 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
8123 			un->un_comp_page = 0;
8124 		} else {
8125 			un->un_comp_page = 0;
8126 		}
8127 
8128 	default:	/* FALLTHROUGH */
8129 		rval = st_cmd(un, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
8130 	}
8131 	return (rval);
8132 }
8133 
8134 static int
8135 st_modeselect(struct scsi_tape *un)
8136 {
8137 	int rval = 0;
8138 	int ix;
8139 
8140 	ST_FUNC(ST_DEVINFO, st_modeselect);
8141 
8142 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8143 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
8144 	    un->un_dev, un->un_mspl->density);
8145 
8146 	ASSERT(mutex_owned(ST_MUTEX));
8147 
8148 	/*
8149 	 * The parameter list should be the same for all of the
8150 	 * cases that follow so set them here
8151 	 *
8152 	 * Try mode select first if if fails set fields manually
8153 	 */
8154 	rval = st_modesense(un);
8155 	if (rval != 0) {
8156 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8157 		    "st_modeselect: First mode sense failed\n");
8158 		un->un_mspl->bd_len  = 8;
8159 		un->un_mspl->high_nb = 0;
8160 		un->un_mspl->mid_nb  = 0;
8161 		un->un_mspl->low_nb  = 0;
8162 	}
8163 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
8164 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
8165 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
8166 
8167 
8168 	/*
8169 	 * If configured to use a specific density code for a media type.
8170 	 * curdens is previously set by the minor node opened.
8171 	 * If the media type doesn't match the minor node we change it so it
8172 	 * looks like the correct one was opened.
8173 	 */
8174 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
8175 		uchar_t best;
8176 
8177 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
8178 			if (un->un_mspl->media_type ==
8179 			    un->un_dp->mediatype[ix]) {
8180 				best = ix;
8181 				/*
8182 				 * It matches but it might not be the only one.
8183 				 * Use the highest matching media type but not
8184 				 * to exceed the density selected by the open.
8185 				 */
8186 				if (ix < un->un_curdens) {
8187 					continue;
8188 				}
8189 				un->un_curdens = ix;
8190 				break;
8191 			}
8192 		}
8193 		/* If a match was found best will not be 0xff any more */
8194 		if (best < NDENSITIES) {
8195 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8196 			    "found media 0x%X using density 0x%X\n",
8197 			    un->un_mspl->media_type,
8198 			    un->un_dp->densities[best]);
8199 			un->un_mspl->density = un->un_dp->densities[best];
8200 		} else {
8201 			/* Otherwise set density based on minor node opened */
8202 			un->un_mspl->density =
8203 			    un->un_dp->densities[un->un_curdens];
8204 		}
8205 	} else {
8206 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
8207 	}
8208 
8209 	if (un->un_dp->options & ST_NOBUF) {
8210 		un->un_mspl->bufm = 0;
8211 	} else {
8212 		un->un_mspl->bufm = 1;
8213 	}
8214 
8215 	rval = st_set_compression(un);
8216 
8217 	/*
8218 	 * If st_set_compression returned invalid or already it
8219 	 * found no need to do the mode select.
8220 	 * So do it here.
8221 	 */
8222 	if ((rval == ENOTTY) || (rval == EALREADY)) {
8223 
8224 		/* Zero non-writeable fields */
8225 		un->un_mspl->data_len = 0;
8226 		un->un_mspl->media_type = 0;
8227 		un->un_mspl->wp = 0;
8228 
8229 		/* need to set the density code */
8230 		rval = st_cmd(un, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
8231 		if (rval != 0) {
8232 			if (un->un_state >= ST_STATE_OPEN) {
8233 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8234 				    "unable to set tape mode\n");
8235 				un->un_pos.pmode = invalid;
8236 				rval = EIO;
8237 			} else {
8238 				rval = -1;
8239 			}
8240 		}
8241 	}
8242 
8243 	/*
8244 	 * The spec recommends to send a mode sense after a mode select
8245 	 */
8246 	(void) st_modesense(un);
8247 
8248 	ASSERT(mutex_owned(ST_MUTEX));
8249 
8250 	return (rval);
8251 }
8252 
8253 /*
8254  * st_gen_mode_sense
8255  *
8256  * generic mode sense.. it allows for any page
8257  */
8258 static int
8259 st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
8260     struct seq_mode *page_data, int page_size)
8261 {
8262 
8263 	int r;
8264 	char	cdb[CDB_GROUP0];
8265 	struct uscsi_cmd *com;
8266 	struct scsi_arq_status status;
8267 
8268 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
8269 
8270 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8271 
8272 	bzero(cdb, CDB_GROUP0);
8273 	cdb[0] = SCMD_MODE_SENSE;
8274 	cdb[2] = (char)page;
8275 	cdb[4] = (char)page_size;
8276 
8277 	com->uscsi_cdb = cdb;
8278 	com->uscsi_cdblen = CDB_GROUP0;
8279 	com->uscsi_bufaddr = (caddr_t)page_data;
8280 	com->uscsi_buflen = page_size;
8281 	com->uscsi_rqlen = sizeof (status);
8282 	com->uscsi_rqbuf = (caddr_t)&status;
8283 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8284 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8285 
8286 	r = ubf(un, com, FKIOCTL);
8287 	kmem_free(com, sizeof (*com));
8288 	return (r);
8289 }
8290 
8291 /*
8292  * st_gen_mode_select
8293  *
8294  * generic mode select.. it allows for any page
8295  */
8296 static int
8297 st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
8298     struct seq_mode *page_data, int page_size)
8299 {
8300 
8301 	int r;
8302 	char cdb[CDB_GROUP0];
8303 	struct uscsi_cmd *com;
8304 	struct scsi_arq_status status;
8305 
8306 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
8307 
8308 	/* Zero non-writeable fields */
8309 	page_data->data_len = 0;
8310 	page_data->media_type = 0;
8311 	page_data->wp = 0;
8312 
8313 	/*
8314 	 * If mode select has any page data, zero the ps (Page Savable) bit.
8315 	 */
8316 	if (page_size > MSIZE) {
8317 		page_data->ps = 0;
8318 	}
8319 
8320 
8321 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8322 
8323 	/*
8324 	 * then, do a mode select to set what ever info
8325 	 */
8326 	bzero(cdb, CDB_GROUP0);
8327 	cdb[0] = SCMD_MODE_SELECT;
8328 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
8329 	cdb[4] = (char)page_size;
8330 
8331 	com->uscsi_cdb = cdb;
8332 	com->uscsi_cdblen = CDB_GROUP0;
8333 	com->uscsi_bufaddr = (caddr_t)page_data;
8334 	com->uscsi_buflen = page_size;
8335 	com->uscsi_rqlen = sizeof (status);
8336 	com->uscsi_rqbuf = (caddr_t)&status;
8337 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8338 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_WRITE;
8339 
8340 	r = ubf(un, com, FKIOCTL);
8341 
8342 	kmem_free(com, sizeof (*com));
8343 	return (r);
8344 }
8345 
8346 static int
8347 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
8348 {
8349 	int rval;
8350 	char cdb[CDB_GROUP0];
8351 	struct uscsi_cmd *com;
8352 	struct scsi_arq_status status;
8353 
8354 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
8355 
8356 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8357 
8358 	bzero(cdb, CDB_GROUP0);
8359 	cdb[0] = SCMD_READ_BLKLIM;
8360 
8361 	com->uscsi_cdb = cdb;
8362 	com->uscsi_cdblen = CDB_GROUP0;
8363 	com->uscsi_bufaddr = (caddr_t)read_blk;
8364 	com->uscsi_buflen = sizeof (struct read_blklim);
8365 	com->uscsi_rqlen = sizeof (status);
8366 	com->uscsi_rqbuf = (caddr_t)&status;
8367 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8368 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8369 
8370 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8371 	if (com->uscsi_status || com->uscsi_resid) {
8372 		rval = -1;
8373 	}
8374 
8375 	kmem_free(com, sizeof (*com));
8376 	return (rval);
8377 }
8378 
8379 static int
8380 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
8381     size_t buflen)
8382 {
8383 	int rval;
8384 	char cdb[CDB_GROUP1];
8385 	struct uscsi_cmd *com;
8386 	struct scsi_arq_status status;
8387 
8388 	ST_FUNC(ST_DEVINFO, st_report_density_support);
8389 
8390 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8391 
8392 	bzero(cdb, CDB_GROUP1);
8393 	cdb[0] = SCMD_REPORT_DENSITIES;
8394 	cdb[7] = (buflen & 0xff00) >> 8;
8395 	cdb[8] = buflen & 0xff;
8396 
8397 	com->uscsi_cdb = cdb;
8398 	com->uscsi_cdblen = CDB_GROUP1;
8399 	com->uscsi_bufaddr = (caddr_t)density_data;
8400 	com->uscsi_buflen = buflen;
8401 	com->uscsi_rqlen = sizeof (status);
8402 	com->uscsi_rqbuf = (caddr_t)&status;
8403 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8404 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8405 
8406 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8407 	if (com->uscsi_status || com->uscsi_resid) {
8408 		rval = -1;
8409 	}
8410 
8411 	kmem_free(com, sizeof (*com));
8412 	return (rval);
8413 }
8414 
8415 static int
8416 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
8417     uchar_t option_code, ushort_t service_action)
8418 {
8419 	int rval;
8420 	char cdb[CDB_GROUP5];
8421 	struct uscsi_cmd *com;
8422 	struct scsi_arq_status status;
8423 	uint32_t allo_length;
8424 
8425 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
8426 
8427 	allo_length = sizeof (struct one_com_des) +
8428 	    sizeof (struct com_timeout_des);
8429 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8430 
8431 	bzero(cdb, CDB_GROUP5);
8432 	cdb[0] = (char)SCMD_MAINTENANCE_IN;
8433 	cdb[1] = SSVC_ACTION_GET_SUPPORTED_OPERATIONS;
8434 	if (service_action) {
8435 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
8436 		cdb[4] = (service_action & 0xff00) >> 8;
8437 		cdb[5] = service_action & 0xff;
8438 	} else {
8439 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
8440 		    0x80); /* RCTD */
8441 	}
8442 	cdb[3] = option_code;
8443 	cdb[6] = (allo_length & 0xff000000) >> 24;
8444 	cdb[7] = (allo_length & 0xff0000) >> 16;
8445 	cdb[8] = (allo_length & 0xff00) >> 8;
8446 	cdb[9] = allo_length & 0xff;
8447 
8448 	com->uscsi_cdb = cdb;
8449 	com->uscsi_cdblen = CDB_GROUP5;
8450 	com->uscsi_bufaddr = (caddr_t)oper_data;
8451 	com->uscsi_buflen = allo_length;
8452 	com->uscsi_rqlen = sizeof (status);
8453 	com->uscsi_rqbuf = (caddr_t)&status;
8454 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8455 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8456 
8457 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8458 	if (com->uscsi_status) {
8459 		rval = -1;
8460 	}
8461 
8462 	kmem_free(com, sizeof (*com));
8463 	return (rval);
8464 }
8465 
8466 /*
8467  * Changes devices blocksize and bsize to requested blocksize nblksz.
8468  * Returns returned value from first failed call or zero on success.
8469  */
8470 static int
8471 st_change_block_size(struct scsi_tape *un, uint32_t nblksz)
8472 {
8473 	struct seq_mode *current;
8474 	int rval;
8475 	uint32_t oldblksz;
8476 
8477 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8478 
8479 	current = kmem_zalloc(MSIZE, KM_SLEEP);
8480 
8481 	/*
8482 	 * If we haven't got the compression page yet, do that first.
8483 	 */
8484 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
8485 		(void) st_modesense(un);
8486 	}
8487 
8488 	/* Read current settings */
8489 	rval = st_gen_mode_sense(un, st_uscsi_cmd, 0, current, MSIZE);
8490 	if (rval != 0) {
8491 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8492 		    "mode sense for change block size failed: rval = %d", rval);
8493 		goto finish;
8494 	}
8495 
8496 	/* Figure the current block size */
8497 	oldblksz =
8498 	    (current->high_bl << 16) |
8499 	    (current->mid_bl << 8) |
8500 	    (current->low_bl);
8501 
8502 	/* If current block size is the same as requested were done */
8503 	if (oldblksz == nblksz) {
8504 		un->un_bsize = nblksz;
8505 		rval = 0;
8506 		goto finish;
8507 	}
8508 
8509 	/* Change to requested block size */
8510 	current->high_bl = (uchar_t)(nblksz >> 16);
8511 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8512 	current->low_bl  = (uchar_t)(nblksz);
8513 
8514 	/* Attempt to change block size */
8515 	rval = st_gen_mode_select(un, st_uscsi_cmd, current, MSIZE);
8516 	if (rval != 0) {
8517 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8518 		    "Set new block size failed: rval = %d", rval);
8519 		goto finish;
8520 	}
8521 
8522 	/* Read back and verify setting */
8523 	rval = st_modesense(un);
8524 	if (rval == 0) {
8525 		un->un_bsize =
8526 		    (un->un_mspl->high_bl << 16) |
8527 		    (un->un_mspl->mid_bl << 8) |
8528 		    (un->un_mspl->low_bl);
8529 
8530 		if (un->un_bsize != nblksz) {
8531 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8532 			    "Blocksize set does not equal requested blocksize"
8533 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8534 			rval = EIO;
8535 		}
8536 	}
8537 finish:
8538 	kmem_free(current, MSIZE);
8539 	return (rval);
8540 }
8541 
8542 
8543 static void
8544 st_init(struct scsi_tape *un)
8545 {
8546 	ST_FUNC(ST_DEVINFO, st_init);
8547 
8548 	ASSERT(mutex_owned(ST_MUTEX));
8549 
8550 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8551 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8552 	    un->un_dev);
8553 
8554 	un->un_pos.blkno = 0;
8555 	un->un_pos.fileno = 0;
8556 	un->un_lastop = ST_OP_NIL;
8557 	un->un_pos.eof = ST_NO_EOF;
8558 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8559 	if (st_error_level != SCSI_ERR_ALL) {
8560 		if (DEBUGGING) {
8561 			st_error_level = SCSI_ERR_ALL;
8562 		} else {
8563 			st_error_level = SCSI_ERR_RETRYABLE;
8564 		}
8565 	}
8566 }
8567 
8568 
8569 static void
8570 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8571 {
8572 	struct scsi_pkt *pkt;
8573 	struct uscsi_cmd *ucmd;
8574 	recov_info *ri;
8575 	int tval = 0;
8576 	int64_t count;
8577 	uint32_t additional = 0;
8578 	uint32_t address = 0;
8579 	union scsi_cdb *ucdb;
8580 	int flags = 0;
8581 	int cdb_len = CDB_GROUP0; /* default */
8582 	uchar_t com;
8583 	char fixbit;
8584 	char short_fm = 0;
8585 	optype prev_op = un->un_lastop;
8586 	int stat_size =
8587 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
8588 
8589 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8590 
8591 	ASSERT(mutex_owned(ST_MUTEX));
8592 
8593 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8594 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8595 
8596 
8597 	/*
8598 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8599 	 * Length Indicator bits on read/write commands, for setting
8600 	 * the Long bit on erase commands, and for setting the Code
8601 	 * Field bits on space commands.
8602 	 */
8603 
8604 	/* regular raw I/O */
8605 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
8606 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8607 		    CDB_GROUP0, stat_size, st_recov_sz, 0, func,
8608 		    (caddr_t)un);
8609 		if (pkt == NULL) {
8610 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8611 			    "Read Write scsi_init_pkt() failure\n");
8612 			goto exit;
8613 		}
8614 		ASSERT(pkt->pkt_resid == 0);
8615 #ifdef STDEBUG
8616 		bzero(pkt->pkt_private, st_recov_sz);
8617 		bzero(pkt->pkt_scbp, stat_size);
8618 #endif
8619 		ri = (recov_info *)pkt->pkt_private;
8620 		ri->privatelen = st_recov_sz;
8621 		if (un->un_bsize == 0) {
8622 			count = bp->b_bcount;
8623 			fixbit = 0;
8624 		} else {
8625 			count = bp->b_bcount / un->un_bsize;
8626 			fixbit = 1;
8627 		}
8628 		if (bp->b_flags & B_READ) {
8629 			com = SCMD_READ;
8630 			un->un_lastop = ST_OP_READ;
8631 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8632 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8633 				fixbit = 2;
8634 			}
8635 		} else {
8636 			com = SCMD_WRITE;
8637 			un->un_lastop = ST_OP_WRITE;
8638 		}
8639 		tval = un->un_dp->io_timeout;
8640 
8641 		/*
8642 		 * For really large xfers, increase timeout
8643 		 */
8644 		if (bp->b_bcount > (10 * ONE_MEG))
8645 			tval *= bp->b_bcount/(10 * ONE_MEG);
8646 
8647 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8648 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8649 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8650 
8651 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8652 		/*
8653 		 * uscsi - build command, allocate scsi resources
8654 		 */
8655 		st_make_uscsi_cmd(un, ucmd, bp, func);
8656 		goto exit;
8657 
8658 	} else {				/* special I/O */
8659 		struct buf *allocbp = NULL;
8660 		com = (uchar_t)(uintptr_t)bp->b_forw;
8661 		count = bp->b_bcount;
8662 
8663 		switch (com) {
8664 		case SCMD_READ:
8665 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8666 			    "special read %"PRId64"\n", count);
8667 			if (un->un_bsize == 0) {
8668 				fixbit = 2;	/* suppress SILI */
8669 			} else {
8670 				fixbit = 1;	/* Fixed Block Mode */
8671 				count /= un->un_bsize;
8672 			}
8673 			allocbp = bp;
8674 			un->un_lastop = ST_OP_READ;
8675 			tval = un->un_dp->io_timeout;
8676 			break;
8677 
8678 		case SCMD_WRITE:
8679 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8680 			    "special write %"PRId64"\n", count);
8681 			if (un->un_bsize != 0) {
8682 				fixbit = 1;	/* Fixed Block Mode */
8683 				count /= un->un_bsize;
8684 			} else {
8685 				fixbit = 0;
8686 			}
8687 			allocbp = bp;
8688 			un->un_lastop = ST_OP_WRITE;
8689 			tval = un->un_dp->io_timeout;
8690 			break;
8691 
8692 		case SCMD_WRITE_FILE_MARK:
8693 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8694 			    "write %"PRId64" file marks\n", count);
8695 			un->un_lastop = ST_OP_WEOF;
8696 			fixbit = 0;
8697 			tval = un->un_dp->io_timeout;
8698 			/*
8699 			 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8700 			 * device, set the Vendor Unique bit to
8701 			 * write Short File Mark.
8702 			 */
8703 			if ((un->un_dp->options & ST_SHORT_FILEMARKS) &&
8704 			    ((un->un_dp->type == ST_TYPE_EXB8500) ||
8705 			    (un->un_dp->type == ST_TYPE_EXABYTE))) {
8706 				/*
8707 				 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8708 				 * is set to to write Short File Mark
8709 				 */
8710 				short_fm = 1;
8711 			}
8712 			break;
8713 
8714 		case SCMD_REWIND:
8715 			/*
8716 			 * In the case of rewind we're gona do the rewind with
8717 			 * the immediate bit set so status will be retured when
8718 			 * the command is accepted by the device. We clear the
8719 			 * B_ASYNC flag so we wait for that acceptance.
8720 			 */
8721 			fixbit = 0;
8722 			if (bp->b_flags & B_ASYNC) {
8723 				allocbp = bp;
8724 				if (count) {
8725 					fixbit = 1;
8726 					bp->b_flags &= ~B_ASYNC;
8727 				}
8728 			}
8729 			count = 0;
8730 			bp->b_bcount = 0;
8731 			un->un_lastop = ST_OP_CTL;
8732 			tval = un->un_dp->rewind_timeout;
8733 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8734 			    "rewind\n");
8735 			break;
8736 
8737 		case SCMD_SPACE_G4:
8738 			cdb_len = CDB_GROUP4;
8739 			fixbit = SPACE_TYPE(bp->b_bcount);
8740 			count = SPACE_CNT(bp->b_bcount);
8741 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8742 			    " %s space %s %"PRId64" from file %d blk %d\n",
8743 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8744 			    space_strs[fixbit & 7], count,
8745 			    un->un_pos.fileno, un->un_pos.blkno);
8746 			address = (count >> 48) & 0x1fff;
8747 			additional = (count >> 16) & 0xffffffff;
8748 			count &= 0xffff;
8749 			count <<= 16;
8750 			un->un_lastop = ST_OP_CTL;
8751 			tval = un->un_dp->space_timeout;
8752 			break;
8753 
8754 		case SCMD_SPACE:
8755 			fixbit = SPACE_TYPE(bp->b_bcount);
8756 			count = SPACE_CNT(bp->b_bcount);
8757 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8758 			    " %s space %s %"PRId64" from file %d blk %d\n",
8759 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8760 			    space_strs[fixbit & 7], count,
8761 			    un->un_pos.fileno, un->un_pos.blkno);
8762 			count &= 0xffffffff;
8763 			un->un_lastop = ST_OP_CTL;
8764 			tval = un->un_dp->space_timeout;
8765 			break;
8766 
8767 		case SCMD_LOAD:
8768 			ASSERT(count < 10);
8769 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8770 			    "%s tape\n", load_strs[count]);
8771 			fixbit = 0;
8772 
8773 			/* Loading or Unloading */
8774 			if (count & LD_LOAD) {
8775 				tval = un->un_dp->load_timeout;
8776 			} else {
8777 				tval = un->un_dp->unload_timeout;
8778 			}
8779 			/* Is Retension requested */
8780 			if (count & LD_RETEN) {
8781 				tval += un->un_dp->rewind_timeout;
8782 			}
8783 			un->un_lastop = ST_OP_CTL;
8784 			break;
8785 
8786 		case SCMD_ERASE:
8787 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8788 			    "erase tape\n");
8789 			ASSERT(count == 1); /* mt sets this */
8790 			if (count == 1) {
8791 				/*
8792 				 * do long erase
8793 				 */
8794 				fixbit = 1; /* Long */
8795 
8796 				/* Drive might not honor immidiate bit */
8797 				tval = un->un_dp->erase_timeout;
8798 			} else {
8799 				/* Short Erase */
8800 				tval = un->un_dp->erase_timeout;
8801 				fixbit = 0;
8802 			}
8803 			un->un_lastop = ST_OP_CTL;
8804 			count = 0;
8805 			break;
8806 
8807 		case SCMD_MODE_SENSE:
8808 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8809 			    "mode sense\n");
8810 			allocbp = bp;
8811 			fixbit = 0;
8812 			tval = un->un_dp->non_motion_timeout;
8813 			un->un_lastop = ST_OP_CTL;
8814 			break;
8815 
8816 		case SCMD_MODE_SELECT:
8817 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8818 			    "mode select\n");
8819 			allocbp = bp;
8820 			fixbit = 0;
8821 			tval = un->un_dp->non_motion_timeout;
8822 			un->un_lastop = ST_OP_CTL;
8823 			break;
8824 
8825 		case SCMD_RESERVE:
8826 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8827 			    "reserve\n");
8828 			fixbit = 0;
8829 			tval = un->un_dp->non_motion_timeout;
8830 			un->un_lastop = ST_OP_CTL;
8831 			break;
8832 
8833 		case SCMD_RELEASE:
8834 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8835 			    "release\n");
8836 			fixbit = 0;
8837 			tval = un->un_dp->non_motion_timeout;
8838 			un->un_lastop = ST_OP_CTL;
8839 			break;
8840 
8841 		case SCMD_READ_BLKLIM:
8842 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8843 			    "read block limits\n");
8844 			allocbp = bp;
8845 			fixbit = count = 0;
8846 			tval = un->un_dp->non_motion_timeout;
8847 			un->un_lastop = ST_OP_CTL;
8848 			break;
8849 
8850 		case SCMD_TEST_UNIT_READY:
8851 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8852 			    "test unit ready\n");
8853 			fixbit = 0;
8854 			tval = un->un_dp->non_motion_timeout;
8855 			un->un_lastop = ST_OP_CTL;
8856 			break;
8857 
8858 		case SCMD_DOORLOCK:
8859 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8860 			    "prevent/allow media removal\n");
8861 			fixbit = 0;
8862 			tval = un->un_dp->non_motion_timeout;
8863 			un->un_lastop = ST_OP_CTL;
8864 			break;
8865 
8866 		case SCMD_READ_POSITION:
8867 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8868 			    "read position\n");
8869 			fixbit = un->un_read_pos_type;
8870 			cdb_len = CDB_GROUP1;
8871 			tval = un->un_dp->non_motion_timeout;
8872 			allocbp = bp;
8873 			un->un_lastop = ST_OP_CTL;
8874 			switch (un->un_read_pos_type) {
8875 			case LONG_POS:
8876 				count = 0;
8877 				break;
8878 			case EXT_POS:
8879 				count = sizeof (tape_position_ext_t);
8880 				break;
8881 			case SHORT_POS:
8882 				count = 0;
8883 				break;
8884 			default:
8885 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8886 				    "Unknown read position type 0x%x in "
8887 				    " st_make_cmd()\n", un->un_read_pos_type);
8888 			}
8889 			break;
8890 
8891 		default:
8892 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8893 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8894 			    com);
8895 		}
8896 
8897 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8898 		    st_recov_sz, 0, func, (caddr_t)un);
8899 		if (pkt == NULL) {
8900 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8901 			    "generic command scsi_init_pkt() failure\n");
8902 			goto exit;
8903 		}
8904 
8905 		ASSERT(pkt->pkt_resid == 0);
8906 #ifdef STDEBUG
8907 		bzero(pkt->pkt_private, st_recov_sz);
8908 		bzero(pkt->pkt_scbp, stat_size);
8909 #endif
8910 		ri = (recov_info *)pkt->pkt_private;
8911 		ri->privatelen = st_recov_sz;
8912 		if (allocbp) {
8913 			ASSERT(geterror(allocbp) == 0);
8914 		}
8915 
8916 	}
8917 
8918 	ucdb = (union scsi_cdb *)pkt->pkt_cdbp;
8919 
8920 	(void) scsi_setup_cdb(ucdb, com, address, (uint_t)count, additional);
8921 	FILL_SCSI1_LUN(un->un_sd, pkt);
8922 	/*
8923 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8924 	 */
8925 	ucdb->t_code = fixbit;
8926 	ucdb->g0_vu_1 = short_fm;
8927 	pkt->pkt_flags = flags;
8928 
8929 	ASSERT(tval);
8930 	pkt->pkt_time = tval;
8931 	if (bp == un->un_recov_buf) {
8932 		pkt->pkt_comp = st_recov_cb;
8933 	} else {
8934 		pkt->pkt_comp = st_intr;
8935 	}
8936 
8937 	st_add_recovery_info_to_pkt(un, bp, pkt);
8938 
8939 	/*
8940 	 * If we just write data to tape and did a command that doesn't
8941 	 * change position, we still need to write a filemark.
8942 	 */
8943 	if ((prev_op == ST_OP_WRITE) || (prev_op == ST_OP_WEOF)) {
8944 		recov_info *rcvi = pkt->pkt_private;
8945 		cmd_attribute const *atrib;
8946 
8947 		if (rcvi->privatelen == sizeof (recov_info)) {
8948 			atrib = rcvi->cmd_attrib;
8949 		} else {
8950 			atrib = st_lookup_cmd_attribute(com);
8951 		}
8952 		if (atrib->chg_tape_direction == DIR_NONE) {
8953 			un->un_lastop = prev_op;
8954 		}
8955 	}
8956 
8957 exit:
8958 	ASSERT(mutex_owned(ST_MUTEX));
8959 }
8960 
8961 
8962 /*
8963  * Build a command based on a uscsi command;
8964  */
8965 static void
8966 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
8967     struct buf *bp, int (*func)(caddr_t))
8968 {
8969 	struct scsi_pkt *pkt;
8970 	recov_info *ri;
8971 	caddr_t cdb;
8972 	int	cdblen;
8973 	int	stat_size = 1;
8974 	int	flags = 0;
8975 
8976 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
8977 
8978 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8979 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
8980 
8981 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
8982 		if (un->un_arq_enabled) {
8983 			if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
8984 				stat_size = (int)(ucmd->uscsi_rqlen) +
8985 				    sizeof (struct scsi_arq_status) -
8986 				    sizeof (struct scsi_extended_sense);
8987 				flags = PKT_XARQ;
8988 			} else {
8989 				stat_size = sizeof (struct scsi_arq_status);
8990 			}
8991 		}
8992 	}
8993 
8994 	ASSERT(mutex_owned(ST_MUTEX));
8995 
8996 	cdb = ucmd->uscsi_cdb;
8997 	cdblen = ucmd->uscsi_cdblen;
8998 
8999 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9000 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
9001 	    ucmd->uscsi_buflen, bp->b_bcount);
9002 	pkt = scsi_init_pkt(ROUTE, NULL,
9003 	    (bp->b_bcount > 0) ? bp : NULL,
9004 	    cdblen, stat_size, st_recov_sz, flags, func, (caddr_t)un);
9005 	if (pkt == NULL) {
9006 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
9007 		    "uscsi command scsi_init_pkt() failure\n");
9008 		goto exit;
9009 	}
9010 
9011 	ASSERT(pkt->pkt_resid == 0);
9012 #ifdef STDEBUG
9013 	bzero(pkt->pkt_private, st_recov_sz);
9014 	bzero(pkt->pkt_scbp, stat_size);
9015 #endif
9016 	ri = (recov_info *)pkt->pkt_private;
9017 	ri->privatelen = st_recov_sz;
9018 
9019 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
9020 
9021 #ifdef STDEBUG
9022 	if ((st_debug & 0x7) >= 6) {
9023 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
9024 		    "pkt_cdbp", (char *)cdb, cdblen);
9025 	}
9026 #endif
9027 
9028 	if (ucmd->uscsi_flags & USCSI_SILENT) {
9029 		pkt->pkt_flags |= FLAG_SILENT;
9030 	}
9031 
9032 	pkt->pkt_time = ucmd->uscsi_timeout;
9033 	if (bp == un->un_recov_buf) {
9034 		pkt->pkt_comp = st_recov_cb;
9035 	} else {
9036 		pkt->pkt_comp = st_intr;
9037 	}
9038 	st_add_recovery_info_to_pkt(un, bp, pkt);
9039 exit:
9040 	ASSERT(mutex_owned(ST_MUTEX));
9041 }
9042 
9043 
9044 /*
9045  * restart cmd currently at the head of the runq
9046  *
9047  * If scsi_transport() succeeds or the retries
9048  * count exhausted, restore the throttle that was
9049  * zeroed out in st_handle_intr_busy().
9050  *
9051  */
9052 static void
9053 st_intr_restart(void *arg)
9054 {
9055 	struct scsi_tape *un = arg;
9056 	struct buf *bp;
9057 	int queued;
9058 	int status = TRAN_ACCEPT;
9059 
9060 	mutex_enter(ST_MUTEX);
9061 
9062 	ST_FUNC(ST_DEVINFO, st_intr_restart);
9063 
9064 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9065 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
9066 
9067 	un->un_hib_tid = 0;
9068 
9069 	if (un->un_recov_buf_busy != 0) {
9070 		bp = un->un_recov_buf;
9071 		queued = 0;
9072 	} else if (un->un_sbuf_busy != 0) {
9073 		bp = un->un_sbufp;
9074 		queued = 0;
9075 	} else if (un->un_quef != NULL) {
9076 		bp = un->un_quef;
9077 		queued = 1;
9078 	} else {
9079 		mutex_exit(ST_MUTEX);
9080 		return;
9081 	}
9082 
9083 	/*
9084 	 * Here we know :
9085 	 *	throttle = 0, via st_handle_intr_busy
9086 	 */
9087 
9088 	if (queued) {
9089 		/*
9090 		 * move from waitq to runq, if there is anything on the waitq
9091 		 */
9092 		(void) st_remove_from_queue(&un->un_quef, &un->un_quef, bp);
9093 
9094 		if (un->un_runqf) {
9095 			/*
9096 			 * not good, we don't want to requeue something after
9097 			 * another.
9098 			 */
9099 			goto done_error;
9100 		} else {
9101 			un->un_runqf = bp;
9102 			un->un_runql = bp;
9103 		}
9104 	}
9105 
9106 	ST_CDB(ST_DEVINFO, "Interrupt restart CDB",
9107 	    (char *)BP_PKT(bp)->pkt_cdbp);
9108 
9109 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
9110 
9111 	status = st_transport(un, BP_PKT(bp));
9112 
9113 	if (status != TRAN_ACCEPT) {
9114 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9115 
9116 		if (status == TRAN_BUSY) {
9117 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
9118 
9119 			if (pkti->privatelen == sizeof (recov_info) &&
9120 			    un->un_unit_attention_flags &&
9121 			    bp != un->un_recov_buf) {
9122 			un->un_unit_attention_flags = 0;
9123 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9124 				    "Command Recovery called on busy resend\n");
9125 				if (st_command_recovery(un, BP_PKT(bp),
9126 				    ATTEMPT_RETRY) == JUST_RETURN) {
9127 					mutex_exit(ST_MUTEX);
9128 					return;
9129 				}
9130 			}
9131 			mutex_exit(ST_MUTEX);
9132 			if (st_handle_intr_busy(un, bp,
9133 			    ST_TRAN_BUSY_TIMEOUT) == 0)
9134 				return;	/* timeout is setup again */
9135 			mutex_enter(ST_MUTEX);
9136 		}
9137 
9138 done_error:
9139 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9140 		    "restart transport rejected\n");
9141 		bp->b_resid = bp->b_bcount;
9142 
9143 		if (un->un_last_throttle) {
9144 			un->un_throttle = un->un_last_throttle;
9145 		}
9146 		if (status != TRAN_ACCEPT) {
9147 			ST_DO_ERRSTATS(un, st_transerrs);
9148 		}
9149 		ST_DO_KSTATS(bp, kstat_waitq_exit);
9150 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9151 		    "busy restart aborted\n");
9152 		st_set_pe_flag(un);
9153 		st_bioerror(bp, EIO);
9154 		st_done_and_mutex_exit(un, bp);
9155 	} else {
9156 		if (un->un_last_throttle) {
9157 			un->un_throttle = un->un_last_throttle;
9158 		}
9159 		mutex_exit(ST_MUTEX);
9160 	}
9161 }
9162 
9163 /*
9164  * st_check_media():
9165  * Periodically check the media state using scsi_watch service;
9166  * this service calls back after TUR and possibly request sense
9167  * the callback handler (st_media_watch_cb()) decodes the request sense
9168  * data (if any)
9169  */
9170 
9171 static int
9172 st_check_media(dev_t dev, enum mtio_state state)
9173 {
9174 	int rval = 0;
9175 	enum mtio_state	prev_state;
9176 	opaque_t token = NULL;
9177 
9178 	GET_SOFT_STATE(dev);
9179 
9180 	ST_FUNC(ST_DEVINFO, st_check_media);
9181 
9182 	mutex_enter(ST_MUTEX);
9183 
9184 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9185 	    "st_check_media:state=%x, mediastate=%x\n",
9186 	    state, un->un_mediastate);
9187 
9188 	prev_state = un->un_mediastate;
9189 
9190 	/*
9191 	 * is there anything to do?
9192 	 */
9193 retry:
9194 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
9195 		/*
9196 		 * submit the request to the scsi_watch service;
9197 		 * scsi_media_watch_cb() does the real work
9198 		 */
9199 		mutex_exit(ST_MUTEX);
9200 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
9201 		    st_check_media_time, SENSE_LENGTH,
9202 		    st_media_watch_cb, (caddr_t)dev);
9203 		if (token == NULL) {
9204 			rval = EAGAIN;
9205 			goto done;
9206 		}
9207 		mutex_enter(ST_MUTEX);
9208 
9209 		un->un_swr_token = token;
9210 		un->un_specified_mediastate = state;
9211 
9212 		/*
9213 		 * now wait for media change
9214 		 * we will not be signalled unless mediastate == state but it
9215 		 * still better to test for this condition, since there
9216 		 * is a 5 sec cv_broadcast delay when
9217 		 *  mediastate == MTIO_INSERTED
9218 		 */
9219 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9220 		    "st_check_media:waiting for media state change\n");
9221 		while (un->un_mediastate == state) {
9222 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
9223 				mutex_exit(ST_MUTEX);
9224 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9225 				    "st_check_media:waiting for media state "
9226 				    "was interrupted\n");
9227 				rval = EINTR;
9228 				goto done;
9229 			}
9230 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9231 			    "st_check_media:received signal, state=%x\n",
9232 			    un->un_mediastate);
9233 		}
9234 	}
9235 
9236 	/*
9237 	 * if we transitioned to MTIO_INSERTED, media has really been
9238 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
9239 	 * Reset and retry the state change.  If everything is ok, replay
9240 	 * the open() logic.
9241 	 */
9242 	if ((un->un_mediastate == MTIO_INSERTED) &&
9243 	    (un->un_state == ST_STATE_OFFLINE)) {
9244 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9245 		    "st_check_media: calling st_cmd to confirm inserted\n");
9246 
9247 		/*
9248 		 * set this early so that TUR will make it through strategy
9249 		 * without triggering a st_tape_init().  We needed it set
9250 		 * before calling st_tape_init() ourselves anyway.  If TUR
9251 		 * fails, set it back
9252 		 */
9253 		un->un_state = ST_STATE_INITIALIZING;
9254 
9255 		/*
9256 		 * If not reserved fail as getting reservation conflict
9257 		 * will make this hang forever.
9258 		 */
9259 		if ((un->un_rsvd_status &
9260 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9261 			mutex_exit(ST_MUTEX);
9262 			rval = EACCES;
9263 			goto done;
9264 		}
9265 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
9266 		if (rval == EACCES) {
9267 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9268 			    "st_check_media: TUR got Reservation Conflict\n");
9269 			mutex_exit(ST_MUTEX);
9270 			goto done;
9271 		}
9272 		if (rval) {
9273 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9274 			    "st_check_media: TUR failed, going to retry\n");
9275 			un->un_mediastate = prev_state;
9276 			un->un_state = ST_STATE_OFFLINE;
9277 			goto retry;
9278 		}
9279 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9280 		    "st_check_media: media inserted\n");
9281 
9282 		/* this also rewinds the tape */
9283 		rval = st_tape_init(un);
9284 		if (rval != 0) {
9285 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9286 			    "st_check_media : OFFLINE init failure ");
9287 			un->un_state = ST_STATE_OFFLINE;
9288 			un->un_pos.pmode = invalid;
9289 		} else {
9290 			un->un_state = ST_STATE_OPEN_PENDING_IO;
9291 		}
9292 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
9293 	    (un->un_state != ST_STATE_OFFLINE)) {
9294 		/*
9295 		 * supported devices must be rewound before ejection
9296 		 * rewind resets fileno & blkno
9297 		 */
9298 		un->un_laststate = un->un_state;
9299 		un->un_state = ST_STATE_OFFLINE;
9300 	}
9301 	mutex_exit(ST_MUTEX);
9302 done:
9303 	if (token) {
9304 		(void) scsi_watch_request_terminate(token,
9305 		    SCSI_WATCH_TERMINATE_WAIT);
9306 		mutex_enter(ST_MUTEX);
9307 		un->un_swr_token = (opaque_t)NULL;
9308 		mutex_exit(ST_MUTEX);
9309 	}
9310 
9311 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
9312 
9313 	return (rval);
9314 }
9315 
9316 /*
9317  * st_media_watch_cb() is called by scsi_watch_thread for
9318  * verifying the request sense data (if any)
9319  */
9320 static int
9321 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
9322 {
9323 	struct scsi_status *statusp = resultp->statusp;
9324 	struct scsi_extended_sense *sensep = resultp->sensep;
9325 	uchar_t actual_sense_length = resultp->actual_sense_length;
9326 	struct scsi_tape *un;
9327 	enum mtio_state state = MTIO_NONE;
9328 	int instance;
9329 	dev_t dev = (dev_t)arg;
9330 
9331 	instance = MTUNIT(dev);
9332 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
9333 		return (-1);
9334 	}
9335 
9336 	mutex_enter(ST_MUTEX);
9337 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
9338 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9339 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
9340 	    *((char *)statusp), (void *)sensep,
9341 	    actual_sense_length);
9342 
9343 
9344 	/*
9345 	 * if there was a check condition then sensep points to valid
9346 	 * sense data
9347 	 * if status was not a check condition but a reservation or busy
9348 	 * status then the new state is MTIO_NONE
9349 	 */
9350 	if (sensep) {
9351 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9352 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
9353 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
9354 
9355 		switch (un->un_dp->type) {
9356 		default:
9357 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9358 			    "st_media_watch_cb: unknown drive type %d, "
9359 			    "default to ST_TYPE_HP\n", un->un_dp->type);
9360 		/* FALLTHROUGH */
9361 
9362 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
9363 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
9364 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
9365 			if (un->un_dp->type == ST_TYPE_FUJI) {
9366 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9367 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
9368 			} else {
9369 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9370 				    "st_media_watch_cb: ST_TYPE_HP\n");
9371 			}
9372 			switch (sensep->es_key) {
9373 			case KEY_UNIT_ATTENTION:
9374 				/* not ready to ready transition */
9375 				/* hp/es_qual_code == 80 on>off>on */
9376 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
9377 				if (sensep->es_add_code == 0x28) {
9378 					state = MTIO_INSERTED;
9379 				}
9380 				break;
9381 			case KEY_NOT_READY:
9382 				/* in process, rewinding or loading */
9383 				if ((sensep->es_add_code == 0x04) &&
9384 				    (sensep->es_qual_code == 0x00)) {
9385 					state = MTIO_EJECTED;
9386 				}
9387 				break;
9388 			}
9389 			break;
9390 
9391 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
9392 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9393 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
9394 			switch (sensep->es_key) {
9395 			case KEY_UNIT_ATTENTION:
9396 				/* operator medium removal request */
9397 				if ((sensep->es_add_code == 0x5a) &&
9398 				    (sensep->es_qual_code == 0x01)) {
9399 					state = MTIO_EJECTED;
9400 				/* not ready to ready transition */
9401 				} else if ((sensep->es_add_code == 0x28) &&
9402 				    (sensep->es_qual_code == 0x00)) {
9403 					state = MTIO_INSERTED;
9404 				}
9405 				break;
9406 			case KEY_NOT_READY:
9407 				/* medium not present */
9408 				if (sensep->es_add_code == 0x3a) {
9409 					state = MTIO_EJECTED;
9410 				}
9411 				break;
9412 			}
9413 			break;
9414 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
9415 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9416 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
9417 			switch (sensep->es_key) {
9418 			case KEY_NOT_READY:
9419 				if ((sensep->es_add_code == 0x04) &&
9420 				    (sensep->es_qual_code == 0x00)) {
9421 					/* volume not mounted? */
9422 					state = MTIO_EJECTED;
9423 				} else if (sensep->es_add_code == 0x3a) {
9424 					state = MTIO_EJECTED;
9425 				}
9426 				break;
9427 			case KEY_UNIT_ATTENTION:
9428 				state = MTIO_EJECTED;
9429 				break;
9430 			}
9431 			break;
9432 
9433 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
9434 			switch (sensep->es_key) {
9435 			case KEY_UNIT_ATTENTION:
9436 				if (sensep->es_add_code == 0x28) {
9437 					state = MTIO_INSERTED;
9438 				}
9439 				break;
9440 			case KEY_NOT_READY:
9441 				if (sensep->es_add_code == 0x04) {
9442 					/* in transition but could be either */
9443 					state = un->un_specified_mediastate;
9444 				} else if ((sensep->es_add_code == 0x3a) &&
9445 				    (sensep->es_qual_code == 0x00)) {
9446 					state = MTIO_EJECTED;
9447 				}
9448 				break;
9449 			}
9450 			break;
9451 		}
9452 	} else if (*((char *)statusp) == STATUS_GOOD) {
9453 		state = MTIO_INSERTED;
9454 	}
9455 
9456 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9457 	    "st_media_watch_cb:state=%x, specified=%x\n",
9458 	    state, un->un_specified_mediastate);
9459 
9460 	/*
9461 	 * now signal the waiting thread if this is *not* the specified state;
9462 	 * delay the signal if the state is MTIO_INSERTED
9463 	 * to allow the target to recover
9464 	 */
9465 	if (state != un->un_specified_mediastate) {
9466 		un->un_mediastate = state;
9467 		if (state == MTIO_INSERTED) {
9468 			/*
9469 			 * delay the signal to give the drive a chance
9470 			 * to do what it apparently needs to do
9471 			 */
9472 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9473 			    "st_media_watch_cb:delayed cv_broadcast\n");
9474 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
9475 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
9476 		} else {
9477 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9478 			    "st_media_watch_cb:immediate cv_broadcast\n");
9479 			cv_broadcast(&un->un_state_cv);
9480 		}
9481 	}
9482 	mutex_exit(ST_MUTEX);
9483 	return (0);
9484 }
9485 
9486 /*
9487  * delayed cv_broadcast to allow for target to recover
9488  * from media insertion
9489  */
9490 static void
9491 st_delayed_cv_broadcast(void *arg)
9492 {
9493 	struct scsi_tape *un = arg;
9494 
9495 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
9496 
9497 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9498 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
9499 
9500 	mutex_enter(ST_MUTEX);
9501 	cv_broadcast(&un->un_state_cv);
9502 	mutex_exit(ST_MUTEX);
9503 }
9504 
9505 /*
9506  * restart cmd currently at the start of the waitq
9507  */
9508 static void
9509 st_start_restart(void *arg)
9510 {
9511 	struct scsi_tape *un = arg;
9512 
9513 	ST_FUNC(ST_DEVINFO, st_start_restart);
9514 
9515 	ASSERT(un != NULL);
9516 
9517 	mutex_enter(ST_MUTEX);
9518 
9519 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_tran_restart()\n");
9520 
9521 	st_start(un);
9522 
9523 	mutex_exit(ST_MUTEX);
9524 }
9525 
9526 
9527 /*
9528  * Command completion processing
9529  *
9530  */
9531 static void
9532 st_intr(struct scsi_pkt *pkt)
9533 {
9534 	recov_info *rcv = pkt->pkt_private;
9535 	struct buf *bp = rcv->cmd_bp;
9536 	struct scsi_tape *un;
9537 	errstate action = COMMAND_DONE;
9538 	clock_t	timout;
9539 	int	status;
9540 
9541 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
9542 
9543 	ST_FUNC(ST_DEVINFO, st_intr);
9544 
9545 	ASSERT(un != NULL);
9546 
9547 	mutex_enter(ST_MUTEX);
9548 
9549 	ASSERT(bp != un->un_recov_buf);
9550 
9551 	un->un_rqs_state &= ~(ST_RQS_ERROR);
9552 
9553 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
9554 
9555 	if (pkt->pkt_reason != CMD_CMPLT) {
9556 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9557 		    "Unhappy packet status reason = %s statistics = 0x%x\n",
9558 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9559 
9560 		/* If device has gone away not much else to do */
9561 		if (pkt->pkt_reason == CMD_DEV_GONE) {
9562 			action = COMMAND_DONE_ERROR;
9563 		} else if ((pkt == un->un_rqs) ||
9564 		    (un->un_state == ST_STATE_SENSING)) {
9565 			ASSERT(pkt == un->un_rqs);
9566 			ASSERT(un->un_state == ST_STATE_SENSING);
9567 			un->un_state = un->un_laststate;
9568 			rcv->cmd_bp = un->un_rqs_bp;
9569 			ST_DO_ERRSTATS(un, st_transerrs);
9570 			action = COMMAND_DONE_ERROR;
9571 		} else {
9572 			action = st_handle_incomplete(un, bp);
9573 		}
9574 	/*
9575 	 * At this point we know that the command was successfully
9576 	 * completed. Now what?
9577 	 */
9578 	} else if ((pkt == un->un_rqs) || (un->un_state == ST_STATE_SENSING)) {
9579 		/*
9580 		 * okay. We were running a REQUEST SENSE. Find
9581 		 * out what to do next.
9582 		 */
9583 		ASSERT(pkt == un->un_rqs);
9584 		ASSERT(un->un_state == ST_STATE_SENSING);
9585 		scsi_sync_pkt(pkt);
9586 		action = st_handle_sense(un, bp, &un->un_pos);
9587 		/*
9588 		 * Make rqs isn't going to be retied.
9589 		 */
9590 		if (action != QUE_BUSY_COMMAND && action != QUE_COMMAND) {
9591 			/*
9592 			 * set pkt back to original packet in case we will have
9593 			 * to requeue it
9594 			 */
9595 			pkt = BP_PKT(bp);
9596 			rcv->cmd_bp = un->un_rqs_bp;
9597 			/*
9598 			 * some actions are based on un_state, hence
9599 			 * restore the state st was in before ST_STATE_SENSING.
9600 			 */
9601 			un->un_state = un->un_laststate;
9602 		}
9603 
9604 	} else if (un->un_arq_enabled && (pkt->pkt_state & STATE_ARQ_DONE)) {
9605 		/*
9606 		 * the transport layer successfully completed an autorqsense
9607 		 */
9608 		action = st_handle_autosense(un, bp, &un->un_pos);
9609 
9610 	} else  if ((SCBP(pkt)->sts_busy) ||
9611 	    (SCBP(pkt)->sts_chk) ||
9612 	    (SCBP(pkt)->sts_vu7)) {
9613 		/*
9614 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9615 		 * to see if the status bits we're okay. If a request sense
9616 		 * is to be run, that will happen.
9617 		 */
9618 		action = st_check_error(un, pkt);
9619 	}
9620 
9621 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9622 		switch (action) {
9623 			case QUE_COMMAND:
9624 				/*
9625 				 * return cmd to head to the queue
9626 				 * since we are suspending so that
9627 				 * it gets restarted during resume
9628 				 */
9629 				st_add_to_queue(&un->un_runqf, &un->un_runql,
9630 				    un->un_runqf, bp);
9631 
9632 				action = JUST_RETURN;
9633 				break;
9634 
9635 			case QUE_SENSE:
9636 				action = COMMAND_DONE_ERROR;
9637 				break;
9638 
9639 			default:
9640 				break;
9641 		}
9642 	}
9643 
9644 	/*
9645 	 * check for undetected path failover.
9646 	 */
9647 	if ((un->un_multipath) &&
9648 	    (un->un_last_path_instance != pkt->pkt_path_instance)) {
9649 		if (un->un_state > ST_STATE_OPENING) {
9650 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
9651 			    "Failover detected, action is %s\n",
9652 			    errstatenames[action]);
9653 			if (action == COMMAND_DONE) {
9654 				action = PATH_FAILED;
9655 			}
9656 		}
9657 		un->un_last_path_instance = pkt->pkt_path_instance;
9658 	}
9659 
9660 	/*
9661 	 * Restore old state if we were sensing.
9662 	 */
9663 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9664 		un->un_state = un->un_laststate;
9665 	}
9666 
9667 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9668 	    "st_intr: pkt=%p, bp=%p, action=%s, status=%x\n",
9669 	    (void *)pkt, (void *)bp, errstatenames[action], SCBP_C(pkt));
9670 
9671 again:
9672 	switch (action) {
9673 	case COMMAND_DONE_EACCES:
9674 		/* this is to report a reservation conflict */
9675 		st_bioerror(bp, EACCES);
9676 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9677 		    "Reservation Conflict \n");
9678 		un->un_pos.pmode = invalid;
9679 
9680 		/*FALLTHROUGH*/
9681 	case COMMAND_DONE_ERROR:
9682 		if (un->un_pos.eof < ST_EOT_PENDING &&
9683 		    un->un_state >= ST_STATE_OPEN) {
9684 			/*
9685 			 * all errors set state of the tape to 'unknown'
9686 			 * unless we're at EOT or are doing append testing.
9687 			 * If sense key was illegal request, preserve state.
9688 			 */
9689 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9690 				un->un_pos.pmode = invalid;
9691 			}
9692 		}
9693 
9694 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9695 		/*
9696 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9697 		 * make sure an error ocurrs, so make sure at least EIO is
9698 		 * returned
9699 		 */
9700 		if (geterror(bp) == 0)
9701 			st_bioerror(bp, EIO);
9702 
9703 		st_set_pe_flag(un);
9704 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9705 		    (un->un_errno == EIO)) {
9706 			un->un_rqs_state &= ~(ST_RQS_VALID);
9707 		}
9708 		break;
9709 
9710 	case COMMAND_DONE_ERROR_RECOVERED:
9711 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9712 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9713 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9714 		if (geterror(bp) == 0) {
9715 			st_bioerror(bp, EIO);
9716 		}
9717 		st_set_pe_flag(un);
9718 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9719 		    (un->un_errno == EIO)) {
9720 			un->un_rqs_state &= ~(ST_RQS_VALID);
9721 		}
9722 		/*FALLTHROUGH*/
9723 	case COMMAND_DONE:
9724 		st_set_state(un, bp);
9725 		break;
9726 
9727 	case QUE_SENSE:
9728 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9729 			goto sense_error;
9730 
9731 		if (un->un_state != ST_STATE_SENSING) {
9732 			un->un_laststate = un->un_state;
9733 			un->un_state = ST_STATE_SENSING;
9734 		}
9735 
9736 		/*
9737 		 * zero the sense data.
9738 		 */
9739 		bzero(un->un_rqs->pkt_scbp, SENSE_LENGTH);
9740 
9741 		/*
9742 		 * If this is not a retry on QUE_SENSE point to the original
9743 		 * bp of the command that got us here.
9744 		 */
9745 		if (pkt != un->un_rqs) {
9746 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp = bp;
9747 		}
9748 
9749 		if (un->un_throttle) {
9750 			un->un_last_throttle = un->un_throttle;
9751 			un->un_throttle = 0;
9752 		}
9753 
9754 		ST_CDB(ST_DEVINFO, "Queue sense CDB",
9755 		    (char *)BP_PKT(bp)->pkt_cdbp);
9756 
9757 		/*
9758 		 * never retry this, some other command will have nuked the
9759 		 * sense, anyway
9760 		 */
9761 		status = st_transport(un, un->un_rqs);
9762 
9763 		if (un->un_last_throttle) {
9764 			un->un_throttle = un->un_last_throttle;
9765 		}
9766 
9767 		if (status == TRAN_ACCEPT) {
9768 			mutex_exit(ST_MUTEX);
9769 			return;
9770 		}
9771 		if (status != TRAN_BUSY)
9772 			ST_DO_ERRSTATS(un, st_transerrs);
9773 sense_error:
9774 		un->un_pos.pmode = invalid;
9775 		st_bioerror(bp, EIO);
9776 		st_set_pe_flag(un);
9777 		break;
9778 
9779 	case QUE_BUSY_COMMAND:
9780 		/* longish timeout */
9781 		timout = ST_STATUS_BUSY_TIMEOUT;
9782 		goto que_it_up;
9783 
9784 	case QUE_COMMAND:
9785 		/* short timeout */
9786 		timout = ST_TRAN_BUSY_TIMEOUT;
9787 que_it_up:
9788 		/*
9789 		 * let st_handle_intr_busy put this bp back on waitq and make
9790 		 * checks to see if it is ok to requeue the command.
9791 		 */
9792 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9793 
9794 		/*
9795 		 * Save the throttle before setting up the timeout
9796 		 */
9797 		if (un->un_throttle) {
9798 			un->un_last_throttle = un->un_throttle;
9799 		}
9800 		mutex_exit(ST_MUTEX);
9801 		if (st_handle_intr_busy(un, bp, timout) == 0)
9802 			return;		/* timeout is setup again */
9803 
9804 		mutex_enter(ST_MUTEX);
9805 		un->un_pos.pmode = invalid;
9806 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9807 		st_bioerror(bp, EIO);
9808 		st_set_pe_flag(un);
9809 		break;
9810 
9811 	case QUE_LAST_COMMAND:
9812 
9813 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9814 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9815 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9816 			goto last_command_error;
9817 		}
9818 		mutex_exit(ST_MUTEX);
9819 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9820 			return;
9821 		mutex_enter(ST_MUTEX);
9822 last_command_error:
9823 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9824 		un->un_pos.pmode = invalid;
9825 		st_bioerror(bp, EIO);
9826 		st_set_pe_flag(un);
9827 		break;
9828 
9829 	case COMMAND_TIMEOUT:
9830 	case DEVICE_RESET:
9831 	case DEVICE_TAMPER:
9832 	case ATTEMPT_RETRY:
9833 	case PATH_FAILED:
9834 		ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9835 		    "Command Recovery called on %s status\n",
9836 		    errstatenames[action]);
9837 		action = st_command_recovery(un, pkt, action);
9838 		goto again;
9839 
9840 	default:
9841 		ASSERT(0);
9842 		/* FALLTHRU */
9843 	case JUST_RETURN:
9844 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9845 		mutex_exit(ST_MUTEX);
9846 		return;
9847 	}
9848 
9849 	ST_DO_KSTATS(bp, kstat_runq_exit);
9850 	st_done_and_mutex_exit(un, bp);
9851 }
9852 
9853 static errstate
9854 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9855 {
9856 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9857 	recov_info *rinfo;
9858 	errstate rval = COMMAND_DONE_ERROR;
9859 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9860 	    un->un_rqs : BP_PKT(bp);
9861 	int result;
9862 
9863 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9864 
9865 	rinfo = (recov_info *)pkt->pkt_private;
9866 
9867 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9868 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9869 
9870 	ASSERT(mutex_owned(ST_MUTEX));
9871 
9872 	switch (pkt->pkt_reason) {
9873 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9874 		/*
9875 		 * this occurs when accessing a powered down drive, no
9876 		 * need to complain; just fail the open
9877 		 */
9878 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9879 
9880 		/*
9881 		 * if we have commands outstanding in HBA, and a command
9882 		 * comes back incomplete, we're hosed, so reset target
9883 		 * If we have the bus, but cmd_incomplete, we probably just
9884 		 * have a failed selection, so don't reset the target, just
9885 		 * requeue the command and try again
9886 		 */
9887 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9888 			goto reset_target;
9889 		}
9890 
9891 		/*
9892 		 * Retry selection a couple more times if we're
9893 		 * open.  If opening, we only try just once to
9894 		 * reduce probe time for nonexistant devices.
9895 		 */
9896 		if ((un->un_laststate > ST_STATE_OPENING) &&
9897 		    (rinfo->pkt_retry_cnt < st_selection_retry_count)) {
9898 			/* XXX check retriable? */
9899 			rval = QUE_COMMAND;
9900 		}
9901 		ST_DO_ERRSTATS(un, st_transerrs);
9902 		break;
9903 
9904 	case CMD_ABORTED:
9905 		/*
9906 		 * most likely this is caused by flush-on-error support. If
9907 		 * it was not there, the we're in trouble.
9908 		 */
9909 		if (!un->un_flush_on_errors) {
9910 			un->un_status = SUN_KEY_FATAL;
9911 			goto reset_target;
9912 		}
9913 
9914 		st_set_pe_errno(un);
9915 		bioerror(bp, un->un_errno);
9916 		if (un->un_errno)
9917 			return (COMMAND_DONE_ERROR);
9918 		else
9919 			return (COMMAND_DONE);
9920 
9921 	case CMD_TIMEOUT:	/* Command timed out */
9922 		un->un_status = SUN_KEY_TIMEOUT;
9923 		return (COMMAND_TIMEOUT);
9924 
9925 	case CMD_TRAN_ERR:
9926 	case CMD_RESET:
9927 		if (pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET)) {
9928 			if ((un->un_rsvd_status &
9929 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
9930 			    ST_RESERVE) {
9931 				un->un_rsvd_status |= ST_LOST_RESERVE;
9932 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
9933 				    "Lost Reservation\n");
9934 			}
9935 			rval = DEVICE_RESET;
9936 			return (rval);
9937 		}
9938 		if (pkt->pkt_statistics & (STAT_ABORTED | STAT_TERMINATED)) {
9939 			rval = DEVICE_RESET;
9940 			return (rval);
9941 		}
9942 		/*FALLTHROUGH*/
9943 	default:
9944 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9945 		    "Unhandled packet status reason = %s statistics = 0x%x\n",
9946 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9947 reset_target:
9948 
9949 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9950 		    "transport completed with %s\n",
9951 		    scsi_rname(pkt->pkt_reason));
9952 		ST_DO_ERRSTATS(un, st_transerrs);
9953 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
9954 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
9955 		    STAT_ABORTED)) == 0)) {
9956 
9957 			/*
9958 			 * If we haven't reserved the drive don't reset it.
9959 			 */
9960 			if ((un->un_rsvd_status &
9961 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9962 				return (rval);
9963 			}
9964 
9965 			/*
9966 			 * if we aren't lost yet we will be soon.
9967 			 */
9968 			un->un_pos.pmode = invalid;
9969 
9970 			result = st_reset(un, RESET_LUN);
9971 
9972 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
9973 				/* no hope left to recover */
9974 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
9975 				    "recovery by resets failed\n");
9976 				return (rval);
9977 			}
9978 		}
9979 	}
9980 
9981 
9982 	if (rinfo->pkt_retry_cnt++ < st_retry_count) {
9983 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9984 			rval = QUE_COMMAND;
9985 		} else if (bp == un->un_sbufp) {
9986 			if (rinfo->privatelen == sizeof (recov_info)) {
9987 				if (rinfo->cmd_attrib->retriable) {
9988 					/*
9989 					 * These commands can be rerun
9990 					 * with impunity
9991 					 */
9992 					rval = QUE_COMMAND;
9993 				}
9994 			} else {
9995 				cmd_attribute const *attrib;
9996 				attrib =
9997 				    st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
9998 				if (attrib->retriable) {
9999 					rval = QUE_COMMAND;
10000 				}
10001 			}
10002 		}
10003 	} else {
10004 		rval = COMMAND_DONE_ERROR;
10005 	}
10006 
10007 	if (un->un_state >= ST_STATE_OPEN) {
10008 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10009 		    fail, scsi_rname(pkt->pkt_reason),
10010 		    (rval == COMMAND_DONE_ERROR)?
10011 		    "giving up" : "retrying command");
10012 	}
10013 	return (rval);
10014 }
10015 
10016 /*
10017  * if the device is busy, then put this bp back on the waitq, on the
10018  * interrupt thread, where we want the head of the queue and not the
10019  * end
10020  *
10021  * The callers of this routine should take measures to save the
10022  * un_throttle in un_last_throttle which will be restored in
10023  * st_intr_restart(). The only exception should be st_intr_restart()
10024  * calling this routine for which the saving is already done.
10025  */
10026 static int
10027 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
10028 	clock_t timeout_interval)
10029 {
10030 
10031 	int queued;
10032 	int rval = 0;
10033 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
10034 
10035 	mutex_enter(ST_MUTEX);
10036 
10037 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
10038 
10039 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10040 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
10041 
10042 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
10043 		queued = 1;
10044 	} else {
10045 		queued = 0;
10046 	}
10047 
10048 	/*
10049 	 * Check to see if we hit the retry timeout. We check to make sure
10050 	 * this is the first one on the runq and make sure we have not
10051 	 * queued up any more, so this one has to be the last on the list
10052 	 * also. If it is not, we have to fail.  If it is not the first, but
10053 	 * is the last we are in trouble anyway, as we are in the interrupt
10054 	 * context here.
10055 	 */
10056 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
10057 	    ((un->un_runqf != bp) && (un->un_runql != bp) && (queued))) {
10058 		rval = -1;
10059 		goto exit;
10060 	}
10061 
10062 	/* put the bp back on the waitq */
10063 	if (queued) {
10064 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
10065 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
10066 	}
10067 
10068 	/*
10069 	 * We don't want any other commands being started in the mean time.
10070 	 * If start had just released mutex after putting something on the
10071 	 * runq, we won't even get here.
10072 	 */
10073 	un->un_throttle = 0;
10074 
10075 	/*
10076 	 * send a marker pkt, if appropriate
10077 	 */
10078 	st_hba_unflush(un);
10079 
10080 	/*
10081 	 * all queues are aligned, we are just waiting to
10082 	 * transport
10083 	 */
10084 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
10085 
10086 exit:
10087 	mutex_exit(ST_MUTEX);
10088 	return (rval);
10089 }
10090 
10091 /*
10092  * To get one error entry from error stack
10093  */
10094 static int
10095 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
10096 {
10097 #ifdef _MULTI_DATAMODEL
10098 	/*
10099 	 * For use when a 32 bit app makes a call into a
10100 	 * 64 bit ioctl
10101 	 */
10102 	struct mterror_entry32 err_entry32;
10103 #endif /* _MULTI_DATAMODEL */
10104 
10105 	int rval = 0;
10106 	struct mterror_entry err_entry;
10107 	struct mterror_entry_stack *err_link_entry_p;
10108 	size_t arq_status_len_in, arq_status_len_kr;
10109 
10110 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
10111 
10112 	ASSERT(mutex_owned(ST_MUTEX));
10113 
10114 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10115 	    "st_get_error_entry()\n");
10116 
10117 	/*
10118 	 * if error record stack empty, return ENXIO
10119 	 */
10120 	if (un->un_error_entry_stk == NULL) {
10121 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10122 		    "st_get_error_entry: Error Entry Stack Empty!\n");
10123 		rval = ENXIO;
10124 		goto ret;
10125 	}
10126 
10127 	/*
10128 	 * get the top entry from stack
10129 	 */
10130 	err_link_entry_p = un->un_error_entry_stk;
10131 	arq_status_len_kr =
10132 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
10133 
10134 #ifdef _MULTI_DATAMODEL
10135 	switch (ddi_model_convert_from(flag & FMODELS)) {
10136 	case DDI_MODEL_ILP32:
10137 		if (ddi_copyin((void *)arg, &err_entry32,
10138 		    MTERROR_ENTRY_SIZE_32, flag)) {
10139 			rval = EFAULT;
10140 			goto ret;
10141 		}
10142 
10143 		arq_status_len_in =
10144 		    (size_t)err_entry32.mtee_arq_status_len;
10145 
10146 		err_entry32.mtee_cdb_len =
10147 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
10148 
10149 		if (arq_status_len_in > arq_status_len_kr)
10150 			err_entry32.mtee_arq_status_len =
10151 			    (size32_t)arq_status_len_kr;
10152 
10153 		if (ddi_copyout(
10154 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10155 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
10156 		    err_entry32.mtee_cdb_len, flag)) {
10157 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10158 			    "st_get_error_entry: Copy cdb buffer error!");
10159 			rval = EFAULT;
10160 		}
10161 
10162 		if (ddi_copyout(
10163 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10164 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
10165 		    err_entry32.mtee_arq_status_len, flag)) {
10166 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10167 			    "st_get_error_entry: copy arq status error!");
10168 			rval = EFAULT;
10169 		}
10170 
10171 		if (ddi_copyout(&err_entry32, (void *)arg,
10172 		    MTERROR_ENTRY_SIZE_32, flag)) {
10173 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10174 			    "st_get_error_entry: copy arq status out error!");
10175 			rval = EFAULT;
10176 		}
10177 		break;
10178 
10179 	case DDI_MODEL_NONE:
10180 		if (ddi_copyin((void *)arg, &err_entry,
10181 		    MTERROR_ENTRY_SIZE_64, flag)) {
10182 			rval = EFAULT;
10183 			goto ret;
10184 		}
10185 		arq_status_len_in = err_entry.mtee_arq_status_len;
10186 
10187 		err_entry.mtee_cdb_len =
10188 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
10189 
10190 		if (arq_status_len_in > arq_status_len_kr)
10191 			err_entry.mtee_arq_status_len =
10192 			    arq_status_len_kr;
10193 
10194 		if (ddi_copyout(
10195 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10196 		    err_entry.mtee_cdb_buf,
10197 		    err_entry.mtee_cdb_len, flag)) {
10198 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10199 			    "st_get_error_entry: Copy cdb buffer error!");
10200 			rval = EFAULT;
10201 		}
10202 
10203 		if (ddi_copyout(
10204 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10205 		    err_entry.mtee_arq_status,
10206 		    err_entry.mtee_arq_status_len, flag)) {
10207 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10208 			    "st_get_error_entry: copy arq status error!");
10209 			rval = EFAULT;
10210 		}
10211 
10212 		if (ddi_copyout(&err_entry, (void *)arg,
10213 		    MTERROR_ENTRY_SIZE_64, flag)) {
10214 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10215 			    "st_get_error_entry: copy arq status out error!");
10216 			rval = EFAULT;
10217 		}
10218 		break;
10219 	}
10220 #else /* _MULTI_DATAMODEL */
10221 	if (ddi_copyin((void *)arg, &err_entry,
10222 	    MTERROR_ENTRY_SIZE_64, flag)) {
10223 		rval = EFAULT;
10224 		goto ret;
10225 	}
10226 	arq_status_len_in = err_entry.mtee_arq_status_len;
10227 
10228 	err_entry.mtee_cdb_len =
10229 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
10230 
10231 	if (arq_status_len_in > arq_status_len_kr)
10232 		err_entry.mtee_arq_status_len =
10233 		    arq_status_len_kr;
10234 
10235 	if (ddi_copyout(
10236 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10237 	    err_entry.mtee_cdb_buf,
10238 	    err_entry.mtee_cdb_len, flag)) {
10239 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10240 		    "st_get_error_entry: Copy cdb buffer error!");
10241 		rval = EFAULT;
10242 	}
10243 
10244 	if (ddi_copyout(
10245 	    err_link_entry_p->mtees_entry.mtee_arq_status,
10246 	    err_entry.mtee_arq_status,
10247 	    err_entry.mtee_arq_status_len, flag)) {
10248 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10249 		    "st_get_error_entry: copy arq status buffer error!");
10250 		rval = EFAULT;
10251 	}
10252 
10253 	if (ddi_copyout(&err_entry, (void *)arg,
10254 	    MTERROR_ENTRY_SIZE_64, flag)) {
10255 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10256 		    "st_get_error_entry: copy arq status out error!");
10257 		rval = EFAULT;
10258 	}
10259 #endif /* _MULTI_DATAMODEL */
10260 
10261 	/*
10262 	 * update stack
10263 	 */
10264 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
10265 
10266 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
10267 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
10268 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
10269 
10270 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
10271 	    SECMDS_STATUS_SIZE);
10272 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
10273 
10274 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
10275 	err_link_entry_p = NULL;
10276 ret:
10277 	return (rval);
10278 }
10279 
10280 /*
10281  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
10282  * the scsi CDB command which causes the error and generates sense data and
10283  * the scsi status.
10284  *
10285  *      error-record stack
10286  *
10287  *
10288  *             TOP                                     BOTTOM
10289  *              ------------------------------------------
10290  *              |   0   |   1   |   2   |   ...  |   n   |
10291  *              ------------------------------------------
10292  *                  ^
10293  *                  |
10294  *       pointer to error entry
10295  *
10296  * when st driver generates one sense data record, it creates a error-entry
10297  * and pushes it onto the stack.
10298  *
10299  */
10300 
10301 static void
10302 st_update_error_stack(struct scsi_tape *un,
10303 			struct scsi_pkt *pkt,
10304 			struct scsi_arq_status *cmd)
10305 {
10306 	struct mterror_entry_stack *err_entry_tmp;
10307 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
10308 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
10309 
10310 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
10311 
10312 	ASSERT(mutex_owned(ST_MUTEX));
10313 
10314 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10315 	    "st_update_error_stack()\n");
10316 
10317 	ASSERT(cmd);
10318 	ASSERT(cdbp);
10319 	if (cdblen == 0) {
10320 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10321 		    "st_update_error_stack: CDB length error!\n");
10322 		return;
10323 	}
10324 
10325 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
10326 	ASSERT(err_entry_tmp != NULL);
10327 
10328 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
10329 	    kmem_alloc(cdblen, KM_SLEEP);
10330 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
10331 
10332 	err_entry_tmp->mtees_entry.mtee_arq_status =
10333 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
10334 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
10335 
10336 	/*
10337 	 * copy cdb command & length to current error entry
10338 	 */
10339 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
10340 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
10341 
10342 	/*
10343 	 * copy scsi status length to current error entry
10344 	 */
10345 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
10346 	    SECMDS_STATUS_SIZE;
10347 
10348 	/*
10349 	 * copy sense data and scsi status to current error entry
10350 	 */
10351 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
10352 	    SECMDS_STATUS_SIZE);
10353 
10354 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
10355 	un->un_error_entry_stk = err_entry_tmp;
10356 
10357 }
10358 
10359 /*
10360  * Empty all the error entry in stack
10361  */
10362 static void
10363 st_empty_error_stack(struct scsi_tape *un)
10364 {
10365 	struct mterror_entry_stack *linkp;
10366 
10367 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
10368 
10369 	ASSERT(mutex_owned(ST_MUTEX));
10370 
10371 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10372 	    "st_empty_entry_stack()\n");
10373 
10374 	while (un->un_error_entry_stk != NULL) {
10375 		linkp = un->un_error_entry_stk;
10376 		un->un_error_entry_stk =
10377 		    un->un_error_entry_stk->mtees_nextp;
10378 
10379 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
10380 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
10381 			    linkp->mtees_entry.mtee_cdb_len);
10382 
10383 		if (linkp->mtees_entry.mtee_arq_status != NULL)
10384 			kmem_free(linkp->mtees_entry.mtee_arq_status,
10385 			    linkp->mtees_entry.mtee_arq_status_len);
10386 
10387 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
10388 		linkp = NULL;
10389 	}
10390 }
10391 
10392 static errstate
10393 st_handle_sense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10394 {
10395 	struct scsi_pkt *pkt = BP_PKT(bp);
10396 	struct scsi_pkt *rqpkt = un->un_rqs;
10397 	struct scsi_arq_status arqstat;
10398 	recov_info *rcif = pkt->pkt_private;
10399 
10400 	errstate rval = COMMAND_DONE_ERROR;
10401 	int amt;
10402 
10403 	ST_FUNC(ST_DEVINFO, st_handle_sense);
10404 
10405 	ASSERT(mutex_owned(ST_MUTEX));
10406 
10407 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10408 	    "st_handle_sense()\n");
10409 
10410 	if (SCBP(rqpkt)->sts_busy) {
10411 		if (rcif->privatelen == sizeof (recov_info)) {
10412 			ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
10413 			    "Attempt recovery of busy unit on request sense\n");
10414 			rval = ATTEMPT_RETRY;
10415 		} else if (rcif->pkt_retry_cnt++ < st_retry_count) {
10416 			ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10417 			    "Retry busy unit on request sense\n");
10418 			rval = QUE_BUSY_COMMAND;
10419 		}
10420 		return (rval);
10421 	} else if (SCBP(rqpkt)->sts_chk) {
10422 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10423 		    "Check Condition on REQUEST SENSE\n");
10424 		return (rval);
10425 	}
10426 
10427 	/*
10428 	 * Make sure there is sense data to look at.
10429 	 */
10430 	if ((rqpkt->pkt_state & (STATE_GOT_BUS | STATE_GOT_TARGET |
10431 	    STATE_SENT_CMD | STATE_GOT_STATUS)) != (STATE_GOT_BUS |
10432 	    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) {
10433 		return (rval);
10434 	}
10435 
10436 	/* was there enough data? */
10437 	amt = (int)MAX_SENSE_LENGTH - rqpkt->pkt_resid;
10438 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
10439 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10440 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10441 		    "REQUEST SENSE couldn't get sense data\n");
10442 		return (rval);
10443 	}
10444 
10445 	bcopy(SCBP(pkt), &arqstat.sts_status,
10446 	    sizeof (struct scsi_status));
10447 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
10448 	    sizeof (struct scsi_status));
10449 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
10450 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
10451 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
10452 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
10453 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
10454 
10455 	/*
10456 	 * copy one arqstat entry in the sense data buffer
10457 	 */
10458 	st_update_error_stack(un, pkt, &arqstat);
10459 	return (st_decode_sense(un, bp, amt, &arqstat, pos));
10460 }
10461 
10462 static errstate
10463 st_handle_autosense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10464 {
10465 	struct scsi_pkt *pkt = BP_PKT(bp);
10466 	struct scsi_arq_status *arqstat =
10467 	    (struct scsi_arq_status *)pkt->pkt_scbp;
10468 	errstate rval = COMMAND_DONE_ERROR;
10469 	int amt;
10470 
10471 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
10472 
10473 	ASSERT(mutex_owned(ST_MUTEX));
10474 
10475 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10476 	    "st_handle_autosense()\n");
10477 
10478 	if (arqstat->sts_rqpkt_status.sts_busy) {
10479 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10480 		    "busy unit on request sense\n");
10481 		/*
10482 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
10483 		 * the disadvantage is that we do not have any delay for the
10484 		 * second retry of rqsense and we have to keep a packet around
10485 		 */
10486 		return (QUE_SENSE);
10487 
10488 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
10489 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10490 		    "transport error on REQUEST SENSE\n");
10491 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
10492 		    ((arqstat->sts_rqpkt_statistics &
10493 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
10494 			if (st_reset(un, RESET_LUN) == 0) {
10495 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10496 				    "recovery by resets failed\n");
10497 			}
10498 		}
10499 		return (rval);
10500 
10501 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
10502 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10503 		    "Check Condition on REQUEST SENSE\n");
10504 		return (rval);
10505 	}
10506 
10507 
10508 	/* was there enough data? */
10509 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10510 		amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10511 	} else {
10512 		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
10513 			amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10514 		} else {
10515 			amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10516 		}
10517 	}
10518 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
10519 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10520 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10521 		    "REQUEST SENSE couldn't get sense data\n");
10522 		return (rval);
10523 	}
10524 
10525 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10526 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, MAX_SENSE_LENGTH);
10527 	} else {
10528 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
10529 	}
10530 
10531 	/*
10532 	 * copy one arqstat entry in the sense data buffer
10533 	 */
10534 	st_update_error_stack(un, pkt, arqstat);
10535 
10536 	return (st_decode_sense(un, bp, amt, arqstat, pos));
10537 }
10538 
10539 static errstate
10540 st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
10541     struct scsi_arq_status *statusp, tapepos_t *pos)
10542 {
10543 	struct scsi_pkt *pkt = BP_PKT(bp);
10544 	recov_info *ri = pkt->pkt_private;
10545 	errstate rval = COMMAND_DONE_ERROR;
10546 	cmd_attribute const *attrib;
10547 	long resid;
10548 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10549 	int severity;
10550 	int get_error;
10551 
10552 	ST_FUNC(ST_DEVINFO, st_decode_sense);
10553 
10554 	ASSERT(mutex_owned(ST_MUTEX));
10555 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10556 	    "st_decode_sense()\n");
10557 
10558 	/*
10559 	 * For uscsi commands, squirrel away a copy of the
10560 	 * results of the Request Sense.
10561 	 */
10562 	if (USCSI_CMD(bp)) {
10563 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
10564 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
10565 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
10566 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
10567 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
10568 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
10569 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10570 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
10571 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
10572 		}
10573 	}
10574 
10575 	if (ri->privatelen == sizeof (recov_info)) {
10576 		attrib = ri->cmd_attrib;
10577 	} else {
10578 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10579 	}
10580 
10581 	/*
10582 	 * If the drive is an MT-02, reposition the
10583 	 * secondary error code into the proper place.
10584 	 *
10585 	 * XXX	MT-02 is non-CCS tape, so secondary error code
10586 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
10587 	 * so it's in byte 12.
10588 	 */
10589 	if (un->un_dp->type == ST_TYPE_EMULEX) {
10590 		sensep->es_code = sensep->es_add_info[0];
10591 	}
10592 
10593 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
10594 	    (caddr_t)&CDBP(pkt)->scc_cmd);
10595 
10596 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)statusp,
10597 	    sizeof (*statusp));
10598 
10599 	/* for normal I/O check extract the resid values. */
10600 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
10601 		if (sensep->es_valid) {
10602 			resid =
10603 			    (sensep->es_info_1 << 24) |
10604 			    (sensep->es_info_2 << 16) |
10605 			    (sensep->es_info_3 << 8)  |
10606 			    (sensep->es_info_4);
10607 			/* If fixed block */
10608 			if (un->un_bsize) {
10609 				resid *= un->un_bsize;
10610 			}
10611 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
10612 			resid = pkt->pkt_resid;
10613 		} else {
10614 			resid = bp->b_bcount;
10615 		}
10616 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10617 		    "st_decode_sense (rw): xferred bit = %d, resid=%ld (%d), "
10618 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
10619 		    resid,
10620 		    (sensep->es_info_1 << 24) |
10621 		    (sensep->es_info_2 << 16) |
10622 		    (sensep->es_info_3 << 8)  |
10623 		    (sensep->es_info_4),
10624 		    pkt->pkt_resid);
10625 		/*
10626 		 * The problem is, what should we believe?
10627 		 */
10628 		if (resid && (pkt->pkt_resid == 0)) {
10629 			pkt->pkt_resid = resid;
10630 		}
10631 	} else {
10632 		/*
10633 		 * If the command is SCMD_SPACE, we need to get the
10634 		 * residual as returned in the sense data, to adjust
10635 		 * our idea of current tape position correctly
10636 		 */
10637 		if ((sensep->es_valid) &&
10638 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10639 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10640 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
10641 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE_G4) ||
10642 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK)) {
10643 			resid =
10644 			    (sensep->es_info_1 << 24) |
10645 			    (sensep->es_info_2 << 16) |
10646 			    (sensep->es_info_3 << 8)  |
10647 			    (sensep->es_info_4);
10648 			bp->b_resid = resid;
10649 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10650 			    "st_decode_sense(other):	resid=%ld\n", resid);
10651 		} else {
10652 			/*
10653 			 * If the special command is SCMD_READ,
10654 			 * the correct resid will be set later.
10655 			 */
10656 			if (attrib->get_cnt != NULL) {
10657 				resid = attrib->get_cnt(pkt->pkt_cdbp);
10658 			} else {
10659 				resid = bp->b_bcount;
10660 			}
10661 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10662 			    "st_decode_sense(special read):  resid=%ld\n",
10663 			    resid);
10664 		}
10665 	}
10666 
10667 	if ((un->un_state >= ST_STATE_OPEN) &&
10668 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
10669 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
10670 		    "Failed CDB", (char *)pkt->pkt_cdbp);
10671 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10672 		    "sense data", (char *)sensep, amt);
10673 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10674 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10675 		    bp->b_bcount, resid, pkt->pkt_resid);
10676 	}
10677 
10678 	switch (un->un_status = sensep->es_key) {
10679 	case KEY_NO_SENSE:
10680 		severity = SCSI_ERR_INFO;
10681 
10682 		/*
10683 		 * Erase, locate or rewind operation in progress, retry
10684 		 * ASC  ASCQ
10685 		 *  00   18    Erase operation in progress
10686 		 *  00   19    Locate operation in progress
10687 		 *  00   1A    Rewind operation in progress
10688 		 */
10689 		if (sensep->es_add_code == 0 &&
10690 		    ((sensep->es_qual_code == 0x18) ||
10691 		    (sensep->es_qual_code == 0x19) ||
10692 		    (sensep->es_qual_code == 0x1a))) {
10693 			rval = QUE_BUSY_COMMAND;
10694 			break;
10695 		}
10696 
10697 		goto common;
10698 
10699 	case KEY_RECOVERABLE_ERROR:
10700 		severity = SCSI_ERR_RECOVERED;
10701 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10702 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10703 			if (un->un_dp->options &
10704 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10705 				rval = QUE_LAST_COMMAND;
10706 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10707 				    severity, pos->lgclblkno,
10708 				    un->un_err_pos.lgclblkno, scsi_cmds,
10709 				    sensep);
10710 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10711 				    "Command will be retried\n");
10712 			} else {
10713 				severity = SCSI_ERR_FATAL;
10714 				rval = COMMAND_DONE_ERROR_RECOVERED;
10715 				ST_DO_ERRSTATS(un, st_softerrs);
10716 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10717 				    severity, pos->lgclblkno,
10718 				    un->un_err_pos.lgclblkno, scsi_cmds,
10719 				    sensep);
10720 			}
10721 			break;
10722 		}
10723 common:
10724 		/*
10725 		 * XXX only want reads to be stopped by filemarks.
10726 		 * Don't want them to be stopped by EOT.  EOT matters
10727 		 * only on write.
10728 		 */
10729 		if (sensep->es_filmk && !sensep->es_eom) {
10730 			rval = COMMAND_DONE;
10731 		} else if (sensep->es_eom) {
10732 			rval = COMMAND_DONE;
10733 		} else if (sensep->es_ili) {
10734 			/*
10735 			 * Fun with variable length record devices:
10736 			 * for specifying larger blocks sizes than the
10737 			 * actual physical record size.
10738 			 */
10739 			if (un->un_bsize == 0 && resid > 0) {
10740 				/*
10741 				 * XXX! Ugly.
10742 				 * The requested blocksize is > tape blocksize,
10743 				 * so this is ok, so we just return the
10744 				 * actual size xferred.
10745 				 */
10746 				pkt->pkt_resid = resid;
10747 				rval = COMMAND_DONE;
10748 			} else if (un->un_bsize == 0 && resid < 0) {
10749 				/*
10750 				 * The requested blocksize is < tape blocksize,
10751 				 * so this is not ok, so we err with ENOMEM
10752 				 */
10753 				rval = COMMAND_DONE_ERROR_RECOVERED;
10754 				st_bioerror(bp, ENOMEM);
10755 			} else {
10756 				ST_DO_ERRSTATS(un, st_softerrs);
10757 				severity = SCSI_ERR_FATAL;
10758 				rval = COMMAND_DONE_ERROR;
10759 				st_bioerror(bp, EINVAL);
10760 				un->un_running.pmode = invalid;
10761 			}
10762 		} else {
10763 			/*
10764 			 * we hope and pray for this just being
10765 			 * something we can ignore (ie. a
10766 			 * truly recoverable soft error)
10767 			 */
10768 			rval = COMMAND_DONE;
10769 		}
10770 		if (sensep->es_filmk) {
10771 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10772 			    "filemark\n");
10773 			un->un_status = SUN_KEY_EOF;
10774 			pos->eof = ST_EOF_PENDING;
10775 			st_set_pe_flag(un);
10776 		}
10777 
10778 		/*
10779 		 * ignore eom when reading, a fmk should terminate reading
10780 		 */
10781 		if ((sensep->es_eom) &&
10782 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10783 			if ((sensep->es_add_code == 0) &&
10784 			    (sensep->es_qual_code == 4)) {
10785 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10786 				    "bot\n");
10787 				un->un_status = SUN_KEY_BOT;
10788 				pos->eof = ST_NO_EOF;
10789 				pos->lgclblkno = 0;
10790 				pos->fileno = 0;
10791 				pos->blkno = 0;
10792 				if (pos->pmode != legacy)
10793 					pos->pmode = legacy;
10794 			} else {
10795 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10796 				    "eom\n");
10797 				un->un_status = SUN_KEY_EOT;
10798 				pos->eof = ST_EOM;
10799 			}
10800 			st_set_pe_flag(un);
10801 		}
10802 
10803 		break;
10804 
10805 	case KEY_ILLEGAL_REQUEST:
10806 
10807 		if (un->un_laststate >= ST_STATE_OPEN) {
10808 			ST_DO_ERRSTATS(un, st_softerrs);
10809 			severity = SCSI_ERR_FATAL;
10810 		} else {
10811 			severity = SCSI_ERR_INFO;
10812 		}
10813 		break;
10814 
10815 	case KEY_MEDIUM_ERROR:
10816 		ST_DO_ERRSTATS(un, st_harderrs);
10817 		severity = SCSI_ERR_FATAL;
10818 check_keys:
10819 		/*
10820 		 * attempt to process the keys in the presence of
10821 		 * other errors
10822 		 */
10823 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10824 			/*
10825 			 * Fun with variable length record devices:
10826 			 * for specifying larger blocks sizes than the
10827 			 * actual physical record size.
10828 			 */
10829 			if (un->un_bsize == 0 && resid > 0) {
10830 				/*
10831 				 * XXX! Ugly
10832 				 */
10833 				pkt->pkt_resid = resid;
10834 			} else if (un->un_bsize == 0 && resid < 0) {
10835 				st_bioerror(bp, EINVAL);
10836 			} else {
10837 				severity = SCSI_ERR_FATAL;
10838 				rval = COMMAND_DONE_ERROR;
10839 				st_bioerror(bp, EINVAL);
10840 			}
10841 		}
10842 		if (sensep->es_filmk) {
10843 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10844 			    "filemark\n");
10845 			un->un_status = SUN_KEY_EOF;
10846 			pos->eof = ST_EOF_PENDING;
10847 			st_set_pe_flag(un);
10848 		}
10849 
10850 		/*
10851 		 * ignore eom when reading, a fmk should terminate reading
10852 		 */
10853 		if ((sensep->es_eom) &&
10854 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10855 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10856 			un->un_status = SUN_KEY_EOT;
10857 			pos->eof = ST_EOM;
10858 			st_set_pe_flag(un);
10859 		}
10860 
10861 		break;
10862 
10863 	case KEY_VOLUME_OVERFLOW:
10864 		ST_DO_ERRSTATS(un, st_softerrs);
10865 		pos->eof = ST_EOM;
10866 		severity = SCSI_ERR_FATAL;
10867 		rval = COMMAND_DONE_ERROR;
10868 		goto check_keys;
10869 
10870 	case KEY_HARDWARE_ERROR:
10871 		ST_DO_ERRSTATS(un, st_harderrs);
10872 		severity = SCSI_ERR_FATAL;
10873 		rval = COMMAND_DONE_ERROR;
10874 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10875 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10876 		break;
10877 
10878 	case KEY_BLANK_CHECK:
10879 		ST_DO_ERRSTATS(un, st_softerrs);
10880 		severity = SCSI_ERR_INFO;
10881 
10882 		/*
10883 		 * if not a special request and some data was xferred then it
10884 		 * it is not an error yet
10885 		 */
10886 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10887 			/*
10888 			 * no error for read with or without data xferred
10889 			 */
10890 			un->un_status = SUN_KEY_EOT;
10891 			pos->eof = ST_EOT;
10892 			rval = COMMAND_DONE_ERROR;
10893 			un->un_running.pmode = invalid;
10894 			st_set_pe_flag(un);
10895 			goto check_keys;
10896 		} else if (bp != un->un_sbufp &&
10897 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10898 			rval = COMMAND_DONE;
10899 		} else {
10900 			rval = COMMAND_DONE_ERROR_RECOVERED;
10901 		}
10902 
10903 		if (un->un_laststate >= ST_STATE_OPEN) {
10904 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10905 			    "blank check\n");
10906 			pos->eof = ST_EOM;
10907 		}
10908 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10909 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10910 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
10911 		    (un->un_dp->options & ST_KNOWS_EOD)) {
10912 			/*
10913 			 * we were doing a fast forward by skipping
10914 			 * multiple fmk at the time
10915 			 */
10916 			st_bioerror(bp, EIO);
10917 			severity = SCSI_ERR_RECOVERED;
10918 			rval	 = COMMAND_DONE;
10919 		}
10920 		st_set_pe_flag(un);
10921 		goto check_keys;
10922 
10923 	case KEY_WRITE_PROTECT:
10924 		if (st_wrongtapetype(un)) {
10925 			un->un_status = SUN_KEY_WRONGMEDIA;
10926 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10927 			    "wrong tape for writing- use DC6150 tape "
10928 			    "(or equivalent)\n");
10929 			severity = SCSI_ERR_UNKNOWN;
10930 		} else {
10931 			severity = SCSI_ERR_FATAL;
10932 		}
10933 		ST_DO_ERRSTATS(un, st_harderrs);
10934 		rval = COMMAND_DONE_ERROR;
10935 		st_bioerror(bp, EACCES);
10936 		break;
10937 
10938 	case KEY_UNIT_ATTENTION:
10939 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10940 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
10941 
10942 		un->un_unit_attention_flags |= 1;
10943 		/*
10944 		 * If we have detected a Bus Reset and the tape
10945 		 * drive has been reserved.
10946 		 */
10947 		if (ST_RQSENSE->es_add_code == 0x29) {
10948 			rval = DEVICE_RESET;
10949 			if ((un->un_rsvd_status &
10950 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
10951 			    ST_RESERVE) {
10952 				un->un_rsvd_status |= ST_LOST_RESERVE;
10953 				ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
10954 				    "st_decode_sense: Lost Reservation\n");
10955 			}
10956 		}
10957 
10958 		/*
10959 		 * If this is a recovery command and retrable, retry.
10960 		 */
10961 		if (bp == un->un_recov_buf) {
10962 			severity = SCSI_ERR_INFO;
10963 			if (attrib->retriable &&
10964 			    ri->pkt_retry_cnt++ < st_retry_count) {
10965 				rval = QUE_COMMAND;
10966 			} else {
10967 				rval = COMMAND_DONE_ERROR;
10968 			}
10969 			break; /* Don't set position invalid */
10970 		}
10971 
10972 		/*
10973 		 * If ST_APPLICATION_RESERVATIONS is set,
10974 		 * If the asc/ascq indicates that the reservation
10975 		 * has been cleared just allow the write to continue
10976 		 * which would force a scsi 2 reserve.
10977 		 * If preempted that persistent reservation
10978 		 * the scsi 2 reserve would get a reservation conflict.
10979 		 */
10980 		if ((un->un_rsvd_status &
10981 		    ST_APPLICATION_RESERVATIONS) != 0) {
10982 			/*
10983 			 * RESERVATIONS PREEMPTED
10984 			 * With MPxIO this could be a fail over? XXX
10985 			 */
10986 			if (ST_RQSENSE->es_add_code == 0x2a &&
10987 			    ST_RQSENSE->es_qual_code == 0x03) {
10988 				severity = SCSI_ERR_INFO;
10989 				rval = COMMAND_DONE_ERROR;
10990 				pos->pmode = invalid;
10991 				break;
10992 			/*
10993 			 * RESERVATIONS RELEASED
10994 			 */
10995 			} else if (ST_RQSENSE->es_add_code == 0x2a &&
10996 			    ST_RQSENSE->es_qual_code == 0x04) {
10997 				severity = SCSI_ERR_INFO;
10998 				rval = COMMAND_DONE;
10999 				break;
11000 			}
11001 		}
11002 
11003 		if (un->un_state <= ST_STATE_OPENING) {
11004 			/*
11005 			 * Look, the tape isn't open yet, now determine
11006 			 * if the cause is a BUS RESET, Save the file
11007 			 * and Block positions for the callers to
11008 			 * recover from the loss of position.
11009 			 */
11010 			severity = SCSI_ERR_INFO;
11011 			if ((pos->pmode != invalid) &&
11012 			    (rval == DEVICE_RESET) &&
11013 			    (un->un_restore_pos != 1)) {
11014 				un->un_save_fileno = pos->fileno;
11015 				un->un_save_blkno = pos->blkno;
11016 				un->un_restore_pos = 1;
11017 			}
11018 
11019 			if (attrib->retriable &&
11020 			    ri->pkt_retry_cnt++ < st_retry_count) {
11021 				rval = QUE_COMMAND;
11022 			} else if (rval == DEVICE_RESET) {
11023 				break;
11024 			} else {
11025 				rval = COMMAND_DONE_ERROR;
11026 			}
11027 		/*
11028 		 * Means it thinks the mode parameters have changed.
11029 		 * This is the result of a reset clearing settings or
11030 		 * another initiator changing what we set.
11031 		 */
11032 		}
11033 		if (ST_RQSENSE->es_add_code == 0x2a) {
11034 			if (ST_RQSENSE->es_qual_code == 0x1) {
11035 				/* Error recovery will modeselect and retry. */
11036 				rval = DEVICE_TAMPER;
11037 				severity = SCSI_ERR_INFO;
11038 				break; /* don't set position invalid */
11039 			}
11040 			if (ST_RQSENSE->es_qual_code == 0x0 ||
11041 			    ST_RQSENSE->es_qual_code == 0x2 ||
11042 			    ST_RQSENSE->es_qual_code == 0x3 ||
11043 			    ST_RQSENSE->es_qual_code == 0x4 ||
11044 			    ST_RQSENSE->es_qual_code == 0x5 ||
11045 			    ST_RQSENSE->es_qual_code == 0x6 ||
11046 			    ST_RQSENSE->es_qual_code == 0x7) {
11047 				rval = DEVICE_TAMPER;
11048 				severity = SCSI_ERR_INFO;
11049 			}
11050 		} else if (ST_RQSENSE->es_add_code == 0x28 &&
11051 		    ((ST_RQSENSE->es_qual_code == 0x0) ||
11052 		    ST_RQSENSE->es_qual_code == 0x5)) {
11053 			/*
11054 			 * Not Ready to Ready change, Media may have changed.
11055 			 */
11056 			rval = DEVICE_TAMPER;
11057 			severity = SCSI_ERR_RETRYABLE;
11058 		} else {
11059 			if (rval != DEVICE_RESET) {
11060 				rval = COMMAND_DONE_ERROR;
11061 			} else {
11062 				/*
11063 				 * Returning DEVICE_RESET will call
11064 				 * error recovery.
11065 				 */
11066 				severity = SCSI_ERR_INFO;
11067 				break; /* don't set position invalid */
11068 			}
11069 			/*
11070 			 * Check if it is an Unexpected Unit Attention.
11071 			 * If state is >= ST_STATE_OPEN, we have
11072 			 * already done the initialization .
11073 			 * In this case it is Fatal Error
11074 			 * since no further reading/writing
11075 			 * can be done with fileno set to < 0.
11076 			 */
11077 			if (un->un_state >= ST_STATE_OPEN) {
11078 				ST_DO_ERRSTATS(un, st_harderrs);
11079 				severity = SCSI_ERR_FATAL;
11080 			} else {
11081 				severity = SCSI_ERR_INFO;
11082 			}
11083 		}
11084 
11085 		pos->pmode = invalid;
11086 
11087 		break;
11088 
11089 	case KEY_NOT_READY:
11090 		/*
11091 		 * If in process of getting ready retry.
11092 		 */
11093 		if (sensep->es_add_code == 0x04) {
11094 			switch (sensep->es_qual_code) {
11095 			case 0x07:
11096 				/*
11097 				 * We get here when the tape is rewinding.
11098 				 * QUE_BUSY_COMMAND retries every 10 seconds.
11099 				 */
11100 				if (ri->pkt_retry_cnt++ <
11101 				    (un->un_dp->rewind_timeout / 10)) {
11102 					rval = QUE_BUSY_COMMAND;
11103 					severity = SCSI_ERR_INFO;
11104 				} else {
11105 					/* give up */
11106 					rval = COMMAND_DONE_ERROR;
11107 					severity = SCSI_ERR_FATAL;
11108 				}
11109 				break;
11110 			case 0x01:
11111 				if (ri->pkt_retry_cnt++ < st_retry_count) {
11112 					rval = QUE_COMMAND;
11113 					severity = SCSI_ERR_INFO;
11114 					break;
11115 				}
11116 			default: /* FALLTHRU */
11117 				/* give up */
11118 				rval = COMMAND_DONE_ERROR;
11119 				severity = SCSI_ERR_FATAL;
11120 			}
11121 		} else {
11122 			/* give up */
11123 			rval = COMMAND_DONE_ERROR;
11124 			severity = SCSI_ERR_FATAL;
11125 		}
11126 
11127 		/*
11128 		 * If this was an error and after device opened
11129 		 * do error stats.
11130 		 */
11131 		if (rval == COMMAND_DONE_ERROR &&
11132 		    un->un_state > ST_STATE_OPENING) {
11133 			ST_DO_ERRSTATS(un, st_harderrs);
11134 		}
11135 
11136 		if (ST_RQSENSE->es_add_code == 0x3a) {
11137 			if (st_error_level >= SCSI_ERR_FATAL)
11138 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11139 				    "Tape not inserted in drive\n");
11140 			un->un_mediastate = MTIO_EJECTED;
11141 			cv_broadcast(&un->un_state_cv);
11142 		}
11143 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
11144 		    (rval != QUE_COMMAND))
11145 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
11146 		break;
11147 
11148 	case KEY_ABORTED_COMMAND:
11149 		/* XXX Do drives return this when they see a lost light? */
11150 		/* Testing would say yes */
11151 
11152 		if (ri->pkt_retry_cnt++ < st_retry_count) {
11153 			rval = ATTEMPT_RETRY;
11154 			severity = SCSI_ERR_RETRYABLE;
11155 			goto check_keys;
11156 		}
11157 		/*
11158 		 * Probably a parity error...
11159 		 * if we retry here then this may cause data to be
11160 		 * written twice or data skipped during reading
11161 		 */
11162 		ST_DO_ERRSTATS(un, st_harderrs);
11163 		severity = SCSI_ERR_FATAL;
11164 		rval = COMMAND_DONE_ERROR;
11165 		goto check_keys;
11166 
11167 	default:
11168 		/*
11169 		 * Undecoded sense key.	 Try retries and hope
11170 		 * that will fix the problem.  Otherwise, we're
11171 		 * dead.
11172 		 */
11173 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11174 		    "Unhandled Sense Key '%s'\n",
11175 		    sense_keys[un->un_status]);
11176 		ST_DO_ERRSTATS(un, st_harderrs);
11177 		severity = SCSI_ERR_FATAL;
11178 		rval = COMMAND_DONE_ERROR;
11179 		goto check_keys;
11180 	}
11181 
11182 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
11183 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
11184 	    (un->un_laststate > ST_STATE_OPENING) &&
11185 	    (severity >= st_error_level))) {
11186 
11187 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
11188 		    pos->lgclblkno, un->un_err_pos.lgclblkno,
11189 		    scsi_cmds, sensep);
11190 		if (sensep->es_filmk) {
11191 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11192 			    "File Mark Detected\n");
11193 		}
11194 		if (sensep->es_eom) {
11195 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11196 			    "End-of-Media Detected\n");
11197 		}
11198 		if (sensep->es_ili) {
11199 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11200 			    "Incorrect Length Indicator Set\n");
11201 		}
11202 	}
11203 	get_error = geterror(bp);
11204 	if (((rval == COMMAND_DONE_ERROR) ||
11205 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
11206 	    ((get_error == EIO) || (get_error == 0))) {
11207 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
11208 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
11209 		if (un->un_rqs_state & ST_RQS_READ) {
11210 			un->un_rqs_state &= ~(ST_RQS_READ);
11211 		} else {
11212 			un->un_rqs_state |= ST_RQS_OVR;
11213 		}
11214 	}
11215 
11216 	return (rval);
11217 }
11218 
11219 
11220 static int
11221 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
11222 {
11223 	int status = TRAN_ACCEPT;
11224 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
11225 
11226 	mutex_enter(ST_MUTEX);
11227 
11228 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
11229 
11230 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11231 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
11232 
11233 	/*
11234 	 * Check to see if we hit the retry timeout. We check to make sure
11235 	 * this is the first one on the runq and make sure we have not
11236 	 * queued up any more, so this one has to be the last on the list
11237 	 * also. If it is not, we have to fail.  If it is not the first, but
11238 	 * is the last we are in trouble anyway, as we are in the interrupt
11239 	 * context here.
11240 	 */
11241 	if ((pktinfo->pkt_retry_cnt > st_retry_count) ||
11242 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
11243 		goto exit;
11244 	}
11245 
11246 	if (un->un_throttle) {
11247 		un->un_last_throttle = un->un_throttle;
11248 		un->un_throttle = 0;
11249 	}
11250 
11251 	/*
11252 	 * Here we know : bp is the first and last one on the runq
11253 	 * it is not necessary to put it back on the head of the
11254 	 * waitq and then move from waitq to runq. Save this queuing
11255 	 * and call scsi_transport.
11256 	 */
11257 	ST_CDB(ST_DEVINFO, "Retry lcmd CDB", (char *)BP_PKT(bp)->pkt_cdbp);
11258 
11259 	status = st_transport(un, BP_PKT(bp));
11260 
11261 	if (status == TRAN_ACCEPT) {
11262 		if (un->un_last_throttle) {
11263 			un->un_throttle = un->un_last_throttle;
11264 		}
11265 		mutex_exit(ST_MUTEX);
11266 
11267 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11268 		    "restart transport \n");
11269 		return (0);
11270 	}
11271 
11272 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
11273 	mutex_exit(ST_MUTEX);
11274 
11275 	if (status == TRAN_BUSY) {
11276 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
11277 			return (0);
11278 		}
11279 	}
11280 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11281 	    "restart transport rejected\n");
11282 	mutex_enter(ST_MUTEX);
11283 	ST_DO_ERRSTATS(un, st_transerrs);
11284 	if (un->un_last_throttle) {
11285 		un->un_throttle = un->un_last_throttle;
11286 	}
11287 exit:
11288 	mutex_exit(ST_MUTEX);
11289 	return (-1);
11290 }
11291 
11292 static int
11293 st_wrongtapetype(struct scsi_tape *un)
11294 {
11295 
11296 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
11297 
11298 	ASSERT(mutex_owned(ST_MUTEX));
11299 
11300 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
11301 
11302 	/*
11303 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
11304 	 */
11305 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
11306 		switch (un->un_dp->type) {
11307 		case ST_TYPE_WANGTEK:
11308 		case ST_TYPE_ARCHIVE:
11309 			/*
11310 			 * If this really worked, we could go off of
11311 			 * the density codes set in the modesense
11312 			 * page. For this drive, 0x10 == QIC-120,
11313 			 * 0xf == QIC-150, and 0x5 should be for
11314 			 * both QIC-24 and, maybe, QIC-11. However,
11315 			 * the h/w doesn't do what the manual says
11316 			 * that it should, so we'll key off of
11317 			 * getting a WRITE PROTECT error AND wp *not*
11318 			 * set in the mode sense information.
11319 			 */
11320 			/*
11321 			 * XXX but we already know that status is
11322 			 * write protect, so don't check it again.
11323 			 */
11324 
11325 			if (un->un_status == KEY_WRITE_PROTECT &&
11326 			    un->un_mspl->wp == 0) {
11327 				return (1);
11328 			}
11329 			break;
11330 		default:
11331 			break;
11332 		}
11333 	}
11334 	return (0);
11335 }
11336 
11337 static errstate
11338 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
11339 {
11340 	errstate action;
11341 	recov_info *rcvi = pkt->pkt_private;
11342 	buf_t *bp = rcvi->cmd_bp;
11343 	struct scsi_arq_status *stat = (struct scsi_arq_status *)pkt->pkt_scbp;
11344 
11345 	ST_FUNC(ST_DEVINFO, st_check_error);
11346 
11347 	ASSERT(mutex_owned(ST_MUTEX));
11348 
11349 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
11350 
11351 	switch (SCBP_C(pkt)) {
11352 	case STATUS_RESERVATION_CONFLICT:
11353 		/*
11354 		 * Command recovery is enabled, not just opening,
11355 		 * we had the drive reserved and we thing its ours.
11356 		 * Call recovery to attempt to take it back.
11357 		 */
11358 		if ((rcvi->privatelen == sizeof (recov_info)) &&
11359 		    (bp != un->un_recov_buf) &&
11360 		    (un->un_state > ST_STATE_OPEN_PENDING_IO) &&
11361 		    ((un->un_rsvd_status & (ST_RESERVE |
11362 		    ST_APPLICATION_RESERVATIONS)) != 0)) {
11363 			action = ATTEMPT_RETRY;
11364 			un->un_rsvd_status |= ST_LOST_RESERVE;
11365 		} else {
11366 			action = COMMAND_DONE_EACCES;
11367 			un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
11368 		}
11369 		break;
11370 
11371 	case STATUS_BUSY:
11372 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
11373 		if (rcvi->privatelen == sizeof (recov_info) &&
11374 		    un->un_multipath && (pkt->pkt_state == (STATE_GOT_BUS |
11375 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS))) {
11376 			/*
11377 			 * Status returned by scsi_vhci indicating path
11378 			 * has failed over.
11379 			 */
11380 			action = PATH_FAILED;
11381 			break;
11382 		}
11383 		/* FALLTHRU */
11384 	case STATUS_QFULL:
11385 		if (rcvi->privatelen == sizeof (recov_info)) {
11386 			/*
11387 			 * If recovery is inabled use it instead of
11388 			 * blind reties.
11389 			 */
11390 			action = ATTEMPT_RETRY;
11391 		} else if (rcvi->pkt_retry_cnt++ < st_retry_count) {
11392 			action = QUE_BUSY_COMMAND;
11393 		} else if ((un->un_rsvd_status &
11394 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
11395 			/*
11396 			 * If this is a command done before reserve is done
11397 			 * don't reset.
11398 			 */
11399 			action = COMMAND_DONE_ERROR;
11400 		} else {
11401 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11402 			    "unit busy too long\n");
11403 			(void) st_reset(un, RESET_ALL);
11404 			action = COMMAND_DONE_ERROR;
11405 		}
11406 		break;
11407 
11408 	case STATUS_CHECK:
11409 	case STATUS_TERMINATED:
11410 		/*
11411 		 * we should only get here if the auto rqsense failed
11412 		 * thru a uscsi cmd without autorequest sense
11413 		 * so we just try again
11414 		 */
11415 		if (un->un_arq_enabled &&
11416 		    stat->sts_rqpkt_reason == CMD_CMPLT &&
11417 		    (stat->sts_rqpkt_state & (STATE_GOT_BUS |
11418 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) ==
11419 		    (STATE_GOT_BUS | STATE_GOT_TARGET | STATE_SENT_CMD |
11420 		    STATE_GOT_STATUS)) {
11421 
11422 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11423 			    "Really got sense data\n");
11424 			action = st_decode_sense(un, bp, MAX_SENSE_LENGTH -
11425 			    pkt->pkt_resid, stat, &un->un_pos);
11426 		} else {
11427 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11428 			    "Trying to queue sense command\n");
11429 			action = QUE_SENSE;
11430 		}
11431 		break;
11432 
11433 	case STATUS_TASK_ABORT:
11434 		/*
11435 		 * This is an aborted task. This can be a reset on the other
11436 		 * port of a multiport drive. Lets try and recover it.
11437 		 */
11438 		action = DEVICE_RESET;
11439 		break;
11440 
11441 	default:
11442 		action = COMMAND_DONE;
11443 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
11444 		    "Unexpected scsi status byte 0x%x\n", SCBP_C(pkt));
11445 	}
11446 	return (action);
11447 }
11448 
11449 static void
11450 st_calc_bnum(struct scsi_tape *un, struct buf *bp, struct scsi_pkt *pkt)
11451 {
11452 	int nblks;
11453 	int nfiles;
11454 	long count;
11455 	recov_info *ri = pkt->pkt_private;
11456 	cmd_attribute const *attrib;
11457 
11458 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
11459 
11460 	ASSERT(mutex_owned(ST_MUTEX));
11461 
11462 	if (ri->privatelen == sizeof (recov_info)) {
11463 		attrib = ri->cmd_attrib;
11464 		ASSERT(attrib->recov_pos_type == POS_EXPECTED);
11465 		ASSERT(attrib->chg_tape_pos);
11466 	} else {
11467 		ri = NULL;
11468 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
11469 	}
11470 
11471 	count = bp->b_bcount - bp->b_resid;
11472 
11473 	/* Command reads or writes data */
11474 	if (attrib->transfers_data != TRAN_NONE) {
11475 		if (count == 0) {
11476 			/* failed writes should not make it here */
11477 			ASSERT(attrib->transfers_data == TRAN_READ);
11478 			nblks = 0;
11479 			nfiles = 1;
11480 		} else if (un->un_bsize == 0) {
11481 			/*
11482 			 * If variable block mode.
11483 			 * Fixed bit in CBD should be zero.
11484 			 */
11485 			ASSERT((pkt->pkt_cdbp[1] & 1) == 0);
11486 			nblks = 1;
11487 			un->un_kbytes_xferred += (count / ONE_K);
11488 			nfiles = 0;
11489 		} else {
11490 			/*
11491 			 * If fixed block mode.
11492 			 * Fixed bit in CBD should be one.
11493 			 */
11494 			ASSERT((pkt->pkt_cdbp[1] & 1) == 1);
11495 			nblks = (count / un->un_bsize);
11496 			un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
11497 			nfiles = 0;
11498 		}
11499 		/*
11500 		 * So its possable to read some blocks and hit a filemark.
11501 		 * Example reading in fixed block mode where more then one
11502 		 * block at a time is requested. In this case because the
11503 		 * filemark is hit something less then the requesed number
11504 		 * of blocks is read.
11505 		 */
11506 		if (un->un_pos.eof == ST_EOF_PENDING && bp->b_resid) {
11507 			nfiles = 1;
11508 		}
11509 	} else {
11510 		nblks = 0;
11511 		nfiles = count;
11512 	}
11513 
11514 	/*
11515 	 * If some command failed after this one started and it seems
11516 	 * to have finshed without error count the position.
11517 	 */
11518 	if (un->un_persistence && un->un_persist_errors) {
11519 		ASSERT(un->un_pos.pmode != invalid);
11520 	}
11521 
11522 	if (attrib->chg_tape_direction == DIR_FORW) {
11523 		un->un_pos.blkno += nblks;
11524 		un->un_pos.lgclblkno += nblks;
11525 		un->un_pos.lgclblkno += nfiles;
11526 	} else if (attrib->chg_tape_direction == DIR_REVC) {
11527 		un->un_pos.blkno -= nblks;
11528 		un->un_pos.lgclblkno -= nblks;
11529 		un->un_pos.lgclblkno -= nfiles;
11530 	} else {
11531 		ASSERT(0);
11532 	}
11533 
11534 	/* recovery disabled */
11535 	if (ri == NULL) {
11536 		un->un_running.pmode = invalid;
11537 		return;
11538 	}
11539 
11540 	/*
11541 	 * If we didn't just read a filemark.
11542 	 */
11543 	if (un->un_pos.eof != ST_EOF_PENDING) {
11544 		ASSERT(nblks != 0 && nfiles == 0);
11545 		/*
11546 		 * If Previously calulated expected position does not match
11547 		 * debug the expected position.
11548 		 */
11549 		if ((ri->pos.pmode != invalid) && nblks &&
11550 		    ((un->un_pos.blkno != ri->pos.blkno) ||
11551 		    (un->un_pos.lgclblkno != ri->pos.lgclblkno))) {
11552 #ifdef STDEBUG
11553 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11554 			    "Expected", &ri->pos);
11555 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11556 			    "But Got", &un->un_pos);
11557 #endif
11558 			un->un_running.pmode = invalid;
11559 		}
11560 	} else {
11561 		ASSERT(nfiles != 0);
11562 		if (un->un_running.pmode != invalid) {
11563 			/*
11564 			 * blkno and lgclblkno already counted in
11565 			 * st_add_recovery_info_to_pkt(). Since a block was not
11566 			 * read and a filemark was.
11567 			 */
11568 			if (attrib->chg_tape_direction == DIR_FORW) {
11569 				un->un_running.fileno++;
11570 				un->un_running.blkno = 0;
11571 			} else if (attrib->chg_tape_direction == DIR_REVC) {
11572 				un->un_running.fileno--;
11573 				un->un_running.blkno = LASTBLK;
11574 			}
11575 		}
11576 	}
11577 }
11578 
11579 static void
11580 st_set_state(struct scsi_tape *un, struct buf *bp)
11581 {
11582 	struct scsi_pkt *sp = BP_PKT(bp);
11583 	struct uscsi_cmd *ucmd;
11584 
11585 	ST_FUNC(ST_DEVINFO, st_set_state);
11586 
11587 	ASSERT(mutex_owned(ST_MUTEX));
11588 	ASSERT(bp != un->un_recov_buf);
11589 
11590 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11591 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
11592 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
11593 
11594 	if (bp != un->un_sbufp) {
11595 #ifdef STDEBUG
11596 		if (DEBUGGING && sp->pkt_resid) {
11597 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11598 			    "pkt_resid %ld bcount %ld\n",
11599 			    sp->pkt_resid, bp->b_bcount);
11600 		}
11601 #endif
11602 		bp->b_resid = sp->pkt_resid;
11603 		if (geterror(bp) != EIO) {
11604 			st_calc_bnum(un, bp, sp);
11605 		}
11606 		if (bp->b_flags & B_READ) {
11607 			un->un_lastop = ST_OP_READ;
11608 			un->un_fmneeded = 0;
11609 		} else {
11610 			un->un_lastop = ST_OP_WRITE;
11611 			if (un->un_dp->options & ST_REEL) {
11612 				un->un_fmneeded = 2;
11613 			} else {
11614 				un->un_fmneeded = 1;
11615 			}
11616 		}
11617 		/*
11618 		 * all is honky dory at this point, so let's
11619 		 * readjust the throttle, to increase speed, if we
11620 		 * have not throttled down.
11621 		 */
11622 		if (un->un_throttle) {
11623 			un->un_throttle = un->un_max_throttle;
11624 		}
11625 	} else {
11626 		optype new_lastop = ST_OP_NIL;
11627 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
11628 
11629 		switch (cmd) {
11630 		case SCMD_WRITE:
11631 		case SCMD_WRITE_G4:
11632 			bp->b_resid = sp->pkt_resid;
11633 			new_lastop = ST_OP_WRITE;
11634 			if (geterror(bp) == EIO) {
11635 				break;
11636 			}
11637 			st_calc_bnum(un, bp, sp);
11638 			if (un->un_dp->options & ST_REEL) {
11639 				un->un_fmneeded = 2;
11640 			} else {
11641 				un->un_fmneeded = 1;
11642 			}
11643 			break;
11644 		case SCMD_READ:
11645 		case SCMD_READ_G4:
11646 			bp->b_resid = sp->pkt_resid;
11647 			new_lastop = ST_OP_READ;
11648 			if (geterror(bp) == EIO) {
11649 				break;
11650 			}
11651 			st_calc_bnum(un, bp, sp);
11652 			un->un_fmneeded = 0;
11653 			break;
11654 		case SCMD_WRITE_FILE_MARK_G4:
11655 		case SCMD_WRITE_FILE_MARK:
11656 		{
11657 			int fmdone;
11658 
11659 			if (un->un_pos.eof != ST_EOM) {
11660 				un->un_pos.eof = ST_NO_EOF;
11661 			}
11662 			fmdone = (bp->b_bcount - bp->b_resid);
11663 			if (fmdone > 0) {
11664 				un->un_lastop = new_lastop = ST_OP_WEOF;
11665 				un->un_pos.lgclblkno += fmdone;
11666 				un->un_pos.fileno += fmdone;
11667 				un->un_pos.blkno = 0;
11668 			} else {
11669 				new_lastop = ST_OP_CTL;
11670 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11671 				    "Flushed buffer\n");
11672 			}
11673 			if (fmdone > un->un_fmneeded) {
11674 				un->un_fmneeded = 0;
11675 			} else {
11676 				un->un_fmneeded -= fmdone;
11677 			}
11678 			break;
11679 		}
11680 		case SCMD_REWIND:
11681 			un->un_pos.eof = ST_NO_EOF;
11682 			un->un_pos.fileno = 0;
11683 			un->un_pos.blkno = 0;
11684 			un->un_pos.lgclblkno = 0;
11685 			if (un->un_pos.pmode != legacy)
11686 				un->un_pos.pmode = legacy;
11687 			new_lastop = ST_OP_CTL;
11688 			un->un_restore_pos = 0;
11689 			break;
11690 
11691 		case SCMD_SPACE:
11692 		case SCMD_SPACE_G4:
11693 		{
11694 			int64_t count;
11695 			int64_t resid;
11696 			int64_t done;
11697 			cmd_attribute const *attrib;
11698 			recov_info *ri = sp->pkt_private;
11699 
11700 			if (ri->privatelen == sizeof (recov_info)) {
11701 				attrib = ri->cmd_attrib;
11702 			} else {
11703 				attrib =
11704 				    st_lookup_cmd_attribute(sp->pkt_cdbp[0]);
11705 			}
11706 
11707 			resid = (int64_t)SPACE_CNT(bp->b_resid);
11708 			count = (int64_t)attrib->get_cnt(sp->pkt_cdbp);
11709 
11710 			if (count >= 0) {
11711 				done = (count - resid);
11712 			} else {
11713 				done = ((-count) - resid);
11714 			}
11715 			if (done > 0) {
11716 				un->un_lastop = new_lastop = ST_OP_CTL;
11717 			} else {
11718 				new_lastop = ST_OP_CTL;
11719 			}
11720 
11721 			ST_SPAC(ST_DEVINFO, st_label, CE_WARN,
11722 			    "space cmd: cdb[1] = %s\n"
11723 			    "space data:       = 0x%lx\n"
11724 			    "space count:      = %"PRId64"\n"
11725 			    "space resid:      = %"PRId64"\n"
11726 			    "spaces done:      = %"PRId64"\n"
11727 			    "fileno before     = %d\n"
11728 			    "blkno before      = %d\n",
11729 			    space_strs[sp->pkt_cdbp[1] & 7],
11730 			    bp->b_bcount,
11731 			    count, resid, done,
11732 			    un->un_pos.fileno, un->un_pos.blkno);
11733 
11734 			switch (sp->pkt_cdbp[1]) {
11735 			case SPACE_TYPE(SP_FLM):
11736 				/* Space file forward */
11737 				if (count >= 0) {
11738 					if (un->un_pos.eof <= ST_EOF) {
11739 						un->un_pos.eof = ST_NO_EOF;
11740 					}
11741 					un->un_pos.fileno += done;
11742 					un->un_pos.blkno = 0;
11743 					break;
11744 				}
11745 				/* Space file backward */
11746 				if (done > un->un_pos.fileno) {
11747 					un->un_pos.fileno = 0;
11748 					un->un_pos.blkno = 0;
11749 				} else {
11750 					un->un_pos.fileno -= done;
11751 					un->un_pos.blkno = LASTBLK;
11752 					un->un_running.pmode = invalid;
11753 				}
11754 				break;
11755 			case SPACE_TYPE(SP_BLK):
11756 				/* Space block forward */
11757 				if (count >= 0) {
11758 					un->un_pos.blkno += done;
11759 					break;
11760 				}
11761 				/* Space block backward */
11762 				if (un->un_pos.eof >= ST_EOF_PENDING) {
11763 				/*
11764 				 * we stepped back into
11765 				 * a previous file; we are not
11766 				 * making an effort to pretend that
11767 				 * we are still in the current file
11768 				 * ie. logical == physical position
11769 				 * and leave it to st_ioctl to correct
11770 				 */
11771 					if (done > un->un_pos.blkno) {
11772 						un->un_pos.blkno = 0;
11773 					} else {
11774 						un->un_pos.fileno--;
11775 						un->un_pos.blkno = LASTBLK;
11776 						un->un_running.pmode = invalid;
11777 					}
11778 				} else {
11779 					un->un_pos.blkno -= done;
11780 				}
11781 				break;
11782 			case SPACE_TYPE(SP_SQFLM):
11783 				un->un_pos.pmode = logical;
11784 				un->un_pos.blkno = 0;
11785 				un->un_lastop = new_lastop = ST_OP_CTL;
11786 				break;
11787 			case SPACE_TYPE(SP_EOD):
11788 				un->un_pos.pmode = logical;
11789 				un->un_pos.eof = ST_EOM;
11790 				un->un_status = KEY_BLANK_CHECK;
11791 				break;
11792 			default:
11793 				un->un_pos.pmode = invalid;
11794 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11795 				    "Unsupported space cmd: %s\n",
11796 				    space_strs[sp->pkt_cdbp[1] & 7]);
11797 
11798 				un->un_lastop = new_lastop = ST_OP_CTL;
11799 			}
11800 
11801 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11802 			    "after_space rs %"PRId64" fil %d blk %d\n",
11803 			    resid, un->un_pos.fileno, un->un_pos.blkno);
11804 
11805 			break;
11806 		}
11807 		case SCMD_LOAD:
11808 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
11809 				un->un_pos.fileno = 0;
11810 				if (un->un_pos.pmode != legacy)
11811 					un->un_pos.pmode = legacy;
11812 			} else {
11813 				un->un_state = ST_STATE_OFFLINE;
11814 				un->un_pos.pmode = invalid;
11815 
11816 			}
11817 			/*
11818 			 * If we are loading or unloading we expect the media id
11819 			 * to change. Lets make it unknown.
11820 			 */
11821 			if (un->un_media_id != bogusID && un->un_media_id_len) {
11822 				kmem_free(un->un_media_id, un->un_media_id_len);
11823 				un->un_media_id = NULL;
11824 				un->un_media_id_len = 0;
11825 			}
11826 			un->un_density_known = 0;
11827 			un->un_pos.eof = ST_NO_EOF;
11828 			un->un_pos.blkno = 0;
11829 			un->un_lastop = new_lastop = ST_OP_CTL;
11830 			break;
11831 		case SCMD_ERASE:
11832 			un->un_pos.eof = ST_NO_EOF;
11833 			un->un_pos.blkno = 0;
11834 			un->un_pos.fileno = 0;
11835 			un->un_pos.lgclblkno = 0;
11836 			if (un->un_pos.pmode != legacy)
11837 				un->un_pos.pmode = legacy;
11838 			new_lastop = ST_OP_CTL;
11839 			break;
11840 		case SCMD_RESERVE:
11841 			un->un_rsvd_status |= ST_RESERVE;
11842 			un->un_rsvd_status &=
11843 			    ~(ST_RELEASE | ST_LOST_RESERVE |
11844 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11845 			new_lastop = ST_OP_CTL;
11846 			break;
11847 		case SCMD_RELEASE:
11848 			un->un_rsvd_status |= ST_RELEASE;
11849 			un->un_rsvd_status &=
11850 			    ~(ST_RESERVE | ST_LOST_RESERVE |
11851 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11852 			new_lastop = ST_OP_CTL;
11853 			break;
11854 		case SCMD_PERSISTENT_RESERVE_IN:
11855 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11856 			    "PGR_IN command\n");
11857 			new_lastop = ST_OP_CTL;
11858 			break;
11859 		case SCMD_PERSISTENT_RESERVE_OUT:
11860 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
11861 			case ST_SA_SCSI3_RESERVE:
11862 			case ST_SA_SCSI3_PREEMPT:
11863 			case ST_SA_SCSI3_PREEMPTANDABORT:
11864 				un->un_rsvd_status |=
11865 				    (ST_APPLICATION_RESERVATIONS | ST_RESERVE);
11866 				un->un_rsvd_status &= ~(ST_RELEASE |
11867 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11868 				    ST_INITIATED_RESET);
11869 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11870 				    "PGR Reserve and set: entering"
11871 				    " ST_APPLICATION_RESERVATIONS mode");
11872 				break;
11873 			case ST_SA_SCSI3_REGISTER:
11874 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11875 				    "PGR Reserve register key");
11876 				un->un_rsvd_status |= ST_INIT_RESERVE;
11877 				break;
11878 			case ST_SA_SCSI3_CLEAR:
11879 				un->un_rsvd_status &= ~ST_INIT_RESERVE;
11880 				/* FALLTHROUGH */
11881 			case ST_SA_SCSI3_RELEASE:
11882 				un->un_rsvd_status &=
11883 				    ~(ST_APPLICATION_RESERVATIONS | ST_RESERVE |
11884 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11885 				    ST_INITIATED_RESET);
11886 				un->un_rsvd_status |= ST_RELEASE;
11887 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11888 				    "PGR Release and reset: exiting"
11889 				    " ST_APPLICATION_RESERVATIONS mode");
11890 				break;
11891 			}
11892 			new_lastop = ST_OP_CTL;
11893 			break;
11894 		case SCMD_TEST_UNIT_READY:
11895 		case SCMD_READ_BLKLIM:
11896 		case SCMD_REQUEST_SENSE:
11897 		case SCMD_INQUIRY:
11898 		case SCMD_RECOVER_BUF:
11899 		case SCMD_MODE_SELECT:
11900 		case SCMD_MODE_SENSE:
11901 		case SCMD_DOORLOCK:
11902 		case SCMD_READ_BUFFER:
11903 		case SCMD_REPORT_DENSITIES:
11904 		case SCMD_LOG_SELECT_G1:
11905 		case SCMD_LOG_SENSE_G1:
11906 		case SCMD_REPORT_LUNS:
11907 		case SCMD_READ_ATTRIBUTE:
11908 		case SCMD_WRITE_ATTRIBUTE:
11909 		case SCMD_SVC_ACTION_IN_G5:
11910 			new_lastop = ST_OP_CTL;
11911 			break;
11912 		case SCMD_READ_POSITION:
11913 			new_lastop = ST_OP_CTL;
11914 			/*
11915 			 * Only if the buf used was un_sbufp.
11916 			 * Among other things the prevents read positions used
11917 			 * as part of error recovery from messing up our
11918 			 * current position as they will use un_recov_buf.
11919 			 */
11920 			if (USCSI_CMD(bp)) {
11921 				(void) st_get_read_pos(un, bp);
11922 			}
11923 			break;
11924 		case SCMD_LOCATE:
11925 		case SCMD_LOCATE_G4:
11926 			/* Locate makes position mode no longer legacy */
11927 			un->un_lastop = new_lastop = ST_OP_CTL;
11928 			break;
11929 		case SCMD_MAINTENANCE_IN:
11930 			switch (sp->pkt_cdbp[1]) {
11931 			case SSVC_ACTION_GET_SUPPORTED_OPERATIONS:
11932 			case SSVC_ACTION_SET_TARGET_PORT_GROUPS:
11933 				new_lastop = ST_OP_CTL;
11934 				break;
11935 			}
11936 			if (new_lastop != ST_OP_NIL) {
11937 				break;
11938 			}
11939 		default:
11940 			/*
11941 			 * Unknown command, If was USCSI and USCSI_SILENT
11942 			 * flag was not set, set position to unknown.
11943 			 */
11944 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
11945 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
11946 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11947 				    "unknown cmd 0x%X caused loss of state\n",
11948 				    cmd);
11949 			} else {
11950 				/*
11951 				 * keep the old agreement to allow unknown
11952 				 * commands with the USCSI_SILENT set.
11953 				 * This prevents ASSERT below.
11954 				 */
11955 				new_lastop = ST_OP_CTL;
11956 				break;
11957 			}
11958 			/* FALLTHROUGH */
11959 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
11960 			un->un_pos.pmode = invalid;
11961 			un->un_lastop = new_lastop = ST_OP_CTL;
11962 			break;
11963 		}
11964 
11965 		/* new_lastop should have been changed */
11966 		ASSERT(new_lastop != ST_OP_NIL);
11967 
11968 		/* If un_lastop should copy new_lastop  */
11969 		if (((un->un_lastop == ST_OP_WRITE) ||
11970 		    (un->un_lastop == ST_OP_WEOF)) &&
11971 		    new_lastop != ST_OP_CTL) {
11972 			un->un_lastop = new_lastop;
11973 		}
11974 	}
11975 
11976 	/*
11977 	 * In the st driver we have a logical and physical file position.
11978 	 * Under BSD behavior, when you get a zero read, the logical position
11979 	 * is before the filemark but after the last record of the file.
11980 	 * The physical position is after the filemark. MTIOCGET should always
11981 	 * return the logical file position.
11982 	 *
11983 	 * The next read gives a silent skip to the next file.
11984 	 * Under SVR4, the logical file position remains before the filemark
11985 	 * until the file is closed or a space operation is performed.
11986 	 * Hence set err_resid and err_file before changing fileno if case
11987 	 * BSD Behaviour.
11988 	 */
11989 	un->un_err_resid = bp->b_resid;
11990 	COPY_POS(&un->un_err_pos, &un->un_pos);
11991 
11992 
11993 	/*
11994 	 * If we've seen a filemark via the last read operation
11995 	 * advance the file counter, but mark things such that
11996 	 * the next read operation gets a zero count. We have
11997 	 * to put this here to handle the case of sitting right
11998 	 * at the end of a tape file having seen the file mark,
11999 	 * but the tape is closed and then re-opened without
12000 	 * any further i/o. That is, the position information
12001 	 * must be updated before a close.
12002 	 */
12003 
12004 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
12005 		/*
12006 		 * If we're a 1/2" tape, and we get a filemark
12007 		 * right on block 0, *AND* we were not in the
12008 		 * first file on the tape, and we've hit logical EOM.
12009 		 * We'll mark the state so that later we do the
12010 		 * right thing (in st_close(), st_strategy() or
12011 		 * st_ioctl()).
12012 		 *
12013 		 */
12014 		if ((un->un_dp->options & ST_REEL) &&
12015 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
12016 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
12017 			un->un_pos.eof = ST_EOT_PENDING;
12018 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12019 			    "eot pending\n");
12020 			un->un_pos.fileno++;
12021 			un->un_pos.blkno = 0;
12022 		} else if (BSD_BEHAVIOR) {
12023 			/*
12024 			 * If the read of the filemark was a side effect
12025 			 * of reading some blocks (i.e., data was actually
12026 			 * read), then the EOF mark is pending and the
12027 			 * bump into the next file awaits the next read
12028 			 * operation (which will return a zero count), or
12029 			 * a close or a space operation, else the bump
12030 			 * into the next file occurs now.
12031 			 */
12032 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12033 			    "resid=%lx, bcount=%lx\n",
12034 			    bp->b_resid, bp->b_bcount);
12035 
12036 			if (bp->b_resid != bp->b_bcount) {
12037 				un->un_pos.eof = ST_EOF;
12038 			} else {
12039 				un->un_silent_skip = 1;
12040 				un->un_pos.eof = ST_NO_EOF;
12041 				un->un_pos.fileno++;
12042 				un->un_pos.lgclblkno++;
12043 				un->un_save_blkno = un->un_pos.blkno;
12044 				un->un_pos.blkno = 0;
12045 			}
12046 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12047 			    "eof of file %d, eof=%d\n",
12048 			    un->un_pos.fileno, un->un_pos.eof);
12049 		} else if (SVR4_BEHAVIOR) {
12050 			/*
12051 			 * If the read of the filemark was a side effect
12052 			 * of reading some blocks (i.e., data was actually
12053 			 * read), then the next read should return 0
12054 			 */
12055 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12056 			    "resid=%lx, bcount=%lx\n",
12057 			    bp->b_resid, bp->b_bcount);
12058 			if (bp->b_resid == bp->b_bcount) {
12059 				un->un_pos.eof = ST_EOF;
12060 			}
12061 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12062 			    "eof of file=%d, eof=%d\n",
12063 			    un->un_pos.fileno, un->un_pos.eof);
12064 		}
12065 	}
12066 }
12067 
12068 /*
12069  * set the correct un_errno, to take corner cases into consideration
12070  */
12071 static void
12072 st_set_pe_errno(struct scsi_tape *un)
12073 {
12074 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
12075 
12076 	ASSERT(mutex_owned(ST_MUTEX));
12077 
12078 	/* if errno is already set, don't reset it */
12079 	if (un->un_errno)
12080 		return;
12081 
12082 	/* here un_errno == 0 */
12083 	/*
12084 	 * if the last transfer before flushing all the
12085 	 * waiting I/O's, was 0 (resid = count), then we
12086 	 * want to give the user an error on all the rest,
12087 	 * so here.  If there was a transfer, we set the
12088 	 * resid and counts to 0, and let it drop through,
12089 	 * giving a zero return.  the next I/O will then
12090 	 * give an error.
12091 	 */
12092 	if (un->un_last_resid == un->un_last_count) {
12093 		switch (un->un_pos.eof) {
12094 		case ST_EOM:
12095 			un->un_errno = ENOMEM;
12096 			break;
12097 		case ST_EOT:
12098 		case ST_EOF:
12099 			un->un_errno = EIO;
12100 			break;
12101 		}
12102 	} else {
12103 		/*
12104 		 * we know they did not have a zero, so make
12105 		 * sure they get one
12106 		 */
12107 		un->un_last_resid = un->un_last_count = 0;
12108 	}
12109 }
12110 
12111 
12112 /*
12113  * send in a marker pkt to terminate flushing of commands by BBA (via
12114  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
12115  */
12116 static void
12117 st_hba_unflush(struct scsi_tape *un)
12118 {
12119 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
12120 
12121 	ASSERT(mutex_owned(ST_MUTEX));
12122 
12123 	if (!un->un_flush_on_errors)
12124 		return;
12125 
12126 #ifdef FLUSH_ON_ERRORS
12127 
12128 	if (!un->un_mkr_pkt) {
12129 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
12130 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
12131 
12132 		/* we slept, so it must be there */
12133 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
12134 	}
12135 
12136 	st_transport(un, un->un_mkr_pkt);
12137 #endif
12138 }
12139 
12140 static char *
12141 st_print_scsi_cmd(char cmd)
12142 {
12143 	char tmp[64];
12144 	char *cpnt;
12145 
12146 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
12147 	/* tmp goes out of scope on return and caller sees garbage */
12148 	if (cpnt == tmp) {
12149 		cpnt = "Unknown Command";
12150 	}
12151 	return (cpnt);
12152 }
12153 
12154 static void
12155 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
12156     char *title, char *cdb)
12157 {
12158 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
12159 	char buf[256];
12160 	struct scsi_tape *un;
12161 	int instance = ddi_get_instance(dip);
12162 
12163 	un = ddi_get_soft_state(st_state, instance);
12164 
12165 	ST_FUNC(dip, st_print_cdb);
12166 
12167 	/* force one line output so repeated commands are printed once */
12168 	if ((st_debug & 0x180) == 0x100) {
12169 		scsi_log(dip, label, level, "node %s cmd %s\n",
12170 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
12171 		return;
12172 	}
12173 
12174 	/* force one line output so repeated CDB's are printed once */
12175 	if ((st_debug & 0x180) == 0x80) {
12176 		st_clean_print(dip, label, level, NULL, cdb, len);
12177 	} else {
12178 		(void) sprintf(buf, "%s for cmd(%s)", title,
12179 		    st_print_scsi_cmd(*cdb));
12180 		st_clean_print(dip, label, level, buf, cdb, len);
12181 	}
12182 }
12183 
12184 static void
12185 st_clean_print(dev_info_t *dev, char *label, uint_t level,
12186     char *title, char *data, int len)
12187 {
12188 	int	i;
12189 	int 	c;
12190 	char	*format;
12191 	char	buf[256];
12192 	uchar_t	byte;
12193 
12194 	ST_FUNC(dev, st_clean_print);
12195 
12196 
12197 	if (title) {
12198 		(void) sprintf(buf, "%s:\n", title);
12199 		scsi_log(dev, label, level, "%s", buf);
12200 		level = CE_CONT;
12201 	}
12202 
12203 	for (i = 0; i < len; ) {
12204 		buf[0] = 0;
12205 		for (c = 0; c < 8 && i < len; c++, i++) {
12206 			byte = (uchar_t)data[i];
12207 			if (byte < 0x10)
12208 				format = "0x0%x ";
12209 			else
12210 				format = "0x%x ";
12211 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
12212 		}
12213 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
12214 
12215 		scsi_log(dev, label, level, "%s\n", buf);
12216 		level = CE_CONT;
12217 	}
12218 }
12219 
12220 /*
12221  * Conditionally enabled debugging
12222  */
12223 #ifdef	STDEBUG
12224 static void
12225 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
12226 {
12227 	char tmpbuf[64];
12228 
12229 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
12230 
12231 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12232 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
12233 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
12234 	    count, count,
12235 	    wait == ASYNC_CMD ? "a" : "");
12236 }
12237 #endif	/* STDEBUG */
12238 
12239 /*
12240  * Returns pointer to name of minor node name of device 'dev'.
12241  */
12242 static char *
12243 st_dev_name(dev_t dev)
12244 {
12245 	struct scsi_tape *un;
12246 	const char density[] = { 'l', 'm', 'h', 'c' };
12247 	static char name[32];
12248 	minor_t minor;
12249 	int instance;
12250 	int nprt = 0;
12251 
12252 	minor = getminor(dev);
12253 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
12254 	un = ddi_get_soft_state(st_state, instance);
12255 	if (un) {
12256 		ST_FUNC(ST_DEVINFO, st_dev_name);
12257 	}
12258 
12259 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
12260 
12261 	if (minor & MT_BSD) {
12262 		name[++nprt] = 'b';
12263 	}
12264 
12265 	if (minor & MT_NOREWIND) {
12266 		name[++nprt] = 'n';
12267 	}
12268 
12269 	/* NULL terminator */
12270 	name[++nprt] = 0;
12271 
12272 	return (name);
12273 }
12274 
12275 /*
12276  * Soft error reporting, so far unique to each drive
12277  *
12278  * Currently supported: exabyte and DAT soft error reporting
12279  */
12280 static int
12281 st_report_exabyte_soft_errors(dev_t dev, int flag)
12282 {
12283 	uchar_t *sensep;
12284 	int amt;
12285 	int rval = 0;
12286 	char cdb[CDB_GROUP0], *c = cdb;
12287 	struct uscsi_cmd *com;
12288 
12289 	GET_SOFT_STATE(dev);
12290 
12291 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
12292 
12293 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12294 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
12295 	    dev, flag);
12296 
12297 	ASSERT(mutex_owned(ST_MUTEX));
12298 
12299 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12300 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
12301 
12302 	*c++ = SCMD_REQUEST_SENSE;
12303 	*c++ = 0;
12304 	*c++ = 0;
12305 	*c++ = 0;
12306 	*c++ = TAPE_SENSE_LENGTH;
12307 	/*
12308 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
12309 	 */
12310 	*c   = (char)0x80;
12311 
12312 	com->uscsi_cdb = cdb;
12313 	com->uscsi_cdblen = CDB_GROUP0;
12314 	com->uscsi_bufaddr = (caddr_t)sensep;
12315 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
12316 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12317 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12318 
12319 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12320 	if (rval || com->uscsi_status) {
12321 		goto done;
12322 	}
12323 
12324 	/*
12325 	 * was there enough data?
12326 	 */
12327 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
12328 
12329 	if ((amt >= 19) && un->un_kbytes_xferred) {
12330 		uint_t count, error_rate;
12331 		uint_t rate;
12332 
12333 		if (sensep[21] & CLN) {
12334 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12335 			    "Periodic head cleaning required");
12336 		}
12337 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
12338 			goto done;
12339 		}
12340 		/*
12341 		 * check if soft error reporting needs to be done.
12342 		 */
12343 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
12344 		count &= 0xffffff;
12345 		error_rate = (count * 100)/un->un_kbytes_xferred;
12346 
12347 #ifdef	STDEBUG
12348 		if (st_soft_error_report_debug) {
12349 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12350 			    "Exabyte Soft Error Report:\n");
12351 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12352 			    "read/write error counter: %d\n", count);
12353 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12354 			    "number of bytes transferred: %dK\n",
12355 			    un->un_kbytes_xferred);
12356 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12357 			    "error_rate: %d%%\n", error_rate);
12358 
12359 			if (amt >= 22) {
12360 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12361 				    "unit sense: 0x%b 0x%b 0x%b\n",
12362 				    sensep[19], SENSE_19_BITS,
12363 				    sensep[20], SENSE_20_BITS,
12364 				    sensep[21], SENSE_21_BITS);
12365 			}
12366 			if (amt >= 27) {
12367 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12368 				    "tracking retry counter: %d\n",
12369 				    sensep[26]);
12370 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12371 				    "read/write retry counter: %d\n",
12372 				    sensep[27]);
12373 			}
12374 		}
12375 #endif
12376 
12377 		if (flag & FWRITE) {
12378 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
12379 		} else {
12380 			rate = EXABYTE_READ_ERROR_THRESHOLD;
12381 		}
12382 		if (error_rate >= rate) {
12383 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12384 			    "Soft error rate (%d%%) during %s was too high",
12385 			    error_rate,
12386 			    ((flag & FWRITE) ? wrg_str : rdg_str));
12387 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12388 			    "Please, replace tape cartridge\n");
12389 		}
12390 	}
12391 
12392 done:
12393 	kmem_free(com, sizeof (*com));
12394 	kmem_free(sensep, TAPE_SENSE_LENGTH);
12395 
12396 	if (rval != 0) {
12397 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12398 		    "exabyte soft error reporting failed\n");
12399 	}
12400 	return (rval);
12401 }
12402 
12403 /*
12404  * this is very specific to Archive 4mm dat
12405  */
12406 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
12407 
12408 static int
12409 st_report_dat_soft_errors(dev_t dev, int flag)
12410 {
12411 	uchar_t *sensep;
12412 	int amt, i;
12413 	int rval = 0;
12414 	char cdb[CDB_GROUP1], *c = cdb;
12415 	struct uscsi_cmd *com;
12416 	struct scsi_arq_status status;
12417 
12418 	GET_SOFT_STATE(dev);
12419 
12420 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
12421 
12422 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12423 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12424 
12425 	ASSERT(mutex_owned(ST_MUTEX));
12426 
12427 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12428 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12429 
12430 	*c++ = SCMD_LOG_SENSE_G1;
12431 	*c++ = 0;
12432 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
12433 	*c++ = 0;
12434 	*c++ = 0;
12435 	*c++ = 0;
12436 	*c++ = 2;
12437 	*c++ = 0;
12438 	*c++ = (char)LOG_SENSE_LENGTH;
12439 	*c   = 0;
12440 	com->uscsi_cdb    = cdb;
12441 	com->uscsi_cdblen  = CDB_GROUP1;
12442 	com->uscsi_bufaddr = (caddr_t)sensep;
12443 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
12444 	com->uscsi_rqlen = sizeof (status);
12445 	com->uscsi_rqbuf = (caddr_t)&status;
12446 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
12447 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12448 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12449 	if (rval) {
12450 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12451 		    "DAT soft error reporting failed\n");
12452 	}
12453 	if (rval || com->uscsi_status) {
12454 		goto done;
12455 	}
12456 
12457 	/*
12458 	 * was there enough data?
12459 	 */
12460 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
12461 
12462 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
12463 		int total, retries, param_code;
12464 
12465 		total = -1;
12466 		retries = -1;
12467 		amt = sensep[3] + 4;
12468 
12469 
12470 #ifdef STDEBUG
12471 		if (st_soft_error_report_debug) {
12472 			(void) printf("logsense:");
12473 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
12474 				if (i % 16 == 0) {
12475 					(void) printf("\t\n");
12476 				}
12477 				(void) printf(" %x", sensep[i]);
12478 			}
12479 			(void) printf("\n");
12480 		}
12481 #endif
12482 
12483 		/*
12484 		 * parse the param_codes
12485 		 */
12486 		if (sensep[0] == 2 || sensep[0] == 3) {
12487 			for (i = 4; i < amt; i++) {
12488 				param_code = (sensep[i++] << 8);
12489 				param_code += sensep[i++];
12490 				i++; /* skip control byte */
12491 				if (param_code == 5) {
12492 					if (sensep[i++] == 4) {
12493 						total = (sensep[i++] << 24);
12494 						total += (sensep[i++] << 16);
12495 						total += (sensep[i++] << 8);
12496 						total += sensep[i];
12497 					}
12498 				} else if (param_code == 0x8007) {
12499 					if (sensep[i++] == 2) {
12500 						retries = sensep[i++] << 8;
12501 						retries += sensep[i];
12502 					}
12503 				} else {
12504 					i += sensep[i];
12505 				}
12506 			}
12507 		}
12508 
12509 		/*
12510 		 * if the log sense returned valid numbers then determine
12511 		 * the read and write error thresholds based on the amount of
12512 		 * data transferred
12513 		 */
12514 
12515 		if (total > 0 && retries > 0) {
12516 			short normal_retries = 0;
12517 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12518 			    "total xferred (%s) =%x, retries=%x\n",
12519 			    ((flag & FWRITE) ? wrg_str : rdg_str),
12520 			    total, retries);
12521 
12522 			if (flag & FWRITE) {
12523 				if (total <=
12524 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
12525 					normal_retries =
12526 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
12527 				} else {
12528 					normal_retries =
12529 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
12530 				}
12531 			} else {
12532 				if (total <=
12533 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
12534 					normal_retries =
12535 					    DAT_SMALL_READ_ERROR_THRESHOLD;
12536 				} else {
12537 					normal_retries =
12538 					    DAT_LARGE_READ_ERROR_THRESHOLD;
12539 				}
12540 			}
12541 
12542 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12543 			"normal retries=%d\n", normal_retries);
12544 
12545 			if (retries >= normal_retries) {
12546 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12547 				    "Soft error rate (retries = %d) during "
12548 				    "%s was too high",  retries,
12549 				    ((flag & FWRITE) ? wrg_str : rdg_str));
12550 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12551 				    "Periodic head cleaning required "
12552 				    "and/or replace tape cartridge\n");
12553 			}
12554 
12555 		} else if (total == -1 || retries == -1) {
12556 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12557 			    "log sense parameter code does not make sense\n");
12558 		}
12559 	}
12560 
12561 	/*
12562 	 * reset all values
12563 	 */
12564 	c = cdb;
12565 	*c++ = SCMD_LOG_SELECT_G1;
12566 	*c++ = 2;	/* this resets all values */
12567 	*c++ = (char)0xc0;
12568 	*c++ = 0;
12569 	*c++ = 0;
12570 	*c++ = 0;
12571 	*c++ = 0;
12572 	*c++ = 0;
12573 	*c++ = 0;
12574 	*c   = 0;
12575 	com->uscsi_bufaddr = NULL;
12576 	com->uscsi_buflen  = 0;
12577 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
12578 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12579 	if (rval) {
12580 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12581 		    "DAT soft error reset failed\n");
12582 	}
12583 done:
12584 	kmem_free(com, sizeof (*com));
12585 	kmem_free(sensep, LOG_SENSE_LENGTH);
12586 	return (rval);
12587 }
12588 
12589 static int
12590 st_report_soft_errors(dev_t dev, int flag)
12591 {
12592 	GET_SOFT_STATE(dev);
12593 
12594 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
12595 
12596 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12597 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12598 
12599 	ASSERT(mutex_owned(ST_MUTEX));
12600 
12601 	switch (un->un_dp->type) {
12602 	case ST_TYPE_EXB8500:
12603 	case ST_TYPE_EXABYTE:
12604 		return (st_report_exabyte_soft_errors(dev, flag));
12605 		/*NOTREACHED*/
12606 	case ST_TYPE_PYTHON:
12607 		return (st_report_dat_soft_errors(dev, flag));
12608 		/*NOTREACHED*/
12609 	default:
12610 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
12611 		return (-1);
12612 	}
12613 }
12614 
12615 /*
12616  * persistent error routines
12617  */
12618 
12619 /*
12620  * enable persistent errors, and set the throttle appropriately, checking
12621  * for flush-on-errors capability
12622  */
12623 static void
12624 st_turn_pe_on(struct scsi_tape *un)
12625 {
12626 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
12627 
12628 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
12629 	ASSERT(mutex_owned(ST_MUTEX));
12630 
12631 	un->un_persistence = 1;
12632 
12633 	/*
12634 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
12635 	 * enabled.  This will simplify the error handling for request senses
12636 	 */
12637 
12638 	if (un->un_arq_enabled && un->un_untagged_qing) {
12639 		uchar_t f_o_e;
12640 
12641 		mutex_exit(ST_MUTEX);
12642 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
12643 		    1 : 0;
12644 		mutex_enter(ST_MUTEX);
12645 
12646 		un->un_flush_on_errors = f_o_e;
12647 	} else {
12648 		un->un_flush_on_errors = 0;
12649 	}
12650 
12651 	if (un->un_flush_on_errors)
12652 		un->un_max_throttle = (uchar_t)st_max_throttle;
12653 	else
12654 		un->un_max_throttle = 1;
12655 
12656 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
12657 		un->un_max_throttle = 1;
12658 
12659 	/* this will send a marker pkt */
12660 	st_clear_pe(un);
12661 }
12662 
12663 /*
12664  * This turns persistent errors permanently off
12665  */
12666 static void
12667 st_turn_pe_off(struct scsi_tape *un)
12668 {
12669 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
12670 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
12671 	ASSERT(mutex_owned(ST_MUTEX));
12672 
12673 	/* turn it off for good */
12674 	un->un_persistence = 0;
12675 
12676 	/* this will send a marker pkt */
12677 	st_clear_pe(un);
12678 
12679 	/* turn off flush on error capability, if enabled */
12680 	if (un->un_flush_on_errors) {
12681 		mutex_exit(ST_MUTEX);
12682 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
12683 		mutex_enter(ST_MUTEX);
12684 	}
12685 
12686 
12687 	un->un_flush_on_errors = 0;
12688 }
12689 
12690 /*
12691  * This clear persistent errors, allowing more commands through, and also
12692  * sending a marker packet.
12693  */
12694 static void
12695 st_clear_pe(struct scsi_tape *un)
12696 {
12697 	ST_FUNC(ST_DEVINFO, st_clear_pe);
12698 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
12699 	ASSERT(mutex_owned(ST_MUTEX));
12700 
12701 	un->un_persist_errors = 0;
12702 	un->un_throttle = un->un_last_throttle = 1;
12703 	un->un_errno = 0;
12704 	st_hba_unflush(un);
12705 }
12706 
12707 /*
12708  * This will flag persistent errors, shutting everything down, if the
12709  * application had enabled persistent errors via MTIOCPERSISTENT
12710  */
12711 static void
12712 st_set_pe_flag(struct scsi_tape *un)
12713 {
12714 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
12715 	ASSERT(mutex_owned(ST_MUTEX));
12716 
12717 	if (un->un_persistence) {
12718 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
12719 		un->un_persist_errors = 1;
12720 		un->un_throttle = un->un_last_throttle = 0;
12721 		cv_broadcast(&un->un_sbuf_cv);
12722 	}
12723 }
12724 
12725 static int
12726 st_do_reserve(struct scsi_tape *un)
12727 {
12728 	int rval;
12729 	int was_lost = un->un_rsvd_status & ST_LOST_RESERVE;
12730 
12731 	ST_FUNC(ST_DEVINFO, st_do_reserve);
12732 
12733 	/*
12734 	 * Issue a Throw-Away reserve command to clear the
12735 	 * check condition.
12736 	 * If the current behaviour of reserve/release is to
12737 	 * hold reservation across opens , and if a Bus reset
12738 	 * has been issued between opens then this command
12739 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
12740 	 * In this case return an EACCES so that user knows that
12741 	 * reservation has been lost in between opens.
12742 	 * If this error is not returned and we continue with
12743 	 * successful open , then user may think position of the
12744 	 * tape is still the same but inreality we would rewind the
12745 	 * tape and continue from BOT.
12746 	 */
12747 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12748 	if (rval) {
12749 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
12750 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
12751 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
12752 			un->un_errno = EACCES;
12753 			return (EACCES);
12754 		}
12755 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12756 	}
12757 	if (rval == 0) {
12758 		un->un_rsvd_status |= ST_INIT_RESERVE;
12759 	}
12760 	if (was_lost) {
12761 		un->un_running.pmode = invalid;
12762 	}
12763 
12764 	return (rval);
12765 }
12766 
12767 static int
12768 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb)
12769 {
12770 	int rval;
12771 	cmd_attribute const *attrib;
12772 
12773 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
12774 
12775 	/*
12776 	 * If already reserved no need to do it again.
12777 	 * Also if Reserve and Release are disabled Just return.
12778 	 */
12779 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12780 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12781 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12782 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12783 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
12784 		    st_print_scsi_cmd((uchar_t)cdb[0]));
12785 		return (0);
12786 	}
12787 
12788 	/* See if command is on the list */
12789 	attrib = st_lookup_cmd_attribute(cdb[0]);
12790 
12791 	if (attrib == NULL) {
12792 		rval = 1; /* Not found, when in doubt reserve */
12793 	} else if ((attrib->requires_reserve) != 0) {
12794 		rval = 1;
12795 	} else if ((attrib->reserve_byte) != 0) {
12796 		/*
12797 		 * cmd is on list.
12798 		 * if byte is zero always allowed.
12799 		 */
12800 		rval = 1;
12801 	} else if (((cdb[attrib->reserve_byte]) &
12802 	    (attrib->reserve_mask)) != 0) {
12803 		rval = 1;
12804 	} else {
12805 		rval = 0;
12806 	}
12807 
12808 	if (rval) {
12809 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12810 		    "Command %s requires reservation",
12811 		    st_print_scsi_cmd(cdb[0]));
12812 
12813 		rval = st_do_reserve(un);
12814 	}
12815 
12816 	return (rval);
12817 }
12818 
12819 static int
12820 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
12821 {
12822 	int rval;
12823 	cmd_attribute const *attrib;
12824 
12825 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
12826 
12827 	/*
12828 	 * Do not reserve when already reserved, when not supported or when
12829 	 * auto-rewinding on device closure.
12830 	 */
12831 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12832 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12833 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE) ||
12834 	    ((un->un_state == ST_STATE_CLOSING) && (cmd == SCMD_REWIND))) {
12835 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12836 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
12837 		    st_print_scsi_cmd(cmd));
12838 		return (0);
12839 	}
12840 
12841 	/* search for this command on the list */
12842 	attrib = st_lookup_cmd_attribute(cmd);
12843 
12844 	if (attrib == NULL) {
12845 		rval = 1; /* Not found, when in doubt reserve */
12846 	} else if ((attrib->requires_reserve) != 0) {
12847 		rval = 1;
12848 	} else if ((attrib->reserve_byte) != 0) {
12849 		/*
12850 		 * cmd is on list.
12851 		 * if byte is zero always allowed.
12852 		 */
12853 		rval = 1;
12854 	} else if (((attrib->reserve_mask) & cnt) != 0) {
12855 		rval = 1;
12856 	} else {
12857 		rval = 0;
12858 	}
12859 
12860 	if (rval) {
12861 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12862 		    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
12863 
12864 		rval = st_do_reserve(un);
12865 	}
12866 
12867 	return (rval);
12868 }
12869 
12870 static int
12871 st_reserve_release(struct scsi_tape *un, int cmd, ubufunc_t ubf)
12872 {
12873 	struct uscsi_cmd	uscsi_cmd;
12874 	int			rval;
12875 	char			cdb[CDB_GROUP0];
12876 	struct scsi_arq_status	stat;
12877 
12878 
12879 
12880 	ST_FUNC(ST_DEVINFO, st_reserve_release);
12881 
12882 	ASSERT(mutex_owned(ST_MUTEX));
12883 
12884 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12885 	    "st_reserve_release: %s \n",
12886 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
12887 
12888 	bzero(&cdb, CDB_GROUP0);
12889 	if (cmd == ST_RELEASE) {
12890 		cdb[0] = SCMD_RELEASE;
12891 	} else {
12892 		cdb[0] = SCMD_RESERVE;
12893 	}
12894 	bzero(&uscsi_cmd, sizeof (struct uscsi_cmd));
12895 	uscsi_cmd.uscsi_flags = USCSI_WRITE | USCSI_RQENABLE;
12896 	uscsi_cmd.uscsi_cdb = cdb;
12897 	uscsi_cmd.uscsi_cdblen = CDB_GROUP0;
12898 	uscsi_cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
12899 	uscsi_cmd.uscsi_rqbuf = (caddr_t)&stat;
12900 	uscsi_cmd.uscsi_rqlen = sizeof (stat);
12901 
12902 	rval = ubf(un, &uscsi_cmd, FKIOCTL);
12903 
12904 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12905 	    "st_reserve_release: rval(1)=%d\n", rval);
12906 
12907 	if (rval) {
12908 		if (uscsi_cmd.uscsi_status == STATUS_RESERVATION_CONFLICT) {
12909 			rval = EACCES;
12910 		}
12911 		/*
12912 		 * dynamically turn off reserve/release support
12913 		 * in case of drives which do not support
12914 		 * reserve/release command(ATAPI drives).
12915 		 */
12916 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
12917 			if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
12918 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
12919 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12920 				    "Tape unit does not support "
12921 				    "reserve/release \n");
12922 			}
12923 			rval = 0;
12924 		}
12925 	}
12926 	return (rval);
12927 }
12928 
12929 static int
12930 st_take_ownership(struct scsi_tape *un, ubufunc_t ubf)
12931 {
12932 	int rval;
12933 
12934 	ST_FUNC(ST_DEVINFO, st_take_ownership);
12935 
12936 	ASSERT(mutex_owned(ST_MUTEX));
12937 
12938 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12939 	    "st_take_ownership: Entering ...\n");
12940 
12941 
12942 	rval = st_reserve_release(un, ST_RESERVE, ubf);
12943 	/*
12944 	 * XXX -> Should reset be done only if we get EACCES.
12945 	 * .
12946 	 */
12947 	if (rval) {
12948 		if (st_reset(un, RESET_LUN) == 0) {
12949 			return (EIO);
12950 		}
12951 		un->un_rsvd_status &=
12952 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
12953 
12954 		mutex_exit(ST_MUTEX);
12955 		delay(drv_usectohz(ST_RESERVATION_DELAY));
12956 		mutex_enter(ST_MUTEX);
12957 		/*
12958 		 * remove the check condition.
12959 		 */
12960 		(void) st_reserve_release(un, ST_RESERVE, ubf);
12961 		rval = st_reserve_release(un, ST_RESERVE, ubf);
12962 		if (rval != 0) {
12963 			if ((st_reserve_release(un, ST_RESERVE, ubf))
12964 			    != 0) {
12965 				rval = (un->un_rsvd_status &
12966 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
12967 				return (rval);
12968 			}
12969 		}
12970 		/*
12971 		 * Set tape state to ST_STATE_OFFLINE , in case if
12972 		 * the user wants to continue and start using
12973 		 * the tape.
12974 		 */
12975 		un->un_state = ST_STATE_OFFLINE;
12976 		un->un_rsvd_status |= ST_INIT_RESERVE;
12977 	}
12978 	return (rval);
12979 }
12980 
12981 static int
12982 st_create_errstats(struct scsi_tape *un, int instance)
12983 {
12984 	char	kstatname[KSTAT_STRLEN];
12985 
12986 	ST_FUNC(ST_DEVINFO, st_create_errstats);
12987 
12988 	/*
12989 	 * Create device error kstats
12990 	 */
12991 
12992 	if (un->un_errstats == (kstat_t *)0) {
12993 		(void) sprintf(kstatname, "st%d,err", instance);
12994 		un->un_errstats = kstat_create("sterr", instance, kstatname,
12995 		    "device_error", KSTAT_TYPE_NAMED,
12996 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
12997 		    KSTAT_FLAG_PERSISTENT);
12998 
12999 		if (un->un_errstats) {
13000 			struct st_errstats	*stp;
13001 
13002 			stp = (struct st_errstats *)un->un_errstats->ks_data;
13003 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
13004 			    KSTAT_DATA_ULONG);
13005 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
13006 			    KSTAT_DATA_ULONG);
13007 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
13008 			    KSTAT_DATA_ULONG);
13009 			kstat_named_init(&stp->st_vid, "Vendor",
13010 			    KSTAT_DATA_CHAR);
13011 			kstat_named_init(&stp->st_pid, "Product",
13012 			    KSTAT_DATA_CHAR);
13013 			kstat_named_init(&stp->st_revision, "Revision",
13014 			    KSTAT_DATA_CHAR);
13015 			kstat_named_init(&stp->st_serial, "Serial No",
13016 			    KSTAT_DATA_CHAR);
13017 			un->un_errstats->ks_private = un;
13018 			un->un_errstats->ks_update = nulldev;
13019 			kstat_install(un->un_errstats);
13020 			/*
13021 			 * Fill in the static data
13022 			 */
13023 			(void) strncpy(&stp->st_vid.value.c[0],
13024 			    ST_INQUIRY->inq_vid, 8);
13025 			/*
13026 			 * XXX:  Emulex MT-02 (and emulators) predates
13027 			 *	 SCSI-1 and has no vid & pid inquiry data.
13028 			 */
13029 			if (ST_INQUIRY->inq_len != 0) {
13030 				(void) strncpy(&stp->st_pid.value.c[0],
13031 				    ST_INQUIRY->inq_pid, 16);
13032 				(void) strncpy(&stp->st_revision.value.c[0],
13033 				    ST_INQUIRY->inq_revision, 4);
13034 				(void) strncpy(&stp->st_serial.value.c[0],
13035 				    ST_INQUIRY->inq_serial, 12);
13036 			}
13037 		}
13038 	}
13039 	return (0);
13040 }
13041 
13042 static int
13043 st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos)
13044 {
13045 	int rval;
13046 	bufunc_t bf = (ubf == st_uscsi_rcmd) ? st_rcmd : st_cmd;
13047 
13048 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
13049 
13050 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
13051 	ASSERT(mutex_owned(ST_MUTEX));
13052 
13053 	/* Can't restore an invalid position */
13054 	if (pos->pmode == invalid) {
13055 		return (4);
13056 	}
13057 
13058 	/*
13059 	 * Assumtions:
13060 	 *	If a position was read and is in logical position mode.
13061 	 *	If a drive supports read position it supports locate.
13062 	 *	If the read position type is not NO_POS. even though
13063 	 *	   a read position make not have been attemped yet.
13064 	 *
13065 	 *	The drive can locate to the position.
13066 	 */
13067 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
13068 		/*
13069 		 * If position mode is logical or legacy mode try
13070 		 * to locate there as it is faster.
13071 		 * If it fails try the old way.
13072 		 */
13073 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13074 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
13075 		    pos->lgclblkno);
13076 
13077 		if (st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
13078 		    pos->lgclblkno, pos->partition) == 0) {
13079 			/* Assume we are there copy rest of position back */
13080 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
13081 				COPY_POS(&un->un_pos, pos);
13082 			}
13083 			return (0);
13084 		}
13085 
13086 		/*
13087 		 * If logical block locate failed to restore a logical
13088 		 * position, can't recover.
13089 		 */
13090 		if (pos->pmode == logical) {
13091 			return (-1);
13092 		}
13093 	}
13094 
13095 
13096 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13097 	    "Restoring tape position at fileno=%x, blkno=%x....",
13098 	    pos->fileno, pos->blkno);
13099 
13100 	/*
13101 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
13102 	 * so as not to rewind tape on RESETS: Gee, Has life ever
13103 	 * been simple in tape land ?
13104 	 */
13105 	rval = bf(un, SCMD_REWIND, 0, SYNC_CMD);
13106 	if (rval) {
13107 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
13108 		    "Failed to restore the last file and block position: In"
13109 		    " this state, Tape will be loaded at BOT during next open");
13110 		un->un_pos.pmode = invalid;
13111 		return (rval);
13112 	}
13113 
13114 	/* If the position was as the result of back space file */
13115 	if (pos->blkno > (INF / 2)) {
13116 		/* Go one extra file forward */
13117 		pos->fileno++;
13118 		/* Figure how many blocks to back into the previous file */
13119 		pos->blkno = -(INF - pos->blkno);
13120 	}
13121 
13122 	/* Go to requested fileno */
13123 	if (pos->fileno) {
13124 		rval = st_cmd(un, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
13125 		if (rval) {
13126 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13127 			    "Failed to restore the last file position: In this "
13128 			    " state, Tape will be loaded at BOT during next"
13129 			    " open %d", __LINE__);
13130 			un->un_pos.pmode = invalid;
13131 			pos->pmode = invalid;
13132 			return (rval);
13133 		}
13134 	}
13135 
13136 	/*
13137 	 * If backing into a file we already did an extra file forward.
13138 	 * Now we have to back over the filemark to get to the end of
13139 	 * the previous file. The blkno has been ajusted to a negative
13140 	 * value so we will get to the expected location.
13141 	 */
13142 	if (pos->blkno) {
13143 		rval = bf(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
13144 		if (rval) {
13145 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13146 			    "Failed to restore the last file position: In this "
13147 			    " state, Tape will be loaded at BOT during next"
13148 			    " open %d", __LINE__);
13149 			un->un_pos.pmode = invalid;
13150 			pos->pmode = invalid;
13151 			return (rval);
13152 		}
13153 	}
13154 
13155 	/*
13156 	 * The position mode, block and fileno should be correct,
13157 	 * This updates eof and logical position information.
13158 	 */
13159 	un->un_pos.eof = pos->eof;
13160 	un->un_pos.lgclblkno = pos->lgclblkno;
13161 
13162 	return (0);
13163 }
13164 
13165 /*
13166  * check sense key, ASC, ASCQ in order to determine if the tape needs
13167  * to be ejected
13168  */
13169 
13170 static int
13171 st_check_asc_ascq(struct scsi_tape *un)
13172 {
13173 	struct scsi_extended_sense *sensep = ST_RQSENSE;
13174 	struct tape_failure_code   *code;
13175 
13176 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
13177 
13178 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
13179 		if ((code->key  == sensep->es_key) &&
13180 		    (code->add_code  == sensep->es_add_code) &&
13181 		    (code->qual_code == sensep->es_qual_code))
13182 			return (1);
13183 	}
13184 	return (0);
13185 }
13186 
13187 /*
13188  * st_logpage_supported() sends a Log Sense command with
13189  * page code = 0 = Supported Log Pages Page to the device,
13190  * to see whether the page 'page' is supported.
13191  * Return values are:
13192  * -1 if the Log Sense command fails
13193  * 0 if page is not supported
13194  * 1 if page is supported
13195  */
13196 
13197 static int
13198 st_logpage_supported(struct scsi_tape *un, uchar_t page)
13199 {
13200 	uchar_t *sp, *sensep;
13201 	unsigned length;
13202 	struct uscsi_cmd *com;
13203 	struct scsi_arq_status status;
13204 	int rval;
13205 	char cdb[CDB_GROUP1] = {
13206 		SCMD_LOG_SENSE_G1,
13207 		0,
13208 		SUPPORTED_LOG_PAGES_PAGE,
13209 		0,
13210 		0,
13211 		0,
13212 		0,
13213 		0,
13214 		(char)LOG_SENSE_LENGTH,
13215 		0
13216 	};
13217 
13218 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
13219 
13220 	ASSERT(mutex_owned(ST_MUTEX));
13221 
13222 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13223 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
13224 
13225 	com->uscsi_cdb = cdb;
13226 	com->uscsi_cdblen = CDB_GROUP1;
13227 	com->uscsi_bufaddr = (caddr_t)sensep;
13228 	com->uscsi_buflen = LOG_SENSE_LENGTH;
13229 	com->uscsi_rqlen = sizeof (status);
13230 	com->uscsi_rqbuf = (caddr_t)&status;
13231 	com->uscsi_flags =
13232 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13233 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13234 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13235 	if (rval || com->uscsi_status) {
13236 		/* uscsi-command failed */
13237 		rval = -1;
13238 	} else {
13239 
13240 		sp = sensep + 3;
13241 
13242 		for (length = *sp++; length > 0; length--, sp++) {
13243 
13244 			if (*sp == page) {
13245 				rval = 1;
13246 				break;
13247 			}
13248 		}
13249 	}
13250 	kmem_free(com, sizeof (struct uscsi_cmd));
13251 	kmem_free(sensep, LOG_SENSE_LENGTH);
13252 	return (rval);
13253 }
13254 
13255 
13256 /*
13257  * st_check_clean_bit() gets the status of the tape's cleaning bit.
13258  *
13259  * If the device does support the TapeAlert log page, then the cleaning bit
13260  * information will be read from this page. Otherwise we will see if one of
13261  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
13262  * the device, which means, that we can get the cleaning bit information via
13263  * a RequestSense command.
13264  * If both methods of getting cleaning bit information are not supported
13265  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
13266  * returns with
13267  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
13268  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
13269  * If the call to st_uscsi_cmd() to do the Log Sense or the Request Sense
13270  * command fails, or if the amount of Request Sense data is not enough, then
13271  *  st_check_clean_bit() returns with -1.
13272  */
13273 
13274 static int
13275 st_check_clean_bit(struct scsi_tape *un)
13276 {
13277 	int rval = 0;
13278 
13279 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
13280 
13281 	ASSERT(mutex_owned(ST_MUTEX));
13282 
13283 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
13284 		return (rval);
13285 	}
13286 
13287 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13288 
13289 		rval = st_logpage_supported(un, TAPE_SEQUENTIAL_PAGE);
13290 		if (rval == -1) {
13291 			return (0);
13292 		}
13293 		if (rval == 1) {
13294 
13295 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
13296 		}
13297 
13298 		rval = st_logpage_supported(un, TAPE_ALERT_PAGE);
13299 		if (rval == -1) {
13300 			return (0);
13301 		}
13302 		if (rval == 1) {
13303 
13304 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
13305 		}
13306 
13307 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13308 
13309 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
13310 		}
13311 	}
13312 
13313 	rval = 0;
13314 
13315 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
13316 
13317 		rval = st_check_sequential_clean_bit(un);
13318 		if (rval == -1) {
13319 			return (0);
13320 		}
13321 	}
13322 
13323 	if ((rval == 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
13324 
13325 		rval = st_check_alert_flags(un);
13326 		if (rval == -1) {
13327 			return (0);
13328 		}
13329 	}
13330 
13331 	if ((rval == 0) && (un->un_dp->options & ST_CLN_MASK)) {
13332 
13333 		rval = st_check_sense_clean_bit(un);
13334 		if (rval == -1) {
13335 			return (0);
13336 		}
13337 	}
13338 
13339 	/*
13340 	 * If found a supported means to check need to clean.
13341 	 */
13342 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
13343 
13344 		/*
13345 		 * head needs to be cleaned.
13346 		 */
13347 		if (rval & MTF_TAPE_HEAD_DIRTY) {
13348 
13349 			/*
13350 			 * Print log message only first time
13351 			 * found needing cleaned.
13352 			 */
13353 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
13354 
13355 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
13356 				    "Periodic head cleaning required");
13357 
13358 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
13359 			}
13360 
13361 		} else {
13362 
13363 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
13364 		}
13365 	}
13366 
13367 	return (rval);
13368 }
13369 
13370 
13371 static int
13372 st_check_sequential_clean_bit(struct scsi_tape *un)
13373 {
13374 	int rval;
13375 	int ix;
13376 	ushort_t parameter;
13377 	struct uscsi_cmd *cmd;
13378 	struct log_sequential_page *sp;
13379 	struct log_sequential_page_parameter *prm;
13380 	struct scsi_arq_status status;
13381 	char cdb[CDB_GROUP1] = {
13382 		SCMD_LOG_SENSE_G1,
13383 		0,
13384 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
13385 		0,
13386 		0,
13387 		0,
13388 		0,
13389 		(char)(sizeof (struct log_sequential_page) >> 8),
13390 		(char)(sizeof (struct log_sequential_page)),
13391 		0
13392 	};
13393 
13394 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
13395 
13396 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13397 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
13398 
13399 	cmd->uscsi_flags   =
13400 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13401 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13402 	cmd->uscsi_cdb	   = cdb;
13403 	cmd->uscsi_cdblen  = CDB_GROUP1;
13404 	cmd->uscsi_bufaddr = (caddr_t)sp;
13405 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
13406 	cmd->uscsi_rqlen   = sizeof (status);
13407 	cmd->uscsi_rqbuf   = (caddr_t)&status;
13408 
13409 	rval = st_uscsi_cmd(un, cmd, FKIOCTL);
13410 
13411 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
13412 
13413 		rval = -1;
13414 
13415 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
13416 
13417 		rval = -1;
13418 	}
13419 
13420 	prm = &sp->param[0];
13421 
13422 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
13423 
13424 		if (prm->log_param.length == 0) {
13425 			break;
13426 		}
13427 
13428 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
13429 		    (prm->log_param.pc_lo & 0xff));
13430 
13431 		if (parameter == SEQUENTIAL_NEED_CLN) {
13432 
13433 			rval = MTF_TAPE_CLN_SUPPORTED;
13434 			if (prm->param_value[prm->log_param.length - 1]) {
13435 
13436 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13437 				    "sequential log says head dirty\n");
13438 				rval |= MTF_TAPE_HEAD_DIRTY;
13439 			}
13440 		}
13441 		prm = (struct log_sequential_page_parameter *)
13442 		    &prm->param_value[prm->log_param.length];
13443 	}
13444 
13445 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13446 	kmem_free(sp,  sizeof (struct log_sequential_page));
13447 
13448 	return (rval);
13449 }
13450 
13451 
13452 static int
13453 st_check_alert_flags(struct scsi_tape *un)
13454 {
13455 	struct st_tape_alert *ta;
13456 	struct uscsi_cmd *com;
13457 	struct scsi_arq_status status;
13458 	unsigned ix, length;
13459 	int rval;
13460 	tape_alert_flags flag;
13461 	char cdb[CDB_GROUP1] = {
13462 		SCMD_LOG_SENSE_G1,
13463 		0,
13464 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
13465 		0,
13466 		0,
13467 		0,
13468 		0,
13469 		(char)(sizeof (struct st_tape_alert) >> 8),
13470 		(char)(sizeof (struct st_tape_alert)),
13471 		0
13472 	};
13473 
13474 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
13475 
13476 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13477 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
13478 
13479 	com->uscsi_cdb = cdb;
13480 	com->uscsi_cdblen = CDB_GROUP1;
13481 	com->uscsi_bufaddr = (caddr_t)ta;
13482 	com->uscsi_buflen = sizeof (struct st_tape_alert);
13483 	com->uscsi_rqlen = sizeof (status);
13484 	com->uscsi_rqbuf = (caddr_t)&status;
13485 	com->uscsi_flags =
13486 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13487 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13488 
13489 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13490 
13491 	if (rval || com->uscsi_status || com->uscsi_resid) {
13492 
13493 		rval = -1; /* uscsi-command failed */
13494 
13495 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
13496 
13497 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13498 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
13499 		rval = -1;
13500 	}
13501 
13502 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
13503 
13504 
13505 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
13506 
13507 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13508 		    "TapeAlert length %d\n", length);
13509 	}
13510 
13511 
13512 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
13513 
13514 		/*
13515 		 * if rval is bad before the first pass don't bother
13516 		 */
13517 		if (ix == 0 && rval != 0) {
13518 
13519 			break;
13520 		}
13521 
13522 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
13523 		    ta->param[ix].log_param.pc_lo);
13524 
13525 		if ((ta->param[ix].param_value & 1) == 0) {
13526 			continue;
13527 		}
13528 		/*
13529 		 * check to see if current parameter is of interest.
13530 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
13531 		 */
13532 		if ((flag == TAF_CLEAN_NOW) ||
13533 		    (flag == TAF_CLEAN_PERIODIC) ||
13534 		    ((flag == CLEAN_FOR_ERRORS) &&
13535 		    (un->un_dp->type == ST_TYPE_STK9840))) {
13536 
13537 			rval = MTF_TAPE_CLN_SUPPORTED;
13538 
13539 
13540 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13541 			    "alert_page drive needs clean %d\n", flag);
13542 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
13543 			rval |= MTF_TAPE_HEAD_DIRTY;
13544 
13545 		} else if (flag == TAF_CLEANING_MEDIA) {
13546 
13547 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13548 			    "alert_page drive was cleaned\n");
13549 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
13550 		}
13551 
13552 	}
13553 
13554 	/*
13555 	 * Report it as dirty till we see it cleaned
13556 	 */
13557 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
13558 
13559 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13560 		    "alert_page still dirty\n");
13561 		rval |= MTF_TAPE_HEAD_DIRTY;
13562 	}
13563 
13564 	kmem_free(com, sizeof (struct uscsi_cmd));
13565 	kmem_free(ta,  sizeof (struct st_tape_alert));
13566 
13567 	return (rval);
13568 }
13569 
13570 
13571 static int
13572 st_check_sense_clean_bit(struct scsi_tape *un)
13573 {
13574 	uchar_t *sensep;
13575 	char cdb[CDB_GROUP0];
13576 	struct uscsi_cmd *com;
13577 	ushort_t byte_pos;
13578 	uchar_t bit_mask;
13579 	unsigned length;
13580 	int index;
13581 	int rval;
13582 
13583 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
13584 
13585 	/*
13586 	 * Since this tape does not support Tape Alert,
13587 	 * we now try to get the cleanbit status via
13588 	 * Request Sense.
13589 	 */
13590 
13591 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
13592 
13593 		index = 0;
13594 
13595 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
13596 
13597 		index = 1;
13598 
13599 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
13600 
13601 		index = 2;
13602 
13603 	} else {
13604 
13605 		return (-1);
13606 	}
13607 
13608 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
13609 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
13610 	length = byte_pos + 1;
13611 
13612 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13613 	sensep = kmem_zalloc(length, KM_SLEEP);
13614 
13615 	cdb[0] = SCMD_REQUEST_SENSE;
13616 	cdb[1] = 0;
13617 	cdb[2] = 0;
13618 	cdb[3] = 0;
13619 	cdb[4] = (char)length;
13620 	cdb[5] = 0;
13621 
13622 	com->uscsi_cdb = cdb;
13623 	com->uscsi_cdblen = CDB_GROUP0;
13624 	com->uscsi_bufaddr = (caddr_t)sensep;
13625 	com->uscsi_buflen = length;
13626 	com->uscsi_flags =
13627 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13628 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13629 
13630 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13631 
13632 	if (rval || com->uscsi_status || com->uscsi_resid) {
13633 
13634 		rval = -1;
13635 
13636 	} else {
13637 
13638 		rval = MTF_TAPE_CLN_SUPPORTED;
13639 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
13640 
13641 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13642 			    "sense data says head dirty\n");
13643 			rval |= MTF_TAPE_HEAD_DIRTY;
13644 		}
13645 	}
13646 
13647 	kmem_free(com, sizeof (struct uscsi_cmd));
13648 	kmem_free(sensep, length);
13649 	return (rval);
13650 }
13651 
13652 /*
13653  * st_clear_unit_attention
13654  *
13655  *  	run test unit ready's to clear out outstanding
13656  * 	unit attentions.
13657  * 	returns zero for SUCCESS or the errno from st_cmd call
13658  */
13659 static int
13660 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
13661 {
13662 	int	i    = 0;
13663 	int	rval;
13664 
13665 	GET_SOFT_STATE(dev_instance);
13666 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
13667 
13668 	do {
13669 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
13670 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
13671 	return (rval);
13672 }
13673 
13674 static void
13675 st_calculate_timeouts(struct scsi_tape *un)
13676 {
13677 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
13678 
13679 	if (un->un_dp->non_motion_timeout == 0) {
13680 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13681 			un->un_dp->non_motion_timeout =
13682 			    st_io_time * st_long_timeout_x;
13683 		} else {
13684 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
13685 		}
13686 	}
13687 
13688 	if (un->un_dp->io_timeout == 0) {
13689 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13690 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
13691 		} else {
13692 			un->un_dp->io_timeout = (ushort_t)st_io_time;
13693 		}
13694 	}
13695 
13696 	if (un->un_dp->rewind_timeout == 0) {
13697 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13698 			un->un_dp->rewind_timeout =
13699 			    st_space_time * st_long_timeout_x;
13700 		} else {
13701 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
13702 		}
13703 	}
13704 
13705 	if (un->un_dp->space_timeout == 0) {
13706 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13707 			un->un_dp->space_timeout =
13708 			    st_space_time * st_long_timeout_x;
13709 		} else {
13710 			un->un_dp->space_timeout = (ushort_t)st_space_time;
13711 		}
13712 	}
13713 
13714 	if (un->un_dp->load_timeout == 0) {
13715 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13716 			un->un_dp->load_timeout =
13717 			    st_space_time * st_long_timeout_x;
13718 		} else {
13719 			un->un_dp->load_timeout = (ushort_t)st_space_time;
13720 		}
13721 	}
13722 
13723 	if (un->un_dp->unload_timeout == 0) {
13724 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13725 			un->un_dp->unload_timeout =
13726 			    st_space_time * st_long_timeout_x;
13727 		} else {
13728 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
13729 		}
13730 	}
13731 
13732 	if (un->un_dp->erase_timeout == 0) {
13733 		if (un->un_dp->options & ST_LONG_ERASE) {
13734 			un->un_dp->erase_timeout =
13735 			    st_space_time * st_long_space_time_x;
13736 		} else {
13737 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
13738 		}
13739 	}
13740 }
13741 
13742 
13743 static writablity
13744 st_is_not_wormable(struct scsi_tape *un)
13745 {
13746 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
13747 	return (RDWR);
13748 }
13749 
13750 static writablity
13751 st_is_hp_dat_tape_worm(struct scsi_tape *un)
13752 {
13753 	writablity wrt;
13754 
13755 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
13756 
13757 	/* Mode sense should be current */
13758 	if (un->un_mspl->media_type == 1) {
13759 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13760 		    "Drive has WORM media loaded\n");
13761 		wrt = WORM;
13762 	} else {
13763 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13764 		    "Drive has non WORM media loaded\n");
13765 		wrt = RDWR;
13766 	}
13767 	return (wrt);
13768 }
13769 
13770 #define	HP_DAT_INQUIRY 0x4A
13771 static writablity
13772 st_is_hp_dat_worm(struct scsi_tape *un)
13773 {
13774 	char *buf;
13775 	int result;
13776 	writablity wrt;
13777 
13778 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
13779 
13780 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
13781 
13782 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
13783 
13784 	if (result != 0) {
13785 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13786 		    "Read Standard Inquiry for WORM support failed");
13787 		wrt = FAILED;
13788 	} else if ((buf[40] & 1) == 0) {
13789 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13790 		    "Drive is NOT WORMable\n");
13791 		/* This drive doesn't support it so don't check again */
13792 		un->un_dp->options &= ~ST_WORMABLE;
13793 		wrt = RDWR;
13794 		un->un_wormable = st_is_not_wormable;
13795 	} else {
13796 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13797 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13798 		un->un_wormable = st_is_hp_dat_tape_worm;
13799 		wrt = un->un_wormable(un);
13800 	}
13801 
13802 	kmem_free(buf, HP_DAT_INQUIRY);
13803 
13804 	/*
13805 	 * If drive doesn't support it no point in checking further.
13806 	 */
13807 	return (wrt);
13808 }
13809 
13810 static writablity
13811 st_is_hp_lto_tape_worm(struct scsi_tape *un)
13812 {
13813 	writablity wrt;
13814 
13815 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
13816 
13817 	/* Mode sense should be current */
13818 	switch (un->un_mspl->media_type) {
13819 	case 0x00:
13820 		switch (un->un_mspl->density) {
13821 		case 0x40:
13822 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13823 			    "Drive has standard Gen I media loaded\n");
13824 			break;
13825 		case 0x42:
13826 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13827 			    "Drive has standard Gen II media loaded\n");
13828 			break;
13829 		case 0x44:
13830 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13831 			    "Drive has standard Gen III media loaded\n");
13832 			break;
13833 		case 0x46:
13834 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13835 			    "Drive has standard Gen IV media loaded\n");
13836 			break;
13837 		default:
13838 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13839 			    "Drive has standard unknown 0x%X media loaded\n",
13840 			    un->un_mspl->density);
13841 		}
13842 		wrt = RDWR;
13843 		break;
13844 	case 0x01:
13845 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13846 		    "Drive has WORM medium loaded\n");
13847 		wrt = WORM;
13848 		break;
13849 	case 0x80:
13850 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13851 		    "Drive has CD-ROM emulation medium loaded\n");
13852 		wrt = WORM;
13853 		break;
13854 	default:
13855 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13856 		    "Drive has an unexpected medium type 0x%X loaded\n",
13857 		    un->un_mspl->media_type);
13858 		wrt = RDWR;
13859 	}
13860 
13861 	return (wrt);
13862 }
13863 
13864 #define	LTO_REQ_INQUIRY 44
13865 static writablity
13866 st_is_hp_lto_worm(struct scsi_tape *un)
13867 {
13868 	char *buf;
13869 	int result;
13870 	writablity wrt;
13871 
13872 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
13873 
13874 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
13875 
13876 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
13877 
13878 	if (result != 0) {
13879 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13880 		    "Read Standard Inquiry for WORM support failed");
13881 		wrt = FAILED;
13882 	} else if ((buf[40] & 1) == 0) {
13883 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13884 		    "Drive is NOT WORMable\n");
13885 		/* This drive doesn't support it so don't check again */
13886 		un->un_dp->options &= ~ST_WORMABLE;
13887 		wrt = RDWR;
13888 		un->un_wormable = st_is_not_wormable;
13889 	} else {
13890 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13891 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13892 		un->un_wormable = st_is_hp_lto_tape_worm;
13893 		wrt = un->un_wormable(un);
13894 	}
13895 
13896 	kmem_free(buf, LTO_REQ_INQUIRY);
13897 
13898 	/*
13899 	 * If drive doesn't support it no point in checking further.
13900 	 */
13901 	return (wrt);
13902 }
13903 
13904 static writablity
13905 st_is_t10_worm_device(struct scsi_tape *un)
13906 {
13907 	writablity wrt;
13908 
13909 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
13910 
13911 	if (un->un_mspl->media_type == 0x3c) {
13912 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13913 		    "Drive has WORM media loaded\n");
13914 		wrt = WORM;
13915 	} else {
13916 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13917 		    "Drive has non WORM media loaded\n");
13918 		wrt = RDWR;
13919 	}
13920 	return (wrt);
13921 }
13922 
13923 #define	SEQ_CAP_PAGE	(char)0xb0
13924 static writablity
13925 st_is_t10_worm(struct scsi_tape *un)
13926 {
13927 	char *buf;
13928 	int result;
13929 	writablity wrt;
13930 
13931 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
13932 
13933 	buf = kmem_zalloc(6, KM_SLEEP);
13934 
13935 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
13936 
13937 	if (result != 0) {
13938 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13939 		    "Read Vitial Inquiry for Sequental Capability"
13940 		    " WORM support failed %x", result);
13941 		wrt = FAILED;
13942 	} else if ((buf[4] & 1) == 0) {
13943 		ASSERT(buf[1] == SEQ_CAP_PAGE);
13944 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13945 		    "Drive is NOT WORMable\n");
13946 		/* This drive doesn't support it so don't check again */
13947 		un->un_dp->options &= ~ST_WORMABLE;
13948 		wrt = RDWR;
13949 		un->un_wormable = st_is_not_wormable;
13950 	} else {
13951 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13952 		    "Drive supports WORM\n");
13953 		un->un_wormable = st_is_t10_worm_device;
13954 		wrt = un->un_wormable(un);
13955 	}
13956 
13957 	kmem_free(buf, 6);
13958 
13959 	return (wrt);
13960 }
13961 
13962 
13963 #define	STK_REQ_SENSE 26
13964 
13965 static writablity
13966 st_is_stk_worm(struct scsi_tape *un)
13967 {
13968 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
13969 	struct scsi_extended_sense *sense;
13970 	struct uscsi_cmd *cmd;
13971 	char *buf;
13972 	int result;
13973 	writablity wrt;
13974 
13975 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
13976 
13977 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13978 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
13979 	sense = (struct scsi_extended_sense *)buf;
13980 
13981 	cmd->uscsi_flags = USCSI_READ;
13982 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13983 	cmd->uscsi_cdb = &cdb[0];
13984 	cmd->uscsi_bufaddr = buf;
13985 	cmd->uscsi_buflen = STK_REQ_SENSE;
13986 	cmd->uscsi_cdblen = CDB_GROUP0;
13987 	cmd->uscsi_rqlen = 0;
13988 	cmd->uscsi_rqbuf = NULL;
13989 
13990 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
13991 
13992 	if (result != 0 || cmd->uscsi_status != 0) {
13993 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13994 		    "Request Sense for WORM failed");
13995 		wrt = RDWR;
13996 	} else if (sense->es_add_len + 8 < 24) {
13997 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13998 		    "Drive didn't send enough sense data for WORM byte %d\n",
13999 		    sense->es_add_len + 8);
14000 		wrt = RDWR;
14001 		un->un_wormable = st_is_not_wormable;
14002 	} else if ((buf[24]) & 0x02) {
14003 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14004 		    "Drive has WORM tape loaded\n");
14005 		wrt = WORM;
14006 		un->un_wormable = st_is_stk_worm;
14007 	} else {
14008 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14009 		    "Drive has normal tape loaded\n");
14010 		wrt = RDWR;
14011 		un->un_wormable = st_is_stk_worm;
14012 	}
14013 
14014 	kmem_free(buf, STK_REQ_SENSE);
14015 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14016 	return (wrt);
14017 }
14018 
14019 #define	DLT_INQ_SZ 44
14020 
14021 static writablity
14022 st_is_dlt_tape_worm(struct scsi_tape *un)
14023 {
14024 	caddr_t buf;
14025 	int result;
14026 	writablity wrt;
14027 
14028 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
14029 
14030 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14031 
14032 	/* Read Attribute Media Type */
14033 
14034 	result = st_read_attributes(un, 0x0408, buf, 10, st_uscsi_cmd);
14035 
14036 	/*
14037 	 * If this quantum drive is attached via an HBA that cannot
14038 	 * support thr read attributes command return error in the
14039 	 * hope that someday they will support the t10 method.
14040 	 */
14041 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
14042 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14043 		    "Read Attribute Command for WORM Media detection is not "
14044 		    "supported on the HBA that this drive is attached to.");
14045 		wrt = RDWR;
14046 		un->un_wormable = st_is_not_wormable;
14047 		goto out;
14048 	}
14049 
14050 	if (result != 0) {
14051 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14052 		    "Read Attribute Command for WORM Media returned 0x%x",
14053 		    result);
14054 		wrt = RDWR;
14055 		un->un_dp->options &= ~ST_WORMABLE;
14056 		goto out;
14057 	}
14058 
14059 	if ((uchar_t)buf[9] == 0x80) {
14060 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14061 		    "Drive media is WORM\n");
14062 		wrt = WORM;
14063 	} else {
14064 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14065 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
14066 		wrt = RDWR;
14067 	}
14068 
14069 out:
14070 	kmem_free(buf, DLT_INQ_SZ);
14071 	return (wrt);
14072 }
14073 
14074 static writablity
14075 st_is_dlt_worm(struct scsi_tape *un)
14076 {
14077 	caddr_t buf;
14078 	int result;
14079 	writablity wrt;
14080 
14081 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
14082 
14083 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14084 
14085 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
14086 
14087 	if (result != 0) {
14088 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14089 		    "Read Vendor Specific Inquiry for WORM support failed");
14090 		wrt = RDWR;
14091 		goto out;
14092 	}
14093 
14094 	if ((buf[2] & 1) == 0) {
14095 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14096 		    "Drive is not WORMable\n");
14097 		wrt = RDWR;
14098 		un->un_dp->options &= ~ST_WORMABLE;
14099 		un->un_wormable = st_is_not_wormable;
14100 		goto out;
14101 	} else {
14102 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14103 		    "Drive is WORMable\n");
14104 		un->un_wormable = st_is_dlt_tape_worm;
14105 		wrt = un->un_wormable(un);
14106 	}
14107 out:
14108 	kmem_free(buf, DLT_INQ_SZ);
14109 
14110 	return (wrt);
14111 }
14112 
14113 typedef struct {
14114 	struct modeheader_seq header;
14115 #if defined(_BIT_FIELDS_LTOH) /* X86 */
14116 	uchar_t pagecode	:6,
14117 				:2;
14118 	uchar_t page_len;
14119 	uchar_t syslogalive	:2,
14120 		device		:1,
14121 		abs		:1,
14122 		ulpbot		:1,
14123 		prth		:1,
14124 		ponej		:1,
14125 		ait		:1;
14126 	uchar_t span;
14127 
14128 	uchar_t			:6,
14129 		worm		:1,
14130 		mic		:1;
14131 	uchar_t worm_cap	:1,
14132 				:7;
14133 	uint32_t		:32;
14134 #else /* SPARC */
14135 	uchar_t			:2,
14136 		pagecode	:6;
14137 	uchar_t page_len;
14138 	uchar_t ait		:1,
14139 		device		:1,
14140 		abs		:1,
14141 		ulpbot		:1,
14142 		prth		:1,
14143 		ponej		:1,
14144 		syslogalive	:2;
14145 	uchar_t span;
14146 	uchar_t mic		:1,
14147 		worm		:1,
14148 				:6;
14149 	uchar_t			:7,
14150 		worm_cap	:1;
14151 	uint32_t		:32;
14152 #endif
14153 }ait_dev_con;
14154 
14155 #define	AIT_DEV_PAGE 0x31
14156 static writablity
14157 st_is_sony_worm(struct scsi_tape *un)
14158 {
14159 	int result;
14160 	writablity wrt;
14161 	ait_dev_con *ait_conf;
14162 
14163 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14164 
14165 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
14166 
14167 	result = st_gen_mode_sense(un, st_uscsi_cmd, AIT_DEV_PAGE,
14168 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
14169 
14170 	if (result == 0) {
14171 
14172 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
14173 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14174 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
14175 			    ait_conf->pagecode, AIT_DEV_PAGE);
14176 			wrt = RDWR;
14177 			un->un_wormable = st_is_not_wormable;
14178 
14179 		} else if (ait_conf->worm_cap) {
14180 
14181 			un->un_wormable = st_is_sony_worm;
14182 
14183 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14184 			    "Drives is WORMable\n");
14185 			if (ait_conf->worm) {
14186 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14187 				    "Media is WORM\n");
14188 				wrt = WORM;
14189 			} else {
14190 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14191 				    "Media is not WORM\n");
14192 				wrt = RDWR;
14193 			}
14194 
14195 		} else {
14196 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14197 			    "Drives not is WORMable\n");
14198 			wrt = RDWR;
14199 			/* No further checking required */
14200 			un->un_dp->options &= ~ST_WORMABLE;
14201 		}
14202 
14203 	} else {
14204 
14205 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14206 		    "AIT device config mode sense page read command failed"
14207 		    " result = %d ", result);
14208 		wrt = FAILED;
14209 		un->un_wormable = st_is_not_wormable;
14210 	}
14211 
14212 	kmem_free(ait_conf, sizeof (ait_dev_con));
14213 	return (wrt);
14214 }
14215 
14216 static writablity
14217 st_is_drive_worm(struct scsi_tape *un)
14218 {
14219 	writablity wrt;
14220 
14221 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14222 
14223 	switch (un->un_dp->type) {
14224 	case MT_ISDLT:
14225 		wrt = st_is_dlt_worm(un);
14226 		break;
14227 
14228 	case MT_ISSTK9840:
14229 		wrt = st_is_stk_worm(un);
14230 		break;
14231 
14232 	case MT_IS8MM:
14233 	case MT_ISAIT:
14234 		wrt = st_is_sony_worm(un);
14235 		break;
14236 
14237 	case MT_LTO:
14238 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14239 			wrt = st_is_hp_lto_worm(un);
14240 		} else {
14241 			wrt = st_is_t10_worm(un);
14242 		}
14243 		break;
14244 
14245 	case MT_ISDAT:
14246 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14247 			wrt = st_is_hp_dat_worm(un);
14248 		} else {
14249 			wrt = st_is_t10_worm(un);
14250 		}
14251 		break;
14252 
14253 	default:
14254 		wrt = FAILED;
14255 		break;
14256 	}
14257 
14258 	/*
14259 	 * If any of the above failed try the t10 standard method.
14260 	 */
14261 	if (wrt == FAILED) {
14262 		wrt = st_is_t10_worm(un);
14263 	}
14264 
14265 	/*
14266 	 * Unknown method for detecting WORM media.
14267 	 */
14268 	if (wrt == FAILED) {
14269 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14270 		    "Unknown method for WORM media detection\n");
14271 		wrt = RDWR;
14272 		un->un_dp->options &= ~ST_WORMABLE;
14273 	}
14274 
14275 	return (wrt);
14276 }
14277 
14278 static int
14279 st_read_attributes(struct scsi_tape *un, uint16_t attribute, void *pnt,
14280     size_t size, ubufunc_t bufunc)
14281 {
14282 	char cdb[CDB_GROUP4];
14283 	int result;
14284 	struct uscsi_cmd *cmd;
14285 	struct scsi_arq_status status;
14286 
14287 	caddr_t buf = (caddr_t)pnt;
14288 
14289 	ST_FUNC(ST_DEVINFO, st_read_attributes);
14290 
14291 	if (un->un_sd->sd_inq->inq_ansi < 3) {
14292 		return (ENOTTY);
14293 	}
14294 
14295 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14296 
14297 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
14298 	cdb[1] = 0;
14299 	cdb[2] = 0;
14300 	cdb[3] = 0;
14301 	cdb[4] = 0;
14302 	cdb[5] = 0;
14303 	cdb[6] = 0;
14304 	cdb[7] = 0;
14305 	cdb[8] = (char)(attribute >> 8);
14306 	cdb[9] = (char)(attribute);
14307 	cdb[10] = (char)(size >> 24);
14308 	cdb[11] = (char)(size >> 16);
14309 	cdb[12] = (char)(size >> 8);
14310 	cdb[13] = (char)(size);
14311 	cdb[14] = 0;
14312 	cdb[15] = 0;
14313 
14314 
14315 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE | USCSI_DIAGNOSE;
14316 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14317 	cmd->uscsi_cdb = &cdb[0];
14318 	cmd->uscsi_bufaddr = (caddr_t)buf;
14319 	cmd->uscsi_buflen = size;
14320 	cmd->uscsi_cdblen = sizeof (cdb);
14321 	cmd->uscsi_rqlen = sizeof (status);
14322 	cmd->uscsi_rqbuf = (caddr_t)&status;
14323 
14324 	result = bufunc(un, cmd, FKIOCTL);
14325 
14326 	if (result != 0 || cmd->uscsi_status != 0) {
14327 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
14328 		    "st_read_attribute failed: result %d status %d\n",
14329 		    result, cmd->uscsi_status);
14330 		/*
14331 		 * If this returns invalid operation code don't try again.
14332 		 */
14333 		if (un->un_sd->sd_sense->es_key == KEY_ILLEGAL_REQUEST &&
14334 		    un->un_sd->sd_sense->es_add_code == 0x20) {
14335 			result = ENOTTY;
14336 		} else if (result == 0) {
14337 			result = EIO;
14338 		}
14339 
14340 	} else {
14341 
14342 		/*
14343 		 * The attribute retured should match the attribute requested.
14344 		 */
14345 		if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
14346 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14347 			    "st_read_attribute got wrong data back expected "
14348 			    "0x%x got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
14349 			st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14350 			    "bad? data", buf, size);
14351 			result = EIO;
14352 		}
14353 	}
14354 
14355 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14356 
14357 	return (result);
14358 }
14359 
14360 static int
14361 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
14362     uchar_t page)
14363 {
14364 	char cdb[CDB_GROUP0];
14365 	struct scsi_extended_sense *sense;
14366 	struct uscsi_cmd *cmd;
14367 	int result;
14368 
14369 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
14370 
14371 	cdb[0] = SCMD_INQUIRY;
14372 	cdb[1] = page ? 1 : 0;
14373 	cdb[2] = page;
14374 	cdb[3] = 0;
14375 	cdb[4] = size;
14376 	cdb[5] = 0;
14377 
14378 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14379 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
14380 
14381 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
14382 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14383 	cmd->uscsi_cdb = &cdb[0];
14384 	cmd->uscsi_bufaddr = dest;
14385 	cmd->uscsi_buflen = size;
14386 	cmd->uscsi_cdblen = CDB_GROUP0;
14387 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
14388 	cmd->uscsi_rqbuf = (caddr_t)sense;
14389 
14390 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14391 
14392 	if (result != 0 || cmd->uscsi_status != 0) {
14393 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14394 		    "st_get_special_inquiry() failed for page %x", page);
14395 		if (result == 0) {
14396 			result = EIO;
14397 		}
14398 	}
14399 
14400 	kmem_free(sense, sizeof (struct scsi_extended_sense));
14401 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14402 
14403 	return (result);
14404 }
14405 
14406 
14407 static int
14408 st_update_block_pos(struct scsi_tape *un, bufunc_t bf, int post_space)
14409 {
14410 	int rval = ENOTTY;
14411 	uchar_t status = un->un_status;
14412 	posmode previous_pmode = un->un_running.pmode;
14413 
14414 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
14415 
14416 	while (un->un_read_pos_type != NO_POS) {
14417 		rval = bf(un, SCMD_READ_POSITION, 32, SYNC_CMD);
14418 
14419 		/*
14420 		 * If read position command returned good status
14421 		 * Parse the data to see if the position can be interpreted.
14422 		 */
14423 		if ((rval == 0) &&
14424 		    ((rval = st_interpret_read_pos(un, &un->un_pos,
14425 		    un->un_read_pos_type, 32, (caddr_t)un->un_read_pos_data,
14426 		    post_space)) == 0)) {
14427 			/*
14428 			 * Update the running position as well if un_pos was
14429 			 * ok. But only if recovery is enabled.
14430 			 */
14431 			if (st_recov_sz != sizeof (recov_info)) {
14432 				break;
14433 			}
14434 			rval = st_interpret_read_pos(un, &un->un_running,
14435 			    un->un_read_pos_type, 32,
14436 			    (caddr_t)un->un_read_pos_data, post_space);
14437 			un->un_status = status;
14438 			break;
14439 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
14440 			un->un_running.pmode = previous_pmode;
14441 			continue;
14442 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
14443 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
14444 			    "st_update_block_pos() read position cmd 0x%x"
14445 			    " returned 0x%x un_status = %d",
14446 			    un->un_read_pos_type, rval, un->un_status);
14447 			/* ENOTTY means it read garbage. try something else. */
14448 			if (rval == ENOTTY) {
14449 				rval = EIO; /* so ENOTTY is not final rval */
14450 			} else {
14451 				break;
14452 			}
14453 		} else {
14454 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
14455 			    "st_update_block_pos() read position cmd %x"
14456 			    " returned %x", un->un_read_pos_type, rval);
14457 			un->un_running.pmode = previous_pmode;
14458 		}
14459 
14460 		switch (un->un_read_pos_type) {
14461 		case SHORT_POS:
14462 			un->un_read_pos_type = NO_POS;
14463 			break;
14464 
14465 		case LONG_POS:
14466 			un->un_read_pos_type = EXT_POS;
14467 			break;
14468 
14469 		case EXT_POS:
14470 			un->un_read_pos_type = SHORT_POS;
14471 			break;
14472 
14473 		default:
14474 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14475 			    "Unexpected read position type 0x%x",
14476 			    un->un_read_pos_type);
14477 		}
14478 		un->un_status = KEY_NO_SENSE;
14479 	}
14480 
14481 	return (rval);
14482 }
14483 
14484 static int
14485 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
14486 {
14487 	int result;
14488 	size_t d_sz;
14489 	caddr_t pos_info;
14490 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
14491 
14492 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
14493 
14494 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
14495 		return (0);
14496 	}
14497 
14498 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
14499 
14500 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14501 		    "bp_mapin_common() failed");
14502 
14503 		return (EIO);
14504 	}
14505 
14506 	d_sz = bp->b_bcount - bp->b_resid;
14507 	if (d_sz == 0) {
14508 		bp_mapout(bp);
14509 		return (EIO);
14510 	}
14511 
14512 	/*
14513 	 * Copy the buf to a double-word aligned memory that can hold the
14514 	 * tape_position_t data structure.
14515 	 */
14516 	if ((pos_info = kmem_alloc(d_sz, KM_NOSLEEP)) == NULL) {
14517 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14518 		    "kmem_alloc() failed");
14519 		bp_mapout(bp);
14520 		return (EIO);
14521 	}
14522 	bcopy(bp->b_un.b_addr, pos_info, d_sz);
14523 
14524 #ifdef STDEBUG
14525 	if ((st_debug & 0x7) > 2) {
14526 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14527 		    "st_get_read_pos() position info",
14528 		    pos_info, bp->b_bcount);
14529 	}
14530 #endif
14531 
14532 	result = st_interpret_read_pos(un, &un->un_pos, cmd->uscsi_cdb[1],
14533 	    d_sz, pos_info, 0);
14534 
14535 	COPY_POS(&un->un_running, &un->un_pos);
14536 
14537 	kmem_free(pos_info, d_sz);
14538 	bp_mapout(bp);
14539 
14540 	return (result);
14541 }
14542 
14543 #if defined(_BIG_ENDIAN)
14544 
14545 #define	FIX_ENDIAN16(x)
14546 #define	FIX_ENDIAN32(x)
14547 #define	FIX_ENDIAN64(x)
14548 
14549 #elif defined(_LITTLE_ENDIAN)
14550 
14551 static void
14552 st_swap16(uint16_t *val)
14553 {
14554 	uint16_t tmp;
14555 
14556 	tmp = (*val >>  8) & 0xff;
14557 	tmp |= (*val <<  8) & 0xff00;
14558 
14559 	*val = tmp;
14560 }
14561 
14562 static void
14563 st_swap32(uint32_t *val)
14564 {
14565 	uint32_t tmp;
14566 
14567 	tmp =  (*val >> 24) & 0xff;
14568 	tmp |= (*val >>  8) & 0xff00;
14569 	tmp |= (*val <<  8) & 0xff0000;
14570 	tmp |= (*val << 24) & 0xff000000;
14571 
14572 	*val = tmp;
14573 }
14574 
14575 static void
14576 st_swap64(uint64_t *val)
14577 {
14578 	uint32_t low;
14579 	uint32_t high;
14580 
14581 	low =  (uint32_t)(*val);
14582 	high = (uint32_t)(*val >> 32);
14583 
14584 	st_swap32(&low);
14585 	st_swap32(&high);
14586 
14587 	*val =  high;
14588 	*val |= ((uint64_t)low << 32);
14589 }
14590 
14591 #define	FIX_ENDIAN16(x) st_swap16(x)
14592 #define	FIX_ENDIAN32(x) st_swap32(x)
14593 #define	FIX_ENDIAN64(x) st_swap64(x)
14594 #endif
14595 
14596 /*
14597  * st_interpret_read_pos()
14598  *
14599  * Returns:
14600  *	0	If secsessful.
14601  *	EIO	If read postion responce data was unuseable or invalid.
14602  *	ERANGE	If the position of the drive is too large for the read_p_type.
14603  *	ENOTTY	If the responce data looks invalid for the read position type.
14604  */
14605 
14606 static int
14607 st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
14608     read_p_types type, size_t data_sz, const caddr_t responce, int post_space)
14609 {
14610 	int rval = 0;
14611 	int flag = 0;
14612 	tapepos_t org;
14613 
14614 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
14615 
14616 	/*
14617 	 * We expect the position value to change after a space command.
14618 	 * So if post_space is set we don't print out what has changed.
14619 	 */
14620 	if ((dest != &un->un_pos) && (post_space == 0) &&
14621 	    (st_recov_sz == sizeof (recov_info))) {
14622 		COPY_POS(&org, dest);
14623 		flag = 1;
14624 	}
14625 
14626 	/*
14627 	 * See what kind of read position was requested.
14628 	 */
14629 	switch (type) {
14630 
14631 	case SHORT_POS: /* Short data format */
14632 	{
14633 		tape_position_t *pos_info = (tape_position_t *)responce;
14634 		uint32_t value;
14635 
14636 		/* If reserved fields are non zero don't use the data */
14637 		if (pos_info->reserved0 || pos_info->reserved1 ||
14638 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
14639 		    pos_info->reserved3) {
14640 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14641 			    "Invalid Read Short Position Data returned\n");
14642 			rval = EIO;
14643 			break;
14644 		}
14645 		/*
14646 		 * Position is to large to use this type of read position.
14647 		 */
14648 		if (pos_info->posi_err == 1) {
14649 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14650 			    "Drive reported position error\n");
14651 			rval = ERANGE;
14652 			break;
14653 		}
14654 		/*
14655 		 * If your at the begining of partition and end at the same
14656 		 * time it's very small partition or bad data.
14657 		 */
14658 		if (pos_info->begin_of_part && pos_info->end_of_part) {
14659 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14660 			    "SHORT_POS returned begin and end of"
14661 			    " partition\n");
14662 			rval = EIO;
14663 			break;
14664 		}
14665 
14666 		if (pos_info->blk_posi_unkwn == 0) {
14667 
14668 			value = pos_info->host_block;
14669 			FIX_ENDIAN32(&value);
14670 
14671 			/*
14672 			 * If the tape is rewound the host blcok should be 0.
14673 			 */
14674 			if ((pos_info->begin_of_part == 1) &&
14675 			    (value != 0)) {
14676 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14677 				    "SHORT_POS returned begin of partition"
14678 				    " but host block was 0x%x\n", value);
14679 				rval = EIO;
14680 				break;
14681 			}
14682 
14683 			if (dest->lgclblkno != value) {
14684 				if (flag)
14685 					flag++;
14686 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14687 				    "SHORT_POS current logical 0x%"PRIx64" read"
14688 				    " 0x%x\n", dest->lgclblkno, value);
14689 			}
14690 
14691 			dest->lgclblkno = (uint64_t)value;
14692 
14693 			/*
14694 			 * If the begining of partition is true and the
14695 			 * block number is zero we will beleive that it is
14696 			 * rewound. Promote the pmode to legacy.
14697 			 */
14698 			if ((pos_info->begin_of_part == 1) &&
14699 			    (value == 0)) {
14700 				dest->blkno = 0;
14701 				dest->fileno = 0;
14702 				if (dest->pmode != legacy)
14703 					dest->pmode = legacy;
14704 			/*
14705 			 * otherwise if the pmode was invalid,
14706 			 * promote it to logical.
14707 			 */
14708 			} else if (dest->pmode == invalid) {
14709 				dest->pmode = logical;
14710 			}
14711 
14712 			if (dest->partition != pos_info->partition_number) {
14713 				if (flag)
14714 					flag++;
14715 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14716 				    "SHORT_POS current partition %d read %d\n",
14717 				    dest->partition,
14718 				    pos_info->partition_number);
14719 			}
14720 
14721 			dest->partition = pos_info->partition_number;
14722 
14723 		} else {
14724 			dest->pmode = invalid;
14725 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14726 			    "Tape drive reported block position as unknown\n");
14727 		}
14728 		break;
14729 	}
14730 
14731 	case LONG_POS: /* Long data format */
14732 	{
14733 		uint64_t value;
14734 		tape_position_long_t *long_pos_info =
14735 		    (tape_position_long_t *)responce;
14736 
14737 		/* If reserved fields are non zero don't use the data */
14738 		if ((long_pos_info->reserved0) ||
14739 		    (long_pos_info->reserved1) ||
14740 		    (long_pos_info->reserved2)) {
14741 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14742 			    "Invalid Read Long Position Data returned\n");
14743 			rval = ENOTTY;
14744 			break;
14745 		}
14746 
14747 		/* Is position Valid */
14748 		if (long_pos_info->blk_posi_unkwn == 0) {
14749 			uint32_t part;
14750 
14751 			value = long_pos_info->block_number;
14752 			FIX_ENDIAN64(&value);
14753 
14754 			/*
14755 			 * If it says we are at the begining of partition
14756 			 * the block value better be 0.
14757 			 */
14758 			if ((long_pos_info->begin_of_part == 1) &&
14759 			    (value != 0)) {
14760 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14761 				    "LONG_POS returned begin of partition but"
14762 				    " block number was 0x%"PRIx64"\n", value);
14763 				rval = ENOTTY;
14764 				break;
14765 			}
14766 			/*
14767 			 * Can't be at the start and the end of the partition
14768 			 * at the same time if the partition is larger the 0.
14769 			 */
14770 			if (long_pos_info->begin_of_part &&
14771 			    long_pos_info->end_of_part) {
14772 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14773 				    "LONG_POS returned begin and end of"
14774 				    " partition\n");
14775 				rval = ENOTTY;
14776 				break;
14777 			}
14778 
14779 			/*
14780 			 * If the logical block number is not what we expected.
14781 			 */
14782 			if (dest->lgclblkno != value) {
14783 				if (flag)
14784 					flag++;
14785 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14786 				    "LONG_POS current logical 0x%"PRIx64
14787 				    " read 0x%"PRIx64"\n",
14788 				    dest->lgclblkno, value);
14789 			}
14790 			dest->lgclblkno = value;
14791 
14792 			/*
14793 			 * If the begining of partition is true and the
14794 			 * block number is zero we will beleive that it is
14795 			 * rewound. Promote the pmode to legacy.
14796 			 */
14797 			if ((long_pos_info->begin_of_part == 1) &&
14798 			    (long_pos_info->block_number == 0)) {
14799 				dest->blkno = 0;
14800 				dest->fileno = 0;
14801 				if (dest->pmode != legacy)
14802 					dest->pmode = legacy;
14803 			/*
14804 			 * otherwise if the pmode was invalid,
14805 			 * promote it to logical.
14806 			 */
14807 			} else if (dest->pmode == invalid) {
14808 				dest->pmode = logical;
14809 			}
14810 
14811 			part = long_pos_info->partition;
14812 			FIX_ENDIAN32(&part);
14813 			if (dest->partition != part) {
14814 				if (flag)
14815 					flag++;
14816 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14817 				    "LONG_POS current partition %d"
14818 				    " read %d\n", dest->partition, part);
14819 			}
14820 			dest->partition = part;
14821 		} else {
14822 			/*
14823 			 * If the drive doesn't know location,
14824 			 * we don't either.
14825 			 */
14826 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14827 			    "Tape drive reported block position as unknown\n");
14828 			dest->pmode = invalid;
14829 		}
14830 
14831 		/* Is file position valid */
14832 		if (long_pos_info->mrk_posi_unkwn == 0) {
14833 			value = long_pos_info->file_number;
14834 			FIX_ENDIAN64(&value);
14835 			/*
14836 			 * If it says we are at the begining of partition
14837 			 * the block value better be 0.
14838 			 */
14839 			if ((long_pos_info->begin_of_part == 1) &&
14840 			    (value != 0)) {
14841 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14842 				    "LONG_POS returned begin of partition but"
14843 				    " block number was 0x%"PRIx64"\n", value);
14844 				rval = ENOTTY;
14845 				break;
14846 			}
14847 			if (((dest->pmode == legacy) ||
14848 			    (dest->pmode == logical)) &&
14849 			    (dest->fileno != value)) {
14850 				if (flag)
14851 					flag++;
14852 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14853 				    "LONG_POS fileno 0x%"PRIx64
14854 				    " not un_pos %x\n", value,
14855 				    dest->fileno);
14856 			} else if (dest->pmode == invalid) {
14857 				dest->pmode = logical;
14858 			}
14859 			dest->fileno = (int32_t)value;
14860 		}
14861 
14862 		if (dest->pmode != invalid && long_pos_info->end_of_part) {
14863 			dest->eof = ST_EOT;
14864 		}
14865 
14866 		break;
14867 	}
14868 
14869 	case EXT_POS: /* Extended data format */
14870 	{
14871 		uint64_t value;
14872 		uint16_t len;
14873 		tape_position_ext_t *ext_pos_info =
14874 		    (tape_position_ext_t *)responce;
14875 
14876 		/* Make sure that there is enough data there */
14877 		if (data_sz < 16) {
14878 			break;
14879 		}
14880 
14881 		/* If reserved fields are non zero don't use the data */
14882 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
14883 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14884 			    "EXT_POS reserved fields not zero\n");
14885 			rval = ENOTTY;
14886 			break;
14887 		}
14888 
14889 		/*
14890 		 * In the unlikely event of overflowing 64 bits of position.
14891 		 */
14892 		if (ext_pos_info->posi_err != 0) {
14893 			rval = ERANGE;
14894 			break;
14895 		}
14896 
14897 		len = ext_pos_info->parameter_len;
14898 		FIX_ENDIAN16(&len);
14899 
14900 		if (len != 0x1c) {
14901 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14902 			    "EXT_POS parameter_len should be 0x1c was 0x%x\n",
14903 			    len);
14904 			rval = ENOTTY;
14905 			break;
14906 		}
14907 
14908 		/* Is block position information valid */
14909 		if (ext_pos_info->blk_posi_unkwn == 0) {
14910 
14911 			value = ext_pos_info->host_block;
14912 			FIX_ENDIAN64(&value);
14913 			if ((ext_pos_info->begin_of_part == 1) &&
14914 			    (value != 0)) {
14915 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14916 				    "EXT_POS returned begining of partition but"
14917 				    " the host block was 0x%"PRIx64"\n", value);
14918 				rval = ENOTTY;
14919 				break;
14920 			}
14921 
14922 			if (dest->lgclblkno != value) {
14923 				if (flag)
14924 					flag++;
14925 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14926 				    "EXT_POS current logical 0x%"PRIx64
14927 				    " read 0x%"PRIx64"\n",
14928 				    dest->lgclblkno, value);
14929 			}
14930 			dest->lgclblkno = value;
14931 
14932 			/*
14933 			 * If the begining of partition is true and the
14934 			 * block number is zero we will beleive that it is
14935 			 * rewound. Promote the pmode to legacy.
14936 			 */
14937 			if ((ext_pos_info->begin_of_part == 1) &&
14938 			    (ext_pos_info->host_block == 0)) {
14939 				dest->blkno = 0;
14940 				dest->fileno = 0;
14941 				if (dest->pmode != legacy) {
14942 					dest->pmode = legacy;
14943 				}
14944 			/*
14945 			 * otherwise if the pmode was invalid,
14946 			 * promote it to logical.
14947 			 */
14948 			} else if (dest->pmode == invalid) {
14949 				dest->pmode = logical;
14950 			}
14951 
14952 			if (dest->partition != ext_pos_info->partition) {
14953 				if (flag)
14954 					flag++;
14955 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14956 				    "EXT_POS current partition %d read %d\n",
14957 				    dest->partition,
14958 				    ext_pos_info->partition);
14959 			}
14960 			dest->partition = ext_pos_info->partition;
14961 
14962 		} else {
14963 			dest->pmode = invalid;
14964 		}
14965 		break;
14966 	}
14967 
14968 	default:
14969 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14970 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
14971 		rval = EIO;
14972 	}
14973 
14974 	if ((flag > 1) && (rval == 0) && (org.pmode != invalid)) {
14975 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14976 		    "position read in", &org);
14977 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14978 		    "position read out", dest);
14979 	}
14980 
14981 	return (rval);
14982 }
14983 
14984 static int
14985 st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos,
14986     uint64_t lblk, uchar_t partition)
14987 {
14988 	int rval;
14989 	char cdb[CDB_GROUP4];
14990 	struct uscsi_cmd *cmd;
14991 	struct scsi_extended_sense sense;
14992 	bufunc_t bf = (ubf == st_uscsi_cmd) ? st_cmd : st_rcmd;
14993 
14994 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
14995 	/*
14996 	 * Not sure what to do when doing recovery and not wanting
14997 	 * to update un_pos
14998 	 */
14999 
15000 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
15001 
15002 	if (lblk <= INT32_MAX) {
15003 		cmd->uscsi_cdblen = CDB_GROUP1;
15004 		cdb[0] = SCMD_LOCATE;
15005 		cdb[1] = pos->partition == partition ? 0 : 2;
15006 		cdb[2] = 0;
15007 		cdb[3] = (char)(lblk >> 24);
15008 		cdb[4] = (char)(lblk >> 16);
15009 		cdb[5] = (char)(lblk >> 8);
15010 		cdb[6] = (char)(lblk);
15011 		cdb[7] = 0;
15012 		cdb[8] = partition;
15013 		cdb[9] = 0;
15014 	} else {
15015 		/*
15016 		 * If the drive doesn't give a 64 bit read position data
15017 		 * it is unlikely it will accept 64 bit locates.
15018 		 */
15019 		if (un->un_read_pos_type != LONG_POS) {
15020 			kmem_free(cmd, sizeof (struct uscsi_cmd));
15021 			return (ERANGE);
15022 		}
15023 		cmd->uscsi_cdblen = CDB_GROUP4;
15024 		cdb[0] = (char)SCMD_LOCATE_G4;
15025 		cdb[1] = pos->partition == partition ? 0 : 2;
15026 		cdb[2] = 0;
15027 		cdb[3] = partition;
15028 		cdb[4] = (char)(lblk >> 56);
15029 		cdb[5] = (char)(lblk >> 48);
15030 		cdb[6] = (char)(lblk >> 40);
15031 		cdb[7] = (char)(lblk >> 32);
15032 		cdb[8] = (char)(lblk >> 24);
15033 		cdb[9] = (char)(lblk >> 16);
15034 		cdb[10] = (char)(lblk >> 8);
15035 		cdb[11] = (char)(lblk);
15036 		cdb[12] = 0;
15037 		cdb[13] = 0;
15038 		cdb[14] = 0;
15039 		cdb[15] = 0;
15040 	}
15041 
15042 
15043 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
15044 	cmd->uscsi_rqbuf = (caddr_t)&sense;
15045 	cmd->uscsi_rqlen = sizeof (sense);
15046 	cmd->uscsi_timeout = un->un_dp->space_timeout;
15047 	cmd->uscsi_cdb = cdb;
15048 
15049 	rval = ubf(un, cmd, FKIOCTL);
15050 
15051 	pos->pmode = logical;
15052 	pos->eof = ST_NO_EOF;
15053 
15054 	if (lblk > INT32_MAX) {
15055 		/*
15056 		 * XXX This is a work around till we handle Descriptor format
15057 		 * sense data. Since we are sending a command where the standard
15058 		 * sense data can not correctly represent a correct residual in
15059 		 * 4 bytes.
15060 		 */
15061 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
15062 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15063 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
15064 			/* Doesn't like big locate command */
15065 			un->un_status = 0;
15066 			rval = ERANGE;
15067 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
15068 			/* Aborted big locate command */
15069 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15070 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
15071 			    rval);
15072 			un->un_status = 0;
15073 			rval = EIO;
15074 		} else if (st_update_block_pos(un, bf, 1)) {
15075 			/* read position failed */
15076 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15077 			    "Big LOCATE and read pos: rval = %d\n", rval);
15078 			rval = EIO;
15079 		} else if (lblk > un->un_pos.lgclblkno) {
15080 			/* read position worked but position was not expected */
15081 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15082 			    "Big LOCATE and recover read less then desired 0x%"
15083 			    PRIx64"\n", un->un_pos.lgclblkno);
15084 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
15085 			un->un_status = KEY_BLANK_CHECK;
15086 			rval = ESPIPE;
15087 		} else if (lblk == un->un_pos.lgclblkno) {
15088 			/* read position was what was expected */
15089 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15090 			    "Big LOCATE and recover seems to have worked\n");
15091 			un->un_err_resid = 0;
15092 			rval = 0;
15093 		} else {
15094 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15095 			    "BIGLOCATE end up going backwards");
15096 			un->un_err_resid = lblk;
15097 			rval = EIO;
15098 		}
15099 
15100 	} else if (rval == 0) {
15101 		/* Worked as requested */
15102 		pos->lgclblkno = lblk;
15103 
15104 	} else if (((cmd->uscsi_status & ST_STATUS_MASK) == STATUS_CHECK) &&
15105 	    (cmd->uscsi_resid != 0)) {
15106 		/* Got part way there but wasn't enough blocks on tape */
15107 		pos->lgclblkno = lblk - cmd->uscsi_resid;
15108 		un->un_err_resid = cmd->uscsi_resid;
15109 		un->un_status = KEY_BLANK_CHECK;
15110 		rval = ESPIPE;
15111 
15112 	} else if (st_update_block_pos(un, bf, 1) == 0) {
15113 		/* Got part way there but drive didn't tell what we missed by */
15114 		un->un_err_resid = lblk - pos->lgclblkno;
15115 		un->un_status = KEY_BLANK_CHECK;
15116 		rval = ESPIPE;
15117 
15118 	} else {
15119 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15120 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
15121 		    rval, cmd->uscsi_status);
15122 		un->un_err_resid = lblk;
15123 		un->un_status = KEY_ILLEGAL_REQUEST;
15124 		pos->pmode = invalid;
15125 		rval = EIO;
15126 	}
15127 
15128 	kmem_free(cmd, sizeof (struct uscsi_cmd));
15129 
15130 	return (rval);
15131 }
15132 
15133 static int
15134 st_mtfsf_ioctl(struct scsi_tape *un, int64_t files)
15135 {
15136 	int rval;
15137 
15138 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
15139 
15140 
15141 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15142 	    "st_mtfsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15143 #if 0
15144 	if ((IN_EOF(un->un_pos)) && (files == 1)) {
15145 		un->un_pos.fileno++;
15146 		un->un_pos.blkno = 0;
15147 		return (0);
15148 	}
15149 #endif
15150 	/* pmode == invalid already handled */
15151 	if (un->un_pos.pmode == legacy) {
15152 		/*
15153 		 * forward space over filemark
15154 		 *
15155 		 * For ASF we allow a count of 0 on fsf which means
15156 		 * we just want to go to beginning of current file.
15157 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
15158 		 * Allow stepping over double fmk with reel
15159 		 */
15160 		if ((un->un_pos.eof >= ST_EOT) &&
15161 		    (files > 0) &&
15162 		    ((un->un_dp->options & ST_REEL) == 0)) {
15163 			/* we're at EOM */
15164 			un->un_err_resid = files;
15165 			un->un_status = KEY_BLANK_CHECK;
15166 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15167 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
15168 			return (EIO);
15169 		}
15170 
15171 		/*
15172 		 * physical tape position may not be what we've been
15173 		 * telling the user; adjust the request accordingly
15174 		 */
15175 		if (IN_EOF(un->un_pos)) {
15176 			un->un_pos.fileno++;
15177 			un->un_pos.blkno = 0;
15178 			/*
15179 			 * For positive direction case, we're now covered.
15180 			 * For zero or negative direction, we're covered
15181 			 * (almost)
15182 			 */
15183 			files--;
15184 		}
15185 
15186 	}
15187 
15188 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15189 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15190 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
15191 		return (EIO);
15192 	}
15193 
15194 
15195 	/*
15196 	 * Forward space file marks.
15197 	 * We leave ourselves at block zero
15198 	 * of the target file number.
15199 	 */
15200 	if (files < 0) {
15201 		rval = st_backward_space_files(un, -files, 0);
15202 	} else {
15203 		rval = st_forward_space_files(un, files);
15204 	}
15205 
15206 	return (rval);
15207 }
15208 
15209 static int
15210 st_forward_space_files(struct scsi_tape *un, int64_t count)
15211 {
15212 	int rval;
15213 
15214 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
15215 
15216 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15217 	    "fspace: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15218 
15219 	ASSERT(count >= 0);
15220 	ASSERT(un->un_pos.pmode != invalid);
15221 
15222 	/*
15223 	 * A space with a count of zero means take me to the start of file.
15224 	 */
15225 	if (count == 0) {
15226 
15227 		/* Hay look were already there */
15228 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0) {
15229 			un->un_err_resid = 0;
15230 			COPY_POS(&un->un_err_pos, &un->un_pos);
15231 			return (0);
15232 		}
15233 
15234 		/*
15235 		 * Well we are in the first file.
15236 		 * A rewind will get to the start.
15237 		 */
15238 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
15239 			rval = st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
15240 
15241 		/*
15242 		 * Can we backspace to get there?
15243 		 * This should work in logical mode.
15244 		 */
15245 		} else if (un->un_dp->options & ST_BSF) {
15246 			rval = st_space_to_begining_of_file(un);
15247 
15248 		/*
15249 		 * Can't back space but current file number is known,
15250 		 * So rewind and space from the begining of the partition.
15251 		 */
15252 		} else if (un->un_pos.pmode == legacy) {
15253 			rval = st_scenic_route_to_begining_of_file(un,
15254 			    un->un_pos.fileno);
15255 
15256 		/*
15257 		 * pmode is logical and ST_BSF is not set.
15258 		 * The LONG_POS read position contains the fileno.
15259 		 * If the read position works, rewind and space.
15260 		 */
15261 		} else if (un->un_read_pos_type == LONG_POS) {
15262 			rval = st_cmd(un, SCMD_READ_POSITION, 0, SYNC_CMD);
15263 			if (rval) {
15264 				/*
15265 				 * We didn't get the file position from the
15266 				 * read position command.
15267 				 * We are going to trust the drive to backspace
15268 				 * and then position after the filemark.
15269 				 */
15270 				rval = st_space_to_begining_of_file(un);
15271 			}
15272 			rval = st_interpret_read_pos(un, &un->un_pos, LONG_POS,
15273 			    32, (caddr_t)un->un_read_pos_data, 0);
15274 			if ((rval) && (un->un_pos.pmode == invalid)) {
15275 				rval = st_space_to_begining_of_file(un);
15276 			} else {
15277 				rval = st_scenic_route_to_begining_of_file(un,
15278 				    un->un_pos.fileno);
15279 			}
15280 		} else {
15281 			rval = EIO;
15282 		}
15283 		/*
15284 		 * If something didn't work we are lost
15285 		 */
15286 		if (rval != 0) {
15287 			un->un_pos.pmode = invalid;
15288 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15289 			    "st_mtioctop : EIO : fspace pmode invalid");
15290 
15291 			rval = EIO;
15292 		}
15293 
15294 	} else {
15295 		rval = st_space_fmks(un, count);
15296 	}
15297 
15298 	if (rval != EIO && count < 0) {
15299 		/*
15300 		 * we came here with a count < 0; we now need
15301 		 * to skip back to end up before the filemark
15302 		 */
15303 		rval = st_backward_space_files(un, 1, 1);
15304 	}
15305 
15306 	return (rval);
15307 }
15308 
15309 static int
15310 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
15311 {
15312 	int rval;
15313 
15314 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
15315 
15316 	if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15317 		rval = EIO;
15318 	} else if (st_cmd(un, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
15319 		rval = EIO;
15320 	}
15321 
15322 	return (rval);
15323 }
15324 
15325 static int
15326 st_space_to_begining_of_file(struct scsi_tape *un)
15327 {
15328 	int rval;
15329 
15330 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
15331 
15332 	/*
15333 	 * Back space of the file at the begining of the file.
15334 	 */
15335 	rval = st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
15336 	if (rval) {
15337 		rval = EIO;
15338 		return (rval);
15339 	}
15340 
15341 	/*
15342 	 * Other interesting answers might be crashed BOT which isn't bad.
15343 	 */
15344 	if (un->un_status == SUN_KEY_BOT) {
15345 		return (rval);
15346 	}
15347 
15348 	un->un_running.pmode = invalid;
15349 
15350 	/*
15351 	 * Now we are on the BOP side of the filemark. Forward space to
15352 	 * the EOM side and we are at the begining of the file.
15353 	 */
15354 	rval = st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD);
15355 	if (rval) {
15356 		rval = EIO;
15357 	}
15358 
15359 	return (rval);
15360 }
15361 
15362 static int
15363 st_mtfsr_ioctl(struct scsi_tape *un, int64_t count)
15364 {
15365 
15366 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
15367 
15368 	/*
15369 	 * forward space to inter-record gap
15370 	 *
15371 	 */
15372 
15373 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15374 	    "st_ioctl_fsr: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15375 
15376 	if (un->un_pos.pmode == legacy) {
15377 		/*
15378 		 * If were are at end of tape and count is forward.
15379 		 * Return blank check.
15380 		 */
15381 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
15382 			/* we're at EOM */
15383 			un->un_err_resid = count;
15384 			un->un_status = KEY_BLANK_CHECK;
15385 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15386 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
15387 			return (EIO);
15388 		}
15389 
15390 		/*
15391 		 * If count is zero there is nothing to do.
15392 		 */
15393 		if (count == 0) {
15394 			un->un_err_pos.fileno = un->un_pos.fileno;
15395 			un->un_err_pos.blkno = un->un_pos.blkno;
15396 			un->un_err_resid = 0;
15397 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15398 				un->un_status = SUN_KEY_EOF;
15399 			}
15400 			return (0);
15401 		}
15402 
15403 		/*
15404 		 * physical tape position may not be what we've been
15405 		 * telling the user; adjust the position accordingly
15406 		 */
15407 		if (IN_EOF(un->un_pos)) {
15408 			daddr_t blkno = un->un_pos.blkno;
15409 			int fileno = un->un_pos.fileno;
15410 
15411 			optype lastop = un->un_lastop;
15412 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)
15413 			    == -1) {
15414 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15415 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
15416 				return (EIO);
15417 			}
15418 
15419 			un->un_pos.blkno = blkno;
15420 			un->un_pos.fileno = fileno;
15421 			un->un_lastop = lastop;
15422 		}
15423 	}
15424 
15425 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15426 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15427 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
15428 		return (EIO);
15429 	}
15430 
15431 	return (st_space_records(un, count));
15432 }
15433 
15434 static int
15435 st_space_records(struct scsi_tape *un, int64_t count)
15436 {
15437 	int64_t dblk;
15438 	int rval = 0;
15439 
15440 	ST_FUNC(ST_DEVINFO, st_space_records);
15441 
15442 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15443 	    "st_space_records: count=%"PRIx64", eof=%x\n",
15444 	    count, un->un_pos.eof);
15445 
15446 	if (un->un_pos.pmode == logical) {
15447 		rval = st_cmd(un, SCMD_SPACE, Blk(count), SYNC_CMD);
15448 		if (rval != 0) {
15449 			rval = EIO;
15450 		}
15451 		return (rval);
15452 	}
15453 
15454 	dblk = count + un->un_pos.blkno;
15455 
15456 	/* Already there */
15457 	if (dblk == un->un_pos.blkno) {
15458 		un->un_err_resid = 0;
15459 		COPY_POS(&un->un_err_pos, &un->un_pos);
15460 		return (0);
15461 	}
15462 
15463 	/*
15464 	 * If the destination block is forward
15465 	 * or the drive will backspace records.
15466 	 */
15467 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
15468 		/*
15469 		 * If we're spacing forward, or the device can
15470 		 * backspace records, we can just use the SPACE
15471 		 * command.
15472 		 */
15473 		dblk -= un->un_pos.blkno;
15474 		if (st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15475 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15476 			    "st_space_records:EIO:space_records can't spc");
15477 			rval = EIO;
15478 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
15479 			/*
15480 			 * check if we hit BOT/EOT
15481 			 */
15482 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
15483 				un->un_status = SUN_KEY_BOT;
15484 				un->un_pos.eof = ST_NO_EOF;
15485 			} else if (dblk < 0 &&
15486 			    un->un_pos.eof == ST_EOF_PENDING) {
15487 				int residue = un->un_err_resid;
15488 				/*
15489 				 * we skipped over a filemark
15490 				 * and need to go forward again
15491 				 */
15492 				if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
15493 					ST_DEBUG2(ST_DEVINFO, st_label,
15494 					    SCSI_DEBUG, "st_space_records: EIO"
15495 					    " : can't space #2");
15496 					rval = EIO;
15497 				}
15498 				un->un_err_resid = residue;
15499 			}
15500 			if (rval == 0) {
15501 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15502 				    "st_space_records: EIO : space_rec rval"
15503 				    " == 0");
15504 				rval = EIO;
15505 			}
15506 		}
15507 	} else {
15508 		/*
15509 		 * else we rewind, space forward across filemarks to
15510 		 * the desired file, and then space records to the
15511 		 * desired block.
15512 		 */
15513 
15514 		int dfile = un->un_pos.fileno;	/* save current file */
15515 
15516 		if (dblk < 0) {
15517 			/*
15518 			 * Wups - we're backing up over a filemark
15519 			 */
15520 			if (un->un_pos.blkno != 0 &&
15521 			    (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15522 			    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD))) {
15523 				un->un_pos.pmode = invalid;
15524 			}
15525 			un->un_err_resid = -dblk;
15526 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
15527 				un->un_status = SUN_KEY_BOT;
15528 				un->un_pos.eof = ST_NO_EOF;
15529 			} else if (un->un_pos.fileno > 0) {
15530 				un->un_status = SUN_KEY_EOF;
15531 				un->un_pos.eof = ST_NO_EOF;
15532 			}
15533 			COPY_POS(&un->un_err_pos, &un->un_pos);
15534 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15535 			    "st_space_records:EIO:space_records : dblk < 0");
15536 			rval = EIO;
15537 		} else if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15538 		    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
15539 		    st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15540 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15541 			    "st_space_records: EIO :space_records : rewind "
15542 			    "and space failed");
15543 			un->un_pos.pmode = invalid;
15544 			rval = EIO;
15545 		}
15546 	}
15547 
15548 	return (rval);
15549 }
15550 
15551 static int
15552 st_mtbsf_ioctl(struct scsi_tape *un, int64_t files)
15553 {
15554 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
15555 
15556 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15557 	    "st_mtbsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15558 	/*
15559 	 * backward space of file filemark (1/2" and 8mm)
15560 	 * tape position will end on the beginning of tape side
15561 	 * of the desired file mark
15562 	 */
15563 	if ((un->un_dp->options & ST_BSF) == 0) {
15564 		return (ENOTTY);
15565 	}
15566 
15567 	if (un->un_pos.pmode == legacy) {
15568 
15569 		/*
15570 		 * If a negative count (which implies a forward space op)
15571 		 * is specified, and we're at logical or physical eot,
15572 		 * bounce the request.
15573 		 */
15574 
15575 		if (un->un_pos.eof >= ST_EOT && files < 0) {
15576 			un->un_err_resid = files;
15577 			un->un_status = SUN_KEY_EOT;
15578 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15579 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
15580 			return (EIO);
15581 		}
15582 		/*
15583 		 * physical tape position may not be what we've been
15584 		 * telling the user; adjust the request accordingly
15585 		 */
15586 		if (IN_EOF(un->un_pos)) {
15587 			un->un_pos.fileno++;
15588 			un->un_pos.blkno = 0;
15589 			files++;
15590 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15591 			    "st_mtbsf_ioctl in eof: count=%"PRIx64", op=%x\n",
15592 			    files, MTBSF);
15593 
15594 		}
15595 	}
15596 
15597 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15598 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15599 		    "st_ioctl : EIO : MTBSF : check den wfm");
15600 		return (EIO);
15601 	}
15602 
15603 	if (files <= 0) {
15604 		/*
15605 		 * for a negative count, we need to step forward
15606 		 * first and then step back again
15607 		 */
15608 		files = -files + 1;
15609 		return (st_forward_space_files(un, files));
15610 	}
15611 	return (st_backward_space_files(un, files, 1));
15612 }
15613 
15614 static int
15615 st_backward_space_files(struct scsi_tape *un, int64_t count, int infront)
15616 {
15617 	int64_t end_fileno;
15618 	int64_t skip_cnt;
15619 	int rval = 0;
15620 
15621 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
15622 
15623 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15624 	    "st_backward_space_files: count=%"PRIx64" eof=%x\n",
15625 	    count, un->un_pos.eof);
15626 	/*
15627 	 * Backspace files (MTNBSF): infront == 0
15628 	 *
15629 	 *	For tapes that can backspace, backspace
15630 	 *	count+1 filemarks and then run forward over
15631 	 *	a filemark
15632 	 *
15633 	 *	For tapes that can't backspace,
15634 	 *		calculate desired filenumber
15635 	 *		(un->un_pos.fileno - count), rewind,
15636 	 *		and then space forward this amount
15637 	 *
15638 	 * Backspace filemarks (MTBSF) infront == 1
15639 	 *
15640 	 *	For tapes that can backspace, backspace count
15641 	 *	filemarks
15642 	 *
15643 	 *	For tapes that can't backspace, calculate
15644 	 *	desired filenumber (un->un_pos.fileno - count),
15645 	 *	add 1, rewind, space forward this amount,
15646 	 *	and mark state as ST_EOF_PENDING appropriately.
15647 	 */
15648 
15649 	if (un->un_pos.pmode == logical) {
15650 
15651 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15652 		    "st_backward_space_files: mt_op=%x count=%"PRIx64
15653 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
15654 		    un->un_pos.lgclblkno);
15655 
15656 
15657 		/* In case a drive that won't back space gets in logical mode */
15658 		if ((un->un_dp->options & ST_BSF) == 0) {
15659 			rval = EIO;
15660 			return (rval);
15661 		}
15662 		if ((infront == 1) &&
15663 		    (st_cmd(un, SCMD_SPACE, Fmk(-count), SYNC_CMD))) {
15664 			rval = EIO;
15665 			return (rval);
15666 		} else if ((infront == 0) &&
15667 		    (st_cmd(un, SCMD_SPACE, Fmk((-count)-1), SYNC_CMD)) &&
15668 		    (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
15669 			rval = EIO;
15670 			return (rval);
15671 		}
15672 		return (rval);
15673 	}
15674 
15675 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15676 	    "st_backward_space_files: mt_op=%x count=%"PRIx64
15677 	    "fileno=%x blkno=%x\n",
15678 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
15679 
15680 
15681 
15682 	/*
15683 	 * Handle the simple case of BOT
15684 	 * playing a role in these cmds.
15685 	 * We do this by calculating the
15686 	 * ending file number. If the ending
15687 	 * file is < BOT, rewind and set an
15688 	 * error and mark resid appropriately.
15689 	 * If we're backspacing a file (not a
15690 	 * filemark) and the target file is
15691 	 * the first file on the tape, just
15692 	 * rewind.
15693 	 */
15694 
15695 	/* figure expected destination of this SPACE command */
15696 	end_fileno = un->un_pos.fileno - count;
15697 
15698 	/*
15699 	 * Would the end effect of this SPACE be the same as rewinding?
15700 	 * If so just rewind instead.
15701 	 */
15702 	if ((infront != 0) && (end_fileno < 0) ||
15703 	    (infront == 0) && (end_fileno <= 0)) {
15704 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15705 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15706 			    "st_backward_space_files: EIO : "
15707 			    "rewind in lou of BSF failed\n");
15708 			rval = EIO;
15709 		}
15710 		if (end_fileno < 0) {
15711 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15712 			    "st_backward_space_files: EIO : "
15713 			    "back space file greater then fileno\n");
15714 			rval = EIO;
15715 			un->un_err_resid = -end_fileno;
15716 			un->un_status = SUN_KEY_BOT;
15717 		}
15718 		return (rval);
15719 	}
15720 
15721 	if (un->un_dp->options & ST_BSF) {
15722 		skip_cnt = 1 - infront;
15723 		/*
15724 		 * If we are going to end up at the beginning
15725 		 * of the file, we have to space one extra file
15726 		 * first, and then space forward later.
15727 		 */
15728 		end_fileno = -(count + skip_cnt);
15729 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15730 		    "skip_cnt=%"PRIx64", tmp=%"PRIx64"\n",
15731 		    skip_cnt, end_fileno);
15732 		if (st_cmd(un, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
15733 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15734 			    "st_backward_space_files:EIO:back space fm failed");
15735 			rval = EIO;
15736 		}
15737 	} else {
15738 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15739 			rval = EIO;
15740 		} else {
15741 			skip_cnt = end_fileno + infront;
15742 		}
15743 	}
15744 
15745 	/*
15746 	 * If we have to space forward, do so...
15747 	 */
15748 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15749 	    "space forward skip_cnt=%"PRIx64", rval=%x\n", skip_cnt, rval);
15750 
15751 	if (rval == 0 && skip_cnt) {
15752 		if (st_cmd(un, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
15753 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15754 			    "st_backward_space_files:EIO:space fm skip count");
15755 			rval = EIO;
15756 		} else if (infront) {
15757 			/*
15758 			 * If we had to space forward, and we're
15759 			 * not a tape that can backspace, mark state
15760 			 * as if we'd just seen a filemark during a
15761 			 * a read.
15762 			 */
15763 			if ((un->un_dp->options & ST_BSF) == 0) {
15764 				un->un_pos.eof = ST_EOF_PENDING;
15765 				un->un_pos.fileno -= 1;
15766 				un->un_pos.blkno = LASTBLK;
15767 				un->un_running.pmode = invalid;
15768 			}
15769 		}
15770 	}
15771 
15772 	if (rval != 0) {
15773 		un->un_pos.pmode = invalid;
15774 	}
15775 
15776 	return (rval);
15777 }
15778 
15779 static int
15780 st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count)
15781 {
15782 	int rval;
15783 
15784 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
15785 
15786 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15787 	    "nbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15788 
15789 	if (un->un_pos.pmode == legacy) {
15790 		/*
15791 		 * backward space file to beginning of file
15792 		 *
15793 		 * If a negative count (which implies a forward space op)
15794 		 * is specified, and we're at logical or physical eot,
15795 		 * bounce the request.
15796 		 */
15797 
15798 		if (un->un_pos.eof >= ST_EOT && count < 0) {
15799 			un->un_err_resid = count;
15800 			un->un_status = SUN_KEY_EOT;
15801 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15802 			    "st_ioctl : EIO : > EOT and count < 0");
15803 			return (EIO);
15804 		}
15805 		/*
15806 		 * physical tape position may not be what we've been
15807 		 * telling the user; adjust the request accordingly
15808 		 */
15809 		if (IN_EOF(un->un_pos)) {
15810 			un->un_pos.fileno++;
15811 			un->un_pos.blkno = 0;
15812 			count++;
15813 		}
15814 	}
15815 
15816 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15817 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15818 		    "st_ioctl : EIO : MTNBSF check den and wfm");
15819 		return (EIO);
15820 	}
15821 
15822 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15823 	    "mtnbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15824 
15825 	if (count <= 0) {
15826 		rval = st_forward_space_files(un, -count);
15827 	} else {
15828 		rval = st_backward_space_files(un, count, 0);
15829 	}
15830 	return (rval);
15831 }
15832 
15833 static int
15834 st_mtbsr_ioctl(struct scsi_tape *un, int64_t num)
15835 {
15836 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
15837 
15838 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15839 	    "bsr: count=%"PRIx64", eof=%x\n", num, un->un_pos.eof);
15840 
15841 	if (un->un_pos.pmode == legacy) {
15842 		/*
15843 		 * backward space into inter-record gap
15844 		 *
15845 		 * If a negative count (which implies a forward space op)
15846 		 * is specified, and we're at logical or physical eot,
15847 		 * bounce the request.
15848 		 */
15849 		if (un->un_pos.eof >= ST_EOT && num < 0) {
15850 			un->un_err_resid = num;
15851 			un->un_status = SUN_KEY_EOT;
15852 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15853 			    "st_ioctl : EIO : MTBSR > EOT");
15854 			return (EIO);
15855 		}
15856 
15857 		if (num == 0) {
15858 			COPY_POS(&un->un_err_pos, &un->un_pos);
15859 			un->un_err_resid = 0;
15860 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15861 				un->un_status = SUN_KEY_EOF;
15862 			}
15863 			return (0);
15864 		}
15865 
15866 		/*
15867 		 * physical tape position may not be what we've been
15868 		 * telling the user; adjust the position accordingly.
15869 		 * bsr can not skip filemarks and continue to skip records
15870 		 * therefore if we are logically before the filemark but
15871 		 * physically at the EOT side of the filemark, we need to step
15872 		 * back; this allows fsr N where N > number of blocks in file
15873 		 * followed by bsr 1 to position at the beginning of last block
15874 		 */
15875 		if (IN_EOF(un->un_pos)) {
15876 			tapepos_t save;
15877 			optype lastop = un->un_lastop;
15878 
15879 			COPY_POS(&save, &un->un_pos);
15880 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD) == -1) {
15881 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15882 				    "st_mtbsr_ioctl: EIO : MTBSR can't space");
15883 				return (EIO);
15884 			}
15885 
15886 			COPY_POS(&un->un_pos, &save);
15887 			un->un_lastop = lastop;
15888 		}
15889 	}
15890 
15891 	un->un_pos.eof = ST_NO_EOF;
15892 
15893 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15894 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15895 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
15896 		return (EIO);
15897 	}
15898 
15899 	num = -num;
15900 	return (st_space_records(un, num));
15901 }
15902 
15903 static int
15904 st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt)
15905 {
15906 	int rval;
15907 
15908 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
15909 
15910 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
15911 	if (rval == 0) {
15912 		un->un_pos.pmode = logical;
15913 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15914 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15915 		/*
15916 		 * Drive says invalid field in cdb.
15917 		 * Doesn't like space multiple. Position isn't lost.
15918 		 */
15919 		un->un_err_resid = cnt;
15920 		un->un_status = 0;
15921 		rval = ENOTTY;
15922 	} else {
15923 		un->un_err_resid = cnt;
15924 		un->un_pos.pmode = invalid;
15925 	}
15926 	return (rval);
15927 }
15928 
15929 static int
15930 st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt)
15931 {
15932 	int rval;
15933 
15934 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
15935 
15936 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
15937 	if (rval == 0) {
15938 		un->un_pos.pmode = logical;
15939 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15940 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15941 		/*
15942 		 * Drive says invalid field in cdb.
15943 		 * Doesn't like space multiple. Position isn't lost.
15944 		 */
15945 		un->un_err_resid = cnt;
15946 		un->un_status = 0;
15947 		rval = ENOTTY;
15948 	} else {
15949 		un->un_err_resid = cnt;
15950 		un->un_pos.pmode = invalid;
15951 	}
15952 	return (rval);
15953 }
15954 
15955 #ifdef	__x86
15956 
15957 /*
15958  * release contig_mem and wake up waiting thread, if any
15959  */
15960 static void
15961 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
15962 {
15963 	mutex_enter(ST_MUTEX);
15964 
15965 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
15966 
15967 	cp->cm_next = un->un_contig_mem;
15968 	un->un_contig_mem = cp;
15969 	un->un_contig_mem_available_num++;
15970 	cv_broadcast(&un->un_contig_mem_cv);
15971 
15972 	mutex_exit(ST_MUTEX);
15973 }
15974 
15975 /*
15976  * St_get_contig_mem will return a contig_mem if there is one available
15977  * in current system. Otherwise, it will try to alloc one, if the total
15978  * number of contig_mem is within st_max_contig_mem_num.
15979  * It will sleep, if allowed by caller or return NULL, if no contig_mem
15980  * is available for now.
15981  */
15982 static struct contig_mem *
15983 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
15984 {
15985 	size_t rlen;
15986 	struct contig_mem *cp = NULL;
15987 	ddi_acc_handle_t acc_hdl;
15988 	caddr_t addr;
15989 	int big_enough = 0;
15990 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
15991 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
15992 
15993 	/* Try to get one available contig_mem */
15994 	mutex_enter(ST_MUTEX);
15995 
15996 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
15997 
15998 	if (un->un_contig_mem_available_num > 0) {
15999 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16000 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
16001 		/*
16002 		 * we failed to get one. we're going to
16003 		 * alloc one more contig_mem for this I/O
16004 		 */
16005 		mutex_exit(ST_MUTEX);
16006 		cp = (struct contig_mem *)kmem_zalloc(
16007 		    sizeof (struct contig_mem) + biosize(),
16008 		    alloc_flags);
16009 		if (cp == NULL) {
16010 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16011 			    "alloc contig_mem failure\n");
16012 			return (NULL); /* cannot get one */
16013 		}
16014 		cp->cm_bp = (struct buf *)
16015 		    (((caddr_t)cp) + sizeof (struct contig_mem));
16016 		bioinit(cp->cm_bp);
16017 		mutex_enter(ST_MUTEX);
16018 		un->un_contig_mem_total_num++; /* one more available */
16019 	} else {
16020 		/*
16021 		 * we failed to get one and we're NOT allowed to
16022 		 * alloc more contig_mem
16023 		 */
16024 		if (alloc_flags == KM_SLEEP) {
16025 			while (un->un_contig_mem_available_num <= 0) {
16026 				cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16027 			}
16028 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16029 		} else {
16030 			mutex_exit(ST_MUTEX);
16031 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16032 			    "alloc contig_mem failure\n");
16033 			return (NULL); /* cannot get one */
16034 		}
16035 	}
16036 	mutex_exit(ST_MUTEX);
16037 
16038 	/* We need to check if this block of mem is big enough for this I/O */
16039 	if (cp->cm_len < len) {
16040 		/* not big enough, need to alloc a new one */
16041 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
16042 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
16043 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
16044 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16045 			    "alloc contig_mem failure: not enough mem\n");
16046 			st_release_contig_mem(un, cp);
16047 			cp = NULL;
16048 		} else {
16049 			if (cp->cm_addr) {
16050 				/* release previous one before attach new one */
16051 				ddi_dma_mem_free(&cp->cm_acc_hdl);
16052 			}
16053 			mutex_enter(ST_MUTEX);
16054 			un->un_max_contig_mem_len =
16055 			    un->un_max_contig_mem_len >= len ?
16056 			    un->un_max_contig_mem_len : len;
16057 			mutex_exit(ST_MUTEX);
16058 
16059 			/* attach new mem to this cp */
16060 			cp->cm_addr = addr;
16061 			cp->cm_acc_hdl = acc_hdl;
16062 			cp->cm_len = len;
16063 
16064 			goto alloc_ok; /* get one usable cp */
16065 		}
16066 	} else {
16067 		goto alloc_ok; /* get one usable cp */
16068 	}
16069 
16070 	/* cannot find/alloc a usable cp, when we get here */
16071 
16072 	mutex_enter(ST_MUTEX);
16073 	if ((un->un_max_contig_mem_len < len) ||
16074 	    (alloc_flags != KM_SLEEP)) {
16075 		mutex_exit(ST_MUTEX);
16076 		return (NULL);
16077 	}
16078 
16079 	/*
16080 	 * we're allowed to sleep, and there is one big enough
16081 	 * contig mem in the system, which is currently in use,
16082 	 * wait for it...
16083 	 */
16084 	big_enough = 1;
16085 	do {
16086 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16087 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16088 	} while (cp == NULL);
16089 	mutex_exit(ST_MUTEX);
16090 
16091 	/* we get the big enough contig mem, finally */
16092 
16093 alloc_ok:
16094 	/* init bp attached to this cp */
16095 	bioreset(cp->cm_bp);
16096 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
16097 	cp->cm_bp->b_private = (void *)cp;
16098 
16099 	return (cp);
16100 }
16101 
16102 /*
16103  * this is the biodone func for the bp used in big block I/O
16104  */
16105 static int
16106 st_bigblk_xfer_done(struct buf *bp)
16107 {
16108 	struct contig_mem *cp;
16109 	struct buf *orig_bp;
16110 	int ioerr;
16111 	struct scsi_tape *un;
16112 
16113 	/* sanity check */
16114 	if (bp == NULL) {
16115 		return (DDI_FAILURE);
16116 	}
16117 
16118 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16119 	if (un == NULL) {
16120 		return (DDI_FAILURE);
16121 	}
16122 
16123 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
16124 
16125 	cp = (struct contig_mem *)bp->b_private;
16126 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
16127 	cp->cm_bp = bp;
16128 
16129 	/* special handling for special I/O */
16130 	if (cp->cm_use_sbuf) {
16131 #ifndef __lock_lint
16132 		ASSERT(un->un_sbuf_busy);
16133 #endif
16134 		un->un_sbufp = orig_bp;
16135 		cp->cm_use_sbuf = 0;
16136 	}
16137 
16138 	orig_bp->b_resid = bp->b_resid;
16139 	ioerr = geterror(bp);
16140 	if (ioerr != 0) {
16141 		bioerror(orig_bp, ioerr);
16142 	} else if (orig_bp->b_flags & B_READ) {
16143 		/* copy data back to original bp */
16144 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
16145 		    bp->b_bcount - bp->b_resid);
16146 	}
16147 
16148 	st_release_contig_mem(un, cp);
16149 
16150 	biodone(orig_bp);
16151 
16152 	return (DDI_SUCCESS);
16153 }
16154 
16155 /*
16156  * We use this func to replace original bp that may not be able to do I/O
16157  * in big block size with one that can
16158  */
16159 static struct buf *
16160 st_get_bigblk_bp(struct buf *bp)
16161 {
16162 	struct contig_mem *cp;
16163 	struct scsi_tape *un;
16164 	struct buf *cont_bp;
16165 
16166 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16167 	if (un == NULL) {
16168 		return (bp);
16169 	}
16170 
16171 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
16172 
16173 	/* try to get one contig_mem */
16174 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
16175 	if (!cp) {
16176 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
16177 		    "Cannot alloc contig buf for I/O for %lu blk size",
16178 		    bp->b_bcount);
16179 		return (bp);
16180 	}
16181 	cont_bp = cp->cm_bp;
16182 	cp->cm_bp = bp;
16183 
16184 	/* make sure that we "are" using un_sbufp for special I/O */
16185 	if (bp == un->un_sbufp) {
16186 #ifndef __lock_lint
16187 		ASSERT(un->un_sbuf_busy);
16188 #endif
16189 		un->un_sbufp = cont_bp;
16190 		cp->cm_use_sbuf = 1;
16191 	}
16192 
16193 	/* clone bp */
16194 	cont_bp->b_bcount = bp->b_bcount;
16195 	cont_bp->b_resid = bp->b_resid;
16196 	cont_bp->b_iodone = st_bigblk_xfer_done;
16197 	cont_bp->b_file = bp->b_file;
16198 	cont_bp->b_offset = bp->b_offset;
16199 	cont_bp->b_dip = bp->b_dip;
16200 	cont_bp->b_error = 0;
16201 	cont_bp->b_proc = NULL;
16202 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
16203 	cont_bp->b_shadow = NULL;
16204 	cont_bp->b_pages = NULL;
16205 	cont_bp->b_edev = bp->b_edev;
16206 	cont_bp->b_dev = bp->b_dev;
16207 	cont_bp->b_lblkno = bp->b_lblkno;
16208 	cont_bp->b_forw = bp->b_forw;
16209 	cont_bp->b_back = bp->b_back;
16210 	cont_bp->av_forw = bp->av_forw;
16211 	cont_bp->av_back = bp->av_back;
16212 	cont_bp->b_bufsize = bp->b_bufsize;
16213 
16214 	/* get data in original bp */
16215 	if (bp->b_flags & B_WRITE) {
16216 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
16217 	}
16218 
16219 	return (cont_bp);
16220 }
16221 #else
16222 #ifdef __lock_lint
16223 static int
16224 st_bigblk_xfer_done(struct buf *bp)
16225 {
16226 	return (0);
16227 }
16228 #endif
16229 #endif
16230 
16231 static const char *eof_status[] =
16232 {
16233 	"NO_EOF",
16234 	"EOF_PENDING",
16235 	"EOF",
16236 	"EOT_PENDING",
16237 	"EOT",
16238 	"EOM",
16239 	"AFTER_EOM"
16240 };
16241 static const char *mode[] = {
16242 	"invalid",
16243 	"legacy",
16244 	"logical"
16245 };
16246 
16247 static void
16248 st_print_position(dev_info_t *dev, char *label, uint_t level,
16249 const char *comment, tapepos_t *pos)
16250 {
16251 	ST_FUNC(dev, st_print_position);
16252 
16253 	scsi_log(dev, label, level,
16254 	    "%s Position data:\n", comment);
16255 	scsi_log(dev, label, CE_CONT,
16256 	    "Positioning mode = %s", mode[pos->pmode]);
16257 	scsi_log(dev, label, CE_CONT,
16258 	    "End Of File/Tape = %s", eof_status[pos->eof]);
16259 	scsi_log(dev, label, CE_CONT,
16260 	    "File Number      = 0x%x", pos->fileno);
16261 	scsi_log(dev, label, CE_CONT,
16262 	    "Block Number     = 0x%x", pos->blkno);
16263 	scsi_log(dev, label, CE_CONT,
16264 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
16265 	scsi_log(dev, label, CE_CONT,
16266 	    "Partition Number = 0x%x", pos->partition);
16267 }
16268 static int
16269 st_check_if_media_changed(struct scsi_tape *un, caddr_t data, int size)
16270 {
16271 
16272 	int result = 0;
16273 	int i;
16274 	ST_FUNC(ST_DEVINFO, st_check_if_media_changed);
16275 
16276 	/*
16277 	 * find non alpha numeric working from the end.
16278 	 */
16279 	for (i = size - 1; i >= 0; i--) {
16280 		if (ISALNUM(data[i]) == 0 || data[i] == ' ') {
16281 			data[i] = 0;
16282 			size = i;
16283 		}
16284 	}
16285 
16286 	if (size == 1) {
16287 		/*
16288 		 * Drive seems to think its returning useful data
16289 		 * but it looks like all junk
16290 		 */
16291 		return (result);
16292 	}
16293 
16294 	size++;
16295 
16296 	/*
16297 	 * Actually got a valid serial number.
16298 	 * If never stored one before alloc space for it.
16299 	 */
16300 	if (un->un_media_id_len == 0) {
16301 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16302 		un->un_media_id_len = size;
16303 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16304 		un->un_media_id[min(size, strlen(data))] = 0;
16305 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16306 		    "Found Media Id %s length = %d\n", un->un_media_id, size);
16307 	} else if (size > un->un_media_id_len) {
16308 		if (strncmp(un->un_media_id, data, size) != 0) {
16309 			result = ESPIPE;
16310 		}
16311 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16312 		    "Longer Media Id old ID:%s new ID:%s\n",
16313 		    un->un_media_id, data);
16314 		kmem_free(un->un_media_id, un->un_media_id_len);
16315 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16316 		un->un_media_id_len = size;
16317 		(void) strncpy(un->un_media_id, data, size);
16318 		un->un_media_id[size] = 0;
16319 	} else if (strncmp(data, un->un_media_id,
16320 	    min(size, un->un_media_id_len)) != 0) {
16321 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16322 		    "Old Media Id %s length = %d New %s length = %d\n",
16323 		    un->un_media_id, un->un_media_id_len, data, size);
16324 		bzero(un->un_media_id, un->un_media_id_len);
16325 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16326 		un->un_media_id[min(size, strlen(data))] = 0;
16327 		result = ESPIPE;
16328 	} else {
16329 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
16330 		    "Media Id still %s\n", un->un_media_id);
16331 	}
16332 
16333 	ASSERT(strlen(un->un_media_id) <= size);
16334 
16335 	return (result);
16336 }
16337 #define	ID_SIZE 32
16338 typedef struct
16339 {
16340 	uchar_t avilable_data0;
16341 	uchar_t avilable_data1;
16342 	uchar_t avilable_data2;
16343 	uchar_t avilable_data3;
16344 	uchar_t attribute_msb;
16345 	uchar_t attribute_lsb;
16346 #ifdef _BIT_FIELDS_LTOH
16347 	uchar_t format		: 2,
16348 				: 5,
16349 		read_only	: 1;
16350 #else
16351 	uchar_t read_only	: 1,
16352 				: 5,
16353 		format		: 2;
16354 #endif
16355 	uchar_t attribute_len_msb;
16356 	uchar_t attribute_len_lsb;
16357 }attribute_header;
16358 
16359 typedef struct {
16360 	attribute_header header;
16361 	char data[1];
16362 }mam_attribute;
16363 
16364 static int
16365 st_handle_hex_media_id(struct scsi_tape *un, void *pnt, int size)
16366 {
16367 	int result;
16368 	int newsize = (size << 1) + 3; /* extra for leading 0x and null term */
16369 	int i;
16370 	uchar_t byte;
16371 	char *format;
16372 	uchar_t *data = (uchar_t *)pnt;
16373 	char *buf = kmem_alloc(newsize, KM_SLEEP);
16374 
16375 	ST_FUNC(ST_DEVINFO, st_handle_hex_media_id);
16376 
16377 	(void) sprintf(buf, "0x");
16378 	for (i = 0; i < size; i++) {
16379 		byte = data[i];
16380 		if (byte < 0x10)
16381 			format = "0%x";
16382 		else
16383 			format = "%x";
16384 		(void) sprintf(&buf[(int)strlen(buf)], format, byte);
16385 	}
16386 	result = st_check_if_media_changed(un, buf, newsize);
16387 
16388 	kmem_free(buf, newsize);
16389 
16390 	return (result);
16391 }
16392 
16393 
16394 static int
16395 st_get_media_id_via_read_attribute(struct scsi_tape *un, ubufunc_t bufunc)
16396 {
16397 	int result;
16398 	mam_attribute *buffer;
16399 	int size;
16400 	int newsize;
16401 
16402 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_read_attribute);
16403 	size = sizeof (attribute_header) + max(un->un_media_id_len, ID_SIZE);
16404 again:
16405 	buffer = kmem_zalloc(size, KM_SLEEP);
16406 	result = st_read_attributes(un, 0x0401, buffer, size, bufunc);
16407 	if (result == 0) {
16408 
16409 		newsize = (buffer->header.attribute_len_msb << 8) |
16410 		    buffer->header.attribute_len_lsb;
16411 
16412 		if (newsize + sizeof (attribute_header) > size) {
16413 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
16414 			    "resizing read attribute data from %d to %d format"
16415 			    " %d\n", size, (int)sizeof (attribute_header) +
16416 			    newsize, buffer->header.format);
16417 			kmem_free(buffer, size);
16418 			size = newsize + sizeof (attribute_header);
16419 			goto again;
16420 		}
16421 
16422 		un->un_media_id_method = st_get_media_id_via_read_attribute;
16423 		if (buffer->header.format == 0) {
16424 			result =
16425 			    st_handle_hex_media_id(un, buffer->data, newsize);
16426 		} else {
16427 			result = st_check_if_media_changed(un, buffer->data,
16428 			    newsize);
16429 		}
16430 	} else if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
16431 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
16432 		    "Read Attribute Command for Media Identification is not "
16433 		    "supported on the HBA that this drive is attached to.");
16434 		result = ENOTTY;
16435 	}
16436 
16437 	kmem_free(buffer, size);
16438 	un->un_status = 0;
16439 
16440 	return (result);
16441 }
16442 
16443 
16444 static int
16445 st_get_media_id_via_media_serial_cmd(struct scsi_tape *un, ubufunc_t bufunc)
16446 {
16447 	char cdb[CDB_GROUP5];
16448 	struct uscsi_cmd *ucmd;
16449 	struct scsi_extended_sense sense;
16450 	int rval;
16451 	int size = max(un->un_media_id_len, ID_SIZE);
16452 	caddr_t buf;
16453 
16454 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_media_serial_cmd);
16455 
16456 	if (un->un_sd->sd_inq->inq_ansi < 3) {
16457 		return (ENOTTY);
16458 	}
16459 
16460 	ucmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
16461 upsize:
16462 	buf = kmem_alloc(size, KM_SLEEP);
16463 
16464 	cdb[0] = (char)SCMD_SVC_ACTION_IN_G5;
16465 	cdb[1] = SSVC_ACTION_READ_MEDIA_SERIAL;
16466 	cdb[2] = 0;
16467 	cdb[3] = 0;
16468 	cdb[4] = 0;
16469 	cdb[5] = 0;
16470 	cdb[6] = (char)(size >> 24);
16471 	cdb[7] = (char)(size >> 16);
16472 	cdb[8] = (char)(size >> 8);
16473 	cdb[9] = (char)(size);
16474 	cdb[10] = 0;
16475 	cdb[11] = 0;
16476 
16477 	ucmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
16478 	ucmd->uscsi_timeout = un->un_dp->non_motion_timeout;
16479 	ucmd->uscsi_cdb = &cdb[0];
16480 	ucmd->uscsi_cdblen = sizeof (cdb);
16481 	ucmd->uscsi_bufaddr = buf;
16482 	ucmd->uscsi_buflen = size;
16483 	ucmd->uscsi_rqbuf = (caddr_t)&sense;
16484 	ucmd->uscsi_rqlen = sizeof (sense);
16485 
16486 	rval = bufunc(un, ucmd, FKIOCTL);
16487 
16488 	if (rval || ucmd->uscsi_status != 0) {
16489 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16490 		    "media serial command returned %d scsi_status %d"
16491 		    " rqstatus %d", rval, ucmd->uscsi_status,
16492 		    ucmd->uscsi_rqstatus);
16493 		/*
16494 		 * If this returns invalid operation code don't try again.
16495 		 */
16496 		if (sense.es_key == KEY_ILLEGAL_REQUEST &&
16497 		    sense.es_add_code == 0x20) {
16498 			rval = ENOTTY;
16499 		} else if (rval == 0) {
16500 			rval = EIO;
16501 		}
16502 		un->un_status = 0;
16503 	} else {
16504 		int act_size;
16505 
16506 		/*
16507 		 * get reported size.
16508 		 */
16509 		act_size = (int)buf[3] | (int)(buf[2] << 8) |
16510 		    (int)(buf[1] << 16) | (int)(buf[0] << 24);
16511 
16512 		/* documentation says mod 4. */
16513 		while (act_size & 3) {
16514 			act_size++;
16515 		}
16516 
16517 		/*
16518 		 * If reported size is larger that we our buffer.
16519 		 * Free the old one and allocate one that is larger
16520 		 * enough and re-issuse the command.
16521 		 */
16522 		if (act_size + 4 > size) {
16523 			kmem_free(buf, size);
16524 			size = act_size + 4;
16525 			goto upsize;
16526 		}
16527 
16528 		if (act_size == 0) {
16529 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16530 			    "media serial number is not available");
16531 			un->un_status = 0;
16532 			rval = 0;
16533 		} else {
16534 			/*
16535 			 * set data pointer to point to the start
16536 			 * of that serial number.
16537 			 */
16538 			un->un_media_id_method =
16539 			    st_get_media_id_via_media_serial_cmd;
16540 			rval =
16541 			    st_check_if_media_changed(un, &buf[4], act_size);
16542 		}
16543 	}
16544 
16545 	kmem_free(ucmd, sizeof (struct uscsi_cmd));
16546 	kmem_free(buf, size);
16547 
16548 	return (rval);
16549 }
16550 
16551 
16552 /* ARGSUSED */
16553 static int
16554 st_bogus_media_id(struct scsi_tape *un, ubufunc_t bufunc)
16555 {
16556 	ST_FUNC(ST_DEVINFO, st_bogus_media_id);
16557 
16558 	ASSERT(un->un_media_id == NULL || un->un_media_id == bogusID);
16559 	ASSERT(un->un_media_id_len == 0);
16560 	un->un_media_id = (char *)bogusID;
16561 	un->un_media_id_len = 0;
16562 	return (0);
16563 }
16564 
16565 typedef int (*media_chk_function)(struct scsi_tape *, ubufunc_t bufunc);
16566 
16567 media_chk_function media_chk_functions[] = {
16568 	st_get_media_id_via_media_serial_cmd,
16569 	st_get_media_id_via_read_attribute,
16570 	st_bogus_media_id
16571 };
16572 
16573 static int
16574 st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc)
16575 {
16576 	int result = 0;
16577 	int i;
16578 
16579 	ST_FUNC(ST_DEVINFO, st_get_media_identification);
16580 
16581 	for (i = 0; i < ST_NUM_MEMBERS(media_chk_functions); i++) {
16582 		if (result == ENOTTY) {
16583 			/*
16584 			 * Last operation type not supported by this device.
16585 			 * Make so next time it doesn`t do that again.
16586 			 */
16587 			un->un_media_id_method = media_chk_functions[i];
16588 		} else if (un->un_media_id_method != media_chk_functions[i] &&
16589 		    un->un_media_id_method != st_get_media_identification) {
16590 			continue;
16591 		}
16592 		result = media_chk_functions[i](un, bufunc);
16593 		/*
16594 		 * If result indicates the function was successful or
16595 		 * that the media is not the same as last known, break.
16596 		 */
16597 		if (result == 0 || result == ESPIPE) {
16598 			break;
16599 		}
16600 	}
16601 
16602 	return (result);
16603 }
16604 
16605 static errstate
16606 st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
16607     errstate onentry)
16608 {
16609 
16610 	int ret;
16611 	st_err_info *errinfo;
16612 	recov_info *ri = (recov_info *)pkt->pkt_private;
16613 
16614 	ST_FUNC(ST_DEVINFO, st_command_recovery);
16615 
16616 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16617 
16618 	ASSERT(un->un_recov_buf_busy == 0);
16619 
16620 	/*
16621 	 * Don't try and recover a reset that this device sent.
16622 	 */
16623 	if (un->un_rsvd_status & ST_INITIATED_RESET &&
16624 	    onentry == DEVICE_RESET) {
16625 		return (COMMAND_DONE_ERROR);
16626 	}
16627 
16628 	/*
16629 	 * See if expected position was passed with scsi_pkt.
16630 	 */
16631 	if (ri->privatelen == sizeof (recov_info)) {
16632 
16633 		/*
16634 		 * Not for this command.
16635 		 */
16636 		if (ri->cmd_attrib->do_not_recover) {
16637 			return (COMMAND_DONE_ERROR);
16638 		}
16639 
16640 		/*
16641 		 * Create structure to hold all error state info.
16642 		 */
16643 		errinfo = kmem_zalloc(ST_ERR_INFO_SIZE, KM_SLEEP);
16644 		errinfo->ei_error_type = onentry;
16645 		errinfo->ei_failing_bp = ri->cmd_bp;
16646 		COPY_POS(&errinfo->ei_expected_pos, &ri->pos);
16647 	} else {
16648 		/* disabled */
16649 		return (COMMAND_DONE_ERROR);
16650 	}
16651 
16652 	bcopy(pkt, &errinfo->ei_failed_pkt, scsi_pkt_size());
16653 	bcopy(pkt->pkt_scbp, &errinfo->ei_failing_status, SECMDS_STATUS_SIZE);
16654 	ret = ddi_taskq_dispatch(un->un_recov_taskq, st_recover, errinfo,
16655 	    DDI_NOSLEEP);
16656 	ASSERT(ret == DDI_SUCCESS);
16657 	if (ret != DDI_SUCCESS) {
16658 		kmem_free(errinfo, ST_ERR_INFO_SIZE);
16659 		return (COMMAND_DONE_ERROR);
16660 	}
16661 	return (JUST_RETURN); /* release calling thread */
16662 }
16663 
16664 
16665 static void
16666 st_recov_ret(struct scsi_tape *un, st_err_info *errinfo, errstate err)
16667 {
16668 	int error_number;
16669 	buf_t *bp;
16670 
16671 
16672 	ST_FUNC(ST_DEVINFO, st_recov_ret);
16673 
16674 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16675 #if !defined(lint)
16676 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
16677 #endif
16678 
16679 	bp = errinfo->ei_failing_bp;
16680 	kmem_free(errinfo, ST_ERR_INFO_SIZE);
16681 
16682 	switch (err) {
16683 	case JUST_RETURN:
16684 		mutex_exit(&un->un_sd->sd_mutex);
16685 		return;
16686 
16687 	case COMMAND_DONE:
16688 	case COMMAND_DONE_ERROR_RECOVERED:
16689 		ST_DO_KSTATS(bp, kstat_runq_exit);
16690 		error_number = 0;
16691 		break;
16692 
16693 	default:
16694 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16695 		    "st_recov_ret with unhandled errstat %d\n", err);
16696 		/* FALLTHROUGH */
16697 	case COMMAND_DONE_ERROR:
16698 	case COMMAND_DONE_EACCES:
16699 		ST_DO_KSTATS(bp, kstat_waitq_exit);
16700 		ST_DO_ERRSTATS(un, st_transerrs);
16701 		error_number = EIO;
16702 		st_set_pe_flag(un);
16703 		break;
16704 
16705 	}
16706 
16707 	st_bioerror(bp, error_number);
16708 	st_done_and_mutex_exit(un, bp);
16709 }
16710 
16711 
16712 static void
16713 st_recover(void *arg)
16714 {
16715 	st_err_info *const errinfo = (st_err_info *)arg;
16716 	uchar_t com = errinfo->ei_failed_pkt.pkt_cdbp[0];
16717 	struct scsi_tape *un;
16718 	tapepos_t cur_pos;
16719 	int rval;
16720 	errstate status = COMMAND_DONE_ERROR;
16721 	recov_info *rcv;
16722 	buf_t *bp;
16723 
16724 
16725 	rcv = errinfo->ei_failed_pkt.pkt_private;
16726 	ASSERT(rcv->privatelen == sizeof (recov_info));
16727 	bp = rcv->cmd_bp;
16728 
16729 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16730 
16731 	ASSERT(un != NULL);
16732 
16733 	mutex_enter(ST_MUTEX);
16734 
16735 	ST_FUNC(ST_DEVINFO, st_recover);
16736 
16737 	ST_CDB(ST_DEVINFO, "Recovering command",
16738 	    (caddr_t)errinfo->ei_failed_pkt.pkt_cdbp);
16739 	ST_SENSE(ST_DEVINFO, "sense status for failed command",
16740 	    (caddr_t)&errinfo->ei_failing_status,
16741 	    sizeof (struct scsi_arq_status));
16742 	ST_POS(ST_DEVINFO, rcv->cmd_attrib->recov_pos_type == POS_STARTING ?
16743 	    "starting position for recovery command" :
16744 	    "expected position for recovery command",
16745 	    &errinfo->ei_expected_pos);
16746 
16747 	rval = st_test_path_to_device(un);
16748 
16749 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16750 	    "st_recover called with %s, TUR returned %d\n",
16751 	    errstatenames[errinfo->ei_error_type], rval);
16752 	/*
16753 	 * If the drive responed to the TUR lets try and get it to sync
16754 	 * any data it might have in the buffer.
16755 	 */
16756 	if (rval == 0 && rcv->cmd_attrib->chg_tape_data) {
16757 		(void) st_rcmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
16758 	}
16759 	switch (errinfo->ei_error_type) {
16760 	case ATTEMPT_RETRY:
16761 	case COMMAND_TIMEOUT:
16762 	case DEVICE_RESET:
16763 	case PATH_FAILED:
16764 		/*
16765 		 * For now if we can't talk to the device we are done.
16766 		 * If the drive is reserved we can try to get it back.
16767 		 */
16768 		if (rval != 0 && rval != EACCES) {
16769 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16770 			return;
16771 		}
16772 
16773 		/*
16774 		 * If scsi II lost reserve try and get it back.
16775 		 */
16776 		if ((((un->un_rsvd_status &
16777 		    (ST_LOST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
16778 		    ST_LOST_RESERVE)) &&
16779 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] != SCMD_RELEASE)) {
16780 			rval = st_reserve_release(un, ST_RESERVE,
16781 			    st_uscsi_rcmd);
16782 			if (rval != 0) {
16783 				if (st_take_ownership(un, st_uscsi_rcmd) != 0) {
16784 					st_recov_ret(un, errinfo,
16785 					    COMMAND_DONE_EACCES);
16786 					return;
16787 				}
16788 			}
16789 			un->un_rsvd_status |= ST_RESERVE;
16790 			un->un_rsvd_status &= ~(ST_RELEASE | ST_LOST_RESERVE |
16791 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
16792 		}
16793 		rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16794 		if (rval) {
16795 			rval = st_gen_mode_select(un, st_uscsi_rcmd,
16796 			    un->un_mspl, sizeof (struct seq_mode));
16797 		}
16798 		if (rval) {
16799 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16800 			return;
16801 		}
16802 		break;
16803 	case DEVICE_TAMPER:
16804 		/*
16805 		 * Check if the ASC/ASCQ says mode data has changed.
16806 		 */
16807 		if ((errinfo->ei_failing_status.sts_sensedata.es_add_code ==
16808 		    0x2a) &&
16809 		    (errinfo->ei_failing_status.sts_sensedata.es_qual_code ==
16810 		    0x01)) {
16811 			/*
16812 			 * See if mode sense changed.
16813 			 */
16814 			rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16815 			if (rval) {
16816 				/*
16817 				 * If so change it back.
16818 				 */
16819 				rval = st_gen_mode_select(un, st_uscsi_rcmd,
16820 				    un->un_mspl, sizeof (struct seq_mode));
16821 			}
16822 			if (rval) {
16823 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16824 				return;
16825 			}
16826 		}
16827 		/*
16828 		 * if we have a media id and its not bogus.
16829 		 * Check to see if it the same.
16830 		 */
16831 		if (un->un_media_id != NULL && un->un_media_id != bogusID) {
16832 			rval = st_get_media_identification(un, st_uscsi_rcmd);
16833 			if (rval == ESPIPE) {
16834 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16835 				return;
16836 			}
16837 		}
16838 		break;
16839 	default:
16840 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16841 		    "Unhandled error type %s in st_recover() 0x%x\n",
16842 		    errstatenames[errinfo->ei_error_type], com);
16843 	}
16844 
16845 	/*
16846 	 * if command is retriable retry it.
16847 	 * Special case here. The command attribute for SCMD_REQUEST_SENSE
16848 	 * does not say that it is retriable. That because if you reissue a
16849 	 * request sense and the target responds the sense data will have
16850 	 * been consumed and no long be valid. If we get a busy status on
16851 	 * request sense while the state is ST_STATE_SENSING this will
16852 	 * reissue that pkt.
16853 	 *
16854 	 * XXX If this request sense gets sent to a different port then
16855 	 * the original command that failed was sent on it will not get
16856 	 * valid sense data for that command.
16857 	 */
16858 	if (rcv->cmd_attrib->retriable || un->un_rqs_bp == bp) {
16859 		status = st_recover_reissue_pkt(un, &errinfo->ei_failed_pkt);
16860 
16861 	/*
16862 	 * if drive doesn't support read position we are done
16863 	 */
16864 	} else if (un->un_read_pos_type == NO_POS) {
16865 		status = COMMAND_DONE_ERROR;
16866 	/*
16867 	 * If this command results in a changed tape position,
16868 	 * lets see where we are.
16869 	 */
16870 	} else if (rcv->cmd_attrib->chg_tape_pos) {
16871 		/*
16872 		 * XXX May be a reason to choose a different type here.
16873 		 * Long format has file position information.
16874 		 * Short and Extended have information about whats
16875 		 * in the buffer. St's positioning assumes in the buffer
16876 		 * to be the same as on tape.
16877 		 */
16878 		rval = st_compare_expected_position(un, errinfo,
16879 		    rcv->cmd_attrib, &cur_pos);
16880 		if (rval == 0) {
16881 			status = COMMAND_DONE;
16882 		} else if (rval == EAGAIN) {
16883 			status = st_recover_reissue_pkt(un,
16884 			    &errinfo->ei_failed_pkt);
16885 		} else {
16886 			status = COMMAND_DONE_ERROR;
16887 		}
16888 	} else {
16889 		ASSERT(0);
16890 	}
16891 
16892 	st_recov_ret(un, errinfo, status);
16893 }
16894 
16895 static void
16896 st_recov_cb(struct scsi_pkt *pkt)
16897 {
16898 	struct scsi_tape *un;
16899 	struct buf *bp;
16900 	recov_info *rcv;
16901 	errstate action = COMMAND_DONE_ERROR;
16902 	int timout = ST_TRAN_BUSY_TIMEOUT; /* short (default) timeout */
16903 
16904 	/*
16905 	 * Get the buf from the packet.
16906 	 */
16907 	rcv = pkt->pkt_private;
16908 	ASSERT(rcv->privatelen == sizeof (recov_info));
16909 	bp = rcv->cmd_bp;
16910 
16911 	/*
16912 	 * get the unit from the buf.
16913 	 */
16914 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16915 	ASSERT(un != NULL);
16916 
16917 	ST_FUNC(ST_DEVINFO, st_recov_cb);
16918 
16919 	mutex_enter(ST_MUTEX);
16920 
16921 	ASSERT(bp == un->un_recov_buf);
16922 
16923 
16924 	switch (pkt->pkt_reason) {
16925 	case CMD_CMPLT:
16926 		if (un->un_arq_enabled && pkt->pkt_state & STATE_ARQ_DONE) {
16927 			action = st_handle_autosense(un, bp, &rcv->pos);
16928 		} else  if ((SCBP(pkt)->sts_busy) ||
16929 		    (SCBP(pkt)->sts_chk) ||
16930 		    (SCBP(pkt)->sts_vu7)) {
16931 			action = st_check_error(un, pkt);
16932 		} else {
16933 			action = COMMAND_DONE;
16934 		}
16935 		break;
16936 	case CMD_TIMEOUT:
16937 		action = COMMAND_TIMEOUT;
16938 		break;
16939 	case CMD_TRAN_ERR:
16940 		action = QUE_COMMAND;
16941 		break;
16942 	default:
16943 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16944 		    "pkt_reason not handled yet %s",
16945 		    scsi_rname(pkt->pkt_reason));
16946 		action = COMMAND_DONE_ERROR;
16947 	}
16948 
16949 	/*
16950 	 * check for undetected path failover.
16951 	 */
16952 	if ((un->un_multipath) &&
16953 	    (un->un_last_path_instance != pkt->pkt_path_instance)) {
16954 		if (un->un_state > ST_STATE_OPENING) {
16955 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16956 			    "Failover detected in recovery, action is %s\n",
16957 			    errstatenames[action]);
16958 		}
16959 		un->un_last_path_instance = pkt->pkt_path_instance;
16960 	}
16961 
16962 	ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
16963 	    "Recovery call back got %s status on %s\n",
16964 	    errstatenames[action], st_print_scsi_cmd(pkt->pkt_cdbp[0]));
16965 
16966 	switch (action) {
16967 	case COMMAND_DONE:
16968 		break;
16969 
16970 	case COMMAND_DONE_EACCES:
16971 		bioerror(bp, EACCES);
16972 		break;
16973 
16974 	case COMMAND_DONE_ERROR_RECOVERED: /* XXX maybe wrong */
16975 		ASSERT(0);
16976 		break;
16977 
16978 	case COMMAND_TIMEOUT:
16979 	case COMMAND_DONE_ERROR:
16980 		bioerror(bp, EIO);
16981 		break;
16982 
16983 	case DEVICE_RESET:
16984 	case QUE_BUSY_COMMAND:
16985 	case PATH_FAILED:
16986 		/* longish timeout */
16987 		timout = ST_STATUS_BUSY_TIMEOUT;
16988 		/* FALLTHRU */
16989 	case QUE_COMMAND:
16990 	case DEVICE_TAMPER:
16991 	case ATTEMPT_RETRY:
16992 		/*
16993 		 * let st_handle_intr_busy put this bp back on waitq and make
16994 		 * checks to see if it is ok to requeue the command.
16995 		 */
16996 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
16997 
16998 		/*
16999 		 * Save the throttle before setting up the timeout
17000 		 */
17001 		if (un->un_throttle) {
17002 			un->un_last_throttle = un->un_throttle;
17003 		}
17004 		mutex_exit(ST_MUTEX);
17005 		if (st_handle_intr_busy(un, bp, timout) == 0) {
17006 			return;		/* timeout is setup again */
17007 		}
17008 		mutex_enter(ST_MUTEX);
17009 		un->un_pos.pmode = invalid;
17010 		un->un_err_resid = bp->b_resid = bp->b_bcount;
17011 		st_bioerror(bp, EIO);
17012 		st_set_pe_flag(un);
17013 		break;
17014 
17015 	default:
17016 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
17017 		    "Unhandled recovery state 0x%x\n", action);
17018 		un->un_pos.pmode = invalid;
17019 		un->un_err_resid = bp->b_resid = bp->b_bcount;
17020 		st_bioerror(bp, EIO);
17021 		st_set_pe_flag(un);
17022 		break;
17023 	}
17024 
17025 	st_done_and_mutex_exit(un, bp);
17026 }
17027 
17028 static int
17029 st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait)
17030 {
17031 	struct buf *bp;
17032 	int err;
17033 
17034 	ST_FUNC(ST_DEVINFO, st_rcmd);
17035 
17036 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
17037 	    "st_rcmd(un = 0x%p, com = 0x%x, count = %"PRIx64", wait = %d)\n",
17038 	    (void *)un, com, count, wait);
17039 
17040 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
17041 	ASSERT(mutex_owned(ST_MUTEX));
17042 
17043 #ifdef STDEBUG
17044 	if ((st_debug & 0x7)) {
17045 		st_debug_cmds(un, com, count, wait);
17046 	}
17047 #endif
17048 
17049 	while (un->un_recov_buf_busy)
17050 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17051 	un->un_recov_buf_busy = 1;
17052 
17053 	bp = un->un_recov_buf;
17054 	bzero(bp, sizeof (buf_t));
17055 
17056 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
17057 
17058 	err = st_setup_cmd(un, bp, com, count);
17059 
17060 	un->un_recov_buf_busy = 0;
17061 
17062 	cv_signal(&un->un_recov_buf_cv);
17063 
17064 	return (err);
17065 }
17066 
17067 /* args used */
17068 static int
17069 st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
17070 {
17071 	int rval;
17072 	buf_t *bp;
17073 
17074 	ST_FUNC(ST_DEVINFO, st_uscsi_rcmd);
17075 	ASSERT(flag == FKIOCTL);
17076 
17077 	/*
17078 	 * Get buffer resources...
17079 	 */
17080 	while (un->un_recov_buf_busy)
17081 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17082 	un->un_recov_buf_busy = 1;
17083 
17084 	bp = un->un_recov_buf;
17085 	bzero(bp, sizeof (buf_t));
17086 
17087 	bp->b_forw = (struct buf *)(uintptr_t)ucmd->uscsi_cdb[0];
17088 	bp->b_back = (struct buf *)ucmd;
17089 
17090 	mutex_exit(ST_MUTEX);
17091 	rval = scsi_uscsi_handle_cmd(un->un_dev, UIO_SYSSPACE, ucmd,
17092 	    st_strategy, bp, NULL);
17093 	mutex_enter(ST_MUTEX);
17094 
17095 	ucmd->uscsi_resid = bp->b_resid;
17096 
17097 	/*
17098 	 * Free resources
17099 	 */
17100 	un->un_recov_buf_busy = 0;
17101 	cv_signal(&un->un_recov_buf_cv);
17102 
17103 	return (rval);
17104 }
17105 
17106 /*
17107  * Add data to scsi_pkt to help know what to do if the command fails.
17108  */
17109 static void
17110 st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
17111     struct scsi_pkt *pkt)
17112 {
17113 	uint64_t count;
17114 	recov_info *rinfo = (recov_info *)pkt->pkt_private;
17115 
17116 	ST_FUNC(ST_DEVINFO, st_add_recovery_info_to_pkt);
17117 
17118 	ASSERT(rinfo->privatelen == sizeof (pkt_info) ||
17119 	    rinfo->privatelen == sizeof (recov_info));
17120 
17121 	SET_BP_PKT(bp, pkt);
17122 	rinfo->cmd_bp = bp;
17123 
17124 	if (rinfo->privatelen != sizeof (recov_info)) {
17125 		return;
17126 	}
17127 
17128 	rinfo->cmd_bp = bp;
17129 
17130 	rinfo->cmd_attrib = NULL;
17131 
17132 	/*
17133 	 * lookup the command attributes and add them to the recovery info.
17134 	 */
17135 	rinfo->cmd_attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
17136 
17137 	ASSERT(rinfo->cmd_attrib);
17138 
17139 	/*
17140 	 * For commands that there is no way to figure the expected position
17141 	 * once completed, we save the position the command was started from
17142 	 * so that if they fail we can position back and try again.
17143 	 * This has already been done in st_cmd() or st_iscsi_cmd().
17144 	 */
17145 	if (rinfo->cmd_attrib->recov_pos_type == POS_STARTING) {
17146 		/* save current position as the starting position. */
17147 		COPY_POS(&rinfo->pos, &un->un_pos);
17148 		un->un_running.pmode = invalid;
17149 		return;
17150 	}
17151 
17152 	/*
17153 	 * Don't want to update the running position for recovery.
17154 	 */
17155 	if (bp == un->un_recov_buf) {
17156 		rinfo->pos.pmode = un->un_running.pmode;
17157 		return;
17158 	}
17159 	/*
17160 	 * If running position is invalid copy the current position.
17161 	 * Running being set invalid means we are not in a read, write
17162 	 * or write filemark sequence.
17163 	 * We'll copy the current position and start from there.
17164 	 */
17165 	if (un->un_running.pmode == invalid) {
17166 		COPY_POS(&un->un_running, &un->un_pos);
17167 		COPY_POS(&rinfo->pos, &un->un_running);
17168 	} else {
17169 		COPY_POS(&rinfo->pos, &un->un_running);
17170 		if (rinfo->pos.pmode == legacy) {
17171 			/*
17172 			 * Always should be more logical blocks then
17173 			 * data blocks and files marks.
17174 			 */
17175 			ASSERT((rinfo->pos.blkno >= 0) ?
17176 			    rinfo->pos.lgclblkno >=
17177 			    (rinfo->pos.blkno + rinfo->pos.fileno) : 1);
17178 		}
17179 	}
17180 
17181 	/*
17182 	 * If the command is not expected to change the drive position
17183 	 * then the running position should be the expected position.
17184 	 */
17185 	if (rinfo->cmd_attrib->chg_tape_pos == 0) {
17186 		ASSERT(rinfo->cmd_attrib->chg_tape_direction == DIR_NONE);
17187 		return;
17188 	}
17189 
17190 	if (rinfo->cmd_attrib->explicit) {
17191 		ASSERT(rinfo->pos.pmode != invalid);
17192 		ASSERT(rinfo->cmd_attrib->get_cnt);
17193 		count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17194 		/*
17195 		 * This is a user generated CDB.
17196 		 */
17197 		if (bp == un->un_sbufp) {
17198 			uint64_t lbn;
17199 
17200 			lbn = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17201 
17202 			/*
17203 			 * See if this CDB will generate a locate or change
17204 			 * partition.
17205 			 */
17206 			if ((lbn != un->un_running.lgclblkno) ||
17207 			    (pkt->pkt_cdbp[3] != un->un_running.partition)) {
17208 				rinfo->pos.partition = pkt->pkt_cdbp[3];
17209 				rinfo->pos.pmode = logical;
17210 				rinfo->pos.lgclblkno = lbn;
17211 				un->un_running.partition = pkt->pkt_cdbp[3];
17212 				un->un_running.pmode = logical;
17213 				un->un_running.lgclblkno = lbn;
17214 			}
17215 		} else {
17216 			uint64_t lbn = un->un_running.lgclblkno;
17217 
17218 			pkt->pkt_cdbp[3]  = (uchar_t)un->un_running.partition;
17219 
17220 			pkt->pkt_cdbp[4]  = (uchar_t)(lbn >> 56);
17221 			pkt->pkt_cdbp[5]  = (uchar_t)(lbn >> 48);
17222 			pkt->pkt_cdbp[6]  = (uchar_t)(lbn >> 40);
17223 			pkt->pkt_cdbp[7]  = (uchar_t)(lbn >> 32);
17224 			pkt->pkt_cdbp[8]  = (uchar_t)(lbn >> 24);
17225 			pkt->pkt_cdbp[9]  = (uchar_t)(lbn >> 16);
17226 			pkt->pkt_cdbp[10] = (uchar_t)(lbn >> 8);
17227 			pkt->pkt_cdbp[11] = (uchar_t)(lbn);
17228 		}
17229 		rinfo->pos.lgclblkno += count;
17230 		rinfo->pos.blkno += count;
17231 		un->un_running.lgclblkno += count;
17232 		return;
17233 	}
17234 
17235 	if (rinfo->cmd_attrib->chg_tape_pos) {
17236 
17237 		/* should not have got an invalid position from running. */
17238 		if (un->un_mediastate == MTIO_INSERTED) {
17239 			ASSERT(rinfo->pos.pmode != invalid);
17240 		}
17241 
17242 		/* should have either a get count or or get lba function */
17243 		ASSERT(rinfo->cmd_attrib->get_cnt != NULL ||
17244 		    rinfo->cmd_attrib->get_lba != NULL);
17245 
17246 		/* only explicit commands have both and they're handled above */
17247 		ASSERT(!(rinfo->cmd_attrib->get_cnt != NULL &&
17248 		    rinfo->cmd_attrib->get_lba != NULL));
17249 
17250 		/* if it has a get count function */
17251 		if (rinfo->cmd_attrib->get_cnt != NULL) {
17252 			count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17253 			if (count == 0) {
17254 				return;
17255 			}
17256 			/*
17257 			 * Changes position but doesn't transfer data.
17258 			 * i.e. rewind, write_file_mark and load.
17259 			 */
17260 			if (rinfo->cmd_attrib->transfers_data == TRAN_NONE) {
17261 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17262 				case DIR_NONE: /* Erase */
17263 					ASSERT(rinfo->cmd_attrib->cmd ==
17264 					    SCMD_ERASE);
17265 					break;
17266 				case DIR_FORW: /* write_file_mark */
17267 					rinfo->pos.fileno += count;
17268 					rinfo->pos.lgclblkno += count;
17269 					rinfo->pos.blkno = 0;
17270 					un->un_running.fileno += count;
17271 					un->un_running.lgclblkno += count;
17272 					un->un_running.blkno = 0;
17273 					break;
17274 				case DIR_REVC: /* rewind */
17275 					rinfo->pos.fileno = 0;
17276 					rinfo->pos.lgclblkno = 0;
17277 					rinfo->pos.blkno = 0;
17278 					rinfo->pos.eof = ST_NO_EOF;
17279 					rinfo->pos.pmode = legacy;
17280 					un->un_running.fileno = 0;
17281 					un->un_running.lgclblkno = 0;
17282 					un->un_running.blkno = 0;
17283 					un->un_running.eof = ST_NO_EOF;
17284 					if (un->un_running.pmode != legacy)
17285 						un->un_running.pmode = legacy;
17286 					break;
17287 				case DIR_EITH: /* Load unload */
17288 					ASSERT(rinfo->cmd_attrib->cmd ==
17289 					    SCMD_LOAD);
17290 					switch (count & (LD_LOAD | LD_RETEN |
17291 					    LD_RETEN | LD_HOLD)) {
17292 					case LD_UNLOAD:
17293 					case LD_RETEN:
17294 					case LD_HOLD:
17295 					case LD_LOAD | LD_HOLD:
17296 					case LD_EOT | LD_HOLD:
17297 					case LD_RETEN | LD_HOLD:
17298 						rinfo->pos.pmode = invalid;
17299 						un->un_running.pmode = invalid;
17300 						break;
17301 					case LD_EOT:
17302 					case LD_LOAD | LD_EOT:
17303 						rinfo->pos.eof = ST_EOT;
17304 						rinfo->pos.pmode = invalid;
17305 						un->un_running.eof = ST_EOT;
17306 						un->un_running.pmode = invalid;
17307 						break;
17308 					case LD_LOAD:
17309 					case LD_RETEN | LD_LOAD:
17310 						rinfo->pos.fileno = 0;
17311 						rinfo->pos.lgclblkno = 0;
17312 						rinfo->pos.blkno = 0;
17313 						rinfo->pos.eof = ST_NO_EOF;
17314 						rinfo->pos.pmode = legacy;
17315 						un->un_running.fileno = 0;
17316 						un->un_running.lgclblkno = 0;
17317 						un->un_running.blkno = 0;
17318 						un->un_running.eof = ST_NO_EOF;
17319 						break;
17320 					default:
17321 						ASSERT(0);
17322 					}
17323 					break;
17324 				default:
17325 					ASSERT(0);
17326 					break;
17327 				}
17328 			} else {
17329 				/*
17330 				 * Changes position and does transfer data.
17331 				 * i.e. read or write.
17332 				 */
17333 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17334 				case DIR_FORW:
17335 					rinfo->pos.lgclblkno += count;
17336 					rinfo->pos.blkno += count;
17337 					un->un_running.lgclblkno += count;
17338 					un->un_running.blkno += count;
17339 					break;
17340 				case DIR_REVC:
17341 					rinfo->pos.lgclblkno -= count;
17342 					rinfo->pos.blkno -= count;
17343 					un->un_running.lgclblkno -= count;
17344 					un->un_running.blkno -= count;
17345 					break;
17346 				default:
17347 					ASSERT(0);
17348 					break;
17349 				}
17350 			}
17351 		} else if (rinfo->cmd_attrib->get_lba != NULL) {
17352 			/* Have a get LBA fuction. i.e. Locate */
17353 			ASSERT(rinfo->cmd_attrib->chg_tape_direction ==
17354 			    DIR_EITH);
17355 			count = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17356 			un->un_running.lgclblkno = count;
17357 			un->un_running.blkno = 0;
17358 			un->un_running.fileno = 0;
17359 			un->un_running.pmode = logical;
17360 			rinfo->pos.lgclblkno = count;
17361 			rinfo->pos.pmode = invalid;
17362 		} else {
17363 			ASSERT(0);
17364 		}
17365 		return;
17366 	}
17367 
17368 	ST_CDB(ST_DEVINFO, "Unhanded CDB for position prediction",
17369 	    (char *)pkt->pkt_cdbp);
17370 
17371 }
17372 
17373 static int
17374 st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf)
17375 {
17376 	struct seq_mode *current;
17377 	int rval;
17378 	int i;
17379 	caddr_t this;
17380 	caddr_t that;
17381 
17382 	ST_FUNC(ST_DEVINFO, st_check_mode_for_change);
17383 
17384 	/* recovery called with mode tamper before mode selection */
17385 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
17386 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17387 		    "Mode Select not done yet");
17388 		return (0);
17389 	}
17390 
17391 	current = kmem_zalloc(sizeof (struct seq_mode), KM_SLEEP);
17392 
17393 	rval = st_gen_mode_sense(un, ubf, un->un_comp_page, current,
17394 	    sizeof (struct seq_mode));
17395 	if (rval != 0) {
17396 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17397 		    "Mode Sense for mode verification failed");
17398 		kmem_free(current, sizeof (struct seq_mode));
17399 		return (rval);
17400 	}
17401 
17402 	this = (caddr_t)current;
17403 	that = (caddr_t)un->un_mspl;
17404 
17405 	rval = bcmp(this, that, sizeof (struct seq_mode));
17406 	if (rval == 0) {
17407 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17408 		    "Found no changes in mode data");
17409 	}
17410 #ifdef STDEBUG
17411 	else {
17412 		for (i = 1; i < sizeof (struct seq_mode); i++) {
17413 			if (this[i] != that[i]) {
17414 				ST_RECOV(ST_DEVINFO, st_label, CE_CONT,
17415 				    "sense data changed at byte %d was "
17416 				    "0x%x now 0x%x", i,
17417 				    (uchar_t)that[i], (uchar_t)this[i]);
17418 			}
17419 		}
17420 	}
17421 #endif
17422 	kmem_free(current, sizeof (struct seq_mode));
17423 
17424 	return (rval);
17425 }
17426 
17427 static int
17428 st_test_path_to_device(struct scsi_tape *un)
17429 {
17430 	int rval = 0;
17431 	int limit = st_retry_count;
17432 
17433 	ST_FUNC(ST_DEVINFO, st_test_path_to_device);
17434 
17435 	/*
17436 	 * XXX Newer drives may not RESEVATION CONFLICT a TUR.
17437 	 */
17438 	do {
17439 		if (rval != 0) {
17440 			mutex_exit(ST_MUTEX);
17441 			delay(drv_usectohz(1000000));
17442 			mutex_enter(ST_MUTEX);
17443 		}
17444 		rval = st_rcmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
17445 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17446 		    "ping TUR returned 0x%x", rval);
17447 		limit--;
17448 	} while (((rval == EACCES) || (rval == EBUSY)) && limit);
17449 
17450 	if (un->un_status == KEY_NOT_READY || un->un_mediastate == MTIO_EJECTED)
17451 		rval = 0;
17452 
17453 	return (rval);
17454 }
17455 
17456 /*
17457  * Does read position using recov_buf and doesn't update un_pos.
17458  * Does what ever kind of read position you want.
17459  */
17460 static int
17461 st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
17462     read_pos_data_t *raw)
17463 {
17464 	int rval;
17465 	struct uscsi_cmd cmd;
17466 	struct scsi_arq_status status;
17467 	char cdb[CDB_GROUP1];
17468 
17469 	ST_FUNC(ST_DEVINFO, st_recovery_read_pos);
17470 	bzero(&cmd, sizeof (cmd));
17471 
17472 	cdb[0] = SCMD_READ_POSITION;
17473 	cdb[1] = type;
17474 	cdb[2] = 0;
17475 	cdb[3] = 0;
17476 	cdb[4] = 0;
17477 	cdb[5] = 0;
17478 	cdb[6] = 0;
17479 	cdb[7] = 0;
17480 	cdb[8] = (type == EXT_POS) ? 28 : 0;
17481 	cdb[9] = 0;
17482 
17483 	cmd.uscsi_flags = USCSI_READ | USCSI_RQENABLE;
17484 	cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
17485 	cmd.uscsi_cdb = cdb;
17486 	cmd.uscsi_cdblen = sizeof (cdb);
17487 	cmd.uscsi_rqlen = sizeof (status);
17488 	cmd.uscsi_rqbuf = (caddr_t)&status;
17489 	cmd.uscsi_bufaddr = (caddr_t)raw;
17490 	switch (type) {
17491 	case SHORT_POS:
17492 		cmd.uscsi_buflen = sizeof (tape_position_t);
17493 		break;
17494 	case LONG_POS:
17495 		cmd.uscsi_buflen = sizeof (tape_position_long_t);
17496 		break;
17497 	case EXT_POS:
17498 		cmd.uscsi_buflen = sizeof (tape_position_ext_t);
17499 		break;
17500 	default:
17501 		ASSERT(0);
17502 	}
17503 
17504 	rval = st_uscsi_rcmd(un, &cmd, FKIOCTL);
17505 	if (cmd.uscsi_status) {
17506 		rval = EIO;
17507 	}
17508 	return (rval);
17509 }
17510 
17511 static int
17512 st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
17513     read_pos_data_t *raw)
17514 {
17515 	int rval;
17516 	read_p_types type = un->un_read_pos_type;
17517 
17518 	ST_FUNC(ST_DEVINFO, st_recovery_get_position);
17519 
17520 	do {
17521 		rval = st_recovery_read_pos(un, type, raw);
17522 		if (rval != 0) {
17523 			switch (type) {
17524 			case SHORT_POS:
17525 				type = NO_POS;
17526 				break;
17527 
17528 			case LONG_POS:
17529 				type = EXT_POS;
17530 				break;
17531 
17532 			case EXT_POS:
17533 				type = SHORT_POS;
17534 				break;
17535 
17536 			default:
17537 				type = LONG_POS;
17538 				break;
17539 
17540 			}
17541 		} else {
17542 			if (type != un->un_read_pos_type) {
17543 				un->un_read_pos_type = type;
17544 			}
17545 			break;
17546 		}
17547 	} while (type != NO_POS);
17548 
17549 	if (rval == 0) {
17550 		rval = st_interpret_read_pos(un, read, type,
17551 		    sizeof (read_pos_data_t), (caddr_t)raw, 1);
17552 	}
17553 	return (rval);
17554 }
17555 
17556 /*
17557  * based on the command do we retry, continue or give up?
17558  * possable return values?
17559  *	zero do nothing looks fine.
17560  *	EAGAIN retry.
17561  *	EIO failed makes no sense.
17562  */
17563 static int
17564 st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
17565     cmd_attribute const * cmd_att, tapepos_t *read)
17566 {
17567 	int rval;
17568 	read_pos_data_t *readp_datap;
17569 
17570 	ST_FUNC(ST_DEVINFO, st_compare_expected_position);
17571 
17572 	ASSERT(un != NULL);
17573 	ASSERT(ei != NULL);
17574 	ASSERT(read != NULL);
17575 	ASSERT(cmd_att->chg_tape_pos);
17576 
17577 	COPY_POS(read, &ei->ei_expected_pos);
17578 
17579 	readp_datap = kmem_zalloc(sizeof (read_pos_data_t), KM_SLEEP);
17580 
17581 	rval = st_recovery_get_position(un, read, readp_datap);
17582 
17583 	kmem_free(readp_datap, sizeof (read_pos_data_t));
17584 
17585 	if (rval != 0) {
17586 		return (EIO);
17587 	}
17588 
17589 	ST_POS(ST_DEVINFO, "st_compare_expected_position", read);
17590 
17591 	if ((read->pmode == invalid) ||
17592 	    (ei->ei_expected_pos.pmode == invalid)) {
17593 		return (EIO);
17594 	}
17595 
17596 	/*
17597 	 * Command that changes tape position and have an expected position
17598 	 * if it were to chave completed sucessfully.
17599 	 */
17600 	if (cmd_att->recov_pos_type == POS_EXPECTED) {
17601 		uint32_t count;
17602 		int64_t difference;
17603 		uchar_t reposition = 0;
17604 
17605 		ASSERT(cmd_att->get_cnt);
17606 		count = cmd_att->get_cnt(ei->ei_failed_pkt.pkt_cdbp);
17607 
17608 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17609 		    "Got count from CDB and it was %d\n", count);
17610 
17611 		/*
17612 		 * At expected?
17613 		 */
17614 		if (read->lgclblkno == ei->ei_expected_pos.lgclblkno) {
17615 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17616 			    "Found drive to be at expected position\n");
17617 
17618 			/*
17619 			 * If the command should move tape and it got a busy
17620 			 * it shouldn't be in the expected position.
17621 			 */
17622 			if (ei->ei_failing_status.sts_status.sts_busy != 0) {
17623 				reposition = 1;
17624 
17625 			/*
17626 			 * If the command doesn't transfer data should be good.
17627 			 */
17628 			} else if (cmd_att->transfers_data == TRAN_NONE) {
17629 				return (0); /* Good */
17630 
17631 			/*
17632 			 * Command transfers data, should have done so.
17633 			 */
17634 			} else if (ei->ei_failed_pkt.pkt_state &
17635 			    STATE_XFERRED_DATA) {
17636 				return (0); /* Good */
17637 			} else {
17638 				reposition = 1;
17639 			}
17640 		}
17641 
17642 		if (cmd_att->chg_tape_direction == DIR_FORW) {
17643 			difference =
17644 			    ei->ei_expected_pos.lgclblkno - read->lgclblkno;
17645 
17646 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17647 			    "difference between expected and actual is %"
17648 			    PRId64"\n", difference);
17649 			if (count == difference && reposition == 0) {
17650 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17651 				    "Found failed FORW command, retrying\n");
17652 				return (EAGAIN);
17653 			}
17654 
17655 			/*
17656 			 * If rewound or somewhere between the starting position
17657 			 * and the expected position (partial read or write).
17658 			 * Locate to the starting position and try the whole
17659 			 * thing over again.
17660 			 */
17661 			if ((read->lgclblkno == 0) ||
17662 			    ((difference > 0) && (difference < count))) {
17663 				rval = st_logical_block_locate(un,
17664 				    st_uscsi_rcmd, read,
17665 				    ei->ei_expected_pos.lgclblkno - count,
17666 				    ei->ei_expected_pos.partition);
17667 				if (rval == 0) {
17668 					ST_RECOV(ST_DEVINFO, st_label,
17669 					    CE_NOTE, "reestablished FORW"
17670 					    " command retrying\n");
17671 					return (EAGAIN);
17672 				}
17673 			/*
17674 			 * This handles flushed read ahead on the drive or
17675 			 * an aborted read that presents as a busy and advanced
17676 			 * the tape position.
17677 			 */
17678 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17679 			    ((difference < 0) || (reposition == 1))) {
17680 				rval = st_logical_block_locate(un,
17681 				    st_uscsi_rcmd, read,
17682 				    ei->ei_expected_pos.lgclblkno - count,
17683 				    ei->ei_expected_pos.partition);
17684 				if (rval == 0) {
17685 					ST_RECOV(ST_DEVINFO, st_label,
17686 					    CE_NOTE, "reestablished FORW"
17687 					    " read command retrying\n");
17688 					return (EAGAIN);
17689 				}
17690 			/*
17691 			 * XXX swag seeing difference of 2 on write filemark.
17692 			 * If the space to the starting position works on a
17693 			 * write that means the previous write made it to tape.
17694 			 * If not we lost data and have to give up.
17695 			 *
17696 			 * The plot thickens. Now I am attempting to cover a
17697 			 * count of 1 and a differance of 2 on a write.
17698 			 */
17699 			} else if ((difference > count) || (reposition == 1)) {
17700 				rval = st_logical_block_locate(un,
17701 				    st_uscsi_rcmd, read,
17702 				    ei->ei_expected_pos.lgclblkno - count,
17703 				    ei->ei_expected_pos.partition);
17704 				if (rval == 0) {
17705 					ST_RECOV(ST_DEVINFO, st_label,
17706 					    CE_NOTE, "reestablished FORW"
17707 					    " write command retrying\n");
17708 					return (EAGAIN);
17709 				}
17710 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17711 				    "Seek to block %"PRId64" returned %d\n",
17712 				    ei->ei_expected_pos.lgclblkno - count,
17713 				    rval);
17714 			} else {
17715 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17716 				    "Not expected transfers_data = %d "
17717 				    "difference = %"PRId64,
17718 				    cmd_att->transfers_data, difference);
17719 			}
17720 
17721 			return (EIO);
17722 
17723 		} else if (cmd_att->chg_tape_direction == DIR_REVC) {
17724 			/* Don't think we can write backwards */
17725 			ASSERT(cmd_att->transfers_data != TRAN_WRTE);
17726 			difference =
17727 			    read->lgclblkno - ei->ei_expected_pos.lgclblkno;
17728 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17729 			    "difference between expected and actual is %"
17730 			    PRId64"\n", difference);
17731 			if (count == difference && reposition == 0) {
17732 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17733 				    "Found failed REVC command, retrying\n");
17734 				return (EAGAIN);
17735 			}
17736 			if ((read->lgclblkno == 0) ||
17737 			    ((difference > 0) && (difference < count))) {
17738 				rval = st_logical_block_locate(un,
17739 				    st_uscsi_rcmd, read,
17740 				    ei->ei_expected_pos.lgclblkno + count,
17741 				    ei->ei_expected_pos.partition);
17742 				if (rval == 0) {
17743 					ST_RECOV(ST_DEVINFO, st_label,
17744 					    CE_NOTE, "reestablished REVC"
17745 					    " command retrying\n");
17746 					return (EAGAIN);
17747 				}
17748 			/* This handles read ahead in reverse direction */
17749 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17750 			    (difference < 0) || (reposition == 1)) {
17751 				rval = st_logical_block_locate(un,
17752 				    st_uscsi_rcmd, read,
17753 				    ei->ei_expected_pos.lgclblkno - count,
17754 				    ei->ei_expected_pos.partition);
17755 				if (rval == 0) {
17756 					ST_RECOV(ST_DEVINFO, st_label,
17757 					    CE_NOTE, "reestablished REVC"
17758 					    " read command retrying\n");
17759 					return (EAGAIN);
17760 				}
17761 			} else {
17762 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17763 				    "Not expected transfers_data = %d "
17764 				    "difference = %"PRId64,
17765 				    cmd_att->transfers_data, difference);
17766 			}
17767 			return (EIO);
17768 
17769 		} else {
17770 			/*
17771 			 * Commands that change tape position either
17772 			 * direction or don't change position should not
17773 			 * get here.
17774 			 */
17775 			ASSERT(0);
17776 		}
17777 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17778 		    "Didn't find a recoverable position, Failing\n");
17779 
17780 	/*
17781 	 * Command that changes tape position and can only be recovered
17782 	 * by going back to the point of origin and retrying.
17783 	 *
17784 	 * Example SCMD_SPACE.
17785 	 */
17786 	} else if (cmd_att->recov_pos_type == POS_STARTING) {
17787 		/*
17788 		 * This type of command stores the starting position.
17789 		 * If the read position is the starting position,
17790 		 * reissue the command.
17791 		 */
17792 		if (ei->ei_expected_pos.lgclblkno == read->lgclblkno) {
17793 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17794 			    "Found Space command at starting position, "
17795 			    "Reissuing\n");
17796 			return (EAGAIN);
17797 		}
17798 		/*
17799 		 * Not in the position that the command was originally issued,
17800 		 * Attempt to locate to that position.
17801 		 */
17802 		rval = st_logical_block_locate(un, st_uscsi_rcmd, read,
17803 		    ei->ei_expected_pos.lgclblkno,
17804 		    ei->ei_expected_pos.partition);
17805 		if (rval) {
17806 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17807 			    "Found Space at an unexpected position and locate "
17808 			    "back to starting position failed\n");
17809 			return (EIO);
17810 		}
17811 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17812 		    "Found Space at an unexpected position and locate "
17813 		    "back to starting position worked, Reissuing\n");
17814 		return (EAGAIN);
17815 	}
17816 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17817 	    "Unhandled attribute/expected position", &ei->ei_expected_pos);
17818 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17819 	    "Read position above did not make sense", read);
17820 	ASSERT(0);
17821 	return (EIO);
17822 }
17823 
17824 static errstate
17825 st_recover_reissue_pkt(struct scsi_tape *un, struct scsi_pkt *oldpkt)
17826 {
17827 	buf_t *bp;
17828 	buf_t *pkt_bp;
17829 	struct scsi_pkt *newpkt;
17830 	cmd_attribute const *attrib;
17831 	recov_info *rcv = oldpkt->pkt_private;
17832 	uint_t cdblen;
17833 	int queued = 0;
17834 	int rval;
17835 	int flags = 0;
17836 	int stat_size =
17837 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
17838 
17839 	ST_FUNC(ST_DEVINFO, st_recover_reissue_pkt);
17840 
17841 	bp = rcv->cmd_bp;
17842 
17843 	if (rcv->privatelen == sizeof (recov_info)) {
17844 		attrib = rcv->cmd_attrib;
17845 	} else {
17846 		attrib = st_lookup_cmd_attribute(oldpkt->pkt_cdbp[0]);
17847 	}
17848 
17849 	/*
17850 	 * Some non-uscsi commands use the b_bcount for values that
17851 	 * have nothing to do with how much data is transfered.
17852 	 * In those cases we need to hide the buf_t from scsi_init_pkt().
17853 	 */
17854 	if ((BP_UCMD(bp)) && (bp->b_bcount)) {
17855 		pkt_bp = bp;
17856 	} else if (attrib->transfers_data == TRAN_NONE) {
17857 		pkt_bp = NULL;
17858 	} else {
17859 		pkt_bp = bp;
17860 	}
17861 
17862 	/*
17863 	 * if this is a queued command make sure it the only one in the
17864 	 * run queue.
17865 	 */
17866 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
17867 		ASSERT(un->un_runqf == un->un_runql);
17868 		ASSERT(un->un_runqf == bp);
17869 		queued = 1;
17870 	}
17871 
17872 	cdblen = scsi_cdb_size[CDB_GROUPID(oldpkt->pkt_cdbp[0])];
17873 
17874 	if (pkt_bp == un->un_rqs_bp) {
17875 		flags |= PKT_CONSISTENT;
17876 		stat_size = 1;
17877 	}
17878 
17879 	newpkt = scsi_init_pkt(ROUTE, NULL, pkt_bp, cdblen,
17880 	    stat_size, rcv->privatelen, flags, NULL_FUNC, NULL);
17881 	if (newpkt == NULL) {
17882 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17883 		    "Reissue pkt scsi_init_pkt() failure\n");
17884 		return (COMMAND_DONE_ERROR);
17885 	}
17886 
17887 	ASSERT(newpkt->pkt_resid == 0);
17888 	bp->b_flags &= ~(B_DONE);
17889 	bp->b_resid = 0;
17890 	st_bioerror(bp, 0);
17891 
17892 	bcopy(oldpkt->pkt_private, newpkt->pkt_private, rcv->privatelen);
17893 
17894 	newpkt->pkt_comp = oldpkt->pkt_comp;
17895 	newpkt->pkt_time = oldpkt->pkt_time;
17896 
17897 	bzero(newpkt->pkt_scbp, stat_size);
17898 	bcopy(oldpkt->pkt_cdbp, newpkt->pkt_cdbp, cdblen);
17899 
17900 	newpkt->pkt_state = 0;
17901 	newpkt->pkt_statistics = 0;
17902 
17903 	/*
17904 	 * oldpkt passed in was a copy of the original.
17905 	 * to distroy we need the address of the original.
17906 	 */
17907 	oldpkt = BP_PKT(bp);
17908 
17909 	if (oldpkt == un->un_rqs) {
17910 		ASSERT(bp == un->un_rqs_bp);
17911 		un->un_rqs = newpkt;
17912 	}
17913 
17914 	SET_BP_PKT(bp, newpkt);
17915 
17916 	scsi_destroy_pkt(oldpkt);
17917 
17918 	rval = st_transport(un, newpkt);
17919 	if (rval == TRAN_ACCEPT) {
17920 		return (JUST_RETURN);
17921 	}
17922 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17923 	    "Reissue pkt st_transport(0x%x) failure\n", rval);
17924 	if (rval != TRAN_BUSY) {
17925 		return (COMMAND_DONE_ERROR);
17926 	}
17927 	mutex_exit(ST_MUTEX);
17928 	rval = st_handle_start_busy(un, bp, ST_TRAN_BUSY_TIMEOUT, queued);
17929 	mutex_enter(ST_MUTEX);
17930 	if (rval) {
17931 		return (COMMAND_DONE_ERROR);
17932 	}
17933 
17934 	return (JUST_RETURN);
17935 }
17936 
17937 static int
17938 st_transport(struct scsi_tape *un, struct scsi_pkt *pkt)
17939 {
17940 	int status;
17941 
17942 	ST_FUNC(ST_DEVINFO, st_transport);
17943 
17944 	ST_CDB(ST_DEVINFO, "transport CDB", (caddr_t)pkt->pkt_cdbp);
17945 
17946 	mutex_exit(ST_MUTEX);
17947 
17948 	status = scsi_transport(pkt);
17949 
17950 	mutex_enter(ST_MUTEX);
17951 
17952 	return (status);
17953 }
17954 
17955 /*
17956  * Removed the buf_t bp from the queue referenced to by head and tail.
17957  * Returns the buf_t pointer if it is found in the queue.
17958  * Returns NULL if it is not found.
17959  */
17960 static buf_t *
17961 st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp)
17962 {
17963 	buf_t *runqbp;
17964 	buf_t *prevbp = NULL;
17965 
17966 	for (runqbp = *head; runqbp != 0; runqbp = runqbp->av_forw) {
17967 		if (runqbp == bp) {
17968 			/* found it, is it at the head? */
17969 			if (runqbp == *head) {
17970 				*head = bp->av_forw;
17971 			} else {
17972 				prevbp->av_forw = bp->av_forw;
17973 			}
17974 			if (*tail == bp) {
17975 				*tail = prevbp;
17976 			}
17977 			bp->av_forw = NULL;
17978 			return (bp); /* found and removed */
17979 		}
17980 		prevbp = runqbp;
17981 	}
17982 	return (NULL);
17983 }
17984 
17985 /*
17986  * Adds a buf_t to the queue pointed to by head and tail.
17987  * Adds it either to the head end or the tail end based on which
17988  * the passed variable end (head or tail) points at.
17989  */
17990 static void
17991 st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp)
17992 {
17993 
17994 	bp->av_forw = NULL;
17995 	if (*head) {
17996 		/* Queue is not empty */
17997 		if (end == *head) {
17998 			/* Add at front of queue */
17999 			bp->av_forw = *head;
18000 			*head = bp;
18001 		} else if (end == *tail) {
18002 			/* Add at end of queue */
18003 			(*tail)->av_forw = bp;
18004 			*tail = bp;
18005 		} else {
18006 			ASSERT(0);
18007 		}
18008 	} else {
18009 		/* Queue is empty */
18010 		*head = bp;
18011 		*tail = bp;
18012 	}
18013 }
18014 
18015 
18016 static uint64_t
18017 st_get_cdb_g0_rw_count(uchar_t *cdb)
18018 {
18019 	uint64_t count;
18020 
18021 	if ((cdb[1]) & 1) {
18022 		/* fixed block mode, the count is the number of blocks */
18023 		count =
18024 		    cdb[2] << 16 |
18025 		    cdb[3] << 8 |
18026 		    cdb[4];
18027 	} else {
18028 		/* variable block mode, the count is the block size */
18029 		count = 1;
18030 	}
18031 	return (count);
18032 }
18033 
18034 static uint64_t
18035 st_get_cdb_g0_sign_count(uchar_t *cdb)
18036 {
18037 	uint64_t count;
18038 
18039 	count =
18040 	    cdb[2] << 16 |
18041 	    cdb[3] << 8 |
18042 	    cdb[4];
18043 	/*
18044 	 * If the sign bit of the 3 byte value is set, extended it.
18045 	 */
18046 	if (count & 0x800000) {
18047 		count |= 0xffffffffff000000;
18048 	}
18049 	return (count);
18050 }
18051 
18052 static uint64_t
18053 st_get_cdb_g0_count(uchar_t *cdb)
18054 {
18055 	uint64_t count;
18056 
18057 	count =
18058 	    cdb[2] << 16 |
18059 	    cdb[3] << 8 |
18060 	    cdb[4];
18061 	return (count);
18062 }
18063 
18064 static uint64_t
18065 st_get_cdb_g5_rw_cnt(uchar_t *cdb)
18066 {
18067 	uint64_t count;
18068 
18069 	if ((cdb[1]) & 1) {
18070 		/* fixed block mode */
18071 		count =
18072 		    cdb[12] << 16 |
18073 		    cdb[13] << 8 |
18074 		    cdb[14];
18075 	} else {
18076 		/* variable block mode */
18077 		count = 1;
18078 	}
18079 	return (count);
18080 }
18081 
18082 static uint64_t
18083 st_get_no_count(uchar_t *cdb)
18084 {
18085 	ASSERT(cdb[0] == SCMD_REWIND);
18086 	return ((uint64_t)cdb[0]);
18087 }
18088 
18089 static uint64_t
18090 st_get_load_options(uchar_t *cdb)
18091 {
18092 	return ((uint64_t)(cdb[4] | (LD_HOLD << 1)));
18093 }
18094 
18095 static uint64_t
18096 st_get_erase_options(uchar_t *cdb)
18097 {
18098 	return (cdb[1] | (cdb[0] << 8));
18099 }
18100 
18101 static uint64_t
18102 st_get_cdb_g1_lba(uchar_t *cdb)
18103 {
18104 	uint64_t lba;
18105 
18106 	lba =
18107 	    cdb[3] << 24 |
18108 	    cdb[4] << 16 |
18109 	    cdb[5] << 8 |
18110 	    cdb[6];
18111 	return (lba);
18112 }
18113 
18114 static uint64_t
18115 st_get_cdb_g5_count(uchar_t *cdb)
18116 {
18117 	uint64_t count =
18118 	    cdb[12] << 16 |
18119 	    cdb[13] << 8 |
18120 	    cdb[14];
18121 
18122 	return (count);
18123 }
18124 
18125 static uint64_t
18126 st_get_cdb_g4g5_cnt(uchar_t *cdb)
18127 {
18128 	uint64_t lba;
18129 
18130 	lba =
18131 	    (uint64_t)cdb[4] << 56 |
18132 	    (uint64_t)cdb[5] << 48 |
18133 	    (uint64_t)cdb[6] << 40 |
18134 	    (uint64_t)cdb[7] << 32 |
18135 	    (uint64_t)cdb[8] << 24 |
18136 	    (uint64_t)cdb[9] << 16 |
18137 	    (uint64_t)cdb[10] << 8 |
18138 	    (uint64_t)cdb[11];
18139 	return (lba);
18140 }
18141 
18142 static const cmd_attribute cmd_attributes[] = {
18143 	{ SCMD_READ,
18144 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_READ, POS_EXPECTED,
18145 	    0, 0, 0, st_get_cdb_g0_rw_count },
18146 	{ SCMD_WRITE,
18147 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18148 	    0, 0, 0, st_get_cdb_g0_rw_count },
18149 	{ SCMD_TEST_UNIT_READY,
18150 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18151 	    0, 0, 0 },
18152 	{ SCMD_REWIND,
18153 	    1, 1, 1, 0, 0, DIR_REVC, TRAN_NONE, POS_EXPECTED,
18154 	    0, 0, 0, st_get_no_count },
18155 	{ SCMD_REQUEST_SENSE,
18156 	    0, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18157 	    0, 0, 0 },
18158 	{ SCMD_READ_BLKLIM,
18159 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18160 	    0, 0, 0 },
18161 	{ SCMD_READ_G4,
18162 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_READ, POS_EXPECTED,
18163 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18164 	{ SCMD_WRITE_G4,
18165 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18166 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18167 	{ SCMD_READ_REVERSE,
18168 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18169 	    0, 0, 0, st_get_cdb_g0_rw_count },
18170 	{ SCMD_READ_REVERSE_G4,
18171 	    1, 0, 1, 1, 1, DIR_REVC, TRAN_READ, POS_EXPECTED,
18172 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18173 	{ SCMD_WRITE_FILE_MARK,
18174 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18175 	    0, 0, 0, st_get_cdb_g0_count },
18176 	{ SCMD_WRITE_FILE_MARK_G4,
18177 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18178 	    0, 0, 0, st_get_cdb_g5_count, st_get_cdb_g4g5_cnt },
18179 	{ SCMD_SPACE,
18180 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18181 	    0, 0, 0, st_get_cdb_g0_sign_count },
18182 	{ SCMD_SPACE_G4,
18183 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18184 	    0, 0, 0, st_get_cdb_g4g5_cnt },
18185 	{ SCMD_INQUIRY,
18186 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18187 	    0, 0, 0 },
18188 	{ SCMD_VERIFY_G0,
18189 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18190 	    0, 0, 0, st_get_cdb_g0_rw_count },
18191 	{ SCMD_VERIFY_G4,
18192 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18193 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18194 	{ SCMD_RECOVER_BUF,
18195 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18196 	    0, 0, 0 },
18197 	{ SCMD_MODE_SELECT,
18198 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18199 	    0, 0, 0 },
18200 	{ SCMD_RESERVE,
18201 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18202 	    0, 0, 0 },
18203 	{ SCMD_RELEASE,
18204 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18205 	    0, 0, 0 },
18206 	{ SCMD_ERASE,
18207 	    1, 0, 1, 1, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18208 	    0, 0, 0, st_get_erase_options },
18209 	{ SCMD_MODE_SENSE,
18210 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18211 	    0, 0, 0 },
18212 	{ SCMD_LOAD,
18213 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18214 	    0, 0, 0, st_get_load_options },
18215 	{ SCMD_GDIAG,
18216 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18217 	    1, 0, 0 },
18218 	{ SCMD_SDIAG,
18219 	    1, 0, 1, 1, 0, DIR_EITH, TRAN_WRTE, POS_EXPECTED,
18220 	    1, 0, 0 },
18221 	{ SCMD_DOORLOCK,
18222 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18223 	    0, 4, 3 },
18224 	{ SCMD_LOCATE,
18225 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18226 	    0, 0, 0, NULL, st_get_cdb_g1_lba },
18227 	{ SCMD_READ_POSITION,
18228 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18229 	    0, 0, 0 },
18230 	{ SCMD_WRITE_BUFFER,
18231 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18232 	    1, 0, 0 },
18233 	{ SCMD_READ_BUFFER,
18234 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18235 	    1, 0, 0 },
18236 	{ SCMD_REPORT_DENSITIES,
18237 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18238 	    0, 0, 0 },
18239 	{ SCMD_LOG_SELECT_G1,
18240 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18241 	    0, 0, 0 },
18242 	{ SCMD_LOG_SENSE_G1,
18243 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18244 	    0, 0, 0 },
18245 	{ SCMD_PRIN,
18246 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18247 	    0, 0, 0 },
18248 	{ SCMD_PROUT,
18249 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18250 	    0, 0, 0 },
18251 	{ SCMD_READ_ATTRIBUTE,
18252 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18253 	    0, 0, 0 },
18254 	{ SCMD_WRITE_ATTRIBUTE,
18255 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18256 	    0, 0, 0 },
18257 	{ SCMD_LOCATE_G4,
18258 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18259 	    0, 0, 0, NULL, st_get_cdb_g4g5_cnt },
18260 	{ SCMD_REPORT_LUNS,
18261 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18262 	    0, 0, 0 },
18263 	{ SCMD_SVC_ACTION_IN_G5,
18264 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18265 	    0, 0, 0 },
18266 	{ SCMD_MAINTENANCE_IN,
18267 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18268 	    0, 0, 0 },
18269 	{ SCMD_MAINTENANCE_OUT,
18270 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18271 	    0, 0, 0 },
18272 	{ 0xff, /* Default attribute for unsupported commands */
18273 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_STARTING,
18274 	    1, 0, 0, NULL, NULL }
18275 };
18276 
18277 static const cmd_attribute *
18278 st_lookup_cmd_attribute(unsigned char cmd)
18279 {
18280 	int i;
18281 	cmd_attribute const *attribute;
18282 
18283 	for (i = 0; i < ST_NUM_MEMBERS(cmd_attributes); i++) {
18284 		attribute = &cmd_attributes[i];
18285 		if (attribute->cmd == cmd) {
18286 			return (attribute);
18287 		}
18288 	}
18289 	ASSERT(attribute);
18290 	return (attribute);
18291 }
18292 
18293 static int
18294 st_reset(struct scsi_tape *un, int reset_type)
18295 {
18296 	int rval;
18297 
18298 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
18299 
18300 	ST_FUNC(ST_DEVINFO, st_reset);
18301 	un->un_rsvd_status |= ST_INITIATED_RESET;
18302 	mutex_exit(ST_MUTEX);
18303 	do {
18304 		rval = scsi_reset(&un->un_sd->sd_address, reset_type);
18305 		if (rval == 0) {
18306 			switch (reset_type) {
18307 			case RESET_LUN:
18308 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18309 				    "LUN reset failed trying target reset");
18310 				reset_type = RESET_TARGET;
18311 				break;
18312 			case RESET_TARGET:
18313 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18314 				    "target reset failed trying bus reset");
18315 				reset_type = RESET_BUS;
18316 				break;
18317 			case RESET_BUS:
18318 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18319 				    "bus reset failed trying all reset");
18320 				reset_type = RESET_ALL;
18321 			default:
18322 				mutex_enter(ST_MUTEX);
18323 				return (rval);
18324 			}
18325 		}
18326 	} while (rval == 0);
18327 	mutex_enter(ST_MUTEX);
18328 	return (rval);
18329 }
18330 
18331 
18332 static void
18333 st_reset_notification(caddr_t arg)
18334 {
18335 	struct scsi_tape *un = (struct scsi_tape *)arg;
18336 
18337 	ST_FUNC(ST_DEVINFO, st_reset_notification);
18338 	mutex_enter(ST_MUTEX);
18339 
18340 	un->un_unit_attention_flags |= 2;
18341 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
18342 	    ST_RESERVE) {
18343 		un->un_rsvd_status |= ST_LOST_RESERVE;
18344 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18345 		    "Lost Reservation notification");
18346 	} else {
18347 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18348 		    "reset notification");
18349 	}
18350 
18351 	if ((un->un_restore_pos == 0) &&
18352 	    (un->un_state == ST_STATE_CLOSED) ||
18353 	    (un->un_state == ST_STATE_OPEN_PENDING_IO) ||
18354 	    (un->un_state == ST_STATE_CLOSING)) {
18355 		un->un_restore_pos = 1;
18356 	}
18357 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
18358 	    "reset and state was %d\n", un->un_state);
18359 	mutex_exit(ST_MUTEX);
18360 }
18361