xref: /titanic_41/usr/src/uts/common/io/scsi/targets/st.c (revision ab003da878e3fe36b164e1856f9e15a78384c9eb)
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 2010 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 static int st_set_target_TLR_mode(struct scsi_tape *un, ubufunc_t ubf);
650 static int st_make_sure_mode_data_is_correct(struct scsi_tape *un,
651     ubufunc_t ubf);
652 
653 #ifdef	__x86
654 /*
655  * routines for I/O in big block size
656  */
657 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
658 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
659     int alloc_flags);
660 static int st_bigblk_xfer_done(struct buf *bp);
661 static struct buf *st_get_bigblk_bp(struct buf *bp);
662 #endif
663 static void st_print_position(dev_info_t *dev, char *label, uint_t level,
664     const char *comment, tapepos_t *pos);
665 
666 /*
667  * error statistics create/update functions
668  */
669 static int st_create_errstats(struct scsi_tape *, int);
670 static int st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf,
671     tapepos_t *pos);
672 
673 #ifdef STDEBUG
674 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
675 #endif /* STDEBUG */
676 static char *st_dev_name(dev_t dev);
677 
678 #if !defined(lint)
679 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
680     scsi_pkt buf uio scsi_cdb uscsi_cmd))
681 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
682 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", recov_info))
683 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
684 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
685 #endif
686 
687 /*
688  * autoconfiguration routines.
689  */
690 char _depends_on[] = "misc/scsi";
691 
692 static struct modldrv modldrv = {
693 	&mod_driverops,		/* Type of module. This one is a driver */
694 	"SCSI tape Driver", 	/* Name of the module. */
695 	&st_ops			/* driver ops */
696 };
697 
698 static struct modlinkage modlinkage = {
699 	MODREV_1, &modldrv, NULL
700 };
701 
702 /*
703  * Notes on Post Reset Behavior in the tape driver:
704  *
705  * When the tape drive is opened, the driver  attempts  to make sure that
706  * the tape head is positioned exactly where it was left when it was last
707  * closed  provided  the  medium  is not  changed.  If the tape  drive is
708  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
709  * of position due to reset) will happen when the first tape operation or
710  * I/O occurs.  The repositioning (if required) may not be possible under
711  * certain situations such as when the device firmware not able to report
712  * the medium  change in the REQUEST  SENSE data  because of a reset or a
713  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
714  * extraordinary  situations, where the driver fails to position the head
715  * at its  original  position,  it will fail the open the first  time, to
716  * save the applications from overwriting the data.  All further attempts
717  * to open the tape device will result in the driver  attempting  to load
718  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
719  * indicate  that further  attempts to open the tape device may result in
720  * the tape being  loaded at BOT will be printed on the  console.  If the
721  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
722  * original tape head  position,  will result in the failure of the first
723  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
724  * internal tape position  which will  necessitate  the  applications  to
725  * validate the position by using either a tape  positioning  ioctl (such
726  * as MTREW) or closing and reopening the tape device.
727  *
728  */
729 
730 int
731 _init(void)
732 {
733 	int e;
734 
735 	if (((e = ddi_soft_state_init(&st_state,
736 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
737 		return (e);
738 	}
739 
740 	if ((e = mod_install(&modlinkage)) != 0) {
741 		ddi_soft_state_fini(&st_state);
742 	} else {
743 #ifdef STDEBUG
744 		mutex_init(&st_debug_mutex, NULL, MUTEX_DRIVER, NULL);
745 #endif
746 
747 #if defined(__x86)
748 		/* set the max physical address for iob allocs on x86 */
749 		st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
750 
751 		/*
752 		 * set the sgllen for iob allocs on x86. If this is set less
753 		 * than the number of pages the buffer will take
754 		 * (taking into account alignment), it would force the
755 		 * allocator to try and allocate contiguous pages.
756 		 */
757 		st_alloc_attr.dma_attr_sgllen = st_sgl_size;
758 #endif
759 	}
760 
761 	return (e);
762 }
763 
764 int
765 _fini(void)
766 {
767 	int e;
768 
769 	if ((e = mod_remove(&modlinkage)) != 0) {
770 		return (e);
771 	}
772 
773 #ifdef STDEBUG
774 	mutex_destroy(&st_debug_mutex);
775 #endif
776 
777 	ddi_soft_state_fini(&st_state);
778 
779 	return (e);
780 }
781 
782 int
783 _info(struct modinfo *modinfop)
784 {
785 	return (mod_info(&modlinkage, modinfop));
786 }
787 
788 
789 static int
790 st_probe(dev_info_t *devi)
791 {
792 	int instance;
793 	struct scsi_device *devp;
794 	int rval;
795 
796 #if !defined(__sparc)
797 	char    *tape_prop;
798 	int	tape_prop_len;
799 #endif
800 
801 	ST_ENTR(devi, st_probe);
802 
803 	/* If self identifying device */
804 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
805 		return (DDI_PROBE_DONTCARE);
806 	}
807 
808 #if !defined(__sparc)
809 	/*
810 	 * Since some x86 HBAs have devnodes that look like SCSI as
811 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
812 	 * we check for the presence of the "tape" property.
813 	 */
814 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
815 	    DDI_PROP_CANSLEEP, "tape",
816 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
817 		return (DDI_PROBE_FAILURE);
818 	}
819 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
820 		kmem_free(tape_prop, tape_prop_len);
821 		return (DDI_PROBE_FAILURE);
822 	}
823 	kmem_free(tape_prop, tape_prop_len);
824 #endif
825 
826 	devp = ddi_get_driver_private(devi);
827 	instance = ddi_get_instance(devi);
828 
829 	if (ddi_get_soft_state(st_state, instance) != NULL) {
830 		return (DDI_PROBE_PARTIAL);
831 	}
832 
833 
834 	/*
835 	 * Turn around and call probe routine to see whether
836 	 * we actually have a tape at this SCSI nexus.
837 	 */
838 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
839 
840 		/*
841 		 * In checking the whole inq_dtype byte we are looking at both
842 		 * the Peripheral Qualifier and the Peripheral Device Type.
843 		 * For this driver we are only interested in sequential devices
844 		 * that are connected or capable if connecting to this logical
845 		 * unit.
846 		 */
847 		if (devp->sd_inq->inq_dtype ==
848 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
849 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
850 			    "probe exists\n");
851 			rval = DDI_PROBE_SUCCESS;
852 		} else {
853 			rval = DDI_PROBE_FAILURE;
854 		}
855 	} else {
856 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
857 		    "probe failure: nothing there\n");
858 		rval = DDI_PROBE_FAILURE;
859 	}
860 	scsi_unprobe(devp);
861 	return (rval);
862 }
863 
864 static int
865 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
866 {
867 	int 	instance;
868 	int	wide;
869 	int 	dev_instance;
870 	int	ret_status;
871 	struct	scsi_device *devp;
872 	int	node_ix;
873 	struct	scsi_tape *un;
874 
875 	ST_ENTR(devi, st_attach);
876 
877 	devp = ddi_get_driver_private(devi);
878 	instance = ddi_get_instance(devi);
879 
880 	switch (cmd) {
881 		case DDI_ATTACH:
882 			if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
883 			    "tape-command-recovery-disable", 0) != 0) {
884 				st_recov_sz = sizeof (pkt_info);
885 			}
886 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
887 				return (DDI_FAILURE);
888 			}
889 			break;
890 		case DDI_RESUME:
891 			/*
892 			 * Suspend/Resume
893 			 *
894 			 * When the driver suspended, there might be
895 			 * outstanding cmds and therefore we need to
896 			 * reset the suspended flag and resume the scsi
897 			 * watch thread and restart commands and timeouts
898 			 */
899 
900 			if (!(un = ddi_get_soft_state(st_state, instance))) {
901 				return (DDI_FAILURE);
902 			}
903 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
904 			    un->un_dev);
905 
906 			mutex_enter(ST_MUTEX);
907 
908 			un->un_throttle = un->un_max_throttle;
909 			un->un_tids_at_suspend = 0;
910 			un->un_pwr_mgmt = ST_PWR_NORMAL;
911 
912 			if (un->un_swr_token) {
913 				scsi_watch_resume(un->un_swr_token);
914 			}
915 
916 			/*
917 			 * Restart timeouts
918 			 */
919 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
920 				mutex_exit(ST_MUTEX);
921 				un->un_delay_tid = timeout(
922 				    st_delayed_cv_broadcast, un,
923 				    drv_usectohz((clock_t)
924 				    MEDIA_ACCESS_DELAY));
925 				mutex_enter(ST_MUTEX);
926 			}
927 
928 			if (un->un_tids_at_suspend & ST_HIB_TID) {
929 				mutex_exit(ST_MUTEX);
930 				un->un_hib_tid = timeout(st_intr_restart, un,
931 				    ST_STATUS_BUSY_TIMEOUT);
932 				mutex_enter(ST_MUTEX);
933 			}
934 
935 			ret_status = st_clear_unit_attentions(dev_instance, 5);
936 
937 			/*
938 			 * now check if we need to restore the tape position
939 			 */
940 			if ((un->un_suspend_pos.pmode != invalid) &&
941 			    ((un->un_suspend_pos.fileno > 0) ||
942 			    (un->un_suspend_pos.blkno > 0)) ||
943 			    (un->un_suspend_pos.lgclblkno > 0)) {
944 				if (ret_status != 0) {
945 					/*
946 					 * tape didn't get good TUR
947 					 * just print out error messages
948 					 */
949 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
950 					    "st_attach-RESUME: tape failure "
951 					    " tape position will be lost");
952 				} else {
953 					/* this prints errors */
954 					(void) st_validate_tapemarks(un,
955 					    st_uscsi_cmd, &un->un_suspend_pos);
956 				}
957 				/*
958 				 * there are no retries, if there is an error
959 				 * we don't know if the tape has changed
960 				 */
961 				un->un_suspend_pos.pmode = invalid;
962 			}
963 
964 			/* now we are ready to start up any queued I/Os */
965 			if (un->un_ncmds || un->un_quef) {
966 				st_start(un);
967 			}
968 
969 			cv_broadcast(&un->un_suspend_cv);
970 			mutex_exit(ST_MUTEX);
971 			return (DDI_SUCCESS);
972 
973 		default:
974 			return (DDI_FAILURE);
975 	}
976 
977 	un = ddi_get_soft_state(st_state, instance);
978 
979 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
980 	    "st_attach: instance=%x\n", instance);
981 
982 	/*
983 	 * Add a zero-length attribute to tell the world we support
984 	 * kernel ioctls (for layered drivers)
985 	 */
986 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
987 	    DDI_KERNEL_IOCTL, NULL, 0);
988 
989 	ddi_report_dev((dev_info_t *)devi);
990 
991 	/*
992 	 * If it's a SCSI-2 tape drive which supports wide,
993 	 * tell the host adapter to use wide.
994 	 */
995 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
996 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
997 
998 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
999 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1000 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
1001 	}
1002 
1003 	/*
1004 	 * enable autorequest sense; keep the rq packet around in case
1005 	 * the autorequest sense fails because of a busy condition
1006 	 * do a getcap first in case the capability is not variable
1007 	 */
1008 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
1009 		un->un_arq_enabled = 1;
1010 	} else {
1011 		un->un_arq_enabled =
1012 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
1013 	}
1014 
1015 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
1016 	    (un->un_arq_enabled ? "enabled" : "disabled"));
1017 
1018 	un->un_untagged_qing =
1019 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
1020 
1021 	/*
1022 	 * XXX - This is just for 2.6.  to tell users that write buffering
1023 	 *	has gone away.
1024 	 */
1025 	if (un->un_arq_enabled && un->un_untagged_qing) {
1026 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
1027 		    "tape-driver-buffering", 0) != 0) {
1028 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1029 			    "Write Data Buffering has been depricated. Your "
1030 			    "applications should continue to work normally.\n"
1031 			    " But, they should  ported to use Asynchronous "
1032 			    " I/O\n"
1033 			    " For more information, read about "
1034 			    " tape-driver-buffering "
1035 			    "property in the st(7d) man page\n");
1036 		}
1037 	}
1038 
1039 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
1040 	un->un_flush_on_errors = 0;
1041 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
1042 
1043 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
1044 	    "throttle=%x, max_throttle = %x\n",
1045 	    un->un_throttle, un->un_max_throttle);
1046 
1047 	/* initialize persistent errors to nil */
1048 	un->un_persistence = 0;
1049 	un->un_persist_errors = 0;
1050 
1051 	/*
1052 	 * Get dma-max from HBA driver. If it is not defined, use 64k
1053 	 */
1054 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
1055 	if (un->un_maxdma == -1) {
1056 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1057 		    "Received a value that looked like -1. Using 64k maxdma");
1058 		un->un_maxdma = (64 * ONE_K);
1059 	}
1060 
1061 #ifdef	__x86
1062 	/*
1063 	 * for x86, the device may be able to DMA more than the system will
1064 	 * allow under some circumstances. We need account for both the HBA's
1065 	 * and system's contraints.
1066 	 *
1067 	 * Get the maximum DMA under worse case conditions. e.g. looking at the
1068 	 * device constraints, the max copy buffer size, and the worse case
1069 	 * fragmentation. NOTE: this may differ from dma-max since dma-max
1070 	 * doesn't take the worse case framentation into account.
1071 	 *
1072 	 * e.g. a device may be able to DMA 16MBytes, but can only DMA 1MByte
1073 	 * if none of the pages are contiguous. Keeping track of both of these
1074 	 * values allows us to support larger tape block sizes on some devices.
1075 	 */
1076 	un->un_maxdma_arch = scsi_ifgetcap(&devp->sd_address, "dma-max-arch",
1077 	    1);
1078 
1079 	/*
1080 	 * If the dma-max-arch capability is not implemented, or the value
1081 	 * comes back higher than what was reported in dma-max, use dma-max.
1082 	 */
1083 	if ((un->un_maxdma_arch == -1) ||
1084 	    ((uint_t)un->un_maxdma < (uint_t)un->un_maxdma_arch)) {
1085 		un->un_maxdma_arch = un->un_maxdma;
1086 	}
1087 #endif
1088 
1089 	/*
1090 	 * Get the max allowable cdb size
1091 	 */
1092 	un->un_max_cdb_sz =
1093 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
1094 	if (un->un_max_cdb_sz < CDB_GROUP0) {
1095 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1096 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
1097 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
1098 	}
1099 
1100 	if (strcmp(ddi_driver_name(ddi_get_parent(ST_DEVINFO)), "scsi_vhci")) {
1101 		un->un_multipath = 0;
1102 	} else {
1103 		un->un_multipath = 1;
1104 	}
1105 
1106 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1107 
1108 	un->un_mediastate = MTIO_NONE;
1109 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1110 
1111 	/*
1112 	 * initialize kstats
1113 	 */
1114 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1115 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1116 	if (un->un_stats) {
1117 		un->un_stats->ks_lock = ST_MUTEX;
1118 		kstat_install(un->un_stats);
1119 	}
1120 	(void) st_create_errstats(un, instance);
1121 
1122 	/*
1123 	 * find the drive type for this target
1124 	 */
1125 	mutex_enter(ST_MUTEX);
1126 	un->un_dev = MTMINOR(instance);
1127 	st_known_tape_type(un);
1128 	un->un_dev = 0;
1129 	mutex_exit(ST_MUTEX);
1130 
1131 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
1132 		int minor;
1133 		char *name;
1134 
1135 		name  = st_minor_data[node_ix].name;
1136 		minor = st_minor_data[node_ix].minor;
1137 
1138 		/*
1139 		 * For default devices set the density to the
1140 		 * preferred default density for this device.
1141 		 */
1142 		if (node_ix <= DEF_BSD_NR) {
1143 			minor |= un->un_dp->default_density;
1144 		}
1145 		minor |= MTMINOR(instance);
1146 
1147 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
1148 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
1149 			continue;
1150 		}
1151 
1152 		ddi_remove_minor_node(devi, NULL);
1153 
1154 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1155 		    st_reset_notification, (caddr_t)un);
1156 		cv_destroy(&un->un_clscv);
1157 		cv_destroy(&un->un_sbuf_cv);
1158 		cv_destroy(&un->un_queue_cv);
1159 		cv_destroy(&un->un_state_cv);
1160 #ifdef	__x86
1161 		cv_destroy(&un->un_contig_mem_cv);
1162 #endif
1163 		cv_destroy(&un->un_suspend_cv);
1164 		cv_destroy(&un->un_tape_busy_cv);
1165 		cv_destroy(&un->un_recov_buf_cv);
1166 		if (un->un_recov_taskq) {
1167 			ddi_taskq_destroy(un->un_recov_taskq);
1168 		}
1169 		if (un->un_sbufp) {
1170 			freerbuf(un->un_sbufp);
1171 		}
1172 		if (un->un_recov_buf) {
1173 			freerbuf(un->un_recov_buf);
1174 		}
1175 		if (un->un_uscsi_rqs_buf) {
1176 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1177 		}
1178 		if (un->un_mspl) {
1179 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1180 		}
1181 		if (un->un_dp_size) {
1182 			kmem_free(un->un_dp, un->un_dp_size);
1183 		}
1184 		if (un->un_state) {
1185 			kstat_delete(un->un_stats);
1186 		}
1187 		if (un->un_errstats) {
1188 			kstat_delete(un->un_errstats);
1189 		}
1190 
1191 		scsi_destroy_pkt(un->un_rqs);
1192 		scsi_free_consistent_buf(un->un_rqs_bp);
1193 		ddi_soft_state_free(st_state, instance);
1194 		devp->sd_private = NULL;
1195 		devp->sd_sense = NULL;
1196 
1197 		ddi_prop_remove_all(devi);
1198 		return (DDI_FAILURE);
1199 	}
1200 
1201 	return (DDI_SUCCESS);
1202 }
1203 
1204 /*
1205  * st_detach:
1206  *
1207  * we allow a detach if and only if:
1208  *	- no tape is currently inserted
1209  *	- tape position is at BOT or unknown
1210  *		(if it is not at BOT then a no rewind
1211  *		device was opened and we have to preserve state)
1212  *	- it must be in a closed state : no timeouts or scsi_watch requests
1213  *		will exist if it is closed, so we don't need to check for
1214  *		them here.
1215  */
1216 /*ARGSUSED*/
1217 static int
1218 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1219 {
1220 	int instance;
1221 	int result;
1222 	struct scsi_device *devp;
1223 	struct scsi_tape *un;
1224 	clock_t wait_cmds_complete;
1225 
1226 	ST_ENTR(devi, st_detach);
1227 
1228 	instance = ddi_get_instance(devi);
1229 
1230 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1231 		return (DDI_FAILURE);
1232 	}
1233 
1234 	mutex_enter(ST_MUTEX);
1235 
1236 	/*
1237 	 * Clear error entry stack
1238 	 */
1239 	st_empty_error_stack(un);
1240 
1241 	mutex_exit(ST_MUTEX);
1242 
1243 	switch (cmd) {
1244 
1245 	case DDI_DETACH:
1246 		/*
1247 		 * Undo what we did in st_attach & st_doattach,
1248 		 * freeing resources and removing things we installed.
1249 		 * The system framework guarantees we are not active
1250 		 * with this devinfo node in any other entry points at
1251 		 * this time.
1252 		 */
1253 
1254 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1255 		    "st_detach: instance=%x, un=%p\n", instance,
1256 		    (void *)un);
1257 
1258 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1259 		    ((un->un_rsvd_status & ST_APPLICATION_RESERVATIONS) != 0) ||
1260 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1261 		    (un->un_state != ST_STATE_CLOSED)) {
1262 			/*
1263 			 * we cannot unload some targets because the
1264 			 * inquiry returns junk unless immediately
1265 			 * after a reset
1266 			 */
1267 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1268 			    "cannot unload instance %x\n", instance);
1269 			un->un_unit_attention_flags |= 4;
1270 			return (DDI_FAILURE);
1271 		}
1272 
1273 		/*
1274 		 * if the tape has been removed then we may unload;
1275 		 * do a test unit ready and if it returns NOT READY
1276 		 * then we assume that it is safe to unload.
1277 		 * as a side effect, pmode may be set to invalid if the
1278 		 * the test unit ready fails;
1279 		 * also un_state may be set to non-closed, so reset it
1280 		 */
1281 		if ((un->un_dev) &&		/* Been opened since attach */
1282 		    ((un->un_pos.pmode == legacy) &&
1283 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1284 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1285 		    ((un->un_pos.pmode == logical) &&
1286 		    (un->un_pos.lgclblkno > 0))) {
1287 			mutex_enter(ST_MUTEX);
1288 			/*
1289 			 * Send Test Unit Ready in the hopes that if
1290 			 * the drive is not in the state we think it is.
1291 			 * And the state will be changed so it can be detached.
1292 			 * If the command fails to reach the device and
1293 			 * the drive was not rewound or unloaded we want
1294 			 * to fail the detach till a user command fails
1295 			 * where after the detach will succead.
1296 			 */
1297 			result = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
1298 			/*
1299 			 * After TUR un_state may be set to non-closed,
1300 			 * so reset it back.
1301 			 */
1302 			un->un_state = ST_STATE_CLOSED;
1303 			mutex_exit(ST_MUTEX);
1304 		}
1305 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1306 		    "un_status=%x, fileno=%x, blkno=%x\n",
1307 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1308 
1309 		/*
1310 		 * check again:
1311 		 * if we are not at BOT then it is not safe to unload
1312 		 */
1313 		if ((un->un_dev) &&		/* Been opened since attach */
1314 		    (result != EACCES) &&	/* drive is use by somebody */
1315 		    ((((un->un_pos.pmode == legacy) &&
1316 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1317 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1318 		    ((un->un_pos.pmode == logical) &&
1319 		    (un->un_pos.lgclblkno > 0))) &&
1320 		    ((un->un_state == ST_STATE_CLOSED) &&
1321 		    (un->un_laststate == ST_STATE_CLOSING)))) {
1322 
1323 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1324 			    "cannot detach: pmode=%d fileno=0x%x, blkno=0x%x"
1325 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1326 			    un->un_pos.fileno, un->un_pos.blkno,
1327 			    un->un_pos.lgclblkno);
1328 			un->un_unit_attention_flags |= 4;
1329 			return (DDI_FAILURE);
1330 		}
1331 
1332 		/*
1333 		 * Just To make sure that we have released the
1334 		 * tape unit .
1335 		 */
1336 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1337 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1338 			mutex_enter(ST_MUTEX);
1339 			(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
1340 			mutex_exit(ST_MUTEX);
1341 		}
1342 
1343 		/*
1344 		 * now remove other data structures allocated in st_doattach()
1345 		 */
1346 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1347 		    "destroying/freeing\n");
1348 
1349 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1350 		    st_reset_notification, (caddr_t)un);
1351 		cv_destroy(&un->un_clscv);
1352 		cv_destroy(&un->un_sbuf_cv);
1353 		cv_destroy(&un->un_queue_cv);
1354 		cv_destroy(&un->un_suspend_cv);
1355 		cv_destroy(&un->un_tape_busy_cv);
1356 		cv_destroy(&un->un_recov_buf_cv);
1357 
1358 		if (un->un_recov_taskq) {
1359 			ddi_taskq_destroy(un->un_recov_taskq);
1360 		}
1361 
1362 		if (un->un_hib_tid) {
1363 			(void) untimeout(un->un_hib_tid);
1364 			un->un_hib_tid = 0;
1365 		}
1366 
1367 		if (un->un_delay_tid) {
1368 			(void) untimeout(un->un_delay_tid);
1369 			un->un_delay_tid = 0;
1370 		}
1371 		cv_destroy(&un->un_state_cv);
1372 
1373 #ifdef	__x86
1374 		cv_destroy(&un->un_contig_mem_cv);
1375 
1376 		if (un->un_contig_mem_hdl != NULL) {
1377 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1378 		}
1379 #endif
1380 		if (un->un_sbufp) {
1381 			freerbuf(un->un_sbufp);
1382 		}
1383 		if (un->un_recov_buf) {
1384 			freerbuf(un->un_recov_buf);
1385 		}
1386 		if (un->un_uscsi_rqs_buf) {
1387 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1388 		}
1389 		if (un->un_mspl) {
1390 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1391 		}
1392 		if (un->un_rqs) {
1393 			scsi_destroy_pkt(un->un_rqs);
1394 			scsi_free_consistent_buf(un->un_rqs_bp);
1395 		}
1396 		if (un->un_mkr_pkt) {
1397 			scsi_destroy_pkt(un->un_mkr_pkt);
1398 		}
1399 		if (un->un_arq_enabled) {
1400 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1401 		}
1402 		if (un->un_dp_size) {
1403 			kmem_free(un->un_dp, un->un_dp_size);
1404 		}
1405 		if (un->un_stats) {
1406 			kstat_delete(un->un_stats);
1407 			un->un_stats = (kstat_t *)0;
1408 		}
1409 		if (un->un_errstats) {
1410 			kstat_delete(un->un_errstats);
1411 			un->un_errstats = (kstat_t *)0;
1412 		}
1413 		if (un->un_media_id_len) {
1414 			kmem_free(un->un_media_id, un->un_media_id_len);
1415 		}
1416 		devp = ST_SCSI_DEVP;
1417 		ddi_soft_state_free(st_state, instance);
1418 		devp->sd_private = NULL;
1419 		devp->sd_sense = NULL;
1420 		scsi_unprobe(devp);
1421 		ddi_prop_remove_all(devi);
1422 		ddi_remove_minor_node(devi, NULL);
1423 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1424 		return (DDI_SUCCESS);
1425 
1426 	case DDI_SUSPEND:
1427 
1428 		/*
1429 		 * Suspend/Resume
1430 		 *
1431 		 * To process DDI_SUSPEND, we must do the following:
1432 		 *
1433 		 *  - check ddi_removing_power to see if power will be turned
1434 		 *    off. if so, return DDI_FAILURE
1435 		 *  - check if we are already suspended,
1436 		 *    if so, return DDI_FAILURE
1437 		 *  - check if device state is CLOSED,
1438 		 *    if not, return DDI_FAILURE.
1439 		 *  - wait until outstanding operations complete
1440 		 *  - save tape state
1441 		 *  - block new operations
1442 		 *  - cancel pending timeouts
1443 		 *
1444 		 */
1445 
1446 		if (ddi_removing_power(devi)) {
1447 			return (DDI_FAILURE);
1448 		}
1449 
1450 		if (un->un_dev == 0)
1451 			un->un_dev = MTMINOR(instance);
1452 
1453 		mutex_enter(ST_MUTEX);
1454 
1455 		/*
1456 		 * Shouldn't already be suspended, if so return failure
1457 		 */
1458 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1459 			mutex_exit(ST_MUTEX);
1460 			return (DDI_FAILURE);
1461 		}
1462 		if (un->un_state != ST_STATE_CLOSED) {
1463 			mutex_exit(ST_MUTEX);
1464 			return (DDI_FAILURE);
1465 		}
1466 
1467 		/*
1468 		 * Wait for all outstanding I/O's to complete
1469 		 *
1470 		 * we wait on both ncmds and the wait queue for times
1471 		 * when we are flushing after persistent errors are
1472 		 * flagged, which is when ncmds can be 0, and the
1473 		 * queue can still have I/O's.  This way we preserve
1474 		 * order of biodone's.
1475 		 */
1476 		wait_cmds_complete = ddi_get_lbolt();
1477 		wait_cmds_complete +=
1478 		    st_wait_cmds_complete * drv_usectohz(1000000);
1479 		while (un->un_ncmds || un->un_quef ||
1480 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1481 
1482 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1483 			    wait_cmds_complete) == -1) {
1484 				/*
1485 				 * Time expired then cancel the command
1486 				 */
1487 				if (st_reset(un, RESET_LUN) == 0) {
1488 					if (un->un_last_throttle) {
1489 						un->un_throttle =
1490 						    un->un_last_throttle;
1491 					}
1492 					mutex_exit(ST_MUTEX);
1493 					return (DDI_FAILURE);
1494 				} else {
1495 					break;
1496 				}
1497 			}
1498 		}
1499 
1500 		/*
1501 		 * DDI_SUSPEND says that the system "may" power down, we
1502 		 * remember the file and block number before rewinding.
1503 		 * we also need to save state before issuing
1504 		 * any WRITE_FILE_MARK command.
1505 		 */
1506 		(void) st_update_block_pos(un, st_cmd, 0);
1507 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1508 
1509 
1510 		/*
1511 		 * Issue a zero write file fmk command to tell the drive to
1512 		 * flush any buffered tape marks
1513 		 */
1514 		(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1515 
1516 		/*
1517 		 * Because not all tape drives correctly implement buffer
1518 		 * flushing with the zero write file fmk command, issue a
1519 		 * synchronous rewind command to force data flushing.
1520 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1521 		 * anyway.
1522 		 */
1523 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
1524 
1525 		/* stop any new operations */
1526 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1527 		un->un_throttle = 0;
1528 
1529 		/*
1530 		 * cancel any outstanding timeouts
1531 		 */
1532 		if (un->un_delay_tid) {
1533 			timeout_id_t temp_id = un->un_delay_tid;
1534 			un->un_delay_tid = 0;
1535 			un->un_tids_at_suspend |= ST_DELAY_TID;
1536 			mutex_exit(ST_MUTEX);
1537 			(void) untimeout(temp_id);
1538 			mutex_enter(ST_MUTEX);
1539 		}
1540 
1541 		if (un->un_hib_tid) {
1542 			timeout_id_t temp_id = un->un_hib_tid;
1543 			un->un_hib_tid = 0;
1544 			un->un_tids_at_suspend |= ST_HIB_TID;
1545 			mutex_exit(ST_MUTEX);
1546 			(void) untimeout(temp_id);
1547 			mutex_enter(ST_MUTEX);
1548 		}
1549 
1550 		/*
1551 		 * Suspend the scsi_watch_thread
1552 		 */
1553 		if (un->un_swr_token) {
1554 			opaque_t temp_token = un->un_swr_token;
1555 			mutex_exit(ST_MUTEX);
1556 			scsi_watch_suspend(temp_token);
1557 		} else {
1558 			mutex_exit(ST_MUTEX);
1559 		}
1560 
1561 		return (DDI_SUCCESS);
1562 
1563 	default:
1564 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1565 		return (DDI_FAILURE);
1566 	}
1567 }
1568 
1569 
1570 /* ARGSUSED */
1571 static int
1572 st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1573 {
1574 	dev_t dev;
1575 	struct scsi_tape *un;
1576 	int instance, error;
1577 
1578 	ST_ENTR(dip, st_info);
1579 
1580 	switch (infocmd) {
1581 	case DDI_INFO_DEVT2DEVINFO:
1582 		dev = (dev_t)arg;
1583 		instance = MTUNIT(dev);
1584 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1585 			return (DDI_FAILURE);
1586 		*result = (void *) ST_DEVINFO;
1587 		error = DDI_SUCCESS;
1588 		break;
1589 	case DDI_INFO_DEVT2INSTANCE:
1590 		dev = (dev_t)arg;
1591 		instance = MTUNIT(dev);
1592 		*result = (void *)(uintptr_t)instance;
1593 		error = DDI_SUCCESS;
1594 		break;
1595 	default:
1596 		error = DDI_FAILURE;
1597 	}
1598 	return (error);
1599 }
1600 
1601 static int
1602 st_doattach(struct scsi_device *devp, int (*canwait)())
1603 {
1604 	struct scsi_tape *un = NULL;
1605 	recov_info *ri;
1606 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1607 	int instance;
1608 	size_t rlen;
1609 
1610 	ST_FUNC(devp->sd_dev, st_doattach);
1611 	/*
1612 	 * Call the routine scsi_probe to do some of the dirty work.
1613 	 * If the INQUIRY command succeeds, the field sd_inq in the
1614 	 * device structure will be filled in.
1615 	 */
1616 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1617 	    "st_doattach(): probing\n");
1618 
1619 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1620 
1621 		/*
1622 		 * In checking the whole inq_dtype byte we are looking at both
1623 		 * the Peripheral Qualifier and the Peripheral Device Type.
1624 		 * For this driver we are only interested in sequential devices
1625 		 * that are connected or capable if connecting to this logical
1626 		 * unit.
1627 		 */
1628 		if (devp->sd_inq->inq_dtype ==
1629 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1630 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1631 			    "probe exists\n");
1632 		} else {
1633 			/* Something there but not a tape device */
1634 			scsi_unprobe(devp);
1635 			return (DDI_FAILURE);
1636 		}
1637 	} else {
1638 		/* Nothing there */
1639 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1640 		    "probe failure: nothing there\n");
1641 		scsi_unprobe(devp);
1642 		return (DDI_FAILURE);
1643 	}
1644 
1645 
1646 	/*
1647 	 * The actual unit is present.
1648 	 * Now is the time to fill in the rest of our info..
1649 	 */
1650 	instance = ddi_get_instance(devp->sd_dev);
1651 
1652 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1653 		goto error;
1654 	}
1655 	un = ddi_get_soft_state(st_state, instance);
1656 
1657 	ASSERT(un != NULL);
1658 
1659 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
1660 	    MAX_SENSE_LENGTH, B_READ, canwait, NULL);
1661 	if (un->un_rqs_bp == NULL) {
1662 		goto error;
1663 	}
1664 	un->un_rqs = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
1665 	    CDB_GROUP0, 1, st_recov_sz, PKT_CONSISTENT, canwait, NULL);
1666 	if (!un->un_rqs) {
1667 		goto error;
1668 	}
1669 	ASSERT(un->un_rqs->pkt_resid == 0);
1670 	devp->sd_sense =
1671 	    (struct scsi_extended_sense *)un->un_rqs_bp->b_un.b_addr;
1672 	ASSERT(geterror(un->un_rqs_bp) == NULL);
1673 
1674 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs->pkt_cdbp,
1675 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
1676 	FILL_SCSI1_LUN(devp, un->un_rqs);
1677 	un->un_rqs->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1678 	un->un_rqs->pkt_time = st_io_time;
1679 	un->un_rqs->pkt_comp = st_intr;
1680 	ri = (recov_info *)un->un_rqs->pkt_private;
1681 	if (st_recov_sz == sizeof (recov_info)) {
1682 		ri->privatelen = sizeof (recov_info);
1683 	} else {
1684 		ri->privatelen = sizeof (pkt_info);
1685 	}
1686 
1687 	un->un_sbufp = getrbuf(km_flags);
1688 	un->un_recov_buf = getrbuf(km_flags);
1689 
1690 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1691 
1692 	/*
1693 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1694 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1695 	 * is obsolete and we want more flexibility in controlling the DMA
1696 	 * address constraints.
1697 	 */
1698 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1699 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1700 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1701 
1702 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1703 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1704 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1705 
1706 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1707 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1708 		    "probe partial failure: no space\n");
1709 		goto error;
1710 	}
1711 
1712 	bzero(un->un_mspl, sizeof (struct seq_mode));
1713 
1714 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1715 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1716 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1717 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1718 #ifdef	__x86
1719 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1720 #endif
1721 
1722 	/* Initialize power managemnet condition variable */
1723 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1724 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1725 	cv_init(&un->un_recov_buf_cv, NULL, CV_DRIVER, NULL);
1726 
1727 	un->un_recov_taskq = ddi_taskq_create(devp->sd_dev,
1728 	    "un_recov_taskq", 1, TASKQ_DEFAULTPRI, km_flags);
1729 
1730 	ASSERT(un->un_recov_taskq != NULL);
1731 
1732 	un->un_pos.pmode = invalid;
1733 	un->un_sd	= devp;
1734 	un->un_swr_token = (opaque_t)NULL;
1735 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1736 	un->un_wormable = st_is_drive_worm;
1737 	un->un_media_id_method = st_get_media_identification;
1738 	/*
1739 	 * setting long a initial as it contains logical file info.
1740 	 * support for long format is mandatory but many drive don't do it.
1741 	 */
1742 	un->un_read_pos_type = LONG_POS;
1743 
1744 	un->un_suspend_pos.pmode = invalid;
1745 
1746 	st_add_recovery_info_to_pkt(un, un->un_rqs_bp, un->un_rqs);
1747 
1748 #ifdef	__x86
1749 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1750 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1751 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1752 		    "allocation of contiguous memory dma handle failed!");
1753 		un->un_contig_mem_hdl = NULL;
1754 		goto error;
1755 	}
1756 #endif
1757 
1758 	/*
1759 	 * Since this driver manages devices with "remote" hardware,
1760 	 * i.e. the devices themselves have no "reg" properties,
1761 	 * the SUSPEND/RESUME commands in detach/attach will not be
1762 	 * called by the power management framework unless we request
1763 	 * it by creating a "pm-hardware-state" property and setting it
1764 	 * to value "needs-suspend-resume".
1765 	 */
1766 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1767 	    "pm-hardware-state", "needs-suspend-resume") !=
1768 	    DDI_PROP_SUCCESS) {
1769 
1770 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1771 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1772 		goto error;
1773 	}
1774 
1775 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1776 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1777 
1778 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1779 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1780 		    "failed\n");
1781 		goto error;
1782 	}
1783 
1784 	(void) scsi_reset_notify(ROUTE, SCSI_RESET_NOTIFY,
1785 	    st_reset_notification, (caddr_t)un);
1786 
1787 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "attach success\n");
1788 	return (DDI_SUCCESS);
1789 
1790 error:
1791 	devp->sd_sense = NULL;
1792 
1793 	ddi_remove_minor_node(devp->sd_dev, NULL);
1794 	if (un) {
1795 		if (un->un_mspl) {
1796 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1797 		}
1798 		if (un->un_read_pos_data) {
1799 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1800 		}
1801 		if (un->un_sbufp) {
1802 			freerbuf(un->un_sbufp);
1803 		}
1804 		if (un->un_recov_buf) {
1805 			freerbuf(un->un_recov_buf);
1806 		}
1807 		if (un->un_uscsi_rqs_buf) {
1808 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1809 		}
1810 #ifdef	__x86
1811 		if (un->un_contig_mem_hdl != NULL) {
1812 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1813 		}
1814 #endif
1815 		if (un->un_rqs) {
1816 			scsi_destroy_pkt(un->un_rqs);
1817 		}
1818 
1819 		if (un->un_rqs_bp) {
1820 			scsi_free_consistent_buf(un->un_rqs_bp);
1821 		}
1822 
1823 		ddi_soft_state_free(st_state, instance);
1824 		devp->sd_private = NULL;
1825 	}
1826 
1827 	if (devp->sd_inq) {
1828 		scsi_unprobe(devp);
1829 	}
1830 	return (DDI_FAILURE);
1831 }
1832 
1833 typedef int
1834 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1835 
1836 static cfg_functp config_functs[] = {
1837 	st_get_conf_from_st_dot_conf,
1838 	st_get_conf_from_st_conf_dot_c,
1839 	st_get_conf_from_tape_drive,
1840 	st_get_default_conf
1841 };
1842 
1843 
1844 /*
1845  * determine tape type, using tape-config-list or built-in table or
1846  * use a generic tape config entry
1847  */
1848 static void
1849 st_known_tape_type(struct scsi_tape *un)
1850 {
1851 	struct st_drivetype *dp;
1852 	cfg_functp *config_funct;
1853 	uchar_t reserved;
1854 
1855 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1856 
1857 	reserved = (un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1858 	    : ST_RELEASE;
1859 
1860 	/*
1861 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1862 	 *	 no vid & pid inquiry data.  So, we provide one.
1863 	 */
1864 	if (ST_INQUIRY->inq_len == 0 ||
1865 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1866 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1867 	}
1868 
1869 	if (un->un_dp_size == 0) {
1870 		un->un_dp_size = sizeof (struct st_drivetype);
1871 		dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1872 		un->un_dp = dp;
1873 	} else {
1874 		dp = un->un_dp;
1875 	}
1876 
1877 	un->un_dp->non_motion_timeout = st_io_time;
1878 	/*
1879 	 * Loop through the configuration methods till one works.
1880 	 */
1881 	for (config_funct = &config_functs[0]; ; config_funct++) {
1882 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1883 			break;
1884 		}
1885 	}
1886 
1887 	/*
1888 	 * If we didn't just make up this configuration and
1889 	 * all the density codes are the same..
1890 	 * Set Auto Density over ride.
1891 	 */
1892 	if (*config_funct != st_get_default_conf) {
1893 		/*
1894 		 * If this device is one that is configured and all
1895 		 * densities are the same, This saves doing gets and set
1896 		 * that yield nothing.
1897 		 */
1898 		if ((dp->densities[0]) == (dp->densities[1]) &&
1899 		    (dp->densities[0]) == (dp->densities[2]) &&
1900 		    (dp->densities[0]) == (dp->densities[3])) {
1901 
1902 			dp->options |= ST_AUTODEN_OVERRIDE;
1903 		}
1904 	}
1905 
1906 
1907 	/*
1908 	 * Store tape drive characteristics.
1909 	 */
1910 	un->un_status = 0;
1911 	un->un_attached = 1;
1912 	un->un_init_options = dp->options;
1913 
1914 	/* setup operation time-outs based on options */
1915 	st_calculate_timeouts(un);
1916 
1917 	/* TLR support */
1918 	if (un->un_dp->type != ST_TYPE_INVALID) {
1919 		int result;
1920 
1921 		/* try and enable TLR */
1922 		un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
1923 		result = st_set_target_TLR_mode(un, st_uscsi_cmd);
1924 		if (result == EACCES) {
1925 			/*
1926 			 * From attach command failed.
1927 			 * Set dp type so is run again on open.
1928 			 */
1929 			un->un_dp->type = ST_TYPE_INVALID;
1930 			un->un_tlr_flag = TLR_NOT_KNOWN;
1931 		} else if (result == 0) {
1932 			if (scsi_ifgetcap(&un->un_sd->sd_address,
1933 			    "tran-layer-retries", 1) == -1) {
1934 				un->un_tlr_flag = TLR_NOT_SUPPORTED;
1935 				(void) st_set_target_TLR_mode(un, st_uscsi_cmd);
1936 			} else {
1937 				un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
1938 			}
1939 		} else {
1940 			un->un_tlr_flag = TLR_NOT_SUPPORTED;
1941 		}
1942 	}
1943 
1944 	/* make sure if we are supposed to be variable, make it variable */
1945 	if (dp->options & ST_VARIABLE) {
1946 		dp->bsize = 0;
1947 	}
1948 
1949 	if (reserved != ((un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1950 	    : ST_RELEASE)) {
1951 		(void) st_reserve_release(un, reserved, st_uscsi_cmd);
1952 	}
1953 
1954 	un->un_unit_attention_flags |= 1;
1955 
1956 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1957 
1958 }
1959 
1960 
1961 typedef struct {
1962 	int mask;
1963 	int bottom;
1964 	int top;
1965 	char *name;
1966 } conf_limit;
1967 
1968 static const conf_limit conf_limits[] = {
1969 
1970 	-1,		1,		2,		"conf version",
1971 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1972 	-1,		0,		0xffffff,	"block size",
1973 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1974 	-1,		0,		4,		"number of densities",
1975 	-1,		0,		UINT8_MAX,	"density code",
1976 	-1,		0,		3,		"default density",
1977 	-1,		0,		UINT16_MAX,	"non motion timeout",
1978 	-1,		0,		UINT16_MAX,	"I/O timeout",
1979 	-1,		0,		UINT16_MAX,	"space timeout",
1980 	-1,		0,		UINT16_MAX,	"load timeout",
1981 	-1,		0,		UINT16_MAX,	"unload timeout",
1982 	-1,		0,		UINT16_MAX,	"erase timeout",
1983 	0,		0,		0,		NULL
1984 };
1985 
1986 static int
1987 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1988     const char *conf_name)
1989 {
1990 	int dens;
1991 	int ndens;
1992 	int value;
1993 	int type;
1994 	int count;
1995 	const conf_limit *limit = &conf_limits[0];
1996 
1997 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1998 
1999 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
2000 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
2001 
2002 	count = list_len;
2003 	type = *list;
2004 	for (;  count && limit->name; count--, list++, limit++) {
2005 
2006 		value = *list;
2007 		if (value & ~limit->mask) {
2008 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2009 			    "%s %s value invalid bits set: 0x%X\n",
2010 			    conf_name, limit->name, value & ~limit->mask);
2011 			*list &= limit->mask;
2012 		} else if (value < limit->bottom) {
2013 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2014 			    "%s %s value too low: value = %d limit %d\n",
2015 			    conf_name, limit->name, value, limit->bottom);
2016 		} else if (value > limit->top) {
2017 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2018 			    "%s %s value too high: value = %d limit %d\n",
2019 			    conf_name, limit->name, value, limit->top);
2020 		} else {
2021 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2022 			    "%s %s value = 0x%X\n",
2023 			    conf_name, limit->name, value);
2024 		}
2025 
2026 		/* If not the number of densities continue */
2027 		if (limit != &conf_limits[4]) {
2028 			continue;
2029 		}
2030 
2031 		/* If number of densities is not in range can't use config */
2032 		if (value < limit->bottom || value > limit->top) {
2033 			return (-1);
2034 		}
2035 
2036 		ndens = min(value, NDENSITIES);
2037 		if ((type == 1) && (list_len - ndens) != 6) {
2038 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2039 			    "%s conf version 1 with %d densities has %d items"
2040 			    " should have %d",
2041 			    conf_name, ndens, list_len, 6 + ndens);
2042 		} else if ((type == 2) && (list_len - ndens) != 13) {
2043 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2044 			    "%s conf version 2 with %d densities has %d items"
2045 			    " should have %d",
2046 			    conf_name, ndens, list_len, 13 + ndens);
2047 		}
2048 
2049 		limit++;
2050 		for (dens = 0; dens < ndens && count; dens++) {
2051 			count--;
2052 			list++;
2053 			value = *list;
2054 			if (value < limit->bottom) {
2055 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2056 				    "%s density[%d] value too low: value ="
2057 				    " 0x%X limit 0x%X\n",
2058 				    conf_name, dens, value, limit->bottom);
2059 			} else if (value > limit->top) {
2060 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2061 				    "%s density[%d] value too high: value ="
2062 				    " 0x%X limit 0x%X\n",
2063 				    conf_name, dens, value, limit->top);
2064 			} else {
2065 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2066 				    "%s density[%d] value = 0x%X\n",
2067 				    conf_name, dens, value);
2068 			}
2069 		}
2070 	}
2071 
2072 	return (0);
2073 }
2074 
2075 static int
2076 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
2077     struct st_drivetype *dp)
2078 {
2079 	caddr_t config_list = NULL;
2080 	caddr_t data_list = NULL;
2081 	int	*data_ptr;
2082 	caddr_t vidptr, prettyptr, datanameptr;
2083 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
2084 	int config_list_len, data_list_len, len, i;
2085 	int version;
2086 	int found = 0;
2087 
2088 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
2089 
2090 	/*
2091 	 * Determine type of tape controller. Type is determined by
2092 	 * checking the vendor ids of the earlier inquiry command and
2093 	 * comparing those with vids in tape-config-list defined in st.conf
2094 	 */
2095 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
2096 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
2097 	    != DDI_PROP_SUCCESS) {
2098 		return (found);
2099 	}
2100 
2101 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2102 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
2103 
2104 	/*
2105 	 * Compare vids in each triplet - if it matches, get value for
2106 	 * data_name and contruct a st_drivetype struct
2107 	 * tripletlen is not set yet!
2108 	 */
2109 	for (len = config_list_len, vidptr = config_list;
2110 	    len > 0;
2111 	    vidptr += tripletlen, len -= tripletlen) {
2112 
2113 		vidlen = strlen(vidptr);
2114 		prettyptr = vidptr + vidlen + 1;
2115 		prettylen = strlen(prettyptr);
2116 		datanameptr = prettyptr + prettylen + 1;
2117 		datanamelen = strlen(datanameptr);
2118 		tripletlen = vidlen + prettylen + datanamelen + 3;
2119 
2120 		if (vidlen == 0) {
2121 			continue;
2122 		}
2123 
2124 		/*
2125 		 * If inquiry vid dosen't match this triplets vid,
2126 		 * try the next.
2127 		 */
2128 		if (strncasecmp(vidpid, vidptr, vidlen)) {
2129 			continue;
2130 		}
2131 
2132 		/*
2133 		 * if prettylen is zero then use the vid string
2134 		 */
2135 		if (prettylen == 0) {
2136 			prettyptr = vidptr;
2137 			prettylen = vidlen;
2138 		}
2139 
2140 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2141 		    "vid = %s, pretty=%s, dataname = %s\n",
2142 		    vidptr, prettyptr, datanameptr);
2143 
2144 		/*
2145 		 * get the data list
2146 		 */
2147 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
2148 		    datanameptr, (caddr_t)&data_list,
2149 		    &data_list_len) != DDI_PROP_SUCCESS) {
2150 			/*
2151 			 * Error in getting property value
2152 			 * print warning!
2153 			 */
2154 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2155 			    "data property (%s) has no value\n",
2156 			    datanameptr);
2157 			continue;
2158 		}
2159 
2160 		/*
2161 		 * now initialize the st_drivetype struct
2162 		 */
2163 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
2164 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
2165 		(void) strncpy(dp->vid, vidptr, dp->length);
2166 		data_ptr = (int *)data_list;
2167 		/*
2168 		 * check if data is enough for version, type,
2169 		 * bsize, options, # of densities, density1,
2170 		 * density2, ..., default_density
2171 		 */
2172 		if ((data_list_len < 5 * sizeof (int)) ||
2173 		    (data_list_len < 6 * sizeof (int) +
2174 		    *(data_ptr + 4) * sizeof (int))) {
2175 			/*
2176 			 * print warning and skip to next triplet.
2177 			 */
2178 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2179 			    "data property (%s) incomplete\n",
2180 			    datanameptr);
2181 			kmem_free(data_list, data_list_len);
2182 			continue;
2183 		}
2184 
2185 		if (st_validate_conf_data(un, data_ptr,
2186 		    data_list_len / sizeof (int), datanameptr)) {
2187 			kmem_free(data_list, data_list_len);
2188 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2189 			    "data property (%s) rejected\n",
2190 			    datanameptr);
2191 			continue;
2192 		}
2193 
2194 		/*
2195 		 * check version
2196 		 */
2197 		version = *data_ptr++;
2198 		if (version != 1 && version != 2) {
2199 			/* print warning but accept it */
2200 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2201 			    "Version # for data property (%s) "
2202 			    "not set to 1 or 2\n", datanameptr);
2203 		}
2204 
2205 		dp->type    = *data_ptr++;
2206 		dp->bsize   = *data_ptr++;
2207 		dp->options = *data_ptr++;
2208 		dp->options |= ST_DYNAMIC;
2209 		len = *data_ptr++;
2210 		for (i = 0; i < NDENSITIES; i++) {
2211 			if (i < len) {
2212 				dp->densities[i] = *data_ptr++;
2213 			}
2214 		}
2215 		dp->default_density = *data_ptr << 3;
2216 		if (version == 2 &&
2217 		    data_list_len >= (13 + len) * sizeof (int)) {
2218 			data_ptr++;
2219 			dp->non_motion_timeout	= *data_ptr++;
2220 			dp->io_timeout		= *data_ptr++;
2221 			dp->rewind_timeout	= *data_ptr++;
2222 			dp->space_timeout	= *data_ptr++;
2223 			dp->load_timeout	= *data_ptr++;
2224 			dp->unload_timeout	= *data_ptr++;
2225 			dp->erase_timeout	= *data_ptr++;
2226 		}
2227 		kmem_free(data_list, data_list_len);
2228 		found = 1;
2229 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2230 		    "found in st.conf: vid = %s, pretty=%s\n",
2231 		    dp->vid, dp->name);
2232 		break;
2233 	}
2234 
2235 	/*
2236 	 * free up the memory allocated by ddi_getlongprop
2237 	 */
2238 	if (config_list) {
2239 		kmem_free(config_list, config_list_len);
2240 	}
2241 	return (found);
2242 }
2243 
2244 static int
2245 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2246     struct st_drivetype *dp)
2247 {
2248 	int i;
2249 
2250 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2251 	/*
2252 	 * Determine type of tape controller.  Type is determined by
2253 	 * checking the result of the earlier inquiry command and
2254 	 * comparing vendor ids with strings in a table declared in st_conf.c.
2255 	 */
2256 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2257 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2258 
2259 	for (i = 0; i < st_ndrivetypes; i++) {
2260 		if (st_drivetypes[i].length == 0) {
2261 			continue;
2262 		}
2263 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2264 		    st_drivetypes[i].length)) {
2265 			continue;
2266 		}
2267 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2268 		return (1);
2269 	}
2270 	return (0);
2271 }
2272 
2273 static int
2274 st_get_conf_from_tape_drive(struct scsi_tape *un, char *vidpid,
2275     struct st_drivetype *dp)
2276 {
2277 	int bsize;
2278 	ulong_t maxbsize;
2279 	caddr_t buf;
2280 	struct st_drivetype *tem_dp;
2281 	struct read_blklim *blklim;
2282 	int rval;
2283 	int i;
2284 
2285 	ST_FUNC(ST_DEVINFO, st_get_conf_from_tape_drive);
2286 
2287 	/*
2288 	 * Determine the type of tape controller. Type is determined by
2289 	 * sending SCSI commands to tape drive and deriving the type from
2290 	 * the returned data.
2291 	 */
2292 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2293 	    "st_get_conf_from_tape_drive(): asking tape drive\n");
2294 
2295 	tem_dp = kmem_zalloc(sizeof (struct st_drivetype), KM_SLEEP);
2296 
2297 	/*
2298 	 * Make up a name
2299 	 */
2300 	bcopy(vidpid, tem_dp->name, VIDPIDLEN);
2301 	tem_dp->name[VIDPIDLEN] = '\0';
2302 	tem_dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2303 	(void) strncpy(tem_dp->vid, ST_INQUIRY->inq_vid, tem_dp->length);
2304 	/*
2305 	 * 'clean' vendor and product strings of non-printing chars
2306 	 */
2307 	for (i = 0; i < VIDPIDLEN - 1; i ++) {
2308 		if (tem_dp->name[i] < ' ' || tem_dp->name[i] > '~') {
2309 			tem_dp->name[i] = '.';
2310 		}
2311 	}
2312 
2313 	/*
2314 	 * MODE SENSE to determine block size.
2315 	 */
2316 	un->un_dp->options |= ST_MODE_SEL_COMP | ST_UNLOADABLE;
2317 	rval = st_modesense(un);
2318 	if (rval) {
2319 		if (rval == EACCES) {
2320 			un->un_dp->type = ST_TYPE_INVALID;
2321 			rval = 1;
2322 		} else {
2323 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
2324 			rval = 0;
2325 		}
2326 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2327 		    "st_get_conf_from_tape_drive(): fail to mode sense\n");
2328 		goto exit;
2329 	}
2330 
2331 	/* Can mode sense page 0x10 or 0xf */
2332 	tem_dp->options |= ST_MODE_SEL_COMP;
2333 	bsize = (un->un_mspl->high_bl << 16)	|
2334 	    (un->un_mspl->mid_bl << 8)		|
2335 	    (un->un_mspl->low_bl);
2336 
2337 	if (bsize == 0) {
2338 		tem_dp->options |= ST_VARIABLE;
2339 		tem_dp->bsize = 0;
2340 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
2341 		rval = st_change_block_size(un, 0);
2342 		if (rval) {
2343 			if (rval == EACCES) {
2344 				un->un_dp->type = ST_TYPE_INVALID;
2345 				rval = 1;
2346 			} else {
2347 				rval = 0;
2348 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2349 				    "st_get_conf_from_tape_drive(): "
2350 				    "Fixed record size is too large and"
2351 				    "cannot switch to variable record size");
2352 			}
2353 			goto exit;
2354 		}
2355 		tem_dp->options |= ST_VARIABLE;
2356 	} else {
2357 		rval = st_change_block_size(un, 0);
2358 		if (rval == 0) {
2359 			tem_dp->options |= ST_VARIABLE;
2360 			tem_dp->bsize = 0;
2361 		} else if (rval != EACCES) {
2362 			tem_dp->bsize = bsize;
2363 		} else {
2364 			un->un_dp->type = ST_TYPE_INVALID;
2365 			rval = 1;
2366 			goto exit;
2367 		}
2368 	}
2369 
2370 	/*
2371 	 * If READ BLOCk LIMITS works and upper block size limit is
2372 	 * more than 64K, ST_NO_RECSIZE_LIMIT is supported.
2373 	 */
2374 	blklim = kmem_zalloc(sizeof (struct read_blklim), KM_SLEEP);
2375 	rval = st_read_block_limits(un, blklim);
2376 	if (rval) {
2377 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2378 		    "st_get_conf_from_tape_drive(): "
2379 		    "fail to read block limits.\n");
2380 		rval = 0;
2381 		kmem_free(blklim, sizeof (struct read_blklim));
2382 		goto exit;
2383 	}
2384 	maxbsize = (blklim->max_hi << 16) +
2385 	    (blklim->max_mid << 8) + blklim->max_lo;
2386 	if (maxbsize > ST_MAXRECSIZE_VARIABLE) {
2387 		tem_dp->options |= ST_NO_RECSIZE_LIMIT;
2388 	}
2389 	kmem_free(blklim, sizeof (struct read_blklim));
2390 
2391 	/*
2392 	 * Inquiry VPD page 0xb0 to see if the tape drive supports WORM
2393 	 */
2394 	buf = kmem_zalloc(6, KM_SLEEP);
2395 	rval = st_get_special_inquiry(un, 6, buf, 0xb0);
2396 	if (rval) {
2397 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2398 		    "st_get_conf_from_tape_drive(): "
2399 		    "fail to read vitial inquiry.\n");
2400 		rval = 0;
2401 		kmem_free(buf, 6);
2402 		goto exit;
2403 	}
2404 	if (buf[4] & 1) {
2405 		tem_dp->options |= ST_WORMABLE;
2406 	}
2407 	kmem_free(buf, 6);
2408 
2409 	/* Assume BSD BSR KNOWS_EOD */
2410 	tem_dp->options |= ST_BSF | ST_BSR | ST_KNOWS_EOD | ST_UNLOADABLE;
2411 	tem_dp->max_rretries = -1;
2412 	tem_dp->max_wretries = -1;
2413 
2414 	/*
2415 	 * Decide the densities supported by tape drive by sending
2416 	 * REPORT DENSITY SUPPORT command.
2417 	 */
2418 	if (st_get_densities_from_tape_drive(un, tem_dp) == 0) {
2419 		goto exit;
2420 	}
2421 
2422 	/*
2423 	 * Decide the timeout values for several commands by sending
2424 	 * REPORT SUPPORTED OPERATION CODES command.
2425 	 */
2426 	rval = st_get_timeout_values_from_tape_drive(un, tem_dp);
2427 	if (rval == 0 || ((rval == 1) && (tem_dp->type == ST_TYPE_INVALID))) {
2428 		goto exit;
2429 	}
2430 
2431 	bcopy(tem_dp, dp, sizeof (struct st_drivetype));
2432 	rval = 1;
2433 
2434 exit:
2435 	un->un_status = KEY_NO_SENSE;
2436 	kmem_free(tem_dp, sizeof (struct st_drivetype));
2437 	return (rval);
2438 }
2439 
2440 static int
2441 st_get_densities_from_tape_drive(struct scsi_tape *un,
2442     struct st_drivetype *dp)
2443 {
2444 	int i, p;
2445 	size_t buflen;
2446 	ushort_t des_len;
2447 	uchar_t *den_header;
2448 	uchar_t num_den;
2449 	uchar_t den[NDENSITIES];
2450 	uchar_t deflt[NDENSITIES];
2451 	struct report_density_desc *den_desc;
2452 
2453 	ST_FUNC(ST_DEVINFO, st_get_densities_from_type_drive);
2454 
2455 	/*
2456 	 * Since we have no idea how many densitiy support entries
2457 	 * will be returned, we send the command firstly assuming
2458 	 * there is only one. Then we can decide the number of
2459 	 * entries by available density support length. If multiple
2460 	 * entries exist, we will resend the command with enough
2461 	 * buffer size.
2462 	 */
2463 	buflen = sizeof (struct report_density_header) +
2464 	    sizeof (struct report_density_desc);
2465 	den_header = kmem_zalloc(buflen, KM_SLEEP);
2466 	if (st_report_density_support(un, den_header, buflen) != 0) {
2467 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2468 		    "st_get_conf_from_tape_drive(): fail to report density.\n");
2469 		kmem_free(den_header, buflen);
2470 		return (0);
2471 	}
2472 	des_len =
2473 	    BE_16(((struct report_density_header *)den_header)->ava_dens_len);
2474 	num_den = (des_len - 2) / sizeof (struct report_density_desc);
2475 
2476 	if (num_den > 1) {
2477 		kmem_free(den_header, buflen);
2478 		buflen = sizeof (struct report_density_header) +
2479 		    sizeof (struct report_density_desc) * num_den;
2480 		den_header = kmem_zalloc(buflen, KM_SLEEP);
2481 		if (st_report_density_support(un, den_header, buflen) != 0) {
2482 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2483 			    "st_get_conf_from_tape_drive(): "
2484 			    "fail to report density.\n");
2485 			kmem_free(den_header, buflen);
2486 			return (0);
2487 		}
2488 	}
2489 
2490 	den_desc = (struct report_density_desc *)(den_header
2491 	    + sizeof (struct report_density_header));
2492 
2493 	/*
2494 	 * Decide the drive type by assigning organization
2495 	 */
2496 	for (i = 0; i < ST_NUM_MEMBERS(st_vid_dt); i ++) {
2497 		if (strncmp(st_vid_dt[i].vid, (char *)(den_desc->ass_org),
2498 		    8) == 0) {
2499 			dp->type = st_vid_dt[i].type;
2500 			break;
2501 		}
2502 	}
2503 	if (i == ST_NUM_MEMBERS(st_vid_dt)) {
2504 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2505 		    "st_get_conf_from_tape_drive(): "
2506 		    "can't find match of assigned ort.\n");
2507 		kmem_free(den_header, buflen);
2508 		return (0);
2509 	}
2510 
2511 	/*
2512 	 * The tape drive may support many tape formats, but the st driver
2513 	 * supports only the four highest densities. Since density code
2514 	 * values are returned by ascending sequence, we start from the
2515 	 * last entry of density support data block descriptor.
2516 	 */
2517 	p = 0;
2518 	den_desc += num_den - 1;
2519 	for (i = 0; i < num_den && p < NDENSITIES; i ++, den_desc --) {
2520 		if ((den_desc->pri_den != 0) && (den_desc->wrtok)) {
2521 			if (p != 0) {
2522 				if (den_desc->pri_den >= den[p - 1]) {
2523 					continue;
2524 				}
2525 			}
2526 			den[p] = den_desc->pri_den;
2527 			deflt[p] = den_desc->deflt;
2528 			p ++;
2529 		}
2530 	}
2531 
2532 	switch (p) {
2533 	case 0:
2534 		bzero(dp->densities, NDENSITIES);
2535 		dp->options |= ST_AUTODEN_OVERRIDE;
2536 		dp->default_density = MT_DENSITY4;
2537 		break;
2538 
2539 	case 1:
2540 		(void) memset(dp->densities, den[0], NDENSITIES);
2541 		dp->options |= ST_AUTODEN_OVERRIDE;
2542 		dp->default_density = MT_DENSITY4;
2543 		break;
2544 
2545 	case 2:
2546 		dp->densities[0] = den[1];
2547 		dp->densities[1] = den[1];
2548 		dp->densities[2] = den[0];
2549 		dp->densities[3] = den[0];
2550 		if (deflt[0]) {
2551 			dp->default_density = MT_DENSITY4;
2552 		} else {
2553 			dp->default_density = MT_DENSITY2;
2554 		}
2555 		break;
2556 
2557 	case 3:
2558 		dp->densities[0] = den[2];
2559 		dp->densities[1] = den[1];
2560 		dp->densities[2] = den[0];
2561 		dp->densities[3] = den[0];
2562 		if (deflt[0]) {
2563 			dp->default_density = MT_DENSITY4;
2564 		} else if (deflt[1]) {
2565 			dp->default_density = MT_DENSITY2;
2566 		} else {
2567 			dp->default_density = MT_DENSITY1;
2568 		}
2569 		break;
2570 
2571 	default:
2572 		for (i = p; i > p - NDENSITIES; i --) {
2573 			dp->densities[i - 1] = den[p - i];
2574 		}
2575 		if (deflt[0]) {
2576 			dp->default_density = MT_DENSITY4;
2577 		} else if (deflt[1]) {
2578 			dp->default_density = MT_DENSITY3;
2579 		} else if (deflt[2]) {
2580 			dp->default_density = MT_DENSITY2;
2581 		} else {
2582 			dp->default_density = MT_DENSITY1;
2583 		}
2584 		break;
2585 	}
2586 
2587 	bzero(dp->mediatype, NDENSITIES);
2588 
2589 	kmem_free(den_header, buflen);
2590 	return (1);
2591 }
2592 
2593 static int
2594 st_get_timeout_values_from_tape_drive(struct scsi_tape *un,
2595     struct st_drivetype *dp)
2596 {
2597 	ushort_t timeout;
2598 	int rval;
2599 
2600 	ST_FUNC(ST_DEVINFO, st_get_timeout_values_from_type_drive);
2601 
2602 	rval = st_get_timeouts_value(un, SCMD_ERASE, &timeout, 0);
2603 	if (rval) {
2604 		if (rval == EACCES) {
2605 			un->un_dp->type = ST_TYPE_INVALID;
2606 			dp->type = ST_TYPE_INVALID;
2607 			return (1);
2608 		}
2609 		return (0);
2610 	}
2611 	dp->erase_timeout = timeout;
2612 
2613 	rval = st_get_timeouts_value(un, SCMD_READ, &timeout, 0);
2614 	if (rval) {
2615 		if (rval == EACCES) {
2616 			un->un_dp->type = ST_TYPE_INVALID;
2617 			dp->type = ST_TYPE_INVALID;
2618 			return (1);
2619 		}
2620 		return (0);
2621 	}
2622 	dp->io_timeout = timeout;
2623 
2624 	rval = st_get_timeouts_value(un, SCMD_WRITE, &timeout, 0);
2625 	if (rval) {
2626 		if (rval == EACCES) {
2627 			un->un_dp->type = ST_TYPE_INVALID;
2628 			dp->type = ST_TYPE_INVALID;
2629 			return (1);
2630 		}
2631 		return (0);
2632 	}
2633 	dp->io_timeout = max(dp->io_timeout, timeout);
2634 
2635 	rval = st_get_timeouts_value(un, SCMD_SPACE, &timeout, 0);
2636 	if (rval) {
2637 		if (rval == EACCES) {
2638 			un->un_dp->type = ST_TYPE_INVALID;
2639 			dp->type = ST_TYPE_INVALID;
2640 			return (1);
2641 		}
2642 		return (0);
2643 	}
2644 	dp->space_timeout = timeout;
2645 
2646 	rval = st_get_timeouts_value(un, SCMD_LOAD, &timeout, 0);
2647 	if (rval) {
2648 		if (rval == EACCES) {
2649 			un->un_dp->type = ST_TYPE_INVALID;
2650 			dp->type = ST_TYPE_INVALID;
2651 			return (1);
2652 		}
2653 		return (0);
2654 	}
2655 	dp->load_timeout = timeout;
2656 	dp->unload_timeout = timeout;
2657 
2658 	rval = st_get_timeouts_value(un, SCMD_REWIND, &timeout, 0);
2659 	if (rval) {
2660 		if (rval == EACCES) {
2661 			un->un_dp->type = ST_TYPE_INVALID;
2662 			dp->type = ST_TYPE_INVALID;
2663 			return (1);
2664 		}
2665 		return (0);
2666 	}
2667 	dp->rewind_timeout = timeout;
2668 
2669 	rval = st_get_timeouts_value(un, SCMD_INQUIRY, &timeout, 0);
2670 	if (rval) {
2671 		if (rval == EACCES) {
2672 			un->un_dp->type = ST_TYPE_INVALID;
2673 			dp->type = ST_TYPE_INVALID;
2674 			return (1);
2675 		}
2676 		return (0);
2677 	}
2678 	dp->non_motion_timeout = timeout;
2679 
2680 	return (1);
2681 }
2682 
2683 static int
2684 st_get_timeouts_value(struct scsi_tape *un, uchar_t option_code,
2685     ushort_t *timeout_value, ushort_t service_action)
2686 {
2687 	uchar_t *timeouts;
2688 	uchar_t *oper;
2689 	uchar_t support;
2690 	uchar_t cdbsize;
2691 	uchar_t ctdp;
2692 	size_t buflen;
2693 	int rval;
2694 
2695 	ST_FUNC(ST_DEVINFO, st_get_timeouts_value);
2696 
2697 	buflen = sizeof (struct one_com_des) +
2698 	    sizeof (struct com_timeout_des);
2699 	oper = kmem_zalloc(buflen, KM_SLEEP);
2700 	rval = st_report_supported_operation(un, oper, option_code,
2701 	    service_action);
2702 
2703 	if (rval) {
2704 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2705 		    "st_get_timeouts_value(): "
2706 		    "fail to timeouts value for command %d.\n", option_code);
2707 		kmem_free(oper, buflen);
2708 		return (rval);
2709 	}
2710 
2711 	support = ((struct one_com_des *)oper)->support;
2712 	if ((support != SUPPORT_VALUES_SUPPORT_SCSI) &&
2713 	    (support != SUPPORT_VALUES_SUPPORT_VENDOR)) {
2714 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2715 		    "st_get_timeouts_value(): "
2716 		    "command %d is not supported.\n", option_code);
2717 		kmem_free(oper, buflen);
2718 		return (ENOTSUP);
2719 	}
2720 
2721 	ctdp = ((struct one_com_des *)oper)->ctdp;
2722 	if (!ctdp) {
2723 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2724 		    "st_get_timeouts_value(): "
2725 		    "command timeout is not included.\n");
2726 		kmem_free(oper, buflen);
2727 		return (ENOTSUP);
2728 	}
2729 
2730 	cdbsize = BE_16(((struct one_com_des *)oper)->cdb_size);
2731 	timeouts = (uchar_t *)(oper + cdbsize + 4);
2732 
2733 	/*
2734 	 * Timeout value in seconds is 4 bytes, but we only support the lower 2
2735 	 * bytes. If the higher 2 bytes are not zero, the timeout value is set
2736 	 * to 0xFFFF.
2737 	 */
2738 	if (*(timeouts + 8) != 0 || *(timeouts + 9) != 0) {
2739 		*timeout_value = USHRT_MAX;
2740 	} else {
2741 		*timeout_value = ((*(timeouts + 10)) << 8) |
2742 		    (*(timeouts + 11));
2743 	}
2744 
2745 	kmem_free(oper, buflen);
2746 	return (0);
2747 }
2748 
2749 static int
2750 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2751 {
2752 	int i;
2753 
2754 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2755 
2756 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2757 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2758 
2759 	/*
2760 	 * Make up a name
2761 	 */
2762 	bcopy("Vendor '", dp->name, 8);
2763 	bcopy(vidpid, &dp->name[8], VIDLEN);
2764 	bcopy("' Product '", &dp->name[16], 11);
2765 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2766 	dp->name[ST_NAMESIZE - 2] = '\'';
2767 	dp->name[ST_NAMESIZE - 1] = '\0';
2768 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2769 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2770 	/*
2771 	 * 'clean' vendor and product strings of non-printing chars
2772 	 */
2773 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2774 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2775 			dp->name[i] = '.';
2776 		}
2777 	}
2778 	dp->type = ST_TYPE_INVALID;
2779 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2780 
2781 	return (1); /* Can Not Fail */
2782 }
2783 
2784 /*
2785  * Regular Unix Entry points
2786  */
2787 
2788 
2789 
2790 /* ARGSUSED */
2791 static int
2792 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2793 {
2794 	dev_t dev = *dev_p;
2795 	int rval = 0;
2796 
2797 	GET_SOFT_STATE(dev);
2798 
2799 	ST_ENTR(ST_DEVINFO, st_open);
2800 
2801 	/*
2802 	 * validate that we are addressing a sensible unit
2803 	 */
2804 	mutex_enter(ST_MUTEX);
2805 
2806 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2807 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2808 	    st_dev_name(dev), *dev_p, flag, otyp);
2809 
2810 	/*
2811 	 * All device accesss go thru st_strategy() where we check
2812 	 * suspend status
2813 	 */
2814 
2815 	if (!un->un_attached) {
2816 		st_known_tape_type(un);
2817 		if (!un->un_attached) {
2818 			rval = ENXIO;
2819 			goto exit;
2820 		}
2821 
2822 	}
2823 
2824 	/*
2825 	 * Check for the case of the tape in the middle of closing.
2826 	 * This isn't simply a check of the current state, because
2827 	 * we could be in state of sensing with the previous state
2828 	 * that of closing.
2829 	 *
2830 	 * And don't allow multiple opens.
2831 	 */
2832 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2833 		un->un_laststate = un->un_state;
2834 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2835 		while (IS_CLOSING(un) ||
2836 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2837 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2838 				rval = EINTR;
2839 				un->un_state = un->un_laststate;
2840 				goto exit;
2841 			}
2842 		}
2843 	} else if (un->un_state != ST_STATE_CLOSED) {
2844 		rval = EBUSY;
2845 		goto busy;
2846 	}
2847 
2848 	/*
2849 	 * record current dev
2850 	 */
2851 	un->un_dev = dev;
2852 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2853 	un->un_errno = 0;	/* no errors yet */
2854 	un->un_restore_pos = 0;
2855 	un->un_rqs_state = 0;
2856 
2857 	/*
2858 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2859 	 * anything, leave internal states alone, if fileno >= 0
2860 	 */
2861 	if (flag & (FNDELAY | FNONBLOCK)) {
2862 		switch (un->un_pos.pmode) {
2863 
2864 		case invalid:
2865 			un->un_state = ST_STATE_OFFLINE;
2866 			break;
2867 
2868 		case legacy:
2869 			/*
2870 			 * If position is anything other than rewound.
2871 			 */
2872 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2873 				/*
2874 				 * set un_read_only/write-protect status.
2875 				 *
2876 				 * If the tape is not bot we can assume
2877 				 * that mspl->wp_status is set properly.
2878 				 * else
2879 				 * we need to do a mode sense/Tur once
2880 				 * again to get the actual tape status.(since
2881 				 * user might have replaced the tape)
2882 				 * Hence make the st state OFFLINE so that
2883 				 * we re-intialize the tape once again.
2884 				 */
2885 				un->un_read_only =
2886 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2887 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2888 			} else {
2889 				un->un_state = ST_STATE_OFFLINE;
2890 			}
2891 			break;
2892 		case logical:
2893 			if (un->un_pos.lgclblkno == 0) {
2894 				un->un_state = ST_STATE_OFFLINE;
2895 			} else {
2896 				un->un_read_only =
2897 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2898 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2899 			}
2900 			break;
2901 		}
2902 		rval = 0;
2903 	} else {
2904 		/*
2905 		 * Not opening O_NDELAY.
2906 		 */
2907 		un->un_state = ST_STATE_OPENING;
2908 
2909 		/*
2910 		 * Clear error entry stack
2911 		 */
2912 		st_empty_error_stack(un);
2913 
2914 		rval = st_tape_init(un);
2915 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2916 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2917 			rval = 0; /* so open doesn't fail */
2918 		} else if (rval) {
2919 			/*
2920 			 * Release the tape unit, if reserved and not
2921 			 * preserve reserve.
2922 			 */
2923 			if ((un->un_rsvd_status &
2924 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2925 				(void) st_reserve_release(un, ST_RELEASE,
2926 				    st_uscsi_cmd);
2927 			}
2928 		} else {
2929 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2930 		}
2931 	}
2932 
2933 exit:
2934 	/*
2935 	 * we don't want any uninvited guests scrogging our data when we're
2936 	 * busy with something, so for successful opens or failed opens
2937 	 * (except for EBUSY), reset these counters and state appropriately.
2938 	 */
2939 	if (rval != EBUSY) {
2940 		if (rval) {
2941 			un->un_state = ST_STATE_CLOSED;
2942 		}
2943 		un->un_err_resid = 0;
2944 		un->un_retry_ct = 0;
2945 	}
2946 busy:
2947 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2948 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2949 	mutex_exit(ST_MUTEX);
2950 	return (rval);
2951 
2952 }
2953 
2954 static int
2955 st_tape_init(struct scsi_tape *un)
2956 {
2957 	int err;
2958 	int rval = 0;
2959 
2960 	ST_FUNC(ST_DEVINFO, st_tape_init);
2961 
2962 	ASSERT(mutex_owned(ST_MUTEX));
2963 
2964 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2965 	    "st_tape_init(un = 0x%p, oflags = %d)\n", (void*)un, un->un_oflags);
2966 
2967 	/*
2968 	 * Clean up after any errors left by 'last' close.
2969 	 * This also handles the case of the initial open.
2970 	 */
2971 	if (un->un_state != ST_STATE_INITIALIZING) {
2972 		un->un_laststate = un->un_state;
2973 		un->un_state = ST_STATE_OPENING;
2974 	}
2975 
2976 	un->un_kbytes_xferred = 0;
2977 
2978 	/*
2979 	 * do a throw away TUR to clear check condition
2980 	 */
2981 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2982 
2983 	/*
2984 	 * If test unit ready fails because the drive is reserved
2985 	 * by another host fail the open for no access.
2986 	 */
2987 	if (err) {
2988 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2989 			un->un_state = ST_STATE_CLOSED;
2990 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2991 			    "st_tape_init: RESERVATION CONFLICT\n");
2992 			rval = EACCES;
2993 			goto exit;
2994 		} else if ((un->un_rsvd_status &
2995 		    ST_APPLICATION_RESERVATIONS) != 0) {
2996 			if ((ST_RQSENSE != NULL) &&
2997 			    (ST_RQSENSE->es_add_code == 0x2a &&
2998 			    ST_RQSENSE->es_qual_code == 0x03)) {
2999 				un->un_state = ST_STATE_CLOSED;
3000 				rval = EACCES;
3001 				goto exit;
3002 			}
3003 		}
3004 	}
3005 
3006 	/*
3007 	 * Tape self identification could fail if the tape drive is used by
3008 	 * another host during attach time. We try to get the tape type
3009 	 * again. This is also applied to any posponed configuration methods.
3010 	 */
3011 	if (un->un_dp->type == ST_TYPE_INVALID) {
3012 		un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
3013 		st_known_tape_type(un);
3014 	}
3015 
3016 	/*
3017 	 * If the tape type is still invalid, try to determine the generic
3018 	 * configuration.
3019 	 */
3020 	if (un->un_dp->type == ST_TYPE_INVALID) {
3021 		rval = st_determine_generic(un);
3022 		if (rval) {
3023 			if (rval != EACCES) {
3024 				rval = EIO;
3025 			}
3026 			un->un_state = ST_STATE_CLOSED;
3027 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3028 			    "st_tape_init: %s invalid type\n",
3029 			    rval == EACCES ? "EACCES" : "EIO");
3030 			goto exit;
3031 		}
3032 		/*
3033 		 * If this is a Unknown Type drive,
3034 		 * Use the READ BLOCK LIMITS to determine if
3035 		 * allow large xfer is approprate if not globally
3036 		 * disabled with st_allow_large_xfer.
3037 		 */
3038 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
3039 	} else {
3040 
3041 		/*
3042 		 * If we allow_large_xfer (ie >64k) and have not yet found out
3043 		 * the max block size supported by the drive,
3044 		 * find it by issueing a READ_BLKLIM command.
3045 		 * if READ_BLKLIM cmd fails, assume drive doesn't
3046 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
3047 		 */
3048 		un->un_allow_large_xfer = st_allow_large_xfer &&
3049 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
3050 	}
3051 	/*
3052 	 * if maxbsize is unknown, set the maximum block size.
3053 	 */
3054 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
3055 
3056 		/*
3057 		 * Get the Block limits of the tape drive.
3058 		 * if un->un_allow_large_xfer = 0 , then make sure
3059 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
3060 		 */
3061 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
3062 
3063 		err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3064 		if (err) {
3065 			/* Retry */
3066 			err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3067 		}
3068 		if (!err) {
3069 
3070 			/*
3071 			 * if cmd successful, use limit returned
3072 			 */
3073 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
3074 			    (un->un_rbl->max_mid << 8) +
3075 			    un->un_rbl->max_lo;
3076 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
3077 			    un->un_rbl->min_lo;
3078 			un->un_data_mod = 1 << un->un_rbl->granularity;
3079 			if ((un->un_maxbsize == 0) ||
3080 			    (un->un_allow_large_xfer == 0 &&
3081 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
3082 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3083 
3084 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
3085 				/*
3086 				 * Drive is not one that is configured, But the
3087 				 * READ BLOCK LIMITS tells us it can do large
3088 				 * xfers.
3089 				 */
3090 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
3091 					un->un_dp->options |=
3092 					    ST_NO_RECSIZE_LIMIT;
3093 				}
3094 				/*
3095 				 * If max and mimimum block limits are the
3096 				 * same this is a fixed block size device.
3097 				 */
3098 				if (un->un_maxbsize == un->un_minbsize) {
3099 					un->un_dp->options &= ~ST_VARIABLE;
3100 				}
3101 			}
3102 
3103 			if (un->un_minbsize == 0) {
3104 				un->un_minbsize = 1;
3105 			}
3106 
3107 		} else { /* error on read block limits */
3108 
3109 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3110 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
3111 			    " errno = %d un_rsvd_status = 0x%X\n",
3112 			    err, un->un_rsvd_status);
3113 
3114 			/*
3115 			 * since read block limits cmd failed,
3116 			 * do not allow large xfers.
3117 			 * use old values in st_minphys
3118 			 */
3119 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
3120 				rval = EACCES;
3121 			} else {
3122 				un->un_allow_large_xfer = 0;
3123 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3124 				    "!Disabling large transfers\n");
3125 
3126 				/*
3127 				 * we guess maxbsize and minbsize
3128 				 */
3129 				if (un->un_bsize) {
3130 					un->un_maxbsize = un->un_minbsize =
3131 					    un->un_bsize;
3132 				} else {
3133 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3134 					un->un_minbsize = 1;
3135 				}
3136 				/*
3137 				 * Data Mod must be set,
3138 				 * Even if read block limits fails.
3139 				 * Prevents Divide By Zero in st_rw().
3140 				 */
3141 				un->un_data_mod = 1;
3142 			}
3143 		}
3144 		if (un->un_rbl) {
3145 			kmem_free(un->un_rbl, RBLSIZE);
3146 			un->un_rbl = NULL;
3147 		}
3148 
3149 		if (rval) {
3150 			goto exit;
3151 		}
3152 	}
3153 
3154 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3155 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
3156 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
3157 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
3158 
3159 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
3160 
3161 	if (err != 0) {
3162 		if (err == EINTR) {
3163 			un->un_laststate = un->un_state;
3164 			un->un_state = ST_STATE_CLOSED;
3165 			rval = EINTR;
3166 			goto exit;
3167 		}
3168 		/*
3169 		 * Make sure the tape is ready
3170 		 */
3171 		un->un_pos.pmode = invalid;
3172 		if (un->un_status != KEY_UNIT_ATTENTION) {
3173 			/*
3174 			 * allow open no media.  Subsequent MTIOCSTATE
3175 			 * with media present will complete the open
3176 			 * logic.
3177 			 */
3178 			un->un_laststate = un->un_state;
3179 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
3180 				un->un_mediastate = MTIO_EJECTED;
3181 				un->un_state = ST_STATE_OFFLINE;
3182 				rval = 0;
3183 				goto exit;
3184 			} else {
3185 				un->un_state = ST_STATE_CLOSED;
3186 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3187 				    "st_tape_init EIO no media, not opened "
3188 				    "O_NONBLOCK|O_EXCL\n");
3189 				rval = EIO;
3190 				goto exit;
3191 			}
3192 		}
3193 	}
3194 
3195 	/*
3196 	 * On each open, initialize block size from drivetype struct,
3197 	 * as it could have been changed by MTSRSZ ioctl.
3198 	 * Now, ST_VARIABLE simply means drive is capable of variable
3199 	 * mode. All drives are assumed to support fixed records.
3200 	 * Hence, un_bsize tells what mode the drive is in.
3201 	 *	un_bsize	= 0	- variable record length
3202 	 *			= x	- fixed record length is x
3203 	 */
3204 	un->un_bsize = un->un_dp->bsize;
3205 
3206 	/*
3207 	 * If saved position is valid go there
3208 	 */
3209 	if (un->un_restore_pos) {
3210 		un->un_restore_pos = 0;
3211 		un->un_pos.fileno = un->un_save_fileno;
3212 		un->un_pos.blkno = un->un_save_blkno;
3213 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &un->un_pos);
3214 		if (rval != 0) {
3215 			if (rval != EACCES) {
3216 				rval = EIO;
3217 			}
3218 			un->un_laststate = un->un_state;
3219 			un->un_state = ST_STATE_CLOSED;
3220 			goto exit;
3221 		}
3222 	}
3223 
3224 	if (un->un_pos.pmode == invalid) {
3225 		rval = st_loadtape(un);
3226 		if (rval) {
3227 			if (rval != EACCES) {
3228 				rval = EIO;
3229 			}
3230 			un->un_laststate = un->un_state;
3231 			un->un_state = ST_STATE_CLOSED;
3232 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3233 			    "st_tape_init: %s can't open tape\n",
3234 			    rval == EACCES ? "EACCES" : "EIO");
3235 			goto exit;
3236 		}
3237 	}
3238 
3239 	/*
3240 	 * do a mode sense to pick up state of current write-protect,
3241 	 * Could cause reserve and fail due to conflict.
3242 	 */
3243 	if (un->un_unit_attention_flags) {
3244 		rval = st_modesense(un);
3245 		if (rval == EACCES) {
3246 			goto exit;
3247 		}
3248 	}
3249 
3250 	/*
3251 	 * If we are opening the tape for writing, check
3252 	 * to make sure that the tape can be written.
3253 	 */
3254 	if (un->un_oflags & FWRITE) {
3255 		err = 0;
3256 		if (un->un_mspl->wp) {
3257 			un->un_status = KEY_WRITE_PROTECT;
3258 			un->un_laststate = un->un_state;
3259 			un->un_state = ST_STATE_CLOSED;
3260 			rval = EACCES;
3261 			/*
3262 			 * STK sets the wp bit if volsafe tape is loaded.
3263 			 */
3264 			if ((un->un_dp->type == MT_ISSTK9840) &&
3265 			    (un->un_dp->options & ST_WORMABLE)) {
3266 				un->un_read_only = RDONLY;
3267 			} else {
3268 				goto exit;
3269 			}
3270 		} else {
3271 			un->un_read_only = RDWR;
3272 		}
3273 	} else {
3274 		un->un_read_only = RDONLY;
3275 	}
3276 
3277 	if (un->un_dp->options & ST_WORMABLE &&
3278 	    un->un_unit_attention_flags) {
3279 		un->un_read_only |= un->un_wormable(un);
3280 
3281 		if (((un->un_read_only == WORM) ||
3282 		    (un->un_read_only == RDWORM)) &&
3283 		    ((un->un_oflags & FWRITE) == FWRITE)) {
3284 			un->un_status = KEY_DATA_PROTECT;
3285 			rval = EACCES;
3286 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3287 			    "read_only = %d eof = %d oflag = %d\n",
3288 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3289 		}
3290 	}
3291 
3292 	/*
3293 	 * If we're opening the tape write-only, we need to
3294 	 * write 2 filemarks on the HP 1/2 inch drive, to
3295 	 * create a null file.
3296 	 */
3297 	if ((un->un_read_only == RDWR) ||
3298 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3299 		if (un->un_dp->options & ST_REEL) {
3300 			un->un_fmneeded = 2;
3301 		} else {
3302 			un->un_fmneeded = 1;
3303 		}
3304 	} else {
3305 		un->un_fmneeded = 0;
3306 	}
3307 
3308 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3309 	    "fmneeded = %x\n", un->un_fmneeded);
3310 
3311 	/*
3312 	 * Make sure the density can be selected correctly.
3313 	 * If WORM can only write at the append point which in most cases
3314 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3315 	 * to set and try densities if a BOP.
3316 	 */
3317 	if (st_determine_density(un,
3318 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3319 		un->un_status = KEY_ILLEGAL_REQUEST;
3320 		un->un_laststate = un->un_state;
3321 		un->un_state = ST_STATE_CLOSED;
3322 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3323 		    "st_tape_init: EIO can't determine density\n");
3324 		rval = EIO;
3325 		goto exit;
3326 	}
3327 
3328 	/*
3329 	 * Destroy the knowledge that we have 'determined'
3330 	 * density so that a later read at BOT comes along
3331 	 * does the right density determination.
3332 	 */
3333 
3334 	un->un_density_known = 0;
3335 
3336 
3337 	/*
3338 	 * Okay, the tape is loaded and either at BOT or somewhere past.
3339 	 * Mark the state such that any I/O or tape space operations
3340 	 * will get/set the right density, etc..
3341 	 */
3342 	un->un_laststate = un->un_state;
3343 	un->un_lastop = ST_OP_NIL;
3344 	un->un_mediastate = MTIO_INSERTED;
3345 	cv_broadcast(&un->un_state_cv);
3346 
3347 	/*
3348 	 *  Set test append flag if writing.
3349 	 *  First write must check that tape is positioned correctly.
3350 	 */
3351 	un->un_test_append = (un->un_oflags & FWRITE);
3352 
3353 	/*
3354 	 * if there are pending unit attention flags.
3355 	 * Check that the media has not changed.
3356 	 */
3357 	if (un->un_unit_attention_flags) {
3358 		rval = st_get_media_identification(un, st_uscsi_cmd);
3359 		if (rval != 0 && rval != EACCES) {
3360 			rval = EIO;
3361 		}
3362 		un->un_unit_attention_flags = 0;
3363 	}
3364 
3365 exit:
3366 	un->un_err_resid = 0;
3367 	un->un_last_resid = 0;
3368 	un->un_last_count = 0;
3369 
3370 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3371 	    "st_tape_init: return val = %x\n", rval);
3372 	return (rval);
3373 
3374 }
3375 
3376 
3377 
3378 /* ARGSUSED */
3379 static int
3380 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3381 {
3382 	int err = 0;
3383 	int count, last_state;
3384 	minor_t minor = getminor(dev);
3385 #ifdef	__x86
3386 	struct contig_mem *cp, *cp_temp;
3387 #endif
3388 
3389 	GET_SOFT_STATE(dev);
3390 
3391 	ST_ENTR(ST_DEVINFO, st_close);
3392 
3393 	/*
3394 	 * wait till all cmds in the pipeline have been completed
3395 	 */
3396 	mutex_enter(ST_MUTEX);
3397 
3398 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3399 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3400 
3401 	st_wait_for_io(un);
3402 
3403 	/* turn off persistent errors on close, as we want close to succeed */
3404 	st_turn_pe_off(un);
3405 
3406 	/*
3407 	 * set state to indicate that we are in process of closing
3408 	 */
3409 	last_state = un->un_laststate = un->un_state;
3410 	un->un_state = ST_STATE_CLOSING;
3411 
3412 	ST_POS(ST_DEVINFO, "st_close1:", &un->un_pos);
3413 
3414 	/*
3415 	 * BSD behavior:
3416 	 * a close always causes a silent span to the next file if we've hit
3417 	 * an EOF (but not yet read across it).
3418 	 */
3419 	if ((minor & MT_BSD) && (un->un_pos.eof == ST_EOF)) {
3420 		if (un->un_pos.pmode != invalid) {
3421 			un->un_pos.fileno++;
3422 			un->un_pos.blkno = 0;
3423 		}
3424 		un->un_pos.eof = ST_NO_EOF;
3425 	}
3426 
3427 	/*
3428 	 * SVR4 behavior for skipping to next file:
3429 	 *
3430 	 * If we have not seen a filemark, space to the next file
3431 	 *
3432 	 * If we have already seen the filemark we are physically in the next
3433 	 * file and we only increment the filenumber
3434 	 */
3435 	if (((minor & (MT_BSD | MT_NOREWIND)) == MT_NOREWIND) &&
3436 	    (flag & FREAD) &&		/* reading or at least asked to */
3437 	    (un->un_mediastate == MTIO_INSERTED) &&	/* tape loaded */
3438 	    (un->un_pos.pmode != invalid) &&		/* XXX position known */
3439 	    ((un->un_pos.blkno != 0) && 		/* inside a file */
3440 	    (un->un_lastop != ST_OP_WRITE) &&		/* Didn't just write */
3441 	    (un->un_lastop != ST_OP_WEOF))) {		/* or write filemarks */
3442 		switch (un->un_pos.eof) {
3443 		case ST_NO_EOF:
3444 			/*
3445 			 * if we were reading and did not read the complete file
3446 			 * skip to the next file, leaving the tape correctly
3447 			 * positioned to read the first record of the next file
3448 			 * Check first for REEL if we are at EOT by trying to
3449 			 * read a block
3450 			 */
3451 			if ((un->un_dp->options & ST_REEL) &&
3452 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3453 			    (un->un_pos.blkno == 0)) {
3454 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3455 					ST_DEBUG2(ST_DEVINFO, st_label,
3456 					    SCSI_DEBUG,
3457 					    "st_close : EIO can't space\n");
3458 					err = EIO;
3459 					goto error_out;
3460 				}
3461 				if (un->un_pos.eof >= ST_EOF_PENDING) {
3462 					un->un_pos.eof = ST_EOT_PENDING;
3463 					un->un_pos.fileno += 1;
3464 					un->un_pos.blkno   = 0;
3465 					break;
3466 				}
3467 			}
3468 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3469 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3470 				    "st_close: EIO can't space #2\n");
3471 				err = EIO;
3472 				goto error_out;
3473 			} else {
3474 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3475 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3476 				    un->un_pos.fileno, un->un_pos.blkno,
3477 				    un->un_pos.eof);
3478 				un->un_pos.eof = ST_NO_EOF;
3479 			}
3480 			break;
3481 
3482 		case ST_EOF_PENDING:
3483 		case ST_EOF:
3484 			un->un_pos.fileno += 1;
3485 			un->un_pos.lgclblkno += 1;
3486 			un->un_pos.blkno   = 0;
3487 			un->un_pos.eof = ST_NO_EOF;
3488 			break;
3489 
3490 		case ST_EOT:
3491 		case ST_EOT_PENDING:
3492 		case ST_EOM:
3493 			/* nothing to do */
3494 			break;
3495 		default:
3496 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
3497 			    "Undefined state 0x%x", un->un_pos.eof);
3498 
3499 		}
3500 	}
3501 
3502 
3503 	/*
3504 	 * For performance reasons (HP 88780), the driver should
3505 	 * postpone writing the second tape mark until just before a file
3506 	 * positioning ioctl is issued (e.g., rewind).	This means that
3507 	 * the user must not manually rewind the tape because the tape will
3508 	 * be missing the second tape mark which marks EOM.
3509 	 * However, this small performance improvement is not worth the risk.
3510 	 */
3511 
3512 	/*
3513 	 * We need to back up over the filemark we inadvertently popped
3514 	 * over doing a read in between the two filemarks that constitute
3515 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3516 	 * set while reading.
3517 	 *
3518 	 * If we happen to be at physical eot (ST_EOM) (writing case),
3519 	 * the writing of filemark(s) will clear the ST_EOM state, which
3520 	 * we don't want, so we save this state and restore it later.
3521 	 */
3522 
3523 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3524 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3525 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3526 
3527 	if (un->un_pos.eof == ST_EOT_PENDING) {
3528 		if (minor & MT_NOREWIND) {
3529 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3530 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3531 				    "st_close: EIO can't space #3\n");
3532 				err = EIO;
3533 				goto error_out;
3534 			} else {
3535 				un->un_pos.blkno = 0;
3536 				un->un_pos.eof = ST_EOT;
3537 			}
3538 		} else {
3539 			un->un_pos.eof = ST_NO_EOF;
3540 		}
3541 
3542 	/*
3543 	 * Do we need to write a file mark?
3544 	 *
3545 	 * only write filemarks if there are fmks to be written and
3546 	 *   - open for write (possibly read/write)
3547 	 *   - the last operation was a write
3548 	 * or:
3549 	 *   -	opened for wronly
3550 	 *   -	no data was written
3551 	 */
3552 	} else if ((un->un_pos.pmode != invalid) &&
3553 	    (un->un_fmneeded > 0) &&
3554 	    (((flag & FWRITE) &&
3555 	    ((un->un_lastop == ST_OP_WRITE)||(un->un_lastop == ST_OP_WEOF))) ||
3556 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3557 
3558 		/* save ST_EOM state */
3559 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3560 
3561 		/*
3562 		 * Note that we will write a filemark if we had opened
3563 		 * the tape write only and no data was written, thus
3564 		 * creating a null file.
3565 		 *
3566 		 * If the user already wrote one, we only have to write 1 more.
3567 		 * If they wrote two, we don't have to write any.
3568 		 */
3569 
3570 		count = un->un_fmneeded;
3571 		if (count > 0) {
3572 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, count, SYNC_CMD)) {
3573 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3574 				    "st_close : EIO can't wfm\n");
3575 				err = EIO;
3576 				goto error_out;
3577 			}
3578 			if ((un->un_dp->options & ST_REEL) &&
3579 			    (minor & MT_NOREWIND)) {
3580 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3581 					ST_DEBUG2(ST_DEVINFO, st_label,
3582 					    SCSI_DEBUG,
3583 					    "st_close : EIO space fmk(-1)\n");
3584 					err = EIO;
3585 					goto error_out;
3586 				}
3587 				un->un_pos.eof = ST_NO_EOF;
3588 				/* fix up block number */
3589 				un->un_pos.blkno = 0;
3590 			}
3591 		}
3592 
3593 		/*
3594 		 * If we aren't going to be rewinding, and we were at
3595 		 * physical eot, restore the state that indicates we
3596 		 * are at physical eot. Once you have reached physical
3597 		 * eot, and you close the tape, the only thing you can
3598 		 * do on the next open is to rewind. Access to trailer
3599 		 * records is only allowed without closing the device.
3600 		 */
3601 		if ((minor & MT_NOREWIND) == 0 && was_at_eom) {
3602 			un->un_pos.eof = ST_EOM;
3603 		}
3604 	}
3605 
3606 	/*
3607 	 * report soft errors if enabled and available, if we never accessed
3608 	 * the drive, don't get errors. This will prevent some DAT error
3609 	 * messages upon LOG SENSE.
3610 	 */
3611 	if (st_report_soft_errors_on_close &&
3612 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3613 	    (last_state != ST_STATE_OFFLINE)) {
3614 		if (st_report_soft_errors(dev, flag)) {
3615 			err = EIO;
3616 			goto error_out;
3617 		}
3618 	}
3619 
3620 
3621 	/*
3622 	 * Do we need to rewind? Can we rewind?
3623 	 */
3624 	if ((minor & MT_NOREWIND) == 0 &&
3625 	    un->un_pos.pmode != invalid && err == 0) {
3626 		/*
3627 		 * We'd like to rewind with the
3628 		 * 'immediate' bit set, but this
3629 		 * causes problems on some drives
3630 		 * where subsequent opens get a
3631 		 * 'NOT READY' error condition
3632 		 * back while the tape is rewinding,
3633 		 * which is impossible to distinguish
3634 		 * from the condition of 'no tape loaded'.
3635 		 *
3636 		 * Also, for some targets, if you disconnect
3637 		 * with the 'immediate' bit set, you don't
3638 		 * actually return right away, i.e., the
3639 		 * target ignores your request for immediate
3640 		 * return.
3641 		 *
3642 		 * Instead, we'll fire off an async rewind
3643 		 * command. We'll mark the device as closed,
3644 		 * and any subsequent open will stall on
3645 		 * the first TEST_UNIT_READY until the rewind
3646 		 * completes.
3647 		 */
3648 
3649 		/*
3650 		 * Used to be if reserve was not supported we'd send an
3651 		 * asynchronious rewind. Comments above may be slightly invalid
3652 		 * as the immediate bit was never set. Doing an immedate rewind
3653 		 * makes sense, I think fixes to not ready status might handle
3654 		 * the problems described above.
3655 		 */
3656 		if (un->un_sd->sd_inq->inq_ansi < 2) {
3657 			if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
3658 				err = EIO;
3659 			}
3660 		} else {
3661 			/* flush data for older drives per scsi spec. */
3662 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD)) {
3663 				err = EIO;
3664 			} else {
3665 				/* release the drive before rewind immediate */
3666 				if ((un->un_rsvd_status &
3667 				    (ST_RESERVE | ST_PRESERVE_RESERVE)) ==
3668 				    ST_RESERVE) {
3669 					if (st_reserve_release(un, ST_RELEASE,
3670 					    st_uscsi_cmd)) {
3671 						err = EIO;
3672 					}
3673 				}
3674 
3675 				/* send rewind with immediate bit set */
3676 				if (st_cmd(un, SCMD_REWIND, 1, ASYNC_CMD)) {
3677 					err = EIO;
3678 				}
3679 			}
3680 		}
3681 		/*
3682 		 * Setting positions invalid in case the rewind doesn't
3683 		 * happen. Drives don't like to rewind if resets happen
3684 		 * they will tend to move back to where the rewind was
3685 		 * issued if a reset or something happens so that if a
3686 		 * write happens the data doesn't get clobbered.
3687 		 *
3688 		 * Not a big deal if the position is invalid when the
3689 		 * open occures it will do a read position.
3690 		 */
3691 		un->un_pos.pmode = invalid;
3692 		un->un_running.pmode = invalid;
3693 
3694 		if (err == EIO) {
3695 			goto error_out;
3696 		}
3697 	}
3698 
3699 	/*
3700 	 * eject tape if necessary
3701 	 */
3702 	if (un->un_eject_tape_on_failure) {
3703 		un->un_eject_tape_on_failure = 0;
3704 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3705 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3706 			    "st_close : can't unload tape\n");
3707 			err = EIO;
3708 			goto error_out;
3709 		} else {
3710 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3711 			    "st_close : tape unloaded \n");
3712 			un->un_pos.eof = ST_NO_EOF;
3713 			un->un_mediastate = MTIO_EJECTED;
3714 		}
3715 	}
3716 	/*
3717 	 * Release the tape unit, if default reserve/release
3718 	 * behaviour.
3719 	 */
3720 	if ((un->un_rsvd_status &
3721 	    (ST_RESERVE | ST_PRESERVE_RESERVE |
3722 	    ST_APPLICATION_RESERVATIONS)) == ST_RESERVE) {
3723 		(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
3724 	}
3725 error_out:
3726 	/*
3727 	 * clear up state
3728 	 */
3729 	un->un_laststate = un->un_state;
3730 	un->un_state = ST_STATE_CLOSED;
3731 	un->un_lastop = ST_OP_NIL;
3732 	un->un_throttle = 1;	/* assume one request at time, for now */
3733 	un->un_retry_ct = 0;
3734 	un->un_errno = 0;
3735 	un->un_swr_token = (opaque_t)NULL;
3736 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3737 
3738 	/* Restore the options to the init time settings */
3739 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3740 		un->un_dp->options |= ST_READ_IGNORE_ILI;
3741 	} else {
3742 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3743 	}
3744 
3745 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3746 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3747 	} else {
3748 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3749 	}
3750 
3751 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3752 		un->un_dp->options |= ST_SHORT_FILEMARKS;
3753 	} else {
3754 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3755 	}
3756 
3757 	ASSERT(mutex_owned(ST_MUTEX));
3758 
3759 	/*
3760 	 * Signal anyone awaiting a close operation to complete.
3761 	 */
3762 	cv_signal(&un->un_clscv);
3763 
3764 	/*
3765 	 * any kind of error on closing causes all state to be tossed
3766 	 */
3767 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3768 		/*
3769 		 * note that st_intr has already set
3770 		 * un_pos.pmode to invalid.
3771 		 */
3772 		un->un_density_known = 0;
3773 	}
3774 
3775 #ifdef	__x86
3776 	/*
3777 	 * free any contiguous mem alloc'ed for big block I/O
3778 	 */
3779 	cp = un->un_contig_mem;
3780 	while (cp) {
3781 		if (cp->cm_addr) {
3782 			ddi_dma_mem_free(&cp->cm_acc_hdl);
3783 		}
3784 		cp_temp = cp;
3785 		cp = cp->cm_next;
3786 		kmem_free(cp_temp,
3787 		    sizeof (struct contig_mem) + biosize());
3788 	}
3789 	un->un_contig_mem_total_num = 0;
3790 	un->un_contig_mem_available_num = 0;
3791 	un->un_contig_mem = NULL;
3792 	un->un_max_contig_mem_len = 0;
3793 #endif
3794 
3795 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3796 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3797 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3798 
3799 	mutex_exit(ST_MUTEX);
3800 	return (err);
3801 }
3802 
3803 /*
3804  * These routines perform raw i/o operations.
3805  */
3806 
3807 /* ARGSUSED2 */
3808 static int
3809 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3810 {
3811 #ifdef STDEBUG
3812 	GET_SOFT_STATE(dev);
3813 	ST_ENTR(ST_DEVINFO, st_aread);
3814 #endif
3815 	return (st_arw(dev, aio, B_READ));
3816 }
3817 
3818 
3819 /* ARGSUSED2 */
3820 static int
3821 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3822 {
3823 #ifdef STDEBUG
3824 	GET_SOFT_STATE(dev);
3825 	ST_ENTR(ST_DEVINFO, st_awrite);
3826 #endif
3827 	return (st_arw(dev, aio, B_WRITE));
3828 }
3829 
3830 
3831 
3832 /* ARGSUSED */
3833 static int
3834 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3835 {
3836 #ifdef STDEBUG
3837 	GET_SOFT_STATE(dev);
3838 	ST_ENTR(ST_DEVINFO, st_read);
3839 #endif
3840 	return (st_rw(dev, uiop, B_READ));
3841 }
3842 
3843 /* ARGSUSED */
3844 static int
3845 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3846 {
3847 #ifdef STDEBUG
3848 	GET_SOFT_STATE(dev);
3849 	ST_ENTR(ST_DEVINFO, st_write);
3850 #endif
3851 	return (st_rw(dev, uiop, B_WRITE));
3852 }
3853 
3854 /*
3855  * Due to historical reasons, old limits are: For variable-length devices:
3856  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3857  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3858  * (let it through unmodified. For fixed-length record devices:
3859  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3860  *
3861  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3862  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3863  * command to the drive).
3864  *
3865  */
3866 static void
3867 st_minphys(struct buf *bp)
3868 {
3869 	struct scsi_tape *un;
3870 
3871 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3872 
3873 	ST_FUNC(ST_DEVINFO, st_minphys);
3874 
3875 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3876 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3877 	    bp->b_bcount);
3878 
3879 	if (un->un_allow_large_xfer) {
3880 
3881 		/*
3882 		 * check un_maxbsize for variable length devices only
3883 		 */
3884 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3885 			bp->b_bcount = un->un_maxbsize;
3886 		}
3887 		/*
3888 		 * can't go more that HBA maxdma limit in either fixed-length
3889 		 * or variable-length tape drives.
3890 		 */
3891 		if (bp->b_bcount > un->un_maxdma) {
3892 			bp->b_bcount = un->un_maxdma;
3893 		}
3894 	} else {
3895 
3896 		/*
3897 		 *  use old fixed limits
3898 		 */
3899 		if (un->un_bsize == 0) {
3900 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3901 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3902 			}
3903 		} else {
3904 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3905 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3906 			}
3907 		}
3908 	}
3909 
3910 	/*
3911 	 * For regular raw I/O and Fixed Block length devices, make sure
3912 	 * the adjusted block count is a whole multiple of the device
3913 	 * block size.
3914 	 */
3915 	if (bp != un->un_sbufp && un->un_bsize) {
3916 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3917 	}
3918 }
3919 
3920 static int
3921 st_rw(dev_t dev, struct uio *uio, int flag)
3922 {
3923 	int rval = 0;
3924 	long len;
3925 
3926 	GET_SOFT_STATE(dev);
3927 
3928 	ST_FUNC(ST_DEVINFO, st_rw);
3929 
3930 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3931 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3932 	    (flag == B_READ ? rd_str: wr_str));
3933 
3934 	/* get local copy of transfer length */
3935 	len = uio->uio_iov->iov_len;
3936 
3937 	mutex_enter(ST_MUTEX);
3938 
3939 	/*
3940 	 * Clear error entry stack
3941 	 */
3942 	st_empty_error_stack(un);
3943 
3944 	/*
3945 	 * If in fixed block size mode and requested read or write
3946 	 * is not an even multiple of that block size.
3947 	 */
3948 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3949 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3950 		    "%s: not modulo %d block size\n",
3951 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3952 		rval = EINVAL;
3953 	}
3954 
3955 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3956 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3957 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3958 		    "%s: not modulo %d device granularity\n",
3959 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3960 		rval = EINVAL;
3961 	}
3962 
3963 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
3964 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
3965 		rval = EFAULT;
3966 	}
3967 
3968 	if (rval != 0) {
3969 		un->un_errno = rval;
3970 		mutex_exit(ST_MUTEX);
3971 		return (rval);
3972 	}
3973 
3974 	/*
3975 	 * Reset this so it can be set if Berkeley and read over a filemark.
3976 	 */
3977 	un->un_silent_skip = 0;
3978 	mutex_exit(ST_MUTEX);
3979 
3980 	len = uio->uio_resid;
3981 
3982 	rval = physio(st_queued_strategy, (struct buf *)NULL,
3983 	    dev, flag, st_minphys, uio);
3984 	/*
3985 	 * if we have hit logical EOT during this xfer and there is not a
3986 	 * full residue, then set eof back  to ST_EOM to make sure that
3987 	 * the user will see at least one zero write
3988 	 * after this short write
3989 	 */
3990 	mutex_enter(ST_MUTEX);
3991 	if (un->un_pos.eof > ST_NO_EOF) {
3992 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3993 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3994 	}
3995 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3996 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3997 			un->un_pos.eof = ST_EOM;
3998 		} else if (uio->uio_resid == len) {
3999 			un->un_pos.eof = ST_NO_EOF;
4000 		}
4001 	}
4002 
4003 	if (un->un_silent_skip && uio->uio_resid != len) {
4004 		un->un_pos.eof = ST_EOF;
4005 		un->un_pos.blkno = un->un_save_blkno;
4006 		un->un_pos.fileno--;
4007 	}
4008 
4009 	un->un_errno = rval;
4010 
4011 	mutex_exit(ST_MUTEX);
4012 
4013 	return (rval);
4014 }
4015 
4016 static int
4017 st_arw(dev_t dev, struct aio_req *aio, int flag)
4018 {
4019 	struct uio *uio = aio->aio_uio;
4020 	int rval = 0;
4021 	long len;
4022 
4023 	GET_SOFT_STATE(dev);
4024 
4025 	ST_FUNC(ST_DEVINFO, st_arw);
4026 
4027 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4028 	    "st_arw(dev = 0x%lx, flag = %s)\n", dev,
4029 	    (flag == B_READ ? rd_str: wr_str));
4030 
4031 	/* get local copy of transfer length */
4032 	len = uio->uio_iov->iov_len;
4033 
4034 	mutex_enter(ST_MUTEX);
4035 
4036 	/*
4037 	 * If in fixed block size mode and requested read or write
4038 	 * is not an even multiple of that block size.
4039 	 */
4040 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
4041 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4042 		    "%s: not modulo %d block size\n",
4043 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
4044 		rval = EINVAL;
4045 	}
4046 
4047 	/* If device has set granularity in the READ_BLKLIM we honor it. */
4048 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
4049 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4050 		    "%s: not modulo %d device granularity\n",
4051 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
4052 		rval = EINVAL;
4053 	}
4054 
4055 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
4056 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
4057 		rval = EFAULT;
4058 	}
4059 
4060 	if (rval != 0) {
4061 		un->un_errno = rval;
4062 		mutex_exit(ST_MUTEX);
4063 		return (rval);
4064 	}
4065 
4066 	mutex_exit(ST_MUTEX);
4067 
4068 	len = uio->uio_resid;
4069 
4070 	rval =
4071 	    aphysio(st_queued_strategy, anocancel, dev, flag, st_minphys, aio);
4072 
4073 	/*
4074 	 * if we have hit logical EOT during this xfer and there is not a
4075 	 * full residue, then set eof back  to ST_EOM to make sure that
4076 	 * the user will see at least one zero write
4077 	 * after this short write
4078 	 *
4079 	 * we keep this here just in case the application is not using
4080 	 * persistent errors
4081 	 */
4082 	mutex_enter(ST_MUTEX);
4083 	if (un->un_pos.eof > ST_NO_EOF) {
4084 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4085 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
4086 	}
4087 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
4088 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
4089 			un->un_pos.eof = ST_EOM;
4090 		} else if (uio->uio_resid == len &&
4091 		    !(un->un_persistence && un->un_persist_errors)) {
4092 			un->un_pos.eof = ST_NO_EOF;
4093 		}
4094 	}
4095 	un->un_errno = rval;
4096 	mutex_exit(ST_MUTEX);
4097 
4098 	return (rval);
4099 }
4100 
4101 
4102 
4103 static int
4104 st_queued_strategy(buf_t *bp)
4105 {
4106 	struct scsi_tape *un;
4107 	char reading = bp->b_flags & B_READ;
4108 	int wasopening = 0;
4109 
4110 	/*
4111 	 * validate arguments
4112 	 */
4113 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4114 	if (un == NULL) {
4115 		bp->b_resid = bp->b_bcount;
4116 		bioerror(bp, ENXIO);
4117 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4118 		    "st_queued_strategy: ENXIO error exit\n");
4119 		biodone(bp);
4120 		return (0);
4121 	}
4122 
4123 	ST_ENTR(ST_DEVINFO, st_queued_strategy);
4124 
4125 	mutex_enter(ST_MUTEX);
4126 
4127 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4128 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4129 	}
4130 
4131 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4132 	    "st_queued_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4133 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4134 
4135 	/*
4136 	 * If persistent errors have been flagged, just nix this one. We wait
4137 	 * for any outstanding I/O's below, so we will be in order.
4138 	 */
4139 	if (un->un_persistence && un->un_persist_errors) {
4140 		goto exit;
4141 	}
4142 
4143 	/*
4144 	 * If last command was non queued, wait till it finishes.
4145 	 */
4146 	while (un->un_sbuf_busy) {
4147 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
4148 		/* woke up because of an error */
4149 		if (un->un_persistence && un->un_persist_errors) {
4150 			goto exit;
4151 		}
4152 	}
4153 
4154 	/*
4155 	 * s_buf and recovery commands shouldn't come here.
4156 	 */
4157 	ASSERT(bp != un->un_recov_buf);
4158 	ASSERT(bp != un->un_sbufp);
4159 
4160 	/*
4161 	 * If we haven't done/checked reservation on the tape unit
4162 	 * do it now.
4163 	 */
4164 	if ((un->un_rsvd_status &
4165 	    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
4166 		if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
4167 			if (st_reserve_release(un, ST_RESERVE, st_uscsi_cmd)) {
4168 				st_bioerror(bp, un->un_errno);
4169 				goto exit;
4170 			}
4171 		} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4172 			/*
4173 			 * Enter here to restore position for possible
4174 			 * resets when the device was closed and opened
4175 			 * in O_NDELAY mode subsequently
4176 			 */
4177 			un->un_state = ST_STATE_INITIALIZING;
4178 			(void) st_cmd(un, SCMD_TEST_UNIT_READY,
4179 			    0, SYNC_CMD);
4180 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4181 		}
4182 		un->un_rsvd_status |= ST_INIT_RESERVE;
4183 	}
4184 
4185 	/*
4186 	 * If we are offline, we have to initialize everything first.
4187 	 * This is to handle either when opened with O_NDELAY, or
4188 	 * we just got a new tape in the drive, after an offline.
4189 	 * We don't observe O_NDELAY past the open,
4190 	 * as it will not make sense for tapes.
4191 	 */
4192 	if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
4193 		/*
4194 		 * reset state to avoid recursion
4195 		 */
4196 		un->un_laststate = un->un_state;
4197 		un->un_state = ST_STATE_INITIALIZING;
4198 		if (st_tape_init(un)) {
4199 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4200 			    "stioctl : OFFLINE init failure ");
4201 			un->un_state = ST_STATE_OFFLINE;
4202 			un->un_pos.pmode = invalid;
4203 			goto b_done_err;
4204 		}
4205 		/* un_restore_pos make invalid */
4206 		un->un_state = ST_STATE_OPEN_PENDING_IO;
4207 		un->un_restore_pos = 0;
4208 	}
4209 	/*
4210 	 * Check for legal operations
4211 	 */
4212 	if (un->un_pos.pmode == invalid) {
4213 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4214 		    "strategy with un->un_pos.pmode invalid\n");
4215 		goto b_done_err;
4216 	}
4217 
4218 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4219 	    "st_queued_strategy(): regular io\n");
4220 
4221 	/*
4222 	 * Process this first. If we were reading, and we're pending
4223 	 * logical eot, that means we've bumped one file mark too far.
4224 	 */
4225 
4226 	/*
4227 	 * Recursion warning: st_cmd will route back through here.
4228 	 * Not anymore st_cmd will go through st_strategy()!
4229 	 */
4230 	if (un->un_pos.eof == ST_EOT_PENDING) {
4231 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4232 			un->un_pos.pmode = invalid;
4233 			un->un_density_known = 0;
4234 			goto b_done_err;
4235 		}
4236 		un->un_pos.blkno = 0; /* fix up block number.. */
4237 		un->un_pos.eof = ST_EOT;
4238 	}
4239 
4240 	/*
4241 	 * If we are in the process of opening, we may have to
4242 	 * determine/set the correct density. We also may have
4243 	 * to do a test_append (if QIC) to see whether we are
4244 	 * in a position to append to the end of the tape.
4245 	 *
4246 	 * If we're already at logical eot, we transition
4247 	 * to ST_NO_EOF. If we're at physical eot, we punt
4248 	 * to the switch statement below to handle.
4249 	 */
4250 	if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
4251 	    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
4252 
4253 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4254 			if (st_determine_density(un, (int)reading)) {
4255 				goto b_done_err;
4256 			}
4257 		}
4258 
4259 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4260 		    "pending_io@fileno %d rw %d qic %d eof %d\n",
4261 		    un->un_pos.fileno, (int)reading,
4262 		    (un->un_dp->options & ST_QIC) ? 1 : 0,
4263 		    un->un_pos.eof);
4264 
4265 		if (!reading && un->un_pos.eof != ST_EOM) {
4266 			if (un->un_pos.eof == ST_EOT) {
4267 				un->un_pos.eof = ST_NO_EOF;
4268 			} else if (un->un_pos.pmode != invalid &&
4269 			    (un->un_dp->options & ST_QIC)) {
4270 				/*
4271 				 * st_test_append() will do it all
4272 				 */
4273 				st_test_append(bp);
4274 				mutex_exit(ST_MUTEX);
4275 				return (0);
4276 			}
4277 		}
4278 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4279 			wasopening = 1;
4280 		}
4281 		un->un_laststate = un->un_state;
4282 		un->un_state = ST_STATE_OPEN;
4283 	}
4284 
4285 
4286 	/*
4287 	 * Process rest of END OF FILE and END OF TAPE conditions
4288 	 */
4289 
4290 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4291 	    "eof=%x, wasopening=%x\n",
4292 	    un->un_pos.eof, wasopening);
4293 
4294 	switch (un->un_pos.eof) {
4295 	case ST_EOM:
4296 		/*
4297 		 * This allows writes to proceed past physical
4298 		 * eot. We'll *really* be in trouble if the
4299 		 * user continues blindly writing data too
4300 		 * much past this point (unwind the tape).
4301 		 * Physical eot really means 'early warning
4302 		 * eot' in this context.
4303 		 *
4304 		 * Every other write from now on will succeed
4305 		 * (if sufficient  tape left).
4306 		 * This write will return with resid == count
4307 		 * but the next one should be successful
4308 		 *
4309 		 * Note that we only transition to logical EOT
4310 		 * if the last state wasn't the OPENING state.
4311 		 * We explicitly prohibit running up to physical
4312 		 * eot, closing the device, and then re-opening
4313 		 * to proceed. Trailer records may only be gotten
4314 		 * at by keeping the tape open after hitting eot.
4315 		 *
4316 		 * Also note that ST_EOM cannot be set by reading-
4317 		 * this can only be set during writing. Reading
4318 		 * up to the end of the tape gets a blank check
4319 		 * or a double-filemark indication (ST_EOT_PENDING),
4320 		 * and we prohibit reading after that point.
4321 		 *
4322 		 */
4323 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
4324 		if (wasopening == 0) {
4325 			/*
4326 			 * this allows st_rw() to reset it back to
4327 			 * will see a zero write
4328 			 */
4329 			un->un_pos.eof = ST_WRITE_AFTER_EOM;
4330 		}
4331 		un->un_status = SUN_KEY_EOT;
4332 		goto b_done;
4333 
4334 	case ST_WRITE_AFTER_EOM:
4335 	case ST_EOT:
4336 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
4337 		un->un_status = SUN_KEY_EOT;
4338 		if (SVR4_BEHAVIOR && reading) {
4339 			goto b_done_err;
4340 		}
4341 
4342 		if (reading) {
4343 			goto b_done;
4344 		}
4345 		un->un_pos.eof = ST_NO_EOF;
4346 		break;
4347 
4348 	case ST_EOF_PENDING:
4349 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4350 		    "EOF PENDING\n");
4351 		un->un_status = SUN_KEY_EOF;
4352 		if (SVR4_BEHAVIOR) {
4353 			un->un_pos.eof = ST_EOF;
4354 			goto b_done;
4355 		}
4356 		/* FALLTHROUGH */
4357 	case ST_EOF:
4358 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
4359 		un->un_status = SUN_KEY_EOF;
4360 		if (SVR4_BEHAVIOR) {
4361 			goto b_done_err;
4362 		}
4363 
4364 		if (BSD_BEHAVIOR) {
4365 			un->un_pos.eof = ST_NO_EOF;
4366 			un->un_pos.fileno += 1;
4367 			un->un_pos.blkno   = 0;
4368 		}
4369 
4370 		if (reading) {
4371 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4372 			    "now file %d (read)\n",
4373 			    un->un_pos.fileno);
4374 			goto b_done;
4375 		}
4376 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4377 		    "now file %d (write)\n", un->un_pos.fileno);
4378 		break;
4379 	default:
4380 		un->un_status = 0;
4381 		break;
4382 	}
4383 
4384 	bp->b_flags &= ~(B_DONE);
4385 	st_bioerror(bp, 0);
4386 	bp->av_forw = NULL;
4387 	bp->b_resid = 0;
4388 	SET_BP_PKT(bp, 0);
4389 
4390 
4391 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4392 	    "st_queued_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4393 	    " pkt=0x%p\n",
4394 	    (void *)bp->b_forw, bp->b_bcount,
4395 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4396 
4397 #ifdef	__x86
4398 	/*
4399 	 * We will replace bp with a new bp that can do big blk xfer
4400 	 * if the requested xfer size is bigger than un->un_maxdma_arch
4401 	 *
4402 	 * Also, we need to make sure that we're handling real I/O
4403 	 * by checking group 0/1 SCSI I/O commands, if needed
4404 	 */
4405 	if (bp->b_bcount > un->un_maxdma_arch &&
4406 	    ((uchar_t)(uintptr_t)bp->b_forw == SCMD_READ ||
4407 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G4 ||
4408 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE ||
4409 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G4)) {
4410 		mutex_exit(ST_MUTEX);
4411 		bp = st_get_bigblk_bp(bp);
4412 		mutex_enter(ST_MUTEX);
4413 	}
4414 #endif
4415 
4416 	/* put on wait queue */
4417 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4418 	    "st_queued_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4419 	    (void *)un->un_quef, (void *)bp);
4420 
4421 	st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quel, bp);
4422 
4423 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4424 
4425 	st_start(un);
4426 
4427 	mutex_exit(ST_MUTEX);
4428 	return (0);
4429 
4430 b_done_err:
4431 	st_bioerror(bp, EIO);
4432 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4433 	    "st_queued_strategy : EIO b_done_err\n");
4434 
4435 b_done:
4436 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4437 	    "st_queued_strategy: b_done\n");
4438 
4439 exit:
4440 	/*
4441 	 * make sure no commands are outstanding or waiting before closing,
4442 	 * so we can guarantee order
4443 	 */
4444 	st_wait_for_io(un);
4445 	un->un_err_resid = bp->b_resid = bp->b_bcount;
4446 
4447 	/* override errno here, if persistent errors were flagged */
4448 	if (un->un_persistence && un->un_persist_errors)
4449 		bioerror(bp, un->un_errno);
4450 
4451 	mutex_exit(ST_MUTEX);
4452 
4453 	biodone(bp);
4454 	ASSERT(mutex_owned(ST_MUTEX) == 0);
4455 	return (0);
4456 }
4457 
4458 
4459 static int
4460 st_strategy(struct buf *bp)
4461 {
4462 	struct scsi_tape *un;
4463 
4464 	/*
4465 	 * validate arguments
4466 	 */
4467 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4468 	if (un == NULL) {
4469 		bp->b_resid = bp->b_bcount;
4470 		bioerror(bp, ENXIO);
4471 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4472 		    "st_strategy: ENXIO error exit\n");
4473 
4474 		biodone(bp);
4475 		return (0);
4476 
4477 	}
4478 
4479 	ST_ENTR(ST_DEVINFO, st_strategy);
4480 
4481 	mutex_enter(ST_MUTEX);
4482 
4483 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4484 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4485 	}
4486 
4487 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4488 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4489 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4490 
4491 	ASSERT((bp == un->un_recov_buf) || (bp == un->un_sbufp));
4492 
4493 	bp->b_flags &= ~(B_DONE);
4494 	st_bioerror(bp, 0);
4495 	bp->av_forw = NULL;
4496 	bp->b_resid = 0;
4497 	SET_BP_PKT(bp, 0);
4498 
4499 
4500 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4501 	    "st_strategy: cmd=0x%x  count=%ld  resid=%ld flags=0x%x"
4502 	    " pkt=0x%p\n",
4503 	    (unsigned char)(uintptr_t)bp->b_forw, bp->b_bcount,
4504 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4505 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4506 
4507 	st_start(un);
4508 
4509 	mutex_exit(ST_MUTEX);
4510 	return (0);
4511 }
4512 
4513 /*
4514  * this routine spaces forward over filemarks
4515  */
4516 static int
4517 st_space_fmks(struct scsi_tape *un, int64_t count)
4518 {
4519 	int rval = 0;
4520 
4521 	ST_FUNC(ST_DEVINFO, st_space_fmks);
4522 
4523 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4524 	    "st_space_fmks(dev = 0x%lx, count = %"PRIx64")\n",
4525 	    un->un_dev, count);
4526 
4527 	ASSERT(mutex_owned(ST_MUTEX));
4528 
4529 	/*
4530 	 * the risk with doing only one space operation is that we
4531 	 * may accidentily jump in old data
4532 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4533 	 * because the 8200 does not append a marker; in order not to
4534 	 * sacrifice the fast file skip, we do a slow skip if the low
4535 	 * density device has been opened
4536 	 */
4537 
4538 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4539 	    !((un->un_dp->type == ST_TYPE_EXB8500 &&
4540 	    MT_DENSITY(un->un_dev) == 0))) {
4541 		if (st_cmd(un, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4542 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4543 			    "space_fmks : EIO can't do space cmd #1\n");
4544 			rval = EIO;
4545 		}
4546 	} else {
4547 		while (count > 0) {
4548 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4549 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4550 				    "space_fmks : EIO can't do space cmd #2\n");
4551 				rval = EIO;
4552 				break;
4553 			}
4554 			count -= 1;
4555 			/*
4556 			 * read a block to see if we have reached
4557 			 * end of medium (double filemark for reel or
4558 			 * medium error for others)
4559 			 */
4560 			if (count > 0) {
4561 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
4562 					ST_DEBUG2(ST_DEVINFO, st_label,
4563 					    SCSI_DEBUG,
4564 					    "space_fmks : EIO can't do "
4565 					    "space cmd #3\n");
4566 					rval = EIO;
4567 					break;
4568 				}
4569 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4570 				    (un->un_dp->options & ST_REEL)) {
4571 					un->un_status = SUN_KEY_EOT;
4572 					ST_DEBUG2(ST_DEVINFO, st_label,
4573 					    SCSI_DEBUG,
4574 					    "space_fmks : EIO ST_REEL\n");
4575 					rval = EIO;
4576 					break;
4577 				} else if (IN_EOF(un->un_pos)) {
4578 					un->un_pos.eof = ST_NO_EOF;
4579 					un->un_pos.fileno++;
4580 					un->un_pos.blkno = 0;
4581 					count--;
4582 				} else if (un->un_pos.eof > ST_EOF) {
4583 					ST_DEBUG2(ST_DEVINFO, st_label,
4584 					    SCSI_DEBUG,
4585 					    "space_fmks, EIO > ST_EOF\n");
4586 					rval = EIO;
4587 					break;
4588 				}
4589 
4590 			}
4591 		}
4592 		un->un_err_resid = count;
4593 		COPY_POS(&un->un_pos, &un->un_err_pos);
4594 	}
4595 	ASSERT(mutex_owned(ST_MUTEX));
4596 	return (rval);
4597 }
4598 
4599 /*
4600  * this routine spaces to EOD
4601  *
4602  * it keeps track of the current filenumber and returns the filenumber after
4603  * the last successful space operation, we keep the number high because as
4604  * tapes are getting larger, the possibility of more and more files exist,
4605  * 0x100000 (1 Meg of files) probably will never have to be changed any time
4606  * soon
4607  */
4608 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4609 
4610 static int
4611 st_find_eod(struct scsi_tape *un)
4612 {
4613 	tapepos_t savepos;
4614 	int64_t sp_type;
4615 	int result;
4616 
4617 	if (un == NULL) {
4618 		return (-1);
4619 	}
4620 
4621 	ST_FUNC(ST_DEVINFO, st_find_eod);
4622 
4623 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4624 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", un->un_dev,
4625 	    un->un_pos.fileno);
4626 
4627 	ASSERT(mutex_owned(ST_MUTEX));
4628 
4629 	COPY_POS(&savepos, &un->un_pos);
4630 
4631 	/*
4632 	 * see if the drive is smart enough to do the skips in
4633 	 * one operation; 1/2" use two filemarks
4634 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4635 	 * because the 8200 does not append a marker; in order not to
4636 	 * sacrifice the fast file skip, we do a slow skip if the low
4637 	 * density device has been opened
4638 	 */
4639 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4640 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4641 		    (MT_DENSITY(un->un_dev) == 0)) {
4642 			sp_type = Fmk(1);
4643 		} else if (un->un_pos.pmode == logical) {
4644 			sp_type = SPACE(SP_EOD, 0);
4645 		} else {
4646 			sp_type = Fmk(MAX_SKIP);
4647 		}
4648 	} else {
4649 		sp_type = Fmk(1);
4650 	}
4651 
4652 	for (;;) {
4653 		result = st_cmd(un, SCMD_SPACE, sp_type, SYNC_CMD);
4654 
4655 		if (result == 0) {
4656 			COPY_POS(&savepos, &un->un_pos);
4657 		}
4658 
4659 		if (sp_type == SPACE(SP_EOD, 0)) {
4660 			if (result != 0) {
4661 				sp_type = Fmk(MAX_SKIP);
4662 				continue;
4663 			}
4664 
4665 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4666 			    "st_find_eod: 0x%"PRIx64"\n",
4667 			    savepos.lgclblkno);
4668 			/*
4669 			 * What we return will become the current file position.
4670 			 * After completing the space command with the position
4671 			 * mode that is not invalid a read position command will
4672 			 * be automaticly issued. If the drive support the long
4673 			 * read position format a valid file position can be
4674 			 * returned.
4675 			 */
4676 			return (un->un_pos.fileno);
4677 		}
4678 
4679 		if (result != 0) {
4680 			break;
4681 		}
4682 
4683 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4684 		    "count=%"PRIx64", eof=%x, status=%x\n",
4685 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4686 
4687 		/*
4688 		 * If we're not EOM smart,  space a record
4689 		 * to see whether we're now in the slot between
4690 		 * the two sequential filemarks that logical
4691 		 * EOM consists of (REEL) or hit nowhere land
4692 		 * (8mm).
4693 		 */
4694 		if (sp_type == Fmk(1)) {
4695 			/*
4696 			 * no fast skipping, check a record
4697 			 */
4698 			if (st_cmd(un, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4699 				break;
4700 			}
4701 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4702 			    (un->un_dp->options & ST_REEL)) {
4703 				un->un_status = KEY_BLANK_CHECK;
4704 				un->un_pos.fileno++;
4705 				un->un_pos.blkno = 0;
4706 				break;
4707 			}
4708 			if (IN_EOF(un->un_pos)) {
4709 				un->un_pos.eof = ST_NO_EOF;
4710 				un->un_pos.fileno++;
4711 				un->un_pos.blkno = 0;
4712 			}
4713 			if (un->un_pos.eof > ST_EOF) {
4714 				break;
4715 			}
4716 		} else {
4717 			if (un->un_pos.eof > ST_EOF) {
4718 				break;
4719 			}
4720 		}
4721 	}
4722 
4723 	if (un->un_dp->options & ST_KNOWS_EOD) {
4724 		COPY_POS(&savepos, &un->un_pos);
4725 	}
4726 
4727 	ASSERT(mutex_owned(ST_MUTEX));
4728 
4729 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4730 	    "st_find_eod: %x\n", savepos.fileno);
4731 	return (savepos.fileno);
4732 }
4733 
4734 
4735 /*
4736  * this routine is frequently used in ioctls below;
4737  * it determines whether we know the density and if not will
4738  * determine it
4739  * if we have written the tape before, one or more filemarks are written
4740  *
4741  * depending on the stepflag, the head is repositioned to where it was before
4742  * the filemarks were written in order not to confuse step counts
4743  */
4744 #define	STEPBACK    0
4745 #define	NO_STEPBACK 1
4746 
4747 static int
4748 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4749 {
4750 
4751 	GET_SOFT_STATE(dev);
4752 
4753 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4754 
4755 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4756 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4757 	    "\n", dev, wfm, mode, stepflag);
4758 
4759 	ASSERT(mutex_owned(ST_MUTEX));
4760 
4761 	/*
4762 	 * If we don't yet know the density of the tape we have inserted,
4763 	 * we have to either unconditionally set it (if we're 'writing'),
4764 	 * or we have to determine it. As side effects, check for any
4765 	 * write-protect errors, and for the need to put out any file-marks
4766 	 * before positioning a tape.
4767 	 *
4768 	 * If we are going to be spacing forward, and we haven't determined
4769 	 * the tape density yet, we have to do so now...
4770 	 */
4771 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4772 		if (st_determine_density(un, mode)) {
4773 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4774 			    "check_density_or_wfm : EIO can't determine "
4775 			    "density\n");
4776 			un->un_errno = EIO;
4777 			return (EIO);
4778 		}
4779 		/*
4780 		 * Presumably we are at BOT. If we attempt to write, it will
4781 		 * either work okay, or bomb. We don't do a st_test_append
4782 		 * unless we're past BOT.
4783 		 */
4784 		un->un_laststate = un->un_state;
4785 		un->un_state = ST_STATE_OPEN;
4786 
4787 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4788 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4789 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4790 
4791 		tapepos_t spos;
4792 
4793 		COPY_POS(&spos, &un->un_pos);
4794 
4795 		/*
4796 		 * We need to write one or two filemarks.
4797 		 * In the case of the HP, we need to
4798 		 * position the head between the two
4799 		 * marks.
4800 		 */
4801 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4802 			wfm = un->un_fmneeded;
4803 			un->un_fmneeded = 0;
4804 		}
4805 
4806 		if (st_write_fm(dev, wfm)) {
4807 			un->un_pos.pmode = invalid;
4808 			un->un_density_known = 0;
4809 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4810 			    "check_density_or_wfm : EIO can't write fm\n");
4811 			un->un_errno = EIO;
4812 			return (EIO);
4813 		}
4814 
4815 		if (stepflag == STEPBACK) {
4816 			if (st_cmd(un, SCMD_SPACE, Fmk(-wfm), SYNC_CMD)) {
4817 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4818 				    "check_density_or_wfm : EIO can't space "
4819 				    "(-wfm)\n");
4820 				un->un_errno = EIO;
4821 				return (EIO);
4822 			}
4823 			COPY_POS(&un->un_pos, &spos);
4824 		}
4825 	}
4826 
4827 	/*
4828 	 * Whatever we do at this point clears the state of the eof flag.
4829 	 */
4830 
4831 	un->un_pos.eof = ST_NO_EOF;
4832 
4833 	/*
4834 	 * If writing, let's check that we're positioned correctly
4835 	 * at the end of tape before issuing the next write.
4836 	 */
4837 	if (un->un_read_only == RDWR) {
4838 		un->un_test_append = 1;
4839 	}
4840 
4841 	ASSERT(mutex_owned(ST_MUTEX));
4842 	return (0);
4843 }
4844 
4845 
4846 /*
4847  * Wait for all outstaning I/O's to complete
4848  *
4849  * we wait on both ncmds and the wait queue for times when we are flushing
4850  * after persistent errors are flagged, which is when ncmds can be 0, and the
4851  * queue can still have I/O's.  This way we preserve order of biodone's.
4852  */
4853 static void
4854 st_wait_for_io(struct scsi_tape *un)
4855 {
4856 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4857 	ASSERT(mutex_owned(ST_MUTEX));
4858 	while ((un->un_ncmds) || (un->un_quef) || (un->un_runqf)) {
4859 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4860 	}
4861 }
4862 
4863 /*
4864  * This routine implements the ioctl calls.  It is called
4865  * from the device switch at normal priority.
4866  */
4867 /*ARGSUSED*/
4868 static int
4869 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4870     int *rval_p)
4871 {
4872 	int tmp, rval = 0;
4873 
4874 	GET_SOFT_STATE(dev);
4875 
4876 	ST_ENTR(ST_DEVINFO, st_ioctl);
4877 
4878 	mutex_enter(ST_MUTEX);
4879 
4880 	ASSERT(un->un_recov_buf_busy == 0);
4881 
4882 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4883 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4884 	    "pe_flag = %d\n",
4885 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4886 	    un->un_persistence && un->un_persist_errors);
4887 
4888 	/*
4889 	 * We don't want to block on these, so let them through
4890 	 * and we don't care about setting driver states here.
4891 	 */
4892 	if ((cmd == MTIOCGETDRIVETYPE) ||
4893 	    (cmd == MTIOCGUARANTEEDORDER) ||
4894 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4895 		goto check_commands;
4896 	}
4897 
4898 	/*
4899 	 * We clear error entry stack except command
4900 	 * MTIOCGETERROR and MTIOCGET
4901 	 */
4902 	if ((cmd != MTIOCGETERROR) &&
4903 	    (cmd != MTIOCGET)) {
4904 		st_empty_error_stack(un);
4905 	}
4906 
4907 	/*
4908 	 * wait for all outstanding commands to complete, or be dequeued.
4909 	 * And because ioctl's are synchronous commands, any return value
4910 	 * after this,  will be in order
4911 	 */
4912 	st_wait_for_io(un);
4913 
4914 	/*
4915 	 * allow only a through clear errors and persistent status, and
4916 	 * status
4917 	 */
4918 	if (un->un_persistence && un->un_persist_errors) {
4919 		if ((cmd == MTIOCLRERR) ||
4920 		    (cmd == MTIOCPERSISTENT) ||
4921 		    (cmd == MTIOCGET)) {
4922 			goto check_commands;
4923 		} else {
4924 			rval = un->un_errno;
4925 			goto exit;
4926 		}
4927 	}
4928 
4929 	ASSERT(un->un_throttle != 0);
4930 	un->un_throttle = 1;	/* > 1 will never happen here */
4931 	un->un_errno = 0;	/* start clean from here */
4932 
4933 	/*
4934 	 * first and foremost, handle any ST_EOT_PENDING cases.
4935 	 * That is, if a logical eot is pending notice, notice it.
4936 	 */
4937 	if (un->un_pos.eof == ST_EOT_PENDING) {
4938 		int resid = un->un_err_resid;
4939 		uchar_t status = un->un_status;
4940 		uchar_t lastop = un->un_lastop;
4941 
4942 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4943 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4944 			    "stioctl : EIO can't space fmk(-1)\n");
4945 			rval = EIO;
4946 			goto exit;
4947 		}
4948 		un->un_lastop = lastop; /* restore last operation */
4949 		if (status == SUN_KEY_EOF) {
4950 			un->un_status = SUN_KEY_EOT;
4951 		} else {
4952 			un->un_status = status;
4953 		}
4954 		un->un_err_resid  = resid;
4955 		/* fix up block number */
4956 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4957 		/* now we're at logical eot */
4958 		un->un_pos.eof = ST_EOT;
4959 	}
4960 
4961 	/*
4962 	 * now, handle the rest of the situations
4963 	 */
4964 check_commands:
4965 	switch (cmd) {
4966 	case MTIOCGET:
4967 	{
4968 #ifdef _MULTI_DATAMODEL
4969 		/*
4970 		 * For use when a 32 bit app makes a call into a
4971 		 * 64 bit ioctl
4972 		 */
4973 		struct mtget32		mtg_local32;
4974 		struct mtget32 		*mtget_32 = &mtg_local32;
4975 #endif /* _MULTI_DATAMODEL */
4976 
4977 			/* Get tape status */
4978 		struct mtget mtg_local;
4979 		struct mtget *mtget = &mtg_local;
4980 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4981 		    "st_ioctl: MTIOCGET\n");
4982 
4983 		bzero((caddr_t)mtget, sizeof (struct mtget));
4984 		mtget->mt_erreg = un->un_status;
4985 		mtget->mt_resid = un->un_err_resid;
4986 		mtget->mt_dsreg = un->un_retry_ct;
4987 		if (un->un_err_pos.pmode == legacy) {
4988 			mtget->mt_fileno = un->un_err_pos.fileno;
4989 		} else {
4990 			mtget->mt_fileno = -1;
4991 		}
4992 		/*
4993 		 * If the value is positive fine.
4994 		 * If its negative we need to return a value based on the
4995 		 * old way if counting backwards from INF (1,000,000,000).
4996 		 */
4997 		if (un->un_err_pos.blkno >= 0) {
4998 			mtget->mt_blkno = un->un_err_pos.blkno;
4999 		} else {
5000 			mtget->mt_blkno = INF + 1 - (-un->un_err_pos.blkno);
5001 		}
5002 		mtget->mt_type = un->un_dp->type;
5003 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
5004 		if (un->un_read_pos_type != NO_POS) {
5005 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
5006 		}
5007 		if (un->un_dp->options & ST_REEL) {
5008 			mtget->mt_flags |= MTF_REEL;
5009 			mtget->mt_bf = 20;
5010 		} else {		/* 1/4" cartridges */
5011 			switch (mtget->mt_type) {
5012 			/* Emulex cartridge tape */
5013 			case MT_ISMT02:
5014 				mtget->mt_bf = 40;
5015 				break;
5016 			default:
5017 				mtget->mt_bf = 126;
5018 				break;
5019 			}
5020 		}
5021 
5022 		/*
5023 		 * If large transfers are allowed and drive options
5024 		 * has no record size limit set. Calculate blocking
5025 		 * factor from the lesser of maxbsize and maxdma.
5026 		 */
5027 		if ((un->un_allow_large_xfer) &&
5028 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
5029 			mtget->mt_bf = min(un->un_maxbsize,
5030 			    un->un_maxdma) / SECSIZE;
5031 		}
5032 
5033 		if (un->un_read_only == WORM ||
5034 		    un->un_read_only == RDWORM) {
5035 			mtget->mt_flags |= MTF_WORM_MEDIA;
5036 		}
5037 
5038 		/*
5039 		 * In persistent error mode sending a non-queued can hang
5040 		 * because this ioctl gets to be run without turning off
5041 		 * persistense. Fake the answer based on previous info.
5042 		 */
5043 		if (un->un_persistence) {
5044 			rval = 0;
5045 		} else {
5046 			rval = st_check_clean_bit(un);
5047 		}
5048 		if (rval == 0) {
5049 			/*
5050 			 * If zero is returned or in persistent mode,
5051 			 * use the old data.
5052 			 */
5053 			if ((un->un_HeadClean & (TAPE_ALERT_SUPPORTED |
5054 			    TAPE_SEQUENTIAL_SUPPORTED|TAPE_ALERT_NOT_SUPPORTED))
5055 			    != TAPE_ALERT_NOT_SUPPORTED) {
5056 				mtget->mt_flags |= MTF_TAPE_CLN_SUPPORTED;
5057 			}
5058 			if (un->un_HeadClean & (TAPE_PREVIOUSLY_DIRTY |
5059 			    TAPE_ALERT_STILL_DIRTY)) {
5060 				mtget->mt_flags |= MTF_TAPE_HEAD_DIRTY;
5061 			}
5062 		} else {
5063 			mtget->mt_flags |= (ushort_t)rval;
5064 			rval = 0;
5065 		}
5066 
5067 		un->un_status = 0;		/* Reset status */
5068 		un->un_err_resid = 0;
5069 		tmp = sizeof (struct mtget);
5070 
5071 #ifdef _MULTI_DATAMODEL
5072 
5073 		switch (ddi_model_convert_from(flag & FMODELS)) {
5074 		case DDI_MODEL_ILP32:
5075 			/*
5076 			 * Convert 64 bit back to 32 bit before doing
5077 			 * copyout. This is what the ILP32 app expects.
5078 			 */
5079 			mtget_32->mt_erreg = 	mtget->mt_erreg;
5080 			mtget_32->mt_resid = 	mtget->mt_resid;
5081 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
5082 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
5083 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
5084 			mtget_32->mt_type =  	mtget->mt_type;
5085 			mtget_32->mt_flags = 	mtget->mt_flags;
5086 			mtget_32->mt_bf = 	mtget->mt_bf;
5087 
5088 			if (ddi_copyout(mtget_32, (void *)arg,
5089 			    sizeof (struct mtget32), flag)) {
5090 				rval = EFAULT;
5091 			}
5092 			break;
5093 
5094 		case DDI_MODEL_NONE:
5095 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5096 				rval = EFAULT;
5097 			}
5098 			break;
5099 		}
5100 #else /* ! _MULTI_DATAMODE */
5101 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5102 			rval = EFAULT;
5103 		}
5104 #endif /* _MULTI_DATAMODE */
5105 
5106 		break;
5107 	}
5108 	case MTIOCGETERROR:
5109 			/*
5110 			 * get error entry from error stack
5111 			 */
5112 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5113 			    "st_ioctl: MTIOCGETERROR\n");
5114 
5115 			rval = st_get_error_entry(un, arg, flag);
5116 
5117 			break;
5118 
5119 	case MTIOCSTATE:
5120 		{
5121 			/*
5122 			 * return when media presence matches state
5123 			 */
5124 			enum mtio_state state;
5125 
5126 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5127 			    "st_ioctl: MTIOCSTATE\n");
5128 
5129 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
5130 				rval = EFAULT;
5131 
5132 			mutex_exit(ST_MUTEX);
5133 
5134 			rval = st_check_media(dev, state);
5135 
5136 			mutex_enter(ST_MUTEX);
5137 
5138 			if (rval != 0) {
5139 				break;
5140 			}
5141 
5142 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
5143 			    sizeof (int), flag))
5144 				rval = EFAULT;
5145 			break;
5146 
5147 		}
5148 
5149 	case MTIOCGETDRIVETYPE:
5150 		{
5151 #ifdef _MULTI_DATAMODEL
5152 		/*
5153 		 * For use when a 32 bit app makes a call into a
5154 		 * 64 bit ioctl
5155 		 */
5156 		struct mtdrivetype_request32	mtdtrq32;
5157 #endif /* _MULTI_DATAMODEL */
5158 
5159 			/*
5160 			 * return mtdrivetype
5161 			 */
5162 			struct mtdrivetype_request mtdtrq;
5163 			struct mtdrivetype mtdrtyp;
5164 			struct mtdrivetype *mtdt = &mtdrtyp;
5165 			struct st_drivetype *stdt = un->un_dp;
5166 
5167 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5168 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
5169 
5170 #ifdef _MULTI_DATAMODEL
5171 		switch (ddi_model_convert_from(flag & FMODELS)) {
5172 		case DDI_MODEL_ILP32:
5173 		{
5174 			if (ddi_copyin((void *)arg, &mtdtrq32,
5175 			    sizeof (struct mtdrivetype_request32), flag)) {
5176 				rval = EFAULT;
5177 				break;
5178 			}
5179 			mtdtrq.size = mtdtrq32.size;
5180 			mtdtrq.mtdtp =
5181 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
5182 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5183 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
5184 			break;
5185 		}
5186 		case DDI_MODEL_NONE:
5187 			if (ddi_copyin((void *)arg, &mtdtrq,
5188 			    sizeof (struct mtdrivetype_request), flag)) {
5189 				rval = EFAULT;
5190 				break;
5191 			}
5192 			break;
5193 		}
5194 
5195 #else /* ! _MULTI_DATAMODEL */
5196 		if (ddi_copyin((void *)arg, &mtdtrq,
5197 		    sizeof (struct mtdrivetype_request), flag)) {
5198 			rval = EFAULT;
5199 			break;
5200 		}
5201 #endif /* _MULTI_DATAMODEL */
5202 
5203 			/*
5204 			 * if requested size is < 0 then return
5205 			 * error.
5206 			 */
5207 			if (mtdtrq.size < 0) {
5208 				rval = EINVAL;
5209 				break;
5210 			}
5211 			bzero(mtdt, sizeof (struct mtdrivetype));
5212 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
5213 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
5214 			mtdt->type = stdt->type;
5215 			mtdt->bsize = stdt->bsize;
5216 			mtdt->options = stdt->options;
5217 			mtdt->max_rretries = stdt->max_rretries;
5218 			mtdt->max_wretries = stdt->max_wretries;
5219 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5220 				mtdt->densities[tmp] = stdt->densities[tmp];
5221 			}
5222 			mtdt->default_density = stdt->default_density;
5223 			/*
5224 			 * Speed hasn't been used since the hayday of reel tape.
5225 			 * For all drives not setting the option ST_KNOWS_MEDIA
5226 			 * the speed member renamed to mediatype are zeros.
5227 			 * Those drives that have ST_KNOWS_MEDIA set use the
5228 			 * new mediatype member which is used to figure the
5229 			 * type of media loaded.
5230 			 *
5231 			 * So as to not break applications speed in the
5232 			 * mtdrivetype structure is not renamed.
5233 			 */
5234 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5235 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
5236 			}
5237 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
5238 			mtdt->io_timeout = stdt->io_timeout;
5239 			mtdt->rewind_timeout = stdt->rewind_timeout;
5240 			mtdt->space_timeout = stdt->space_timeout;
5241 			mtdt->load_timeout = stdt->load_timeout;
5242 			mtdt->unload_timeout = stdt->unload_timeout;
5243 			mtdt->erase_timeout = stdt->erase_timeout;
5244 
5245 			/*
5246 			 * Limit the maximum length of the result to
5247 			 * sizeof (struct mtdrivetype).
5248 			 */
5249 			tmp = sizeof (struct mtdrivetype);
5250 			if (mtdtrq.size < tmp)
5251 				tmp = mtdtrq.size;
5252 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
5253 				rval = EFAULT;
5254 			}
5255 			break;
5256 		}
5257 	case MTIOCPERSISTENT:
5258 
5259 		if (ddi_copyin((void *)arg, &tmp, sizeof (tmp), flag)) {
5260 			rval = EFAULT;
5261 			break;
5262 		}
5263 
5264 		if (tmp) {
5265 			st_turn_pe_on(un);
5266 		} else {
5267 			st_turn_pe_off(un);
5268 		}
5269 
5270 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5271 		    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
5272 		    un->un_persistence);
5273 
5274 		break;
5275 
5276 	case MTIOCPERSISTENTSTATUS:
5277 		tmp = (int)un->un_persistence;
5278 
5279 		if (ddi_copyout(&tmp, (void *)arg, sizeof (tmp), flag)) {
5280 			rval = EFAULT;
5281 		}
5282 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5283 		    "st_ioctl: MTIOCPERSISTENTSTATUS:persistence = %d\n",
5284 		    un->un_persistence);
5285 
5286 		break;
5287 
5288 	case MTIOCLRERR:
5289 		{
5290 			/* clear persistent errors */
5291 
5292 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5293 			    "st_ioctl: MTIOCLRERR\n");
5294 
5295 			st_clear_pe(un);
5296 
5297 			break;
5298 		}
5299 
5300 	case MTIOCGUARANTEEDORDER:
5301 		{
5302 			/*
5303 			 * this is just a holder to make a valid ioctl and
5304 			 * it won't be in any earlier release
5305 			 */
5306 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5307 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
5308 
5309 			break;
5310 		}
5311 
5312 	case MTIOCRESERVE:
5313 		{
5314 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5315 			    "st_ioctl: MTIOCRESERVE\n");
5316 
5317 			/*
5318 			 * Check if Reserve/Release is supported.
5319 			 */
5320 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5321 				rval = ENOTTY;
5322 				break;
5323 			}
5324 
5325 			rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5326 
5327 			if (rval == 0) {
5328 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
5329 			}
5330 			break;
5331 		}
5332 
5333 	case MTIOCRELEASE:
5334 		{
5335 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5336 			    "st_ioctl: MTIOCRELEASE\n");
5337 
5338 			/*
5339 			 * Check if Reserve/Release is supported.
5340 			 */
5341 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5342 				rval = ENOTTY;
5343 				break;
5344 			}
5345 
5346 			/*
5347 			 * Used to just clear ST_PRESERVE_RESERVE which
5348 			 * made the reservation release at next close.
5349 			 * As the user may have opened and then done a
5350 			 * persistant reservation we now need to drop
5351 			 * the reservation without closing if the user
5352 			 * attempts to do this.
5353 			 */
5354 			rval = st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
5355 
5356 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5357 
5358 			break;
5359 		}
5360 
5361 	case MTIOCFORCERESERVE:
5362 	{
5363 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5364 		    "st_ioctl: MTIOCFORCERESERVE\n");
5365 
5366 		/*
5367 		 * Check if Reserve/Release is supported.
5368 		 */
5369 		if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5370 			rval = ENOTTY;
5371 			break;
5372 		}
5373 		/*
5374 		 * allow only super user to run this.
5375 		 */
5376 		if (drv_priv(cred_p) != 0) {
5377 			rval = EPERM;
5378 			break;
5379 		}
5380 		/*
5381 		 * Throw away reserve,
5382 		 * not using test-unit-ready
5383 		 * since reserve can succeed without tape being
5384 		 * present in the drive.
5385 		 */
5386 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5387 
5388 		rval = st_take_ownership(un, st_uscsi_cmd);
5389 
5390 		break;
5391 	}
5392 
5393 	case USCSICMD:
5394 	{
5395 		cred_t	*cr;
5396 
5397 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5398 		    "st_ioctl: USCSICMD\n");
5399 
5400 		cr = ddi_get_cred();
5401 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5402 			rval = EPERM;
5403 		} else {
5404 			rval = st_uscsi_cmd(un, (struct uscsi_cmd *)arg, flag);
5405 		}
5406 		break;
5407 	}
5408 	case MTIOCTOP:
5409 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5410 		    "st_ioctl: MTIOCTOP\n");
5411 		rval = st_mtioctop(un, arg, flag);
5412 		break;
5413 
5414 	case MTIOCLTOP:
5415 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5416 		    "st_ioctl: MTIOLCTOP\n");
5417 		rval = st_mtiocltop(un, arg, flag);
5418 		break;
5419 
5420 	case MTIOCREADIGNOREILI:
5421 		{
5422 			int set_ili;
5423 
5424 			if (ddi_copyin((void *)arg, &set_ili,
5425 			    sizeof (set_ili), flag)) {
5426 				rval = EFAULT;
5427 				break;
5428 			}
5429 
5430 			if (un->un_bsize) {
5431 				rval = ENOTTY;
5432 				break;
5433 			}
5434 
5435 			switch (set_ili) {
5436 			case 0:
5437 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5438 				break;
5439 
5440 			case 1:
5441 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5442 				break;
5443 
5444 			default:
5445 				rval = EINVAL;
5446 				break;
5447 			}
5448 			break;
5449 		}
5450 
5451 	case MTIOCREADIGNOREEOFS:
5452 		{
5453 			int ignore_eof;
5454 
5455 			if (ddi_copyin((void *)arg, &ignore_eof,
5456 			    sizeof (ignore_eof), flag)) {
5457 				rval = EFAULT;
5458 				break;
5459 			}
5460 
5461 			if (!(un->un_dp->options & ST_REEL)) {
5462 				rval = ENOTTY;
5463 				break;
5464 			}
5465 
5466 			switch (ignore_eof) {
5467 			case 0:
5468 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5469 				break;
5470 
5471 			case 1:
5472 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5473 				break;
5474 
5475 			default:
5476 				rval = EINVAL;
5477 				break;
5478 			}
5479 			break;
5480 		}
5481 
5482 	case MTIOCSHORTFMK:
5483 	{
5484 		int short_fmk;
5485 
5486 		if (ddi_copyin((void *)arg, &short_fmk,
5487 		    sizeof (short_fmk), flag)) {
5488 			rval = EFAULT;
5489 			break;
5490 		}
5491 
5492 		switch (un->un_dp->type) {
5493 		case ST_TYPE_EXB8500:
5494 		case ST_TYPE_EXABYTE:
5495 			if (!short_fmk) {
5496 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5497 			} else if (short_fmk == 1) {
5498 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5499 			} else {
5500 				rval = EINVAL;
5501 			}
5502 			break;
5503 
5504 		default:
5505 			rval = ENOTTY;
5506 			break;
5507 		}
5508 		break;
5509 	}
5510 
5511 	case MTIOCGETPOS:
5512 		rval = st_update_block_pos(un, st_cmd, 0);
5513 		if (rval == 0) {
5514 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5515 			    sizeof (tapepos_t), flag)) {
5516 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5517 				    "MTIOCGETPOS copy out failed\n");
5518 				rval = EFAULT;
5519 			}
5520 		}
5521 		break;
5522 
5523 	case MTIOCRESTPOS:
5524 	{
5525 		tapepos_t dest;
5526 
5527 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5528 		    flag) != 0) {
5529 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5530 			    "MTIOCRESTPOS copy in failed\n");
5531 			rval = EFAULT;
5532 			break;
5533 		}
5534 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &dest);
5535 		if (rval != 0) {
5536 			rval = EIO;
5537 		}
5538 		break;
5539 	}
5540 	default:
5541 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5542 		    "st_ioctl: unknown ioctl\n");
5543 		rval = ENOTTY;
5544 	}
5545 
5546 exit:
5547 	if (!(un->un_persistence && un->un_persist_errors)) {
5548 		un->un_errno = rval;
5549 	}
5550 
5551 	mutex_exit(ST_MUTEX);
5552 
5553 	return (rval);
5554 }
5555 
5556 
5557 /*
5558  * do some MTIOCTOP tape operations
5559  */
5560 static int
5561 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5562 {
5563 #ifdef _MULTI_DATAMODEL
5564 	/*
5565 	 * For use when a 32 bit app makes a call into a
5566 	 * 64 bit ioctl
5567 	 */
5568 	struct mtop32	mtop_32_for_64;
5569 #endif /* _MULTI_DATAMODEL */
5570 	struct mtop passed;
5571 	struct mtlop local;
5572 	int rval = 0;
5573 
5574 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5575 
5576 	ASSERT(mutex_owned(ST_MUTEX));
5577 
5578 #ifdef _MULTI_DATAMODEL
5579 	switch (ddi_model_convert_from(flag & FMODELS)) {
5580 	case DDI_MODEL_ILP32:
5581 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5582 		    sizeof (struct mtop32), flag)) {
5583 			return (EFAULT);
5584 		}
5585 		local.mt_op = mtop_32_for_64.mt_op;
5586 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5587 		break;
5588 
5589 	case DDI_MODEL_NONE:
5590 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5591 			return (EFAULT);
5592 		}
5593 		local.mt_op = passed.mt_op;
5594 		/* prevent sign extention */
5595 		local.mt_count = (UINT32_MAX & passed.mt_count);
5596 		break;
5597 	}
5598 
5599 #else /* ! _MULTI_DATAMODEL */
5600 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5601 		return (EFAULT);
5602 	}
5603 	local.mt_op = passed.mt_op;
5604 	/* prevent sign extention */
5605 	local.mt_count = (UINT32_MAX & passed.mt_count);
5606 #endif /* _MULTI_DATAMODEL */
5607 
5608 	rval = st_do_mtioctop(un, &local);
5609 
5610 #ifdef _MULTI_DATAMODEL
5611 	switch (ddi_model_convert_from(flag & FMODELS)) {
5612 	case DDI_MODEL_ILP32:
5613 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5614 			rval = ERANGE;
5615 			break;
5616 		}
5617 		/*
5618 		 * Convert 64 bit back to 32 bit before doing
5619 		 * copyout. This is what the ILP32 app expects.
5620 		 */
5621 		mtop_32_for_64.mt_op = local.mt_op;
5622 		mtop_32_for_64.mt_count = local.mt_count;
5623 
5624 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5625 		    sizeof (struct mtop32), flag)) {
5626 			rval = EFAULT;
5627 		}
5628 		break;
5629 
5630 	case DDI_MODEL_NONE:
5631 		passed.mt_count = local.mt_count;
5632 		passed.mt_op = local.mt_op;
5633 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5634 			rval = EFAULT;
5635 		}
5636 		break;
5637 	}
5638 #else /* ! _MULTI_DATAMODE */
5639 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5640 		rval = ERANGE;
5641 	} else {
5642 		passed.mt_op = local.mt_op;
5643 		passed.mt_count = local.mt_count;
5644 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5645 			rval = EFAULT;
5646 		}
5647 	}
5648 #endif /* _MULTI_DATAMODE */
5649 
5650 
5651 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5652 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5653 	    un->un_pos.blkno, un->un_pos.eof);
5654 
5655 	if (un->un_pos.pmode == invalid) {
5656 		un->un_density_known = 0;
5657 	}
5658 
5659 	ASSERT(mutex_owned(ST_MUTEX));
5660 	return (rval);
5661 }
5662 
5663 static int
5664 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5665 {
5666 	struct mtlop local;
5667 	int rval;
5668 
5669 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5670 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5671 		return (EFAULT);
5672 	}
5673 
5674 	rval = st_do_mtioctop(un, &local);
5675 
5676 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5677 		rval = EFAULT;
5678 	}
5679 	return (rval);
5680 }
5681 
5682 
5683 static int
5684 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5685 {
5686 	dev_t dev = un->un_dev;
5687 	int savefile;
5688 	int rval = 0;
5689 
5690 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5691 
5692 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5693 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5694 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5695 	    "fileno=%x, blkno=%x, eof=%x\n",
5696 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5697 
5698 	un->un_status = 0;
5699 
5700 	/*
5701 	 * if we are going to mess with a tape, we have to make sure we have
5702 	 * one and are not offline (i.e. no tape is initialized).  We let
5703 	 * commands pass here that don't actually touch the tape, except for
5704 	 * loading and initialization (rewinding).
5705 	 */
5706 	if (un->un_state == ST_STATE_OFFLINE) {
5707 		switch (mtop->mt_op) {
5708 		case MTLOAD:
5709 		case MTNOP:
5710 			/*
5711 			 * We don't want strategy calling st_tape_init here,
5712 			 * so, change state
5713 			 */
5714 			un->un_state = ST_STATE_INITIALIZING;
5715 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5716 			    "st_do_mtioctop : OFFLINE state = %d\n",
5717 			    un->un_state);
5718 			break;
5719 		default:
5720 			/*
5721 			 * reinitialize by normal means
5722 			 */
5723 			rval = st_tape_init(un);
5724 			if (rval) {
5725 				un->un_state = ST_STATE_INITIALIZING;
5726 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5727 				    "st_do_mtioctop : OFFLINE init failure ");
5728 				un->un_state = ST_STATE_OFFLINE;
5729 				un->un_pos.pmode = invalid;
5730 				if (rval != EACCES) {
5731 					rval = EIO;
5732 				}
5733 				return (rval);
5734 			}
5735 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5736 			break;
5737 		}
5738 	}
5739 
5740 	/*
5741 	 * If the file position is invalid, allow only those
5742 	 * commands that properly position the tape and fail
5743 	 * the rest with EIO
5744 	 */
5745 	if (un->un_pos.pmode == invalid) {
5746 		switch (mtop->mt_op) {
5747 		case MTWEOF:
5748 		case MTRETEN:
5749 		case MTERASE:
5750 		case MTEOM:
5751 		case MTFSF:
5752 		case MTFSR:
5753 		case MTBSF:
5754 		case MTNBSF:
5755 		case MTBSR:
5756 		case MTSRSZ:
5757 		case MTGRSZ:
5758 		case MTSEEK:
5759 		case MTBSSF:
5760 		case MTFSSF:
5761 			return (EIO);
5762 			/* NOTREACHED */
5763 		case MTREW:
5764 		case MTLOAD:
5765 		case MTOFFL:
5766 		case MTNOP:
5767 		case MTTELL:
5768 		case MTLOCK:
5769 		case MTUNLOCK:
5770 			break;
5771 
5772 		default:
5773 			return (ENOTTY);
5774 			/* NOTREACHED */
5775 		}
5776 	}
5777 
5778 	switch (mtop->mt_op) {
5779 	case MTERASE:
5780 		/*
5781 		 * MTERASE rewinds the tape, erase it completely, and returns
5782 		 * to the beginning of the tape
5783 		 */
5784 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5785 			un->un_status = KEY_WRITE_PROTECT;
5786 			un->un_err_resid = mtop->mt_count;
5787 			COPY_POS(&un->un_err_pos, &un->un_pos);
5788 			return (EACCES);
5789 		}
5790 		if (un->un_dp->options & ST_REEL) {
5791 			un->un_fmneeded = 2;
5792 		} else {
5793 			un->un_fmneeded = 1;
5794 		}
5795 		mtop->mt_count = mtop->mt_count ? 1 : 0;
5796 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5797 		    st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
5798 		    st_cmd(un, SCMD_ERASE, mtop->mt_count, SYNC_CMD)) {
5799 			un->un_pos.pmode = invalid;
5800 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5801 			    "st_do_mtioctop : EIO space or erase or "
5802 			    "check den)\n");
5803 			rval = EIO;
5804 		} else {
5805 			/* QIC and helical scan rewind after erase */
5806 			if (un->un_dp->options & ST_REEL) {
5807 				(void) st_cmd(un, SCMD_REWIND, 0, ASYNC_CMD);
5808 			}
5809 		}
5810 		break;
5811 
5812 	case MTWEOF:
5813 		/*
5814 		 * write an end-of-file record
5815 		 */
5816 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5817 			un->un_status = KEY_WRITE_PROTECT;
5818 			un->un_err_resid = mtop->mt_count;
5819 			COPY_POS(&un->un_err_pos, &un->un_pos);
5820 			return (EACCES);
5821 		}
5822 
5823 		/*
5824 		 * zero count means just flush buffers
5825 		 * negative count is not permitted
5826 		 */
5827 		if (mtop->mt_count < 0) {
5828 			return (EINVAL);
5829 		}
5830 
5831 		/* Not on worm */
5832 		if (un->un_read_only == RDWR) {
5833 			un->un_test_append = 1;
5834 		}
5835 
5836 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5837 			if (st_determine_density(un, B_WRITE)) {
5838 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5839 				    "st_do_mtioctop : EIO : MTWEOF can't "
5840 				    "determine density");
5841 				return (EIO);
5842 			}
5843 		}
5844 
5845 		rval = st_write_fm(dev, (int)mtop->mt_count);
5846 		if ((rval != 0) && (rval != EACCES)) {
5847 			/*
5848 			 * Failure due to something other than illegal
5849 			 * request results in loss of state (st_intr).
5850 			 */
5851 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5852 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5853 			    "file mark");
5854 			rval = EIO;
5855 		}
5856 		break;
5857 
5858 	case MTRETEN:
5859 		/*
5860 		 * retension the tape
5861 		 */
5862 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5863 		    st_cmd(un, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5864 			un->un_pos.pmode = invalid;
5865 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5866 			    "st_do_mtioctop : EIO : MTRETEN ");
5867 			rval = EIO;
5868 		}
5869 		break;
5870 
5871 	case MTREW:
5872 		/*
5873 		 * rewind  the tape
5874 		 */
5875 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5876 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5877 			    "st_do_mtioctop : EIO:MTREW check "
5878 			    "density/wfm failed");
5879 			return (EIO);
5880 		}
5881 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
5882 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5883 			    "st_do_mtioctop : EIO : MTREW ");
5884 			rval = EIO;
5885 		}
5886 		break;
5887 
5888 	case MTOFFL:
5889 		/*
5890 		 * rewinds, and, if appropriate, takes the device offline by
5891 		 * unloading the tape
5892 		 */
5893 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5894 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5895 			    "st_do_mtioctop :EIO:MTOFFL check "
5896 			    "density/wfm failed");
5897 			return (EIO);
5898 		}
5899 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
5900 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5901 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5902 			    "st_do_mtioctop : EIO : MTOFFL");
5903 			return (EIO);
5904 		}
5905 		un->un_pos.eof = ST_NO_EOF;
5906 		un->un_laststate = un->un_state;
5907 		un->un_state = ST_STATE_OFFLINE;
5908 		un->un_mediastate = MTIO_EJECTED;
5909 		break;
5910 
5911 	case MTLOAD:
5912 		/*
5913 		 * This is to load a tape into the drive
5914 		 * Note that if the tape is not loaded, the device will have
5915 		 * to be opened via O_NDELAY or O_NONBLOCK.
5916 		 */
5917 		/*
5918 		 * Let's try and clean things up, if we are not
5919 		 * initializing, and then send in the load command, no
5920 		 * matter what.
5921 		 *
5922 		 * load after a media change by the user.
5923 		 */
5924 
5925 		if (un->un_state > ST_STATE_INITIALIZING) {
5926 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5927 		}
5928 		rval = st_cmd(un, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5929 		/* Load command to a drive that doesn't support load */
5930 		if ((rval == EIO) &&
5931 		    ((un->un_status == KEY_NOT_READY) &&
5932 			/* Medium not present */
5933 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5934 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5935 		    (un->un_dp->type == MT_ISSTK9840) &&
5936 			/* CSL not present */
5937 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5938 			rval = ENOTTY;
5939 			break;
5940 		} else if (rval != EACCES && rval != 0) {
5941 			rval = EIO;
5942 		}
5943 		if (rval) {
5944 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5945 			    "st_do_mtioctop : %s : MTLOAD\n",
5946 			    rval == EACCES ? "EACCES" : "EIO");
5947 			/*
5948 			 * If load tape fails, who knows what happened...
5949 			 */
5950 			un->un_pos.pmode = invalid;
5951 			break;
5952 		}
5953 
5954 		/*
5955 		 * reset all counters appropriately using rewind, as if LOAD
5956 		 * succeeds, we are at BOT
5957 		 */
5958 		un->un_state = ST_STATE_INITIALIZING;
5959 
5960 		rval = st_tape_init(un);
5961 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5962 			rval = 0;
5963 			break;
5964 		}
5965 
5966 		if (rval != 0) {
5967 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5968 			    "st_do_mtioctop : EIO : MTLOAD calls "
5969 			    "st_tape_init\n");
5970 			rval = EIO;
5971 			un->un_state = ST_STATE_OFFLINE;
5972 		}
5973 
5974 		break;
5975 
5976 	case MTNOP:
5977 		un->un_status = 0;		/* Reset status */
5978 		un->un_err_resid = 0;
5979 		mtop->mt_count = MTUNIT(dev);
5980 		break;
5981 
5982 	case MTEOM:
5983 		/*
5984 		 * positions the tape at a location just after the last file
5985 		 * written on the tape. For cartridge and 8 mm, this after
5986 		 * the last file mark; for reel, this is inbetween the two
5987 		 * last 2 file marks
5988 		 */
5989 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5990 		    (un->un_lastop == ST_OP_WRITE) ||
5991 		    (un->un_lastop == ST_OP_WEOF)) {
5992 			/*
5993 			 * If the command wants to move to logical end
5994 			 * of media, and we're already there, we're done.
5995 			 * If we were at logical eot, we reset the state
5996 			 * to be *not* at logical eot.
5997 			 *
5998 			 * If we're at physical or logical eot, we prohibit
5999 			 * forward space operations (unconditionally).
6000 			 *
6001 			 * Also if the last operation was a write of any
6002 			 * kind the tape is at EOD.
6003 			 */
6004 			return (0);
6005 		}
6006 		/*
6007 		 * physical tape position may not be what we've been
6008 		 * telling the user; adjust the request accordingly
6009 		 */
6010 		if (IN_EOF(un->un_pos)) {
6011 			un->un_pos.fileno++;
6012 			un->un_pos.blkno = 0;
6013 		}
6014 
6015 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
6016 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6017 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
6018 			    " failed");
6019 			return (EIO);
6020 		}
6021 
6022 		/*
6023 		 * st_find_eod() returns the last fileno we knew about;
6024 		 */
6025 		savefile = st_find_eod(un);
6026 
6027 		if ((un->un_status != KEY_BLANK_CHECK) &&
6028 		    (un->un_status != SUN_KEY_EOT)) {
6029 			un->un_pos.pmode = invalid;
6030 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6031 			    "st_do_mtioctop : EIO : MTEOM status check failed");
6032 			rval = EIO;
6033 		} else {
6034 			/*
6035 			 * For 1/2" reel tapes assume logical EOT marked
6036 			 * by two file marks or we don't care that we may
6037 			 * be extending the last file on the tape.
6038 			 */
6039 			if (un->un_dp->options & ST_REEL) {
6040 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
6041 					un->un_pos.pmode = invalid;
6042 					ST_DEBUG2(ST_DEVINFO, st_label,
6043 					    SCSI_DEBUG,
6044 					    "st_do_mtioctop : EIO : MTEOM space"
6045 					    " cmd failed");
6046 					rval = EIO;
6047 					break;
6048 				}
6049 				/*
6050 				 * Fix up the block number.
6051 				 */
6052 				un->un_pos.blkno = 0;
6053 				un->un_err_pos.blkno = 0;
6054 			}
6055 			un->un_err_resid = 0;
6056 			un->un_pos.fileno = savefile;
6057 			un->un_pos.eof = ST_EOT;
6058 		}
6059 		un->un_status = 0;
6060 		break;
6061 
6062 	case MTFSF:
6063 		MAX_SPACE_CNT(mtop->mt_count);
6064 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
6065 		break;
6066 
6067 	case MTFSR:
6068 		MAX_SPACE_CNT(mtop->mt_count);
6069 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
6070 		break;
6071 
6072 	case MTBSF:
6073 		MAX_SPACE_CNT(mtop->mt_count);
6074 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
6075 		break;
6076 
6077 	case MTNBSF:
6078 		MAX_SPACE_CNT(mtop->mt_count);
6079 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
6080 		break;
6081 
6082 	case MTBSR:
6083 		MAX_SPACE_CNT(mtop->mt_count);
6084 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
6085 		break;
6086 
6087 	case MTBSSF:
6088 		MAX_SPACE_CNT(mtop->mt_count);
6089 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
6090 		break;
6091 
6092 	case MTFSSF:
6093 		MAX_SPACE_CNT(mtop->mt_count);
6094 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
6095 		break;
6096 
6097 	case MTSRSZ:
6098 
6099 		/*
6100 		 * Set record-size to that sent by user
6101 		 * Check to see if there is reason that the requested
6102 		 * block size should not be set.
6103 		 */
6104 
6105 		/* If requesting variable block size is it ok? */
6106 		if ((mtop->mt_count == 0) &&
6107 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
6108 			return (ENOTTY);
6109 		}
6110 
6111 		/*
6112 		 * If requested block size is not variable "0",
6113 		 * is it less then minimum.
6114 		 */
6115 		if ((mtop->mt_count != 0) &&
6116 		    (mtop->mt_count < un->un_minbsize)) {
6117 			return (EINVAL);
6118 		}
6119 
6120 		/* Is the requested block size more then maximum */
6121 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
6122 		    (un->un_maxbsize != 0)) {
6123 			return (EINVAL);
6124 		}
6125 
6126 		/* Is requested block size a modulus the device likes */
6127 		if ((mtop->mt_count % un->un_data_mod) != 0) {
6128 			return (EINVAL);
6129 		}
6130 
6131 		if (st_change_block_size(un, (uint32_t)mtop->mt_count) != 0) {
6132 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6133 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
6134 			return (EIO);
6135 		}
6136 
6137 		return (0);
6138 
6139 	case MTGRSZ:
6140 		/*
6141 		 * Get record-size to the user
6142 		 */
6143 		mtop->mt_count = un->un_bsize;
6144 		rval = 0;
6145 		break;
6146 
6147 	case MTTELL:
6148 		rval = st_update_block_pos(un, st_cmd, 0);
6149 		mtop->mt_count = un->un_pos.lgclblkno;
6150 		break;
6151 
6152 	case MTSEEK:
6153 		rval = st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
6154 		    (uint64_t)mtop->mt_count, un->un_pos.partition);
6155 		/*
6156 		 * This bit of magic make mt print the actual position if
6157 		 * the resulting position was not what was asked for.
6158 		 */
6159 		if (rval == ESPIPE) {
6160 			rval = EIO;
6161 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
6162 				mtop->mt_op = MTTELL;
6163 				mtop->mt_count = un->un_pos.lgclblkno;
6164 			}
6165 		}
6166 		break;
6167 
6168 	case MTLOCK:
6169 		if (st_cmd(un, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
6170 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6171 			    "st_do_mtioctop : EIO : MTLOCK");
6172 			rval = EIO;
6173 		}
6174 		break;
6175 
6176 	case MTUNLOCK:
6177 		if (st_cmd(un, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
6178 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6179 			    "st_do_mtioctop : EIO : MTUNLOCK");
6180 			rval = EIO;
6181 		}
6182 		break;
6183 
6184 	default:
6185 		rval = ENOTTY;
6186 	}
6187 
6188 	return (rval);
6189 }
6190 
6191 
6192 /*
6193  * Run a command for uscsi ioctl.
6194  */
6195 static int
6196 st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
6197 {
6198 	struct uscsi_cmd	*uscmd;
6199 	struct buf	*bp;
6200 	enum uio_seg	uioseg;
6201 	int	offline_state = 0;
6202 	int	err = 0;
6203 	dev_t dev = un->un_dev;
6204 
6205 	ST_FUNC(ST_DEVINFO, st_uscsi_cmd);
6206 
6207 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6208 	    "st_uscsi_cmd(dev = 0x%lx)\n", un->un_dev);
6209 
6210 	ASSERT(mutex_owned(ST_MUTEX));
6211 
6212 	/*
6213 	 * We really don't know what commands are coming in here and
6214 	 * we don't want to limit the commands coming in.
6215 	 *
6216 	 * If st_tape_init() gets called from st_strategy(), then we
6217 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
6218 	 * which it never will, as we set it below.  To prevent
6219 	 * st_tape_init() from getting called, we have to set state to other
6220 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
6221 	 * achieves this purpose already.
6222 	 *
6223 	 * We use offline_state to preserve the OFFLINE state, if it exists,
6224 	 * so other entry points to the driver might have the chance to call
6225 	 * st_tape_init().
6226 	 */
6227 	if (un->un_state == ST_STATE_OFFLINE) {
6228 		un->un_laststate = ST_STATE_OFFLINE;
6229 		un->un_state = ST_STATE_INITIALIZING;
6230 		offline_state = 1;
6231 	}
6232 
6233 	mutex_exit(ST_MUTEX);
6234 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag, ROUTE, &uscmd);
6235 	mutex_enter(ST_MUTEX);
6236 	if (err != 0) {
6237 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6238 		    "st_uscsi_cmd: scsi_uscsi_alloc_and_copyin failed\n");
6239 		goto exit;
6240 	}
6241 
6242 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
6243 
6244 	/* check to see if this command requires the drive to be reserved */
6245 	if (uscmd->uscsi_cdb != NULL) {
6246 		err = st_check_cdb_for_need_to_reserve(un,
6247 		    (uchar_t *)uscmd->uscsi_cdb);
6248 		if (err) {
6249 			goto exit_free;
6250 		}
6251 		/*
6252 		 * If this is a space command we need to save the starting
6253 		 * point so we can retry from there if the command fails.
6254 		 */
6255 		if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6256 		    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) {
6257 			(void) st_update_block_pos(un, st_cmd, 0);
6258 		}
6259 	}
6260 
6261 	/*
6262 	 * Forground should not be doing anything while recovery is active.
6263 	 */
6264 	ASSERT(un->un_recov_buf_busy == 0);
6265 
6266 	/*
6267 	 * Get buffer resources...
6268 	 */
6269 	while (un->un_sbuf_busy)
6270 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6271 	un->un_sbuf_busy = 1;
6272 
6273 #ifdef STDEBUG
6274 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0x7) > 6) {
6275 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
6276 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6277 		    "uscsi cdb", uscmd->uscsi_cdb);
6278 		if (uscmd->uscsi_buflen) {
6279 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6280 			    "uscsi %s of %ld bytes %s %s space\n",
6281 			    (rw == B_READ) ? rd_str : wr_str,
6282 			    uscmd->uscsi_buflen,
6283 			    (rw == B_READ) ? "to" : "from",
6284 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
6285 		}
6286 	}
6287 #endif /* STDEBUG */
6288 
6289 	/*
6290 	 * Although st_uscsi_cmd() never makes use of these
6291 	 * now, we are just being safe and consistent.
6292 	 */
6293 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
6294 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
6295 
6296 	un->un_srqbufp = uscmd->uscsi_rqbuf;
6297 	bp = un->un_sbufp;
6298 	bzero(bp, sizeof (buf_t));
6299 	if (uscmd->uscsi_cdb != NULL) {
6300 		bp->b_forw = (struct buf *)(uintptr_t)uscmd->uscsi_cdb[0];
6301 	}
6302 	bp->b_back = (struct buf *)uscmd;
6303 
6304 	mutex_exit(ST_MUTEX);
6305 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, st_strategy, bp, NULL);
6306 	mutex_enter(ST_MUTEX);
6307 
6308 	/*
6309 	 * If scsi reset successful, don't write any filemarks.
6310 	 */
6311 	if ((err == 0) && (uscmd->uscsi_flags &
6312 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
6313 		un->un_fmneeded = 0;
6314 	}
6315 
6316 exit_free:
6317 	/*
6318 	 * Free resources
6319 	 */
6320 	un->un_sbuf_busy = 0;
6321 	un->un_srqbufp = NULL;
6322 
6323 	/*
6324 	 * If was a space command need to update logical block position.
6325 	 * If the command failed such that positioning is invalid, Don't
6326 	 * update the position as the user must do this to validate the
6327 	 * position for data protection.
6328 	 */
6329 	if ((uscmd->uscsi_cdb != NULL) &&
6330 	    ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6331 	    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) &&
6332 	    (un->un_pos.pmode != invalid)) {
6333 		un->un_running.pmode = invalid;
6334 		(void) st_update_block_pos(un, st_cmd, 1);
6335 		/*
6336 		 * Set running position to invalid so it updates on the
6337 		 * next command.
6338 		 */
6339 		un->un_running.pmode = invalid;
6340 	}
6341 	cv_signal(&un->un_sbuf_cv);
6342 	mutex_exit(ST_MUTEX);
6343 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
6344 	mutex_enter(ST_MUTEX);
6345 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6346 	    "st_uscsi_cmd returns 0x%x\n", err);
6347 
6348 exit:
6349 	/* don't lose offline state */
6350 	if (offline_state) {
6351 		un->un_state = ST_STATE_OFFLINE;
6352 	}
6353 
6354 	ASSERT(mutex_owned(ST_MUTEX));
6355 	return (err);
6356 }
6357 
6358 static int
6359 st_write_fm(dev_t dev, int wfm)
6360 {
6361 	int i;
6362 	int rval;
6363 
6364 	GET_SOFT_STATE(dev);
6365 
6366 	ST_FUNC(ST_DEVINFO, st_write_fm);
6367 
6368 	ASSERT(mutex_owned(ST_MUTEX));
6369 
6370 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6371 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6372 
6373 	/*
6374 	 * write one filemark at the time after EOT
6375 	 */
6376 	if (un->un_pos.eof >= ST_EOT) {
6377 		for (i = 0; i < wfm; i++) {
6378 			rval = st_cmd(un, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6379 			if (rval == EACCES) {
6380 				return (rval);
6381 			}
6382 			if (rval != 0) {
6383 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6384 				    "st_write_fm : EIO : write EOT file mark");
6385 				return (EIO);
6386 			}
6387 		}
6388 	} else {
6389 		rval = st_cmd(un, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6390 		if (rval == EACCES) {
6391 			return (rval);
6392 		}
6393 		if (rval) {
6394 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6395 			    "st_write_fm : EIO : write file mark");
6396 			return (EIO);
6397 		}
6398 	}
6399 
6400 	ASSERT(mutex_owned(ST_MUTEX));
6401 	return (0);
6402 }
6403 
6404 #ifdef STDEBUG
6405 static void
6406 st_start_dump(struct scsi_tape *un, struct buf *bp)
6407 {
6408 	struct scsi_pkt *pkt = BP_PKT(bp);
6409 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6410 
6411 	ST_FUNC(ST_DEVINFO, st_start_dump);
6412 
6413 	if ((st_debug & 0x7) < 6)
6414 		return;
6415 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6416 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6417 	    (void *)bp->b_forw, bp->b_bcount,
6418 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6419 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6420 	    "st_start: cdb",  (caddr_t)cdbp);
6421 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6422 	    "st_start: fileno=%d, blk=%d\n",
6423 	    un->un_pos.fileno, un->un_pos.blkno);
6424 }
6425 #endif
6426 
6427 
6428 /*
6429  * Command start && done functions
6430  */
6431 
6432 /*
6433  * st_start()
6434  *
6435  * Called from:
6436  *  st_strategy() to start a command.
6437  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6438  *  st_attach() when resuming from power down state.
6439  *  st_start_restart() to retry transport when device was previously busy.
6440  *  st_done_and_mutex_exit() to start the next command when previous is done.
6441  *
6442  * On entry:
6443  *  scsi_pkt may or may not be allocated.
6444  *
6445  */
6446 static void
6447 st_start(struct scsi_tape *un)
6448 {
6449 	struct buf *bp;
6450 	int status;
6451 	int queued;
6452 
6453 	ST_FUNC(ST_DEVINFO, st_start);
6454 	ASSERT(mutex_owned(ST_MUTEX));
6455 
6456 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6457 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6458 
6459 	if (un->un_recov_buf_busy) {
6460 		/* recovery commands can happen anytime */
6461 		bp = un->un_recov_buf;
6462 		queued = 0;
6463 	} else if (un->un_sbuf_busy) {
6464 		/* sbuf commands should only happen with an empty queue. */
6465 		ASSERT(un->un_quef == NULL);
6466 		ASSERT(un->un_runqf == NULL);
6467 		bp = un->un_sbufp;
6468 		queued = 0;
6469 	} else if (un->un_quef != NULL) {
6470 		if (un->un_persistence && un->un_persist_errors) {
6471 			return;
6472 		}
6473 		bp = un->un_quef;
6474 		queued = 1;
6475 	} else {
6476 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6477 		    "st_start() returning no buf found\n");
6478 		return;
6479 	}
6480 
6481 	ASSERT((bp->b_flags & B_DONE) == 0);
6482 
6483 	/*
6484 	 * Don't send more than un_throttle commands to the HBA
6485 	 */
6486 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6487 		/*
6488 		 * if doing recovery we know there is outstanding commands.
6489 		 */
6490 		if (bp != un->un_recov_buf) {
6491 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6492 			    "st_start returning throttle = %d or ncmds = %d\n",
6493 			    un->un_throttle, un->un_ncmds);
6494 			if (un->un_ncmds == 0) {
6495 				typedef void (*func)();
6496 				func fnc = (func)st_runout;
6497 
6498 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6499 				    "Sending delayed start to st_runout()\n");
6500 				mutex_exit(ST_MUTEX);
6501 				(void) timeout(fnc, un, drv_usectohz(1000000));
6502 				mutex_enter(ST_MUTEX);
6503 			}
6504 			return;
6505 		}
6506 	}
6507 
6508 	/*
6509 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6510 	 * build the command.
6511 	 */
6512 	if (BP_PKT(bp) == NULL) {
6513 		ASSERT((bp->b_flags & B_DONE) == 0);
6514 		st_make_cmd(un, bp, st_runout);
6515 		ASSERT((bp->b_flags & B_DONE) == 0);
6516 		status = geterror(bp);
6517 
6518 		/*
6519 		 * Some HBA's don't call bioerror() to set an error.
6520 		 * And geterror() returns zero if B_ERROR is not set.
6521 		 * So if we get zero we must check b_error.
6522 		 */
6523 		if (status == 0 && bp->b_error != 0) {
6524 			status = bp->b_error;
6525 			bioerror(bp, status);
6526 		}
6527 
6528 		/*
6529 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6530 		 * In tape ENOMEM has special meaning so we'll change it.
6531 		 */
6532 		if (status == ENOMEM) {
6533 			status = 0;
6534 			bioerror(bp, status);
6535 		}
6536 
6537 		/*
6538 		 * Did it fail and is it retryable?
6539 		 * If so return and wait for the callback through st_runout.
6540 		 * Also looks like scsi_init_pkt() will setup a callback even
6541 		 * if it isn't retryable.
6542 		 */
6543 		if (BP_PKT(bp) == NULL) {
6544 			if (status == 0) {
6545 				/*
6546 				 * If first attempt save state.
6547 				 */
6548 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6549 					un->un_laststate = un->un_state;
6550 					un->un_state = ST_STATE_RESOURCE_WAIT;
6551 				}
6552 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6553 				    "temp no resources for pkt\n");
6554 			} else if (status == EINVAL) {
6555 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6556 				    "scsi_init_pkt rejected pkt as too big\n");
6557 				if (un->un_persistence) {
6558 					st_set_pe_flag(un);
6559 				}
6560 			} else {
6561 				/*
6562 				 * Unlikely that it would be retryable then not.
6563 				 */
6564 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6565 					un->un_state = un->un_laststate;
6566 				}
6567 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6568 				    "perm no resources for pkt errno = 0x%x\n",
6569 				    status);
6570 			}
6571 			return;
6572 		}
6573 		/*
6574 		 * Worked this time set the state back.
6575 		 */
6576 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6577 			un->un_state = un->un_laststate;
6578 		}
6579 	}
6580 
6581 	if (queued) {
6582 		/*
6583 		 * move from waitq to runq
6584 		 */
6585 		(void) st_remove_from_queue(&un->un_quef, &un->un_quel, bp);
6586 		st_add_to_queue(&un->un_runqf, &un->un_runql, un->un_runql, bp);
6587 	}
6588 
6589 
6590 #ifdef STDEBUG
6591 	st_start_dump(un, bp);
6592 #endif
6593 
6594 	/* could not get here if throttle was zero */
6595 	un->un_last_throttle = un->un_throttle;
6596 	un->un_throttle = 0;	/* so nothing else will come in here */
6597 	un->un_ncmds++;
6598 
6599 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6600 
6601 	status = st_transport(un, BP_PKT(bp));
6602 
6603 	if (un->un_last_throttle) {
6604 		un->un_throttle = un->un_last_throttle;
6605 	}
6606 
6607 	if (status != TRAN_ACCEPT) {
6608 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6609 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
6610 		    "Unhappy transport packet status 0x%x\n", status);
6611 
6612 		if (status == TRAN_BUSY) {
6613 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
6614 
6615 			/*
6616 			 * If command recovery is enabled and this isn't
6617 			 * a recovery command try command recovery.
6618 			 */
6619 			if (pkti->privatelen == sizeof (recov_info) &&
6620 			    bp != un->un_recov_buf) {
6621 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
6622 				    "Command Recovery called on busy send\n");
6623 				if (st_command_recovery(un, BP_PKT(bp),
6624 				    ATTEMPT_RETRY) == JUST_RETURN) {
6625 					return;
6626 				}
6627 			} else {
6628 				mutex_exit(ST_MUTEX);
6629 				if (st_handle_start_busy(un, bp,
6630 				    ST_TRAN_BUSY_TIMEOUT, queued) == 0) {
6631 					mutex_enter(ST_MUTEX);
6632 					return;
6633 				}
6634 				/*
6635 				 * if too many retries, fail the transport
6636 				 */
6637 				mutex_enter(ST_MUTEX);
6638 			}
6639 		}
6640 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6641 		    "transport rejected %d\n", status);
6642 		bp->b_resid = bp->b_bcount;
6643 
6644 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6645 		ST_DO_ERRSTATS(un, st_transerrs);
6646 		if ((bp == un->un_recov_buf) && (status == TRAN_BUSY)) {
6647 			st_bioerror(bp, EBUSY);
6648 		} else {
6649 			st_bioerror(bp, EIO);
6650 			st_set_pe_flag(un);
6651 		}
6652 		st_done_and_mutex_exit(un, bp);
6653 		mutex_enter(ST_MUTEX);
6654 	}
6655 
6656 	ASSERT(mutex_owned(ST_MUTEX));
6657 }
6658 
6659 /*
6660  * if the transport is busy, then put this bp back on the waitq
6661  */
6662 static int
6663 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6664     clock_t timeout_interval, int queued)
6665 {
6666 
6667 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
6668 
6669 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6670 
6671 	mutex_enter(ST_MUTEX);
6672 
6673 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6674 	    "st_handle_start_busy()\n");
6675 
6676 	/*
6677 	 * Check to see if we hit the retry timeout and one last check for
6678 	 * making sure this is the last on the runq, if it is not, we have
6679 	 * to fail
6680 	 */
6681 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
6682 	    ((queued) && (un->un_runql != bp))) {
6683 		mutex_exit(ST_MUTEX);
6684 		return (-1);
6685 	}
6686 
6687 	if (queued) {
6688 		/* put the bp back on the waitq */
6689 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
6690 	}
6691 
6692 	/*
6693 	 * Decrement un_ncmds so that this
6694 	 * gets thru' st_start() again.
6695 	 */
6696 	un->un_ncmds--;
6697 
6698 	if (queued) {
6699 		/*
6700 		 * since this is an error case, we won't have to do this list
6701 		 * walking much. We've already made sure this bp was the
6702 		 * last on the runq
6703 		 */
6704 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6705 
6706 		/*
6707 		 * send a marker pkt, if appropriate
6708 		 */
6709 		st_hba_unflush(un);
6710 
6711 	}
6712 	/*
6713 	 * all queues are aligned, we are just waiting to
6714 	 * transport, don't alloc any more buf p's, when
6715 	 * st_start is reentered.
6716 	 */
6717 	(void) timeout(st_start_restart, un, timeout_interval);
6718 
6719 	mutex_exit(ST_MUTEX);
6720 	return (0);
6721 }
6722 
6723 
6724 /*
6725  * st_runout a callback that is called what a resource allocatation failed
6726  */
6727 static int
6728 st_runout(caddr_t arg)
6729 {
6730 	struct scsi_tape *un = (struct scsi_tape *)arg;
6731 	struct buf *bp;
6732 	int queued;
6733 
6734 	ASSERT(un != NULL);
6735 
6736 	ST_FUNC(ST_DEVINFO, st_runout);
6737 
6738 	mutex_enter(ST_MUTEX);
6739 
6740 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6741 
6742 	if (un->un_recov_buf_busy != 0) {
6743 		bp = un->un_recov_buf;
6744 		queued = 0;
6745 	} else if (un->un_sbuf_busy != 0) {
6746 		/* sbuf commands should only happen with an empty queue. */
6747 		ASSERT(un->un_quef == NULL);
6748 		ASSERT(un->un_runqf == NULL);
6749 		bp = un->un_sbufp;
6750 		queued = 0;
6751 	} else if (un->un_quef != NULL) {
6752 		bp = un->un_quef;
6753 		if (un->un_persistence && un->un_persist_errors) {
6754 			mutex_exit(ST_MUTEX);
6755 			bp->b_resid = bp->b_bcount;
6756 			biodone(bp);
6757 			return (1);
6758 		}
6759 		queued = 1;
6760 	} else {
6761 		ASSERT(1 == 0);
6762 		mutex_exit(ST_MUTEX);
6763 		return (1);
6764 	}
6765 
6766 	/*
6767 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6768 	 */
6769 	if ((bp != NULL) && (geterror(bp) != 0)) {
6770 
6771 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6772 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6773 		    bp->b_flags, geterror(bp));
6774 		ASSERT((bp->b_flags & B_DONE) == 0);
6775 
6776 		if (queued) {
6777 			(void) st_remove_from_queue(&un->un_quef, &un->un_quel,
6778 			    bp);
6779 		}
6780 		mutex_exit(ST_MUTEX);
6781 
6782 		ASSERT((bp->b_flags & B_DONE) == 0);
6783 
6784 		/*
6785 		 * Set resid, Error already set, then unblock calling thread.
6786 		 */
6787 		bp->b_resid = bp->b_bcount;
6788 		biodone(bp);
6789 	} else {
6790 		/*
6791 		 * Try Again
6792 		 */
6793 		st_start(un);
6794 		mutex_exit(ST_MUTEX);
6795 	}
6796 
6797 	/*
6798 	 * Comments courtesy of sd.c
6799 	 * The scsi_init_pkt routine allows for the callback function to
6800 	 * return a 0 indicating the callback should be rescheduled or a 1
6801 	 * indicating not to reschedule. This routine always returns 1
6802 	 * because the driver always provides a callback function to
6803 	 * scsi_init_pkt. This results in a callback always being scheduled
6804 	 * (via the scsi_init_pkt callback implementation) if a resource
6805 	 * failure occurs.
6806 	 */
6807 
6808 	return (1);
6809 }
6810 
6811 /*
6812  * st_done_and_mutex_exit()
6813  *	- remove bp from runq
6814  *	- start up the next request
6815  *	- if this was an asynch bp, clean up
6816  *	- exit with released mutex
6817  */
6818 static void
6819 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6820 {
6821 	int pe_flagged = 0;
6822 	struct scsi_pkt *pkt = BP_PKT(bp);
6823 	pkt_info *pktinfo = pkt->pkt_private;
6824 
6825 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6826 #if !defined(lint)
6827 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6828 #endif
6829 
6830 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6831 
6832 	ASSERT(mutex_owned(ST_MUTEX));
6833 
6834 	(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6835 
6836 	un->un_ncmds--;
6837 	cv_signal(&un->un_queue_cv);
6838 
6839 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6840 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6841 	    "0x%x\n", pkt->pkt_cdbp[0], bp->b_bcount,
6842 	    bp->b_resid, bp->b_flags);
6843 
6844 
6845 	/*
6846 	 * update kstats with transfer count info
6847 	 */
6848 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6849 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6850 		if (bp->b_flags & B_READ) {
6851 			IOSP->reads++;
6852 			IOSP->nread += n_done;
6853 		} else {
6854 			IOSP->writes++;
6855 			IOSP->nwritten += n_done;
6856 		}
6857 	}
6858 
6859 	/*
6860 	 * Start the next one before releasing resources on this one, if
6861 	 * there is something on the queue and persistent errors has not been
6862 	 * flagged
6863 	 */
6864 
6865 	if ((pe_flagged = (un->un_persistence && un->un_persist_errors)) != 0) {
6866 		un->un_last_resid = bp->b_resid;
6867 		un->un_last_count = bp->b_bcount;
6868 	}
6869 
6870 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6871 		cv_broadcast(&un->un_tape_busy_cv);
6872 	} else if (un->un_quef && un->un_throttle && !pe_flagged &&
6873 	    (bp != un->un_recov_buf)) {
6874 		st_start(un);
6875 	}
6876 
6877 	un->un_retry_ct = max(pktinfo->pkt_retry_cnt, pktinfo->str_retry_cnt);
6878 
6879 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6880 		/*
6881 		 * Since we marked this ourselves as ASYNC,
6882 		 * there isn't anybody around waiting for
6883 		 * completion any more.
6884 		 */
6885 		uchar_t *cmd = pkt->pkt_cdbp;
6886 		if (*cmd == SCMD_READ || *cmd == SCMD_WRITE) {
6887 			bp->b_un.b_addr = (caddr_t)0;
6888 		}
6889 		ST_DEBUG(ST_DEVINFO, st_label, CE_NOTE,
6890 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6891 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
6892 		    "CDB sent with B_ASYNC",  (caddr_t)cmd);
6893 		if (pkt) {
6894 			scsi_destroy_pkt(pkt);
6895 		}
6896 		un->un_sbuf_busy = 0;
6897 		cv_signal(&un->un_sbuf_cv);
6898 		mutex_exit(ST_MUTEX);
6899 		return;
6900 	}
6901 
6902 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6903 		/*
6904 		 * Copy status from scsi_pkt to uscsi_cmd
6905 		 * since st_uscsi_cmd needs it
6906 		 */
6907 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6908 	}
6909 
6910 
6911 #ifdef STDEBUG
6912 	if (((st_debug & 0x7) >= 4) &&
6913 	    (((un->un_pos.blkno % 100) == 0) ||
6914 	    (un->un_persistence && un->un_persist_errors))) {
6915 
6916 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6917 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6918 		    "un_errno = %d, un_pe = %d\n",
6919 		    un->un_ncmds, un->un_throttle, un->un_errno,
6920 		    un->un_persist_errors);
6921 	}
6922 
6923 #endif
6924 
6925 	mutex_exit(ST_MUTEX);
6926 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6927 	    "st_done_and_mutex_exit: freeing pkt\n");
6928 
6929 	if (pkt) {
6930 		scsi_destroy_pkt(pkt);
6931 	}
6932 
6933 	biodone(bp);
6934 
6935 	/*
6936 	 * now that we biodoned that command, if persistent errors have been
6937 	 * flagged, flush the waitq
6938 	 */
6939 	if (pe_flagged)
6940 		st_flush(un);
6941 }
6942 
6943 
6944 /*
6945  * Tape error, flush tape driver queue.
6946  */
6947 static void
6948 st_flush(struct scsi_tape *un)
6949 {
6950 	struct buf *bp;
6951 
6952 	ST_FUNC(ST_DEVINFO, st_flush);
6953 
6954 	mutex_enter(ST_MUTEX);
6955 
6956 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6957 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6958 	    un->un_ncmds, (void *)un->un_quef);
6959 
6960 	/*
6961 	 * if we still have commands outstanding, wait for them to come in
6962 	 * before flushing the queue, and make sure there is a queue
6963 	 */
6964 	if (un->un_ncmds || !un->un_quef)
6965 		goto exit;
6966 
6967 	/*
6968 	 * we have no more commands outstanding, so let's deal with special
6969 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6970 	 * is 0, then we know there was no error and we return a 0 read or
6971 	 * write before showing errors
6972 	 */
6973 
6974 	/* Flush the wait queue. */
6975 	while ((bp = un->un_quef) != NULL) {
6976 		un->un_quef = bp->b_actf;
6977 
6978 		bp->b_resid = bp->b_bcount;
6979 
6980 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6981 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6982 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6983 
6984 		st_set_pe_errno(un);
6985 
6986 		bioerror(bp, un->un_errno);
6987 
6988 		mutex_exit(ST_MUTEX);
6989 		/* it should have one, but check anyway */
6990 		if (BP_PKT(bp)) {
6991 			scsi_destroy_pkt(BP_PKT(bp));
6992 		}
6993 		biodone(bp);
6994 		mutex_enter(ST_MUTEX);
6995 	}
6996 
6997 	/*
6998 	 * It's not a bad practice to reset the
6999 	 * waitq tail pointer to NULL.
7000 	 */
7001 	un->un_quel = NULL;
7002 
7003 exit:
7004 	/* we mucked with the queue, so let others know about it */
7005 	cv_signal(&un->un_queue_cv);
7006 	mutex_exit(ST_MUTEX);
7007 }
7008 
7009 
7010 /*
7011  * Utility functions
7012  */
7013 static int
7014 st_determine_generic(struct scsi_tape *un)
7015 {
7016 	int bsize;
7017 	static char *cart = "0.25 inch cartridge";
7018 	char *sizestr;
7019 
7020 	ST_FUNC(ST_DEVINFO, st_determine_generic);
7021 
7022 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7023 	    "st_determine_generic(un = 0x%p)\n", (void*)un);
7024 
7025 	ASSERT(mutex_owned(ST_MUTEX));
7026 
7027 	if (st_modesense(un)) {
7028 		return (-1);
7029 	}
7030 
7031 	bsize = (un->un_mspl->high_bl << 16)	|
7032 	    (un->un_mspl->mid_bl << 8)	|
7033 	    (un->un_mspl->low_bl);
7034 
7035 	if (bsize == 0) {
7036 		un->un_dp->options |= ST_VARIABLE;
7037 		un->un_dp->bsize = 0;
7038 		un->un_bsize = 0;
7039 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
7040 		/*
7041 		 * record size of this device too big.
7042 		 * try and convert it to variable record length.
7043 		 *
7044 		 */
7045 		un->un_dp->options |= ST_VARIABLE;
7046 		if (st_change_block_size(un, 0) != 0) {
7047 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7048 			    "Fixed Record Size %d is too large\n", bsize);
7049 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7050 			    "Cannot switch to variable record size\n");
7051 			un->un_dp->options &= ~ST_VARIABLE;
7052 			return (-1);
7053 		}
7054 	} else if (st_change_block_size(un, 0) == 0) {
7055 		/*
7056 		 * If the drive was set to a non zero block size,
7057 		 * See if it can be set to a zero block size.
7058 		 * If it works, ST_VARIABLE so user can set it as they want.
7059 		 */
7060 		un->un_dp->options |= ST_VARIABLE;
7061 		un->un_dp->bsize = 0;
7062 		un->un_bsize = 0;
7063 	} else {
7064 		un->un_dp->bsize = bsize;
7065 		un->un_bsize = bsize;
7066 	}
7067 
7068 
7069 	switch (un->un_mspl->density) {
7070 	default:
7071 	case 0x0:
7072 		/*
7073 		 * default density, cannot determine any other
7074 		 * information.
7075 		 */
7076 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
7077 		un->un_dp->type = ST_TYPE_DEFAULT;
7078 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
7079 		break;
7080 	case 0x1:
7081 	case 0x2:
7082 	case 0x3:
7083 	case 0x6:
7084 		/*
7085 		 * 1/2" reel
7086 		 */
7087 		sizestr = "0.50 inch reel";
7088 		un->un_dp->type = ST_TYPE_REEL;
7089 		un->un_dp->options |= ST_REEL;
7090 		un->un_dp->densities[0] = 0x1;
7091 		un->un_dp->densities[1] = 0x2;
7092 		un->un_dp->densities[2] = 0x6;
7093 		un->un_dp->densities[3] = 0x3;
7094 		break;
7095 	case 0x4:
7096 	case 0x5:
7097 	case 0x7:
7098 	case 0x0b:
7099 
7100 		/*
7101 		 * Quarter inch.
7102 		 */
7103 		sizestr = cart;
7104 		un->un_dp->type = ST_TYPE_DEFAULT;
7105 		un->un_dp->options |= ST_QIC;
7106 
7107 		un->un_dp->densities[1] = 0x4;
7108 		un->un_dp->densities[2] = 0x5;
7109 		un->un_dp->densities[3] = 0x7;
7110 		un->un_dp->densities[0] = 0x0b;
7111 		break;
7112 
7113 	case 0x0f:
7114 	case 0x10:
7115 	case 0x11:
7116 	case 0x12:
7117 		/*
7118 		 * QIC-120, QIC-150, QIC-320, QIC-600
7119 		 */
7120 		sizestr = cart;
7121 		un->un_dp->type = ST_TYPE_DEFAULT;
7122 		un->un_dp->options |= ST_QIC;
7123 		un->un_dp->densities[0] = 0x0f;
7124 		un->un_dp->densities[1] = 0x10;
7125 		un->un_dp->densities[2] = 0x11;
7126 		un->un_dp->densities[3] = 0x12;
7127 		break;
7128 
7129 	case 0x09:
7130 	case 0x0a:
7131 	case 0x0c:
7132 	case 0x0d:
7133 		/*
7134 		 * 1/2" cartridge tapes. Include HI-TC.
7135 		 */
7136 		sizestr = cart;
7137 		sizestr[2] = '5';
7138 		sizestr[3] = '0';
7139 		un->un_dp->type = ST_TYPE_HIC;
7140 		un->un_dp->densities[0] = 0x09;
7141 		un->un_dp->densities[1] = 0x0a;
7142 		un->un_dp->densities[2] = 0x0c;
7143 		un->un_dp->densities[3] = 0x0d;
7144 		break;
7145 
7146 	case 0x13:
7147 			/* DDS-2/DDS-3 scsi spec densities */
7148 	case 0x24:
7149 	case 0x25:
7150 	case 0x26:
7151 		sizestr = "DAT Data Storage (DDS)";
7152 		un->un_dp->type = ST_TYPE_DAT;
7153 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7154 		break;
7155 
7156 	case 0x14:
7157 		/*
7158 		 * Helical Scan (Exabyte) devices
7159 		 */
7160 		sizestr = "8mm helical scan cartridge";
7161 		un->un_dp->type = ST_TYPE_EXABYTE;
7162 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7163 		break;
7164 	}
7165 
7166 	/*
7167 	 * Assume LONG ERASE, BSF and BSR
7168 	 */
7169 
7170 	un->un_dp->options |=
7171 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
7172 
7173 	/*
7174 	 * Only if mode sense data says no buffered write, set NOBUF
7175 	 */
7176 	if (un->un_mspl->bufm == 0)
7177 		un->un_dp->options |= ST_NOBUF;
7178 
7179 	/*
7180 	 * set up large read and write retry counts
7181 	 */
7182 
7183 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
7184 
7185 	/*
7186 	 * If this is a 0.50 inch reel tape, and
7187 	 * it is *not* variable mode, try and
7188 	 * set it to variable record length
7189 	 * mode.
7190 	 */
7191 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
7192 	    (un->un_dp->options & ST_VARIABLE)) {
7193 		if (st_change_block_size(un, 0) == 0) {
7194 			un->un_dp->bsize = 0;
7195 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
7196 			    un->un_mspl->low_bl = 0;
7197 		}
7198 	}
7199 
7200 	/*
7201 	 * Write to console about type of device found
7202 	 */
7203 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
7204 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
7205 	    sizestr);
7206 	if (un->un_dp->options & ST_VARIABLE) {
7207 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7208 		    "!Variable record length I/O\n");
7209 	} else {
7210 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7211 		    "!Fixed record length (%d byte blocks) I/O\n",
7212 		    un->un_dp->bsize);
7213 	}
7214 	ASSERT(mutex_owned(ST_MUTEX));
7215 	return (0);
7216 }
7217 
7218 static int
7219 st_determine_density(struct scsi_tape *un, int rw)
7220 {
7221 	int rval = 0;
7222 
7223 	ST_FUNC(ST_DEVINFO, st_determine_density);
7224 
7225 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7226 	    "st_determine_density(un = 0x%p, rw = %s)\n",
7227 	    (void*)un, (rw == B_WRITE ? wr_str: rd_str));
7228 
7229 	ASSERT(mutex_owned(ST_MUTEX));
7230 
7231 	/*
7232 	 * If we're past BOT, density is determined already.
7233 	 */
7234 	if (un->un_pos.pmode == logical) {
7235 		if (un->un_pos.lgclblkno != 0) {
7236 			goto exit;
7237 		}
7238 	} else if (un->un_pos.pmode == legacy) {
7239 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
7240 			/*
7241 			 * XXX: put in a bitch message about attempting to
7242 			 * XXX: change density past BOT.
7243 			 */
7244 			goto exit;
7245 		}
7246 	} else {
7247 		goto exit;
7248 	}
7249 	if ((un->un_pos.pmode == logical) &&
7250 	    (un->un_pos.lgclblkno != 0)) {
7251 		goto exit;
7252 	}
7253 
7254 
7255 	/*
7256 	 * If we're going to be writing, we set the density
7257 	 */
7258 	if (rw == 0 || rw == B_WRITE) {
7259 		/* un_curdens is used as an index into densities table */
7260 		un->un_curdens = MT_DENSITY(un->un_dev);
7261 		if (st_set_density(un)) {
7262 			rval = -1;
7263 		}
7264 		goto exit;
7265 	}
7266 
7267 	/*
7268 	 * If density is known already,
7269 	 * we don't have to get it again.(?)
7270 	 */
7271 	if (!un->un_density_known) {
7272 		if (st_get_density(un)) {
7273 			rval = -1;
7274 		}
7275 	}
7276 
7277 exit:
7278 	ASSERT(mutex_owned(ST_MUTEX));
7279 	return (rval);
7280 }
7281 
7282 
7283 /*
7284  * Try to determine density. We do this by attempting to read the
7285  * first record off the tape, cycling through the available density
7286  * codes as we go.
7287  */
7288 
7289 static int
7290 st_get_density(struct scsi_tape *un)
7291 {
7292 	int succes = 0, rval = -1, i;
7293 	uint_t size;
7294 	uchar_t dens, olddens;
7295 
7296 	ST_FUNC(ST_DEVINFO, st_get_density);
7297 
7298 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7299 	    "st_get_density(un = 0x%p)\n", (void*)un);
7300 
7301 	ASSERT(mutex_owned(ST_MUTEX));
7302 
7303 	/*
7304 	 * If Auto Density override is enabled The drive has
7305 	 * only one density and there is no point in attempting
7306 	 * find the correct one.
7307 	 *
7308 	 * Since most modern drives auto detect the density
7309 	 * and format of the recorded media before they come
7310 	 * ready. What this function does is a legacy behavior
7311 	 * and modern drives not only don't need it, The backup
7312 	 * utilities that do positioning via uscsi find the un-
7313 	 * expected rewinds problematic.
7314 	 *
7315 	 * The drives that need this are old reel to reel devices.
7316 	 * I took a swag and said they must be scsi-1 or older.
7317 	 * I don't beleave there will any of the newer devices
7318 	 * that need this. There will be some scsi-1 devices that
7319 	 * don't need this but I don't think they will be using the
7320 	 * BIG aftermarket backup and restore utilitys.
7321 	 */
7322 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
7323 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
7324 		un->un_density_known = 1;
7325 		rval = 0;
7326 		goto exit;
7327 	}
7328 
7329 	/*
7330 	 * This will only work on variable record length tapes
7331 	 * if and only if all variable record length tapes autodensity
7332 	 * select.
7333 	 */
7334 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
7335 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
7336 
7337 	/*
7338 	 * Start at the specified density
7339 	 */
7340 
7341 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
7342 
7343 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
7344 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
7345 		/*
7346 		 * If we've done this density before,
7347 		 * don't bother to do it again.
7348 		 */
7349 		dens = un->un_dp->densities[un->un_curdens];
7350 		if (i > 0 && dens == olddens)
7351 			continue;
7352 		olddens = dens;
7353 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7354 		    "trying density 0x%x\n", dens);
7355 		if (st_set_density(un)) {
7356 			continue;
7357 		}
7358 
7359 		/*
7360 		 * XXX - the creates lots of headaches and slowdowns - must
7361 		 * fix.
7362 		 */
7363 		succes = (st_cmd(un, SCMD_READ, (int)size, SYNC_CMD) == 0);
7364 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
7365 			break;
7366 		}
7367 		if (succes) {
7368 			st_init(un);
7369 			rval = 0;
7370 			un->un_density_known = 1;
7371 			break;
7372 		}
7373 	}
7374 	kmem_free(un->un_tmpbuf, size);
7375 	un->un_tmpbuf = 0;
7376 
7377 exit:
7378 	ASSERT(mutex_owned(ST_MUTEX));
7379 	return (rval);
7380 }
7381 
7382 static int
7383 st_set_density(struct scsi_tape *un)
7384 {
7385 	int rval = 0;
7386 
7387 	ST_FUNC(ST_DEVINFO, st_set_density);
7388 
7389 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7390 	    "st_set_density(un = 0x%p): density = 0x%x\n", (void*)un,
7391 	    un->un_dp->densities[un->un_curdens]);
7392 
7393 	ASSERT(mutex_owned(ST_MUTEX));
7394 
7395 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7396 
7397 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
7398 		/*
7399 		 * If auto density override is not set, Use mode select
7400 		 * to set density and compression.
7401 		 */
7402 		if (st_modeselect(un)) {
7403 			rval = -1;
7404 		}
7405 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
7406 		/*
7407 		 * If auto density and mode select compression are set,
7408 		 * This is a drive with one density code but compression
7409 		 * can be enabled or disabled.
7410 		 * Set compression but no need to set density.
7411 		 */
7412 		rval = st_set_compression(un);
7413 		if ((rval != 0) && (rval != EALREADY)) {
7414 			rval = -1;
7415 		} else {
7416 			rval = 0;
7417 		}
7418 	}
7419 
7420 	/* If sucessful set density and/or compression, mark density known */
7421 	if (rval == 0) {
7422 		un->un_density_known = 1;
7423 	}
7424 
7425 	ASSERT(mutex_owned(ST_MUTEX));
7426 	return (rval);
7427 }
7428 
7429 static int
7430 st_loadtape(struct scsi_tape *un)
7431 {
7432 	int rval;
7433 
7434 	ST_FUNC(ST_DEVINFO, st_loadtape);
7435 
7436 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7437 	    "st_loadtape(un = 0x%p)\n", (void*) un);
7438 
7439 	ASSERT(mutex_owned(ST_MUTEX));
7440 
7441 	rval = st_update_block_pos(un, st_cmd, 0);
7442 	if (rval == EACCES) {
7443 		return (rval);
7444 	}
7445 
7446 	/*
7447 	 * 'LOAD' the tape to BOT by rewinding
7448 	 */
7449 	rval = st_cmd(un, SCMD_REWIND, 1, SYNC_CMD);
7450 	if (rval == 0) {
7451 		st_init(un);
7452 		un->un_density_known = 0;
7453 	}
7454 
7455 	ASSERT(mutex_owned(ST_MUTEX));
7456 	return (rval);
7457 }
7458 
7459 
7460 /*
7461  * Note: QIC devices aren't so smart.  If you try to append
7462  * after EOM, the write can fail because the device doesn't know
7463  * it's at EOM.	 In that case, issue a read.  The read should fail
7464  * because there's no data, but the device knows it's at EOM,
7465  * so a subsequent write should succeed.  To further confuse matters,
7466  * the target returns the same error if the tape is positioned
7467  * such that a write would overwrite existing data.  That's why
7468  * we have to do the append test.  A read in the middle of
7469  * recorded data would succeed, thus indicating we're attempting
7470  * something illegal.
7471  */
7472 
7473 
7474 static void
7475 st_test_append(struct buf *bp)
7476 {
7477 	dev_t dev = bp->b_edev;
7478 	struct scsi_tape *un;
7479 	uchar_t status;
7480 	unsigned bcount;
7481 
7482 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7483 
7484 	ST_FUNC(ST_DEVINFO, st_test_append);
7485 
7486 	ASSERT(mutex_owned(ST_MUTEX));
7487 
7488 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7489 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7490 
7491 	un->un_laststate = un->un_state;
7492 	un->un_state = ST_STATE_APPEND_TESTING;
7493 	un->un_test_append = 0;
7494 
7495 	/*
7496 	 * first, map in the buffer, because we're doing a double write --
7497 	 * first into the kernel, then onto the tape.
7498 	 */
7499 	bp_mapin(bp);
7500 
7501 	/*
7502 	 * get a copy of the data....
7503 	 */
7504 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7505 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7506 
7507 	/*
7508 	 * attempt the write..
7509 	 */
7510 
7511 	if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7512 success:
7513 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7514 		    "append write succeeded\n");
7515 		bp->b_resid = un->un_sbufp->b_resid;
7516 		mutex_exit(ST_MUTEX);
7517 		bcount = (unsigned)bp->b_bcount;
7518 		biodone(bp);
7519 		mutex_enter(ST_MUTEX);
7520 		un->un_laststate = un->un_state;
7521 		un->un_state = ST_STATE_OPEN;
7522 		kmem_free(un->un_tmpbuf, bcount);
7523 		un->un_tmpbuf = NULL;
7524 		return;
7525 	}
7526 
7527 	/*
7528 	 * The append failed. Do a short read. If that fails,  we are at EOM
7529 	 * so we can retry the write command. If that succeeds, than we're
7530 	 * all screwed up (the controller reported a real error).
7531 	 *
7532 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7533 	 * XXX: block size?
7534 	 *
7535 	 */
7536 	status = un->un_status;
7537 	un->un_status = 0;
7538 	(void) st_cmd(un, SCMD_READ, SECSIZE, SYNC_CMD);
7539 	if (un->un_status == KEY_BLANK_CHECK) {
7540 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7541 		    "append at EOM\n");
7542 		/*
7543 		 * Okay- the read failed. We should actually have confused
7544 		 * the controller enough to allow writing. In any case, the
7545 		 * i/o is on its own from here on out.
7546 		 */
7547 		un->un_laststate = un->un_state;
7548 		un->un_state = ST_STATE_OPEN;
7549 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7550 		if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount,
7551 		    SYNC_CMD) == 0) {
7552 			goto success;
7553 		}
7554 	}
7555 
7556 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7557 	    "append write failed- not at EOM\n");
7558 	bp->b_resid = bp->b_bcount;
7559 	st_bioerror(bp, EIO);
7560 
7561 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7562 	    "st_test_append : EIO : append write failed - not at EOM");
7563 
7564 	/*
7565 	 * backspace one record to get back to where we were
7566 	 */
7567 	if (st_cmd(un, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7568 		un->un_pos.pmode = invalid;
7569 	}
7570 
7571 	un->un_err_resid = bp->b_resid;
7572 	un->un_status = status;
7573 
7574 	/*
7575 	 * Note: biodone will do a bp_mapout()
7576 	 */
7577 	mutex_exit(ST_MUTEX);
7578 	bcount = (unsigned)bp->b_bcount;
7579 	biodone(bp);
7580 	mutex_enter(ST_MUTEX);
7581 	un->un_laststate = un->un_state;
7582 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7583 	kmem_free(un->un_tmpbuf, bcount);
7584 	un->un_tmpbuf = NULL;
7585 }
7586 
7587 /*
7588  * Special command handler
7589  */
7590 
7591 /*
7592  * common st_cmd code. The fourth parameter states
7593  * whether the caller wishes to await the results
7594  * Note the release of the mutex during most of the function
7595  */
7596 static int
7597 st_cmd(struct scsi_tape *un, int com, int64_t count, int wait)
7598 {
7599 	struct buf *bp;
7600 	int err;
7601 	uint_t last_err_resid;
7602 
7603 	ST_FUNC(ST_DEVINFO, st_cmd);
7604 
7605 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7606 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %"PRIx64", wait = %d)\n",
7607 	    un->un_dev, com, count, wait);
7608 
7609 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7610 	ASSERT(mutex_owned(ST_MUTEX));
7611 
7612 #ifdef STDEBUG
7613 	if ((st_debug & 0x7)) {
7614 		st_debug_cmds(un, com, count, wait);
7615 	}
7616 #endif
7617 
7618 	st_wait_for_io(un);
7619 
7620 	/* check to see if this command requires the drive to be reserved */
7621 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7622 
7623 	if (err) {
7624 		return (err);
7625 	}
7626 
7627 	/*
7628 	 * A space command is not recoverable if we don't know were we
7629 	 * were when it was issued.
7630 	 */
7631 	if ((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) {
7632 		(void) st_update_block_pos(un, st_cmd, 0);
7633 	}
7634 
7635 	/*
7636 	 * Forground should not be doing anything while recovery is active.
7637 	 */
7638 	ASSERT(un->un_recov_buf_busy == 0);
7639 
7640 	while (un->un_sbuf_busy)
7641 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7642 	un->un_sbuf_busy = 1;
7643 
7644 	bp = un->un_sbufp;
7645 	bzero(bp, sizeof (buf_t));
7646 
7647 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7648 
7649 	err = st_setup_cmd(un, bp, com, count);
7650 
7651 	un->un_sbuf_busy = 0;
7652 
7653 	/*
7654 	 * If was a space command need to update logical block position.
7655 	 * Only do this if the command was sucessful or it will mask the fact
7656 	 * that the space command failed by promoting the pmode to logical.
7657 	 */
7658 	if (((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) &&
7659 	    (un->un_pos.pmode != invalid)) {
7660 		un->un_running.pmode = invalid;
7661 		last_err_resid = un->un_err_resid;
7662 		(void) st_update_block_pos(un, st_cmd, 1);
7663 		/*
7664 		 * Set running position to invalid so it updates on the
7665 		 * next command.
7666 		 */
7667 		un->un_running.pmode = invalid;
7668 		un->un_err_resid = last_err_resid;
7669 	}
7670 
7671 	cv_signal(&un->un_sbuf_cv);
7672 
7673 	return (err);
7674 }
7675 
7676 static int
7677 st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com, int64_t count)
7678 {
7679 	int err;
7680 	dev_t dev = un->un_dev;
7681 
7682 	ST_FUNC(ST_DEVINFO, st_setup_cmd);
7683 	/*
7684 	 * Set count to the actual size of the data tranfer.
7685 	 * For commands with no data transfer, set bp->b_bcount
7686 	 * to the value to be used when constructing the
7687 	 * cdb in st_make_cmd().
7688 	 */
7689 	switch (com) {
7690 	case SCMD_READ:
7691 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7692 		    "special read %"PRId64"\n", count);
7693 		bp->b_flags |= B_READ;
7694 		bp->b_un.b_addr = un->un_tmpbuf;
7695 		break;
7696 
7697 	case SCMD_WRITE:
7698 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7699 		    "special write %"PRId64"\n", count);
7700 		bp->b_un.b_addr = un->un_tmpbuf;
7701 		break;
7702 
7703 	case SCMD_WRITE_FILE_MARK:
7704 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7705 		    "write %"PRId64" file marks\n", count);
7706 		bp->b_bcount = count;
7707 		count = 0;
7708 		break;
7709 
7710 	case SCMD_REWIND:
7711 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7712 		bp->b_bcount = count;
7713 		count = 0;
7714 		break;
7715 
7716 	case SCMD_SPACE:
7717 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7718 		/*
7719 		 * If the user could have entered a number that will
7720 		 * not fit in the 12 bit count field of space(8),
7721 		 * use space(16).
7722 		 */
7723 		if (((int64_t)SPACE_CNT(count) > 0x7fffff) ||
7724 		    ((int64_t)SPACE_CNT(count) < -(0x7fffff))) {
7725 			com = SCMD_SPACE_G4;
7726 		}
7727 		bp->b_bcount = count;
7728 		count = 0;
7729 		break;
7730 
7731 	case SCMD_RESERVE:
7732 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7733 		bp->b_bcount = 0;
7734 		count = 0;
7735 		break;
7736 
7737 	case SCMD_RELEASE:
7738 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7739 		bp->b_bcount = 0;
7740 		count = 0;
7741 		break;
7742 
7743 	case SCMD_LOAD:
7744 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7745 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7746 		bp->b_bcount = count;
7747 		count = 0;
7748 		break;
7749 
7750 	case SCMD_ERASE:
7751 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7752 		    "erase tape\n");
7753 		bp->b_bcount = count;
7754 		count = 0;
7755 		break;
7756 
7757 	case SCMD_MODE_SENSE:
7758 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7759 		    "mode sense\n");
7760 		bp->b_flags |= B_READ;
7761 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7762 		break;
7763 
7764 	case SCMD_MODE_SELECT:
7765 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7766 		    "mode select\n");
7767 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7768 		break;
7769 
7770 	case SCMD_READ_BLKLIM:
7771 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7772 		    "read block limits\n");
7773 		bp->b_bcount = count;
7774 		bp->b_flags |= B_READ;
7775 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7776 		break;
7777 
7778 	case SCMD_TEST_UNIT_READY:
7779 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7780 		    "test unit ready\n");
7781 		bp->b_bcount = 0;
7782 		count = 0;
7783 		break;
7784 
7785 	case SCMD_DOORLOCK:
7786 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7787 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7788 		bp->b_bcount = count = 0;
7789 		break;
7790 
7791 	case SCMD_READ_POSITION:
7792 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7793 		    "read position\n");
7794 		switch (un->un_read_pos_type) {
7795 		case LONG_POS:
7796 			count = sizeof (tape_position_long_t);
7797 			break;
7798 		case EXT_POS:
7799 			count = min(count, sizeof (tape_position_ext_t));
7800 			break;
7801 		case SHORT_POS:
7802 			count = sizeof (tape_position_t);
7803 			break;
7804 		default:
7805 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7806 			    "Unknown read position type 0x%x in "
7807 			    "st_make_cmd()\n", un->un_read_pos_type);
7808 		}
7809 		bp->b_bcount = count;
7810 		bp->b_flags |= B_READ;
7811 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7812 		break;
7813 
7814 	default:
7815 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7816 		    "Unhandled scsi command 0x%x in st_setup_cmd()\n", com);
7817 	}
7818 
7819 	mutex_exit(ST_MUTEX);
7820 
7821 	if (count > 0) {
7822 		int flg = (bp->b_flags & B_READ) ? B_READ : B_WRITE;
7823 		/*
7824 		 * We're going to do actual I/O.
7825 		 * Set things up for physio.
7826 		 */
7827 		struct iovec aiov;
7828 		struct uio auio;
7829 		struct uio *uio = &auio;
7830 
7831 		bzero(&auio, sizeof (struct uio));
7832 		bzero(&aiov, sizeof (struct iovec));
7833 		aiov.iov_base = bp->b_un.b_addr;
7834 		aiov.iov_len = count;
7835 
7836 		uio->uio_iov = &aiov;
7837 		uio->uio_iovcnt = 1;
7838 		uio->uio_resid = aiov.iov_len;
7839 		uio->uio_segflg = UIO_SYSSPACE;
7840 
7841 		/*
7842 		 * Let physio do the rest...
7843 		 */
7844 		bp->b_forw = (struct buf *)(uintptr_t)com;
7845 		bp->b_back = NULL;
7846 		err = physio(st_strategy, bp, dev, flg, st_minphys, uio);
7847 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7848 		    "st_setup_cmd: physio returns %d\n", err);
7849 	} else {
7850 		/*
7851 		 * Mimic physio
7852 		 */
7853 		bp->b_forw = (struct buf *)(uintptr_t)com;
7854 		bp->b_back = NULL;
7855 		bp->b_edev = dev;
7856 		bp->b_dev = cmpdev(dev);
7857 		bp->b_blkno = 0;
7858 		bp->b_resid = 0;
7859 		(void) st_strategy(bp);
7860 		if (bp->b_flags & B_ASYNC) {
7861 			/*
7862 			 * This is an async command- the caller won't wait
7863 			 * and doesn't care about errors.
7864 			 */
7865 			mutex_enter(ST_MUTEX);
7866 			return (0);
7867 		}
7868 
7869 		/*
7870 		 * BugTraq #4260046
7871 		 * ----------------
7872 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7873 		 * unconditionally. The old comment said...
7874 		 *
7875 		 * "if strategy was flagged with  persistent errors, we would
7876 		 *  have an error here, and the bp would never be sent, so we
7877 		 *  don't want to wait on a bp that was never sent...or hang"
7878 		 *
7879 		 * The new rationale, courtesy of Chitrank...
7880 		 *
7881 		 * "we should unconditionally biowait() here because
7882 		 *  st_strategy() will do a biodone() in the persistent error
7883 		 *  case and the following biowait() will return immediately.
7884 		 *  If not, in the case of "errors after pkt alloc" in
7885 		 *  st_start(), we will not biowait here which will cause the
7886 		 *  next biowait() to return immediately which will cause
7887 		 *  us to send out the next command. In the case where both of
7888 		 *  these use the sbuf, when the first command completes we'll
7889 		 *  free the packet attached to sbuf and the same pkt will
7890 		 *  get freed again when we complete the second command.
7891 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7892 		 *  st_start() for the pkt alloc failure case because physio()
7893 		 *  does biowait() and will hang if we don't do biodone()"
7894 		 */
7895 
7896 		err = biowait(bp);
7897 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7898 		    "st_setup_cmd: biowait returns %d\n", err);
7899 	}
7900 
7901 	mutex_enter(ST_MUTEX);
7902 
7903 	return (err);
7904 }
7905 
7906 static int
7907 st_set_compression(struct scsi_tape *un)
7908 {
7909 	int rval;
7910 	int turn_compression_on;
7911 	minor_t minor;
7912 
7913 	ST_FUNC(ST_DEVINFO, st_set_compression);
7914 
7915 	/*
7916 	 * Drive either dosn't have compression or it is controlled with
7917 	 * special density codes. Return ENOTTY so caller
7918 	 * knows nothing was done.
7919 	 */
7920 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7921 		un->un_comp_page = 0;
7922 		return (ENOTTY);
7923 	}
7924 
7925 	/* set compression based on minor node opened */
7926 	minor = MT_DENSITY(un->un_dev);
7927 
7928 	/*
7929 	 * If this the compression density or
7930 	 * the drive has two densities and uses mode select for
7931 	 * control of compression turn on compression for MT_DENSITY2
7932 	 * as well.
7933 	 */
7934 	if ((minor == ST_COMPRESSION_DENSITY) ||
7935 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7936 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7937 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7938 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7939 
7940 		turn_compression_on = 1;
7941 	} else {
7942 		turn_compression_on = 0;
7943 	}
7944 
7945 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7946 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7947 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7948 
7949 	/*
7950 	 * Need to determine which page does the device use for compression.
7951 	 * First try the data compression page. If this fails try the device
7952 	 * configuration page
7953 	 */
7954 
7955 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7956 		rval = st_set_datacomp_page(un, turn_compression_on);
7957 		if (rval == EALREADY) {
7958 			return (rval);
7959 		}
7960 		if (rval != 0) {
7961 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7962 				/*
7963 				 * This device does not support data
7964 				 * compression page
7965 				 */
7966 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7967 			} else if (un->un_state >= ST_STATE_OPEN) {
7968 				un->un_pos.pmode = invalid;
7969 				rval = EIO;
7970 			} else {
7971 				rval = -1;
7972 			}
7973 		} else {
7974 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7975 		}
7976 	}
7977 
7978 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7979 		rval = st_set_devconfig_page(un, turn_compression_on);
7980 		if (rval == EALREADY) {
7981 			return (rval);
7982 		}
7983 		if (rval != 0) {
7984 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7985 				/*
7986 				 * This device does not support
7987 				 * compression at all advice the
7988 				 * user and unset ST_MODE_SEL_COMP
7989 				 */
7990 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7991 				un->un_comp_page = 0;
7992 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7993 				    "Device Does Not Support Compression\n");
7994 			} else if (un->un_state >= ST_STATE_OPEN) {
7995 				un->un_pos.pmode = invalid;
7996 				rval = EIO;
7997 			} else {
7998 				rval = -1;
7999 			}
8000 		}
8001 	}
8002 
8003 	return (rval);
8004 }
8005 
8006 /*
8007  * set or unset compression thru device configuration page.
8008  */
8009 static int
8010 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
8011 {
8012 	unsigned char cflag;
8013 	int rval = 0;
8014 
8015 
8016 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
8017 
8018 	ASSERT(mutex_owned(ST_MUTEX));
8019 
8020 	/*
8021 	 * if the mode sense page is not the correct one, load the correct one.
8022 	 */
8023 	if (un->un_mspl->page_code != ST_DEV_CONFIG_PAGE) {
8024 		rval = st_gen_mode_sense(un, st_uscsi_cmd, ST_DEV_CONFIG_PAGE,
8025 		    un->un_mspl, sizeof (struct seq_mode));
8026 		if (rval)
8027 			return (rval);
8028 	}
8029 
8030 	/*
8031 	 * Figure what to set compression flag to.
8032 	 */
8033 	if (compression_on) {
8034 		/* They have selected a compression node */
8035 		if (un->un_dp->type == ST_TYPE_FUJI) {
8036 			cflag = 0x84;   /* use EDRC */
8037 		} else {
8038 			cflag = ST_DEV_CONFIG_DEF_COMP;
8039 		}
8040 	} else {
8041 		cflag = ST_DEV_CONFIG_NO_COMP;
8042 	}
8043 
8044 	/*
8045 	 * If compression is already set the way it was requested.
8046 	 * And if this not the first time we has tried.
8047 	 */
8048 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
8049 	    (un->un_comp_page == ST_DEV_CONFIG_PAGE)) {
8050 		return (EALREADY);
8051 	}
8052 
8053 	un->un_mspl->page.dev.comp_alg = cflag;
8054 	/*
8055 	 * need to send mode select even if correct compression is
8056 	 * already set since need to set density code
8057 	 */
8058 
8059 #ifdef STDEBUG
8060 	if ((st_debug & 0x7) >= 6) {
8061 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8062 		    "st_set_devconfig_page: sense data for mode select",
8063 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8064 	}
8065 #endif
8066 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8067 	    sizeof (struct seq_mode));
8068 
8069 	return (rval);
8070 }
8071 
8072 /*
8073  * set/reset compression bit thru data compression page
8074  */
8075 static int
8076 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
8077 {
8078 	int compression_on_already;
8079 	int rval = 0;
8080 
8081 
8082 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
8083 
8084 	ASSERT(mutex_owned(ST_MUTEX));
8085 
8086 	/*
8087 	 * if the mode sense page is not the correct one, load the correct one.
8088 	 */
8089 	if (un->un_mspl->page_code != ST_DEV_DATACOMP_PAGE) {
8090 		rval = st_gen_mode_sense(un, st_uscsi_cmd, ST_DEV_DATACOMP_PAGE,
8091 		    un->un_mspl, sizeof (struct seq_mode));
8092 		if (rval)
8093 			return (rval);
8094 	}
8095 
8096 	/*
8097 	 * If drive is not capable of compression (at this time)
8098 	 * return EALREADY so caller doesn't think that this page
8099 	 * is not supported. This check is for drives that can
8100 	 * disable compression from the front panel or configuration.
8101 	 * I doubt that a drive that supports this page is not really
8102 	 * capable of compression.
8103 	 */
8104 	if (un->un_mspl->page.comp.dcc == 0) {
8105 		return (EALREADY);
8106 	}
8107 
8108 	/* See if compression currently turned on */
8109 	if (un->un_mspl->page.comp.dce) {
8110 		compression_on_already = 1;
8111 	} else {
8112 		compression_on_already = 0;
8113 	}
8114 
8115 	/*
8116 	 * If compression is already set the way it was requested.
8117 	 * And if this not the first time we has tried.
8118 	 */
8119 	if ((compression_on == compression_on_already) &&
8120 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
8121 		return (EALREADY);
8122 	}
8123 
8124 	/*
8125 	 * if we are already set to the appropriate compression
8126 	 * mode, don't set it again
8127 	 */
8128 	if (compression_on) {
8129 		/* compression selected */
8130 		un->un_mspl->page.comp.dce = 1;
8131 	} else {
8132 		un->un_mspl->page.comp.dce = 0;
8133 	}
8134 
8135 
8136 #ifdef STDEBUG
8137 	if ((st_debug & 0x7) >= 6) {
8138 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8139 		    "st_set_datacomp_page: sense data for mode select",
8140 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8141 	}
8142 #endif
8143 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8144 	    sizeof (struct seq_mode));
8145 
8146 	return (rval);
8147 }
8148 
8149 static int
8150 st_modesense(struct scsi_tape *un)
8151 {
8152 	int rval;
8153 	uchar_t page;
8154 
8155 	ST_FUNC(ST_DEVINFO, st_modesense);
8156 
8157 	page = un->un_comp_page;
8158 
8159 	switch (page) {
8160 	case ST_DEV_DATACOMP_PAGE:
8161 	case ST_DEV_CONFIG_PAGE: /* FALLTHROUGH */
8162 		rval = st_gen_mode_sense(un, st_uscsi_cmd, page, un->un_mspl,
8163 		    sizeof (struct seq_mode));
8164 		break;
8165 
8166 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
8167 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
8168 			page = ST_DEV_DATACOMP_PAGE;
8169 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8170 			    un->un_mspl, sizeof (struct seq_mode));
8171 			if (rval == 0 && un->un_mspl->page_code == page) {
8172 				un->un_comp_page = page;
8173 				break;
8174 			}
8175 			page = ST_DEV_CONFIG_PAGE;
8176 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8177 			    un->un_mspl, sizeof (struct seq_mode));
8178 			if (rval == 0 && un->un_mspl->page_code == page) {
8179 				un->un_comp_page = page;
8180 				break;
8181 			}
8182 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
8183 			un->un_comp_page = 0;
8184 		} else {
8185 			un->un_comp_page = 0;
8186 		}
8187 
8188 	default:	/* FALLTHROUGH */
8189 		rval = st_cmd(un, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
8190 	}
8191 	return (rval);
8192 }
8193 
8194 static int
8195 st_modeselect(struct scsi_tape *un)
8196 {
8197 	int rval = 0;
8198 	int ix;
8199 
8200 	ST_FUNC(ST_DEVINFO, st_modeselect);
8201 
8202 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8203 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
8204 	    un->un_dev, un->un_mspl->density);
8205 
8206 	ASSERT(mutex_owned(ST_MUTEX));
8207 
8208 	/*
8209 	 * The parameter list should be the same for all of the
8210 	 * cases that follow so set them here
8211 	 *
8212 	 * Try mode select first if if fails set fields manually
8213 	 */
8214 	rval = st_modesense(un);
8215 	if (rval != 0) {
8216 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8217 		    "st_modeselect: First mode sense failed\n");
8218 		un->un_mspl->bd_len  = 8;
8219 		un->un_mspl->high_nb = 0;
8220 		un->un_mspl->mid_nb  = 0;
8221 		un->un_mspl->low_nb  = 0;
8222 	}
8223 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
8224 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
8225 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
8226 
8227 
8228 	/*
8229 	 * If configured to use a specific density code for a media type.
8230 	 * curdens is previously set by the minor node opened.
8231 	 * If the media type doesn't match the minor node we change it so it
8232 	 * looks like the correct one was opened.
8233 	 */
8234 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
8235 		uchar_t best;
8236 
8237 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
8238 			if (un->un_mspl->media_type ==
8239 			    un->un_dp->mediatype[ix]) {
8240 				best = ix;
8241 				/*
8242 				 * It matches but it might not be the only one.
8243 				 * Use the highest matching media type but not
8244 				 * to exceed the density selected by the open.
8245 				 */
8246 				if (ix < un->un_curdens) {
8247 					continue;
8248 				}
8249 				un->un_curdens = ix;
8250 				break;
8251 			}
8252 		}
8253 		/* If a match was found best will not be 0xff any more */
8254 		if (best < NDENSITIES) {
8255 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8256 			    "found media 0x%X using density 0x%X\n",
8257 			    un->un_mspl->media_type,
8258 			    un->un_dp->densities[best]);
8259 			un->un_mspl->density = un->un_dp->densities[best];
8260 		} else {
8261 			/* Otherwise set density based on minor node opened */
8262 			un->un_mspl->density =
8263 			    un->un_dp->densities[un->un_curdens];
8264 		}
8265 	} else {
8266 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
8267 	}
8268 
8269 	if (un->un_dp->options & ST_NOBUF) {
8270 		un->un_mspl->bufm = 0;
8271 	} else {
8272 		un->un_mspl->bufm = 1;
8273 	}
8274 
8275 	rval = st_set_compression(un);
8276 
8277 	/*
8278 	 * If st_set_compression returned invalid or already it
8279 	 * found no need to do the mode select.
8280 	 * So do it here.
8281 	 */
8282 	if ((rval == ENOTTY) || (rval == EALREADY)) {
8283 
8284 		/* Zero non-writeable fields */
8285 		un->un_mspl->data_len = 0;
8286 		un->un_mspl->media_type = 0;
8287 		un->un_mspl->wp = 0;
8288 
8289 		/* need to set the density code */
8290 		rval = st_cmd(un, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
8291 		if (rval != 0) {
8292 			if (un->un_state >= ST_STATE_OPEN) {
8293 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8294 				    "unable to set tape mode\n");
8295 				un->un_pos.pmode = invalid;
8296 				rval = EIO;
8297 			} else {
8298 				rval = -1;
8299 			}
8300 		}
8301 	}
8302 
8303 	/*
8304 	 * The spec recommends to send a mode sense after a mode select
8305 	 */
8306 	(void) st_modesense(un);
8307 
8308 	ASSERT(mutex_owned(ST_MUTEX));
8309 
8310 	return (rval);
8311 }
8312 
8313 /*
8314  * st_gen_mode_sense
8315  *
8316  * generic mode sense.. it allows for any page
8317  */
8318 static int
8319 st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
8320     struct seq_mode *page_data, int page_size)
8321 {
8322 
8323 	int r;
8324 	char	cdb[CDB_GROUP0];
8325 	struct uscsi_cmd *com;
8326 	struct scsi_arq_status status;
8327 
8328 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
8329 
8330 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8331 
8332 	bzero(cdb, CDB_GROUP0);
8333 	cdb[0] = SCMD_MODE_SENSE;
8334 	cdb[2] = (char)page;
8335 	cdb[4] = (char)page_size;
8336 
8337 	com->uscsi_cdb = cdb;
8338 	com->uscsi_cdblen = CDB_GROUP0;
8339 	com->uscsi_bufaddr = (caddr_t)page_data;
8340 	com->uscsi_buflen = page_size;
8341 	com->uscsi_rqlen = sizeof (status);
8342 	com->uscsi_rqbuf = (caddr_t)&status;
8343 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8344 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8345 
8346 	r = ubf(un, com, FKIOCTL);
8347 	kmem_free(com, sizeof (*com));
8348 	return (r);
8349 }
8350 
8351 /*
8352  * st_gen_mode_select
8353  *
8354  * generic mode select.. it allows for any page
8355  */
8356 static int
8357 st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
8358     struct seq_mode *page_data, int page_size)
8359 {
8360 
8361 	int r;
8362 	char cdb[CDB_GROUP0];
8363 	struct uscsi_cmd *com;
8364 	struct scsi_arq_status status;
8365 
8366 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
8367 
8368 	/* Zero non-writeable fields */
8369 	page_data->data_len = 0;
8370 	page_data->media_type = 0;
8371 	page_data->wp = 0;
8372 
8373 	/*
8374 	 * If mode select has any page data, zero the ps (Page Savable) bit.
8375 	 */
8376 	if (page_size > MSIZE) {
8377 		page_data->ps = 0;
8378 	}
8379 
8380 
8381 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8382 
8383 	/*
8384 	 * then, do a mode select to set what ever info
8385 	 */
8386 	bzero(cdb, CDB_GROUP0);
8387 	cdb[0] = SCMD_MODE_SELECT;
8388 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
8389 	cdb[4] = (char)page_size;
8390 
8391 	com->uscsi_cdb = cdb;
8392 	com->uscsi_cdblen = CDB_GROUP0;
8393 	com->uscsi_bufaddr = (caddr_t)page_data;
8394 	com->uscsi_buflen = page_size;
8395 	com->uscsi_rqlen = sizeof (status);
8396 	com->uscsi_rqbuf = (caddr_t)&status;
8397 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8398 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_WRITE;
8399 
8400 	r = ubf(un, com, FKIOCTL);
8401 
8402 	kmem_free(com, sizeof (*com));
8403 	return (r);
8404 }
8405 
8406 static int
8407 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
8408 {
8409 	int rval;
8410 	char cdb[CDB_GROUP0];
8411 	struct uscsi_cmd *com;
8412 	struct scsi_arq_status status;
8413 
8414 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
8415 
8416 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8417 
8418 	bzero(cdb, CDB_GROUP0);
8419 	cdb[0] = SCMD_READ_BLKLIM;
8420 
8421 	com->uscsi_cdb = cdb;
8422 	com->uscsi_cdblen = CDB_GROUP0;
8423 	com->uscsi_bufaddr = (caddr_t)read_blk;
8424 	com->uscsi_buflen = sizeof (struct read_blklim);
8425 	com->uscsi_rqlen = sizeof (status);
8426 	com->uscsi_rqbuf = (caddr_t)&status;
8427 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8428 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8429 
8430 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8431 	if (com->uscsi_status || com->uscsi_resid) {
8432 		rval = -1;
8433 	}
8434 
8435 	kmem_free(com, sizeof (*com));
8436 	return (rval);
8437 }
8438 
8439 static int
8440 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
8441     size_t buflen)
8442 {
8443 	int rval;
8444 	char cdb[CDB_GROUP1];
8445 	struct uscsi_cmd *com;
8446 	struct scsi_arq_status status;
8447 
8448 	ST_FUNC(ST_DEVINFO, st_report_density_support);
8449 
8450 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8451 
8452 	bzero(cdb, CDB_GROUP1);
8453 	cdb[0] = SCMD_REPORT_DENSITIES;
8454 	cdb[7] = (buflen & 0xff00) >> 8;
8455 	cdb[8] = buflen & 0xff;
8456 
8457 	com->uscsi_cdb = cdb;
8458 	com->uscsi_cdblen = CDB_GROUP1;
8459 	com->uscsi_bufaddr = (caddr_t)density_data;
8460 	com->uscsi_buflen = buflen;
8461 	com->uscsi_rqlen = sizeof (status);
8462 	com->uscsi_rqbuf = (caddr_t)&status;
8463 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8464 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8465 
8466 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8467 	if (com->uscsi_status || com->uscsi_resid) {
8468 		rval = -1;
8469 	}
8470 
8471 	kmem_free(com, sizeof (*com));
8472 	return (rval);
8473 }
8474 
8475 static int
8476 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
8477     uchar_t option_code, ushort_t service_action)
8478 {
8479 	int rval;
8480 	char cdb[CDB_GROUP5];
8481 	struct uscsi_cmd *com;
8482 	struct scsi_arq_status status;
8483 	uint32_t allo_length;
8484 
8485 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
8486 
8487 	allo_length = sizeof (struct one_com_des) +
8488 	    sizeof (struct com_timeout_des);
8489 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8490 
8491 	bzero(cdb, CDB_GROUP5);
8492 	cdb[0] = (char)SCMD_MAINTENANCE_IN;
8493 	cdb[1] = SSVC_ACTION_GET_SUPPORTED_OPERATIONS;
8494 	if (service_action) {
8495 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
8496 		cdb[4] = (service_action & 0xff00) >> 8;
8497 		cdb[5] = service_action & 0xff;
8498 	} else {
8499 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
8500 		    0x80); /* RCTD */
8501 	}
8502 	cdb[3] = option_code;
8503 	cdb[6] = (allo_length & 0xff000000) >> 24;
8504 	cdb[7] = (allo_length & 0xff0000) >> 16;
8505 	cdb[8] = (allo_length & 0xff00) >> 8;
8506 	cdb[9] = allo_length & 0xff;
8507 
8508 	com->uscsi_cdb = cdb;
8509 	com->uscsi_cdblen = CDB_GROUP5;
8510 	com->uscsi_bufaddr = (caddr_t)oper_data;
8511 	com->uscsi_buflen = allo_length;
8512 	com->uscsi_rqlen = sizeof (status);
8513 	com->uscsi_rqbuf = (caddr_t)&status;
8514 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8515 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8516 
8517 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8518 	if (com->uscsi_status) {
8519 		rval = -1;
8520 	}
8521 
8522 	kmem_free(com, sizeof (*com));
8523 	return (rval);
8524 }
8525 
8526 /*
8527  * Changes devices blocksize and bsize to requested blocksize nblksz.
8528  * Returns returned value from first failed call or zero on success.
8529  */
8530 static int
8531 st_change_block_size(struct scsi_tape *un, uint32_t nblksz)
8532 {
8533 	struct seq_mode *current;
8534 	int rval;
8535 	uint32_t oldblksz;
8536 
8537 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8538 
8539 	current = kmem_zalloc(MSIZE, KM_SLEEP);
8540 
8541 	/*
8542 	 * If we haven't got the compression page yet, do that first.
8543 	 */
8544 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
8545 		(void) st_modesense(un);
8546 	}
8547 
8548 	/* Read current settings */
8549 	rval = st_gen_mode_sense(un, st_uscsi_cmd, 0, current, MSIZE);
8550 	if (rval != 0) {
8551 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8552 		    "mode sense for change block size failed: rval = %d", rval);
8553 		goto finish;
8554 	}
8555 
8556 	/* Figure the current block size */
8557 	oldblksz =
8558 	    (current->high_bl << 16) |
8559 	    (current->mid_bl << 8) |
8560 	    (current->low_bl);
8561 
8562 	/* If current block size is the same as requested were done */
8563 	if (oldblksz == nblksz) {
8564 		un->un_bsize = nblksz;
8565 		rval = 0;
8566 		goto finish;
8567 	}
8568 
8569 	/* Change to requested block size */
8570 	current->high_bl = (uchar_t)(nblksz >> 16);
8571 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8572 	current->low_bl  = (uchar_t)(nblksz);
8573 
8574 	/* Attempt to change block size */
8575 	rval = st_gen_mode_select(un, st_uscsi_cmd, current, MSIZE);
8576 	if (rval != 0) {
8577 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8578 		    "Set new block size failed: rval = %d", rval);
8579 		goto finish;
8580 	}
8581 
8582 	/* Read back and verify setting */
8583 	rval = st_modesense(un);
8584 	if (rval == 0) {
8585 		un->un_bsize =
8586 		    (un->un_mspl->high_bl << 16) |
8587 		    (un->un_mspl->mid_bl << 8) |
8588 		    (un->un_mspl->low_bl);
8589 
8590 		if (un->un_bsize != nblksz) {
8591 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8592 			    "Blocksize set does not equal requested blocksize"
8593 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8594 			rval = EIO;
8595 		}
8596 	}
8597 finish:
8598 	kmem_free(current, MSIZE);
8599 	return (rval);
8600 }
8601 
8602 
8603 static void
8604 st_init(struct scsi_tape *un)
8605 {
8606 	ST_FUNC(ST_DEVINFO, st_init);
8607 
8608 	ASSERT(mutex_owned(ST_MUTEX));
8609 
8610 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8611 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8612 	    un->un_dev);
8613 
8614 	un->un_pos.blkno = 0;
8615 	un->un_pos.fileno = 0;
8616 	un->un_lastop = ST_OP_NIL;
8617 	un->un_pos.eof = ST_NO_EOF;
8618 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8619 	if (st_error_level != SCSI_ERR_ALL) {
8620 		if (DEBUGGING) {
8621 			st_error_level = SCSI_ERR_ALL;
8622 		} else {
8623 			st_error_level = SCSI_ERR_RETRYABLE;
8624 		}
8625 	}
8626 }
8627 
8628 
8629 static void
8630 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8631 {
8632 	struct scsi_pkt *pkt;
8633 	struct uscsi_cmd *ucmd;
8634 	recov_info *ri;
8635 	int tval = 0;
8636 	int64_t count;
8637 	uint32_t additional = 0;
8638 	uint32_t address = 0;
8639 	union scsi_cdb *ucdb;
8640 	int flags = 0;
8641 	int cdb_len = CDB_GROUP0; /* default */
8642 	uchar_t com;
8643 	char fixbit;
8644 	char short_fm = 0;
8645 	optype prev_op = un->un_lastop;
8646 	int stat_size =
8647 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
8648 
8649 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8650 
8651 	ASSERT(mutex_owned(ST_MUTEX));
8652 
8653 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8654 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8655 
8656 
8657 	/*
8658 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8659 	 * Length Indicator bits on read/write commands, for setting
8660 	 * the Long bit on erase commands, and for setting the Code
8661 	 * Field bits on space commands.
8662 	 */
8663 
8664 	/* regular raw I/O */
8665 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
8666 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8667 		    CDB_GROUP0, stat_size, st_recov_sz, 0, func,
8668 		    (caddr_t)un);
8669 		if (pkt == NULL) {
8670 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8671 			    "Read Write scsi_init_pkt() failure\n");
8672 			goto exit;
8673 		}
8674 		ASSERT(pkt->pkt_resid == 0);
8675 #ifdef STDEBUG
8676 		bzero(pkt->pkt_private, st_recov_sz);
8677 		bzero(pkt->pkt_scbp, stat_size);
8678 #endif
8679 		ri = (recov_info *)pkt->pkt_private;
8680 		ri->privatelen = st_recov_sz;
8681 		if (un->un_bsize == 0) {
8682 			count = bp->b_bcount;
8683 			fixbit = 0;
8684 		} else {
8685 			count = bp->b_bcount / un->un_bsize;
8686 			fixbit = 1;
8687 		}
8688 		if (bp->b_flags & B_READ) {
8689 			com = SCMD_READ;
8690 			un->un_lastop = ST_OP_READ;
8691 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8692 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8693 				fixbit = 2;
8694 			}
8695 		} else {
8696 			com = SCMD_WRITE;
8697 			un->un_lastop = ST_OP_WRITE;
8698 		}
8699 		tval = un->un_dp->io_timeout;
8700 
8701 		/*
8702 		 * For really large xfers, increase timeout
8703 		 */
8704 		if (bp->b_bcount > (10 * ONE_MEG))
8705 			tval *= bp->b_bcount/(10 * ONE_MEG);
8706 
8707 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8708 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8709 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8710 
8711 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8712 		/*
8713 		 * uscsi - build command, allocate scsi resources
8714 		 */
8715 		st_make_uscsi_cmd(un, ucmd, bp, func);
8716 		goto exit;
8717 
8718 	} else {				/* special I/O */
8719 		struct buf *allocbp = NULL;
8720 		com = (uchar_t)(uintptr_t)bp->b_forw;
8721 		count = bp->b_bcount;
8722 
8723 		switch (com) {
8724 		case SCMD_READ:
8725 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8726 			    "special read %"PRId64"\n", count);
8727 			if (un->un_bsize == 0) {
8728 				fixbit = 2;	/* suppress SILI */
8729 			} else {
8730 				fixbit = 1;	/* Fixed Block Mode */
8731 				count /= un->un_bsize;
8732 			}
8733 			allocbp = bp;
8734 			un->un_lastop = ST_OP_READ;
8735 			tval = un->un_dp->io_timeout;
8736 			break;
8737 
8738 		case SCMD_WRITE:
8739 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8740 			    "special write %"PRId64"\n", count);
8741 			if (un->un_bsize != 0) {
8742 				fixbit = 1;	/* Fixed Block Mode */
8743 				count /= un->un_bsize;
8744 			} else {
8745 				fixbit = 0;
8746 			}
8747 			allocbp = bp;
8748 			un->un_lastop = ST_OP_WRITE;
8749 			tval = un->un_dp->io_timeout;
8750 			break;
8751 
8752 		case SCMD_WRITE_FILE_MARK:
8753 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8754 			    "write %"PRId64" file marks\n", count);
8755 			un->un_lastop = ST_OP_WEOF;
8756 			fixbit = 0;
8757 			tval = un->un_dp->io_timeout;
8758 			/*
8759 			 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8760 			 * device, set the Vendor Unique bit to
8761 			 * write Short File Mark.
8762 			 */
8763 			if ((un->un_dp->options & ST_SHORT_FILEMARKS) &&
8764 			    ((un->un_dp->type == ST_TYPE_EXB8500) ||
8765 			    (un->un_dp->type == ST_TYPE_EXABYTE))) {
8766 				/*
8767 				 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8768 				 * is set to to write Short File Mark
8769 				 */
8770 				short_fm = 1;
8771 			}
8772 			break;
8773 
8774 		case SCMD_REWIND:
8775 			/*
8776 			 * In the case of rewind we're gona do the rewind with
8777 			 * the immediate bit set so status will be retured when
8778 			 * the command is accepted by the device. We clear the
8779 			 * B_ASYNC flag so we wait for that acceptance.
8780 			 */
8781 			fixbit = 0;
8782 			if (bp->b_flags & B_ASYNC) {
8783 				allocbp = bp;
8784 				if (count) {
8785 					fixbit = 1;
8786 					bp->b_flags &= ~B_ASYNC;
8787 				}
8788 			}
8789 			count = 0;
8790 			bp->b_bcount = 0;
8791 			un->un_lastop = ST_OP_CTL;
8792 			tval = un->un_dp->rewind_timeout;
8793 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8794 			    "rewind\n");
8795 			break;
8796 
8797 		case SCMD_SPACE_G4:
8798 			cdb_len = CDB_GROUP4;
8799 			fixbit = SPACE_TYPE(bp->b_bcount);
8800 			count = SPACE_CNT(bp->b_bcount);
8801 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8802 			    " %s space %s %"PRId64" from file %d blk %d\n",
8803 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8804 			    space_strs[fixbit & 7], count,
8805 			    un->un_pos.fileno, un->un_pos.blkno);
8806 			address = (count >> 48) & 0x1fff;
8807 			additional = (count >> 16) & 0xffffffff;
8808 			count &= 0xffff;
8809 			count <<= 16;
8810 			un->un_lastop = ST_OP_CTL;
8811 			tval = un->un_dp->space_timeout;
8812 			break;
8813 
8814 		case SCMD_SPACE:
8815 			fixbit = SPACE_TYPE(bp->b_bcount);
8816 			count = SPACE_CNT(bp->b_bcount);
8817 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8818 			    " %s space %s %"PRId64" from file %d blk %d\n",
8819 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8820 			    space_strs[fixbit & 7], count,
8821 			    un->un_pos.fileno, un->un_pos.blkno);
8822 			count &= 0xffffffff;
8823 			un->un_lastop = ST_OP_CTL;
8824 			tval = un->un_dp->space_timeout;
8825 			break;
8826 
8827 		case SCMD_LOAD:
8828 			ASSERT(count < 10);
8829 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8830 			    "%s tape\n", load_strs[count]);
8831 			fixbit = 0;
8832 
8833 			/* Loading or Unloading */
8834 			if (count & LD_LOAD) {
8835 				tval = un->un_dp->load_timeout;
8836 			} else {
8837 				tval = un->un_dp->unload_timeout;
8838 			}
8839 			/* Is Retension requested */
8840 			if (count & LD_RETEN) {
8841 				tval += un->un_dp->rewind_timeout;
8842 			}
8843 			un->un_lastop = ST_OP_CTL;
8844 			break;
8845 
8846 		case SCMD_ERASE:
8847 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8848 			    "erase tape\n");
8849 			ASSERT(count == 1); /* mt sets this */
8850 			if (count == 1) {
8851 				/*
8852 				 * do long erase
8853 				 */
8854 				fixbit = 1; /* Long */
8855 
8856 				/* Drive might not honor immidiate bit */
8857 				tval = un->un_dp->erase_timeout;
8858 			} else {
8859 				/* Short Erase */
8860 				tval = un->un_dp->erase_timeout;
8861 				fixbit = 0;
8862 			}
8863 			un->un_lastop = ST_OP_CTL;
8864 			count = 0;
8865 			break;
8866 
8867 		case SCMD_MODE_SENSE:
8868 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8869 			    "mode sense\n");
8870 			allocbp = bp;
8871 			fixbit = 0;
8872 			tval = un->un_dp->non_motion_timeout;
8873 			un->un_lastop = ST_OP_CTL;
8874 			break;
8875 
8876 		case SCMD_MODE_SELECT:
8877 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8878 			    "mode select\n");
8879 			allocbp = bp;
8880 			fixbit = 0;
8881 			tval = un->un_dp->non_motion_timeout;
8882 			un->un_lastop = ST_OP_CTL;
8883 			break;
8884 
8885 		case SCMD_RESERVE:
8886 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8887 			    "reserve\n");
8888 			fixbit = 0;
8889 			tval = un->un_dp->non_motion_timeout;
8890 			un->un_lastop = ST_OP_CTL;
8891 			break;
8892 
8893 		case SCMD_RELEASE:
8894 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8895 			    "release\n");
8896 			fixbit = 0;
8897 			tval = un->un_dp->non_motion_timeout;
8898 			un->un_lastop = ST_OP_CTL;
8899 			break;
8900 
8901 		case SCMD_READ_BLKLIM:
8902 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8903 			    "read block limits\n");
8904 			allocbp = bp;
8905 			fixbit = count = 0;
8906 			tval = un->un_dp->non_motion_timeout;
8907 			un->un_lastop = ST_OP_CTL;
8908 			break;
8909 
8910 		case SCMD_TEST_UNIT_READY:
8911 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8912 			    "test unit ready\n");
8913 			fixbit = 0;
8914 			tval = un->un_dp->non_motion_timeout;
8915 			un->un_lastop = ST_OP_CTL;
8916 			break;
8917 
8918 		case SCMD_DOORLOCK:
8919 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8920 			    "prevent/allow media removal\n");
8921 			fixbit = 0;
8922 			tval = un->un_dp->non_motion_timeout;
8923 			un->un_lastop = ST_OP_CTL;
8924 			break;
8925 
8926 		case SCMD_READ_POSITION:
8927 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8928 			    "read position\n");
8929 			fixbit = un->un_read_pos_type;
8930 			cdb_len = CDB_GROUP1;
8931 			tval = un->un_dp->non_motion_timeout;
8932 			allocbp = bp;
8933 			un->un_lastop = ST_OP_CTL;
8934 			switch (un->un_read_pos_type) {
8935 			case LONG_POS:
8936 				count = 0;
8937 				break;
8938 			case EXT_POS:
8939 				count = sizeof (tape_position_ext_t);
8940 				break;
8941 			case SHORT_POS:
8942 				count = 0;
8943 				break;
8944 			default:
8945 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8946 				    "Unknown read position type 0x%x in "
8947 				    " st_make_cmd()\n", un->un_read_pos_type);
8948 			}
8949 			break;
8950 
8951 		default:
8952 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8953 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8954 			    com);
8955 		}
8956 
8957 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8958 		    st_recov_sz, 0, func, (caddr_t)un);
8959 		if (pkt == NULL) {
8960 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8961 			    "generic command scsi_init_pkt() failure\n");
8962 			goto exit;
8963 		}
8964 
8965 		ASSERT(pkt->pkt_resid == 0);
8966 #ifdef STDEBUG
8967 		bzero(pkt->pkt_private, st_recov_sz);
8968 		bzero(pkt->pkt_scbp, stat_size);
8969 #endif
8970 		ri = (recov_info *)pkt->pkt_private;
8971 		ri->privatelen = st_recov_sz;
8972 		if (allocbp) {
8973 			ASSERT(geterror(allocbp) == 0);
8974 		}
8975 
8976 	}
8977 
8978 	ucdb = (union scsi_cdb *)pkt->pkt_cdbp;
8979 
8980 	(void) scsi_setup_cdb(ucdb, com, address, (uint_t)count, additional);
8981 	FILL_SCSI1_LUN(un->un_sd, pkt);
8982 	/*
8983 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8984 	 */
8985 	ucdb->t_code = fixbit;
8986 	ucdb->g0_vu_1 = short_fm;
8987 	pkt->pkt_flags = flags;
8988 
8989 	ASSERT(tval);
8990 	pkt->pkt_time = tval;
8991 	if (bp == un->un_recov_buf) {
8992 		pkt->pkt_comp = st_recov_cb;
8993 	} else {
8994 		pkt->pkt_comp = st_intr;
8995 	}
8996 
8997 	st_add_recovery_info_to_pkt(un, bp, pkt);
8998 
8999 	/*
9000 	 * If we just write data to tape and did a command that doesn't
9001 	 * change position, we still need to write a filemark.
9002 	 */
9003 	if ((prev_op == ST_OP_WRITE) || (prev_op == ST_OP_WEOF)) {
9004 		recov_info *rcvi = pkt->pkt_private;
9005 		cmd_attribute const *atrib;
9006 
9007 		if (rcvi->privatelen == sizeof (recov_info)) {
9008 			atrib = rcvi->cmd_attrib;
9009 		} else {
9010 			atrib = st_lookup_cmd_attribute(com);
9011 		}
9012 		if (atrib->chg_tape_direction == DIR_NONE) {
9013 			un->un_lastop = prev_op;
9014 		}
9015 	}
9016 
9017 exit:
9018 	ASSERT(mutex_owned(ST_MUTEX));
9019 }
9020 
9021 
9022 /*
9023  * Build a command based on a uscsi command;
9024  */
9025 static void
9026 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
9027     struct buf *bp, int (*func)(caddr_t))
9028 {
9029 	struct scsi_pkt *pkt;
9030 	recov_info *ri;
9031 	caddr_t cdb;
9032 	int	cdblen;
9033 	int	stat_size = 1;
9034 	int	flags = 0;
9035 
9036 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
9037 
9038 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9039 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
9040 
9041 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
9042 		if (un->un_arq_enabled) {
9043 			if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
9044 				stat_size = (int)(ucmd->uscsi_rqlen) +
9045 				    sizeof (struct scsi_arq_status) -
9046 				    sizeof (struct scsi_extended_sense);
9047 				flags = PKT_XARQ;
9048 			} else {
9049 				stat_size = sizeof (struct scsi_arq_status);
9050 			}
9051 		}
9052 	}
9053 
9054 	ASSERT(mutex_owned(ST_MUTEX));
9055 
9056 	cdb = ucmd->uscsi_cdb;
9057 	cdblen = ucmd->uscsi_cdblen;
9058 
9059 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9060 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
9061 	    ucmd->uscsi_buflen, bp->b_bcount);
9062 	pkt = scsi_init_pkt(ROUTE, NULL,
9063 	    (bp->b_bcount > 0) ? bp : NULL,
9064 	    cdblen, stat_size, st_recov_sz, flags, func, (caddr_t)un);
9065 	if (pkt == NULL) {
9066 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
9067 		    "uscsi command scsi_init_pkt() failure\n");
9068 		goto exit;
9069 	}
9070 
9071 	ASSERT(pkt->pkt_resid == 0);
9072 #ifdef STDEBUG
9073 	bzero(pkt->pkt_private, st_recov_sz);
9074 	bzero(pkt->pkt_scbp, stat_size);
9075 #endif
9076 	ri = (recov_info *)pkt->pkt_private;
9077 	ri->privatelen = st_recov_sz;
9078 
9079 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
9080 
9081 #ifdef STDEBUG
9082 	if ((st_debug & 0x7) >= 6) {
9083 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
9084 		    "pkt_cdbp", (char *)cdb, cdblen);
9085 	}
9086 #endif
9087 
9088 	if (ucmd->uscsi_flags & USCSI_SILENT) {
9089 		pkt->pkt_flags |= FLAG_SILENT;
9090 	}
9091 
9092 	(void) scsi_uscsi_pktinit(ucmd, pkt);
9093 
9094 	pkt->pkt_time = ucmd->uscsi_timeout;
9095 	if (bp == un->un_recov_buf) {
9096 		pkt->pkt_comp = st_recov_cb;
9097 	} else {
9098 		pkt->pkt_comp = st_intr;
9099 	}
9100 
9101 	st_add_recovery_info_to_pkt(un, bp, pkt);
9102 exit:
9103 	ASSERT(mutex_owned(ST_MUTEX));
9104 }
9105 
9106 
9107 /*
9108  * restart cmd currently at the head of the runq
9109  *
9110  * If scsi_transport() succeeds or the retries
9111  * count exhausted, restore the throttle that was
9112  * zeroed out in st_handle_intr_busy().
9113  *
9114  */
9115 static void
9116 st_intr_restart(void *arg)
9117 {
9118 	struct scsi_tape *un = arg;
9119 	struct buf *bp;
9120 	int queued;
9121 	int status = TRAN_ACCEPT;
9122 
9123 	mutex_enter(ST_MUTEX);
9124 
9125 	ST_FUNC(ST_DEVINFO, st_intr_restart);
9126 
9127 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9128 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
9129 
9130 	un->un_hib_tid = 0;
9131 
9132 	if (un->un_recov_buf_busy != 0) {
9133 		bp = un->un_recov_buf;
9134 		queued = 0;
9135 	} else if (un->un_sbuf_busy != 0) {
9136 		bp = un->un_sbufp;
9137 		queued = 0;
9138 	} else if (un->un_quef != NULL) {
9139 		bp = un->un_quef;
9140 		queued = 1;
9141 	} else {
9142 		mutex_exit(ST_MUTEX);
9143 		return;
9144 	}
9145 
9146 	/*
9147 	 * Here we know :
9148 	 *	throttle = 0, via st_handle_intr_busy
9149 	 */
9150 
9151 	if (queued) {
9152 		/*
9153 		 * move from waitq to runq, if there is anything on the waitq
9154 		 */
9155 		(void) st_remove_from_queue(&un->un_quef, &un->un_quef, bp);
9156 
9157 		if (un->un_runqf) {
9158 			/*
9159 			 * not good, we don't want to requeue something after
9160 			 * another.
9161 			 */
9162 			goto done_error;
9163 		} else {
9164 			un->un_runqf = bp;
9165 			un->un_runql = bp;
9166 		}
9167 	}
9168 
9169 	ST_CDB(ST_DEVINFO, "Interrupt restart CDB",
9170 	    (char *)BP_PKT(bp)->pkt_cdbp);
9171 
9172 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
9173 
9174 	status = st_transport(un, BP_PKT(bp));
9175 
9176 	if (status != TRAN_ACCEPT) {
9177 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9178 
9179 		if (status == TRAN_BUSY) {
9180 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
9181 
9182 			if (pkti->privatelen == sizeof (recov_info) &&
9183 			    un->un_unit_attention_flags &&
9184 			    bp != un->un_recov_buf) {
9185 			un->un_unit_attention_flags = 0;
9186 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9187 				    "Command Recovery called on busy resend\n");
9188 				if (st_command_recovery(un, BP_PKT(bp),
9189 				    ATTEMPT_RETRY) == JUST_RETURN) {
9190 					mutex_exit(ST_MUTEX);
9191 					return;
9192 				}
9193 			}
9194 			mutex_exit(ST_MUTEX);
9195 			if (st_handle_intr_busy(un, bp,
9196 			    ST_TRAN_BUSY_TIMEOUT) == 0)
9197 				return;	/* timeout is setup again */
9198 			mutex_enter(ST_MUTEX);
9199 		}
9200 
9201 done_error:
9202 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9203 		    "restart transport rejected\n");
9204 		bp->b_resid = bp->b_bcount;
9205 
9206 		if (un->un_last_throttle) {
9207 			un->un_throttle = un->un_last_throttle;
9208 		}
9209 		if (status != TRAN_ACCEPT) {
9210 			ST_DO_ERRSTATS(un, st_transerrs);
9211 		}
9212 		ST_DO_KSTATS(bp, kstat_waitq_exit);
9213 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9214 		    "busy restart aborted\n");
9215 		st_set_pe_flag(un);
9216 		st_bioerror(bp, EIO);
9217 		st_done_and_mutex_exit(un, bp);
9218 	} else {
9219 		if (un->un_last_throttle) {
9220 			un->un_throttle = un->un_last_throttle;
9221 		}
9222 		mutex_exit(ST_MUTEX);
9223 	}
9224 }
9225 
9226 /*
9227  * st_check_media():
9228  * Periodically check the media state using scsi_watch service;
9229  * this service calls back after TUR and possibly request sense
9230  * the callback handler (st_media_watch_cb()) decodes the request sense
9231  * data (if any)
9232  */
9233 
9234 static int
9235 st_check_media(dev_t dev, enum mtio_state state)
9236 {
9237 	int rval = 0;
9238 	enum mtio_state	prev_state;
9239 	opaque_t token = NULL;
9240 
9241 	GET_SOFT_STATE(dev);
9242 
9243 	ST_FUNC(ST_DEVINFO, st_check_media);
9244 
9245 	mutex_enter(ST_MUTEX);
9246 
9247 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9248 	    "st_check_media:state=%x, mediastate=%x\n",
9249 	    state, un->un_mediastate);
9250 
9251 	prev_state = un->un_mediastate;
9252 
9253 	/*
9254 	 * is there anything to do?
9255 	 */
9256 retry:
9257 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
9258 		/*
9259 		 * submit the request to the scsi_watch service;
9260 		 * scsi_media_watch_cb() does the real work
9261 		 */
9262 		mutex_exit(ST_MUTEX);
9263 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
9264 		    st_check_media_time, SENSE_LENGTH,
9265 		    st_media_watch_cb, (caddr_t)dev);
9266 		if (token == NULL) {
9267 			rval = EAGAIN;
9268 			goto done;
9269 		}
9270 		mutex_enter(ST_MUTEX);
9271 
9272 		un->un_swr_token = token;
9273 		un->un_specified_mediastate = state;
9274 
9275 		/*
9276 		 * now wait for media change
9277 		 * we will not be signalled unless mediastate == state but it
9278 		 * still better to test for this condition, since there
9279 		 * is a 5 sec cv_broadcast delay when
9280 		 *  mediastate == MTIO_INSERTED
9281 		 */
9282 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9283 		    "st_check_media:waiting for media state change\n");
9284 		while (un->un_mediastate == state) {
9285 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
9286 				mutex_exit(ST_MUTEX);
9287 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9288 				    "st_check_media:waiting for media state "
9289 				    "was interrupted\n");
9290 				rval = EINTR;
9291 				goto done;
9292 			}
9293 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9294 			    "st_check_media:received signal, state=%x\n",
9295 			    un->un_mediastate);
9296 		}
9297 	}
9298 
9299 	/*
9300 	 * if we transitioned to MTIO_INSERTED, media has really been
9301 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
9302 	 * Reset and retry the state change.  If everything is ok, replay
9303 	 * the open() logic.
9304 	 */
9305 	if ((un->un_mediastate == MTIO_INSERTED) &&
9306 	    (un->un_state == ST_STATE_OFFLINE)) {
9307 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9308 		    "st_check_media: calling st_cmd to confirm inserted\n");
9309 
9310 		/*
9311 		 * set this early so that TUR will make it through strategy
9312 		 * without triggering a st_tape_init().  We needed it set
9313 		 * before calling st_tape_init() ourselves anyway.  If TUR
9314 		 * fails, set it back
9315 		 */
9316 		un->un_state = ST_STATE_INITIALIZING;
9317 
9318 		/*
9319 		 * If not reserved fail as getting reservation conflict
9320 		 * will make this hang forever.
9321 		 */
9322 		if ((un->un_rsvd_status &
9323 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9324 			mutex_exit(ST_MUTEX);
9325 			rval = EACCES;
9326 			goto done;
9327 		}
9328 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
9329 		if (rval == EACCES) {
9330 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9331 			    "st_check_media: TUR got Reservation Conflict\n");
9332 			mutex_exit(ST_MUTEX);
9333 			goto done;
9334 		}
9335 		if (rval) {
9336 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9337 			    "st_check_media: TUR failed, going to retry\n");
9338 			un->un_mediastate = prev_state;
9339 			un->un_state = ST_STATE_OFFLINE;
9340 			goto retry;
9341 		}
9342 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9343 		    "st_check_media: media inserted\n");
9344 
9345 		/* this also rewinds the tape */
9346 		rval = st_tape_init(un);
9347 		if (rval != 0) {
9348 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9349 			    "st_check_media : OFFLINE init failure ");
9350 			un->un_state = ST_STATE_OFFLINE;
9351 			un->un_pos.pmode = invalid;
9352 		} else {
9353 			un->un_state = ST_STATE_OPEN_PENDING_IO;
9354 		}
9355 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
9356 	    (un->un_state != ST_STATE_OFFLINE)) {
9357 		/*
9358 		 * supported devices must be rewound before ejection
9359 		 * rewind resets fileno & blkno
9360 		 */
9361 		un->un_laststate = un->un_state;
9362 		un->un_state = ST_STATE_OFFLINE;
9363 	}
9364 	mutex_exit(ST_MUTEX);
9365 done:
9366 	if (token) {
9367 		(void) scsi_watch_request_terminate(token,
9368 		    SCSI_WATCH_TERMINATE_WAIT);
9369 		mutex_enter(ST_MUTEX);
9370 		un->un_swr_token = (opaque_t)NULL;
9371 		mutex_exit(ST_MUTEX);
9372 	}
9373 
9374 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
9375 
9376 	return (rval);
9377 }
9378 
9379 /*
9380  * st_media_watch_cb() is called by scsi_watch_thread for
9381  * verifying the request sense data (if any)
9382  */
9383 static int
9384 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
9385 {
9386 	struct scsi_status *statusp = resultp->statusp;
9387 	struct scsi_extended_sense *sensep = resultp->sensep;
9388 	uchar_t actual_sense_length = resultp->actual_sense_length;
9389 	struct scsi_tape *un;
9390 	enum mtio_state state = MTIO_NONE;
9391 	int instance;
9392 	dev_t dev = (dev_t)arg;
9393 
9394 	instance = MTUNIT(dev);
9395 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
9396 		return (-1);
9397 	}
9398 
9399 	mutex_enter(ST_MUTEX);
9400 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
9401 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9402 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
9403 	    *((char *)statusp), (void *)sensep,
9404 	    actual_sense_length);
9405 
9406 
9407 	/*
9408 	 * if there was a check condition then sensep points to valid
9409 	 * sense data
9410 	 * if status was not a check condition but a reservation or busy
9411 	 * status then the new state is MTIO_NONE
9412 	 */
9413 	if (sensep) {
9414 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9415 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
9416 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
9417 
9418 		switch (un->un_dp->type) {
9419 		default:
9420 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9421 			    "st_media_watch_cb: unknown drive type %d, "
9422 			    "default to ST_TYPE_HP\n", un->un_dp->type);
9423 		/* FALLTHROUGH */
9424 
9425 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
9426 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
9427 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
9428 			if (un->un_dp->type == ST_TYPE_FUJI) {
9429 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9430 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
9431 			} else {
9432 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9433 				    "st_media_watch_cb: ST_TYPE_HP\n");
9434 			}
9435 			switch (sensep->es_key) {
9436 			case KEY_UNIT_ATTENTION:
9437 				/* not ready to ready transition */
9438 				/* hp/es_qual_code == 80 on>off>on */
9439 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
9440 				if (sensep->es_add_code == 0x28) {
9441 					state = MTIO_INSERTED;
9442 				}
9443 				break;
9444 			case KEY_NOT_READY:
9445 				/* in process, rewinding or loading */
9446 				if ((sensep->es_add_code == 0x04) &&
9447 				    (sensep->es_qual_code == 0x00)) {
9448 					state = MTIO_EJECTED;
9449 				}
9450 				break;
9451 			}
9452 			break;
9453 
9454 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
9455 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9456 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
9457 			switch (sensep->es_key) {
9458 			case KEY_UNIT_ATTENTION:
9459 				/* operator medium removal request */
9460 				if ((sensep->es_add_code == 0x5a) &&
9461 				    (sensep->es_qual_code == 0x01)) {
9462 					state = MTIO_EJECTED;
9463 				/* not ready to ready transition */
9464 				} else if ((sensep->es_add_code == 0x28) &&
9465 				    (sensep->es_qual_code == 0x00)) {
9466 					state = MTIO_INSERTED;
9467 				}
9468 				break;
9469 			case KEY_NOT_READY:
9470 				/* medium not present */
9471 				if (sensep->es_add_code == 0x3a) {
9472 					state = MTIO_EJECTED;
9473 				}
9474 				break;
9475 			}
9476 			break;
9477 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
9478 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9479 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
9480 			switch (sensep->es_key) {
9481 			case KEY_NOT_READY:
9482 				if ((sensep->es_add_code == 0x04) &&
9483 				    (sensep->es_qual_code == 0x00)) {
9484 					/* volume not mounted? */
9485 					state = MTIO_EJECTED;
9486 				} else if (sensep->es_add_code == 0x3a) {
9487 					state = MTIO_EJECTED;
9488 				}
9489 				break;
9490 			case KEY_UNIT_ATTENTION:
9491 				state = MTIO_EJECTED;
9492 				break;
9493 			}
9494 			break;
9495 
9496 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
9497 			switch (sensep->es_key) {
9498 			case KEY_UNIT_ATTENTION:
9499 				if (sensep->es_add_code == 0x28) {
9500 					state = MTIO_INSERTED;
9501 				}
9502 				break;
9503 			case KEY_NOT_READY:
9504 				if (sensep->es_add_code == 0x04) {
9505 					/* in transition but could be either */
9506 					state = un->un_specified_mediastate;
9507 				} else if ((sensep->es_add_code == 0x3a) &&
9508 				    (sensep->es_qual_code == 0x00)) {
9509 					state = MTIO_EJECTED;
9510 				}
9511 				break;
9512 			}
9513 			break;
9514 		}
9515 	} else if (*((char *)statusp) == STATUS_GOOD) {
9516 		state = MTIO_INSERTED;
9517 	}
9518 
9519 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9520 	    "st_media_watch_cb:state=%x, specified=%x\n",
9521 	    state, un->un_specified_mediastate);
9522 
9523 	/*
9524 	 * now signal the waiting thread if this is *not* the specified state;
9525 	 * delay the signal if the state is MTIO_INSERTED
9526 	 * to allow the target to recover
9527 	 */
9528 	if (state != un->un_specified_mediastate) {
9529 		un->un_mediastate = state;
9530 		if (state == MTIO_INSERTED) {
9531 			/*
9532 			 * delay the signal to give the drive a chance
9533 			 * to do what it apparently needs to do
9534 			 */
9535 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9536 			    "st_media_watch_cb:delayed cv_broadcast\n");
9537 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
9538 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
9539 		} else {
9540 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9541 			    "st_media_watch_cb:immediate cv_broadcast\n");
9542 			cv_broadcast(&un->un_state_cv);
9543 		}
9544 	}
9545 	mutex_exit(ST_MUTEX);
9546 	return (0);
9547 }
9548 
9549 /*
9550  * delayed cv_broadcast to allow for target to recover
9551  * from media insertion
9552  */
9553 static void
9554 st_delayed_cv_broadcast(void *arg)
9555 {
9556 	struct scsi_tape *un = arg;
9557 
9558 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
9559 
9560 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9561 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
9562 
9563 	mutex_enter(ST_MUTEX);
9564 	cv_broadcast(&un->un_state_cv);
9565 	mutex_exit(ST_MUTEX);
9566 }
9567 
9568 /*
9569  * restart cmd currently at the start of the waitq
9570  */
9571 static void
9572 st_start_restart(void *arg)
9573 {
9574 	struct scsi_tape *un = arg;
9575 
9576 	ST_FUNC(ST_DEVINFO, st_start_restart);
9577 
9578 	ASSERT(un != NULL);
9579 
9580 	mutex_enter(ST_MUTEX);
9581 
9582 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_tran_restart()\n");
9583 
9584 	st_start(un);
9585 
9586 	mutex_exit(ST_MUTEX);
9587 }
9588 
9589 
9590 /*
9591  * Command completion processing
9592  *
9593  */
9594 static void
9595 st_intr(struct scsi_pkt *pkt)
9596 {
9597 	recov_info *rcv = pkt->pkt_private;
9598 	struct buf *bp = rcv->cmd_bp;
9599 	struct scsi_tape *un;
9600 	errstate action = COMMAND_DONE;
9601 	clock_t	timout;
9602 	int	status;
9603 
9604 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
9605 
9606 	ST_FUNC(ST_DEVINFO, st_intr);
9607 
9608 	ASSERT(un != NULL);
9609 
9610 	mutex_enter(ST_MUTEX);
9611 
9612 	ASSERT(bp != un->un_recov_buf);
9613 
9614 	un->un_rqs_state &= ~(ST_RQS_ERROR);
9615 
9616 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
9617 
9618 	if (pkt->pkt_reason != CMD_CMPLT) {
9619 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9620 		    "Unhappy packet status reason = %s statistics = 0x%x\n",
9621 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9622 
9623 		/* If device has gone away not much else to do */
9624 		if (pkt->pkt_reason == CMD_DEV_GONE) {
9625 			action = COMMAND_DONE_ERROR;
9626 		} else if ((pkt == un->un_rqs) ||
9627 		    (un->un_state == ST_STATE_SENSING)) {
9628 			ASSERT(pkt == un->un_rqs);
9629 			ASSERT(un->un_state == ST_STATE_SENSING);
9630 			un->un_state = un->un_laststate;
9631 			rcv->cmd_bp = un->un_rqs_bp;
9632 			ST_DO_ERRSTATS(un, st_transerrs);
9633 			action = COMMAND_DONE_ERROR;
9634 		} else {
9635 			action = st_handle_incomplete(un, bp);
9636 		}
9637 	/*
9638 	 * At this point we know that the command was successfully
9639 	 * completed. Now what?
9640 	 */
9641 	} else if ((pkt == un->un_rqs) || (un->un_state == ST_STATE_SENSING)) {
9642 		/*
9643 		 * okay. We were running a REQUEST SENSE. Find
9644 		 * out what to do next.
9645 		 */
9646 		ASSERT(pkt == un->un_rqs);
9647 		ASSERT(un->un_state == ST_STATE_SENSING);
9648 		scsi_sync_pkt(pkt);
9649 		action = st_handle_sense(un, bp, &un->un_pos);
9650 		/*
9651 		 * Make rqs isn't going to be retied.
9652 		 */
9653 		if (action != QUE_BUSY_COMMAND && action != QUE_COMMAND) {
9654 			/*
9655 			 * set pkt back to original packet in case we will have
9656 			 * to requeue it
9657 			 */
9658 			pkt = BP_PKT(bp);
9659 			rcv->cmd_bp = un->un_rqs_bp;
9660 			/*
9661 			 * some actions are based on un_state, hence
9662 			 * restore the state st was in before ST_STATE_SENSING.
9663 			 */
9664 			un->un_state = un->un_laststate;
9665 		}
9666 
9667 	} else if (un->un_arq_enabled && (pkt->pkt_state & STATE_ARQ_DONE)) {
9668 		/*
9669 		 * the transport layer successfully completed an autorqsense
9670 		 */
9671 		action = st_handle_autosense(un, bp, &un->un_pos);
9672 
9673 	} else  if ((SCBP(pkt)->sts_busy) ||
9674 	    (SCBP(pkt)->sts_chk) ||
9675 	    (SCBP(pkt)->sts_vu7)) {
9676 		/*
9677 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9678 		 * to see if the status bits we're okay. If a request sense
9679 		 * is to be run, that will happen.
9680 		 */
9681 		action = st_check_error(un, pkt);
9682 	}
9683 
9684 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9685 		switch (action) {
9686 			case QUE_COMMAND:
9687 				/*
9688 				 * return cmd to head to the queue
9689 				 * since we are suspending so that
9690 				 * it gets restarted during resume
9691 				 */
9692 				st_add_to_queue(&un->un_runqf, &un->un_runql,
9693 				    un->un_runqf, bp);
9694 
9695 				action = JUST_RETURN;
9696 				break;
9697 
9698 			case QUE_SENSE:
9699 				action = COMMAND_DONE_ERROR;
9700 				break;
9701 
9702 			default:
9703 				break;
9704 		}
9705 	}
9706 
9707 	/*
9708 	 * check for undetected path failover.
9709 	 */
9710 	if (un->un_multipath) {
9711 
9712 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
9713 		int pkt_valid = 0;
9714 
9715 		if (ucmd) {
9716 			/*
9717 			 * Also copies path instance to the uscsi structure.
9718 			 */
9719 			pkt_valid = scsi_uscsi_pktfini(pkt, ucmd);
9720 
9721 			/*
9722 			 * scsi_uscsi_pktfini() zeros pkt_path_instance.
9723 			 */
9724 			pkt->pkt_path_instance = ucmd->uscsi_path_instance;
9725 		} else {
9726 			pkt_valid = scsi_pkt_allocated_correctly(pkt);
9727 		}
9728 
9729 		/*
9730 		 * If the scsi_pkt was not allocated correctly the
9731 		 * pkt_path_instance is not even there.
9732 		 */
9733 		if ((pkt_valid != 0) &&
9734 		    (un->un_last_path_instance != pkt->pkt_path_instance)) {
9735 			/*
9736 			 * Don't recover the path change if it was done
9737 			 * intentionally or if the device has not completely
9738 			 * opened yet.
9739 			 */
9740 			if (((pkt->pkt_flags & FLAG_PKT_PATH_INSTANCE) == 0) &&
9741 			    (un->un_state > ST_STATE_OPENING)) {
9742 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
9743 				    "Failover detected, action is %s\n",
9744 				    errstatenames[action]);
9745 				if (action == COMMAND_DONE) {
9746 					action = PATH_FAILED;
9747 				}
9748 			}
9749 			un->un_last_path_instance = pkt->pkt_path_instance;
9750 		}
9751 	}
9752 
9753 	/*
9754 	 * Restore old state if we were sensing.
9755 	 */
9756 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9757 		un->un_state = un->un_laststate;
9758 	}
9759 
9760 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9761 	    "st_intr: pkt=%p, bp=%p, action=%s, status=%x\n",
9762 	    (void *)pkt, (void *)bp, errstatenames[action], SCBP_C(pkt));
9763 
9764 again:
9765 	switch (action) {
9766 	case COMMAND_DONE_EACCES:
9767 		/* this is to report a reservation conflict */
9768 		st_bioerror(bp, EACCES);
9769 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9770 		    "Reservation Conflict \n");
9771 		un->un_pos.pmode = invalid;
9772 
9773 		/*FALLTHROUGH*/
9774 	case COMMAND_DONE_ERROR:
9775 		if (un->un_pos.eof < ST_EOT_PENDING &&
9776 		    un->un_state >= ST_STATE_OPEN) {
9777 			/*
9778 			 * all errors set state of the tape to 'unknown'
9779 			 * unless we're at EOT or are doing append testing.
9780 			 * If sense key was illegal request, preserve state.
9781 			 */
9782 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9783 				un->un_pos.pmode = invalid;
9784 			}
9785 		}
9786 
9787 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9788 		/*
9789 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9790 		 * make sure an error ocurrs, so make sure at least EIO is
9791 		 * returned
9792 		 */
9793 		if (geterror(bp) == 0)
9794 			st_bioerror(bp, EIO);
9795 
9796 		st_set_pe_flag(un);
9797 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9798 		    (un->un_errno == EIO)) {
9799 			un->un_rqs_state &= ~(ST_RQS_VALID);
9800 		}
9801 		break;
9802 
9803 	case COMMAND_DONE_ERROR_RECOVERED:
9804 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9805 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9806 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9807 		if (geterror(bp) == 0) {
9808 			st_bioerror(bp, EIO);
9809 		}
9810 		st_set_pe_flag(un);
9811 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9812 		    (un->un_errno == EIO)) {
9813 			un->un_rqs_state &= ~(ST_RQS_VALID);
9814 		}
9815 		/*FALLTHROUGH*/
9816 	case COMMAND_DONE:
9817 		st_set_state(un, bp);
9818 		break;
9819 
9820 	case QUE_SENSE:
9821 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9822 			goto sense_error;
9823 
9824 		if (un->un_state != ST_STATE_SENSING) {
9825 			un->un_laststate = un->un_state;
9826 			un->un_state = ST_STATE_SENSING;
9827 		}
9828 
9829 		/*
9830 		 * zero the sense data.
9831 		 */
9832 		bzero(un->un_rqs->pkt_scbp, SENSE_LENGTH);
9833 
9834 		/*
9835 		 * If this is not a retry on QUE_SENSE point to the original
9836 		 * bp of the command that got us here.
9837 		 */
9838 		if (pkt != un->un_rqs) {
9839 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp = bp;
9840 		}
9841 
9842 		if (un->un_throttle) {
9843 			un->un_last_throttle = un->un_throttle;
9844 			un->un_throttle = 0;
9845 		}
9846 
9847 		ST_CDB(ST_DEVINFO, "Queue sense CDB",
9848 		    (char *)BP_PKT(bp)->pkt_cdbp);
9849 
9850 		/*
9851 		 * never retry this, some other command will have nuked the
9852 		 * sense, anyway
9853 		 */
9854 		status = st_transport(un, un->un_rqs);
9855 
9856 		if (un->un_last_throttle) {
9857 			un->un_throttle = un->un_last_throttle;
9858 		}
9859 
9860 		if (status == TRAN_ACCEPT) {
9861 			mutex_exit(ST_MUTEX);
9862 			return;
9863 		}
9864 		if (status != TRAN_BUSY)
9865 			ST_DO_ERRSTATS(un, st_transerrs);
9866 sense_error:
9867 		un->un_pos.pmode = invalid;
9868 		st_bioerror(bp, EIO);
9869 		st_set_pe_flag(un);
9870 		break;
9871 
9872 	case QUE_BUSY_COMMAND:
9873 		/* longish timeout */
9874 		timout = ST_STATUS_BUSY_TIMEOUT;
9875 		goto que_it_up;
9876 
9877 	case QUE_COMMAND:
9878 		/* short timeout */
9879 		timout = ST_TRAN_BUSY_TIMEOUT;
9880 que_it_up:
9881 		/*
9882 		 * let st_handle_intr_busy put this bp back on waitq and make
9883 		 * checks to see if it is ok to requeue the command.
9884 		 */
9885 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9886 
9887 		/*
9888 		 * Save the throttle before setting up the timeout
9889 		 */
9890 		if (un->un_throttle) {
9891 			un->un_last_throttle = un->un_throttle;
9892 		}
9893 		mutex_exit(ST_MUTEX);
9894 		if (st_handle_intr_busy(un, bp, timout) == 0)
9895 			return;		/* timeout is setup again */
9896 
9897 		mutex_enter(ST_MUTEX);
9898 		un->un_pos.pmode = invalid;
9899 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9900 		st_bioerror(bp, EIO);
9901 		st_set_pe_flag(un);
9902 		break;
9903 
9904 	case QUE_LAST_COMMAND:
9905 
9906 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9907 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9908 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9909 			goto last_command_error;
9910 		}
9911 		mutex_exit(ST_MUTEX);
9912 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9913 			return;
9914 		mutex_enter(ST_MUTEX);
9915 last_command_error:
9916 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9917 		un->un_pos.pmode = invalid;
9918 		st_bioerror(bp, EIO);
9919 		st_set_pe_flag(un);
9920 		break;
9921 
9922 	case COMMAND_TIMEOUT:
9923 	case DEVICE_RESET:
9924 	case DEVICE_TAMPER:
9925 	case ATTEMPT_RETRY:
9926 	case PATH_FAILED:
9927 		ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9928 		    "Command Recovery called on %s status\n",
9929 		    errstatenames[action]);
9930 		action = st_command_recovery(un, pkt, action);
9931 		goto again;
9932 
9933 	default:
9934 		ASSERT(0);
9935 		/* FALLTHRU */
9936 	case JUST_RETURN:
9937 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9938 		mutex_exit(ST_MUTEX);
9939 		return;
9940 	}
9941 
9942 	ST_DO_KSTATS(bp, kstat_runq_exit);
9943 	st_done_and_mutex_exit(un, bp);
9944 }
9945 
9946 static errstate
9947 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9948 {
9949 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9950 	recov_info *rinfo;
9951 	errstate rval = COMMAND_DONE_ERROR;
9952 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9953 	    un->un_rqs : BP_PKT(bp);
9954 	int result;
9955 
9956 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9957 
9958 	rinfo = (recov_info *)pkt->pkt_private;
9959 
9960 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9961 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9962 
9963 	ASSERT(mutex_owned(ST_MUTEX));
9964 
9965 	switch (pkt->pkt_reason) {
9966 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9967 		/*
9968 		 * this occurs when accessing a powered down drive, no
9969 		 * need to complain; just fail the open
9970 		 */
9971 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9972 
9973 		/*
9974 		 * if we have commands outstanding in HBA, and a command
9975 		 * comes back incomplete, we're hosed, so reset target
9976 		 * If we have the bus, but cmd_incomplete, we probably just
9977 		 * have a failed selection, so don't reset the target, just
9978 		 * requeue the command and try again
9979 		 */
9980 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9981 			goto reset_target;
9982 		}
9983 
9984 		/*
9985 		 * Retry selection a couple more times if we're
9986 		 * open.  If opening, we only try just once to
9987 		 * reduce probe time for nonexistant devices.
9988 		 */
9989 		if ((un->un_laststate > ST_STATE_OPENING) &&
9990 		    (rinfo->pkt_retry_cnt < st_selection_retry_count)) {
9991 			/* XXX check retriable? */
9992 			rval = QUE_COMMAND;
9993 		}
9994 		ST_DO_ERRSTATS(un, st_transerrs);
9995 		break;
9996 
9997 	case CMD_ABORTED:
9998 		/*
9999 		 * most likely this is caused by flush-on-error support. If
10000 		 * it was not there, the we're in trouble.
10001 		 */
10002 		if (!un->un_flush_on_errors) {
10003 			un->un_status = SUN_KEY_FATAL;
10004 			goto reset_target;
10005 		}
10006 
10007 		st_set_pe_errno(un);
10008 		bioerror(bp, un->un_errno);
10009 		if (un->un_errno)
10010 			return (COMMAND_DONE_ERROR);
10011 		else
10012 			return (COMMAND_DONE);
10013 
10014 	case CMD_TIMEOUT:	/* Command timed out */
10015 		un->un_status = SUN_KEY_TIMEOUT;
10016 		return (COMMAND_TIMEOUT);
10017 
10018 	case CMD_TRAN_ERR:
10019 	case CMD_RESET:
10020 		if (pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET)) {
10021 			if ((un->un_rsvd_status &
10022 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
10023 			    ST_RESERVE) {
10024 				un->un_rsvd_status |= ST_LOST_RESERVE;
10025 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
10026 				    "Lost Reservation\n");
10027 			}
10028 			rval = DEVICE_RESET;
10029 			return (rval);
10030 		}
10031 		if (pkt->pkt_statistics & (STAT_ABORTED | STAT_TERMINATED)) {
10032 			rval = DEVICE_RESET;
10033 			return (rval);
10034 		}
10035 		/*FALLTHROUGH*/
10036 	default:
10037 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10038 		    "Unhandled packet status reason = %s statistics = 0x%x\n",
10039 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
10040 reset_target:
10041 
10042 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10043 		    "transport completed with %s\n",
10044 		    scsi_rname(pkt->pkt_reason));
10045 		ST_DO_ERRSTATS(un, st_transerrs);
10046 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
10047 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
10048 		    STAT_ABORTED)) == 0)) {
10049 
10050 			/*
10051 			 * If we haven't reserved the drive don't reset it.
10052 			 */
10053 			if ((un->un_rsvd_status &
10054 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
10055 				return (rval);
10056 			}
10057 
10058 			/*
10059 			 * if we aren't lost yet we will be soon.
10060 			 */
10061 			un->un_pos.pmode = invalid;
10062 
10063 			result = st_reset(un, RESET_LUN);
10064 
10065 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
10066 				/* no hope left to recover */
10067 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
10068 				    "recovery by resets failed\n");
10069 				return (rval);
10070 			}
10071 		}
10072 	}
10073 
10074 
10075 	if (rinfo->pkt_retry_cnt++ < st_retry_count) {
10076 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
10077 			rval = QUE_COMMAND;
10078 		} else if (bp == un->un_sbufp) {
10079 			if (rinfo->privatelen == sizeof (recov_info)) {
10080 				if (rinfo->cmd_attrib->retriable) {
10081 					/*
10082 					 * These commands can be rerun
10083 					 * with impunity
10084 					 */
10085 					rval = QUE_COMMAND;
10086 				}
10087 			} else {
10088 				cmd_attribute const *attrib;
10089 				attrib =
10090 				    st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10091 				if (attrib->retriable) {
10092 					rval = QUE_COMMAND;
10093 				}
10094 			}
10095 		}
10096 	} else {
10097 		rval = COMMAND_DONE_ERROR;
10098 	}
10099 
10100 	if (un->un_state >= ST_STATE_OPEN) {
10101 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10102 		    fail, scsi_rname(pkt->pkt_reason),
10103 		    (rval == COMMAND_DONE_ERROR)?
10104 		    "giving up" : "retrying command");
10105 	}
10106 	return (rval);
10107 }
10108 
10109 /*
10110  * if the device is busy, then put this bp back on the waitq, on the
10111  * interrupt thread, where we want the head of the queue and not the
10112  * end
10113  *
10114  * The callers of this routine should take measures to save the
10115  * un_throttle in un_last_throttle which will be restored in
10116  * st_intr_restart(). The only exception should be st_intr_restart()
10117  * calling this routine for which the saving is already done.
10118  */
10119 static int
10120 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
10121 	clock_t timeout_interval)
10122 {
10123 
10124 	int queued;
10125 	int rval = 0;
10126 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
10127 
10128 	mutex_enter(ST_MUTEX);
10129 
10130 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
10131 
10132 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10133 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
10134 
10135 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
10136 		queued = 1;
10137 	} else {
10138 		queued = 0;
10139 	}
10140 
10141 	/*
10142 	 * Check to see if we hit the retry timeout. We check to make sure
10143 	 * this is the first one on the runq and make sure we have not
10144 	 * queued up any more, so this one has to be the last on the list
10145 	 * also. If it is not, we have to fail.  If it is not the first, but
10146 	 * is the last we are in trouble anyway, as we are in the interrupt
10147 	 * context here.
10148 	 */
10149 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
10150 	    ((un->un_runqf != bp) && (un->un_runql != bp) && (queued))) {
10151 		rval = -1;
10152 		goto exit;
10153 	}
10154 
10155 	/* put the bp back on the waitq */
10156 	if (queued) {
10157 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
10158 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
10159 	}
10160 
10161 	/*
10162 	 * We don't want any other commands being started in the mean time.
10163 	 * If start had just released mutex after putting something on the
10164 	 * runq, we won't even get here.
10165 	 */
10166 	un->un_throttle = 0;
10167 
10168 	/*
10169 	 * send a marker pkt, if appropriate
10170 	 */
10171 	st_hba_unflush(un);
10172 
10173 	/*
10174 	 * all queues are aligned, we are just waiting to
10175 	 * transport
10176 	 */
10177 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
10178 
10179 exit:
10180 	mutex_exit(ST_MUTEX);
10181 	return (rval);
10182 }
10183 
10184 /*
10185  * To get one error entry from error stack
10186  */
10187 static int
10188 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
10189 {
10190 #ifdef _MULTI_DATAMODEL
10191 	/*
10192 	 * For use when a 32 bit app makes a call into a
10193 	 * 64 bit ioctl
10194 	 */
10195 	struct mterror_entry32 err_entry32;
10196 #endif /* _MULTI_DATAMODEL */
10197 
10198 	int rval = 0;
10199 	struct mterror_entry err_entry;
10200 	struct mterror_entry_stack *err_link_entry_p;
10201 	size_t arq_status_len_in, arq_status_len_kr;
10202 
10203 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
10204 
10205 	ASSERT(mutex_owned(ST_MUTEX));
10206 
10207 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10208 	    "st_get_error_entry()\n");
10209 
10210 	/*
10211 	 * if error record stack empty, return ENXIO
10212 	 */
10213 	if (un->un_error_entry_stk == NULL) {
10214 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10215 		    "st_get_error_entry: Error Entry Stack Empty!\n");
10216 		rval = ENXIO;
10217 		goto ret;
10218 	}
10219 
10220 	/*
10221 	 * get the top entry from stack
10222 	 */
10223 	err_link_entry_p = un->un_error_entry_stk;
10224 	arq_status_len_kr =
10225 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
10226 
10227 #ifdef _MULTI_DATAMODEL
10228 	switch (ddi_model_convert_from(flag & FMODELS)) {
10229 	case DDI_MODEL_ILP32:
10230 		if (ddi_copyin((void *)arg, &err_entry32,
10231 		    MTERROR_ENTRY_SIZE_32, flag)) {
10232 			rval = EFAULT;
10233 			goto ret;
10234 		}
10235 
10236 		arq_status_len_in =
10237 		    (size_t)err_entry32.mtee_arq_status_len;
10238 
10239 		err_entry32.mtee_cdb_len =
10240 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
10241 
10242 		if (arq_status_len_in > arq_status_len_kr)
10243 			err_entry32.mtee_arq_status_len =
10244 			    (size32_t)arq_status_len_kr;
10245 
10246 		if (ddi_copyout(
10247 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10248 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
10249 		    err_entry32.mtee_cdb_len, flag)) {
10250 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10251 			    "st_get_error_entry: Copy cdb buffer error!");
10252 			rval = EFAULT;
10253 		}
10254 
10255 		if (ddi_copyout(
10256 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10257 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
10258 		    err_entry32.mtee_arq_status_len, flag)) {
10259 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10260 			    "st_get_error_entry: copy arq status error!");
10261 			rval = EFAULT;
10262 		}
10263 
10264 		if (ddi_copyout(&err_entry32, (void *)arg,
10265 		    MTERROR_ENTRY_SIZE_32, flag)) {
10266 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10267 			    "st_get_error_entry: copy arq status out error!");
10268 			rval = EFAULT;
10269 		}
10270 		break;
10271 
10272 	case DDI_MODEL_NONE:
10273 		if (ddi_copyin((void *)arg, &err_entry,
10274 		    MTERROR_ENTRY_SIZE_64, flag)) {
10275 			rval = EFAULT;
10276 			goto ret;
10277 		}
10278 		arq_status_len_in = err_entry.mtee_arq_status_len;
10279 
10280 		err_entry.mtee_cdb_len =
10281 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
10282 
10283 		if (arq_status_len_in > arq_status_len_kr)
10284 			err_entry.mtee_arq_status_len =
10285 			    arq_status_len_kr;
10286 
10287 		if (ddi_copyout(
10288 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10289 		    err_entry.mtee_cdb_buf,
10290 		    err_entry.mtee_cdb_len, flag)) {
10291 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10292 			    "st_get_error_entry: Copy cdb buffer error!");
10293 			rval = EFAULT;
10294 		}
10295 
10296 		if (ddi_copyout(
10297 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10298 		    err_entry.mtee_arq_status,
10299 		    err_entry.mtee_arq_status_len, flag)) {
10300 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10301 			    "st_get_error_entry: copy arq status error!");
10302 			rval = EFAULT;
10303 		}
10304 
10305 		if (ddi_copyout(&err_entry, (void *)arg,
10306 		    MTERROR_ENTRY_SIZE_64, flag)) {
10307 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10308 			    "st_get_error_entry: copy arq status out error!");
10309 			rval = EFAULT;
10310 		}
10311 		break;
10312 	}
10313 #else /* _MULTI_DATAMODEL */
10314 	if (ddi_copyin((void *)arg, &err_entry,
10315 	    MTERROR_ENTRY_SIZE_64, flag)) {
10316 		rval = EFAULT;
10317 		goto ret;
10318 	}
10319 	arq_status_len_in = err_entry.mtee_arq_status_len;
10320 
10321 	err_entry.mtee_cdb_len =
10322 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
10323 
10324 	if (arq_status_len_in > arq_status_len_kr)
10325 		err_entry.mtee_arq_status_len =
10326 		    arq_status_len_kr;
10327 
10328 	if (ddi_copyout(
10329 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10330 	    err_entry.mtee_cdb_buf,
10331 	    err_entry.mtee_cdb_len, flag)) {
10332 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10333 		    "st_get_error_entry: Copy cdb buffer error!");
10334 		rval = EFAULT;
10335 	}
10336 
10337 	if (ddi_copyout(
10338 	    err_link_entry_p->mtees_entry.mtee_arq_status,
10339 	    err_entry.mtee_arq_status,
10340 	    err_entry.mtee_arq_status_len, flag)) {
10341 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10342 		    "st_get_error_entry: copy arq status buffer error!");
10343 		rval = EFAULT;
10344 	}
10345 
10346 	if (ddi_copyout(&err_entry, (void *)arg,
10347 	    MTERROR_ENTRY_SIZE_64, flag)) {
10348 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10349 		    "st_get_error_entry: copy arq status out error!");
10350 		rval = EFAULT;
10351 	}
10352 #endif /* _MULTI_DATAMODEL */
10353 
10354 	/*
10355 	 * update stack
10356 	 */
10357 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
10358 
10359 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
10360 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
10361 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
10362 
10363 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
10364 	    SECMDS_STATUS_SIZE);
10365 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
10366 
10367 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
10368 	err_link_entry_p = NULL;
10369 ret:
10370 	return (rval);
10371 }
10372 
10373 /*
10374  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
10375  * the scsi CDB command which causes the error and generates sense data and
10376  * the scsi status.
10377  *
10378  *      error-record stack
10379  *
10380  *
10381  *             TOP                                     BOTTOM
10382  *              ------------------------------------------
10383  *              |   0   |   1   |   2   |   ...  |   n   |
10384  *              ------------------------------------------
10385  *                  ^
10386  *                  |
10387  *       pointer to error entry
10388  *
10389  * when st driver generates one sense data record, it creates a error-entry
10390  * and pushes it onto the stack.
10391  *
10392  */
10393 
10394 static void
10395 st_update_error_stack(struct scsi_tape *un,
10396 			struct scsi_pkt *pkt,
10397 			struct scsi_arq_status *cmd)
10398 {
10399 	struct mterror_entry_stack *err_entry_tmp;
10400 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
10401 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
10402 
10403 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
10404 
10405 	ASSERT(mutex_owned(ST_MUTEX));
10406 
10407 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10408 	    "st_update_error_stack()\n");
10409 
10410 	ASSERT(cmd);
10411 	ASSERT(cdbp);
10412 	if (cdblen == 0) {
10413 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10414 		    "st_update_error_stack: CDB length error!\n");
10415 		return;
10416 	}
10417 
10418 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
10419 	ASSERT(err_entry_tmp != NULL);
10420 
10421 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
10422 	    kmem_alloc(cdblen, KM_SLEEP);
10423 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
10424 
10425 	err_entry_tmp->mtees_entry.mtee_arq_status =
10426 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
10427 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
10428 
10429 	/*
10430 	 * copy cdb command & length to current error entry
10431 	 */
10432 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
10433 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
10434 
10435 	/*
10436 	 * copy scsi status length to current error entry
10437 	 */
10438 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
10439 	    SECMDS_STATUS_SIZE;
10440 
10441 	/*
10442 	 * copy sense data and scsi status to current error entry
10443 	 */
10444 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
10445 	    SECMDS_STATUS_SIZE);
10446 
10447 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
10448 	un->un_error_entry_stk = err_entry_tmp;
10449 
10450 }
10451 
10452 /*
10453  * Empty all the error entry in stack
10454  */
10455 static void
10456 st_empty_error_stack(struct scsi_tape *un)
10457 {
10458 	struct mterror_entry_stack *linkp;
10459 
10460 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
10461 
10462 	ASSERT(mutex_owned(ST_MUTEX));
10463 
10464 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10465 	    "st_empty_entry_stack()\n");
10466 
10467 	while (un->un_error_entry_stk != NULL) {
10468 		linkp = un->un_error_entry_stk;
10469 		un->un_error_entry_stk =
10470 		    un->un_error_entry_stk->mtees_nextp;
10471 
10472 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
10473 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
10474 			    linkp->mtees_entry.mtee_cdb_len);
10475 
10476 		if (linkp->mtees_entry.mtee_arq_status != NULL)
10477 			kmem_free(linkp->mtees_entry.mtee_arq_status,
10478 			    linkp->mtees_entry.mtee_arq_status_len);
10479 
10480 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
10481 		linkp = NULL;
10482 	}
10483 }
10484 
10485 static errstate
10486 st_handle_sense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10487 {
10488 	struct scsi_pkt *pkt = BP_PKT(bp);
10489 	struct scsi_pkt *rqpkt = un->un_rqs;
10490 	struct scsi_arq_status arqstat;
10491 	recov_info *rcif = pkt->pkt_private;
10492 
10493 	errstate rval = COMMAND_DONE_ERROR;
10494 	int amt;
10495 
10496 	ST_FUNC(ST_DEVINFO, st_handle_sense);
10497 
10498 	ASSERT(mutex_owned(ST_MUTEX));
10499 
10500 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10501 	    "st_handle_sense()\n");
10502 
10503 	if (SCBP(rqpkt)->sts_busy) {
10504 		if (rcif->privatelen == sizeof (recov_info)) {
10505 			ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
10506 			    "Attempt recovery of busy unit on request sense\n");
10507 			rval = ATTEMPT_RETRY;
10508 		} else if (rcif->pkt_retry_cnt++ < st_retry_count) {
10509 			ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10510 			    "Retry busy unit on request sense\n");
10511 			rval = QUE_BUSY_COMMAND;
10512 		}
10513 		return (rval);
10514 	} else if (SCBP(rqpkt)->sts_chk) {
10515 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10516 		    "Check Condition on REQUEST SENSE\n");
10517 		return (rval);
10518 	}
10519 
10520 	/*
10521 	 * Make sure there is sense data to look at.
10522 	 */
10523 	if ((rqpkt->pkt_state & (STATE_GOT_BUS | STATE_GOT_TARGET |
10524 	    STATE_SENT_CMD | STATE_GOT_STATUS)) != (STATE_GOT_BUS |
10525 	    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) {
10526 		return (rval);
10527 	}
10528 
10529 	/* was there enough data? */
10530 	amt = (int)MAX_SENSE_LENGTH - rqpkt->pkt_resid;
10531 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
10532 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10533 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10534 		    "REQUEST SENSE couldn't get sense data\n");
10535 		return (rval);
10536 	}
10537 
10538 	bcopy(SCBP(pkt), &arqstat.sts_status,
10539 	    sizeof (struct scsi_status));
10540 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
10541 	    sizeof (struct scsi_status));
10542 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
10543 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
10544 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
10545 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
10546 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
10547 
10548 	/*
10549 	 * copy one arqstat entry in the sense data buffer
10550 	 */
10551 	st_update_error_stack(un, pkt, &arqstat);
10552 	return (st_decode_sense(un, bp, amt, &arqstat, pos));
10553 }
10554 
10555 static errstate
10556 st_handle_autosense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10557 {
10558 	struct scsi_pkt *pkt = BP_PKT(bp);
10559 	struct scsi_arq_status *arqstat =
10560 	    (struct scsi_arq_status *)pkt->pkt_scbp;
10561 	errstate rval = COMMAND_DONE_ERROR;
10562 	int amt;
10563 
10564 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
10565 
10566 	ASSERT(mutex_owned(ST_MUTEX));
10567 
10568 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10569 	    "st_handle_autosense()\n");
10570 
10571 	if (arqstat->sts_rqpkt_status.sts_busy) {
10572 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10573 		    "busy unit on request sense\n");
10574 		/*
10575 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
10576 		 * the disadvantage is that we do not have any delay for the
10577 		 * second retry of rqsense and we have to keep a packet around
10578 		 */
10579 		return (QUE_SENSE);
10580 
10581 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
10582 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10583 		    "transport error on REQUEST SENSE\n");
10584 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
10585 		    ((arqstat->sts_rqpkt_statistics &
10586 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
10587 			if (st_reset(un, RESET_LUN) == 0) {
10588 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10589 				    "recovery by resets failed\n");
10590 			}
10591 		}
10592 		return (rval);
10593 
10594 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
10595 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10596 		    "Check Condition on REQUEST SENSE\n");
10597 		return (rval);
10598 	}
10599 
10600 
10601 	/* was there enough data? */
10602 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10603 		amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10604 	} else {
10605 		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
10606 			amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10607 		} else {
10608 			amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10609 		}
10610 	}
10611 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
10612 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10613 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10614 		    "REQUEST SENSE couldn't get sense data\n");
10615 		return (rval);
10616 	}
10617 
10618 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10619 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, MAX_SENSE_LENGTH);
10620 	} else {
10621 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
10622 	}
10623 
10624 	/*
10625 	 * copy one arqstat entry in the sense data buffer
10626 	 */
10627 	st_update_error_stack(un, pkt, arqstat);
10628 
10629 	return (st_decode_sense(un, bp, amt, arqstat, pos));
10630 }
10631 
10632 static errstate
10633 st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
10634     struct scsi_arq_status *statusp, tapepos_t *pos)
10635 {
10636 	struct scsi_pkt *pkt = BP_PKT(bp);
10637 	recov_info *ri = pkt->pkt_private;
10638 	errstate rval = COMMAND_DONE_ERROR;
10639 	cmd_attribute const *attrib;
10640 	long resid;
10641 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10642 	int severity;
10643 	int get_error;
10644 
10645 	ST_FUNC(ST_DEVINFO, st_decode_sense);
10646 
10647 	ASSERT(mutex_owned(ST_MUTEX));
10648 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10649 	    "st_decode_sense()\n");
10650 
10651 	/*
10652 	 * For uscsi commands, squirrel away a copy of the
10653 	 * results of the Request Sense.
10654 	 */
10655 	if (USCSI_CMD(bp)) {
10656 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
10657 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
10658 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
10659 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
10660 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
10661 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
10662 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10663 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
10664 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
10665 		}
10666 	}
10667 
10668 	if (ri->privatelen == sizeof (recov_info)) {
10669 		attrib = ri->cmd_attrib;
10670 	} else {
10671 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10672 	}
10673 
10674 	/*
10675 	 * If the drive is an MT-02, reposition the
10676 	 * secondary error code into the proper place.
10677 	 *
10678 	 * XXX	MT-02 is non-CCS tape, so secondary error code
10679 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
10680 	 * so it's in byte 12.
10681 	 */
10682 	if (un->un_dp->type == ST_TYPE_EMULEX) {
10683 		sensep->es_code = sensep->es_add_info[0];
10684 	}
10685 
10686 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
10687 	    (caddr_t)&CDBP(pkt)->scc_cmd);
10688 
10689 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)statusp,
10690 	    sizeof (*statusp));
10691 
10692 	/* for normal I/O check extract the resid values. */
10693 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
10694 		if (sensep->es_valid) {
10695 			resid =
10696 			    (sensep->es_info_1 << 24) |
10697 			    (sensep->es_info_2 << 16) |
10698 			    (sensep->es_info_3 << 8)  |
10699 			    (sensep->es_info_4);
10700 			/* If fixed block */
10701 			if (un->un_bsize) {
10702 				resid *= un->un_bsize;
10703 			}
10704 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
10705 			resid = pkt->pkt_resid;
10706 		} else {
10707 			resid = bp->b_bcount;
10708 		}
10709 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10710 		    "st_decode_sense (rw): xferred bit = %d, resid=%ld (%d), "
10711 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
10712 		    resid,
10713 		    (sensep->es_info_1 << 24) |
10714 		    (sensep->es_info_2 << 16) |
10715 		    (sensep->es_info_3 << 8)  |
10716 		    (sensep->es_info_4),
10717 		    pkt->pkt_resid);
10718 		/*
10719 		 * The problem is, what should we believe?
10720 		 */
10721 		if (resid && (pkt->pkt_resid == 0)) {
10722 			pkt->pkt_resid = resid;
10723 		}
10724 	} else {
10725 		/*
10726 		 * If the command is SCMD_SPACE, we need to get the
10727 		 * residual as returned in the sense data, to adjust
10728 		 * our idea of current tape position correctly
10729 		 */
10730 		if ((sensep->es_valid) &&
10731 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10732 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10733 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
10734 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE_G4) ||
10735 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK)) {
10736 			resid =
10737 			    (sensep->es_info_1 << 24) |
10738 			    (sensep->es_info_2 << 16) |
10739 			    (sensep->es_info_3 << 8)  |
10740 			    (sensep->es_info_4);
10741 			bp->b_resid = resid;
10742 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10743 			    "st_decode_sense(other):	resid=%ld\n", resid);
10744 		} else {
10745 			/*
10746 			 * If the special command is SCMD_READ,
10747 			 * the correct resid will be set later.
10748 			 */
10749 			if (attrib->get_cnt != NULL) {
10750 				resid = attrib->get_cnt(pkt->pkt_cdbp);
10751 			} else {
10752 				resid = bp->b_bcount;
10753 			}
10754 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10755 			    "st_decode_sense(special read):  resid=%ld\n",
10756 			    resid);
10757 		}
10758 	}
10759 
10760 	if ((un->un_state >= ST_STATE_OPEN) &&
10761 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
10762 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
10763 		    "Failed CDB", (char *)pkt->pkt_cdbp);
10764 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10765 		    "sense data", (char *)sensep, amt);
10766 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10767 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10768 		    bp->b_bcount, resid, pkt->pkt_resid);
10769 	}
10770 
10771 	switch (un->un_status = sensep->es_key) {
10772 	case KEY_NO_SENSE:
10773 		severity = SCSI_ERR_INFO;
10774 
10775 		/*
10776 		 * Erase, locate or rewind operation in progress, retry
10777 		 * ASC  ASCQ
10778 		 *  00   18    Erase operation in progress
10779 		 *  00   19    Locate operation in progress
10780 		 *  00   1A    Rewind operation in progress
10781 		 */
10782 		if (sensep->es_add_code == 0 &&
10783 		    ((sensep->es_qual_code == 0x18) ||
10784 		    (sensep->es_qual_code == 0x19) ||
10785 		    (sensep->es_qual_code == 0x1a))) {
10786 			rval = QUE_BUSY_COMMAND;
10787 			break;
10788 		}
10789 
10790 		goto common;
10791 
10792 	case KEY_RECOVERABLE_ERROR:
10793 		severity = SCSI_ERR_RECOVERED;
10794 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10795 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10796 			if (un->un_dp->options &
10797 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10798 				rval = QUE_LAST_COMMAND;
10799 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10800 				    severity, pos->lgclblkno,
10801 				    un->un_err_pos.lgclblkno, scsi_cmds,
10802 				    sensep);
10803 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10804 				    "Command will be retried\n");
10805 			} else {
10806 				severity = SCSI_ERR_FATAL;
10807 				rval = COMMAND_DONE_ERROR_RECOVERED;
10808 				ST_DO_ERRSTATS(un, st_softerrs);
10809 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10810 				    severity, pos->lgclblkno,
10811 				    un->un_err_pos.lgclblkno, scsi_cmds,
10812 				    sensep);
10813 			}
10814 			break;
10815 		}
10816 common:
10817 		/*
10818 		 * XXX only want reads to be stopped by filemarks.
10819 		 * Don't want them to be stopped by EOT.  EOT matters
10820 		 * only on write.
10821 		 */
10822 		if (sensep->es_filmk && !sensep->es_eom) {
10823 			rval = COMMAND_DONE;
10824 		} else if (sensep->es_eom) {
10825 			rval = COMMAND_DONE;
10826 		} else if (sensep->es_ili) {
10827 			/*
10828 			 * Fun with variable length record devices:
10829 			 * for specifying larger blocks sizes than the
10830 			 * actual physical record size.
10831 			 */
10832 			if (un->un_bsize == 0 && resid > 0) {
10833 				/*
10834 				 * XXX! Ugly.
10835 				 * The requested blocksize is > tape blocksize,
10836 				 * so this is ok, so we just return the
10837 				 * actual size xferred.
10838 				 */
10839 				pkt->pkt_resid = resid;
10840 				rval = COMMAND_DONE;
10841 			} else if (un->un_bsize == 0 && resid < 0) {
10842 				/*
10843 				 * The requested blocksize is < tape blocksize,
10844 				 * so this is not ok, so we err with ENOMEM
10845 				 */
10846 				rval = COMMAND_DONE_ERROR_RECOVERED;
10847 				st_bioerror(bp, ENOMEM);
10848 			} else {
10849 				ST_DO_ERRSTATS(un, st_softerrs);
10850 				severity = SCSI_ERR_FATAL;
10851 				rval = COMMAND_DONE_ERROR;
10852 				st_bioerror(bp, EINVAL);
10853 				un->un_running.pmode = invalid;
10854 			}
10855 		} else {
10856 			/*
10857 			 * we hope and pray for this just being
10858 			 * something we can ignore (ie. a
10859 			 * truly recoverable soft error)
10860 			 */
10861 			rval = COMMAND_DONE;
10862 		}
10863 		if (sensep->es_filmk) {
10864 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10865 			    "filemark\n");
10866 			un->un_status = SUN_KEY_EOF;
10867 			pos->eof = ST_EOF_PENDING;
10868 			st_set_pe_flag(un);
10869 		}
10870 
10871 		/*
10872 		 * ignore eom when reading, a fmk should terminate reading
10873 		 */
10874 		if ((sensep->es_eom) &&
10875 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10876 			if ((sensep->es_add_code == 0) &&
10877 			    (sensep->es_qual_code == 4)) {
10878 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10879 				    "bot\n");
10880 				un->un_status = SUN_KEY_BOT;
10881 				pos->eof = ST_NO_EOF;
10882 				pos->lgclblkno = 0;
10883 				pos->fileno = 0;
10884 				pos->blkno = 0;
10885 				if (pos->pmode != legacy)
10886 					pos->pmode = legacy;
10887 			} else {
10888 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10889 				    "eom\n");
10890 				un->un_status = SUN_KEY_EOT;
10891 				pos->eof = ST_EOM;
10892 			}
10893 			st_set_pe_flag(un);
10894 		}
10895 
10896 		break;
10897 
10898 	case KEY_ILLEGAL_REQUEST:
10899 
10900 		if (un->un_laststate >= ST_STATE_OPEN) {
10901 			ST_DO_ERRSTATS(un, st_softerrs);
10902 			severity = SCSI_ERR_FATAL;
10903 		} else {
10904 			severity = SCSI_ERR_INFO;
10905 		}
10906 		break;
10907 
10908 	case KEY_MEDIUM_ERROR:
10909 		ST_DO_ERRSTATS(un, st_harderrs);
10910 		severity = SCSI_ERR_FATAL;
10911 		un->un_pos.pmode = invalid;
10912 		un->un_running.pmode = invalid;
10913 check_keys:
10914 		/*
10915 		 * attempt to process the keys in the presence of
10916 		 * other errors
10917 		 */
10918 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10919 			/*
10920 			 * Fun with variable length record devices:
10921 			 * for specifying larger blocks sizes than the
10922 			 * actual physical record size.
10923 			 */
10924 			if (un->un_bsize == 0 && resid > 0) {
10925 				/*
10926 				 * XXX! Ugly
10927 				 */
10928 				pkt->pkt_resid = resid;
10929 			} else if (un->un_bsize == 0 && resid < 0) {
10930 				st_bioerror(bp, EINVAL);
10931 			} else {
10932 				severity = SCSI_ERR_FATAL;
10933 				rval = COMMAND_DONE_ERROR;
10934 				st_bioerror(bp, EINVAL);
10935 			}
10936 		}
10937 		if (sensep->es_filmk) {
10938 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10939 			    "filemark\n");
10940 			un->un_status = SUN_KEY_EOF;
10941 			pos->eof = ST_EOF_PENDING;
10942 			st_set_pe_flag(un);
10943 		}
10944 
10945 		/*
10946 		 * ignore eom when reading, a fmk should terminate reading
10947 		 */
10948 		if ((sensep->es_eom) &&
10949 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10950 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10951 			un->un_status = SUN_KEY_EOT;
10952 			pos->eof = ST_EOM;
10953 			st_set_pe_flag(un);
10954 		}
10955 
10956 		break;
10957 
10958 	case KEY_VOLUME_OVERFLOW:
10959 		ST_DO_ERRSTATS(un, st_softerrs);
10960 		pos->eof = ST_EOM;
10961 		severity = SCSI_ERR_FATAL;
10962 		rval = COMMAND_DONE_ERROR;
10963 		goto check_keys;
10964 
10965 	case KEY_HARDWARE_ERROR:
10966 		ST_DO_ERRSTATS(un, st_harderrs);
10967 		severity = SCSI_ERR_FATAL;
10968 		rval = COMMAND_DONE_ERROR;
10969 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10970 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10971 		break;
10972 
10973 	case KEY_BLANK_CHECK:
10974 		ST_DO_ERRSTATS(un, st_softerrs);
10975 		severity = SCSI_ERR_INFO;
10976 
10977 		/*
10978 		 * if not a special request and some data was xferred then it
10979 		 * it is not an error yet
10980 		 */
10981 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10982 			/*
10983 			 * no error for read with or without data xferred
10984 			 */
10985 			un->un_status = SUN_KEY_EOT;
10986 			pos->eof = ST_EOT;
10987 			rval = COMMAND_DONE_ERROR;
10988 			un->un_running.pmode = invalid;
10989 			st_set_pe_flag(un);
10990 			goto check_keys;
10991 		} else if (bp != un->un_sbufp &&
10992 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10993 			rval = COMMAND_DONE;
10994 		} else {
10995 			rval = COMMAND_DONE_ERROR_RECOVERED;
10996 		}
10997 
10998 		if (un->un_laststate >= ST_STATE_OPEN) {
10999 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11000 			    "blank check\n");
11001 			pos->eof = ST_EOM;
11002 		}
11003 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
11004 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
11005 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
11006 		    (un->un_dp->options & ST_KNOWS_EOD)) {
11007 			/*
11008 			 * we were doing a fast forward by skipping
11009 			 * multiple fmk at the time
11010 			 */
11011 			st_bioerror(bp, EIO);
11012 			severity = SCSI_ERR_RECOVERED;
11013 			rval	 = COMMAND_DONE;
11014 		}
11015 		st_set_pe_flag(un);
11016 		goto check_keys;
11017 
11018 	case KEY_WRITE_PROTECT:
11019 		if (st_wrongtapetype(un)) {
11020 			un->un_status = SUN_KEY_WRONGMEDIA;
11021 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11022 			    "wrong tape for writing- use DC6150 tape "
11023 			    "(or equivalent)\n");
11024 			severity = SCSI_ERR_UNKNOWN;
11025 		} else {
11026 			severity = SCSI_ERR_FATAL;
11027 		}
11028 		ST_DO_ERRSTATS(un, st_harderrs);
11029 		rval = COMMAND_DONE_ERROR;
11030 		st_bioerror(bp, EACCES);
11031 		break;
11032 
11033 	case KEY_UNIT_ATTENTION:
11034 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11035 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
11036 
11037 		un->un_unit_attention_flags |= 1;
11038 		/*
11039 		 * If we have detected a Bus Reset and the tape
11040 		 * drive has been reserved.
11041 		 */
11042 		if (ST_RQSENSE->es_add_code == 0x29) {
11043 			rval = DEVICE_RESET;
11044 			if ((un->un_rsvd_status &
11045 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
11046 			    ST_RESERVE) {
11047 				un->un_rsvd_status |= ST_LOST_RESERVE;
11048 				ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
11049 				    "st_decode_sense: Lost Reservation\n");
11050 			}
11051 		}
11052 
11053 		/*
11054 		 * If this is a recovery command and retrable, retry.
11055 		 */
11056 		if (bp == un->un_recov_buf) {
11057 			severity = SCSI_ERR_INFO;
11058 			if (attrib->retriable &&
11059 			    ri->pkt_retry_cnt++ < st_retry_count) {
11060 				rval = QUE_COMMAND;
11061 			} else {
11062 				rval = COMMAND_DONE_ERROR;
11063 			}
11064 			break; /* Don't set position invalid */
11065 		}
11066 
11067 		/*
11068 		 * If ST_APPLICATION_RESERVATIONS is set,
11069 		 * If the asc/ascq indicates that the reservation
11070 		 * has been cleared just allow the write to continue
11071 		 * which would force a scsi 2 reserve.
11072 		 * If preempted that persistent reservation
11073 		 * the scsi 2 reserve would get a reservation conflict.
11074 		 */
11075 		if ((un->un_rsvd_status &
11076 		    ST_APPLICATION_RESERVATIONS) != 0) {
11077 			/*
11078 			 * RESERVATIONS PREEMPTED
11079 			 * With MPxIO this could be a fail over? XXX
11080 			 */
11081 			if (ST_RQSENSE->es_add_code == 0x2a &&
11082 			    ST_RQSENSE->es_qual_code == 0x03) {
11083 				severity = SCSI_ERR_INFO;
11084 				rval = COMMAND_DONE_ERROR;
11085 				pos->pmode = invalid;
11086 				break;
11087 			/*
11088 			 * RESERVATIONS RELEASED
11089 			 */
11090 			} else if (ST_RQSENSE->es_add_code == 0x2a &&
11091 			    ST_RQSENSE->es_qual_code == 0x04) {
11092 				severity = SCSI_ERR_INFO;
11093 				rval = COMMAND_DONE;
11094 				break;
11095 			}
11096 		}
11097 
11098 		if (un->un_state <= ST_STATE_OPENING) {
11099 			/*
11100 			 * Look, the tape isn't open yet, now determine
11101 			 * if the cause is a BUS RESET, Save the file
11102 			 * and Block positions for the callers to
11103 			 * recover from the loss of position.
11104 			 */
11105 			severity = SCSI_ERR_INFO;
11106 			if ((pos->pmode != invalid) &&
11107 			    (rval == DEVICE_RESET) &&
11108 			    (un->un_restore_pos != 1)) {
11109 				un->un_save_fileno = pos->fileno;
11110 				un->un_save_blkno = pos->blkno;
11111 				un->un_restore_pos = 1;
11112 			}
11113 
11114 			if (attrib->retriable &&
11115 			    ri->pkt_retry_cnt++ < st_retry_count) {
11116 				rval = QUE_COMMAND;
11117 			} else if (rval == DEVICE_RESET) {
11118 				break;
11119 			} else {
11120 				rval = COMMAND_DONE_ERROR;
11121 			}
11122 		/*
11123 		 * Means it thinks the mode parameters have changed.
11124 		 * This is the result of a reset clearing settings or
11125 		 * another initiator changing what we set.
11126 		 */
11127 		}
11128 		if (ST_RQSENSE->es_add_code == 0x2a) {
11129 			if (ST_RQSENSE->es_qual_code == 0x1) {
11130 				/* Error recovery will modeselect and retry. */
11131 				rval = DEVICE_TAMPER;
11132 				severity = SCSI_ERR_INFO;
11133 				break; /* don't set position invalid */
11134 			}
11135 			if (ST_RQSENSE->es_qual_code == 0x0 ||
11136 			    ST_RQSENSE->es_qual_code == 0x2 ||
11137 			    ST_RQSENSE->es_qual_code == 0x3 ||
11138 			    ST_RQSENSE->es_qual_code == 0x4 ||
11139 			    ST_RQSENSE->es_qual_code == 0x5 ||
11140 			    ST_RQSENSE->es_qual_code == 0x6 ||
11141 			    ST_RQSENSE->es_qual_code == 0x7) {
11142 				rval = DEVICE_TAMPER;
11143 				severity = SCSI_ERR_INFO;
11144 			}
11145 		} else if (ST_RQSENSE->es_add_code == 0x28 &&
11146 		    ((ST_RQSENSE->es_qual_code == 0x0) ||
11147 		    ST_RQSENSE->es_qual_code == 0x5)) {
11148 			/*
11149 			 * Not Ready to Ready change, Media may have changed.
11150 			 */
11151 			rval = DEVICE_TAMPER;
11152 			severity = SCSI_ERR_RETRYABLE;
11153 		} else {
11154 			if (rval != DEVICE_RESET) {
11155 				rval = COMMAND_DONE_ERROR;
11156 			} else {
11157 				/*
11158 				 * Returning DEVICE_RESET will call
11159 				 * error recovery.
11160 				 */
11161 				severity = SCSI_ERR_INFO;
11162 				break; /* don't set position invalid */
11163 			}
11164 			/*
11165 			 * Check if it is an Unexpected Unit Attention.
11166 			 * If state is >= ST_STATE_OPEN, we have
11167 			 * already done the initialization .
11168 			 * In this case it is Fatal Error
11169 			 * since no further reading/writing
11170 			 * can be done with fileno set to < 0.
11171 			 */
11172 			if (un->un_state >= ST_STATE_OPEN) {
11173 				ST_DO_ERRSTATS(un, st_harderrs);
11174 				severity = SCSI_ERR_FATAL;
11175 			} else {
11176 				severity = SCSI_ERR_INFO;
11177 			}
11178 		}
11179 
11180 		pos->pmode = invalid;
11181 
11182 		break;
11183 
11184 	case KEY_NOT_READY:
11185 		/*
11186 		 * If in process of getting ready retry.
11187 		 */
11188 		if (sensep->es_add_code == 0x04) {
11189 			switch (sensep->es_qual_code) {
11190 			case 0x07:
11191 				/*
11192 				 * We get here when the tape is rewinding.
11193 				 * QUE_BUSY_COMMAND retries every 10 seconds.
11194 				 */
11195 				if (ri->pkt_retry_cnt++ <
11196 				    (un->un_dp->rewind_timeout / 10)) {
11197 					rval = QUE_BUSY_COMMAND;
11198 					severity = SCSI_ERR_INFO;
11199 				} else {
11200 					/* give up */
11201 					rval = COMMAND_DONE_ERROR;
11202 					severity = SCSI_ERR_FATAL;
11203 				}
11204 				break;
11205 			case 0x01:
11206 				if (ri->pkt_retry_cnt++ < st_retry_count) {
11207 					rval = QUE_COMMAND;
11208 					severity = SCSI_ERR_INFO;
11209 					break;
11210 				}
11211 			default: /* FALLTHRU */
11212 				/* give up */
11213 				rval = COMMAND_DONE_ERROR;
11214 				severity = SCSI_ERR_FATAL;
11215 			}
11216 		} else {
11217 			/* give up */
11218 			rval = COMMAND_DONE_ERROR;
11219 			severity = SCSI_ERR_FATAL;
11220 		}
11221 
11222 		/*
11223 		 * If this was an error and after device opened
11224 		 * do error stats.
11225 		 */
11226 		if (rval == COMMAND_DONE_ERROR &&
11227 		    un->un_state > ST_STATE_OPENING) {
11228 			ST_DO_ERRSTATS(un, st_harderrs);
11229 		}
11230 
11231 		if (ST_RQSENSE->es_add_code == 0x3a) {
11232 			if (st_error_level >= SCSI_ERR_FATAL)
11233 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11234 				    "Tape not inserted in drive\n");
11235 			un->un_mediastate = MTIO_EJECTED;
11236 			cv_broadcast(&un->un_state_cv);
11237 		}
11238 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
11239 		    (rval != QUE_COMMAND))
11240 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
11241 		break;
11242 
11243 	case KEY_ABORTED_COMMAND:
11244 		/* XXX Do drives return this when they see a lost light? */
11245 		/* Testing would say yes */
11246 
11247 		if (ri->pkt_retry_cnt++ < st_retry_count) {
11248 			rval = ATTEMPT_RETRY;
11249 			severity = SCSI_ERR_RETRYABLE;
11250 			goto check_keys;
11251 		}
11252 		/*
11253 		 * Probably a parity error...
11254 		 * if we retry here then this may cause data to be
11255 		 * written twice or data skipped during reading
11256 		 */
11257 		ST_DO_ERRSTATS(un, st_harderrs);
11258 		severity = SCSI_ERR_FATAL;
11259 		rval = COMMAND_DONE_ERROR;
11260 		goto check_keys;
11261 
11262 	default:
11263 		/*
11264 		 * Undecoded sense key.	 Try retries and hope
11265 		 * that will fix the problem.  Otherwise, we're
11266 		 * dead.
11267 		 */
11268 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11269 		    "Unhandled Sense Key '%s'\n",
11270 		    sense_keys[un->un_status]);
11271 		ST_DO_ERRSTATS(un, st_harderrs);
11272 		severity = SCSI_ERR_FATAL;
11273 		rval = COMMAND_DONE_ERROR;
11274 		goto check_keys;
11275 	}
11276 
11277 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
11278 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
11279 	    (un->un_laststate > ST_STATE_OPENING) &&
11280 	    (severity >= st_error_level))) {
11281 
11282 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
11283 		    pos->lgclblkno, un->un_err_pos.lgclblkno,
11284 		    scsi_cmds, sensep);
11285 		if (sensep->es_filmk) {
11286 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11287 			    "File Mark Detected\n");
11288 		}
11289 		if (sensep->es_eom) {
11290 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11291 			    "End-of-Media Detected\n");
11292 		}
11293 		if (sensep->es_ili) {
11294 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11295 			    "Incorrect Length Indicator Set\n");
11296 		}
11297 	}
11298 	get_error = geterror(bp);
11299 	if (((rval == COMMAND_DONE_ERROR) ||
11300 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
11301 	    ((get_error == EIO) || (get_error == 0))) {
11302 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
11303 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
11304 		if (un->un_rqs_state & ST_RQS_READ) {
11305 			un->un_rqs_state &= ~(ST_RQS_READ);
11306 		} else {
11307 			un->un_rqs_state |= ST_RQS_OVR;
11308 		}
11309 	}
11310 
11311 	return (rval);
11312 }
11313 
11314 
11315 static int
11316 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
11317 {
11318 	int status = TRAN_ACCEPT;
11319 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
11320 
11321 	mutex_enter(ST_MUTEX);
11322 
11323 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
11324 
11325 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11326 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
11327 
11328 	/*
11329 	 * Check to see if we hit the retry timeout. We check to make sure
11330 	 * this is the first one on the runq and make sure we have not
11331 	 * queued up any more, so this one has to be the last on the list
11332 	 * also. If it is not, we have to fail.  If it is not the first, but
11333 	 * is the last we are in trouble anyway, as we are in the interrupt
11334 	 * context here.
11335 	 */
11336 	if ((pktinfo->pkt_retry_cnt > st_retry_count) ||
11337 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
11338 		goto exit;
11339 	}
11340 
11341 	if (un->un_throttle) {
11342 		un->un_last_throttle = un->un_throttle;
11343 		un->un_throttle = 0;
11344 	}
11345 
11346 	/*
11347 	 * Here we know : bp is the first and last one on the runq
11348 	 * it is not necessary to put it back on the head of the
11349 	 * waitq and then move from waitq to runq. Save this queuing
11350 	 * and call scsi_transport.
11351 	 */
11352 	ST_CDB(ST_DEVINFO, "Retry lcmd CDB", (char *)BP_PKT(bp)->pkt_cdbp);
11353 
11354 	status = st_transport(un, BP_PKT(bp));
11355 
11356 	if (status == TRAN_ACCEPT) {
11357 		if (un->un_last_throttle) {
11358 			un->un_throttle = un->un_last_throttle;
11359 		}
11360 		mutex_exit(ST_MUTEX);
11361 
11362 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11363 		    "restart transport \n");
11364 		return (0);
11365 	}
11366 
11367 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
11368 	mutex_exit(ST_MUTEX);
11369 
11370 	if (status == TRAN_BUSY) {
11371 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
11372 			return (0);
11373 		}
11374 	}
11375 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11376 	    "restart transport rejected\n");
11377 	mutex_enter(ST_MUTEX);
11378 	ST_DO_ERRSTATS(un, st_transerrs);
11379 	if (un->un_last_throttle) {
11380 		un->un_throttle = un->un_last_throttle;
11381 	}
11382 exit:
11383 	mutex_exit(ST_MUTEX);
11384 	return (-1);
11385 }
11386 
11387 static int
11388 st_wrongtapetype(struct scsi_tape *un)
11389 {
11390 
11391 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
11392 
11393 	ASSERT(mutex_owned(ST_MUTEX));
11394 
11395 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
11396 
11397 	/*
11398 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
11399 	 */
11400 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
11401 		switch (un->un_dp->type) {
11402 		case ST_TYPE_WANGTEK:
11403 		case ST_TYPE_ARCHIVE:
11404 			/*
11405 			 * If this really worked, we could go off of
11406 			 * the density codes set in the modesense
11407 			 * page. For this drive, 0x10 == QIC-120,
11408 			 * 0xf == QIC-150, and 0x5 should be for
11409 			 * both QIC-24 and, maybe, QIC-11. However,
11410 			 * the h/w doesn't do what the manual says
11411 			 * that it should, so we'll key off of
11412 			 * getting a WRITE PROTECT error AND wp *not*
11413 			 * set in the mode sense information.
11414 			 */
11415 			/*
11416 			 * XXX but we already know that status is
11417 			 * write protect, so don't check it again.
11418 			 */
11419 
11420 			if (un->un_status == KEY_WRITE_PROTECT &&
11421 			    un->un_mspl->wp == 0) {
11422 				return (1);
11423 			}
11424 			break;
11425 		default:
11426 			break;
11427 		}
11428 	}
11429 	return (0);
11430 }
11431 
11432 static errstate
11433 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
11434 {
11435 	errstate action;
11436 	recov_info *rcvi = pkt->pkt_private;
11437 	buf_t *bp = rcvi->cmd_bp;
11438 	struct scsi_arq_status *stat = (struct scsi_arq_status *)pkt->pkt_scbp;
11439 
11440 	ST_FUNC(ST_DEVINFO, st_check_error);
11441 
11442 	ASSERT(mutex_owned(ST_MUTEX));
11443 
11444 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
11445 
11446 	switch (SCBP_C(pkt)) {
11447 	case STATUS_RESERVATION_CONFLICT:
11448 		/*
11449 		 * Command recovery is enabled, not just opening,
11450 		 * we had the drive reserved and we thing its ours.
11451 		 * Call recovery to attempt to take it back.
11452 		 */
11453 		if ((rcvi->privatelen == sizeof (recov_info)) &&
11454 		    (bp != un->un_recov_buf) &&
11455 		    (un->un_state > ST_STATE_OPEN_PENDING_IO) &&
11456 		    ((un->un_rsvd_status & (ST_RESERVE |
11457 		    ST_APPLICATION_RESERVATIONS)) != 0)) {
11458 			action = ATTEMPT_RETRY;
11459 			un->un_rsvd_status |= ST_LOST_RESERVE;
11460 		} else {
11461 			action = COMMAND_DONE_EACCES;
11462 			un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
11463 		}
11464 		break;
11465 
11466 	case STATUS_BUSY:
11467 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
11468 		if (rcvi->privatelen == sizeof (recov_info) &&
11469 		    un->un_multipath && (pkt->pkt_state == (STATE_GOT_BUS |
11470 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS))) {
11471 			/*
11472 			 * Status returned by scsi_vhci indicating path
11473 			 * has failed over.
11474 			 */
11475 			action = PATH_FAILED;
11476 			break;
11477 		}
11478 		/* FALLTHRU */
11479 	case STATUS_QFULL:
11480 		if (rcvi->privatelen == sizeof (recov_info)) {
11481 			/*
11482 			 * If recovery is inabled use it instead of
11483 			 * blind reties.
11484 			 */
11485 			action = ATTEMPT_RETRY;
11486 		} else if (rcvi->pkt_retry_cnt++ < st_retry_count) {
11487 			action = QUE_BUSY_COMMAND;
11488 		} else if ((un->un_rsvd_status &
11489 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
11490 			/*
11491 			 * If this is a command done before reserve is done
11492 			 * don't reset.
11493 			 */
11494 			action = COMMAND_DONE_ERROR;
11495 		} else {
11496 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11497 			    "unit busy too long\n");
11498 			(void) st_reset(un, RESET_ALL);
11499 			action = COMMAND_DONE_ERROR;
11500 		}
11501 		break;
11502 
11503 	case STATUS_CHECK:
11504 	case STATUS_TERMINATED:
11505 		/*
11506 		 * we should only get here if the auto rqsense failed
11507 		 * thru a uscsi cmd without autorequest sense
11508 		 * so we just try again
11509 		 */
11510 		if (un->un_arq_enabled &&
11511 		    stat->sts_rqpkt_reason == CMD_CMPLT &&
11512 		    (stat->sts_rqpkt_state & (STATE_GOT_BUS |
11513 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) ==
11514 		    (STATE_GOT_BUS | STATE_GOT_TARGET | STATE_SENT_CMD |
11515 		    STATE_GOT_STATUS)) {
11516 
11517 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11518 			    "Really got sense data\n");
11519 			action = st_decode_sense(un, bp, MAX_SENSE_LENGTH -
11520 			    pkt->pkt_resid, stat, &un->un_pos);
11521 		} else {
11522 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11523 			    "Trying to queue sense command\n");
11524 			action = QUE_SENSE;
11525 		}
11526 		break;
11527 
11528 	case STATUS_TASK_ABORT:
11529 		/*
11530 		 * This is an aborted task. This can be a reset on the other
11531 		 * port of a multiport drive. Lets try and recover it.
11532 		 */
11533 		action = DEVICE_RESET;
11534 		break;
11535 
11536 	default:
11537 		action = COMMAND_DONE;
11538 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
11539 		    "Unexpected scsi status byte 0x%x\n", SCBP_C(pkt));
11540 	}
11541 	return (action);
11542 }
11543 
11544 static void
11545 st_calc_bnum(struct scsi_tape *un, struct buf *bp, struct scsi_pkt *pkt)
11546 {
11547 	int nblks;
11548 	int nfiles;
11549 	long count;
11550 	recov_info *ri = pkt->pkt_private;
11551 	cmd_attribute const *attrib;
11552 
11553 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
11554 
11555 	ASSERT(mutex_owned(ST_MUTEX));
11556 
11557 	if (ri->privatelen == sizeof (recov_info)) {
11558 		attrib = ri->cmd_attrib;
11559 		ASSERT(attrib->recov_pos_type == POS_EXPECTED);
11560 		ASSERT(attrib->chg_tape_pos);
11561 	} else {
11562 		ri = NULL;
11563 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
11564 	}
11565 
11566 	count = bp->b_bcount - bp->b_resid;
11567 
11568 	/* Command reads or writes data */
11569 	if (attrib->transfers_data != TRAN_NONE) {
11570 		if (count == 0) {
11571 			/* failed writes should not make it here */
11572 			ASSERT(attrib->transfers_data == TRAN_READ);
11573 			nblks = 0;
11574 			nfiles = 1;
11575 		} else if (un->un_bsize == 0) {
11576 			/*
11577 			 * If variable block mode.
11578 			 * Fixed bit in CBD should be zero.
11579 			 */
11580 			ASSERT((pkt->pkt_cdbp[1] & 1) == 0);
11581 			nblks = 1;
11582 			un->un_kbytes_xferred += (count / ONE_K);
11583 			nfiles = 0;
11584 		} else {
11585 			/*
11586 			 * If fixed block mode.
11587 			 * Fixed bit in CBD should be one.
11588 			 */
11589 			ASSERT((pkt->pkt_cdbp[1] & 1) == 1);
11590 			nblks = (count / un->un_bsize);
11591 			un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
11592 			nfiles = 0;
11593 		}
11594 		/*
11595 		 * So its possable to read some blocks and hit a filemark.
11596 		 * Example reading in fixed block mode where more then one
11597 		 * block at a time is requested. In this case because the
11598 		 * filemark is hit something less then the requesed number
11599 		 * of blocks is read.
11600 		 */
11601 		if (un->un_pos.eof == ST_EOF_PENDING && bp->b_resid) {
11602 			nfiles = 1;
11603 		}
11604 	} else {
11605 		nblks = 0;
11606 		nfiles = count;
11607 	}
11608 
11609 	/*
11610 	 * If some command failed after this one started and it seems
11611 	 * to have finshed without error count the position.
11612 	 */
11613 	if (un->un_persistence && un->un_persist_errors) {
11614 		ASSERT(un->un_pos.pmode != invalid);
11615 	}
11616 
11617 	if (attrib->chg_tape_direction == DIR_FORW) {
11618 		un->un_pos.blkno += nblks;
11619 		un->un_pos.lgclblkno += nblks;
11620 		un->un_pos.lgclblkno += nfiles;
11621 	} else if (attrib->chg_tape_direction == DIR_REVC) {
11622 		un->un_pos.blkno -= nblks;
11623 		un->un_pos.lgclblkno -= nblks;
11624 		un->un_pos.lgclblkno -= nfiles;
11625 	} else {
11626 		ASSERT(0);
11627 	}
11628 
11629 	/* recovery disabled */
11630 	if (ri == NULL) {
11631 		un->un_running.pmode = invalid;
11632 		return;
11633 	}
11634 
11635 	/*
11636 	 * If we didn't just read a filemark.
11637 	 */
11638 	if (un->un_pos.eof != ST_EOF_PENDING) {
11639 		ASSERT(nblks != 0 && nfiles == 0);
11640 		/*
11641 		 * If Previously calulated expected position does not match
11642 		 * debug the expected position.
11643 		 */
11644 		if ((ri->pos.pmode != invalid) && nblks &&
11645 		    ((un->un_pos.blkno != ri->pos.blkno) ||
11646 		    (un->un_pos.lgclblkno != ri->pos.lgclblkno))) {
11647 #ifdef STDEBUG
11648 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11649 			    "Expected", &ri->pos);
11650 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11651 			    "But Got", &un->un_pos);
11652 #endif
11653 			un->un_running.pmode = invalid;
11654 		}
11655 	} else {
11656 		ASSERT(nfiles != 0);
11657 		if (un->un_running.pmode != invalid) {
11658 			/*
11659 			 * blkno and lgclblkno already counted in
11660 			 * st_add_recovery_info_to_pkt(). Since a block was not
11661 			 * read and a filemark was.
11662 			 */
11663 			if (attrib->chg_tape_direction == DIR_FORW) {
11664 				un->un_running.fileno++;
11665 				un->un_running.blkno = 0;
11666 			} else if (attrib->chg_tape_direction == DIR_REVC) {
11667 				un->un_running.fileno--;
11668 				un->un_running.blkno = LASTBLK;
11669 			}
11670 		}
11671 	}
11672 }
11673 
11674 static void
11675 st_set_state(struct scsi_tape *un, struct buf *bp)
11676 {
11677 	struct scsi_pkt *sp = BP_PKT(bp);
11678 	struct uscsi_cmd *ucmd;
11679 
11680 	ST_FUNC(ST_DEVINFO, st_set_state);
11681 
11682 	ASSERT(mutex_owned(ST_MUTEX));
11683 	ASSERT(bp != un->un_recov_buf);
11684 
11685 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11686 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
11687 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
11688 
11689 	if (bp != un->un_sbufp) {
11690 #ifdef STDEBUG
11691 		if (DEBUGGING && sp->pkt_resid) {
11692 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11693 			    "pkt_resid %ld bcount %ld\n",
11694 			    sp->pkt_resid, bp->b_bcount);
11695 		}
11696 #endif
11697 		bp->b_resid = sp->pkt_resid;
11698 		if (geterror(bp) != EIO) {
11699 			st_calc_bnum(un, bp, sp);
11700 		}
11701 		if (bp->b_flags & B_READ) {
11702 			un->un_lastop = ST_OP_READ;
11703 			un->un_fmneeded = 0;
11704 		} else {
11705 			un->un_lastop = ST_OP_WRITE;
11706 			if (un->un_dp->options & ST_REEL) {
11707 				un->un_fmneeded = 2;
11708 			} else {
11709 				un->un_fmneeded = 1;
11710 			}
11711 		}
11712 		/*
11713 		 * all is honky dory at this point, so let's
11714 		 * readjust the throttle, to increase speed, if we
11715 		 * have not throttled down.
11716 		 */
11717 		if (un->un_throttle) {
11718 			un->un_throttle = un->un_max_throttle;
11719 		}
11720 	} else {
11721 		optype new_lastop = ST_OP_NIL;
11722 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
11723 
11724 		switch (cmd) {
11725 		case SCMD_WRITE:
11726 		case SCMD_WRITE_G4:
11727 			bp->b_resid = sp->pkt_resid;
11728 			new_lastop = ST_OP_WRITE;
11729 			if (geterror(bp) == EIO) {
11730 				break;
11731 			}
11732 			st_calc_bnum(un, bp, sp);
11733 			if (un->un_dp->options & ST_REEL) {
11734 				un->un_fmneeded = 2;
11735 			} else {
11736 				un->un_fmneeded = 1;
11737 			}
11738 			break;
11739 		case SCMD_READ:
11740 		case SCMD_READ_G4:
11741 			bp->b_resid = sp->pkt_resid;
11742 			new_lastop = ST_OP_READ;
11743 			if (geterror(bp) == EIO) {
11744 				break;
11745 			}
11746 			st_calc_bnum(un, bp, sp);
11747 			un->un_fmneeded = 0;
11748 			break;
11749 		case SCMD_WRITE_FILE_MARK_G4:
11750 		case SCMD_WRITE_FILE_MARK:
11751 		{
11752 			int fmdone;
11753 
11754 			if (un->un_pos.eof != ST_EOM) {
11755 				un->un_pos.eof = ST_NO_EOF;
11756 			}
11757 			fmdone = (bp->b_bcount - bp->b_resid);
11758 			if (fmdone > 0) {
11759 				un->un_lastop = new_lastop = ST_OP_WEOF;
11760 				un->un_pos.lgclblkno += fmdone;
11761 				un->un_pos.fileno += fmdone;
11762 				un->un_pos.blkno = 0;
11763 			} else {
11764 				new_lastop = ST_OP_CTL;
11765 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11766 				    "Flushed buffer\n");
11767 			}
11768 			if (fmdone > un->un_fmneeded) {
11769 				un->un_fmneeded = 0;
11770 			} else {
11771 				un->un_fmneeded -= fmdone;
11772 			}
11773 			break;
11774 		}
11775 		case SCMD_REWIND:
11776 			un->un_pos.eof = ST_NO_EOF;
11777 			un->un_pos.fileno = 0;
11778 			un->un_pos.blkno = 0;
11779 			un->un_pos.lgclblkno = 0;
11780 			if (un->un_pos.pmode != legacy)
11781 				un->un_pos.pmode = legacy;
11782 			new_lastop = ST_OP_CTL;
11783 			un->un_restore_pos = 0;
11784 			break;
11785 
11786 		case SCMD_SPACE:
11787 		case SCMD_SPACE_G4:
11788 		{
11789 			int64_t count;
11790 			int64_t resid;
11791 			int64_t done;
11792 			cmd_attribute const *attrib;
11793 			recov_info *ri = sp->pkt_private;
11794 
11795 			if (ri->privatelen == sizeof (recov_info)) {
11796 				attrib = ri->cmd_attrib;
11797 			} else {
11798 				attrib =
11799 				    st_lookup_cmd_attribute(sp->pkt_cdbp[0]);
11800 			}
11801 
11802 			resid = (int64_t)SPACE_CNT(bp->b_resid);
11803 			count = (int64_t)attrib->get_cnt(sp->pkt_cdbp);
11804 
11805 			if (count >= 0) {
11806 				done = (count - resid);
11807 			} else {
11808 				done = ((-count) - resid);
11809 			}
11810 			if (done > 0) {
11811 				un->un_lastop = new_lastop = ST_OP_CTL;
11812 			} else {
11813 				new_lastop = ST_OP_CTL;
11814 			}
11815 
11816 			ST_SPAC(ST_DEVINFO, st_label, CE_WARN,
11817 			    "space cmd: cdb[1] = %s\n"
11818 			    "space data:       = 0x%lx\n"
11819 			    "space count:      = %"PRId64"\n"
11820 			    "space resid:      = %"PRId64"\n"
11821 			    "spaces done:      = %"PRId64"\n"
11822 			    "fileno before     = %d\n"
11823 			    "blkno before      = %d\n",
11824 			    space_strs[sp->pkt_cdbp[1] & 7],
11825 			    bp->b_bcount,
11826 			    count, resid, done,
11827 			    un->un_pos.fileno, un->un_pos.blkno);
11828 
11829 			switch (sp->pkt_cdbp[1]) {
11830 			case SPACE_TYPE(SP_FLM):
11831 				/* Space file forward */
11832 				if (count >= 0) {
11833 					if (un->un_pos.eof <= ST_EOF) {
11834 						un->un_pos.eof = ST_NO_EOF;
11835 					}
11836 					un->un_pos.fileno += done;
11837 					un->un_pos.blkno = 0;
11838 					break;
11839 				}
11840 				/* Space file backward */
11841 				if (done > un->un_pos.fileno) {
11842 					un->un_pos.fileno = 0;
11843 					un->un_pos.blkno = 0;
11844 				} else {
11845 					un->un_pos.fileno -= done;
11846 					un->un_pos.blkno = LASTBLK;
11847 					un->un_running.pmode = invalid;
11848 				}
11849 				break;
11850 			case SPACE_TYPE(SP_BLK):
11851 				/* Space block forward */
11852 				if (count >= 0) {
11853 					un->un_pos.blkno += done;
11854 					break;
11855 				}
11856 				/* Space block backward */
11857 				if (un->un_pos.eof >= ST_EOF_PENDING) {
11858 				/*
11859 				 * we stepped back into
11860 				 * a previous file; we are not
11861 				 * making an effort to pretend that
11862 				 * we are still in the current file
11863 				 * ie. logical == physical position
11864 				 * and leave it to st_ioctl to correct
11865 				 */
11866 					if (done > un->un_pos.blkno) {
11867 						un->un_pos.blkno = 0;
11868 					} else {
11869 						un->un_pos.fileno--;
11870 						un->un_pos.blkno = LASTBLK;
11871 						un->un_running.pmode = invalid;
11872 					}
11873 				} else {
11874 					un->un_pos.blkno -= done;
11875 				}
11876 				break;
11877 			case SPACE_TYPE(SP_SQFLM):
11878 				un->un_pos.pmode = logical;
11879 				un->un_pos.blkno = 0;
11880 				un->un_lastop = new_lastop = ST_OP_CTL;
11881 				break;
11882 			case SPACE_TYPE(SP_EOD):
11883 				un->un_pos.pmode = logical;
11884 				un->un_pos.eof = ST_EOM;
11885 				un->un_status = KEY_BLANK_CHECK;
11886 				break;
11887 			default:
11888 				un->un_pos.pmode = invalid;
11889 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11890 				    "Unsupported space cmd: %s\n",
11891 				    space_strs[sp->pkt_cdbp[1] & 7]);
11892 
11893 				un->un_lastop = new_lastop = ST_OP_CTL;
11894 			}
11895 
11896 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11897 			    "after_space rs %"PRId64" fil %d blk %d\n",
11898 			    resid, un->un_pos.fileno, un->un_pos.blkno);
11899 
11900 			break;
11901 		}
11902 		case SCMD_LOAD:
11903 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
11904 				un->un_pos.fileno = 0;
11905 				if (un->un_pos.pmode != legacy)
11906 					un->un_pos.pmode = legacy;
11907 			} else {
11908 				un->un_state = ST_STATE_OFFLINE;
11909 				un->un_pos.pmode = invalid;
11910 
11911 			}
11912 			/*
11913 			 * If we are loading or unloading we expect the media id
11914 			 * to change. Lets make it unknown.
11915 			 */
11916 			if (un->un_media_id != bogusID && un->un_media_id_len) {
11917 				kmem_free(un->un_media_id, un->un_media_id_len);
11918 				un->un_media_id = NULL;
11919 				un->un_media_id_len = 0;
11920 			}
11921 			un->un_density_known = 0;
11922 			un->un_pos.eof = ST_NO_EOF;
11923 			un->un_pos.blkno = 0;
11924 			un->un_lastop = new_lastop = ST_OP_CTL;
11925 			break;
11926 		case SCMD_ERASE:
11927 			un->un_pos.eof = ST_NO_EOF;
11928 			un->un_pos.blkno = 0;
11929 			un->un_pos.fileno = 0;
11930 			un->un_pos.lgclblkno = 0;
11931 			if (un->un_pos.pmode != legacy)
11932 				un->un_pos.pmode = legacy;
11933 			new_lastop = ST_OP_CTL;
11934 			break;
11935 		case SCMD_RESERVE:
11936 			un->un_rsvd_status |= ST_RESERVE;
11937 			un->un_rsvd_status &=
11938 			    ~(ST_RELEASE | ST_LOST_RESERVE |
11939 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11940 			new_lastop = ST_OP_CTL;
11941 			break;
11942 		case SCMD_RELEASE:
11943 			un->un_rsvd_status |= ST_RELEASE;
11944 			un->un_rsvd_status &=
11945 			    ~(ST_RESERVE | ST_LOST_RESERVE |
11946 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11947 			new_lastop = ST_OP_CTL;
11948 			break;
11949 		case SCMD_PERSISTENT_RESERVE_IN:
11950 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11951 			    "PGR_IN command\n");
11952 			new_lastop = ST_OP_CTL;
11953 			break;
11954 		case SCMD_PERSISTENT_RESERVE_OUT:
11955 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
11956 			case ST_SA_SCSI3_RESERVE:
11957 			case ST_SA_SCSI3_PREEMPT:
11958 			case ST_SA_SCSI3_PREEMPTANDABORT:
11959 				un->un_rsvd_status |=
11960 				    (ST_APPLICATION_RESERVATIONS | ST_RESERVE);
11961 				un->un_rsvd_status &= ~(ST_RELEASE |
11962 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11963 				    ST_INITIATED_RESET);
11964 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11965 				    "PGR Reserve and set: entering"
11966 				    " ST_APPLICATION_RESERVATIONS mode");
11967 				break;
11968 			case ST_SA_SCSI3_REGISTER:
11969 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11970 				    "PGR Reserve register key");
11971 				un->un_rsvd_status |= ST_INIT_RESERVE;
11972 				break;
11973 			case ST_SA_SCSI3_CLEAR:
11974 				un->un_rsvd_status &= ~ST_INIT_RESERVE;
11975 				/* FALLTHROUGH */
11976 			case ST_SA_SCSI3_RELEASE:
11977 				un->un_rsvd_status &=
11978 				    ~(ST_APPLICATION_RESERVATIONS | ST_RESERVE |
11979 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11980 				    ST_INITIATED_RESET);
11981 				un->un_rsvd_status |= ST_RELEASE;
11982 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11983 				    "PGR Release and reset: exiting"
11984 				    " ST_APPLICATION_RESERVATIONS mode");
11985 				break;
11986 			}
11987 			new_lastop = ST_OP_CTL;
11988 			break;
11989 		case SCMD_TEST_UNIT_READY:
11990 		case SCMD_READ_BLKLIM:
11991 		case SCMD_REQUEST_SENSE:
11992 		case SCMD_INQUIRY:
11993 		case SCMD_RECOVER_BUF:
11994 		case SCMD_MODE_SELECT:
11995 		case SCMD_MODE_SENSE:
11996 		case SCMD_DOORLOCK:
11997 		case SCMD_READ_BUFFER:
11998 		case SCMD_REPORT_DENSITIES:
11999 		case SCMD_LOG_SELECT_G1:
12000 		case SCMD_LOG_SENSE_G1:
12001 		case SCMD_REPORT_LUNS:
12002 		case SCMD_READ_ATTRIBUTE:
12003 		case SCMD_WRITE_ATTRIBUTE:
12004 		case SCMD_SVC_ACTION_IN_G5:
12005 		case SCMD_SECURITY_PROTO_IN:
12006 		case SCMD_SECURITY_PROTO_OUT:
12007 			new_lastop = ST_OP_CTL;
12008 			break;
12009 		case SCMD_READ_POSITION:
12010 			new_lastop = ST_OP_CTL;
12011 			/*
12012 			 * Only if the buf used was un_sbufp.
12013 			 * Among other things the prevents read positions used
12014 			 * as part of error recovery from messing up our
12015 			 * current position as they will use un_recov_buf.
12016 			 */
12017 			if (USCSI_CMD(bp)) {
12018 				(void) st_get_read_pos(un, bp);
12019 			}
12020 			break;
12021 		case SCMD_LOCATE:
12022 		case SCMD_LOCATE_G4:
12023 			/* Locate makes position mode no longer legacy */
12024 			un->un_lastop = new_lastop = ST_OP_CTL;
12025 			break;
12026 		case SCMD_MAINTENANCE_IN:
12027 			switch (sp->pkt_cdbp[1]) {
12028 			case SSVC_ACTION_GET_SUPPORTED_OPERATIONS:
12029 			case SSVC_ACTION_SET_TARGET_PORT_GROUPS:
12030 				new_lastop = ST_OP_CTL;
12031 				break;
12032 			}
12033 			if (new_lastop != ST_OP_NIL) {
12034 				break;
12035 			}
12036 		default:
12037 			/*
12038 			 * Unknown command, If was USCSI and USCSI_SILENT
12039 			 * flag was not set, set position to unknown.
12040 			 */
12041 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
12042 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
12043 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
12044 				    "unknown cmd 0x%X caused loss of state\n",
12045 				    cmd);
12046 			} else {
12047 				/*
12048 				 * keep the old agreement to allow unknown
12049 				 * commands with the USCSI_SILENT set.
12050 				 * This prevents ASSERT below.
12051 				 */
12052 				new_lastop = ST_OP_CTL;
12053 				break;
12054 			}
12055 			/* FALLTHROUGH */
12056 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
12057 			un->un_pos.pmode = invalid;
12058 			un->un_lastop = new_lastop = ST_OP_CTL;
12059 			break;
12060 		}
12061 
12062 		/* new_lastop should have been changed */
12063 		ASSERT(new_lastop != ST_OP_NIL);
12064 
12065 		/* If un_lastop should copy new_lastop  */
12066 		if (((un->un_lastop == ST_OP_WRITE) ||
12067 		    (un->un_lastop == ST_OP_WEOF)) &&
12068 		    new_lastop != ST_OP_CTL) {
12069 			un->un_lastop = new_lastop;
12070 		}
12071 	}
12072 
12073 	/*
12074 	 * In the st driver we have a logical and physical file position.
12075 	 * Under BSD behavior, when you get a zero read, the logical position
12076 	 * is before the filemark but after the last record of the file.
12077 	 * The physical position is after the filemark. MTIOCGET should always
12078 	 * return the logical file position.
12079 	 *
12080 	 * The next read gives a silent skip to the next file.
12081 	 * Under SVR4, the logical file position remains before the filemark
12082 	 * until the file is closed or a space operation is performed.
12083 	 * Hence set err_resid and err_file before changing fileno if case
12084 	 * BSD Behaviour.
12085 	 */
12086 	un->un_err_resid = bp->b_resid;
12087 	COPY_POS(&un->un_err_pos, &un->un_pos);
12088 
12089 
12090 	/*
12091 	 * If we've seen a filemark via the last read operation
12092 	 * advance the file counter, but mark things such that
12093 	 * the next read operation gets a zero count. We have
12094 	 * to put this here to handle the case of sitting right
12095 	 * at the end of a tape file having seen the file mark,
12096 	 * but the tape is closed and then re-opened without
12097 	 * any further i/o. That is, the position information
12098 	 * must be updated before a close.
12099 	 */
12100 
12101 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
12102 		/*
12103 		 * If we're a 1/2" tape, and we get a filemark
12104 		 * right on block 0, *AND* we were not in the
12105 		 * first file on the tape, and we've hit logical EOM.
12106 		 * We'll mark the state so that later we do the
12107 		 * right thing (in st_close(), st_strategy() or
12108 		 * st_ioctl()).
12109 		 *
12110 		 */
12111 		if ((un->un_dp->options & ST_REEL) &&
12112 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
12113 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
12114 			un->un_pos.eof = ST_EOT_PENDING;
12115 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12116 			    "eot pending\n");
12117 			un->un_pos.fileno++;
12118 			un->un_pos.blkno = 0;
12119 		} else if (BSD_BEHAVIOR) {
12120 			/*
12121 			 * If the read of the filemark was a side effect
12122 			 * of reading some blocks (i.e., data was actually
12123 			 * read), then the EOF mark is pending and the
12124 			 * bump into the next file awaits the next read
12125 			 * operation (which will return a zero count), or
12126 			 * a close or a space operation, else the bump
12127 			 * into the next file occurs now.
12128 			 */
12129 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12130 			    "resid=%lx, bcount=%lx\n",
12131 			    bp->b_resid, bp->b_bcount);
12132 
12133 			if (bp->b_resid != bp->b_bcount) {
12134 				un->un_pos.eof = ST_EOF;
12135 			} else {
12136 				un->un_silent_skip = 1;
12137 				un->un_pos.eof = ST_NO_EOF;
12138 				un->un_pos.fileno++;
12139 				un->un_pos.lgclblkno++;
12140 				un->un_save_blkno = un->un_pos.blkno;
12141 				un->un_pos.blkno = 0;
12142 			}
12143 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12144 			    "eof of file %d, eof=%d\n",
12145 			    un->un_pos.fileno, un->un_pos.eof);
12146 		} else if (SVR4_BEHAVIOR) {
12147 			/*
12148 			 * If the read of the filemark was a side effect
12149 			 * of reading some blocks (i.e., data was actually
12150 			 * read), then the next read should return 0
12151 			 */
12152 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12153 			    "resid=%lx, bcount=%lx\n",
12154 			    bp->b_resid, bp->b_bcount);
12155 			if (bp->b_resid == bp->b_bcount) {
12156 				un->un_pos.eof = ST_EOF;
12157 			}
12158 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12159 			    "eof of file=%d, eof=%d\n",
12160 			    un->un_pos.fileno, un->un_pos.eof);
12161 		}
12162 	}
12163 }
12164 
12165 /*
12166  * set the correct un_errno, to take corner cases into consideration
12167  */
12168 static void
12169 st_set_pe_errno(struct scsi_tape *un)
12170 {
12171 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
12172 
12173 	ASSERT(mutex_owned(ST_MUTEX));
12174 
12175 	/* if errno is already set, don't reset it */
12176 	if (un->un_errno)
12177 		return;
12178 
12179 	/* here un_errno == 0 */
12180 	/*
12181 	 * if the last transfer before flushing all the
12182 	 * waiting I/O's, was 0 (resid = count), then we
12183 	 * want to give the user an error on all the rest,
12184 	 * so here.  If there was a transfer, we set the
12185 	 * resid and counts to 0, and let it drop through,
12186 	 * giving a zero return.  the next I/O will then
12187 	 * give an error.
12188 	 */
12189 	if (un->un_last_resid == un->un_last_count) {
12190 		switch (un->un_pos.eof) {
12191 		case ST_EOM:
12192 			un->un_errno = ENOMEM;
12193 			break;
12194 		case ST_EOT:
12195 		case ST_EOF:
12196 			un->un_errno = EIO;
12197 			break;
12198 		}
12199 	} else {
12200 		/*
12201 		 * we know they did not have a zero, so make
12202 		 * sure they get one
12203 		 */
12204 		un->un_last_resid = un->un_last_count = 0;
12205 	}
12206 }
12207 
12208 
12209 /*
12210  * send in a marker pkt to terminate flushing of commands by BBA (via
12211  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
12212  */
12213 static void
12214 st_hba_unflush(struct scsi_tape *un)
12215 {
12216 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
12217 
12218 	ASSERT(mutex_owned(ST_MUTEX));
12219 
12220 	if (!un->un_flush_on_errors)
12221 		return;
12222 
12223 #ifdef FLUSH_ON_ERRORS
12224 
12225 	if (!un->un_mkr_pkt) {
12226 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
12227 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
12228 
12229 		/* we slept, so it must be there */
12230 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
12231 	}
12232 
12233 	st_transport(un, un->un_mkr_pkt);
12234 #endif
12235 }
12236 
12237 static char *
12238 st_print_scsi_cmd(char cmd)
12239 {
12240 	char tmp[64];
12241 	char *cpnt;
12242 
12243 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
12244 	/* tmp goes out of scope on return and caller sees garbage */
12245 	if (cpnt == tmp) {
12246 		cpnt = "Unknown Command";
12247 	}
12248 	return (cpnt);
12249 }
12250 
12251 static void
12252 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
12253     char *title, char *cdb)
12254 {
12255 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
12256 	char buf[256];
12257 	struct scsi_tape *un;
12258 	int instance = ddi_get_instance(dip);
12259 
12260 	un = ddi_get_soft_state(st_state, instance);
12261 
12262 	ST_FUNC(dip, st_print_cdb);
12263 
12264 	/* force one line output so repeated commands are printed once */
12265 	if ((st_debug & 0x180) == 0x100) {
12266 		scsi_log(dip, label, level, "node %s cmd %s\n",
12267 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
12268 		return;
12269 	}
12270 
12271 	/* force one line output so repeated CDB's are printed once */
12272 	if ((st_debug & 0x180) == 0x80) {
12273 		st_clean_print(dip, label, level, NULL, cdb, len);
12274 	} else {
12275 		(void) sprintf(buf, "%s for cmd(%s)", title,
12276 		    st_print_scsi_cmd(*cdb));
12277 		st_clean_print(dip, label, level, buf, cdb, len);
12278 	}
12279 }
12280 
12281 static void
12282 st_clean_print(dev_info_t *dev, char *label, uint_t level,
12283     char *title, char *data, int len)
12284 {
12285 	int	i;
12286 	int 	c;
12287 	char	*format;
12288 	char	buf[256];
12289 	uchar_t	byte;
12290 
12291 	ST_FUNC(dev, st_clean_print);
12292 
12293 
12294 	if (title) {
12295 		(void) sprintf(buf, "%s:\n", title);
12296 		scsi_log(dev, label, level, "%s", buf);
12297 		level = CE_CONT;
12298 	}
12299 
12300 	for (i = 0; i < len; ) {
12301 		buf[0] = 0;
12302 		for (c = 0; c < 8 && i < len; c++, i++) {
12303 			byte = (uchar_t)data[i];
12304 			if (byte < 0x10)
12305 				format = "0x0%x ";
12306 			else
12307 				format = "0x%x ";
12308 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
12309 		}
12310 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
12311 
12312 		scsi_log(dev, label, level, "%s\n", buf);
12313 		level = CE_CONT;
12314 	}
12315 }
12316 
12317 /*
12318  * Conditionally enabled debugging
12319  */
12320 #ifdef	STDEBUG
12321 static void
12322 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
12323 {
12324 	char tmpbuf[64];
12325 
12326 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
12327 
12328 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12329 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
12330 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
12331 	    count, count,
12332 	    wait == ASYNC_CMD ? "a" : "");
12333 }
12334 #endif	/* STDEBUG */
12335 
12336 /*
12337  * Returns pointer to name of minor node name of device 'dev'.
12338  */
12339 static char *
12340 st_dev_name(dev_t dev)
12341 {
12342 	struct scsi_tape *un;
12343 	const char density[] = { 'l', 'm', 'h', 'c' };
12344 	static char name[32];
12345 	minor_t minor;
12346 	int instance;
12347 	int nprt = 0;
12348 
12349 	minor = getminor(dev);
12350 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
12351 	un = ddi_get_soft_state(st_state, instance);
12352 	if (un) {
12353 		ST_FUNC(ST_DEVINFO, st_dev_name);
12354 	}
12355 
12356 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
12357 
12358 	if (minor & MT_BSD) {
12359 		name[++nprt] = 'b';
12360 	}
12361 
12362 	if (minor & MT_NOREWIND) {
12363 		name[++nprt] = 'n';
12364 	}
12365 
12366 	/* NULL terminator */
12367 	name[++nprt] = 0;
12368 
12369 	return (name);
12370 }
12371 
12372 /*
12373  * Soft error reporting, so far unique to each drive
12374  *
12375  * Currently supported: exabyte and DAT soft error reporting
12376  */
12377 static int
12378 st_report_exabyte_soft_errors(dev_t dev, int flag)
12379 {
12380 	uchar_t *sensep;
12381 	int amt;
12382 	int rval = 0;
12383 	char cdb[CDB_GROUP0], *c = cdb;
12384 	struct uscsi_cmd *com;
12385 
12386 	GET_SOFT_STATE(dev);
12387 
12388 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
12389 
12390 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12391 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
12392 	    dev, flag);
12393 
12394 	ASSERT(mutex_owned(ST_MUTEX));
12395 
12396 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12397 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
12398 
12399 	*c++ = SCMD_REQUEST_SENSE;
12400 	*c++ = 0;
12401 	*c++ = 0;
12402 	*c++ = 0;
12403 	*c++ = TAPE_SENSE_LENGTH;
12404 	/*
12405 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
12406 	 */
12407 	*c   = (char)0x80;
12408 
12409 	com->uscsi_cdb = cdb;
12410 	com->uscsi_cdblen = CDB_GROUP0;
12411 	com->uscsi_bufaddr = (caddr_t)sensep;
12412 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
12413 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12414 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12415 
12416 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12417 	if (rval || com->uscsi_status) {
12418 		goto done;
12419 	}
12420 
12421 	/*
12422 	 * was there enough data?
12423 	 */
12424 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
12425 
12426 	if ((amt >= 19) && un->un_kbytes_xferred) {
12427 		uint_t count, error_rate;
12428 		uint_t rate;
12429 
12430 		if (sensep[21] & CLN) {
12431 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12432 			    "Periodic head cleaning required");
12433 		}
12434 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
12435 			goto done;
12436 		}
12437 		/*
12438 		 * check if soft error reporting needs to be done.
12439 		 */
12440 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
12441 		count &= 0xffffff;
12442 		error_rate = (count * 100)/un->un_kbytes_xferred;
12443 
12444 #ifdef	STDEBUG
12445 		if (st_soft_error_report_debug) {
12446 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12447 			    "Exabyte Soft Error Report:\n");
12448 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12449 			    "read/write error counter: %d\n", count);
12450 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12451 			    "number of bytes transferred: %dK\n",
12452 			    un->un_kbytes_xferred);
12453 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12454 			    "error_rate: %d%%\n", error_rate);
12455 
12456 			if (amt >= 22) {
12457 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12458 				    "unit sense: 0x%b 0x%b 0x%b\n",
12459 				    sensep[19], SENSE_19_BITS,
12460 				    sensep[20], SENSE_20_BITS,
12461 				    sensep[21], SENSE_21_BITS);
12462 			}
12463 			if (amt >= 27) {
12464 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12465 				    "tracking retry counter: %d\n",
12466 				    sensep[26]);
12467 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12468 				    "read/write retry counter: %d\n",
12469 				    sensep[27]);
12470 			}
12471 		}
12472 #endif
12473 
12474 		if (flag & FWRITE) {
12475 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
12476 		} else {
12477 			rate = EXABYTE_READ_ERROR_THRESHOLD;
12478 		}
12479 		if (error_rate >= rate) {
12480 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12481 			    "Soft error rate (%d%%) during %s was too high",
12482 			    error_rate,
12483 			    ((flag & FWRITE) ? wrg_str : rdg_str));
12484 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12485 			    "Please, replace tape cartridge\n");
12486 		}
12487 	}
12488 
12489 done:
12490 	kmem_free(com, sizeof (*com));
12491 	kmem_free(sensep, TAPE_SENSE_LENGTH);
12492 
12493 	if (rval != 0) {
12494 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12495 		    "exabyte soft error reporting failed\n");
12496 	}
12497 	return (rval);
12498 }
12499 
12500 /*
12501  * this is very specific to Archive 4mm dat
12502  */
12503 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
12504 
12505 static int
12506 st_report_dat_soft_errors(dev_t dev, int flag)
12507 {
12508 	uchar_t *sensep;
12509 	int amt, i;
12510 	int rval = 0;
12511 	char cdb[CDB_GROUP1], *c = cdb;
12512 	struct uscsi_cmd *com;
12513 	struct scsi_arq_status status;
12514 
12515 	GET_SOFT_STATE(dev);
12516 
12517 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
12518 
12519 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12520 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12521 
12522 	ASSERT(mutex_owned(ST_MUTEX));
12523 
12524 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12525 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12526 
12527 	*c++ = SCMD_LOG_SENSE_G1;
12528 	*c++ = 0;
12529 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
12530 	*c++ = 0;
12531 	*c++ = 0;
12532 	*c++ = 0;
12533 	*c++ = 2;
12534 	*c++ = 0;
12535 	*c++ = (char)LOG_SENSE_LENGTH;
12536 	*c   = 0;
12537 	com->uscsi_cdb    = cdb;
12538 	com->uscsi_cdblen  = CDB_GROUP1;
12539 	com->uscsi_bufaddr = (caddr_t)sensep;
12540 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
12541 	com->uscsi_rqlen = sizeof (status);
12542 	com->uscsi_rqbuf = (caddr_t)&status;
12543 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
12544 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12545 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12546 	if (rval) {
12547 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12548 		    "DAT soft error reporting failed\n");
12549 	}
12550 	if (rval || com->uscsi_status) {
12551 		goto done;
12552 	}
12553 
12554 	/*
12555 	 * was there enough data?
12556 	 */
12557 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
12558 
12559 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
12560 		int total, retries, param_code;
12561 
12562 		total = -1;
12563 		retries = -1;
12564 		amt = sensep[3] + 4;
12565 
12566 
12567 #ifdef STDEBUG
12568 		if (st_soft_error_report_debug) {
12569 			(void) printf("logsense:");
12570 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
12571 				if (i % 16 == 0) {
12572 					(void) printf("\t\n");
12573 				}
12574 				(void) printf(" %x", sensep[i]);
12575 			}
12576 			(void) printf("\n");
12577 		}
12578 #endif
12579 
12580 		/*
12581 		 * parse the param_codes
12582 		 */
12583 		if (sensep[0] == 2 || sensep[0] == 3) {
12584 			for (i = 4; i < amt; i++) {
12585 				param_code = (sensep[i++] << 8);
12586 				param_code += sensep[i++];
12587 				i++; /* skip control byte */
12588 				if (param_code == 5) {
12589 					if (sensep[i++] == 4) {
12590 						total = (sensep[i++] << 24);
12591 						total += (sensep[i++] << 16);
12592 						total += (sensep[i++] << 8);
12593 						total += sensep[i];
12594 					}
12595 				} else if (param_code == 0x8007) {
12596 					if (sensep[i++] == 2) {
12597 						retries = sensep[i++] << 8;
12598 						retries += sensep[i];
12599 					}
12600 				} else {
12601 					i += sensep[i];
12602 				}
12603 			}
12604 		}
12605 
12606 		/*
12607 		 * if the log sense returned valid numbers then determine
12608 		 * the read and write error thresholds based on the amount of
12609 		 * data transferred
12610 		 */
12611 
12612 		if (total > 0 && retries > 0) {
12613 			short normal_retries = 0;
12614 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12615 			    "total xferred (%s) =%x, retries=%x\n",
12616 			    ((flag & FWRITE) ? wrg_str : rdg_str),
12617 			    total, retries);
12618 
12619 			if (flag & FWRITE) {
12620 				if (total <=
12621 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
12622 					normal_retries =
12623 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
12624 				} else {
12625 					normal_retries =
12626 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
12627 				}
12628 			} else {
12629 				if (total <=
12630 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
12631 					normal_retries =
12632 					    DAT_SMALL_READ_ERROR_THRESHOLD;
12633 				} else {
12634 					normal_retries =
12635 					    DAT_LARGE_READ_ERROR_THRESHOLD;
12636 				}
12637 			}
12638 
12639 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12640 			"normal retries=%d\n", normal_retries);
12641 
12642 			if (retries >= normal_retries) {
12643 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12644 				    "Soft error rate (retries = %d) during "
12645 				    "%s was too high",  retries,
12646 				    ((flag & FWRITE) ? wrg_str : rdg_str));
12647 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12648 				    "Periodic head cleaning required "
12649 				    "and/or replace tape cartridge\n");
12650 			}
12651 
12652 		} else if (total == -1 || retries == -1) {
12653 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12654 			    "log sense parameter code does not make sense\n");
12655 		}
12656 	}
12657 
12658 	/*
12659 	 * reset all values
12660 	 */
12661 	c = cdb;
12662 	*c++ = SCMD_LOG_SELECT_G1;
12663 	*c++ = 2;	/* this resets all values */
12664 	*c++ = (char)0xc0;
12665 	*c++ = 0;
12666 	*c++ = 0;
12667 	*c++ = 0;
12668 	*c++ = 0;
12669 	*c++ = 0;
12670 	*c++ = 0;
12671 	*c   = 0;
12672 	com->uscsi_bufaddr = NULL;
12673 	com->uscsi_buflen  = 0;
12674 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
12675 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12676 	if (rval) {
12677 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12678 		    "DAT soft error reset failed\n");
12679 	}
12680 done:
12681 	kmem_free(com, sizeof (*com));
12682 	kmem_free(sensep, LOG_SENSE_LENGTH);
12683 	return (rval);
12684 }
12685 
12686 static int
12687 st_report_soft_errors(dev_t dev, int flag)
12688 {
12689 	GET_SOFT_STATE(dev);
12690 
12691 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
12692 
12693 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12694 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12695 
12696 	ASSERT(mutex_owned(ST_MUTEX));
12697 
12698 	switch (un->un_dp->type) {
12699 	case ST_TYPE_EXB8500:
12700 	case ST_TYPE_EXABYTE:
12701 		return (st_report_exabyte_soft_errors(dev, flag));
12702 		/*NOTREACHED*/
12703 	case ST_TYPE_PYTHON:
12704 		return (st_report_dat_soft_errors(dev, flag));
12705 		/*NOTREACHED*/
12706 	default:
12707 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
12708 		return (-1);
12709 	}
12710 }
12711 
12712 /*
12713  * persistent error routines
12714  */
12715 
12716 /*
12717  * enable persistent errors, and set the throttle appropriately, checking
12718  * for flush-on-errors capability
12719  */
12720 static void
12721 st_turn_pe_on(struct scsi_tape *un)
12722 {
12723 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
12724 
12725 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
12726 	ASSERT(mutex_owned(ST_MUTEX));
12727 
12728 	un->un_persistence = 1;
12729 
12730 	/*
12731 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
12732 	 * enabled.  This will simplify the error handling for request senses
12733 	 */
12734 
12735 	if (un->un_arq_enabled && un->un_untagged_qing) {
12736 		uchar_t f_o_e;
12737 
12738 		mutex_exit(ST_MUTEX);
12739 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
12740 		    1 : 0;
12741 		mutex_enter(ST_MUTEX);
12742 
12743 		un->un_flush_on_errors = f_o_e;
12744 	} else {
12745 		un->un_flush_on_errors = 0;
12746 	}
12747 
12748 	if (un->un_flush_on_errors)
12749 		un->un_max_throttle = (uchar_t)st_max_throttle;
12750 	else
12751 		un->un_max_throttle = 1;
12752 
12753 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
12754 		un->un_max_throttle = 1;
12755 
12756 	/* this will send a marker pkt */
12757 	st_clear_pe(un);
12758 }
12759 
12760 /*
12761  * This turns persistent errors permanently off
12762  */
12763 static void
12764 st_turn_pe_off(struct scsi_tape *un)
12765 {
12766 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
12767 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
12768 	ASSERT(mutex_owned(ST_MUTEX));
12769 
12770 	/* turn it off for good */
12771 	un->un_persistence = 0;
12772 
12773 	/* this will send a marker pkt */
12774 	st_clear_pe(un);
12775 
12776 	/* turn off flush on error capability, if enabled */
12777 	if (un->un_flush_on_errors) {
12778 		mutex_exit(ST_MUTEX);
12779 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
12780 		mutex_enter(ST_MUTEX);
12781 	}
12782 
12783 
12784 	un->un_flush_on_errors = 0;
12785 }
12786 
12787 /*
12788  * This clear persistent errors, allowing more commands through, and also
12789  * sending a marker packet.
12790  */
12791 static void
12792 st_clear_pe(struct scsi_tape *un)
12793 {
12794 	ST_FUNC(ST_DEVINFO, st_clear_pe);
12795 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
12796 	ASSERT(mutex_owned(ST_MUTEX));
12797 
12798 	un->un_persist_errors = 0;
12799 	un->un_throttle = un->un_last_throttle = 1;
12800 	un->un_errno = 0;
12801 	st_hba_unflush(un);
12802 }
12803 
12804 /*
12805  * This will flag persistent errors, shutting everything down, if the
12806  * application had enabled persistent errors via MTIOCPERSISTENT
12807  */
12808 static void
12809 st_set_pe_flag(struct scsi_tape *un)
12810 {
12811 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
12812 	ASSERT(mutex_owned(ST_MUTEX));
12813 
12814 	if (un->un_persistence) {
12815 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
12816 		un->un_persist_errors = 1;
12817 		un->un_throttle = un->un_last_throttle = 0;
12818 		cv_broadcast(&un->un_sbuf_cv);
12819 	}
12820 }
12821 
12822 static int
12823 st_do_reserve(struct scsi_tape *un)
12824 {
12825 	int rval;
12826 	int was_lost = un->un_rsvd_status & ST_LOST_RESERVE;
12827 
12828 	ST_FUNC(ST_DEVINFO, st_do_reserve);
12829 
12830 	/*
12831 	 * Issue a Throw-Away reserve command to clear the
12832 	 * check condition.
12833 	 * If the current behaviour of reserve/release is to
12834 	 * hold reservation across opens , and if a Bus reset
12835 	 * has been issued between opens then this command
12836 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
12837 	 * In this case return an EACCES so that user knows that
12838 	 * reservation has been lost in between opens.
12839 	 * If this error is not returned and we continue with
12840 	 * successful open , then user may think position of the
12841 	 * tape is still the same but inreality we would rewind the
12842 	 * tape and continue from BOT.
12843 	 */
12844 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12845 	if (rval) {
12846 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
12847 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
12848 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
12849 			un->un_errno = EACCES;
12850 			return (EACCES);
12851 		}
12852 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12853 	}
12854 	if (rval == 0) {
12855 		un->un_rsvd_status |= ST_INIT_RESERVE;
12856 	}
12857 	if (was_lost) {
12858 		un->un_running.pmode = invalid;
12859 	}
12860 
12861 	return (rval);
12862 }
12863 
12864 static int
12865 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb)
12866 {
12867 	int rval;
12868 	cmd_attribute const *attrib;
12869 
12870 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
12871 
12872 	/*
12873 	 * If already reserved no need to do it again.
12874 	 * Also if Reserve and Release are disabled Just return.
12875 	 */
12876 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12877 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12878 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12879 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12880 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
12881 		    st_print_scsi_cmd((uchar_t)cdb[0]));
12882 		return (0);
12883 	}
12884 
12885 	/* See if command is on the list */
12886 	attrib = st_lookup_cmd_attribute(cdb[0]);
12887 
12888 	if (attrib == NULL) {
12889 		rval = 1; /* Not found, when in doubt reserve */
12890 	} else if ((attrib->requires_reserve) != 0) {
12891 		rval = 1;
12892 	} else if ((attrib->reserve_byte) != 0) {
12893 		/*
12894 		 * cmd is on list.
12895 		 * if byte is zero always allowed.
12896 		 */
12897 		rval = 1;
12898 	} else if (((cdb[attrib->reserve_byte]) &
12899 	    (attrib->reserve_mask)) != 0) {
12900 		rval = 1;
12901 	} else {
12902 		rval = 0;
12903 	}
12904 
12905 	if (rval) {
12906 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12907 		    "Command %s requires reservation",
12908 		    st_print_scsi_cmd(cdb[0]));
12909 
12910 		rval = st_do_reserve(un);
12911 	}
12912 
12913 	return (rval);
12914 }
12915 
12916 static int
12917 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
12918 {
12919 	int rval;
12920 	cmd_attribute const *attrib;
12921 
12922 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
12923 
12924 	/*
12925 	 * Do not reserve when already reserved, when not supported or when
12926 	 * auto-rewinding on device closure.
12927 	 */
12928 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12929 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12930 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE) ||
12931 	    ((un->un_state == ST_STATE_CLOSING) && (cmd == SCMD_REWIND))) {
12932 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12933 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
12934 		    st_print_scsi_cmd(cmd));
12935 		return (0);
12936 	}
12937 
12938 	/* search for this command on the list */
12939 	attrib = st_lookup_cmd_attribute(cmd);
12940 
12941 	if (attrib == NULL) {
12942 		rval = 1; /* Not found, when in doubt reserve */
12943 	} else if ((attrib->requires_reserve) != 0) {
12944 		rval = 1;
12945 	} else if ((attrib->reserve_byte) != 0) {
12946 		/*
12947 		 * cmd is on list.
12948 		 * if byte is zero always allowed.
12949 		 */
12950 		rval = 1;
12951 	} else if (((attrib->reserve_mask) & cnt) != 0) {
12952 		rval = 1;
12953 	} else {
12954 		rval = 0;
12955 	}
12956 
12957 	if (rval) {
12958 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12959 		    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
12960 
12961 		rval = st_do_reserve(un);
12962 	}
12963 
12964 	return (rval);
12965 }
12966 
12967 static int
12968 st_reserve_release(struct scsi_tape *un, int cmd, ubufunc_t ubf)
12969 {
12970 	struct uscsi_cmd	uscsi_cmd;
12971 	int			rval;
12972 	char			cdb[CDB_GROUP0];
12973 	struct scsi_arq_status	stat;
12974 
12975 
12976 
12977 	ST_FUNC(ST_DEVINFO, st_reserve_release);
12978 
12979 	ASSERT(mutex_owned(ST_MUTEX));
12980 
12981 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12982 	    "st_reserve_release: %s \n",
12983 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
12984 
12985 	bzero(&cdb, CDB_GROUP0);
12986 	if (cmd == ST_RELEASE) {
12987 		cdb[0] = SCMD_RELEASE;
12988 	} else {
12989 		cdb[0] = SCMD_RESERVE;
12990 	}
12991 	bzero(&uscsi_cmd, sizeof (struct uscsi_cmd));
12992 	uscsi_cmd.uscsi_flags = USCSI_WRITE | USCSI_RQENABLE;
12993 	uscsi_cmd.uscsi_cdb = cdb;
12994 	uscsi_cmd.uscsi_cdblen = CDB_GROUP0;
12995 	uscsi_cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
12996 	uscsi_cmd.uscsi_rqbuf = (caddr_t)&stat;
12997 	uscsi_cmd.uscsi_rqlen = sizeof (stat);
12998 
12999 	rval = ubf(un, &uscsi_cmd, FKIOCTL);
13000 
13001 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13002 	    "st_reserve_release: rval(1)=%d\n", rval);
13003 
13004 	if (rval) {
13005 		if (uscsi_cmd.uscsi_status == STATUS_RESERVATION_CONFLICT) {
13006 			rval = EACCES;
13007 		}
13008 		/*
13009 		 * dynamically turn off reserve/release support
13010 		 * in case of drives which do not support
13011 		 * reserve/release command(ATAPI drives).
13012 		 */
13013 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
13014 			if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
13015 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
13016 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13017 				    "Tape unit does not support "
13018 				    "reserve/release \n");
13019 			}
13020 			rval = 0;
13021 		}
13022 	}
13023 	return (rval);
13024 }
13025 
13026 static int
13027 st_take_ownership(struct scsi_tape *un, ubufunc_t ubf)
13028 {
13029 	int rval;
13030 
13031 	ST_FUNC(ST_DEVINFO, st_take_ownership);
13032 
13033 	ASSERT(mutex_owned(ST_MUTEX));
13034 
13035 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13036 	    "st_take_ownership: Entering ...\n");
13037 
13038 
13039 	rval = st_reserve_release(un, ST_RESERVE, ubf);
13040 	/*
13041 	 * XXX -> Should reset be done only if we get EACCES.
13042 	 * .
13043 	 */
13044 	if (rval) {
13045 		if (st_reset(un, RESET_LUN) == 0) {
13046 			return (EIO);
13047 		}
13048 		un->un_rsvd_status &=
13049 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
13050 
13051 		mutex_exit(ST_MUTEX);
13052 		delay(drv_usectohz(ST_RESERVATION_DELAY));
13053 		mutex_enter(ST_MUTEX);
13054 		/*
13055 		 * remove the check condition.
13056 		 */
13057 		(void) st_reserve_release(un, ST_RESERVE, ubf);
13058 		rval = st_reserve_release(un, ST_RESERVE, ubf);
13059 		if (rval != 0) {
13060 			if ((st_reserve_release(un, ST_RESERVE, ubf))
13061 			    != 0) {
13062 				rval = (un->un_rsvd_status &
13063 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
13064 				return (rval);
13065 			}
13066 		}
13067 		/*
13068 		 * Set tape state to ST_STATE_OFFLINE , in case if
13069 		 * the user wants to continue and start using
13070 		 * the tape.
13071 		 */
13072 		un->un_state = ST_STATE_OFFLINE;
13073 		un->un_rsvd_status |= ST_INIT_RESERVE;
13074 	}
13075 	return (rval);
13076 }
13077 
13078 static int
13079 st_create_errstats(struct scsi_tape *un, int instance)
13080 {
13081 	char	kstatname[KSTAT_STRLEN];
13082 
13083 	ST_FUNC(ST_DEVINFO, st_create_errstats);
13084 
13085 	/*
13086 	 * Create device error kstats
13087 	 */
13088 
13089 	if (un->un_errstats == (kstat_t *)0) {
13090 		(void) sprintf(kstatname, "st%d,err", instance);
13091 		un->un_errstats = kstat_create("sterr", instance, kstatname,
13092 		    "device_error", KSTAT_TYPE_NAMED,
13093 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
13094 		    KSTAT_FLAG_PERSISTENT);
13095 
13096 		if (un->un_errstats) {
13097 			struct st_errstats	*stp;
13098 
13099 			stp = (struct st_errstats *)un->un_errstats->ks_data;
13100 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
13101 			    KSTAT_DATA_ULONG);
13102 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
13103 			    KSTAT_DATA_ULONG);
13104 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
13105 			    KSTAT_DATA_ULONG);
13106 			kstat_named_init(&stp->st_vid, "Vendor",
13107 			    KSTAT_DATA_CHAR);
13108 			kstat_named_init(&stp->st_pid, "Product",
13109 			    KSTAT_DATA_CHAR);
13110 			kstat_named_init(&stp->st_revision, "Revision",
13111 			    KSTAT_DATA_CHAR);
13112 			kstat_named_init(&stp->st_serial, "Serial No",
13113 			    KSTAT_DATA_CHAR);
13114 			un->un_errstats->ks_private = un;
13115 			un->un_errstats->ks_update = nulldev;
13116 			kstat_install(un->un_errstats);
13117 			/*
13118 			 * Fill in the static data
13119 			 */
13120 			(void) strncpy(&stp->st_vid.value.c[0],
13121 			    ST_INQUIRY->inq_vid, 8);
13122 			/*
13123 			 * XXX:  Emulex MT-02 (and emulators) predates
13124 			 *	 SCSI-1 and has no vid & pid inquiry data.
13125 			 */
13126 			if (ST_INQUIRY->inq_len != 0) {
13127 				(void) strncpy(&stp->st_pid.value.c[0],
13128 				    ST_INQUIRY->inq_pid, 16);
13129 				(void) strncpy(&stp->st_revision.value.c[0],
13130 				    ST_INQUIRY->inq_revision, 4);
13131 			}
13132 		}
13133 	}
13134 	return (0);
13135 }
13136 
13137 static int
13138 st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos)
13139 {
13140 	int rval;
13141 	bufunc_t bf = (ubf == st_uscsi_rcmd) ? st_rcmd : st_cmd;
13142 
13143 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
13144 
13145 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
13146 	ASSERT(mutex_owned(ST_MUTEX));
13147 
13148 	/* Can't restore an invalid position */
13149 	if (pos->pmode == invalid) {
13150 		return (4);
13151 	}
13152 
13153 	/*
13154 	 * Assumtions:
13155 	 *	If a position was read and is in logical position mode.
13156 	 *	If a drive supports read position it supports locate.
13157 	 *	If the read position type is not NO_POS. even though
13158 	 *	   a read position make not have been attemped yet.
13159 	 *
13160 	 *	The drive can locate to the position.
13161 	 */
13162 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
13163 		/*
13164 		 * If position mode is logical or legacy mode try
13165 		 * to locate there as it is faster.
13166 		 * If it fails try the old way.
13167 		 */
13168 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13169 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
13170 		    pos->lgclblkno);
13171 
13172 		if (st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
13173 		    pos->lgclblkno, pos->partition) == 0) {
13174 			/* Assume we are there copy rest of position back */
13175 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
13176 				COPY_POS(&un->un_pos, pos);
13177 			}
13178 			return (0);
13179 		}
13180 
13181 		/*
13182 		 * If logical block locate failed to restore a logical
13183 		 * position, can't recover.
13184 		 */
13185 		if (pos->pmode == logical) {
13186 			return (-1);
13187 		}
13188 	}
13189 
13190 
13191 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13192 	    "Restoring tape position at fileno=%x, blkno=%x....",
13193 	    pos->fileno, pos->blkno);
13194 
13195 	/*
13196 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
13197 	 * so as not to rewind tape on RESETS: Gee, Has life ever
13198 	 * been simple in tape land ?
13199 	 */
13200 	rval = bf(un, SCMD_REWIND, 0, SYNC_CMD);
13201 	if (rval) {
13202 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
13203 		    "Failed to restore the last file and block position: In"
13204 		    " this state, Tape will be loaded at BOT during next open");
13205 		un->un_pos.pmode = invalid;
13206 		return (rval);
13207 	}
13208 
13209 	/* If the position was as the result of back space file */
13210 	if (pos->blkno > (INF / 2)) {
13211 		/* Go one extra file forward */
13212 		pos->fileno++;
13213 		/* Figure how many blocks to back into the previous file */
13214 		pos->blkno = -(INF - pos->blkno);
13215 	}
13216 
13217 	/* Go to requested fileno */
13218 	if (pos->fileno) {
13219 		rval = st_cmd(un, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
13220 		if (rval) {
13221 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13222 			    "Failed to restore the last file position: In this "
13223 			    " state, Tape will be loaded at BOT during next"
13224 			    " open %d", __LINE__);
13225 			un->un_pos.pmode = invalid;
13226 			pos->pmode = invalid;
13227 			return (rval);
13228 		}
13229 	}
13230 
13231 	/*
13232 	 * If backing into a file we already did an extra file forward.
13233 	 * Now we have to back over the filemark to get to the end of
13234 	 * the previous file. The blkno has been ajusted to a negative
13235 	 * value so we will get to the expected location.
13236 	 */
13237 	if (pos->blkno) {
13238 		rval = bf(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
13239 		if (rval) {
13240 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13241 			    "Failed to restore the last file position: In this "
13242 			    " state, Tape will be loaded at BOT during next"
13243 			    " open %d", __LINE__);
13244 			un->un_pos.pmode = invalid;
13245 			pos->pmode = invalid;
13246 			return (rval);
13247 		}
13248 	}
13249 
13250 	/*
13251 	 * The position mode, block and fileno should be correct,
13252 	 * This updates eof and logical position information.
13253 	 */
13254 	un->un_pos.eof = pos->eof;
13255 	un->un_pos.lgclblkno = pos->lgclblkno;
13256 
13257 	return (0);
13258 }
13259 
13260 /*
13261  * check sense key, ASC, ASCQ in order to determine if the tape needs
13262  * to be ejected
13263  */
13264 
13265 static int
13266 st_check_asc_ascq(struct scsi_tape *un)
13267 {
13268 	struct scsi_extended_sense *sensep = ST_RQSENSE;
13269 	struct tape_failure_code   *code;
13270 
13271 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
13272 
13273 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
13274 		if ((code->key  == sensep->es_key) &&
13275 		    (code->add_code  == sensep->es_add_code) &&
13276 		    (code->qual_code == sensep->es_qual_code))
13277 			return (1);
13278 	}
13279 	return (0);
13280 }
13281 
13282 /*
13283  * st_logpage_supported() sends a Log Sense command with
13284  * page code = 0 = Supported Log Pages Page to the device,
13285  * to see whether the page 'page' is supported.
13286  * Return values are:
13287  * -1 if the Log Sense command fails
13288  * 0 if page is not supported
13289  * 1 if page is supported
13290  */
13291 
13292 static int
13293 st_logpage_supported(struct scsi_tape *un, uchar_t page)
13294 {
13295 	uchar_t *sp, *sensep;
13296 	unsigned length;
13297 	struct uscsi_cmd *com;
13298 	struct scsi_arq_status status;
13299 	int rval;
13300 	char cdb[CDB_GROUP1] = {
13301 		SCMD_LOG_SENSE_G1,
13302 		0,
13303 		SUPPORTED_LOG_PAGES_PAGE,
13304 		0,
13305 		0,
13306 		0,
13307 		0,
13308 		0,
13309 		(char)LOG_SENSE_LENGTH,
13310 		0
13311 	};
13312 
13313 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
13314 
13315 	ASSERT(mutex_owned(ST_MUTEX));
13316 
13317 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13318 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
13319 
13320 	com->uscsi_cdb = cdb;
13321 	com->uscsi_cdblen = CDB_GROUP1;
13322 	com->uscsi_bufaddr = (caddr_t)sensep;
13323 	com->uscsi_buflen = LOG_SENSE_LENGTH;
13324 	com->uscsi_rqlen = sizeof (status);
13325 	com->uscsi_rqbuf = (caddr_t)&status;
13326 	com->uscsi_flags =
13327 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13328 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13329 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13330 	if (rval || com->uscsi_status) {
13331 		/* uscsi-command failed */
13332 		rval = -1;
13333 	} else {
13334 
13335 		sp = sensep + 3;
13336 
13337 		for (length = *sp++; length > 0; length--, sp++) {
13338 
13339 			if (*sp == page) {
13340 				rval = 1;
13341 				break;
13342 			}
13343 		}
13344 	}
13345 	kmem_free(com, sizeof (struct uscsi_cmd));
13346 	kmem_free(sensep, LOG_SENSE_LENGTH);
13347 	return (rval);
13348 }
13349 
13350 
13351 /*
13352  * st_check_clean_bit() gets the status of the tape's cleaning bit.
13353  *
13354  * If the device does support the TapeAlert log page, then the cleaning bit
13355  * information will be read from this page. Otherwise we will see if one of
13356  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
13357  * the device, which means, that we can get the cleaning bit information via
13358  * a RequestSense command.
13359  * If both methods of getting cleaning bit information are not supported
13360  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
13361  * returns with
13362  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
13363  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
13364  * If the call to st_uscsi_cmd() to do the Log Sense or the Request Sense
13365  * command fails, or if the amount of Request Sense data is not enough, then
13366  *  st_check_clean_bit() returns with -1.
13367  */
13368 
13369 static int
13370 st_check_clean_bit(struct scsi_tape *un)
13371 {
13372 	int rval = 0;
13373 
13374 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
13375 
13376 	ASSERT(mutex_owned(ST_MUTEX));
13377 
13378 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
13379 		return (rval);
13380 	}
13381 
13382 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13383 
13384 		rval = st_logpage_supported(un, TAPE_SEQUENTIAL_PAGE);
13385 		if (rval == -1) {
13386 			return (0);
13387 		}
13388 		if (rval == 1) {
13389 
13390 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
13391 		}
13392 
13393 		rval = st_logpage_supported(un, TAPE_ALERT_PAGE);
13394 		if (rval == -1) {
13395 			return (0);
13396 		}
13397 		if (rval == 1) {
13398 
13399 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
13400 		}
13401 
13402 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13403 
13404 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
13405 		}
13406 	}
13407 
13408 	rval = 0;
13409 
13410 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
13411 
13412 		rval = st_check_sequential_clean_bit(un);
13413 		if (rval == -1) {
13414 			return (0);
13415 		}
13416 	}
13417 
13418 	if ((rval == 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
13419 
13420 		rval = st_check_alert_flags(un);
13421 		if (rval == -1) {
13422 			return (0);
13423 		}
13424 	}
13425 
13426 	if ((rval == 0) && (un->un_dp->options & ST_CLN_MASK)) {
13427 
13428 		rval = st_check_sense_clean_bit(un);
13429 		if (rval == -1) {
13430 			return (0);
13431 		}
13432 	}
13433 
13434 	/*
13435 	 * If found a supported means to check need to clean.
13436 	 */
13437 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
13438 
13439 		/*
13440 		 * head needs to be cleaned.
13441 		 */
13442 		if (rval & MTF_TAPE_HEAD_DIRTY) {
13443 
13444 			/*
13445 			 * Print log message only first time
13446 			 * found needing cleaned.
13447 			 */
13448 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
13449 
13450 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
13451 				    "Periodic head cleaning required");
13452 
13453 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
13454 			}
13455 
13456 		} else {
13457 
13458 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
13459 		}
13460 	}
13461 
13462 	return (rval);
13463 }
13464 
13465 
13466 static int
13467 st_check_sequential_clean_bit(struct scsi_tape *un)
13468 {
13469 	int rval;
13470 	int ix;
13471 	ushort_t parameter;
13472 	struct uscsi_cmd *cmd;
13473 	struct log_sequential_page *sp;
13474 	struct log_sequential_page_parameter *prm;
13475 	struct scsi_arq_status status;
13476 	char cdb[CDB_GROUP1] = {
13477 		SCMD_LOG_SENSE_G1,
13478 		0,
13479 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
13480 		0,
13481 		0,
13482 		0,
13483 		0,
13484 		(char)(sizeof (struct log_sequential_page) >> 8),
13485 		(char)(sizeof (struct log_sequential_page)),
13486 		0
13487 	};
13488 
13489 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
13490 
13491 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13492 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
13493 
13494 	cmd->uscsi_flags   =
13495 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13496 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13497 	cmd->uscsi_cdb	   = cdb;
13498 	cmd->uscsi_cdblen  = CDB_GROUP1;
13499 	cmd->uscsi_bufaddr = (caddr_t)sp;
13500 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
13501 	cmd->uscsi_rqlen   = sizeof (status);
13502 	cmd->uscsi_rqbuf   = (caddr_t)&status;
13503 
13504 	rval = st_uscsi_cmd(un, cmd, FKIOCTL);
13505 
13506 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
13507 
13508 		rval = -1;
13509 
13510 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
13511 
13512 		rval = -1;
13513 	}
13514 
13515 	prm = &sp->param[0];
13516 
13517 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
13518 
13519 		if (prm->log_param.length == 0) {
13520 			break;
13521 		}
13522 
13523 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
13524 		    (prm->log_param.pc_lo & 0xff));
13525 
13526 		if (parameter == SEQUENTIAL_NEED_CLN) {
13527 
13528 			rval = MTF_TAPE_CLN_SUPPORTED;
13529 			if (prm->param_value[prm->log_param.length - 1]) {
13530 
13531 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13532 				    "sequential log says head dirty\n");
13533 				rval |= MTF_TAPE_HEAD_DIRTY;
13534 			}
13535 		}
13536 		prm = (struct log_sequential_page_parameter *)
13537 		    &prm->param_value[prm->log_param.length];
13538 	}
13539 
13540 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13541 	kmem_free(sp,  sizeof (struct log_sequential_page));
13542 
13543 	return (rval);
13544 }
13545 
13546 
13547 static int
13548 st_check_alert_flags(struct scsi_tape *un)
13549 {
13550 	struct st_tape_alert *ta;
13551 	struct uscsi_cmd *com;
13552 	struct scsi_arq_status status;
13553 	unsigned ix, length;
13554 	int rval;
13555 	tape_alert_flags flag;
13556 	char cdb[CDB_GROUP1] = {
13557 		SCMD_LOG_SENSE_G1,
13558 		0,
13559 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
13560 		0,
13561 		0,
13562 		0,
13563 		0,
13564 		(char)(sizeof (struct st_tape_alert) >> 8),
13565 		(char)(sizeof (struct st_tape_alert)),
13566 		0
13567 	};
13568 
13569 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
13570 
13571 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13572 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
13573 
13574 	com->uscsi_cdb = cdb;
13575 	com->uscsi_cdblen = CDB_GROUP1;
13576 	com->uscsi_bufaddr = (caddr_t)ta;
13577 	com->uscsi_buflen = sizeof (struct st_tape_alert);
13578 	com->uscsi_rqlen = sizeof (status);
13579 	com->uscsi_rqbuf = (caddr_t)&status;
13580 	com->uscsi_flags =
13581 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13582 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13583 
13584 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13585 
13586 	if (rval || com->uscsi_status || com->uscsi_resid) {
13587 
13588 		rval = -1; /* uscsi-command failed */
13589 
13590 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
13591 
13592 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13593 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
13594 		rval = -1;
13595 	}
13596 
13597 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
13598 
13599 
13600 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
13601 
13602 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13603 		    "TapeAlert length %d\n", length);
13604 	}
13605 
13606 
13607 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
13608 
13609 		/*
13610 		 * if rval is bad before the first pass don't bother
13611 		 */
13612 		if (ix == 0 && rval != 0) {
13613 
13614 			break;
13615 		}
13616 
13617 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
13618 		    ta->param[ix].log_param.pc_lo);
13619 
13620 		if ((ta->param[ix].param_value & 1) == 0) {
13621 			continue;
13622 		}
13623 		/*
13624 		 * check to see if current parameter is of interest.
13625 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
13626 		 */
13627 		if ((flag == TAF_CLEAN_NOW) ||
13628 		    (flag == TAF_CLEAN_PERIODIC) ||
13629 		    ((flag == CLEAN_FOR_ERRORS) &&
13630 		    (un->un_dp->type == ST_TYPE_STK9840))) {
13631 
13632 			rval = MTF_TAPE_CLN_SUPPORTED;
13633 
13634 
13635 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13636 			    "alert_page drive needs clean %d\n", flag);
13637 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
13638 			rval |= MTF_TAPE_HEAD_DIRTY;
13639 
13640 		} else if (flag == TAF_CLEANING_MEDIA) {
13641 
13642 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13643 			    "alert_page drive was cleaned\n");
13644 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
13645 		}
13646 
13647 	}
13648 
13649 	/*
13650 	 * Report it as dirty till we see it cleaned
13651 	 */
13652 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
13653 
13654 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13655 		    "alert_page still dirty\n");
13656 		rval |= MTF_TAPE_HEAD_DIRTY;
13657 	}
13658 
13659 	kmem_free(com, sizeof (struct uscsi_cmd));
13660 	kmem_free(ta,  sizeof (struct st_tape_alert));
13661 
13662 	return (rval);
13663 }
13664 
13665 
13666 static int
13667 st_check_sense_clean_bit(struct scsi_tape *un)
13668 {
13669 	uchar_t *sensep;
13670 	char cdb[CDB_GROUP0];
13671 	struct uscsi_cmd *com;
13672 	ushort_t byte_pos;
13673 	uchar_t bit_mask;
13674 	unsigned length;
13675 	int index;
13676 	int rval;
13677 
13678 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
13679 
13680 	/*
13681 	 * Since this tape does not support Tape Alert,
13682 	 * we now try to get the cleanbit status via
13683 	 * Request Sense.
13684 	 */
13685 
13686 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
13687 
13688 		index = 0;
13689 
13690 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
13691 
13692 		index = 1;
13693 
13694 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
13695 
13696 		index = 2;
13697 
13698 	} else {
13699 
13700 		return (-1);
13701 	}
13702 
13703 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
13704 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
13705 	length = byte_pos + 1;
13706 
13707 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13708 	sensep = kmem_zalloc(length, KM_SLEEP);
13709 
13710 	cdb[0] = SCMD_REQUEST_SENSE;
13711 	cdb[1] = 0;
13712 	cdb[2] = 0;
13713 	cdb[3] = 0;
13714 	cdb[4] = (char)length;
13715 	cdb[5] = 0;
13716 
13717 	com->uscsi_cdb = cdb;
13718 	com->uscsi_cdblen = CDB_GROUP0;
13719 	com->uscsi_bufaddr = (caddr_t)sensep;
13720 	com->uscsi_buflen = length;
13721 	com->uscsi_flags =
13722 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13723 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13724 
13725 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13726 
13727 	if (rval || com->uscsi_status || com->uscsi_resid) {
13728 
13729 		rval = -1;
13730 
13731 	} else {
13732 
13733 		rval = MTF_TAPE_CLN_SUPPORTED;
13734 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
13735 
13736 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13737 			    "sense data says head dirty\n");
13738 			rval |= MTF_TAPE_HEAD_DIRTY;
13739 		}
13740 	}
13741 
13742 	kmem_free(com, sizeof (struct uscsi_cmd));
13743 	kmem_free(sensep, length);
13744 	return (rval);
13745 }
13746 
13747 /*
13748  * st_clear_unit_attention
13749  *
13750  *  	run test unit ready's to clear out outstanding
13751  * 	unit attentions.
13752  * 	returns zero for SUCCESS or the errno from st_cmd call
13753  */
13754 static int
13755 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
13756 {
13757 	int	i    = 0;
13758 	int	rval;
13759 
13760 	GET_SOFT_STATE(dev_instance);
13761 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
13762 
13763 	do {
13764 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
13765 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
13766 	return (rval);
13767 }
13768 
13769 static void
13770 st_calculate_timeouts(struct scsi_tape *un)
13771 {
13772 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
13773 
13774 	if (un->un_dp->non_motion_timeout == 0) {
13775 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13776 			un->un_dp->non_motion_timeout =
13777 			    st_io_time * st_long_timeout_x;
13778 		} else {
13779 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
13780 		}
13781 	}
13782 
13783 	if (un->un_dp->io_timeout == 0) {
13784 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13785 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
13786 		} else {
13787 			un->un_dp->io_timeout = (ushort_t)st_io_time;
13788 		}
13789 	}
13790 
13791 	if (un->un_dp->rewind_timeout == 0) {
13792 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13793 			un->un_dp->rewind_timeout =
13794 			    st_space_time * st_long_timeout_x;
13795 		} else {
13796 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
13797 		}
13798 	}
13799 
13800 	if (un->un_dp->space_timeout == 0) {
13801 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13802 			un->un_dp->space_timeout =
13803 			    st_space_time * st_long_timeout_x;
13804 		} else {
13805 			un->un_dp->space_timeout = (ushort_t)st_space_time;
13806 		}
13807 	}
13808 
13809 	if (un->un_dp->load_timeout == 0) {
13810 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13811 			un->un_dp->load_timeout =
13812 			    st_space_time * st_long_timeout_x;
13813 		} else {
13814 			un->un_dp->load_timeout = (ushort_t)st_space_time;
13815 		}
13816 	}
13817 
13818 	if (un->un_dp->unload_timeout == 0) {
13819 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13820 			un->un_dp->unload_timeout =
13821 			    st_space_time * st_long_timeout_x;
13822 		} else {
13823 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
13824 		}
13825 	}
13826 
13827 	if (un->un_dp->erase_timeout == 0) {
13828 		if (un->un_dp->options & ST_LONG_ERASE) {
13829 			un->un_dp->erase_timeout =
13830 			    st_space_time * st_long_space_time_x;
13831 		} else {
13832 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
13833 		}
13834 	}
13835 }
13836 
13837 
13838 static writablity
13839 st_is_not_wormable(struct scsi_tape *un)
13840 {
13841 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
13842 	return (RDWR);
13843 }
13844 
13845 static writablity
13846 st_is_hp_dat_tape_worm(struct scsi_tape *un)
13847 {
13848 	writablity wrt;
13849 
13850 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
13851 
13852 	/* Mode sense should be current */
13853 	if (un->un_mspl->media_type == 1) {
13854 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13855 		    "Drive has WORM media loaded\n");
13856 		wrt = WORM;
13857 	} else {
13858 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13859 		    "Drive has non WORM media loaded\n");
13860 		wrt = RDWR;
13861 	}
13862 	return (wrt);
13863 }
13864 
13865 #define	HP_DAT_INQUIRY 0x4A
13866 static writablity
13867 st_is_hp_dat_worm(struct scsi_tape *un)
13868 {
13869 	char *buf;
13870 	int result;
13871 	writablity wrt;
13872 
13873 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
13874 
13875 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
13876 
13877 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
13878 
13879 	if (result != 0) {
13880 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13881 		    "Read Standard Inquiry for WORM support failed");
13882 		wrt = FAILED;
13883 	} else if ((buf[40] & 1) == 0) {
13884 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13885 		    "Drive is NOT WORMable\n");
13886 		/* This drive doesn't support it so don't check again */
13887 		un->un_dp->options &= ~ST_WORMABLE;
13888 		wrt = RDWR;
13889 		un->un_wormable = st_is_not_wormable;
13890 	} else {
13891 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13892 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13893 		un->un_wormable = st_is_hp_dat_tape_worm;
13894 		wrt = un->un_wormable(un);
13895 	}
13896 
13897 	kmem_free(buf, HP_DAT_INQUIRY);
13898 
13899 	/*
13900 	 * If drive doesn't support it no point in checking further.
13901 	 */
13902 	return (wrt);
13903 }
13904 
13905 static writablity
13906 st_is_hp_lto_tape_worm(struct scsi_tape *un)
13907 {
13908 	writablity wrt;
13909 
13910 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
13911 
13912 	/* Mode sense should be current */
13913 	switch (un->un_mspl->media_type) {
13914 	case 0x00:
13915 		switch (un->un_mspl->density) {
13916 		case 0x40:
13917 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13918 			    "Drive has standard Gen I media loaded\n");
13919 			break;
13920 		case 0x42:
13921 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13922 			    "Drive has standard Gen II media loaded\n");
13923 			break;
13924 		case 0x44:
13925 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13926 			    "Drive has standard Gen III media loaded\n");
13927 			break;
13928 		case 0x46:
13929 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13930 			    "Drive has standard Gen IV media loaded\n");
13931 			break;
13932 		default:
13933 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13934 			    "Drive has standard unknown 0x%X media loaded\n",
13935 			    un->un_mspl->density);
13936 		}
13937 		wrt = RDWR;
13938 		break;
13939 	case 0x01:
13940 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13941 		    "Drive has WORM medium loaded\n");
13942 		wrt = WORM;
13943 		break;
13944 	case 0x80:
13945 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13946 		    "Drive has CD-ROM emulation medium loaded\n");
13947 		wrt = WORM;
13948 		break;
13949 	default:
13950 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13951 		    "Drive has an unexpected medium type 0x%X loaded\n",
13952 		    un->un_mspl->media_type);
13953 		wrt = RDWR;
13954 	}
13955 
13956 	return (wrt);
13957 }
13958 
13959 #define	LTO_REQ_INQUIRY 44
13960 static writablity
13961 st_is_hp_lto_worm(struct scsi_tape *un)
13962 {
13963 	char *buf;
13964 	int result;
13965 	writablity wrt;
13966 
13967 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
13968 
13969 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
13970 
13971 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
13972 
13973 	if (result != 0) {
13974 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13975 		    "Read Standard Inquiry for WORM support failed");
13976 		wrt = FAILED;
13977 	} else if ((buf[40] & 1) == 0) {
13978 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13979 		    "Drive is NOT WORMable\n");
13980 		/* This drive doesn't support it so don't check again */
13981 		un->un_dp->options &= ~ST_WORMABLE;
13982 		wrt = RDWR;
13983 		un->un_wormable = st_is_not_wormable;
13984 	} else {
13985 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13986 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13987 		un->un_wormable = st_is_hp_lto_tape_worm;
13988 		wrt = un->un_wormable(un);
13989 	}
13990 
13991 	kmem_free(buf, LTO_REQ_INQUIRY);
13992 
13993 	/*
13994 	 * If drive doesn't support it no point in checking further.
13995 	 */
13996 	return (wrt);
13997 }
13998 
13999 static writablity
14000 st_is_t10_worm_device(struct scsi_tape *un)
14001 {
14002 	writablity wrt;
14003 
14004 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
14005 
14006 	if (un->un_mspl->media_type == 0x3c) {
14007 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14008 		    "Drive has WORM media loaded\n");
14009 		wrt = WORM;
14010 	} else {
14011 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14012 		    "Drive has non WORM media loaded\n");
14013 		wrt = RDWR;
14014 	}
14015 	return (wrt);
14016 }
14017 
14018 #define	SEQ_CAP_PAGE	(char)0xb0
14019 static writablity
14020 st_is_t10_worm(struct scsi_tape *un)
14021 {
14022 	char *buf;
14023 	int result;
14024 	writablity wrt;
14025 
14026 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
14027 
14028 	buf = kmem_zalloc(6, KM_SLEEP);
14029 
14030 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
14031 
14032 	if (result != 0) {
14033 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14034 		    "Read Vitial Inquiry for Sequental Capability"
14035 		    " WORM support failed %x", result);
14036 		wrt = FAILED;
14037 	} else if ((buf[4] & 1) == 0) {
14038 		ASSERT(buf[1] == SEQ_CAP_PAGE);
14039 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14040 		    "Drive is NOT WORMable\n");
14041 		/* This drive doesn't support it so don't check again */
14042 		un->un_dp->options &= ~ST_WORMABLE;
14043 		wrt = RDWR;
14044 		un->un_wormable = st_is_not_wormable;
14045 	} else {
14046 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14047 		    "Drive supports WORM\n");
14048 		un->un_wormable = st_is_t10_worm_device;
14049 		wrt = un->un_wormable(un);
14050 	}
14051 
14052 	kmem_free(buf, 6);
14053 
14054 	return (wrt);
14055 }
14056 
14057 
14058 #define	STK_REQ_SENSE 26
14059 
14060 static writablity
14061 st_is_stk_worm(struct scsi_tape *un)
14062 {
14063 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
14064 	struct scsi_extended_sense *sense;
14065 	struct uscsi_cmd *cmd;
14066 	char *buf;
14067 	int result;
14068 	writablity wrt;
14069 
14070 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
14071 
14072 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14073 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
14074 	sense = (struct scsi_extended_sense *)buf;
14075 
14076 	cmd->uscsi_flags = USCSI_READ;
14077 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14078 	cmd->uscsi_cdb = &cdb[0];
14079 	cmd->uscsi_bufaddr = buf;
14080 	cmd->uscsi_buflen = STK_REQ_SENSE;
14081 	cmd->uscsi_cdblen = CDB_GROUP0;
14082 	cmd->uscsi_rqlen = 0;
14083 	cmd->uscsi_rqbuf = NULL;
14084 
14085 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14086 
14087 	if (result != 0 || cmd->uscsi_status != 0) {
14088 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14089 		    "Request Sense for WORM failed");
14090 		wrt = RDWR;
14091 	} else if (sense->es_add_len + 8 < 24) {
14092 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14093 		    "Drive didn't send enough sense data for WORM byte %d\n",
14094 		    sense->es_add_len + 8);
14095 		wrt = RDWR;
14096 		un->un_wormable = st_is_not_wormable;
14097 	} else if ((buf[24]) & 0x02) {
14098 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14099 		    "Drive has WORM tape loaded\n");
14100 		wrt = WORM;
14101 		un->un_wormable = st_is_stk_worm;
14102 	} else {
14103 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14104 		    "Drive has normal tape loaded\n");
14105 		wrt = RDWR;
14106 		un->un_wormable = st_is_stk_worm;
14107 	}
14108 
14109 	kmem_free(buf, STK_REQ_SENSE);
14110 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14111 	return (wrt);
14112 }
14113 
14114 #define	DLT_INQ_SZ 44
14115 
14116 static writablity
14117 st_is_dlt_tape_worm(struct scsi_tape *un)
14118 {
14119 	caddr_t buf;
14120 	int result;
14121 	writablity wrt;
14122 
14123 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
14124 
14125 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14126 
14127 	/* Read Attribute Media Type */
14128 
14129 	result = st_read_attributes(un, 0x0408, buf, 10, st_uscsi_cmd);
14130 
14131 	/*
14132 	 * If this quantum drive is attached via an HBA that cannot
14133 	 * support thr read attributes command return error in the
14134 	 * hope that someday they will support the t10 method.
14135 	 */
14136 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
14137 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14138 		    "Read Attribute Command for WORM Media detection is not "
14139 		    "supported on the HBA that this drive is attached to.");
14140 		wrt = RDWR;
14141 		un->un_wormable = st_is_not_wormable;
14142 		goto out;
14143 	}
14144 
14145 	if (result != 0) {
14146 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14147 		    "Read Attribute Command for WORM Media returned 0x%x",
14148 		    result);
14149 		wrt = RDWR;
14150 		un->un_dp->options &= ~ST_WORMABLE;
14151 		goto out;
14152 	}
14153 
14154 	if ((uchar_t)buf[9] == 0x80) {
14155 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14156 		    "Drive media is WORM\n");
14157 		wrt = WORM;
14158 	} else {
14159 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14160 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
14161 		wrt = RDWR;
14162 	}
14163 
14164 out:
14165 	kmem_free(buf, DLT_INQ_SZ);
14166 	return (wrt);
14167 }
14168 
14169 static writablity
14170 st_is_dlt_worm(struct scsi_tape *un)
14171 {
14172 	caddr_t buf;
14173 	int result;
14174 	writablity wrt;
14175 
14176 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
14177 
14178 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14179 
14180 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
14181 
14182 	if (result != 0) {
14183 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14184 		    "Read Vendor Specific Inquiry for WORM support failed");
14185 		wrt = RDWR;
14186 		goto out;
14187 	}
14188 
14189 	if ((buf[2] & 1) == 0) {
14190 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14191 		    "Drive is not WORMable\n");
14192 		wrt = RDWR;
14193 		un->un_dp->options &= ~ST_WORMABLE;
14194 		un->un_wormable = st_is_not_wormable;
14195 		goto out;
14196 	} else {
14197 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14198 		    "Drive is WORMable\n");
14199 		un->un_wormable = st_is_dlt_tape_worm;
14200 		wrt = un->un_wormable(un);
14201 	}
14202 out:
14203 	kmem_free(buf, DLT_INQ_SZ);
14204 
14205 	return (wrt);
14206 }
14207 
14208 typedef struct {
14209 	struct modeheader_seq header;
14210 #if defined(_BIT_FIELDS_LTOH) /* X86 */
14211 	uchar_t pagecode	:6,
14212 				:2;
14213 	uchar_t page_len;
14214 	uchar_t syslogalive	:2,
14215 		device		:1,
14216 		abs		:1,
14217 		ulpbot		:1,
14218 		prth		:1,
14219 		ponej		:1,
14220 		ait		:1;
14221 	uchar_t span;
14222 
14223 	uchar_t			:6,
14224 		worm		:1,
14225 		mic		:1;
14226 	uchar_t worm_cap	:1,
14227 				:7;
14228 	uint32_t		:32;
14229 #else /* SPARC */
14230 	uchar_t			:2,
14231 		pagecode	:6;
14232 	uchar_t page_len;
14233 	uchar_t ait		:1,
14234 		device		:1,
14235 		abs		:1,
14236 		ulpbot		:1,
14237 		prth		:1,
14238 		ponej		:1,
14239 		syslogalive	:2;
14240 	uchar_t span;
14241 	uchar_t mic		:1,
14242 		worm		:1,
14243 				:6;
14244 	uchar_t			:7,
14245 		worm_cap	:1;
14246 	uint32_t		:32;
14247 #endif
14248 }ait_dev_con;
14249 
14250 #define	AIT_DEV_PAGE 0x31
14251 static writablity
14252 st_is_sony_worm(struct scsi_tape *un)
14253 {
14254 	int result;
14255 	writablity wrt;
14256 	ait_dev_con *ait_conf;
14257 
14258 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14259 
14260 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
14261 
14262 	result = st_gen_mode_sense(un, st_uscsi_cmd, AIT_DEV_PAGE,
14263 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
14264 
14265 	if (result == 0) {
14266 
14267 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
14268 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14269 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
14270 			    ait_conf->pagecode, AIT_DEV_PAGE);
14271 			wrt = RDWR;
14272 			un->un_wormable = st_is_not_wormable;
14273 
14274 		} else if (ait_conf->worm_cap) {
14275 
14276 			un->un_wormable = st_is_sony_worm;
14277 
14278 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14279 			    "Drives is WORMable\n");
14280 			if (ait_conf->worm) {
14281 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14282 				    "Media is WORM\n");
14283 				wrt = WORM;
14284 			} else {
14285 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14286 				    "Media is not WORM\n");
14287 				wrt = RDWR;
14288 			}
14289 
14290 		} else {
14291 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14292 			    "Drives not is WORMable\n");
14293 			wrt = RDWR;
14294 			/* No further checking required */
14295 			un->un_dp->options &= ~ST_WORMABLE;
14296 		}
14297 
14298 	} else {
14299 
14300 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14301 		    "AIT device config mode sense page read command failed"
14302 		    " result = %d ", result);
14303 		wrt = FAILED;
14304 		un->un_wormable = st_is_not_wormable;
14305 	}
14306 
14307 	kmem_free(ait_conf, sizeof (ait_dev_con));
14308 	return (wrt);
14309 }
14310 
14311 static writablity
14312 st_is_drive_worm(struct scsi_tape *un)
14313 {
14314 	writablity wrt;
14315 
14316 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14317 
14318 	switch (un->un_dp->type) {
14319 	case MT_ISDLT:
14320 		wrt = st_is_dlt_worm(un);
14321 		break;
14322 
14323 	case MT_ISSTK9840:
14324 		wrt = st_is_stk_worm(un);
14325 		break;
14326 
14327 	case MT_IS8MM:
14328 	case MT_ISAIT:
14329 		wrt = st_is_sony_worm(un);
14330 		break;
14331 
14332 	case MT_LTO:
14333 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14334 			wrt = st_is_hp_lto_worm(un);
14335 		} else {
14336 			wrt = st_is_t10_worm(un);
14337 		}
14338 		break;
14339 
14340 	case MT_ISDAT:
14341 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14342 			wrt = st_is_hp_dat_worm(un);
14343 		} else {
14344 			wrt = st_is_t10_worm(un);
14345 		}
14346 		break;
14347 
14348 	default:
14349 		wrt = FAILED;
14350 		break;
14351 	}
14352 
14353 	/*
14354 	 * If any of the above failed try the t10 standard method.
14355 	 */
14356 	if (wrt == FAILED) {
14357 		wrt = st_is_t10_worm(un);
14358 	}
14359 
14360 	/*
14361 	 * Unknown method for detecting WORM media.
14362 	 */
14363 	if (wrt == FAILED) {
14364 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14365 		    "Unknown method for WORM media detection\n");
14366 		wrt = RDWR;
14367 		un->un_dp->options &= ~ST_WORMABLE;
14368 	}
14369 
14370 	return (wrt);
14371 }
14372 
14373 static int
14374 st_read_attributes(struct scsi_tape *un, uint16_t attribute, void *pnt,
14375     size_t size, ubufunc_t bufunc)
14376 {
14377 	char cdb[CDB_GROUP4];
14378 	int result;
14379 	struct uscsi_cmd *cmd;
14380 	struct scsi_arq_status status;
14381 
14382 	caddr_t buf = (caddr_t)pnt;
14383 
14384 	ST_FUNC(ST_DEVINFO, st_read_attributes);
14385 
14386 	if (un->un_sd->sd_inq->inq_ansi < 3) {
14387 		return (ENOTTY);
14388 	}
14389 
14390 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14391 
14392 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
14393 	cdb[1] = 0;
14394 	cdb[2] = 0;
14395 	cdb[3] = 0;
14396 	cdb[4] = 0;
14397 	cdb[5] = 0;
14398 	cdb[6] = 0;
14399 	cdb[7] = 0;
14400 	cdb[8] = (char)(attribute >> 8);
14401 	cdb[9] = (char)(attribute);
14402 	cdb[10] = (char)(size >> 24);
14403 	cdb[11] = (char)(size >> 16);
14404 	cdb[12] = (char)(size >> 8);
14405 	cdb[13] = (char)(size);
14406 	cdb[14] = 0;
14407 	cdb[15] = 0;
14408 
14409 
14410 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE | USCSI_DIAGNOSE;
14411 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14412 	cmd->uscsi_cdb = &cdb[0];
14413 	cmd->uscsi_bufaddr = (caddr_t)buf;
14414 	cmd->uscsi_buflen = size;
14415 	cmd->uscsi_cdblen = sizeof (cdb);
14416 	cmd->uscsi_rqlen = sizeof (status);
14417 	cmd->uscsi_rqbuf = (caddr_t)&status;
14418 
14419 	result = bufunc(un, cmd, FKIOCTL);
14420 
14421 	if (result != 0 || cmd->uscsi_status != 0) {
14422 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
14423 		    "st_read_attribute failed: result %d status %d\n",
14424 		    result, cmd->uscsi_status);
14425 		/*
14426 		 * If this returns invalid operation code don't try again.
14427 		 */
14428 		if (un->un_sd->sd_sense->es_key == KEY_ILLEGAL_REQUEST &&
14429 		    un->un_sd->sd_sense->es_add_code == 0x20) {
14430 			result = ENOTTY;
14431 		} else if (result == 0) {
14432 			result = EIO;
14433 		}
14434 
14435 	} else {
14436 
14437 		/*
14438 		 * The attribute retured should match the attribute requested.
14439 		 */
14440 		if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
14441 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14442 			    "st_read_attribute got wrong data back expected "
14443 			    "0x%x got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
14444 			st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14445 			    "bad? data", buf, size);
14446 			result = EIO;
14447 		}
14448 	}
14449 
14450 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14451 
14452 	return (result);
14453 }
14454 
14455 static int
14456 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
14457     uchar_t page)
14458 {
14459 	char cdb[CDB_GROUP0];
14460 	struct scsi_extended_sense *sense;
14461 	struct uscsi_cmd *cmd;
14462 	int result;
14463 
14464 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
14465 
14466 	cdb[0] = SCMD_INQUIRY;
14467 	cdb[1] = page ? 1 : 0;
14468 	cdb[2] = page;
14469 	cdb[3] = 0;
14470 	cdb[4] = size;
14471 	cdb[5] = 0;
14472 
14473 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14474 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
14475 
14476 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
14477 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14478 	cmd->uscsi_cdb = &cdb[0];
14479 	cmd->uscsi_bufaddr = dest;
14480 	cmd->uscsi_buflen = size;
14481 	cmd->uscsi_cdblen = CDB_GROUP0;
14482 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
14483 	cmd->uscsi_rqbuf = (caddr_t)sense;
14484 
14485 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14486 
14487 	if (result != 0 || cmd->uscsi_status != 0) {
14488 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14489 		    "st_get_special_inquiry() failed for page %x", page);
14490 		if (result == 0) {
14491 			result = EIO;
14492 		}
14493 	}
14494 
14495 	kmem_free(sense, sizeof (struct scsi_extended_sense));
14496 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14497 
14498 	return (result);
14499 }
14500 
14501 
14502 static int
14503 st_update_block_pos(struct scsi_tape *un, bufunc_t bf, int post_space)
14504 {
14505 	int rval = ENOTTY;
14506 	uchar_t status = un->un_status;
14507 	posmode previous_pmode = un->un_running.pmode;
14508 
14509 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
14510 
14511 	while (un->un_read_pos_type != NO_POS) {
14512 		rval = bf(un, SCMD_READ_POSITION, 32, SYNC_CMD);
14513 
14514 		/*
14515 		 * If read position command returned good status
14516 		 * Parse the data to see if the position can be interpreted.
14517 		 */
14518 		if ((rval == 0) &&
14519 		    ((rval = st_interpret_read_pos(un, &un->un_pos,
14520 		    un->un_read_pos_type, 32, (caddr_t)un->un_read_pos_data,
14521 		    post_space)) == 0)) {
14522 			/*
14523 			 * Update the running position as well if un_pos was
14524 			 * ok. But only if recovery is enabled.
14525 			 */
14526 			if (st_recov_sz != sizeof (recov_info)) {
14527 				break;
14528 			}
14529 			rval = st_interpret_read_pos(un, &un->un_running,
14530 			    un->un_read_pos_type, 32,
14531 			    (caddr_t)un->un_read_pos_data, post_space);
14532 			un->un_status = status;
14533 			break;
14534 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
14535 			un->un_running.pmode = previous_pmode;
14536 			continue;
14537 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
14538 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
14539 			    "st_update_block_pos() read position cmd 0x%x"
14540 			    " returned 0x%x un_status = %d",
14541 			    un->un_read_pos_type, rval, un->un_status);
14542 			/* ENOTTY means it read garbage. try something else. */
14543 			if (rval == ENOTTY) {
14544 				rval = EIO; /* so ENOTTY is not final rval */
14545 			} else {
14546 				break;
14547 			}
14548 		} else {
14549 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
14550 			    "st_update_block_pos() read position cmd %x"
14551 			    " returned %x", un->un_read_pos_type, rval);
14552 			un->un_running.pmode = previous_pmode;
14553 		}
14554 
14555 		switch (un->un_read_pos_type) {
14556 		case SHORT_POS:
14557 			un->un_read_pos_type = NO_POS;
14558 			break;
14559 
14560 		case LONG_POS:
14561 			un->un_read_pos_type = EXT_POS;
14562 			break;
14563 
14564 		case EXT_POS:
14565 			un->un_read_pos_type = SHORT_POS;
14566 			break;
14567 
14568 		default:
14569 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14570 			    "Unexpected read position type 0x%x",
14571 			    un->un_read_pos_type);
14572 		}
14573 		un->un_status = KEY_NO_SENSE;
14574 	}
14575 
14576 	return (rval);
14577 }
14578 
14579 static int
14580 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
14581 {
14582 	int result;
14583 	size_t d_sz;
14584 	caddr_t pos_info;
14585 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
14586 
14587 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
14588 
14589 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
14590 		return (0);
14591 	}
14592 
14593 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
14594 
14595 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14596 		    "bp_mapin_common() failed");
14597 
14598 		return (EIO);
14599 	}
14600 
14601 	d_sz = bp->b_bcount - bp->b_resid;
14602 	if (d_sz == 0) {
14603 		bp_mapout(bp);
14604 		return (EIO);
14605 	}
14606 
14607 	/*
14608 	 * Copy the buf to a double-word aligned memory that can hold the
14609 	 * tape_position_t data structure.
14610 	 */
14611 	if ((pos_info = kmem_alloc(d_sz, KM_NOSLEEP)) == NULL) {
14612 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14613 		    "kmem_alloc() failed");
14614 		bp_mapout(bp);
14615 		return (EIO);
14616 	}
14617 	bcopy(bp->b_un.b_addr, pos_info, d_sz);
14618 
14619 #ifdef STDEBUG
14620 	if ((st_debug & 0x7) > 2) {
14621 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14622 		    "st_get_read_pos() position info",
14623 		    pos_info, bp->b_bcount);
14624 	}
14625 #endif
14626 
14627 	result = st_interpret_read_pos(un, &un->un_pos, cmd->uscsi_cdb[1],
14628 	    d_sz, pos_info, 0);
14629 
14630 	COPY_POS(&un->un_running, &un->un_pos);
14631 
14632 	kmem_free(pos_info, d_sz);
14633 	bp_mapout(bp);
14634 
14635 	return (result);
14636 }
14637 
14638 #if defined(_BIG_ENDIAN)
14639 
14640 #define	FIX_ENDIAN16(x)
14641 #define	FIX_ENDIAN32(x)
14642 #define	FIX_ENDIAN64(x)
14643 
14644 #elif defined(_LITTLE_ENDIAN)
14645 
14646 static void
14647 st_swap16(uint16_t *val)
14648 {
14649 	uint16_t tmp;
14650 
14651 	tmp = (*val >>  8) & 0xff;
14652 	tmp |= (*val <<  8) & 0xff00;
14653 
14654 	*val = tmp;
14655 }
14656 
14657 static void
14658 st_swap32(uint32_t *val)
14659 {
14660 	uint32_t tmp;
14661 
14662 	tmp =  (*val >> 24) & 0xff;
14663 	tmp |= (*val >>  8) & 0xff00;
14664 	tmp |= (*val <<  8) & 0xff0000;
14665 	tmp |= (*val << 24) & 0xff000000;
14666 
14667 	*val = tmp;
14668 }
14669 
14670 static void
14671 st_swap64(uint64_t *val)
14672 {
14673 	uint32_t low;
14674 	uint32_t high;
14675 
14676 	low =  (uint32_t)(*val);
14677 	high = (uint32_t)(*val >> 32);
14678 
14679 	st_swap32(&low);
14680 	st_swap32(&high);
14681 
14682 	*val =  high;
14683 	*val |= ((uint64_t)low << 32);
14684 }
14685 
14686 #define	FIX_ENDIAN16(x) st_swap16(x)
14687 #define	FIX_ENDIAN32(x) st_swap32(x)
14688 #define	FIX_ENDIAN64(x) st_swap64(x)
14689 #endif
14690 
14691 /*
14692  * st_interpret_read_pos()
14693  *
14694  * Returns:
14695  *	0	If secsessful.
14696  *	EIO	If read postion responce data was unuseable or invalid.
14697  *	ERANGE	If the position of the drive is too large for the read_p_type.
14698  *	ENOTTY	If the responce data looks invalid for the read position type.
14699  */
14700 
14701 static int
14702 st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
14703     read_p_types type, size_t data_sz, const caddr_t responce, int post_space)
14704 {
14705 	int rval = 0;
14706 	int flag = 0;
14707 	tapepos_t org;
14708 
14709 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
14710 
14711 	/*
14712 	 * We expect the position value to change after a space command.
14713 	 * So if post_space is set we don't print out what has changed.
14714 	 */
14715 	if ((dest != &un->un_pos) && (post_space == 0) &&
14716 	    (st_recov_sz == sizeof (recov_info))) {
14717 		COPY_POS(&org, dest);
14718 		flag = 1;
14719 	}
14720 
14721 	/*
14722 	 * See what kind of read position was requested.
14723 	 */
14724 	switch (type) {
14725 
14726 	case SHORT_POS: /* Short data format */
14727 	{
14728 		tape_position_t *pos_info = (tape_position_t *)responce;
14729 		uint32_t value;
14730 
14731 		/* If reserved fields are non zero don't use the data */
14732 		if (pos_info->reserved0 || pos_info->reserved1 ||
14733 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
14734 		    pos_info->reserved3) {
14735 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14736 			    "Invalid Read Short Position Data returned\n");
14737 			rval = EIO;
14738 			break;
14739 		}
14740 		/*
14741 		 * Position is to large to use this type of read position.
14742 		 */
14743 		if (pos_info->posi_err == 1) {
14744 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14745 			    "Drive reported position error\n");
14746 			rval = ERANGE;
14747 			break;
14748 		}
14749 		/*
14750 		 * If your at the begining of partition and end at the same
14751 		 * time it's very small partition or bad data.
14752 		 */
14753 		if (pos_info->begin_of_part && pos_info->end_of_part) {
14754 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14755 			    "SHORT_POS returned begin and end of"
14756 			    " partition\n");
14757 			rval = EIO;
14758 			break;
14759 		}
14760 
14761 		if (pos_info->blk_posi_unkwn == 0) {
14762 
14763 			value = pos_info->host_block;
14764 			FIX_ENDIAN32(&value);
14765 
14766 			/*
14767 			 * If the tape is rewound the host blcok should be 0.
14768 			 */
14769 			if ((pos_info->begin_of_part == 1) &&
14770 			    (value != 0)) {
14771 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14772 				    "SHORT_POS returned begin of partition"
14773 				    " but host block was 0x%x\n", value);
14774 				rval = EIO;
14775 				break;
14776 			}
14777 
14778 			if (dest->lgclblkno != value) {
14779 				if (flag)
14780 					flag++;
14781 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14782 				    "SHORT_POS current logical 0x%"PRIx64" read"
14783 				    " 0x%x\n", dest->lgclblkno, value);
14784 			}
14785 
14786 			dest->lgclblkno = (uint64_t)value;
14787 
14788 			/*
14789 			 * If the begining of partition is true and the
14790 			 * block number is zero we will beleive that it is
14791 			 * rewound. Promote the pmode to legacy.
14792 			 */
14793 			if ((pos_info->begin_of_part == 1) &&
14794 			    (value == 0)) {
14795 				dest->blkno = 0;
14796 				dest->fileno = 0;
14797 				if (dest->pmode != legacy)
14798 					dest->pmode = legacy;
14799 			/*
14800 			 * otherwise if the pmode was invalid,
14801 			 * promote it to logical.
14802 			 */
14803 			} else if (dest->pmode == invalid) {
14804 				dest->pmode = logical;
14805 			}
14806 
14807 			if (dest->partition != pos_info->partition_number) {
14808 				if (flag)
14809 					flag++;
14810 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14811 				    "SHORT_POS current partition %d read %d\n",
14812 				    dest->partition,
14813 				    pos_info->partition_number);
14814 			}
14815 
14816 			dest->partition = pos_info->partition_number;
14817 
14818 		} else {
14819 			dest->pmode = invalid;
14820 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14821 			    "Tape drive reported block position as unknown\n");
14822 		}
14823 		break;
14824 	}
14825 
14826 	case LONG_POS: /* Long data format */
14827 	{
14828 		uint64_t value;
14829 		tape_position_long_t *long_pos_info =
14830 		    (tape_position_long_t *)responce;
14831 
14832 		/* If reserved fields are non zero don't use the data */
14833 		if ((long_pos_info->reserved0) ||
14834 		    (long_pos_info->reserved1) ||
14835 		    (long_pos_info->reserved2)) {
14836 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14837 			    "Invalid Read Long Position Data returned\n");
14838 			rval = ENOTTY;
14839 			break;
14840 		}
14841 
14842 		/* Is position Valid */
14843 		if (long_pos_info->blk_posi_unkwn == 0) {
14844 			uint32_t part;
14845 
14846 			value = long_pos_info->block_number;
14847 			FIX_ENDIAN64(&value);
14848 
14849 			/*
14850 			 * If it says we are at the begining of partition
14851 			 * the block value better be 0.
14852 			 */
14853 			if ((long_pos_info->begin_of_part == 1) &&
14854 			    (value != 0)) {
14855 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14856 				    "LONG_POS returned begin of partition but"
14857 				    " block number was 0x%"PRIx64"\n", value);
14858 				rval = ENOTTY;
14859 				break;
14860 			}
14861 			/*
14862 			 * Can't be at the start and the end of the partition
14863 			 * at the same time if the partition is larger the 0.
14864 			 */
14865 			if (long_pos_info->begin_of_part &&
14866 			    long_pos_info->end_of_part) {
14867 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14868 				    "LONG_POS returned begin and end of"
14869 				    " partition\n");
14870 				rval = ENOTTY;
14871 				break;
14872 			}
14873 
14874 			/*
14875 			 * If the logical block number is not what we expected.
14876 			 */
14877 			if (dest->lgclblkno != value) {
14878 				if (flag)
14879 					flag++;
14880 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14881 				    "LONG_POS current logical 0x%"PRIx64
14882 				    " read 0x%"PRIx64"\n",
14883 				    dest->lgclblkno, value);
14884 			}
14885 			dest->lgclblkno = value;
14886 
14887 			/*
14888 			 * If the begining of partition is true and the
14889 			 * block number is zero we will beleive that it is
14890 			 * rewound. Promote the pmode to legacy.
14891 			 */
14892 			if ((long_pos_info->begin_of_part == 1) &&
14893 			    (long_pos_info->block_number == 0)) {
14894 				dest->blkno = 0;
14895 				dest->fileno = 0;
14896 				if (dest->pmode != legacy)
14897 					dest->pmode = legacy;
14898 			/*
14899 			 * otherwise if the pmode was invalid,
14900 			 * promote it to logical.
14901 			 */
14902 			} else if (dest->pmode == invalid) {
14903 				dest->pmode = logical;
14904 			}
14905 
14906 			part = long_pos_info->partition;
14907 			FIX_ENDIAN32(&part);
14908 			if (dest->partition != part) {
14909 				if (flag)
14910 					flag++;
14911 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14912 				    "LONG_POS current partition %d"
14913 				    " read %d\n", dest->partition, part);
14914 			}
14915 			dest->partition = part;
14916 		} else {
14917 			/*
14918 			 * If the drive doesn't know location,
14919 			 * we don't either.
14920 			 */
14921 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14922 			    "Tape drive reported block position as unknown\n");
14923 			dest->pmode = invalid;
14924 		}
14925 
14926 		/* Is file position valid */
14927 		if (long_pos_info->mrk_posi_unkwn == 0) {
14928 			value = long_pos_info->file_number;
14929 			FIX_ENDIAN64(&value);
14930 			/*
14931 			 * If it says we are at the begining of partition
14932 			 * the block value better be 0.
14933 			 */
14934 			if ((long_pos_info->begin_of_part == 1) &&
14935 			    (value != 0)) {
14936 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14937 				    "LONG_POS returned begin of partition but"
14938 				    " block number was 0x%"PRIx64"\n", value);
14939 				rval = ENOTTY;
14940 				break;
14941 			}
14942 			if (((dest->pmode == legacy) ||
14943 			    (dest->pmode == logical)) &&
14944 			    (dest->fileno != value)) {
14945 				if (flag)
14946 					flag++;
14947 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14948 				    "LONG_POS fileno 0x%"PRIx64
14949 				    " not un_pos %x\n", value,
14950 				    dest->fileno);
14951 			} else if (dest->pmode == invalid) {
14952 				dest->pmode = logical;
14953 			}
14954 			dest->fileno = (int32_t)value;
14955 		}
14956 
14957 		if (dest->pmode != invalid && long_pos_info->end_of_part) {
14958 			dest->eof = ST_EOT;
14959 		}
14960 
14961 		break;
14962 	}
14963 
14964 	case EXT_POS: /* Extended data format */
14965 	{
14966 		uint64_t value;
14967 		uint16_t len;
14968 		tape_position_ext_t *ext_pos_info =
14969 		    (tape_position_ext_t *)responce;
14970 
14971 		/* Make sure that there is enough data there */
14972 		if (data_sz < 16) {
14973 			break;
14974 		}
14975 
14976 		/* If reserved fields are non zero don't use the data */
14977 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
14978 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14979 			    "EXT_POS reserved fields not zero\n");
14980 			rval = ENOTTY;
14981 			break;
14982 		}
14983 
14984 		/*
14985 		 * In the unlikely event of overflowing 64 bits of position.
14986 		 */
14987 		if (ext_pos_info->posi_err != 0) {
14988 			rval = ERANGE;
14989 			break;
14990 		}
14991 
14992 		len = ext_pos_info->parameter_len;
14993 		FIX_ENDIAN16(&len);
14994 
14995 		if (len != 0x1c) {
14996 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14997 			    "EXT_POS parameter_len should be 0x1c was 0x%x\n",
14998 			    len);
14999 			rval = ENOTTY;
15000 			break;
15001 		}
15002 
15003 		/* Is block position information valid */
15004 		if (ext_pos_info->blk_posi_unkwn == 0) {
15005 
15006 			value = ext_pos_info->host_block;
15007 			FIX_ENDIAN64(&value);
15008 			if ((ext_pos_info->begin_of_part == 1) &&
15009 			    (value != 0)) {
15010 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15011 				    "EXT_POS returned begining of partition but"
15012 				    " the host block was 0x%"PRIx64"\n", value);
15013 				rval = ENOTTY;
15014 				break;
15015 			}
15016 
15017 			if (dest->lgclblkno != value) {
15018 				if (flag)
15019 					flag++;
15020 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15021 				    "EXT_POS current logical 0x%"PRIx64
15022 				    " read 0x%"PRIx64"\n",
15023 				    dest->lgclblkno, value);
15024 			}
15025 			dest->lgclblkno = value;
15026 
15027 			/*
15028 			 * If the begining of partition is true and the
15029 			 * block number is zero we will beleive that it is
15030 			 * rewound. Promote the pmode to legacy.
15031 			 */
15032 			if ((ext_pos_info->begin_of_part == 1) &&
15033 			    (ext_pos_info->host_block == 0)) {
15034 				dest->blkno = 0;
15035 				dest->fileno = 0;
15036 				if (dest->pmode != legacy) {
15037 					dest->pmode = legacy;
15038 				}
15039 			/*
15040 			 * otherwise if the pmode was invalid,
15041 			 * promote it to logical.
15042 			 */
15043 			} else if (dest->pmode == invalid) {
15044 				dest->pmode = logical;
15045 			}
15046 
15047 			if (dest->partition != ext_pos_info->partition) {
15048 				if (flag)
15049 					flag++;
15050 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15051 				    "EXT_POS current partition %d read %d\n",
15052 				    dest->partition,
15053 				    ext_pos_info->partition);
15054 			}
15055 			dest->partition = ext_pos_info->partition;
15056 
15057 		} else {
15058 			dest->pmode = invalid;
15059 		}
15060 		break;
15061 	}
15062 
15063 	default:
15064 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15065 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
15066 		rval = EIO;
15067 	}
15068 
15069 	if ((flag > 1) && (rval == 0) && (org.pmode != invalid)) {
15070 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
15071 		    "position read in", &org);
15072 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
15073 		    "position read out", dest);
15074 	}
15075 
15076 	return (rval);
15077 }
15078 
15079 static int
15080 st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos,
15081     uint64_t lblk, uchar_t partition)
15082 {
15083 	int rval;
15084 	char cdb[CDB_GROUP4];
15085 	struct uscsi_cmd *cmd;
15086 	struct scsi_extended_sense sense;
15087 	bufunc_t bf = (ubf == st_uscsi_cmd) ? st_cmd : st_rcmd;
15088 
15089 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
15090 	/*
15091 	 * Not sure what to do when doing recovery and not wanting
15092 	 * to update un_pos
15093 	 */
15094 
15095 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
15096 
15097 	if (lblk <= INT32_MAX) {
15098 		cmd->uscsi_cdblen = CDB_GROUP1;
15099 		cdb[0] = SCMD_LOCATE;
15100 		cdb[1] = pos->partition == partition ? 0 : 2;
15101 		cdb[2] = 0;
15102 		cdb[3] = (char)(lblk >> 24);
15103 		cdb[4] = (char)(lblk >> 16);
15104 		cdb[5] = (char)(lblk >> 8);
15105 		cdb[6] = (char)(lblk);
15106 		cdb[7] = 0;
15107 		cdb[8] = partition;
15108 		cdb[9] = 0;
15109 	} else {
15110 		/*
15111 		 * If the drive doesn't give a 64 bit read position data
15112 		 * it is unlikely it will accept 64 bit locates.
15113 		 */
15114 		if (un->un_read_pos_type != LONG_POS) {
15115 			kmem_free(cmd, sizeof (struct uscsi_cmd));
15116 			return (ERANGE);
15117 		}
15118 		cmd->uscsi_cdblen = CDB_GROUP4;
15119 		cdb[0] = (char)SCMD_LOCATE_G4;
15120 		cdb[1] = pos->partition == partition ? 0 : 2;
15121 		cdb[2] = 0;
15122 		cdb[3] = partition;
15123 		cdb[4] = (char)(lblk >> 56);
15124 		cdb[5] = (char)(lblk >> 48);
15125 		cdb[6] = (char)(lblk >> 40);
15126 		cdb[7] = (char)(lblk >> 32);
15127 		cdb[8] = (char)(lblk >> 24);
15128 		cdb[9] = (char)(lblk >> 16);
15129 		cdb[10] = (char)(lblk >> 8);
15130 		cdb[11] = (char)(lblk);
15131 		cdb[12] = 0;
15132 		cdb[13] = 0;
15133 		cdb[14] = 0;
15134 		cdb[15] = 0;
15135 	}
15136 
15137 
15138 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
15139 	cmd->uscsi_rqbuf = (caddr_t)&sense;
15140 	cmd->uscsi_rqlen = sizeof (sense);
15141 	cmd->uscsi_timeout = un->un_dp->space_timeout;
15142 	cmd->uscsi_cdb = cdb;
15143 
15144 	rval = ubf(un, cmd, FKIOCTL);
15145 
15146 	pos->pmode = logical;
15147 	pos->eof = ST_NO_EOF;
15148 
15149 	if (lblk > INT32_MAX) {
15150 		/*
15151 		 * XXX This is a work around till we handle Descriptor format
15152 		 * sense data. Since we are sending a command where the standard
15153 		 * sense data can not correctly represent a correct residual in
15154 		 * 4 bytes.
15155 		 */
15156 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
15157 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15158 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
15159 			/* Doesn't like big locate command */
15160 			un->un_status = 0;
15161 			rval = ERANGE;
15162 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
15163 			/* Aborted big locate command */
15164 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15165 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
15166 			    rval);
15167 			un->un_status = 0;
15168 			rval = EIO;
15169 		} else if (st_update_block_pos(un, bf, 1)) {
15170 			/* read position failed */
15171 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15172 			    "Big LOCATE and read pos: rval = %d\n", rval);
15173 			rval = EIO;
15174 		} else if (lblk > un->un_pos.lgclblkno) {
15175 			/* read position worked but position was not expected */
15176 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15177 			    "Big LOCATE and recover read less then desired 0x%"
15178 			    PRIx64"\n", un->un_pos.lgclblkno);
15179 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
15180 			un->un_status = KEY_BLANK_CHECK;
15181 			rval = ESPIPE;
15182 		} else if (lblk == un->un_pos.lgclblkno) {
15183 			/* read position was what was expected */
15184 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15185 			    "Big LOCATE and recover seems to have worked\n");
15186 			un->un_err_resid = 0;
15187 			rval = 0;
15188 		} else {
15189 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15190 			    "BIGLOCATE end up going backwards");
15191 			un->un_err_resid = lblk;
15192 			rval = EIO;
15193 		}
15194 
15195 	} else if (rval == 0) {
15196 		/* Worked as requested */
15197 		pos->lgclblkno = lblk;
15198 
15199 	} else if (((cmd->uscsi_status & ST_STATUS_MASK) == STATUS_CHECK) &&
15200 	    (cmd->uscsi_resid != 0)) {
15201 		/* Got part way there but wasn't enough blocks on tape */
15202 		pos->lgclblkno = lblk - cmd->uscsi_resid;
15203 		un->un_err_resid = cmd->uscsi_resid;
15204 		un->un_status = KEY_BLANK_CHECK;
15205 		rval = ESPIPE;
15206 
15207 	} else if (st_update_block_pos(un, bf, 1) == 0) {
15208 		/* Got part way there but drive didn't tell what we missed by */
15209 		un->un_err_resid = lblk - pos->lgclblkno;
15210 		un->un_status = KEY_BLANK_CHECK;
15211 		rval = ESPIPE;
15212 
15213 	} else {
15214 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15215 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
15216 		    rval, cmd->uscsi_status);
15217 		un->un_err_resid = lblk;
15218 		un->un_status = KEY_ILLEGAL_REQUEST;
15219 		pos->pmode = invalid;
15220 		rval = EIO;
15221 	}
15222 
15223 	kmem_free(cmd, sizeof (struct uscsi_cmd));
15224 
15225 	return (rval);
15226 }
15227 
15228 static int
15229 st_mtfsf_ioctl(struct scsi_tape *un, int64_t files)
15230 {
15231 	int rval;
15232 
15233 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
15234 
15235 
15236 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15237 	    "st_mtfsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15238 #if 0
15239 	if ((IN_EOF(un->un_pos)) && (files == 1)) {
15240 		un->un_pos.fileno++;
15241 		un->un_pos.blkno = 0;
15242 		return (0);
15243 	}
15244 #endif
15245 	/* pmode == invalid already handled */
15246 	if (un->un_pos.pmode == legacy) {
15247 		/*
15248 		 * forward space over filemark
15249 		 *
15250 		 * For ASF we allow a count of 0 on fsf which means
15251 		 * we just want to go to beginning of current file.
15252 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
15253 		 * Allow stepping over double fmk with reel
15254 		 */
15255 		if ((un->un_pos.eof >= ST_EOT) &&
15256 		    (files > 0) &&
15257 		    ((un->un_dp->options & ST_REEL) == 0)) {
15258 			/* we're at EOM */
15259 			un->un_err_resid = files;
15260 			un->un_status = KEY_BLANK_CHECK;
15261 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15262 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
15263 			return (EIO);
15264 		}
15265 
15266 		/*
15267 		 * physical tape position may not be what we've been
15268 		 * telling the user; adjust the request accordingly
15269 		 */
15270 		if (IN_EOF(un->un_pos)) {
15271 			un->un_pos.fileno++;
15272 			un->un_pos.blkno = 0;
15273 			/*
15274 			 * For positive direction case, we're now covered.
15275 			 * For zero or negative direction, we're covered
15276 			 * (almost)
15277 			 */
15278 			files--;
15279 		}
15280 
15281 	}
15282 
15283 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15284 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15285 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
15286 		return (EIO);
15287 	}
15288 
15289 
15290 	/*
15291 	 * Forward space file marks.
15292 	 * We leave ourselves at block zero
15293 	 * of the target file number.
15294 	 */
15295 	if (files < 0) {
15296 		rval = st_backward_space_files(un, -files, 0);
15297 	} else {
15298 		rval = st_forward_space_files(un, files);
15299 	}
15300 
15301 	return (rval);
15302 }
15303 
15304 static int
15305 st_forward_space_files(struct scsi_tape *un, int64_t count)
15306 {
15307 	int rval;
15308 
15309 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
15310 
15311 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15312 	    "fspace: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15313 
15314 	ASSERT(count >= 0);
15315 	ASSERT(un->un_pos.pmode != invalid);
15316 
15317 	/*
15318 	 * A space with a count of zero means take me to the start of file.
15319 	 */
15320 	if (count == 0) {
15321 
15322 		/* Hay look were already there */
15323 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0) {
15324 			un->un_err_resid = 0;
15325 			COPY_POS(&un->un_err_pos, &un->un_pos);
15326 			return (0);
15327 		}
15328 
15329 		/*
15330 		 * Well we are in the first file.
15331 		 * A rewind will get to the start.
15332 		 */
15333 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
15334 			rval = st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
15335 
15336 		/*
15337 		 * Can we backspace to get there?
15338 		 * This should work in logical mode.
15339 		 */
15340 		} else if (un->un_dp->options & ST_BSF) {
15341 			rval = st_space_to_begining_of_file(un);
15342 
15343 		/*
15344 		 * Can't back space but current file number is known,
15345 		 * So rewind and space from the begining of the partition.
15346 		 */
15347 		} else if (un->un_pos.pmode == legacy) {
15348 			rval = st_scenic_route_to_begining_of_file(un,
15349 			    un->un_pos.fileno);
15350 
15351 		/*
15352 		 * pmode is logical and ST_BSF is not set.
15353 		 * The LONG_POS read position contains the fileno.
15354 		 * If the read position works, rewind and space.
15355 		 */
15356 		} else if (un->un_read_pos_type == LONG_POS) {
15357 			rval = st_cmd(un, SCMD_READ_POSITION, 0, SYNC_CMD);
15358 			if (rval) {
15359 				/*
15360 				 * We didn't get the file position from the
15361 				 * read position command.
15362 				 * We are going to trust the drive to backspace
15363 				 * and then position after the filemark.
15364 				 */
15365 				rval = st_space_to_begining_of_file(un);
15366 			}
15367 			rval = st_interpret_read_pos(un, &un->un_pos, LONG_POS,
15368 			    32, (caddr_t)un->un_read_pos_data, 0);
15369 			if ((rval) && (un->un_pos.pmode == invalid)) {
15370 				rval = st_space_to_begining_of_file(un);
15371 			} else {
15372 				rval = st_scenic_route_to_begining_of_file(un,
15373 				    un->un_pos.fileno);
15374 			}
15375 		} else {
15376 			rval = EIO;
15377 		}
15378 		/*
15379 		 * If something didn't work we are lost
15380 		 */
15381 		if (rval != 0) {
15382 			un->un_pos.pmode = invalid;
15383 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15384 			    "st_mtioctop : EIO : fspace pmode invalid");
15385 
15386 			rval = EIO;
15387 		}
15388 
15389 	} else {
15390 		rval = st_space_fmks(un, count);
15391 	}
15392 
15393 	if (rval != EIO && count < 0) {
15394 		/*
15395 		 * we came here with a count < 0; we now need
15396 		 * to skip back to end up before the filemark
15397 		 */
15398 		rval = st_backward_space_files(un, 1, 1);
15399 	}
15400 
15401 	return (rval);
15402 }
15403 
15404 static int
15405 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
15406 {
15407 	int rval;
15408 
15409 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
15410 
15411 	if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15412 		rval = EIO;
15413 	} else if (st_cmd(un, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
15414 		rval = EIO;
15415 	}
15416 
15417 	return (rval);
15418 }
15419 
15420 static int
15421 st_space_to_begining_of_file(struct scsi_tape *un)
15422 {
15423 	int rval;
15424 
15425 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
15426 
15427 	/*
15428 	 * Back space of the file at the begining of the file.
15429 	 */
15430 	rval = st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
15431 	if (rval) {
15432 		rval = EIO;
15433 		return (rval);
15434 	}
15435 
15436 	/*
15437 	 * Other interesting answers might be crashed BOT which isn't bad.
15438 	 */
15439 	if (un->un_status == SUN_KEY_BOT) {
15440 		return (rval);
15441 	}
15442 
15443 	un->un_running.pmode = invalid;
15444 
15445 	/*
15446 	 * Now we are on the BOP side of the filemark. Forward space to
15447 	 * the EOM side and we are at the begining of the file.
15448 	 */
15449 	rval = st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD);
15450 	if (rval) {
15451 		rval = EIO;
15452 	}
15453 
15454 	return (rval);
15455 }
15456 
15457 static int
15458 st_mtfsr_ioctl(struct scsi_tape *un, int64_t count)
15459 {
15460 
15461 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
15462 
15463 	/*
15464 	 * forward space to inter-record gap
15465 	 *
15466 	 */
15467 
15468 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15469 	    "st_ioctl_fsr: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15470 
15471 	if (un->un_pos.pmode == legacy) {
15472 		/*
15473 		 * If were are at end of tape and count is forward.
15474 		 * Return blank check.
15475 		 */
15476 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
15477 			/* we're at EOM */
15478 			un->un_err_resid = count;
15479 			un->un_status = KEY_BLANK_CHECK;
15480 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15481 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
15482 			return (EIO);
15483 		}
15484 
15485 		/*
15486 		 * If count is zero there is nothing to do.
15487 		 */
15488 		if (count == 0) {
15489 			un->un_err_pos.fileno = un->un_pos.fileno;
15490 			un->un_err_pos.blkno = un->un_pos.blkno;
15491 			un->un_err_resid = 0;
15492 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15493 				un->un_status = SUN_KEY_EOF;
15494 			}
15495 			return (0);
15496 		}
15497 
15498 		/*
15499 		 * physical tape position may not be what we've been
15500 		 * telling the user; adjust the position accordingly
15501 		 */
15502 		if (IN_EOF(un->un_pos)) {
15503 			daddr_t blkno = un->un_pos.blkno;
15504 			int fileno = un->un_pos.fileno;
15505 
15506 			optype lastop = un->un_lastop;
15507 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)
15508 			    == -1) {
15509 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15510 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
15511 				return (EIO);
15512 			}
15513 
15514 			un->un_pos.blkno = blkno;
15515 			un->un_pos.fileno = fileno;
15516 			un->un_lastop = lastop;
15517 		}
15518 	}
15519 
15520 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15521 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15522 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
15523 		return (EIO);
15524 	}
15525 
15526 	return (st_space_records(un, count));
15527 }
15528 
15529 static int
15530 st_space_records(struct scsi_tape *un, int64_t count)
15531 {
15532 	int64_t dblk;
15533 	int rval = 0;
15534 
15535 	ST_FUNC(ST_DEVINFO, st_space_records);
15536 
15537 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15538 	    "st_space_records: count=%"PRIx64", eof=%x\n",
15539 	    count, un->un_pos.eof);
15540 
15541 	if (un->un_pos.pmode == logical) {
15542 		rval = st_cmd(un, SCMD_SPACE, Blk(count), SYNC_CMD);
15543 		if (rval != 0) {
15544 			rval = EIO;
15545 		}
15546 		return (rval);
15547 	}
15548 
15549 	dblk = count + un->un_pos.blkno;
15550 
15551 	/* Already there */
15552 	if (dblk == un->un_pos.blkno) {
15553 		un->un_err_resid = 0;
15554 		COPY_POS(&un->un_err_pos, &un->un_pos);
15555 		return (0);
15556 	}
15557 
15558 	/*
15559 	 * If the destination block is forward
15560 	 * or the drive will backspace records.
15561 	 */
15562 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
15563 		/*
15564 		 * If we're spacing forward, or the device can
15565 		 * backspace records, we can just use the SPACE
15566 		 * command.
15567 		 */
15568 		dblk -= un->un_pos.blkno;
15569 		if (st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15570 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15571 			    "st_space_records:EIO:space_records can't spc");
15572 			rval = EIO;
15573 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
15574 			/*
15575 			 * check if we hit BOT/EOT
15576 			 */
15577 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
15578 				un->un_status = SUN_KEY_BOT;
15579 				un->un_pos.eof = ST_NO_EOF;
15580 			} else if (dblk < 0 &&
15581 			    un->un_pos.eof == ST_EOF_PENDING) {
15582 				int residue = un->un_err_resid;
15583 				/*
15584 				 * we skipped over a filemark
15585 				 * and need to go forward again
15586 				 */
15587 				if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
15588 					ST_DEBUG2(ST_DEVINFO, st_label,
15589 					    SCSI_DEBUG, "st_space_records: EIO"
15590 					    " : can't space #2");
15591 					rval = EIO;
15592 				}
15593 				un->un_err_resid = residue;
15594 			}
15595 			if (rval == 0) {
15596 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15597 				    "st_space_records: EIO : space_rec rval"
15598 				    " == 0");
15599 				rval = EIO;
15600 			}
15601 		}
15602 	} else {
15603 		/*
15604 		 * else we rewind, space forward across filemarks to
15605 		 * the desired file, and then space records to the
15606 		 * desired block.
15607 		 */
15608 
15609 		int dfile = un->un_pos.fileno;	/* save current file */
15610 
15611 		if (dblk < 0) {
15612 			/*
15613 			 * Wups - we're backing up over a filemark
15614 			 */
15615 			if (un->un_pos.blkno != 0 &&
15616 			    (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15617 			    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD))) {
15618 				un->un_pos.pmode = invalid;
15619 			}
15620 			un->un_err_resid = -dblk;
15621 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
15622 				un->un_status = SUN_KEY_BOT;
15623 				un->un_pos.eof = ST_NO_EOF;
15624 			} else if (un->un_pos.fileno > 0) {
15625 				un->un_status = SUN_KEY_EOF;
15626 				un->un_pos.eof = ST_NO_EOF;
15627 			}
15628 			COPY_POS(&un->un_err_pos, &un->un_pos);
15629 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15630 			    "st_space_records:EIO:space_records : dblk < 0");
15631 			rval = EIO;
15632 		} else if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15633 		    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
15634 		    st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15635 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15636 			    "st_space_records: EIO :space_records : rewind "
15637 			    "and space failed");
15638 			un->un_pos.pmode = invalid;
15639 			rval = EIO;
15640 		}
15641 	}
15642 
15643 	return (rval);
15644 }
15645 
15646 static int
15647 st_mtbsf_ioctl(struct scsi_tape *un, int64_t files)
15648 {
15649 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
15650 
15651 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15652 	    "st_mtbsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15653 	/*
15654 	 * backward space of file filemark (1/2" and 8mm)
15655 	 * tape position will end on the beginning of tape side
15656 	 * of the desired file mark
15657 	 */
15658 	if ((un->un_dp->options & ST_BSF) == 0) {
15659 		return (ENOTTY);
15660 	}
15661 
15662 	if (un->un_pos.pmode == legacy) {
15663 
15664 		/*
15665 		 * If a negative count (which implies a forward space op)
15666 		 * is specified, and we're at logical or physical eot,
15667 		 * bounce the request.
15668 		 */
15669 
15670 		if (un->un_pos.eof >= ST_EOT && files < 0) {
15671 			un->un_err_resid = files;
15672 			un->un_status = SUN_KEY_EOT;
15673 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15674 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
15675 			return (EIO);
15676 		}
15677 		/*
15678 		 * physical tape position may not be what we've been
15679 		 * telling the user; adjust the request accordingly
15680 		 */
15681 		if (IN_EOF(un->un_pos)) {
15682 			un->un_pos.fileno++;
15683 			un->un_pos.blkno = 0;
15684 			files++;
15685 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15686 			    "st_mtbsf_ioctl in eof: count=%"PRIx64", op=%x\n",
15687 			    files, MTBSF);
15688 
15689 		}
15690 	}
15691 
15692 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15693 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15694 		    "st_ioctl : EIO : MTBSF : check den wfm");
15695 		return (EIO);
15696 	}
15697 
15698 	if (files <= 0) {
15699 		/*
15700 		 * for a negative count, we need to step forward
15701 		 * first and then step back again
15702 		 */
15703 		files = -files + 1;
15704 		return (st_forward_space_files(un, files));
15705 	}
15706 	return (st_backward_space_files(un, files, 1));
15707 }
15708 
15709 static int
15710 st_backward_space_files(struct scsi_tape *un, int64_t count, int infront)
15711 {
15712 	int64_t end_fileno;
15713 	int64_t skip_cnt;
15714 	int rval = 0;
15715 
15716 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
15717 
15718 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15719 	    "st_backward_space_files: count=%"PRIx64" eof=%x\n",
15720 	    count, un->un_pos.eof);
15721 	/*
15722 	 * Backspace files (MTNBSF): infront == 0
15723 	 *
15724 	 *	For tapes that can backspace, backspace
15725 	 *	count+1 filemarks and then run forward over
15726 	 *	a filemark
15727 	 *
15728 	 *	For tapes that can't backspace,
15729 	 *		calculate desired filenumber
15730 	 *		(un->un_pos.fileno - count), rewind,
15731 	 *		and then space forward this amount
15732 	 *
15733 	 * Backspace filemarks (MTBSF) infront == 1
15734 	 *
15735 	 *	For tapes that can backspace, backspace count
15736 	 *	filemarks
15737 	 *
15738 	 *	For tapes that can't backspace, calculate
15739 	 *	desired filenumber (un->un_pos.fileno - count),
15740 	 *	add 1, rewind, space forward this amount,
15741 	 *	and mark state as ST_EOF_PENDING appropriately.
15742 	 */
15743 
15744 	if (un->un_pos.pmode == logical) {
15745 
15746 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15747 		    "st_backward_space_files: mt_op=%x count=%"PRIx64
15748 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
15749 		    un->un_pos.lgclblkno);
15750 
15751 
15752 		/* In case a drive that won't back space gets in logical mode */
15753 		if ((un->un_dp->options & ST_BSF) == 0) {
15754 			rval = EIO;
15755 			return (rval);
15756 		}
15757 		if ((infront == 1) &&
15758 		    (st_cmd(un, SCMD_SPACE, Fmk(-count), SYNC_CMD))) {
15759 			rval = EIO;
15760 			return (rval);
15761 		} else if ((infront == 0) &&
15762 		    (st_cmd(un, SCMD_SPACE, Fmk((-count)-1), SYNC_CMD)) &&
15763 		    (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
15764 			rval = EIO;
15765 			return (rval);
15766 		}
15767 		return (rval);
15768 	}
15769 
15770 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15771 	    "st_backward_space_files: mt_op=%x count=%"PRIx64
15772 	    "fileno=%x blkno=%x\n",
15773 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
15774 
15775 
15776 
15777 	/*
15778 	 * Handle the simple case of BOT
15779 	 * playing a role in these cmds.
15780 	 * We do this by calculating the
15781 	 * ending file number. If the ending
15782 	 * file is < BOT, rewind and set an
15783 	 * error and mark resid appropriately.
15784 	 * If we're backspacing a file (not a
15785 	 * filemark) and the target file is
15786 	 * the first file on the tape, just
15787 	 * rewind.
15788 	 */
15789 
15790 	/* figure expected destination of this SPACE command */
15791 	end_fileno = un->un_pos.fileno - count;
15792 
15793 	/*
15794 	 * Would the end effect of this SPACE be the same as rewinding?
15795 	 * If so just rewind instead.
15796 	 */
15797 	if ((infront != 0) && (end_fileno < 0) ||
15798 	    (infront == 0) && (end_fileno <= 0)) {
15799 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15800 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15801 			    "st_backward_space_files: EIO : "
15802 			    "rewind in lou of BSF failed\n");
15803 			rval = EIO;
15804 		}
15805 		if (end_fileno < 0) {
15806 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15807 			    "st_backward_space_files: EIO : "
15808 			    "back space file greater then fileno\n");
15809 			rval = EIO;
15810 			un->un_err_resid = -end_fileno;
15811 			un->un_status = SUN_KEY_BOT;
15812 		}
15813 		return (rval);
15814 	}
15815 
15816 	if (un->un_dp->options & ST_BSF) {
15817 		skip_cnt = 1 - infront;
15818 		/*
15819 		 * If we are going to end up at the beginning
15820 		 * of the file, we have to space one extra file
15821 		 * first, and then space forward later.
15822 		 */
15823 		end_fileno = -(count + skip_cnt);
15824 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15825 		    "skip_cnt=%"PRIx64", tmp=%"PRIx64"\n",
15826 		    skip_cnt, end_fileno);
15827 		if (st_cmd(un, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
15828 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15829 			    "st_backward_space_files:EIO:back space fm failed");
15830 			rval = EIO;
15831 		}
15832 	} else {
15833 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15834 			rval = EIO;
15835 		} else {
15836 			skip_cnt = end_fileno + infront;
15837 		}
15838 	}
15839 
15840 	/*
15841 	 * If we have to space forward, do so...
15842 	 */
15843 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15844 	    "space forward skip_cnt=%"PRIx64", rval=%x\n", skip_cnt, rval);
15845 
15846 	if (rval == 0 && skip_cnt) {
15847 		if (st_cmd(un, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
15848 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15849 			    "st_backward_space_files:EIO:space fm skip count");
15850 			rval = EIO;
15851 		} else if (infront) {
15852 			/*
15853 			 * If we had to space forward, and we're
15854 			 * not a tape that can backspace, mark state
15855 			 * as if we'd just seen a filemark during a
15856 			 * a read.
15857 			 */
15858 			if ((un->un_dp->options & ST_BSF) == 0) {
15859 				un->un_pos.eof = ST_EOF_PENDING;
15860 				un->un_pos.fileno -= 1;
15861 				un->un_pos.blkno = LASTBLK;
15862 				un->un_running.pmode = invalid;
15863 			}
15864 		}
15865 	}
15866 
15867 	if (rval != 0) {
15868 		un->un_pos.pmode = invalid;
15869 	}
15870 
15871 	return (rval);
15872 }
15873 
15874 static int
15875 st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count)
15876 {
15877 	int rval;
15878 
15879 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
15880 
15881 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15882 	    "nbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15883 
15884 	if (un->un_pos.pmode == legacy) {
15885 		/*
15886 		 * backward space file to beginning of file
15887 		 *
15888 		 * If a negative count (which implies a forward space op)
15889 		 * is specified, and we're at logical or physical eot,
15890 		 * bounce the request.
15891 		 */
15892 
15893 		if (un->un_pos.eof >= ST_EOT && count < 0) {
15894 			un->un_err_resid = count;
15895 			un->un_status = SUN_KEY_EOT;
15896 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15897 			    "st_ioctl : EIO : > EOT and count < 0");
15898 			return (EIO);
15899 		}
15900 		/*
15901 		 * physical tape position may not be what we've been
15902 		 * telling the user; adjust the request accordingly
15903 		 */
15904 		if (IN_EOF(un->un_pos)) {
15905 			un->un_pos.fileno++;
15906 			un->un_pos.blkno = 0;
15907 			count++;
15908 		}
15909 	}
15910 
15911 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15912 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15913 		    "st_ioctl : EIO : MTNBSF check den and wfm");
15914 		return (EIO);
15915 	}
15916 
15917 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15918 	    "mtnbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15919 
15920 	if (count <= 0) {
15921 		rval = st_forward_space_files(un, -count);
15922 	} else {
15923 		rval = st_backward_space_files(un, count, 0);
15924 	}
15925 	return (rval);
15926 }
15927 
15928 static int
15929 st_mtbsr_ioctl(struct scsi_tape *un, int64_t num)
15930 {
15931 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
15932 
15933 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15934 	    "bsr: count=%"PRIx64", eof=%x\n", num, un->un_pos.eof);
15935 
15936 	if (un->un_pos.pmode == legacy) {
15937 		/*
15938 		 * backward space into inter-record gap
15939 		 *
15940 		 * If a negative count (which implies a forward space op)
15941 		 * is specified, and we're at logical or physical eot,
15942 		 * bounce the request.
15943 		 */
15944 		if (un->un_pos.eof >= ST_EOT && num < 0) {
15945 			un->un_err_resid = num;
15946 			un->un_status = SUN_KEY_EOT;
15947 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15948 			    "st_ioctl : EIO : MTBSR > EOT");
15949 			return (EIO);
15950 		}
15951 
15952 		if (num == 0) {
15953 			COPY_POS(&un->un_err_pos, &un->un_pos);
15954 			un->un_err_resid = 0;
15955 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15956 				un->un_status = SUN_KEY_EOF;
15957 			}
15958 			return (0);
15959 		}
15960 
15961 		/*
15962 		 * physical tape position may not be what we've been
15963 		 * telling the user; adjust the position accordingly.
15964 		 * bsr can not skip filemarks and continue to skip records
15965 		 * therefore if we are logically before the filemark but
15966 		 * physically at the EOT side of the filemark, we need to step
15967 		 * back; this allows fsr N where N > number of blocks in file
15968 		 * followed by bsr 1 to position at the beginning of last block
15969 		 */
15970 		if (IN_EOF(un->un_pos)) {
15971 			tapepos_t save;
15972 			optype lastop = un->un_lastop;
15973 
15974 			COPY_POS(&save, &un->un_pos);
15975 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD) == -1) {
15976 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15977 				    "st_mtbsr_ioctl: EIO : MTBSR can't space");
15978 				return (EIO);
15979 			}
15980 
15981 			COPY_POS(&un->un_pos, &save);
15982 			un->un_lastop = lastop;
15983 		}
15984 	}
15985 
15986 	un->un_pos.eof = ST_NO_EOF;
15987 
15988 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15989 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15990 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
15991 		return (EIO);
15992 	}
15993 
15994 	num = -num;
15995 	return (st_space_records(un, num));
15996 }
15997 
15998 static int
15999 st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt)
16000 {
16001 	int rval;
16002 
16003 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
16004 
16005 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
16006 	if (rval == 0) {
16007 		un->un_pos.pmode = logical;
16008 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
16009 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
16010 		/*
16011 		 * Drive says invalid field in cdb.
16012 		 * Doesn't like space multiple. Position isn't lost.
16013 		 */
16014 		un->un_err_resid = cnt;
16015 		un->un_status = 0;
16016 		rval = ENOTTY;
16017 	} else {
16018 		un->un_err_resid = cnt;
16019 		un->un_pos.pmode = invalid;
16020 	}
16021 	return (rval);
16022 }
16023 
16024 static int
16025 st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt)
16026 {
16027 	int rval;
16028 
16029 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
16030 
16031 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
16032 	if (rval == 0) {
16033 		un->un_pos.pmode = logical;
16034 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
16035 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
16036 		/*
16037 		 * Drive says invalid field in cdb.
16038 		 * Doesn't like space multiple. Position isn't lost.
16039 		 */
16040 		un->un_err_resid = cnt;
16041 		un->un_status = 0;
16042 		rval = ENOTTY;
16043 	} else {
16044 		un->un_err_resid = cnt;
16045 		un->un_pos.pmode = invalid;
16046 	}
16047 	return (rval);
16048 }
16049 
16050 #ifdef	__x86
16051 
16052 /*
16053  * release contig_mem and wake up waiting thread, if any
16054  */
16055 static void
16056 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
16057 {
16058 	mutex_enter(ST_MUTEX);
16059 
16060 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
16061 
16062 	cp->cm_next = un->un_contig_mem;
16063 	un->un_contig_mem = cp;
16064 	un->un_contig_mem_available_num++;
16065 	cv_broadcast(&un->un_contig_mem_cv);
16066 
16067 	mutex_exit(ST_MUTEX);
16068 }
16069 
16070 /*
16071  * St_get_contig_mem will return a contig_mem if there is one available
16072  * in current system. Otherwise, it will try to alloc one, if the total
16073  * number of contig_mem is within st_max_contig_mem_num.
16074  * It will sleep, if allowed by caller or return NULL, if no contig_mem
16075  * is available for now.
16076  */
16077 static struct contig_mem *
16078 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
16079 {
16080 	size_t rlen;
16081 	struct contig_mem *cp = NULL;
16082 	ddi_acc_handle_t acc_hdl;
16083 	caddr_t addr;
16084 	int big_enough = 0;
16085 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
16086 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
16087 
16088 	/* Try to get one available contig_mem */
16089 	mutex_enter(ST_MUTEX);
16090 
16091 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
16092 
16093 	if (un->un_contig_mem_available_num > 0) {
16094 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16095 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
16096 		/*
16097 		 * we failed to get one. we're going to
16098 		 * alloc one more contig_mem for this I/O
16099 		 */
16100 		mutex_exit(ST_MUTEX);
16101 		cp = (struct contig_mem *)kmem_zalloc(
16102 		    sizeof (struct contig_mem) + biosize(),
16103 		    alloc_flags);
16104 		if (cp == NULL) {
16105 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16106 			    "alloc contig_mem failure\n");
16107 			return (NULL); /* cannot get one */
16108 		}
16109 		cp->cm_bp = (struct buf *)
16110 		    (((caddr_t)cp) + sizeof (struct contig_mem));
16111 		bioinit(cp->cm_bp);
16112 		mutex_enter(ST_MUTEX);
16113 		un->un_contig_mem_total_num++; /* one more available */
16114 	} else {
16115 		/*
16116 		 * we failed to get one and we're NOT allowed to
16117 		 * alloc more contig_mem
16118 		 */
16119 		if (alloc_flags == KM_SLEEP) {
16120 			while (un->un_contig_mem_available_num <= 0) {
16121 				cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16122 			}
16123 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16124 		} else {
16125 			mutex_exit(ST_MUTEX);
16126 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16127 			    "alloc contig_mem failure\n");
16128 			return (NULL); /* cannot get one */
16129 		}
16130 	}
16131 	mutex_exit(ST_MUTEX);
16132 
16133 	/* We need to check if this block of mem is big enough for this I/O */
16134 	if (cp->cm_len < len) {
16135 		/* not big enough, need to alloc a new one */
16136 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
16137 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
16138 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
16139 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16140 			    "alloc contig_mem failure: not enough mem\n");
16141 			st_release_contig_mem(un, cp);
16142 			cp = NULL;
16143 		} else {
16144 			if (cp->cm_addr) {
16145 				/* release previous one before attach new one */
16146 				ddi_dma_mem_free(&cp->cm_acc_hdl);
16147 			}
16148 			mutex_enter(ST_MUTEX);
16149 			un->un_max_contig_mem_len =
16150 			    un->un_max_contig_mem_len >= len ?
16151 			    un->un_max_contig_mem_len : len;
16152 			mutex_exit(ST_MUTEX);
16153 
16154 			/* attach new mem to this cp */
16155 			cp->cm_addr = addr;
16156 			cp->cm_acc_hdl = acc_hdl;
16157 			cp->cm_len = len;
16158 
16159 			goto alloc_ok; /* get one usable cp */
16160 		}
16161 	} else {
16162 		goto alloc_ok; /* get one usable cp */
16163 	}
16164 
16165 	/* cannot find/alloc a usable cp, when we get here */
16166 
16167 	mutex_enter(ST_MUTEX);
16168 	if ((un->un_max_contig_mem_len < len) ||
16169 	    (alloc_flags != KM_SLEEP)) {
16170 		mutex_exit(ST_MUTEX);
16171 		return (NULL);
16172 	}
16173 
16174 	/*
16175 	 * we're allowed to sleep, and there is one big enough
16176 	 * contig mem in the system, which is currently in use,
16177 	 * wait for it...
16178 	 */
16179 	big_enough = 1;
16180 	do {
16181 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16182 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16183 	} while (cp == NULL);
16184 	mutex_exit(ST_MUTEX);
16185 
16186 	/* we get the big enough contig mem, finally */
16187 
16188 alloc_ok:
16189 	/* init bp attached to this cp */
16190 	bioreset(cp->cm_bp);
16191 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
16192 	cp->cm_bp->b_private = (void *)cp;
16193 
16194 	return (cp);
16195 }
16196 
16197 /*
16198  * this is the biodone func for the bp used in big block I/O
16199  */
16200 static int
16201 st_bigblk_xfer_done(struct buf *bp)
16202 {
16203 	struct contig_mem *cp;
16204 	struct buf *orig_bp;
16205 	int ioerr;
16206 	struct scsi_tape *un;
16207 
16208 	/* sanity check */
16209 	if (bp == NULL) {
16210 		return (DDI_FAILURE);
16211 	}
16212 
16213 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16214 	if (un == NULL) {
16215 		return (DDI_FAILURE);
16216 	}
16217 
16218 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
16219 
16220 	cp = (struct contig_mem *)bp->b_private;
16221 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
16222 	cp->cm_bp = bp;
16223 
16224 	/* special handling for special I/O */
16225 	if (cp->cm_use_sbuf) {
16226 #ifndef __lock_lint
16227 		ASSERT(un->un_sbuf_busy);
16228 #endif
16229 		un->un_sbufp = orig_bp;
16230 		cp->cm_use_sbuf = 0;
16231 	}
16232 
16233 	orig_bp->b_resid = bp->b_resid;
16234 	ioerr = geterror(bp);
16235 	if (ioerr != 0) {
16236 		bioerror(orig_bp, ioerr);
16237 	} else if (orig_bp->b_flags & B_READ) {
16238 		/* copy data back to original bp */
16239 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
16240 		    bp->b_bcount - bp->b_resid);
16241 	}
16242 
16243 	st_release_contig_mem(un, cp);
16244 
16245 	biodone(orig_bp);
16246 
16247 	return (DDI_SUCCESS);
16248 }
16249 
16250 /*
16251  * We use this func to replace original bp that may not be able to do I/O
16252  * in big block size with one that can
16253  */
16254 static struct buf *
16255 st_get_bigblk_bp(struct buf *bp)
16256 {
16257 	struct contig_mem *cp;
16258 	struct scsi_tape *un;
16259 	struct buf *cont_bp;
16260 
16261 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16262 	if (un == NULL) {
16263 		return (bp);
16264 	}
16265 
16266 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
16267 
16268 	/* try to get one contig_mem */
16269 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
16270 	if (!cp) {
16271 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
16272 		    "Cannot alloc contig buf for I/O for %lu blk size",
16273 		    bp->b_bcount);
16274 		return (bp);
16275 	}
16276 	cont_bp = cp->cm_bp;
16277 	cp->cm_bp = bp;
16278 
16279 	/* make sure that we "are" using un_sbufp for special I/O */
16280 	if (bp == un->un_sbufp) {
16281 #ifndef __lock_lint
16282 		ASSERT(un->un_sbuf_busy);
16283 #endif
16284 		un->un_sbufp = cont_bp;
16285 		cp->cm_use_sbuf = 1;
16286 	}
16287 
16288 	/* clone bp */
16289 	cont_bp->b_bcount = bp->b_bcount;
16290 	cont_bp->b_resid = bp->b_resid;
16291 	cont_bp->b_iodone = st_bigblk_xfer_done;
16292 	cont_bp->b_file = bp->b_file;
16293 	cont_bp->b_offset = bp->b_offset;
16294 	cont_bp->b_dip = bp->b_dip;
16295 	cont_bp->b_error = 0;
16296 	cont_bp->b_proc = NULL;
16297 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
16298 	cont_bp->b_shadow = NULL;
16299 	cont_bp->b_pages = NULL;
16300 	cont_bp->b_edev = bp->b_edev;
16301 	cont_bp->b_dev = bp->b_dev;
16302 	cont_bp->b_lblkno = bp->b_lblkno;
16303 	cont_bp->b_forw = bp->b_forw;
16304 	cont_bp->b_back = bp->b_back;
16305 	cont_bp->av_forw = bp->av_forw;
16306 	cont_bp->av_back = bp->av_back;
16307 	cont_bp->b_bufsize = bp->b_bufsize;
16308 
16309 	/* get data in original bp */
16310 	if (bp->b_flags & B_WRITE) {
16311 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
16312 	}
16313 
16314 	return (cont_bp);
16315 }
16316 #else
16317 #ifdef __lock_lint
16318 static int
16319 st_bigblk_xfer_done(struct buf *bp)
16320 {
16321 	return (0);
16322 }
16323 #endif
16324 #endif
16325 
16326 static const char *eof_status[] =
16327 {
16328 	"NO_EOF",
16329 	"EOF_PENDING",
16330 	"EOF",
16331 	"EOT_PENDING",
16332 	"EOT",
16333 	"EOM",
16334 	"AFTER_EOM"
16335 };
16336 static const char *mode[] = {
16337 	"invalid",
16338 	"legacy",
16339 	"logical"
16340 };
16341 
16342 static void
16343 st_print_position(dev_info_t *dev, char *label, uint_t level,
16344 const char *comment, tapepos_t *pos)
16345 {
16346 	ST_FUNC(dev, st_print_position);
16347 
16348 	scsi_log(dev, label, level,
16349 	    "%s Position data:\n", comment);
16350 	scsi_log(dev, label, CE_CONT,
16351 	    "Positioning mode = %s", mode[pos->pmode]);
16352 	scsi_log(dev, label, CE_CONT,
16353 	    "End Of File/Tape = %s", eof_status[pos->eof]);
16354 	scsi_log(dev, label, CE_CONT,
16355 	    "File Number      = 0x%x", pos->fileno);
16356 	scsi_log(dev, label, CE_CONT,
16357 	    "Block Number     = 0x%x", pos->blkno);
16358 	scsi_log(dev, label, CE_CONT,
16359 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
16360 	scsi_log(dev, label, CE_CONT,
16361 	    "Partition Number = 0x%x", pos->partition);
16362 }
16363 static int
16364 st_check_if_media_changed(struct scsi_tape *un, caddr_t data, int size)
16365 {
16366 
16367 	int result = 0;
16368 	int i;
16369 	ST_FUNC(ST_DEVINFO, st_check_if_media_changed);
16370 
16371 	/*
16372 	 * find non alpha numeric working from the end.
16373 	 */
16374 	for (i = size - 1; i >= 0; i--) {
16375 		if (ISALNUM(data[i]) == 0 || data[i] == ' ') {
16376 			data[i] = 0;
16377 			size = i;
16378 		}
16379 	}
16380 
16381 	if (size == 1) {
16382 		/*
16383 		 * Drive seems to think its returning useful data
16384 		 * but it looks like all junk
16385 		 */
16386 		return (result);
16387 	}
16388 
16389 	size++;
16390 
16391 	/*
16392 	 * Actually got a valid serial number.
16393 	 * If never stored one before alloc space for it.
16394 	 */
16395 	if (un->un_media_id_len == 0) {
16396 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16397 		un->un_media_id_len = size;
16398 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16399 		un->un_media_id[min(size, strlen(data))] = 0;
16400 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16401 		    "Found Media Id %s length = %d\n", un->un_media_id, size);
16402 	} else if (size > un->un_media_id_len) {
16403 		if (strncmp(un->un_media_id, data, size) != 0) {
16404 			result = ESPIPE;
16405 		}
16406 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16407 		    "Longer Media Id old ID:%s new ID:%s\n",
16408 		    un->un_media_id, data);
16409 		kmem_free(un->un_media_id, un->un_media_id_len);
16410 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16411 		un->un_media_id_len = size;
16412 		(void) strncpy(un->un_media_id, data, size);
16413 		un->un_media_id[size] = 0;
16414 	} else if (strncmp(data, un->un_media_id,
16415 	    min(size, un->un_media_id_len)) != 0) {
16416 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16417 		    "Old Media Id %s length = %d New %s length = %d\n",
16418 		    un->un_media_id, un->un_media_id_len, data, size);
16419 		bzero(un->un_media_id, un->un_media_id_len);
16420 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16421 		un->un_media_id[min(size, strlen(data))] = 0;
16422 		result = ESPIPE;
16423 	} else {
16424 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
16425 		    "Media Id still %s\n", un->un_media_id);
16426 	}
16427 
16428 	ASSERT(strlen(un->un_media_id) <= size);
16429 
16430 	return (result);
16431 }
16432 #define	ID_SIZE 32
16433 typedef struct
16434 {
16435 	uchar_t avilable_data0;
16436 	uchar_t avilable_data1;
16437 	uchar_t avilable_data2;
16438 	uchar_t avilable_data3;
16439 	uchar_t attribute_msb;
16440 	uchar_t attribute_lsb;
16441 #ifdef _BIT_FIELDS_LTOH
16442 	uchar_t format		: 2,
16443 				: 5,
16444 		read_only	: 1;
16445 #else
16446 	uchar_t read_only	: 1,
16447 				: 5,
16448 		format		: 2;
16449 #endif
16450 	uchar_t attribute_len_msb;
16451 	uchar_t attribute_len_lsb;
16452 }attribute_header;
16453 
16454 typedef struct {
16455 	attribute_header header;
16456 	char data[1];
16457 }mam_attribute;
16458 
16459 static int
16460 st_handle_hex_media_id(struct scsi_tape *un, void *pnt, int size)
16461 {
16462 	int result;
16463 	int newsize = (size << 1) + 3; /* extra for leading 0x and null term */
16464 	int i;
16465 	uchar_t byte;
16466 	char *format;
16467 	uchar_t *data = (uchar_t *)pnt;
16468 	char *buf = kmem_alloc(newsize, KM_SLEEP);
16469 
16470 	ST_FUNC(ST_DEVINFO, st_handle_hex_media_id);
16471 
16472 	(void) sprintf(buf, "0x");
16473 	for (i = 0; i < size; i++) {
16474 		byte = data[i];
16475 		if (byte < 0x10)
16476 			format = "0%x";
16477 		else
16478 			format = "%x";
16479 		(void) sprintf(&buf[(int)strlen(buf)], format, byte);
16480 	}
16481 	result = st_check_if_media_changed(un, buf, newsize);
16482 
16483 	kmem_free(buf, newsize);
16484 
16485 	return (result);
16486 }
16487 
16488 
16489 static int
16490 st_get_media_id_via_read_attribute(struct scsi_tape *un, ubufunc_t bufunc)
16491 {
16492 	int result;
16493 	mam_attribute *buffer;
16494 	int size;
16495 	int newsize;
16496 
16497 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_read_attribute);
16498 	size = sizeof (attribute_header) + max(un->un_media_id_len, ID_SIZE);
16499 again:
16500 	buffer = kmem_zalloc(size, KM_SLEEP);
16501 	result = st_read_attributes(un, 0x0401, buffer, size, bufunc);
16502 	if (result == 0) {
16503 
16504 		newsize = (buffer->header.attribute_len_msb << 8) |
16505 		    buffer->header.attribute_len_lsb;
16506 
16507 		if (newsize + sizeof (attribute_header) > size) {
16508 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
16509 			    "resizing read attribute data from %d to %d format"
16510 			    " %d\n", size, (int)sizeof (attribute_header) +
16511 			    newsize, buffer->header.format);
16512 			kmem_free(buffer, size);
16513 			size = newsize + sizeof (attribute_header);
16514 			goto again;
16515 		}
16516 
16517 		un->un_media_id_method = st_get_media_id_via_read_attribute;
16518 		if (buffer->header.format == 0) {
16519 			result =
16520 			    st_handle_hex_media_id(un, buffer->data, newsize);
16521 		} else {
16522 			result = st_check_if_media_changed(un, buffer->data,
16523 			    newsize);
16524 		}
16525 	} else if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
16526 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
16527 		    "Read Attribute Command for Media Identification is not "
16528 		    "supported on the HBA that this drive is attached to.");
16529 		result = ENOTTY;
16530 	}
16531 
16532 	kmem_free(buffer, size);
16533 	un->un_status = 0;
16534 
16535 	return (result);
16536 }
16537 
16538 
16539 static int
16540 st_get_media_id_via_media_serial_cmd(struct scsi_tape *un, ubufunc_t bufunc)
16541 {
16542 	char cdb[CDB_GROUP5];
16543 	struct uscsi_cmd *ucmd;
16544 	struct scsi_extended_sense sense;
16545 	int rval;
16546 	int size = max(un->un_media_id_len, ID_SIZE);
16547 	caddr_t buf;
16548 
16549 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_media_serial_cmd);
16550 
16551 	if (un->un_sd->sd_inq->inq_ansi < 3) {
16552 		return (ENOTTY);
16553 	}
16554 
16555 	ucmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
16556 upsize:
16557 	buf = kmem_alloc(size, KM_SLEEP);
16558 
16559 	cdb[0] = (char)SCMD_SVC_ACTION_IN_G5;
16560 	cdb[1] = SSVC_ACTION_READ_MEDIA_SERIAL;
16561 	cdb[2] = 0;
16562 	cdb[3] = 0;
16563 	cdb[4] = 0;
16564 	cdb[5] = 0;
16565 	cdb[6] = (char)(size >> 24);
16566 	cdb[7] = (char)(size >> 16);
16567 	cdb[8] = (char)(size >> 8);
16568 	cdb[9] = (char)(size);
16569 	cdb[10] = 0;
16570 	cdb[11] = 0;
16571 
16572 	ucmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
16573 	ucmd->uscsi_timeout = un->un_dp->non_motion_timeout;
16574 	ucmd->uscsi_cdb = &cdb[0];
16575 	ucmd->uscsi_cdblen = sizeof (cdb);
16576 	ucmd->uscsi_bufaddr = buf;
16577 	ucmd->uscsi_buflen = size;
16578 	ucmd->uscsi_rqbuf = (caddr_t)&sense;
16579 	ucmd->uscsi_rqlen = sizeof (sense);
16580 
16581 	rval = bufunc(un, ucmd, FKIOCTL);
16582 
16583 	if (rval || ucmd->uscsi_status != 0) {
16584 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16585 		    "media serial command returned %d scsi_status %d"
16586 		    " rqstatus %d", rval, ucmd->uscsi_status,
16587 		    ucmd->uscsi_rqstatus);
16588 		/*
16589 		 * If this returns invalid operation code don't try again.
16590 		 */
16591 		if (sense.es_key == KEY_ILLEGAL_REQUEST &&
16592 		    sense.es_add_code == 0x20) {
16593 			rval = ENOTTY;
16594 		} else if (rval == 0) {
16595 			rval = EIO;
16596 		}
16597 		un->un_status = 0;
16598 	} else {
16599 		int act_size;
16600 
16601 		/*
16602 		 * get reported size.
16603 		 */
16604 		act_size = (int)buf[3] | (int)(buf[2] << 8) |
16605 		    (int)(buf[1] << 16) | (int)(buf[0] << 24);
16606 
16607 		/* documentation says mod 4. */
16608 		while (act_size & 3) {
16609 			act_size++;
16610 		}
16611 
16612 		/*
16613 		 * If reported size is larger that we our buffer.
16614 		 * Free the old one and allocate one that is larger
16615 		 * enough and re-issuse the command.
16616 		 */
16617 		if (act_size + 4 > size) {
16618 			kmem_free(buf, size);
16619 			size = act_size + 4;
16620 			goto upsize;
16621 		}
16622 
16623 		if (act_size == 0) {
16624 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16625 			    "media serial number is not available");
16626 			un->un_status = 0;
16627 			rval = 0;
16628 		} else {
16629 			/*
16630 			 * set data pointer to point to the start
16631 			 * of that serial number.
16632 			 */
16633 			un->un_media_id_method =
16634 			    st_get_media_id_via_media_serial_cmd;
16635 			rval =
16636 			    st_check_if_media_changed(un, &buf[4], act_size);
16637 		}
16638 	}
16639 
16640 	kmem_free(ucmd, sizeof (struct uscsi_cmd));
16641 	kmem_free(buf, size);
16642 
16643 	return (rval);
16644 }
16645 
16646 
16647 /* ARGSUSED */
16648 static int
16649 st_bogus_media_id(struct scsi_tape *un, ubufunc_t bufunc)
16650 {
16651 	ST_FUNC(ST_DEVINFO, st_bogus_media_id);
16652 
16653 	ASSERT(un->un_media_id == NULL || un->un_media_id == bogusID);
16654 	ASSERT(un->un_media_id_len == 0);
16655 	un->un_media_id = (char *)bogusID;
16656 	un->un_media_id_len = 0;
16657 	return (0);
16658 }
16659 
16660 typedef int (*media_chk_function)(struct scsi_tape *, ubufunc_t bufunc);
16661 
16662 media_chk_function media_chk_functions[] = {
16663 	st_get_media_id_via_media_serial_cmd,
16664 	st_get_media_id_via_read_attribute,
16665 	st_bogus_media_id
16666 };
16667 
16668 static int
16669 st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc)
16670 {
16671 	int result = 0;
16672 	int i;
16673 
16674 	ST_FUNC(ST_DEVINFO, st_get_media_identification);
16675 
16676 	for (i = 0; i < ST_NUM_MEMBERS(media_chk_functions); i++) {
16677 		if (result == ENOTTY) {
16678 			/*
16679 			 * Last operation type not supported by this device.
16680 			 * Make so next time it doesn`t do that again.
16681 			 */
16682 			un->un_media_id_method = media_chk_functions[i];
16683 		} else if (un->un_media_id_method != media_chk_functions[i] &&
16684 		    un->un_media_id_method != st_get_media_identification) {
16685 			continue;
16686 		}
16687 		result = media_chk_functions[i](un, bufunc);
16688 		/*
16689 		 * If result indicates the function was successful or
16690 		 * that the media is not the same as last known, break.
16691 		 */
16692 		if (result == 0 || result == ESPIPE) {
16693 			break;
16694 		}
16695 	}
16696 
16697 	return (result);
16698 }
16699 
16700 static errstate
16701 st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
16702     errstate onentry)
16703 {
16704 
16705 	int ret;
16706 	st_err_info *errinfo;
16707 	recov_info *ri = (recov_info *)pkt->pkt_private;
16708 
16709 	ST_FUNC(ST_DEVINFO, st_command_recovery);
16710 
16711 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16712 
16713 	ASSERT(un->un_recov_buf_busy == 0);
16714 
16715 	/*
16716 	 * Don't try and recover a reset that this device sent.
16717 	 */
16718 	if (un->un_rsvd_status & ST_INITIATED_RESET &&
16719 	    onentry == DEVICE_RESET) {
16720 		return (COMMAND_DONE_ERROR);
16721 	}
16722 
16723 	/*
16724 	 * See if expected position was passed with scsi_pkt.
16725 	 */
16726 	if (ri->privatelen == sizeof (recov_info)) {
16727 
16728 		/*
16729 		 * Not for this command.
16730 		 */
16731 		if (ri->cmd_attrib->do_not_recover) {
16732 			return (COMMAND_DONE_ERROR);
16733 		}
16734 
16735 		/*
16736 		 * Create structure to hold all error state info.
16737 		 */
16738 		errinfo = kmem_zalloc(ST_ERR_INFO_SIZE, KM_SLEEP);
16739 		errinfo->ei_error_type = onentry;
16740 		errinfo->ei_failing_bp = ri->cmd_bp;
16741 		COPY_POS(&errinfo->ei_expected_pos, &ri->pos);
16742 	} else {
16743 		/* disabled */
16744 		return (COMMAND_DONE_ERROR);
16745 	}
16746 
16747 	bcopy(pkt, &errinfo->ei_failed_pkt, scsi_pkt_size());
16748 	bcopy(pkt->pkt_scbp, &errinfo->ei_failing_status, SECMDS_STATUS_SIZE);
16749 	ret = ddi_taskq_dispatch(un->un_recov_taskq, st_recover, errinfo,
16750 	    DDI_NOSLEEP);
16751 	ASSERT(ret == DDI_SUCCESS);
16752 	if (ret != DDI_SUCCESS) {
16753 		kmem_free(errinfo, ST_ERR_INFO_SIZE);
16754 		return (COMMAND_DONE_ERROR);
16755 	}
16756 	return (JUST_RETURN); /* release calling thread */
16757 }
16758 
16759 
16760 static void
16761 st_recov_ret(struct scsi_tape *un, st_err_info *errinfo, errstate err)
16762 {
16763 	int error_number;
16764 	buf_t *bp;
16765 
16766 
16767 	ST_FUNC(ST_DEVINFO, st_recov_ret);
16768 
16769 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16770 #if !defined(lint)
16771 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
16772 #endif
16773 
16774 	bp = errinfo->ei_failing_bp;
16775 	kmem_free(errinfo, ST_ERR_INFO_SIZE);
16776 
16777 	switch (err) {
16778 	case JUST_RETURN:
16779 		mutex_exit(&un->un_sd->sd_mutex);
16780 		return;
16781 
16782 	case COMMAND_DONE:
16783 	case COMMAND_DONE_ERROR_RECOVERED:
16784 		ST_DO_KSTATS(bp, kstat_runq_exit);
16785 		error_number = 0;
16786 		break;
16787 
16788 	default:
16789 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16790 		    "st_recov_ret with unhandled errstat %d\n", err);
16791 		/* FALLTHROUGH */
16792 	case COMMAND_DONE_ERROR:
16793 		un->un_pos.pmode = invalid;
16794 		un->un_running.pmode = invalid;
16795 		/* FALLTHROUGH */
16796 	case COMMAND_DONE_EACCES:
16797 		ST_DO_KSTATS(bp, kstat_waitq_exit);
16798 		ST_DO_ERRSTATS(un, st_transerrs);
16799 		error_number = EIO;
16800 		st_set_pe_flag(un);
16801 		break;
16802 
16803 	}
16804 
16805 	st_bioerror(bp, error_number);
16806 	st_done_and_mutex_exit(un, bp);
16807 }
16808 
16809 
16810 static void
16811 st_recover(void *arg)
16812 {
16813 	st_err_info *const errinfo = (st_err_info *)arg;
16814 	uchar_t com = errinfo->ei_failed_pkt.pkt_cdbp[0];
16815 	struct scsi_tape *un;
16816 	tapepos_t cur_pos;
16817 	int rval;
16818 	errstate status = COMMAND_DONE_ERROR;
16819 	recov_info *rcv;
16820 	buf_t *bp;
16821 
16822 
16823 	rcv = errinfo->ei_failed_pkt.pkt_private;
16824 	ASSERT(rcv->privatelen == sizeof (recov_info));
16825 	bp = rcv->cmd_bp;
16826 
16827 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16828 
16829 	ASSERT(un != NULL);
16830 
16831 	mutex_enter(ST_MUTEX);
16832 
16833 	ST_FUNC(ST_DEVINFO, st_recover);
16834 
16835 	ST_CDB(ST_DEVINFO, "Recovering command",
16836 	    (caddr_t)errinfo->ei_failed_pkt.pkt_cdbp);
16837 	ST_SENSE(ST_DEVINFO, "sense status for failed command",
16838 	    (caddr_t)&errinfo->ei_failing_status,
16839 	    sizeof (struct scsi_arq_status));
16840 	ST_POS(ST_DEVINFO, rcv->cmd_attrib->recov_pos_type == POS_STARTING ?
16841 	    "starting position for recovery command" :
16842 	    "expected position for recovery command",
16843 	    &errinfo->ei_expected_pos);
16844 
16845 	rval = st_test_path_to_device(un);
16846 
16847 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16848 	    "st_recover called with %s, TUR returned %d\n",
16849 	    errstatenames[errinfo->ei_error_type], rval);
16850 	/*
16851 	 * If the drive responed to the TUR lets try and get it to sync
16852 	 * any data it might have in the buffer.
16853 	 */
16854 	if (rval == 0 && rcv->cmd_attrib->chg_tape_data) {
16855 		rval = st_rcmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
16856 		if (rval) {
16857 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16858 			    "st_recover failed to flush, returned %d\n", rval);
16859 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16860 			return;
16861 		}
16862 	}
16863 	switch (errinfo->ei_error_type) {
16864 	case ATTEMPT_RETRY:
16865 	case COMMAND_TIMEOUT:
16866 	case DEVICE_RESET:
16867 	case PATH_FAILED:
16868 		/*
16869 		 * For now if we can't talk to the device we are done.
16870 		 * If the drive is reserved we can try to get it back.
16871 		 */
16872 		if (rval != 0 && rval != EACCES) {
16873 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16874 			return;
16875 		}
16876 
16877 		/*
16878 		 * If reservation conflict and do a preempt, fail it.
16879 		 */
16880 		if ((un->un_rsvd_status &
16881 		    (ST_APPLICATION_RESERVATIONS | ST_RESERVE)) != 0) {
16882 			if ((errinfo->ei_failed_pkt.pkt_cdbp[0] ==
16883 			    SCMD_PERSISTENT_RESERVE_OUT) &&
16884 			    (errinfo->ei_failed_pkt.pkt_cdbp[1] ==
16885 			    ST_SA_SCSI3_PREEMPT) &&
16886 			    (SCBP_C(&errinfo->ei_failed_pkt) ==
16887 			    STATUS_RESERVATION_CONFLICT)) {
16888 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16889 				return;
16890 			}
16891 		}
16892 
16893 		/*
16894 		 * If we have already set a scsi II reserve and get a
16895 		 * conflict on a scsi III type reserve fail without
16896 		 * any attempt to recover.
16897 		 */
16898 		if ((un->un_rsvd_status & ST_RESERVE | ST_PRESERVE_RESERVE) &&
16899 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] ==
16900 		    SCMD_PERSISTENT_RESERVE_OUT) ||
16901 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] ==
16902 		    SCMD_PERSISTENT_RESERVE_IN)) {
16903 			st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16904 			return;
16905 		}
16906 
16907 		/*
16908 		 * If scsi II lost reserve try and get it back.
16909 		 */
16910 		if ((((un->un_rsvd_status &
16911 		    (ST_LOST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
16912 		    ST_LOST_RESERVE)) &&
16913 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] != SCMD_RELEASE)) {
16914 			rval = st_reserve_release(un, ST_RESERVE,
16915 			    st_uscsi_rcmd);
16916 			if (rval != 0) {
16917 				if (st_take_ownership(un, st_uscsi_rcmd) != 0) {
16918 					st_recov_ret(un, errinfo,
16919 					    COMMAND_DONE_EACCES);
16920 					return;
16921 				}
16922 			}
16923 			un->un_rsvd_status |= ST_RESERVE;
16924 			un->un_rsvd_status &= ~(ST_RELEASE | ST_LOST_RESERVE |
16925 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
16926 		}
16927 		rval = st_make_sure_mode_data_is_correct(un, st_uscsi_rcmd);
16928 		if (rval) {
16929 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16930 			return;
16931 		}
16932 		break;
16933 	case DEVICE_TAMPER:
16934 		/*
16935 		 * Check if the ASC/ASCQ says mode data has changed.
16936 		 */
16937 		if ((errinfo->ei_failing_status.sts_sensedata.es_add_code ==
16938 		    0x2a) &&
16939 		    (errinfo->ei_failing_status.sts_sensedata.es_qual_code ==
16940 		    0x01)) {
16941 			/*
16942 			 * See if mode sense changed.
16943 			 */
16944 			rval = st_make_sure_mode_data_is_correct(un,
16945 			    st_uscsi_rcmd);
16946 			if (rval) {
16947 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16948 				return;
16949 			}
16950 		}
16951 		/*
16952 		 * if we have a media id and its not bogus.
16953 		 * Check to see if it the same.
16954 		 */
16955 		if (un->un_media_id != NULL && un->un_media_id != bogusID) {
16956 			rval = st_get_media_identification(un, st_uscsi_rcmd);
16957 			if (rval == ESPIPE) {
16958 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16959 				return;
16960 			}
16961 		}
16962 		break;
16963 	default:
16964 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16965 		    "Unhandled error type %s in st_recover() 0x%x\n",
16966 		    errstatenames[errinfo->ei_error_type], com);
16967 	}
16968 
16969 	/*
16970 	 * if command is retriable retry it.
16971 	 * Special case here. The command attribute for SCMD_REQUEST_SENSE
16972 	 * does not say that it is retriable. That because if you reissue a
16973 	 * request sense and the target responds the sense data will have
16974 	 * been consumed and no long be valid. If we get a busy status on
16975 	 * request sense while the state is ST_STATE_SENSING this will
16976 	 * reissue that pkt.
16977 	 *
16978 	 * XXX If this request sense gets sent to a different port then
16979 	 * the original command that failed was sent on it will not get
16980 	 * valid sense data for that command.
16981 	 */
16982 	if (rcv->cmd_attrib->retriable || un->un_rqs_bp == bp) {
16983 		status = st_recover_reissue_pkt(un, &errinfo->ei_failed_pkt);
16984 
16985 	/*
16986 	 * if drive doesn't support read position we are done
16987 	 */
16988 	} else if (un->un_read_pos_type == NO_POS) {
16989 		status = COMMAND_DONE_ERROR;
16990 	/*
16991 	 * If this command results in a changed tape position,
16992 	 * lets see where we are.
16993 	 */
16994 	} else if (rcv->cmd_attrib->chg_tape_pos) {
16995 		/*
16996 		 * XXX May be a reason to choose a different type here.
16997 		 * Long format has file position information.
16998 		 * Short and Extended have information about whats
16999 		 * in the buffer. St's positioning assumes in the buffer
17000 		 * to be the same as on tape.
17001 		 */
17002 		rval = st_compare_expected_position(un, errinfo,
17003 		    rcv->cmd_attrib, &cur_pos);
17004 		if (rval == 0) {
17005 			status = COMMAND_DONE;
17006 		} else if (rval == EAGAIN) {
17007 			status = st_recover_reissue_pkt(un,
17008 			    &errinfo->ei_failed_pkt);
17009 		} else {
17010 			status = COMMAND_DONE_ERROR;
17011 		}
17012 	} else {
17013 		ASSERT(0);
17014 	}
17015 
17016 	st_recov_ret(un, errinfo, status);
17017 }
17018 
17019 static void
17020 st_recov_cb(struct scsi_pkt *pkt)
17021 {
17022 	struct scsi_tape *un;
17023 	struct buf *bp;
17024 	recov_info *rcv;
17025 	errstate action = COMMAND_DONE_ERROR;
17026 	int timout = ST_TRAN_BUSY_TIMEOUT; /* short (default) timeout */
17027 
17028 	/*
17029 	 * Get the buf from the packet.
17030 	 */
17031 	rcv = pkt->pkt_private;
17032 	ASSERT(rcv->privatelen == sizeof (recov_info));
17033 	bp = rcv->cmd_bp;
17034 
17035 	/*
17036 	 * get the unit from the buf.
17037 	 */
17038 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
17039 	ASSERT(un != NULL);
17040 
17041 	ST_FUNC(ST_DEVINFO, st_recov_cb);
17042 
17043 	mutex_enter(ST_MUTEX);
17044 
17045 	ASSERT(bp == un->un_recov_buf);
17046 
17047 
17048 	switch (pkt->pkt_reason) {
17049 	case CMD_CMPLT:
17050 		if (un->un_arq_enabled && pkt->pkt_state & STATE_ARQ_DONE) {
17051 			action = st_handle_autosense(un, bp, &rcv->pos);
17052 		} else  if ((SCBP(pkt)->sts_busy) ||
17053 		    (SCBP(pkt)->sts_chk) ||
17054 		    (SCBP(pkt)->sts_vu7)) {
17055 			action = st_check_error(un, pkt);
17056 		} else {
17057 			action = COMMAND_DONE;
17058 		}
17059 		break;
17060 	case CMD_TIMEOUT:
17061 		action = COMMAND_TIMEOUT;
17062 		break;
17063 	case CMD_TRAN_ERR:
17064 		action = QUE_COMMAND;
17065 		break;
17066 	case CMD_DEV_GONE:
17067 		if (un->un_multipath)
17068 			action = PATH_FAILED;
17069 		else
17070 			action = COMMAND_DONE_ERROR;
17071 		break;
17072 	default:
17073 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
17074 		    "pkt_reason not handled yet %s",
17075 		    scsi_rname(pkt->pkt_reason));
17076 		action = COMMAND_DONE_ERROR;
17077 	}
17078 
17079 	/*
17080 	 * check for undetected path failover.
17081 	 */
17082 	if (un->un_multipath) {
17083 		if (scsi_pkt_allocated_correctly(pkt) &&
17084 		    (un->un_last_path_instance != pkt->pkt_path_instance)) {
17085 			if (un->un_state > ST_STATE_OPENING) {
17086 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17087 				    "Failover detected in recovery, action is "
17088 				    "%s\n", errstatenames[action]);
17089 			}
17090 			un->un_last_path_instance = pkt->pkt_path_instance;
17091 		}
17092 	}
17093 
17094 	ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
17095 	    "Recovery call back got %s status on %s\n",
17096 	    errstatenames[action], st_print_scsi_cmd(pkt->pkt_cdbp[0]));
17097 
17098 	switch (action) {
17099 	case COMMAND_DONE:
17100 		break;
17101 
17102 	case COMMAND_DONE_EACCES:
17103 		bioerror(bp, EACCES);
17104 		break;
17105 
17106 	case COMMAND_DONE_ERROR_RECOVERED: /* XXX maybe wrong */
17107 		ASSERT(0);
17108 		break;
17109 
17110 	case COMMAND_TIMEOUT:
17111 	case COMMAND_DONE_ERROR:
17112 		bioerror(bp, EIO);
17113 		break;
17114 
17115 	case DEVICE_RESET:
17116 	case QUE_BUSY_COMMAND:
17117 	case PATH_FAILED:
17118 		/* longish timeout */
17119 		timout = ST_STATUS_BUSY_TIMEOUT;
17120 		/* FALLTHRU */
17121 	case QUE_COMMAND:
17122 	case DEVICE_TAMPER:
17123 	case ATTEMPT_RETRY:
17124 		/*
17125 		 * let st_handle_intr_busy put this bp back on waitq and make
17126 		 * checks to see if it is ok to requeue the command.
17127 		 */
17128 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
17129 
17130 		/*
17131 		 * Save the throttle before setting up the timeout
17132 		 */
17133 		if (un->un_throttle) {
17134 			un->un_last_throttle = un->un_throttle;
17135 		}
17136 		mutex_exit(ST_MUTEX);
17137 		if (st_handle_intr_busy(un, bp, timout) == 0) {
17138 			return;		/* timeout is setup again */
17139 		}
17140 		mutex_enter(ST_MUTEX);
17141 		un->un_pos.pmode = invalid;
17142 		un->un_err_resid = bp->b_resid = bp->b_bcount;
17143 		st_bioerror(bp, EIO);
17144 		st_set_pe_flag(un);
17145 		break;
17146 
17147 	default:
17148 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
17149 		    "Unhandled recovery state 0x%x\n", action);
17150 		un->un_pos.pmode = invalid;
17151 		un->un_err_resid = bp->b_resid = bp->b_bcount;
17152 		st_bioerror(bp, EIO);
17153 		st_set_pe_flag(un);
17154 		break;
17155 	}
17156 
17157 	st_done_and_mutex_exit(un, bp);
17158 }
17159 
17160 static int
17161 st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait)
17162 {
17163 	struct buf *bp;
17164 	int err;
17165 
17166 	ST_FUNC(ST_DEVINFO, st_rcmd);
17167 
17168 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
17169 	    "st_rcmd(un = 0x%p, com = 0x%x, count = %"PRIx64", wait = %d)\n",
17170 	    (void *)un, com, count, wait);
17171 
17172 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
17173 	ASSERT(mutex_owned(ST_MUTEX));
17174 
17175 #ifdef STDEBUG
17176 	if ((st_debug & 0x7)) {
17177 		st_debug_cmds(un, com, count, wait);
17178 	}
17179 #endif
17180 
17181 	while (un->un_recov_buf_busy)
17182 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17183 	un->un_recov_buf_busy = 1;
17184 
17185 	bp = un->un_recov_buf;
17186 	bzero(bp, sizeof (buf_t));
17187 
17188 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
17189 
17190 	err = st_setup_cmd(un, bp, com, count);
17191 
17192 	un->un_recov_buf_busy = 0;
17193 
17194 	cv_signal(&un->un_recov_buf_cv);
17195 
17196 	return (err);
17197 }
17198 
17199 /* args used */
17200 static int
17201 st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
17202 {
17203 	int rval;
17204 	buf_t *bp;
17205 
17206 	ST_FUNC(ST_DEVINFO, st_uscsi_rcmd);
17207 	ASSERT(flag == FKIOCTL);
17208 
17209 	/*
17210 	 * Get buffer resources...
17211 	 */
17212 	while (un->un_recov_buf_busy)
17213 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17214 	un->un_recov_buf_busy = 1;
17215 
17216 	bp = un->un_recov_buf;
17217 	bzero(bp, sizeof (buf_t));
17218 
17219 	bp->b_forw = (struct buf *)(uintptr_t)ucmd->uscsi_cdb[0];
17220 	bp->b_back = (struct buf *)ucmd;
17221 
17222 	mutex_exit(ST_MUTEX);
17223 	rval = scsi_uscsi_handle_cmd(un->un_dev, UIO_SYSSPACE, ucmd,
17224 	    st_strategy, bp, NULL);
17225 	mutex_enter(ST_MUTEX);
17226 
17227 	ucmd->uscsi_resid = bp->b_resid;
17228 
17229 	/*
17230 	 * Free resources
17231 	 */
17232 	un->un_recov_buf_busy = 0;
17233 	cv_signal(&un->un_recov_buf_cv);
17234 
17235 	return (rval);
17236 }
17237 
17238 /*
17239  * Add data to scsi_pkt to help know what to do if the command fails.
17240  */
17241 static void
17242 st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
17243     struct scsi_pkt *pkt)
17244 {
17245 	uint64_t count;
17246 	recov_info *rinfo = (recov_info *)pkt->pkt_private;
17247 
17248 	ST_FUNC(ST_DEVINFO, st_add_recovery_info_to_pkt);
17249 
17250 	ASSERT(rinfo->privatelen == sizeof (pkt_info) ||
17251 	    rinfo->privatelen == sizeof (recov_info));
17252 
17253 	SET_BP_PKT(bp, pkt);
17254 	rinfo->cmd_bp = bp;
17255 
17256 	if (rinfo->privatelen != sizeof (recov_info)) {
17257 		return;
17258 	}
17259 
17260 	rinfo->cmd_bp = bp;
17261 
17262 	rinfo->cmd_attrib = NULL;
17263 
17264 	/*
17265 	 * lookup the command attributes and add them to the recovery info.
17266 	 */
17267 	rinfo->cmd_attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
17268 
17269 	ASSERT(rinfo->cmd_attrib);
17270 
17271 	/*
17272 	 * For commands that there is no way to figure the expected position
17273 	 * once completed, we save the position the command was started from
17274 	 * so that if they fail we can position back and try again.
17275 	 * This has already been done in st_cmd() or st_iscsi_cmd().
17276 	 */
17277 	if (rinfo->cmd_attrib->recov_pos_type == POS_STARTING) {
17278 		/* save current position as the starting position. */
17279 		COPY_POS(&rinfo->pos, &un->un_pos);
17280 		un->un_running.pmode = invalid;
17281 		return;
17282 	}
17283 
17284 	/*
17285 	 * Don't want to update the running position for recovery.
17286 	 */
17287 	if (bp == un->un_recov_buf) {
17288 		rinfo->pos.pmode = un->un_running.pmode;
17289 		return;
17290 	}
17291 	/*
17292 	 * If running position is invalid copy the current position.
17293 	 * Running being set invalid means we are not in a read, write
17294 	 * or write filemark sequence.
17295 	 * We'll copy the current position and start from there.
17296 	 */
17297 	if (un->un_running.pmode == invalid) {
17298 		COPY_POS(&un->un_running, &un->un_pos);
17299 		COPY_POS(&rinfo->pos, &un->un_running);
17300 	} else {
17301 		COPY_POS(&rinfo->pos, &un->un_running);
17302 		if (rinfo->pos.pmode == legacy) {
17303 			/*
17304 			 * Always should be more logical blocks then
17305 			 * data blocks and files marks.
17306 			 */
17307 			ASSERT((rinfo->pos.blkno >= 0) ?
17308 			    rinfo->pos.lgclblkno >=
17309 			    (rinfo->pos.blkno + rinfo->pos.fileno) : 1);
17310 		}
17311 	}
17312 
17313 	/*
17314 	 * If the command is not expected to change the drive position
17315 	 * then the running position should be the expected position.
17316 	 */
17317 	if (rinfo->cmd_attrib->chg_tape_pos == 0) {
17318 		ASSERT(rinfo->cmd_attrib->chg_tape_direction == DIR_NONE);
17319 		return;
17320 	}
17321 
17322 	if (rinfo->cmd_attrib->explicit_cmd_set) {
17323 		ASSERT(rinfo->pos.pmode != invalid);
17324 		ASSERT(rinfo->cmd_attrib->get_cnt);
17325 		count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17326 		/*
17327 		 * This is a user generated CDB.
17328 		 */
17329 		if (bp == un->un_sbufp) {
17330 			uint64_t lbn;
17331 
17332 			lbn = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17333 
17334 			/*
17335 			 * See if this CDB will generate a locate or change
17336 			 * partition.
17337 			 */
17338 			if ((lbn != un->un_running.lgclblkno) ||
17339 			    (pkt->pkt_cdbp[3] != un->un_running.partition)) {
17340 				rinfo->pos.partition = pkt->pkt_cdbp[3];
17341 				rinfo->pos.pmode = logical;
17342 				rinfo->pos.lgclblkno = lbn;
17343 				un->un_running.partition = pkt->pkt_cdbp[3];
17344 				un->un_running.pmode = logical;
17345 				un->un_running.lgclblkno = lbn;
17346 			}
17347 		} else {
17348 			uint64_t lbn = un->un_running.lgclblkno;
17349 
17350 			pkt->pkt_cdbp[3]  = (uchar_t)un->un_running.partition;
17351 
17352 			pkt->pkt_cdbp[4]  = (uchar_t)(lbn >> 56);
17353 			pkt->pkt_cdbp[5]  = (uchar_t)(lbn >> 48);
17354 			pkt->pkt_cdbp[6]  = (uchar_t)(lbn >> 40);
17355 			pkt->pkt_cdbp[7]  = (uchar_t)(lbn >> 32);
17356 			pkt->pkt_cdbp[8]  = (uchar_t)(lbn >> 24);
17357 			pkt->pkt_cdbp[9]  = (uchar_t)(lbn >> 16);
17358 			pkt->pkt_cdbp[10] = (uchar_t)(lbn >> 8);
17359 			pkt->pkt_cdbp[11] = (uchar_t)(lbn);
17360 		}
17361 		rinfo->pos.lgclblkno += count;
17362 		rinfo->pos.blkno += count;
17363 		un->un_running.lgclblkno += count;
17364 		return;
17365 	}
17366 
17367 	if (rinfo->cmd_attrib->chg_tape_pos) {
17368 
17369 		/* should not have got an invalid position from running. */
17370 		if (un->un_mediastate == MTIO_INSERTED) {
17371 			ASSERT(rinfo->pos.pmode != invalid);
17372 		}
17373 
17374 		/* should have either a get count or or get lba function */
17375 		ASSERT(rinfo->cmd_attrib->get_cnt != NULL ||
17376 		    rinfo->cmd_attrib->get_lba != NULL);
17377 
17378 		/* only explicit commands have both and they're handled above */
17379 		ASSERT(!(rinfo->cmd_attrib->get_cnt != NULL &&
17380 		    rinfo->cmd_attrib->get_lba != NULL));
17381 
17382 		/* if it has a get count function */
17383 		if (rinfo->cmd_attrib->get_cnt != NULL) {
17384 			count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17385 			if (count == 0) {
17386 				return;
17387 			}
17388 			/*
17389 			 * Changes position but doesn't transfer data.
17390 			 * i.e. rewind, write_file_mark and load.
17391 			 */
17392 			if (rinfo->cmd_attrib->transfers_data == TRAN_NONE) {
17393 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17394 				case DIR_NONE: /* Erase */
17395 					ASSERT(rinfo->cmd_attrib->cmd ==
17396 					    SCMD_ERASE);
17397 					break;
17398 				case DIR_FORW: /* write_file_mark */
17399 					rinfo->pos.fileno += count;
17400 					rinfo->pos.lgclblkno += count;
17401 					rinfo->pos.blkno = 0;
17402 					un->un_running.fileno += count;
17403 					un->un_running.lgclblkno += count;
17404 					un->un_running.blkno = 0;
17405 					break;
17406 				case DIR_REVC: /* rewind */
17407 					rinfo->pos.fileno = 0;
17408 					rinfo->pos.lgclblkno = 0;
17409 					rinfo->pos.blkno = 0;
17410 					rinfo->pos.eof = ST_NO_EOF;
17411 					rinfo->pos.pmode = legacy;
17412 					un->un_running.fileno = 0;
17413 					un->un_running.lgclblkno = 0;
17414 					un->un_running.blkno = 0;
17415 					un->un_running.eof = ST_NO_EOF;
17416 					if (un->un_running.pmode != legacy)
17417 						un->un_running.pmode = legacy;
17418 					break;
17419 				case DIR_EITH: /* Load unload */
17420 					ASSERT(rinfo->cmd_attrib->cmd ==
17421 					    SCMD_LOAD);
17422 					switch (count & (LD_LOAD | LD_RETEN |
17423 					    LD_RETEN | LD_HOLD)) {
17424 					case LD_UNLOAD:
17425 					case LD_RETEN:
17426 					case LD_HOLD:
17427 					case LD_LOAD | LD_HOLD:
17428 					case LD_EOT | LD_HOLD:
17429 					case LD_RETEN | LD_HOLD:
17430 						rinfo->pos.pmode = invalid;
17431 						un->un_running.pmode = invalid;
17432 						break;
17433 					case LD_EOT:
17434 					case LD_LOAD | LD_EOT:
17435 						rinfo->pos.eof = ST_EOT;
17436 						rinfo->pos.pmode = invalid;
17437 						un->un_running.eof = ST_EOT;
17438 						un->un_running.pmode = invalid;
17439 						break;
17440 					case LD_LOAD:
17441 					case LD_RETEN | LD_LOAD:
17442 						rinfo->pos.fileno = 0;
17443 						rinfo->pos.lgclblkno = 0;
17444 						rinfo->pos.blkno = 0;
17445 						rinfo->pos.eof = ST_NO_EOF;
17446 						rinfo->pos.pmode = legacy;
17447 						un->un_running.fileno = 0;
17448 						un->un_running.lgclblkno = 0;
17449 						un->un_running.blkno = 0;
17450 						un->un_running.eof = ST_NO_EOF;
17451 						break;
17452 					default:
17453 						ASSERT(0);
17454 					}
17455 					break;
17456 				default:
17457 					ASSERT(0);
17458 					break;
17459 				}
17460 			} else {
17461 				/*
17462 				 * Changes position and does transfer data.
17463 				 * i.e. read or write.
17464 				 */
17465 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17466 				case DIR_FORW:
17467 					rinfo->pos.lgclblkno += count;
17468 					rinfo->pos.blkno += count;
17469 					un->un_running.lgclblkno += count;
17470 					un->un_running.blkno += count;
17471 					break;
17472 				case DIR_REVC:
17473 					rinfo->pos.lgclblkno -= count;
17474 					rinfo->pos.blkno -= count;
17475 					un->un_running.lgclblkno -= count;
17476 					un->un_running.blkno -= count;
17477 					break;
17478 				default:
17479 					ASSERT(0);
17480 					break;
17481 				}
17482 			}
17483 		} else if (rinfo->cmd_attrib->get_lba != NULL) {
17484 			/* Have a get LBA fuction. i.e. Locate */
17485 			ASSERT(rinfo->cmd_attrib->chg_tape_direction ==
17486 			    DIR_EITH);
17487 			count = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17488 			un->un_running.lgclblkno = count;
17489 			un->un_running.blkno = 0;
17490 			un->un_running.fileno = 0;
17491 			un->un_running.pmode = logical;
17492 			rinfo->pos.lgclblkno = count;
17493 			rinfo->pos.pmode = invalid;
17494 		} else {
17495 			ASSERT(0);
17496 		}
17497 		return;
17498 	}
17499 
17500 	ST_CDB(ST_DEVINFO, "Unhanded CDB for position prediction",
17501 	    (char *)pkt->pkt_cdbp);
17502 
17503 }
17504 
17505 static int
17506 st_make_sure_mode_data_is_correct(struct scsi_tape *un, ubufunc_t ubf)
17507 {
17508 	int rval;
17509 
17510 	ST_FUNC(ST_DEVINFO, st_make_sure_mode_data_is_correct);
17511 
17512 	/*
17513 	 * check to see if mode data has changed.
17514 	 */
17515 	rval = st_check_mode_for_change(un, ubf);
17516 	if (rval) {
17517 		rval = st_gen_mode_select(un, ubf, un->un_mspl,
17518 		    sizeof (struct seq_mode));
17519 	}
17520 	if (un->un_tlr_flag != TLR_NOT_SUPPORTED) {
17521 		rval |= st_set_target_TLR_mode(un, ubf);
17522 	}
17523 	return (rval);
17524 }
17525 
17526 static int
17527 st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf)
17528 {
17529 	struct seq_mode *current;
17530 	int rval;
17531 	int i;
17532 	caddr_t this;
17533 	caddr_t that;
17534 
17535 	ST_FUNC(ST_DEVINFO, st_check_mode_for_change);
17536 
17537 	/* recovery called with mode tamper before mode selection */
17538 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
17539 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17540 		    "Mode Select not done yet");
17541 		return (0);
17542 	}
17543 
17544 	current = kmem_zalloc(sizeof (struct seq_mode), KM_SLEEP);
17545 
17546 	rval = st_gen_mode_sense(un, ubf, un->un_comp_page, current,
17547 	    sizeof (struct seq_mode));
17548 	if (rval != 0) {
17549 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17550 		    "Mode Sense for mode verification failed");
17551 		kmem_free(current, sizeof (struct seq_mode));
17552 		return (rval);
17553 	}
17554 
17555 	this = (caddr_t)current;
17556 	that = (caddr_t)un->un_mspl;
17557 
17558 	rval = bcmp(this, that, sizeof (struct seq_mode));
17559 	if (rval == 0) {
17560 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17561 		    "Found no changes in mode data");
17562 	}
17563 #ifdef STDEBUG
17564 	else {
17565 		for (i = 1; i < sizeof (struct seq_mode); i++) {
17566 			if (this[i] != that[i]) {
17567 				ST_RECOV(ST_DEVINFO, st_label, CE_CONT,
17568 				    "sense data changed at byte %d was "
17569 				    "0x%x now 0x%x", i,
17570 				    (uchar_t)that[i], (uchar_t)this[i]);
17571 			}
17572 		}
17573 	}
17574 #endif
17575 	kmem_free(current, sizeof (struct seq_mode));
17576 
17577 	return (rval);
17578 }
17579 
17580 static int
17581 st_test_path_to_device(struct scsi_tape *un)
17582 {
17583 	int rval = 0;
17584 	int limit = st_retry_count;
17585 
17586 	ST_FUNC(ST_DEVINFO, st_test_path_to_device);
17587 
17588 	/*
17589 	 * XXX Newer drives may not RESEVATION CONFLICT a TUR.
17590 	 */
17591 	do {
17592 		if (rval != 0) {
17593 			mutex_exit(ST_MUTEX);
17594 			delay(drv_usectohz(1000000));
17595 			mutex_enter(ST_MUTEX);
17596 		}
17597 		rval = st_rcmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
17598 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17599 		    "ping TUR returned 0x%x", rval);
17600 		limit--;
17601 	} while (((rval == EACCES) || (rval == EBUSY)) && limit);
17602 
17603 	if (un->un_status == KEY_NOT_READY || un->un_mediastate == MTIO_EJECTED)
17604 		rval = 0;
17605 
17606 	return (rval);
17607 }
17608 
17609 /*
17610  * Does read position using recov_buf and doesn't update un_pos.
17611  * Does what ever kind of read position you want.
17612  */
17613 static int
17614 st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
17615     read_pos_data_t *raw)
17616 {
17617 	int rval;
17618 	struct uscsi_cmd cmd;
17619 	struct scsi_arq_status status;
17620 	char cdb[CDB_GROUP1];
17621 
17622 	ST_FUNC(ST_DEVINFO, st_recovery_read_pos);
17623 	bzero(&cmd, sizeof (cmd));
17624 
17625 	cdb[0] = SCMD_READ_POSITION;
17626 	cdb[1] = type;
17627 	cdb[2] = 0;
17628 	cdb[3] = 0;
17629 	cdb[4] = 0;
17630 	cdb[5] = 0;
17631 	cdb[6] = 0;
17632 	cdb[7] = 0;
17633 	cdb[8] = (type == EXT_POS) ? 28 : 0;
17634 	cdb[9] = 0;
17635 
17636 	cmd.uscsi_flags = USCSI_READ | USCSI_RQENABLE;
17637 	cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
17638 	cmd.uscsi_cdb = cdb;
17639 	cmd.uscsi_cdblen = sizeof (cdb);
17640 	cmd.uscsi_rqlen = sizeof (status);
17641 	cmd.uscsi_rqbuf = (caddr_t)&status;
17642 	cmd.uscsi_bufaddr = (caddr_t)raw;
17643 	switch (type) {
17644 	case SHORT_POS:
17645 		cmd.uscsi_buflen = sizeof (tape_position_t);
17646 		break;
17647 	case LONG_POS:
17648 		cmd.uscsi_buflen = sizeof (tape_position_long_t);
17649 		break;
17650 	case EXT_POS:
17651 		cmd.uscsi_buflen = sizeof (tape_position_ext_t);
17652 		break;
17653 	default:
17654 		ASSERT(0);
17655 	}
17656 
17657 	rval = st_uscsi_rcmd(un, &cmd, FKIOCTL);
17658 	if (cmd.uscsi_status) {
17659 		rval = EIO;
17660 	}
17661 	return (rval);
17662 }
17663 
17664 static int
17665 st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
17666     read_pos_data_t *raw)
17667 {
17668 	int rval;
17669 	read_p_types type = un->un_read_pos_type;
17670 
17671 	ST_FUNC(ST_DEVINFO, st_recovery_get_position);
17672 
17673 	do {
17674 		rval = st_recovery_read_pos(un, type, raw);
17675 		if (rval != 0) {
17676 			switch (type) {
17677 			case SHORT_POS:
17678 				type = NO_POS;
17679 				break;
17680 
17681 			case LONG_POS:
17682 				type = EXT_POS;
17683 				break;
17684 
17685 			case EXT_POS:
17686 				type = SHORT_POS;
17687 				break;
17688 
17689 			default:
17690 				type = LONG_POS;
17691 				break;
17692 
17693 			}
17694 		} else {
17695 			if (type != un->un_read_pos_type) {
17696 				un->un_read_pos_type = type;
17697 			}
17698 			break;
17699 		}
17700 	} while (type != NO_POS);
17701 
17702 	if (rval == 0) {
17703 		rval = st_interpret_read_pos(un, read, type,
17704 		    sizeof (read_pos_data_t), (caddr_t)raw, 1);
17705 	}
17706 	return (rval);
17707 }
17708 
17709 /*
17710  * based on the command do we retry, continue or give up?
17711  * possable return values?
17712  *	zero do nothing looks fine.
17713  *	EAGAIN retry.
17714  *	EIO failed makes no sense.
17715  */
17716 static int
17717 st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
17718     cmd_attribute const * cmd_att, tapepos_t *read)
17719 {
17720 	int rval;
17721 	read_pos_data_t *readp_datap;
17722 
17723 	ST_FUNC(ST_DEVINFO, st_compare_expected_position);
17724 
17725 	ASSERT(un != NULL);
17726 	ASSERT(ei != NULL);
17727 	ASSERT(read != NULL);
17728 	ASSERT(cmd_att->chg_tape_pos);
17729 
17730 	COPY_POS(read, &ei->ei_expected_pos);
17731 
17732 	readp_datap = kmem_zalloc(sizeof (read_pos_data_t), KM_SLEEP);
17733 
17734 	rval = st_recovery_get_position(un, read, readp_datap);
17735 
17736 	kmem_free(readp_datap, sizeof (read_pos_data_t));
17737 
17738 	if (rval != 0) {
17739 		return (EIO);
17740 	}
17741 
17742 	ST_POS(ST_DEVINFO, "st_compare_expected_position", read);
17743 
17744 	if ((read->pmode == invalid) ||
17745 	    (ei->ei_expected_pos.pmode == invalid)) {
17746 		return (EIO);
17747 	}
17748 
17749 	/*
17750 	 * Command that changes tape position and have an expected position
17751 	 * if it were to chave completed sucessfully.
17752 	 */
17753 	if (cmd_att->recov_pos_type == POS_EXPECTED) {
17754 		uint32_t count;
17755 		int64_t difference;
17756 		uchar_t reposition = 0;
17757 
17758 		ASSERT(cmd_att->get_cnt);
17759 		count = cmd_att->get_cnt(ei->ei_failed_pkt.pkt_cdbp);
17760 
17761 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17762 		    "Got count from CDB and it was %d\n", count);
17763 
17764 		/*
17765 		 * At expected?
17766 		 */
17767 		if (read->lgclblkno == ei->ei_expected_pos.lgclblkno) {
17768 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17769 			    "Found drive to be at expected position\n");
17770 
17771 			/*
17772 			 * If the command should move tape and it got a busy
17773 			 * it shouldn't be in the expected position.
17774 			 */
17775 			if (ei->ei_failing_status.sts_status.sts_busy != 0) {
17776 				reposition = 1;
17777 
17778 			/*
17779 			 * If the command doesn't transfer data should be good.
17780 			 */
17781 			} else if (cmd_att->transfers_data == TRAN_NONE) {
17782 				return (0); /* Good */
17783 
17784 			/*
17785 			 * Command transfers data, should have done so.
17786 			 */
17787 			} else if (ei->ei_failed_pkt.pkt_state &
17788 			    STATE_XFERRED_DATA) {
17789 				return (0); /* Good */
17790 			} else {
17791 				reposition = 1;
17792 			}
17793 		}
17794 
17795 		if (cmd_att->chg_tape_direction == DIR_FORW) {
17796 			difference =
17797 			    ei->ei_expected_pos.lgclblkno - read->lgclblkno;
17798 
17799 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17800 			    "difference between expected and actual is %"
17801 			    PRId64"\n", difference);
17802 			if (count == difference && reposition == 0) {
17803 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17804 				    "Found failed FORW command, retrying\n");
17805 				return (EAGAIN);
17806 			}
17807 
17808 			/*
17809 			 * If rewound or somewhere between the starting position
17810 			 * and the expected position (partial read or write).
17811 			 * Locate to the starting position and try the whole
17812 			 * thing over again.
17813 			 */
17814 			if ((read->lgclblkno == 0) ||
17815 			    ((difference > 0) && (difference < count))) {
17816 				rval = st_logical_block_locate(un,
17817 				    st_uscsi_rcmd, read,
17818 				    ei->ei_expected_pos.lgclblkno - count,
17819 				    ei->ei_expected_pos.partition);
17820 				if (rval == 0) {
17821 					ST_RECOV(ST_DEVINFO, st_label,
17822 					    CE_NOTE, "reestablished FORW"
17823 					    " command retrying\n");
17824 					return (EAGAIN);
17825 				}
17826 			/*
17827 			 * This handles flushed read ahead on the drive or
17828 			 * an aborted read that presents as a busy and advanced
17829 			 * the tape position.
17830 			 */
17831 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17832 			    ((difference < 0) || (reposition == 1))) {
17833 				rval = st_logical_block_locate(un,
17834 				    st_uscsi_rcmd, read,
17835 				    ei->ei_expected_pos.lgclblkno - count,
17836 				    ei->ei_expected_pos.partition);
17837 				if (rval == 0) {
17838 					ST_RECOV(ST_DEVINFO, st_label,
17839 					    CE_NOTE, "reestablished FORW"
17840 					    " read command retrying\n");
17841 					return (EAGAIN);
17842 				}
17843 			/*
17844 			 * XXX swag seeing difference of 2 on write filemark.
17845 			 * If the space to the starting position works on a
17846 			 * write that means the previous write made it to tape.
17847 			 * If not we lost data and have to give up.
17848 			 *
17849 			 * The plot thickens. Now I am attempting to cover a
17850 			 * count of 1 and a differance of 2 on a write.
17851 			 */
17852 			} else if ((difference > count) || (reposition == 1)) {
17853 				rval = st_logical_block_locate(un,
17854 				    st_uscsi_rcmd, read,
17855 				    ei->ei_expected_pos.lgclblkno - count,
17856 				    ei->ei_expected_pos.partition);
17857 				if (rval == 0) {
17858 					ST_RECOV(ST_DEVINFO, st_label,
17859 					    CE_NOTE, "reestablished FORW"
17860 					    " write command retrying\n");
17861 					return (EAGAIN);
17862 				}
17863 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17864 				    "Seek to block %"PRId64" returned %d\n",
17865 				    ei->ei_expected_pos.lgclblkno - count,
17866 				    rval);
17867 			} else {
17868 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17869 				    "Not expected transfers_data = %d "
17870 				    "difference = %"PRId64,
17871 				    cmd_att->transfers_data, difference);
17872 			}
17873 
17874 			return (EIO);
17875 
17876 		} else if (cmd_att->chg_tape_direction == DIR_REVC) {
17877 			/* Don't think we can write backwards */
17878 			ASSERT(cmd_att->transfers_data != TRAN_WRTE);
17879 			difference =
17880 			    read->lgclblkno - ei->ei_expected_pos.lgclblkno;
17881 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17882 			    "difference between expected and actual is %"
17883 			    PRId64"\n", difference);
17884 			if (count == difference && reposition == 0) {
17885 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17886 				    "Found failed REVC command, retrying\n");
17887 				return (EAGAIN);
17888 			}
17889 			if ((read->lgclblkno == 0) ||
17890 			    ((difference > 0) && (difference < count))) {
17891 				rval = st_logical_block_locate(un,
17892 				    st_uscsi_rcmd, read,
17893 				    ei->ei_expected_pos.lgclblkno + count,
17894 				    ei->ei_expected_pos.partition);
17895 				if (rval == 0) {
17896 					ST_RECOV(ST_DEVINFO, st_label,
17897 					    CE_NOTE, "reestablished REVC"
17898 					    " command retrying\n");
17899 					return (EAGAIN);
17900 				}
17901 			/* This handles read ahead in reverse direction */
17902 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17903 			    (difference < 0) || (reposition == 1)) {
17904 				rval = st_logical_block_locate(un,
17905 				    st_uscsi_rcmd, read,
17906 				    ei->ei_expected_pos.lgclblkno - count,
17907 				    ei->ei_expected_pos.partition);
17908 				if (rval == 0) {
17909 					ST_RECOV(ST_DEVINFO, st_label,
17910 					    CE_NOTE, "reestablished REVC"
17911 					    " read command retrying\n");
17912 					return (EAGAIN);
17913 				}
17914 			} else {
17915 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17916 				    "Not expected transfers_data = %d "
17917 				    "difference = %"PRId64,
17918 				    cmd_att->transfers_data, difference);
17919 			}
17920 			return (EIO);
17921 
17922 		} else {
17923 			/*
17924 			 * Commands that change tape position either
17925 			 * direction or don't change position should not
17926 			 * get here.
17927 			 */
17928 			ASSERT(0);
17929 		}
17930 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17931 		    "Didn't find a recoverable position, Failing\n");
17932 
17933 	/*
17934 	 * Command that changes tape position and can only be recovered
17935 	 * by going back to the point of origin and retrying.
17936 	 *
17937 	 * Example SCMD_SPACE.
17938 	 */
17939 	} else if (cmd_att->recov_pos_type == POS_STARTING) {
17940 		/*
17941 		 * This type of command stores the starting position.
17942 		 * If the read position is the starting position,
17943 		 * reissue the command.
17944 		 */
17945 		if (ei->ei_expected_pos.lgclblkno == read->lgclblkno) {
17946 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17947 			    "Found Space command at starting position, "
17948 			    "Reissuing\n");
17949 			return (EAGAIN);
17950 		}
17951 		/*
17952 		 * Not in the position that the command was originally issued,
17953 		 * Attempt to locate to that position.
17954 		 */
17955 		rval = st_logical_block_locate(un, st_uscsi_rcmd, read,
17956 		    ei->ei_expected_pos.lgclblkno,
17957 		    ei->ei_expected_pos.partition);
17958 		if (rval) {
17959 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17960 			    "Found Space at an unexpected position and locate "
17961 			    "back to starting position failed\n");
17962 			return (EIO);
17963 		}
17964 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17965 		    "Found Space at an unexpected position and locate "
17966 		    "back to starting position worked, Reissuing\n");
17967 		return (EAGAIN);
17968 	}
17969 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17970 	    "Unhandled attribute/expected position", &ei->ei_expected_pos);
17971 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17972 	    "Read position above did not make sense", read);
17973 	ASSERT(0);
17974 	return (EIO);
17975 }
17976 
17977 static errstate
17978 st_recover_reissue_pkt(struct scsi_tape *un, struct scsi_pkt *oldpkt)
17979 {
17980 	buf_t *bp;
17981 	buf_t *pkt_bp;
17982 	struct scsi_pkt *newpkt;
17983 	cmd_attribute const *attrib;
17984 	recov_info *rcv = oldpkt->pkt_private;
17985 	uint_t cdblen;
17986 	int queued = 0;
17987 	int rval;
17988 	int flags = 0;
17989 	int stat_size =
17990 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
17991 
17992 	ST_FUNC(ST_DEVINFO, st_recover_reissue_pkt);
17993 
17994 	bp = rcv->cmd_bp;
17995 
17996 	if (rcv->privatelen == sizeof (recov_info)) {
17997 		attrib = rcv->cmd_attrib;
17998 	} else {
17999 		attrib = st_lookup_cmd_attribute(oldpkt->pkt_cdbp[0]);
18000 	}
18001 
18002 	/*
18003 	 * Some non-uscsi commands use the b_bcount for values that
18004 	 * have nothing to do with how much data is transfered.
18005 	 * In those cases we need to hide the buf_t from scsi_init_pkt().
18006 	 */
18007 	if ((BP_UCMD(bp)) && (bp->b_bcount)) {
18008 		pkt_bp = bp;
18009 	} else if (attrib->transfers_data == TRAN_NONE) {
18010 		pkt_bp = NULL;
18011 	} else {
18012 		pkt_bp = bp;
18013 	}
18014 
18015 	/*
18016 	 * if this is a queued command make sure it the only one in the
18017 	 * run queue.
18018 	 */
18019 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
18020 		ASSERT(un->un_runqf == un->un_runql);
18021 		ASSERT(un->un_runqf == bp);
18022 		queued = 1;
18023 	}
18024 
18025 	cdblen = scsi_cdb_size[CDB_GROUPID(oldpkt->pkt_cdbp[0])];
18026 
18027 	if (pkt_bp == un->un_rqs_bp) {
18028 		flags |= PKT_CONSISTENT;
18029 		stat_size = 1;
18030 	}
18031 
18032 	newpkt = scsi_init_pkt(ROUTE, NULL, pkt_bp, cdblen,
18033 	    stat_size, rcv->privatelen, flags, NULL_FUNC, NULL);
18034 	if (newpkt == NULL) {
18035 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
18036 		    "Reissue pkt scsi_init_pkt() failure\n");
18037 		return (COMMAND_DONE_ERROR);
18038 	}
18039 
18040 	ASSERT(newpkt->pkt_resid == 0);
18041 	bp->b_flags &= ~(B_DONE);
18042 	bp->b_resid = 0;
18043 	st_bioerror(bp, 0);
18044 
18045 	bcopy(oldpkt->pkt_private, newpkt->pkt_private, rcv->privatelen);
18046 
18047 	newpkt->pkt_comp = oldpkt->pkt_comp;
18048 	newpkt->pkt_time = oldpkt->pkt_time;
18049 
18050 	bzero(newpkt->pkt_scbp, stat_size);
18051 	bcopy(oldpkt->pkt_cdbp, newpkt->pkt_cdbp, cdblen);
18052 
18053 	newpkt->pkt_state = 0;
18054 	newpkt->pkt_statistics = 0;
18055 
18056 	/*
18057 	 * oldpkt passed in was a copy of the original.
18058 	 * to distroy we need the address of the original.
18059 	 */
18060 	oldpkt = BP_PKT(bp);
18061 
18062 	if (oldpkt == un->un_rqs) {
18063 		ASSERT(bp == un->un_rqs_bp);
18064 		un->un_rqs = newpkt;
18065 	}
18066 
18067 	SET_BP_PKT(bp, newpkt);
18068 
18069 	scsi_destroy_pkt(oldpkt);
18070 
18071 	rval = st_transport(un, newpkt);
18072 	if (rval == TRAN_ACCEPT) {
18073 		return (JUST_RETURN);
18074 	}
18075 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
18076 	    "Reissue pkt st_transport(0x%x) failure\n", rval);
18077 	if (rval != TRAN_BUSY) {
18078 		return (COMMAND_DONE_ERROR);
18079 	}
18080 	mutex_exit(ST_MUTEX);
18081 	rval = st_handle_start_busy(un, bp, ST_TRAN_BUSY_TIMEOUT, queued);
18082 	mutex_enter(ST_MUTEX);
18083 	if (rval) {
18084 		return (COMMAND_DONE_ERROR);
18085 	}
18086 
18087 	return (JUST_RETURN);
18088 }
18089 
18090 static int
18091 st_transport(struct scsi_tape *un, struct scsi_pkt *pkt)
18092 {
18093 	int status;
18094 
18095 	ST_FUNC(ST_DEVINFO, st_transport);
18096 
18097 	ST_CDB(ST_DEVINFO, "transport CDB", (caddr_t)pkt->pkt_cdbp);
18098 
18099 	mutex_exit(ST_MUTEX);
18100 
18101 	status = scsi_transport(pkt);
18102 
18103 	mutex_enter(ST_MUTEX);
18104 
18105 	return (status);
18106 }
18107 
18108 /*
18109  * Removed the buf_t bp from the queue referenced to by head and tail.
18110  * Returns the buf_t pointer if it is found in the queue.
18111  * Returns NULL if it is not found.
18112  */
18113 static buf_t *
18114 st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp)
18115 {
18116 	buf_t *runqbp;
18117 	buf_t *prevbp = NULL;
18118 
18119 	for (runqbp = *head; runqbp != 0; runqbp = runqbp->av_forw) {
18120 		if (runqbp == bp) {
18121 			/* found it, is it at the head? */
18122 			if (runqbp == *head) {
18123 				*head = bp->av_forw;
18124 			} else {
18125 				prevbp->av_forw = bp->av_forw;
18126 			}
18127 			if (*tail == bp) {
18128 				*tail = prevbp;
18129 			}
18130 			bp->av_forw = NULL;
18131 			return (bp); /* found and removed */
18132 		}
18133 		prevbp = runqbp;
18134 	}
18135 	return (NULL);
18136 }
18137 
18138 /*
18139  * Adds a buf_t to the queue pointed to by head and tail.
18140  * Adds it either to the head end or the tail end based on which
18141  * the passed variable end (head or tail) points at.
18142  */
18143 static void
18144 st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp)
18145 {
18146 
18147 	bp->av_forw = NULL;
18148 	if (*head) {
18149 		/* Queue is not empty */
18150 		if (end == *head) {
18151 			/* Add at front of queue */
18152 			bp->av_forw = *head;
18153 			*head = bp;
18154 		} else if (end == *tail) {
18155 			/* Add at end of queue */
18156 			(*tail)->av_forw = bp;
18157 			*tail = bp;
18158 		} else {
18159 			ASSERT(0);
18160 		}
18161 	} else {
18162 		/* Queue is empty */
18163 		*head = bp;
18164 		*tail = bp;
18165 	}
18166 }
18167 
18168 
18169 static uint64_t
18170 st_get_cdb_g0_rw_count(uchar_t *cdb)
18171 {
18172 	uint64_t count;
18173 
18174 	if ((cdb[1]) & 1) {
18175 		/* fixed block mode, the count is the number of blocks */
18176 		count =
18177 		    cdb[2] << 16 |
18178 		    cdb[3] << 8 |
18179 		    cdb[4];
18180 	} else {
18181 		/* variable block mode, the count is the block size */
18182 		count = 1;
18183 	}
18184 	return (count);
18185 }
18186 
18187 static uint64_t
18188 st_get_cdb_g0_sign_count(uchar_t *cdb)
18189 {
18190 	uint64_t count;
18191 
18192 	count =
18193 	    cdb[2] << 16 |
18194 	    cdb[3] << 8 |
18195 	    cdb[4];
18196 	/*
18197 	 * If the sign bit of the 3 byte value is set, extended it.
18198 	 */
18199 	if (count & 0x800000) {
18200 		count |= 0xffffffffff000000;
18201 	}
18202 	return (count);
18203 }
18204 
18205 static uint64_t
18206 st_get_cdb_g0_count(uchar_t *cdb)
18207 {
18208 	uint64_t count;
18209 
18210 	count =
18211 	    cdb[2] << 16 |
18212 	    cdb[3] << 8 |
18213 	    cdb[4];
18214 	return (count);
18215 }
18216 
18217 static uint64_t
18218 st_get_cdb_g5_rw_cnt(uchar_t *cdb)
18219 {
18220 	uint64_t count;
18221 
18222 	if ((cdb[1]) & 1) {
18223 		/* fixed block mode */
18224 		count =
18225 		    cdb[12] << 16 |
18226 		    cdb[13] << 8 |
18227 		    cdb[14];
18228 	} else {
18229 		/* variable block mode */
18230 		count = 1;
18231 	}
18232 	return (count);
18233 }
18234 
18235 static uint64_t
18236 st_get_no_count(uchar_t *cdb)
18237 {
18238 	ASSERT(cdb[0] == SCMD_REWIND);
18239 	return ((uint64_t)cdb[0]);
18240 }
18241 
18242 static uint64_t
18243 st_get_load_options(uchar_t *cdb)
18244 {
18245 	return ((uint64_t)(cdb[4] | (LD_HOLD << 1)));
18246 }
18247 
18248 static uint64_t
18249 st_get_erase_options(uchar_t *cdb)
18250 {
18251 	return (cdb[1] | (cdb[0] << 8));
18252 }
18253 
18254 static uint64_t
18255 st_get_cdb_g1_lba(uchar_t *cdb)
18256 {
18257 	uint64_t lba;
18258 
18259 	lba =
18260 	    cdb[3] << 24 |
18261 	    cdb[4] << 16 |
18262 	    cdb[5] << 8 |
18263 	    cdb[6];
18264 	return (lba);
18265 }
18266 
18267 static uint64_t
18268 st_get_cdb_g5_count(uchar_t *cdb)
18269 {
18270 	uint64_t count =
18271 	    cdb[12] << 16 |
18272 	    cdb[13] << 8 |
18273 	    cdb[14];
18274 
18275 	return (count);
18276 }
18277 
18278 static uint64_t
18279 st_get_cdb_g4g5_cnt(uchar_t *cdb)
18280 {
18281 	uint64_t lba;
18282 
18283 	lba =
18284 	    (uint64_t)cdb[4] << 56 |
18285 	    (uint64_t)cdb[5] << 48 |
18286 	    (uint64_t)cdb[6] << 40 |
18287 	    (uint64_t)cdb[7] << 32 |
18288 	    (uint64_t)cdb[8] << 24 |
18289 	    (uint64_t)cdb[9] << 16 |
18290 	    (uint64_t)cdb[10] << 8 |
18291 	    (uint64_t)cdb[11];
18292 	return (lba);
18293 }
18294 
18295 static const cmd_attribute cmd_attributes[] = {
18296 	{ SCMD_READ,
18297 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_READ, POS_EXPECTED,
18298 	    0, 0, 0, st_get_cdb_g0_rw_count },
18299 	{ SCMD_WRITE,
18300 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18301 	    0, 0, 0, st_get_cdb_g0_rw_count },
18302 	{ SCMD_TEST_UNIT_READY,
18303 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18304 	    0, 0, 0 },
18305 	{ SCMD_REWIND,
18306 	    1, 1, 1, 0, 0, DIR_REVC, TRAN_NONE, POS_EXPECTED,
18307 	    0, 0, 0, st_get_no_count },
18308 	{ SCMD_REQUEST_SENSE,
18309 	    0, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18310 	    0, 0, 0 },
18311 	{ SCMD_READ_BLKLIM,
18312 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18313 	    0, 0, 0 },
18314 	{ SCMD_READ_G4,
18315 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_READ, POS_EXPECTED,
18316 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18317 	{ SCMD_WRITE_G4,
18318 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18319 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18320 	{ SCMD_READ_REVERSE,
18321 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18322 	    0, 0, 0, st_get_cdb_g0_rw_count },
18323 	{ SCMD_READ_REVERSE_G4,
18324 	    1, 0, 1, 1, 1, DIR_REVC, TRAN_READ, POS_EXPECTED,
18325 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18326 	{ SCMD_WRITE_FILE_MARK,
18327 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18328 	    0, 0, 0, st_get_cdb_g0_count },
18329 	{ SCMD_WRITE_FILE_MARK_G4,
18330 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18331 	    0, 0, 0, st_get_cdb_g5_count, st_get_cdb_g4g5_cnt },
18332 	{ SCMD_SPACE,
18333 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18334 	    0, 0, 0, st_get_cdb_g0_sign_count },
18335 	{ SCMD_SPACE_G4,
18336 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18337 	    0, 0, 0, st_get_cdb_g4g5_cnt },
18338 	{ SCMD_INQUIRY,
18339 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18340 	    0, 0, 0 },
18341 	{ SCMD_VERIFY_G0,
18342 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18343 	    0, 0, 0, st_get_cdb_g0_rw_count },
18344 	{ SCMD_VERIFY_G4,
18345 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18346 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18347 	{ SCMD_RECOVER_BUF,
18348 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18349 	    0, 0, 0 },
18350 	{ SCMD_MODE_SELECT,
18351 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18352 	    0, 0, 0 },
18353 	{ SCMD_RESERVE,
18354 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18355 	    0, 0, 0 },
18356 	{ SCMD_RELEASE,
18357 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18358 	    0, 0, 0 },
18359 	{ SCMD_ERASE,
18360 	    1, 0, 1, 1, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18361 	    0, 0, 0, st_get_erase_options },
18362 	{ SCMD_MODE_SENSE,
18363 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18364 	    0, 0, 0 },
18365 	{ SCMD_LOAD,
18366 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18367 	    0, 0, 0, st_get_load_options },
18368 	{ SCMD_GDIAG,
18369 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18370 	    1, 0, 0 },
18371 	{ SCMD_SDIAG,
18372 	    1, 0, 1, 1, 0, DIR_EITH, TRAN_WRTE, POS_EXPECTED,
18373 	    1, 0, 0 },
18374 	{ SCMD_DOORLOCK,
18375 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18376 	    0, 4, 3 },
18377 	{ SCMD_LOCATE,
18378 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18379 	    0, 0, 0, NULL, st_get_cdb_g1_lba },
18380 	{ SCMD_READ_POSITION,
18381 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18382 	    0, 0, 0 },
18383 	{ SCMD_WRITE_BUFFER,
18384 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18385 	    1, 0, 0 },
18386 	{ SCMD_READ_BUFFER,
18387 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18388 	    1, 0, 0 },
18389 	{ SCMD_REPORT_DENSITIES,
18390 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18391 	    0, 0, 0 },
18392 	{ SCMD_LOG_SELECT_G1,
18393 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18394 	    0, 0, 0 },
18395 	{ SCMD_LOG_SENSE_G1,
18396 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18397 	    0, 0, 0 },
18398 	{ SCMD_PRIN,
18399 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18400 	    0, 0, 0 },
18401 	{ SCMD_PROUT,
18402 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18403 	    0, 0, 0 },
18404 	{ SCMD_READ_ATTRIBUTE,
18405 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18406 	    0, 0, 0 },
18407 	{ SCMD_WRITE_ATTRIBUTE,
18408 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18409 	    0, 0, 0 },
18410 	{ SCMD_LOCATE_G4,
18411 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18412 	    0, 0, 0, NULL, st_get_cdb_g4g5_cnt },
18413 	{ SCMD_REPORT_LUNS,
18414 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18415 	    0, 0, 0 },
18416 	{ SCMD_SVC_ACTION_IN_G5,
18417 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18418 	    0, 0, 0 },
18419 	{ SCMD_MAINTENANCE_IN,
18420 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18421 	    0, 0, 0 },
18422 	{ SCMD_MAINTENANCE_OUT,
18423 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18424 	    0, 0, 0 },
18425 	{ 0xff, /* Default attribute for unsupported commands */
18426 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_STARTING,
18427 	    1, 0, 0, NULL, NULL }
18428 };
18429 
18430 static const cmd_attribute *
18431 st_lookup_cmd_attribute(unsigned char cmd)
18432 {
18433 	int i;
18434 	cmd_attribute const *attribute;
18435 
18436 	for (i = 0; i < ST_NUM_MEMBERS(cmd_attributes); i++) {
18437 		attribute = &cmd_attributes[i];
18438 		if (attribute->cmd == cmd) {
18439 			return (attribute);
18440 		}
18441 	}
18442 	ASSERT(attribute);
18443 	return (attribute);
18444 }
18445 
18446 static int
18447 st_reset(struct scsi_tape *un, int reset_type)
18448 {
18449 	int rval;
18450 
18451 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
18452 
18453 	ST_FUNC(ST_DEVINFO, st_reset);
18454 	un->un_rsvd_status |= ST_INITIATED_RESET;
18455 	mutex_exit(ST_MUTEX);
18456 	do {
18457 		rval = scsi_reset(&un->un_sd->sd_address, reset_type);
18458 		if (rval == 0) {
18459 			switch (reset_type) {
18460 			case RESET_LUN:
18461 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18462 				    "LUN reset failed trying target reset");
18463 				reset_type = RESET_TARGET;
18464 				break;
18465 			case RESET_TARGET:
18466 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18467 				    "target reset failed trying bus reset");
18468 				reset_type = RESET_BUS;
18469 				break;
18470 			case RESET_BUS:
18471 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18472 				    "bus reset failed trying all reset");
18473 				reset_type = RESET_ALL;
18474 			default:
18475 				mutex_enter(ST_MUTEX);
18476 				return (rval);
18477 			}
18478 		}
18479 	} while (rval == 0);
18480 	mutex_enter(ST_MUTEX);
18481 	return (rval);
18482 }
18483 
18484 #define	SAS_TLR_MOD_LEN sizeof (struct seq_mode)
18485 static int
18486 st_set_target_TLR_mode(struct scsi_tape *un, ubufunc_t ubf)
18487 {
18488 	int ret;
18489 	int amount = SAS_TLR_MOD_LEN;
18490 	struct seq_mode *mode_data;
18491 
18492 	ST_FUNC(ST_DEVINFO, st_set_target_TLR_mode);
18493 
18494 	mode_data = kmem_zalloc(SAS_TLR_MOD_LEN, KM_SLEEP);
18495 	ret = st_gen_mode_sense(un, ubf, 0x18, mode_data, amount);
18496 	if (ret != DDI_SUCCESS) {
18497 		if (ret != EACCES)
18498 			un->un_tlr_flag = TLR_NOT_SUPPORTED;
18499 		goto out;
18500 	}
18501 	if (mode_data->data_len != amount + 1) {
18502 		amount = mode_data->data_len + 1;
18503 	}
18504 	/* Must be SAS protocol */
18505 	if (mode_data->page.saslun.protocol_id != 6) {
18506 		un->un_tlr_flag = TLR_NOT_SUPPORTED;
18507 		ret = ENOTSUP;
18508 		goto out;
18509 	}
18510 	if (un->un_tlr_flag == TLR_SAS_ONE_DEVICE) {
18511 		if (mode_data->page.saslun.tran_layer_ret == 1)
18512 			goto out;
18513 		mode_data->page.saslun.tran_layer_ret = 1;
18514 	} else {
18515 		if (mode_data->page.saslun.tran_layer_ret == 0)
18516 			goto out;
18517 		mode_data->page.saslun.tran_layer_ret = 0;
18518 	}
18519 	ret = st_gen_mode_select(un, ubf, mode_data, amount);
18520 	if (ret != DDI_SUCCESS) {
18521 		if (ret != EACCES)
18522 			un->un_tlr_flag = TLR_NOT_SUPPORTED;
18523 	} else {
18524 		if (mode_data->page.saslun.tran_layer_ret == 0)
18525 			un->un_tlr_flag = TLR_NOT_KNOWN;
18526 		else
18527 			un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
18528 	}
18529 #ifdef STDEBUG
18530 	st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG, "TLR data sent",
18531 	    (char *)mode_data, amount);
18532 #endif
18533 out:
18534 	kmem_free(mode_data, SAS_TLR_MOD_LEN);
18535 	return (ret);
18536 }
18537 
18538 
18539 static void
18540 st_reset_notification(caddr_t arg)
18541 {
18542 	struct scsi_tape *un = (struct scsi_tape *)arg;
18543 
18544 	ST_FUNC(ST_DEVINFO, st_reset_notification);
18545 	mutex_enter(ST_MUTEX);
18546 
18547 	un->un_unit_attention_flags |= 2;
18548 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
18549 	    ST_RESERVE) {
18550 		un->un_rsvd_status |= ST_LOST_RESERVE;
18551 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18552 		    "Lost Reservation notification");
18553 	} else {
18554 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18555 		    "reset notification");
18556 	}
18557 
18558 	if ((un->un_restore_pos == 0) &&
18559 	    (un->un_state == ST_STATE_CLOSED) ||
18560 	    (un->un_state == ST_STATE_OPEN_PENDING_IO) ||
18561 	    (un->un_state == ST_STATE_CLOSING)) {
18562 		un->un_restore_pos = 1;
18563 	}
18564 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
18565 	    "reset and state was %d\n", un->un_state);
18566 	mutex_exit(ST_MUTEX);
18567 }
18568