xref: /titanic_44/usr/src/uts/common/io/scsi/targets/st.c (revision 193974072f41a843678abf5f61979c748687e66b)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * SCSI	 SCSA-compliant and not-so-DDI-compliant Tape Driver
29  */
30 
31 #if defined(lint) && !defined(DEBUG)
32 #define	DEBUG	1
33 #endif
34 
35 #include <sys/modctl.h>
36 #include <sys/scsi/scsi.h>
37 #include <sys/mtio.h>
38 #include <sys/scsi/targets/stdef.h>
39 #include <sys/file.h>
40 #include <sys/kstat.h>
41 #include <sys/ddidmareq.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/byteorder.h>
45 
46 #define	IOSP	KSTAT_IO_PTR(un->un_stats)
47 /*
48  * stats maintained only for reads/writes as commands
49  * like rewind etc skew the wait/busy times
50  */
51 #define	IS_RW(bp) 	((bp)->b_bcount > 0)
52 #define	ST_DO_KSTATS(bp, kstat_function) \
53 	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
54 		kstat_function(IOSP); \
55 	}
56 
57 #define	ST_DO_ERRSTATS(un, x)  \
58 	if (un->un_errstats) { \
59 		struct st_errstats *stp; \
60 		stp = (struct st_errstats *)un->un_errstats->ks_data; \
61 		stp->x.value.ul++; \
62 	}
63 
64 #define	FILL_SCSI1_LUN(devp, pkt) 					\
65 	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
66 		int _lun;						\
67 		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
68 		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
69 		if (_lun > 0) {						\
70 			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
71 			    _lun;					\
72 		}							\
73 	}
74 
75 /*
76  * get an available contig mem header, cp.
77  * when big_enough is true, we will return NULL, if no big enough
78  * contig mem is found.
79  * when big_enough is false, we will try to find cp containing big
80  * enough contig mem. if not found, we will ruturn the last cp available.
81  *
82  * used by st_get_contig_mem()
83  */
84 #define	ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough) {		\
85 	struct contig_mem *tmp_cp = NULL;				\
86 	for ((cp) = (un)->un_contig_mem;				\
87 	    (cp) != NULL;						\
88 	    tmp_cp = (cp), (cp) = (cp)->cm_next) { 			\
89 		if (((cp)->cm_len >= (len)) || 				\
90 		    (!(big_enough) && ((cp)->cm_next == NULL))) { 	\
91 			if (tmp_cp == NULL) { 				\
92 				(un)->un_contig_mem = (cp)->cm_next; 	\
93 			} else { 					\
94 				tmp_cp->cm_next = (cp)->cm_next; 	\
95 			} 						\
96 			(cp)->cm_next = NULL; 				\
97 			(un)->un_contig_mem_available_num--; 		\
98 			break; 						\
99 		} 							\
100 	} 								\
101 }
102 
103 #define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
104 #define	COPY_POS(dest, source) bcopy(source, dest, sizeof (tapepos_t))
105 #define	ISALNUM(byte) \
106 	(((byte) >= 'a' && (byte) <= 'z') || \
107 	((byte) >= 'A' && (byte) <= 'Z') || \
108 	((byte) >= '0' && (byte) <= '9'))
109 
110 #define	ONE_K	1024
111 
112 #define	MAX_SPACE_CNT(cnt) if (cnt >= 0) { \
113 		if (cnt > MIN(SP_CNT_MASK, INT32_MAX)) \
114 			return (EINVAL); \
115 	} else { \
116 		if (-(cnt) > MIN(SP_CNT_MASK, INT32_MAX)) \
117 			return (EINVAL); \
118 	} \
119 
120 /*
121  * Global External Data Definitions
122  */
123 extern struct scsi_key_strings scsi_cmds[];
124 extern uchar_t	scsi_cdb_size[];
125 
126 /*
127  * Local Static Data
128  */
129 static void *st_state;
130 static char *const st_label = "st";
131 static volatile int st_recov_sz = sizeof (recov_info);
132 static const char mp_misconf[] = {
133 	"St Tape is misconfigured, MPxIO enabled and "
134 	"tape-command-recovery-disable set in st.conf\n"
135 };
136 
137 #ifdef	__x86
138 /*
139  * We need to use below DMA attr to alloc physically contiguous
140  * memory to do I/O in big block size
141  */
142 static ddi_dma_attr_t st_contig_mem_dma_attr = {
143 	DMA_ATTR_V0,    /* version number */
144 	0x0,		/* lowest usable address */
145 	0xFFFFFFFFull,  /* high DMA address range */
146 	0xFFFFFFFFull,  /* DMA counter register */
147 	1,		/* DMA address alignment */
148 	1,		/* DMA burstsizes */
149 	1,		/* min effective DMA size */
150 	0xFFFFFFFFull,  /* max DMA xfer size */
151 	0xFFFFFFFFull,  /* segment boundary */
152 	1,		/* s/g list length */
153 	1,		/* granularity of device */
154 	0		/* DMA transfer flags */
155 };
156 
157 static ddi_device_acc_attr_t st_acc_attr = {
158 	DDI_DEVICE_ATTR_V0,
159 	DDI_NEVERSWAP_ACC,
160 	DDI_STRICTORDER_ACC
161 };
162 
163 /* set limitation for the number of contig_mem */
164 static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
165 #endif
166 
167 /*
168  * Tunable parameters
169  *
170  * DISCLAIMER
171  * ----------
172  * These parameters are intended for use only in system testing; if you use
173  * them in production systems, you do so at your own risk. Altering any
174  * variable not listed below may cause unpredictable system behavior.
175  *
176  * st_check_media_time
177  *
178  *   Three second state check
179  *
180  * st_allow_large_xfer
181  *
182  *   Gated with ST_NO_RECSIZE_LIMIT
183  *
184  *   0 - Transfers larger than 64KB will not be allowed
185  *       regardless of the setting of ST_NO_RECSIZE_LIMIT
186  *   1 - Transfers larger than 64KB will be allowed
187  *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
188  *
189  * st_report_soft_errors_on_close
190  *
191  *  Gated with ST_SOFT_ERROR_REPORTING
192  *
193  *  0 - Errors will not be reported on close regardless
194  *      of the setting of ST_SOFT_ERROR_REPORTING
195  *
196  *  1 - Errors will be reported on close if
197  *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
198  */
199 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
200 static int st_retry_count	= ST_RETRY_COUNT;
201 
202 static int st_io_time		= ST_IO_TIME;
203 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
204 
205 static int st_space_time	= ST_SPACE_TIME;
206 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
207 
208 static int st_error_level	= SCSI_ERR_RETRYABLE;
209 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
210 
211 static int st_max_throttle	= ST_MAX_THROTTLE;
212 
213 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
214 
215 static int st_allow_large_xfer = 1;
216 static int st_report_soft_errors_on_close = 1;
217 
218 /*
219  * End of tunable parameters list
220  */
221 
222 
223 
224 /*
225  * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
226  *
227  * Asynchronous I/O's main offering is that it is a non-blocking way to do
228  * reads and writes.  The driver will queue up all the requests it gets and
229  * have them ready to transport to the HBA.  Unfortunately, we cannot always
230  * just ship the I/O requests to the HBA, as there errors and exceptions
231  * that may happen when we don't want the HBA to continue.  Therein comes
232  * the flush-on-errors capability.  If the HBA supports it, then st will
233  * send in st_max_throttle I/O requests at the same time.
234  *
235  * Persistent errors : This was also reasonably simple.  In the interrupt
236  * routines, if there was an error or exception (FM, LEOT, media error,
237  * transport error), the persistent error bits are set and shuts everything
238  * down, but setting the throttle to zero.  If we hit and exception in the
239  * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
240  * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
241  * the appropriate error, and this will preserve order. Of course, depending
242  * on the exception we have to show a zero read or write before we show
243  * errors back to the application.
244  */
245 
246 extern const int st_ndrivetypes;	/* defined in st_conf.c */
247 extern const struct st_drivetype st_drivetypes[];
248 extern const char st_conf_version[];
249 
250 #ifdef STDEBUG
251 static int st_soft_error_report_debug = 0;
252 volatile int st_debug = 0;
253 static volatile dev_info_t *st_lastdev;
254 static kmutex_t st_debug_mutex;
255 #endif
256 
257 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
258 
259 static const struct vid_drivetype {
260 	char	*vid;
261 	char	type;
262 } st_vid_dt[] = {
263 	{"LTO-CVE ",	MT_LTO},
264 	{"QUANTUM ",    MT_ISDLT},
265 	{"SONY    ",    MT_ISAIT},
266 	{"STK     ",	MT_ISSTK9840}
267 };
268 
269 static const struct driver_minor_data {
270 	char	*name;
271 	int	minor;
272 } st_minor_data[] = {
273 	/*
274 	 * The top 4 entries are for the default densities,
275 	 * don't alter their position.
276 	 */
277 	{"",	0},
278 	{"n",	MT_NOREWIND},
279 	{"b",	MT_BSD},
280 	{"bn",	MT_NOREWIND | MT_BSD},
281 	{"l",	MT_DENSITY1},
282 	{"m",	MT_DENSITY2},
283 	{"h",	MT_DENSITY3},
284 	{"c",	MT_DENSITY4},
285 	{"u",	MT_DENSITY4},
286 	{"ln",	MT_DENSITY1 | MT_NOREWIND},
287 	{"mn",	MT_DENSITY2 | MT_NOREWIND},
288 	{"hn",	MT_DENSITY3 | MT_NOREWIND},
289 	{"cn",	MT_DENSITY4 | MT_NOREWIND},
290 	{"un",	MT_DENSITY4 | MT_NOREWIND},
291 	{"lb",	MT_DENSITY1 | MT_BSD},
292 	{"mb",	MT_DENSITY2 | MT_BSD},
293 	{"hb",	MT_DENSITY3 | MT_BSD},
294 	{"cb",	MT_DENSITY4 | MT_BSD},
295 	{"ub",	MT_DENSITY4 | MT_BSD},
296 	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
297 	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
298 	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
299 	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
300 	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
301 };
302 
303 /* strings used in many debug and warning messages */
304 static const char wr_str[]  = "write";
305 static const char rd_str[]  = "read";
306 static const char wrg_str[] = "writing";
307 static const char rdg_str[] = "reading";
308 static const char *space_strs[] = {
309 	"records",
310 	"filemarks",
311 	"sequential filemarks",
312 	"eod",
313 	"setmarks",
314 	"sequential setmarks",
315 	"Reserved",
316 	"Reserved"
317 };
318 static const char *load_strs[] = {
319 	"unload",		/* LD_UNLOAD		0 */
320 	"load",			/* LD_LOAD		1 */
321 	"retension",		/* LD_RETEN		2 */
322 	"load reten",		/* LD_LOAD | LD_RETEN	3 */
323 	"eod",			/* LD_EOT		4 */
324 	"load EOD",		/* LD_LOAD | LD_EOT	5 */
325 	"reten EOD",		/* LD_RETEN | LD_EOT	6 */
326 	"load reten EOD"	/* LD_LOAD|LD_RETEN|LD_EOT 7 */
327 	"hold",			/* LD_HOLD		8 */
328 	"load and hold"		/* LD_LOAD | LD_HOLD	9 */
329 };
330 
331 static const char *errstatenames[] = {
332 	"COMMAND_DONE",
333 	"COMMAND_DONE_ERROR",
334 	"COMMAND_DONE_ERROR_RECOVERED",
335 	"QUE_COMMAND",
336 	"QUE_BUSY_COMMAND",
337 	"QUE_SENSE",
338 	"JUST_RETURN",
339 	"COMMAND_DONE_EACCES",
340 	"QUE_LAST_COMMAND",
341 	"COMMAND_TIMEOUT",
342 	"PATH_FAILED",
343 	"DEVICE_RESET",
344 	"DEVICE_TAMPER",
345 	"ATTEMPT_RETRY"
346 };
347 
348 const char *bogusID = "Unknown Media ID";
349 
350 /* default density offsets in the table above */
351 #define	DEF_BLANK	0
352 #define	DEF_NOREWIND	1
353 #define	DEF_BSD		2
354 #define	DEF_BSD_NR	3
355 
356 /* Sense Key, ASC/ASCQ for which tape ejection is needed */
357 
358 static struct tape_failure_code {
359 	uchar_t key;
360 	uchar_t add_code;
361 	uchar_t qual_code;
362 } st_tape_failure_code[] = {
363 	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
364 	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
365 	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
366 	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
367 	{ KEY_NOT_READY, 0x53, 0x00},
368 	{ 0xff}
369 };
370 
371 /*  clean bit position and mask */
372 
373 static struct cln_bit_position {
374 	ushort_t cln_bit_byte;
375 	uchar_t cln_bit_mask;
376 } st_cln_bit_position[] = {
377 	{ 21, 0x08},
378 	{ 70, 0xc0},
379 	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
380 };
381 
382 /*
383  * architecture dependent allocation restrictions. For x86, we'll set
384  * dma_attr_addr_hi to st_max_phys_addr and dma_attr_sgllen to
385  * st_sgl_size during _init().
386  */
387 #if defined(__sparc)
388 static ddi_dma_attr_t st_alloc_attr = {
389 	DMA_ATTR_V0,	/* version number */
390 	0x0,		/* lowest usable address */
391 	0xFFFFFFFFull,	/* high DMA address range */
392 	0xFFFFFFFFull,	/* DMA counter register */
393 	1,		/* DMA address alignment */
394 	1,		/* DMA burstsizes */
395 	1,		/* min effective DMA size */
396 	0xFFFFFFFFull,	/* max DMA xfer size */
397 	0xFFFFFFFFull,	/* segment boundary */
398 	1,		/* s/g list length */
399 	512,		/* granularity of device */
400 	0		/* DMA transfer flags */
401 };
402 #elif defined(__x86)
403 static ddi_dma_attr_t st_alloc_attr = {
404 	DMA_ATTR_V0,	/* version number */
405 	0x0,		/* lowest usable address */
406 	0x0,		/* high DMA address range [set in _init()] */
407 	0xFFFFull,	/* DMA counter register */
408 	512,		/* DMA address alignment */
409 	1,		/* DMA burstsizes */
410 	1,		/* min effective DMA size */
411 	0xFFFFFFFFull,	/* max DMA xfer size */
412 	0xFFFFFFFFull,  /* segment boundary */
413 	0,		/* s/g list length */
414 	512,		/* granularity of device [set in _init()] */
415 	0		/* DMA transfer flags */
416 };
417 uint64_t st_max_phys_addr = 0xFFFFFFFFull;
418 int st_sgl_size = 0xF;
419 
420 #endif
421 
422 /*
423  * Configuration Data:
424  *
425  * Device driver ops vector
426  */
427 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
428 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
429 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
430 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
431 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
432 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
433 static int st_strategy(struct buf *bp);
434 static int st_queued_strategy(buf_t *bp);
435 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
436 	cred_t *cred_p, int *rval_p);
437 extern int nulldev(), nodev();
438 
439 static struct cb_ops st_cb_ops = {
440 	st_open,		/* open */
441 	st_close,		/* close */
442 	st_queued_strategy,	/* strategy Not Block device but async checks */
443 	nodev,			/* print */
444 	nodev,			/* dump */
445 	st_read,		/* read */
446 	st_write,		/* write */
447 	st_ioctl,		/* ioctl */
448 	nodev,			/* devmap */
449 	nodev,			/* mmap */
450 	nodev,			/* segmap */
451 	nochpoll,		/* poll */
452 	ddi_prop_op,		/* cb_prop_op */
453 	0,			/* streamtab  */
454 	D_64BIT | D_MP | D_NEW | D_HOTPLUG |
455 	D_OPEN_RETURNS_EINTR,	/* cb_flag */
456 	CB_REV,			/* cb_rev */
457 	st_aread, 		/* async I/O read entry point */
458 	st_awrite		/* async I/O write entry point */
459 
460 };
461 
462 static int st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
463 		void **result);
464 static int st_probe(dev_info_t *dev);
465 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
466 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
467 
468 static struct dev_ops st_ops = {
469 	DEVO_REV,		/* devo_rev, */
470 	0,			/* refcnt  */
471 	st_info,		/* info */
472 	nulldev,		/* identify */
473 	st_probe,		/* probe */
474 	st_attach,		/* attach */
475 	st_detach,		/* detach */
476 	nodev,			/* reset */
477 	&st_cb_ops,		/* driver operations */
478 	(struct bus_ops *)0,	/* bus operations */
479 	nulldev,		/* power */
480 	ddi_quiesce_not_supported,	/* devo_quiesce */
481 };
482 
483 /*
484  * Local Function Declarations
485  */
486 static char *st_print_scsi_cmd(char cmd);
487 static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
488     char *title, char *cdb);
489 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
490     char *title, char *data, int len);
491 static int st_doattach(struct scsi_device *devp, int (*canwait)());
492 static void st_known_tape_type(struct scsi_tape *un);
493 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
494     struct st_drivetype *);
495 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
496     struct st_drivetype *);
497 static int st_get_conf_from_tape_drive(struct scsi_tape *, char *,
498     struct st_drivetype *);
499 static int st_get_densities_from_tape_drive(struct scsi_tape *,
500     struct st_drivetype *);
501 static int st_get_timeout_values_from_tape_drive(struct scsi_tape *,
502     struct st_drivetype *);
503 static int st_get_timeouts_value(struct scsi_tape *, uchar_t, ushort_t *,
504     ushort_t);
505 static int st_get_default_conf(struct scsi_tape *, char *,
506     struct st_drivetype *);
507 static int st_rw(dev_t dev, struct uio *uio, int flag);
508 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
509 static int st_find_eod(struct scsi_tape *un);
510 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
511 static int st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *, int flag);
512 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
513 static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
514 static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
515 static void st_start(struct scsi_tape *un);
516 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
517     clock_t timeout_interval, int queued);
518 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
519     clock_t timeout_interval);
520 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
521 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
522 static void st_init(struct scsi_tape *un);
523 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
524     int (*func)(caddr_t));
525 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
526     struct buf *bp, int (*func)(caddr_t));
527 static void st_intr(struct scsi_pkt *pkt);
528 static void st_set_state(struct scsi_tape *un, buf_t *bp);
529 static void st_test_append(struct buf *bp);
530 static int st_runout(caddr_t);
531 static int st_cmd(struct scsi_tape *un, int com, int64_t count, int wait);
532 static int st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com,
533     int64_t count);
534 static int st_set_compression(struct scsi_tape *un);
535 static int st_write_fm(dev_t dev, int wfm);
536 static int st_determine_generic(struct scsi_tape *un);
537 static int st_determine_density(struct scsi_tape *un, int rw);
538 static int st_get_density(struct scsi_tape *un);
539 static int st_set_density(struct scsi_tape *un);
540 static int st_loadtape(struct scsi_tape *un);
541 static int st_modesense(struct scsi_tape *un);
542 static int st_modeselect(struct scsi_tape *un);
543 static errstate st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
544 static int st_wrongtapetype(struct scsi_tape *un);
545 static errstate st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
546 static errstate st_handle_sense(struct scsi_tape *un, struct buf *bp,
547     tapepos_t *);
548 static errstate st_handle_autosense(struct scsi_tape *un, struct buf *bp,
549     tapepos_t *);
550 static int st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag);
551 static void st_update_error_stack(struct scsi_tape *un, struct scsi_pkt *pkt,
552     struct scsi_arq_status *cmd);
553 static void st_empty_error_stack(struct scsi_tape *un);
554 static errstate st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
555     struct scsi_arq_status *, tapepos_t *);
556 static int st_report_soft_errors(dev_t dev, int flag);
557 static void st_delayed_cv_broadcast(void *arg);
558 static int st_check_media(dev_t dev, enum mtio_state state);
559 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
560 static void st_intr_restart(void *arg);
561 static void st_start_restart(void *arg);
562 static int st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
563     struct seq_mode *page_data, int page_size);
564 static int st_change_block_size(struct scsi_tape *un, uint32_t nblksz);
565 static int st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
566     struct seq_mode *page_data, int page_size);
567 static int st_read_block_limits(struct scsi_tape *un,
568     struct read_blklim *read_blk);
569 static int st_report_density_support(struct scsi_tape *un,
570     uchar_t *density_data, size_t buflen);
571 static int st_report_supported_operation(struct scsi_tape *un,
572     uchar_t *oper_data, uchar_t option_code, ushort_t service_action);
573 static int st_tape_init(struct scsi_tape *un);
574 static void st_flush(struct scsi_tape *un);
575 static void st_set_pe_errno(struct scsi_tape *un);
576 static void st_hba_unflush(struct scsi_tape *un);
577 static void st_turn_pe_on(struct scsi_tape *un);
578 static void st_turn_pe_off(struct scsi_tape *un);
579 static void st_set_pe_flag(struct scsi_tape *un);
580 static void st_clear_pe(struct scsi_tape *un);
581 static void st_wait_for_io(struct scsi_tape *un);
582 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
583 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
584 static int st_reserve_release(struct scsi_tape *un, int command, ubufunc_t ubf);
585 static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb);
586 static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
587     int count);
588 static int st_take_ownership(struct scsi_tape *un, ubufunc_t ubf);
589 static int st_check_asc_ascq(struct scsi_tape *un);
590 static int st_check_clean_bit(struct scsi_tape *un);
591 static int st_check_alert_flags(struct scsi_tape *un);
592 static int st_check_sequential_clean_bit(struct scsi_tape *un);
593 static int st_check_sense_clean_bit(struct scsi_tape *un);
594 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
595 static void st_calculate_timeouts(struct scsi_tape *un);
596 static writablity st_is_drive_worm(struct scsi_tape *un);
597 static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
598     void *buf, size_t size, ubufunc_t bufunc);
599 static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
600     caddr_t dest, uchar_t page);
601 static int st_update_block_pos(struct scsi_tape *un, bufunc_t bf,
602     int post_space);
603 static int st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
604     read_p_types type, size_t data_sz, const caddr_t responce, int post_space);
605 static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
606 static int st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf,
607     tapepos_t *pos, uint64_t lblk, uchar_t partition);
608 static int st_mtfsf_ioctl(struct scsi_tape *un, int64_t files);
609 static int st_mtfsr_ioctl(struct scsi_tape *un, int64_t count);
610 static int st_mtbsf_ioctl(struct scsi_tape *un, int64_t files);
611 static int st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count);
612 static int st_mtbsr_ioctl(struct scsi_tape *un, int64_t num);
613 static int st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt);
614 static int st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt);
615 static int st_backward_space_files(struct scsi_tape *un, int64_t count,
616     int infront);
617 static int st_forward_space_files(struct scsi_tape *un, int64_t files);
618 static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
619     int32_t fileno);
620 static int st_space_to_begining_of_file(struct scsi_tape *un);
621 static int st_space_records(struct scsi_tape *un, int64_t records);
622 static int st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc);
623 static errstate st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
624     errstate onentry);
625 static void st_recover(void *arg);
626 static void st_recov_cb(struct scsi_pkt *pkt);
627 static int st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait);
628 static int st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
629     int flag);
630 static void st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
631     struct scsi_pkt *cmd);
632 static int st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf);
633 static int st_test_path_to_device(struct scsi_tape *un);
634 static int st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
635     read_pos_data_t *raw);
636 static int st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
637     read_pos_data_t *raw);
638 static int st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
639     cmd_attribute const * cmd_att, tapepos_t *read);
640 static errstate st_recover_reissue_pkt(struct scsi_tape *us,
641     struct scsi_pkt *pkt);
642 static int st_transport(struct scsi_tape *un, struct scsi_pkt *pkt);
643 static buf_t *st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp);
644 static void st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp);
645 static int st_reset(struct scsi_tape *un, int reset_type);
646 static void st_reset_notification(caddr_t arg);
647 static const cmd_attribute *st_lookup_cmd_attribute(unsigned char cmd);
648 
649 #ifdef	__x86
650 /*
651  * routines for I/O in big block size
652  */
653 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
654 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
655     int alloc_flags);
656 static int st_bigblk_xfer_done(struct buf *bp);
657 static struct buf *st_get_bigblk_bp(struct buf *bp);
658 #endif
659 static void st_print_position(dev_info_t *dev, char *label, uint_t level,
660     const char *comment, tapepos_t *pos);
661 
662 /*
663  * error statistics create/update functions
664  */
665 static int st_create_errstats(struct scsi_tape *, int);
666 static int st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf,
667     tapepos_t *pos);
668 
669 #ifdef STDEBUG
670 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
671 #endif /* STDEBUG */
672 static char *st_dev_name(dev_t dev);
673 
674 #if !defined(lint)
675 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
676     scsi_pkt buf uio scsi_cdb uscsi_cmd))
677 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
678 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", recov_info))
679 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
680 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
681 #endif
682 
683 /*
684  * autoconfiguration routines.
685  */
686 char _depends_on[] = "misc/scsi";
687 
688 static struct modldrv modldrv = {
689 	&mod_driverops,		/* Type of module. This one is a driver */
690 	"SCSI tape Driver", 	/* Name of the module. */
691 	&st_ops			/* driver ops */
692 };
693 
694 static struct modlinkage modlinkage = {
695 	MODREV_1, &modldrv, NULL
696 };
697 
698 /*
699  * Notes on Post Reset Behavior in the tape driver:
700  *
701  * When the tape drive is opened, the driver  attempts  to make sure that
702  * the tape head is positioned exactly where it was left when it was last
703  * closed  provided  the  medium  is not  changed.  If the tape  drive is
704  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
705  * of position due to reset) will happen when the first tape operation or
706  * I/O occurs.  The repositioning (if required) may not be possible under
707  * certain situations such as when the device firmware not able to report
708  * the medium  change in the REQUEST  SENSE data  because of a reset or a
709  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
710  * extraordinary  situations, where the driver fails to position the head
711  * at its  original  position,  it will fail the open the first  time, to
712  * save the applications from overwriting the data.  All further attempts
713  * to open the tape device will result in the driver  attempting  to load
714  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
715  * indicate  that further  attempts to open the tape device may result in
716  * the tape being  loaded at BOT will be printed on the  console.  If the
717  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
718  * original tape head  position,  will result in the failure of the first
719  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
720  * internal tape position  which will  necessitate  the  applications  to
721  * validate the position by using either a tape  positioning  ioctl (such
722  * as MTREW) or closing and reopening the tape device.
723  *
724  */
725 
726 int
727 _init(void)
728 {
729 	int e;
730 
731 	if (((e = ddi_soft_state_init(&st_state,
732 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
733 		return (e);
734 	}
735 
736 	if ((e = mod_install(&modlinkage)) != 0) {
737 		ddi_soft_state_fini(&st_state);
738 	} else {
739 #ifdef STDEBUG
740 		mutex_init(&st_debug_mutex, NULL, MUTEX_DRIVER, NULL);
741 #endif
742 
743 #if defined(__x86)
744 		/* set the max physical address for iob allocs on x86 */
745 		st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
746 
747 		/*
748 		 * set the sgllen for iob allocs on x86. If this is set less
749 		 * than the number of pages the buffer will take
750 		 * (taking into account alignment), it would force the
751 		 * allocator to try and allocate contiguous pages.
752 		 */
753 		st_alloc_attr.dma_attr_sgllen = st_sgl_size;
754 #endif
755 	}
756 
757 	return (e);
758 }
759 
760 int
761 _fini(void)
762 {
763 	int e;
764 
765 	if ((e = mod_remove(&modlinkage)) != 0) {
766 		return (e);
767 	}
768 
769 #ifdef STDEBUG
770 	mutex_destroy(&st_debug_mutex);
771 #endif
772 
773 	ddi_soft_state_fini(&st_state);
774 
775 	return (e);
776 }
777 
778 int
779 _info(struct modinfo *modinfop)
780 {
781 	return (mod_info(&modlinkage, modinfop));
782 }
783 
784 
785 static int
786 st_probe(dev_info_t *devi)
787 {
788 	int instance;
789 	struct scsi_device *devp;
790 	int rval;
791 
792 #if !defined(__sparc)
793 	char    *tape_prop;
794 	int	tape_prop_len;
795 #endif
796 
797 	ST_ENTR(devi, st_probe);
798 
799 	/* If self identifying device */
800 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
801 		return (DDI_PROBE_DONTCARE);
802 	}
803 
804 #if !defined(__sparc)
805 	/*
806 	 * Since some x86 HBAs have devnodes that look like SCSI as
807 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
808 	 * we check for the presence of the "tape" property.
809 	 */
810 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
811 	    DDI_PROP_CANSLEEP, "tape",
812 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
813 		return (DDI_PROBE_FAILURE);
814 	}
815 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
816 		kmem_free(tape_prop, tape_prop_len);
817 		return (DDI_PROBE_FAILURE);
818 	}
819 	kmem_free(tape_prop, tape_prop_len);
820 #endif
821 
822 	devp = ddi_get_driver_private(devi);
823 	instance = ddi_get_instance(devi);
824 
825 	if (ddi_get_soft_state(st_state, instance) != NULL) {
826 		return (DDI_PROBE_PARTIAL);
827 	}
828 
829 
830 	/*
831 	 * Turn around and call probe routine to see whether
832 	 * we actually have a tape at this SCSI nexus.
833 	 */
834 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
835 
836 		/*
837 		 * In checking the whole inq_dtype byte we are looking at both
838 		 * the Peripheral Qualifier and the Peripheral Device Type.
839 		 * For this driver we are only interested in sequential devices
840 		 * that are connected or capable if connecting to this logical
841 		 * unit.
842 		 */
843 		if (devp->sd_inq->inq_dtype ==
844 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
845 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
846 			    "probe exists\n");
847 			rval = DDI_PROBE_SUCCESS;
848 		} else {
849 			rval = DDI_PROBE_FAILURE;
850 		}
851 	} else {
852 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
853 		    "probe failure: nothing there\n");
854 		rval = DDI_PROBE_FAILURE;
855 	}
856 	scsi_unprobe(devp);
857 	return (rval);
858 }
859 
860 static int
861 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
862 {
863 	int 	instance;
864 	int	wide;
865 	int 	dev_instance;
866 	int	ret_status;
867 	struct	scsi_device *devp;
868 	int	node_ix;
869 	struct	scsi_tape *un;
870 
871 	ST_ENTR(devi, st_attach);
872 
873 	devp = ddi_get_driver_private(devi);
874 	instance = ddi_get_instance(devi);
875 
876 	switch (cmd) {
877 		case DDI_ATTACH:
878 			if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
879 			    "tape-command-recovery-disable", 0) != 0) {
880 				st_recov_sz = sizeof (pkt_info);
881 			}
882 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
883 				return (DDI_FAILURE);
884 			}
885 			break;
886 		case DDI_RESUME:
887 			/*
888 			 * Suspend/Resume
889 			 *
890 			 * When the driver suspended, there might be
891 			 * outstanding cmds and therefore we need to
892 			 * reset the suspended flag and resume the scsi
893 			 * watch thread and restart commands and timeouts
894 			 */
895 
896 			if (!(un = ddi_get_soft_state(st_state, instance))) {
897 				return (DDI_FAILURE);
898 			}
899 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
900 			    un->un_dev);
901 
902 			mutex_enter(ST_MUTEX);
903 
904 			un->un_throttle = un->un_max_throttle;
905 			un->un_tids_at_suspend = 0;
906 			un->un_pwr_mgmt = ST_PWR_NORMAL;
907 
908 			if (un->un_swr_token) {
909 				scsi_watch_resume(un->un_swr_token);
910 			}
911 
912 			/*
913 			 * Restart timeouts
914 			 */
915 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
916 				mutex_exit(ST_MUTEX);
917 				un->un_delay_tid = timeout(
918 				    st_delayed_cv_broadcast, un,
919 				    drv_usectohz((clock_t)
920 				    MEDIA_ACCESS_DELAY));
921 				mutex_enter(ST_MUTEX);
922 			}
923 
924 			if (un->un_tids_at_suspend & ST_HIB_TID) {
925 				mutex_exit(ST_MUTEX);
926 				un->un_hib_tid = timeout(st_intr_restart, un,
927 				    ST_STATUS_BUSY_TIMEOUT);
928 				mutex_enter(ST_MUTEX);
929 			}
930 
931 			ret_status = st_clear_unit_attentions(dev_instance, 5);
932 
933 			/*
934 			 * now check if we need to restore the tape position
935 			 */
936 			if ((un->un_suspend_pos.pmode != invalid) &&
937 			    ((un->un_suspend_pos.fileno > 0) ||
938 			    (un->un_suspend_pos.blkno > 0)) ||
939 			    (un->un_suspend_pos.lgclblkno > 0)) {
940 				if (ret_status != 0) {
941 					/*
942 					 * tape didn't get good TUR
943 					 * just print out error messages
944 					 */
945 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
946 					    "st_attach-RESUME: tape failure "
947 					    " tape position will be lost");
948 				} else {
949 					/* this prints errors */
950 					(void) st_validate_tapemarks(un,
951 					    st_uscsi_cmd, &un->un_suspend_pos);
952 				}
953 				/*
954 				 * there are no retries, if there is an error
955 				 * we don't know if the tape has changed
956 				 */
957 				un->un_suspend_pos.pmode = invalid;
958 			}
959 
960 			/* now we are ready to start up any queued I/Os */
961 			if (un->un_ncmds || un->un_quef) {
962 				st_start(un);
963 			}
964 
965 			cv_broadcast(&un->un_suspend_cv);
966 			mutex_exit(ST_MUTEX);
967 			return (DDI_SUCCESS);
968 
969 		default:
970 			return (DDI_FAILURE);
971 	}
972 
973 	un = ddi_get_soft_state(st_state, instance);
974 
975 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
976 	    "st_attach: instance=%x\n", instance);
977 
978 	/*
979 	 * Add a zero-length attribute to tell the world we support
980 	 * kernel ioctls (for layered drivers)
981 	 */
982 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
983 	    DDI_KERNEL_IOCTL, NULL, 0);
984 
985 	ddi_report_dev((dev_info_t *)devi);
986 
987 	/*
988 	 * If it's a SCSI-2 tape drive which supports wide,
989 	 * tell the host adapter to use wide.
990 	 */
991 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
992 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
993 
994 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
995 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
996 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
997 	}
998 
999 	/*
1000 	 * enable autorequest sense; keep the rq packet around in case
1001 	 * the autorequest sense fails because of a busy condition
1002 	 * do a getcap first in case the capability is not variable
1003 	 */
1004 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
1005 		un->un_arq_enabled = 1;
1006 	} else {
1007 		un->un_arq_enabled =
1008 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
1009 	}
1010 
1011 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
1012 	    (un->un_arq_enabled ? "enabled" : "disabled"));
1013 
1014 	un->un_untagged_qing =
1015 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
1016 
1017 	/*
1018 	 * XXX - This is just for 2.6.  to tell users that write buffering
1019 	 *	has gone away.
1020 	 */
1021 	if (un->un_arq_enabled && un->un_untagged_qing) {
1022 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
1023 		    "tape-driver-buffering", 0) != 0) {
1024 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1025 			    "Write Data Buffering has been depricated. Your "
1026 			    "applications should continue to work normally.\n"
1027 			    " But, they should  ported to use Asynchronous "
1028 			    " I/O\n"
1029 			    " For more information, read about "
1030 			    " tape-driver-buffering "
1031 			    "property in the st(7d) man page\n");
1032 		}
1033 	}
1034 
1035 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
1036 	un->un_flush_on_errors = 0;
1037 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
1038 
1039 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
1040 	    "throttle=%x, max_throttle = %x\n",
1041 	    un->un_throttle, un->un_max_throttle);
1042 
1043 	/* initialize persistent errors to nil */
1044 	un->un_persistence = 0;
1045 	un->un_persist_errors = 0;
1046 
1047 	/*
1048 	 * Get dma-max from HBA driver. If it is not defined, use 64k
1049 	 */
1050 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
1051 	if (un->un_maxdma == -1) {
1052 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1053 		    "Received a value that looked like -1. Using 64k maxdma");
1054 		un->un_maxdma = (64 * ONE_K);
1055 	}
1056 
1057 #ifdef	__x86
1058 	/*
1059 	 * for x86, the device may be able to DMA more than the system will
1060 	 * allow under some circumstances. We need account for both the HBA's
1061 	 * and system's contraints.
1062 	 *
1063 	 * Get the maximum DMA under worse case conditions. e.g. looking at the
1064 	 * device constraints, the max copy buffer size, and the worse case
1065 	 * fragmentation. NOTE: this may differ from dma-max since dma-max
1066 	 * doesn't take the worse case framentation into account.
1067 	 *
1068 	 * e.g. a device may be able to DMA 16MBytes, but can only DMA 1MByte
1069 	 * if none of the pages are contiguous. Keeping track of both of these
1070 	 * values allows us to support larger tape block sizes on some devices.
1071 	 */
1072 	un->un_maxdma_arch = scsi_ifgetcap(&devp->sd_address, "dma-max-arch",
1073 	    1);
1074 
1075 	/*
1076 	 * If the dma-max-arch capability is not implemented, or the value
1077 	 * comes back higher than what was reported in dma-max, use dma-max.
1078 	 */
1079 	if ((un->un_maxdma_arch == -1) ||
1080 	    ((uint_t)un->un_maxdma < (uint_t)un->un_maxdma_arch)) {
1081 		un->un_maxdma_arch = un->un_maxdma;
1082 	}
1083 #endif
1084 
1085 	/*
1086 	 * Get the max allowable cdb size
1087 	 */
1088 	un->un_max_cdb_sz =
1089 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
1090 	if (un->un_max_cdb_sz < CDB_GROUP0) {
1091 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1092 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
1093 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
1094 	}
1095 
1096 	if (strcmp(ddi_driver_name(ddi_get_parent(ST_DEVINFO)), "scsi_vhci")) {
1097 		un->un_multipath = 0;
1098 	} else {
1099 		un->un_multipath = 1;
1100 	}
1101 
1102 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1103 
1104 	un->un_mediastate = MTIO_NONE;
1105 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1106 
1107 	/*
1108 	 * initialize kstats
1109 	 */
1110 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1111 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1112 	if (un->un_stats) {
1113 		un->un_stats->ks_lock = ST_MUTEX;
1114 		kstat_install(un->un_stats);
1115 	}
1116 	(void) st_create_errstats(un, instance);
1117 
1118 	/*
1119 	 * find the drive type for this target
1120 	 */
1121 	mutex_enter(ST_MUTEX);
1122 	un->un_dev = MTMINOR(instance);
1123 	st_known_tape_type(un);
1124 	un->un_dev = 0;
1125 	mutex_exit(ST_MUTEX);
1126 
1127 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
1128 		int minor;
1129 		char *name;
1130 
1131 		name  = st_minor_data[node_ix].name;
1132 		minor = st_minor_data[node_ix].minor;
1133 
1134 		/*
1135 		 * For default devices set the density to the
1136 		 * preferred default density for this device.
1137 		 */
1138 		if (node_ix <= DEF_BSD_NR) {
1139 			minor |= un->un_dp->default_density;
1140 		}
1141 		minor |= MTMINOR(instance);
1142 
1143 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
1144 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
1145 			continue;
1146 		}
1147 
1148 		ddi_remove_minor_node(devi, NULL);
1149 
1150 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1151 		    st_reset_notification, (caddr_t)un);
1152 		cv_destroy(&un->un_clscv);
1153 		cv_destroy(&un->un_sbuf_cv);
1154 		cv_destroy(&un->un_queue_cv);
1155 		cv_destroy(&un->un_state_cv);
1156 #ifdef	__x86
1157 		cv_destroy(&un->un_contig_mem_cv);
1158 #endif
1159 		cv_destroy(&un->un_suspend_cv);
1160 		cv_destroy(&un->un_tape_busy_cv);
1161 		cv_destroy(&un->un_recov_buf_cv);
1162 		if (un->un_recov_taskq) {
1163 			ddi_taskq_destroy(un->un_recov_taskq);
1164 		}
1165 		if (un->un_sbufp) {
1166 			freerbuf(un->un_sbufp);
1167 		}
1168 		if (un->un_recov_buf) {
1169 			freerbuf(un->un_recov_buf);
1170 		}
1171 		if (un->un_uscsi_rqs_buf) {
1172 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1173 		}
1174 		if (un->un_mspl) {
1175 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1176 		}
1177 		if (un->un_dp_size) {
1178 			kmem_free(un->un_dp, un->un_dp_size);
1179 		}
1180 		if (un->un_state) {
1181 			kstat_delete(un->un_stats);
1182 		}
1183 		if (un->un_errstats) {
1184 			kstat_delete(un->un_errstats);
1185 		}
1186 
1187 		scsi_destroy_pkt(un->un_rqs);
1188 		scsi_free_consistent_buf(un->un_rqs_bp);
1189 		ddi_soft_state_free(st_state, instance);
1190 		devp->sd_private = NULL;
1191 		devp->sd_sense = NULL;
1192 
1193 		ddi_prop_remove_all(devi);
1194 		return (DDI_FAILURE);
1195 	}
1196 
1197 	return (DDI_SUCCESS);
1198 }
1199 
1200 /*
1201  * st_detach:
1202  *
1203  * we allow a detach if and only if:
1204  *	- no tape is currently inserted
1205  *	- tape position is at BOT or unknown
1206  *		(if it is not at BOT then a no rewind
1207  *		device was opened and we have to preserve state)
1208  *	- it must be in a closed state : no timeouts or scsi_watch requests
1209  *		will exist if it is closed, so we don't need to check for
1210  *		them here.
1211  */
1212 /*ARGSUSED*/
1213 static int
1214 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1215 {
1216 	int instance;
1217 	int result;
1218 	struct scsi_device *devp;
1219 	struct scsi_tape *un;
1220 	clock_t wait_cmds_complete;
1221 
1222 	ST_ENTR(devi, st_detach);
1223 
1224 	instance = ddi_get_instance(devi);
1225 
1226 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1227 		return (DDI_FAILURE);
1228 	}
1229 
1230 	mutex_enter(ST_MUTEX);
1231 
1232 	/*
1233 	 * Clear error entry stack
1234 	 */
1235 	st_empty_error_stack(un);
1236 
1237 	mutex_exit(ST_MUTEX);
1238 
1239 	switch (cmd) {
1240 
1241 	case DDI_DETACH:
1242 		/*
1243 		 * Undo what we did in st_attach & st_doattach,
1244 		 * freeing resources and removing things we installed.
1245 		 * The system framework guarantees we are not active
1246 		 * with this devinfo node in any other entry points at
1247 		 * this time.
1248 		 */
1249 
1250 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1251 		    "st_detach: instance=%x, un=%p\n", instance,
1252 		    (void *)un);
1253 
1254 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1255 		    ((un->un_rsvd_status & ST_APPLICATION_RESERVATIONS) != 0) ||
1256 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1257 		    (un->un_state != ST_STATE_CLOSED)) {
1258 			/*
1259 			 * we cannot unload some targets because the
1260 			 * inquiry returns junk unless immediately
1261 			 * after a reset
1262 			 */
1263 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1264 			    "cannot unload instance %x\n", instance);
1265 			un->un_unit_attention_flags |= 4;
1266 			return (DDI_FAILURE);
1267 		}
1268 
1269 		/*
1270 		 * if the tape has been removed then we may unload;
1271 		 * do a test unit ready and if it returns NOT READY
1272 		 * then we assume that it is safe to unload.
1273 		 * as a side effect, pmode may be set to invalid if the
1274 		 * the test unit ready fails;
1275 		 * also un_state may be set to non-closed, so reset it
1276 		 */
1277 		if ((un->un_dev) &&		/* Been opened since attach */
1278 		    ((un->un_pos.pmode == legacy) &&
1279 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1280 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1281 		    ((un->un_pos.pmode == logical) &&
1282 		    (un->un_pos.lgclblkno > 0))) {
1283 			mutex_enter(ST_MUTEX);
1284 			/*
1285 			 * Send Test Unit Ready in the hopes that if
1286 			 * the drive is not in the state we think it is.
1287 			 * And the state will be changed so it can be detached.
1288 			 * If the command fails to reach the device and
1289 			 * the drive was not rewound or unloaded we want
1290 			 * to fail the detach till a user command fails
1291 			 * where after the detach will succead.
1292 			 */
1293 			result = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
1294 			/*
1295 			 * After TUR un_state may be set to non-closed,
1296 			 * so reset it back.
1297 			 */
1298 			un->un_state = ST_STATE_CLOSED;
1299 			mutex_exit(ST_MUTEX);
1300 		}
1301 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1302 		    "un_status=%x, fileno=%x, blkno=%x\n",
1303 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1304 
1305 		/*
1306 		 * check again:
1307 		 * if we are not at BOT then it is not safe to unload
1308 		 */
1309 		if ((un->un_dev) &&		/* Been opened since attach */
1310 		    (result != EACCES) &&	/* drive is use by somebody */
1311 		    (((un->un_pos.pmode == legacy) &&
1312 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1313 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1314 		    ((un->un_pos.pmode == logical) &&
1315 		    (un->un_pos.lgclblkno > 0)))) {
1316 
1317 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1318 			    "cannot detach: pmode=%d fileno=0x%x, blkno=0x%x"
1319 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1320 			    un->un_pos.fileno, un->un_pos.blkno,
1321 			    un->un_pos.lgclblkno);
1322 			un->un_unit_attention_flags |= 4;
1323 			return (DDI_FAILURE);
1324 		}
1325 
1326 		/*
1327 		 * Just To make sure that we have released the
1328 		 * tape unit .
1329 		 */
1330 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1331 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1332 			mutex_enter(ST_MUTEX);
1333 			(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
1334 			mutex_exit(ST_MUTEX);
1335 		}
1336 
1337 		/*
1338 		 * now remove other data structures allocated in st_doattach()
1339 		 */
1340 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1341 		    "destroying/freeing\n");
1342 
1343 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1344 		    st_reset_notification, (caddr_t)un);
1345 		cv_destroy(&un->un_clscv);
1346 		cv_destroy(&un->un_sbuf_cv);
1347 		cv_destroy(&un->un_queue_cv);
1348 		cv_destroy(&un->un_suspend_cv);
1349 		cv_destroy(&un->un_tape_busy_cv);
1350 		cv_destroy(&un->un_recov_buf_cv);
1351 
1352 		if (un->un_recov_taskq) {
1353 			ddi_taskq_destroy(un->un_recov_taskq);
1354 		}
1355 
1356 		if (un->un_hib_tid) {
1357 			(void) untimeout(un->un_hib_tid);
1358 			un->un_hib_tid = 0;
1359 		}
1360 
1361 		if (un->un_delay_tid) {
1362 			(void) untimeout(un->un_delay_tid);
1363 			un->un_delay_tid = 0;
1364 		}
1365 		cv_destroy(&un->un_state_cv);
1366 
1367 #ifdef	__x86
1368 		cv_destroy(&un->un_contig_mem_cv);
1369 
1370 		if (un->un_contig_mem_hdl != NULL) {
1371 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1372 		}
1373 #endif
1374 		if (un->un_sbufp) {
1375 			freerbuf(un->un_sbufp);
1376 		}
1377 		if (un->un_recov_buf) {
1378 			freerbuf(un->un_recov_buf);
1379 		}
1380 		if (un->un_uscsi_rqs_buf) {
1381 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1382 		}
1383 		if (un->un_mspl) {
1384 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1385 		}
1386 		if (un->un_rqs) {
1387 			scsi_destroy_pkt(un->un_rqs);
1388 			scsi_free_consistent_buf(un->un_rqs_bp);
1389 		}
1390 		if (un->un_mkr_pkt) {
1391 			scsi_destroy_pkt(un->un_mkr_pkt);
1392 		}
1393 		if (un->un_arq_enabled) {
1394 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1395 		}
1396 		if (un->un_dp_size) {
1397 			kmem_free(un->un_dp, un->un_dp_size);
1398 		}
1399 		if (un->un_stats) {
1400 			kstat_delete(un->un_stats);
1401 			un->un_stats = (kstat_t *)0;
1402 		}
1403 		if (un->un_errstats) {
1404 			kstat_delete(un->un_errstats);
1405 			un->un_errstats = (kstat_t *)0;
1406 		}
1407 		if (un->un_media_id_len) {
1408 			kmem_free(un->un_media_id, un->un_media_id_len);
1409 		}
1410 		devp = ST_SCSI_DEVP;
1411 		ddi_soft_state_free(st_state, instance);
1412 		devp->sd_private = NULL;
1413 		devp->sd_sense = NULL;
1414 		scsi_unprobe(devp);
1415 		ddi_prop_remove_all(devi);
1416 		ddi_remove_minor_node(devi, NULL);
1417 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1418 		return (DDI_SUCCESS);
1419 
1420 	case DDI_SUSPEND:
1421 
1422 		/*
1423 		 * Suspend/Resume
1424 		 *
1425 		 * To process DDI_SUSPEND, we must do the following:
1426 		 *
1427 		 *  - check ddi_removing_power to see if power will be turned
1428 		 *    off. if so, return DDI_FAILURE
1429 		 *  - check if we are already suspended,
1430 		 *    if so, return DDI_FAILURE
1431 		 *  - check if device state is CLOSED,
1432 		 *    if not, return DDI_FAILURE.
1433 		 *  - wait until outstanding operations complete
1434 		 *  - save tape state
1435 		 *  - block new operations
1436 		 *  - cancel pending timeouts
1437 		 *
1438 		 */
1439 
1440 		if (ddi_removing_power(devi)) {
1441 			return (DDI_FAILURE);
1442 		}
1443 		mutex_enter(ST_MUTEX);
1444 
1445 		/*
1446 		 * Shouldn't already be suspended, if so return failure
1447 		 */
1448 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1449 			mutex_exit(ST_MUTEX);
1450 			return (DDI_FAILURE);
1451 		}
1452 		if (un->un_state != ST_STATE_CLOSED) {
1453 			mutex_exit(ST_MUTEX);
1454 			return (DDI_FAILURE);
1455 		}
1456 
1457 		/*
1458 		 * Wait for all outstanding I/O's to complete
1459 		 *
1460 		 * we wait on both ncmds and the wait queue for times
1461 		 * when we are flushing after persistent errors are
1462 		 * flagged, which is when ncmds can be 0, and the
1463 		 * queue can still have I/O's.  This way we preserve
1464 		 * order of biodone's.
1465 		 */
1466 		wait_cmds_complete = ddi_get_lbolt();
1467 		wait_cmds_complete +=
1468 		    st_wait_cmds_complete * drv_usectohz(1000000);
1469 		while (un->un_ncmds || un->un_quef ||
1470 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1471 
1472 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1473 			    wait_cmds_complete) == -1) {
1474 				/*
1475 				 * Time expired then cancel the command
1476 				 */
1477 				if (st_reset(un, RESET_LUN) == 0) {
1478 					if (un->un_last_throttle) {
1479 						un->un_throttle =
1480 						    un->un_last_throttle;
1481 					}
1482 					mutex_exit(ST_MUTEX);
1483 					return (DDI_FAILURE);
1484 				} else {
1485 					break;
1486 				}
1487 			}
1488 		}
1489 
1490 		/*
1491 		 * DDI_SUSPEND says that the system "may" power down, we
1492 		 * remember the file and block number before rewinding.
1493 		 * we also need to save state before issuing
1494 		 * any WRITE_FILE_MARK command.
1495 		 */
1496 		(void) st_update_block_pos(un, st_cmd, 0);
1497 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1498 
1499 
1500 		/*
1501 		 * Issue a zero write file fmk command to tell the drive to
1502 		 * flush any buffered tape marks
1503 		 */
1504 		(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1505 
1506 		/*
1507 		 * Because not all tape drives correctly implement buffer
1508 		 * flushing with the zero write file fmk command, issue a
1509 		 * synchronous rewind command to force data flushing.
1510 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1511 		 * anyway.
1512 		 */
1513 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
1514 
1515 		/* stop any new operations */
1516 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1517 		un->un_throttle = 0;
1518 
1519 		/*
1520 		 * cancel any outstanding timeouts
1521 		 */
1522 		if (un->un_delay_tid) {
1523 			timeout_id_t temp_id = un->un_delay_tid;
1524 			un->un_delay_tid = 0;
1525 			un->un_tids_at_suspend |= ST_DELAY_TID;
1526 			mutex_exit(ST_MUTEX);
1527 			(void) untimeout(temp_id);
1528 			mutex_enter(ST_MUTEX);
1529 		}
1530 
1531 		if (un->un_hib_tid) {
1532 			timeout_id_t temp_id = un->un_hib_tid;
1533 			un->un_hib_tid = 0;
1534 			un->un_tids_at_suspend |= ST_HIB_TID;
1535 			mutex_exit(ST_MUTEX);
1536 			(void) untimeout(temp_id);
1537 			mutex_enter(ST_MUTEX);
1538 		}
1539 
1540 		/*
1541 		 * Suspend the scsi_watch_thread
1542 		 */
1543 		if (un->un_swr_token) {
1544 			opaque_t temp_token = un->un_swr_token;
1545 			mutex_exit(ST_MUTEX);
1546 			scsi_watch_suspend(temp_token);
1547 		} else {
1548 			mutex_exit(ST_MUTEX);
1549 		}
1550 
1551 		return (DDI_SUCCESS);
1552 
1553 	default:
1554 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1555 		return (DDI_FAILURE);
1556 	}
1557 }
1558 
1559 
1560 /* ARGSUSED */
1561 static int
1562 st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1563 {
1564 	dev_t dev;
1565 	struct scsi_tape *un;
1566 	int instance, error;
1567 
1568 	ST_ENTR(dip, st_info);
1569 
1570 	switch (infocmd) {
1571 	case DDI_INFO_DEVT2DEVINFO:
1572 		dev = (dev_t)arg;
1573 		instance = MTUNIT(dev);
1574 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1575 			return (DDI_FAILURE);
1576 		*result = (void *) ST_DEVINFO;
1577 		error = DDI_SUCCESS;
1578 		break;
1579 	case DDI_INFO_DEVT2INSTANCE:
1580 		dev = (dev_t)arg;
1581 		instance = MTUNIT(dev);
1582 		*result = (void *)(uintptr_t)instance;
1583 		error = DDI_SUCCESS;
1584 		break;
1585 	default:
1586 		error = DDI_FAILURE;
1587 	}
1588 	return (error);
1589 }
1590 
1591 static int
1592 st_doattach(struct scsi_device *devp, int (*canwait)())
1593 {
1594 	struct scsi_tape *un = NULL;
1595 	recov_info *ri;
1596 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1597 	int instance;
1598 	size_t rlen;
1599 
1600 	ST_FUNC(devp->sd_dev, st_doattach);
1601 	/*
1602 	 * Call the routine scsi_probe to do some of the dirty work.
1603 	 * If the INQUIRY command succeeds, the field sd_inq in the
1604 	 * device structure will be filled in.
1605 	 */
1606 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1607 	    "st_doattach(): probing\n");
1608 
1609 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1610 
1611 		/*
1612 		 * In checking the whole inq_dtype byte we are looking at both
1613 		 * the Peripheral Qualifier and the Peripheral Device Type.
1614 		 * For this driver we are only interested in sequential devices
1615 		 * that are connected or capable if connecting to this logical
1616 		 * unit.
1617 		 */
1618 		if (devp->sd_inq->inq_dtype ==
1619 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1620 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1621 			    "probe exists\n");
1622 		} else {
1623 			/* Something there but not a tape device */
1624 			scsi_unprobe(devp);
1625 			return (DDI_FAILURE);
1626 		}
1627 	} else {
1628 		/* Nothing there */
1629 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1630 		    "probe failure: nothing there\n");
1631 		scsi_unprobe(devp);
1632 		return (DDI_FAILURE);
1633 	}
1634 
1635 
1636 	/*
1637 	 * The actual unit is present.
1638 	 * Now is the time to fill in the rest of our info..
1639 	 */
1640 	instance = ddi_get_instance(devp->sd_dev);
1641 
1642 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1643 		goto error;
1644 	}
1645 	un = ddi_get_soft_state(st_state, instance);
1646 
1647 	ASSERT(un != NULL);
1648 
1649 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
1650 	    MAX_SENSE_LENGTH, B_READ, canwait, NULL);
1651 	if (un->un_rqs_bp == NULL) {
1652 		goto error;
1653 	}
1654 	un->un_rqs = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
1655 	    CDB_GROUP0, 1, st_recov_sz, PKT_CONSISTENT, canwait, NULL);
1656 	if (!un->un_rqs) {
1657 		goto error;
1658 	}
1659 	ASSERT(un->un_rqs->pkt_resid == 0);
1660 	devp->sd_sense =
1661 	    (struct scsi_extended_sense *)un->un_rqs_bp->b_un.b_addr;
1662 	ASSERT(geterror(un->un_rqs_bp) == NULL);
1663 
1664 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs->pkt_cdbp,
1665 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
1666 	FILL_SCSI1_LUN(devp, un->un_rqs);
1667 	un->un_rqs->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1668 	un->un_rqs->pkt_time = st_io_time;
1669 	un->un_rqs->pkt_comp = st_intr;
1670 	ri = (recov_info *)un->un_rqs->pkt_private;
1671 	if (st_recov_sz == sizeof (recov_info)) {
1672 		ri->privatelen = sizeof (recov_info);
1673 	} else {
1674 		ri->privatelen = sizeof (pkt_info);
1675 	}
1676 
1677 	un->un_sbufp = getrbuf(km_flags);
1678 	un->un_recov_buf = getrbuf(km_flags);
1679 
1680 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1681 
1682 	/*
1683 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1684 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1685 	 * is obsolete and we want more flexibility in controlling the DMA
1686 	 * address constraints.
1687 	 */
1688 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1689 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1690 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1691 
1692 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1693 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1694 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1695 
1696 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1697 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1698 		    "probe partial failure: no space\n");
1699 		goto error;
1700 	}
1701 
1702 	bzero(un->un_mspl, sizeof (struct seq_mode));
1703 
1704 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1705 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1706 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1707 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1708 #ifdef	__x86
1709 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1710 #endif
1711 
1712 	/* Initialize power managemnet condition variable */
1713 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1714 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1715 	cv_init(&un->un_recov_buf_cv, NULL, CV_DRIVER, NULL);
1716 
1717 	un->un_recov_taskq = ddi_taskq_create(devp->sd_dev,
1718 	    "un_recov_taskq", 1, TASKQ_DEFAULTPRI, km_flags);
1719 
1720 	ASSERT(un->un_recov_taskq != NULL);
1721 
1722 	un->un_pos.pmode = invalid;
1723 	un->un_sd	= devp;
1724 	un->un_swr_token = (opaque_t)NULL;
1725 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1726 	un->un_wormable = st_is_drive_worm;
1727 	un->un_media_id_method = st_get_media_identification;
1728 	/*
1729 	 * setting long a initial as it contains logical file info.
1730 	 * support for long format is mandatory but many drive don't do it.
1731 	 */
1732 	un->un_read_pos_type = LONG_POS;
1733 
1734 	un->un_suspend_pos.pmode = invalid;
1735 
1736 	st_add_recovery_info_to_pkt(un, un->un_rqs_bp, un->un_rqs);
1737 
1738 #ifdef	__x86
1739 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1740 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1741 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1742 		    "allocation of contiguous memory dma handle failed!");
1743 		un->un_contig_mem_hdl = NULL;
1744 		goto error;
1745 	}
1746 #endif
1747 
1748 	/*
1749 	 * Since this driver manages devices with "remote" hardware,
1750 	 * i.e. the devices themselves have no "reg" properties,
1751 	 * the SUSPEND/RESUME commands in detach/attach will not be
1752 	 * called by the power management framework unless we request
1753 	 * it by creating a "pm-hardware-state" property and setting it
1754 	 * to value "needs-suspend-resume".
1755 	 */
1756 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1757 	    "pm-hardware-state", "needs-suspend-resume") !=
1758 	    DDI_PROP_SUCCESS) {
1759 
1760 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1761 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1762 		goto error;
1763 	}
1764 
1765 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1766 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1767 
1768 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1769 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1770 		    "failed\n");
1771 		goto error;
1772 	}
1773 
1774 	(void) scsi_reset_notify(ROUTE, SCSI_RESET_NOTIFY,
1775 	    st_reset_notification, (caddr_t)un);
1776 
1777 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "attach success\n");
1778 	return (DDI_SUCCESS);
1779 
1780 error:
1781 	devp->sd_sense = NULL;
1782 
1783 	ddi_remove_minor_node(devp->sd_dev, NULL);
1784 	if (un) {
1785 		if (un->un_mspl) {
1786 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1787 		}
1788 		if (un->un_read_pos_data) {
1789 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1790 		}
1791 		if (un->un_sbufp) {
1792 			freerbuf(un->un_sbufp);
1793 		}
1794 		if (un->un_recov_buf) {
1795 			freerbuf(un->un_recov_buf);
1796 		}
1797 		if (un->un_uscsi_rqs_buf) {
1798 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1799 		}
1800 #ifdef	__x86
1801 		if (un->un_contig_mem_hdl != NULL) {
1802 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1803 		}
1804 #endif
1805 		if (un->un_rqs) {
1806 			scsi_destroy_pkt(un->un_rqs);
1807 		}
1808 
1809 		if (un->un_rqs_bp) {
1810 			scsi_free_consistent_buf(un->un_rqs_bp);
1811 		}
1812 
1813 		ddi_soft_state_free(st_state, instance);
1814 		devp->sd_private = NULL;
1815 	}
1816 
1817 	if (devp->sd_inq) {
1818 		scsi_unprobe(devp);
1819 	}
1820 	return (DDI_FAILURE);
1821 }
1822 
1823 typedef int
1824 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1825 
1826 static cfg_functp config_functs[] = {
1827 	st_get_conf_from_st_dot_conf,
1828 	st_get_conf_from_st_conf_dot_c,
1829 	st_get_conf_from_tape_drive,
1830 	st_get_default_conf
1831 };
1832 
1833 
1834 /*
1835  * determine tape type, using tape-config-list or built-in table or
1836  * use a generic tape config entry
1837  */
1838 static void
1839 st_known_tape_type(struct scsi_tape *un)
1840 {
1841 	struct st_drivetype *dp;
1842 	cfg_functp *config_funct;
1843 	uchar_t reserved;
1844 
1845 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1846 
1847 	reserved = (un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1848 	    : ST_RELEASE;
1849 
1850 	/*
1851 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1852 	 *	 no vid & pid inquiry data.  So, we provide one.
1853 	 */
1854 	if (ST_INQUIRY->inq_len == 0 ||
1855 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1856 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1857 	}
1858 
1859 	if (un->un_dp_size == 0) {
1860 		un->un_dp_size = sizeof (struct st_drivetype);
1861 		dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1862 		un->un_dp = dp;
1863 	} else {
1864 		dp = un->un_dp;
1865 	}
1866 
1867 	un->un_dp->non_motion_timeout = st_io_time;
1868 	/*
1869 	 * Loop through the configuration methods till one works.
1870 	 */
1871 	for (config_funct = &config_functs[0]; ; config_funct++) {
1872 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1873 			break;
1874 		}
1875 	}
1876 
1877 	/*
1878 	 * If we didn't just make up this configuration and
1879 	 * all the density codes are the same..
1880 	 * Set Auto Density over ride.
1881 	 */
1882 	if (*config_funct != st_get_default_conf) {
1883 		/*
1884 		 * If this device is one that is configured and all
1885 		 * densities are the same, This saves doing gets and set
1886 		 * that yield nothing.
1887 		 */
1888 		if ((dp->densities[0]) == (dp->densities[1]) &&
1889 		    (dp->densities[0]) == (dp->densities[2]) &&
1890 		    (dp->densities[0]) == (dp->densities[3])) {
1891 
1892 			dp->options |= ST_AUTODEN_OVERRIDE;
1893 		}
1894 	}
1895 
1896 
1897 	/*
1898 	 * Store tape drive characteristics.
1899 	 */
1900 	un->un_status = 0;
1901 	un->un_attached = 1;
1902 	un->un_init_options = dp->options;
1903 
1904 	/* setup operation time-outs based on options */
1905 	st_calculate_timeouts(un);
1906 
1907 	/* make sure if we are supposed to be variable, make it variable */
1908 	if (dp->options & ST_VARIABLE) {
1909 		dp->bsize = 0;
1910 	}
1911 
1912 	if (reserved != ((un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1913 	    : ST_RELEASE)) {
1914 		(void) st_reserve_release(un, reserved, st_uscsi_cmd);
1915 	}
1916 
1917 	un->un_unit_attention_flags |= 1;
1918 
1919 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1920 
1921 }
1922 
1923 
1924 typedef struct {
1925 	int mask;
1926 	int bottom;
1927 	int top;
1928 	char *name;
1929 } conf_limit;
1930 
1931 static const conf_limit conf_limits[] = {
1932 
1933 	-1,		1,		2,		"conf version",
1934 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1935 	-1,		0,		0xffffff,	"block size",
1936 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1937 	-1,		0,		4,		"number of densities",
1938 	-1,		0,		UINT8_MAX,	"density code",
1939 	-1,		0,		3,		"default density",
1940 	-1,		0,		UINT16_MAX,	"non motion timeout",
1941 	-1,		0,		UINT16_MAX,	"I/O timeout",
1942 	-1,		0,		UINT16_MAX,	"space timeout",
1943 	-1,		0,		UINT16_MAX,	"load timeout",
1944 	-1,		0,		UINT16_MAX,	"unload timeout",
1945 	-1,		0,		UINT16_MAX,	"erase timeout",
1946 	0,		0,		0,		NULL
1947 };
1948 
1949 static int
1950 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1951     const char *conf_name)
1952 {
1953 	int dens;
1954 	int ndens;
1955 	int value;
1956 	int type;
1957 	int count;
1958 	const conf_limit *limit = &conf_limits[0];
1959 
1960 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1961 
1962 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1963 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1964 
1965 	count = list_len;
1966 	type = *list;
1967 	for (;  count && limit->name; count--, list++, limit++) {
1968 
1969 		value = *list;
1970 		if (value & ~limit->mask) {
1971 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1972 			    "%s %s value invalid bits set: 0x%X\n",
1973 			    conf_name, limit->name, value & ~limit->mask);
1974 			*list &= limit->mask;
1975 		} else if (value < limit->bottom) {
1976 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1977 			    "%s %s value too low: value = %d limit %d\n",
1978 			    conf_name, limit->name, value, limit->bottom);
1979 		} else if (value > limit->top) {
1980 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1981 			    "%s %s value too high: value = %d limit %d\n",
1982 			    conf_name, limit->name, value, limit->top);
1983 		} else {
1984 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1985 			    "%s %s value = 0x%X\n",
1986 			    conf_name, limit->name, value);
1987 		}
1988 
1989 		/* If not the number of densities continue */
1990 		if (limit != &conf_limits[4]) {
1991 			continue;
1992 		}
1993 
1994 		/* If number of densities is not in range can't use config */
1995 		if (value < limit->bottom || value > limit->top) {
1996 			return (-1);
1997 		}
1998 
1999 		ndens = min(value, NDENSITIES);
2000 		if ((type == 1) && (list_len - ndens) != 6) {
2001 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2002 			    "%s conf version 1 with %d densities has %d items"
2003 			    " should have %d",
2004 			    conf_name, ndens, list_len, 6 + ndens);
2005 		} else if ((type == 2) && (list_len - ndens) != 13) {
2006 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2007 			    "%s conf version 2 with %d densities has %d items"
2008 			    " should have %d",
2009 			    conf_name, ndens, list_len, 13 + ndens);
2010 		}
2011 
2012 		limit++;
2013 		for (dens = 0; dens < ndens && count; dens++) {
2014 			count--;
2015 			list++;
2016 			value = *list;
2017 			if (value < limit->bottom) {
2018 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2019 				    "%s density[%d] value too low: value ="
2020 				    " 0x%X limit 0x%X\n",
2021 				    conf_name, dens, value, limit->bottom);
2022 			} else if (value > limit->top) {
2023 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2024 				    "%s density[%d] value too high: value ="
2025 				    " 0x%X limit 0x%X\n",
2026 				    conf_name, dens, value, limit->top);
2027 			} else {
2028 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2029 				    "%s density[%d] value = 0x%X\n",
2030 				    conf_name, dens, value);
2031 			}
2032 		}
2033 	}
2034 
2035 	return (0);
2036 }
2037 
2038 static int
2039 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
2040     struct st_drivetype *dp)
2041 {
2042 	caddr_t config_list = NULL;
2043 	caddr_t data_list = NULL;
2044 	int	*data_ptr;
2045 	caddr_t vidptr, prettyptr, datanameptr;
2046 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
2047 	int config_list_len, data_list_len, len, i;
2048 	int version;
2049 	int found = 0;
2050 
2051 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
2052 
2053 	/*
2054 	 * Determine type of tape controller. Type is determined by
2055 	 * checking the vendor ids of the earlier inquiry command and
2056 	 * comparing those with vids in tape-config-list defined in st.conf
2057 	 */
2058 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
2059 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
2060 	    != DDI_PROP_SUCCESS) {
2061 		return (found);
2062 	}
2063 
2064 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2065 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
2066 
2067 	/*
2068 	 * Compare vids in each triplet - if it matches, get value for
2069 	 * data_name and contruct a st_drivetype struct
2070 	 * tripletlen is not set yet!
2071 	 */
2072 	for (len = config_list_len, vidptr = config_list;
2073 	    len > 0;
2074 	    vidptr += tripletlen, len -= tripletlen) {
2075 
2076 		vidlen = strlen(vidptr);
2077 		prettyptr = vidptr + vidlen + 1;
2078 		prettylen = strlen(prettyptr);
2079 		datanameptr = prettyptr + prettylen + 1;
2080 		datanamelen = strlen(datanameptr);
2081 		tripletlen = vidlen + prettylen + datanamelen + 3;
2082 
2083 		if (vidlen == 0) {
2084 			continue;
2085 		}
2086 
2087 		/*
2088 		 * If inquiry vid dosen't match this triplets vid,
2089 		 * try the next.
2090 		 */
2091 		if (strncasecmp(vidpid, vidptr, vidlen)) {
2092 			continue;
2093 		}
2094 
2095 		/*
2096 		 * if prettylen is zero then use the vid string
2097 		 */
2098 		if (prettylen == 0) {
2099 			prettyptr = vidptr;
2100 			prettylen = vidlen;
2101 		}
2102 
2103 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2104 		    "vid = %s, pretty=%s, dataname = %s\n",
2105 		    vidptr, prettyptr, datanameptr);
2106 
2107 		/*
2108 		 * get the data list
2109 		 */
2110 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
2111 		    datanameptr, (caddr_t)&data_list,
2112 		    &data_list_len) != DDI_PROP_SUCCESS) {
2113 			/*
2114 			 * Error in getting property value
2115 			 * print warning!
2116 			 */
2117 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2118 			    "data property (%s) has no value\n",
2119 			    datanameptr);
2120 			continue;
2121 		}
2122 
2123 		/*
2124 		 * now initialize the st_drivetype struct
2125 		 */
2126 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
2127 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
2128 		(void) strncpy(dp->vid, vidptr, dp->length);
2129 		data_ptr = (int *)data_list;
2130 		/*
2131 		 * check if data is enough for version, type,
2132 		 * bsize, options, # of densities, density1,
2133 		 * density2, ..., default_density
2134 		 */
2135 		if ((data_list_len < 5 * sizeof (int)) ||
2136 		    (data_list_len < 6 * sizeof (int) +
2137 		    *(data_ptr + 4) * sizeof (int))) {
2138 			/*
2139 			 * print warning and skip to next triplet.
2140 			 */
2141 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2142 			    "data property (%s) incomplete\n",
2143 			    datanameptr);
2144 			kmem_free(data_list, data_list_len);
2145 			continue;
2146 		}
2147 
2148 		if (st_validate_conf_data(un, data_ptr,
2149 		    data_list_len / sizeof (int), datanameptr)) {
2150 			kmem_free(data_list, data_list_len);
2151 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2152 			    "data property (%s) rejected\n",
2153 			    datanameptr);
2154 			continue;
2155 		}
2156 
2157 		/*
2158 		 * check version
2159 		 */
2160 		version = *data_ptr++;
2161 		if (version != 1 && version != 2) {
2162 			/* print warning but accept it */
2163 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2164 			    "Version # for data property (%s) "
2165 			    "not set to 1 or 2\n", datanameptr);
2166 		}
2167 
2168 		dp->type    = *data_ptr++;
2169 		dp->bsize   = *data_ptr++;
2170 		dp->options = *data_ptr++;
2171 		dp->options |= ST_DYNAMIC;
2172 		len = *data_ptr++;
2173 		for (i = 0; i < NDENSITIES; i++) {
2174 			if (i < len) {
2175 				dp->densities[i] = *data_ptr++;
2176 			}
2177 		}
2178 		dp->default_density = *data_ptr << 3;
2179 		if (version == 2 &&
2180 		    data_list_len >= (13 + len) * sizeof (int)) {
2181 			data_ptr++;
2182 			dp->non_motion_timeout	= *data_ptr++;
2183 			dp->io_timeout		= *data_ptr++;
2184 			dp->rewind_timeout	= *data_ptr++;
2185 			dp->space_timeout	= *data_ptr++;
2186 			dp->load_timeout	= *data_ptr++;
2187 			dp->unload_timeout	= *data_ptr++;
2188 			dp->erase_timeout	= *data_ptr++;
2189 		}
2190 		kmem_free(data_list, data_list_len);
2191 		found = 1;
2192 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2193 		    "found in st.conf: vid = %s, pretty=%s\n",
2194 		    dp->vid, dp->name);
2195 		break;
2196 	}
2197 
2198 	/*
2199 	 * free up the memory allocated by ddi_getlongprop
2200 	 */
2201 	if (config_list) {
2202 		kmem_free(config_list, config_list_len);
2203 	}
2204 	return (found);
2205 }
2206 
2207 static int
2208 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2209     struct st_drivetype *dp)
2210 {
2211 	int i;
2212 
2213 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2214 	/*
2215 	 * Determine type of tape controller.  Type is determined by
2216 	 * checking the result of the earlier inquiry command and
2217 	 * comparing vendor ids with strings in a table declared in st_conf.c.
2218 	 */
2219 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2220 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2221 
2222 	for (i = 0; i < st_ndrivetypes; i++) {
2223 		if (st_drivetypes[i].length == 0) {
2224 			continue;
2225 		}
2226 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2227 		    st_drivetypes[i].length)) {
2228 			continue;
2229 		}
2230 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2231 		return (1);
2232 	}
2233 	return (0);
2234 }
2235 
2236 static int
2237 st_get_conf_from_tape_drive(struct scsi_tape *un, char *vidpid,
2238     struct st_drivetype *dp)
2239 {
2240 	int bsize;
2241 	ulong_t maxbsize;
2242 	caddr_t buf;
2243 	struct st_drivetype *tem_dp;
2244 	struct read_blklim *blklim;
2245 	int rval;
2246 	int i;
2247 
2248 	ST_FUNC(ST_DEVINFO, st_get_conf_from_tape_drive);
2249 
2250 	/*
2251 	 * Determine the type of tape controller. Type is determined by
2252 	 * sending SCSI commands to tape drive and deriving the type from
2253 	 * the returned data.
2254 	 */
2255 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2256 	    "st_get_conf_from_tape_drive(): asking tape drive\n");
2257 
2258 	tem_dp = kmem_zalloc(sizeof (struct st_drivetype), KM_SLEEP);
2259 
2260 	/*
2261 	 * Make up a name
2262 	 */
2263 	bcopy(vidpid, tem_dp->name, VIDPIDLEN);
2264 	tem_dp->name[VIDPIDLEN] = '\0';
2265 	tem_dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2266 	(void) strncpy(tem_dp->vid, ST_INQUIRY->inq_vid, tem_dp->length);
2267 	/*
2268 	 * 'clean' vendor and product strings of non-printing chars
2269 	 */
2270 	for (i = 0; i < VIDPIDLEN - 1; i ++) {
2271 		if (tem_dp->name[i] < ' ' || tem_dp->name[i] > '~') {
2272 			tem_dp->name[i] = '.';
2273 		}
2274 	}
2275 
2276 	/*
2277 	 * MODE SENSE to determine block size.
2278 	 */
2279 	un->un_dp->options |= ST_MODE_SEL_COMP | ST_UNLOADABLE;
2280 	rval = st_modesense(un);
2281 	if (rval) {
2282 		if (rval == EACCES) {
2283 			un->un_dp->type = ST_TYPE_INVALID;
2284 			rval = 1;
2285 		} else {
2286 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
2287 			rval = 0;
2288 		}
2289 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2290 		    "st_get_conf_from_tape_drive(): fail to mode sense\n");
2291 		goto exit;
2292 	}
2293 
2294 	/* Can mode sense page 0x10 or 0xf */
2295 	tem_dp->options |= ST_MODE_SEL_COMP;
2296 	bsize = (un->un_mspl->high_bl << 16)	|
2297 	    (un->un_mspl->mid_bl << 8)		|
2298 	    (un->un_mspl->low_bl);
2299 
2300 	if (bsize == 0) {
2301 		tem_dp->options |= ST_VARIABLE;
2302 		tem_dp->bsize = 0;
2303 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
2304 		rval = st_change_block_size(un, 0);
2305 		if (rval) {
2306 			if (rval == EACCES) {
2307 				un->un_dp->type = ST_TYPE_INVALID;
2308 				rval = 1;
2309 			} else {
2310 				rval = 0;
2311 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2312 				    "st_get_conf_from_tape_drive(): "
2313 				    "Fixed record size is too large and"
2314 				    "cannot switch to variable record size");
2315 			}
2316 			goto exit;
2317 		}
2318 		tem_dp->options |= ST_VARIABLE;
2319 	} else {
2320 		rval = st_change_block_size(un, 0);
2321 		if (rval == 0) {
2322 			tem_dp->options |= ST_VARIABLE;
2323 			tem_dp->bsize = 0;
2324 		} else if (rval != EACCES) {
2325 			tem_dp->bsize = bsize;
2326 		} else {
2327 			un->un_dp->type = ST_TYPE_INVALID;
2328 			rval = 1;
2329 			goto exit;
2330 		}
2331 	}
2332 
2333 	/*
2334 	 * If READ BLOCk LIMITS works and upper block size limit is
2335 	 * more than 64K, ST_NO_RECSIZE_LIMIT is supported.
2336 	 */
2337 	blklim = kmem_zalloc(sizeof (struct read_blklim), KM_SLEEP);
2338 	rval = st_read_block_limits(un, blklim);
2339 	if (rval) {
2340 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2341 		    "st_get_conf_from_tape_drive(): "
2342 		    "fail to read block limits.\n");
2343 		rval = 0;
2344 		kmem_free(blklim, sizeof (struct read_blklim));
2345 		goto exit;
2346 	}
2347 	maxbsize = (blklim->max_hi << 16) +
2348 	    (blklim->max_mid << 8) + blklim->max_lo;
2349 	if (maxbsize > ST_MAXRECSIZE_VARIABLE) {
2350 		tem_dp->options |= ST_NO_RECSIZE_LIMIT;
2351 	}
2352 	kmem_free(blklim, sizeof (struct read_blklim));
2353 
2354 	/*
2355 	 * Inquiry VPD page 0xb0 to see if the tape drive supports WORM
2356 	 */
2357 	buf = kmem_zalloc(6, KM_SLEEP);
2358 	rval = st_get_special_inquiry(un, 6, buf, 0xb0);
2359 	if (rval) {
2360 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2361 		    "st_get_conf_from_tape_drive(): "
2362 		    "fail to read vitial inquiry.\n");
2363 		rval = 0;
2364 		kmem_free(buf, 6);
2365 		goto exit;
2366 	}
2367 	if (buf[4] & 1) {
2368 		tem_dp->options |= ST_WORMABLE;
2369 	}
2370 	kmem_free(buf, 6);
2371 
2372 	/* Assume BSD BSR KNOWS_EOD */
2373 	tem_dp->options |= ST_BSF | ST_BSR | ST_KNOWS_EOD | ST_UNLOADABLE;
2374 	tem_dp->max_rretries = -1;
2375 	tem_dp->max_wretries = -1;
2376 
2377 	/*
2378 	 * Decide the densities supported by tape drive by sending
2379 	 * REPORT DENSITY SUPPORT command.
2380 	 */
2381 	if (st_get_densities_from_tape_drive(un, tem_dp) == 0) {
2382 		goto exit;
2383 	}
2384 
2385 	/*
2386 	 * Decide the timeout values for several commands by sending
2387 	 * REPORT SUPPORTED OPERATION CODES command.
2388 	 */
2389 	rval = st_get_timeout_values_from_tape_drive(un, tem_dp);
2390 	if (rval == 0 || ((rval == 1) && (tem_dp->type == ST_TYPE_INVALID))) {
2391 		goto exit;
2392 	}
2393 
2394 	bcopy(tem_dp, dp, sizeof (struct st_drivetype));
2395 	rval = 1;
2396 
2397 exit:
2398 	un->un_status = KEY_NO_SENSE;
2399 	kmem_free(tem_dp, sizeof (struct st_drivetype));
2400 	return (rval);
2401 }
2402 
2403 static int
2404 st_get_densities_from_tape_drive(struct scsi_tape *un,
2405     struct st_drivetype *dp)
2406 {
2407 	int i, p;
2408 	size_t buflen;
2409 	ushort_t des_len;
2410 	uchar_t *den_header;
2411 	uchar_t num_den;
2412 	uchar_t den[NDENSITIES];
2413 	uchar_t deflt[NDENSITIES];
2414 	struct report_density_desc *den_desc;
2415 
2416 	ST_FUNC(ST_DEVINFO, st_get_densities_from_type_drive);
2417 
2418 	/*
2419 	 * Since we have no idea how many densitiy support entries
2420 	 * will be returned, we send the command firstly assuming
2421 	 * there is only one. Then we can decide the number of
2422 	 * entries by available density support length. If multiple
2423 	 * entries exist, we will resend the command with enough
2424 	 * buffer size.
2425 	 */
2426 	buflen = sizeof (struct report_density_header) +
2427 	    sizeof (struct report_density_desc);
2428 	den_header = kmem_zalloc(buflen, KM_SLEEP);
2429 	if (st_report_density_support(un, den_header, buflen) != 0) {
2430 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2431 		    "st_get_conf_from_tape_drive(): fail to report density.\n");
2432 		kmem_free(den_header, buflen);
2433 		return (0);
2434 	}
2435 	des_len =
2436 	    BE_16(((struct report_density_header *)den_header)->ava_dens_len);
2437 	num_den = (des_len - 2) / sizeof (struct report_density_desc);
2438 
2439 	if (num_den > 1) {
2440 		kmem_free(den_header, buflen);
2441 		buflen = sizeof (struct report_density_header) +
2442 		    sizeof (struct report_density_desc) * num_den;
2443 		den_header = kmem_zalloc(buflen, KM_SLEEP);
2444 		if (st_report_density_support(un, den_header, buflen) != 0) {
2445 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2446 			    "st_get_conf_from_tape_drive(): "
2447 			    "fail to report density.\n");
2448 			kmem_free(den_header, buflen);
2449 			return (0);
2450 		}
2451 	}
2452 
2453 	den_desc = (struct report_density_desc *)(den_header
2454 	    + sizeof (struct report_density_header));
2455 
2456 	/*
2457 	 * Decide the drive type by assigning organization
2458 	 */
2459 	for (i = 0; i < ST_NUM_MEMBERS(st_vid_dt); i ++) {
2460 		if (strncmp(st_vid_dt[i].vid, (char *)(den_desc->ass_org),
2461 		    8) == 0) {
2462 			dp->type = st_vid_dt[i].type;
2463 			break;
2464 		}
2465 	}
2466 	if (i == ST_NUM_MEMBERS(st_vid_dt)) {
2467 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2468 		    "st_get_conf_from_tape_drive(): "
2469 		    "can't find match of assigned ort.\n");
2470 		kmem_free(den_header, buflen);
2471 		return (0);
2472 	}
2473 
2474 	/*
2475 	 * The tape drive may support many tape formats, but the st driver
2476 	 * supports only the four highest densities. Since density code
2477 	 * values are returned by ascending sequence, we start from the
2478 	 * last entry of density support data block descriptor.
2479 	 */
2480 	p = 0;
2481 	den_desc += num_den - 1;
2482 	for (i = 0; i < num_den && p < NDENSITIES; i ++, den_desc --) {
2483 		if ((den_desc->pri_den != 0) && (den_desc->wrtok)) {
2484 			if (p != 0) {
2485 				if (den_desc->pri_den >= den[p - 1]) {
2486 					continue;
2487 				}
2488 			}
2489 			den[p] = den_desc->pri_den;
2490 			deflt[p] = den_desc->deflt;
2491 			p ++;
2492 		}
2493 	}
2494 
2495 	switch (p) {
2496 	case 0:
2497 		bzero(dp->densities, NDENSITIES);
2498 		dp->options |= ST_AUTODEN_OVERRIDE;
2499 		dp->default_density = MT_DENSITY4;
2500 		break;
2501 
2502 	case 1:
2503 		(void) memset(dp->densities, den[0], NDENSITIES);
2504 		dp->options |= ST_AUTODEN_OVERRIDE;
2505 		dp->default_density = MT_DENSITY4;
2506 		break;
2507 
2508 	case 2:
2509 		dp->densities[0] = den[1];
2510 		dp->densities[1] = den[1];
2511 		dp->densities[2] = den[0];
2512 		dp->densities[3] = den[0];
2513 		if (deflt[0]) {
2514 			dp->default_density = MT_DENSITY4;
2515 		} else {
2516 			dp->default_density = MT_DENSITY2;
2517 		}
2518 		break;
2519 
2520 	case 3:
2521 		dp->densities[0] = den[2];
2522 		dp->densities[1] = den[1];
2523 		dp->densities[2] = den[0];
2524 		dp->densities[3] = den[0];
2525 		if (deflt[0]) {
2526 			dp->default_density = MT_DENSITY4;
2527 		} else if (deflt[1]) {
2528 			dp->default_density = MT_DENSITY2;
2529 		} else {
2530 			dp->default_density = MT_DENSITY1;
2531 		}
2532 		break;
2533 
2534 	default:
2535 		for (i = p; i > p - NDENSITIES; i --) {
2536 			dp->densities[i - 1] = den[p - i];
2537 		}
2538 		if (deflt[0]) {
2539 			dp->default_density = MT_DENSITY4;
2540 		} else if (deflt[1]) {
2541 			dp->default_density = MT_DENSITY3;
2542 		} else if (deflt[2]) {
2543 			dp->default_density = MT_DENSITY2;
2544 		} else {
2545 			dp->default_density = MT_DENSITY1;
2546 		}
2547 		break;
2548 	}
2549 
2550 	bzero(dp->mediatype, NDENSITIES);
2551 
2552 	kmem_free(den_header, buflen);
2553 	return (1);
2554 }
2555 
2556 static int
2557 st_get_timeout_values_from_tape_drive(struct scsi_tape *un,
2558     struct st_drivetype *dp)
2559 {
2560 	ushort_t timeout;
2561 	int rval;
2562 
2563 	ST_FUNC(ST_DEVINFO, st_get_timeout_values_from_type_drive);
2564 
2565 	rval = st_get_timeouts_value(un, SCMD_ERASE, &timeout, 0);
2566 	if (rval) {
2567 		if (rval == EACCES) {
2568 			un->un_dp->type = ST_TYPE_INVALID;
2569 			dp->type = ST_TYPE_INVALID;
2570 			return (1);
2571 		}
2572 		return (0);
2573 	}
2574 	dp->erase_timeout = timeout;
2575 
2576 	rval = st_get_timeouts_value(un, SCMD_READ, &timeout, 0);
2577 	if (rval) {
2578 		if (rval == EACCES) {
2579 			un->un_dp->type = ST_TYPE_INVALID;
2580 			dp->type = ST_TYPE_INVALID;
2581 			return (1);
2582 		}
2583 		return (0);
2584 	}
2585 	dp->io_timeout = timeout;
2586 
2587 	rval = st_get_timeouts_value(un, SCMD_WRITE, &timeout, 0);
2588 	if (rval) {
2589 		if (rval == EACCES) {
2590 			un->un_dp->type = ST_TYPE_INVALID;
2591 			dp->type = ST_TYPE_INVALID;
2592 			return (1);
2593 		}
2594 		return (0);
2595 	}
2596 	dp->io_timeout = max(dp->io_timeout, timeout);
2597 
2598 	rval = st_get_timeouts_value(un, SCMD_SPACE, &timeout, 0);
2599 	if (rval) {
2600 		if (rval == EACCES) {
2601 			un->un_dp->type = ST_TYPE_INVALID;
2602 			dp->type = ST_TYPE_INVALID;
2603 			return (1);
2604 		}
2605 		return (0);
2606 	}
2607 	dp->space_timeout = timeout;
2608 
2609 	rval = st_get_timeouts_value(un, SCMD_LOAD, &timeout, 0);
2610 	if (rval) {
2611 		if (rval == EACCES) {
2612 			un->un_dp->type = ST_TYPE_INVALID;
2613 			dp->type = ST_TYPE_INVALID;
2614 			return (1);
2615 		}
2616 		return (0);
2617 	}
2618 	dp->load_timeout = timeout;
2619 	dp->unload_timeout = timeout;
2620 
2621 	rval = st_get_timeouts_value(un, SCMD_REWIND, &timeout, 0);
2622 	if (rval) {
2623 		if (rval == EACCES) {
2624 			un->un_dp->type = ST_TYPE_INVALID;
2625 			dp->type = ST_TYPE_INVALID;
2626 			return (1);
2627 		}
2628 		return (0);
2629 	}
2630 	dp->rewind_timeout = timeout;
2631 
2632 	rval = st_get_timeouts_value(un, SCMD_INQUIRY, &timeout, 0);
2633 	if (rval) {
2634 		if (rval == EACCES) {
2635 			un->un_dp->type = ST_TYPE_INVALID;
2636 			dp->type = ST_TYPE_INVALID;
2637 			return (1);
2638 		}
2639 		return (0);
2640 	}
2641 	dp->non_motion_timeout = timeout;
2642 
2643 	return (1);
2644 }
2645 
2646 static int
2647 st_get_timeouts_value(struct scsi_tape *un, uchar_t option_code,
2648     ushort_t *timeout_value, ushort_t service_action)
2649 {
2650 	uchar_t *timeouts;
2651 	uchar_t *oper;
2652 	uchar_t support;
2653 	uchar_t cdbsize;
2654 	uchar_t ctdp;
2655 	size_t buflen;
2656 	int rval;
2657 
2658 	ST_FUNC(ST_DEVINFO, st_get_timeouts_value);
2659 
2660 	buflen = sizeof (struct one_com_des) +
2661 	    sizeof (struct com_timeout_des);
2662 	oper = kmem_zalloc(buflen, KM_SLEEP);
2663 	rval = st_report_supported_operation(un, oper, option_code,
2664 	    service_action);
2665 
2666 	if (rval) {
2667 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2668 		    "st_get_timeouts_value(): "
2669 		    "fail to timeouts value for command %d.\n", option_code);
2670 		kmem_free(oper, buflen);
2671 		return (rval);
2672 	}
2673 
2674 	support = ((struct one_com_des *)oper)->support;
2675 	if ((support != SUPPORT_VALUES_SUPPORT_SCSI) &&
2676 	    (support != SUPPORT_VALUES_SUPPORT_VENDOR)) {
2677 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2678 		    "st_get_timeouts_value(): "
2679 		    "command %d is not supported.\n", option_code);
2680 		kmem_free(oper, buflen);
2681 		return (ENOTSUP);
2682 	}
2683 
2684 	ctdp = ((struct one_com_des *)oper)->ctdp;
2685 	if (!ctdp) {
2686 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2687 		    "st_get_timeouts_value(): "
2688 		    "command timeout is not included.\n");
2689 		kmem_free(oper, buflen);
2690 		return (ENOTSUP);
2691 	}
2692 
2693 	cdbsize = BE_16(((struct one_com_des *)oper)->cdb_size);
2694 	timeouts = (uchar_t *)(oper + cdbsize + 4);
2695 
2696 	/*
2697 	 * Timeout value in seconds is 4 bytes, but we only support the lower 2
2698 	 * bytes. If the higher 2 bytes are not zero, the timeout value is set
2699 	 * to 0xFFFF.
2700 	 */
2701 	if (*(timeouts + 8) != 0 || *(timeouts + 9) != 0) {
2702 		*timeout_value = USHRT_MAX;
2703 	} else {
2704 		*timeout_value = ((*(timeouts + 10)) << 8) |
2705 		    (*(timeouts + 11));
2706 	}
2707 
2708 	kmem_free(oper, buflen);
2709 	return (0);
2710 }
2711 
2712 static int
2713 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2714 {
2715 	int i;
2716 
2717 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2718 
2719 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2720 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2721 
2722 	/*
2723 	 * Make up a name
2724 	 */
2725 	bcopy("Vendor '", dp->name, 8);
2726 	bcopy(vidpid, &dp->name[8], VIDLEN);
2727 	bcopy("' Product '", &dp->name[16], 11);
2728 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2729 	dp->name[ST_NAMESIZE - 2] = '\'';
2730 	dp->name[ST_NAMESIZE - 1] = '\0';
2731 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2732 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2733 	/*
2734 	 * 'clean' vendor and product strings of non-printing chars
2735 	 */
2736 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2737 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2738 			dp->name[i] = '.';
2739 		}
2740 	}
2741 	dp->type = ST_TYPE_INVALID;
2742 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2743 
2744 	return (1); /* Can Not Fail */
2745 }
2746 
2747 /*
2748  * Regular Unix Entry points
2749  */
2750 
2751 
2752 
2753 /* ARGSUSED */
2754 static int
2755 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2756 {
2757 	dev_t dev = *dev_p;
2758 	int rval = 0;
2759 
2760 	GET_SOFT_STATE(dev);
2761 
2762 	ST_ENTR(ST_DEVINFO, st_open);
2763 
2764 	/*
2765 	 * validate that we are addressing a sensible unit
2766 	 */
2767 	mutex_enter(ST_MUTEX);
2768 
2769 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2770 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2771 	    st_dev_name(dev), *dev_p, flag, otyp);
2772 
2773 	/*
2774 	 * All device accesss go thru st_strategy() where we check
2775 	 * suspend status
2776 	 */
2777 
2778 	if (!un->un_attached) {
2779 		st_known_tape_type(un);
2780 		if (!un->un_attached) {
2781 			rval = ENXIO;
2782 			goto exit;
2783 		}
2784 
2785 	}
2786 
2787 	/*
2788 	 * Check for the case of the tape in the middle of closing.
2789 	 * This isn't simply a check of the current state, because
2790 	 * we could be in state of sensing with the previous state
2791 	 * that of closing.
2792 	 *
2793 	 * And don't allow multiple opens.
2794 	 */
2795 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2796 		un->un_laststate = un->un_state;
2797 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2798 		while (IS_CLOSING(un) ||
2799 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2800 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2801 				rval = EINTR;
2802 				un->un_state = un->un_laststate;
2803 				goto exit;
2804 			}
2805 		}
2806 	} else if (un->un_state != ST_STATE_CLOSED) {
2807 		rval = EBUSY;
2808 		goto busy;
2809 	}
2810 
2811 	/*
2812 	 * record current dev
2813 	 */
2814 	un->un_dev = dev;
2815 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2816 	un->un_errno = 0;	/* no errors yet */
2817 	un->un_restore_pos = 0;
2818 	un->un_rqs_state = 0;
2819 
2820 	/*
2821 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2822 	 * anything, leave internal states alone, if fileno >= 0
2823 	 */
2824 	if (flag & (FNDELAY | FNONBLOCK)) {
2825 		switch (un->un_pos.pmode) {
2826 
2827 		case invalid:
2828 			un->un_state = ST_STATE_OFFLINE;
2829 			break;
2830 
2831 		case legacy:
2832 			/*
2833 			 * If position is anything other than rewound.
2834 			 */
2835 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2836 				/*
2837 				 * set un_read_only/write-protect status.
2838 				 *
2839 				 * If the tape is not bot we can assume
2840 				 * that mspl->wp_status is set properly.
2841 				 * else
2842 				 * we need to do a mode sense/Tur once
2843 				 * again to get the actual tape status.(since
2844 				 * user might have replaced the tape)
2845 				 * Hence make the st state OFFLINE so that
2846 				 * we re-intialize the tape once again.
2847 				 */
2848 				un->un_read_only =
2849 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2850 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2851 			} else {
2852 				un->un_state = ST_STATE_OFFLINE;
2853 			}
2854 			break;
2855 		case logical:
2856 			if (un->un_pos.lgclblkno == 0) {
2857 				un->un_state = ST_STATE_OFFLINE;
2858 			} else {
2859 				un->un_read_only =
2860 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2861 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2862 			}
2863 			break;
2864 		}
2865 		rval = 0;
2866 	} else {
2867 		/*
2868 		 * Not opening O_NDELAY.
2869 		 */
2870 		un->un_state = ST_STATE_OPENING;
2871 
2872 		/*
2873 		 * Clear error entry stack
2874 		 */
2875 		st_empty_error_stack(un);
2876 
2877 		rval = st_tape_init(un);
2878 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2879 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2880 			rval = 0; /* so open doesn't fail */
2881 		} else if (rval) {
2882 			/*
2883 			 * Release the tape unit, if reserved and not
2884 			 * preserve reserve.
2885 			 */
2886 			if ((un->un_rsvd_status &
2887 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2888 				(void) st_reserve_release(un, ST_RELEASE,
2889 				    st_uscsi_cmd);
2890 			}
2891 		} else {
2892 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2893 		}
2894 	}
2895 
2896 exit:
2897 	/*
2898 	 * we don't want any uninvited guests scrogging our data when we're
2899 	 * busy with something, so for successful opens or failed opens
2900 	 * (except for EBUSY), reset these counters and state appropriately.
2901 	 */
2902 	if (rval != EBUSY) {
2903 		if (rval) {
2904 			un->un_state = ST_STATE_CLOSED;
2905 		}
2906 		un->un_err_resid = 0;
2907 		un->un_retry_ct = 0;
2908 	}
2909 busy:
2910 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2911 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2912 	mutex_exit(ST_MUTEX);
2913 	return (rval);
2914 
2915 }
2916 
2917 static int
2918 st_tape_init(struct scsi_tape *un)
2919 {
2920 	int err;
2921 	int rval = 0;
2922 
2923 	ST_FUNC(ST_DEVINFO, st_tape_init);
2924 
2925 	ASSERT(mutex_owned(ST_MUTEX));
2926 
2927 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2928 	    "st_tape_init(un = 0x%p, oflags = %d)\n", (void*)un, un->un_oflags);
2929 
2930 	/*
2931 	 * Clean up after any errors left by 'last' close.
2932 	 * This also handles the case of the initial open.
2933 	 */
2934 	if (un->un_state != ST_STATE_INITIALIZING) {
2935 		un->un_laststate = un->un_state;
2936 		un->un_state = ST_STATE_OPENING;
2937 	}
2938 
2939 	un->un_kbytes_xferred = 0;
2940 
2941 	/*
2942 	 * do a throw away TUR to clear check condition
2943 	 */
2944 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2945 
2946 	/*
2947 	 * If test unit ready fails because the drive is reserved
2948 	 * by another host fail the open for no access.
2949 	 */
2950 	if (err) {
2951 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2952 			un->un_state = ST_STATE_CLOSED;
2953 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2954 			    "st_tape_init: RESERVATION CONFLICT\n");
2955 			rval = EACCES;
2956 			goto exit;
2957 		} else if ((un->un_rsvd_status &
2958 		    ST_APPLICATION_RESERVATIONS) != 0) {
2959 			if ((ST_RQSENSE != NULL) &&
2960 			    (ST_RQSENSE->es_add_code == 0x2a &&
2961 			    ST_RQSENSE->es_qual_code == 0x03)) {
2962 				un->un_state = ST_STATE_CLOSED;
2963 				rval = EACCES;
2964 				goto exit;
2965 			}
2966 		}
2967 	}
2968 
2969 	/*
2970 	 * Tape self identification could fail if the tape drive is used by
2971 	 * another host during attach time. We try to get the tape type
2972 	 * again. This is also applied to any posponed configuration methods.
2973 	 */
2974 	if (un->un_dp->type == ST_TYPE_INVALID) {
2975 		un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
2976 		st_known_tape_type(un);
2977 	}
2978 
2979 	/*
2980 	 * If the tape type is still invalid, try to determine the generic
2981 	 * configuration.
2982 	 */
2983 	if (un->un_dp->type == ST_TYPE_INVALID) {
2984 		rval = st_determine_generic(un);
2985 		if (rval) {
2986 			if (rval != EACCES) {
2987 				rval = EIO;
2988 			}
2989 			un->un_state = ST_STATE_CLOSED;
2990 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2991 			    "st_tape_init: %s invalid type\n",
2992 			    rval == EACCES ? "EACCES" : "EIO");
2993 			goto exit;
2994 		}
2995 		/*
2996 		 * If this is a Unknown Type drive,
2997 		 * Use the READ BLOCK LIMITS to determine if
2998 		 * allow large xfer is approprate if not globally
2999 		 * disabled with st_allow_large_xfer.
3000 		 */
3001 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
3002 	} else {
3003 
3004 		/*
3005 		 * If we allow_large_xfer (ie >64k) and have not yet found out
3006 		 * the max block size supported by the drive,
3007 		 * find it by issueing a READ_BLKLIM command.
3008 		 * if READ_BLKLIM cmd fails, assume drive doesn't
3009 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
3010 		 */
3011 		un->un_allow_large_xfer = st_allow_large_xfer &&
3012 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
3013 	}
3014 	/*
3015 	 * if maxbsize is unknown, set the maximum block size.
3016 	 */
3017 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
3018 
3019 		/*
3020 		 * Get the Block limits of the tape drive.
3021 		 * if un->un_allow_large_xfer = 0 , then make sure
3022 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
3023 		 */
3024 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
3025 
3026 		err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3027 		if (err) {
3028 			/* Retry */
3029 			err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3030 		}
3031 		if (!err) {
3032 
3033 			/*
3034 			 * if cmd successful, use limit returned
3035 			 */
3036 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
3037 			    (un->un_rbl->max_mid << 8) +
3038 			    un->un_rbl->max_lo;
3039 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
3040 			    un->un_rbl->min_lo;
3041 			un->un_data_mod = 1 << un->un_rbl->granularity;
3042 			if ((un->un_maxbsize == 0) ||
3043 			    (un->un_allow_large_xfer == 0 &&
3044 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
3045 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3046 
3047 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
3048 				/*
3049 				 * Drive is not one that is configured, But the
3050 				 * READ BLOCK LIMITS tells us it can do large
3051 				 * xfers.
3052 				 */
3053 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
3054 					un->un_dp->options |=
3055 					    ST_NO_RECSIZE_LIMIT;
3056 				}
3057 				/*
3058 				 * If max and mimimum block limits are the
3059 				 * same this is a fixed block size device.
3060 				 */
3061 				if (un->un_maxbsize == un->un_minbsize) {
3062 					un->un_dp->options &= ~ST_VARIABLE;
3063 				}
3064 			}
3065 
3066 			if (un->un_minbsize == 0) {
3067 				un->un_minbsize = 1;
3068 			}
3069 
3070 		} else { /* error on read block limits */
3071 
3072 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3073 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
3074 			    " errno = %d un_rsvd_status = 0x%X\n",
3075 			    err, un->un_rsvd_status);
3076 
3077 			/*
3078 			 * since read block limits cmd failed,
3079 			 * do not allow large xfers.
3080 			 * use old values in st_minphys
3081 			 */
3082 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
3083 				rval = EACCES;
3084 			} else {
3085 				un->un_allow_large_xfer = 0;
3086 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3087 				    "!Disabling large transfers\n");
3088 
3089 				/*
3090 				 * we guess maxbsize and minbsize
3091 				 */
3092 				if (un->un_bsize) {
3093 					un->un_maxbsize = un->un_minbsize =
3094 					    un->un_bsize;
3095 				} else {
3096 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3097 					un->un_minbsize = 1;
3098 				}
3099 				/*
3100 				 * Data Mod must be set,
3101 				 * Even if read block limits fails.
3102 				 * Prevents Divide By Zero in st_rw().
3103 				 */
3104 				un->un_data_mod = 1;
3105 			}
3106 		}
3107 		if (un->un_rbl) {
3108 			kmem_free(un->un_rbl, RBLSIZE);
3109 			un->un_rbl = NULL;
3110 		}
3111 
3112 		if (rval) {
3113 			goto exit;
3114 		}
3115 	}
3116 
3117 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3118 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
3119 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
3120 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
3121 
3122 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
3123 
3124 	if (err != 0) {
3125 		if (err == EINTR) {
3126 			un->un_laststate = un->un_state;
3127 			un->un_state = ST_STATE_CLOSED;
3128 			rval = EINTR;
3129 			goto exit;
3130 		}
3131 		/*
3132 		 * Make sure the tape is ready
3133 		 */
3134 		un->un_pos.pmode = invalid;
3135 		if (un->un_status != KEY_UNIT_ATTENTION) {
3136 			/*
3137 			 * allow open no media.  Subsequent MTIOCSTATE
3138 			 * with media present will complete the open
3139 			 * logic.
3140 			 */
3141 			un->un_laststate = un->un_state;
3142 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
3143 				un->un_mediastate = MTIO_EJECTED;
3144 				un->un_state = ST_STATE_OFFLINE;
3145 				rval = 0;
3146 				goto exit;
3147 			} else {
3148 				un->un_state = ST_STATE_CLOSED;
3149 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3150 				    "st_tape_init EIO no media, not opened "
3151 				    "O_NONBLOCK|O_EXCL\n");
3152 				rval = EIO;
3153 				goto exit;
3154 			}
3155 		}
3156 	}
3157 
3158 	/*
3159 	 * On each open, initialize block size from drivetype struct,
3160 	 * as it could have been changed by MTSRSZ ioctl.
3161 	 * Now, ST_VARIABLE simply means drive is capable of variable
3162 	 * mode. All drives are assumed to support fixed records.
3163 	 * Hence, un_bsize tells what mode the drive is in.
3164 	 *	un_bsize	= 0	- variable record length
3165 	 *			= x	- fixed record length is x
3166 	 */
3167 	un->un_bsize = un->un_dp->bsize;
3168 
3169 	/*
3170 	 * If saved position is valid go there
3171 	 */
3172 	if (un->un_restore_pos) {
3173 		un->un_restore_pos = 0;
3174 		un->un_pos.fileno = un->un_save_fileno;
3175 		un->un_pos.blkno = un->un_save_blkno;
3176 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &un->un_pos);
3177 		if (rval != 0) {
3178 			if (rval != EACCES) {
3179 				rval = EIO;
3180 			}
3181 			un->un_laststate = un->un_state;
3182 			un->un_state = ST_STATE_CLOSED;
3183 			goto exit;
3184 		}
3185 	}
3186 
3187 	if (un->un_pos.pmode == invalid) {
3188 		rval = st_loadtape(un);
3189 		if (rval) {
3190 			if (rval != EACCES) {
3191 				rval = EIO;
3192 			}
3193 			un->un_laststate = un->un_state;
3194 			un->un_state = ST_STATE_CLOSED;
3195 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3196 			    "st_tape_init: %s can't open tape\n",
3197 			    rval == EACCES ? "EACCES" : "EIO");
3198 			goto exit;
3199 		}
3200 	}
3201 
3202 	/*
3203 	 * do a mode sense to pick up state of current write-protect,
3204 	 * Could cause reserve and fail due to conflict.
3205 	 */
3206 	if (un->un_unit_attention_flags) {
3207 		rval = st_modesense(un);
3208 		if (rval == EACCES) {
3209 			goto exit;
3210 		}
3211 	}
3212 
3213 	/*
3214 	 * If we are opening the tape for writing, check
3215 	 * to make sure that the tape can be written.
3216 	 */
3217 	if (un->un_oflags & FWRITE) {
3218 		err = 0;
3219 		if (un->un_mspl->wp) {
3220 			un->un_status = KEY_WRITE_PROTECT;
3221 			un->un_laststate = un->un_state;
3222 			un->un_state = ST_STATE_CLOSED;
3223 			rval = EACCES;
3224 			/*
3225 			 * STK sets the wp bit if volsafe tape is loaded.
3226 			 */
3227 			if ((un->un_dp->type == MT_ISSTK9840) &&
3228 			    (un->un_dp->options & ST_WORMABLE)) {
3229 				un->un_read_only = RDONLY;
3230 			} else {
3231 				goto exit;
3232 			}
3233 		} else {
3234 			un->un_read_only = RDWR;
3235 		}
3236 	} else {
3237 		un->un_read_only = RDONLY;
3238 	}
3239 
3240 	if (un->un_dp->options & ST_WORMABLE &&
3241 	    un->un_unit_attention_flags) {
3242 		un->un_read_only |= un->un_wormable(un);
3243 
3244 		if (((un->un_read_only == WORM) ||
3245 		    (un->un_read_only == RDWORM)) &&
3246 		    ((un->un_oflags & FWRITE) == FWRITE)) {
3247 			un->un_status = KEY_DATA_PROTECT;
3248 			rval = EACCES;
3249 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3250 			    "read_only = %d eof = %d oflag = %d\n",
3251 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3252 		}
3253 	}
3254 
3255 	/*
3256 	 * If we're opening the tape write-only, we need to
3257 	 * write 2 filemarks on the HP 1/2 inch drive, to
3258 	 * create a null file.
3259 	 */
3260 	if ((un->un_read_only == RDWR) ||
3261 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3262 		if (un->un_dp->options & ST_REEL) {
3263 			un->un_fmneeded = 2;
3264 		} else {
3265 			un->un_fmneeded = 1;
3266 		}
3267 	} else {
3268 		un->un_fmneeded = 0;
3269 	}
3270 
3271 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3272 	    "fmneeded = %x\n", un->un_fmneeded);
3273 
3274 	/*
3275 	 * Make sure the density can be selected correctly.
3276 	 * If WORM can only write at the append point which in most cases
3277 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3278 	 * to set and try densities if a BOP.
3279 	 */
3280 	if (st_determine_density(un,
3281 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3282 		un->un_status = KEY_ILLEGAL_REQUEST;
3283 		un->un_laststate = un->un_state;
3284 		un->un_state = ST_STATE_CLOSED;
3285 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3286 		    "st_tape_init: EIO can't determine density\n");
3287 		rval = EIO;
3288 		goto exit;
3289 	}
3290 
3291 	/*
3292 	 * Destroy the knowledge that we have 'determined'
3293 	 * density so that a later read at BOT comes along
3294 	 * does the right density determination.
3295 	 */
3296 
3297 	un->un_density_known = 0;
3298 
3299 
3300 	/*
3301 	 * Okay, the tape is loaded and either at BOT or somewhere past.
3302 	 * Mark the state such that any I/O or tape space operations
3303 	 * will get/set the right density, etc..
3304 	 */
3305 	un->un_laststate = un->un_state;
3306 	un->un_lastop = ST_OP_NIL;
3307 	un->un_mediastate = MTIO_INSERTED;
3308 	cv_broadcast(&un->un_state_cv);
3309 
3310 	/*
3311 	 *  Set test append flag if writing.
3312 	 *  First write must check that tape is positioned correctly.
3313 	 */
3314 	un->un_test_append = (un->un_oflags & FWRITE);
3315 
3316 	/*
3317 	 * if there are pending unit attention flags.
3318 	 * Check that the media has not changed.
3319 	 */
3320 	if (un->un_unit_attention_flags) {
3321 		rval = st_get_media_identification(un, st_uscsi_cmd);
3322 		if (rval != 0 && rval != EACCES) {
3323 			rval = EIO;
3324 		}
3325 		un->un_unit_attention_flags = 0;
3326 	}
3327 
3328 exit:
3329 	un->un_err_resid = 0;
3330 	un->un_last_resid = 0;
3331 	un->un_last_count = 0;
3332 
3333 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3334 	    "st_tape_init: return val = %x\n", rval);
3335 	return (rval);
3336 
3337 }
3338 
3339 
3340 
3341 /* ARGSUSED */
3342 static int
3343 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3344 {
3345 	int err = 0;
3346 	int count, last_state;
3347 	minor_t minor = getminor(dev);
3348 #ifdef	__x86
3349 	struct contig_mem *cp, *cp_temp;
3350 #endif
3351 
3352 	GET_SOFT_STATE(dev);
3353 
3354 	ST_ENTR(ST_DEVINFO, st_close);
3355 
3356 	/*
3357 	 * wait till all cmds in the pipeline have been completed
3358 	 */
3359 	mutex_enter(ST_MUTEX);
3360 
3361 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3362 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3363 
3364 	st_wait_for_io(un);
3365 
3366 	/* turn off persistent errors on close, as we want close to succeed */
3367 	st_turn_pe_off(un);
3368 
3369 	/*
3370 	 * set state to indicate that we are in process of closing
3371 	 */
3372 	last_state = un->un_laststate = un->un_state;
3373 	un->un_state = ST_STATE_CLOSING;
3374 
3375 	ST_POS(ST_DEVINFO, "st_close1:", &un->un_pos);
3376 
3377 	/*
3378 	 * BSD behavior:
3379 	 * a close always causes a silent span to the next file if we've hit
3380 	 * an EOF (but not yet read across it).
3381 	 */
3382 	if ((minor & MT_BSD) && (un->un_pos.eof == ST_EOF)) {
3383 		if (un->un_pos.pmode != invalid) {
3384 			un->un_pos.fileno++;
3385 			un->un_pos.blkno = 0;
3386 		}
3387 		un->un_pos.eof = ST_NO_EOF;
3388 	}
3389 
3390 	/*
3391 	 * SVR4 behavior for skipping to next file:
3392 	 *
3393 	 * If we have not seen a filemark, space to the next file
3394 	 *
3395 	 * If we have already seen the filemark we are physically in the next
3396 	 * file and we only increment the filenumber
3397 	 */
3398 	if (((minor & (MT_BSD | MT_NOREWIND)) == MT_NOREWIND) &&
3399 	    (flag & FREAD) &&		/* reading or at least asked to */
3400 	    (un->un_mediastate == MTIO_INSERTED) &&	/* tape loaded */
3401 	    (un->un_pos.pmode != invalid) &&		/* XXX position known */
3402 	    ((un->un_pos.blkno != 0) && 		/* inside a file */
3403 	    (un->un_lastop != ST_OP_WRITE) &&		/* Didn't just write */
3404 	    (un->un_lastop != ST_OP_WEOF))) {		/* or write filemarks */
3405 		switch (un->un_pos.eof) {
3406 		case ST_NO_EOF:
3407 			/*
3408 			 * if we were reading and did not read the complete file
3409 			 * skip to the next file, leaving the tape correctly
3410 			 * positioned to read the first record of the next file
3411 			 * Check first for REEL if we are at EOT by trying to
3412 			 * read a block
3413 			 */
3414 			if ((un->un_dp->options & ST_REEL) &&
3415 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3416 			    (un->un_pos.blkno == 0)) {
3417 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3418 					ST_DEBUG2(ST_DEVINFO, st_label,
3419 					    SCSI_DEBUG,
3420 					    "st_close : EIO can't space\n");
3421 					err = EIO;
3422 					goto error_out;
3423 				}
3424 				if (un->un_pos.eof >= ST_EOF_PENDING) {
3425 					un->un_pos.eof = ST_EOT_PENDING;
3426 					un->un_pos.fileno += 1;
3427 					un->un_pos.blkno   = 0;
3428 					break;
3429 				}
3430 			}
3431 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3432 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3433 				    "st_close: EIO can't space #2\n");
3434 				err = EIO;
3435 				goto error_out;
3436 			} else {
3437 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3438 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3439 				    un->un_pos.fileno, un->un_pos.blkno,
3440 				    un->un_pos.eof);
3441 				un->un_pos.eof = ST_NO_EOF;
3442 			}
3443 			break;
3444 
3445 		case ST_EOF_PENDING:
3446 		case ST_EOF:
3447 			un->un_pos.fileno += 1;
3448 			un->un_pos.lgclblkno += 1;
3449 			un->un_pos.blkno   = 0;
3450 			un->un_pos.eof = ST_NO_EOF;
3451 			break;
3452 
3453 		case ST_EOT:
3454 		case ST_EOT_PENDING:
3455 		case ST_EOM:
3456 			/* nothing to do */
3457 			break;
3458 		default:
3459 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
3460 			    "Undefined state 0x%x", un->un_pos.eof);
3461 
3462 		}
3463 	}
3464 
3465 
3466 	/*
3467 	 * For performance reasons (HP 88780), the driver should
3468 	 * postpone writing the second tape mark until just before a file
3469 	 * positioning ioctl is issued (e.g., rewind).	This means that
3470 	 * the user must not manually rewind the tape because the tape will
3471 	 * be missing the second tape mark which marks EOM.
3472 	 * However, this small performance improvement is not worth the risk.
3473 	 */
3474 
3475 	/*
3476 	 * We need to back up over the filemark we inadvertently popped
3477 	 * over doing a read in between the two filemarks that constitute
3478 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3479 	 * set while reading.
3480 	 *
3481 	 * If we happen to be at physical eot (ST_EOM) (writing case),
3482 	 * the writing of filemark(s) will clear the ST_EOM state, which
3483 	 * we don't want, so we save this state and restore it later.
3484 	 */
3485 
3486 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3487 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3488 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3489 
3490 	if (un->un_pos.eof == ST_EOT_PENDING) {
3491 		if (minor & MT_NOREWIND) {
3492 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3493 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3494 				    "st_close: EIO can't space #3\n");
3495 				err = EIO;
3496 				goto error_out;
3497 			} else {
3498 				un->un_pos.blkno = 0;
3499 				un->un_pos.eof = ST_EOT;
3500 			}
3501 		} else {
3502 			un->un_pos.eof = ST_NO_EOF;
3503 		}
3504 
3505 	/*
3506 	 * Do we need to write a file mark?
3507 	 *
3508 	 * only write filemarks if there are fmks to be written and
3509 	 *   - open for write (possibly read/write)
3510 	 *   - the last operation was a write
3511 	 * or:
3512 	 *   -	opened for wronly
3513 	 *   -	no data was written
3514 	 */
3515 	} else if ((un->un_pos.pmode != invalid) &&
3516 	    (un->un_fmneeded > 0) &&
3517 	    (((flag & FWRITE) &&
3518 	    ((un->un_lastop == ST_OP_WRITE)||(un->un_lastop == ST_OP_WEOF))) ||
3519 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3520 
3521 		/* save ST_EOM state */
3522 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3523 
3524 		/*
3525 		 * Note that we will write a filemark if we had opened
3526 		 * the tape write only and no data was written, thus
3527 		 * creating a null file.
3528 		 *
3529 		 * If the user already wrote one, we only have to write 1 more.
3530 		 * If they wrote two, we don't have to write any.
3531 		 */
3532 
3533 		count = un->un_fmneeded;
3534 		if (count > 0) {
3535 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, count, SYNC_CMD)) {
3536 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3537 				    "st_close : EIO can't wfm\n");
3538 				err = EIO;
3539 				goto error_out;
3540 			}
3541 			if ((un->un_dp->options & ST_REEL) &&
3542 			    (minor & MT_NOREWIND)) {
3543 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3544 					ST_DEBUG2(ST_DEVINFO, st_label,
3545 					    SCSI_DEBUG,
3546 					    "st_close : EIO space fmk(-1)\n");
3547 					err = EIO;
3548 					goto error_out;
3549 				}
3550 				un->un_pos.eof = ST_NO_EOF;
3551 				/* fix up block number */
3552 				un->un_pos.blkno = 0;
3553 			}
3554 		}
3555 
3556 		/*
3557 		 * If we aren't going to be rewinding, and we were at
3558 		 * physical eot, restore the state that indicates we
3559 		 * are at physical eot. Once you have reached physical
3560 		 * eot, and you close the tape, the only thing you can
3561 		 * do on the next open is to rewind. Access to trailer
3562 		 * records is only allowed without closing the device.
3563 		 */
3564 		if ((minor & MT_NOREWIND) == 0 && was_at_eom) {
3565 			un->un_pos.eof = ST_EOM;
3566 		}
3567 	}
3568 
3569 	/*
3570 	 * report soft errors if enabled and available, if we never accessed
3571 	 * the drive, don't get errors. This will prevent some DAT error
3572 	 * messages upon LOG SENSE.
3573 	 */
3574 	if (st_report_soft_errors_on_close &&
3575 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3576 	    (last_state != ST_STATE_OFFLINE)) {
3577 		if (st_report_soft_errors(dev, flag)) {
3578 			err = EIO;
3579 			goto error_out;
3580 		}
3581 	}
3582 
3583 
3584 	/*
3585 	 * Do we need to rewind? Can we rewind?
3586 	 */
3587 	if ((minor & MT_NOREWIND) == 0 &&
3588 	    un->un_pos.pmode != invalid && err == 0) {
3589 		/*
3590 		 * We'd like to rewind with the
3591 		 * 'immediate' bit set, but this
3592 		 * causes problems on some drives
3593 		 * where subsequent opens get a
3594 		 * 'NOT READY' error condition
3595 		 * back while the tape is rewinding,
3596 		 * which is impossible to distinguish
3597 		 * from the condition of 'no tape loaded'.
3598 		 *
3599 		 * Also, for some targets, if you disconnect
3600 		 * with the 'immediate' bit set, you don't
3601 		 * actually return right away, i.e., the
3602 		 * target ignores your request for immediate
3603 		 * return.
3604 		 *
3605 		 * Instead, we'll fire off an async rewind
3606 		 * command. We'll mark the device as closed,
3607 		 * and any subsequent open will stall on
3608 		 * the first TEST_UNIT_READY until the rewind
3609 		 * completes.
3610 		 */
3611 
3612 		/*
3613 		 * Used to be if reserve was not supported we'd send an
3614 		 * asynchronious rewind. Comments above may be slightly invalid
3615 		 * as the immediate bit was never set. Doing an immedate rewind
3616 		 * makes sense, I think fixes to not ready status might handle
3617 		 * the problems described above.
3618 		 */
3619 		if (un->un_sd->sd_inq->inq_ansi < 2) {
3620 			if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
3621 				err = EIO;
3622 			}
3623 		} else {
3624 			/* flush data for older drives per scsi spec. */
3625 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD)) {
3626 				err = EIO;
3627 			} else if (st_cmd(un, SCMD_REWIND, 1, ASYNC_CMD)) {
3628 				err = EIO;
3629 			}
3630 		}
3631 		/*
3632 		 * Setting positions invalid in case the rewind doesn't
3633 		 * happen. Drives don't like to rewind if resets happen
3634 		 * they will tend to move back to where the rewind was
3635 		 * issued if a reset or something happens so that if a
3636 		 * write happens the data doesn't get clobbered.
3637 		 *
3638 		 * Not a big deal if the position is invalid when the
3639 		 * open occures it will do a read position.
3640 		 */
3641 		un->un_pos.pmode = invalid;
3642 		un->un_running.pmode = invalid;
3643 
3644 		if (err == EIO) {
3645 			goto error_out;
3646 		}
3647 	}
3648 
3649 	/*
3650 	 * eject tape if necessary
3651 	 */
3652 	if (un->un_eject_tape_on_failure) {
3653 		un->un_eject_tape_on_failure = 0;
3654 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3655 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3656 			    "st_close : can't unload tape\n");
3657 			err = EIO;
3658 			goto error_out;
3659 		} else {
3660 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3661 			    "st_close : tape unloaded \n");
3662 			un->un_pos.eof = ST_NO_EOF;
3663 			un->un_mediastate = MTIO_EJECTED;
3664 		}
3665 	}
3666 	/*
3667 	 * Release the tape unit, if default reserve/release
3668 	 * behaviour.
3669 	 */
3670 	if ((un->un_rsvd_status &
3671 	    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
3672 		(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
3673 	}
3674 error_out:
3675 	/*
3676 	 * clear up state
3677 	 */
3678 	un->un_laststate = un->un_state;
3679 	un->un_state = ST_STATE_CLOSED;
3680 	un->un_lastop = ST_OP_NIL;
3681 	un->un_throttle = 1;	/* assume one request at time, for now */
3682 	un->un_retry_ct = 0;
3683 	un->un_errno = 0;
3684 	un->un_swr_token = (opaque_t)NULL;
3685 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3686 
3687 	/* Restore the options to the init time settings */
3688 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3689 		un->un_dp->options |= ST_READ_IGNORE_ILI;
3690 	} else {
3691 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3692 	}
3693 
3694 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3695 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3696 	} else {
3697 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3698 	}
3699 
3700 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3701 		un->un_dp->options |= ST_SHORT_FILEMARKS;
3702 	} else {
3703 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3704 	}
3705 
3706 	ASSERT(mutex_owned(ST_MUTEX));
3707 
3708 	/*
3709 	 * Signal anyone awaiting a close operation to complete.
3710 	 */
3711 	cv_signal(&un->un_clscv);
3712 
3713 	/*
3714 	 * any kind of error on closing causes all state to be tossed
3715 	 */
3716 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3717 		/*
3718 		 * note that st_intr has already set
3719 		 * un_pos.pmode to invalid.
3720 		 */
3721 		un->un_density_known = 0;
3722 	}
3723 
3724 #ifdef	__x86
3725 	/*
3726 	 * free any contiguous mem alloc'ed for big block I/O
3727 	 */
3728 	cp = un->un_contig_mem;
3729 	while (cp) {
3730 		if (cp->cm_addr) {
3731 			ddi_dma_mem_free(&cp->cm_acc_hdl);
3732 		}
3733 		cp_temp = cp;
3734 		cp = cp->cm_next;
3735 		kmem_free(cp_temp,
3736 		    sizeof (struct contig_mem) + biosize());
3737 	}
3738 	un->un_contig_mem_total_num = 0;
3739 	un->un_contig_mem_available_num = 0;
3740 	un->un_contig_mem = NULL;
3741 	un->un_max_contig_mem_len = 0;
3742 #endif
3743 
3744 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3745 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3746 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3747 
3748 	mutex_exit(ST_MUTEX);
3749 	return (err);
3750 }
3751 
3752 /*
3753  * These routines perform raw i/o operations.
3754  */
3755 
3756 /* ARGSUSED2 */
3757 static int
3758 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3759 {
3760 #ifdef STDEBUG
3761 	GET_SOFT_STATE(dev);
3762 	ST_ENTR(ST_DEVINFO, st_aread);
3763 #endif
3764 	return (st_arw(dev, aio, B_READ));
3765 }
3766 
3767 
3768 /* ARGSUSED2 */
3769 static int
3770 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3771 {
3772 #ifdef STDEBUG
3773 	GET_SOFT_STATE(dev);
3774 	ST_ENTR(ST_DEVINFO, st_awrite);
3775 #endif
3776 	return (st_arw(dev, aio, B_WRITE));
3777 }
3778 
3779 
3780 
3781 /* ARGSUSED */
3782 static int
3783 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3784 {
3785 #ifdef STDEBUG
3786 	GET_SOFT_STATE(dev);
3787 	ST_ENTR(ST_DEVINFO, st_read);
3788 #endif
3789 	return (st_rw(dev, uiop, B_READ));
3790 }
3791 
3792 /* ARGSUSED */
3793 static int
3794 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3795 {
3796 #ifdef STDEBUG
3797 	GET_SOFT_STATE(dev);
3798 	ST_ENTR(ST_DEVINFO, st_write);
3799 #endif
3800 	return (st_rw(dev, uiop, B_WRITE));
3801 }
3802 
3803 /*
3804  * Due to historical reasons, old limits are: For variable-length devices:
3805  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3806  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3807  * (let it through unmodified. For fixed-length record devices:
3808  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3809  *
3810  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3811  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3812  * command to the drive).
3813  *
3814  */
3815 static void
3816 st_minphys(struct buf *bp)
3817 {
3818 	struct scsi_tape *un;
3819 
3820 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3821 
3822 	ST_FUNC(ST_DEVINFO, st_minphys);
3823 
3824 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3825 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3826 	    bp->b_bcount);
3827 
3828 	if (un->un_allow_large_xfer) {
3829 
3830 		/*
3831 		 * check un_maxbsize for variable length devices only
3832 		 */
3833 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3834 			bp->b_bcount = un->un_maxbsize;
3835 		}
3836 		/*
3837 		 * can't go more that HBA maxdma limit in either fixed-length
3838 		 * or variable-length tape drives.
3839 		 */
3840 		if (bp->b_bcount > un->un_maxdma) {
3841 			bp->b_bcount = un->un_maxdma;
3842 		}
3843 	} else {
3844 
3845 		/*
3846 		 *  use old fixed limits
3847 		 */
3848 		if (un->un_bsize == 0) {
3849 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3850 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3851 			}
3852 		} else {
3853 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3854 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3855 			}
3856 		}
3857 	}
3858 
3859 	/*
3860 	 * For regular raw I/O and Fixed Block length devices, make sure
3861 	 * the adjusted block count is a whole multiple of the device
3862 	 * block size.
3863 	 */
3864 	if (bp != un->un_sbufp && un->un_bsize) {
3865 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3866 	}
3867 }
3868 
3869 static int
3870 st_rw(dev_t dev, struct uio *uio, int flag)
3871 {
3872 	int rval = 0;
3873 	long len;
3874 
3875 	GET_SOFT_STATE(dev);
3876 
3877 	ST_FUNC(ST_DEVINFO, st_rw);
3878 
3879 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3880 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3881 	    (flag == B_READ ? rd_str: wr_str));
3882 
3883 	/* get local copy of transfer length */
3884 	len = uio->uio_iov->iov_len;
3885 
3886 	mutex_enter(ST_MUTEX);
3887 
3888 	/*
3889 	 * Clear error entry stack
3890 	 */
3891 	st_empty_error_stack(un);
3892 
3893 	/*
3894 	 * If in fixed block size mode and requested read or write
3895 	 * is not an even multiple of that block size.
3896 	 */
3897 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3898 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3899 		    "%s: not modulo %d block size\n",
3900 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3901 		rval = EINVAL;
3902 	}
3903 
3904 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3905 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3906 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3907 		    "%s: not modulo %d device granularity\n",
3908 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3909 		rval = EINVAL;
3910 	}
3911 
3912 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
3913 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
3914 		rval = EFAULT;
3915 	}
3916 
3917 	if (rval != 0) {
3918 		un->un_errno = rval;
3919 		mutex_exit(ST_MUTEX);
3920 		return (rval);
3921 	}
3922 
3923 	/*
3924 	 * Reset this so it can be set if Berkeley and read over a filemark.
3925 	 */
3926 	un->un_silent_skip = 0;
3927 	mutex_exit(ST_MUTEX);
3928 
3929 	len = uio->uio_resid;
3930 
3931 	rval = physio(st_queued_strategy, (struct buf *)NULL,
3932 	    dev, flag, st_minphys, uio);
3933 	/*
3934 	 * if we have hit logical EOT during this xfer and there is not a
3935 	 * full residue, then set eof back  to ST_EOM to make sure that
3936 	 * the user will see at least one zero write
3937 	 * after this short write
3938 	 */
3939 	mutex_enter(ST_MUTEX);
3940 	if (un->un_pos.eof > ST_NO_EOF) {
3941 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3942 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3943 	}
3944 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3945 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3946 			un->un_pos.eof = ST_EOM;
3947 		} else if (uio->uio_resid == len) {
3948 			un->un_pos.eof = ST_NO_EOF;
3949 		}
3950 	}
3951 
3952 	if (un->un_silent_skip && uio->uio_resid != len) {
3953 		un->un_pos.eof = ST_EOF;
3954 		un->un_pos.blkno = un->un_save_blkno;
3955 		un->un_pos.fileno--;
3956 	}
3957 
3958 	un->un_errno = rval;
3959 
3960 	mutex_exit(ST_MUTEX);
3961 
3962 	return (rval);
3963 }
3964 
3965 static int
3966 st_arw(dev_t dev, struct aio_req *aio, int flag)
3967 {
3968 	struct uio *uio = aio->aio_uio;
3969 	int rval = 0;
3970 	long len;
3971 
3972 	GET_SOFT_STATE(dev);
3973 
3974 	ST_FUNC(ST_DEVINFO, st_arw);
3975 
3976 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3977 	    "st_arw(dev = 0x%lx, flag = %s)\n", dev,
3978 	    (flag == B_READ ? rd_str: wr_str));
3979 
3980 	/* get local copy of transfer length */
3981 	len = uio->uio_iov->iov_len;
3982 
3983 	mutex_enter(ST_MUTEX);
3984 
3985 	/*
3986 	 * If in fixed block size mode and requested read or write
3987 	 * is not an even multiple of that block size.
3988 	 */
3989 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3990 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3991 		    "%s: not modulo %d block size\n",
3992 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3993 		rval = EINVAL;
3994 	}
3995 
3996 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3997 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3998 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3999 		    "%s: not modulo %d device granularity\n",
4000 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
4001 		rval = EINVAL;
4002 	}
4003 
4004 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
4005 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
4006 		rval = EFAULT;
4007 	}
4008 
4009 	if (rval != 0) {
4010 		un->un_errno = rval;
4011 		mutex_exit(ST_MUTEX);
4012 		return (rval);
4013 	}
4014 
4015 	mutex_exit(ST_MUTEX);
4016 
4017 	len = uio->uio_resid;
4018 
4019 	rval =
4020 	    aphysio(st_queued_strategy, anocancel, dev, flag, st_minphys, aio);
4021 
4022 	/*
4023 	 * if we have hit logical EOT during this xfer and there is not a
4024 	 * full residue, then set eof back  to ST_EOM to make sure that
4025 	 * the user will see at least one zero write
4026 	 * after this short write
4027 	 *
4028 	 * we keep this here just in case the application is not using
4029 	 * persistent errors
4030 	 */
4031 	mutex_enter(ST_MUTEX);
4032 	if (un->un_pos.eof > ST_NO_EOF) {
4033 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4034 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
4035 	}
4036 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
4037 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
4038 			un->un_pos.eof = ST_EOM;
4039 		} else if (uio->uio_resid == len &&
4040 		    !(un->un_persistence && un->un_persist_errors)) {
4041 			un->un_pos.eof = ST_NO_EOF;
4042 		}
4043 	}
4044 	un->un_errno = rval;
4045 	mutex_exit(ST_MUTEX);
4046 
4047 	return (rval);
4048 }
4049 
4050 
4051 
4052 static int
4053 st_queued_strategy(buf_t *bp)
4054 {
4055 	struct scsi_tape *un;
4056 	char reading = bp->b_flags & B_READ;
4057 	int wasopening = 0;
4058 
4059 	/*
4060 	 * validate arguments
4061 	 */
4062 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4063 	if (un == NULL) {
4064 		bp->b_resid = bp->b_bcount;
4065 		bioerror(bp, ENXIO);
4066 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4067 		    "st_queued_strategy: ENXIO error exit\n");
4068 		biodone(bp);
4069 		return (0);
4070 	}
4071 
4072 	ST_ENTR(ST_DEVINFO, st_queued_strategy);
4073 
4074 	mutex_enter(ST_MUTEX);
4075 
4076 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4077 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4078 	}
4079 
4080 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4081 	    "st_queued_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4082 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4083 
4084 	/*
4085 	 * If persistent errors have been flagged, just nix this one. We wait
4086 	 * for any outstanding I/O's below, so we will be in order.
4087 	 */
4088 	if (un->un_persistence && un->un_persist_errors) {
4089 		goto exit;
4090 	}
4091 
4092 	/*
4093 	 * If last command was non queued, wait till it finishes.
4094 	 */
4095 	while (un->un_sbuf_busy) {
4096 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
4097 		/* woke up because of an error */
4098 		if (un->un_persistence && un->un_persist_errors) {
4099 			goto exit;
4100 		}
4101 	}
4102 
4103 	/*
4104 	 * s_buf and recovery commands shouldn't come here.
4105 	 */
4106 	ASSERT(bp != un->un_recov_buf);
4107 	ASSERT(bp != un->un_sbufp);
4108 
4109 	/*
4110 	 * If we haven't done/checked reservation on the tape unit
4111 	 * do it now.
4112 	 */
4113 	if ((un->un_rsvd_status &
4114 	    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
4115 		if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
4116 			if (st_reserve_release(un, ST_RESERVE, st_uscsi_cmd)) {
4117 				st_bioerror(bp, un->un_errno);
4118 				goto exit;
4119 			}
4120 		} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4121 			/*
4122 			 * Enter here to restore position for possible
4123 			 * resets when the device was closed and opened
4124 			 * in O_NDELAY mode subsequently
4125 			 */
4126 			un->un_state = ST_STATE_INITIALIZING;
4127 			(void) st_cmd(un, SCMD_TEST_UNIT_READY,
4128 			    0, SYNC_CMD);
4129 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4130 		}
4131 		un->un_rsvd_status |= ST_INIT_RESERVE;
4132 	}
4133 
4134 	/*
4135 	 * If we are offline, we have to initialize everything first.
4136 	 * This is to handle either when opened with O_NDELAY, or
4137 	 * we just got a new tape in the drive, after an offline.
4138 	 * We don't observe O_NDELAY past the open,
4139 	 * as it will not make sense for tapes.
4140 	 */
4141 	if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
4142 		/*
4143 		 * reset state to avoid recursion
4144 		 */
4145 		un->un_laststate = un->un_state;
4146 		un->un_state = ST_STATE_INITIALIZING;
4147 		if (st_tape_init(un)) {
4148 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4149 			    "stioctl : OFFLINE init failure ");
4150 			un->un_state = ST_STATE_OFFLINE;
4151 			un->un_pos.pmode = invalid;
4152 			goto b_done_err;
4153 		}
4154 		/* un_restore_pos make invalid */
4155 		un->un_state = ST_STATE_OPEN_PENDING_IO;
4156 		un->un_restore_pos = 0;
4157 	}
4158 	/*
4159 	 * Check for legal operations
4160 	 */
4161 	if (un->un_pos.pmode == invalid) {
4162 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4163 		    "strategy with un->un_pos.pmode invalid\n");
4164 		goto b_done_err;
4165 	}
4166 
4167 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4168 	    "st_queued_strategy(): regular io\n");
4169 
4170 	/*
4171 	 * Process this first. If we were reading, and we're pending
4172 	 * logical eot, that means we've bumped one file mark too far.
4173 	 */
4174 
4175 	/*
4176 	 * Recursion warning: st_cmd will route back through here.
4177 	 * Not anymore st_cmd will go through st_strategy()!
4178 	 */
4179 	if (un->un_pos.eof == ST_EOT_PENDING) {
4180 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4181 			un->un_pos.pmode = invalid;
4182 			un->un_density_known = 0;
4183 			goto b_done_err;
4184 		}
4185 		un->un_pos.blkno = 0; /* fix up block number.. */
4186 		un->un_pos.eof = ST_EOT;
4187 	}
4188 
4189 	/*
4190 	 * If we are in the process of opening, we may have to
4191 	 * determine/set the correct density. We also may have
4192 	 * to do a test_append (if QIC) to see whether we are
4193 	 * in a position to append to the end of the tape.
4194 	 *
4195 	 * If we're already at logical eot, we transition
4196 	 * to ST_NO_EOF. If we're at physical eot, we punt
4197 	 * to the switch statement below to handle.
4198 	 */
4199 	if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
4200 	    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
4201 
4202 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4203 			if (st_determine_density(un, (int)reading)) {
4204 				goto b_done_err;
4205 			}
4206 		}
4207 
4208 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4209 		    "pending_io@fileno %d rw %d qic %d eof %d\n",
4210 		    un->un_pos.fileno, (int)reading,
4211 		    (un->un_dp->options & ST_QIC) ? 1 : 0,
4212 		    un->un_pos.eof);
4213 
4214 		if (!reading && un->un_pos.eof != ST_EOM) {
4215 			if (un->un_pos.eof == ST_EOT) {
4216 				un->un_pos.eof = ST_NO_EOF;
4217 			} else if (un->un_pos.pmode != invalid &&
4218 			    (un->un_dp->options & ST_QIC)) {
4219 				/*
4220 				 * st_test_append() will do it all
4221 				 */
4222 				st_test_append(bp);
4223 				mutex_exit(ST_MUTEX);
4224 				return (0);
4225 			}
4226 		}
4227 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4228 			wasopening = 1;
4229 		}
4230 		un->un_laststate = un->un_state;
4231 		un->un_state = ST_STATE_OPEN;
4232 	}
4233 
4234 
4235 	/*
4236 	 * Process rest of END OF FILE and END OF TAPE conditions
4237 	 */
4238 
4239 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4240 	    "eof=%x, wasopening=%x\n",
4241 	    un->un_pos.eof, wasopening);
4242 
4243 	switch (un->un_pos.eof) {
4244 	case ST_EOM:
4245 		/*
4246 		 * This allows writes to proceed past physical
4247 		 * eot. We'll *really* be in trouble if the
4248 		 * user continues blindly writing data too
4249 		 * much past this point (unwind the tape).
4250 		 * Physical eot really means 'early warning
4251 		 * eot' in this context.
4252 		 *
4253 		 * Every other write from now on will succeed
4254 		 * (if sufficient  tape left).
4255 		 * This write will return with resid == count
4256 		 * but the next one should be successful
4257 		 *
4258 		 * Note that we only transition to logical EOT
4259 		 * if the last state wasn't the OPENING state.
4260 		 * We explicitly prohibit running up to physical
4261 		 * eot, closing the device, and then re-opening
4262 		 * to proceed. Trailer records may only be gotten
4263 		 * at by keeping the tape open after hitting eot.
4264 		 *
4265 		 * Also note that ST_EOM cannot be set by reading-
4266 		 * this can only be set during writing. Reading
4267 		 * up to the end of the tape gets a blank check
4268 		 * or a double-filemark indication (ST_EOT_PENDING),
4269 		 * and we prohibit reading after that point.
4270 		 *
4271 		 */
4272 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
4273 		if (wasopening == 0) {
4274 			/*
4275 			 * this allows st_rw() to reset it back to
4276 			 * will see a zero write
4277 			 */
4278 			un->un_pos.eof = ST_WRITE_AFTER_EOM;
4279 		}
4280 		un->un_status = SUN_KEY_EOT;
4281 		goto b_done;
4282 
4283 	case ST_WRITE_AFTER_EOM:
4284 	case ST_EOT:
4285 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
4286 		un->un_status = SUN_KEY_EOT;
4287 		if (SVR4_BEHAVIOR && reading) {
4288 			goto b_done_err;
4289 		}
4290 
4291 		if (reading) {
4292 			goto b_done;
4293 		}
4294 		un->un_pos.eof = ST_NO_EOF;
4295 		break;
4296 
4297 	case ST_EOF_PENDING:
4298 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4299 		    "EOF PENDING\n");
4300 		un->un_status = SUN_KEY_EOF;
4301 		if (SVR4_BEHAVIOR) {
4302 			un->un_pos.eof = ST_EOF;
4303 			goto b_done;
4304 		}
4305 		/* FALLTHROUGH */
4306 	case ST_EOF:
4307 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
4308 		un->un_status = SUN_KEY_EOF;
4309 		if (SVR4_BEHAVIOR) {
4310 			goto b_done_err;
4311 		}
4312 
4313 		if (BSD_BEHAVIOR) {
4314 			un->un_pos.eof = ST_NO_EOF;
4315 			un->un_pos.fileno += 1;
4316 			un->un_pos.blkno   = 0;
4317 		}
4318 
4319 		if (reading) {
4320 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4321 			    "now file %d (read)\n",
4322 			    un->un_pos.fileno);
4323 			goto b_done;
4324 		}
4325 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4326 		    "now file %d (write)\n", un->un_pos.fileno);
4327 		break;
4328 	default:
4329 		un->un_status = 0;
4330 		break;
4331 	}
4332 
4333 	bp->b_flags &= ~(B_DONE);
4334 	st_bioerror(bp, 0);
4335 	bp->av_forw = NULL;
4336 	bp->b_resid = 0;
4337 	SET_BP_PKT(bp, 0);
4338 
4339 
4340 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4341 	    "st_queued_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4342 	    " pkt=0x%p\n",
4343 	    (void *)bp->b_forw, bp->b_bcount,
4344 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4345 
4346 #ifdef	__x86
4347 	/*
4348 	 * We will replace bp with a new bp that can do big blk xfer
4349 	 * if the requested xfer size is bigger than un->un_maxdma_arch
4350 	 *
4351 	 * Also, we need to make sure that we're handling real I/O
4352 	 * by checking group 0/1 SCSI I/O commands, if needed
4353 	 */
4354 	if (bp->b_bcount > un->un_maxdma_arch &&
4355 	    ((uchar_t)(uintptr_t)bp->b_forw == SCMD_READ ||
4356 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G4 ||
4357 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE ||
4358 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G4)) {
4359 		mutex_exit(ST_MUTEX);
4360 		bp = st_get_bigblk_bp(bp);
4361 		mutex_enter(ST_MUTEX);
4362 	}
4363 #endif
4364 
4365 	/* put on wait queue */
4366 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4367 	    "st_queued_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4368 	    (void *)un->un_quef, (void *)bp);
4369 
4370 	st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quel, bp);
4371 
4372 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4373 
4374 	st_start(un);
4375 
4376 	mutex_exit(ST_MUTEX);
4377 	return (0);
4378 
4379 b_done_err:
4380 	st_bioerror(bp, EIO);
4381 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4382 	    "st_queued_strategy : EIO b_done_err\n");
4383 
4384 b_done:
4385 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4386 	    "st_queued_strategy: b_done\n");
4387 
4388 exit:
4389 	/*
4390 	 * make sure no commands are outstanding or waiting before closing,
4391 	 * so we can guarantee order
4392 	 */
4393 	st_wait_for_io(un);
4394 	un->un_err_resid = bp->b_resid = bp->b_bcount;
4395 
4396 	/* override errno here, if persistent errors were flagged */
4397 	if (un->un_persistence && un->un_persist_errors)
4398 		bioerror(bp, un->un_errno);
4399 
4400 	mutex_exit(ST_MUTEX);
4401 
4402 	biodone(bp);
4403 	ASSERT(mutex_owned(ST_MUTEX) == 0);
4404 	return (0);
4405 }
4406 
4407 
4408 static int
4409 st_strategy(struct buf *bp)
4410 {
4411 	struct scsi_tape *un;
4412 
4413 	/*
4414 	 * validate arguments
4415 	 */
4416 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4417 	if (un == NULL) {
4418 		bp->b_resid = bp->b_bcount;
4419 		bioerror(bp, ENXIO);
4420 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4421 		    "st_strategy: ENXIO error exit\n");
4422 
4423 		biodone(bp);
4424 		return (0);
4425 
4426 	}
4427 
4428 	ST_ENTR(ST_DEVINFO, st_strategy);
4429 
4430 	mutex_enter(ST_MUTEX);
4431 
4432 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4433 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4434 	}
4435 
4436 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4437 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4438 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4439 
4440 	ASSERT((bp == un->un_recov_buf) || (bp == un->un_sbufp));
4441 
4442 	bp->b_flags &= ~(B_DONE);
4443 	st_bioerror(bp, 0);
4444 	bp->av_forw = NULL;
4445 	bp->b_resid = 0;
4446 	SET_BP_PKT(bp, 0);
4447 
4448 
4449 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4450 	    "st_strategy: cmd=0x%x  count=%ld  resid=%ld flags=0x%x"
4451 	    " pkt=0x%p\n",
4452 	    (unsigned char)(uintptr_t)bp->b_forw, bp->b_bcount,
4453 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4454 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4455 
4456 	st_start(un);
4457 
4458 	mutex_exit(ST_MUTEX);
4459 	return (0);
4460 }
4461 
4462 /*
4463  * this routine spaces forward over filemarks
4464  */
4465 static int
4466 st_space_fmks(struct scsi_tape *un, int64_t count)
4467 {
4468 	int rval = 0;
4469 
4470 	ST_FUNC(ST_DEVINFO, st_space_fmks);
4471 
4472 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4473 	    "st_space_fmks(dev = 0x%lx, count = %"PRIx64")\n",
4474 	    un->un_dev, count);
4475 
4476 	ASSERT(mutex_owned(ST_MUTEX));
4477 
4478 	/*
4479 	 * the risk with doing only one space operation is that we
4480 	 * may accidentily jump in old data
4481 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4482 	 * because the 8200 does not append a marker; in order not to
4483 	 * sacrifice the fast file skip, we do a slow skip if the low
4484 	 * density device has been opened
4485 	 */
4486 
4487 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4488 	    !((un->un_dp->type == ST_TYPE_EXB8500 &&
4489 	    MT_DENSITY(un->un_dev) == 0))) {
4490 		if (st_cmd(un, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4491 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4492 			    "space_fmks : EIO can't do space cmd #1\n");
4493 			rval = EIO;
4494 		}
4495 	} else {
4496 		while (count > 0) {
4497 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4498 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4499 				    "space_fmks : EIO can't do space cmd #2\n");
4500 				rval = EIO;
4501 				break;
4502 			}
4503 			count -= 1;
4504 			/*
4505 			 * read a block to see if we have reached
4506 			 * end of medium (double filemark for reel or
4507 			 * medium error for others)
4508 			 */
4509 			if (count > 0) {
4510 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
4511 					ST_DEBUG2(ST_DEVINFO, st_label,
4512 					    SCSI_DEBUG,
4513 					    "space_fmks : EIO can't do "
4514 					    "space cmd #3\n");
4515 					rval = EIO;
4516 					break;
4517 				}
4518 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4519 				    (un->un_dp->options & ST_REEL)) {
4520 					un->un_status = SUN_KEY_EOT;
4521 					ST_DEBUG2(ST_DEVINFO, st_label,
4522 					    SCSI_DEBUG,
4523 					    "space_fmks : EIO ST_REEL\n");
4524 					rval = EIO;
4525 					break;
4526 				} else if (IN_EOF(un->un_pos)) {
4527 					un->un_pos.eof = ST_NO_EOF;
4528 					un->un_pos.fileno++;
4529 					un->un_pos.blkno = 0;
4530 					count--;
4531 				} else if (un->un_pos.eof > ST_EOF) {
4532 					ST_DEBUG2(ST_DEVINFO, st_label,
4533 					    SCSI_DEBUG,
4534 					    "space_fmks, EIO > ST_EOF\n");
4535 					rval = EIO;
4536 					break;
4537 				}
4538 
4539 			}
4540 		}
4541 		un->un_err_resid = count;
4542 		COPY_POS(&un->un_pos, &un->un_err_pos);
4543 	}
4544 	ASSERT(mutex_owned(ST_MUTEX));
4545 	return (rval);
4546 }
4547 
4548 /*
4549  * this routine spaces to EOD
4550  *
4551  * it keeps track of the current filenumber and returns the filenumber after
4552  * the last successful space operation, we keep the number high because as
4553  * tapes are getting larger, the possibility of more and more files exist,
4554  * 0x100000 (1 Meg of files) probably will never have to be changed any time
4555  * soon
4556  */
4557 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4558 
4559 static int
4560 st_find_eod(struct scsi_tape *un)
4561 {
4562 	tapepos_t savepos;
4563 	int64_t sp_type;
4564 	int result;
4565 
4566 	if (un == NULL) {
4567 		return (-1);
4568 	}
4569 
4570 	ST_FUNC(ST_DEVINFO, st_find_eod);
4571 
4572 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4573 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", un->un_dev,
4574 	    un->un_pos.fileno);
4575 
4576 	ASSERT(mutex_owned(ST_MUTEX));
4577 
4578 	COPY_POS(&savepos, &un->un_pos);
4579 
4580 	/*
4581 	 * see if the drive is smart enough to do the skips in
4582 	 * one operation; 1/2" use two filemarks
4583 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4584 	 * because the 8200 does not append a marker; in order not to
4585 	 * sacrifice the fast file skip, we do a slow skip if the low
4586 	 * density device has been opened
4587 	 */
4588 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4589 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4590 		    (MT_DENSITY(un->un_dev) == 0)) {
4591 			sp_type = Fmk(1);
4592 		} else if (un->un_pos.pmode == logical) {
4593 			sp_type = SPACE(SP_EOD, 0);
4594 		} else {
4595 			sp_type = Fmk(MAX_SKIP);
4596 		}
4597 	} else {
4598 		sp_type = Fmk(1);
4599 	}
4600 
4601 	for (;;) {
4602 		result = st_cmd(un, SCMD_SPACE, sp_type, SYNC_CMD);
4603 
4604 		if (result == 0) {
4605 			COPY_POS(&savepos, &un->un_pos);
4606 		}
4607 
4608 		if (sp_type == SPACE(SP_EOD, 0)) {
4609 			if (result != 0) {
4610 				sp_type = Fmk(MAX_SKIP);
4611 				continue;
4612 			}
4613 
4614 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4615 			    "st_find_eod: 0x%"PRIx64"\n",
4616 			    savepos.lgclblkno);
4617 			/*
4618 			 * What we return will become the current file position.
4619 			 * After completing the space command with the position
4620 			 * mode that is not invalid a read position command will
4621 			 * be automaticly issued. If the drive support the long
4622 			 * read position format a valid file position can be
4623 			 * returned.
4624 			 */
4625 			return (un->un_pos.fileno);
4626 		}
4627 
4628 		if (result != 0) {
4629 			break;
4630 		}
4631 
4632 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4633 		    "count=%"PRIx64", eof=%x, status=%x\n",
4634 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4635 
4636 		/*
4637 		 * If we're not EOM smart,  space a record
4638 		 * to see whether we're now in the slot between
4639 		 * the two sequential filemarks that logical
4640 		 * EOM consists of (REEL) or hit nowhere land
4641 		 * (8mm).
4642 		 */
4643 		if (sp_type == Fmk(1)) {
4644 			/*
4645 			 * no fast skipping, check a record
4646 			 */
4647 			if (st_cmd(un, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4648 				break;
4649 			}
4650 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4651 			    (un->un_dp->options & ST_REEL)) {
4652 				un->un_status = KEY_BLANK_CHECK;
4653 				un->un_pos.fileno++;
4654 				un->un_pos.blkno = 0;
4655 				break;
4656 			}
4657 			if (IN_EOF(un->un_pos)) {
4658 				un->un_pos.eof = ST_NO_EOF;
4659 				un->un_pos.fileno++;
4660 				un->un_pos.blkno = 0;
4661 			}
4662 			if (un->un_pos.eof > ST_EOF) {
4663 				break;
4664 			}
4665 		} else {
4666 			if (un->un_pos.eof > ST_EOF) {
4667 				break;
4668 			}
4669 		}
4670 	}
4671 
4672 	if (un->un_dp->options & ST_KNOWS_EOD) {
4673 		COPY_POS(&savepos, &un->un_pos);
4674 	}
4675 
4676 	ASSERT(mutex_owned(ST_MUTEX));
4677 
4678 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4679 	    "st_find_eod: %x\n", savepos.fileno);
4680 	return (savepos.fileno);
4681 }
4682 
4683 
4684 /*
4685  * this routine is frequently used in ioctls below;
4686  * it determines whether we know the density and if not will
4687  * determine it
4688  * if we have written the tape before, one or more filemarks are written
4689  *
4690  * depending on the stepflag, the head is repositioned to where it was before
4691  * the filemarks were written in order not to confuse step counts
4692  */
4693 #define	STEPBACK    0
4694 #define	NO_STEPBACK 1
4695 
4696 static int
4697 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4698 {
4699 
4700 	GET_SOFT_STATE(dev);
4701 
4702 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4703 
4704 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4705 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4706 	    "\n", dev, wfm, mode, stepflag);
4707 
4708 	ASSERT(mutex_owned(ST_MUTEX));
4709 
4710 	/*
4711 	 * If we don't yet know the density of the tape we have inserted,
4712 	 * we have to either unconditionally set it (if we're 'writing'),
4713 	 * or we have to determine it. As side effects, check for any
4714 	 * write-protect errors, and for the need to put out any file-marks
4715 	 * before positioning a tape.
4716 	 *
4717 	 * If we are going to be spacing forward, and we haven't determined
4718 	 * the tape density yet, we have to do so now...
4719 	 */
4720 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4721 		if (st_determine_density(un, mode)) {
4722 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4723 			    "check_density_or_wfm : EIO can't determine "
4724 			    "density\n");
4725 			un->un_errno = EIO;
4726 			return (EIO);
4727 		}
4728 		/*
4729 		 * Presumably we are at BOT. If we attempt to write, it will
4730 		 * either work okay, or bomb. We don't do a st_test_append
4731 		 * unless we're past BOT.
4732 		 */
4733 		un->un_laststate = un->un_state;
4734 		un->un_state = ST_STATE_OPEN;
4735 
4736 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4737 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4738 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4739 
4740 		tapepos_t spos;
4741 
4742 		COPY_POS(&spos, &un->un_pos);
4743 
4744 		/*
4745 		 * We need to write one or two filemarks.
4746 		 * In the case of the HP, we need to
4747 		 * position the head between the two
4748 		 * marks.
4749 		 */
4750 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4751 			wfm = un->un_fmneeded;
4752 			un->un_fmneeded = 0;
4753 		}
4754 
4755 		if (st_write_fm(dev, wfm)) {
4756 			un->un_pos.pmode = invalid;
4757 			un->un_density_known = 0;
4758 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4759 			    "check_density_or_wfm : EIO can't write fm\n");
4760 			un->un_errno = EIO;
4761 			return (EIO);
4762 		}
4763 
4764 		if (stepflag == STEPBACK) {
4765 			if (st_cmd(un, SCMD_SPACE, Fmk(-wfm), SYNC_CMD)) {
4766 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4767 				    "check_density_or_wfm : EIO can't space "
4768 				    "(-wfm)\n");
4769 				un->un_errno = EIO;
4770 				return (EIO);
4771 			}
4772 			COPY_POS(&un->un_pos, &spos);
4773 		}
4774 	}
4775 
4776 	/*
4777 	 * Whatever we do at this point clears the state of the eof flag.
4778 	 */
4779 
4780 	un->un_pos.eof = ST_NO_EOF;
4781 
4782 	/*
4783 	 * If writing, let's check that we're positioned correctly
4784 	 * at the end of tape before issuing the next write.
4785 	 */
4786 	if (un->un_read_only == RDWR) {
4787 		un->un_test_append = 1;
4788 	}
4789 
4790 	ASSERT(mutex_owned(ST_MUTEX));
4791 	return (0);
4792 }
4793 
4794 
4795 /*
4796  * Wait for all outstaning I/O's to complete
4797  *
4798  * we wait on both ncmds and the wait queue for times when we are flushing
4799  * after persistent errors are flagged, which is when ncmds can be 0, and the
4800  * queue can still have I/O's.  This way we preserve order of biodone's.
4801  */
4802 static void
4803 st_wait_for_io(struct scsi_tape *un)
4804 {
4805 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4806 	ASSERT(mutex_owned(ST_MUTEX));
4807 	while ((un->un_ncmds) || (un->un_quef) || (un->un_runqf)) {
4808 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4809 	}
4810 }
4811 
4812 /*
4813  * This routine implements the ioctl calls.  It is called
4814  * from the device switch at normal priority.
4815  */
4816 /*ARGSUSED*/
4817 static int
4818 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4819     int *rval_p)
4820 {
4821 	int tmp, rval = 0;
4822 
4823 	GET_SOFT_STATE(dev);
4824 
4825 	ST_ENTR(ST_DEVINFO, st_ioctl);
4826 
4827 	mutex_enter(ST_MUTEX);
4828 
4829 	ASSERT(un->un_recov_buf_busy == 0);
4830 
4831 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4832 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4833 	    "pe_flag = %d\n",
4834 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4835 	    un->un_persistence && un->un_persist_errors);
4836 
4837 	/*
4838 	 * We don't want to block on these, so let them through
4839 	 * and we don't care about setting driver states here.
4840 	 */
4841 	if ((cmd == MTIOCGETDRIVETYPE) ||
4842 	    (cmd == MTIOCGUARANTEEDORDER) ||
4843 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4844 		goto check_commands;
4845 	}
4846 
4847 	/*
4848 	 * We clear error entry stack except command
4849 	 * MTIOCGETERROR and MTIOCGET
4850 	 */
4851 	if ((cmd != MTIOCGETERROR) &&
4852 	    (cmd != MTIOCGET)) {
4853 		st_empty_error_stack(un);
4854 	}
4855 
4856 	/*
4857 	 * wait for all outstanding commands to complete, or be dequeued.
4858 	 * And because ioctl's are synchronous commands, any return value
4859 	 * after this,  will be in order
4860 	 */
4861 	st_wait_for_io(un);
4862 
4863 	/*
4864 	 * allow only a through clear errors and persistent status, and
4865 	 * status
4866 	 */
4867 	if (un->un_persistence && un->un_persist_errors) {
4868 		if ((cmd == MTIOCLRERR) ||
4869 		    (cmd == MTIOCPERSISTENT) ||
4870 		    (cmd == MTIOCGET)) {
4871 			goto check_commands;
4872 		} else {
4873 			rval = un->un_errno;
4874 			goto exit;
4875 		}
4876 	}
4877 
4878 	ASSERT(un->un_throttle != 0);
4879 	un->un_throttle = 1;	/* > 1 will never happen here */
4880 	un->un_errno = 0;	/* start clean from here */
4881 
4882 	/*
4883 	 * first and foremost, handle any ST_EOT_PENDING cases.
4884 	 * That is, if a logical eot is pending notice, notice it.
4885 	 */
4886 	if (un->un_pos.eof == ST_EOT_PENDING) {
4887 		int resid = un->un_err_resid;
4888 		uchar_t status = un->un_status;
4889 		uchar_t lastop = un->un_lastop;
4890 
4891 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4892 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4893 			    "stioctl : EIO can't space fmk(-1)\n");
4894 			rval = EIO;
4895 			goto exit;
4896 		}
4897 		un->un_lastop = lastop; /* restore last operation */
4898 		if (status == SUN_KEY_EOF) {
4899 			un->un_status = SUN_KEY_EOT;
4900 		} else {
4901 			un->un_status = status;
4902 		}
4903 		un->un_err_resid  = resid;
4904 		/* fix up block number */
4905 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4906 		/* now we're at logical eot */
4907 		un->un_pos.eof = ST_EOT;
4908 	}
4909 
4910 	/*
4911 	 * now, handle the rest of the situations
4912 	 */
4913 check_commands:
4914 	switch (cmd) {
4915 	case MTIOCGET:
4916 	{
4917 #ifdef _MULTI_DATAMODEL
4918 		/*
4919 		 * For use when a 32 bit app makes a call into a
4920 		 * 64 bit ioctl
4921 		 */
4922 		struct mtget32		mtg_local32;
4923 		struct mtget32 		*mtget_32 = &mtg_local32;
4924 #endif /* _MULTI_DATAMODEL */
4925 
4926 			/* Get tape status */
4927 		struct mtget mtg_local;
4928 		struct mtget *mtget = &mtg_local;
4929 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4930 		    "st_ioctl: MTIOCGET\n");
4931 
4932 		bzero((caddr_t)mtget, sizeof (struct mtget));
4933 		mtget->mt_erreg = un->un_status;
4934 		mtget->mt_resid = un->un_err_resid;
4935 		mtget->mt_dsreg = un->un_retry_ct;
4936 		if (un->un_err_pos.pmode == legacy) {
4937 			mtget->mt_fileno = un->un_err_pos.fileno;
4938 		} else {
4939 			mtget->mt_fileno = -1;
4940 		}
4941 		/*
4942 		 * If the value is positive fine.
4943 		 * If its negative we need to return a value based on the
4944 		 * old way if counting backwards from INF (1,000,000,000).
4945 		 */
4946 		if (un->un_err_pos.blkno >= 0) {
4947 			mtget->mt_blkno = un->un_err_pos.blkno;
4948 		} else {
4949 			mtget->mt_blkno = INF + 1 - (-un->un_err_pos.blkno);
4950 		}
4951 		mtget->mt_type = un->un_dp->type;
4952 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
4953 		if (un->un_read_pos_type != NO_POS) {
4954 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
4955 		}
4956 		if (un->un_dp->options & ST_REEL) {
4957 			mtget->mt_flags |= MTF_REEL;
4958 			mtget->mt_bf = 20;
4959 		} else {		/* 1/4" cartridges */
4960 			switch (mtget->mt_type) {
4961 			/* Emulex cartridge tape */
4962 			case MT_ISMT02:
4963 				mtget->mt_bf = 40;
4964 				break;
4965 			default:
4966 				mtget->mt_bf = 126;
4967 				break;
4968 			}
4969 		}
4970 
4971 		/*
4972 		 * If large transfers are allowed and drive options
4973 		 * has no record size limit set. Calculate blocking
4974 		 * factor from the lesser of maxbsize and maxdma.
4975 		 */
4976 		if ((un->un_allow_large_xfer) &&
4977 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
4978 			mtget->mt_bf = min(un->un_maxbsize,
4979 			    un->un_maxdma) / SECSIZE;
4980 		}
4981 
4982 		if (un->un_read_only == WORM ||
4983 		    un->un_read_only == RDWORM) {
4984 			mtget->mt_flags |= MTF_WORM_MEDIA;
4985 		}
4986 
4987 		/*
4988 		 * In persistent error mode sending a non-queued can hang
4989 		 * because this ioctl gets to be run without turning off
4990 		 * persistense. Fake the answer based on previous info.
4991 		 */
4992 		if (un->un_persistence) {
4993 			rval = 0;
4994 		} else {
4995 			rval = st_check_clean_bit(un);
4996 		}
4997 		if (rval == 0) {
4998 			/*
4999 			 * If zero is returned or in persistent mode,
5000 			 * use the old data.
5001 			 */
5002 			if ((un->un_HeadClean & (TAPE_ALERT_SUPPORTED |
5003 			    TAPE_SEQUENTIAL_SUPPORTED|TAPE_ALERT_NOT_SUPPORTED))
5004 			    != TAPE_ALERT_NOT_SUPPORTED) {
5005 				mtget->mt_flags |= MTF_TAPE_CLN_SUPPORTED;
5006 			}
5007 			if (un->un_HeadClean & (TAPE_PREVIOUSLY_DIRTY |
5008 			    TAPE_ALERT_STILL_DIRTY)) {
5009 				mtget->mt_flags |= MTF_TAPE_HEAD_DIRTY;
5010 			}
5011 		} else {
5012 			mtget->mt_flags |= (ushort_t)rval;
5013 			rval = 0;
5014 		}
5015 
5016 		un->un_status = 0;		/* Reset status */
5017 		un->un_err_resid = 0;
5018 		tmp = sizeof (struct mtget);
5019 
5020 #ifdef _MULTI_DATAMODEL
5021 
5022 		switch (ddi_model_convert_from(flag & FMODELS)) {
5023 		case DDI_MODEL_ILP32:
5024 			/*
5025 			 * Convert 64 bit back to 32 bit before doing
5026 			 * copyout. This is what the ILP32 app expects.
5027 			 */
5028 			mtget_32->mt_erreg = 	mtget->mt_erreg;
5029 			mtget_32->mt_resid = 	mtget->mt_resid;
5030 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
5031 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
5032 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
5033 			mtget_32->mt_type =  	mtget->mt_type;
5034 			mtget_32->mt_flags = 	mtget->mt_flags;
5035 			mtget_32->mt_bf = 	mtget->mt_bf;
5036 
5037 			if (ddi_copyout(mtget_32, (void *)arg,
5038 			    sizeof (struct mtget32), flag)) {
5039 				rval = EFAULT;
5040 			}
5041 			break;
5042 
5043 		case DDI_MODEL_NONE:
5044 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5045 				rval = EFAULT;
5046 			}
5047 			break;
5048 		}
5049 #else /* ! _MULTI_DATAMODE */
5050 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5051 			rval = EFAULT;
5052 		}
5053 #endif /* _MULTI_DATAMODE */
5054 
5055 		break;
5056 	}
5057 	case MTIOCGETERROR:
5058 			/*
5059 			 * get error entry from error stack
5060 			 */
5061 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5062 			    "st_ioctl: MTIOCGETERROR\n");
5063 
5064 			rval = st_get_error_entry(un, arg, flag);
5065 
5066 			break;
5067 
5068 	case MTIOCSTATE:
5069 		{
5070 			/*
5071 			 * return when media presence matches state
5072 			 */
5073 			enum mtio_state state;
5074 
5075 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5076 			    "st_ioctl: MTIOCSTATE\n");
5077 
5078 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
5079 				rval = EFAULT;
5080 
5081 			mutex_exit(ST_MUTEX);
5082 
5083 			rval = st_check_media(dev, state);
5084 
5085 			mutex_enter(ST_MUTEX);
5086 
5087 			if (rval != 0) {
5088 				break;
5089 			}
5090 
5091 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
5092 			    sizeof (int), flag))
5093 				rval = EFAULT;
5094 			break;
5095 
5096 		}
5097 
5098 	case MTIOCGETDRIVETYPE:
5099 		{
5100 #ifdef _MULTI_DATAMODEL
5101 		/*
5102 		 * For use when a 32 bit app makes a call into a
5103 		 * 64 bit ioctl
5104 		 */
5105 		struct mtdrivetype_request32	mtdtrq32;
5106 #endif /* _MULTI_DATAMODEL */
5107 
5108 			/*
5109 			 * return mtdrivetype
5110 			 */
5111 			struct mtdrivetype_request mtdtrq;
5112 			struct mtdrivetype mtdrtyp;
5113 			struct mtdrivetype *mtdt = &mtdrtyp;
5114 			struct st_drivetype *stdt = un->un_dp;
5115 
5116 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5117 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
5118 
5119 #ifdef _MULTI_DATAMODEL
5120 		switch (ddi_model_convert_from(flag & FMODELS)) {
5121 		case DDI_MODEL_ILP32:
5122 		{
5123 			if (ddi_copyin((void *)arg, &mtdtrq32,
5124 			    sizeof (struct mtdrivetype_request32), flag)) {
5125 				rval = EFAULT;
5126 				break;
5127 			}
5128 			mtdtrq.size = mtdtrq32.size;
5129 			mtdtrq.mtdtp =
5130 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
5131 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5132 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
5133 			break;
5134 		}
5135 		case DDI_MODEL_NONE:
5136 			if (ddi_copyin((void *)arg, &mtdtrq,
5137 			    sizeof (struct mtdrivetype_request), flag)) {
5138 				rval = EFAULT;
5139 				break;
5140 			}
5141 			break;
5142 		}
5143 
5144 #else /* ! _MULTI_DATAMODEL */
5145 		if (ddi_copyin((void *)arg, &mtdtrq,
5146 		    sizeof (struct mtdrivetype_request), flag)) {
5147 			rval = EFAULT;
5148 			break;
5149 		}
5150 #endif /* _MULTI_DATAMODEL */
5151 
5152 			/*
5153 			 * if requested size is < 0 then return
5154 			 * error.
5155 			 */
5156 			if (mtdtrq.size < 0) {
5157 				rval = EINVAL;
5158 				break;
5159 			}
5160 			bzero(mtdt, sizeof (struct mtdrivetype));
5161 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
5162 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
5163 			mtdt->type = stdt->type;
5164 			mtdt->bsize = stdt->bsize;
5165 			mtdt->options = stdt->options;
5166 			mtdt->max_rretries = stdt->max_rretries;
5167 			mtdt->max_wretries = stdt->max_wretries;
5168 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5169 				mtdt->densities[tmp] = stdt->densities[tmp];
5170 			}
5171 			mtdt->default_density = stdt->default_density;
5172 			/*
5173 			 * Speed hasn't been used since the hayday of reel tape.
5174 			 * For all drives not setting the option ST_KNOWS_MEDIA
5175 			 * the speed member renamed to mediatype are zeros.
5176 			 * Those drives that have ST_KNOWS_MEDIA set use the
5177 			 * new mediatype member which is used to figure the
5178 			 * type of media loaded.
5179 			 *
5180 			 * So as to not break applications speed in the
5181 			 * mtdrivetype structure is not renamed.
5182 			 */
5183 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5184 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
5185 			}
5186 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
5187 			mtdt->io_timeout = stdt->io_timeout;
5188 			mtdt->rewind_timeout = stdt->rewind_timeout;
5189 			mtdt->space_timeout = stdt->space_timeout;
5190 			mtdt->load_timeout = stdt->load_timeout;
5191 			mtdt->unload_timeout = stdt->unload_timeout;
5192 			mtdt->erase_timeout = stdt->erase_timeout;
5193 
5194 			/*
5195 			 * Limit the maximum length of the result to
5196 			 * sizeof (struct mtdrivetype).
5197 			 */
5198 			tmp = sizeof (struct mtdrivetype);
5199 			if (mtdtrq.size < tmp)
5200 				tmp = mtdtrq.size;
5201 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
5202 				rval = EFAULT;
5203 			}
5204 			break;
5205 		}
5206 	case MTIOCPERSISTENT:
5207 
5208 		if (ddi_copyin((void *)arg, &tmp, sizeof (tmp), flag)) {
5209 			rval = EFAULT;
5210 			break;
5211 		}
5212 
5213 		if (tmp) {
5214 			st_turn_pe_on(un);
5215 		} else {
5216 			st_turn_pe_off(un);
5217 		}
5218 
5219 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5220 		    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
5221 		    un->un_persistence);
5222 
5223 		break;
5224 
5225 	case MTIOCPERSISTENTSTATUS:
5226 		tmp = (int)un->un_persistence;
5227 
5228 		if (ddi_copyout(&tmp, (void *)arg, sizeof (tmp), flag)) {
5229 			rval = EFAULT;
5230 		}
5231 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5232 		    "st_ioctl: MTIOCPERSISTENTSTATUS:persistence = %d\n",
5233 		    un->un_persistence);
5234 
5235 		break;
5236 
5237 	case MTIOCLRERR:
5238 		{
5239 			/* clear persistent errors */
5240 
5241 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5242 			    "st_ioctl: MTIOCLRERR\n");
5243 
5244 			st_clear_pe(un);
5245 
5246 			break;
5247 		}
5248 
5249 	case MTIOCGUARANTEEDORDER:
5250 		{
5251 			/*
5252 			 * this is just a holder to make a valid ioctl and
5253 			 * it won't be in any earlier release
5254 			 */
5255 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5256 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
5257 
5258 			break;
5259 		}
5260 
5261 	case MTIOCRESERVE:
5262 		{
5263 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5264 			    "st_ioctl: MTIOCRESERVE\n");
5265 
5266 			/*
5267 			 * Check if Reserve/Release is supported.
5268 			 */
5269 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5270 				rval = ENOTTY;
5271 				break;
5272 			}
5273 
5274 			rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5275 
5276 			if (rval == 0) {
5277 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
5278 			}
5279 			break;
5280 		}
5281 
5282 	case MTIOCRELEASE:
5283 		{
5284 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5285 			    "st_ioctl: MTIOCRELEASE\n");
5286 
5287 			/*
5288 			 * Check if Reserve/Release is supported.
5289 			 */
5290 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5291 				rval = ENOTTY;
5292 				break;
5293 			}
5294 
5295 			/*
5296 			 * Used to just clear ST_PRESERVE_RESERVE which
5297 			 * made the reservation release at next close.
5298 			 * As the user may have opened and then done a
5299 			 * persistant reservation we now need to drop
5300 			 * the reservation without closing if the user
5301 			 * attempts to do this.
5302 			 */
5303 			rval = st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
5304 
5305 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5306 
5307 			break;
5308 		}
5309 
5310 	case MTIOCFORCERESERVE:
5311 	{
5312 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5313 		    "st_ioctl: MTIOCFORCERESERVE\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 		 * allow only super user to run this.
5324 		 */
5325 		if (drv_priv(cred_p) != 0) {
5326 			rval = EPERM;
5327 			break;
5328 		}
5329 		/*
5330 		 * Throw away reserve,
5331 		 * not using test-unit-ready
5332 		 * since reserve can succeed without tape being
5333 		 * present in the drive.
5334 		 */
5335 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5336 
5337 		rval = st_take_ownership(un, st_uscsi_cmd);
5338 
5339 		break;
5340 	}
5341 
5342 	case USCSICMD:
5343 	{
5344 		cred_t	*cr;
5345 
5346 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5347 		    "st_ioctl: USCSICMD\n");
5348 
5349 		cr = ddi_get_cred();
5350 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5351 			rval = EPERM;
5352 		} else {
5353 			rval = st_uscsi_cmd(un, (struct uscsi_cmd *)arg, flag);
5354 		}
5355 		break;
5356 	}
5357 	case MTIOCTOP:
5358 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5359 		    "st_ioctl: MTIOCTOP\n");
5360 		rval = st_mtioctop(un, arg, flag);
5361 		break;
5362 
5363 	case MTIOCLTOP:
5364 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5365 		    "st_ioctl: MTIOLCTOP\n");
5366 		rval = st_mtiocltop(un, arg, flag);
5367 		break;
5368 
5369 	case MTIOCREADIGNOREILI:
5370 		{
5371 			int set_ili;
5372 
5373 			if (ddi_copyin((void *)arg, &set_ili,
5374 			    sizeof (set_ili), flag)) {
5375 				rval = EFAULT;
5376 				break;
5377 			}
5378 
5379 			if (un->un_bsize) {
5380 				rval = ENOTTY;
5381 				break;
5382 			}
5383 
5384 			switch (set_ili) {
5385 			case 0:
5386 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5387 				break;
5388 
5389 			case 1:
5390 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5391 				break;
5392 
5393 			default:
5394 				rval = EINVAL;
5395 				break;
5396 			}
5397 			break;
5398 		}
5399 
5400 	case MTIOCREADIGNOREEOFS:
5401 		{
5402 			int ignore_eof;
5403 
5404 			if (ddi_copyin((void *)arg, &ignore_eof,
5405 			    sizeof (ignore_eof), flag)) {
5406 				rval = EFAULT;
5407 				break;
5408 			}
5409 
5410 			if (!(un->un_dp->options & ST_REEL)) {
5411 				rval = ENOTTY;
5412 				break;
5413 			}
5414 
5415 			switch (ignore_eof) {
5416 			case 0:
5417 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5418 				break;
5419 
5420 			case 1:
5421 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5422 				break;
5423 
5424 			default:
5425 				rval = EINVAL;
5426 				break;
5427 			}
5428 			break;
5429 		}
5430 
5431 	case MTIOCSHORTFMK:
5432 	{
5433 		int short_fmk;
5434 
5435 		if (ddi_copyin((void *)arg, &short_fmk,
5436 		    sizeof (short_fmk), flag)) {
5437 			rval = EFAULT;
5438 			break;
5439 		}
5440 
5441 		switch (un->un_dp->type) {
5442 		case ST_TYPE_EXB8500:
5443 		case ST_TYPE_EXABYTE:
5444 			if (!short_fmk) {
5445 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5446 			} else if (short_fmk == 1) {
5447 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5448 			} else {
5449 				rval = EINVAL;
5450 			}
5451 			break;
5452 
5453 		default:
5454 			rval = ENOTTY;
5455 			break;
5456 		}
5457 		break;
5458 	}
5459 
5460 	case MTIOCGETPOS:
5461 		rval = st_update_block_pos(un, st_cmd, 0);
5462 		if (rval == 0) {
5463 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5464 			    sizeof (tapepos_t), flag)) {
5465 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5466 				    "MTIOCGETPOS copy out failed\n");
5467 				rval = EFAULT;
5468 			}
5469 		}
5470 		break;
5471 
5472 	case MTIOCRESTPOS:
5473 	{
5474 		tapepos_t dest;
5475 
5476 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5477 		    flag) != 0) {
5478 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5479 			    "MTIOCRESTPOS copy in failed\n");
5480 			rval = EFAULT;
5481 			break;
5482 		}
5483 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &dest);
5484 		if (rval != 0) {
5485 			rval = EIO;
5486 		}
5487 		break;
5488 	}
5489 	default:
5490 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5491 		    "st_ioctl: unknown ioctl\n");
5492 		rval = ENOTTY;
5493 	}
5494 
5495 exit:
5496 	if (!(un->un_persistence && un->un_persist_errors)) {
5497 		un->un_errno = rval;
5498 	}
5499 
5500 	mutex_exit(ST_MUTEX);
5501 
5502 	return (rval);
5503 }
5504 
5505 
5506 /*
5507  * do some MTIOCTOP tape operations
5508  */
5509 static int
5510 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5511 {
5512 #ifdef _MULTI_DATAMODEL
5513 	/*
5514 	 * For use when a 32 bit app makes a call into a
5515 	 * 64 bit ioctl
5516 	 */
5517 	struct mtop32	mtop_32_for_64;
5518 #endif /* _MULTI_DATAMODEL */
5519 	struct mtop passed;
5520 	struct mtlop local;
5521 	int rval = 0;
5522 
5523 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5524 
5525 	ASSERT(mutex_owned(ST_MUTEX));
5526 
5527 #ifdef _MULTI_DATAMODEL
5528 	switch (ddi_model_convert_from(flag & FMODELS)) {
5529 	case DDI_MODEL_ILP32:
5530 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5531 		    sizeof (struct mtop32), flag)) {
5532 			return (EFAULT);
5533 		}
5534 		local.mt_op = mtop_32_for_64.mt_op;
5535 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5536 		break;
5537 
5538 	case DDI_MODEL_NONE:
5539 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5540 			return (EFAULT);
5541 		}
5542 		local.mt_op = passed.mt_op;
5543 		/* prevent sign extention */
5544 		local.mt_count = (UINT32_MAX & passed.mt_count);
5545 		break;
5546 	}
5547 
5548 #else /* ! _MULTI_DATAMODEL */
5549 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5550 		return (EFAULT);
5551 	}
5552 	local.mt_op = passed.mt_op;
5553 	/* prevent sign extention */
5554 	local.mt_count = (UINT32_MAX & passed.mt_count);
5555 #endif /* _MULTI_DATAMODEL */
5556 
5557 	rval = st_do_mtioctop(un, &local);
5558 
5559 #ifdef _MULTI_DATAMODEL
5560 	switch (ddi_model_convert_from(flag & FMODELS)) {
5561 	case DDI_MODEL_ILP32:
5562 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5563 			rval = ERANGE;
5564 			break;
5565 		}
5566 		/*
5567 		 * Convert 64 bit back to 32 bit before doing
5568 		 * copyout. This is what the ILP32 app expects.
5569 		 */
5570 		mtop_32_for_64.mt_op = local.mt_op;
5571 		mtop_32_for_64.mt_count = local.mt_count;
5572 
5573 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5574 		    sizeof (struct mtop32), flag)) {
5575 			rval = EFAULT;
5576 		}
5577 		break;
5578 
5579 	case DDI_MODEL_NONE:
5580 		passed.mt_count = local.mt_count;
5581 		passed.mt_op = local.mt_op;
5582 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5583 			rval = EFAULT;
5584 		}
5585 		break;
5586 	}
5587 #else /* ! _MULTI_DATAMODE */
5588 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5589 		rval = ERANGE;
5590 	} else {
5591 		passed.mt_op = local.mt_op;
5592 		passed.mt_count = local.mt_count;
5593 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5594 			rval = EFAULT;
5595 		}
5596 	}
5597 #endif /* _MULTI_DATAMODE */
5598 
5599 
5600 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5601 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5602 	    un->un_pos.blkno, un->un_pos.eof);
5603 
5604 	if (un->un_pos.pmode == invalid) {
5605 		un->un_density_known = 0;
5606 	}
5607 
5608 	ASSERT(mutex_owned(ST_MUTEX));
5609 	return (rval);
5610 }
5611 
5612 static int
5613 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5614 {
5615 	struct mtlop local;
5616 	int rval;
5617 
5618 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5619 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5620 		return (EFAULT);
5621 	}
5622 
5623 	rval = st_do_mtioctop(un, &local);
5624 
5625 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5626 		rval = EFAULT;
5627 	}
5628 	return (rval);
5629 }
5630 
5631 
5632 static int
5633 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5634 {
5635 	dev_t dev = un->un_dev;
5636 	int savefile;
5637 	int rval = 0;
5638 
5639 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5640 
5641 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5642 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5643 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5644 	    "fileno=%x, blkno=%x, eof=%x\n",
5645 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5646 
5647 	un->un_status = 0;
5648 
5649 	/*
5650 	 * if we are going to mess with a tape, we have to make sure we have
5651 	 * one and are not offline (i.e. no tape is initialized).  We let
5652 	 * commands pass here that don't actually touch the tape, except for
5653 	 * loading and initialization (rewinding).
5654 	 */
5655 	if (un->un_state == ST_STATE_OFFLINE) {
5656 		switch (mtop->mt_op) {
5657 		case MTLOAD:
5658 		case MTNOP:
5659 			/*
5660 			 * We don't want strategy calling st_tape_init here,
5661 			 * so, change state
5662 			 */
5663 			un->un_state = ST_STATE_INITIALIZING;
5664 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5665 			    "st_do_mtioctop : OFFLINE state = %d\n",
5666 			    un->un_state);
5667 			break;
5668 		default:
5669 			/*
5670 			 * reinitialize by normal means
5671 			 */
5672 			rval = st_tape_init(un);
5673 			if (rval) {
5674 				un->un_state = ST_STATE_INITIALIZING;
5675 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5676 				    "st_do_mtioctop : OFFLINE init failure ");
5677 				un->un_state = ST_STATE_OFFLINE;
5678 				un->un_pos.pmode = invalid;
5679 				if (rval != EACCES) {
5680 					rval = EIO;
5681 				}
5682 				return (rval);
5683 			}
5684 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5685 			break;
5686 		}
5687 	}
5688 
5689 	/*
5690 	 * If the file position is invalid, allow only those
5691 	 * commands that properly position the tape and fail
5692 	 * the rest with EIO
5693 	 */
5694 	if (un->un_pos.pmode == invalid) {
5695 		switch (mtop->mt_op) {
5696 		case MTWEOF:
5697 		case MTRETEN:
5698 		case MTERASE:
5699 		case MTEOM:
5700 		case MTFSF:
5701 		case MTFSR:
5702 		case MTBSF:
5703 		case MTNBSF:
5704 		case MTBSR:
5705 		case MTSRSZ:
5706 		case MTGRSZ:
5707 		case MTSEEK:
5708 		case MTBSSF:
5709 		case MTFSSF:
5710 			return (EIO);
5711 			/* NOTREACHED */
5712 		case MTREW:
5713 		case MTLOAD:
5714 		case MTOFFL:
5715 		case MTNOP:
5716 		case MTTELL:
5717 		case MTLOCK:
5718 		case MTUNLOCK:
5719 			break;
5720 
5721 		default:
5722 			return (ENOTTY);
5723 			/* NOTREACHED */
5724 		}
5725 	}
5726 
5727 	switch (mtop->mt_op) {
5728 	case MTERASE:
5729 		/*
5730 		 * MTERASE rewinds the tape, erase it completely, and returns
5731 		 * to the beginning of the tape
5732 		 */
5733 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5734 			un->un_status = KEY_WRITE_PROTECT;
5735 			un->un_err_resid = mtop->mt_count;
5736 			COPY_POS(&un->un_err_pos, &un->un_pos);
5737 			return (EACCES);
5738 		}
5739 		if (un->un_dp->options & ST_REEL) {
5740 			un->un_fmneeded = 2;
5741 		} else {
5742 			un->un_fmneeded = 1;
5743 		}
5744 		mtop->mt_count = mtop->mt_count ? 1 : 0;
5745 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5746 		    st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
5747 		    st_cmd(un, SCMD_ERASE, mtop->mt_count, SYNC_CMD)) {
5748 			un->un_pos.pmode = invalid;
5749 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5750 			    "st_do_mtioctop : EIO space or erase or "
5751 			    "check den)\n");
5752 			rval = EIO;
5753 		} else {
5754 			/* QIC and helical scan rewind after erase */
5755 			if (un->un_dp->options & ST_REEL) {
5756 				(void) st_cmd(un, SCMD_REWIND, 0, ASYNC_CMD);
5757 			}
5758 		}
5759 		break;
5760 
5761 	case MTWEOF:
5762 		/*
5763 		 * write an end-of-file record
5764 		 */
5765 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5766 			un->un_status = KEY_WRITE_PROTECT;
5767 			un->un_err_resid = mtop->mt_count;
5768 			COPY_POS(&un->un_err_pos, &un->un_pos);
5769 			return (EACCES);
5770 		}
5771 
5772 		/*
5773 		 * zero count means just flush buffers
5774 		 * negative count is not permitted
5775 		 */
5776 		if (mtop->mt_count < 0) {
5777 			return (EINVAL);
5778 		}
5779 
5780 		/* Not on worm */
5781 		if (un->un_read_only == RDWR) {
5782 			un->un_test_append = 1;
5783 		}
5784 
5785 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5786 			if (st_determine_density(un, B_WRITE)) {
5787 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5788 				    "st_do_mtioctop : EIO : MTWEOF can't "
5789 				    "determine density");
5790 				return (EIO);
5791 			}
5792 		}
5793 
5794 		rval = st_write_fm(dev, (int)mtop->mt_count);
5795 		if ((rval != 0) && (rval != EACCES)) {
5796 			/*
5797 			 * Failure due to something other than illegal
5798 			 * request results in loss of state (st_intr).
5799 			 */
5800 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5801 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5802 			    "file mark");
5803 			rval = EIO;
5804 		}
5805 		break;
5806 
5807 	case MTRETEN:
5808 		/*
5809 		 * retension the tape
5810 		 */
5811 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5812 		    st_cmd(un, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5813 			un->un_pos.pmode = invalid;
5814 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5815 			    "st_do_mtioctop : EIO : MTRETEN ");
5816 			rval = EIO;
5817 		}
5818 		break;
5819 
5820 	case MTREW:
5821 		/*
5822 		 * rewind  the tape
5823 		 */
5824 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5825 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5826 			    "st_do_mtioctop : EIO:MTREW check "
5827 			    "density/wfm failed");
5828 			return (EIO);
5829 		}
5830 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
5831 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5832 			    "st_do_mtioctop : EIO : MTREW ");
5833 			rval = EIO;
5834 		}
5835 		break;
5836 
5837 	case MTOFFL:
5838 		/*
5839 		 * rewinds, and, if appropriate, takes the device offline by
5840 		 * unloading the tape
5841 		 */
5842 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5843 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5844 			    "st_do_mtioctop :EIO:MTOFFL check "
5845 			    "density/wfm failed");
5846 			return (EIO);
5847 		}
5848 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
5849 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5850 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5851 			    "st_do_mtioctop : EIO : MTOFFL");
5852 			return (EIO);
5853 		}
5854 		un->un_pos.eof = ST_NO_EOF;
5855 		un->un_laststate = un->un_state;
5856 		un->un_state = ST_STATE_OFFLINE;
5857 		un->un_mediastate = MTIO_EJECTED;
5858 		break;
5859 
5860 	case MTLOAD:
5861 		/*
5862 		 * This is to load a tape into the drive
5863 		 * Note that if the tape is not loaded, the device will have
5864 		 * to be opened via O_NDELAY or O_NONBLOCK.
5865 		 */
5866 		/*
5867 		 * Let's try and clean things up, if we are not
5868 		 * initializing, and then send in the load command, no
5869 		 * matter what.
5870 		 *
5871 		 * load after a media change by the user.
5872 		 */
5873 
5874 		if (un->un_state > ST_STATE_INITIALIZING) {
5875 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5876 		}
5877 		rval = st_cmd(un, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5878 		/* Load command to a drive that doesn't support load */
5879 		if ((rval == EIO) &&
5880 		    ((un->un_status == KEY_NOT_READY) &&
5881 			/* Medium not present */
5882 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5883 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5884 		    (un->un_dp->type == MT_ISSTK9840) &&
5885 			/* CSL not present */
5886 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5887 			rval = ENOTTY;
5888 			break;
5889 		} else if (rval != EACCES && rval != 0) {
5890 			rval = EIO;
5891 		}
5892 		if (rval) {
5893 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5894 			    "st_do_mtioctop : %s : MTLOAD\n",
5895 			    rval == EACCES ? "EACCES" : "EIO");
5896 			/*
5897 			 * If load tape fails, who knows what happened...
5898 			 */
5899 			un->un_pos.pmode = invalid;
5900 			break;
5901 		}
5902 
5903 		/*
5904 		 * reset all counters appropriately using rewind, as if LOAD
5905 		 * succeeds, we are at BOT
5906 		 */
5907 		un->un_state = ST_STATE_INITIALIZING;
5908 
5909 		rval = st_tape_init(un);
5910 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5911 			rval = 0;
5912 			break;
5913 		}
5914 
5915 		if (rval != 0) {
5916 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5917 			    "st_do_mtioctop : EIO : MTLOAD calls "
5918 			    "st_tape_init\n");
5919 			rval = EIO;
5920 			un->un_state = ST_STATE_OFFLINE;
5921 		}
5922 
5923 		break;
5924 
5925 	case MTNOP:
5926 		un->un_status = 0;		/* Reset status */
5927 		un->un_err_resid = 0;
5928 		mtop->mt_count = MTUNIT(dev);
5929 		break;
5930 
5931 	case MTEOM:
5932 		/*
5933 		 * positions the tape at a location just after the last file
5934 		 * written on the tape. For cartridge and 8 mm, this after
5935 		 * the last file mark; for reel, this is inbetween the two
5936 		 * last 2 file marks
5937 		 */
5938 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5939 		    (un->un_lastop == ST_OP_WRITE) ||
5940 		    (un->un_lastop == ST_OP_WEOF)) {
5941 			/*
5942 			 * If the command wants to move to logical end
5943 			 * of media, and we're already there, we're done.
5944 			 * If we were at logical eot, we reset the state
5945 			 * to be *not* at logical eot.
5946 			 *
5947 			 * If we're at physical or logical eot, we prohibit
5948 			 * forward space operations (unconditionally).
5949 			 *
5950 			 * Also if the last operation was a write of any
5951 			 * kind the tape is at EOD.
5952 			 */
5953 			return (0);
5954 		}
5955 		/*
5956 		 * physical tape position may not be what we've been
5957 		 * telling the user; adjust the request accordingly
5958 		 */
5959 		if (IN_EOF(un->un_pos)) {
5960 			un->un_pos.fileno++;
5961 			un->un_pos.blkno = 0;
5962 		}
5963 
5964 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
5965 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5966 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
5967 			    " failed");
5968 			return (EIO);
5969 		}
5970 
5971 		/*
5972 		 * st_find_eod() returns the last fileno we knew about;
5973 		 */
5974 		savefile = st_find_eod(un);
5975 
5976 		if ((un->un_status != KEY_BLANK_CHECK) &&
5977 		    (un->un_status != SUN_KEY_EOT)) {
5978 			un->un_pos.pmode = invalid;
5979 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5980 			    "st_do_mtioctop : EIO : MTEOM status check failed");
5981 			rval = EIO;
5982 		} else {
5983 			/*
5984 			 * For 1/2" reel tapes assume logical EOT marked
5985 			 * by two file marks or we don't care that we may
5986 			 * be extending the last file on the tape.
5987 			 */
5988 			if (un->un_dp->options & ST_REEL) {
5989 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
5990 					un->un_pos.pmode = invalid;
5991 					ST_DEBUG2(ST_DEVINFO, st_label,
5992 					    SCSI_DEBUG,
5993 					    "st_do_mtioctop : EIO : MTEOM space"
5994 					    " cmd failed");
5995 					rval = EIO;
5996 					break;
5997 				}
5998 				/*
5999 				 * Fix up the block number.
6000 				 */
6001 				un->un_pos.blkno = 0;
6002 				un->un_err_pos.blkno = 0;
6003 			}
6004 			un->un_err_resid = 0;
6005 			un->un_pos.fileno = savefile;
6006 			un->un_pos.eof = ST_EOT;
6007 		}
6008 		un->un_status = 0;
6009 		break;
6010 
6011 	case MTFSF:
6012 		MAX_SPACE_CNT(mtop->mt_count);
6013 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
6014 		break;
6015 
6016 	case MTFSR:
6017 		MAX_SPACE_CNT(mtop->mt_count);
6018 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
6019 		break;
6020 
6021 	case MTBSF:
6022 		MAX_SPACE_CNT(mtop->mt_count);
6023 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
6024 		break;
6025 
6026 	case MTNBSF:
6027 		MAX_SPACE_CNT(mtop->mt_count);
6028 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
6029 		break;
6030 
6031 	case MTBSR:
6032 		MAX_SPACE_CNT(mtop->mt_count);
6033 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
6034 		break;
6035 
6036 	case MTBSSF:
6037 		MAX_SPACE_CNT(mtop->mt_count);
6038 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
6039 		break;
6040 
6041 	case MTFSSF:
6042 		MAX_SPACE_CNT(mtop->mt_count);
6043 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
6044 		break;
6045 
6046 	case MTSRSZ:
6047 
6048 		/*
6049 		 * Set record-size to that sent by user
6050 		 * Check to see if there is reason that the requested
6051 		 * block size should not be set.
6052 		 */
6053 
6054 		/* If requesting variable block size is it ok? */
6055 		if ((mtop->mt_count == 0) &&
6056 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
6057 			return (ENOTTY);
6058 		}
6059 
6060 		/*
6061 		 * If requested block size is not variable "0",
6062 		 * is it less then minimum.
6063 		 */
6064 		if ((mtop->mt_count != 0) &&
6065 		    (mtop->mt_count < un->un_minbsize)) {
6066 			return (EINVAL);
6067 		}
6068 
6069 		/* Is the requested block size more then maximum */
6070 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
6071 		    (un->un_maxbsize != 0)) {
6072 			return (EINVAL);
6073 		}
6074 
6075 		/* Is requested block size a modulus the device likes */
6076 		if ((mtop->mt_count % un->un_data_mod) != 0) {
6077 			return (EINVAL);
6078 		}
6079 
6080 		if (st_change_block_size(un, (uint32_t)mtop->mt_count) != 0) {
6081 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6082 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
6083 			return (EIO);
6084 		}
6085 
6086 		return (0);
6087 
6088 	case MTGRSZ:
6089 		/*
6090 		 * Get record-size to the user
6091 		 */
6092 		mtop->mt_count = un->un_bsize;
6093 		rval = 0;
6094 		break;
6095 
6096 	case MTTELL:
6097 		rval = st_update_block_pos(un, st_cmd, 0);
6098 		mtop->mt_count = un->un_pos.lgclblkno;
6099 		break;
6100 
6101 	case MTSEEK:
6102 		rval = st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
6103 		    (uint64_t)mtop->mt_count, un->un_pos.partition);
6104 		/*
6105 		 * This bit of magic make mt print the actual position if
6106 		 * the resulting position was not what was asked for.
6107 		 */
6108 		if (rval == ESPIPE) {
6109 			rval = EIO;
6110 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
6111 				mtop->mt_op = MTTELL;
6112 				mtop->mt_count = un->un_pos.lgclblkno;
6113 			}
6114 		}
6115 		break;
6116 
6117 	case MTLOCK:
6118 		if (st_cmd(un, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
6119 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6120 			    "st_do_mtioctop : EIO : MTLOCK");
6121 			rval = EIO;
6122 		}
6123 		break;
6124 
6125 	case MTUNLOCK:
6126 		if (st_cmd(un, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
6127 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6128 			    "st_do_mtioctop : EIO : MTUNLOCK");
6129 			rval = EIO;
6130 		}
6131 		break;
6132 
6133 	default:
6134 		rval = ENOTTY;
6135 	}
6136 
6137 	return (rval);
6138 }
6139 
6140 
6141 /*
6142  * Run a command for uscsi ioctl.
6143  */
6144 static int
6145 st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
6146 {
6147 	struct uscsi_cmd	*uscmd;
6148 	struct buf	*bp;
6149 	enum uio_seg	uioseg;
6150 	int	offline_state = 0;
6151 	int	err = 0;
6152 	dev_t dev = un->un_dev;
6153 
6154 	ST_FUNC(ST_DEVINFO, st_uscsi_cmd);
6155 
6156 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6157 	    "st_uscsi_cmd(dev = 0x%lx)\n", un->un_dev);
6158 
6159 	ASSERT(mutex_owned(ST_MUTEX));
6160 
6161 	/*
6162 	 * We really don't know what commands are coming in here and
6163 	 * we don't want to limit the commands coming in.
6164 	 *
6165 	 * If st_tape_init() gets called from st_strategy(), then we
6166 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
6167 	 * which it never will, as we set it below.  To prevent
6168 	 * st_tape_init() from getting called, we have to set state to other
6169 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
6170 	 * achieves this purpose already.
6171 	 *
6172 	 * We use offline_state to preserve the OFFLINE state, if it exists,
6173 	 * so other entry points to the driver might have the chance to call
6174 	 * st_tape_init().
6175 	 */
6176 	if (un->un_state == ST_STATE_OFFLINE) {
6177 		un->un_laststate = ST_STATE_OFFLINE;
6178 		un->un_state = ST_STATE_INITIALIZING;
6179 		offline_state = 1;
6180 	}
6181 
6182 	mutex_exit(ST_MUTEX);
6183 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag, ROUTE, &uscmd);
6184 	mutex_enter(ST_MUTEX);
6185 	if (err != 0) {
6186 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6187 		    "st_uscsi_cmd: scsi_uscsi_alloc_and_copyin failed\n");
6188 		goto exit;
6189 	}
6190 
6191 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
6192 
6193 	/* check to see if this command requires the drive to be reserved */
6194 	if (uscmd->uscsi_cdb != NULL) {
6195 		err = st_check_cdb_for_need_to_reserve(un,
6196 		    (uchar_t *)uscmd->uscsi_cdb);
6197 		if (err) {
6198 			goto exit_free;
6199 		}
6200 		/*
6201 		 * If this is a space command we need to save the starting
6202 		 * point so we can retry from there if the command fails.
6203 		 */
6204 		if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6205 		    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) {
6206 			(void) st_update_block_pos(un, st_cmd, 0);
6207 		}
6208 	}
6209 
6210 	/*
6211 	 * Forground should not be doing anything while recovery is active.
6212 	 */
6213 	ASSERT(un->un_recov_buf_busy == 0);
6214 
6215 	/*
6216 	 * Get buffer resources...
6217 	 */
6218 	while (un->un_sbuf_busy)
6219 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6220 	un->un_sbuf_busy = 1;
6221 
6222 #ifdef STDEBUG
6223 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0x7) > 6) {
6224 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
6225 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6226 		    "uscsi cdb", uscmd->uscsi_cdb);
6227 		if (uscmd->uscsi_buflen) {
6228 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6229 			    "uscsi %s of %ld bytes %s %s space\n",
6230 			    (rw == B_READ) ? rd_str : wr_str,
6231 			    uscmd->uscsi_buflen,
6232 			    (rw == B_READ) ? "to" : "from",
6233 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
6234 		}
6235 	}
6236 #endif /* STDEBUG */
6237 
6238 	/*
6239 	 * Although st_uscsi_cmd() never makes use of these
6240 	 * now, we are just being safe and consistent.
6241 	 */
6242 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
6243 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
6244 
6245 	un->un_srqbufp = uscmd->uscsi_rqbuf;
6246 	bp = un->un_sbufp;
6247 	bzero(bp, sizeof (buf_t));
6248 	if (uscmd->uscsi_cdb != NULL) {
6249 		bp->b_forw = (struct buf *)(uintptr_t)uscmd->uscsi_cdb[0];
6250 	}
6251 	bp->b_back = (struct buf *)uscmd;
6252 
6253 	mutex_exit(ST_MUTEX);
6254 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, st_strategy, bp, NULL);
6255 	mutex_enter(ST_MUTEX);
6256 
6257 	/*
6258 	 * If scsi reset successful, don't write any filemarks.
6259 	 */
6260 	if ((err == 0) && (uscmd->uscsi_flags &
6261 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
6262 		un->un_fmneeded = 0;
6263 	}
6264 
6265 exit_free:
6266 	/*
6267 	 * Free resources
6268 	 */
6269 	un->un_sbuf_busy = 0;
6270 	un->un_srqbufp = NULL;
6271 
6272 	/*
6273 	 * If was a space command need to update logical block position.
6274 	 * If the command failed such that positioning is invalid, Don't
6275 	 * update the position as the user must do this to validate the
6276 	 * position for data protection.
6277 	 */
6278 	if ((uscmd->uscsi_cdb != NULL) &&
6279 	    ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6280 	    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) &&
6281 	    (un->un_pos.pmode != invalid)) {
6282 		un->un_running.pmode = invalid;
6283 		(void) st_update_block_pos(un, st_cmd, 1);
6284 		/*
6285 		 * Set running position to invalid so it updates on the
6286 		 * next command.
6287 		 */
6288 		un->un_running.pmode = invalid;
6289 	}
6290 	cv_signal(&un->un_sbuf_cv);
6291 	mutex_exit(ST_MUTEX);
6292 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
6293 	mutex_enter(ST_MUTEX);
6294 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6295 	    "st_uscsi_cmd returns 0x%x\n", err);
6296 
6297 exit:
6298 	/* don't lose offline state */
6299 	if (offline_state) {
6300 		un->un_state = ST_STATE_OFFLINE;
6301 	}
6302 
6303 	ASSERT(mutex_owned(ST_MUTEX));
6304 	return (err);
6305 }
6306 
6307 static int
6308 st_write_fm(dev_t dev, int wfm)
6309 {
6310 	int i;
6311 	int rval;
6312 
6313 	GET_SOFT_STATE(dev);
6314 
6315 	ST_FUNC(ST_DEVINFO, st_write_fm);
6316 
6317 	ASSERT(mutex_owned(ST_MUTEX));
6318 
6319 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6320 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6321 
6322 	/*
6323 	 * write one filemark at the time after EOT
6324 	 */
6325 	if (un->un_pos.eof >= ST_EOT) {
6326 		for (i = 0; i < wfm; i++) {
6327 			rval = st_cmd(un, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6328 			if (rval == EACCES) {
6329 				return (rval);
6330 			}
6331 			if (rval != 0) {
6332 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6333 				    "st_write_fm : EIO : write EOT file mark");
6334 				return (EIO);
6335 			}
6336 		}
6337 	} else {
6338 		rval = st_cmd(un, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6339 		if (rval == EACCES) {
6340 			return (rval);
6341 		}
6342 		if (rval) {
6343 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6344 			    "st_write_fm : EIO : write file mark");
6345 			return (EIO);
6346 		}
6347 	}
6348 
6349 	ASSERT(mutex_owned(ST_MUTEX));
6350 	return (0);
6351 }
6352 
6353 #ifdef STDEBUG
6354 static void
6355 st_start_dump(struct scsi_tape *un, struct buf *bp)
6356 {
6357 	struct scsi_pkt *pkt = BP_PKT(bp);
6358 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6359 
6360 	ST_FUNC(ST_DEVINFO, st_start_dump);
6361 
6362 	if ((st_debug & 0x7) < 6)
6363 		return;
6364 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6365 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6366 	    (void *)bp->b_forw, bp->b_bcount,
6367 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6368 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6369 	    "st_start: cdb",  (caddr_t)cdbp);
6370 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6371 	    "st_start: fileno=%d, blk=%d\n",
6372 	    un->un_pos.fileno, un->un_pos.blkno);
6373 }
6374 #endif
6375 
6376 
6377 /*
6378  * Command start && done functions
6379  */
6380 
6381 /*
6382  * st_start()
6383  *
6384  * Called from:
6385  *  st_strategy() to start a command.
6386  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6387  *  st_attach() when resuming from power down state.
6388  *  st_start_restart() to retry transport when device was previously busy.
6389  *  st_done_and_mutex_exit() to start the next command when previous is done.
6390  *
6391  * On entry:
6392  *  scsi_pkt may or may not be allocated.
6393  *
6394  */
6395 static void
6396 st_start(struct scsi_tape *un)
6397 {
6398 	struct buf *bp;
6399 	int status;
6400 	int queued;
6401 
6402 	ST_FUNC(ST_DEVINFO, st_start);
6403 	ASSERT(mutex_owned(ST_MUTEX));
6404 
6405 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6406 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6407 
6408 	if (un->un_recov_buf_busy) {
6409 		/* recovery commands can happen anytime */
6410 		bp = un->un_recov_buf;
6411 		queued = 0;
6412 	} else if (un->un_sbuf_busy) {
6413 		/* sbuf commands should only happen with an empty queue. */
6414 		ASSERT(un->un_quef == NULL);
6415 		ASSERT(un->un_runqf == NULL);
6416 		bp = un->un_sbufp;
6417 		queued = 0;
6418 	} else if (un->un_quef != NULL) {
6419 		if (un->un_persistence && un->un_persist_errors) {
6420 			return;
6421 		}
6422 		bp = un->un_quef;
6423 		queued = 1;
6424 	} else {
6425 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6426 		    "st_start() returning no buf found\n");
6427 		return;
6428 	}
6429 
6430 	ASSERT((bp->b_flags & B_DONE) == 0);
6431 
6432 	/*
6433 	 * Don't send more than un_throttle commands to the HBA
6434 	 */
6435 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6436 		/*
6437 		 * if doing recovery we know there is outstanding commands.
6438 		 */
6439 		if (bp != un->un_recov_buf) {
6440 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6441 			    "st_start returning throttle = %d or ncmds = %d\n",
6442 			    un->un_throttle, un->un_ncmds);
6443 			if (un->un_ncmds == 0) {
6444 				typedef void (*func)();
6445 				func fnc = (func)st_runout;
6446 
6447 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6448 				    "Sending delayed start to st_runout()\n");
6449 				mutex_exit(ST_MUTEX);
6450 				(void) timeout(fnc, un, drv_usectohz(1000000));
6451 				mutex_enter(ST_MUTEX);
6452 			}
6453 			return;
6454 		}
6455 	}
6456 
6457 	/*
6458 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6459 	 * build the command.
6460 	 */
6461 	if (BP_PKT(bp) == NULL) {
6462 		ASSERT((bp->b_flags & B_DONE) == 0);
6463 		st_make_cmd(un, bp, st_runout);
6464 		ASSERT((bp->b_flags & B_DONE) == 0);
6465 		status = geterror(bp);
6466 
6467 		/*
6468 		 * Some HBA's don't call bioerror() to set an error.
6469 		 * And geterror() returns zero if B_ERROR is not set.
6470 		 * So if we get zero we must check b_error.
6471 		 */
6472 		if (status == 0 && bp->b_error != 0) {
6473 			status = bp->b_error;
6474 			bioerror(bp, status);
6475 		}
6476 
6477 		/*
6478 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6479 		 * In tape ENOMEM has special meaning so we'll change it.
6480 		 */
6481 		if (status == ENOMEM) {
6482 			status = 0;
6483 			bioerror(bp, status);
6484 		}
6485 
6486 		/*
6487 		 * Did it fail and is it retryable?
6488 		 * If so return and wait for the callback through st_runout.
6489 		 * Also looks like scsi_init_pkt() will setup a callback even
6490 		 * if it isn't retryable.
6491 		 */
6492 		if (BP_PKT(bp) == NULL) {
6493 			if (status == 0) {
6494 				/*
6495 				 * If first attempt save state.
6496 				 */
6497 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6498 					un->un_laststate = un->un_state;
6499 					un->un_state = ST_STATE_RESOURCE_WAIT;
6500 				}
6501 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6502 				    "temp no resources for pkt\n");
6503 			} else if (status == EINVAL) {
6504 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6505 				    "scsi_init_pkt rejected pkt as too big\n");
6506 				if (un->un_persistence) {
6507 					st_set_pe_flag(un);
6508 				}
6509 			} else {
6510 				/*
6511 				 * Unlikely that it would be retryable then not.
6512 				 */
6513 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6514 					un->un_state = un->un_laststate;
6515 				}
6516 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6517 				    "perm no resources for pkt errno = 0x%x\n",
6518 				    status);
6519 			}
6520 			return;
6521 		}
6522 		/*
6523 		 * Worked this time set the state back.
6524 		 */
6525 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6526 			un->un_state = un->un_laststate;
6527 		}
6528 	}
6529 
6530 	if (queued) {
6531 		/*
6532 		 * move from waitq to runq
6533 		 */
6534 		(void) st_remove_from_queue(&un->un_quef, &un->un_quel, bp);
6535 		st_add_to_queue(&un->un_runqf, &un->un_runql, un->un_runql, bp);
6536 	}
6537 
6538 
6539 #ifdef STDEBUG
6540 	st_start_dump(un, bp);
6541 #endif
6542 
6543 	/* could not get here if throttle was zero */
6544 	un->un_last_throttle = un->un_throttle;
6545 	un->un_throttle = 0;	/* so nothing else will come in here */
6546 	un->un_ncmds++;
6547 
6548 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6549 
6550 	status = st_transport(un, BP_PKT(bp));
6551 
6552 	if (un->un_last_throttle) {
6553 		un->un_throttle = un->un_last_throttle;
6554 	}
6555 
6556 	if (status != TRAN_ACCEPT) {
6557 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6558 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
6559 		    "Unhappy transport packet status 0x%x\n", status);
6560 
6561 		if (status == TRAN_BUSY) {
6562 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
6563 
6564 			/*
6565 			 * If command recovery is enabled and this isn't
6566 			 * a recovery command try command recovery.
6567 			 */
6568 			if (pkti->privatelen == sizeof (recov_info) &&
6569 			    bp != un->un_recov_buf) {
6570 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
6571 				    "Command Recovery called on busy send\n");
6572 				if (st_command_recovery(un, BP_PKT(bp),
6573 				    ATTEMPT_RETRY) == JUST_RETURN) {
6574 					return;
6575 				}
6576 			} else {
6577 				mutex_exit(ST_MUTEX);
6578 				if (st_handle_start_busy(un, bp,
6579 				    ST_TRAN_BUSY_TIMEOUT, queued) == 0) {
6580 					mutex_enter(ST_MUTEX);
6581 					return;
6582 				}
6583 				/*
6584 				 * if too many retries, fail the transport
6585 				 */
6586 				mutex_enter(ST_MUTEX);
6587 			}
6588 		}
6589 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6590 		    "transport rejected %d\n", status);
6591 		bp->b_resid = bp->b_bcount;
6592 
6593 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6594 		ST_DO_ERRSTATS(un, st_transerrs);
6595 		if ((bp == un->un_recov_buf) && (status == TRAN_BUSY)) {
6596 			st_bioerror(bp, EBUSY);
6597 		} else {
6598 			st_bioerror(bp, EIO);
6599 			st_set_pe_flag(un);
6600 		}
6601 		st_done_and_mutex_exit(un, bp);
6602 		mutex_enter(ST_MUTEX);
6603 	}
6604 
6605 	ASSERT(mutex_owned(ST_MUTEX));
6606 }
6607 
6608 /*
6609  * if the transport is busy, then put this bp back on the waitq
6610  */
6611 static int
6612 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6613     clock_t timeout_interval, int queued)
6614 {
6615 
6616 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
6617 
6618 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6619 
6620 	mutex_enter(ST_MUTEX);
6621 
6622 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6623 	    "st_handle_start_busy()\n");
6624 
6625 	/*
6626 	 * Check to see if we hit the retry timeout and one last check for
6627 	 * making sure this is the last on the runq, if it is not, we have
6628 	 * to fail
6629 	 */
6630 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
6631 	    ((queued) && (un->un_runql != bp))) {
6632 		mutex_exit(ST_MUTEX);
6633 		return (-1);
6634 	}
6635 
6636 	if (queued) {
6637 		/* put the bp back on the waitq */
6638 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
6639 	}
6640 
6641 	/*
6642 	 * Decrement un_ncmds so that this
6643 	 * gets thru' st_start() again.
6644 	 */
6645 	un->un_ncmds--;
6646 
6647 	if (queued) {
6648 		/*
6649 		 * since this is an error case, we won't have to do this list
6650 		 * walking much. We've already made sure this bp was the
6651 		 * last on the runq
6652 		 */
6653 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6654 
6655 		/*
6656 		 * send a marker pkt, if appropriate
6657 		 */
6658 		st_hba_unflush(un);
6659 
6660 	}
6661 	/*
6662 	 * all queues are aligned, we are just waiting to
6663 	 * transport, don't alloc any more buf p's, when
6664 	 * st_start is reentered.
6665 	 */
6666 	(void) timeout(st_start_restart, un, timeout_interval);
6667 
6668 	mutex_exit(ST_MUTEX);
6669 	return (0);
6670 }
6671 
6672 
6673 /*
6674  * st_runout a callback that is called what a resource allocatation failed
6675  */
6676 static int
6677 st_runout(caddr_t arg)
6678 {
6679 	struct scsi_tape *un = (struct scsi_tape *)arg;
6680 	struct buf *bp;
6681 	int queued;
6682 
6683 	ASSERT(un != NULL);
6684 
6685 	ST_FUNC(ST_DEVINFO, st_runout);
6686 
6687 	mutex_enter(ST_MUTEX);
6688 
6689 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6690 
6691 	if (un->un_recov_buf_busy != 0) {
6692 		bp = un->un_recov_buf;
6693 		queued = 0;
6694 	} else if (un->un_sbuf_busy != 0) {
6695 		/* sbuf commands should only happen with an empty queue. */
6696 		ASSERT(un->un_quef == NULL);
6697 		ASSERT(un->un_runqf == NULL);
6698 		bp = un->un_sbufp;
6699 		queued = 0;
6700 	} else if (un->un_quef != NULL) {
6701 		bp = un->un_quef;
6702 		if (un->un_persistence && un->un_persist_errors) {
6703 			mutex_exit(ST_MUTEX);
6704 			bp->b_resid = bp->b_bcount;
6705 			biodone(bp);
6706 			return (1);
6707 		}
6708 		queued = 1;
6709 	} else {
6710 		ASSERT(1 == 0);
6711 		mutex_exit(ST_MUTEX);
6712 		return (1);
6713 	}
6714 
6715 	/*
6716 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6717 	 */
6718 	if ((bp != NULL) && (geterror(bp) != 0)) {
6719 
6720 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6721 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6722 		    bp->b_flags, geterror(bp));
6723 		ASSERT((bp->b_flags & B_DONE) == 0);
6724 
6725 		if (queued) {
6726 			(void) st_remove_from_queue(&un->un_quef, &un->un_quel,
6727 			    bp);
6728 		}
6729 		mutex_exit(ST_MUTEX);
6730 
6731 		ASSERT((bp->b_flags & B_DONE) == 0);
6732 
6733 		/*
6734 		 * Set resid, Error already set, then unblock calling thread.
6735 		 */
6736 		bp->b_resid = bp->b_bcount;
6737 		biodone(bp);
6738 	} else {
6739 		/*
6740 		 * Try Again
6741 		 */
6742 		st_start(un);
6743 		mutex_exit(ST_MUTEX);
6744 	}
6745 
6746 	/*
6747 	 * Comments courtesy of sd.c
6748 	 * The scsi_init_pkt routine allows for the callback function to
6749 	 * return a 0 indicating the callback should be rescheduled or a 1
6750 	 * indicating not to reschedule. This routine always returns 1
6751 	 * because the driver always provides a callback function to
6752 	 * scsi_init_pkt. This results in a callback always being scheduled
6753 	 * (via the scsi_init_pkt callback implementation) if a resource
6754 	 * failure occurs.
6755 	 */
6756 
6757 	return (1);
6758 }
6759 
6760 /*
6761  * st_done_and_mutex_exit()
6762  *	- remove bp from runq
6763  *	- start up the next request
6764  *	- if this was an asynch bp, clean up
6765  *	- exit with released mutex
6766  */
6767 static void
6768 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6769 {
6770 	int pe_flagged = 0;
6771 	struct scsi_pkt *pkt = BP_PKT(bp);
6772 	pkt_info *pktinfo = pkt->pkt_private;
6773 
6774 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6775 #if !defined(lint)
6776 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6777 #endif
6778 
6779 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6780 
6781 	ASSERT(mutex_owned(ST_MUTEX));
6782 
6783 	(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6784 
6785 	un->un_ncmds--;
6786 	cv_signal(&un->un_queue_cv);
6787 
6788 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6789 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6790 	    "0x%x\n", pkt->pkt_cdbp[0], bp->b_bcount,
6791 	    bp->b_resid, bp->b_flags);
6792 
6793 
6794 	/*
6795 	 * update kstats with transfer count info
6796 	 */
6797 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6798 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6799 		if (bp->b_flags & B_READ) {
6800 			IOSP->reads++;
6801 			IOSP->nread += n_done;
6802 		} else {
6803 			IOSP->writes++;
6804 			IOSP->nwritten += n_done;
6805 		}
6806 	}
6807 
6808 	/*
6809 	 * Start the next one before releasing resources on this one, if
6810 	 * there is something on the queue and persistent errors has not been
6811 	 * flagged
6812 	 */
6813 
6814 	if ((pe_flagged = (un->un_persistence && un->un_persist_errors)) != 0) {
6815 		un->un_last_resid = bp->b_resid;
6816 		un->un_last_count = bp->b_bcount;
6817 	}
6818 
6819 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6820 		cv_broadcast(&un->un_tape_busy_cv);
6821 	} else if (un->un_quef && un->un_throttle && !pe_flagged &&
6822 	    (bp != un->un_recov_buf)) {
6823 		st_start(un);
6824 	}
6825 
6826 	un->un_retry_ct = max(pktinfo->pkt_retry_cnt, pktinfo->str_retry_cnt);
6827 
6828 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6829 		/*
6830 		 * Since we marked this ourselves as ASYNC,
6831 		 * there isn't anybody around waiting for
6832 		 * completion any more.
6833 		 */
6834 		uchar_t *cmd = pkt->pkt_cdbp;
6835 		if (*cmd == SCMD_READ || *cmd == SCMD_WRITE) {
6836 			bp->b_un.b_addr = (caddr_t)0;
6837 		}
6838 		ST_DEBUG(ST_DEVINFO, st_label, CE_NOTE,
6839 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6840 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
6841 		    "CDB sent with B_ASYNC",  (caddr_t)cmd);
6842 		if (pkt) {
6843 			scsi_destroy_pkt(pkt);
6844 		}
6845 		un->un_sbuf_busy = 0;
6846 		cv_signal(&un->un_sbuf_cv);
6847 		mutex_exit(ST_MUTEX);
6848 		return;
6849 	}
6850 
6851 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6852 		/*
6853 		 * Copy status from scsi_pkt to uscsi_cmd
6854 		 * since st_uscsi_cmd needs it
6855 		 */
6856 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6857 	}
6858 
6859 
6860 #ifdef STDEBUG
6861 	if (((st_debug & 0x7) >= 4) &&
6862 	    (((un->un_pos.blkno % 100) == 0) ||
6863 	    (un->un_persistence && un->un_persist_errors))) {
6864 
6865 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6866 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6867 		    "un_errno = %d, un_pe = %d\n",
6868 		    un->un_ncmds, un->un_throttle, un->un_errno,
6869 		    un->un_persist_errors);
6870 	}
6871 
6872 #endif
6873 
6874 	mutex_exit(ST_MUTEX);
6875 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6876 	    "st_done_and_mutex_exit: freeing pkt\n");
6877 
6878 	if (pkt) {
6879 		scsi_destroy_pkt(pkt);
6880 	}
6881 
6882 	biodone(bp);
6883 
6884 	/*
6885 	 * now that we biodoned that command, if persistent errors have been
6886 	 * flagged, flush the waitq
6887 	 */
6888 	if (pe_flagged)
6889 		st_flush(un);
6890 }
6891 
6892 
6893 /*
6894  * Tape error, flush tape driver queue.
6895  */
6896 static void
6897 st_flush(struct scsi_tape *un)
6898 {
6899 	struct buf *bp;
6900 
6901 	ST_FUNC(ST_DEVINFO, st_flush);
6902 
6903 	mutex_enter(ST_MUTEX);
6904 
6905 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6906 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6907 	    un->un_ncmds, (void *)un->un_quef);
6908 
6909 	/*
6910 	 * if we still have commands outstanding, wait for them to come in
6911 	 * before flushing the queue, and make sure there is a queue
6912 	 */
6913 	if (un->un_ncmds || !un->un_quef)
6914 		goto exit;
6915 
6916 	/*
6917 	 * we have no more commands outstanding, so let's deal with special
6918 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6919 	 * is 0, then we know there was no error and we return a 0 read or
6920 	 * write before showing errors
6921 	 */
6922 
6923 	/* Flush the wait queue. */
6924 	while ((bp = un->un_quef) != NULL) {
6925 		un->un_quef = bp->b_actf;
6926 
6927 		bp->b_resid = bp->b_bcount;
6928 
6929 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6930 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6931 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6932 
6933 		st_set_pe_errno(un);
6934 
6935 		bioerror(bp, un->un_errno);
6936 
6937 		mutex_exit(ST_MUTEX);
6938 		/* it should have one, but check anyway */
6939 		if (BP_PKT(bp)) {
6940 			scsi_destroy_pkt(BP_PKT(bp));
6941 		}
6942 		biodone(bp);
6943 		mutex_enter(ST_MUTEX);
6944 	}
6945 
6946 	/*
6947 	 * It's not a bad practice to reset the
6948 	 * waitq tail pointer to NULL.
6949 	 */
6950 	un->un_quel = NULL;
6951 
6952 exit:
6953 	/* we mucked with the queue, so let others know about it */
6954 	cv_signal(&un->un_queue_cv);
6955 	mutex_exit(ST_MUTEX);
6956 }
6957 
6958 
6959 /*
6960  * Utility functions
6961  */
6962 static int
6963 st_determine_generic(struct scsi_tape *un)
6964 {
6965 	int bsize;
6966 	static char *cart = "0.25 inch cartridge";
6967 	char *sizestr;
6968 
6969 	ST_FUNC(ST_DEVINFO, st_determine_generic);
6970 
6971 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6972 	    "st_determine_generic(un = 0x%p)\n", (void*)un);
6973 
6974 	ASSERT(mutex_owned(ST_MUTEX));
6975 
6976 	if (st_modesense(un)) {
6977 		return (-1);
6978 	}
6979 
6980 	bsize = (un->un_mspl->high_bl << 16)	|
6981 	    (un->un_mspl->mid_bl << 8)	|
6982 	    (un->un_mspl->low_bl);
6983 
6984 	if (bsize == 0) {
6985 		un->un_dp->options |= ST_VARIABLE;
6986 		un->un_dp->bsize = 0;
6987 		un->un_bsize = 0;
6988 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
6989 		/*
6990 		 * record size of this device too big.
6991 		 * try and convert it to variable record length.
6992 		 *
6993 		 */
6994 		un->un_dp->options |= ST_VARIABLE;
6995 		if (st_change_block_size(un, 0) != 0) {
6996 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6997 			    "Fixed Record Size %d is too large\n", bsize);
6998 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6999 			    "Cannot switch to variable record size\n");
7000 			un->un_dp->options &= ~ST_VARIABLE;
7001 			return (-1);
7002 		}
7003 	} else if (st_change_block_size(un, 0) == 0) {
7004 		/*
7005 		 * If the drive was set to a non zero block size,
7006 		 * See if it can be set to a zero block size.
7007 		 * If it works, ST_VARIABLE so user can set it as they want.
7008 		 */
7009 		un->un_dp->options |= ST_VARIABLE;
7010 		un->un_dp->bsize = 0;
7011 		un->un_bsize = 0;
7012 	} else {
7013 		un->un_dp->bsize = bsize;
7014 		un->un_bsize = bsize;
7015 	}
7016 
7017 
7018 	switch (un->un_mspl->density) {
7019 	default:
7020 	case 0x0:
7021 		/*
7022 		 * default density, cannot determine any other
7023 		 * information.
7024 		 */
7025 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
7026 		un->un_dp->type = ST_TYPE_DEFAULT;
7027 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
7028 		break;
7029 	case 0x1:
7030 	case 0x2:
7031 	case 0x3:
7032 	case 0x6:
7033 		/*
7034 		 * 1/2" reel
7035 		 */
7036 		sizestr = "0.50 inch reel";
7037 		un->un_dp->type = ST_TYPE_REEL;
7038 		un->un_dp->options |= ST_REEL;
7039 		un->un_dp->densities[0] = 0x1;
7040 		un->un_dp->densities[1] = 0x2;
7041 		un->un_dp->densities[2] = 0x6;
7042 		un->un_dp->densities[3] = 0x3;
7043 		break;
7044 	case 0x4:
7045 	case 0x5:
7046 	case 0x7:
7047 	case 0x0b:
7048 
7049 		/*
7050 		 * Quarter inch.
7051 		 */
7052 		sizestr = cart;
7053 		un->un_dp->type = ST_TYPE_DEFAULT;
7054 		un->un_dp->options |= ST_QIC;
7055 
7056 		un->un_dp->densities[1] = 0x4;
7057 		un->un_dp->densities[2] = 0x5;
7058 		un->un_dp->densities[3] = 0x7;
7059 		un->un_dp->densities[0] = 0x0b;
7060 		break;
7061 
7062 	case 0x0f:
7063 	case 0x10:
7064 	case 0x11:
7065 	case 0x12:
7066 		/*
7067 		 * QIC-120, QIC-150, QIC-320, QIC-600
7068 		 */
7069 		sizestr = cart;
7070 		un->un_dp->type = ST_TYPE_DEFAULT;
7071 		un->un_dp->options |= ST_QIC;
7072 		un->un_dp->densities[0] = 0x0f;
7073 		un->un_dp->densities[1] = 0x10;
7074 		un->un_dp->densities[2] = 0x11;
7075 		un->un_dp->densities[3] = 0x12;
7076 		break;
7077 
7078 	case 0x09:
7079 	case 0x0a:
7080 	case 0x0c:
7081 	case 0x0d:
7082 		/*
7083 		 * 1/2" cartridge tapes. Include HI-TC.
7084 		 */
7085 		sizestr = cart;
7086 		sizestr[2] = '5';
7087 		sizestr[3] = '0';
7088 		un->un_dp->type = ST_TYPE_HIC;
7089 		un->un_dp->densities[0] = 0x09;
7090 		un->un_dp->densities[1] = 0x0a;
7091 		un->un_dp->densities[2] = 0x0c;
7092 		un->un_dp->densities[3] = 0x0d;
7093 		break;
7094 
7095 	case 0x13:
7096 			/* DDS-2/DDS-3 scsi spec densities */
7097 	case 0x24:
7098 	case 0x25:
7099 	case 0x26:
7100 		sizestr = "DAT Data Storage (DDS)";
7101 		un->un_dp->type = ST_TYPE_DAT;
7102 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7103 		break;
7104 
7105 	case 0x14:
7106 		/*
7107 		 * Helical Scan (Exabyte) devices
7108 		 */
7109 		sizestr = "8mm helical scan cartridge";
7110 		un->un_dp->type = ST_TYPE_EXABYTE;
7111 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7112 		break;
7113 	}
7114 
7115 	/*
7116 	 * Assume LONG ERASE, BSF and BSR
7117 	 */
7118 
7119 	un->un_dp->options |=
7120 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
7121 
7122 	/*
7123 	 * Only if mode sense data says no buffered write, set NOBUF
7124 	 */
7125 	if (un->un_mspl->bufm == 0)
7126 		un->un_dp->options |= ST_NOBUF;
7127 
7128 	/*
7129 	 * set up large read and write retry counts
7130 	 */
7131 
7132 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
7133 
7134 	/*
7135 	 * If this is a 0.50 inch reel tape, and
7136 	 * it is *not* variable mode, try and
7137 	 * set it to variable record length
7138 	 * mode.
7139 	 */
7140 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
7141 	    (un->un_dp->options & ST_VARIABLE)) {
7142 		if (st_change_block_size(un, 0) == 0) {
7143 			un->un_dp->bsize = 0;
7144 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
7145 			    un->un_mspl->low_bl = 0;
7146 		}
7147 	}
7148 
7149 	/*
7150 	 * Write to console about type of device found
7151 	 */
7152 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
7153 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
7154 	    sizestr);
7155 	if (un->un_dp->options & ST_VARIABLE) {
7156 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7157 		    "!Variable record length I/O\n");
7158 	} else {
7159 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7160 		    "!Fixed record length (%d byte blocks) I/O\n",
7161 		    un->un_dp->bsize);
7162 	}
7163 	ASSERT(mutex_owned(ST_MUTEX));
7164 	return (0);
7165 }
7166 
7167 static int
7168 st_determine_density(struct scsi_tape *un, int rw)
7169 {
7170 	int rval = 0;
7171 
7172 	ST_FUNC(ST_DEVINFO, st_determine_density);
7173 
7174 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7175 	    "st_determine_density(un = 0x%p, rw = %s)\n",
7176 	    (void*)un, (rw == B_WRITE ? wr_str: rd_str));
7177 
7178 	ASSERT(mutex_owned(ST_MUTEX));
7179 
7180 	/*
7181 	 * If we're past BOT, density is determined already.
7182 	 */
7183 	if (un->un_pos.pmode == logical) {
7184 		if (un->un_pos.lgclblkno != 0) {
7185 			goto exit;
7186 		}
7187 	} else if (un->un_pos.pmode == legacy) {
7188 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
7189 			/*
7190 			 * XXX: put in a bitch message about attempting to
7191 			 * XXX: change density past BOT.
7192 			 */
7193 			goto exit;
7194 		}
7195 	} else {
7196 		goto exit;
7197 	}
7198 	if ((un->un_pos.pmode == logical) &&
7199 	    (un->un_pos.lgclblkno != 0)) {
7200 		goto exit;
7201 	}
7202 
7203 
7204 	/*
7205 	 * If we're going to be writing, we set the density
7206 	 */
7207 	if (rw == 0 || rw == B_WRITE) {
7208 		/* un_curdens is used as an index into densities table */
7209 		un->un_curdens = MT_DENSITY(un->un_dev);
7210 		if (st_set_density(un)) {
7211 			rval = -1;
7212 		}
7213 		goto exit;
7214 	}
7215 
7216 	/*
7217 	 * If density is known already,
7218 	 * we don't have to get it again.(?)
7219 	 */
7220 	if (!un->un_density_known) {
7221 		if (st_get_density(un)) {
7222 			rval = -1;
7223 		}
7224 	}
7225 
7226 exit:
7227 	ASSERT(mutex_owned(ST_MUTEX));
7228 	return (rval);
7229 }
7230 
7231 
7232 /*
7233  * Try to determine density. We do this by attempting to read the
7234  * first record off the tape, cycling through the available density
7235  * codes as we go.
7236  */
7237 
7238 static int
7239 st_get_density(struct scsi_tape *un)
7240 {
7241 	int succes = 0, rval = -1, i;
7242 	uint_t size;
7243 	uchar_t dens, olddens;
7244 
7245 	ST_FUNC(ST_DEVINFO, st_get_density);
7246 
7247 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7248 	    "st_get_density(un = 0x%p)\n", (void*)un);
7249 
7250 	ASSERT(mutex_owned(ST_MUTEX));
7251 
7252 	/*
7253 	 * If Auto Density override is enabled The drive has
7254 	 * only one density and there is no point in attempting
7255 	 * find the correct one.
7256 	 *
7257 	 * Since most modern drives auto detect the density
7258 	 * and format of the recorded media before they come
7259 	 * ready. What this function does is a legacy behavior
7260 	 * and modern drives not only don't need it, The backup
7261 	 * utilities that do positioning via uscsi find the un-
7262 	 * expected rewinds problematic.
7263 	 *
7264 	 * The drives that need this are old reel to reel devices.
7265 	 * I took a swag and said they must be scsi-1 or older.
7266 	 * I don't beleave there will any of the newer devices
7267 	 * that need this. There will be some scsi-1 devices that
7268 	 * don't need this but I don't think they will be using the
7269 	 * BIG aftermarket backup and restore utilitys.
7270 	 */
7271 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
7272 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
7273 		un->un_density_known = 1;
7274 		rval = 0;
7275 		goto exit;
7276 	}
7277 
7278 	/*
7279 	 * This will only work on variable record length tapes
7280 	 * if and only if all variable record length tapes autodensity
7281 	 * select.
7282 	 */
7283 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
7284 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
7285 
7286 	/*
7287 	 * Start at the specified density
7288 	 */
7289 
7290 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
7291 
7292 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
7293 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
7294 		/*
7295 		 * If we've done this density before,
7296 		 * don't bother to do it again.
7297 		 */
7298 		dens = un->un_dp->densities[un->un_curdens];
7299 		if (i > 0 && dens == olddens)
7300 			continue;
7301 		olddens = dens;
7302 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7303 		    "trying density 0x%x\n", dens);
7304 		if (st_set_density(un)) {
7305 			continue;
7306 		}
7307 
7308 		/*
7309 		 * XXX - the creates lots of headaches and slowdowns - must
7310 		 * fix.
7311 		 */
7312 		succes = (st_cmd(un, SCMD_READ, (int)size, SYNC_CMD) == 0);
7313 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
7314 			break;
7315 		}
7316 		if (succes) {
7317 			st_init(un);
7318 			rval = 0;
7319 			un->un_density_known = 1;
7320 			break;
7321 		}
7322 	}
7323 	kmem_free(un->un_tmpbuf, size);
7324 	un->un_tmpbuf = 0;
7325 
7326 exit:
7327 	ASSERT(mutex_owned(ST_MUTEX));
7328 	return (rval);
7329 }
7330 
7331 static int
7332 st_set_density(struct scsi_tape *un)
7333 {
7334 	int rval = 0;
7335 
7336 	ST_FUNC(ST_DEVINFO, st_set_density);
7337 
7338 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7339 	    "st_set_density(un = 0x%p): density = 0x%x\n", (void*)un,
7340 	    un->un_dp->densities[un->un_curdens]);
7341 
7342 	ASSERT(mutex_owned(ST_MUTEX));
7343 
7344 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7345 
7346 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
7347 		/*
7348 		 * If auto density override is not set, Use mode select
7349 		 * to set density and compression.
7350 		 */
7351 		if (st_modeselect(un)) {
7352 			rval = -1;
7353 		}
7354 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
7355 		/*
7356 		 * If auto density and mode select compression are set,
7357 		 * This is a drive with one density code but compression
7358 		 * can be enabled or disabled.
7359 		 * Set compression but no need to set density.
7360 		 */
7361 		rval = st_set_compression(un);
7362 		if ((rval != 0) && (rval != EALREADY)) {
7363 			rval = -1;
7364 		} else {
7365 			rval = 0;
7366 		}
7367 	}
7368 
7369 	/* If sucessful set density and/or compression, mark density known */
7370 	if (rval == 0) {
7371 		un->un_density_known = 1;
7372 	}
7373 
7374 	ASSERT(mutex_owned(ST_MUTEX));
7375 	return (rval);
7376 }
7377 
7378 static int
7379 st_loadtape(struct scsi_tape *un)
7380 {
7381 	int rval;
7382 
7383 	ST_FUNC(ST_DEVINFO, st_loadtape);
7384 
7385 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7386 	    "st_loadtape(un = 0x%p)\n", (void*) un);
7387 
7388 	ASSERT(mutex_owned(ST_MUTEX));
7389 
7390 	rval = st_update_block_pos(un, st_cmd, 0);
7391 	if (rval == EACCES) {
7392 		return (rval);
7393 	}
7394 
7395 	/*
7396 	 * 'LOAD' the tape to BOT by rewinding
7397 	 */
7398 	rval = st_cmd(un, SCMD_REWIND, 1, SYNC_CMD);
7399 	if (rval == 0) {
7400 		st_init(un);
7401 		un->un_density_known = 0;
7402 	}
7403 
7404 	ASSERT(mutex_owned(ST_MUTEX));
7405 	return (rval);
7406 }
7407 
7408 
7409 /*
7410  * Note: QIC devices aren't so smart.  If you try to append
7411  * after EOM, the write can fail because the device doesn't know
7412  * it's at EOM.	 In that case, issue a read.  The read should fail
7413  * because there's no data, but the device knows it's at EOM,
7414  * so a subsequent write should succeed.  To further confuse matters,
7415  * the target returns the same error if the tape is positioned
7416  * such that a write would overwrite existing data.  That's why
7417  * we have to do the append test.  A read in the middle of
7418  * recorded data would succeed, thus indicating we're attempting
7419  * something illegal.
7420  */
7421 
7422 
7423 static void
7424 st_test_append(struct buf *bp)
7425 {
7426 	dev_t dev = bp->b_edev;
7427 	struct scsi_tape *un;
7428 	uchar_t status;
7429 	unsigned bcount;
7430 
7431 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7432 
7433 	ST_FUNC(ST_DEVINFO, st_test_append);
7434 
7435 	ASSERT(mutex_owned(ST_MUTEX));
7436 
7437 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7438 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7439 
7440 	un->un_laststate = un->un_state;
7441 	un->un_state = ST_STATE_APPEND_TESTING;
7442 	un->un_test_append = 0;
7443 
7444 	/*
7445 	 * first, map in the buffer, because we're doing a double write --
7446 	 * first into the kernel, then onto the tape.
7447 	 */
7448 	bp_mapin(bp);
7449 
7450 	/*
7451 	 * get a copy of the data....
7452 	 */
7453 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7454 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7455 
7456 	/*
7457 	 * attempt the write..
7458 	 */
7459 
7460 	if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7461 success:
7462 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7463 		    "append write succeeded\n");
7464 		bp->b_resid = un->un_sbufp->b_resid;
7465 		mutex_exit(ST_MUTEX);
7466 		bcount = (unsigned)bp->b_bcount;
7467 		biodone(bp);
7468 		mutex_enter(ST_MUTEX);
7469 		un->un_laststate = un->un_state;
7470 		un->un_state = ST_STATE_OPEN;
7471 		kmem_free(un->un_tmpbuf, bcount);
7472 		un->un_tmpbuf = NULL;
7473 		return;
7474 	}
7475 
7476 	/*
7477 	 * The append failed. Do a short read. If that fails,  we are at EOM
7478 	 * so we can retry the write command. If that succeeds, than we're
7479 	 * all screwed up (the controller reported a real error).
7480 	 *
7481 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7482 	 * XXX: block size?
7483 	 *
7484 	 */
7485 	status = un->un_status;
7486 	un->un_status = 0;
7487 	(void) st_cmd(un, SCMD_READ, SECSIZE, SYNC_CMD);
7488 	if (un->un_status == KEY_BLANK_CHECK) {
7489 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7490 		    "append at EOM\n");
7491 		/*
7492 		 * Okay- the read failed. We should actually have confused
7493 		 * the controller enough to allow writing. In any case, the
7494 		 * i/o is on its own from here on out.
7495 		 */
7496 		un->un_laststate = un->un_state;
7497 		un->un_state = ST_STATE_OPEN;
7498 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7499 		if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount,
7500 		    SYNC_CMD) == 0) {
7501 			goto success;
7502 		}
7503 	}
7504 
7505 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7506 	    "append write failed- not at EOM\n");
7507 	bp->b_resid = bp->b_bcount;
7508 	st_bioerror(bp, EIO);
7509 
7510 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7511 	    "st_test_append : EIO : append write failed - not at EOM");
7512 
7513 	/*
7514 	 * backspace one record to get back to where we were
7515 	 */
7516 	if (st_cmd(un, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7517 		un->un_pos.pmode = invalid;
7518 	}
7519 
7520 	un->un_err_resid = bp->b_resid;
7521 	un->un_status = status;
7522 
7523 	/*
7524 	 * Note: biodone will do a bp_mapout()
7525 	 */
7526 	mutex_exit(ST_MUTEX);
7527 	bcount = (unsigned)bp->b_bcount;
7528 	biodone(bp);
7529 	mutex_enter(ST_MUTEX);
7530 	un->un_laststate = un->un_state;
7531 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7532 	kmem_free(un->un_tmpbuf, bcount);
7533 	un->un_tmpbuf = NULL;
7534 }
7535 
7536 /*
7537  * Special command handler
7538  */
7539 
7540 /*
7541  * common st_cmd code. The fourth parameter states
7542  * whether the caller wishes to await the results
7543  * Note the release of the mutex during most of the function
7544  */
7545 static int
7546 st_cmd(struct scsi_tape *un, int com, int64_t count, int wait)
7547 {
7548 	struct buf *bp;
7549 	int err;
7550 	uint_t last_err_resid;
7551 
7552 	ST_FUNC(ST_DEVINFO, st_cmd);
7553 
7554 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7555 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %"PRIx64", wait = %d)\n",
7556 	    un->un_dev, com, count, wait);
7557 
7558 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7559 	ASSERT(mutex_owned(ST_MUTEX));
7560 
7561 #ifdef STDEBUG
7562 	if ((st_debug & 0x7)) {
7563 		st_debug_cmds(un, com, count, wait);
7564 	}
7565 #endif
7566 
7567 	st_wait_for_io(un);
7568 
7569 	/* check to see if this command requires the drive to be reserved */
7570 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7571 
7572 	if (err) {
7573 		return (err);
7574 	}
7575 
7576 	/*
7577 	 * A space command is not recoverable if we don't know were we
7578 	 * were when it was issued.
7579 	 */
7580 	if ((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) {
7581 		(void) st_update_block_pos(un, st_cmd, 0);
7582 	}
7583 
7584 	/*
7585 	 * Forground should not be doing anything while recovery is active.
7586 	 */
7587 	ASSERT(un->un_recov_buf_busy == 0);
7588 
7589 	while (un->un_sbuf_busy)
7590 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7591 	un->un_sbuf_busy = 1;
7592 
7593 	bp = un->un_sbufp;
7594 	bzero(bp, sizeof (buf_t));
7595 
7596 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7597 
7598 	err = st_setup_cmd(un, bp, com, count);
7599 
7600 	un->un_sbuf_busy = 0;
7601 
7602 	/*
7603 	 * If was a space command need to update logical block position.
7604 	 * Only do this if the command was sucessful or it will mask the fact
7605 	 * that the space command failed by promoting the pmode to logical.
7606 	 */
7607 	if (((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) &&
7608 	    (un->un_pos.pmode != invalid)) {
7609 		un->un_running.pmode = invalid;
7610 		last_err_resid = un->un_err_resid;
7611 		(void) st_update_block_pos(un, st_cmd, 1);
7612 		/*
7613 		 * Set running position to invalid so it updates on the
7614 		 * next command.
7615 		 */
7616 		un->un_running.pmode = invalid;
7617 		un->un_err_resid = last_err_resid;
7618 	}
7619 
7620 	cv_signal(&un->un_sbuf_cv);
7621 
7622 	return (err);
7623 }
7624 
7625 static int
7626 st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com, int64_t count)
7627 {
7628 	int err;
7629 	dev_t dev = un->un_dev;
7630 
7631 	ST_FUNC(ST_DEVINFO, st_setup_cmd);
7632 	/*
7633 	 * Set count to the actual size of the data tranfer.
7634 	 * For commands with no data transfer, set bp->b_bcount
7635 	 * to the value to be used when constructing the
7636 	 * cdb in st_make_cmd().
7637 	 */
7638 	switch (com) {
7639 	case SCMD_READ:
7640 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7641 		    "special read %"PRId64"\n", count);
7642 		bp->b_flags |= B_READ;
7643 		bp->b_un.b_addr = un->un_tmpbuf;
7644 		break;
7645 
7646 	case SCMD_WRITE:
7647 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7648 		    "special write %"PRId64"\n", count);
7649 		bp->b_un.b_addr = un->un_tmpbuf;
7650 		break;
7651 
7652 	case SCMD_WRITE_FILE_MARK:
7653 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7654 		    "write %"PRId64" file marks\n", count);
7655 		bp->b_bcount = count;
7656 		count = 0;
7657 		break;
7658 
7659 	case SCMD_REWIND:
7660 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7661 		bp->b_bcount = count;
7662 		count = 0;
7663 		break;
7664 
7665 	case SCMD_SPACE:
7666 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7667 		/*
7668 		 * If the user could have entered a number that will
7669 		 * not fit in the 12 bit count field of space(8),
7670 		 * use space(16).
7671 		 */
7672 		if (((int64_t)SPACE_CNT(count) > 0x7fffff) ||
7673 		    ((int64_t)SPACE_CNT(count) < -(0x7fffff))) {
7674 			com = SCMD_SPACE_G4;
7675 		}
7676 		bp->b_bcount = count;
7677 		count = 0;
7678 		break;
7679 
7680 	case SCMD_RESERVE:
7681 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7682 		bp->b_bcount = 0;
7683 		count = 0;
7684 		break;
7685 
7686 	case SCMD_RELEASE:
7687 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7688 		bp->b_bcount = 0;
7689 		count = 0;
7690 		break;
7691 
7692 	case SCMD_LOAD:
7693 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7694 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7695 		bp->b_bcount = count;
7696 		count = 0;
7697 		break;
7698 
7699 	case SCMD_ERASE:
7700 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7701 		    "erase tape\n");
7702 		bp->b_bcount = count;
7703 		count = 0;
7704 		break;
7705 
7706 	case SCMD_MODE_SENSE:
7707 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7708 		    "mode sense\n");
7709 		bp->b_flags |= B_READ;
7710 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7711 		break;
7712 
7713 	case SCMD_MODE_SELECT:
7714 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7715 		    "mode select\n");
7716 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7717 		break;
7718 
7719 	case SCMD_READ_BLKLIM:
7720 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7721 		    "read block limits\n");
7722 		bp->b_bcount = count;
7723 		bp->b_flags |= B_READ;
7724 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7725 		break;
7726 
7727 	case SCMD_TEST_UNIT_READY:
7728 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7729 		    "test unit ready\n");
7730 		bp->b_bcount = 0;
7731 		count = 0;
7732 		break;
7733 
7734 	case SCMD_DOORLOCK:
7735 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7736 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7737 		bp->b_bcount = count = 0;
7738 		break;
7739 
7740 	case SCMD_READ_POSITION:
7741 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7742 		    "read position\n");
7743 		switch (un->un_read_pos_type) {
7744 		case LONG_POS:
7745 			count = sizeof (tape_position_long_t);
7746 			break;
7747 		case EXT_POS:
7748 			count = min(count, sizeof (tape_position_ext_t));
7749 			break;
7750 		case SHORT_POS:
7751 			count = sizeof (tape_position_t);
7752 			break;
7753 		default:
7754 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7755 			    "Unknown read position type 0x%x in "
7756 			    "st_make_cmd()\n", un->un_read_pos_type);
7757 		}
7758 		bp->b_bcount = count;
7759 		bp->b_flags |= B_READ;
7760 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7761 		break;
7762 
7763 	default:
7764 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7765 		    "Unhandled scsi command 0x%x in st_setup_cmd()\n", com);
7766 	}
7767 
7768 	mutex_exit(ST_MUTEX);
7769 
7770 	if (count > 0) {
7771 		int flg = (bp->b_flags & B_READ) ? B_READ : B_WRITE;
7772 		/*
7773 		 * We're going to do actual I/O.
7774 		 * Set things up for physio.
7775 		 */
7776 		struct iovec aiov;
7777 		struct uio auio;
7778 		struct uio *uio = &auio;
7779 
7780 		bzero(&auio, sizeof (struct uio));
7781 		bzero(&aiov, sizeof (struct iovec));
7782 		aiov.iov_base = bp->b_un.b_addr;
7783 		aiov.iov_len = count;
7784 
7785 		uio->uio_iov = &aiov;
7786 		uio->uio_iovcnt = 1;
7787 		uio->uio_resid = aiov.iov_len;
7788 		uio->uio_segflg = UIO_SYSSPACE;
7789 
7790 		/*
7791 		 * Let physio do the rest...
7792 		 */
7793 		bp->b_forw = (struct buf *)(uintptr_t)com;
7794 		bp->b_back = NULL;
7795 		err = physio(st_strategy, bp, dev, flg, st_minphys, uio);
7796 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7797 		    "st_setup_cmd: physio returns %d\n", err);
7798 	} else {
7799 		/*
7800 		 * Mimic physio
7801 		 */
7802 		bp->b_forw = (struct buf *)(uintptr_t)com;
7803 		bp->b_back = NULL;
7804 		bp->b_edev = dev;
7805 		bp->b_dev = cmpdev(dev);
7806 		bp->b_blkno = 0;
7807 		bp->b_resid = 0;
7808 		(void) st_strategy(bp);
7809 		if (bp->b_flags & B_ASYNC) {
7810 			/*
7811 			 * This is an async command- the caller won't wait
7812 			 * and doesn't care about errors.
7813 			 */
7814 			mutex_enter(ST_MUTEX);
7815 			return (0);
7816 		}
7817 
7818 		/*
7819 		 * BugTraq #4260046
7820 		 * ----------------
7821 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7822 		 * unconditionally. The old comment said...
7823 		 *
7824 		 * "if strategy was flagged with  persistent errors, we would
7825 		 *  have an error here, and the bp would never be sent, so we
7826 		 *  don't want to wait on a bp that was never sent...or hang"
7827 		 *
7828 		 * The new rationale, courtesy of Chitrank...
7829 		 *
7830 		 * "we should unconditionally biowait() here because
7831 		 *  st_strategy() will do a biodone() in the persistent error
7832 		 *  case and the following biowait() will return immediately.
7833 		 *  If not, in the case of "errors after pkt alloc" in
7834 		 *  st_start(), we will not biowait here which will cause the
7835 		 *  next biowait() to return immediately which will cause
7836 		 *  us to send out the next command. In the case where both of
7837 		 *  these use the sbuf, when the first command completes we'll
7838 		 *  free the packet attached to sbuf and the same pkt will
7839 		 *  get freed again when we complete the second command.
7840 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7841 		 *  st_start() for the pkt alloc failure case because physio()
7842 		 *  does biowait() and will hang if we don't do biodone()"
7843 		 */
7844 
7845 		err = biowait(bp);
7846 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7847 		    "st_setup_cmd: biowait returns %d\n", err);
7848 	}
7849 
7850 	mutex_enter(ST_MUTEX);
7851 
7852 	return (err);
7853 }
7854 
7855 static int
7856 st_set_compression(struct scsi_tape *un)
7857 {
7858 	int rval;
7859 	int turn_compression_on;
7860 	minor_t minor;
7861 
7862 	ST_FUNC(ST_DEVINFO, st_set_compression);
7863 
7864 	/*
7865 	 * Drive either dosn't have compression or it is controlled with
7866 	 * special density codes. Return ENOTTY so caller
7867 	 * knows nothing was done.
7868 	 */
7869 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7870 		un->un_comp_page = 0;
7871 		return (ENOTTY);
7872 	}
7873 
7874 	/* set compression based on minor node opened */
7875 	minor = MT_DENSITY(un->un_dev);
7876 
7877 	/*
7878 	 * If this the compression density or
7879 	 * the drive has two densities and uses mode select for
7880 	 * control of compression turn on compression for MT_DENSITY2
7881 	 * as well.
7882 	 */
7883 	if ((minor == ST_COMPRESSION_DENSITY) ||
7884 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7885 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7886 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7887 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7888 
7889 		turn_compression_on = 1;
7890 	} else {
7891 		turn_compression_on = 0;
7892 	}
7893 
7894 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7895 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7896 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7897 
7898 	/*
7899 	 * Need to determine which page does the device use for compression.
7900 	 * First try the data compression page. If this fails try the device
7901 	 * configuration page
7902 	 */
7903 
7904 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7905 		rval = st_set_datacomp_page(un, turn_compression_on);
7906 		if (rval == EALREADY) {
7907 			return (rval);
7908 		}
7909 		if (rval != 0) {
7910 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7911 				/*
7912 				 * This device does not support data
7913 				 * compression page
7914 				 */
7915 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7916 			} else if (un->un_state >= ST_STATE_OPEN) {
7917 				un->un_pos.pmode = invalid;
7918 				rval = EIO;
7919 			} else {
7920 				rval = -1;
7921 			}
7922 		} else {
7923 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7924 		}
7925 	}
7926 
7927 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7928 		rval = st_set_devconfig_page(un, turn_compression_on);
7929 		if (rval == EALREADY) {
7930 			return (rval);
7931 		}
7932 		if (rval != 0) {
7933 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7934 				/*
7935 				 * This device does not support
7936 				 * compression at all advice the
7937 				 * user and unset ST_MODE_SEL_COMP
7938 				 */
7939 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7940 				un->un_comp_page = 0;
7941 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7942 				    "Device Does Not Support Compression\n");
7943 			} else if (un->un_state >= ST_STATE_OPEN) {
7944 				un->un_pos.pmode = invalid;
7945 				rval = EIO;
7946 			} else {
7947 				rval = -1;
7948 			}
7949 		}
7950 	}
7951 
7952 	return (rval);
7953 }
7954 
7955 /*
7956  * set or unset compression thru device configuration page.
7957  */
7958 static int
7959 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
7960 {
7961 	unsigned char cflag;
7962 	int rval = 0;
7963 
7964 
7965 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
7966 
7967 	ASSERT(mutex_owned(ST_MUTEX));
7968 	/*
7969 	 * Figure what to set compression flag to.
7970 	 */
7971 	if (compression_on) {
7972 		/* They have selected a compression node */
7973 		if (un->un_dp->type == ST_TYPE_FUJI) {
7974 			cflag = 0x84;   /* use EDRC */
7975 		} else {
7976 			cflag = ST_DEV_CONFIG_DEF_COMP;
7977 		}
7978 	} else {
7979 		cflag = ST_DEV_CONFIG_NO_COMP;
7980 	}
7981 
7982 	/*
7983 	 * If compression is already set the way it was requested.
7984 	 * And if this not the first time we has tried.
7985 	 */
7986 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
7987 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7988 		return (EALREADY);
7989 	}
7990 
7991 	un->un_mspl->page.dev.comp_alg = cflag;
7992 	/*
7993 	 * need to send mode select even if correct compression is
7994 	 * already set since need to set density code
7995 	 */
7996 
7997 #ifdef STDEBUG
7998 	if ((st_debug & 0x7) >= 6) {
7999 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8000 		    "st_set_devconfig_page: sense data for mode select",
8001 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8002 	}
8003 #endif
8004 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8005 	    sizeof (struct seq_mode));
8006 
8007 	return (rval);
8008 }
8009 
8010 /*
8011  * set/reset compression bit thru data compression page
8012  */
8013 static int
8014 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
8015 {
8016 	int compression_on_already;
8017 	int rval = 0;
8018 
8019 
8020 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
8021 
8022 	ASSERT(mutex_owned(ST_MUTEX));
8023 	/*
8024 	 * If drive is not capable of compression (at this time)
8025 	 * return EALREADY so caller doesn't think that this page
8026 	 * is not supported. This check is for drives that can
8027 	 * disable compression from the front panel or configuration.
8028 	 * I doubt that a drive that supports this page is not really
8029 	 * capable of compression.
8030 	 */
8031 	if (un->un_mspl->page.comp.dcc == 0) {
8032 		return (EALREADY);
8033 	}
8034 
8035 	/* See if compression currently turned on */
8036 	if (un->un_mspl->page.comp.dce) {
8037 		compression_on_already = 1;
8038 	} else {
8039 		compression_on_already = 0;
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 ((compression_on == compression_on_already) &&
8047 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
8048 		return (EALREADY);
8049 	}
8050 
8051 	/*
8052 	 * if we are already set to the appropriate compression
8053 	 * mode, don't set it again
8054 	 */
8055 	if (compression_on) {
8056 		/* compression selected */
8057 		un->un_mspl->page.comp.dce = 1;
8058 	} else {
8059 		un->un_mspl->page.comp.dce = 0;
8060 	}
8061 
8062 
8063 #ifdef STDEBUG
8064 	if ((st_debug & 0x7) >= 6) {
8065 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8066 		    "st_set_datacomp_page: sense data for mode select",
8067 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8068 	}
8069 #endif
8070 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8071 	    sizeof (struct seq_mode));
8072 
8073 	return (rval);
8074 }
8075 
8076 static int
8077 st_modesense(struct scsi_tape *un)
8078 {
8079 	int rval;
8080 	uchar_t page;
8081 
8082 	ST_FUNC(ST_DEVINFO, st_modesense);
8083 
8084 	page = un->un_comp_page;
8085 
8086 	switch (page) {
8087 	case ST_DEV_DATACOMP_PAGE:
8088 	case ST_DEV_CONFIG_PAGE: /* FALLTHROUGH */
8089 		rval = st_gen_mode_sense(un, st_uscsi_cmd, page, un->un_mspl,
8090 		    sizeof (struct seq_mode));
8091 		break;
8092 
8093 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
8094 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
8095 			page = ST_DEV_CONFIG_PAGE;
8096 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8097 			    un->un_mspl, sizeof (struct seq_mode));
8098 			if (rval == 0 && un->un_mspl->page_code == page) {
8099 				un->un_comp_page = page;
8100 				break;
8101 			}
8102 			page = ST_DEV_DATACOMP_PAGE;
8103 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8104 			    un->un_mspl, sizeof (struct seq_mode));
8105 			if (rval == 0 && un->un_mspl->page_code == page) {
8106 				un->un_comp_page = page;
8107 				break;
8108 			}
8109 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
8110 			un->un_comp_page = 0;
8111 		} else {
8112 			un->un_comp_page = 0;
8113 		}
8114 
8115 	default:	/* FALLTHROUGH */
8116 		rval = st_cmd(un, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
8117 	}
8118 	return (rval);
8119 }
8120 
8121 static int
8122 st_modeselect(struct scsi_tape *un)
8123 {
8124 	int rval = 0;
8125 	int ix;
8126 
8127 	ST_FUNC(ST_DEVINFO, st_modeselect);
8128 
8129 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8130 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
8131 	    un->un_dev, un->un_mspl->density);
8132 
8133 	ASSERT(mutex_owned(ST_MUTEX));
8134 
8135 	/*
8136 	 * The parameter list should be the same for all of the
8137 	 * cases that follow so set them here
8138 	 *
8139 	 * Try mode select first if if fails set fields manually
8140 	 */
8141 	rval = st_modesense(un);
8142 	if (rval != 0) {
8143 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8144 		    "st_modeselect: First mode sense failed\n");
8145 		un->un_mspl->bd_len  = 8;
8146 		un->un_mspl->high_nb = 0;
8147 		un->un_mspl->mid_nb  = 0;
8148 		un->un_mspl->low_nb  = 0;
8149 	}
8150 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
8151 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
8152 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
8153 
8154 
8155 	/*
8156 	 * If configured to use a specific density code for a media type.
8157 	 * curdens is previously set by the minor node opened.
8158 	 * If the media type doesn't match the minor node we change it so it
8159 	 * looks like the correct one was opened.
8160 	 */
8161 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
8162 		uchar_t best;
8163 
8164 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
8165 			if (un->un_mspl->media_type ==
8166 			    un->un_dp->mediatype[ix]) {
8167 				best = ix;
8168 				/*
8169 				 * It matches but it might not be the only one.
8170 				 * Use the highest matching media type but not
8171 				 * to exceed the density selected by the open.
8172 				 */
8173 				if (ix < un->un_curdens) {
8174 					continue;
8175 				}
8176 				un->un_curdens = ix;
8177 				break;
8178 			}
8179 		}
8180 		/* If a match was found best will not be 0xff any more */
8181 		if (best < NDENSITIES) {
8182 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8183 			    "found media 0x%X using density 0x%X\n",
8184 			    un->un_mspl->media_type,
8185 			    un->un_dp->densities[best]);
8186 			un->un_mspl->density = un->un_dp->densities[best];
8187 		} else {
8188 			/* Otherwise set density based on minor node opened */
8189 			un->un_mspl->density =
8190 			    un->un_dp->densities[un->un_curdens];
8191 		}
8192 	} else {
8193 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
8194 	}
8195 
8196 	if (un->un_dp->options & ST_NOBUF) {
8197 		un->un_mspl->bufm = 0;
8198 	} else {
8199 		un->un_mspl->bufm = 1;
8200 	}
8201 
8202 	rval = st_set_compression(un);
8203 
8204 	/*
8205 	 * If st_set_compression returned invalid or already it
8206 	 * found no need to do the mode select.
8207 	 * So do it here.
8208 	 */
8209 	if ((rval == ENOTTY) || (rval == EALREADY)) {
8210 
8211 		/* Zero non-writeable fields */
8212 		un->un_mspl->data_len = 0;
8213 		un->un_mspl->media_type = 0;
8214 		un->un_mspl->wp = 0;
8215 
8216 		/* need to set the density code */
8217 		rval = st_cmd(un, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
8218 		if (rval != 0) {
8219 			if (un->un_state >= ST_STATE_OPEN) {
8220 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8221 				    "unable to set tape mode\n");
8222 				un->un_pos.pmode = invalid;
8223 				rval = EIO;
8224 			} else {
8225 				rval = -1;
8226 			}
8227 		}
8228 	}
8229 
8230 	/*
8231 	 * The spec recommends to send a mode sense after a mode select
8232 	 */
8233 	(void) st_modesense(un);
8234 
8235 	ASSERT(mutex_owned(ST_MUTEX));
8236 
8237 	return (rval);
8238 }
8239 
8240 /*
8241  * st_gen_mode_sense
8242  *
8243  * generic mode sense.. it allows for any page
8244  */
8245 static int
8246 st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
8247     struct seq_mode *page_data, int page_size)
8248 {
8249 
8250 	int r;
8251 	char	cdb[CDB_GROUP0];
8252 	struct uscsi_cmd *com;
8253 	struct scsi_arq_status status;
8254 
8255 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
8256 
8257 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8258 
8259 	bzero(cdb, CDB_GROUP0);
8260 	cdb[0] = SCMD_MODE_SENSE;
8261 	cdb[2] = (char)page;
8262 	cdb[4] = (char)page_size;
8263 
8264 	com->uscsi_cdb = cdb;
8265 	com->uscsi_cdblen = CDB_GROUP0;
8266 	com->uscsi_bufaddr = (caddr_t)page_data;
8267 	com->uscsi_buflen = page_size;
8268 	com->uscsi_rqlen = sizeof (status);
8269 	com->uscsi_rqbuf = (caddr_t)&status;
8270 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8271 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8272 
8273 	r = ubf(un, com, FKIOCTL);
8274 	kmem_free(com, sizeof (*com));
8275 	return (r);
8276 }
8277 
8278 /*
8279  * st_gen_mode_select
8280  *
8281  * generic mode select.. it allows for any page
8282  */
8283 static int
8284 st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
8285     struct seq_mode *page_data, int page_size)
8286 {
8287 
8288 	int r;
8289 	char cdb[CDB_GROUP0];
8290 	struct uscsi_cmd *com;
8291 	struct scsi_arq_status status;
8292 
8293 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
8294 
8295 	/* Zero non-writeable fields */
8296 	page_data->data_len = 0;
8297 	page_data->media_type = 0;
8298 	page_data->wp = 0;
8299 
8300 	/*
8301 	 * If mode select has any page data, zero the ps (Page Savable) bit.
8302 	 */
8303 	if (page_size > MSIZE) {
8304 		page_data->ps = 0;
8305 	}
8306 
8307 
8308 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8309 
8310 	/*
8311 	 * then, do a mode select to set what ever info
8312 	 */
8313 	bzero(cdb, CDB_GROUP0);
8314 	cdb[0] = SCMD_MODE_SELECT;
8315 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
8316 	cdb[4] = (char)page_size;
8317 
8318 	com->uscsi_cdb = cdb;
8319 	com->uscsi_cdblen = CDB_GROUP0;
8320 	com->uscsi_bufaddr = (caddr_t)page_data;
8321 	com->uscsi_buflen = page_size;
8322 	com->uscsi_rqlen = sizeof (status);
8323 	com->uscsi_rqbuf = (caddr_t)&status;
8324 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8325 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_WRITE;
8326 
8327 	r = ubf(un, com, FKIOCTL);
8328 
8329 	kmem_free(com, sizeof (*com));
8330 	return (r);
8331 }
8332 
8333 static int
8334 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
8335 {
8336 	int rval;
8337 	char cdb[CDB_GROUP0];
8338 	struct uscsi_cmd *com;
8339 	struct scsi_arq_status status;
8340 
8341 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
8342 
8343 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8344 
8345 	bzero(cdb, CDB_GROUP0);
8346 	cdb[0] = SCMD_READ_BLKLIM;
8347 
8348 	com->uscsi_cdb = cdb;
8349 	com->uscsi_cdblen = CDB_GROUP0;
8350 	com->uscsi_bufaddr = (caddr_t)read_blk;
8351 	com->uscsi_buflen = sizeof (struct read_blklim);
8352 	com->uscsi_rqlen = sizeof (status);
8353 	com->uscsi_rqbuf = (caddr_t)&status;
8354 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8355 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8356 
8357 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8358 	if (com->uscsi_status || com->uscsi_resid) {
8359 		rval = -1;
8360 	}
8361 
8362 	kmem_free(com, sizeof (*com));
8363 	return (rval);
8364 }
8365 
8366 static int
8367 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
8368     size_t buflen)
8369 {
8370 	int rval;
8371 	char cdb[CDB_GROUP1];
8372 	struct uscsi_cmd *com;
8373 	struct scsi_arq_status status;
8374 
8375 	ST_FUNC(ST_DEVINFO, st_report_density_support);
8376 
8377 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8378 
8379 	bzero(cdb, CDB_GROUP1);
8380 	cdb[0] = SCMD_REPORT_DENSITIES;
8381 	cdb[7] = (buflen & 0xff00) >> 8;
8382 	cdb[8] = buflen & 0xff;
8383 
8384 	com->uscsi_cdb = cdb;
8385 	com->uscsi_cdblen = CDB_GROUP1;
8386 	com->uscsi_bufaddr = (caddr_t)density_data;
8387 	com->uscsi_buflen = buflen;
8388 	com->uscsi_rqlen = sizeof (status);
8389 	com->uscsi_rqbuf = (caddr_t)&status;
8390 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8391 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8392 
8393 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8394 	if (com->uscsi_status || com->uscsi_resid) {
8395 		rval = -1;
8396 	}
8397 
8398 	kmem_free(com, sizeof (*com));
8399 	return (rval);
8400 }
8401 
8402 static int
8403 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
8404     uchar_t option_code, ushort_t service_action)
8405 {
8406 	int rval;
8407 	char cdb[CDB_GROUP5];
8408 	struct uscsi_cmd *com;
8409 	struct scsi_arq_status status;
8410 	uint32_t allo_length;
8411 
8412 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
8413 
8414 	allo_length = sizeof (struct one_com_des) +
8415 	    sizeof (struct com_timeout_des);
8416 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8417 
8418 	bzero(cdb, CDB_GROUP5);
8419 	cdb[0] = (char)SCMD_MAINTENANCE_IN;
8420 	cdb[1] = SSVC_ACTION_GET_SUPPORTED_OPERATIONS;
8421 	if (service_action) {
8422 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
8423 		cdb[4] = (service_action & 0xff00) >> 8;
8424 		cdb[5] = service_action & 0xff;
8425 	} else {
8426 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
8427 		    0x80); /* RCTD */
8428 	}
8429 	cdb[3] = option_code;
8430 	cdb[6] = (allo_length & 0xff000000) >> 24;
8431 	cdb[7] = (allo_length & 0xff0000) >> 16;
8432 	cdb[8] = (allo_length & 0xff00) >> 8;
8433 	cdb[9] = allo_length & 0xff;
8434 
8435 	com->uscsi_cdb = cdb;
8436 	com->uscsi_cdblen = CDB_GROUP5;
8437 	com->uscsi_bufaddr = (caddr_t)oper_data;
8438 	com->uscsi_buflen = allo_length;
8439 	com->uscsi_rqlen = sizeof (status);
8440 	com->uscsi_rqbuf = (caddr_t)&status;
8441 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8442 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8443 
8444 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8445 	if (com->uscsi_status) {
8446 		rval = -1;
8447 	}
8448 
8449 	kmem_free(com, sizeof (*com));
8450 	return (rval);
8451 }
8452 
8453 /*
8454  * Changes devices blocksize and bsize to requested blocksize nblksz.
8455  * Returns returned value from first failed call or zero on success.
8456  */
8457 static int
8458 st_change_block_size(struct scsi_tape *un, uint32_t nblksz)
8459 {
8460 	struct seq_mode *current;
8461 	int rval;
8462 	uint32_t oldblksz;
8463 
8464 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8465 
8466 	current = kmem_zalloc(MSIZE, KM_SLEEP);
8467 
8468 	/*
8469 	 * If we haven't got the compression page yet, do that first.
8470 	 */
8471 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
8472 		(void) st_modesense(un);
8473 	}
8474 
8475 	/* Read current settings */
8476 	rval = st_gen_mode_sense(un, st_uscsi_cmd, 0, current, MSIZE);
8477 	if (rval != 0) {
8478 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8479 		    "mode sense for change block size failed: rval = %d", rval);
8480 		goto finish;
8481 	}
8482 
8483 	/* Figure the current block size */
8484 	oldblksz =
8485 	    (current->high_bl << 16) |
8486 	    (current->mid_bl << 8) |
8487 	    (current->low_bl);
8488 
8489 	/* If current block size is the same as requested were done */
8490 	if (oldblksz == nblksz) {
8491 		un->un_bsize = nblksz;
8492 		rval = 0;
8493 		goto finish;
8494 	}
8495 
8496 	/* Change to requested block size */
8497 	current->high_bl = (uchar_t)(nblksz >> 16);
8498 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8499 	current->low_bl  = (uchar_t)(nblksz);
8500 
8501 	/* Attempt to change block size */
8502 	rval = st_gen_mode_select(un, st_uscsi_cmd, current, MSIZE);
8503 	if (rval != 0) {
8504 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8505 		    "Set new block size failed: rval = %d", rval);
8506 		goto finish;
8507 	}
8508 
8509 	/* Read back and verify setting */
8510 	rval = st_modesense(un);
8511 	if (rval == 0) {
8512 		un->un_bsize =
8513 		    (un->un_mspl->high_bl << 16) |
8514 		    (un->un_mspl->mid_bl << 8) |
8515 		    (un->un_mspl->low_bl);
8516 
8517 		if (un->un_bsize != nblksz) {
8518 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8519 			    "Blocksize set does not equal requested blocksize"
8520 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8521 			rval = EIO;
8522 		}
8523 	}
8524 finish:
8525 	kmem_free(current, MSIZE);
8526 	return (rval);
8527 }
8528 
8529 
8530 static void
8531 st_init(struct scsi_tape *un)
8532 {
8533 	ST_FUNC(ST_DEVINFO, st_init);
8534 
8535 	ASSERT(mutex_owned(ST_MUTEX));
8536 
8537 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8538 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8539 	    un->un_dev);
8540 
8541 	un->un_pos.blkno = 0;
8542 	un->un_pos.fileno = 0;
8543 	un->un_lastop = ST_OP_NIL;
8544 	un->un_pos.eof = ST_NO_EOF;
8545 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8546 	if (st_error_level != SCSI_ERR_ALL) {
8547 		if (DEBUGGING) {
8548 			st_error_level = SCSI_ERR_ALL;
8549 		} else {
8550 			st_error_level = SCSI_ERR_RETRYABLE;
8551 		}
8552 	}
8553 }
8554 
8555 
8556 static void
8557 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8558 {
8559 	struct scsi_pkt *pkt;
8560 	struct uscsi_cmd *ucmd;
8561 	recov_info *ri;
8562 	int tval = 0;
8563 	int64_t count;
8564 	uint32_t additional = 0;
8565 	uint32_t address = 0;
8566 	union scsi_cdb *ucdb;
8567 	int flags = 0;
8568 	int cdb_len = CDB_GROUP0; /* default */
8569 	uchar_t com;
8570 	char fixbit;
8571 	char short_fm = 0;
8572 	optype prev_op = un->un_lastop;
8573 	int stat_size =
8574 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
8575 
8576 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8577 
8578 	ASSERT(mutex_owned(ST_MUTEX));
8579 
8580 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8581 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8582 
8583 
8584 	/*
8585 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8586 	 * Length Indicator bits on read/write commands, for setting
8587 	 * the Long bit on erase commands, and for setting the Code
8588 	 * Field bits on space commands.
8589 	 */
8590 
8591 	/* regular raw I/O */
8592 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
8593 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8594 		    CDB_GROUP0, stat_size, st_recov_sz, 0, func,
8595 		    (caddr_t)un);
8596 		if (pkt == NULL) {
8597 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8598 			    "Read Write scsi_init_pkt() failure\n");
8599 			goto exit;
8600 		}
8601 		ASSERT(pkt->pkt_resid == 0);
8602 #ifdef STDEBUG
8603 		bzero(pkt->pkt_private, st_recov_sz);
8604 		bzero(pkt->pkt_scbp, stat_size);
8605 #endif
8606 		ri = (recov_info *)pkt->pkt_private;
8607 		ri->privatelen = st_recov_sz;
8608 		if (un->un_bsize == 0) {
8609 			count = bp->b_bcount;
8610 			fixbit = 0;
8611 		} else {
8612 			count = bp->b_bcount / un->un_bsize;
8613 			fixbit = 1;
8614 		}
8615 		if (bp->b_flags & B_READ) {
8616 			com = SCMD_READ;
8617 			un->un_lastop = ST_OP_READ;
8618 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8619 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8620 				fixbit = 2;
8621 			}
8622 		} else {
8623 			com = SCMD_WRITE;
8624 			un->un_lastop = ST_OP_WRITE;
8625 		}
8626 		tval = un->un_dp->io_timeout;
8627 
8628 		/*
8629 		 * For really large xfers, increase timeout
8630 		 */
8631 		if (bp->b_bcount > (10 * ONE_MEG))
8632 			tval *= bp->b_bcount/(10 * ONE_MEG);
8633 
8634 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8635 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8636 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8637 
8638 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8639 		/*
8640 		 * uscsi - build command, allocate scsi resources
8641 		 */
8642 		st_make_uscsi_cmd(un, ucmd, bp, func);
8643 		goto exit;
8644 
8645 	} else {				/* special I/O */
8646 		struct buf *allocbp = NULL;
8647 		com = (uchar_t)(uintptr_t)bp->b_forw;
8648 		count = bp->b_bcount;
8649 
8650 		switch (com) {
8651 		case SCMD_READ:
8652 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8653 			    "special read %"PRId64"\n", count);
8654 			if (un->un_bsize == 0) {
8655 				fixbit = 2;	/* suppress SILI */
8656 			} else {
8657 				fixbit = 1;	/* Fixed Block Mode */
8658 				count /= un->un_bsize;
8659 			}
8660 			allocbp = bp;
8661 			un->un_lastop = ST_OP_READ;
8662 			tval = un->un_dp->io_timeout;
8663 			break;
8664 
8665 		case SCMD_WRITE:
8666 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8667 			    "special write %"PRId64"\n", count);
8668 			if (un->un_bsize != 0) {
8669 				fixbit = 1;	/* Fixed Block Mode */
8670 				count /= un->un_bsize;
8671 			} else {
8672 				fixbit = 0;
8673 			}
8674 			allocbp = bp;
8675 			un->un_lastop = ST_OP_WRITE;
8676 			tval = un->un_dp->io_timeout;
8677 			break;
8678 
8679 		case SCMD_WRITE_FILE_MARK:
8680 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8681 			    "write %"PRId64" file marks\n", count);
8682 			un->un_lastop = ST_OP_WEOF;
8683 			fixbit = 0;
8684 			tval = un->un_dp->io_timeout;
8685 			/*
8686 			 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8687 			 * device, set the Vendor Unique bit to
8688 			 * write Short File Mark.
8689 			 */
8690 			if ((un->un_dp->options & ST_SHORT_FILEMARKS) &&
8691 			    ((un->un_dp->type == ST_TYPE_EXB8500) ||
8692 			    (un->un_dp->type == ST_TYPE_EXABYTE))) {
8693 				/*
8694 				 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8695 				 * is set to to write Short File Mark
8696 				 */
8697 				short_fm = 1;
8698 			}
8699 			break;
8700 
8701 		case SCMD_REWIND:
8702 			/*
8703 			 * In the case of rewind we're gona do the rewind with
8704 			 * the immediate bit set so status will be retured when
8705 			 * the command is accepted by the device. We clear the
8706 			 * B_ASYNC flag so we wait for that acceptance.
8707 			 */
8708 			if (bp->b_flags & B_ASYNC) {
8709 				allocbp = bp;
8710 				if (count) {
8711 					fixbit = 1;
8712 					bp->b_flags &= ~B_ASYNC;
8713 				}
8714 			} else {
8715 				fixbit = 0;
8716 			}
8717 			count = 0;
8718 			bp->b_bcount = 0;
8719 			un->un_lastop = ST_OP_CTL;
8720 			tval = un->un_dp->rewind_timeout;
8721 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8722 			    "rewind\n");
8723 			break;
8724 
8725 		case SCMD_SPACE_G4:
8726 			cdb_len = CDB_GROUP4;
8727 			fixbit = SPACE_TYPE(bp->b_bcount);
8728 			count = SPACE_CNT(bp->b_bcount);
8729 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8730 			    " %s space %s %"PRId64" from file %d blk %d\n",
8731 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8732 			    space_strs[fixbit & 7], count,
8733 			    un->un_pos.fileno, un->un_pos.blkno);
8734 			address = (count >> 48) & 0x1fff;
8735 			additional = (count >> 16) & 0xffffffff;
8736 			count &= 0xffff;
8737 			count <<= 16;
8738 			un->un_lastop = ST_OP_CTL;
8739 			tval = un->un_dp->space_timeout;
8740 			break;
8741 
8742 		case SCMD_SPACE:
8743 			fixbit = SPACE_TYPE(bp->b_bcount);
8744 			count = SPACE_CNT(bp->b_bcount);
8745 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8746 			    " %s space %s %"PRId64" from file %d blk %d\n",
8747 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8748 			    space_strs[fixbit & 7], count,
8749 			    un->un_pos.fileno, un->un_pos.blkno);
8750 			count &= 0xffffffff;
8751 			un->un_lastop = ST_OP_CTL;
8752 			tval = un->un_dp->space_timeout;
8753 			break;
8754 
8755 		case SCMD_LOAD:
8756 			ASSERT(count < 10);
8757 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8758 			    "%s tape\n", load_strs[count]);
8759 			fixbit = 0;
8760 
8761 			/* Loading or Unloading */
8762 			if (count & LD_LOAD) {
8763 				tval = un->un_dp->load_timeout;
8764 			} else {
8765 				tval = un->un_dp->unload_timeout;
8766 			}
8767 			/* Is Retension requested */
8768 			if (count & LD_RETEN) {
8769 				tval += un->un_dp->rewind_timeout;
8770 			}
8771 			un->un_lastop = ST_OP_CTL;
8772 			break;
8773 
8774 		case SCMD_ERASE:
8775 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8776 			    "erase tape\n");
8777 			ASSERT(count == 1); /* mt sets this */
8778 			if (count == 1) {
8779 				/*
8780 				 * do long erase
8781 				 */
8782 				fixbit = 1; /* Long */
8783 
8784 				/* Drive might not honor immidiate bit */
8785 				tval = un->un_dp->erase_timeout;
8786 			} else {
8787 				/* Short Erase */
8788 				tval = un->un_dp->erase_timeout;
8789 				fixbit = 0;
8790 			}
8791 			un->un_lastop = ST_OP_CTL;
8792 			count = 0;
8793 			break;
8794 
8795 		case SCMD_MODE_SENSE:
8796 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8797 			    "mode sense\n");
8798 			allocbp = bp;
8799 			fixbit = 0;
8800 			tval = un->un_dp->non_motion_timeout;
8801 			un->un_lastop = ST_OP_CTL;
8802 			break;
8803 
8804 		case SCMD_MODE_SELECT:
8805 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8806 			    "mode select\n");
8807 			allocbp = bp;
8808 			fixbit = 0;
8809 			tval = un->un_dp->non_motion_timeout;
8810 			un->un_lastop = ST_OP_CTL;
8811 			break;
8812 
8813 		case SCMD_RESERVE:
8814 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8815 			    "reserve\n");
8816 			fixbit = 0;
8817 			tval = un->un_dp->non_motion_timeout;
8818 			un->un_lastop = ST_OP_CTL;
8819 			break;
8820 
8821 		case SCMD_RELEASE:
8822 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8823 			    "release\n");
8824 			fixbit = 0;
8825 			tval = un->un_dp->non_motion_timeout;
8826 			un->un_lastop = ST_OP_CTL;
8827 			break;
8828 
8829 		case SCMD_READ_BLKLIM:
8830 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8831 			    "read block limits\n");
8832 			allocbp = bp;
8833 			fixbit = count = 0;
8834 			tval = un->un_dp->non_motion_timeout;
8835 			un->un_lastop = ST_OP_CTL;
8836 			break;
8837 
8838 		case SCMD_TEST_UNIT_READY:
8839 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8840 			    "test unit ready\n");
8841 			fixbit = 0;
8842 			tval = un->un_dp->non_motion_timeout;
8843 			un->un_lastop = ST_OP_CTL;
8844 			break;
8845 
8846 		case SCMD_DOORLOCK:
8847 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8848 			    "prevent/allow media removal\n");
8849 			fixbit = 0;
8850 			tval = un->un_dp->non_motion_timeout;
8851 			un->un_lastop = ST_OP_CTL;
8852 			break;
8853 
8854 		case SCMD_READ_POSITION:
8855 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8856 			    "read position\n");
8857 			fixbit = un->un_read_pos_type;
8858 			cdb_len = CDB_GROUP1;
8859 			tval = un->un_dp->non_motion_timeout;
8860 			allocbp = bp;
8861 			un->un_lastop = ST_OP_CTL;
8862 			switch (un->un_read_pos_type) {
8863 			case LONG_POS:
8864 				count = 0;
8865 				break;
8866 			case EXT_POS:
8867 				count = sizeof (tape_position_ext_t);
8868 				break;
8869 			case SHORT_POS:
8870 				count = 0;
8871 				break;
8872 			default:
8873 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8874 				    "Unknown read position type 0x%x in "
8875 				    " st_make_cmd()\n", un->un_read_pos_type);
8876 			}
8877 			break;
8878 
8879 		default:
8880 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8881 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8882 			    com);
8883 		}
8884 
8885 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8886 		    st_recov_sz, 0, func, (caddr_t)un);
8887 		if (pkt == NULL) {
8888 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8889 			    "generic command scsi_init_pkt() failure\n");
8890 			goto exit;
8891 		}
8892 
8893 		ASSERT(pkt->pkt_resid == 0);
8894 #ifdef STDEBUG
8895 		bzero(pkt->pkt_private, st_recov_sz);
8896 		bzero(pkt->pkt_scbp, stat_size);
8897 #endif
8898 		ri = (recov_info *)pkt->pkt_private;
8899 		ri->privatelen = st_recov_sz;
8900 		if (allocbp) {
8901 			ASSERT(geterror(allocbp) == 0);
8902 		}
8903 
8904 	}
8905 
8906 	ucdb = (union scsi_cdb *)pkt->pkt_cdbp;
8907 
8908 	(void) scsi_setup_cdb(ucdb, com, address, (uint_t)count, additional);
8909 	FILL_SCSI1_LUN(un->un_sd, pkt);
8910 	/*
8911 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8912 	 */
8913 	ucdb->t_code = fixbit;
8914 	ucdb->g0_vu_1 = short_fm;
8915 	pkt->pkt_flags = flags;
8916 
8917 	ASSERT(tval);
8918 	pkt->pkt_time = tval;
8919 	if (bp == un->un_recov_buf) {
8920 		pkt->pkt_comp = st_recov_cb;
8921 	} else {
8922 		pkt->pkt_comp = st_intr;
8923 	}
8924 
8925 	st_add_recovery_info_to_pkt(un, bp, pkt);
8926 
8927 	/*
8928 	 * If we just write data to tape and did a command that doesn't
8929 	 * change position, we still need to write a filemark.
8930 	 */
8931 	if ((prev_op == ST_OP_WRITE) || (prev_op == ST_OP_WEOF)) {
8932 		recov_info *rcvi = pkt->pkt_private;
8933 		cmd_attribute const *atrib;
8934 
8935 		if (rcvi->privatelen == sizeof (recov_info)) {
8936 			atrib = rcvi->cmd_attrib;
8937 		} else {
8938 			atrib = st_lookup_cmd_attribute(com);
8939 		}
8940 		if (atrib->chg_tape_direction == DIR_NONE) {
8941 			un->un_lastop = prev_op;
8942 		}
8943 	}
8944 
8945 exit:
8946 	ASSERT(mutex_owned(ST_MUTEX));
8947 }
8948 
8949 
8950 /*
8951  * Build a command based on a uscsi command;
8952  */
8953 static void
8954 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
8955     struct buf *bp, int (*func)(caddr_t))
8956 {
8957 	struct scsi_pkt *pkt;
8958 	recov_info *ri;
8959 	caddr_t cdb;
8960 	int	cdblen;
8961 	int	stat_size = 1;
8962 	int	flags = 0;
8963 
8964 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
8965 
8966 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8967 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
8968 
8969 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
8970 		if (un->un_arq_enabled) {
8971 			if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
8972 				stat_size = (int)(ucmd->uscsi_rqlen) +
8973 				    sizeof (struct scsi_arq_status) -
8974 				    sizeof (struct scsi_extended_sense);
8975 				flags = PKT_XARQ;
8976 			} else {
8977 				stat_size = sizeof (struct scsi_arq_status);
8978 			}
8979 		}
8980 	}
8981 
8982 	ASSERT(mutex_owned(ST_MUTEX));
8983 
8984 	cdb = ucmd->uscsi_cdb;
8985 	cdblen = ucmd->uscsi_cdblen;
8986 
8987 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8988 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
8989 	    ucmd->uscsi_buflen, bp->b_bcount);
8990 	pkt = scsi_init_pkt(ROUTE, NULL,
8991 	    (bp->b_bcount > 0) ? bp : NULL,
8992 	    cdblen, stat_size, st_recov_sz, flags, func, (caddr_t)un);
8993 	if (pkt == NULL) {
8994 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8995 		    "uscsi command scsi_init_pkt() failure\n");
8996 		goto exit;
8997 	}
8998 
8999 	ASSERT(pkt->pkt_resid == 0);
9000 #ifdef STDEBUG
9001 	bzero(pkt->pkt_private, st_recov_sz);
9002 	bzero(pkt->pkt_scbp, stat_size);
9003 #endif
9004 	ri = (recov_info *)pkt->pkt_private;
9005 	ri->privatelen = st_recov_sz;
9006 
9007 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
9008 
9009 #ifdef STDEBUG
9010 	if ((st_debug & 0x7) >= 6) {
9011 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
9012 		    "pkt_cdbp", (char *)cdb, cdblen);
9013 	}
9014 #endif
9015 
9016 	if (ucmd->uscsi_flags & USCSI_SILENT) {
9017 		pkt->pkt_flags |= FLAG_SILENT;
9018 	}
9019 
9020 	pkt->pkt_time = ucmd->uscsi_timeout;
9021 	if (bp == un->un_recov_buf) {
9022 		pkt->pkt_comp = st_recov_cb;
9023 	} else {
9024 		pkt->pkt_comp = st_intr;
9025 	}
9026 	st_add_recovery_info_to_pkt(un, bp, pkt);
9027 exit:
9028 	ASSERT(mutex_owned(ST_MUTEX));
9029 }
9030 
9031 
9032 /*
9033  * restart cmd currently at the head of the runq
9034  *
9035  * If scsi_transport() succeeds or the retries
9036  * count exhausted, restore the throttle that was
9037  * zeroed out in st_handle_intr_busy().
9038  *
9039  */
9040 static void
9041 st_intr_restart(void *arg)
9042 {
9043 	struct scsi_tape *un = arg;
9044 	struct buf *bp;
9045 	int queued;
9046 	int status = TRAN_ACCEPT;
9047 
9048 	mutex_enter(ST_MUTEX);
9049 
9050 	ST_FUNC(ST_DEVINFO, st_intr_restart);
9051 
9052 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9053 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
9054 
9055 	un->un_hib_tid = 0;
9056 
9057 	if (un->un_recov_buf_busy != 0) {
9058 		bp = un->un_recov_buf;
9059 		queued = 0;
9060 	} else if (un->un_sbuf_busy != 0) {
9061 		bp = un->un_sbufp;
9062 		queued = 0;
9063 	} else if (un->un_quef != NULL) {
9064 		bp = un->un_quef;
9065 		queued = 1;
9066 	} else {
9067 		mutex_exit(ST_MUTEX);
9068 		return;
9069 	}
9070 
9071 	/*
9072 	 * Here we know :
9073 	 *	throttle = 0, via st_handle_intr_busy
9074 	 */
9075 
9076 	if (queued) {
9077 		/*
9078 		 * move from waitq to runq, if there is anything on the waitq
9079 		 */
9080 		(void) st_remove_from_queue(&un->un_quef, &un->un_quef, bp);
9081 
9082 		if (un->un_runqf) {
9083 			/*
9084 			 * not good, we don't want to requeue something after
9085 			 * another.
9086 			 */
9087 			goto done_error;
9088 		} else {
9089 			un->un_runqf = bp;
9090 			un->un_runql = bp;
9091 		}
9092 	}
9093 
9094 	ST_CDB(ST_DEVINFO, "Interrupt restart CDB",
9095 	    (char *)BP_PKT(bp)->pkt_cdbp);
9096 
9097 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
9098 
9099 	status = st_transport(un, BP_PKT(bp));
9100 
9101 	if (status != TRAN_ACCEPT) {
9102 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9103 
9104 		if (status == TRAN_BUSY) {
9105 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
9106 
9107 			if (pkti->privatelen == sizeof (recov_info) &&
9108 			    un->un_unit_attention_flags &&
9109 			    bp != un->un_recov_buf) {
9110 			un->un_unit_attention_flags = 0;
9111 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9112 				    "Command Recovery called on busy resend\n");
9113 				if (st_command_recovery(un, BP_PKT(bp),
9114 				    ATTEMPT_RETRY) == JUST_RETURN) {
9115 					mutex_exit(ST_MUTEX);
9116 					return;
9117 				}
9118 			}
9119 			mutex_exit(ST_MUTEX);
9120 			if (st_handle_intr_busy(un, bp,
9121 			    ST_TRAN_BUSY_TIMEOUT) == 0)
9122 				return;	/* timeout is setup again */
9123 			mutex_enter(ST_MUTEX);
9124 		}
9125 
9126 done_error:
9127 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9128 		    "restart transport rejected\n");
9129 		bp->b_resid = bp->b_bcount;
9130 
9131 		if (un->un_last_throttle) {
9132 			un->un_throttle = un->un_last_throttle;
9133 		}
9134 		if (status != TRAN_ACCEPT) {
9135 			ST_DO_ERRSTATS(un, st_transerrs);
9136 		}
9137 		ST_DO_KSTATS(bp, kstat_waitq_exit);
9138 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9139 		    "busy restart aborted\n");
9140 		st_set_pe_flag(un);
9141 		st_bioerror(bp, EIO);
9142 		st_done_and_mutex_exit(un, bp);
9143 	} else {
9144 		if (un->un_last_throttle) {
9145 			un->un_throttle = un->un_last_throttle;
9146 		}
9147 		mutex_exit(ST_MUTEX);
9148 	}
9149 }
9150 
9151 /*
9152  * st_check_media():
9153  * Periodically check the media state using scsi_watch service;
9154  * this service calls back after TUR and possibly request sense
9155  * the callback handler (st_media_watch_cb()) decodes the request sense
9156  * data (if any)
9157  */
9158 
9159 static int
9160 st_check_media(dev_t dev, enum mtio_state state)
9161 {
9162 	int rval = 0;
9163 	enum mtio_state	prev_state;
9164 	opaque_t token = NULL;
9165 
9166 	GET_SOFT_STATE(dev);
9167 
9168 	ST_FUNC(ST_DEVINFO, st_check_media);
9169 
9170 	mutex_enter(ST_MUTEX);
9171 
9172 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9173 	    "st_check_media:state=%x, mediastate=%x\n",
9174 	    state, un->un_mediastate);
9175 
9176 	prev_state = un->un_mediastate;
9177 
9178 	/*
9179 	 * is there anything to do?
9180 	 */
9181 retry:
9182 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
9183 		/*
9184 		 * submit the request to the scsi_watch service;
9185 		 * scsi_media_watch_cb() does the real work
9186 		 */
9187 		mutex_exit(ST_MUTEX);
9188 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
9189 		    st_check_media_time, SENSE_LENGTH,
9190 		    st_media_watch_cb, (caddr_t)dev);
9191 		if (token == NULL) {
9192 			rval = EAGAIN;
9193 			goto done;
9194 		}
9195 		mutex_enter(ST_MUTEX);
9196 
9197 		un->un_swr_token = token;
9198 		un->un_specified_mediastate = state;
9199 
9200 		/*
9201 		 * now wait for media change
9202 		 * we will not be signalled unless mediastate == state but it
9203 		 * still better to test for this condition, since there
9204 		 * is a 5 sec cv_broadcast delay when
9205 		 *  mediastate == MTIO_INSERTED
9206 		 */
9207 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9208 		    "st_check_media:waiting for media state change\n");
9209 		while (un->un_mediastate == state) {
9210 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
9211 				mutex_exit(ST_MUTEX);
9212 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9213 				    "st_check_media:waiting for media state "
9214 				    "was interrupted\n");
9215 				rval = EINTR;
9216 				goto done;
9217 			}
9218 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9219 			    "st_check_media:received signal, state=%x\n",
9220 			    un->un_mediastate);
9221 		}
9222 	}
9223 
9224 	/*
9225 	 * if we transitioned to MTIO_INSERTED, media has really been
9226 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
9227 	 * Reset and retry the state change.  If everything is ok, replay
9228 	 * the open() logic.
9229 	 */
9230 	if ((un->un_mediastate == MTIO_INSERTED) &&
9231 	    (un->un_state == ST_STATE_OFFLINE)) {
9232 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9233 		    "st_check_media: calling st_cmd to confirm inserted\n");
9234 
9235 		/*
9236 		 * set this early so that TUR will make it through strategy
9237 		 * without triggering a st_tape_init().  We needed it set
9238 		 * before calling st_tape_init() ourselves anyway.  If TUR
9239 		 * fails, set it back
9240 		 */
9241 		un->un_state = ST_STATE_INITIALIZING;
9242 
9243 		/*
9244 		 * If not reserved fail as getting reservation conflict
9245 		 * will make this hang forever.
9246 		 */
9247 		if ((un->un_rsvd_status &
9248 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9249 			mutex_exit(ST_MUTEX);
9250 			rval = EACCES;
9251 			goto done;
9252 		}
9253 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
9254 		if (rval == EACCES) {
9255 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9256 			    "st_check_media: TUR got Reservation Conflict\n");
9257 			mutex_exit(ST_MUTEX);
9258 			goto done;
9259 		}
9260 		if (rval) {
9261 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9262 			    "st_check_media: TUR failed, going to retry\n");
9263 			un->un_mediastate = prev_state;
9264 			un->un_state = ST_STATE_OFFLINE;
9265 			goto retry;
9266 		}
9267 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9268 		    "st_check_media: media inserted\n");
9269 
9270 		/* this also rewinds the tape */
9271 		rval = st_tape_init(un);
9272 		if (rval != 0) {
9273 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9274 			    "st_check_media : OFFLINE init failure ");
9275 			un->un_state = ST_STATE_OFFLINE;
9276 			un->un_pos.pmode = invalid;
9277 		} else {
9278 			un->un_state = ST_STATE_OPEN_PENDING_IO;
9279 		}
9280 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
9281 	    (un->un_state != ST_STATE_OFFLINE)) {
9282 		/*
9283 		 * supported devices must be rewound before ejection
9284 		 * rewind resets fileno & blkno
9285 		 */
9286 		un->un_laststate = un->un_state;
9287 		un->un_state = ST_STATE_OFFLINE;
9288 	}
9289 	mutex_exit(ST_MUTEX);
9290 done:
9291 	if (token) {
9292 		(void) scsi_watch_request_terminate(token,
9293 		    SCSI_WATCH_TERMINATE_WAIT);
9294 		mutex_enter(ST_MUTEX);
9295 		un->un_swr_token = (opaque_t)NULL;
9296 		mutex_exit(ST_MUTEX);
9297 	}
9298 
9299 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
9300 
9301 	return (rval);
9302 }
9303 
9304 /*
9305  * st_media_watch_cb() is called by scsi_watch_thread for
9306  * verifying the request sense data (if any)
9307  */
9308 static int
9309 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
9310 {
9311 	struct scsi_status *statusp = resultp->statusp;
9312 	struct scsi_extended_sense *sensep = resultp->sensep;
9313 	uchar_t actual_sense_length = resultp->actual_sense_length;
9314 	struct scsi_tape *un;
9315 	enum mtio_state state = MTIO_NONE;
9316 	int instance;
9317 	dev_t dev = (dev_t)arg;
9318 
9319 	instance = MTUNIT(dev);
9320 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
9321 		return (-1);
9322 	}
9323 
9324 	mutex_enter(ST_MUTEX);
9325 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
9326 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9327 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
9328 	    *((char *)statusp), (void *)sensep,
9329 	    actual_sense_length);
9330 
9331 
9332 	/*
9333 	 * if there was a check condition then sensep points to valid
9334 	 * sense data
9335 	 * if status was not a check condition but a reservation or busy
9336 	 * status then the new state is MTIO_NONE
9337 	 */
9338 	if (sensep) {
9339 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9340 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
9341 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
9342 
9343 		switch (un->un_dp->type) {
9344 		default:
9345 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9346 			    "st_media_watch_cb: unknown drive type %d, "
9347 			    "default to ST_TYPE_HP\n", un->un_dp->type);
9348 		/* FALLTHROUGH */
9349 
9350 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
9351 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
9352 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
9353 			if (un->un_dp->type == ST_TYPE_FUJI) {
9354 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9355 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
9356 			} else {
9357 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9358 				    "st_media_watch_cb: ST_TYPE_HP\n");
9359 			}
9360 			switch (sensep->es_key) {
9361 			case KEY_UNIT_ATTENTION:
9362 				/* not ready to ready transition */
9363 				/* hp/es_qual_code == 80 on>off>on */
9364 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
9365 				if (sensep->es_add_code == 0x28) {
9366 					state = MTIO_INSERTED;
9367 				}
9368 				break;
9369 			case KEY_NOT_READY:
9370 				/* in process, rewinding or loading */
9371 				if ((sensep->es_add_code == 0x04) &&
9372 				    (sensep->es_qual_code == 0x00)) {
9373 					state = MTIO_EJECTED;
9374 				}
9375 				break;
9376 			}
9377 			break;
9378 
9379 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
9380 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9381 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
9382 			switch (sensep->es_key) {
9383 			case KEY_UNIT_ATTENTION:
9384 				/* operator medium removal request */
9385 				if ((sensep->es_add_code == 0x5a) &&
9386 				    (sensep->es_qual_code == 0x01)) {
9387 					state = MTIO_EJECTED;
9388 				/* not ready to ready transition */
9389 				} else if ((sensep->es_add_code == 0x28) &&
9390 				    (sensep->es_qual_code == 0x00)) {
9391 					state = MTIO_INSERTED;
9392 				}
9393 				break;
9394 			case KEY_NOT_READY:
9395 				/* medium not present */
9396 				if (sensep->es_add_code == 0x3a) {
9397 					state = MTIO_EJECTED;
9398 				}
9399 				break;
9400 			}
9401 			break;
9402 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
9403 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9404 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
9405 			switch (sensep->es_key) {
9406 			case KEY_NOT_READY:
9407 				if ((sensep->es_add_code == 0x04) &&
9408 				    (sensep->es_qual_code == 0x00)) {
9409 					/* volume not mounted? */
9410 					state = MTIO_EJECTED;
9411 				} else if (sensep->es_add_code == 0x3a) {
9412 					state = MTIO_EJECTED;
9413 				}
9414 				break;
9415 			case KEY_UNIT_ATTENTION:
9416 				state = MTIO_EJECTED;
9417 				break;
9418 			}
9419 			break;
9420 
9421 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
9422 			switch (sensep->es_key) {
9423 			case KEY_UNIT_ATTENTION:
9424 				if (sensep->es_add_code == 0x28) {
9425 					state = MTIO_INSERTED;
9426 				}
9427 				break;
9428 			case KEY_NOT_READY:
9429 				if (sensep->es_add_code == 0x04) {
9430 					/* in transition but could be either */
9431 					state = un->un_specified_mediastate;
9432 				} else if ((sensep->es_add_code == 0x3a) &&
9433 				    (sensep->es_qual_code == 0x00)) {
9434 					state = MTIO_EJECTED;
9435 				}
9436 				break;
9437 			}
9438 			break;
9439 		}
9440 	} else if (*((char *)statusp) == STATUS_GOOD) {
9441 		state = MTIO_INSERTED;
9442 	}
9443 
9444 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9445 	    "st_media_watch_cb:state=%x, specified=%x\n",
9446 	    state, un->un_specified_mediastate);
9447 
9448 	/*
9449 	 * now signal the waiting thread if this is *not* the specified state;
9450 	 * delay the signal if the state is MTIO_INSERTED
9451 	 * to allow the target to recover
9452 	 */
9453 	if (state != un->un_specified_mediastate) {
9454 		un->un_mediastate = state;
9455 		if (state == MTIO_INSERTED) {
9456 			/*
9457 			 * delay the signal to give the drive a chance
9458 			 * to do what it apparently needs to do
9459 			 */
9460 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9461 			    "st_media_watch_cb:delayed cv_broadcast\n");
9462 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
9463 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
9464 		} else {
9465 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9466 			    "st_media_watch_cb:immediate cv_broadcast\n");
9467 			cv_broadcast(&un->un_state_cv);
9468 		}
9469 	}
9470 	mutex_exit(ST_MUTEX);
9471 	return (0);
9472 }
9473 
9474 /*
9475  * delayed cv_broadcast to allow for target to recover
9476  * from media insertion
9477  */
9478 static void
9479 st_delayed_cv_broadcast(void *arg)
9480 {
9481 	struct scsi_tape *un = arg;
9482 
9483 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
9484 
9485 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9486 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
9487 
9488 	mutex_enter(ST_MUTEX);
9489 	cv_broadcast(&un->un_state_cv);
9490 	mutex_exit(ST_MUTEX);
9491 }
9492 
9493 /*
9494  * restart cmd currently at the start of the waitq
9495  */
9496 static void
9497 st_start_restart(void *arg)
9498 {
9499 	struct scsi_tape *un = arg;
9500 
9501 	ST_FUNC(ST_DEVINFO, st_start_restart);
9502 
9503 	ASSERT(un != NULL);
9504 
9505 	mutex_enter(ST_MUTEX);
9506 
9507 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_tran_restart()\n");
9508 
9509 	st_start(un);
9510 
9511 	mutex_exit(ST_MUTEX);
9512 }
9513 
9514 
9515 /*
9516  * Command completion processing
9517  *
9518  */
9519 static void
9520 st_intr(struct scsi_pkt *pkt)
9521 {
9522 	recov_info *rcv = pkt->pkt_private;
9523 	struct buf *bp = rcv->cmd_bp;
9524 	struct scsi_tape *un;
9525 	errstate action = COMMAND_DONE;
9526 	clock_t	timout;
9527 	int	status;
9528 
9529 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
9530 
9531 	ST_FUNC(ST_DEVINFO, st_intr);
9532 
9533 	ASSERT(un != NULL);
9534 
9535 	mutex_enter(ST_MUTEX);
9536 
9537 	ASSERT(bp != un->un_recov_buf);
9538 
9539 	un->un_rqs_state &= ~(ST_RQS_ERROR);
9540 
9541 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
9542 
9543 	if (pkt->pkt_reason != CMD_CMPLT) {
9544 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9545 		    "Unhappy packet status reason = %s statistics = 0x%x\n",
9546 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9547 
9548 		/* If device has gone away not much else to do */
9549 		if (pkt->pkt_reason == CMD_DEV_GONE) {
9550 			action = COMMAND_DONE_ERROR;
9551 		} else if ((pkt == un->un_rqs) ||
9552 		    (un->un_state == ST_STATE_SENSING)) {
9553 			ASSERT(pkt == un->un_rqs);
9554 			ASSERT(un->un_state == ST_STATE_SENSING);
9555 			un->un_state = un->un_laststate;
9556 			rcv->cmd_bp = un->un_rqs_bp;
9557 			ST_DO_ERRSTATS(un, st_transerrs);
9558 			action = COMMAND_DONE_ERROR;
9559 		} else {
9560 			action = st_handle_incomplete(un, bp);
9561 		}
9562 	/*
9563 	 * At this point we know that the command was successfully
9564 	 * completed. Now what?
9565 	 */
9566 	} else if ((pkt == un->un_rqs) || (un->un_state == ST_STATE_SENSING)) {
9567 		/*
9568 		 * okay. We were running a REQUEST SENSE. Find
9569 		 * out what to do next.
9570 		 */
9571 		ASSERT(pkt == un->un_rqs);
9572 		ASSERT(un->un_state == ST_STATE_SENSING);
9573 		scsi_sync_pkt(pkt);
9574 		action = st_handle_sense(un, bp, &un->un_pos);
9575 		/*
9576 		 * Make rqs isn't going to be retied.
9577 		 */
9578 		if (action != QUE_BUSY_COMMAND && action != QUE_COMMAND) {
9579 			/*
9580 			 * set pkt back to original packet in case we will have
9581 			 * to requeue it
9582 			 */
9583 			pkt = BP_PKT(bp);
9584 			rcv->cmd_bp = un->un_rqs_bp;
9585 			/*
9586 			 * some actions are based on un_state, hence
9587 			 * restore the state st was in before ST_STATE_SENSING.
9588 			 */
9589 			un->un_state = un->un_laststate;
9590 		}
9591 
9592 	} else if (un->un_arq_enabled && (pkt->pkt_state & STATE_ARQ_DONE)) {
9593 		/*
9594 		 * the transport layer successfully completed an autorqsense
9595 		 */
9596 		action = st_handle_autosense(un, bp, &un->un_pos);
9597 
9598 	} else  if ((SCBP(pkt)->sts_busy) ||
9599 	    (SCBP(pkt)->sts_chk) ||
9600 	    (SCBP(pkt)->sts_vu7)) {
9601 		/*
9602 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9603 		 * to see if the status bits we're okay. If a request sense
9604 		 * is to be run, that will happen.
9605 		 */
9606 		action = st_check_error(un, pkt);
9607 	}
9608 
9609 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9610 		switch (action) {
9611 			case QUE_COMMAND:
9612 				/*
9613 				 * return cmd to head to the queue
9614 				 * since we are suspending so that
9615 				 * it gets restarted during resume
9616 				 */
9617 				st_add_to_queue(&un->un_runqf, &un->un_runql,
9618 				    un->un_runqf, bp);
9619 
9620 				action = JUST_RETURN;
9621 				break;
9622 
9623 			case QUE_SENSE:
9624 				action = COMMAND_DONE_ERROR;
9625 				break;
9626 
9627 			default:
9628 				break;
9629 		}
9630 	}
9631 
9632 	/*
9633 	 * check for undetected path failover.
9634 	 */
9635 	if ((un->un_multipath) &&
9636 	    (un->un_last_path_instance != pkt->pkt_path_instance)) {
9637 		if (un->un_state > ST_STATE_OPENING) {
9638 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
9639 			    "Failover detected, action is %s\n",
9640 			    errstatenames[action]);
9641 			if (action == COMMAND_DONE) {
9642 				action = PATH_FAILED;
9643 			}
9644 		}
9645 		un->un_last_path_instance = pkt->pkt_path_instance;
9646 	}
9647 
9648 	/*
9649 	 * Restore old state if we were sensing.
9650 	 */
9651 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9652 		un->un_state = un->un_laststate;
9653 	}
9654 
9655 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9656 	    "st_intr: pkt=%p, bp=%p, action=%s, status=%x\n",
9657 	    (void *)pkt, (void *)bp, errstatenames[action], SCBP_C(pkt));
9658 
9659 again:
9660 	switch (action) {
9661 	case COMMAND_DONE_EACCES:
9662 		/* this is to report a reservation conflict */
9663 		st_bioerror(bp, EACCES);
9664 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9665 		    "Reservation Conflict \n");
9666 		un->un_pos.pmode = invalid;
9667 
9668 		/*FALLTHROUGH*/
9669 	case COMMAND_DONE_ERROR:
9670 		if (un->un_pos.eof < ST_EOT_PENDING &&
9671 		    un->un_state >= ST_STATE_OPEN) {
9672 			/*
9673 			 * all errors set state of the tape to 'unknown'
9674 			 * unless we're at EOT or are doing append testing.
9675 			 * If sense key was illegal request, preserve state.
9676 			 */
9677 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9678 				un->un_pos.pmode = invalid;
9679 			}
9680 		}
9681 
9682 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9683 		/*
9684 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9685 		 * make sure an error ocurrs, so make sure at least EIO is
9686 		 * returned
9687 		 */
9688 		if (geterror(bp) == 0)
9689 			st_bioerror(bp, EIO);
9690 
9691 		st_set_pe_flag(un);
9692 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9693 		    (un->un_errno == EIO)) {
9694 			un->un_rqs_state &= ~(ST_RQS_VALID);
9695 		}
9696 		break;
9697 
9698 	case COMMAND_DONE_ERROR_RECOVERED:
9699 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9700 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9701 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9702 		if (geterror(bp) == 0) {
9703 			st_bioerror(bp, EIO);
9704 		}
9705 		st_set_pe_flag(un);
9706 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9707 		    (un->un_errno == EIO)) {
9708 			un->un_rqs_state &= ~(ST_RQS_VALID);
9709 		}
9710 		/*FALLTHROUGH*/
9711 	case COMMAND_DONE:
9712 		st_set_state(un, bp);
9713 		break;
9714 
9715 	case QUE_SENSE:
9716 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9717 			goto sense_error;
9718 
9719 		if (un->un_state != ST_STATE_SENSING) {
9720 			un->un_laststate = un->un_state;
9721 			un->un_state = ST_STATE_SENSING;
9722 		}
9723 
9724 		/*
9725 		 * zero the sense data.
9726 		 */
9727 		bzero(un->un_rqs->pkt_scbp, SENSE_LENGTH);
9728 
9729 		/*
9730 		 * If this is not a retry on QUE_SENSE point to the original
9731 		 * bp of the command that got us here.
9732 		 */
9733 		if (pkt != un->un_rqs) {
9734 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp = bp;
9735 		}
9736 
9737 		if (un->un_throttle) {
9738 			un->un_last_throttle = un->un_throttle;
9739 			un->un_throttle = 0;
9740 		}
9741 
9742 		ST_CDB(ST_DEVINFO, "Queue sense CDB",
9743 		    (char *)BP_PKT(bp)->pkt_cdbp);
9744 
9745 		/*
9746 		 * never retry this, some other command will have nuked the
9747 		 * sense, anyway
9748 		 */
9749 		status = st_transport(un, un->un_rqs);
9750 
9751 		if (un->un_last_throttle) {
9752 			un->un_throttle = un->un_last_throttle;
9753 		}
9754 
9755 		if (status == TRAN_ACCEPT) {
9756 			mutex_exit(ST_MUTEX);
9757 			return;
9758 		}
9759 		if (status != TRAN_BUSY)
9760 			ST_DO_ERRSTATS(un, st_transerrs);
9761 sense_error:
9762 		un->un_pos.pmode = invalid;
9763 		st_bioerror(bp, EIO);
9764 		st_set_pe_flag(un);
9765 		break;
9766 
9767 	case QUE_BUSY_COMMAND:
9768 		/* longish timeout */
9769 		timout = ST_STATUS_BUSY_TIMEOUT;
9770 		goto que_it_up;
9771 
9772 	case QUE_COMMAND:
9773 		/* short timeout */
9774 		timout = ST_TRAN_BUSY_TIMEOUT;
9775 que_it_up:
9776 		/*
9777 		 * let st_handle_intr_busy put this bp back on waitq and make
9778 		 * checks to see if it is ok to requeue the command.
9779 		 */
9780 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9781 
9782 		/*
9783 		 * Save the throttle before setting up the timeout
9784 		 */
9785 		if (un->un_throttle) {
9786 			un->un_last_throttle = un->un_throttle;
9787 		}
9788 		mutex_exit(ST_MUTEX);
9789 		if (st_handle_intr_busy(un, bp, timout) == 0)
9790 			return;		/* timeout is setup again */
9791 
9792 		mutex_enter(ST_MUTEX);
9793 		un->un_pos.pmode = invalid;
9794 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9795 		st_bioerror(bp, EIO);
9796 		st_set_pe_flag(un);
9797 		break;
9798 
9799 	case QUE_LAST_COMMAND:
9800 
9801 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9802 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9803 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9804 			goto last_command_error;
9805 		}
9806 		mutex_exit(ST_MUTEX);
9807 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9808 			return;
9809 		mutex_enter(ST_MUTEX);
9810 last_command_error:
9811 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9812 		un->un_pos.pmode = invalid;
9813 		st_bioerror(bp, EIO);
9814 		st_set_pe_flag(un);
9815 		break;
9816 
9817 	case COMMAND_TIMEOUT:
9818 	case DEVICE_RESET:
9819 	case DEVICE_TAMPER:
9820 	case ATTEMPT_RETRY:
9821 	case PATH_FAILED:
9822 		ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9823 		    "Command Recovery called on %s status\n",
9824 		    errstatenames[action]);
9825 		action = st_command_recovery(un, pkt, action);
9826 		goto again;
9827 
9828 	default:
9829 		ASSERT(0);
9830 		/* FALLTHRU */
9831 	case JUST_RETURN:
9832 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9833 		mutex_exit(ST_MUTEX);
9834 		return;
9835 	}
9836 
9837 	ST_DO_KSTATS(bp, kstat_runq_exit);
9838 	st_done_and_mutex_exit(un, bp);
9839 }
9840 
9841 static errstate
9842 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9843 {
9844 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9845 	recov_info *rinfo;
9846 	errstate rval = COMMAND_DONE_ERROR;
9847 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9848 	    un->un_rqs : BP_PKT(bp);
9849 	int result;
9850 
9851 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9852 
9853 	rinfo = (recov_info *)pkt->pkt_private;
9854 
9855 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9856 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9857 
9858 	ASSERT(mutex_owned(ST_MUTEX));
9859 
9860 	switch (pkt->pkt_reason) {
9861 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9862 		/*
9863 		 * this occurs when accessing a powered down drive, no
9864 		 * need to complain; just fail the open
9865 		 */
9866 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9867 
9868 		/*
9869 		 * if we have commands outstanding in HBA, and a command
9870 		 * comes back incomplete, we're hosed, so reset target
9871 		 * If we have the bus, but cmd_incomplete, we probably just
9872 		 * have a failed selection, so don't reset the target, just
9873 		 * requeue the command and try again
9874 		 */
9875 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9876 			goto reset_target;
9877 		}
9878 
9879 		/*
9880 		 * Retry selection a couple more times if we're
9881 		 * open.  If opening, we only try just once to
9882 		 * reduce probe time for nonexistant devices.
9883 		 */
9884 		if ((un->un_laststate > ST_STATE_OPENING) &&
9885 		    (rinfo->pkt_retry_cnt < st_selection_retry_count)) {
9886 			/* XXX check retriable? */
9887 			rval = QUE_COMMAND;
9888 		}
9889 		ST_DO_ERRSTATS(un, st_transerrs);
9890 		break;
9891 
9892 	case CMD_ABORTED:
9893 		/*
9894 		 * most likely this is caused by flush-on-error support. If
9895 		 * it was not there, the we're in trouble.
9896 		 */
9897 		if (!un->un_flush_on_errors) {
9898 			un->un_status = SUN_KEY_FATAL;
9899 			goto reset_target;
9900 		}
9901 
9902 		st_set_pe_errno(un);
9903 		bioerror(bp, un->un_errno);
9904 		if (un->un_errno)
9905 			return (COMMAND_DONE_ERROR);
9906 		else
9907 			return (COMMAND_DONE);
9908 
9909 	case CMD_TIMEOUT:	/* Command timed out */
9910 		un->un_status = SUN_KEY_TIMEOUT;
9911 		return (COMMAND_TIMEOUT);
9912 
9913 	case CMD_TRAN_ERR:
9914 	case CMD_RESET:
9915 		if (pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET)) {
9916 			if ((un->un_rsvd_status &
9917 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
9918 			    ST_RESERVE) {
9919 				un->un_rsvd_status |= ST_LOST_RESERVE;
9920 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
9921 				    "Lost Reservation\n");
9922 			}
9923 			rval = DEVICE_RESET;
9924 			return (rval);
9925 		}
9926 		if (pkt->pkt_statistics & (STAT_ABORTED | STAT_TERMINATED)) {
9927 			rval = DEVICE_RESET;
9928 			return (rval);
9929 		}
9930 		/*FALLTHROUGH*/
9931 	default:
9932 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9933 		    "Unhandled packet status reason = %s statistics = 0x%x\n",
9934 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9935 reset_target:
9936 
9937 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9938 		    "transport completed with %s\n",
9939 		    scsi_rname(pkt->pkt_reason));
9940 		ST_DO_ERRSTATS(un, st_transerrs);
9941 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
9942 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
9943 		    STAT_ABORTED)) == 0)) {
9944 
9945 			/*
9946 			 * If we haven't reserved the drive don't reset it.
9947 			 */
9948 			if ((un->un_rsvd_status &
9949 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9950 				return (rval);
9951 			}
9952 
9953 			/*
9954 			 * if we aren't lost yet we will be soon.
9955 			 */
9956 			un->un_pos.pmode = invalid;
9957 
9958 			result = st_reset(un, RESET_LUN);
9959 
9960 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
9961 				/* no hope left to recover */
9962 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
9963 				    "recovery by resets failed\n");
9964 				return (rval);
9965 			}
9966 		}
9967 	}
9968 
9969 
9970 	if (rinfo->pkt_retry_cnt++ < st_retry_count) {
9971 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9972 			rval = QUE_COMMAND;
9973 		} else if (bp == un->un_sbufp) {
9974 			if (rinfo->privatelen == sizeof (recov_info)) {
9975 				if (rinfo->cmd_attrib->retriable) {
9976 					/*
9977 					 * These commands can be rerun
9978 					 * with impunity
9979 					 */
9980 					rval = QUE_COMMAND;
9981 				}
9982 			} else {
9983 				cmd_attribute const *attrib;
9984 				attrib =
9985 				    st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
9986 				if (attrib->retriable) {
9987 					rval = QUE_COMMAND;
9988 				}
9989 			}
9990 		}
9991 	} else {
9992 		rval = COMMAND_DONE_ERROR;
9993 	}
9994 
9995 	if (un->un_state >= ST_STATE_OPEN) {
9996 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9997 		    fail, scsi_rname(pkt->pkt_reason),
9998 		    (rval == COMMAND_DONE_ERROR)?
9999 		    "giving up" : "retrying command");
10000 	}
10001 	return (rval);
10002 }
10003 
10004 /*
10005  * if the device is busy, then put this bp back on the waitq, on the
10006  * interrupt thread, where we want the head of the queue and not the
10007  * end
10008  *
10009  * The callers of this routine should take measures to save the
10010  * un_throttle in un_last_throttle which will be restored in
10011  * st_intr_restart(). The only exception should be st_intr_restart()
10012  * calling this routine for which the saving is already done.
10013  */
10014 static int
10015 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
10016 	clock_t timeout_interval)
10017 {
10018 
10019 	int queued;
10020 	int rval = 0;
10021 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
10022 
10023 	mutex_enter(ST_MUTEX);
10024 
10025 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
10026 
10027 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10028 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
10029 
10030 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
10031 		queued = 1;
10032 	} else {
10033 		queued = 0;
10034 	}
10035 
10036 	/*
10037 	 * Check to see if we hit the retry timeout. We check to make sure
10038 	 * this is the first one on the runq and make sure we have not
10039 	 * queued up any more, so this one has to be the last on the list
10040 	 * also. If it is not, we have to fail.  If it is not the first, but
10041 	 * is the last we are in trouble anyway, as we are in the interrupt
10042 	 * context here.
10043 	 */
10044 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
10045 	    ((un->un_runqf != bp) && (un->un_runql != bp) && (queued))) {
10046 		rval = -1;
10047 		goto exit;
10048 	}
10049 
10050 	/* put the bp back on the waitq */
10051 	if (queued) {
10052 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
10053 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
10054 	}
10055 
10056 	/*
10057 	 * We don't want any other commands being started in the mean time.
10058 	 * If start had just released mutex after putting something on the
10059 	 * runq, we won't even get here.
10060 	 */
10061 	un->un_throttle = 0;
10062 
10063 	/*
10064 	 * send a marker pkt, if appropriate
10065 	 */
10066 	st_hba_unflush(un);
10067 
10068 	/*
10069 	 * all queues are aligned, we are just waiting to
10070 	 * transport
10071 	 */
10072 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
10073 
10074 exit:
10075 	mutex_exit(ST_MUTEX);
10076 	return (rval);
10077 }
10078 
10079 /*
10080  * To get one error entry from error stack
10081  */
10082 static int
10083 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
10084 {
10085 #ifdef _MULTI_DATAMODEL
10086 	/*
10087 	 * For use when a 32 bit app makes a call into a
10088 	 * 64 bit ioctl
10089 	 */
10090 	struct mterror_entry32 err_entry32;
10091 #endif /* _MULTI_DATAMODEL */
10092 
10093 	int rval = 0;
10094 	struct mterror_entry err_entry;
10095 	struct mterror_entry_stack *err_link_entry_p;
10096 	size_t arq_status_len_in, arq_status_len_kr;
10097 
10098 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
10099 
10100 	ASSERT(mutex_owned(ST_MUTEX));
10101 
10102 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10103 	    "st_get_error_entry()\n");
10104 
10105 	/*
10106 	 * if error record stack empty, return ENXIO
10107 	 */
10108 	if (un->un_error_entry_stk == NULL) {
10109 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10110 		    "st_get_error_entry: Error Entry Stack Empty!\n");
10111 		rval = ENXIO;
10112 		goto ret;
10113 	}
10114 
10115 	/*
10116 	 * get the top entry from stack
10117 	 */
10118 	err_link_entry_p = un->un_error_entry_stk;
10119 	arq_status_len_kr =
10120 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
10121 
10122 #ifdef _MULTI_DATAMODEL
10123 	switch (ddi_model_convert_from(flag & FMODELS)) {
10124 	case DDI_MODEL_ILP32:
10125 		if (ddi_copyin((void *)arg, &err_entry32,
10126 		    MTERROR_ENTRY_SIZE_32, flag)) {
10127 			rval = EFAULT;
10128 			goto ret;
10129 		}
10130 
10131 		arq_status_len_in =
10132 		    (size_t)err_entry32.mtee_arq_status_len;
10133 
10134 		err_entry32.mtee_cdb_len =
10135 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
10136 
10137 		if (arq_status_len_in > arq_status_len_kr)
10138 			err_entry32.mtee_arq_status_len =
10139 			    (size32_t)arq_status_len_kr;
10140 
10141 		if (ddi_copyout(
10142 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10143 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
10144 		    err_entry32.mtee_cdb_len, flag)) {
10145 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10146 			    "st_get_error_entry: Copy cdb buffer error!");
10147 			rval = EFAULT;
10148 		}
10149 
10150 		if (ddi_copyout(
10151 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10152 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
10153 		    err_entry32.mtee_arq_status_len, flag)) {
10154 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10155 			    "st_get_error_entry: copy arq status error!");
10156 			rval = EFAULT;
10157 		}
10158 
10159 		if (ddi_copyout(&err_entry32, (void *)arg,
10160 		    MTERROR_ENTRY_SIZE_32, flag)) {
10161 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10162 			    "st_get_error_entry: copy arq status out error!");
10163 			rval = EFAULT;
10164 		}
10165 		break;
10166 
10167 	case DDI_MODEL_NONE:
10168 		if (ddi_copyin((void *)arg, &err_entry,
10169 		    MTERROR_ENTRY_SIZE_64, flag)) {
10170 			rval = EFAULT;
10171 			goto ret;
10172 		}
10173 		arq_status_len_in = err_entry.mtee_arq_status_len;
10174 
10175 		err_entry.mtee_cdb_len =
10176 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
10177 
10178 		if (arq_status_len_in > arq_status_len_kr)
10179 			err_entry.mtee_arq_status_len =
10180 			    arq_status_len_kr;
10181 
10182 		if (ddi_copyout(
10183 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10184 		    err_entry.mtee_cdb_buf,
10185 		    err_entry.mtee_cdb_len, flag)) {
10186 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10187 			    "st_get_error_entry: Copy cdb buffer error!");
10188 			rval = EFAULT;
10189 		}
10190 
10191 		if (ddi_copyout(
10192 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10193 		    err_entry.mtee_arq_status,
10194 		    err_entry.mtee_arq_status_len, flag)) {
10195 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10196 			    "st_get_error_entry: copy arq status error!");
10197 			rval = EFAULT;
10198 		}
10199 
10200 		if (ddi_copyout(&err_entry, (void *)arg,
10201 		    MTERROR_ENTRY_SIZE_64, flag)) {
10202 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10203 			    "st_get_error_entry: copy arq status out error!");
10204 			rval = EFAULT;
10205 		}
10206 		break;
10207 	}
10208 #else /* _MULTI_DATAMODEL */
10209 	if (ddi_copyin((void *)arg, &err_entry,
10210 	    MTERROR_ENTRY_SIZE_64, flag)) {
10211 		rval = EFAULT;
10212 		goto ret;
10213 	}
10214 	arq_status_len_in = err_entry.mtee_arq_status_len;
10215 
10216 	err_entry.mtee_cdb_len =
10217 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
10218 
10219 	if (arq_status_len_in > arq_status_len_kr)
10220 		err_entry.mtee_arq_status_len =
10221 		    arq_status_len_kr;
10222 
10223 	if (ddi_copyout(
10224 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10225 	    err_entry.mtee_cdb_buf,
10226 	    err_entry.mtee_cdb_len, flag)) {
10227 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10228 		    "st_get_error_entry: Copy cdb buffer error!");
10229 		rval = EFAULT;
10230 	}
10231 
10232 	if (ddi_copyout(
10233 	    err_link_entry_p->mtees_entry.mtee_arq_status,
10234 	    err_entry.mtee_arq_status,
10235 	    err_entry.mtee_arq_status_len, flag)) {
10236 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10237 		    "st_get_error_entry: copy arq status buffer error!");
10238 		rval = EFAULT;
10239 	}
10240 
10241 	if (ddi_copyout(&err_entry, (void *)arg,
10242 	    MTERROR_ENTRY_SIZE_64, flag)) {
10243 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10244 		    "st_get_error_entry: copy arq status out error!");
10245 		rval = EFAULT;
10246 	}
10247 #endif /* _MULTI_DATAMODEL */
10248 
10249 	/*
10250 	 * update stack
10251 	 */
10252 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
10253 
10254 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
10255 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
10256 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
10257 
10258 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
10259 	    SECMDS_STATUS_SIZE);
10260 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
10261 
10262 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
10263 	err_link_entry_p = NULL;
10264 ret:
10265 	return (rval);
10266 }
10267 
10268 /*
10269  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
10270  * the scsi CDB command which causes the error and generates sense data and
10271  * the scsi status.
10272  *
10273  *      error-record stack
10274  *
10275  *
10276  *             TOP                                     BOTTOM
10277  *              ------------------------------------------
10278  *              |   0   |   1   |   2   |   ...  |   n   |
10279  *              ------------------------------------------
10280  *                  ^
10281  *                  |
10282  *       pointer to error entry
10283  *
10284  * when st driver generates one sense data record, it creates a error-entry
10285  * and pushes it onto the stack.
10286  *
10287  */
10288 
10289 static void
10290 st_update_error_stack(struct scsi_tape *un,
10291 			struct scsi_pkt *pkt,
10292 			struct scsi_arq_status *cmd)
10293 {
10294 	struct mterror_entry_stack *err_entry_tmp;
10295 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
10296 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
10297 
10298 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
10299 
10300 	ASSERT(mutex_owned(ST_MUTEX));
10301 
10302 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10303 	    "st_update_error_stack()\n");
10304 
10305 	ASSERT(cmd);
10306 	ASSERT(cdbp);
10307 	if (cdblen == 0) {
10308 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10309 		    "st_update_error_stack: CDB length error!\n");
10310 		return;
10311 	}
10312 
10313 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
10314 	ASSERT(err_entry_tmp != NULL);
10315 
10316 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
10317 	    kmem_alloc(cdblen, KM_SLEEP);
10318 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
10319 
10320 	err_entry_tmp->mtees_entry.mtee_arq_status =
10321 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
10322 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
10323 
10324 	/*
10325 	 * copy cdb command & length to current error entry
10326 	 */
10327 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
10328 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
10329 
10330 	/*
10331 	 * copy scsi status length to current error entry
10332 	 */
10333 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
10334 	    SECMDS_STATUS_SIZE;
10335 
10336 	/*
10337 	 * copy sense data and scsi status to current error entry
10338 	 */
10339 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
10340 	    SECMDS_STATUS_SIZE);
10341 
10342 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
10343 	un->un_error_entry_stk = err_entry_tmp;
10344 
10345 }
10346 
10347 /*
10348  * Empty all the error entry in stack
10349  */
10350 static void
10351 st_empty_error_stack(struct scsi_tape *un)
10352 {
10353 	struct mterror_entry_stack *linkp;
10354 
10355 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
10356 
10357 	ASSERT(mutex_owned(ST_MUTEX));
10358 
10359 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10360 	    "st_empty_entry_stack()\n");
10361 
10362 	while (un->un_error_entry_stk != NULL) {
10363 		linkp = un->un_error_entry_stk;
10364 		un->un_error_entry_stk =
10365 		    un->un_error_entry_stk->mtees_nextp;
10366 
10367 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
10368 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
10369 			    linkp->mtees_entry.mtee_cdb_len);
10370 
10371 		if (linkp->mtees_entry.mtee_arq_status != NULL)
10372 			kmem_free(linkp->mtees_entry.mtee_arq_status,
10373 			    linkp->mtees_entry.mtee_arq_status_len);
10374 
10375 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
10376 		linkp = NULL;
10377 	}
10378 }
10379 
10380 static errstate
10381 st_handle_sense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10382 {
10383 	struct scsi_pkt *pkt = BP_PKT(bp);
10384 	struct scsi_pkt *rqpkt = un->un_rqs;
10385 	struct scsi_arq_status arqstat;
10386 	recov_info *rcif = pkt->pkt_private;
10387 
10388 	errstate rval = COMMAND_DONE_ERROR;
10389 	int amt;
10390 
10391 	ST_FUNC(ST_DEVINFO, st_handle_sense);
10392 
10393 	ASSERT(mutex_owned(ST_MUTEX));
10394 
10395 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10396 	    "st_handle_sense()\n");
10397 
10398 	if (SCBP(rqpkt)->sts_busy) {
10399 		if (rcif->privatelen == sizeof (recov_info)) {
10400 			ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
10401 			    "Attempt recovery of busy unit on request sense\n");
10402 			rval = ATTEMPT_RETRY;
10403 		} else if (rcif->pkt_retry_cnt++ < st_retry_count) {
10404 			ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10405 			    "Retry busy unit on request sense\n");
10406 			rval = QUE_BUSY_COMMAND;
10407 		}
10408 		return (rval);
10409 	} else if (SCBP(rqpkt)->sts_chk) {
10410 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10411 		    "Check Condition on REQUEST SENSE\n");
10412 		return (rval);
10413 	}
10414 
10415 	/*
10416 	 * Make sure there is sense data to look at.
10417 	 */
10418 	if ((rqpkt->pkt_state & (STATE_GOT_BUS | STATE_GOT_TARGET |
10419 	    STATE_SENT_CMD | STATE_GOT_STATUS)) != (STATE_GOT_BUS |
10420 	    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) {
10421 		return (rval);
10422 	}
10423 
10424 	/* was there enough data? */
10425 	amt = (int)MAX_SENSE_LENGTH - rqpkt->pkt_resid;
10426 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
10427 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10428 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10429 		    "REQUEST SENSE couldn't get sense data\n");
10430 		return (rval);
10431 	}
10432 
10433 	bcopy(SCBP(pkt), &arqstat.sts_status,
10434 	    sizeof (struct scsi_status));
10435 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
10436 	    sizeof (struct scsi_status));
10437 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
10438 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
10439 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
10440 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
10441 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
10442 
10443 	/*
10444 	 * copy one arqstat entry in the sense data buffer
10445 	 */
10446 	st_update_error_stack(un, pkt, &arqstat);
10447 	return (st_decode_sense(un, bp, amt, &arqstat, pos));
10448 }
10449 
10450 static errstate
10451 st_handle_autosense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10452 {
10453 	struct scsi_pkt *pkt = BP_PKT(bp);
10454 	struct scsi_arq_status *arqstat =
10455 	    (struct scsi_arq_status *)pkt->pkt_scbp;
10456 	errstate rval = COMMAND_DONE_ERROR;
10457 	int amt;
10458 
10459 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
10460 
10461 	ASSERT(mutex_owned(ST_MUTEX));
10462 
10463 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10464 	    "st_handle_autosense()\n");
10465 
10466 	if (arqstat->sts_rqpkt_status.sts_busy) {
10467 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10468 		    "busy unit on request sense\n");
10469 		/*
10470 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
10471 		 * the disadvantage is that we do not have any delay for the
10472 		 * second retry of rqsense and we have to keep a packet around
10473 		 */
10474 		return (QUE_SENSE);
10475 
10476 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
10477 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10478 		    "transport error on REQUEST SENSE\n");
10479 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
10480 		    ((arqstat->sts_rqpkt_statistics &
10481 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
10482 			if (st_reset(un, RESET_LUN) == 0) {
10483 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10484 				    "recovery by resets failed\n");
10485 			}
10486 		}
10487 		return (rval);
10488 
10489 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
10490 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10491 		    "Check Condition on REQUEST SENSE\n");
10492 		return (rval);
10493 	}
10494 
10495 
10496 	/* was there enough data? */
10497 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10498 		amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10499 	} else {
10500 		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
10501 			amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10502 		} else {
10503 			amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10504 		}
10505 	}
10506 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
10507 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10508 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10509 		    "REQUEST SENSE couldn't get sense data\n");
10510 		return (rval);
10511 	}
10512 
10513 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10514 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, MAX_SENSE_LENGTH);
10515 	} else {
10516 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
10517 	}
10518 
10519 	/*
10520 	 * copy one arqstat entry in the sense data buffer
10521 	 */
10522 	st_update_error_stack(un, pkt, arqstat);
10523 
10524 	return (st_decode_sense(un, bp, amt, arqstat, pos));
10525 }
10526 
10527 static errstate
10528 st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
10529     struct scsi_arq_status *statusp, tapepos_t *pos)
10530 {
10531 	struct scsi_pkt *pkt = BP_PKT(bp);
10532 	recov_info *ri = pkt->pkt_private;
10533 	errstate rval = COMMAND_DONE_ERROR;
10534 	cmd_attribute const *attrib;
10535 	long resid;
10536 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10537 	int severity;
10538 	int get_error;
10539 
10540 	ST_FUNC(ST_DEVINFO, st_decode_sense);
10541 
10542 	ASSERT(mutex_owned(ST_MUTEX));
10543 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10544 	    "st_decode_sense()\n");
10545 
10546 	/*
10547 	 * For uscsi commands, squirrel away a copy of the
10548 	 * results of the Request Sense.
10549 	 */
10550 	if (USCSI_CMD(bp)) {
10551 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
10552 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
10553 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
10554 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
10555 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
10556 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
10557 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10558 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
10559 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
10560 		}
10561 	}
10562 
10563 	if (ri->privatelen == sizeof (recov_info)) {
10564 		attrib = ri->cmd_attrib;
10565 	} else {
10566 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10567 	}
10568 
10569 	/*
10570 	 * If the drive is an MT-02, reposition the
10571 	 * secondary error code into the proper place.
10572 	 *
10573 	 * XXX	MT-02 is non-CCS tape, so secondary error code
10574 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
10575 	 * so it's in byte 12.
10576 	 */
10577 	if (un->un_dp->type == ST_TYPE_EMULEX) {
10578 		sensep->es_code = sensep->es_add_info[0];
10579 	}
10580 
10581 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
10582 	    (caddr_t)&CDBP(pkt)->scc_cmd);
10583 
10584 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)statusp,
10585 	    sizeof (*statusp));
10586 
10587 	/* for normal I/O check extract the resid values. */
10588 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
10589 		if (sensep->es_valid) {
10590 			resid =
10591 			    (sensep->es_info_1 << 24) |
10592 			    (sensep->es_info_2 << 16) |
10593 			    (sensep->es_info_3 << 8)  |
10594 			    (sensep->es_info_4);
10595 			/* If fixed block */
10596 			if (un->un_bsize) {
10597 				resid *= un->un_bsize;
10598 			}
10599 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
10600 			resid = pkt->pkt_resid;
10601 		} else {
10602 			resid = bp->b_bcount;
10603 		}
10604 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10605 		    "st_decode_sense (rw): xferred bit = %d, resid=%ld (%d), "
10606 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
10607 		    resid,
10608 		    (sensep->es_info_1 << 24) |
10609 		    (sensep->es_info_2 << 16) |
10610 		    (sensep->es_info_3 << 8)  |
10611 		    (sensep->es_info_4),
10612 		    pkt->pkt_resid);
10613 		/*
10614 		 * The problem is, what should we believe?
10615 		 */
10616 		if (resid && (pkt->pkt_resid == 0)) {
10617 			pkt->pkt_resid = resid;
10618 		}
10619 	} else {
10620 		/*
10621 		 * If the command is SCMD_SPACE, we need to get the
10622 		 * residual as returned in the sense data, to adjust
10623 		 * our idea of current tape position correctly
10624 		 */
10625 		if ((sensep->es_valid) &&
10626 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10627 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10628 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
10629 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE_G4) ||
10630 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK)) {
10631 			resid =
10632 			    (sensep->es_info_1 << 24) |
10633 			    (sensep->es_info_2 << 16) |
10634 			    (sensep->es_info_3 << 8)  |
10635 			    (sensep->es_info_4);
10636 			bp->b_resid = resid;
10637 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10638 			    "st_decode_sense(other):	resid=%ld\n", resid);
10639 		} else {
10640 			/*
10641 			 * If the special command is SCMD_READ,
10642 			 * the correct resid will be set later.
10643 			 */
10644 			if (attrib->get_cnt != NULL) {
10645 				resid = attrib->get_cnt(pkt->pkt_cdbp);
10646 			} else {
10647 				resid = bp->b_bcount;
10648 			}
10649 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10650 			    "st_decode_sense(special read):  resid=%ld\n",
10651 			    resid);
10652 		}
10653 	}
10654 
10655 	if ((un->un_state >= ST_STATE_OPEN) &&
10656 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
10657 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
10658 		    "Failed CDB", (char *)pkt->pkt_cdbp);
10659 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10660 		    "sense data", (char *)sensep, amt);
10661 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10662 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10663 		    bp->b_bcount, resid, pkt->pkt_resid);
10664 	}
10665 
10666 	switch (un->un_status = sensep->es_key) {
10667 	case KEY_NO_SENSE:
10668 		severity = SCSI_ERR_INFO;
10669 
10670 		/*
10671 		 * Erase, locate or rewind operation in progress, retry
10672 		 * ASC  ASCQ
10673 		 *  00   18    Erase operation in progress
10674 		 *  00   19    Locate operation in progress
10675 		 *  00   1A    Rewind operation in progress
10676 		 */
10677 		if (sensep->es_add_code == 0 &&
10678 		    ((sensep->es_qual_code == 0x18) ||
10679 		    (sensep->es_qual_code == 0x19) ||
10680 		    (sensep->es_qual_code == 0x1a))) {
10681 			rval = QUE_BUSY_COMMAND;
10682 			break;
10683 		}
10684 
10685 		goto common;
10686 
10687 	case KEY_RECOVERABLE_ERROR:
10688 		severity = SCSI_ERR_RECOVERED;
10689 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10690 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10691 			if (un->un_dp->options &
10692 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10693 				rval = QUE_LAST_COMMAND;
10694 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10695 				    severity, pos->lgclblkno,
10696 				    un->un_err_pos.lgclblkno, scsi_cmds,
10697 				    sensep);
10698 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10699 				    "Command will be retried\n");
10700 			} else {
10701 				severity = SCSI_ERR_FATAL;
10702 				rval = COMMAND_DONE_ERROR_RECOVERED;
10703 				ST_DO_ERRSTATS(un, st_softerrs);
10704 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10705 				    severity, pos->lgclblkno,
10706 				    un->un_err_pos.lgclblkno, scsi_cmds,
10707 				    sensep);
10708 			}
10709 			break;
10710 		}
10711 common:
10712 		/*
10713 		 * XXX only want reads to be stopped by filemarks.
10714 		 * Don't want them to be stopped by EOT.  EOT matters
10715 		 * only on write.
10716 		 */
10717 		if (sensep->es_filmk && !sensep->es_eom) {
10718 			rval = COMMAND_DONE;
10719 		} else if (sensep->es_eom) {
10720 			rval = COMMAND_DONE;
10721 		} else if (sensep->es_ili) {
10722 			/*
10723 			 * Fun with variable length record devices:
10724 			 * for specifying larger blocks sizes than the
10725 			 * actual physical record size.
10726 			 */
10727 			if (un->un_bsize == 0 && resid > 0) {
10728 				/*
10729 				 * XXX! Ugly.
10730 				 * The requested blocksize is > tape blocksize,
10731 				 * so this is ok, so we just return the
10732 				 * actual size xferred.
10733 				 */
10734 				pkt->pkt_resid = resid;
10735 				rval = COMMAND_DONE;
10736 			} else if (un->un_bsize == 0 && resid < 0) {
10737 				/*
10738 				 * The requested blocksize is < tape blocksize,
10739 				 * so this is not ok, so we err with ENOMEM
10740 				 */
10741 				rval = COMMAND_DONE_ERROR_RECOVERED;
10742 				st_bioerror(bp, ENOMEM);
10743 			} else {
10744 				ST_DO_ERRSTATS(un, st_softerrs);
10745 				severity = SCSI_ERR_FATAL;
10746 				rval = COMMAND_DONE_ERROR;
10747 				st_bioerror(bp, EINVAL);
10748 				un->un_running.pmode = invalid;
10749 			}
10750 		} else {
10751 			/*
10752 			 * we hope and pray for this just being
10753 			 * something we can ignore (ie. a
10754 			 * truly recoverable soft error)
10755 			 */
10756 			rval = COMMAND_DONE;
10757 		}
10758 		if (sensep->es_filmk) {
10759 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10760 			    "filemark\n");
10761 			un->un_status = SUN_KEY_EOF;
10762 			pos->eof = ST_EOF_PENDING;
10763 			st_set_pe_flag(un);
10764 		}
10765 
10766 		/*
10767 		 * ignore eom when reading, a fmk should terminate reading
10768 		 */
10769 		if ((sensep->es_eom) &&
10770 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10771 			if ((sensep->es_add_code == 0) &&
10772 			    (sensep->es_qual_code == 4)) {
10773 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10774 				    "bot\n");
10775 				un->un_status = SUN_KEY_BOT;
10776 				pos->eof = ST_NO_EOF;
10777 				pos->lgclblkno = 0;
10778 				pos->fileno = 0;
10779 				pos->blkno = 0;
10780 				if (pos->pmode != legacy)
10781 					pos->pmode = legacy;
10782 			} else {
10783 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10784 				    "eom\n");
10785 				un->un_status = SUN_KEY_EOT;
10786 				pos->eof = ST_EOM;
10787 			}
10788 			st_set_pe_flag(un);
10789 		}
10790 
10791 		break;
10792 
10793 	case KEY_ILLEGAL_REQUEST:
10794 
10795 		if (un->un_laststate >= ST_STATE_OPEN) {
10796 			ST_DO_ERRSTATS(un, st_softerrs);
10797 			severity = SCSI_ERR_FATAL;
10798 		} else {
10799 			severity = SCSI_ERR_INFO;
10800 		}
10801 		break;
10802 
10803 	case KEY_MEDIUM_ERROR:
10804 		ST_DO_ERRSTATS(un, st_harderrs);
10805 		severity = SCSI_ERR_FATAL;
10806 check_keys:
10807 		/*
10808 		 * attempt to process the keys in the presence of
10809 		 * other errors
10810 		 */
10811 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10812 			/*
10813 			 * Fun with variable length record devices:
10814 			 * for specifying larger blocks sizes than the
10815 			 * actual physical record size.
10816 			 */
10817 			if (un->un_bsize == 0 && resid > 0) {
10818 				/*
10819 				 * XXX! Ugly
10820 				 */
10821 				pkt->pkt_resid = resid;
10822 			} else if (un->un_bsize == 0 && resid < 0) {
10823 				st_bioerror(bp, EINVAL);
10824 			} else {
10825 				severity = SCSI_ERR_FATAL;
10826 				rval = COMMAND_DONE_ERROR;
10827 				st_bioerror(bp, EINVAL);
10828 			}
10829 		}
10830 		if (sensep->es_filmk) {
10831 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10832 			    "filemark\n");
10833 			un->un_status = SUN_KEY_EOF;
10834 			pos->eof = ST_EOF_PENDING;
10835 			st_set_pe_flag(un);
10836 		}
10837 
10838 		/*
10839 		 * ignore eom when reading, a fmk should terminate reading
10840 		 */
10841 		if ((sensep->es_eom) &&
10842 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10843 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10844 			un->un_status = SUN_KEY_EOT;
10845 			pos->eof = ST_EOM;
10846 			st_set_pe_flag(un);
10847 		}
10848 
10849 		break;
10850 
10851 	case KEY_VOLUME_OVERFLOW:
10852 		ST_DO_ERRSTATS(un, st_softerrs);
10853 		pos->eof = ST_EOM;
10854 		severity = SCSI_ERR_FATAL;
10855 		rval = COMMAND_DONE_ERROR;
10856 		goto check_keys;
10857 
10858 	case KEY_HARDWARE_ERROR:
10859 		ST_DO_ERRSTATS(un, st_harderrs);
10860 		severity = SCSI_ERR_FATAL;
10861 		rval = COMMAND_DONE_ERROR;
10862 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10863 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10864 		break;
10865 
10866 	case KEY_BLANK_CHECK:
10867 		ST_DO_ERRSTATS(un, st_softerrs);
10868 		severity = SCSI_ERR_INFO;
10869 
10870 		/*
10871 		 * if not a special request and some data was xferred then it
10872 		 * it is not an error yet
10873 		 */
10874 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10875 			/*
10876 			 * no error for read with or without data xferred
10877 			 */
10878 			un->un_status = SUN_KEY_EOT;
10879 			pos->eof = ST_EOT;
10880 			rval = COMMAND_DONE_ERROR;
10881 			un->un_running.pmode = invalid;
10882 			st_set_pe_flag(un);
10883 			goto check_keys;
10884 		} else if (bp != un->un_sbufp &&
10885 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10886 			rval = COMMAND_DONE;
10887 		} else {
10888 			rval = COMMAND_DONE_ERROR_RECOVERED;
10889 		}
10890 
10891 		if (un->un_laststate >= ST_STATE_OPEN) {
10892 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10893 			    "blank check\n");
10894 			pos->eof = ST_EOM;
10895 		}
10896 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10897 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10898 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
10899 		    (un->un_dp->options & ST_KNOWS_EOD)) {
10900 			/*
10901 			 * we were doing a fast forward by skipping
10902 			 * multiple fmk at the time
10903 			 */
10904 			st_bioerror(bp, EIO);
10905 			severity = SCSI_ERR_RECOVERED;
10906 			rval	 = COMMAND_DONE;
10907 		}
10908 		st_set_pe_flag(un);
10909 		goto check_keys;
10910 
10911 	case KEY_WRITE_PROTECT:
10912 		if (st_wrongtapetype(un)) {
10913 			un->un_status = SUN_KEY_WRONGMEDIA;
10914 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10915 			    "wrong tape for writing- use DC6150 tape "
10916 			    "(or equivalent)\n");
10917 			severity = SCSI_ERR_UNKNOWN;
10918 		} else {
10919 			severity = SCSI_ERR_FATAL;
10920 		}
10921 		ST_DO_ERRSTATS(un, st_harderrs);
10922 		rval = COMMAND_DONE_ERROR;
10923 		st_bioerror(bp, EACCES);
10924 		break;
10925 
10926 	case KEY_UNIT_ATTENTION:
10927 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10928 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
10929 
10930 		un->un_unit_attention_flags |= 1;
10931 		/*
10932 		 * If we have detected a Bus Reset and the tape
10933 		 * drive has been reserved.
10934 		 */
10935 		if (ST_RQSENSE->es_add_code == 0x29) {
10936 			rval = DEVICE_RESET;
10937 			if ((un->un_rsvd_status &
10938 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
10939 			    ST_RESERVE) {
10940 				un->un_rsvd_status |= ST_LOST_RESERVE;
10941 				ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
10942 				    "st_decode_sense: Lost Reservation\n");
10943 			}
10944 		}
10945 
10946 		/*
10947 		 * If this is a recovery command and retrable, retry.
10948 		 */
10949 		if (bp == un->un_recov_buf) {
10950 			severity = SCSI_ERR_INFO;
10951 			if (attrib->retriable &&
10952 			    ri->pkt_retry_cnt++ < st_retry_count) {
10953 				rval = QUE_COMMAND;
10954 			} else {
10955 				rval = COMMAND_DONE_ERROR;
10956 			}
10957 			break; /* Don't set position invalid */
10958 		}
10959 
10960 		/*
10961 		 * If ST_APPLICATION_RESERVATIONS is set,
10962 		 * If the asc/ascq indicates that the reservation
10963 		 * has been cleared just allow the write to continue
10964 		 * which would force a scsi 2 reserve.
10965 		 * If preempted that persistent reservation
10966 		 * the scsi 2 reserve would get a reservation conflict.
10967 		 */
10968 		if ((un->un_rsvd_status &
10969 		    ST_APPLICATION_RESERVATIONS) != 0) {
10970 			/*
10971 			 * RESERVATIONS PREEMPTED
10972 			 * With MPxIO this could be a fail over? XXX
10973 			 */
10974 			if (ST_RQSENSE->es_add_code == 0x2a &&
10975 			    ST_RQSENSE->es_qual_code == 0x03) {
10976 				severity = SCSI_ERR_INFO;
10977 				rval = COMMAND_DONE_ERROR;
10978 				pos->pmode = invalid;
10979 				break;
10980 			/*
10981 			 * RESERVATIONS RELEASED
10982 			 */
10983 			} else if (ST_RQSENSE->es_add_code == 0x2a &&
10984 			    ST_RQSENSE->es_qual_code == 0x04) {
10985 				severity = SCSI_ERR_INFO;
10986 				rval = COMMAND_DONE;
10987 				break;
10988 			}
10989 		}
10990 
10991 		if (un->un_state <= ST_STATE_OPENING) {
10992 			/*
10993 			 * Look, the tape isn't open yet, now determine
10994 			 * if the cause is a BUS RESET, Save the file
10995 			 * and Block positions for the callers to
10996 			 * recover from the loss of position.
10997 			 */
10998 			severity = SCSI_ERR_INFO;
10999 			if ((pos->pmode != invalid) &&
11000 			    (rval == DEVICE_RESET) &&
11001 			    (un->un_restore_pos != 1)) {
11002 				un->un_save_fileno = pos->fileno;
11003 				un->un_save_blkno = pos->blkno;
11004 				un->un_restore_pos = 1;
11005 			}
11006 
11007 			if (attrib->retriable &&
11008 			    ri->pkt_retry_cnt++ < st_retry_count) {
11009 				rval = QUE_COMMAND;
11010 			} else if (rval == DEVICE_RESET) {
11011 				break;
11012 			} else {
11013 				rval = COMMAND_DONE_ERROR;
11014 			}
11015 		/*
11016 		 * Means it thinks the mode parameters have changed.
11017 		 * This is the result of a reset clearing settings or
11018 		 * another initiator changing what we set.
11019 		 */
11020 		}
11021 		if (ST_RQSENSE->es_add_code == 0x2a) {
11022 			if (ST_RQSENSE->es_qual_code == 0x1) {
11023 				/* Error recovery will modeselect and retry. */
11024 				rval = DEVICE_TAMPER;
11025 				severity = SCSI_ERR_INFO;
11026 				break; /* don't set position invalid */
11027 			}
11028 			if (ST_RQSENSE->es_qual_code == 0x0 ||
11029 			    ST_RQSENSE->es_qual_code == 0x2 ||
11030 			    ST_RQSENSE->es_qual_code == 0x3 ||
11031 			    ST_RQSENSE->es_qual_code == 0x4 ||
11032 			    ST_RQSENSE->es_qual_code == 0x5 ||
11033 			    ST_RQSENSE->es_qual_code == 0x6 ||
11034 			    ST_RQSENSE->es_qual_code == 0x7) {
11035 				rval = DEVICE_TAMPER;
11036 				severity = SCSI_ERR_INFO;
11037 			}
11038 		} else if (ST_RQSENSE->es_add_code == 0x28 &&
11039 		    ((ST_RQSENSE->es_qual_code == 0x0) ||
11040 		    ST_RQSENSE->es_qual_code == 0x5)) {
11041 			/*
11042 			 * Not Ready to Ready change, Media may have changed.
11043 			 */
11044 			rval = DEVICE_TAMPER;
11045 			severity = SCSI_ERR_RETRYABLE;
11046 		} else {
11047 			if (rval != DEVICE_RESET) {
11048 				rval = COMMAND_DONE_ERROR;
11049 			} else {
11050 				/*
11051 				 * Returning DEVICE_RESET will call
11052 				 * error recovery.
11053 				 */
11054 				severity = SCSI_ERR_INFO;
11055 				break; /* don't set position invalid */
11056 			}
11057 			/*
11058 			 * Check if it is an Unexpected Unit Attention.
11059 			 * If state is >= ST_STATE_OPEN, we have
11060 			 * already done the initialization .
11061 			 * In this case it is Fatal Error
11062 			 * since no further reading/writing
11063 			 * can be done with fileno set to < 0.
11064 			 */
11065 			if (un->un_state >= ST_STATE_OPEN) {
11066 				ST_DO_ERRSTATS(un, st_harderrs);
11067 				severity = SCSI_ERR_FATAL;
11068 			} else {
11069 				severity = SCSI_ERR_INFO;
11070 			}
11071 		}
11072 
11073 		pos->pmode = invalid;
11074 
11075 		break;
11076 
11077 	case KEY_NOT_READY:
11078 		/*
11079 		 * If in process of getting ready retry.
11080 		 */
11081 		if (sensep->es_add_code  == 0x04 &&
11082 		    sensep->es_qual_code == 0x01 &&
11083 		    ri->pkt_retry_cnt++ < st_retry_count) {
11084 			rval = QUE_COMMAND;
11085 			severity = SCSI_ERR_INFO;
11086 		} else {
11087 			/* give up */
11088 			rval = COMMAND_DONE_ERROR;
11089 			severity = SCSI_ERR_FATAL;
11090 		}
11091 
11092 		/*
11093 		 * If this was an error and after device opened
11094 		 * do error stats.
11095 		 */
11096 		if (rval == COMMAND_DONE_ERROR &&
11097 		    un->un_state > ST_STATE_OPENING) {
11098 			ST_DO_ERRSTATS(un, st_harderrs);
11099 		}
11100 
11101 		if (ST_RQSENSE->es_add_code == 0x3a) {
11102 			if (st_error_level >= SCSI_ERR_FATAL)
11103 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11104 				    "Tape not inserted in drive\n");
11105 			un->un_mediastate = MTIO_EJECTED;
11106 			cv_broadcast(&un->un_state_cv);
11107 		}
11108 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
11109 		    (rval != QUE_COMMAND))
11110 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
11111 		break;
11112 
11113 	case KEY_ABORTED_COMMAND:
11114 		/* XXX Do drives return this when they see a lost light? */
11115 		/* Testing would say yes */
11116 
11117 		if (ri->pkt_retry_cnt++ < st_retry_count) {
11118 			rval = ATTEMPT_RETRY;
11119 			severity = SCSI_ERR_RETRYABLE;
11120 			goto check_keys;
11121 		}
11122 		/*
11123 		 * Probably a parity error...
11124 		 * if we retry here then this may cause data to be
11125 		 * written twice or data skipped during reading
11126 		 */
11127 		ST_DO_ERRSTATS(un, st_harderrs);
11128 		severity = SCSI_ERR_FATAL;
11129 		rval = COMMAND_DONE_ERROR;
11130 		goto check_keys;
11131 
11132 	default:
11133 		/*
11134 		 * Undecoded sense key.	 Try retries and hope
11135 		 * that will fix the problem.  Otherwise, we're
11136 		 * dead.
11137 		 */
11138 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11139 		    "Unhandled Sense Key '%s'\n",
11140 		    sense_keys[un->un_status]);
11141 		ST_DO_ERRSTATS(un, st_harderrs);
11142 		severity = SCSI_ERR_FATAL;
11143 		rval = COMMAND_DONE_ERROR;
11144 		goto check_keys;
11145 	}
11146 
11147 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
11148 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
11149 	    (un->un_laststate > ST_STATE_OPENING) &&
11150 	    (severity >= st_error_level))) {
11151 
11152 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
11153 		    pos->lgclblkno, un->un_err_pos.lgclblkno,
11154 		    scsi_cmds, sensep);
11155 		if (sensep->es_filmk) {
11156 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11157 			    "File Mark Detected\n");
11158 		}
11159 		if (sensep->es_eom) {
11160 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11161 			    "End-of-Media Detected\n");
11162 		}
11163 		if (sensep->es_ili) {
11164 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11165 			    "Incorrect Length Indicator Set\n");
11166 		}
11167 	}
11168 	get_error = geterror(bp);
11169 	if (((rval == COMMAND_DONE_ERROR) ||
11170 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
11171 	    ((get_error == EIO) || (get_error == 0))) {
11172 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
11173 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
11174 		if (un->un_rqs_state & ST_RQS_READ) {
11175 			un->un_rqs_state &= ~(ST_RQS_READ);
11176 		} else {
11177 			un->un_rqs_state |= ST_RQS_OVR;
11178 		}
11179 	}
11180 
11181 	return (rval);
11182 }
11183 
11184 
11185 static int
11186 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
11187 {
11188 	int status = TRAN_ACCEPT;
11189 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
11190 
11191 	mutex_enter(ST_MUTEX);
11192 
11193 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
11194 
11195 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11196 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
11197 
11198 	/*
11199 	 * Check to see if we hit the retry timeout. We check to make sure
11200 	 * this is the first one on the runq and make sure we have not
11201 	 * queued up any more, so this one has to be the last on the list
11202 	 * also. If it is not, we have to fail.  If it is not the first, but
11203 	 * is the last we are in trouble anyway, as we are in the interrupt
11204 	 * context here.
11205 	 */
11206 	if ((pktinfo->pkt_retry_cnt > st_retry_count) ||
11207 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
11208 		goto exit;
11209 	}
11210 
11211 	if (un->un_throttle) {
11212 		un->un_last_throttle = un->un_throttle;
11213 		un->un_throttle = 0;
11214 	}
11215 
11216 	/*
11217 	 * Here we know : bp is the first and last one on the runq
11218 	 * it is not necessary to put it back on the head of the
11219 	 * waitq and then move from waitq to runq. Save this queuing
11220 	 * and call scsi_transport.
11221 	 */
11222 	ST_CDB(ST_DEVINFO, "Retry lcmd CDB", (char *)BP_PKT(bp)->pkt_cdbp);
11223 
11224 	status = st_transport(un, BP_PKT(bp));
11225 
11226 	if (status == TRAN_ACCEPT) {
11227 		if (un->un_last_throttle) {
11228 			un->un_throttle = un->un_last_throttle;
11229 		}
11230 		mutex_exit(ST_MUTEX);
11231 
11232 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11233 		    "restart transport \n");
11234 		return (0);
11235 	}
11236 
11237 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
11238 	mutex_exit(ST_MUTEX);
11239 
11240 	if (status == TRAN_BUSY) {
11241 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
11242 			return (0);
11243 		}
11244 	}
11245 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11246 	    "restart transport rejected\n");
11247 	mutex_enter(ST_MUTEX);
11248 	ST_DO_ERRSTATS(un, st_transerrs);
11249 	if (un->un_last_throttle) {
11250 		un->un_throttle = un->un_last_throttle;
11251 	}
11252 exit:
11253 	mutex_exit(ST_MUTEX);
11254 	return (-1);
11255 }
11256 
11257 static int
11258 st_wrongtapetype(struct scsi_tape *un)
11259 {
11260 
11261 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
11262 
11263 	ASSERT(mutex_owned(ST_MUTEX));
11264 
11265 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
11266 
11267 	/*
11268 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
11269 	 */
11270 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
11271 		switch (un->un_dp->type) {
11272 		case ST_TYPE_WANGTEK:
11273 		case ST_TYPE_ARCHIVE:
11274 			/*
11275 			 * If this really worked, we could go off of
11276 			 * the density codes set in the modesense
11277 			 * page. For this drive, 0x10 == QIC-120,
11278 			 * 0xf == QIC-150, and 0x5 should be for
11279 			 * both QIC-24 and, maybe, QIC-11. However,
11280 			 * the h/w doesn't do what the manual says
11281 			 * that it should, so we'll key off of
11282 			 * getting a WRITE PROTECT error AND wp *not*
11283 			 * set in the mode sense information.
11284 			 */
11285 			/*
11286 			 * XXX but we already know that status is
11287 			 * write protect, so don't check it again.
11288 			 */
11289 
11290 			if (un->un_status == KEY_WRITE_PROTECT &&
11291 			    un->un_mspl->wp == 0) {
11292 				return (1);
11293 			}
11294 			break;
11295 		default:
11296 			break;
11297 		}
11298 	}
11299 	return (0);
11300 }
11301 
11302 static errstate
11303 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
11304 {
11305 	errstate action;
11306 	recov_info *rcvi = pkt->pkt_private;
11307 	buf_t *bp = rcvi->cmd_bp;
11308 	struct scsi_arq_status *stat = (struct scsi_arq_status *)pkt->pkt_scbp;
11309 
11310 	ST_FUNC(ST_DEVINFO, st_check_error);
11311 
11312 	ASSERT(mutex_owned(ST_MUTEX));
11313 
11314 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
11315 
11316 	switch (SCBP_C(pkt)) {
11317 	case STATUS_RESERVATION_CONFLICT:
11318 		/*
11319 		 * Command recovery is enabled, not just opening,
11320 		 * we had the drive reserved and we thing its ours.
11321 		 * Call recovery to attempt to take it back.
11322 		 */
11323 		if ((rcvi->privatelen == sizeof (recov_info)) &&
11324 		    (bp != un->un_recov_buf) &&
11325 		    (un->un_state > ST_STATE_OPEN_PENDING_IO) &&
11326 		    ((un->un_rsvd_status & (ST_RESERVE |
11327 		    ST_APPLICATION_RESERVATIONS)) != 0)) {
11328 			action = ATTEMPT_RETRY;
11329 			un->un_rsvd_status |= ST_LOST_RESERVE;
11330 		} else {
11331 			action = COMMAND_DONE_EACCES;
11332 			un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
11333 		}
11334 		break;
11335 
11336 	case STATUS_BUSY:
11337 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
11338 		if (rcvi->privatelen == sizeof (recov_info) &&
11339 		    un->un_multipath && (pkt->pkt_state == (STATE_GOT_BUS |
11340 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS))) {
11341 			/*
11342 			 * Status returned by scsi_vhci indicating path
11343 			 * has failed over.
11344 			 */
11345 			action = PATH_FAILED;
11346 			break;
11347 		}
11348 		/* FALLTHRU */
11349 	case STATUS_QFULL:
11350 		if (rcvi->privatelen == sizeof (recov_info)) {
11351 			/*
11352 			 * If recovery is inabled use it instead of
11353 			 * blind reties.
11354 			 */
11355 			action = ATTEMPT_RETRY;
11356 		} else if (rcvi->pkt_retry_cnt++ < st_retry_count) {
11357 			action = QUE_BUSY_COMMAND;
11358 		} else if ((un->un_rsvd_status &
11359 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
11360 			/*
11361 			 * If this is a command done before reserve is done
11362 			 * don't reset.
11363 			 */
11364 			action = COMMAND_DONE_ERROR;
11365 		} else {
11366 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11367 			    "unit busy too long\n");
11368 			(void) st_reset(un, RESET_ALL);
11369 			action = COMMAND_DONE_ERROR;
11370 		}
11371 		break;
11372 
11373 	case STATUS_CHECK:
11374 	case STATUS_TERMINATED:
11375 		/*
11376 		 * we should only get here if the auto rqsense failed
11377 		 * thru a uscsi cmd without autorequest sense
11378 		 * so we just try again
11379 		 */
11380 		if (un->un_arq_enabled &&
11381 		    stat->sts_rqpkt_reason == CMD_CMPLT &&
11382 		    (stat->sts_rqpkt_state & (STATE_GOT_BUS |
11383 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) ==
11384 		    (STATE_GOT_BUS | STATE_GOT_TARGET | STATE_SENT_CMD |
11385 		    STATE_GOT_STATUS)) {
11386 
11387 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11388 			    "Really got sense data\n");
11389 			action = st_decode_sense(un, bp, MAX_SENSE_LENGTH -
11390 			    pkt->pkt_resid, stat, &un->un_pos);
11391 		} else {
11392 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11393 			    "Trying to queue sense command\n");
11394 			action = QUE_SENSE;
11395 		}
11396 		break;
11397 
11398 	case STATUS_TASK_ABORT:
11399 		/*
11400 		 * This is an aborted task. This can be a reset on the other
11401 		 * port of a multiport drive. Lets try and recover it.
11402 		 */
11403 		action = DEVICE_RESET;
11404 		break;
11405 
11406 	default:
11407 		action = COMMAND_DONE;
11408 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
11409 		    "Unexpected scsi status byte 0x%x\n", SCBP_C(pkt));
11410 	}
11411 	return (action);
11412 }
11413 
11414 static void
11415 st_calc_bnum(struct scsi_tape *un, struct buf *bp, struct scsi_pkt *pkt)
11416 {
11417 	int nblks;
11418 	int nfiles;
11419 	long count;
11420 	recov_info *ri = pkt->pkt_private;
11421 	cmd_attribute const *attrib;
11422 
11423 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
11424 
11425 	ASSERT(mutex_owned(ST_MUTEX));
11426 
11427 	if (ri->privatelen == sizeof (recov_info)) {
11428 		attrib = ri->cmd_attrib;
11429 		ASSERT(attrib->recov_pos_type == POS_EXPECTED);
11430 		ASSERT(attrib->chg_tape_pos);
11431 	} else {
11432 		ri = NULL;
11433 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
11434 	}
11435 
11436 	count = bp->b_bcount - bp->b_resid;
11437 
11438 	/* Command reads or writes data */
11439 	if (attrib->transfers_data != TRAN_NONE) {
11440 		if (count == 0) {
11441 			/* failed writes should not make it here */
11442 			ASSERT(attrib->transfers_data == TRAN_READ);
11443 			nblks = 0;
11444 			nfiles = 1;
11445 		} else if (un->un_bsize == 0) {
11446 			/*
11447 			 * If variable block mode.
11448 			 * Fixed bit in CBD should be zero.
11449 			 */
11450 			ASSERT((pkt->pkt_cdbp[1] & 1) == 0);
11451 			nblks = 1;
11452 			un->un_kbytes_xferred += (count / ONE_K);
11453 			nfiles = 0;
11454 		} else {
11455 			/*
11456 			 * If fixed block mode.
11457 			 * Fixed bit in CBD should be one.
11458 			 */
11459 			ASSERT((pkt->pkt_cdbp[1] & 1) == 1);
11460 			nblks = (count / un->un_bsize);
11461 			un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
11462 			nfiles = 0;
11463 		}
11464 		/*
11465 		 * So its possable to read some blocks and hit a filemark.
11466 		 * Example reading in fixed block mode where more then one
11467 		 * block at a time is requested. In this case because the
11468 		 * filemark is hit something less then the requesed number
11469 		 * of blocks is read.
11470 		 */
11471 		if (un->un_pos.eof == ST_EOF_PENDING && bp->b_resid) {
11472 			nfiles = 1;
11473 		}
11474 	} else {
11475 		nblks = 0;
11476 		nfiles = count;
11477 	}
11478 
11479 	/*
11480 	 * If some command failed after this one started and it seems
11481 	 * to have finshed without error count the position.
11482 	 */
11483 	if (un->un_persistence && un->un_persist_errors) {
11484 		ASSERT(un->un_pos.pmode != invalid);
11485 	}
11486 
11487 	if (attrib->chg_tape_direction == DIR_FORW) {
11488 		un->un_pos.blkno += nblks;
11489 		un->un_pos.lgclblkno += nblks;
11490 		un->un_pos.lgclblkno += nfiles;
11491 	} else if (attrib->chg_tape_direction == DIR_REVC) {
11492 		un->un_pos.blkno -= nblks;
11493 		un->un_pos.lgclblkno -= nblks;
11494 		un->un_pos.lgclblkno -= nfiles;
11495 	} else {
11496 		ASSERT(0);
11497 	}
11498 
11499 	/* recovery disabled */
11500 	if (ri == NULL) {
11501 		un->un_running.pmode = invalid;
11502 		return;
11503 	}
11504 
11505 	/*
11506 	 * If we didn't just read a filemark.
11507 	 */
11508 	if (un->un_pos.eof != ST_EOF_PENDING) {
11509 		ASSERT(nblks != 0 && nfiles == 0);
11510 		/*
11511 		 * If Previously calulated expected position does not match
11512 		 * debug the expected position.
11513 		 */
11514 		if ((ri->pos.pmode != invalid) && nblks &&
11515 		    ((un->un_pos.blkno != ri->pos.blkno) ||
11516 		    (un->un_pos.lgclblkno != ri->pos.lgclblkno))) {
11517 #ifdef STDEBUG
11518 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11519 			    "Expected", &ri->pos);
11520 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11521 			    "But Got", &un->un_pos);
11522 #endif
11523 			un->un_running.pmode = invalid;
11524 		}
11525 	} else {
11526 		ASSERT(nfiles != 0);
11527 		if (un->un_running.pmode != invalid) {
11528 			/*
11529 			 * blkno and lgclblkno already counted in
11530 			 * st_add_recovery_info_to_pkt(). Since a block was not
11531 			 * read and a filemark was.
11532 			 */
11533 			if (attrib->chg_tape_direction == DIR_FORW) {
11534 				un->un_running.fileno++;
11535 				un->un_running.blkno = 0;
11536 			} else if (attrib->chg_tape_direction == DIR_REVC) {
11537 				un->un_running.fileno--;
11538 				un->un_running.blkno = LASTBLK;
11539 			}
11540 		}
11541 	}
11542 }
11543 
11544 static void
11545 st_set_state(struct scsi_tape *un, struct buf *bp)
11546 {
11547 	struct scsi_pkt *sp = BP_PKT(bp);
11548 	struct uscsi_cmd *ucmd;
11549 
11550 	ST_FUNC(ST_DEVINFO, st_set_state);
11551 
11552 	ASSERT(mutex_owned(ST_MUTEX));
11553 	ASSERT(bp != un->un_recov_buf);
11554 
11555 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11556 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
11557 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
11558 
11559 	if (bp != un->un_sbufp) {
11560 #ifdef STDEBUG
11561 		if (DEBUGGING && sp->pkt_resid) {
11562 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11563 			    "pkt_resid %ld bcount %ld\n",
11564 			    sp->pkt_resid, bp->b_bcount);
11565 		}
11566 #endif
11567 		bp->b_resid = sp->pkt_resid;
11568 		if (geterror(bp) != EIO) {
11569 			st_calc_bnum(un, bp, sp);
11570 		}
11571 		if (bp->b_flags & B_READ) {
11572 			un->un_lastop = ST_OP_READ;
11573 			un->un_fmneeded = 0;
11574 		} else {
11575 			un->un_lastop = ST_OP_WRITE;
11576 			if (un->un_dp->options & ST_REEL) {
11577 				un->un_fmneeded = 2;
11578 			} else {
11579 				un->un_fmneeded = 1;
11580 			}
11581 		}
11582 		/*
11583 		 * all is honky dory at this point, so let's
11584 		 * readjust the throttle, to increase speed, if we
11585 		 * have not throttled down.
11586 		 */
11587 		if (un->un_throttle) {
11588 			un->un_throttle = un->un_max_throttle;
11589 		}
11590 	} else {
11591 		optype new_lastop = ST_OP_NIL;
11592 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
11593 
11594 		switch (cmd) {
11595 		case SCMD_WRITE:
11596 		case SCMD_WRITE_G4:
11597 			bp->b_resid = sp->pkt_resid;
11598 			new_lastop = ST_OP_WRITE;
11599 			if (geterror(bp) == EIO) {
11600 				break;
11601 			}
11602 			st_calc_bnum(un, bp, sp);
11603 			if (un->un_dp->options & ST_REEL) {
11604 				un->un_fmneeded = 2;
11605 			} else {
11606 				un->un_fmneeded = 1;
11607 			}
11608 			break;
11609 		case SCMD_READ:
11610 		case SCMD_READ_G4:
11611 			bp->b_resid = sp->pkt_resid;
11612 			new_lastop = ST_OP_READ;
11613 			if (geterror(bp) == EIO) {
11614 				break;
11615 			}
11616 			st_calc_bnum(un, bp, sp);
11617 			un->un_fmneeded = 0;
11618 			break;
11619 		case SCMD_WRITE_FILE_MARK_G4:
11620 		case SCMD_WRITE_FILE_MARK:
11621 		{
11622 			int fmdone;
11623 
11624 			if (un->un_pos.eof != ST_EOM) {
11625 				un->un_pos.eof = ST_NO_EOF;
11626 			}
11627 			fmdone = (bp->b_bcount - bp->b_resid);
11628 			if (fmdone > 0) {
11629 				un->un_lastop = new_lastop = ST_OP_WEOF;
11630 				un->un_pos.lgclblkno += fmdone;
11631 				un->un_pos.fileno += fmdone;
11632 				un->un_pos.blkno = 0;
11633 			} else {
11634 				new_lastop = ST_OP_CTL;
11635 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11636 				    "Flushed buffer\n");
11637 			}
11638 			if (fmdone > un->un_fmneeded) {
11639 				un->un_fmneeded = 0;
11640 			} else {
11641 				un->un_fmneeded -= fmdone;
11642 			}
11643 			break;
11644 		}
11645 		case SCMD_REWIND:
11646 			un->un_pos.eof = ST_NO_EOF;
11647 			un->un_pos.fileno = 0;
11648 			un->un_pos.blkno = 0;
11649 			un->un_pos.lgclblkno = 0;
11650 			if (un->un_pos.pmode != legacy)
11651 				un->un_pos.pmode = legacy;
11652 			new_lastop = ST_OP_CTL;
11653 			un->un_restore_pos = 0;
11654 			break;
11655 
11656 		case SCMD_SPACE:
11657 		case SCMD_SPACE_G4:
11658 		{
11659 			int64_t count;
11660 			int64_t resid;
11661 			int64_t done;
11662 			cmd_attribute const *attrib;
11663 			recov_info *ri = sp->pkt_private;
11664 
11665 			if (ri->privatelen == sizeof (recov_info)) {
11666 				attrib = ri->cmd_attrib;
11667 			} else {
11668 				attrib =
11669 				    st_lookup_cmd_attribute(sp->pkt_cdbp[0]);
11670 			}
11671 
11672 			resid = (int64_t)SPACE_CNT(bp->b_resid);
11673 			count = (int64_t)attrib->get_cnt(sp->pkt_cdbp);
11674 
11675 			if (count >= 0) {
11676 				done = (count - resid);
11677 			} else {
11678 				done = ((-count) - resid);
11679 			}
11680 			if (done > 0) {
11681 				un->un_lastop = new_lastop = ST_OP_CTL;
11682 			} else {
11683 				new_lastop = ST_OP_CTL;
11684 			}
11685 
11686 			ST_SPAC(ST_DEVINFO, st_label, CE_WARN,
11687 			    "space cmd: cdb[1] = %s\n"
11688 			    "space data:       = 0x%lx\n"
11689 			    "space count:      = %"PRId64"\n"
11690 			    "space resid:      = %"PRId64"\n"
11691 			    "spaces done:      = %"PRId64"\n"
11692 			    "fileno before     = %d\n"
11693 			    "blkno before      = %d\n",
11694 			    space_strs[sp->pkt_cdbp[1] & 7],
11695 			    bp->b_bcount,
11696 			    count, resid, done,
11697 			    un->un_pos.fileno, un->un_pos.blkno);
11698 
11699 			switch (sp->pkt_cdbp[1]) {
11700 			case SPACE_TYPE(SP_FLM):
11701 				/* Space file forward */
11702 				if (count >= 0) {
11703 					if (un->un_pos.eof <= ST_EOF) {
11704 						un->un_pos.eof = ST_NO_EOF;
11705 					}
11706 					un->un_pos.fileno += done;
11707 					un->un_pos.blkno = 0;
11708 					break;
11709 				}
11710 				/* Space file backward */
11711 				if (done > un->un_pos.fileno) {
11712 					un->un_pos.fileno = 0;
11713 					un->un_pos.blkno = 0;
11714 				} else {
11715 					un->un_pos.fileno -= done;
11716 					un->un_pos.blkno = LASTBLK;
11717 					un->un_running.pmode = invalid;
11718 				}
11719 				break;
11720 			case SPACE_TYPE(SP_BLK):
11721 				/* Space block forward */
11722 				if (count >= 0) {
11723 					un->un_pos.blkno += done;
11724 					break;
11725 				}
11726 				/* Space block backward */
11727 				if (un->un_pos.eof >= ST_EOF_PENDING) {
11728 				/*
11729 				 * we stepped back into
11730 				 * a previous file; we are not
11731 				 * making an effort to pretend that
11732 				 * we are still in the current file
11733 				 * ie. logical == physical position
11734 				 * and leave it to st_ioctl to correct
11735 				 */
11736 					if (done > un->un_pos.blkno) {
11737 						un->un_pos.blkno = 0;
11738 					} else {
11739 						un->un_pos.fileno--;
11740 						un->un_pos.blkno = LASTBLK;
11741 						un->un_running.pmode = invalid;
11742 					}
11743 				} else {
11744 					un->un_pos.blkno -= done;
11745 				}
11746 				break;
11747 			case SPACE_TYPE(SP_SQFLM):
11748 				un->un_pos.pmode = logical;
11749 				un->un_pos.blkno = 0;
11750 				un->un_lastop = new_lastop = ST_OP_CTL;
11751 				break;
11752 			case SPACE_TYPE(SP_EOD):
11753 				un->un_pos.pmode = logical;
11754 				un->un_pos.eof = ST_EOM;
11755 				un->un_status = KEY_BLANK_CHECK;
11756 				break;
11757 			default:
11758 				un->un_pos.pmode = invalid;
11759 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11760 				    "Unsupported space cmd: %s\n",
11761 				    space_strs[sp->pkt_cdbp[1] & 7]);
11762 
11763 				un->un_lastop = new_lastop = ST_OP_CTL;
11764 			}
11765 
11766 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11767 			    "after_space rs %"PRId64" fil %d blk %d\n",
11768 			    resid, un->un_pos.fileno, un->un_pos.blkno);
11769 
11770 			break;
11771 		}
11772 		case SCMD_LOAD:
11773 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
11774 				un->un_pos.fileno = 0;
11775 				if (un->un_pos.pmode != legacy)
11776 					un->un_pos.pmode = legacy;
11777 			} else {
11778 				un->un_state = ST_STATE_OFFLINE;
11779 				un->un_pos.pmode = invalid;
11780 
11781 			}
11782 			/*
11783 			 * If we are loading or unloading we expect the media id
11784 			 * to change. Lets make it unknown.
11785 			 */
11786 			if (un->un_media_id != bogusID && un->un_media_id_len) {
11787 				kmem_free(un->un_media_id, un->un_media_id_len);
11788 				un->un_media_id = NULL;
11789 				un->un_media_id_len = 0;
11790 			}
11791 			un->un_density_known = 0;
11792 			un->un_pos.eof = ST_NO_EOF;
11793 			un->un_pos.blkno = 0;
11794 			un->un_lastop = new_lastop = ST_OP_CTL;
11795 			break;
11796 		case SCMD_ERASE:
11797 			un->un_pos.eof = ST_NO_EOF;
11798 			un->un_pos.blkno = 0;
11799 			un->un_pos.fileno = 0;
11800 			un->un_pos.lgclblkno = 0;
11801 			if (un->un_pos.pmode != legacy)
11802 				un->un_pos.pmode = legacy;
11803 			new_lastop = ST_OP_CTL;
11804 			break;
11805 		case SCMD_RESERVE:
11806 			un->un_rsvd_status |= ST_RESERVE;
11807 			un->un_rsvd_status &=
11808 			    ~(ST_RELEASE | ST_LOST_RESERVE |
11809 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11810 			new_lastop = ST_OP_CTL;
11811 			break;
11812 		case SCMD_RELEASE:
11813 			un->un_rsvd_status |= ST_RELEASE;
11814 			un->un_rsvd_status &=
11815 			    ~(ST_RESERVE | ST_LOST_RESERVE |
11816 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11817 			new_lastop = ST_OP_CTL;
11818 			break;
11819 		case SCMD_PERSISTENT_RESERVE_IN:
11820 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11821 			    "PGR_IN command\n");
11822 			new_lastop = ST_OP_CTL;
11823 			break;
11824 		case SCMD_PERSISTENT_RESERVE_OUT:
11825 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
11826 			case ST_SA_SCSI3_RESERVE:
11827 			case ST_SA_SCSI3_PREEMPT:
11828 			case ST_SA_SCSI3_PREEMPTANDABORT:
11829 				un->un_rsvd_status |=
11830 				    (ST_APPLICATION_RESERVATIONS | ST_RESERVE);
11831 				un->un_rsvd_status &= ~(ST_RELEASE |
11832 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11833 				    ST_INITIATED_RESET);
11834 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11835 				    "PGR Reserve and set: entering"
11836 				    " ST_APPLICATION_RESERVATIONS mode");
11837 				break;
11838 			case ST_SA_SCSI3_REGISTER:
11839 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11840 				    "PGR Reserve register key");
11841 				un->un_rsvd_status |= ST_INIT_RESERVE;
11842 				break;
11843 			case ST_SA_SCSI3_CLEAR:
11844 				un->un_rsvd_status &= ~ST_INIT_RESERVE;
11845 				/* FALLTHROUGH */
11846 			case ST_SA_SCSI3_RELEASE:
11847 				un->un_rsvd_status &=
11848 				    ~(ST_APPLICATION_RESERVATIONS | ST_RESERVE |
11849 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11850 				    ST_INITIATED_RESET);
11851 				un->un_rsvd_status |= ST_RELEASE;
11852 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11853 				    "PGR Release and reset: exiting"
11854 				    " ST_APPLICATION_RESERVATIONS mode");
11855 				break;
11856 			}
11857 			new_lastop = ST_OP_CTL;
11858 			break;
11859 		case SCMD_TEST_UNIT_READY:
11860 		case SCMD_READ_BLKLIM:
11861 		case SCMD_REQUEST_SENSE:
11862 		case SCMD_INQUIRY:
11863 		case SCMD_RECOVER_BUF:
11864 		case SCMD_MODE_SELECT:
11865 		case SCMD_MODE_SENSE:
11866 		case SCMD_DOORLOCK:
11867 		case SCMD_READ_BUFFER:
11868 		case SCMD_REPORT_DENSITIES:
11869 		case SCMD_LOG_SELECT_G1:
11870 		case SCMD_LOG_SENSE_G1:
11871 		case SCMD_REPORT_LUNS:
11872 		case SCMD_READ_ATTRIBUTE:
11873 		case SCMD_WRITE_ATTRIBUTE:
11874 		case SCMD_SVC_ACTION_IN_G5:
11875 			new_lastop = ST_OP_CTL;
11876 			break;
11877 		case SCMD_READ_POSITION:
11878 			new_lastop = ST_OP_CTL;
11879 			/*
11880 			 * Only if the buf used was un_sbufp.
11881 			 * Among other things the prevents read positions used
11882 			 * as part of error recovery from messing up our
11883 			 * current position as they will use un_recov_buf.
11884 			 */
11885 			if (USCSI_CMD(bp)) {
11886 				(void) st_get_read_pos(un, bp);
11887 			}
11888 			break;
11889 		case SCMD_LOCATE:
11890 		case SCMD_LOCATE_G4:
11891 			/* Locate makes position mode no longer legacy */
11892 			un->un_lastop = new_lastop = ST_OP_CTL;
11893 			break;
11894 		case SCMD_MAINTENANCE_IN:
11895 			switch (sp->pkt_cdbp[1]) {
11896 			case SSVC_ACTION_GET_SUPPORTED_OPERATIONS:
11897 			case SSVC_ACTION_SET_TARGET_PORT_GROUPS:
11898 				new_lastop = ST_OP_CTL;
11899 				break;
11900 			}
11901 			if (new_lastop != ST_OP_NIL) {
11902 				break;
11903 			}
11904 		default:
11905 			/*
11906 			 * Unknown command, If was USCSI and USCSI_SILENT
11907 			 * flag was not set, set position to unknown.
11908 			 */
11909 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
11910 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
11911 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11912 				    "unknown cmd 0x%X caused loss of state\n",
11913 				    cmd);
11914 			} else {
11915 				/*
11916 				 * keep the old agreement to allow unknown
11917 				 * commands with the USCSI_SILENT set.
11918 				 * This prevents ASSERT below.
11919 				 */
11920 				new_lastop = ST_OP_CTL;
11921 				break;
11922 			}
11923 			/* FALLTHROUGH */
11924 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
11925 			un->un_pos.pmode = invalid;
11926 			un->un_lastop = new_lastop = ST_OP_CTL;
11927 			break;
11928 		}
11929 
11930 		/* new_lastop should have been changed */
11931 		ASSERT(new_lastop != ST_OP_NIL);
11932 
11933 		/* If un_lastop should copy new_lastop  */
11934 		if (((un->un_lastop == ST_OP_WRITE) ||
11935 		    (un->un_lastop == ST_OP_WEOF)) &&
11936 		    new_lastop != ST_OP_CTL) {
11937 			un->un_lastop = new_lastop;
11938 		}
11939 	}
11940 
11941 	/*
11942 	 * In the st driver we have a logical and physical file position.
11943 	 * Under BSD behavior, when you get a zero read, the logical position
11944 	 * is before the filemark but after the last record of the file.
11945 	 * The physical position is after the filemark. MTIOCGET should always
11946 	 * return the logical file position.
11947 	 *
11948 	 * The next read gives a silent skip to the next file.
11949 	 * Under SVR4, the logical file position remains before the filemark
11950 	 * until the file is closed or a space operation is performed.
11951 	 * Hence set err_resid and err_file before changing fileno if case
11952 	 * BSD Behaviour.
11953 	 */
11954 	un->un_err_resid = bp->b_resid;
11955 	COPY_POS(&un->un_err_pos, &un->un_pos);
11956 
11957 
11958 	/*
11959 	 * If we've seen a filemark via the last read operation
11960 	 * advance the file counter, but mark things such that
11961 	 * the next read operation gets a zero count. We have
11962 	 * to put this here to handle the case of sitting right
11963 	 * at the end of a tape file having seen the file mark,
11964 	 * but the tape is closed and then re-opened without
11965 	 * any further i/o. That is, the position information
11966 	 * must be updated before a close.
11967 	 */
11968 
11969 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
11970 		/*
11971 		 * If we're a 1/2" tape, and we get a filemark
11972 		 * right on block 0, *AND* we were not in the
11973 		 * first file on the tape, and we've hit logical EOM.
11974 		 * We'll mark the state so that later we do the
11975 		 * right thing (in st_close(), st_strategy() or
11976 		 * st_ioctl()).
11977 		 *
11978 		 */
11979 		if ((un->un_dp->options & ST_REEL) &&
11980 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
11981 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
11982 			un->un_pos.eof = ST_EOT_PENDING;
11983 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11984 			    "eot pending\n");
11985 			un->un_pos.fileno++;
11986 			un->un_pos.blkno = 0;
11987 		} else if (BSD_BEHAVIOR) {
11988 			/*
11989 			 * If the read of the filemark was a side effect
11990 			 * of reading some blocks (i.e., data was actually
11991 			 * read), then the EOF mark is pending and the
11992 			 * bump into the next file awaits the next read
11993 			 * operation (which will return a zero count), or
11994 			 * a close or a space operation, else the bump
11995 			 * into the next file occurs now.
11996 			 */
11997 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11998 			    "resid=%lx, bcount=%lx\n",
11999 			    bp->b_resid, bp->b_bcount);
12000 
12001 			if (bp->b_resid != bp->b_bcount) {
12002 				un->un_pos.eof = ST_EOF;
12003 			} else {
12004 				un->un_silent_skip = 1;
12005 				un->un_pos.eof = ST_NO_EOF;
12006 				un->un_pos.fileno++;
12007 				un->un_pos.lgclblkno++;
12008 				un->un_save_blkno = un->un_pos.blkno;
12009 				un->un_pos.blkno = 0;
12010 			}
12011 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12012 			    "eof of file %d, eof=%d\n",
12013 			    un->un_pos.fileno, un->un_pos.eof);
12014 		} else if (SVR4_BEHAVIOR) {
12015 			/*
12016 			 * If the read of the filemark was a side effect
12017 			 * of reading some blocks (i.e., data was actually
12018 			 * read), then the next read should return 0
12019 			 */
12020 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12021 			    "resid=%lx, bcount=%lx\n",
12022 			    bp->b_resid, bp->b_bcount);
12023 			if (bp->b_resid == bp->b_bcount) {
12024 				un->un_pos.eof = ST_EOF;
12025 			}
12026 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12027 			    "eof of file=%d, eof=%d\n",
12028 			    un->un_pos.fileno, un->un_pos.eof);
12029 		}
12030 	}
12031 }
12032 
12033 /*
12034  * set the correct un_errno, to take corner cases into consideration
12035  */
12036 static void
12037 st_set_pe_errno(struct scsi_tape *un)
12038 {
12039 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
12040 
12041 	ASSERT(mutex_owned(ST_MUTEX));
12042 
12043 	/* if errno is already set, don't reset it */
12044 	if (un->un_errno)
12045 		return;
12046 
12047 	/* here un_errno == 0 */
12048 	/*
12049 	 * if the last transfer before flushing all the
12050 	 * waiting I/O's, was 0 (resid = count), then we
12051 	 * want to give the user an error on all the rest,
12052 	 * so here.  If there was a transfer, we set the
12053 	 * resid and counts to 0, and let it drop through,
12054 	 * giving a zero return.  the next I/O will then
12055 	 * give an error.
12056 	 */
12057 	if (un->un_last_resid == un->un_last_count) {
12058 		switch (un->un_pos.eof) {
12059 		case ST_EOM:
12060 			un->un_errno = ENOMEM;
12061 			break;
12062 		case ST_EOT:
12063 		case ST_EOF:
12064 			un->un_errno = EIO;
12065 			break;
12066 		}
12067 	} else {
12068 		/*
12069 		 * we know they did not have a zero, so make
12070 		 * sure they get one
12071 		 */
12072 		un->un_last_resid = un->un_last_count = 0;
12073 	}
12074 }
12075 
12076 
12077 /*
12078  * send in a marker pkt to terminate flushing of commands by BBA (via
12079  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
12080  */
12081 static void
12082 st_hba_unflush(struct scsi_tape *un)
12083 {
12084 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
12085 
12086 	ASSERT(mutex_owned(ST_MUTEX));
12087 
12088 	if (!un->un_flush_on_errors)
12089 		return;
12090 
12091 #ifdef FLUSH_ON_ERRORS
12092 
12093 	if (!un->un_mkr_pkt) {
12094 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
12095 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
12096 
12097 		/* we slept, so it must be there */
12098 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
12099 	}
12100 
12101 	st_transport(un, un->un_mkr_pkt);
12102 #endif
12103 }
12104 
12105 static char *
12106 st_print_scsi_cmd(char cmd)
12107 {
12108 	char tmp[64];
12109 	char *cpnt;
12110 
12111 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
12112 	/* tmp goes out of scope on return and caller sees garbage */
12113 	if (cpnt == tmp) {
12114 		cpnt = "Unknown Command";
12115 	}
12116 	return (cpnt);
12117 }
12118 
12119 static void
12120 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
12121     char *title, char *cdb)
12122 {
12123 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
12124 	char buf[256];
12125 	struct scsi_tape *un;
12126 	int instance = ddi_get_instance(dip);
12127 
12128 	un = ddi_get_soft_state(st_state, instance);
12129 
12130 	ST_FUNC(dip, st_print_cdb);
12131 
12132 	/* force one line output so repeated commands are printed once */
12133 	if ((st_debug & 0x180) == 0x100) {
12134 		scsi_log(dip, label, level, "node %s cmd %s\n",
12135 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
12136 		return;
12137 	}
12138 
12139 	/* force one line output so repeated CDB's are printed once */
12140 	if ((st_debug & 0x180) == 0x80) {
12141 		st_clean_print(dip, label, level, NULL, cdb, len);
12142 	} else {
12143 		(void) sprintf(buf, "%s for cmd(%s)", title,
12144 		    st_print_scsi_cmd(*cdb));
12145 		st_clean_print(dip, label, level, buf, cdb, len);
12146 	}
12147 }
12148 
12149 static void
12150 st_clean_print(dev_info_t *dev, char *label, uint_t level,
12151     char *title, char *data, int len)
12152 {
12153 	int	i;
12154 	int 	c;
12155 	char	*format;
12156 	char	buf[256];
12157 	uchar_t	byte;
12158 
12159 	ST_FUNC(dev, st_clean_print);
12160 
12161 
12162 	if (title) {
12163 		(void) sprintf(buf, "%s:\n", title);
12164 		scsi_log(dev, label, level, "%s", buf);
12165 		level = CE_CONT;
12166 	}
12167 
12168 	for (i = 0; i < len; ) {
12169 		buf[0] = 0;
12170 		for (c = 0; c < 8 && i < len; c++, i++) {
12171 			byte = (uchar_t)data[i];
12172 			if (byte < 0x10)
12173 				format = "0x0%x ";
12174 			else
12175 				format = "0x%x ";
12176 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
12177 		}
12178 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
12179 
12180 		scsi_log(dev, label, level, "%s\n", buf);
12181 		level = CE_CONT;
12182 	}
12183 }
12184 
12185 /*
12186  * Conditionally enabled debugging
12187  */
12188 #ifdef	STDEBUG
12189 static void
12190 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
12191 {
12192 	char tmpbuf[64];
12193 
12194 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
12195 
12196 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12197 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
12198 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
12199 	    count, count,
12200 	    wait == ASYNC_CMD ? "a" : "");
12201 }
12202 #endif	/* STDEBUG */
12203 
12204 /*
12205  * Returns pointer to name of minor node name of device 'dev'.
12206  */
12207 static char *
12208 st_dev_name(dev_t dev)
12209 {
12210 	struct scsi_tape *un;
12211 	const char density[] = { 'l', 'm', 'h', 'c' };
12212 	static char name[32];
12213 	minor_t minor;
12214 	int instance;
12215 	int nprt = 0;
12216 
12217 	minor = getminor(dev);
12218 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
12219 	un = ddi_get_soft_state(st_state, instance);
12220 	if (un) {
12221 		ST_FUNC(ST_DEVINFO, st_dev_name);
12222 	}
12223 
12224 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
12225 
12226 	if (minor & MT_BSD) {
12227 		name[++nprt] = 'b';
12228 	}
12229 
12230 	if (minor & MT_NOREWIND) {
12231 		name[++nprt] = 'n';
12232 	}
12233 
12234 	/* NULL terminator */
12235 	name[++nprt] = 0;
12236 
12237 	return (name);
12238 }
12239 
12240 /*
12241  * Soft error reporting, so far unique to each drive
12242  *
12243  * Currently supported: exabyte and DAT soft error reporting
12244  */
12245 static int
12246 st_report_exabyte_soft_errors(dev_t dev, int flag)
12247 {
12248 	uchar_t *sensep;
12249 	int amt;
12250 	int rval = 0;
12251 	char cdb[CDB_GROUP0], *c = cdb;
12252 	struct uscsi_cmd *com;
12253 
12254 	GET_SOFT_STATE(dev);
12255 
12256 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
12257 
12258 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12259 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
12260 	    dev, flag);
12261 
12262 	ASSERT(mutex_owned(ST_MUTEX));
12263 
12264 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12265 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
12266 
12267 	*c++ = SCMD_REQUEST_SENSE;
12268 	*c++ = 0;
12269 	*c++ = 0;
12270 	*c++ = 0;
12271 	*c++ = TAPE_SENSE_LENGTH;
12272 	/*
12273 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
12274 	 */
12275 	*c   = (char)0x80;
12276 
12277 	com->uscsi_cdb = cdb;
12278 	com->uscsi_cdblen = CDB_GROUP0;
12279 	com->uscsi_bufaddr = (caddr_t)sensep;
12280 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
12281 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12282 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12283 
12284 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12285 	if (rval || com->uscsi_status) {
12286 		goto done;
12287 	}
12288 
12289 	/*
12290 	 * was there enough data?
12291 	 */
12292 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
12293 
12294 	if ((amt >= 19) && un->un_kbytes_xferred) {
12295 		uint_t count, error_rate;
12296 		uint_t rate;
12297 
12298 		if (sensep[21] & CLN) {
12299 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12300 			    "Periodic head cleaning required");
12301 		}
12302 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
12303 			goto done;
12304 		}
12305 		/*
12306 		 * check if soft error reporting needs to be done.
12307 		 */
12308 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
12309 		count &= 0xffffff;
12310 		error_rate = (count * 100)/un->un_kbytes_xferred;
12311 
12312 #ifdef	STDEBUG
12313 		if (st_soft_error_report_debug) {
12314 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12315 			    "Exabyte Soft Error Report:\n");
12316 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12317 			    "read/write error counter: %d\n", count);
12318 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12319 			    "number of bytes transferred: %dK\n",
12320 			    un->un_kbytes_xferred);
12321 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12322 			    "error_rate: %d%%\n", error_rate);
12323 
12324 			if (amt >= 22) {
12325 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12326 				    "unit sense: 0x%b 0x%b 0x%b\n",
12327 				    sensep[19], SENSE_19_BITS,
12328 				    sensep[20], SENSE_20_BITS,
12329 				    sensep[21], SENSE_21_BITS);
12330 			}
12331 			if (amt >= 27) {
12332 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12333 				    "tracking retry counter: %d\n",
12334 				    sensep[26]);
12335 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12336 				    "read/write retry counter: %d\n",
12337 				    sensep[27]);
12338 			}
12339 		}
12340 #endif
12341 
12342 		if (flag & FWRITE) {
12343 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
12344 		} else {
12345 			rate = EXABYTE_READ_ERROR_THRESHOLD;
12346 		}
12347 		if (error_rate >= rate) {
12348 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12349 			    "Soft error rate (%d%%) during %s was too high",
12350 			    error_rate,
12351 			    ((flag & FWRITE) ? wrg_str : rdg_str));
12352 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12353 			    "Please, replace tape cartridge\n");
12354 		}
12355 	}
12356 
12357 done:
12358 	kmem_free(com, sizeof (*com));
12359 	kmem_free(sensep, TAPE_SENSE_LENGTH);
12360 
12361 	if (rval != 0) {
12362 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12363 		    "exabyte soft error reporting failed\n");
12364 	}
12365 	return (rval);
12366 }
12367 
12368 /*
12369  * this is very specific to Archive 4mm dat
12370  */
12371 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
12372 
12373 static int
12374 st_report_dat_soft_errors(dev_t dev, int flag)
12375 {
12376 	uchar_t *sensep;
12377 	int amt, i;
12378 	int rval = 0;
12379 	char cdb[CDB_GROUP1], *c = cdb;
12380 	struct uscsi_cmd *com;
12381 	struct scsi_arq_status status;
12382 
12383 	GET_SOFT_STATE(dev);
12384 
12385 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
12386 
12387 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12388 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12389 
12390 	ASSERT(mutex_owned(ST_MUTEX));
12391 
12392 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12393 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12394 
12395 	*c++ = SCMD_LOG_SENSE_G1;
12396 	*c++ = 0;
12397 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
12398 	*c++ = 0;
12399 	*c++ = 0;
12400 	*c++ = 0;
12401 	*c++ = 2;
12402 	*c++ = 0;
12403 	*c++ = (char)LOG_SENSE_LENGTH;
12404 	*c   = 0;
12405 	com->uscsi_cdb    = cdb;
12406 	com->uscsi_cdblen  = CDB_GROUP1;
12407 	com->uscsi_bufaddr = (caddr_t)sensep;
12408 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
12409 	com->uscsi_rqlen = sizeof (status);
12410 	com->uscsi_rqbuf = (caddr_t)&status;
12411 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
12412 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12413 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12414 	if (rval) {
12415 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12416 		    "DAT soft error reporting failed\n");
12417 	}
12418 	if (rval || com->uscsi_status) {
12419 		goto done;
12420 	}
12421 
12422 	/*
12423 	 * was there enough data?
12424 	 */
12425 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
12426 
12427 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
12428 		int total, retries, param_code;
12429 
12430 		total = -1;
12431 		retries = -1;
12432 		amt = sensep[3] + 4;
12433 
12434 
12435 #ifdef STDEBUG
12436 		if (st_soft_error_report_debug) {
12437 			(void) printf("logsense:");
12438 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
12439 				if (i % 16 == 0) {
12440 					(void) printf("\t\n");
12441 				}
12442 				(void) printf(" %x", sensep[i]);
12443 			}
12444 			(void) printf("\n");
12445 		}
12446 #endif
12447 
12448 		/*
12449 		 * parse the param_codes
12450 		 */
12451 		if (sensep[0] == 2 || sensep[0] == 3) {
12452 			for (i = 4; i < amt; i++) {
12453 				param_code = (sensep[i++] << 8);
12454 				param_code += sensep[i++];
12455 				i++; /* skip control byte */
12456 				if (param_code == 5) {
12457 					if (sensep[i++] == 4) {
12458 						total = (sensep[i++] << 24);
12459 						total += (sensep[i++] << 16);
12460 						total += (sensep[i++] << 8);
12461 						total += sensep[i];
12462 					}
12463 				} else if (param_code == 0x8007) {
12464 					if (sensep[i++] == 2) {
12465 						retries = sensep[i++] << 8;
12466 						retries += sensep[i];
12467 					}
12468 				} else {
12469 					i += sensep[i];
12470 				}
12471 			}
12472 		}
12473 
12474 		/*
12475 		 * if the log sense returned valid numbers then determine
12476 		 * the read and write error thresholds based on the amount of
12477 		 * data transferred
12478 		 */
12479 
12480 		if (total > 0 && retries > 0) {
12481 			short normal_retries = 0;
12482 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12483 			    "total xferred (%s) =%x, retries=%x\n",
12484 			    ((flag & FWRITE) ? wrg_str : rdg_str),
12485 			    total, retries);
12486 
12487 			if (flag & FWRITE) {
12488 				if (total <=
12489 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
12490 					normal_retries =
12491 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
12492 				} else {
12493 					normal_retries =
12494 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
12495 				}
12496 			} else {
12497 				if (total <=
12498 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
12499 					normal_retries =
12500 					    DAT_SMALL_READ_ERROR_THRESHOLD;
12501 				} else {
12502 					normal_retries =
12503 					    DAT_LARGE_READ_ERROR_THRESHOLD;
12504 				}
12505 			}
12506 
12507 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12508 			"normal retries=%d\n", normal_retries);
12509 
12510 			if (retries >= normal_retries) {
12511 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12512 				    "Soft error rate (retries = %d) during "
12513 				    "%s was too high",  retries,
12514 				    ((flag & FWRITE) ? wrg_str : rdg_str));
12515 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12516 				    "Periodic head cleaning required "
12517 				    "and/or replace tape cartridge\n");
12518 			}
12519 
12520 		} else if (total == -1 || retries == -1) {
12521 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12522 			    "log sense parameter code does not make sense\n");
12523 		}
12524 	}
12525 
12526 	/*
12527 	 * reset all values
12528 	 */
12529 	c = cdb;
12530 	*c++ = SCMD_LOG_SELECT_G1;
12531 	*c++ = 2;	/* this resets all values */
12532 	*c++ = (char)0xc0;
12533 	*c++ = 0;
12534 	*c++ = 0;
12535 	*c++ = 0;
12536 	*c++ = 0;
12537 	*c++ = 0;
12538 	*c++ = 0;
12539 	*c   = 0;
12540 	com->uscsi_bufaddr = NULL;
12541 	com->uscsi_buflen  = 0;
12542 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
12543 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12544 	if (rval) {
12545 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12546 		    "DAT soft error reset failed\n");
12547 	}
12548 done:
12549 	kmem_free(com, sizeof (*com));
12550 	kmem_free(sensep, LOG_SENSE_LENGTH);
12551 	return (rval);
12552 }
12553 
12554 static int
12555 st_report_soft_errors(dev_t dev, int flag)
12556 {
12557 	GET_SOFT_STATE(dev);
12558 
12559 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
12560 
12561 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12562 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12563 
12564 	ASSERT(mutex_owned(ST_MUTEX));
12565 
12566 	switch (un->un_dp->type) {
12567 	case ST_TYPE_EXB8500:
12568 	case ST_TYPE_EXABYTE:
12569 		return (st_report_exabyte_soft_errors(dev, flag));
12570 		/*NOTREACHED*/
12571 	case ST_TYPE_PYTHON:
12572 		return (st_report_dat_soft_errors(dev, flag));
12573 		/*NOTREACHED*/
12574 	default:
12575 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
12576 		return (-1);
12577 	}
12578 }
12579 
12580 /*
12581  * persistent error routines
12582  */
12583 
12584 /*
12585  * enable persistent errors, and set the throttle appropriately, checking
12586  * for flush-on-errors capability
12587  */
12588 static void
12589 st_turn_pe_on(struct scsi_tape *un)
12590 {
12591 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
12592 
12593 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
12594 	ASSERT(mutex_owned(ST_MUTEX));
12595 
12596 	un->un_persistence = 1;
12597 
12598 	/*
12599 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
12600 	 * enabled.  This will simplify the error handling for request senses
12601 	 */
12602 
12603 	if (un->un_arq_enabled && un->un_untagged_qing) {
12604 		uchar_t f_o_e;
12605 
12606 		mutex_exit(ST_MUTEX);
12607 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
12608 		    1 : 0;
12609 		mutex_enter(ST_MUTEX);
12610 
12611 		un->un_flush_on_errors = f_o_e;
12612 	} else {
12613 		un->un_flush_on_errors = 0;
12614 	}
12615 
12616 	if (un->un_flush_on_errors)
12617 		un->un_max_throttle = (uchar_t)st_max_throttle;
12618 	else
12619 		un->un_max_throttle = 1;
12620 
12621 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
12622 		un->un_max_throttle = 1;
12623 
12624 	/* this will send a marker pkt */
12625 	st_clear_pe(un);
12626 }
12627 
12628 /*
12629  * This turns persistent errors permanently off
12630  */
12631 static void
12632 st_turn_pe_off(struct scsi_tape *un)
12633 {
12634 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
12635 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
12636 	ASSERT(mutex_owned(ST_MUTEX));
12637 
12638 	/* turn it off for good */
12639 	un->un_persistence = 0;
12640 
12641 	/* this will send a marker pkt */
12642 	st_clear_pe(un);
12643 
12644 	/* turn off flush on error capability, if enabled */
12645 	if (un->un_flush_on_errors) {
12646 		mutex_exit(ST_MUTEX);
12647 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
12648 		mutex_enter(ST_MUTEX);
12649 	}
12650 
12651 
12652 	un->un_flush_on_errors = 0;
12653 }
12654 
12655 /*
12656  * This clear persistent errors, allowing more commands through, and also
12657  * sending a marker packet.
12658  */
12659 static void
12660 st_clear_pe(struct scsi_tape *un)
12661 {
12662 	ST_FUNC(ST_DEVINFO, st_clear_pe);
12663 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
12664 	ASSERT(mutex_owned(ST_MUTEX));
12665 
12666 	un->un_persist_errors = 0;
12667 	un->un_throttle = un->un_last_throttle = 1;
12668 	un->un_errno = 0;
12669 	st_hba_unflush(un);
12670 }
12671 
12672 /*
12673  * This will flag persistent errors, shutting everything down, if the
12674  * application had enabled persistent errors via MTIOCPERSISTENT
12675  */
12676 static void
12677 st_set_pe_flag(struct scsi_tape *un)
12678 {
12679 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
12680 	ASSERT(mutex_owned(ST_MUTEX));
12681 
12682 	if (un->un_persistence) {
12683 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
12684 		un->un_persist_errors = 1;
12685 		un->un_throttle = un->un_last_throttle = 0;
12686 		cv_broadcast(&un->un_sbuf_cv);
12687 	}
12688 }
12689 
12690 static int
12691 st_do_reserve(struct scsi_tape *un)
12692 {
12693 	int rval;
12694 	int was_lost = un->un_rsvd_status & ST_LOST_RESERVE;
12695 
12696 	ST_FUNC(ST_DEVINFO, st_do_reserve);
12697 
12698 	/*
12699 	 * Issue a Throw-Away reserve command to clear the
12700 	 * check condition.
12701 	 * If the current behaviour of reserve/release is to
12702 	 * hold reservation across opens , and if a Bus reset
12703 	 * has been issued between opens then this command
12704 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
12705 	 * In this case return an EACCES so that user knows that
12706 	 * reservation has been lost in between opens.
12707 	 * If this error is not returned and we continue with
12708 	 * successful open , then user may think position of the
12709 	 * tape is still the same but inreality we would rewind the
12710 	 * tape and continue from BOT.
12711 	 */
12712 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12713 	if (rval) {
12714 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
12715 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
12716 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
12717 			un->un_errno = EACCES;
12718 			return (EACCES);
12719 		}
12720 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12721 	}
12722 	if (rval == 0) {
12723 		un->un_rsvd_status |= ST_INIT_RESERVE;
12724 	}
12725 	if (was_lost) {
12726 		un->un_running.pmode = invalid;
12727 	}
12728 
12729 	return (rval);
12730 }
12731 
12732 static int
12733 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb)
12734 {
12735 	int rval;
12736 	cmd_attribute const *attrib;
12737 
12738 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
12739 
12740 	/*
12741 	 * If already reserved no need to do it again.
12742 	 * Also if Reserve and Release are disabled Just return.
12743 	 */
12744 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12745 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12746 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12747 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12748 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
12749 		    st_print_scsi_cmd((uchar_t)cdb[0]));
12750 		return (0);
12751 	}
12752 
12753 	/* See if command is on the list */
12754 	attrib = st_lookup_cmd_attribute(cdb[0]);
12755 
12756 	if (attrib == NULL) {
12757 		rval = 1; /* Not found, when in doubt reserve */
12758 	} else if ((attrib->requires_reserve) != 0) {
12759 		rval = 1;
12760 	} else if ((attrib->reserve_byte) != 0) {
12761 		/*
12762 		 * cmd is on list.
12763 		 * if byte is zero always allowed.
12764 		 */
12765 		rval = 1;
12766 	} else if (((cdb[attrib->reserve_byte]) &
12767 	    (attrib->reserve_mask)) != 0) {
12768 		rval = 1;
12769 	} else {
12770 		rval = 0;
12771 	}
12772 
12773 	if (rval) {
12774 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12775 		    "Command %s requires reservation",
12776 		    st_print_scsi_cmd(cdb[0]));
12777 
12778 		rval = st_do_reserve(un);
12779 	}
12780 
12781 	return (rval);
12782 }
12783 
12784 static int
12785 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
12786 {
12787 	int rval;
12788 	cmd_attribute const *attrib;
12789 
12790 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
12791 
12792 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12793 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12794 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12795 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12796 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
12797 		    st_print_scsi_cmd(cmd));
12798 		return (0);
12799 	}
12800 
12801 	/* search for this command on the list */
12802 	attrib = st_lookup_cmd_attribute(cmd);
12803 
12804 	if (attrib == NULL) {
12805 		rval = 1; /* Not found, when in doubt reserve */
12806 	} else if ((attrib->requires_reserve) != 0) {
12807 		rval = 1;
12808 	} else if ((attrib->reserve_byte) != 0) {
12809 		/*
12810 		 * cmd is on list.
12811 		 * if byte is zero always allowed.
12812 		 */
12813 		rval = 1;
12814 	} else if (((attrib->reserve_mask) & cnt) != 0) {
12815 		rval = 1;
12816 	} else {
12817 		rval = 0;
12818 	}
12819 
12820 	if (rval) {
12821 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12822 		    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
12823 
12824 		rval = st_do_reserve(un);
12825 	}
12826 
12827 	return (rval);
12828 }
12829 
12830 static int
12831 st_reserve_release(struct scsi_tape *un, int cmd, ubufunc_t ubf)
12832 {
12833 	struct uscsi_cmd	uscsi_cmd;
12834 	int			rval;
12835 	char			cdb[CDB_GROUP0];
12836 	struct scsi_arq_status	stat;
12837 
12838 
12839 
12840 	ST_FUNC(ST_DEVINFO, st_reserve_release);
12841 
12842 	ASSERT(mutex_owned(ST_MUTEX));
12843 
12844 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12845 	    "st_reserve_release: %s \n",
12846 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
12847 
12848 	bzero(&cdb, CDB_GROUP0);
12849 	if (cmd == ST_RELEASE) {
12850 		cdb[0] = SCMD_RELEASE;
12851 	} else {
12852 		cdb[0] = SCMD_RESERVE;
12853 	}
12854 	bzero(&uscsi_cmd, sizeof (struct uscsi_cmd));
12855 	uscsi_cmd.uscsi_flags = USCSI_WRITE | USCSI_RQENABLE;
12856 	uscsi_cmd.uscsi_cdb = cdb;
12857 	uscsi_cmd.uscsi_cdblen = CDB_GROUP0;
12858 	uscsi_cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
12859 	uscsi_cmd.uscsi_rqbuf = (caddr_t)&stat;
12860 	uscsi_cmd.uscsi_rqlen = sizeof (stat);
12861 
12862 	rval = ubf(un, &uscsi_cmd, FKIOCTL);
12863 
12864 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12865 	    "st_reserve_release: rval(1)=%d\n", rval);
12866 
12867 	if (rval) {
12868 		if (uscsi_cmd.uscsi_status == STATUS_RESERVATION_CONFLICT) {
12869 			rval = EACCES;
12870 		}
12871 		/*
12872 		 * dynamically turn off reserve/release support
12873 		 * in case of drives which do not support
12874 		 * reserve/release command(ATAPI drives).
12875 		 */
12876 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
12877 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
12878 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
12879 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12880 				    "Tape unit does not support "
12881 				    "reserve/release \n");
12882 			}
12883 			rval = 0;
12884 		}
12885 	}
12886 	return (rval);
12887 }
12888 
12889 static int
12890 st_take_ownership(struct scsi_tape *un, ubufunc_t ubf)
12891 {
12892 	int rval;
12893 
12894 	ST_FUNC(ST_DEVINFO, st_take_ownership);
12895 
12896 	ASSERT(mutex_owned(ST_MUTEX));
12897 
12898 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12899 	    "st_take_ownership: Entering ...\n");
12900 
12901 
12902 	rval = st_reserve_release(un, ST_RESERVE, ubf);
12903 	/*
12904 	 * XXX -> Should reset be done only if we get EACCES.
12905 	 * .
12906 	 */
12907 	if (rval) {
12908 		if (st_reset(un, RESET_LUN) == 0) {
12909 			return (EIO);
12910 		}
12911 		un->un_rsvd_status &=
12912 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
12913 
12914 		mutex_exit(ST_MUTEX);
12915 		delay(drv_usectohz(ST_RESERVATION_DELAY));
12916 		mutex_enter(ST_MUTEX);
12917 		/*
12918 		 * remove the check condition.
12919 		 */
12920 		(void) st_reserve_release(un, ST_RESERVE, ubf);
12921 		rval = st_reserve_release(un, ST_RESERVE, ubf);
12922 		if (rval != 0) {
12923 			if ((st_reserve_release(un, ST_RESERVE, ubf))
12924 			    != 0) {
12925 				rval = (un->un_rsvd_status &
12926 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
12927 				return (rval);
12928 			}
12929 		}
12930 		/*
12931 		 * Set tape state to ST_STATE_OFFLINE , in case if
12932 		 * the user wants to continue and start using
12933 		 * the tape.
12934 		 */
12935 		un->un_state = ST_STATE_OFFLINE;
12936 		un->un_rsvd_status |= ST_INIT_RESERVE;
12937 	}
12938 	return (rval);
12939 }
12940 
12941 static int
12942 st_create_errstats(struct scsi_tape *un, int instance)
12943 {
12944 	char	kstatname[KSTAT_STRLEN];
12945 
12946 	ST_FUNC(ST_DEVINFO, st_create_errstats);
12947 
12948 	/*
12949 	 * Create device error kstats
12950 	 */
12951 
12952 	if (un->un_errstats == (kstat_t *)0) {
12953 		(void) sprintf(kstatname, "st%d,err", instance);
12954 		un->un_errstats = kstat_create("sterr", instance, kstatname,
12955 		    "device_error", KSTAT_TYPE_NAMED,
12956 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
12957 		    KSTAT_FLAG_PERSISTENT);
12958 
12959 		if (un->un_errstats) {
12960 			struct st_errstats	*stp;
12961 
12962 			stp = (struct st_errstats *)un->un_errstats->ks_data;
12963 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
12964 			    KSTAT_DATA_ULONG);
12965 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
12966 			    KSTAT_DATA_ULONG);
12967 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
12968 			    KSTAT_DATA_ULONG);
12969 			kstat_named_init(&stp->st_vid, "Vendor",
12970 			    KSTAT_DATA_CHAR);
12971 			kstat_named_init(&stp->st_pid, "Product",
12972 			    KSTAT_DATA_CHAR);
12973 			kstat_named_init(&stp->st_revision, "Revision",
12974 			    KSTAT_DATA_CHAR);
12975 			kstat_named_init(&stp->st_serial, "Serial No",
12976 			    KSTAT_DATA_CHAR);
12977 			un->un_errstats->ks_private = un;
12978 			un->un_errstats->ks_update = nulldev;
12979 			kstat_install(un->un_errstats);
12980 			/*
12981 			 * Fill in the static data
12982 			 */
12983 			(void) strncpy(&stp->st_vid.value.c[0],
12984 			    ST_INQUIRY->inq_vid, 8);
12985 			/*
12986 			 * XXX:  Emulex MT-02 (and emulators) predates
12987 			 *	 SCSI-1 and has no vid & pid inquiry data.
12988 			 */
12989 			if (ST_INQUIRY->inq_len != 0) {
12990 				(void) strncpy(&stp->st_pid.value.c[0],
12991 				    ST_INQUIRY->inq_pid, 16);
12992 				(void) strncpy(&stp->st_revision.value.c[0],
12993 				    ST_INQUIRY->inq_revision, 4);
12994 				(void) strncpy(&stp->st_serial.value.c[0],
12995 				    ST_INQUIRY->inq_serial, 12);
12996 			}
12997 		}
12998 	}
12999 	return (0);
13000 }
13001 
13002 static int
13003 st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos)
13004 {
13005 	int rval;
13006 	bufunc_t bf = (ubf == st_uscsi_rcmd) ? st_rcmd : st_cmd;
13007 
13008 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
13009 
13010 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
13011 	ASSERT(mutex_owned(ST_MUTEX));
13012 
13013 	/* Can't restore an invalid position */
13014 	if (pos->pmode == invalid) {
13015 		return (4);
13016 	}
13017 
13018 	/*
13019 	 * Assumtions:
13020 	 *	If a position was read and is in logical position mode.
13021 	 *	If a drive supports read position it supports locate.
13022 	 *	If the read position type is not NO_POS. even though
13023 	 *	   a read position make not have been attemped yet.
13024 	 *
13025 	 *	The drive can locate to the position.
13026 	 */
13027 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
13028 		/*
13029 		 * If position mode is logical or legacy mode try
13030 		 * to locate there as it is faster.
13031 		 * If it fails try the old way.
13032 		 */
13033 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13034 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
13035 		    pos->lgclblkno);
13036 
13037 		if (st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
13038 		    pos->lgclblkno, pos->partition) == 0) {
13039 			/* Assume we are there copy rest of position back */
13040 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
13041 				COPY_POS(&un->un_pos, pos);
13042 			}
13043 			return (0);
13044 		}
13045 
13046 		/*
13047 		 * If logical block locate failed to restore a logical
13048 		 * position, can't recover.
13049 		 */
13050 		if (pos->pmode == logical) {
13051 			return (-1);
13052 		}
13053 	}
13054 
13055 
13056 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13057 	    "Restoring tape position at fileno=%x, blkno=%x....",
13058 	    pos->fileno, pos->blkno);
13059 
13060 	/*
13061 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
13062 	 * so as not to rewind tape on RESETS: Gee, Has life ever
13063 	 * been simple in tape land ?
13064 	 */
13065 	rval = bf(un, SCMD_REWIND, 0, SYNC_CMD);
13066 	if (rval) {
13067 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
13068 		    "Failed to restore the last file and block position: In"
13069 		    " this state, Tape will be loaded at BOT during next open");
13070 		un->un_pos.pmode = invalid;
13071 		return (rval);
13072 	}
13073 
13074 	/* If the position was as the result of back space file */
13075 	if (pos->blkno > (INF / 2)) {
13076 		/* Go one extra file forward */
13077 		pos->fileno++;
13078 		/* Figure how many blocks to back into the previous file */
13079 		pos->blkno = -(INF - pos->blkno);
13080 	}
13081 
13082 	/* Go to requested fileno */
13083 	if (pos->fileno) {
13084 		rval = st_cmd(un, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
13085 		if (rval) {
13086 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13087 			    "Failed to restore the last file position: In this "
13088 			    " state, Tape will be loaded at BOT during next"
13089 			    " open %d", __LINE__);
13090 			un->un_pos.pmode = invalid;
13091 			pos->pmode = invalid;
13092 			return (rval);
13093 		}
13094 	}
13095 
13096 	/*
13097 	 * If backing into a file we already did an extra file forward.
13098 	 * Now we have to back over the filemark to get to the end of
13099 	 * the previous file. The blkno has been ajusted to a negative
13100 	 * value so we will get to the expected location.
13101 	 */
13102 	if (pos->blkno) {
13103 		rval = bf(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
13104 		if (rval) {
13105 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13106 			    "Failed to restore the last file position: In this "
13107 			    " state, Tape will be loaded at BOT during next"
13108 			    " open %d", __LINE__);
13109 			un->un_pos.pmode = invalid;
13110 			pos->pmode = invalid;
13111 			return (rval);
13112 		}
13113 	}
13114 
13115 	/*
13116 	 * The position mode, block and fileno should be correct,
13117 	 * This updates eof and logical position information.
13118 	 */
13119 	un->un_pos.eof = pos->eof;
13120 	un->un_pos.lgclblkno = pos->lgclblkno;
13121 
13122 	return (0);
13123 }
13124 
13125 /*
13126  * check sense key, ASC, ASCQ in order to determine if the tape needs
13127  * to be ejected
13128  */
13129 
13130 static int
13131 st_check_asc_ascq(struct scsi_tape *un)
13132 {
13133 	struct scsi_extended_sense *sensep = ST_RQSENSE;
13134 	struct tape_failure_code   *code;
13135 
13136 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
13137 
13138 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
13139 		if ((code->key  == sensep->es_key) &&
13140 		    (code->add_code  == sensep->es_add_code) &&
13141 		    (code->qual_code == sensep->es_qual_code))
13142 			return (1);
13143 	}
13144 	return (0);
13145 }
13146 
13147 /*
13148  * st_logpage_supported() sends a Log Sense command with
13149  * page code = 0 = Supported Log Pages Page to the device,
13150  * to see whether the page 'page' is supported.
13151  * Return values are:
13152  * -1 if the Log Sense command fails
13153  * 0 if page is not supported
13154  * 1 if page is supported
13155  */
13156 
13157 static int
13158 st_logpage_supported(struct scsi_tape *un, uchar_t page)
13159 {
13160 	uchar_t *sp, *sensep;
13161 	unsigned length;
13162 	struct uscsi_cmd *com;
13163 	struct scsi_arq_status status;
13164 	int rval;
13165 	char cdb[CDB_GROUP1] = {
13166 		SCMD_LOG_SENSE_G1,
13167 		0,
13168 		SUPPORTED_LOG_PAGES_PAGE,
13169 		0,
13170 		0,
13171 		0,
13172 		0,
13173 		0,
13174 		(char)LOG_SENSE_LENGTH,
13175 		0
13176 	};
13177 
13178 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
13179 
13180 	ASSERT(mutex_owned(ST_MUTEX));
13181 
13182 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13183 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
13184 
13185 	com->uscsi_cdb = cdb;
13186 	com->uscsi_cdblen = CDB_GROUP1;
13187 	com->uscsi_bufaddr = (caddr_t)sensep;
13188 	com->uscsi_buflen = LOG_SENSE_LENGTH;
13189 	com->uscsi_rqlen = sizeof (status);
13190 	com->uscsi_rqbuf = (caddr_t)&status;
13191 	com->uscsi_flags =
13192 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13193 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13194 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13195 	if (rval || com->uscsi_status) {
13196 		/* uscsi-command failed */
13197 		rval = -1;
13198 	} else {
13199 
13200 		sp = sensep + 3;
13201 
13202 		for (length = *sp++; length > 0; length--, sp++) {
13203 
13204 			if (*sp == page) {
13205 				rval = 1;
13206 				break;
13207 			}
13208 		}
13209 	}
13210 	kmem_free(com, sizeof (struct uscsi_cmd));
13211 	kmem_free(sensep, LOG_SENSE_LENGTH);
13212 	return (rval);
13213 }
13214 
13215 
13216 /*
13217  * st_check_clean_bit() gets the status of the tape's cleaning bit.
13218  *
13219  * If the device does support the TapeAlert log page, then the cleaning bit
13220  * information will be read from this page. Otherwise we will see if one of
13221  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
13222  * the device, which means, that we can get the cleaning bit information via
13223  * a RequestSense command.
13224  * If both methods of getting cleaning bit information are not supported
13225  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
13226  * returns with
13227  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
13228  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
13229  * If the call to st_uscsi_cmd() to do the Log Sense or the Request Sense
13230  * command fails, or if the amount of Request Sense data is not enough, then
13231  *  st_check_clean_bit() returns with -1.
13232  */
13233 
13234 static int
13235 st_check_clean_bit(struct scsi_tape *un)
13236 {
13237 	int rval = 0;
13238 
13239 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
13240 
13241 	ASSERT(mutex_owned(ST_MUTEX));
13242 
13243 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
13244 		return (rval);
13245 	}
13246 
13247 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13248 
13249 		rval = st_logpage_supported(un, TAPE_SEQUENTIAL_PAGE);
13250 		if (rval == -1) {
13251 			return (0);
13252 		}
13253 		if (rval == 1) {
13254 
13255 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
13256 		}
13257 
13258 		rval = st_logpage_supported(un, TAPE_ALERT_PAGE);
13259 		if (rval == -1) {
13260 			return (0);
13261 		}
13262 		if (rval == 1) {
13263 
13264 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
13265 		}
13266 
13267 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13268 
13269 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
13270 		}
13271 	}
13272 
13273 	rval = 0;
13274 
13275 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
13276 
13277 		rval = st_check_sequential_clean_bit(un);
13278 		if (rval == -1) {
13279 			return (0);
13280 		}
13281 	}
13282 
13283 	if ((rval == 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
13284 
13285 		rval = st_check_alert_flags(un);
13286 		if (rval == -1) {
13287 			return (0);
13288 		}
13289 	}
13290 
13291 	if ((rval == 0) && (un->un_dp->options & ST_CLN_MASK)) {
13292 
13293 		rval = st_check_sense_clean_bit(un);
13294 		if (rval == -1) {
13295 			return (0);
13296 		}
13297 	}
13298 
13299 	/*
13300 	 * If found a supported means to check need to clean.
13301 	 */
13302 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
13303 
13304 		/*
13305 		 * head needs to be cleaned.
13306 		 */
13307 		if (rval & MTF_TAPE_HEAD_DIRTY) {
13308 
13309 			/*
13310 			 * Print log message only first time
13311 			 * found needing cleaned.
13312 			 */
13313 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
13314 
13315 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
13316 				    "Periodic head cleaning required");
13317 
13318 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
13319 			}
13320 
13321 		} else {
13322 
13323 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
13324 		}
13325 	}
13326 
13327 	return (rval);
13328 }
13329 
13330 
13331 static int
13332 st_check_sequential_clean_bit(struct scsi_tape *un)
13333 {
13334 	int rval;
13335 	int ix;
13336 	ushort_t parameter;
13337 	struct uscsi_cmd *cmd;
13338 	struct log_sequential_page *sp;
13339 	struct log_sequential_page_parameter *prm;
13340 	struct scsi_arq_status status;
13341 	char cdb[CDB_GROUP1] = {
13342 		SCMD_LOG_SENSE_G1,
13343 		0,
13344 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
13345 		0,
13346 		0,
13347 		0,
13348 		0,
13349 		(char)(sizeof (struct log_sequential_page) >> 8),
13350 		(char)(sizeof (struct log_sequential_page)),
13351 		0
13352 	};
13353 
13354 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
13355 
13356 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13357 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
13358 
13359 	cmd->uscsi_flags   =
13360 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13361 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13362 	cmd->uscsi_cdb	   = cdb;
13363 	cmd->uscsi_cdblen  = CDB_GROUP1;
13364 	cmd->uscsi_bufaddr = (caddr_t)sp;
13365 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
13366 	cmd->uscsi_rqlen   = sizeof (status);
13367 	cmd->uscsi_rqbuf   = (caddr_t)&status;
13368 
13369 	rval = st_uscsi_cmd(un, cmd, FKIOCTL);
13370 
13371 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
13372 
13373 		rval = -1;
13374 
13375 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
13376 
13377 		rval = -1;
13378 	}
13379 
13380 	prm = &sp->param[0];
13381 
13382 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
13383 
13384 		if (prm->log_param.length == 0) {
13385 			break;
13386 		}
13387 
13388 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
13389 		    (prm->log_param.pc_lo & 0xff));
13390 
13391 		if (parameter == SEQUENTIAL_NEED_CLN) {
13392 
13393 			rval = MTF_TAPE_CLN_SUPPORTED;
13394 			if (prm->param_value[prm->log_param.length - 1]) {
13395 
13396 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13397 				    "sequential log says head dirty\n");
13398 				rval |= MTF_TAPE_HEAD_DIRTY;
13399 			}
13400 		}
13401 		prm = (struct log_sequential_page_parameter *)
13402 		    &prm->param_value[prm->log_param.length];
13403 	}
13404 
13405 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13406 	kmem_free(sp,  sizeof (struct log_sequential_page));
13407 
13408 	return (rval);
13409 }
13410 
13411 
13412 static int
13413 st_check_alert_flags(struct scsi_tape *un)
13414 {
13415 	struct st_tape_alert *ta;
13416 	struct uscsi_cmd *com;
13417 	struct scsi_arq_status status;
13418 	unsigned ix, length;
13419 	int rval;
13420 	tape_alert_flags flag;
13421 	char cdb[CDB_GROUP1] = {
13422 		SCMD_LOG_SENSE_G1,
13423 		0,
13424 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
13425 		0,
13426 		0,
13427 		0,
13428 		0,
13429 		(char)(sizeof (struct st_tape_alert) >> 8),
13430 		(char)(sizeof (struct st_tape_alert)),
13431 		0
13432 	};
13433 
13434 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
13435 
13436 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13437 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
13438 
13439 	com->uscsi_cdb = cdb;
13440 	com->uscsi_cdblen = CDB_GROUP1;
13441 	com->uscsi_bufaddr = (caddr_t)ta;
13442 	com->uscsi_buflen = sizeof (struct st_tape_alert);
13443 	com->uscsi_rqlen = sizeof (status);
13444 	com->uscsi_rqbuf = (caddr_t)&status;
13445 	com->uscsi_flags =
13446 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13447 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13448 
13449 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13450 
13451 	if (rval || com->uscsi_status || com->uscsi_resid) {
13452 
13453 		rval = -1; /* uscsi-command failed */
13454 
13455 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
13456 
13457 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13458 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
13459 		rval = -1;
13460 	}
13461 
13462 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
13463 
13464 
13465 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
13466 
13467 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13468 		    "TapeAlert length %d\n", length);
13469 	}
13470 
13471 
13472 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
13473 
13474 		/*
13475 		 * if rval is bad before the first pass don't bother
13476 		 */
13477 		if (ix == 0 && rval != 0) {
13478 
13479 			break;
13480 		}
13481 
13482 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
13483 		    ta->param[ix].log_param.pc_lo);
13484 
13485 		if ((ta->param[ix].param_value & 1) == 0) {
13486 			continue;
13487 		}
13488 		/*
13489 		 * check to see if current parameter is of interest.
13490 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
13491 		 */
13492 		if ((flag == TAF_CLEAN_NOW) ||
13493 		    (flag == TAF_CLEAN_PERIODIC) ||
13494 		    ((flag == CLEAN_FOR_ERRORS) &&
13495 		    (un->un_dp->type == ST_TYPE_STK9840))) {
13496 
13497 			rval = MTF_TAPE_CLN_SUPPORTED;
13498 
13499 
13500 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13501 			    "alert_page drive needs clean %d\n", flag);
13502 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
13503 			rval |= MTF_TAPE_HEAD_DIRTY;
13504 
13505 		} else if (flag == TAF_CLEANING_MEDIA) {
13506 
13507 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13508 			    "alert_page drive was cleaned\n");
13509 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
13510 		}
13511 
13512 	}
13513 
13514 	/*
13515 	 * Report it as dirty till we see it cleaned
13516 	 */
13517 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
13518 
13519 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13520 		    "alert_page still dirty\n");
13521 		rval |= MTF_TAPE_HEAD_DIRTY;
13522 	}
13523 
13524 	kmem_free(com, sizeof (struct uscsi_cmd));
13525 	kmem_free(ta,  sizeof (struct st_tape_alert));
13526 
13527 	return (rval);
13528 }
13529 
13530 
13531 static int
13532 st_check_sense_clean_bit(struct scsi_tape *un)
13533 {
13534 	uchar_t *sensep;
13535 	char cdb[CDB_GROUP0];
13536 	struct uscsi_cmd *com;
13537 	ushort_t byte_pos;
13538 	uchar_t bit_mask;
13539 	unsigned length;
13540 	int index;
13541 	int rval;
13542 
13543 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
13544 
13545 	/*
13546 	 * Since this tape does not support Tape Alert,
13547 	 * we now try to get the cleanbit status via
13548 	 * Request Sense.
13549 	 */
13550 
13551 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
13552 
13553 		index = 0;
13554 
13555 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
13556 
13557 		index = 1;
13558 
13559 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
13560 
13561 		index = 2;
13562 
13563 	} else {
13564 
13565 		return (-1);
13566 	}
13567 
13568 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
13569 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
13570 	length = byte_pos + 1;
13571 
13572 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13573 	sensep = kmem_zalloc(length, KM_SLEEP);
13574 
13575 	cdb[0] = SCMD_REQUEST_SENSE;
13576 	cdb[1] = 0;
13577 	cdb[2] = 0;
13578 	cdb[3] = 0;
13579 	cdb[4] = (char)length;
13580 	cdb[5] = 0;
13581 
13582 	com->uscsi_cdb = cdb;
13583 	com->uscsi_cdblen = CDB_GROUP0;
13584 	com->uscsi_bufaddr = (caddr_t)sensep;
13585 	com->uscsi_buflen = length;
13586 	com->uscsi_flags =
13587 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13588 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13589 
13590 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13591 
13592 	if (rval || com->uscsi_status || com->uscsi_resid) {
13593 
13594 		rval = -1;
13595 
13596 	} else {
13597 
13598 		rval = MTF_TAPE_CLN_SUPPORTED;
13599 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
13600 
13601 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13602 			    "sense data says head dirty\n");
13603 			rval |= MTF_TAPE_HEAD_DIRTY;
13604 		}
13605 	}
13606 
13607 	kmem_free(com, sizeof (struct uscsi_cmd));
13608 	kmem_free(sensep, length);
13609 	return (rval);
13610 }
13611 
13612 /*
13613  * st_clear_unit_attention
13614  *
13615  *  	run test unit ready's to clear out outstanding
13616  * 	unit attentions.
13617  * 	returns zero for SUCCESS or the errno from st_cmd call
13618  */
13619 static int
13620 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
13621 {
13622 	int	i    = 0;
13623 	int	rval;
13624 
13625 	GET_SOFT_STATE(dev_instance);
13626 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
13627 
13628 	do {
13629 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
13630 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
13631 	return (rval);
13632 }
13633 
13634 static void
13635 st_calculate_timeouts(struct scsi_tape *un)
13636 {
13637 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
13638 
13639 	if (un->un_dp->non_motion_timeout == 0) {
13640 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13641 			un->un_dp->non_motion_timeout =
13642 			    st_io_time * st_long_timeout_x;
13643 		} else {
13644 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
13645 		}
13646 	}
13647 
13648 	if (un->un_dp->io_timeout == 0) {
13649 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13650 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
13651 		} else {
13652 			un->un_dp->io_timeout = (ushort_t)st_io_time;
13653 		}
13654 	}
13655 
13656 	if (un->un_dp->rewind_timeout == 0) {
13657 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13658 			un->un_dp->rewind_timeout =
13659 			    st_space_time * st_long_timeout_x;
13660 		} else {
13661 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
13662 		}
13663 	}
13664 
13665 	if (un->un_dp->space_timeout == 0) {
13666 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13667 			un->un_dp->space_timeout =
13668 			    st_space_time * st_long_timeout_x;
13669 		} else {
13670 			un->un_dp->space_timeout = (ushort_t)st_space_time;
13671 		}
13672 	}
13673 
13674 	if (un->un_dp->load_timeout == 0) {
13675 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13676 			un->un_dp->load_timeout =
13677 			    st_space_time * st_long_timeout_x;
13678 		} else {
13679 			un->un_dp->load_timeout = (ushort_t)st_space_time;
13680 		}
13681 	}
13682 
13683 	if (un->un_dp->unload_timeout == 0) {
13684 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13685 			un->un_dp->unload_timeout =
13686 			    st_space_time * st_long_timeout_x;
13687 		} else {
13688 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
13689 		}
13690 	}
13691 
13692 	if (un->un_dp->erase_timeout == 0) {
13693 		if (un->un_dp->options & ST_LONG_ERASE) {
13694 			un->un_dp->erase_timeout =
13695 			    st_space_time * st_long_space_time_x;
13696 		} else {
13697 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
13698 		}
13699 	}
13700 }
13701 
13702 
13703 static writablity
13704 st_is_not_wormable(struct scsi_tape *un)
13705 {
13706 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
13707 	return (RDWR);
13708 }
13709 
13710 static writablity
13711 st_is_hp_dat_tape_worm(struct scsi_tape *un)
13712 {
13713 	writablity wrt;
13714 
13715 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
13716 
13717 	/* Mode sense should be current */
13718 	if (un->un_mspl->media_type == 1) {
13719 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13720 		    "Drive has WORM media loaded\n");
13721 		wrt = WORM;
13722 	} else {
13723 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13724 		    "Drive has non WORM media loaded\n");
13725 		wrt = RDWR;
13726 	}
13727 	return (wrt);
13728 }
13729 
13730 #define	HP_DAT_INQUIRY 0x4A
13731 static writablity
13732 st_is_hp_dat_worm(struct scsi_tape *un)
13733 {
13734 	char *buf;
13735 	int result;
13736 	writablity wrt;
13737 
13738 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
13739 
13740 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
13741 
13742 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
13743 
13744 	if (result != 0) {
13745 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13746 		    "Read Standard Inquiry for WORM support failed");
13747 		wrt = FAILED;
13748 	} else if ((buf[40] & 1) == 0) {
13749 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13750 		    "Drive is NOT WORMable\n");
13751 		/* This drive doesn't support it so don't check again */
13752 		un->un_dp->options &= ~ST_WORMABLE;
13753 		wrt = RDWR;
13754 		un->un_wormable = st_is_not_wormable;
13755 	} else {
13756 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13757 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13758 		un->un_wormable = st_is_hp_dat_tape_worm;
13759 		wrt = un->un_wormable(un);
13760 	}
13761 
13762 	kmem_free(buf, HP_DAT_INQUIRY);
13763 
13764 	/*
13765 	 * If drive doesn't support it no point in checking further.
13766 	 */
13767 	return (wrt);
13768 }
13769 
13770 static writablity
13771 st_is_hp_lto_tape_worm(struct scsi_tape *un)
13772 {
13773 	writablity wrt;
13774 
13775 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
13776 
13777 	/* Mode sense should be current */
13778 	switch (un->un_mspl->media_type) {
13779 	case 0x00:
13780 		switch (un->un_mspl->density) {
13781 		case 0x40:
13782 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13783 			    "Drive has standard Gen I media loaded\n");
13784 			break;
13785 		case 0x42:
13786 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13787 			    "Drive has standard Gen II media loaded\n");
13788 			break;
13789 		case 0x44:
13790 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13791 			    "Drive has standard Gen III media loaded\n");
13792 			break;
13793 		case 0x46:
13794 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13795 			    "Drive has standard Gen IV media loaded\n");
13796 			break;
13797 		default:
13798 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13799 			    "Drive has standard unknown 0x%X media loaded\n",
13800 			    un->un_mspl->density);
13801 		}
13802 		wrt = RDWR;
13803 		break;
13804 	case 0x01:
13805 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13806 		    "Drive has WORM medium loaded\n");
13807 		wrt = WORM;
13808 		break;
13809 	case 0x80:
13810 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13811 		    "Drive has CD-ROM emulation medium loaded\n");
13812 		wrt = WORM;
13813 		break;
13814 	default:
13815 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13816 		    "Drive has an unexpected medium type 0x%X loaded\n",
13817 		    un->un_mspl->media_type);
13818 		wrt = RDWR;
13819 	}
13820 
13821 	return (wrt);
13822 }
13823 
13824 #define	LTO_REQ_INQUIRY 44
13825 static writablity
13826 st_is_hp_lto_worm(struct scsi_tape *un)
13827 {
13828 	char *buf;
13829 	int result;
13830 	writablity wrt;
13831 
13832 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
13833 
13834 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
13835 
13836 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
13837 
13838 	if (result != 0) {
13839 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13840 		    "Read Standard Inquiry for WORM support failed");
13841 		wrt = FAILED;
13842 	} else if ((buf[40] & 1) == 0) {
13843 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13844 		    "Drive is NOT WORMable\n");
13845 		/* This drive doesn't support it so don't check again */
13846 		un->un_dp->options &= ~ST_WORMABLE;
13847 		wrt = RDWR;
13848 		un->un_wormable = st_is_not_wormable;
13849 	} else {
13850 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13851 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13852 		un->un_wormable = st_is_hp_lto_tape_worm;
13853 		wrt = un->un_wormable(un);
13854 	}
13855 
13856 	kmem_free(buf, LTO_REQ_INQUIRY);
13857 
13858 	/*
13859 	 * If drive doesn't support it no point in checking further.
13860 	 */
13861 	return (wrt);
13862 }
13863 
13864 static writablity
13865 st_is_t10_worm_device(struct scsi_tape *un)
13866 {
13867 	writablity wrt;
13868 
13869 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
13870 
13871 	if (un->un_mspl->media_type == 0x3c) {
13872 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13873 		    "Drive has WORM media loaded\n");
13874 		wrt = WORM;
13875 	} else {
13876 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13877 		    "Drive has non WORM media loaded\n");
13878 		wrt = RDWR;
13879 	}
13880 	return (wrt);
13881 }
13882 
13883 #define	SEQ_CAP_PAGE	(char)0xb0
13884 static writablity
13885 st_is_t10_worm(struct scsi_tape *un)
13886 {
13887 	char *buf;
13888 	int result;
13889 	writablity wrt;
13890 
13891 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
13892 
13893 	buf = kmem_zalloc(6, KM_SLEEP);
13894 
13895 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
13896 
13897 	if (result != 0) {
13898 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13899 		    "Read Vitial Inquiry for Sequental Capability"
13900 		    " WORM support failed %x", result);
13901 		wrt = FAILED;
13902 	} else if ((buf[4] & 1) == 0) {
13903 		ASSERT(buf[1] == SEQ_CAP_PAGE);
13904 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13905 		    "Drive is NOT WORMable\n");
13906 		/* This drive doesn't support it so don't check again */
13907 		un->un_dp->options &= ~ST_WORMABLE;
13908 		wrt = RDWR;
13909 		un->un_wormable = st_is_not_wormable;
13910 	} else {
13911 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13912 		    "Drive supports WORM\n");
13913 		un->un_wormable = st_is_t10_worm_device;
13914 		wrt = un->un_wormable(un);
13915 	}
13916 
13917 	kmem_free(buf, 6);
13918 
13919 	return (wrt);
13920 }
13921 
13922 
13923 #define	STK_REQ_SENSE 26
13924 
13925 static writablity
13926 st_is_stk_worm(struct scsi_tape *un)
13927 {
13928 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
13929 	struct scsi_extended_sense *sense;
13930 	struct uscsi_cmd *cmd;
13931 	char *buf;
13932 	int result;
13933 	writablity wrt;
13934 
13935 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
13936 
13937 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13938 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
13939 	sense = (struct scsi_extended_sense *)buf;
13940 
13941 	cmd->uscsi_flags = USCSI_READ;
13942 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13943 	cmd->uscsi_cdb = &cdb[0];
13944 	cmd->uscsi_bufaddr = buf;
13945 	cmd->uscsi_buflen = STK_REQ_SENSE;
13946 	cmd->uscsi_cdblen = CDB_GROUP0;
13947 	cmd->uscsi_rqlen = 0;
13948 	cmd->uscsi_rqbuf = NULL;
13949 
13950 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
13951 
13952 	if (result != 0 || cmd->uscsi_status != 0) {
13953 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13954 		    "Request Sense for WORM failed");
13955 		wrt = RDWR;
13956 	} else if (sense->es_add_len + 8 < 24) {
13957 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13958 		    "Drive didn't send enough sense data for WORM byte %d\n",
13959 		    sense->es_add_len + 8);
13960 		wrt = RDWR;
13961 		un->un_wormable = st_is_not_wormable;
13962 	} else if ((buf[24]) & 0x02) {
13963 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13964 		    "Drive has WORM tape loaded\n");
13965 		wrt = WORM;
13966 		un->un_wormable = st_is_stk_worm;
13967 	} else {
13968 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13969 		    "Drive has normal tape loaded\n");
13970 		wrt = RDWR;
13971 		un->un_wormable = st_is_stk_worm;
13972 	}
13973 
13974 	kmem_free(buf, STK_REQ_SENSE);
13975 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13976 	return (wrt);
13977 }
13978 
13979 #define	DLT_INQ_SZ 44
13980 
13981 static writablity
13982 st_is_dlt_tape_worm(struct scsi_tape *un)
13983 {
13984 	caddr_t buf;
13985 	int result;
13986 	writablity wrt;
13987 
13988 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
13989 
13990 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
13991 
13992 	/* Read Attribute Media Type */
13993 
13994 	result = st_read_attributes(un, 0x0408, buf, 10, st_uscsi_cmd);
13995 
13996 	/*
13997 	 * If this quantum drive is attached via an HBA that cannot
13998 	 * support thr read attributes command return error in the
13999 	 * hope that someday they will support the t10 method.
14000 	 */
14001 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
14002 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14003 		    "Read Attribute Command for WORM Media detection is not "
14004 		    "supported on the HBA that this drive is attached to.");
14005 		wrt = RDWR;
14006 		un->un_wormable = st_is_not_wormable;
14007 		goto out;
14008 	}
14009 
14010 	if (result != 0) {
14011 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14012 		    "Read Attribute Command for WORM Media returned 0x%x",
14013 		    result);
14014 		wrt = RDWR;
14015 		un->un_dp->options &= ~ST_WORMABLE;
14016 		goto out;
14017 	}
14018 
14019 	if ((uchar_t)buf[9] == 0x80) {
14020 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14021 		    "Drive media is WORM\n");
14022 		wrt = WORM;
14023 	} else {
14024 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14025 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
14026 		wrt = RDWR;
14027 	}
14028 
14029 out:
14030 	kmem_free(buf, DLT_INQ_SZ);
14031 	return (wrt);
14032 }
14033 
14034 static writablity
14035 st_is_dlt_worm(struct scsi_tape *un)
14036 {
14037 	caddr_t buf;
14038 	int result;
14039 	writablity wrt;
14040 
14041 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
14042 
14043 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14044 
14045 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
14046 
14047 	if (result != 0) {
14048 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14049 		    "Read Vendor Specific Inquiry for WORM support failed");
14050 		wrt = RDWR;
14051 		goto out;
14052 	}
14053 
14054 	if ((buf[2] & 1) == 0) {
14055 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14056 		    "Drive is not WORMable\n");
14057 		wrt = RDWR;
14058 		un->un_dp->options &= ~ST_WORMABLE;
14059 		un->un_wormable = st_is_not_wormable;
14060 		goto out;
14061 	} else {
14062 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14063 		    "Drive is WORMable\n");
14064 		un->un_wormable = st_is_dlt_tape_worm;
14065 		wrt = un->un_wormable(un);
14066 	}
14067 out:
14068 	kmem_free(buf, DLT_INQ_SZ);
14069 
14070 	return (wrt);
14071 }
14072 
14073 typedef struct {
14074 	struct modeheader_seq header;
14075 #if defined(_BIT_FIELDS_LTOH) /* X86 */
14076 	uchar_t pagecode	:6,
14077 				:2;
14078 	uchar_t page_len;
14079 	uchar_t syslogalive	:2,
14080 		device		:1,
14081 		abs		:1,
14082 		ulpbot		:1,
14083 		prth		:1,
14084 		ponej		:1,
14085 		ait		:1;
14086 	uchar_t span;
14087 
14088 	uchar_t			:6,
14089 		worm		:1,
14090 		mic		:1;
14091 	uchar_t worm_cap	:1,
14092 				:7;
14093 	uint32_t		:32;
14094 #else /* SPARC */
14095 	uchar_t			:2,
14096 		pagecode	:6;
14097 	uchar_t page_len;
14098 	uchar_t ait		:1,
14099 		device		:1,
14100 		abs		:1,
14101 		ulpbot		:1,
14102 		prth		:1,
14103 		ponej		:1,
14104 		syslogalive	:2;
14105 	uchar_t span;
14106 	uchar_t mic		:1,
14107 		worm		:1,
14108 				:6;
14109 	uchar_t			:7,
14110 		worm_cap	:1;
14111 	uint32_t		:32;
14112 #endif
14113 }ait_dev_con;
14114 
14115 #define	AIT_DEV_PAGE 0x31
14116 static writablity
14117 st_is_sony_worm(struct scsi_tape *un)
14118 {
14119 	int result;
14120 	writablity wrt;
14121 	ait_dev_con *ait_conf;
14122 
14123 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14124 
14125 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
14126 
14127 	result = st_gen_mode_sense(un, st_uscsi_cmd, AIT_DEV_PAGE,
14128 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
14129 
14130 	if (result == 0) {
14131 
14132 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
14133 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14134 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
14135 			    ait_conf->pagecode, AIT_DEV_PAGE);
14136 			wrt = RDWR;
14137 			un->un_wormable = st_is_not_wormable;
14138 
14139 		} else if (ait_conf->worm_cap) {
14140 
14141 			un->un_wormable = st_is_sony_worm;
14142 
14143 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14144 			    "Drives is WORMable\n");
14145 			if (ait_conf->worm) {
14146 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14147 				    "Media is WORM\n");
14148 				wrt = WORM;
14149 			} else {
14150 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14151 				    "Media is not WORM\n");
14152 				wrt = RDWR;
14153 			}
14154 
14155 		} else {
14156 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14157 			    "Drives not is WORMable\n");
14158 			wrt = RDWR;
14159 			/* No further checking required */
14160 			un->un_dp->options &= ~ST_WORMABLE;
14161 		}
14162 
14163 	} else {
14164 
14165 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14166 		    "AIT device config mode sense page read command failed"
14167 		    " result = %d ", result);
14168 		wrt = FAILED;
14169 		un->un_wormable = st_is_not_wormable;
14170 	}
14171 
14172 	kmem_free(ait_conf, sizeof (ait_dev_con));
14173 	return (wrt);
14174 }
14175 
14176 static writablity
14177 st_is_drive_worm(struct scsi_tape *un)
14178 {
14179 	writablity wrt;
14180 
14181 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14182 
14183 	switch (un->un_dp->type) {
14184 	case MT_ISDLT:
14185 		wrt = st_is_dlt_worm(un);
14186 		break;
14187 
14188 	case MT_ISSTK9840:
14189 		wrt = st_is_stk_worm(un);
14190 		break;
14191 
14192 	case MT_IS8MM:
14193 	case MT_ISAIT:
14194 		wrt = st_is_sony_worm(un);
14195 		break;
14196 
14197 	case MT_LTO:
14198 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14199 			wrt = st_is_hp_lto_worm(un);
14200 		} else {
14201 			wrt = st_is_t10_worm(un);
14202 		}
14203 		break;
14204 
14205 	case MT_ISDAT:
14206 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14207 			wrt = st_is_hp_dat_worm(un);
14208 		} else {
14209 			wrt = st_is_t10_worm(un);
14210 		}
14211 		break;
14212 
14213 	default:
14214 		wrt = FAILED;
14215 		break;
14216 	}
14217 
14218 	/*
14219 	 * If any of the above failed try the t10 standard method.
14220 	 */
14221 	if (wrt == FAILED) {
14222 		wrt = st_is_t10_worm(un);
14223 	}
14224 
14225 	/*
14226 	 * Unknown method for detecting WORM media.
14227 	 */
14228 	if (wrt == FAILED) {
14229 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14230 		    "Unknown method for WORM media detection\n");
14231 		wrt = RDWR;
14232 		un->un_dp->options &= ~ST_WORMABLE;
14233 	}
14234 
14235 	return (wrt);
14236 }
14237 
14238 static int
14239 st_read_attributes(struct scsi_tape *un, uint16_t attribute, void *pnt,
14240     size_t size, ubufunc_t bufunc)
14241 {
14242 	char cdb[CDB_GROUP4];
14243 	int result;
14244 	struct uscsi_cmd *cmd;
14245 	struct scsi_arq_status status;
14246 
14247 	caddr_t buf = (caddr_t)pnt;
14248 
14249 	ST_FUNC(ST_DEVINFO, st_read_attributes);
14250 
14251 	if (un->un_sd->sd_inq->inq_ansi < 3) {
14252 		return (ENOTTY);
14253 	}
14254 
14255 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14256 
14257 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
14258 	cdb[1] = 0;
14259 	cdb[2] = 0;
14260 	cdb[3] = 0;
14261 	cdb[4] = 0;
14262 	cdb[5] = 0;
14263 	cdb[6] = 0;
14264 	cdb[7] = 0;
14265 	cdb[8] = (char)(attribute >> 8);
14266 	cdb[9] = (char)(attribute);
14267 	cdb[10] = (char)(size >> 24);
14268 	cdb[11] = (char)(size >> 16);
14269 	cdb[12] = (char)(size >> 8);
14270 	cdb[13] = (char)(size);
14271 	cdb[14] = 0;
14272 	cdb[15] = 0;
14273 
14274 
14275 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE | USCSI_DIAGNOSE;
14276 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14277 	cmd->uscsi_cdb = &cdb[0];
14278 	cmd->uscsi_bufaddr = (caddr_t)buf;
14279 	cmd->uscsi_buflen = size;
14280 	cmd->uscsi_cdblen = sizeof (cdb);
14281 	cmd->uscsi_rqlen = sizeof (status);
14282 	cmd->uscsi_rqbuf = (caddr_t)&status;
14283 
14284 	result = bufunc(un, cmd, FKIOCTL);
14285 
14286 	if (result != 0 || cmd->uscsi_status != 0) {
14287 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
14288 		    "st_read_attribute failed: result %d status %d\n",
14289 		    result, cmd->uscsi_status);
14290 		/*
14291 		 * If this returns invalid operation code don't try again.
14292 		 */
14293 		if (un->un_sd->sd_sense->es_key == KEY_ILLEGAL_REQUEST &&
14294 		    un->un_sd->sd_sense->es_add_code == 0x20) {
14295 			result = ENOTTY;
14296 		} else if (result == 0) {
14297 			result = EIO;
14298 		}
14299 
14300 	} else {
14301 
14302 		/*
14303 		 * The attribute retured should match the attribute requested.
14304 		 */
14305 		if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
14306 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14307 			    "st_read_attribute got wrong data back expected "
14308 			    "0x%x got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
14309 			st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14310 			    "bad? data", buf, size);
14311 			result = EIO;
14312 		}
14313 	}
14314 
14315 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14316 
14317 	return (result);
14318 }
14319 
14320 static int
14321 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
14322     uchar_t page)
14323 {
14324 	char cdb[CDB_GROUP0];
14325 	struct scsi_extended_sense *sense;
14326 	struct uscsi_cmd *cmd;
14327 	int result;
14328 
14329 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
14330 
14331 	cdb[0] = SCMD_INQUIRY;
14332 	cdb[1] = page ? 1 : 0;
14333 	cdb[2] = page;
14334 	cdb[3] = 0;
14335 	cdb[4] = size;
14336 	cdb[5] = 0;
14337 
14338 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14339 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
14340 
14341 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
14342 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14343 	cmd->uscsi_cdb = &cdb[0];
14344 	cmd->uscsi_bufaddr = dest;
14345 	cmd->uscsi_buflen = size;
14346 	cmd->uscsi_cdblen = CDB_GROUP0;
14347 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
14348 	cmd->uscsi_rqbuf = (caddr_t)sense;
14349 
14350 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14351 
14352 	if (result != 0 || cmd->uscsi_status != 0) {
14353 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14354 		    "st_get_special_inquiry() failed for page %x", page);
14355 		if (result == 0) {
14356 			result = EIO;
14357 		}
14358 	}
14359 
14360 	kmem_free(sense, sizeof (struct scsi_extended_sense));
14361 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14362 
14363 	return (result);
14364 }
14365 
14366 
14367 static int
14368 st_update_block_pos(struct scsi_tape *un, bufunc_t bf, int post_space)
14369 {
14370 	int rval = ENOTTY;
14371 	uchar_t status = un->un_status;
14372 	posmode previous_pmode = un->un_running.pmode;
14373 
14374 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
14375 
14376 	while (un->un_read_pos_type != NO_POS) {
14377 		rval = bf(un, SCMD_READ_POSITION, 32, SYNC_CMD);
14378 
14379 		/*
14380 		 * If read position command returned good status
14381 		 * Parse the data to see if the position can be interpreted.
14382 		 */
14383 		if ((rval == 0) &&
14384 		    ((rval = st_interpret_read_pos(un, &un->un_pos,
14385 		    un->un_read_pos_type, 32, (caddr_t)un->un_read_pos_data,
14386 		    post_space)) == 0)) {
14387 			/*
14388 			 * Update the running position as well if un_pos was
14389 			 * ok. But only if recovery is enabled.
14390 			 */
14391 			if (st_recov_sz != sizeof (recov_info)) {
14392 				break;
14393 			}
14394 			rval = st_interpret_read_pos(un, &un->un_running,
14395 			    un->un_read_pos_type, 32,
14396 			    (caddr_t)un->un_read_pos_data, post_space);
14397 			un->un_status = status;
14398 			break;
14399 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
14400 			un->un_running.pmode = previous_pmode;
14401 			continue;
14402 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
14403 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
14404 			    "st_update_block_pos() read position cmd 0x%x"
14405 			    " returned 0x%x un_status = %d",
14406 			    un->un_read_pos_type, rval, un->un_status);
14407 			/* ENOTTY means it read garbage. try something else. */
14408 			if (rval == ENOTTY) {
14409 				rval = EIO; /* so ENOTTY is not final rval */
14410 			} else {
14411 				break;
14412 			}
14413 		} else {
14414 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
14415 			    "st_update_block_pos() read position cmd %x"
14416 			    " returned %x", un->un_read_pos_type, rval);
14417 			un->un_running.pmode = previous_pmode;
14418 		}
14419 
14420 		switch (un->un_read_pos_type) {
14421 		case SHORT_POS:
14422 			un->un_read_pos_type = NO_POS;
14423 			break;
14424 
14425 		case LONG_POS:
14426 			un->un_read_pos_type = EXT_POS;
14427 			break;
14428 
14429 		case EXT_POS:
14430 			un->un_read_pos_type = SHORT_POS;
14431 			break;
14432 
14433 		default:
14434 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14435 			    "Unexpected read position type 0x%x",
14436 			    un->un_read_pos_type);
14437 		}
14438 		un->un_status = KEY_NO_SENSE;
14439 	}
14440 
14441 	return (rval);
14442 }
14443 
14444 static int
14445 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
14446 {
14447 	int result;
14448 	size_t d_sz;
14449 	caddr_t pos_info;
14450 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
14451 
14452 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
14453 
14454 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
14455 		return (0);
14456 	}
14457 
14458 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
14459 
14460 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14461 		    "bp_mapin_common() failed");
14462 
14463 		return (EIO);
14464 	}
14465 
14466 	d_sz = bp->b_bcount - bp->b_resid;
14467 	if (d_sz == 0) {
14468 		bp_mapout(bp);
14469 		return (EIO);
14470 	}
14471 
14472 	/*
14473 	 * Copy the buf to a double-word aligned memory that can hold the
14474 	 * tape_position_t data structure.
14475 	 */
14476 	if ((pos_info = kmem_alloc(d_sz, KM_NOSLEEP)) == NULL) {
14477 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14478 		    "kmem_alloc() failed");
14479 		bp_mapout(bp);
14480 		return (EIO);
14481 	}
14482 	bcopy(bp->b_un.b_addr, pos_info, d_sz);
14483 
14484 #ifdef STDEBUG
14485 	if ((st_debug & 0x7) > 2) {
14486 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14487 		    "st_get_read_pos() position info",
14488 		    pos_info, bp->b_bcount);
14489 	}
14490 #endif
14491 
14492 	result = st_interpret_read_pos(un, &un->un_pos, cmd->uscsi_cdb[1],
14493 	    d_sz, pos_info, 0);
14494 
14495 	COPY_POS(&un->un_running, &un->un_pos);
14496 
14497 	kmem_free(pos_info, d_sz);
14498 	bp_mapout(bp);
14499 
14500 	return (result);
14501 }
14502 
14503 #if defined(_BIG_ENDIAN)
14504 
14505 #define	FIX_ENDIAN16(x)
14506 #define	FIX_ENDIAN32(x)
14507 #define	FIX_ENDIAN64(x)
14508 
14509 #elif defined(_LITTLE_ENDIAN)
14510 
14511 static void
14512 st_swap16(uint16_t *val)
14513 {
14514 	uint16_t tmp;
14515 
14516 	tmp = (*val >>  8) & 0xff;
14517 	tmp |= (*val <<  8) & 0xff00;
14518 
14519 	*val = tmp;
14520 }
14521 
14522 static void
14523 st_swap32(uint32_t *val)
14524 {
14525 	uint32_t tmp;
14526 
14527 	tmp =  (*val >> 24) & 0xff;
14528 	tmp |= (*val >>  8) & 0xff00;
14529 	tmp |= (*val <<  8) & 0xff0000;
14530 	tmp |= (*val << 24) & 0xff000000;
14531 
14532 	*val = tmp;
14533 }
14534 
14535 static void
14536 st_swap64(uint64_t *val)
14537 {
14538 	uint32_t low;
14539 	uint32_t high;
14540 
14541 	low =  (uint32_t)(*val);
14542 	high = (uint32_t)(*val >> 32);
14543 
14544 	st_swap32(&low);
14545 	st_swap32(&high);
14546 
14547 	*val =  high;
14548 	*val |= ((uint64_t)low << 32);
14549 }
14550 
14551 #define	FIX_ENDIAN16(x) st_swap16(x)
14552 #define	FIX_ENDIAN32(x) st_swap32(x)
14553 #define	FIX_ENDIAN64(x) st_swap64(x)
14554 #endif
14555 
14556 /*
14557  * st_interpret_read_pos()
14558  *
14559  * Returns:
14560  *	0	If secsessful.
14561  *	EIO	If read postion responce data was unuseable or invalid.
14562  *	ERANGE	If the position of the drive is too large for the read_p_type.
14563  *	ENOTTY	If the responce data looks invalid for the read position type.
14564  */
14565 
14566 static int
14567 st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
14568     read_p_types type, size_t data_sz, const caddr_t responce, int post_space)
14569 {
14570 	int rval = 0;
14571 	int flag = 0;
14572 	tapepos_t org;
14573 
14574 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
14575 
14576 	/*
14577 	 * We expect the position value to change after a space command.
14578 	 * So if post_space is set we don't print out what has changed.
14579 	 */
14580 	if ((dest != &un->un_pos) && (post_space == 0) &&
14581 	    (st_recov_sz == sizeof (recov_info))) {
14582 		COPY_POS(&org, dest);
14583 		flag = 1;
14584 	}
14585 
14586 	/*
14587 	 * See what kind of read position was requested.
14588 	 */
14589 	switch (type) {
14590 
14591 	case SHORT_POS: /* Short data format */
14592 	{
14593 		tape_position_t *pos_info = (tape_position_t *)responce;
14594 		uint32_t value;
14595 
14596 		/* If reserved fields are non zero don't use the data */
14597 		if (pos_info->reserved0 || pos_info->reserved1 ||
14598 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
14599 		    pos_info->reserved3) {
14600 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14601 			    "Invalid Read Short Position Data returned\n");
14602 			rval = EIO;
14603 			break;
14604 		}
14605 		/*
14606 		 * Position is to large to use this type of read position.
14607 		 */
14608 		if (pos_info->posi_err == 1) {
14609 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14610 			    "Drive reported position error\n");
14611 			rval = ERANGE;
14612 			break;
14613 		}
14614 		/*
14615 		 * If your at the begining of partition and end at the same
14616 		 * time it's very small partition or bad data.
14617 		 */
14618 		if (pos_info->begin_of_part && pos_info->end_of_part) {
14619 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14620 			    "SHORT_POS returned begin and end of"
14621 			    " partition\n");
14622 			rval = EIO;
14623 			break;
14624 		}
14625 
14626 		if (pos_info->blk_posi_unkwn == 0) {
14627 
14628 			value = pos_info->host_block;
14629 			FIX_ENDIAN32(&value);
14630 
14631 			/*
14632 			 * If the tape is rewound the host blcok should be 0.
14633 			 */
14634 			if ((pos_info->begin_of_part == 1) &&
14635 			    (value != 0)) {
14636 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14637 				    "SHORT_POS returned begin of partition"
14638 				    " but host block was 0x%x\n", value);
14639 				rval = EIO;
14640 				break;
14641 			}
14642 
14643 			if (dest->lgclblkno != value) {
14644 				if (flag)
14645 					flag++;
14646 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14647 				    "SHORT_POS current logical 0x%"PRIx64" read"
14648 				    " 0x%x\n", dest->lgclblkno, value);
14649 			}
14650 
14651 			dest->lgclblkno = (uint64_t)value;
14652 
14653 			/*
14654 			 * If the begining of partition is true and the
14655 			 * block number is zero we will beleive that it is
14656 			 * rewound. Promote the pmode to legacy.
14657 			 */
14658 			if ((pos_info->begin_of_part == 1) &&
14659 			    (value == 0)) {
14660 				dest->blkno = 0;
14661 				dest->fileno = 0;
14662 				if (dest->pmode != legacy)
14663 					dest->pmode = legacy;
14664 			/*
14665 			 * otherwise if the pmode was invalid,
14666 			 * promote it to logical.
14667 			 */
14668 			} else if (dest->pmode == invalid) {
14669 				dest->pmode = logical;
14670 			}
14671 
14672 			if (dest->partition != pos_info->partition_number) {
14673 				if (flag)
14674 					flag++;
14675 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14676 				    "SHORT_POS current partition %d read %d\n",
14677 				    dest->partition,
14678 				    pos_info->partition_number);
14679 			}
14680 
14681 			dest->partition = pos_info->partition_number;
14682 
14683 		} else {
14684 			dest->pmode = invalid;
14685 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14686 			    "Tape drive reported block position as unknown\n");
14687 		}
14688 		break;
14689 	}
14690 
14691 	case LONG_POS: /* Long data format */
14692 	{
14693 		uint64_t value;
14694 		tape_position_long_t *long_pos_info =
14695 		    (tape_position_long_t *)responce;
14696 
14697 		/* If reserved fields are non zero don't use the data */
14698 		if ((long_pos_info->reserved0) ||
14699 		    (long_pos_info->reserved1) ||
14700 		    (long_pos_info->reserved2)) {
14701 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14702 			    "Invalid Read Long Position Data returned\n");
14703 			rval = ENOTTY;
14704 			break;
14705 		}
14706 
14707 		/* Is position Valid */
14708 		if (long_pos_info->blk_posi_unkwn == 0) {
14709 			uint32_t part;
14710 
14711 			value = long_pos_info->block_number;
14712 			FIX_ENDIAN64(&value);
14713 
14714 			/*
14715 			 * If it says we are at the begining of partition
14716 			 * the block value better be 0.
14717 			 */
14718 			if ((long_pos_info->begin_of_part == 1) &&
14719 			    (value != 0)) {
14720 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14721 				    "LONG_POS returned begin of partition but"
14722 				    " block number was 0x%"PRIx64"\n", value);
14723 				rval = ENOTTY;
14724 				break;
14725 			}
14726 			/*
14727 			 * Can't be at the start and the end of the partition
14728 			 * at the same time if the partition is larger the 0.
14729 			 */
14730 			if (long_pos_info->begin_of_part &&
14731 			    long_pos_info->end_of_part) {
14732 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14733 				    "LONG_POS returned begin and end of"
14734 				    " partition\n");
14735 				rval = ENOTTY;
14736 				break;
14737 			}
14738 
14739 			/*
14740 			 * If the logical block number is not what we expected.
14741 			 */
14742 			if (dest->lgclblkno != value) {
14743 				if (flag)
14744 					flag++;
14745 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14746 				    "LONG_POS current logical 0x%"PRIx64
14747 				    " read 0x%"PRIx64"\n",
14748 				    dest->lgclblkno, value);
14749 			}
14750 			dest->lgclblkno = value;
14751 
14752 			/*
14753 			 * If the begining of partition is true and the
14754 			 * block number is zero we will beleive that it is
14755 			 * rewound. Promote the pmode to legacy.
14756 			 */
14757 			if ((long_pos_info->begin_of_part == 1) &&
14758 			    (long_pos_info->block_number == 0)) {
14759 				dest->blkno = 0;
14760 				dest->fileno = 0;
14761 				if (dest->pmode != legacy)
14762 					dest->pmode = legacy;
14763 			/*
14764 			 * otherwise if the pmode was invalid,
14765 			 * promote it to logical.
14766 			 */
14767 			} else if (dest->pmode == invalid) {
14768 				dest->pmode = logical;
14769 			}
14770 
14771 			part = long_pos_info->partition;
14772 			FIX_ENDIAN32(&part);
14773 			if (dest->partition != part) {
14774 				if (flag)
14775 					flag++;
14776 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14777 				    "LONG_POS current partition %d"
14778 				    " read %d\n", dest->partition, part);
14779 			}
14780 			dest->partition = part;
14781 		} else {
14782 			/*
14783 			 * If the drive doesn't know location,
14784 			 * we don't either.
14785 			 */
14786 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14787 			    "Tape drive reported block position as unknown\n");
14788 			dest->pmode = invalid;
14789 		}
14790 
14791 		/* Is file position valid */
14792 		if (long_pos_info->mrk_posi_unkwn == 0) {
14793 			value = long_pos_info->file_number;
14794 			FIX_ENDIAN64(&value);
14795 			/*
14796 			 * If it says we are at the begining of partition
14797 			 * the block value better be 0.
14798 			 */
14799 			if ((long_pos_info->begin_of_part == 1) &&
14800 			    (value != 0)) {
14801 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14802 				    "LONG_POS returned begin of partition but"
14803 				    " block number was 0x%"PRIx64"\n", value);
14804 				rval = ENOTTY;
14805 				break;
14806 			}
14807 			if (((dest->pmode == legacy) ||
14808 			    (dest->pmode == logical)) &&
14809 			    (dest->fileno != value)) {
14810 				if (flag)
14811 					flag++;
14812 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14813 				    "LONG_POS fileno 0x%"PRIx64
14814 				    " not un_pos %x\n", value,
14815 				    dest->fileno);
14816 			} else if (dest->pmode == invalid) {
14817 				dest->pmode = logical;
14818 			}
14819 			dest->fileno = (int32_t)value;
14820 		}
14821 
14822 		if (dest->pmode != invalid && long_pos_info->end_of_part) {
14823 			dest->eof = ST_EOT;
14824 		}
14825 
14826 		break;
14827 	}
14828 
14829 	case EXT_POS: /* Extended data format */
14830 	{
14831 		uint64_t value;
14832 		uint16_t len;
14833 		tape_position_ext_t *ext_pos_info =
14834 		    (tape_position_ext_t *)responce;
14835 
14836 		/* Make sure that there is enough data there */
14837 		if (data_sz < 16) {
14838 			break;
14839 		}
14840 
14841 		/* If reserved fields are non zero don't use the data */
14842 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
14843 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14844 			    "EXT_POS reserved fields not zero\n");
14845 			rval = ENOTTY;
14846 			break;
14847 		}
14848 
14849 		/*
14850 		 * In the unlikely event of overflowing 64 bits of position.
14851 		 */
14852 		if (ext_pos_info->posi_err != 0) {
14853 			rval = ERANGE;
14854 			break;
14855 		}
14856 
14857 		len = ext_pos_info->parameter_len;
14858 		FIX_ENDIAN16(&len);
14859 
14860 		if (len != 0x1c) {
14861 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14862 			    "EXT_POS parameter_len should be 0x1c was 0x%x\n",
14863 			    len);
14864 			rval = ENOTTY;
14865 			break;
14866 		}
14867 
14868 		/* Is block position information valid */
14869 		if (ext_pos_info->blk_posi_unkwn == 0) {
14870 
14871 			value = ext_pos_info->host_block;
14872 			FIX_ENDIAN64(&value);
14873 			if ((ext_pos_info->begin_of_part == 1) &&
14874 			    (value != 0)) {
14875 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14876 				    "EXT_POS returned begining of partition but"
14877 				    " the host block was 0x%"PRIx64"\n", value);
14878 				rval = ENOTTY;
14879 				break;
14880 			}
14881 
14882 			if (dest->lgclblkno != value) {
14883 				if (flag)
14884 					flag++;
14885 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14886 				    "EXT_POS current logical 0x%"PRIx64
14887 				    " read 0x%"PRIx64"\n",
14888 				    dest->lgclblkno, value);
14889 			}
14890 			dest->lgclblkno = value;
14891 
14892 			/*
14893 			 * If the begining of partition is true and the
14894 			 * block number is zero we will beleive that it is
14895 			 * rewound. Promote the pmode to legacy.
14896 			 */
14897 			if ((ext_pos_info->begin_of_part == 1) &&
14898 			    (ext_pos_info->host_block == 0)) {
14899 				dest->blkno = 0;
14900 				dest->fileno = 0;
14901 				if (dest->pmode != legacy) {
14902 					dest->pmode = legacy;
14903 				}
14904 			/*
14905 			 * otherwise if the pmode was invalid,
14906 			 * promote it to logical.
14907 			 */
14908 			} else if (dest->pmode == invalid) {
14909 				dest->pmode = logical;
14910 			}
14911 
14912 			if (dest->partition != ext_pos_info->partition) {
14913 				if (flag)
14914 					flag++;
14915 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14916 				    "EXT_POS current partition %d read %d\n",
14917 				    dest->partition,
14918 				    ext_pos_info->partition);
14919 			}
14920 			dest->partition = ext_pos_info->partition;
14921 
14922 		} else {
14923 			dest->pmode = invalid;
14924 		}
14925 		break;
14926 	}
14927 
14928 	default:
14929 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14930 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
14931 		rval = EIO;
14932 	}
14933 
14934 	if ((flag > 1) && (rval == 0) && (org.pmode != invalid)) {
14935 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14936 		    "position read in", &org);
14937 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14938 		    "position read out", dest);
14939 	}
14940 
14941 	return (rval);
14942 }
14943 
14944 static int
14945 st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos,
14946     uint64_t lblk, uchar_t partition)
14947 {
14948 	int rval;
14949 	char cdb[CDB_GROUP4];
14950 	struct uscsi_cmd *cmd;
14951 	struct scsi_extended_sense sense;
14952 	bufunc_t bf = (ubf == st_uscsi_cmd) ? st_cmd : st_rcmd;
14953 
14954 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
14955 	/*
14956 	 * Not sure what to do when doing recovery and not wanting
14957 	 * to update un_pos
14958 	 */
14959 
14960 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14961 
14962 	if (lblk <= INT32_MAX) {
14963 		cmd->uscsi_cdblen = CDB_GROUP1;
14964 		cdb[0] = SCMD_LOCATE;
14965 		cdb[1] = pos->partition == partition ? 0 : 2;
14966 		cdb[2] = 0;
14967 		cdb[3] = (char)(lblk >> 24);
14968 		cdb[4] = (char)(lblk >> 16);
14969 		cdb[5] = (char)(lblk >> 8);
14970 		cdb[6] = (char)(lblk);
14971 		cdb[7] = 0;
14972 		cdb[8] = partition;
14973 		cdb[9] = 0;
14974 	} else {
14975 		/*
14976 		 * If the drive doesn't give a 64 bit read position data
14977 		 * it is unlikely it will accept 64 bit locates.
14978 		 */
14979 		if (un->un_read_pos_type != LONG_POS) {
14980 			kmem_free(cmd, sizeof (struct uscsi_cmd));
14981 			return (ERANGE);
14982 		}
14983 		cmd->uscsi_cdblen = CDB_GROUP4;
14984 		cdb[0] = (char)SCMD_LOCATE_G4;
14985 		cdb[1] = pos->partition == partition ? 0 : 2;
14986 		cdb[2] = 0;
14987 		cdb[3] = partition;
14988 		cdb[4] = (char)(lblk >> 56);
14989 		cdb[5] = (char)(lblk >> 48);
14990 		cdb[6] = (char)(lblk >> 40);
14991 		cdb[7] = (char)(lblk >> 32);
14992 		cdb[8] = (char)(lblk >> 24);
14993 		cdb[9] = (char)(lblk >> 16);
14994 		cdb[10] = (char)(lblk >> 8);
14995 		cdb[11] = (char)(lblk);
14996 		cdb[12] = 0;
14997 		cdb[13] = 0;
14998 		cdb[14] = 0;
14999 		cdb[15] = 0;
15000 	}
15001 
15002 
15003 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
15004 	cmd->uscsi_rqbuf = (caddr_t)&sense;
15005 	cmd->uscsi_rqlen = sizeof (sense);
15006 	cmd->uscsi_timeout = un->un_dp->space_timeout;
15007 	cmd->uscsi_cdb = cdb;
15008 
15009 	rval = ubf(un, cmd, FKIOCTL);
15010 
15011 	pos->pmode = logical;
15012 	pos->eof = ST_NO_EOF;
15013 
15014 	if (lblk > INT32_MAX) {
15015 		/*
15016 		 * XXX This is a work around till we handle Descriptor format
15017 		 * sense data. Since we are sending a command where the standard
15018 		 * sense data can not correctly represent a correct residual in
15019 		 * 4 bytes.
15020 		 */
15021 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
15022 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15023 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
15024 			/* Doesn't like big locate command */
15025 			un->un_status = 0;
15026 			rval = ERANGE;
15027 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
15028 			/* Aborted big locate command */
15029 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15030 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
15031 			    rval);
15032 			un->un_status = 0;
15033 			rval = EIO;
15034 		} else if (st_update_block_pos(un, bf, 1)) {
15035 			/* read position failed */
15036 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15037 			    "Big LOCATE and read pos: rval = %d\n", rval);
15038 			rval = EIO;
15039 		} else if (lblk > un->un_pos.lgclblkno) {
15040 			/* read position worked but position was not expected */
15041 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15042 			    "Big LOCATE and recover read less then desired 0x%"
15043 			    PRIx64"\n", un->un_pos.lgclblkno);
15044 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
15045 			un->un_status = KEY_BLANK_CHECK;
15046 			rval = ESPIPE;
15047 		} else if (lblk == un->un_pos.lgclblkno) {
15048 			/* read position was what was expected */
15049 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15050 			    "Big LOCATE and recover seems to have worked\n");
15051 			un->un_err_resid = 0;
15052 			rval = 0;
15053 		} else {
15054 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15055 			    "BIGLOCATE end up going backwards");
15056 			un->un_err_resid = lblk;
15057 			rval = EIO;
15058 		}
15059 
15060 	} else if (rval == 0) {
15061 		/* Worked as requested */
15062 		pos->lgclblkno = lblk;
15063 
15064 	} else if (((cmd->uscsi_status & ST_STATUS_MASK) == STATUS_CHECK) &&
15065 	    (cmd->uscsi_resid != 0)) {
15066 		/* Got part way there but wasn't enough blocks on tape */
15067 		pos->lgclblkno = lblk - cmd->uscsi_resid;
15068 		un->un_err_resid = cmd->uscsi_resid;
15069 		un->un_status = KEY_BLANK_CHECK;
15070 		rval = ESPIPE;
15071 
15072 	} else if (st_update_block_pos(un, bf, 1) == 0) {
15073 		/* Got part way there but drive didn't tell what we missed by */
15074 		un->un_err_resid = lblk - pos->lgclblkno;
15075 		un->un_status = KEY_BLANK_CHECK;
15076 		rval = ESPIPE;
15077 
15078 	} else {
15079 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15080 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
15081 		    rval, cmd->uscsi_status);
15082 		un->un_err_resid = lblk;
15083 		un->un_status = KEY_ILLEGAL_REQUEST;
15084 		pos->pmode = invalid;
15085 		rval = EIO;
15086 	}
15087 
15088 	kmem_free(cmd, sizeof (struct uscsi_cmd));
15089 
15090 	return (rval);
15091 }
15092 
15093 static int
15094 st_mtfsf_ioctl(struct scsi_tape *un, int64_t files)
15095 {
15096 	int rval;
15097 
15098 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
15099 
15100 
15101 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15102 	    "st_mtfsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15103 #if 0
15104 	if ((IN_EOF(un->un_pos)) && (files == 1)) {
15105 		un->un_pos.fileno++;
15106 		un->un_pos.blkno = 0;
15107 		return (0);
15108 	}
15109 #endif
15110 	/* pmode == invalid already handled */
15111 	if (un->un_pos.pmode == legacy) {
15112 		/*
15113 		 * forward space over filemark
15114 		 *
15115 		 * For ASF we allow a count of 0 on fsf which means
15116 		 * we just want to go to beginning of current file.
15117 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
15118 		 * Allow stepping over double fmk with reel
15119 		 */
15120 		if ((un->un_pos.eof >= ST_EOT) &&
15121 		    (files > 0) &&
15122 		    ((un->un_dp->options & ST_REEL) == 0)) {
15123 			/* we're at EOM */
15124 			un->un_err_resid = files;
15125 			un->un_status = KEY_BLANK_CHECK;
15126 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15127 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
15128 			return (EIO);
15129 		}
15130 
15131 		/*
15132 		 * physical tape position may not be what we've been
15133 		 * telling the user; adjust the request accordingly
15134 		 */
15135 		if (IN_EOF(un->un_pos)) {
15136 			un->un_pos.fileno++;
15137 			un->un_pos.blkno = 0;
15138 			/*
15139 			 * For positive direction case, we're now covered.
15140 			 * For zero or negative direction, we're covered
15141 			 * (almost)
15142 			 */
15143 			files--;
15144 		}
15145 
15146 	}
15147 
15148 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15149 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15150 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
15151 		return (EIO);
15152 	}
15153 
15154 
15155 	/*
15156 	 * Forward space file marks.
15157 	 * We leave ourselves at block zero
15158 	 * of the target file number.
15159 	 */
15160 	if (files < 0) {
15161 		rval = st_backward_space_files(un, -files, 0);
15162 	} else {
15163 		rval = st_forward_space_files(un, files);
15164 	}
15165 
15166 	return (rval);
15167 }
15168 
15169 static int
15170 st_forward_space_files(struct scsi_tape *un, int64_t count)
15171 {
15172 	int rval;
15173 
15174 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
15175 
15176 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15177 	    "fspace: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15178 
15179 	ASSERT(count >= 0);
15180 	ASSERT(un->un_pos.pmode != invalid);
15181 
15182 	/*
15183 	 * A space with a count of zero means take me to the start of file.
15184 	 */
15185 	if (count == 0) {
15186 
15187 		/* Hay look were already there */
15188 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0) {
15189 			un->un_err_resid = 0;
15190 			COPY_POS(&un->un_err_pos, &un->un_pos);
15191 			return (0);
15192 		}
15193 
15194 		/*
15195 		 * Well we are in the first file.
15196 		 * A rewind will get to the start.
15197 		 */
15198 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
15199 			rval = st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
15200 
15201 		/*
15202 		 * Can we backspace to get there?
15203 		 * This should work in logical mode.
15204 		 */
15205 		} else if (un->un_dp->options & ST_BSF) {
15206 			rval = st_space_to_begining_of_file(un);
15207 
15208 		/*
15209 		 * Can't back space but current file number is known,
15210 		 * So rewind and space from the begining of the partition.
15211 		 */
15212 		} else if (un->un_pos.pmode == legacy) {
15213 			rval = st_scenic_route_to_begining_of_file(un,
15214 			    un->un_pos.fileno);
15215 
15216 		/*
15217 		 * pmode is logical and ST_BSF is not set.
15218 		 * The LONG_POS read position contains the fileno.
15219 		 * If the read position works, rewind and space.
15220 		 */
15221 		} else if (un->un_read_pos_type == LONG_POS) {
15222 			rval = st_cmd(un, SCMD_READ_POSITION, 0, SYNC_CMD);
15223 			if (rval) {
15224 				/*
15225 				 * We didn't get the file position from the
15226 				 * read position command.
15227 				 * We are going to trust the drive to backspace
15228 				 * and then position after the filemark.
15229 				 */
15230 				rval = st_space_to_begining_of_file(un);
15231 			}
15232 			rval = st_interpret_read_pos(un, &un->un_pos, LONG_POS,
15233 			    32, (caddr_t)un->un_read_pos_data, 0);
15234 			if ((rval) && (un->un_pos.pmode == invalid)) {
15235 				rval = st_space_to_begining_of_file(un);
15236 			} else {
15237 				rval = st_scenic_route_to_begining_of_file(un,
15238 				    un->un_pos.fileno);
15239 			}
15240 		} else {
15241 			rval = EIO;
15242 		}
15243 		/*
15244 		 * If something didn't work we are lost
15245 		 */
15246 		if (rval != 0) {
15247 			un->un_pos.pmode = invalid;
15248 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15249 			    "st_mtioctop : EIO : fspace pmode invalid");
15250 
15251 			rval = EIO;
15252 		}
15253 
15254 	} else {
15255 		rval = st_space_fmks(un, count);
15256 	}
15257 
15258 	if (rval != EIO && count < 0) {
15259 		/*
15260 		 * we came here with a count < 0; we now need
15261 		 * to skip back to end up before the filemark
15262 		 */
15263 		rval = st_backward_space_files(un, 1, 1);
15264 	}
15265 
15266 	return (rval);
15267 }
15268 
15269 static int
15270 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
15271 {
15272 	int rval;
15273 
15274 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
15275 
15276 	if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15277 		rval = EIO;
15278 	} else if (st_cmd(un, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
15279 		rval = EIO;
15280 	}
15281 
15282 	return (rval);
15283 }
15284 
15285 static int
15286 st_space_to_begining_of_file(struct scsi_tape *un)
15287 {
15288 	int rval;
15289 
15290 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
15291 
15292 	/*
15293 	 * Back space of the file at the begining of the file.
15294 	 */
15295 	rval = st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
15296 	if (rval) {
15297 		rval = EIO;
15298 		return (rval);
15299 	}
15300 
15301 	/*
15302 	 * Other interesting answers might be crashed BOT which isn't bad.
15303 	 */
15304 	if (un->un_status == SUN_KEY_BOT) {
15305 		return (rval);
15306 	}
15307 
15308 	un->un_running.pmode = invalid;
15309 
15310 	/*
15311 	 * Now we are on the BOP side of the filemark. Forward space to
15312 	 * the EOM side and we are at the begining of the file.
15313 	 */
15314 	rval = st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD);
15315 	if (rval) {
15316 		rval = EIO;
15317 	}
15318 
15319 	return (rval);
15320 }
15321 
15322 static int
15323 st_mtfsr_ioctl(struct scsi_tape *un, int64_t count)
15324 {
15325 
15326 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
15327 
15328 	/*
15329 	 * forward space to inter-record gap
15330 	 *
15331 	 */
15332 
15333 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15334 	    "st_ioctl_fsr: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15335 
15336 	if (un->un_pos.pmode == legacy) {
15337 		/*
15338 		 * If were are at end of tape and count is forward.
15339 		 * Return blank check.
15340 		 */
15341 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
15342 			/* we're at EOM */
15343 			un->un_err_resid = count;
15344 			un->un_status = KEY_BLANK_CHECK;
15345 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15346 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
15347 			return (EIO);
15348 		}
15349 
15350 		/*
15351 		 * If count is zero there is nothing to do.
15352 		 */
15353 		if (count == 0) {
15354 			un->un_err_pos.fileno = un->un_pos.fileno;
15355 			un->un_err_pos.blkno = un->un_pos.blkno;
15356 			un->un_err_resid = 0;
15357 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15358 				un->un_status = SUN_KEY_EOF;
15359 			}
15360 			return (0);
15361 		}
15362 
15363 		/*
15364 		 * physical tape position may not be what we've been
15365 		 * telling the user; adjust the position accordingly
15366 		 */
15367 		if (IN_EOF(un->un_pos)) {
15368 			daddr_t blkno = un->un_pos.blkno;
15369 			int fileno = un->un_pos.fileno;
15370 
15371 			optype lastop = un->un_lastop;
15372 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)
15373 			    == -1) {
15374 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15375 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
15376 				return (EIO);
15377 			}
15378 
15379 			un->un_pos.blkno = blkno;
15380 			un->un_pos.fileno = fileno;
15381 			un->un_lastop = lastop;
15382 		}
15383 	}
15384 
15385 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15386 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15387 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
15388 		return (EIO);
15389 	}
15390 
15391 	return (st_space_records(un, count));
15392 }
15393 
15394 static int
15395 st_space_records(struct scsi_tape *un, int64_t count)
15396 {
15397 	int64_t dblk;
15398 	int rval = 0;
15399 
15400 	ST_FUNC(ST_DEVINFO, st_space_records);
15401 
15402 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15403 	    "st_space_records: count=%"PRIx64", eof=%x\n",
15404 	    count, un->un_pos.eof);
15405 
15406 	if (un->un_pos.pmode == logical) {
15407 		rval = st_cmd(un, SCMD_SPACE, Blk(count), SYNC_CMD);
15408 		if (rval != 0) {
15409 			rval = EIO;
15410 		}
15411 		return (rval);
15412 	}
15413 
15414 	dblk = count + un->un_pos.blkno;
15415 
15416 	/* Already there */
15417 	if (dblk == un->un_pos.blkno) {
15418 		un->un_err_resid = 0;
15419 		COPY_POS(&un->un_err_pos, &un->un_pos);
15420 		return (0);
15421 	}
15422 
15423 	/*
15424 	 * If the destination block is forward
15425 	 * or the drive will backspace records.
15426 	 */
15427 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
15428 		/*
15429 		 * If we're spacing forward, or the device can
15430 		 * backspace records, we can just use the SPACE
15431 		 * command.
15432 		 */
15433 		dblk -= un->un_pos.blkno;
15434 		if (st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15435 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15436 			    "st_space_records:EIO:space_records can't spc");
15437 			rval = EIO;
15438 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
15439 			/*
15440 			 * check if we hit BOT/EOT
15441 			 */
15442 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
15443 				un->un_status = SUN_KEY_BOT;
15444 				un->un_pos.eof = ST_NO_EOF;
15445 			} else if (dblk < 0 &&
15446 			    un->un_pos.eof == ST_EOF_PENDING) {
15447 				int residue = un->un_err_resid;
15448 				/*
15449 				 * we skipped over a filemark
15450 				 * and need to go forward again
15451 				 */
15452 				if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
15453 					ST_DEBUG2(ST_DEVINFO, st_label,
15454 					    SCSI_DEBUG, "st_space_records: EIO"
15455 					    " : can't space #2");
15456 					rval = EIO;
15457 				}
15458 				un->un_err_resid = residue;
15459 			}
15460 			if (rval == 0) {
15461 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15462 				    "st_space_records: EIO : space_rec rval"
15463 				    " == 0");
15464 				rval = EIO;
15465 			}
15466 		}
15467 	} else {
15468 		/*
15469 		 * else we rewind, space forward across filemarks to
15470 		 * the desired file, and then space records to the
15471 		 * desired block.
15472 		 */
15473 
15474 		int dfile = un->un_pos.fileno;	/* save current file */
15475 
15476 		if (dblk < 0) {
15477 			/*
15478 			 * Wups - we're backing up over a filemark
15479 			 */
15480 			if (un->un_pos.blkno != 0 &&
15481 			    (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15482 			    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD))) {
15483 				un->un_pos.pmode = invalid;
15484 			}
15485 			un->un_err_resid = -dblk;
15486 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
15487 				un->un_status = SUN_KEY_BOT;
15488 				un->un_pos.eof = ST_NO_EOF;
15489 			} else if (un->un_pos.fileno > 0) {
15490 				un->un_status = SUN_KEY_EOF;
15491 				un->un_pos.eof = ST_NO_EOF;
15492 			}
15493 			COPY_POS(&un->un_err_pos, &un->un_pos);
15494 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15495 			    "st_space_records:EIO:space_records : dblk < 0");
15496 			rval = EIO;
15497 		} else if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15498 		    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
15499 		    st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15500 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15501 			    "st_space_records: EIO :space_records : rewind "
15502 			    "and space failed");
15503 			un->un_pos.pmode = invalid;
15504 			rval = EIO;
15505 		}
15506 	}
15507 
15508 	return (rval);
15509 }
15510 
15511 static int
15512 st_mtbsf_ioctl(struct scsi_tape *un, int64_t files)
15513 {
15514 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
15515 
15516 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15517 	    "st_mtbsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15518 	/*
15519 	 * backward space of file filemark (1/2" and 8mm)
15520 	 * tape position will end on the beginning of tape side
15521 	 * of the desired file mark
15522 	 */
15523 	if ((un->un_dp->options & ST_BSF) == 0) {
15524 		return (ENOTTY);
15525 	}
15526 
15527 	if (un->un_pos.pmode == legacy) {
15528 
15529 		/*
15530 		 * If a negative count (which implies a forward space op)
15531 		 * is specified, and we're at logical or physical eot,
15532 		 * bounce the request.
15533 		 */
15534 
15535 		if (un->un_pos.eof >= ST_EOT && files < 0) {
15536 			un->un_err_resid = files;
15537 			un->un_status = SUN_KEY_EOT;
15538 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15539 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
15540 			return (EIO);
15541 		}
15542 		/*
15543 		 * physical tape position may not be what we've been
15544 		 * telling the user; adjust the request accordingly
15545 		 */
15546 		if (IN_EOF(un->un_pos)) {
15547 			un->un_pos.fileno++;
15548 			un->un_pos.blkno = 0;
15549 			files++;
15550 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15551 			    "st_mtbsf_ioctl in eof: count=%"PRIx64", op=%x\n",
15552 			    files, MTBSF);
15553 
15554 		}
15555 	}
15556 
15557 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15558 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15559 		    "st_ioctl : EIO : MTBSF : check den wfm");
15560 		return (EIO);
15561 	}
15562 
15563 	if (files <= 0) {
15564 		/*
15565 		 * for a negative count, we need to step forward
15566 		 * first and then step back again
15567 		 */
15568 		files = -files + 1;
15569 		return (st_forward_space_files(un, files));
15570 	}
15571 	return (st_backward_space_files(un, files, 1));
15572 }
15573 
15574 static int
15575 st_backward_space_files(struct scsi_tape *un, int64_t count, int infront)
15576 {
15577 	int64_t end_fileno;
15578 	int64_t skip_cnt;
15579 	int rval = 0;
15580 
15581 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
15582 
15583 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15584 	    "st_backward_space_files: count=%"PRIx64" eof=%x\n",
15585 	    count, un->un_pos.eof);
15586 	/*
15587 	 * Backspace files (MTNBSF): infront == 0
15588 	 *
15589 	 *	For tapes that can backspace, backspace
15590 	 *	count+1 filemarks and then run forward over
15591 	 *	a filemark
15592 	 *
15593 	 *	For tapes that can't backspace,
15594 	 *		calculate desired filenumber
15595 	 *		(un->un_pos.fileno - count), rewind,
15596 	 *		and then space forward this amount
15597 	 *
15598 	 * Backspace filemarks (MTBSF) infront == 1
15599 	 *
15600 	 *	For tapes that can backspace, backspace count
15601 	 *	filemarks
15602 	 *
15603 	 *	For tapes that can't backspace, calculate
15604 	 *	desired filenumber (un->un_pos.fileno - count),
15605 	 *	add 1, rewind, space forward this amount,
15606 	 *	and mark state as ST_EOF_PENDING appropriately.
15607 	 */
15608 
15609 	if (un->un_pos.pmode == logical) {
15610 
15611 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15612 		    "st_backward_space_files: mt_op=%x count=%"PRIx64
15613 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
15614 		    un->un_pos.lgclblkno);
15615 
15616 
15617 		/* In case a drive that won't back space gets in logical mode */
15618 		if ((un->un_dp->options & ST_BSF) == 0) {
15619 			rval = EIO;
15620 			return (rval);
15621 		}
15622 		if ((infront == 1) &&
15623 		    (st_cmd(un, SCMD_SPACE, Fmk(-count), SYNC_CMD))) {
15624 			rval = EIO;
15625 			return (rval);
15626 		} else if ((infront == 0) &&
15627 		    (st_cmd(un, SCMD_SPACE, Fmk((-count)-1), SYNC_CMD)) &&
15628 		    (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
15629 			rval = EIO;
15630 			return (rval);
15631 		}
15632 		return (rval);
15633 	}
15634 
15635 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15636 	    "st_backward_space_files: mt_op=%x count=%"PRIx64
15637 	    "fileno=%x blkno=%x\n",
15638 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
15639 
15640 
15641 
15642 	/*
15643 	 * Handle the simple case of BOT
15644 	 * playing a role in these cmds.
15645 	 * We do this by calculating the
15646 	 * ending file number. If the ending
15647 	 * file is < BOT, rewind and set an
15648 	 * error and mark resid appropriately.
15649 	 * If we're backspacing a file (not a
15650 	 * filemark) and the target file is
15651 	 * the first file on the tape, just
15652 	 * rewind.
15653 	 */
15654 
15655 	/* figure expected destination of this SPACE command */
15656 	end_fileno = un->un_pos.fileno - count;
15657 
15658 	/*
15659 	 * Would the end effect of this SPACE be the same as rewinding?
15660 	 * If so just rewind instead.
15661 	 */
15662 	if ((infront != 0) && (end_fileno < 0) ||
15663 	    (infront == 0) && (end_fileno <= 0)) {
15664 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15665 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15666 			    "st_backward_space_files: EIO : "
15667 			    "rewind in lou of BSF failed\n");
15668 			rval = EIO;
15669 		}
15670 		if (end_fileno < 0) {
15671 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15672 			    "st_backward_space_files: EIO : "
15673 			    "back space file greater then fileno\n");
15674 			rval = EIO;
15675 			un->un_err_resid = -end_fileno;
15676 			un->un_status = SUN_KEY_BOT;
15677 		}
15678 		return (rval);
15679 	}
15680 
15681 	if (un->un_dp->options & ST_BSF) {
15682 		skip_cnt = 1 - infront;
15683 		/*
15684 		 * If we are going to end up at the beginning
15685 		 * of the file, we have to space one extra file
15686 		 * first, and then space forward later.
15687 		 */
15688 		end_fileno = -(count + skip_cnt);
15689 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15690 		    "skip_cnt=%"PRIx64", tmp=%"PRIx64"\n",
15691 		    skip_cnt, end_fileno);
15692 		if (st_cmd(un, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
15693 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15694 			    "st_backward_space_files:EIO:back space fm failed");
15695 			rval = EIO;
15696 		}
15697 	} else {
15698 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15699 			rval = EIO;
15700 		} else {
15701 			skip_cnt = end_fileno + infront;
15702 		}
15703 	}
15704 
15705 	/*
15706 	 * If we have to space forward, do so...
15707 	 */
15708 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15709 	    "space forward skip_cnt=%"PRIx64", rval=%x\n", skip_cnt, rval);
15710 
15711 	if (rval == 0 && skip_cnt) {
15712 		if (st_cmd(un, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
15713 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15714 			    "st_backward_space_files:EIO:space fm skip count");
15715 			rval = EIO;
15716 		} else if (infront) {
15717 			/*
15718 			 * If we had to space forward, and we're
15719 			 * not a tape that can backspace, mark state
15720 			 * as if we'd just seen a filemark during a
15721 			 * a read.
15722 			 */
15723 			if ((un->un_dp->options & ST_BSF) == 0) {
15724 				un->un_pos.eof = ST_EOF_PENDING;
15725 				un->un_pos.fileno -= 1;
15726 				un->un_pos.blkno = LASTBLK;
15727 				un->un_running.pmode = invalid;
15728 			}
15729 		}
15730 	}
15731 
15732 	if (rval != 0) {
15733 		un->un_pos.pmode = invalid;
15734 	}
15735 
15736 	return (rval);
15737 }
15738 
15739 static int
15740 st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count)
15741 {
15742 	int rval;
15743 
15744 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
15745 
15746 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15747 	    "nbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15748 
15749 	if (un->un_pos.pmode == legacy) {
15750 		/*
15751 		 * backward space file to beginning of file
15752 		 *
15753 		 * If a negative count (which implies a forward space op)
15754 		 * is specified, and we're at logical or physical eot,
15755 		 * bounce the request.
15756 		 */
15757 
15758 		if (un->un_pos.eof >= ST_EOT && count < 0) {
15759 			un->un_err_resid = count;
15760 			un->un_status = SUN_KEY_EOT;
15761 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15762 			    "st_ioctl : EIO : > EOT and count < 0");
15763 			return (EIO);
15764 		}
15765 		/*
15766 		 * physical tape position may not be what we've been
15767 		 * telling the user; adjust the request accordingly
15768 		 */
15769 		if (IN_EOF(un->un_pos)) {
15770 			un->un_pos.fileno++;
15771 			un->un_pos.blkno = 0;
15772 			count++;
15773 		}
15774 	}
15775 
15776 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15777 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15778 		    "st_ioctl : EIO : MTNBSF check den and wfm");
15779 		return (EIO);
15780 	}
15781 
15782 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15783 	    "mtnbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15784 
15785 	if (count <= 0) {
15786 		rval = st_forward_space_files(un, -count);
15787 	} else {
15788 		rval = st_backward_space_files(un, count, 0);
15789 	}
15790 	return (rval);
15791 }
15792 
15793 static int
15794 st_mtbsr_ioctl(struct scsi_tape *un, int64_t num)
15795 {
15796 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
15797 
15798 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15799 	    "bsr: count=%"PRIx64", eof=%x\n", num, un->un_pos.eof);
15800 
15801 	if (un->un_pos.pmode == legacy) {
15802 		/*
15803 		 * backward space into inter-record gap
15804 		 *
15805 		 * If a negative count (which implies a forward space op)
15806 		 * is specified, and we're at logical or physical eot,
15807 		 * bounce the request.
15808 		 */
15809 		if (un->un_pos.eof >= ST_EOT && num < 0) {
15810 			un->un_err_resid = num;
15811 			un->un_status = SUN_KEY_EOT;
15812 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15813 			    "st_ioctl : EIO : MTBSR > EOT");
15814 			return (EIO);
15815 		}
15816 
15817 		if (num == 0) {
15818 			COPY_POS(&un->un_err_pos, &un->un_pos);
15819 			un->un_err_resid = 0;
15820 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15821 				un->un_status = SUN_KEY_EOF;
15822 			}
15823 			return (0);
15824 		}
15825 
15826 		/*
15827 		 * physical tape position may not be what we've been
15828 		 * telling the user; adjust the position accordingly.
15829 		 * bsr can not skip filemarks and continue to skip records
15830 		 * therefore if we are logically before the filemark but
15831 		 * physically at the EOT side of the filemark, we need to step
15832 		 * back; this allows fsr N where N > number of blocks in file
15833 		 * followed by bsr 1 to position at the beginning of last block
15834 		 */
15835 		if (IN_EOF(un->un_pos)) {
15836 			tapepos_t save;
15837 			optype lastop = un->un_lastop;
15838 
15839 			COPY_POS(&save, &un->un_pos);
15840 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD) == -1) {
15841 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15842 				    "st_mtbsr_ioctl: EIO : MTBSR can't space");
15843 				return (EIO);
15844 			}
15845 
15846 			COPY_POS(&un->un_pos, &save);
15847 			un->un_lastop = lastop;
15848 		}
15849 	}
15850 
15851 	un->un_pos.eof = ST_NO_EOF;
15852 
15853 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15854 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15855 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
15856 		return (EIO);
15857 	}
15858 
15859 	num = -num;
15860 	return (st_space_records(un, num));
15861 }
15862 
15863 static int
15864 st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt)
15865 {
15866 	int rval;
15867 
15868 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
15869 
15870 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
15871 	if (rval == 0) {
15872 		un->un_pos.pmode = logical;
15873 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15874 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15875 		/*
15876 		 * Drive says invalid field in cdb.
15877 		 * Doesn't like space multiple. Position isn't lost.
15878 		 */
15879 		un->un_err_resid = cnt;
15880 		un->un_status = 0;
15881 		rval = ENOTTY;
15882 	} else {
15883 		un->un_err_resid = cnt;
15884 		un->un_pos.pmode = invalid;
15885 	}
15886 	return (rval);
15887 }
15888 
15889 static int
15890 st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt)
15891 {
15892 	int rval;
15893 
15894 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
15895 
15896 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
15897 	if (rval == 0) {
15898 		un->un_pos.pmode = logical;
15899 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15900 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15901 		/*
15902 		 * Drive says invalid field in cdb.
15903 		 * Doesn't like space multiple. Position isn't lost.
15904 		 */
15905 		un->un_err_resid = cnt;
15906 		un->un_status = 0;
15907 		rval = ENOTTY;
15908 	} else {
15909 		un->un_err_resid = cnt;
15910 		un->un_pos.pmode = invalid;
15911 	}
15912 	return (rval);
15913 }
15914 
15915 #ifdef	__x86
15916 
15917 /*
15918  * release contig_mem and wake up waiting thread, if any
15919  */
15920 static void
15921 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
15922 {
15923 	mutex_enter(ST_MUTEX);
15924 
15925 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
15926 
15927 	cp->cm_next = un->un_contig_mem;
15928 	un->un_contig_mem = cp;
15929 	un->un_contig_mem_available_num++;
15930 	cv_broadcast(&un->un_contig_mem_cv);
15931 
15932 	mutex_exit(ST_MUTEX);
15933 }
15934 
15935 /*
15936  * St_get_contig_mem will return a contig_mem if there is one available
15937  * in current system. Otherwise, it will try to alloc one, if the total
15938  * number of contig_mem is within st_max_contig_mem_num.
15939  * It will sleep, if allowed by caller or return NULL, if no contig_mem
15940  * is available for now.
15941  */
15942 static struct contig_mem *
15943 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
15944 {
15945 	size_t rlen;
15946 	struct contig_mem *cp = NULL;
15947 	ddi_acc_handle_t acc_hdl;
15948 	caddr_t addr;
15949 	int big_enough = 0;
15950 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
15951 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
15952 
15953 	/* Try to get one available contig_mem */
15954 	mutex_enter(ST_MUTEX);
15955 
15956 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
15957 
15958 	if (un->un_contig_mem_available_num > 0) {
15959 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15960 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
15961 		/*
15962 		 * we failed to get one. we're going to
15963 		 * alloc one more contig_mem for this I/O
15964 		 */
15965 		mutex_exit(ST_MUTEX);
15966 		cp = (struct contig_mem *)kmem_zalloc(
15967 		    sizeof (struct contig_mem) + biosize(),
15968 		    alloc_flags);
15969 		if (cp == NULL) {
15970 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15971 			    "alloc contig_mem failure\n");
15972 			return (NULL); /* cannot get one */
15973 		}
15974 		cp->cm_bp = (struct buf *)
15975 		    (((caddr_t)cp) + sizeof (struct contig_mem));
15976 		bioinit(cp->cm_bp);
15977 		mutex_enter(ST_MUTEX);
15978 		un->un_contig_mem_total_num++; /* one more available */
15979 	} else {
15980 		/*
15981 		 * we failed to get one and we're NOT allowed to
15982 		 * alloc more contig_mem
15983 		 */
15984 		if (alloc_flags == KM_SLEEP) {
15985 			while (un->un_contig_mem_available_num <= 0) {
15986 				cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
15987 			}
15988 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15989 		} else {
15990 			mutex_exit(ST_MUTEX);
15991 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15992 			    "alloc contig_mem failure\n");
15993 			return (NULL); /* cannot get one */
15994 		}
15995 	}
15996 	mutex_exit(ST_MUTEX);
15997 
15998 	/* We need to check if this block of mem is big enough for this I/O */
15999 	if (cp->cm_len < len) {
16000 		/* not big enough, need to alloc a new one */
16001 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
16002 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
16003 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
16004 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16005 			    "alloc contig_mem failure: not enough mem\n");
16006 			st_release_contig_mem(un, cp);
16007 			cp = NULL;
16008 		} else {
16009 			if (cp->cm_addr) {
16010 				/* release previous one before attach new one */
16011 				ddi_dma_mem_free(&cp->cm_acc_hdl);
16012 			}
16013 			mutex_enter(ST_MUTEX);
16014 			un->un_max_contig_mem_len =
16015 			    un->un_max_contig_mem_len >= len ?
16016 			    un->un_max_contig_mem_len : len;
16017 			mutex_exit(ST_MUTEX);
16018 
16019 			/* attach new mem to this cp */
16020 			cp->cm_addr = addr;
16021 			cp->cm_acc_hdl = acc_hdl;
16022 			cp->cm_len = len;
16023 
16024 			goto alloc_ok; /* get one usable cp */
16025 		}
16026 	} else {
16027 		goto alloc_ok; /* get one usable cp */
16028 	}
16029 
16030 	/* cannot find/alloc a usable cp, when we get here */
16031 
16032 	mutex_enter(ST_MUTEX);
16033 	if ((un->un_max_contig_mem_len < len) ||
16034 	    (alloc_flags != KM_SLEEP)) {
16035 		mutex_exit(ST_MUTEX);
16036 		return (NULL);
16037 	}
16038 
16039 	/*
16040 	 * we're allowed to sleep, and there is one big enough
16041 	 * contig mem in the system, which is currently in use,
16042 	 * wait for it...
16043 	 */
16044 	big_enough = 1;
16045 	do {
16046 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16047 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16048 	} while (cp == NULL);
16049 	mutex_exit(ST_MUTEX);
16050 
16051 	/* we get the big enough contig mem, finally */
16052 
16053 alloc_ok:
16054 	/* init bp attached to this cp */
16055 	bioreset(cp->cm_bp);
16056 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
16057 	cp->cm_bp->b_private = (void *)cp;
16058 
16059 	return (cp);
16060 }
16061 
16062 /*
16063  * this is the biodone func for the bp used in big block I/O
16064  */
16065 static int
16066 st_bigblk_xfer_done(struct buf *bp)
16067 {
16068 	struct contig_mem *cp;
16069 	struct buf *orig_bp;
16070 	int ioerr;
16071 	struct scsi_tape *un;
16072 
16073 	/* sanity check */
16074 	if (bp == NULL) {
16075 		return (DDI_FAILURE);
16076 	}
16077 
16078 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16079 	if (un == NULL) {
16080 		return (DDI_FAILURE);
16081 	}
16082 
16083 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
16084 
16085 	cp = (struct contig_mem *)bp->b_private;
16086 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
16087 	cp->cm_bp = bp;
16088 
16089 	/* special handling for special I/O */
16090 	if (cp->cm_use_sbuf) {
16091 #ifndef __lock_lint
16092 		ASSERT(un->un_sbuf_busy);
16093 #endif
16094 		un->un_sbufp = orig_bp;
16095 		cp->cm_use_sbuf = 0;
16096 	}
16097 
16098 	orig_bp->b_resid = bp->b_resid;
16099 	ioerr = geterror(bp);
16100 	if (ioerr != 0) {
16101 		bioerror(orig_bp, ioerr);
16102 	} else if (orig_bp->b_flags & B_READ) {
16103 		/* copy data back to original bp */
16104 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
16105 		    bp->b_bcount - bp->b_resid);
16106 	}
16107 
16108 	st_release_contig_mem(un, cp);
16109 
16110 	biodone(orig_bp);
16111 
16112 	return (DDI_SUCCESS);
16113 }
16114 
16115 /*
16116  * We use this func to replace original bp that may not be able to do I/O
16117  * in big block size with one that can
16118  */
16119 static struct buf *
16120 st_get_bigblk_bp(struct buf *bp)
16121 {
16122 	struct contig_mem *cp;
16123 	struct scsi_tape *un;
16124 	struct buf *cont_bp;
16125 
16126 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16127 	if (un == NULL) {
16128 		return (bp);
16129 	}
16130 
16131 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
16132 
16133 	/* try to get one contig_mem */
16134 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
16135 	if (!cp) {
16136 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
16137 		    "Cannot alloc contig buf for I/O for %lu blk size",
16138 		    bp->b_bcount);
16139 		return (bp);
16140 	}
16141 	cont_bp = cp->cm_bp;
16142 	cp->cm_bp = bp;
16143 
16144 	/* make sure that we "are" using un_sbufp for special I/O */
16145 	if (bp == un->un_sbufp) {
16146 #ifndef __lock_lint
16147 		ASSERT(un->un_sbuf_busy);
16148 #endif
16149 		un->un_sbufp = cont_bp;
16150 		cp->cm_use_sbuf = 1;
16151 	}
16152 
16153 	/* clone bp */
16154 	cont_bp->b_bcount = bp->b_bcount;
16155 	cont_bp->b_resid = bp->b_resid;
16156 	cont_bp->b_iodone = st_bigblk_xfer_done;
16157 	cont_bp->b_file = bp->b_file;
16158 	cont_bp->b_offset = bp->b_offset;
16159 	cont_bp->b_dip = bp->b_dip;
16160 	cont_bp->b_error = 0;
16161 	cont_bp->b_proc = NULL;
16162 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
16163 	cont_bp->b_shadow = NULL;
16164 	cont_bp->b_pages = NULL;
16165 	cont_bp->b_edev = bp->b_edev;
16166 	cont_bp->b_dev = bp->b_dev;
16167 	cont_bp->b_lblkno = bp->b_lblkno;
16168 	cont_bp->b_forw = bp->b_forw;
16169 	cont_bp->b_back = bp->b_back;
16170 	cont_bp->av_forw = bp->av_forw;
16171 	cont_bp->av_back = bp->av_back;
16172 	cont_bp->b_bufsize = bp->b_bufsize;
16173 
16174 	/* get data in original bp */
16175 	if (bp->b_flags & B_WRITE) {
16176 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
16177 	}
16178 
16179 	return (cont_bp);
16180 }
16181 #else
16182 #ifdef __lock_lint
16183 static int
16184 st_bigblk_xfer_done(struct buf *bp)
16185 {
16186 	return (0);
16187 }
16188 #endif
16189 #endif
16190 
16191 static const char *eof_status[] =
16192 {
16193 	"NO_EOF",
16194 	"EOF_PENDING",
16195 	"EOF",
16196 	"EOT_PENDING",
16197 	"EOT",
16198 	"EOM",
16199 	"AFTER_EOM"
16200 };
16201 static const char *mode[] = {
16202 	"invalid",
16203 	"legacy",
16204 	"logical"
16205 };
16206 
16207 static void
16208 st_print_position(dev_info_t *dev, char *label, uint_t level,
16209 const char *comment, tapepos_t *pos)
16210 {
16211 	ST_FUNC(dev, st_print_position);
16212 
16213 	scsi_log(dev, label, level,
16214 	    "%s Position data:\n", comment);
16215 	scsi_log(dev, label, CE_CONT,
16216 	    "Positioning mode = %s", mode[pos->pmode]);
16217 	scsi_log(dev, label, CE_CONT,
16218 	    "End Of File/Tape = %s", eof_status[pos->eof]);
16219 	scsi_log(dev, label, CE_CONT,
16220 	    "File Number      = 0x%x", pos->fileno);
16221 	scsi_log(dev, label, CE_CONT,
16222 	    "Block Number     = 0x%x", pos->blkno);
16223 	scsi_log(dev, label, CE_CONT,
16224 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
16225 	scsi_log(dev, label, CE_CONT,
16226 	    "Partition Number = 0x%x", pos->partition);
16227 }
16228 static int
16229 st_check_if_media_changed(struct scsi_tape *un, caddr_t data, int size)
16230 {
16231 
16232 	int result = 0;
16233 	int i;
16234 	ST_FUNC(ST_DEVINFO, st_check_if_media_changed);
16235 
16236 	/*
16237 	 * find non alpha numeric working from the end.
16238 	 */
16239 	for (i = size - 1; i >= 0; i--) {
16240 		if (ISALNUM(data[i]) == 0 || data[i] == ' ') {
16241 			data[i] = 0;
16242 			size = i;
16243 		}
16244 	}
16245 
16246 	if (size == 1) {
16247 		/*
16248 		 * Drive seems to think its returning useful data
16249 		 * but it looks like all junk
16250 		 */
16251 		return (result);
16252 	}
16253 
16254 	size++;
16255 
16256 	/*
16257 	 * Actually got a valid serial number.
16258 	 * If never stored one before alloc space for it.
16259 	 */
16260 	if (un->un_media_id_len == 0) {
16261 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16262 		un->un_media_id_len = size;
16263 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16264 		un->un_media_id[min(size, strlen(data))] = 0;
16265 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16266 		    "Found Media Id %s length = %d\n", un->un_media_id, size);
16267 	} else if (size > un->un_media_id_len) {
16268 		if (strncmp(un->un_media_id, data, size) != 0) {
16269 			result = ESPIPE;
16270 		}
16271 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16272 		    "Longer Media Id old ID:%s new ID:%s\n",
16273 		    un->un_media_id, data);
16274 		kmem_free(un->un_media_id, un->un_media_id_len);
16275 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16276 		un->un_media_id_len = size;
16277 		(void) strncpy(un->un_media_id, data, size);
16278 		un->un_media_id[size] = 0;
16279 	} else if (strncmp(data, un->un_media_id,
16280 	    min(size, un->un_media_id_len)) != 0) {
16281 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16282 		    "Old Media Id %s length = %d New %s length = %d\n",
16283 		    un->un_media_id, un->un_media_id_len, data, size);
16284 		bzero(un->un_media_id, un->un_media_id_len);
16285 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16286 		un->un_media_id[min(size, strlen(data))] = 0;
16287 		result = ESPIPE;
16288 	} else {
16289 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
16290 		    "Media Id still %s\n", un->un_media_id);
16291 	}
16292 
16293 	ASSERT(strlen(un->un_media_id) <= size);
16294 
16295 	return (result);
16296 }
16297 #define	ID_SIZE 32
16298 typedef struct
16299 {
16300 	uchar_t avilable_data0;
16301 	uchar_t avilable_data1;
16302 	uchar_t avilable_data2;
16303 	uchar_t avilable_data3;
16304 	uchar_t attribute_msb;
16305 	uchar_t attribute_lsb;
16306 #ifdef _BIT_FIELDS_LTOH
16307 	uchar_t format		: 2,
16308 				: 5,
16309 		read_only	: 1;
16310 #else
16311 	uchar_t read_only	: 1,
16312 				: 5,
16313 		format		: 2;
16314 #endif
16315 	uchar_t attribute_len_msb;
16316 	uchar_t attribute_len_lsb;
16317 }attribute_header;
16318 
16319 typedef struct {
16320 	attribute_header header;
16321 	char data[1];
16322 }mam_attribute;
16323 
16324 static int
16325 st_handle_hex_media_id(struct scsi_tape *un, void *pnt, int size)
16326 {
16327 	int result;
16328 	int newsize = (size << 1) + 3; /* extra for leading 0x and null term */
16329 	int i;
16330 	uchar_t byte;
16331 	char *format;
16332 	uchar_t *data = (uchar_t *)pnt;
16333 	char *buf = kmem_alloc(newsize, KM_SLEEP);
16334 
16335 	ST_FUNC(ST_DEVINFO, st_handle_hex_media_id);
16336 
16337 	(void) sprintf(buf, "0x");
16338 	for (i = 0; i < size; i++) {
16339 		byte = data[i];
16340 		if (byte < 0x10)
16341 			format = "0%x";
16342 		else
16343 			format = "%x";
16344 		(void) sprintf(&buf[(int)strlen(buf)], format, byte);
16345 	}
16346 	result = st_check_if_media_changed(un, buf, newsize);
16347 
16348 	kmem_free(buf, newsize);
16349 
16350 	return (result);
16351 }
16352 
16353 
16354 static int
16355 st_get_media_id_via_read_attribute(struct scsi_tape *un, ubufunc_t bufunc)
16356 {
16357 	int result;
16358 	mam_attribute *buffer;
16359 	int size;
16360 	int newsize;
16361 
16362 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_read_attribute);
16363 	size = sizeof (attribute_header) + max(un->un_media_id_len, ID_SIZE);
16364 again:
16365 	buffer = kmem_zalloc(size, KM_SLEEP);
16366 	result = st_read_attributes(un, 0x0401, buffer, size, bufunc);
16367 	if (result == 0) {
16368 
16369 		newsize = (buffer->header.attribute_len_msb << 8) |
16370 		    buffer->header.attribute_len_lsb;
16371 
16372 		if (newsize + sizeof (attribute_header) > size) {
16373 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
16374 			    "resizing read attribute data from %d to %d format"
16375 			    " %d\n", size, (int)sizeof (attribute_header) +
16376 			    newsize, buffer->header.format);
16377 			kmem_free(buffer, size);
16378 			size = newsize + sizeof (attribute_header);
16379 			goto again;
16380 		}
16381 
16382 		un->un_media_id_method = st_get_media_id_via_read_attribute;
16383 		if (buffer->header.format == 0) {
16384 			result =
16385 			    st_handle_hex_media_id(un, buffer->data, newsize);
16386 		} else {
16387 			result = st_check_if_media_changed(un, buffer->data,
16388 			    newsize);
16389 		}
16390 	} else if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
16391 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
16392 		    "Read Attribute Command for Media Identification is not "
16393 		    "supported on the HBA that this drive is attached to.");
16394 		result = ENOTTY;
16395 	}
16396 
16397 	kmem_free(buffer, size);
16398 	un->un_status = 0;
16399 
16400 	return (result);
16401 }
16402 
16403 
16404 static int
16405 st_get_media_id_via_media_serial_cmd(struct scsi_tape *un, ubufunc_t bufunc)
16406 {
16407 	char cdb[CDB_GROUP5];
16408 	struct uscsi_cmd *ucmd;
16409 	struct scsi_extended_sense sense;
16410 	int rval;
16411 	int size = max(un->un_media_id_len, ID_SIZE);
16412 	caddr_t buf;
16413 
16414 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_media_serial_cmd);
16415 
16416 	if (un->un_sd->sd_inq->inq_ansi < 3) {
16417 		return (ENOTTY);
16418 	}
16419 
16420 	ucmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
16421 upsize:
16422 	buf = kmem_alloc(size, KM_SLEEP);
16423 
16424 	cdb[0] = (char)SCMD_SVC_ACTION_IN_G5;
16425 	cdb[1] = SSVC_ACTION_READ_MEDIA_SERIAL;
16426 	cdb[2] = 0;
16427 	cdb[3] = 0;
16428 	cdb[4] = 0;
16429 	cdb[5] = 0;
16430 	cdb[6] = (char)(size >> 24);
16431 	cdb[7] = (char)(size >> 16);
16432 	cdb[8] = (char)(size >> 8);
16433 	cdb[9] = (char)(size);
16434 	cdb[10] = 0;
16435 	cdb[11] = 0;
16436 
16437 	ucmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
16438 	ucmd->uscsi_timeout = un->un_dp->non_motion_timeout;
16439 	ucmd->uscsi_cdb = &cdb[0];
16440 	ucmd->uscsi_cdblen = sizeof (cdb);
16441 	ucmd->uscsi_bufaddr = buf;
16442 	ucmd->uscsi_buflen = size;
16443 	ucmd->uscsi_rqbuf = (caddr_t)&sense;
16444 	ucmd->uscsi_rqlen = sizeof (sense);
16445 
16446 	rval = bufunc(un, ucmd, FKIOCTL);
16447 
16448 	if (rval || ucmd->uscsi_status != 0) {
16449 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16450 		    "media serial command returned %d scsi_status %d"
16451 		    " rqstatus %d", rval, ucmd->uscsi_status,
16452 		    ucmd->uscsi_rqstatus);
16453 		/*
16454 		 * If this returns invalid operation code don't try again.
16455 		 */
16456 		if (sense.es_key == KEY_ILLEGAL_REQUEST &&
16457 		    sense.es_add_code == 0x20) {
16458 			rval = ENOTTY;
16459 		} else if (rval == 0) {
16460 			rval = EIO;
16461 		}
16462 		un->un_status = 0;
16463 	} else {
16464 		int act_size;
16465 
16466 		/*
16467 		 * get reported size.
16468 		 */
16469 		act_size = (int)buf[3] | (int)(buf[2] << 8) |
16470 		    (int)(buf[1] << 16) | (int)(buf[0] << 24);
16471 
16472 		/* documentation says mod 4. */
16473 		while (act_size & 3) {
16474 			act_size++;
16475 		}
16476 
16477 		/*
16478 		 * If reported size is larger that we our buffer.
16479 		 * Free the old one and allocate one that is larger
16480 		 * enough and re-issuse the command.
16481 		 */
16482 		if (act_size + 4 > size) {
16483 			kmem_free(buf, size);
16484 			size = act_size + 4;
16485 			goto upsize;
16486 		}
16487 
16488 		if (act_size == 0) {
16489 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16490 			    "media serial number is not available");
16491 			un->un_status = 0;
16492 			rval = 0;
16493 		} else {
16494 			/*
16495 			 * set data pointer to point to the start
16496 			 * of that serial number.
16497 			 */
16498 			un->un_media_id_method =
16499 			    st_get_media_id_via_media_serial_cmd;
16500 			rval =
16501 			    st_check_if_media_changed(un, &buf[4], act_size);
16502 		}
16503 	}
16504 
16505 	kmem_free(ucmd, sizeof (struct uscsi_cmd));
16506 	kmem_free(buf, size);
16507 
16508 	return (rval);
16509 }
16510 
16511 
16512 /* ARGSUSED */
16513 static int
16514 st_bogus_media_id(struct scsi_tape *un, ubufunc_t bufunc)
16515 {
16516 	ST_FUNC(ST_DEVINFO, st_bogus_media_id);
16517 
16518 	ASSERT(un->un_media_id == NULL || un->un_media_id == bogusID);
16519 	ASSERT(un->un_media_id_len == 0);
16520 	un->un_media_id = (char *)bogusID;
16521 	un->un_media_id_len = 0;
16522 	return (0);
16523 }
16524 
16525 typedef int (*media_chk_function)(struct scsi_tape *, ubufunc_t bufunc);
16526 
16527 media_chk_function media_chk_functions[] = {
16528 	st_get_media_id_via_media_serial_cmd,
16529 	st_get_media_id_via_read_attribute,
16530 	st_bogus_media_id
16531 };
16532 
16533 static int
16534 st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc)
16535 {
16536 	int result = 0;
16537 	int i;
16538 
16539 	ST_FUNC(ST_DEVINFO, st_get_media_identification);
16540 
16541 	for (i = 0; i < ST_NUM_MEMBERS(media_chk_functions); i++) {
16542 		if (result == ENOTTY) {
16543 			/*
16544 			 * Last operation type not supported by this device.
16545 			 * Make so next time it doesn`t do that again.
16546 			 */
16547 			un->un_media_id_method = media_chk_functions[i];
16548 		} else if (un->un_media_id_method != media_chk_functions[i] &&
16549 		    un->un_media_id_method != st_get_media_identification) {
16550 			continue;
16551 		}
16552 		result = media_chk_functions[i](un, bufunc);
16553 		/*
16554 		 * If result indicates the function was successful or
16555 		 * that the media is not the same as last known, break.
16556 		 */
16557 		if (result == 0 || result == ESPIPE) {
16558 			break;
16559 		}
16560 	}
16561 
16562 	return (result);
16563 }
16564 
16565 static errstate
16566 st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
16567     errstate onentry)
16568 {
16569 
16570 	int ret;
16571 	st_err_info *errinfo;
16572 	recov_info *ri = (recov_info *)pkt->pkt_private;
16573 
16574 	ST_FUNC(ST_DEVINFO, st_command_recovery);
16575 
16576 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16577 
16578 	ASSERT(un->un_recov_buf_busy == 0);
16579 
16580 	/*
16581 	 * Don't try and recover a reset that this device sent.
16582 	 */
16583 	if (un->un_rsvd_status & ST_INITIATED_RESET &&
16584 	    onentry == DEVICE_RESET) {
16585 		return (COMMAND_DONE_ERROR);
16586 	}
16587 
16588 	/*
16589 	 * See if expected position was passed with scsi_pkt.
16590 	 */
16591 	if (ri->privatelen == sizeof (recov_info)) {
16592 
16593 		/*
16594 		 * Not for this command.
16595 		 */
16596 		if (ri->cmd_attrib->do_not_recover) {
16597 			return (COMMAND_DONE_ERROR);
16598 		}
16599 
16600 		/*
16601 		 * Create structure to hold all error state info.
16602 		 */
16603 		errinfo = kmem_zalloc(ST_ERR_INFO_SIZE, KM_SLEEP);
16604 		errinfo->ei_error_type = onentry;
16605 		errinfo->ei_failing_bp = ri->cmd_bp;
16606 		COPY_POS(&errinfo->ei_expected_pos, &ri->pos);
16607 	} else {
16608 		/* disabled */
16609 		return (COMMAND_DONE_ERROR);
16610 	}
16611 
16612 	bcopy(pkt, &errinfo->ei_failed_pkt, scsi_pkt_size());
16613 	bcopy(pkt->pkt_scbp, &errinfo->ei_failing_status, SECMDS_STATUS_SIZE);
16614 	ret = ddi_taskq_dispatch(un->un_recov_taskq, st_recover, errinfo,
16615 	    DDI_NOSLEEP);
16616 	ASSERT(ret == DDI_SUCCESS);
16617 	if (ret != DDI_SUCCESS) {
16618 		kmem_free(errinfo, ST_ERR_INFO_SIZE);
16619 		return (COMMAND_DONE_ERROR);
16620 	}
16621 	return (JUST_RETURN); /* release calling thread */
16622 }
16623 
16624 
16625 static void
16626 st_recov_ret(struct scsi_tape *un, st_err_info *errinfo, errstate err)
16627 {
16628 	int error_number;
16629 	buf_t *bp;
16630 
16631 
16632 	ST_FUNC(ST_DEVINFO, st_recov_ret);
16633 
16634 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16635 #if !defined(lint)
16636 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
16637 #endif
16638 
16639 	bp = errinfo->ei_failing_bp;
16640 	kmem_free(errinfo, ST_ERR_INFO_SIZE);
16641 
16642 	switch (err) {
16643 	case JUST_RETURN:
16644 		mutex_exit(&un->un_sd->sd_mutex);
16645 		return;
16646 
16647 	case COMMAND_DONE:
16648 	case COMMAND_DONE_ERROR_RECOVERED:
16649 		ST_DO_KSTATS(bp, kstat_runq_exit);
16650 		error_number = 0;
16651 		break;
16652 
16653 	default:
16654 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16655 		    "st_recov_ret with unhandled errstat %d\n", err);
16656 		/* FALLTHROUGH */
16657 	case COMMAND_DONE_ERROR:
16658 	case COMMAND_DONE_EACCES:
16659 		ST_DO_KSTATS(bp, kstat_waitq_exit);
16660 		ST_DO_ERRSTATS(un, st_transerrs);
16661 		error_number = EIO;
16662 		st_set_pe_flag(un);
16663 		break;
16664 
16665 	}
16666 
16667 	st_bioerror(bp, error_number);
16668 	st_done_and_mutex_exit(un, bp);
16669 }
16670 
16671 
16672 static void
16673 st_recover(void *arg)
16674 {
16675 	st_err_info *const errinfo = (st_err_info *)arg;
16676 	uchar_t com = errinfo->ei_failed_pkt.pkt_cdbp[0];
16677 	struct scsi_tape *un;
16678 	tapepos_t cur_pos;
16679 	int rval;
16680 	errstate status = COMMAND_DONE_ERROR;
16681 	recov_info *rcv;
16682 	buf_t *bp;
16683 
16684 
16685 	rcv = errinfo->ei_failed_pkt.pkt_private;
16686 	ASSERT(rcv->privatelen == sizeof (recov_info));
16687 	bp = rcv->cmd_bp;
16688 
16689 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16690 
16691 	ASSERT(un != NULL);
16692 
16693 	mutex_enter(ST_MUTEX);
16694 
16695 	ST_FUNC(ST_DEVINFO, st_recover);
16696 
16697 	ST_CDB(ST_DEVINFO, "Recovering command",
16698 	    (caddr_t)errinfo->ei_failed_pkt.pkt_cdbp);
16699 	ST_SENSE(ST_DEVINFO, "sense status for failed command",
16700 	    (caddr_t)&errinfo->ei_failing_status,
16701 	    sizeof (struct scsi_arq_status));
16702 	ST_POS(ST_DEVINFO, rcv->cmd_attrib->recov_pos_type == POS_STARTING ?
16703 	    "starting position for recovery command" :
16704 	    "expected position for recovery command",
16705 	    &errinfo->ei_expected_pos);
16706 
16707 	rval = st_test_path_to_device(un);
16708 
16709 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16710 	    "st_recover called with %s, TUR returned %d\n",
16711 	    errstatenames[errinfo->ei_error_type], rval);
16712 	/*
16713 	 * If the drive responed to the TUR lets try and get it to sync
16714 	 * any data it might have in the buffer.
16715 	 */
16716 	if (rval == 0 && rcv->cmd_attrib->chg_tape_data) {
16717 		(void) st_rcmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
16718 	}
16719 	switch (errinfo->ei_error_type) {
16720 	case ATTEMPT_RETRY:
16721 	case COMMAND_TIMEOUT:
16722 	case DEVICE_RESET:
16723 	case PATH_FAILED:
16724 		/*
16725 		 * For now if we can't talk to the device we are done.
16726 		 * If the drive is reserved we can try to get it back.
16727 		 */
16728 		if (rval != 0 && rval != EACCES) {
16729 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16730 			return;
16731 		}
16732 
16733 		/*
16734 		 * If scsi II lost reserve try and get it back.
16735 		 */
16736 		if ((((un->un_rsvd_status &
16737 		    (ST_LOST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
16738 		    ST_LOST_RESERVE)) &&
16739 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] != SCMD_RELEASE)) {
16740 			rval = st_reserve_release(un, ST_RESERVE,
16741 			    st_uscsi_rcmd);
16742 			if (rval != 0) {
16743 				if (st_take_ownership(un, st_uscsi_rcmd) != 0) {
16744 					st_recov_ret(un, errinfo,
16745 					    COMMAND_DONE_EACCES);
16746 					return;
16747 				}
16748 			}
16749 			un->un_rsvd_status |= ST_RESERVE;
16750 			un->un_rsvd_status &= ~(ST_RELEASE | ST_LOST_RESERVE |
16751 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
16752 		}
16753 		rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16754 		if (rval) {
16755 			rval = st_gen_mode_select(un, st_uscsi_rcmd,
16756 			    un->un_mspl, sizeof (struct seq_mode));
16757 		}
16758 		if (rval) {
16759 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16760 			return;
16761 		}
16762 		break;
16763 	case DEVICE_TAMPER:
16764 		/*
16765 		 * Check if the ASC/ASCQ says mode data has changed.
16766 		 */
16767 		if ((errinfo->ei_failing_status.sts_sensedata.es_add_code ==
16768 		    0x2a) &&
16769 		    (errinfo->ei_failing_status.sts_sensedata.es_qual_code ==
16770 		    0x01)) {
16771 			/*
16772 			 * See if mode sense changed.
16773 			 */
16774 			rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16775 			if (rval) {
16776 				/*
16777 				 * If so change it back.
16778 				 */
16779 				rval = st_gen_mode_select(un, st_uscsi_rcmd,
16780 				    un->un_mspl, sizeof (struct seq_mode));
16781 			}
16782 			if (rval) {
16783 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16784 				return;
16785 			}
16786 		}
16787 		/*
16788 		 * if we have a media id and its not bogus.
16789 		 * Check to see if it the same.
16790 		 */
16791 		if (un->un_media_id != NULL && un->un_media_id != bogusID) {
16792 			rval = st_get_media_identification(un, st_uscsi_rcmd);
16793 			if (rval == ESPIPE) {
16794 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16795 				return;
16796 			}
16797 		}
16798 		break;
16799 	default:
16800 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16801 		    "Unhandled error type %s in st_recover() 0x%x\n",
16802 		    errstatenames[errinfo->ei_error_type], com);
16803 	}
16804 
16805 	/*
16806 	 * if command is retriable retry it.
16807 	 * Special case here. The command attribute for SCMD_REQUEST_SENSE
16808 	 * does not say that it is retriable. That because if you reissue a
16809 	 * request sense and the target responds the sense data will have
16810 	 * been consumed and no long be valid. If we get a busy status on
16811 	 * request sense while the state is ST_STATE_SENSING this will
16812 	 * reissue that pkt.
16813 	 *
16814 	 * XXX If this request sense gets sent to a different port then
16815 	 * the original command that failed was sent on it will not get
16816 	 * valid sense data for that command.
16817 	 */
16818 	if (rcv->cmd_attrib->retriable || un->un_rqs_bp == bp) {
16819 		status = st_recover_reissue_pkt(un, &errinfo->ei_failed_pkt);
16820 
16821 	/*
16822 	 * if drive doesn't support read position we are done
16823 	 */
16824 	} else if (un->un_read_pos_type == NO_POS) {
16825 		status = COMMAND_DONE_ERROR;
16826 	/*
16827 	 * If this command results in a changed tape position,
16828 	 * lets see where we are.
16829 	 */
16830 	} else if (rcv->cmd_attrib->chg_tape_pos) {
16831 		/*
16832 		 * XXX May be a reason to choose a different type here.
16833 		 * Long format has file position information.
16834 		 * Short and Extended have information about whats
16835 		 * in the buffer. St's positioning assumes in the buffer
16836 		 * to be the same as on tape.
16837 		 */
16838 		rval = st_compare_expected_position(un, errinfo,
16839 		    rcv->cmd_attrib, &cur_pos);
16840 		if (rval == 0) {
16841 			status = COMMAND_DONE;
16842 		} else if (rval == EAGAIN) {
16843 			status = st_recover_reissue_pkt(un,
16844 			    &errinfo->ei_failed_pkt);
16845 		} else {
16846 			status = COMMAND_DONE_ERROR;
16847 		}
16848 	} else {
16849 		ASSERT(0);
16850 	}
16851 
16852 	st_recov_ret(un, errinfo, status);
16853 }
16854 
16855 static void
16856 st_recov_cb(struct scsi_pkt *pkt)
16857 {
16858 	struct scsi_tape *un;
16859 	struct buf *bp;
16860 	recov_info *rcv;
16861 	errstate action = COMMAND_DONE_ERROR;
16862 	int timout = ST_TRAN_BUSY_TIMEOUT; /* short (default) timeout */
16863 
16864 	/*
16865 	 * Get the buf from the packet.
16866 	 */
16867 	rcv = pkt->pkt_private;
16868 	ASSERT(rcv->privatelen == sizeof (recov_info));
16869 	bp = rcv->cmd_bp;
16870 
16871 	/*
16872 	 * get the unit from the buf.
16873 	 */
16874 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16875 	ASSERT(un != NULL);
16876 
16877 	ST_FUNC(ST_DEVINFO, st_recov_cb);
16878 
16879 	mutex_enter(ST_MUTEX);
16880 
16881 	ASSERT(bp == un->un_recov_buf);
16882 
16883 
16884 	switch (pkt->pkt_reason) {
16885 	case CMD_CMPLT:
16886 		if (un->un_arq_enabled && pkt->pkt_state & STATE_ARQ_DONE) {
16887 			action = st_handle_autosense(un, bp, &rcv->pos);
16888 		} else  if ((SCBP(pkt)->sts_busy) ||
16889 		    (SCBP(pkt)->sts_chk) ||
16890 		    (SCBP(pkt)->sts_vu7)) {
16891 			action = st_check_error(un, pkt);
16892 		} else {
16893 			action = COMMAND_DONE;
16894 		}
16895 		break;
16896 	case CMD_TIMEOUT:
16897 		action = COMMAND_TIMEOUT;
16898 		break;
16899 	case CMD_TRAN_ERR:
16900 		action = QUE_COMMAND;
16901 		break;
16902 	default:
16903 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16904 		    "pkt_reason not handled yet %s",
16905 		    scsi_rname(pkt->pkt_reason));
16906 		action = COMMAND_DONE_ERROR;
16907 	}
16908 
16909 	/*
16910 	 * check for undetected path failover.
16911 	 */
16912 	if ((un->un_multipath) &&
16913 	    (un->un_last_path_instance != pkt->pkt_path_instance)) {
16914 		if (un->un_state > ST_STATE_OPENING) {
16915 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16916 			    "Failover detected in recovery, action is %s\n",
16917 			    errstatenames[action]);
16918 		}
16919 		un->un_last_path_instance = pkt->pkt_path_instance;
16920 	}
16921 
16922 	ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
16923 	    "Recovery call back got %s status on %s\n",
16924 	    errstatenames[action], st_print_scsi_cmd(pkt->pkt_cdbp[0]));
16925 
16926 	switch (action) {
16927 	case COMMAND_DONE:
16928 		break;
16929 
16930 	case COMMAND_DONE_EACCES:
16931 		bioerror(bp, EACCES);
16932 		break;
16933 
16934 	case COMMAND_DONE_ERROR_RECOVERED: /* XXX maybe wrong */
16935 		ASSERT(0);
16936 		break;
16937 
16938 	case COMMAND_TIMEOUT:
16939 	case COMMAND_DONE_ERROR:
16940 		bioerror(bp, EIO);
16941 		break;
16942 
16943 	case DEVICE_RESET:
16944 	case QUE_BUSY_COMMAND:
16945 	case PATH_FAILED:
16946 		/* longish timeout */
16947 		timout = ST_STATUS_BUSY_TIMEOUT;
16948 		/* FALLTHRU */
16949 	case QUE_COMMAND:
16950 	case DEVICE_TAMPER:
16951 	case ATTEMPT_RETRY:
16952 		/*
16953 		 * let st_handle_intr_busy put this bp back on waitq and make
16954 		 * checks to see if it is ok to requeue the command.
16955 		 */
16956 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
16957 
16958 		/*
16959 		 * Save the throttle before setting up the timeout
16960 		 */
16961 		if (un->un_throttle) {
16962 			un->un_last_throttle = un->un_throttle;
16963 		}
16964 		mutex_exit(ST_MUTEX);
16965 		if (st_handle_intr_busy(un, bp, timout) == 0) {
16966 			return;		/* timeout is setup again */
16967 		}
16968 		mutex_enter(ST_MUTEX);
16969 		un->un_pos.pmode = invalid;
16970 		un->un_err_resid = bp->b_resid = bp->b_bcount;
16971 		st_bioerror(bp, EIO);
16972 		st_set_pe_flag(un);
16973 		break;
16974 
16975 	default:
16976 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16977 		    "Unhandled recovery state 0x%x\n", action);
16978 		un->un_pos.pmode = invalid;
16979 		un->un_err_resid = bp->b_resid = bp->b_bcount;
16980 		st_bioerror(bp, EIO);
16981 		st_set_pe_flag(un);
16982 		break;
16983 	}
16984 
16985 	st_done_and_mutex_exit(un, bp);
16986 }
16987 
16988 static int
16989 st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait)
16990 {
16991 	struct buf *bp;
16992 	int err;
16993 
16994 	ST_FUNC(ST_DEVINFO, st_rcmd);
16995 
16996 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16997 	    "st_rcmd(un = 0x%p, com = 0x%x, count = %"PRIx64", wait = %d)\n",
16998 	    (void *)un, com, count, wait);
16999 
17000 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
17001 	ASSERT(mutex_owned(ST_MUTEX));
17002 
17003 #ifdef STDEBUG
17004 	if ((st_debug & 0x7)) {
17005 		st_debug_cmds(un, com, count, wait);
17006 	}
17007 #endif
17008 
17009 	while (un->un_recov_buf_busy)
17010 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17011 	un->un_recov_buf_busy = 1;
17012 
17013 	bp = un->un_recov_buf;
17014 	bzero(bp, sizeof (buf_t));
17015 
17016 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
17017 
17018 	err = st_setup_cmd(un, bp, com, count);
17019 
17020 	un->un_recov_buf_busy = 0;
17021 
17022 	cv_signal(&un->un_recov_buf_cv);
17023 
17024 	return (err);
17025 }
17026 
17027 /* args used */
17028 static int
17029 st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
17030 {
17031 	int rval;
17032 	buf_t *bp;
17033 
17034 	ST_FUNC(ST_DEVINFO, st_uscsi_rcmd);
17035 	ASSERT(flag == FKIOCTL);
17036 
17037 	/*
17038 	 * Get buffer resources...
17039 	 */
17040 	while (un->un_recov_buf_busy)
17041 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17042 	un->un_recov_buf_busy = 1;
17043 
17044 	bp = un->un_recov_buf;
17045 	bzero(bp, sizeof (buf_t));
17046 
17047 	bp->b_forw = (struct buf *)(uintptr_t)ucmd->uscsi_cdb[0];
17048 	bp->b_back = (struct buf *)ucmd;
17049 
17050 	mutex_exit(ST_MUTEX);
17051 	rval = scsi_uscsi_handle_cmd(un->un_dev, UIO_SYSSPACE, ucmd,
17052 	    st_strategy, bp, NULL);
17053 	mutex_enter(ST_MUTEX);
17054 
17055 	ucmd->uscsi_resid = bp->b_resid;
17056 
17057 	/*
17058 	 * Free resources
17059 	 */
17060 	un->un_recov_buf_busy = 0;
17061 	cv_signal(&un->un_recov_buf_cv);
17062 
17063 	return (rval);
17064 }
17065 
17066 /*
17067  * Add data to scsi_pkt to help know what to do if the command fails.
17068  */
17069 static void
17070 st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
17071     struct scsi_pkt *pkt)
17072 {
17073 	uint64_t count;
17074 	recov_info *rinfo = (recov_info *)pkt->pkt_private;
17075 
17076 	ST_FUNC(ST_DEVINFO, st_add_recovery_info_to_pkt);
17077 
17078 	ASSERT(rinfo->privatelen == sizeof (pkt_info) ||
17079 	    rinfo->privatelen == sizeof (recov_info));
17080 
17081 	SET_BP_PKT(bp, pkt);
17082 	rinfo->cmd_bp = bp;
17083 
17084 	if (rinfo->privatelen != sizeof (recov_info)) {
17085 		return;
17086 	}
17087 
17088 	rinfo->cmd_bp = bp;
17089 
17090 	rinfo->cmd_attrib = NULL;
17091 
17092 	/*
17093 	 * lookup the command attributes and add them to the recovery info.
17094 	 */
17095 	rinfo->cmd_attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
17096 
17097 	ASSERT(rinfo->cmd_attrib);
17098 
17099 	/*
17100 	 * For commands that there is no way to figure the expected position
17101 	 * once completed, we save the position the command was started from
17102 	 * so that if they fail we can position back and try again.
17103 	 * This has already been done in st_cmd() or st_iscsi_cmd().
17104 	 */
17105 	if (rinfo->cmd_attrib->recov_pos_type == POS_STARTING) {
17106 		/* save current position as the starting position. */
17107 		COPY_POS(&rinfo->pos, &un->un_pos);
17108 		un->un_running.pmode = invalid;
17109 		return;
17110 	}
17111 
17112 	/*
17113 	 * Don't want to update the running position for recovery.
17114 	 */
17115 	if (bp == un->un_recov_buf) {
17116 		rinfo->pos.pmode = un->un_running.pmode;
17117 		return;
17118 	}
17119 	/*
17120 	 * If running position is invalid copy the current position.
17121 	 * Running being set invalid means we are not in a read, write
17122 	 * or write filemark sequence.
17123 	 * We'll copy the current position and start from there.
17124 	 */
17125 	if (un->un_running.pmode == invalid) {
17126 		COPY_POS(&un->un_running, &un->un_pos);
17127 		COPY_POS(&rinfo->pos, &un->un_running);
17128 	} else {
17129 		COPY_POS(&rinfo->pos, &un->un_running);
17130 		if (rinfo->pos.pmode == legacy) {
17131 			/*
17132 			 * Always should be more logical blocks then
17133 			 * data blocks and files marks.
17134 			 */
17135 			ASSERT((rinfo->pos.blkno >= 0) ?
17136 			    rinfo->pos.lgclblkno >=
17137 			    (rinfo->pos.blkno + rinfo->pos.fileno) : 1);
17138 		}
17139 	}
17140 
17141 	/*
17142 	 * If the command is not expected to change the drive position
17143 	 * then the running position should be the expected position.
17144 	 */
17145 	if (rinfo->cmd_attrib->chg_tape_pos == 0) {
17146 		ASSERT(rinfo->cmd_attrib->chg_tape_direction == DIR_NONE);
17147 		return;
17148 	}
17149 
17150 	if (rinfo->cmd_attrib->explicit) {
17151 		ASSERT(rinfo->pos.pmode != invalid);
17152 		ASSERT(rinfo->cmd_attrib->get_cnt);
17153 		count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17154 		/*
17155 		 * This is a user generated CDB.
17156 		 */
17157 		if (bp == un->un_sbufp) {
17158 			uint64_t lbn;
17159 
17160 			lbn = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17161 
17162 			/*
17163 			 * See if this CDB will generate a locate or change
17164 			 * partition.
17165 			 */
17166 			if ((lbn != un->un_running.lgclblkno) ||
17167 			    (pkt->pkt_cdbp[3] != un->un_running.partition)) {
17168 				rinfo->pos.partition = pkt->pkt_cdbp[3];
17169 				rinfo->pos.pmode = logical;
17170 				rinfo->pos.lgclblkno = lbn;
17171 				un->un_running.partition = pkt->pkt_cdbp[3];
17172 				un->un_running.pmode = logical;
17173 				un->un_running.lgclblkno = lbn;
17174 			}
17175 		} else {
17176 			uint64_t lbn = un->un_running.lgclblkno;
17177 
17178 			pkt->pkt_cdbp[3]  = (uchar_t)un->un_running.partition;
17179 
17180 			pkt->pkt_cdbp[4]  = (uchar_t)(lbn >> 56);
17181 			pkt->pkt_cdbp[5]  = (uchar_t)(lbn >> 48);
17182 			pkt->pkt_cdbp[6]  = (uchar_t)(lbn >> 40);
17183 			pkt->pkt_cdbp[7]  = (uchar_t)(lbn >> 32);
17184 			pkt->pkt_cdbp[8]  = (uchar_t)(lbn >> 24);
17185 			pkt->pkt_cdbp[9]  = (uchar_t)(lbn >> 16);
17186 			pkt->pkt_cdbp[10] = (uchar_t)(lbn >> 8);
17187 			pkt->pkt_cdbp[11] = (uchar_t)(lbn);
17188 		}
17189 		rinfo->pos.lgclblkno += count;
17190 		rinfo->pos.blkno += count;
17191 		un->un_running.lgclblkno += count;
17192 		return;
17193 	}
17194 
17195 	if (rinfo->cmd_attrib->chg_tape_pos) {
17196 
17197 		/* should not have got an invalid position from running. */
17198 		if (un->un_mediastate == MTIO_INSERTED) {
17199 			ASSERT(rinfo->pos.pmode != invalid);
17200 		}
17201 
17202 		/* should have either a get count or or get lba function */
17203 		ASSERT(rinfo->cmd_attrib->get_cnt != NULL ||
17204 		    rinfo->cmd_attrib->get_lba != NULL);
17205 
17206 		/* only explicit commands have both and they're handled above */
17207 		ASSERT(!(rinfo->cmd_attrib->get_cnt != NULL &&
17208 		    rinfo->cmd_attrib->get_lba != NULL));
17209 
17210 		/* if it has a get count function */
17211 		if (rinfo->cmd_attrib->get_cnt != NULL) {
17212 			count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17213 			if (count == 0) {
17214 				return;
17215 			}
17216 			/*
17217 			 * Changes position but doesn't transfer data.
17218 			 * i.e. rewind, write_file_mark and load.
17219 			 */
17220 			if (rinfo->cmd_attrib->transfers_data == TRAN_NONE) {
17221 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17222 				case DIR_NONE: /* Erase */
17223 					ASSERT(rinfo->cmd_attrib->cmd ==
17224 					    SCMD_ERASE);
17225 					break;
17226 				case DIR_FORW: /* write_file_mark */
17227 					rinfo->pos.fileno += count;
17228 					rinfo->pos.lgclblkno += count;
17229 					rinfo->pos.blkno = 0;
17230 					un->un_running.fileno += count;
17231 					un->un_running.lgclblkno += count;
17232 					un->un_running.blkno = 0;
17233 					break;
17234 				case DIR_REVC: /* rewind */
17235 					rinfo->pos.fileno = 0;
17236 					rinfo->pos.lgclblkno = 0;
17237 					rinfo->pos.blkno = 0;
17238 					rinfo->pos.eof = ST_NO_EOF;
17239 					rinfo->pos.pmode = legacy;
17240 					un->un_running.fileno = 0;
17241 					un->un_running.lgclblkno = 0;
17242 					un->un_running.blkno = 0;
17243 					un->un_running.eof = ST_NO_EOF;
17244 					if (un->un_running.pmode != legacy)
17245 						un->un_running.pmode = legacy;
17246 					break;
17247 				case DIR_EITH: /* Load unload */
17248 					ASSERT(rinfo->cmd_attrib->cmd ==
17249 					    SCMD_LOAD);
17250 					switch (count & (LD_LOAD | LD_RETEN |
17251 					    LD_RETEN | LD_HOLD)) {
17252 					case LD_UNLOAD:
17253 					case LD_RETEN:
17254 					case LD_HOLD:
17255 					case LD_LOAD | LD_HOLD:
17256 					case LD_EOT | LD_HOLD:
17257 					case LD_RETEN | LD_HOLD:
17258 						rinfo->pos.pmode = invalid;
17259 						un->un_running.pmode = invalid;
17260 						break;
17261 					case LD_EOT:
17262 					case LD_LOAD | LD_EOT:
17263 						rinfo->pos.eof = ST_EOT;
17264 						rinfo->pos.pmode = invalid;
17265 						un->un_running.eof = ST_EOT;
17266 						un->un_running.pmode = invalid;
17267 						break;
17268 					case LD_LOAD:
17269 					case LD_RETEN | LD_LOAD:
17270 						rinfo->pos.fileno = 0;
17271 						rinfo->pos.lgclblkno = 0;
17272 						rinfo->pos.blkno = 0;
17273 						rinfo->pos.eof = ST_NO_EOF;
17274 						rinfo->pos.pmode = legacy;
17275 						un->un_running.fileno = 0;
17276 						un->un_running.lgclblkno = 0;
17277 						un->un_running.blkno = 0;
17278 						un->un_running.eof = ST_NO_EOF;
17279 						break;
17280 					default:
17281 						ASSERT(0);
17282 					}
17283 					break;
17284 				default:
17285 					ASSERT(0);
17286 					break;
17287 				}
17288 			} else {
17289 				/*
17290 				 * Changes position and does transfer data.
17291 				 * i.e. read or write.
17292 				 */
17293 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17294 				case DIR_FORW:
17295 					rinfo->pos.lgclblkno += count;
17296 					rinfo->pos.blkno += count;
17297 					un->un_running.lgclblkno += count;
17298 					un->un_running.blkno += count;
17299 					break;
17300 				case DIR_REVC:
17301 					rinfo->pos.lgclblkno -= count;
17302 					rinfo->pos.blkno -= count;
17303 					un->un_running.lgclblkno -= count;
17304 					un->un_running.blkno -= count;
17305 					break;
17306 				default:
17307 					ASSERT(0);
17308 					break;
17309 				}
17310 			}
17311 		} else if (rinfo->cmd_attrib->get_lba != NULL) {
17312 			/* Have a get LBA fuction. i.e. Locate */
17313 			ASSERT(rinfo->cmd_attrib->chg_tape_direction ==
17314 			    DIR_EITH);
17315 			count = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17316 			un->un_running.lgclblkno = count;
17317 			un->un_running.blkno = 0;
17318 			un->un_running.fileno = 0;
17319 			un->un_running.pmode = logical;
17320 			rinfo->pos.lgclblkno = count;
17321 			rinfo->pos.pmode = invalid;
17322 		} else {
17323 			ASSERT(0);
17324 		}
17325 		return;
17326 	}
17327 
17328 	ST_CDB(ST_DEVINFO, "Unhanded CDB for position prediction",
17329 	    (char *)pkt->pkt_cdbp);
17330 
17331 }
17332 
17333 static int
17334 st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf)
17335 {
17336 	struct seq_mode *current;
17337 	int rval;
17338 	int i;
17339 	caddr_t this;
17340 	caddr_t that;
17341 
17342 	ST_FUNC(ST_DEVINFO, st_check_mode_for_change);
17343 
17344 	/* recovery called with mode tamper before mode selection */
17345 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
17346 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17347 		    "Mode Select not done yet");
17348 		return (0);
17349 	}
17350 
17351 	current = kmem_zalloc(sizeof (struct seq_mode), KM_SLEEP);
17352 
17353 	rval = st_gen_mode_sense(un, ubf, un->un_comp_page, current,
17354 	    sizeof (struct seq_mode));
17355 	if (rval != 0) {
17356 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17357 		    "Mode Sense for mode verification failed");
17358 		kmem_free(current, sizeof (struct seq_mode));
17359 		return (rval);
17360 	}
17361 
17362 	this = (caddr_t)current;
17363 	that = (caddr_t)un->un_mspl;
17364 
17365 	rval = bcmp(this, that, sizeof (struct seq_mode));
17366 	if (rval == 0) {
17367 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17368 		    "Found no changes in mode data");
17369 	}
17370 #ifdef STDEBUG
17371 	else {
17372 		for (i = 1; i < sizeof (struct seq_mode); i++) {
17373 			if (this[i] != that[i]) {
17374 				ST_RECOV(ST_DEVINFO, st_label, CE_CONT,
17375 				    "sense data changed at byte %d was "
17376 				    "0x%x now 0x%x", i,
17377 				    (uchar_t)that[i], (uchar_t)this[i]);
17378 			}
17379 		}
17380 	}
17381 #endif
17382 	kmem_free(current, sizeof (struct seq_mode));
17383 
17384 	return (rval);
17385 }
17386 
17387 static int
17388 st_test_path_to_device(struct scsi_tape *un)
17389 {
17390 	int rval = 0;
17391 	int limit = st_retry_count;
17392 
17393 	ST_FUNC(ST_DEVINFO, st_test_path_to_device);
17394 
17395 	/*
17396 	 * XXX Newer drives may not RESEVATION CONFLICT a TUR.
17397 	 */
17398 	do {
17399 		if (rval != 0) {
17400 			mutex_exit(ST_MUTEX);
17401 			delay(drv_usectohz(1000000));
17402 			mutex_enter(ST_MUTEX);
17403 		}
17404 		rval = st_rcmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
17405 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17406 		    "ping TUR returned 0x%x", rval);
17407 		limit--;
17408 	} while (((rval == EACCES) || (rval == EBUSY)) && limit);
17409 
17410 	if (un->un_status == KEY_NOT_READY || un->un_mediastate == MTIO_EJECTED)
17411 		rval = 0;
17412 
17413 	return (rval);
17414 }
17415 
17416 /*
17417  * Does read position using recov_buf and doesn't update un_pos.
17418  * Does what ever kind of read position you want.
17419  */
17420 static int
17421 st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
17422     read_pos_data_t *raw)
17423 {
17424 	int rval;
17425 	struct uscsi_cmd cmd;
17426 	struct scsi_arq_status status;
17427 	char cdb[CDB_GROUP1];
17428 
17429 	ST_FUNC(ST_DEVINFO, st_recovery_read_pos);
17430 	bzero(&cmd, sizeof (cmd));
17431 
17432 	cdb[0] = SCMD_READ_POSITION;
17433 	cdb[1] = type;
17434 	cdb[2] = 0;
17435 	cdb[3] = 0;
17436 	cdb[4] = 0;
17437 	cdb[5] = 0;
17438 	cdb[6] = 0;
17439 	cdb[7] = 0;
17440 	cdb[8] = (type == EXT_POS) ? 28 : 0;
17441 	cdb[9] = 0;
17442 
17443 	cmd.uscsi_flags = USCSI_READ | USCSI_RQENABLE;
17444 	cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
17445 	cmd.uscsi_cdb = cdb;
17446 	cmd.uscsi_cdblen = sizeof (cdb);
17447 	cmd.uscsi_rqlen = sizeof (status);
17448 	cmd.uscsi_rqbuf = (caddr_t)&status;
17449 	cmd.uscsi_bufaddr = (caddr_t)raw;
17450 	switch (type) {
17451 	case SHORT_POS:
17452 		cmd.uscsi_buflen = sizeof (tape_position_t);
17453 		break;
17454 	case LONG_POS:
17455 		cmd.uscsi_buflen = sizeof (tape_position_long_t);
17456 		break;
17457 	case EXT_POS:
17458 		cmd.uscsi_buflen = sizeof (tape_position_ext_t);
17459 		break;
17460 	default:
17461 		ASSERT(0);
17462 	}
17463 
17464 	rval = st_uscsi_rcmd(un, &cmd, FKIOCTL);
17465 	if (cmd.uscsi_status) {
17466 		rval = EIO;
17467 	}
17468 	return (rval);
17469 }
17470 
17471 static int
17472 st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
17473     read_pos_data_t *raw)
17474 {
17475 	int rval;
17476 	read_p_types type = un->un_read_pos_type;
17477 
17478 	ST_FUNC(ST_DEVINFO, st_recovery_get_position);
17479 
17480 	do {
17481 		rval = st_recovery_read_pos(un, type, raw);
17482 		if (rval != 0) {
17483 			switch (type) {
17484 			case SHORT_POS:
17485 				type = NO_POS;
17486 				break;
17487 
17488 			case LONG_POS:
17489 				type = EXT_POS;
17490 				break;
17491 
17492 			case EXT_POS:
17493 				type = SHORT_POS;
17494 				break;
17495 
17496 			default:
17497 				type = LONG_POS;
17498 				break;
17499 
17500 			}
17501 		} else {
17502 			if (type != un->un_read_pos_type) {
17503 				un->un_read_pos_type = type;
17504 			}
17505 			break;
17506 		}
17507 	} while (type != NO_POS);
17508 
17509 	if (rval == 0) {
17510 		rval = st_interpret_read_pos(un, read, type,
17511 		    sizeof (read_pos_data_t), (caddr_t)raw, 1);
17512 	}
17513 	return (rval);
17514 }
17515 
17516 /*
17517  * based on the command do we retry, continue or give up?
17518  * possable return values?
17519  *	zero do nothing looks fine.
17520  *	EAGAIN retry.
17521  *	EIO failed makes no sense.
17522  */
17523 static int
17524 st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
17525     cmd_attribute const * cmd_att, tapepos_t *read)
17526 {
17527 	int rval;
17528 	read_pos_data_t *readp_datap;
17529 
17530 	ST_FUNC(ST_DEVINFO, st_compare_expected_position);
17531 
17532 	ASSERT(un != NULL);
17533 	ASSERT(ei != NULL);
17534 	ASSERT(read != NULL);
17535 	ASSERT(cmd_att->chg_tape_pos);
17536 
17537 	COPY_POS(read, &ei->ei_expected_pos);
17538 
17539 	readp_datap = kmem_zalloc(sizeof (read_pos_data_t), KM_SLEEP);
17540 
17541 	rval = st_recovery_get_position(un, read, readp_datap);
17542 
17543 	kmem_free(readp_datap, sizeof (read_pos_data_t));
17544 
17545 	if (rval != 0) {
17546 		return (EIO);
17547 	}
17548 
17549 	ST_POS(ST_DEVINFO, "st_compare_expected_position", read);
17550 
17551 	if ((read->pmode == invalid) ||
17552 	    (ei->ei_expected_pos.pmode == invalid)) {
17553 		return (EIO);
17554 	}
17555 
17556 	/*
17557 	 * Command that changes tape position and have an expected position
17558 	 * if it were to chave completed sucessfully.
17559 	 */
17560 	if (cmd_att->recov_pos_type == POS_EXPECTED) {
17561 		uint32_t count;
17562 		int64_t difference;
17563 		uchar_t reposition = 0;
17564 
17565 		ASSERT(cmd_att->get_cnt);
17566 		count = cmd_att->get_cnt(ei->ei_failed_pkt.pkt_cdbp);
17567 
17568 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17569 		    "Got count from CDB and it was %d\n", count);
17570 
17571 		/*
17572 		 * At expected?
17573 		 */
17574 		if (read->lgclblkno == ei->ei_expected_pos.lgclblkno) {
17575 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17576 			    "Found drive to be at expected position\n");
17577 
17578 			/*
17579 			 * If the command should move tape and it got a busy
17580 			 * it shouldn't be in the expected position.
17581 			 */
17582 			if (ei->ei_failing_status.sts_status.sts_busy != 0) {
17583 				reposition = 1;
17584 
17585 			/*
17586 			 * If the command doesn't transfer data should be good.
17587 			 */
17588 			} else if (cmd_att->transfers_data == TRAN_NONE) {
17589 				return (0); /* Good */
17590 
17591 			/*
17592 			 * Command transfers data, should have done so.
17593 			 */
17594 			} else if (ei->ei_failed_pkt.pkt_state &
17595 			    STATE_XFERRED_DATA) {
17596 				return (0); /* Good */
17597 			} else {
17598 				reposition = 1;
17599 			}
17600 		}
17601 
17602 		if (cmd_att->chg_tape_direction == DIR_FORW) {
17603 			difference =
17604 			    ei->ei_expected_pos.lgclblkno - read->lgclblkno;
17605 
17606 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17607 			    "difference between expected and actual is %"
17608 			    PRId64"\n", difference);
17609 			if (count == difference && reposition == 0) {
17610 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17611 				    "Found failed FORW command, retrying\n");
17612 				return (EAGAIN);
17613 			}
17614 
17615 			/*
17616 			 * If rewound or somewhere between the starting position
17617 			 * and the expected position (partial read or write).
17618 			 * Locate to the starting position and try the whole
17619 			 * thing over again.
17620 			 */
17621 			if ((read->lgclblkno == 0) ||
17622 			    ((difference > 0) && (difference < count))) {
17623 				rval = st_logical_block_locate(un,
17624 				    st_uscsi_rcmd, read,
17625 				    ei->ei_expected_pos.lgclblkno - count,
17626 				    ei->ei_expected_pos.partition);
17627 				if (rval == 0) {
17628 					ST_RECOV(ST_DEVINFO, st_label,
17629 					    CE_NOTE, "reestablished FORW"
17630 					    " command retrying\n");
17631 					return (EAGAIN);
17632 				}
17633 			/*
17634 			 * This handles flushed read ahead on the drive or
17635 			 * an aborted read that presents as a busy and advanced
17636 			 * the tape position.
17637 			 */
17638 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17639 			    ((difference < 0) || (reposition == 1))) {
17640 				rval = st_logical_block_locate(un,
17641 				    st_uscsi_rcmd, read,
17642 				    ei->ei_expected_pos.lgclblkno - count,
17643 				    ei->ei_expected_pos.partition);
17644 				if (rval == 0) {
17645 					ST_RECOV(ST_DEVINFO, st_label,
17646 					    CE_NOTE, "reestablished FORW"
17647 					    " read command retrying\n");
17648 					return (EAGAIN);
17649 				}
17650 			/*
17651 			 * XXX swag seeing difference of 2 on write filemark.
17652 			 * If the space to the starting position works on a
17653 			 * write that means the previous write made it to tape.
17654 			 * If not we lost data and have to give up.
17655 			 *
17656 			 * The plot thickens. Now I am attempting to cover a
17657 			 * count of 1 and a differance of 2 on a write.
17658 			 */
17659 			} else if ((difference > count) || (reposition == 1)) {
17660 				rval = st_logical_block_locate(un,
17661 				    st_uscsi_rcmd, read,
17662 				    ei->ei_expected_pos.lgclblkno - count,
17663 				    ei->ei_expected_pos.partition);
17664 				if (rval == 0) {
17665 					ST_RECOV(ST_DEVINFO, st_label,
17666 					    CE_NOTE, "reestablished FORW"
17667 					    " write command retrying\n");
17668 					return (EAGAIN);
17669 				}
17670 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17671 				    "Seek to block %"PRId64" returned %d\n",
17672 				    ei->ei_expected_pos.lgclblkno - count,
17673 				    rval);
17674 			} else {
17675 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17676 				    "Not expected transfers_data = %d "
17677 				    "difference = %"PRId64,
17678 				    cmd_att->transfers_data, difference);
17679 			}
17680 
17681 			return (EIO);
17682 
17683 		} else if (cmd_att->chg_tape_direction == DIR_REVC) {
17684 			/* Don't think we can write backwards */
17685 			ASSERT(cmd_att->transfers_data != TRAN_WRTE);
17686 			difference =
17687 			    read->lgclblkno - ei->ei_expected_pos.lgclblkno;
17688 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17689 			    "difference between expected and actual is %"
17690 			    PRId64"\n", difference);
17691 			if (count == difference && reposition == 0) {
17692 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17693 				    "Found failed REVC command, retrying\n");
17694 				return (EAGAIN);
17695 			}
17696 			if ((read->lgclblkno == 0) ||
17697 			    ((difference > 0) && (difference < count))) {
17698 				rval = st_logical_block_locate(un,
17699 				    st_uscsi_rcmd, read,
17700 				    ei->ei_expected_pos.lgclblkno + count,
17701 				    ei->ei_expected_pos.partition);
17702 				if (rval == 0) {
17703 					ST_RECOV(ST_DEVINFO, st_label,
17704 					    CE_NOTE, "reestablished REVC"
17705 					    " command retrying\n");
17706 					return (EAGAIN);
17707 				}
17708 			/* This handles read ahead in reverse direction */
17709 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17710 			    (difference < 0) || (reposition == 1)) {
17711 				rval = st_logical_block_locate(un,
17712 				    st_uscsi_rcmd, read,
17713 				    ei->ei_expected_pos.lgclblkno - count,
17714 				    ei->ei_expected_pos.partition);
17715 				if (rval == 0) {
17716 					ST_RECOV(ST_DEVINFO, st_label,
17717 					    CE_NOTE, "reestablished REVC"
17718 					    " read command retrying\n");
17719 					return (EAGAIN);
17720 				}
17721 			} else {
17722 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17723 				    "Not expected transfers_data = %d "
17724 				    "difference = %"PRId64,
17725 				    cmd_att->transfers_data, difference);
17726 			}
17727 			return (EIO);
17728 
17729 		} else {
17730 			/*
17731 			 * Commands that change tape position either
17732 			 * direction or don't change position should not
17733 			 * get here.
17734 			 */
17735 			ASSERT(0);
17736 		}
17737 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17738 		    "Didn't find a recoverable position, Failing\n");
17739 
17740 	/*
17741 	 * Command that changes tape position and can only be recovered
17742 	 * by going back to the point of origin and retrying.
17743 	 *
17744 	 * Example SCMD_SPACE.
17745 	 */
17746 	} else if (cmd_att->recov_pos_type == POS_STARTING) {
17747 		/*
17748 		 * This type of command stores the starting position.
17749 		 * If the read position is the starting position,
17750 		 * reissue the command.
17751 		 */
17752 		if (ei->ei_expected_pos.lgclblkno == read->lgclblkno) {
17753 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17754 			    "Found Space command at starting position, "
17755 			    "Reissuing\n");
17756 			return (EAGAIN);
17757 		}
17758 		/*
17759 		 * Not in the position that the command was originally issued,
17760 		 * Attempt to locate to that position.
17761 		 */
17762 		rval = st_logical_block_locate(un, st_uscsi_rcmd, read,
17763 		    ei->ei_expected_pos.lgclblkno,
17764 		    ei->ei_expected_pos.partition);
17765 		if (rval) {
17766 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17767 			    "Found Space at an unexpected position and locate "
17768 			    "back to starting position failed\n");
17769 			return (EIO);
17770 		}
17771 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17772 		    "Found Space at an unexpected position and locate "
17773 		    "back to starting position worked, Reissuing\n");
17774 		return (EAGAIN);
17775 	}
17776 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17777 	    "Unhandled attribute/expected position", &ei->ei_expected_pos);
17778 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17779 	    "Read position above did not make sense", read);
17780 	ASSERT(0);
17781 	return (EIO);
17782 }
17783 
17784 static errstate
17785 st_recover_reissue_pkt(struct scsi_tape *un, struct scsi_pkt *oldpkt)
17786 {
17787 	buf_t *bp;
17788 	buf_t *pkt_bp;
17789 	struct scsi_pkt *newpkt;
17790 	cmd_attribute const *attrib;
17791 	recov_info *rcv = oldpkt->pkt_private;
17792 	uint_t cdblen;
17793 	int queued = 0;
17794 	int rval;
17795 	int flags = 0;
17796 	int stat_size =
17797 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
17798 
17799 	ST_FUNC(ST_DEVINFO, st_recover_reissue_pkt);
17800 
17801 	bp = rcv->cmd_bp;
17802 
17803 	if (rcv->privatelen == sizeof (recov_info)) {
17804 		attrib = rcv->cmd_attrib;
17805 	} else {
17806 		attrib = st_lookup_cmd_attribute(oldpkt->pkt_cdbp[0]);
17807 	}
17808 
17809 	/*
17810 	 * Some non-uscsi commands use the b_bcount for values that
17811 	 * have nothing to do with how much data is transfered.
17812 	 * In those cases we need to hide the buf_t from scsi_init_pkt().
17813 	 */
17814 	if ((BP_UCMD(bp)) && (bp->b_bcount)) {
17815 		pkt_bp = bp;
17816 	} else if (attrib->transfers_data == TRAN_NONE) {
17817 		pkt_bp = NULL;
17818 	} else {
17819 		pkt_bp = bp;
17820 	}
17821 
17822 	/*
17823 	 * if this is a queued command make sure it the only one in the
17824 	 * run queue.
17825 	 */
17826 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
17827 		ASSERT(un->un_runqf == un->un_runql);
17828 		ASSERT(un->un_runqf == bp);
17829 		queued = 1;
17830 	}
17831 
17832 	cdblen = scsi_cdb_size[CDB_GROUPID(oldpkt->pkt_cdbp[0])];
17833 
17834 	if (pkt_bp == un->un_rqs_bp) {
17835 		flags |= PKT_CONSISTENT;
17836 		stat_size = 1;
17837 	}
17838 
17839 	newpkt = scsi_init_pkt(ROUTE, NULL, pkt_bp, cdblen,
17840 	    stat_size, rcv->privatelen, flags, NULL_FUNC, NULL);
17841 	if (newpkt == NULL) {
17842 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17843 		    "Reissue pkt scsi_init_pkt() failure\n");
17844 		return (COMMAND_DONE_ERROR);
17845 	}
17846 
17847 	ASSERT(newpkt->pkt_resid == 0);
17848 	bp->b_flags &= ~(B_DONE);
17849 	bp->b_resid = 0;
17850 	st_bioerror(bp, 0);
17851 
17852 	bcopy(oldpkt->pkt_private, newpkt->pkt_private, rcv->privatelen);
17853 
17854 	newpkt->pkt_comp = oldpkt->pkt_comp;
17855 	newpkt->pkt_time = oldpkt->pkt_time;
17856 
17857 	bzero(newpkt->pkt_scbp, stat_size);
17858 	bcopy(oldpkt->pkt_cdbp, newpkt->pkt_cdbp, cdblen);
17859 
17860 	newpkt->pkt_state = 0;
17861 	newpkt->pkt_statistics = 0;
17862 
17863 	/*
17864 	 * oldpkt passed in was a copy of the original.
17865 	 * to distroy we need the address of the original.
17866 	 */
17867 	oldpkt = BP_PKT(bp);
17868 
17869 	if (oldpkt == un->un_rqs) {
17870 		ASSERT(bp == un->un_rqs_bp);
17871 		un->un_rqs = newpkt;
17872 	}
17873 
17874 	SET_BP_PKT(bp, newpkt);
17875 
17876 	scsi_destroy_pkt(oldpkt);
17877 
17878 	rval = st_transport(un, newpkt);
17879 	if (rval == TRAN_ACCEPT) {
17880 		return (JUST_RETURN);
17881 	}
17882 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17883 	    "Reissue pkt st_transport(0x%x) failure\n", rval);
17884 	if (rval != TRAN_BUSY) {
17885 		return (COMMAND_DONE_ERROR);
17886 	}
17887 	mutex_exit(ST_MUTEX);
17888 	rval = st_handle_start_busy(un, bp, ST_TRAN_BUSY_TIMEOUT, queued);
17889 	mutex_enter(ST_MUTEX);
17890 	if (rval) {
17891 		return (COMMAND_DONE_ERROR);
17892 	}
17893 
17894 	return (JUST_RETURN);
17895 }
17896 
17897 static int
17898 st_transport(struct scsi_tape *un, struct scsi_pkt *pkt)
17899 {
17900 	int status;
17901 
17902 	ST_FUNC(ST_DEVINFO, st_transport);
17903 
17904 	ST_CDB(ST_DEVINFO, "transport CDB", (caddr_t)pkt->pkt_cdbp);
17905 
17906 	mutex_exit(ST_MUTEX);
17907 
17908 	status = scsi_transport(pkt);
17909 
17910 	mutex_enter(ST_MUTEX);
17911 
17912 	return (status);
17913 }
17914 
17915 /*
17916  * Removed the buf_t bp from the queue referenced to by head and tail.
17917  * Returns the buf_t pointer if it is found in the queue.
17918  * Returns NULL if it is not found.
17919  */
17920 static buf_t *
17921 st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp)
17922 {
17923 	buf_t *runqbp;
17924 	buf_t *prevbp = NULL;
17925 
17926 	for (runqbp = *head; runqbp != 0; runqbp = runqbp->av_forw) {
17927 		if (runqbp == bp) {
17928 			/* found it, is it at the head? */
17929 			if (runqbp == *head) {
17930 				*head = bp->av_forw;
17931 			} else {
17932 				prevbp->av_forw = bp->av_forw;
17933 			}
17934 			if (*tail == bp) {
17935 				*tail = prevbp;
17936 			}
17937 			bp->av_forw = NULL;
17938 			return (bp); /* found and removed */
17939 		}
17940 		prevbp = runqbp;
17941 	}
17942 	return (NULL);
17943 }
17944 
17945 /*
17946  * Adds a buf_t to the queue pointed to by head and tail.
17947  * Adds it either to the head end or the tail end based on which
17948  * the passed variable end (head or tail) points at.
17949  */
17950 static void
17951 st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp)
17952 {
17953 
17954 	bp->av_forw = NULL;
17955 	if (*head) {
17956 		/* Queue is not empty */
17957 		if (end == *head) {
17958 			/* Add at front of queue */
17959 			bp->av_forw = *head;
17960 			*head = bp;
17961 		} else if (end == *tail) {
17962 			/* Add at end of queue */
17963 			(*tail)->av_forw = bp;
17964 			*tail = bp;
17965 		} else {
17966 			ASSERT(0);
17967 		}
17968 	} else {
17969 		/* Queue is empty */
17970 		*head = bp;
17971 		*tail = bp;
17972 	}
17973 }
17974 
17975 
17976 static uint64_t
17977 st_get_cdb_g0_rw_count(uchar_t *cdb)
17978 {
17979 	uint64_t count;
17980 
17981 	if ((cdb[1]) & 1) {
17982 		/* fixed block mode, the count is the number of blocks */
17983 		count =
17984 		    cdb[2] << 16 |
17985 		    cdb[3] << 8 |
17986 		    cdb[4];
17987 	} else {
17988 		/* variable block mode, the count is the block size */
17989 		count = 1;
17990 	}
17991 	return (count);
17992 }
17993 
17994 static uint64_t
17995 st_get_cdb_g0_sign_count(uchar_t *cdb)
17996 {
17997 	uint64_t count;
17998 
17999 	count =
18000 	    cdb[2] << 16 |
18001 	    cdb[3] << 8 |
18002 	    cdb[4];
18003 	/*
18004 	 * If the sign bit of the 3 byte value is set, extended it.
18005 	 */
18006 	if (count & 0x800000) {
18007 		count |= 0xffffffffff000000;
18008 	}
18009 	return (count);
18010 }
18011 
18012 static uint64_t
18013 st_get_cdb_g0_count(uchar_t *cdb)
18014 {
18015 	uint64_t count;
18016 
18017 	count =
18018 	    cdb[2] << 16 |
18019 	    cdb[3] << 8 |
18020 	    cdb[4];
18021 	return (count);
18022 }
18023 
18024 static uint64_t
18025 st_get_cdb_g5_rw_cnt(uchar_t *cdb)
18026 {
18027 	uint64_t count;
18028 
18029 	if ((cdb[1]) & 1) {
18030 		/* fixed block mode */
18031 		count =
18032 		    cdb[12] << 16 |
18033 		    cdb[13] << 8 |
18034 		    cdb[14];
18035 	} else {
18036 		/* variable block mode */
18037 		count = 1;
18038 	}
18039 	return (count);
18040 }
18041 
18042 static uint64_t
18043 st_get_no_count(uchar_t *cdb)
18044 {
18045 	ASSERT(cdb[0] == SCMD_REWIND);
18046 	return ((uint64_t)cdb[0]);
18047 }
18048 
18049 static uint64_t
18050 st_get_load_options(uchar_t *cdb)
18051 {
18052 	return ((uint64_t)(cdb[4] | (LD_HOLD << 1)));
18053 }
18054 
18055 static uint64_t
18056 st_get_erase_options(uchar_t *cdb)
18057 {
18058 	return (cdb[1] | (cdb[0] << 8));
18059 }
18060 
18061 static uint64_t
18062 st_get_cdb_g1_lba(uchar_t *cdb)
18063 {
18064 	uint64_t lba;
18065 
18066 	lba =
18067 	    cdb[3] << 24 |
18068 	    cdb[4] << 16 |
18069 	    cdb[5] << 8 |
18070 	    cdb[6];
18071 	return (lba);
18072 }
18073 
18074 static uint64_t
18075 st_get_cdb_g5_count(uchar_t *cdb)
18076 {
18077 	uint64_t count =
18078 	    cdb[12] << 16 |
18079 	    cdb[13] << 8 |
18080 	    cdb[14];
18081 
18082 	return (count);
18083 }
18084 
18085 static uint64_t
18086 st_get_cdb_g4g5_cnt(uchar_t *cdb)
18087 {
18088 	uint64_t lba;
18089 
18090 	lba =
18091 	    (uint64_t)cdb[4] << 56 |
18092 	    (uint64_t)cdb[5] << 48 |
18093 	    (uint64_t)cdb[6] << 40 |
18094 	    (uint64_t)cdb[7] << 32 |
18095 	    (uint64_t)cdb[8] << 24 |
18096 	    (uint64_t)cdb[9] << 16 |
18097 	    (uint64_t)cdb[10] << 8 |
18098 	    (uint64_t)cdb[11];
18099 	return (lba);
18100 }
18101 
18102 static const cmd_attribute cmd_attributes[] = {
18103 	{ SCMD_READ,
18104 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_READ, POS_EXPECTED,
18105 	    0, 0, 0, st_get_cdb_g0_rw_count },
18106 	{ SCMD_WRITE,
18107 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18108 	    0, 0, 0, st_get_cdb_g0_rw_count },
18109 	{ SCMD_TEST_UNIT_READY,
18110 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18111 	    0, 0, 0 },
18112 	{ SCMD_REWIND,
18113 	    1, 1, 1, 0, 0, DIR_REVC, TRAN_NONE, POS_EXPECTED,
18114 	    0, 0, 0, st_get_no_count },
18115 	{ SCMD_REQUEST_SENSE,
18116 	    0, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18117 	    0, 0, 0 },
18118 	{ SCMD_READ_BLKLIM,
18119 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18120 	    0, 0, 0 },
18121 	{ SCMD_READ_G4,
18122 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_READ, POS_EXPECTED,
18123 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18124 	{ SCMD_WRITE_G4,
18125 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18126 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18127 	{ SCMD_READ_REVERSE,
18128 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18129 	    0, 0, 0, st_get_cdb_g0_rw_count },
18130 	{ SCMD_READ_REVERSE_G4,
18131 	    1, 0, 1, 1, 1, DIR_REVC, TRAN_READ, POS_EXPECTED,
18132 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18133 	{ SCMD_WRITE_FILE_MARK,
18134 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18135 	    0, 0, 0, st_get_cdb_g0_count },
18136 	{ SCMD_WRITE_FILE_MARK_G4,
18137 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18138 	    0, 0, 0, st_get_cdb_g5_count, st_get_cdb_g4g5_cnt },
18139 	{ SCMD_SPACE,
18140 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18141 	    0, 0, 0, st_get_cdb_g0_sign_count },
18142 	{ SCMD_SPACE_G4,
18143 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18144 	    0, 0, 0, st_get_cdb_g4g5_cnt },
18145 	{ SCMD_INQUIRY,
18146 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18147 	    0, 0, 0 },
18148 	{ SCMD_VERIFY_G0,
18149 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18150 	    0, 0, 0, st_get_cdb_g0_rw_count },
18151 	{ SCMD_VERIFY_G4,
18152 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18153 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18154 	{ SCMD_RECOVER_BUF,
18155 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18156 	    0, 0, 0 },
18157 	{ SCMD_MODE_SELECT,
18158 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18159 	    0, 0, 0 },
18160 	{ SCMD_RESERVE,
18161 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18162 	    0, 0, 0 },
18163 	{ SCMD_RELEASE,
18164 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18165 	    0, 0, 0 },
18166 	{ SCMD_ERASE,
18167 	    1, 0, 1, 1, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18168 	    0, 0, 0, st_get_erase_options },
18169 	{ SCMD_MODE_SENSE,
18170 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18171 	    0, 0, 0 },
18172 	{ SCMD_LOAD,
18173 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18174 	    0, 0, 0, st_get_load_options },
18175 	{ SCMD_GDIAG,
18176 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18177 	    1, 0, 0 },
18178 	{ SCMD_SDIAG,
18179 	    1, 0, 1, 1, 0, DIR_EITH, TRAN_WRTE, POS_EXPECTED,
18180 	    1, 0, 0 },
18181 	{ SCMD_DOORLOCK,
18182 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18183 	    0, 4, 3 },
18184 	{ SCMD_LOCATE,
18185 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18186 	    0, 0, 0, NULL, st_get_cdb_g1_lba },
18187 	{ SCMD_READ_POSITION,
18188 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18189 	    0, 0, 0 },
18190 	{ SCMD_WRITE_BUFFER,
18191 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18192 	    1, 0, 0 },
18193 	{ SCMD_READ_BUFFER,
18194 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18195 	    1, 0, 0 },
18196 	{ SCMD_REPORT_DENSITIES,
18197 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18198 	    0, 0, 0 },
18199 	{ SCMD_LOG_SELECT_G1,
18200 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18201 	    0, 0, 0 },
18202 	{ SCMD_LOG_SENSE_G1,
18203 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18204 	    0, 0, 0 },
18205 	{ SCMD_PRIN,
18206 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18207 	    0, 0, 0 },
18208 	{ SCMD_PROUT,
18209 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18210 	    0, 0, 0 },
18211 	{ SCMD_READ_ATTRIBUTE,
18212 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18213 	    0, 0, 0 },
18214 	{ SCMD_WRITE_ATTRIBUTE,
18215 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18216 	    0, 0, 0 },
18217 	{ SCMD_LOCATE_G4,
18218 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18219 	    0, 0, 0, NULL, st_get_cdb_g4g5_cnt },
18220 	{ SCMD_REPORT_LUNS,
18221 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18222 	    0, 0, 0 },
18223 	{ SCMD_SVC_ACTION_IN_G5,
18224 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18225 	    0, 0, 0 },
18226 	{ SCMD_MAINTENANCE_IN,
18227 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18228 	    0, 0, 0 },
18229 	{ SCMD_MAINTENANCE_OUT,
18230 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18231 	    0, 0, 0 },
18232 	{ 0xff, /* Default attribute for unsupported commands */
18233 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_STARTING,
18234 	    1, 0, 0, NULL, NULL }
18235 };
18236 
18237 static const cmd_attribute *
18238 st_lookup_cmd_attribute(unsigned char cmd)
18239 {
18240 	int i;
18241 	cmd_attribute const *attribute;
18242 
18243 	for (i = 0; i < ST_NUM_MEMBERS(cmd_attributes); i++) {
18244 		attribute = &cmd_attributes[i];
18245 		if (attribute->cmd == cmd) {
18246 			return (attribute);
18247 		}
18248 	}
18249 	ASSERT(attribute);
18250 	return (attribute);
18251 }
18252 
18253 static int
18254 st_reset(struct scsi_tape *un, int reset_type)
18255 {
18256 	int rval;
18257 
18258 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
18259 
18260 	ST_FUNC(ST_DEVINFO, st_reset);
18261 	un->un_rsvd_status |= ST_INITIATED_RESET;
18262 	mutex_exit(ST_MUTEX);
18263 	do {
18264 		rval = scsi_reset(&un->un_sd->sd_address, reset_type);
18265 		if (rval == 0) {
18266 			switch (reset_type) {
18267 			case RESET_LUN:
18268 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18269 				    "LUN reset failed trying target reset");
18270 				reset_type = RESET_TARGET;
18271 				break;
18272 			case RESET_TARGET:
18273 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18274 				    "target reset failed trying bus reset");
18275 				reset_type = RESET_BUS;
18276 				break;
18277 			case RESET_BUS:
18278 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18279 				    "bus reset failed trying all reset");
18280 				reset_type = RESET_ALL;
18281 			default:
18282 				mutex_enter(ST_MUTEX);
18283 				return (rval);
18284 			}
18285 		}
18286 	} while (rval == 0);
18287 	mutex_enter(ST_MUTEX);
18288 	return (rval);
18289 }
18290 
18291 
18292 static void
18293 st_reset_notification(caddr_t arg)
18294 {
18295 	struct scsi_tape *un = (struct scsi_tape *)arg;
18296 
18297 	ST_FUNC(ST_DEVINFO, st_reset_notification);
18298 	mutex_enter(ST_MUTEX);
18299 
18300 	un->un_unit_attention_flags |= 2;
18301 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
18302 	    ST_RESERVE) {
18303 		un->un_rsvd_status |= ST_LOST_RESERVE;
18304 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18305 		    "Lost Reservation notification");
18306 	} else {
18307 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18308 		    "reset notification");
18309 	}
18310 
18311 	if ((un->un_restore_pos == 0) &&
18312 	    (un->un_state == ST_STATE_CLOSED) ||
18313 	    (un->un_state == ST_STATE_OPEN_PENDING_IO) ||
18314 	    (un->un_state == ST_STATE_CLOSING)) {
18315 		un->un_restore_pos = 1;
18316 	}
18317 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
18318 	    "reset and state was %d\n", un->un_state);
18319 	mutex_exit(ST_MUTEX);
18320 }
18321