xref: /titanic_50/usr/src/uts/common/io/scsi/targets/st.c (revision 7c64d3750da7fda7e450b8f9b0b963905ded6379)
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 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * SCSI	 SCSA-compliant and not-so-DDI-compliant Tape Driver
31  */
32 
33 #if defined(lint) && !defined(DEBUG)
34 #define	DEBUG	1
35 #endif
36 
37 #include <sys/modctl.h>
38 #include <sys/scsi/scsi.h>
39 #include <sys/mtio.h>
40 #include <sys/scsi/targets/stdef.h>
41 #include <sys/file.h>
42 #include <sys/kstat.h>
43 #include <sys/ddidmareq.h>
44 #include <sys/ddi.h>
45 #include <sys/sunddi.h>
46 #include <sys/byteorder.h>
47 
48 #define	IOSP	KSTAT_IO_PTR(un->un_stats)
49 /*
50  * stats maintained only for reads/writes as commands
51  * like rewind etc skew the wait/busy times
52  */
53 #define	IS_RW(bp) 	((bp)->b_bcount > 0)
54 #define	ST_DO_KSTATS(bp, kstat_function) \
55 	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
56 		kstat_function(IOSP); \
57 	}
58 
59 #define	ST_DO_ERRSTATS(un, x)  \
60 	if (un->un_errstats) { \
61 		struct st_errstats *stp; \
62 		stp = (struct st_errstats *)un->un_errstats->ks_data; \
63 		stp->x.value.ul++; \
64 	}
65 
66 #define	FILL_SCSI1_LUN(devp, pkt) 					\
67 	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
68 		int _lun;						\
69 		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
70 		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
71 		if (_lun > 0) {						\
72 			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
73 			    _lun;					\
74 		}							\
75 	}
76 
77 /*
78  * get an available contig mem header, cp.
79  * when big_enough is true, we will return NULL, if no big enough
80  * contig mem is found.
81  * when big_enough is false, we will try to find cp containing big
82  * enough contig mem. if not found, we will ruturn the last cp available.
83  *
84  * used by st_get_contig_mem()
85  */
86 #define	ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough) {		\
87 	struct contig_mem *tmp_cp = NULL;				\
88 	for ((cp) = (un)->un_contig_mem;				\
89 	    (cp) != NULL;						\
90 	    tmp_cp = (cp), (cp) = (cp)->cm_next) { 			\
91 		if (((cp)->cm_len >= (len)) || 				\
92 		    (!(big_enough) && ((cp)->cm_next == NULL))) { 	\
93 			if (tmp_cp == NULL) { 				\
94 				(un)->un_contig_mem = (cp)->cm_next; 	\
95 			} else { 					\
96 				tmp_cp->cm_next = (cp)->cm_next; 	\
97 			} 						\
98 			(cp)->cm_next = NULL; 				\
99 			(un)->un_contig_mem_available_num--; 		\
100 			break; 						\
101 		} 							\
102 	} 								\
103 }
104 
105 #define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
106 #define	COPY_POS(dest, source) bcopy(source, dest, sizeof (tapepos_t))
107 #define	ISALNUM(byte) \
108 	(((byte) >= 'a' && (byte) <= 'z') || \
109 	((byte) >= 'A' && (byte) <= 'Z') || \
110 	((byte) >= '0' && (byte) <= '9'))
111 
112 #define	ONE_K	1024
113 
114 /*
115  * Global External Data Definitions
116  */
117 extern struct scsi_key_strings scsi_cmds[];
118 extern uchar_t	scsi_cdb_size[];
119 
120 /*
121  * Local Static Data
122  */
123 static void *st_state;
124 static char *const st_label = "st";
125 static volatile dev_info_t *st_lastdev;
126 static volatile int st_recov_sz = sizeof (recov_info);
127 
128 #ifdef	__x86
129 /*
130  * We need to use below DMA attr to alloc physically contiguous
131  * memory to do I/O in big block size
132  */
133 static ddi_dma_attr_t st_contig_mem_dma_attr = {
134 	DMA_ATTR_V0,    /* version number */
135 	0x0,		/* lowest usable address */
136 	0xFFFFFFFFull,  /* high DMA address range */
137 	0xFFFFFFFFull,  /* DMA counter register */
138 	1,		/* DMA address alignment */
139 	1,		/* DMA burstsizes */
140 	1,		/* min effective DMA size */
141 	0xFFFFFFFFull,  /* max DMA xfer size */
142 	0xFFFFFFFFull,  /* segment boundary */
143 	1,		/* s/g list length */
144 	1,		/* granularity of device */
145 	0		/* DMA transfer flags */
146 };
147 
148 static ddi_device_acc_attr_t st_acc_attr = {
149 	DDI_DEVICE_ATTR_V0,
150 	DDI_NEVERSWAP_ACC,
151 	DDI_STRICTORDER_ACC
152 };
153 
154 /* set limitation for the number of contig_mem */
155 static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
156 #endif
157 
158 /*
159  * Tunable parameters
160  *
161  * DISCLAIMER
162  * ----------
163  * These parameters are intended for use only in system testing; if you use
164  * them in production systems, you do so at your own risk. Altering any
165  * variable not listed below may cause unpredictable system behavior.
166  *
167  * st_check_media_time
168  *
169  *   Three second state check
170  *
171  * st_allow_large_xfer
172  *
173  *   Gated with ST_NO_RECSIZE_LIMIT
174  *
175  *   0 - Transfers larger than 64KB will not be allowed
176  *       regardless of the setting of ST_NO_RECSIZE_LIMIT
177  *   1 - Transfers larger than 64KB will be allowed
178  *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
179  *
180  * st_report_soft_errors_on_close
181  *
182  *  Gated with ST_SOFT_ERROR_REPORTING
183  *
184  *  0 - Errors will not be reported on close regardless
185  *      of the setting of ST_SOFT_ERROR_REPORTING
186  *
187  *  1 - Errors will be reported on close if
188  *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
189  */
190 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
191 static int st_retry_count	= ST_RETRY_COUNT;
192 
193 static int st_io_time		= ST_IO_TIME;
194 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
195 
196 static int st_space_time	= ST_SPACE_TIME;
197 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
198 
199 static int st_error_level	= SCSI_ERR_RETRYABLE;
200 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
201 
202 static int st_max_throttle	= ST_MAX_THROTTLE;
203 
204 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
205 
206 static int st_allow_large_xfer = 1;
207 static int st_report_soft_errors_on_close = 1;
208 
209 /*
210  * End of tunable parameters list
211  */
212 
213 
214 
215 /*
216  * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
217  *
218  * Asynchronous I/O's main offering is that it is a non-blocking way to do
219  * reads and writes.  The driver will queue up all the requests it gets and
220  * have them ready to transport to the HBA.  Unfortunately, we cannot always
221  * just ship the I/O requests to the HBA, as there errors and exceptions
222  * that may happen when we don't want the HBA to continue.  Therein comes
223  * the flush-on-errors capability.  If the HBA supports it, then st will
224  * send in st_max_throttle I/O requests at the same time.
225  *
226  * Persistent errors : This was also reasonably simple.  In the interrupt
227  * routines, if there was an error or exception (FM, LEOT, media error,
228  * transport error), the persistent error bits are set and shuts everything
229  * down, but setting the throttle to zero.  If we hit and exception in the
230  * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
231  * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
232  * the appropriate error, and this will preserve order. Of course, depending
233  * on the exception we have to show a zero read or write before we show
234  * errors back to the application.
235  */
236 
237 extern const int st_ndrivetypes;	/* defined in st_conf.c */
238 extern const struct st_drivetype st_drivetypes[];
239 extern const char st_conf_version[];
240 
241 #ifdef STDEBUG
242 static int st_soft_error_report_debug = 0;
243 volatile int st_debug = 0;
244 #endif
245 
246 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
247 
248 static const struct vid_drivetype {
249 	char	*vid;
250 	char	type;
251 } st_vid_dt[] = {
252 	{"LTO-CVE ",	MT_LTO},
253 	{"QUANTUM ",    MT_ISDLT},
254 	{"SONY    ",    MT_ISAIT},
255 	{"STK     ",	MT_ISSTK9840}
256 };
257 
258 static const struct driver_minor_data {
259 	char	*name;
260 	int	minor;
261 } st_minor_data[] = {
262 	/*
263 	 * The top 4 entries are for the default densities,
264 	 * don't alter their position.
265 	 */
266 	{"",	0},
267 	{"n",	MT_NOREWIND},
268 	{"b",	MT_BSD},
269 	{"bn",	MT_NOREWIND | MT_BSD},
270 	{"l",	MT_DENSITY1},
271 	{"m",	MT_DENSITY2},
272 	{"h",	MT_DENSITY3},
273 	{"c",	MT_DENSITY4},
274 	{"u",	MT_DENSITY4},
275 	{"ln",	MT_DENSITY1 | MT_NOREWIND},
276 	{"mn",	MT_DENSITY2 | MT_NOREWIND},
277 	{"hn",	MT_DENSITY3 | MT_NOREWIND},
278 	{"cn",	MT_DENSITY4 | MT_NOREWIND},
279 	{"un",	MT_DENSITY4 | MT_NOREWIND},
280 	{"lb",	MT_DENSITY1 | MT_BSD},
281 	{"mb",	MT_DENSITY2 | MT_BSD},
282 	{"hb",	MT_DENSITY3 | MT_BSD},
283 	{"cb",	MT_DENSITY4 | MT_BSD},
284 	{"ub",	MT_DENSITY4 | MT_BSD},
285 	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
286 	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
287 	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
288 	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
289 	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
290 };
291 
292 /* strings used in many debug and warning messages */
293 static const char wr_str[]  = "write";
294 static const char rd_str[]  = "read";
295 static const char wrg_str[] = "writing";
296 static const char rdg_str[] = "reading";
297 static const char *space_strs[] = {
298 	"records",
299 	"filemarks",
300 	"sequential filemarks",
301 	"eod",
302 	"setmarks",
303 	"sequential setmarks",
304 	"Reserved",
305 	"Reserved"
306 };
307 static const char *load_strs[] = {
308 	"unload",		/* LD_UNLOAD		0 */
309 	"load",			/* LD_LOAD		1 */
310 	"retension",		/* LD_RETEN		2 */
311 	"load reten",		/* LD_LOAD | LD_RETEN	3 */
312 	"eod",			/* LD_EOT		4 */
313 	"load EOD",		/* LD_LOAD | LD_EOT	5 */
314 	"reten EOD",		/* LD_RETEN | LD_EOT	6 */
315 	"load reten EOD"	/* LD_LOAD|LD_RETEN|LD_EOT 7 */
316 	"hold",			/* LD_HOLD		8 */
317 	"load and hold"		/* LD_LOAD | LD_HOLD	9 */
318 };
319 
320 const char *bogusID = "Unknown Media ID";
321 
322 /* default density offsets in the table above */
323 #define	DEF_BLANK	0
324 #define	DEF_NOREWIND	1
325 #define	DEF_BSD		2
326 #define	DEF_BSD_NR	3
327 
328 /* Sense Key, ASC/ASCQ for which tape ejection is needed */
329 
330 static struct tape_failure_code {
331 	uchar_t key;
332 	uchar_t add_code;
333 	uchar_t qual_code;
334 } st_tape_failure_code[] = {
335 	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
336 	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
337 	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
338 	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
339 	{ KEY_NOT_READY, 0x53, 0x00},
340 	{ 0xff}
341 };
342 
343 /*  clean bit position and mask */
344 
345 static struct cln_bit_position {
346 	ushort_t cln_bit_byte;
347 	uchar_t cln_bit_mask;
348 } st_cln_bit_position[] = {
349 	{ 21, 0x08},
350 	{ 70, 0xc0},
351 	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
352 };
353 
354 /*
355  * architecture dependent allocation restrictions. For x86, we'll set
356  * dma_attr_addr_hi to st_max_phys_addr and dma_attr_sgllen to
357  * st_sgl_size during _init().
358  */
359 #if defined(__sparc)
360 static ddi_dma_attr_t st_alloc_attr = {
361 	DMA_ATTR_V0,	/* version number */
362 	0x0,		/* lowest usable address */
363 	0xFFFFFFFFull,	/* high DMA address range */
364 	0xFFFFFFFFull,	/* DMA counter register */
365 	1,		/* DMA address alignment */
366 	1,		/* DMA burstsizes */
367 	1,		/* min effective DMA size */
368 	0xFFFFFFFFull,	/* max DMA xfer size */
369 	0xFFFFFFFFull,	/* segment boundary */
370 	1,		/* s/g list length */
371 	512,		/* granularity of device */
372 	0		/* DMA transfer flags */
373 };
374 #elif defined(__x86)
375 static ddi_dma_attr_t st_alloc_attr = {
376 	DMA_ATTR_V0,	/* version number */
377 	0x0,		/* lowest usable address */
378 	0x0,		/* high DMA address range [set in _init()] */
379 	0xFFFFull,	/* DMA counter register */
380 	512,		/* DMA address alignment */
381 	1,		/* DMA burstsizes */
382 	1,		/* min effective DMA size */
383 	0xFFFFFFFFull,	/* max DMA xfer size */
384 	0xFFFFFFFFull,  /* segment boundary */
385 	0,		/* s/g list length */
386 	512,		/* granularity of device [set in _init()] */
387 	0		/* DMA transfer flags */
388 };
389 uint64_t st_max_phys_addr = 0xFFFFFFFFull;
390 int st_sgl_size = 0xF;
391 
392 #endif
393 
394 /*
395  * Configuration Data:
396  *
397  * Device driver ops vector
398  */
399 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
400 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
401 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
402 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
403 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
404 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
405 static int st_strategy(struct buf *bp);
406 static int st_queued_strategy(buf_t *bp);
407 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
408 	cred_t *cred_p, int *rval_p);
409 extern int nulldev(), nodev();
410 
411 static struct cb_ops st_cb_ops = {
412 	st_open,		/* open */
413 	st_close,		/* close */
414 	st_queued_strategy,	/* strategy Not Block device but async checks */
415 	nodev,			/* print */
416 	nodev,			/* dump */
417 	st_read,		/* read */
418 	st_write,		/* write */
419 	st_ioctl,		/* ioctl */
420 	nodev,			/* devmap */
421 	nodev,			/* mmap */
422 	nodev,			/* segmap */
423 	nochpoll,		/* poll */
424 	ddi_prop_op,		/* cb_prop_op */
425 	0,			/* streamtab  */
426 	D_64BIT | D_MP | D_NEW | D_HOTPLUG |
427 	D_OPEN_RETURNS_EINTR,	/* cb_flag */
428 	CB_REV,			/* cb_rev */
429 	st_aread, 		/* async I/O read entry point */
430 	st_awrite		/* async I/O write entry point */
431 
432 };
433 
434 static int st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
435 		void **result);
436 static int st_probe(dev_info_t *dev);
437 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
438 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
439 
440 static struct dev_ops st_ops = {
441 	DEVO_REV,		/* devo_rev, */
442 	0,			/* refcnt  */
443 	st_info,		/* info */
444 	nulldev,		/* identify */
445 	st_probe,		/* probe */
446 	st_attach,		/* attach */
447 	st_detach,		/* detach */
448 	nodev,			/* reset */
449 	&st_cb_ops,		/* driver operations */
450 	(struct bus_ops *)0,	/* bus operations */
451 	nulldev			/* power */
452 };
453 
454 /*
455  * Local Function Declarations
456  */
457 static char *st_print_scsi_cmd(char cmd);
458 static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
459     char *title, char *cdb);
460 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
461     char *title, char *data, int len);
462 static int st_doattach(struct scsi_device *devp, int (*canwait)());
463 static void st_known_tape_type(struct scsi_tape *un);
464 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
465     struct st_drivetype *);
466 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
467     struct st_drivetype *);
468 static int st_get_conf_from_tape_drive(struct scsi_tape *, char *,
469     struct st_drivetype *);
470 static int st_get_densities_from_tape_drive(struct scsi_tape *,
471     struct st_drivetype *);
472 static int st_get_timeout_values_from_tape_drive(struct scsi_tape *,
473     struct st_drivetype *);
474 static int st_get_timeouts_value(struct scsi_tape *, uchar_t, ushort_t *,
475     ushort_t);
476 static int st_get_default_conf(struct scsi_tape *, char *,
477     struct st_drivetype *);
478 static int st_rw(dev_t dev, struct uio *uio, int flag);
479 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
480 static int st_find_eod(struct scsi_tape *un);
481 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
482 static int st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *, int flag);
483 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
484 static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
485 static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
486 static void st_start(struct scsi_tape *un);
487 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
488     clock_t timeout_interval, int queued);
489 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
490     clock_t timeout_interval);
491 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
492 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
493 static void st_init(struct scsi_tape *un);
494 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
495     int (*func)(caddr_t));
496 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
497     struct buf *bp, int (*func)(caddr_t));
498 static void st_intr(struct scsi_pkt *pkt);
499 static void st_set_state(struct scsi_tape *un, buf_t *bp);
500 static void st_test_append(struct buf *bp);
501 static int st_runout(caddr_t);
502 static int st_cmd(struct scsi_tape *un, int com, int64_t count, int wait);
503 static int st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com,
504     int64_t count);
505 static int st_set_compression(struct scsi_tape *un);
506 static int st_write_fm(dev_t dev, int wfm);
507 static int st_determine_generic(struct scsi_tape *un);
508 static int st_determine_density(struct scsi_tape *un, int rw);
509 static int st_get_density(struct scsi_tape *un);
510 static int st_set_density(struct scsi_tape *un);
511 static int st_loadtape(struct scsi_tape *un);
512 static int st_modesense(struct scsi_tape *un);
513 static int st_modeselect(struct scsi_tape *un);
514 static errstate st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
515 static int st_wrongtapetype(struct scsi_tape *un);
516 static errstate st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
517 static errstate st_handle_sense(struct scsi_tape *un, struct buf *bp,
518     tapepos_t *);
519 static errstate st_handle_autosense(struct scsi_tape *un, struct buf *bp,
520     tapepos_t *);
521 static int st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag);
522 static void st_update_error_stack(struct scsi_tape *un, struct scsi_pkt *pkt,
523     struct scsi_arq_status *cmd);
524 static void st_empty_error_stack(struct scsi_tape *un);
525 static errstate st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
526     struct scsi_status *, tapepos_t *);
527 static int st_report_soft_errors(dev_t dev, int flag);
528 static void st_delayed_cv_broadcast(void *arg);
529 static int st_check_media(dev_t dev, enum mtio_state state);
530 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
531 static void st_intr_restart(void *arg);
532 static void st_start_restart(void *arg);
533 static int st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
534     struct seq_mode *page_data, int page_size);
535 static int st_change_block_size(struct scsi_tape *un, uint32_t nblksz);
536 static int st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
537     struct seq_mode *page_data, int page_size);
538 static int st_read_block_limits(struct scsi_tape *un,
539     struct read_blklim *read_blk);
540 static int st_report_density_support(struct scsi_tape *un,
541     uchar_t *density_data, size_t buflen);
542 static int st_report_supported_operation(struct scsi_tape *un,
543     uchar_t *oper_data, uchar_t option_code, ushort_t service_action);
544 static int st_tape_init(struct scsi_tape *un);
545 static void st_flush(struct scsi_tape *un);
546 static void st_set_pe_errno(struct scsi_tape *un);
547 static void st_hba_unflush(struct scsi_tape *un);
548 static void st_turn_pe_on(struct scsi_tape *un);
549 static void st_turn_pe_off(struct scsi_tape *un);
550 static void st_set_pe_flag(struct scsi_tape *un);
551 static void st_clear_pe(struct scsi_tape *un);
552 static void st_wait_for_io(struct scsi_tape *un);
553 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
554 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
555 static int st_reserve_release(struct scsi_tape *un, int command, ubufunc_t ubf);
556 static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb);
557 static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
558     int count);
559 static int st_take_ownership(struct scsi_tape *un);
560 static int st_check_asc_ascq(struct scsi_tape *un);
561 static int st_check_clean_bit(struct scsi_tape *un);
562 static int st_check_alert_flags(struct scsi_tape *un);
563 static int st_check_sequential_clean_bit(struct scsi_tape *un);
564 static int st_check_sense_clean_bit(struct scsi_tape *un);
565 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
566 static void st_calculate_timeouts(struct scsi_tape *un);
567 static writablity st_is_drive_worm(struct scsi_tape *un);
568 static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
569     void *buf, size_t size, ubufunc_t bufunc);
570 static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
571     caddr_t dest, uchar_t page);
572 static int st_update_block_pos(struct scsi_tape *un, bufunc_t bf,
573     int post_space);
574 static int st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
575     read_p_types type, size_t data_sz, const caddr_t responce, int post_space);
576 static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
577 static int st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf,
578     tapepos_t *pos, uint64_t lblk, uchar_t partition);
579 static int st_mtfsf_ioctl(struct scsi_tape *un, int files);
580 static int st_mtfsr_ioctl(struct scsi_tape *un, int count);
581 static int st_mtbsf_ioctl(struct scsi_tape *un, int files);
582 static int st_mtnbsf_ioctl(struct scsi_tape *un, int count);
583 static int st_mtbsr_ioctl(struct scsi_tape *un, int num);
584 static int st_mtfsfm_ioctl(struct scsi_tape *un, int cnt);
585 static int st_mtbsfm_ioctl(struct scsi_tape *un, int cnt);
586 static int st_backward_space_files(struct scsi_tape *un, int count,
587     int infront);
588 static int st_forward_space_files(struct scsi_tape *un, int files);
589 static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
590     int32_t fileno);
591 static int st_space_to_begining_of_file(struct scsi_tape *un);
592 static int st_space_records(struct scsi_tape *un, int records);
593 static int st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc);
594 static errstate st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
595     errstate onentry);
596 static void st_recover(void *arg);
597 static void st_recov_cb(struct scsi_pkt *pkt);
598 static int st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait);
599 static int st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
600     int flag);
601 static void st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
602     struct scsi_pkt *cmd);
603 static int st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf);
604 static int st_test_path_to_device(struct scsi_tape *un);
605 static int st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
606     read_pos_data_t *raw);
607 static int st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
608     read_pos_data_t *raw);
609 static int st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
610     cmd_attribute const * cmd_att, tapepos_t *read);
611 static errstate st_recover_reissue_pkt(struct scsi_tape *us,
612     struct scsi_pkt *pkt);
613 static int st_transport(struct scsi_tape *un, struct scsi_pkt *pkt);
614 static buf_t *st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp);
615 static void st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp);
616 static int st_reset(struct scsi_tape *un, int reset_type);
617 static void st_reset_notification(caddr_t arg);
618 static const cmd_attribute *st_lookup_cmd_attribute(unsigned char cmd);
619 
620 #ifdef	__x86
621 /*
622  * routines for I/O in big block size
623  */
624 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
625 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
626     int alloc_flags);
627 static int st_bigblk_xfer_done(struct buf *bp);
628 static struct buf *st_get_bigblk_bp(struct buf *bp);
629 #endif
630 static void st_print_position(dev_info_t *dev, char *label, uint_t level,
631     const char *comment, tapepos_t *pos);
632 
633 /*
634  * error statistics create/update functions
635  */
636 static int st_create_errstats(struct scsi_tape *, int);
637 static int st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf,
638     tapepos_t *pos);
639 
640 #ifdef STDEBUG
641 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
642 static char *st_dev_name(dev_t dev);
643 #endif /* STDEBUG */
644 
645 #if !defined(lint)
646 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
647     scsi_pkt buf uio scsi_cdb uscsi_cmd))
648 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
649 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
650 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
651 #endif
652 
653 /*
654  * autoconfiguration routines.
655  */
656 char _depends_on[] = "misc/scsi";
657 
658 static struct modldrv modldrv = {
659 	&mod_driverops,		/* Type of module. This one is a driver */
660 	"SCSI tape Driver %I%", /* Name of the module. */
661 	&st_ops			/* driver ops */
662 };
663 
664 static struct modlinkage modlinkage = {
665 	MODREV_1, &modldrv, NULL
666 };
667 
668 /*
669  * Notes on Post Reset Behavior in the tape driver:
670  *
671  * When the tape drive is opened, the driver  attempts  to make sure that
672  * the tape head is positioned exactly where it was left when it was last
673  * closed  provided  the  medium  is not  changed.  If the tape  drive is
674  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
675  * of position due to reset) will happen when the first tape operation or
676  * I/O occurs.  The repositioning (if required) may not be possible under
677  * certain situations such as when the device firmware not able to report
678  * the medium  change in the REQUEST  SENSE data  because of a reset or a
679  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
680  * extraordinary  situations, where the driver fails to position the head
681  * at its  original  position,  it will fail the open the first  time, to
682  * save the applications from overwriting the data.  All further attempts
683  * to open the tape device will result in the driver  attempting  to load
684  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
685  * indicate  that further  attempts to open the tape device may result in
686  * the tape being  loaded at BOT will be printed on the  console.  If the
687  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
688  * original tape head  position,  will result in the failure of the first
689  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
690  * internal tape position  which will  necessitate  the  applications  to
691  * validate the position by using either a tape  positioning  ioctl (such
692  * as MTREW) or closing and reopening the tape device.
693  *
694  */
695 
696 int
697 _init(void)
698 {
699 	int e;
700 
701 	if (((e = ddi_soft_state_init(&st_state,
702 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
703 		return (e);
704 	}
705 
706 	if ((e = mod_install(&modlinkage)) != 0) {
707 		ddi_soft_state_fini(&st_state);
708 	}
709 
710 #if defined(__x86)
711 	/* set the max physical address for iob allocs on x86 */
712 	st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
713 
714 	/*
715 	 * set the sgllen for iob allocs on x86. If this is set less than
716 	 * the number of pages the buffer will take (taking into account
717 	 * alignment), it would force the allocator to try and allocate
718 	 * contiguous pages.
719 	 */
720 	st_alloc_attr.dma_attr_sgllen = st_sgl_size;
721 #endif
722 
723 	return (e);
724 }
725 
726 int
727 _fini(void)
728 {
729 	int e;
730 
731 	if ((e = mod_remove(&modlinkage)) != 0) {
732 		return (e);
733 	}
734 
735 	ddi_soft_state_fini(&st_state);
736 
737 	return (e);
738 }
739 
740 int
741 _info(struct modinfo *modinfop)
742 {
743 	return (mod_info(&modlinkage, modinfop));
744 }
745 
746 
747 static int
748 st_probe(dev_info_t *devi)
749 {
750 	int instance;
751 	struct scsi_device *devp;
752 	int rval;
753 
754 #if !defined(__sparc)
755 	char    *tape_prop;
756 	int	tape_prop_len;
757 #endif
758 
759 	ST_ENTR(devi, st_probe);
760 
761 	/* If self identifying device */
762 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
763 		return (DDI_PROBE_DONTCARE);
764 	}
765 
766 #if !defined(__sparc)
767 	/*
768 	 * Since some x86 HBAs have devnodes that look like SCSI as
769 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
770 	 * we check for the presence of the "tape" property.
771 	 */
772 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
773 	    DDI_PROP_CANSLEEP, "tape",
774 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
775 		return (DDI_PROBE_FAILURE);
776 	}
777 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
778 		kmem_free(tape_prop, tape_prop_len);
779 		return (DDI_PROBE_FAILURE);
780 	}
781 	kmem_free(tape_prop, tape_prop_len);
782 #endif
783 
784 	devp = ddi_get_driver_private(devi);
785 	instance = ddi_get_instance(devi);
786 
787 	if (ddi_get_soft_state(st_state, instance) != NULL) {
788 		return (DDI_PROBE_PARTIAL);
789 	}
790 
791 
792 	/*
793 	 * Turn around and call probe routine to see whether
794 	 * we actually have a tape at this SCSI nexus.
795 	 */
796 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
797 
798 		/*
799 		 * In checking the whole inq_dtype byte we are looking at both
800 		 * the Peripheral Qualifier and the Peripheral Device Type.
801 		 * For this driver we are only interested in sequential devices
802 		 * that are connected or capable if connecting to this logical
803 		 * unit.
804 		 */
805 		if (devp->sd_inq->inq_dtype ==
806 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
807 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
808 			    "probe exists\n");
809 			rval = DDI_PROBE_SUCCESS;
810 		} else {
811 			rval = DDI_PROBE_FAILURE;
812 		}
813 	} else {
814 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
815 		    "probe failure: nothing there\n");
816 		rval = DDI_PROBE_FAILURE;
817 	}
818 	scsi_unprobe(devp);
819 	return (rval);
820 }
821 
822 static int
823 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
824 {
825 	int 	instance;
826 	int	wide;
827 	int 	dev_instance;
828 	int	ret_status;
829 	struct	scsi_device *devp;
830 	int	node_ix;
831 	struct	scsi_tape *un;
832 
833 	ST_ENTR(devi, st_attach);
834 
835 	devp = ddi_get_driver_private(devi);
836 	instance = ddi_get_instance(devi);
837 
838 	switch (cmd) {
839 		case DDI_ATTACH:
840 			if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
841 			    "tape-command-recovery-disable", 0) != 0) {
842 				st_recov_sz = sizeof (pkt_info);
843 			}
844 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
845 				return (DDI_FAILURE);
846 			}
847 			break;
848 		case DDI_RESUME:
849 			/*
850 			 * Suspend/Resume
851 			 *
852 			 * When the driver suspended, there might be
853 			 * outstanding cmds and therefore we need to
854 			 * reset the suspended flag and resume the scsi
855 			 * watch thread and restart commands and timeouts
856 			 */
857 
858 			if (!(un = ddi_get_soft_state(st_state, instance))) {
859 				return (DDI_FAILURE);
860 			}
861 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
862 			    un->un_dev);
863 
864 			mutex_enter(ST_MUTEX);
865 
866 			un->un_throttle = un->un_max_throttle;
867 			un->un_tids_at_suspend = 0;
868 			un->un_pwr_mgmt = ST_PWR_NORMAL;
869 
870 			if (un->un_swr_token) {
871 				scsi_watch_resume(un->un_swr_token);
872 			}
873 
874 			/*
875 			 * Restart timeouts
876 			 */
877 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
878 				mutex_exit(ST_MUTEX);
879 				un->un_delay_tid = timeout(
880 				    st_delayed_cv_broadcast, un,
881 				    drv_usectohz((clock_t)
882 				    MEDIA_ACCESS_DELAY));
883 				mutex_enter(ST_MUTEX);
884 			}
885 
886 			if (un->un_tids_at_suspend & ST_HIB_TID) {
887 				mutex_exit(ST_MUTEX);
888 				un->un_hib_tid = timeout(st_intr_restart, un,
889 				    ST_STATUS_BUSY_TIMEOUT);
890 				mutex_enter(ST_MUTEX);
891 			}
892 
893 			ret_status = st_clear_unit_attentions(dev_instance, 5);
894 
895 			/*
896 			 * now check if we need to restore the tape position
897 			 */
898 			if ((un->un_suspend_pos.pmode != invalid) &&
899 			    ((un->un_suspend_pos.fileno > 0) ||
900 			    (un->un_suspend_pos.blkno > 0)) ||
901 			    (un->un_suspend_pos.lgclblkno > 0)) {
902 				if (ret_status != 0) {
903 					/*
904 					 * tape didn't get good TUR
905 					 * just print out error messages
906 					 */
907 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
908 					    "st_attach-RESUME: tape failure "
909 					    " tape position will be lost");
910 				} else {
911 					/* this prints errors */
912 					(void) st_validate_tapemarks(un,
913 					    st_uscsi_cmd, &un->un_suspend_pos);
914 				}
915 				/*
916 				 * there are no retries, if there is an error
917 				 * we don't know if the tape has changed
918 				 */
919 				un->un_suspend_pos.pmode = invalid;
920 			}
921 
922 			/* now we are ready to start up any queued I/Os */
923 			if (un->un_ncmds || un->un_quef) {
924 				st_start(un);
925 			}
926 
927 			cv_broadcast(&un->un_suspend_cv);
928 			mutex_exit(ST_MUTEX);
929 			return (DDI_SUCCESS);
930 
931 		default:
932 			return (DDI_FAILURE);
933 	}
934 
935 	un = ddi_get_soft_state(st_state, instance);
936 
937 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
938 	    "st_attach: instance=%x\n", instance);
939 
940 	/*
941 	 * Add a zero-length attribute to tell the world we support
942 	 * kernel ioctls (for layered drivers)
943 	 */
944 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
945 	    DDI_KERNEL_IOCTL, NULL, 0);
946 
947 	ddi_report_dev((dev_info_t *)devi);
948 
949 	/*
950 	 * If it's a SCSI-2 tape drive which supports wide,
951 	 * tell the host adapter to use wide.
952 	 */
953 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
954 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
955 
956 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
957 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
958 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
959 	}
960 
961 	/*
962 	 * enable autorequest sense; keep the rq packet around in case
963 	 * the autorequest sense fails because of a busy condition
964 	 * do a getcap first in case the capability is not variable
965 	 */
966 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
967 		un->un_arq_enabled = 1;
968 	} else {
969 		un->un_arq_enabled =
970 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
971 	}
972 
973 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
974 	    (un->un_arq_enabled ? "enabled" : "disabled"));
975 
976 	un->un_untagged_qing =
977 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
978 
979 	/*
980 	 * XXX - This is just for 2.6.  to tell users that write buffering
981 	 *	has gone away.
982 	 */
983 	if (un->un_arq_enabled && un->un_untagged_qing) {
984 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
985 		    "tape-driver-buffering", 0) != 0) {
986 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
987 			    "Write Data Buffering has been depricated. Your "
988 			    "applications should continue to work normally.\n"
989 			    " But, they should  ported to use Asynchronous "
990 			    " I/O\n"
991 			    " For more information, read about "
992 			    " tape-driver-buffering "
993 			    "property in the st(7d) man page\n");
994 		}
995 	}
996 
997 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
998 	un->un_flush_on_errors = 0;
999 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
1000 
1001 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
1002 	    "throttle=%x, max_throttle = %x\n",
1003 	    un->un_throttle, un->un_max_throttle);
1004 
1005 	/* initialize persistent errors to nil */
1006 	un->un_persistence = 0;
1007 	un->un_persist_errors = 0;
1008 
1009 	/*
1010 	 * Get dma-max from HBA driver. If it is not defined, use 64k
1011 	 */
1012 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
1013 	if (un->un_maxdma == -1) {
1014 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1015 		    "Received a value that looked like -1. Using 64k maxdma");
1016 		un->un_maxdma = (64 * ONE_K);
1017 	}
1018 
1019 #ifdef	__x86
1020 	/*
1021 	 * for x86, the device may be able to DMA more than the system will
1022 	 * allow under some circumstances. We need account for both the HBA's
1023 	 * and system's contraints.
1024 	 *
1025 	 * Get the maximum DMA under worse case conditions. e.g. looking at the
1026 	 * device constraints, the max copy buffer size, and the worse case
1027 	 * fragmentation. NOTE: this may differ from dma-max since dma-max
1028 	 * doesn't take the worse case framentation into account.
1029 	 *
1030 	 * e.g. a device may be able to DMA 16MBytes, but can only DMA 1MByte
1031 	 * if none of the pages are contiguous. Keeping track of both of these
1032 	 * values allows us to support larger tape block sizes on some devices.
1033 	 */
1034 	un->un_maxdma_arch = scsi_ifgetcap(&devp->sd_address, "dma-max-arch",
1035 	    1);
1036 
1037 	/*
1038 	 * If the dma-max-arch capability is not implemented, or the value
1039 	 * comes back higher than what was reported in dma-max, use dma-max.
1040 	 */
1041 	if ((un->un_maxdma_arch == -1) ||
1042 	    ((uint_t)un->un_maxdma < (uint_t)un->un_maxdma_arch)) {
1043 		un->un_maxdma_arch = un->un_maxdma;
1044 	}
1045 #endif
1046 
1047 	/*
1048 	 * Get the max allowable cdb size
1049 	 */
1050 	un->un_max_cdb_sz =
1051 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
1052 	if (un->un_max_cdb_sz < CDB_GROUP0) {
1053 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1054 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
1055 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
1056 	}
1057 
1058 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1059 
1060 	un->un_mediastate = MTIO_NONE;
1061 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1062 
1063 	/*
1064 	 * initialize kstats
1065 	 */
1066 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1067 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1068 	if (un->un_stats) {
1069 		un->un_stats->ks_lock = ST_MUTEX;
1070 		kstat_install(un->un_stats);
1071 	}
1072 	(void) st_create_errstats(un, instance);
1073 
1074 	/*
1075 	 * find the drive type for this target
1076 	 */
1077 	mutex_enter(ST_MUTEX);
1078 	un->un_dev = MT_TEM_DEV(instance);
1079 	st_known_tape_type(un);
1080 	un->un_dev = 0;
1081 	mutex_exit(ST_MUTEX);
1082 
1083 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
1084 		int minor;
1085 		char *name;
1086 
1087 		name  = st_minor_data[node_ix].name;
1088 		minor = st_minor_data[node_ix].minor;
1089 
1090 		/*
1091 		 * For default devices set the density to the
1092 		 * preferred default density for this device.
1093 		 */
1094 		if (node_ix <= DEF_BSD_NR) {
1095 			minor |= un->un_dp->default_density;
1096 		}
1097 		minor |= MTMINOR(instance);
1098 
1099 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
1100 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
1101 			continue;
1102 		}
1103 
1104 		ddi_remove_minor_node(devi, NULL);
1105 
1106 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1107 		    st_reset_notification, (caddr_t)un);
1108 		cv_destroy(&un->un_clscv);
1109 		cv_destroy(&un->un_sbuf_cv);
1110 		cv_destroy(&un->un_queue_cv);
1111 		cv_destroy(&un->un_state_cv);
1112 #ifdef	__x86
1113 		cv_destroy(&un->un_contig_mem_cv);
1114 #endif
1115 		cv_destroy(&un->un_suspend_cv);
1116 		cv_destroy(&un->un_tape_busy_cv);
1117 		cv_destroy(&un->un_recov_buf_cv);
1118 		if (un->un_recov_taskq) {
1119 			ddi_taskq_destroy(un->un_recov_taskq);
1120 		}
1121 		if (un->un_sbufp) {
1122 			freerbuf(un->un_sbufp);
1123 		}
1124 		if (un->un_recov_buf) {
1125 			freerbuf(un->un_recov_buf);
1126 		}
1127 		if (un->un_uscsi_rqs_buf) {
1128 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1129 		}
1130 		if (un->un_mspl) {
1131 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1132 		}
1133 		if (un->un_dp_size) {
1134 			kmem_free(un->un_dp, un->un_dp_size);
1135 		}
1136 		if (un->un_state) {
1137 			kstat_delete(un->un_stats);
1138 		}
1139 		if (un->un_errstats) {
1140 			kstat_delete(un->un_errstats);
1141 		}
1142 
1143 		scsi_destroy_pkt(un->un_rqs);
1144 		scsi_free_consistent_buf(un->un_rqs_bp);
1145 		ddi_soft_state_free(st_state, instance);
1146 		devp->sd_private = NULL;
1147 		devp->sd_sense = NULL;
1148 
1149 		ddi_prop_remove_all(devi);
1150 		return (DDI_FAILURE);
1151 	}
1152 
1153 	return (DDI_SUCCESS);
1154 }
1155 
1156 /*
1157  * st_detach:
1158  *
1159  * we allow a detach if and only if:
1160  *	- no tape is currently inserted
1161  *	- tape position is at BOT or unknown
1162  *		(if it is not at BOT then a no rewind
1163  *		device was opened and we have to preserve state)
1164  *	- it must be in a closed state : no timeouts or scsi_watch requests
1165  *		will exist if it is closed, so we don't need to check for
1166  *		them here.
1167  */
1168 /*ARGSUSED*/
1169 static int
1170 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1171 {
1172 	int 	instance;
1173 	struct scsi_device *devp;
1174 	struct scsi_tape *un;
1175 	clock_t wait_cmds_complete;
1176 
1177 	ST_ENTR(devi, st_detach);
1178 
1179 	instance = ddi_get_instance(devi);
1180 
1181 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1182 		return (DDI_FAILURE);
1183 	}
1184 
1185 	mutex_enter(ST_MUTEX);
1186 
1187 	/*
1188 	 * Clear error entry stack
1189 	 */
1190 	st_empty_error_stack(un);
1191 
1192 	mutex_exit(ST_MUTEX);
1193 
1194 	switch (cmd) {
1195 
1196 	case DDI_DETACH:
1197 		/*
1198 		 * Undo what we did in st_attach & st_doattach,
1199 		 * freeing resources and removing things we installed.
1200 		 * The system framework guarantees we are not active
1201 		 * with this devinfo node in any other entry points at
1202 		 * this time.
1203 		 */
1204 
1205 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1206 		    "st_detach: instance=%x, un=%p\n", instance,
1207 		    (void *)un);
1208 
1209 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1210 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1211 		    (un->un_state != ST_STATE_CLOSED)) {
1212 			/*
1213 			 * we cannot unload some targets because the
1214 			 * inquiry returns junk unless immediately
1215 			 * after a reset
1216 			 */
1217 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1218 			    "cannot unload instance %x\n", instance);
1219 			return (DDI_FAILURE);
1220 		}
1221 
1222 		/*
1223 		 * if the tape has been removed then we may unload;
1224 		 * do a test unit ready and if it returns NOT READY
1225 		 * then we assume that it is safe to unload.
1226 		 * as a side effect, pmode may be set to invalid if the
1227 		 * the test unit ready fails;
1228 		 * also un_state may be set to non-closed, so reset it
1229 		 */
1230 		if ((un->un_dev) &&		/* Been opened since attach */
1231 		    ((un->un_pos.pmode == legacy) &&
1232 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1233 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1234 		    ((un->un_pos.pmode == logical) &&
1235 		    (un->un_pos.lgclblkno > 0))) {
1236 			mutex_enter(ST_MUTEX);
1237 			/*
1238 			 * Send Test Unit Ready in the hopes that if
1239 			 * the drive is not in the state we think it is.
1240 			 * And the state will be changed so it can be detached.
1241 			 * If the command fails to reach the device and
1242 			 * the drive was not rewound or unloaded we want
1243 			 * to fail the detach till a user command fails
1244 			 * where after the detach will succead.
1245 			 */
1246 			(void) st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
1247 			/*
1248 			 * After TUR un_state may be set to non-closed,
1249 			 * so reset it back.
1250 			 */
1251 			un->un_state = ST_STATE_CLOSED;
1252 			mutex_exit(ST_MUTEX);
1253 		}
1254 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1255 		    "un_status=%x, fileno=%x, blkno=%x\n",
1256 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1257 
1258 		/*
1259 		 * check again:
1260 		 * if we are not at BOT then it is not safe to unload
1261 		 */
1262 		if ((un->un_dev) &&		/* Been opened since attach */
1263 		    (((un->un_pos.pmode == legacy) &&
1264 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1265 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1266 		    ((un->un_pos.pmode == logical) &&
1267 		    (un->un_pos.lgclblkno > 0)))) {
1268 
1269 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1270 			    "cannot detach: pmode=%d fileno=0x%x, blkno=0x%x"
1271 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1272 			    un->un_pos.fileno, un->un_pos.blkno,
1273 			    un->un_pos.lgclblkno);
1274 			return (DDI_FAILURE);
1275 		}
1276 
1277 		/*
1278 		 * Just To make sure that we have released the
1279 		 * tape unit .
1280 		 */
1281 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1282 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1283 			mutex_enter(ST_MUTEX);
1284 			(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
1285 			mutex_exit(ST_MUTEX);
1286 		}
1287 
1288 		/*
1289 		 * now remove other data structures allocated in st_doattach()
1290 		 */
1291 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1292 		    "destroying/freeing\n");
1293 
1294 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1295 		    st_reset_notification, (caddr_t)un);
1296 		cv_destroy(&un->un_clscv);
1297 		cv_destroy(&un->un_sbuf_cv);
1298 		cv_destroy(&un->un_queue_cv);
1299 		cv_destroy(&un->un_suspend_cv);
1300 		cv_destroy(&un->un_tape_busy_cv);
1301 		cv_destroy(&un->un_recov_buf_cv);
1302 
1303 		if (un->un_recov_taskq) {
1304 			ddi_taskq_destroy(un->un_recov_taskq);
1305 		}
1306 
1307 		if (un->un_hib_tid) {
1308 			(void) untimeout(un->un_hib_tid);
1309 			un->un_hib_tid = 0;
1310 		}
1311 
1312 		if (un->un_delay_tid) {
1313 			(void) untimeout(un->un_delay_tid);
1314 			un->un_delay_tid = 0;
1315 		}
1316 		cv_destroy(&un->un_state_cv);
1317 
1318 #ifdef	__x86
1319 		cv_destroy(&un->un_contig_mem_cv);
1320 
1321 		if (un->un_contig_mem_hdl != NULL) {
1322 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1323 		}
1324 #endif
1325 		if (un->un_sbufp) {
1326 			freerbuf(un->un_sbufp);
1327 		}
1328 		if (un->un_recov_buf) {
1329 			freerbuf(un->un_recov_buf);
1330 		}
1331 		if (un->un_uscsi_rqs_buf) {
1332 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1333 		}
1334 		if (un->un_mspl) {
1335 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1336 		}
1337 		if (un->un_rqs) {
1338 			scsi_destroy_pkt(un->un_rqs);
1339 			scsi_free_consistent_buf(un->un_rqs_bp);
1340 		}
1341 		if (un->un_mkr_pkt) {
1342 			scsi_destroy_pkt(un->un_mkr_pkt);
1343 		}
1344 		if (un->un_arq_enabled) {
1345 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1346 		}
1347 		if (un->un_dp_size) {
1348 			kmem_free(un->un_dp, un->un_dp_size);
1349 		}
1350 		if (un->un_stats) {
1351 			kstat_delete(un->un_stats);
1352 			un->un_stats = (kstat_t *)0;
1353 		}
1354 		if (un->un_errstats) {
1355 			kstat_delete(un->un_errstats);
1356 			un->un_errstats = (kstat_t *)0;
1357 		}
1358 		if (un->un_media_id_len) {
1359 			kmem_free(un->un_media_id, un->un_media_id_len);
1360 		}
1361 		devp = ST_SCSI_DEVP;
1362 		ddi_soft_state_free(st_state, instance);
1363 		devp->sd_private = NULL;
1364 		devp->sd_sense = NULL;
1365 		scsi_unprobe(devp);
1366 		ddi_prop_remove_all(devi);
1367 		ddi_remove_minor_node(devi, NULL);
1368 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1369 		return (DDI_SUCCESS);
1370 
1371 	case DDI_SUSPEND:
1372 
1373 		/*
1374 		 * Suspend/Resume
1375 		 *
1376 		 * To process DDI_SUSPEND, we must do the following:
1377 		 *
1378 		 *  - check ddi_removing_power to see if power will be turned
1379 		 *    off. if so, return DDI_FAILURE
1380 		 *  - check if we are already suspended,
1381 		 *    if so, return DDI_FAILURE
1382 		 *  - check if device state is CLOSED,
1383 		 *    if not, return DDI_FAILURE.
1384 		 *  - wait until outstanding operations complete
1385 		 *  - save tape state
1386 		 *  - block new operations
1387 		 *  - cancel pending timeouts
1388 		 *
1389 		 */
1390 
1391 		if (ddi_removing_power(devi)) {
1392 			return (DDI_FAILURE);
1393 		}
1394 		mutex_enter(ST_MUTEX);
1395 
1396 		/*
1397 		 * Shouldn't already be suspended, if so return failure
1398 		 */
1399 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1400 			mutex_exit(ST_MUTEX);
1401 			return (DDI_FAILURE);
1402 		}
1403 		if (un->un_state != ST_STATE_CLOSED) {
1404 			mutex_exit(ST_MUTEX);
1405 			return (DDI_FAILURE);
1406 		}
1407 
1408 		/*
1409 		 * Wait for all outstanding I/O's to complete
1410 		 *
1411 		 * we wait on both ncmds and the wait queue for times
1412 		 * when we are flushing after persistent errors are
1413 		 * flagged, which is when ncmds can be 0, and the
1414 		 * queue can still have I/O's.  This way we preserve
1415 		 * order of biodone's.
1416 		 */
1417 		wait_cmds_complete = ddi_get_lbolt();
1418 		wait_cmds_complete +=
1419 		    st_wait_cmds_complete * drv_usectohz(1000000);
1420 		while (un->un_ncmds || un->un_quef ||
1421 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1422 
1423 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1424 			    wait_cmds_complete) == -1) {
1425 				/*
1426 				 * Time expired then cancel the command
1427 				 */
1428 				if (st_reset(un, RESET_LUN) == 0) {
1429 					if (un->un_last_throttle) {
1430 						un->un_throttle =
1431 						    un->un_last_throttle;
1432 					}
1433 					mutex_exit(ST_MUTEX);
1434 					return (DDI_FAILURE);
1435 				} else {
1436 					break;
1437 				}
1438 			}
1439 		}
1440 
1441 		/*
1442 		 * DDI_SUSPEND says that the system "may" power down, we
1443 		 * remember the file and block number before rewinding.
1444 		 * we also need to save state before issuing
1445 		 * any WRITE_FILE_MARK command.
1446 		 */
1447 		(void) st_update_block_pos(un, st_cmd, 0);
1448 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1449 
1450 
1451 		/*
1452 		 * Issue a zero write file fmk command to tell the drive to
1453 		 * flush any buffered tape marks
1454 		 */
1455 		(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1456 
1457 		/*
1458 		 * Because not all tape drives correctly implement buffer
1459 		 * flushing with the zero write file fmk command, issue a
1460 		 * synchronous rewind command to force data flushing.
1461 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1462 		 * anyway.
1463 		 */
1464 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
1465 
1466 		/* stop any new operations */
1467 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1468 		un->un_throttle = 0;
1469 
1470 		/*
1471 		 * cancel any outstanding timeouts
1472 		 */
1473 		if (un->un_delay_tid) {
1474 			timeout_id_t temp_id = un->un_delay_tid;
1475 			un->un_delay_tid = 0;
1476 			un->un_tids_at_suspend |= ST_DELAY_TID;
1477 			mutex_exit(ST_MUTEX);
1478 			(void) untimeout(temp_id);
1479 			mutex_enter(ST_MUTEX);
1480 		}
1481 
1482 		if (un->un_hib_tid) {
1483 			timeout_id_t temp_id = un->un_hib_tid;
1484 			un->un_hib_tid = 0;
1485 			un->un_tids_at_suspend |= ST_HIB_TID;
1486 			mutex_exit(ST_MUTEX);
1487 			(void) untimeout(temp_id);
1488 			mutex_enter(ST_MUTEX);
1489 		}
1490 
1491 		/*
1492 		 * Suspend the scsi_watch_thread
1493 		 */
1494 		if (un->un_swr_token) {
1495 			opaque_t temp_token = un->un_swr_token;
1496 			mutex_exit(ST_MUTEX);
1497 			scsi_watch_suspend(temp_token);
1498 		} else {
1499 			mutex_exit(ST_MUTEX);
1500 		}
1501 
1502 		return (DDI_SUCCESS);
1503 
1504 	default:
1505 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1506 		return (DDI_FAILURE);
1507 	}
1508 }
1509 
1510 
1511 /* ARGSUSED */
1512 static int
1513 st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1514 {
1515 	dev_t dev;
1516 	struct scsi_tape *un;
1517 	int instance, error;
1518 
1519 	ST_ENTR(dip, st_info);
1520 
1521 	switch (infocmd) {
1522 	case DDI_INFO_DEVT2DEVINFO:
1523 		dev = (dev_t)arg;
1524 		instance = MTUNIT(dev);
1525 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1526 			return (DDI_FAILURE);
1527 		*result = (void *) ST_DEVINFO;
1528 		error = DDI_SUCCESS;
1529 		break;
1530 	case DDI_INFO_DEVT2INSTANCE:
1531 		dev = (dev_t)arg;
1532 		instance = MTUNIT(dev);
1533 		*result = (void *)(uintptr_t)instance;
1534 		error = DDI_SUCCESS;
1535 		break;
1536 	default:
1537 		error = DDI_FAILURE;
1538 	}
1539 	return (error);
1540 }
1541 
1542 static int
1543 st_doattach(struct scsi_device *devp, int (*canwait)())
1544 {
1545 	struct scsi_tape *un = NULL;
1546 	recov_info *ri;
1547 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1548 	int instance;
1549 	size_t rlen;
1550 
1551 	ST_FUNC(devp->sd_dev, st_doattach);
1552 	/*
1553 	 * Call the routine scsi_probe to do some of the dirty work.
1554 	 * If the INQUIRY command succeeds, the field sd_inq in the
1555 	 * device structure will be filled in.
1556 	 */
1557 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1558 	    "st_doattach(): probing\n");
1559 
1560 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1561 
1562 		/*
1563 		 * In checking the whole inq_dtype byte we are looking at both
1564 		 * the Peripheral Qualifier and the Peripheral Device Type.
1565 		 * For this driver we are only interested in sequential devices
1566 		 * that are connected or capable if connecting to this logical
1567 		 * unit.
1568 		 */
1569 		if (devp->sd_inq->inq_dtype ==
1570 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1571 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1572 			    "probe exists\n");
1573 		} else {
1574 			/* Something there but not a tape device */
1575 			scsi_unprobe(devp);
1576 			return (DDI_FAILURE);
1577 		}
1578 	} else {
1579 		/* Nothing there */
1580 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1581 		    "probe failure: nothing there\n");
1582 		scsi_unprobe(devp);
1583 		return (DDI_FAILURE);
1584 	}
1585 
1586 
1587 	/*
1588 	 * The actual unit is present.
1589 	 * Now is the time to fill in the rest of our info..
1590 	 */
1591 	instance = ddi_get_instance(devp->sd_dev);
1592 
1593 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1594 		goto error;
1595 	}
1596 	un = ddi_get_soft_state(st_state, instance);
1597 
1598 	ASSERT(un != NULL);
1599 
1600 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
1601 	    MAX_SENSE_LENGTH, B_READ, canwait, NULL);
1602 	if (un->un_rqs_bp == NULL) {
1603 		goto error;
1604 	}
1605 	un->un_rqs = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
1606 	    CDB_GROUP0, 1, st_recov_sz, PKT_CONSISTENT, canwait, NULL);
1607 	if (!un->un_rqs) {
1608 		goto error;
1609 	}
1610 	ASSERT(un->un_rqs->pkt_resid == 0);
1611 	devp->sd_sense =
1612 	    (struct scsi_extended_sense *)un->un_rqs_bp->b_un.b_addr;
1613 	ASSERT(geterror(un->un_rqs_bp) == NULL);
1614 
1615 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs->pkt_cdbp,
1616 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
1617 	FILL_SCSI1_LUN(devp, un->un_rqs);
1618 	un->un_rqs->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1619 	un->un_rqs->pkt_time = st_io_time;
1620 	un->un_rqs->pkt_comp = st_intr;
1621 	ri = (recov_info *)un->un_rqs->pkt_private;
1622 	if (st_recov_sz == sizeof (recov_info)) {
1623 		ri->privatelen = sizeof (recov_info);
1624 	} else {
1625 		ri->privatelen = sizeof (pkt_info);
1626 	}
1627 
1628 	un->un_sbufp = getrbuf(km_flags);
1629 	un->un_recov_buf = getrbuf(km_flags);
1630 
1631 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1632 
1633 	/*
1634 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1635 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1636 	 * is obsolete and we want more flexibility in controlling the DMA
1637 	 * address constraints.
1638 	 */
1639 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1640 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1641 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1642 
1643 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1644 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1645 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1646 
1647 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1648 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1649 		    "probe partial failure: no space\n");
1650 		goto error;
1651 	}
1652 
1653 	bzero(un->un_mspl, sizeof (struct seq_mode));
1654 
1655 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1656 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1657 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1658 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1659 #ifdef	__x86
1660 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1661 #endif
1662 
1663 	/* Initialize power managemnet condition variable */
1664 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1665 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1666 	cv_init(&un->un_recov_buf_cv, NULL, CV_DRIVER, NULL);
1667 
1668 	un->un_recov_taskq = ddi_taskq_create(devp->sd_dev,
1669 	    "un_recov_taskq", 1, TASKQ_DEFAULTPRI, km_flags);
1670 
1671 	ASSERT(un->un_recov_taskq != NULL);
1672 
1673 	un->un_pos.pmode = invalid;
1674 	un->un_sd	= devp;
1675 	un->un_swr_token = (opaque_t)NULL;
1676 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1677 	un->un_wormable = st_is_drive_worm;
1678 	un->un_media_id_method = st_get_media_identification;
1679 	/*
1680 	 * setting long a initial as it contains logical file info.
1681 	 * support for long format is mandatory but many drive don't do it.
1682 	 */
1683 	un->un_read_pos_type = LONG_POS;
1684 
1685 	un->un_suspend_pos.pmode = invalid;
1686 
1687 #ifdef	__x86
1688 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1689 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1690 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1691 		    "allocation of contiguous memory dma handle failed!");
1692 		un->un_contig_mem_hdl = NULL;
1693 		goto error;
1694 	}
1695 #endif
1696 
1697 	/*
1698 	 * Since this driver manages devices with "remote" hardware,
1699 	 * i.e. the devices themselves have no "reg" properties,
1700 	 * the SUSPEND/RESUME commands in detach/attach will not be
1701 	 * called by the power management framework unless we request
1702 	 * it by creating a "pm-hardware-state" property and setting it
1703 	 * to value "needs-suspend-resume".
1704 	 */
1705 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1706 	    "pm-hardware-state", "needs-suspend-resume") !=
1707 	    DDI_PROP_SUCCESS) {
1708 
1709 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1710 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1711 		goto error;
1712 	}
1713 
1714 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1715 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1716 
1717 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1718 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1719 		    "failed\n");
1720 		goto error;
1721 	}
1722 
1723 	(void) scsi_reset_notify(ROUTE, SCSI_RESET_NOTIFY,
1724 	    st_reset_notification, (caddr_t)un);
1725 
1726 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "attach success\n");
1727 	return (DDI_SUCCESS);
1728 
1729 error:
1730 	devp->sd_sense = NULL;
1731 
1732 	ddi_remove_minor_node(devp->sd_dev, NULL);
1733 	if (un) {
1734 		if (un->un_mspl) {
1735 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1736 		}
1737 		if (un->un_read_pos_data) {
1738 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1739 		}
1740 		if (un->un_sbufp) {
1741 			freerbuf(un->un_sbufp);
1742 		}
1743 		if (un->un_recov_buf) {
1744 			freerbuf(un->un_recov_buf);
1745 		}
1746 		if (un->un_uscsi_rqs_buf) {
1747 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1748 		}
1749 #ifdef	__x86
1750 		if (un->un_contig_mem_hdl != NULL) {
1751 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1752 		}
1753 #endif
1754 		if (un->un_rqs) {
1755 			scsi_destroy_pkt(un->un_rqs);
1756 		}
1757 
1758 		if (un->un_rqs_bp) {
1759 			scsi_free_consistent_buf(un->un_rqs_bp);
1760 		}
1761 
1762 		ddi_soft_state_free(st_state, instance);
1763 		devp->sd_private = NULL;
1764 	}
1765 
1766 	if (devp->sd_inq) {
1767 		scsi_unprobe(devp);
1768 	}
1769 	return (DDI_FAILURE);
1770 }
1771 
1772 typedef int
1773 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1774 
1775 static cfg_functp config_functs[] = {
1776 	st_get_conf_from_st_dot_conf,
1777 	st_get_conf_from_st_conf_dot_c,
1778 	st_get_conf_from_tape_drive,
1779 	st_get_default_conf
1780 };
1781 
1782 
1783 /*
1784  * determine tape type, using tape-config-list or built-in table or
1785  * use a generic tape config entry
1786  */
1787 static void
1788 st_known_tape_type(struct scsi_tape *un)
1789 {
1790 	struct st_drivetype *dp;
1791 	cfg_functp *config_funct;
1792 	uchar_t reserved;
1793 
1794 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1795 
1796 	reserved = (un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1797 	    : ST_RELEASE;
1798 
1799 	/*
1800 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1801 	 *	 no vid & pid inquiry data.  So, we provide one.
1802 	 */
1803 	if (ST_INQUIRY->inq_len == 0 ||
1804 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1805 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1806 	}
1807 
1808 	if (un->un_dp_size == 0) {
1809 		un->un_dp_size = sizeof (struct st_drivetype);
1810 		dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1811 		un->un_dp = dp;
1812 	} else {
1813 		dp = un->un_dp;
1814 	}
1815 
1816 	un->un_dp->non_motion_timeout = st_io_time;
1817 	/*
1818 	 * Loop through the configuration methods till one works.
1819 	 */
1820 	for (config_funct = &config_functs[0]; ; config_funct++) {
1821 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1822 			break;
1823 		}
1824 	}
1825 
1826 	/*
1827 	 * If we didn't just make up this configuration and
1828 	 * all the density codes are the same..
1829 	 * Set Auto Density over ride.
1830 	 */
1831 	if (*config_funct != st_get_default_conf) {
1832 		/*
1833 		 * If this device is one that is configured and all
1834 		 * densities are the same, This saves doing gets and set
1835 		 * that yield nothing.
1836 		 */
1837 		if ((dp->densities[0]) == (dp->densities[1]) &&
1838 		    (dp->densities[0]) == (dp->densities[2]) &&
1839 		    (dp->densities[0]) == (dp->densities[3])) {
1840 
1841 			dp->options |= ST_AUTODEN_OVERRIDE;
1842 		}
1843 	}
1844 
1845 
1846 	/*
1847 	 * Store tape drive characteristics.
1848 	 */
1849 	un->un_status = 0;
1850 	un->un_attached = 1;
1851 	un->un_init_options = dp->options;
1852 
1853 	/* setup operation time-outs based on options */
1854 	st_calculate_timeouts(un);
1855 
1856 	/* make sure if we are supposed to be variable, make it variable */
1857 	if (dp->options & ST_VARIABLE) {
1858 		dp->bsize = 0;
1859 	}
1860 
1861 	if (reserved != ((un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1862 	    : ST_RELEASE)) {
1863 		(void) st_reserve_release(un, reserved, st_uscsi_cmd);
1864 	}
1865 
1866 	un->un_unit_attention_flags = 1;
1867 
1868 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1869 
1870 }
1871 
1872 
1873 typedef struct {
1874 	int mask;
1875 	int bottom;
1876 	int top;
1877 	char *name;
1878 } conf_limit;
1879 
1880 static const conf_limit conf_limits[] = {
1881 
1882 	-1,		1,		2,		"conf version",
1883 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1884 	-1,		0,		0xffffff,	"block size",
1885 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1886 	-1,		0,		4,		"number of densities",
1887 	-1,		0,		UINT8_MAX,	"density code",
1888 	-1,		0,		3,		"default density",
1889 	-1,		0,		UINT16_MAX,	"non motion timeout",
1890 	-1,		0,		UINT16_MAX,	"I/O timeout",
1891 	-1,		0,		UINT16_MAX,	"space timeout",
1892 	-1,		0,		UINT16_MAX,	"load timeout",
1893 	-1,		0,		UINT16_MAX,	"unload timeout",
1894 	-1,		0,		UINT16_MAX,	"erase timeout",
1895 	0,		0,		0,		NULL
1896 };
1897 
1898 static int
1899 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1900     const char *conf_name)
1901 {
1902 	int dens;
1903 	int ndens;
1904 	int value;
1905 	int type;
1906 	int count;
1907 	const conf_limit *limit = &conf_limits[0];
1908 
1909 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1910 
1911 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1912 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1913 
1914 	count = list_len;
1915 	type = *list;
1916 	for (;  count && limit->name; count--, list++, limit++) {
1917 
1918 		value = *list;
1919 		if (value & ~limit->mask) {
1920 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1921 			    "%s %s value invalid bits set: 0x%X\n",
1922 			    conf_name, limit->name, value & ~limit->mask);
1923 			*list &= limit->mask;
1924 		} else if (value < limit->bottom) {
1925 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1926 			    "%s %s value too low: value = %d limit %d\n",
1927 			    conf_name, limit->name, value, limit->bottom);
1928 		} else if (value > limit->top) {
1929 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1930 			    "%s %s value too high: value = %d limit %d\n",
1931 			    conf_name, limit->name, value, limit->top);
1932 		} else {
1933 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1934 			    "%s %s value = 0x%X\n",
1935 			    conf_name, limit->name, value);
1936 		}
1937 
1938 		/* If not the number of densities continue */
1939 		if (limit != &conf_limits[4]) {
1940 			continue;
1941 		}
1942 
1943 		/* If number of densities is not in range can't use config */
1944 		if (value < limit->bottom || value > limit->top) {
1945 			return (-1);
1946 		}
1947 
1948 		ndens = min(value, NDENSITIES);
1949 		if ((type == 1) && (list_len - ndens) != 6) {
1950 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1951 			    "%s conf version 1 with %d densities has %d items"
1952 			    " should have %d",
1953 			    conf_name, ndens, list_len, 6 + ndens);
1954 		} else if ((type == 2) && (list_len - ndens) != 13) {
1955 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1956 			    "%s conf version 2 with %d densities has %d items"
1957 			    " should have %d",
1958 			    conf_name, ndens, list_len, 13 + ndens);
1959 		}
1960 
1961 		limit++;
1962 		for (dens = 0; dens < ndens && count; dens++) {
1963 			count--;
1964 			list++;
1965 			value = *list;
1966 			if (value < limit->bottom) {
1967 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1968 				    "%s density[%d] value too low: value ="
1969 				    " 0x%X limit 0x%X\n",
1970 				    conf_name, dens, value, limit->bottom);
1971 			} else if (value > limit->top) {
1972 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1973 				    "%s density[%d] value too high: value ="
1974 				    " 0x%X limit 0x%X\n",
1975 				    conf_name, dens, value, limit->top);
1976 			} else {
1977 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1978 				    "%s density[%d] value = 0x%X\n",
1979 				    conf_name, dens, value);
1980 			}
1981 		}
1982 	}
1983 
1984 	return (0);
1985 }
1986 
1987 static int
1988 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
1989     struct st_drivetype *dp)
1990 {
1991 	caddr_t config_list = NULL;
1992 	caddr_t data_list = NULL;
1993 	int	*data_ptr;
1994 	caddr_t vidptr, prettyptr, datanameptr;
1995 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
1996 	int config_list_len, data_list_len, len, i;
1997 	int version;
1998 	int found = 0;
1999 
2000 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
2001 
2002 	/*
2003 	 * Determine type of tape controller. Type is determined by
2004 	 * checking the vendor ids of the earlier inquiry command and
2005 	 * comparing those with vids in tape-config-list defined in st.conf
2006 	 */
2007 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
2008 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
2009 	    != DDI_PROP_SUCCESS) {
2010 		return (found);
2011 	}
2012 
2013 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2014 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
2015 
2016 	/*
2017 	 * Compare vids in each triplet - if it matches, get value for
2018 	 * data_name and contruct a st_drivetype struct
2019 	 * tripletlen is not set yet!
2020 	 */
2021 	for (len = config_list_len, vidptr = config_list;
2022 	    len > 0;
2023 	    vidptr += tripletlen, len -= tripletlen) {
2024 
2025 		vidlen = strlen(vidptr);
2026 		prettyptr = vidptr + vidlen + 1;
2027 		prettylen = strlen(prettyptr);
2028 		datanameptr = prettyptr + prettylen + 1;
2029 		datanamelen = strlen(datanameptr);
2030 		tripletlen = vidlen + prettylen + datanamelen + 3;
2031 
2032 		if (vidlen == 0) {
2033 			continue;
2034 		}
2035 
2036 		/*
2037 		 * If inquiry vid dosen't match this triplets vid,
2038 		 * try the next.
2039 		 */
2040 		if (strncasecmp(vidpid, vidptr, vidlen)) {
2041 			continue;
2042 		}
2043 
2044 		/*
2045 		 * if prettylen is zero then use the vid string
2046 		 */
2047 		if (prettylen == 0) {
2048 			prettyptr = vidptr;
2049 			prettylen = vidlen;
2050 		}
2051 
2052 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2053 		    "vid = %s, pretty=%s, dataname = %s\n",
2054 		    vidptr, prettyptr, datanameptr);
2055 
2056 		/*
2057 		 * get the data list
2058 		 */
2059 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
2060 		    datanameptr, (caddr_t)&data_list,
2061 		    &data_list_len) != DDI_PROP_SUCCESS) {
2062 			/*
2063 			 * Error in getting property value
2064 			 * print warning!
2065 			 */
2066 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2067 			    "data property (%s) has no value\n",
2068 			    datanameptr);
2069 			continue;
2070 		}
2071 
2072 		/*
2073 		 * now initialize the st_drivetype struct
2074 		 */
2075 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
2076 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
2077 		(void) strncpy(dp->vid, vidptr, dp->length);
2078 		data_ptr = (int *)data_list;
2079 		/*
2080 		 * check if data is enough for version, type,
2081 		 * bsize, options, # of densities, density1,
2082 		 * density2, ..., default_density
2083 		 */
2084 		if ((data_list_len < 5 * sizeof (int)) ||
2085 		    (data_list_len < 6 * sizeof (int) +
2086 		    *(data_ptr + 4) * sizeof (int))) {
2087 			/*
2088 			 * print warning and skip to next triplet.
2089 			 */
2090 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2091 			    "data property (%s) incomplete\n",
2092 			    datanameptr);
2093 			kmem_free(data_list, data_list_len);
2094 			continue;
2095 		}
2096 
2097 		if (st_validate_conf_data(un, data_ptr,
2098 		    data_list_len / sizeof (int), datanameptr)) {
2099 			kmem_free(data_list, data_list_len);
2100 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2101 			    "data property (%s) rejected\n",
2102 			    datanameptr);
2103 			continue;
2104 		}
2105 
2106 		/*
2107 		 * check version
2108 		 */
2109 		version = *data_ptr++;
2110 		if (version != 1 && version != 2) {
2111 			/* print warning but accept it */
2112 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2113 			    "Version # for data property (%s) "
2114 			    "not set to 1 or 2\n", datanameptr);
2115 		}
2116 
2117 		dp->type    = *data_ptr++;
2118 		dp->bsize   = *data_ptr++;
2119 		dp->options = *data_ptr++;
2120 		dp->options |= ST_DYNAMIC;
2121 		len = *data_ptr++;
2122 		for (i = 0; i < NDENSITIES; i++) {
2123 			if (i < len) {
2124 				dp->densities[i] = *data_ptr++;
2125 			}
2126 		}
2127 		dp->default_density = *data_ptr << 3;
2128 		if (version == 2 &&
2129 		    data_list_len >= (13 + len) * sizeof (int)) {
2130 			data_ptr++;
2131 			dp->non_motion_timeout	= *data_ptr++;
2132 			dp->io_timeout		= *data_ptr++;
2133 			dp->rewind_timeout	= *data_ptr++;
2134 			dp->space_timeout	= *data_ptr++;
2135 			dp->load_timeout	= *data_ptr++;
2136 			dp->unload_timeout	= *data_ptr++;
2137 			dp->erase_timeout	= *data_ptr++;
2138 		}
2139 		kmem_free(data_list, data_list_len);
2140 		found = 1;
2141 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2142 		    "found in st.conf: vid = %s, pretty=%s\n",
2143 		    dp->vid, dp->name);
2144 		break;
2145 	}
2146 
2147 	/*
2148 	 * free up the memory allocated by ddi_getlongprop
2149 	 */
2150 	if (config_list) {
2151 		kmem_free(config_list, config_list_len);
2152 	}
2153 	return (found);
2154 }
2155 
2156 static int
2157 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2158     struct st_drivetype *dp)
2159 {
2160 	int i;
2161 
2162 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2163 	/*
2164 	 * Determine type of tape controller.  Type is determined by
2165 	 * checking the result of the earlier inquiry command and
2166 	 * comparing vendor ids with strings in a table declared in st_conf.c.
2167 	 */
2168 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2169 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2170 
2171 	for (i = 0; i < st_ndrivetypes; i++) {
2172 		if (st_drivetypes[i].length == 0) {
2173 			continue;
2174 		}
2175 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2176 		    st_drivetypes[i].length)) {
2177 			continue;
2178 		}
2179 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2180 		return (1);
2181 	}
2182 	return (0);
2183 }
2184 
2185 static int
2186 st_get_conf_from_tape_drive(struct scsi_tape *un, char *vidpid,
2187     struct st_drivetype *dp)
2188 {
2189 	int bsize;
2190 	ulong_t maxbsize;
2191 	caddr_t buf;
2192 	struct st_drivetype *tem_dp;
2193 	struct read_blklim *blklim;
2194 	int rval;
2195 	int i;
2196 
2197 	ST_FUNC(ST_DEVINFO, st_get_conf_from_tape_drive);
2198 
2199 	/*
2200 	 * Determine the type of tape controller. Type is determined by
2201 	 * sending SCSI commands to tape drive and deriving the type from
2202 	 * the returned data.
2203 	 */
2204 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2205 	    "st_get_conf_from_tape_drive(): asking tape drive\n");
2206 
2207 	tem_dp = kmem_zalloc(sizeof (struct st_drivetype), KM_SLEEP);
2208 
2209 	/*
2210 	 * Make up a name
2211 	 */
2212 	bcopy(vidpid, tem_dp->name, VIDPIDLEN);
2213 	tem_dp->name[VIDPIDLEN] = '\0';
2214 	tem_dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2215 	(void) strncpy(tem_dp->vid, ST_INQUIRY->inq_vid, tem_dp->length);
2216 	/*
2217 	 * 'clean' vendor and product strings of non-printing chars
2218 	 */
2219 	for (i = 0; i < VIDPIDLEN - 1; i ++) {
2220 		if (tem_dp->name[i] < ' ' || tem_dp->name[i] > '~') {
2221 			tem_dp->name[i] = '.';
2222 		}
2223 	}
2224 
2225 	/*
2226 	 * MODE SENSE to determine block size.
2227 	 */
2228 	un->un_dp->options |= ST_MODE_SEL_COMP | ST_UNLOADABLE;
2229 	rval = st_modesense(un);
2230 	if (rval) {
2231 		if (rval == EACCES) {
2232 			un->un_dp->type = ST_TYPE_INVALID;
2233 			rval = 1;
2234 		} else {
2235 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
2236 			rval = 0;
2237 		}
2238 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2239 		    "st_get_conf_from_tape_drive(): fail to mode sense\n");
2240 		goto exit;
2241 	}
2242 
2243 	/* Can mode sense page 0x10 or 0xf */
2244 	tem_dp->options |= ST_MODE_SEL_COMP;
2245 	bsize = (un->un_mspl->high_bl << 16)	|
2246 	    (un->un_mspl->mid_bl << 8)		|
2247 	    (un->un_mspl->low_bl);
2248 
2249 	if (bsize == 0) {
2250 		tem_dp->options |= ST_VARIABLE;
2251 		tem_dp->bsize = 0;
2252 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
2253 		rval = st_change_block_size(un, 0);
2254 		if (rval) {
2255 			if (rval == EACCES) {
2256 				un->un_dp->type = ST_TYPE_INVALID;
2257 				rval = 1;
2258 			} else {
2259 				rval = 0;
2260 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2261 				    "st_get_conf_from_tape_drive(): "
2262 				    "Fixed record size is too large and"
2263 				    "cannot switch to variable record size");
2264 			}
2265 			goto exit;
2266 		}
2267 		tem_dp->options |= ST_VARIABLE;
2268 	} else {
2269 		rval = st_change_block_size(un, 0);
2270 		if (rval == 0) {
2271 			tem_dp->options |= ST_VARIABLE;
2272 			tem_dp->bsize = 0;
2273 		} else if (rval != EACCES) {
2274 			tem_dp->bsize = bsize;
2275 		} else {
2276 			un->un_dp->type = ST_TYPE_INVALID;
2277 			rval = 1;
2278 			goto exit;
2279 		}
2280 	}
2281 
2282 	/*
2283 	 * If READ BLOCk LIMITS works and upper block size limit is
2284 	 * more than 64K, ST_NO_RECSIZE_LIMIT is supported.
2285 	 */
2286 	blklim = kmem_zalloc(sizeof (struct read_blklim), KM_SLEEP);
2287 	rval = st_read_block_limits(un, blklim);
2288 	if (rval) {
2289 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2290 		    "st_get_conf_from_tape_drive(): "
2291 		    "fail to read block limits.\n");
2292 		rval = 0;
2293 		kmem_free(blklim, sizeof (struct read_blklim));
2294 		goto exit;
2295 	}
2296 	maxbsize = (blklim->max_hi << 16) +
2297 	    (blklim->max_mid << 8) + blklim->max_lo;
2298 	if (maxbsize > ST_MAXRECSIZE_VARIABLE) {
2299 		tem_dp->options |= ST_NO_RECSIZE_LIMIT;
2300 	}
2301 	kmem_free(blklim, sizeof (struct read_blklim));
2302 
2303 	/*
2304 	 * Inquiry VPD page 0xb0 to see if the tape drive supports WORM
2305 	 */
2306 	buf = kmem_zalloc(6, KM_SLEEP);
2307 	rval = st_get_special_inquiry(un, 6, buf, 0xb0);
2308 	if (rval) {
2309 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2310 		    "st_get_conf_from_tape_drive(): "
2311 		    "fail to read vitial inquiry.\n");
2312 		rval = 0;
2313 		kmem_free(buf, 6);
2314 		goto exit;
2315 	}
2316 	if (buf[4] & 1) {
2317 		tem_dp->options |= ST_WORMABLE;
2318 	}
2319 	kmem_free(buf, 6);
2320 
2321 	/* Assume BSD BSR KNOWS_EOD */
2322 	tem_dp->options |= ST_BSF | ST_BSR | ST_KNOWS_EOD | ST_UNLOADABLE;
2323 	tem_dp->max_rretries = -1;
2324 	tem_dp->max_wretries = -1;
2325 
2326 	/*
2327 	 * Decide the densities supported by tape drive by sending
2328 	 * REPORT DENSITY SUPPORT command.
2329 	 */
2330 	if (st_get_densities_from_tape_drive(un, tem_dp) == 0) {
2331 		goto exit;
2332 	}
2333 
2334 	/*
2335 	 * Decide the timeout values for several commands by sending
2336 	 * REPORT SUPPORTED OPERATION CODES command.
2337 	 */
2338 	rval = st_get_timeout_values_from_tape_drive(un, tem_dp);
2339 	if (rval == 0 || ((rval == 1) && (tem_dp->type == ST_TYPE_INVALID))) {
2340 		goto exit;
2341 	}
2342 
2343 	bcopy(tem_dp, dp, sizeof (struct st_drivetype));
2344 	rval = 1;
2345 
2346 exit:
2347 	un->un_status = KEY_NO_SENSE;
2348 	kmem_free(tem_dp, sizeof (struct st_drivetype));
2349 	return (rval);
2350 }
2351 
2352 static int
2353 st_get_densities_from_tape_drive(struct scsi_tape *un,
2354     struct st_drivetype *dp)
2355 {
2356 	int i, p;
2357 	size_t buflen;
2358 	ushort_t des_len;
2359 	uchar_t *den_header;
2360 	uchar_t num_den;
2361 	uchar_t den[NDENSITIES];
2362 	uchar_t deflt[NDENSITIES];
2363 	struct report_density_desc *den_desc;
2364 
2365 	ST_FUNC(ST_DEVINFO, st_get_densities_from_type_drive);
2366 
2367 	/*
2368 	 * Since we have no idea how many densitiy support entries
2369 	 * will be returned, we send the command firstly assuming
2370 	 * there is only one. Then we can decide the number of
2371 	 * entries by available density support length. If multiple
2372 	 * entries exist, we will resend the command with enough
2373 	 * buffer size.
2374 	 */
2375 	buflen = sizeof (struct report_density_header) +
2376 	    sizeof (struct report_density_desc);
2377 	den_header = kmem_zalloc(buflen, KM_SLEEP);
2378 	if (st_report_density_support(un, den_header, buflen) != 0) {
2379 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2380 		    "st_get_conf_from_tape_drive(): fail to report density.\n");
2381 		kmem_free(den_header, buflen);
2382 		return (0);
2383 	}
2384 	des_len =
2385 	    BE_16(((struct report_density_header *)den_header)->ava_dens_len);
2386 	num_den = (des_len - 2) / sizeof (struct report_density_desc);
2387 
2388 	if (num_den > 1) {
2389 		kmem_free(den_header, buflen);
2390 		buflen = sizeof (struct report_density_header) +
2391 		    sizeof (struct report_density_desc) * num_den;
2392 		den_header = kmem_zalloc(buflen, KM_SLEEP);
2393 		if (st_report_density_support(un, den_header, buflen) != 0) {
2394 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2395 			    "st_get_conf_from_tape_drive(): "
2396 			    "fail to report density.\n");
2397 			kmem_free(den_header, buflen);
2398 			return (0);
2399 		}
2400 	}
2401 
2402 	den_desc = (struct report_density_desc *)(den_header
2403 	    + sizeof (struct report_density_header));
2404 
2405 	/*
2406 	 * Decide the drive type by assigning organization
2407 	 */
2408 	for (i = 0; i < ST_NUM_MEMBERS(st_vid_dt); i ++) {
2409 		if (strncmp(st_vid_dt[i].vid, (char *)(den_desc->ass_org),
2410 		    8) == 0) {
2411 			dp->type = st_vid_dt[i].type;
2412 			break;
2413 		}
2414 	}
2415 	if (i == ST_NUM_MEMBERS(st_vid_dt)) {
2416 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2417 		    "st_get_conf_from_tape_drive(): "
2418 		    "can't find match of assigned ort.\n");
2419 		kmem_free(den_header, buflen);
2420 		return (0);
2421 	}
2422 
2423 	/*
2424 	 * The tape drive may support many tape formats, but the st driver
2425 	 * supports only the four highest densities. Since density code
2426 	 * values are returned by ascending sequence, we start from the
2427 	 * last entry of density support data block descriptor.
2428 	 */
2429 	p = 0;
2430 	den_desc += num_den - 1;
2431 	for (i = 0; i < num_den && p < NDENSITIES; i ++, den_desc --) {
2432 		if ((den_desc->pri_den != 0) && (den_desc->wrtok)) {
2433 			if (p != 0) {
2434 				if (den_desc->pri_den >= den[p - 1]) {
2435 					continue;
2436 				}
2437 			}
2438 			den[p] = den_desc->pri_den;
2439 			deflt[p] = den_desc->deflt;
2440 			p ++;
2441 		}
2442 	}
2443 
2444 	switch (p) {
2445 	case 0:
2446 		bzero(dp->densities, NDENSITIES);
2447 		dp->options |= ST_AUTODEN_OVERRIDE;
2448 		dp->default_density = MT_DENSITY4;
2449 		break;
2450 
2451 	case 1:
2452 		(void) memset(dp->densities, den[0], NDENSITIES);
2453 		dp->options |= ST_AUTODEN_OVERRIDE;
2454 		dp->default_density = MT_DENSITY4;
2455 		break;
2456 
2457 	case 2:
2458 		dp->densities[0] = den[1];
2459 		dp->densities[1] = den[1];
2460 		dp->densities[2] = den[0];
2461 		dp->densities[3] = den[0];
2462 		if (deflt[0]) {
2463 			dp->default_density = MT_DENSITY4;
2464 		} else {
2465 			dp->default_density = MT_DENSITY2;
2466 		}
2467 		break;
2468 
2469 	case 3:
2470 		dp->densities[0] = den[2];
2471 		dp->densities[1] = den[1];
2472 		dp->densities[2] = den[0];
2473 		dp->densities[3] = den[0];
2474 		if (deflt[0]) {
2475 			dp->default_density = MT_DENSITY4;
2476 		} else if (deflt[1]) {
2477 			dp->default_density = MT_DENSITY2;
2478 		} else {
2479 			dp->default_density = MT_DENSITY1;
2480 		}
2481 		break;
2482 
2483 	default:
2484 		for (i = p; i > p - NDENSITIES; i --) {
2485 			dp->densities[i - 1] = den[p - i];
2486 		}
2487 		if (deflt[0]) {
2488 			dp->default_density = MT_DENSITY4;
2489 		} else if (deflt[1]) {
2490 			dp->default_density = MT_DENSITY3;
2491 		} else if (deflt[2]) {
2492 			dp->default_density = MT_DENSITY2;
2493 		} else {
2494 			dp->default_density = MT_DENSITY1;
2495 		}
2496 		break;
2497 	}
2498 
2499 	bzero(dp->mediatype, NDENSITIES);
2500 
2501 	kmem_free(den_header, buflen);
2502 	return (1);
2503 }
2504 
2505 static int
2506 st_get_timeout_values_from_tape_drive(struct scsi_tape *un,
2507     struct st_drivetype *dp)
2508 {
2509 	ushort_t timeout;
2510 	int rval;
2511 
2512 	ST_FUNC(ST_DEVINFO, st_get_timeout_values_from_type_drive);
2513 
2514 	rval = st_get_timeouts_value(un, SCMD_ERASE, &timeout, 0);
2515 	if (rval) {
2516 		if (rval == EACCES) {
2517 			un->un_dp->type = ST_TYPE_INVALID;
2518 			dp->type = ST_TYPE_INVALID;
2519 			return (1);
2520 		}
2521 		return (0);
2522 	}
2523 	dp->erase_timeout = timeout;
2524 
2525 	rval = st_get_timeouts_value(un, SCMD_READ, &timeout, 0);
2526 	if (rval) {
2527 		if (rval == EACCES) {
2528 			un->un_dp->type = ST_TYPE_INVALID;
2529 			dp->type = ST_TYPE_INVALID;
2530 			return (1);
2531 		}
2532 		return (0);
2533 	}
2534 	dp->io_timeout = timeout;
2535 
2536 	rval = st_get_timeouts_value(un, SCMD_WRITE, &timeout, 0);
2537 	if (rval) {
2538 		if (rval == EACCES) {
2539 			un->un_dp->type = ST_TYPE_INVALID;
2540 			dp->type = ST_TYPE_INVALID;
2541 			return (1);
2542 		}
2543 		return (0);
2544 	}
2545 	dp->io_timeout = max(dp->io_timeout, timeout);
2546 
2547 	rval = st_get_timeouts_value(un, SCMD_SPACE, &timeout, 0);
2548 	if (rval) {
2549 		if (rval == EACCES) {
2550 			un->un_dp->type = ST_TYPE_INVALID;
2551 			dp->type = ST_TYPE_INVALID;
2552 			return (1);
2553 		}
2554 		return (0);
2555 	}
2556 	dp->space_timeout = timeout;
2557 
2558 	rval = st_get_timeouts_value(un, SCMD_LOAD, &timeout, 0);
2559 	if (rval) {
2560 		if (rval == EACCES) {
2561 			un->un_dp->type = ST_TYPE_INVALID;
2562 			dp->type = ST_TYPE_INVALID;
2563 			return (1);
2564 		}
2565 		return (0);
2566 	}
2567 	dp->load_timeout = timeout;
2568 	dp->unload_timeout = timeout;
2569 
2570 	rval = st_get_timeouts_value(un, SCMD_REWIND, &timeout, 0);
2571 	if (rval) {
2572 		if (rval == EACCES) {
2573 			un->un_dp->type = ST_TYPE_INVALID;
2574 			dp->type = ST_TYPE_INVALID;
2575 			return (1);
2576 		}
2577 		return (0);
2578 	}
2579 	dp->rewind_timeout = timeout;
2580 
2581 	rval = st_get_timeouts_value(un, SCMD_INQUIRY, &timeout, 0);
2582 	if (rval) {
2583 		if (rval == EACCES) {
2584 			un->un_dp->type = ST_TYPE_INVALID;
2585 			dp->type = ST_TYPE_INVALID;
2586 			return (1);
2587 		}
2588 		return (0);
2589 	}
2590 	dp->non_motion_timeout = timeout;
2591 
2592 	return (1);
2593 }
2594 
2595 static int
2596 st_get_timeouts_value(struct scsi_tape *un, uchar_t option_code,
2597     ushort_t *timeout_value, ushort_t service_action)
2598 {
2599 	uchar_t *timeouts;
2600 	uchar_t *oper;
2601 	uchar_t support;
2602 	uchar_t cdbsize;
2603 	uchar_t ctdp;
2604 	size_t buflen;
2605 	int rval;
2606 
2607 	ST_FUNC(ST_DEVINFO, st_get_timeouts_value);
2608 
2609 	buflen = sizeof (struct one_com_des) +
2610 	    sizeof (struct com_timeout_des);
2611 	oper = kmem_zalloc(buflen, KM_SLEEP);
2612 	rval = st_report_supported_operation(un, oper, option_code,
2613 	    service_action);
2614 
2615 	if (rval) {
2616 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2617 		    "st_get_timeouts_value(): "
2618 		    "fail to timeouts value for command %d.\n", option_code);
2619 		kmem_free(oper, buflen);
2620 		return (rval);
2621 	}
2622 
2623 	support = ((struct one_com_des *)oper)->support;
2624 	if ((support != SUPPORT_VALUES_SUPPORT_SCSI) &&
2625 	    (support != SUPPORT_VALUES_SUPPORT_VENDOR)) {
2626 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2627 		    "st_get_timeouts_value(): "
2628 		    "command %d is not supported.\n", option_code);
2629 		kmem_free(oper, buflen);
2630 		return (ENOTSUP);
2631 	}
2632 
2633 	ctdp = ((struct one_com_des *)oper)->ctdp;
2634 	if (!ctdp) {
2635 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2636 		    "st_get_timeouts_value(): "
2637 		    "command timeout is not included.\n");
2638 		kmem_free(oper, buflen);
2639 		return (ENOTSUP);
2640 	}
2641 
2642 	cdbsize = BE_16(((struct one_com_des *)oper)->cdb_size);
2643 	timeouts = (uchar_t *)(oper + cdbsize + 4);
2644 
2645 	/*
2646 	 * Timeout value in seconds is 4 bytes, but we only support the lower 2
2647 	 * bytes. If the higher 2 bytes are not zero, the timeout value is set
2648 	 * to 0xFFFF.
2649 	 */
2650 	if (*(timeouts + 8) != 0 || *(timeouts + 9) != 0) {
2651 		*timeout_value = USHRT_MAX;
2652 	} else {
2653 		*timeout_value = ((*(timeouts + 10)) << 8) |
2654 		    (*(timeouts + 11));
2655 	}
2656 
2657 	kmem_free(oper, buflen);
2658 	return (0);
2659 }
2660 
2661 static int
2662 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2663 {
2664 	int i;
2665 
2666 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2667 
2668 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2669 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2670 
2671 	/*
2672 	 * Make up a name
2673 	 */
2674 	bcopy("Vendor '", dp->name, 8);
2675 	bcopy(vidpid, &dp->name[8], VIDLEN);
2676 	bcopy("' Product '", &dp->name[16], 11);
2677 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2678 	dp->name[ST_NAMESIZE - 2] = '\'';
2679 	dp->name[ST_NAMESIZE - 1] = '\0';
2680 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2681 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2682 	/*
2683 	 * 'clean' vendor and product strings of non-printing chars
2684 	 */
2685 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2686 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2687 			dp->name[i] = '.';
2688 		}
2689 	}
2690 	dp->type = ST_TYPE_INVALID;
2691 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2692 
2693 	return (1); /* Can Not Fail */
2694 }
2695 
2696 /*
2697  * Regular Unix Entry points
2698  */
2699 
2700 
2701 
2702 /* ARGSUSED */
2703 static int
2704 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2705 {
2706 	dev_t dev = *dev_p;
2707 	int rval = 0;
2708 
2709 	GET_SOFT_STATE(dev);
2710 
2711 	ST_ENTR(ST_DEVINFO, st_open);
2712 
2713 	/*
2714 	 * validate that we are addressing a sensible unit
2715 	 */
2716 	mutex_enter(ST_MUTEX);
2717 
2718 #ifdef	STDEBUG
2719 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2720 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2721 	    st_dev_name(dev), *dev_p, flag, otyp);
2722 #endif
2723 
2724 	/*
2725 	 * All device accesss go thru st_strategy() where we check
2726 	 * suspend status
2727 	 */
2728 
2729 	if (!un->un_attached) {
2730 		st_known_tape_type(un);
2731 		if (!un->un_attached) {
2732 			rval = ENXIO;
2733 			goto exit;
2734 		}
2735 
2736 	}
2737 
2738 	/*
2739 	 * Check for the case of the tape in the middle of closing.
2740 	 * This isn't simply a check of the current state, because
2741 	 * we could be in state of sensing with the previous state
2742 	 * that of closing.
2743 	 *
2744 	 * And don't allow multiple opens.
2745 	 */
2746 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2747 		un->un_laststate = un->un_state;
2748 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2749 		while (IS_CLOSING(un) ||
2750 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2751 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2752 				rval = EINTR;
2753 				un->un_state = un->un_laststate;
2754 				goto exit;
2755 			}
2756 		}
2757 	} else if (un->un_state != ST_STATE_CLOSED) {
2758 		rval = EBUSY;
2759 		goto busy;
2760 	}
2761 
2762 	/*
2763 	 * record current dev
2764 	 */
2765 	un->un_dev = dev;
2766 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2767 	un->un_errno = 0;	/* no errors yet */
2768 	un->un_restore_pos = 0;
2769 	un->un_rqs_state = 0;
2770 
2771 	/*
2772 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2773 	 * anything, leave internal states alone, if fileno >= 0
2774 	 */
2775 	if (flag & (FNDELAY | FNONBLOCK)) {
2776 		switch (un->un_pos.pmode) {
2777 
2778 		case invalid:
2779 			un->un_state = ST_STATE_OFFLINE;
2780 			break;
2781 
2782 		case legacy:
2783 			/*
2784 			 * If position is anything other than rewound.
2785 			 */
2786 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2787 				/*
2788 				 * set un_read_only/write-protect status.
2789 				 *
2790 				 * If the tape is not bot we can assume
2791 				 * that mspl->wp_status is set properly.
2792 				 * else
2793 				 * we need to do a mode sense/Tur once
2794 				 * again to get the actual tape status.(since
2795 				 * user might have replaced the tape)
2796 				 * Hence make the st state OFFLINE so that
2797 				 * we re-intialize the tape once again.
2798 				 */
2799 				un->un_read_only =
2800 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2801 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2802 			} else {
2803 				un->un_state = ST_STATE_OFFLINE;
2804 			}
2805 			break;
2806 		case logical:
2807 			if (un->un_pos.lgclblkno == 0) {
2808 				un->un_state = ST_STATE_OFFLINE;
2809 			} else {
2810 				un->un_read_only =
2811 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2812 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2813 			}
2814 			break;
2815 		}
2816 		rval = 0;
2817 	} else {
2818 		/*
2819 		 * Not opening O_NDELAY.
2820 		 */
2821 		un->un_state = ST_STATE_OPENING;
2822 
2823 		/*
2824 		 * Clear error entry stack
2825 		 */
2826 		st_empty_error_stack(un);
2827 
2828 		rval = st_tape_init(un);
2829 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2830 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2831 			rval = 0; /* so open doesn't fail */
2832 		} else if (rval) {
2833 			/*
2834 			 * Release the tape unit, if reserved and not
2835 			 * preserve reserve.
2836 			 */
2837 			if ((un->un_rsvd_status &
2838 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2839 				(void) st_reserve_release(un, ST_RELEASE,
2840 				    st_uscsi_cmd);
2841 			}
2842 		} else {
2843 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2844 		}
2845 	}
2846 
2847 exit:
2848 	/*
2849 	 * we don't want any uninvited guests scrogging our data when we're
2850 	 * busy with something, so for successful opens or failed opens
2851 	 * (except for EBUSY), reset these counters and state appropriately.
2852 	 */
2853 	if (rval != EBUSY) {
2854 		if (rval) {
2855 			un->un_state = ST_STATE_CLOSED;
2856 		}
2857 		un->un_err_resid = 0;
2858 		un->un_retry_ct = 0;
2859 		un->un_tran_retry_ct = 0;
2860 	}
2861 busy:
2862 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2863 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2864 	mutex_exit(ST_MUTEX);
2865 	return (rval);
2866 
2867 }
2868 
2869 static int
2870 st_tape_init(struct scsi_tape *un)
2871 {
2872 	int err;
2873 	int rval = 0;
2874 
2875 	ST_FUNC(ST_DEVINFO, st_tape_init);
2876 
2877 	ASSERT(mutex_owned(ST_MUTEX));
2878 
2879 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2880 	    "st_tape_init(un = 0x%p, oflags = %d)\n", (void*)un, un->un_oflags);
2881 
2882 	/*
2883 	 * Clean up after any errors left by 'last' close.
2884 	 * This also handles the case of the initial open.
2885 	 */
2886 	if (un->un_state != ST_STATE_INITIALIZING) {
2887 		un->un_laststate = un->un_state;
2888 		un->un_state = ST_STATE_OPENING;
2889 	}
2890 
2891 	un->un_kbytes_xferred = 0;
2892 
2893 	/*
2894 	 * do a throw away TUR to clear check condition
2895 	 */
2896 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2897 
2898 	/*
2899 	 * If test unit ready fails because the drive is reserved
2900 	 * by another host fail the open for no access.
2901 	 */
2902 	if (err) {
2903 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2904 			un->un_state = ST_STATE_CLOSED;
2905 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2906 			    "st_tape_init: RESERVATION CONFLICT\n");
2907 			rval = EACCES;
2908 			goto exit;
2909 		} else if ((un->un_rsvd_status &
2910 		    ST_APPLICATION_RESERVATIONS) != 0) {
2911 			if ((ST_RQSENSE != NULL) &&
2912 			    (ST_RQSENSE->es_add_code == 0x2a &&
2913 			    ST_RQSENSE->es_qual_code == 0x03)) {
2914 				un->un_state = ST_STATE_CLOSED;
2915 				rval = EACCES;
2916 				goto exit;
2917 			}
2918 		}
2919 	}
2920 
2921 	/*
2922 	 * Tape self identification could fail if the tape drive is used by
2923 	 * another host during attach time. We try to get the tape type
2924 	 * again. This is also applied to any posponed configuration methods.
2925 	 */
2926 	if (un->un_dp->type == ST_TYPE_INVALID) {
2927 		un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
2928 		st_known_tape_type(un);
2929 	}
2930 
2931 	/*
2932 	 * If the tape type is still invalid, try to determine the generic
2933 	 * configuration.
2934 	 */
2935 	if (un->un_dp->type == ST_TYPE_INVALID) {
2936 		rval = st_determine_generic(un);
2937 		if (rval) {
2938 			if (rval != EACCES) {
2939 				rval = EIO;
2940 			}
2941 			un->un_state = ST_STATE_CLOSED;
2942 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2943 			    "st_tape_init: %s invalid type\n",
2944 			    rval == EACCES ? "EACCES" : "EIO");
2945 			goto exit;
2946 		}
2947 		/*
2948 		 * If this is a Unknown Type drive,
2949 		 * Use the READ BLOCK LIMITS to determine if
2950 		 * allow large xfer is approprate if not globally
2951 		 * disabled with st_allow_large_xfer.
2952 		 */
2953 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
2954 	} else {
2955 
2956 		/*
2957 		 * If we allow_large_xfer (ie >64k) and have not yet found out
2958 		 * the max block size supported by the drive,
2959 		 * find it by issueing a READ_BLKLIM command.
2960 		 * if READ_BLKLIM cmd fails, assume drive doesn't
2961 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
2962 		 */
2963 		un->un_allow_large_xfer = st_allow_large_xfer &&
2964 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
2965 	}
2966 	/*
2967 	 * if maxbsize is unknown, set the maximum block size.
2968 	 */
2969 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
2970 
2971 		/*
2972 		 * Get the Block limits of the tape drive.
2973 		 * if un->un_allow_large_xfer = 0 , then make sure
2974 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
2975 		 */
2976 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
2977 
2978 		err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2979 		if (err) {
2980 			/* Retry */
2981 			err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2982 		}
2983 		if (!err) {
2984 
2985 			/*
2986 			 * if cmd successful, use limit returned
2987 			 */
2988 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
2989 			    (un->un_rbl->max_mid << 8) +
2990 			    un->un_rbl->max_lo;
2991 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
2992 			    un->un_rbl->min_lo;
2993 			un->un_data_mod = 1 << un->un_rbl->granularity;
2994 			if ((un->un_maxbsize == 0) ||
2995 			    (un->un_allow_large_xfer == 0 &&
2996 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
2997 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2998 
2999 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
3000 				/*
3001 				 * Drive is not one that is configured, But the
3002 				 * READ BLOCK LIMITS tells us it can do large
3003 				 * xfers.
3004 				 */
3005 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
3006 					un->un_dp->options |=
3007 					    ST_NO_RECSIZE_LIMIT;
3008 				}
3009 				/*
3010 				 * If max and mimimum block limits are the
3011 				 * same this is a fixed block size device.
3012 				 */
3013 				if (un->un_maxbsize == un->un_minbsize) {
3014 					un->un_dp->options &= ~ST_VARIABLE;
3015 				}
3016 			}
3017 
3018 			if (un->un_minbsize == 0) {
3019 				un->un_minbsize = 1;
3020 			}
3021 
3022 		} else { /* error on read block limits */
3023 
3024 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3025 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
3026 			    " errno = %d un_rsvd_status = 0x%X\n",
3027 			    err, un->un_rsvd_status);
3028 
3029 			/*
3030 			 * since read block limits cmd failed,
3031 			 * do not allow large xfers.
3032 			 * use old values in st_minphys
3033 			 */
3034 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
3035 				rval = EACCES;
3036 			} else {
3037 				un->un_allow_large_xfer = 0;
3038 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3039 				    "!Disabling large transfers\n");
3040 
3041 				/*
3042 				 * we guess maxbsize and minbsize
3043 				 */
3044 				if (un->un_bsize) {
3045 					un->un_maxbsize = un->un_minbsize =
3046 					    un->un_bsize;
3047 				} else {
3048 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3049 					un->un_minbsize = 1;
3050 				}
3051 				/*
3052 				 * Data Mod must be set,
3053 				 * Even if read block limits fails.
3054 				 * Prevents Divide By Zero in st_rw().
3055 				 */
3056 				un->un_data_mod = 1;
3057 			}
3058 		}
3059 		if (un->un_rbl) {
3060 			kmem_free(un->un_rbl, RBLSIZE);
3061 			un->un_rbl = NULL;
3062 		}
3063 
3064 		if (rval) {
3065 			goto exit;
3066 		}
3067 	}
3068 
3069 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3070 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
3071 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
3072 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
3073 
3074 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
3075 
3076 	if (err != 0) {
3077 		if (err == EINTR) {
3078 			un->un_laststate = un->un_state;
3079 			un->un_state = ST_STATE_CLOSED;
3080 			rval = EINTR;
3081 			goto exit;
3082 		}
3083 		/*
3084 		 * Make sure the tape is ready
3085 		 */
3086 		un->un_pos.pmode = invalid;
3087 		if (un->un_status != KEY_UNIT_ATTENTION) {
3088 			/*
3089 			 * allow open no media.  Subsequent MTIOCSTATE
3090 			 * with media present will complete the open
3091 			 * logic.
3092 			 */
3093 			un->un_laststate = un->un_state;
3094 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
3095 				un->un_mediastate = MTIO_EJECTED;
3096 				un->un_state = ST_STATE_OFFLINE;
3097 				rval = 0;
3098 				goto exit;
3099 			} else {
3100 				un->un_state = ST_STATE_CLOSED;
3101 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3102 				    "st_tape_init EIO no media, not opened "
3103 				    "O_NONBLOCK|O_EXCL\n");
3104 				rval = EIO;
3105 				goto exit;
3106 			}
3107 		}
3108 	}
3109 
3110 	/*
3111 	 * On each open, initialize block size from drivetype struct,
3112 	 * as it could have been changed by MTSRSZ ioctl.
3113 	 * Now, ST_VARIABLE simply means drive is capable of variable
3114 	 * mode. All drives are assumed to support fixed records.
3115 	 * Hence, un_bsize tells what mode the drive is in.
3116 	 *	un_bsize	= 0	- variable record length
3117 	 *			= x	- fixed record length is x
3118 	 */
3119 	un->un_bsize = un->un_dp->bsize;
3120 
3121 	/*
3122 	 * If saved position is valid go there
3123 	 */
3124 	if (un->un_restore_pos) {
3125 		un->un_restore_pos = 0;
3126 		un->un_pos.fileno = un->un_save_fileno;
3127 		un->un_pos.blkno = un->un_save_blkno;
3128 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &un->un_pos);
3129 		if (rval != 0) {
3130 			if (rval != EACCES) {
3131 				rval = EIO;
3132 			}
3133 			un->un_laststate = un->un_state;
3134 			un->un_state = ST_STATE_CLOSED;
3135 			goto exit;
3136 		}
3137 	}
3138 
3139 	if (un->un_pos.pmode == invalid) {
3140 		rval = st_loadtape(un);
3141 		if (rval) {
3142 			if (rval != EACCES) {
3143 				rval = EIO;
3144 			}
3145 			un->un_laststate = un->un_state;
3146 			un->un_state = ST_STATE_CLOSED;
3147 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3148 			    "st_tape_init: %s can't open tape\n",
3149 			    rval == EACCES ? "EACCES" : "EIO");
3150 			goto exit;
3151 		}
3152 	}
3153 
3154 	/*
3155 	 * do a mode sense to pick up state of current write-protect,
3156 	 * Could cause reserve and fail due to conflict.
3157 	 */
3158 	if (un->un_unit_attention_flags) {
3159 		rval = st_modesense(un);
3160 		if (rval == EACCES) {
3161 			goto exit;
3162 		}
3163 	}
3164 
3165 	/*
3166 	 * If we are opening the tape for writing, check
3167 	 * to make sure that the tape can be written.
3168 	 */
3169 	if (un->un_oflags & FWRITE) {
3170 		err = 0;
3171 		if (un->un_mspl->wp) {
3172 			un->un_status = KEY_WRITE_PROTECT;
3173 			un->un_laststate = un->un_state;
3174 			un->un_state = ST_STATE_CLOSED;
3175 			rval = EACCES;
3176 			/*
3177 			 * STK sets the wp bit if volsafe tape is loaded.
3178 			 */
3179 			if ((un->un_dp->type == MT_ISSTK9840) &&
3180 			    (un->un_dp->options & ST_WORMABLE)) {
3181 				un->un_read_only = RDONLY;
3182 			} else {
3183 				goto exit;
3184 			}
3185 		} else {
3186 			un->un_read_only = RDWR;
3187 		}
3188 	} else {
3189 		un->un_read_only = RDONLY;
3190 	}
3191 
3192 	if (un->un_dp->options & ST_WORMABLE &&
3193 	    un->un_unit_attention_flags) {
3194 		un->un_read_only |= un->un_wormable(un);
3195 
3196 		if (((un->un_read_only == WORM) ||
3197 		    (un->un_read_only == RDWORM)) &&
3198 		    ((un->un_oflags & FWRITE) == FWRITE)) {
3199 			un->un_status = KEY_DATA_PROTECT;
3200 			rval = EACCES;
3201 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3202 			    "read_only = %d eof = %d oflag = %d\n",
3203 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3204 		}
3205 	}
3206 
3207 	/*
3208 	 * If we're opening the tape write-only, we need to
3209 	 * write 2 filemarks on the HP 1/2 inch drive, to
3210 	 * create a null file.
3211 	 */
3212 	if ((un->un_read_only == RDWR) ||
3213 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3214 		if (un->un_dp->options & ST_REEL) {
3215 			un->un_fmneeded = 2;
3216 		} else {
3217 			un->un_fmneeded = 1;
3218 		}
3219 	} else {
3220 		un->un_fmneeded = 0;
3221 	}
3222 
3223 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3224 	    "fmneeded = %x\n", un->un_fmneeded);
3225 
3226 	/*
3227 	 * Make sure the density can be selected correctly.
3228 	 * If WORM can only write at the append point which in most cases
3229 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3230 	 * to set and try densities if a BOP.
3231 	 */
3232 	if (st_determine_density(un,
3233 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3234 		un->un_status = KEY_ILLEGAL_REQUEST;
3235 		un->un_laststate = un->un_state;
3236 		un->un_state = ST_STATE_CLOSED;
3237 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3238 		    "st_tape_init: EIO can't determine density\n");
3239 		rval = EIO;
3240 		goto exit;
3241 	}
3242 
3243 	/*
3244 	 * Destroy the knowledge that we have 'determined'
3245 	 * density so that a later read at BOT comes along
3246 	 * does the right density determination.
3247 	 */
3248 
3249 	un->un_density_known = 0;
3250 
3251 
3252 	/*
3253 	 * Okay, the tape is loaded and either at BOT or somewhere past.
3254 	 * Mark the state such that any I/O or tape space operations
3255 	 * will get/set the right density, etc..
3256 	 */
3257 	un->un_laststate = un->un_state;
3258 	un->un_lastop = ST_OP_NIL;
3259 	un->un_mediastate = MTIO_INSERTED;
3260 	cv_broadcast(&un->un_state_cv);
3261 
3262 	/*
3263 	 *  Set test append flag if writing.
3264 	 *  First write must check that tape is positioned correctly.
3265 	 */
3266 	un->un_test_append = (un->un_oflags & FWRITE);
3267 
3268 	/*
3269 	 * if there are pending unit attention flags.
3270 	 * Check that the media has not changed.
3271 	 */
3272 	if (un->un_unit_attention_flags) {
3273 		rval = st_get_media_identification(un, st_uscsi_cmd);
3274 		if (rval != 0 && rval != EACCES) {
3275 			rval = EIO;
3276 		}
3277 		un->un_unit_attention_flags = 0;
3278 	}
3279 
3280 exit:
3281 	un->un_err_resid = 0;
3282 	un->un_last_resid = 0;
3283 	un->un_last_count = 0;
3284 
3285 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3286 	    "st_tape_init: return val = %x\n", rval);
3287 	return (rval);
3288 
3289 }
3290 
3291 
3292 
3293 /* ARGSUSED */
3294 static int
3295 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3296 {
3297 	int err = 0;
3298 	int count, last_state;
3299 	minor_t minor = getminor(dev);
3300 #ifdef	__x86
3301 	struct contig_mem *cp, *cp_temp;
3302 #endif
3303 
3304 	GET_SOFT_STATE(dev);
3305 
3306 	ST_ENTR(ST_DEVINFO, st_close);
3307 
3308 	/*
3309 	 * wait till all cmds in the pipeline have been completed
3310 	 */
3311 	mutex_enter(ST_MUTEX);
3312 
3313 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3314 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3315 
3316 	st_wait_for_io(un);
3317 
3318 	/* turn off persistent errors on close, as we want close to succeed */
3319 	st_turn_pe_off(un);
3320 
3321 	/*
3322 	 * set state to indicate that we are in process of closing
3323 	 */
3324 	last_state = un->un_laststate = un->un_state;
3325 	un->un_state = ST_STATE_CLOSING;
3326 
3327 	ST_POS(ST_DEVINFO, "st_close1:", &un->un_pos);
3328 
3329 	/*
3330 	 * BSD behavior:
3331 	 * a close always causes a silent span to the next file if we've hit
3332 	 * an EOF (but not yet read across it).
3333 	 */
3334 	if ((minor & MT_BSD) && (un->un_pos.eof == ST_EOF)) {
3335 		if (un->un_pos.pmode != invalid) {
3336 			un->un_pos.fileno++;
3337 			un->un_pos.blkno = 0;
3338 		}
3339 		un->un_pos.eof = ST_NO_EOF;
3340 	}
3341 
3342 	/*
3343 	 * SVR4 behavior for skipping to next file:
3344 	 *
3345 	 * If we have not seen a filemark, space to the next file
3346 	 *
3347 	 * If we have already seen the filemark we are physically in the next
3348 	 * file and we only increment the filenumber
3349 	 */
3350 	if (((minor & (MT_BSD | MT_NOREWIND)) == MT_NOREWIND) &&
3351 	    (flag & FREAD) &&		/* reading or at least asked to */
3352 	    ((un->un_pos.blkno != 0) && 		/* inside a file */
3353 	    (un->un_lastop != ST_OP_WRITE) &&		/* Didn't just write */
3354 	    (un->un_lastop != ST_OP_WEOF))) {		/* or write filemarks */
3355 		switch (un->un_pos.eof) {
3356 		case ST_NO_EOF:
3357 			/*
3358 			 * if we were reading and did not read the complete file
3359 			 * skip to the next file, leaving the tape correctly
3360 			 * positioned to read the first record of the next file
3361 			 * Check first for REEL if we are at EOT by trying to
3362 			 * read a block
3363 			 */
3364 			if ((un->un_dp->options & ST_REEL) &&
3365 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3366 			    (un->un_pos.blkno == 0)) {
3367 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3368 					ST_DEBUG2(ST_DEVINFO, st_label,
3369 					    SCSI_DEBUG,
3370 					    "st_close : EIO can't space\n");
3371 					err = EIO;
3372 					break;
3373 				}
3374 				if (un->un_pos.eof >= ST_EOF_PENDING) {
3375 					un->un_pos.eof = ST_EOT_PENDING;
3376 					un->un_pos.fileno += 1;
3377 					un->un_pos.blkno   = 0;
3378 					break;
3379 				}
3380 			}
3381 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3382 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3383 				    "st_close: EIO can't space #2\n");
3384 				err = EIO;
3385 			} else {
3386 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3387 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3388 				    un->un_pos.fileno, un->un_pos.blkno,
3389 				    un->un_pos.eof);
3390 				un->un_pos.eof = ST_NO_EOF;
3391 			}
3392 			break;
3393 
3394 		case ST_EOF_PENDING:
3395 		case ST_EOF:
3396 			un->un_pos.fileno += 1;
3397 			un->un_pos.lgclblkno += 1;
3398 			un->un_pos.blkno   = 0;
3399 			un->un_pos.eof = ST_NO_EOF;
3400 			break;
3401 
3402 		case ST_EOT:
3403 		case ST_EOT_PENDING:
3404 			/* nothing to do */
3405 			break;
3406 		default:
3407 			scsi_log(ST_DEVINFO, st_label, CE_PANIC,
3408 			    "Undefined state 0x%x", un->un_pos.eof);
3409 
3410 		}
3411 	}
3412 
3413 
3414 	/*
3415 	 * For performance reasons (HP 88780), the driver should
3416 	 * postpone writing the second tape mark until just before a file
3417 	 * positioning ioctl is issued (e.g., rewind).	This means that
3418 	 * the user must not manually rewind the tape because the tape will
3419 	 * be missing the second tape mark which marks EOM.
3420 	 * However, this small performance improvement is not worth the risk.
3421 	 */
3422 
3423 	/*
3424 	 * We need to back up over the filemark we inadvertently popped
3425 	 * over doing a read in between the two filemarks that constitute
3426 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3427 	 * set while reading.
3428 	 *
3429 	 * If we happen to be at physical eot (ST_EOM) (writing case),
3430 	 * the writing of filemark(s) will clear the ST_EOM state, which
3431 	 * we don't want, so we save this state and restore it later.
3432 	 */
3433 
3434 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3435 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3436 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3437 
3438 	if (un->un_pos.eof == ST_EOT_PENDING) {
3439 		if (minor & MT_NOREWIND) {
3440 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3441 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3442 				    "st_close: EIO can't space #3\n");
3443 				err = EIO;
3444 			} else {
3445 				un->un_pos.blkno = 0;
3446 				un->un_pos.eof = ST_EOT;
3447 			}
3448 		} else {
3449 			un->un_pos.eof = ST_NO_EOF;
3450 		}
3451 
3452 	/*
3453 	 * Do we need to write a file mark?
3454 	 *
3455 	 * only write filemarks if there are fmks to be written and
3456 	 *   - open for write (possibly read/write)
3457 	 *   - the last operation was a write
3458 	 * or:
3459 	 *   -	opened for wronly
3460 	 *   -	no data was written
3461 	 */
3462 	} else if ((un->un_pos.pmode != invalid) &&
3463 	    (un->un_fmneeded > 0) &&
3464 	    (((flag & FWRITE) &&
3465 	    ((un->un_lastop == ST_OP_WRITE)||(un->un_lastop == ST_OP_WEOF))) ||
3466 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3467 
3468 		/* save ST_EOM state */
3469 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3470 
3471 		/*
3472 		 * Note that we will write a filemark if we had opened
3473 		 * the tape write only and no data was written, thus
3474 		 * creating a null file.
3475 		 *
3476 		 * If the user already wrote one, we only have to write 1 more.
3477 		 * If they wrote two, we don't have to write any.
3478 		 */
3479 
3480 		count = un->un_fmneeded;
3481 		if (count > 0) {
3482 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, count, SYNC_CMD)) {
3483 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3484 				    "st_close : EIO can't wfm\n");
3485 				err = EIO;
3486 			}
3487 			if ((un->un_dp->options & ST_REEL) &&
3488 			    (minor & MT_NOREWIND)) {
3489 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3490 					ST_DEBUG2(ST_DEVINFO, st_label,
3491 					    SCSI_DEBUG,
3492 					    "st_close : EIO space fmk(-1)\n");
3493 					err = EIO;
3494 				}
3495 				un->un_pos.eof = ST_NO_EOF;
3496 				/* fix up block number */
3497 				un->un_pos.blkno = 0;
3498 			}
3499 		}
3500 
3501 		/*
3502 		 * If we aren't going to be rewinding, and we were at
3503 		 * physical eot, restore the state that indicates we
3504 		 * are at physical eot. Once you have reached physical
3505 		 * eot, and you close the tape, the only thing you can
3506 		 * do on the next open is to rewind. Access to trailer
3507 		 * records is only allowed without closing the device.
3508 		 */
3509 		if ((minor & MT_NOREWIND) == 0 && was_at_eom) {
3510 			un->un_pos.eof = ST_EOM;
3511 		}
3512 	}
3513 
3514 	/*
3515 	 * report soft errors if enabled and available, if we never accessed
3516 	 * the drive, don't get errors. This will prevent some DAT error
3517 	 * messages upon LOG SENSE.
3518 	 */
3519 	if (st_report_soft_errors_on_close &&
3520 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3521 	    (last_state != ST_STATE_OFFLINE)) {
3522 		(void) st_report_soft_errors(dev, flag);
3523 	}
3524 
3525 
3526 	/*
3527 	 * Do we need to rewind? Can we rewind?
3528 	 */
3529 	if ((minor & MT_NOREWIND) == 0 &&
3530 	    un->un_pos.pmode != invalid && err == 0) {
3531 		/*
3532 		 * We'd like to rewind with the
3533 		 * 'immediate' bit set, but this
3534 		 * causes problems on some drives
3535 		 * where subsequent opens get a
3536 		 * 'NOT READY' error condition
3537 		 * back while the tape is rewinding,
3538 		 * which is impossible to distinguish
3539 		 * from the condition of 'no tape loaded'.
3540 		 *
3541 		 * Also, for some targets, if you disconnect
3542 		 * with the 'immediate' bit set, you don't
3543 		 * actually return right away, i.e., the
3544 		 * target ignores your request for immediate
3545 		 * return.
3546 		 *
3547 		 * Instead, we'll fire off an async rewind
3548 		 * command. We'll mark the device as closed,
3549 		 * and any subsequent open will stall on
3550 		 * the first TEST_UNIT_READY until the rewind
3551 		 * completes.
3552 		 */
3553 
3554 		/*
3555 		 * Used to be if reserve was not supported we'd send an
3556 		 * asynchronious rewind. Comments above may be slightly invalid
3557 		 * as the immediate bit was never set. Doing an immedate rewind
3558 		 * makes sense, I think fixes to not ready status might handle
3559 		 * the problems described above.
3560 		 */
3561 		if (un->un_sd->sd_inq->inq_ansi < 2) {
3562 			(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
3563 		} else {
3564 			/* flush data for older drives per scsi spec. */
3565 			(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
3566 			(void) st_cmd(un, SCMD_REWIND, 1, ASYNC_CMD);
3567 		}
3568 	}
3569 
3570 	/*
3571 	 * eject tape if necessary
3572 	 */
3573 	if (un->un_eject_tape_on_failure) {
3574 		un->un_eject_tape_on_failure = 0;
3575 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3576 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3577 			    "st_close : can't unload tape\n");
3578 		} else {
3579 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3580 			    "st_close : tape unloaded \n");
3581 			un->un_pos.eof = ST_NO_EOF;
3582 			un->un_mediastate = MTIO_EJECTED;
3583 		}
3584 	}
3585 	/*
3586 	 * Release the tape unit, if default reserve/release
3587 	 * behaviour.
3588 	 */
3589 	if ((un->un_rsvd_status &
3590 	    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
3591 		(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
3592 	}
3593 
3594 	/*
3595 	 * clear up state
3596 	 */
3597 	un->un_laststate = un->un_state;
3598 	un->un_state = ST_STATE_CLOSED;
3599 	un->un_lastop = ST_OP_NIL;
3600 	un->un_throttle = 1;	/* assume one request at time, for now */
3601 	un->un_retry_ct = 0;
3602 	un->un_tran_retry_ct = 0;
3603 	un->un_errno = 0;
3604 	un->un_swr_token = (opaque_t)NULL;
3605 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3606 
3607 	/* Restore the options to the init time settings */
3608 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3609 		un->un_dp->options |= ST_READ_IGNORE_ILI;
3610 	} else {
3611 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3612 	}
3613 
3614 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3615 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3616 	} else {
3617 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3618 	}
3619 
3620 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3621 		un->un_dp->options |= ST_SHORT_FILEMARKS;
3622 	} else {
3623 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3624 	}
3625 
3626 	ASSERT(mutex_owned(ST_MUTEX));
3627 
3628 	/*
3629 	 * Signal anyone awaiting a close operation to complete.
3630 	 */
3631 	cv_signal(&un->un_clscv);
3632 
3633 	/*
3634 	 * any kind of error on closing causes all state to be tossed
3635 	 */
3636 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3637 		/*
3638 		 * note that st_intr has already set
3639 		 * un_pos.pmode to invalid.
3640 		 */
3641 		un->un_density_known = 0;
3642 	}
3643 
3644 #ifdef	__x86
3645 	/*
3646 	 * free any contiguous mem alloc'ed for big block I/O
3647 	 */
3648 	cp = un->un_contig_mem;
3649 	while (cp) {
3650 		if (cp->cm_addr) {
3651 			ddi_dma_mem_free(&cp->cm_acc_hdl);
3652 		}
3653 		cp_temp = cp;
3654 		cp = cp->cm_next;
3655 		kmem_free(cp_temp,
3656 		    sizeof (struct contig_mem) + biosize());
3657 	}
3658 	un->un_contig_mem_total_num = 0;
3659 	un->un_contig_mem_available_num = 0;
3660 	un->un_contig_mem = NULL;
3661 	un->un_max_contig_mem_len = 0;
3662 #endif
3663 
3664 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3665 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3666 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3667 
3668 	mutex_exit(ST_MUTEX);
3669 	return (err);
3670 }
3671 
3672 /*
3673  * These routines perform raw i/o operations.
3674  */
3675 
3676 /* ARGSUSED2 */
3677 static int
3678 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3679 {
3680 #ifdef STDEBUG
3681 	GET_SOFT_STATE(dev);
3682 	ST_ENTR(ST_DEVINFO, st_aread);
3683 #endif
3684 	return (st_arw(dev, aio, B_READ));
3685 }
3686 
3687 
3688 /* ARGSUSED2 */
3689 static int
3690 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3691 {
3692 #ifdef STDEBUG
3693 	GET_SOFT_STATE(dev);
3694 	ST_ENTR(ST_DEVINFO, st_awrite);
3695 #endif
3696 	return (st_arw(dev, aio, B_WRITE));
3697 }
3698 
3699 
3700 
3701 /* ARGSUSED */
3702 static int
3703 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3704 {
3705 #ifdef STDEBUG
3706 	GET_SOFT_STATE(dev);
3707 	ST_ENTR(ST_DEVINFO, st_read);
3708 #endif
3709 	return (st_rw(dev, uiop, B_READ));
3710 }
3711 
3712 /* ARGSUSED */
3713 static int
3714 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3715 {
3716 #ifdef STDEBUG
3717 	GET_SOFT_STATE(dev);
3718 	ST_ENTR(ST_DEVINFO, st_write);
3719 #endif
3720 	return (st_rw(dev, uiop, B_WRITE));
3721 }
3722 
3723 /*
3724  * Due to historical reasons, old limits are: For variable-length devices:
3725  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3726  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3727  * (let it through unmodified. For fixed-length record devices:
3728  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3729  *
3730  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3731  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3732  * command to the drive).
3733  *
3734  */
3735 static void
3736 st_minphys(struct buf *bp)
3737 {
3738 	struct scsi_tape *un;
3739 
3740 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3741 
3742 	ST_FUNC(ST_DEVINFO, st_minphys);
3743 
3744 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3745 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3746 	    bp->b_bcount);
3747 
3748 	if (un->un_allow_large_xfer) {
3749 
3750 		/*
3751 		 * check un_maxbsize for variable length devices only
3752 		 */
3753 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3754 			bp->b_bcount = un->un_maxbsize;
3755 		}
3756 		/*
3757 		 * can't go more that HBA maxdma limit in either fixed-length
3758 		 * or variable-length tape drives.
3759 		 */
3760 		if (bp->b_bcount > un->un_maxdma) {
3761 			bp->b_bcount = un->un_maxdma;
3762 		}
3763 	} else {
3764 
3765 		/*
3766 		 *  use old fixed limits
3767 		 */
3768 		if (un->un_bsize == 0) {
3769 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3770 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3771 			}
3772 		} else {
3773 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3774 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3775 			}
3776 		}
3777 	}
3778 
3779 	/*
3780 	 * For regular raw I/O and Fixed Block length devices, make sure
3781 	 * the adjusted block count is a whole multiple of the device
3782 	 * block size.
3783 	 */
3784 	if (bp != un->un_sbufp && un->un_bsize) {
3785 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3786 	}
3787 }
3788 
3789 static int
3790 st_rw(dev_t dev, struct uio *uio, int flag)
3791 {
3792 	int rval = 0;
3793 	long len;
3794 
3795 	GET_SOFT_STATE(dev);
3796 
3797 	ST_FUNC(ST_DEVINFO, st_rw);
3798 
3799 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3800 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3801 	    (flag == B_READ ? rd_str: wr_str));
3802 
3803 	/* get local copy of transfer length */
3804 	len = uio->uio_iov->iov_len;
3805 
3806 	mutex_enter(ST_MUTEX);
3807 
3808 	/*
3809 	 * Clear error entry stack
3810 	 */
3811 	st_empty_error_stack(un);
3812 
3813 	/*
3814 	 * If in fixed block size mode and requested read or write
3815 	 * is not an even multiple of that block size.
3816 	 */
3817 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3818 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3819 		    "%s: not modulo %d block size\n",
3820 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3821 		rval = EINVAL;
3822 	}
3823 
3824 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3825 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3826 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3827 		    "%s: not modulo %d device granularity\n",
3828 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3829 		rval = EINVAL;
3830 	}
3831 
3832 	if (rval != 0) {
3833 		un->un_errno = rval;
3834 		mutex_exit(ST_MUTEX);
3835 		return (rval);
3836 	}
3837 
3838 	/*
3839 	 * Reset this so it can be set if Berkeley and read over a filemark.
3840 	 */
3841 	un->un_silent_skip = 0;
3842 	mutex_exit(ST_MUTEX);
3843 
3844 	len = uio->uio_resid;
3845 
3846 	rval = physio(st_queued_strategy, (struct buf *)NULL,
3847 	    dev, flag, st_minphys, uio);
3848 	/*
3849 	 * if we have hit logical EOT during this xfer and there is not a
3850 	 * full residue, then set eof back  to ST_EOM to make sure that
3851 	 * the user will see at least one zero write
3852 	 * after this short write
3853 	 */
3854 	mutex_enter(ST_MUTEX);
3855 	if (un->un_pos.eof > ST_NO_EOF) {
3856 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3857 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3858 	}
3859 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3860 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3861 			un->un_pos.eof = ST_EOM;
3862 		} else if (uio->uio_resid == len) {
3863 			un->un_pos.eof = ST_NO_EOF;
3864 		}
3865 	}
3866 
3867 	if (un->un_silent_skip && uio->uio_resid != len) {
3868 		un->un_pos.eof = ST_EOF;
3869 		un->un_pos.blkno = un->un_save_blkno;
3870 		un->un_pos.fileno--;
3871 	}
3872 
3873 	un->un_errno = rval;
3874 
3875 	mutex_exit(ST_MUTEX);
3876 
3877 	return (rval);
3878 }
3879 
3880 static int
3881 st_arw(dev_t dev, struct aio_req *aio, int flag)
3882 {
3883 	struct uio *uio = aio->aio_uio;
3884 	int rval = 0;
3885 	long len;
3886 
3887 	GET_SOFT_STATE(dev);
3888 
3889 	ST_FUNC(ST_DEVINFO, st_arw);
3890 
3891 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3892 	    "st_arw(dev = 0x%lx, flag = %s)\n", dev,
3893 	    (flag == B_READ ? rd_str: wr_str));
3894 
3895 	/* get local copy of transfer length */
3896 	len = uio->uio_iov->iov_len;
3897 
3898 	mutex_enter(ST_MUTEX);
3899 
3900 	/*
3901 	 * If in fixed block size mode and requested read or write
3902 	 * is not an even multiple of that block size.
3903 	 */
3904 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3905 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3906 		    "%s: not modulo %d block size\n",
3907 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3908 		rval = EINVAL;
3909 	}
3910 
3911 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3912 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3913 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3914 		    "%s: not modulo %d device granularity\n",
3915 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3916 		rval = EINVAL;
3917 	}
3918 
3919 	if (rval != 0) {
3920 		un->un_errno = rval;
3921 		mutex_exit(ST_MUTEX);
3922 		return (rval);
3923 	}
3924 
3925 	mutex_exit(ST_MUTEX);
3926 
3927 	len = uio->uio_resid;
3928 
3929 	rval =
3930 	    aphysio(st_queued_strategy, anocancel, dev, flag, st_minphys, aio);
3931 
3932 	/*
3933 	 * if we have hit logical EOT during this xfer and there is not a
3934 	 * full residue, then set eof back  to ST_EOM to make sure that
3935 	 * the user will see at least one zero write
3936 	 * after this short write
3937 	 *
3938 	 * we keep this here just in case the application is not using
3939 	 * persistent errors
3940 	 */
3941 	mutex_enter(ST_MUTEX);
3942 	if (un->un_pos.eof > ST_NO_EOF) {
3943 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3944 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3945 	}
3946 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3947 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3948 			un->un_pos.eof = ST_EOM;
3949 		} else if (uio->uio_resid == len &&
3950 		    !(un->un_persistence && un->un_persist_errors)) {
3951 			un->un_pos.eof = ST_NO_EOF;
3952 		}
3953 	}
3954 	un->un_errno = rval;
3955 	mutex_exit(ST_MUTEX);
3956 
3957 	return (rval);
3958 }
3959 
3960 
3961 
3962 static int
3963 st_queued_strategy(buf_t *bp)
3964 {
3965 	struct scsi_tape *un;
3966 	char reading = bp->b_flags & B_READ;
3967 	int wasopening = 0;
3968 
3969 	/*
3970 	 * validate arguments
3971 	 */
3972 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3973 	if (un == NULL) {
3974 		bp->b_resid = bp->b_bcount;
3975 		bioerror(bp, ENXIO);
3976 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
3977 		    "st_queued_strategy: ENXIO error exit\n");
3978 		biodone(bp);
3979 		return (0);
3980 	}
3981 
3982 	ST_ENTR(ST_DEVINFO, st_queued_strategy);
3983 
3984 	mutex_enter(ST_MUTEX);
3985 
3986 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
3987 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
3988 	}
3989 
3990 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3991 	    "st_queued_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
3992 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3993 
3994 	/*
3995 	 * If persistent errors have been flagged, just nix this one. We wait
3996 	 * for any outstanding I/O's below, so we will be in order.
3997 	 */
3998 	if (un->un_persistence && un->un_persist_errors) {
3999 		goto exit;
4000 	}
4001 
4002 	/*
4003 	 * If last command was non queued, wait till it finishes.
4004 	 */
4005 	while (un->un_sbuf_busy) {
4006 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
4007 		/* woke up because of an error */
4008 		if (un->un_persistence && un->un_persist_errors) {
4009 			goto exit;
4010 		}
4011 	}
4012 
4013 	/*
4014 	 * s_buf and recovery commands shouldn't come here.
4015 	 */
4016 	ASSERT(bp != un->un_recov_buf);
4017 	ASSERT(bp != un->un_sbufp);
4018 
4019 	/*
4020 	 * If we haven't done/checked reservation on the tape unit
4021 	 * do it now.
4022 	 */
4023 	if ((un->un_rsvd_status &
4024 	    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
4025 		if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
4026 			if (st_reserve_release(un, ST_RESERVE, st_uscsi_cmd)) {
4027 				st_bioerror(bp, un->un_errno);
4028 				goto exit;
4029 			}
4030 		} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4031 			/*
4032 			 * Enter here to restore position for possible
4033 			 * resets when the device was closed and opened
4034 			 * in O_NDELAY mode subsequently
4035 			 */
4036 			un->un_state = ST_STATE_INITIALIZING;
4037 			(void) st_cmd(un, SCMD_TEST_UNIT_READY,
4038 			    0, SYNC_CMD);
4039 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4040 		}
4041 		un->un_rsvd_status |= ST_INIT_RESERVE;
4042 	}
4043 
4044 	/*
4045 	 * If we are offline, we have to initialize everything first.
4046 	 * This is to handle either when opened with O_NDELAY, or
4047 	 * we just got a new tape in the drive, after an offline.
4048 	 * We don't observe O_NDELAY past the open,
4049 	 * as it will not make sense for tapes.
4050 	 */
4051 	if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
4052 		/*
4053 		 * reset state to avoid recursion
4054 		 */
4055 		un->un_laststate = un->un_state;
4056 		un->un_state = ST_STATE_INITIALIZING;
4057 		if (st_tape_init(un)) {
4058 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4059 			    "stioctl : OFFLINE init failure ");
4060 			un->un_state = ST_STATE_OFFLINE;
4061 			un->un_pos.pmode = invalid;
4062 			goto b_done_err;
4063 		}
4064 		/* WTF un_restore_pos make invalid */
4065 		un->un_state = ST_STATE_OPEN_PENDING_IO;
4066 		un->un_restore_pos = 0;
4067 	}
4068 	/*
4069 	 * Check for legal operations
4070 	 */
4071 	if (un->un_pos.pmode == invalid) {
4072 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4073 		    "strategy with un->un_pos.pmode invalid\n");
4074 		goto b_done_err;
4075 	}
4076 
4077 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4078 	    "st_queued_strategy(): regular io\n");
4079 
4080 	/*
4081 	 * Process this first. If we were reading, and we're pending
4082 	 * logical eot, that means we've bumped one file mark too far.
4083 	 */
4084 
4085 	/*
4086 	 * Recursion warning: st_cmd will route back through here.
4087 	 * Not anymore st_cmd will go through st_strategy()!
4088 	 */
4089 	if (un->un_pos.eof == ST_EOT_PENDING) {
4090 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4091 			un->un_pos.pmode = invalid;
4092 			un->un_density_known = 0;
4093 			goto b_done_err;
4094 		}
4095 		un->un_pos.blkno = 0; /* fix up block number.. */
4096 		un->un_pos.eof = ST_EOT;
4097 	}
4098 
4099 	/*
4100 	 * If we are in the process of opening, we may have to
4101 	 * determine/set the correct density. We also may have
4102 	 * to do a test_append (if QIC) to see whether we are
4103 	 * in a position to append to the end of the tape.
4104 	 *
4105 	 * If we're already at logical eot, we transition
4106 	 * to ST_NO_EOF. If we're at physical eot, we punt
4107 	 * to the switch statement below to handle.
4108 	 */
4109 	if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
4110 	    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
4111 
4112 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4113 			if (st_determine_density(un, (int)reading)) {
4114 				goto b_done_err;
4115 			}
4116 		}
4117 
4118 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4119 		    "pending_io@fileno %d rw %d qic %d eof %d\n",
4120 		    un->un_pos.fileno, (int)reading,
4121 		    (un->un_dp->options & ST_QIC) ? 1 : 0,
4122 		    un->un_pos.eof);
4123 
4124 		if (!reading && un->un_pos.eof != ST_EOM) {
4125 			if (un->un_pos.eof == ST_EOT) {
4126 				un->un_pos.eof = ST_NO_EOF;
4127 			} else if (un->un_pos.pmode != invalid &&
4128 			    (un->un_dp->options & ST_QIC)) {
4129 				/*
4130 				 * st_test_append() will do it all
4131 				 */
4132 				st_test_append(bp);
4133 				mutex_exit(ST_MUTEX);
4134 				return (0);
4135 			}
4136 		}
4137 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4138 			wasopening = 1;
4139 		}
4140 		un->un_laststate = un->un_state;
4141 		un->un_state = ST_STATE_OPEN;
4142 	}
4143 
4144 
4145 	/*
4146 	 * Process rest of END OF FILE and END OF TAPE conditions
4147 	 */
4148 
4149 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4150 	    "eof=%x, wasopening=%x\n",
4151 	    un->un_pos.eof, wasopening);
4152 
4153 	switch (un->un_pos.eof) {
4154 	case ST_EOM:
4155 		/*
4156 		 * This allows writes to proceed past physical
4157 		 * eot. We'll *really* be in trouble if the
4158 		 * user continues blindly writing data too
4159 		 * much past this point (unwind the tape).
4160 		 * Physical eot really means 'early warning
4161 		 * eot' in this context.
4162 		 *
4163 		 * Every other write from now on will succeed
4164 		 * (if sufficient  tape left).
4165 		 * This write will return with resid == count
4166 		 * but the next one should be successful
4167 		 *
4168 		 * Note that we only transition to logical EOT
4169 		 * if the last state wasn't the OPENING state.
4170 		 * We explicitly prohibit running up to physical
4171 		 * eot, closing the device, and then re-opening
4172 		 * to proceed. Trailer records may only be gotten
4173 		 * at by keeping the tape open after hitting eot.
4174 		 *
4175 		 * Also note that ST_EOM cannot be set by reading-
4176 		 * this can only be set during writing. Reading
4177 		 * up to the end of the tape gets a blank check
4178 		 * or a double-filemark indication (ST_EOT_PENDING),
4179 		 * and we prohibit reading after that point.
4180 		 *
4181 		 */
4182 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
4183 		if (wasopening == 0) {
4184 			/*
4185 			 * this allows st_rw() to reset it back to
4186 			 * will see a zero write
4187 			 */
4188 			un->un_pos.eof = ST_WRITE_AFTER_EOM;
4189 		}
4190 		un->un_status = SUN_KEY_EOT;
4191 		goto b_done;
4192 
4193 	case ST_WRITE_AFTER_EOM:
4194 	case ST_EOT:
4195 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
4196 		un->un_status = SUN_KEY_EOT;
4197 		if (SVR4_BEHAVIOR && reading) {
4198 			goto b_done_err;
4199 		}
4200 
4201 		if (reading) {
4202 			goto b_done;
4203 		}
4204 		un->un_pos.eof = ST_NO_EOF;
4205 		break;
4206 
4207 	case ST_EOF_PENDING:
4208 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4209 		    "EOF PENDING\n");
4210 		un->un_status = SUN_KEY_EOF;
4211 		if (SVR4_BEHAVIOR) {
4212 			un->un_pos.eof = ST_EOF;
4213 			goto b_done;
4214 		}
4215 		/* FALLTHROUGH */
4216 	case ST_EOF:
4217 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
4218 		un->un_status = SUN_KEY_EOF;
4219 		if (SVR4_BEHAVIOR) {
4220 			goto b_done_err;
4221 		}
4222 
4223 		if (BSD_BEHAVIOR) {
4224 			un->un_pos.eof = ST_NO_EOF;
4225 			un->un_pos.fileno += 1;
4226 			un->un_pos.blkno   = 0;
4227 		}
4228 
4229 		if (reading) {
4230 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4231 			    "now file %d (read)\n",
4232 			    un->un_pos.fileno);
4233 			goto b_done;
4234 		}
4235 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4236 		    "now file %d (write)\n", un->un_pos.fileno);
4237 		break;
4238 	default:
4239 		un->un_status = 0;
4240 		break;
4241 	}
4242 
4243 	bp->b_flags &= ~(B_DONE);
4244 	st_bioerror(bp, 0);
4245 	bp->av_forw = NULL;
4246 	bp->b_resid = 0;
4247 	SET_BP_PKT(bp, 0);
4248 
4249 
4250 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4251 	    "st_queued_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4252 	    " pkt=0x%p\n",
4253 	    (void *)bp->b_forw, bp->b_bcount,
4254 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4255 
4256 #ifdef	__x86
4257 	/*
4258 	 * We will replace bp with a new bp that can do big blk xfer
4259 	 * if the requested xfer size is bigger than un->un_maxdma_arch
4260 	 *
4261 	 * Also, we need to make sure that we're handling real I/O
4262 	 * by checking group 0/1 SCSI I/O commands, if needed
4263 	 */
4264 	if (bp->b_bcount > un->un_maxdma_arch &&
4265 	    ((uchar_t)(uintptr_t)bp->b_forw == SCMD_READ ||
4266 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G4 ||
4267 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE ||
4268 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G4)) {
4269 		mutex_exit(ST_MUTEX);
4270 		bp = st_get_bigblk_bp(bp);
4271 		mutex_enter(ST_MUTEX);
4272 	}
4273 #endif
4274 
4275 	/* put on wait queue */
4276 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4277 	    "st_queued_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4278 	    (void *)un->un_quef, (void *)bp);
4279 
4280 	st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quel, bp);
4281 
4282 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4283 
4284 	st_start(un);
4285 
4286 	mutex_exit(ST_MUTEX);
4287 	return (0);
4288 
4289 b_done_err:
4290 	st_bioerror(bp, EIO);
4291 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4292 	    "st_queued_strategy : EIO b_done_err\n");
4293 
4294 b_done:
4295 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4296 	    "st_queued_strategy: b_done\n");
4297 
4298 exit:
4299 	/*
4300 	 * make sure no commands are outstanding or waiting before closing,
4301 	 * so we can guarantee order
4302 	 */
4303 	st_wait_for_io(un);
4304 	un->un_err_resid = bp->b_resid = bp->b_bcount;
4305 
4306 	/* override errno here, if persistent errors were flagged */
4307 	if (un->un_persistence && un->un_persist_errors)
4308 		bioerror(bp, un->un_errno);
4309 
4310 	mutex_exit(ST_MUTEX);
4311 
4312 	biodone(bp);
4313 	ASSERT(mutex_owned(ST_MUTEX) == 0);
4314 	return (0);
4315 }
4316 
4317 
4318 static int
4319 st_strategy(struct buf *bp)
4320 {
4321 	struct scsi_tape *un;
4322 
4323 	/*
4324 	 * validate arguments
4325 	 */
4326 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4327 	if (un == NULL) {
4328 		bp->b_resid = bp->b_bcount;
4329 		bioerror(bp, ENXIO);
4330 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4331 		    "st_strategy: ENXIO error exit\n");
4332 
4333 		biodone(bp);
4334 		return (0);
4335 
4336 	}
4337 
4338 	ST_ENTR(ST_DEVINFO, st_strategy);
4339 
4340 	mutex_enter(ST_MUTEX);
4341 
4342 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4343 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4344 	}
4345 
4346 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4347 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4348 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4349 
4350 	ASSERT((bp == un->un_recov_buf) || (bp == un->un_sbufp));
4351 
4352 	bp->b_flags &= ~(B_DONE);
4353 	st_bioerror(bp, 0);
4354 	bp->av_forw = NULL;
4355 	bp->b_resid = 0;
4356 	SET_BP_PKT(bp, 0);
4357 
4358 
4359 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4360 	    "st_strategy: cmd=0x%x  count=%ld  resid=%ld flags=0x%x"
4361 	    " pkt=0x%p\n",
4362 	    (unsigned char)(uintptr_t)bp->b_forw, bp->b_bcount,
4363 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4364 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4365 
4366 	st_start(un);
4367 
4368 	mutex_exit(ST_MUTEX);
4369 	return (0);
4370 }
4371 
4372 /*
4373  * this routine spaces forward over filemarks
4374  */
4375 static int
4376 st_space_fmks(struct scsi_tape *un, long count)
4377 {
4378 	int rval = 0;
4379 
4380 	ST_FUNC(ST_DEVINFO, st_space_fmks);
4381 
4382 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4383 	    "st_space_fmks(dev = 0x%lx, count = %ld)\n", un->un_dev, count);
4384 
4385 	ASSERT(mutex_owned(ST_MUTEX));
4386 
4387 	/*
4388 	 * the risk with doing only one space operation is that we
4389 	 * may accidentily jump in old data
4390 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4391 	 * because the 8200 does not append a marker; in order not to
4392 	 * sacrifice the fast file skip, we do a slow skip if the low
4393 	 * density device has been opened
4394 	 */
4395 
4396 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4397 	    !((un->un_dp->type == ST_TYPE_EXB8500 &&
4398 	    MT_DENSITY(un->un_dev) == 0))) {
4399 		if (st_cmd(un, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4400 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4401 			    "space_fmks : EIO can't do space cmd #1\n");
4402 			rval = EIO;
4403 		}
4404 	} else {
4405 		while (count > 0) {
4406 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4407 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4408 				    "space_fmks : EIO can't do space cmd #2\n");
4409 				rval = EIO;
4410 				break;
4411 			}
4412 			count -= 1;
4413 			/*
4414 			 * read a block to see if we have reached
4415 			 * end of medium (double filemark for reel or
4416 			 * medium error for others)
4417 			 */
4418 			if (count > 0) {
4419 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
4420 					ST_DEBUG2(ST_DEVINFO, st_label,
4421 					    SCSI_DEBUG,
4422 					    "space_fmks : EIO can't do "
4423 					    "space cmd #3\n");
4424 					rval = EIO;
4425 					break;
4426 				}
4427 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4428 				    (un->un_dp->options & ST_REEL)) {
4429 					un->un_status = SUN_KEY_EOT;
4430 					ST_DEBUG2(ST_DEVINFO, st_label,
4431 					    SCSI_DEBUG,
4432 					    "space_fmks : EIO ST_REEL\n");
4433 					rval = EIO;
4434 					break;
4435 				} else if (IN_EOF(un->un_pos)) {
4436 					un->un_pos.eof = ST_NO_EOF;
4437 					un->un_pos.fileno++;
4438 					un->un_pos.blkno = 0;
4439 					count--;
4440 				} else if (un->un_pos.eof > ST_EOF) {
4441 					ST_DEBUG2(ST_DEVINFO, st_label,
4442 					    SCSI_DEBUG,
4443 					    "space_fmks, EIO > ST_EOF\n");
4444 					rval = EIO;
4445 					break;
4446 				}
4447 
4448 			}
4449 		}
4450 		un->un_err_resid = count;
4451 		COPY_POS(&un->un_pos, &un->un_err_pos);
4452 	}
4453 	ASSERT(mutex_owned(ST_MUTEX));
4454 	return (rval);
4455 }
4456 
4457 /*
4458  * this routine spaces to EOD
4459  *
4460  * it keeps track of the current filenumber and returns the filenumber after
4461  * the last successful space operation, we keep the number high because as
4462  * tapes are getting larger, the possibility of more and more files exist,
4463  * 0x100000 (1 Meg of files) probably will never have to be changed any time
4464  * soon
4465  */
4466 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4467 
4468 static int
4469 st_find_eod(struct scsi_tape *un)
4470 {
4471 	tapepos_t savepos;
4472 	int64_t sp_type;
4473 	int result;
4474 
4475 	if (un == NULL) {
4476 		return (-1);
4477 	}
4478 
4479 	ST_FUNC(ST_DEVINFO, st_find_eod);
4480 
4481 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4482 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", un->un_dev,
4483 	    un->un_pos.fileno);
4484 
4485 	ASSERT(mutex_owned(ST_MUTEX));
4486 
4487 	COPY_POS(&savepos, &un->un_pos);
4488 
4489 	/*
4490 	 * see if the drive is smart enough to do the skips in
4491 	 * one operation; 1/2" use two filemarks
4492 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4493 	 * because the 8200 does not append a marker; in order not to
4494 	 * sacrifice the fast file skip, we do a slow skip if the low
4495 	 * density device has been opened
4496 	 */
4497 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4498 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4499 		    (MT_DENSITY(un->un_dev) == 0)) {
4500 			sp_type = Fmk(1);
4501 		} else if (un->un_pos.pmode == logical) {
4502 			sp_type = SPACE(SP_EOD, 0);
4503 		} else {
4504 			sp_type = Fmk(MAX_SKIP);
4505 		}
4506 	} else {
4507 		sp_type = Fmk(1);
4508 	}
4509 
4510 	for (;;) {
4511 		result = st_cmd(un, SCMD_SPACE, sp_type, SYNC_CMD);
4512 
4513 		if (result == 0) {
4514 			COPY_POS(&savepos, &un->un_pos);
4515 		}
4516 
4517 		if (sp_type == SPACE(SP_EOD, 0)) {
4518 			if (result != 0) {
4519 				sp_type = Fmk(MAX_SKIP);
4520 				continue;
4521 			}
4522 
4523 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4524 			    "st_find_eod: 0x%"PRIx64"\n",
4525 			    savepos.lgclblkno);
4526 			/*
4527 			 * What we return will become the current file position.
4528 			 * After completing the space command with the position
4529 			 * mode that is not invalid a read position command will
4530 			 * be automaticly issued. If the drive support the long
4531 			 * read position format a valid file position can be
4532 			 * returned.
4533 			 */
4534 			return (un->un_pos.fileno);
4535 		}
4536 
4537 		if (result != 0) {
4538 			break;
4539 		}
4540 
4541 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4542 		    "count=%"PRIx64", eof=%x, status=%x\n",
4543 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4544 
4545 		/*
4546 		 * If we're not EOM smart,  space a record
4547 		 * to see whether we're now in the slot between
4548 		 * the two sequential filemarks that logical
4549 		 * EOM consists of (REEL) or hit nowhere land
4550 		 * (8mm).
4551 		 */
4552 		if (sp_type == Fmk(1)) {
4553 			/*
4554 			 * no fast skipping, check a record
4555 			 */
4556 			if (st_cmd(un, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4557 				break;
4558 			}
4559 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4560 			    (un->un_dp->options & ST_REEL)) {
4561 				un->un_status = KEY_BLANK_CHECK;
4562 				un->un_pos.fileno++;
4563 				un->un_pos.blkno = 0;
4564 				break;
4565 			}
4566 			if (IN_EOF(un->un_pos)) {
4567 				un->un_pos.eof = ST_NO_EOF;
4568 				un->un_pos.fileno++;
4569 				un->un_pos.blkno = 0;
4570 			}
4571 			if (un->un_pos.eof > ST_EOF) {
4572 				break;
4573 			}
4574 		} else {
4575 			if (un->un_pos.eof > ST_EOF) {
4576 				break;
4577 			}
4578 		}
4579 	}
4580 
4581 	if (un->un_dp->options & ST_KNOWS_EOD) {
4582 		COPY_POS(&savepos, &un->un_pos);
4583 	}
4584 
4585 	ASSERT(mutex_owned(ST_MUTEX));
4586 
4587 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4588 	    "st_find_eod: %x\n", savepos.fileno);
4589 	return (savepos.fileno);
4590 }
4591 
4592 
4593 /*
4594  * this routine is frequently used in ioctls below;
4595  * it determines whether we know the density and if not will
4596  * determine it
4597  * if we have written the tape before, one or more filemarks are written
4598  *
4599  * depending on the stepflag, the head is repositioned to where it was before
4600  * the filemarks were written in order not to confuse step counts
4601  */
4602 #define	STEPBACK    0
4603 #define	NO_STEPBACK 1
4604 
4605 static int
4606 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4607 {
4608 
4609 	GET_SOFT_STATE(dev);
4610 
4611 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4612 
4613 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4614 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4615 	    "\n", dev, wfm, mode, stepflag);
4616 
4617 	ASSERT(mutex_owned(ST_MUTEX));
4618 
4619 	/*
4620 	 * If we don't yet know the density of the tape we have inserted,
4621 	 * we have to either unconditionally set it (if we're 'writing'),
4622 	 * or we have to determine it. As side effects, check for any
4623 	 * write-protect errors, and for the need to put out any file-marks
4624 	 * before positioning a tape.
4625 	 *
4626 	 * If we are going to be spacing forward, and we haven't determined
4627 	 * the tape density yet, we have to do so now...
4628 	 */
4629 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4630 		if (st_determine_density(un, mode)) {
4631 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4632 			    "check_density_or_wfm : EIO can't determine "
4633 			    "density\n");
4634 			un->un_errno = EIO;
4635 			return (EIO);
4636 		}
4637 		/*
4638 		 * Presumably we are at BOT. If we attempt to write, it will
4639 		 * either work okay, or bomb. We don't do a st_test_append
4640 		 * unless we're past BOT.
4641 		 */
4642 		un->un_laststate = un->un_state;
4643 		un->un_state = ST_STATE_OPEN;
4644 
4645 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4646 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4647 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4648 
4649 		tapepos_t spos;
4650 
4651 		COPY_POS(&spos, &un->un_pos);
4652 
4653 		/*
4654 		 * We need to write one or two filemarks.
4655 		 * In the case of the HP, we need to
4656 		 * position the head between the two
4657 		 * marks.
4658 		 */
4659 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4660 			wfm = un->un_fmneeded;
4661 			un->un_fmneeded = 0;
4662 		}
4663 
4664 		if (st_write_fm(dev, wfm)) {
4665 			un->un_pos.pmode = invalid;
4666 			un->un_density_known = 0;
4667 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4668 			    "check_density_or_wfm : EIO can't write fm\n");
4669 			un->un_errno = EIO;
4670 			return (EIO);
4671 		}
4672 
4673 		if (stepflag == STEPBACK) {
4674 			if (st_cmd(un, SCMD_SPACE, Fmk(-wfm), SYNC_CMD)) {
4675 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4676 				    "check_density_or_wfm : EIO can't space "
4677 				    "(-wfm)\n");
4678 				un->un_errno = EIO;
4679 				return (EIO);
4680 			}
4681 			COPY_POS(&un->un_pos, &spos);
4682 		}
4683 	}
4684 
4685 	/*
4686 	 * Whatever we do at this point clears the state of the eof flag.
4687 	 */
4688 
4689 	un->un_pos.eof = ST_NO_EOF;
4690 
4691 	/*
4692 	 * If writing, let's check that we're positioned correctly
4693 	 * at the end of tape before issuing the next write.
4694 	 */
4695 	if (un->un_read_only == RDWR) {
4696 		un->un_test_append = 1;
4697 	}
4698 
4699 	ASSERT(mutex_owned(ST_MUTEX));
4700 	return (0);
4701 }
4702 
4703 
4704 /*
4705  * Wait for all outstaning I/O's to complete
4706  *
4707  * we wait on both ncmds and the wait queue for times when we are flushing
4708  * after persistent errors are flagged, which is when ncmds can be 0, and the
4709  * queue can still have I/O's.  This way we preserve order of biodone's.
4710  */
4711 static void
4712 st_wait_for_io(struct scsi_tape *un)
4713 {
4714 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4715 	ASSERT(mutex_owned(ST_MUTEX));
4716 	while ((un->un_ncmds) || (un->un_quef) || (un->un_runqf)) {
4717 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4718 	}
4719 }
4720 
4721 /*
4722  * This routine implements the ioctl calls.  It is called
4723  * from the device switch at normal priority.
4724  */
4725 /*ARGSUSED*/
4726 static int
4727 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4728     int *rval_p)
4729 {
4730 	int tmp, rval = 0;
4731 
4732 	GET_SOFT_STATE(dev);
4733 
4734 	ST_ENTR(ST_DEVINFO, st_ioctl);
4735 
4736 	mutex_enter(ST_MUTEX);
4737 
4738 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4739 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4740 	    "pe_flag = %d\n",
4741 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4742 	    un->un_persistence && un->un_persist_errors);
4743 
4744 	/*
4745 	 * We don't want to block on these, so let them through
4746 	 * and we don't care about setting driver states here.
4747 	 */
4748 	if ((cmd == MTIOCGETDRIVETYPE) ||
4749 	    (cmd == MTIOCGUARANTEEDORDER) ||
4750 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4751 		goto check_commands;
4752 	}
4753 
4754 	/*
4755 	 * We clear error entry stack except command
4756 	 * MTIOCGETERROR and MTIOCGET
4757 	 */
4758 	if ((cmd != MTIOCGETERROR) &&
4759 	    (cmd != MTIOCGET)) {
4760 		st_empty_error_stack(un);
4761 	}
4762 
4763 	/*
4764 	 * wait for all outstanding commands to complete, or be dequeued.
4765 	 * And because ioctl's are synchronous commands, any return value
4766 	 * after this,  will be in order
4767 	 */
4768 	st_wait_for_io(un);
4769 
4770 	/*
4771 	 * allow only a through clear errors and persistent status, and
4772 	 * status
4773 	 */
4774 	if (un->un_persistence && un->un_persist_errors) {
4775 		if ((cmd == MTIOCLRERR) ||
4776 		    (cmd == MTIOCPERSISTENT) ||
4777 		    (cmd == MTIOCGET)) {
4778 			goto check_commands;
4779 		} else {
4780 			rval = un->un_errno;
4781 			goto exit;
4782 		}
4783 	}
4784 
4785 	ASSERT(un->un_throttle != 0);
4786 	un->un_throttle = 1;	/* > 1 will never happen here */
4787 	un->un_errno = 0;	/* start clean from here */
4788 
4789 	/*
4790 	 * first and foremost, handle any ST_EOT_PENDING cases.
4791 	 * That is, if a logical eot is pending notice, notice it.
4792 	 */
4793 	if (un->un_pos.eof == ST_EOT_PENDING) {
4794 		int resid = un->un_err_resid;
4795 		uchar_t status = un->un_status;
4796 		uchar_t lastop = un->un_lastop;
4797 
4798 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4799 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4800 			    "stioctl : EIO can't space fmk(-1)\n");
4801 			rval = EIO;
4802 			goto exit;
4803 		}
4804 		un->un_lastop = lastop; /* restore last operation */
4805 		if (status == SUN_KEY_EOF) {
4806 			un->un_status = SUN_KEY_EOT;
4807 		} else {
4808 			un->un_status = status;
4809 		}
4810 		un->un_err_resid  = resid;
4811 		/* fix up block number */
4812 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4813 		/* now we're at logical eot */
4814 		un->un_pos.eof = ST_EOT;
4815 	}
4816 
4817 	/*
4818 	 * now, handle the rest of the situations
4819 	 */
4820 check_commands:
4821 	switch (cmd) {
4822 	case MTIOCGET:
4823 	{
4824 #ifdef _MULTI_DATAMODEL
4825 		/*
4826 		 * For use when a 32 bit app makes a call into a
4827 		 * 64 bit ioctl
4828 		 */
4829 		struct mtget32		mtg_local32;
4830 		struct mtget32 		*mtget_32 = &mtg_local32;
4831 #endif /* _MULTI_DATAMODEL */
4832 
4833 			/* Get tape status */
4834 		struct mtget mtg_local;
4835 		struct mtget *mtget = &mtg_local;
4836 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4837 		    "st_ioctl: MTIOCGET\n");
4838 
4839 		bzero((caddr_t)mtget, sizeof (struct mtget));
4840 		mtget->mt_erreg = un->un_status;
4841 		mtget->mt_resid = un->un_err_resid;
4842 		mtget->mt_dsreg = un->un_retry_ct;
4843 		if (un->un_err_pos.pmode == legacy) {
4844 			mtget->mt_fileno = un->un_err_pos.fileno;
4845 		} else {
4846 			mtget->mt_fileno = -1;
4847 		}
4848 		/*
4849 		 * If the value is positive fine.
4850 		 * If its negative we need to return a value based on the
4851 		 * old way if counting backwards from INF (1,000,000,000).
4852 		 */
4853 		if (un->un_err_pos.blkno >= 0) {
4854 			mtget->mt_blkno = un->un_err_pos.blkno;
4855 		} else {
4856 			mtget->mt_blkno = INF + 1 - (-un->un_err_pos.blkno);
4857 		}
4858 		mtget->mt_type = un->un_dp->type;
4859 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
4860 		if (un->un_read_pos_type != NO_POS) {
4861 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
4862 		}
4863 		if (un->un_dp->options & ST_REEL) {
4864 			mtget->mt_flags |= MTF_REEL;
4865 			mtget->mt_bf = 20;
4866 		} else {		/* 1/4" cartridges */
4867 			switch (mtget->mt_type) {
4868 			/* Emulex cartridge tape */
4869 			case MT_ISMT02:
4870 				mtget->mt_bf = 40;
4871 				break;
4872 			default:
4873 				mtget->mt_bf = 126;
4874 				break;
4875 			}
4876 		}
4877 
4878 		/*
4879 		 * If large transfers are allowed and drive options
4880 		 * has no record size limit set. Calculate blocking
4881 		 * factor from the lesser of maxbsize and maxdma.
4882 		 */
4883 		if ((un->un_allow_large_xfer) &&
4884 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
4885 			mtget->mt_bf = min(un->un_maxbsize,
4886 			    un->un_maxdma) / SECSIZE;
4887 		}
4888 
4889 		if (un->un_read_only == WORM ||
4890 		    un->un_read_only == RDWORM) {
4891 			mtget->mt_flags |= MTF_WORM_MEDIA;
4892 		}
4893 
4894 		/*
4895 		 * In persistent error mode sending a non-queued can hang
4896 		 * because this ioctl gets to be run without turning off
4897 		 * persistense. Fake the answer based on previous info.
4898 		 */
4899 		if (un->un_persistence) {
4900 			if ((un->un_HeadClean & (TAPE_ALERT_SUPPORTED |
4901 			    TAPE_SEQUENTIAL_SUPPORTED|TAPE_ALERT_NOT_SUPPORTED))
4902 			    != TAPE_ALERT_NOT_SUPPORTED) {
4903 				mtget->mt_flags |= MTF_TAPE_CLN_SUPPORTED;
4904 			}
4905 			if (un->un_HeadClean & (TAPE_PREVIOUSLY_DIRTY |
4906 			    TAPE_ALERT_STILL_DIRTY)) {
4907 				mtget->mt_flags |= MTF_TAPE_HEAD_DIRTY;
4908 			}
4909 			rval = 0;
4910 		} else {
4911 			rval = st_check_clean_bit(un);
4912 		}
4913 		if (rval == -1) {
4914 			rval = EIO;
4915 			goto exit;
4916 		} else {
4917 			mtget->mt_flags |= (ushort_t)rval;
4918 			rval = 0;
4919 		}
4920 
4921 		un->un_status = 0;		/* Reset status */
4922 		un->un_err_resid = 0;
4923 		tmp = sizeof (struct mtget);
4924 
4925 #ifdef _MULTI_DATAMODEL
4926 
4927 		switch (ddi_model_convert_from(flag & FMODELS)) {
4928 		case DDI_MODEL_ILP32:
4929 			/*
4930 			 * Convert 64 bit back to 32 bit before doing
4931 			 * copyout. This is what the ILP32 app expects.
4932 			 */
4933 			mtget_32->mt_erreg = 	mtget->mt_erreg;
4934 			mtget_32->mt_resid = 	mtget->mt_resid;
4935 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
4936 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
4937 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
4938 			mtget_32->mt_type =  	mtget->mt_type;
4939 			mtget_32->mt_flags = 	mtget->mt_flags;
4940 			mtget_32->mt_bf = 	mtget->mt_bf;
4941 
4942 			if (ddi_copyout(mtget_32, (void *)arg,
4943 			    sizeof (struct mtget32), flag)) {
4944 				rval = EFAULT;
4945 			}
4946 			break;
4947 
4948 		case DDI_MODEL_NONE:
4949 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4950 				rval = EFAULT;
4951 			}
4952 			break;
4953 		}
4954 #else /* ! _MULTI_DATAMODE */
4955 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4956 			rval = EFAULT;
4957 		}
4958 #endif /* _MULTI_DATAMODE */
4959 
4960 		break;
4961 	}
4962 	case MTIOCGETERROR:
4963 			/*
4964 			 * get error entry from error stack
4965 			 */
4966 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4967 			    "st_ioctl: MTIOCGETERROR\n");
4968 
4969 			rval = st_get_error_entry(un, arg, flag);
4970 
4971 			break;
4972 
4973 	case MTIOCSTATE:
4974 		{
4975 			/*
4976 			 * return when media presence matches state
4977 			 */
4978 			enum mtio_state state;
4979 
4980 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4981 			    "st_ioctl: MTIOCSTATE\n");
4982 
4983 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
4984 				rval = EFAULT;
4985 
4986 			mutex_exit(ST_MUTEX);
4987 
4988 			rval = st_check_media(dev, state);
4989 
4990 			mutex_enter(ST_MUTEX);
4991 
4992 			if (rval != 0) {
4993 				break;
4994 			}
4995 
4996 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
4997 			    sizeof (int), flag))
4998 				rval = EFAULT;
4999 			break;
5000 
5001 		}
5002 
5003 	case MTIOCGETDRIVETYPE:
5004 		{
5005 #ifdef _MULTI_DATAMODEL
5006 		/*
5007 		 * For use when a 32 bit app makes a call into a
5008 		 * 64 bit ioctl
5009 		 */
5010 		struct mtdrivetype_request32	mtdtrq32;
5011 #endif /* _MULTI_DATAMODEL */
5012 
5013 			/*
5014 			 * return mtdrivetype
5015 			 */
5016 			struct mtdrivetype_request mtdtrq;
5017 			struct mtdrivetype mtdrtyp;
5018 			struct mtdrivetype *mtdt = &mtdrtyp;
5019 			struct st_drivetype *stdt = un->un_dp;
5020 
5021 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5022 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
5023 
5024 #ifdef _MULTI_DATAMODEL
5025 		switch (ddi_model_convert_from(flag & FMODELS)) {
5026 		case DDI_MODEL_ILP32:
5027 		{
5028 			if (ddi_copyin((void *)arg, &mtdtrq32,
5029 			    sizeof (struct mtdrivetype_request32), flag)) {
5030 				rval = EFAULT;
5031 				break;
5032 			}
5033 			mtdtrq.size = mtdtrq32.size;
5034 			mtdtrq.mtdtp =
5035 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
5036 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5037 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
5038 			break;
5039 		}
5040 		case DDI_MODEL_NONE:
5041 			if (ddi_copyin((void *)arg, &mtdtrq,
5042 			    sizeof (struct mtdrivetype_request), flag)) {
5043 				rval = EFAULT;
5044 				break;
5045 			}
5046 			break;
5047 		}
5048 
5049 #else /* ! _MULTI_DATAMODEL */
5050 		if (ddi_copyin((void *)arg, &mtdtrq,
5051 		    sizeof (struct mtdrivetype_request), flag)) {
5052 			rval = EFAULT;
5053 			break;
5054 		}
5055 #endif /* _MULTI_DATAMODEL */
5056 
5057 			/*
5058 			 * if requested size is < 0 then return
5059 			 * error.
5060 			 */
5061 			if (mtdtrq.size < 0) {
5062 				rval = EINVAL;
5063 				break;
5064 			}
5065 			bzero(mtdt, sizeof (struct mtdrivetype));
5066 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
5067 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
5068 			mtdt->type = stdt->type;
5069 			mtdt->bsize = stdt->bsize;
5070 			mtdt->options = stdt->options;
5071 			mtdt->max_rretries = stdt->max_rretries;
5072 			mtdt->max_wretries = stdt->max_wretries;
5073 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5074 				mtdt->densities[tmp] = stdt->densities[tmp];
5075 			}
5076 			mtdt->default_density = stdt->default_density;
5077 			/*
5078 			 * Speed hasn't been used since the hayday of reel tape.
5079 			 * For all drives not setting the option ST_KNOWS_MEDIA
5080 			 * the speed member renamed to mediatype are zeros.
5081 			 * Those drives that have ST_KNOWS_MEDIA set use the
5082 			 * new mediatype member which is used to figure the
5083 			 * type of media loaded.
5084 			 *
5085 			 * So as to not break applications speed in the
5086 			 * mtdrivetype structure is not renamed.
5087 			 */
5088 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5089 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
5090 			}
5091 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
5092 			mtdt->io_timeout = stdt->io_timeout;
5093 			mtdt->rewind_timeout = stdt->rewind_timeout;
5094 			mtdt->space_timeout = stdt->space_timeout;
5095 			mtdt->load_timeout = stdt->load_timeout;
5096 			mtdt->unload_timeout = stdt->unload_timeout;
5097 			mtdt->erase_timeout = stdt->erase_timeout;
5098 
5099 			/*
5100 			 * Limit the maximum length of the result to
5101 			 * sizeof (struct mtdrivetype).
5102 			 */
5103 			tmp = sizeof (struct mtdrivetype);
5104 			if (mtdtrq.size < tmp)
5105 				tmp = mtdtrq.size;
5106 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
5107 				rval = EFAULT;
5108 			}
5109 			break;
5110 		}
5111 	case MTIOCPERSISTENT:
5112 
5113 		if (ddi_copyin((void *)arg, &tmp, sizeof (tmp), flag)) {
5114 			rval = EFAULT;
5115 			break;
5116 		}
5117 
5118 		if (tmp) {
5119 			st_turn_pe_on(un);
5120 		} else {
5121 			st_turn_pe_off(un);
5122 		}
5123 
5124 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5125 		    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
5126 		    un->un_persistence);
5127 
5128 		break;
5129 
5130 	case MTIOCPERSISTENTSTATUS:
5131 		tmp = (int)un->un_persistence;
5132 
5133 		if (ddi_copyout(&tmp, (void *)arg, sizeof (tmp), flag)) {
5134 			rval = EFAULT;
5135 		}
5136 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5137 		    "st_ioctl: MTIOCPERSISTENTSTATUS:persistence = %d\n",
5138 		    un->un_persistence);
5139 
5140 		break;
5141 
5142 	case MTIOCLRERR:
5143 		{
5144 			/* clear persistent errors */
5145 
5146 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5147 			    "st_ioctl: MTIOCLRERR\n");
5148 
5149 			st_clear_pe(un);
5150 
5151 			break;
5152 		}
5153 
5154 	case MTIOCGUARANTEEDORDER:
5155 		{
5156 			/*
5157 			 * this is just a holder to make a valid ioctl and
5158 			 * it won't be in any earlier release
5159 			 */
5160 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5161 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
5162 
5163 			break;
5164 		}
5165 
5166 	case MTIOCRESERVE:
5167 		{
5168 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5169 			    "st_ioctl: MTIOCRESERVE\n");
5170 
5171 			/*
5172 			 * Check if Reserve/Release is supported.
5173 			 */
5174 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5175 				rval = ENOTTY;
5176 				break;
5177 			}
5178 
5179 			rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5180 
5181 			if (rval == 0) {
5182 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
5183 			}
5184 			break;
5185 		}
5186 
5187 	case MTIOCRELEASE:
5188 		{
5189 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5190 			    "st_ioctl: MTIOCRELEASE\n");
5191 
5192 			/*
5193 			 * Check if Reserve/Release is supported.
5194 			 */
5195 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5196 				rval = ENOTTY;
5197 				break;
5198 			}
5199 
5200 			/*
5201 			 * Used to just clear ST_PRESERVE_RESERVE which
5202 			 * made the reservation release at next close.
5203 			 * As the user may have opened and then done a
5204 			 * persistant reservation we now need to drop
5205 			 * the reservation without closing if the user
5206 			 * attempts to do this.
5207 			 */
5208 			rval = st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
5209 
5210 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5211 
5212 			break;
5213 		}
5214 
5215 	case MTIOCFORCERESERVE:
5216 	{
5217 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5218 		    "st_ioctl: MTIOCFORCERESERVE\n");
5219 
5220 		/*
5221 		 * Check if Reserve/Release is supported.
5222 		 */
5223 		if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5224 			rval = ENOTTY;
5225 			break;
5226 		}
5227 		/*
5228 		 * allow only super user to run this.
5229 		 */
5230 		if (drv_priv(cred_p) != 0) {
5231 			rval = EPERM;
5232 			break;
5233 		}
5234 		/*
5235 		 * Throw away reserve,
5236 		 * not using test-unit-ready
5237 		 * since reserve can succeed without tape being
5238 		 * present in the drive.
5239 		 */
5240 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5241 
5242 		rval = st_take_ownership(un);
5243 
5244 		break;
5245 	}
5246 
5247 	case USCSICMD:
5248 	{
5249 		cred_t	*cr;
5250 
5251 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5252 		    "st_ioctl: USCSICMD\n");
5253 
5254 		cr = ddi_get_cred();
5255 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5256 			rval = EPERM;
5257 		} else {
5258 			rval = st_uscsi_cmd(un, (struct uscsi_cmd *)arg, flag);
5259 		}
5260 		break;
5261 	}
5262 	case MTIOCTOP:
5263 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5264 		    "st_ioctl: MTIOCTOP\n");
5265 		rval = st_mtioctop(un, arg, flag);
5266 		break;
5267 
5268 	case MTIOCLTOP:
5269 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5270 		    "st_ioctl: MTIOLCTOP\n");
5271 		rval = st_mtiocltop(un, arg, flag);
5272 		break;
5273 
5274 	case MTIOCREADIGNOREILI:
5275 		{
5276 			int set_ili;
5277 
5278 			if (ddi_copyin((void *)arg, &set_ili,
5279 			    sizeof (set_ili), flag)) {
5280 				rval = EFAULT;
5281 				break;
5282 			}
5283 
5284 			if (un->un_bsize) {
5285 				rval = ENOTTY;
5286 				break;
5287 			}
5288 
5289 			switch (set_ili) {
5290 			case 0:
5291 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5292 				break;
5293 
5294 			case 1:
5295 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5296 				break;
5297 
5298 			default:
5299 				rval = EINVAL;
5300 				break;
5301 			}
5302 			break;
5303 		}
5304 
5305 	case MTIOCREADIGNOREEOFS:
5306 		{
5307 			int ignore_eof;
5308 
5309 			if (ddi_copyin((void *)arg, &ignore_eof,
5310 			    sizeof (ignore_eof), flag)) {
5311 				rval = EFAULT;
5312 				break;
5313 			}
5314 
5315 			if (!(un->un_dp->options & ST_REEL)) {
5316 				rval = ENOTTY;
5317 				break;
5318 			}
5319 
5320 			switch (ignore_eof) {
5321 			case 0:
5322 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5323 				break;
5324 
5325 			case 1:
5326 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5327 				break;
5328 
5329 			default:
5330 				rval = EINVAL;
5331 				break;
5332 			}
5333 			break;
5334 		}
5335 
5336 	case MTIOCSHORTFMK:
5337 	{
5338 		int short_fmk;
5339 
5340 		if (ddi_copyin((void *)arg, &short_fmk,
5341 		    sizeof (short_fmk), flag)) {
5342 			rval = EFAULT;
5343 			break;
5344 		}
5345 
5346 		switch (un->un_dp->type) {
5347 		case ST_TYPE_EXB8500:
5348 		case ST_TYPE_EXABYTE:
5349 			if (!short_fmk) {
5350 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5351 			} else if (short_fmk == 1) {
5352 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5353 			} else {
5354 				rval = EINVAL;
5355 			}
5356 			break;
5357 
5358 		default:
5359 			rval = ENOTTY;
5360 			break;
5361 		}
5362 		break;
5363 	}
5364 
5365 	case MTIOCGETPOS:
5366 		rval = st_update_block_pos(un, st_cmd, 0);
5367 		if (rval == 0) {
5368 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5369 			    sizeof (tapepos_t), flag)) {
5370 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5371 				    "MTIOCGETPOS copy out failed\n");
5372 				rval = EFAULT;
5373 			}
5374 		}
5375 		break;
5376 
5377 	case MTIOCRESTPOS:
5378 	{
5379 		tapepos_t dest;
5380 
5381 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5382 		    flag) != 0) {
5383 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5384 			    "MTIOCRESTPOS copy in failed\n");
5385 			rval = EFAULT;
5386 			break;
5387 		}
5388 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &dest);
5389 		if (rval != 0) {
5390 			rval = EIO;
5391 		}
5392 		break;
5393 	}
5394 	default:
5395 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5396 		    "st_ioctl: unknown ioctl\n");
5397 		rval = ENOTTY;
5398 	}
5399 
5400 exit:
5401 	if (!(un->un_persistence && un->un_persist_errors)) {
5402 		un->un_errno = rval;
5403 	}
5404 
5405 	mutex_exit(ST_MUTEX);
5406 
5407 	return (rval);
5408 }
5409 
5410 
5411 /*
5412  * do some MTIOCTOP tape operations
5413  */
5414 static int
5415 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5416 {
5417 #ifdef _MULTI_DATAMODEL
5418 	/*
5419 	 * For use when a 32 bit app makes a call into a
5420 	 * 64 bit ioctl
5421 	 */
5422 	struct mtop32	mtop_32_for_64;
5423 #endif /* _MULTI_DATAMODEL */
5424 	struct mtop passed;
5425 	struct mtlop local;
5426 	int rval = 0;
5427 
5428 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5429 
5430 	ASSERT(mutex_owned(ST_MUTEX));
5431 
5432 #ifdef _MULTI_DATAMODEL
5433 	switch (ddi_model_convert_from(flag & FMODELS)) {
5434 	case DDI_MODEL_ILP32:
5435 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5436 		    sizeof (struct mtop32), flag)) {
5437 			return (EFAULT);
5438 		}
5439 		local.mt_op = mtop_32_for_64.mt_op;
5440 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5441 		break;
5442 
5443 	case DDI_MODEL_NONE:
5444 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5445 			return (EFAULT);
5446 		}
5447 		local.mt_op = passed.mt_op;
5448 		/* prevent sign extention */
5449 		local.mt_count = (UINT32_MAX & passed.mt_count);
5450 		break;
5451 	}
5452 
5453 #else /* ! _MULTI_DATAMODEL */
5454 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5455 		return (EFAULT);
5456 	}
5457 	local.mt_op = passed.mt_op;
5458 	/* prevent sign extention */
5459 	local.mt_count = (UINT32_MAX & passed.mt_count);
5460 #endif /* _MULTI_DATAMODEL */
5461 
5462 	rval = st_do_mtioctop(un, &local);
5463 
5464 #ifdef _MULTI_DATAMODEL
5465 	switch (ddi_model_convert_from(flag & FMODELS)) {
5466 	case DDI_MODEL_ILP32:
5467 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5468 			rval = ERANGE;
5469 			break;
5470 		}
5471 		/*
5472 		 * Convert 64 bit back to 32 bit before doing
5473 		 * copyout. This is what the ILP32 app expects.
5474 		 */
5475 		mtop_32_for_64.mt_op = local.mt_op;
5476 		mtop_32_for_64.mt_count = local.mt_count;
5477 
5478 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5479 		    sizeof (struct mtop32), flag)) {
5480 			rval = EFAULT;
5481 		}
5482 		break;
5483 
5484 	case DDI_MODEL_NONE:
5485 		passed.mt_count = local.mt_count;
5486 		passed.mt_op = local.mt_op;
5487 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5488 			rval = EFAULT;
5489 		}
5490 		break;
5491 	}
5492 #else /* ! _MULTI_DATAMODE */
5493 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5494 		rval = ERANGE;
5495 	} else {
5496 		passed.mt_op = local.mt_op;
5497 		passed.mt_count = local.mt_count;
5498 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5499 			rval = EFAULT;
5500 		}
5501 	}
5502 #endif /* _MULTI_DATAMODE */
5503 
5504 
5505 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5506 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5507 	    un->un_pos.blkno, un->un_pos.eof);
5508 
5509 	if (un->un_pos.pmode == invalid) {
5510 		un->un_density_known = 0;
5511 	}
5512 
5513 	ASSERT(mutex_owned(ST_MUTEX));
5514 	return (rval);
5515 }
5516 
5517 static int
5518 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5519 {
5520 	struct mtlop local;
5521 	int rval;
5522 
5523 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5524 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5525 		return (EFAULT);
5526 	}
5527 
5528 	rval = st_do_mtioctop(un, &local);
5529 
5530 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5531 		rval = EFAULT;
5532 	}
5533 	return (rval);
5534 }
5535 
5536 
5537 static int
5538 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5539 {
5540 	dev_t dev = un->un_dev;
5541 	int savefile;
5542 	int rval = 0;
5543 
5544 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5545 
5546 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5547 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5548 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5549 	    "fileno=%x, blkno=%x, eof=%x\n",
5550 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5551 
5552 	un->un_status = 0;
5553 
5554 	/*
5555 	 * if we are going to mess with a tape, we have to make sure we have
5556 	 * one and are not offline (i.e. no tape is initialized).  We let
5557 	 * commands pass here that don't actually touch the tape, except for
5558 	 * loading and initialization (rewinding).
5559 	 */
5560 	if (un->un_state == ST_STATE_OFFLINE) {
5561 		switch (mtop->mt_op) {
5562 		case MTLOAD:
5563 		case MTNOP:
5564 			/*
5565 			 * We don't want strategy calling st_tape_init here,
5566 			 * so, change state
5567 			 */
5568 			un->un_state = ST_STATE_INITIALIZING;
5569 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5570 			    "st_do_mtioctop : OFFLINE state = %d\n",
5571 			    un->un_state);
5572 			break;
5573 		default:
5574 			/*
5575 			 * reinitialize by normal means
5576 			 */
5577 			rval = st_tape_init(un);
5578 			if (rval) {
5579 				un->un_state = ST_STATE_INITIALIZING;
5580 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5581 				    "st_do_mtioctop : OFFLINE init failure ");
5582 				un->un_state = ST_STATE_OFFLINE;
5583 				un->un_pos.pmode = invalid;
5584 				if (rval != EACCES) {
5585 					rval = EIO;
5586 				}
5587 				return (rval);
5588 			}
5589 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5590 			break;
5591 		}
5592 	}
5593 
5594 	/*
5595 	 * If the file position is invalid, allow only those
5596 	 * commands that properly position the tape and fail
5597 	 * the rest with EIO
5598 	 */
5599 	if (un->un_pos.pmode == invalid) {
5600 		switch (mtop->mt_op) {
5601 		case MTWEOF:
5602 		case MTRETEN:
5603 		case MTERASE:
5604 		case MTEOM:
5605 		case MTFSF:
5606 		case MTFSR:
5607 		case MTBSF:
5608 		case MTNBSF:
5609 		case MTBSR:
5610 		case MTSRSZ:
5611 		case MTGRSZ:
5612 		case MTSEEK:
5613 		case MTBSSF:
5614 		case MTFSSF:
5615 			return (EIO);
5616 			/* NOTREACHED */
5617 		case MTREW:
5618 		case MTLOAD:
5619 		case MTOFFL:
5620 		case MTNOP:
5621 		case MTTELL:
5622 		case MTLOCK:
5623 		case MTUNLOCK:
5624 			break;
5625 
5626 		default:
5627 			return (ENOTTY);
5628 			/* NOTREACHED */
5629 		}
5630 	}
5631 
5632 	switch (mtop->mt_op) {
5633 	case MTERASE:
5634 		/*
5635 		 * MTERASE rewinds the tape, erase it completely, and returns
5636 		 * to the beginning of the tape
5637 		 */
5638 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5639 			un->un_status = KEY_WRITE_PROTECT;
5640 			un->un_err_resid = mtop->mt_count;
5641 			COPY_POS(&un->un_err_pos, &un->un_pos);
5642 			return (EACCES);
5643 		}
5644 		if (un->un_dp->options & ST_REEL) {
5645 			un->un_fmneeded = 2;
5646 		} else {
5647 			un->un_fmneeded = 1;
5648 		}
5649 		mtop->mt_count = mtop->mt_count ? 1 : 0;
5650 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5651 		    st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
5652 		    st_cmd(un, SCMD_ERASE, mtop->mt_count, SYNC_CMD)) {
5653 			un->un_pos.pmode = invalid;
5654 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5655 			    "st_do_mtioctop : EIO space or erase or "
5656 			    "check den)\n");
5657 			rval = EIO;
5658 		} else {
5659 			/* QIC and helical scan rewind after erase */
5660 			if (un->un_dp->options & ST_REEL) {
5661 				(void) st_cmd(un, SCMD_REWIND, 0, ASYNC_CMD);
5662 			}
5663 		}
5664 		break;
5665 
5666 	case MTWEOF:
5667 		/*
5668 		 * write an end-of-file record
5669 		 */
5670 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5671 			un->un_status = KEY_WRITE_PROTECT;
5672 			un->un_err_resid = mtop->mt_count;
5673 			COPY_POS(&un->un_err_pos, &un->un_pos);
5674 			return (EACCES);
5675 		}
5676 
5677 		/*
5678 		 * zero count means just flush buffers
5679 		 * negative count is not permitted
5680 		 */
5681 		if (mtop->mt_count < 0) {
5682 			return (EINVAL);
5683 		}
5684 
5685 		/* Not on worm */
5686 		if (un->un_read_only == RDWR) {
5687 			un->un_test_append = 1;
5688 		}
5689 
5690 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5691 			if (st_determine_density(un, B_WRITE)) {
5692 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5693 				    "st_do_mtioctop : EIO : MTWEOF can't "
5694 				    "determine density");
5695 				return (EIO);
5696 			}
5697 		}
5698 
5699 		rval = st_write_fm(dev, (int)mtop->mt_count);
5700 		if ((rval != 0) && (rval != EACCES)) {
5701 			/*
5702 			 * Failure due to something other than illegal
5703 			 * request results in loss of state (st_intr).
5704 			 */
5705 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5706 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5707 			    "file mark");
5708 			rval = EIO;
5709 		}
5710 		break;
5711 
5712 	case MTRETEN:
5713 		/*
5714 		 * retension the tape
5715 		 */
5716 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5717 		    st_cmd(un, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5718 			un->un_pos.pmode = invalid;
5719 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5720 			    "st_do_mtioctop : EIO : MTRETEN ");
5721 			rval = EIO;
5722 		}
5723 		break;
5724 
5725 	case MTREW:
5726 		/*
5727 		 * rewind  the tape
5728 		 */
5729 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5730 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5731 			    "st_do_mtioctop : EIO:MTREW check "
5732 			    "density/wfm failed");
5733 			return (EIO);
5734 		}
5735 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
5736 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5737 			    "st_do_mtioctop : EIO : MTREW ");
5738 			rval = EIO;
5739 		}
5740 		break;
5741 
5742 	case MTOFFL:
5743 		/*
5744 		 * rewinds, and, if appropriate, takes the device offline by
5745 		 * unloading the tape
5746 		 */
5747 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5748 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5749 			    "st_do_mtioctop :EIO:MTOFFL check "
5750 			    "density/wfm failed");
5751 			return (EIO);
5752 		}
5753 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
5754 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5755 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5756 			    "st_do_mtioctop : EIO : MTOFFL");
5757 			return (EIO);
5758 		}
5759 		un->un_pos.eof = ST_NO_EOF;
5760 		un->un_laststate = un->un_state;
5761 		un->un_state = ST_STATE_OFFLINE;
5762 		un->un_mediastate = MTIO_EJECTED;
5763 		break;
5764 
5765 	case MTLOAD:
5766 		/*
5767 		 * This is to load a tape into the drive
5768 		 * Note that if the tape is not loaded, the device will have
5769 		 * to be opened via O_NDELAY or O_NONBLOCK.
5770 		 */
5771 		/*
5772 		 * Let's try and clean things up, if we are not
5773 		 * initializing, and then send in the load command, no
5774 		 * matter what.
5775 		 *
5776 		 * load after a media change by the user.
5777 		 */
5778 
5779 		if (un->un_state > ST_STATE_INITIALIZING) {
5780 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5781 		}
5782 		rval = st_cmd(un, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5783 		/* Load command to a drive that doesn't support load */
5784 		if ((rval == EIO) &&
5785 		    ((un->un_status == KEY_NOT_READY) &&
5786 			/* Medium not present */
5787 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5788 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5789 		    (un->un_dp->type == MT_ISSTK9840) &&
5790 			/* CSL not present */
5791 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5792 			rval = ENOTTY;
5793 			break;
5794 		} else if (rval != EACCES && rval != 0) {
5795 			rval = EIO;
5796 		}
5797 		if (rval) {
5798 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5799 			    "st_do_mtioctop : %s : MTLOAD\n",
5800 			    rval == EACCES ? "EACCES" : "EIO");
5801 			/*
5802 			 * If load tape fails, who knows what happened...
5803 			 */
5804 			un->un_pos.pmode = invalid;
5805 			break;
5806 		}
5807 
5808 		/*
5809 		 * reset all counters appropriately using rewind, as if LOAD
5810 		 * succeeds, we are at BOT
5811 		 */
5812 		un->un_state = ST_STATE_INITIALIZING;
5813 
5814 		rval = st_tape_init(un);
5815 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5816 			rval = 0;
5817 			break;
5818 		}
5819 
5820 		if (rval != 0) {
5821 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5822 			    "st_do_mtioctop : EIO : MTLOAD calls "
5823 			    "st_tape_init\n");
5824 			rval = EIO;
5825 			un->un_state = ST_STATE_OFFLINE;
5826 		}
5827 
5828 		break;
5829 
5830 	case MTNOP:
5831 		un->un_status = 0;		/* Reset status */
5832 		un->un_err_resid = 0;
5833 		mtop->mt_count = MTUNIT(dev);
5834 		break;
5835 
5836 	case MTEOM:
5837 		/*
5838 		 * positions the tape at a location just after the last file
5839 		 * written on the tape. For cartridge and 8 mm, this after
5840 		 * the last file mark; for reel, this is inbetween the two
5841 		 * last 2 file marks
5842 		 */
5843 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5844 		    (un->un_lastop == ST_OP_WRITE) ||
5845 		    (un->un_lastop == ST_OP_WEOF)) {
5846 			/*
5847 			 * If the command wants to move to logical end
5848 			 * of media, and we're already there, we're done.
5849 			 * If we were at logical eot, we reset the state
5850 			 * to be *not* at logical eot.
5851 			 *
5852 			 * If we're at physical or logical eot, we prohibit
5853 			 * forward space operations (unconditionally).
5854 			 *
5855 			 * Also if the last operation was a write of any
5856 			 * kind the tape is at EOD.
5857 			 */
5858 			return (0);
5859 		}
5860 		/*
5861 		 * physical tape position may not be what we've been
5862 		 * telling the user; adjust the request accordingly
5863 		 */
5864 		if (IN_EOF(un->un_pos)) {
5865 			un->un_pos.fileno++;
5866 			un->un_pos.blkno = 0;
5867 		}
5868 
5869 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
5870 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5871 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
5872 			    " failed");
5873 			return (EIO);
5874 		}
5875 
5876 		/*
5877 		 * st_find_eod() returns the last fileno we knew about;
5878 		 */
5879 		savefile = st_find_eod(un);
5880 
5881 		if ((un->un_status != KEY_BLANK_CHECK) &&
5882 		    (un->un_status != SUN_KEY_EOT)) {
5883 			un->un_pos.pmode = invalid;
5884 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5885 			    "st_do_mtioctop : EIO : MTEOM status check failed");
5886 			rval = EIO;
5887 		} else {
5888 			/*
5889 			 * For 1/2" reel tapes assume logical EOT marked
5890 			 * by two file marks or we don't care that we may
5891 			 * be extending the last file on the tape.
5892 			 */
5893 			if (un->un_dp->options & ST_REEL) {
5894 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
5895 					un->un_pos.pmode = invalid;
5896 					ST_DEBUG2(ST_DEVINFO, st_label,
5897 					    SCSI_DEBUG,
5898 					    "st_do_mtioctop : EIO : MTEOM space"
5899 					    " cmd failed");
5900 					rval = EIO;
5901 					break;
5902 				}
5903 				/*
5904 				 * Fix up the block number.
5905 				 */
5906 				un->un_pos.blkno = 0;
5907 				un->un_err_pos.blkno = 0;
5908 			}
5909 			un->un_err_resid = 0;
5910 			un->un_pos.fileno = savefile;
5911 			un->un_pos.eof = ST_EOT;
5912 		}
5913 		un->un_status = 0;
5914 		break;
5915 
5916 	case MTFSF:
5917 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
5918 		break;
5919 
5920 	case MTFSR:
5921 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
5922 		break;
5923 
5924 	case MTBSF:
5925 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
5926 		break;
5927 
5928 	case MTNBSF:
5929 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
5930 		break;
5931 
5932 	case MTBSR:
5933 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
5934 		break;
5935 
5936 	case MTBSSF:
5937 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
5938 		break;
5939 
5940 	case MTFSSF:
5941 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
5942 		break;
5943 
5944 	case MTSRSZ:
5945 
5946 		/*
5947 		 * Set record-size to that sent by user
5948 		 * Check to see if there is reason that the requested
5949 		 * block size should not be set.
5950 		 */
5951 
5952 		/* If requesting variable block size is it ok? */
5953 		if ((mtop->mt_count == 0) &&
5954 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
5955 			return (ENOTTY);
5956 		}
5957 
5958 		/*
5959 		 * If requested block size is not variable "0",
5960 		 * is it less then minimum.
5961 		 */
5962 		if ((mtop->mt_count != 0) &&
5963 		    (mtop->mt_count < un->un_minbsize)) {
5964 			return (EINVAL);
5965 		}
5966 
5967 		/* Is the requested block size more then maximum */
5968 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
5969 		    (un->un_maxbsize != 0)) {
5970 			return (EINVAL);
5971 		}
5972 
5973 		/* Is requested block size a modulus the device likes */
5974 		if ((mtop->mt_count % un->un_data_mod) != 0) {
5975 			return (EINVAL);
5976 		}
5977 
5978 		if (st_change_block_size(un, (uint32_t)mtop->mt_count) != 0) {
5979 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5980 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
5981 			return (EIO);
5982 		}
5983 
5984 		return (0);
5985 
5986 	case MTGRSZ:
5987 		/*
5988 		 * Get record-size to the user
5989 		 */
5990 		mtop->mt_count = un->un_bsize;
5991 		rval = 0;
5992 		break;
5993 
5994 	case MTTELL:
5995 		rval = st_update_block_pos(un, st_cmd, 0);
5996 		mtop->mt_count = un->un_pos.lgclblkno;
5997 		break;
5998 
5999 	case MTSEEK:
6000 		rval = st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
6001 		    (uint64_t)mtop->mt_count, un->un_pos.partition);
6002 		/*
6003 		 * This bit of magic make mt print the actual position if
6004 		 * the resulting position was not what was asked for.
6005 		 */
6006 		if (rval == ESPIPE) {
6007 			rval = EIO;
6008 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
6009 				mtop->mt_op = MTTELL;
6010 				mtop->mt_count = un->un_pos.lgclblkno;
6011 			}
6012 		}
6013 		break;
6014 
6015 	case MTLOCK:
6016 		if (st_cmd(un, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
6017 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6018 			    "st_do_mtioctop : EIO : MTLOCK");
6019 			rval = EIO;
6020 		}
6021 		break;
6022 
6023 	case MTUNLOCK:
6024 		if (st_cmd(un, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
6025 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6026 			    "st_do_mtioctop : EIO : MTUNLOCK");
6027 			rval = EIO;
6028 		}
6029 		break;
6030 
6031 	default:
6032 		rval = ENOTTY;
6033 	}
6034 
6035 	return (rval);
6036 }
6037 
6038 
6039 /*
6040  * Run a command for uscsi ioctl.
6041  */
6042 static int
6043 st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
6044 {
6045 	struct uscsi_cmd	*uscmd;
6046 	struct buf	*bp;
6047 	enum uio_seg	uioseg;
6048 	int	offline_state = 0;
6049 	int	err = 0;
6050 	dev_t dev = un->un_dev;
6051 
6052 	ST_FUNC(ST_DEVINFO, st_uscsi_cmd);
6053 
6054 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6055 	    "st_uscsi_cmd(dev = 0x%lx)\n", un->un_dev);
6056 
6057 	ASSERT(mutex_owned(ST_MUTEX));
6058 
6059 	/*
6060 	 * We really don't know what commands are coming in here and
6061 	 * we don't want to limit the commands coming in.
6062 	 *
6063 	 * If st_tape_init() gets called from st_strategy(), then we
6064 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
6065 	 * which it never will, as we set it below.  To prevent
6066 	 * st_tape_init() from getting called, we have to set state to other
6067 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
6068 	 * achieves this purpose already.
6069 	 *
6070 	 * We use offline_state to preserve the OFFLINE state, if it exists,
6071 	 * so other entry points to the driver might have the chance to call
6072 	 * st_tape_init().
6073 	 */
6074 	if (un->un_state == ST_STATE_OFFLINE) {
6075 		un->un_laststate = ST_STATE_OFFLINE;
6076 		un->un_state = ST_STATE_INITIALIZING;
6077 		offline_state = 1;
6078 	}
6079 
6080 	mutex_exit(ST_MUTEX);
6081 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag, ROUTE, &uscmd);
6082 	mutex_enter(ST_MUTEX);
6083 	if (err != 0) {
6084 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6085 		    "st_uscsi_cmd: scsi_uscsi_alloc_and_copyin failed\n");
6086 		goto exit;
6087 	}
6088 
6089 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
6090 
6091 	/* check to see if this command requires the drive to be reserved */
6092 	if (uscmd->uscsi_cdb != NULL) {
6093 		err = st_check_cdb_for_need_to_reserve(un,
6094 		    (uchar_t *)uscmd->uscsi_cdb);
6095 		if (err) {
6096 			goto exit_free;
6097 		}
6098 		/*
6099 		 * If this is a space command we need to save the starting
6100 		 * point so we can retry from there if the command fails.
6101 		 */
6102 		if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6103 		    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) {
6104 			(void) st_update_block_pos(un, st_cmd, 0);
6105 		}
6106 	}
6107 
6108 	/*
6109 	 * Forground should not be doing anything while recovery is active.
6110 	 */
6111 	ASSERT(un->un_recov_buf_busy == 0);
6112 
6113 	/*
6114 	 * Get buffer resources...
6115 	 */
6116 	while (un->un_sbuf_busy)
6117 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6118 	un->un_sbuf_busy = 1;
6119 
6120 #ifdef STDEBUG
6121 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0x7) > 6) {
6122 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
6123 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6124 		    "uscsi cdb", uscmd->uscsi_cdb);
6125 		if (uscmd->uscsi_buflen) {
6126 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6127 			    "uscsi %s of %ld bytes %s %s space\n",
6128 			    (rw == B_READ) ? rd_str : wr_str,
6129 			    uscmd->uscsi_buflen,
6130 			    (rw == B_READ) ? "to" : "from",
6131 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
6132 		}
6133 	}
6134 #endif /* STDEBUG */
6135 
6136 	/*
6137 	 * Although st_uscsi_cmd() never makes use of these
6138 	 * now, we are just being safe and consistent.
6139 	 */
6140 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
6141 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
6142 
6143 	un->un_srqbufp = uscmd->uscsi_rqbuf;
6144 	bp = un->un_sbufp;
6145 	bzero(bp, sizeof (buf_t));
6146 	if (uscmd->uscsi_cdb != NULL) {
6147 		bp->b_forw = (struct buf *)(uintptr_t)uscmd->uscsi_cdb[0];
6148 	}
6149 	bp->b_back = (struct buf *)uscmd;
6150 
6151 	mutex_exit(ST_MUTEX);
6152 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, st_strategy, bp, NULL);
6153 	mutex_enter(ST_MUTEX);
6154 
6155 	/*
6156 	 * If scsi reset successful, don't write any filemarks.
6157 	 */
6158 	if ((err == 0) && (uscmd->uscsi_flags &
6159 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
6160 		un->un_fmneeded = 0;
6161 	}
6162 
6163 exit_free:
6164 	/*
6165 	 * Free resources
6166 	 */
6167 	un->un_sbuf_busy = 0;
6168 	un->un_srqbufp = NULL;
6169 
6170 	/*
6171 	 * If was a space command need to update logical block position.
6172 	 * If the command failed such that positioning is invalid, Don't
6173 	 * update the position as the user must do this to validate the
6174 	 * position for data protection.
6175 	 */
6176 	if ((uscmd->uscsi_cdb != NULL) &&
6177 	    ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6178 	    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) &&
6179 	    (un->un_pos.pmode != invalid)) {
6180 		un->un_running.pmode = invalid;
6181 		(void) st_update_block_pos(un, st_cmd, 1);
6182 		/*
6183 		 * Set running position to invalid so it updates on the
6184 		 * next command.
6185 		 */
6186 		un->un_running.pmode = invalid;
6187 	}
6188 	cv_signal(&un->un_sbuf_cv);
6189 	mutex_exit(ST_MUTEX);
6190 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
6191 	mutex_enter(ST_MUTEX);
6192 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6193 	    "st_uscsi_cmd returns 0x%x\n", err);
6194 
6195 exit:
6196 	/* don't lose offline state */
6197 	if (offline_state) {
6198 		un->un_state = ST_STATE_OFFLINE;
6199 	}
6200 
6201 	ASSERT(mutex_owned(ST_MUTEX));
6202 	return (err);
6203 }
6204 
6205 static int
6206 st_write_fm(dev_t dev, int wfm)
6207 {
6208 	int i;
6209 	int rval;
6210 
6211 	GET_SOFT_STATE(dev);
6212 
6213 	ST_FUNC(ST_DEVINFO, st_write_fm);
6214 
6215 	ASSERT(mutex_owned(ST_MUTEX));
6216 
6217 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6218 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6219 
6220 	/*
6221 	 * write one filemark at the time after EOT
6222 	 */
6223 	if (un->un_pos.eof >= ST_EOT) {
6224 		for (i = 0; i < wfm; i++) {
6225 			rval = st_cmd(un, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6226 			if (rval == EACCES) {
6227 				return (rval);
6228 			}
6229 			if (rval != 0) {
6230 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6231 				    "st_write_fm : EIO : write EOT file mark");
6232 				return (EIO);
6233 			}
6234 		}
6235 	} else {
6236 		rval = st_cmd(un, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6237 		if (rval == EACCES) {
6238 			return (rval);
6239 		}
6240 		if (rval) {
6241 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6242 			    "st_write_fm : EIO : write file mark");
6243 			return (EIO);
6244 		}
6245 	}
6246 
6247 	ASSERT(mutex_owned(ST_MUTEX));
6248 	return (0);
6249 }
6250 
6251 #ifdef STDEBUG
6252 static void
6253 st_start_dump(struct scsi_tape *un, struct buf *bp)
6254 {
6255 	struct scsi_pkt *pkt = BP_PKT(bp);
6256 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6257 
6258 	ST_FUNC(ST_DEVINFO, st_start_dump);
6259 
6260 	if ((st_debug & 0x7) < 6)
6261 		return;
6262 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6263 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6264 	    (void *)bp->b_forw, bp->b_bcount,
6265 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6266 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6267 	    "st_start: cdb",  (caddr_t)cdbp);
6268 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6269 	    "st_start: fileno=%d, blk=%d\n",
6270 	    un->un_pos.fileno, un->un_pos.blkno);
6271 }
6272 #endif
6273 
6274 
6275 /*
6276  * Command start && done functions
6277  */
6278 
6279 /*
6280  * st_start()
6281  *
6282  * Called from:
6283  *  st_strategy() to start a command.
6284  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6285  *  st_attach() when resuming from power down state.
6286  *  st_start_restart() to retry transport when device was previously busy.
6287  *  st_done_and_mutex_exit() to start the next command when previous is done.
6288  *
6289  * On entry:
6290  *  scsi_pkt may or may not be allocated.
6291  *
6292  */
6293 static void
6294 st_start(struct scsi_tape *un)
6295 {
6296 	struct buf *bp;
6297 	int status;
6298 	int queued;
6299 
6300 	ST_FUNC(ST_DEVINFO, st_start);
6301 	ASSERT(mutex_owned(ST_MUTEX));
6302 
6303 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6304 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6305 
6306 	if (un->un_recov_buf_busy) {
6307 		/* recovery commands can happen anytime */
6308 		bp = un->un_recov_buf;
6309 		queued = 0;
6310 	} else if (un->un_sbuf_busy) {
6311 		/* sbuf commands should only happen with an empty queue. */
6312 		ASSERT(un->un_quef == NULL);
6313 		ASSERT(un->un_runqf == NULL);
6314 		bp = un->un_sbufp;
6315 		queued = 0;
6316 	} else if (un->un_quef != NULL) {
6317 		if (un->un_persistence && un->un_persist_errors) {
6318 			return;
6319 		}
6320 		bp = un->un_quef;
6321 		queued = 1;
6322 	} else {
6323 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6324 		    "st_start() returning no buf found\n");
6325 		return;
6326 	}
6327 
6328 	ASSERT((bp->b_flags & B_DONE) == 0);
6329 
6330 	/*
6331 	 * Don't send more than un_throttle commands to the HBA
6332 	 */
6333 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6334 		/*
6335 		 * if doing recovery we know there is outstanding commands.
6336 		 */
6337 		if (bp != un->un_recov_buf) {
6338 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6339 			    "st_start returning throttle = %d or ncmds = %d\n",
6340 			    un->un_throttle, un->un_ncmds);
6341 			if (un->un_ncmds == 0) {
6342 				typedef void (*func)();
6343 				func fnc = (func)st_runout;
6344 
6345 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6346 				    "Sending delayed start to st_runout()\n");
6347 				mutex_exit(ST_MUTEX);
6348 				(void) timeout(fnc, un, drv_usectohz(1000000));
6349 			}
6350 			return;
6351 		}
6352 	}
6353 
6354 	/*
6355 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6356 	 * build the command.
6357 	 */
6358 	if (BP_PKT(bp) == NULL) {
6359 		ASSERT((bp->b_flags & B_DONE) == 0);
6360 		st_make_cmd(un, bp, st_runout);
6361 		ASSERT((bp->b_flags & B_DONE) == 0);
6362 		status = geterror(bp);
6363 
6364 		/*
6365 		 * Some HBA's don't call bioerror() to set an error.
6366 		 * And geterror() returns zero if B_ERROR is not set.
6367 		 * So if we get zero we must check b_error.
6368 		 */
6369 		if (status == 0 && bp->b_error != 0) {
6370 			status = bp->b_error;
6371 			bioerror(bp, status);
6372 		}
6373 
6374 		/*
6375 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6376 		 * In tape ENOMEM has special meaning so we'll change it.
6377 		 */
6378 		if (status == ENOMEM) {
6379 			status = 0;
6380 			bioerror(bp, status);
6381 		}
6382 
6383 		/*
6384 		 * Did it fail and is it retryable?
6385 		 * If so return and wait for the callback through st_runout.
6386 		 * Also looks like scsi_init_pkt() will setup a callback even
6387 		 * if it isn't retryable.
6388 		 */
6389 		if (BP_PKT(bp) == NULL) {
6390 			if (status == 0) {
6391 				/*
6392 				 * If first attempt save state.
6393 				 */
6394 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6395 					un->un_laststate = un->un_state;
6396 					un->un_state = ST_STATE_RESOURCE_WAIT;
6397 				}
6398 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6399 				    "temp no resources for pkt\n");
6400 			} else if (status == EINVAL) {
6401 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6402 				    "scsi_init_pkt rejected pkt as too big\n");
6403 				if (un->un_persistence) {
6404 					st_set_pe_flag(un);
6405 				}
6406 			} else {
6407 				/*
6408 				 * Unlikely that it would be retryable then not.
6409 				 */
6410 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6411 					un->un_state = un->un_laststate;
6412 				}
6413 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6414 				    "perm no resources for pkt errno = 0x%x\n",
6415 				    status);
6416 			}
6417 			return;
6418 		}
6419 		/*
6420 		 * Worked this time set the state back.
6421 		 */
6422 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6423 			un->un_state = un->un_laststate;
6424 		}
6425 	}
6426 
6427 	if (queued) {
6428 		/*
6429 		 * move from waitq to runq
6430 		 */
6431 		(void) st_remove_from_queue(&un->un_quef, &un->un_quel, bp);
6432 		st_add_to_queue(&un->un_runqf, &un->un_runql, un->un_runql, bp);
6433 	}
6434 
6435 
6436 #ifdef STDEBUG
6437 	st_start_dump(un, bp);
6438 #endif
6439 
6440 	/* could not get here if throttle was zero */
6441 	un->un_last_throttle = un->un_throttle;
6442 	un->un_throttle = 0;	/* so nothing else will come in here */
6443 	un->un_ncmds++;
6444 
6445 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6446 
6447 	status = st_transport(un, BP_PKT(bp));
6448 
6449 	if (un->un_last_throttle) {
6450 		un->un_throttle = un->un_last_throttle;
6451 	}
6452 
6453 	if (status != TRAN_ACCEPT) {
6454 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6455 		mutex_exit(ST_MUTEX);
6456 
6457 		if (status == TRAN_BUSY) {
6458 			/* if too many retries, fail the transport */
6459 			if (st_handle_start_busy(un, bp,
6460 			    ST_TRAN_BUSY_TIMEOUT, queued) == 0)
6461 				goto done;
6462 		}
6463 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6464 		    "transport rejected %d\n", status);
6465 		bp->b_resid = bp->b_bcount;
6466 
6467 
6468 #ifndef __lock_lint
6469 		/*
6470 		 * warlock doesn't understand this potential
6471 		 * recursion?
6472 		 */
6473 		mutex_enter(ST_MUTEX);
6474 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6475 		ST_DO_ERRSTATS(un, st_transerrs);
6476 		st_bioerror(bp, EIO);
6477 		st_set_pe_flag(un);
6478 		st_done_and_mutex_exit(un, bp);
6479 #endif
6480 	} else {
6481 		un->un_tran_retry_ct = 0;
6482 		mutex_exit(ST_MUTEX);
6483 	}
6484 
6485 done:
6486 
6487 	mutex_enter(ST_MUTEX);
6488 }
6489 
6490 /*
6491  * if the transport is busy, then put this bp back on the waitq
6492  */
6493 static int
6494 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6495     clock_t timeout_interval, int queued)
6496 {
6497 
6498 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6499 
6500 	mutex_enter(ST_MUTEX);
6501 
6502 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6503 	    "st_handle_start_busy()\n");
6504 
6505 	/*
6506 	 * Check to see if we hit the retry timeout and one last check for
6507 	 * making sure this is the last on the runq, if it is not, we have
6508 	 * to fail
6509 	 */
6510 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
6511 	    ((queued) && (un->un_runql != bp))) {
6512 		mutex_exit(ST_MUTEX);
6513 		return (-1);
6514 	}
6515 
6516 	if (queued) {
6517 		/* put the bp back on the waitq */
6518 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
6519 	}
6520 
6521 	/*
6522 	 * Decrement un_ncmds so that this
6523 	 * gets thru' st_start() again.
6524 	 */
6525 	un->un_ncmds--;
6526 
6527 	if (queued) {
6528 		/*
6529 		 * since this is an error case, we won't have to do this list
6530 		 * walking much. We've already made sure this bp was the
6531 		 * last on the runq
6532 		 */
6533 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6534 
6535 		/*
6536 		 * send a marker pkt, if appropriate
6537 		 */
6538 		st_hba_unflush(un);
6539 
6540 	}
6541 	/*
6542 	 * all queues are aligned, we are just waiting to
6543 	 * transport, don't alloc any more buf p's, when
6544 	 * st_start is reentered.
6545 	 */
6546 	(void) timeout(st_start_restart, un, timeout_interval);
6547 
6548 	mutex_exit(ST_MUTEX);
6549 	return (0);
6550 }
6551 
6552 
6553 /*
6554  * st_runout a callback that is called what a resource allocatation failed
6555  */
6556 static int
6557 st_runout(caddr_t arg)
6558 {
6559 	struct scsi_tape *un = (struct scsi_tape *)arg;
6560 	struct buf *bp;
6561 	int queued;
6562 
6563 	ASSERT(un != NULL);
6564 
6565 	ST_FUNC(ST_DEVINFO, st_runout);
6566 
6567 	mutex_enter(ST_MUTEX);
6568 
6569 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6570 
6571 	if (un->un_recov_buf_busy != 0) {
6572 		bp = un->un_recov_buf;
6573 		queued = 0;
6574 	} else if (un->un_sbuf_busy != 0) {
6575 		/* sbuf commands should only happen with an empty queue. */
6576 		ASSERT(un->un_quef == NULL);
6577 		ASSERT(un->un_runqf == NULL);
6578 		bp = un->un_sbufp;
6579 		queued = 0;
6580 	} else if (un->un_quef != NULL) {
6581 		bp = un->un_quef;
6582 		if (un->un_persistence && un->un_persist_errors) {
6583 			mutex_exit(ST_MUTEX);
6584 			bp->b_resid = bp->b_bcount;
6585 			biodone(bp);
6586 			return (1);
6587 		}
6588 		queued = 1;
6589 	} else {
6590 		ASSERT(1 == 0);
6591 		mutex_exit(ST_MUTEX);
6592 		return (1);
6593 	}
6594 
6595 	/*
6596 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6597 	 */
6598 	if ((bp != NULL) && (geterror(bp) != 0)) {
6599 
6600 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6601 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6602 		    bp->b_flags, geterror(bp));
6603 		ASSERT((bp->b_flags & B_DONE) == 0);
6604 
6605 		if (queued) {
6606 			(void) st_remove_from_queue(&un->un_quef, &un->un_quel,
6607 			    bp);
6608 		}
6609 		mutex_exit(ST_MUTEX);
6610 
6611 		ASSERT((bp->b_flags & B_DONE) == 0);
6612 
6613 		/*
6614 		 * Set resid, Error already set, then unblock calling thread.
6615 		 */
6616 		bp->b_resid = bp->b_bcount;
6617 		biodone(bp);
6618 	} else {
6619 		/*
6620 		 * Try Again
6621 		 */
6622 		st_start(un);
6623 		mutex_exit(ST_MUTEX);
6624 	}
6625 
6626 	/*
6627 	 * Comments courtesy of sd.c
6628 	 * The scsi_init_pkt routine allows for the callback function to
6629 	 * return a 0 indicating the callback should be rescheduled or a 1
6630 	 * indicating not to reschedule. This routine always returns 1
6631 	 * because the driver always provides a callback function to
6632 	 * scsi_init_pkt. This results in a callback always being scheduled
6633 	 * (via the scsi_init_pkt callback implementation) if a resource
6634 	 * failure occurs.
6635 	 */
6636 
6637 	return (1);
6638 }
6639 
6640 /*
6641  * st_done_and_mutex_exit()
6642  *	- remove bp from runq
6643  *	- start up the next request
6644  *	- if this was an asynch bp, clean up
6645  *	- exit with released mutex
6646  */
6647 static void
6648 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6649 {
6650 	int	pe_flagged = 0;
6651 
6652 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6653 #if !defined(lint)
6654 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6655 #endif
6656 
6657 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6658 
6659 	ASSERT(mutex_owned(ST_MUTEX));
6660 
6661 	(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6662 
6663 	un->un_ncmds--;
6664 	cv_signal(&un->un_queue_cv);
6665 
6666 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6667 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6668 	    "0x%x\n", (uchar_t)*((caddr_t)(BP_PKT(bp))->pkt_cdbp), bp->b_bcount,
6669 	    bp->b_resid, bp->b_flags);
6670 
6671 
6672 	/*
6673 	 * update kstats with transfer count info
6674 	 */
6675 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6676 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6677 		if (bp->b_flags & B_READ) {
6678 			IOSP->reads++;
6679 			IOSP->nread += n_done;
6680 		} else {
6681 			IOSP->writes++;
6682 			IOSP->nwritten += n_done;
6683 		}
6684 	}
6685 
6686 	/*
6687 	 * Start the next one before releasing resources on this one, if
6688 	 * there is something on the queue and persistent errors has not been
6689 	 * flagged
6690 	 */
6691 
6692 	if ((pe_flagged = (un->un_persistence && un->un_persist_errors)) != 0) {
6693 		un->un_last_resid = bp->b_resid;
6694 		un->un_last_count = bp->b_bcount;
6695 	}
6696 
6697 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6698 		cv_broadcast(&un->un_tape_busy_cv);
6699 	} else if (un->un_quef && un->un_throttle && !pe_flagged &&
6700 	    (bp != un->un_recov_buf)) {
6701 		st_start(un);
6702 	}
6703 
6704 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6705 		/*
6706 		 * Since we marked this ourselves as ASYNC,
6707 		 * there isn't anybody around waiting for
6708 		 * completion any more.
6709 		 */
6710 		uchar_t *cdb = (uchar_t *)bp->b_forw;
6711 		if (*cdb == SCMD_READ || *cdb == SCMD_WRITE) {
6712 			bp->b_un.b_addr = (caddr_t)0;
6713 		}
6714 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6715 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6716 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
6717 		    "CDB sent with B_ASYNC",  (caddr_t)cdb);
6718 		if (BP_PKT(bp)) {
6719 			scsi_destroy_pkt(BP_PKT(bp));
6720 		}
6721 		un->un_sbuf_busy = 0;
6722 		cv_signal(&un->un_sbuf_cv);
6723 		mutex_exit(ST_MUTEX);
6724 		return;
6725 	}
6726 
6727 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6728 		/*
6729 		 * Copy status from scsi_pkt to uscsi_cmd
6730 		 * since st_uscsi_cmd needs it
6731 		 */
6732 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6733 	}
6734 
6735 
6736 #ifdef STDEBUG
6737 	if (((st_debug & 0x7) >= 4) &&
6738 	    (((un->un_pos.blkno % 100) == 0) ||
6739 	    (un->un_persistence && un->un_persist_errors))) {
6740 
6741 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6742 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6743 		    "un_errno = %d, un_pe = %d\n",
6744 		    un->un_ncmds, un->un_throttle, un->un_errno,
6745 		    un->un_persist_errors);
6746 	}
6747 
6748 #endif
6749 
6750 	mutex_exit(ST_MUTEX);
6751 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6752 	    "st_done_and_mutex_exit: freeing pkt\n");
6753 
6754 	if (BP_PKT(bp)) {
6755 		scsi_destroy_pkt(BP_PKT(bp));
6756 	}
6757 
6758 	biodone(bp);
6759 
6760 	/*
6761 	 * now that we biodoned that command, if persistent errors have been
6762 	 * flagged, flush the waitq
6763 	 */
6764 	if (pe_flagged)
6765 		st_flush(un);
6766 }
6767 
6768 
6769 /*
6770  * Tape error, flush tape driver queue.
6771  */
6772 static void
6773 st_flush(struct scsi_tape *un)
6774 {
6775 	struct buf *bp;
6776 
6777 	ST_FUNC(ST_DEVINFO, st_flush);
6778 
6779 	mutex_enter(ST_MUTEX);
6780 
6781 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6782 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6783 	    un->un_ncmds, (void *)un->un_quef);
6784 
6785 	/*
6786 	 * if we still have commands outstanding, wait for them to come in
6787 	 * before flushing the queue, and make sure there is a queue
6788 	 */
6789 	if (un->un_ncmds || !un->un_quef)
6790 		goto exit;
6791 
6792 	/*
6793 	 * we have no more commands outstanding, so let's deal with special
6794 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6795 	 * is 0, then we know there was no error and we return a 0 read or
6796 	 * write before showing errors
6797 	 */
6798 
6799 	/* Flush the wait queue. */
6800 	while ((bp = un->un_quef) != NULL) {
6801 		un->un_quef = bp->b_actf;
6802 
6803 		bp->b_resid = bp->b_bcount;
6804 
6805 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6806 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6807 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6808 
6809 		st_set_pe_errno(un);
6810 
6811 		bioerror(bp, un->un_errno);
6812 
6813 		mutex_exit(ST_MUTEX);
6814 		/* it should have one, but check anyway */
6815 		if (BP_PKT(bp)) {
6816 			scsi_destroy_pkt(BP_PKT(bp));
6817 		}
6818 		biodone(bp);
6819 		mutex_enter(ST_MUTEX);
6820 	}
6821 
6822 	/*
6823 	 * It's not a bad practice to reset the
6824 	 * waitq tail pointer to NULL.
6825 	 */
6826 	un->un_quel = NULL;
6827 
6828 exit:
6829 	/* we mucked with the queue, so let others know about it */
6830 	cv_signal(&un->un_queue_cv);
6831 	mutex_exit(ST_MUTEX);
6832 }
6833 
6834 
6835 /*
6836  * Utility functions
6837  */
6838 static int
6839 st_determine_generic(struct scsi_tape *un)
6840 {
6841 	int bsize;
6842 	static char *cart = "0.25 inch cartridge";
6843 	char *sizestr;
6844 
6845 	ST_FUNC(ST_DEVINFO, st_determine_generic);
6846 
6847 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6848 	    "st_determine_generic(un = 0x%p)\n", (void*)un);
6849 
6850 	ASSERT(mutex_owned(ST_MUTEX));
6851 
6852 	if (st_modesense(un)) {
6853 		return (-1);
6854 	}
6855 
6856 	bsize = (un->un_mspl->high_bl << 16)	|
6857 	    (un->un_mspl->mid_bl << 8)	|
6858 	    (un->un_mspl->low_bl);
6859 
6860 	if (bsize == 0) {
6861 		un->un_dp->options |= ST_VARIABLE;
6862 		un->un_dp->bsize = 0;
6863 		un->un_bsize = 0;
6864 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
6865 		/*
6866 		 * record size of this device too big.
6867 		 * try and convert it to variable record length.
6868 		 *
6869 		 */
6870 		un->un_dp->options |= ST_VARIABLE;
6871 		if (st_change_block_size(un, 0) != 0) {
6872 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6873 			    "Fixed Record Size %d is too large\n", bsize);
6874 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6875 			    "Cannot switch to variable record size\n");
6876 			un->un_dp->options &= ~ST_VARIABLE;
6877 			return (-1);
6878 		}
6879 	} else if (st_change_block_size(un, 0) == 0) {
6880 		/*
6881 		 * If the drive was set to a non zero block size,
6882 		 * See if it can be set to a zero block size.
6883 		 * If it works, ST_VARIABLE so user can set it as they want.
6884 		 */
6885 		un->un_dp->options |= ST_VARIABLE;
6886 		un->un_dp->bsize = 0;
6887 		un->un_bsize = 0;
6888 	} else {
6889 		un->un_dp->bsize = bsize;
6890 		un->un_bsize = bsize;
6891 	}
6892 
6893 
6894 	switch (un->un_mspl->density) {
6895 	default:
6896 	case 0x0:
6897 		/*
6898 		 * default density, cannot determine any other
6899 		 * information.
6900 		 */
6901 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
6902 		un->un_dp->type = ST_TYPE_DEFAULT;
6903 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
6904 		break;
6905 	case 0x1:
6906 	case 0x2:
6907 	case 0x3:
6908 	case 0x6:
6909 		/*
6910 		 * 1/2" reel
6911 		 */
6912 		sizestr = "0.50 inch reel";
6913 		un->un_dp->type = ST_TYPE_REEL;
6914 		un->un_dp->options |= ST_REEL;
6915 		un->un_dp->densities[0] = 0x1;
6916 		un->un_dp->densities[1] = 0x2;
6917 		un->un_dp->densities[2] = 0x6;
6918 		un->un_dp->densities[3] = 0x3;
6919 		break;
6920 	case 0x4:
6921 	case 0x5:
6922 	case 0x7:
6923 	case 0x0b:
6924 
6925 		/*
6926 		 * Quarter inch.
6927 		 */
6928 		sizestr = cart;
6929 		un->un_dp->type = ST_TYPE_DEFAULT;
6930 		un->un_dp->options |= ST_QIC;
6931 
6932 		un->un_dp->densities[1] = 0x4;
6933 		un->un_dp->densities[2] = 0x5;
6934 		un->un_dp->densities[3] = 0x7;
6935 		un->un_dp->densities[0] = 0x0b;
6936 		break;
6937 
6938 	case 0x0f:
6939 	case 0x10:
6940 	case 0x11:
6941 	case 0x12:
6942 		/*
6943 		 * QIC-120, QIC-150, QIC-320, QIC-600
6944 		 */
6945 		sizestr = cart;
6946 		un->un_dp->type = ST_TYPE_DEFAULT;
6947 		un->un_dp->options |= ST_QIC;
6948 		un->un_dp->densities[0] = 0x0f;
6949 		un->un_dp->densities[1] = 0x10;
6950 		un->un_dp->densities[2] = 0x11;
6951 		un->un_dp->densities[3] = 0x12;
6952 		break;
6953 
6954 	case 0x09:
6955 	case 0x0a:
6956 	case 0x0c:
6957 	case 0x0d:
6958 		/*
6959 		 * 1/2" cartridge tapes. Include HI-TC.
6960 		 */
6961 		sizestr = cart;
6962 		sizestr[2] = '5';
6963 		sizestr[3] = '0';
6964 		un->un_dp->type = ST_TYPE_HIC;
6965 		un->un_dp->densities[0] = 0x09;
6966 		un->un_dp->densities[1] = 0x0a;
6967 		un->un_dp->densities[2] = 0x0c;
6968 		un->un_dp->densities[3] = 0x0d;
6969 		break;
6970 
6971 	case 0x13:
6972 			/* DDS-2/DDS-3 scsi spec densities */
6973 	case 0x24:
6974 	case 0x25:
6975 	case 0x26:
6976 		sizestr = "DAT Data Storage (DDS)";
6977 		un->un_dp->type = ST_TYPE_DAT;
6978 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6979 		break;
6980 
6981 	case 0x14:
6982 		/*
6983 		 * Helical Scan (Exabyte) devices
6984 		 */
6985 		sizestr = "8mm helical scan cartridge";
6986 		un->un_dp->type = ST_TYPE_EXABYTE;
6987 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6988 		break;
6989 	}
6990 
6991 	/*
6992 	 * Assume LONG ERASE, BSF and BSR
6993 	 */
6994 
6995 	un->un_dp->options |=
6996 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
6997 
6998 	/*
6999 	 * Only if mode sense data says no buffered write, set NOBUF
7000 	 */
7001 	if (un->un_mspl->bufm == 0)
7002 		un->un_dp->options |= ST_NOBUF;
7003 
7004 	/*
7005 	 * set up large read and write retry counts
7006 	 */
7007 
7008 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
7009 
7010 	/*
7011 	 * If this is a 0.50 inch reel tape, and
7012 	 * it is *not* variable mode, try and
7013 	 * set it to variable record length
7014 	 * mode.
7015 	 */
7016 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
7017 	    (un->un_dp->options & ST_VARIABLE)) {
7018 		if (st_change_block_size(un, 0) == 0) {
7019 			un->un_dp->bsize = 0;
7020 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
7021 			    un->un_mspl->low_bl = 0;
7022 		}
7023 	}
7024 
7025 	/*
7026 	 * Write to console about type of device found
7027 	 */
7028 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
7029 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
7030 	    sizestr);
7031 	if (un->un_dp->options & ST_VARIABLE) {
7032 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7033 		    "!Variable record length I/O\n");
7034 	} else {
7035 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7036 		    "!Fixed record length (%d byte blocks) I/O\n",
7037 		    un->un_dp->bsize);
7038 	}
7039 	ASSERT(mutex_owned(ST_MUTEX));
7040 	return (0);
7041 }
7042 
7043 static int
7044 st_determine_density(struct scsi_tape *un, int rw)
7045 {
7046 	int rval = 0;
7047 
7048 	ST_FUNC(ST_DEVINFO, st_determine_density);
7049 
7050 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7051 	    "st_determine_density(un = 0x%p, rw = %s)\n",
7052 	    (void*)un, (rw == B_WRITE ? wr_str: rd_str));
7053 
7054 	ASSERT(mutex_owned(ST_MUTEX));
7055 
7056 	/*
7057 	 * If we're past BOT, density is determined already.
7058 	 */
7059 	if (un->un_pos.pmode == logical) {
7060 		if (un->un_pos.lgclblkno != 0) {
7061 			goto exit;
7062 		}
7063 	} else if (un->un_pos.pmode == legacy) {
7064 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
7065 			/*
7066 			 * XXX: put in a bitch message about attempting to
7067 			 * XXX: change density past BOT.
7068 			 */
7069 			goto exit;
7070 		}
7071 	} else {
7072 		goto exit;
7073 	}
7074 	if ((un->un_pos.pmode == logical) &&
7075 	    (un->un_pos.lgclblkno != 0)) {
7076 		goto exit;
7077 	}
7078 
7079 
7080 	/*
7081 	 * If we're going to be writing, we set the density
7082 	 */
7083 	if (rw == 0 || rw == B_WRITE) {
7084 		/* un_curdens is used as an index into densities table */
7085 		un->un_curdens = MT_DENSITY(un->un_dev);
7086 		if (st_set_density(un)) {
7087 			rval = -1;
7088 		}
7089 		goto exit;
7090 	}
7091 
7092 	/*
7093 	 * If density is known already,
7094 	 * we don't have to get it again.(?)
7095 	 */
7096 	if (!un->un_density_known) {
7097 		if (st_get_density(un)) {
7098 			rval = -1;
7099 		}
7100 	}
7101 
7102 exit:
7103 	ASSERT(mutex_owned(ST_MUTEX));
7104 	return (rval);
7105 }
7106 
7107 
7108 /*
7109  * Try to determine density. We do this by attempting to read the
7110  * first record off the tape, cycling through the available density
7111  * codes as we go.
7112  */
7113 
7114 static int
7115 st_get_density(struct scsi_tape *un)
7116 {
7117 	int succes = 0, rval = -1, i;
7118 	uint_t size;
7119 	uchar_t dens, olddens;
7120 
7121 	ST_FUNC(ST_DEVINFO, st_get_density);
7122 
7123 	ST_FUNC(ST_DEVINFO, st_get_density);
7124 
7125 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7126 	    "st_get_density(un = 0x%p)\n", (void*)un);
7127 
7128 	ASSERT(mutex_owned(ST_MUTEX));
7129 
7130 	/*
7131 	 * If Auto Density override is enabled The drive has
7132 	 * only one density and there is no point in attempting
7133 	 * find the correct one.
7134 	 *
7135 	 * Since most modern drives auto detect the density
7136 	 * and format of the recorded media before they come
7137 	 * ready. What this function does is a legacy behavior
7138 	 * and modern drives not only don't need it, The backup
7139 	 * utilities that do positioning via uscsi find the un-
7140 	 * expected rewinds problematic.
7141 	 *
7142 	 * The drives that need this are old reel to reel devices.
7143 	 * I took a swag and said they must be scsi-1 or older.
7144 	 * I don't beleave there will any of the newer devices
7145 	 * that need this. There will be some scsi-1 devices that
7146 	 * don't need this but I don't think they will be using the
7147 	 * BIG aftermarket backup and restore utilitys.
7148 	 */
7149 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
7150 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
7151 		un->un_density_known = 1;
7152 		rval = 0;
7153 		goto exit;
7154 	}
7155 
7156 	/*
7157 	 * This will only work on variable record length tapes
7158 	 * if and only if all variable record length tapes autodensity
7159 	 * select.
7160 	 */
7161 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
7162 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
7163 
7164 	/*
7165 	 * Start at the specified density
7166 	 */
7167 
7168 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
7169 
7170 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
7171 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
7172 		/*
7173 		 * If we've done this density before,
7174 		 * don't bother to do it again.
7175 		 */
7176 		dens = un->un_dp->densities[un->un_curdens];
7177 		if (i > 0 && dens == olddens)
7178 			continue;
7179 		olddens = dens;
7180 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7181 		    "trying density 0x%x\n", dens);
7182 		if (st_set_density(un)) {
7183 			continue;
7184 		}
7185 
7186 		/*
7187 		 * XXX - the creates lots of headaches and slowdowns - must
7188 		 * fix.
7189 		 */
7190 		succes = (st_cmd(un, SCMD_READ, (int)size, SYNC_CMD) == 0);
7191 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
7192 			break;
7193 		}
7194 		if (succes) {
7195 			st_init(un);
7196 			rval = 0;
7197 			un->un_density_known = 1;
7198 			break;
7199 		}
7200 	}
7201 	kmem_free(un->un_tmpbuf, size);
7202 	un->un_tmpbuf = 0;
7203 
7204 exit:
7205 	ASSERT(mutex_owned(ST_MUTEX));
7206 	return (rval);
7207 }
7208 
7209 static int
7210 st_set_density(struct scsi_tape *un)
7211 {
7212 	int rval = 0;
7213 
7214 	ST_FUNC(ST_DEVINFO, st_set_density);
7215 
7216 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7217 	    "st_set_density(un = 0x%p): density = 0x%x\n", (void*)un,
7218 	    un->un_dp->densities[un->un_curdens]);
7219 
7220 	ASSERT(mutex_owned(ST_MUTEX));
7221 
7222 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7223 
7224 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
7225 		/*
7226 		 * If auto density override is not set, Use mode select
7227 		 * to set density and compression.
7228 		 */
7229 		if (st_modeselect(un)) {
7230 			rval = -1;
7231 		}
7232 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
7233 		/*
7234 		 * If auto density and mode select compression are set,
7235 		 * This is a drive with one density code but compression
7236 		 * can be enabled or disabled.
7237 		 * Set compression but no need to set density.
7238 		 */
7239 		rval = st_set_compression(un);
7240 		if ((rval != 0) && (rval != EALREADY)) {
7241 			rval = -1;
7242 		} else {
7243 			rval = 0;
7244 		}
7245 	}
7246 
7247 	/* If sucessful set density and/or compression, mark density known */
7248 	if (rval == 0) {
7249 		un->un_density_known = 1;
7250 	}
7251 
7252 	ASSERT(mutex_owned(ST_MUTEX));
7253 	return (rval);
7254 }
7255 
7256 static int
7257 st_loadtape(struct scsi_tape *un)
7258 {
7259 	int rval;
7260 
7261 	ST_FUNC(ST_DEVINFO, st_loadtape);
7262 
7263 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7264 	    "st_loadtape(un = 0x%p)\n", (void*) un);
7265 
7266 	ASSERT(mutex_owned(ST_MUTEX));
7267 
7268 	rval = st_update_block_pos(un, st_cmd, 0);
7269 	if (rval == EACCES) {
7270 		return (rval);
7271 	}
7272 
7273 	/*
7274 	 * 'LOAD' the tape to BOT by rewinding
7275 	 */
7276 	rval = st_cmd(un, SCMD_REWIND, 1, SYNC_CMD);
7277 	if (rval == 0) {
7278 		st_init(un);
7279 		un->un_density_known = 0;
7280 	}
7281 
7282 	ASSERT(mutex_owned(ST_MUTEX));
7283 	return (rval);
7284 }
7285 
7286 
7287 /*
7288  * Note: QIC devices aren't so smart.  If you try to append
7289  * after EOM, the write can fail because the device doesn't know
7290  * it's at EOM.	 In that case, issue a read.  The read should fail
7291  * because there's no data, but the device knows it's at EOM,
7292  * so a subsequent write should succeed.  To further confuse matters,
7293  * the target returns the same error if the tape is positioned
7294  * such that a write would overwrite existing data.  That's why
7295  * we have to do the append test.  A read in the middle of
7296  * recorded data would succeed, thus indicating we're attempting
7297  * something illegal.
7298  */
7299 
7300 
7301 static void
7302 st_test_append(struct buf *bp)
7303 {
7304 	dev_t dev = bp->b_edev;
7305 	struct scsi_tape *un;
7306 	uchar_t status;
7307 	unsigned bcount;
7308 
7309 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7310 
7311 	ST_FUNC(ST_DEVINFO, st_test_append);
7312 
7313 	ASSERT(mutex_owned(ST_MUTEX));
7314 
7315 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7316 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7317 
7318 	un->un_laststate = un->un_state;
7319 	un->un_state = ST_STATE_APPEND_TESTING;
7320 	un->un_test_append = 0;
7321 
7322 	/*
7323 	 * first, map in the buffer, because we're doing a double write --
7324 	 * first into the kernel, then onto the tape.
7325 	 */
7326 	bp_mapin(bp);
7327 
7328 	/*
7329 	 * get a copy of the data....
7330 	 */
7331 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7332 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7333 
7334 	/*
7335 	 * attempt the write..
7336 	 */
7337 
7338 	if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7339 success:
7340 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7341 		    "append write succeeded\n");
7342 		bp->b_resid = un->un_sbufp->b_resid;
7343 		mutex_exit(ST_MUTEX);
7344 		bcount = (unsigned)bp->b_bcount;
7345 		biodone(bp);
7346 		mutex_enter(ST_MUTEX);
7347 		un->un_laststate = un->un_state;
7348 		un->un_state = ST_STATE_OPEN;
7349 		kmem_free(un->un_tmpbuf, bcount);
7350 		un->un_tmpbuf = NULL;
7351 		return;
7352 	}
7353 
7354 	/*
7355 	 * The append failed. Do a short read. If that fails,  we are at EOM
7356 	 * so we can retry the write command. If that succeeds, than we're
7357 	 * all screwed up (the controller reported a real error).
7358 	 *
7359 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7360 	 * XXX: block size?
7361 	 *
7362 	 */
7363 	status = un->un_status;
7364 	un->un_status = 0;
7365 	(void) st_cmd(un, SCMD_READ, SECSIZE, SYNC_CMD);
7366 	if (un->un_status == KEY_BLANK_CHECK) {
7367 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7368 		    "append at EOM\n");
7369 		/*
7370 		 * Okay- the read failed. We should actually have confused
7371 		 * the controller enough to allow writing. In any case, the
7372 		 * i/o is on its own from here on out.
7373 		 */
7374 		un->un_laststate = un->un_state;
7375 		un->un_state = ST_STATE_OPEN;
7376 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7377 		if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount,
7378 		    SYNC_CMD) == 0) {
7379 			goto success;
7380 		}
7381 	}
7382 
7383 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7384 	    "append write failed- not at EOM\n");
7385 	bp->b_resid = bp->b_bcount;
7386 	st_bioerror(bp, EIO);
7387 
7388 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7389 	    "st_test_append : EIO : append write failed - not at EOM");
7390 
7391 	/*
7392 	 * backspace one record to get back to where we were
7393 	 */
7394 	if (st_cmd(un, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7395 		un->un_pos.pmode = invalid;
7396 	}
7397 
7398 	un->un_err_resid = bp->b_resid;
7399 	un->un_status = status;
7400 
7401 	/*
7402 	 * Note: biodone will do a bp_mapout()
7403 	 */
7404 	mutex_exit(ST_MUTEX);
7405 	bcount = (unsigned)bp->b_bcount;
7406 	biodone(bp);
7407 	mutex_enter(ST_MUTEX);
7408 	un->un_laststate = un->un_state;
7409 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7410 	kmem_free(un->un_tmpbuf, bcount);
7411 	un->un_tmpbuf = NULL;
7412 }
7413 
7414 /*
7415  * Special command handler
7416  */
7417 
7418 /*
7419  * common st_cmd code. The fourth parameter states
7420  * whether the caller wishes to await the results
7421  * Note the release of the mutex during most of the function
7422  */
7423 static int
7424 st_cmd(struct scsi_tape *un, int com, int64_t count, int wait)
7425 {
7426 	struct buf *bp;
7427 	int err;
7428 	uint_t last_err_resid;
7429 
7430 	ST_FUNC(ST_DEVINFO, st_cmd);
7431 
7432 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7433 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %"PRIx64", wait = %d)\n",
7434 	    un->un_dev, com, count, wait);
7435 
7436 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7437 	ASSERT(mutex_owned(ST_MUTEX));
7438 
7439 #ifdef STDEBUG
7440 	if ((st_debug & 0x7)) {
7441 		st_debug_cmds(un, com, count, wait);
7442 	}
7443 #endif
7444 
7445 	st_wait_for_io(un);
7446 
7447 	/* check to see if this command requires the drive to be reserved */
7448 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7449 
7450 	if (err) {
7451 		return (err);
7452 	}
7453 
7454 	/*
7455 	 * A space command is not recoverable if we don't know were we
7456 	 * were when it was issued.
7457 	 */
7458 	if ((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) {
7459 		(void) st_update_block_pos(un, st_cmd, 0);
7460 	}
7461 
7462 	/*
7463 	 * Forground should not be doing anything while recovery is active.
7464 	 */
7465 	ASSERT(un->un_recov_buf_busy == 0);
7466 
7467 	while (un->un_sbuf_busy)
7468 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7469 	un->un_sbuf_busy = 1;
7470 
7471 	bp = un->un_sbufp;
7472 	bzero(bp, sizeof (buf_t));
7473 
7474 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7475 
7476 	err = st_setup_cmd(un, bp, com, count);
7477 
7478 	un->un_sbuf_busy = 0;
7479 
7480 	/*
7481 	 * If was a space command need to update logical block position.
7482 	 * Only do this if the command was sucessful or it will mask the fact
7483 	 * that the space command failed by promoting the pmode to logical.
7484 	 */
7485 	if (((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) &&
7486 	    (un->un_pos.pmode != invalid)) {
7487 		un->un_running.pmode = invalid;
7488 		last_err_resid = un->un_err_resid;
7489 		(void) st_update_block_pos(un, st_cmd, 1);
7490 		/*
7491 		 * Set running position to invalid so it updates on the
7492 		 * next command.
7493 		 */
7494 		un->un_running.pmode = invalid;
7495 		un->un_err_resid = last_err_resid;
7496 	}
7497 
7498 	cv_signal(&un->un_sbuf_cv);
7499 
7500 	return (err);
7501 }
7502 
7503 static int
7504 st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com, int64_t count)
7505 {
7506 	int err;
7507 	dev_t dev = un->un_dev;
7508 
7509 	ST_FUNC(ST_DEVINFO, st_setup_cmd);
7510 	/*
7511 	 * Set count to the actual size of the data tranfer.
7512 	 * For commands with no data transfer, set bp->b_bcount
7513 	 * to the value to be used when constructing the
7514 	 * cdb in st_make_cmd().
7515 	 */
7516 	switch (com) {
7517 	case SCMD_READ:
7518 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7519 		    "special read %"PRId64"\n", count);
7520 		bp->b_flags |= B_READ;
7521 		bp->b_un.b_addr = un->un_tmpbuf;
7522 		break;
7523 
7524 	case SCMD_WRITE:
7525 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7526 		    "special write %"PRId64"\n", count);
7527 		bp->b_un.b_addr = un->un_tmpbuf;
7528 		break;
7529 
7530 	case SCMD_WRITE_FILE_MARK:
7531 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7532 		    "write %"PRId64" file marks\n", count);
7533 		bp->b_bcount = count;
7534 		count = 0;
7535 		break;
7536 
7537 	case SCMD_REWIND:
7538 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7539 		bp->b_bcount = count;
7540 		count = 0;
7541 		break;
7542 
7543 	case SCMD_SPACE:
7544 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7545 		/*
7546 		 * If the user could have entered a number that will
7547 		 * not fit in the 12 bit count field of space(8),
7548 		 * use space(16).
7549 		 */
7550 		if (((int64_t)SPACE_CNT(count) > 0x7fffff) ||
7551 		    ((int64_t)SPACE_CNT(count) < -(0x7fffff))) {
7552 			com = SCMD_SPACE_G4;
7553 		}
7554 		bp->b_bcount = count;
7555 		count = 0;
7556 		break;
7557 
7558 	case SCMD_RESERVE:
7559 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7560 		bp->b_bcount = 0;
7561 		count = 0;
7562 		break;
7563 
7564 	case SCMD_RELEASE:
7565 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7566 		bp->b_bcount = 0;
7567 		count = 0;
7568 		break;
7569 
7570 	case SCMD_LOAD:
7571 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7572 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7573 		bp->b_bcount = count;
7574 		count = 0;
7575 		break;
7576 
7577 	case SCMD_ERASE:
7578 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7579 		    "erase tape\n");
7580 		bp->b_bcount = count;
7581 		count = 0;
7582 		break;
7583 
7584 	case SCMD_MODE_SENSE:
7585 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7586 		    "mode sense\n");
7587 		bp->b_flags |= B_READ;
7588 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7589 		break;
7590 
7591 	case SCMD_MODE_SELECT:
7592 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7593 		    "mode select\n");
7594 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7595 		break;
7596 
7597 	case SCMD_READ_BLKLIM:
7598 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7599 		    "read block limits\n");
7600 		bp->b_bcount = count;
7601 		bp->b_flags |= B_READ;
7602 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7603 		break;
7604 
7605 	case SCMD_TEST_UNIT_READY:
7606 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7607 		    "test unit ready\n");
7608 		bp->b_bcount = 0;
7609 		count = 0;
7610 		break;
7611 
7612 	case SCMD_DOORLOCK:
7613 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7614 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7615 		bp->b_bcount = count = 0;
7616 		break;
7617 
7618 	case SCMD_READ_POSITION:
7619 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7620 		    "read position\n");
7621 		switch (un->un_read_pos_type) {
7622 		case LONG_POS:
7623 			count = sizeof (tape_position_long_t);
7624 			break;
7625 		case EXT_POS:
7626 			count = min(count, sizeof (tape_position_ext_t));
7627 			break;
7628 		case SHORT_POS:
7629 			count = sizeof (tape_position_t);
7630 			break;
7631 		default:
7632 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7633 			    "Unknown read position type 0x%x in "
7634 			    "st_make_cmd()\n", un->un_read_pos_type);
7635 		}
7636 		bp->b_bcount = count;
7637 		bp->b_flags |= B_READ;
7638 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7639 		break;
7640 
7641 	default:
7642 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7643 		    "Unhandled scsi command 0x%x in st_setup_cmd()\n", com);
7644 	}
7645 
7646 	mutex_exit(ST_MUTEX);
7647 
7648 	if (count > 0) {
7649 		int flg = (bp->b_flags & B_READ) ? B_READ : B_WRITE;
7650 		/*
7651 		 * We're going to do actual I/O.
7652 		 * Set things up for physio.
7653 		 */
7654 		struct iovec aiov;
7655 		struct uio auio;
7656 		struct uio *uio = &auio;
7657 
7658 		bzero(&auio, sizeof (struct uio));
7659 		bzero(&aiov, sizeof (struct iovec));
7660 		aiov.iov_base = bp->b_un.b_addr;
7661 		aiov.iov_len = count;
7662 
7663 		uio->uio_iov = &aiov;
7664 		uio->uio_iovcnt = 1;
7665 		uio->uio_resid = aiov.iov_len;
7666 		uio->uio_segflg = UIO_SYSSPACE;
7667 
7668 		/*
7669 		 * Let physio do the rest...
7670 		 */
7671 		bp->b_forw = (struct buf *)(uintptr_t)com;
7672 		bp->b_back = NULL;
7673 		err = physio(st_strategy, bp, dev, flg, st_minphys, uio);
7674 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7675 		    "st_setup_cmd: physio returns %d\n", err);
7676 	} else {
7677 		/*
7678 		 * Mimic physio
7679 		 */
7680 		bp->b_forw = (struct buf *)(uintptr_t)com;
7681 		bp->b_back = NULL;
7682 		bp->b_edev = dev;
7683 		bp->b_dev = cmpdev(dev);
7684 		bp->b_blkno = 0;
7685 		bp->b_resid = 0;
7686 		(void) st_strategy(bp);
7687 		if (bp->b_flags & B_ASYNC) {
7688 			/*
7689 			 * This is an async command- the caller won't wait
7690 			 * and doesn't care about errors.
7691 			 */
7692 			mutex_enter(ST_MUTEX);
7693 			return (0);
7694 		}
7695 
7696 		/*
7697 		 * BugTraq #4260046
7698 		 * ----------------
7699 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7700 		 * unconditionally. The old comment said...
7701 		 *
7702 		 * "if strategy was flagged with  persistent errors, we would
7703 		 *  have an error here, and the bp would never be sent, so we
7704 		 *  don't want to wait on a bp that was never sent...or hang"
7705 		 *
7706 		 * The new rationale, courtesy of Chitrank...
7707 		 *
7708 		 * "we should unconditionally biowait() here because
7709 		 *  st_strategy() will do a biodone() in the persistent error
7710 		 *  case and the following biowait() will return immediately.
7711 		 *  If not, in the case of "errors after pkt alloc" in
7712 		 *  st_start(), we will not biowait here which will cause the
7713 		 *  next biowait() to return immediately which will cause
7714 		 *  us to send out the next command. In the case where both of
7715 		 *  these use the sbuf, when the first command completes we'll
7716 		 *  free the packet attached to sbuf and the same pkt will
7717 		 *  get freed again when we complete the second command.
7718 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7719 		 *  st_start() for the pkt alloc failure case because physio()
7720 		 *  does biowait() and will hang if we don't do biodone()"
7721 		 */
7722 
7723 		err = biowait(bp);
7724 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7725 		    "st_setup_cmd: biowait returns %d\n", err);
7726 	}
7727 
7728 	mutex_enter(ST_MUTEX);
7729 
7730 	return (err);
7731 }
7732 
7733 static int
7734 st_set_compression(struct scsi_tape *un)
7735 {
7736 	int rval;
7737 	int turn_compression_on;
7738 	minor_t minor;
7739 
7740 	ST_FUNC(ST_DEVINFO, st_set_compression);
7741 
7742 	/*
7743 	 * Drive either dosn't have compression or it is controlled with
7744 	 * special density codes. Return ENOTTY so caller
7745 	 * knows nothing was done.
7746 	 */
7747 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7748 		un->un_comp_page = 0;
7749 		return (ENOTTY);
7750 	}
7751 
7752 	/* set compression based on minor node opened */
7753 	minor = MT_DENSITY(un->un_dev);
7754 
7755 	/*
7756 	 * If this the compression density or
7757 	 * the drive has two densities and uses mode select for
7758 	 * control of compression turn on compression for MT_DENSITY2
7759 	 * as well.
7760 	 */
7761 	if ((minor == ST_COMPRESSION_DENSITY) ||
7762 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7763 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7764 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7765 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7766 
7767 		turn_compression_on = 1;
7768 	} else {
7769 		turn_compression_on = 0;
7770 	}
7771 
7772 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7773 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7774 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7775 
7776 	/*
7777 	 * Need to determine which page does the device use for compression.
7778 	 * First try the data compression page. If this fails try the device
7779 	 * configuration page
7780 	 */
7781 
7782 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7783 		rval = st_set_datacomp_page(un, turn_compression_on);
7784 		if (rval == EALREADY) {
7785 			return (rval);
7786 		}
7787 		if (rval != 0) {
7788 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7789 				/*
7790 				 * This device does not support data
7791 				 * compression page
7792 				 */
7793 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7794 			} else if (un->un_state >= ST_STATE_OPEN) {
7795 				un->un_pos.pmode = invalid;
7796 				rval = EIO;
7797 			} else {
7798 				rval = -1;
7799 			}
7800 		} else {
7801 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7802 		}
7803 	}
7804 
7805 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7806 		rval = st_set_devconfig_page(un, turn_compression_on);
7807 		if (rval == EALREADY) {
7808 			return (rval);
7809 		}
7810 		if (rval != 0) {
7811 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7812 				/*
7813 				 * This device does not support
7814 				 * compression at all advice the
7815 				 * user and unset ST_MODE_SEL_COMP
7816 				 */
7817 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7818 				un->un_comp_page = 0;
7819 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7820 				    "Device Does Not Support Compression\n");
7821 			} else if (un->un_state >= ST_STATE_OPEN) {
7822 				un->un_pos.pmode = invalid;
7823 				rval = EIO;
7824 			} else {
7825 				rval = -1;
7826 			}
7827 		}
7828 	}
7829 
7830 	return (rval);
7831 }
7832 
7833 /*
7834  * set or unset compression thru device configuration page.
7835  */
7836 static int
7837 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
7838 {
7839 	unsigned char cflag;
7840 	int rval = 0;
7841 
7842 
7843 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
7844 
7845 	ASSERT(mutex_owned(ST_MUTEX));
7846 	/*
7847 	 * Figure what to set compression flag to.
7848 	 */
7849 	if (compression_on) {
7850 		/* They have selected a compression node */
7851 		if (un->un_dp->type == ST_TYPE_FUJI) {
7852 			cflag = 0x84;   /* use EDRC */
7853 		} else {
7854 			cflag = ST_DEV_CONFIG_DEF_COMP;
7855 		}
7856 	} else {
7857 		cflag = ST_DEV_CONFIG_NO_COMP;
7858 	}
7859 
7860 	/*
7861 	 * If compression is already set the way it was requested.
7862 	 * And if this not the first time we has tried.
7863 	 */
7864 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
7865 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7866 		return (EALREADY);
7867 	}
7868 
7869 	un->un_mspl->page.dev.comp_alg = cflag;
7870 	/*
7871 	 * need to send mode select even if correct compression is
7872 	 * already set since need to set density code
7873 	 */
7874 
7875 #ifdef STDEBUG
7876 	if ((st_debug & 0x7) >= 6) {
7877 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7878 		    "st_set_devconfig_page: sense data for mode select",
7879 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7880 	}
7881 #endif
7882 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
7883 	    sizeof (struct seq_mode));
7884 
7885 	return (rval);
7886 }
7887 
7888 /*
7889  * set/reset compression bit thru data compression page
7890  */
7891 static int
7892 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
7893 {
7894 	int compression_on_already;
7895 	int rval = 0;
7896 
7897 
7898 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
7899 
7900 	ASSERT(mutex_owned(ST_MUTEX));
7901 	/*
7902 	 * If drive is not capable of compression (at this time)
7903 	 * return EALREADY so caller doesn't think that this page
7904 	 * is not supported. This check is for drives that can
7905 	 * disable compression from the front panel or configuration.
7906 	 * I doubt that a drive that supports this page is not really
7907 	 * capable of compression.
7908 	 */
7909 	if (un->un_mspl->page.comp.dcc == 0) {
7910 		return (EALREADY);
7911 	}
7912 
7913 	/* See if compression currently turned on */
7914 	if (un->un_mspl->page.comp.dce) {
7915 		compression_on_already = 1;
7916 	} else {
7917 		compression_on_already = 0;
7918 	}
7919 
7920 	/*
7921 	 * If compression is already set the way it was requested.
7922 	 * And if this not the first time we has tried.
7923 	 */
7924 	if ((compression_on == compression_on_already) &&
7925 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7926 		return (EALREADY);
7927 	}
7928 
7929 	/*
7930 	 * if we are already set to the appropriate compression
7931 	 * mode, don't set it again
7932 	 */
7933 	if (compression_on) {
7934 		/* compression selected */
7935 		un->un_mspl->page.comp.dce = 1;
7936 	} else {
7937 		un->un_mspl->page.comp.dce = 0;
7938 	}
7939 
7940 
7941 #ifdef STDEBUG
7942 	if ((st_debug & 0x7) >= 6) {
7943 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7944 		    "st_set_datacomp_page: sense data for mode select",
7945 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7946 	}
7947 #endif
7948 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
7949 	    sizeof (struct seq_mode));
7950 
7951 	return (rval);
7952 }
7953 
7954 static int
7955 st_modesense(struct scsi_tape *un)
7956 {
7957 	int rval;
7958 	uchar_t page;
7959 
7960 	ST_FUNC(ST_DEVINFO, st_modesense);
7961 
7962 	page = un->un_comp_page;
7963 
7964 	switch (page) {
7965 	case ST_DEV_DATACOMP_PAGE:
7966 	case ST_DEV_CONFIG_PAGE: /* FALLTHROUGH */
7967 		rval = st_gen_mode_sense(un, st_uscsi_cmd, page, un->un_mspl,
7968 		    sizeof (struct seq_mode));
7969 		break;
7970 
7971 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
7972 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
7973 			page = ST_DEV_CONFIG_PAGE;
7974 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
7975 			    un->un_mspl, sizeof (struct seq_mode));
7976 			if (rval == 0 && un->un_mspl->page_code == page) {
7977 				un->un_comp_page = page;
7978 				break;
7979 			}
7980 			page = ST_DEV_DATACOMP_PAGE;
7981 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
7982 			    un->un_mspl, sizeof (struct seq_mode));
7983 			if (rval == 0 && un->un_mspl->page_code == page) {
7984 				un->un_comp_page = page;
7985 				break;
7986 			}
7987 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
7988 			un->un_comp_page = 0;
7989 		} else {
7990 			un->un_comp_page = 0;
7991 		}
7992 
7993 	default:	/* FALLTHROUGH */
7994 		rval = st_cmd(un, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
7995 	}
7996 	return (rval);
7997 }
7998 
7999 static int
8000 st_modeselect(struct scsi_tape *un)
8001 {
8002 	int rval = 0;
8003 	int ix;
8004 
8005 	ST_FUNC(ST_DEVINFO, st_modeselect);
8006 
8007 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8008 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
8009 	    un->un_dev, un->un_mspl->density);
8010 
8011 	ASSERT(mutex_owned(ST_MUTEX));
8012 
8013 	/*
8014 	 * The parameter list should be the same for all of the
8015 	 * cases that follow so set them here
8016 	 *
8017 	 * Try mode select first if if fails set fields manually
8018 	 */
8019 	rval = st_modesense(un);
8020 	if (rval != 0) {
8021 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8022 		    "st_modeselect: First mode sense failed\n");
8023 		un->un_mspl->bd_len  = 8;
8024 		un->un_mspl->high_nb = 0;
8025 		un->un_mspl->mid_nb  = 0;
8026 		un->un_mspl->low_nb  = 0;
8027 	}
8028 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
8029 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
8030 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
8031 
8032 
8033 	/*
8034 	 * If configured to use a specific density code for a media type.
8035 	 * curdens is previously set by the minor node opened.
8036 	 * If the media type doesn't match the minor node we change it so it
8037 	 * looks like the correct one was opened.
8038 	 */
8039 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
8040 		uchar_t best;
8041 
8042 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
8043 			if (un->un_mspl->media_type ==
8044 			    un->un_dp->mediatype[ix]) {
8045 				best = ix;
8046 				/*
8047 				 * It matches but it might not be the only one.
8048 				 * Use the highest matching media type but not
8049 				 * to exceed the density selected by the open.
8050 				 */
8051 				if (ix < un->un_curdens) {
8052 					continue;
8053 				}
8054 				un->un_curdens = ix;
8055 				break;
8056 			}
8057 		}
8058 		/* If a match was found best will not be 0xff any more */
8059 		if (best < NDENSITIES) {
8060 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8061 			    "found media 0x%X using density 0x%X\n",
8062 			    un->un_mspl->media_type,
8063 			    un->un_dp->densities[best]);
8064 			un->un_mspl->density = un->un_dp->densities[best];
8065 		} else {
8066 			/* Otherwise set density based on minor node opened */
8067 			un->un_mspl->density =
8068 			    un->un_dp->densities[un->un_curdens];
8069 		}
8070 	} else {
8071 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
8072 	}
8073 
8074 	if (un->un_dp->options & ST_NOBUF) {
8075 		un->un_mspl->bufm = 0;
8076 	} else {
8077 		un->un_mspl->bufm = 1;
8078 	}
8079 
8080 	rval = st_set_compression(un);
8081 
8082 	/*
8083 	 * If st_set_compression returned invalid or already it
8084 	 * found no need to do the mode select.
8085 	 * So do it here.
8086 	 */
8087 	if ((rval == ENOTTY) || (rval == EALREADY)) {
8088 
8089 		/* Zero non-writeable fields */
8090 		un->un_mspl->data_len = 0;
8091 		un->un_mspl->media_type = 0;
8092 		un->un_mspl->wp = 0;
8093 
8094 		/* need to set the density code */
8095 		rval = st_cmd(un, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
8096 		if (rval != 0) {
8097 			if (un->un_state >= ST_STATE_OPEN) {
8098 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8099 				    "unable to set tape mode\n");
8100 				un->un_pos.pmode = invalid;
8101 				rval = EIO;
8102 			} else {
8103 				rval = -1;
8104 			}
8105 		}
8106 	}
8107 
8108 	/*
8109 	 * The spec recommends to send a mode sense after a mode select
8110 	 */
8111 	(void) st_modesense(un);
8112 
8113 	ASSERT(mutex_owned(ST_MUTEX));
8114 
8115 	return (rval);
8116 }
8117 
8118 /*
8119  * st_gen_mode_sense
8120  *
8121  * generic mode sense.. it allows for any page
8122  */
8123 static int
8124 st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
8125     struct seq_mode *page_data, int page_size)
8126 {
8127 
8128 	int r;
8129 	char	cdb[CDB_GROUP0];
8130 	struct uscsi_cmd *com;
8131 
8132 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
8133 
8134 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8135 
8136 	bzero(cdb, CDB_GROUP0);
8137 	cdb[0] = SCMD_MODE_SENSE;
8138 	cdb[2] = (char)page;
8139 	cdb[4] = (char)page_size;
8140 
8141 	com->uscsi_cdb = cdb;
8142 	com->uscsi_cdblen = CDB_GROUP0;
8143 	com->uscsi_bufaddr = (caddr_t)page_data;
8144 	com->uscsi_buflen = page_size;
8145 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8146 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8147 
8148 	r = ubf(un, com, FKIOCTL);
8149 	kmem_free(com, sizeof (*com));
8150 	return (r);
8151 }
8152 
8153 /*
8154  * st_gen_mode_select
8155  *
8156  * generic mode select.. it allows for any page
8157  */
8158 static int
8159 st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
8160     struct seq_mode *page_data, int page_size)
8161 {
8162 
8163 	int r;
8164 	char cdb[CDB_GROUP0];
8165 	struct uscsi_cmd *com;
8166 
8167 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
8168 
8169 	/* Zero non-writeable fields */
8170 	page_data->data_len = 0;
8171 	page_data->media_type = 0;
8172 	page_data->wp = 0;
8173 
8174 	/*
8175 	 * If mode select has any page data, zero the ps (Page Savable) bit.
8176 	 */
8177 	if (page_size > MSIZE) {
8178 		page_data->ps = 0;
8179 	}
8180 
8181 
8182 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8183 
8184 	/*
8185 	 * then, do a mode select to set what ever info
8186 	 */
8187 	bzero(cdb, CDB_GROUP0);
8188 	cdb[0] = SCMD_MODE_SELECT;
8189 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
8190 	cdb[4] = (char)page_size;
8191 
8192 	com->uscsi_cdb = cdb;
8193 	com->uscsi_cdblen = CDB_GROUP0;
8194 	com->uscsi_bufaddr = (caddr_t)page_data;
8195 	com->uscsi_buflen = page_size;
8196 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8197 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_WRITE;
8198 
8199 	r = ubf(un, com, FKIOCTL);
8200 
8201 	kmem_free(com, sizeof (*com));
8202 	return (r);
8203 }
8204 
8205 static int
8206 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
8207 {
8208 	int rval;
8209 	char cdb[CDB_GROUP0];
8210 	struct uscsi_cmd *com;
8211 
8212 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
8213 
8214 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8215 
8216 	bzero(cdb, CDB_GROUP0);
8217 	cdb[0] = SCMD_READ_BLKLIM;
8218 
8219 	com->uscsi_cdb = cdb;
8220 	com->uscsi_cdblen = CDB_GROUP0;
8221 	com->uscsi_bufaddr = (caddr_t)read_blk;
8222 	com->uscsi_buflen = sizeof (struct read_blklim);
8223 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8224 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8225 
8226 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8227 	if (com->uscsi_status || com->uscsi_resid) {
8228 		rval = -1;
8229 	}
8230 
8231 	kmem_free(com, sizeof (*com));
8232 	return (rval);
8233 }
8234 
8235 static int
8236 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
8237     size_t buflen)
8238 {
8239 	int rval;
8240 	char cdb[CDB_GROUP1];
8241 	struct uscsi_cmd *com;
8242 
8243 	ST_FUNC(ST_DEVINFO, st_report_density_support);
8244 
8245 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8246 
8247 	bzero(cdb, CDB_GROUP1);
8248 	cdb[0] = SCMD_REPORT_DENSITIES;
8249 	cdb[7] = (buflen & 0xff00) >> 8;
8250 	cdb[8] = buflen & 0xff;
8251 
8252 	com->uscsi_cdb = cdb;
8253 	com->uscsi_cdblen = CDB_GROUP1;
8254 	com->uscsi_bufaddr = (caddr_t)density_data;
8255 	com->uscsi_buflen = buflen;
8256 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8257 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8258 
8259 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8260 	if (com->uscsi_status || com->uscsi_resid) {
8261 		rval = -1;
8262 	}
8263 
8264 	kmem_free(com, sizeof (*com));
8265 	return (rval);
8266 }
8267 
8268 static int
8269 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
8270     uchar_t option_code, ushort_t service_action)
8271 {
8272 	int rval;
8273 	char cdb[CDB_GROUP5];
8274 	struct uscsi_cmd *com;
8275 	uint32_t allo_length;
8276 
8277 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
8278 
8279 	allo_length = sizeof (struct one_com_des) +
8280 	    sizeof (struct com_timeout_des);
8281 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8282 
8283 	bzero(cdb, CDB_GROUP5);
8284 	cdb[0] = (char)SCMD_MAINTENANCE_IN;
8285 	cdb[1] = 0x0c; /* service action */
8286 	if (service_action) {
8287 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
8288 		cdb[4] = (service_action & 0xff00) >> 8;
8289 		cdb[5] = service_action & 0xff;
8290 	} else {
8291 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
8292 		    0x80); /* RCTD */
8293 	}
8294 	cdb[3] = option_code;
8295 	cdb[6] = (allo_length & 0xff000000) >> 24;
8296 	cdb[7] = (allo_length & 0xff0000) >> 16;
8297 	cdb[8] = (allo_length & 0xff00) >> 8;
8298 	cdb[9] = allo_length & 0xff;
8299 
8300 	com->uscsi_cdb = cdb;
8301 	com->uscsi_cdblen = CDB_GROUP5;
8302 	com->uscsi_bufaddr = (caddr_t)oper_data;
8303 	com->uscsi_buflen = allo_length;
8304 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8305 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8306 
8307 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8308 	if (com->uscsi_status) {
8309 		rval = -1;
8310 	}
8311 
8312 	kmem_free(com, sizeof (*com));
8313 	return (rval);
8314 }
8315 
8316 /*
8317  * Changes devices blocksize and bsize to requested blocksize nblksz.
8318  * Returns returned value from first failed call or zero on success.
8319  */
8320 static int
8321 st_change_block_size(struct scsi_tape *un, uint32_t nblksz)
8322 {
8323 	struct seq_mode *current;
8324 	int rval;
8325 	uint32_t oldblksz;
8326 
8327 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8328 
8329 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8330 
8331 	current = kmem_zalloc(MSIZE, KM_SLEEP);
8332 
8333 	/*
8334 	 * If we haven't got the compression page yet, do that first.
8335 	 */
8336 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
8337 		(void) st_modesense(un);
8338 	}
8339 
8340 	/* Read current settings */
8341 	rval = st_gen_mode_sense(un, st_uscsi_cmd, 0, current, MSIZE);
8342 	if (rval != 0) {
8343 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8344 		    "mode sense for change block size failed: rval = %d", rval);
8345 		goto finish;
8346 	}
8347 
8348 	/* Figure the current block size */
8349 	oldblksz =
8350 	    (current->high_bl << 16) |
8351 	    (current->mid_bl << 8) |
8352 	    (current->low_bl);
8353 
8354 	/* If current block size is the same as requested were done */
8355 	if (oldblksz == nblksz) {
8356 		un->un_bsize = nblksz;
8357 		rval = 0;
8358 		goto finish;
8359 	}
8360 
8361 	/* Change to requested block size */
8362 	current->high_bl = (uchar_t)(nblksz >> 16);
8363 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8364 	current->low_bl  = (uchar_t)(nblksz);
8365 
8366 	/* Attempt to change block size */
8367 	rval = st_gen_mode_select(un, st_uscsi_cmd, current, MSIZE);
8368 	if (rval != 0) {
8369 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8370 		    "Set new block size failed: rval = %d", rval);
8371 		goto finish;
8372 	}
8373 
8374 	/* Read back and verify setting */
8375 	rval = st_modesense(un);
8376 	if (rval == 0) {
8377 		un->un_bsize =
8378 		    (un->un_mspl->high_bl << 16) |
8379 		    (un->un_mspl->mid_bl << 8) |
8380 		    (un->un_mspl->low_bl);
8381 
8382 		if (un->un_bsize != nblksz) {
8383 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8384 			    "Blocksize set does not equal requested blocksize"
8385 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8386 			rval = EIO;
8387 		}
8388 	}
8389 finish:
8390 	kmem_free(current, MSIZE);
8391 	return (rval);
8392 }
8393 
8394 
8395 static void
8396 st_init(struct scsi_tape *un)
8397 {
8398 	ST_FUNC(ST_DEVINFO, st_init);
8399 
8400 	ASSERT(mutex_owned(ST_MUTEX));
8401 
8402 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8403 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8404 	    un->un_dev);
8405 
8406 	un->un_pos.blkno = 0;
8407 	un->un_pos.fileno = 0;
8408 	un->un_lastop = ST_OP_NIL;
8409 	un->un_pos.eof = ST_NO_EOF;
8410 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8411 	if (st_error_level != SCSI_ERR_ALL) {
8412 		if (DEBUGGING) {
8413 			st_error_level = SCSI_ERR_ALL;
8414 		} else {
8415 			st_error_level = SCSI_ERR_RETRYABLE;
8416 		}
8417 	}
8418 }
8419 
8420 
8421 static void
8422 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8423 {
8424 	struct scsi_pkt *pkt;
8425 	struct uscsi_cmd *ucmd;
8426 	recov_info *ri;
8427 	int tval = 0;
8428 	uint64_t count;
8429 	uint32_t additional;
8430 	int flags = 0;
8431 	int cdb_len = CDB_GROUP0; /* default */
8432 	uchar_t com;
8433 	char fixbit;
8434 	char short_fm = 0;
8435 	int stat_size =
8436 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
8437 
8438 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8439 
8440 	ASSERT(mutex_owned(ST_MUTEX));
8441 
8442 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8443 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8444 
8445 
8446 	/*
8447 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8448 	 * Length Indicator bits on read/write commands, for setting
8449 	 * the Long bit on erase commands, and for setting the Code
8450 	 * Field bits on space commands.
8451 	 */
8452 
8453 	/* regular raw I/O */
8454 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
8455 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8456 		    CDB_GROUP0, stat_size, st_recov_sz, 0, func,
8457 		    (caddr_t)un);
8458 		if (pkt == NULL) {
8459 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8460 			    "Read Write scsi_init_pkt() failure\n");
8461 			goto exit;
8462 		}
8463 		ASSERT(pkt->pkt_resid == 0);
8464 #ifdef STDEBUG
8465 		bzero(pkt->pkt_private, st_recov_sz);
8466 		bzero(pkt->pkt_scbp, stat_size);
8467 #endif
8468 		ri = (recov_info *)pkt->pkt_private;
8469 		ri->privatelen = st_recov_sz;
8470 		if (un->un_bsize == 0) {
8471 			count = bp->b_bcount;
8472 			fixbit = 0;
8473 		} else {
8474 			count = bp->b_bcount / un->un_bsize;
8475 			fixbit = 1;
8476 		}
8477 		if (bp->b_flags & B_READ) {
8478 			com = SCMD_READ;
8479 			un->un_lastop = ST_OP_READ;
8480 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8481 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8482 				fixbit = 2;
8483 			}
8484 		} else {
8485 			com = SCMD_WRITE;
8486 			un->un_lastop = ST_OP_WRITE;
8487 		}
8488 		tval = un->un_dp->io_timeout;
8489 
8490 		/*
8491 		 * For really large xfers, increase timeout
8492 		 */
8493 		if (bp->b_bcount > (10 * ONE_MEG))
8494 			tval *= bp->b_bcount/(10 * ONE_MEG);
8495 
8496 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8497 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8498 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8499 
8500 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8501 		/*
8502 		 * uscsi - build command, allocate scsi resources
8503 		 */
8504 		st_make_uscsi_cmd(un, ucmd, bp, func);
8505 		goto exit;
8506 
8507 	} else {				/* special I/O */
8508 		struct buf *allocbp = NULL;
8509 		com = (uchar_t)(uintptr_t)bp->b_forw;
8510 		count = bp->b_bcount;
8511 
8512 		switch (com) {
8513 		case SCMD_READ:
8514 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8515 			    "special read %"PRId64"\n", count);
8516 			if (un->un_bsize == 0) {
8517 				fixbit = 2;	/* suppress SILI */
8518 			} else {
8519 				fixbit = 1;	/* Fixed Block Mode */
8520 				count /= un->un_bsize;
8521 			}
8522 			allocbp = bp;
8523 			un->un_lastop = ST_OP_READ;
8524 			tval = un->un_dp->io_timeout;
8525 			break;
8526 
8527 		case SCMD_WRITE:
8528 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8529 			    "special write %"PRId64"\n", count);
8530 			if (un->un_bsize != 0) {
8531 				fixbit = 1;	/* Fixed Block Mode */
8532 				count /= un->un_bsize;
8533 			} else {
8534 				fixbit = 0;
8535 			}
8536 			allocbp = bp;
8537 			un->un_lastop = ST_OP_WRITE;
8538 			tval = un->un_dp->io_timeout;
8539 			break;
8540 
8541 		case SCMD_WRITE_FILE_MARK:
8542 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8543 			    "write %"PRId64" file marks\n", count);
8544 			un->un_lastop = ST_OP_WEOF;
8545 			fixbit = 0;
8546 			tval = un->un_dp->io_timeout;
8547 			/*
8548 			 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8549 			 * device, set the Vendor Unique bit to
8550 			 * write Short File Mark.
8551 			 */
8552 			if ((un->un_dp->options & ST_SHORT_FILEMARKS) &&
8553 			    ((un->un_dp->type == ST_TYPE_EXB8500) ||
8554 			    (un->un_dp->type == ST_TYPE_EXABYTE))) {
8555 				/*
8556 				 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8557 				 * is set to to write Short File Mark
8558 				 */
8559 				short_fm = 1;
8560 			}
8561 			break;
8562 
8563 		case SCMD_REWIND:
8564 			/*
8565 			 * In the case of rewind we're gona do the rewind with
8566 			 * the immediate bit set so status will be retured when
8567 			 * the command is accepted by the device. We clear the
8568 			 * B_ASYNC flag so we wait for that acceptance.
8569 			 */
8570 			if (bp->b_flags & B_ASYNC) {
8571 				allocbp = bp;
8572 				if (count) {
8573 					fixbit = 1;
8574 					bp->b_flags &= ~B_ASYNC;
8575 				}
8576 			} else {
8577 				fixbit = 0;
8578 			}
8579 			count = 0;
8580 			bp->b_bcount = 0;
8581 			un->un_lastop = ST_OP_CTL;
8582 			tval = un->un_dp->rewind_timeout;
8583 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8584 			    "rewind\n");
8585 			break;
8586 
8587 		case SCMD_SPACE_G4:
8588 			cdb_len = CDB_GROUP4;
8589 		case SCMD_SPACE: /* FALL THROUGH */
8590 			fixbit = SPACE_TYPE(bp->b_bcount);
8591 			count = SPACE_CNT(bp->b_bcount);
8592 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8593 			    " %s space %s %"PRId64" from file %d blk %d\n",
8594 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8595 			    space_strs[fixbit & 7], count,
8596 			    un->un_pos.fileno, un->un_pos.blkno);
8597 			additional = count >> 32;
8598 			count &= 0xffffffff;
8599 			un->un_lastop = ST_OP_CTL;
8600 			tval = un->un_dp->space_timeout;
8601 			break;
8602 
8603 		case SCMD_LOAD:
8604 			ASSERT(count < 10);
8605 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8606 			    "%s tape\n", load_strs[count]);
8607 			fixbit = 0;
8608 
8609 			/* Loading or Unloading */
8610 			if (count & LD_LOAD) {
8611 				tval = un->un_dp->load_timeout;
8612 			} else {
8613 				tval = un->un_dp->unload_timeout;
8614 			}
8615 			/* Is Retension requested */
8616 			if (count & LD_RETEN) {
8617 				tval += un->un_dp->rewind_timeout;
8618 			}
8619 			un->un_lastop = ST_OP_CTL;
8620 			break;
8621 
8622 		case SCMD_ERASE:
8623 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8624 			    "erase tape\n");
8625 			ASSERT(count == 1); /* mt sets this */
8626 			if (count == 1) {
8627 				/*
8628 				 * do long erase
8629 				 */
8630 				fixbit = 1; /* Long */
8631 
8632 				/* Drive might not honor immidiate bit */
8633 				tval = un->un_dp->erase_timeout;
8634 			} else {
8635 				/* Short Erase */
8636 				tval = un->un_dp->erase_timeout;
8637 				fixbit = 0;
8638 			}
8639 			un->un_lastop = ST_OP_CTL;
8640 			count = 0;
8641 			break;
8642 
8643 		case SCMD_MODE_SENSE:
8644 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8645 			    "mode sense\n");
8646 			allocbp = bp;
8647 			fixbit = 0;
8648 			tval = un->un_dp->non_motion_timeout;
8649 			un->un_lastop = ST_OP_CTL;
8650 			break;
8651 
8652 		case SCMD_MODE_SELECT:
8653 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8654 			    "mode select\n");
8655 			allocbp = bp;
8656 			fixbit = 0;
8657 			tval = un->un_dp->non_motion_timeout;
8658 			un->un_lastop = ST_OP_CTL;
8659 			break;
8660 
8661 		case SCMD_RESERVE:
8662 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8663 			    "reserve\n");
8664 			fixbit = 0;
8665 			tval = un->un_dp->non_motion_timeout;
8666 			un->un_lastop = ST_OP_CTL;
8667 			break;
8668 
8669 		case SCMD_RELEASE:
8670 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8671 			    "release\n");
8672 			fixbit = 0;
8673 			tval = un->un_dp->non_motion_timeout;
8674 			un->un_lastop = ST_OP_CTL;
8675 			break;
8676 
8677 		case SCMD_READ_BLKLIM:
8678 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8679 			    "read block limits\n");
8680 			allocbp = bp;
8681 			fixbit = count = 0;
8682 			tval = un->un_dp->non_motion_timeout;
8683 			un->un_lastop = ST_OP_CTL;
8684 			break;
8685 
8686 		case SCMD_TEST_UNIT_READY:
8687 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8688 			    "test unit ready\n");
8689 			fixbit = 0;
8690 			tval = un->un_dp->non_motion_timeout;
8691 			un->un_lastop = ST_OP_CTL;
8692 			break;
8693 
8694 		case SCMD_DOORLOCK:
8695 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8696 			    "prevent/allow media removal\n");
8697 			fixbit = 0;
8698 			tval = un->un_dp->non_motion_timeout;
8699 			un->un_lastop = ST_OP_CTL;
8700 			break;
8701 
8702 		case SCMD_READ_POSITION:
8703 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8704 			    "read position\n");
8705 			fixbit = un->un_read_pos_type;
8706 			cdb_len = CDB_GROUP1;
8707 			tval = un->un_dp->non_motion_timeout;
8708 			allocbp = bp;
8709 			un->un_lastop = ST_OP_CTL;
8710 			switch (un->un_read_pos_type) {
8711 			case LONG_POS:
8712 				count = 0;
8713 				break;
8714 			case EXT_POS:
8715 				count = sizeof (tape_position_ext_t);
8716 				break;
8717 			case SHORT_POS:
8718 				count = 0;
8719 				break;
8720 			default:
8721 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8722 				    "Unknown read position type 0x%x in "
8723 				    " st_make_cmd()\n", un->un_read_pos_type);
8724 			}
8725 			break;
8726 
8727 		default:
8728 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8729 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8730 			    com);
8731 		}
8732 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8733 		    st_recov_sz, 0, func, (caddr_t)un);
8734 		if (pkt == NULL) {
8735 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8736 			    "generic command scsi_init_pkt() failure\n");
8737 			goto exit;
8738 		}
8739 
8740 		ASSERT(pkt->pkt_resid == 0);
8741 #ifdef STDEBUG
8742 		bzero(pkt->pkt_private, st_recov_sz);
8743 		bzero(pkt->pkt_scbp, stat_size);
8744 #endif
8745 		ri = (recov_info *)pkt->pkt_private;
8746 		ri->privatelen = st_recov_sz;
8747 		if (allocbp) {
8748 			ASSERT(geterror(allocbp) == 0);
8749 		}
8750 
8751 	}
8752 
8753 
8754 	(void) scsi_setup_cdb((union scsi_cdb *)pkt->pkt_cdbp,
8755 	    com, 0, (uint_t)count, additional);
8756 	FILL_SCSI1_LUN(un->un_sd, pkt);
8757 	/*
8758 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8759 	 */
8760 	((union scsi_cdb *)(pkt->pkt_cdbp))->t_code = fixbit;
8761 	((union scsi_cdb *)pkt->pkt_cdbp)->g0_vu_1 = short_fm;
8762 	pkt->pkt_flags = flags;
8763 
8764 	ASSERT(tval);
8765 	pkt->pkt_time = tval;
8766 	if (bp == un->un_recov_buf) {
8767 		pkt->pkt_comp = st_recov_cb;
8768 	} else {
8769 		pkt->pkt_comp = st_intr;
8770 	}
8771 
8772 	st_add_recovery_info_to_pkt(un, bp, pkt);
8773 
8774 exit:
8775 	ASSERT(mutex_owned(ST_MUTEX));
8776 }
8777 
8778 
8779 /*
8780  * Build a command based on a uscsi command;
8781  */
8782 static void
8783 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
8784     struct buf *bp, int (*func)(caddr_t))
8785 {
8786 	struct scsi_pkt *pkt;
8787 	recov_info *ri;
8788 	caddr_t cdb;
8789 	int	cdblen;
8790 	int	stat_size = 1;
8791 	int	flags = 0;
8792 
8793 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
8794 
8795 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8796 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
8797 
8798 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
8799 		if (un->un_arq_enabled) {
8800 			if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
8801 				stat_size = (int)(ucmd->uscsi_rqlen) +
8802 				    sizeof (struct scsi_arq_status) -
8803 				    sizeof (struct scsi_extended_sense);
8804 				flags = PKT_XARQ;
8805 			} else {
8806 				stat_size = sizeof (struct scsi_arq_status);
8807 			}
8808 		}
8809 	}
8810 
8811 	ASSERT(mutex_owned(ST_MUTEX));
8812 
8813 	cdb = ucmd->uscsi_cdb;
8814 	cdblen = ucmd->uscsi_cdblen;
8815 
8816 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8817 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
8818 	    ucmd->uscsi_buflen, bp->b_bcount);
8819 	pkt = scsi_init_pkt(ROUTE, NULL,
8820 	    (bp->b_bcount > 0) ? bp : NULL,
8821 	    cdblen, stat_size, st_recov_sz, flags, func, (caddr_t)un);
8822 	if (pkt == NULL) {
8823 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8824 		    "uscsi command scsi_init_pkt() failure\n");
8825 		goto exit;
8826 	}
8827 
8828 	ASSERT(pkt->pkt_resid == 0);
8829 #ifdef STDEBUG
8830 	bzero(pkt->pkt_private, st_recov_sz);
8831 	bzero(pkt->pkt_scbp, stat_size);
8832 #endif
8833 	ri = (recov_info *)pkt->pkt_private;
8834 	ri->privatelen = st_recov_sz;
8835 
8836 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
8837 
8838 #ifdef STDEBUG
8839 	if ((st_debug & 0x7) >= 6) {
8840 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8841 		    "pkt_cdbp", (char *)cdb, cdblen);
8842 	}
8843 #endif
8844 
8845 	if (ucmd->uscsi_flags & USCSI_SILENT) {
8846 		pkt->pkt_flags |= FLAG_SILENT;
8847 	}
8848 
8849 	pkt->pkt_time = ucmd->uscsi_timeout;
8850 	if (bp == un->un_recov_buf) {
8851 		pkt->pkt_comp = st_recov_cb;
8852 	} else {
8853 		pkt->pkt_comp = st_intr;
8854 	}
8855 	st_add_recovery_info_to_pkt(un, bp, pkt);
8856 exit:
8857 	ASSERT(mutex_owned(ST_MUTEX));
8858 }
8859 
8860 
8861 /*
8862  * restart cmd currently at the head of the runq
8863  *
8864  * If scsi_transport() succeeds or the retries
8865  * count exhausted, restore the throttle that was
8866  * zeroed out in st_handle_intr_busy().
8867  *
8868  */
8869 static void
8870 st_intr_restart(void *arg)
8871 {
8872 	struct scsi_tape *un = arg;
8873 	struct buf *bp;
8874 	int queued;
8875 	int status = TRAN_ACCEPT;
8876 
8877 	mutex_enter(ST_MUTEX);
8878 
8879 	ST_FUNC(ST_DEVINFO, st_intr_restart);
8880 
8881 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8882 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
8883 
8884 	un->un_hib_tid = 0;
8885 
8886 	if (un->un_recov_buf_busy != 0) {
8887 		bp = un->un_recov_buf;
8888 		queued = 0;
8889 	} else if (un->un_sbuf_busy != 0) {
8890 		bp = un->un_sbufp;
8891 		queued = 0;
8892 	} else if (un->un_quef != NULL) {
8893 		bp = un->un_quef;
8894 		queued = 1;
8895 	} else {
8896 		mutex_exit(ST_MUTEX);
8897 		return;
8898 	}
8899 
8900 	/*
8901 	 * Here we know :
8902 	 *	throttle = 0, via st_handle_intr_busy
8903 	 */
8904 
8905 	if (queued) {
8906 		/*
8907 		 * move from waitq to runq, if there is anything on the waitq
8908 		 */
8909 		(void) st_remove_from_queue(&un->un_quef, &un->un_quef, bp);
8910 
8911 		if (un->un_runqf) {
8912 			/*
8913 			 * not good, we don't want to requeue something after
8914 			 * another.
8915 			 */
8916 			mutex_exit(ST_MUTEX);
8917 			goto done_error;
8918 		} else {
8919 			un->un_runqf = bp;
8920 			un->un_runql = bp;
8921 		}
8922 	}
8923 
8924 	ST_CDB(ST_DEVINFO, "Interrupt restart CDB",
8925 	    (char *)BP_PKT(bp)->pkt_cdbp);
8926 
8927 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
8928 
8929 	status = st_transport(un, BP_PKT(bp));
8930 
8931 	if (status != TRAN_ACCEPT) {
8932 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8933 		mutex_exit(ST_MUTEX);
8934 
8935 		if (status == TRAN_BUSY) {
8936 			if (st_handle_intr_busy(un, bp,
8937 			    ST_TRAN_BUSY_TIMEOUT) == 0)
8938 				return;	/* timeout is setup again */
8939 		}
8940 
8941 	} else {
8942 		un->un_tran_retry_ct = 0;
8943 		if (un->un_last_throttle) {
8944 			un->un_throttle = un->un_last_throttle;
8945 		}
8946 		mutex_exit(ST_MUTEX);
8947 		return;
8948 	}
8949 
8950 done_error:
8951 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8952 	    "restart transport rejected\n");
8953 	bp->b_resid = bp->b_bcount;
8954 
8955 #ifndef __lock_lint
8956 	/*
8957 	 * warlock doesn't understand this potential
8958 	 * recursion?
8959 	 */
8960 	mutex_enter(ST_MUTEX);
8961 	if (un->un_last_throttle) {
8962 		un->un_throttle = un->un_last_throttle;
8963 	}
8964 	if (status != TRAN_ACCEPT)
8965 		ST_DO_ERRSTATS(un, st_transerrs);
8966 	ST_DO_KSTATS(bp, kstat_waitq_exit);
8967 	st_set_pe_flag(un);
8968 	st_bioerror(bp, EIO);
8969 	st_done_and_mutex_exit(un, bp);
8970 #endif
8971 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8972 	    "busy restart aborted\n");
8973 }
8974 
8975 /*
8976  * st_check_media():
8977  * Periodically check the media state using scsi_watch service;
8978  * this service calls back after TUR and possibly request sense
8979  * the callback handler (st_media_watch_cb()) decodes the request sense
8980  * data (if any)
8981  */
8982 
8983 static int
8984 st_check_media(dev_t dev, enum mtio_state state)
8985 {
8986 	int rval = 0;
8987 	enum mtio_state	prev_state;
8988 	opaque_t token = NULL;
8989 
8990 	GET_SOFT_STATE(dev);
8991 
8992 	ST_FUNC(ST_DEVINFO, st_check_media);
8993 
8994 	mutex_enter(ST_MUTEX);
8995 
8996 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8997 	    "st_check_media:state=%x, mediastate=%x\n",
8998 	    state, un->un_mediastate);
8999 
9000 	prev_state = un->un_mediastate;
9001 
9002 	/*
9003 	 * is there anything to do?
9004 	 */
9005 retry:
9006 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
9007 		/*
9008 		 * submit the request to the scsi_watch service;
9009 		 * scsi_media_watch_cb() does the real work
9010 		 */
9011 		mutex_exit(ST_MUTEX);
9012 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
9013 		    st_check_media_time, SENSE_LENGTH,
9014 		    st_media_watch_cb, (caddr_t)dev);
9015 		if (token == NULL) {
9016 			rval = EAGAIN;
9017 			goto done;
9018 		}
9019 		mutex_enter(ST_MUTEX);
9020 
9021 		un->un_swr_token = token;
9022 		un->un_specified_mediastate = state;
9023 
9024 		/*
9025 		 * now wait for media change
9026 		 * we will not be signalled unless mediastate == state but it
9027 		 * still better to test for this condition, since there
9028 		 * is a 5 sec cv_broadcast delay when
9029 		 *  mediastate == MTIO_INSERTED
9030 		 */
9031 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9032 		    "st_check_media:waiting for media state change\n");
9033 		while (un->un_mediastate == state) {
9034 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
9035 				mutex_exit(ST_MUTEX);
9036 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9037 				    "st_check_media:waiting for media state "
9038 				    "was interrupted\n");
9039 				rval = EINTR;
9040 				goto done;
9041 			}
9042 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9043 			    "st_check_media:received signal, state=%x\n",
9044 			    un->un_mediastate);
9045 		}
9046 	}
9047 
9048 	/*
9049 	 * if we transitioned to MTIO_INSERTED, media has really been
9050 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
9051 	 * Reset and retry the state change.  If everything is ok, replay
9052 	 * the open() logic.
9053 	 */
9054 	if ((un->un_mediastate == MTIO_INSERTED) &&
9055 	    (un->un_state == ST_STATE_OFFLINE)) {
9056 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9057 		    "st_check_media: calling st_cmd to confirm inserted\n");
9058 
9059 		/*
9060 		 * set this early so that TUR will make it through strategy
9061 		 * without triggering a st_tape_init().  We needed it set
9062 		 * before calling st_tape_init() ourselves anyway.  If TUR
9063 		 * fails, set it back
9064 		 */
9065 		un->un_state = ST_STATE_INITIALIZING;
9066 
9067 		/*
9068 		 * If not reserved fail as getting reservation conflict
9069 		 * will make this hang forever.
9070 		 */
9071 		if ((un->un_rsvd_status &
9072 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9073 			mutex_exit(ST_MUTEX);
9074 			rval = EACCES;
9075 			goto done;
9076 		}
9077 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
9078 		if (rval == EACCES) {
9079 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9080 			    "st_check_media: TUR got Reservation Conflict\n");
9081 			mutex_exit(ST_MUTEX);
9082 			goto done;
9083 		}
9084 		if (rval) {
9085 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9086 			    "st_check_media: TUR failed, going to retry\n");
9087 			un->un_mediastate = prev_state;
9088 			un->un_state = ST_STATE_OFFLINE;
9089 			goto retry;
9090 		}
9091 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9092 		    "st_check_media: media inserted\n");
9093 
9094 		/* this also rewinds the tape */
9095 		rval = st_tape_init(un);
9096 		if (rval != 0) {
9097 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9098 			    "st_check_media : OFFLINE init failure ");
9099 			un->un_state = ST_STATE_OFFLINE;
9100 			un->un_pos.pmode = invalid;
9101 		} else {
9102 			un->un_state = ST_STATE_OPEN_PENDING_IO;
9103 		}
9104 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
9105 	    (un->un_state != ST_STATE_OFFLINE)) {
9106 		/*
9107 		 * supported devices must be rewound before ejection
9108 		 * rewind resets fileno & blkno
9109 		 */
9110 		un->un_laststate = un->un_state;
9111 		un->un_state = ST_STATE_OFFLINE;
9112 	}
9113 	mutex_exit(ST_MUTEX);
9114 done:
9115 	if (token) {
9116 		(void) scsi_watch_request_terminate(token,
9117 		    SCSI_WATCH_TERMINATE_WAIT);
9118 		mutex_enter(ST_MUTEX);
9119 		un->un_swr_token = (opaque_t)NULL;
9120 		mutex_exit(ST_MUTEX);
9121 	}
9122 
9123 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
9124 
9125 	return (rval);
9126 }
9127 
9128 /*
9129  * st_media_watch_cb() is called by scsi_watch_thread for
9130  * verifying the request sense data (if any)
9131  */
9132 static int
9133 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
9134 {
9135 	struct scsi_status *statusp = resultp->statusp;
9136 	struct scsi_extended_sense *sensep = resultp->sensep;
9137 	uchar_t actual_sense_length = resultp->actual_sense_length;
9138 	struct scsi_tape *un;
9139 	enum mtio_state state = MTIO_NONE;
9140 	int instance;
9141 	dev_t dev = (dev_t)arg;
9142 
9143 	instance = MTUNIT(dev);
9144 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
9145 		return (-1);
9146 	}
9147 
9148 	mutex_enter(ST_MUTEX);
9149 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
9150 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9151 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
9152 	    *((char *)statusp), (void *)sensep,
9153 	    actual_sense_length);
9154 
9155 
9156 	/*
9157 	 * if there was a check condition then sensep points to valid
9158 	 * sense data
9159 	 * if status was not a check condition but a reservation or busy
9160 	 * status then the new state is MTIO_NONE
9161 	 */
9162 	if (sensep) {
9163 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9164 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
9165 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
9166 
9167 		switch (un->un_dp->type) {
9168 		default:
9169 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9170 			    "st_media_watch_cb: unknown drive type %d, "
9171 			    "default to ST_TYPE_HP\n", un->un_dp->type);
9172 		/* FALLTHROUGH */
9173 
9174 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
9175 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
9176 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
9177 			if (un->un_dp->type == ST_TYPE_FUJI) {
9178 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9179 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
9180 			} else {
9181 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9182 				    "st_media_watch_cb: ST_TYPE_HP\n");
9183 			}
9184 			switch (sensep->es_key) {
9185 			case KEY_UNIT_ATTENTION:
9186 				/* not ready to ready transition */
9187 				/* hp/es_qual_code == 80 on>off>on */
9188 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
9189 				if (sensep->es_add_code == 0x28) {
9190 					state = MTIO_INSERTED;
9191 				}
9192 				break;
9193 			case KEY_NOT_READY:
9194 				/* in process, rewinding or loading */
9195 				if ((sensep->es_add_code == 0x04) &&
9196 				    (sensep->es_qual_code == 0x00)) {
9197 					state = MTIO_EJECTED;
9198 				}
9199 				break;
9200 			}
9201 			break;
9202 
9203 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
9204 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9205 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
9206 			switch (sensep->es_key) {
9207 			case KEY_UNIT_ATTENTION:
9208 				/* operator medium removal request */
9209 				if ((sensep->es_add_code == 0x5a) &&
9210 				    (sensep->es_qual_code == 0x01)) {
9211 					state = MTIO_EJECTED;
9212 				/* not ready to ready transition */
9213 				} else if ((sensep->es_add_code == 0x28) &&
9214 				    (sensep->es_qual_code == 0x00)) {
9215 					state = MTIO_INSERTED;
9216 				}
9217 				break;
9218 			case KEY_NOT_READY:
9219 				/* medium not present */
9220 				if (sensep->es_add_code == 0x3a) {
9221 					state = MTIO_EJECTED;
9222 				}
9223 				break;
9224 			}
9225 			break;
9226 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
9227 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9228 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
9229 			switch (sensep->es_key) {
9230 			case KEY_NOT_READY:
9231 				if ((sensep->es_add_code == 0x04) &&
9232 				    (sensep->es_qual_code == 0x00)) {
9233 					/* volume not mounted? */
9234 					state = MTIO_EJECTED;
9235 				} else if (sensep->es_add_code == 0x3a) {
9236 					state = MTIO_EJECTED;
9237 				}
9238 				break;
9239 			case KEY_UNIT_ATTENTION:
9240 				state = MTIO_EJECTED;
9241 				break;
9242 			}
9243 			break;
9244 
9245 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
9246 			switch (sensep->es_key) {
9247 			case KEY_UNIT_ATTENTION:
9248 				if (sensep->es_add_code == 0x28) {
9249 					state = MTIO_INSERTED;
9250 				}
9251 				break;
9252 			case KEY_NOT_READY:
9253 				if (sensep->es_add_code == 0x04) {
9254 					/* in transition but could be either */
9255 					state = un->un_specified_mediastate;
9256 				} else if ((sensep->es_add_code == 0x3a) &&
9257 				    (sensep->es_qual_code == 0x00)) {
9258 					state = MTIO_EJECTED;
9259 				}
9260 				break;
9261 			}
9262 			break;
9263 		}
9264 	} else if (*((char *)statusp) == STATUS_GOOD) {
9265 		state = MTIO_INSERTED;
9266 	}
9267 
9268 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9269 	    "st_media_watch_cb:state=%x, specified=%x\n",
9270 	    state, un->un_specified_mediastate);
9271 
9272 	/*
9273 	 * now signal the waiting thread if this is *not* the specified state;
9274 	 * delay the signal if the state is MTIO_INSERTED
9275 	 * to allow the target to recover
9276 	 */
9277 	if (state != un->un_specified_mediastate) {
9278 		un->un_mediastate = state;
9279 		if (state == MTIO_INSERTED) {
9280 			/*
9281 			 * delay the signal to give the drive a chance
9282 			 * to do what it apparently needs to do
9283 			 */
9284 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9285 			    "st_media_watch_cb:delayed cv_broadcast\n");
9286 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
9287 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
9288 		} else {
9289 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9290 			    "st_media_watch_cb:immediate cv_broadcast\n");
9291 			cv_broadcast(&un->un_state_cv);
9292 		}
9293 	}
9294 	mutex_exit(ST_MUTEX);
9295 	return (0);
9296 }
9297 
9298 /*
9299  * delayed cv_broadcast to allow for target to recover
9300  * from media insertion
9301  */
9302 static void
9303 st_delayed_cv_broadcast(void *arg)
9304 {
9305 	struct scsi_tape *un = arg;
9306 
9307 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
9308 
9309 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9310 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
9311 
9312 	mutex_enter(ST_MUTEX);
9313 	cv_broadcast(&un->un_state_cv);
9314 	mutex_exit(ST_MUTEX);
9315 }
9316 
9317 /*
9318  * restart cmd currently at the start of the waitq
9319  */
9320 static void
9321 st_start_restart(void *arg)
9322 {
9323 	struct scsi_tape *un = arg;
9324 
9325 	ST_FUNC(ST_DEVINFO, st_start_restart);
9326 
9327 	ASSERT(un != NULL);
9328 
9329 	mutex_enter(ST_MUTEX);
9330 
9331 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_tran_restart()\n");
9332 
9333 	st_start(un);
9334 
9335 	mutex_exit(ST_MUTEX);
9336 }
9337 
9338 
9339 /*
9340  * Command completion processing
9341  *
9342  */
9343 static void
9344 st_intr(struct scsi_pkt *pkt)
9345 {
9346 	recov_info *rcv = pkt->pkt_private;
9347 	struct buf *bp = rcv->cmd_bp;
9348 	struct scsi_tape *un;
9349 	errstate action = COMMAND_DONE;
9350 	clock_t	timout;
9351 	int	status;
9352 
9353 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
9354 
9355 	ST_FUNC(ST_DEVINFO, st_intr);
9356 
9357 	ASSERT(un != NULL);
9358 
9359 	mutex_enter(ST_MUTEX);
9360 
9361 	ASSERT(bp != un->un_recov_buf);
9362 
9363 	un->un_rqs_state &= ~(ST_RQS_ERROR);
9364 
9365 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
9366 
9367 	if (pkt->pkt_reason != CMD_CMPLT) {
9368 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9369 		    "Unhappy packet status reason = %s statistics = 0x%x\n",
9370 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9371 
9372 		/* If device has gone away not much else to do */
9373 		if (pkt->pkt_reason == CMD_DEV_GONE) {
9374 			action = COMMAND_DONE_ERROR;
9375 		} else if ((pkt == un->un_rqs) ||
9376 		    (un->un_state == ST_STATE_SENSING)) {
9377 			ASSERT(pkt == un->un_rqs);
9378 			ASSERT(un->un_state == ST_STATE_SENSING);
9379 			un->un_state = un->un_laststate;
9380 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp =
9381 			    un->un_rqs_bp;
9382 			ST_DO_ERRSTATS(un, st_transerrs);
9383 			action = COMMAND_DONE_ERROR;
9384 		} else {
9385 			action = st_handle_incomplete(un, bp);
9386 		}
9387 	/*
9388 	 * At this point we know that the command was successfully
9389 	 * completed. Now what?
9390 	 */
9391 	} else if ((pkt == un->un_rqs) || (un->un_state == ST_STATE_SENSING)) {
9392 		/*
9393 		 * okay. We were running a REQUEST SENSE. Find
9394 		 * out what to do next.
9395 		 */
9396 		ASSERT(pkt == un->un_rqs);
9397 		ASSERT(un->un_state == ST_STATE_SENSING);
9398 		scsi_sync_pkt(pkt);
9399 		action = st_handle_sense(un, bp, &un->un_pos);
9400 		/*
9401 		 * Make rqs isn't going to be retied.
9402 		 */
9403 		if (action != QUE_BUSY_COMMAND && action != QUE_COMMAND) {
9404 			/*
9405 			 * set pkt back to original packet in case we will have
9406 			 * to requeue it
9407 			 */
9408 			pkt = BP_PKT(bp);
9409 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp =
9410 			    un->un_rqs_bp;
9411 			/*
9412 			 * some actions are based on un_state, hence
9413 			 * restore the state st was in before ST_STATE_SENSING.
9414 			 */
9415 			un->un_state = un->un_laststate;
9416 		}
9417 
9418 	} else if (un->un_arq_enabled && (pkt->pkt_state & STATE_ARQ_DONE)) {
9419 		/*
9420 		 * the transport layer successfully completed an autorqsense
9421 		 */
9422 		action = st_handle_autosense(un, bp, &un->un_pos);
9423 
9424 	} else  if ((SCBP(pkt)->sts_busy) ||
9425 	    (SCBP(pkt)->sts_chk) ||
9426 	    (SCBP(pkt)->sts_vu7)) {
9427 		/*
9428 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9429 		 * to see if the status bits we're okay. If a request sense
9430 		 * is to be run, that will happen.
9431 		 */
9432 		action = st_check_error(un, pkt);
9433 	}
9434 
9435 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9436 		switch (action) {
9437 			case QUE_COMMAND:
9438 				/*
9439 				 * return cmd to head to the queue
9440 				 * since we are suspending so that
9441 				 * it gets restarted during resume
9442 				 */
9443 				st_add_to_queue(&un->un_runqf, &un->un_runql,
9444 				    un->un_runqf, bp);
9445 
9446 				action = JUST_RETURN;
9447 				break;
9448 
9449 			case QUE_SENSE:
9450 				action = COMMAND_DONE_ERROR;
9451 				break;
9452 
9453 			default:
9454 				break;
9455 		}
9456 	}
9457 
9458 	/*
9459 	 * Restore old state if we were sensing.
9460 	 */
9461 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9462 		un->un_state = un->un_laststate;
9463 	}
9464 
9465 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9466 	    "st_intr: pkt=%p, bp=%p, action=%x, status=%x\n",
9467 	    (void *)pkt, (void *)bp, action, SCBP_C(pkt));
9468 
9469 again:
9470 	switch (action) {
9471 	case COMMAND_DONE_EACCES:
9472 		/* this is to report a reservation conflict */
9473 		st_bioerror(bp, EACCES);
9474 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9475 		    "Reservation Conflict \n");
9476 		un->un_pos.pmode = invalid;
9477 
9478 		/*FALLTHROUGH*/
9479 	case COMMAND_DONE_ERROR:
9480 		if (un->un_pos.eof < ST_EOT_PENDING &&
9481 		    un->un_state >= ST_STATE_OPEN) {
9482 			/*
9483 			 * all errors set state of the tape to 'unknown'
9484 			 * unless we're at EOT or are doing append testing.
9485 			 * If sense key was illegal request, preserve state.
9486 			 */
9487 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9488 				un->un_pos.pmode = invalid;
9489 			}
9490 		}
9491 
9492 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9493 		/*
9494 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9495 		 * make sure an error ocurrs, so make sure at least EIO is
9496 		 * returned
9497 		 */
9498 		if (geterror(bp) == 0)
9499 			st_bioerror(bp, EIO);
9500 
9501 		st_set_pe_flag(un);
9502 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9503 		    (un->un_errno == EIO)) {
9504 			un->un_rqs_state &= ~(ST_RQS_VALID);
9505 		}
9506 		break;
9507 
9508 	case COMMAND_DONE_ERROR_RECOVERED:
9509 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9510 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9511 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9512 		if (geterror(bp) == 0) {
9513 			st_bioerror(bp, EIO);
9514 		}
9515 		st_set_pe_flag(un);
9516 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9517 		    (un->un_errno == EIO)) {
9518 			un->un_rqs_state &= ~(ST_RQS_VALID);
9519 		}
9520 		/*FALLTHROUGH*/
9521 	case COMMAND_DONE:
9522 		st_set_state(un, bp);
9523 		break;
9524 
9525 	case QUE_SENSE:
9526 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9527 			goto sense_error;
9528 
9529 		if (un->un_state != ST_STATE_SENSING) {
9530 			un->un_laststate = un->un_state;
9531 			un->un_state = ST_STATE_SENSING;
9532 		}
9533 
9534 		/*
9535 		 * zero the sense data.
9536 		 */
9537 		bzero(un->un_rqs->pkt_scbp, SENSE_LENGTH);
9538 
9539 		/*
9540 		 * If this is not a retry on QUE_SENSE point to the original
9541 		 * bp of the command that got us here.
9542 		 */
9543 		if (pkt != un->un_rqs) {
9544 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp = bp;
9545 		}
9546 
9547 		if (un->un_throttle) {
9548 			un->un_last_throttle = un->un_throttle;
9549 			un->un_throttle = 0;
9550 		}
9551 
9552 		ST_CDB(ST_DEVINFO, "Queue sense CDB",
9553 		    (char *)BP_PKT(bp)->pkt_cdbp);
9554 
9555 		/*
9556 		 * never retry this, some other command will have nuked the
9557 		 * sense, anyway
9558 		 */
9559 		status = st_transport(un, un->un_rqs);
9560 
9561 		if (un->un_last_throttle) {
9562 			un->un_throttle = un->un_last_throttle;
9563 		}
9564 
9565 		if (status == TRAN_ACCEPT) {
9566 			mutex_exit(ST_MUTEX);
9567 			return;
9568 		}
9569 		if (status != TRAN_BUSY)
9570 			ST_DO_ERRSTATS(un, st_transerrs);
9571 sense_error:
9572 		un->un_pos.pmode = invalid;
9573 		st_bioerror(bp, EIO);
9574 		st_set_pe_flag(un);
9575 		break;
9576 
9577 	case QUE_BUSY_COMMAND:
9578 		/* longish timeout */
9579 		timout = ST_STATUS_BUSY_TIMEOUT;
9580 		goto que_it_up;
9581 
9582 	case QUE_COMMAND:
9583 		/* short timeout */
9584 		timout = ST_TRAN_BUSY_TIMEOUT;
9585 que_it_up:
9586 		/*
9587 		 * let st_handle_intr_busy put this bp back on waitq and make
9588 		 * checks to see if it is ok to requeue the command.
9589 		 */
9590 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9591 
9592 		/*
9593 		 * Save the throttle before setting up the timeout
9594 		 */
9595 		if (un->un_throttle) {
9596 			un->un_last_throttle = un->un_throttle;
9597 		}
9598 		mutex_exit(ST_MUTEX);
9599 		if (st_handle_intr_busy(un, bp, timout) == 0)
9600 			return;		/* timeout is setup again */
9601 
9602 		mutex_enter(ST_MUTEX);
9603 		un->un_pos.pmode = invalid;
9604 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9605 		st_bioerror(bp, EIO);
9606 		st_set_pe_flag(un);
9607 		break;
9608 
9609 	case QUE_LAST_COMMAND:
9610 
9611 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9612 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9613 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9614 			goto last_command_error;
9615 		}
9616 		mutex_exit(ST_MUTEX);
9617 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9618 			return;
9619 		mutex_enter(ST_MUTEX);
9620 last_command_error:
9621 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9622 		un->un_pos.pmode = invalid;
9623 		st_bioerror(bp, EIO);
9624 		st_set_pe_flag(un);
9625 		break;
9626 
9627 	case COMMAND_TIMEOUT:
9628 	case DEVICE_RESET:
9629 	case DEVICE_TAMPER:
9630 	case ATTEMPT_RETRY:
9631 		action = st_command_recovery(un, pkt, action);
9632 		goto again;
9633 
9634 	default:
9635 		ASSERT(0);
9636 		/* FALLTHRU */
9637 	case JUST_RETURN:
9638 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9639 		mutex_exit(ST_MUTEX);
9640 		return;
9641 	}
9642 
9643 	ST_DO_KSTATS(bp, kstat_runq_exit);
9644 	st_done_and_mutex_exit(un, bp);
9645 }
9646 
9647 static errstate
9648 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9649 {
9650 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9651 	recov_info *rinfo;
9652 	errstate rval = COMMAND_DONE_ERROR;
9653 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9654 	    un->un_rqs : BP_PKT(bp);
9655 	int result;
9656 
9657 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9658 
9659 	rinfo = (recov_info *)pkt->pkt_private;
9660 
9661 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9662 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9663 
9664 	ASSERT(mutex_owned(ST_MUTEX));
9665 
9666 	switch (pkt->pkt_reason) {
9667 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9668 		/*
9669 		 * this occurs when accessing a powered down drive, no
9670 		 * need to complain; just fail the open
9671 		 */
9672 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9673 
9674 		/*
9675 		 * if we have commands outstanding in HBA, and a command
9676 		 * comes back incomplete, we're hosed, so reset target
9677 		 * If we have the bus, but cmd_incomplete, we probably just
9678 		 * have a failed selection, so don't reset the target, just
9679 		 * requeue the command and try again
9680 		 */
9681 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9682 			goto reset_target;
9683 		}
9684 
9685 		/*
9686 		 * Retry selection a couple more times if we're
9687 		 * open.  If opening, we only try just once to
9688 		 * reduce probe time for nonexistant devices.
9689 		 */
9690 		if ((un->un_laststate > ST_STATE_OPENING) &&
9691 		    ((int)un->un_retry_ct < st_selection_retry_count)) {
9692 /* XXX check retriable? */
9693 			rval = QUE_COMMAND;
9694 		}
9695 		ST_DO_ERRSTATS(un, st_transerrs);
9696 		break;
9697 
9698 	case CMD_ABORTED:
9699 		/*
9700 		 * most likely this is caused by flush-on-error support. If
9701 		 * it was not there, the we're in trouble.
9702 		 */
9703 		if (!un->un_flush_on_errors) {
9704 			un->un_status = SUN_KEY_FATAL;
9705 			goto reset_target;
9706 		}
9707 
9708 		st_set_pe_errno(un);
9709 		bioerror(bp, un->un_errno);
9710 		if (un->un_errno)
9711 			return (COMMAND_DONE_ERROR);
9712 		else
9713 			return (COMMAND_DONE);
9714 
9715 	case CMD_TIMEOUT:	/* Command timed out */
9716 		un->un_status = SUN_KEY_TIMEOUT;
9717 		return (COMMAND_TIMEOUT);
9718 
9719 	case CMD_TRAN_ERR:
9720 	case CMD_RESET:
9721 		if (pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET)) {
9722 			if ((un->un_rsvd_status &
9723 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
9724 			    ST_RESERVE) {
9725 				un->un_rsvd_status |= ST_LOST_RESERVE;
9726 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
9727 				    "Lost Reservation\n");
9728 			}
9729 			rval = DEVICE_RESET;
9730 			return (rval);
9731 		}
9732 		if (pkt->pkt_statistics & (STAT_ABORTED | STAT_TERMINATED)) {
9733 			rval = DEVICE_RESET;
9734 			return (rval);
9735 		}
9736 		/*FALLTHROUGH*/
9737 	default:
9738 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9739 		    "Unhandled packet status reason = %s statistics = 0x%x\n",
9740 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9741 reset_target:
9742 
9743 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9744 		    "transport completed with %s\n",
9745 		    scsi_rname(pkt->pkt_reason));
9746 		ST_DO_ERRSTATS(un, st_transerrs);
9747 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
9748 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
9749 		    STAT_ABORTED)) == 0)) {
9750 
9751 			/*
9752 			 * If we haven't reserved the drive don't reset it.
9753 			 */
9754 			if ((un->un_rsvd_status &
9755 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9756 				return (rval);
9757 			}
9758 
9759 			/*
9760 			 * if we aren't lost yet we will be soon.
9761 			 */
9762 			un->un_pos.pmode = invalid;
9763 
9764 			result = st_reset(un, RESET_LUN);
9765 
9766 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
9767 				/* no hope left to recover */
9768 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
9769 				    "recovery by resets failed\n");
9770 				return (rval);
9771 			}
9772 		}
9773 	}
9774 
9775 
9776 	if ((int)un->un_retry_ct++ < st_retry_count) {
9777 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9778 			rval = QUE_COMMAND;
9779 		} else if (bp == un->un_sbufp) {
9780 			if (rinfo->privatelen == sizeof (recov_info)) {
9781 				if (rinfo->cmd_attrib->retriable) {
9782 					/*
9783 					 * These commands can be rerun
9784 					 * with impunity
9785 					 */
9786 					rval = QUE_COMMAND;
9787 				}
9788 			} else {
9789 				cmd_attribute const *attrib;
9790 				attrib =
9791 				    st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
9792 				if (attrib->retriable) {
9793 					rval = QUE_COMMAND;
9794 				}
9795 			}
9796 		}
9797 	} else {
9798 		rval = COMMAND_DONE_ERROR;
9799 	}
9800 
9801 	if (un->un_state >= ST_STATE_OPEN) {
9802 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9803 		    fail, scsi_rname(pkt->pkt_reason),
9804 		    (rval == COMMAND_DONE_ERROR)?
9805 		    "giving up" : "retrying command");
9806 	}
9807 	return (rval);
9808 }
9809 
9810 /*
9811  * if the device is busy, then put this bp back on the waitq, on the
9812  * interrupt thread, where we want the head of the queue and not the
9813  * end
9814  *
9815  * The callers of this routine should take measures to save the
9816  * un_throttle in un_last_throttle which will be restored in
9817  * st_intr_restart(). The only exception should be st_intr_restart()
9818  * calling this routine for which the saving is already done.
9819  */
9820 static int
9821 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
9822 	clock_t timeout_interval)
9823 {
9824 
9825 	int queued;
9826 	int rval = 0;
9827 
9828 	mutex_enter(ST_MUTEX);
9829 
9830 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
9831 
9832 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9833 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
9834 
9835 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
9836 		queued = 1;
9837 	} else {
9838 		queued = 0;
9839 	}
9840 
9841 	/*
9842 	 * Check to see if we hit the retry timeout. We check to make sure
9843 	 * this is the first one on the runq and make sure we have not
9844 	 * queued up any more, so this one has to be the last on the list
9845 	 * also. If it is not, we have to fail.  If it is not the first, but
9846 	 * is the last we are in trouble anyway, as we are in the interrupt
9847 	 * context here.
9848 	 */
9849 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
9850 	    ((un->un_runqf != bp) && (un->un_runql != bp) && (queued))) {
9851 		rval = -1;
9852 		goto exit;
9853 	}
9854 
9855 	/* put the bp back on the waitq */
9856 	if (queued) {
9857 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
9858 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
9859 	}
9860 
9861 	/*
9862 	 * We don't want any other commands being started in the mean time.
9863 	 * If start had just released mutex after putting something on the
9864 	 * runq, we won't even get here.
9865 	 */
9866 	un->un_throttle = 0;
9867 
9868 	/*
9869 	 * send a marker pkt, if appropriate
9870 	 */
9871 	st_hba_unflush(un);
9872 
9873 	/*
9874 	 * all queues are aligned, we are just waiting to
9875 	 * transport
9876 	 */
9877 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
9878 
9879 exit:
9880 	mutex_exit(ST_MUTEX);
9881 	return (rval);
9882 }
9883 
9884 /*
9885  * To get one error entry from error stack
9886  */
9887 static int
9888 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
9889 {
9890 #ifdef _MULTI_DATAMODEL
9891 	/*
9892 	 * For use when a 32 bit app makes a call into a
9893 	 * 64 bit ioctl
9894 	 */
9895 	struct mterror_entry32 err_entry32;
9896 #endif /* _MULTI_DATAMODEL */
9897 
9898 	int rval = 0;
9899 	struct mterror_entry err_entry;
9900 	struct mterror_entry_stack *err_link_entry_p;
9901 	size_t arq_status_len_in, arq_status_len_kr;
9902 
9903 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
9904 
9905 	ASSERT(mutex_owned(ST_MUTEX));
9906 
9907 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9908 	    "st_get_error_entry()\n");
9909 
9910 	/*
9911 	 * if error record stack empty, return ENXIO
9912 	 */
9913 	if (un->un_error_entry_stk == NULL) {
9914 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9915 		    "st_get_error_entry: Error Entry Stack Empty!\n");
9916 		rval = ENXIO;
9917 		goto ret;
9918 	}
9919 
9920 	/*
9921 	 * get the top entry from stack
9922 	 */
9923 	err_link_entry_p = un->un_error_entry_stk;
9924 	arq_status_len_kr =
9925 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
9926 
9927 #ifdef _MULTI_DATAMODEL
9928 	switch (ddi_model_convert_from(flag & FMODELS)) {
9929 	case DDI_MODEL_ILP32:
9930 		if (ddi_copyin((void *)arg, &err_entry32,
9931 		    MTERROR_ENTRY_SIZE_32, flag)) {
9932 			rval = EFAULT;
9933 			goto ret;
9934 		}
9935 
9936 		arq_status_len_in =
9937 		    (size_t)err_entry32.mtee_arq_status_len;
9938 
9939 		err_entry32.mtee_cdb_len =
9940 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
9941 
9942 		if (arq_status_len_in > arq_status_len_kr)
9943 			err_entry32.mtee_arq_status_len =
9944 			    (size32_t)arq_status_len_kr;
9945 
9946 		if (ddi_copyout(
9947 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
9948 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
9949 		    err_entry32.mtee_cdb_len, flag)) {
9950 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9951 			    "st_get_error_entry: Copy cdb buffer error!");
9952 			rval = EFAULT;
9953 		}
9954 
9955 		if (ddi_copyout(
9956 		    err_link_entry_p->mtees_entry.mtee_arq_status,
9957 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
9958 		    err_entry32.mtee_arq_status_len, flag)) {
9959 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9960 			    "st_get_error_entry: copy arq status error!");
9961 			rval = EFAULT;
9962 		}
9963 
9964 		if (ddi_copyout(&err_entry32, (void *)arg,
9965 		    MTERROR_ENTRY_SIZE_32, flag)) {
9966 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9967 			    "st_get_error_entry: copy arq status out error!");
9968 			rval = EFAULT;
9969 		}
9970 		break;
9971 
9972 	case DDI_MODEL_NONE:
9973 		if (ddi_copyin((void *)arg, &err_entry,
9974 		    MTERROR_ENTRY_SIZE_64, flag)) {
9975 			rval = EFAULT;
9976 			goto ret;
9977 		}
9978 		arq_status_len_in = err_entry.mtee_arq_status_len;
9979 
9980 		err_entry.mtee_cdb_len =
9981 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
9982 
9983 		if (arq_status_len_in > arq_status_len_kr)
9984 			err_entry.mtee_arq_status_len =
9985 			    arq_status_len_kr;
9986 
9987 		if (ddi_copyout(
9988 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
9989 		    err_entry.mtee_cdb_buf,
9990 		    err_entry.mtee_cdb_len, flag)) {
9991 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9992 			    "st_get_error_entry: Copy cdb buffer error!");
9993 			rval = EFAULT;
9994 		}
9995 
9996 		if (ddi_copyout(
9997 		    err_link_entry_p->mtees_entry.mtee_arq_status,
9998 		    err_entry.mtee_arq_status,
9999 		    err_entry.mtee_arq_status_len, flag)) {
10000 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10001 			    "st_get_error_entry: copy arq status error!");
10002 			rval = EFAULT;
10003 		}
10004 
10005 		if (ddi_copyout(&err_entry, (void *)arg,
10006 		    MTERROR_ENTRY_SIZE_64, flag)) {
10007 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10008 			    "st_get_error_entry: copy arq status out error!");
10009 			rval = EFAULT;
10010 		}
10011 		break;
10012 	}
10013 #else /* _MULTI_DATAMODEL */
10014 	if (ddi_copyin((void *)arg, &err_entry,
10015 	    MTERROR_ENTRY_SIZE_64, flag)) {
10016 		rval = EFAULT;
10017 		goto ret;
10018 	}
10019 	arq_status_len_in = err_entry.mtee_arq_status_len;
10020 
10021 	err_entry.mtee_cdb_len =
10022 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
10023 
10024 	if (arq_status_len_in > arq_status_len_kr)
10025 		err_entry.mtee_arq_status_len =
10026 		    arq_status_len_kr;
10027 
10028 	if (ddi_copyout(
10029 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10030 	    err_entry.mtee_cdb_buf,
10031 	    err_entry.mtee_cdb_len, flag)) {
10032 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10033 		    "st_get_error_entry: Copy cdb buffer error!");
10034 		rval = EFAULT;
10035 	}
10036 
10037 	if (ddi_copyout(
10038 	    err_link_entry_p->mtees_entry.mtee_arq_status,
10039 	    err_entry.mtee_arq_status,
10040 	    err_entry.mtee_arq_status_len, flag)) {
10041 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10042 		    "st_get_error_entry: copy arq status buffer error!");
10043 		rval = EFAULT;
10044 	}
10045 
10046 	if (ddi_copyout(&err_entry, (void *)arg,
10047 	    MTERROR_ENTRY_SIZE_64, flag)) {
10048 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10049 		    "st_get_error_entry: copy arq status out error!");
10050 		rval = EFAULT;
10051 	}
10052 #endif /* _MULTI_DATAMODEL */
10053 
10054 	/*
10055 	 * update stack
10056 	 */
10057 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
10058 
10059 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
10060 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
10061 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
10062 
10063 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
10064 	    SECMDS_STATUS_SIZE);
10065 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
10066 
10067 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
10068 	err_link_entry_p = NULL;
10069 ret:
10070 	return (rval);
10071 }
10072 
10073 /*
10074  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
10075  * the scsi CDB command which causes the error and generates sense data and
10076  * the scsi status.
10077  *
10078  *      error-record stack
10079  *
10080  *
10081  *             TOP                                     BOTTOM
10082  *              ------------------------------------------
10083  *              |   0   |   1   |   2   |   ...  |   n   |
10084  *              ------------------------------------------
10085  *                  ^
10086  *                  |
10087  *       pointer to error entry
10088  *
10089  * when st driver generates one sense data record, it creates a error-entry
10090  * and pushes it onto the stack.
10091  *
10092  */
10093 
10094 static void
10095 st_update_error_stack(struct scsi_tape *un,
10096 			struct scsi_pkt *pkt,
10097 			struct scsi_arq_status *cmd)
10098 {
10099 	struct mterror_entry_stack *err_entry_tmp;
10100 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
10101 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
10102 
10103 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
10104 
10105 	ASSERT(mutex_owned(ST_MUTEX));
10106 
10107 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10108 	    "st_update_error_stack()\n");
10109 
10110 	ASSERT(cmd);
10111 	ASSERT(cdbp);
10112 	if (cdblen == 0) {
10113 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10114 		    "st_update_error_stack: CDB length error!\n");
10115 		return;
10116 	}
10117 
10118 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
10119 	ASSERT(err_entry_tmp != NULL);
10120 
10121 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
10122 	    kmem_alloc(cdblen, KM_SLEEP);
10123 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
10124 
10125 	err_entry_tmp->mtees_entry.mtee_arq_status =
10126 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
10127 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
10128 
10129 	/*
10130 	 * copy cdb command & length to current error entry
10131 	 */
10132 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
10133 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
10134 
10135 	/*
10136 	 * copy scsi status length to current error entry
10137 	 */
10138 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
10139 	    SECMDS_STATUS_SIZE;
10140 
10141 	/*
10142 	 * copy sense data and scsi status to current error entry
10143 	 */
10144 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
10145 	    SECMDS_STATUS_SIZE);
10146 
10147 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
10148 	un->un_error_entry_stk = err_entry_tmp;
10149 
10150 }
10151 
10152 /*
10153  * Empty all the error entry in stack
10154  */
10155 static void
10156 st_empty_error_stack(struct scsi_tape *un)
10157 {
10158 	struct mterror_entry_stack *linkp;
10159 
10160 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
10161 
10162 	ASSERT(mutex_owned(ST_MUTEX));
10163 
10164 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10165 	    "st_empty_entry_stack()\n");
10166 
10167 	while (un->un_error_entry_stk != NULL) {
10168 		linkp = un->un_error_entry_stk;
10169 		un->un_error_entry_stk =
10170 		    un->un_error_entry_stk->mtees_nextp;
10171 
10172 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
10173 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
10174 			    linkp->mtees_entry.mtee_cdb_len);
10175 
10176 		if (linkp->mtees_entry.mtee_arq_status != NULL)
10177 			kmem_free(linkp->mtees_entry.mtee_arq_status,
10178 			    linkp->mtees_entry.mtee_arq_status_len);
10179 
10180 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
10181 		linkp = NULL;
10182 	}
10183 }
10184 
10185 static errstate
10186 st_handle_sense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10187 {
10188 	struct scsi_pkt *pkt = BP_PKT(bp);
10189 	struct scsi_pkt *rqpkt = un->un_rqs;
10190 	struct scsi_arq_status arqstat;
10191 
10192 	errstate rval = COMMAND_DONE_ERROR;
10193 	int amt;
10194 
10195 	ST_FUNC(ST_DEVINFO, st_handle_sense);
10196 
10197 	ASSERT(mutex_owned(ST_MUTEX));
10198 
10199 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10200 	    "st_handle_sense()\n");
10201 
10202 	if (SCBP(rqpkt)->sts_busy) {
10203 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10204 		    "busy unit on request sense\n");
10205 		if ((int)un->un_retry_ct++ < st_retry_count) {
10206 			rval = QUE_BUSY_COMMAND;
10207 		}
10208 		return (rval);
10209 	} else if (SCBP(rqpkt)->sts_chk) {
10210 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10211 		    "Check Condition on REQUEST SENSE\n");
10212 		return (rval);
10213 	}
10214 
10215 	/* was there enough data? */
10216 	amt = (int)MAX_SENSE_LENGTH - rqpkt->pkt_resid;
10217 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
10218 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10219 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10220 		    "REQUEST SENSE couldn't get sense data\n");
10221 		return (rval);
10222 	}
10223 
10224 	bcopy(SCBP(pkt), &arqstat.sts_status,
10225 	    sizeof (struct scsi_status));
10226 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
10227 	    sizeof (struct scsi_status));
10228 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
10229 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
10230 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
10231 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
10232 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
10233 
10234 	/*
10235 	 * copy one arqstat entry in the sense data buffer
10236 	 */
10237 	st_update_error_stack(un, pkt, &arqstat);
10238 	return (st_decode_sense(un, bp, amt, SCBP(rqpkt), pos));
10239 }
10240 
10241 static errstate
10242 st_handle_autosense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10243 {
10244 	struct scsi_pkt *pkt = BP_PKT(bp);
10245 	struct scsi_arq_status *arqstat =
10246 	    (struct scsi_arq_status *)pkt->pkt_scbp;
10247 	errstate rval = COMMAND_DONE_ERROR;
10248 	int amt;
10249 
10250 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
10251 
10252 	ASSERT(mutex_owned(ST_MUTEX));
10253 
10254 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10255 	    "st_handle_autosense()\n");
10256 
10257 	if (arqstat->sts_rqpkt_status.sts_busy) {
10258 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10259 		    "busy unit on request sense\n");
10260 		/*
10261 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
10262 		 * the disadvantage is that we do not have any delay for the
10263 		 * second retry of rqsense and we have to keep a packet around
10264 		 */
10265 		return (QUE_SENSE);
10266 
10267 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
10268 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10269 		    "transport error on REQUEST SENSE\n");
10270 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
10271 		    ((arqstat->sts_rqpkt_statistics &
10272 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
10273 			if (st_reset(un, RESET_LUN) == 0) {
10274 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10275 				    "recovery by resets failed\n");
10276 			}
10277 		}
10278 		return (rval);
10279 
10280 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
10281 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10282 		    "Check Condition on REQUEST SENSE\n");
10283 		return (rval);
10284 	}
10285 
10286 
10287 	/* was there enough data? */
10288 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10289 		amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10290 	} else {
10291 		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
10292 			amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10293 		} else {
10294 			amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10295 		}
10296 	}
10297 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
10298 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10299 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10300 		    "REQUEST SENSE couldn't get sense data\n");
10301 		return (rval);
10302 	}
10303 
10304 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10305 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, MAX_SENSE_LENGTH);
10306 	} else {
10307 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
10308 	}
10309 
10310 	/*
10311 	 * copy one arqstat entry in the sense data buffer
10312 	 */
10313 	st_update_error_stack(un, pkt, arqstat);
10314 
10315 	return (st_decode_sense(un, bp, amt, &arqstat->sts_rqpkt_status, pos));
10316 }
10317 
10318 static errstate
10319 st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
10320     struct scsi_status *statusp, tapepos_t *pos)
10321 {
10322 	struct scsi_pkt *pkt = BP_PKT(bp);
10323 	recov_info *ri = (recov_info *)pkt->pkt_private;
10324 	errstate rval = COMMAND_DONE_ERROR;
10325 	cmd_attribute const *attrib;
10326 	long resid;
10327 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10328 	int severity;
10329 	int get_error;
10330 
10331 	ST_FUNC(ST_DEVINFO, st_decode_sense);
10332 
10333 	ASSERT(mutex_owned(ST_MUTEX));
10334 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10335 	    "st_decode_sense()\n");
10336 
10337 	/*
10338 	 * For uscsi commands, squirrel away a copy of the
10339 	 * results of the Request Sense.
10340 	 */
10341 	if (USCSI_CMD(bp)) {
10342 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
10343 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
10344 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
10345 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
10346 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
10347 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
10348 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10349 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
10350 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
10351 		}
10352 	}
10353 
10354 	if (ri->privatelen == sizeof (recov_info)) {
10355 		attrib = ri->cmd_attrib;
10356 	} else {
10357 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10358 	}
10359 
10360 	/*
10361 	 * If the drive is an MT-02, reposition the
10362 	 * secondary error code into the proper place.
10363 	 *
10364 	 * XXX	MT-02 is non-CCS tape, so secondary error code
10365 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
10366 	 * so it's in byte 12.
10367 	 */
10368 	if (un->un_dp->type == ST_TYPE_EMULEX) {
10369 		sensep->es_code = sensep->es_add_info[0];
10370 	}
10371 
10372 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
10373 	    (caddr_t)&CDBP(pkt)->scc_cmd);
10374 
10375 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)sensep,
10376 	    sizeof (*sensep));
10377 
10378 	/* for normal I/O check extract the resid values. */
10379 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
10380 		if (sensep->es_valid) {
10381 			resid =
10382 			    (sensep->es_info_1 << 24) |
10383 			    (sensep->es_info_2 << 16) |
10384 			    (sensep->es_info_3 << 8)  |
10385 			    (sensep->es_info_4);
10386 			/* If fixed block */
10387 			if (un->un_bsize) {
10388 				resid *= un->un_bsize;
10389 			}
10390 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
10391 			resid = pkt->pkt_resid;
10392 		} else {
10393 			resid = bp->b_bcount;
10394 		}
10395 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10396 		    "st_decode_sense (rw): xferred bit = %d, resid=%ld (%d), "
10397 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
10398 		    resid,
10399 		    (sensep->es_info_1 << 24) |
10400 		    (sensep->es_info_2 << 16) |
10401 		    (sensep->es_info_3 << 8)  |
10402 		    (sensep->es_info_4),
10403 		    pkt->pkt_resid);
10404 		/*
10405 		 * The problem is, what should we believe?
10406 		 */
10407 		if (resid && (pkt->pkt_resid == 0)) {
10408 			pkt->pkt_resid = resid;
10409 		}
10410 	} else {
10411 		/*
10412 		 * If the command is SCMD_SPACE, we need to get the
10413 		 * residual as returned in the sense data, to adjust
10414 		 * our idea of current tape position correctly
10415 		 */
10416 		if ((sensep->es_valid) &&
10417 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10418 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10419 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
10420 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK)) {
10421 			resid =
10422 			    (sensep->es_info_1 << 24) |
10423 			    (sensep->es_info_2 << 16) |
10424 			    (sensep->es_info_3 << 8)  |
10425 			    (sensep->es_info_4);
10426 			bp->b_resid = resid;
10427 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10428 			    "st_decode_sense(other):	resid=%ld\n", resid);
10429 		} else {
10430 			/*
10431 			 * If the special command is SCMD_READ,
10432 			 * the correct resid will be set later.
10433 			 */
10434 			if (attrib->get_cnt != NULL) {
10435 				resid = attrib->get_cnt(pkt->pkt_cdbp);
10436 			} else {
10437 				resid = bp->b_bcount;
10438 			}
10439 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10440 			    "st_decode_sense(special read):  resid=%ld\n",
10441 			    resid);
10442 		}
10443 	}
10444 
10445 	if ((un->un_state >= ST_STATE_OPEN) &&
10446 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
10447 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
10448 		    "Failed CDB", (char *)pkt->pkt_cdbp);
10449 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10450 		    "sense data", (char *)sensep, amt);
10451 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10452 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10453 		    bp->b_bcount, resid, pkt->pkt_resid);
10454 	}
10455 
10456 	switch (un->un_status = sensep->es_key) {
10457 	case KEY_NO_SENSE:
10458 		severity = SCSI_ERR_INFO;
10459 
10460 		/*
10461 		 * Erase, locate or rewind operation in progress, retry
10462 		 * ASC  ASCQ
10463 		 *  00   18    Erase operation in progress
10464 		 *  00   19    Locate operation in progress
10465 		 *  00   1A    Rewind operation in progress
10466 		 */
10467 		if (sensep->es_add_code == 0 &&
10468 		    ((sensep->es_qual_code == 0x18) ||
10469 		    (sensep->es_qual_code == 0x19) ||
10470 		    (sensep->es_qual_code == 0x1a))) {
10471 			rval = QUE_BUSY_COMMAND;
10472 			break;
10473 		}
10474 
10475 		goto common;
10476 
10477 	case KEY_RECOVERABLE_ERROR:
10478 		severity = SCSI_ERR_RECOVERED;
10479 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10480 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10481 			if (un->un_dp->options &
10482 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10483 				rval = QUE_LAST_COMMAND;
10484 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10485 				    severity, pos->lgclblkno,
10486 				    un->un_err_pos.lgclblkno, scsi_cmds,
10487 				    sensep);
10488 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10489 				    "Command will be retried\n");
10490 			} else {
10491 				severity = SCSI_ERR_FATAL;
10492 				rval = COMMAND_DONE_ERROR_RECOVERED;
10493 				ST_DO_ERRSTATS(un, st_softerrs);
10494 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10495 				    severity, pos->lgclblkno,
10496 				    un->un_err_pos.lgclblkno, scsi_cmds,
10497 				    sensep);
10498 			}
10499 			break;
10500 		}
10501 common:
10502 		/*
10503 		 * XXX only want reads to be stopped by filemarks.
10504 		 * Don't want them to be stopped by EOT.  EOT matters
10505 		 * only on write.
10506 		 */
10507 		if (sensep->es_filmk && !sensep->es_eom) {
10508 			rval = COMMAND_DONE;
10509 		} else if (sensep->es_eom) {
10510 			rval = COMMAND_DONE;
10511 		} else if (sensep->es_ili) {
10512 			/*
10513 			 * Fun with variable length record devices:
10514 			 * for specifying larger blocks sizes than the
10515 			 * actual physical record size.
10516 			 */
10517 			if (un->un_bsize == 0 && resid > 0) {
10518 				/*
10519 				 * XXX! Ugly.
10520 				 * The requested blocksize is > tape blocksize,
10521 				 * so this is ok, so we just return the
10522 				 * actual size xferred.
10523 				 */
10524 				pkt->pkt_resid = resid;
10525 				rval = COMMAND_DONE;
10526 			} else if (un->un_bsize == 0 && resid < 0) {
10527 				/*
10528 				 * The requested blocksize is < tape blocksize,
10529 				 * so this is not ok, so we err with ENOMEM
10530 				 */
10531 				rval = COMMAND_DONE_ERROR_RECOVERED;
10532 				st_bioerror(bp, ENOMEM);
10533 			} else {
10534 				ST_DO_ERRSTATS(un, st_softerrs);
10535 				severity = SCSI_ERR_FATAL;
10536 				rval = COMMAND_DONE_ERROR;
10537 				st_bioerror(bp, EINVAL);
10538 				un->un_running.pmode = invalid;
10539 			}
10540 		} else {
10541 			/*
10542 			 * we hope and pray for this just being
10543 			 * something we can ignore (ie. a
10544 			 * truly recoverable soft error)
10545 			 */
10546 			rval = COMMAND_DONE;
10547 		}
10548 		if (sensep->es_filmk) {
10549 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10550 			    "filemark\n");
10551 			un->un_status = SUN_KEY_EOF;
10552 			pos->eof = ST_EOF_PENDING;
10553 			st_set_pe_flag(un);
10554 		}
10555 
10556 		/*
10557 		 * ignore eom when reading, a fmk should terminate reading
10558 		 */
10559 		if ((sensep->es_eom) &&
10560 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10561 			if ((sensep->es_add_code == 0) &&
10562 			    (sensep->es_qual_code == 4)) {
10563 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10564 				    "bot\n");
10565 				un->un_status = SUN_KEY_BOT;
10566 				pos->eof = ST_NO_EOF;
10567 				pos->lgclblkno = 0;
10568 				pos->fileno = 0;
10569 				pos->blkno = 0;
10570 				if (pos->pmode != legacy)
10571 					pos->pmode = legacy;
10572 			} else {
10573 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10574 				    "eom\n");
10575 				un->un_status = SUN_KEY_EOT;
10576 				pos->eof = ST_EOM;
10577 			}
10578 			st_set_pe_flag(un);
10579 		}
10580 
10581 		break;
10582 
10583 	case KEY_ILLEGAL_REQUEST:
10584 
10585 		if (un->un_laststate >= ST_STATE_OPEN) {
10586 			ST_DO_ERRSTATS(un, st_softerrs);
10587 			severity = SCSI_ERR_FATAL;
10588 		} else {
10589 			severity = SCSI_ERR_INFO;
10590 		}
10591 		break;
10592 
10593 	case KEY_MEDIUM_ERROR:
10594 		ST_DO_ERRSTATS(un, st_harderrs);
10595 		severity = SCSI_ERR_FATAL;
10596 
10597 		/*
10598 		 * for (buffered) writes, a medium error must be fatal
10599 		 */
10600 		if (CDBP(pkt)->scc_cmd != SCMD_WRITE) {
10601 			rval = COMMAND_DONE_ERROR_RECOVERED;
10602 		}
10603 
10604 check_keys:
10605 		/*
10606 		 * attempt to process the keys in the presence of
10607 		 * other errors
10608 		 */
10609 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10610 			/*
10611 			 * Fun with variable length record devices:
10612 			 * for specifying larger blocks sizes than the
10613 			 * actual physical record size.
10614 			 */
10615 			if (un->un_bsize == 0 && resid > 0) {
10616 				/*
10617 				 * XXX! Ugly
10618 				 */
10619 				pkt->pkt_resid = resid;
10620 			} else if (un->un_bsize == 0 && resid < 0) {
10621 				st_bioerror(bp, EINVAL);
10622 			} else {
10623 				severity = SCSI_ERR_FATAL;
10624 				rval = COMMAND_DONE_ERROR;
10625 				st_bioerror(bp, EINVAL);
10626 			}
10627 		}
10628 		if (sensep->es_filmk) {
10629 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10630 			    "filemark\n");
10631 			un->un_status = SUN_KEY_EOF;
10632 			pos->eof = ST_EOF_PENDING;
10633 			st_set_pe_flag(un);
10634 		}
10635 
10636 		/*
10637 		 * ignore eom when reading, a fmk should terminate reading
10638 		 */
10639 		if ((sensep->es_eom) &&
10640 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10641 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10642 			un->un_status = SUN_KEY_EOT;
10643 			pos->eof = ST_EOM;
10644 			st_set_pe_flag(un);
10645 		}
10646 
10647 		break;
10648 
10649 	case KEY_VOLUME_OVERFLOW:
10650 		ST_DO_ERRSTATS(un, st_softerrs);
10651 		pos->eof = ST_EOM;
10652 		severity = SCSI_ERR_FATAL;
10653 		rval = COMMAND_DONE_ERROR;
10654 		goto check_keys;
10655 
10656 	case KEY_HARDWARE_ERROR:
10657 		ST_DO_ERRSTATS(un, st_harderrs);
10658 		severity = SCSI_ERR_FATAL;
10659 		rval = COMMAND_DONE_ERROR;
10660 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10661 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10662 		break;
10663 
10664 	case KEY_BLANK_CHECK:
10665 		ST_DO_ERRSTATS(un, st_softerrs);
10666 		severity = SCSI_ERR_INFO;
10667 
10668 		/*
10669 		 * if not a special request and some data was xferred then it
10670 		 * it is not an error yet
10671 		 */
10672 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10673 			/*
10674 			 * no error for read with or without data xferred
10675 			 */
10676 			un->un_status = SUN_KEY_EOT;
10677 			pos->eof = ST_EOT;
10678 			rval = COMMAND_DONE_ERROR;
10679 			st_set_pe_flag(un);
10680 			goto check_keys;
10681 		} else if (bp != un->un_sbufp &&
10682 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10683 			rval = COMMAND_DONE;
10684 		} else {
10685 			rval = COMMAND_DONE_ERROR_RECOVERED;
10686 		}
10687 
10688 		if (un->un_laststate >= ST_STATE_OPEN) {
10689 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10690 			    "blank check\n");
10691 			pos->eof = ST_EOM;
10692 		}
10693 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10694 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10695 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
10696 		    (un->un_dp->options & ST_KNOWS_EOD)) {
10697 			/*
10698 			 * we were doing a fast forward by skipping
10699 			 * multiple fmk at the time
10700 			 */
10701 			st_bioerror(bp, EIO);
10702 			severity = SCSI_ERR_RECOVERED;
10703 			rval	 = COMMAND_DONE;
10704 		}
10705 		st_set_pe_flag(un);
10706 		goto check_keys;
10707 
10708 	case KEY_WRITE_PROTECT:
10709 		if (st_wrongtapetype(un)) {
10710 			un->un_status = SUN_KEY_WRONGMEDIA;
10711 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10712 			    "wrong tape for writing- use DC6150 tape "
10713 			    "(or equivalent)\n");
10714 			severity = SCSI_ERR_UNKNOWN;
10715 		} else {
10716 			severity = SCSI_ERR_FATAL;
10717 		}
10718 		ST_DO_ERRSTATS(un, st_harderrs);
10719 		rval = COMMAND_DONE_ERROR;
10720 		st_bioerror(bp, EACCES);
10721 		break;
10722 
10723 	case KEY_UNIT_ATTENTION:
10724 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10725 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
10726 
10727 		un->un_unit_attention_flags = 1;
10728 		/*
10729 		 * If we have detected a Bus Reset and the tape
10730 		 * drive has been reserved.
10731 		 */
10732 		if (ST_RQSENSE->es_add_code == 0x29) {
10733 			rval = DEVICE_RESET;
10734 			if ((un->un_rsvd_status &
10735 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
10736 			    ST_RESERVE) {
10737 				un->un_rsvd_status |= ST_LOST_RESERVE;
10738 				ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
10739 				    "st_decode_sense: Lost Reservation\n");
10740 			}
10741 		}
10742 
10743 		/*
10744 		 * If this is a recovery command and retrable, retry.
10745 		 */
10746 		if (bp == un->un_recov_buf) {
10747 			severity = SCSI_ERR_INFO;
10748 			if (attrib->retriable &&
10749 			    (int)un->un_retry_ct++ < st_retry_count) {
10750 				rval = QUE_COMMAND;
10751 			} else {
10752 				rval = COMMAND_DONE_ERROR;
10753 			}
10754 			break; /* Don't set position invalid */
10755 		}
10756 
10757 		/*
10758 		 * If ST_APPLICATION_RESERVATIONS is set,
10759 		 * If the asc/ascq indicates that the reservation
10760 		 * has been cleared just allow the write to continue
10761 		 * which would force a scsi 2 reserve.
10762 		 * If preempted that persistent reservation
10763 		 * the scsi 2 reserve would get a reservation conflict.
10764 		 */
10765 		if ((un->un_rsvd_status &
10766 		    ST_APPLICATION_RESERVATIONS) != 0) {
10767 			if (ST_RQSENSE->es_add_code == 0x2a &&
10768 			    ST_RQSENSE->es_qual_code == 0x03) {
10769 				severity = SCSI_ERR_INFO;
10770 				rval = COMMAND_DONE_ERROR;
10771 				pos->pmode = invalid;
10772 			} else if (ST_RQSENSE->es_add_code == 0x2a &&
10773 			    ST_RQSENSE->es_qual_code == 0x04) {
10774 				rval = COMMAND_DONE;
10775 			}
10776 			break;
10777 		}
10778 
10779 		if (un->un_state <= ST_STATE_OPENING) {
10780 			/*
10781 			 * Look, the tape isn't open yet, now determine
10782 			 * if the cause is a BUS RESET, Save the file
10783 			 * and Block positions for the callers to
10784 			 * recover from the loss of position.
10785 			 */
10786 			severity = SCSI_ERR_INFO;
10787 			if ((pos->pmode != invalid) &&
10788 			    (rval == DEVICE_RESET) &&
10789 			    (un->un_restore_pos != 1)) {
10790 				un->un_save_fileno = pos->fileno;
10791 				un->un_save_blkno = pos->blkno;
10792 				un->un_restore_pos = 1;
10793 			}
10794 
10795 			if (attrib->retriable &&
10796 			    (int)un->un_retry_ct++ < st_retry_count) {
10797 				rval = QUE_COMMAND;
10798 			} else if (rval == DEVICE_RESET) {
10799 				break;
10800 			} else {
10801 				rval = COMMAND_DONE_ERROR;
10802 			}
10803 		/*
10804 		 * Means it thinks the mode parameters have changed.
10805 		 * This is the result of a reset clearing settings or
10806 		 * another initiator changing what we set.
10807 		 */
10808 		} else if (ST_RQSENSE->es_add_code == 0x2a) {
10809 			if (ST_RQSENSE->es_qual_code == 0x1) {
10810 				/* Error recovery will modeselect and retry. */
10811 				rval = DEVICE_TAMPER;
10812 				severity = SCSI_ERR_INFO;
10813 				break; /* don't set position invalid */
10814 			}
10815 			if (ST_RQSENSE->es_qual_code == 0x0 ||
10816 			    ST_RQSENSE->es_qual_code == 0x2 ||
10817 			    ST_RQSENSE->es_qual_code == 0x3 ||
10818 			    ST_RQSENSE->es_qual_code == 0x4 ||
10819 			    ST_RQSENSE->es_qual_code == 0x5 ||
10820 			    ST_RQSENSE->es_qual_code == 0x6 ||
10821 			    ST_RQSENSE->es_qual_code == 0x7) {
10822 				rval = DEVICE_TAMPER;
10823 				severity = SCSI_ERR_INFO;
10824 			}
10825 		} else if (ST_RQSENSE->es_add_code == 0x28 &&
10826 		    ((ST_RQSENSE->es_qual_code == 0x0) ||
10827 		    ST_RQSENSE->es_qual_code == 0x5)) {
10828 			/*
10829 			 * Not Ready to Ready change, Media may have changed.
10830 			 */
10831 			rval = DEVICE_TAMPER;
10832 			severity = SCSI_ERR_RETRYABLE;
10833 		} else {
10834 			if (rval != DEVICE_RESET) {
10835 				rval = COMMAND_DONE_ERROR;
10836 			} else {
10837 				/*
10838 				 * Returning DEVICE_RESET will call
10839 				 * error recovery.
10840 				 */
10841 				severity = SCSI_ERR_INFO;
10842 				break; /* don't set position invalid */
10843 			}
10844 			/*
10845 			 * Check if it is an Unexpected Unit Attention.
10846 			 * If state is >= ST_STATE_OPEN, we have
10847 			 * already done the initialization .
10848 			 * In this case it is Fatal Error
10849 			 * since no further reading/writing
10850 			 * can be done with fileno set to < 0.
10851 			 */
10852 			if (un->un_state >= ST_STATE_OPEN) {
10853 				ST_DO_ERRSTATS(un, st_harderrs);
10854 				severity = SCSI_ERR_FATAL;
10855 			} else {
10856 				severity = SCSI_ERR_INFO;
10857 			}
10858 		}
10859 
10860 		pos->pmode = invalid;
10861 
10862 		break;
10863 
10864 	case KEY_NOT_READY:
10865 		/*
10866 		 * If in process of getting ready retry.
10867 		 */
10868 		if (sensep->es_add_code  == 0x04 &&
10869 		    sensep->es_qual_code == 0x01 &&
10870 		    un->un_retry_ct++ < st_retry_count) {
10871 			rval = QUE_COMMAND;
10872 			severity = SCSI_ERR_INFO;
10873 		} else {
10874 			/* give up */
10875 			rval = COMMAND_DONE_ERROR;
10876 			severity = SCSI_ERR_FATAL;
10877 		}
10878 
10879 		/*
10880 		 * If this was an error and after device opened
10881 		 * do error stats.
10882 		 */
10883 		if (rval == COMMAND_DONE_ERROR &&
10884 		    un->un_state > ST_STATE_OPENING) {
10885 			ST_DO_ERRSTATS(un, st_harderrs);
10886 		}
10887 
10888 		if (ST_RQSENSE->es_add_code == 0x3a) {
10889 			if (st_error_level >= SCSI_ERR_FATAL)
10890 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
10891 				    "Tape not inserted in drive\n");
10892 			un->un_mediastate = MTIO_EJECTED;
10893 			cv_broadcast(&un->un_state_cv);
10894 		}
10895 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
10896 		    (rval != QUE_COMMAND))
10897 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10898 		break;
10899 
10900 	case KEY_ABORTED_COMMAND:
10901 		/* XXX Do drives return this when they see a lost light? */
10902 		/* Testing would say yes */
10903 
10904 		if (un->un_retry_ct++ < st_retry_count) {
10905 			rval = ATTEMPT_RETRY;
10906 			severity = SCSI_ERR_RETRYABLE;
10907 			goto check_keys;
10908 		}
10909 		/*
10910 		 * Probably a parity error...
10911 		 * if we retry here then this may cause data to be
10912 		 * written twice or data skipped during reading
10913 		 */
10914 		ST_DO_ERRSTATS(un, st_harderrs);
10915 		severity = SCSI_ERR_FATAL;
10916 		rval = COMMAND_DONE_ERROR;
10917 		goto check_keys;
10918 
10919 	default:
10920 		/*
10921 		 * Undecoded sense key.	 Try retries and hope
10922 		 * that will fix the problem.  Otherwise, we're
10923 		 * dead.
10924 		 */
10925 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10926 		    "Unhandled Sense Key '%s'\n",
10927 		    sense_keys[un->un_status]);
10928 		ST_DO_ERRSTATS(un, st_harderrs);
10929 		severity = SCSI_ERR_FATAL;
10930 		rval = COMMAND_DONE_ERROR;
10931 		goto check_keys;
10932 	}
10933 
10934 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
10935 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
10936 	    (un->un_laststate > ST_STATE_OPENING) &&
10937 	    (severity >= st_error_level))) {
10938 
10939 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
10940 		    pos->lgclblkno, un->un_err_pos.lgclblkno,
10941 		    scsi_cmds, sensep);
10942 		if (sensep->es_filmk) {
10943 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10944 			    "File Mark Detected\n");
10945 		}
10946 		if (sensep->es_eom) {
10947 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10948 			    "End-of-Media Detected\n");
10949 		}
10950 		if (sensep->es_ili) {
10951 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10952 			    "Incorrect Length Indicator Set\n");
10953 		}
10954 	}
10955 	get_error = geterror(bp);
10956 	if (((rval == COMMAND_DONE_ERROR) ||
10957 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
10958 	    ((get_error == EIO) || (get_error == 0))) {
10959 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
10960 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
10961 		if (un->un_rqs_state & ST_RQS_READ) {
10962 			un->un_rqs_state &= ~(ST_RQS_READ);
10963 		} else {
10964 			un->un_rqs_state |= ST_RQS_OVR;
10965 		}
10966 	}
10967 
10968 	return (rval);
10969 }
10970 
10971 
10972 static int
10973 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
10974 {
10975 	int status = TRAN_ACCEPT;
10976 
10977 	mutex_enter(ST_MUTEX);
10978 
10979 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
10980 
10981 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10982 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
10983 
10984 	/*
10985 	 * Check to see if we hit the retry timeout. We check to make sure
10986 	 * this is the first one on the runq and make sure we have not
10987 	 * queued up any more, so this one has to be the last on the list
10988 	 * also. If it is not, we have to fail.  If it is not the first, but
10989 	 * is the last we are in trouble anyway, as we are in the interrupt
10990 	 * context here.
10991 	 */
10992 	if (((int)un->un_retry_ct > st_retry_count) ||
10993 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
10994 		goto exit;
10995 	}
10996 
10997 	if (un->un_throttle) {
10998 		un->un_last_throttle = un->un_throttle;
10999 		un->un_throttle = 0;
11000 	}
11001 
11002 	/*
11003 	 * Here we know : bp is the first and last one on the runq
11004 	 * it is not necessary to put it back on the head of the
11005 	 * waitq and then move from waitq to runq. Save this queuing
11006 	 * and call scsi_transport.
11007 	 */
11008 	ST_CDB(ST_DEVINFO, "Retry lcmd CDB", (char *)BP_PKT(bp)->pkt_cdbp);
11009 
11010 	status = st_transport(un, BP_PKT(bp));
11011 
11012 	if (status == TRAN_ACCEPT) {
11013 		un->un_tran_retry_ct = 0;
11014 		if (un->un_last_throttle) {
11015 			un->un_throttle = un->un_last_throttle;
11016 		}
11017 		mutex_exit(ST_MUTEX);
11018 
11019 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11020 		    "restart transport \n");
11021 		return (0);
11022 	}
11023 
11024 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
11025 	mutex_exit(ST_MUTEX);
11026 
11027 	if (status == TRAN_BUSY) {
11028 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
11029 			return (0);
11030 		}
11031 	}
11032 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11033 	    "restart transport rejected\n");
11034 	mutex_enter(ST_MUTEX);
11035 	ST_DO_ERRSTATS(un, st_transerrs);
11036 	if (un->un_last_throttle) {
11037 		un->un_throttle = un->un_last_throttle;
11038 	}
11039 exit:
11040 	mutex_exit(ST_MUTEX);
11041 	return (-1);
11042 }
11043 
11044 static int
11045 st_wrongtapetype(struct scsi_tape *un)
11046 {
11047 
11048 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
11049 
11050 	ASSERT(mutex_owned(ST_MUTEX));
11051 
11052 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
11053 
11054 	/*
11055 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
11056 	 */
11057 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
11058 		switch (un->un_dp->type) {
11059 		case ST_TYPE_WANGTEK:
11060 		case ST_TYPE_ARCHIVE:
11061 			/*
11062 			 * If this really worked, we could go off of
11063 			 * the density codes set in the modesense
11064 			 * page. For this drive, 0x10 == QIC-120,
11065 			 * 0xf == QIC-150, and 0x5 should be for
11066 			 * both QIC-24 and, maybe, QIC-11. However,
11067 			 * the h/w doesn't do what the manual says
11068 			 * that it should, so we'll key off of
11069 			 * getting a WRITE PROTECT error AND wp *not*
11070 			 * set in the mode sense information.
11071 			 */
11072 			/*
11073 			 * XXX but we already know that status is
11074 			 * write protect, so don't check it again.
11075 			 */
11076 
11077 			if (un->un_status == KEY_WRITE_PROTECT &&
11078 			    un->un_mspl->wp == 0) {
11079 				return (1);
11080 			}
11081 			break;
11082 		default:
11083 			break;
11084 		}
11085 	}
11086 	return (0);
11087 }
11088 
11089 static errstate
11090 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
11091 {
11092 	errstate action;
11093 
11094 	ST_FUNC(ST_DEVINFO, st_check_error);
11095 
11096 	ASSERT(mutex_owned(ST_MUTEX));
11097 
11098 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
11099 
11100 	if (SCBP_C(pkt) == STATUS_RESERVATION_CONFLICT) {
11101 		action = COMMAND_DONE_EACCES;
11102 		un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
11103 	} else if (SCBP(pkt)->sts_busy) {
11104 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
11105 		if ((int)un->un_retry_ct++ < st_retry_count) {
11106 			action = QUE_BUSY_COMMAND;
11107 		} else if ((un->un_rsvd_status &
11108 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
11109 			/*
11110 			 * If this is a command done before reserve is done
11111 			 * don't reset.
11112 			 */
11113 			action = COMMAND_DONE_ERROR;
11114 		} else {
11115 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11116 			    "unit busy too long\n");
11117 			(void) st_reset(un, RESET_ALL);
11118 			action = COMMAND_DONE_ERROR;
11119 		}
11120 	} else if (SCBP(pkt)->sts_chk) {
11121 		/*
11122 		 * we should only get here if the auto rqsense failed
11123 		 * thru a uscsi cmd without autorequest sense
11124 		 * so we just try again
11125 		 */
11126 		action = QUE_SENSE;
11127 	} else if (SCBP(pkt)->sts_vu7) {
11128 		/*
11129 		 * This is an aborted task. This can be a reset on the other
11130 		 * port of a multiport drive. Lets try and recover it.
11131 		 */
11132 		action = DEVICE_RESET;
11133 	} else {
11134 		action = COMMAND_DONE;
11135 	}
11136 	return (action);
11137 }
11138 
11139 static void
11140 st_calc_bnum(struct scsi_tape *un, struct buf *bp, struct scsi_pkt *pkt)
11141 {
11142 	int nblks;
11143 	long count;
11144 	recov_info *ri = (recov_info *)pkt->pkt_private;
11145 	cmd_attribute const *attrib;
11146 
11147 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
11148 
11149 	ASSERT(mutex_owned(ST_MUTEX));
11150 
11151 	if (ri->privatelen == sizeof (recov_info)) {
11152 		attrib = ri->cmd_attrib;
11153 		ASSERT(attrib->recov_pos_type == POS_EXPECTED);
11154 		ASSERT(attrib->chg_tape_pos);
11155 	} else {
11156 		ri = NULL;
11157 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
11158 	}
11159 
11160 	count = bp->b_bcount - bp->b_resid;
11161 
11162 	/* If variable block mode */
11163 	if (un->un_bsize == 0) {
11164 		nblks = ((count == 0) ? 0 : 1);
11165 		un->un_kbytes_xferred += (count / ONE_K);
11166 	} else {
11167 		nblks = (count / un->un_bsize);
11168 		un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
11169 	}
11170 
11171 	/*
11172 	 * If some command failed after this one started and it seems
11173 	 * to have finshed without error count the position.
11174 	 */
11175 	if (un->un_persistence && un->un_persist_errors) {
11176 		ASSERT(un->un_pos.pmode != invalid);
11177 	}
11178 
11179 	if (attrib->chg_tape_direction == DIR_FORW) {
11180 		un->un_pos.blkno += nblks;
11181 		un->un_pos.lgclblkno += nblks;
11182 	} else if (attrib->chg_tape_direction == DIR_REVC) {
11183 		un->un_pos.blkno -= nblks;
11184 		un->un_pos.lgclblkno -= nblks;
11185 	} else {
11186 		ASSERT(0);
11187 	}
11188 
11189 	/* recovery disabled */
11190 	if (ri == NULL) {
11191 		un->un_running.pmode = invalid;
11192 		return;
11193 	}
11194 
11195 	/*
11196 	 * If we didn't just read a filemark.
11197 	 */
11198 	if (un->un_pos.eof != ST_EOF_PENDING) {
11199 		ASSERT(nblks != 0);
11200 		/*
11201 		 * If Previously calulated expected position does not match
11202 		 * debug the expected position.
11203 		 */
11204 		if ((ri->pos.pmode != invalid) && nblks &&
11205 		    ((un->un_pos.blkno != ri->pos.blkno) ||
11206 		    (un->un_pos.lgclblkno != ri->pos.lgclblkno))) {
11207 #ifdef STDEBUG
11208 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11209 			    "Expected", &ri->pos);
11210 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11211 			    "But Got", &un->un_pos);
11212 #endif
11213 			un->un_running.pmode = invalid;
11214 		}
11215 	} else {
11216 		ASSERT(nblks == 0);
11217 		if (un->un_running.pmode != invalid) {
11218 			/*
11219 			 * blkno and lgclblkno already counted in
11220 			 * st_add_recovery_info_to_pkt(). Since a block was not
11221 			 * read and a filemark was.
11222 			 */
11223 			if (attrib->chg_tape_direction == DIR_FORW) {
11224 				un->un_running.fileno++;
11225 				un->un_running.blkno = 0;
11226 			} else if (attrib->chg_tape_direction == DIR_REVC) {
11227 				un->un_running.fileno--;
11228 				un->un_running.blkno = LASTBLK;
11229 			}
11230 		}
11231 	}
11232 }
11233 
11234 static void
11235 st_set_state(struct scsi_tape *un, struct buf *bp)
11236 {
11237 	struct scsi_pkt *sp = BP_PKT(bp);
11238 	struct uscsi_cmd *ucmd;
11239 
11240 	ST_FUNC(ST_DEVINFO, st_set_state);
11241 
11242 	ASSERT(mutex_owned(ST_MUTEX));
11243 	ASSERT(bp != un->un_recov_buf);
11244 
11245 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11246 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
11247 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
11248 
11249 	if (bp != un->un_sbufp) {
11250 #ifdef STDEBUG
11251 		if (DEBUGGING && sp->pkt_resid) {
11252 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11253 			    "pkt_resid %ld bcount %ld\n",
11254 			    sp->pkt_resid, bp->b_bcount);
11255 		}
11256 #endif
11257 		bp->b_resid = sp->pkt_resid;
11258 		if (geterror(bp) != EIO) {
11259 			st_calc_bnum(un, bp, sp);
11260 		}
11261 		if (bp->b_flags & B_READ) {
11262 			un->un_lastop = ST_OP_READ;
11263 			un->un_fmneeded = 0;
11264 		} else {
11265 			un->un_lastop = ST_OP_WRITE;
11266 			if (un->un_dp->options & ST_REEL) {
11267 				un->un_fmneeded = 2;
11268 			} else {
11269 				un->un_fmneeded = 1;
11270 			}
11271 		}
11272 		/*
11273 		 * all is honky dory at this point, so let's
11274 		 * readjust the throttle, to increase speed, if we
11275 		 * have not throttled down.
11276 		 */
11277 		if (un->un_throttle) {
11278 			un->un_throttle = un->un_max_throttle;
11279 		}
11280 	} else {
11281 		optype new_lastop;
11282 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
11283 
11284 		un->un_lastop = ST_OP_CTL;
11285 
11286 		switch (cmd) {
11287 		case SCMD_WRITE:
11288 		case SCMD_WRITE_G4:
11289 			bp->b_resid = sp->pkt_resid;
11290 			if (geterror(bp) == EIO) {
11291 				break;
11292 			}
11293 			new_lastop = ST_OP_WRITE;
11294 			st_calc_bnum(un, bp, sp);
11295 			if (un->un_dp->options & ST_REEL) {
11296 				un->un_fmneeded = 2;
11297 			} else {
11298 				un->un_fmneeded = 1;
11299 			}
11300 			break;
11301 		case SCMD_READ:
11302 		case SCMD_READ_G4:
11303 			bp->b_resid = sp->pkt_resid;
11304 			if (geterror(bp) == EIO) {
11305 				break;
11306 			}
11307 			new_lastop = ST_OP_READ;
11308 			st_calc_bnum(un, bp, sp);
11309 			un->un_fmneeded = 0;
11310 			break;
11311 		case SCMD_WRITE_FILE_MARK_G4:
11312 		case SCMD_WRITE_FILE_MARK:
11313 		{
11314 			int fmdone;
11315 
11316 			if (un->un_pos.eof != ST_EOM) {
11317 				un->un_pos.eof = ST_NO_EOF;
11318 			}
11319 			fmdone = (bp->b_bcount - bp->b_resid);
11320 			if (fmdone > 0) {
11321 				un->un_lastop = new_lastop = ST_OP_WEOF;
11322 				un->un_pos.lgclblkno += fmdone;
11323 				un->un_pos.fileno += fmdone;
11324 				un->un_pos.blkno = 0;
11325 			} else {
11326 				new_lastop = ST_OP_CTL;
11327 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11328 				    "Flushed buffer\n");
11329 			}
11330 			if (fmdone > un->un_fmneeded) {
11331 				un->un_fmneeded = 0;
11332 			} else {
11333 				un->un_fmneeded -= fmdone;
11334 			}
11335 			break;
11336 		}
11337 		case SCMD_REWIND:
11338 			un->un_pos.eof = ST_NO_EOF;
11339 			un->un_pos.fileno = 0;
11340 			un->un_pos.blkno = 0;
11341 			un->un_pos.lgclblkno = 0;
11342 			if (un->un_pos.pmode != legacy)
11343 				un->un_pos.pmode = legacy;
11344 			new_lastop = ST_OP_CTL;
11345 			un->un_restore_pos = 0;
11346 			break;
11347 
11348 		case SCMD_SPACE:
11349 		case SCMD_SPACE_G4:
11350 		{
11351 			int64_t count;
11352 			int64_t resid;
11353 			int64_t done;
11354 			cmd_attribute const *attrib;
11355 			recov_info *ri = (recov_info *)sp->pkt_private;
11356 
11357 			if (ri->privatelen == sizeof (recov_info)) {
11358 				attrib = ri->cmd_attrib;
11359 			} else {
11360 				attrib =
11361 				    st_lookup_cmd_attribute(sp->pkt_cdbp[0]);
11362 			}
11363 
11364 			resid = (int64_t)SPACE_CNT(bp->b_resid);
11365 			count = (int64_t)attrib->get_cnt(sp->pkt_cdbp);
11366 
11367 			if (count >= 0) {
11368 				done = (count - resid);
11369 			} else {
11370 				done = ((-count) - resid);
11371 			}
11372 			if (done > 0) {
11373 				un->un_lastop = new_lastop = ST_OP_CTL;
11374 			} else {
11375 				new_lastop = ST_OP_CTL;
11376 			}
11377 
11378 			ST_SPAC(ST_DEVINFO, st_label, SCSI_DEBUG,
11379 			    "space cmd: cdb[1] = %s\n"
11380 			    "space data:       = 0x%lx\n"
11381 			    "space count:      = %"PRId64"\n"
11382 			    "space resid:      = %"PRId64"\n"
11383 			    "spaces done:      = %"PRId64"\n"
11384 			    "fileno before     = %d\n"
11385 			    "blkno before      = %d\n",
11386 			    space_strs[sp->pkt_cdbp[1] & 7],
11387 			    bp->b_bcount,
11388 			    count, resid, done,
11389 			    un->un_pos.fileno, un->un_pos.blkno);
11390 
11391 			switch (sp->pkt_cdbp[1]) {
11392 			case SPACE_TYPE(SP_FLM):
11393 				/* Space file forward */
11394 				if (count >= 0) {
11395 					if (un->un_pos.eof <= ST_EOF) {
11396 						un->un_pos.eof = ST_NO_EOF;
11397 					}
11398 					un->un_pos.fileno += done;
11399 					un->un_pos.blkno = 0;
11400 					break;
11401 				}
11402 				/* Space file backward */
11403 				if (done > un->un_pos.fileno) {
11404 					un->un_pos.fileno = 0;
11405 					un->un_pos.blkno = 0;
11406 				} else {
11407 					un->un_pos.fileno -= done;
11408 					un->un_pos.blkno = LASTBLK;
11409 					un->un_running.pmode = invalid;
11410 				}
11411 				break;
11412 			case SPACE_TYPE(SP_BLK):
11413 				/* Space block forward */
11414 				if (count >= 0) {
11415 					un->un_pos.blkno += done;
11416 					break;
11417 				}
11418 				/* Space block backward */
11419 				if (un->un_pos.eof >= ST_EOF_PENDING) {
11420 				/*
11421 				 * we stepped back into
11422 				 * a previous file; we are not
11423 				 * making an effort to pretend that
11424 				 * we are still in the current file
11425 				 * ie. logical == physical position
11426 				 * and leave it to st_ioctl to correct
11427 				 */
11428 					if (done > un->un_pos.blkno) {
11429 						un->un_pos.blkno = 0;
11430 					} else {
11431 						un->un_pos.fileno--;
11432 						un->un_pos.blkno = LASTBLK;
11433 						un->un_running.pmode = invalid;
11434 					}
11435 				} else {
11436 					un->un_pos.blkno -= done;
11437 				}
11438 				break;
11439 			case SPACE_TYPE(SP_SQFLM):
11440 				un->un_pos.pmode = logical;
11441 				un->un_pos.blkno = 0;
11442 				un->un_lastop = new_lastop = ST_OP_CTL;
11443 				break;
11444 			case SPACE_TYPE(SP_EOD):
11445 				un->un_pos.pmode = logical;
11446 				un->un_pos.eof = ST_EOM;
11447 				un->un_status = KEY_BLANK_CHECK;
11448 				break;
11449 			default:
11450 				un->un_pos.pmode = invalid;
11451 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11452 				    "Unsupported space cmd: %s\n",
11453 				    space_strs[sp->pkt_cdbp[1] & 7]);
11454 
11455 				un->un_lastop = new_lastop = ST_OP_CTL;
11456 			}
11457 
11458 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11459 			    "after_space rs %"PRId64" fil %d blk %d\n",
11460 			    resid, un->un_pos.fileno, un->un_pos.blkno);
11461 
11462 			break;
11463 		}
11464 		case SCMD_LOAD:
11465 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
11466 				un->un_pos.fileno = 0;
11467 				if (un->un_pos.pmode != legacy)
11468 					un->un_pos.pmode = legacy;
11469 			} else {
11470 				un->un_state = ST_STATE_OFFLINE;
11471 				un->un_pos.pmode = invalid;
11472 			}
11473 			un->un_density_known = 0;
11474 			un->un_pos.eof = ST_NO_EOF;
11475 			un->un_pos.blkno = 0;
11476 			un->un_lastop = new_lastop = ST_OP_CTL;
11477 			break;
11478 		case SCMD_ERASE:
11479 			un->un_pos.eof = ST_NO_EOF;
11480 			un->un_pos.blkno = 0;
11481 			un->un_pos.fileno = 0;
11482 			un->un_pos.lgclblkno = 0;
11483 			if (un->un_pos.pmode != legacy)
11484 				un->un_pos.pmode = legacy;
11485 			new_lastop = ST_OP_CTL;
11486 			break;
11487 		case SCMD_RESERVE:
11488 			un->un_rsvd_status |= ST_RESERVE;
11489 			un->un_rsvd_status &=
11490 			    ~(ST_RELEASE | ST_LOST_RESERVE |
11491 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11492 			new_lastop = un->un_lastop;
11493 			break;
11494 		case SCMD_RELEASE:
11495 			un->un_rsvd_status |= ST_RELEASE;
11496 			un->un_rsvd_status &=
11497 			    ~(ST_RESERVE | ST_LOST_RESERVE |
11498 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11499 			new_lastop = ST_OP_CTL;
11500 			break;
11501 		case SCMD_PERSISTENT_RESERVE_IN:
11502 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11503 			    "PGR_IN command\n");
11504 			break;
11505 		case SCMD_PERSISTENT_RESERVE_OUT:
11506 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
11507 			case ST_SA_SCSI3_RESERVE:
11508 			case ST_SA_SCSI3_PREEMPT:
11509 			case ST_SA_SCSI3_PREEMPTANDABORT:
11510 				un->un_rsvd_status |=
11511 				    ST_APPLICATION_RESERVATIONS;
11512 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11513 				    "PGR Reserve and set: entering"
11514 				    " ST_APPLICATION_RESERVATIONS mode");
11515 				break;
11516 			case ST_SA_SCSI3_RELEASE:
11517 			case ST_SA_SCSI3_CLEAR:
11518 				un->un_rsvd_status &=
11519 				    ~ST_APPLICATION_RESERVATIONS;
11520 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11521 				    "PGR Release and reset: exiting"
11522 				    " ST_APPLICATION_RESERVATIONS mode");
11523 				break;
11524 			}
11525 			break;
11526 		case SCMD_TEST_UNIT_READY:
11527 		case SCMD_READ_BLKLIM:
11528 		case SCMD_REQUEST_SENSE:
11529 		case SCMD_INQUIRY:
11530 		case SCMD_RECOVER_BUF:
11531 		case SCMD_MODE_SELECT:
11532 		case SCMD_MODE_SENSE:
11533 		case SCMD_DOORLOCK:
11534 		case SCMD_READ_BUFFER:
11535 		case SCMD_REPORT_DENSITIES:
11536 		case SCMD_LOG_SELECT_G1:
11537 		case SCMD_LOG_SENSE_G1:
11538 		case SCMD_REPORT_LUNS:
11539 		case SCMD_READ_ATTRIBUTE:
11540 		case SCMD_WRITE_ATTRIBUTE:
11541 		case SCMD_SVC_ACTION_IN_G5:
11542 			new_lastop = ST_OP_CTL;
11543 			break;
11544 		case SCMD_READ_POSITION:
11545 			new_lastop = ST_OP_CTL;
11546 			/*
11547 			 * Only if the buf used was un_sbufp.
11548 			 * Among other things the prevents read positions used
11549 			 * as part of error recovery from messing up our
11550 			 * current position as they will use un_recov_buf.
11551 			 */
11552 			if (USCSI_CMD(bp)) {
11553 				(void) st_get_read_pos(un, bp);
11554 			}
11555 			break;
11556 		case SCMD_LOCATE:
11557 		case SCMD_LOCATE_G4:
11558 			/* Locate makes position mode no longer legacy */
11559 			un->un_lastop = new_lastop = ST_OP_CTL;
11560 			break;
11561 		default:
11562 			/*
11563 			 * Unknown command, If was USCSI and USCSI_SILENT
11564 			 * flag was not set, set position to unknown.
11565 			 */
11566 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
11567 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
11568 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11569 				    "unknown cmd 0x%X caused loss of state\n",
11570 				    cmd);
11571 			} else {
11572 				break;
11573 			}
11574 			/* FALLTHROUGH */
11575 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
11576 			un->un_pos.pmode = invalid;
11577 			un->un_lastop = new_lastop = ST_OP_CTL;
11578 			break;
11579 		}
11580 
11581 		/* new_lastop should have been changed */
11582 		ASSERT(new_lastop != ST_OP_NIL);
11583 
11584 		/* If un_lastop should copy new_lastop  */
11585 		if (((un->un_lastop == ST_OP_WRITE) ||
11586 		    (un->un_lastop == ST_OP_WEOF)) &&
11587 		    new_lastop != ST_OP_CTL) {
11588 			un->un_lastop = new_lastop;
11589 		}
11590 	}
11591 
11592 	/*
11593 	 * In the st driver we have a logical and physical file position.
11594 	 * Under BSD behavior, when you get a zero read, the logical position
11595 	 * is before the filemark but after the last record of the file.
11596 	 * The physical position is after the filemark. MTIOCGET should always
11597 	 * return the logical file position.
11598 	 *
11599 	 * The next read gives a silent skip to the next file.
11600 	 * Under SVR4, the logical file position remains before the filemark
11601 	 * until the file is closed or a space operation is performed.
11602 	 * Hence set err_resid and err_file before changing fileno if case
11603 	 * BSD Behaviour.
11604 	 */
11605 	un->un_err_resid = bp->b_resid;
11606 	COPY_POS(&un->un_err_pos, &un->un_pos);
11607 	un->un_retry_ct = 0;
11608 
11609 
11610 	/*
11611 	 * If we've seen a filemark via the last read operation
11612 	 * advance the file counter, but mark things such that
11613 	 * the next read operation gets a zero count. We have
11614 	 * to put this here to handle the case of sitting right
11615 	 * at the end of a tape file having seen the file mark,
11616 	 * but the tape is closed and then re-opened without
11617 	 * any further i/o. That is, the position information
11618 	 * must be updated before a close.
11619 	 */
11620 
11621 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
11622 		/*
11623 		 * If we're a 1/2" tape, and we get a filemark
11624 		 * right on block 0, *AND* we were not in the
11625 		 * first file on the tape, and we've hit logical EOM.
11626 		 * We'll mark the state so that later we do the
11627 		 * right thing (in st_close(), st_strategy() or
11628 		 * st_ioctl()).
11629 		 *
11630 		 */
11631 		if ((un->un_dp->options & ST_REEL) &&
11632 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
11633 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
11634 			un->un_pos.eof = ST_EOT_PENDING;
11635 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11636 			    "eot pending\n");
11637 			un->un_pos.fileno++;
11638 			un->un_pos.blkno = 0;
11639 		} else if (BSD_BEHAVIOR) {
11640 			/*
11641 			 * If the read of the filemark was a side effect
11642 			 * of reading some blocks (i.e., data was actually
11643 			 * read), then the EOF mark is pending and the
11644 			 * bump into the next file awaits the next read
11645 			 * operation (which will return a zero count), or
11646 			 * a close or a space operation, else the bump
11647 			 * into the next file occurs now.
11648 			 */
11649 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11650 			    "resid=%lx, bcount=%lx\n",
11651 			    bp->b_resid, bp->b_bcount);
11652 
11653 			if (bp->b_resid != bp->b_bcount) {
11654 				un->un_pos.eof = ST_EOF;
11655 			} else {
11656 				un->un_silent_skip = 1;
11657 				un->un_pos.eof = ST_NO_EOF;
11658 				un->un_pos.fileno++;
11659 				un->un_pos.lgclblkno++;
11660 				un->un_save_blkno = un->un_pos.blkno;
11661 				un->un_pos.blkno = 0;
11662 			}
11663 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11664 			    "eof of file %d, eof=%d\n",
11665 			    un->un_pos.fileno, un->un_pos.eof);
11666 		} else if (SVR4_BEHAVIOR) {
11667 			/*
11668 			 * If the read of the filemark was a side effect
11669 			 * of reading some blocks (i.e., data was actually
11670 			 * read), then the next read should return 0
11671 			 */
11672 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11673 			    "resid=%lx, bcount=%lx\n",
11674 			    bp->b_resid, bp->b_bcount);
11675 			if (bp->b_resid == bp->b_bcount) {
11676 				un->un_pos.eof = ST_EOF;
11677 			}
11678 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11679 			    "eof of file=%d, eof=%d\n",
11680 			    un->un_pos.fileno, un->un_pos.eof);
11681 		}
11682 	}
11683 }
11684 
11685 /*
11686  * set the correct un_errno, to take corner cases into consideration
11687  */
11688 static void
11689 st_set_pe_errno(struct scsi_tape *un)
11690 {
11691 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
11692 
11693 	ASSERT(mutex_owned(ST_MUTEX));
11694 
11695 	/* if errno is already set, don't reset it */
11696 	if (un->un_errno)
11697 		return;
11698 
11699 	/* here un_errno == 0 */
11700 	/*
11701 	 * if the last transfer before flushing all the
11702 	 * waiting I/O's, was 0 (resid = count), then we
11703 	 * want to give the user an error on all the rest,
11704 	 * so here.  If there was a transfer, we set the
11705 	 * resid and counts to 0, and let it drop through,
11706 	 * giving a zero return.  the next I/O will then
11707 	 * give an error.
11708 	 */
11709 	if (un->un_last_resid == un->un_last_count) {
11710 		switch (un->un_pos.eof) {
11711 		case ST_EOM:
11712 			un->un_errno = ENOMEM;
11713 			break;
11714 		case ST_EOT:
11715 		case ST_EOF:
11716 			un->un_errno = EIO;
11717 			break;
11718 		}
11719 	} else {
11720 		/*
11721 		 * we know they did not have a zero, so make
11722 		 * sure they get one
11723 		 */
11724 		un->un_last_resid = un->un_last_count = 0;
11725 	}
11726 }
11727 
11728 
11729 /*
11730  * send in a marker pkt to terminate flushing of commands by BBA (via
11731  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
11732  */
11733 static void
11734 st_hba_unflush(struct scsi_tape *un)
11735 {
11736 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
11737 
11738 	ASSERT(mutex_owned(ST_MUTEX));
11739 
11740 	if (!un->un_flush_on_errors)
11741 		return;
11742 
11743 #ifdef FLUSH_ON_ERRORS
11744 
11745 	if (!un->un_mkr_pkt) {
11746 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
11747 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
11748 
11749 		/* we slept, so it must be there */
11750 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
11751 	}
11752 
11753 	st_transport(un, un->un_mkr_pkt);
11754 #endif
11755 }
11756 
11757 static char *
11758 st_print_scsi_cmd(char cmd)
11759 {
11760 	char tmp[64];
11761 	char *cpnt;
11762 
11763 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
11764 	/* tmp goes out of scope on return and caller sees garbage */
11765 	if (cpnt == tmp) {
11766 		cpnt = "Unknown Command";
11767 	}
11768 	return (cpnt);
11769 }
11770 
11771 static void
11772 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
11773     char *title, char *cdb)
11774 {
11775 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
11776 	char buf[256];
11777 	struct scsi_tape *un;
11778 	int instance = ddi_get_instance(dip);
11779 
11780 	un = ddi_get_soft_state(st_state, instance);
11781 
11782 	ST_FUNC(dip, st_print_cdb);
11783 
11784 #ifdef STDEBUG
11785 	if ((st_debug & 0x180) == 0x100) {
11786 		scsi_log(dip, label, level, "node %s cmd %s\n",
11787 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
11788 		return;
11789 	}
11790 #endif
11791 	(void) sprintf(buf, "%s for cmd(%s)", title, st_print_scsi_cmd(*cdb));
11792 	st_clean_print(dip, label, level, buf, cdb, len);
11793 }
11794 
11795 static void
11796 st_clean_print(dev_info_t *dev, char *label, uint_t level,
11797     char *title, char *data, int len)
11798 {
11799 	int	i;
11800 	int 	c;
11801 	char	*format;
11802 	char	buf[256];
11803 	uchar_t	byte;
11804 
11805 	ST_FUNC(dev, st_clean_print);
11806 
11807 
11808 	(void) sprintf(buf, "%s:\n", title);
11809 	scsi_log(dev, label, level, "%s", buf);
11810 	level = CE_CONT;
11811 	for (i = 0; i < len; ) {
11812 		buf[0] = 0;
11813 		for (c = 0; c < 8 && i < len; c++, i++) {
11814 			byte = (uchar_t)data[i];
11815 			if (byte < 0x10)
11816 				format = "0x0%x ";
11817 			else
11818 				format = "0x%x ";
11819 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
11820 		}
11821 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
11822 
11823 		scsi_log(dev, label, level, "%s\n", buf);
11824 	}
11825 }
11826 
11827 /*
11828  * Conditionally enabled debugging
11829  */
11830 #ifdef	STDEBUG
11831 static void
11832 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
11833 {
11834 	char tmpbuf[64];
11835 
11836 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
11837 
11838 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11839 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
11840 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
11841 	    count, count,
11842 	    wait == ASYNC_CMD ? "a" : "");
11843 }
11844 
11845 /*
11846  * Returns pointer to name of minor node name of device 'dev'.
11847  */
11848 static char *
11849 st_dev_name(dev_t dev)
11850 {
11851 	struct scsi_tape *un;
11852 	const char density[] = { 'l', 'm', 'h', 'c' };
11853 	static char name[32];
11854 	minor_t minor;
11855 	int instance;
11856 	int nprt = 0;
11857 
11858 	minor = getminor(dev);
11859 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
11860 	un = ddi_get_soft_state(st_state, instance);
11861 	if (un) {
11862 		ST_FUNC(ST_DEVINFO, st_dev_name);
11863 	}
11864 
11865 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
11866 
11867 	if (minor & MT_BSD) {
11868 		name[++nprt] = 'b';
11869 	}
11870 
11871 	if (minor & MT_NOREWIND) {
11872 		name[++nprt] = 'n';
11873 	}
11874 
11875 	/* NULL terminator */
11876 	name[++nprt] = 0;
11877 
11878 	return (name);
11879 }
11880 #endif	/* STDEBUG */
11881 
11882 /*
11883  * Soft error reporting, so far unique to each drive
11884  *
11885  * Currently supported: exabyte and DAT soft error reporting
11886  */
11887 static int
11888 st_report_exabyte_soft_errors(dev_t dev, int flag)
11889 {
11890 	uchar_t *sensep;
11891 	int amt;
11892 	int rval = 0;
11893 	char cdb[CDB_GROUP0], *c = cdb;
11894 	struct uscsi_cmd *com;
11895 
11896 	GET_SOFT_STATE(dev);
11897 
11898 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
11899 
11900 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11901 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
11902 	    dev, flag);
11903 
11904 	ASSERT(mutex_owned(ST_MUTEX));
11905 
11906 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
11907 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
11908 
11909 	*c++ = SCMD_REQUEST_SENSE;
11910 	*c++ = 0;
11911 	*c++ = 0;
11912 	*c++ = 0;
11913 	*c++ = TAPE_SENSE_LENGTH;
11914 	/*
11915 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
11916 	 */
11917 	*c   = (char)0x80;
11918 
11919 	com->uscsi_cdb = cdb;
11920 	com->uscsi_cdblen = CDB_GROUP0;
11921 	com->uscsi_bufaddr = (caddr_t)sensep;
11922 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
11923 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11924 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11925 
11926 	rval = st_uscsi_cmd(un, com, FKIOCTL);
11927 	if (rval || com->uscsi_status) {
11928 		goto done;
11929 	}
11930 
11931 	/*
11932 	 * was there enough data?
11933 	 */
11934 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
11935 
11936 	if ((amt >= 19) && un->un_kbytes_xferred) {
11937 		uint_t count, error_rate;
11938 		uint_t rate;
11939 
11940 		if (sensep[21] & CLN) {
11941 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11942 			    "Periodic head cleaning required");
11943 		}
11944 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
11945 			goto done;
11946 		}
11947 		/*
11948 		 * check if soft error reporting needs to be done.
11949 		 */
11950 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
11951 		count &= 0xffffff;
11952 		error_rate = (count * 100)/un->un_kbytes_xferred;
11953 
11954 #ifdef	STDEBUG
11955 		if (st_soft_error_report_debug) {
11956 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11957 			    "Exabyte Soft Error Report:\n");
11958 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11959 			    "read/write error counter: %d\n", count);
11960 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11961 			    "number of bytes transferred: %dK\n",
11962 			    un->un_kbytes_xferred);
11963 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11964 			    "error_rate: %d%%\n", error_rate);
11965 
11966 			if (amt >= 22) {
11967 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11968 				    "unit sense: 0x%b 0x%b 0x%b\n",
11969 				    sensep[19], SENSE_19_BITS,
11970 				    sensep[20], SENSE_20_BITS,
11971 				    sensep[21], SENSE_21_BITS);
11972 			}
11973 			if (amt >= 27) {
11974 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11975 				    "tracking retry counter: %d\n",
11976 				    sensep[26]);
11977 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11978 				    "read/write retry counter: %d\n",
11979 				    sensep[27]);
11980 			}
11981 		}
11982 #endif
11983 
11984 		if (flag & FWRITE) {
11985 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
11986 		} else {
11987 			rate = EXABYTE_READ_ERROR_THRESHOLD;
11988 		}
11989 		if (error_rate >= rate) {
11990 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11991 			    "Soft error rate (%d%%) during %s was too high",
11992 			    error_rate,
11993 			    ((flag & FWRITE) ? wrg_str : rdg_str));
11994 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11995 			    "Please, replace tape cartridge\n");
11996 		}
11997 	}
11998 
11999 done:
12000 	kmem_free(com, sizeof (*com));
12001 	kmem_free(sensep, TAPE_SENSE_LENGTH);
12002 
12003 	if (rval != 0) {
12004 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12005 		    "exabyte soft error reporting failed\n");
12006 	}
12007 	return (rval);
12008 }
12009 
12010 /*
12011  * this is very specific to Archive 4mm dat
12012  */
12013 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
12014 
12015 static int
12016 st_report_dat_soft_errors(dev_t dev, int flag)
12017 {
12018 	uchar_t *sensep;
12019 	int amt, i;
12020 	int rval = 0;
12021 	char cdb[CDB_GROUP1], *c = cdb;
12022 	struct uscsi_cmd *com;
12023 
12024 	GET_SOFT_STATE(dev);
12025 
12026 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
12027 
12028 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12029 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12030 
12031 	ASSERT(mutex_owned(ST_MUTEX));
12032 
12033 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12034 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12035 
12036 	*c++ = SCMD_LOG_SENSE_G1;
12037 	*c++ = 0;
12038 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
12039 	*c++ = 0;
12040 	*c++ = 0;
12041 	*c++ = 0;
12042 	*c++ = 2;
12043 	*c++ = 0;
12044 	*c++ = (char)LOG_SENSE_LENGTH;
12045 	*c   = 0;
12046 	com->uscsi_cdb    = cdb;
12047 	com->uscsi_cdblen  = CDB_GROUP1;
12048 	com->uscsi_bufaddr = (caddr_t)sensep;
12049 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
12050 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12051 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12052 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12053 	if (rval) {
12054 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12055 		    "DAT soft error reporting failed\n");
12056 	}
12057 	if (rval || com->uscsi_status) {
12058 		goto done;
12059 	}
12060 
12061 	/*
12062 	 * was there enough data?
12063 	 */
12064 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
12065 
12066 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
12067 		int total, retries, param_code;
12068 
12069 		total = -1;
12070 		retries = -1;
12071 		amt = sensep[3] + 4;
12072 
12073 
12074 #ifdef STDEBUG
12075 		if (st_soft_error_report_debug) {
12076 			(void) printf("logsense:");
12077 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
12078 				if (i % 16 == 0) {
12079 					(void) printf("\t\n");
12080 				}
12081 				(void) printf(" %x", sensep[i]);
12082 			}
12083 			(void) printf("\n");
12084 		}
12085 #endif
12086 
12087 		/*
12088 		 * parse the param_codes
12089 		 */
12090 		if (sensep[0] == 2 || sensep[0] == 3) {
12091 			for (i = 4; i < amt; i++) {
12092 				param_code = (sensep[i++] << 8);
12093 				param_code += sensep[i++];
12094 				i++; /* skip control byte */
12095 				if (param_code == 5) {
12096 					if (sensep[i++] == 4) {
12097 						total = (sensep[i++] << 24);
12098 						total += (sensep[i++] << 16);
12099 						total += (sensep[i++] << 8);
12100 						total += sensep[i];
12101 					}
12102 				} else if (param_code == 0x8007) {
12103 					if (sensep[i++] == 2) {
12104 						retries = sensep[i++] << 8;
12105 						retries += sensep[i];
12106 					}
12107 				} else {
12108 					i += sensep[i];
12109 				}
12110 			}
12111 		}
12112 
12113 		/*
12114 		 * if the log sense returned valid numbers then determine
12115 		 * the read and write error thresholds based on the amount of
12116 		 * data transferred
12117 		 */
12118 
12119 		if (total > 0 && retries > 0) {
12120 			short normal_retries = 0;
12121 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12122 			    "total xferred (%s) =%x, retries=%x\n",
12123 			    ((flag & FWRITE) ? wrg_str : rdg_str),
12124 			    total, retries);
12125 
12126 			if (flag & FWRITE) {
12127 				if (total <=
12128 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
12129 					normal_retries =
12130 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
12131 				} else {
12132 					normal_retries =
12133 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
12134 				}
12135 			} else {
12136 				if (total <=
12137 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
12138 					normal_retries =
12139 					    DAT_SMALL_READ_ERROR_THRESHOLD;
12140 				} else {
12141 					normal_retries =
12142 					    DAT_LARGE_READ_ERROR_THRESHOLD;
12143 				}
12144 			}
12145 
12146 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12147 			"normal retries=%d\n", normal_retries);
12148 
12149 			if (retries >= normal_retries) {
12150 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12151 				    "Soft error rate (retries = %d) during "
12152 				    "%s was too high",  retries,
12153 				    ((flag & FWRITE) ? wrg_str : rdg_str));
12154 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12155 				    "Periodic head cleaning required "
12156 				    "and/or replace tape cartridge\n");
12157 			}
12158 
12159 		} else if (total == -1 || retries == -1) {
12160 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12161 			    "log sense parameter code does not make sense\n");
12162 		}
12163 	}
12164 
12165 	/*
12166 	 * reset all values
12167 	 */
12168 	c = cdb;
12169 	*c++ = SCMD_LOG_SELECT_G1;
12170 	*c++ = 2;	/* this resets all values */
12171 	*c++ = (char)0xc0;
12172 	*c++ = 0;
12173 	*c++ = 0;
12174 	*c++ = 0;
12175 	*c++ = 0;
12176 	*c++ = 0;
12177 	*c++ = 0;
12178 	*c   = 0;
12179 	com->uscsi_bufaddr = NULL;
12180 	com->uscsi_buflen  = 0;
12181 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
12182 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12183 	if (rval) {
12184 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12185 		    "DAT soft error reset failed\n");
12186 	}
12187 done:
12188 	kmem_free(com, sizeof (*com));
12189 	kmem_free(sensep, LOG_SENSE_LENGTH);
12190 	return (rval);
12191 }
12192 
12193 static int
12194 st_report_soft_errors(dev_t dev, int flag)
12195 {
12196 	GET_SOFT_STATE(dev);
12197 
12198 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
12199 
12200 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12201 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12202 
12203 	ASSERT(mutex_owned(ST_MUTEX));
12204 
12205 	switch (un->un_dp->type) {
12206 	case ST_TYPE_EXB8500:
12207 	case ST_TYPE_EXABYTE:
12208 		return (st_report_exabyte_soft_errors(dev, flag));
12209 		/*NOTREACHED*/
12210 	case ST_TYPE_PYTHON:
12211 		return (st_report_dat_soft_errors(dev, flag));
12212 		/*NOTREACHED*/
12213 	default:
12214 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
12215 		return (-1);
12216 	}
12217 }
12218 
12219 /*
12220  * persistent error routines
12221  */
12222 
12223 /*
12224  * enable persistent errors, and set the throttle appropriately, checking
12225  * for flush-on-errors capability
12226  */
12227 static void
12228 st_turn_pe_on(struct scsi_tape *un)
12229 {
12230 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
12231 
12232 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
12233 	ASSERT(mutex_owned(ST_MUTEX));
12234 
12235 	un->un_persistence = 1;
12236 
12237 	/*
12238 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
12239 	 * enabled.  This will simplify the error handling for request senses
12240 	 */
12241 
12242 	if (un->un_arq_enabled && un->un_untagged_qing) {
12243 		uchar_t f_o_e;
12244 
12245 		mutex_exit(ST_MUTEX);
12246 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
12247 		    1 : 0;
12248 		mutex_enter(ST_MUTEX);
12249 
12250 		un->un_flush_on_errors = f_o_e;
12251 	} else {
12252 		un->un_flush_on_errors = 0;
12253 	}
12254 
12255 	if (un->un_flush_on_errors)
12256 		un->un_max_throttle = (uchar_t)st_max_throttle;
12257 	else
12258 		un->un_max_throttle = 1;
12259 
12260 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
12261 		un->un_max_throttle = 1;
12262 
12263 	/* this will send a marker pkt */
12264 	st_clear_pe(un);
12265 }
12266 
12267 /*
12268  * This turns persistent errors permanently off
12269  */
12270 static void
12271 st_turn_pe_off(struct scsi_tape *un)
12272 {
12273 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
12274 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
12275 	ASSERT(mutex_owned(ST_MUTEX));
12276 
12277 	/* turn it off for good */
12278 	un->un_persistence = 0;
12279 
12280 	/* this will send a marker pkt */
12281 	st_clear_pe(un);
12282 
12283 	/* turn off flush on error capability, if enabled */
12284 	if (un->un_flush_on_errors) {
12285 		mutex_exit(ST_MUTEX);
12286 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
12287 		mutex_enter(ST_MUTEX);
12288 	}
12289 
12290 
12291 	un->un_flush_on_errors = 0;
12292 }
12293 
12294 /*
12295  * This clear persistent errors, allowing more commands through, and also
12296  * sending a marker packet.
12297  */
12298 static void
12299 st_clear_pe(struct scsi_tape *un)
12300 {
12301 	ST_FUNC(ST_DEVINFO, st_clear_pe);
12302 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
12303 	ASSERT(mutex_owned(ST_MUTEX));
12304 
12305 	un->un_persist_errors = 0;
12306 	un->un_throttle = un->un_last_throttle = 1;
12307 	un->un_errno = 0;
12308 	st_hba_unflush(un);
12309 }
12310 
12311 /*
12312  * This will flag persistent errors, shutting everything down, if the
12313  * application had enabled persistent errors via MTIOCPERSISTENT
12314  */
12315 static void
12316 st_set_pe_flag(struct scsi_tape *un)
12317 {
12318 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
12319 	ASSERT(mutex_owned(ST_MUTEX));
12320 
12321 	if (un->un_persistence) {
12322 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
12323 		un->un_persist_errors = 1;
12324 		un->un_throttle = un->un_last_throttle = 0;
12325 		cv_broadcast(&un->un_sbuf_cv);
12326 	}
12327 }
12328 
12329 static int
12330 st_do_reserve(struct scsi_tape *un)
12331 {
12332 	int rval;
12333 
12334 	ST_FUNC(ST_DEVINFO, st_do_reserve);
12335 
12336 	/*
12337 	 * Issue a Throw-Away reserve command to clear the
12338 	 * check condition.
12339 	 * If the current behaviour of reserve/release is to
12340 	 * hold reservation across opens , and if a Bus reset
12341 	 * has been issued between opens then this command
12342 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
12343 	 * In this case return an EACCES so that user knows that
12344 	 * reservation has been lost in between opens.
12345 	 * If this error is not returned and we continue with
12346 	 * successful open , then user may think position of the
12347 	 * tape is still the same but inreality we would rewind the
12348 	 * tape and continue from BOT.
12349 	 */
12350 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12351 	if (rval) {
12352 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
12353 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
12354 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
12355 			un->un_errno = EACCES;
12356 			return (EACCES);
12357 		}
12358 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12359 	}
12360 	if (rval == 0) {
12361 		un->un_rsvd_status |= ST_INIT_RESERVE;
12362 	}
12363 
12364 	return (rval);
12365 }
12366 
12367 static int
12368 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb)
12369 {
12370 	int rval;
12371 	cmd_attribute const *attrib;
12372 
12373 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
12374 
12375 	/*
12376 	 * If already reserved no need to do it again.
12377 	 * Also if Reserve and Release are disabled Just return.
12378 	 */
12379 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12380 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12381 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12382 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12383 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
12384 		    st_print_scsi_cmd((uchar_t)cdb[0]));
12385 		return (0);
12386 	}
12387 
12388 	/* See if command is on the list */
12389 	attrib = st_lookup_cmd_attribute(cdb[0]);
12390 
12391 	if (attrib == NULL) {
12392 		rval = 1; /* Not found, when in doubt reserve */
12393 	} else if ((attrib->requires_reserve) != 0) {
12394 		rval = 1;
12395 	} else if ((attrib->reserve_byte) != 0) {
12396 		/*
12397 		 * cmd is on list.
12398 		 * if byte is zero always allowed.
12399 		 */
12400 		rval = 1;
12401 	} else if (((cdb[attrib->reserve_byte]) &
12402 	    (attrib->reserve_mask)) != 0) {
12403 		rval = 1;
12404 	} else {
12405 		rval = 0;
12406 	}
12407 
12408 	if (rval) {
12409 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12410 		    "Command %s requires reservation",
12411 		    st_print_scsi_cmd(cdb[0]));
12412 
12413 		rval = st_do_reserve(un);
12414 	}
12415 
12416 	return (rval);
12417 }
12418 
12419 static int
12420 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
12421 {
12422 	int rval;
12423 	cmd_attribute const *attrib;
12424 
12425 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
12426 
12427 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12428 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12429 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12430 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12431 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
12432 		    st_print_scsi_cmd(cmd));
12433 		return (0);
12434 	}
12435 
12436 	/* search for this command on the list */
12437 	attrib = st_lookup_cmd_attribute(cmd);
12438 
12439 	if (attrib == NULL) {
12440 		rval = 1; /* Not found, when in doubt reserve */
12441 	} else if ((attrib->requires_reserve) != 0) {
12442 		rval = 1;
12443 	} else if ((attrib->reserve_byte) != 0) {
12444 		/*
12445 		 * cmd is on list.
12446 		 * if byte is zero always allowed.
12447 		 */
12448 		rval = 1;
12449 	} else if (((attrib->reserve_mask) & cnt) != 0) {
12450 		rval = 1;
12451 	} else {
12452 		rval = 0;
12453 	}
12454 
12455 	if (rval) {
12456 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12457 		    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
12458 
12459 		rval = st_do_reserve(un);
12460 	}
12461 
12462 	return (rval);
12463 }
12464 
12465 static int
12466 st_reserve_release(struct scsi_tape *un, int cmd, ubufunc_t ubf)
12467 {
12468 	struct uscsi_cmd	uscsi_cmd;
12469 	int			rval;
12470 	char			cdb[CDB_GROUP0];
12471 	struct scsi_arq_status	stat;
12472 
12473 
12474 
12475 	ST_FUNC(ST_DEVINFO, st_reserve_release);
12476 
12477 	ASSERT(mutex_owned(ST_MUTEX));
12478 
12479 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12480 	    "st_reserve_release: %s \n",
12481 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
12482 
12483 	bzero(&cdb, CDB_GROUP0);
12484 	if (cmd == ST_RELEASE) {
12485 		cdb[0] = SCMD_RELEASE;
12486 	} else {
12487 		cdb[0] = SCMD_RESERVE;
12488 	}
12489 	bzero(&uscsi_cmd, sizeof (struct uscsi_cmd));
12490 	uscsi_cmd.uscsi_flags = USCSI_WRITE | USCSI_RQENABLE;
12491 	uscsi_cmd.uscsi_cdb = cdb;
12492 	uscsi_cmd.uscsi_cdblen = CDB_GROUP0;
12493 	uscsi_cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
12494 	uscsi_cmd.uscsi_rqbuf = (caddr_t)&stat;
12495 	uscsi_cmd.uscsi_rqlen = sizeof (stat);
12496 
12497 	rval = ubf(un, &uscsi_cmd, FKIOCTL);
12498 
12499 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12500 	    "st_reserve_release: rval(1)=%d\n", rval);
12501 
12502 	if (rval) {
12503 		if (uscsi_cmd.uscsi_status == STATUS_RESERVATION_CONFLICT) {
12504 			rval = EACCES;
12505 		}
12506 		/*
12507 		 * dynamically turn off reserve/release support
12508 		 * in case of drives which do not support
12509 		 * reserve/release command(ATAPI drives).
12510 		 */
12511 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
12512 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
12513 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
12514 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12515 				    "Tape unit does not support "
12516 				    "reserve/release \n");
12517 			}
12518 			rval = 0;
12519 		}
12520 	}
12521 	return (rval);
12522 }
12523 
12524 static int
12525 st_take_ownership(struct scsi_tape *un)
12526 {
12527 	int rval;
12528 
12529 	ST_FUNC(ST_DEVINFO, st_take_ownership);
12530 
12531 	ASSERT(mutex_owned(ST_MUTEX));
12532 
12533 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12534 	    "st_take_ownership: Entering ...\n");
12535 
12536 
12537 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12538 	/*
12539 	 * XXX -> Should reset be done only if we get EACCES.
12540 	 * .
12541 	 */
12542 	if (rval) {
12543 		if (st_reset(un, RESET_LUN) == 0) {
12544 			return (EIO);
12545 		}
12546 		un->un_rsvd_status &=
12547 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
12548 
12549 		mutex_exit(ST_MUTEX);
12550 		delay(drv_usectohz(ST_RESERVATION_DELAY));
12551 		mutex_enter(ST_MUTEX);
12552 		/*
12553 		 * remove the check condition.
12554 		 */
12555 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12556 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12557 		if (rval != 0) {
12558 			if ((st_reserve_release(un, ST_RESERVE, st_uscsi_cmd))
12559 			    != 0) {
12560 				rval = (un->un_rsvd_status &
12561 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
12562 				return (rval);
12563 			}
12564 		}
12565 		/*
12566 		 * Set tape state to ST_STATE_OFFLINE , in case if
12567 		 * the user wants to continue and start using
12568 		 * the tape.
12569 		 */
12570 		un->un_state = ST_STATE_OFFLINE;
12571 		un->un_rsvd_status |= ST_INIT_RESERVE;
12572 	}
12573 	return (rval);
12574 }
12575 
12576 static int
12577 st_create_errstats(struct scsi_tape *un, int instance)
12578 {
12579 	char	kstatname[KSTAT_STRLEN];
12580 
12581 	ST_FUNC(ST_DEVINFO, st_create_errstats);
12582 
12583 	/*
12584 	 * Create device error kstats
12585 	 */
12586 
12587 	if (un->un_errstats == (kstat_t *)0) {
12588 		(void) sprintf(kstatname, "st%d,err", instance);
12589 		un->un_errstats = kstat_create("sterr", instance, kstatname,
12590 		    "device_error", KSTAT_TYPE_NAMED,
12591 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
12592 		    KSTAT_FLAG_PERSISTENT);
12593 
12594 		if (un->un_errstats) {
12595 			struct st_errstats	*stp;
12596 
12597 			stp = (struct st_errstats *)un->un_errstats->ks_data;
12598 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
12599 			    KSTAT_DATA_ULONG);
12600 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
12601 			    KSTAT_DATA_ULONG);
12602 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
12603 			    KSTAT_DATA_ULONG);
12604 			kstat_named_init(&stp->st_vid, "Vendor",
12605 			    KSTAT_DATA_CHAR);
12606 			kstat_named_init(&stp->st_pid, "Product",
12607 			    KSTAT_DATA_CHAR);
12608 			kstat_named_init(&stp->st_revision, "Revision",
12609 			    KSTAT_DATA_CHAR);
12610 			kstat_named_init(&stp->st_serial, "Serial No",
12611 			    KSTAT_DATA_CHAR);
12612 			un->un_errstats->ks_private = un;
12613 			un->un_errstats->ks_update = nulldev;
12614 			kstat_install(un->un_errstats);
12615 			/*
12616 			 * Fill in the static data
12617 			 */
12618 			(void) strncpy(&stp->st_vid.value.c[0],
12619 			    ST_INQUIRY->inq_vid, 8);
12620 			/*
12621 			 * XXX:  Emulex MT-02 (and emulators) predates
12622 			 *	 SCSI-1 and has no vid & pid inquiry data.
12623 			 */
12624 			if (ST_INQUIRY->inq_len != 0) {
12625 				(void) strncpy(&stp->st_pid.value.c[0],
12626 				    ST_INQUIRY->inq_pid, 16);
12627 				(void) strncpy(&stp->st_revision.value.c[0],
12628 				    ST_INQUIRY->inq_revision, 4);
12629 				(void) strncpy(&stp->st_serial.value.c[0],
12630 				    ST_INQUIRY->inq_serial, 12);
12631 			}
12632 		}
12633 	}
12634 	return (0);
12635 }
12636 
12637 static int
12638 st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos)
12639 {
12640 	int rval;
12641 	bufunc_t bf = (ubf == st_uscsi_rcmd) ? st_rcmd : st_cmd;
12642 
12643 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
12644 
12645 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
12646 	ASSERT(mutex_owned(ST_MUTEX));
12647 
12648 	/* Can't restore an invalid position */
12649 	if (pos->pmode == invalid) {
12650 		return (4);
12651 	}
12652 
12653 	/*
12654 	 * Assumtions:
12655 	 *	If a position was read and is in logical position mode.
12656 	 *	If a drive supports read position it supports locate.
12657 	 *	If the read position type is not NO_POS. even though
12658 	 *	   a read position make not have been attemped yet.
12659 	 *
12660 	 *	The drive can locate to the position.
12661 	 */
12662 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
12663 		/*
12664 		 * If position mode is logical or legacy mode try
12665 		 * to locate there as it is faster.
12666 		 * If it fails try the old way.
12667 		 */
12668 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12669 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
12670 		    pos->lgclblkno);
12671 
12672 		if (st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
12673 		    pos->lgclblkno, pos->partition) == 0) {
12674 			/* Assume we are there copy rest of position back */
12675 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
12676 				COPY_POS(&un->un_pos, pos);
12677 			}
12678 			return (0);
12679 		}
12680 
12681 		/*
12682 		 * If logical block locate failed to restore a logical
12683 		 * position, can't recover.
12684 		 */
12685 		if (pos->pmode == logical) {
12686 			return (-1);
12687 		}
12688 	}
12689 
12690 
12691 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12692 	    "Restoring tape position at fileno=%x, blkno=%x....",
12693 	    pos->fileno, pos->blkno);
12694 
12695 	/*
12696 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
12697 	 * so as not to rewind tape on RESETS: Gee, Has life ever
12698 	 * been simple in tape land ?
12699 	 */
12700 	rval = bf(un, SCMD_REWIND, 0, SYNC_CMD);
12701 	if (rval) {
12702 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12703 		    "Failed to restore the last file and block position: In"
12704 		    " this state, Tape will be loaded at BOT during next open");
12705 		un->un_pos.pmode = invalid;
12706 		return (rval);
12707 	}
12708 
12709 	/* If the position was as the result of back space file */
12710 	if (pos->blkno > (INF / 2)) {
12711 		/* Go one extra file forward */
12712 		pos->fileno++;
12713 		/* Figure how many blocks to back into the previous file */
12714 		pos->blkno = -(INF - pos->blkno);
12715 	}
12716 
12717 	/* Go to requested fileno */
12718 	if (pos->fileno) {
12719 		rval = st_cmd(un, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
12720 		if (rval) {
12721 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12722 			    "Failed to restore the last file position: In this "
12723 			    " state, Tape will be loaded at BOT during next"
12724 			    " open %d", __LINE__);
12725 			un->un_pos.pmode = invalid;
12726 			pos->pmode = invalid;
12727 			return (rval);
12728 		}
12729 	}
12730 
12731 	/*
12732 	 * If backing into a file we already did an extra file forward.
12733 	 * Now we have to back over the filemark to get to the end of
12734 	 * the previous file. The blkno has been ajusted to a negative
12735 	 * value so we will get to the expected location.
12736 	 */
12737 	if (pos->blkno) {
12738 		rval = bf(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
12739 		if (rval) {
12740 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12741 			    "Failed to restore the last file position: In this "
12742 			    " state, Tape will be loaded at BOT during next"
12743 			    " open %d", __LINE__);
12744 			un->un_pos.pmode = invalid;
12745 			pos->pmode = invalid;
12746 			return (rval);
12747 		}
12748 	}
12749 
12750 	/*
12751 	 * The position mode, block and fileno should be correct,
12752 	 * This updates eof and logical position information.
12753 	 */
12754 	un->un_pos.eof = pos->eof;
12755 	un->un_pos.lgclblkno = pos->lgclblkno;
12756 
12757 	return (0);
12758 }
12759 
12760 /*
12761  * check sense key, ASC, ASCQ in order to determine if the tape needs
12762  * to be ejected
12763  */
12764 
12765 static int
12766 st_check_asc_ascq(struct scsi_tape *un)
12767 {
12768 	struct scsi_extended_sense *sensep = ST_RQSENSE;
12769 	struct tape_failure_code   *code;
12770 
12771 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
12772 
12773 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
12774 		if ((code->key  == sensep->es_key) &&
12775 		    (code->add_code  == sensep->es_add_code) &&
12776 		    (code->qual_code == sensep->es_qual_code))
12777 			return (1);
12778 	}
12779 	return (0);
12780 }
12781 
12782 /*
12783  * st_logpage_supported() sends a Log Sense command with
12784  * page code = 0 = Supported Log Pages Page to the device,
12785  * to see whether the page 'page' is supported.
12786  * Return values are:
12787  * -1 if the Log Sense command fails
12788  * 0 if page is not supported
12789  * 1 if page is supported
12790  */
12791 
12792 static int
12793 st_logpage_supported(struct scsi_tape *un, uchar_t page)
12794 {
12795 	uchar_t *sp, *sensep;
12796 	unsigned length;
12797 	struct uscsi_cmd *com;
12798 	int rval;
12799 	char cdb[CDB_GROUP1] = {
12800 		SCMD_LOG_SENSE_G1,
12801 		0,
12802 		SUPPORTED_LOG_PAGES_PAGE,
12803 		0,
12804 		0,
12805 		0,
12806 		0,
12807 		0,
12808 		(char)LOG_SENSE_LENGTH,
12809 		0
12810 	};
12811 
12812 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
12813 
12814 	ASSERT(mutex_owned(ST_MUTEX));
12815 
12816 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12817 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12818 
12819 	com->uscsi_cdb = cdb;
12820 	com->uscsi_cdblen = CDB_GROUP1;
12821 	com->uscsi_bufaddr = (caddr_t)sensep;
12822 	com->uscsi_buflen = LOG_SENSE_LENGTH;
12823 	com->uscsi_flags =
12824 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12825 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12826 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12827 	if (rval || com->uscsi_status) {
12828 		/* uscsi-command failed */
12829 		rval = -1;
12830 	} else {
12831 
12832 		sp = sensep + 3;
12833 
12834 		for (length = *sp++; length > 0; length--, sp++) {
12835 
12836 			if (*sp == page) {
12837 				rval = 1;
12838 				break;
12839 			}
12840 		}
12841 	}
12842 	kmem_free(com, sizeof (struct uscsi_cmd));
12843 	kmem_free(sensep, LOG_SENSE_LENGTH);
12844 	return (rval);
12845 }
12846 
12847 
12848 /*
12849  * st_check_clean_bit() gets the status of the tape's cleaning bit.
12850  *
12851  * If the device does support the TapeAlert log page, then the cleaning bit
12852  * information will be read from this page. Otherwise we will see if one of
12853  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
12854  * the device, which means, that we can get the cleaning bit information via
12855  * a RequestSense command.
12856  * If both methods of getting cleaning bit information are not supported
12857  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
12858  * returns with
12859  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
12860  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
12861  * If the call to st_uscsi_cmd() to do the Log Sense or the Request Sense
12862  * command fails, or if the amount of Request Sense data is not enough, then
12863  *  st_check_clean_bit() returns with -1.
12864  */
12865 
12866 static int
12867 st_check_clean_bit(struct scsi_tape *un)
12868 {
12869 	int rval = 0;
12870 
12871 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
12872 
12873 	ASSERT(mutex_owned(ST_MUTEX));
12874 
12875 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
12876 		return (rval);
12877 	}
12878 
12879 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
12880 
12881 		rval = st_logpage_supported(un, TAPE_SEQUENTIAL_PAGE);
12882 		if (rval == 1) {
12883 
12884 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
12885 		}
12886 
12887 		rval = st_logpage_supported(un, TAPE_ALERT_PAGE);
12888 		if (rval == 1) {
12889 
12890 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
12891 		}
12892 
12893 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
12894 
12895 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
12896 		}
12897 	}
12898 
12899 	rval = 0;
12900 
12901 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
12902 
12903 		rval = st_check_sequential_clean_bit(un);
12904 	}
12905 
12906 	if ((rval <= 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
12907 
12908 		rval = st_check_alert_flags(un);
12909 	}
12910 
12911 	if ((rval <= 0) && (un->un_dp->options & ST_CLN_MASK)) {
12912 
12913 		rval = st_check_sense_clean_bit(un);
12914 	}
12915 
12916 	if (rval < 0) {
12917 		return (rval);
12918 	}
12919 
12920 	/*
12921 	 * If found a supported means to check need to clean.
12922 	 */
12923 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
12924 
12925 		/*
12926 		 * head needs to be cleaned.
12927 		 */
12928 		if (rval & MTF_TAPE_HEAD_DIRTY) {
12929 
12930 			/*
12931 			 * Print log message only first time
12932 			 * found needing cleaned.
12933 			 */
12934 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
12935 
12936 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12937 				    "Periodic head cleaning required");
12938 
12939 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
12940 			}
12941 
12942 		} else {
12943 
12944 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
12945 		}
12946 	}
12947 
12948 	return (rval);
12949 }
12950 
12951 
12952 static int
12953 st_check_sequential_clean_bit(struct scsi_tape *un)
12954 {
12955 	int rval;
12956 	int ix;
12957 	ushort_t parameter;
12958 	struct uscsi_cmd *cmd;
12959 	struct log_sequential_page *sp;
12960 	struct log_sequential_page_parameter *prm;
12961 	char cdb[CDB_GROUP1] = {
12962 		SCMD_LOG_SENSE_G1,
12963 		0,
12964 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
12965 		0,
12966 		0,
12967 		0,
12968 		0,
12969 		(char)(sizeof (struct log_sequential_page) >> 8),
12970 		(char)(sizeof (struct log_sequential_page)),
12971 		0
12972 	};
12973 
12974 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
12975 
12976 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12977 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
12978 
12979 	cmd->uscsi_flags   =
12980 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12981 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12982 	cmd->uscsi_cdb	   = cdb;
12983 	cmd->uscsi_cdblen  = CDB_GROUP1;
12984 	cmd->uscsi_bufaddr = (caddr_t)sp;
12985 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
12986 
12987 	rval = st_uscsi_cmd(un, cmd, FKIOCTL);
12988 
12989 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
12990 
12991 		rval = -1;
12992 
12993 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
12994 
12995 		rval = -1;
12996 	}
12997 
12998 	prm = &sp->param[0];
12999 
13000 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
13001 
13002 		if (prm->log_param.length == 0) {
13003 			break;
13004 		}
13005 
13006 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
13007 		    (prm->log_param.pc_lo & 0xff));
13008 
13009 		if (parameter == SEQUENTIAL_NEED_CLN) {
13010 
13011 			rval = MTF_TAPE_CLN_SUPPORTED;
13012 			if (prm->param_value[prm->log_param.length - 1]) {
13013 
13014 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13015 				    "sequential log says head dirty\n");
13016 				rval |= MTF_TAPE_HEAD_DIRTY;
13017 			}
13018 		}
13019 		prm = (struct log_sequential_page_parameter *)
13020 		    &prm->param_value[prm->log_param.length];
13021 	}
13022 
13023 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13024 	kmem_free(sp,  sizeof (struct log_sequential_page));
13025 
13026 	return (rval);
13027 }
13028 
13029 
13030 static int
13031 st_check_alert_flags(struct scsi_tape *un)
13032 {
13033 	struct st_tape_alert *ta;
13034 	struct uscsi_cmd *com;
13035 	unsigned ix, length;
13036 	int rval;
13037 	tape_alert_flags flag;
13038 	char cdb[CDB_GROUP1] = {
13039 		SCMD_LOG_SENSE_G1,
13040 		0,
13041 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
13042 		0,
13043 		0,
13044 		0,
13045 		0,
13046 		(char)(sizeof (struct st_tape_alert) >> 8),
13047 		(char)(sizeof (struct st_tape_alert)),
13048 		0
13049 	};
13050 
13051 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
13052 
13053 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13054 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
13055 
13056 	com->uscsi_cdb = cdb;
13057 	com->uscsi_cdblen = CDB_GROUP1;
13058 	com->uscsi_bufaddr = (caddr_t)ta;
13059 	com->uscsi_buflen = sizeof (struct st_tape_alert);
13060 	com->uscsi_flags =
13061 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13062 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13063 
13064 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13065 
13066 	if (rval || com->uscsi_status || com->uscsi_resid) {
13067 
13068 		rval = -1; /* uscsi-command failed */
13069 
13070 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
13071 
13072 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13073 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
13074 		rval = -1;
13075 	}
13076 
13077 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
13078 
13079 
13080 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
13081 
13082 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13083 		    "TapeAlert length %d\n", length);
13084 	}
13085 
13086 
13087 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
13088 
13089 		/*
13090 		 * if rval is bad before the first pass don't bother
13091 		 */
13092 		if (ix == 0 && rval != 0) {
13093 
13094 			break;
13095 		}
13096 
13097 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
13098 		    ta->param[ix].log_param.pc_lo);
13099 
13100 		if ((ta->param[ix].param_value & 1) == 0) {
13101 			continue;
13102 		}
13103 		/*
13104 		 * check to see if current parameter is of interest.
13105 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
13106 		 */
13107 		if ((flag == TAF_CLEAN_NOW) ||
13108 		    (flag == TAF_CLEAN_PERIODIC) ||
13109 		    ((flag == CLEAN_FOR_ERRORS) &&
13110 		    (un->un_dp->type == ST_TYPE_STK9840))) {
13111 
13112 			rval = MTF_TAPE_CLN_SUPPORTED;
13113 
13114 
13115 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13116 			    "alert_page drive needs clean %d\n", flag);
13117 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
13118 			rval |= MTF_TAPE_HEAD_DIRTY;
13119 
13120 		} else if (flag == TAF_CLEANING_MEDIA) {
13121 
13122 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13123 			    "alert_page drive was cleaned\n");
13124 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
13125 		}
13126 
13127 	}
13128 
13129 	/*
13130 	 * Report it as dirty till we see it cleaned
13131 	 */
13132 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
13133 
13134 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13135 		    "alert_page still dirty\n");
13136 		rval |= MTF_TAPE_HEAD_DIRTY;
13137 	}
13138 
13139 	kmem_free(com, sizeof (struct uscsi_cmd));
13140 	kmem_free(ta,  sizeof (struct st_tape_alert));
13141 
13142 	return (rval);
13143 }
13144 
13145 
13146 static int
13147 st_check_sense_clean_bit(struct scsi_tape *un)
13148 {
13149 	uchar_t *sensep;
13150 	char cdb[CDB_GROUP0];
13151 	struct uscsi_cmd *com;
13152 	ushort_t byte_pos;
13153 	uchar_t bit_mask;
13154 	unsigned length;
13155 	int index;
13156 	int rval;
13157 
13158 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
13159 
13160 	/*
13161 	 * Since this tape does not support Tape Alert,
13162 	 * we now try to get the cleanbit status via
13163 	 * Request Sense.
13164 	 */
13165 
13166 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
13167 
13168 		index = 0;
13169 
13170 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
13171 
13172 		index = 1;
13173 
13174 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
13175 
13176 		index = 2;
13177 
13178 	} else {
13179 
13180 		return (-1);
13181 	}
13182 
13183 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
13184 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
13185 	length = byte_pos + 1;
13186 
13187 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13188 	sensep = kmem_zalloc(length, KM_SLEEP);
13189 
13190 	cdb[0] = SCMD_REQUEST_SENSE;
13191 	cdb[1] = 0;
13192 	cdb[2] = 0;
13193 	cdb[3] = 0;
13194 	cdb[4] = (char)length;
13195 	cdb[5] = 0;
13196 
13197 	com->uscsi_cdb = cdb;
13198 	com->uscsi_cdblen = CDB_GROUP0;
13199 	com->uscsi_bufaddr = (caddr_t)sensep;
13200 	com->uscsi_buflen = length;
13201 	com->uscsi_flags =
13202 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13203 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13204 
13205 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13206 
13207 	if (rval || com->uscsi_status || com->uscsi_resid) {
13208 
13209 		rval = -1;
13210 
13211 	} else {
13212 
13213 		rval = MTF_TAPE_CLN_SUPPORTED;
13214 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
13215 
13216 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13217 			    "sense data says head dirty\n");
13218 			rval |= MTF_TAPE_HEAD_DIRTY;
13219 		}
13220 	}
13221 
13222 	kmem_free(com, sizeof (struct uscsi_cmd));
13223 	kmem_free(sensep, length);
13224 	return (rval);
13225 }
13226 
13227 /*
13228  * st_clear_unit_attention
13229  *
13230  *  	run test unit ready's to clear out outstanding
13231  * 	unit attentions.
13232  * 	returns zero for SUCCESS or the errno from st_cmd call
13233  */
13234 static int
13235 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
13236 {
13237 	int	i    = 0;
13238 	int	rval;
13239 
13240 	GET_SOFT_STATE(dev_instance);
13241 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
13242 
13243 	do {
13244 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
13245 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
13246 	return (rval);
13247 }
13248 
13249 static void
13250 st_calculate_timeouts(struct scsi_tape *un)
13251 {
13252 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
13253 
13254 	if (un->un_dp->non_motion_timeout == 0) {
13255 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13256 			un->un_dp->non_motion_timeout =
13257 			    st_io_time * st_long_timeout_x;
13258 		} else {
13259 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
13260 		}
13261 	}
13262 
13263 	if (un->un_dp->io_timeout == 0) {
13264 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13265 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
13266 		} else {
13267 			un->un_dp->io_timeout = (ushort_t)st_io_time;
13268 		}
13269 	}
13270 
13271 	if (un->un_dp->rewind_timeout == 0) {
13272 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13273 			un->un_dp->rewind_timeout =
13274 			    st_space_time * st_long_timeout_x;
13275 		} else {
13276 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
13277 		}
13278 	}
13279 
13280 	if (un->un_dp->space_timeout == 0) {
13281 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13282 			un->un_dp->space_timeout =
13283 			    st_space_time * st_long_timeout_x;
13284 		} else {
13285 			un->un_dp->space_timeout = (ushort_t)st_space_time;
13286 		}
13287 	}
13288 
13289 	if (un->un_dp->load_timeout == 0) {
13290 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13291 			un->un_dp->load_timeout =
13292 			    st_space_time * st_long_timeout_x;
13293 		} else {
13294 			un->un_dp->load_timeout = (ushort_t)st_space_time;
13295 		}
13296 	}
13297 
13298 	if (un->un_dp->unload_timeout == 0) {
13299 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13300 			un->un_dp->unload_timeout =
13301 			    st_space_time * st_long_timeout_x;
13302 		} else {
13303 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
13304 		}
13305 	}
13306 
13307 	if (un->un_dp->erase_timeout == 0) {
13308 		if (un->un_dp->options & ST_LONG_ERASE) {
13309 			un->un_dp->erase_timeout =
13310 			    st_space_time * st_long_space_time_x;
13311 		} else {
13312 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
13313 		}
13314 	}
13315 }
13316 
13317 
13318 static writablity
13319 st_is_not_wormable(struct scsi_tape *un)
13320 {
13321 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
13322 	return (RDWR);
13323 }
13324 
13325 static writablity
13326 st_is_hp_dat_tape_worm(struct scsi_tape *un)
13327 {
13328 	writablity wrt;
13329 
13330 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
13331 
13332 	/* Mode sense should be current */
13333 	if (un->un_mspl->media_type == 1) {
13334 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13335 		    "Drive has WORM media loaded\n");
13336 		wrt = WORM;
13337 	} else {
13338 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13339 		    "Drive has non WORM media loaded\n");
13340 		wrt = RDWR;
13341 	}
13342 	return (wrt);
13343 }
13344 
13345 #define	HP_DAT_INQUIRY 0x4A
13346 static writablity
13347 st_is_hp_dat_worm(struct scsi_tape *un)
13348 {
13349 	char *buf;
13350 	int result;
13351 	writablity wrt;
13352 
13353 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
13354 
13355 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
13356 
13357 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
13358 
13359 	if (result != 0) {
13360 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13361 		    "Read Standard Inquiry for WORM support failed");
13362 		wrt = FAILED;
13363 	} else if ((buf[40] & 1) == 0) {
13364 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13365 		    "Drive is NOT WORMable\n");
13366 		/* This drive doesn't support it so don't check again */
13367 		un->un_dp->options &= ~ST_WORMABLE;
13368 		wrt = RDWR;
13369 		un->un_wormable = st_is_not_wormable;
13370 	} else {
13371 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13372 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13373 		un->un_wormable = st_is_hp_dat_tape_worm;
13374 		wrt = un->un_wormable(un);
13375 	}
13376 
13377 	kmem_free(buf, HP_DAT_INQUIRY);
13378 
13379 	/*
13380 	 * If drive doesn't support it no point in checking further.
13381 	 */
13382 	return (wrt);
13383 }
13384 
13385 static writablity
13386 st_is_hp_lto_tape_worm(struct scsi_tape *un)
13387 {
13388 	writablity wrt;
13389 
13390 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
13391 
13392 	/* Mode sense should be current */
13393 	switch (un->un_mspl->media_type) {
13394 	case 0x00:
13395 		switch (un->un_mspl->density) {
13396 		case 0x40:
13397 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13398 			    "Drive has standard Gen I media loaded\n");
13399 			break;
13400 		case 0x42:
13401 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13402 			    "Drive has standard Gen II media loaded\n");
13403 			break;
13404 		case 0x44:
13405 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13406 			    "Drive has standard Gen III media loaded\n");
13407 			break;
13408 		case 0x46:
13409 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13410 			    "Drive has standard Gen IV media loaded\n");
13411 			break;
13412 		default:
13413 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13414 			    "Drive has standard unknown 0x%X media loaded\n",
13415 			    un->un_mspl->density);
13416 		}
13417 		wrt = RDWR;
13418 		break;
13419 	case 0x01:
13420 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13421 		    "Drive has WORM medium loaded\n");
13422 		wrt = WORM;
13423 		break;
13424 	case 0x80:
13425 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13426 		    "Drive has CD-ROM emulation medium loaded\n");
13427 		wrt = WORM;
13428 		break;
13429 	default:
13430 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13431 		    "Drive has an unexpected medium type 0x%X loaded\n",
13432 		    un->un_mspl->media_type);
13433 		wrt = RDWR;
13434 	}
13435 
13436 	return (wrt);
13437 }
13438 
13439 #define	LTO_REQ_INQUIRY 44
13440 static writablity
13441 st_is_hp_lto_worm(struct scsi_tape *un)
13442 {
13443 	char *buf;
13444 	int result;
13445 	writablity wrt;
13446 
13447 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
13448 
13449 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
13450 
13451 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
13452 
13453 	if (result != 0) {
13454 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13455 		    "Read Standard Inquiry for WORM support failed");
13456 		wrt = FAILED;
13457 	} else if ((buf[40] & 1) == 0) {
13458 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13459 		    "Drive is NOT WORMable\n");
13460 		/* This drive doesn't support it so don't check again */
13461 		un->un_dp->options &= ~ST_WORMABLE;
13462 		wrt = RDWR;
13463 		un->un_wormable = st_is_not_wormable;
13464 	} else {
13465 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13466 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13467 		un->un_wormable = st_is_hp_lto_tape_worm;
13468 		wrt = un->un_wormable(un);
13469 	}
13470 
13471 	kmem_free(buf, LTO_REQ_INQUIRY);
13472 
13473 	/*
13474 	 * If drive doesn't support it no point in checking further.
13475 	 */
13476 	return (wrt);
13477 }
13478 
13479 static writablity
13480 st_is_t10_worm_device(struct scsi_tape *un)
13481 {
13482 	writablity wrt;
13483 
13484 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
13485 
13486 	if (un->un_mspl->media_type == 0x3c) {
13487 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13488 		    "Drive has WORM media loaded\n");
13489 		wrt = WORM;
13490 	} else {
13491 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13492 		    "Drive has non WORM media loaded\n");
13493 		wrt = RDWR;
13494 	}
13495 	return (wrt);
13496 }
13497 
13498 #define	SEQ_CAP_PAGE	(char)0xb0
13499 static writablity
13500 st_is_t10_worm(struct scsi_tape *un)
13501 {
13502 	char *buf;
13503 	int result;
13504 	writablity wrt;
13505 
13506 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
13507 
13508 	buf = kmem_zalloc(6, KM_SLEEP);
13509 
13510 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
13511 
13512 	if (result != 0) {
13513 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13514 		    "Read Vitial Inquiry for Sequental Capability"
13515 		    " WORM support failed %x", result);
13516 		wrt = FAILED;
13517 	} else if ((buf[4] & 1) == 0) {
13518 		ASSERT(buf[1] == SEQ_CAP_PAGE);
13519 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13520 		    "Drive is NOT WORMable\n");
13521 		/* This drive doesn't support it so don't check again */
13522 		un->un_dp->options &= ~ST_WORMABLE;
13523 		wrt = RDWR;
13524 		un->un_wormable = st_is_not_wormable;
13525 	} else {
13526 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13527 		    "Drive supports WORM\n");
13528 		un->un_wormable = st_is_t10_worm_device;
13529 		wrt = un->un_wormable(un);
13530 	}
13531 
13532 	kmem_free(buf, 6);
13533 
13534 	return (wrt);
13535 }
13536 
13537 
13538 #define	STK_REQ_SENSE 26
13539 
13540 static writablity
13541 st_is_stk_worm(struct scsi_tape *un)
13542 {
13543 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
13544 	struct scsi_extended_sense *sense;
13545 	struct uscsi_cmd *cmd;
13546 	char *buf;
13547 	int result;
13548 	writablity wrt;
13549 
13550 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
13551 
13552 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13553 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
13554 	sense = (struct scsi_extended_sense *)buf;
13555 
13556 	cmd->uscsi_flags = USCSI_READ;
13557 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13558 	cmd->uscsi_cdb = &cdb[0];
13559 	cmd->uscsi_bufaddr = buf;
13560 	cmd->uscsi_buflen = STK_REQ_SENSE;
13561 	cmd->uscsi_cdblen = CDB_GROUP0;
13562 	cmd->uscsi_rqlen = 0;
13563 	cmd->uscsi_rqbuf = NULL;
13564 
13565 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
13566 
13567 	if (result != 0 || cmd->uscsi_status != 0) {
13568 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13569 		    "Request Sense for WORM failed");
13570 		wrt = RDWR;
13571 	} else if (sense->es_add_len + 8 < 24) {
13572 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13573 		    "Drive didn't send enough sense data for WORM byte %d\n",
13574 		    sense->es_add_len + 8);
13575 		wrt = RDWR;
13576 		un->un_wormable = st_is_not_wormable;
13577 	} else if ((buf[24]) & 0x02) {
13578 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13579 		    "Drive has WORM tape loaded\n");
13580 		wrt = WORM;
13581 		un->un_wormable = st_is_stk_worm;
13582 	} else {
13583 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13584 		    "Drive has normal tape loaded\n");
13585 		wrt = RDWR;
13586 		un->un_wormable = st_is_stk_worm;
13587 	}
13588 
13589 	kmem_free(buf, STK_REQ_SENSE);
13590 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13591 	return (wrt);
13592 }
13593 
13594 #define	DLT_INQ_SZ 44
13595 
13596 static writablity
13597 st_is_dlt_tape_worm(struct scsi_tape *un)
13598 {
13599 	caddr_t buf;
13600 	int result;
13601 	writablity wrt;
13602 
13603 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
13604 
13605 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
13606 
13607 	/* Read Attribute Media Type */
13608 
13609 	result = st_read_attributes(un, 0x0408, buf, 10, st_uscsi_cmd);
13610 
13611 	/*
13612 	 * If this quantum drive is attached via an HBA that cannot
13613 	 * support thr read attributes command return error in the
13614 	 * hope that someday they will support the t10 method.
13615 	 */
13616 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
13617 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13618 		    "Read Attribute Command for WORM Media detection is not "
13619 		    "supported on the HBA that this drive is attached to.");
13620 		wrt = RDWR;
13621 		un->un_wormable = st_is_not_wormable;
13622 		goto out;
13623 	}
13624 
13625 	if (result != 0) {
13626 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13627 		    "Read Attribute Command for WORM Media returned 0x%x",
13628 		    result);
13629 		wrt = RDWR;
13630 		un->un_dp->options &= ~ST_WORMABLE;
13631 		goto out;
13632 	}
13633 
13634 	if ((uchar_t)buf[9] == 0x80) {
13635 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13636 		    "Drive media is WORM\n");
13637 		wrt = WORM;
13638 	} else {
13639 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13640 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
13641 		wrt = RDWR;
13642 	}
13643 
13644 out:
13645 	kmem_free(buf, DLT_INQ_SZ);
13646 	return (wrt);
13647 }
13648 
13649 static writablity
13650 st_is_dlt_worm(struct scsi_tape *un)
13651 {
13652 	caddr_t buf;
13653 	int result;
13654 	writablity wrt;
13655 
13656 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
13657 
13658 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
13659 
13660 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
13661 
13662 	if (result != 0) {
13663 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13664 		    "Read Vendor Specific Inquiry for WORM support failed");
13665 		wrt = RDWR;
13666 		goto out;
13667 	}
13668 
13669 	if ((buf[2] & 1) == 0) {
13670 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13671 		    "Drive is not WORMable\n");
13672 		wrt = RDWR;
13673 		un->un_dp->options &= ~ST_WORMABLE;
13674 		un->un_wormable = st_is_not_wormable;
13675 		goto out;
13676 	} else {
13677 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13678 		    "Drive is WORMable\n");
13679 		un->un_wormable = st_is_dlt_tape_worm;
13680 		wrt = un->un_wormable(un);
13681 	}
13682 out:
13683 	kmem_free(buf, DLT_INQ_SZ);
13684 
13685 	return (wrt);
13686 }
13687 
13688 typedef struct {
13689 	struct modeheader_seq header;
13690 #if defined(_BIT_FIELDS_LTOH) /* X86 */
13691 	uchar_t pagecode	:6,
13692 				:2;
13693 	uchar_t page_len;
13694 	uchar_t syslogalive	:2,
13695 		device		:1,
13696 		abs		:1,
13697 		ulpbot		:1,
13698 		prth		:1,
13699 		ponej		:1,
13700 		ait		:1;
13701 	uchar_t span;
13702 
13703 	uchar_t			:6,
13704 		worm		:1,
13705 		mic		:1;
13706 	uchar_t worm_cap	:1,
13707 				:7;
13708 	uint32_t		:32;
13709 #else /* SPARC */
13710 	uchar_t			:2,
13711 		pagecode	:6;
13712 	uchar_t page_len;
13713 	uchar_t ait		:1,
13714 		device		:1,
13715 		abs		:1,
13716 		ulpbot		:1,
13717 		prth		:1,
13718 		ponej		:1,
13719 		syslogalive	:2;
13720 	uchar_t span;
13721 	uchar_t mic		:1,
13722 		worm		:1,
13723 				:6;
13724 	uchar_t			:7,
13725 		worm_cap	:1;
13726 	uint32_t		:32;
13727 #endif
13728 }ait_dev_con;
13729 
13730 #define	AIT_DEV_PAGE 0x31
13731 static writablity
13732 st_is_sony_worm(struct scsi_tape *un)
13733 {
13734 	int result;
13735 	writablity wrt;
13736 	ait_dev_con *ait_conf;
13737 
13738 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
13739 
13740 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
13741 
13742 	result = st_gen_mode_sense(un, st_uscsi_cmd, AIT_DEV_PAGE,
13743 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
13744 
13745 	if (result == 0) {
13746 
13747 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
13748 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13749 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
13750 			    ait_conf->pagecode, AIT_DEV_PAGE);
13751 			wrt = RDWR;
13752 			un->un_wormable = st_is_not_wormable;
13753 
13754 		} else if (ait_conf->worm_cap) {
13755 
13756 			un->un_wormable = st_is_sony_worm;
13757 
13758 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13759 			    "Drives is WORMable\n");
13760 			if (ait_conf->worm) {
13761 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13762 				    "Media is WORM\n");
13763 				wrt = WORM;
13764 			} else {
13765 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13766 				    "Media is not WORM\n");
13767 				wrt = RDWR;
13768 			}
13769 
13770 		} else {
13771 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13772 			    "Drives not is WORMable\n");
13773 			wrt = RDWR;
13774 			/* No further checking required */
13775 			un->un_dp->options &= ~ST_WORMABLE;
13776 		}
13777 
13778 	} else {
13779 
13780 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13781 		    "AIT device config mode sense page read command failed"
13782 		    " result = %d ", result);
13783 		wrt = FAILED;
13784 		un->un_wormable = st_is_not_wormable;
13785 	}
13786 
13787 	kmem_free(ait_conf, sizeof (ait_dev_con));
13788 	return (wrt);
13789 }
13790 
13791 static writablity
13792 st_is_drive_worm(struct scsi_tape *un)
13793 {
13794 	writablity wrt;
13795 
13796 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
13797 
13798 	switch (un->un_dp->type) {
13799 	case MT_ISDLT:
13800 		wrt = st_is_dlt_worm(un);
13801 		break;
13802 
13803 	case MT_ISSTK9840:
13804 		wrt = st_is_stk_worm(un);
13805 		break;
13806 
13807 	case MT_IS8MM:
13808 	case MT_ISAIT:
13809 		wrt = st_is_sony_worm(un);
13810 		break;
13811 
13812 	case MT_LTO:
13813 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
13814 			wrt = st_is_hp_lto_worm(un);
13815 		} else {
13816 			wrt = st_is_t10_worm(un);
13817 		}
13818 		break;
13819 
13820 	case MT_ISDAT:
13821 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
13822 			wrt = st_is_hp_dat_worm(un);
13823 		} else {
13824 			wrt = st_is_t10_worm(un);
13825 		}
13826 		break;
13827 
13828 	default:
13829 		wrt = FAILED;
13830 		break;
13831 	}
13832 
13833 	/*
13834 	 * If any of the above failed try the t10 standard method.
13835 	 */
13836 	if (wrt == FAILED) {
13837 		wrt = st_is_t10_worm(un);
13838 	}
13839 
13840 	/*
13841 	 * Unknown method for detecting WORM media.
13842 	 */
13843 	if (wrt == FAILED) {
13844 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13845 		    "Unknown method for WORM media detection\n");
13846 		wrt = RDWR;
13847 		un->un_dp->options &= ~ST_WORMABLE;
13848 	}
13849 
13850 	return (wrt);
13851 }
13852 
13853 static int
13854 st_read_attributes(struct scsi_tape *un, uint16_t attribute, void *pnt,
13855     size_t size, ubufunc_t bufunc)
13856 {
13857 	char cdb[CDB_GROUP4];
13858 	int result;
13859 	struct uscsi_cmd *cmd;
13860 	caddr_t buf = (caddr_t)pnt;
13861 
13862 	ST_FUNC(ST_DEVINFO, st_read_attributes);
13863 
13864 	if (un->un_sd->sd_inq->inq_ansi < 3) {
13865 		return (ENOTTY);
13866 	}
13867 
13868 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13869 
13870 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
13871 	cdb[1] = 0;
13872 	cdb[2] = 0;
13873 	cdb[3] = 0;
13874 	cdb[4] = 0;
13875 	cdb[5] = 0;
13876 	cdb[6] = 0;
13877 	cdb[7] = 0;
13878 	cdb[8] = (char)(attribute >> 8);
13879 	cdb[9] = (char)(attribute);
13880 	cdb[10] = (char)(size >> 24);
13881 	cdb[11] = (char)(size >> 16);
13882 	cdb[12] = (char)(size >> 8);
13883 	cdb[13] = (char)(size);
13884 	cdb[14] = 0;
13885 	cdb[15] = 0;
13886 
13887 
13888 	cmd->uscsi_flags = USCSI_READ | USCSI_DIAGNOSE;
13889 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13890 	cmd->uscsi_cdb = &cdb[0];
13891 	cmd->uscsi_bufaddr = (caddr_t)buf;
13892 	cmd->uscsi_buflen = size;
13893 	cmd->uscsi_cdblen = sizeof (cdb);
13894 
13895 	result = bufunc(un, cmd, FKIOCTL);
13896 
13897 	if (result != 0 || cmd->uscsi_status != 0) {
13898 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13899 		    "st_read_attribute failed: result %d status %d\n",
13900 		    result, cmd->uscsi_status);
13901 		/*
13902 		 * If this returns invalid operation code don't try again.
13903 		 */
13904 		if (un->un_sd->sd_sense->es_key == KEY_ILLEGAL_REQUEST &&
13905 		    un->un_sd->sd_sense->es_add_code == 0x20) {
13906 			result = ENOTTY;
13907 		} else if (result == 0) {
13908 			result = EIO;
13909 		}
13910 
13911 	} else {
13912 
13913 		/*
13914 		 * The attribute retured should match the attribute requested.
13915 		 */
13916 		if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
13917 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13918 			    "st_read_attribute got wrong data back expected "
13919 			    "0x%x got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
13920 			st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
13921 			    "bad? data", buf, size);
13922 			result = EIO;
13923 		}
13924 	}
13925 
13926 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13927 
13928 	return (result);
13929 }
13930 
13931 static int
13932 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
13933     uchar_t page)
13934 {
13935 	char cdb[CDB_GROUP0];
13936 	struct scsi_extended_sense *sense;
13937 	struct uscsi_cmd *cmd;
13938 	int result;
13939 
13940 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
13941 
13942 	cdb[0] = SCMD_INQUIRY;
13943 	cdb[1] = page ? 1 : 0;
13944 	cdb[2] = page;
13945 	cdb[3] = 0;
13946 	cdb[4] = size;
13947 	cdb[5] = 0;
13948 
13949 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13950 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
13951 
13952 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
13953 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13954 	cmd->uscsi_cdb = &cdb[0];
13955 	cmd->uscsi_bufaddr = dest;
13956 	cmd->uscsi_buflen = size;
13957 	cmd->uscsi_cdblen = CDB_GROUP0;
13958 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
13959 	cmd->uscsi_rqbuf = (caddr_t)sense;
13960 
13961 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
13962 
13963 	if (result != 0 || cmd->uscsi_status != 0) {
13964 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13965 		    "st_get_special_inquiry() failed for page %x", page);
13966 		if (result == 0) {
13967 			result = EIO;
13968 		}
13969 	}
13970 
13971 	kmem_free(sense, sizeof (struct scsi_extended_sense));
13972 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13973 
13974 	return (result);
13975 }
13976 
13977 
13978 static int
13979 st_update_block_pos(struct scsi_tape *un, bufunc_t bf, int post_space)
13980 {
13981 	int rval = ENOTTY;
13982 	uchar_t status = un->un_status;
13983 	posmode previous_pmode = un->un_running.pmode;
13984 
13985 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
13986 
13987 	while (un->un_read_pos_type != NO_POS) {
13988 		rval = bf(un, SCMD_READ_POSITION, 32, SYNC_CMD);
13989 
13990 		/*
13991 		 * If read position command returned good status
13992 		 * Parse the data to see if the position can be interpreted.
13993 		 */
13994 		if ((rval == 0) &&
13995 		    ((rval = st_interpret_read_pos(un, &un->un_pos,
13996 		    un->un_read_pos_type, 32, (caddr_t)un->un_read_pos_data,
13997 		    post_space)) == 0)) {
13998 			/*
13999 			 * Update the running position as well if un_pos was
14000 			 * ok. But only if recovery is enabled.
14001 			 */
14002 			if (st_recov_sz != sizeof (recov_info)) {
14003 				break;
14004 			}
14005 			rval = st_interpret_read_pos(un, &un->un_running,
14006 			    un->un_read_pos_type, 32,
14007 			    (caddr_t)un->un_read_pos_data, post_space);
14008 			un->un_status = status;
14009 			break;
14010 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
14011 			un->un_running.pmode = previous_pmode;
14012 			continue;
14013 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
14014 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
14015 			    "st_update_block_pos() read position cmd 0x%x"
14016 			    " returned 0x%x un_status = %d",
14017 			    un->un_read_pos_type, rval, un->un_status);
14018 			/* ENOTTY means it read garbage. try something else. */
14019 			if (rval == ENOTTY) {
14020 				rval = EIO; /* so ENOTTY is not final rval */
14021 			} else {
14022 				break;
14023 			}
14024 		} else {
14025 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
14026 			    "st_update_block_pos() read position cmd %x"
14027 			    " returned %x", un->un_read_pos_type, rval);
14028 			un->un_running.pmode = previous_pmode;
14029 		}
14030 
14031 		switch (un->un_read_pos_type) {
14032 		case SHORT_POS:
14033 			un->un_read_pos_type = NO_POS;
14034 			break;
14035 
14036 		case LONG_POS:
14037 			un->un_read_pos_type = EXT_POS;
14038 			break;
14039 
14040 		case EXT_POS:
14041 			un->un_read_pos_type = SHORT_POS;
14042 			break;
14043 
14044 		default:
14045 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14046 			    "Unexpected read position type 0x%x",
14047 			    un->un_read_pos_type);
14048 		}
14049 		un->un_status = KEY_NO_SENSE;
14050 	}
14051 
14052 	return (rval);
14053 }
14054 
14055 static int
14056 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
14057 {
14058 	int result;
14059 	size_t d_sz;
14060 	caddr_t pos_info;
14061 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
14062 
14063 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
14064 
14065 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
14066 		return (0);
14067 	}
14068 
14069 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
14070 
14071 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14072 		    "bp_mapin_common() failed");
14073 
14074 		return (EIO);
14075 	}
14076 
14077 	d_sz = bp->b_bcount - bp->b_resid;
14078 	if (d_sz == 0) {
14079 		bp_mapout(bp);
14080 		return (EIO);
14081 	}
14082 
14083 	/*
14084 	 * Copy the buf to a double-word aligned memory that can hold the
14085 	 * tape_position_t data structure.
14086 	 */
14087 	if ((pos_info = kmem_alloc(d_sz, KM_NOSLEEP)) == NULL) {
14088 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14089 		    "kmem_alloc() failed");
14090 		bp_mapout(bp);
14091 		return (EIO);
14092 	}
14093 	bcopy(bp->b_un.b_addr, pos_info, d_sz);
14094 
14095 #ifdef STDEBUG
14096 	if ((st_debug & 0x7) > 2) {
14097 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14098 		    "st_get_read_pos() position info",
14099 		    pos_info, bp->b_bcount);
14100 	}
14101 #endif
14102 
14103 	result = st_interpret_read_pos(un, &un->un_pos, cmd->uscsi_cdb[1],
14104 	    d_sz, pos_info, 0);
14105 
14106 	COPY_POS(&un->un_running, &un->un_pos);
14107 
14108 	kmem_free(pos_info, d_sz);
14109 	bp_mapout(bp);
14110 
14111 	return (result);
14112 }
14113 
14114 #if defined(_BIG_ENDIAN)
14115 
14116 #define	FIX_ENDIAN16(x)
14117 #define	FIX_ENDIAN32(x)
14118 #define	FIX_ENDIAN64(x)
14119 
14120 #elif defined(_LITTLE_ENDIAN)
14121 
14122 static void
14123 st_swap16(uint16_t *val)
14124 {
14125 	uint16_t tmp;
14126 
14127 	tmp = (*val >>  8) & 0xff;
14128 	tmp |= (*val <<  8) & 0xff00;
14129 
14130 	*val = tmp;
14131 }
14132 
14133 static void
14134 st_swap32(uint32_t *val)
14135 {
14136 	uint32_t tmp;
14137 
14138 	tmp =  (*val >> 24) & 0xff;
14139 	tmp |= (*val >>  8) & 0xff00;
14140 	tmp |= (*val <<  8) & 0xff0000;
14141 	tmp |= (*val << 24) & 0xff000000;
14142 
14143 	*val = tmp;
14144 }
14145 
14146 static void
14147 st_swap64(uint64_t *val)
14148 {
14149 	uint32_t low;
14150 	uint32_t high;
14151 
14152 	low =  (uint32_t)(*val);
14153 	high = (uint32_t)(*val >> 32);
14154 
14155 	st_swap32(&low);
14156 	st_swap32(&high);
14157 
14158 	*val =  high;
14159 	*val |= ((uint64_t)low << 32);
14160 }
14161 
14162 #define	FIX_ENDIAN16(x) st_swap16(x)
14163 #define	FIX_ENDIAN32(x) st_swap32(x)
14164 #define	FIX_ENDIAN64(x) st_swap64(x)
14165 #endif
14166 
14167 /*
14168  * st_interpret_read_pos()
14169  *
14170  * Returns:
14171  *	0	If secsessful.
14172  *	EIO	If read postion responce data was unuseable or invalid.
14173  *	ERANGE	If the position of the drive is too large for the read_p_type.
14174  *	ENOTTY	If the responce data looks invalid for the read position type.
14175  */
14176 
14177 static int
14178 st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
14179     read_p_types type, size_t data_sz, const caddr_t responce, int post_space)
14180 {
14181 	int rval = 0;
14182 	int flag = 0;
14183 	tapepos_t org;
14184 
14185 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
14186 
14187 	/*
14188 	 * We expect the position value to change after a space command.
14189 	 * So if post_space is set we don't print out what has changed.
14190 	 */
14191 	if ((dest != &un->un_pos) && (post_space == 0) &&
14192 	    (st_recov_sz == sizeof (recov_info))) {
14193 		COPY_POS(&org, dest);
14194 		flag = 1;
14195 	}
14196 
14197 	/*
14198 	 * See what kind of read position was requested.
14199 	 */
14200 	switch (type) {
14201 
14202 	case SHORT_POS: /* Short data format */
14203 	{
14204 		tape_position_t *pos_info = (tape_position_t *)responce;
14205 		uint32_t value;
14206 
14207 		/* If reserved fields are non zero don't use the data */
14208 		if (pos_info->reserved0 || pos_info->reserved1 ||
14209 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
14210 		    pos_info->reserved3) {
14211 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14212 			    "Invalid Read Short Position Data returned\n");
14213 			rval = EIO;
14214 			break;
14215 		}
14216 		/*
14217 		 * Position is to large to use this type of read position.
14218 		 */
14219 		if (pos_info->posi_err == 1) {
14220 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14221 			    "Drive reported position error\n");
14222 			rval = ERANGE;
14223 			break;
14224 		}
14225 		/*
14226 		 * If your at the begining of partition and end at the same
14227 		 * time it's very small partition or bad data.
14228 		 */
14229 		if (pos_info->begin_of_part && pos_info->end_of_part) {
14230 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14231 			    "SHORT_POS returned begin and end of"
14232 			    " partition\n");
14233 			rval = EIO;
14234 			break;
14235 		}
14236 
14237 		if (pos_info->blk_posi_unkwn == 0) {
14238 
14239 			value = pos_info->host_block;
14240 			FIX_ENDIAN32(&value);
14241 
14242 			/*
14243 			 * If the tape is rewound the host blcok should be 0.
14244 			 */
14245 			if ((pos_info->begin_of_part == 1) &&
14246 			    (value != 0)) {
14247 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14248 				    "SHORT_POS returned begin of partition"
14249 				    " but host block was 0x%x\n", value);
14250 				rval = EIO;
14251 				break;
14252 			}
14253 
14254 			if (dest->lgclblkno != value) {
14255 				if (flag)
14256 					flag++;
14257 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14258 				    "SHORT_POS current logical 0x%"PRIx64" read"
14259 				    " 0x%x\n", dest->lgclblkno, value);
14260 			}
14261 
14262 			dest->lgclblkno = (uint64_t)value;
14263 
14264 			/*
14265 			 * If the begining of partition is true and the
14266 			 * block number is zero we will beleive that it is
14267 			 * rewound. Promote the pmode to legacy.
14268 			 */
14269 			if ((pos_info->begin_of_part == 1) &&
14270 			    (value == 0)) {
14271 				dest->blkno = 0;
14272 				dest->fileno = 0;
14273 				if (dest->pmode != legacy)
14274 					dest->pmode = legacy;
14275 			/*
14276 			 * otherwise if the pmode was invalid,
14277 			 * promote it to logical.
14278 			 */
14279 			} else if (dest->pmode == invalid) {
14280 				dest->pmode = logical;
14281 			}
14282 
14283 			if (dest->partition != pos_info->partition_number) {
14284 				if (flag)
14285 					flag++;
14286 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14287 				    "SHORT_POS current partition %d read %d\n",
14288 				    dest->partition,
14289 				    pos_info->partition_number);
14290 			}
14291 
14292 			dest->partition = pos_info->partition_number;
14293 
14294 		} else {
14295 			dest->pmode = invalid;
14296 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14297 			    "Tape drive reported block position as unknown\n");
14298 		}
14299 		break;
14300 	}
14301 
14302 	case LONG_POS: /* Long data format */
14303 	{
14304 		uint64_t value;
14305 		tape_position_long_t *long_pos_info =
14306 		    (tape_position_long_t *)responce;
14307 
14308 		/* If reserved fields are non zero don't use the data */
14309 		if ((long_pos_info->reserved0) ||
14310 		    (long_pos_info->reserved1) ||
14311 		    (long_pos_info->reserved2)) {
14312 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14313 			    "Invalid Read Long Position Data returned\n");
14314 			rval = ENOTTY;
14315 			break;
14316 		}
14317 
14318 		/* Is position Valid */
14319 		if (long_pos_info->blk_posi_unkwn == 0) {
14320 			uint32_t part;
14321 
14322 			value = long_pos_info->block_number;
14323 			FIX_ENDIAN64(&value);
14324 
14325 			/*
14326 			 * If it says we are at the begining of partition
14327 			 * the block value better be 0.
14328 			 */
14329 			if ((long_pos_info->begin_of_part == 1) &&
14330 			    (value != 0)) {
14331 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14332 				    "LONG_POS returned begin of partition but"
14333 				    " block number was 0x%"PRIx64"\n", value);
14334 				rval = ENOTTY;
14335 				break;
14336 			}
14337 			/*
14338 			 * Can't be at the start and the end of the partition
14339 			 * at the same time if the partition is larger the 0.
14340 			 */
14341 			if (long_pos_info->begin_of_part &&
14342 			    long_pos_info->end_of_part) {
14343 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14344 				    "LONG_POS returned begin and end of"
14345 				    " partition\n");
14346 				rval = ENOTTY;
14347 				break;
14348 			}
14349 
14350 			/*
14351 			 * If the logical block number is not what we expected.
14352 			 */
14353 			if (dest->lgclblkno != value) {
14354 				if (flag)
14355 					flag++;
14356 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14357 				    "LONG_POS current logical 0x%"PRIx64
14358 				    " read 0x%"PRIx64"\n",
14359 				    dest->lgclblkno, value);
14360 			}
14361 			dest->lgclblkno = value;
14362 
14363 			/*
14364 			 * If the begining of partition is true and the
14365 			 * block number is zero we will beleive that it is
14366 			 * rewound. Promote the pmode to legacy.
14367 			 */
14368 			if ((long_pos_info->begin_of_part == 1) &&
14369 			    (long_pos_info->block_number == 0)) {
14370 				dest->blkno = 0;
14371 				dest->fileno = 0;
14372 				if (dest->pmode != legacy)
14373 					dest->pmode = legacy;
14374 			/*
14375 			 * otherwise if the pmode was invalid,
14376 			 * promote it to logical.
14377 			 */
14378 			} else if (dest->pmode == invalid) {
14379 				dest->pmode = logical;
14380 			}
14381 
14382 			part = long_pos_info->partition;
14383 			FIX_ENDIAN32(&part);
14384 			if (dest->partition != part) {
14385 				if (flag)
14386 					flag++;
14387 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14388 				    "LONG_POS current partition %d"
14389 				    " read %d\n", dest->partition, part);
14390 			}
14391 			dest->partition = part;
14392 		} else {
14393 			/*
14394 			 * If the drive doesn't know location,
14395 			 * we don't either.
14396 			 */
14397 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14398 			    "Tape drive reported block position as unknown\n");
14399 			dest->pmode = invalid;
14400 		}
14401 
14402 		/* Is file position valid */
14403 		if (long_pos_info->mrk_posi_unkwn == 0) {
14404 			value = long_pos_info->file_number;
14405 			FIX_ENDIAN64(&value);
14406 			/*
14407 			 * If it says we are at the begining of partition
14408 			 * the block value better be 0.
14409 			 */
14410 			if ((long_pos_info->begin_of_part == 1) &&
14411 			    (value != 0)) {
14412 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14413 				    "LONG_POS returned begin of partition but"
14414 				    " block number was 0x%"PRIx64"\n", value);
14415 				rval = ENOTTY;
14416 				break;
14417 			}
14418 			if (((dest->pmode == legacy) ||
14419 			    (dest->pmode == logical)) &&
14420 			    (dest->fileno != value)) {
14421 				if (flag)
14422 					flag++;
14423 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14424 				    "LONG_POS fileno 0x%"PRIx64
14425 				    " not un_pos %x\n", value,
14426 				    dest->fileno);
14427 			} else if (dest->pmode == invalid) {
14428 				dest->pmode = logical;
14429 			}
14430 			dest->fileno = (int32_t)value;
14431 		} else {
14432 			/*
14433 			 * If the drive doesn't know its position,
14434 			 * we don't either.
14435 			 */
14436 			dest->pmode = invalid;
14437 		}
14438 		if (dest->pmode != invalid && long_pos_info->end_of_part) {
14439 			dest->eof = ST_EOT;
14440 		}
14441 
14442 		break;
14443 	}
14444 
14445 	case EXT_POS: /* Extended data format */
14446 	{
14447 		uint64_t value;
14448 		uint16_t len;
14449 		tape_position_ext_t *ext_pos_info =
14450 		    (tape_position_ext_t *)responce;
14451 
14452 		/* Make sure that there is enough data there */
14453 		if (data_sz < 16) {
14454 			break;
14455 		}
14456 
14457 		/* If reserved fields are non zero don't use the data */
14458 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
14459 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14460 			    "EXT_POS reserved fields not zero\n");
14461 			rval = ENOTTY;
14462 			break;
14463 		}
14464 
14465 		/*
14466 		 * In the unlikely event of overflowing 64 bits of position.
14467 		 */
14468 		if (ext_pos_info->posi_err != 0) {
14469 			rval = ERANGE;
14470 			break;
14471 		}
14472 
14473 		len = ext_pos_info->parameter_len;
14474 		FIX_ENDIAN16(&len);
14475 
14476 		if (len != 0x1c) {
14477 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14478 			    "EXT_POS parameter_len should be 0x1c was 0x%x\n",
14479 			    len);
14480 			rval = ENOTTY;
14481 			break;
14482 		}
14483 
14484 		/* Is block position information valid */
14485 		if (ext_pos_info->blk_posi_unkwn == 0) {
14486 
14487 			value = ext_pos_info->host_block;
14488 			FIX_ENDIAN64(&value);
14489 			if ((ext_pos_info->begin_of_part == 1) &&
14490 			    (value != 0)) {
14491 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14492 				    "EXT_POS returned begining of partition but"
14493 				    " the host block was 0x%"PRIx64"\n", value);
14494 				rval = ENOTTY;
14495 				break;
14496 			}
14497 
14498 			if (dest->lgclblkno != value) {
14499 				if (flag)
14500 					flag++;
14501 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14502 				    "EXT_POS current logical 0x%"PRIx64
14503 				    " read 0x%"PRIx64"\n",
14504 				    dest->lgclblkno, value);
14505 			}
14506 			dest->lgclblkno = value;
14507 
14508 			/*
14509 			 * If the begining of partition is true and the
14510 			 * block number is zero we will beleive that it is
14511 			 * rewound. Promote the pmode to legacy.
14512 			 */
14513 			if ((ext_pos_info->begin_of_part == 1) &&
14514 			    (ext_pos_info->host_block == 0)) {
14515 				dest->blkno = 0;
14516 				dest->fileno = 0;
14517 				if (dest->pmode != legacy) {
14518 					dest->pmode = legacy;
14519 				}
14520 			/*
14521 			 * otherwise if the pmode was invalid,
14522 			 * promote it to logical.
14523 			 */
14524 			} else if (dest->pmode == invalid) {
14525 				dest->pmode = logical;
14526 			}
14527 
14528 			if (dest->partition != ext_pos_info->partition) {
14529 				if (flag)
14530 					flag++;
14531 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14532 				    "EXT_POS current partition %d read %d\n",
14533 				    dest->partition,
14534 				    ext_pos_info->partition);
14535 			}
14536 			dest->partition = ext_pos_info->partition;
14537 
14538 		} else {
14539 			dest->pmode = invalid;
14540 		}
14541 		break;
14542 	}
14543 
14544 	default:
14545 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14546 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
14547 		rval = EIO;
14548 	}
14549 
14550 	if ((flag > 1) && (rval == 0)) {
14551 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14552 		    "position read in", &org);
14553 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14554 		    "position read out", dest);
14555 	}
14556 
14557 	return (rval);
14558 }
14559 
14560 static int
14561 st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos,
14562     uint64_t lblk, uchar_t partition)
14563 {
14564 	int rval;
14565 	char cdb[CDB_GROUP4];
14566 	struct uscsi_cmd *cmd;
14567 	struct scsi_extended_sense sense;
14568 	bufunc_t bf = (ubf == st_uscsi_cmd) ? st_cmd : st_rcmd;
14569 
14570 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
14571 	/*
14572 	 * WTF Not sure what to do when doing recovery and not wanting
14573 	 * to update un_pos
14574 	 */
14575 
14576 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14577 
14578 	if (lblk <= INT32_MAX) {
14579 		cmd->uscsi_cdblen = CDB_GROUP1;
14580 		cdb[0] = SCMD_LOCATE;
14581 		cdb[1] = pos->partition == partition ? 0 : 2;
14582 		cdb[2] = 0;
14583 		cdb[3] = (char)(lblk >> 24);
14584 		cdb[4] = (char)(lblk >> 16);
14585 		cdb[5] = (char)(lblk >> 8);
14586 		cdb[6] = (char)(lblk);
14587 		cdb[7] = 0;
14588 		cdb[8] = partition;
14589 		cdb[9] = 0;
14590 	} else {
14591 		/*
14592 		 * If the drive doesn't give a 64 bit read position data
14593 		 * it is unlikely it will accept 64 bit locates.
14594 		 */
14595 		if (un->un_read_pos_type != LONG_POS) {
14596 			kmem_free(cmd, sizeof (struct uscsi_cmd));
14597 			return (ERANGE);
14598 		}
14599 		cmd->uscsi_cdblen = CDB_GROUP4;
14600 		cdb[0] = (char)SCMD_LOCATE_G4;
14601 		cdb[1] = pos->partition == partition ? 0 : 2;
14602 		cdb[2] = 0;
14603 		cdb[3] = partition;
14604 		cdb[4] = (char)(lblk >> 56);
14605 		cdb[5] = (char)(lblk >> 48);
14606 		cdb[6] = (char)(lblk >> 40);
14607 		cdb[7] = (char)(lblk >> 32);
14608 		cdb[8] = (char)(lblk >> 24);
14609 		cdb[9] = (char)(lblk >> 16);
14610 		cdb[10] = (char)(lblk >> 8);
14611 		cdb[11] = (char)(lblk);
14612 		cdb[12] = 0;
14613 		cdb[13] = 0;
14614 		cdb[14] = 0;
14615 		cdb[15] = 0;
14616 	}
14617 
14618 
14619 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
14620 	cmd->uscsi_rqbuf = (caddr_t)&sense;
14621 	cmd->uscsi_rqlen = sizeof (sense);
14622 	cmd->uscsi_timeout = un->un_dp->space_timeout;
14623 	cmd->uscsi_cdb = cdb;
14624 
14625 	rval = ubf(un, cmd, FKIOCTL);
14626 
14627 	pos->pmode = logical;
14628 	pos->eof = ST_NO_EOF;
14629 
14630 	if (lblk > INT32_MAX) {
14631 		/*
14632 		 * XXX This is a work around till we handle Descriptor format
14633 		 * sense data. Since we are sending a command where the standard
14634 		 * sense data can not correctly represent a correct residual in
14635 		 * 4 bytes.
14636 		 */
14637 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
14638 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14639 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
14640 			/* Doesn't like big locate command */
14641 			un->un_status = 0;
14642 			rval = ERANGE;
14643 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
14644 			/* Aborted big locate command */
14645 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14646 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
14647 			    rval);
14648 			un->un_status = 0;
14649 			rval = EIO;
14650 		} else if (st_update_block_pos(un, bf, 1)) {
14651 			/* read position failed */
14652 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14653 			    "Big LOCATE and read pos: rval = %d\n", rval);
14654 			rval = EIO;
14655 		} else if (lblk > un->un_pos.lgclblkno) {
14656 			/* read position worked but position was not expected */
14657 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14658 			    "Big LOCATE and recover read less then desired 0x%"
14659 			    PRIx64"\n", un->un_pos.lgclblkno);
14660 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
14661 			un->un_status = KEY_BLANK_CHECK;
14662 			rval = ESPIPE;
14663 		} else if (lblk == un->un_pos.lgclblkno) {
14664 			/* read position was what was expected */
14665 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14666 			    "Big LOCATE and recover seems to have worked\n");
14667 			un->un_err_resid = 0;
14668 			rval = 0;
14669 		} else {
14670 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14671 			    "BIGLOCATE end up going backwards");
14672 			un->un_err_resid = lblk;
14673 			rval = EIO;
14674 		}
14675 
14676 	} else if (rval == 0) {
14677 		/* Worked as requested */
14678 		pos->lgclblkno = lblk;
14679 
14680 	} else if (((cmd->uscsi_status & STATUS_MASK) == STATUS_CHECK) &&
14681 	    (cmd->uscsi_resid != 0)) {
14682 		/* Got part way there but wasn't enough blocks on tape */
14683 		pos->lgclblkno = lblk - cmd->uscsi_resid;
14684 		un->un_err_resid = cmd->uscsi_resid;
14685 		un->un_status = KEY_BLANK_CHECK;
14686 		rval = ESPIPE;
14687 
14688 	} else if (st_update_block_pos(un, bf, 1) == 0) {
14689 		/* Got part way there but drive didn't tell what we missed by */
14690 		un->un_err_resid = lblk - pos->lgclblkno;
14691 		un->un_status = KEY_BLANK_CHECK;
14692 		rval = ESPIPE;
14693 
14694 	} else {
14695 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14696 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
14697 		    rval, cmd->uscsi_status);
14698 		un->un_err_resid = lblk;
14699 		un->un_status = KEY_ILLEGAL_REQUEST;
14700 		pos->pmode = invalid;
14701 		rval = EIO;
14702 	}
14703 
14704 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14705 
14706 	return (rval);
14707 }
14708 
14709 static int
14710 st_mtfsf_ioctl(struct scsi_tape *un, int files)
14711 {
14712 	int rval;
14713 
14714 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
14715 
14716 
14717 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14718 	    "st_mtfsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
14719 #if 0
14720 	if ((IN_EOF(un->un_pos)) && (files == 1)) {
14721 		un->un_pos.fileno++;
14722 		un->un_pos.blkno = 0;
14723 		return (0);
14724 	}
14725 #endif
14726 	/* pmode == invalid already handled */
14727 	if (un->un_pos.pmode == legacy) {
14728 		/*
14729 		 * forward space over filemark
14730 		 *
14731 		 * For ASF we allow a count of 0 on fsf which means
14732 		 * we just want to go to beginning of current file.
14733 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
14734 		 * Allow stepping over double fmk with reel
14735 		 */
14736 		if ((un->un_pos.eof >= ST_EOT) &&
14737 		    (files > 0) &&
14738 		    ((un->un_dp->options & ST_REEL) == 0)) {
14739 			/* we're at EOM */
14740 			un->un_err_resid = files;
14741 			un->un_status = KEY_BLANK_CHECK;
14742 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14743 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
14744 			return (EIO);
14745 		}
14746 
14747 		/*
14748 		 * physical tape position may not be what we've been
14749 		 * telling the user; adjust the request accordingly
14750 		 */
14751 		if (IN_EOF(un->un_pos)) {
14752 			un->un_pos.fileno++;
14753 			un->un_pos.blkno = 0;
14754 			/*
14755 			 * For positive direction case, we're now covered.
14756 			 * For zero or negative direction, we're covered
14757 			 * (almost)
14758 			 */
14759 			files--;
14760 		}
14761 
14762 	}
14763 
14764 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
14765 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14766 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
14767 		return (EIO);
14768 	}
14769 
14770 
14771 	/*
14772 	 * Forward space file marks.
14773 	 * We leave ourselves at block zero
14774 	 * of the target file number.
14775 	 */
14776 	if (files < 0) {
14777 		rval = st_backward_space_files(un, -files, 0);
14778 	} else {
14779 		rval = st_forward_space_files(un, files);
14780 	}
14781 
14782 	return (rval);
14783 }
14784 
14785 static int
14786 st_forward_space_files(struct scsi_tape *un, int count)
14787 {
14788 	int rval;
14789 
14790 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
14791 
14792 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14793 	    "fspace: count=%x, eof=%x\n", count, un->un_pos.eof);
14794 
14795 	ASSERT(count >= 0);
14796 	ASSERT(un->un_pos.pmode != invalid);
14797 
14798 	/*
14799 	 * A space with a count of zero means take me to the start of file.
14800 	 */
14801 	if (count == 0) {
14802 
14803 		/* Hay look were already there */
14804 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0) {
14805 			un->un_err_resid = 0;
14806 			COPY_POS(&un->un_err_pos, &un->un_pos);
14807 			return (0);
14808 		}
14809 
14810 		/*
14811 		 * Well we are in the first file.
14812 		 * A rewind will get to the start.
14813 		 */
14814 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
14815 			rval = st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
14816 
14817 		/*
14818 		 * Can we backspace to get there?
14819 		 * This should work in logical mode.
14820 		 */
14821 		} else if (un->un_dp->options & ST_BSF) {
14822 			rval = st_space_to_begining_of_file(un);
14823 
14824 		/*
14825 		 * Can't back space but current file number is known,
14826 		 * So rewind and space from the begining of the partition.
14827 		 */
14828 		} else if (un->un_pos.pmode == legacy) {
14829 			rval = st_scenic_route_to_begining_of_file(un,
14830 			    un->un_pos.fileno);
14831 
14832 		/*
14833 		 * pmode is logical and ST_BSF is not set.
14834 		 * The LONG_POS read position contains the fileno.
14835 		 * If the read position works, rewind and space.
14836 		 */
14837 		} else if (un->un_read_pos_type == LONG_POS) {
14838 			rval = st_cmd(un, SCMD_READ_POSITION, 0, SYNC_CMD);
14839 			if (rval) {
14840 				/*
14841 				 * We didn't get the file position from the
14842 				 * read position command.
14843 				 * We are going to trust the drive to backspace
14844 				 * and then position after the filemark.
14845 				 */
14846 				rval = st_space_to_begining_of_file(un);
14847 			}
14848 			rval = st_interpret_read_pos(un, &un->un_pos, LONG_POS,
14849 			    32, (caddr_t)un->un_read_pos_data, 0);
14850 			if ((rval) && (un->un_pos.pmode == invalid)) {
14851 				rval = st_space_to_begining_of_file(un);
14852 			} else {
14853 				rval = st_scenic_route_to_begining_of_file(un,
14854 				    un->un_pos.fileno);
14855 			}
14856 		} else {
14857 			rval = EIO;
14858 		}
14859 		/*
14860 		 * If something didn't work we are lost
14861 		 */
14862 		if (rval != 0) {
14863 			un->un_pos.pmode = invalid;
14864 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14865 			    "st_mtioctop : EIO : fspace pmode invalid");
14866 
14867 			rval = EIO;
14868 		}
14869 
14870 	} else {
14871 		rval = st_space_fmks(un, count);
14872 	}
14873 
14874 	if (rval != EIO && count < 0) {
14875 		/*
14876 		 * we came here with a count < 0; we now need
14877 		 * to skip back to end up before the filemark
14878 		 */
14879 		rval = st_backward_space_files(un, 1, 1);
14880 	}
14881 
14882 	return (rval);
14883 }
14884 
14885 static int
14886 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
14887 {
14888 	int rval;
14889 
14890 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
14891 
14892 	if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
14893 		rval = EIO;
14894 	} else if (st_cmd(un, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
14895 		rval = EIO;
14896 	}
14897 
14898 	return (rval);
14899 }
14900 
14901 static int
14902 st_space_to_begining_of_file(struct scsi_tape *un)
14903 {
14904 	int rval;
14905 
14906 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
14907 
14908 	/*
14909 	 * Back space of the file at the begining of the file.
14910 	 */
14911 	rval = st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
14912 	if (rval) {
14913 		rval = EIO;
14914 		return (rval);
14915 	}
14916 
14917 	/*
14918 	 * Other interesting answers might be crashed BOT which isn't bad.
14919 	 */
14920 	if (un->un_status == SUN_KEY_BOT) {
14921 		return (rval);
14922 	}
14923 
14924 	un->un_running.pmode = invalid;
14925 
14926 	/*
14927 	 * Now we are on the BOP side of the filemark. Forward space to
14928 	 * the EOM side and we are at the begining of the file.
14929 	 */
14930 	rval = st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD);
14931 	if (rval) {
14932 		rval = EIO;
14933 	}
14934 
14935 	return (rval);
14936 }
14937 
14938 static int
14939 st_mtfsr_ioctl(struct scsi_tape *un, int count)
14940 {
14941 
14942 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
14943 
14944 	/*
14945 	 * forward space to inter-record gap
14946 	 *
14947 	 */
14948 
14949 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14950 	    "st_ioctl_fsr: count=%x, eof=%x\n", count, un->un_pos.eof);
14951 
14952 	if (un->un_pos.pmode == legacy) {
14953 		/*
14954 		 * If were are at end of tape and count is forward.
14955 		 * Return blank check.
14956 		 */
14957 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
14958 			/* we're at EOM */
14959 			un->un_err_resid = count;
14960 			un->un_status = KEY_BLANK_CHECK;
14961 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14962 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
14963 			return (EIO);
14964 		}
14965 
14966 		/*
14967 		 * If count is zero there is nothing to do.
14968 		 */
14969 		if (count == 0) {
14970 			un->un_err_pos.fileno = un->un_pos.fileno;
14971 			un->un_err_pos.blkno = un->un_pos.blkno;
14972 			un->un_err_resid = 0;
14973 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
14974 				un->un_status = SUN_KEY_EOF;
14975 			}
14976 			return (0);
14977 		}
14978 
14979 		/*
14980 		 * physical tape position may not be what we've been
14981 		 * telling the user; adjust the position accordingly
14982 		 */
14983 		if (IN_EOF(un->un_pos)) {
14984 			daddr_t blkno = un->un_pos.blkno;
14985 			int fileno = un->un_pos.fileno;
14986 
14987 			optype lastop = un->un_lastop;
14988 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)
14989 			    == -1) {
14990 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14991 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
14992 				return (EIO);
14993 			}
14994 
14995 			un->un_pos.blkno = blkno;
14996 			un->un_pos.fileno = fileno;
14997 			un->un_lastop = lastop;
14998 		}
14999 	}
15000 
15001 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15002 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15003 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
15004 		return (EIO);
15005 	}
15006 
15007 	return (st_space_records(un, count));
15008 }
15009 
15010 static int
15011 st_space_records(struct scsi_tape *un, int count)
15012 {
15013 	int dblk;
15014 	int rval = 0;
15015 
15016 	ST_FUNC(ST_DEVINFO, st_space_records);
15017 
15018 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15019 	    "st_space_records: count=%x, eof=%x\n", count, un->un_pos.eof);
15020 
15021 	if (un->un_pos.pmode == logical) {
15022 		rval = st_cmd(un, SCMD_SPACE, Blk(count), SYNC_CMD);
15023 		if (rval != 0) {
15024 			rval = EIO;
15025 		}
15026 		return (rval);
15027 	}
15028 
15029 	dblk = un->un_pos.blkno + count;
15030 
15031 	/* Already there */
15032 	if (dblk == un->un_pos.blkno) {
15033 		un->un_err_resid = 0;
15034 		COPY_POS(&un->un_err_pos, &un->un_pos);
15035 		return (0);
15036 	}
15037 
15038 	/*
15039 	 * If the destination block is forward
15040 	 * or the drive will backspace records.
15041 	 */
15042 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
15043 		/*
15044 		 * If we're spacing forward, or the device can
15045 		 * backspace records, we can just use the SPACE
15046 		 * command.
15047 		 */
15048 		dblk -= un->un_pos.blkno;
15049 		if (st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15050 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15051 			    "st_space_records:EIO:space_records can't spc");
15052 			rval = EIO;
15053 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
15054 			/*
15055 			 * check if we hit BOT/EOT
15056 			 */
15057 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
15058 				un->un_status = SUN_KEY_BOT;
15059 				un->un_pos.eof = ST_NO_EOF;
15060 			} else if (dblk < 0 &&
15061 			    un->un_pos.eof == ST_EOF_PENDING) {
15062 				int residue = un->un_err_resid;
15063 				/*
15064 				 * we skipped over a filemark
15065 				 * and need to go forward again
15066 				 */
15067 				if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
15068 					ST_DEBUG2(ST_DEVINFO, st_label,
15069 					    SCSI_DEBUG, "st_space_records: EIO"
15070 					    " : can't space #2");
15071 					rval = EIO;
15072 				}
15073 				un->un_err_resid = residue;
15074 			}
15075 			if (rval == 0) {
15076 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15077 				    "st_space_records: EIO : space_rec rval"
15078 				    " == 0");
15079 				rval = EIO;
15080 			}
15081 		}
15082 	} else {
15083 		/*
15084 		 * else we rewind, space forward across filemarks to
15085 		 * the desired file, and then space records to the
15086 		 * desired block.
15087 		 */
15088 
15089 		int dfile = un->un_pos.fileno;	/* save current file */
15090 
15091 		if (dblk < 0) {
15092 			/*
15093 			 * Wups - we're backing up over a filemark
15094 			 */
15095 			if (un->un_pos.blkno != 0 &&
15096 			    (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15097 			    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD))) {
15098 				un->un_pos.pmode = invalid;
15099 			}
15100 			un->un_err_resid = -dblk;
15101 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
15102 				un->un_status = SUN_KEY_BOT;
15103 				un->un_pos.eof = ST_NO_EOF;
15104 			} else if (un->un_pos.fileno > 0) {
15105 				un->un_status = SUN_KEY_EOF;
15106 				un->un_pos.eof = ST_NO_EOF;
15107 			}
15108 			COPY_POS(&un->un_err_pos, &un->un_pos);
15109 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15110 			    "st_space_records:EIO:space_records : dblk < 0");
15111 			rval = EIO;
15112 		} else if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15113 		    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
15114 		    st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15115 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15116 			    "st_space_records: EIO :space_records : rewind "
15117 			    "and space failed");
15118 			un->un_pos.pmode = invalid;
15119 			rval = EIO;
15120 		}
15121 	}
15122 
15123 	return (rval);
15124 }
15125 
15126 static int
15127 st_mtbsf_ioctl(struct scsi_tape *un, int files)
15128 {
15129 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
15130 
15131 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15132 	    "st_mtbsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
15133 	/*
15134 	 * backward space of file filemark (1/2" and 8mm)
15135 	 * tape position will end on the beginning of tape side
15136 	 * of the desired file mark
15137 	 */
15138 	if ((un->un_dp->options & ST_BSF) == 0) {
15139 		return (ENOTTY);
15140 	}
15141 
15142 	if (un->un_pos.pmode == legacy) {
15143 
15144 		/*
15145 		 * If a negative count (which implies a forward space op)
15146 		 * is specified, and we're at logical or physical eot,
15147 		 * bounce the request.
15148 		 */
15149 
15150 		if (un->un_pos.eof >= ST_EOT && files < 0) {
15151 			un->un_err_resid = files;
15152 			un->un_status = SUN_KEY_EOT;
15153 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15154 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
15155 			return (EIO);
15156 		}
15157 		/*
15158 		 * physical tape position may not be what we've been
15159 		 * telling the user; adjust the request accordingly
15160 		 */
15161 		if (IN_EOF(un->un_pos)) {
15162 			un->un_pos.fileno++;
15163 			un->un_pos.blkno = 0;
15164 			files++;
15165 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15166 			    "st_mtbsf_ioctl in eof: count=%d, op=%x\n",
15167 			    files, MTBSF);
15168 
15169 		}
15170 	}
15171 
15172 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15173 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15174 		    "st_ioctl : EIO : MTBSF : check den wfm");
15175 		return (EIO);
15176 	}
15177 
15178 	if (files <= 0) {
15179 		/*
15180 		 * for a negative count, we need to step forward
15181 		 * first and then step back again
15182 		 */
15183 		files = -files + 1;
15184 		return (st_forward_space_files(un, files));
15185 	}
15186 	return (st_backward_space_files(un, files, 1));
15187 }
15188 
15189 static int
15190 st_backward_space_files(struct scsi_tape *un, int count, int infront)
15191 {
15192 	int end_fileno;
15193 	int skip_cnt;
15194 	int rval = 0;
15195 
15196 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
15197 
15198 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15199 	    "st_backward_space_files: count=%x eof=%x\n",
15200 	    count, un->un_pos.eof);
15201 	/*
15202 	 * Backspace files (MTNBSF): infront == 0
15203 	 *
15204 	 *	For tapes that can backspace, backspace
15205 	 *	count+1 filemarks and then run forward over
15206 	 *	a filemark
15207 	 *
15208 	 *	For tapes that can't backspace,
15209 	 *		calculate desired filenumber
15210 	 *		(un->un_pos.fileno - count), rewind,
15211 	 *		and then space forward this amount
15212 	 *
15213 	 * Backspace filemarks (MTBSF) infront == 1
15214 	 *
15215 	 *	For tapes that can backspace, backspace count
15216 	 *	filemarks
15217 	 *
15218 	 *	For tapes that can't backspace, calculate
15219 	 *	desired filenumber (un->un_pos.fileno - count),
15220 	 *	add 1, rewind, space forward this amount,
15221 	 *	and mark state as ST_EOF_PENDING appropriately.
15222 	 */
15223 
15224 	if (un->un_pos.pmode == logical) {
15225 
15226 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15227 		    "st_backward_space_files: mt_op=%x count=%x"
15228 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
15229 		    un->un_pos.lgclblkno);
15230 
15231 
15232 		/* In case a drive that won't back space gets in logical mode */
15233 		if ((un->un_dp->options & ST_BSF) == 0) {
15234 			rval = EIO;
15235 			return (rval);
15236 		}
15237 		if ((infront == 1) &&
15238 		    (st_cmd(un, SCMD_SPACE, Fmk(-count), SYNC_CMD))) {
15239 			rval = EIO;
15240 			return (rval);
15241 		} else if ((infront == 0) &&
15242 		    (st_cmd(un, SCMD_SPACE, Fmk((-count)-1), SYNC_CMD)) &&
15243 		    (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
15244 			rval = EIO;
15245 			return (rval);
15246 		}
15247 		return (rval);
15248 	}
15249 
15250 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15251 	    "st_backward_space_files: mt_op=%x count=%x fileno=%x blkno=%x\n",
15252 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
15253 
15254 
15255 
15256 	/*
15257 	 * Handle the simple case of BOT
15258 	 * playing a role in these cmds.
15259 	 * We do this by calculating the
15260 	 * ending file number. If the ending
15261 	 * file is < BOT, rewind and set an
15262 	 * error and mark resid appropriately.
15263 	 * If we're backspacing a file (not a
15264 	 * filemark) and the target file is
15265 	 * the first file on the tape, just
15266 	 * rewind.
15267 	 */
15268 
15269 	/* figure expected destination of this SPACE command */
15270 	end_fileno = un->un_pos.fileno - count;
15271 
15272 	/*
15273 	 * Would the end effect of this SPACE be the same as rewinding?
15274 	 * If so just rewind instead.
15275 	 */
15276 	if ((infront != 0) && (end_fileno < 0) ||
15277 	    (infront == 0) && (end_fileno <= 0)) {
15278 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15279 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15280 			    "st_backward_space_files: EIO : "
15281 			    "rewind in lou of BSF failed\n");
15282 			rval = EIO;
15283 		}
15284 		if (end_fileno < 0) {
15285 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15286 			    "st_backward_space_files: EIO : "
15287 			    "back space file greater then fileno\n");
15288 			rval = EIO;
15289 			un->un_err_resid = -end_fileno;
15290 			un->un_status = SUN_KEY_BOT;
15291 		}
15292 		return (rval);
15293 	}
15294 
15295 	if (un->un_dp->options & ST_BSF) {
15296 		skip_cnt = 1 - infront;
15297 		/*
15298 		 * If we are going to end up at the beginning
15299 		 * of the file, we have to space one extra file
15300 		 * first, and then space forward later.
15301 		 */
15302 		end_fileno = -(count + skip_cnt);
15303 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15304 		    "skip_cnt=%x, tmp=%x\n", skip_cnt, end_fileno);
15305 		if (st_cmd(un, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
15306 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15307 			    "st_backward_space_files:EIO:back space fm failed");
15308 			rval = EIO;
15309 		}
15310 	} else {
15311 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15312 			rval = EIO;
15313 		} else {
15314 			skip_cnt = end_fileno + infront;
15315 		}
15316 	}
15317 
15318 	/*
15319 	 * If we have to space forward, do so...
15320 	 */
15321 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15322 	    "space forward skip_cnt=%x, rval=%x\n", skip_cnt, rval);
15323 
15324 	if (rval == 0 && skip_cnt) {
15325 		if (st_cmd(un, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
15326 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15327 			    "st_backward_space_files:EIO:space fm skip count");
15328 			rval = EIO;
15329 		} else if (infront) {
15330 			/*
15331 			 * If we had to space forward, and we're
15332 			 * not a tape that can backspace, mark state
15333 			 * as if we'd just seen a filemark during a
15334 			 * a read.
15335 			 */
15336 			if ((un->un_dp->options & ST_BSF) == 0) {
15337 				un->un_pos.eof = ST_EOF_PENDING;
15338 				un->un_pos.fileno -= 1;
15339 				un->un_pos.blkno = LASTBLK;
15340 				un->un_running.pmode = invalid;
15341 			}
15342 		}
15343 	}
15344 
15345 	if (rval != 0) {
15346 		un->un_pos.pmode = invalid;
15347 	}
15348 
15349 	return (rval);
15350 }
15351 
15352 static int
15353 st_mtnbsf_ioctl(struct scsi_tape *un, int count)
15354 {
15355 	int rval;
15356 
15357 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
15358 
15359 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15360 	    "nbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
15361 
15362 	if (un->un_pos.pmode == legacy) {
15363 		/*
15364 		 * backward space file to beginning of file
15365 		 *
15366 		 * If a negative count (which implies a forward space op)
15367 		 * is specified, and we're at logical or physical eot,
15368 		 * bounce the request.
15369 		 */
15370 
15371 		if (un->un_pos.eof >= ST_EOT && count < 0) {
15372 			un->un_err_resid = count;
15373 			un->un_status = SUN_KEY_EOT;
15374 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15375 			    "st_ioctl : EIO : > EOT and count < 0");
15376 			return (EIO);
15377 		}
15378 		/*
15379 		 * physical tape position may not be what we've been
15380 		 * telling the user; adjust the request accordingly
15381 		 */
15382 		if (IN_EOF(un->un_pos)) {
15383 			un->un_pos.fileno++;
15384 			un->un_pos.blkno = 0;
15385 			count++;
15386 		}
15387 	}
15388 
15389 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15390 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15391 		    "st_ioctl : EIO : MTNBSF check den and wfm");
15392 		return (EIO);
15393 	}
15394 
15395 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15396 	    "mtnbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
15397 
15398 	if (count <= 0) {
15399 		rval = st_forward_space_files(un, -count);
15400 	} else {
15401 		rval = st_backward_space_files(un, count, 0);
15402 	}
15403 	return (rval);
15404 }
15405 
15406 static int
15407 st_mtbsr_ioctl(struct scsi_tape *un, int num)
15408 {
15409 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
15410 
15411 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15412 	    "bsr: count=%x, eof=%x\n", num, un->un_pos.eof);
15413 
15414 	if (un->un_pos.pmode == legacy) {
15415 		/*
15416 		 * backward space into inter-record gap
15417 		 *
15418 		 * If a negative count (which implies a forward space op)
15419 		 * is specified, and we're at logical or physical eot,
15420 		 * bounce the request.
15421 		 */
15422 		if (un->un_pos.eof >= ST_EOT && num < 0) {
15423 			un->un_err_resid = num;
15424 			un->un_status = SUN_KEY_EOT;
15425 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15426 			    "st_ioctl : EIO : MTBSR > EOT");
15427 			return (EIO);
15428 		}
15429 
15430 		if (num == 0) {
15431 			COPY_POS(&un->un_err_pos, &un->un_pos);
15432 			un->un_err_resid = 0;
15433 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15434 				un->un_status = SUN_KEY_EOF;
15435 			}
15436 			return (0);
15437 		}
15438 
15439 		/*
15440 		 * physical tape position may not be what we've been
15441 		 * telling the user; adjust the position accordingly.
15442 		 * bsr can not skip filemarks and continue to skip records
15443 		 * therefore if we are logically before the filemark but
15444 		 * physically at the EOT side of the filemark, we need to step
15445 		 * back; this allows fsr N where N > number of blocks in file
15446 		 * followed by bsr 1 to position at the beginning of last block
15447 		 */
15448 		if (IN_EOF(un->un_pos)) {
15449 			tapepos_t save;
15450 			optype lastop = un->un_lastop;
15451 
15452 			COPY_POS(&save, &un->un_pos);
15453 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD) == -1) {
15454 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15455 				    "st_mtbsr_ioctl: EIO : MTBSR can't space");
15456 				return (EIO);
15457 			}
15458 
15459 			COPY_POS(&un->un_pos, &save);
15460 			un->un_lastop = lastop;
15461 		}
15462 	}
15463 
15464 	un->un_pos.eof = ST_NO_EOF;
15465 
15466 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15467 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15468 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
15469 		return (EIO);
15470 	}
15471 
15472 	num = -num;
15473 	return (st_space_records(un, num));
15474 }
15475 
15476 static int
15477 st_mtfsfm_ioctl(struct scsi_tape *un, int cnt)
15478 {
15479 	int rval;
15480 
15481 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
15482 
15483 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
15484 	if (rval == 0) {
15485 		un->un_pos.pmode = logical;
15486 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15487 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15488 		/*
15489 		 * Drive says invalid field in cdb.
15490 		 * Doesn't like space multiple. Position isn't lost.
15491 		 */
15492 		un->un_err_resid = cnt;
15493 		un->un_status = 0;
15494 		rval = ENOTTY;
15495 	} else {
15496 		un->un_err_resid = cnt;
15497 		un->un_pos.pmode = invalid;
15498 	}
15499 	return (rval);
15500 }
15501 
15502 static int
15503 st_mtbsfm_ioctl(struct scsi_tape *un, int cnt)
15504 {
15505 	int rval;
15506 
15507 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
15508 
15509 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
15510 	if (rval == 0) {
15511 		un->un_pos.pmode = logical;
15512 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15513 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15514 		/*
15515 		 * Drive says invalid field in cdb.
15516 		 * Doesn't like space multiple. Position isn't lost.
15517 		 */
15518 		un->un_err_resid = cnt;
15519 		un->un_status = 0;
15520 		rval = ENOTTY;
15521 	} else {
15522 		un->un_err_resid = cnt;
15523 		un->un_pos.pmode = invalid;
15524 	}
15525 	return (rval);
15526 }
15527 
15528 #ifdef	__x86
15529 
15530 /*
15531  * release contig_mem and wake up waiting thread, if any
15532  */
15533 static void
15534 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
15535 {
15536 	mutex_enter(ST_MUTEX);
15537 
15538 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
15539 
15540 	cp->cm_next = un->un_contig_mem;
15541 	un->un_contig_mem = cp;
15542 	un->un_contig_mem_available_num++;
15543 	cv_broadcast(&un->un_contig_mem_cv);
15544 
15545 	mutex_exit(ST_MUTEX);
15546 }
15547 
15548 /*
15549  * St_get_contig_mem will return a contig_mem if there is one available
15550  * in current system. Otherwise, it will try to alloc one, if the total
15551  * number of contig_mem is within st_max_contig_mem_num.
15552  * It will sleep, if allowed by caller or return NULL, if no contig_mem
15553  * is available for now.
15554  */
15555 static struct contig_mem *
15556 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
15557 {
15558 	size_t rlen;
15559 	struct contig_mem *cp = NULL;
15560 	ddi_acc_handle_t acc_hdl;
15561 	caddr_t addr;
15562 	int big_enough = 0;
15563 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
15564 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
15565 
15566 	/* Try to get one available contig_mem */
15567 	mutex_enter(ST_MUTEX);
15568 
15569 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
15570 
15571 	if (un->un_contig_mem_available_num > 0) {
15572 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15573 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
15574 		/*
15575 		 * we failed to get one. we're going to
15576 		 * alloc one more contig_mem for this I/O
15577 		 */
15578 		mutex_exit(ST_MUTEX);
15579 		cp = (struct contig_mem *)kmem_zalloc(
15580 		    sizeof (struct contig_mem) + biosize(),
15581 		    alloc_flags);
15582 		if (cp == NULL) {
15583 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15584 			    "alloc contig_mem failure\n");
15585 			return (NULL); /* cannot get one */
15586 		}
15587 		cp->cm_bp = (struct buf *)
15588 		    (((caddr_t)cp) + sizeof (struct contig_mem));
15589 		bioinit(cp->cm_bp);
15590 		mutex_enter(ST_MUTEX);
15591 		un->un_contig_mem_total_num++; /* one more available */
15592 	} else {
15593 		/*
15594 		 * we failed to get one and we're NOT allowed to
15595 		 * alloc more contig_mem
15596 		 */
15597 		if (alloc_flags == KM_SLEEP) {
15598 			while (un->un_contig_mem_available_num <= 0) {
15599 				cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
15600 			}
15601 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15602 		} else {
15603 			mutex_exit(ST_MUTEX);
15604 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15605 			    "alloc contig_mem failure\n");
15606 			return (NULL); /* cannot get one */
15607 		}
15608 	}
15609 	mutex_exit(ST_MUTEX);
15610 
15611 	/* We need to check if this block of mem is big enough for this I/O */
15612 	if (cp->cm_len < len) {
15613 		/* not big enough, need to alloc a new one */
15614 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
15615 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
15616 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
15617 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15618 			    "alloc contig_mem failure: not enough mem\n");
15619 			st_release_contig_mem(un, cp);
15620 			cp = NULL;
15621 		} else {
15622 			if (cp->cm_addr) {
15623 				/* release previous one before attach new one */
15624 				ddi_dma_mem_free(&cp->cm_acc_hdl);
15625 			}
15626 			mutex_enter(ST_MUTEX);
15627 			un->un_max_contig_mem_len =
15628 			    un->un_max_contig_mem_len >= len ?
15629 			    un->un_max_contig_mem_len : len;
15630 			mutex_exit(ST_MUTEX);
15631 
15632 			/* attach new mem to this cp */
15633 			cp->cm_addr = addr;
15634 			cp->cm_acc_hdl = acc_hdl;
15635 			cp->cm_len = len;
15636 
15637 			goto alloc_ok; /* get one usable cp */
15638 		}
15639 	} else {
15640 		goto alloc_ok; /* get one usable cp */
15641 	}
15642 
15643 	/* cannot find/alloc a usable cp, when we get here */
15644 
15645 	mutex_enter(ST_MUTEX);
15646 	if ((un->un_max_contig_mem_len < len) ||
15647 	    (alloc_flags != KM_SLEEP)) {
15648 		mutex_exit(ST_MUTEX);
15649 		return (NULL);
15650 	}
15651 
15652 	/*
15653 	 * we're allowed to sleep, and there is one big enough
15654 	 * contig mem in the system, which is currently in use,
15655 	 * wait for it...
15656 	 */
15657 	big_enough = 1;
15658 	do {
15659 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
15660 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15661 	} while (cp == NULL);
15662 	mutex_exit(ST_MUTEX);
15663 
15664 	/* we get the big enough contig mem, finally */
15665 
15666 alloc_ok:
15667 	/* init bp attached to this cp */
15668 	bioreset(cp->cm_bp);
15669 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
15670 	cp->cm_bp->b_private = (void *)cp;
15671 
15672 	return (cp);
15673 }
15674 
15675 /*
15676  * this is the biodone func for the bp used in big block I/O
15677  */
15678 static int
15679 st_bigblk_xfer_done(struct buf *bp)
15680 {
15681 	struct contig_mem *cp;
15682 	struct buf *orig_bp;
15683 	int ioerr;
15684 	struct scsi_tape *un;
15685 
15686 	/* sanity check */
15687 	if (bp == NULL) {
15688 		return (DDI_FAILURE);
15689 	}
15690 
15691 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
15692 	if (un == NULL) {
15693 		return (DDI_FAILURE);
15694 	}
15695 
15696 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
15697 
15698 	cp = (struct contig_mem *)bp->b_private;
15699 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
15700 	cp->cm_bp = bp;
15701 
15702 	/* special handling for special I/O */
15703 	if (cp->cm_use_sbuf) {
15704 #ifndef __lock_lint
15705 		ASSERT(un->un_sbuf_busy);
15706 #endif
15707 		un->un_sbufp = orig_bp;
15708 		cp->cm_use_sbuf = 0;
15709 	}
15710 
15711 	orig_bp->b_resid = bp->b_resid;
15712 	ioerr = geterror(bp);
15713 	if (ioerr != 0) {
15714 		bioerror(orig_bp, ioerr);
15715 	} else if (orig_bp->b_flags & B_READ) {
15716 		/* copy data back to original bp */
15717 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
15718 		    bp->b_bcount - bp->b_resid);
15719 	}
15720 
15721 	st_release_contig_mem(un, cp);
15722 
15723 	biodone(orig_bp);
15724 
15725 	return (DDI_SUCCESS);
15726 }
15727 
15728 /*
15729  * We use this func to replace original bp that may not be able to do I/O
15730  * in big block size with one that can
15731  */
15732 static struct buf *
15733 st_get_bigblk_bp(struct buf *bp)
15734 {
15735 	struct contig_mem *cp;
15736 	struct scsi_tape *un;
15737 	struct buf *cont_bp;
15738 
15739 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
15740 	if (un == NULL) {
15741 		return (bp);
15742 	}
15743 
15744 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
15745 
15746 	/* try to get one contig_mem */
15747 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
15748 	if (!cp) {
15749 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
15750 		    "Cannot alloc contig buf for I/O for %lu blk size",
15751 		    bp->b_bcount);
15752 		return (bp);
15753 	}
15754 	cont_bp = cp->cm_bp;
15755 	cp->cm_bp = bp;
15756 
15757 	/* make sure that we "are" using un_sbufp for special I/O */
15758 	if (bp == un->un_sbufp) {
15759 #ifndef __lock_lint
15760 		ASSERT(un->un_sbuf_busy);
15761 #endif
15762 		un->un_sbufp = cont_bp;
15763 		cp->cm_use_sbuf = 1;
15764 	}
15765 
15766 	/* clone bp */
15767 	cont_bp->b_bcount = bp->b_bcount;
15768 	cont_bp->b_resid = bp->b_resid;
15769 	cont_bp->b_iodone = st_bigblk_xfer_done;
15770 	cont_bp->b_file = bp->b_file;
15771 	cont_bp->b_offset = bp->b_offset;
15772 	cont_bp->b_dip = bp->b_dip;
15773 	cont_bp->b_error = 0;
15774 	cont_bp->b_proc = NULL;
15775 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
15776 	cont_bp->b_shadow = NULL;
15777 	cont_bp->b_pages = NULL;
15778 	cont_bp->b_edev = bp->b_edev;
15779 	cont_bp->b_dev = bp->b_dev;
15780 	cont_bp->b_lblkno = bp->b_lblkno;
15781 	cont_bp->b_forw = bp->b_forw;
15782 	cont_bp->b_back = bp->b_back;
15783 	cont_bp->av_forw = bp->av_forw;
15784 	cont_bp->av_back = bp->av_back;
15785 	cont_bp->b_bufsize = bp->b_bufsize;
15786 
15787 	/* get data in original bp */
15788 	if (bp->b_flags & B_WRITE) {
15789 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
15790 	}
15791 
15792 	return (cont_bp);
15793 }
15794 #else
15795 #ifdef __lock_lint
15796 static int
15797 st_bigblk_xfer_done(struct buf *bp)
15798 {
15799 	return (0);
15800 }
15801 #endif
15802 #endif
15803 
15804 static const char *eof_status[] =
15805 {
15806 	"NO_EOF",
15807 	"EOF_PENDING",
15808 	"EOF",
15809 	"EOT_PENDING",
15810 	"EOT",
15811 	"EOM",
15812 	"AFTER_EOM"
15813 };
15814 static const char *mode[] = {
15815 	"invalid",
15816 	"legacy",
15817 	"logical"
15818 };
15819 
15820 static void
15821 st_print_position(dev_info_t *dev, char *label, uint_t level,
15822 const char *comment, tapepos_t *pos)
15823 {
15824 	ST_FUNC(dev, st_print_position);
15825 
15826 	scsi_log(dev, label, level,
15827 	    "%s Position data:\n", comment);
15828 	scsi_log(dev, label, CE_CONT,
15829 	    "Positioning mode = %s", mode[pos->pmode]);
15830 	scsi_log(dev, label, CE_CONT,
15831 	    "End Of File/Tape = %s", eof_status[pos->eof]);
15832 	scsi_log(dev, label, CE_CONT,
15833 	    "File Number      = 0x%x", pos->fileno);
15834 	scsi_log(dev, label, CE_CONT,
15835 	    "Block Number     = 0x%x", pos->blkno);
15836 	scsi_log(dev, label, CE_CONT,
15837 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
15838 	scsi_log(dev, label, CE_CONT,
15839 	    "Partition Number = 0x%x", pos->partition);
15840 }
15841 static int
15842 st_check_if_media_changed(struct scsi_tape *un, caddr_t data, int size)
15843 {
15844 
15845 	int result = 0;
15846 	int i;
15847 	ST_FUNC(ST_DEVINFO, st_check_if_media_changed);
15848 
15849 	/*
15850 	 * find non alpha numeric working from the end.
15851 	 */
15852 	for (i = size - 1; i; i--) {
15853 		if (ISALNUM(data[i]) == 0 || data[i] == ' ') {
15854 			data[i] = 0;
15855 			size = i;
15856 		}
15857 	}
15858 
15859 	if (size == 1) {
15860 		/*
15861 		 * Drive seems to think its returning useful data
15862 		 * but it looks like all junk
15863 		 */
15864 		return (result);
15865 	}
15866 
15867 	size++;
15868 
15869 	/*
15870 	 * Actually got a valid serial number.
15871 	 * If never stored one before alloc space for it.
15872 	 */
15873 	if (un->un_media_id_len == 0) {
15874 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
15875 		un->un_media_id_len = size;
15876 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
15877 		un->un_media_id[min(size, strlen(data))] = 0;
15878 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
15879 		    "Found Media Id %s length = %d\n", un->un_media_id, size);
15880 	} else if (size > un->un_media_id_len) {
15881 		if (strncmp(un->un_media_id, data, size) != 0) {
15882 			result = ESPIPE;
15883 		}
15884 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
15885 		    "Longer Media Id old ID:%s new ID:%s\n",
15886 		    un->un_media_id, data);
15887 		kmem_free(un->un_media_id, un->un_media_id_len);
15888 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
15889 		un->un_media_id_len = size;
15890 		(void) strncpy(un->un_media_id, data, size);
15891 		un->un_media_id[size] = 0;
15892 	} else if (strncmp(data, un->un_media_id,
15893 	    min(size, un->un_media_id_len)) != 0) {
15894 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
15895 		    "Old Media Id %s length = %d New %s length = %d\n",
15896 		    un->un_media_id, un->un_media_id_len, data, size);
15897 		bzero(un->un_media_id, un->un_media_id_len);
15898 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
15899 		un->un_media_id[min(size, strlen(data))] = 0;
15900 		result = ESPIPE;
15901 	} else {
15902 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15903 		    "Media Id still %s\n", un->un_media_id);
15904 	}
15905 
15906 	ASSERT(strlen(un->un_media_id) <= size);
15907 
15908 	return (result);
15909 }
15910 #define	ID_SIZE 32
15911 typedef struct
15912 {
15913 	uchar_t avilable_data0;
15914 	uchar_t avilable_data1;
15915 	uchar_t avilable_data2;
15916 	uchar_t avilable_data3;
15917 	uchar_t attribute_msb;
15918 	uchar_t attribute_lsb;
15919 #ifdef _BIT_FIELDS_LTOH
15920 	uchar_t format		: 2,
15921 				: 5,
15922 		read_only	: 1;
15923 #else
15924 	uchar_t read_only	: 1,
15925 				: 5,
15926 		format		: 2;
15927 #endif
15928 	uchar_t attribute_len_msb;
15929 	uchar_t attribute_len_lsb;
15930 }attribute_header;
15931 
15932 typedef struct {
15933 	attribute_header header;
15934 	char data[1];
15935 }mam_attribute;
15936 
15937 static int
15938 st_handle_hex_media_id(struct scsi_tape *un, void *pnt, int size)
15939 {
15940 	int result;
15941 	int newsize = (size + 1) << 1;
15942 	int i;
15943 	char byte;
15944 	char *format;
15945 	char *data = (char *)pnt;
15946 	char *buf = kmem_alloc(newsize, KM_SLEEP);
15947 
15948 	ST_FUNC(ST_DEVINFO, st_handle_hex_media_id);
15949 
15950 	(void) sprintf(buf, "0x");
15951 	for (i = 0; i < size; i++) {
15952 		byte = (uchar_t)data[i];
15953 		if (byte < 0x10)
15954 			format = "0%x";
15955 		else
15956 			format = "%x";
15957 		(void) sprintf(&buf[(int)strlen(buf)], format, byte);
15958 	}
15959 	result = st_check_if_media_changed(un, buf, newsize);
15960 
15961 	kmem_free(buf, newsize);
15962 
15963 	return (result);
15964 }
15965 
15966 
15967 static int
15968 st_get_media_id_via_read_attribute(struct scsi_tape *un, ubufunc_t bufunc)
15969 {
15970 	int result;
15971 	mam_attribute *buffer;
15972 	int size;
15973 	int newsize;
15974 
15975 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_read_attribute);
15976 	size = sizeof (attribute_header) + max(un->un_media_id_len, ID_SIZE);
15977 again:
15978 	buffer = kmem_zalloc(size, KM_SLEEP);
15979 	result = st_read_attributes(un, 0x0401, buffer, size, bufunc);
15980 	if (result == 0) {
15981 
15982 		newsize = (buffer->header.attribute_len_msb << 8) |
15983 		    buffer->header.attribute_len_lsb;
15984 
15985 		if (newsize + sizeof (attribute_header) > size) {
15986 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15987 			    "resizing read attribute data from %d to %d format"
15988 			    " %d\n", size, (int)sizeof (attribute_header) +
15989 			    newsize, buffer->header.format);
15990 			kmem_free(buffer, size);
15991 			size = newsize + sizeof (attribute_header);
15992 			goto again;
15993 		}
15994 
15995 		un->un_media_id_method = st_get_media_id_via_read_attribute;
15996 		if (buffer->header.format == 0) {
15997 			result =
15998 			    st_handle_hex_media_id(un, buffer->data, newsize);
15999 		} else {
16000 			result = st_check_if_media_changed(un, buffer->data,
16001 			    newsize);
16002 		}
16003 	} else if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
16004 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
16005 		    "Read Attribute Command for Media Identification is not "
16006 		    "supported on the HBA that this drive is attached to.");
16007 		result = ENOTTY;
16008 	}
16009 
16010 	kmem_free(buffer, size);
16011 	un->un_status = 0;
16012 
16013 	return (result);
16014 }
16015 
16016 
16017 static int
16018 st_get_media_id_via_media_serial_cmd(struct scsi_tape *un, ubufunc_t bufunc)
16019 {
16020 	char cdb[CDB_GROUP5];
16021 	struct uscsi_cmd *ucmd;
16022 	struct scsi_extended_sense sense;
16023 	int rval;
16024 	int size = max(un->un_media_id_len, ID_SIZE);
16025 	caddr_t buf;
16026 
16027 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_media_serial_cmd);
16028 
16029 	if (un->un_sd->sd_inq->inq_ansi < 3) {
16030 		return (ENOTTY);
16031 	}
16032 
16033 	ucmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
16034 upsize:
16035 	buf = kmem_alloc(size, KM_SLEEP);
16036 
16037 	cdb[0] = (char)SCMD_SVC_ACTION_IN_G5;
16038 	cdb[1] = 1; /* READ MEDIA SERIAL NUMBER */
16039 	cdb[2] = 0;
16040 	cdb[3] = 0;
16041 	cdb[4] = 0;
16042 	cdb[5] = 0;
16043 	cdb[6] = (char)(size >> 24);
16044 	cdb[7] = (char)(size >> 16);
16045 	cdb[8] = (char)(size >> 8);
16046 	cdb[9] = (char)(size);
16047 	cdb[10] = 0;
16048 	cdb[11] = 0;
16049 
16050 	ucmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
16051 	ucmd->uscsi_timeout = un->un_dp->non_motion_timeout;
16052 	ucmd->uscsi_cdb = &cdb[0];
16053 	ucmd->uscsi_cdblen = sizeof (cdb);
16054 	ucmd->uscsi_bufaddr = buf;
16055 	ucmd->uscsi_buflen = size;
16056 	ucmd->uscsi_rqbuf = (caddr_t)&sense;
16057 	ucmd->uscsi_rqlen = sizeof (sense);
16058 
16059 	rval = bufunc(un, ucmd, FKIOCTL);
16060 
16061 	if (rval || ucmd->uscsi_status != 0) {
16062 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16063 		    "media serial command returned %d scsi_status %d"
16064 		    " rqstatus %d", rval, ucmd->uscsi_status,
16065 		    ucmd->uscsi_rqstatus);
16066 		/*
16067 		 * If this returns invalid operation code don't try again.
16068 		 */
16069 		if (sense.es_key == KEY_ILLEGAL_REQUEST &&
16070 		    sense.es_add_code == 0x20) {
16071 			rval = ENOTTY;
16072 		} else if (rval == 0) {
16073 			rval = EIO;
16074 		}
16075 		un->un_status = 0;
16076 	} else {
16077 		int act_size;
16078 
16079 		/*
16080 		 * get reported size.
16081 		 */
16082 		act_size = (int)buf[3] | (int)(buf[2] << 8) |
16083 		    (int)(buf[1] << 16) | (int)(buf[0] << 24);
16084 
16085 		/* documentation says mod 4. */
16086 		while (act_size & 3) {
16087 			act_size++;
16088 		}
16089 
16090 		/*
16091 		 * If reported size is larger that we our buffer.
16092 		 * Free the old one and allocate one that is larger
16093 		 * enough and re-issuse the command.
16094 		 */
16095 		if (act_size + 4 > size) {
16096 			kmem_free(buf, size);
16097 			size = act_size + 4;
16098 			goto upsize;
16099 		}
16100 
16101 		/*
16102 		 * set data pointer to point to the start of that serial number.
16103 		 */
16104 		un->un_media_id_method = st_get_media_id_via_media_serial_cmd;
16105 		rval = st_check_if_media_changed(un, &buf[4], act_size);
16106 	}
16107 
16108 	kmem_free(ucmd, sizeof (struct uscsi_cmd));
16109 	kmem_free(buf, size);
16110 
16111 	return (rval);
16112 }
16113 
16114 
16115 /* ARGSUSED */
16116 static int
16117 st_bogus_media_id(struct scsi_tape *un, ubufunc_t bufunc)
16118 {
16119 	ST_FUNC(ST_DEVINFO, st_bogus_media_id);
16120 
16121 	ASSERT(un->un_media_id == NULL || un->un_media_id == bogusID);
16122 	ASSERT(un->un_media_id_len == 0);
16123 	un->un_media_id = (char *)bogusID;
16124 	un->un_media_id_len = 0;
16125 	return (0);
16126 }
16127 
16128 typedef int (*media_chk_function)(struct scsi_tape *, ubufunc_t bufunc);
16129 
16130 media_chk_function media_chk_functions[] = {
16131 	st_get_media_id_via_media_serial_cmd,
16132 	st_get_media_id_via_read_attribute,
16133 	st_bogus_media_id
16134 };
16135 
16136 static int
16137 st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc)
16138 {
16139 	int result = 0;
16140 	int i;
16141 
16142 	ST_FUNC(ST_DEVINFO, st_get_media_identification);
16143 
16144 	for (i = 0; i < ST_NUM_MEMBERS(media_chk_functions); i++) {
16145 		if (result == ENOTTY) {
16146 			/*
16147 			 * Last operation type not supported by this device.
16148 			 * Make so next time it doesn`t do that again.
16149 			 */
16150 			un->un_media_id_method = media_chk_functions[i];
16151 		} else if (un->un_media_id_method != media_chk_functions[i] &&
16152 		    un->un_media_id_method != st_get_media_identification) {
16153 			continue;
16154 		}
16155 		result = media_chk_functions[i](un, bufunc);
16156 		/*
16157 		 * If result indicates the function was successful or
16158 		 * that the media is not the same as last known, break.
16159 		 */
16160 		if (result == 0 || result == ESPIPE) {
16161 			break;
16162 		}
16163 	}
16164 
16165 	return (result);
16166 }
16167 
16168 static errstate
16169 st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
16170     errstate onentry)
16171 {
16172 
16173 	int ret;
16174 	st_err_info *errinfo;
16175 	recov_info *ri = (recov_info *)pkt->pkt_private;
16176 
16177 	ST_FUNC(ST_DEVINFO, st_command_recovery);
16178 
16179 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16180 
16181 	ASSERT(un->un_recov_buf_busy == 0);
16182 
16183 	/*
16184 	 * Don't try and recover a reset that this device sent.
16185 	 */
16186 	if (un->un_rsvd_status & ST_INITIATED_RESET &&
16187 	    onentry == DEVICE_RESET) {
16188 		return (COMMAND_DONE_ERROR);
16189 	}
16190 
16191 	/*
16192 	 * See if expected position was passed with scsi_pkt.
16193 	 */
16194 	if (ri->privatelen == sizeof (recov_info)) {
16195 
16196 		/*
16197 		 * Not for this command.
16198 		 */
16199 		if (ri->cmd_attrib->do_not_recover) {
16200 			return (COMMAND_DONE_ERROR);
16201 		}
16202 
16203 		/*
16204 		 * Create structure to hold all error state info.
16205 		 */
16206 		errinfo = kmem_zalloc(sizeof (st_err_info), KM_SLEEP);
16207 		errinfo->ei_error_type = onentry;
16208 		errinfo->ei_failing_bp = ri->cmd_bp;
16209 		COPY_POS(&errinfo->ei_expected_pos, &ri->pos);
16210 	} else {
16211 		/* disabled */
16212 		return (COMMAND_DONE_ERROR);
16213 	}
16214 
16215 	bcopy(pkt, &errinfo->ei_failed_pkt, sizeof (struct scsi_pkt));
16216 	bcopy(pkt->pkt_scbp, &errinfo->ei_failing_status, SECMDS_STATUS_SIZE);
16217 	ret = ddi_taskq_dispatch(un->un_recov_taskq, st_recover, errinfo,
16218 	    DDI_NOSLEEP);
16219 	ASSERT(ret == DDI_SUCCESS);
16220 	if (ret != DDI_SUCCESS) {
16221 		kmem_free(errinfo, sizeof (st_err_info));
16222 		return (COMMAND_DONE_ERROR);
16223 	}
16224 	return (JUST_RETURN); /* release calling thread */
16225 }
16226 
16227 static void
16228 st_recov_ret(struct scsi_tape *un, st_err_info *errinfo, errstate err)
16229 {
16230 	int error_number;
16231 	buf_t *bp;
16232 
16233 
16234 	ST_FUNC(ST_DEVINFO, st_recov_ret);
16235 
16236 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16237 
16238 	bp = errinfo->ei_failing_bp;
16239 	kmem_free(errinfo, sizeof (st_err_info));
16240 
16241 	switch (err) {
16242 	case JUST_RETURN:
16243 		mutex_exit(&un->un_sd->sd_mutex);
16244 		return;
16245 
16246 	case COMMAND_DONE:
16247 	case COMMAND_DONE_ERROR_RECOVERED:
16248 		ST_DO_KSTATS(bp, kstat_runq_exit);
16249 		error_number = 0;
16250 		break;
16251 
16252 	default:
16253 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16254 		    "st_recov_ret with unhandled errstat %d\n", err);
16255 		/* FALLTHROUGH */
16256 	case COMMAND_DONE_ERROR:
16257 	case COMMAND_DONE_EACCES:
16258 		ST_DO_KSTATS(bp, kstat_waitq_exit);
16259 		ST_DO_ERRSTATS(un, st_transerrs);
16260 		error_number = EIO;
16261 		st_set_pe_flag(un);
16262 		break;
16263 
16264 	}
16265 	st_bioerror(bp, error_number);
16266 	st_done_and_mutex_exit(un, bp);
16267 }
16268 
16269 static void
16270 st_recover(void *arg)
16271 {
16272 	st_err_info *const errinfo = (st_err_info *)arg;
16273 	uchar_t com = errinfo->ei_failed_pkt.pkt_cdbp[0];
16274 	struct scsi_tape *un;
16275 	tapepos_t cur_pos;
16276 	int rval;
16277 	errstate status = COMMAND_DONE_ERROR;
16278 	recov_info *rcv;
16279 	buf_t *bp;
16280 
16281 
16282 	rcv = errinfo->ei_failed_pkt.pkt_private;
16283 	ASSERT(rcv->privatelen == sizeof (recov_info));
16284 	bp = rcv->cmd_bp;
16285 
16286 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16287 
16288 	ASSERT(un != NULL);
16289 
16290 	mutex_enter(ST_MUTEX);
16291 
16292 	ST_FUNC(ST_DEVINFO, st_recover);
16293 
16294 	ST_CDB(ST_DEVINFO, "Recovering command",
16295 	    (caddr_t)errinfo->ei_failed_pkt.pkt_cdbp);
16296 	ST_SENSE(ST_DEVINFO, "sense status for failed command",
16297 	    (caddr_t)&errinfo->ei_failing_status,
16298 	    sizeof (struct scsi_arq_status));
16299 	ST_POS(ST_DEVINFO, rcv->cmd_attrib->recov_pos_type == POS_STARTING ?
16300 	    "starting position for recovery command" :
16301 	    "expected position for recovery command",
16302 	    &errinfo->ei_expected_pos);
16303 
16304 	rval = st_test_path_to_device(un);
16305 
16306 	/*
16307 	 * If the drive responed to the TUR lets try and get it to sync
16308 	 * any data it have in the buffer.
16309 	 */
16310 	if (rval == 0 && rcv->cmd_attrib->chg_tape_data) {
16311 		(void) st_rcmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
16312 	}
16313 	switch (errinfo->ei_error_type) {
16314 	case ATTEMPT_RETRY:
16315 	case COMMAND_TIMEOUT:
16316 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16317 		    "st_recover called with COMMAND_TIMEOUT, TUR returned %d\n",
16318 		    rval);
16319 		if (rval != 0) {
16320 			/* ping failed, we're done. */
16321 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16322 			return;
16323 		}
16324 
16325 		/*
16326 		 * If a reset occured fall through.
16327 		 */
16328 		if (un->un_unit_attention_flags == 0) {
16329 			break;
16330 		}
16331 		/* FALLTHROUGH */
16332 	case DEVICE_RESET:
16333 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16334 		    "st_recover called with DEVICE_RESET, TUR returned %d\n",
16335 		    rval);
16336 		/*
16337 		 * For now if we can't talk to the device we are done.
16338 		 */
16339 		if (rval) {
16340 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16341 			return;
16342 		}
16343 
16344 		if ((un->un_rsvd_status & ST_LOST_RESERVE) &&
16345 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] != SCMD_RELEASE)) {
16346 			rval = st_reserve_release(un, ST_RESERVE,
16347 			    st_uscsi_rcmd);
16348 			if (rval == 0) {
16349 				un->un_rsvd_status |= ST_RESERVE;
16350 				un->un_rsvd_status &= ~(ST_RELEASE |
16351 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
16352 				    ST_INITIATED_RESET);
16353 			} else {
16354 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16355 				return;
16356 			}
16357 			rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16358 			if (rval) {
16359 				rval = st_gen_mode_select(un, st_uscsi_rcmd,
16360 				    un->un_mspl, sizeof (struct seq_mode));
16361 			}
16362 			if (rval) {
16363 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16364 				return;
16365 			}
16366 		}
16367 		break;
16368 	case PATH_FAILED:
16369 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16370 		    "st_recover called with PATH_FAILED, TUR returned %d\n",
16371 		    rval);
16372 		if (rval != 0) {
16373 			/* ping failed, we're done. */
16374 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16375 			return;
16376 		}
16377 		break;
16378 	case DEVICE_TAMPER:
16379 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16380 		    "st_recover called with DEVICE_TAMPER, TUR returned %d\n",
16381 		    rval);
16382 		/*
16383 		 * Check if the ASC/ASCQ says mode data has changed.
16384 		 */
16385 		if (errinfo->ei_failing_status.sts_sensedata.es_add_code ==
16386 		    0x2a &&
16387 		    errinfo->ei_failing_status.sts_sensedata.es_qual_code ==
16388 		    0x01) {
16389 			/*
16390 			 * See if mode sense changed.
16391 			 */
16392 			rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16393 			/*
16394 			 * if not cross your fingers and go for it.
16395 			 */
16396 			if (rval == 0) {
16397 				st_recov_ret(un, errinfo, COMMAND_DONE);
16398 				return;
16399 			}
16400 			/*
16401 			 * If so change it back.
16402 			 */
16403 			rval = st_gen_mode_select(un, st_uscsi_rcmd,
16404 			    un->un_mspl, sizeof (struct seq_mode));
16405 			if (rval) {
16406 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16407 			} else {
16408 				st_recov_ret(un, errinfo, COMMAND_DONE);
16409 			}
16410 			return;
16411 		}
16412 		/*
16413 		 * if we have a media id and its not bogus.
16414 		 * Check to see if it the same.
16415 		 */
16416 		if (un->un_media_id != NULL && un->un_media_id != bogusID) {
16417 			rval = st_get_media_identification(un, st_uscsi_rcmd);
16418 			if (rval == ESPIPE) {
16419 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16420 				return;
16421 			}
16422 		}
16423 		break;
16424 	default:
16425 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16426 		    "Unhandled error type 0x%x in st_recover()\n", com);
16427 	}
16428 
16429 	/*
16430 	 * if command is retriable retry it
16431 	 */
16432 	if (rcv->cmd_attrib->retriable) {
16433 		status = st_recover_reissue_pkt(un, &errinfo->ei_failed_pkt);
16434 
16435 	/*
16436 	 * if drive doesn't support read position we are done
16437 	 */
16438 	} else if (un->un_read_pos_type == NO_POS) {
16439 		status = COMMAND_DONE_ERROR;
16440 	/*
16441 	 * If this command results in a changed tape position,
16442 	 * lets see where we are.
16443 	 */
16444 	} else if (rcv->cmd_attrib->chg_tape_pos) {
16445 		/*
16446 		 * XXX May be a reason to choose a different type here.
16447 		 * Long format has file position information.
16448 		 * Short and Extended have information about whats
16449 		 * in the buffer. St's positioning assumes in the buffer
16450 		 * to be the same as on tape.
16451 		 */
16452 		rval = st_compare_expected_position(un, errinfo,
16453 		    rcv->cmd_attrib, &cur_pos);
16454 		if (rval == 0) {
16455 			status = COMMAND_DONE;
16456 		} else if (rval == EAGAIN) {
16457 			status = st_recover_reissue_pkt(un,
16458 			    &errinfo->ei_failed_pkt);
16459 		} else {
16460 			status = COMMAND_DONE_ERROR;
16461 		}
16462 	} else {
16463 		ASSERT(0);
16464 	}
16465 
16466 	st_recov_ret(un, errinfo, status);
16467 }
16468 
16469 static void
16470 st_recov_cb(struct scsi_pkt *pkt)
16471 {
16472 	struct scsi_tape *un;
16473 	struct buf *bp;
16474 	recov_info *rcv;
16475 	errstate action = COMMAND_DONE;
16476 	int timout = ST_TRAN_BUSY_TIMEOUT; /* short (default) timeout */
16477 
16478 	/*
16479 	 * Get the buf from the packet.
16480 	 */
16481 	rcv = pkt->pkt_private;
16482 	ASSERT(rcv->privatelen == sizeof (recov_info));
16483 	bp = rcv->cmd_bp;
16484 
16485 	/*
16486 	 * get the unit from the buf.
16487 	 */
16488 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16489 	ASSERT(un != NULL);
16490 
16491 	ST_FUNC(ST_DEVINFO, st_recov_cb);
16492 
16493 	mutex_enter(ST_MUTEX);
16494 
16495 	ASSERT(bp == un->un_recov_buf);
16496 
16497 
16498 	switch (pkt->pkt_reason) {
16499 	case CMD_CMPLT:
16500 		if (un->un_arq_enabled && pkt->pkt_state & STATE_ARQ_DONE) {
16501 			action = st_handle_autosense(un, bp, &rcv->pos);
16502 		} else if (*pkt->pkt_scbp & (STATUS_BUSY | STATUS_CHECK)) {
16503 			action = st_check_error(un, pkt);
16504 		}
16505 		break;
16506 	case CMD_TIMEOUT:
16507 		action = COMMAND_TIMEOUT;
16508 		break;
16509 	default:
16510 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16511 		    "pkt_reason not handled yet %s",
16512 		    scsi_rname(pkt->pkt_reason));
16513 		action = COMMAND_DONE_ERROR;
16514 	}
16515 
16516 	switch (action) {
16517 	case COMMAND_DONE:
16518 		break;
16519 
16520 	case COMMAND_DONE_EACCES:
16521 		bioerror(bp, EACCES);
16522 		break;
16523 
16524 	case COMMAND_TIMEOUT:
16525 	case COMMAND_DONE_ERROR:
16526 		bioerror(bp, EIO);
16527 		break;
16528 
16529 	case DEVICE_RESET:
16530 	case QUE_BUSY_COMMAND:
16531 		/* longish timeout */
16532 		timout = ST_STATUS_BUSY_TIMEOUT;
16533 		/* FALLTHRU */
16534 	case QUE_COMMAND:
16535 	case DEVICE_TAMPER:
16536 	case ATTEMPT_RETRY:
16537 		/*
16538 		 * let st_handle_intr_busy put this bp back on waitq and make
16539 		 * checks to see if it is ok to requeue the command.
16540 		 */
16541 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
16542 
16543 		/*
16544 		 * Save the throttle before setting up the timeout
16545 		 */
16546 		if (un->un_throttle) {
16547 			un->un_last_throttle = un->un_throttle;
16548 		}
16549 		mutex_exit(ST_MUTEX);
16550 		if (st_handle_intr_busy(un, bp, timout) == 0) {
16551 			return;		/* timeout is setup again */
16552 		}
16553 		mutex_enter(ST_MUTEX);
16554 		un->un_pos.pmode = invalid;
16555 		un->un_err_resid = bp->b_resid = bp->b_bcount;
16556 		st_bioerror(bp, EIO);
16557 		st_set_pe_flag(un);
16558 		break;
16559 
16560 	default:
16561 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16562 		    "Unhandled recovery state 0x%x\n", action);
16563 		un->un_pos.pmode = invalid;
16564 		un->un_err_resid = bp->b_resid = bp->b_bcount;
16565 		st_bioerror(bp, EIO);
16566 		st_set_pe_flag(un);
16567 		break;
16568 	}
16569 
16570 	st_done_and_mutex_exit(un, bp);
16571 }
16572 
16573 static int
16574 st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait)
16575 {
16576 	struct buf *bp;
16577 	int err;
16578 
16579 	ST_FUNC(ST_DEVINFO, st_rcmd);
16580 
16581 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16582 	    "st_rcmd(un = 0x%p, com = 0x%x, count = %"PRIx64", wait = %d)\n",
16583 	    (void *)un, com, count, wait);
16584 
16585 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16586 	ASSERT(mutex_owned(ST_MUTEX));
16587 
16588 #ifdef STDEBUG
16589 	if ((st_debug & 0x7)) {
16590 		st_debug_cmds(un, com, count, wait);
16591 	}
16592 #endif
16593 
16594 	while (un->un_recov_buf_busy)
16595 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
16596 	un->un_recov_buf_busy = 1;
16597 
16598 	bp = un->un_recov_buf;
16599 	bzero(bp, sizeof (buf_t));
16600 
16601 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
16602 
16603 	err = st_setup_cmd(un, bp, com, count);
16604 
16605 	un->un_recov_buf_busy = 0;
16606 
16607 	cv_signal(&un->un_recov_buf_cv);
16608 
16609 	return (err);
16610 }
16611 
16612 /* args used */
16613 static int
16614 st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
16615 {
16616 	int rval;
16617 	buf_t *bp;
16618 
16619 	ST_FUNC(ST_DEVINFO, st_uscsi_rcmd);
16620 	ASSERT(flag == FKIOCTL);
16621 
16622 	/*
16623 	 * Get buffer resources...
16624 	 */
16625 	while (un->un_recov_buf_busy)
16626 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
16627 	un->un_recov_buf_busy = 1;
16628 
16629 	bp = un->un_recov_buf;
16630 	bzero(bp, sizeof (buf_t));
16631 
16632 	bp->b_forw = (struct buf *)(uintptr_t)ucmd->uscsi_cdb[0];
16633 	bp->b_back = (struct buf *)ucmd;
16634 
16635 	mutex_exit(ST_MUTEX);
16636 	rval = scsi_uscsi_handle_cmd(un->un_dev, UIO_SYSSPACE, ucmd,
16637 	    st_strategy, bp, NULL);
16638 	mutex_enter(ST_MUTEX);
16639 
16640 	ucmd->uscsi_resid = bp->b_resid;
16641 
16642 	/*
16643 	 * Free resources
16644 	 */
16645 	un->un_recov_buf_busy = 0;
16646 	cv_signal(&un->un_recov_buf_cv);
16647 
16648 	return (rval);
16649 }
16650 
16651 /*
16652  * Add data to scsi_pkt to help know what to do if the command fails.
16653  */
16654 static void
16655 st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
16656     struct scsi_pkt *pkt)
16657 {
16658 	uint64_t count;
16659 	recov_info *rinfo = (recov_info *)pkt->pkt_private;
16660 
16661 	ST_FUNC(ST_DEVINFO, st_add_recovery_info_to_pkt);
16662 
16663 	ASSERT(rinfo->privatelen == sizeof (pkt_info) ||
16664 	    rinfo->privatelen == sizeof (recov_info));
16665 
16666 	SET_BP_PKT(bp, pkt);
16667 	rinfo->cmd_bp = bp;
16668 
16669 	if (rinfo->privatelen != sizeof (recov_info)) {
16670 		return;
16671 	}
16672 
16673 	rinfo->cmd_bp = bp;
16674 
16675 	rinfo->cmd_attrib = NULL;
16676 
16677 	/*
16678 	 * lookup the command attributes and add them to the recovery info.
16679 	 */
16680 	rinfo->cmd_attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
16681 
16682 	ASSERT(rinfo->cmd_attrib);
16683 
16684 	/*
16685 	 * For commands that there is no way to figure the expected position
16686 	 * once completed, we save the position the command was started from
16687 	 * so that if they fail we can position back and try again.
16688 	 * This has already been done in st_cmd() or st_iscsi_cmd().
16689 	 */
16690 	if (rinfo->cmd_attrib->recov_pos_type == POS_STARTING) {
16691 		/* save current position as the starting position. */
16692 		COPY_POS(&rinfo->pos, &un->un_pos);
16693 		un->un_running.pmode = invalid;
16694 		return;
16695 	}
16696 
16697 	/*
16698 	 * Don't want to update the running position for recovery.
16699 	 */
16700 	if (bp == un->un_recov_buf) {
16701 		rinfo->pos.pmode = un->un_running.pmode;
16702 		return;
16703 	}
16704 	/*
16705 	 * If running position is invalid copy the current position.
16706 	 * Running being set invalid means we are not in a read, write
16707 	 * or write filemark sequence.
16708 	 * We'll copy the current position and start from there.
16709 	 */
16710 	if (un->un_running.pmode == invalid) {
16711 		COPY_POS(&un->un_running, &un->un_pos);
16712 		COPY_POS(&rinfo->pos, &un->un_running);
16713 	} else {
16714 		COPY_POS(&rinfo->pos, &un->un_running);
16715 		if (rinfo->pos.pmode == legacy) {
16716 			/*
16717 			 * Always should be more logical blocks then
16718 			 * data blocks and files marks.
16719 			 */
16720 			ASSERT((rinfo->pos.blkno >= 0) ?
16721 			    rinfo->pos.lgclblkno >=
16722 			    (rinfo->pos.blkno + rinfo->pos.fileno) : 1);
16723 		}
16724 	}
16725 
16726 	/*
16727 	 * If the command is not expected to change the drive position
16728 	 * then the running position should be the expected position.
16729 	 */
16730 	if (rinfo->cmd_attrib->chg_tape_pos == 0) {
16731 		ASSERT(rinfo->cmd_attrib->chg_tape_direction == DIR_NONE);
16732 		return;
16733 	}
16734 
16735 	if (rinfo->cmd_attrib->explicit) {
16736 		ASSERT(rinfo->pos.pmode != invalid);
16737 		ASSERT(rinfo->cmd_attrib->get_cnt);
16738 		count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
16739 		/*
16740 		 * This is a user generated CDB.
16741 		 */
16742 		if (bp == un->un_sbufp) {
16743 			uint64_t lbn;
16744 
16745 			lbn = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
16746 
16747 			/*
16748 			 * See if this CDB will generate a locate or change
16749 			 * partition.
16750 			 */
16751 			if ((lbn != un->un_running.lgclblkno) ||
16752 			    (pkt->pkt_cdbp[3] != un->un_running.partition)) {
16753 				rinfo->pos.partition = pkt->pkt_cdbp[3];
16754 				rinfo->pos.pmode = logical;
16755 				rinfo->pos.lgclblkno = lbn;
16756 				un->un_running.partition = pkt->pkt_cdbp[3];
16757 				un->un_running.pmode = logical;
16758 				un->un_running.lgclblkno = lbn;
16759 			}
16760 		} else {
16761 			uint64_t lbn = un->un_running.lgclblkno;
16762 
16763 			pkt->pkt_cdbp[3]  = (uchar_t)un->un_running.partition;
16764 
16765 			pkt->pkt_cdbp[4]  = (uchar_t)(lbn >> 56);
16766 			pkt->pkt_cdbp[5]  = (uchar_t)(lbn >> 48);
16767 			pkt->pkt_cdbp[6]  = (uchar_t)(lbn >> 40);
16768 			pkt->pkt_cdbp[7]  = (uchar_t)(lbn >> 32);
16769 			pkt->pkt_cdbp[8]  = (uchar_t)(lbn >> 24);
16770 			pkt->pkt_cdbp[9]  = (uchar_t)(lbn >> 16);
16771 			pkt->pkt_cdbp[10] = (uchar_t)(lbn >> 8);
16772 			pkt->pkt_cdbp[11] = (uchar_t)(lbn);
16773 		}
16774 		rinfo->pos.lgclblkno += count;
16775 		rinfo->pos.blkno += count;
16776 		un->un_running.lgclblkno += count;
16777 		return;
16778 	}
16779 
16780 	if (rinfo->cmd_attrib->chg_tape_pos) {
16781 
16782 		/* should not have got an invalid position from running. */
16783 		if (un->un_mediastate == MTIO_INSERTED) {
16784 			ASSERT(rinfo->pos.pmode != invalid);
16785 		}
16786 
16787 		/* should have either a get count or or get lba function */
16788 		ASSERT(rinfo->cmd_attrib->get_cnt != NULL ||
16789 		    rinfo->cmd_attrib->get_lba != NULL);
16790 
16791 		/* only explicit commands have both and they're handled above */
16792 		ASSERT(!(rinfo->cmd_attrib->get_cnt != NULL &&
16793 		    rinfo->cmd_attrib->get_lba != NULL));
16794 
16795 		/* if it has a get count function */
16796 		if (rinfo->cmd_attrib->get_cnt != NULL) {
16797 			count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
16798 			if (count == 0) {
16799 				return;
16800 			}
16801 			/*
16802 			 * Changes position but doesn't transfer data.
16803 			 * i.e. rewind, write_file_mark and load.
16804 			 */
16805 			if (rinfo->cmd_attrib->transfers_data == TRAN_NONE) {
16806 				switch (rinfo->cmd_attrib->chg_tape_direction) {
16807 				case DIR_NONE: /* Erase */
16808 					ASSERT(rinfo->cmd_attrib->cmd ==
16809 					    SCMD_ERASE);
16810 					break;
16811 				case DIR_FORW: /* write_file_mark */
16812 					rinfo->pos.fileno += count;
16813 					rinfo->pos.lgclblkno += count;
16814 					rinfo->pos.blkno = 0;
16815 					un->un_running.fileno += count;
16816 					un->un_running.lgclblkno += count;
16817 					un->un_running.blkno = 0;
16818 					break;
16819 				case DIR_REVC: /* rewind */
16820 					rinfo->pos.fileno = 0;
16821 					rinfo->pos.lgclblkno = 0;
16822 					rinfo->pos.blkno = 0;
16823 					rinfo->pos.eof = ST_NO_EOF;
16824 					rinfo->pos.pmode = legacy;
16825 					un->un_running.fileno = 0;
16826 					un->un_running.lgclblkno = 0;
16827 					un->un_running.blkno = 0;
16828 					un->un_running.eof = ST_NO_EOF;
16829 					if (un->un_running.pmode != legacy)
16830 						un->un_running.pmode = legacy;
16831 					break;
16832 				case DIR_EITH: /* Load unload */
16833 					ASSERT(rinfo->cmd_attrib->cmd ==
16834 					    SCMD_LOAD);
16835 					switch (count & (LD_LOAD | LD_RETEN |
16836 					    LD_RETEN | LD_HOLD)) {
16837 					case LD_UNLOAD:
16838 					case LD_RETEN:
16839 					case LD_HOLD:
16840 					case LD_LOAD | LD_HOLD:
16841 					case LD_EOT | LD_HOLD:
16842 					case LD_RETEN | LD_HOLD:
16843 						rinfo->pos.pmode = invalid;
16844 						un->un_running.pmode = invalid;
16845 						break;
16846 					case LD_EOT:
16847 					case LD_LOAD | LD_EOT:
16848 						rinfo->pos.eof = ST_EOT;
16849 						rinfo->pos.pmode = invalid;
16850 						un->un_running.eof = ST_EOT;
16851 						un->un_running.pmode = invalid;
16852 						break;
16853 					case LD_LOAD:
16854 					case LD_RETEN | LD_LOAD:
16855 						rinfo->pos.fileno = 0;
16856 						rinfo->pos.lgclblkno = 0;
16857 						rinfo->pos.blkno = 0;
16858 						rinfo->pos.eof = ST_NO_EOF;
16859 						rinfo->pos.pmode = legacy;
16860 						un->un_running.fileno = 0;
16861 						un->un_running.lgclblkno = 0;
16862 						un->un_running.blkno = 0;
16863 						un->un_running.eof = ST_NO_EOF;
16864 						break;
16865 					default:
16866 						ASSERT(0);
16867 					}
16868 					break;
16869 				default:
16870 					ASSERT(0);
16871 					break;
16872 				}
16873 			} else {
16874 				/*
16875 				 * Changes position and does transfer data.
16876 				 * i.e. read or write.
16877 				 */
16878 				switch (rinfo->cmd_attrib->chg_tape_direction) {
16879 				case DIR_FORW:
16880 					rinfo->pos.lgclblkno += count;
16881 					rinfo->pos.blkno += count;
16882 					un->un_running.lgclblkno += count;
16883 					un->un_running.blkno += count;
16884 					break;
16885 				case DIR_REVC:
16886 					rinfo->pos.lgclblkno -= count;
16887 					rinfo->pos.blkno -= count;
16888 					un->un_running.lgclblkno -= count;
16889 					un->un_running.blkno -= count;
16890 					break;
16891 				default:
16892 					ASSERT(0);
16893 					break;
16894 				}
16895 			}
16896 		} else if (rinfo->cmd_attrib->get_lba != NULL) {
16897 			/* Have a get LBA fuction. i.e. Locate */
16898 			ASSERT(rinfo->cmd_attrib->chg_tape_direction ==
16899 			    DIR_EITH);
16900 			count = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
16901 			un->un_running.lgclblkno = count;
16902 			un->un_running.blkno = 0;
16903 			un->un_running.fileno = 0;
16904 			un->un_running.pmode = logical;
16905 			rinfo->pos.lgclblkno = count;
16906 			rinfo->pos.pmode = invalid;
16907 		} else {
16908 			ASSERT(0);
16909 		}
16910 		return;
16911 	}
16912 
16913 	ST_CDB(ST_DEVINFO, "Unhanded CDB for position prediction",
16914 	    (char *)pkt->pkt_cdbp);
16915 
16916 }
16917 
16918 static int
16919 st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf)
16920 {
16921 	struct seq_mode *current;
16922 	int rval;
16923 	int i;
16924 	caddr_t this;
16925 	caddr_t that;
16926 
16927 	ST_FUNC(ST_DEVINFO, st_check_mode_for_change);
16928 
16929 	/* recovery called with mode tamper before mode selection */
16930 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
16931 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16932 		    "Mode Select not done yet");
16933 		return (0);
16934 	}
16935 
16936 	current = kmem_zalloc(sizeof (struct seq_mode), KM_SLEEP);
16937 
16938 	rval = st_gen_mode_sense(un, ubf, un->un_comp_page, current,
16939 	    sizeof (struct seq_mode));
16940 	if (rval != 0) {
16941 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16942 		    "Mode Sense for mode verification failed");
16943 		kmem_free(current, sizeof (struct seq_mode));
16944 		return (rval);
16945 	}
16946 
16947 	this = (caddr_t)current;
16948 	that = (caddr_t)un->un_mspl;
16949 
16950 	rval = bcmp(this, that, sizeof (struct seq_mode));
16951 	if (rval == 0) {
16952 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16953 		    "Found no changes in mode data");
16954 	}
16955 #ifdef STDEBUG
16956 	else {
16957 		for (i = 1; i < sizeof (struct seq_mode); i++) {
16958 			if (this[i] != that[i]) {
16959 				ST_RECOV(ST_DEVINFO, st_label, CE_CONT,
16960 				    "sense data changed at byte %d was "
16961 				    "0x%x now 0x%x", i,
16962 				    (uchar_t)that[i], (uchar_t)this[i]);
16963 			}
16964 		}
16965 	}
16966 #endif
16967 	kmem_free(current, sizeof (struct seq_mode));
16968 
16969 	return (rval);
16970 }
16971 
16972 static int
16973 st_test_path_to_device(struct scsi_tape *un)
16974 {
16975 	int rval;
16976 
16977 	ST_FUNC(ST_DEVINFO, st_test_path_to_device);
16978 
16979 	/*
16980 	 * XXX Newer drives may not RESEVATION CONFLICT a TUR.
16981 	 */
16982 	do {
16983 		rval = st_rcmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
16984 	} while (rval == DEVICE_RESET);
16985 
16986 	return (rval);
16987 }
16988 
16989 /*
16990  * Does read position using recov_buf and doesn't update un_pos.
16991  * Does what ever kind of read position you want.
16992  */
16993 static int
16994 st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
16995     read_pos_data_t *raw)
16996 {
16997 	int rval;
16998 	struct uscsi_cmd cmd;
16999 	char cdb[CDB_GROUP1];
17000 
17001 	ST_FUNC(ST_DEVINFO, st_recovery_read_pos);
17002 	bzero(&cmd, sizeof (cmd));
17003 
17004 	cdb[0] = SCMD_READ_POSITION;
17005 	cdb[1] = type;
17006 	cdb[2] = 0;
17007 	cdb[3] = 0;
17008 	cdb[4] = 0;
17009 	cdb[5] = 0;
17010 	cdb[6] = 0;
17011 	cdb[7] = 0;
17012 	cdb[8] =  (type == EXT_POS) ? 28 : 0;
17013 	cdb[9] = 0;
17014 
17015 	cmd.uscsi_flags = USCSI_READ;
17016 	cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
17017 	cmd.uscsi_cdb = cdb;
17018 	cmd.uscsi_cdblen = sizeof (cdb);
17019 	cmd.uscsi_bufaddr = (caddr_t)raw;
17020 	switch (type) {
17021 	case SHORT_POS:
17022 		cmd.uscsi_buflen = sizeof (tape_position_t);
17023 		break;
17024 	case LONG_POS:
17025 		cmd.uscsi_buflen = sizeof (tape_position_long_t);
17026 		break;
17027 	case EXT_POS:
17028 		cmd.uscsi_buflen = sizeof (tape_position_ext_t);
17029 		break;
17030 	default:
17031 		ASSERT(0);
17032 	}
17033 
17034 	rval = st_uscsi_rcmd(un, &cmd, FKIOCTL);
17035 	if (cmd.uscsi_status) {
17036 		rval = EIO;
17037 	}
17038 	return (rval);
17039 }
17040 
17041 static int
17042 st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
17043     read_pos_data_t *raw)
17044 {
17045 	int rval;
17046 	read_p_types type = un->un_read_pos_type;
17047 
17048 	ST_FUNC(ST_DEVINFO, st_recovery_get_position);
17049 
17050 	rval = st_recovery_read_pos(un, type, raw);
17051 	if (rval != 0) {
17052 		return (rval);
17053 	}
17054 	rval = st_interpret_read_pos(un, read, type, sizeof (read_pos_data_t),
17055 	    (caddr_t)raw, 1);
17056 
17057 	return (rval);
17058 }
17059 
17060 /*
17061  * based on the command do we retry, continue or give up?
17062  * possable return values?
17063  *	zero do nothing looks fine.
17064  *	EAGAIN retry.
17065  *	EIO failed makes no sense.
17066  */
17067 static int
17068 st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
17069     cmd_attribute const * cmd_att, tapepos_t *read)
17070 {
17071 	int rval;
17072 	read_pos_data_t *readp_datap;
17073 
17074 	ST_FUNC(ST_DEVINFO, st_compare_expected_position);
17075 
17076 	ASSERT(un != NULL);
17077 	ASSERT(ei != NULL);
17078 	ASSERT(read != NULL);
17079 	ASSERT(cmd_att->chg_tape_pos);
17080 
17081 	COPY_POS(read, &ei->ei_expected_pos);
17082 
17083 	readp_datap = kmem_zalloc(sizeof (read_pos_data_t), KM_SLEEP);
17084 
17085 	rval = st_recovery_get_position(un, read, readp_datap);
17086 
17087 	kmem_free(readp_datap, sizeof (read_pos_data_t));
17088 
17089 	if (rval != 0) {
17090 		return (EIO);
17091 	}
17092 
17093 	ST_POS(ST_DEVINFO, "st_compare_expected_position", read);
17094 
17095 	if ((read->pmode == invalid) ||
17096 	    (ei->ei_expected_pos.pmode == invalid)) {
17097 		return (EIO);
17098 	}
17099 
17100 	/*
17101 	 * Command that changes tape position and have an expected position
17102 	 * if it were to chave completed sucessfully.
17103 	 */
17104 	if (cmd_att->recov_pos_type == POS_EXPECTED) {
17105 		uint32_t count;
17106 		int64_t difference;
17107 
17108 		/* At expected? */
17109 		if (read->lgclblkno == ei->ei_expected_pos.lgclblkno) {
17110 			ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17111 			    "Found drive to be at expected position\n");
17112 			return (0); /* Good */
17113 		}
17114 		ASSERT(cmd_att->get_cnt);
17115 		count = cmd_att->get_cnt(ei->ei_failed_pkt.pkt_cdbp);
17116 
17117 		ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17118 		    "Got count from CDB and it was %d\n", count);
17119 		if (cmd_att->chg_tape_direction == DIR_FORW) {
17120 			difference =
17121 			    ei->ei_expected_pos.lgclblkno - read->lgclblkno;
17122 			ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17123 			    "difference between expected and actual is %"
17124 			    PRId64"\n", difference);
17125 			if (count == difference) {
17126 				ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17127 				    "Found failed FORW command, retrying\n");
17128 				return (EAGAIN);
17129 			}
17130 
17131 			/*
17132 			 * If rewound or somewhere between the starting position
17133 			 * and the expected position (partial read or write).
17134 			 * Locate to the starting position and try the whole
17135 			 * thing over again.
17136 			 */
17137 			if ((read->lgclblkno == 0) ||
17138 			    ((difference > 0) && (difference < count))) {
17139 				rval = st_logical_block_locate(un,
17140 				    st_uscsi_rcmd, read,
17141 				    ei->ei_expected_pos.lgclblkno - count,
17142 				    ei->ei_expected_pos.partition);
17143 				if (rval == 0) {
17144 					ST_RECOV(ST_DEVINFO, st_label,
17145 					    SCSI_DEBUG, "reestablished FORW"
17146 					    " command retrying\n");
17147 					return (EAGAIN);
17148 				}
17149 			/* This handles flushed read ahead on the drive */
17150 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17151 			    (difference < 0)) {
17152 				rval = st_logical_block_locate(un,
17153 				    st_uscsi_rcmd, read,
17154 				    ei->ei_expected_pos.lgclblkno - count,
17155 				    ei->ei_expected_pos.partition);
17156 				if (rval == 0) {
17157 					ST_RECOV(ST_DEVINFO, st_label,
17158 					    SCSI_DEBUG, "reestablished FORW"
17159 					    " read command retrying\n");
17160 					return (EAGAIN);
17161 				}
17162 			/*
17163 			 * XXX swag seeing difference of 2 on write filemark.
17164 			 * If the space to the starting position works on a
17165 			 * write that means the previous write made it to tape.
17166 			 * If not we lost data and have to give up.
17167 			 *
17168 			 * The plot thickens. Now I am attempting to cover a
17169 			 * count of 1 and a differance of 2 on a write.
17170 			 */
17171 			} else if (difference > count) {
17172 				rval = st_logical_block_locate(un,
17173 				    st_uscsi_rcmd, read,
17174 				    ei->ei_expected_pos.lgclblkno - count,
17175 				    ei->ei_expected_pos.partition);
17176 				if (rval == 0) {
17177 					ST_RECOV(ST_DEVINFO, st_label,
17178 					    SCSI_DEBUG, "reestablished FORW"
17179 					    " write command retrying\n");
17180 					return (EAGAIN);
17181 				}
17182 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17183 				    "Seek to block %"PRId64" returned %d\n",
17184 				    ei->ei_expected_pos.lgclblkno - count,
17185 				    rval);
17186 			} else {
17187 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17188 				    "Not expected transfers_data = %d "
17189 				    "difference = %"PRId64,
17190 				    cmd_att->transfers_data, difference);
17191 			}
17192 
17193 			return (EIO);
17194 
17195 		} else if (cmd_att->chg_tape_direction == DIR_REVC) {
17196 			/* Don't think we can write backwards */
17197 			ASSERT(cmd_att->transfers_data != TRAN_WRTE);
17198 			difference =
17199 			    read->lgclblkno - ei->ei_expected_pos.lgclblkno;
17200 			ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17201 			    "difference between expected and actual is %"
17202 			    PRId64"\n", difference);
17203 			if (count == difference) {
17204 				ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17205 				    "Found failed REVC command, retrying\n");
17206 				return (EAGAIN);
17207 			}
17208 			if ((read->lgclblkno == 0) ||
17209 			    ((difference > 0) && (difference < count))) {
17210 				rval = st_logical_block_locate(un,
17211 				    st_uscsi_rcmd, read,
17212 				    ei->ei_expected_pos.lgclblkno + count,
17213 				    ei->ei_expected_pos.partition);
17214 				if (rval == 0) {
17215 					ST_RECOV(ST_DEVINFO, st_label,
17216 					    SCSI_DEBUG, "reestablished REVC"
17217 					    " command retrying\n");
17218 					return (EAGAIN);
17219 				}
17220 			/* This handles read ahead in reverse direction */
17221 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17222 			    (difference < 0)) {
17223 				rval = st_logical_block_locate(un,
17224 				    st_uscsi_rcmd, read,
17225 				    ei->ei_expected_pos.lgclblkno - count,
17226 				    ei->ei_expected_pos.partition);
17227 				if (rval == 0) {
17228 					ST_RECOV(ST_DEVINFO, st_label,
17229 					    SCSI_DEBUG, "reestablished REVC"
17230 					    " read command retrying\n");
17231 					return (EAGAIN);
17232 				}
17233 			} else {
17234 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17235 				    "Not expected transfers_data = %d "
17236 				    "difference = %"PRId64,
17237 				    cmd_att->transfers_data, difference);
17238 			}
17239 			return (EIO);
17240 
17241 		} else {
17242 			/*
17243 			 * Commands that change tape position either
17244 			 * direction or don't change position should not
17245 			 * get here.
17246 			 */
17247 			ASSERT(0);
17248 		}
17249 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17250 		    "Didn't find a recoverable position, Failing\n");
17251 
17252 	/*
17253 	 * Command that changes tape position and can only be recovered
17254 	 * by going back to the point of origin and retrying.
17255 	 *
17256 	 * Example SCMD_SPACE.
17257 	 */
17258 	} else if (cmd_att->recov_pos_type == POS_STARTING) {
17259 		/*
17260 		 * This type of command stores the starting position.
17261 		 * If the read position is the starting position,
17262 		 * reissue the command.
17263 		 */
17264 		if (ei->ei_expected_pos.lgclblkno == read->lgclblkno) {
17265 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17266 			    "Found Space command at starting position, "
17267 			    "Reissuing\n");
17268 			return (EAGAIN);
17269 		}
17270 		/*
17271 		 * Not in the position that the command was originally issued,
17272 		 * Attempt to locate to that position.
17273 		 */
17274 		rval = st_logical_block_locate(un, st_uscsi_rcmd, read,
17275 		    ei->ei_expected_pos.lgclblkno,
17276 		    ei->ei_expected_pos.partition);
17277 		if (rval) {
17278 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17279 			    "Found Space at an unexpected position and locate "
17280 			    "back to starting position failed\n");
17281 			return (EIO);
17282 		}
17283 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17284 		    "Found Space at an unexpected position and locate "
17285 		    "back to starting position worked, Reissuing\n");
17286 		return (EAGAIN);
17287 	}
17288 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17289 	    "Unhandled attribute/expected position", &ei->ei_expected_pos);
17290 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17291 	    "Read position above did not make sense", read);
17292 	ASSERT(0);
17293 	return (EIO);
17294 }
17295 
17296 static errstate
17297 st_recover_reissue_pkt(struct scsi_tape *un, struct scsi_pkt *oldpkt)
17298 {
17299 	buf_t *bp;
17300 	buf_t *pkt_bp;
17301 	struct scsi_pkt *newpkt;
17302 	cmd_attribute const *attrib;
17303 	recov_info *rcv = oldpkt->pkt_private;
17304 	uint_t cdblen;
17305 	int rval;
17306 	int stat_size =
17307 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
17308 
17309 	ST_FUNC(ST_DEVINFO, st_recover_reissue_pkt);
17310 
17311 	bp = rcv->cmd_bp;
17312 
17313 	if (rcv->privatelen == sizeof (recov_info)) {
17314 		attrib = rcv->cmd_attrib;
17315 	} else {
17316 		attrib = st_lookup_cmd_attribute(oldpkt->pkt_cdbp[0]);
17317 	}
17318 
17319 	/*
17320 	 * Some non-uscsi commands use the b_bcount for values that
17321 	 * have nothing to do with how much data is transfered.
17322 	 * In those cases we need to hide the buf_t from scsi_init_pkt().
17323 	 */
17324 	if ((BP_UCMD(bp)) && (bp->b_bcount)) {
17325 		pkt_bp = bp;
17326 	} else if (attrib->transfers_data == TRAN_NONE) {
17327 		pkt_bp = NULL;
17328 	} else {
17329 		pkt_bp = bp;
17330 	}
17331 	/*
17332 	 * if this is a queued command make sure it the only one in the
17333 	 * run queue.
17334 	 */
17335 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
17336 		ASSERT(un->un_runqf == un->un_runql);
17337 		ASSERT(un->un_runqf == bp);
17338 	}
17339 
17340 	cdblen = scsi_cdb_size[CDB_GROUPID(oldpkt->pkt_cdbp[0])];
17341 
17342 	newpkt = scsi_init_pkt(ROUTE, NULL, pkt_bp, cdblen,
17343 	    stat_size, rcv->privatelen, 0, NULL_FUNC, NULL);
17344 	if (newpkt == NULL) {
17345 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17346 		    "Reissue pkt scsi_init_pkt() failure\n");
17347 		return (COMMAND_DONE_ERROR);
17348 	}
17349 
17350 	ASSERT(newpkt->pkt_resid == 0);
17351 	bp->b_flags &= ~(B_DONE);
17352 	bp->b_resid = 0;
17353 	st_bioerror(bp, 0);
17354 
17355 	bcopy(oldpkt->pkt_private, newpkt->pkt_private, rcv->privatelen);
17356 
17357 	newpkt->pkt_comp = oldpkt->pkt_comp;
17358 	newpkt->pkt_time = oldpkt->pkt_time;
17359 
17360 	bzero(newpkt->pkt_scbp, stat_size);
17361 	bcopy(oldpkt->pkt_cdbp, newpkt->pkt_cdbp, cdblen);
17362 
17363 	newpkt->pkt_state = 0;
17364 	newpkt->pkt_statistics = 0;
17365 
17366 	oldpkt = BP_PKT(bp);
17367 
17368 	SET_BP_PKT(bp, newpkt);
17369 
17370 	scsi_destroy_pkt(oldpkt);
17371 
17372 	rval = st_transport(un, newpkt);
17373 	if (rval == TRAN_ACCEPT) {
17374 		return (JUST_RETURN);
17375 	}
17376 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17377 	    "Reissue pkt st_transport(0x%x) failure\n", rval);
17378 	if (rval != TRAN_BUSY) {
17379 		return (COMMAND_DONE_ERROR);
17380 	}
17381 	mutex_exit(ST_MUTEX);
17382 	rval = st_handle_start_busy(un, bp, ST_TRAN_BUSY_TIMEOUT, 0);
17383 	mutex_enter(ST_MUTEX);
17384 	if (rval) {
17385 		return (COMMAND_DONE_ERROR);
17386 	}
17387 
17388 	return (JUST_RETURN);
17389 }
17390 
17391 static int
17392 st_transport(struct scsi_tape *un, struct scsi_pkt *pkt)
17393 {
17394 	int status;
17395 
17396 	ST_FUNC(ST_DEVINFO, st_transport);
17397 
17398 	ST_CDB(ST_DEVINFO, "transport CDB", (caddr_t)pkt->pkt_cdbp);
17399 
17400 	mutex_exit(ST_MUTEX);
17401 
17402 	status = scsi_transport(pkt);
17403 
17404 	mutex_enter(ST_MUTEX);
17405 
17406 	return (status);
17407 }
17408 
17409 /*
17410  * Removed the buf_t bp from the queue referenced to by head and tail.
17411  * Returns the buf_t pointer if it is found in the queue.
17412  * Returns NULL if it is not found.
17413  */
17414 static buf_t *
17415 st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp)
17416 {
17417 	buf_t *runqbp;
17418 	buf_t *prevbp = NULL;
17419 
17420 	for (runqbp = *head; runqbp != 0; runqbp = runqbp->av_forw) {
17421 		if (runqbp == bp) {
17422 			/* found it, is it at the head? */
17423 			if (runqbp == *head) {
17424 				*head = bp->av_forw;
17425 			} else {
17426 				prevbp->av_forw = bp->av_forw;
17427 			}
17428 			if (*tail == bp) {
17429 				*tail = prevbp;
17430 			}
17431 			bp->av_forw = NULL;
17432 			return (bp); /* found and removed */
17433 		}
17434 		prevbp = runqbp;
17435 	}
17436 	return (NULL);
17437 }
17438 
17439 /*
17440  * Adds a buf_t to the queue pointed to by head and tail.
17441  * Adds it either to the head end or the tail end based on which
17442  * the passed variable end (head or tail) points at.
17443  */
17444 static void
17445 st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp)
17446 {
17447 
17448 	bp->av_forw = NULL;
17449 	if (*head) {
17450 		/* Queue is not empty */
17451 		if (end == *head) {
17452 			/* Add at front of queue */
17453 			bp->av_forw = *head;
17454 			*head = bp;
17455 		} else if (end == *tail) {
17456 			/* Add at end of queue */
17457 			(*tail)->av_forw = bp;
17458 			*tail = bp;
17459 		} else {
17460 			ASSERT(0);
17461 		}
17462 	} else {
17463 		/* Queue is empty */
17464 		*head = bp;
17465 		*tail = bp;
17466 	}
17467 }
17468 
17469 
17470 static uint64_t
17471 st_get_cdb_g0_rw_count(uchar_t *cdb)
17472 {
17473 	uint64_t count;
17474 
17475 	if ((cdb[1]) & 1) {
17476 		/* fixed block mode, the count is the number of blocks */
17477 		count =
17478 		    cdb[2] << 16 |
17479 		    cdb[3] << 8 |
17480 		    cdb[4];
17481 	} else {
17482 		/* variable block mode, the count is the block size */
17483 		count = 1;
17484 	}
17485 	return (count);
17486 }
17487 
17488 static uint64_t
17489 st_get_cdb_g0_sign_count(uchar_t *cdb)
17490 {
17491 	uint64_t count;
17492 
17493 	count =
17494 	    cdb[2] << 16 |
17495 	    cdb[3] << 8 |
17496 	    cdb[4];
17497 	/*
17498 	 * If the sign bit of the 3 byte value is set, extended it.
17499 	 */
17500 	if (count & 0x800000) {
17501 		count |= 0xffffffffff000000;
17502 	}
17503 	return (count);
17504 }
17505 
17506 static uint64_t
17507 st_get_cdb_g0_count(uchar_t *cdb)
17508 {
17509 	uint64_t count;
17510 
17511 	count =
17512 	    cdb[2] << 16 |
17513 	    cdb[3] << 8 |
17514 	    cdb[4];
17515 	return (count);
17516 }
17517 
17518 static uint64_t
17519 st_get_cdb_g5_rw_cnt(uchar_t *cdb)
17520 {
17521 	uint64_t count;
17522 
17523 	if ((cdb[1]) & 1) {
17524 		/* fixed block mode */
17525 		count =
17526 		    cdb[12] << 16 |
17527 		    cdb[13] << 8 |
17528 		    cdb[14];
17529 	} else {
17530 		/* variable block mode */
17531 		count = 1;
17532 	}
17533 	return (count);
17534 }
17535 
17536 static uint64_t
17537 st_get_no_count(uchar_t *cdb)
17538 {
17539 	ASSERT(cdb[0] == SCMD_REWIND);
17540 	return ((uint64_t)cdb[0]);
17541 }
17542 
17543 static uint64_t
17544 st_get_load_options(uchar_t *cdb)
17545 {
17546 	return ((uint64_t)(cdb[4] | (LD_HOLD << 1)));
17547 }
17548 
17549 static uint64_t
17550 st_get_erase_options(uchar_t *cdb)
17551 {
17552 	return (cdb[1] | (cdb[0] << 8));
17553 }
17554 
17555 static uint64_t
17556 st_get_cdb_g1_lba(uchar_t *cdb)
17557 {
17558 	uint64_t lba;
17559 
17560 	lba =
17561 	    cdb[3] << 24 |
17562 	    cdb[4] << 16 |
17563 	    cdb[5] << 8 |
17564 	    cdb[6];
17565 	return (lba);
17566 }
17567 
17568 static uint64_t
17569 st_get_cdb_g5_count(uchar_t *cdb)
17570 {
17571 	uint64_t count =
17572 	    cdb[12] << 16 |
17573 	    cdb[13] << 8 |
17574 	    cdb[14];
17575 
17576 	return (count);
17577 }
17578 
17579 static uint64_t
17580 st_get_cdb_g4g5_cnt(uchar_t *cdb)
17581 {
17582 	uint64_t lba;
17583 
17584 	lba =
17585 	    (uint64_t)cdb[4] << 56 |
17586 	    (uint64_t)cdb[5] << 48 |
17587 	    (uint64_t)cdb[6] << 40 |
17588 	    (uint64_t)cdb[7] << 32 |
17589 	    (uint64_t)cdb[8] << 24 |
17590 	    (uint64_t)cdb[9] << 16 |
17591 	    (uint64_t)cdb[10] << 8 |
17592 	    (uint64_t)cdb[11];
17593 	return (lba);
17594 }
17595 
17596 static const cmd_attribute cmd_attributes[] = {
17597 	{ SCMD_TEST_UNIT_READY,
17598 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17599 	    0, 0, 0 },
17600 	{ SCMD_REWIND,
17601 	    1, 1, 1, 0, 0, DIR_REVC, TRAN_NONE, POS_EXPECTED,
17602 	    0, 0, 0, st_get_no_count },
17603 	{ SCMD_REQUEST_SENSE,
17604 	    0, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17605 	    0, 0, 0 },
17606 	{ SCMD_READ_BLKLIM,
17607 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17608 	    0, 0, 0 },
17609 	{ SCMD_READ,
17610 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_READ, POS_EXPECTED,
17611 	    0, 0, 0, st_get_cdb_g0_rw_count },
17612 	{ SCMD_WRITE,
17613 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
17614 	    0, 0, 0, st_get_cdb_g0_rw_count },
17615 	{ SCMD_READ_G4,
17616 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_READ, POS_EXPECTED,
17617 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17618 	{ SCMD_WRITE_G4,
17619 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
17620 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17621 	{ SCMD_READ_REVERSE,
17622 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
17623 	    0, 0, 0, st_get_cdb_g0_rw_count },
17624 	{ SCMD_READ_REVERSE_G4,
17625 	    1, 0, 1, 1, 1, DIR_REVC, TRAN_READ, POS_EXPECTED,
17626 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17627 	{ SCMD_WRITE_FILE_MARK,
17628 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17629 	    0, 0, 0, st_get_cdb_g0_count },
17630 	{ SCMD_WRITE_FILE_MARK_G4,
17631 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17632 	    0, 0, 0, st_get_cdb_g5_count, st_get_cdb_g4g5_cnt },
17633 	{ SCMD_SPACE,
17634 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
17635 	    0, 0, 0, st_get_cdb_g0_sign_count },
17636 	{ SCMD_SPACE_G4,
17637 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
17638 	    0, 0, 0, st_get_cdb_g4g5_cnt },
17639 	{ SCMD_INQUIRY,
17640 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17641 	    0, 0, 0 },
17642 	{ SCMD_VERIFY_G0,
17643 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17644 	    0, 0, 0, st_get_cdb_g0_rw_count },
17645 	{ SCMD_VERIFY_G4,
17646 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17647 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17648 	{ SCMD_RECOVER_BUF,
17649 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
17650 	    0, 0, 0 },
17651 	{ SCMD_MODE_SELECT,
17652 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17653 	    0, 0, 0 },
17654 	{ SCMD_RESERVE,
17655 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17656 	    0, 0, 0 },
17657 	{ SCMD_RELEASE,
17658 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17659 	    0, 0, 0 },
17660 	{ SCMD_ERASE,
17661 	    1, 0, 1, 1, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17662 	    0, 0, 0, st_get_erase_options },
17663 	{ SCMD_MODE_SENSE,
17664 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17665 	    0, 0, 0 },
17666 	{ SCMD_LOAD,
17667 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
17668 	    0, 0, 0, st_get_load_options },
17669 	{ SCMD_GDIAG,
17670 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17671 	    1, 0, 0 },
17672 	{ SCMD_SDIAG,
17673 	    1, 0, 1, 1, 0, DIR_EITH, TRAN_WRTE, POS_EXPECTED,
17674 	    1, 0, 0 },
17675 	{ SCMD_DOORLOCK,
17676 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17677 	    0, 4, 3 },
17678 	{ SCMD_LOCATE,
17679 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
17680 	    0, 0, 0, NULL, st_get_cdb_g1_lba },
17681 	{ SCMD_READ_POSITION,
17682 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17683 	    0, 0, 0 },
17684 	{ SCMD_WRITE_BUFFER,
17685 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17686 	    1, 0, 0 },
17687 	{ SCMD_READ_BUFFER,
17688 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17689 	    1, 0, 0 },
17690 	{ SCMD_REPORT_DENSITIES,
17691 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17692 	    0, 0, 0 },
17693 	{ SCMD_LOG_SELECT_G1,
17694 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17695 	    0, 0, 0 },
17696 	{ SCMD_LOG_SENSE_G1,
17697 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17698 	    0, 0, 0 },
17699 	{ SCMD_PRIN,
17700 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17701 	    0, 0, 0 },
17702 	{ SCMD_PROUT,
17703 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17704 	    0, 0, 0 },
17705 	{ SCMD_READ_ATTRIBUTE,
17706 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17707 	    0, 0, 0 },
17708 	{ SCMD_WRITE_ATTRIBUTE,
17709 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17710 	    0, 0, 0 },
17711 	{ SCMD_LOCATE_G4,
17712 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
17713 	    0, 0, 0, NULL, st_get_cdb_g4g5_cnt },
17714 	{ SCMD_REPORT_LUNS,
17715 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17716 	    0, 0, 0 },
17717 	{ SCMD_SVC_ACTION_IN_G5,
17718 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17719 	    0, 0, 0 },
17720 	{ SCMD_MAINTENANCE_IN,
17721 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17722 	    0, 0, 0 },
17723 	{ SCMD_MAINTENANCE_OUT,
17724 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17725 	    0, 0, 0 },
17726 	{ 0xff, /* Default attribute for unsupported commands */
17727 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_STARTING,
17728 	    1, 0, 0, NULL, NULL }
17729 };
17730 
17731 static const cmd_attribute *
17732 st_lookup_cmd_attribute(unsigned char cmd)
17733 {
17734 	int i;
17735 	cmd_attribute const *attribute;
17736 
17737 	for (i = 0; i < ST_NUM_MEMBERS(cmd_attributes); i++) {
17738 		attribute = &cmd_attributes[i];
17739 		if (attribute->cmd == cmd) {
17740 			return (attribute);
17741 		}
17742 	}
17743 	ASSERT(attribute);
17744 	return (attribute);
17745 }
17746 
17747 static int
17748 st_reset(struct scsi_tape *un, int reset_type)
17749 {
17750 	int rval;
17751 
17752 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
17753 
17754 	ST_FUNC(ST_DEVINFO, st_reset);
17755 	un->un_rsvd_status |= ST_INITIATED_RESET;
17756 	mutex_exit(ST_MUTEX);
17757 	do {
17758 		rval = scsi_reset(&un->un_sd->sd_address, reset_type);
17759 		if (rval == 0) {
17760 			switch (reset_type) {
17761 			case RESET_LUN:
17762 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
17763 				    "LUN reset failed trying target reset");
17764 				reset_type = RESET_TARGET;
17765 				break;
17766 			case RESET_TARGET:
17767 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
17768 				    "target reset failed trying bus reset");
17769 				reset_type = RESET_BUS;
17770 				break;
17771 			case RESET_BUS:
17772 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
17773 				    "bus reset failed trying all reset");
17774 				reset_type = RESET_ALL;
17775 			default:
17776 				mutex_enter(ST_MUTEX);
17777 				return (rval);
17778 			}
17779 		}
17780 	} while (rval == 0);
17781 	mutex_enter(ST_MUTEX);
17782 	return (rval);
17783 }
17784 
17785 
17786 static void
17787 st_reset_notification(caddr_t arg)
17788 {
17789 	struct scsi_tape *un = (struct scsi_tape *)arg;
17790 
17791 	ST_FUNC(ST_DEVINFO, st_reset_notification);
17792 	mutex_enter(ST_MUTEX);
17793 
17794 	un->un_unit_attention_flags = 2;
17795 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
17796 	    ST_RESERVE) {
17797 		un->un_rsvd_status |= ST_LOST_RESERVE;
17798 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
17799 		    "Lost Reservation notification");
17800 	} else {
17801 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
17802 		    "reset notification");
17803 	}
17804 
17805 	if ((un->un_restore_pos == 0) &&
17806 	    (un->un_state == ST_STATE_CLOSED) ||
17807 	    (un->un_state == ST_STATE_OPEN_PENDING_IO) ||
17808 	    (un->un_state == ST_STATE_CLOSING)) {
17809 		un->un_restore_pos = 1;
17810 	}
17811 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
17812 	    "reset and state was %d\n", un->un_state);
17813 	mutex_exit(ST_MUTEX);
17814 }
17815