xref: /titanic_41/usr/src/uts/common/io/scsi/targets/st.c (revision 5bbb4db2c3f208d12bf0fd11769728f9e5ba66a2)
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 2009 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 		mutex_enter(ST_MUTEX);
1450 
1451 		/*
1452 		 * Shouldn't already be suspended, if so return failure
1453 		 */
1454 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1455 			mutex_exit(ST_MUTEX);
1456 			return (DDI_FAILURE);
1457 		}
1458 		if (un->un_state != ST_STATE_CLOSED) {
1459 			mutex_exit(ST_MUTEX);
1460 			return (DDI_FAILURE);
1461 		}
1462 
1463 		/*
1464 		 * Wait for all outstanding I/O's to complete
1465 		 *
1466 		 * we wait on both ncmds and the wait queue for times
1467 		 * when we are flushing after persistent errors are
1468 		 * flagged, which is when ncmds can be 0, and the
1469 		 * queue can still have I/O's.  This way we preserve
1470 		 * order of biodone's.
1471 		 */
1472 		wait_cmds_complete = ddi_get_lbolt();
1473 		wait_cmds_complete +=
1474 		    st_wait_cmds_complete * drv_usectohz(1000000);
1475 		while (un->un_ncmds || un->un_quef ||
1476 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1477 
1478 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1479 			    wait_cmds_complete) == -1) {
1480 				/*
1481 				 * Time expired then cancel the command
1482 				 */
1483 				if (st_reset(un, RESET_LUN) == 0) {
1484 					if (un->un_last_throttle) {
1485 						un->un_throttle =
1486 						    un->un_last_throttle;
1487 					}
1488 					mutex_exit(ST_MUTEX);
1489 					return (DDI_FAILURE);
1490 				} else {
1491 					break;
1492 				}
1493 			}
1494 		}
1495 
1496 		/*
1497 		 * DDI_SUSPEND says that the system "may" power down, we
1498 		 * remember the file and block number before rewinding.
1499 		 * we also need to save state before issuing
1500 		 * any WRITE_FILE_MARK command.
1501 		 */
1502 		(void) st_update_block_pos(un, st_cmd, 0);
1503 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1504 
1505 
1506 		/*
1507 		 * Issue a zero write file fmk command to tell the drive to
1508 		 * flush any buffered tape marks
1509 		 */
1510 		(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1511 
1512 		/*
1513 		 * Because not all tape drives correctly implement buffer
1514 		 * flushing with the zero write file fmk command, issue a
1515 		 * synchronous rewind command to force data flushing.
1516 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1517 		 * anyway.
1518 		 */
1519 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
1520 
1521 		/* stop any new operations */
1522 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1523 		un->un_throttle = 0;
1524 
1525 		/*
1526 		 * cancel any outstanding timeouts
1527 		 */
1528 		if (un->un_delay_tid) {
1529 			timeout_id_t temp_id = un->un_delay_tid;
1530 			un->un_delay_tid = 0;
1531 			un->un_tids_at_suspend |= ST_DELAY_TID;
1532 			mutex_exit(ST_MUTEX);
1533 			(void) untimeout(temp_id);
1534 			mutex_enter(ST_MUTEX);
1535 		}
1536 
1537 		if (un->un_hib_tid) {
1538 			timeout_id_t temp_id = un->un_hib_tid;
1539 			un->un_hib_tid = 0;
1540 			un->un_tids_at_suspend |= ST_HIB_TID;
1541 			mutex_exit(ST_MUTEX);
1542 			(void) untimeout(temp_id);
1543 			mutex_enter(ST_MUTEX);
1544 		}
1545 
1546 		/*
1547 		 * Suspend the scsi_watch_thread
1548 		 */
1549 		if (un->un_swr_token) {
1550 			opaque_t temp_token = un->un_swr_token;
1551 			mutex_exit(ST_MUTEX);
1552 			scsi_watch_suspend(temp_token);
1553 		} else {
1554 			mutex_exit(ST_MUTEX);
1555 		}
1556 
1557 		return (DDI_SUCCESS);
1558 
1559 	default:
1560 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1561 		return (DDI_FAILURE);
1562 	}
1563 }
1564 
1565 
1566 /* ARGSUSED */
1567 static int
1568 st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1569 {
1570 	dev_t dev;
1571 	struct scsi_tape *un;
1572 	int instance, error;
1573 
1574 	ST_ENTR(dip, st_info);
1575 
1576 	switch (infocmd) {
1577 	case DDI_INFO_DEVT2DEVINFO:
1578 		dev = (dev_t)arg;
1579 		instance = MTUNIT(dev);
1580 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1581 			return (DDI_FAILURE);
1582 		*result = (void *) ST_DEVINFO;
1583 		error = DDI_SUCCESS;
1584 		break;
1585 	case DDI_INFO_DEVT2INSTANCE:
1586 		dev = (dev_t)arg;
1587 		instance = MTUNIT(dev);
1588 		*result = (void *)(uintptr_t)instance;
1589 		error = DDI_SUCCESS;
1590 		break;
1591 	default:
1592 		error = DDI_FAILURE;
1593 	}
1594 	return (error);
1595 }
1596 
1597 static int
1598 st_doattach(struct scsi_device *devp, int (*canwait)())
1599 {
1600 	struct scsi_tape *un = NULL;
1601 	recov_info *ri;
1602 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1603 	int instance;
1604 	size_t rlen;
1605 
1606 	ST_FUNC(devp->sd_dev, st_doattach);
1607 	/*
1608 	 * Call the routine scsi_probe to do some of the dirty work.
1609 	 * If the INQUIRY command succeeds, the field sd_inq in the
1610 	 * device structure will be filled in.
1611 	 */
1612 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1613 	    "st_doattach(): probing\n");
1614 
1615 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1616 
1617 		/*
1618 		 * In checking the whole inq_dtype byte we are looking at both
1619 		 * the Peripheral Qualifier and the Peripheral Device Type.
1620 		 * For this driver we are only interested in sequential devices
1621 		 * that are connected or capable if connecting to this logical
1622 		 * unit.
1623 		 */
1624 		if (devp->sd_inq->inq_dtype ==
1625 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1626 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1627 			    "probe exists\n");
1628 		} else {
1629 			/* Something there but not a tape device */
1630 			scsi_unprobe(devp);
1631 			return (DDI_FAILURE);
1632 		}
1633 	} else {
1634 		/* Nothing there */
1635 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1636 		    "probe failure: nothing there\n");
1637 		scsi_unprobe(devp);
1638 		return (DDI_FAILURE);
1639 	}
1640 
1641 
1642 	/*
1643 	 * The actual unit is present.
1644 	 * Now is the time to fill in the rest of our info..
1645 	 */
1646 	instance = ddi_get_instance(devp->sd_dev);
1647 
1648 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1649 		goto error;
1650 	}
1651 	un = ddi_get_soft_state(st_state, instance);
1652 
1653 	ASSERT(un != NULL);
1654 
1655 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
1656 	    MAX_SENSE_LENGTH, B_READ, canwait, NULL);
1657 	if (un->un_rqs_bp == NULL) {
1658 		goto error;
1659 	}
1660 	un->un_rqs = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
1661 	    CDB_GROUP0, 1, st_recov_sz, PKT_CONSISTENT, canwait, NULL);
1662 	if (!un->un_rqs) {
1663 		goto error;
1664 	}
1665 	ASSERT(un->un_rqs->pkt_resid == 0);
1666 	devp->sd_sense =
1667 	    (struct scsi_extended_sense *)un->un_rqs_bp->b_un.b_addr;
1668 	ASSERT(geterror(un->un_rqs_bp) == NULL);
1669 
1670 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs->pkt_cdbp,
1671 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
1672 	FILL_SCSI1_LUN(devp, un->un_rqs);
1673 	un->un_rqs->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1674 	un->un_rqs->pkt_time = st_io_time;
1675 	un->un_rqs->pkt_comp = st_intr;
1676 	ri = (recov_info *)un->un_rqs->pkt_private;
1677 	if (st_recov_sz == sizeof (recov_info)) {
1678 		ri->privatelen = sizeof (recov_info);
1679 	} else {
1680 		ri->privatelen = sizeof (pkt_info);
1681 	}
1682 
1683 	un->un_sbufp = getrbuf(km_flags);
1684 	un->un_recov_buf = getrbuf(km_flags);
1685 
1686 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1687 
1688 	/*
1689 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1690 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1691 	 * is obsolete and we want more flexibility in controlling the DMA
1692 	 * address constraints.
1693 	 */
1694 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1695 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1696 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1697 
1698 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1699 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1700 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1701 
1702 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1703 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1704 		    "probe partial failure: no space\n");
1705 		goto error;
1706 	}
1707 
1708 	bzero(un->un_mspl, sizeof (struct seq_mode));
1709 
1710 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1711 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1712 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1713 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1714 #ifdef	__x86
1715 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1716 #endif
1717 
1718 	/* Initialize power managemnet condition variable */
1719 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1720 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1721 	cv_init(&un->un_recov_buf_cv, NULL, CV_DRIVER, NULL);
1722 
1723 	un->un_recov_taskq = ddi_taskq_create(devp->sd_dev,
1724 	    "un_recov_taskq", 1, TASKQ_DEFAULTPRI, km_flags);
1725 
1726 	ASSERT(un->un_recov_taskq != NULL);
1727 
1728 	un->un_pos.pmode = invalid;
1729 	un->un_sd	= devp;
1730 	un->un_swr_token = (opaque_t)NULL;
1731 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1732 	un->un_wormable = st_is_drive_worm;
1733 	un->un_media_id_method = st_get_media_identification;
1734 	/*
1735 	 * setting long a initial as it contains logical file info.
1736 	 * support for long format is mandatory but many drive don't do it.
1737 	 */
1738 	un->un_read_pos_type = LONG_POS;
1739 
1740 	un->un_suspend_pos.pmode = invalid;
1741 
1742 	st_add_recovery_info_to_pkt(un, un->un_rqs_bp, un->un_rqs);
1743 
1744 #ifdef	__x86
1745 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1746 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1747 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1748 		    "allocation of contiguous memory dma handle failed!");
1749 		un->un_contig_mem_hdl = NULL;
1750 		goto error;
1751 	}
1752 #endif
1753 
1754 	/*
1755 	 * Since this driver manages devices with "remote" hardware,
1756 	 * i.e. the devices themselves have no "reg" properties,
1757 	 * the SUSPEND/RESUME commands in detach/attach will not be
1758 	 * called by the power management framework unless we request
1759 	 * it by creating a "pm-hardware-state" property and setting it
1760 	 * to value "needs-suspend-resume".
1761 	 */
1762 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1763 	    "pm-hardware-state", "needs-suspend-resume") !=
1764 	    DDI_PROP_SUCCESS) {
1765 
1766 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1767 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1768 		goto error;
1769 	}
1770 
1771 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1772 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1773 
1774 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1775 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1776 		    "failed\n");
1777 		goto error;
1778 	}
1779 
1780 	(void) scsi_reset_notify(ROUTE, SCSI_RESET_NOTIFY,
1781 	    st_reset_notification, (caddr_t)un);
1782 
1783 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "attach success\n");
1784 	return (DDI_SUCCESS);
1785 
1786 error:
1787 	devp->sd_sense = NULL;
1788 
1789 	ddi_remove_minor_node(devp->sd_dev, NULL);
1790 	if (un) {
1791 		if (un->un_mspl) {
1792 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1793 		}
1794 		if (un->un_read_pos_data) {
1795 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1796 		}
1797 		if (un->un_sbufp) {
1798 			freerbuf(un->un_sbufp);
1799 		}
1800 		if (un->un_recov_buf) {
1801 			freerbuf(un->un_recov_buf);
1802 		}
1803 		if (un->un_uscsi_rqs_buf) {
1804 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1805 		}
1806 #ifdef	__x86
1807 		if (un->un_contig_mem_hdl != NULL) {
1808 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1809 		}
1810 #endif
1811 		if (un->un_rqs) {
1812 			scsi_destroy_pkt(un->un_rqs);
1813 		}
1814 
1815 		if (un->un_rqs_bp) {
1816 			scsi_free_consistent_buf(un->un_rqs_bp);
1817 		}
1818 
1819 		ddi_soft_state_free(st_state, instance);
1820 		devp->sd_private = NULL;
1821 	}
1822 
1823 	if (devp->sd_inq) {
1824 		scsi_unprobe(devp);
1825 	}
1826 	return (DDI_FAILURE);
1827 }
1828 
1829 typedef int
1830 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1831 
1832 static cfg_functp config_functs[] = {
1833 	st_get_conf_from_st_dot_conf,
1834 	st_get_conf_from_st_conf_dot_c,
1835 	st_get_conf_from_tape_drive,
1836 	st_get_default_conf
1837 };
1838 
1839 
1840 /*
1841  * determine tape type, using tape-config-list or built-in table or
1842  * use a generic tape config entry
1843  */
1844 static void
1845 st_known_tape_type(struct scsi_tape *un)
1846 {
1847 	struct st_drivetype *dp;
1848 	cfg_functp *config_funct;
1849 	uchar_t reserved;
1850 
1851 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1852 
1853 	reserved = (un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1854 	    : ST_RELEASE;
1855 
1856 	/*
1857 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1858 	 *	 no vid & pid inquiry data.  So, we provide one.
1859 	 */
1860 	if (ST_INQUIRY->inq_len == 0 ||
1861 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1862 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1863 	}
1864 
1865 	if (un->un_dp_size == 0) {
1866 		un->un_dp_size = sizeof (struct st_drivetype);
1867 		dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1868 		un->un_dp = dp;
1869 	} else {
1870 		dp = un->un_dp;
1871 	}
1872 
1873 	un->un_dp->non_motion_timeout = st_io_time;
1874 	/*
1875 	 * Loop through the configuration methods till one works.
1876 	 */
1877 	for (config_funct = &config_functs[0]; ; config_funct++) {
1878 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1879 			break;
1880 		}
1881 	}
1882 
1883 	if (un->un_dp->type != ST_TYPE_INVALID) {
1884 		int result;
1885 
1886 		/* try and enable TLR */
1887 		un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
1888 		result = st_set_target_TLR_mode(un, st_uscsi_cmd);
1889 		if (result == EACCES) {
1890 			/*
1891 			 * From attach command failed.
1892 			 * Set dp type so is run again on open.
1893 			 */
1894 			un->un_dp->type = ST_TYPE_INVALID;
1895 			un->un_tlr_flag = TLR_NOT_KNOWN;
1896 		} else if (result == 0) {
1897 			if (scsi_ifgetcap(&un->un_sd->sd_address,
1898 			    "tran-layer-retries", 1) == -1) {
1899 				un->un_tlr_flag = TLR_NOT_SUPPORTED;
1900 				(void) st_set_target_TLR_mode(un, st_uscsi_cmd);
1901 			} else {
1902 				un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
1903 			}
1904 		} else {
1905 			un->un_tlr_flag = TLR_NOT_SUPPORTED;
1906 		}
1907 	}
1908 
1909 
1910 
1911 
1912 	/*
1913 	 * If we didn't just make up this configuration and
1914 	 * all the density codes are the same..
1915 	 * Set Auto Density over ride.
1916 	 */
1917 	if (*config_funct != st_get_default_conf) {
1918 		/*
1919 		 * If this device is one that is configured and all
1920 		 * densities are the same, This saves doing gets and set
1921 		 * that yield nothing.
1922 		 */
1923 		if ((dp->densities[0]) == (dp->densities[1]) &&
1924 		    (dp->densities[0]) == (dp->densities[2]) &&
1925 		    (dp->densities[0]) == (dp->densities[3])) {
1926 
1927 			dp->options |= ST_AUTODEN_OVERRIDE;
1928 		}
1929 	}
1930 
1931 
1932 	/*
1933 	 * Store tape drive characteristics.
1934 	 */
1935 	un->un_status = 0;
1936 	un->un_attached = 1;
1937 	un->un_init_options = dp->options;
1938 
1939 	/* setup operation time-outs based on options */
1940 	st_calculate_timeouts(un);
1941 
1942 	/* make sure if we are supposed to be variable, make it variable */
1943 	if (dp->options & ST_VARIABLE) {
1944 		dp->bsize = 0;
1945 	}
1946 
1947 	if (reserved != ((un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1948 	    : ST_RELEASE)) {
1949 		(void) st_reserve_release(un, reserved, st_uscsi_cmd);
1950 	}
1951 
1952 	un->un_unit_attention_flags |= 1;
1953 
1954 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1955 
1956 }
1957 
1958 
1959 typedef struct {
1960 	int mask;
1961 	int bottom;
1962 	int top;
1963 	char *name;
1964 } conf_limit;
1965 
1966 static const conf_limit conf_limits[] = {
1967 
1968 	-1,		1,		2,		"conf version",
1969 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1970 	-1,		0,		0xffffff,	"block size",
1971 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1972 	-1,		0,		4,		"number of densities",
1973 	-1,		0,		UINT8_MAX,	"density code",
1974 	-1,		0,		3,		"default density",
1975 	-1,		0,		UINT16_MAX,	"non motion timeout",
1976 	-1,		0,		UINT16_MAX,	"I/O timeout",
1977 	-1,		0,		UINT16_MAX,	"space timeout",
1978 	-1,		0,		UINT16_MAX,	"load timeout",
1979 	-1,		0,		UINT16_MAX,	"unload timeout",
1980 	-1,		0,		UINT16_MAX,	"erase timeout",
1981 	0,		0,		0,		NULL
1982 };
1983 
1984 static int
1985 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1986     const char *conf_name)
1987 {
1988 	int dens;
1989 	int ndens;
1990 	int value;
1991 	int type;
1992 	int count;
1993 	const conf_limit *limit = &conf_limits[0];
1994 
1995 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1996 
1997 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1998 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1999 
2000 	count = list_len;
2001 	type = *list;
2002 	for (;  count && limit->name; count--, list++, limit++) {
2003 
2004 		value = *list;
2005 		if (value & ~limit->mask) {
2006 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2007 			    "%s %s value invalid bits set: 0x%X\n",
2008 			    conf_name, limit->name, value & ~limit->mask);
2009 			*list &= limit->mask;
2010 		} else if (value < limit->bottom) {
2011 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2012 			    "%s %s value too low: value = %d limit %d\n",
2013 			    conf_name, limit->name, value, limit->bottom);
2014 		} else if (value > limit->top) {
2015 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2016 			    "%s %s value too high: value = %d limit %d\n",
2017 			    conf_name, limit->name, value, limit->top);
2018 		} else {
2019 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2020 			    "%s %s value = 0x%X\n",
2021 			    conf_name, limit->name, value);
2022 		}
2023 
2024 		/* If not the number of densities continue */
2025 		if (limit != &conf_limits[4]) {
2026 			continue;
2027 		}
2028 
2029 		/* If number of densities is not in range can't use config */
2030 		if (value < limit->bottom || value > limit->top) {
2031 			return (-1);
2032 		}
2033 
2034 		ndens = min(value, NDENSITIES);
2035 		if ((type == 1) && (list_len - ndens) != 6) {
2036 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2037 			    "%s conf version 1 with %d densities has %d items"
2038 			    " should have %d",
2039 			    conf_name, ndens, list_len, 6 + ndens);
2040 		} else if ((type == 2) && (list_len - ndens) != 13) {
2041 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2042 			    "%s conf version 2 with %d densities has %d items"
2043 			    " should have %d",
2044 			    conf_name, ndens, list_len, 13 + ndens);
2045 		}
2046 
2047 		limit++;
2048 		for (dens = 0; dens < ndens && count; dens++) {
2049 			count--;
2050 			list++;
2051 			value = *list;
2052 			if (value < limit->bottom) {
2053 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2054 				    "%s density[%d] value too low: value ="
2055 				    " 0x%X limit 0x%X\n",
2056 				    conf_name, dens, value, limit->bottom);
2057 			} else if (value > limit->top) {
2058 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2059 				    "%s density[%d] value too high: value ="
2060 				    " 0x%X limit 0x%X\n",
2061 				    conf_name, dens, value, limit->top);
2062 			} else {
2063 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2064 				    "%s density[%d] value = 0x%X\n",
2065 				    conf_name, dens, value);
2066 			}
2067 		}
2068 	}
2069 
2070 	return (0);
2071 }
2072 
2073 static int
2074 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
2075     struct st_drivetype *dp)
2076 {
2077 	caddr_t config_list = NULL;
2078 	caddr_t data_list = NULL;
2079 	int	*data_ptr;
2080 	caddr_t vidptr, prettyptr, datanameptr;
2081 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
2082 	int config_list_len, data_list_len, len, i;
2083 	int version;
2084 	int found = 0;
2085 
2086 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
2087 
2088 	/*
2089 	 * Determine type of tape controller. Type is determined by
2090 	 * checking the vendor ids of the earlier inquiry command and
2091 	 * comparing those with vids in tape-config-list defined in st.conf
2092 	 */
2093 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
2094 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
2095 	    != DDI_PROP_SUCCESS) {
2096 		return (found);
2097 	}
2098 
2099 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2100 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
2101 
2102 	/*
2103 	 * Compare vids in each triplet - if it matches, get value for
2104 	 * data_name and contruct a st_drivetype struct
2105 	 * tripletlen is not set yet!
2106 	 */
2107 	for (len = config_list_len, vidptr = config_list;
2108 	    len > 0;
2109 	    vidptr += tripletlen, len -= tripletlen) {
2110 
2111 		vidlen = strlen(vidptr);
2112 		prettyptr = vidptr + vidlen + 1;
2113 		prettylen = strlen(prettyptr);
2114 		datanameptr = prettyptr + prettylen + 1;
2115 		datanamelen = strlen(datanameptr);
2116 		tripletlen = vidlen + prettylen + datanamelen + 3;
2117 
2118 		if (vidlen == 0) {
2119 			continue;
2120 		}
2121 
2122 		/*
2123 		 * If inquiry vid dosen't match this triplets vid,
2124 		 * try the next.
2125 		 */
2126 		if (strncasecmp(vidpid, vidptr, vidlen)) {
2127 			continue;
2128 		}
2129 
2130 		/*
2131 		 * if prettylen is zero then use the vid string
2132 		 */
2133 		if (prettylen == 0) {
2134 			prettyptr = vidptr;
2135 			prettylen = vidlen;
2136 		}
2137 
2138 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2139 		    "vid = %s, pretty=%s, dataname = %s\n",
2140 		    vidptr, prettyptr, datanameptr);
2141 
2142 		/*
2143 		 * get the data list
2144 		 */
2145 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
2146 		    datanameptr, (caddr_t)&data_list,
2147 		    &data_list_len) != DDI_PROP_SUCCESS) {
2148 			/*
2149 			 * Error in getting property value
2150 			 * print warning!
2151 			 */
2152 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2153 			    "data property (%s) has no value\n",
2154 			    datanameptr);
2155 			continue;
2156 		}
2157 
2158 		/*
2159 		 * now initialize the st_drivetype struct
2160 		 */
2161 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
2162 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
2163 		(void) strncpy(dp->vid, vidptr, dp->length);
2164 		data_ptr = (int *)data_list;
2165 		/*
2166 		 * check if data is enough for version, type,
2167 		 * bsize, options, # of densities, density1,
2168 		 * density2, ..., default_density
2169 		 */
2170 		if ((data_list_len < 5 * sizeof (int)) ||
2171 		    (data_list_len < 6 * sizeof (int) +
2172 		    *(data_ptr + 4) * sizeof (int))) {
2173 			/*
2174 			 * print warning and skip to next triplet.
2175 			 */
2176 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2177 			    "data property (%s) incomplete\n",
2178 			    datanameptr);
2179 			kmem_free(data_list, data_list_len);
2180 			continue;
2181 		}
2182 
2183 		if (st_validate_conf_data(un, data_ptr,
2184 		    data_list_len / sizeof (int), datanameptr)) {
2185 			kmem_free(data_list, data_list_len);
2186 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2187 			    "data property (%s) rejected\n",
2188 			    datanameptr);
2189 			continue;
2190 		}
2191 
2192 		/*
2193 		 * check version
2194 		 */
2195 		version = *data_ptr++;
2196 		if (version != 1 && version != 2) {
2197 			/* print warning but accept it */
2198 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2199 			    "Version # for data property (%s) "
2200 			    "not set to 1 or 2\n", datanameptr);
2201 		}
2202 
2203 		dp->type    = *data_ptr++;
2204 		dp->bsize   = *data_ptr++;
2205 		dp->options = *data_ptr++;
2206 		dp->options |= ST_DYNAMIC;
2207 		len = *data_ptr++;
2208 		for (i = 0; i < NDENSITIES; i++) {
2209 			if (i < len) {
2210 				dp->densities[i] = *data_ptr++;
2211 			}
2212 		}
2213 		dp->default_density = *data_ptr << 3;
2214 		if (version == 2 &&
2215 		    data_list_len >= (13 + len) * sizeof (int)) {
2216 			data_ptr++;
2217 			dp->non_motion_timeout	= *data_ptr++;
2218 			dp->io_timeout		= *data_ptr++;
2219 			dp->rewind_timeout	= *data_ptr++;
2220 			dp->space_timeout	= *data_ptr++;
2221 			dp->load_timeout	= *data_ptr++;
2222 			dp->unload_timeout	= *data_ptr++;
2223 			dp->erase_timeout	= *data_ptr++;
2224 		}
2225 		kmem_free(data_list, data_list_len);
2226 		found = 1;
2227 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2228 		    "found in st.conf: vid = %s, pretty=%s\n",
2229 		    dp->vid, dp->name);
2230 		break;
2231 	}
2232 
2233 	/*
2234 	 * free up the memory allocated by ddi_getlongprop
2235 	 */
2236 	if (config_list) {
2237 		kmem_free(config_list, config_list_len);
2238 	}
2239 	return (found);
2240 }
2241 
2242 static int
2243 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2244     struct st_drivetype *dp)
2245 {
2246 	int i;
2247 
2248 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2249 	/*
2250 	 * Determine type of tape controller.  Type is determined by
2251 	 * checking the result of the earlier inquiry command and
2252 	 * comparing vendor ids with strings in a table declared in st_conf.c.
2253 	 */
2254 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2255 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2256 
2257 	for (i = 0; i < st_ndrivetypes; i++) {
2258 		if (st_drivetypes[i].length == 0) {
2259 			continue;
2260 		}
2261 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2262 		    st_drivetypes[i].length)) {
2263 			continue;
2264 		}
2265 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2266 		return (1);
2267 	}
2268 	return (0);
2269 }
2270 
2271 static int
2272 st_get_conf_from_tape_drive(struct scsi_tape *un, char *vidpid,
2273     struct st_drivetype *dp)
2274 {
2275 	int bsize;
2276 	ulong_t maxbsize;
2277 	caddr_t buf;
2278 	struct st_drivetype *tem_dp;
2279 	struct read_blklim *blklim;
2280 	int rval;
2281 	int i;
2282 
2283 	ST_FUNC(ST_DEVINFO, st_get_conf_from_tape_drive);
2284 
2285 	/*
2286 	 * Determine the type of tape controller. Type is determined by
2287 	 * sending SCSI commands to tape drive and deriving the type from
2288 	 * the returned data.
2289 	 */
2290 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2291 	    "st_get_conf_from_tape_drive(): asking tape drive\n");
2292 
2293 	tem_dp = kmem_zalloc(sizeof (struct st_drivetype), KM_SLEEP);
2294 
2295 	/*
2296 	 * Make up a name
2297 	 */
2298 	bcopy(vidpid, tem_dp->name, VIDPIDLEN);
2299 	tem_dp->name[VIDPIDLEN] = '\0';
2300 	tem_dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2301 	(void) strncpy(tem_dp->vid, ST_INQUIRY->inq_vid, tem_dp->length);
2302 	/*
2303 	 * 'clean' vendor and product strings of non-printing chars
2304 	 */
2305 	for (i = 0; i < VIDPIDLEN - 1; i ++) {
2306 		if (tem_dp->name[i] < ' ' || tem_dp->name[i] > '~') {
2307 			tem_dp->name[i] = '.';
2308 		}
2309 	}
2310 
2311 	/*
2312 	 * MODE SENSE to determine block size.
2313 	 */
2314 	un->un_dp->options |= ST_MODE_SEL_COMP | ST_UNLOADABLE;
2315 	rval = st_modesense(un);
2316 	if (rval) {
2317 		if (rval == EACCES) {
2318 			un->un_dp->type = ST_TYPE_INVALID;
2319 			rval = 1;
2320 		} else {
2321 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
2322 			rval = 0;
2323 		}
2324 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2325 		    "st_get_conf_from_tape_drive(): fail to mode sense\n");
2326 		goto exit;
2327 	}
2328 
2329 	/* Can mode sense page 0x10 or 0xf */
2330 	tem_dp->options |= ST_MODE_SEL_COMP;
2331 	bsize = (un->un_mspl->high_bl << 16)	|
2332 	    (un->un_mspl->mid_bl << 8)		|
2333 	    (un->un_mspl->low_bl);
2334 
2335 	if (bsize == 0) {
2336 		tem_dp->options |= ST_VARIABLE;
2337 		tem_dp->bsize = 0;
2338 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
2339 		rval = st_change_block_size(un, 0);
2340 		if (rval) {
2341 			if (rval == EACCES) {
2342 				un->un_dp->type = ST_TYPE_INVALID;
2343 				rval = 1;
2344 			} else {
2345 				rval = 0;
2346 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2347 				    "st_get_conf_from_tape_drive(): "
2348 				    "Fixed record size is too large and"
2349 				    "cannot switch to variable record size");
2350 			}
2351 			goto exit;
2352 		}
2353 		tem_dp->options |= ST_VARIABLE;
2354 	} else {
2355 		rval = st_change_block_size(un, 0);
2356 		if (rval == 0) {
2357 			tem_dp->options |= ST_VARIABLE;
2358 			tem_dp->bsize = 0;
2359 		} else if (rval != EACCES) {
2360 			tem_dp->bsize = bsize;
2361 		} else {
2362 			un->un_dp->type = ST_TYPE_INVALID;
2363 			rval = 1;
2364 			goto exit;
2365 		}
2366 	}
2367 
2368 	/*
2369 	 * If READ BLOCk LIMITS works and upper block size limit is
2370 	 * more than 64K, ST_NO_RECSIZE_LIMIT is supported.
2371 	 */
2372 	blklim = kmem_zalloc(sizeof (struct read_blklim), KM_SLEEP);
2373 	rval = st_read_block_limits(un, blklim);
2374 	if (rval) {
2375 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2376 		    "st_get_conf_from_tape_drive(): "
2377 		    "fail to read block limits.\n");
2378 		rval = 0;
2379 		kmem_free(blklim, sizeof (struct read_blklim));
2380 		goto exit;
2381 	}
2382 	maxbsize = (blklim->max_hi << 16) +
2383 	    (blklim->max_mid << 8) + blklim->max_lo;
2384 	if (maxbsize > ST_MAXRECSIZE_VARIABLE) {
2385 		tem_dp->options |= ST_NO_RECSIZE_LIMIT;
2386 	}
2387 	kmem_free(blklim, sizeof (struct read_blklim));
2388 
2389 	/*
2390 	 * Inquiry VPD page 0xb0 to see if the tape drive supports WORM
2391 	 */
2392 	buf = kmem_zalloc(6, KM_SLEEP);
2393 	rval = st_get_special_inquiry(un, 6, buf, 0xb0);
2394 	if (rval) {
2395 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2396 		    "st_get_conf_from_tape_drive(): "
2397 		    "fail to read vitial inquiry.\n");
2398 		rval = 0;
2399 		kmem_free(buf, 6);
2400 		goto exit;
2401 	}
2402 	if (buf[4] & 1) {
2403 		tem_dp->options |= ST_WORMABLE;
2404 	}
2405 	kmem_free(buf, 6);
2406 
2407 	/* Assume BSD BSR KNOWS_EOD */
2408 	tem_dp->options |= ST_BSF | ST_BSR | ST_KNOWS_EOD | ST_UNLOADABLE;
2409 	tem_dp->max_rretries = -1;
2410 	tem_dp->max_wretries = -1;
2411 
2412 	/*
2413 	 * Decide the densities supported by tape drive by sending
2414 	 * REPORT DENSITY SUPPORT command.
2415 	 */
2416 	if (st_get_densities_from_tape_drive(un, tem_dp) == 0) {
2417 		goto exit;
2418 	}
2419 
2420 	/*
2421 	 * Decide the timeout values for several commands by sending
2422 	 * REPORT SUPPORTED OPERATION CODES command.
2423 	 */
2424 	rval = st_get_timeout_values_from_tape_drive(un, tem_dp);
2425 	if (rval == 0 || ((rval == 1) && (tem_dp->type == ST_TYPE_INVALID))) {
2426 		goto exit;
2427 	}
2428 
2429 	bcopy(tem_dp, dp, sizeof (struct st_drivetype));
2430 	rval = 1;
2431 
2432 exit:
2433 	un->un_status = KEY_NO_SENSE;
2434 	kmem_free(tem_dp, sizeof (struct st_drivetype));
2435 	return (rval);
2436 }
2437 
2438 static int
2439 st_get_densities_from_tape_drive(struct scsi_tape *un,
2440     struct st_drivetype *dp)
2441 {
2442 	int i, p;
2443 	size_t buflen;
2444 	ushort_t des_len;
2445 	uchar_t *den_header;
2446 	uchar_t num_den;
2447 	uchar_t den[NDENSITIES];
2448 	uchar_t deflt[NDENSITIES];
2449 	struct report_density_desc *den_desc;
2450 
2451 	ST_FUNC(ST_DEVINFO, st_get_densities_from_type_drive);
2452 
2453 	/*
2454 	 * Since we have no idea how many densitiy support entries
2455 	 * will be returned, we send the command firstly assuming
2456 	 * there is only one. Then we can decide the number of
2457 	 * entries by available density support length. If multiple
2458 	 * entries exist, we will resend the command with enough
2459 	 * buffer size.
2460 	 */
2461 	buflen = sizeof (struct report_density_header) +
2462 	    sizeof (struct report_density_desc);
2463 	den_header = kmem_zalloc(buflen, KM_SLEEP);
2464 	if (st_report_density_support(un, den_header, buflen) != 0) {
2465 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2466 		    "st_get_conf_from_tape_drive(): fail to report density.\n");
2467 		kmem_free(den_header, buflen);
2468 		return (0);
2469 	}
2470 	des_len =
2471 	    BE_16(((struct report_density_header *)den_header)->ava_dens_len);
2472 	num_den = (des_len - 2) / sizeof (struct report_density_desc);
2473 
2474 	if (num_den > 1) {
2475 		kmem_free(den_header, buflen);
2476 		buflen = sizeof (struct report_density_header) +
2477 		    sizeof (struct report_density_desc) * num_den;
2478 		den_header = kmem_zalloc(buflen, KM_SLEEP);
2479 		if (st_report_density_support(un, den_header, buflen) != 0) {
2480 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2481 			    "st_get_conf_from_tape_drive(): "
2482 			    "fail to report density.\n");
2483 			kmem_free(den_header, buflen);
2484 			return (0);
2485 		}
2486 	}
2487 
2488 	den_desc = (struct report_density_desc *)(den_header
2489 	    + sizeof (struct report_density_header));
2490 
2491 	/*
2492 	 * Decide the drive type by assigning organization
2493 	 */
2494 	for (i = 0; i < ST_NUM_MEMBERS(st_vid_dt); i ++) {
2495 		if (strncmp(st_vid_dt[i].vid, (char *)(den_desc->ass_org),
2496 		    8) == 0) {
2497 			dp->type = st_vid_dt[i].type;
2498 			break;
2499 		}
2500 	}
2501 	if (i == ST_NUM_MEMBERS(st_vid_dt)) {
2502 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2503 		    "st_get_conf_from_tape_drive(): "
2504 		    "can't find match of assigned ort.\n");
2505 		kmem_free(den_header, buflen);
2506 		return (0);
2507 	}
2508 
2509 	/*
2510 	 * The tape drive may support many tape formats, but the st driver
2511 	 * supports only the four highest densities. Since density code
2512 	 * values are returned by ascending sequence, we start from the
2513 	 * last entry of density support data block descriptor.
2514 	 */
2515 	p = 0;
2516 	den_desc += num_den - 1;
2517 	for (i = 0; i < num_den && p < NDENSITIES; i ++, den_desc --) {
2518 		if ((den_desc->pri_den != 0) && (den_desc->wrtok)) {
2519 			if (p != 0) {
2520 				if (den_desc->pri_den >= den[p - 1]) {
2521 					continue;
2522 				}
2523 			}
2524 			den[p] = den_desc->pri_den;
2525 			deflt[p] = den_desc->deflt;
2526 			p ++;
2527 		}
2528 	}
2529 
2530 	switch (p) {
2531 	case 0:
2532 		bzero(dp->densities, NDENSITIES);
2533 		dp->options |= ST_AUTODEN_OVERRIDE;
2534 		dp->default_density = MT_DENSITY4;
2535 		break;
2536 
2537 	case 1:
2538 		(void) memset(dp->densities, den[0], NDENSITIES);
2539 		dp->options |= ST_AUTODEN_OVERRIDE;
2540 		dp->default_density = MT_DENSITY4;
2541 		break;
2542 
2543 	case 2:
2544 		dp->densities[0] = den[1];
2545 		dp->densities[1] = den[1];
2546 		dp->densities[2] = den[0];
2547 		dp->densities[3] = den[0];
2548 		if (deflt[0]) {
2549 			dp->default_density = MT_DENSITY4;
2550 		} else {
2551 			dp->default_density = MT_DENSITY2;
2552 		}
2553 		break;
2554 
2555 	case 3:
2556 		dp->densities[0] = den[2];
2557 		dp->densities[1] = den[1];
2558 		dp->densities[2] = den[0];
2559 		dp->densities[3] = den[0];
2560 		if (deflt[0]) {
2561 			dp->default_density = MT_DENSITY4;
2562 		} else if (deflt[1]) {
2563 			dp->default_density = MT_DENSITY2;
2564 		} else {
2565 			dp->default_density = MT_DENSITY1;
2566 		}
2567 		break;
2568 
2569 	default:
2570 		for (i = p; i > p - NDENSITIES; i --) {
2571 			dp->densities[i - 1] = den[p - i];
2572 		}
2573 		if (deflt[0]) {
2574 			dp->default_density = MT_DENSITY4;
2575 		} else if (deflt[1]) {
2576 			dp->default_density = MT_DENSITY3;
2577 		} else if (deflt[2]) {
2578 			dp->default_density = MT_DENSITY2;
2579 		} else {
2580 			dp->default_density = MT_DENSITY1;
2581 		}
2582 		break;
2583 	}
2584 
2585 	bzero(dp->mediatype, NDENSITIES);
2586 
2587 	kmem_free(den_header, buflen);
2588 	return (1);
2589 }
2590 
2591 static int
2592 st_get_timeout_values_from_tape_drive(struct scsi_tape *un,
2593     struct st_drivetype *dp)
2594 {
2595 	ushort_t timeout;
2596 	int rval;
2597 
2598 	ST_FUNC(ST_DEVINFO, st_get_timeout_values_from_type_drive);
2599 
2600 	rval = st_get_timeouts_value(un, SCMD_ERASE, &timeout, 0);
2601 	if (rval) {
2602 		if (rval == EACCES) {
2603 			un->un_dp->type = ST_TYPE_INVALID;
2604 			dp->type = ST_TYPE_INVALID;
2605 			return (1);
2606 		}
2607 		return (0);
2608 	}
2609 	dp->erase_timeout = timeout;
2610 
2611 	rval = st_get_timeouts_value(un, SCMD_READ, &timeout, 0);
2612 	if (rval) {
2613 		if (rval == EACCES) {
2614 			un->un_dp->type = ST_TYPE_INVALID;
2615 			dp->type = ST_TYPE_INVALID;
2616 			return (1);
2617 		}
2618 		return (0);
2619 	}
2620 	dp->io_timeout = timeout;
2621 
2622 	rval = st_get_timeouts_value(un, SCMD_WRITE, &timeout, 0);
2623 	if (rval) {
2624 		if (rval == EACCES) {
2625 			un->un_dp->type = ST_TYPE_INVALID;
2626 			dp->type = ST_TYPE_INVALID;
2627 			return (1);
2628 		}
2629 		return (0);
2630 	}
2631 	dp->io_timeout = max(dp->io_timeout, timeout);
2632 
2633 	rval = st_get_timeouts_value(un, SCMD_SPACE, &timeout, 0);
2634 	if (rval) {
2635 		if (rval == EACCES) {
2636 			un->un_dp->type = ST_TYPE_INVALID;
2637 			dp->type = ST_TYPE_INVALID;
2638 			return (1);
2639 		}
2640 		return (0);
2641 	}
2642 	dp->space_timeout = timeout;
2643 
2644 	rval = st_get_timeouts_value(un, SCMD_LOAD, &timeout, 0);
2645 	if (rval) {
2646 		if (rval == EACCES) {
2647 			un->un_dp->type = ST_TYPE_INVALID;
2648 			dp->type = ST_TYPE_INVALID;
2649 			return (1);
2650 		}
2651 		return (0);
2652 	}
2653 	dp->load_timeout = timeout;
2654 	dp->unload_timeout = timeout;
2655 
2656 	rval = st_get_timeouts_value(un, SCMD_REWIND, &timeout, 0);
2657 	if (rval) {
2658 		if (rval == EACCES) {
2659 			un->un_dp->type = ST_TYPE_INVALID;
2660 			dp->type = ST_TYPE_INVALID;
2661 			return (1);
2662 		}
2663 		return (0);
2664 	}
2665 	dp->rewind_timeout = timeout;
2666 
2667 	rval = st_get_timeouts_value(un, SCMD_INQUIRY, &timeout, 0);
2668 	if (rval) {
2669 		if (rval == EACCES) {
2670 			un->un_dp->type = ST_TYPE_INVALID;
2671 			dp->type = ST_TYPE_INVALID;
2672 			return (1);
2673 		}
2674 		return (0);
2675 	}
2676 	dp->non_motion_timeout = timeout;
2677 
2678 	return (1);
2679 }
2680 
2681 static int
2682 st_get_timeouts_value(struct scsi_tape *un, uchar_t option_code,
2683     ushort_t *timeout_value, ushort_t service_action)
2684 {
2685 	uchar_t *timeouts;
2686 	uchar_t *oper;
2687 	uchar_t support;
2688 	uchar_t cdbsize;
2689 	uchar_t ctdp;
2690 	size_t buflen;
2691 	int rval;
2692 
2693 	ST_FUNC(ST_DEVINFO, st_get_timeouts_value);
2694 
2695 	buflen = sizeof (struct one_com_des) +
2696 	    sizeof (struct com_timeout_des);
2697 	oper = kmem_zalloc(buflen, KM_SLEEP);
2698 	rval = st_report_supported_operation(un, oper, option_code,
2699 	    service_action);
2700 
2701 	if (rval) {
2702 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2703 		    "st_get_timeouts_value(): "
2704 		    "fail to timeouts value for command %d.\n", option_code);
2705 		kmem_free(oper, buflen);
2706 		return (rval);
2707 	}
2708 
2709 	support = ((struct one_com_des *)oper)->support;
2710 	if ((support != SUPPORT_VALUES_SUPPORT_SCSI) &&
2711 	    (support != SUPPORT_VALUES_SUPPORT_VENDOR)) {
2712 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2713 		    "st_get_timeouts_value(): "
2714 		    "command %d is not supported.\n", option_code);
2715 		kmem_free(oper, buflen);
2716 		return (ENOTSUP);
2717 	}
2718 
2719 	ctdp = ((struct one_com_des *)oper)->ctdp;
2720 	if (!ctdp) {
2721 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2722 		    "st_get_timeouts_value(): "
2723 		    "command timeout is not included.\n");
2724 		kmem_free(oper, buflen);
2725 		return (ENOTSUP);
2726 	}
2727 
2728 	cdbsize = BE_16(((struct one_com_des *)oper)->cdb_size);
2729 	timeouts = (uchar_t *)(oper + cdbsize + 4);
2730 
2731 	/*
2732 	 * Timeout value in seconds is 4 bytes, but we only support the lower 2
2733 	 * bytes. If the higher 2 bytes are not zero, the timeout value is set
2734 	 * to 0xFFFF.
2735 	 */
2736 	if (*(timeouts + 8) != 0 || *(timeouts + 9) != 0) {
2737 		*timeout_value = USHRT_MAX;
2738 	} else {
2739 		*timeout_value = ((*(timeouts + 10)) << 8) |
2740 		    (*(timeouts + 11));
2741 	}
2742 
2743 	kmem_free(oper, buflen);
2744 	return (0);
2745 }
2746 
2747 static int
2748 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2749 {
2750 	int i;
2751 
2752 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2753 
2754 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2755 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2756 
2757 	/*
2758 	 * Make up a name
2759 	 */
2760 	bcopy("Vendor '", dp->name, 8);
2761 	bcopy(vidpid, &dp->name[8], VIDLEN);
2762 	bcopy("' Product '", &dp->name[16], 11);
2763 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2764 	dp->name[ST_NAMESIZE - 2] = '\'';
2765 	dp->name[ST_NAMESIZE - 1] = '\0';
2766 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2767 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2768 	/*
2769 	 * 'clean' vendor and product strings of non-printing chars
2770 	 */
2771 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2772 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2773 			dp->name[i] = '.';
2774 		}
2775 	}
2776 	dp->type = ST_TYPE_INVALID;
2777 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2778 
2779 	return (1); /* Can Not Fail */
2780 }
2781 
2782 /*
2783  * Regular Unix Entry points
2784  */
2785 
2786 
2787 
2788 /* ARGSUSED */
2789 static int
2790 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2791 {
2792 	dev_t dev = *dev_p;
2793 	int rval = 0;
2794 
2795 	GET_SOFT_STATE(dev);
2796 
2797 	ST_ENTR(ST_DEVINFO, st_open);
2798 
2799 	/*
2800 	 * validate that we are addressing a sensible unit
2801 	 */
2802 	mutex_enter(ST_MUTEX);
2803 
2804 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2805 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2806 	    st_dev_name(dev), *dev_p, flag, otyp);
2807 
2808 	/*
2809 	 * All device accesss go thru st_strategy() where we check
2810 	 * suspend status
2811 	 */
2812 
2813 	if (!un->un_attached) {
2814 		st_known_tape_type(un);
2815 		if (!un->un_attached) {
2816 			rval = ENXIO;
2817 			goto exit;
2818 		}
2819 
2820 	}
2821 
2822 	/*
2823 	 * Check for the case of the tape in the middle of closing.
2824 	 * This isn't simply a check of the current state, because
2825 	 * we could be in state of sensing with the previous state
2826 	 * that of closing.
2827 	 *
2828 	 * And don't allow multiple opens.
2829 	 */
2830 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2831 		un->un_laststate = un->un_state;
2832 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2833 		while (IS_CLOSING(un) ||
2834 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2835 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2836 				rval = EINTR;
2837 				un->un_state = un->un_laststate;
2838 				goto exit;
2839 			}
2840 		}
2841 	} else if (un->un_state != ST_STATE_CLOSED) {
2842 		rval = EBUSY;
2843 		goto busy;
2844 	}
2845 
2846 	/*
2847 	 * record current dev
2848 	 */
2849 	un->un_dev = dev;
2850 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2851 	un->un_errno = 0;	/* no errors yet */
2852 	un->un_restore_pos = 0;
2853 	un->un_rqs_state = 0;
2854 
2855 	/*
2856 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2857 	 * anything, leave internal states alone, if fileno >= 0
2858 	 */
2859 	if (flag & (FNDELAY | FNONBLOCK)) {
2860 		switch (un->un_pos.pmode) {
2861 
2862 		case invalid:
2863 			un->un_state = ST_STATE_OFFLINE;
2864 			break;
2865 
2866 		case legacy:
2867 			/*
2868 			 * If position is anything other than rewound.
2869 			 */
2870 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2871 				/*
2872 				 * set un_read_only/write-protect status.
2873 				 *
2874 				 * If the tape is not bot we can assume
2875 				 * that mspl->wp_status is set properly.
2876 				 * else
2877 				 * we need to do a mode sense/Tur once
2878 				 * again to get the actual tape status.(since
2879 				 * user might have replaced the tape)
2880 				 * Hence make the st state OFFLINE so that
2881 				 * we re-intialize the tape once again.
2882 				 */
2883 				un->un_read_only =
2884 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2885 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2886 			} else {
2887 				un->un_state = ST_STATE_OFFLINE;
2888 			}
2889 			break;
2890 		case logical:
2891 			if (un->un_pos.lgclblkno == 0) {
2892 				un->un_state = ST_STATE_OFFLINE;
2893 			} else {
2894 				un->un_read_only =
2895 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2896 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2897 			}
2898 			break;
2899 		}
2900 		rval = 0;
2901 	} else {
2902 		/*
2903 		 * Not opening O_NDELAY.
2904 		 */
2905 		un->un_state = ST_STATE_OPENING;
2906 
2907 		/*
2908 		 * Clear error entry stack
2909 		 */
2910 		st_empty_error_stack(un);
2911 
2912 		rval = st_tape_init(un);
2913 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2914 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2915 			rval = 0; /* so open doesn't fail */
2916 		} else if (rval) {
2917 			/*
2918 			 * Release the tape unit, if reserved and not
2919 			 * preserve reserve.
2920 			 */
2921 			if ((un->un_rsvd_status &
2922 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2923 				(void) st_reserve_release(un, ST_RELEASE,
2924 				    st_uscsi_cmd);
2925 			}
2926 		} else {
2927 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2928 		}
2929 	}
2930 
2931 exit:
2932 	/*
2933 	 * we don't want any uninvited guests scrogging our data when we're
2934 	 * busy with something, so for successful opens or failed opens
2935 	 * (except for EBUSY), reset these counters and state appropriately.
2936 	 */
2937 	if (rval != EBUSY) {
2938 		if (rval) {
2939 			un->un_state = ST_STATE_CLOSED;
2940 		}
2941 		un->un_err_resid = 0;
2942 		un->un_retry_ct = 0;
2943 	}
2944 busy:
2945 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2946 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2947 	mutex_exit(ST_MUTEX);
2948 	return (rval);
2949 
2950 }
2951 
2952 static int
2953 st_tape_init(struct scsi_tape *un)
2954 {
2955 	int err;
2956 	int rval = 0;
2957 
2958 	ST_FUNC(ST_DEVINFO, st_tape_init);
2959 
2960 	ASSERT(mutex_owned(ST_MUTEX));
2961 
2962 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2963 	    "st_tape_init(un = 0x%p, oflags = %d)\n", (void*)un, un->un_oflags);
2964 
2965 	/*
2966 	 * Clean up after any errors left by 'last' close.
2967 	 * This also handles the case of the initial open.
2968 	 */
2969 	if (un->un_state != ST_STATE_INITIALIZING) {
2970 		un->un_laststate = un->un_state;
2971 		un->un_state = ST_STATE_OPENING;
2972 	}
2973 
2974 	un->un_kbytes_xferred = 0;
2975 
2976 	/*
2977 	 * do a throw away TUR to clear check condition
2978 	 */
2979 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2980 
2981 	/*
2982 	 * If test unit ready fails because the drive is reserved
2983 	 * by another host fail the open for no access.
2984 	 */
2985 	if (err) {
2986 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2987 			un->un_state = ST_STATE_CLOSED;
2988 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2989 			    "st_tape_init: RESERVATION CONFLICT\n");
2990 			rval = EACCES;
2991 			goto exit;
2992 		} else if ((un->un_rsvd_status &
2993 		    ST_APPLICATION_RESERVATIONS) != 0) {
2994 			if ((ST_RQSENSE != NULL) &&
2995 			    (ST_RQSENSE->es_add_code == 0x2a &&
2996 			    ST_RQSENSE->es_qual_code == 0x03)) {
2997 				un->un_state = ST_STATE_CLOSED;
2998 				rval = EACCES;
2999 				goto exit;
3000 			}
3001 		}
3002 	}
3003 
3004 	/*
3005 	 * Tape self identification could fail if the tape drive is used by
3006 	 * another host during attach time. We try to get the tape type
3007 	 * again. This is also applied to any posponed configuration methods.
3008 	 */
3009 	if (un->un_dp->type == ST_TYPE_INVALID) {
3010 		un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
3011 		st_known_tape_type(un);
3012 	}
3013 
3014 	/*
3015 	 * If the tape type is still invalid, try to determine the generic
3016 	 * configuration.
3017 	 */
3018 	if (un->un_dp->type == ST_TYPE_INVALID) {
3019 		rval = st_determine_generic(un);
3020 		if (rval) {
3021 			if (rval != EACCES) {
3022 				rval = EIO;
3023 			}
3024 			un->un_state = ST_STATE_CLOSED;
3025 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3026 			    "st_tape_init: %s invalid type\n",
3027 			    rval == EACCES ? "EACCES" : "EIO");
3028 			goto exit;
3029 		}
3030 		/*
3031 		 * If this is a Unknown Type drive,
3032 		 * Use the READ BLOCK LIMITS to determine if
3033 		 * allow large xfer is approprate if not globally
3034 		 * disabled with st_allow_large_xfer.
3035 		 */
3036 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
3037 	} else {
3038 
3039 		/*
3040 		 * If we allow_large_xfer (ie >64k) and have not yet found out
3041 		 * the max block size supported by the drive,
3042 		 * find it by issueing a READ_BLKLIM command.
3043 		 * if READ_BLKLIM cmd fails, assume drive doesn't
3044 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
3045 		 */
3046 		un->un_allow_large_xfer = st_allow_large_xfer &&
3047 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
3048 	}
3049 	/*
3050 	 * if maxbsize is unknown, set the maximum block size.
3051 	 */
3052 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
3053 
3054 		/*
3055 		 * Get the Block limits of the tape drive.
3056 		 * if un->un_allow_large_xfer = 0 , then make sure
3057 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
3058 		 */
3059 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
3060 
3061 		err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3062 		if (err) {
3063 			/* Retry */
3064 			err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3065 		}
3066 		if (!err) {
3067 
3068 			/*
3069 			 * if cmd successful, use limit returned
3070 			 */
3071 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
3072 			    (un->un_rbl->max_mid << 8) +
3073 			    un->un_rbl->max_lo;
3074 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
3075 			    un->un_rbl->min_lo;
3076 			un->un_data_mod = 1 << un->un_rbl->granularity;
3077 			if ((un->un_maxbsize == 0) ||
3078 			    (un->un_allow_large_xfer == 0 &&
3079 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
3080 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3081 
3082 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
3083 				/*
3084 				 * Drive is not one that is configured, But the
3085 				 * READ BLOCK LIMITS tells us it can do large
3086 				 * xfers.
3087 				 */
3088 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
3089 					un->un_dp->options |=
3090 					    ST_NO_RECSIZE_LIMIT;
3091 				}
3092 				/*
3093 				 * If max and mimimum block limits are the
3094 				 * same this is a fixed block size device.
3095 				 */
3096 				if (un->un_maxbsize == un->un_minbsize) {
3097 					un->un_dp->options &= ~ST_VARIABLE;
3098 				}
3099 			}
3100 
3101 			if (un->un_minbsize == 0) {
3102 				un->un_minbsize = 1;
3103 			}
3104 
3105 		} else { /* error on read block limits */
3106 
3107 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3108 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
3109 			    " errno = %d un_rsvd_status = 0x%X\n",
3110 			    err, un->un_rsvd_status);
3111 
3112 			/*
3113 			 * since read block limits cmd failed,
3114 			 * do not allow large xfers.
3115 			 * use old values in st_minphys
3116 			 */
3117 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
3118 				rval = EACCES;
3119 			} else {
3120 				un->un_allow_large_xfer = 0;
3121 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3122 				    "!Disabling large transfers\n");
3123 
3124 				/*
3125 				 * we guess maxbsize and minbsize
3126 				 */
3127 				if (un->un_bsize) {
3128 					un->un_maxbsize = un->un_minbsize =
3129 					    un->un_bsize;
3130 				} else {
3131 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3132 					un->un_minbsize = 1;
3133 				}
3134 				/*
3135 				 * Data Mod must be set,
3136 				 * Even if read block limits fails.
3137 				 * Prevents Divide By Zero in st_rw().
3138 				 */
3139 				un->un_data_mod = 1;
3140 			}
3141 		}
3142 		if (un->un_rbl) {
3143 			kmem_free(un->un_rbl, RBLSIZE);
3144 			un->un_rbl = NULL;
3145 		}
3146 
3147 		if (rval) {
3148 			goto exit;
3149 		}
3150 	}
3151 
3152 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3153 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
3154 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
3155 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
3156 
3157 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
3158 
3159 	if (err != 0) {
3160 		if (err == EINTR) {
3161 			un->un_laststate = un->un_state;
3162 			un->un_state = ST_STATE_CLOSED;
3163 			rval = EINTR;
3164 			goto exit;
3165 		}
3166 		/*
3167 		 * Make sure the tape is ready
3168 		 */
3169 		un->un_pos.pmode = invalid;
3170 		if (un->un_status != KEY_UNIT_ATTENTION) {
3171 			/*
3172 			 * allow open no media.  Subsequent MTIOCSTATE
3173 			 * with media present will complete the open
3174 			 * logic.
3175 			 */
3176 			un->un_laststate = un->un_state;
3177 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
3178 				un->un_mediastate = MTIO_EJECTED;
3179 				un->un_state = ST_STATE_OFFLINE;
3180 				rval = 0;
3181 				goto exit;
3182 			} else {
3183 				un->un_state = ST_STATE_CLOSED;
3184 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3185 				    "st_tape_init EIO no media, not opened "
3186 				    "O_NONBLOCK|O_EXCL\n");
3187 				rval = EIO;
3188 				goto exit;
3189 			}
3190 		}
3191 	}
3192 
3193 	/*
3194 	 * On each open, initialize block size from drivetype struct,
3195 	 * as it could have been changed by MTSRSZ ioctl.
3196 	 * Now, ST_VARIABLE simply means drive is capable of variable
3197 	 * mode. All drives are assumed to support fixed records.
3198 	 * Hence, un_bsize tells what mode the drive is in.
3199 	 *	un_bsize	= 0	- variable record length
3200 	 *			= x	- fixed record length is x
3201 	 */
3202 	un->un_bsize = un->un_dp->bsize;
3203 
3204 	/*
3205 	 * If saved position is valid go there
3206 	 */
3207 	if (un->un_restore_pos) {
3208 		un->un_restore_pos = 0;
3209 		un->un_pos.fileno = un->un_save_fileno;
3210 		un->un_pos.blkno = un->un_save_blkno;
3211 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &un->un_pos);
3212 		if (rval != 0) {
3213 			if (rval != EACCES) {
3214 				rval = EIO;
3215 			}
3216 			un->un_laststate = un->un_state;
3217 			un->un_state = ST_STATE_CLOSED;
3218 			goto exit;
3219 		}
3220 	}
3221 
3222 	if (un->un_pos.pmode == invalid) {
3223 		rval = st_loadtape(un);
3224 		if (rval) {
3225 			if (rval != EACCES) {
3226 				rval = EIO;
3227 			}
3228 			un->un_laststate = un->un_state;
3229 			un->un_state = ST_STATE_CLOSED;
3230 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3231 			    "st_tape_init: %s can't open tape\n",
3232 			    rval == EACCES ? "EACCES" : "EIO");
3233 			goto exit;
3234 		}
3235 	}
3236 
3237 	/*
3238 	 * do a mode sense to pick up state of current write-protect,
3239 	 * Could cause reserve and fail due to conflict.
3240 	 */
3241 	if (un->un_unit_attention_flags) {
3242 		rval = st_modesense(un);
3243 		if (rval == EACCES) {
3244 			goto exit;
3245 		}
3246 	}
3247 
3248 	/*
3249 	 * If we are opening the tape for writing, check
3250 	 * to make sure that the tape can be written.
3251 	 */
3252 	if (un->un_oflags & FWRITE) {
3253 		err = 0;
3254 		if (un->un_mspl->wp) {
3255 			un->un_status = KEY_WRITE_PROTECT;
3256 			un->un_laststate = un->un_state;
3257 			un->un_state = ST_STATE_CLOSED;
3258 			rval = EACCES;
3259 			/*
3260 			 * STK sets the wp bit if volsafe tape is loaded.
3261 			 */
3262 			if ((un->un_dp->type == MT_ISSTK9840) &&
3263 			    (un->un_dp->options & ST_WORMABLE)) {
3264 				un->un_read_only = RDONLY;
3265 			} else {
3266 				goto exit;
3267 			}
3268 		} else {
3269 			un->un_read_only = RDWR;
3270 		}
3271 	} else {
3272 		un->un_read_only = RDONLY;
3273 	}
3274 
3275 	if (un->un_dp->options & ST_WORMABLE &&
3276 	    un->un_unit_attention_flags) {
3277 		un->un_read_only |= un->un_wormable(un);
3278 
3279 		if (((un->un_read_only == WORM) ||
3280 		    (un->un_read_only == RDWORM)) &&
3281 		    ((un->un_oflags & FWRITE) == FWRITE)) {
3282 			un->un_status = KEY_DATA_PROTECT;
3283 			rval = EACCES;
3284 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3285 			    "read_only = %d eof = %d oflag = %d\n",
3286 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3287 		}
3288 	}
3289 
3290 	/*
3291 	 * If we're opening the tape write-only, we need to
3292 	 * write 2 filemarks on the HP 1/2 inch drive, to
3293 	 * create a null file.
3294 	 */
3295 	if ((un->un_read_only == RDWR) ||
3296 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3297 		if (un->un_dp->options & ST_REEL) {
3298 			un->un_fmneeded = 2;
3299 		} else {
3300 			un->un_fmneeded = 1;
3301 		}
3302 	} else {
3303 		un->un_fmneeded = 0;
3304 	}
3305 
3306 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3307 	    "fmneeded = %x\n", un->un_fmneeded);
3308 
3309 	/*
3310 	 * Make sure the density can be selected correctly.
3311 	 * If WORM can only write at the append point which in most cases
3312 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3313 	 * to set and try densities if a BOP.
3314 	 */
3315 	if (st_determine_density(un,
3316 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3317 		un->un_status = KEY_ILLEGAL_REQUEST;
3318 		un->un_laststate = un->un_state;
3319 		un->un_state = ST_STATE_CLOSED;
3320 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3321 		    "st_tape_init: EIO can't determine density\n");
3322 		rval = EIO;
3323 		goto exit;
3324 	}
3325 
3326 	/*
3327 	 * Destroy the knowledge that we have 'determined'
3328 	 * density so that a later read at BOT comes along
3329 	 * does the right density determination.
3330 	 */
3331 
3332 	un->un_density_known = 0;
3333 
3334 
3335 	/*
3336 	 * Okay, the tape is loaded and either at BOT or somewhere past.
3337 	 * Mark the state such that any I/O or tape space operations
3338 	 * will get/set the right density, etc..
3339 	 */
3340 	un->un_laststate = un->un_state;
3341 	un->un_lastop = ST_OP_NIL;
3342 	un->un_mediastate = MTIO_INSERTED;
3343 	cv_broadcast(&un->un_state_cv);
3344 
3345 	/*
3346 	 *  Set test append flag if writing.
3347 	 *  First write must check that tape is positioned correctly.
3348 	 */
3349 	un->un_test_append = (un->un_oflags & FWRITE);
3350 
3351 	/*
3352 	 * if there are pending unit attention flags.
3353 	 * Check that the media has not changed.
3354 	 */
3355 	if (un->un_unit_attention_flags) {
3356 		rval = st_get_media_identification(un, st_uscsi_cmd);
3357 		if (rval != 0 && rval != EACCES) {
3358 			rval = EIO;
3359 		}
3360 		un->un_unit_attention_flags = 0;
3361 	}
3362 
3363 exit:
3364 	un->un_err_resid = 0;
3365 	un->un_last_resid = 0;
3366 	un->un_last_count = 0;
3367 
3368 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3369 	    "st_tape_init: return val = %x\n", rval);
3370 	return (rval);
3371 
3372 }
3373 
3374 
3375 
3376 /* ARGSUSED */
3377 static int
3378 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3379 {
3380 	int err = 0;
3381 	int count, last_state;
3382 	minor_t minor = getminor(dev);
3383 #ifdef	__x86
3384 	struct contig_mem *cp, *cp_temp;
3385 #endif
3386 
3387 	GET_SOFT_STATE(dev);
3388 
3389 	ST_ENTR(ST_DEVINFO, st_close);
3390 
3391 	/*
3392 	 * wait till all cmds in the pipeline have been completed
3393 	 */
3394 	mutex_enter(ST_MUTEX);
3395 
3396 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3397 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3398 
3399 	st_wait_for_io(un);
3400 
3401 	/* turn off persistent errors on close, as we want close to succeed */
3402 	st_turn_pe_off(un);
3403 
3404 	/*
3405 	 * set state to indicate that we are in process of closing
3406 	 */
3407 	last_state = un->un_laststate = un->un_state;
3408 	un->un_state = ST_STATE_CLOSING;
3409 
3410 	ST_POS(ST_DEVINFO, "st_close1:", &un->un_pos);
3411 
3412 	/*
3413 	 * BSD behavior:
3414 	 * a close always causes a silent span to the next file if we've hit
3415 	 * an EOF (but not yet read across it).
3416 	 */
3417 	if ((minor & MT_BSD) && (un->un_pos.eof == ST_EOF)) {
3418 		if (un->un_pos.pmode != invalid) {
3419 			un->un_pos.fileno++;
3420 			un->un_pos.blkno = 0;
3421 		}
3422 		un->un_pos.eof = ST_NO_EOF;
3423 	}
3424 
3425 	/*
3426 	 * SVR4 behavior for skipping to next file:
3427 	 *
3428 	 * If we have not seen a filemark, space to the next file
3429 	 *
3430 	 * If we have already seen the filemark we are physically in the next
3431 	 * file and we only increment the filenumber
3432 	 */
3433 	if (((minor & (MT_BSD | MT_NOREWIND)) == MT_NOREWIND) &&
3434 	    (flag & FREAD) &&		/* reading or at least asked to */
3435 	    (un->un_mediastate == MTIO_INSERTED) &&	/* tape loaded */
3436 	    (un->un_pos.pmode != invalid) &&		/* XXX position known */
3437 	    ((un->un_pos.blkno != 0) && 		/* inside a file */
3438 	    (un->un_lastop != ST_OP_WRITE) &&		/* Didn't just write */
3439 	    (un->un_lastop != ST_OP_WEOF))) {		/* or write filemarks */
3440 		switch (un->un_pos.eof) {
3441 		case ST_NO_EOF:
3442 			/*
3443 			 * if we were reading and did not read the complete file
3444 			 * skip to the next file, leaving the tape correctly
3445 			 * positioned to read the first record of the next file
3446 			 * Check first for REEL if we are at EOT by trying to
3447 			 * read a block
3448 			 */
3449 			if ((un->un_dp->options & ST_REEL) &&
3450 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3451 			    (un->un_pos.blkno == 0)) {
3452 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3453 					ST_DEBUG2(ST_DEVINFO, st_label,
3454 					    SCSI_DEBUG,
3455 					    "st_close : EIO can't space\n");
3456 					err = EIO;
3457 					goto error_out;
3458 				}
3459 				if (un->un_pos.eof >= ST_EOF_PENDING) {
3460 					un->un_pos.eof = ST_EOT_PENDING;
3461 					un->un_pos.fileno += 1;
3462 					un->un_pos.blkno   = 0;
3463 					break;
3464 				}
3465 			}
3466 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3467 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3468 				    "st_close: EIO can't space #2\n");
3469 				err = EIO;
3470 				goto error_out;
3471 			} else {
3472 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3473 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3474 				    un->un_pos.fileno, un->un_pos.blkno,
3475 				    un->un_pos.eof);
3476 				un->un_pos.eof = ST_NO_EOF;
3477 			}
3478 			break;
3479 
3480 		case ST_EOF_PENDING:
3481 		case ST_EOF:
3482 			un->un_pos.fileno += 1;
3483 			un->un_pos.lgclblkno += 1;
3484 			un->un_pos.blkno   = 0;
3485 			un->un_pos.eof = ST_NO_EOF;
3486 			break;
3487 
3488 		case ST_EOT:
3489 		case ST_EOT_PENDING:
3490 		case ST_EOM:
3491 			/* nothing to do */
3492 			break;
3493 		default:
3494 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
3495 			    "Undefined state 0x%x", un->un_pos.eof);
3496 
3497 		}
3498 	}
3499 
3500 
3501 	/*
3502 	 * For performance reasons (HP 88780), the driver should
3503 	 * postpone writing the second tape mark until just before a file
3504 	 * positioning ioctl is issued (e.g., rewind).	This means that
3505 	 * the user must not manually rewind the tape because the tape will
3506 	 * be missing the second tape mark which marks EOM.
3507 	 * However, this small performance improvement is not worth the risk.
3508 	 */
3509 
3510 	/*
3511 	 * We need to back up over the filemark we inadvertently popped
3512 	 * over doing a read in between the two filemarks that constitute
3513 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3514 	 * set while reading.
3515 	 *
3516 	 * If we happen to be at physical eot (ST_EOM) (writing case),
3517 	 * the writing of filemark(s) will clear the ST_EOM state, which
3518 	 * we don't want, so we save this state and restore it later.
3519 	 */
3520 
3521 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3522 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3523 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3524 
3525 	if (un->un_pos.eof == ST_EOT_PENDING) {
3526 		if (minor & MT_NOREWIND) {
3527 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3528 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3529 				    "st_close: EIO can't space #3\n");
3530 				err = EIO;
3531 				goto error_out;
3532 			} else {
3533 				un->un_pos.blkno = 0;
3534 				un->un_pos.eof = ST_EOT;
3535 			}
3536 		} else {
3537 			un->un_pos.eof = ST_NO_EOF;
3538 		}
3539 
3540 	/*
3541 	 * Do we need to write a file mark?
3542 	 *
3543 	 * only write filemarks if there are fmks to be written and
3544 	 *   - open for write (possibly read/write)
3545 	 *   - the last operation was a write
3546 	 * or:
3547 	 *   -	opened for wronly
3548 	 *   -	no data was written
3549 	 */
3550 	} else if ((un->un_pos.pmode != invalid) &&
3551 	    (un->un_fmneeded > 0) &&
3552 	    (((flag & FWRITE) &&
3553 	    ((un->un_lastop == ST_OP_WRITE)||(un->un_lastop == ST_OP_WEOF))) ||
3554 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3555 
3556 		/* save ST_EOM state */
3557 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3558 
3559 		/*
3560 		 * Note that we will write a filemark if we had opened
3561 		 * the tape write only and no data was written, thus
3562 		 * creating a null file.
3563 		 *
3564 		 * If the user already wrote one, we only have to write 1 more.
3565 		 * If they wrote two, we don't have to write any.
3566 		 */
3567 
3568 		count = un->un_fmneeded;
3569 		if (count > 0) {
3570 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, count, SYNC_CMD)) {
3571 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3572 				    "st_close : EIO can't wfm\n");
3573 				err = EIO;
3574 				goto error_out;
3575 			}
3576 			if ((un->un_dp->options & ST_REEL) &&
3577 			    (minor & MT_NOREWIND)) {
3578 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3579 					ST_DEBUG2(ST_DEVINFO, st_label,
3580 					    SCSI_DEBUG,
3581 					    "st_close : EIO space fmk(-1)\n");
3582 					err = EIO;
3583 					goto error_out;
3584 				}
3585 				un->un_pos.eof = ST_NO_EOF;
3586 				/* fix up block number */
3587 				un->un_pos.blkno = 0;
3588 			}
3589 		}
3590 
3591 		/*
3592 		 * If we aren't going to be rewinding, and we were at
3593 		 * physical eot, restore the state that indicates we
3594 		 * are at physical eot. Once you have reached physical
3595 		 * eot, and you close the tape, the only thing you can
3596 		 * do on the next open is to rewind. Access to trailer
3597 		 * records is only allowed without closing the device.
3598 		 */
3599 		if ((minor & MT_NOREWIND) == 0 && was_at_eom) {
3600 			un->un_pos.eof = ST_EOM;
3601 		}
3602 	}
3603 
3604 	/*
3605 	 * report soft errors if enabled and available, if we never accessed
3606 	 * the drive, don't get errors. This will prevent some DAT error
3607 	 * messages upon LOG SENSE.
3608 	 */
3609 	if (st_report_soft_errors_on_close &&
3610 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3611 	    (last_state != ST_STATE_OFFLINE)) {
3612 		if (st_report_soft_errors(dev, flag)) {
3613 			err = EIO;
3614 			goto error_out;
3615 		}
3616 	}
3617 
3618 
3619 	/*
3620 	 * Do we need to rewind? Can we rewind?
3621 	 */
3622 	if ((minor & MT_NOREWIND) == 0 &&
3623 	    un->un_pos.pmode != invalid && err == 0) {
3624 		/*
3625 		 * We'd like to rewind with the
3626 		 * 'immediate' bit set, but this
3627 		 * causes problems on some drives
3628 		 * where subsequent opens get a
3629 		 * 'NOT READY' error condition
3630 		 * back while the tape is rewinding,
3631 		 * which is impossible to distinguish
3632 		 * from the condition of 'no tape loaded'.
3633 		 *
3634 		 * Also, for some targets, if you disconnect
3635 		 * with the 'immediate' bit set, you don't
3636 		 * actually return right away, i.e., the
3637 		 * target ignores your request for immediate
3638 		 * return.
3639 		 *
3640 		 * Instead, we'll fire off an async rewind
3641 		 * command. We'll mark the device as closed,
3642 		 * and any subsequent open will stall on
3643 		 * the first TEST_UNIT_READY until the rewind
3644 		 * completes.
3645 		 */
3646 
3647 		/*
3648 		 * Used to be if reserve was not supported we'd send an
3649 		 * asynchronious rewind. Comments above may be slightly invalid
3650 		 * as the immediate bit was never set. Doing an immedate rewind
3651 		 * makes sense, I think fixes to not ready status might handle
3652 		 * the problems described above.
3653 		 */
3654 		if (un->un_sd->sd_inq->inq_ansi < 2) {
3655 			if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
3656 				err = EIO;
3657 			}
3658 		} else {
3659 			/* flush data for older drives per scsi spec. */
3660 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD)) {
3661 				err = EIO;
3662 			} else {
3663 				/* release the drive before rewind immediate */
3664 				if ((un->un_rsvd_status &
3665 				    (ST_RESERVE | ST_PRESERVE_RESERVE)) ==
3666 				    ST_RESERVE) {
3667 					if (st_reserve_release(un, ST_RELEASE,
3668 					    st_uscsi_cmd)) {
3669 						err = EIO;
3670 					}
3671 				}
3672 
3673 				/* send rewind with immediate bit set */
3674 				if (st_cmd(un, SCMD_REWIND, 1, ASYNC_CMD)) {
3675 					err = EIO;
3676 				}
3677 			}
3678 		}
3679 		/*
3680 		 * Setting positions invalid in case the rewind doesn't
3681 		 * happen. Drives don't like to rewind if resets happen
3682 		 * they will tend to move back to where the rewind was
3683 		 * issued if a reset or something happens so that if a
3684 		 * write happens the data doesn't get clobbered.
3685 		 *
3686 		 * Not a big deal if the position is invalid when the
3687 		 * open occures it will do a read position.
3688 		 */
3689 		un->un_pos.pmode = invalid;
3690 		un->un_running.pmode = invalid;
3691 
3692 		if (err == EIO) {
3693 			goto error_out;
3694 		}
3695 	}
3696 
3697 	/*
3698 	 * eject tape if necessary
3699 	 */
3700 	if (un->un_eject_tape_on_failure) {
3701 		un->un_eject_tape_on_failure = 0;
3702 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3703 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3704 			    "st_close : can't unload tape\n");
3705 			err = EIO;
3706 			goto error_out;
3707 		} else {
3708 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3709 			    "st_close : tape unloaded \n");
3710 			un->un_pos.eof = ST_NO_EOF;
3711 			un->un_mediastate = MTIO_EJECTED;
3712 		}
3713 	}
3714 	/*
3715 	 * Release the tape unit, if default reserve/release
3716 	 * behaviour.
3717 	 */
3718 	if ((un->un_rsvd_status &
3719 	    (ST_RESERVE | ST_PRESERVE_RESERVE |
3720 	    ST_APPLICATION_RESERVATIONS)) == ST_RESERVE) {
3721 		(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
3722 	}
3723 error_out:
3724 	/*
3725 	 * clear up state
3726 	 */
3727 	un->un_laststate = un->un_state;
3728 	un->un_state = ST_STATE_CLOSED;
3729 	un->un_lastop = ST_OP_NIL;
3730 	un->un_throttle = 1;	/* assume one request at time, for now */
3731 	un->un_retry_ct = 0;
3732 	un->un_errno = 0;
3733 	un->un_swr_token = (opaque_t)NULL;
3734 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3735 
3736 	/* Restore the options to the init time settings */
3737 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3738 		un->un_dp->options |= ST_READ_IGNORE_ILI;
3739 	} else {
3740 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3741 	}
3742 
3743 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3744 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3745 	} else {
3746 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3747 	}
3748 
3749 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3750 		un->un_dp->options |= ST_SHORT_FILEMARKS;
3751 	} else {
3752 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3753 	}
3754 
3755 	ASSERT(mutex_owned(ST_MUTEX));
3756 
3757 	/*
3758 	 * Signal anyone awaiting a close operation to complete.
3759 	 */
3760 	cv_signal(&un->un_clscv);
3761 
3762 	/*
3763 	 * any kind of error on closing causes all state to be tossed
3764 	 */
3765 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3766 		/*
3767 		 * note that st_intr has already set
3768 		 * un_pos.pmode to invalid.
3769 		 */
3770 		un->un_density_known = 0;
3771 	}
3772 
3773 #ifdef	__x86
3774 	/*
3775 	 * free any contiguous mem alloc'ed for big block I/O
3776 	 */
3777 	cp = un->un_contig_mem;
3778 	while (cp) {
3779 		if (cp->cm_addr) {
3780 			ddi_dma_mem_free(&cp->cm_acc_hdl);
3781 		}
3782 		cp_temp = cp;
3783 		cp = cp->cm_next;
3784 		kmem_free(cp_temp,
3785 		    sizeof (struct contig_mem) + biosize());
3786 	}
3787 	un->un_contig_mem_total_num = 0;
3788 	un->un_contig_mem_available_num = 0;
3789 	un->un_contig_mem = NULL;
3790 	un->un_max_contig_mem_len = 0;
3791 #endif
3792 
3793 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3794 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3795 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3796 
3797 	mutex_exit(ST_MUTEX);
3798 	return (err);
3799 }
3800 
3801 /*
3802  * These routines perform raw i/o operations.
3803  */
3804 
3805 /* ARGSUSED2 */
3806 static int
3807 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3808 {
3809 #ifdef STDEBUG
3810 	GET_SOFT_STATE(dev);
3811 	ST_ENTR(ST_DEVINFO, st_aread);
3812 #endif
3813 	return (st_arw(dev, aio, B_READ));
3814 }
3815 
3816 
3817 /* ARGSUSED2 */
3818 static int
3819 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3820 {
3821 #ifdef STDEBUG
3822 	GET_SOFT_STATE(dev);
3823 	ST_ENTR(ST_DEVINFO, st_awrite);
3824 #endif
3825 	return (st_arw(dev, aio, B_WRITE));
3826 }
3827 
3828 
3829 
3830 /* ARGSUSED */
3831 static int
3832 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3833 {
3834 #ifdef STDEBUG
3835 	GET_SOFT_STATE(dev);
3836 	ST_ENTR(ST_DEVINFO, st_read);
3837 #endif
3838 	return (st_rw(dev, uiop, B_READ));
3839 }
3840 
3841 /* ARGSUSED */
3842 static int
3843 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3844 {
3845 #ifdef STDEBUG
3846 	GET_SOFT_STATE(dev);
3847 	ST_ENTR(ST_DEVINFO, st_write);
3848 #endif
3849 	return (st_rw(dev, uiop, B_WRITE));
3850 }
3851 
3852 /*
3853  * Due to historical reasons, old limits are: For variable-length devices:
3854  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3855  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3856  * (let it through unmodified. For fixed-length record devices:
3857  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3858  *
3859  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3860  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3861  * command to the drive).
3862  *
3863  */
3864 static void
3865 st_minphys(struct buf *bp)
3866 {
3867 	struct scsi_tape *un;
3868 
3869 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3870 
3871 	ST_FUNC(ST_DEVINFO, st_minphys);
3872 
3873 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3874 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3875 	    bp->b_bcount);
3876 
3877 	if (un->un_allow_large_xfer) {
3878 
3879 		/*
3880 		 * check un_maxbsize for variable length devices only
3881 		 */
3882 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3883 			bp->b_bcount = un->un_maxbsize;
3884 		}
3885 		/*
3886 		 * can't go more that HBA maxdma limit in either fixed-length
3887 		 * or variable-length tape drives.
3888 		 */
3889 		if (bp->b_bcount > un->un_maxdma) {
3890 			bp->b_bcount = un->un_maxdma;
3891 		}
3892 	} else {
3893 
3894 		/*
3895 		 *  use old fixed limits
3896 		 */
3897 		if (un->un_bsize == 0) {
3898 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3899 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3900 			}
3901 		} else {
3902 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3903 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3904 			}
3905 		}
3906 	}
3907 
3908 	/*
3909 	 * For regular raw I/O and Fixed Block length devices, make sure
3910 	 * the adjusted block count is a whole multiple of the device
3911 	 * block size.
3912 	 */
3913 	if (bp != un->un_sbufp && un->un_bsize) {
3914 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3915 	}
3916 }
3917 
3918 static int
3919 st_rw(dev_t dev, struct uio *uio, int flag)
3920 {
3921 	int rval = 0;
3922 	long len;
3923 
3924 	GET_SOFT_STATE(dev);
3925 
3926 	ST_FUNC(ST_DEVINFO, st_rw);
3927 
3928 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3929 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3930 	    (flag == B_READ ? rd_str: wr_str));
3931 
3932 	/* get local copy of transfer length */
3933 	len = uio->uio_iov->iov_len;
3934 
3935 	mutex_enter(ST_MUTEX);
3936 
3937 	/*
3938 	 * Clear error entry stack
3939 	 */
3940 	st_empty_error_stack(un);
3941 
3942 	/*
3943 	 * If in fixed block size mode and requested read or write
3944 	 * is not an even multiple of that block size.
3945 	 */
3946 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3947 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3948 		    "%s: not modulo %d block size\n",
3949 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3950 		rval = EINVAL;
3951 	}
3952 
3953 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3954 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3955 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3956 		    "%s: not modulo %d device granularity\n",
3957 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3958 		rval = EINVAL;
3959 	}
3960 
3961 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
3962 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
3963 		rval = EFAULT;
3964 	}
3965 
3966 	if (rval != 0) {
3967 		un->un_errno = rval;
3968 		mutex_exit(ST_MUTEX);
3969 		return (rval);
3970 	}
3971 
3972 	/*
3973 	 * Reset this so it can be set if Berkeley and read over a filemark.
3974 	 */
3975 	un->un_silent_skip = 0;
3976 	mutex_exit(ST_MUTEX);
3977 
3978 	len = uio->uio_resid;
3979 
3980 	rval = physio(st_queued_strategy, (struct buf *)NULL,
3981 	    dev, flag, st_minphys, uio);
3982 	/*
3983 	 * if we have hit logical EOT during this xfer and there is not a
3984 	 * full residue, then set eof back  to ST_EOM to make sure that
3985 	 * the user will see at least one zero write
3986 	 * after this short write
3987 	 */
3988 	mutex_enter(ST_MUTEX);
3989 	if (un->un_pos.eof > ST_NO_EOF) {
3990 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3991 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3992 	}
3993 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3994 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3995 			un->un_pos.eof = ST_EOM;
3996 		} else if (uio->uio_resid == len) {
3997 			un->un_pos.eof = ST_NO_EOF;
3998 		}
3999 	}
4000 
4001 	if (un->un_silent_skip && uio->uio_resid != len) {
4002 		un->un_pos.eof = ST_EOF;
4003 		un->un_pos.blkno = un->un_save_blkno;
4004 		un->un_pos.fileno--;
4005 	}
4006 
4007 	un->un_errno = rval;
4008 
4009 	mutex_exit(ST_MUTEX);
4010 
4011 	return (rval);
4012 }
4013 
4014 static int
4015 st_arw(dev_t dev, struct aio_req *aio, int flag)
4016 {
4017 	struct uio *uio = aio->aio_uio;
4018 	int rval = 0;
4019 	long len;
4020 
4021 	GET_SOFT_STATE(dev);
4022 
4023 	ST_FUNC(ST_DEVINFO, st_arw);
4024 
4025 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4026 	    "st_arw(dev = 0x%lx, flag = %s)\n", dev,
4027 	    (flag == B_READ ? rd_str: wr_str));
4028 
4029 	/* get local copy of transfer length */
4030 	len = uio->uio_iov->iov_len;
4031 
4032 	mutex_enter(ST_MUTEX);
4033 
4034 	/*
4035 	 * If in fixed block size mode and requested read or write
4036 	 * is not an even multiple of that block size.
4037 	 */
4038 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
4039 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4040 		    "%s: not modulo %d block size\n",
4041 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
4042 		rval = EINVAL;
4043 	}
4044 
4045 	/* If device has set granularity in the READ_BLKLIM we honor it. */
4046 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
4047 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4048 		    "%s: not modulo %d device granularity\n",
4049 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
4050 		rval = EINVAL;
4051 	}
4052 
4053 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
4054 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
4055 		rval = EFAULT;
4056 	}
4057 
4058 	if (rval != 0) {
4059 		un->un_errno = rval;
4060 		mutex_exit(ST_MUTEX);
4061 		return (rval);
4062 	}
4063 
4064 	mutex_exit(ST_MUTEX);
4065 
4066 	len = uio->uio_resid;
4067 
4068 	rval =
4069 	    aphysio(st_queued_strategy, anocancel, dev, flag, st_minphys, aio);
4070 
4071 	/*
4072 	 * if we have hit logical EOT during this xfer and there is not a
4073 	 * full residue, then set eof back  to ST_EOM to make sure that
4074 	 * the user will see at least one zero write
4075 	 * after this short write
4076 	 *
4077 	 * we keep this here just in case the application is not using
4078 	 * persistent errors
4079 	 */
4080 	mutex_enter(ST_MUTEX);
4081 	if (un->un_pos.eof > ST_NO_EOF) {
4082 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4083 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
4084 	}
4085 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
4086 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
4087 			un->un_pos.eof = ST_EOM;
4088 		} else if (uio->uio_resid == len &&
4089 		    !(un->un_persistence && un->un_persist_errors)) {
4090 			un->un_pos.eof = ST_NO_EOF;
4091 		}
4092 	}
4093 	un->un_errno = rval;
4094 	mutex_exit(ST_MUTEX);
4095 
4096 	return (rval);
4097 }
4098 
4099 
4100 
4101 static int
4102 st_queued_strategy(buf_t *bp)
4103 {
4104 	struct scsi_tape *un;
4105 	char reading = bp->b_flags & B_READ;
4106 	int wasopening = 0;
4107 
4108 	/*
4109 	 * validate arguments
4110 	 */
4111 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4112 	if (un == NULL) {
4113 		bp->b_resid = bp->b_bcount;
4114 		bioerror(bp, ENXIO);
4115 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4116 		    "st_queued_strategy: ENXIO error exit\n");
4117 		biodone(bp);
4118 		return (0);
4119 	}
4120 
4121 	ST_ENTR(ST_DEVINFO, st_queued_strategy);
4122 
4123 	mutex_enter(ST_MUTEX);
4124 
4125 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4126 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4127 	}
4128 
4129 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4130 	    "st_queued_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4131 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4132 
4133 	/*
4134 	 * If persistent errors have been flagged, just nix this one. We wait
4135 	 * for any outstanding I/O's below, so we will be in order.
4136 	 */
4137 	if (un->un_persistence && un->un_persist_errors) {
4138 		goto exit;
4139 	}
4140 
4141 	/*
4142 	 * If last command was non queued, wait till it finishes.
4143 	 */
4144 	while (un->un_sbuf_busy) {
4145 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
4146 		/* woke up because of an error */
4147 		if (un->un_persistence && un->un_persist_errors) {
4148 			goto exit;
4149 		}
4150 	}
4151 
4152 	/*
4153 	 * s_buf and recovery commands shouldn't come here.
4154 	 */
4155 	ASSERT(bp != un->un_recov_buf);
4156 	ASSERT(bp != un->un_sbufp);
4157 
4158 	/*
4159 	 * If we haven't done/checked reservation on the tape unit
4160 	 * do it now.
4161 	 */
4162 	if ((un->un_rsvd_status &
4163 	    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
4164 		if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
4165 			if (st_reserve_release(un, ST_RESERVE, st_uscsi_cmd)) {
4166 				st_bioerror(bp, un->un_errno);
4167 				goto exit;
4168 			}
4169 		} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4170 			/*
4171 			 * Enter here to restore position for possible
4172 			 * resets when the device was closed and opened
4173 			 * in O_NDELAY mode subsequently
4174 			 */
4175 			un->un_state = ST_STATE_INITIALIZING;
4176 			(void) st_cmd(un, SCMD_TEST_UNIT_READY,
4177 			    0, SYNC_CMD);
4178 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4179 		}
4180 		un->un_rsvd_status |= ST_INIT_RESERVE;
4181 	}
4182 
4183 	/*
4184 	 * If we are offline, we have to initialize everything first.
4185 	 * This is to handle either when opened with O_NDELAY, or
4186 	 * we just got a new tape in the drive, after an offline.
4187 	 * We don't observe O_NDELAY past the open,
4188 	 * as it will not make sense for tapes.
4189 	 */
4190 	if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
4191 		/*
4192 		 * reset state to avoid recursion
4193 		 */
4194 		un->un_laststate = un->un_state;
4195 		un->un_state = ST_STATE_INITIALIZING;
4196 		if (st_tape_init(un)) {
4197 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4198 			    "stioctl : OFFLINE init failure ");
4199 			un->un_state = ST_STATE_OFFLINE;
4200 			un->un_pos.pmode = invalid;
4201 			goto b_done_err;
4202 		}
4203 		/* un_restore_pos make invalid */
4204 		un->un_state = ST_STATE_OPEN_PENDING_IO;
4205 		un->un_restore_pos = 0;
4206 	}
4207 	/*
4208 	 * Check for legal operations
4209 	 */
4210 	if (un->un_pos.pmode == invalid) {
4211 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4212 		    "strategy with un->un_pos.pmode invalid\n");
4213 		goto b_done_err;
4214 	}
4215 
4216 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4217 	    "st_queued_strategy(): regular io\n");
4218 
4219 	/*
4220 	 * Process this first. If we were reading, and we're pending
4221 	 * logical eot, that means we've bumped one file mark too far.
4222 	 */
4223 
4224 	/*
4225 	 * Recursion warning: st_cmd will route back through here.
4226 	 * Not anymore st_cmd will go through st_strategy()!
4227 	 */
4228 	if (un->un_pos.eof == ST_EOT_PENDING) {
4229 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4230 			un->un_pos.pmode = invalid;
4231 			un->un_density_known = 0;
4232 			goto b_done_err;
4233 		}
4234 		un->un_pos.blkno = 0; /* fix up block number.. */
4235 		un->un_pos.eof = ST_EOT;
4236 	}
4237 
4238 	/*
4239 	 * If we are in the process of opening, we may have to
4240 	 * determine/set the correct density. We also may have
4241 	 * to do a test_append (if QIC) to see whether we are
4242 	 * in a position to append to the end of the tape.
4243 	 *
4244 	 * If we're already at logical eot, we transition
4245 	 * to ST_NO_EOF. If we're at physical eot, we punt
4246 	 * to the switch statement below to handle.
4247 	 */
4248 	if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
4249 	    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
4250 
4251 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4252 			if (st_determine_density(un, (int)reading)) {
4253 				goto b_done_err;
4254 			}
4255 		}
4256 
4257 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4258 		    "pending_io@fileno %d rw %d qic %d eof %d\n",
4259 		    un->un_pos.fileno, (int)reading,
4260 		    (un->un_dp->options & ST_QIC) ? 1 : 0,
4261 		    un->un_pos.eof);
4262 
4263 		if (!reading && un->un_pos.eof != ST_EOM) {
4264 			if (un->un_pos.eof == ST_EOT) {
4265 				un->un_pos.eof = ST_NO_EOF;
4266 			} else if (un->un_pos.pmode != invalid &&
4267 			    (un->un_dp->options & ST_QIC)) {
4268 				/*
4269 				 * st_test_append() will do it all
4270 				 */
4271 				st_test_append(bp);
4272 				mutex_exit(ST_MUTEX);
4273 				return (0);
4274 			}
4275 		}
4276 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4277 			wasopening = 1;
4278 		}
4279 		un->un_laststate = un->un_state;
4280 		un->un_state = ST_STATE_OPEN;
4281 	}
4282 
4283 
4284 	/*
4285 	 * Process rest of END OF FILE and END OF TAPE conditions
4286 	 */
4287 
4288 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4289 	    "eof=%x, wasopening=%x\n",
4290 	    un->un_pos.eof, wasopening);
4291 
4292 	switch (un->un_pos.eof) {
4293 	case ST_EOM:
4294 		/*
4295 		 * This allows writes to proceed past physical
4296 		 * eot. We'll *really* be in trouble if the
4297 		 * user continues blindly writing data too
4298 		 * much past this point (unwind the tape).
4299 		 * Physical eot really means 'early warning
4300 		 * eot' in this context.
4301 		 *
4302 		 * Every other write from now on will succeed
4303 		 * (if sufficient  tape left).
4304 		 * This write will return with resid == count
4305 		 * but the next one should be successful
4306 		 *
4307 		 * Note that we only transition to logical EOT
4308 		 * if the last state wasn't the OPENING state.
4309 		 * We explicitly prohibit running up to physical
4310 		 * eot, closing the device, and then re-opening
4311 		 * to proceed. Trailer records may only be gotten
4312 		 * at by keeping the tape open after hitting eot.
4313 		 *
4314 		 * Also note that ST_EOM cannot be set by reading-
4315 		 * this can only be set during writing. Reading
4316 		 * up to the end of the tape gets a blank check
4317 		 * or a double-filemark indication (ST_EOT_PENDING),
4318 		 * and we prohibit reading after that point.
4319 		 *
4320 		 */
4321 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
4322 		if (wasopening == 0) {
4323 			/*
4324 			 * this allows st_rw() to reset it back to
4325 			 * will see a zero write
4326 			 */
4327 			un->un_pos.eof = ST_WRITE_AFTER_EOM;
4328 		}
4329 		un->un_status = SUN_KEY_EOT;
4330 		goto b_done;
4331 
4332 	case ST_WRITE_AFTER_EOM:
4333 	case ST_EOT:
4334 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
4335 		un->un_status = SUN_KEY_EOT;
4336 		if (SVR4_BEHAVIOR && reading) {
4337 			goto b_done_err;
4338 		}
4339 
4340 		if (reading) {
4341 			goto b_done;
4342 		}
4343 		un->un_pos.eof = ST_NO_EOF;
4344 		break;
4345 
4346 	case ST_EOF_PENDING:
4347 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4348 		    "EOF PENDING\n");
4349 		un->un_status = SUN_KEY_EOF;
4350 		if (SVR4_BEHAVIOR) {
4351 			un->un_pos.eof = ST_EOF;
4352 			goto b_done;
4353 		}
4354 		/* FALLTHROUGH */
4355 	case ST_EOF:
4356 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
4357 		un->un_status = SUN_KEY_EOF;
4358 		if (SVR4_BEHAVIOR) {
4359 			goto b_done_err;
4360 		}
4361 
4362 		if (BSD_BEHAVIOR) {
4363 			un->un_pos.eof = ST_NO_EOF;
4364 			un->un_pos.fileno += 1;
4365 			un->un_pos.blkno   = 0;
4366 		}
4367 
4368 		if (reading) {
4369 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4370 			    "now file %d (read)\n",
4371 			    un->un_pos.fileno);
4372 			goto b_done;
4373 		}
4374 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4375 		    "now file %d (write)\n", un->un_pos.fileno);
4376 		break;
4377 	default:
4378 		un->un_status = 0;
4379 		break;
4380 	}
4381 
4382 	bp->b_flags &= ~(B_DONE);
4383 	st_bioerror(bp, 0);
4384 	bp->av_forw = NULL;
4385 	bp->b_resid = 0;
4386 	SET_BP_PKT(bp, 0);
4387 
4388 
4389 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4390 	    "st_queued_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4391 	    " pkt=0x%p\n",
4392 	    (void *)bp->b_forw, bp->b_bcount,
4393 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4394 
4395 #ifdef	__x86
4396 	/*
4397 	 * We will replace bp with a new bp that can do big blk xfer
4398 	 * if the requested xfer size is bigger than un->un_maxdma_arch
4399 	 *
4400 	 * Also, we need to make sure that we're handling real I/O
4401 	 * by checking group 0/1 SCSI I/O commands, if needed
4402 	 */
4403 	if (bp->b_bcount > un->un_maxdma_arch &&
4404 	    ((uchar_t)(uintptr_t)bp->b_forw == SCMD_READ ||
4405 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G4 ||
4406 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE ||
4407 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G4)) {
4408 		mutex_exit(ST_MUTEX);
4409 		bp = st_get_bigblk_bp(bp);
4410 		mutex_enter(ST_MUTEX);
4411 	}
4412 #endif
4413 
4414 	/* put on wait queue */
4415 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4416 	    "st_queued_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4417 	    (void *)un->un_quef, (void *)bp);
4418 
4419 	st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quel, bp);
4420 
4421 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4422 
4423 	st_start(un);
4424 
4425 	mutex_exit(ST_MUTEX);
4426 	return (0);
4427 
4428 b_done_err:
4429 	st_bioerror(bp, EIO);
4430 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4431 	    "st_queued_strategy : EIO b_done_err\n");
4432 
4433 b_done:
4434 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4435 	    "st_queued_strategy: b_done\n");
4436 
4437 exit:
4438 	/*
4439 	 * make sure no commands are outstanding or waiting before closing,
4440 	 * so we can guarantee order
4441 	 */
4442 	st_wait_for_io(un);
4443 	un->un_err_resid = bp->b_resid = bp->b_bcount;
4444 
4445 	/* override errno here, if persistent errors were flagged */
4446 	if (un->un_persistence && un->un_persist_errors)
4447 		bioerror(bp, un->un_errno);
4448 
4449 	mutex_exit(ST_MUTEX);
4450 
4451 	biodone(bp);
4452 	ASSERT(mutex_owned(ST_MUTEX) == 0);
4453 	return (0);
4454 }
4455 
4456 
4457 static int
4458 st_strategy(struct buf *bp)
4459 {
4460 	struct scsi_tape *un;
4461 
4462 	/*
4463 	 * validate arguments
4464 	 */
4465 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4466 	if (un == NULL) {
4467 		bp->b_resid = bp->b_bcount;
4468 		bioerror(bp, ENXIO);
4469 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4470 		    "st_strategy: ENXIO error exit\n");
4471 
4472 		biodone(bp);
4473 		return (0);
4474 
4475 	}
4476 
4477 	ST_ENTR(ST_DEVINFO, st_strategy);
4478 
4479 	mutex_enter(ST_MUTEX);
4480 
4481 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4482 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4483 	}
4484 
4485 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4486 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4487 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4488 
4489 	ASSERT((bp == un->un_recov_buf) || (bp == un->un_sbufp));
4490 
4491 	bp->b_flags &= ~(B_DONE);
4492 	st_bioerror(bp, 0);
4493 	bp->av_forw = NULL;
4494 	bp->b_resid = 0;
4495 	SET_BP_PKT(bp, 0);
4496 
4497 
4498 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4499 	    "st_strategy: cmd=0x%x  count=%ld  resid=%ld flags=0x%x"
4500 	    " pkt=0x%p\n",
4501 	    (unsigned char)(uintptr_t)bp->b_forw, bp->b_bcount,
4502 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4503 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4504 
4505 	st_start(un);
4506 
4507 	mutex_exit(ST_MUTEX);
4508 	return (0);
4509 }
4510 
4511 /*
4512  * this routine spaces forward over filemarks
4513  */
4514 static int
4515 st_space_fmks(struct scsi_tape *un, int64_t count)
4516 {
4517 	int rval = 0;
4518 
4519 	ST_FUNC(ST_DEVINFO, st_space_fmks);
4520 
4521 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4522 	    "st_space_fmks(dev = 0x%lx, count = %"PRIx64")\n",
4523 	    un->un_dev, count);
4524 
4525 	ASSERT(mutex_owned(ST_MUTEX));
4526 
4527 	/*
4528 	 * the risk with doing only one space operation is that we
4529 	 * may accidentily jump in old data
4530 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4531 	 * because the 8200 does not append a marker; in order not to
4532 	 * sacrifice the fast file skip, we do a slow skip if the low
4533 	 * density device has been opened
4534 	 */
4535 
4536 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4537 	    !((un->un_dp->type == ST_TYPE_EXB8500 &&
4538 	    MT_DENSITY(un->un_dev) == 0))) {
4539 		if (st_cmd(un, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4540 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4541 			    "space_fmks : EIO can't do space cmd #1\n");
4542 			rval = EIO;
4543 		}
4544 	} else {
4545 		while (count > 0) {
4546 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4547 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4548 				    "space_fmks : EIO can't do space cmd #2\n");
4549 				rval = EIO;
4550 				break;
4551 			}
4552 			count -= 1;
4553 			/*
4554 			 * read a block to see if we have reached
4555 			 * end of medium (double filemark for reel or
4556 			 * medium error for others)
4557 			 */
4558 			if (count > 0) {
4559 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
4560 					ST_DEBUG2(ST_DEVINFO, st_label,
4561 					    SCSI_DEBUG,
4562 					    "space_fmks : EIO can't do "
4563 					    "space cmd #3\n");
4564 					rval = EIO;
4565 					break;
4566 				}
4567 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4568 				    (un->un_dp->options & ST_REEL)) {
4569 					un->un_status = SUN_KEY_EOT;
4570 					ST_DEBUG2(ST_DEVINFO, st_label,
4571 					    SCSI_DEBUG,
4572 					    "space_fmks : EIO ST_REEL\n");
4573 					rval = EIO;
4574 					break;
4575 				} else if (IN_EOF(un->un_pos)) {
4576 					un->un_pos.eof = ST_NO_EOF;
4577 					un->un_pos.fileno++;
4578 					un->un_pos.blkno = 0;
4579 					count--;
4580 				} else if (un->un_pos.eof > ST_EOF) {
4581 					ST_DEBUG2(ST_DEVINFO, st_label,
4582 					    SCSI_DEBUG,
4583 					    "space_fmks, EIO > ST_EOF\n");
4584 					rval = EIO;
4585 					break;
4586 				}
4587 
4588 			}
4589 		}
4590 		un->un_err_resid = count;
4591 		COPY_POS(&un->un_pos, &un->un_err_pos);
4592 	}
4593 	ASSERT(mutex_owned(ST_MUTEX));
4594 	return (rval);
4595 }
4596 
4597 /*
4598  * this routine spaces to EOD
4599  *
4600  * it keeps track of the current filenumber and returns the filenumber after
4601  * the last successful space operation, we keep the number high because as
4602  * tapes are getting larger, the possibility of more and more files exist,
4603  * 0x100000 (1 Meg of files) probably will never have to be changed any time
4604  * soon
4605  */
4606 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4607 
4608 static int
4609 st_find_eod(struct scsi_tape *un)
4610 {
4611 	tapepos_t savepos;
4612 	int64_t sp_type;
4613 	int result;
4614 
4615 	if (un == NULL) {
4616 		return (-1);
4617 	}
4618 
4619 	ST_FUNC(ST_DEVINFO, st_find_eod);
4620 
4621 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4622 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", un->un_dev,
4623 	    un->un_pos.fileno);
4624 
4625 	ASSERT(mutex_owned(ST_MUTEX));
4626 
4627 	COPY_POS(&savepos, &un->un_pos);
4628 
4629 	/*
4630 	 * see if the drive is smart enough to do the skips in
4631 	 * one operation; 1/2" use two filemarks
4632 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4633 	 * because the 8200 does not append a marker; in order not to
4634 	 * sacrifice the fast file skip, we do a slow skip if the low
4635 	 * density device has been opened
4636 	 */
4637 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4638 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4639 		    (MT_DENSITY(un->un_dev) == 0)) {
4640 			sp_type = Fmk(1);
4641 		} else if (un->un_pos.pmode == logical) {
4642 			sp_type = SPACE(SP_EOD, 0);
4643 		} else {
4644 			sp_type = Fmk(MAX_SKIP);
4645 		}
4646 	} else {
4647 		sp_type = Fmk(1);
4648 	}
4649 
4650 	for (;;) {
4651 		result = st_cmd(un, SCMD_SPACE, sp_type, SYNC_CMD);
4652 
4653 		if (result == 0) {
4654 			COPY_POS(&savepos, &un->un_pos);
4655 		}
4656 
4657 		if (sp_type == SPACE(SP_EOD, 0)) {
4658 			if (result != 0) {
4659 				sp_type = Fmk(MAX_SKIP);
4660 				continue;
4661 			}
4662 
4663 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4664 			    "st_find_eod: 0x%"PRIx64"\n",
4665 			    savepos.lgclblkno);
4666 			/*
4667 			 * What we return will become the current file position.
4668 			 * After completing the space command with the position
4669 			 * mode that is not invalid a read position command will
4670 			 * be automaticly issued. If the drive support the long
4671 			 * read position format a valid file position can be
4672 			 * returned.
4673 			 */
4674 			return (un->un_pos.fileno);
4675 		}
4676 
4677 		if (result != 0) {
4678 			break;
4679 		}
4680 
4681 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4682 		    "count=%"PRIx64", eof=%x, status=%x\n",
4683 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4684 
4685 		/*
4686 		 * If we're not EOM smart,  space a record
4687 		 * to see whether we're now in the slot between
4688 		 * the two sequential filemarks that logical
4689 		 * EOM consists of (REEL) or hit nowhere land
4690 		 * (8mm).
4691 		 */
4692 		if (sp_type == Fmk(1)) {
4693 			/*
4694 			 * no fast skipping, check a record
4695 			 */
4696 			if (st_cmd(un, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4697 				break;
4698 			}
4699 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4700 			    (un->un_dp->options & ST_REEL)) {
4701 				un->un_status = KEY_BLANK_CHECK;
4702 				un->un_pos.fileno++;
4703 				un->un_pos.blkno = 0;
4704 				break;
4705 			}
4706 			if (IN_EOF(un->un_pos)) {
4707 				un->un_pos.eof = ST_NO_EOF;
4708 				un->un_pos.fileno++;
4709 				un->un_pos.blkno = 0;
4710 			}
4711 			if (un->un_pos.eof > ST_EOF) {
4712 				break;
4713 			}
4714 		} else {
4715 			if (un->un_pos.eof > ST_EOF) {
4716 				break;
4717 			}
4718 		}
4719 	}
4720 
4721 	if (un->un_dp->options & ST_KNOWS_EOD) {
4722 		COPY_POS(&savepos, &un->un_pos);
4723 	}
4724 
4725 	ASSERT(mutex_owned(ST_MUTEX));
4726 
4727 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4728 	    "st_find_eod: %x\n", savepos.fileno);
4729 	return (savepos.fileno);
4730 }
4731 
4732 
4733 /*
4734  * this routine is frequently used in ioctls below;
4735  * it determines whether we know the density and if not will
4736  * determine it
4737  * if we have written the tape before, one or more filemarks are written
4738  *
4739  * depending on the stepflag, the head is repositioned to where it was before
4740  * the filemarks were written in order not to confuse step counts
4741  */
4742 #define	STEPBACK    0
4743 #define	NO_STEPBACK 1
4744 
4745 static int
4746 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4747 {
4748 
4749 	GET_SOFT_STATE(dev);
4750 
4751 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4752 
4753 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4754 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4755 	    "\n", dev, wfm, mode, stepflag);
4756 
4757 	ASSERT(mutex_owned(ST_MUTEX));
4758 
4759 	/*
4760 	 * If we don't yet know the density of the tape we have inserted,
4761 	 * we have to either unconditionally set it (if we're 'writing'),
4762 	 * or we have to determine it. As side effects, check for any
4763 	 * write-protect errors, and for the need to put out any file-marks
4764 	 * before positioning a tape.
4765 	 *
4766 	 * If we are going to be spacing forward, and we haven't determined
4767 	 * the tape density yet, we have to do so now...
4768 	 */
4769 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4770 		if (st_determine_density(un, mode)) {
4771 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4772 			    "check_density_or_wfm : EIO can't determine "
4773 			    "density\n");
4774 			un->un_errno = EIO;
4775 			return (EIO);
4776 		}
4777 		/*
4778 		 * Presumably we are at BOT. If we attempt to write, it will
4779 		 * either work okay, or bomb. We don't do a st_test_append
4780 		 * unless we're past BOT.
4781 		 */
4782 		un->un_laststate = un->un_state;
4783 		un->un_state = ST_STATE_OPEN;
4784 
4785 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4786 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4787 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4788 
4789 		tapepos_t spos;
4790 
4791 		COPY_POS(&spos, &un->un_pos);
4792 
4793 		/*
4794 		 * We need to write one or two filemarks.
4795 		 * In the case of the HP, we need to
4796 		 * position the head between the two
4797 		 * marks.
4798 		 */
4799 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4800 			wfm = un->un_fmneeded;
4801 			un->un_fmneeded = 0;
4802 		}
4803 
4804 		if (st_write_fm(dev, wfm)) {
4805 			un->un_pos.pmode = invalid;
4806 			un->un_density_known = 0;
4807 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4808 			    "check_density_or_wfm : EIO can't write fm\n");
4809 			un->un_errno = EIO;
4810 			return (EIO);
4811 		}
4812 
4813 		if (stepflag == STEPBACK) {
4814 			if (st_cmd(un, SCMD_SPACE, Fmk(-wfm), SYNC_CMD)) {
4815 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4816 				    "check_density_or_wfm : EIO can't space "
4817 				    "(-wfm)\n");
4818 				un->un_errno = EIO;
4819 				return (EIO);
4820 			}
4821 			COPY_POS(&un->un_pos, &spos);
4822 		}
4823 	}
4824 
4825 	/*
4826 	 * Whatever we do at this point clears the state of the eof flag.
4827 	 */
4828 
4829 	un->un_pos.eof = ST_NO_EOF;
4830 
4831 	/*
4832 	 * If writing, let's check that we're positioned correctly
4833 	 * at the end of tape before issuing the next write.
4834 	 */
4835 	if (un->un_read_only == RDWR) {
4836 		un->un_test_append = 1;
4837 	}
4838 
4839 	ASSERT(mutex_owned(ST_MUTEX));
4840 	return (0);
4841 }
4842 
4843 
4844 /*
4845  * Wait for all outstaning I/O's to complete
4846  *
4847  * we wait on both ncmds and the wait queue for times when we are flushing
4848  * after persistent errors are flagged, which is when ncmds can be 0, and the
4849  * queue can still have I/O's.  This way we preserve order of biodone's.
4850  */
4851 static void
4852 st_wait_for_io(struct scsi_tape *un)
4853 {
4854 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4855 	ASSERT(mutex_owned(ST_MUTEX));
4856 	while ((un->un_ncmds) || (un->un_quef) || (un->un_runqf)) {
4857 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4858 	}
4859 }
4860 
4861 /*
4862  * This routine implements the ioctl calls.  It is called
4863  * from the device switch at normal priority.
4864  */
4865 /*ARGSUSED*/
4866 static int
4867 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4868     int *rval_p)
4869 {
4870 	int tmp, rval = 0;
4871 
4872 	GET_SOFT_STATE(dev);
4873 
4874 	ST_ENTR(ST_DEVINFO, st_ioctl);
4875 
4876 	mutex_enter(ST_MUTEX);
4877 
4878 	ASSERT(un->un_recov_buf_busy == 0);
4879 
4880 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4881 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4882 	    "pe_flag = %d\n",
4883 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4884 	    un->un_persistence && un->un_persist_errors);
4885 
4886 	/*
4887 	 * We don't want to block on these, so let them through
4888 	 * and we don't care about setting driver states here.
4889 	 */
4890 	if ((cmd == MTIOCGETDRIVETYPE) ||
4891 	    (cmd == MTIOCGUARANTEEDORDER) ||
4892 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4893 		goto check_commands;
4894 	}
4895 
4896 	/*
4897 	 * We clear error entry stack except command
4898 	 * MTIOCGETERROR and MTIOCGET
4899 	 */
4900 	if ((cmd != MTIOCGETERROR) &&
4901 	    (cmd != MTIOCGET)) {
4902 		st_empty_error_stack(un);
4903 	}
4904 
4905 	/*
4906 	 * wait for all outstanding commands to complete, or be dequeued.
4907 	 * And because ioctl's are synchronous commands, any return value
4908 	 * after this,  will be in order
4909 	 */
4910 	st_wait_for_io(un);
4911 
4912 	/*
4913 	 * allow only a through clear errors and persistent status, and
4914 	 * status
4915 	 */
4916 	if (un->un_persistence && un->un_persist_errors) {
4917 		if ((cmd == MTIOCLRERR) ||
4918 		    (cmd == MTIOCPERSISTENT) ||
4919 		    (cmd == MTIOCGET)) {
4920 			goto check_commands;
4921 		} else {
4922 			rval = un->un_errno;
4923 			goto exit;
4924 		}
4925 	}
4926 
4927 	ASSERT(un->un_throttle != 0);
4928 	un->un_throttle = 1;	/* > 1 will never happen here */
4929 	un->un_errno = 0;	/* start clean from here */
4930 
4931 	/*
4932 	 * first and foremost, handle any ST_EOT_PENDING cases.
4933 	 * That is, if a logical eot is pending notice, notice it.
4934 	 */
4935 	if (un->un_pos.eof == ST_EOT_PENDING) {
4936 		int resid = un->un_err_resid;
4937 		uchar_t status = un->un_status;
4938 		uchar_t lastop = un->un_lastop;
4939 
4940 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4941 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4942 			    "stioctl : EIO can't space fmk(-1)\n");
4943 			rval = EIO;
4944 			goto exit;
4945 		}
4946 		un->un_lastop = lastop; /* restore last operation */
4947 		if (status == SUN_KEY_EOF) {
4948 			un->un_status = SUN_KEY_EOT;
4949 		} else {
4950 			un->un_status = status;
4951 		}
4952 		un->un_err_resid  = resid;
4953 		/* fix up block number */
4954 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4955 		/* now we're at logical eot */
4956 		un->un_pos.eof = ST_EOT;
4957 	}
4958 
4959 	/*
4960 	 * now, handle the rest of the situations
4961 	 */
4962 check_commands:
4963 	switch (cmd) {
4964 	case MTIOCGET:
4965 	{
4966 #ifdef _MULTI_DATAMODEL
4967 		/*
4968 		 * For use when a 32 bit app makes a call into a
4969 		 * 64 bit ioctl
4970 		 */
4971 		struct mtget32		mtg_local32;
4972 		struct mtget32 		*mtget_32 = &mtg_local32;
4973 #endif /* _MULTI_DATAMODEL */
4974 
4975 			/* Get tape status */
4976 		struct mtget mtg_local;
4977 		struct mtget *mtget = &mtg_local;
4978 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4979 		    "st_ioctl: MTIOCGET\n");
4980 
4981 		bzero((caddr_t)mtget, sizeof (struct mtget));
4982 		mtget->mt_erreg = un->un_status;
4983 		mtget->mt_resid = un->un_err_resid;
4984 		mtget->mt_dsreg = un->un_retry_ct;
4985 		if (un->un_err_pos.pmode == legacy) {
4986 			mtget->mt_fileno = un->un_err_pos.fileno;
4987 		} else {
4988 			mtget->mt_fileno = -1;
4989 		}
4990 		/*
4991 		 * If the value is positive fine.
4992 		 * If its negative we need to return a value based on the
4993 		 * old way if counting backwards from INF (1,000,000,000).
4994 		 */
4995 		if (un->un_err_pos.blkno >= 0) {
4996 			mtget->mt_blkno = un->un_err_pos.blkno;
4997 		} else {
4998 			mtget->mt_blkno = INF + 1 - (-un->un_err_pos.blkno);
4999 		}
5000 		mtget->mt_type = un->un_dp->type;
5001 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
5002 		if (un->un_read_pos_type != NO_POS) {
5003 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
5004 		}
5005 		if (un->un_dp->options & ST_REEL) {
5006 			mtget->mt_flags |= MTF_REEL;
5007 			mtget->mt_bf = 20;
5008 		} else {		/* 1/4" cartridges */
5009 			switch (mtget->mt_type) {
5010 			/* Emulex cartridge tape */
5011 			case MT_ISMT02:
5012 				mtget->mt_bf = 40;
5013 				break;
5014 			default:
5015 				mtget->mt_bf = 126;
5016 				break;
5017 			}
5018 		}
5019 
5020 		/*
5021 		 * If large transfers are allowed and drive options
5022 		 * has no record size limit set. Calculate blocking
5023 		 * factor from the lesser of maxbsize and maxdma.
5024 		 */
5025 		if ((un->un_allow_large_xfer) &&
5026 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
5027 			mtget->mt_bf = min(un->un_maxbsize,
5028 			    un->un_maxdma) / SECSIZE;
5029 		}
5030 
5031 		if (un->un_read_only == WORM ||
5032 		    un->un_read_only == RDWORM) {
5033 			mtget->mt_flags |= MTF_WORM_MEDIA;
5034 		}
5035 
5036 		/*
5037 		 * In persistent error mode sending a non-queued can hang
5038 		 * because this ioctl gets to be run without turning off
5039 		 * persistense. Fake the answer based on previous info.
5040 		 */
5041 		if (un->un_persistence) {
5042 			rval = 0;
5043 		} else {
5044 			rval = st_check_clean_bit(un);
5045 		}
5046 		if (rval == 0) {
5047 			/*
5048 			 * If zero is returned or in persistent mode,
5049 			 * use the old data.
5050 			 */
5051 			if ((un->un_HeadClean & (TAPE_ALERT_SUPPORTED |
5052 			    TAPE_SEQUENTIAL_SUPPORTED|TAPE_ALERT_NOT_SUPPORTED))
5053 			    != TAPE_ALERT_NOT_SUPPORTED) {
5054 				mtget->mt_flags |= MTF_TAPE_CLN_SUPPORTED;
5055 			}
5056 			if (un->un_HeadClean & (TAPE_PREVIOUSLY_DIRTY |
5057 			    TAPE_ALERT_STILL_DIRTY)) {
5058 				mtget->mt_flags |= MTF_TAPE_HEAD_DIRTY;
5059 			}
5060 		} else {
5061 			mtget->mt_flags |= (ushort_t)rval;
5062 			rval = 0;
5063 		}
5064 
5065 		un->un_status = 0;		/* Reset status */
5066 		un->un_err_resid = 0;
5067 		tmp = sizeof (struct mtget);
5068 
5069 #ifdef _MULTI_DATAMODEL
5070 
5071 		switch (ddi_model_convert_from(flag & FMODELS)) {
5072 		case DDI_MODEL_ILP32:
5073 			/*
5074 			 * Convert 64 bit back to 32 bit before doing
5075 			 * copyout. This is what the ILP32 app expects.
5076 			 */
5077 			mtget_32->mt_erreg = 	mtget->mt_erreg;
5078 			mtget_32->mt_resid = 	mtget->mt_resid;
5079 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
5080 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
5081 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
5082 			mtget_32->mt_type =  	mtget->mt_type;
5083 			mtget_32->mt_flags = 	mtget->mt_flags;
5084 			mtget_32->mt_bf = 	mtget->mt_bf;
5085 
5086 			if (ddi_copyout(mtget_32, (void *)arg,
5087 			    sizeof (struct mtget32), flag)) {
5088 				rval = EFAULT;
5089 			}
5090 			break;
5091 
5092 		case DDI_MODEL_NONE:
5093 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5094 				rval = EFAULT;
5095 			}
5096 			break;
5097 		}
5098 #else /* ! _MULTI_DATAMODE */
5099 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5100 			rval = EFAULT;
5101 		}
5102 #endif /* _MULTI_DATAMODE */
5103 
5104 		break;
5105 	}
5106 	case MTIOCGETERROR:
5107 			/*
5108 			 * get error entry from error stack
5109 			 */
5110 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5111 			    "st_ioctl: MTIOCGETERROR\n");
5112 
5113 			rval = st_get_error_entry(un, arg, flag);
5114 
5115 			break;
5116 
5117 	case MTIOCSTATE:
5118 		{
5119 			/*
5120 			 * return when media presence matches state
5121 			 */
5122 			enum mtio_state state;
5123 
5124 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5125 			    "st_ioctl: MTIOCSTATE\n");
5126 
5127 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
5128 				rval = EFAULT;
5129 
5130 			mutex_exit(ST_MUTEX);
5131 
5132 			rval = st_check_media(dev, state);
5133 
5134 			mutex_enter(ST_MUTEX);
5135 
5136 			if (rval != 0) {
5137 				break;
5138 			}
5139 
5140 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
5141 			    sizeof (int), flag))
5142 				rval = EFAULT;
5143 			break;
5144 
5145 		}
5146 
5147 	case MTIOCGETDRIVETYPE:
5148 		{
5149 #ifdef _MULTI_DATAMODEL
5150 		/*
5151 		 * For use when a 32 bit app makes a call into a
5152 		 * 64 bit ioctl
5153 		 */
5154 		struct mtdrivetype_request32	mtdtrq32;
5155 #endif /* _MULTI_DATAMODEL */
5156 
5157 			/*
5158 			 * return mtdrivetype
5159 			 */
5160 			struct mtdrivetype_request mtdtrq;
5161 			struct mtdrivetype mtdrtyp;
5162 			struct mtdrivetype *mtdt = &mtdrtyp;
5163 			struct st_drivetype *stdt = un->un_dp;
5164 
5165 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5166 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
5167 
5168 #ifdef _MULTI_DATAMODEL
5169 		switch (ddi_model_convert_from(flag & FMODELS)) {
5170 		case DDI_MODEL_ILP32:
5171 		{
5172 			if (ddi_copyin((void *)arg, &mtdtrq32,
5173 			    sizeof (struct mtdrivetype_request32), flag)) {
5174 				rval = EFAULT;
5175 				break;
5176 			}
5177 			mtdtrq.size = mtdtrq32.size;
5178 			mtdtrq.mtdtp =
5179 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
5180 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5181 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
5182 			break;
5183 		}
5184 		case DDI_MODEL_NONE:
5185 			if (ddi_copyin((void *)arg, &mtdtrq,
5186 			    sizeof (struct mtdrivetype_request), flag)) {
5187 				rval = EFAULT;
5188 				break;
5189 			}
5190 			break;
5191 		}
5192 
5193 #else /* ! _MULTI_DATAMODEL */
5194 		if (ddi_copyin((void *)arg, &mtdtrq,
5195 		    sizeof (struct mtdrivetype_request), flag)) {
5196 			rval = EFAULT;
5197 			break;
5198 		}
5199 #endif /* _MULTI_DATAMODEL */
5200 
5201 			/*
5202 			 * if requested size is < 0 then return
5203 			 * error.
5204 			 */
5205 			if (mtdtrq.size < 0) {
5206 				rval = EINVAL;
5207 				break;
5208 			}
5209 			bzero(mtdt, sizeof (struct mtdrivetype));
5210 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
5211 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
5212 			mtdt->type = stdt->type;
5213 			mtdt->bsize = stdt->bsize;
5214 			mtdt->options = stdt->options;
5215 			mtdt->max_rretries = stdt->max_rretries;
5216 			mtdt->max_wretries = stdt->max_wretries;
5217 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5218 				mtdt->densities[tmp] = stdt->densities[tmp];
5219 			}
5220 			mtdt->default_density = stdt->default_density;
5221 			/*
5222 			 * Speed hasn't been used since the hayday of reel tape.
5223 			 * For all drives not setting the option ST_KNOWS_MEDIA
5224 			 * the speed member renamed to mediatype are zeros.
5225 			 * Those drives that have ST_KNOWS_MEDIA set use the
5226 			 * new mediatype member which is used to figure the
5227 			 * type of media loaded.
5228 			 *
5229 			 * So as to not break applications speed in the
5230 			 * mtdrivetype structure is not renamed.
5231 			 */
5232 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5233 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
5234 			}
5235 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
5236 			mtdt->io_timeout = stdt->io_timeout;
5237 			mtdt->rewind_timeout = stdt->rewind_timeout;
5238 			mtdt->space_timeout = stdt->space_timeout;
5239 			mtdt->load_timeout = stdt->load_timeout;
5240 			mtdt->unload_timeout = stdt->unload_timeout;
5241 			mtdt->erase_timeout = stdt->erase_timeout;
5242 
5243 			/*
5244 			 * Limit the maximum length of the result to
5245 			 * sizeof (struct mtdrivetype).
5246 			 */
5247 			tmp = sizeof (struct mtdrivetype);
5248 			if (mtdtrq.size < tmp)
5249 				tmp = mtdtrq.size;
5250 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
5251 				rval = EFAULT;
5252 			}
5253 			break;
5254 		}
5255 	case MTIOCPERSISTENT:
5256 
5257 		if (ddi_copyin((void *)arg, &tmp, sizeof (tmp), flag)) {
5258 			rval = EFAULT;
5259 			break;
5260 		}
5261 
5262 		if (tmp) {
5263 			st_turn_pe_on(un);
5264 		} else {
5265 			st_turn_pe_off(un);
5266 		}
5267 
5268 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5269 		    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
5270 		    un->un_persistence);
5271 
5272 		break;
5273 
5274 	case MTIOCPERSISTENTSTATUS:
5275 		tmp = (int)un->un_persistence;
5276 
5277 		if (ddi_copyout(&tmp, (void *)arg, sizeof (tmp), flag)) {
5278 			rval = EFAULT;
5279 		}
5280 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5281 		    "st_ioctl: MTIOCPERSISTENTSTATUS:persistence = %d\n",
5282 		    un->un_persistence);
5283 
5284 		break;
5285 
5286 	case MTIOCLRERR:
5287 		{
5288 			/* clear persistent errors */
5289 
5290 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5291 			    "st_ioctl: MTIOCLRERR\n");
5292 
5293 			st_clear_pe(un);
5294 
5295 			break;
5296 		}
5297 
5298 	case MTIOCGUARANTEEDORDER:
5299 		{
5300 			/*
5301 			 * this is just a holder to make a valid ioctl and
5302 			 * it won't be in any earlier release
5303 			 */
5304 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5305 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
5306 
5307 			break;
5308 		}
5309 
5310 	case MTIOCRESERVE:
5311 		{
5312 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5313 			    "st_ioctl: MTIOCRESERVE\n");
5314 
5315 			/*
5316 			 * Check if Reserve/Release is supported.
5317 			 */
5318 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5319 				rval = ENOTTY;
5320 				break;
5321 			}
5322 
5323 			rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5324 
5325 			if (rval == 0) {
5326 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
5327 			}
5328 			break;
5329 		}
5330 
5331 	case MTIOCRELEASE:
5332 		{
5333 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5334 			    "st_ioctl: MTIOCRELEASE\n");
5335 
5336 			/*
5337 			 * Check if Reserve/Release is supported.
5338 			 */
5339 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5340 				rval = ENOTTY;
5341 				break;
5342 			}
5343 
5344 			/*
5345 			 * Used to just clear ST_PRESERVE_RESERVE which
5346 			 * made the reservation release at next close.
5347 			 * As the user may have opened and then done a
5348 			 * persistant reservation we now need to drop
5349 			 * the reservation without closing if the user
5350 			 * attempts to do this.
5351 			 */
5352 			rval = st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
5353 
5354 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5355 
5356 			break;
5357 		}
5358 
5359 	case MTIOCFORCERESERVE:
5360 	{
5361 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5362 		    "st_ioctl: MTIOCFORCERESERVE\n");
5363 
5364 		/*
5365 		 * Check if Reserve/Release is supported.
5366 		 */
5367 		if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5368 			rval = ENOTTY;
5369 			break;
5370 		}
5371 		/*
5372 		 * allow only super user to run this.
5373 		 */
5374 		if (drv_priv(cred_p) != 0) {
5375 			rval = EPERM;
5376 			break;
5377 		}
5378 		/*
5379 		 * Throw away reserve,
5380 		 * not using test-unit-ready
5381 		 * since reserve can succeed without tape being
5382 		 * present in the drive.
5383 		 */
5384 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5385 
5386 		rval = st_take_ownership(un, st_uscsi_cmd);
5387 
5388 		break;
5389 	}
5390 
5391 	case USCSICMD:
5392 	{
5393 		cred_t	*cr;
5394 
5395 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5396 		    "st_ioctl: USCSICMD\n");
5397 
5398 		cr = ddi_get_cred();
5399 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5400 			rval = EPERM;
5401 		} else {
5402 			rval = st_uscsi_cmd(un, (struct uscsi_cmd *)arg, flag);
5403 		}
5404 		break;
5405 	}
5406 	case MTIOCTOP:
5407 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5408 		    "st_ioctl: MTIOCTOP\n");
5409 		rval = st_mtioctop(un, arg, flag);
5410 		break;
5411 
5412 	case MTIOCLTOP:
5413 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5414 		    "st_ioctl: MTIOLCTOP\n");
5415 		rval = st_mtiocltop(un, arg, flag);
5416 		break;
5417 
5418 	case MTIOCREADIGNOREILI:
5419 		{
5420 			int set_ili;
5421 
5422 			if (ddi_copyin((void *)arg, &set_ili,
5423 			    sizeof (set_ili), flag)) {
5424 				rval = EFAULT;
5425 				break;
5426 			}
5427 
5428 			if (un->un_bsize) {
5429 				rval = ENOTTY;
5430 				break;
5431 			}
5432 
5433 			switch (set_ili) {
5434 			case 0:
5435 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5436 				break;
5437 
5438 			case 1:
5439 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5440 				break;
5441 
5442 			default:
5443 				rval = EINVAL;
5444 				break;
5445 			}
5446 			break;
5447 		}
5448 
5449 	case MTIOCREADIGNOREEOFS:
5450 		{
5451 			int ignore_eof;
5452 
5453 			if (ddi_copyin((void *)arg, &ignore_eof,
5454 			    sizeof (ignore_eof), flag)) {
5455 				rval = EFAULT;
5456 				break;
5457 			}
5458 
5459 			if (!(un->un_dp->options & ST_REEL)) {
5460 				rval = ENOTTY;
5461 				break;
5462 			}
5463 
5464 			switch (ignore_eof) {
5465 			case 0:
5466 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5467 				break;
5468 
5469 			case 1:
5470 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5471 				break;
5472 
5473 			default:
5474 				rval = EINVAL;
5475 				break;
5476 			}
5477 			break;
5478 		}
5479 
5480 	case MTIOCSHORTFMK:
5481 	{
5482 		int short_fmk;
5483 
5484 		if (ddi_copyin((void *)arg, &short_fmk,
5485 		    sizeof (short_fmk), flag)) {
5486 			rval = EFAULT;
5487 			break;
5488 		}
5489 
5490 		switch (un->un_dp->type) {
5491 		case ST_TYPE_EXB8500:
5492 		case ST_TYPE_EXABYTE:
5493 			if (!short_fmk) {
5494 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5495 			} else if (short_fmk == 1) {
5496 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5497 			} else {
5498 				rval = EINVAL;
5499 			}
5500 			break;
5501 
5502 		default:
5503 			rval = ENOTTY;
5504 			break;
5505 		}
5506 		break;
5507 	}
5508 
5509 	case MTIOCGETPOS:
5510 		rval = st_update_block_pos(un, st_cmd, 0);
5511 		if (rval == 0) {
5512 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5513 			    sizeof (tapepos_t), flag)) {
5514 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5515 				    "MTIOCGETPOS copy out failed\n");
5516 				rval = EFAULT;
5517 			}
5518 		}
5519 		break;
5520 
5521 	case MTIOCRESTPOS:
5522 	{
5523 		tapepos_t dest;
5524 
5525 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5526 		    flag) != 0) {
5527 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5528 			    "MTIOCRESTPOS copy in failed\n");
5529 			rval = EFAULT;
5530 			break;
5531 		}
5532 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &dest);
5533 		if (rval != 0) {
5534 			rval = EIO;
5535 		}
5536 		break;
5537 	}
5538 	default:
5539 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5540 		    "st_ioctl: unknown ioctl\n");
5541 		rval = ENOTTY;
5542 	}
5543 
5544 exit:
5545 	if (!(un->un_persistence && un->un_persist_errors)) {
5546 		un->un_errno = rval;
5547 	}
5548 
5549 	mutex_exit(ST_MUTEX);
5550 
5551 	return (rval);
5552 }
5553 
5554 
5555 /*
5556  * do some MTIOCTOP tape operations
5557  */
5558 static int
5559 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5560 {
5561 #ifdef _MULTI_DATAMODEL
5562 	/*
5563 	 * For use when a 32 bit app makes a call into a
5564 	 * 64 bit ioctl
5565 	 */
5566 	struct mtop32	mtop_32_for_64;
5567 #endif /* _MULTI_DATAMODEL */
5568 	struct mtop passed;
5569 	struct mtlop local;
5570 	int rval = 0;
5571 
5572 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5573 
5574 	ASSERT(mutex_owned(ST_MUTEX));
5575 
5576 #ifdef _MULTI_DATAMODEL
5577 	switch (ddi_model_convert_from(flag & FMODELS)) {
5578 	case DDI_MODEL_ILP32:
5579 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5580 		    sizeof (struct mtop32), flag)) {
5581 			return (EFAULT);
5582 		}
5583 		local.mt_op = mtop_32_for_64.mt_op;
5584 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5585 		break;
5586 
5587 	case DDI_MODEL_NONE:
5588 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5589 			return (EFAULT);
5590 		}
5591 		local.mt_op = passed.mt_op;
5592 		/* prevent sign extention */
5593 		local.mt_count = (UINT32_MAX & passed.mt_count);
5594 		break;
5595 	}
5596 
5597 #else /* ! _MULTI_DATAMODEL */
5598 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5599 		return (EFAULT);
5600 	}
5601 	local.mt_op = passed.mt_op;
5602 	/* prevent sign extention */
5603 	local.mt_count = (UINT32_MAX & passed.mt_count);
5604 #endif /* _MULTI_DATAMODEL */
5605 
5606 	rval = st_do_mtioctop(un, &local);
5607 
5608 #ifdef _MULTI_DATAMODEL
5609 	switch (ddi_model_convert_from(flag & FMODELS)) {
5610 	case DDI_MODEL_ILP32:
5611 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5612 			rval = ERANGE;
5613 			break;
5614 		}
5615 		/*
5616 		 * Convert 64 bit back to 32 bit before doing
5617 		 * copyout. This is what the ILP32 app expects.
5618 		 */
5619 		mtop_32_for_64.mt_op = local.mt_op;
5620 		mtop_32_for_64.mt_count = local.mt_count;
5621 
5622 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5623 		    sizeof (struct mtop32), flag)) {
5624 			rval = EFAULT;
5625 		}
5626 		break;
5627 
5628 	case DDI_MODEL_NONE:
5629 		passed.mt_count = local.mt_count;
5630 		passed.mt_op = local.mt_op;
5631 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5632 			rval = EFAULT;
5633 		}
5634 		break;
5635 	}
5636 #else /* ! _MULTI_DATAMODE */
5637 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5638 		rval = ERANGE;
5639 	} else {
5640 		passed.mt_op = local.mt_op;
5641 		passed.mt_count = local.mt_count;
5642 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5643 			rval = EFAULT;
5644 		}
5645 	}
5646 #endif /* _MULTI_DATAMODE */
5647 
5648 
5649 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5650 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5651 	    un->un_pos.blkno, un->un_pos.eof);
5652 
5653 	if (un->un_pos.pmode == invalid) {
5654 		un->un_density_known = 0;
5655 	}
5656 
5657 	ASSERT(mutex_owned(ST_MUTEX));
5658 	return (rval);
5659 }
5660 
5661 static int
5662 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5663 {
5664 	struct mtlop local;
5665 	int rval;
5666 
5667 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5668 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5669 		return (EFAULT);
5670 	}
5671 
5672 	rval = st_do_mtioctop(un, &local);
5673 
5674 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5675 		rval = EFAULT;
5676 	}
5677 	return (rval);
5678 }
5679 
5680 
5681 static int
5682 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5683 {
5684 	dev_t dev = un->un_dev;
5685 	int savefile;
5686 	int rval = 0;
5687 
5688 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5689 
5690 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5691 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5692 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5693 	    "fileno=%x, blkno=%x, eof=%x\n",
5694 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5695 
5696 	un->un_status = 0;
5697 
5698 	/*
5699 	 * if we are going to mess with a tape, we have to make sure we have
5700 	 * one and are not offline (i.e. no tape is initialized).  We let
5701 	 * commands pass here that don't actually touch the tape, except for
5702 	 * loading and initialization (rewinding).
5703 	 */
5704 	if (un->un_state == ST_STATE_OFFLINE) {
5705 		switch (mtop->mt_op) {
5706 		case MTLOAD:
5707 		case MTNOP:
5708 			/*
5709 			 * We don't want strategy calling st_tape_init here,
5710 			 * so, change state
5711 			 */
5712 			un->un_state = ST_STATE_INITIALIZING;
5713 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5714 			    "st_do_mtioctop : OFFLINE state = %d\n",
5715 			    un->un_state);
5716 			break;
5717 		default:
5718 			/*
5719 			 * reinitialize by normal means
5720 			 */
5721 			rval = st_tape_init(un);
5722 			if (rval) {
5723 				un->un_state = ST_STATE_INITIALIZING;
5724 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5725 				    "st_do_mtioctop : OFFLINE init failure ");
5726 				un->un_state = ST_STATE_OFFLINE;
5727 				un->un_pos.pmode = invalid;
5728 				if (rval != EACCES) {
5729 					rval = EIO;
5730 				}
5731 				return (rval);
5732 			}
5733 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5734 			break;
5735 		}
5736 	}
5737 
5738 	/*
5739 	 * If the file position is invalid, allow only those
5740 	 * commands that properly position the tape and fail
5741 	 * the rest with EIO
5742 	 */
5743 	if (un->un_pos.pmode == invalid) {
5744 		switch (mtop->mt_op) {
5745 		case MTWEOF:
5746 		case MTRETEN:
5747 		case MTERASE:
5748 		case MTEOM:
5749 		case MTFSF:
5750 		case MTFSR:
5751 		case MTBSF:
5752 		case MTNBSF:
5753 		case MTBSR:
5754 		case MTSRSZ:
5755 		case MTGRSZ:
5756 		case MTSEEK:
5757 		case MTBSSF:
5758 		case MTFSSF:
5759 			return (EIO);
5760 			/* NOTREACHED */
5761 		case MTREW:
5762 		case MTLOAD:
5763 		case MTOFFL:
5764 		case MTNOP:
5765 		case MTTELL:
5766 		case MTLOCK:
5767 		case MTUNLOCK:
5768 			break;
5769 
5770 		default:
5771 			return (ENOTTY);
5772 			/* NOTREACHED */
5773 		}
5774 	}
5775 
5776 	switch (mtop->mt_op) {
5777 	case MTERASE:
5778 		/*
5779 		 * MTERASE rewinds the tape, erase it completely, and returns
5780 		 * to the beginning of the tape
5781 		 */
5782 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5783 			un->un_status = KEY_WRITE_PROTECT;
5784 			un->un_err_resid = mtop->mt_count;
5785 			COPY_POS(&un->un_err_pos, &un->un_pos);
5786 			return (EACCES);
5787 		}
5788 		if (un->un_dp->options & ST_REEL) {
5789 			un->un_fmneeded = 2;
5790 		} else {
5791 			un->un_fmneeded = 1;
5792 		}
5793 		mtop->mt_count = mtop->mt_count ? 1 : 0;
5794 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5795 		    st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
5796 		    st_cmd(un, SCMD_ERASE, mtop->mt_count, SYNC_CMD)) {
5797 			un->un_pos.pmode = invalid;
5798 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5799 			    "st_do_mtioctop : EIO space or erase or "
5800 			    "check den)\n");
5801 			rval = EIO;
5802 		} else {
5803 			/* QIC and helical scan rewind after erase */
5804 			if (un->un_dp->options & ST_REEL) {
5805 				(void) st_cmd(un, SCMD_REWIND, 0, ASYNC_CMD);
5806 			}
5807 		}
5808 		break;
5809 
5810 	case MTWEOF:
5811 		/*
5812 		 * write an end-of-file record
5813 		 */
5814 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5815 			un->un_status = KEY_WRITE_PROTECT;
5816 			un->un_err_resid = mtop->mt_count;
5817 			COPY_POS(&un->un_err_pos, &un->un_pos);
5818 			return (EACCES);
5819 		}
5820 
5821 		/*
5822 		 * zero count means just flush buffers
5823 		 * negative count is not permitted
5824 		 */
5825 		if (mtop->mt_count < 0) {
5826 			return (EINVAL);
5827 		}
5828 
5829 		/* Not on worm */
5830 		if (un->un_read_only == RDWR) {
5831 			un->un_test_append = 1;
5832 		}
5833 
5834 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5835 			if (st_determine_density(un, B_WRITE)) {
5836 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5837 				    "st_do_mtioctop : EIO : MTWEOF can't "
5838 				    "determine density");
5839 				return (EIO);
5840 			}
5841 		}
5842 
5843 		rval = st_write_fm(dev, (int)mtop->mt_count);
5844 		if ((rval != 0) && (rval != EACCES)) {
5845 			/*
5846 			 * Failure due to something other than illegal
5847 			 * request results in loss of state (st_intr).
5848 			 */
5849 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5850 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5851 			    "file mark");
5852 			rval = EIO;
5853 		}
5854 		break;
5855 
5856 	case MTRETEN:
5857 		/*
5858 		 * retension the tape
5859 		 */
5860 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5861 		    st_cmd(un, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5862 			un->un_pos.pmode = invalid;
5863 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5864 			    "st_do_mtioctop : EIO : MTRETEN ");
5865 			rval = EIO;
5866 		}
5867 		break;
5868 
5869 	case MTREW:
5870 		/*
5871 		 * rewind  the tape
5872 		 */
5873 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5874 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5875 			    "st_do_mtioctop : EIO:MTREW check "
5876 			    "density/wfm failed");
5877 			return (EIO);
5878 		}
5879 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
5880 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5881 			    "st_do_mtioctop : EIO : MTREW ");
5882 			rval = EIO;
5883 		}
5884 		break;
5885 
5886 	case MTOFFL:
5887 		/*
5888 		 * rewinds, and, if appropriate, takes the device offline by
5889 		 * unloading the tape
5890 		 */
5891 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5892 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5893 			    "st_do_mtioctop :EIO:MTOFFL check "
5894 			    "density/wfm failed");
5895 			return (EIO);
5896 		}
5897 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
5898 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5899 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5900 			    "st_do_mtioctop : EIO : MTOFFL");
5901 			return (EIO);
5902 		}
5903 		un->un_pos.eof = ST_NO_EOF;
5904 		un->un_laststate = un->un_state;
5905 		un->un_state = ST_STATE_OFFLINE;
5906 		un->un_mediastate = MTIO_EJECTED;
5907 		break;
5908 
5909 	case MTLOAD:
5910 		/*
5911 		 * This is to load a tape into the drive
5912 		 * Note that if the tape is not loaded, the device will have
5913 		 * to be opened via O_NDELAY or O_NONBLOCK.
5914 		 */
5915 		/*
5916 		 * Let's try and clean things up, if we are not
5917 		 * initializing, and then send in the load command, no
5918 		 * matter what.
5919 		 *
5920 		 * load after a media change by the user.
5921 		 */
5922 
5923 		if (un->un_state > ST_STATE_INITIALIZING) {
5924 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5925 		}
5926 		rval = st_cmd(un, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5927 		/* Load command to a drive that doesn't support load */
5928 		if ((rval == EIO) &&
5929 		    ((un->un_status == KEY_NOT_READY) &&
5930 			/* Medium not present */
5931 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5932 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5933 		    (un->un_dp->type == MT_ISSTK9840) &&
5934 			/* CSL not present */
5935 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5936 			rval = ENOTTY;
5937 			break;
5938 		} else if (rval != EACCES && rval != 0) {
5939 			rval = EIO;
5940 		}
5941 		if (rval) {
5942 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5943 			    "st_do_mtioctop : %s : MTLOAD\n",
5944 			    rval == EACCES ? "EACCES" : "EIO");
5945 			/*
5946 			 * If load tape fails, who knows what happened...
5947 			 */
5948 			un->un_pos.pmode = invalid;
5949 			break;
5950 		}
5951 
5952 		/*
5953 		 * reset all counters appropriately using rewind, as if LOAD
5954 		 * succeeds, we are at BOT
5955 		 */
5956 		un->un_state = ST_STATE_INITIALIZING;
5957 
5958 		rval = st_tape_init(un);
5959 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5960 			rval = 0;
5961 			break;
5962 		}
5963 
5964 		if (rval != 0) {
5965 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5966 			    "st_do_mtioctop : EIO : MTLOAD calls "
5967 			    "st_tape_init\n");
5968 			rval = EIO;
5969 			un->un_state = ST_STATE_OFFLINE;
5970 		}
5971 
5972 		break;
5973 
5974 	case MTNOP:
5975 		un->un_status = 0;		/* Reset status */
5976 		un->un_err_resid = 0;
5977 		mtop->mt_count = MTUNIT(dev);
5978 		break;
5979 
5980 	case MTEOM:
5981 		/*
5982 		 * positions the tape at a location just after the last file
5983 		 * written on the tape. For cartridge and 8 mm, this after
5984 		 * the last file mark; for reel, this is inbetween the two
5985 		 * last 2 file marks
5986 		 */
5987 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5988 		    (un->un_lastop == ST_OP_WRITE) ||
5989 		    (un->un_lastop == ST_OP_WEOF)) {
5990 			/*
5991 			 * If the command wants to move to logical end
5992 			 * of media, and we're already there, we're done.
5993 			 * If we were at logical eot, we reset the state
5994 			 * to be *not* at logical eot.
5995 			 *
5996 			 * If we're at physical or logical eot, we prohibit
5997 			 * forward space operations (unconditionally).
5998 			 *
5999 			 * Also if the last operation was a write of any
6000 			 * kind the tape is at EOD.
6001 			 */
6002 			return (0);
6003 		}
6004 		/*
6005 		 * physical tape position may not be what we've been
6006 		 * telling the user; adjust the request accordingly
6007 		 */
6008 		if (IN_EOF(un->un_pos)) {
6009 			un->un_pos.fileno++;
6010 			un->un_pos.blkno = 0;
6011 		}
6012 
6013 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
6014 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6015 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
6016 			    " failed");
6017 			return (EIO);
6018 		}
6019 
6020 		/*
6021 		 * st_find_eod() returns the last fileno we knew about;
6022 		 */
6023 		savefile = st_find_eod(un);
6024 
6025 		if ((un->un_status != KEY_BLANK_CHECK) &&
6026 		    (un->un_status != SUN_KEY_EOT)) {
6027 			un->un_pos.pmode = invalid;
6028 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6029 			    "st_do_mtioctop : EIO : MTEOM status check failed");
6030 			rval = EIO;
6031 		} else {
6032 			/*
6033 			 * For 1/2" reel tapes assume logical EOT marked
6034 			 * by two file marks or we don't care that we may
6035 			 * be extending the last file on the tape.
6036 			 */
6037 			if (un->un_dp->options & ST_REEL) {
6038 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
6039 					un->un_pos.pmode = invalid;
6040 					ST_DEBUG2(ST_DEVINFO, st_label,
6041 					    SCSI_DEBUG,
6042 					    "st_do_mtioctop : EIO : MTEOM space"
6043 					    " cmd failed");
6044 					rval = EIO;
6045 					break;
6046 				}
6047 				/*
6048 				 * Fix up the block number.
6049 				 */
6050 				un->un_pos.blkno = 0;
6051 				un->un_err_pos.blkno = 0;
6052 			}
6053 			un->un_err_resid = 0;
6054 			un->un_pos.fileno = savefile;
6055 			un->un_pos.eof = ST_EOT;
6056 		}
6057 		un->un_status = 0;
6058 		break;
6059 
6060 	case MTFSF:
6061 		MAX_SPACE_CNT(mtop->mt_count);
6062 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
6063 		break;
6064 
6065 	case MTFSR:
6066 		MAX_SPACE_CNT(mtop->mt_count);
6067 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
6068 		break;
6069 
6070 	case MTBSF:
6071 		MAX_SPACE_CNT(mtop->mt_count);
6072 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
6073 		break;
6074 
6075 	case MTNBSF:
6076 		MAX_SPACE_CNT(mtop->mt_count);
6077 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
6078 		break;
6079 
6080 	case MTBSR:
6081 		MAX_SPACE_CNT(mtop->mt_count);
6082 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
6083 		break;
6084 
6085 	case MTBSSF:
6086 		MAX_SPACE_CNT(mtop->mt_count);
6087 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
6088 		break;
6089 
6090 	case MTFSSF:
6091 		MAX_SPACE_CNT(mtop->mt_count);
6092 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
6093 		break;
6094 
6095 	case MTSRSZ:
6096 
6097 		/*
6098 		 * Set record-size to that sent by user
6099 		 * Check to see if there is reason that the requested
6100 		 * block size should not be set.
6101 		 */
6102 
6103 		/* If requesting variable block size is it ok? */
6104 		if ((mtop->mt_count == 0) &&
6105 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
6106 			return (ENOTTY);
6107 		}
6108 
6109 		/*
6110 		 * If requested block size is not variable "0",
6111 		 * is it less then minimum.
6112 		 */
6113 		if ((mtop->mt_count != 0) &&
6114 		    (mtop->mt_count < un->un_minbsize)) {
6115 			return (EINVAL);
6116 		}
6117 
6118 		/* Is the requested block size more then maximum */
6119 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
6120 		    (un->un_maxbsize != 0)) {
6121 			return (EINVAL);
6122 		}
6123 
6124 		/* Is requested block size a modulus the device likes */
6125 		if ((mtop->mt_count % un->un_data_mod) != 0) {
6126 			return (EINVAL);
6127 		}
6128 
6129 		if (st_change_block_size(un, (uint32_t)mtop->mt_count) != 0) {
6130 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6131 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
6132 			return (EIO);
6133 		}
6134 
6135 		return (0);
6136 
6137 	case MTGRSZ:
6138 		/*
6139 		 * Get record-size to the user
6140 		 */
6141 		mtop->mt_count = un->un_bsize;
6142 		rval = 0;
6143 		break;
6144 
6145 	case MTTELL:
6146 		rval = st_update_block_pos(un, st_cmd, 0);
6147 		mtop->mt_count = un->un_pos.lgclblkno;
6148 		break;
6149 
6150 	case MTSEEK:
6151 		rval = st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
6152 		    (uint64_t)mtop->mt_count, un->un_pos.partition);
6153 		/*
6154 		 * This bit of magic make mt print the actual position if
6155 		 * the resulting position was not what was asked for.
6156 		 */
6157 		if (rval == ESPIPE) {
6158 			rval = EIO;
6159 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
6160 				mtop->mt_op = MTTELL;
6161 				mtop->mt_count = un->un_pos.lgclblkno;
6162 			}
6163 		}
6164 		break;
6165 
6166 	case MTLOCK:
6167 		if (st_cmd(un, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
6168 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6169 			    "st_do_mtioctop : EIO : MTLOCK");
6170 			rval = EIO;
6171 		}
6172 		break;
6173 
6174 	case MTUNLOCK:
6175 		if (st_cmd(un, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
6176 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6177 			    "st_do_mtioctop : EIO : MTUNLOCK");
6178 			rval = EIO;
6179 		}
6180 		break;
6181 
6182 	default:
6183 		rval = ENOTTY;
6184 	}
6185 
6186 	return (rval);
6187 }
6188 
6189 
6190 /*
6191  * Run a command for uscsi ioctl.
6192  */
6193 static int
6194 st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
6195 {
6196 	struct uscsi_cmd	*uscmd;
6197 	struct buf	*bp;
6198 	enum uio_seg	uioseg;
6199 	int	offline_state = 0;
6200 	int	err = 0;
6201 	dev_t dev = un->un_dev;
6202 
6203 	ST_FUNC(ST_DEVINFO, st_uscsi_cmd);
6204 
6205 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6206 	    "st_uscsi_cmd(dev = 0x%lx)\n", un->un_dev);
6207 
6208 	ASSERT(mutex_owned(ST_MUTEX));
6209 
6210 	/*
6211 	 * We really don't know what commands are coming in here and
6212 	 * we don't want to limit the commands coming in.
6213 	 *
6214 	 * If st_tape_init() gets called from st_strategy(), then we
6215 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
6216 	 * which it never will, as we set it below.  To prevent
6217 	 * st_tape_init() from getting called, we have to set state to other
6218 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
6219 	 * achieves this purpose already.
6220 	 *
6221 	 * We use offline_state to preserve the OFFLINE state, if it exists,
6222 	 * so other entry points to the driver might have the chance to call
6223 	 * st_tape_init().
6224 	 */
6225 	if (un->un_state == ST_STATE_OFFLINE) {
6226 		un->un_laststate = ST_STATE_OFFLINE;
6227 		un->un_state = ST_STATE_INITIALIZING;
6228 		offline_state = 1;
6229 	}
6230 
6231 	mutex_exit(ST_MUTEX);
6232 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag, ROUTE, &uscmd);
6233 	mutex_enter(ST_MUTEX);
6234 	if (err != 0) {
6235 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6236 		    "st_uscsi_cmd: scsi_uscsi_alloc_and_copyin failed\n");
6237 		goto exit;
6238 	}
6239 
6240 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
6241 
6242 	/* check to see if this command requires the drive to be reserved */
6243 	if (uscmd->uscsi_cdb != NULL) {
6244 		err = st_check_cdb_for_need_to_reserve(un,
6245 		    (uchar_t *)uscmd->uscsi_cdb);
6246 		if (err) {
6247 			goto exit_free;
6248 		}
6249 		/*
6250 		 * If this is a space command we need to save the starting
6251 		 * point so we can retry from there if the command fails.
6252 		 */
6253 		if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6254 		    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) {
6255 			(void) st_update_block_pos(un, st_cmd, 0);
6256 		}
6257 	}
6258 
6259 	/*
6260 	 * Forground should not be doing anything while recovery is active.
6261 	 */
6262 	ASSERT(un->un_recov_buf_busy == 0);
6263 
6264 	/*
6265 	 * Get buffer resources...
6266 	 */
6267 	while (un->un_sbuf_busy)
6268 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6269 	un->un_sbuf_busy = 1;
6270 
6271 #ifdef STDEBUG
6272 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0x7) > 6) {
6273 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
6274 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6275 		    "uscsi cdb", uscmd->uscsi_cdb);
6276 		if (uscmd->uscsi_buflen) {
6277 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6278 			    "uscsi %s of %ld bytes %s %s space\n",
6279 			    (rw == B_READ) ? rd_str : wr_str,
6280 			    uscmd->uscsi_buflen,
6281 			    (rw == B_READ) ? "to" : "from",
6282 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
6283 		}
6284 	}
6285 #endif /* STDEBUG */
6286 
6287 	/*
6288 	 * Although st_uscsi_cmd() never makes use of these
6289 	 * now, we are just being safe and consistent.
6290 	 */
6291 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
6292 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
6293 
6294 	un->un_srqbufp = uscmd->uscsi_rqbuf;
6295 	bp = un->un_sbufp;
6296 	bzero(bp, sizeof (buf_t));
6297 	if (uscmd->uscsi_cdb != NULL) {
6298 		bp->b_forw = (struct buf *)(uintptr_t)uscmd->uscsi_cdb[0];
6299 	}
6300 	bp->b_back = (struct buf *)uscmd;
6301 
6302 	mutex_exit(ST_MUTEX);
6303 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, st_strategy, bp, NULL);
6304 	mutex_enter(ST_MUTEX);
6305 
6306 	/*
6307 	 * If scsi reset successful, don't write any filemarks.
6308 	 */
6309 	if ((err == 0) && (uscmd->uscsi_flags &
6310 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
6311 		un->un_fmneeded = 0;
6312 	}
6313 
6314 exit_free:
6315 	/*
6316 	 * Free resources
6317 	 */
6318 	un->un_sbuf_busy = 0;
6319 	un->un_srqbufp = NULL;
6320 
6321 	/*
6322 	 * If was a space command need to update logical block position.
6323 	 * If the command failed such that positioning is invalid, Don't
6324 	 * update the position as the user must do this to validate the
6325 	 * position for data protection.
6326 	 */
6327 	if ((uscmd->uscsi_cdb != NULL) &&
6328 	    ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6329 	    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) &&
6330 	    (un->un_pos.pmode != invalid)) {
6331 		un->un_running.pmode = invalid;
6332 		(void) st_update_block_pos(un, st_cmd, 1);
6333 		/*
6334 		 * Set running position to invalid so it updates on the
6335 		 * next command.
6336 		 */
6337 		un->un_running.pmode = invalid;
6338 	}
6339 	cv_signal(&un->un_sbuf_cv);
6340 	mutex_exit(ST_MUTEX);
6341 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
6342 	mutex_enter(ST_MUTEX);
6343 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6344 	    "st_uscsi_cmd returns 0x%x\n", err);
6345 
6346 exit:
6347 	/* don't lose offline state */
6348 	if (offline_state) {
6349 		un->un_state = ST_STATE_OFFLINE;
6350 	}
6351 
6352 	ASSERT(mutex_owned(ST_MUTEX));
6353 	return (err);
6354 }
6355 
6356 static int
6357 st_write_fm(dev_t dev, int wfm)
6358 {
6359 	int i;
6360 	int rval;
6361 
6362 	GET_SOFT_STATE(dev);
6363 
6364 	ST_FUNC(ST_DEVINFO, st_write_fm);
6365 
6366 	ASSERT(mutex_owned(ST_MUTEX));
6367 
6368 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6369 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6370 
6371 	/*
6372 	 * write one filemark at the time after EOT
6373 	 */
6374 	if (un->un_pos.eof >= ST_EOT) {
6375 		for (i = 0; i < wfm; i++) {
6376 			rval = st_cmd(un, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6377 			if (rval == EACCES) {
6378 				return (rval);
6379 			}
6380 			if (rval != 0) {
6381 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6382 				    "st_write_fm : EIO : write EOT file mark");
6383 				return (EIO);
6384 			}
6385 		}
6386 	} else {
6387 		rval = st_cmd(un, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6388 		if (rval == EACCES) {
6389 			return (rval);
6390 		}
6391 		if (rval) {
6392 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6393 			    "st_write_fm : EIO : write file mark");
6394 			return (EIO);
6395 		}
6396 	}
6397 
6398 	ASSERT(mutex_owned(ST_MUTEX));
6399 	return (0);
6400 }
6401 
6402 #ifdef STDEBUG
6403 static void
6404 st_start_dump(struct scsi_tape *un, struct buf *bp)
6405 {
6406 	struct scsi_pkt *pkt = BP_PKT(bp);
6407 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6408 
6409 	ST_FUNC(ST_DEVINFO, st_start_dump);
6410 
6411 	if ((st_debug & 0x7) < 6)
6412 		return;
6413 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6414 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6415 	    (void *)bp->b_forw, bp->b_bcount,
6416 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6417 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6418 	    "st_start: cdb",  (caddr_t)cdbp);
6419 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6420 	    "st_start: fileno=%d, blk=%d\n",
6421 	    un->un_pos.fileno, un->un_pos.blkno);
6422 }
6423 #endif
6424 
6425 
6426 /*
6427  * Command start && done functions
6428  */
6429 
6430 /*
6431  * st_start()
6432  *
6433  * Called from:
6434  *  st_strategy() to start a command.
6435  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6436  *  st_attach() when resuming from power down state.
6437  *  st_start_restart() to retry transport when device was previously busy.
6438  *  st_done_and_mutex_exit() to start the next command when previous is done.
6439  *
6440  * On entry:
6441  *  scsi_pkt may or may not be allocated.
6442  *
6443  */
6444 static void
6445 st_start(struct scsi_tape *un)
6446 {
6447 	struct buf *bp;
6448 	int status;
6449 	int queued;
6450 
6451 	ST_FUNC(ST_DEVINFO, st_start);
6452 	ASSERT(mutex_owned(ST_MUTEX));
6453 
6454 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6455 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6456 
6457 	if (un->un_recov_buf_busy) {
6458 		/* recovery commands can happen anytime */
6459 		bp = un->un_recov_buf;
6460 		queued = 0;
6461 	} else if (un->un_sbuf_busy) {
6462 		/* sbuf commands should only happen with an empty queue. */
6463 		ASSERT(un->un_quef == NULL);
6464 		ASSERT(un->un_runqf == NULL);
6465 		bp = un->un_sbufp;
6466 		queued = 0;
6467 	} else if (un->un_quef != NULL) {
6468 		if (un->un_persistence && un->un_persist_errors) {
6469 			return;
6470 		}
6471 		bp = un->un_quef;
6472 		queued = 1;
6473 	} else {
6474 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6475 		    "st_start() returning no buf found\n");
6476 		return;
6477 	}
6478 
6479 	ASSERT((bp->b_flags & B_DONE) == 0);
6480 
6481 	/*
6482 	 * Don't send more than un_throttle commands to the HBA
6483 	 */
6484 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6485 		/*
6486 		 * if doing recovery we know there is outstanding commands.
6487 		 */
6488 		if (bp != un->un_recov_buf) {
6489 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6490 			    "st_start returning throttle = %d or ncmds = %d\n",
6491 			    un->un_throttle, un->un_ncmds);
6492 			if (un->un_ncmds == 0) {
6493 				typedef void (*func)();
6494 				func fnc = (func)st_runout;
6495 
6496 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6497 				    "Sending delayed start to st_runout()\n");
6498 				mutex_exit(ST_MUTEX);
6499 				(void) timeout(fnc, un, drv_usectohz(1000000));
6500 				mutex_enter(ST_MUTEX);
6501 			}
6502 			return;
6503 		}
6504 	}
6505 
6506 	/*
6507 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6508 	 * build the command.
6509 	 */
6510 	if (BP_PKT(bp) == NULL) {
6511 		ASSERT((bp->b_flags & B_DONE) == 0);
6512 		st_make_cmd(un, bp, st_runout);
6513 		ASSERT((bp->b_flags & B_DONE) == 0);
6514 		status = geterror(bp);
6515 
6516 		/*
6517 		 * Some HBA's don't call bioerror() to set an error.
6518 		 * And geterror() returns zero if B_ERROR is not set.
6519 		 * So if we get zero we must check b_error.
6520 		 */
6521 		if (status == 0 && bp->b_error != 0) {
6522 			status = bp->b_error;
6523 			bioerror(bp, status);
6524 		}
6525 
6526 		/*
6527 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6528 		 * In tape ENOMEM has special meaning so we'll change it.
6529 		 */
6530 		if (status == ENOMEM) {
6531 			status = 0;
6532 			bioerror(bp, status);
6533 		}
6534 
6535 		/*
6536 		 * Did it fail and is it retryable?
6537 		 * If so return and wait for the callback through st_runout.
6538 		 * Also looks like scsi_init_pkt() will setup a callback even
6539 		 * if it isn't retryable.
6540 		 */
6541 		if (BP_PKT(bp) == NULL) {
6542 			if (status == 0) {
6543 				/*
6544 				 * If first attempt save state.
6545 				 */
6546 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6547 					un->un_laststate = un->un_state;
6548 					un->un_state = ST_STATE_RESOURCE_WAIT;
6549 				}
6550 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6551 				    "temp no resources for pkt\n");
6552 			} else if (status == EINVAL) {
6553 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6554 				    "scsi_init_pkt rejected pkt as too big\n");
6555 				if (un->un_persistence) {
6556 					st_set_pe_flag(un);
6557 				}
6558 			} else {
6559 				/*
6560 				 * Unlikely that it would be retryable then not.
6561 				 */
6562 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6563 					un->un_state = un->un_laststate;
6564 				}
6565 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6566 				    "perm no resources for pkt errno = 0x%x\n",
6567 				    status);
6568 			}
6569 			return;
6570 		}
6571 		/*
6572 		 * Worked this time set the state back.
6573 		 */
6574 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6575 			un->un_state = un->un_laststate;
6576 		}
6577 	}
6578 
6579 	if (queued) {
6580 		/*
6581 		 * move from waitq to runq
6582 		 */
6583 		(void) st_remove_from_queue(&un->un_quef, &un->un_quel, bp);
6584 		st_add_to_queue(&un->un_runqf, &un->un_runql, un->un_runql, bp);
6585 	}
6586 
6587 
6588 #ifdef STDEBUG
6589 	st_start_dump(un, bp);
6590 #endif
6591 
6592 	/* could not get here if throttle was zero */
6593 	un->un_last_throttle = un->un_throttle;
6594 	un->un_throttle = 0;	/* so nothing else will come in here */
6595 	un->un_ncmds++;
6596 
6597 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6598 
6599 	status = st_transport(un, BP_PKT(bp));
6600 
6601 	if (un->un_last_throttle) {
6602 		un->un_throttle = un->un_last_throttle;
6603 	}
6604 
6605 	if (status != TRAN_ACCEPT) {
6606 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6607 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
6608 		    "Unhappy transport packet status 0x%x\n", status);
6609 
6610 		if (status == TRAN_BUSY) {
6611 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
6612 
6613 			/*
6614 			 * If command recovery is enabled and this isn't
6615 			 * a recovery command try command recovery.
6616 			 */
6617 			if (pkti->privatelen == sizeof (recov_info) &&
6618 			    bp != un->un_recov_buf) {
6619 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
6620 				    "Command Recovery called on busy send\n");
6621 				if (st_command_recovery(un, BP_PKT(bp),
6622 				    ATTEMPT_RETRY) == JUST_RETURN) {
6623 					return;
6624 				}
6625 			} else {
6626 				mutex_exit(ST_MUTEX);
6627 				if (st_handle_start_busy(un, bp,
6628 				    ST_TRAN_BUSY_TIMEOUT, queued) == 0) {
6629 					mutex_enter(ST_MUTEX);
6630 					return;
6631 				}
6632 				/*
6633 				 * if too many retries, fail the transport
6634 				 */
6635 				mutex_enter(ST_MUTEX);
6636 			}
6637 		}
6638 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6639 		    "transport rejected %d\n", status);
6640 		bp->b_resid = bp->b_bcount;
6641 
6642 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6643 		ST_DO_ERRSTATS(un, st_transerrs);
6644 		if ((bp == un->un_recov_buf) && (status == TRAN_BUSY)) {
6645 			st_bioerror(bp, EBUSY);
6646 		} else {
6647 			st_bioerror(bp, EIO);
6648 			st_set_pe_flag(un);
6649 		}
6650 		st_done_and_mutex_exit(un, bp);
6651 		mutex_enter(ST_MUTEX);
6652 	}
6653 
6654 	ASSERT(mutex_owned(ST_MUTEX));
6655 }
6656 
6657 /*
6658  * if the transport is busy, then put this bp back on the waitq
6659  */
6660 static int
6661 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6662     clock_t timeout_interval, int queued)
6663 {
6664 
6665 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
6666 
6667 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6668 
6669 	mutex_enter(ST_MUTEX);
6670 
6671 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6672 	    "st_handle_start_busy()\n");
6673 
6674 	/*
6675 	 * Check to see if we hit the retry timeout and one last check for
6676 	 * making sure this is the last on the runq, if it is not, we have
6677 	 * to fail
6678 	 */
6679 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
6680 	    ((queued) && (un->un_runql != bp))) {
6681 		mutex_exit(ST_MUTEX);
6682 		return (-1);
6683 	}
6684 
6685 	if (queued) {
6686 		/* put the bp back on the waitq */
6687 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
6688 	}
6689 
6690 	/*
6691 	 * Decrement un_ncmds so that this
6692 	 * gets thru' st_start() again.
6693 	 */
6694 	un->un_ncmds--;
6695 
6696 	if (queued) {
6697 		/*
6698 		 * since this is an error case, we won't have to do this list
6699 		 * walking much. We've already made sure this bp was the
6700 		 * last on the runq
6701 		 */
6702 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6703 
6704 		/*
6705 		 * send a marker pkt, if appropriate
6706 		 */
6707 		st_hba_unflush(un);
6708 
6709 	}
6710 	/*
6711 	 * all queues are aligned, we are just waiting to
6712 	 * transport, don't alloc any more buf p's, when
6713 	 * st_start is reentered.
6714 	 */
6715 	(void) timeout(st_start_restart, un, timeout_interval);
6716 
6717 	mutex_exit(ST_MUTEX);
6718 	return (0);
6719 }
6720 
6721 
6722 /*
6723  * st_runout a callback that is called what a resource allocatation failed
6724  */
6725 static int
6726 st_runout(caddr_t arg)
6727 {
6728 	struct scsi_tape *un = (struct scsi_tape *)arg;
6729 	struct buf *bp;
6730 	int queued;
6731 
6732 	ASSERT(un != NULL);
6733 
6734 	ST_FUNC(ST_DEVINFO, st_runout);
6735 
6736 	mutex_enter(ST_MUTEX);
6737 
6738 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6739 
6740 	if (un->un_recov_buf_busy != 0) {
6741 		bp = un->un_recov_buf;
6742 		queued = 0;
6743 	} else if (un->un_sbuf_busy != 0) {
6744 		/* sbuf commands should only happen with an empty queue. */
6745 		ASSERT(un->un_quef == NULL);
6746 		ASSERT(un->un_runqf == NULL);
6747 		bp = un->un_sbufp;
6748 		queued = 0;
6749 	} else if (un->un_quef != NULL) {
6750 		bp = un->un_quef;
6751 		if (un->un_persistence && un->un_persist_errors) {
6752 			mutex_exit(ST_MUTEX);
6753 			bp->b_resid = bp->b_bcount;
6754 			biodone(bp);
6755 			return (1);
6756 		}
6757 		queued = 1;
6758 	} else {
6759 		ASSERT(1 == 0);
6760 		mutex_exit(ST_MUTEX);
6761 		return (1);
6762 	}
6763 
6764 	/*
6765 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6766 	 */
6767 	if ((bp != NULL) && (geterror(bp) != 0)) {
6768 
6769 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6770 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6771 		    bp->b_flags, geterror(bp));
6772 		ASSERT((bp->b_flags & B_DONE) == 0);
6773 
6774 		if (queued) {
6775 			(void) st_remove_from_queue(&un->un_quef, &un->un_quel,
6776 			    bp);
6777 		}
6778 		mutex_exit(ST_MUTEX);
6779 
6780 		ASSERT((bp->b_flags & B_DONE) == 0);
6781 
6782 		/*
6783 		 * Set resid, Error already set, then unblock calling thread.
6784 		 */
6785 		bp->b_resid = bp->b_bcount;
6786 		biodone(bp);
6787 	} else {
6788 		/*
6789 		 * Try Again
6790 		 */
6791 		st_start(un);
6792 		mutex_exit(ST_MUTEX);
6793 	}
6794 
6795 	/*
6796 	 * Comments courtesy of sd.c
6797 	 * The scsi_init_pkt routine allows for the callback function to
6798 	 * return a 0 indicating the callback should be rescheduled or a 1
6799 	 * indicating not to reschedule. This routine always returns 1
6800 	 * because the driver always provides a callback function to
6801 	 * scsi_init_pkt. This results in a callback always being scheduled
6802 	 * (via the scsi_init_pkt callback implementation) if a resource
6803 	 * failure occurs.
6804 	 */
6805 
6806 	return (1);
6807 }
6808 
6809 /*
6810  * st_done_and_mutex_exit()
6811  *	- remove bp from runq
6812  *	- start up the next request
6813  *	- if this was an asynch bp, clean up
6814  *	- exit with released mutex
6815  */
6816 static void
6817 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6818 {
6819 	int pe_flagged = 0;
6820 	struct scsi_pkt *pkt = BP_PKT(bp);
6821 	pkt_info *pktinfo = pkt->pkt_private;
6822 
6823 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6824 #if !defined(lint)
6825 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6826 #endif
6827 
6828 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6829 
6830 	ASSERT(mutex_owned(ST_MUTEX));
6831 
6832 	(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6833 
6834 	un->un_ncmds--;
6835 	cv_signal(&un->un_queue_cv);
6836 
6837 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6838 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6839 	    "0x%x\n", pkt->pkt_cdbp[0], bp->b_bcount,
6840 	    bp->b_resid, bp->b_flags);
6841 
6842 
6843 	/*
6844 	 * update kstats with transfer count info
6845 	 */
6846 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6847 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6848 		if (bp->b_flags & B_READ) {
6849 			IOSP->reads++;
6850 			IOSP->nread += n_done;
6851 		} else {
6852 			IOSP->writes++;
6853 			IOSP->nwritten += n_done;
6854 		}
6855 	}
6856 
6857 	/*
6858 	 * Start the next one before releasing resources on this one, if
6859 	 * there is something on the queue and persistent errors has not been
6860 	 * flagged
6861 	 */
6862 
6863 	if ((pe_flagged = (un->un_persistence && un->un_persist_errors)) != 0) {
6864 		un->un_last_resid = bp->b_resid;
6865 		un->un_last_count = bp->b_bcount;
6866 	}
6867 
6868 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6869 		cv_broadcast(&un->un_tape_busy_cv);
6870 	} else if (un->un_quef && un->un_throttle && !pe_flagged &&
6871 	    (bp != un->un_recov_buf)) {
6872 		st_start(un);
6873 	}
6874 
6875 	un->un_retry_ct = max(pktinfo->pkt_retry_cnt, pktinfo->str_retry_cnt);
6876 
6877 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6878 		/*
6879 		 * Since we marked this ourselves as ASYNC,
6880 		 * there isn't anybody around waiting for
6881 		 * completion any more.
6882 		 */
6883 		uchar_t *cmd = pkt->pkt_cdbp;
6884 		if (*cmd == SCMD_READ || *cmd == SCMD_WRITE) {
6885 			bp->b_un.b_addr = (caddr_t)0;
6886 		}
6887 		ST_DEBUG(ST_DEVINFO, st_label, CE_NOTE,
6888 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6889 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
6890 		    "CDB sent with B_ASYNC",  (caddr_t)cmd);
6891 		if (pkt) {
6892 			scsi_destroy_pkt(pkt);
6893 		}
6894 		un->un_sbuf_busy = 0;
6895 		cv_signal(&un->un_sbuf_cv);
6896 		mutex_exit(ST_MUTEX);
6897 		return;
6898 	}
6899 
6900 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6901 		/*
6902 		 * Copy status from scsi_pkt to uscsi_cmd
6903 		 * since st_uscsi_cmd needs it
6904 		 */
6905 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6906 	}
6907 
6908 
6909 #ifdef STDEBUG
6910 	if (((st_debug & 0x7) >= 4) &&
6911 	    (((un->un_pos.blkno % 100) == 0) ||
6912 	    (un->un_persistence && un->un_persist_errors))) {
6913 
6914 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6915 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6916 		    "un_errno = %d, un_pe = %d\n",
6917 		    un->un_ncmds, un->un_throttle, un->un_errno,
6918 		    un->un_persist_errors);
6919 	}
6920 
6921 #endif
6922 
6923 	mutex_exit(ST_MUTEX);
6924 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6925 	    "st_done_and_mutex_exit: freeing pkt\n");
6926 
6927 	if (pkt) {
6928 		scsi_destroy_pkt(pkt);
6929 	}
6930 
6931 	biodone(bp);
6932 
6933 	/*
6934 	 * now that we biodoned that command, if persistent errors have been
6935 	 * flagged, flush the waitq
6936 	 */
6937 	if (pe_flagged)
6938 		st_flush(un);
6939 }
6940 
6941 
6942 /*
6943  * Tape error, flush tape driver queue.
6944  */
6945 static void
6946 st_flush(struct scsi_tape *un)
6947 {
6948 	struct buf *bp;
6949 
6950 	ST_FUNC(ST_DEVINFO, st_flush);
6951 
6952 	mutex_enter(ST_MUTEX);
6953 
6954 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6955 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6956 	    un->un_ncmds, (void *)un->un_quef);
6957 
6958 	/*
6959 	 * if we still have commands outstanding, wait for them to come in
6960 	 * before flushing the queue, and make sure there is a queue
6961 	 */
6962 	if (un->un_ncmds || !un->un_quef)
6963 		goto exit;
6964 
6965 	/*
6966 	 * we have no more commands outstanding, so let's deal with special
6967 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6968 	 * is 0, then we know there was no error and we return a 0 read or
6969 	 * write before showing errors
6970 	 */
6971 
6972 	/* Flush the wait queue. */
6973 	while ((bp = un->un_quef) != NULL) {
6974 		un->un_quef = bp->b_actf;
6975 
6976 		bp->b_resid = bp->b_bcount;
6977 
6978 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6979 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6980 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6981 
6982 		st_set_pe_errno(un);
6983 
6984 		bioerror(bp, un->un_errno);
6985 
6986 		mutex_exit(ST_MUTEX);
6987 		/* it should have one, but check anyway */
6988 		if (BP_PKT(bp)) {
6989 			scsi_destroy_pkt(BP_PKT(bp));
6990 		}
6991 		biodone(bp);
6992 		mutex_enter(ST_MUTEX);
6993 	}
6994 
6995 	/*
6996 	 * It's not a bad practice to reset the
6997 	 * waitq tail pointer to NULL.
6998 	 */
6999 	un->un_quel = NULL;
7000 
7001 exit:
7002 	/* we mucked with the queue, so let others know about it */
7003 	cv_signal(&un->un_queue_cv);
7004 	mutex_exit(ST_MUTEX);
7005 }
7006 
7007 
7008 /*
7009  * Utility functions
7010  */
7011 static int
7012 st_determine_generic(struct scsi_tape *un)
7013 {
7014 	int bsize;
7015 	static char *cart = "0.25 inch cartridge";
7016 	char *sizestr;
7017 
7018 	ST_FUNC(ST_DEVINFO, st_determine_generic);
7019 
7020 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7021 	    "st_determine_generic(un = 0x%p)\n", (void*)un);
7022 
7023 	ASSERT(mutex_owned(ST_MUTEX));
7024 
7025 	if (st_modesense(un)) {
7026 		return (-1);
7027 	}
7028 
7029 	bsize = (un->un_mspl->high_bl << 16)	|
7030 	    (un->un_mspl->mid_bl << 8)	|
7031 	    (un->un_mspl->low_bl);
7032 
7033 	if (bsize == 0) {
7034 		un->un_dp->options |= ST_VARIABLE;
7035 		un->un_dp->bsize = 0;
7036 		un->un_bsize = 0;
7037 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
7038 		/*
7039 		 * record size of this device too big.
7040 		 * try and convert it to variable record length.
7041 		 *
7042 		 */
7043 		un->un_dp->options |= ST_VARIABLE;
7044 		if (st_change_block_size(un, 0) != 0) {
7045 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7046 			    "Fixed Record Size %d is too large\n", bsize);
7047 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7048 			    "Cannot switch to variable record size\n");
7049 			un->un_dp->options &= ~ST_VARIABLE;
7050 			return (-1);
7051 		}
7052 	} else if (st_change_block_size(un, 0) == 0) {
7053 		/*
7054 		 * If the drive was set to a non zero block size,
7055 		 * See if it can be set to a zero block size.
7056 		 * If it works, ST_VARIABLE so user can set it as they want.
7057 		 */
7058 		un->un_dp->options |= ST_VARIABLE;
7059 		un->un_dp->bsize = 0;
7060 		un->un_bsize = 0;
7061 	} else {
7062 		un->un_dp->bsize = bsize;
7063 		un->un_bsize = bsize;
7064 	}
7065 
7066 
7067 	switch (un->un_mspl->density) {
7068 	default:
7069 	case 0x0:
7070 		/*
7071 		 * default density, cannot determine any other
7072 		 * information.
7073 		 */
7074 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
7075 		un->un_dp->type = ST_TYPE_DEFAULT;
7076 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
7077 		break;
7078 	case 0x1:
7079 	case 0x2:
7080 	case 0x3:
7081 	case 0x6:
7082 		/*
7083 		 * 1/2" reel
7084 		 */
7085 		sizestr = "0.50 inch reel";
7086 		un->un_dp->type = ST_TYPE_REEL;
7087 		un->un_dp->options |= ST_REEL;
7088 		un->un_dp->densities[0] = 0x1;
7089 		un->un_dp->densities[1] = 0x2;
7090 		un->un_dp->densities[2] = 0x6;
7091 		un->un_dp->densities[3] = 0x3;
7092 		break;
7093 	case 0x4:
7094 	case 0x5:
7095 	case 0x7:
7096 	case 0x0b:
7097 
7098 		/*
7099 		 * Quarter inch.
7100 		 */
7101 		sizestr = cart;
7102 		un->un_dp->type = ST_TYPE_DEFAULT;
7103 		un->un_dp->options |= ST_QIC;
7104 
7105 		un->un_dp->densities[1] = 0x4;
7106 		un->un_dp->densities[2] = 0x5;
7107 		un->un_dp->densities[3] = 0x7;
7108 		un->un_dp->densities[0] = 0x0b;
7109 		break;
7110 
7111 	case 0x0f:
7112 	case 0x10:
7113 	case 0x11:
7114 	case 0x12:
7115 		/*
7116 		 * QIC-120, QIC-150, QIC-320, QIC-600
7117 		 */
7118 		sizestr = cart;
7119 		un->un_dp->type = ST_TYPE_DEFAULT;
7120 		un->un_dp->options |= ST_QIC;
7121 		un->un_dp->densities[0] = 0x0f;
7122 		un->un_dp->densities[1] = 0x10;
7123 		un->un_dp->densities[2] = 0x11;
7124 		un->un_dp->densities[3] = 0x12;
7125 		break;
7126 
7127 	case 0x09:
7128 	case 0x0a:
7129 	case 0x0c:
7130 	case 0x0d:
7131 		/*
7132 		 * 1/2" cartridge tapes. Include HI-TC.
7133 		 */
7134 		sizestr = cart;
7135 		sizestr[2] = '5';
7136 		sizestr[3] = '0';
7137 		un->un_dp->type = ST_TYPE_HIC;
7138 		un->un_dp->densities[0] = 0x09;
7139 		un->un_dp->densities[1] = 0x0a;
7140 		un->un_dp->densities[2] = 0x0c;
7141 		un->un_dp->densities[3] = 0x0d;
7142 		break;
7143 
7144 	case 0x13:
7145 			/* DDS-2/DDS-3 scsi spec densities */
7146 	case 0x24:
7147 	case 0x25:
7148 	case 0x26:
7149 		sizestr = "DAT Data Storage (DDS)";
7150 		un->un_dp->type = ST_TYPE_DAT;
7151 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7152 		break;
7153 
7154 	case 0x14:
7155 		/*
7156 		 * Helical Scan (Exabyte) devices
7157 		 */
7158 		sizestr = "8mm helical scan cartridge";
7159 		un->un_dp->type = ST_TYPE_EXABYTE;
7160 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7161 		break;
7162 	}
7163 
7164 	/*
7165 	 * Assume LONG ERASE, BSF and BSR
7166 	 */
7167 
7168 	un->un_dp->options |=
7169 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
7170 
7171 	/*
7172 	 * Only if mode sense data says no buffered write, set NOBUF
7173 	 */
7174 	if (un->un_mspl->bufm == 0)
7175 		un->un_dp->options |= ST_NOBUF;
7176 
7177 	/*
7178 	 * set up large read and write retry counts
7179 	 */
7180 
7181 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
7182 
7183 	/*
7184 	 * If this is a 0.50 inch reel tape, and
7185 	 * it is *not* variable mode, try and
7186 	 * set it to variable record length
7187 	 * mode.
7188 	 */
7189 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
7190 	    (un->un_dp->options & ST_VARIABLE)) {
7191 		if (st_change_block_size(un, 0) == 0) {
7192 			un->un_dp->bsize = 0;
7193 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
7194 			    un->un_mspl->low_bl = 0;
7195 		}
7196 	}
7197 
7198 	/*
7199 	 * Write to console about type of device found
7200 	 */
7201 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
7202 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
7203 	    sizestr);
7204 	if (un->un_dp->options & ST_VARIABLE) {
7205 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7206 		    "!Variable record length I/O\n");
7207 	} else {
7208 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7209 		    "!Fixed record length (%d byte blocks) I/O\n",
7210 		    un->un_dp->bsize);
7211 	}
7212 	ASSERT(mutex_owned(ST_MUTEX));
7213 	return (0);
7214 }
7215 
7216 static int
7217 st_determine_density(struct scsi_tape *un, int rw)
7218 {
7219 	int rval = 0;
7220 
7221 	ST_FUNC(ST_DEVINFO, st_determine_density);
7222 
7223 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7224 	    "st_determine_density(un = 0x%p, rw = %s)\n",
7225 	    (void*)un, (rw == B_WRITE ? wr_str: rd_str));
7226 
7227 	ASSERT(mutex_owned(ST_MUTEX));
7228 
7229 	/*
7230 	 * If we're past BOT, density is determined already.
7231 	 */
7232 	if (un->un_pos.pmode == logical) {
7233 		if (un->un_pos.lgclblkno != 0) {
7234 			goto exit;
7235 		}
7236 	} else if (un->un_pos.pmode == legacy) {
7237 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
7238 			/*
7239 			 * XXX: put in a bitch message about attempting to
7240 			 * XXX: change density past BOT.
7241 			 */
7242 			goto exit;
7243 		}
7244 	} else {
7245 		goto exit;
7246 	}
7247 	if ((un->un_pos.pmode == logical) &&
7248 	    (un->un_pos.lgclblkno != 0)) {
7249 		goto exit;
7250 	}
7251 
7252 
7253 	/*
7254 	 * If we're going to be writing, we set the density
7255 	 */
7256 	if (rw == 0 || rw == B_WRITE) {
7257 		/* un_curdens is used as an index into densities table */
7258 		un->un_curdens = MT_DENSITY(un->un_dev);
7259 		if (st_set_density(un)) {
7260 			rval = -1;
7261 		}
7262 		goto exit;
7263 	}
7264 
7265 	/*
7266 	 * If density is known already,
7267 	 * we don't have to get it again.(?)
7268 	 */
7269 	if (!un->un_density_known) {
7270 		if (st_get_density(un)) {
7271 			rval = -1;
7272 		}
7273 	}
7274 
7275 exit:
7276 	ASSERT(mutex_owned(ST_MUTEX));
7277 	return (rval);
7278 }
7279 
7280 
7281 /*
7282  * Try to determine density. We do this by attempting to read the
7283  * first record off the tape, cycling through the available density
7284  * codes as we go.
7285  */
7286 
7287 static int
7288 st_get_density(struct scsi_tape *un)
7289 {
7290 	int succes = 0, rval = -1, i;
7291 	uint_t size;
7292 	uchar_t dens, olddens;
7293 
7294 	ST_FUNC(ST_DEVINFO, st_get_density);
7295 
7296 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7297 	    "st_get_density(un = 0x%p)\n", (void*)un);
7298 
7299 	ASSERT(mutex_owned(ST_MUTEX));
7300 
7301 	/*
7302 	 * If Auto Density override is enabled The drive has
7303 	 * only one density and there is no point in attempting
7304 	 * find the correct one.
7305 	 *
7306 	 * Since most modern drives auto detect the density
7307 	 * and format of the recorded media before they come
7308 	 * ready. What this function does is a legacy behavior
7309 	 * and modern drives not only don't need it, The backup
7310 	 * utilities that do positioning via uscsi find the un-
7311 	 * expected rewinds problematic.
7312 	 *
7313 	 * The drives that need this are old reel to reel devices.
7314 	 * I took a swag and said they must be scsi-1 or older.
7315 	 * I don't beleave there will any of the newer devices
7316 	 * that need this. There will be some scsi-1 devices that
7317 	 * don't need this but I don't think they will be using the
7318 	 * BIG aftermarket backup and restore utilitys.
7319 	 */
7320 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
7321 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
7322 		un->un_density_known = 1;
7323 		rval = 0;
7324 		goto exit;
7325 	}
7326 
7327 	/*
7328 	 * This will only work on variable record length tapes
7329 	 * if and only if all variable record length tapes autodensity
7330 	 * select.
7331 	 */
7332 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
7333 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
7334 
7335 	/*
7336 	 * Start at the specified density
7337 	 */
7338 
7339 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
7340 
7341 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
7342 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
7343 		/*
7344 		 * If we've done this density before,
7345 		 * don't bother to do it again.
7346 		 */
7347 		dens = un->un_dp->densities[un->un_curdens];
7348 		if (i > 0 && dens == olddens)
7349 			continue;
7350 		olddens = dens;
7351 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7352 		    "trying density 0x%x\n", dens);
7353 		if (st_set_density(un)) {
7354 			continue;
7355 		}
7356 
7357 		/*
7358 		 * XXX - the creates lots of headaches and slowdowns - must
7359 		 * fix.
7360 		 */
7361 		succes = (st_cmd(un, SCMD_READ, (int)size, SYNC_CMD) == 0);
7362 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
7363 			break;
7364 		}
7365 		if (succes) {
7366 			st_init(un);
7367 			rval = 0;
7368 			un->un_density_known = 1;
7369 			break;
7370 		}
7371 	}
7372 	kmem_free(un->un_tmpbuf, size);
7373 	un->un_tmpbuf = 0;
7374 
7375 exit:
7376 	ASSERT(mutex_owned(ST_MUTEX));
7377 	return (rval);
7378 }
7379 
7380 static int
7381 st_set_density(struct scsi_tape *un)
7382 {
7383 	int rval = 0;
7384 
7385 	ST_FUNC(ST_DEVINFO, st_set_density);
7386 
7387 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7388 	    "st_set_density(un = 0x%p): density = 0x%x\n", (void*)un,
7389 	    un->un_dp->densities[un->un_curdens]);
7390 
7391 	ASSERT(mutex_owned(ST_MUTEX));
7392 
7393 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7394 
7395 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
7396 		/*
7397 		 * If auto density override is not set, Use mode select
7398 		 * to set density and compression.
7399 		 */
7400 		if (st_modeselect(un)) {
7401 			rval = -1;
7402 		}
7403 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
7404 		/*
7405 		 * If auto density and mode select compression are set,
7406 		 * This is a drive with one density code but compression
7407 		 * can be enabled or disabled.
7408 		 * Set compression but no need to set density.
7409 		 */
7410 		rval = st_set_compression(un);
7411 		if ((rval != 0) && (rval != EALREADY)) {
7412 			rval = -1;
7413 		} else {
7414 			rval = 0;
7415 		}
7416 	}
7417 
7418 	/* If sucessful set density and/or compression, mark density known */
7419 	if (rval == 0) {
7420 		un->un_density_known = 1;
7421 	}
7422 
7423 	ASSERT(mutex_owned(ST_MUTEX));
7424 	return (rval);
7425 }
7426 
7427 static int
7428 st_loadtape(struct scsi_tape *un)
7429 {
7430 	int rval;
7431 
7432 	ST_FUNC(ST_DEVINFO, st_loadtape);
7433 
7434 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7435 	    "st_loadtape(un = 0x%p)\n", (void*) un);
7436 
7437 	ASSERT(mutex_owned(ST_MUTEX));
7438 
7439 	rval = st_update_block_pos(un, st_cmd, 0);
7440 	if (rval == EACCES) {
7441 		return (rval);
7442 	}
7443 
7444 	/*
7445 	 * 'LOAD' the tape to BOT by rewinding
7446 	 */
7447 	rval = st_cmd(un, SCMD_REWIND, 1, SYNC_CMD);
7448 	if (rval == 0) {
7449 		st_init(un);
7450 		un->un_density_known = 0;
7451 	}
7452 
7453 	ASSERT(mutex_owned(ST_MUTEX));
7454 	return (rval);
7455 }
7456 
7457 
7458 /*
7459  * Note: QIC devices aren't so smart.  If you try to append
7460  * after EOM, the write can fail because the device doesn't know
7461  * it's at EOM.	 In that case, issue a read.  The read should fail
7462  * because there's no data, but the device knows it's at EOM,
7463  * so a subsequent write should succeed.  To further confuse matters,
7464  * the target returns the same error if the tape is positioned
7465  * such that a write would overwrite existing data.  That's why
7466  * we have to do the append test.  A read in the middle of
7467  * recorded data would succeed, thus indicating we're attempting
7468  * something illegal.
7469  */
7470 
7471 
7472 static void
7473 st_test_append(struct buf *bp)
7474 {
7475 	dev_t dev = bp->b_edev;
7476 	struct scsi_tape *un;
7477 	uchar_t status;
7478 	unsigned bcount;
7479 
7480 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7481 
7482 	ST_FUNC(ST_DEVINFO, st_test_append);
7483 
7484 	ASSERT(mutex_owned(ST_MUTEX));
7485 
7486 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7487 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7488 
7489 	un->un_laststate = un->un_state;
7490 	un->un_state = ST_STATE_APPEND_TESTING;
7491 	un->un_test_append = 0;
7492 
7493 	/*
7494 	 * first, map in the buffer, because we're doing a double write --
7495 	 * first into the kernel, then onto the tape.
7496 	 */
7497 	bp_mapin(bp);
7498 
7499 	/*
7500 	 * get a copy of the data....
7501 	 */
7502 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7503 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7504 
7505 	/*
7506 	 * attempt the write..
7507 	 */
7508 
7509 	if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7510 success:
7511 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7512 		    "append write succeeded\n");
7513 		bp->b_resid = un->un_sbufp->b_resid;
7514 		mutex_exit(ST_MUTEX);
7515 		bcount = (unsigned)bp->b_bcount;
7516 		biodone(bp);
7517 		mutex_enter(ST_MUTEX);
7518 		un->un_laststate = un->un_state;
7519 		un->un_state = ST_STATE_OPEN;
7520 		kmem_free(un->un_tmpbuf, bcount);
7521 		un->un_tmpbuf = NULL;
7522 		return;
7523 	}
7524 
7525 	/*
7526 	 * The append failed. Do a short read. If that fails,  we are at EOM
7527 	 * so we can retry the write command. If that succeeds, than we're
7528 	 * all screwed up (the controller reported a real error).
7529 	 *
7530 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7531 	 * XXX: block size?
7532 	 *
7533 	 */
7534 	status = un->un_status;
7535 	un->un_status = 0;
7536 	(void) st_cmd(un, SCMD_READ, SECSIZE, SYNC_CMD);
7537 	if (un->un_status == KEY_BLANK_CHECK) {
7538 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7539 		    "append at EOM\n");
7540 		/*
7541 		 * Okay- the read failed. We should actually have confused
7542 		 * the controller enough to allow writing. In any case, the
7543 		 * i/o is on its own from here on out.
7544 		 */
7545 		un->un_laststate = un->un_state;
7546 		un->un_state = ST_STATE_OPEN;
7547 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7548 		if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount,
7549 		    SYNC_CMD) == 0) {
7550 			goto success;
7551 		}
7552 	}
7553 
7554 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7555 	    "append write failed- not at EOM\n");
7556 	bp->b_resid = bp->b_bcount;
7557 	st_bioerror(bp, EIO);
7558 
7559 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7560 	    "st_test_append : EIO : append write failed - not at EOM");
7561 
7562 	/*
7563 	 * backspace one record to get back to where we were
7564 	 */
7565 	if (st_cmd(un, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7566 		un->un_pos.pmode = invalid;
7567 	}
7568 
7569 	un->un_err_resid = bp->b_resid;
7570 	un->un_status = status;
7571 
7572 	/*
7573 	 * Note: biodone will do a bp_mapout()
7574 	 */
7575 	mutex_exit(ST_MUTEX);
7576 	bcount = (unsigned)bp->b_bcount;
7577 	biodone(bp);
7578 	mutex_enter(ST_MUTEX);
7579 	un->un_laststate = un->un_state;
7580 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7581 	kmem_free(un->un_tmpbuf, bcount);
7582 	un->un_tmpbuf = NULL;
7583 }
7584 
7585 /*
7586  * Special command handler
7587  */
7588 
7589 /*
7590  * common st_cmd code. The fourth parameter states
7591  * whether the caller wishes to await the results
7592  * Note the release of the mutex during most of the function
7593  */
7594 static int
7595 st_cmd(struct scsi_tape *un, int com, int64_t count, int wait)
7596 {
7597 	struct buf *bp;
7598 	int err;
7599 	uint_t last_err_resid;
7600 
7601 	ST_FUNC(ST_DEVINFO, st_cmd);
7602 
7603 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7604 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %"PRIx64", wait = %d)\n",
7605 	    un->un_dev, com, count, wait);
7606 
7607 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7608 	ASSERT(mutex_owned(ST_MUTEX));
7609 
7610 #ifdef STDEBUG
7611 	if ((st_debug & 0x7)) {
7612 		st_debug_cmds(un, com, count, wait);
7613 	}
7614 #endif
7615 
7616 	st_wait_for_io(un);
7617 
7618 	/* check to see if this command requires the drive to be reserved */
7619 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7620 
7621 	if (err) {
7622 		return (err);
7623 	}
7624 
7625 	/*
7626 	 * A space command is not recoverable if we don't know were we
7627 	 * were when it was issued.
7628 	 */
7629 	if ((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) {
7630 		(void) st_update_block_pos(un, st_cmd, 0);
7631 	}
7632 
7633 	/*
7634 	 * Forground should not be doing anything while recovery is active.
7635 	 */
7636 	ASSERT(un->un_recov_buf_busy == 0);
7637 
7638 	while (un->un_sbuf_busy)
7639 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7640 	un->un_sbuf_busy = 1;
7641 
7642 	bp = un->un_sbufp;
7643 	bzero(bp, sizeof (buf_t));
7644 
7645 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7646 
7647 	err = st_setup_cmd(un, bp, com, count);
7648 
7649 	un->un_sbuf_busy = 0;
7650 
7651 	/*
7652 	 * If was a space command need to update logical block position.
7653 	 * Only do this if the command was sucessful or it will mask the fact
7654 	 * that the space command failed by promoting the pmode to logical.
7655 	 */
7656 	if (((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) &&
7657 	    (un->un_pos.pmode != invalid)) {
7658 		un->un_running.pmode = invalid;
7659 		last_err_resid = un->un_err_resid;
7660 		(void) st_update_block_pos(un, st_cmd, 1);
7661 		/*
7662 		 * Set running position to invalid so it updates on the
7663 		 * next command.
7664 		 */
7665 		un->un_running.pmode = invalid;
7666 		un->un_err_resid = last_err_resid;
7667 	}
7668 
7669 	cv_signal(&un->un_sbuf_cv);
7670 
7671 	return (err);
7672 }
7673 
7674 static int
7675 st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com, int64_t count)
7676 {
7677 	int err;
7678 	dev_t dev = un->un_dev;
7679 
7680 	ST_FUNC(ST_DEVINFO, st_setup_cmd);
7681 	/*
7682 	 * Set count to the actual size of the data tranfer.
7683 	 * For commands with no data transfer, set bp->b_bcount
7684 	 * to the value to be used when constructing the
7685 	 * cdb in st_make_cmd().
7686 	 */
7687 	switch (com) {
7688 	case SCMD_READ:
7689 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7690 		    "special read %"PRId64"\n", count);
7691 		bp->b_flags |= B_READ;
7692 		bp->b_un.b_addr = un->un_tmpbuf;
7693 		break;
7694 
7695 	case SCMD_WRITE:
7696 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7697 		    "special write %"PRId64"\n", count);
7698 		bp->b_un.b_addr = un->un_tmpbuf;
7699 		break;
7700 
7701 	case SCMD_WRITE_FILE_MARK:
7702 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7703 		    "write %"PRId64" file marks\n", count);
7704 		bp->b_bcount = count;
7705 		count = 0;
7706 		break;
7707 
7708 	case SCMD_REWIND:
7709 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7710 		bp->b_bcount = count;
7711 		count = 0;
7712 		break;
7713 
7714 	case SCMD_SPACE:
7715 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7716 		/*
7717 		 * If the user could have entered a number that will
7718 		 * not fit in the 12 bit count field of space(8),
7719 		 * use space(16).
7720 		 */
7721 		if (((int64_t)SPACE_CNT(count) > 0x7fffff) ||
7722 		    ((int64_t)SPACE_CNT(count) < -(0x7fffff))) {
7723 			com = SCMD_SPACE_G4;
7724 		}
7725 		bp->b_bcount = count;
7726 		count = 0;
7727 		break;
7728 
7729 	case SCMD_RESERVE:
7730 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7731 		bp->b_bcount = 0;
7732 		count = 0;
7733 		break;
7734 
7735 	case SCMD_RELEASE:
7736 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7737 		bp->b_bcount = 0;
7738 		count = 0;
7739 		break;
7740 
7741 	case SCMD_LOAD:
7742 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7743 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7744 		bp->b_bcount = count;
7745 		count = 0;
7746 		break;
7747 
7748 	case SCMD_ERASE:
7749 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7750 		    "erase tape\n");
7751 		bp->b_bcount = count;
7752 		count = 0;
7753 		break;
7754 
7755 	case SCMD_MODE_SENSE:
7756 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7757 		    "mode sense\n");
7758 		bp->b_flags |= B_READ;
7759 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7760 		break;
7761 
7762 	case SCMD_MODE_SELECT:
7763 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7764 		    "mode select\n");
7765 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7766 		break;
7767 
7768 	case SCMD_READ_BLKLIM:
7769 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7770 		    "read block limits\n");
7771 		bp->b_bcount = count;
7772 		bp->b_flags |= B_READ;
7773 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7774 		break;
7775 
7776 	case SCMD_TEST_UNIT_READY:
7777 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7778 		    "test unit ready\n");
7779 		bp->b_bcount = 0;
7780 		count = 0;
7781 		break;
7782 
7783 	case SCMD_DOORLOCK:
7784 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7785 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7786 		bp->b_bcount = count = 0;
7787 		break;
7788 
7789 	case SCMD_READ_POSITION:
7790 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7791 		    "read position\n");
7792 		switch (un->un_read_pos_type) {
7793 		case LONG_POS:
7794 			count = sizeof (tape_position_long_t);
7795 			break;
7796 		case EXT_POS:
7797 			count = min(count, sizeof (tape_position_ext_t));
7798 			break;
7799 		case SHORT_POS:
7800 			count = sizeof (tape_position_t);
7801 			break;
7802 		default:
7803 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7804 			    "Unknown read position type 0x%x in "
7805 			    "st_make_cmd()\n", un->un_read_pos_type);
7806 		}
7807 		bp->b_bcount = count;
7808 		bp->b_flags |= B_READ;
7809 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7810 		break;
7811 
7812 	default:
7813 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7814 		    "Unhandled scsi command 0x%x in st_setup_cmd()\n", com);
7815 	}
7816 
7817 	mutex_exit(ST_MUTEX);
7818 
7819 	if (count > 0) {
7820 		int flg = (bp->b_flags & B_READ) ? B_READ : B_WRITE;
7821 		/*
7822 		 * We're going to do actual I/O.
7823 		 * Set things up for physio.
7824 		 */
7825 		struct iovec aiov;
7826 		struct uio auio;
7827 		struct uio *uio = &auio;
7828 
7829 		bzero(&auio, sizeof (struct uio));
7830 		bzero(&aiov, sizeof (struct iovec));
7831 		aiov.iov_base = bp->b_un.b_addr;
7832 		aiov.iov_len = count;
7833 
7834 		uio->uio_iov = &aiov;
7835 		uio->uio_iovcnt = 1;
7836 		uio->uio_resid = aiov.iov_len;
7837 		uio->uio_segflg = UIO_SYSSPACE;
7838 
7839 		/*
7840 		 * Let physio do the rest...
7841 		 */
7842 		bp->b_forw = (struct buf *)(uintptr_t)com;
7843 		bp->b_back = NULL;
7844 		err = physio(st_strategy, bp, dev, flg, st_minphys, uio);
7845 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7846 		    "st_setup_cmd: physio returns %d\n", err);
7847 	} else {
7848 		/*
7849 		 * Mimic physio
7850 		 */
7851 		bp->b_forw = (struct buf *)(uintptr_t)com;
7852 		bp->b_back = NULL;
7853 		bp->b_edev = dev;
7854 		bp->b_dev = cmpdev(dev);
7855 		bp->b_blkno = 0;
7856 		bp->b_resid = 0;
7857 		(void) st_strategy(bp);
7858 		if (bp->b_flags & B_ASYNC) {
7859 			/*
7860 			 * This is an async command- the caller won't wait
7861 			 * and doesn't care about errors.
7862 			 */
7863 			mutex_enter(ST_MUTEX);
7864 			return (0);
7865 		}
7866 
7867 		/*
7868 		 * BugTraq #4260046
7869 		 * ----------------
7870 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7871 		 * unconditionally. The old comment said...
7872 		 *
7873 		 * "if strategy was flagged with  persistent errors, we would
7874 		 *  have an error here, and the bp would never be sent, so we
7875 		 *  don't want to wait on a bp that was never sent...or hang"
7876 		 *
7877 		 * The new rationale, courtesy of Chitrank...
7878 		 *
7879 		 * "we should unconditionally biowait() here because
7880 		 *  st_strategy() will do a biodone() in the persistent error
7881 		 *  case and the following biowait() will return immediately.
7882 		 *  If not, in the case of "errors after pkt alloc" in
7883 		 *  st_start(), we will not biowait here which will cause the
7884 		 *  next biowait() to return immediately which will cause
7885 		 *  us to send out the next command. In the case where both of
7886 		 *  these use the sbuf, when the first command completes we'll
7887 		 *  free the packet attached to sbuf and the same pkt will
7888 		 *  get freed again when we complete the second command.
7889 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7890 		 *  st_start() for the pkt alloc failure case because physio()
7891 		 *  does biowait() and will hang if we don't do biodone()"
7892 		 */
7893 
7894 		err = biowait(bp);
7895 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7896 		    "st_setup_cmd: biowait returns %d\n", err);
7897 	}
7898 
7899 	mutex_enter(ST_MUTEX);
7900 
7901 	return (err);
7902 }
7903 
7904 static int
7905 st_set_compression(struct scsi_tape *un)
7906 {
7907 	int rval;
7908 	int turn_compression_on;
7909 	minor_t minor;
7910 
7911 	ST_FUNC(ST_DEVINFO, st_set_compression);
7912 
7913 	/*
7914 	 * Drive either dosn't have compression or it is controlled with
7915 	 * special density codes. Return ENOTTY so caller
7916 	 * knows nothing was done.
7917 	 */
7918 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7919 		un->un_comp_page = 0;
7920 		return (ENOTTY);
7921 	}
7922 
7923 	/* set compression based on minor node opened */
7924 	minor = MT_DENSITY(un->un_dev);
7925 
7926 	/*
7927 	 * If this the compression density or
7928 	 * the drive has two densities and uses mode select for
7929 	 * control of compression turn on compression for MT_DENSITY2
7930 	 * as well.
7931 	 */
7932 	if ((minor == ST_COMPRESSION_DENSITY) ||
7933 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7934 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7935 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7936 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7937 
7938 		turn_compression_on = 1;
7939 	} else {
7940 		turn_compression_on = 0;
7941 	}
7942 
7943 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7944 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7945 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7946 
7947 	/*
7948 	 * Need to determine which page does the device use for compression.
7949 	 * First try the data compression page. If this fails try the device
7950 	 * configuration page
7951 	 */
7952 
7953 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7954 		rval = st_set_datacomp_page(un, turn_compression_on);
7955 		if (rval == EALREADY) {
7956 			return (rval);
7957 		}
7958 		if (rval != 0) {
7959 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7960 				/*
7961 				 * This device does not support data
7962 				 * compression page
7963 				 */
7964 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7965 			} else if (un->un_state >= ST_STATE_OPEN) {
7966 				un->un_pos.pmode = invalid;
7967 				rval = EIO;
7968 			} else {
7969 				rval = -1;
7970 			}
7971 		} else {
7972 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7973 		}
7974 	}
7975 
7976 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7977 		rval = st_set_devconfig_page(un, turn_compression_on);
7978 		if (rval == EALREADY) {
7979 			return (rval);
7980 		}
7981 		if (rval != 0) {
7982 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7983 				/*
7984 				 * This device does not support
7985 				 * compression at all advice the
7986 				 * user and unset ST_MODE_SEL_COMP
7987 				 */
7988 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7989 				un->un_comp_page = 0;
7990 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7991 				    "Device Does Not Support Compression\n");
7992 			} else if (un->un_state >= ST_STATE_OPEN) {
7993 				un->un_pos.pmode = invalid;
7994 				rval = EIO;
7995 			} else {
7996 				rval = -1;
7997 			}
7998 		}
7999 	}
8000 
8001 	return (rval);
8002 }
8003 
8004 /*
8005  * set or unset compression thru device configuration page.
8006  */
8007 static int
8008 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
8009 {
8010 	unsigned char cflag;
8011 	int rval = 0;
8012 
8013 
8014 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
8015 
8016 	ASSERT(mutex_owned(ST_MUTEX));
8017 
8018 	/*
8019 	 * if the mode sense page is not the correct one, load the correct one.
8020 	 */
8021 	if (un->un_mspl->page_code != ST_DEV_CONFIG_PAGE) {
8022 		rval = st_gen_mode_sense(un, st_uscsi_cmd, ST_DEV_CONFIG_PAGE,
8023 		    un->un_mspl, sizeof (struct seq_mode));
8024 		if (rval)
8025 			return (rval);
8026 	}
8027 
8028 	/*
8029 	 * Figure what to set compression flag to.
8030 	 */
8031 	if (compression_on) {
8032 		/* They have selected a compression node */
8033 		if (un->un_dp->type == ST_TYPE_FUJI) {
8034 			cflag = 0x84;   /* use EDRC */
8035 		} else {
8036 			cflag = ST_DEV_CONFIG_DEF_COMP;
8037 		}
8038 	} else {
8039 		cflag = ST_DEV_CONFIG_NO_COMP;
8040 	}
8041 
8042 	/*
8043 	 * If compression is already set the way it was requested.
8044 	 * And if this not the first time we has tried.
8045 	 */
8046 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
8047 	    (un->un_comp_page == ST_DEV_CONFIG_PAGE)) {
8048 		return (EALREADY);
8049 	}
8050 
8051 	un->un_mspl->page.dev.comp_alg = cflag;
8052 	/*
8053 	 * need to send mode select even if correct compression is
8054 	 * already set since need to set density code
8055 	 */
8056 
8057 #ifdef STDEBUG
8058 	if ((st_debug & 0x7) >= 6) {
8059 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8060 		    "st_set_devconfig_page: sense data for mode select",
8061 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8062 	}
8063 #endif
8064 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8065 	    sizeof (struct seq_mode));
8066 
8067 	return (rval);
8068 }
8069 
8070 /*
8071  * set/reset compression bit thru data compression page
8072  */
8073 static int
8074 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
8075 {
8076 	int compression_on_already;
8077 	int rval = 0;
8078 
8079 
8080 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
8081 
8082 	ASSERT(mutex_owned(ST_MUTEX));
8083 
8084 	/*
8085 	 * if the mode sense page is not the correct one, load the correct one.
8086 	 */
8087 	if (un->un_mspl->page_code != ST_DEV_DATACOMP_PAGE) {
8088 		rval = st_gen_mode_sense(un, st_uscsi_cmd, ST_DEV_DATACOMP_PAGE,
8089 		    un->un_mspl, sizeof (struct seq_mode));
8090 		if (rval)
8091 			return (rval);
8092 	}
8093 
8094 	/*
8095 	 * If drive is not capable of compression (at this time)
8096 	 * return EALREADY so caller doesn't think that this page
8097 	 * is not supported. This check is for drives that can
8098 	 * disable compression from the front panel or configuration.
8099 	 * I doubt that a drive that supports this page is not really
8100 	 * capable of compression.
8101 	 */
8102 	if (un->un_mspl->page.comp.dcc == 0) {
8103 		return (EALREADY);
8104 	}
8105 
8106 	/* See if compression currently turned on */
8107 	if (un->un_mspl->page.comp.dce) {
8108 		compression_on_already = 1;
8109 	} else {
8110 		compression_on_already = 0;
8111 	}
8112 
8113 	/*
8114 	 * If compression is already set the way it was requested.
8115 	 * And if this not the first time we has tried.
8116 	 */
8117 	if ((compression_on == compression_on_already) &&
8118 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
8119 		return (EALREADY);
8120 	}
8121 
8122 	/*
8123 	 * if we are already set to the appropriate compression
8124 	 * mode, don't set it again
8125 	 */
8126 	if (compression_on) {
8127 		/* compression selected */
8128 		un->un_mspl->page.comp.dce = 1;
8129 	} else {
8130 		un->un_mspl->page.comp.dce = 0;
8131 	}
8132 
8133 
8134 #ifdef STDEBUG
8135 	if ((st_debug & 0x7) >= 6) {
8136 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8137 		    "st_set_datacomp_page: sense data for mode select",
8138 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8139 	}
8140 #endif
8141 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8142 	    sizeof (struct seq_mode));
8143 
8144 	return (rval);
8145 }
8146 
8147 static int
8148 st_modesense(struct scsi_tape *un)
8149 {
8150 	int rval;
8151 	uchar_t page;
8152 
8153 	ST_FUNC(ST_DEVINFO, st_modesense);
8154 
8155 	page = un->un_comp_page;
8156 
8157 	switch (page) {
8158 	case ST_DEV_DATACOMP_PAGE:
8159 	case ST_DEV_CONFIG_PAGE: /* FALLTHROUGH */
8160 		rval = st_gen_mode_sense(un, st_uscsi_cmd, page, un->un_mspl,
8161 		    sizeof (struct seq_mode));
8162 		break;
8163 
8164 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
8165 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
8166 			page = ST_DEV_DATACOMP_PAGE;
8167 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8168 			    un->un_mspl, sizeof (struct seq_mode));
8169 			if (rval == 0 && un->un_mspl->page_code == page) {
8170 				un->un_comp_page = page;
8171 				break;
8172 			}
8173 			page = ST_DEV_CONFIG_PAGE;
8174 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8175 			    un->un_mspl, sizeof (struct seq_mode));
8176 			if (rval == 0 && un->un_mspl->page_code == page) {
8177 				un->un_comp_page = page;
8178 				break;
8179 			}
8180 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
8181 			un->un_comp_page = 0;
8182 		} else {
8183 			un->un_comp_page = 0;
8184 		}
8185 
8186 	default:	/* FALLTHROUGH */
8187 		rval = st_cmd(un, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
8188 	}
8189 	return (rval);
8190 }
8191 
8192 static int
8193 st_modeselect(struct scsi_tape *un)
8194 {
8195 	int rval = 0;
8196 	int ix;
8197 
8198 	ST_FUNC(ST_DEVINFO, st_modeselect);
8199 
8200 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8201 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
8202 	    un->un_dev, un->un_mspl->density);
8203 
8204 	ASSERT(mutex_owned(ST_MUTEX));
8205 
8206 	/*
8207 	 * The parameter list should be the same for all of the
8208 	 * cases that follow so set them here
8209 	 *
8210 	 * Try mode select first if if fails set fields manually
8211 	 */
8212 	rval = st_modesense(un);
8213 	if (rval != 0) {
8214 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8215 		    "st_modeselect: First mode sense failed\n");
8216 		un->un_mspl->bd_len  = 8;
8217 		un->un_mspl->high_nb = 0;
8218 		un->un_mspl->mid_nb  = 0;
8219 		un->un_mspl->low_nb  = 0;
8220 	}
8221 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
8222 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
8223 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
8224 
8225 
8226 	/*
8227 	 * If configured to use a specific density code for a media type.
8228 	 * curdens is previously set by the minor node opened.
8229 	 * If the media type doesn't match the minor node we change it so it
8230 	 * looks like the correct one was opened.
8231 	 */
8232 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
8233 		uchar_t best;
8234 
8235 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
8236 			if (un->un_mspl->media_type ==
8237 			    un->un_dp->mediatype[ix]) {
8238 				best = ix;
8239 				/*
8240 				 * It matches but it might not be the only one.
8241 				 * Use the highest matching media type but not
8242 				 * to exceed the density selected by the open.
8243 				 */
8244 				if (ix < un->un_curdens) {
8245 					continue;
8246 				}
8247 				un->un_curdens = ix;
8248 				break;
8249 			}
8250 		}
8251 		/* If a match was found best will not be 0xff any more */
8252 		if (best < NDENSITIES) {
8253 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8254 			    "found media 0x%X using density 0x%X\n",
8255 			    un->un_mspl->media_type,
8256 			    un->un_dp->densities[best]);
8257 			un->un_mspl->density = un->un_dp->densities[best];
8258 		} else {
8259 			/* Otherwise set density based on minor node opened */
8260 			un->un_mspl->density =
8261 			    un->un_dp->densities[un->un_curdens];
8262 		}
8263 	} else {
8264 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
8265 	}
8266 
8267 	if (un->un_dp->options & ST_NOBUF) {
8268 		un->un_mspl->bufm = 0;
8269 	} else {
8270 		un->un_mspl->bufm = 1;
8271 	}
8272 
8273 	rval = st_set_compression(un);
8274 
8275 	/*
8276 	 * If st_set_compression returned invalid or already it
8277 	 * found no need to do the mode select.
8278 	 * So do it here.
8279 	 */
8280 	if ((rval == ENOTTY) || (rval == EALREADY)) {
8281 
8282 		/* Zero non-writeable fields */
8283 		un->un_mspl->data_len = 0;
8284 		un->un_mspl->media_type = 0;
8285 		un->un_mspl->wp = 0;
8286 
8287 		/* need to set the density code */
8288 		rval = st_cmd(un, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
8289 		if (rval != 0) {
8290 			if (un->un_state >= ST_STATE_OPEN) {
8291 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8292 				    "unable to set tape mode\n");
8293 				un->un_pos.pmode = invalid;
8294 				rval = EIO;
8295 			} else {
8296 				rval = -1;
8297 			}
8298 		}
8299 	}
8300 
8301 	/*
8302 	 * The spec recommends to send a mode sense after a mode select
8303 	 */
8304 	(void) st_modesense(un);
8305 
8306 	ASSERT(mutex_owned(ST_MUTEX));
8307 
8308 	return (rval);
8309 }
8310 
8311 /*
8312  * st_gen_mode_sense
8313  *
8314  * generic mode sense.. it allows for any page
8315  */
8316 static int
8317 st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
8318     struct seq_mode *page_data, int page_size)
8319 {
8320 
8321 	int r;
8322 	char	cdb[CDB_GROUP0];
8323 	struct uscsi_cmd *com;
8324 	struct scsi_arq_status status;
8325 
8326 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
8327 
8328 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8329 
8330 	bzero(cdb, CDB_GROUP0);
8331 	cdb[0] = SCMD_MODE_SENSE;
8332 	cdb[2] = (char)page;
8333 	cdb[4] = (char)page_size;
8334 
8335 	com->uscsi_cdb = cdb;
8336 	com->uscsi_cdblen = CDB_GROUP0;
8337 	com->uscsi_bufaddr = (caddr_t)page_data;
8338 	com->uscsi_buflen = page_size;
8339 	com->uscsi_rqlen = sizeof (status);
8340 	com->uscsi_rqbuf = (caddr_t)&status;
8341 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8342 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8343 
8344 	r = ubf(un, com, FKIOCTL);
8345 	kmem_free(com, sizeof (*com));
8346 	return (r);
8347 }
8348 
8349 /*
8350  * st_gen_mode_select
8351  *
8352  * generic mode select.. it allows for any page
8353  */
8354 static int
8355 st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
8356     struct seq_mode *page_data, int page_size)
8357 {
8358 
8359 	int r;
8360 	char cdb[CDB_GROUP0];
8361 	struct uscsi_cmd *com;
8362 	struct scsi_arq_status status;
8363 
8364 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
8365 
8366 	/* Zero non-writeable fields */
8367 	page_data->data_len = 0;
8368 	page_data->media_type = 0;
8369 	page_data->wp = 0;
8370 
8371 	/*
8372 	 * If mode select has any page data, zero the ps (Page Savable) bit.
8373 	 */
8374 	if (page_size > MSIZE) {
8375 		page_data->ps = 0;
8376 	}
8377 
8378 
8379 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8380 
8381 	/*
8382 	 * then, do a mode select to set what ever info
8383 	 */
8384 	bzero(cdb, CDB_GROUP0);
8385 	cdb[0] = SCMD_MODE_SELECT;
8386 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
8387 	cdb[4] = (char)page_size;
8388 
8389 	com->uscsi_cdb = cdb;
8390 	com->uscsi_cdblen = CDB_GROUP0;
8391 	com->uscsi_bufaddr = (caddr_t)page_data;
8392 	com->uscsi_buflen = page_size;
8393 	com->uscsi_rqlen = sizeof (status);
8394 	com->uscsi_rqbuf = (caddr_t)&status;
8395 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8396 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_WRITE;
8397 
8398 	r = ubf(un, com, FKIOCTL);
8399 
8400 	kmem_free(com, sizeof (*com));
8401 	return (r);
8402 }
8403 
8404 static int
8405 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
8406 {
8407 	int rval;
8408 	char cdb[CDB_GROUP0];
8409 	struct uscsi_cmd *com;
8410 	struct scsi_arq_status status;
8411 
8412 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
8413 
8414 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8415 
8416 	bzero(cdb, CDB_GROUP0);
8417 	cdb[0] = SCMD_READ_BLKLIM;
8418 
8419 	com->uscsi_cdb = cdb;
8420 	com->uscsi_cdblen = CDB_GROUP0;
8421 	com->uscsi_bufaddr = (caddr_t)read_blk;
8422 	com->uscsi_buflen = sizeof (struct read_blklim);
8423 	com->uscsi_rqlen = sizeof (status);
8424 	com->uscsi_rqbuf = (caddr_t)&status;
8425 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8426 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8427 
8428 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8429 	if (com->uscsi_status || com->uscsi_resid) {
8430 		rval = -1;
8431 	}
8432 
8433 	kmem_free(com, sizeof (*com));
8434 	return (rval);
8435 }
8436 
8437 static int
8438 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
8439     size_t buflen)
8440 {
8441 	int rval;
8442 	char cdb[CDB_GROUP1];
8443 	struct uscsi_cmd *com;
8444 	struct scsi_arq_status status;
8445 
8446 	ST_FUNC(ST_DEVINFO, st_report_density_support);
8447 
8448 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8449 
8450 	bzero(cdb, CDB_GROUP1);
8451 	cdb[0] = SCMD_REPORT_DENSITIES;
8452 	cdb[7] = (buflen & 0xff00) >> 8;
8453 	cdb[8] = buflen & 0xff;
8454 
8455 	com->uscsi_cdb = cdb;
8456 	com->uscsi_cdblen = CDB_GROUP1;
8457 	com->uscsi_bufaddr = (caddr_t)density_data;
8458 	com->uscsi_buflen = buflen;
8459 	com->uscsi_rqlen = sizeof (status);
8460 	com->uscsi_rqbuf = (caddr_t)&status;
8461 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8462 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8463 
8464 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8465 	if (com->uscsi_status || com->uscsi_resid) {
8466 		rval = -1;
8467 	}
8468 
8469 	kmem_free(com, sizeof (*com));
8470 	return (rval);
8471 }
8472 
8473 static int
8474 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
8475     uchar_t option_code, ushort_t service_action)
8476 {
8477 	int rval;
8478 	char cdb[CDB_GROUP5];
8479 	struct uscsi_cmd *com;
8480 	struct scsi_arq_status status;
8481 	uint32_t allo_length;
8482 
8483 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
8484 
8485 	allo_length = sizeof (struct one_com_des) +
8486 	    sizeof (struct com_timeout_des);
8487 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8488 
8489 	bzero(cdb, CDB_GROUP5);
8490 	cdb[0] = (char)SCMD_MAINTENANCE_IN;
8491 	cdb[1] = SSVC_ACTION_GET_SUPPORTED_OPERATIONS;
8492 	if (service_action) {
8493 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
8494 		cdb[4] = (service_action & 0xff00) >> 8;
8495 		cdb[5] = service_action & 0xff;
8496 	} else {
8497 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
8498 		    0x80); /* RCTD */
8499 	}
8500 	cdb[3] = option_code;
8501 	cdb[6] = (allo_length & 0xff000000) >> 24;
8502 	cdb[7] = (allo_length & 0xff0000) >> 16;
8503 	cdb[8] = (allo_length & 0xff00) >> 8;
8504 	cdb[9] = allo_length & 0xff;
8505 
8506 	com->uscsi_cdb = cdb;
8507 	com->uscsi_cdblen = CDB_GROUP5;
8508 	com->uscsi_bufaddr = (caddr_t)oper_data;
8509 	com->uscsi_buflen = allo_length;
8510 	com->uscsi_rqlen = sizeof (status);
8511 	com->uscsi_rqbuf = (caddr_t)&status;
8512 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8513 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8514 
8515 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8516 	if (com->uscsi_status) {
8517 		rval = -1;
8518 	}
8519 
8520 	kmem_free(com, sizeof (*com));
8521 	return (rval);
8522 }
8523 
8524 /*
8525  * Changes devices blocksize and bsize to requested blocksize nblksz.
8526  * Returns returned value from first failed call or zero on success.
8527  */
8528 static int
8529 st_change_block_size(struct scsi_tape *un, uint32_t nblksz)
8530 {
8531 	struct seq_mode *current;
8532 	int rval;
8533 	uint32_t oldblksz;
8534 
8535 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8536 
8537 	current = kmem_zalloc(MSIZE, KM_SLEEP);
8538 
8539 	/*
8540 	 * If we haven't got the compression page yet, do that first.
8541 	 */
8542 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
8543 		(void) st_modesense(un);
8544 	}
8545 
8546 	/* Read current settings */
8547 	rval = st_gen_mode_sense(un, st_uscsi_cmd, 0, current, MSIZE);
8548 	if (rval != 0) {
8549 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8550 		    "mode sense for change block size failed: rval = %d", rval);
8551 		goto finish;
8552 	}
8553 
8554 	/* Figure the current block size */
8555 	oldblksz =
8556 	    (current->high_bl << 16) |
8557 	    (current->mid_bl << 8) |
8558 	    (current->low_bl);
8559 
8560 	/* If current block size is the same as requested were done */
8561 	if (oldblksz == nblksz) {
8562 		un->un_bsize = nblksz;
8563 		rval = 0;
8564 		goto finish;
8565 	}
8566 
8567 	/* Change to requested block size */
8568 	current->high_bl = (uchar_t)(nblksz >> 16);
8569 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8570 	current->low_bl  = (uchar_t)(nblksz);
8571 
8572 	/* Attempt to change block size */
8573 	rval = st_gen_mode_select(un, st_uscsi_cmd, current, MSIZE);
8574 	if (rval != 0) {
8575 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8576 		    "Set new block size failed: rval = %d", rval);
8577 		goto finish;
8578 	}
8579 
8580 	/* Read back and verify setting */
8581 	rval = st_modesense(un);
8582 	if (rval == 0) {
8583 		un->un_bsize =
8584 		    (un->un_mspl->high_bl << 16) |
8585 		    (un->un_mspl->mid_bl << 8) |
8586 		    (un->un_mspl->low_bl);
8587 
8588 		if (un->un_bsize != nblksz) {
8589 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8590 			    "Blocksize set does not equal requested blocksize"
8591 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8592 			rval = EIO;
8593 		}
8594 	}
8595 finish:
8596 	kmem_free(current, MSIZE);
8597 	return (rval);
8598 }
8599 
8600 
8601 static void
8602 st_init(struct scsi_tape *un)
8603 {
8604 	ST_FUNC(ST_DEVINFO, st_init);
8605 
8606 	ASSERT(mutex_owned(ST_MUTEX));
8607 
8608 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8609 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8610 	    un->un_dev);
8611 
8612 	un->un_pos.blkno = 0;
8613 	un->un_pos.fileno = 0;
8614 	un->un_lastop = ST_OP_NIL;
8615 	un->un_pos.eof = ST_NO_EOF;
8616 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8617 	if (st_error_level != SCSI_ERR_ALL) {
8618 		if (DEBUGGING) {
8619 			st_error_level = SCSI_ERR_ALL;
8620 		} else {
8621 			st_error_level = SCSI_ERR_RETRYABLE;
8622 		}
8623 	}
8624 }
8625 
8626 
8627 static void
8628 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8629 {
8630 	struct scsi_pkt *pkt;
8631 	struct uscsi_cmd *ucmd;
8632 	recov_info *ri;
8633 	int tval = 0;
8634 	int64_t count;
8635 	uint32_t additional = 0;
8636 	uint32_t address = 0;
8637 	union scsi_cdb *ucdb;
8638 	int flags = 0;
8639 	int cdb_len = CDB_GROUP0; /* default */
8640 	uchar_t com;
8641 	char fixbit;
8642 	char short_fm = 0;
8643 	optype prev_op = un->un_lastop;
8644 	int stat_size =
8645 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
8646 
8647 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8648 
8649 	ASSERT(mutex_owned(ST_MUTEX));
8650 
8651 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8652 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8653 
8654 
8655 	/*
8656 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8657 	 * Length Indicator bits on read/write commands, for setting
8658 	 * the Long bit on erase commands, and for setting the Code
8659 	 * Field bits on space commands.
8660 	 */
8661 
8662 	/* regular raw I/O */
8663 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
8664 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8665 		    CDB_GROUP0, stat_size, st_recov_sz, 0, func,
8666 		    (caddr_t)un);
8667 		if (pkt == NULL) {
8668 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8669 			    "Read Write scsi_init_pkt() failure\n");
8670 			goto exit;
8671 		}
8672 		ASSERT(pkt->pkt_resid == 0);
8673 #ifdef STDEBUG
8674 		bzero(pkt->pkt_private, st_recov_sz);
8675 		bzero(pkt->pkt_scbp, stat_size);
8676 #endif
8677 		ri = (recov_info *)pkt->pkt_private;
8678 		ri->privatelen = st_recov_sz;
8679 		if (un->un_bsize == 0) {
8680 			count = bp->b_bcount;
8681 			fixbit = 0;
8682 		} else {
8683 			count = bp->b_bcount / un->un_bsize;
8684 			fixbit = 1;
8685 		}
8686 		if (bp->b_flags & B_READ) {
8687 			com = SCMD_READ;
8688 			un->un_lastop = ST_OP_READ;
8689 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8690 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8691 				fixbit = 2;
8692 			}
8693 		} else {
8694 			com = SCMD_WRITE;
8695 			un->un_lastop = ST_OP_WRITE;
8696 		}
8697 		tval = un->un_dp->io_timeout;
8698 
8699 		/*
8700 		 * For really large xfers, increase timeout
8701 		 */
8702 		if (bp->b_bcount > (10 * ONE_MEG))
8703 			tval *= bp->b_bcount/(10 * ONE_MEG);
8704 
8705 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8706 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8707 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8708 
8709 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8710 		/*
8711 		 * uscsi - build command, allocate scsi resources
8712 		 */
8713 		st_make_uscsi_cmd(un, ucmd, bp, func);
8714 		goto exit;
8715 
8716 	} else {				/* special I/O */
8717 		struct buf *allocbp = NULL;
8718 		com = (uchar_t)(uintptr_t)bp->b_forw;
8719 		count = bp->b_bcount;
8720 
8721 		switch (com) {
8722 		case SCMD_READ:
8723 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8724 			    "special read %"PRId64"\n", count);
8725 			if (un->un_bsize == 0) {
8726 				fixbit = 2;	/* suppress SILI */
8727 			} else {
8728 				fixbit = 1;	/* Fixed Block Mode */
8729 				count /= un->un_bsize;
8730 			}
8731 			allocbp = bp;
8732 			un->un_lastop = ST_OP_READ;
8733 			tval = un->un_dp->io_timeout;
8734 			break;
8735 
8736 		case SCMD_WRITE:
8737 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8738 			    "special write %"PRId64"\n", count);
8739 			if (un->un_bsize != 0) {
8740 				fixbit = 1;	/* Fixed Block Mode */
8741 				count /= un->un_bsize;
8742 			} else {
8743 				fixbit = 0;
8744 			}
8745 			allocbp = bp;
8746 			un->un_lastop = ST_OP_WRITE;
8747 			tval = un->un_dp->io_timeout;
8748 			break;
8749 
8750 		case SCMD_WRITE_FILE_MARK:
8751 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8752 			    "write %"PRId64" file marks\n", count);
8753 			un->un_lastop = ST_OP_WEOF;
8754 			fixbit = 0;
8755 			tval = un->un_dp->io_timeout;
8756 			/*
8757 			 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8758 			 * device, set the Vendor Unique bit to
8759 			 * write Short File Mark.
8760 			 */
8761 			if ((un->un_dp->options & ST_SHORT_FILEMARKS) &&
8762 			    ((un->un_dp->type == ST_TYPE_EXB8500) ||
8763 			    (un->un_dp->type == ST_TYPE_EXABYTE))) {
8764 				/*
8765 				 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8766 				 * is set to to write Short File Mark
8767 				 */
8768 				short_fm = 1;
8769 			}
8770 			break;
8771 
8772 		case SCMD_REWIND:
8773 			/*
8774 			 * In the case of rewind we're gona do the rewind with
8775 			 * the immediate bit set so status will be retured when
8776 			 * the command is accepted by the device. We clear the
8777 			 * B_ASYNC flag so we wait for that acceptance.
8778 			 */
8779 			fixbit = 0;
8780 			if (bp->b_flags & B_ASYNC) {
8781 				allocbp = bp;
8782 				if (count) {
8783 					fixbit = 1;
8784 					bp->b_flags &= ~B_ASYNC;
8785 				}
8786 			}
8787 			count = 0;
8788 			bp->b_bcount = 0;
8789 			un->un_lastop = ST_OP_CTL;
8790 			tval = un->un_dp->rewind_timeout;
8791 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8792 			    "rewind\n");
8793 			break;
8794 
8795 		case SCMD_SPACE_G4:
8796 			cdb_len = CDB_GROUP4;
8797 			fixbit = SPACE_TYPE(bp->b_bcount);
8798 			count = SPACE_CNT(bp->b_bcount);
8799 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8800 			    " %s space %s %"PRId64" from file %d blk %d\n",
8801 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8802 			    space_strs[fixbit & 7], count,
8803 			    un->un_pos.fileno, un->un_pos.blkno);
8804 			address = (count >> 48) & 0x1fff;
8805 			additional = (count >> 16) & 0xffffffff;
8806 			count &= 0xffff;
8807 			count <<= 16;
8808 			un->un_lastop = ST_OP_CTL;
8809 			tval = un->un_dp->space_timeout;
8810 			break;
8811 
8812 		case SCMD_SPACE:
8813 			fixbit = SPACE_TYPE(bp->b_bcount);
8814 			count = SPACE_CNT(bp->b_bcount);
8815 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8816 			    " %s space %s %"PRId64" from file %d blk %d\n",
8817 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8818 			    space_strs[fixbit & 7], count,
8819 			    un->un_pos.fileno, un->un_pos.blkno);
8820 			count &= 0xffffffff;
8821 			un->un_lastop = ST_OP_CTL;
8822 			tval = un->un_dp->space_timeout;
8823 			break;
8824 
8825 		case SCMD_LOAD:
8826 			ASSERT(count < 10);
8827 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8828 			    "%s tape\n", load_strs[count]);
8829 			fixbit = 0;
8830 
8831 			/* Loading or Unloading */
8832 			if (count & LD_LOAD) {
8833 				tval = un->un_dp->load_timeout;
8834 			} else {
8835 				tval = un->un_dp->unload_timeout;
8836 			}
8837 			/* Is Retension requested */
8838 			if (count & LD_RETEN) {
8839 				tval += un->un_dp->rewind_timeout;
8840 			}
8841 			un->un_lastop = ST_OP_CTL;
8842 			break;
8843 
8844 		case SCMD_ERASE:
8845 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8846 			    "erase tape\n");
8847 			ASSERT(count == 1); /* mt sets this */
8848 			if (count == 1) {
8849 				/*
8850 				 * do long erase
8851 				 */
8852 				fixbit = 1; /* Long */
8853 
8854 				/* Drive might not honor immidiate bit */
8855 				tval = un->un_dp->erase_timeout;
8856 			} else {
8857 				/* Short Erase */
8858 				tval = un->un_dp->erase_timeout;
8859 				fixbit = 0;
8860 			}
8861 			un->un_lastop = ST_OP_CTL;
8862 			count = 0;
8863 			break;
8864 
8865 		case SCMD_MODE_SENSE:
8866 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8867 			    "mode sense\n");
8868 			allocbp = bp;
8869 			fixbit = 0;
8870 			tval = un->un_dp->non_motion_timeout;
8871 			un->un_lastop = ST_OP_CTL;
8872 			break;
8873 
8874 		case SCMD_MODE_SELECT:
8875 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8876 			    "mode select\n");
8877 			allocbp = bp;
8878 			fixbit = 0;
8879 			tval = un->un_dp->non_motion_timeout;
8880 			un->un_lastop = ST_OP_CTL;
8881 			break;
8882 
8883 		case SCMD_RESERVE:
8884 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8885 			    "reserve\n");
8886 			fixbit = 0;
8887 			tval = un->un_dp->non_motion_timeout;
8888 			un->un_lastop = ST_OP_CTL;
8889 			break;
8890 
8891 		case SCMD_RELEASE:
8892 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8893 			    "release\n");
8894 			fixbit = 0;
8895 			tval = un->un_dp->non_motion_timeout;
8896 			un->un_lastop = ST_OP_CTL;
8897 			break;
8898 
8899 		case SCMD_READ_BLKLIM:
8900 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8901 			    "read block limits\n");
8902 			allocbp = bp;
8903 			fixbit = count = 0;
8904 			tval = un->un_dp->non_motion_timeout;
8905 			un->un_lastop = ST_OP_CTL;
8906 			break;
8907 
8908 		case SCMD_TEST_UNIT_READY:
8909 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8910 			    "test unit ready\n");
8911 			fixbit = 0;
8912 			tval = un->un_dp->non_motion_timeout;
8913 			un->un_lastop = ST_OP_CTL;
8914 			break;
8915 
8916 		case SCMD_DOORLOCK:
8917 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8918 			    "prevent/allow media removal\n");
8919 			fixbit = 0;
8920 			tval = un->un_dp->non_motion_timeout;
8921 			un->un_lastop = ST_OP_CTL;
8922 			break;
8923 
8924 		case SCMD_READ_POSITION:
8925 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8926 			    "read position\n");
8927 			fixbit = un->un_read_pos_type;
8928 			cdb_len = CDB_GROUP1;
8929 			tval = un->un_dp->non_motion_timeout;
8930 			allocbp = bp;
8931 			un->un_lastop = ST_OP_CTL;
8932 			switch (un->un_read_pos_type) {
8933 			case LONG_POS:
8934 				count = 0;
8935 				break;
8936 			case EXT_POS:
8937 				count = sizeof (tape_position_ext_t);
8938 				break;
8939 			case SHORT_POS:
8940 				count = 0;
8941 				break;
8942 			default:
8943 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8944 				    "Unknown read position type 0x%x in "
8945 				    " st_make_cmd()\n", un->un_read_pos_type);
8946 			}
8947 			break;
8948 
8949 		default:
8950 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8951 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8952 			    com);
8953 		}
8954 
8955 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8956 		    st_recov_sz, 0, func, (caddr_t)un);
8957 		if (pkt == NULL) {
8958 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8959 			    "generic command scsi_init_pkt() failure\n");
8960 			goto exit;
8961 		}
8962 
8963 		ASSERT(pkt->pkt_resid == 0);
8964 #ifdef STDEBUG
8965 		bzero(pkt->pkt_private, st_recov_sz);
8966 		bzero(pkt->pkt_scbp, stat_size);
8967 #endif
8968 		ri = (recov_info *)pkt->pkt_private;
8969 		ri->privatelen = st_recov_sz;
8970 		if (allocbp) {
8971 			ASSERT(geterror(allocbp) == 0);
8972 		}
8973 
8974 	}
8975 
8976 	ucdb = (union scsi_cdb *)pkt->pkt_cdbp;
8977 
8978 	(void) scsi_setup_cdb(ucdb, com, address, (uint_t)count, additional);
8979 	FILL_SCSI1_LUN(un->un_sd, pkt);
8980 	/*
8981 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8982 	 */
8983 	ucdb->t_code = fixbit;
8984 	ucdb->g0_vu_1 = short_fm;
8985 	pkt->pkt_flags = flags;
8986 
8987 	ASSERT(tval);
8988 	pkt->pkt_time = tval;
8989 	if (bp == un->un_recov_buf) {
8990 		pkt->pkt_comp = st_recov_cb;
8991 	} else {
8992 		pkt->pkt_comp = st_intr;
8993 	}
8994 
8995 	st_add_recovery_info_to_pkt(un, bp, pkt);
8996 
8997 	/*
8998 	 * If we just write data to tape and did a command that doesn't
8999 	 * change position, we still need to write a filemark.
9000 	 */
9001 	if ((prev_op == ST_OP_WRITE) || (prev_op == ST_OP_WEOF)) {
9002 		recov_info *rcvi = pkt->pkt_private;
9003 		cmd_attribute const *atrib;
9004 
9005 		if (rcvi->privatelen == sizeof (recov_info)) {
9006 			atrib = rcvi->cmd_attrib;
9007 		} else {
9008 			atrib = st_lookup_cmd_attribute(com);
9009 		}
9010 		if (atrib->chg_tape_direction == DIR_NONE) {
9011 			un->un_lastop = prev_op;
9012 		}
9013 	}
9014 
9015 exit:
9016 	ASSERT(mutex_owned(ST_MUTEX));
9017 }
9018 
9019 
9020 /*
9021  * Build a command based on a uscsi command;
9022  */
9023 static void
9024 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
9025     struct buf *bp, int (*func)(caddr_t))
9026 {
9027 	struct scsi_pkt *pkt;
9028 	recov_info *ri;
9029 	caddr_t cdb;
9030 	int	cdblen;
9031 	int	stat_size = 1;
9032 	int	flags = 0;
9033 
9034 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
9035 
9036 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9037 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
9038 
9039 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
9040 		if (un->un_arq_enabled) {
9041 			if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
9042 				stat_size = (int)(ucmd->uscsi_rqlen) +
9043 				    sizeof (struct scsi_arq_status) -
9044 				    sizeof (struct scsi_extended_sense);
9045 				flags = PKT_XARQ;
9046 			} else {
9047 				stat_size = sizeof (struct scsi_arq_status);
9048 			}
9049 		}
9050 	}
9051 
9052 	ASSERT(mutex_owned(ST_MUTEX));
9053 
9054 	cdb = ucmd->uscsi_cdb;
9055 	cdblen = ucmd->uscsi_cdblen;
9056 
9057 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9058 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
9059 	    ucmd->uscsi_buflen, bp->b_bcount);
9060 	pkt = scsi_init_pkt(ROUTE, NULL,
9061 	    (bp->b_bcount > 0) ? bp : NULL,
9062 	    cdblen, stat_size, st_recov_sz, flags, func, (caddr_t)un);
9063 	if (pkt == NULL) {
9064 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
9065 		    "uscsi command scsi_init_pkt() failure\n");
9066 		goto exit;
9067 	}
9068 
9069 	ASSERT(pkt->pkt_resid == 0);
9070 #ifdef STDEBUG
9071 	bzero(pkt->pkt_private, st_recov_sz);
9072 	bzero(pkt->pkt_scbp, stat_size);
9073 #endif
9074 	ri = (recov_info *)pkt->pkt_private;
9075 	ri->privatelen = st_recov_sz;
9076 
9077 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
9078 
9079 #ifdef STDEBUG
9080 	if ((st_debug & 0x7) >= 6) {
9081 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
9082 		    "pkt_cdbp", (char *)cdb, cdblen);
9083 	}
9084 #endif
9085 
9086 	if (ucmd->uscsi_flags & USCSI_SILENT) {
9087 		pkt->pkt_flags |= FLAG_SILENT;
9088 	}
9089 
9090 	(void) scsi_uscsi_pktinit(ucmd, pkt);
9091 
9092 	pkt->pkt_time = ucmd->uscsi_timeout;
9093 	if (bp == un->un_recov_buf) {
9094 		pkt->pkt_comp = st_recov_cb;
9095 	} else {
9096 		pkt->pkt_comp = st_intr;
9097 	}
9098 
9099 	st_add_recovery_info_to_pkt(un, bp, pkt);
9100 exit:
9101 	ASSERT(mutex_owned(ST_MUTEX));
9102 }
9103 
9104 
9105 /*
9106  * restart cmd currently at the head of the runq
9107  *
9108  * If scsi_transport() succeeds or the retries
9109  * count exhausted, restore the throttle that was
9110  * zeroed out in st_handle_intr_busy().
9111  *
9112  */
9113 static void
9114 st_intr_restart(void *arg)
9115 {
9116 	struct scsi_tape *un = arg;
9117 	struct buf *bp;
9118 	int queued;
9119 	int status = TRAN_ACCEPT;
9120 
9121 	mutex_enter(ST_MUTEX);
9122 
9123 	ST_FUNC(ST_DEVINFO, st_intr_restart);
9124 
9125 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9126 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
9127 
9128 	un->un_hib_tid = 0;
9129 
9130 	if (un->un_recov_buf_busy != 0) {
9131 		bp = un->un_recov_buf;
9132 		queued = 0;
9133 	} else if (un->un_sbuf_busy != 0) {
9134 		bp = un->un_sbufp;
9135 		queued = 0;
9136 	} else if (un->un_quef != NULL) {
9137 		bp = un->un_quef;
9138 		queued = 1;
9139 	} else {
9140 		mutex_exit(ST_MUTEX);
9141 		return;
9142 	}
9143 
9144 	/*
9145 	 * Here we know :
9146 	 *	throttle = 0, via st_handle_intr_busy
9147 	 */
9148 
9149 	if (queued) {
9150 		/*
9151 		 * move from waitq to runq, if there is anything on the waitq
9152 		 */
9153 		(void) st_remove_from_queue(&un->un_quef, &un->un_quef, bp);
9154 
9155 		if (un->un_runqf) {
9156 			/*
9157 			 * not good, we don't want to requeue something after
9158 			 * another.
9159 			 */
9160 			goto done_error;
9161 		} else {
9162 			un->un_runqf = bp;
9163 			un->un_runql = bp;
9164 		}
9165 	}
9166 
9167 	ST_CDB(ST_DEVINFO, "Interrupt restart CDB",
9168 	    (char *)BP_PKT(bp)->pkt_cdbp);
9169 
9170 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
9171 
9172 	status = st_transport(un, BP_PKT(bp));
9173 
9174 	if (status != TRAN_ACCEPT) {
9175 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9176 
9177 		if (status == TRAN_BUSY) {
9178 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
9179 
9180 			if (pkti->privatelen == sizeof (recov_info) &&
9181 			    un->un_unit_attention_flags &&
9182 			    bp != un->un_recov_buf) {
9183 			un->un_unit_attention_flags = 0;
9184 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9185 				    "Command Recovery called on busy resend\n");
9186 				if (st_command_recovery(un, BP_PKT(bp),
9187 				    ATTEMPT_RETRY) == JUST_RETURN) {
9188 					mutex_exit(ST_MUTEX);
9189 					return;
9190 				}
9191 			}
9192 			mutex_exit(ST_MUTEX);
9193 			if (st_handle_intr_busy(un, bp,
9194 			    ST_TRAN_BUSY_TIMEOUT) == 0)
9195 				return;	/* timeout is setup again */
9196 			mutex_enter(ST_MUTEX);
9197 		}
9198 
9199 done_error:
9200 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9201 		    "restart transport rejected\n");
9202 		bp->b_resid = bp->b_bcount;
9203 
9204 		if (un->un_last_throttle) {
9205 			un->un_throttle = un->un_last_throttle;
9206 		}
9207 		if (status != TRAN_ACCEPT) {
9208 			ST_DO_ERRSTATS(un, st_transerrs);
9209 		}
9210 		ST_DO_KSTATS(bp, kstat_waitq_exit);
9211 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9212 		    "busy restart aborted\n");
9213 		st_set_pe_flag(un);
9214 		st_bioerror(bp, EIO);
9215 		st_done_and_mutex_exit(un, bp);
9216 	} else {
9217 		if (un->un_last_throttle) {
9218 			un->un_throttle = un->un_last_throttle;
9219 		}
9220 		mutex_exit(ST_MUTEX);
9221 	}
9222 }
9223 
9224 /*
9225  * st_check_media():
9226  * Periodically check the media state using scsi_watch service;
9227  * this service calls back after TUR and possibly request sense
9228  * the callback handler (st_media_watch_cb()) decodes the request sense
9229  * data (if any)
9230  */
9231 
9232 static int
9233 st_check_media(dev_t dev, enum mtio_state state)
9234 {
9235 	int rval = 0;
9236 	enum mtio_state	prev_state;
9237 	opaque_t token = NULL;
9238 
9239 	GET_SOFT_STATE(dev);
9240 
9241 	ST_FUNC(ST_DEVINFO, st_check_media);
9242 
9243 	mutex_enter(ST_MUTEX);
9244 
9245 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9246 	    "st_check_media:state=%x, mediastate=%x\n",
9247 	    state, un->un_mediastate);
9248 
9249 	prev_state = un->un_mediastate;
9250 
9251 	/*
9252 	 * is there anything to do?
9253 	 */
9254 retry:
9255 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
9256 		/*
9257 		 * submit the request to the scsi_watch service;
9258 		 * scsi_media_watch_cb() does the real work
9259 		 */
9260 		mutex_exit(ST_MUTEX);
9261 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
9262 		    st_check_media_time, SENSE_LENGTH,
9263 		    st_media_watch_cb, (caddr_t)dev);
9264 		if (token == NULL) {
9265 			rval = EAGAIN;
9266 			goto done;
9267 		}
9268 		mutex_enter(ST_MUTEX);
9269 
9270 		un->un_swr_token = token;
9271 		un->un_specified_mediastate = state;
9272 
9273 		/*
9274 		 * now wait for media change
9275 		 * we will not be signalled unless mediastate == state but it
9276 		 * still better to test for this condition, since there
9277 		 * is a 5 sec cv_broadcast delay when
9278 		 *  mediastate == MTIO_INSERTED
9279 		 */
9280 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9281 		    "st_check_media:waiting for media state change\n");
9282 		while (un->un_mediastate == state) {
9283 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
9284 				mutex_exit(ST_MUTEX);
9285 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9286 				    "st_check_media:waiting for media state "
9287 				    "was interrupted\n");
9288 				rval = EINTR;
9289 				goto done;
9290 			}
9291 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9292 			    "st_check_media:received signal, state=%x\n",
9293 			    un->un_mediastate);
9294 		}
9295 	}
9296 
9297 	/*
9298 	 * if we transitioned to MTIO_INSERTED, media has really been
9299 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
9300 	 * Reset and retry the state change.  If everything is ok, replay
9301 	 * the open() logic.
9302 	 */
9303 	if ((un->un_mediastate == MTIO_INSERTED) &&
9304 	    (un->un_state == ST_STATE_OFFLINE)) {
9305 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9306 		    "st_check_media: calling st_cmd to confirm inserted\n");
9307 
9308 		/*
9309 		 * set this early so that TUR will make it through strategy
9310 		 * without triggering a st_tape_init().  We needed it set
9311 		 * before calling st_tape_init() ourselves anyway.  If TUR
9312 		 * fails, set it back
9313 		 */
9314 		un->un_state = ST_STATE_INITIALIZING;
9315 
9316 		/*
9317 		 * If not reserved fail as getting reservation conflict
9318 		 * will make this hang forever.
9319 		 */
9320 		if ((un->un_rsvd_status &
9321 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9322 			mutex_exit(ST_MUTEX);
9323 			rval = EACCES;
9324 			goto done;
9325 		}
9326 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
9327 		if (rval == EACCES) {
9328 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9329 			    "st_check_media: TUR got Reservation Conflict\n");
9330 			mutex_exit(ST_MUTEX);
9331 			goto done;
9332 		}
9333 		if (rval) {
9334 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9335 			    "st_check_media: TUR failed, going to retry\n");
9336 			un->un_mediastate = prev_state;
9337 			un->un_state = ST_STATE_OFFLINE;
9338 			goto retry;
9339 		}
9340 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9341 		    "st_check_media: media inserted\n");
9342 
9343 		/* this also rewinds the tape */
9344 		rval = st_tape_init(un);
9345 		if (rval != 0) {
9346 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9347 			    "st_check_media : OFFLINE init failure ");
9348 			un->un_state = ST_STATE_OFFLINE;
9349 			un->un_pos.pmode = invalid;
9350 		} else {
9351 			un->un_state = ST_STATE_OPEN_PENDING_IO;
9352 		}
9353 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
9354 	    (un->un_state != ST_STATE_OFFLINE)) {
9355 		/*
9356 		 * supported devices must be rewound before ejection
9357 		 * rewind resets fileno & blkno
9358 		 */
9359 		un->un_laststate = un->un_state;
9360 		un->un_state = ST_STATE_OFFLINE;
9361 	}
9362 	mutex_exit(ST_MUTEX);
9363 done:
9364 	if (token) {
9365 		(void) scsi_watch_request_terminate(token,
9366 		    SCSI_WATCH_TERMINATE_WAIT);
9367 		mutex_enter(ST_MUTEX);
9368 		un->un_swr_token = (opaque_t)NULL;
9369 		mutex_exit(ST_MUTEX);
9370 	}
9371 
9372 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
9373 
9374 	return (rval);
9375 }
9376 
9377 /*
9378  * st_media_watch_cb() is called by scsi_watch_thread for
9379  * verifying the request sense data (if any)
9380  */
9381 static int
9382 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
9383 {
9384 	struct scsi_status *statusp = resultp->statusp;
9385 	struct scsi_extended_sense *sensep = resultp->sensep;
9386 	uchar_t actual_sense_length = resultp->actual_sense_length;
9387 	struct scsi_tape *un;
9388 	enum mtio_state state = MTIO_NONE;
9389 	int instance;
9390 	dev_t dev = (dev_t)arg;
9391 
9392 	instance = MTUNIT(dev);
9393 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
9394 		return (-1);
9395 	}
9396 
9397 	mutex_enter(ST_MUTEX);
9398 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
9399 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9400 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
9401 	    *((char *)statusp), (void *)sensep,
9402 	    actual_sense_length);
9403 
9404 
9405 	/*
9406 	 * if there was a check condition then sensep points to valid
9407 	 * sense data
9408 	 * if status was not a check condition but a reservation or busy
9409 	 * status then the new state is MTIO_NONE
9410 	 */
9411 	if (sensep) {
9412 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9413 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
9414 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
9415 
9416 		switch (un->un_dp->type) {
9417 		default:
9418 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9419 			    "st_media_watch_cb: unknown drive type %d, "
9420 			    "default to ST_TYPE_HP\n", un->un_dp->type);
9421 		/* FALLTHROUGH */
9422 
9423 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
9424 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
9425 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
9426 			if (un->un_dp->type == ST_TYPE_FUJI) {
9427 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9428 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
9429 			} else {
9430 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9431 				    "st_media_watch_cb: ST_TYPE_HP\n");
9432 			}
9433 			switch (sensep->es_key) {
9434 			case KEY_UNIT_ATTENTION:
9435 				/* not ready to ready transition */
9436 				/* hp/es_qual_code == 80 on>off>on */
9437 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
9438 				if (sensep->es_add_code == 0x28) {
9439 					state = MTIO_INSERTED;
9440 				}
9441 				break;
9442 			case KEY_NOT_READY:
9443 				/* in process, rewinding or loading */
9444 				if ((sensep->es_add_code == 0x04) &&
9445 				    (sensep->es_qual_code == 0x00)) {
9446 					state = MTIO_EJECTED;
9447 				}
9448 				break;
9449 			}
9450 			break;
9451 
9452 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
9453 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9454 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
9455 			switch (sensep->es_key) {
9456 			case KEY_UNIT_ATTENTION:
9457 				/* operator medium removal request */
9458 				if ((sensep->es_add_code == 0x5a) &&
9459 				    (sensep->es_qual_code == 0x01)) {
9460 					state = MTIO_EJECTED;
9461 				/* not ready to ready transition */
9462 				} else if ((sensep->es_add_code == 0x28) &&
9463 				    (sensep->es_qual_code == 0x00)) {
9464 					state = MTIO_INSERTED;
9465 				}
9466 				break;
9467 			case KEY_NOT_READY:
9468 				/* medium not present */
9469 				if (sensep->es_add_code == 0x3a) {
9470 					state = MTIO_EJECTED;
9471 				}
9472 				break;
9473 			}
9474 			break;
9475 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
9476 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9477 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
9478 			switch (sensep->es_key) {
9479 			case KEY_NOT_READY:
9480 				if ((sensep->es_add_code == 0x04) &&
9481 				    (sensep->es_qual_code == 0x00)) {
9482 					/* volume not mounted? */
9483 					state = MTIO_EJECTED;
9484 				} else if (sensep->es_add_code == 0x3a) {
9485 					state = MTIO_EJECTED;
9486 				}
9487 				break;
9488 			case KEY_UNIT_ATTENTION:
9489 				state = MTIO_EJECTED;
9490 				break;
9491 			}
9492 			break;
9493 
9494 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
9495 			switch (sensep->es_key) {
9496 			case KEY_UNIT_ATTENTION:
9497 				if (sensep->es_add_code == 0x28) {
9498 					state = MTIO_INSERTED;
9499 				}
9500 				break;
9501 			case KEY_NOT_READY:
9502 				if (sensep->es_add_code == 0x04) {
9503 					/* in transition but could be either */
9504 					state = un->un_specified_mediastate;
9505 				} else if ((sensep->es_add_code == 0x3a) &&
9506 				    (sensep->es_qual_code == 0x00)) {
9507 					state = MTIO_EJECTED;
9508 				}
9509 				break;
9510 			}
9511 			break;
9512 		}
9513 	} else if (*((char *)statusp) == STATUS_GOOD) {
9514 		state = MTIO_INSERTED;
9515 	}
9516 
9517 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9518 	    "st_media_watch_cb:state=%x, specified=%x\n",
9519 	    state, un->un_specified_mediastate);
9520 
9521 	/*
9522 	 * now signal the waiting thread if this is *not* the specified state;
9523 	 * delay the signal if the state is MTIO_INSERTED
9524 	 * to allow the target to recover
9525 	 */
9526 	if (state != un->un_specified_mediastate) {
9527 		un->un_mediastate = state;
9528 		if (state == MTIO_INSERTED) {
9529 			/*
9530 			 * delay the signal to give the drive a chance
9531 			 * to do what it apparently needs to do
9532 			 */
9533 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9534 			    "st_media_watch_cb:delayed cv_broadcast\n");
9535 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
9536 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
9537 		} else {
9538 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9539 			    "st_media_watch_cb:immediate cv_broadcast\n");
9540 			cv_broadcast(&un->un_state_cv);
9541 		}
9542 	}
9543 	mutex_exit(ST_MUTEX);
9544 	return (0);
9545 }
9546 
9547 /*
9548  * delayed cv_broadcast to allow for target to recover
9549  * from media insertion
9550  */
9551 static void
9552 st_delayed_cv_broadcast(void *arg)
9553 {
9554 	struct scsi_tape *un = arg;
9555 
9556 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
9557 
9558 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9559 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
9560 
9561 	mutex_enter(ST_MUTEX);
9562 	cv_broadcast(&un->un_state_cv);
9563 	mutex_exit(ST_MUTEX);
9564 }
9565 
9566 /*
9567  * restart cmd currently at the start of the waitq
9568  */
9569 static void
9570 st_start_restart(void *arg)
9571 {
9572 	struct scsi_tape *un = arg;
9573 
9574 	ST_FUNC(ST_DEVINFO, st_start_restart);
9575 
9576 	ASSERT(un != NULL);
9577 
9578 	mutex_enter(ST_MUTEX);
9579 
9580 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_tran_restart()\n");
9581 
9582 	st_start(un);
9583 
9584 	mutex_exit(ST_MUTEX);
9585 }
9586 
9587 
9588 /*
9589  * Command completion processing
9590  *
9591  */
9592 static void
9593 st_intr(struct scsi_pkt *pkt)
9594 {
9595 	recov_info *rcv = pkt->pkt_private;
9596 	struct buf *bp = rcv->cmd_bp;
9597 	struct scsi_tape *un;
9598 	errstate action = COMMAND_DONE;
9599 	clock_t	timout;
9600 	int	status;
9601 
9602 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
9603 
9604 	ST_FUNC(ST_DEVINFO, st_intr);
9605 
9606 	ASSERT(un != NULL);
9607 
9608 	mutex_enter(ST_MUTEX);
9609 
9610 	ASSERT(bp != un->un_recov_buf);
9611 
9612 	un->un_rqs_state &= ~(ST_RQS_ERROR);
9613 
9614 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
9615 
9616 	if (pkt->pkt_reason != CMD_CMPLT) {
9617 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9618 		    "Unhappy packet status reason = %s statistics = 0x%x\n",
9619 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9620 
9621 		/* If device has gone away not much else to do */
9622 		if (pkt->pkt_reason == CMD_DEV_GONE) {
9623 			action = COMMAND_DONE_ERROR;
9624 		} else if ((pkt == un->un_rqs) ||
9625 		    (un->un_state == ST_STATE_SENSING)) {
9626 			ASSERT(pkt == un->un_rqs);
9627 			ASSERT(un->un_state == ST_STATE_SENSING);
9628 			un->un_state = un->un_laststate;
9629 			rcv->cmd_bp = un->un_rqs_bp;
9630 			ST_DO_ERRSTATS(un, st_transerrs);
9631 			action = COMMAND_DONE_ERROR;
9632 		} else {
9633 			action = st_handle_incomplete(un, bp);
9634 		}
9635 	/*
9636 	 * At this point we know that the command was successfully
9637 	 * completed. Now what?
9638 	 */
9639 	} else if ((pkt == un->un_rqs) || (un->un_state == ST_STATE_SENSING)) {
9640 		/*
9641 		 * okay. We were running a REQUEST SENSE. Find
9642 		 * out what to do next.
9643 		 */
9644 		ASSERT(pkt == un->un_rqs);
9645 		ASSERT(un->un_state == ST_STATE_SENSING);
9646 		scsi_sync_pkt(pkt);
9647 		action = st_handle_sense(un, bp, &un->un_pos);
9648 		/*
9649 		 * Make rqs isn't going to be retied.
9650 		 */
9651 		if (action != QUE_BUSY_COMMAND && action != QUE_COMMAND) {
9652 			/*
9653 			 * set pkt back to original packet in case we will have
9654 			 * to requeue it
9655 			 */
9656 			pkt = BP_PKT(bp);
9657 			rcv->cmd_bp = un->un_rqs_bp;
9658 			/*
9659 			 * some actions are based on un_state, hence
9660 			 * restore the state st was in before ST_STATE_SENSING.
9661 			 */
9662 			un->un_state = un->un_laststate;
9663 		}
9664 
9665 	} else if (un->un_arq_enabled && (pkt->pkt_state & STATE_ARQ_DONE)) {
9666 		/*
9667 		 * the transport layer successfully completed an autorqsense
9668 		 */
9669 		action = st_handle_autosense(un, bp, &un->un_pos);
9670 
9671 	} else  if ((SCBP(pkt)->sts_busy) ||
9672 	    (SCBP(pkt)->sts_chk) ||
9673 	    (SCBP(pkt)->sts_vu7)) {
9674 		/*
9675 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9676 		 * to see if the status bits we're okay. If a request sense
9677 		 * is to be run, that will happen.
9678 		 */
9679 		action = st_check_error(un, pkt);
9680 	}
9681 
9682 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9683 		switch (action) {
9684 			case QUE_COMMAND:
9685 				/*
9686 				 * return cmd to head to the queue
9687 				 * since we are suspending so that
9688 				 * it gets restarted during resume
9689 				 */
9690 				st_add_to_queue(&un->un_runqf, &un->un_runql,
9691 				    un->un_runqf, bp);
9692 
9693 				action = JUST_RETURN;
9694 				break;
9695 
9696 			case QUE_SENSE:
9697 				action = COMMAND_DONE_ERROR;
9698 				break;
9699 
9700 			default:
9701 				break;
9702 		}
9703 	}
9704 
9705 	/*
9706 	 * check for undetected path failover.
9707 	 */
9708 	if (un->un_multipath) {
9709 
9710 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
9711 		int pkt_valid;
9712 
9713 		if (ucmd) {
9714 			/*
9715 			 * Also copies path instance to the uscsi structure.
9716 			 */
9717 			pkt_valid = scsi_uscsi_pktfini(pkt, ucmd);
9718 
9719 			/*
9720 			 * scsi_uscsi_pktfini() zeros pkt_path_instance.
9721 			 */
9722 			pkt->pkt_path_instance = ucmd->uscsi_path_instance;
9723 		} else {
9724 			pkt_valid = scsi_pkt_allocated_correctly(pkt);
9725 		}
9726 
9727 		/*
9728 		 * If the scsi_pkt was not allocated correctly the
9729 		 * pkt_path_instance is not even there.
9730 		 */
9731 		if ((pkt_valid != 0) &&
9732 		    (un->un_last_path_instance != pkt->pkt_path_instance)) {
9733 			if (un->un_state > ST_STATE_OPENING) {
9734 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
9735 				    "Failover detected, action is %s\n",
9736 				    errstatenames[action]);
9737 				if (action == COMMAND_DONE) {
9738 					action = PATH_FAILED;
9739 				}
9740 			}
9741 			un->un_last_path_instance = pkt->pkt_path_instance;
9742 		}
9743 	}
9744 
9745 	/*
9746 	 * Restore old state if we were sensing.
9747 	 */
9748 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9749 		un->un_state = un->un_laststate;
9750 	}
9751 
9752 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9753 	    "st_intr: pkt=%p, bp=%p, action=%s, status=%x\n",
9754 	    (void *)pkt, (void *)bp, errstatenames[action], SCBP_C(pkt));
9755 
9756 again:
9757 	switch (action) {
9758 	case COMMAND_DONE_EACCES:
9759 		/* this is to report a reservation conflict */
9760 		st_bioerror(bp, EACCES);
9761 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9762 		    "Reservation Conflict \n");
9763 		un->un_pos.pmode = invalid;
9764 
9765 		/*FALLTHROUGH*/
9766 	case COMMAND_DONE_ERROR:
9767 		if (un->un_pos.eof < ST_EOT_PENDING &&
9768 		    un->un_state >= ST_STATE_OPEN) {
9769 			/*
9770 			 * all errors set state of the tape to 'unknown'
9771 			 * unless we're at EOT or are doing append testing.
9772 			 * If sense key was illegal request, preserve state.
9773 			 */
9774 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9775 				un->un_pos.pmode = invalid;
9776 			}
9777 		}
9778 
9779 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9780 		/*
9781 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9782 		 * make sure an error ocurrs, so make sure at least EIO is
9783 		 * returned
9784 		 */
9785 		if (geterror(bp) == 0)
9786 			st_bioerror(bp, EIO);
9787 
9788 		st_set_pe_flag(un);
9789 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9790 		    (un->un_errno == EIO)) {
9791 			un->un_rqs_state &= ~(ST_RQS_VALID);
9792 		}
9793 		break;
9794 
9795 	case COMMAND_DONE_ERROR_RECOVERED:
9796 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9797 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9798 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9799 		if (geterror(bp) == 0) {
9800 			st_bioerror(bp, EIO);
9801 		}
9802 		st_set_pe_flag(un);
9803 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9804 		    (un->un_errno == EIO)) {
9805 			un->un_rqs_state &= ~(ST_RQS_VALID);
9806 		}
9807 		/*FALLTHROUGH*/
9808 	case COMMAND_DONE:
9809 		st_set_state(un, bp);
9810 		break;
9811 
9812 	case QUE_SENSE:
9813 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9814 			goto sense_error;
9815 
9816 		if (un->un_state != ST_STATE_SENSING) {
9817 			un->un_laststate = un->un_state;
9818 			un->un_state = ST_STATE_SENSING;
9819 		}
9820 
9821 		/*
9822 		 * zero the sense data.
9823 		 */
9824 		bzero(un->un_rqs->pkt_scbp, SENSE_LENGTH);
9825 
9826 		/*
9827 		 * If this is not a retry on QUE_SENSE point to the original
9828 		 * bp of the command that got us here.
9829 		 */
9830 		if (pkt != un->un_rqs) {
9831 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp = bp;
9832 		}
9833 
9834 		if (un->un_throttle) {
9835 			un->un_last_throttle = un->un_throttle;
9836 			un->un_throttle = 0;
9837 		}
9838 
9839 		ST_CDB(ST_DEVINFO, "Queue sense CDB",
9840 		    (char *)BP_PKT(bp)->pkt_cdbp);
9841 
9842 		/*
9843 		 * never retry this, some other command will have nuked the
9844 		 * sense, anyway
9845 		 */
9846 		status = st_transport(un, un->un_rqs);
9847 
9848 		if (un->un_last_throttle) {
9849 			un->un_throttle = un->un_last_throttle;
9850 		}
9851 
9852 		if (status == TRAN_ACCEPT) {
9853 			mutex_exit(ST_MUTEX);
9854 			return;
9855 		}
9856 		if (status != TRAN_BUSY)
9857 			ST_DO_ERRSTATS(un, st_transerrs);
9858 sense_error:
9859 		un->un_pos.pmode = invalid;
9860 		st_bioerror(bp, EIO);
9861 		st_set_pe_flag(un);
9862 		break;
9863 
9864 	case QUE_BUSY_COMMAND:
9865 		/* longish timeout */
9866 		timout = ST_STATUS_BUSY_TIMEOUT;
9867 		goto que_it_up;
9868 
9869 	case QUE_COMMAND:
9870 		/* short timeout */
9871 		timout = ST_TRAN_BUSY_TIMEOUT;
9872 que_it_up:
9873 		/*
9874 		 * let st_handle_intr_busy put this bp back on waitq and make
9875 		 * checks to see if it is ok to requeue the command.
9876 		 */
9877 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9878 
9879 		/*
9880 		 * Save the throttle before setting up the timeout
9881 		 */
9882 		if (un->un_throttle) {
9883 			un->un_last_throttle = un->un_throttle;
9884 		}
9885 		mutex_exit(ST_MUTEX);
9886 		if (st_handle_intr_busy(un, bp, timout) == 0)
9887 			return;		/* timeout is setup again */
9888 
9889 		mutex_enter(ST_MUTEX);
9890 		un->un_pos.pmode = invalid;
9891 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9892 		st_bioerror(bp, EIO);
9893 		st_set_pe_flag(un);
9894 		break;
9895 
9896 	case QUE_LAST_COMMAND:
9897 
9898 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9899 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9900 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9901 			goto last_command_error;
9902 		}
9903 		mutex_exit(ST_MUTEX);
9904 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9905 			return;
9906 		mutex_enter(ST_MUTEX);
9907 last_command_error:
9908 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9909 		un->un_pos.pmode = invalid;
9910 		st_bioerror(bp, EIO);
9911 		st_set_pe_flag(un);
9912 		break;
9913 
9914 	case COMMAND_TIMEOUT:
9915 	case DEVICE_RESET:
9916 	case DEVICE_TAMPER:
9917 	case ATTEMPT_RETRY:
9918 	case PATH_FAILED:
9919 		ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9920 		    "Command Recovery called on %s status\n",
9921 		    errstatenames[action]);
9922 		action = st_command_recovery(un, pkt, action);
9923 		goto again;
9924 
9925 	default:
9926 		ASSERT(0);
9927 		/* FALLTHRU */
9928 	case JUST_RETURN:
9929 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9930 		mutex_exit(ST_MUTEX);
9931 		return;
9932 	}
9933 
9934 	ST_DO_KSTATS(bp, kstat_runq_exit);
9935 	st_done_and_mutex_exit(un, bp);
9936 }
9937 
9938 static errstate
9939 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9940 {
9941 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9942 	recov_info *rinfo;
9943 	errstate rval = COMMAND_DONE_ERROR;
9944 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9945 	    un->un_rqs : BP_PKT(bp);
9946 	int result;
9947 
9948 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9949 
9950 	rinfo = (recov_info *)pkt->pkt_private;
9951 
9952 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9953 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9954 
9955 	ASSERT(mutex_owned(ST_MUTEX));
9956 
9957 	switch (pkt->pkt_reason) {
9958 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9959 		/*
9960 		 * this occurs when accessing a powered down drive, no
9961 		 * need to complain; just fail the open
9962 		 */
9963 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9964 
9965 		/*
9966 		 * if we have commands outstanding in HBA, and a command
9967 		 * comes back incomplete, we're hosed, so reset target
9968 		 * If we have the bus, but cmd_incomplete, we probably just
9969 		 * have a failed selection, so don't reset the target, just
9970 		 * requeue the command and try again
9971 		 */
9972 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9973 			goto reset_target;
9974 		}
9975 
9976 		/*
9977 		 * Retry selection a couple more times if we're
9978 		 * open.  If opening, we only try just once to
9979 		 * reduce probe time for nonexistant devices.
9980 		 */
9981 		if ((un->un_laststate > ST_STATE_OPENING) &&
9982 		    (rinfo->pkt_retry_cnt < st_selection_retry_count)) {
9983 			/* XXX check retriable? */
9984 			rval = QUE_COMMAND;
9985 		}
9986 		ST_DO_ERRSTATS(un, st_transerrs);
9987 		break;
9988 
9989 	case CMD_ABORTED:
9990 		/*
9991 		 * most likely this is caused by flush-on-error support. If
9992 		 * it was not there, the we're in trouble.
9993 		 */
9994 		if (!un->un_flush_on_errors) {
9995 			un->un_status = SUN_KEY_FATAL;
9996 			goto reset_target;
9997 		}
9998 
9999 		st_set_pe_errno(un);
10000 		bioerror(bp, un->un_errno);
10001 		if (un->un_errno)
10002 			return (COMMAND_DONE_ERROR);
10003 		else
10004 			return (COMMAND_DONE);
10005 
10006 	case CMD_TIMEOUT:	/* Command timed out */
10007 		un->un_status = SUN_KEY_TIMEOUT;
10008 		return (COMMAND_TIMEOUT);
10009 
10010 	case CMD_TRAN_ERR:
10011 	case CMD_RESET:
10012 		if (pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET)) {
10013 			if ((un->un_rsvd_status &
10014 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
10015 			    ST_RESERVE) {
10016 				un->un_rsvd_status |= ST_LOST_RESERVE;
10017 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
10018 				    "Lost Reservation\n");
10019 			}
10020 			rval = DEVICE_RESET;
10021 			return (rval);
10022 		}
10023 		if (pkt->pkt_statistics & (STAT_ABORTED | STAT_TERMINATED)) {
10024 			rval = DEVICE_RESET;
10025 			return (rval);
10026 		}
10027 		/*FALLTHROUGH*/
10028 	default:
10029 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10030 		    "Unhandled packet status reason = %s statistics = 0x%x\n",
10031 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
10032 reset_target:
10033 
10034 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10035 		    "transport completed with %s\n",
10036 		    scsi_rname(pkt->pkt_reason));
10037 		ST_DO_ERRSTATS(un, st_transerrs);
10038 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
10039 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
10040 		    STAT_ABORTED)) == 0)) {
10041 
10042 			/*
10043 			 * If we haven't reserved the drive don't reset it.
10044 			 */
10045 			if ((un->un_rsvd_status &
10046 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
10047 				return (rval);
10048 			}
10049 
10050 			/*
10051 			 * if we aren't lost yet we will be soon.
10052 			 */
10053 			un->un_pos.pmode = invalid;
10054 
10055 			result = st_reset(un, RESET_LUN);
10056 
10057 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
10058 				/* no hope left to recover */
10059 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
10060 				    "recovery by resets failed\n");
10061 				return (rval);
10062 			}
10063 		}
10064 	}
10065 
10066 
10067 	if (rinfo->pkt_retry_cnt++ < st_retry_count) {
10068 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
10069 			rval = QUE_COMMAND;
10070 		} else if (bp == un->un_sbufp) {
10071 			if (rinfo->privatelen == sizeof (recov_info)) {
10072 				if (rinfo->cmd_attrib->retriable) {
10073 					/*
10074 					 * These commands can be rerun
10075 					 * with impunity
10076 					 */
10077 					rval = QUE_COMMAND;
10078 				}
10079 			} else {
10080 				cmd_attribute const *attrib;
10081 				attrib =
10082 				    st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10083 				if (attrib->retriable) {
10084 					rval = QUE_COMMAND;
10085 				}
10086 			}
10087 		}
10088 	} else {
10089 		rval = COMMAND_DONE_ERROR;
10090 	}
10091 
10092 	if (un->un_state >= ST_STATE_OPEN) {
10093 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10094 		    fail, scsi_rname(pkt->pkt_reason),
10095 		    (rval == COMMAND_DONE_ERROR)?
10096 		    "giving up" : "retrying command");
10097 	}
10098 	return (rval);
10099 }
10100 
10101 /*
10102  * if the device is busy, then put this bp back on the waitq, on the
10103  * interrupt thread, where we want the head of the queue and not the
10104  * end
10105  *
10106  * The callers of this routine should take measures to save the
10107  * un_throttle in un_last_throttle which will be restored in
10108  * st_intr_restart(). The only exception should be st_intr_restart()
10109  * calling this routine for which the saving is already done.
10110  */
10111 static int
10112 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
10113 	clock_t timeout_interval)
10114 {
10115 
10116 	int queued;
10117 	int rval = 0;
10118 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
10119 
10120 	mutex_enter(ST_MUTEX);
10121 
10122 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
10123 
10124 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10125 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
10126 
10127 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
10128 		queued = 1;
10129 	} else {
10130 		queued = 0;
10131 	}
10132 
10133 	/*
10134 	 * Check to see if we hit the retry timeout. We check to make sure
10135 	 * this is the first one on the runq and make sure we have not
10136 	 * queued up any more, so this one has to be the last on the list
10137 	 * also. If it is not, we have to fail.  If it is not the first, but
10138 	 * is the last we are in trouble anyway, as we are in the interrupt
10139 	 * context here.
10140 	 */
10141 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
10142 	    ((un->un_runqf != bp) && (un->un_runql != bp) && (queued))) {
10143 		rval = -1;
10144 		goto exit;
10145 	}
10146 
10147 	/* put the bp back on the waitq */
10148 	if (queued) {
10149 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
10150 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
10151 	}
10152 
10153 	/*
10154 	 * We don't want any other commands being started in the mean time.
10155 	 * If start had just released mutex after putting something on the
10156 	 * runq, we won't even get here.
10157 	 */
10158 	un->un_throttle = 0;
10159 
10160 	/*
10161 	 * send a marker pkt, if appropriate
10162 	 */
10163 	st_hba_unflush(un);
10164 
10165 	/*
10166 	 * all queues are aligned, we are just waiting to
10167 	 * transport
10168 	 */
10169 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
10170 
10171 exit:
10172 	mutex_exit(ST_MUTEX);
10173 	return (rval);
10174 }
10175 
10176 /*
10177  * To get one error entry from error stack
10178  */
10179 static int
10180 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
10181 {
10182 #ifdef _MULTI_DATAMODEL
10183 	/*
10184 	 * For use when a 32 bit app makes a call into a
10185 	 * 64 bit ioctl
10186 	 */
10187 	struct mterror_entry32 err_entry32;
10188 #endif /* _MULTI_DATAMODEL */
10189 
10190 	int rval = 0;
10191 	struct mterror_entry err_entry;
10192 	struct mterror_entry_stack *err_link_entry_p;
10193 	size_t arq_status_len_in, arq_status_len_kr;
10194 
10195 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
10196 
10197 	ASSERT(mutex_owned(ST_MUTEX));
10198 
10199 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10200 	    "st_get_error_entry()\n");
10201 
10202 	/*
10203 	 * if error record stack empty, return ENXIO
10204 	 */
10205 	if (un->un_error_entry_stk == NULL) {
10206 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10207 		    "st_get_error_entry: Error Entry Stack Empty!\n");
10208 		rval = ENXIO;
10209 		goto ret;
10210 	}
10211 
10212 	/*
10213 	 * get the top entry from stack
10214 	 */
10215 	err_link_entry_p = un->un_error_entry_stk;
10216 	arq_status_len_kr =
10217 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
10218 
10219 #ifdef _MULTI_DATAMODEL
10220 	switch (ddi_model_convert_from(flag & FMODELS)) {
10221 	case DDI_MODEL_ILP32:
10222 		if (ddi_copyin((void *)arg, &err_entry32,
10223 		    MTERROR_ENTRY_SIZE_32, flag)) {
10224 			rval = EFAULT;
10225 			goto ret;
10226 		}
10227 
10228 		arq_status_len_in =
10229 		    (size_t)err_entry32.mtee_arq_status_len;
10230 
10231 		err_entry32.mtee_cdb_len =
10232 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
10233 
10234 		if (arq_status_len_in > arq_status_len_kr)
10235 			err_entry32.mtee_arq_status_len =
10236 			    (size32_t)arq_status_len_kr;
10237 
10238 		if (ddi_copyout(
10239 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10240 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
10241 		    err_entry32.mtee_cdb_len, flag)) {
10242 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10243 			    "st_get_error_entry: Copy cdb buffer error!");
10244 			rval = EFAULT;
10245 		}
10246 
10247 		if (ddi_copyout(
10248 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10249 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
10250 		    err_entry32.mtee_arq_status_len, flag)) {
10251 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10252 			    "st_get_error_entry: copy arq status error!");
10253 			rval = EFAULT;
10254 		}
10255 
10256 		if (ddi_copyout(&err_entry32, (void *)arg,
10257 		    MTERROR_ENTRY_SIZE_32, flag)) {
10258 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10259 			    "st_get_error_entry: copy arq status out error!");
10260 			rval = EFAULT;
10261 		}
10262 		break;
10263 
10264 	case DDI_MODEL_NONE:
10265 		if (ddi_copyin((void *)arg, &err_entry,
10266 		    MTERROR_ENTRY_SIZE_64, flag)) {
10267 			rval = EFAULT;
10268 			goto ret;
10269 		}
10270 		arq_status_len_in = err_entry.mtee_arq_status_len;
10271 
10272 		err_entry.mtee_cdb_len =
10273 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
10274 
10275 		if (arq_status_len_in > arq_status_len_kr)
10276 			err_entry.mtee_arq_status_len =
10277 			    arq_status_len_kr;
10278 
10279 		if (ddi_copyout(
10280 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10281 		    err_entry.mtee_cdb_buf,
10282 		    err_entry.mtee_cdb_len, flag)) {
10283 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10284 			    "st_get_error_entry: Copy cdb buffer error!");
10285 			rval = EFAULT;
10286 		}
10287 
10288 		if (ddi_copyout(
10289 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10290 		    err_entry.mtee_arq_status,
10291 		    err_entry.mtee_arq_status_len, flag)) {
10292 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10293 			    "st_get_error_entry: copy arq status error!");
10294 			rval = EFAULT;
10295 		}
10296 
10297 		if (ddi_copyout(&err_entry, (void *)arg,
10298 		    MTERROR_ENTRY_SIZE_64, flag)) {
10299 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10300 			    "st_get_error_entry: copy arq status out error!");
10301 			rval = EFAULT;
10302 		}
10303 		break;
10304 	}
10305 #else /* _MULTI_DATAMODEL */
10306 	if (ddi_copyin((void *)arg, &err_entry,
10307 	    MTERROR_ENTRY_SIZE_64, flag)) {
10308 		rval = EFAULT;
10309 		goto ret;
10310 	}
10311 	arq_status_len_in = err_entry.mtee_arq_status_len;
10312 
10313 	err_entry.mtee_cdb_len =
10314 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
10315 
10316 	if (arq_status_len_in > arq_status_len_kr)
10317 		err_entry.mtee_arq_status_len =
10318 		    arq_status_len_kr;
10319 
10320 	if (ddi_copyout(
10321 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10322 	    err_entry.mtee_cdb_buf,
10323 	    err_entry.mtee_cdb_len, flag)) {
10324 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10325 		    "st_get_error_entry: Copy cdb buffer error!");
10326 		rval = EFAULT;
10327 	}
10328 
10329 	if (ddi_copyout(
10330 	    err_link_entry_p->mtees_entry.mtee_arq_status,
10331 	    err_entry.mtee_arq_status,
10332 	    err_entry.mtee_arq_status_len, flag)) {
10333 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10334 		    "st_get_error_entry: copy arq status buffer error!");
10335 		rval = EFAULT;
10336 	}
10337 
10338 	if (ddi_copyout(&err_entry, (void *)arg,
10339 	    MTERROR_ENTRY_SIZE_64, flag)) {
10340 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10341 		    "st_get_error_entry: copy arq status out error!");
10342 		rval = EFAULT;
10343 	}
10344 #endif /* _MULTI_DATAMODEL */
10345 
10346 	/*
10347 	 * update stack
10348 	 */
10349 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
10350 
10351 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
10352 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
10353 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
10354 
10355 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
10356 	    SECMDS_STATUS_SIZE);
10357 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
10358 
10359 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
10360 	err_link_entry_p = NULL;
10361 ret:
10362 	return (rval);
10363 }
10364 
10365 /*
10366  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
10367  * the scsi CDB command which causes the error and generates sense data and
10368  * the scsi status.
10369  *
10370  *      error-record stack
10371  *
10372  *
10373  *             TOP                                     BOTTOM
10374  *              ------------------------------------------
10375  *              |   0   |   1   |   2   |   ...  |   n   |
10376  *              ------------------------------------------
10377  *                  ^
10378  *                  |
10379  *       pointer to error entry
10380  *
10381  * when st driver generates one sense data record, it creates a error-entry
10382  * and pushes it onto the stack.
10383  *
10384  */
10385 
10386 static void
10387 st_update_error_stack(struct scsi_tape *un,
10388 			struct scsi_pkt *pkt,
10389 			struct scsi_arq_status *cmd)
10390 {
10391 	struct mterror_entry_stack *err_entry_tmp;
10392 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
10393 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
10394 
10395 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
10396 
10397 	ASSERT(mutex_owned(ST_MUTEX));
10398 
10399 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10400 	    "st_update_error_stack()\n");
10401 
10402 	ASSERT(cmd);
10403 	ASSERT(cdbp);
10404 	if (cdblen == 0) {
10405 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10406 		    "st_update_error_stack: CDB length error!\n");
10407 		return;
10408 	}
10409 
10410 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
10411 	ASSERT(err_entry_tmp != NULL);
10412 
10413 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
10414 	    kmem_alloc(cdblen, KM_SLEEP);
10415 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
10416 
10417 	err_entry_tmp->mtees_entry.mtee_arq_status =
10418 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
10419 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
10420 
10421 	/*
10422 	 * copy cdb command & length to current error entry
10423 	 */
10424 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
10425 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
10426 
10427 	/*
10428 	 * copy scsi status length to current error entry
10429 	 */
10430 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
10431 	    SECMDS_STATUS_SIZE;
10432 
10433 	/*
10434 	 * copy sense data and scsi status to current error entry
10435 	 */
10436 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
10437 	    SECMDS_STATUS_SIZE);
10438 
10439 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
10440 	un->un_error_entry_stk = err_entry_tmp;
10441 
10442 }
10443 
10444 /*
10445  * Empty all the error entry in stack
10446  */
10447 static void
10448 st_empty_error_stack(struct scsi_tape *un)
10449 {
10450 	struct mterror_entry_stack *linkp;
10451 
10452 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
10453 
10454 	ASSERT(mutex_owned(ST_MUTEX));
10455 
10456 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10457 	    "st_empty_entry_stack()\n");
10458 
10459 	while (un->un_error_entry_stk != NULL) {
10460 		linkp = un->un_error_entry_stk;
10461 		un->un_error_entry_stk =
10462 		    un->un_error_entry_stk->mtees_nextp;
10463 
10464 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
10465 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
10466 			    linkp->mtees_entry.mtee_cdb_len);
10467 
10468 		if (linkp->mtees_entry.mtee_arq_status != NULL)
10469 			kmem_free(linkp->mtees_entry.mtee_arq_status,
10470 			    linkp->mtees_entry.mtee_arq_status_len);
10471 
10472 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
10473 		linkp = NULL;
10474 	}
10475 }
10476 
10477 static errstate
10478 st_handle_sense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10479 {
10480 	struct scsi_pkt *pkt = BP_PKT(bp);
10481 	struct scsi_pkt *rqpkt = un->un_rqs;
10482 	struct scsi_arq_status arqstat;
10483 	recov_info *rcif = pkt->pkt_private;
10484 
10485 	errstate rval = COMMAND_DONE_ERROR;
10486 	int amt;
10487 
10488 	ST_FUNC(ST_DEVINFO, st_handle_sense);
10489 
10490 	ASSERT(mutex_owned(ST_MUTEX));
10491 
10492 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10493 	    "st_handle_sense()\n");
10494 
10495 	if (SCBP(rqpkt)->sts_busy) {
10496 		if (rcif->privatelen == sizeof (recov_info)) {
10497 			ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
10498 			    "Attempt recovery of busy unit on request sense\n");
10499 			rval = ATTEMPT_RETRY;
10500 		} else if (rcif->pkt_retry_cnt++ < st_retry_count) {
10501 			ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10502 			    "Retry busy unit on request sense\n");
10503 			rval = QUE_BUSY_COMMAND;
10504 		}
10505 		return (rval);
10506 	} else if (SCBP(rqpkt)->sts_chk) {
10507 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10508 		    "Check Condition on REQUEST SENSE\n");
10509 		return (rval);
10510 	}
10511 
10512 	/*
10513 	 * Make sure there is sense data to look at.
10514 	 */
10515 	if ((rqpkt->pkt_state & (STATE_GOT_BUS | STATE_GOT_TARGET |
10516 	    STATE_SENT_CMD | STATE_GOT_STATUS)) != (STATE_GOT_BUS |
10517 	    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) {
10518 		return (rval);
10519 	}
10520 
10521 	/* was there enough data? */
10522 	amt = (int)MAX_SENSE_LENGTH - rqpkt->pkt_resid;
10523 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
10524 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10525 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10526 		    "REQUEST SENSE couldn't get sense data\n");
10527 		return (rval);
10528 	}
10529 
10530 	bcopy(SCBP(pkt), &arqstat.sts_status,
10531 	    sizeof (struct scsi_status));
10532 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
10533 	    sizeof (struct scsi_status));
10534 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
10535 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
10536 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
10537 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
10538 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
10539 
10540 	/*
10541 	 * copy one arqstat entry in the sense data buffer
10542 	 */
10543 	st_update_error_stack(un, pkt, &arqstat);
10544 	return (st_decode_sense(un, bp, amt, &arqstat, pos));
10545 }
10546 
10547 static errstate
10548 st_handle_autosense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10549 {
10550 	struct scsi_pkt *pkt = BP_PKT(bp);
10551 	struct scsi_arq_status *arqstat =
10552 	    (struct scsi_arq_status *)pkt->pkt_scbp;
10553 	errstate rval = COMMAND_DONE_ERROR;
10554 	int amt;
10555 
10556 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
10557 
10558 	ASSERT(mutex_owned(ST_MUTEX));
10559 
10560 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10561 	    "st_handle_autosense()\n");
10562 
10563 	if (arqstat->sts_rqpkt_status.sts_busy) {
10564 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10565 		    "busy unit on request sense\n");
10566 		/*
10567 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
10568 		 * the disadvantage is that we do not have any delay for the
10569 		 * second retry of rqsense and we have to keep a packet around
10570 		 */
10571 		return (QUE_SENSE);
10572 
10573 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
10574 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10575 		    "transport error on REQUEST SENSE\n");
10576 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
10577 		    ((arqstat->sts_rqpkt_statistics &
10578 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
10579 			if (st_reset(un, RESET_LUN) == 0) {
10580 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10581 				    "recovery by resets failed\n");
10582 			}
10583 		}
10584 		return (rval);
10585 
10586 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
10587 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10588 		    "Check Condition on REQUEST SENSE\n");
10589 		return (rval);
10590 	}
10591 
10592 
10593 	/* was there enough data? */
10594 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10595 		amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10596 	} else {
10597 		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
10598 			amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10599 		} else {
10600 			amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10601 		}
10602 	}
10603 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
10604 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10605 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10606 		    "REQUEST SENSE couldn't get sense data\n");
10607 		return (rval);
10608 	}
10609 
10610 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10611 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, MAX_SENSE_LENGTH);
10612 	} else {
10613 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
10614 	}
10615 
10616 	/*
10617 	 * copy one arqstat entry in the sense data buffer
10618 	 */
10619 	st_update_error_stack(un, pkt, arqstat);
10620 
10621 	return (st_decode_sense(un, bp, amt, arqstat, pos));
10622 }
10623 
10624 static errstate
10625 st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
10626     struct scsi_arq_status *statusp, tapepos_t *pos)
10627 {
10628 	struct scsi_pkt *pkt = BP_PKT(bp);
10629 	recov_info *ri = pkt->pkt_private;
10630 	errstate rval = COMMAND_DONE_ERROR;
10631 	cmd_attribute const *attrib;
10632 	long resid;
10633 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10634 	int severity;
10635 	int get_error;
10636 
10637 	ST_FUNC(ST_DEVINFO, st_decode_sense);
10638 
10639 	ASSERT(mutex_owned(ST_MUTEX));
10640 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10641 	    "st_decode_sense()\n");
10642 
10643 	/*
10644 	 * For uscsi commands, squirrel away a copy of the
10645 	 * results of the Request Sense.
10646 	 */
10647 	if (USCSI_CMD(bp)) {
10648 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
10649 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
10650 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
10651 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
10652 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
10653 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
10654 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10655 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
10656 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
10657 		}
10658 	}
10659 
10660 	if (ri->privatelen == sizeof (recov_info)) {
10661 		attrib = ri->cmd_attrib;
10662 	} else {
10663 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10664 	}
10665 
10666 	/*
10667 	 * If the drive is an MT-02, reposition the
10668 	 * secondary error code into the proper place.
10669 	 *
10670 	 * XXX	MT-02 is non-CCS tape, so secondary error code
10671 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
10672 	 * so it's in byte 12.
10673 	 */
10674 	if (un->un_dp->type == ST_TYPE_EMULEX) {
10675 		sensep->es_code = sensep->es_add_info[0];
10676 	}
10677 
10678 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
10679 	    (caddr_t)&CDBP(pkt)->scc_cmd);
10680 
10681 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)statusp,
10682 	    sizeof (*statusp));
10683 
10684 	/* for normal I/O check extract the resid values. */
10685 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
10686 		if (sensep->es_valid) {
10687 			resid =
10688 			    (sensep->es_info_1 << 24) |
10689 			    (sensep->es_info_2 << 16) |
10690 			    (sensep->es_info_3 << 8)  |
10691 			    (sensep->es_info_4);
10692 			/* If fixed block */
10693 			if (un->un_bsize) {
10694 				resid *= un->un_bsize;
10695 			}
10696 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
10697 			resid = pkt->pkt_resid;
10698 		} else {
10699 			resid = bp->b_bcount;
10700 		}
10701 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10702 		    "st_decode_sense (rw): xferred bit = %d, resid=%ld (%d), "
10703 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
10704 		    resid,
10705 		    (sensep->es_info_1 << 24) |
10706 		    (sensep->es_info_2 << 16) |
10707 		    (sensep->es_info_3 << 8)  |
10708 		    (sensep->es_info_4),
10709 		    pkt->pkt_resid);
10710 		/*
10711 		 * The problem is, what should we believe?
10712 		 */
10713 		if (resid && (pkt->pkt_resid == 0)) {
10714 			pkt->pkt_resid = resid;
10715 		}
10716 	} else {
10717 		/*
10718 		 * If the command is SCMD_SPACE, we need to get the
10719 		 * residual as returned in the sense data, to adjust
10720 		 * our idea of current tape position correctly
10721 		 */
10722 		if ((sensep->es_valid) &&
10723 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10724 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10725 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
10726 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE_G4) ||
10727 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK)) {
10728 			resid =
10729 			    (sensep->es_info_1 << 24) |
10730 			    (sensep->es_info_2 << 16) |
10731 			    (sensep->es_info_3 << 8)  |
10732 			    (sensep->es_info_4);
10733 			bp->b_resid = resid;
10734 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10735 			    "st_decode_sense(other):	resid=%ld\n", resid);
10736 		} else {
10737 			/*
10738 			 * If the special command is SCMD_READ,
10739 			 * the correct resid will be set later.
10740 			 */
10741 			if (attrib->get_cnt != NULL) {
10742 				resid = attrib->get_cnt(pkt->pkt_cdbp);
10743 			} else {
10744 				resid = bp->b_bcount;
10745 			}
10746 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10747 			    "st_decode_sense(special read):  resid=%ld\n",
10748 			    resid);
10749 		}
10750 	}
10751 
10752 	if ((un->un_state >= ST_STATE_OPEN) &&
10753 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
10754 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
10755 		    "Failed CDB", (char *)pkt->pkt_cdbp);
10756 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10757 		    "sense data", (char *)sensep, amt);
10758 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10759 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10760 		    bp->b_bcount, resid, pkt->pkt_resid);
10761 	}
10762 
10763 	switch (un->un_status = sensep->es_key) {
10764 	case KEY_NO_SENSE:
10765 		severity = SCSI_ERR_INFO;
10766 
10767 		/*
10768 		 * Erase, locate or rewind operation in progress, retry
10769 		 * ASC  ASCQ
10770 		 *  00   18    Erase operation in progress
10771 		 *  00   19    Locate operation in progress
10772 		 *  00   1A    Rewind operation in progress
10773 		 */
10774 		if (sensep->es_add_code == 0 &&
10775 		    ((sensep->es_qual_code == 0x18) ||
10776 		    (sensep->es_qual_code == 0x19) ||
10777 		    (sensep->es_qual_code == 0x1a))) {
10778 			rval = QUE_BUSY_COMMAND;
10779 			break;
10780 		}
10781 
10782 		goto common;
10783 
10784 	case KEY_RECOVERABLE_ERROR:
10785 		severity = SCSI_ERR_RECOVERED;
10786 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10787 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10788 			if (un->un_dp->options &
10789 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10790 				rval = QUE_LAST_COMMAND;
10791 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10792 				    severity, pos->lgclblkno,
10793 				    un->un_err_pos.lgclblkno, scsi_cmds,
10794 				    sensep);
10795 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10796 				    "Command will be retried\n");
10797 			} else {
10798 				severity = SCSI_ERR_FATAL;
10799 				rval = COMMAND_DONE_ERROR_RECOVERED;
10800 				ST_DO_ERRSTATS(un, st_softerrs);
10801 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10802 				    severity, pos->lgclblkno,
10803 				    un->un_err_pos.lgclblkno, scsi_cmds,
10804 				    sensep);
10805 			}
10806 			break;
10807 		}
10808 common:
10809 		/*
10810 		 * XXX only want reads to be stopped by filemarks.
10811 		 * Don't want them to be stopped by EOT.  EOT matters
10812 		 * only on write.
10813 		 */
10814 		if (sensep->es_filmk && !sensep->es_eom) {
10815 			rval = COMMAND_DONE;
10816 		} else if (sensep->es_eom) {
10817 			rval = COMMAND_DONE;
10818 		} else if (sensep->es_ili) {
10819 			/*
10820 			 * Fun with variable length record devices:
10821 			 * for specifying larger blocks sizes than the
10822 			 * actual physical record size.
10823 			 */
10824 			if (un->un_bsize == 0 && resid > 0) {
10825 				/*
10826 				 * XXX! Ugly.
10827 				 * The requested blocksize is > tape blocksize,
10828 				 * so this is ok, so we just return the
10829 				 * actual size xferred.
10830 				 */
10831 				pkt->pkt_resid = resid;
10832 				rval = COMMAND_DONE;
10833 			} else if (un->un_bsize == 0 && resid < 0) {
10834 				/*
10835 				 * The requested blocksize is < tape blocksize,
10836 				 * so this is not ok, so we err with ENOMEM
10837 				 */
10838 				rval = COMMAND_DONE_ERROR_RECOVERED;
10839 				st_bioerror(bp, ENOMEM);
10840 			} else {
10841 				ST_DO_ERRSTATS(un, st_softerrs);
10842 				severity = SCSI_ERR_FATAL;
10843 				rval = COMMAND_DONE_ERROR;
10844 				st_bioerror(bp, EINVAL);
10845 				un->un_running.pmode = invalid;
10846 			}
10847 		} else {
10848 			/*
10849 			 * we hope and pray for this just being
10850 			 * something we can ignore (ie. a
10851 			 * truly recoverable soft error)
10852 			 */
10853 			rval = COMMAND_DONE;
10854 		}
10855 		if (sensep->es_filmk) {
10856 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10857 			    "filemark\n");
10858 			un->un_status = SUN_KEY_EOF;
10859 			pos->eof = ST_EOF_PENDING;
10860 			st_set_pe_flag(un);
10861 		}
10862 
10863 		/*
10864 		 * ignore eom when reading, a fmk should terminate reading
10865 		 */
10866 		if ((sensep->es_eom) &&
10867 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10868 			if ((sensep->es_add_code == 0) &&
10869 			    (sensep->es_qual_code == 4)) {
10870 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10871 				    "bot\n");
10872 				un->un_status = SUN_KEY_BOT;
10873 				pos->eof = ST_NO_EOF;
10874 				pos->lgclblkno = 0;
10875 				pos->fileno = 0;
10876 				pos->blkno = 0;
10877 				if (pos->pmode != legacy)
10878 					pos->pmode = legacy;
10879 			} else {
10880 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10881 				    "eom\n");
10882 				un->un_status = SUN_KEY_EOT;
10883 				pos->eof = ST_EOM;
10884 			}
10885 			st_set_pe_flag(un);
10886 		}
10887 
10888 		break;
10889 
10890 	case KEY_ILLEGAL_REQUEST:
10891 
10892 		if (un->un_laststate >= ST_STATE_OPEN) {
10893 			ST_DO_ERRSTATS(un, st_softerrs);
10894 			severity = SCSI_ERR_FATAL;
10895 		} else {
10896 			severity = SCSI_ERR_INFO;
10897 		}
10898 		break;
10899 
10900 	case KEY_MEDIUM_ERROR:
10901 		ST_DO_ERRSTATS(un, st_harderrs);
10902 		severity = SCSI_ERR_FATAL;
10903 		un->un_pos.pmode = invalid;
10904 		un->un_running.pmode = invalid;
10905 check_keys:
10906 		/*
10907 		 * attempt to process the keys in the presence of
10908 		 * other errors
10909 		 */
10910 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10911 			/*
10912 			 * Fun with variable length record devices:
10913 			 * for specifying larger blocks sizes than the
10914 			 * actual physical record size.
10915 			 */
10916 			if (un->un_bsize == 0 && resid > 0) {
10917 				/*
10918 				 * XXX! Ugly
10919 				 */
10920 				pkt->pkt_resid = resid;
10921 			} else if (un->un_bsize == 0 && resid < 0) {
10922 				st_bioerror(bp, EINVAL);
10923 			} else {
10924 				severity = SCSI_ERR_FATAL;
10925 				rval = COMMAND_DONE_ERROR;
10926 				st_bioerror(bp, EINVAL);
10927 			}
10928 		}
10929 		if (sensep->es_filmk) {
10930 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10931 			    "filemark\n");
10932 			un->un_status = SUN_KEY_EOF;
10933 			pos->eof = ST_EOF_PENDING;
10934 			st_set_pe_flag(un);
10935 		}
10936 
10937 		/*
10938 		 * ignore eom when reading, a fmk should terminate reading
10939 		 */
10940 		if ((sensep->es_eom) &&
10941 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10942 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10943 			un->un_status = SUN_KEY_EOT;
10944 			pos->eof = ST_EOM;
10945 			st_set_pe_flag(un);
10946 		}
10947 
10948 		break;
10949 
10950 	case KEY_VOLUME_OVERFLOW:
10951 		ST_DO_ERRSTATS(un, st_softerrs);
10952 		pos->eof = ST_EOM;
10953 		severity = SCSI_ERR_FATAL;
10954 		rval = COMMAND_DONE_ERROR;
10955 		goto check_keys;
10956 
10957 	case KEY_HARDWARE_ERROR:
10958 		ST_DO_ERRSTATS(un, st_harderrs);
10959 		severity = SCSI_ERR_FATAL;
10960 		rval = COMMAND_DONE_ERROR;
10961 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10962 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10963 		break;
10964 
10965 	case KEY_BLANK_CHECK:
10966 		ST_DO_ERRSTATS(un, st_softerrs);
10967 		severity = SCSI_ERR_INFO;
10968 
10969 		/*
10970 		 * if not a special request and some data was xferred then it
10971 		 * it is not an error yet
10972 		 */
10973 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10974 			/*
10975 			 * no error for read with or without data xferred
10976 			 */
10977 			un->un_status = SUN_KEY_EOT;
10978 			pos->eof = ST_EOT;
10979 			rval = COMMAND_DONE_ERROR;
10980 			un->un_running.pmode = invalid;
10981 			st_set_pe_flag(un);
10982 			goto check_keys;
10983 		} else if (bp != un->un_sbufp &&
10984 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10985 			rval = COMMAND_DONE;
10986 		} else {
10987 			rval = COMMAND_DONE_ERROR_RECOVERED;
10988 		}
10989 
10990 		if (un->un_laststate >= ST_STATE_OPEN) {
10991 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10992 			    "blank check\n");
10993 			pos->eof = ST_EOM;
10994 		}
10995 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10996 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10997 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
10998 		    (un->un_dp->options & ST_KNOWS_EOD)) {
10999 			/*
11000 			 * we were doing a fast forward by skipping
11001 			 * multiple fmk at the time
11002 			 */
11003 			st_bioerror(bp, EIO);
11004 			severity = SCSI_ERR_RECOVERED;
11005 			rval	 = COMMAND_DONE;
11006 		}
11007 		st_set_pe_flag(un);
11008 		goto check_keys;
11009 
11010 	case KEY_WRITE_PROTECT:
11011 		if (st_wrongtapetype(un)) {
11012 			un->un_status = SUN_KEY_WRONGMEDIA;
11013 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11014 			    "wrong tape for writing- use DC6150 tape "
11015 			    "(or equivalent)\n");
11016 			severity = SCSI_ERR_UNKNOWN;
11017 		} else {
11018 			severity = SCSI_ERR_FATAL;
11019 		}
11020 		ST_DO_ERRSTATS(un, st_harderrs);
11021 		rval = COMMAND_DONE_ERROR;
11022 		st_bioerror(bp, EACCES);
11023 		break;
11024 
11025 	case KEY_UNIT_ATTENTION:
11026 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11027 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
11028 
11029 		un->un_unit_attention_flags |= 1;
11030 		/*
11031 		 * If we have detected a Bus Reset and the tape
11032 		 * drive has been reserved.
11033 		 */
11034 		if (ST_RQSENSE->es_add_code == 0x29) {
11035 			rval = DEVICE_RESET;
11036 			if ((un->un_rsvd_status &
11037 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
11038 			    ST_RESERVE) {
11039 				un->un_rsvd_status |= ST_LOST_RESERVE;
11040 				ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
11041 				    "st_decode_sense: Lost Reservation\n");
11042 			}
11043 		}
11044 
11045 		/*
11046 		 * If this is a recovery command and retrable, retry.
11047 		 */
11048 		if (bp == un->un_recov_buf) {
11049 			severity = SCSI_ERR_INFO;
11050 			if (attrib->retriable &&
11051 			    ri->pkt_retry_cnt++ < st_retry_count) {
11052 				rval = QUE_COMMAND;
11053 			} else {
11054 				rval = COMMAND_DONE_ERROR;
11055 			}
11056 			break; /* Don't set position invalid */
11057 		}
11058 
11059 		/*
11060 		 * If ST_APPLICATION_RESERVATIONS is set,
11061 		 * If the asc/ascq indicates that the reservation
11062 		 * has been cleared just allow the write to continue
11063 		 * which would force a scsi 2 reserve.
11064 		 * If preempted that persistent reservation
11065 		 * the scsi 2 reserve would get a reservation conflict.
11066 		 */
11067 		if ((un->un_rsvd_status &
11068 		    ST_APPLICATION_RESERVATIONS) != 0) {
11069 			/*
11070 			 * RESERVATIONS PREEMPTED
11071 			 * With MPxIO this could be a fail over? XXX
11072 			 */
11073 			if (ST_RQSENSE->es_add_code == 0x2a &&
11074 			    ST_RQSENSE->es_qual_code == 0x03) {
11075 				severity = SCSI_ERR_INFO;
11076 				rval = COMMAND_DONE_ERROR;
11077 				pos->pmode = invalid;
11078 				break;
11079 			/*
11080 			 * RESERVATIONS RELEASED
11081 			 */
11082 			} else if (ST_RQSENSE->es_add_code == 0x2a &&
11083 			    ST_RQSENSE->es_qual_code == 0x04) {
11084 				severity = SCSI_ERR_INFO;
11085 				rval = COMMAND_DONE;
11086 				break;
11087 			}
11088 		}
11089 
11090 		if (un->un_state <= ST_STATE_OPENING) {
11091 			/*
11092 			 * Look, the tape isn't open yet, now determine
11093 			 * if the cause is a BUS RESET, Save the file
11094 			 * and Block positions for the callers to
11095 			 * recover from the loss of position.
11096 			 */
11097 			severity = SCSI_ERR_INFO;
11098 			if ((pos->pmode != invalid) &&
11099 			    (rval == DEVICE_RESET) &&
11100 			    (un->un_restore_pos != 1)) {
11101 				un->un_save_fileno = pos->fileno;
11102 				un->un_save_blkno = pos->blkno;
11103 				un->un_restore_pos = 1;
11104 			}
11105 
11106 			if (attrib->retriable &&
11107 			    ri->pkt_retry_cnt++ < st_retry_count) {
11108 				rval = QUE_COMMAND;
11109 			} else if (rval == DEVICE_RESET) {
11110 				break;
11111 			} else {
11112 				rval = COMMAND_DONE_ERROR;
11113 			}
11114 		/*
11115 		 * Means it thinks the mode parameters have changed.
11116 		 * This is the result of a reset clearing settings or
11117 		 * another initiator changing what we set.
11118 		 */
11119 		}
11120 		if (ST_RQSENSE->es_add_code == 0x2a) {
11121 			if (ST_RQSENSE->es_qual_code == 0x1) {
11122 				/* Error recovery will modeselect and retry. */
11123 				rval = DEVICE_TAMPER;
11124 				severity = SCSI_ERR_INFO;
11125 				break; /* don't set position invalid */
11126 			}
11127 			if (ST_RQSENSE->es_qual_code == 0x0 ||
11128 			    ST_RQSENSE->es_qual_code == 0x2 ||
11129 			    ST_RQSENSE->es_qual_code == 0x3 ||
11130 			    ST_RQSENSE->es_qual_code == 0x4 ||
11131 			    ST_RQSENSE->es_qual_code == 0x5 ||
11132 			    ST_RQSENSE->es_qual_code == 0x6 ||
11133 			    ST_RQSENSE->es_qual_code == 0x7) {
11134 				rval = DEVICE_TAMPER;
11135 				severity = SCSI_ERR_INFO;
11136 			}
11137 		} else if (ST_RQSENSE->es_add_code == 0x28 &&
11138 		    ((ST_RQSENSE->es_qual_code == 0x0) ||
11139 		    ST_RQSENSE->es_qual_code == 0x5)) {
11140 			/*
11141 			 * Not Ready to Ready change, Media may have changed.
11142 			 */
11143 			rval = DEVICE_TAMPER;
11144 			severity = SCSI_ERR_RETRYABLE;
11145 		} else {
11146 			if (rval != DEVICE_RESET) {
11147 				rval = COMMAND_DONE_ERROR;
11148 			} else {
11149 				/*
11150 				 * Returning DEVICE_RESET will call
11151 				 * error recovery.
11152 				 */
11153 				severity = SCSI_ERR_INFO;
11154 				break; /* don't set position invalid */
11155 			}
11156 			/*
11157 			 * Check if it is an Unexpected Unit Attention.
11158 			 * If state is >= ST_STATE_OPEN, we have
11159 			 * already done the initialization .
11160 			 * In this case it is Fatal Error
11161 			 * since no further reading/writing
11162 			 * can be done with fileno set to < 0.
11163 			 */
11164 			if (un->un_state >= ST_STATE_OPEN) {
11165 				ST_DO_ERRSTATS(un, st_harderrs);
11166 				severity = SCSI_ERR_FATAL;
11167 			} else {
11168 				severity = SCSI_ERR_INFO;
11169 			}
11170 		}
11171 
11172 		pos->pmode = invalid;
11173 
11174 		break;
11175 
11176 	case KEY_NOT_READY:
11177 		/*
11178 		 * If in process of getting ready retry.
11179 		 */
11180 		if (sensep->es_add_code == 0x04) {
11181 			switch (sensep->es_qual_code) {
11182 			case 0x07:
11183 				/*
11184 				 * We get here when the tape is rewinding.
11185 				 * QUE_BUSY_COMMAND retries every 10 seconds.
11186 				 */
11187 				if (ri->pkt_retry_cnt++ <
11188 				    (un->un_dp->rewind_timeout / 10)) {
11189 					rval = QUE_BUSY_COMMAND;
11190 					severity = SCSI_ERR_INFO;
11191 				} else {
11192 					/* give up */
11193 					rval = COMMAND_DONE_ERROR;
11194 					severity = SCSI_ERR_FATAL;
11195 				}
11196 				break;
11197 			case 0x01:
11198 				if (ri->pkt_retry_cnt++ < st_retry_count) {
11199 					rval = QUE_COMMAND;
11200 					severity = SCSI_ERR_INFO;
11201 					break;
11202 				}
11203 			default: /* FALLTHRU */
11204 				/* give up */
11205 				rval = COMMAND_DONE_ERROR;
11206 				severity = SCSI_ERR_FATAL;
11207 			}
11208 		} else {
11209 			/* give up */
11210 			rval = COMMAND_DONE_ERROR;
11211 			severity = SCSI_ERR_FATAL;
11212 		}
11213 
11214 		/*
11215 		 * If this was an error and after device opened
11216 		 * do error stats.
11217 		 */
11218 		if (rval == COMMAND_DONE_ERROR &&
11219 		    un->un_state > ST_STATE_OPENING) {
11220 			ST_DO_ERRSTATS(un, st_harderrs);
11221 		}
11222 
11223 		if (ST_RQSENSE->es_add_code == 0x3a) {
11224 			if (st_error_level >= SCSI_ERR_FATAL)
11225 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11226 				    "Tape not inserted in drive\n");
11227 			un->un_mediastate = MTIO_EJECTED;
11228 			cv_broadcast(&un->un_state_cv);
11229 		}
11230 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
11231 		    (rval != QUE_COMMAND))
11232 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
11233 		break;
11234 
11235 	case KEY_ABORTED_COMMAND:
11236 		/* XXX Do drives return this when they see a lost light? */
11237 		/* Testing would say yes */
11238 
11239 		if (ri->pkt_retry_cnt++ < st_retry_count) {
11240 			rval = ATTEMPT_RETRY;
11241 			severity = SCSI_ERR_RETRYABLE;
11242 			goto check_keys;
11243 		}
11244 		/*
11245 		 * Probably a parity error...
11246 		 * if we retry here then this may cause data to be
11247 		 * written twice or data skipped during reading
11248 		 */
11249 		ST_DO_ERRSTATS(un, st_harderrs);
11250 		severity = SCSI_ERR_FATAL;
11251 		rval = COMMAND_DONE_ERROR;
11252 		goto check_keys;
11253 
11254 	default:
11255 		/*
11256 		 * Undecoded sense key.	 Try retries and hope
11257 		 * that will fix the problem.  Otherwise, we're
11258 		 * dead.
11259 		 */
11260 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11261 		    "Unhandled Sense Key '%s'\n",
11262 		    sense_keys[un->un_status]);
11263 		ST_DO_ERRSTATS(un, st_harderrs);
11264 		severity = SCSI_ERR_FATAL;
11265 		rval = COMMAND_DONE_ERROR;
11266 		goto check_keys;
11267 	}
11268 
11269 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
11270 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
11271 	    (un->un_laststate > ST_STATE_OPENING) &&
11272 	    (severity >= st_error_level))) {
11273 
11274 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
11275 		    pos->lgclblkno, un->un_err_pos.lgclblkno,
11276 		    scsi_cmds, sensep);
11277 		if (sensep->es_filmk) {
11278 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11279 			    "File Mark Detected\n");
11280 		}
11281 		if (sensep->es_eom) {
11282 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11283 			    "End-of-Media Detected\n");
11284 		}
11285 		if (sensep->es_ili) {
11286 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11287 			    "Incorrect Length Indicator Set\n");
11288 		}
11289 	}
11290 	get_error = geterror(bp);
11291 	if (((rval == COMMAND_DONE_ERROR) ||
11292 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
11293 	    ((get_error == EIO) || (get_error == 0))) {
11294 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
11295 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
11296 		if (un->un_rqs_state & ST_RQS_READ) {
11297 			un->un_rqs_state &= ~(ST_RQS_READ);
11298 		} else {
11299 			un->un_rqs_state |= ST_RQS_OVR;
11300 		}
11301 	}
11302 
11303 	return (rval);
11304 }
11305 
11306 
11307 static int
11308 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
11309 {
11310 	int status = TRAN_ACCEPT;
11311 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
11312 
11313 	mutex_enter(ST_MUTEX);
11314 
11315 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
11316 
11317 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11318 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
11319 
11320 	/*
11321 	 * Check to see if we hit the retry timeout. We check to make sure
11322 	 * this is the first one on the runq and make sure we have not
11323 	 * queued up any more, so this one has to be the last on the list
11324 	 * also. If it is not, we have to fail.  If it is not the first, but
11325 	 * is the last we are in trouble anyway, as we are in the interrupt
11326 	 * context here.
11327 	 */
11328 	if ((pktinfo->pkt_retry_cnt > st_retry_count) ||
11329 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
11330 		goto exit;
11331 	}
11332 
11333 	if (un->un_throttle) {
11334 		un->un_last_throttle = un->un_throttle;
11335 		un->un_throttle = 0;
11336 	}
11337 
11338 	/*
11339 	 * Here we know : bp is the first and last one on the runq
11340 	 * it is not necessary to put it back on the head of the
11341 	 * waitq and then move from waitq to runq. Save this queuing
11342 	 * and call scsi_transport.
11343 	 */
11344 	ST_CDB(ST_DEVINFO, "Retry lcmd CDB", (char *)BP_PKT(bp)->pkt_cdbp);
11345 
11346 	status = st_transport(un, BP_PKT(bp));
11347 
11348 	if (status == TRAN_ACCEPT) {
11349 		if (un->un_last_throttle) {
11350 			un->un_throttle = un->un_last_throttle;
11351 		}
11352 		mutex_exit(ST_MUTEX);
11353 
11354 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11355 		    "restart transport \n");
11356 		return (0);
11357 	}
11358 
11359 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
11360 	mutex_exit(ST_MUTEX);
11361 
11362 	if (status == TRAN_BUSY) {
11363 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
11364 			return (0);
11365 		}
11366 	}
11367 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11368 	    "restart transport rejected\n");
11369 	mutex_enter(ST_MUTEX);
11370 	ST_DO_ERRSTATS(un, st_transerrs);
11371 	if (un->un_last_throttle) {
11372 		un->un_throttle = un->un_last_throttle;
11373 	}
11374 exit:
11375 	mutex_exit(ST_MUTEX);
11376 	return (-1);
11377 }
11378 
11379 static int
11380 st_wrongtapetype(struct scsi_tape *un)
11381 {
11382 
11383 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
11384 
11385 	ASSERT(mutex_owned(ST_MUTEX));
11386 
11387 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
11388 
11389 	/*
11390 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
11391 	 */
11392 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
11393 		switch (un->un_dp->type) {
11394 		case ST_TYPE_WANGTEK:
11395 		case ST_TYPE_ARCHIVE:
11396 			/*
11397 			 * If this really worked, we could go off of
11398 			 * the density codes set in the modesense
11399 			 * page. For this drive, 0x10 == QIC-120,
11400 			 * 0xf == QIC-150, and 0x5 should be for
11401 			 * both QIC-24 and, maybe, QIC-11. However,
11402 			 * the h/w doesn't do what the manual says
11403 			 * that it should, so we'll key off of
11404 			 * getting a WRITE PROTECT error AND wp *not*
11405 			 * set in the mode sense information.
11406 			 */
11407 			/*
11408 			 * XXX but we already know that status is
11409 			 * write protect, so don't check it again.
11410 			 */
11411 
11412 			if (un->un_status == KEY_WRITE_PROTECT &&
11413 			    un->un_mspl->wp == 0) {
11414 				return (1);
11415 			}
11416 			break;
11417 		default:
11418 			break;
11419 		}
11420 	}
11421 	return (0);
11422 }
11423 
11424 static errstate
11425 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
11426 {
11427 	errstate action;
11428 	recov_info *rcvi = pkt->pkt_private;
11429 	buf_t *bp = rcvi->cmd_bp;
11430 	struct scsi_arq_status *stat = (struct scsi_arq_status *)pkt->pkt_scbp;
11431 
11432 	ST_FUNC(ST_DEVINFO, st_check_error);
11433 
11434 	ASSERT(mutex_owned(ST_MUTEX));
11435 
11436 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
11437 
11438 	switch (SCBP_C(pkt)) {
11439 	case STATUS_RESERVATION_CONFLICT:
11440 		/*
11441 		 * Command recovery is enabled, not just opening,
11442 		 * we had the drive reserved and we thing its ours.
11443 		 * Call recovery to attempt to take it back.
11444 		 */
11445 		if ((rcvi->privatelen == sizeof (recov_info)) &&
11446 		    (bp != un->un_recov_buf) &&
11447 		    (un->un_state > ST_STATE_OPEN_PENDING_IO) &&
11448 		    ((un->un_rsvd_status & (ST_RESERVE |
11449 		    ST_APPLICATION_RESERVATIONS)) != 0)) {
11450 			action = ATTEMPT_RETRY;
11451 			un->un_rsvd_status |= ST_LOST_RESERVE;
11452 		} else {
11453 			action = COMMAND_DONE_EACCES;
11454 			un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
11455 		}
11456 		break;
11457 
11458 	case STATUS_BUSY:
11459 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
11460 		if (rcvi->privatelen == sizeof (recov_info) &&
11461 		    un->un_multipath && (pkt->pkt_state == (STATE_GOT_BUS |
11462 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS))) {
11463 			/*
11464 			 * Status returned by scsi_vhci indicating path
11465 			 * has failed over.
11466 			 */
11467 			action = PATH_FAILED;
11468 			break;
11469 		}
11470 		/* FALLTHRU */
11471 	case STATUS_QFULL:
11472 		if (rcvi->privatelen == sizeof (recov_info)) {
11473 			/*
11474 			 * If recovery is inabled use it instead of
11475 			 * blind reties.
11476 			 */
11477 			action = ATTEMPT_RETRY;
11478 		} else if (rcvi->pkt_retry_cnt++ < st_retry_count) {
11479 			action = QUE_BUSY_COMMAND;
11480 		} else if ((un->un_rsvd_status &
11481 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
11482 			/*
11483 			 * If this is a command done before reserve is done
11484 			 * don't reset.
11485 			 */
11486 			action = COMMAND_DONE_ERROR;
11487 		} else {
11488 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11489 			    "unit busy too long\n");
11490 			(void) st_reset(un, RESET_ALL);
11491 			action = COMMAND_DONE_ERROR;
11492 		}
11493 		break;
11494 
11495 	case STATUS_CHECK:
11496 	case STATUS_TERMINATED:
11497 		/*
11498 		 * we should only get here if the auto rqsense failed
11499 		 * thru a uscsi cmd without autorequest sense
11500 		 * so we just try again
11501 		 */
11502 		if (un->un_arq_enabled &&
11503 		    stat->sts_rqpkt_reason == CMD_CMPLT &&
11504 		    (stat->sts_rqpkt_state & (STATE_GOT_BUS |
11505 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) ==
11506 		    (STATE_GOT_BUS | STATE_GOT_TARGET | STATE_SENT_CMD |
11507 		    STATE_GOT_STATUS)) {
11508 
11509 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11510 			    "Really got sense data\n");
11511 			action = st_decode_sense(un, bp, MAX_SENSE_LENGTH -
11512 			    pkt->pkt_resid, stat, &un->un_pos);
11513 		} else {
11514 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11515 			    "Trying to queue sense command\n");
11516 			action = QUE_SENSE;
11517 		}
11518 		break;
11519 
11520 	case STATUS_TASK_ABORT:
11521 		/*
11522 		 * This is an aborted task. This can be a reset on the other
11523 		 * port of a multiport drive. Lets try and recover it.
11524 		 */
11525 		action = DEVICE_RESET;
11526 		break;
11527 
11528 	default:
11529 		action = COMMAND_DONE;
11530 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
11531 		    "Unexpected scsi status byte 0x%x\n", SCBP_C(pkt));
11532 	}
11533 	return (action);
11534 }
11535 
11536 static void
11537 st_calc_bnum(struct scsi_tape *un, struct buf *bp, struct scsi_pkt *pkt)
11538 {
11539 	int nblks;
11540 	int nfiles;
11541 	long count;
11542 	recov_info *ri = pkt->pkt_private;
11543 	cmd_attribute const *attrib;
11544 
11545 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
11546 
11547 	ASSERT(mutex_owned(ST_MUTEX));
11548 
11549 	if (ri->privatelen == sizeof (recov_info)) {
11550 		attrib = ri->cmd_attrib;
11551 		ASSERT(attrib->recov_pos_type == POS_EXPECTED);
11552 		ASSERT(attrib->chg_tape_pos);
11553 	} else {
11554 		ri = NULL;
11555 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
11556 	}
11557 
11558 	count = bp->b_bcount - bp->b_resid;
11559 
11560 	/* Command reads or writes data */
11561 	if (attrib->transfers_data != TRAN_NONE) {
11562 		if (count == 0) {
11563 			/* failed writes should not make it here */
11564 			ASSERT(attrib->transfers_data == TRAN_READ);
11565 			nblks = 0;
11566 			nfiles = 1;
11567 		} else if (un->un_bsize == 0) {
11568 			/*
11569 			 * If variable block mode.
11570 			 * Fixed bit in CBD should be zero.
11571 			 */
11572 			ASSERT((pkt->pkt_cdbp[1] & 1) == 0);
11573 			nblks = 1;
11574 			un->un_kbytes_xferred += (count / ONE_K);
11575 			nfiles = 0;
11576 		} else {
11577 			/*
11578 			 * If fixed block mode.
11579 			 * Fixed bit in CBD should be one.
11580 			 */
11581 			ASSERT((pkt->pkt_cdbp[1] & 1) == 1);
11582 			nblks = (count / un->un_bsize);
11583 			un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
11584 			nfiles = 0;
11585 		}
11586 		/*
11587 		 * So its possable to read some blocks and hit a filemark.
11588 		 * Example reading in fixed block mode where more then one
11589 		 * block at a time is requested. In this case because the
11590 		 * filemark is hit something less then the requesed number
11591 		 * of blocks is read.
11592 		 */
11593 		if (un->un_pos.eof == ST_EOF_PENDING && bp->b_resid) {
11594 			nfiles = 1;
11595 		}
11596 	} else {
11597 		nblks = 0;
11598 		nfiles = count;
11599 	}
11600 
11601 	/*
11602 	 * If some command failed after this one started and it seems
11603 	 * to have finshed without error count the position.
11604 	 */
11605 	if (un->un_persistence && un->un_persist_errors) {
11606 		ASSERT(un->un_pos.pmode != invalid);
11607 	}
11608 
11609 	if (attrib->chg_tape_direction == DIR_FORW) {
11610 		un->un_pos.blkno += nblks;
11611 		un->un_pos.lgclblkno += nblks;
11612 		un->un_pos.lgclblkno += nfiles;
11613 	} else if (attrib->chg_tape_direction == DIR_REVC) {
11614 		un->un_pos.blkno -= nblks;
11615 		un->un_pos.lgclblkno -= nblks;
11616 		un->un_pos.lgclblkno -= nfiles;
11617 	} else {
11618 		ASSERT(0);
11619 	}
11620 
11621 	/* recovery disabled */
11622 	if (ri == NULL) {
11623 		un->un_running.pmode = invalid;
11624 		return;
11625 	}
11626 
11627 	/*
11628 	 * If we didn't just read a filemark.
11629 	 */
11630 	if (un->un_pos.eof != ST_EOF_PENDING) {
11631 		ASSERT(nblks != 0 && nfiles == 0);
11632 		/*
11633 		 * If Previously calulated expected position does not match
11634 		 * debug the expected position.
11635 		 */
11636 		if ((ri->pos.pmode != invalid) && nblks &&
11637 		    ((un->un_pos.blkno != ri->pos.blkno) ||
11638 		    (un->un_pos.lgclblkno != ri->pos.lgclblkno))) {
11639 #ifdef STDEBUG
11640 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11641 			    "Expected", &ri->pos);
11642 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11643 			    "But Got", &un->un_pos);
11644 #endif
11645 			un->un_running.pmode = invalid;
11646 		}
11647 	} else {
11648 		ASSERT(nfiles != 0);
11649 		if (un->un_running.pmode != invalid) {
11650 			/*
11651 			 * blkno and lgclblkno already counted in
11652 			 * st_add_recovery_info_to_pkt(). Since a block was not
11653 			 * read and a filemark was.
11654 			 */
11655 			if (attrib->chg_tape_direction == DIR_FORW) {
11656 				un->un_running.fileno++;
11657 				un->un_running.blkno = 0;
11658 			} else if (attrib->chg_tape_direction == DIR_REVC) {
11659 				un->un_running.fileno--;
11660 				un->un_running.blkno = LASTBLK;
11661 			}
11662 		}
11663 	}
11664 }
11665 
11666 static void
11667 st_set_state(struct scsi_tape *un, struct buf *bp)
11668 {
11669 	struct scsi_pkt *sp = BP_PKT(bp);
11670 	struct uscsi_cmd *ucmd;
11671 
11672 	ST_FUNC(ST_DEVINFO, st_set_state);
11673 
11674 	ASSERT(mutex_owned(ST_MUTEX));
11675 	ASSERT(bp != un->un_recov_buf);
11676 
11677 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11678 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
11679 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
11680 
11681 	if (bp != un->un_sbufp) {
11682 #ifdef STDEBUG
11683 		if (DEBUGGING && sp->pkt_resid) {
11684 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11685 			    "pkt_resid %ld bcount %ld\n",
11686 			    sp->pkt_resid, bp->b_bcount);
11687 		}
11688 #endif
11689 		bp->b_resid = sp->pkt_resid;
11690 		if (geterror(bp) != EIO) {
11691 			st_calc_bnum(un, bp, sp);
11692 		}
11693 		if (bp->b_flags & B_READ) {
11694 			un->un_lastop = ST_OP_READ;
11695 			un->un_fmneeded = 0;
11696 		} else {
11697 			un->un_lastop = ST_OP_WRITE;
11698 			if (un->un_dp->options & ST_REEL) {
11699 				un->un_fmneeded = 2;
11700 			} else {
11701 				un->un_fmneeded = 1;
11702 			}
11703 		}
11704 		/*
11705 		 * all is honky dory at this point, so let's
11706 		 * readjust the throttle, to increase speed, if we
11707 		 * have not throttled down.
11708 		 */
11709 		if (un->un_throttle) {
11710 			un->un_throttle = un->un_max_throttle;
11711 		}
11712 	} else {
11713 		optype new_lastop = ST_OP_NIL;
11714 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
11715 
11716 		switch (cmd) {
11717 		case SCMD_WRITE:
11718 		case SCMD_WRITE_G4:
11719 			bp->b_resid = sp->pkt_resid;
11720 			new_lastop = ST_OP_WRITE;
11721 			if (geterror(bp) == EIO) {
11722 				break;
11723 			}
11724 			st_calc_bnum(un, bp, sp);
11725 			if (un->un_dp->options & ST_REEL) {
11726 				un->un_fmneeded = 2;
11727 			} else {
11728 				un->un_fmneeded = 1;
11729 			}
11730 			break;
11731 		case SCMD_READ:
11732 		case SCMD_READ_G4:
11733 			bp->b_resid = sp->pkt_resid;
11734 			new_lastop = ST_OP_READ;
11735 			if (geterror(bp) == EIO) {
11736 				break;
11737 			}
11738 			st_calc_bnum(un, bp, sp);
11739 			un->un_fmneeded = 0;
11740 			break;
11741 		case SCMD_WRITE_FILE_MARK_G4:
11742 		case SCMD_WRITE_FILE_MARK:
11743 		{
11744 			int fmdone;
11745 
11746 			if (un->un_pos.eof != ST_EOM) {
11747 				un->un_pos.eof = ST_NO_EOF;
11748 			}
11749 			fmdone = (bp->b_bcount - bp->b_resid);
11750 			if (fmdone > 0) {
11751 				un->un_lastop = new_lastop = ST_OP_WEOF;
11752 				un->un_pos.lgclblkno += fmdone;
11753 				un->un_pos.fileno += fmdone;
11754 				un->un_pos.blkno = 0;
11755 			} else {
11756 				new_lastop = ST_OP_CTL;
11757 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11758 				    "Flushed buffer\n");
11759 			}
11760 			if (fmdone > un->un_fmneeded) {
11761 				un->un_fmneeded = 0;
11762 			} else {
11763 				un->un_fmneeded -= fmdone;
11764 			}
11765 			break;
11766 		}
11767 		case SCMD_REWIND:
11768 			un->un_pos.eof = ST_NO_EOF;
11769 			un->un_pos.fileno = 0;
11770 			un->un_pos.blkno = 0;
11771 			un->un_pos.lgclblkno = 0;
11772 			if (un->un_pos.pmode != legacy)
11773 				un->un_pos.pmode = legacy;
11774 			new_lastop = ST_OP_CTL;
11775 			un->un_restore_pos = 0;
11776 			break;
11777 
11778 		case SCMD_SPACE:
11779 		case SCMD_SPACE_G4:
11780 		{
11781 			int64_t count;
11782 			int64_t resid;
11783 			int64_t done;
11784 			cmd_attribute const *attrib;
11785 			recov_info *ri = sp->pkt_private;
11786 
11787 			if (ri->privatelen == sizeof (recov_info)) {
11788 				attrib = ri->cmd_attrib;
11789 			} else {
11790 				attrib =
11791 				    st_lookup_cmd_attribute(sp->pkt_cdbp[0]);
11792 			}
11793 
11794 			resid = (int64_t)SPACE_CNT(bp->b_resid);
11795 			count = (int64_t)attrib->get_cnt(sp->pkt_cdbp);
11796 
11797 			if (count >= 0) {
11798 				done = (count - resid);
11799 			} else {
11800 				done = ((-count) - resid);
11801 			}
11802 			if (done > 0) {
11803 				un->un_lastop = new_lastop = ST_OP_CTL;
11804 			} else {
11805 				new_lastop = ST_OP_CTL;
11806 			}
11807 
11808 			ST_SPAC(ST_DEVINFO, st_label, CE_WARN,
11809 			    "space cmd: cdb[1] = %s\n"
11810 			    "space data:       = 0x%lx\n"
11811 			    "space count:      = %"PRId64"\n"
11812 			    "space resid:      = %"PRId64"\n"
11813 			    "spaces done:      = %"PRId64"\n"
11814 			    "fileno before     = %d\n"
11815 			    "blkno before      = %d\n",
11816 			    space_strs[sp->pkt_cdbp[1] & 7],
11817 			    bp->b_bcount,
11818 			    count, resid, done,
11819 			    un->un_pos.fileno, un->un_pos.blkno);
11820 
11821 			switch (sp->pkt_cdbp[1]) {
11822 			case SPACE_TYPE(SP_FLM):
11823 				/* Space file forward */
11824 				if (count >= 0) {
11825 					if (un->un_pos.eof <= ST_EOF) {
11826 						un->un_pos.eof = ST_NO_EOF;
11827 					}
11828 					un->un_pos.fileno += done;
11829 					un->un_pos.blkno = 0;
11830 					break;
11831 				}
11832 				/* Space file backward */
11833 				if (done > un->un_pos.fileno) {
11834 					un->un_pos.fileno = 0;
11835 					un->un_pos.blkno = 0;
11836 				} else {
11837 					un->un_pos.fileno -= done;
11838 					un->un_pos.blkno = LASTBLK;
11839 					un->un_running.pmode = invalid;
11840 				}
11841 				break;
11842 			case SPACE_TYPE(SP_BLK):
11843 				/* Space block forward */
11844 				if (count >= 0) {
11845 					un->un_pos.blkno += done;
11846 					break;
11847 				}
11848 				/* Space block backward */
11849 				if (un->un_pos.eof >= ST_EOF_PENDING) {
11850 				/*
11851 				 * we stepped back into
11852 				 * a previous file; we are not
11853 				 * making an effort to pretend that
11854 				 * we are still in the current file
11855 				 * ie. logical == physical position
11856 				 * and leave it to st_ioctl to correct
11857 				 */
11858 					if (done > un->un_pos.blkno) {
11859 						un->un_pos.blkno = 0;
11860 					} else {
11861 						un->un_pos.fileno--;
11862 						un->un_pos.blkno = LASTBLK;
11863 						un->un_running.pmode = invalid;
11864 					}
11865 				} else {
11866 					un->un_pos.blkno -= done;
11867 				}
11868 				break;
11869 			case SPACE_TYPE(SP_SQFLM):
11870 				un->un_pos.pmode = logical;
11871 				un->un_pos.blkno = 0;
11872 				un->un_lastop = new_lastop = ST_OP_CTL;
11873 				break;
11874 			case SPACE_TYPE(SP_EOD):
11875 				un->un_pos.pmode = logical;
11876 				un->un_pos.eof = ST_EOM;
11877 				un->un_status = KEY_BLANK_CHECK;
11878 				break;
11879 			default:
11880 				un->un_pos.pmode = invalid;
11881 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11882 				    "Unsupported space cmd: %s\n",
11883 				    space_strs[sp->pkt_cdbp[1] & 7]);
11884 
11885 				un->un_lastop = new_lastop = ST_OP_CTL;
11886 			}
11887 
11888 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11889 			    "after_space rs %"PRId64" fil %d blk %d\n",
11890 			    resid, un->un_pos.fileno, un->un_pos.blkno);
11891 
11892 			break;
11893 		}
11894 		case SCMD_LOAD:
11895 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
11896 				un->un_pos.fileno = 0;
11897 				if (un->un_pos.pmode != legacy)
11898 					un->un_pos.pmode = legacy;
11899 			} else {
11900 				un->un_state = ST_STATE_OFFLINE;
11901 				un->un_pos.pmode = invalid;
11902 
11903 			}
11904 			/*
11905 			 * If we are loading or unloading we expect the media id
11906 			 * to change. Lets make it unknown.
11907 			 */
11908 			if (un->un_media_id != bogusID && un->un_media_id_len) {
11909 				kmem_free(un->un_media_id, un->un_media_id_len);
11910 				un->un_media_id = NULL;
11911 				un->un_media_id_len = 0;
11912 			}
11913 			un->un_density_known = 0;
11914 			un->un_pos.eof = ST_NO_EOF;
11915 			un->un_pos.blkno = 0;
11916 			un->un_lastop = new_lastop = ST_OP_CTL;
11917 			break;
11918 		case SCMD_ERASE:
11919 			un->un_pos.eof = ST_NO_EOF;
11920 			un->un_pos.blkno = 0;
11921 			un->un_pos.fileno = 0;
11922 			un->un_pos.lgclblkno = 0;
11923 			if (un->un_pos.pmode != legacy)
11924 				un->un_pos.pmode = legacy;
11925 			new_lastop = ST_OP_CTL;
11926 			break;
11927 		case SCMD_RESERVE:
11928 			un->un_rsvd_status |= ST_RESERVE;
11929 			un->un_rsvd_status &=
11930 			    ~(ST_RELEASE | ST_LOST_RESERVE |
11931 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11932 			new_lastop = ST_OP_CTL;
11933 			break;
11934 		case SCMD_RELEASE:
11935 			un->un_rsvd_status |= ST_RELEASE;
11936 			un->un_rsvd_status &=
11937 			    ~(ST_RESERVE | ST_LOST_RESERVE |
11938 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11939 			new_lastop = ST_OP_CTL;
11940 			break;
11941 		case SCMD_PERSISTENT_RESERVE_IN:
11942 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11943 			    "PGR_IN command\n");
11944 			new_lastop = ST_OP_CTL;
11945 			break;
11946 		case SCMD_PERSISTENT_RESERVE_OUT:
11947 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
11948 			case ST_SA_SCSI3_RESERVE:
11949 			case ST_SA_SCSI3_PREEMPT:
11950 			case ST_SA_SCSI3_PREEMPTANDABORT:
11951 				un->un_rsvd_status |=
11952 				    (ST_APPLICATION_RESERVATIONS | ST_RESERVE);
11953 				un->un_rsvd_status &= ~(ST_RELEASE |
11954 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11955 				    ST_INITIATED_RESET);
11956 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11957 				    "PGR Reserve and set: entering"
11958 				    " ST_APPLICATION_RESERVATIONS mode");
11959 				break;
11960 			case ST_SA_SCSI3_REGISTER:
11961 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11962 				    "PGR Reserve register key");
11963 				un->un_rsvd_status |= ST_INIT_RESERVE;
11964 				break;
11965 			case ST_SA_SCSI3_CLEAR:
11966 				un->un_rsvd_status &= ~ST_INIT_RESERVE;
11967 				/* FALLTHROUGH */
11968 			case ST_SA_SCSI3_RELEASE:
11969 				un->un_rsvd_status &=
11970 				    ~(ST_APPLICATION_RESERVATIONS | ST_RESERVE |
11971 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11972 				    ST_INITIATED_RESET);
11973 				un->un_rsvd_status |= ST_RELEASE;
11974 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11975 				    "PGR Release and reset: exiting"
11976 				    " ST_APPLICATION_RESERVATIONS mode");
11977 				break;
11978 			}
11979 			new_lastop = ST_OP_CTL;
11980 			break;
11981 		case SCMD_TEST_UNIT_READY:
11982 		case SCMD_READ_BLKLIM:
11983 		case SCMD_REQUEST_SENSE:
11984 		case SCMD_INQUIRY:
11985 		case SCMD_RECOVER_BUF:
11986 		case SCMD_MODE_SELECT:
11987 		case SCMD_MODE_SENSE:
11988 		case SCMD_DOORLOCK:
11989 		case SCMD_READ_BUFFER:
11990 		case SCMD_REPORT_DENSITIES:
11991 		case SCMD_LOG_SELECT_G1:
11992 		case SCMD_LOG_SENSE_G1:
11993 		case SCMD_REPORT_LUNS:
11994 		case SCMD_READ_ATTRIBUTE:
11995 		case SCMD_WRITE_ATTRIBUTE:
11996 		case SCMD_SVC_ACTION_IN_G5:
11997 			new_lastop = ST_OP_CTL;
11998 			break;
11999 		case SCMD_READ_POSITION:
12000 			new_lastop = ST_OP_CTL;
12001 			/*
12002 			 * Only if the buf used was un_sbufp.
12003 			 * Among other things the prevents read positions used
12004 			 * as part of error recovery from messing up our
12005 			 * current position as they will use un_recov_buf.
12006 			 */
12007 			if (USCSI_CMD(bp)) {
12008 				(void) st_get_read_pos(un, bp);
12009 			}
12010 			break;
12011 		case SCMD_LOCATE:
12012 		case SCMD_LOCATE_G4:
12013 			/* Locate makes position mode no longer legacy */
12014 			un->un_lastop = new_lastop = ST_OP_CTL;
12015 			break;
12016 		case SCMD_MAINTENANCE_IN:
12017 			switch (sp->pkt_cdbp[1]) {
12018 			case SSVC_ACTION_GET_SUPPORTED_OPERATIONS:
12019 			case SSVC_ACTION_SET_TARGET_PORT_GROUPS:
12020 				new_lastop = ST_OP_CTL;
12021 				break;
12022 			}
12023 			if (new_lastop != ST_OP_NIL) {
12024 				break;
12025 			}
12026 		default:
12027 			/*
12028 			 * Unknown command, If was USCSI and USCSI_SILENT
12029 			 * flag was not set, set position to unknown.
12030 			 */
12031 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
12032 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
12033 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
12034 				    "unknown cmd 0x%X caused loss of state\n",
12035 				    cmd);
12036 			} else {
12037 				/*
12038 				 * keep the old agreement to allow unknown
12039 				 * commands with the USCSI_SILENT set.
12040 				 * This prevents ASSERT below.
12041 				 */
12042 				new_lastop = ST_OP_CTL;
12043 				break;
12044 			}
12045 			/* FALLTHROUGH */
12046 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
12047 			un->un_pos.pmode = invalid;
12048 			un->un_lastop = new_lastop = ST_OP_CTL;
12049 			break;
12050 		}
12051 
12052 		/* new_lastop should have been changed */
12053 		ASSERT(new_lastop != ST_OP_NIL);
12054 
12055 		/* If un_lastop should copy new_lastop  */
12056 		if (((un->un_lastop == ST_OP_WRITE) ||
12057 		    (un->un_lastop == ST_OP_WEOF)) &&
12058 		    new_lastop != ST_OP_CTL) {
12059 			un->un_lastop = new_lastop;
12060 		}
12061 	}
12062 
12063 	/*
12064 	 * In the st driver we have a logical and physical file position.
12065 	 * Under BSD behavior, when you get a zero read, the logical position
12066 	 * is before the filemark but after the last record of the file.
12067 	 * The physical position is after the filemark. MTIOCGET should always
12068 	 * return the logical file position.
12069 	 *
12070 	 * The next read gives a silent skip to the next file.
12071 	 * Under SVR4, the logical file position remains before the filemark
12072 	 * until the file is closed or a space operation is performed.
12073 	 * Hence set err_resid and err_file before changing fileno if case
12074 	 * BSD Behaviour.
12075 	 */
12076 	un->un_err_resid = bp->b_resid;
12077 	COPY_POS(&un->un_err_pos, &un->un_pos);
12078 
12079 
12080 	/*
12081 	 * If we've seen a filemark via the last read operation
12082 	 * advance the file counter, but mark things such that
12083 	 * the next read operation gets a zero count. We have
12084 	 * to put this here to handle the case of sitting right
12085 	 * at the end of a tape file having seen the file mark,
12086 	 * but the tape is closed and then re-opened without
12087 	 * any further i/o. That is, the position information
12088 	 * must be updated before a close.
12089 	 */
12090 
12091 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
12092 		/*
12093 		 * If we're a 1/2" tape, and we get a filemark
12094 		 * right on block 0, *AND* we were not in the
12095 		 * first file on the tape, and we've hit logical EOM.
12096 		 * We'll mark the state so that later we do the
12097 		 * right thing (in st_close(), st_strategy() or
12098 		 * st_ioctl()).
12099 		 *
12100 		 */
12101 		if ((un->un_dp->options & ST_REEL) &&
12102 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
12103 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
12104 			un->un_pos.eof = ST_EOT_PENDING;
12105 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12106 			    "eot pending\n");
12107 			un->un_pos.fileno++;
12108 			un->un_pos.blkno = 0;
12109 		} else if (BSD_BEHAVIOR) {
12110 			/*
12111 			 * If the read of the filemark was a side effect
12112 			 * of reading some blocks (i.e., data was actually
12113 			 * read), then the EOF mark is pending and the
12114 			 * bump into the next file awaits the next read
12115 			 * operation (which will return a zero count), or
12116 			 * a close or a space operation, else the bump
12117 			 * into the next file occurs now.
12118 			 */
12119 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12120 			    "resid=%lx, bcount=%lx\n",
12121 			    bp->b_resid, bp->b_bcount);
12122 
12123 			if (bp->b_resid != bp->b_bcount) {
12124 				un->un_pos.eof = ST_EOF;
12125 			} else {
12126 				un->un_silent_skip = 1;
12127 				un->un_pos.eof = ST_NO_EOF;
12128 				un->un_pos.fileno++;
12129 				un->un_pos.lgclblkno++;
12130 				un->un_save_blkno = un->un_pos.blkno;
12131 				un->un_pos.blkno = 0;
12132 			}
12133 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12134 			    "eof of file %d, eof=%d\n",
12135 			    un->un_pos.fileno, un->un_pos.eof);
12136 		} else if (SVR4_BEHAVIOR) {
12137 			/*
12138 			 * If the read of the filemark was a side effect
12139 			 * of reading some blocks (i.e., data was actually
12140 			 * read), then the next read should return 0
12141 			 */
12142 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12143 			    "resid=%lx, bcount=%lx\n",
12144 			    bp->b_resid, bp->b_bcount);
12145 			if (bp->b_resid == bp->b_bcount) {
12146 				un->un_pos.eof = ST_EOF;
12147 			}
12148 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12149 			    "eof of file=%d, eof=%d\n",
12150 			    un->un_pos.fileno, un->un_pos.eof);
12151 		}
12152 	}
12153 }
12154 
12155 /*
12156  * set the correct un_errno, to take corner cases into consideration
12157  */
12158 static void
12159 st_set_pe_errno(struct scsi_tape *un)
12160 {
12161 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
12162 
12163 	ASSERT(mutex_owned(ST_MUTEX));
12164 
12165 	/* if errno is already set, don't reset it */
12166 	if (un->un_errno)
12167 		return;
12168 
12169 	/* here un_errno == 0 */
12170 	/*
12171 	 * if the last transfer before flushing all the
12172 	 * waiting I/O's, was 0 (resid = count), then we
12173 	 * want to give the user an error on all the rest,
12174 	 * so here.  If there was a transfer, we set the
12175 	 * resid and counts to 0, and let it drop through,
12176 	 * giving a zero return.  the next I/O will then
12177 	 * give an error.
12178 	 */
12179 	if (un->un_last_resid == un->un_last_count) {
12180 		switch (un->un_pos.eof) {
12181 		case ST_EOM:
12182 			un->un_errno = ENOMEM;
12183 			break;
12184 		case ST_EOT:
12185 		case ST_EOF:
12186 			un->un_errno = EIO;
12187 			break;
12188 		}
12189 	} else {
12190 		/*
12191 		 * we know they did not have a zero, so make
12192 		 * sure they get one
12193 		 */
12194 		un->un_last_resid = un->un_last_count = 0;
12195 	}
12196 }
12197 
12198 
12199 /*
12200  * send in a marker pkt to terminate flushing of commands by BBA (via
12201  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
12202  */
12203 static void
12204 st_hba_unflush(struct scsi_tape *un)
12205 {
12206 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
12207 
12208 	ASSERT(mutex_owned(ST_MUTEX));
12209 
12210 	if (!un->un_flush_on_errors)
12211 		return;
12212 
12213 #ifdef FLUSH_ON_ERRORS
12214 
12215 	if (!un->un_mkr_pkt) {
12216 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
12217 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
12218 
12219 		/* we slept, so it must be there */
12220 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
12221 	}
12222 
12223 	st_transport(un, un->un_mkr_pkt);
12224 #endif
12225 }
12226 
12227 static char *
12228 st_print_scsi_cmd(char cmd)
12229 {
12230 	char tmp[64];
12231 	char *cpnt;
12232 
12233 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
12234 	/* tmp goes out of scope on return and caller sees garbage */
12235 	if (cpnt == tmp) {
12236 		cpnt = "Unknown Command";
12237 	}
12238 	return (cpnt);
12239 }
12240 
12241 static void
12242 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
12243     char *title, char *cdb)
12244 {
12245 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
12246 	char buf[256];
12247 	struct scsi_tape *un;
12248 	int instance = ddi_get_instance(dip);
12249 
12250 	un = ddi_get_soft_state(st_state, instance);
12251 
12252 	ST_FUNC(dip, st_print_cdb);
12253 
12254 	/* force one line output so repeated commands are printed once */
12255 	if ((st_debug & 0x180) == 0x100) {
12256 		scsi_log(dip, label, level, "node %s cmd %s\n",
12257 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
12258 		return;
12259 	}
12260 
12261 	/* force one line output so repeated CDB's are printed once */
12262 	if ((st_debug & 0x180) == 0x80) {
12263 		st_clean_print(dip, label, level, NULL, cdb, len);
12264 	} else {
12265 		(void) sprintf(buf, "%s for cmd(%s)", title,
12266 		    st_print_scsi_cmd(*cdb));
12267 		st_clean_print(dip, label, level, buf, cdb, len);
12268 	}
12269 }
12270 
12271 static void
12272 st_clean_print(dev_info_t *dev, char *label, uint_t level,
12273     char *title, char *data, int len)
12274 {
12275 	int	i;
12276 	int 	c;
12277 	char	*format;
12278 	char	buf[256];
12279 	uchar_t	byte;
12280 
12281 	ST_FUNC(dev, st_clean_print);
12282 
12283 
12284 	if (title) {
12285 		(void) sprintf(buf, "%s:\n", title);
12286 		scsi_log(dev, label, level, "%s", buf);
12287 		level = CE_CONT;
12288 	}
12289 
12290 	for (i = 0; i < len; ) {
12291 		buf[0] = 0;
12292 		for (c = 0; c < 8 && i < len; c++, i++) {
12293 			byte = (uchar_t)data[i];
12294 			if (byte < 0x10)
12295 				format = "0x0%x ";
12296 			else
12297 				format = "0x%x ";
12298 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
12299 		}
12300 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
12301 
12302 		scsi_log(dev, label, level, "%s\n", buf);
12303 		level = CE_CONT;
12304 	}
12305 }
12306 
12307 /*
12308  * Conditionally enabled debugging
12309  */
12310 #ifdef	STDEBUG
12311 static void
12312 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
12313 {
12314 	char tmpbuf[64];
12315 
12316 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
12317 
12318 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12319 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
12320 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
12321 	    count, count,
12322 	    wait == ASYNC_CMD ? "a" : "");
12323 }
12324 #endif	/* STDEBUG */
12325 
12326 /*
12327  * Returns pointer to name of minor node name of device 'dev'.
12328  */
12329 static char *
12330 st_dev_name(dev_t dev)
12331 {
12332 	struct scsi_tape *un;
12333 	const char density[] = { 'l', 'm', 'h', 'c' };
12334 	static char name[32];
12335 	minor_t minor;
12336 	int instance;
12337 	int nprt = 0;
12338 
12339 	minor = getminor(dev);
12340 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
12341 	un = ddi_get_soft_state(st_state, instance);
12342 	if (un) {
12343 		ST_FUNC(ST_DEVINFO, st_dev_name);
12344 	}
12345 
12346 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
12347 
12348 	if (minor & MT_BSD) {
12349 		name[++nprt] = 'b';
12350 	}
12351 
12352 	if (minor & MT_NOREWIND) {
12353 		name[++nprt] = 'n';
12354 	}
12355 
12356 	/* NULL terminator */
12357 	name[++nprt] = 0;
12358 
12359 	return (name);
12360 }
12361 
12362 /*
12363  * Soft error reporting, so far unique to each drive
12364  *
12365  * Currently supported: exabyte and DAT soft error reporting
12366  */
12367 static int
12368 st_report_exabyte_soft_errors(dev_t dev, int flag)
12369 {
12370 	uchar_t *sensep;
12371 	int amt;
12372 	int rval = 0;
12373 	char cdb[CDB_GROUP0], *c = cdb;
12374 	struct uscsi_cmd *com;
12375 
12376 	GET_SOFT_STATE(dev);
12377 
12378 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
12379 
12380 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12381 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
12382 	    dev, flag);
12383 
12384 	ASSERT(mutex_owned(ST_MUTEX));
12385 
12386 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12387 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
12388 
12389 	*c++ = SCMD_REQUEST_SENSE;
12390 	*c++ = 0;
12391 	*c++ = 0;
12392 	*c++ = 0;
12393 	*c++ = TAPE_SENSE_LENGTH;
12394 	/*
12395 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
12396 	 */
12397 	*c   = (char)0x80;
12398 
12399 	com->uscsi_cdb = cdb;
12400 	com->uscsi_cdblen = CDB_GROUP0;
12401 	com->uscsi_bufaddr = (caddr_t)sensep;
12402 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
12403 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12404 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12405 
12406 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12407 	if (rval || com->uscsi_status) {
12408 		goto done;
12409 	}
12410 
12411 	/*
12412 	 * was there enough data?
12413 	 */
12414 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
12415 
12416 	if ((amt >= 19) && un->un_kbytes_xferred) {
12417 		uint_t count, error_rate;
12418 		uint_t rate;
12419 
12420 		if (sensep[21] & CLN) {
12421 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12422 			    "Periodic head cleaning required");
12423 		}
12424 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
12425 			goto done;
12426 		}
12427 		/*
12428 		 * check if soft error reporting needs to be done.
12429 		 */
12430 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
12431 		count &= 0xffffff;
12432 		error_rate = (count * 100)/un->un_kbytes_xferred;
12433 
12434 #ifdef	STDEBUG
12435 		if (st_soft_error_report_debug) {
12436 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12437 			    "Exabyte Soft Error Report:\n");
12438 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12439 			    "read/write error counter: %d\n", count);
12440 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12441 			    "number of bytes transferred: %dK\n",
12442 			    un->un_kbytes_xferred);
12443 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12444 			    "error_rate: %d%%\n", error_rate);
12445 
12446 			if (amt >= 22) {
12447 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12448 				    "unit sense: 0x%b 0x%b 0x%b\n",
12449 				    sensep[19], SENSE_19_BITS,
12450 				    sensep[20], SENSE_20_BITS,
12451 				    sensep[21], SENSE_21_BITS);
12452 			}
12453 			if (amt >= 27) {
12454 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12455 				    "tracking retry counter: %d\n",
12456 				    sensep[26]);
12457 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12458 				    "read/write retry counter: %d\n",
12459 				    sensep[27]);
12460 			}
12461 		}
12462 #endif
12463 
12464 		if (flag & FWRITE) {
12465 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
12466 		} else {
12467 			rate = EXABYTE_READ_ERROR_THRESHOLD;
12468 		}
12469 		if (error_rate >= rate) {
12470 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12471 			    "Soft error rate (%d%%) during %s was too high",
12472 			    error_rate,
12473 			    ((flag & FWRITE) ? wrg_str : rdg_str));
12474 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12475 			    "Please, replace tape cartridge\n");
12476 		}
12477 	}
12478 
12479 done:
12480 	kmem_free(com, sizeof (*com));
12481 	kmem_free(sensep, TAPE_SENSE_LENGTH);
12482 
12483 	if (rval != 0) {
12484 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12485 		    "exabyte soft error reporting failed\n");
12486 	}
12487 	return (rval);
12488 }
12489 
12490 /*
12491  * this is very specific to Archive 4mm dat
12492  */
12493 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
12494 
12495 static int
12496 st_report_dat_soft_errors(dev_t dev, int flag)
12497 {
12498 	uchar_t *sensep;
12499 	int amt, i;
12500 	int rval = 0;
12501 	char cdb[CDB_GROUP1], *c = cdb;
12502 	struct uscsi_cmd *com;
12503 	struct scsi_arq_status status;
12504 
12505 	GET_SOFT_STATE(dev);
12506 
12507 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
12508 
12509 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12510 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12511 
12512 	ASSERT(mutex_owned(ST_MUTEX));
12513 
12514 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12515 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12516 
12517 	*c++ = SCMD_LOG_SENSE_G1;
12518 	*c++ = 0;
12519 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
12520 	*c++ = 0;
12521 	*c++ = 0;
12522 	*c++ = 0;
12523 	*c++ = 2;
12524 	*c++ = 0;
12525 	*c++ = (char)LOG_SENSE_LENGTH;
12526 	*c   = 0;
12527 	com->uscsi_cdb    = cdb;
12528 	com->uscsi_cdblen  = CDB_GROUP1;
12529 	com->uscsi_bufaddr = (caddr_t)sensep;
12530 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
12531 	com->uscsi_rqlen = sizeof (status);
12532 	com->uscsi_rqbuf = (caddr_t)&status;
12533 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
12534 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12535 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12536 	if (rval) {
12537 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12538 		    "DAT soft error reporting failed\n");
12539 	}
12540 	if (rval || com->uscsi_status) {
12541 		goto done;
12542 	}
12543 
12544 	/*
12545 	 * was there enough data?
12546 	 */
12547 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
12548 
12549 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
12550 		int total, retries, param_code;
12551 
12552 		total = -1;
12553 		retries = -1;
12554 		amt = sensep[3] + 4;
12555 
12556 
12557 #ifdef STDEBUG
12558 		if (st_soft_error_report_debug) {
12559 			(void) printf("logsense:");
12560 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
12561 				if (i % 16 == 0) {
12562 					(void) printf("\t\n");
12563 				}
12564 				(void) printf(" %x", sensep[i]);
12565 			}
12566 			(void) printf("\n");
12567 		}
12568 #endif
12569 
12570 		/*
12571 		 * parse the param_codes
12572 		 */
12573 		if (sensep[0] == 2 || sensep[0] == 3) {
12574 			for (i = 4; i < amt; i++) {
12575 				param_code = (sensep[i++] << 8);
12576 				param_code += sensep[i++];
12577 				i++; /* skip control byte */
12578 				if (param_code == 5) {
12579 					if (sensep[i++] == 4) {
12580 						total = (sensep[i++] << 24);
12581 						total += (sensep[i++] << 16);
12582 						total += (sensep[i++] << 8);
12583 						total += sensep[i];
12584 					}
12585 				} else if (param_code == 0x8007) {
12586 					if (sensep[i++] == 2) {
12587 						retries = sensep[i++] << 8;
12588 						retries += sensep[i];
12589 					}
12590 				} else {
12591 					i += sensep[i];
12592 				}
12593 			}
12594 		}
12595 
12596 		/*
12597 		 * if the log sense returned valid numbers then determine
12598 		 * the read and write error thresholds based on the amount of
12599 		 * data transferred
12600 		 */
12601 
12602 		if (total > 0 && retries > 0) {
12603 			short normal_retries = 0;
12604 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12605 			    "total xferred (%s) =%x, retries=%x\n",
12606 			    ((flag & FWRITE) ? wrg_str : rdg_str),
12607 			    total, retries);
12608 
12609 			if (flag & FWRITE) {
12610 				if (total <=
12611 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
12612 					normal_retries =
12613 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
12614 				} else {
12615 					normal_retries =
12616 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
12617 				}
12618 			} else {
12619 				if (total <=
12620 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
12621 					normal_retries =
12622 					    DAT_SMALL_READ_ERROR_THRESHOLD;
12623 				} else {
12624 					normal_retries =
12625 					    DAT_LARGE_READ_ERROR_THRESHOLD;
12626 				}
12627 			}
12628 
12629 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12630 			"normal retries=%d\n", normal_retries);
12631 
12632 			if (retries >= normal_retries) {
12633 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12634 				    "Soft error rate (retries = %d) during "
12635 				    "%s was too high",  retries,
12636 				    ((flag & FWRITE) ? wrg_str : rdg_str));
12637 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12638 				    "Periodic head cleaning required "
12639 				    "and/or replace tape cartridge\n");
12640 			}
12641 
12642 		} else if (total == -1 || retries == -1) {
12643 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12644 			    "log sense parameter code does not make sense\n");
12645 		}
12646 	}
12647 
12648 	/*
12649 	 * reset all values
12650 	 */
12651 	c = cdb;
12652 	*c++ = SCMD_LOG_SELECT_G1;
12653 	*c++ = 2;	/* this resets all values */
12654 	*c++ = (char)0xc0;
12655 	*c++ = 0;
12656 	*c++ = 0;
12657 	*c++ = 0;
12658 	*c++ = 0;
12659 	*c++ = 0;
12660 	*c++ = 0;
12661 	*c   = 0;
12662 	com->uscsi_bufaddr = NULL;
12663 	com->uscsi_buflen  = 0;
12664 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
12665 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12666 	if (rval) {
12667 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12668 		    "DAT soft error reset failed\n");
12669 	}
12670 done:
12671 	kmem_free(com, sizeof (*com));
12672 	kmem_free(sensep, LOG_SENSE_LENGTH);
12673 	return (rval);
12674 }
12675 
12676 static int
12677 st_report_soft_errors(dev_t dev, int flag)
12678 {
12679 	GET_SOFT_STATE(dev);
12680 
12681 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
12682 
12683 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12684 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12685 
12686 	ASSERT(mutex_owned(ST_MUTEX));
12687 
12688 	switch (un->un_dp->type) {
12689 	case ST_TYPE_EXB8500:
12690 	case ST_TYPE_EXABYTE:
12691 		return (st_report_exabyte_soft_errors(dev, flag));
12692 		/*NOTREACHED*/
12693 	case ST_TYPE_PYTHON:
12694 		return (st_report_dat_soft_errors(dev, flag));
12695 		/*NOTREACHED*/
12696 	default:
12697 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
12698 		return (-1);
12699 	}
12700 }
12701 
12702 /*
12703  * persistent error routines
12704  */
12705 
12706 /*
12707  * enable persistent errors, and set the throttle appropriately, checking
12708  * for flush-on-errors capability
12709  */
12710 static void
12711 st_turn_pe_on(struct scsi_tape *un)
12712 {
12713 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
12714 
12715 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
12716 	ASSERT(mutex_owned(ST_MUTEX));
12717 
12718 	un->un_persistence = 1;
12719 
12720 	/*
12721 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
12722 	 * enabled.  This will simplify the error handling for request senses
12723 	 */
12724 
12725 	if (un->un_arq_enabled && un->un_untagged_qing) {
12726 		uchar_t f_o_e;
12727 
12728 		mutex_exit(ST_MUTEX);
12729 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
12730 		    1 : 0;
12731 		mutex_enter(ST_MUTEX);
12732 
12733 		un->un_flush_on_errors = f_o_e;
12734 	} else {
12735 		un->un_flush_on_errors = 0;
12736 	}
12737 
12738 	if (un->un_flush_on_errors)
12739 		un->un_max_throttle = (uchar_t)st_max_throttle;
12740 	else
12741 		un->un_max_throttle = 1;
12742 
12743 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
12744 		un->un_max_throttle = 1;
12745 
12746 	/* this will send a marker pkt */
12747 	st_clear_pe(un);
12748 }
12749 
12750 /*
12751  * This turns persistent errors permanently off
12752  */
12753 static void
12754 st_turn_pe_off(struct scsi_tape *un)
12755 {
12756 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
12757 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
12758 	ASSERT(mutex_owned(ST_MUTEX));
12759 
12760 	/* turn it off for good */
12761 	un->un_persistence = 0;
12762 
12763 	/* this will send a marker pkt */
12764 	st_clear_pe(un);
12765 
12766 	/* turn off flush on error capability, if enabled */
12767 	if (un->un_flush_on_errors) {
12768 		mutex_exit(ST_MUTEX);
12769 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
12770 		mutex_enter(ST_MUTEX);
12771 	}
12772 
12773 
12774 	un->un_flush_on_errors = 0;
12775 }
12776 
12777 /*
12778  * This clear persistent errors, allowing more commands through, and also
12779  * sending a marker packet.
12780  */
12781 static void
12782 st_clear_pe(struct scsi_tape *un)
12783 {
12784 	ST_FUNC(ST_DEVINFO, st_clear_pe);
12785 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
12786 	ASSERT(mutex_owned(ST_MUTEX));
12787 
12788 	un->un_persist_errors = 0;
12789 	un->un_throttle = un->un_last_throttle = 1;
12790 	un->un_errno = 0;
12791 	st_hba_unflush(un);
12792 }
12793 
12794 /*
12795  * This will flag persistent errors, shutting everything down, if the
12796  * application had enabled persistent errors via MTIOCPERSISTENT
12797  */
12798 static void
12799 st_set_pe_flag(struct scsi_tape *un)
12800 {
12801 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
12802 	ASSERT(mutex_owned(ST_MUTEX));
12803 
12804 	if (un->un_persistence) {
12805 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
12806 		un->un_persist_errors = 1;
12807 		un->un_throttle = un->un_last_throttle = 0;
12808 		cv_broadcast(&un->un_sbuf_cv);
12809 	}
12810 }
12811 
12812 static int
12813 st_do_reserve(struct scsi_tape *un)
12814 {
12815 	int rval;
12816 	int was_lost = un->un_rsvd_status & ST_LOST_RESERVE;
12817 
12818 	ST_FUNC(ST_DEVINFO, st_do_reserve);
12819 
12820 	/*
12821 	 * Issue a Throw-Away reserve command to clear the
12822 	 * check condition.
12823 	 * If the current behaviour of reserve/release is to
12824 	 * hold reservation across opens , and if a Bus reset
12825 	 * has been issued between opens then this command
12826 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
12827 	 * In this case return an EACCES so that user knows that
12828 	 * reservation has been lost in between opens.
12829 	 * If this error is not returned and we continue with
12830 	 * successful open , then user may think position of the
12831 	 * tape is still the same but inreality we would rewind the
12832 	 * tape and continue from BOT.
12833 	 */
12834 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12835 	if (rval) {
12836 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
12837 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
12838 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
12839 			un->un_errno = EACCES;
12840 			return (EACCES);
12841 		}
12842 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12843 	}
12844 	if (rval == 0) {
12845 		un->un_rsvd_status |= ST_INIT_RESERVE;
12846 	}
12847 	if (was_lost) {
12848 		un->un_running.pmode = invalid;
12849 	}
12850 
12851 	return (rval);
12852 }
12853 
12854 static int
12855 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb)
12856 {
12857 	int rval;
12858 	cmd_attribute const *attrib;
12859 
12860 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
12861 
12862 	/*
12863 	 * If already reserved no need to do it again.
12864 	 * Also if Reserve and Release are disabled Just return.
12865 	 */
12866 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12867 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12868 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12869 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12870 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
12871 		    st_print_scsi_cmd((uchar_t)cdb[0]));
12872 		return (0);
12873 	}
12874 
12875 	/* See if command is on the list */
12876 	attrib = st_lookup_cmd_attribute(cdb[0]);
12877 
12878 	if (attrib == NULL) {
12879 		rval = 1; /* Not found, when in doubt reserve */
12880 	} else if ((attrib->requires_reserve) != 0) {
12881 		rval = 1;
12882 	} else if ((attrib->reserve_byte) != 0) {
12883 		/*
12884 		 * cmd is on list.
12885 		 * if byte is zero always allowed.
12886 		 */
12887 		rval = 1;
12888 	} else if (((cdb[attrib->reserve_byte]) &
12889 	    (attrib->reserve_mask)) != 0) {
12890 		rval = 1;
12891 	} else {
12892 		rval = 0;
12893 	}
12894 
12895 	if (rval) {
12896 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12897 		    "Command %s requires reservation",
12898 		    st_print_scsi_cmd(cdb[0]));
12899 
12900 		rval = st_do_reserve(un);
12901 	}
12902 
12903 	return (rval);
12904 }
12905 
12906 static int
12907 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
12908 {
12909 	int rval;
12910 	cmd_attribute const *attrib;
12911 
12912 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
12913 
12914 	/*
12915 	 * Do not reserve when already reserved, when not supported or when
12916 	 * auto-rewinding on device closure.
12917 	 */
12918 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12919 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12920 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE) ||
12921 	    ((un->un_state == ST_STATE_CLOSING) && (cmd == SCMD_REWIND))) {
12922 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12923 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
12924 		    st_print_scsi_cmd(cmd));
12925 		return (0);
12926 	}
12927 
12928 	/* search for this command on the list */
12929 	attrib = st_lookup_cmd_attribute(cmd);
12930 
12931 	if (attrib == NULL) {
12932 		rval = 1; /* Not found, when in doubt reserve */
12933 	} else if ((attrib->requires_reserve) != 0) {
12934 		rval = 1;
12935 	} else if ((attrib->reserve_byte) != 0) {
12936 		/*
12937 		 * cmd is on list.
12938 		 * if byte is zero always allowed.
12939 		 */
12940 		rval = 1;
12941 	} else if (((attrib->reserve_mask) & cnt) != 0) {
12942 		rval = 1;
12943 	} else {
12944 		rval = 0;
12945 	}
12946 
12947 	if (rval) {
12948 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12949 		    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
12950 
12951 		rval = st_do_reserve(un);
12952 	}
12953 
12954 	return (rval);
12955 }
12956 
12957 static int
12958 st_reserve_release(struct scsi_tape *un, int cmd, ubufunc_t ubf)
12959 {
12960 	struct uscsi_cmd	uscsi_cmd;
12961 	int			rval;
12962 	char			cdb[CDB_GROUP0];
12963 	struct scsi_arq_status	stat;
12964 
12965 
12966 
12967 	ST_FUNC(ST_DEVINFO, st_reserve_release);
12968 
12969 	ASSERT(mutex_owned(ST_MUTEX));
12970 
12971 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12972 	    "st_reserve_release: %s \n",
12973 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
12974 
12975 	bzero(&cdb, CDB_GROUP0);
12976 	if (cmd == ST_RELEASE) {
12977 		cdb[0] = SCMD_RELEASE;
12978 	} else {
12979 		cdb[0] = SCMD_RESERVE;
12980 	}
12981 	bzero(&uscsi_cmd, sizeof (struct uscsi_cmd));
12982 	uscsi_cmd.uscsi_flags = USCSI_WRITE | USCSI_RQENABLE;
12983 	uscsi_cmd.uscsi_cdb = cdb;
12984 	uscsi_cmd.uscsi_cdblen = CDB_GROUP0;
12985 	uscsi_cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
12986 	uscsi_cmd.uscsi_rqbuf = (caddr_t)&stat;
12987 	uscsi_cmd.uscsi_rqlen = sizeof (stat);
12988 
12989 	rval = ubf(un, &uscsi_cmd, FKIOCTL);
12990 
12991 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12992 	    "st_reserve_release: rval(1)=%d\n", rval);
12993 
12994 	if (rval) {
12995 		if (uscsi_cmd.uscsi_status == STATUS_RESERVATION_CONFLICT) {
12996 			rval = EACCES;
12997 		}
12998 		/*
12999 		 * dynamically turn off reserve/release support
13000 		 * in case of drives which do not support
13001 		 * reserve/release command(ATAPI drives).
13002 		 */
13003 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
13004 			if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
13005 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
13006 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13007 				    "Tape unit does not support "
13008 				    "reserve/release \n");
13009 			}
13010 			rval = 0;
13011 		}
13012 	}
13013 	return (rval);
13014 }
13015 
13016 static int
13017 st_take_ownership(struct scsi_tape *un, ubufunc_t ubf)
13018 {
13019 	int rval;
13020 
13021 	ST_FUNC(ST_DEVINFO, st_take_ownership);
13022 
13023 	ASSERT(mutex_owned(ST_MUTEX));
13024 
13025 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13026 	    "st_take_ownership: Entering ...\n");
13027 
13028 
13029 	rval = st_reserve_release(un, ST_RESERVE, ubf);
13030 	/*
13031 	 * XXX -> Should reset be done only if we get EACCES.
13032 	 * .
13033 	 */
13034 	if (rval) {
13035 		if (st_reset(un, RESET_LUN) == 0) {
13036 			return (EIO);
13037 		}
13038 		un->un_rsvd_status &=
13039 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
13040 
13041 		mutex_exit(ST_MUTEX);
13042 		delay(drv_usectohz(ST_RESERVATION_DELAY));
13043 		mutex_enter(ST_MUTEX);
13044 		/*
13045 		 * remove the check condition.
13046 		 */
13047 		(void) st_reserve_release(un, ST_RESERVE, ubf);
13048 		rval = st_reserve_release(un, ST_RESERVE, ubf);
13049 		if (rval != 0) {
13050 			if ((st_reserve_release(un, ST_RESERVE, ubf))
13051 			    != 0) {
13052 				rval = (un->un_rsvd_status &
13053 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
13054 				return (rval);
13055 			}
13056 		}
13057 		/*
13058 		 * Set tape state to ST_STATE_OFFLINE , in case if
13059 		 * the user wants to continue and start using
13060 		 * the tape.
13061 		 */
13062 		un->un_state = ST_STATE_OFFLINE;
13063 		un->un_rsvd_status |= ST_INIT_RESERVE;
13064 	}
13065 	return (rval);
13066 }
13067 
13068 static int
13069 st_create_errstats(struct scsi_tape *un, int instance)
13070 {
13071 	char	kstatname[KSTAT_STRLEN];
13072 
13073 	ST_FUNC(ST_DEVINFO, st_create_errstats);
13074 
13075 	/*
13076 	 * Create device error kstats
13077 	 */
13078 
13079 	if (un->un_errstats == (kstat_t *)0) {
13080 		(void) sprintf(kstatname, "st%d,err", instance);
13081 		un->un_errstats = kstat_create("sterr", instance, kstatname,
13082 		    "device_error", KSTAT_TYPE_NAMED,
13083 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
13084 		    KSTAT_FLAG_PERSISTENT);
13085 
13086 		if (un->un_errstats) {
13087 			struct st_errstats	*stp;
13088 
13089 			stp = (struct st_errstats *)un->un_errstats->ks_data;
13090 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
13091 			    KSTAT_DATA_ULONG);
13092 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
13093 			    KSTAT_DATA_ULONG);
13094 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
13095 			    KSTAT_DATA_ULONG);
13096 			kstat_named_init(&stp->st_vid, "Vendor",
13097 			    KSTAT_DATA_CHAR);
13098 			kstat_named_init(&stp->st_pid, "Product",
13099 			    KSTAT_DATA_CHAR);
13100 			kstat_named_init(&stp->st_revision, "Revision",
13101 			    KSTAT_DATA_CHAR);
13102 			kstat_named_init(&stp->st_serial, "Serial No",
13103 			    KSTAT_DATA_CHAR);
13104 			un->un_errstats->ks_private = un;
13105 			un->un_errstats->ks_update = nulldev;
13106 			kstat_install(un->un_errstats);
13107 			/*
13108 			 * Fill in the static data
13109 			 */
13110 			(void) strncpy(&stp->st_vid.value.c[0],
13111 			    ST_INQUIRY->inq_vid, 8);
13112 			/*
13113 			 * XXX:  Emulex MT-02 (and emulators) predates
13114 			 *	 SCSI-1 and has no vid & pid inquiry data.
13115 			 */
13116 			if (ST_INQUIRY->inq_len != 0) {
13117 				(void) strncpy(&stp->st_pid.value.c[0],
13118 				    ST_INQUIRY->inq_pid, 16);
13119 				(void) strncpy(&stp->st_revision.value.c[0],
13120 				    ST_INQUIRY->inq_revision, 4);
13121 			}
13122 		}
13123 	}
13124 	return (0);
13125 }
13126 
13127 static int
13128 st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos)
13129 {
13130 	int rval;
13131 	bufunc_t bf = (ubf == st_uscsi_rcmd) ? st_rcmd : st_cmd;
13132 
13133 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
13134 
13135 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
13136 	ASSERT(mutex_owned(ST_MUTEX));
13137 
13138 	/* Can't restore an invalid position */
13139 	if (pos->pmode == invalid) {
13140 		return (4);
13141 	}
13142 
13143 	/*
13144 	 * Assumtions:
13145 	 *	If a position was read and is in logical position mode.
13146 	 *	If a drive supports read position it supports locate.
13147 	 *	If the read position type is not NO_POS. even though
13148 	 *	   a read position make not have been attemped yet.
13149 	 *
13150 	 *	The drive can locate to the position.
13151 	 */
13152 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
13153 		/*
13154 		 * If position mode is logical or legacy mode try
13155 		 * to locate there as it is faster.
13156 		 * If it fails try the old way.
13157 		 */
13158 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13159 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
13160 		    pos->lgclblkno);
13161 
13162 		if (st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
13163 		    pos->lgclblkno, pos->partition) == 0) {
13164 			/* Assume we are there copy rest of position back */
13165 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
13166 				COPY_POS(&un->un_pos, pos);
13167 			}
13168 			return (0);
13169 		}
13170 
13171 		/*
13172 		 * If logical block locate failed to restore a logical
13173 		 * position, can't recover.
13174 		 */
13175 		if (pos->pmode == logical) {
13176 			return (-1);
13177 		}
13178 	}
13179 
13180 
13181 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13182 	    "Restoring tape position at fileno=%x, blkno=%x....",
13183 	    pos->fileno, pos->blkno);
13184 
13185 	/*
13186 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
13187 	 * so as not to rewind tape on RESETS: Gee, Has life ever
13188 	 * been simple in tape land ?
13189 	 */
13190 	rval = bf(un, SCMD_REWIND, 0, SYNC_CMD);
13191 	if (rval) {
13192 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
13193 		    "Failed to restore the last file and block position: In"
13194 		    " this state, Tape will be loaded at BOT during next open");
13195 		un->un_pos.pmode = invalid;
13196 		return (rval);
13197 	}
13198 
13199 	/* If the position was as the result of back space file */
13200 	if (pos->blkno > (INF / 2)) {
13201 		/* Go one extra file forward */
13202 		pos->fileno++;
13203 		/* Figure how many blocks to back into the previous file */
13204 		pos->blkno = -(INF - pos->blkno);
13205 	}
13206 
13207 	/* Go to requested fileno */
13208 	if (pos->fileno) {
13209 		rval = st_cmd(un, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
13210 		if (rval) {
13211 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13212 			    "Failed to restore the last file position: In this "
13213 			    " state, Tape will be loaded at BOT during next"
13214 			    " open %d", __LINE__);
13215 			un->un_pos.pmode = invalid;
13216 			pos->pmode = invalid;
13217 			return (rval);
13218 		}
13219 	}
13220 
13221 	/*
13222 	 * If backing into a file we already did an extra file forward.
13223 	 * Now we have to back over the filemark to get to the end of
13224 	 * the previous file. The blkno has been ajusted to a negative
13225 	 * value so we will get to the expected location.
13226 	 */
13227 	if (pos->blkno) {
13228 		rval = bf(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
13229 		if (rval) {
13230 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13231 			    "Failed to restore the last file position: In this "
13232 			    " state, Tape will be loaded at BOT during next"
13233 			    " open %d", __LINE__);
13234 			un->un_pos.pmode = invalid;
13235 			pos->pmode = invalid;
13236 			return (rval);
13237 		}
13238 	}
13239 
13240 	/*
13241 	 * The position mode, block and fileno should be correct,
13242 	 * This updates eof and logical position information.
13243 	 */
13244 	un->un_pos.eof = pos->eof;
13245 	un->un_pos.lgclblkno = pos->lgclblkno;
13246 
13247 	return (0);
13248 }
13249 
13250 /*
13251  * check sense key, ASC, ASCQ in order to determine if the tape needs
13252  * to be ejected
13253  */
13254 
13255 static int
13256 st_check_asc_ascq(struct scsi_tape *un)
13257 {
13258 	struct scsi_extended_sense *sensep = ST_RQSENSE;
13259 	struct tape_failure_code   *code;
13260 
13261 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
13262 
13263 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
13264 		if ((code->key  == sensep->es_key) &&
13265 		    (code->add_code  == sensep->es_add_code) &&
13266 		    (code->qual_code == sensep->es_qual_code))
13267 			return (1);
13268 	}
13269 	return (0);
13270 }
13271 
13272 /*
13273  * st_logpage_supported() sends a Log Sense command with
13274  * page code = 0 = Supported Log Pages Page to the device,
13275  * to see whether the page 'page' is supported.
13276  * Return values are:
13277  * -1 if the Log Sense command fails
13278  * 0 if page is not supported
13279  * 1 if page is supported
13280  */
13281 
13282 static int
13283 st_logpage_supported(struct scsi_tape *un, uchar_t page)
13284 {
13285 	uchar_t *sp, *sensep;
13286 	unsigned length;
13287 	struct uscsi_cmd *com;
13288 	struct scsi_arq_status status;
13289 	int rval;
13290 	char cdb[CDB_GROUP1] = {
13291 		SCMD_LOG_SENSE_G1,
13292 		0,
13293 		SUPPORTED_LOG_PAGES_PAGE,
13294 		0,
13295 		0,
13296 		0,
13297 		0,
13298 		0,
13299 		(char)LOG_SENSE_LENGTH,
13300 		0
13301 	};
13302 
13303 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
13304 
13305 	ASSERT(mutex_owned(ST_MUTEX));
13306 
13307 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13308 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
13309 
13310 	com->uscsi_cdb = cdb;
13311 	com->uscsi_cdblen = CDB_GROUP1;
13312 	com->uscsi_bufaddr = (caddr_t)sensep;
13313 	com->uscsi_buflen = LOG_SENSE_LENGTH;
13314 	com->uscsi_rqlen = sizeof (status);
13315 	com->uscsi_rqbuf = (caddr_t)&status;
13316 	com->uscsi_flags =
13317 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13318 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13319 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13320 	if (rval || com->uscsi_status) {
13321 		/* uscsi-command failed */
13322 		rval = -1;
13323 	} else {
13324 
13325 		sp = sensep + 3;
13326 
13327 		for (length = *sp++; length > 0; length--, sp++) {
13328 
13329 			if (*sp == page) {
13330 				rval = 1;
13331 				break;
13332 			}
13333 		}
13334 	}
13335 	kmem_free(com, sizeof (struct uscsi_cmd));
13336 	kmem_free(sensep, LOG_SENSE_LENGTH);
13337 	return (rval);
13338 }
13339 
13340 
13341 /*
13342  * st_check_clean_bit() gets the status of the tape's cleaning bit.
13343  *
13344  * If the device does support the TapeAlert log page, then the cleaning bit
13345  * information will be read from this page. Otherwise we will see if one of
13346  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
13347  * the device, which means, that we can get the cleaning bit information via
13348  * a RequestSense command.
13349  * If both methods of getting cleaning bit information are not supported
13350  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
13351  * returns with
13352  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
13353  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
13354  * If the call to st_uscsi_cmd() to do the Log Sense or the Request Sense
13355  * command fails, or if the amount of Request Sense data is not enough, then
13356  *  st_check_clean_bit() returns with -1.
13357  */
13358 
13359 static int
13360 st_check_clean_bit(struct scsi_tape *un)
13361 {
13362 	int rval = 0;
13363 
13364 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
13365 
13366 	ASSERT(mutex_owned(ST_MUTEX));
13367 
13368 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
13369 		return (rval);
13370 	}
13371 
13372 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13373 
13374 		rval = st_logpage_supported(un, TAPE_SEQUENTIAL_PAGE);
13375 		if (rval == -1) {
13376 			return (0);
13377 		}
13378 		if (rval == 1) {
13379 
13380 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
13381 		}
13382 
13383 		rval = st_logpage_supported(un, TAPE_ALERT_PAGE);
13384 		if (rval == -1) {
13385 			return (0);
13386 		}
13387 		if (rval == 1) {
13388 
13389 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
13390 		}
13391 
13392 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13393 
13394 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
13395 		}
13396 	}
13397 
13398 	rval = 0;
13399 
13400 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
13401 
13402 		rval = st_check_sequential_clean_bit(un);
13403 		if (rval == -1) {
13404 			return (0);
13405 		}
13406 	}
13407 
13408 	if ((rval == 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
13409 
13410 		rval = st_check_alert_flags(un);
13411 		if (rval == -1) {
13412 			return (0);
13413 		}
13414 	}
13415 
13416 	if ((rval == 0) && (un->un_dp->options & ST_CLN_MASK)) {
13417 
13418 		rval = st_check_sense_clean_bit(un);
13419 		if (rval == -1) {
13420 			return (0);
13421 		}
13422 	}
13423 
13424 	/*
13425 	 * If found a supported means to check need to clean.
13426 	 */
13427 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
13428 
13429 		/*
13430 		 * head needs to be cleaned.
13431 		 */
13432 		if (rval & MTF_TAPE_HEAD_DIRTY) {
13433 
13434 			/*
13435 			 * Print log message only first time
13436 			 * found needing cleaned.
13437 			 */
13438 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
13439 
13440 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
13441 				    "Periodic head cleaning required");
13442 
13443 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
13444 			}
13445 
13446 		} else {
13447 
13448 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
13449 		}
13450 	}
13451 
13452 	return (rval);
13453 }
13454 
13455 
13456 static int
13457 st_check_sequential_clean_bit(struct scsi_tape *un)
13458 {
13459 	int rval;
13460 	int ix;
13461 	ushort_t parameter;
13462 	struct uscsi_cmd *cmd;
13463 	struct log_sequential_page *sp;
13464 	struct log_sequential_page_parameter *prm;
13465 	struct scsi_arq_status status;
13466 	char cdb[CDB_GROUP1] = {
13467 		SCMD_LOG_SENSE_G1,
13468 		0,
13469 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
13470 		0,
13471 		0,
13472 		0,
13473 		0,
13474 		(char)(sizeof (struct log_sequential_page) >> 8),
13475 		(char)(sizeof (struct log_sequential_page)),
13476 		0
13477 	};
13478 
13479 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
13480 
13481 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13482 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
13483 
13484 	cmd->uscsi_flags   =
13485 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13486 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13487 	cmd->uscsi_cdb	   = cdb;
13488 	cmd->uscsi_cdblen  = CDB_GROUP1;
13489 	cmd->uscsi_bufaddr = (caddr_t)sp;
13490 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
13491 	cmd->uscsi_rqlen   = sizeof (status);
13492 	cmd->uscsi_rqbuf   = (caddr_t)&status;
13493 
13494 	rval = st_uscsi_cmd(un, cmd, FKIOCTL);
13495 
13496 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
13497 
13498 		rval = -1;
13499 
13500 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
13501 
13502 		rval = -1;
13503 	}
13504 
13505 	prm = &sp->param[0];
13506 
13507 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
13508 
13509 		if (prm->log_param.length == 0) {
13510 			break;
13511 		}
13512 
13513 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
13514 		    (prm->log_param.pc_lo & 0xff));
13515 
13516 		if (parameter == SEQUENTIAL_NEED_CLN) {
13517 
13518 			rval = MTF_TAPE_CLN_SUPPORTED;
13519 			if (prm->param_value[prm->log_param.length - 1]) {
13520 
13521 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13522 				    "sequential log says head dirty\n");
13523 				rval |= MTF_TAPE_HEAD_DIRTY;
13524 			}
13525 		}
13526 		prm = (struct log_sequential_page_parameter *)
13527 		    &prm->param_value[prm->log_param.length];
13528 	}
13529 
13530 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13531 	kmem_free(sp,  sizeof (struct log_sequential_page));
13532 
13533 	return (rval);
13534 }
13535 
13536 
13537 static int
13538 st_check_alert_flags(struct scsi_tape *un)
13539 {
13540 	struct st_tape_alert *ta;
13541 	struct uscsi_cmd *com;
13542 	struct scsi_arq_status status;
13543 	unsigned ix, length;
13544 	int rval;
13545 	tape_alert_flags flag;
13546 	char cdb[CDB_GROUP1] = {
13547 		SCMD_LOG_SENSE_G1,
13548 		0,
13549 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
13550 		0,
13551 		0,
13552 		0,
13553 		0,
13554 		(char)(sizeof (struct st_tape_alert) >> 8),
13555 		(char)(sizeof (struct st_tape_alert)),
13556 		0
13557 	};
13558 
13559 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
13560 
13561 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13562 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
13563 
13564 	com->uscsi_cdb = cdb;
13565 	com->uscsi_cdblen = CDB_GROUP1;
13566 	com->uscsi_bufaddr = (caddr_t)ta;
13567 	com->uscsi_buflen = sizeof (struct st_tape_alert);
13568 	com->uscsi_rqlen = sizeof (status);
13569 	com->uscsi_rqbuf = (caddr_t)&status;
13570 	com->uscsi_flags =
13571 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13572 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13573 
13574 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13575 
13576 	if (rval || com->uscsi_status || com->uscsi_resid) {
13577 
13578 		rval = -1; /* uscsi-command failed */
13579 
13580 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
13581 
13582 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13583 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
13584 		rval = -1;
13585 	}
13586 
13587 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
13588 
13589 
13590 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
13591 
13592 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13593 		    "TapeAlert length %d\n", length);
13594 	}
13595 
13596 
13597 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
13598 
13599 		/*
13600 		 * if rval is bad before the first pass don't bother
13601 		 */
13602 		if (ix == 0 && rval != 0) {
13603 
13604 			break;
13605 		}
13606 
13607 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
13608 		    ta->param[ix].log_param.pc_lo);
13609 
13610 		if ((ta->param[ix].param_value & 1) == 0) {
13611 			continue;
13612 		}
13613 		/*
13614 		 * check to see if current parameter is of interest.
13615 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
13616 		 */
13617 		if ((flag == TAF_CLEAN_NOW) ||
13618 		    (flag == TAF_CLEAN_PERIODIC) ||
13619 		    ((flag == CLEAN_FOR_ERRORS) &&
13620 		    (un->un_dp->type == ST_TYPE_STK9840))) {
13621 
13622 			rval = MTF_TAPE_CLN_SUPPORTED;
13623 
13624 
13625 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13626 			    "alert_page drive needs clean %d\n", flag);
13627 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
13628 			rval |= MTF_TAPE_HEAD_DIRTY;
13629 
13630 		} else if (flag == TAF_CLEANING_MEDIA) {
13631 
13632 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13633 			    "alert_page drive was cleaned\n");
13634 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
13635 		}
13636 
13637 	}
13638 
13639 	/*
13640 	 * Report it as dirty till we see it cleaned
13641 	 */
13642 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
13643 
13644 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13645 		    "alert_page still dirty\n");
13646 		rval |= MTF_TAPE_HEAD_DIRTY;
13647 	}
13648 
13649 	kmem_free(com, sizeof (struct uscsi_cmd));
13650 	kmem_free(ta,  sizeof (struct st_tape_alert));
13651 
13652 	return (rval);
13653 }
13654 
13655 
13656 static int
13657 st_check_sense_clean_bit(struct scsi_tape *un)
13658 {
13659 	uchar_t *sensep;
13660 	char cdb[CDB_GROUP0];
13661 	struct uscsi_cmd *com;
13662 	ushort_t byte_pos;
13663 	uchar_t bit_mask;
13664 	unsigned length;
13665 	int index;
13666 	int rval;
13667 
13668 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
13669 
13670 	/*
13671 	 * Since this tape does not support Tape Alert,
13672 	 * we now try to get the cleanbit status via
13673 	 * Request Sense.
13674 	 */
13675 
13676 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
13677 
13678 		index = 0;
13679 
13680 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
13681 
13682 		index = 1;
13683 
13684 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
13685 
13686 		index = 2;
13687 
13688 	} else {
13689 
13690 		return (-1);
13691 	}
13692 
13693 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
13694 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
13695 	length = byte_pos + 1;
13696 
13697 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13698 	sensep = kmem_zalloc(length, KM_SLEEP);
13699 
13700 	cdb[0] = SCMD_REQUEST_SENSE;
13701 	cdb[1] = 0;
13702 	cdb[2] = 0;
13703 	cdb[3] = 0;
13704 	cdb[4] = (char)length;
13705 	cdb[5] = 0;
13706 
13707 	com->uscsi_cdb = cdb;
13708 	com->uscsi_cdblen = CDB_GROUP0;
13709 	com->uscsi_bufaddr = (caddr_t)sensep;
13710 	com->uscsi_buflen = length;
13711 	com->uscsi_flags =
13712 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13713 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13714 
13715 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13716 
13717 	if (rval || com->uscsi_status || com->uscsi_resid) {
13718 
13719 		rval = -1;
13720 
13721 	} else {
13722 
13723 		rval = MTF_TAPE_CLN_SUPPORTED;
13724 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
13725 
13726 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13727 			    "sense data says head dirty\n");
13728 			rval |= MTF_TAPE_HEAD_DIRTY;
13729 		}
13730 	}
13731 
13732 	kmem_free(com, sizeof (struct uscsi_cmd));
13733 	kmem_free(sensep, length);
13734 	return (rval);
13735 }
13736 
13737 /*
13738  * st_clear_unit_attention
13739  *
13740  *  	run test unit ready's to clear out outstanding
13741  * 	unit attentions.
13742  * 	returns zero for SUCCESS or the errno from st_cmd call
13743  */
13744 static int
13745 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
13746 {
13747 	int	i    = 0;
13748 	int	rval;
13749 
13750 	GET_SOFT_STATE(dev_instance);
13751 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
13752 
13753 	do {
13754 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
13755 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
13756 	return (rval);
13757 }
13758 
13759 static void
13760 st_calculate_timeouts(struct scsi_tape *un)
13761 {
13762 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
13763 
13764 	if (un->un_dp->non_motion_timeout == 0) {
13765 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13766 			un->un_dp->non_motion_timeout =
13767 			    st_io_time * st_long_timeout_x;
13768 		} else {
13769 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
13770 		}
13771 	}
13772 
13773 	if (un->un_dp->io_timeout == 0) {
13774 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13775 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
13776 		} else {
13777 			un->un_dp->io_timeout = (ushort_t)st_io_time;
13778 		}
13779 	}
13780 
13781 	if (un->un_dp->rewind_timeout == 0) {
13782 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13783 			un->un_dp->rewind_timeout =
13784 			    st_space_time * st_long_timeout_x;
13785 		} else {
13786 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
13787 		}
13788 	}
13789 
13790 	if (un->un_dp->space_timeout == 0) {
13791 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13792 			un->un_dp->space_timeout =
13793 			    st_space_time * st_long_timeout_x;
13794 		} else {
13795 			un->un_dp->space_timeout = (ushort_t)st_space_time;
13796 		}
13797 	}
13798 
13799 	if (un->un_dp->load_timeout == 0) {
13800 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13801 			un->un_dp->load_timeout =
13802 			    st_space_time * st_long_timeout_x;
13803 		} else {
13804 			un->un_dp->load_timeout = (ushort_t)st_space_time;
13805 		}
13806 	}
13807 
13808 	if (un->un_dp->unload_timeout == 0) {
13809 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13810 			un->un_dp->unload_timeout =
13811 			    st_space_time * st_long_timeout_x;
13812 		} else {
13813 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
13814 		}
13815 	}
13816 
13817 	if (un->un_dp->erase_timeout == 0) {
13818 		if (un->un_dp->options & ST_LONG_ERASE) {
13819 			un->un_dp->erase_timeout =
13820 			    st_space_time * st_long_space_time_x;
13821 		} else {
13822 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
13823 		}
13824 	}
13825 }
13826 
13827 
13828 static writablity
13829 st_is_not_wormable(struct scsi_tape *un)
13830 {
13831 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
13832 	return (RDWR);
13833 }
13834 
13835 static writablity
13836 st_is_hp_dat_tape_worm(struct scsi_tape *un)
13837 {
13838 	writablity wrt;
13839 
13840 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
13841 
13842 	/* Mode sense should be current */
13843 	if (un->un_mspl->media_type == 1) {
13844 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13845 		    "Drive has WORM media loaded\n");
13846 		wrt = WORM;
13847 	} else {
13848 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13849 		    "Drive has non WORM media loaded\n");
13850 		wrt = RDWR;
13851 	}
13852 	return (wrt);
13853 }
13854 
13855 #define	HP_DAT_INQUIRY 0x4A
13856 static writablity
13857 st_is_hp_dat_worm(struct scsi_tape *un)
13858 {
13859 	char *buf;
13860 	int result;
13861 	writablity wrt;
13862 
13863 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
13864 
13865 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
13866 
13867 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
13868 
13869 	if (result != 0) {
13870 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13871 		    "Read Standard Inquiry for WORM support failed");
13872 		wrt = FAILED;
13873 	} else if ((buf[40] & 1) == 0) {
13874 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13875 		    "Drive is NOT WORMable\n");
13876 		/* This drive doesn't support it so don't check again */
13877 		un->un_dp->options &= ~ST_WORMABLE;
13878 		wrt = RDWR;
13879 		un->un_wormable = st_is_not_wormable;
13880 	} else {
13881 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13882 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13883 		un->un_wormable = st_is_hp_dat_tape_worm;
13884 		wrt = un->un_wormable(un);
13885 	}
13886 
13887 	kmem_free(buf, HP_DAT_INQUIRY);
13888 
13889 	/*
13890 	 * If drive doesn't support it no point in checking further.
13891 	 */
13892 	return (wrt);
13893 }
13894 
13895 static writablity
13896 st_is_hp_lto_tape_worm(struct scsi_tape *un)
13897 {
13898 	writablity wrt;
13899 
13900 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
13901 
13902 	/* Mode sense should be current */
13903 	switch (un->un_mspl->media_type) {
13904 	case 0x00:
13905 		switch (un->un_mspl->density) {
13906 		case 0x40:
13907 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13908 			    "Drive has standard Gen I media loaded\n");
13909 			break;
13910 		case 0x42:
13911 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13912 			    "Drive has standard Gen II media loaded\n");
13913 			break;
13914 		case 0x44:
13915 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13916 			    "Drive has standard Gen III media loaded\n");
13917 			break;
13918 		case 0x46:
13919 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13920 			    "Drive has standard Gen IV media loaded\n");
13921 			break;
13922 		default:
13923 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13924 			    "Drive has standard unknown 0x%X media loaded\n",
13925 			    un->un_mspl->density);
13926 		}
13927 		wrt = RDWR;
13928 		break;
13929 	case 0x01:
13930 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13931 		    "Drive has WORM medium loaded\n");
13932 		wrt = WORM;
13933 		break;
13934 	case 0x80:
13935 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13936 		    "Drive has CD-ROM emulation medium loaded\n");
13937 		wrt = WORM;
13938 		break;
13939 	default:
13940 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13941 		    "Drive has an unexpected medium type 0x%X loaded\n",
13942 		    un->un_mspl->media_type);
13943 		wrt = RDWR;
13944 	}
13945 
13946 	return (wrt);
13947 }
13948 
13949 #define	LTO_REQ_INQUIRY 44
13950 static writablity
13951 st_is_hp_lto_worm(struct scsi_tape *un)
13952 {
13953 	char *buf;
13954 	int result;
13955 	writablity wrt;
13956 
13957 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
13958 
13959 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
13960 
13961 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
13962 
13963 	if (result != 0) {
13964 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13965 		    "Read Standard Inquiry for WORM support failed");
13966 		wrt = FAILED;
13967 	} else if ((buf[40] & 1) == 0) {
13968 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13969 		    "Drive is NOT WORMable\n");
13970 		/* This drive doesn't support it so don't check again */
13971 		un->un_dp->options &= ~ST_WORMABLE;
13972 		wrt = RDWR;
13973 		un->un_wormable = st_is_not_wormable;
13974 	} else {
13975 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13976 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13977 		un->un_wormable = st_is_hp_lto_tape_worm;
13978 		wrt = un->un_wormable(un);
13979 	}
13980 
13981 	kmem_free(buf, LTO_REQ_INQUIRY);
13982 
13983 	/*
13984 	 * If drive doesn't support it no point in checking further.
13985 	 */
13986 	return (wrt);
13987 }
13988 
13989 static writablity
13990 st_is_t10_worm_device(struct scsi_tape *un)
13991 {
13992 	writablity wrt;
13993 
13994 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
13995 
13996 	if (un->un_mspl->media_type == 0x3c) {
13997 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13998 		    "Drive has WORM media loaded\n");
13999 		wrt = WORM;
14000 	} else {
14001 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14002 		    "Drive has non WORM media loaded\n");
14003 		wrt = RDWR;
14004 	}
14005 	return (wrt);
14006 }
14007 
14008 #define	SEQ_CAP_PAGE	(char)0xb0
14009 static writablity
14010 st_is_t10_worm(struct scsi_tape *un)
14011 {
14012 	char *buf;
14013 	int result;
14014 	writablity wrt;
14015 
14016 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
14017 
14018 	buf = kmem_zalloc(6, KM_SLEEP);
14019 
14020 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
14021 
14022 	if (result != 0) {
14023 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14024 		    "Read Vitial Inquiry for Sequental Capability"
14025 		    " WORM support failed %x", result);
14026 		wrt = FAILED;
14027 	} else if ((buf[4] & 1) == 0) {
14028 		ASSERT(buf[1] == SEQ_CAP_PAGE);
14029 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14030 		    "Drive is NOT WORMable\n");
14031 		/* This drive doesn't support it so don't check again */
14032 		un->un_dp->options &= ~ST_WORMABLE;
14033 		wrt = RDWR;
14034 		un->un_wormable = st_is_not_wormable;
14035 	} else {
14036 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14037 		    "Drive supports WORM\n");
14038 		un->un_wormable = st_is_t10_worm_device;
14039 		wrt = un->un_wormable(un);
14040 	}
14041 
14042 	kmem_free(buf, 6);
14043 
14044 	return (wrt);
14045 }
14046 
14047 
14048 #define	STK_REQ_SENSE 26
14049 
14050 static writablity
14051 st_is_stk_worm(struct scsi_tape *un)
14052 {
14053 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
14054 	struct scsi_extended_sense *sense;
14055 	struct uscsi_cmd *cmd;
14056 	char *buf;
14057 	int result;
14058 	writablity wrt;
14059 
14060 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
14061 
14062 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14063 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
14064 	sense = (struct scsi_extended_sense *)buf;
14065 
14066 	cmd->uscsi_flags = USCSI_READ;
14067 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14068 	cmd->uscsi_cdb = &cdb[0];
14069 	cmd->uscsi_bufaddr = buf;
14070 	cmd->uscsi_buflen = STK_REQ_SENSE;
14071 	cmd->uscsi_cdblen = CDB_GROUP0;
14072 	cmd->uscsi_rqlen = 0;
14073 	cmd->uscsi_rqbuf = NULL;
14074 
14075 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14076 
14077 	if (result != 0 || cmd->uscsi_status != 0) {
14078 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14079 		    "Request Sense for WORM failed");
14080 		wrt = RDWR;
14081 	} else if (sense->es_add_len + 8 < 24) {
14082 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14083 		    "Drive didn't send enough sense data for WORM byte %d\n",
14084 		    sense->es_add_len + 8);
14085 		wrt = RDWR;
14086 		un->un_wormable = st_is_not_wormable;
14087 	} else if ((buf[24]) & 0x02) {
14088 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14089 		    "Drive has WORM tape loaded\n");
14090 		wrt = WORM;
14091 		un->un_wormable = st_is_stk_worm;
14092 	} else {
14093 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14094 		    "Drive has normal tape loaded\n");
14095 		wrt = RDWR;
14096 		un->un_wormable = st_is_stk_worm;
14097 	}
14098 
14099 	kmem_free(buf, STK_REQ_SENSE);
14100 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14101 	return (wrt);
14102 }
14103 
14104 #define	DLT_INQ_SZ 44
14105 
14106 static writablity
14107 st_is_dlt_tape_worm(struct scsi_tape *un)
14108 {
14109 	caddr_t buf;
14110 	int result;
14111 	writablity wrt;
14112 
14113 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
14114 
14115 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14116 
14117 	/* Read Attribute Media Type */
14118 
14119 	result = st_read_attributes(un, 0x0408, buf, 10, st_uscsi_cmd);
14120 
14121 	/*
14122 	 * If this quantum drive is attached via an HBA that cannot
14123 	 * support thr read attributes command return error in the
14124 	 * hope that someday they will support the t10 method.
14125 	 */
14126 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
14127 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14128 		    "Read Attribute Command for WORM Media detection is not "
14129 		    "supported on the HBA that this drive is attached to.");
14130 		wrt = RDWR;
14131 		un->un_wormable = st_is_not_wormable;
14132 		goto out;
14133 	}
14134 
14135 	if (result != 0) {
14136 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14137 		    "Read Attribute Command for WORM Media returned 0x%x",
14138 		    result);
14139 		wrt = RDWR;
14140 		un->un_dp->options &= ~ST_WORMABLE;
14141 		goto out;
14142 	}
14143 
14144 	if ((uchar_t)buf[9] == 0x80) {
14145 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14146 		    "Drive media is WORM\n");
14147 		wrt = WORM;
14148 	} else {
14149 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14150 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
14151 		wrt = RDWR;
14152 	}
14153 
14154 out:
14155 	kmem_free(buf, DLT_INQ_SZ);
14156 	return (wrt);
14157 }
14158 
14159 static writablity
14160 st_is_dlt_worm(struct scsi_tape *un)
14161 {
14162 	caddr_t buf;
14163 	int result;
14164 	writablity wrt;
14165 
14166 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
14167 
14168 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14169 
14170 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
14171 
14172 	if (result != 0) {
14173 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14174 		    "Read Vendor Specific Inquiry for WORM support failed");
14175 		wrt = RDWR;
14176 		goto out;
14177 	}
14178 
14179 	if ((buf[2] & 1) == 0) {
14180 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14181 		    "Drive is not WORMable\n");
14182 		wrt = RDWR;
14183 		un->un_dp->options &= ~ST_WORMABLE;
14184 		un->un_wormable = st_is_not_wormable;
14185 		goto out;
14186 	} else {
14187 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14188 		    "Drive is WORMable\n");
14189 		un->un_wormable = st_is_dlt_tape_worm;
14190 		wrt = un->un_wormable(un);
14191 	}
14192 out:
14193 	kmem_free(buf, DLT_INQ_SZ);
14194 
14195 	return (wrt);
14196 }
14197 
14198 typedef struct {
14199 	struct modeheader_seq header;
14200 #if defined(_BIT_FIELDS_LTOH) /* X86 */
14201 	uchar_t pagecode	:6,
14202 				:2;
14203 	uchar_t page_len;
14204 	uchar_t syslogalive	:2,
14205 		device		:1,
14206 		abs		:1,
14207 		ulpbot		:1,
14208 		prth		:1,
14209 		ponej		:1,
14210 		ait		:1;
14211 	uchar_t span;
14212 
14213 	uchar_t			:6,
14214 		worm		:1,
14215 		mic		:1;
14216 	uchar_t worm_cap	:1,
14217 				:7;
14218 	uint32_t		:32;
14219 #else /* SPARC */
14220 	uchar_t			:2,
14221 		pagecode	:6;
14222 	uchar_t page_len;
14223 	uchar_t ait		:1,
14224 		device		:1,
14225 		abs		:1,
14226 		ulpbot		:1,
14227 		prth		:1,
14228 		ponej		:1,
14229 		syslogalive	:2;
14230 	uchar_t span;
14231 	uchar_t mic		:1,
14232 		worm		:1,
14233 				:6;
14234 	uchar_t			:7,
14235 		worm_cap	:1;
14236 	uint32_t		:32;
14237 #endif
14238 }ait_dev_con;
14239 
14240 #define	AIT_DEV_PAGE 0x31
14241 static writablity
14242 st_is_sony_worm(struct scsi_tape *un)
14243 {
14244 	int result;
14245 	writablity wrt;
14246 	ait_dev_con *ait_conf;
14247 
14248 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14249 
14250 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
14251 
14252 	result = st_gen_mode_sense(un, st_uscsi_cmd, AIT_DEV_PAGE,
14253 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
14254 
14255 	if (result == 0) {
14256 
14257 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
14258 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14259 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
14260 			    ait_conf->pagecode, AIT_DEV_PAGE);
14261 			wrt = RDWR;
14262 			un->un_wormable = st_is_not_wormable;
14263 
14264 		} else if (ait_conf->worm_cap) {
14265 
14266 			un->un_wormable = st_is_sony_worm;
14267 
14268 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14269 			    "Drives is WORMable\n");
14270 			if (ait_conf->worm) {
14271 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14272 				    "Media is WORM\n");
14273 				wrt = WORM;
14274 			} else {
14275 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14276 				    "Media is not WORM\n");
14277 				wrt = RDWR;
14278 			}
14279 
14280 		} else {
14281 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14282 			    "Drives not is WORMable\n");
14283 			wrt = RDWR;
14284 			/* No further checking required */
14285 			un->un_dp->options &= ~ST_WORMABLE;
14286 		}
14287 
14288 	} else {
14289 
14290 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14291 		    "AIT device config mode sense page read command failed"
14292 		    " result = %d ", result);
14293 		wrt = FAILED;
14294 		un->un_wormable = st_is_not_wormable;
14295 	}
14296 
14297 	kmem_free(ait_conf, sizeof (ait_dev_con));
14298 	return (wrt);
14299 }
14300 
14301 static writablity
14302 st_is_drive_worm(struct scsi_tape *un)
14303 {
14304 	writablity wrt;
14305 
14306 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14307 
14308 	switch (un->un_dp->type) {
14309 	case MT_ISDLT:
14310 		wrt = st_is_dlt_worm(un);
14311 		break;
14312 
14313 	case MT_ISSTK9840:
14314 		wrt = st_is_stk_worm(un);
14315 		break;
14316 
14317 	case MT_IS8MM:
14318 	case MT_ISAIT:
14319 		wrt = st_is_sony_worm(un);
14320 		break;
14321 
14322 	case MT_LTO:
14323 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14324 			wrt = st_is_hp_lto_worm(un);
14325 		} else {
14326 			wrt = st_is_t10_worm(un);
14327 		}
14328 		break;
14329 
14330 	case MT_ISDAT:
14331 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14332 			wrt = st_is_hp_dat_worm(un);
14333 		} else {
14334 			wrt = st_is_t10_worm(un);
14335 		}
14336 		break;
14337 
14338 	default:
14339 		wrt = FAILED;
14340 		break;
14341 	}
14342 
14343 	/*
14344 	 * If any of the above failed try the t10 standard method.
14345 	 */
14346 	if (wrt == FAILED) {
14347 		wrt = st_is_t10_worm(un);
14348 	}
14349 
14350 	/*
14351 	 * Unknown method for detecting WORM media.
14352 	 */
14353 	if (wrt == FAILED) {
14354 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14355 		    "Unknown method for WORM media detection\n");
14356 		wrt = RDWR;
14357 		un->un_dp->options &= ~ST_WORMABLE;
14358 	}
14359 
14360 	return (wrt);
14361 }
14362 
14363 static int
14364 st_read_attributes(struct scsi_tape *un, uint16_t attribute, void *pnt,
14365     size_t size, ubufunc_t bufunc)
14366 {
14367 	char cdb[CDB_GROUP4];
14368 	int result;
14369 	struct uscsi_cmd *cmd;
14370 	struct scsi_arq_status status;
14371 
14372 	caddr_t buf = (caddr_t)pnt;
14373 
14374 	ST_FUNC(ST_DEVINFO, st_read_attributes);
14375 
14376 	if (un->un_sd->sd_inq->inq_ansi < 3) {
14377 		return (ENOTTY);
14378 	}
14379 
14380 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14381 
14382 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
14383 	cdb[1] = 0;
14384 	cdb[2] = 0;
14385 	cdb[3] = 0;
14386 	cdb[4] = 0;
14387 	cdb[5] = 0;
14388 	cdb[6] = 0;
14389 	cdb[7] = 0;
14390 	cdb[8] = (char)(attribute >> 8);
14391 	cdb[9] = (char)(attribute);
14392 	cdb[10] = (char)(size >> 24);
14393 	cdb[11] = (char)(size >> 16);
14394 	cdb[12] = (char)(size >> 8);
14395 	cdb[13] = (char)(size);
14396 	cdb[14] = 0;
14397 	cdb[15] = 0;
14398 
14399 
14400 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE | USCSI_DIAGNOSE;
14401 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14402 	cmd->uscsi_cdb = &cdb[0];
14403 	cmd->uscsi_bufaddr = (caddr_t)buf;
14404 	cmd->uscsi_buflen = size;
14405 	cmd->uscsi_cdblen = sizeof (cdb);
14406 	cmd->uscsi_rqlen = sizeof (status);
14407 	cmd->uscsi_rqbuf = (caddr_t)&status;
14408 
14409 	result = bufunc(un, cmd, FKIOCTL);
14410 
14411 	if (result != 0 || cmd->uscsi_status != 0) {
14412 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
14413 		    "st_read_attribute failed: result %d status %d\n",
14414 		    result, cmd->uscsi_status);
14415 		/*
14416 		 * If this returns invalid operation code don't try again.
14417 		 */
14418 		if (un->un_sd->sd_sense->es_key == KEY_ILLEGAL_REQUEST &&
14419 		    un->un_sd->sd_sense->es_add_code == 0x20) {
14420 			result = ENOTTY;
14421 		} else if (result == 0) {
14422 			result = EIO;
14423 		}
14424 
14425 	} else {
14426 
14427 		/*
14428 		 * The attribute retured should match the attribute requested.
14429 		 */
14430 		if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
14431 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14432 			    "st_read_attribute got wrong data back expected "
14433 			    "0x%x got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
14434 			st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14435 			    "bad? data", buf, size);
14436 			result = EIO;
14437 		}
14438 	}
14439 
14440 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14441 
14442 	return (result);
14443 }
14444 
14445 static int
14446 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
14447     uchar_t page)
14448 {
14449 	char cdb[CDB_GROUP0];
14450 	struct scsi_extended_sense *sense;
14451 	struct uscsi_cmd *cmd;
14452 	int result;
14453 
14454 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
14455 
14456 	cdb[0] = SCMD_INQUIRY;
14457 	cdb[1] = page ? 1 : 0;
14458 	cdb[2] = page;
14459 	cdb[3] = 0;
14460 	cdb[4] = size;
14461 	cdb[5] = 0;
14462 
14463 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14464 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
14465 
14466 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
14467 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14468 	cmd->uscsi_cdb = &cdb[0];
14469 	cmd->uscsi_bufaddr = dest;
14470 	cmd->uscsi_buflen = size;
14471 	cmd->uscsi_cdblen = CDB_GROUP0;
14472 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
14473 	cmd->uscsi_rqbuf = (caddr_t)sense;
14474 
14475 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14476 
14477 	if (result != 0 || cmd->uscsi_status != 0) {
14478 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14479 		    "st_get_special_inquiry() failed for page %x", page);
14480 		if (result == 0) {
14481 			result = EIO;
14482 		}
14483 	}
14484 
14485 	kmem_free(sense, sizeof (struct scsi_extended_sense));
14486 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14487 
14488 	return (result);
14489 }
14490 
14491 
14492 static int
14493 st_update_block_pos(struct scsi_tape *un, bufunc_t bf, int post_space)
14494 {
14495 	int rval = ENOTTY;
14496 	uchar_t status = un->un_status;
14497 	posmode previous_pmode = un->un_running.pmode;
14498 
14499 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
14500 
14501 	while (un->un_read_pos_type != NO_POS) {
14502 		rval = bf(un, SCMD_READ_POSITION, 32, SYNC_CMD);
14503 
14504 		/*
14505 		 * If read position command returned good status
14506 		 * Parse the data to see if the position can be interpreted.
14507 		 */
14508 		if ((rval == 0) &&
14509 		    ((rval = st_interpret_read_pos(un, &un->un_pos,
14510 		    un->un_read_pos_type, 32, (caddr_t)un->un_read_pos_data,
14511 		    post_space)) == 0)) {
14512 			/*
14513 			 * Update the running position as well if un_pos was
14514 			 * ok. But only if recovery is enabled.
14515 			 */
14516 			if (st_recov_sz != sizeof (recov_info)) {
14517 				break;
14518 			}
14519 			rval = st_interpret_read_pos(un, &un->un_running,
14520 			    un->un_read_pos_type, 32,
14521 			    (caddr_t)un->un_read_pos_data, post_space);
14522 			un->un_status = status;
14523 			break;
14524 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
14525 			un->un_running.pmode = previous_pmode;
14526 			continue;
14527 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
14528 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
14529 			    "st_update_block_pos() read position cmd 0x%x"
14530 			    " returned 0x%x un_status = %d",
14531 			    un->un_read_pos_type, rval, un->un_status);
14532 			/* ENOTTY means it read garbage. try something else. */
14533 			if (rval == ENOTTY) {
14534 				rval = EIO; /* so ENOTTY is not final rval */
14535 			} else {
14536 				break;
14537 			}
14538 		} else {
14539 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
14540 			    "st_update_block_pos() read position cmd %x"
14541 			    " returned %x", un->un_read_pos_type, rval);
14542 			un->un_running.pmode = previous_pmode;
14543 		}
14544 
14545 		switch (un->un_read_pos_type) {
14546 		case SHORT_POS:
14547 			un->un_read_pos_type = NO_POS;
14548 			break;
14549 
14550 		case LONG_POS:
14551 			un->un_read_pos_type = EXT_POS;
14552 			break;
14553 
14554 		case EXT_POS:
14555 			un->un_read_pos_type = SHORT_POS;
14556 			break;
14557 
14558 		default:
14559 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14560 			    "Unexpected read position type 0x%x",
14561 			    un->un_read_pos_type);
14562 		}
14563 		un->un_status = KEY_NO_SENSE;
14564 	}
14565 
14566 	return (rval);
14567 }
14568 
14569 static int
14570 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
14571 {
14572 	int result;
14573 	size_t d_sz;
14574 	caddr_t pos_info;
14575 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
14576 
14577 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
14578 
14579 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
14580 		return (0);
14581 	}
14582 
14583 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
14584 
14585 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14586 		    "bp_mapin_common() failed");
14587 
14588 		return (EIO);
14589 	}
14590 
14591 	d_sz = bp->b_bcount - bp->b_resid;
14592 	if (d_sz == 0) {
14593 		bp_mapout(bp);
14594 		return (EIO);
14595 	}
14596 
14597 	/*
14598 	 * Copy the buf to a double-word aligned memory that can hold the
14599 	 * tape_position_t data structure.
14600 	 */
14601 	if ((pos_info = kmem_alloc(d_sz, KM_NOSLEEP)) == NULL) {
14602 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14603 		    "kmem_alloc() failed");
14604 		bp_mapout(bp);
14605 		return (EIO);
14606 	}
14607 	bcopy(bp->b_un.b_addr, pos_info, d_sz);
14608 
14609 #ifdef STDEBUG
14610 	if ((st_debug & 0x7) > 2) {
14611 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14612 		    "st_get_read_pos() position info",
14613 		    pos_info, bp->b_bcount);
14614 	}
14615 #endif
14616 
14617 	result = st_interpret_read_pos(un, &un->un_pos, cmd->uscsi_cdb[1],
14618 	    d_sz, pos_info, 0);
14619 
14620 	COPY_POS(&un->un_running, &un->un_pos);
14621 
14622 	kmem_free(pos_info, d_sz);
14623 	bp_mapout(bp);
14624 
14625 	return (result);
14626 }
14627 
14628 #if defined(_BIG_ENDIAN)
14629 
14630 #define	FIX_ENDIAN16(x)
14631 #define	FIX_ENDIAN32(x)
14632 #define	FIX_ENDIAN64(x)
14633 
14634 #elif defined(_LITTLE_ENDIAN)
14635 
14636 static void
14637 st_swap16(uint16_t *val)
14638 {
14639 	uint16_t tmp;
14640 
14641 	tmp = (*val >>  8) & 0xff;
14642 	tmp |= (*val <<  8) & 0xff00;
14643 
14644 	*val = tmp;
14645 }
14646 
14647 static void
14648 st_swap32(uint32_t *val)
14649 {
14650 	uint32_t tmp;
14651 
14652 	tmp =  (*val >> 24) & 0xff;
14653 	tmp |= (*val >>  8) & 0xff00;
14654 	tmp |= (*val <<  8) & 0xff0000;
14655 	tmp |= (*val << 24) & 0xff000000;
14656 
14657 	*val = tmp;
14658 }
14659 
14660 static void
14661 st_swap64(uint64_t *val)
14662 {
14663 	uint32_t low;
14664 	uint32_t high;
14665 
14666 	low =  (uint32_t)(*val);
14667 	high = (uint32_t)(*val >> 32);
14668 
14669 	st_swap32(&low);
14670 	st_swap32(&high);
14671 
14672 	*val =  high;
14673 	*val |= ((uint64_t)low << 32);
14674 }
14675 
14676 #define	FIX_ENDIAN16(x) st_swap16(x)
14677 #define	FIX_ENDIAN32(x) st_swap32(x)
14678 #define	FIX_ENDIAN64(x) st_swap64(x)
14679 #endif
14680 
14681 /*
14682  * st_interpret_read_pos()
14683  *
14684  * Returns:
14685  *	0	If secsessful.
14686  *	EIO	If read postion responce data was unuseable or invalid.
14687  *	ERANGE	If the position of the drive is too large for the read_p_type.
14688  *	ENOTTY	If the responce data looks invalid for the read position type.
14689  */
14690 
14691 static int
14692 st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
14693     read_p_types type, size_t data_sz, const caddr_t responce, int post_space)
14694 {
14695 	int rval = 0;
14696 	int flag = 0;
14697 	tapepos_t org;
14698 
14699 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
14700 
14701 	/*
14702 	 * We expect the position value to change after a space command.
14703 	 * So if post_space is set we don't print out what has changed.
14704 	 */
14705 	if ((dest != &un->un_pos) && (post_space == 0) &&
14706 	    (st_recov_sz == sizeof (recov_info))) {
14707 		COPY_POS(&org, dest);
14708 		flag = 1;
14709 	}
14710 
14711 	/*
14712 	 * See what kind of read position was requested.
14713 	 */
14714 	switch (type) {
14715 
14716 	case SHORT_POS: /* Short data format */
14717 	{
14718 		tape_position_t *pos_info = (tape_position_t *)responce;
14719 		uint32_t value;
14720 
14721 		/* If reserved fields are non zero don't use the data */
14722 		if (pos_info->reserved0 || pos_info->reserved1 ||
14723 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
14724 		    pos_info->reserved3) {
14725 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14726 			    "Invalid Read Short Position Data returned\n");
14727 			rval = EIO;
14728 			break;
14729 		}
14730 		/*
14731 		 * Position is to large to use this type of read position.
14732 		 */
14733 		if (pos_info->posi_err == 1) {
14734 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14735 			    "Drive reported position error\n");
14736 			rval = ERANGE;
14737 			break;
14738 		}
14739 		/*
14740 		 * If your at the begining of partition and end at the same
14741 		 * time it's very small partition or bad data.
14742 		 */
14743 		if (pos_info->begin_of_part && pos_info->end_of_part) {
14744 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14745 			    "SHORT_POS returned begin and end of"
14746 			    " partition\n");
14747 			rval = EIO;
14748 			break;
14749 		}
14750 
14751 		if (pos_info->blk_posi_unkwn == 0) {
14752 
14753 			value = pos_info->host_block;
14754 			FIX_ENDIAN32(&value);
14755 
14756 			/*
14757 			 * If the tape is rewound the host blcok should be 0.
14758 			 */
14759 			if ((pos_info->begin_of_part == 1) &&
14760 			    (value != 0)) {
14761 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14762 				    "SHORT_POS returned begin of partition"
14763 				    " but host block was 0x%x\n", value);
14764 				rval = EIO;
14765 				break;
14766 			}
14767 
14768 			if (dest->lgclblkno != value) {
14769 				if (flag)
14770 					flag++;
14771 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14772 				    "SHORT_POS current logical 0x%"PRIx64" read"
14773 				    " 0x%x\n", dest->lgclblkno, value);
14774 			}
14775 
14776 			dest->lgclblkno = (uint64_t)value;
14777 
14778 			/*
14779 			 * If the begining of partition is true and the
14780 			 * block number is zero we will beleive that it is
14781 			 * rewound. Promote the pmode to legacy.
14782 			 */
14783 			if ((pos_info->begin_of_part == 1) &&
14784 			    (value == 0)) {
14785 				dest->blkno = 0;
14786 				dest->fileno = 0;
14787 				if (dest->pmode != legacy)
14788 					dest->pmode = legacy;
14789 			/*
14790 			 * otherwise if the pmode was invalid,
14791 			 * promote it to logical.
14792 			 */
14793 			} else if (dest->pmode == invalid) {
14794 				dest->pmode = logical;
14795 			}
14796 
14797 			if (dest->partition != pos_info->partition_number) {
14798 				if (flag)
14799 					flag++;
14800 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14801 				    "SHORT_POS current partition %d read %d\n",
14802 				    dest->partition,
14803 				    pos_info->partition_number);
14804 			}
14805 
14806 			dest->partition = pos_info->partition_number;
14807 
14808 		} else {
14809 			dest->pmode = invalid;
14810 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14811 			    "Tape drive reported block position as unknown\n");
14812 		}
14813 		break;
14814 	}
14815 
14816 	case LONG_POS: /* Long data format */
14817 	{
14818 		uint64_t value;
14819 		tape_position_long_t *long_pos_info =
14820 		    (tape_position_long_t *)responce;
14821 
14822 		/* If reserved fields are non zero don't use the data */
14823 		if ((long_pos_info->reserved0) ||
14824 		    (long_pos_info->reserved1) ||
14825 		    (long_pos_info->reserved2)) {
14826 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14827 			    "Invalid Read Long Position Data returned\n");
14828 			rval = ENOTTY;
14829 			break;
14830 		}
14831 
14832 		/* Is position Valid */
14833 		if (long_pos_info->blk_posi_unkwn == 0) {
14834 			uint32_t part;
14835 
14836 			value = long_pos_info->block_number;
14837 			FIX_ENDIAN64(&value);
14838 
14839 			/*
14840 			 * If it says we are at the begining of partition
14841 			 * the block value better be 0.
14842 			 */
14843 			if ((long_pos_info->begin_of_part == 1) &&
14844 			    (value != 0)) {
14845 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14846 				    "LONG_POS returned begin of partition but"
14847 				    " block number was 0x%"PRIx64"\n", value);
14848 				rval = ENOTTY;
14849 				break;
14850 			}
14851 			/*
14852 			 * Can't be at the start and the end of the partition
14853 			 * at the same time if the partition is larger the 0.
14854 			 */
14855 			if (long_pos_info->begin_of_part &&
14856 			    long_pos_info->end_of_part) {
14857 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14858 				    "LONG_POS returned begin and end of"
14859 				    " partition\n");
14860 				rval = ENOTTY;
14861 				break;
14862 			}
14863 
14864 			/*
14865 			 * If the logical block number is not what we expected.
14866 			 */
14867 			if (dest->lgclblkno != value) {
14868 				if (flag)
14869 					flag++;
14870 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14871 				    "LONG_POS current logical 0x%"PRIx64
14872 				    " read 0x%"PRIx64"\n",
14873 				    dest->lgclblkno, value);
14874 			}
14875 			dest->lgclblkno = value;
14876 
14877 			/*
14878 			 * If the begining of partition is true and the
14879 			 * block number is zero we will beleive that it is
14880 			 * rewound. Promote the pmode to legacy.
14881 			 */
14882 			if ((long_pos_info->begin_of_part == 1) &&
14883 			    (long_pos_info->block_number == 0)) {
14884 				dest->blkno = 0;
14885 				dest->fileno = 0;
14886 				if (dest->pmode != legacy)
14887 					dest->pmode = legacy;
14888 			/*
14889 			 * otherwise if the pmode was invalid,
14890 			 * promote it to logical.
14891 			 */
14892 			} else if (dest->pmode == invalid) {
14893 				dest->pmode = logical;
14894 			}
14895 
14896 			part = long_pos_info->partition;
14897 			FIX_ENDIAN32(&part);
14898 			if (dest->partition != part) {
14899 				if (flag)
14900 					flag++;
14901 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14902 				    "LONG_POS current partition %d"
14903 				    " read %d\n", dest->partition, part);
14904 			}
14905 			dest->partition = part;
14906 		} else {
14907 			/*
14908 			 * If the drive doesn't know location,
14909 			 * we don't either.
14910 			 */
14911 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14912 			    "Tape drive reported block position as unknown\n");
14913 			dest->pmode = invalid;
14914 		}
14915 
14916 		/* Is file position valid */
14917 		if (long_pos_info->mrk_posi_unkwn == 0) {
14918 			value = long_pos_info->file_number;
14919 			FIX_ENDIAN64(&value);
14920 			/*
14921 			 * If it says we are at the begining of partition
14922 			 * the block value better be 0.
14923 			 */
14924 			if ((long_pos_info->begin_of_part == 1) &&
14925 			    (value != 0)) {
14926 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14927 				    "LONG_POS returned begin of partition but"
14928 				    " block number was 0x%"PRIx64"\n", value);
14929 				rval = ENOTTY;
14930 				break;
14931 			}
14932 			if (((dest->pmode == legacy) ||
14933 			    (dest->pmode == logical)) &&
14934 			    (dest->fileno != value)) {
14935 				if (flag)
14936 					flag++;
14937 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14938 				    "LONG_POS fileno 0x%"PRIx64
14939 				    " not un_pos %x\n", value,
14940 				    dest->fileno);
14941 			} else if (dest->pmode == invalid) {
14942 				dest->pmode = logical;
14943 			}
14944 			dest->fileno = (int32_t)value;
14945 		}
14946 
14947 		if (dest->pmode != invalid && long_pos_info->end_of_part) {
14948 			dest->eof = ST_EOT;
14949 		}
14950 
14951 		break;
14952 	}
14953 
14954 	case EXT_POS: /* Extended data format */
14955 	{
14956 		uint64_t value;
14957 		uint16_t len;
14958 		tape_position_ext_t *ext_pos_info =
14959 		    (tape_position_ext_t *)responce;
14960 
14961 		/* Make sure that there is enough data there */
14962 		if (data_sz < 16) {
14963 			break;
14964 		}
14965 
14966 		/* If reserved fields are non zero don't use the data */
14967 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
14968 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14969 			    "EXT_POS reserved fields not zero\n");
14970 			rval = ENOTTY;
14971 			break;
14972 		}
14973 
14974 		/*
14975 		 * In the unlikely event of overflowing 64 bits of position.
14976 		 */
14977 		if (ext_pos_info->posi_err != 0) {
14978 			rval = ERANGE;
14979 			break;
14980 		}
14981 
14982 		len = ext_pos_info->parameter_len;
14983 		FIX_ENDIAN16(&len);
14984 
14985 		if (len != 0x1c) {
14986 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14987 			    "EXT_POS parameter_len should be 0x1c was 0x%x\n",
14988 			    len);
14989 			rval = ENOTTY;
14990 			break;
14991 		}
14992 
14993 		/* Is block position information valid */
14994 		if (ext_pos_info->blk_posi_unkwn == 0) {
14995 
14996 			value = ext_pos_info->host_block;
14997 			FIX_ENDIAN64(&value);
14998 			if ((ext_pos_info->begin_of_part == 1) &&
14999 			    (value != 0)) {
15000 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15001 				    "EXT_POS returned begining of partition but"
15002 				    " the host block was 0x%"PRIx64"\n", value);
15003 				rval = ENOTTY;
15004 				break;
15005 			}
15006 
15007 			if (dest->lgclblkno != value) {
15008 				if (flag)
15009 					flag++;
15010 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15011 				    "EXT_POS current logical 0x%"PRIx64
15012 				    " read 0x%"PRIx64"\n",
15013 				    dest->lgclblkno, value);
15014 			}
15015 			dest->lgclblkno = value;
15016 
15017 			/*
15018 			 * If the begining of partition is true and the
15019 			 * block number is zero we will beleive that it is
15020 			 * rewound. Promote the pmode to legacy.
15021 			 */
15022 			if ((ext_pos_info->begin_of_part == 1) &&
15023 			    (ext_pos_info->host_block == 0)) {
15024 				dest->blkno = 0;
15025 				dest->fileno = 0;
15026 				if (dest->pmode != legacy) {
15027 					dest->pmode = legacy;
15028 				}
15029 			/*
15030 			 * otherwise if the pmode was invalid,
15031 			 * promote it to logical.
15032 			 */
15033 			} else if (dest->pmode == invalid) {
15034 				dest->pmode = logical;
15035 			}
15036 
15037 			if (dest->partition != ext_pos_info->partition) {
15038 				if (flag)
15039 					flag++;
15040 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15041 				    "EXT_POS current partition %d read %d\n",
15042 				    dest->partition,
15043 				    ext_pos_info->partition);
15044 			}
15045 			dest->partition = ext_pos_info->partition;
15046 
15047 		} else {
15048 			dest->pmode = invalid;
15049 		}
15050 		break;
15051 	}
15052 
15053 	default:
15054 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15055 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
15056 		rval = EIO;
15057 	}
15058 
15059 	if ((flag > 1) && (rval == 0) && (org.pmode != invalid)) {
15060 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
15061 		    "position read in", &org);
15062 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
15063 		    "position read out", dest);
15064 	}
15065 
15066 	return (rval);
15067 }
15068 
15069 static int
15070 st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos,
15071     uint64_t lblk, uchar_t partition)
15072 {
15073 	int rval;
15074 	char cdb[CDB_GROUP4];
15075 	struct uscsi_cmd *cmd;
15076 	struct scsi_extended_sense sense;
15077 	bufunc_t bf = (ubf == st_uscsi_cmd) ? st_cmd : st_rcmd;
15078 
15079 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
15080 	/*
15081 	 * Not sure what to do when doing recovery and not wanting
15082 	 * to update un_pos
15083 	 */
15084 
15085 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
15086 
15087 	if (lblk <= INT32_MAX) {
15088 		cmd->uscsi_cdblen = CDB_GROUP1;
15089 		cdb[0] = SCMD_LOCATE;
15090 		cdb[1] = pos->partition == partition ? 0 : 2;
15091 		cdb[2] = 0;
15092 		cdb[3] = (char)(lblk >> 24);
15093 		cdb[4] = (char)(lblk >> 16);
15094 		cdb[5] = (char)(lblk >> 8);
15095 		cdb[6] = (char)(lblk);
15096 		cdb[7] = 0;
15097 		cdb[8] = partition;
15098 		cdb[9] = 0;
15099 	} else {
15100 		/*
15101 		 * If the drive doesn't give a 64 bit read position data
15102 		 * it is unlikely it will accept 64 bit locates.
15103 		 */
15104 		if (un->un_read_pos_type != LONG_POS) {
15105 			kmem_free(cmd, sizeof (struct uscsi_cmd));
15106 			return (ERANGE);
15107 		}
15108 		cmd->uscsi_cdblen = CDB_GROUP4;
15109 		cdb[0] = (char)SCMD_LOCATE_G4;
15110 		cdb[1] = pos->partition == partition ? 0 : 2;
15111 		cdb[2] = 0;
15112 		cdb[3] = partition;
15113 		cdb[4] = (char)(lblk >> 56);
15114 		cdb[5] = (char)(lblk >> 48);
15115 		cdb[6] = (char)(lblk >> 40);
15116 		cdb[7] = (char)(lblk >> 32);
15117 		cdb[8] = (char)(lblk >> 24);
15118 		cdb[9] = (char)(lblk >> 16);
15119 		cdb[10] = (char)(lblk >> 8);
15120 		cdb[11] = (char)(lblk);
15121 		cdb[12] = 0;
15122 		cdb[13] = 0;
15123 		cdb[14] = 0;
15124 		cdb[15] = 0;
15125 	}
15126 
15127 
15128 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
15129 	cmd->uscsi_rqbuf = (caddr_t)&sense;
15130 	cmd->uscsi_rqlen = sizeof (sense);
15131 	cmd->uscsi_timeout = un->un_dp->space_timeout;
15132 	cmd->uscsi_cdb = cdb;
15133 
15134 	rval = ubf(un, cmd, FKIOCTL);
15135 
15136 	pos->pmode = logical;
15137 	pos->eof = ST_NO_EOF;
15138 
15139 	if (lblk > INT32_MAX) {
15140 		/*
15141 		 * XXX This is a work around till we handle Descriptor format
15142 		 * sense data. Since we are sending a command where the standard
15143 		 * sense data can not correctly represent a correct residual in
15144 		 * 4 bytes.
15145 		 */
15146 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
15147 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15148 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
15149 			/* Doesn't like big locate command */
15150 			un->un_status = 0;
15151 			rval = ERANGE;
15152 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
15153 			/* Aborted big locate command */
15154 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15155 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
15156 			    rval);
15157 			un->un_status = 0;
15158 			rval = EIO;
15159 		} else if (st_update_block_pos(un, bf, 1)) {
15160 			/* read position failed */
15161 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15162 			    "Big LOCATE and read pos: rval = %d\n", rval);
15163 			rval = EIO;
15164 		} else if (lblk > un->un_pos.lgclblkno) {
15165 			/* read position worked but position was not expected */
15166 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15167 			    "Big LOCATE and recover read less then desired 0x%"
15168 			    PRIx64"\n", un->un_pos.lgclblkno);
15169 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
15170 			un->un_status = KEY_BLANK_CHECK;
15171 			rval = ESPIPE;
15172 		} else if (lblk == un->un_pos.lgclblkno) {
15173 			/* read position was what was expected */
15174 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15175 			    "Big LOCATE and recover seems to have worked\n");
15176 			un->un_err_resid = 0;
15177 			rval = 0;
15178 		} else {
15179 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15180 			    "BIGLOCATE end up going backwards");
15181 			un->un_err_resid = lblk;
15182 			rval = EIO;
15183 		}
15184 
15185 	} else if (rval == 0) {
15186 		/* Worked as requested */
15187 		pos->lgclblkno = lblk;
15188 
15189 	} else if (((cmd->uscsi_status & ST_STATUS_MASK) == STATUS_CHECK) &&
15190 	    (cmd->uscsi_resid != 0)) {
15191 		/* Got part way there but wasn't enough blocks on tape */
15192 		pos->lgclblkno = lblk - cmd->uscsi_resid;
15193 		un->un_err_resid = cmd->uscsi_resid;
15194 		un->un_status = KEY_BLANK_CHECK;
15195 		rval = ESPIPE;
15196 
15197 	} else if (st_update_block_pos(un, bf, 1) == 0) {
15198 		/* Got part way there but drive didn't tell what we missed by */
15199 		un->un_err_resid = lblk - pos->lgclblkno;
15200 		un->un_status = KEY_BLANK_CHECK;
15201 		rval = ESPIPE;
15202 
15203 	} else {
15204 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15205 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
15206 		    rval, cmd->uscsi_status);
15207 		un->un_err_resid = lblk;
15208 		un->un_status = KEY_ILLEGAL_REQUEST;
15209 		pos->pmode = invalid;
15210 		rval = EIO;
15211 	}
15212 
15213 	kmem_free(cmd, sizeof (struct uscsi_cmd));
15214 
15215 	return (rval);
15216 }
15217 
15218 static int
15219 st_mtfsf_ioctl(struct scsi_tape *un, int64_t files)
15220 {
15221 	int rval;
15222 
15223 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
15224 
15225 
15226 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15227 	    "st_mtfsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15228 #if 0
15229 	if ((IN_EOF(un->un_pos)) && (files == 1)) {
15230 		un->un_pos.fileno++;
15231 		un->un_pos.blkno = 0;
15232 		return (0);
15233 	}
15234 #endif
15235 	/* pmode == invalid already handled */
15236 	if (un->un_pos.pmode == legacy) {
15237 		/*
15238 		 * forward space over filemark
15239 		 *
15240 		 * For ASF we allow a count of 0 on fsf which means
15241 		 * we just want to go to beginning of current file.
15242 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
15243 		 * Allow stepping over double fmk with reel
15244 		 */
15245 		if ((un->un_pos.eof >= ST_EOT) &&
15246 		    (files > 0) &&
15247 		    ((un->un_dp->options & ST_REEL) == 0)) {
15248 			/* we're at EOM */
15249 			un->un_err_resid = files;
15250 			un->un_status = KEY_BLANK_CHECK;
15251 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15252 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
15253 			return (EIO);
15254 		}
15255 
15256 		/*
15257 		 * physical tape position may not be what we've been
15258 		 * telling the user; adjust the request accordingly
15259 		 */
15260 		if (IN_EOF(un->un_pos)) {
15261 			un->un_pos.fileno++;
15262 			un->un_pos.blkno = 0;
15263 			/*
15264 			 * For positive direction case, we're now covered.
15265 			 * For zero or negative direction, we're covered
15266 			 * (almost)
15267 			 */
15268 			files--;
15269 		}
15270 
15271 	}
15272 
15273 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15274 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15275 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
15276 		return (EIO);
15277 	}
15278 
15279 
15280 	/*
15281 	 * Forward space file marks.
15282 	 * We leave ourselves at block zero
15283 	 * of the target file number.
15284 	 */
15285 	if (files < 0) {
15286 		rval = st_backward_space_files(un, -files, 0);
15287 	} else {
15288 		rval = st_forward_space_files(un, files);
15289 	}
15290 
15291 	return (rval);
15292 }
15293 
15294 static int
15295 st_forward_space_files(struct scsi_tape *un, int64_t count)
15296 {
15297 	int rval;
15298 
15299 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
15300 
15301 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15302 	    "fspace: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15303 
15304 	ASSERT(count >= 0);
15305 	ASSERT(un->un_pos.pmode != invalid);
15306 
15307 	/*
15308 	 * A space with a count of zero means take me to the start of file.
15309 	 */
15310 	if (count == 0) {
15311 
15312 		/* Hay look were already there */
15313 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0) {
15314 			un->un_err_resid = 0;
15315 			COPY_POS(&un->un_err_pos, &un->un_pos);
15316 			return (0);
15317 		}
15318 
15319 		/*
15320 		 * Well we are in the first file.
15321 		 * A rewind will get to the start.
15322 		 */
15323 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
15324 			rval = st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
15325 
15326 		/*
15327 		 * Can we backspace to get there?
15328 		 * This should work in logical mode.
15329 		 */
15330 		} else if (un->un_dp->options & ST_BSF) {
15331 			rval = st_space_to_begining_of_file(un);
15332 
15333 		/*
15334 		 * Can't back space but current file number is known,
15335 		 * So rewind and space from the begining of the partition.
15336 		 */
15337 		} else if (un->un_pos.pmode == legacy) {
15338 			rval = st_scenic_route_to_begining_of_file(un,
15339 			    un->un_pos.fileno);
15340 
15341 		/*
15342 		 * pmode is logical and ST_BSF is not set.
15343 		 * The LONG_POS read position contains the fileno.
15344 		 * If the read position works, rewind and space.
15345 		 */
15346 		} else if (un->un_read_pos_type == LONG_POS) {
15347 			rval = st_cmd(un, SCMD_READ_POSITION, 0, SYNC_CMD);
15348 			if (rval) {
15349 				/*
15350 				 * We didn't get the file position from the
15351 				 * read position command.
15352 				 * We are going to trust the drive to backspace
15353 				 * and then position after the filemark.
15354 				 */
15355 				rval = st_space_to_begining_of_file(un);
15356 			}
15357 			rval = st_interpret_read_pos(un, &un->un_pos, LONG_POS,
15358 			    32, (caddr_t)un->un_read_pos_data, 0);
15359 			if ((rval) && (un->un_pos.pmode == invalid)) {
15360 				rval = st_space_to_begining_of_file(un);
15361 			} else {
15362 				rval = st_scenic_route_to_begining_of_file(un,
15363 				    un->un_pos.fileno);
15364 			}
15365 		} else {
15366 			rval = EIO;
15367 		}
15368 		/*
15369 		 * If something didn't work we are lost
15370 		 */
15371 		if (rval != 0) {
15372 			un->un_pos.pmode = invalid;
15373 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15374 			    "st_mtioctop : EIO : fspace pmode invalid");
15375 
15376 			rval = EIO;
15377 		}
15378 
15379 	} else {
15380 		rval = st_space_fmks(un, count);
15381 	}
15382 
15383 	if (rval != EIO && count < 0) {
15384 		/*
15385 		 * we came here with a count < 0; we now need
15386 		 * to skip back to end up before the filemark
15387 		 */
15388 		rval = st_backward_space_files(un, 1, 1);
15389 	}
15390 
15391 	return (rval);
15392 }
15393 
15394 static int
15395 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
15396 {
15397 	int rval;
15398 
15399 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
15400 
15401 	if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15402 		rval = EIO;
15403 	} else if (st_cmd(un, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
15404 		rval = EIO;
15405 	}
15406 
15407 	return (rval);
15408 }
15409 
15410 static int
15411 st_space_to_begining_of_file(struct scsi_tape *un)
15412 {
15413 	int rval;
15414 
15415 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
15416 
15417 	/*
15418 	 * Back space of the file at the begining of the file.
15419 	 */
15420 	rval = st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
15421 	if (rval) {
15422 		rval = EIO;
15423 		return (rval);
15424 	}
15425 
15426 	/*
15427 	 * Other interesting answers might be crashed BOT which isn't bad.
15428 	 */
15429 	if (un->un_status == SUN_KEY_BOT) {
15430 		return (rval);
15431 	}
15432 
15433 	un->un_running.pmode = invalid;
15434 
15435 	/*
15436 	 * Now we are on the BOP side of the filemark. Forward space to
15437 	 * the EOM side and we are at the begining of the file.
15438 	 */
15439 	rval = st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD);
15440 	if (rval) {
15441 		rval = EIO;
15442 	}
15443 
15444 	return (rval);
15445 }
15446 
15447 static int
15448 st_mtfsr_ioctl(struct scsi_tape *un, int64_t count)
15449 {
15450 
15451 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
15452 
15453 	/*
15454 	 * forward space to inter-record gap
15455 	 *
15456 	 */
15457 
15458 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15459 	    "st_ioctl_fsr: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15460 
15461 	if (un->un_pos.pmode == legacy) {
15462 		/*
15463 		 * If were are at end of tape and count is forward.
15464 		 * Return blank check.
15465 		 */
15466 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
15467 			/* we're at EOM */
15468 			un->un_err_resid = count;
15469 			un->un_status = KEY_BLANK_CHECK;
15470 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15471 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
15472 			return (EIO);
15473 		}
15474 
15475 		/*
15476 		 * If count is zero there is nothing to do.
15477 		 */
15478 		if (count == 0) {
15479 			un->un_err_pos.fileno = un->un_pos.fileno;
15480 			un->un_err_pos.blkno = un->un_pos.blkno;
15481 			un->un_err_resid = 0;
15482 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15483 				un->un_status = SUN_KEY_EOF;
15484 			}
15485 			return (0);
15486 		}
15487 
15488 		/*
15489 		 * physical tape position may not be what we've been
15490 		 * telling the user; adjust the position accordingly
15491 		 */
15492 		if (IN_EOF(un->un_pos)) {
15493 			daddr_t blkno = un->un_pos.blkno;
15494 			int fileno = un->un_pos.fileno;
15495 
15496 			optype lastop = un->un_lastop;
15497 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)
15498 			    == -1) {
15499 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15500 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
15501 				return (EIO);
15502 			}
15503 
15504 			un->un_pos.blkno = blkno;
15505 			un->un_pos.fileno = fileno;
15506 			un->un_lastop = lastop;
15507 		}
15508 	}
15509 
15510 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15511 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15512 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
15513 		return (EIO);
15514 	}
15515 
15516 	return (st_space_records(un, count));
15517 }
15518 
15519 static int
15520 st_space_records(struct scsi_tape *un, int64_t count)
15521 {
15522 	int64_t dblk;
15523 	int rval = 0;
15524 
15525 	ST_FUNC(ST_DEVINFO, st_space_records);
15526 
15527 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15528 	    "st_space_records: count=%"PRIx64", eof=%x\n",
15529 	    count, un->un_pos.eof);
15530 
15531 	if (un->un_pos.pmode == logical) {
15532 		rval = st_cmd(un, SCMD_SPACE, Blk(count), SYNC_CMD);
15533 		if (rval != 0) {
15534 			rval = EIO;
15535 		}
15536 		return (rval);
15537 	}
15538 
15539 	dblk = count + un->un_pos.blkno;
15540 
15541 	/* Already there */
15542 	if (dblk == un->un_pos.blkno) {
15543 		un->un_err_resid = 0;
15544 		COPY_POS(&un->un_err_pos, &un->un_pos);
15545 		return (0);
15546 	}
15547 
15548 	/*
15549 	 * If the destination block is forward
15550 	 * or the drive will backspace records.
15551 	 */
15552 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
15553 		/*
15554 		 * If we're spacing forward, or the device can
15555 		 * backspace records, we can just use the SPACE
15556 		 * command.
15557 		 */
15558 		dblk -= un->un_pos.blkno;
15559 		if (st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15560 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15561 			    "st_space_records:EIO:space_records can't spc");
15562 			rval = EIO;
15563 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
15564 			/*
15565 			 * check if we hit BOT/EOT
15566 			 */
15567 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
15568 				un->un_status = SUN_KEY_BOT;
15569 				un->un_pos.eof = ST_NO_EOF;
15570 			} else if (dblk < 0 &&
15571 			    un->un_pos.eof == ST_EOF_PENDING) {
15572 				int residue = un->un_err_resid;
15573 				/*
15574 				 * we skipped over a filemark
15575 				 * and need to go forward again
15576 				 */
15577 				if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
15578 					ST_DEBUG2(ST_DEVINFO, st_label,
15579 					    SCSI_DEBUG, "st_space_records: EIO"
15580 					    " : can't space #2");
15581 					rval = EIO;
15582 				}
15583 				un->un_err_resid = residue;
15584 			}
15585 			if (rval == 0) {
15586 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15587 				    "st_space_records: EIO : space_rec rval"
15588 				    " == 0");
15589 				rval = EIO;
15590 			}
15591 		}
15592 	} else {
15593 		/*
15594 		 * else we rewind, space forward across filemarks to
15595 		 * the desired file, and then space records to the
15596 		 * desired block.
15597 		 */
15598 
15599 		int dfile = un->un_pos.fileno;	/* save current file */
15600 
15601 		if (dblk < 0) {
15602 			/*
15603 			 * Wups - we're backing up over a filemark
15604 			 */
15605 			if (un->un_pos.blkno != 0 &&
15606 			    (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15607 			    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD))) {
15608 				un->un_pos.pmode = invalid;
15609 			}
15610 			un->un_err_resid = -dblk;
15611 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
15612 				un->un_status = SUN_KEY_BOT;
15613 				un->un_pos.eof = ST_NO_EOF;
15614 			} else if (un->un_pos.fileno > 0) {
15615 				un->un_status = SUN_KEY_EOF;
15616 				un->un_pos.eof = ST_NO_EOF;
15617 			}
15618 			COPY_POS(&un->un_err_pos, &un->un_pos);
15619 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15620 			    "st_space_records:EIO:space_records : dblk < 0");
15621 			rval = EIO;
15622 		} else if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15623 		    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
15624 		    st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15625 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15626 			    "st_space_records: EIO :space_records : rewind "
15627 			    "and space failed");
15628 			un->un_pos.pmode = invalid;
15629 			rval = EIO;
15630 		}
15631 	}
15632 
15633 	return (rval);
15634 }
15635 
15636 static int
15637 st_mtbsf_ioctl(struct scsi_tape *un, int64_t files)
15638 {
15639 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
15640 
15641 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15642 	    "st_mtbsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15643 	/*
15644 	 * backward space of file filemark (1/2" and 8mm)
15645 	 * tape position will end on the beginning of tape side
15646 	 * of the desired file mark
15647 	 */
15648 	if ((un->un_dp->options & ST_BSF) == 0) {
15649 		return (ENOTTY);
15650 	}
15651 
15652 	if (un->un_pos.pmode == legacy) {
15653 
15654 		/*
15655 		 * If a negative count (which implies a forward space op)
15656 		 * is specified, and we're at logical or physical eot,
15657 		 * bounce the request.
15658 		 */
15659 
15660 		if (un->un_pos.eof >= ST_EOT && files < 0) {
15661 			un->un_err_resid = files;
15662 			un->un_status = SUN_KEY_EOT;
15663 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15664 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
15665 			return (EIO);
15666 		}
15667 		/*
15668 		 * physical tape position may not be what we've been
15669 		 * telling the user; adjust the request accordingly
15670 		 */
15671 		if (IN_EOF(un->un_pos)) {
15672 			un->un_pos.fileno++;
15673 			un->un_pos.blkno = 0;
15674 			files++;
15675 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15676 			    "st_mtbsf_ioctl in eof: count=%"PRIx64", op=%x\n",
15677 			    files, MTBSF);
15678 
15679 		}
15680 	}
15681 
15682 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15683 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15684 		    "st_ioctl : EIO : MTBSF : check den wfm");
15685 		return (EIO);
15686 	}
15687 
15688 	if (files <= 0) {
15689 		/*
15690 		 * for a negative count, we need to step forward
15691 		 * first and then step back again
15692 		 */
15693 		files = -files + 1;
15694 		return (st_forward_space_files(un, files));
15695 	}
15696 	return (st_backward_space_files(un, files, 1));
15697 }
15698 
15699 static int
15700 st_backward_space_files(struct scsi_tape *un, int64_t count, int infront)
15701 {
15702 	int64_t end_fileno;
15703 	int64_t skip_cnt;
15704 	int rval = 0;
15705 
15706 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
15707 
15708 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15709 	    "st_backward_space_files: count=%"PRIx64" eof=%x\n",
15710 	    count, un->un_pos.eof);
15711 	/*
15712 	 * Backspace files (MTNBSF): infront == 0
15713 	 *
15714 	 *	For tapes that can backspace, backspace
15715 	 *	count+1 filemarks and then run forward over
15716 	 *	a filemark
15717 	 *
15718 	 *	For tapes that can't backspace,
15719 	 *		calculate desired filenumber
15720 	 *		(un->un_pos.fileno - count), rewind,
15721 	 *		and then space forward this amount
15722 	 *
15723 	 * Backspace filemarks (MTBSF) infront == 1
15724 	 *
15725 	 *	For tapes that can backspace, backspace count
15726 	 *	filemarks
15727 	 *
15728 	 *	For tapes that can't backspace, calculate
15729 	 *	desired filenumber (un->un_pos.fileno - count),
15730 	 *	add 1, rewind, space forward this amount,
15731 	 *	and mark state as ST_EOF_PENDING appropriately.
15732 	 */
15733 
15734 	if (un->un_pos.pmode == logical) {
15735 
15736 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15737 		    "st_backward_space_files: mt_op=%x count=%"PRIx64
15738 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
15739 		    un->un_pos.lgclblkno);
15740 
15741 
15742 		/* In case a drive that won't back space gets in logical mode */
15743 		if ((un->un_dp->options & ST_BSF) == 0) {
15744 			rval = EIO;
15745 			return (rval);
15746 		}
15747 		if ((infront == 1) &&
15748 		    (st_cmd(un, SCMD_SPACE, Fmk(-count), SYNC_CMD))) {
15749 			rval = EIO;
15750 			return (rval);
15751 		} else if ((infront == 0) &&
15752 		    (st_cmd(un, SCMD_SPACE, Fmk((-count)-1), SYNC_CMD)) &&
15753 		    (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
15754 			rval = EIO;
15755 			return (rval);
15756 		}
15757 		return (rval);
15758 	}
15759 
15760 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15761 	    "st_backward_space_files: mt_op=%x count=%"PRIx64
15762 	    "fileno=%x blkno=%x\n",
15763 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
15764 
15765 
15766 
15767 	/*
15768 	 * Handle the simple case of BOT
15769 	 * playing a role in these cmds.
15770 	 * We do this by calculating the
15771 	 * ending file number. If the ending
15772 	 * file is < BOT, rewind and set an
15773 	 * error and mark resid appropriately.
15774 	 * If we're backspacing a file (not a
15775 	 * filemark) and the target file is
15776 	 * the first file on the tape, just
15777 	 * rewind.
15778 	 */
15779 
15780 	/* figure expected destination of this SPACE command */
15781 	end_fileno = un->un_pos.fileno - count;
15782 
15783 	/*
15784 	 * Would the end effect of this SPACE be the same as rewinding?
15785 	 * If so just rewind instead.
15786 	 */
15787 	if ((infront != 0) && (end_fileno < 0) ||
15788 	    (infront == 0) && (end_fileno <= 0)) {
15789 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15790 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15791 			    "st_backward_space_files: EIO : "
15792 			    "rewind in lou of BSF failed\n");
15793 			rval = EIO;
15794 		}
15795 		if (end_fileno < 0) {
15796 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15797 			    "st_backward_space_files: EIO : "
15798 			    "back space file greater then fileno\n");
15799 			rval = EIO;
15800 			un->un_err_resid = -end_fileno;
15801 			un->un_status = SUN_KEY_BOT;
15802 		}
15803 		return (rval);
15804 	}
15805 
15806 	if (un->un_dp->options & ST_BSF) {
15807 		skip_cnt = 1 - infront;
15808 		/*
15809 		 * If we are going to end up at the beginning
15810 		 * of the file, we have to space one extra file
15811 		 * first, and then space forward later.
15812 		 */
15813 		end_fileno = -(count + skip_cnt);
15814 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15815 		    "skip_cnt=%"PRIx64", tmp=%"PRIx64"\n",
15816 		    skip_cnt, end_fileno);
15817 		if (st_cmd(un, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
15818 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15819 			    "st_backward_space_files:EIO:back space fm failed");
15820 			rval = EIO;
15821 		}
15822 	} else {
15823 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15824 			rval = EIO;
15825 		} else {
15826 			skip_cnt = end_fileno + infront;
15827 		}
15828 	}
15829 
15830 	/*
15831 	 * If we have to space forward, do so...
15832 	 */
15833 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15834 	    "space forward skip_cnt=%"PRIx64", rval=%x\n", skip_cnt, rval);
15835 
15836 	if (rval == 0 && skip_cnt) {
15837 		if (st_cmd(un, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
15838 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15839 			    "st_backward_space_files:EIO:space fm skip count");
15840 			rval = EIO;
15841 		} else if (infront) {
15842 			/*
15843 			 * If we had to space forward, and we're
15844 			 * not a tape that can backspace, mark state
15845 			 * as if we'd just seen a filemark during a
15846 			 * a read.
15847 			 */
15848 			if ((un->un_dp->options & ST_BSF) == 0) {
15849 				un->un_pos.eof = ST_EOF_PENDING;
15850 				un->un_pos.fileno -= 1;
15851 				un->un_pos.blkno = LASTBLK;
15852 				un->un_running.pmode = invalid;
15853 			}
15854 		}
15855 	}
15856 
15857 	if (rval != 0) {
15858 		un->un_pos.pmode = invalid;
15859 	}
15860 
15861 	return (rval);
15862 }
15863 
15864 static int
15865 st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count)
15866 {
15867 	int rval;
15868 
15869 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
15870 
15871 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15872 	    "nbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15873 
15874 	if (un->un_pos.pmode == legacy) {
15875 		/*
15876 		 * backward space file to beginning of file
15877 		 *
15878 		 * If a negative count (which implies a forward space op)
15879 		 * is specified, and we're at logical or physical eot,
15880 		 * bounce the request.
15881 		 */
15882 
15883 		if (un->un_pos.eof >= ST_EOT && count < 0) {
15884 			un->un_err_resid = count;
15885 			un->un_status = SUN_KEY_EOT;
15886 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15887 			    "st_ioctl : EIO : > EOT and count < 0");
15888 			return (EIO);
15889 		}
15890 		/*
15891 		 * physical tape position may not be what we've been
15892 		 * telling the user; adjust the request accordingly
15893 		 */
15894 		if (IN_EOF(un->un_pos)) {
15895 			un->un_pos.fileno++;
15896 			un->un_pos.blkno = 0;
15897 			count++;
15898 		}
15899 	}
15900 
15901 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15902 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15903 		    "st_ioctl : EIO : MTNBSF check den and wfm");
15904 		return (EIO);
15905 	}
15906 
15907 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15908 	    "mtnbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15909 
15910 	if (count <= 0) {
15911 		rval = st_forward_space_files(un, -count);
15912 	} else {
15913 		rval = st_backward_space_files(un, count, 0);
15914 	}
15915 	return (rval);
15916 }
15917 
15918 static int
15919 st_mtbsr_ioctl(struct scsi_tape *un, int64_t num)
15920 {
15921 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
15922 
15923 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15924 	    "bsr: count=%"PRIx64", eof=%x\n", num, un->un_pos.eof);
15925 
15926 	if (un->un_pos.pmode == legacy) {
15927 		/*
15928 		 * backward space into inter-record gap
15929 		 *
15930 		 * If a negative count (which implies a forward space op)
15931 		 * is specified, and we're at logical or physical eot,
15932 		 * bounce the request.
15933 		 */
15934 		if (un->un_pos.eof >= ST_EOT && num < 0) {
15935 			un->un_err_resid = num;
15936 			un->un_status = SUN_KEY_EOT;
15937 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15938 			    "st_ioctl : EIO : MTBSR > EOT");
15939 			return (EIO);
15940 		}
15941 
15942 		if (num == 0) {
15943 			COPY_POS(&un->un_err_pos, &un->un_pos);
15944 			un->un_err_resid = 0;
15945 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15946 				un->un_status = SUN_KEY_EOF;
15947 			}
15948 			return (0);
15949 		}
15950 
15951 		/*
15952 		 * physical tape position may not be what we've been
15953 		 * telling the user; adjust the position accordingly.
15954 		 * bsr can not skip filemarks and continue to skip records
15955 		 * therefore if we are logically before the filemark but
15956 		 * physically at the EOT side of the filemark, we need to step
15957 		 * back; this allows fsr N where N > number of blocks in file
15958 		 * followed by bsr 1 to position at the beginning of last block
15959 		 */
15960 		if (IN_EOF(un->un_pos)) {
15961 			tapepos_t save;
15962 			optype lastop = un->un_lastop;
15963 
15964 			COPY_POS(&save, &un->un_pos);
15965 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD) == -1) {
15966 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15967 				    "st_mtbsr_ioctl: EIO : MTBSR can't space");
15968 				return (EIO);
15969 			}
15970 
15971 			COPY_POS(&un->un_pos, &save);
15972 			un->un_lastop = lastop;
15973 		}
15974 	}
15975 
15976 	un->un_pos.eof = ST_NO_EOF;
15977 
15978 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15979 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15980 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
15981 		return (EIO);
15982 	}
15983 
15984 	num = -num;
15985 	return (st_space_records(un, num));
15986 }
15987 
15988 static int
15989 st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt)
15990 {
15991 	int rval;
15992 
15993 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
15994 
15995 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
15996 	if (rval == 0) {
15997 		un->un_pos.pmode = logical;
15998 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15999 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
16000 		/*
16001 		 * Drive says invalid field in cdb.
16002 		 * Doesn't like space multiple. Position isn't lost.
16003 		 */
16004 		un->un_err_resid = cnt;
16005 		un->un_status = 0;
16006 		rval = ENOTTY;
16007 	} else {
16008 		un->un_err_resid = cnt;
16009 		un->un_pos.pmode = invalid;
16010 	}
16011 	return (rval);
16012 }
16013 
16014 static int
16015 st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt)
16016 {
16017 	int rval;
16018 
16019 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
16020 
16021 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
16022 	if (rval == 0) {
16023 		un->un_pos.pmode = logical;
16024 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
16025 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
16026 		/*
16027 		 * Drive says invalid field in cdb.
16028 		 * Doesn't like space multiple. Position isn't lost.
16029 		 */
16030 		un->un_err_resid = cnt;
16031 		un->un_status = 0;
16032 		rval = ENOTTY;
16033 	} else {
16034 		un->un_err_resid = cnt;
16035 		un->un_pos.pmode = invalid;
16036 	}
16037 	return (rval);
16038 }
16039 
16040 #ifdef	__x86
16041 
16042 /*
16043  * release contig_mem and wake up waiting thread, if any
16044  */
16045 static void
16046 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
16047 {
16048 	mutex_enter(ST_MUTEX);
16049 
16050 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
16051 
16052 	cp->cm_next = un->un_contig_mem;
16053 	un->un_contig_mem = cp;
16054 	un->un_contig_mem_available_num++;
16055 	cv_broadcast(&un->un_contig_mem_cv);
16056 
16057 	mutex_exit(ST_MUTEX);
16058 }
16059 
16060 /*
16061  * St_get_contig_mem will return a contig_mem if there is one available
16062  * in current system. Otherwise, it will try to alloc one, if the total
16063  * number of contig_mem is within st_max_contig_mem_num.
16064  * It will sleep, if allowed by caller or return NULL, if no contig_mem
16065  * is available for now.
16066  */
16067 static struct contig_mem *
16068 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
16069 {
16070 	size_t rlen;
16071 	struct contig_mem *cp = NULL;
16072 	ddi_acc_handle_t acc_hdl;
16073 	caddr_t addr;
16074 	int big_enough = 0;
16075 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
16076 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
16077 
16078 	/* Try to get one available contig_mem */
16079 	mutex_enter(ST_MUTEX);
16080 
16081 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
16082 
16083 	if (un->un_contig_mem_available_num > 0) {
16084 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16085 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
16086 		/*
16087 		 * we failed to get one. we're going to
16088 		 * alloc one more contig_mem for this I/O
16089 		 */
16090 		mutex_exit(ST_MUTEX);
16091 		cp = (struct contig_mem *)kmem_zalloc(
16092 		    sizeof (struct contig_mem) + biosize(),
16093 		    alloc_flags);
16094 		if (cp == NULL) {
16095 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16096 			    "alloc contig_mem failure\n");
16097 			return (NULL); /* cannot get one */
16098 		}
16099 		cp->cm_bp = (struct buf *)
16100 		    (((caddr_t)cp) + sizeof (struct contig_mem));
16101 		bioinit(cp->cm_bp);
16102 		mutex_enter(ST_MUTEX);
16103 		un->un_contig_mem_total_num++; /* one more available */
16104 	} else {
16105 		/*
16106 		 * we failed to get one and we're NOT allowed to
16107 		 * alloc more contig_mem
16108 		 */
16109 		if (alloc_flags == KM_SLEEP) {
16110 			while (un->un_contig_mem_available_num <= 0) {
16111 				cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16112 			}
16113 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16114 		} else {
16115 			mutex_exit(ST_MUTEX);
16116 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16117 			    "alloc contig_mem failure\n");
16118 			return (NULL); /* cannot get one */
16119 		}
16120 	}
16121 	mutex_exit(ST_MUTEX);
16122 
16123 	/* We need to check if this block of mem is big enough for this I/O */
16124 	if (cp->cm_len < len) {
16125 		/* not big enough, need to alloc a new one */
16126 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
16127 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
16128 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
16129 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16130 			    "alloc contig_mem failure: not enough mem\n");
16131 			st_release_contig_mem(un, cp);
16132 			cp = NULL;
16133 		} else {
16134 			if (cp->cm_addr) {
16135 				/* release previous one before attach new one */
16136 				ddi_dma_mem_free(&cp->cm_acc_hdl);
16137 			}
16138 			mutex_enter(ST_MUTEX);
16139 			un->un_max_contig_mem_len =
16140 			    un->un_max_contig_mem_len >= len ?
16141 			    un->un_max_contig_mem_len : len;
16142 			mutex_exit(ST_MUTEX);
16143 
16144 			/* attach new mem to this cp */
16145 			cp->cm_addr = addr;
16146 			cp->cm_acc_hdl = acc_hdl;
16147 			cp->cm_len = len;
16148 
16149 			goto alloc_ok; /* get one usable cp */
16150 		}
16151 	} else {
16152 		goto alloc_ok; /* get one usable cp */
16153 	}
16154 
16155 	/* cannot find/alloc a usable cp, when we get here */
16156 
16157 	mutex_enter(ST_MUTEX);
16158 	if ((un->un_max_contig_mem_len < len) ||
16159 	    (alloc_flags != KM_SLEEP)) {
16160 		mutex_exit(ST_MUTEX);
16161 		return (NULL);
16162 	}
16163 
16164 	/*
16165 	 * we're allowed to sleep, and there is one big enough
16166 	 * contig mem in the system, which is currently in use,
16167 	 * wait for it...
16168 	 */
16169 	big_enough = 1;
16170 	do {
16171 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16172 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16173 	} while (cp == NULL);
16174 	mutex_exit(ST_MUTEX);
16175 
16176 	/* we get the big enough contig mem, finally */
16177 
16178 alloc_ok:
16179 	/* init bp attached to this cp */
16180 	bioreset(cp->cm_bp);
16181 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
16182 	cp->cm_bp->b_private = (void *)cp;
16183 
16184 	return (cp);
16185 }
16186 
16187 /*
16188  * this is the biodone func for the bp used in big block I/O
16189  */
16190 static int
16191 st_bigblk_xfer_done(struct buf *bp)
16192 {
16193 	struct contig_mem *cp;
16194 	struct buf *orig_bp;
16195 	int ioerr;
16196 	struct scsi_tape *un;
16197 
16198 	/* sanity check */
16199 	if (bp == NULL) {
16200 		return (DDI_FAILURE);
16201 	}
16202 
16203 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16204 	if (un == NULL) {
16205 		return (DDI_FAILURE);
16206 	}
16207 
16208 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
16209 
16210 	cp = (struct contig_mem *)bp->b_private;
16211 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
16212 	cp->cm_bp = bp;
16213 
16214 	/* special handling for special I/O */
16215 	if (cp->cm_use_sbuf) {
16216 #ifndef __lock_lint
16217 		ASSERT(un->un_sbuf_busy);
16218 #endif
16219 		un->un_sbufp = orig_bp;
16220 		cp->cm_use_sbuf = 0;
16221 	}
16222 
16223 	orig_bp->b_resid = bp->b_resid;
16224 	ioerr = geterror(bp);
16225 	if (ioerr != 0) {
16226 		bioerror(orig_bp, ioerr);
16227 	} else if (orig_bp->b_flags & B_READ) {
16228 		/* copy data back to original bp */
16229 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
16230 		    bp->b_bcount - bp->b_resid);
16231 	}
16232 
16233 	st_release_contig_mem(un, cp);
16234 
16235 	biodone(orig_bp);
16236 
16237 	return (DDI_SUCCESS);
16238 }
16239 
16240 /*
16241  * We use this func to replace original bp that may not be able to do I/O
16242  * in big block size with one that can
16243  */
16244 static struct buf *
16245 st_get_bigblk_bp(struct buf *bp)
16246 {
16247 	struct contig_mem *cp;
16248 	struct scsi_tape *un;
16249 	struct buf *cont_bp;
16250 
16251 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16252 	if (un == NULL) {
16253 		return (bp);
16254 	}
16255 
16256 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
16257 
16258 	/* try to get one contig_mem */
16259 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
16260 	if (!cp) {
16261 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
16262 		    "Cannot alloc contig buf for I/O for %lu blk size",
16263 		    bp->b_bcount);
16264 		return (bp);
16265 	}
16266 	cont_bp = cp->cm_bp;
16267 	cp->cm_bp = bp;
16268 
16269 	/* make sure that we "are" using un_sbufp for special I/O */
16270 	if (bp == un->un_sbufp) {
16271 #ifndef __lock_lint
16272 		ASSERT(un->un_sbuf_busy);
16273 #endif
16274 		un->un_sbufp = cont_bp;
16275 		cp->cm_use_sbuf = 1;
16276 	}
16277 
16278 	/* clone bp */
16279 	cont_bp->b_bcount = bp->b_bcount;
16280 	cont_bp->b_resid = bp->b_resid;
16281 	cont_bp->b_iodone = st_bigblk_xfer_done;
16282 	cont_bp->b_file = bp->b_file;
16283 	cont_bp->b_offset = bp->b_offset;
16284 	cont_bp->b_dip = bp->b_dip;
16285 	cont_bp->b_error = 0;
16286 	cont_bp->b_proc = NULL;
16287 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
16288 	cont_bp->b_shadow = NULL;
16289 	cont_bp->b_pages = NULL;
16290 	cont_bp->b_edev = bp->b_edev;
16291 	cont_bp->b_dev = bp->b_dev;
16292 	cont_bp->b_lblkno = bp->b_lblkno;
16293 	cont_bp->b_forw = bp->b_forw;
16294 	cont_bp->b_back = bp->b_back;
16295 	cont_bp->av_forw = bp->av_forw;
16296 	cont_bp->av_back = bp->av_back;
16297 	cont_bp->b_bufsize = bp->b_bufsize;
16298 
16299 	/* get data in original bp */
16300 	if (bp->b_flags & B_WRITE) {
16301 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
16302 	}
16303 
16304 	return (cont_bp);
16305 }
16306 #else
16307 #ifdef __lock_lint
16308 static int
16309 st_bigblk_xfer_done(struct buf *bp)
16310 {
16311 	return (0);
16312 }
16313 #endif
16314 #endif
16315 
16316 static const char *eof_status[] =
16317 {
16318 	"NO_EOF",
16319 	"EOF_PENDING",
16320 	"EOF",
16321 	"EOT_PENDING",
16322 	"EOT",
16323 	"EOM",
16324 	"AFTER_EOM"
16325 };
16326 static const char *mode[] = {
16327 	"invalid",
16328 	"legacy",
16329 	"logical"
16330 };
16331 
16332 static void
16333 st_print_position(dev_info_t *dev, char *label, uint_t level,
16334 const char *comment, tapepos_t *pos)
16335 {
16336 	ST_FUNC(dev, st_print_position);
16337 
16338 	scsi_log(dev, label, level,
16339 	    "%s Position data:\n", comment);
16340 	scsi_log(dev, label, CE_CONT,
16341 	    "Positioning mode = %s", mode[pos->pmode]);
16342 	scsi_log(dev, label, CE_CONT,
16343 	    "End Of File/Tape = %s", eof_status[pos->eof]);
16344 	scsi_log(dev, label, CE_CONT,
16345 	    "File Number      = 0x%x", pos->fileno);
16346 	scsi_log(dev, label, CE_CONT,
16347 	    "Block Number     = 0x%x", pos->blkno);
16348 	scsi_log(dev, label, CE_CONT,
16349 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
16350 	scsi_log(dev, label, CE_CONT,
16351 	    "Partition Number = 0x%x", pos->partition);
16352 }
16353 static int
16354 st_check_if_media_changed(struct scsi_tape *un, caddr_t data, int size)
16355 {
16356 
16357 	int result = 0;
16358 	int i;
16359 	ST_FUNC(ST_DEVINFO, st_check_if_media_changed);
16360 
16361 	/*
16362 	 * find non alpha numeric working from the end.
16363 	 */
16364 	for (i = size - 1; i >= 0; i--) {
16365 		if (ISALNUM(data[i]) == 0 || data[i] == ' ') {
16366 			data[i] = 0;
16367 			size = i;
16368 		}
16369 	}
16370 
16371 	if (size == 1) {
16372 		/*
16373 		 * Drive seems to think its returning useful data
16374 		 * but it looks like all junk
16375 		 */
16376 		return (result);
16377 	}
16378 
16379 	size++;
16380 
16381 	/*
16382 	 * Actually got a valid serial number.
16383 	 * If never stored one before alloc space for it.
16384 	 */
16385 	if (un->un_media_id_len == 0) {
16386 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16387 		un->un_media_id_len = size;
16388 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16389 		un->un_media_id[min(size, strlen(data))] = 0;
16390 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16391 		    "Found Media Id %s length = %d\n", un->un_media_id, size);
16392 	} else if (size > un->un_media_id_len) {
16393 		if (strncmp(un->un_media_id, data, size) != 0) {
16394 			result = ESPIPE;
16395 		}
16396 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16397 		    "Longer Media Id old ID:%s new ID:%s\n",
16398 		    un->un_media_id, data);
16399 		kmem_free(un->un_media_id, un->un_media_id_len);
16400 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16401 		un->un_media_id_len = size;
16402 		(void) strncpy(un->un_media_id, data, size);
16403 		un->un_media_id[size] = 0;
16404 	} else if (strncmp(data, un->un_media_id,
16405 	    min(size, un->un_media_id_len)) != 0) {
16406 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16407 		    "Old Media Id %s length = %d New %s length = %d\n",
16408 		    un->un_media_id, un->un_media_id_len, data, size);
16409 		bzero(un->un_media_id, un->un_media_id_len);
16410 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16411 		un->un_media_id[min(size, strlen(data))] = 0;
16412 		result = ESPIPE;
16413 	} else {
16414 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
16415 		    "Media Id still %s\n", un->un_media_id);
16416 	}
16417 
16418 	ASSERT(strlen(un->un_media_id) <= size);
16419 
16420 	return (result);
16421 }
16422 #define	ID_SIZE 32
16423 typedef struct
16424 {
16425 	uchar_t avilable_data0;
16426 	uchar_t avilable_data1;
16427 	uchar_t avilable_data2;
16428 	uchar_t avilable_data3;
16429 	uchar_t attribute_msb;
16430 	uchar_t attribute_lsb;
16431 #ifdef _BIT_FIELDS_LTOH
16432 	uchar_t format		: 2,
16433 				: 5,
16434 		read_only	: 1;
16435 #else
16436 	uchar_t read_only	: 1,
16437 				: 5,
16438 		format		: 2;
16439 #endif
16440 	uchar_t attribute_len_msb;
16441 	uchar_t attribute_len_lsb;
16442 }attribute_header;
16443 
16444 typedef struct {
16445 	attribute_header header;
16446 	char data[1];
16447 }mam_attribute;
16448 
16449 static int
16450 st_handle_hex_media_id(struct scsi_tape *un, void *pnt, int size)
16451 {
16452 	int result;
16453 	int newsize = (size << 1) + 3; /* extra for leading 0x and null term */
16454 	int i;
16455 	uchar_t byte;
16456 	char *format;
16457 	uchar_t *data = (uchar_t *)pnt;
16458 	char *buf = kmem_alloc(newsize, KM_SLEEP);
16459 
16460 	ST_FUNC(ST_DEVINFO, st_handle_hex_media_id);
16461 
16462 	(void) sprintf(buf, "0x");
16463 	for (i = 0; i < size; i++) {
16464 		byte = data[i];
16465 		if (byte < 0x10)
16466 			format = "0%x";
16467 		else
16468 			format = "%x";
16469 		(void) sprintf(&buf[(int)strlen(buf)], format, byte);
16470 	}
16471 	result = st_check_if_media_changed(un, buf, newsize);
16472 
16473 	kmem_free(buf, newsize);
16474 
16475 	return (result);
16476 }
16477 
16478 
16479 static int
16480 st_get_media_id_via_read_attribute(struct scsi_tape *un, ubufunc_t bufunc)
16481 {
16482 	int result;
16483 	mam_attribute *buffer;
16484 	int size;
16485 	int newsize;
16486 
16487 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_read_attribute);
16488 	size = sizeof (attribute_header) + max(un->un_media_id_len, ID_SIZE);
16489 again:
16490 	buffer = kmem_zalloc(size, KM_SLEEP);
16491 	result = st_read_attributes(un, 0x0401, buffer, size, bufunc);
16492 	if (result == 0) {
16493 
16494 		newsize = (buffer->header.attribute_len_msb << 8) |
16495 		    buffer->header.attribute_len_lsb;
16496 
16497 		if (newsize + sizeof (attribute_header) > size) {
16498 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
16499 			    "resizing read attribute data from %d to %d format"
16500 			    " %d\n", size, (int)sizeof (attribute_header) +
16501 			    newsize, buffer->header.format);
16502 			kmem_free(buffer, size);
16503 			size = newsize + sizeof (attribute_header);
16504 			goto again;
16505 		}
16506 
16507 		un->un_media_id_method = st_get_media_id_via_read_attribute;
16508 		if (buffer->header.format == 0) {
16509 			result =
16510 			    st_handle_hex_media_id(un, buffer->data, newsize);
16511 		} else {
16512 			result = st_check_if_media_changed(un, buffer->data,
16513 			    newsize);
16514 		}
16515 	} else if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
16516 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
16517 		    "Read Attribute Command for Media Identification is not "
16518 		    "supported on the HBA that this drive is attached to.");
16519 		result = ENOTTY;
16520 	}
16521 
16522 	kmem_free(buffer, size);
16523 	un->un_status = 0;
16524 
16525 	return (result);
16526 }
16527 
16528 
16529 static int
16530 st_get_media_id_via_media_serial_cmd(struct scsi_tape *un, ubufunc_t bufunc)
16531 {
16532 	char cdb[CDB_GROUP5];
16533 	struct uscsi_cmd *ucmd;
16534 	struct scsi_extended_sense sense;
16535 	int rval;
16536 	int size = max(un->un_media_id_len, ID_SIZE);
16537 	caddr_t buf;
16538 
16539 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_media_serial_cmd);
16540 
16541 	if (un->un_sd->sd_inq->inq_ansi < 3) {
16542 		return (ENOTTY);
16543 	}
16544 
16545 	ucmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
16546 upsize:
16547 	buf = kmem_alloc(size, KM_SLEEP);
16548 
16549 	cdb[0] = (char)SCMD_SVC_ACTION_IN_G5;
16550 	cdb[1] = SSVC_ACTION_READ_MEDIA_SERIAL;
16551 	cdb[2] = 0;
16552 	cdb[3] = 0;
16553 	cdb[4] = 0;
16554 	cdb[5] = 0;
16555 	cdb[6] = (char)(size >> 24);
16556 	cdb[7] = (char)(size >> 16);
16557 	cdb[8] = (char)(size >> 8);
16558 	cdb[9] = (char)(size);
16559 	cdb[10] = 0;
16560 	cdb[11] = 0;
16561 
16562 	ucmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
16563 	ucmd->uscsi_timeout = un->un_dp->non_motion_timeout;
16564 	ucmd->uscsi_cdb = &cdb[0];
16565 	ucmd->uscsi_cdblen = sizeof (cdb);
16566 	ucmd->uscsi_bufaddr = buf;
16567 	ucmd->uscsi_buflen = size;
16568 	ucmd->uscsi_rqbuf = (caddr_t)&sense;
16569 	ucmd->uscsi_rqlen = sizeof (sense);
16570 
16571 	rval = bufunc(un, ucmd, FKIOCTL);
16572 
16573 	if (rval || ucmd->uscsi_status != 0) {
16574 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16575 		    "media serial command returned %d scsi_status %d"
16576 		    " rqstatus %d", rval, ucmd->uscsi_status,
16577 		    ucmd->uscsi_rqstatus);
16578 		/*
16579 		 * If this returns invalid operation code don't try again.
16580 		 */
16581 		if (sense.es_key == KEY_ILLEGAL_REQUEST &&
16582 		    sense.es_add_code == 0x20) {
16583 			rval = ENOTTY;
16584 		} else if (rval == 0) {
16585 			rval = EIO;
16586 		}
16587 		un->un_status = 0;
16588 	} else {
16589 		int act_size;
16590 
16591 		/*
16592 		 * get reported size.
16593 		 */
16594 		act_size = (int)buf[3] | (int)(buf[2] << 8) |
16595 		    (int)(buf[1] << 16) | (int)(buf[0] << 24);
16596 
16597 		/* documentation says mod 4. */
16598 		while (act_size & 3) {
16599 			act_size++;
16600 		}
16601 
16602 		/*
16603 		 * If reported size is larger that we our buffer.
16604 		 * Free the old one and allocate one that is larger
16605 		 * enough and re-issuse the command.
16606 		 */
16607 		if (act_size + 4 > size) {
16608 			kmem_free(buf, size);
16609 			size = act_size + 4;
16610 			goto upsize;
16611 		}
16612 
16613 		if (act_size == 0) {
16614 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16615 			    "media serial number is not available");
16616 			un->un_status = 0;
16617 			rval = 0;
16618 		} else {
16619 			/*
16620 			 * set data pointer to point to the start
16621 			 * of that serial number.
16622 			 */
16623 			un->un_media_id_method =
16624 			    st_get_media_id_via_media_serial_cmd;
16625 			rval =
16626 			    st_check_if_media_changed(un, &buf[4], act_size);
16627 		}
16628 	}
16629 
16630 	kmem_free(ucmd, sizeof (struct uscsi_cmd));
16631 	kmem_free(buf, size);
16632 
16633 	return (rval);
16634 }
16635 
16636 
16637 /* ARGSUSED */
16638 static int
16639 st_bogus_media_id(struct scsi_tape *un, ubufunc_t bufunc)
16640 {
16641 	ST_FUNC(ST_DEVINFO, st_bogus_media_id);
16642 
16643 	ASSERT(un->un_media_id == NULL || un->un_media_id == bogusID);
16644 	ASSERT(un->un_media_id_len == 0);
16645 	un->un_media_id = (char *)bogusID;
16646 	un->un_media_id_len = 0;
16647 	return (0);
16648 }
16649 
16650 typedef int (*media_chk_function)(struct scsi_tape *, ubufunc_t bufunc);
16651 
16652 media_chk_function media_chk_functions[] = {
16653 	st_get_media_id_via_media_serial_cmd,
16654 	st_get_media_id_via_read_attribute,
16655 	st_bogus_media_id
16656 };
16657 
16658 static int
16659 st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc)
16660 {
16661 	int result = 0;
16662 	int i;
16663 
16664 	ST_FUNC(ST_DEVINFO, st_get_media_identification);
16665 
16666 	for (i = 0; i < ST_NUM_MEMBERS(media_chk_functions); i++) {
16667 		if (result == ENOTTY) {
16668 			/*
16669 			 * Last operation type not supported by this device.
16670 			 * Make so next time it doesn`t do that again.
16671 			 */
16672 			un->un_media_id_method = media_chk_functions[i];
16673 		} else if (un->un_media_id_method != media_chk_functions[i] &&
16674 		    un->un_media_id_method != st_get_media_identification) {
16675 			continue;
16676 		}
16677 		result = media_chk_functions[i](un, bufunc);
16678 		/*
16679 		 * If result indicates the function was successful or
16680 		 * that the media is not the same as last known, break.
16681 		 */
16682 		if (result == 0 || result == ESPIPE) {
16683 			break;
16684 		}
16685 	}
16686 
16687 	return (result);
16688 }
16689 
16690 static errstate
16691 st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
16692     errstate onentry)
16693 {
16694 
16695 	int ret;
16696 	st_err_info *errinfo;
16697 	recov_info *ri = (recov_info *)pkt->pkt_private;
16698 
16699 	ST_FUNC(ST_DEVINFO, st_command_recovery);
16700 
16701 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16702 
16703 	ASSERT(un->un_recov_buf_busy == 0);
16704 
16705 	/*
16706 	 * Don't try and recover a reset that this device sent.
16707 	 */
16708 	if (un->un_rsvd_status & ST_INITIATED_RESET &&
16709 	    onentry == DEVICE_RESET) {
16710 		return (COMMAND_DONE_ERROR);
16711 	}
16712 
16713 	/*
16714 	 * See if expected position was passed with scsi_pkt.
16715 	 */
16716 	if (ri->privatelen == sizeof (recov_info)) {
16717 
16718 		/*
16719 		 * Not for this command.
16720 		 */
16721 		if (ri->cmd_attrib->do_not_recover) {
16722 			return (COMMAND_DONE_ERROR);
16723 		}
16724 
16725 		/*
16726 		 * Create structure to hold all error state info.
16727 		 */
16728 		errinfo = kmem_zalloc(ST_ERR_INFO_SIZE, KM_SLEEP);
16729 		errinfo->ei_error_type = onentry;
16730 		errinfo->ei_failing_bp = ri->cmd_bp;
16731 		COPY_POS(&errinfo->ei_expected_pos, &ri->pos);
16732 	} else {
16733 		/* disabled */
16734 		return (COMMAND_DONE_ERROR);
16735 	}
16736 
16737 	bcopy(pkt, &errinfo->ei_failed_pkt, scsi_pkt_size());
16738 	bcopy(pkt->pkt_scbp, &errinfo->ei_failing_status, SECMDS_STATUS_SIZE);
16739 	ret = ddi_taskq_dispatch(un->un_recov_taskq, st_recover, errinfo,
16740 	    DDI_NOSLEEP);
16741 	ASSERT(ret == DDI_SUCCESS);
16742 	if (ret != DDI_SUCCESS) {
16743 		kmem_free(errinfo, ST_ERR_INFO_SIZE);
16744 		return (COMMAND_DONE_ERROR);
16745 	}
16746 	return (JUST_RETURN); /* release calling thread */
16747 }
16748 
16749 
16750 static void
16751 st_recov_ret(struct scsi_tape *un, st_err_info *errinfo, errstate err)
16752 {
16753 	int error_number;
16754 	buf_t *bp;
16755 
16756 
16757 	ST_FUNC(ST_DEVINFO, st_recov_ret);
16758 
16759 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16760 #if !defined(lint)
16761 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
16762 #endif
16763 
16764 	bp = errinfo->ei_failing_bp;
16765 	kmem_free(errinfo, ST_ERR_INFO_SIZE);
16766 
16767 	switch (err) {
16768 	case JUST_RETURN:
16769 		mutex_exit(&un->un_sd->sd_mutex);
16770 		return;
16771 
16772 	case COMMAND_DONE:
16773 	case COMMAND_DONE_ERROR_RECOVERED:
16774 		ST_DO_KSTATS(bp, kstat_runq_exit);
16775 		error_number = 0;
16776 		break;
16777 
16778 	default:
16779 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16780 		    "st_recov_ret with unhandled errstat %d\n", err);
16781 		/* FALLTHROUGH */
16782 	case COMMAND_DONE_ERROR:
16783 		un->un_pos.pmode = invalid;
16784 		un->un_running.pmode = invalid;
16785 		/* FALLTHROUGH */
16786 	case COMMAND_DONE_EACCES:
16787 		ST_DO_KSTATS(bp, kstat_waitq_exit);
16788 		ST_DO_ERRSTATS(un, st_transerrs);
16789 		error_number = EIO;
16790 		st_set_pe_flag(un);
16791 		break;
16792 
16793 	}
16794 
16795 	st_bioerror(bp, error_number);
16796 	st_done_and_mutex_exit(un, bp);
16797 }
16798 
16799 
16800 static void
16801 st_recover(void *arg)
16802 {
16803 	st_err_info *const errinfo = (st_err_info *)arg;
16804 	uchar_t com = errinfo->ei_failed_pkt.pkt_cdbp[0];
16805 	struct scsi_tape *un;
16806 	tapepos_t cur_pos;
16807 	int rval;
16808 	errstate status = COMMAND_DONE_ERROR;
16809 	recov_info *rcv;
16810 	buf_t *bp;
16811 
16812 
16813 	rcv = errinfo->ei_failed_pkt.pkt_private;
16814 	ASSERT(rcv->privatelen == sizeof (recov_info));
16815 	bp = rcv->cmd_bp;
16816 
16817 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16818 
16819 	ASSERT(un != NULL);
16820 
16821 	mutex_enter(ST_MUTEX);
16822 
16823 	ST_FUNC(ST_DEVINFO, st_recover);
16824 
16825 	ST_CDB(ST_DEVINFO, "Recovering command",
16826 	    (caddr_t)errinfo->ei_failed_pkt.pkt_cdbp);
16827 	ST_SENSE(ST_DEVINFO, "sense status for failed command",
16828 	    (caddr_t)&errinfo->ei_failing_status,
16829 	    sizeof (struct scsi_arq_status));
16830 	ST_POS(ST_DEVINFO, rcv->cmd_attrib->recov_pos_type == POS_STARTING ?
16831 	    "starting position for recovery command" :
16832 	    "expected position for recovery command",
16833 	    &errinfo->ei_expected_pos);
16834 
16835 	rval = st_test_path_to_device(un);
16836 
16837 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16838 	    "st_recover called with %s, TUR returned %d\n",
16839 	    errstatenames[errinfo->ei_error_type], rval);
16840 	/*
16841 	 * If the drive responed to the TUR lets try and get it to sync
16842 	 * any data it might have in the buffer.
16843 	 */
16844 	if (rval == 0 && rcv->cmd_attrib->chg_tape_data) {
16845 		rval = st_rcmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
16846 		if (rval) {
16847 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16848 			    "st_recover failed to flush, returned %d\n", rval);
16849 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16850 			return;
16851 		}
16852 	}
16853 	switch (errinfo->ei_error_type) {
16854 	case ATTEMPT_RETRY:
16855 	case COMMAND_TIMEOUT:
16856 	case DEVICE_RESET:
16857 	case PATH_FAILED:
16858 		/*
16859 		 * For now if we can't talk to the device we are done.
16860 		 * If the drive is reserved we can try to get it back.
16861 		 */
16862 		if (rval != 0 && rval != EACCES) {
16863 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16864 			return;
16865 		}
16866 
16867 		/*
16868 		 * If reservation conflict and do a preempt, fail it.
16869 		 */
16870 		if ((un->un_rsvd_status &
16871 		    (ST_APPLICATION_RESERVATIONS | ST_RESERVE)) != 0) {
16872 			if ((errinfo->ei_failed_pkt.pkt_cdbp[0] ==
16873 			    SCMD_PERSISTENT_RESERVE_OUT) &&
16874 			    (errinfo->ei_failed_pkt.pkt_cdbp[1] ==
16875 			    ST_SA_SCSI3_PREEMPT) &&
16876 			    (SCBP_C(&errinfo->ei_failed_pkt) ==
16877 			    STATUS_RESERVATION_CONFLICT)) {
16878 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16879 				return;
16880 			}
16881 		}
16882 
16883 		/*
16884 		 * If scsi II lost reserve try and get it back.
16885 		 */
16886 		if ((((un->un_rsvd_status &
16887 		    (ST_LOST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
16888 		    ST_LOST_RESERVE)) &&
16889 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] != SCMD_RELEASE)) {
16890 			rval = st_reserve_release(un, ST_RESERVE,
16891 			    st_uscsi_rcmd);
16892 			if (rval != 0) {
16893 				if (st_take_ownership(un, st_uscsi_rcmd) != 0) {
16894 					st_recov_ret(un, errinfo,
16895 					    COMMAND_DONE_EACCES);
16896 					return;
16897 				}
16898 			}
16899 			un->un_rsvd_status |= ST_RESERVE;
16900 			un->un_rsvd_status &= ~(ST_RELEASE | ST_LOST_RESERVE |
16901 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
16902 		}
16903 		rval = st_make_sure_mode_data_is_correct(un, st_uscsi_rcmd);
16904 		if (rval) {
16905 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16906 			return;
16907 		}
16908 		break;
16909 	case DEVICE_TAMPER:
16910 		/*
16911 		 * Check if the ASC/ASCQ says mode data has changed.
16912 		 */
16913 		if ((errinfo->ei_failing_status.sts_sensedata.es_add_code ==
16914 		    0x2a) &&
16915 		    (errinfo->ei_failing_status.sts_sensedata.es_qual_code ==
16916 		    0x01)) {
16917 			/*
16918 			 * See if mode sense changed.
16919 			 */
16920 			rval = st_make_sure_mode_data_is_correct(un,
16921 			    st_uscsi_rcmd);
16922 			if (rval) {
16923 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16924 				return;
16925 			}
16926 		}
16927 		/*
16928 		 * if we have a media id and its not bogus.
16929 		 * Check to see if it the same.
16930 		 */
16931 		if (un->un_media_id != NULL && un->un_media_id != bogusID) {
16932 			rval = st_get_media_identification(un, st_uscsi_rcmd);
16933 			if (rval == ESPIPE) {
16934 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16935 				return;
16936 			}
16937 		}
16938 		break;
16939 	default:
16940 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16941 		    "Unhandled error type %s in st_recover() 0x%x\n",
16942 		    errstatenames[errinfo->ei_error_type], com);
16943 	}
16944 
16945 	/*
16946 	 * if command is retriable retry it.
16947 	 * Special case here. The command attribute for SCMD_REQUEST_SENSE
16948 	 * does not say that it is retriable. That because if you reissue a
16949 	 * request sense and the target responds the sense data will have
16950 	 * been consumed and no long be valid. If we get a busy status on
16951 	 * request sense while the state is ST_STATE_SENSING this will
16952 	 * reissue that pkt.
16953 	 *
16954 	 * XXX If this request sense gets sent to a different port then
16955 	 * the original command that failed was sent on it will not get
16956 	 * valid sense data for that command.
16957 	 */
16958 	if (rcv->cmd_attrib->retriable || un->un_rqs_bp == bp) {
16959 		status = st_recover_reissue_pkt(un, &errinfo->ei_failed_pkt);
16960 
16961 	/*
16962 	 * if drive doesn't support read position we are done
16963 	 */
16964 	} else if (un->un_read_pos_type == NO_POS) {
16965 		status = COMMAND_DONE_ERROR;
16966 	/*
16967 	 * If this command results in a changed tape position,
16968 	 * lets see where we are.
16969 	 */
16970 	} else if (rcv->cmd_attrib->chg_tape_pos) {
16971 		/*
16972 		 * XXX May be a reason to choose a different type here.
16973 		 * Long format has file position information.
16974 		 * Short and Extended have information about whats
16975 		 * in the buffer. St's positioning assumes in the buffer
16976 		 * to be the same as on tape.
16977 		 */
16978 		rval = st_compare_expected_position(un, errinfo,
16979 		    rcv->cmd_attrib, &cur_pos);
16980 		if (rval == 0) {
16981 			status = COMMAND_DONE;
16982 		} else if (rval == EAGAIN) {
16983 			status = st_recover_reissue_pkt(un,
16984 			    &errinfo->ei_failed_pkt);
16985 		} else {
16986 			status = COMMAND_DONE_ERROR;
16987 		}
16988 	} else {
16989 		ASSERT(0);
16990 	}
16991 
16992 	st_recov_ret(un, errinfo, status);
16993 }
16994 
16995 static void
16996 st_recov_cb(struct scsi_pkt *pkt)
16997 {
16998 	struct scsi_tape *un;
16999 	struct buf *bp;
17000 	recov_info *rcv;
17001 	errstate action = COMMAND_DONE_ERROR;
17002 	int timout = ST_TRAN_BUSY_TIMEOUT; /* short (default) timeout */
17003 
17004 	/*
17005 	 * Get the buf from the packet.
17006 	 */
17007 	rcv = pkt->pkt_private;
17008 	ASSERT(rcv->privatelen == sizeof (recov_info));
17009 	bp = rcv->cmd_bp;
17010 
17011 	/*
17012 	 * get the unit from the buf.
17013 	 */
17014 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
17015 	ASSERT(un != NULL);
17016 
17017 	ST_FUNC(ST_DEVINFO, st_recov_cb);
17018 
17019 	mutex_enter(ST_MUTEX);
17020 
17021 	ASSERT(bp == un->un_recov_buf);
17022 
17023 
17024 	switch (pkt->pkt_reason) {
17025 	case CMD_CMPLT:
17026 		if (un->un_arq_enabled && pkt->pkt_state & STATE_ARQ_DONE) {
17027 			action = st_handle_autosense(un, bp, &rcv->pos);
17028 		} else  if ((SCBP(pkt)->sts_busy) ||
17029 		    (SCBP(pkt)->sts_chk) ||
17030 		    (SCBP(pkt)->sts_vu7)) {
17031 			action = st_check_error(un, pkt);
17032 		} else {
17033 			action = COMMAND_DONE;
17034 		}
17035 		break;
17036 	case CMD_TIMEOUT:
17037 		action = COMMAND_TIMEOUT;
17038 		break;
17039 	case CMD_TRAN_ERR:
17040 		action = QUE_COMMAND;
17041 		break;
17042 	case CMD_DEV_GONE:
17043 		if (un->un_multipath)
17044 			action = PATH_FAILED;
17045 		else
17046 			action = COMMAND_DONE_ERROR;
17047 		break;
17048 	default:
17049 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
17050 		    "pkt_reason not handled yet %s",
17051 		    scsi_rname(pkt->pkt_reason));
17052 		action = COMMAND_DONE_ERROR;
17053 	}
17054 
17055 	/*
17056 	 * check for undetected path failover.
17057 	 */
17058 	if (un->un_multipath) {
17059 		if (scsi_pkt_allocated_correctly(pkt) &&
17060 		    (un->un_last_path_instance != pkt->pkt_path_instance)) {
17061 			if (un->un_state > ST_STATE_OPENING) {
17062 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17063 				    "Failover detected in recovery, action is "
17064 				    "%s\n", errstatenames[action]);
17065 			}
17066 			un->un_last_path_instance = pkt->pkt_path_instance;
17067 		}
17068 	}
17069 
17070 	ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
17071 	    "Recovery call back got %s status on %s\n",
17072 	    errstatenames[action], st_print_scsi_cmd(pkt->pkt_cdbp[0]));
17073 
17074 	switch (action) {
17075 	case COMMAND_DONE:
17076 		break;
17077 
17078 	case COMMAND_DONE_EACCES:
17079 		bioerror(bp, EACCES);
17080 		break;
17081 
17082 	case COMMAND_DONE_ERROR_RECOVERED: /* XXX maybe wrong */
17083 		ASSERT(0);
17084 		break;
17085 
17086 	case COMMAND_TIMEOUT:
17087 	case COMMAND_DONE_ERROR:
17088 		bioerror(bp, EIO);
17089 		break;
17090 
17091 	case DEVICE_RESET:
17092 	case QUE_BUSY_COMMAND:
17093 	case PATH_FAILED:
17094 		/* longish timeout */
17095 		timout = ST_STATUS_BUSY_TIMEOUT;
17096 		/* FALLTHRU */
17097 	case QUE_COMMAND:
17098 	case DEVICE_TAMPER:
17099 	case ATTEMPT_RETRY:
17100 		/*
17101 		 * let st_handle_intr_busy put this bp back on waitq and make
17102 		 * checks to see if it is ok to requeue the command.
17103 		 */
17104 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
17105 
17106 		/*
17107 		 * Save the throttle before setting up the timeout
17108 		 */
17109 		if (un->un_throttle) {
17110 			un->un_last_throttle = un->un_throttle;
17111 		}
17112 		mutex_exit(ST_MUTEX);
17113 		if (st_handle_intr_busy(un, bp, timout) == 0) {
17114 			return;		/* timeout is setup again */
17115 		}
17116 		mutex_enter(ST_MUTEX);
17117 		un->un_pos.pmode = invalid;
17118 		un->un_err_resid = bp->b_resid = bp->b_bcount;
17119 		st_bioerror(bp, EIO);
17120 		st_set_pe_flag(un);
17121 		break;
17122 
17123 	default:
17124 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
17125 		    "Unhandled recovery state 0x%x\n", action);
17126 		un->un_pos.pmode = invalid;
17127 		un->un_err_resid = bp->b_resid = bp->b_bcount;
17128 		st_bioerror(bp, EIO);
17129 		st_set_pe_flag(un);
17130 		break;
17131 	}
17132 
17133 	st_done_and_mutex_exit(un, bp);
17134 }
17135 
17136 static int
17137 st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait)
17138 {
17139 	struct buf *bp;
17140 	int err;
17141 
17142 	ST_FUNC(ST_DEVINFO, st_rcmd);
17143 
17144 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
17145 	    "st_rcmd(un = 0x%p, com = 0x%x, count = %"PRIx64", wait = %d)\n",
17146 	    (void *)un, com, count, wait);
17147 
17148 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
17149 	ASSERT(mutex_owned(ST_MUTEX));
17150 
17151 #ifdef STDEBUG
17152 	if ((st_debug & 0x7)) {
17153 		st_debug_cmds(un, com, count, wait);
17154 	}
17155 #endif
17156 
17157 	while (un->un_recov_buf_busy)
17158 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17159 	un->un_recov_buf_busy = 1;
17160 
17161 	bp = un->un_recov_buf;
17162 	bzero(bp, sizeof (buf_t));
17163 
17164 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
17165 
17166 	err = st_setup_cmd(un, bp, com, count);
17167 
17168 	un->un_recov_buf_busy = 0;
17169 
17170 	cv_signal(&un->un_recov_buf_cv);
17171 
17172 	return (err);
17173 }
17174 
17175 /* args used */
17176 static int
17177 st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
17178 {
17179 	int rval;
17180 	buf_t *bp;
17181 
17182 	ST_FUNC(ST_DEVINFO, st_uscsi_rcmd);
17183 	ASSERT(flag == FKIOCTL);
17184 
17185 	/*
17186 	 * Get buffer resources...
17187 	 */
17188 	while (un->un_recov_buf_busy)
17189 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17190 	un->un_recov_buf_busy = 1;
17191 
17192 	bp = un->un_recov_buf;
17193 	bzero(bp, sizeof (buf_t));
17194 
17195 	bp->b_forw = (struct buf *)(uintptr_t)ucmd->uscsi_cdb[0];
17196 	bp->b_back = (struct buf *)ucmd;
17197 
17198 	mutex_exit(ST_MUTEX);
17199 	rval = scsi_uscsi_handle_cmd(un->un_dev, UIO_SYSSPACE, ucmd,
17200 	    st_strategy, bp, NULL);
17201 	mutex_enter(ST_MUTEX);
17202 
17203 	ucmd->uscsi_resid = bp->b_resid;
17204 
17205 	/*
17206 	 * Free resources
17207 	 */
17208 	un->un_recov_buf_busy = 0;
17209 	cv_signal(&un->un_recov_buf_cv);
17210 
17211 	return (rval);
17212 }
17213 
17214 /*
17215  * Add data to scsi_pkt to help know what to do if the command fails.
17216  */
17217 static void
17218 st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
17219     struct scsi_pkt *pkt)
17220 {
17221 	uint64_t count;
17222 	recov_info *rinfo = (recov_info *)pkt->pkt_private;
17223 
17224 	ST_FUNC(ST_DEVINFO, st_add_recovery_info_to_pkt);
17225 
17226 	ASSERT(rinfo->privatelen == sizeof (pkt_info) ||
17227 	    rinfo->privatelen == sizeof (recov_info));
17228 
17229 	SET_BP_PKT(bp, pkt);
17230 	rinfo->cmd_bp = bp;
17231 
17232 	if (rinfo->privatelen != sizeof (recov_info)) {
17233 		return;
17234 	}
17235 
17236 	rinfo->cmd_bp = bp;
17237 
17238 	rinfo->cmd_attrib = NULL;
17239 
17240 	/*
17241 	 * lookup the command attributes and add them to the recovery info.
17242 	 */
17243 	rinfo->cmd_attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
17244 
17245 	ASSERT(rinfo->cmd_attrib);
17246 
17247 	/*
17248 	 * For commands that there is no way to figure the expected position
17249 	 * once completed, we save the position the command was started from
17250 	 * so that if they fail we can position back and try again.
17251 	 * This has already been done in st_cmd() or st_iscsi_cmd().
17252 	 */
17253 	if (rinfo->cmd_attrib->recov_pos_type == POS_STARTING) {
17254 		/* save current position as the starting position. */
17255 		COPY_POS(&rinfo->pos, &un->un_pos);
17256 		un->un_running.pmode = invalid;
17257 		return;
17258 	}
17259 
17260 	/*
17261 	 * Don't want to update the running position for recovery.
17262 	 */
17263 	if (bp == un->un_recov_buf) {
17264 		rinfo->pos.pmode = un->un_running.pmode;
17265 		return;
17266 	}
17267 	/*
17268 	 * If running position is invalid copy the current position.
17269 	 * Running being set invalid means we are not in a read, write
17270 	 * or write filemark sequence.
17271 	 * We'll copy the current position and start from there.
17272 	 */
17273 	if (un->un_running.pmode == invalid) {
17274 		COPY_POS(&un->un_running, &un->un_pos);
17275 		COPY_POS(&rinfo->pos, &un->un_running);
17276 	} else {
17277 		COPY_POS(&rinfo->pos, &un->un_running);
17278 		if (rinfo->pos.pmode == legacy) {
17279 			/*
17280 			 * Always should be more logical blocks then
17281 			 * data blocks and files marks.
17282 			 */
17283 			ASSERT((rinfo->pos.blkno >= 0) ?
17284 			    rinfo->pos.lgclblkno >=
17285 			    (rinfo->pos.blkno + rinfo->pos.fileno) : 1);
17286 		}
17287 	}
17288 
17289 	/*
17290 	 * If the command is not expected to change the drive position
17291 	 * then the running position should be the expected position.
17292 	 */
17293 	if (rinfo->cmd_attrib->chg_tape_pos == 0) {
17294 		ASSERT(rinfo->cmd_attrib->chg_tape_direction == DIR_NONE);
17295 		return;
17296 	}
17297 
17298 	if (rinfo->cmd_attrib->explicit_cmd_set) {
17299 		ASSERT(rinfo->pos.pmode != invalid);
17300 		ASSERT(rinfo->cmd_attrib->get_cnt);
17301 		count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17302 		/*
17303 		 * This is a user generated CDB.
17304 		 */
17305 		if (bp == un->un_sbufp) {
17306 			uint64_t lbn;
17307 
17308 			lbn = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17309 
17310 			/*
17311 			 * See if this CDB will generate a locate or change
17312 			 * partition.
17313 			 */
17314 			if ((lbn != un->un_running.lgclblkno) ||
17315 			    (pkt->pkt_cdbp[3] != un->un_running.partition)) {
17316 				rinfo->pos.partition = pkt->pkt_cdbp[3];
17317 				rinfo->pos.pmode = logical;
17318 				rinfo->pos.lgclblkno = lbn;
17319 				un->un_running.partition = pkt->pkt_cdbp[3];
17320 				un->un_running.pmode = logical;
17321 				un->un_running.lgclblkno = lbn;
17322 			}
17323 		} else {
17324 			uint64_t lbn = un->un_running.lgclblkno;
17325 
17326 			pkt->pkt_cdbp[3]  = (uchar_t)un->un_running.partition;
17327 
17328 			pkt->pkt_cdbp[4]  = (uchar_t)(lbn >> 56);
17329 			pkt->pkt_cdbp[5]  = (uchar_t)(lbn >> 48);
17330 			pkt->pkt_cdbp[6]  = (uchar_t)(lbn >> 40);
17331 			pkt->pkt_cdbp[7]  = (uchar_t)(lbn >> 32);
17332 			pkt->pkt_cdbp[8]  = (uchar_t)(lbn >> 24);
17333 			pkt->pkt_cdbp[9]  = (uchar_t)(lbn >> 16);
17334 			pkt->pkt_cdbp[10] = (uchar_t)(lbn >> 8);
17335 			pkt->pkt_cdbp[11] = (uchar_t)(lbn);
17336 		}
17337 		rinfo->pos.lgclblkno += count;
17338 		rinfo->pos.blkno += count;
17339 		un->un_running.lgclblkno += count;
17340 		return;
17341 	}
17342 
17343 	if (rinfo->cmd_attrib->chg_tape_pos) {
17344 
17345 		/* should not have got an invalid position from running. */
17346 		if (un->un_mediastate == MTIO_INSERTED) {
17347 			ASSERT(rinfo->pos.pmode != invalid);
17348 		}
17349 
17350 		/* should have either a get count or or get lba function */
17351 		ASSERT(rinfo->cmd_attrib->get_cnt != NULL ||
17352 		    rinfo->cmd_attrib->get_lba != NULL);
17353 
17354 		/* only explicit commands have both and they're handled above */
17355 		ASSERT(!(rinfo->cmd_attrib->get_cnt != NULL &&
17356 		    rinfo->cmd_attrib->get_lba != NULL));
17357 
17358 		/* if it has a get count function */
17359 		if (rinfo->cmd_attrib->get_cnt != NULL) {
17360 			count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17361 			if (count == 0) {
17362 				return;
17363 			}
17364 			/*
17365 			 * Changes position but doesn't transfer data.
17366 			 * i.e. rewind, write_file_mark and load.
17367 			 */
17368 			if (rinfo->cmd_attrib->transfers_data == TRAN_NONE) {
17369 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17370 				case DIR_NONE: /* Erase */
17371 					ASSERT(rinfo->cmd_attrib->cmd ==
17372 					    SCMD_ERASE);
17373 					break;
17374 				case DIR_FORW: /* write_file_mark */
17375 					rinfo->pos.fileno += count;
17376 					rinfo->pos.lgclblkno += count;
17377 					rinfo->pos.blkno = 0;
17378 					un->un_running.fileno += count;
17379 					un->un_running.lgclblkno += count;
17380 					un->un_running.blkno = 0;
17381 					break;
17382 				case DIR_REVC: /* rewind */
17383 					rinfo->pos.fileno = 0;
17384 					rinfo->pos.lgclblkno = 0;
17385 					rinfo->pos.blkno = 0;
17386 					rinfo->pos.eof = ST_NO_EOF;
17387 					rinfo->pos.pmode = legacy;
17388 					un->un_running.fileno = 0;
17389 					un->un_running.lgclblkno = 0;
17390 					un->un_running.blkno = 0;
17391 					un->un_running.eof = ST_NO_EOF;
17392 					if (un->un_running.pmode != legacy)
17393 						un->un_running.pmode = legacy;
17394 					break;
17395 				case DIR_EITH: /* Load unload */
17396 					ASSERT(rinfo->cmd_attrib->cmd ==
17397 					    SCMD_LOAD);
17398 					switch (count & (LD_LOAD | LD_RETEN |
17399 					    LD_RETEN | LD_HOLD)) {
17400 					case LD_UNLOAD:
17401 					case LD_RETEN:
17402 					case LD_HOLD:
17403 					case LD_LOAD | LD_HOLD:
17404 					case LD_EOT | LD_HOLD:
17405 					case LD_RETEN | LD_HOLD:
17406 						rinfo->pos.pmode = invalid;
17407 						un->un_running.pmode = invalid;
17408 						break;
17409 					case LD_EOT:
17410 					case LD_LOAD | LD_EOT:
17411 						rinfo->pos.eof = ST_EOT;
17412 						rinfo->pos.pmode = invalid;
17413 						un->un_running.eof = ST_EOT;
17414 						un->un_running.pmode = invalid;
17415 						break;
17416 					case LD_LOAD:
17417 					case LD_RETEN | LD_LOAD:
17418 						rinfo->pos.fileno = 0;
17419 						rinfo->pos.lgclblkno = 0;
17420 						rinfo->pos.blkno = 0;
17421 						rinfo->pos.eof = ST_NO_EOF;
17422 						rinfo->pos.pmode = legacy;
17423 						un->un_running.fileno = 0;
17424 						un->un_running.lgclblkno = 0;
17425 						un->un_running.blkno = 0;
17426 						un->un_running.eof = ST_NO_EOF;
17427 						break;
17428 					default:
17429 						ASSERT(0);
17430 					}
17431 					break;
17432 				default:
17433 					ASSERT(0);
17434 					break;
17435 				}
17436 			} else {
17437 				/*
17438 				 * Changes position and does transfer data.
17439 				 * i.e. read or write.
17440 				 */
17441 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17442 				case DIR_FORW:
17443 					rinfo->pos.lgclblkno += count;
17444 					rinfo->pos.blkno += count;
17445 					un->un_running.lgclblkno += count;
17446 					un->un_running.blkno += count;
17447 					break;
17448 				case DIR_REVC:
17449 					rinfo->pos.lgclblkno -= count;
17450 					rinfo->pos.blkno -= count;
17451 					un->un_running.lgclblkno -= count;
17452 					un->un_running.blkno -= count;
17453 					break;
17454 				default:
17455 					ASSERT(0);
17456 					break;
17457 				}
17458 			}
17459 		} else if (rinfo->cmd_attrib->get_lba != NULL) {
17460 			/* Have a get LBA fuction. i.e. Locate */
17461 			ASSERT(rinfo->cmd_attrib->chg_tape_direction ==
17462 			    DIR_EITH);
17463 			count = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17464 			un->un_running.lgclblkno = count;
17465 			un->un_running.blkno = 0;
17466 			un->un_running.fileno = 0;
17467 			un->un_running.pmode = logical;
17468 			rinfo->pos.lgclblkno = count;
17469 			rinfo->pos.pmode = invalid;
17470 		} else {
17471 			ASSERT(0);
17472 		}
17473 		return;
17474 	}
17475 
17476 	ST_CDB(ST_DEVINFO, "Unhanded CDB for position prediction",
17477 	    (char *)pkt->pkt_cdbp);
17478 
17479 }
17480 
17481 static int
17482 st_make_sure_mode_data_is_correct(struct scsi_tape *un, ubufunc_t ubf)
17483 {
17484 	int rval;
17485 
17486 	ST_FUNC(ST_DEVINFO, st_make_sure_mode_data_is_correct);
17487 
17488 	/*
17489 	 * check to see if mode data has changed.
17490 	 */
17491 	rval = st_check_mode_for_change(un, ubf);
17492 	if (rval) {
17493 		rval = st_gen_mode_select(un, ubf, un->un_mspl,
17494 		    sizeof (struct seq_mode));
17495 	}
17496 	if (un->un_tlr_flag != TLR_NOT_SUPPORTED) {
17497 		rval |= st_set_target_TLR_mode(un, ubf);
17498 	}
17499 	return (rval);
17500 }
17501 
17502 static int
17503 st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf)
17504 {
17505 	struct seq_mode *current;
17506 	int rval;
17507 	int i;
17508 	caddr_t this;
17509 	caddr_t that;
17510 
17511 	ST_FUNC(ST_DEVINFO, st_check_mode_for_change);
17512 
17513 	/* recovery called with mode tamper before mode selection */
17514 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
17515 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17516 		    "Mode Select not done yet");
17517 		return (0);
17518 	}
17519 
17520 	current = kmem_zalloc(sizeof (struct seq_mode), KM_SLEEP);
17521 
17522 	rval = st_gen_mode_sense(un, ubf, un->un_comp_page, current,
17523 	    sizeof (struct seq_mode));
17524 	if (rval != 0) {
17525 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17526 		    "Mode Sense for mode verification failed");
17527 		kmem_free(current, sizeof (struct seq_mode));
17528 		return (rval);
17529 	}
17530 
17531 	this = (caddr_t)current;
17532 	that = (caddr_t)un->un_mspl;
17533 
17534 	rval = bcmp(this, that, sizeof (struct seq_mode));
17535 	if (rval == 0) {
17536 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17537 		    "Found no changes in mode data");
17538 	}
17539 #ifdef STDEBUG
17540 	else {
17541 		for (i = 1; i < sizeof (struct seq_mode); i++) {
17542 			if (this[i] != that[i]) {
17543 				ST_RECOV(ST_DEVINFO, st_label, CE_CONT,
17544 				    "sense data changed at byte %d was "
17545 				    "0x%x now 0x%x", i,
17546 				    (uchar_t)that[i], (uchar_t)this[i]);
17547 			}
17548 		}
17549 	}
17550 #endif
17551 	kmem_free(current, sizeof (struct seq_mode));
17552 
17553 	return (rval);
17554 }
17555 
17556 static int
17557 st_test_path_to_device(struct scsi_tape *un)
17558 {
17559 	int rval = 0;
17560 	int limit = st_retry_count;
17561 
17562 	ST_FUNC(ST_DEVINFO, st_test_path_to_device);
17563 
17564 	/*
17565 	 * XXX Newer drives may not RESEVATION CONFLICT a TUR.
17566 	 */
17567 	do {
17568 		if (rval != 0) {
17569 			mutex_exit(ST_MUTEX);
17570 			delay(drv_usectohz(1000000));
17571 			mutex_enter(ST_MUTEX);
17572 		}
17573 		rval = st_rcmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
17574 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17575 		    "ping TUR returned 0x%x", rval);
17576 		limit--;
17577 	} while (((rval == EACCES) || (rval == EBUSY)) && limit);
17578 
17579 	if (un->un_status == KEY_NOT_READY || un->un_mediastate == MTIO_EJECTED)
17580 		rval = 0;
17581 
17582 	return (rval);
17583 }
17584 
17585 /*
17586  * Does read position using recov_buf and doesn't update un_pos.
17587  * Does what ever kind of read position you want.
17588  */
17589 static int
17590 st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
17591     read_pos_data_t *raw)
17592 {
17593 	int rval;
17594 	struct uscsi_cmd cmd;
17595 	struct scsi_arq_status status;
17596 	char cdb[CDB_GROUP1];
17597 
17598 	ST_FUNC(ST_DEVINFO, st_recovery_read_pos);
17599 	bzero(&cmd, sizeof (cmd));
17600 
17601 	cdb[0] = SCMD_READ_POSITION;
17602 	cdb[1] = type;
17603 	cdb[2] = 0;
17604 	cdb[3] = 0;
17605 	cdb[4] = 0;
17606 	cdb[5] = 0;
17607 	cdb[6] = 0;
17608 	cdb[7] = 0;
17609 	cdb[8] = (type == EXT_POS) ? 28 : 0;
17610 	cdb[9] = 0;
17611 
17612 	cmd.uscsi_flags = USCSI_READ | USCSI_RQENABLE;
17613 	cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
17614 	cmd.uscsi_cdb = cdb;
17615 	cmd.uscsi_cdblen = sizeof (cdb);
17616 	cmd.uscsi_rqlen = sizeof (status);
17617 	cmd.uscsi_rqbuf = (caddr_t)&status;
17618 	cmd.uscsi_bufaddr = (caddr_t)raw;
17619 	switch (type) {
17620 	case SHORT_POS:
17621 		cmd.uscsi_buflen = sizeof (tape_position_t);
17622 		break;
17623 	case LONG_POS:
17624 		cmd.uscsi_buflen = sizeof (tape_position_long_t);
17625 		break;
17626 	case EXT_POS:
17627 		cmd.uscsi_buflen = sizeof (tape_position_ext_t);
17628 		break;
17629 	default:
17630 		ASSERT(0);
17631 	}
17632 
17633 	rval = st_uscsi_rcmd(un, &cmd, FKIOCTL);
17634 	if (cmd.uscsi_status) {
17635 		rval = EIO;
17636 	}
17637 	return (rval);
17638 }
17639 
17640 static int
17641 st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
17642     read_pos_data_t *raw)
17643 {
17644 	int rval;
17645 	read_p_types type = un->un_read_pos_type;
17646 
17647 	ST_FUNC(ST_DEVINFO, st_recovery_get_position);
17648 
17649 	do {
17650 		rval = st_recovery_read_pos(un, type, raw);
17651 		if (rval != 0) {
17652 			switch (type) {
17653 			case SHORT_POS:
17654 				type = NO_POS;
17655 				break;
17656 
17657 			case LONG_POS:
17658 				type = EXT_POS;
17659 				break;
17660 
17661 			case EXT_POS:
17662 				type = SHORT_POS;
17663 				break;
17664 
17665 			default:
17666 				type = LONG_POS;
17667 				break;
17668 
17669 			}
17670 		} else {
17671 			if (type != un->un_read_pos_type) {
17672 				un->un_read_pos_type = type;
17673 			}
17674 			break;
17675 		}
17676 	} while (type != NO_POS);
17677 
17678 	if (rval == 0) {
17679 		rval = st_interpret_read_pos(un, read, type,
17680 		    sizeof (read_pos_data_t), (caddr_t)raw, 1);
17681 	}
17682 	return (rval);
17683 }
17684 
17685 /*
17686  * based on the command do we retry, continue or give up?
17687  * possable return values?
17688  *	zero do nothing looks fine.
17689  *	EAGAIN retry.
17690  *	EIO failed makes no sense.
17691  */
17692 static int
17693 st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
17694     cmd_attribute const * cmd_att, tapepos_t *read)
17695 {
17696 	int rval;
17697 	read_pos_data_t *readp_datap;
17698 
17699 	ST_FUNC(ST_DEVINFO, st_compare_expected_position);
17700 
17701 	ASSERT(un != NULL);
17702 	ASSERT(ei != NULL);
17703 	ASSERT(read != NULL);
17704 	ASSERT(cmd_att->chg_tape_pos);
17705 
17706 	COPY_POS(read, &ei->ei_expected_pos);
17707 
17708 	readp_datap = kmem_zalloc(sizeof (read_pos_data_t), KM_SLEEP);
17709 
17710 	rval = st_recovery_get_position(un, read, readp_datap);
17711 
17712 	kmem_free(readp_datap, sizeof (read_pos_data_t));
17713 
17714 	if (rval != 0) {
17715 		return (EIO);
17716 	}
17717 
17718 	ST_POS(ST_DEVINFO, "st_compare_expected_position", read);
17719 
17720 	if ((read->pmode == invalid) ||
17721 	    (ei->ei_expected_pos.pmode == invalid)) {
17722 		return (EIO);
17723 	}
17724 
17725 	/*
17726 	 * Command that changes tape position and have an expected position
17727 	 * if it were to chave completed sucessfully.
17728 	 */
17729 	if (cmd_att->recov_pos_type == POS_EXPECTED) {
17730 		uint32_t count;
17731 		int64_t difference;
17732 		uchar_t reposition = 0;
17733 
17734 		ASSERT(cmd_att->get_cnt);
17735 		count = cmd_att->get_cnt(ei->ei_failed_pkt.pkt_cdbp);
17736 
17737 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17738 		    "Got count from CDB and it was %d\n", count);
17739 
17740 		/*
17741 		 * At expected?
17742 		 */
17743 		if (read->lgclblkno == ei->ei_expected_pos.lgclblkno) {
17744 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17745 			    "Found drive to be at expected position\n");
17746 
17747 			/*
17748 			 * If the command should move tape and it got a busy
17749 			 * it shouldn't be in the expected position.
17750 			 */
17751 			if (ei->ei_failing_status.sts_status.sts_busy != 0) {
17752 				reposition = 1;
17753 
17754 			/*
17755 			 * If the command doesn't transfer data should be good.
17756 			 */
17757 			} else if (cmd_att->transfers_data == TRAN_NONE) {
17758 				return (0); /* Good */
17759 
17760 			/*
17761 			 * Command transfers data, should have done so.
17762 			 */
17763 			} else if (ei->ei_failed_pkt.pkt_state &
17764 			    STATE_XFERRED_DATA) {
17765 				return (0); /* Good */
17766 			} else {
17767 				reposition = 1;
17768 			}
17769 		}
17770 
17771 		if (cmd_att->chg_tape_direction == DIR_FORW) {
17772 			difference =
17773 			    ei->ei_expected_pos.lgclblkno - read->lgclblkno;
17774 
17775 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17776 			    "difference between expected and actual is %"
17777 			    PRId64"\n", difference);
17778 			if (count == difference && reposition == 0) {
17779 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17780 				    "Found failed FORW command, retrying\n");
17781 				return (EAGAIN);
17782 			}
17783 
17784 			/*
17785 			 * If rewound or somewhere between the starting position
17786 			 * and the expected position (partial read or write).
17787 			 * Locate to the starting position and try the whole
17788 			 * thing over again.
17789 			 */
17790 			if ((read->lgclblkno == 0) ||
17791 			    ((difference > 0) && (difference < count))) {
17792 				rval = st_logical_block_locate(un,
17793 				    st_uscsi_rcmd, read,
17794 				    ei->ei_expected_pos.lgclblkno - count,
17795 				    ei->ei_expected_pos.partition);
17796 				if (rval == 0) {
17797 					ST_RECOV(ST_DEVINFO, st_label,
17798 					    CE_NOTE, "reestablished FORW"
17799 					    " command retrying\n");
17800 					return (EAGAIN);
17801 				}
17802 			/*
17803 			 * This handles flushed read ahead on the drive or
17804 			 * an aborted read that presents as a busy and advanced
17805 			 * the tape position.
17806 			 */
17807 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17808 			    ((difference < 0) || (reposition == 1))) {
17809 				rval = st_logical_block_locate(un,
17810 				    st_uscsi_rcmd, read,
17811 				    ei->ei_expected_pos.lgclblkno - count,
17812 				    ei->ei_expected_pos.partition);
17813 				if (rval == 0) {
17814 					ST_RECOV(ST_DEVINFO, st_label,
17815 					    CE_NOTE, "reestablished FORW"
17816 					    " read command retrying\n");
17817 					return (EAGAIN);
17818 				}
17819 			/*
17820 			 * XXX swag seeing difference of 2 on write filemark.
17821 			 * If the space to the starting position works on a
17822 			 * write that means the previous write made it to tape.
17823 			 * If not we lost data and have to give up.
17824 			 *
17825 			 * The plot thickens. Now I am attempting to cover a
17826 			 * count of 1 and a differance of 2 on a write.
17827 			 */
17828 			} else if ((difference > count) || (reposition == 1)) {
17829 				rval = st_logical_block_locate(un,
17830 				    st_uscsi_rcmd, read,
17831 				    ei->ei_expected_pos.lgclblkno - count,
17832 				    ei->ei_expected_pos.partition);
17833 				if (rval == 0) {
17834 					ST_RECOV(ST_DEVINFO, st_label,
17835 					    CE_NOTE, "reestablished FORW"
17836 					    " write command retrying\n");
17837 					return (EAGAIN);
17838 				}
17839 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17840 				    "Seek to block %"PRId64" returned %d\n",
17841 				    ei->ei_expected_pos.lgclblkno - count,
17842 				    rval);
17843 			} else {
17844 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17845 				    "Not expected transfers_data = %d "
17846 				    "difference = %"PRId64,
17847 				    cmd_att->transfers_data, difference);
17848 			}
17849 
17850 			return (EIO);
17851 
17852 		} else if (cmd_att->chg_tape_direction == DIR_REVC) {
17853 			/* Don't think we can write backwards */
17854 			ASSERT(cmd_att->transfers_data != TRAN_WRTE);
17855 			difference =
17856 			    read->lgclblkno - ei->ei_expected_pos.lgclblkno;
17857 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17858 			    "difference between expected and actual is %"
17859 			    PRId64"\n", difference);
17860 			if (count == difference && reposition == 0) {
17861 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17862 				    "Found failed REVC command, retrying\n");
17863 				return (EAGAIN);
17864 			}
17865 			if ((read->lgclblkno == 0) ||
17866 			    ((difference > 0) && (difference < count))) {
17867 				rval = st_logical_block_locate(un,
17868 				    st_uscsi_rcmd, read,
17869 				    ei->ei_expected_pos.lgclblkno + count,
17870 				    ei->ei_expected_pos.partition);
17871 				if (rval == 0) {
17872 					ST_RECOV(ST_DEVINFO, st_label,
17873 					    CE_NOTE, "reestablished REVC"
17874 					    " command retrying\n");
17875 					return (EAGAIN);
17876 				}
17877 			/* This handles read ahead in reverse direction */
17878 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17879 			    (difference < 0) || (reposition == 1)) {
17880 				rval = st_logical_block_locate(un,
17881 				    st_uscsi_rcmd, read,
17882 				    ei->ei_expected_pos.lgclblkno - count,
17883 				    ei->ei_expected_pos.partition);
17884 				if (rval == 0) {
17885 					ST_RECOV(ST_DEVINFO, st_label,
17886 					    CE_NOTE, "reestablished REVC"
17887 					    " read command retrying\n");
17888 					return (EAGAIN);
17889 				}
17890 			} else {
17891 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17892 				    "Not expected transfers_data = %d "
17893 				    "difference = %"PRId64,
17894 				    cmd_att->transfers_data, difference);
17895 			}
17896 			return (EIO);
17897 
17898 		} else {
17899 			/*
17900 			 * Commands that change tape position either
17901 			 * direction or don't change position should not
17902 			 * get here.
17903 			 */
17904 			ASSERT(0);
17905 		}
17906 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17907 		    "Didn't find a recoverable position, Failing\n");
17908 
17909 	/*
17910 	 * Command that changes tape position and can only be recovered
17911 	 * by going back to the point of origin and retrying.
17912 	 *
17913 	 * Example SCMD_SPACE.
17914 	 */
17915 	} else if (cmd_att->recov_pos_type == POS_STARTING) {
17916 		/*
17917 		 * This type of command stores the starting position.
17918 		 * If the read position is the starting position,
17919 		 * reissue the command.
17920 		 */
17921 		if (ei->ei_expected_pos.lgclblkno == read->lgclblkno) {
17922 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17923 			    "Found Space command at starting position, "
17924 			    "Reissuing\n");
17925 			return (EAGAIN);
17926 		}
17927 		/*
17928 		 * Not in the position that the command was originally issued,
17929 		 * Attempt to locate to that position.
17930 		 */
17931 		rval = st_logical_block_locate(un, st_uscsi_rcmd, read,
17932 		    ei->ei_expected_pos.lgclblkno,
17933 		    ei->ei_expected_pos.partition);
17934 		if (rval) {
17935 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17936 			    "Found Space at an unexpected position and locate "
17937 			    "back to starting position failed\n");
17938 			return (EIO);
17939 		}
17940 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17941 		    "Found Space at an unexpected position and locate "
17942 		    "back to starting position worked, Reissuing\n");
17943 		return (EAGAIN);
17944 	}
17945 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17946 	    "Unhandled attribute/expected position", &ei->ei_expected_pos);
17947 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17948 	    "Read position above did not make sense", read);
17949 	ASSERT(0);
17950 	return (EIO);
17951 }
17952 
17953 static errstate
17954 st_recover_reissue_pkt(struct scsi_tape *un, struct scsi_pkt *oldpkt)
17955 {
17956 	buf_t *bp;
17957 	buf_t *pkt_bp;
17958 	struct scsi_pkt *newpkt;
17959 	cmd_attribute const *attrib;
17960 	recov_info *rcv = oldpkt->pkt_private;
17961 	uint_t cdblen;
17962 	int queued = 0;
17963 	int rval;
17964 	int flags = 0;
17965 	int stat_size =
17966 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
17967 
17968 	ST_FUNC(ST_DEVINFO, st_recover_reissue_pkt);
17969 
17970 	bp = rcv->cmd_bp;
17971 
17972 	if (rcv->privatelen == sizeof (recov_info)) {
17973 		attrib = rcv->cmd_attrib;
17974 	} else {
17975 		attrib = st_lookup_cmd_attribute(oldpkt->pkt_cdbp[0]);
17976 	}
17977 
17978 	/*
17979 	 * Some non-uscsi commands use the b_bcount for values that
17980 	 * have nothing to do with how much data is transfered.
17981 	 * In those cases we need to hide the buf_t from scsi_init_pkt().
17982 	 */
17983 	if ((BP_UCMD(bp)) && (bp->b_bcount)) {
17984 		pkt_bp = bp;
17985 	} else if (attrib->transfers_data == TRAN_NONE) {
17986 		pkt_bp = NULL;
17987 	} else {
17988 		pkt_bp = bp;
17989 	}
17990 
17991 	/*
17992 	 * if this is a queued command make sure it the only one in the
17993 	 * run queue.
17994 	 */
17995 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
17996 		ASSERT(un->un_runqf == un->un_runql);
17997 		ASSERT(un->un_runqf == bp);
17998 		queued = 1;
17999 	}
18000 
18001 	cdblen = scsi_cdb_size[CDB_GROUPID(oldpkt->pkt_cdbp[0])];
18002 
18003 	if (pkt_bp == un->un_rqs_bp) {
18004 		flags |= PKT_CONSISTENT;
18005 		stat_size = 1;
18006 	}
18007 
18008 	newpkt = scsi_init_pkt(ROUTE, NULL, pkt_bp, cdblen,
18009 	    stat_size, rcv->privatelen, flags, NULL_FUNC, NULL);
18010 	if (newpkt == NULL) {
18011 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
18012 		    "Reissue pkt scsi_init_pkt() failure\n");
18013 		return (COMMAND_DONE_ERROR);
18014 	}
18015 
18016 	ASSERT(newpkt->pkt_resid == 0);
18017 	bp->b_flags &= ~(B_DONE);
18018 	bp->b_resid = 0;
18019 	st_bioerror(bp, 0);
18020 
18021 	bcopy(oldpkt->pkt_private, newpkt->pkt_private, rcv->privatelen);
18022 
18023 	newpkt->pkt_comp = oldpkt->pkt_comp;
18024 	newpkt->pkt_time = oldpkt->pkt_time;
18025 
18026 	bzero(newpkt->pkt_scbp, stat_size);
18027 	bcopy(oldpkt->pkt_cdbp, newpkt->pkt_cdbp, cdblen);
18028 
18029 	newpkt->pkt_state = 0;
18030 	newpkt->pkt_statistics = 0;
18031 
18032 	/*
18033 	 * oldpkt passed in was a copy of the original.
18034 	 * to distroy we need the address of the original.
18035 	 */
18036 	oldpkt = BP_PKT(bp);
18037 
18038 	if (oldpkt == un->un_rqs) {
18039 		ASSERT(bp == un->un_rqs_bp);
18040 		un->un_rqs = newpkt;
18041 	}
18042 
18043 	SET_BP_PKT(bp, newpkt);
18044 
18045 	scsi_destroy_pkt(oldpkt);
18046 
18047 	rval = st_transport(un, newpkt);
18048 	if (rval == TRAN_ACCEPT) {
18049 		return (JUST_RETURN);
18050 	}
18051 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
18052 	    "Reissue pkt st_transport(0x%x) failure\n", rval);
18053 	if (rval != TRAN_BUSY) {
18054 		return (COMMAND_DONE_ERROR);
18055 	}
18056 	mutex_exit(ST_MUTEX);
18057 	rval = st_handle_start_busy(un, bp, ST_TRAN_BUSY_TIMEOUT, queued);
18058 	mutex_enter(ST_MUTEX);
18059 	if (rval) {
18060 		return (COMMAND_DONE_ERROR);
18061 	}
18062 
18063 	return (JUST_RETURN);
18064 }
18065 
18066 static int
18067 st_transport(struct scsi_tape *un, struct scsi_pkt *pkt)
18068 {
18069 	int status;
18070 
18071 	ST_FUNC(ST_DEVINFO, st_transport);
18072 
18073 	ST_CDB(ST_DEVINFO, "transport CDB", (caddr_t)pkt->pkt_cdbp);
18074 
18075 	mutex_exit(ST_MUTEX);
18076 
18077 	status = scsi_transport(pkt);
18078 
18079 	mutex_enter(ST_MUTEX);
18080 
18081 	return (status);
18082 }
18083 
18084 /*
18085  * Removed the buf_t bp from the queue referenced to by head and tail.
18086  * Returns the buf_t pointer if it is found in the queue.
18087  * Returns NULL if it is not found.
18088  */
18089 static buf_t *
18090 st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp)
18091 {
18092 	buf_t *runqbp;
18093 	buf_t *prevbp = NULL;
18094 
18095 	for (runqbp = *head; runqbp != 0; runqbp = runqbp->av_forw) {
18096 		if (runqbp == bp) {
18097 			/* found it, is it at the head? */
18098 			if (runqbp == *head) {
18099 				*head = bp->av_forw;
18100 			} else {
18101 				prevbp->av_forw = bp->av_forw;
18102 			}
18103 			if (*tail == bp) {
18104 				*tail = prevbp;
18105 			}
18106 			bp->av_forw = NULL;
18107 			return (bp); /* found and removed */
18108 		}
18109 		prevbp = runqbp;
18110 	}
18111 	return (NULL);
18112 }
18113 
18114 /*
18115  * Adds a buf_t to the queue pointed to by head and tail.
18116  * Adds it either to the head end or the tail end based on which
18117  * the passed variable end (head or tail) points at.
18118  */
18119 static void
18120 st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp)
18121 {
18122 
18123 	bp->av_forw = NULL;
18124 	if (*head) {
18125 		/* Queue is not empty */
18126 		if (end == *head) {
18127 			/* Add at front of queue */
18128 			bp->av_forw = *head;
18129 			*head = bp;
18130 		} else if (end == *tail) {
18131 			/* Add at end of queue */
18132 			(*tail)->av_forw = bp;
18133 			*tail = bp;
18134 		} else {
18135 			ASSERT(0);
18136 		}
18137 	} else {
18138 		/* Queue is empty */
18139 		*head = bp;
18140 		*tail = bp;
18141 	}
18142 }
18143 
18144 
18145 static uint64_t
18146 st_get_cdb_g0_rw_count(uchar_t *cdb)
18147 {
18148 	uint64_t count;
18149 
18150 	if ((cdb[1]) & 1) {
18151 		/* fixed block mode, the count is the number of blocks */
18152 		count =
18153 		    cdb[2] << 16 |
18154 		    cdb[3] << 8 |
18155 		    cdb[4];
18156 	} else {
18157 		/* variable block mode, the count is the block size */
18158 		count = 1;
18159 	}
18160 	return (count);
18161 }
18162 
18163 static uint64_t
18164 st_get_cdb_g0_sign_count(uchar_t *cdb)
18165 {
18166 	uint64_t count;
18167 
18168 	count =
18169 	    cdb[2] << 16 |
18170 	    cdb[3] << 8 |
18171 	    cdb[4];
18172 	/*
18173 	 * If the sign bit of the 3 byte value is set, extended it.
18174 	 */
18175 	if (count & 0x800000) {
18176 		count |= 0xffffffffff000000;
18177 	}
18178 	return (count);
18179 }
18180 
18181 static uint64_t
18182 st_get_cdb_g0_count(uchar_t *cdb)
18183 {
18184 	uint64_t count;
18185 
18186 	count =
18187 	    cdb[2] << 16 |
18188 	    cdb[3] << 8 |
18189 	    cdb[4];
18190 	return (count);
18191 }
18192 
18193 static uint64_t
18194 st_get_cdb_g5_rw_cnt(uchar_t *cdb)
18195 {
18196 	uint64_t count;
18197 
18198 	if ((cdb[1]) & 1) {
18199 		/* fixed block mode */
18200 		count =
18201 		    cdb[12] << 16 |
18202 		    cdb[13] << 8 |
18203 		    cdb[14];
18204 	} else {
18205 		/* variable block mode */
18206 		count = 1;
18207 	}
18208 	return (count);
18209 }
18210 
18211 static uint64_t
18212 st_get_no_count(uchar_t *cdb)
18213 {
18214 	ASSERT(cdb[0] == SCMD_REWIND);
18215 	return ((uint64_t)cdb[0]);
18216 }
18217 
18218 static uint64_t
18219 st_get_load_options(uchar_t *cdb)
18220 {
18221 	return ((uint64_t)(cdb[4] | (LD_HOLD << 1)));
18222 }
18223 
18224 static uint64_t
18225 st_get_erase_options(uchar_t *cdb)
18226 {
18227 	return (cdb[1] | (cdb[0] << 8));
18228 }
18229 
18230 static uint64_t
18231 st_get_cdb_g1_lba(uchar_t *cdb)
18232 {
18233 	uint64_t lba;
18234 
18235 	lba =
18236 	    cdb[3] << 24 |
18237 	    cdb[4] << 16 |
18238 	    cdb[5] << 8 |
18239 	    cdb[6];
18240 	return (lba);
18241 }
18242 
18243 static uint64_t
18244 st_get_cdb_g5_count(uchar_t *cdb)
18245 {
18246 	uint64_t count =
18247 	    cdb[12] << 16 |
18248 	    cdb[13] << 8 |
18249 	    cdb[14];
18250 
18251 	return (count);
18252 }
18253 
18254 static uint64_t
18255 st_get_cdb_g4g5_cnt(uchar_t *cdb)
18256 {
18257 	uint64_t lba;
18258 
18259 	lba =
18260 	    (uint64_t)cdb[4] << 56 |
18261 	    (uint64_t)cdb[5] << 48 |
18262 	    (uint64_t)cdb[6] << 40 |
18263 	    (uint64_t)cdb[7] << 32 |
18264 	    (uint64_t)cdb[8] << 24 |
18265 	    (uint64_t)cdb[9] << 16 |
18266 	    (uint64_t)cdb[10] << 8 |
18267 	    (uint64_t)cdb[11];
18268 	return (lba);
18269 }
18270 
18271 static const cmd_attribute cmd_attributes[] = {
18272 	{ SCMD_READ,
18273 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_READ, POS_EXPECTED,
18274 	    0, 0, 0, st_get_cdb_g0_rw_count },
18275 	{ SCMD_WRITE,
18276 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18277 	    0, 0, 0, st_get_cdb_g0_rw_count },
18278 	{ SCMD_TEST_UNIT_READY,
18279 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18280 	    0, 0, 0 },
18281 	{ SCMD_REWIND,
18282 	    1, 1, 1, 0, 0, DIR_REVC, TRAN_NONE, POS_EXPECTED,
18283 	    0, 0, 0, st_get_no_count },
18284 	{ SCMD_REQUEST_SENSE,
18285 	    0, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18286 	    0, 0, 0 },
18287 	{ SCMD_READ_BLKLIM,
18288 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18289 	    0, 0, 0 },
18290 	{ SCMD_READ_G4,
18291 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_READ, POS_EXPECTED,
18292 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18293 	{ SCMD_WRITE_G4,
18294 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18295 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18296 	{ SCMD_READ_REVERSE,
18297 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18298 	    0, 0, 0, st_get_cdb_g0_rw_count },
18299 	{ SCMD_READ_REVERSE_G4,
18300 	    1, 0, 1, 1, 1, DIR_REVC, TRAN_READ, POS_EXPECTED,
18301 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18302 	{ SCMD_WRITE_FILE_MARK,
18303 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18304 	    0, 0, 0, st_get_cdb_g0_count },
18305 	{ SCMD_WRITE_FILE_MARK_G4,
18306 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18307 	    0, 0, 0, st_get_cdb_g5_count, st_get_cdb_g4g5_cnt },
18308 	{ SCMD_SPACE,
18309 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18310 	    0, 0, 0, st_get_cdb_g0_sign_count },
18311 	{ SCMD_SPACE_G4,
18312 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18313 	    0, 0, 0, st_get_cdb_g4g5_cnt },
18314 	{ SCMD_INQUIRY,
18315 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18316 	    0, 0, 0 },
18317 	{ SCMD_VERIFY_G0,
18318 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18319 	    0, 0, 0, st_get_cdb_g0_rw_count },
18320 	{ SCMD_VERIFY_G4,
18321 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18322 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18323 	{ SCMD_RECOVER_BUF,
18324 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18325 	    0, 0, 0 },
18326 	{ SCMD_MODE_SELECT,
18327 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18328 	    0, 0, 0 },
18329 	{ SCMD_RESERVE,
18330 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18331 	    0, 0, 0 },
18332 	{ SCMD_RELEASE,
18333 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18334 	    0, 0, 0 },
18335 	{ SCMD_ERASE,
18336 	    1, 0, 1, 1, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18337 	    0, 0, 0, st_get_erase_options },
18338 	{ SCMD_MODE_SENSE,
18339 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18340 	    0, 0, 0 },
18341 	{ SCMD_LOAD,
18342 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18343 	    0, 0, 0, st_get_load_options },
18344 	{ SCMD_GDIAG,
18345 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18346 	    1, 0, 0 },
18347 	{ SCMD_SDIAG,
18348 	    1, 0, 1, 1, 0, DIR_EITH, TRAN_WRTE, POS_EXPECTED,
18349 	    1, 0, 0 },
18350 	{ SCMD_DOORLOCK,
18351 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18352 	    0, 4, 3 },
18353 	{ SCMD_LOCATE,
18354 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18355 	    0, 0, 0, NULL, st_get_cdb_g1_lba },
18356 	{ SCMD_READ_POSITION,
18357 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18358 	    0, 0, 0 },
18359 	{ SCMD_WRITE_BUFFER,
18360 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18361 	    1, 0, 0 },
18362 	{ SCMD_READ_BUFFER,
18363 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18364 	    1, 0, 0 },
18365 	{ SCMD_REPORT_DENSITIES,
18366 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18367 	    0, 0, 0 },
18368 	{ SCMD_LOG_SELECT_G1,
18369 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18370 	    0, 0, 0 },
18371 	{ SCMD_LOG_SENSE_G1,
18372 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18373 	    0, 0, 0 },
18374 	{ SCMD_PRIN,
18375 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18376 	    0, 0, 0 },
18377 	{ SCMD_PROUT,
18378 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18379 	    0, 0, 0 },
18380 	{ SCMD_READ_ATTRIBUTE,
18381 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18382 	    0, 0, 0 },
18383 	{ SCMD_WRITE_ATTRIBUTE,
18384 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18385 	    0, 0, 0 },
18386 	{ SCMD_LOCATE_G4,
18387 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18388 	    0, 0, 0, NULL, st_get_cdb_g4g5_cnt },
18389 	{ SCMD_REPORT_LUNS,
18390 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18391 	    0, 0, 0 },
18392 	{ SCMD_SVC_ACTION_IN_G5,
18393 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18394 	    0, 0, 0 },
18395 	{ SCMD_MAINTENANCE_IN,
18396 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18397 	    0, 0, 0 },
18398 	{ SCMD_MAINTENANCE_OUT,
18399 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18400 	    0, 0, 0 },
18401 	{ 0xff, /* Default attribute for unsupported commands */
18402 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_STARTING,
18403 	    1, 0, 0, NULL, NULL }
18404 };
18405 
18406 static const cmd_attribute *
18407 st_lookup_cmd_attribute(unsigned char cmd)
18408 {
18409 	int i;
18410 	cmd_attribute const *attribute;
18411 
18412 	for (i = 0; i < ST_NUM_MEMBERS(cmd_attributes); i++) {
18413 		attribute = &cmd_attributes[i];
18414 		if (attribute->cmd == cmd) {
18415 			return (attribute);
18416 		}
18417 	}
18418 	ASSERT(attribute);
18419 	return (attribute);
18420 }
18421 
18422 static int
18423 st_reset(struct scsi_tape *un, int reset_type)
18424 {
18425 	int rval;
18426 
18427 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
18428 
18429 	ST_FUNC(ST_DEVINFO, st_reset);
18430 	un->un_rsvd_status |= ST_INITIATED_RESET;
18431 	mutex_exit(ST_MUTEX);
18432 	do {
18433 		rval = scsi_reset(&un->un_sd->sd_address, reset_type);
18434 		if (rval == 0) {
18435 			switch (reset_type) {
18436 			case RESET_LUN:
18437 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18438 				    "LUN reset failed trying target reset");
18439 				reset_type = RESET_TARGET;
18440 				break;
18441 			case RESET_TARGET:
18442 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18443 				    "target reset failed trying bus reset");
18444 				reset_type = RESET_BUS;
18445 				break;
18446 			case RESET_BUS:
18447 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18448 				    "bus reset failed trying all reset");
18449 				reset_type = RESET_ALL;
18450 			default:
18451 				mutex_enter(ST_MUTEX);
18452 				return (rval);
18453 			}
18454 		}
18455 	} while (rval == 0);
18456 	mutex_enter(ST_MUTEX);
18457 	return (rval);
18458 }
18459 
18460 #define	SAS_TLR_MOD_LEN sizeof (struct seq_mode)
18461 static int
18462 st_set_target_TLR_mode(struct scsi_tape *un, ubufunc_t ubf)
18463 {
18464 	int ret;
18465 	int amount = SAS_TLR_MOD_LEN;
18466 	struct seq_mode *mode_data;
18467 
18468 	ST_FUNC(ST_DEVINFO, st_set_target_TLR_mode);
18469 
18470 	mode_data = kmem_zalloc(SAS_TLR_MOD_LEN, KM_SLEEP);
18471 	ret = st_gen_mode_sense(un, ubf, 0x18, mode_data, amount);
18472 	if (ret != DDI_SUCCESS) {
18473 		if (ret != EACCES)
18474 			un->un_tlr_flag = TLR_NOT_SUPPORTED;
18475 		goto out;
18476 	}
18477 	if (mode_data->data_len != amount + 1) {
18478 		amount = mode_data->data_len + 1;
18479 	}
18480 	/* Must be SAS protocol */
18481 	if (mode_data->page.saslun.protocol_id != 6) {
18482 		un->un_tlr_flag = TLR_NOT_SUPPORTED;
18483 		ret = ENOTSUP;
18484 		goto out;
18485 	}
18486 	if (un->un_tlr_flag == TLR_SAS_ONE_DEVICE) {
18487 		if (mode_data->page.saslun.tran_layer_ret == 1)
18488 			goto out;
18489 		mode_data->page.saslun.tran_layer_ret = 1;
18490 	} else {
18491 		if (mode_data->page.saslun.tran_layer_ret == 0)
18492 			goto out;
18493 		mode_data->page.saslun.tran_layer_ret = 0;
18494 	}
18495 	ret = st_gen_mode_select(un, ubf, mode_data, amount);
18496 	if (ret != DDI_SUCCESS) {
18497 		if (ret != EACCES)
18498 			un->un_tlr_flag = TLR_NOT_SUPPORTED;
18499 	} else {
18500 		if (mode_data->page.saslun.tran_layer_ret == 0)
18501 			un->un_tlr_flag = TLR_NOT_KNOWN;
18502 		else
18503 			un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
18504 	}
18505 #ifdef STDEBUG
18506 	st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG, "TLR data sent",
18507 	    (char *)mode_data, amount);
18508 #endif
18509 out:
18510 	kmem_free(mode_data, SAS_TLR_MOD_LEN);
18511 	return (ret);
18512 }
18513 
18514 
18515 static void
18516 st_reset_notification(caddr_t arg)
18517 {
18518 	struct scsi_tape *un = (struct scsi_tape *)arg;
18519 
18520 	ST_FUNC(ST_DEVINFO, st_reset_notification);
18521 	mutex_enter(ST_MUTEX);
18522 
18523 	un->un_unit_attention_flags |= 2;
18524 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
18525 	    ST_RESERVE) {
18526 		un->un_rsvd_status |= ST_LOST_RESERVE;
18527 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18528 		    "Lost Reservation notification");
18529 	} else {
18530 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18531 		    "reset notification");
18532 	}
18533 
18534 	if ((un->un_restore_pos == 0) &&
18535 	    (un->un_state == ST_STATE_CLOSED) ||
18536 	    (un->un_state == ST_STATE_OPEN_PENDING_IO) ||
18537 	    (un->un_state == ST_STATE_CLOSING)) {
18538 		un->un_restore_pos = 1;
18539 	}
18540 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
18541 	    "reset and state was %d\n", un->un_state);
18542 	mutex_exit(ST_MUTEX);
18543 }
18544