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