xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/st.c (revision e38a713ad4e0a9c42f8cccd9350412b2c6ccccdb)
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 		}
2910 	}
2911 
2912 	/*
2913 	 * Tape self identification could fail if the tape drive is used by
2914 	 * another host during attach time. We try to get the tape type
2915 	 * again. This is also applied to any posponed configuration methods.
2916 	 */
2917 	if (un->un_dp->type == ST_TYPE_INVALID) {
2918 		un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
2919 		st_known_tape_type(un);
2920 	}
2921 
2922 	/*
2923 	 * If the tape type is still invalid, try to determine the generic
2924 	 * configuration.
2925 	 */
2926 	if (un->un_dp->type == ST_TYPE_INVALID) {
2927 		rval = st_determine_generic(un);
2928 		if (rval) {
2929 			if (rval != EACCES) {
2930 				rval = EIO;
2931 			}
2932 			un->un_state = ST_STATE_CLOSED;
2933 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2934 			    "st_tape_init: %s invalid type\n",
2935 			    rval == EACCES ? "EACCES" : "EIO");
2936 			goto exit;
2937 		}
2938 		/*
2939 		 * If this is a Unknown Type drive,
2940 		 * Use the READ BLOCK LIMITS to determine if
2941 		 * allow large xfer is approprate if not globally
2942 		 * disabled with st_allow_large_xfer.
2943 		 */
2944 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
2945 	} else {
2946 
2947 		/*
2948 		 * If we allow_large_xfer (ie >64k) and have not yet found out
2949 		 * the max block size supported by the drive,
2950 		 * find it by issueing a READ_BLKLIM command.
2951 		 * if READ_BLKLIM cmd fails, assume drive doesn't
2952 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
2953 		 */
2954 		un->un_allow_large_xfer = st_allow_large_xfer &&
2955 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
2956 	}
2957 	/*
2958 	 * if maxbsize is unknown, set the maximum block size.
2959 	 */
2960 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
2961 
2962 		/*
2963 		 * Get the Block limits of the tape drive.
2964 		 * if un->un_allow_large_xfer = 0 , then make sure
2965 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
2966 		 */
2967 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
2968 
2969 		err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2970 		if (err) {
2971 			/* Retry */
2972 			err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2973 		}
2974 		if (!err) {
2975 
2976 			/*
2977 			 * if cmd successful, use limit returned
2978 			 */
2979 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
2980 			    (un->un_rbl->max_mid << 8) +
2981 			    un->un_rbl->max_lo;
2982 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
2983 			    un->un_rbl->min_lo;
2984 			un->un_data_mod = 1 << un->un_rbl->granularity;
2985 			if ((un->un_maxbsize == 0) ||
2986 			    (un->un_allow_large_xfer == 0 &&
2987 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
2988 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2989 
2990 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
2991 				/*
2992 				 * Drive is not one that is configured, But the
2993 				 * READ BLOCK LIMITS tells us it can do large
2994 				 * xfers.
2995 				 */
2996 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
2997 					un->un_dp->options |=
2998 					    ST_NO_RECSIZE_LIMIT;
2999 				}
3000 				/*
3001 				 * If max and mimimum block limits are the
3002 				 * same this is a fixed block size device.
3003 				 */
3004 				if (un->un_maxbsize == un->un_minbsize) {
3005 					un->un_dp->options &= ~ST_VARIABLE;
3006 				}
3007 			}
3008 
3009 			if (un->un_minbsize == 0) {
3010 				un->un_minbsize = 1;
3011 			}
3012 
3013 		} else { /* error on read block limits */
3014 
3015 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3016 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
3017 			    " errno = %d un_rsvd_status = 0x%X\n",
3018 			    err, un->un_rsvd_status);
3019 
3020 			/*
3021 			 * since read block limits cmd failed,
3022 			 * do not allow large xfers.
3023 			 * use old values in st_minphys
3024 			 */
3025 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
3026 				rval = EACCES;
3027 			} else {
3028 				un->un_allow_large_xfer = 0;
3029 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3030 				    "!Disabling large transfers\n");
3031 
3032 				/*
3033 				 * we guess maxbsize and minbsize
3034 				 */
3035 				if (un->un_bsize) {
3036 					un->un_maxbsize = un->un_minbsize =
3037 					    un->un_bsize;
3038 				} else {
3039 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3040 					un->un_minbsize = 1;
3041 				}
3042 				/*
3043 				 * Data Mod must be set,
3044 				 * Even if read block limits fails.
3045 				 * Prevents Divide By Zero in st_rw().
3046 				 */
3047 				un->un_data_mod = 1;
3048 			}
3049 		}
3050 		if (un->un_rbl) {
3051 			kmem_free(un->un_rbl, RBLSIZE);
3052 			un->un_rbl = NULL;
3053 		}
3054 
3055 		if (rval) {
3056 			goto exit;
3057 		}
3058 	}
3059 
3060 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3061 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
3062 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
3063 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
3064 
3065 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
3066 
3067 	if (err != 0) {
3068 		if (err == EINTR) {
3069 			un->un_laststate = un->un_state;
3070 			un->un_state = ST_STATE_CLOSED;
3071 			rval = EINTR;
3072 			goto exit;
3073 		}
3074 		/*
3075 		 * Make sure the tape is ready
3076 		 */
3077 		un->un_pos.pmode = invalid;
3078 		if (un->un_status != KEY_UNIT_ATTENTION) {
3079 			/*
3080 			 * allow open no media.  Subsequent MTIOCSTATE
3081 			 * with media present will complete the open
3082 			 * logic.
3083 			 */
3084 			un->un_laststate = un->un_state;
3085 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
3086 				un->un_mediastate = MTIO_EJECTED;
3087 				un->un_state = ST_STATE_OFFLINE;
3088 				rval = 0;
3089 				goto exit;
3090 			} else {
3091 				un->un_state = ST_STATE_CLOSED;
3092 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3093 				    "st_tape_init EIO no media, not opened "
3094 				    "O_NONBLOCK|O_EXCL\n");
3095 				rval = EIO;
3096 				goto exit;
3097 			}
3098 		}
3099 	}
3100 
3101 	/*
3102 	 * On each open, initialize block size from drivetype struct,
3103 	 * as it could have been changed by MTSRSZ ioctl.
3104 	 * Now, ST_VARIABLE simply means drive is capable of variable
3105 	 * mode. All drives are assumed to support fixed records.
3106 	 * Hence, un_bsize tells what mode the drive is in.
3107 	 *	un_bsize	= 0	- variable record length
3108 	 *			= x	- fixed record length is x
3109 	 */
3110 	un->un_bsize = un->un_dp->bsize;
3111 
3112 	/*
3113 	 * If saved position is valid go there
3114 	 */
3115 	if (un->un_restore_pos) {
3116 		un->un_restore_pos = 0;
3117 		un->un_pos.fileno = un->un_save_fileno;
3118 		un->un_pos.blkno = un->un_save_blkno;
3119 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &un->un_pos);
3120 		if (rval != 0) {
3121 			if (rval != EACCES) {
3122 				rval = EIO;
3123 			}
3124 			un->un_laststate = un->un_state;
3125 			un->un_state = ST_STATE_CLOSED;
3126 			goto exit;
3127 		}
3128 	}
3129 
3130 	if (un->un_pos.pmode == invalid) {
3131 		rval = st_loadtape(un);
3132 		if (rval) {
3133 			if (rval != EACCES) {
3134 				rval = EIO;
3135 			}
3136 			un->un_laststate = un->un_state;
3137 			un->un_state = ST_STATE_CLOSED;
3138 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3139 			    "st_tape_init: %s can't open tape\n",
3140 			    rval == EACCES ? "EACCES" : "EIO");
3141 			goto exit;
3142 		}
3143 	}
3144 
3145 	/*
3146 	 * do a mode sense to pick up state of current write-protect,
3147 	 * Could cause reserve and fail due to conflict.
3148 	 */
3149 	if (un->un_unit_attention_flags) {
3150 		rval = st_modesense(un);
3151 		if (rval == EACCES) {
3152 			goto exit;
3153 		}
3154 	}
3155 
3156 	/*
3157 	 * If we are opening the tape for writing, check
3158 	 * to make sure that the tape can be written.
3159 	 */
3160 	if (un->un_oflags & FWRITE) {
3161 		err = 0;
3162 		if (un->un_mspl->wp) {
3163 			un->un_status = KEY_WRITE_PROTECT;
3164 			un->un_laststate = un->un_state;
3165 			un->un_state = ST_STATE_CLOSED;
3166 			rval = EACCES;
3167 			/*
3168 			 * STK sets the wp bit if volsafe tape is loaded.
3169 			 */
3170 			if ((un->un_dp->type == MT_ISSTK9840) &&
3171 			    (un->un_dp->options & ST_WORMABLE)) {
3172 				un->un_read_only = RDONLY;
3173 			} else {
3174 				goto exit;
3175 			}
3176 		} else {
3177 			un->un_read_only = RDWR;
3178 		}
3179 	} else {
3180 		un->un_read_only = RDONLY;
3181 	}
3182 
3183 	if (un->un_dp->options & ST_WORMABLE &&
3184 	    un->un_unit_attention_flags) {
3185 		un->un_read_only |= un->un_wormable(un);
3186 
3187 		if (((un->un_read_only == WORM) ||
3188 		    (un->un_read_only == RDWORM)) &&
3189 		    ((un->un_oflags & FWRITE) == FWRITE)) {
3190 			un->un_status = KEY_DATA_PROTECT;
3191 			rval = EACCES;
3192 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3193 			    "read_only = %d eof = %d oflag = %d\n",
3194 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3195 		}
3196 	}
3197 
3198 	/*
3199 	 * If we're opening the tape write-only, we need to
3200 	 * write 2 filemarks on the HP 1/2 inch drive, to
3201 	 * create a null file.
3202 	 */
3203 	if ((un->un_read_only == RDWR) ||
3204 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3205 		if (un->un_dp->options & ST_REEL) {
3206 			un->un_fmneeded = 2;
3207 		} else {
3208 			un->un_fmneeded = 1;
3209 		}
3210 	} else {
3211 		un->un_fmneeded = 0;
3212 	}
3213 
3214 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3215 	    "fmneeded = %x\n", un->un_fmneeded);
3216 
3217 	/*
3218 	 * Make sure the density can be selected correctly.
3219 	 * If WORM can only write at the append point which in most cases
3220 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3221 	 * to set and try densities if a BOP.
3222 	 */
3223 	if (st_determine_density(un,
3224 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3225 		un->un_status = KEY_ILLEGAL_REQUEST;
3226 		un->un_laststate = un->un_state;
3227 		un->un_state = ST_STATE_CLOSED;
3228 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3229 		    "st_tape_init: EIO can't determine density\n");
3230 		rval = EIO;
3231 		goto exit;
3232 	}
3233 
3234 	/*
3235 	 * Destroy the knowledge that we have 'determined'
3236 	 * density so that a later read at BOT comes along
3237 	 * does the right density determination.
3238 	 */
3239 
3240 	un->un_density_known = 0;
3241 
3242 
3243 	/*
3244 	 * Okay, the tape is loaded and either at BOT or somewhere past.
3245 	 * Mark the state such that any I/O or tape space operations
3246 	 * will get/set the right density, etc..
3247 	 */
3248 	un->un_laststate = un->un_state;
3249 	un->un_lastop = ST_OP_NIL;
3250 	un->un_mediastate = MTIO_INSERTED;
3251 	cv_broadcast(&un->un_state_cv);
3252 
3253 	/*
3254 	 *  Set test append flag if writing.
3255 	 *  First write must check that tape is positioned correctly.
3256 	 */
3257 	un->un_test_append = (un->un_oflags & FWRITE);
3258 
3259 	/*
3260 	 * if there are pending unit attention flags.
3261 	 * Check that the media has not changed.
3262 	 */
3263 	if (un->un_unit_attention_flags) {
3264 		rval = st_get_media_identification(un, st_uscsi_cmd);
3265 		if (rval != 0 && rval != EACCES) {
3266 			rval = EIO;
3267 		}
3268 		un->un_unit_attention_flags = 0;
3269 	}
3270 
3271 exit:
3272 	un->un_err_resid = 0;
3273 	un->un_last_resid = 0;
3274 	un->un_last_count = 0;
3275 
3276 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3277 	    "st_tape_init: return val = %x\n", rval);
3278 	return (rval);
3279 
3280 }
3281 
3282 
3283 
3284 /* ARGSUSED */
3285 static int
3286 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3287 {
3288 	int err = 0;
3289 	int count, last_state;
3290 	minor_t minor = getminor(dev);
3291 #ifdef	__x86
3292 	struct contig_mem *cp, *cp_temp;
3293 #endif
3294 
3295 	GET_SOFT_STATE(dev);
3296 
3297 	ST_ENTR(ST_DEVINFO, st_close);
3298 
3299 	/*
3300 	 * wait till all cmds in the pipeline have been completed
3301 	 */
3302 	mutex_enter(ST_MUTEX);
3303 
3304 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3305 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3306 
3307 	st_wait_for_io(un);
3308 
3309 	/* turn off persistent errors on close, as we want close to succeed */
3310 	st_turn_pe_off(un);
3311 
3312 	/*
3313 	 * set state to indicate that we are in process of closing
3314 	 */
3315 	last_state = un->un_laststate = un->un_state;
3316 	un->un_state = ST_STATE_CLOSING;
3317 
3318 	ST_POS(ST_DEVINFO, "st_close1:", &un->un_pos);
3319 
3320 	/*
3321 	 * BSD behavior:
3322 	 * a close always causes a silent span to the next file if we've hit
3323 	 * an EOF (but not yet read across it).
3324 	 */
3325 	if ((minor & MT_BSD) && (un->un_pos.eof == ST_EOF)) {
3326 		if (un->un_pos.pmode != invalid) {
3327 			un->un_pos.fileno++;
3328 			un->un_pos.blkno = 0;
3329 		}
3330 		un->un_pos.eof = ST_NO_EOF;
3331 	}
3332 
3333 	/*
3334 	 * SVR4 behavior for skipping to next file:
3335 	 *
3336 	 * If we have not seen a filemark, space to the next file
3337 	 *
3338 	 * If we have already seen the filemark we are physically in the next
3339 	 * file and we only increment the filenumber
3340 	 */
3341 	if (((minor & (MT_BSD | MT_NOREWIND)) == MT_NOREWIND) &&
3342 	    (flag & FREAD) &&		/* reading or at least asked to */
3343 	    ((un->un_pos.blkno != 0) && 		/* inside a file */
3344 	    (un->un_lastop != ST_OP_WRITE) &&		/* Didn't just write */
3345 	    (un->un_lastop != ST_OP_WEOF))) {		/* or write filemarks */
3346 		switch (un->un_pos.eof) {
3347 		case ST_NO_EOF:
3348 			/*
3349 			 * if we were reading and did not read the complete file
3350 			 * skip to the next file, leaving the tape correctly
3351 			 * positioned to read the first record of the next file
3352 			 * Check first for REEL if we are at EOT by trying to
3353 			 * read a block
3354 			 */
3355 			if ((un->un_dp->options & ST_REEL) &&
3356 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3357 			    (un->un_pos.blkno == 0)) {
3358 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3359 					ST_DEBUG2(ST_DEVINFO, st_label,
3360 					    SCSI_DEBUG,
3361 					    "st_close : EIO can't space\n");
3362 					err = EIO;
3363 					break;
3364 				}
3365 				if (un->un_pos.eof >= ST_EOF_PENDING) {
3366 					un->un_pos.eof = ST_EOT_PENDING;
3367 					un->un_pos.fileno += 1;
3368 					un->un_pos.blkno   = 0;
3369 					break;
3370 				}
3371 			}
3372 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3373 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3374 				    "st_close: EIO can't space #2\n");
3375 				err = EIO;
3376 			} else {
3377 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3378 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3379 				    un->un_pos.fileno, un->un_pos.blkno,
3380 				    un->un_pos.eof);
3381 				un->un_pos.eof = ST_NO_EOF;
3382 			}
3383 			break;
3384 
3385 		case ST_EOF_PENDING:
3386 		case ST_EOF:
3387 			un->un_pos.fileno += 1;
3388 			un->un_pos.lgclblkno += 1;
3389 			un->un_pos.blkno   = 0;
3390 			un->un_pos.eof = ST_NO_EOF;
3391 			break;
3392 
3393 		case ST_EOT:
3394 		case ST_EOT_PENDING:
3395 			/* nothing to do */
3396 			break;
3397 		default:
3398 			scsi_log(ST_DEVINFO, st_label, CE_PANIC,
3399 			    "Undefined state 0x%x", un->un_pos.eof);
3400 
3401 		}
3402 	}
3403 
3404 
3405 	/*
3406 	 * For performance reasons (HP 88780), the driver should
3407 	 * postpone writing the second tape mark until just before a file
3408 	 * positioning ioctl is issued (e.g., rewind).	This means that
3409 	 * the user must not manually rewind the tape because the tape will
3410 	 * be missing the second tape mark which marks EOM.
3411 	 * However, this small performance improvement is not worth the risk.
3412 	 */
3413 
3414 	/*
3415 	 * We need to back up over the filemark we inadvertently popped
3416 	 * over doing a read in between the two filemarks that constitute
3417 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3418 	 * set while reading.
3419 	 *
3420 	 * If we happen to be at physical eot (ST_EOM) (writing case),
3421 	 * the writing of filemark(s) will clear the ST_EOM state, which
3422 	 * we don't want, so we save this state and restore it later.
3423 	 */
3424 
3425 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3426 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3427 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3428 
3429 	if (un->un_pos.eof == ST_EOT_PENDING) {
3430 		if (minor & MT_NOREWIND) {
3431 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3432 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3433 				    "st_close: EIO can't space #3\n");
3434 				err = EIO;
3435 			} else {
3436 				un->un_pos.blkno = 0;
3437 				un->un_pos.eof = ST_EOT;
3438 			}
3439 		} else {
3440 			un->un_pos.eof = ST_NO_EOF;
3441 		}
3442 
3443 	/*
3444 	 * Do we need to write a file mark?
3445 	 *
3446 	 * only write filemarks if there are fmks to be written and
3447 	 *   - open for write (possibly read/write)
3448 	 *   - the last operation was a write
3449 	 * or:
3450 	 *   -	opened for wronly
3451 	 *   -	no data was written
3452 	 */
3453 	} else if ((un->un_pos.pmode != invalid) &&
3454 	    (un->un_fmneeded > 0) &&
3455 	    (((flag & FWRITE) &&
3456 	    ((un->un_lastop == ST_OP_WRITE)||(un->un_lastop == ST_OP_WEOF))) ||
3457 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3458 
3459 		/* save ST_EOM state */
3460 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3461 
3462 		/*
3463 		 * Note that we will write a filemark if we had opened
3464 		 * the tape write only and no data was written, thus
3465 		 * creating a null file.
3466 		 *
3467 		 * If the user already wrote one, we only have to write 1 more.
3468 		 * If they wrote two, we don't have to write any.
3469 		 */
3470 
3471 		count = un->un_fmneeded;
3472 		if (count > 0) {
3473 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, count, SYNC_CMD)) {
3474 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3475 				    "st_close : EIO can't wfm\n");
3476 				err = EIO;
3477 			}
3478 			if ((un->un_dp->options & ST_REEL) &&
3479 			    (minor & MT_NOREWIND)) {
3480 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3481 					ST_DEBUG2(ST_DEVINFO, st_label,
3482 					    SCSI_DEBUG,
3483 					    "st_close : EIO space fmk(-1)\n");
3484 					err = EIO;
3485 				}
3486 				un->un_pos.eof = ST_NO_EOF;
3487 				/* fix up block number */
3488 				un->un_pos.blkno = 0;
3489 			}
3490 		}
3491 
3492 		/*
3493 		 * If we aren't going to be rewinding, and we were at
3494 		 * physical eot, restore the state that indicates we
3495 		 * are at physical eot. Once you have reached physical
3496 		 * eot, and you close the tape, the only thing you can
3497 		 * do on the next open is to rewind. Access to trailer
3498 		 * records is only allowed without closing the device.
3499 		 */
3500 		if ((minor & MT_NOREWIND) == 0 && was_at_eom) {
3501 			un->un_pos.eof = ST_EOM;
3502 		}
3503 	}
3504 
3505 	/*
3506 	 * report soft errors if enabled and available, if we never accessed
3507 	 * the drive, don't get errors. This will prevent some DAT error
3508 	 * messages upon LOG SENSE.
3509 	 */
3510 	if (st_report_soft_errors_on_close &&
3511 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3512 	    (last_state != ST_STATE_OFFLINE)) {
3513 		(void) st_report_soft_errors(dev, flag);
3514 	}
3515 
3516 
3517 	/*
3518 	 * Do we need to rewind? Can we rewind?
3519 	 */
3520 	if ((minor & MT_NOREWIND) == 0 &&
3521 	    un->un_pos.pmode != invalid && err == 0) {
3522 		/*
3523 		 * We'd like to rewind with the
3524 		 * 'immediate' bit set, but this
3525 		 * causes problems on some drives
3526 		 * where subsequent opens get a
3527 		 * 'NOT READY' error condition
3528 		 * back while the tape is rewinding,
3529 		 * which is impossible to distinguish
3530 		 * from the condition of 'no tape loaded'.
3531 		 *
3532 		 * Also, for some targets, if you disconnect
3533 		 * with the 'immediate' bit set, you don't
3534 		 * actually return right away, i.e., the
3535 		 * target ignores your request for immediate
3536 		 * return.
3537 		 *
3538 		 * Instead, we'll fire off an async rewind
3539 		 * command. We'll mark the device as closed,
3540 		 * and any subsequent open will stall on
3541 		 * the first TEST_UNIT_READY until the rewind
3542 		 * completes.
3543 		 */
3544 
3545 		/*
3546 		 * Used to be if reserve was not supported we'd send an
3547 		 * asynchronious rewind. Comments above may be slightly invalid
3548 		 * as the immediate bit was never set. Doing an immedate rewind
3549 		 * makes sense, I think fixes to not ready status might handle
3550 		 * the problems described above.
3551 		 */
3552 		if (un->un_sd->sd_inq->inq_ansi < 2) {
3553 			(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
3554 		} else {
3555 			/* flush data for older drives per scsi spec. */
3556 			(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
3557 			(void) st_cmd(un, SCMD_REWIND, 1, ASYNC_CMD);
3558 		}
3559 	}
3560 
3561 	/*
3562 	 * eject tape if necessary
3563 	 */
3564 	if (un->un_eject_tape_on_failure) {
3565 		un->un_eject_tape_on_failure = 0;
3566 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3567 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3568 			    "st_close : can't unload tape\n");
3569 		} else {
3570 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3571 			    "st_close : tape unloaded \n");
3572 			un->un_pos.eof = ST_NO_EOF;
3573 			un->un_mediastate = MTIO_EJECTED;
3574 		}
3575 	}
3576 	/*
3577 	 * Release the tape unit, if default reserve/release
3578 	 * behaviour.
3579 	 */
3580 	if ((un->un_rsvd_status &
3581 	    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
3582 		(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
3583 	}
3584 
3585 	/*
3586 	 * clear up state
3587 	 */
3588 	un->un_laststate = un->un_state;
3589 	un->un_state = ST_STATE_CLOSED;
3590 	un->un_lastop = ST_OP_NIL;
3591 	un->un_throttle = 1;	/* assume one request at time, for now */
3592 	un->un_retry_ct = 0;
3593 	un->un_tran_retry_ct = 0;
3594 	un->un_errno = 0;
3595 	un->un_swr_token = (opaque_t)NULL;
3596 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3597 
3598 	/* Restore the options to the init time settings */
3599 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3600 		un->un_dp->options |= ST_READ_IGNORE_ILI;
3601 	} else {
3602 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3603 	}
3604 
3605 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3606 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3607 	} else {
3608 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3609 	}
3610 
3611 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3612 		un->un_dp->options |= ST_SHORT_FILEMARKS;
3613 	} else {
3614 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3615 	}
3616 
3617 	ASSERT(mutex_owned(ST_MUTEX));
3618 
3619 	/*
3620 	 * Signal anyone awaiting a close operation to complete.
3621 	 */
3622 	cv_signal(&un->un_clscv);
3623 
3624 	/*
3625 	 * any kind of error on closing causes all state to be tossed
3626 	 */
3627 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3628 		/*
3629 		 * note that st_intr has already set
3630 		 * un_pos.pmode to invalid.
3631 		 */
3632 		un->un_density_known = 0;
3633 	}
3634 
3635 #ifdef	__x86
3636 	/*
3637 	 * free any contiguous mem alloc'ed for big block I/O
3638 	 */
3639 	cp = un->un_contig_mem;
3640 	while (cp) {
3641 		if (cp->cm_addr) {
3642 			ddi_dma_mem_free(&cp->cm_acc_hdl);
3643 		}
3644 		cp_temp = cp;
3645 		cp = cp->cm_next;
3646 		kmem_free(cp_temp,
3647 		    sizeof (struct contig_mem) + biosize());
3648 	}
3649 	un->un_contig_mem_total_num = 0;
3650 	un->un_contig_mem_available_num = 0;
3651 	un->un_contig_mem = NULL;
3652 	un->un_max_contig_mem_len = 0;
3653 #endif
3654 
3655 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3656 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3657 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3658 
3659 	mutex_exit(ST_MUTEX);
3660 	return (err);
3661 }
3662 
3663 /*
3664  * These routines perform raw i/o operations.
3665  */
3666 
3667 /* ARGSUSED2 */
3668 static int
3669 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3670 {
3671 #ifdef STDEBUG
3672 	GET_SOFT_STATE(dev);
3673 	ST_ENTR(ST_DEVINFO, st_aread);
3674 #endif
3675 	return (st_arw(dev, aio, B_READ));
3676 }
3677 
3678 
3679 /* ARGSUSED2 */
3680 static int
3681 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3682 {
3683 #ifdef STDEBUG
3684 	GET_SOFT_STATE(dev);
3685 	ST_ENTR(ST_DEVINFO, st_awrite);
3686 #endif
3687 	return (st_arw(dev, aio, B_WRITE));
3688 }
3689 
3690 
3691 
3692 /* ARGSUSED */
3693 static int
3694 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3695 {
3696 #ifdef STDEBUG
3697 	GET_SOFT_STATE(dev);
3698 	ST_ENTR(ST_DEVINFO, st_read);
3699 #endif
3700 	return (st_rw(dev, uiop, B_READ));
3701 }
3702 
3703 /* ARGSUSED */
3704 static int
3705 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3706 {
3707 #ifdef STDEBUG
3708 	GET_SOFT_STATE(dev);
3709 	ST_ENTR(ST_DEVINFO, st_write);
3710 #endif
3711 	return (st_rw(dev, uiop, B_WRITE));
3712 }
3713 
3714 /*
3715  * Due to historical reasons, old limits are: For variable-length devices:
3716  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3717  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3718  * (let it through unmodified. For fixed-length record devices:
3719  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3720  *
3721  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3722  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3723  * command to the drive).
3724  *
3725  */
3726 static void
3727 st_minphys(struct buf *bp)
3728 {
3729 	struct scsi_tape *un;
3730 
3731 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3732 
3733 	ST_FUNC(ST_DEVINFO, st_minphys);
3734 
3735 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3736 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3737 	    bp->b_bcount);
3738 
3739 	if (un->un_allow_large_xfer) {
3740 
3741 		/*
3742 		 * check un_maxbsize for variable length devices only
3743 		 */
3744 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3745 			bp->b_bcount = un->un_maxbsize;
3746 		}
3747 		/*
3748 		 * can't go more that HBA maxdma limit in either fixed-length
3749 		 * or variable-length tape drives.
3750 		 */
3751 		if (bp->b_bcount > un->un_maxdma) {
3752 			bp->b_bcount = un->un_maxdma;
3753 		}
3754 	} else {
3755 
3756 		/*
3757 		 *  use old fixed limits
3758 		 */
3759 		if (un->un_bsize == 0) {
3760 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3761 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3762 			}
3763 		} else {
3764 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3765 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3766 			}
3767 		}
3768 	}
3769 
3770 	/*
3771 	 * For regular raw I/O and Fixed Block length devices, make sure
3772 	 * the adjusted block count is a whole multiple of the device
3773 	 * block size.
3774 	 */
3775 	if (bp != un->un_sbufp && un->un_bsize) {
3776 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3777 	}
3778 }
3779 
3780 static int
3781 st_rw(dev_t dev, struct uio *uio, int flag)
3782 {
3783 	int rval = 0;
3784 	long len;
3785 
3786 	GET_SOFT_STATE(dev);
3787 
3788 	ST_FUNC(ST_DEVINFO, st_rw);
3789 
3790 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3791 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3792 	    (flag == B_READ ? rd_str: wr_str));
3793 
3794 	/* get local copy of transfer length */
3795 	len = uio->uio_iov->iov_len;
3796 
3797 	mutex_enter(ST_MUTEX);
3798 
3799 	/*
3800 	 * Clear error entry stack
3801 	 */
3802 	st_empty_error_stack(un);
3803 
3804 	/*
3805 	 * If in fixed block size mode and requested read or write
3806 	 * is not an even multiple of that block size.
3807 	 */
3808 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3809 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3810 		    "%s: not modulo %d block size\n",
3811 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3812 		rval = EINVAL;
3813 	}
3814 
3815 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3816 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3817 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3818 		    "%s: not modulo %d device granularity\n",
3819 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3820 		rval = EINVAL;
3821 	}
3822 
3823 	if (rval != 0) {
3824 		un->un_errno = rval;
3825 		mutex_exit(ST_MUTEX);
3826 		return (rval);
3827 	}
3828 
3829 	/*
3830 	 * Reset this so it can be set if Berkeley and read over a filemark.
3831 	 */
3832 	un->un_silent_skip = 0;
3833 	mutex_exit(ST_MUTEX);
3834 
3835 	len = uio->uio_resid;
3836 
3837 	rval = physio(st_queued_strategy, (struct buf *)NULL,
3838 	    dev, flag, st_minphys, uio);
3839 	/*
3840 	 * if we have hit logical EOT during this xfer and there is not a
3841 	 * full residue, then set eof back  to ST_EOM to make sure that
3842 	 * the user will see at least one zero write
3843 	 * after this short write
3844 	 */
3845 	mutex_enter(ST_MUTEX);
3846 	if (un->un_pos.eof > ST_NO_EOF) {
3847 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3848 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3849 	}
3850 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3851 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3852 			un->un_pos.eof = ST_EOM;
3853 		} else if (uio->uio_resid == len) {
3854 			un->un_pos.eof = ST_NO_EOF;
3855 		}
3856 	}
3857 
3858 	if (un->un_silent_skip && uio->uio_resid != len) {
3859 		un->un_pos.eof = ST_EOF;
3860 		un->un_pos.blkno = un->un_save_blkno;
3861 		un->un_pos.fileno--;
3862 	}
3863 
3864 	un->un_errno = rval;
3865 
3866 	mutex_exit(ST_MUTEX);
3867 
3868 	return (rval);
3869 }
3870 
3871 static int
3872 st_arw(dev_t dev, struct aio_req *aio, int flag)
3873 {
3874 	struct uio *uio = aio->aio_uio;
3875 	int rval = 0;
3876 	long len;
3877 
3878 	GET_SOFT_STATE(dev);
3879 
3880 	ST_FUNC(ST_DEVINFO, st_arw);
3881 
3882 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3883 	    "st_arw(dev = 0x%lx, flag = %s)\n", dev,
3884 	    (flag == B_READ ? rd_str: wr_str));
3885 
3886 	/* get local copy of transfer length */
3887 	len = uio->uio_iov->iov_len;
3888 
3889 	mutex_enter(ST_MUTEX);
3890 
3891 	/*
3892 	 * If in fixed block size mode and requested read or write
3893 	 * is not an even multiple of that block size.
3894 	 */
3895 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3896 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3897 		    "%s: not modulo %d block size\n",
3898 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3899 		rval = EINVAL;
3900 	}
3901 
3902 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3903 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3904 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3905 		    "%s: not modulo %d device granularity\n",
3906 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3907 		rval = EINVAL;
3908 	}
3909 
3910 	if (rval != 0) {
3911 		un->un_errno = rval;
3912 		mutex_exit(ST_MUTEX);
3913 		return (rval);
3914 	}
3915 
3916 	mutex_exit(ST_MUTEX);
3917 
3918 	len = uio->uio_resid;
3919 
3920 	rval =
3921 	    aphysio(st_queued_strategy, anocancel, dev, flag, st_minphys, aio);
3922 
3923 	/*
3924 	 * if we have hit logical EOT during this xfer and there is not a
3925 	 * full residue, then set eof back  to ST_EOM to make sure that
3926 	 * the user will see at least one zero write
3927 	 * after this short write
3928 	 *
3929 	 * we keep this here just in case the application is not using
3930 	 * persistent errors
3931 	 */
3932 	mutex_enter(ST_MUTEX);
3933 	if (un->un_pos.eof > ST_NO_EOF) {
3934 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3935 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3936 	}
3937 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3938 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3939 			un->un_pos.eof = ST_EOM;
3940 		} else if (uio->uio_resid == len &&
3941 		    !(un->un_persistence && un->un_persist_errors)) {
3942 			un->un_pos.eof = ST_NO_EOF;
3943 		}
3944 	}
3945 	un->un_errno = rval;
3946 	mutex_exit(ST_MUTEX);
3947 
3948 	return (rval);
3949 }
3950 
3951 
3952 
3953 static int
3954 st_queued_strategy(buf_t *bp)
3955 {
3956 	struct scsi_tape *un;
3957 	char reading = bp->b_flags & B_READ;
3958 	int wasopening = 0;
3959 
3960 	/*
3961 	 * validate arguments
3962 	 */
3963 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3964 	if (un == NULL) {
3965 		bp->b_resid = bp->b_bcount;
3966 		bioerror(bp, ENXIO);
3967 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
3968 		    "st_queued_strategy: ENXIO error exit\n");
3969 		biodone(bp);
3970 		return (0);
3971 	}
3972 
3973 	ST_ENTR(ST_DEVINFO, st_queued_strategy);
3974 
3975 	mutex_enter(ST_MUTEX);
3976 
3977 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
3978 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
3979 	}
3980 
3981 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3982 	    "st_queued_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
3983 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3984 
3985 	/*
3986 	 * If persistent errors have been flagged, just nix this one. We wait
3987 	 * for any outstanding I/O's below, so we will be in order.
3988 	 */
3989 	if (un->un_persistence && un->un_persist_errors) {
3990 		goto exit;
3991 	}
3992 
3993 	/*
3994 	 * If last command was non queued, wait till it finishes.
3995 	 */
3996 	while (un->un_sbuf_busy) {
3997 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
3998 		/* woke up because of an error */
3999 		if (un->un_persistence && un->un_persist_errors) {
4000 			goto exit;
4001 		}
4002 	}
4003 
4004 	/*
4005 	 * s_buf and recovery commands shouldn't come here.
4006 	 */
4007 	ASSERT(bp != un->un_recov_buf);
4008 	ASSERT(bp != un->un_sbufp);
4009 
4010 	/*
4011 	 * If we haven't done/checked reservation on the tape unit
4012 	 * do it now.
4013 	 */
4014 	if ((un->un_rsvd_status &
4015 	    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
4016 		if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
4017 			if (st_reserve_release(un, ST_RESERVE, st_uscsi_cmd)) {
4018 				st_bioerror(bp, un->un_errno);
4019 				goto exit;
4020 			}
4021 		} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4022 			/*
4023 			 * Enter here to restore position for possible
4024 			 * resets when the device was closed and opened
4025 			 * in O_NDELAY mode subsequently
4026 			 */
4027 			un->un_state = ST_STATE_INITIALIZING;
4028 			(void) st_cmd(un, SCMD_TEST_UNIT_READY,
4029 			    0, SYNC_CMD);
4030 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4031 		}
4032 		un->un_rsvd_status |= ST_INIT_RESERVE;
4033 	}
4034 
4035 	/*
4036 	 * If we are offline, we have to initialize everything first.
4037 	 * This is to handle either when opened with O_NDELAY, or
4038 	 * we just got a new tape in the drive, after an offline.
4039 	 * We don't observe O_NDELAY past the open,
4040 	 * as it will not make sense for tapes.
4041 	 */
4042 	if (un->un_state == ST_STATE_OFFLINE && un->un_restore_pos) {
4043 		/*
4044 		 * reset state to avoid recursion
4045 		 */
4046 		un->un_laststate = un->un_state;
4047 		un->un_state = ST_STATE_INITIALIZING;
4048 		if (st_tape_init(un)) {
4049 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4050 			    "stioctl : OFFLINE init failure ");
4051 			un->un_state = ST_STATE_OFFLINE;
4052 			un->un_pos.pmode = invalid;
4053 			goto b_done_err;
4054 		}
4055 		/* WTF un_restore_pos make invalid */
4056 		un->un_state = ST_STATE_OPEN_PENDING_IO;
4057 		un->un_restore_pos = 0;
4058 	}
4059 	/*
4060 	 * Check for legal operations
4061 	 */
4062 	if (un->un_pos.pmode == invalid) {
4063 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4064 		    "strategy with un->un_pos.pmode invalid\n");
4065 		goto b_done_err;
4066 	}
4067 
4068 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4069 	    "st_queued_strategy(): regular io\n");
4070 
4071 	/*
4072 	 * Process this first. If we were reading, and we're pending
4073 	 * logical eot, that means we've bumped one file mark too far.
4074 	 */
4075 
4076 	/*
4077 	 * Recursion warning: st_cmd will route back through here.
4078 	 * Not anymore st_cmd will go through st_strategy()!
4079 	 */
4080 	if (un->un_pos.eof == ST_EOT_PENDING) {
4081 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4082 			un->un_pos.pmode = invalid;
4083 			un->un_density_known = 0;
4084 			goto b_done_err;
4085 		}
4086 		un->un_pos.blkno = 0; /* fix up block number.. */
4087 		un->un_pos.eof = ST_EOT;
4088 	}
4089 
4090 	/*
4091 	 * If we are in the process of opening, we may have to
4092 	 * determine/set the correct density. We also may have
4093 	 * to do a test_append (if QIC) to see whether we are
4094 	 * in a position to append to the end of the tape.
4095 	 *
4096 	 * If we're already at logical eot, we transition
4097 	 * to ST_NO_EOF. If we're at physical eot, we punt
4098 	 * to the switch statement below to handle.
4099 	 */
4100 	if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
4101 	    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
4102 
4103 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4104 			if (st_determine_density(un, (int)reading)) {
4105 				goto b_done_err;
4106 			}
4107 		}
4108 
4109 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4110 		    "pending_io@fileno %d rw %d qic %d eof %d\n",
4111 		    un->un_pos.fileno, (int)reading,
4112 		    (un->un_dp->options & ST_QIC) ? 1 : 0,
4113 		    un->un_pos.eof);
4114 
4115 		if (!reading && un->un_pos.eof != ST_EOM) {
4116 			if (un->un_pos.eof == ST_EOT) {
4117 				un->un_pos.eof = ST_NO_EOF;
4118 			} else if (un->un_pos.pmode != invalid &&
4119 			    (un->un_dp->options & ST_QIC)) {
4120 				/*
4121 				 * st_test_append() will do it all
4122 				 */
4123 				st_test_append(bp);
4124 				mutex_exit(ST_MUTEX);
4125 				return (0);
4126 			}
4127 		}
4128 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4129 			wasopening = 1;
4130 		}
4131 		un->un_laststate = un->un_state;
4132 		un->un_state = ST_STATE_OPEN;
4133 	}
4134 
4135 
4136 	/*
4137 	 * Process rest of END OF FILE and END OF TAPE conditions
4138 	 */
4139 
4140 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4141 	    "eof=%x, wasopening=%x\n",
4142 	    un->un_pos.eof, wasopening);
4143 
4144 	switch (un->un_pos.eof) {
4145 	case ST_EOM:
4146 		/*
4147 		 * This allows writes to proceed past physical
4148 		 * eot. We'll *really* be in trouble if the
4149 		 * user continues blindly writing data too
4150 		 * much past this point (unwind the tape).
4151 		 * Physical eot really means 'early warning
4152 		 * eot' in this context.
4153 		 *
4154 		 * Every other write from now on will succeed
4155 		 * (if sufficient  tape left).
4156 		 * This write will return with resid == count
4157 		 * but the next one should be successful
4158 		 *
4159 		 * Note that we only transition to logical EOT
4160 		 * if the last state wasn't the OPENING state.
4161 		 * We explicitly prohibit running up to physical
4162 		 * eot, closing the device, and then re-opening
4163 		 * to proceed. Trailer records may only be gotten
4164 		 * at by keeping the tape open after hitting eot.
4165 		 *
4166 		 * Also note that ST_EOM cannot be set by reading-
4167 		 * this can only be set during writing. Reading
4168 		 * up to the end of the tape gets a blank check
4169 		 * or a double-filemark indication (ST_EOT_PENDING),
4170 		 * and we prohibit reading after that point.
4171 		 *
4172 		 */
4173 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
4174 		if (wasopening == 0) {
4175 			/*
4176 			 * this allows st_rw() to reset it back to
4177 			 * will see a zero write
4178 			 */
4179 			un->un_pos.eof = ST_WRITE_AFTER_EOM;
4180 		}
4181 		un->un_status = SUN_KEY_EOT;
4182 		goto b_done;
4183 
4184 	case ST_WRITE_AFTER_EOM:
4185 	case ST_EOT:
4186 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
4187 		un->un_status = SUN_KEY_EOT;
4188 		if (SVR4_BEHAVIOR && reading) {
4189 			goto b_done_err;
4190 		}
4191 
4192 		if (reading) {
4193 			goto b_done;
4194 		}
4195 		un->un_pos.eof = ST_NO_EOF;
4196 		break;
4197 
4198 	case ST_EOF_PENDING:
4199 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4200 		    "EOF PENDING\n");
4201 		un->un_status = SUN_KEY_EOF;
4202 		if (SVR4_BEHAVIOR) {
4203 			un->un_pos.eof = ST_EOF;
4204 			goto b_done;
4205 		}
4206 		/* FALLTHROUGH */
4207 	case ST_EOF:
4208 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
4209 		un->un_status = SUN_KEY_EOF;
4210 		if (SVR4_BEHAVIOR) {
4211 			goto b_done_err;
4212 		}
4213 
4214 		if (BSD_BEHAVIOR) {
4215 			un->un_pos.eof = ST_NO_EOF;
4216 			un->un_pos.fileno += 1;
4217 			un->un_pos.blkno   = 0;
4218 		}
4219 
4220 		if (reading) {
4221 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4222 			    "now file %d (read)\n",
4223 			    un->un_pos.fileno);
4224 			goto b_done;
4225 		}
4226 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4227 		    "now file %d (write)\n", un->un_pos.fileno);
4228 		break;
4229 	default:
4230 		un->un_status = 0;
4231 		break;
4232 	}
4233 
4234 	bp->b_flags &= ~(B_DONE);
4235 	st_bioerror(bp, 0);
4236 	bp->av_forw = NULL;
4237 	bp->b_resid = 0;
4238 	SET_BP_PKT(bp, 0);
4239 
4240 
4241 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4242 	    "st_queued_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4243 	    " pkt=0x%p\n",
4244 	    (void *)bp->b_forw, bp->b_bcount,
4245 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4246 
4247 #ifdef	__x86
4248 	/*
4249 	 * We will replace bp with a new bp that can do big blk xfer
4250 	 * if the requested xfer size is bigger than un->un_maxdma_arch
4251 	 *
4252 	 * Also, we need to make sure that we're handling real I/O
4253 	 * by checking group 0/1 SCSI I/O commands, if needed
4254 	 */
4255 	if (bp->b_bcount > un->un_maxdma_arch &&
4256 	    ((uchar_t)(uintptr_t)bp->b_forw == SCMD_READ ||
4257 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G4 ||
4258 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE ||
4259 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G4)) {
4260 		mutex_exit(ST_MUTEX);
4261 		bp = st_get_bigblk_bp(bp);
4262 		mutex_enter(ST_MUTEX);
4263 	}
4264 #endif
4265 
4266 	/* put on wait queue */
4267 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4268 	    "st_queued_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4269 	    (void *)un->un_quef, (void *)bp);
4270 
4271 	st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quel, bp);
4272 
4273 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4274 
4275 	st_start(un);
4276 
4277 	mutex_exit(ST_MUTEX);
4278 	return (0);
4279 
4280 b_done_err:
4281 	st_bioerror(bp, EIO);
4282 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4283 	    "st_queued_strategy : EIO b_done_err\n");
4284 
4285 b_done:
4286 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4287 	    "st_queued_strategy: b_done\n");
4288 
4289 exit:
4290 	/*
4291 	 * make sure no commands are outstanding or waiting before closing,
4292 	 * so we can guarantee order
4293 	 */
4294 	st_wait_for_io(un);
4295 	un->un_err_resid = bp->b_resid = bp->b_bcount;
4296 
4297 	/* override errno here, if persistent errors were flagged */
4298 	if (un->un_persistence && un->un_persist_errors)
4299 		bioerror(bp, un->un_errno);
4300 
4301 	mutex_exit(ST_MUTEX);
4302 
4303 	biodone(bp);
4304 	ASSERT(mutex_owned(ST_MUTEX) == 0);
4305 	return (0);
4306 }
4307 
4308 
4309 static int
4310 st_strategy(struct buf *bp)
4311 {
4312 	struct scsi_tape *un;
4313 
4314 	/*
4315 	 * validate arguments
4316 	 */
4317 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4318 	if (un == NULL) {
4319 		bp->b_resid = bp->b_bcount;
4320 		bioerror(bp, ENXIO);
4321 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4322 		    "st_strategy: ENXIO error exit\n");
4323 
4324 		biodone(bp);
4325 		return (0);
4326 
4327 	}
4328 
4329 	ST_ENTR(ST_DEVINFO, st_strategy);
4330 
4331 	mutex_enter(ST_MUTEX);
4332 
4333 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4334 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4335 	}
4336 
4337 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4338 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4339 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4340 
4341 	ASSERT((bp == un->un_recov_buf) || (bp == un->un_sbufp));
4342 
4343 	bp->b_flags &= ~(B_DONE);
4344 	st_bioerror(bp, 0);
4345 	bp->av_forw = NULL;
4346 	bp->b_resid = 0;
4347 	SET_BP_PKT(bp, 0);
4348 
4349 
4350 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4351 	    "st_strategy: cmd=0x%x  count=%ld  resid=%ld flags=0x%x"
4352 	    " pkt=0x%p\n",
4353 	    (unsigned char)(uintptr_t)bp->b_forw, bp->b_bcount,
4354 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4355 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4356 
4357 	st_start(un);
4358 
4359 	mutex_exit(ST_MUTEX);
4360 	return (0);
4361 }
4362 
4363 /*
4364  * this routine spaces forward over filemarks
4365  */
4366 static int
4367 st_space_fmks(struct scsi_tape *un, long count)
4368 {
4369 	int rval = 0;
4370 
4371 	ST_FUNC(ST_DEVINFO, st_space_fmks);
4372 
4373 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4374 	    "st_space_fmks(dev = 0x%lx, count = %ld)\n", un->un_dev, count);
4375 
4376 	ASSERT(mutex_owned(ST_MUTEX));
4377 
4378 	/*
4379 	 * the risk with doing only one space operation is that we
4380 	 * may accidentily jump in old data
4381 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4382 	 * because the 8200 does not append a marker; in order not to
4383 	 * sacrifice the fast file skip, we do a slow skip if the low
4384 	 * density device has been opened
4385 	 */
4386 
4387 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4388 	    !((un->un_dp->type == ST_TYPE_EXB8500 &&
4389 	    MT_DENSITY(un->un_dev) == 0))) {
4390 		if (st_cmd(un, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4391 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4392 			    "space_fmks : EIO can't do space cmd #1\n");
4393 			rval = EIO;
4394 		}
4395 	} else {
4396 		while (count > 0) {
4397 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4398 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4399 				    "space_fmks : EIO can't do space cmd #2\n");
4400 				rval = EIO;
4401 				break;
4402 			}
4403 			count -= 1;
4404 			/*
4405 			 * read a block to see if we have reached
4406 			 * end of medium (double filemark for reel or
4407 			 * medium error for others)
4408 			 */
4409 			if (count > 0) {
4410 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
4411 					ST_DEBUG2(ST_DEVINFO, st_label,
4412 					    SCSI_DEBUG,
4413 					    "space_fmks : EIO can't do "
4414 					    "space cmd #3\n");
4415 					rval = EIO;
4416 					break;
4417 				}
4418 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4419 				    (un->un_dp->options & ST_REEL)) {
4420 					un->un_status = SUN_KEY_EOT;
4421 					ST_DEBUG2(ST_DEVINFO, st_label,
4422 					    SCSI_DEBUG,
4423 					    "space_fmks : EIO ST_REEL\n");
4424 					rval = EIO;
4425 					break;
4426 				} else if (IN_EOF(un->un_pos)) {
4427 					un->un_pos.eof = ST_NO_EOF;
4428 					un->un_pos.fileno++;
4429 					un->un_pos.blkno = 0;
4430 					count--;
4431 				} else if (un->un_pos.eof > ST_EOF) {
4432 					ST_DEBUG2(ST_DEVINFO, st_label,
4433 					    SCSI_DEBUG,
4434 					    "space_fmks, EIO > ST_EOF\n");
4435 					rval = EIO;
4436 					break;
4437 				}
4438 
4439 			}
4440 		}
4441 		un->un_err_resid = count;
4442 		COPY_POS(&un->un_pos, &un->un_err_pos);
4443 	}
4444 	ASSERT(mutex_owned(ST_MUTEX));
4445 	return (rval);
4446 }
4447 
4448 /*
4449  * this routine spaces to EOD
4450  *
4451  * it keeps track of the current filenumber and returns the filenumber after
4452  * the last successful space operation, we keep the number high because as
4453  * tapes are getting larger, the possibility of more and more files exist,
4454  * 0x100000 (1 Meg of files) probably will never have to be changed any time
4455  * soon
4456  */
4457 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4458 
4459 static int
4460 st_find_eod(struct scsi_tape *un)
4461 {
4462 	tapepos_t savepos;
4463 	int64_t sp_type;
4464 	int result;
4465 
4466 	if (un == NULL) {
4467 		return (-1);
4468 	}
4469 
4470 	ST_FUNC(ST_DEVINFO, st_find_eod);
4471 
4472 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4473 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", un->un_dev,
4474 	    un->un_pos.fileno);
4475 
4476 	ASSERT(mutex_owned(ST_MUTEX));
4477 
4478 	COPY_POS(&savepos, &un->un_pos);
4479 
4480 	/*
4481 	 * see if the drive is smart enough to do the skips in
4482 	 * one operation; 1/2" use two filemarks
4483 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4484 	 * because the 8200 does not append a marker; in order not to
4485 	 * sacrifice the fast file skip, we do a slow skip if the low
4486 	 * density device has been opened
4487 	 */
4488 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4489 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4490 		    (MT_DENSITY(un->un_dev) == 0)) {
4491 			sp_type = Fmk(1);
4492 		} else if (un->un_pos.pmode == logical) {
4493 			sp_type = SPACE(SP_EOD, 0);
4494 		} else {
4495 			sp_type = Fmk(MAX_SKIP);
4496 		}
4497 	} else {
4498 		sp_type = Fmk(1);
4499 	}
4500 
4501 	for (;;) {
4502 		result = st_cmd(un, SCMD_SPACE, sp_type, SYNC_CMD);
4503 
4504 		if (result == 0) {
4505 			COPY_POS(&savepos, &un->un_pos);
4506 		}
4507 
4508 		if (sp_type == SPACE(SP_EOD, 0)) {
4509 			if (result != 0) {
4510 				sp_type = Fmk(MAX_SKIP);
4511 				continue;
4512 			}
4513 
4514 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4515 			    "st_find_eod: 0x%"PRIx64"\n",
4516 			    savepos.lgclblkno);
4517 			/*
4518 			 * What we return will become the current file position.
4519 			 * After completing the space command with the position
4520 			 * mode that is not invalid a read position command will
4521 			 * be automaticly issued. If the drive support the long
4522 			 * read position format a valid file position can be
4523 			 * returned.
4524 			 */
4525 			return (un->un_pos.fileno);
4526 		}
4527 
4528 		if (result != 0) {
4529 			break;
4530 		}
4531 
4532 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4533 		    "count=%"PRIx64", eof=%x, status=%x\n",
4534 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4535 
4536 		/*
4537 		 * If we're not EOM smart,  space a record
4538 		 * to see whether we're now in the slot between
4539 		 * the two sequential filemarks that logical
4540 		 * EOM consists of (REEL) or hit nowhere land
4541 		 * (8mm).
4542 		 */
4543 		if (sp_type == Fmk(1)) {
4544 			/*
4545 			 * no fast skipping, check a record
4546 			 */
4547 			if (st_cmd(un, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4548 				break;
4549 			}
4550 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4551 			    (un->un_dp->options & ST_REEL)) {
4552 				un->un_status = KEY_BLANK_CHECK;
4553 				un->un_pos.fileno++;
4554 				un->un_pos.blkno = 0;
4555 				break;
4556 			}
4557 			if (IN_EOF(un->un_pos)) {
4558 				un->un_pos.eof = ST_NO_EOF;
4559 				un->un_pos.fileno++;
4560 				un->un_pos.blkno = 0;
4561 			}
4562 			if (un->un_pos.eof > ST_EOF) {
4563 				break;
4564 			}
4565 		} else {
4566 			if (un->un_pos.eof > ST_EOF) {
4567 				break;
4568 			}
4569 		}
4570 	}
4571 
4572 	if (un->un_dp->options & ST_KNOWS_EOD) {
4573 		COPY_POS(&savepos, &un->un_pos);
4574 	}
4575 
4576 	ASSERT(mutex_owned(ST_MUTEX));
4577 
4578 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4579 	    "st_find_eod: %x\n", savepos.fileno);
4580 	return (savepos.fileno);
4581 }
4582 
4583 
4584 /*
4585  * this routine is frequently used in ioctls below;
4586  * it determines whether we know the density and if not will
4587  * determine it
4588  * if we have written the tape before, one or more filemarks are written
4589  *
4590  * depending on the stepflag, the head is repositioned to where it was before
4591  * the filemarks were written in order not to confuse step counts
4592  */
4593 #define	STEPBACK    0
4594 #define	NO_STEPBACK 1
4595 
4596 static int
4597 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4598 {
4599 
4600 	GET_SOFT_STATE(dev);
4601 
4602 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4603 
4604 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4605 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4606 	    "\n", dev, wfm, mode, stepflag);
4607 
4608 	ASSERT(mutex_owned(ST_MUTEX));
4609 
4610 	/*
4611 	 * If we don't yet know the density of the tape we have inserted,
4612 	 * we have to either unconditionally set it (if we're 'writing'),
4613 	 * or we have to determine it. As side effects, check for any
4614 	 * write-protect errors, and for the need to put out any file-marks
4615 	 * before positioning a tape.
4616 	 *
4617 	 * If we are going to be spacing forward, and we haven't determined
4618 	 * the tape density yet, we have to do so now...
4619 	 */
4620 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4621 		if (st_determine_density(un, mode)) {
4622 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4623 			    "check_density_or_wfm : EIO can't determine "
4624 			    "density\n");
4625 			un->un_errno = EIO;
4626 			return (EIO);
4627 		}
4628 		/*
4629 		 * Presumably we are at BOT. If we attempt to write, it will
4630 		 * either work okay, or bomb. We don't do a st_test_append
4631 		 * unless we're past BOT.
4632 		 */
4633 		un->un_laststate = un->un_state;
4634 		un->un_state = ST_STATE_OPEN;
4635 
4636 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4637 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4638 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4639 
4640 		tapepos_t spos;
4641 
4642 		COPY_POS(&spos, &un->un_pos);
4643 
4644 		/*
4645 		 * We need to write one or two filemarks.
4646 		 * In the case of the HP, we need to
4647 		 * position the head between the two
4648 		 * marks.
4649 		 */
4650 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4651 			wfm = un->un_fmneeded;
4652 			un->un_fmneeded = 0;
4653 		}
4654 
4655 		if (st_write_fm(dev, wfm)) {
4656 			un->un_pos.pmode = invalid;
4657 			un->un_density_known = 0;
4658 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4659 			    "check_density_or_wfm : EIO can't write fm\n");
4660 			un->un_errno = EIO;
4661 			return (EIO);
4662 		}
4663 
4664 		if (stepflag == STEPBACK) {
4665 			if (st_cmd(un, SCMD_SPACE, Fmk(-wfm), SYNC_CMD)) {
4666 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4667 				    "check_density_or_wfm : EIO can't space "
4668 				    "(-wfm)\n");
4669 				un->un_errno = EIO;
4670 				return (EIO);
4671 			}
4672 			COPY_POS(&un->un_pos, &spos);
4673 		}
4674 	}
4675 
4676 	/*
4677 	 * Whatever we do at this point clears the state of the eof flag.
4678 	 */
4679 
4680 	un->un_pos.eof = ST_NO_EOF;
4681 
4682 	/*
4683 	 * If writing, let's check that we're positioned correctly
4684 	 * at the end of tape before issuing the next write.
4685 	 */
4686 	if (un->un_read_only == RDWR) {
4687 		un->un_test_append = 1;
4688 	}
4689 
4690 	ASSERT(mutex_owned(ST_MUTEX));
4691 	return (0);
4692 }
4693 
4694 
4695 /*
4696  * Wait for all outstaning I/O's to complete
4697  *
4698  * we wait on both ncmds and the wait queue for times when we are flushing
4699  * after persistent errors are flagged, which is when ncmds can be 0, and the
4700  * queue can still have I/O's.  This way we preserve order of biodone's.
4701  */
4702 static void
4703 st_wait_for_io(struct scsi_tape *un)
4704 {
4705 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4706 	ASSERT(mutex_owned(ST_MUTEX));
4707 	while ((un->un_ncmds) || (un->un_quef) || (un->un_runqf)) {
4708 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4709 	}
4710 }
4711 
4712 /*
4713  * This routine implements the ioctl calls.  It is called
4714  * from the device switch at normal priority.
4715  */
4716 /*ARGSUSED*/
4717 static int
4718 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4719     int *rval_p)
4720 {
4721 	int tmp, rval = 0;
4722 
4723 	GET_SOFT_STATE(dev);
4724 
4725 	ST_ENTR(ST_DEVINFO, st_ioctl);
4726 
4727 	mutex_enter(ST_MUTEX);
4728 
4729 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4730 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4731 	    "pe_flag = %d\n",
4732 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4733 	    un->un_persistence && un->un_persist_errors);
4734 
4735 	/*
4736 	 * We don't want to block on these, so let them through
4737 	 * and we don't care about setting driver states here.
4738 	 */
4739 	if ((cmd == MTIOCGETDRIVETYPE) ||
4740 	    (cmd == MTIOCGUARANTEEDORDER) ||
4741 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4742 		goto check_commands;
4743 	}
4744 
4745 	/*
4746 	 * We clear error entry stack except command
4747 	 * MTIOCGETERROR and MTIOCGET
4748 	 */
4749 	if ((cmd != MTIOCGETERROR) &&
4750 	    (cmd != MTIOCGET)) {
4751 		st_empty_error_stack(un);
4752 	}
4753 
4754 	/*
4755 	 * wait for all outstanding commands to complete, or be dequeued.
4756 	 * And because ioctl's are synchronous commands, any return value
4757 	 * after this,  will be in order
4758 	 */
4759 	st_wait_for_io(un);
4760 
4761 	/*
4762 	 * allow only a through clear errors and persistent status, and
4763 	 * status
4764 	 */
4765 	if (un->un_persistence && un->un_persist_errors) {
4766 		if ((cmd == MTIOCLRERR) ||
4767 		    (cmd == MTIOCPERSISTENT) ||
4768 		    (cmd == MTIOCGET)) {
4769 			goto check_commands;
4770 		} else {
4771 			rval = un->un_errno;
4772 			goto exit;
4773 		}
4774 	}
4775 
4776 	ASSERT(un->un_throttle != 0);
4777 	un->un_throttle = 1;	/* > 1 will never happen here */
4778 	un->un_errno = 0;	/* start clean from here */
4779 
4780 	/*
4781 	 * first and foremost, handle any ST_EOT_PENDING cases.
4782 	 * That is, if a logical eot is pending notice, notice it.
4783 	 */
4784 	if (un->un_pos.eof == ST_EOT_PENDING) {
4785 		int resid = un->un_err_resid;
4786 		uchar_t status = un->un_status;
4787 		uchar_t lastop = un->un_lastop;
4788 
4789 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4790 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4791 			    "stioctl : EIO can't space fmk(-1)\n");
4792 			rval = EIO;
4793 			goto exit;
4794 		}
4795 		un->un_lastop = lastop; /* restore last operation */
4796 		if (status == SUN_KEY_EOF) {
4797 			un->un_status = SUN_KEY_EOT;
4798 		} else {
4799 			un->un_status = status;
4800 		}
4801 		un->un_err_resid  = resid;
4802 		/* fix up block number */
4803 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4804 		/* now we're at logical eot */
4805 		un->un_pos.eof = ST_EOT;
4806 	}
4807 
4808 	/*
4809 	 * now, handle the rest of the situations
4810 	 */
4811 check_commands:
4812 	switch (cmd) {
4813 	case MTIOCGET:
4814 	{
4815 #ifdef _MULTI_DATAMODEL
4816 		/*
4817 		 * For use when a 32 bit app makes a call into a
4818 		 * 64 bit ioctl
4819 		 */
4820 		struct mtget32		mtg_local32;
4821 		struct mtget32 		*mtget_32 = &mtg_local32;
4822 #endif /* _MULTI_DATAMODEL */
4823 
4824 			/* Get tape status */
4825 		struct mtget mtg_local;
4826 		struct mtget *mtget = &mtg_local;
4827 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4828 		    "st_ioctl: MTIOCGET\n");
4829 
4830 		bzero((caddr_t)mtget, sizeof (struct mtget));
4831 		mtget->mt_erreg = un->un_status;
4832 		mtget->mt_resid = un->un_err_resid;
4833 		mtget->mt_dsreg = un->un_retry_ct;
4834 		if (un->un_err_pos.pmode == legacy) {
4835 			mtget->mt_fileno = un->un_err_pos.fileno;
4836 		} else {
4837 			mtget->mt_fileno = -1;
4838 		}
4839 		/*
4840 		 * If the value is positive fine.
4841 		 * If its negative we need to return a value based on the
4842 		 * old way if counting backwards from INF (1,000,000,000).
4843 		 */
4844 		if (un->un_err_pos.blkno >= 0) {
4845 			mtget->mt_blkno = un->un_err_pos.blkno;
4846 		} else {
4847 			mtget->mt_blkno = INF + 1 - (-un->un_err_pos.blkno);
4848 		}
4849 		mtget->mt_type = un->un_dp->type;
4850 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
4851 		if (un->un_read_pos_type != NO_POS) {
4852 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
4853 		}
4854 		if (un->un_dp->options & ST_REEL) {
4855 			mtget->mt_flags |= MTF_REEL;
4856 			mtget->mt_bf = 20;
4857 		} else {		/* 1/4" cartridges */
4858 			switch (mtget->mt_type) {
4859 			/* Emulex cartridge tape */
4860 			case MT_ISMT02:
4861 				mtget->mt_bf = 40;
4862 				break;
4863 			default:
4864 				mtget->mt_bf = 126;
4865 				break;
4866 			}
4867 		}
4868 
4869 		/*
4870 		 * If large transfers are allowed and drive options
4871 		 * has no record size limit set. Calculate blocking
4872 		 * factor from the lesser of maxbsize and maxdma.
4873 		 */
4874 		if ((un->un_allow_large_xfer) &&
4875 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
4876 			mtget->mt_bf = min(un->un_maxbsize,
4877 			    un->un_maxdma) / SECSIZE;
4878 		}
4879 
4880 		if (un->un_read_only == WORM ||
4881 		    un->un_read_only == RDWORM) {
4882 			mtget->mt_flags |= MTF_WORM_MEDIA;
4883 		}
4884 
4885 		/*
4886 		 * In persistent error mode sending a non-queued can hang
4887 		 * because this ioctl gets to be run without turning off
4888 		 * persistense. Fake the answer based on previous info.
4889 		 */
4890 		if (un->un_persistence) {
4891 			if ((un->un_HeadClean & (TAPE_ALERT_SUPPORTED |
4892 			    TAPE_SEQUENTIAL_SUPPORTED|TAPE_ALERT_NOT_SUPPORTED))
4893 			    != TAPE_ALERT_NOT_SUPPORTED) {
4894 				mtget->mt_flags |= MTF_TAPE_CLN_SUPPORTED;
4895 			}
4896 			if (un->un_HeadClean & (TAPE_PREVIOUSLY_DIRTY |
4897 			    TAPE_ALERT_STILL_DIRTY)) {
4898 				mtget->mt_flags |= MTF_TAPE_HEAD_DIRTY;
4899 			}
4900 			rval = 0;
4901 		} else {
4902 			rval = st_check_clean_bit(un);
4903 		}
4904 		if (rval == -1) {
4905 			rval = EIO;
4906 			goto exit;
4907 		} else {
4908 			mtget->mt_flags |= (ushort_t)rval;
4909 			rval = 0;
4910 		}
4911 
4912 		un->un_status = 0;		/* Reset status */
4913 		un->un_err_resid = 0;
4914 		tmp = sizeof (struct mtget);
4915 
4916 #ifdef _MULTI_DATAMODEL
4917 
4918 		switch (ddi_model_convert_from(flag & FMODELS)) {
4919 		case DDI_MODEL_ILP32:
4920 			/*
4921 			 * Convert 64 bit back to 32 bit before doing
4922 			 * copyout. This is what the ILP32 app expects.
4923 			 */
4924 			mtget_32->mt_erreg = 	mtget->mt_erreg;
4925 			mtget_32->mt_resid = 	mtget->mt_resid;
4926 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
4927 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
4928 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
4929 			mtget_32->mt_type =  	mtget->mt_type;
4930 			mtget_32->mt_flags = 	mtget->mt_flags;
4931 			mtget_32->mt_bf = 	mtget->mt_bf;
4932 
4933 			if (ddi_copyout(mtget_32, (void *)arg,
4934 			    sizeof (struct mtget32), flag)) {
4935 				rval = EFAULT;
4936 			}
4937 			break;
4938 
4939 		case DDI_MODEL_NONE:
4940 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4941 				rval = EFAULT;
4942 			}
4943 			break;
4944 		}
4945 #else /* ! _MULTI_DATAMODE */
4946 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4947 			rval = EFAULT;
4948 		}
4949 #endif /* _MULTI_DATAMODE */
4950 
4951 		break;
4952 	}
4953 	case MTIOCGETERROR:
4954 			/*
4955 			 * get error entry from error stack
4956 			 */
4957 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4958 			    "st_ioctl: MTIOCGETERROR\n");
4959 
4960 			rval = st_get_error_entry(un, arg, flag);
4961 
4962 			break;
4963 
4964 	case MTIOCSTATE:
4965 		{
4966 			/*
4967 			 * return when media presence matches state
4968 			 */
4969 			enum mtio_state state;
4970 
4971 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4972 			    "st_ioctl: MTIOCSTATE\n");
4973 
4974 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
4975 				rval = EFAULT;
4976 
4977 			mutex_exit(ST_MUTEX);
4978 
4979 			rval = st_check_media(dev, state);
4980 
4981 			mutex_enter(ST_MUTEX);
4982 
4983 			if (rval != 0) {
4984 				break;
4985 			}
4986 
4987 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
4988 			    sizeof (int), flag))
4989 				rval = EFAULT;
4990 			break;
4991 
4992 		}
4993 
4994 	case MTIOCGETDRIVETYPE:
4995 		{
4996 #ifdef _MULTI_DATAMODEL
4997 		/*
4998 		 * For use when a 32 bit app makes a call into a
4999 		 * 64 bit ioctl
5000 		 */
5001 		struct mtdrivetype_request32	mtdtrq32;
5002 #endif /* _MULTI_DATAMODEL */
5003 
5004 			/*
5005 			 * return mtdrivetype
5006 			 */
5007 			struct mtdrivetype_request mtdtrq;
5008 			struct mtdrivetype mtdrtyp;
5009 			struct mtdrivetype *mtdt = &mtdrtyp;
5010 			struct st_drivetype *stdt = un->un_dp;
5011 
5012 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5013 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
5014 
5015 #ifdef _MULTI_DATAMODEL
5016 		switch (ddi_model_convert_from(flag & FMODELS)) {
5017 		case DDI_MODEL_ILP32:
5018 		{
5019 			if (ddi_copyin((void *)arg, &mtdtrq32,
5020 			    sizeof (struct mtdrivetype_request32), flag)) {
5021 				rval = EFAULT;
5022 				break;
5023 			}
5024 			mtdtrq.size = mtdtrq32.size;
5025 			mtdtrq.mtdtp =
5026 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
5027 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5028 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
5029 			break;
5030 		}
5031 		case DDI_MODEL_NONE:
5032 			if (ddi_copyin((void *)arg, &mtdtrq,
5033 			    sizeof (struct mtdrivetype_request), flag)) {
5034 				rval = EFAULT;
5035 				break;
5036 			}
5037 			break;
5038 		}
5039 
5040 #else /* ! _MULTI_DATAMODEL */
5041 		if (ddi_copyin((void *)arg, &mtdtrq,
5042 		    sizeof (struct mtdrivetype_request), flag)) {
5043 			rval = EFAULT;
5044 			break;
5045 		}
5046 #endif /* _MULTI_DATAMODEL */
5047 
5048 			/*
5049 			 * if requested size is < 0 then return
5050 			 * error.
5051 			 */
5052 			if (mtdtrq.size < 0) {
5053 				rval = EINVAL;
5054 				break;
5055 			}
5056 			bzero(mtdt, sizeof (struct mtdrivetype));
5057 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
5058 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
5059 			mtdt->type = stdt->type;
5060 			mtdt->bsize = stdt->bsize;
5061 			mtdt->options = stdt->options;
5062 			mtdt->max_rretries = stdt->max_rretries;
5063 			mtdt->max_wretries = stdt->max_wretries;
5064 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5065 				mtdt->densities[tmp] = stdt->densities[tmp];
5066 			}
5067 			mtdt->default_density = stdt->default_density;
5068 			/*
5069 			 * Speed hasn't been used since the hayday of reel tape.
5070 			 * For all drives not setting the option ST_KNOWS_MEDIA
5071 			 * the speed member renamed to mediatype are zeros.
5072 			 * Those drives that have ST_KNOWS_MEDIA set use the
5073 			 * new mediatype member which is used to figure the
5074 			 * type of media loaded.
5075 			 *
5076 			 * So as to not break applications speed in the
5077 			 * mtdrivetype structure is not renamed.
5078 			 */
5079 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5080 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
5081 			}
5082 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
5083 			mtdt->io_timeout = stdt->io_timeout;
5084 			mtdt->rewind_timeout = stdt->rewind_timeout;
5085 			mtdt->space_timeout = stdt->space_timeout;
5086 			mtdt->load_timeout = stdt->load_timeout;
5087 			mtdt->unload_timeout = stdt->unload_timeout;
5088 			mtdt->erase_timeout = stdt->erase_timeout;
5089 
5090 			/*
5091 			 * Limit the maximum length of the result to
5092 			 * sizeof (struct mtdrivetype).
5093 			 */
5094 			tmp = sizeof (struct mtdrivetype);
5095 			if (mtdtrq.size < tmp)
5096 				tmp = mtdtrq.size;
5097 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
5098 				rval = EFAULT;
5099 			}
5100 			break;
5101 		}
5102 	case MTIOCPERSISTENT:
5103 
5104 		if (ddi_copyin((void *)arg, &tmp, sizeof (tmp), flag)) {
5105 			rval = EFAULT;
5106 			break;
5107 		}
5108 
5109 		if (tmp) {
5110 			st_turn_pe_on(un);
5111 		} else {
5112 			st_turn_pe_off(un);
5113 		}
5114 
5115 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5116 		    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
5117 		    un->un_persistence);
5118 
5119 		break;
5120 
5121 	case MTIOCPERSISTENTSTATUS:
5122 		tmp = (int)un->un_persistence;
5123 
5124 		if (ddi_copyout(&tmp, (void *)arg, sizeof (tmp), flag)) {
5125 			rval = EFAULT;
5126 		}
5127 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5128 		    "st_ioctl: MTIOCPERSISTENTSTATUS:persistence = %d\n",
5129 		    un->un_persistence);
5130 
5131 		break;
5132 
5133 	case MTIOCLRERR:
5134 		{
5135 			/* clear persistent errors */
5136 
5137 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5138 			    "st_ioctl: MTIOCLRERR\n");
5139 
5140 			st_clear_pe(un);
5141 
5142 			break;
5143 		}
5144 
5145 	case MTIOCGUARANTEEDORDER:
5146 		{
5147 			/*
5148 			 * this is just a holder to make a valid ioctl and
5149 			 * it won't be in any earlier release
5150 			 */
5151 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5152 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
5153 
5154 			break;
5155 		}
5156 
5157 	case MTIOCRESERVE:
5158 		{
5159 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5160 			    "st_ioctl: MTIOCRESERVE\n");
5161 
5162 			/*
5163 			 * Check if Reserve/Release is supported.
5164 			 */
5165 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5166 				rval = ENOTTY;
5167 				break;
5168 			}
5169 
5170 			rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5171 
5172 			if (rval == 0) {
5173 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
5174 			}
5175 			break;
5176 		}
5177 
5178 	case MTIOCRELEASE:
5179 		{
5180 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5181 			    "st_ioctl: MTIOCRELEASE\n");
5182 
5183 			/*
5184 			 * Check if Reserve/Release is supported.
5185 			 */
5186 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5187 				rval = ENOTTY;
5188 				break;
5189 			}
5190 
5191 			/*
5192 			 * Used to just clear ST_PRESERVE_RESERVE which
5193 			 * made the reservation release at next close.
5194 			 * As the user may have opened and then done a
5195 			 * persistant reservation we now need to drop
5196 			 * the reservation without closing if the user
5197 			 * attempts to do this.
5198 			 */
5199 			rval = st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
5200 
5201 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5202 
5203 			break;
5204 		}
5205 
5206 	case MTIOCFORCERESERVE:
5207 	{
5208 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5209 		    "st_ioctl: MTIOCFORCERESERVE\n");
5210 
5211 		/*
5212 		 * Check if Reserve/Release is supported.
5213 		 */
5214 		if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5215 			rval = ENOTTY;
5216 			break;
5217 		}
5218 		/*
5219 		 * allow only super user to run this.
5220 		 */
5221 		if (drv_priv(cred_p) != 0) {
5222 			rval = EPERM;
5223 			break;
5224 		}
5225 		/*
5226 		 * Throw away reserve,
5227 		 * not using test-unit-ready
5228 		 * since reserve can succeed without tape being
5229 		 * present in the drive.
5230 		 */
5231 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5232 
5233 		rval = st_take_ownership(un);
5234 
5235 		break;
5236 	}
5237 
5238 	case USCSICMD:
5239 	{
5240 		cred_t	*cr;
5241 
5242 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5243 		    "st_ioctl: USCSICMD\n");
5244 
5245 		cr = ddi_get_cred();
5246 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5247 			rval = EPERM;
5248 		} else {
5249 			rval = st_uscsi_cmd(un, (struct uscsi_cmd *)arg, flag);
5250 		}
5251 		break;
5252 	}
5253 	case MTIOCTOP:
5254 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5255 		    "st_ioctl: MTIOCTOP\n");
5256 		rval = st_mtioctop(un, arg, flag);
5257 		break;
5258 
5259 	case MTIOCLTOP:
5260 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5261 		    "st_ioctl: MTIOLCTOP\n");
5262 		rval = st_mtiocltop(un, arg, flag);
5263 		break;
5264 
5265 	case MTIOCREADIGNOREILI:
5266 		{
5267 			int set_ili;
5268 
5269 			if (ddi_copyin((void *)arg, &set_ili,
5270 			    sizeof (set_ili), flag)) {
5271 				rval = EFAULT;
5272 				break;
5273 			}
5274 
5275 			if (un->un_bsize) {
5276 				rval = ENOTTY;
5277 				break;
5278 			}
5279 
5280 			switch (set_ili) {
5281 			case 0:
5282 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5283 				break;
5284 
5285 			case 1:
5286 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5287 				break;
5288 
5289 			default:
5290 				rval = EINVAL;
5291 				break;
5292 			}
5293 			break;
5294 		}
5295 
5296 	case MTIOCREADIGNOREEOFS:
5297 		{
5298 			int ignore_eof;
5299 
5300 			if (ddi_copyin((void *)arg, &ignore_eof,
5301 			    sizeof (ignore_eof), flag)) {
5302 				rval = EFAULT;
5303 				break;
5304 			}
5305 
5306 			if (!(un->un_dp->options & ST_REEL)) {
5307 				rval = ENOTTY;
5308 				break;
5309 			}
5310 
5311 			switch (ignore_eof) {
5312 			case 0:
5313 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5314 				break;
5315 
5316 			case 1:
5317 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5318 				break;
5319 
5320 			default:
5321 				rval = EINVAL;
5322 				break;
5323 			}
5324 			break;
5325 		}
5326 
5327 	case MTIOCSHORTFMK:
5328 	{
5329 		int short_fmk;
5330 
5331 		if (ddi_copyin((void *)arg, &short_fmk,
5332 		    sizeof (short_fmk), flag)) {
5333 			rval = EFAULT;
5334 			break;
5335 		}
5336 
5337 		switch (un->un_dp->type) {
5338 		case ST_TYPE_EXB8500:
5339 		case ST_TYPE_EXABYTE:
5340 			if (!short_fmk) {
5341 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5342 			} else if (short_fmk == 1) {
5343 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5344 			} else {
5345 				rval = EINVAL;
5346 			}
5347 			break;
5348 
5349 		default:
5350 			rval = ENOTTY;
5351 			break;
5352 		}
5353 		break;
5354 	}
5355 
5356 	case MTIOCGETPOS:
5357 		rval = st_update_block_pos(un, st_cmd, 0);
5358 		if (rval == 0) {
5359 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5360 			    sizeof (tapepos_t), flag)) {
5361 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5362 				    "MTIOCGETPOS copy out failed\n");
5363 				rval = EFAULT;
5364 			}
5365 		}
5366 		break;
5367 
5368 	case MTIOCRESTPOS:
5369 	{
5370 		tapepos_t dest;
5371 
5372 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5373 		    flag) != 0) {
5374 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5375 			    "MTIOCRESTPOS copy in failed\n");
5376 			rval = EFAULT;
5377 			break;
5378 		}
5379 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &dest);
5380 		if (rval != 0) {
5381 			rval = EIO;
5382 		}
5383 		break;
5384 	}
5385 	default:
5386 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5387 		    "st_ioctl: unknown ioctl\n");
5388 		rval = ENOTTY;
5389 	}
5390 
5391 exit:
5392 	if (!(un->un_persistence && un->un_persist_errors)) {
5393 		un->un_errno = rval;
5394 	}
5395 
5396 	mutex_exit(ST_MUTEX);
5397 
5398 	return (rval);
5399 }
5400 
5401 
5402 /*
5403  * do some MTIOCTOP tape operations
5404  */
5405 static int
5406 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5407 {
5408 #ifdef _MULTI_DATAMODEL
5409 	/*
5410 	 * For use when a 32 bit app makes a call into a
5411 	 * 64 bit ioctl
5412 	 */
5413 	struct mtop32	mtop_32_for_64;
5414 #endif /* _MULTI_DATAMODEL */
5415 	struct mtop passed;
5416 	struct mtlop local;
5417 	int rval = 0;
5418 
5419 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5420 
5421 	ASSERT(mutex_owned(ST_MUTEX));
5422 
5423 #ifdef _MULTI_DATAMODEL
5424 	switch (ddi_model_convert_from(flag & FMODELS)) {
5425 	case DDI_MODEL_ILP32:
5426 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5427 		    sizeof (struct mtop32), flag)) {
5428 			return (EFAULT);
5429 		}
5430 		local.mt_op = mtop_32_for_64.mt_op;
5431 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5432 		break;
5433 
5434 	case DDI_MODEL_NONE:
5435 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5436 			return (EFAULT);
5437 		}
5438 		local.mt_op = passed.mt_op;
5439 		/* prevent sign extention */
5440 		local.mt_count = (UINT32_MAX & passed.mt_count);
5441 		break;
5442 	}
5443 
5444 #else /* ! _MULTI_DATAMODEL */
5445 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5446 		return (EFAULT);
5447 	}
5448 	local.mt_op = passed.mt_op;
5449 	/* prevent sign extention */
5450 	local.mt_count = (UINT32_MAX & passed.mt_count);
5451 #endif /* _MULTI_DATAMODEL */
5452 
5453 	rval = st_do_mtioctop(un, &local);
5454 
5455 #ifdef _MULTI_DATAMODEL
5456 	switch (ddi_model_convert_from(flag & FMODELS)) {
5457 	case DDI_MODEL_ILP32:
5458 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5459 			rval = ERANGE;
5460 			break;
5461 		}
5462 		/*
5463 		 * Convert 64 bit back to 32 bit before doing
5464 		 * copyout. This is what the ILP32 app expects.
5465 		 */
5466 		mtop_32_for_64.mt_op = local.mt_op;
5467 		mtop_32_for_64.mt_count = local.mt_count;
5468 
5469 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5470 		    sizeof (struct mtop32), flag)) {
5471 			rval = EFAULT;
5472 		}
5473 		break;
5474 
5475 	case DDI_MODEL_NONE:
5476 		passed.mt_count = local.mt_count;
5477 		passed.mt_op = local.mt_op;
5478 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5479 			rval = EFAULT;
5480 		}
5481 		break;
5482 	}
5483 #else /* ! _MULTI_DATAMODE */
5484 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5485 		rval = ERANGE;
5486 	} else {
5487 		passed.mt_op = local.mt_op;
5488 		passed.mt_count = local.mt_count;
5489 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5490 			rval = EFAULT;
5491 		}
5492 	}
5493 #endif /* _MULTI_DATAMODE */
5494 
5495 
5496 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5497 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5498 	    un->un_pos.blkno, un->un_pos.eof);
5499 
5500 	if (un->un_pos.pmode == invalid) {
5501 		un->un_density_known = 0;
5502 	}
5503 
5504 	ASSERT(mutex_owned(ST_MUTEX));
5505 	return (rval);
5506 }
5507 
5508 static int
5509 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5510 {
5511 	struct mtlop local;
5512 	int rval;
5513 
5514 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5515 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5516 		return (EFAULT);
5517 	}
5518 
5519 	rval = st_do_mtioctop(un, &local);
5520 
5521 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5522 		rval = EFAULT;
5523 	}
5524 	return (rval);
5525 }
5526 
5527 
5528 static int
5529 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5530 {
5531 	dev_t dev = un->un_dev;
5532 	int savefile;
5533 	int rval = 0;
5534 
5535 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5536 
5537 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5538 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5539 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5540 	    "fileno=%x, blkno=%x, eof=%x\n",
5541 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5542 
5543 	un->un_status = 0;
5544 
5545 	/*
5546 	 * if we are going to mess with a tape, we have to make sure we have
5547 	 * one and are not offline (i.e. no tape is initialized).  We let
5548 	 * commands pass here that don't actually touch the tape, except for
5549 	 * loading and initialization (rewinding).
5550 	 */
5551 	if (un->un_state == ST_STATE_OFFLINE) {
5552 		switch (mtop->mt_op) {
5553 		case MTLOAD:
5554 		case MTNOP:
5555 			/*
5556 			 * We don't want strategy calling st_tape_init here,
5557 			 * so, change state
5558 			 */
5559 			un->un_state = ST_STATE_INITIALIZING;
5560 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5561 			    "st_do_mtioctop : OFFLINE state = %d\n",
5562 			    un->un_state);
5563 			break;
5564 		default:
5565 			/*
5566 			 * reinitialize by normal means
5567 			 */
5568 			rval = st_tape_init(un);
5569 			if (rval) {
5570 				un->un_state = ST_STATE_INITIALIZING;
5571 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5572 				    "st_do_mtioctop : OFFLINE init failure ");
5573 				un->un_state = ST_STATE_OFFLINE;
5574 				un->un_pos.pmode = invalid;
5575 				if (rval != EACCES) {
5576 					rval = EIO;
5577 				}
5578 				return (rval);
5579 			}
5580 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5581 			break;
5582 		}
5583 	}
5584 
5585 	/*
5586 	 * If the file position is invalid, allow only those
5587 	 * commands that properly position the tape and fail
5588 	 * the rest with EIO
5589 	 */
5590 	if (un->un_pos.pmode == invalid) {
5591 		switch (mtop->mt_op) {
5592 		case MTWEOF:
5593 		case MTRETEN:
5594 		case MTERASE:
5595 		case MTEOM:
5596 		case MTFSF:
5597 		case MTFSR:
5598 		case MTBSF:
5599 		case MTNBSF:
5600 		case MTBSR:
5601 		case MTSRSZ:
5602 		case MTGRSZ:
5603 		case MTSEEK:
5604 		case MTBSSF:
5605 		case MTFSSF:
5606 			return (EIO);
5607 			/* NOTREACHED */
5608 		case MTREW:
5609 		case MTLOAD:
5610 		case MTOFFL:
5611 		case MTNOP:
5612 		case MTTELL:
5613 		case MTLOCK:
5614 		case MTUNLOCK:
5615 			break;
5616 
5617 		default:
5618 			return (ENOTTY);
5619 			/* NOTREACHED */
5620 		}
5621 	}
5622 
5623 	switch (mtop->mt_op) {
5624 	case MTERASE:
5625 		/*
5626 		 * MTERASE rewinds the tape, erase it completely, and returns
5627 		 * to the beginning of the tape
5628 		 */
5629 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5630 			un->un_status = KEY_WRITE_PROTECT;
5631 			un->un_err_resid = mtop->mt_count;
5632 			COPY_POS(&un->un_err_pos, &un->un_pos);
5633 			return (EACCES);
5634 		}
5635 		if (un->un_dp->options & ST_REEL) {
5636 			un->un_fmneeded = 2;
5637 		} else {
5638 			un->un_fmneeded = 1;
5639 		}
5640 		mtop->mt_count = mtop->mt_count ? 1 : 0;
5641 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5642 		    st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
5643 		    st_cmd(un, SCMD_ERASE, mtop->mt_count, SYNC_CMD)) {
5644 			un->un_pos.pmode = invalid;
5645 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5646 			    "st_do_mtioctop : EIO space or erase or "
5647 			    "check den)\n");
5648 			rval = EIO;
5649 		} else {
5650 			/* QIC and helical scan rewind after erase */
5651 			if (un->un_dp->options & ST_REEL) {
5652 				(void) st_cmd(un, SCMD_REWIND, 0, ASYNC_CMD);
5653 			}
5654 		}
5655 		break;
5656 
5657 	case MTWEOF:
5658 		/*
5659 		 * write an end-of-file record
5660 		 */
5661 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5662 			un->un_status = KEY_WRITE_PROTECT;
5663 			un->un_err_resid = mtop->mt_count;
5664 			COPY_POS(&un->un_err_pos, &un->un_pos);
5665 			return (EACCES);
5666 		}
5667 
5668 		/*
5669 		 * zero count means just flush buffers
5670 		 * negative count is not permitted
5671 		 */
5672 		if (mtop->mt_count < 0) {
5673 			return (EINVAL);
5674 		}
5675 
5676 		/* Not on worm */
5677 		if (un->un_read_only == RDWR) {
5678 			un->un_test_append = 1;
5679 		}
5680 
5681 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5682 			if (st_determine_density(un, B_WRITE)) {
5683 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5684 				    "st_do_mtioctop : EIO : MTWEOF can't "
5685 				    "determine density");
5686 				return (EIO);
5687 			}
5688 		}
5689 
5690 		rval = st_write_fm(dev, (int)mtop->mt_count);
5691 		if ((rval != 0) && (rval != EACCES)) {
5692 			/*
5693 			 * Failure due to something other than illegal
5694 			 * request results in loss of state (st_intr).
5695 			 */
5696 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5697 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5698 			    "file mark");
5699 			rval = EIO;
5700 		}
5701 		break;
5702 
5703 	case MTRETEN:
5704 		/*
5705 		 * retension the tape
5706 		 */
5707 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5708 		    st_cmd(un, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5709 			un->un_pos.pmode = invalid;
5710 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5711 			    "st_do_mtioctop : EIO : MTRETEN ");
5712 			rval = EIO;
5713 		}
5714 		break;
5715 
5716 	case MTREW:
5717 		/*
5718 		 * rewind  the tape
5719 		 */
5720 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5721 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5722 			    "st_do_mtioctop : EIO:MTREW check "
5723 			    "density/wfm failed");
5724 			return (EIO);
5725 		}
5726 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
5727 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5728 			    "st_do_mtioctop : EIO : MTREW ");
5729 			rval = EIO;
5730 		}
5731 		break;
5732 
5733 	case MTOFFL:
5734 		/*
5735 		 * rewinds, and, if appropriate, takes the device offline by
5736 		 * unloading the tape
5737 		 */
5738 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5739 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5740 			    "st_do_mtioctop :EIO:MTOFFL check "
5741 			    "density/wfm failed");
5742 			return (EIO);
5743 		}
5744 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
5745 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5746 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5747 			    "st_do_mtioctop : EIO : MTOFFL");
5748 			return (EIO);
5749 		}
5750 		un->un_pos.eof = ST_NO_EOF;
5751 		un->un_laststate = un->un_state;
5752 		un->un_state = ST_STATE_OFFLINE;
5753 		un->un_mediastate = MTIO_EJECTED;
5754 		break;
5755 
5756 	case MTLOAD:
5757 		/*
5758 		 * This is to load a tape into the drive
5759 		 * Note that if the tape is not loaded, the device will have
5760 		 * to be opened via O_NDELAY or O_NONBLOCK.
5761 		 */
5762 		/*
5763 		 * Let's try and clean things up, if we are not
5764 		 * initializing, and then send in the load command, no
5765 		 * matter what.
5766 		 *
5767 		 * load after a media change by the user.
5768 		 */
5769 
5770 		if (un->un_state > ST_STATE_INITIALIZING) {
5771 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5772 		}
5773 		rval = st_cmd(un, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5774 		/* Load command to a drive that doesn't support load */
5775 		if ((rval == EIO) &&
5776 		    ((un->un_status == KEY_NOT_READY) &&
5777 			/* Medium not present */
5778 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5779 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5780 		    (un->un_dp->type == MT_ISSTK9840) &&
5781 			/* CSL not present */
5782 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5783 			rval = ENOTTY;
5784 			break;
5785 		} else if (rval != EACCES && rval != 0) {
5786 			rval = EIO;
5787 		}
5788 		if (rval) {
5789 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5790 			    "st_do_mtioctop : %s : MTLOAD\n",
5791 			    rval == EACCES ? "EACCES" : "EIO");
5792 			/*
5793 			 * If load tape fails, who knows what happened...
5794 			 */
5795 			un->un_pos.pmode = invalid;
5796 			break;
5797 		}
5798 
5799 		/*
5800 		 * reset all counters appropriately using rewind, as if LOAD
5801 		 * succeeds, we are at BOT
5802 		 */
5803 		un->un_state = ST_STATE_INITIALIZING;
5804 
5805 		rval = st_tape_init(un);
5806 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5807 			rval = 0;
5808 			break;
5809 		}
5810 
5811 		if (rval != 0) {
5812 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5813 			    "st_do_mtioctop : EIO : MTLOAD calls "
5814 			    "st_tape_init\n");
5815 			rval = EIO;
5816 			un->un_state = ST_STATE_OFFLINE;
5817 		}
5818 
5819 		break;
5820 
5821 	case MTNOP:
5822 		un->un_status = 0;		/* Reset status */
5823 		un->un_err_resid = 0;
5824 		mtop->mt_count = MTUNIT(dev);
5825 		break;
5826 
5827 	case MTEOM:
5828 		/*
5829 		 * positions the tape at a location just after the last file
5830 		 * written on the tape. For cartridge and 8 mm, this after
5831 		 * the last file mark; for reel, this is inbetween the two
5832 		 * last 2 file marks
5833 		 */
5834 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5835 		    (un->un_lastop == ST_OP_WRITE) ||
5836 		    (un->un_lastop == ST_OP_WEOF)) {
5837 			/*
5838 			 * If the command wants to move to logical end
5839 			 * of media, and we're already there, we're done.
5840 			 * If we were at logical eot, we reset the state
5841 			 * to be *not* at logical eot.
5842 			 *
5843 			 * If we're at physical or logical eot, we prohibit
5844 			 * forward space operations (unconditionally).
5845 			 *
5846 			 * Also if the last operation was a write of any
5847 			 * kind the tape is at EOD.
5848 			 */
5849 			return (0);
5850 		}
5851 		/*
5852 		 * physical tape position may not be what we've been
5853 		 * telling the user; adjust the request accordingly
5854 		 */
5855 		if (IN_EOF(un->un_pos)) {
5856 			un->un_pos.fileno++;
5857 			un->un_pos.blkno = 0;
5858 		}
5859 
5860 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
5861 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5862 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
5863 			    " failed");
5864 			return (EIO);
5865 		}
5866 
5867 		/*
5868 		 * st_find_eod() returns the last fileno we knew about;
5869 		 */
5870 		savefile = st_find_eod(un);
5871 
5872 		if ((un->un_status != KEY_BLANK_CHECK) &&
5873 		    (un->un_status != SUN_KEY_EOT)) {
5874 			un->un_pos.pmode = invalid;
5875 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5876 			    "st_do_mtioctop : EIO : MTEOM status check failed");
5877 			rval = EIO;
5878 		} else {
5879 			/*
5880 			 * For 1/2" reel tapes assume logical EOT marked
5881 			 * by two file marks or we don't care that we may
5882 			 * be extending the last file on the tape.
5883 			 */
5884 			if (un->un_dp->options & ST_REEL) {
5885 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
5886 					un->un_pos.pmode = invalid;
5887 					ST_DEBUG2(ST_DEVINFO, st_label,
5888 					    SCSI_DEBUG,
5889 					    "st_do_mtioctop : EIO : MTEOM space"
5890 					    " cmd failed");
5891 					rval = EIO;
5892 					break;
5893 				}
5894 				/*
5895 				 * Fix up the block number.
5896 				 */
5897 				un->un_pos.blkno = 0;
5898 				un->un_err_pos.blkno = 0;
5899 			}
5900 			un->un_err_resid = 0;
5901 			un->un_pos.fileno = savefile;
5902 			un->un_pos.eof = ST_EOT;
5903 		}
5904 		un->un_status = 0;
5905 		break;
5906 
5907 	case MTFSF:
5908 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
5909 		break;
5910 
5911 	case MTFSR:
5912 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
5913 		break;
5914 
5915 	case MTBSF:
5916 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
5917 		break;
5918 
5919 	case MTNBSF:
5920 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
5921 		break;
5922 
5923 	case MTBSR:
5924 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
5925 		break;
5926 
5927 	case MTBSSF:
5928 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
5929 		break;
5930 
5931 	case MTFSSF:
5932 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
5933 		break;
5934 
5935 	case MTSRSZ:
5936 
5937 		/*
5938 		 * Set record-size to that sent by user
5939 		 * Check to see if there is reason that the requested
5940 		 * block size should not be set.
5941 		 */
5942 
5943 		/* If requesting variable block size is it ok? */
5944 		if ((mtop->mt_count == 0) &&
5945 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
5946 			return (ENOTTY);
5947 		}
5948 
5949 		/*
5950 		 * If requested block size is not variable "0",
5951 		 * is it less then minimum.
5952 		 */
5953 		if ((mtop->mt_count != 0) &&
5954 		    (mtop->mt_count < un->un_minbsize)) {
5955 			return (EINVAL);
5956 		}
5957 
5958 		/* Is the requested block size more then maximum */
5959 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
5960 		    (un->un_maxbsize != 0)) {
5961 			return (EINVAL);
5962 		}
5963 
5964 		/* Is requested block size a modulus the device likes */
5965 		if ((mtop->mt_count % un->un_data_mod) != 0) {
5966 			return (EINVAL);
5967 		}
5968 
5969 		if (st_change_block_size(un, (uint32_t)mtop->mt_count) != 0) {
5970 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5971 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
5972 			return (EIO);
5973 		}
5974 
5975 		return (0);
5976 
5977 	case MTGRSZ:
5978 		/*
5979 		 * Get record-size to the user
5980 		 */
5981 		mtop->mt_count = un->un_bsize;
5982 		rval = 0;
5983 		break;
5984 
5985 	case MTTELL:
5986 		rval = st_update_block_pos(un, st_cmd, 0);
5987 		mtop->mt_count = un->un_pos.lgclblkno;
5988 		break;
5989 
5990 	case MTSEEK:
5991 		rval = st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
5992 		    (uint64_t)mtop->mt_count, un->un_pos.partition);
5993 		/*
5994 		 * This bit of magic make mt print the actual position if
5995 		 * the resulting position was not what was asked for.
5996 		 */
5997 		if (rval == ESPIPE) {
5998 			rval = EIO;
5999 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
6000 				mtop->mt_op = MTTELL;
6001 				mtop->mt_count = un->un_pos.lgclblkno;
6002 			}
6003 		}
6004 		break;
6005 
6006 	case MTLOCK:
6007 		if (st_cmd(un, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
6008 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6009 			    "st_do_mtioctop : EIO : MTLOCK");
6010 			rval = EIO;
6011 		}
6012 		break;
6013 
6014 	case MTUNLOCK:
6015 		if (st_cmd(un, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
6016 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6017 			    "st_do_mtioctop : EIO : MTUNLOCK");
6018 			rval = EIO;
6019 		}
6020 		break;
6021 
6022 	default:
6023 		rval = ENOTTY;
6024 	}
6025 
6026 	return (rval);
6027 }
6028 
6029 
6030 /*
6031  * Run a command for uscsi ioctl.
6032  */
6033 static int
6034 st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
6035 {
6036 	struct uscsi_cmd	*uscmd;
6037 	struct buf	*bp;
6038 	enum uio_seg	uioseg;
6039 	int	offline_state = 0;
6040 	int	err = 0;
6041 	dev_t dev = un->un_dev;
6042 
6043 	ST_FUNC(ST_DEVINFO, st_uscsi_cmd);
6044 
6045 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6046 	    "st_uscsi_cmd(dev = 0x%lx)\n", un->un_dev);
6047 
6048 	ASSERT(mutex_owned(ST_MUTEX));
6049 
6050 	/*
6051 	 * We really don't know what commands are coming in here and
6052 	 * we don't want to limit the commands coming in.
6053 	 *
6054 	 * If st_tape_init() gets called from st_strategy(), then we
6055 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
6056 	 * which it never will, as we set it below.  To prevent
6057 	 * st_tape_init() from getting called, we have to set state to other
6058 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
6059 	 * achieves this purpose already.
6060 	 *
6061 	 * We use offline_state to preserve the OFFLINE state, if it exists,
6062 	 * so other entry points to the driver might have the chance to call
6063 	 * st_tape_init().
6064 	 */
6065 	if (un->un_state == ST_STATE_OFFLINE) {
6066 		un->un_laststate = ST_STATE_OFFLINE;
6067 		un->un_state = ST_STATE_INITIALIZING;
6068 		offline_state = 1;
6069 	}
6070 
6071 	mutex_exit(ST_MUTEX);
6072 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag, ROUTE, &uscmd);
6073 	mutex_enter(ST_MUTEX);
6074 	if (err != 0) {
6075 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6076 		    "st_uscsi_cmd: scsi_uscsi_alloc_and_copyin failed\n");
6077 		goto exit;
6078 	}
6079 
6080 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
6081 
6082 	/* check to see if this command requires the drive to be reserved */
6083 	if (uscmd->uscsi_cdb != NULL) {
6084 		err = st_check_cdb_for_need_to_reserve(un,
6085 		    (uchar_t *)uscmd->uscsi_cdb);
6086 		if (err) {
6087 			goto exit_free;
6088 		}
6089 		/*
6090 		 * If this is a space command we need to save the starting
6091 		 * point so we can retry from there if the command fails.
6092 		 */
6093 		if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6094 		    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) {
6095 			(void) st_update_block_pos(un, st_cmd, 0);
6096 		}
6097 	}
6098 
6099 	/*
6100 	 * Forground should not be doing anything while recovery is active.
6101 	 */
6102 	ASSERT(un->un_recov_buf_busy == 0);
6103 
6104 	/*
6105 	 * Get buffer resources...
6106 	 */
6107 	while (un->un_sbuf_busy)
6108 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6109 	un->un_sbuf_busy = 1;
6110 
6111 #ifdef STDEBUG
6112 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0x7) > 6) {
6113 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
6114 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6115 		    "uscsi cdb", uscmd->uscsi_cdb);
6116 		if (uscmd->uscsi_buflen) {
6117 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6118 			    "uscsi %s of %ld bytes %s %s space\n",
6119 			    (rw == B_READ) ? rd_str : wr_str,
6120 			    uscmd->uscsi_buflen,
6121 			    (rw == B_READ) ? "to" : "from",
6122 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
6123 		}
6124 	}
6125 #endif /* STDEBUG */
6126 
6127 	/*
6128 	 * Although st_uscsi_cmd() never makes use of these
6129 	 * now, we are just being safe and consistent.
6130 	 */
6131 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
6132 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
6133 
6134 	un->un_srqbufp = uscmd->uscsi_rqbuf;
6135 	bp = un->un_sbufp;
6136 	bzero(bp, sizeof (buf_t));
6137 	if (uscmd->uscsi_cdb != NULL) {
6138 		bp->b_forw = (struct buf *)(uintptr_t)uscmd->uscsi_cdb[0];
6139 	}
6140 	bp->b_back = (struct buf *)uscmd;
6141 
6142 	mutex_exit(ST_MUTEX);
6143 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, st_strategy, bp, NULL);
6144 	mutex_enter(ST_MUTEX);
6145 
6146 	/*
6147 	 * If scsi reset successful, don't write any filemarks.
6148 	 */
6149 	if ((err == 0) && (uscmd->uscsi_flags &
6150 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
6151 		un->un_fmneeded = 0;
6152 	}
6153 
6154 exit_free:
6155 	/*
6156 	 * Free resources
6157 	 */
6158 	un->un_sbuf_busy = 0;
6159 	un->un_srqbufp = NULL;
6160 
6161 	/*
6162 	 * If was a space command need to update logical block position.
6163 	 * If the command failed such that positioning is invalid, Don't
6164 	 * update the position as the user must do this to validate the
6165 	 * position for data protection.
6166 	 */
6167 	if ((uscmd->uscsi_cdb != NULL) &&
6168 	    ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6169 	    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) &&
6170 	    (un->un_pos.pmode != invalid)) {
6171 		un->un_running.pmode = invalid;
6172 		(void) st_update_block_pos(un, st_cmd, 1);
6173 		/*
6174 		 * Set running position to invalid so it updates on the
6175 		 * next command.
6176 		 */
6177 		un->un_running.pmode = invalid;
6178 	}
6179 	cv_signal(&un->un_sbuf_cv);
6180 	mutex_exit(ST_MUTEX);
6181 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
6182 	mutex_enter(ST_MUTEX);
6183 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6184 	    "st_uscsi_cmd returns 0x%x\n", err);
6185 
6186 exit:
6187 	/* don't lose offline state */
6188 	if (offline_state) {
6189 		un->un_state = ST_STATE_OFFLINE;
6190 	}
6191 
6192 	ASSERT(mutex_owned(ST_MUTEX));
6193 	return (err);
6194 }
6195 
6196 static int
6197 st_write_fm(dev_t dev, int wfm)
6198 {
6199 	int i;
6200 	int rval;
6201 
6202 	GET_SOFT_STATE(dev);
6203 
6204 	ST_FUNC(ST_DEVINFO, st_write_fm);
6205 
6206 	ASSERT(mutex_owned(ST_MUTEX));
6207 
6208 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6209 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6210 
6211 	/*
6212 	 * write one filemark at the time after EOT
6213 	 */
6214 	if (un->un_pos.eof >= ST_EOT) {
6215 		for (i = 0; i < wfm; i++) {
6216 			rval = st_cmd(un, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6217 			if (rval == EACCES) {
6218 				return (rval);
6219 			}
6220 			if (rval != 0) {
6221 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6222 				    "st_write_fm : EIO : write EOT file mark");
6223 				return (EIO);
6224 			}
6225 		}
6226 	} else {
6227 		rval = st_cmd(un, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6228 		if (rval == EACCES) {
6229 			return (rval);
6230 		}
6231 		if (rval) {
6232 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6233 			    "st_write_fm : EIO : write file mark");
6234 			return (EIO);
6235 		}
6236 	}
6237 
6238 	ASSERT(mutex_owned(ST_MUTEX));
6239 	return (0);
6240 }
6241 
6242 #ifdef STDEBUG
6243 static void
6244 st_start_dump(struct scsi_tape *un, struct buf *bp)
6245 {
6246 	struct scsi_pkt *pkt = BP_PKT(bp);
6247 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6248 
6249 	ST_FUNC(ST_DEVINFO, st_start_dump);
6250 
6251 	if ((st_debug & 0x7) < 6)
6252 		return;
6253 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6254 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6255 	    (void *)bp->b_forw, bp->b_bcount,
6256 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6257 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6258 	    "st_start: cdb",  (caddr_t)cdbp);
6259 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6260 	    "st_start: fileno=%d, blk=%d\n",
6261 	    un->un_pos.fileno, un->un_pos.blkno);
6262 }
6263 #endif
6264 
6265 
6266 /*
6267  * Command start && done functions
6268  */
6269 
6270 /*
6271  * st_start()
6272  *
6273  * Called from:
6274  *  st_strategy() to start a command.
6275  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6276  *  st_attach() when resuming from power down state.
6277  *  st_start_restart() to retry transport when device was previously busy.
6278  *  st_done_and_mutex_exit() to start the next command when previous is done.
6279  *
6280  * On entry:
6281  *  scsi_pkt may or may not be allocated.
6282  *
6283  */
6284 static void
6285 st_start(struct scsi_tape *un)
6286 {
6287 	struct buf *bp;
6288 	int status;
6289 	int queued;
6290 
6291 	ST_FUNC(ST_DEVINFO, st_start);
6292 	ASSERT(mutex_owned(ST_MUTEX));
6293 
6294 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6295 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6296 
6297 	if (un->un_recov_buf_busy) {
6298 		/* recovery commands can happen anytime */
6299 		bp = un->un_recov_buf;
6300 		queued = 0;
6301 	} else if (un->un_sbuf_busy) {
6302 		/* sbuf commands should only happen with an empty queue. */
6303 		ASSERT(un->un_quef == NULL);
6304 		ASSERT(un->un_runqf == NULL);
6305 		bp = un->un_sbufp;
6306 		queued = 0;
6307 	} else if (un->un_quef != NULL) {
6308 		if (un->un_persistence && un->un_persist_errors) {
6309 			return;
6310 		}
6311 		bp = un->un_quef;
6312 		queued = 1;
6313 	} else {
6314 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6315 		    "st_start() returning no buf found\n");
6316 		return;
6317 	}
6318 
6319 	ASSERT((bp->b_flags & B_DONE) == 0);
6320 
6321 	/*
6322 	 * Don't send more than un_throttle commands to the HBA
6323 	 */
6324 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6325 		/*
6326 		 * if doing recovery we know there is outstanding commands.
6327 		 */
6328 		if (bp != un->un_recov_buf) {
6329 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6330 			    "st_start returning throttle = %d or ncmds = %d\n",
6331 			    un->un_throttle, un->un_ncmds);
6332 			if (un->un_ncmds == 0) {
6333 				typedef void (*func)();
6334 				func fnc = (func)st_runout;
6335 
6336 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6337 				    "Sending delayed start to st_runout()\n");
6338 				mutex_exit(ST_MUTEX);
6339 				(void) timeout(fnc, un, drv_usectohz(1000000));
6340 			}
6341 			return;
6342 		}
6343 	}
6344 
6345 	/*
6346 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6347 	 * build the command.
6348 	 */
6349 	if (BP_PKT(bp) == NULL) {
6350 		ASSERT((bp->b_flags & B_DONE) == 0);
6351 		st_make_cmd(un, bp, st_runout);
6352 		ASSERT((bp->b_flags & B_DONE) == 0);
6353 		status = geterror(bp);
6354 
6355 		/*
6356 		 * Some HBA's don't call bioerror() to set an error.
6357 		 * And geterror() returns zero if B_ERROR is not set.
6358 		 * So if we get zero we must check b_error.
6359 		 */
6360 		if (status == 0 && bp->b_error != 0) {
6361 			status = bp->b_error;
6362 			bioerror(bp, status);
6363 		}
6364 
6365 		/*
6366 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6367 		 * In tape ENOMEM has special meaning so we'll change it.
6368 		 */
6369 		if (status == ENOMEM) {
6370 			status = 0;
6371 			bioerror(bp, status);
6372 		}
6373 
6374 		/*
6375 		 * Did it fail and is it retryable?
6376 		 * If so return and wait for the callback through st_runout.
6377 		 * Also looks like scsi_init_pkt() will setup a callback even
6378 		 * if it isn't retryable.
6379 		 */
6380 		if (BP_PKT(bp) == NULL) {
6381 			if (status == 0) {
6382 				/*
6383 				 * If first attempt save state.
6384 				 */
6385 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6386 					un->un_laststate = un->un_state;
6387 					un->un_state = ST_STATE_RESOURCE_WAIT;
6388 				}
6389 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6390 				    "temp no resources for pkt\n");
6391 			} else if (status == EINVAL) {
6392 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6393 				    "scsi_init_pkt rejected pkt as too big\n");
6394 				if (un->un_persistence) {
6395 					st_set_pe_flag(un);
6396 				}
6397 			} else {
6398 				/*
6399 				 * Unlikely that it would be retryable then not.
6400 				 */
6401 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6402 					un->un_state = un->un_laststate;
6403 				}
6404 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6405 				    "perm no resources for pkt errno = 0x%x\n",
6406 				    status);
6407 			}
6408 			return;
6409 		}
6410 		/*
6411 		 * Worked this time set the state back.
6412 		 */
6413 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6414 			un->un_state = un->un_laststate;
6415 		}
6416 	}
6417 
6418 	if (queued) {
6419 		/*
6420 		 * move from waitq to runq
6421 		 */
6422 		(void) st_remove_from_queue(&un->un_quef, &un->un_quel, bp);
6423 		st_add_to_queue(&un->un_runqf, &un->un_runql, un->un_runql, bp);
6424 	}
6425 
6426 
6427 #ifdef STDEBUG
6428 	st_start_dump(un, bp);
6429 #endif
6430 
6431 	/* could not get here if throttle was zero */
6432 	un->un_last_throttle = un->un_throttle;
6433 	un->un_throttle = 0;	/* so nothing else will come in here */
6434 	un->un_ncmds++;
6435 
6436 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6437 
6438 	status = st_transport(un, BP_PKT(bp));
6439 
6440 	if (un->un_last_throttle) {
6441 		un->un_throttle = un->un_last_throttle;
6442 	}
6443 
6444 	if (status != TRAN_ACCEPT) {
6445 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6446 		mutex_exit(ST_MUTEX);
6447 
6448 		if (status == TRAN_BUSY) {
6449 			/* if too many retries, fail the transport */
6450 			if (st_handle_start_busy(un, bp,
6451 			    ST_TRAN_BUSY_TIMEOUT, queued) == 0)
6452 				goto done;
6453 		}
6454 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6455 		    "transport rejected %d\n", status);
6456 		bp->b_resid = bp->b_bcount;
6457 
6458 
6459 #ifndef __lock_lint
6460 		/*
6461 		 * warlock doesn't understand this potential
6462 		 * recursion?
6463 		 */
6464 		mutex_enter(ST_MUTEX);
6465 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6466 		ST_DO_ERRSTATS(un, st_transerrs);
6467 		st_bioerror(bp, EIO);
6468 		st_set_pe_flag(un);
6469 		st_done_and_mutex_exit(un, bp);
6470 #endif
6471 	} else {
6472 		un->un_tran_retry_ct = 0;
6473 		mutex_exit(ST_MUTEX);
6474 	}
6475 
6476 done:
6477 
6478 	mutex_enter(ST_MUTEX);
6479 }
6480 
6481 /*
6482  * if the transport is busy, then put this bp back on the waitq
6483  */
6484 static int
6485 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6486     clock_t timeout_interval, int queued)
6487 {
6488 
6489 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6490 
6491 	mutex_enter(ST_MUTEX);
6492 
6493 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6494 	    "st_handle_start_busy()\n");
6495 
6496 	/*
6497 	 * Check to see if we hit the retry timeout and one last check for
6498 	 * making sure this is the last on the runq, if it is not, we have
6499 	 * to fail
6500 	 */
6501 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
6502 	    ((queued) && (un->un_runql != bp))) {
6503 		mutex_exit(ST_MUTEX);
6504 		return (-1);
6505 	}
6506 
6507 	if (queued) {
6508 		/* put the bp back on the waitq */
6509 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
6510 	}
6511 
6512 	/*
6513 	 * Decrement un_ncmds so that this
6514 	 * gets thru' st_start() again.
6515 	 */
6516 	un->un_ncmds--;
6517 
6518 	if (queued) {
6519 		/*
6520 		 * since this is an error case, we won't have to do this list
6521 		 * walking much. We've already made sure this bp was the
6522 		 * last on the runq
6523 		 */
6524 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6525 
6526 		/*
6527 		 * send a marker pkt, if appropriate
6528 		 */
6529 		st_hba_unflush(un);
6530 
6531 	}
6532 	/*
6533 	 * all queues are aligned, we are just waiting to
6534 	 * transport, don't alloc any more buf p's, when
6535 	 * st_start is reentered.
6536 	 */
6537 	(void) timeout(st_start_restart, un, timeout_interval);
6538 
6539 	mutex_exit(ST_MUTEX);
6540 	return (0);
6541 }
6542 
6543 
6544 /*
6545  * st_runout a callback that is called what a resource allocatation failed
6546  */
6547 static int
6548 st_runout(caddr_t arg)
6549 {
6550 	struct scsi_tape *un = (struct scsi_tape *)arg;
6551 	struct buf *bp;
6552 	int queued;
6553 
6554 	ASSERT(un != NULL);
6555 
6556 	ST_FUNC(ST_DEVINFO, st_runout);
6557 
6558 	mutex_enter(ST_MUTEX);
6559 
6560 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6561 
6562 	if (un->un_recov_buf_busy != 0) {
6563 		bp = un->un_recov_buf;
6564 		queued = 0;
6565 	} else if (un->un_sbuf_busy != 0) {
6566 		/* sbuf commands should only happen with an empty queue. */
6567 		ASSERT(un->un_quef == NULL);
6568 		ASSERT(un->un_runqf == NULL);
6569 		bp = un->un_sbufp;
6570 		queued = 0;
6571 	} else if (un->un_quef != NULL) {
6572 		bp = un->un_quef;
6573 		if (un->un_persistence && un->un_persist_errors) {
6574 			mutex_exit(ST_MUTEX);
6575 			bp->b_resid = bp->b_bcount;
6576 			biodone(bp);
6577 			return (1);
6578 		}
6579 		queued = 1;
6580 	} else {
6581 		ASSERT(1 == 0);
6582 		mutex_exit(ST_MUTEX);
6583 		return (1);
6584 	}
6585 
6586 	/*
6587 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6588 	 */
6589 	if ((bp != NULL) && (geterror(bp) != 0)) {
6590 
6591 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6592 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6593 		    bp->b_flags, geterror(bp));
6594 		ASSERT((bp->b_flags & B_DONE) == 0);
6595 
6596 		if (queued) {
6597 			(void) st_remove_from_queue(&un->un_quef, &un->un_quel,
6598 			    bp);
6599 		}
6600 		mutex_exit(ST_MUTEX);
6601 
6602 		ASSERT((bp->b_flags & B_DONE) == 0);
6603 
6604 		/*
6605 		 * Set resid, Error already set, then unblock calling thread.
6606 		 */
6607 		bp->b_resid = bp->b_bcount;
6608 		biodone(bp);
6609 	} else {
6610 		/*
6611 		 * Try Again
6612 		 */
6613 		st_start(un);
6614 		mutex_exit(ST_MUTEX);
6615 	}
6616 
6617 	/*
6618 	 * Comments courtesy of sd.c
6619 	 * The scsi_init_pkt routine allows for the callback function to
6620 	 * return a 0 indicating the callback should be rescheduled or a 1
6621 	 * indicating not to reschedule. This routine always returns 1
6622 	 * because the driver always provides a callback function to
6623 	 * scsi_init_pkt. This results in a callback always being scheduled
6624 	 * (via the scsi_init_pkt callback implementation) if a resource
6625 	 * failure occurs.
6626 	 */
6627 
6628 	return (1);
6629 }
6630 
6631 /*
6632  * st_done_and_mutex_exit()
6633  *	- remove bp from runq
6634  *	- start up the next request
6635  *	- if this was an asynch bp, clean up
6636  *	- exit with released mutex
6637  */
6638 static void
6639 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6640 {
6641 	int	pe_flagged = 0;
6642 
6643 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6644 #if !defined(lint)
6645 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6646 #endif
6647 
6648 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6649 
6650 	ASSERT(mutex_owned(ST_MUTEX));
6651 
6652 	(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6653 
6654 	un->un_ncmds--;
6655 	cv_signal(&un->un_queue_cv);
6656 
6657 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6658 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6659 	    "0x%x\n", (uchar_t)*((caddr_t)(BP_PKT(bp))->pkt_cdbp), bp->b_bcount,
6660 	    bp->b_resid, bp->b_flags);
6661 
6662 
6663 	/*
6664 	 * update kstats with transfer count info
6665 	 */
6666 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6667 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6668 		if (bp->b_flags & B_READ) {
6669 			IOSP->reads++;
6670 			IOSP->nread += n_done;
6671 		} else {
6672 			IOSP->writes++;
6673 			IOSP->nwritten += n_done;
6674 		}
6675 	}
6676 
6677 	/*
6678 	 * Start the next one before releasing resources on this one, if
6679 	 * there is something on the queue and persistent errors has not been
6680 	 * flagged
6681 	 */
6682 
6683 	if ((pe_flagged = (un->un_persistence && un->un_persist_errors)) != 0) {
6684 		un->un_last_resid = bp->b_resid;
6685 		un->un_last_count = bp->b_bcount;
6686 	}
6687 
6688 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6689 		cv_broadcast(&un->un_tape_busy_cv);
6690 	} else if (un->un_quef && un->un_throttle && !pe_flagged &&
6691 	    (bp != un->un_recov_buf)) {
6692 		st_start(un);
6693 	}
6694 
6695 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6696 		/*
6697 		 * Since we marked this ourselves as ASYNC,
6698 		 * there isn't anybody around waiting for
6699 		 * completion any more.
6700 		 */
6701 		uchar_t *cdb = (uchar_t *)bp->b_forw;
6702 		if (*cdb == SCMD_READ || *cdb == SCMD_WRITE) {
6703 			bp->b_un.b_addr = (caddr_t)0;
6704 		}
6705 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6706 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6707 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
6708 		    "CDB sent with B_ASYNC",  (caddr_t)cdb);
6709 		if (BP_PKT(bp)) {
6710 			scsi_destroy_pkt(BP_PKT(bp));
6711 		}
6712 		un->un_sbuf_busy = 0;
6713 		cv_signal(&un->un_sbuf_cv);
6714 		mutex_exit(ST_MUTEX);
6715 		return;
6716 	}
6717 
6718 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6719 		/*
6720 		 * Copy status from scsi_pkt to uscsi_cmd
6721 		 * since st_uscsi_cmd needs it
6722 		 */
6723 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6724 	}
6725 
6726 
6727 #ifdef STDEBUG
6728 	if (((st_debug & 0x7) >= 4) &&
6729 	    (((un->un_pos.blkno % 100) == 0) ||
6730 	    (un->un_persistence && un->un_persist_errors))) {
6731 
6732 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6733 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6734 		    "un_errno = %d, un_pe = %d\n",
6735 		    un->un_ncmds, un->un_throttle, un->un_errno,
6736 		    un->un_persist_errors);
6737 	}
6738 
6739 #endif
6740 
6741 	mutex_exit(ST_MUTEX);
6742 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6743 	    "st_done_and_mutex_exit: freeing pkt\n");
6744 
6745 	if (BP_PKT(bp)) {
6746 		scsi_destroy_pkt(BP_PKT(bp));
6747 	}
6748 
6749 	biodone(bp);
6750 
6751 	/*
6752 	 * now that we biodoned that command, if persistent errors have been
6753 	 * flagged, flush the waitq
6754 	 */
6755 	if (pe_flagged)
6756 		st_flush(un);
6757 }
6758 
6759 
6760 /*
6761  * Tape error, flush tape driver queue.
6762  */
6763 static void
6764 st_flush(struct scsi_tape *un)
6765 {
6766 	struct buf *bp;
6767 
6768 	ST_FUNC(ST_DEVINFO, st_flush);
6769 
6770 	mutex_enter(ST_MUTEX);
6771 
6772 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6773 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6774 	    un->un_ncmds, (void *)un->un_quef);
6775 
6776 	/*
6777 	 * if we still have commands outstanding, wait for them to come in
6778 	 * before flushing the queue, and make sure there is a queue
6779 	 */
6780 	if (un->un_ncmds || !un->un_quef)
6781 		goto exit;
6782 
6783 	/*
6784 	 * we have no more commands outstanding, so let's deal with special
6785 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6786 	 * is 0, then we know there was no error and we return a 0 read or
6787 	 * write before showing errors
6788 	 */
6789 
6790 	/* Flush the wait queue. */
6791 	while ((bp = un->un_quef) != NULL) {
6792 		un->un_quef = bp->b_actf;
6793 
6794 		bp->b_resid = bp->b_bcount;
6795 
6796 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6797 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6798 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6799 
6800 		st_set_pe_errno(un);
6801 
6802 		bioerror(bp, un->un_errno);
6803 
6804 		mutex_exit(ST_MUTEX);
6805 		/* it should have one, but check anyway */
6806 		if (BP_PKT(bp)) {
6807 			scsi_destroy_pkt(BP_PKT(bp));
6808 		}
6809 		biodone(bp);
6810 		mutex_enter(ST_MUTEX);
6811 	}
6812 
6813 	/*
6814 	 * It's not a bad practice to reset the
6815 	 * waitq tail pointer to NULL.
6816 	 */
6817 	un->un_quel = NULL;
6818 
6819 exit:
6820 	/* we mucked with the queue, so let others know about it */
6821 	cv_signal(&un->un_queue_cv);
6822 	mutex_exit(ST_MUTEX);
6823 }
6824 
6825 
6826 /*
6827  * Utility functions
6828  */
6829 static int
6830 st_determine_generic(struct scsi_tape *un)
6831 {
6832 	int bsize;
6833 	static char *cart = "0.25 inch cartridge";
6834 	char *sizestr;
6835 
6836 	ST_FUNC(ST_DEVINFO, st_determine_generic);
6837 
6838 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6839 	    "st_determine_generic(un = 0x%p)\n", (void*)un);
6840 
6841 	ASSERT(mutex_owned(ST_MUTEX));
6842 
6843 	if (st_modesense(un)) {
6844 		return (-1);
6845 	}
6846 
6847 	bsize = (un->un_mspl->high_bl << 16)	|
6848 	    (un->un_mspl->mid_bl << 8)	|
6849 	    (un->un_mspl->low_bl);
6850 
6851 	if (bsize == 0) {
6852 		un->un_dp->options |= ST_VARIABLE;
6853 		un->un_dp->bsize = 0;
6854 		un->un_bsize = 0;
6855 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
6856 		/*
6857 		 * record size of this device too big.
6858 		 * try and convert it to variable record length.
6859 		 *
6860 		 */
6861 		un->un_dp->options |= ST_VARIABLE;
6862 		if (st_change_block_size(un, 0) != 0) {
6863 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6864 			    "Fixed Record Size %d is too large\n", bsize);
6865 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6866 			    "Cannot switch to variable record size\n");
6867 			un->un_dp->options &= ~ST_VARIABLE;
6868 			return (-1);
6869 		}
6870 	} else if (st_change_block_size(un, 0) == 0) {
6871 		/*
6872 		 * If the drive was set to a non zero block size,
6873 		 * See if it can be set to a zero block size.
6874 		 * If it works, ST_VARIABLE so user can set it as they want.
6875 		 */
6876 		un->un_dp->options |= ST_VARIABLE;
6877 		un->un_dp->bsize = 0;
6878 		un->un_bsize = 0;
6879 	} else {
6880 		un->un_dp->bsize = bsize;
6881 		un->un_bsize = bsize;
6882 	}
6883 
6884 
6885 	switch (un->un_mspl->density) {
6886 	default:
6887 	case 0x0:
6888 		/*
6889 		 * default density, cannot determine any other
6890 		 * information.
6891 		 */
6892 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
6893 		un->un_dp->type = ST_TYPE_DEFAULT;
6894 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
6895 		break;
6896 	case 0x1:
6897 	case 0x2:
6898 	case 0x3:
6899 	case 0x6:
6900 		/*
6901 		 * 1/2" reel
6902 		 */
6903 		sizestr = "0.50 inch reel";
6904 		un->un_dp->type = ST_TYPE_REEL;
6905 		un->un_dp->options |= ST_REEL;
6906 		un->un_dp->densities[0] = 0x1;
6907 		un->un_dp->densities[1] = 0x2;
6908 		un->un_dp->densities[2] = 0x6;
6909 		un->un_dp->densities[3] = 0x3;
6910 		break;
6911 	case 0x4:
6912 	case 0x5:
6913 	case 0x7:
6914 	case 0x0b:
6915 
6916 		/*
6917 		 * Quarter inch.
6918 		 */
6919 		sizestr = cart;
6920 		un->un_dp->type = ST_TYPE_DEFAULT;
6921 		un->un_dp->options |= ST_QIC;
6922 
6923 		un->un_dp->densities[1] = 0x4;
6924 		un->un_dp->densities[2] = 0x5;
6925 		un->un_dp->densities[3] = 0x7;
6926 		un->un_dp->densities[0] = 0x0b;
6927 		break;
6928 
6929 	case 0x0f:
6930 	case 0x10:
6931 	case 0x11:
6932 	case 0x12:
6933 		/*
6934 		 * QIC-120, QIC-150, QIC-320, QIC-600
6935 		 */
6936 		sizestr = cart;
6937 		un->un_dp->type = ST_TYPE_DEFAULT;
6938 		un->un_dp->options |= ST_QIC;
6939 		un->un_dp->densities[0] = 0x0f;
6940 		un->un_dp->densities[1] = 0x10;
6941 		un->un_dp->densities[2] = 0x11;
6942 		un->un_dp->densities[3] = 0x12;
6943 		break;
6944 
6945 	case 0x09:
6946 	case 0x0a:
6947 	case 0x0c:
6948 	case 0x0d:
6949 		/*
6950 		 * 1/2" cartridge tapes. Include HI-TC.
6951 		 */
6952 		sizestr = cart;
6953 		sizestr[2] = '5';
6954 		sizestr[3] = '0';
6955 		un->un_dp->type = ST_TYPE_HIC;
6956 		un->un_dp->densities[0] = 0x09;
6957 		un->un_dp->densities[1] = 0x0a;
6958 		un->un_dp->densities[2] = 0x0c;
6959 		un->un_dp->densities[3] = 0x0d;
6960 		break;
6961 
6962 	case 0x13:
6963 			/* DDS-2/DDS-3 scsi spec densities */
6964 	case 0x24:
6965 	case 0x25:
6966 	case 0x26:
6967 		sizestr = "DAT Data Storage (DDS)";
6968 		un->un_dp->type = ST_TYPE_DAT;
6969 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6970 		break;
6971 
6972 	case 0x14:
6973 		/*
6974 		 * Helical Scan (Exabyte) devices
6975 		 */
6976 		sizestr = "8mm helical scan cartridge";
6977 		un->un_dp->type = ST_TYPE_EXABYTE;
6978 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6979 		break;
6980 	}
6981 
6982 	/*
6983 	 * Assume LONG ERASE, BSF and BSR
6984 	 */
6985 
6986 	un->un_dp->options |=
6987 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
6988 
6989 	/*
6990 	 * Only if mode sense data says no buffered write, set NOBUF
6991 	 */
6992 	if (un->un_mspl->bufm == 0)
6993 		un->un_dp->options |= ST_NOBUF;
6994 
6995 	/*
6996 	 * set up large read and write retry counts
6997 	 */
6998 
6999 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
7000 
7001 	/*
7002 	 * If this is a 0.50 inch reel tape, and
7003 	 * it is *not* variable mode, try and
7004 	 * set it to variable record length
7005 	 * mode.
7006 	 */
7007 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
7008 	    (un->un_dp->options & ST_VARIABLE)) {
7009 		if (st_change_block_size(un, 0) == 0) {
7010 			un->un_dp->bsize = 0;
7011 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
7012 			    un->un_mspl->low_bl = 0;
7013 		}
7014 	}
7015 
7016 	/*
7017 	 * Write to console about type of device found
7018 	 */
7019 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
7020 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
7021 	    sizestr);
7022 	if (un->un_dp->options & ST_VARIABLE) {
7023 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7024 		    "!Variable record length I/O\n");
7025 	} else {
7026 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7027 		    "!Fixed record length (%d byte blocks) I/O\n",
7028 		    un->un_dp->bsize);
7029 	}
7030 	ASSERT(mutex_owned(ST_MUTEX));
7031 	return (0);
7032 }
7033 
7034 static int
7035 st_determine_density(struct scsi_tape *un, int rw)
7036 {
7037 	int rval = 0;
7038 
7039 	ST_FUNC(ST_DEVINFO, st_determine_density);
7040 
7041 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7042 	    "st_determine_density(un = 0x%p, rw = %s)\n",
7043 	    (void*)un, (rw == B_WRITE ? wr_str: rd_str));
7044 
7045 	ASSERT(mutex_owned(ST_MUTEX));
7046 
7047 	/*
7048 	 * If we're past BOT, density is determined already.
7049 	 */
7050 	if (un->un_pos.pmode == logical) {
7051 		if (un->un_pos.lgclblkno != 0) {
7052 			goto exit;
7053 		}
7054 	} else if (un->un_pos.pmode == legacy) {
7055 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
7056 			/*
7057 			 * XXX: put in a bitch message about attempting to
7058 			 * XXX: change density past BOT.
7059 			 */
7060 			goto exit;
7061 		}
7062 	} else {
7063 		goto exit;
7064 	}
7065 	if ((un->un_pos.pmode == logical) &&
7066 	    (un->un_pos.lgclblkno != 0)) {
7067 		goto exit;
7068 	}
7069 
7070 
7071 	/*
7072 	 * If we're going to be writing, we set the density
7073 	 */
7074 	if (rw == 0 || rw == B_WRITE) {
7075 		/* un_curdens is used as an index into densities table */
7076 		un->un_curdens = MT_DENSITY(un->un_dev);
7077 		if (st_set_density(un)) {
7078 			rval = -1;
7079 		}
7080 		goto exit;
7081 	}
7082 
7083 	/*
7084 	 * If density is known already,
7085 	 * we don't have to get it again.(?)
7086 	 */
7087 	if (!un->un_density_known) {
7088 		if (st_get_density(un)) {
7089 			rval = -1;
7090 		}
7091 	}
7092 
7093 exit:
7094 	ASSERT(mutex_owned(ST_MUTEX));
7095 	return (rval);
7096 }
7097 
7098 
7099 /*
7100  * Try to determine density. We do this by attempting to read the
7101  * first record off the tape, cycling through the available density
7102  * codes as we go.
7103  */
7104 
7105 static int
7106 st_get_density(struct scsi_tape *un)
7107 {
7108 	int succes = 0, rval = -1, i;
7109 	uint_t size;
7110 	uchar_t dens, olddens;
7111 
7112 	ST_FUNC(ST_DEVINFO, st_get_density);
7113 
7114 	ST_FUNC(ST_DEVINFO, st_get_density);
7115 
7116 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7117 	    "st_get_density(un = 0x%p)\n", (void*)un);
7118 
7119 	ASSERT(mutex_owned(ST_MUTEX));
7120 
7121 	/*
7122 	 * If Auto Density override is enabled The drive has
7123 	 * only one density and there is no point in attempting
7124 	 * find the correct one.
7125 	 *
7126 	 * Since most modern drives auto detect the density
7127 	 * and format of the recorded media before they come
7128 	 * ready. What this function does is a legacy behavior
7129 	 * and modern drives not only don't need it, The backup
7130 	 * utilities that do positioning via uscsi find the un-
7131 	 * expected rewinds problematic.
7132 	 *
7133 	 * The drives that need this are old reel to reel devices.
7134 	 * I took a swag and said they must be scsi-1 or older.
7135 	 * I don't beleave there will any of the newer devices
7136 	 * that need this. There will be some scsi-1 devices that
7137 	 * don't need this but I don't think they will be using the
7138 	 * BIG aftermarket backup and restore utilitys.
7139 	 */
7140 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
7141 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
7142 		un->un_density_known = 1;
7143 		rval = 0;
7144 		goto exit;
7145 	}
7146 
7147 	/*
7148 	 * This will only work on variable record length tapes
7149 	 * if and only if all variable record length tapes autodensity
7150 	 * select.
7151 	 */
7152 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
7153 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
7154 
7155 	/*
7156 	 * Start at the specified density
7157 	 */
7158 
7159 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
7160 
7161 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
7162 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
7163 		/*
7164 		 * If we've done this density before,
7165 		 * don't bother to do it again.
7166 		 */
7167 		dens = un->un_dp->densities[un->un_curdens];
7168 		if (i > 0 && dens == olddens)
7169 			continue;
7170 		olddens = dens;
7171 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7172 		    "trying density 0x%x\n", dens);
7173 		if (st_set_density(un)) {
7174 			continue;
7175 		}
7176 
7177 		/*
7178 		 * XXX - the creates lots of headaches and slowdowns - must
7179 		 * fix.
7180 		 */
7181 		succes = (st_cmd(un, SCMD_READ, (int)size, SYNC_CMD) == 0);
7182 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
7183 			break;
7184 		}
7185 		if (succes) {
7186 			st_init(un);
7187 			rval = 0;
7188 			un->un_density_known = 1;
7189 			break;
7190 		}
7191 	}
7192 	kmem_free(un->un_tmpbuf, size);
7193 	un->un_tmpbuf = 0;
7194 
7195 exit:
7196 	ASSERT(mutex_owned(ST_MUTEX));
7197 	return (rval);
7198 }
7199 
7200 static int
7201 st_set_density(struct scsi_tape *un)
7202 {
7203 	int rval = 0;
7204 
7205 	ST_FUNC(ST_DEVINFO, st_set_density);
7206 
7207 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7208 	    "st_set_density(un = 0x%p): density = 0x%x\n", (void*)un,
7209 	    un->un_dp->densities[un->un_curdens]);
7210 
7211 	ASSERT(mutex_owned(ST_MUTEX));
7212 
7213 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7214 
7215 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
7216 		/*
7217 		 * If auto density override is not set, Use mode select
7218 		 * to set density and compression.
7219 		 */
7220 		if (st_modeselect(un)) {
7221 			rval = -1;
7222 		}
7223 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
7224 		/*
7225 		 * If auto density and mode select compression are set,
7226 		 * This is a drive with one density code but compression
7227 		 * can be enabled or disabled.
7228 		 * Set compression but no need to set density.
7229 		 */
7230 		rval = st_set_compression(un);
7231 		if ((rval != 0) && (rval != EALREADY)) {
7232 			rval = -1;
7233 		} else {
7234 			rval = 0;
7235 		}
7236 	}
7237 
7238 	/* If sucessful set density and/or compression, mark density known */
7239 	if (rval == 0) {
7240 		un->un_density_known = 1;
7241 	}
7242 
7243 	ASSERT(mutex_owned(ST_MUTEX));
7244 	return (rval);
7245 }
7246 
7247 static int
7248 st_loadtape(struct scsi_tape *un)
7249 {
7250 	int rval;
7251 
7252 	ST_FUNC(ST_DEVINFO, st_loadtape);
7253 
7254 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7255 	    "st_loadtape(un = 0x%p)\n", (void*) un);
7256 
7257 	ASSERT(mutex_owned(ST_MUTEX));
7258 
7259 	rval = st_update_block_pos(un, st_cmd, 0);
7260 	if (rval == EACCES) {
7261 		return (rval);
7262 	}
7263 
7264 	/*
7265 	 * 'LOAD' the tape to BOT by rewinding
7266 	 */
7267 	rval = st_cmd(un, SCMD_REWIND, 1, SYNC_CMD);
7268 	if (rval == 0) {
7269 		st_init(un);
7270 		un->un_density_known = 0;
7271 	}
7272 
7273 	ASSERT(mutex_owned(ST_MUTEX));
7274 	return (rval);
7275 }
7276 
7277 
7278 /*
7279  * Note: QIC devices aren't so smart.  If you try to append
7280  * after EOM, the write can fail because the device doesn't know
7281  * it's at EOM.	 In that case, issue a read.  The read should fail
7282  * because there's no data, but the device knows it's at EOM,
7283  * so a subsequent write should succeed.  To further confuse matters,
7284  * the target returns the same error if the tape is positioned
7285  * such that a write would overwrite existing data.  That's why
7286  * we have to do the append test.  A read in the middle of
7287  * recorded data would succeed, thus indicating we're attempting
7288  * something illegal.
7289  */
7290 
7291 
7292 static void
7293 st_test_append(struct buf *bp)
7294 {
7295 	dev_t dev = bp->b_edev;
7296 	struct scsi_tape *un;
7297 	uchar_t status;
7298 	unsigned bcount;
7299 
7300 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7301 
7302 	ST_FUNC(ST_DEVINFO, st_test_append);
7303 
7304 	ASSERT(mutex_owned(ST_MUTEX));
7305 
7306 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7307 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7308 
7309 	un->un_laststate = un->un_state;
7310 	un->un_state = ST_STATE_APPEND_TESTING;
7311 	un->un_test_append = 0;
7312 
7313 	/*
7314 	 * first, map in the buffer, because we're doing a double write --
7315 	 * first into the kernel, then onto the tape.
7316 	 */
7317 	bp_mapin(bp);
7318 
7319 	/*
7320 	 * get a copy of the data....
7321 	 */
7322 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7323 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7324 
7325 	/*
7326 	 * attempt the write..
7327 	 */
7328 
7329 	if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7330 success:
7331 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7332 		    "append write succeeded\n");
7333 		bp->b_resid = un->un_sbufp->b_resid;
7334 		mutex_exit(ST_MUTEX);
7335 		bcount = (unsigned)bp->b_bcount;
7336 		biodone(bp);
7337 		mutex_enter(ST_MUTEX);
7338 		un->un_laststate = un->un_state;
7339 		un->un_state = ST_STATE_OPEN;
7340 		kmem_free(un->un_tmpbuf, bcount);
7341 		un->un_tmpbuf = NULL;
7342 		return;
7343 	}
7344 
7345 	/*
7346 	 * The append failed. Do a short read. If that fails,  we are at EOM
7347 	 * so we can retry the write command. If that succeeds, than we're
7348 	 * all screwed up (the controller reported a real error).
7349 	 *
7350 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7351 	 * XXX: block size?
7352 	 *
7353 	 */
7354 	status = un->un_status;
7355 	un->un_status = 0;
7356 	(void) st_cmd(un, SCMD_READ, SECSIZE, SYNC_CMD);
7357 	if (un->un_status == KEY_BLANK_CHECK) {
7358 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7359 		    "append at EOM\n");
7360 		/*
7361 		 * Okay- the read failed. We should actually have confused
7362 		 * the controller enough to allow writing. In any case, the
7363 		 * i/o is on its own from here on out.
7364 		 */
7365 		un->un_laststate = un->un_state;
7366 		un->un_state = ST_STATE_OPEN;
7367 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7368 		if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount,
7369 		    SYNC_CMD) == 0) {
7370 			goto success;
7371 		}
7372 	}
7373 
7374 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7375 	    "append write failed- not at EOM\n");
7376 	bp->b_resid = bp->b_bcount;
7377 	st_bioerror(bp, EIO);
7378 
7379 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7380 	    "st_test_append : EIO : append write failed - not at EOM");
7381 
7382 	/*
7383 	 * backspace one record to get back to where we were
7384 	 */
7385 	if (st_cmd(un, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7386 		un->un_pos.pmode = invalid;
7387 	}
7388 
7389 	un->un_err_resid = bp->b_resid;
7390 	un->un_status = status;
7391 
7392 	/*
7393 	 * Note: biodone will do a bp_mapout()
7394 	 */
7395 	mutex_exit(ST_MUTEX);
7396 	bcount = (unsigned)bp->b_bcount;
7397 	biodone(bp);
7398 	mutex_enter(ST_MUTEX);
7399 	un->un_laststate = un->un_state;
7400 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7401 	kmem_free(un->un_tmpbuf, bcount);
7402 	un->un_tmpbuf = NULL;
7403 }
7404 
7405 /*
7406  * Special command handler
7407  */
7408 
7409 /*
7410  * common st_cmd code. The fourth parameter states
7411  * whether the caller wishes to await the results
7412  * Note the release of the mutex during most of the function
7413  */
7414 static int
7415 st_cmd(struct scsi_tape *un, int com, int64_t count, int wait)
7416 {
7417 	struct buf *bp;
7418 	int err;
7419 
7420 	ST_FUNC(ST_DEVINFO, st_cmd);
7421 
7422 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7423 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %"PRIx64", wait = %d)\n",
7424 	    un->un_dev, com, count, wait);
7425 
7426 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7427 	ASSERT(mutex_owned(ST_MUTEX));
7428 
7429 #ifdef STDEBUG
7430 	if ((st_debug & 0x7)) {
7431 		st_debug_cmds(un, com, count, wait);
7432 	}
7433 #endif
7434 
7435 	st_wait_for_io(un);
7436 
7437 	/* check to see if this command requires the drive to be reserved */
7438 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7439 
7440 	if (err) {
7441 		return (err);
7442 	}
7443 
7444 	/*
7445 	 * A space command is not recoverable if we don't know were we
7446 	 * were when it was issued.
7447 	 */
7448 	if ((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) {
7449 		(void) st_update_block_pos(un, st_cmd, 0);
7450 	}
7451 
7452 	/*
7453 	 * Forground should not be doing anything while recovery is active.
7454 	 */
7455 	ASSERT(un->un_recov_buf_busy == 0);
7456 
7457 	while (un->un_sbuf_busy)
7458 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7459 	un->un_sbuf_busy = 1;
7460 
7461 	bp = un->un_sbufp;
7462 	bzero(bp, sizeof (buf_t));
7463 
7464 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7465 
7466 	err = st_setup_cmd(un, bp, com, count);
7467 
7468 	un->un_sbuf_busy = 0;
7469 
7470 	/*
7471 	 * If was a space command need to update logical block position.
7472 	 * Only do this if the command was sucessful or it will mask the fact
7473 	 * that the space command failed by promoting the pmode to logical.
7474 	 */
7475 	if (((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) &&
7476 	    (un->un_pos.pmode != invalid)) {
7477 		un->un_running.pmode = invalid;
7478 		(void) st_update_block_pos(un, st_cmd, 1);
7479 		/*
7480 		 * Set running position to invalid so it updates on the
7481 		 * next command.
7482 		 */
7483 		un->un_running.pmode = invalid;
7484 	}
7485 
7486 	cv_signal(&un->un_sbuf_cv);
7487 
7488 	return (err);
7489 }
7490 
7491 static int
7492 st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com, int64_t count)
7493 {
7494 	int err;
7495 	dev_t dev = un->un_dev;
7496 
7497 	ST_FUNC(ST_DEVINFO, st_setup_cmd);
7498 	/*
7499 	 * Set count to the actual size of the data tranfer.
7500 	 * For commands with no data transfer, set bp->b_bcount
7501 	 * to the value to be used when constructing the
7502 	 * cdb in st_make_cmd().
7503 	 */
7504 	switch (com) {
7505 	case SCMD_READ:
7506 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7507 		    "special read %"PRId64"\n", count);
7508 		bp->b_flags |= B_READ;
7509 		bp->b_un.b_addr = un->un_tmpbuf;
7510 		break;
7511 
7512 	case SCMD_WRITE:
7513 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7514 		    "special write %"PRId64"\n", count);
7515 		bp->b_un.b_addr = un->un_tmpbuf;
7516 		break;
7517 
7518 	case SCMD_WRITE_FILE_MARK:
7519 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7520 		    "write %"PRId64" file marks\n", count);
7521 		bp->b_bcount = count;
7522 		count = 0;
7523 		break;
7524 
7525 	case SCMD_REWIND:
7526 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7527 		bp->b_bcount = count;
7528 		count = 0;
7529 		break;
7530 
7531 	case SCMD_SPACE:
7532 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7533 		/*
7534 		 * If the user could have entered a number that will
7535 		 * not fit in the 12 bit count field of space(8),
7536 		 * use space(16).
7537 		 */
7538 		if (((int64_t)SPACE_CNT(count) > 0x7fffff) ||
7539 		    ((int64_t)SPACE_CNT(count) < -(0x7fffff))) {
7540 			com = SCMD_SPACE_G4;
7541 		}
7542 		bp->b_bcount = count;
7543 		count = 0;
7544 		break;
7545 
7546 	case SCMD_RESERVE:
7547 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7548 		bp->b_bcount = 0;
7549 		count = 0;
7550 		break;
7551 
7552 	case SCMD_RELEASE:
7553 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7554 		bp->b_bcount = 0;
7555 		count = 0;
7556 		break;
7557 
7558 	case SCMD_LOAD:
7559 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7560 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7561 		bp->b_bcount = count;
7562 		count = 0;
7563 		break;
7564 
7565 	case SCMD_ERASE:
7566 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7567 		    "erase tape\n");
7568 		bp->b_bcount = count;
7569 		count = 0;
7570 		break;
7571 
7572 	case SCMD_MODE_SENSE:
7573 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7574 		    "mode sense\n");
7575 		bp->b_flags |= B_READ;
7576 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7577 		break;
7578 
7579 	case SCMD_MODE_SELECT:
7580 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7581 		    "mode select\n");
7582 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7583 		break;
7584 
7585 	case SCMD_READ_BLKLIM:
7586 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7587 		    "read block limits\n");
7588 		bp->b_bcount = count;
7589 		bp->b_flags |= B_READ;
7590 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7591 		break;
7592 
7593 	case SCMD_TEST_UNIT_READY:
7594 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7595 		    "test unit ready\n");
7596 		bp->b_bcount = 0;
7597 		count = 0;
7598 		break;
7599 
7600 	case SCMD_DOORLOCK:
7601 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7602 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7603 		bp->b_bcount = count = 0;
7604 		break;
7605 
7606 	case SCMD_READ_POSITION:
7607 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7608 		    "read position\n");
7609 		switch (un->un_read_pos_type) {
7610 		case LONG_POS:
7611 			count = sizeof (tape_position_long_t);
7612 			break;
7613 		case EXT_POS:
7614 			count = min(count, sizeof (tape_position_ext_t));
7615 			break;
7616 		case SHORT_POS:
7617 			count = sizeof (tape_position_t);
7618 			break;
7619 		default:
7620 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7621 			    "Unknown read position type 0x%x in "
7622 			    "st_make_cmd()\n", un->un_read_pos_type);
7623 		}
7624 		bp->b_bcount = count;
7625 		bp->b_flags |= B_READ;
7626 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7627 		break;
7628 
7629 	default:
7630 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7631 		    "Unhandled scsi command 0x%x in st_setup_cmd()\n", com);
7632 	}
7633 
7634 	mutex_exit(ST_MUTEX);
7635 
7636 	if (count > 0) {
7637 		int flg = (bp->b_flags & B_READ) ? B_READ : B_WRITE;
7638 		/*
7639 		 * We're going to do actual I/O.
7640 		 * Set things up for physio.
7641 		 */
7642 		struct iovec aiov;
7643 		struct uio auio;
7644 		struct uio *uio = &auio;
7645 
7646 		bzero(&auio, sizeof (struct uio));
7647 		bzero(&aiov, sizeof (struct iovec));
7648 		aiov.iov_base = bp->b_un.b_addr;
7649 		aiov.iov_len = count;
7650 
7651 		uio->uio_iov = &aiov;
7652 		uio->uio_iovcnt = 1;
7653 		uio->uio_resid = aiov.iov_len;
7654 		uio->uio_segflg = UIO_SYSSPACE;
7655 
7656 		/*
7657 		 * Let physio do the rest...
7658 		 */
7659 		bp->b_forw = (struct buf *)(uintptr_t)com;
7660 		bp->b_back = NULL;
7661 		err = physio(st_strategy, bp, dev, flg, st_minphys, uio);
7662 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7663 		    "st_setup_cmd: physio returns %d\n", err);
7664 	} else {
7665 		/*
7666 		 * Mimic physio
7667 		 */
7668 		bp->b_forw = (struct buf *)(uintptr_t)com;
7669 		bp->b_back = NULL;
7670 		bp->b_edev = dev;
7671 		bp->b_dev = cmpdev(dev);
7672 		bp->b_blkno = 0;
7673 		bp->b_resid = 0;
7674 		(void) st_strategy(bp);
7675 		if (bp->b_flags & B_ASYNC) {
7676 			/*
7677 			 * This is an async command- the caller won't wait
7678 			 * and doesn't care about errors.
7679 			 */
7680 			mutex_enter(ST_MUTEX);
7681 			return (0);
7682 		}
7683 
7684 		/*
7685 		 * BugTraq #4260046
7686 		 * ----------------
7687 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7688 		 * unconditionally. The old comment said...
7689 		 *
7690 		 * "if strategy was flagged with  persistent errors, we would
7691 		 *  have an error here, and the bp would never be sent, so we
7692 		 *  don't want to wait on a bp that was never sent...or hang"
7693 		 *
7694 		 * The new rationale, courtesy of Chitrank...
7695 		 *
7696 		 * "we should unconditionally biowait() here because
7697 		 *  st_strategy() will do a biodone() in the persistent error
7698 		 *  case and the following biowait() will return immediately.
7699 		 *  If not, in the case of "errors after pkt alloc" in
7700 		 *  st_start(), we will not biowait here which will cause the
7701 		 *  next biowait() to return immediately which will cause
7702 		 *  us to send out the next command. In the case where both of
7703 		 *  these use the sbuf, when the first command completes we'll
7704 		 *  free the packet attached to sbuf and the same pkt will
7705 		 *  get freed again when we complete the second command.
7706 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7707 		 *  st_start() for the pkt alloc failure case because physio()
7708 		 *  does biowait() and will hang if we don't do biodone()"
7709 		 */
7710 
7711 		err = biowait(bp);
7712 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7713 		    "st_setup_cmd: biowait returns %d\n", err);
7714 	}
7715 
7716 	mutex_enter(ST_MUTEX);
7717 
7718 	return (err);
7719 }
7720 
7721 static int
7722 st_set_compression(struct scsi_tape *un)
7723 {
7724 	int rval;
7725 	int turn_compression_on;
7726 	minor_t minor;
7727 
7728 	ST_FUNC(ST_DEVINFO, st_set_compression);
7729 
7730 	/*
7731 	 * Drive either dosn't have compression or it is controlled with
7732 	 * special density codes. Return ENOTTY so caller
7733 	 * knows nothing was done.
7734 	 */
7735 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7736 		un->un_comp_page = 0;
7737 		return (ENOTTY);
7738 	}
7739 
7740 	/* set compression based on minor node opened */
7741 	minor = MT_DENSITY(un->un_dev);
7742 
7743 	/*
7744 	 * If this the compression density or
7745 	 * the drive has two densities and uses mode select for
7746 	 * control of compression turn on compression for MT_DENSITY2
7747 	 * as well.
7748 	 */
7749 	if ((minor == ST_COMPRESSION_DENSITY) ||
7750 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7751 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7752 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7753 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7754 
7755 		turn_compression_on = 1;
7756 	} else {
7757 		turn_compression_on = 0;
7758 	}
7759 
7760 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7761 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7762 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7763 
7764 	/*
7765 	 * Need to determine which page does the device use for compression.
7766 	 * First try the data compression page. If this fails try the device
7767 	 * configuration page
7768 	 */
7769 
7770 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7771 		rval = st_set_datacomp_page(un, turn_compression_on);
7772 		if (rval == EALREADY) {
7773 			return (rval);
7774 		}
7775 		if (rval != 0) {
7776 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7777 				/*
7778 				 * This device does not support data
7779 				 * compression page
7780 				 */
7781 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7782 			} else if (un->un_state >= ST_STATE_OPEN) {
7783 				un->un_pos.pmode = invalid;
7784 				rval = EIO;
7785 			} else {
7786 				rval = -1;
7787 			}
7788 		} else {
7789 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7790 		}
7791 	}
7792 
7793 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7794 		rval = st_set_devconfig_page(un, turn_compression_on);
7795 		if (rval == EALREADY) {
7796 			return (rval);
7797 		}
7798 		if (rval != 0) {
7799 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7800 				/*
7801 				 * This device does not support
7802 				 * compression at all advice the
7803 				 * user and unset ST_MODE_SEL_COMP
7804 				 */
7805 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7806 				un->un_comp_page = 0;
7807 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7808 				    "Device Does Not Support Compression\n");
7809 			} else if (un->un_state >= ST_STATE_OPEN) {
7810 				un->un_pos.pmode = invalid;
7811 				rval = EIO;
7812 			} else {
7813 				rval = -1;
7814 			}
7815 		}
7816 	}
7817 
7818 	return (rval);
7819 }
7820 
7821 /*
7822  * set or unset compression thru device configuration page.
7823  */
7824 static int
7825 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
7826 {
7827 	unsigned char cflag;
7828 	int rval = 0;
7829 
7830 
7831 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
7832 
7833 	ASSERT(mutex_owned(ST_MUTEX));
7834 	/*
7835 	 * Figure what to set compression flag to.
7836 	 */
7837 	if (compression_on) {
7838 		/* They have selected a compression node */
7839 		if (un->un_dp->type == ST_TYPE_FUJI) {
7840 			cflag = 0x84;   /* use EDRC */
7841 		} else {
7842 			cflag = ST_DEV_CONFIG_DEF_COMP;
7843 		}
7844 	} else {
7845 		cflag = ST_DEV_CONFIG_NO_COMP;
7846 	}
7847 
7848 	/*
7849 	 * If compression is already set the way it was requested.
7850 	 * And if this not the first time we has tried.
7851 	 */
7852 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
7853 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7854 		return (EALREADY);
7855 	}
7856 
7857 	un->un_mspl->page.dev.comp_alg = cflag;
7858 	/*
7859 	 * need to send mode select even if correct compression is
7860 	 * already set since need to set density code
7861 	 */
7862 
7863 #ifdef STDEBUG
7864 	if ((st_debug & 0x7) >= 6) {
7865 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7866 		    "st_set_devconfig_page: sense data for mode select",
7867 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7868 	}
7869 #endif
7870 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
7871 	    sizeof (struct seq_mode));
7872 
7873 	return (rval);
7874 }
7875 
7876 /*
7877  * set/reset compression bit thru data compression page
7878  */
7879 static int
7880 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
7881 {
7882 	int compression_on_already;
7883 	int rval = 0;
7884 
7885 
7886 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
7887 
7888 	ASSERT(mutex_owned(ST_MUTEX));
7889 	/*
7890 	 * If drive is not capable of compression (at this time)
7891 	 * return EALREADY so caller doesn't think that this page
7892 	 * is not supported. This check is for drives that can
7893 	 * disable compression from the front panel or configuration.
7894 	 * I doubt that a drive that supports this page is not really
7895 	 * capable of compression.
7896 	 */
7897 	if (un->un_mspl->page.comp.dcc == 0) {
7898 		return (EALREADY);
7899 	}
7900 
7901 	/* See if compression currently turned on */
7902 	if (un->un_mspl->page.comp.dce) {
7903 		compression_on_already = 1;
7904 	} else {
7905 		compression_on_already = 0;
7906 	}
7907 
7908 	/*
7909 	 * If compression is already set the way it was requested.
7910 	 * And if this not the first time we has tried.
7911 	 */
7912 	if ((compression_on == compression_on_already) &&
7913 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7914 		return (EALREADY);
7915 	}
7916 
7917 	/*
7918 	 * if we are already set to the appropriate compression
7919 	 * mode, don't set it again
7920 	 */
7921 	if (compression_on) {
7922 		/* compression selected */
7923 		un->un_mspl->page.comp.dce = 1;
7924 	} else {
7925 		un->un_mspl->page.comp.dce = 0;
7926 	}
7927 
7928 
7929 #ifdef STDEBUG
7930 	if ((st_debug & 0x7) >= 6) {
7931 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7932 		    "st_set_datacomp_page: sense data for mode select",
7933 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7934 	}
7935 #endif
7936 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
7937 	    sizeof (struct seq_mode));
7938 
7939 	return (rval);
7940 }
7941 
7942 static int
7943 st_modesense(struct scsi_tape *un)
7944 {
7945 	int rval;
7946 	uchar_t page;
7947 
7948 	ST_FUNC(ST_DEVINFO, st_modesense);
7949 
7950 	page = un->un_comp_page;
7951 
7952 	switch (page) {
7953 	case ST_DEV_DATACOMP_PAGE:
7954 	case ST_DEV_CONFIG_PAGE: /* FALLTHROUGH */
7955 		rval = st_gen_mode_sense(un, st_uscsi_cmd, page, un->un_mspl,
7956 		    sizeof (struct seq_mode));
7957 		break;
7958 
7959 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
7960 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
7961 			page = ST_DEV_CONFIG_PAGE;
7962 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
7963 			    un->un_mspl, sizeof (struct seq_mode));
7964 			if (rval == 0 && un->un_mspl->page_code == page) {
7965 				un->un_comp_page = page;
7966 				break;
7967 			}
7968 			page = ST_DEV_DATACOMP_PAGE;
7969 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
7970 			    un->un_mspl, sizeof (struct seq_mode));
7971 			if (rval == 0 && un->un_mspl->page_code == page) {
7972 				un->un_comp_page = page;
7973 				break;
7974 			}
7975 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
7976 			un->un_comp_page = 0;
7977 		} else {
7978 			un->un_comp_page = 0;
7979 		}
7980 
7981 	default:	/* FALLTHROUGH */
7982 		rval = st_cmd(un, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
7983 	}
7984 	return (rval);
7985 }
7986 
7987 static int
7988 st_modeselect(struct scsi_tape *un)
7989 {
7990 	int rval = 0;
7991 	int ix;
7992 
7993 	ST_FUNC(ST_DEVINFO, st_modeselect);
7994 
7995 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7996 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
7997 	    un->un_dev, un->un_mspl->density);
7998 
7999 	ASSERT(mutex_owned(ST_MUTEX));
8000 
8001 	/*
8002 	 * The parameter list should be the same for all of the
8003 	 * cases that follow so set them here
8004 	 *
8005 	 * Try mode select first if if fails set fields manually
8006 	 */
8007 	rval = st_modesense(un);
8008 	if (rval != 0) {
8009 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8010 		    "st_modeselect: First mode sense failed\n");
8011 		un->un_mspl->bd_len  = 8;
8012 		un->un_mspl->high_nb = 0;
8013 		un->un_mspl->mid_nb  = 0;
8014 		un->un_mspl->low_nb  = 0;
8015 	}
8016 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
8017 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
8018 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
8019 
8020 
8021 	/*
8022 	 * If configured to use a specific density code for a media type.
8023 	 * curdens is previously set by the minor node opened.
8024 	 * If the media type doesn't match the minor node we change it so it
8025 	 * looks like the correct one was opened.
8026 	 */
8027 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
8028 		uchar_t best;
8029 
8030 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
8031 			if (un->un_mspl->media_type ==
8032 			    un->un_dp->mediatype[ix]) {
8033 				best = ix;
8034 				/*
8035 				 * It matches but it might not be the only one.
8036 				 * Use the highest matching media type but not
8037 				 * to exceed the density selected by the open.
8038 				 */
8039 				if (ix < un->un_curdens) {
8040 					continue;
8041 				}
8042 				un->un_curdens = ix;
8043 				break;
8044 			}
8045 		}
8046 		/* If a match was found best will not be 0xff any more */
8047 		if (best < NDENSITIES) {
8048 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8049 			    "found media 0x%X using density 0x%X\n",
8050 			    un->un_mspl->media_type,
8051 			    un->un_dp->densities[best]);
8052 			un->un_mspl->density = un->un_dp->densities[best];
8053 		} else {
8054 			/* Otherwise set density based on minor node opened */
8055 			un->un_mspl->density =
8056 			    un->un_dp->densities[un->un_curdens];
8057 		}
8058 	} else {
8059 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
8060 	}
8061 
8062 	if (un->un_dp->options & ST_NOBUF) {
8063 		un->un_mspl->bufm = 0;
8064 	} else {
8065 		un->un_mspl->bufm = 1;
8066 	}
8067 
8068 	rval = st_set_compression(un);
8069 
8070 	/*
8071 	 * If st_set_compression returned invalid or already it
8072 	 * found no need to do the mode select.
8073 	 * So do it here.
8074 	 */
8075 	if ((rval == ENOTTY) || (rval == EALREADY)) {
8076 
8077 		/* Zero non-writeable fields */
8078 		un->un_mspl->data_len = 0;
8079 		un->un_mspl->media_type = 0;
8080 		un->un_mspl->wp = 0;
8081 
8082 		/* need to set the density code */
8083 		rval = st_cmd(un, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
8084 		if (rval != 0) {
8085 			if (un->un_state >= ST_STATE_OPEN) {
8086 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8087 				    "unable to set tape mode\n");
8088 				un->un_pos.pmode = invalid;
8089 				rval = EIO;
8090 			} else {
8091 				rval = -1;
8092 			}
8093 		}
8094 	}
8095 
8096 	/*
8097 	 * The spec recommends to send a mode sense after a mode select
8098 	 */
8099 	(void) st_modesense(un);
8100 
8101 	ASSERT(mutex_owned(ST_MUTEX));
8102 
8103 	return (rval);
8104 }
8105 
8106 /*
8107  * st_gen_mode_sense
8108  *
8109  * generic mode sense.. it allows for any page
8110  */
8111 static int
8112 st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
8113     struct seq_mode *page_data, int page_size)
8114 {
8115 
8116 	int r;
8117 	char	cdb[CDB_GROUP0];
8118 	struct uscsi_cmd *com;
8119 
8120 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
8121 
8122 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8123 
8124 	bzero(cdb, CDB_GROUP0);
8125 	cdb[0] = SCMD_MODE_SENSE;
8126 	cdb[2] = (char)page;
8127 	cdb[4] = (char)page_size;
8128 
8129 	com->uscsi_cdb = cdb;
8130 	com->uscsi_cdblen = CDB_GROUP0;
8131 	com->uscsi_bufaddr = (caddr_t)page_data;
8132 	com->uscsi_buflen = page_size;
8133 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8134 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8135 
8136 	r = ubf(un, com, FKIOCTL);
8137 	kmem_free(com, sizeof (*com));
8138 	return (r);
8139 }
8140 
8141 /*
8142  * st_gen_mode_select
8143  *
8144  * generic mode select.. it allows for any page
8145  */
8146 static int
8147 st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
8148     struct seq_mode *page_data, int page_size)
8149 {
8150 
8151 	int r;
8152 	char cdb[CDB_GROUP0];
8153 	struct uscsi_cmd *com;
8154 
8155 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
8156 
8157 	/* Zero non-writeable fields */
8158 	page_data->data_len = 0;
8159 	page_data->media_type = 0;
8160 	page_data->wp = 0;
8161 
8162 	/*
8163 	 * If mode select has any page data, zero the ps (Page Savable) bit.
8164 	 */
8165 	if (page_size > MSIZE) {
8166 		page_data->ps = 0;
8167 	}
8168 
8169 
8170 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8171 
8172 	/*
8173 	 * then, do a mode select to set what ever info
8174 	 */
8175 	bzero(cdb, CDB_GROUP0);
8176 	cdb[0] = SCMD_MODE_SELECT;
8177 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
8178 	cdb[4] = (char)page_size;
8179 
8180 	com->uscsi_cdb = cdb;
8181 	com->uscsi_cdblen = CDB_GROUP0;
8182 	com->uscsi_bufaddr = (caddr_t)page_data;
8183 	com->uscsi_buflen = page_size;
8184 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8185 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_WRITE;
8186 
8187 	r = ubf(un, com, FKIOCTL);
8188 
8189 	kmem_free(com, sizeof (*com));
8190 	return (r);
8191 }
8192 
8193 static int
8194 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
8195 {
8196 	int rval;
8197 	char cdb[CDB_GROUP0];
8198 	struct uscsi_cmd *com;
8199 
8200 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
8201 
8202 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8203 
8204 	bzero(cdb, CDB_GROUP0);
8205 	cdb[0] = SCMD_READ_BLKLIM;
8206 
8207 	com->uscsi_cdb = cdb;
8208 	com->uscsi_cdblen = CDB_GROUP0;
8209 	com->uscsi_bufaddr = (caddr_t)read_blk;
8210 	com->uscsi_buflen = sizeof (struct read_blklim);
8211 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8212 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8213 
8214 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8215 	if (com->uscsi_status || com->uscsi_resid) {
8216 		rval = -1;
8217 	}
8218 
8219 	kmem_free(com, sizeof (*com));
8220 	return (rval);
8221 }
8222 
8223 static int
8224 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
8225     size_t buflen)
8226 {
8227 	int rval;
8228 	char cdb[CDB_GROUP1];
8229 	struct uscsi_cmd *com;
8230 
8231 	ST_FUNC(ST_DEVINFO, st_report_density_support);
8232 
8233 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8234 
8235 	bzero(cdb, CDB_GROUP1);
8236 	cdb[0] = SCMD_REPORT_DENSITIES;
8237 	cdb[7] = (buflen & 0xff00) >> 8;
8238 	cdb[8] = buflen & 0xff;
8239 
8240 	com->uscsi_cdb = cdb;
8241 	com->uscsi_cdblen = CDB_GROUP1;
8242 	com->uscsi_bufaddr = (caddr_t)density_data;
8243 	com->uscsi_buflen = buflen;
8244 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8245 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8246 
8247 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8248 	if (com->uscsi_status || com->uscsi_resid) {
8249 		rval = -1;
8250 	}
8251 
8252 	kmem_free(com, sizeof (*com));
8253 	return (rval);
8254 }
8255 
8256 static int
8257 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
8258     uchar_t option_code, ushort_t service_action)
8259 {
8260 	int rval;
8261 	char cdb[CDB_GROUP5];
8262 	struct uscsi_cmd *com;
8263 	uint32_t allo_length;
8264 
8265 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
8266 
8267 	allo_length = sizeof (struct one_com_des) +
8268 	    sizeof (struct com_timeout_des);
8269 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8270 
8271 	bzero(cdb, CDB_GROUP5);
8272 	cdb[0] = (char)SCMD_MAINTENANCE_IN;
8273 	cdb[1] = 0x0c; /* service action */
8274 	if (service_action) {
8275 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
8276 		cdb[4] = (service_action & 0xff00) >> 8;
8277 		cdb[5] = service_action & 0xff;
8278 	} else {
8279 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
8280 		    0x80); /* RCTD */
8281 	}
8282 	cdb[3] = option_code;
8283 	cdb[6] = (allo_length & 0xff000000) >> 24;
8284 	cdb[7] = (allo_length & 0xff0000) >> 16;
8285 	cdb[8] = (allo_length & 0xff00) >> 8;
8286 	cdb[9] = allo_length & 0xff;
8287 
8288 	com->uscsi_cdb = cdb;
8289 	com->uscsi_cdblen = CDB_GROUP5;
8290 	com->uscsi_bufaddr = (caddr_t)oper_data;
8291 	com->uscsi_buflen = allo_length;
8292 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8293 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8294 
8295 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8296 	if (com->uscsi_status) {
8297 		rval = -1;
8298 	}
8299 
8300 	kmem_free(com, sizeof (*com));
8301 	return (rval);
8302 }
8303 
8304 /*
8305  * Changes devices blocksize and bsize to requested blocksize nblksz.
8306  * Returns returned value from first failed call or zero on success.
8307  */
8308 static int
8309 st_change_block_size(struct scsi_tape *un, uint32_t nblksz)
8310 {
8311 	struct seq_mode *current;
8312 	int rval;
8313 	uint32_t oldblksz;
8314 
8315 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8316 
8317 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8318 
8319 	current = kmem_zalloc(MSIZE, KM_SLEEP);
8320 
8321 	/*
8322 	 * If we haven't got the compression page yet, do that first.
8323 	 */
8324 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
8325 		(void) st_modesense(un);
8326 	}
8327 
8328 	/* Read current settings */
8329 	rval = st_gen_mode_sense(un, st_uscsi_cmd, 0, current, MSIZE);
8330 	if (rval != 0) {
8331 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8332 		    "mode sense for change block size failed: rval = %d", rval);
8333 		goto finish;
8334 	}
8335 
8336 	/* Figure the current block size */
8337 	oldblksz =
8338 	    (current->high_bl << 16) |
8339 	    (current->mid_bl << 8) |
8340 	    (current->low_bl);
8341 
8342 	/* If current block size is the same as requested were done */
8343 	if (oldblksz == nblksz) {
8344 		un->un_bsize = nblksz;
8345 		rval = 0;
8346 		goto finish;
8347 	}
8348 
8349 	/* Change to requested block size */
8350 	current->high_bl = (uchar_t)(nblksz >> 16);
8351 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8352 	current->low_bl  = (uchar_t)(nblksz);
8353 
8354 	/* Attempt to change block size */
8355 	rval = st_gen_mode_select(un, st_uscsi_cmd, current, MSIZE);
8356 	if (rval != 0) {
8357 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8358 		    "Set new block size failed: rval = %d", rval);
8359 		goto finish;
8360 	}
8361 
8362 	/* Read back and verify setting */
8363 	rval = st_modesense(un);
8364 	if (rval == 0) {
8365 		un->un_bsize =
8366 		    (un->un_mspl->high_bl << 16) |
8367 		    (un->un_mspl->mid_bl << 8) |
8368 		    (un->un_mspl->low_bl);
8369 
8370 		if (un->un_bsize != nblksz) {
8371 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8372 			    "Blocksize set does not equal requested blocksize"
8373 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8374 			rval = EIO;
8375 		}
8376 	}
8377 finish:
8378 	kmem_free(current, MSIZE);
8379 	return (rval);
8380 }
8381 
8382 
8383 static void
8384 st_init(struct scsi_tape *un)
8385 {
8386 	ST_FUNC(ST_DEVINFO, st_init);
8387 
8388 	ASSERT(mutex_owned(ST_MUTEX));
8389 
8390 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8391 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8392 	    un->un_dev);
8393 
8394 	un->un_pos.blkno = 0;
8395 	un->un_pos.fileno = 0;
8396 	un->un_lastop = ST_OP_NIL;
8397 	un->un_pos.eof = ST_NO_EOF;
8398 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8399 	if (st_error_level != SCSI_ERR_ALL) {
8400 		if (DEBUGGING) {
8401 			st_error_level = SCSI_ERR_ALL;
8402 		} else {
8403 			st_error_level = SCSI_ERR_RETRYABLE;
8404 		}
8405 	}
8406 }
8407 
8408 
8409 static void
8410 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8411 {
8412 	struct scsi_pkt *pkt;
8413 	struct uscsi_cmd *ucmd;
8414 	recov_info *ri;
8415 	int tval = 0;
8416 	uint64_t count;
8417 	uint32_t additional;
8418 	int flags = 0;
8419 	int cdb_len = CDB_GROUP0; /* default */
8420 	uchar_t com;
8421 	char fixbit;
8422 	char short_fm = 0;
8423 	int stat_size =
8424 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
8425 
8426 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8427 
8428 	ASSERT(mutex_owned(ST_MUTEX));
8429 
8430 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8431 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8432 
8433 
8434 	/*
8435 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8436 	 * Length Indicator bits on read/write commands, for setting
8437 	 * the Long bit on erase commands, and for setting the Code
8438 	 * Field bits on space commands.
8439 	 */
8440 
8441 	/* regular raw I/O */
8442 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
8443 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8444 		    CDB_GROUP0, stat_size, st_recov_sz, 0, func,
8445 		    (caddr_t)un);
8446 		if (pkt == NULL) {
8447 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8448 			    "Read Write scsi_init_pkt() failure\n");
8449 			goto exit;
8450 		}
8451 		ASSERT(pkt->pkt_resid == 0);
8452 #ifdef STDEBUG
8453 		bzero(pkt->pkt_private, st_recov_sz);
8454 		bzero(pkt->pkt_scbp, stat_size);
8455 #endif
8456 		ri = (recov_info *)pkt->pkt_private;
8457 		ri->privatelen = st_recov_sz;
8458 		if (un->un_bsize == 0) {
8459 			count = bp->b_bcount;
8460 			fixbit = 0;
8461 		} else {
8462 			count = bp->b_bcount / un->un_bsize;
8463 			fixbit = 1;
8464 		}
8465 		if (bp->b_flags & B_READ) {
8466 			com = SCMD_READ;
8467 			un->un_lastop = ST_OP_READ;
8468 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8469 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8470 				fixbit = 2;
8471 			}
8472 		} else {
8473 			com = SCMD_WRITE;
8474 			un->un_lastop = ST_OP_WRITE;
8475 		}
8476 		tval = un->un_dp->io_timeout;
8477 
8478 		/*
8479 		 * For really large xfers, increase timeout
8480 		 */
8481 		if (bp->b_bcount > (10 * ONE_MEG))
8482 			tval *= bp->b_bcount/(10 * ONE_MEG);
8483 
8484 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8485 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8486 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8487 
8488 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8489 		/*
8490 		 * uscsi - build command, allocate scsi resources
8491 		 */
8492 		st_make_uscsi_cmd(un, ucmd, bp, func);
8493 		goto exit;
8494 
8495 	} else {				/* special I/O */
8496 		int stat_size = (un->un_arq_enabled ?
8497 		    sizeof (struct scsi_arq_status) : 1);
8498 		struct buf *allocbp = NULL;
8499 		com = (uchar_t)(uintptr_t)bp->b_forw;
8500 		count = bp->b_bcount;
8501 
8502 		switch (com) {
8503 		case SCMD_READ:
8504 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8505 			    "special read %"PRId64"\n", count);
8506 			if (un->un_bsize == 0) {
8507 				fixbit = 2;	/* suppress SILI */
8508 			} else {
8509 				fixbit = 1;	/* Fixed Block Mode */
8510 				count /= un->un_bsize;
8511 			}
8512 			allocbp = bp;
8513 			un->un_lastop = ST_OP_READ;
8514 			tval = un->un_dp->io_timeout;
8515 			break;
8516 
8517 		case SCMD_WRITE:
8518 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8519 			    "special write %"PRId64"\n", count);
8520 			if (un->un_bsize != 0) {
8521 				fixbit = 1;	/* Fixed Block Mode */
8522 				count /= un->un_bsize;
8523 			} else {
8524 				fixbit = 0;
8525 			}
8526 			allocbp = bp;
8527 			un->un_lastop = ST_OP_WRITE;
8528 			tval = un->un_dp->io_timeout;
8529 			break;
8530 
8531 		case SCMD_WRITE_FILE_MARK:
8532 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8533 			    "write %"PRId64" file marks\n", count);
8534 			un->un_lastop = ST_OP_WEOF;
8535 			fixbit = 0;
8536 			tval = un->un_dp->io_timeout;
8537 			/*
8538 			 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8539 			 * device, set the Vendor Unique bit to
8540 			 * write Short File Mark.
8541 			 */
8542 			if ((un->un_dp->options & ST_SHORT_FILEMARKS) &&
8543 			    ((un->un_dp->type == ST_TYPE_EXB8500) ||
8544 			    (un->un_dp->type == ST_TYPE_EXABYTE))) {
8545 				/*
8546 				 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8547 				 * is set to to write Short File Mark
8548 				 */
8549 				short_fm = 1;
8550 			}
8551 			break;
8552 
8553 		case SCMD_REWIND:
8554 			/*
8555 			 * In the case of rewind we're gona do the rewind with
8556 			 * the immediate bit set so status will be retured when
8557 			 * the command is accepted by the device. We clear the
8558 			 * B_ASYNC flag so we wait for that acceptance.
8559 			 */
8560 			if (bp->b_flags & B_ASYNC) {
8561 				allocbp = bp;
8562 				if (count) {
8563 					fixbit = 1;
8564 					bp->b_flags &= ~B_ASYNC;
8565 				}
8566 			} else {
8567 				fixbit = 0;
8568 			}
8569 			count = 0;
8570 			bp->b_bcount = 0;
8571 			un->un_lastop = ST_OP_CTL;
8572 			tval = un->un_dp->rewind_timeout;
8573 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8574 			    "rewind\n");
8575 			break;
8576 
8577 		case SCMD_SPACE_G4:
8578 			cdb_len = CDB_GROUP4;
8579 		case SCMD_SPACE: /* FALL THROUGH */
8580 			fixbit = SPACE_TYPE(bp->b_bcount);
8581 			count = SPACE_CNT(bp->b_bcount);
8582 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8583 			    " %s space %s %"PRId64" from file %d blk %d\n",
8584 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8585 			    space_strs[fixbit & 7], count,
8586 			    un->un_pos.fileno, un->un_pos.blkno);
8587 			additional = count >> 32;
8588 			count &= 0xffffffff;
8589 			un->un_lastop = ST_OP_CTL;
8590 			tval = un->un_dp->space_timeout;
8591 			break;
8592 
8593 		case SCMD_LOAD:
8594 			ASSERT(count < 10);
8595 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8596 			    "%s tape\n", load_strs[count]);
8597 			fixbit = 0;
8598 
8599 			/* Loading or Unloading */
8600 			if (count & LD_LOAD) {
8601 				tval = un->un_dp->load_timeout;
8602 			} else {
8603 				tval = un->un_dp->unload_timeout;
8604 			}
8605 			/* Is Retension requested */
8606 			if (count & LD_RETEN) {
8607 				tval += un->un_dp->rewind_timeout;
8608 			}
8609 			un->un_lastop = ST_OP_CTL;
8610 			break;
8611 
8612 		case SCMD_ERASE:
8613 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8614 			    "erase tape\n");
8615 			ASSERT(count == 1); /* mt sets this */
8616 			if (count == 1) {
8617 				/*
8618 				 * do long erase
8619 				 */
8620 				fixbit = 1; /* Long */
8621 
8622 				/* Drive might not honor immidiate bit */
8623 				tval = un->un_dp->erase_timeout;
8624 			} else {
8625 				/* Short Erase */
8626 				tval = un->un_dp->erase_timeout;
8627 				fixbit = 0;
8628 			}
8629 			un->un_lastop = ST_OP_CTL;
8630 			count = 0;
8631 			break;
8632 
8633 		case SCMD_MODE_SENSE:
8634 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8635 			    "mode sense\n");
8636 			allocbp = bp;
8637 			fixbit = 0;
8638 			tval = un->un_dp->non_motion_timeout;
8639 			un->un_lastop = ST_OP_CTL;
8640 			break;
8641 
8642 		case SCMD_MODE_SELECT:
8643 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8644 			    "mode select\n");
8645 			allocbp = bp;
8646 			fixbit = 0;
8647 			tval = un->un_dp->non_motion_timeout;
8648 			un->un_lastop = ST_OP_CTL;
8649 			break;
8650 
8651 		case SCMD_RESERVE:
8652 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8653 			    "reserve\n");
8654 			fixbit = 0;
8655 			tval = un->un_dp->non_motion_timeout;
8656 			un->un_lastop = ST_OP_CTL;
8657 			break;
8658 
8659 		case SCMD_RELEASE:
8660 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8661 			    "release\n");
8662 			fixbit = 0;
8663 			tval = un->un_dp->non_motion_timeout;
8664 			un->un_lastop = ST_OP_CTL;
8665 			break;
8666 
8667 		case SCMD_READ_BLKLIM:
8668 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8669 			    "read block limits\n");
8670 			allocbp = bp;
8671 			fixbit = count = 0;
8672 			tval = un->un_dp->non_motion_timeout;
8673 			un->un_lastop = ST_OP_CTL;
8674 			break;
8675 
8676 		case SCMD_TEST_UNIT_READY:
8677 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8678 			    "test unit ready\n");
8679 			fixbit = 0;
8680 			tval = un->un_dp->non_motion_timeout;
8681 			un->un_lastop = ST_OP_CTL;
8682 			break;
8683 
8684 		case SCMD_DOORLOCK:
8685 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8686 			    "prevent/allow media removal\n");
8687 			fixbit = 0;
8688 			tval = un->un_dp->non_motion_timeout;
8689 			un->un_lastop = ST_OP_CTL;
8690 			break;
8691 
8692 		case SCMD_READ_POSITION:
8693 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8694 			    "read position\n");
8695 			fixbit = un->un_read_pos_type;
8696 			cdb_len = CDB_GROUP1;
8697 			tval = un->un_dp->non_motion_timeout;
8698 			allocbp = bp;
8699 			un->un_lastop = ST_OP_CTL;
8700 			switch (un->un_read_pos_type) {
8701 			case LONG_POS:
8702 				count = 0;
8703 				break;
8704 			case EXT_POS:
8705 				count = sizeof (tape_position_ext_t);
8706 				break;
8707 			case SHORT_POS:
8708 				count = 0;
8709 				break;
8710 			default:
8711 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8712 				    "Unknown read position type 0x%x in "
8713 				    " st_make_cmd()\n", un->un_read_pos_type);
8714 			}
8715 			break;
8716 
8717 		default:
8718 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8719 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8720 			    com);
8721 		}
8722 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8723 		    st_recov_sz, 0, func, (caddr_t)un);
8724 		if (pkt == NULL) {
8725 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8726 			    "generic command scsi_init_pkt() failure\n");
8727 			goto exit;
8728 		}
8729 
8730 		ASSERT(pkt->pkt_resid == 0);
8731 #ifdef STDEBUG
8732 		bzero(pkt->pkt_private, st_recov_sz);
8733 		bzero(pkt->pkt_scbp, stat_size);
8734 #endif
8735 		ri = (recov_info *)pkt->pkt_private;
8736 		ri->privatelen = st_recov_sz;
8737 		if (allocbp) {
8738 			ASSERT(geterror(allocbp) == 0);
8739 		}
8740 
8741 	}
8742 
8743 
8744 	(void) scsi_setup_cdb((union scsi_cdb *)pkt->pkt_cdbp,
8745 	    com, 0, (uint_t)count, additional);
8746 	FILL_SCSI1_LUN(un->un_sd, pkt);
8747 	/*
8748 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8749 	 */
8750 	((union scsi_cdb *)(pkt->pkt_cdbp))->t_code = fixbit;
8751 	((union scsi_cdb *)pkt->pkt_cdbp)->g0_vu_1 = short_fm;
8752 	pkt->pkt_flags = flags;
8753 
8754 	ASSERT(tval);
8755 	pkt->pkt_time = tval;
8756 	if (bp == un->un_recov_buf) {
8757 		pkt->pkt_comp = st_recov_cb;
8758 	} else {
8759 		pkt->pkt_comp = st_intr;
8760 	}
8761 
8762 	st_add_recovery_info_to_pkt(un, bp, pkt);
8763 
8764 exit:
8765 	ASSERT(mutex_owned(ST_MUTEX));
8766 }
8767 
8768 
8769 /*
8770  * Build a command based on a uscsi command;
8771  */
8772 static void
8773 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
8774     struct buf *bp, int (*func)(caddr_t))
8775 {
8776 	struct scsi_pkt *pkt;
8777 	recov_info *ri;
8778 	caddr_t cdb;
8779 	int	cdblen;
8780 	int	stat_size = 1;
8781 	int	flags = 0;
8782 
8783 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
8784 
8785 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8786 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
8787 
8788 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
8789 		if (un->un_arq_enabled) {
8790 			if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
8791 				stat_size = (int)(ucmd->uscsi_rqlen) +
8792 				    sizeof (struct scsi_arq_status) -
8793 				    sizeof (struct scsi_extended_sense);
8794 				flags = PKT_XARQ;
8795 			} else {
8796 				stat_size = sizeof (struct scsi_arq_status);
8797 			}
8798 		}
8799 	}
8800 
8801 	ASSERT(mutex_owned(ST_MUTEX));
8802 
8803 	cdb = ucmd->uscsi_cdb;
8804 	cdblen = ucmd->uscsi_cdblen;
8805 
8806 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8807 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
8808 	    ucmd->uscsi_buflen, bp->b_bcount);
8809 	pkt = scsi_init_pkt(ROUTE, NULL,
8810 	    (bp->b_bcount > 0) ? bp : NULL,
8811 	    cdblen, stat_size, st_recov_sz, flags, func, (caddr_t)un);
8812 	if (pkt == NULL) {
8813 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8814 		    "uscsi command scsi_init_pkt() failure\n");
8815 		goto exit;
8816 	}
8817 
8818 	ASSERT(pkt->pkt_resid == 0);
8819 #ifdef STDEBUG
8820 	bzero(pkt->pkt_private, st_recov_sz);
8821 	bzero(pkt->pkt_scbp, stat_size);
8822 #endif
8823 	ri = (recov_info *)pkt->pkt_private;
8824 	ri->privatelen = st_recov_sz;
8825 
8826 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
8827 
8828 #ifdef STDEBUG
8829 	if ((st_debug & 0x7) >= 6) {
8830 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8831 		    "pkt_cdbp", (char *)cdb, cdblen);
8832 	}
8833 #endif
8834 
8835 	if (ucmd->uscsi_flags & USCSI_SILENT) {
8836 		pkt->pkt_flags |= FLAG_SILENT;
8837 	}
8838 
8839 	pkt->pkt_time = ucmd->uscsi_timeout;
8840 	if (bp == un->un_recov_buf) {
8841 		pkt->pkt_comp = st_recov_cb;
8842 	} else {
8843 		pkt->pkt_comp = st_intr;
8844 	}
8845 	st_add_recovery_info_to_pkt(un, bp, pkt);
8846 exit:
8847 	ASSERT(mutex_owned(ST_MUTEX));
8848 }
8849 
8850 
8851 /*
8852  * restart cmd currently at the head of the runq
8853  *
8854  * If scsi_transport() succeeds or the retries
8855  * count exhausted, restore the throttle that was
8856  * zeroed out in st_handle_intr_busy().
8857  *
8858  */
8859 static void
8860 st_intr_restart(void *arg)
8861 {
8862 	struct scsi_tape *un = arg;
8863 	struct buf *bp;
8864 	int queued;
8865 	int status = TRAN_ACCEPT;
8866 
8867 	mutex_enter(ST_MUTEX);
8868 
8869 	ST_FUNC(ST_DEVINFO, st_intr_restart);
8870 
8871 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8872 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
8873 
8874 	un->un_hib_tid = 0;
8875 
8876 	if (un->un_recov_buf_busy != 0) {
8877 		bp = un->un_recov_buf;
8878 		queued = 0;
8879 	} else if (un->un_sbuf_busy != 0) {
8880 		bp = un->un_sbufp;
8881 		queued = 0;
8882 	} else if (un->un_quef != NULL) {
8883 		bp = un->un_quef;
8884 		queued = 1;
8885 	} else {
8886 		mutex_exit(ST_MUTEX);
8887 		return;
8888 	}
8889 
8890 	/*
8891 	 * Here we know :
8892 	 *	throttle = 0, via st_handle_intr_busy
8893 	 */
8894 
8895 	if (queued) {
8896 		/*
8897 		 * move from waitq to runq, if there is anything on the waitq
8898 		 */
8899 		(void) st_remove_from_queue(&un->un_quef, &un->un_quef, bp);
8900 
8901 		if (un->un_runqf) {
8902 			/*
8903 			 * not good, we don't want to requeue something after
8904 			 * another.
8905 			 */
8906 			mutex_exit(ST_MUTEX);
8907 			goto done_error;
8908 		} else {
8909 			un->un_runqf = bp;
8910 			un->un_runql = bp;
8911 		}
8912 	}
8913 
8914 	ST_CDB(ST_DEVINFO, "Interrupt restart CDB",
8915 	    (char *)BP_PKT(bp)->pkt_cdbp);
8916 
8917 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
8918 
8919 	status = st_transport(un, BP_PKT(bp));
8920 
8921 	if (status != TRAN_ACCEPT) {
8922 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8923 		mutex_exit(ST_MUTEX);
8924 
8925 		if (status == TRAN_BUSY) {
8926 			if (st_handle_intr_busy(un, bp,
8927 			    ST_TRAN_BUSY_TIMEOUT) == 0)
8928 				return;	/* timeout is setup again */
8929 		}
8930 
8931 	} else {
8932 		un->un_tran_retry_ct = 0;
8933 		if (un->un_last_throttle) {
8934 			un->un_throttle = un->un_last_throttle;
8935 		}
8936 		mutex_exit(ST_MUTEX);
8937 		return;
8938 	}
8939 
8940 done_error:
8941 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8942 	    "restart transport rejected\n");
8943 	bp->b_resid = bp->b_bcount;
8944 
8945 #ifndef __lock_lint
8946 	/*
8947 	 * warlock doesn't understand this potential
8948 	 * recursion?
8949 	 */
8950 	mutex_enter(ST_MUTEX);
8951 	if (un->un_last_throttle) {
8952 		un->un_throttle = un->un_last_throttle;
8953 	}
8954 	if (status != TRAN_ACCEPT)
8955 		ST_DO_ERRSTATS(un, st_transerrs);
8956 	ST_DO_KSTATS(bp, kstat_waitq_exit);
8957 	st_set_pe_flag(un);
8958 	st_bioerror(bp, EIO);
8959 	st_done_and_mutex_exit(un, bp);
8960 #endif
8961 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8962 	    "busy restart aborted\n");
8963 }
8964 
8965 /*
8966  * st_check_media():
8967  * Periodically check the media state using scsi_watch service;
8968  * this service calls back after TUR and possibly request sense
8969  * the callback handler (st_media_watch_cb()) decodes the request sense
8970  * data (if any)
8971  */
8972 
8973 static int
8974 st_check_media(dev_t dev, enum mtio_state state)
8975 {
8976 	int rval = 0;
8977 	enum mtio_state	prev_state;
8978 	opaque_t token = NULL;
8979 
8980 	GET_SOFT_STATE(dev);
8981 
8982 	ST_FUNC(ST_DEVINFO, st_check_media);
8983 
8984 	mutex_enter(ST_MUTEX);
8985 
8986 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8987 	    "st_check_media:state=%x, mediastate=%x\n",
8988 	    state, un->un_mediastate);
8989 
8990 	prev_state = un->un_mediastate;
8991 
8992 	/*
8993 	 * is there anything to do?
8994 	 */
8995 retry:
8996 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
8997 		/*
8998 		 * submit the request to the scsi_watch service;
8999 		 * scsi_media_watch_cb() does the real work
9000 		 */
9001 		mutex_exit(ST_MUTEX);
9002 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
9003 		    st_check_media_time, SENSE_LENGTH,
9004 		    st_media_watch_cb, (caddr_t)dev);
9005 		if (token == NULL) {
9006 			rval = EAGAIN;
9007 			goto done;
9008 		}
9009 		mutex_enter(ST_MUTEX);
9010 
9011 		un->un_swr_token = token;
9012 		un->un_specified_mediastate = state;
9013 
9014 		/*
9015 		 * now wait for media change
9016 		 * we will not be signalled unless mediastate == state but it
9017 		 * still better to test for this condition, since there
9018 		 * is a 5 sec cv_broadcast delay when
9019 		 *  mediastate == MTIO_INSERTED
9020 		 */
9021 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9022 		    "st_check_media:waiting for media state change\n");
9023 		while (un->un_mediastate == state) {
9024 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
9025 				mutex_exit(ST_MUTEX);
9026 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9027 				    "st_check_media:waiting for media state "
9028 				    "was interrupted\n");
9029 				rval = EINTR;
9030 				goto done;
9031 			}
9032 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9033 			    "st_check_media:received signal, state=%x\n",
9034 			    un->un_mediastate);
9035 		}
9036 	}
9037 
9038 	/*
9039 	 * if we transitioned to MTIO_INSERTED, media has really been
9040 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
9041 	 * Reset and retry the state change.  If everything is ok, replay
9042 	 * the open() logic.
9043 	 */
9044 	if ((un->un_mediastate == MTIO_INSERTED) &&
9045 	    (un->un_state == ST_STATE_OFFLINE)) {
9046 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9047 		    "st_check_media: calling st_cmd to confirm inserted\n");
9048 
9049 		/*
9050 		 * set this early so that TUR will make it through strategy
9051 		 * without triggering a st_tape_init().  We needed it set
9052 		 * before calling st_tape_init() ourselves anyway.  If TUR
9053 		 * fails, set it back
9054 		 */
9055 		un->un_state = ST_STATE_INITIALIZING;
9056 
9057 		/*
9058 		 * If not reserved fail as getting reservation conflict
9059 		 * will make this hang forever.
9060 		 */
9061 		if ((un->un_rsvd_status &
9062 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9063 			mutex_exit(ST_MUTEX);
9064 			rval = EACCES;
9065 			goto done;
9066 		}
9067 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
9068 		if (rval == EACCES) {
9069 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9070 			    "st_check_media: TUR got Reservation Conflict\n");
9071 			mutex_exit(ST_MUTEX);
9072 			goto done;
9073 		}
9074 		if (rval) {
9075 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9076 			    "st_check_media: TUR failed, going to retry\n");
9077 			un->un_mediastate = prev_state;
9078 			un->un_state = ST_STATE_OFFLINE;
9079 			goto retry;
9080 		}
9081 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9082 		    "st_check_media: media inserted\n");
9083 
9084 		/* this also rewinds the tape */
9085 		rval = st_tape_init(un);
9086 		if (rval != 0) {
9087 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9088 			    "st_check_media : OFFLINE init failure ");
9089 			un->un_state = ST_STATE_OFFLINE;
9090 			un->un_pos.pmode = invalid;
9091 		} else {
9092 			un->un_state = ST_STATE_OPEN_PENDING_IO;
9093 		}
9094 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
9095 	    (un->un_state != ST_STATE_OFFLINE)) {
9096 		/*
9097 		 * supported devices must be rewound before ejection
9098 		 * rewind resets fileno & blkno
9099 		 */
9100 		un->un_laststate = un->un_state;
9101 		un->un_state = ST_STATE_OFFLINE;
9102 	}
9103 	mutex_exit(ST_MUTEX);
9104 done:
9105 	if (token) {
9106 		(void) scsi_watch_request_terminate(token,
9107 		    SCSI_WATCH_TERMINATE_WAIT);
9108 		mutex_enter(ST_MUTEX);
9109 		un->un_swr_token = (opaque_t)NULL;
9110 		mutex_exit(ST_MUTEX);
9111 	}
9112 
9113 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
9114 
9115 	return (rval);
9116 }
9117 
9118 /*
9119  * st_media_watch_cb() is called by scsi_watch_thread for
9120  * verifying the request sense data (if any)
9121  */
9122 static int
9123 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
9124 {
9125 	struct scsi_status *statusp = resultp->statusp;
9126 	struct scsi_extended_sense *sensep = resultp->sensep;
9127 	uchar_t actual_sense_length = resultp->actual_sense_length;
9128 	struct scsi_tape *un;
9129 	enum mtio_state state = MTIO_NONE;
9130 	int instance;
9131 	dev_t dev = (dev_t)arg;
9132 
9133 	instance = MTUNIT(dev);
9134 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
9135 		return (-1);
9136 	}
9137 
9138 	mutex_enter(ST_MUTEX);
9139 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
9140 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9141 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
9142 	    *((char *)statusp), (void *)sensep,
9143 	    actual_sense_length);
9144 
9145 
9146 	/*
9147 	 * if there was a check condition then sensep points to valid
9148 	 * sense data
9149 	 * if status was not a check condition but a reservation or busy
9150 	 * status then the new state is MTIO_NONE
9151 	 */
9152 	if (sensep) {
9153 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9154 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
9155 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
9156 
9157 		switch (un->un_dp->type) {
9158 		default:
9159 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9160 			    "st_media_watch_cb: unknown drive type %d, "
9161 			    "default to ST_TYPE_HP\n", un->un_dp->type);
9162 		/* FALLTHROUGH */
9163 
9164 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
9165 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
9166 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
9167 			if (un->un_dp->type == ST_TYPE_FUJI) {
9168 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9169 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
9170 			} else {
9171 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9172 				    "st_media_watch_cb: ST_TYPE_HP\n");
9173 			}
9174 			switch (sensep->es_key) {
9175 			case KEY_UNIT_ATTENTION:
9176 				/* not ready to ready transition */
9177 				/* hp/es_qual_code == 80 on>off>on */
9178 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
9179 				if (sensep->es_add_code == 0x28) {
9180 					state = MTIO_INSERTED;
9181 				}
9182 				break;
9183 			case KEY_NOT_READY:
9184 				/* in process, rewinding or loading */
9185 				if ((sensep->es_add_code == 0x04) &&
9186 				    (sensep->es_qual_code == 0x00)) {
9187 					state = MTIO_EJECTED;
9188 				}
9189 				break;
9190 			}
9191 			break;
9192 
9193 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
9194 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9195 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
9196 			switch (sensep->es_key) {
9197 			case KEY_UNIT_ATTENTION:
9198 				/* operator medium removal request */
9199 				if ((sensep->es_add_code == 0x5a) &&
9200 				    (sensep->es_qual_code == 0x01)) {
9201 					state = MTIO_EJECTED;
9202 				/* not ready to ready transition */
9203 				} else if ((sensep->es_add_code == 0x28) &&
9204 				    (sensep->es_qual_code == 0x00)) {
9205 					state = MTIO_INSERTED;
9206 				}
9207 				break;
9208 			case KEY_NOT_READY:
9209 				/* medium not present */
9210 				if (sensep->es_add_code == 0x3a) {
9211 					state = MTIO_EJECTED;
9212 				}
9213 				break;
9214 			}
9215 			break;
9216 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
9217 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9218 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
9219 			switch (sensep->es_key) {
9220 			case KEY_NOT_READY:
9221 				if ((sensep->es_add_code == 0x04) &&
9222 				    (sensep->es_qual_code == 0x00)) {
9223 					/* volume not mounted? */
9224 					state = MTIO_EJECTED;
9225 				} else if (sensep->es_add_code == 0x3a) {
9226 					state = MTIO_EJECTED;
9227 				}
9228 				break;
9229 			case KEY_UNIT_ATTENTION:
9230 				state = MTIO_EJECTED;
9231 				break;
9232 			}
9233 			break;
9234 
9235 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
9236 			switch (sensep->es_key) {
9237 			case KEY_UNIT_ATTENTION:
9238 				if (sensep->es_add_code == 0x28) {
9239 					state = MTIO_INSERTED;
9240 				}
9241 				break;
9242 			case KEY_NOT_READY:
9243 				if (sensep->es_add_code == 0x04) {
9244 					/* in transition but could be either */
9245 					state = un->un_specified_mediastate;
9246 				} else if ((sensep->es_add_code == 0x3a) &&
9247 				    (sensep->es_qual_code == 0x00)) {
9248 					state = MTIO_EJECTED;
9249 				}
9250 				break;
9251 			}
9252 			break;
9253 		}
9254 	} else if (*((char *)statusp) == STATUS_GOOD) {
9255 		state = MTIO_INSERTED;
9256 	}
9257 
9258 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9259 	    "st_media_watch_cb:state=%x, specified=%x\n",
9260 	    state, un->un_specified_mediastate);
9261 
9262 	/*
9263 	 * now signal the waiting thread if this is *not* the specified state;
9264 	 * delay the signal if the state is MTIO_INSERTED
9265 	 * to allow the target to recover
9266 	 */
9267 	if (state != un->un_specified_mediastate) {
9268 		un->un_mediastate = state;
9269 		if (state == MTIO_INSERTED) {
9270 			/*
9271 			 * delay the signal to give the drive a chance
9272 			 * to do what it apparently needs to do
9273 			 */
9274 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9275 			    "st_media_watch_cb:delayed cv_broadcast\n");
9276 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
9277 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
9278 		} else {
9279 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9280 			    "st_media_watch_cb:immediate cv_broadcast\n");
9281 			cv_broadcast(&un->un_state_cv);
9282 		}
9283 	}
9284 	mutex_exit(ST_MUTEX);
9285 	return (0);
9286 }
9287 
9288 /*
9289  * delayed cv_broadcast to allow for target to recover
9290  * from media insertion
9291  */
9292 static void
9293 st_delayed_cv_broadcast(void *arg)
9294 {
9295 	struct scsi_tape *un = arg;
9296 
9297 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
9298 
9299 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9300 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
9301 
9302 	mutex_enter(ST_MUTEX);
9303 	cv_broadcast(&un->un_state_cv);
9304 	mutex_exit(ST_MUTEX);
9305 }
9306 
9307 /*
9308  * restart cmd currently at the start of the waitq
9309  */
9310 static void
9311 st_start_restart(void *arg)
9312 {
9313 	struct scsi_tape *un = arg;
9314 
9315 	ST_FUNC(ST_DEVINFO, st_start_restart);
9316 
9317 	ASSERT(un != NULL);
9318 
9319 	mutex_enter(ST_MUTEX);
9320 
9321 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_tran_restart()\n");
9322 
9323 	st_start(un);
9324 
9325 	mutex_exit(ST_MUTEX);
9326 }
9327 
9328 
9329 /*
9330  * Command completion processing
9331  *
9332  */
9333 static void
9334 st_intr(struct scsi_pkt *pkt)
9335 {
9336 	recov_info *rcv = pkt->pkt_private;
9337 	struct buf *bp = rcv->cmd_bp;
9338 	struct scsi_tape *un;
9339 	errstate action = COMMAND_DONE;
9340 	clock_t	timout;
9341 	int	status;
9342 
9343 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
9344 
9345 	ST_FUNC(ST_DEVINFO, st_intr);
9346 
9347 	ASSERT(un != NULL);
9348 
9349 	mutex_enter(ST_MUTEX);
9350 
9351 	ASSERT(bp != un->un_recov_buf);
9352 
9353 	if (pkt == un->un_rqs) {
9354 		scsi_sync_pkt(pkt);
9355 	}
9356 
9357 	un->un_rqs_state &= ~(ST_RQS_ERROR);
9358 
9359 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
9360 
9361 	if (pkt->pkt_reason != CMD_CMPLT) {
9362 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9363 		    "Unhappy packet status reason = %s statistics = 0x%x\n",
9364 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9365 
9366 		/* If device has gone away not much else to do */
9367 		if (pkt->pkt_reason == CMD_DEV_GONE) {
9368 			action = COMMAND_DONE_ERROR;
9369 		} else if ((pkt == un->un_rqs) ||
9370 		    (un->un_state == ST_STATE_SENSING)) {
9371 			ASSERT(pkt == un->un_rqs);
9372 			ASSERT(un->un_state == ST_STATE_SENSING);
9373 			un->un_state = un->un_laststate;
9374 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp =
9375 			    un->un_rqs_bp;
9376 			ST_DO_ERRSTATS(un, st_transerrs);
9377 			action = COMMAND_DONE_ERROR;
9378 		} else {
9379 			action = st_handle_incomplete(un, bp);
9380 		}
9381 	/*
9382 	 * At this point we know that the command was successfully
9383 	 * completed. Now what?
9384 	 */
9385 	} else if ((pkt == un->un_rqs) || (un->un_state == ST_STATE_SENSING)) {
9386 		/*
9387 		 * okay. We were running a REQUEST SENSE. Find
9388 		 * out what to do next.
9389 		 */
9390 		ASSERT(pkt == un->un_rqs);
9391 		ASSERT(un->un_state == ST_STATE_SENSING);
9392 		action = st_handle_sense(un, bp, &un->un_pos);
9393 		/*
9394 		 * Make rqs isn't going to be retied.
9395 		 */
9396 		if (action != QUE_BUSY_COMMAND && action != QUE_COMMAND) {
9397 			/*
9398 			 * set pkt back to original packet in case we will have
9399 			 * to requeue it
9400 			 */
9401 			pkt = BP_PKT(bp);
9402 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp =
9403 			    un->un_rqs_bp;
9404 			/*
9405 			 * some actions are based on un_state, hence
9406 			 * restore the state st was in before ST_STATE_SENSING.
9407 			 */
9408 			un->un_state = un->un_laststate;
9409 		}
9410 
9411 	} else if (un->un_arq_enabled && (pkt->pkt_state & STATE_ARQ_DONE)) {
9412 		/*
9413 		 * the transport layer successfully completed an autorqsense
9414 		 */
9415 		action = st_handle_autosense(un, bp, &un->un_pos);
9416 
9417 	} else  if ((SCBP(pkt)->sts_busy) || (SCBP(pkt)->sts_chk)) {
9418 		/*
9419 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9420 		 * to see if the status bits we're okay. If a request sense
9421 		 * is to be run, that will happen.
9422 		 */
9423 		action = st_check_error(un, pkt);
9424 	}
9425 
9426 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9427 		switch (action) {
9428 			case QUE_COMMAND:
9429 				/*
9430 				 * return cmd to head to the queue
9431 				 * since we are suspending so that
9432 				 * it gets restarted during resume
9433 				 */
9434 				st_add_to_queue(&un->un_runqf, &un->un_runql,
9435 				    un->un_runqf, bp);
9436 
9437 				action = JUST_RETURN;
9438 				break;
9439 
9440 			case QUE_SENSE:
9441 				action = COMMAND_DONE_ERROR;
9442 				break;
9443 
9444 			default:
9445 				break;
9446 		}
9447 	}
9448 
9449 	/*
9450 	 * Restore old state if we were sensing.
9451 	 */
9452 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9453 		un->un_state = un->un_laststate;
9454 	}
9455 
9456 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9457 	    "st_intr: pkt=%p, bp=%p, action=%x, status=%x\n",
9458 	    (void *)pkt, (void *)bp, action, SCBP_C(pkt));
9459 
9460 again:
9461 	switch (action) {
9462 	case COMMAND_DONE_EACCES:
9463 		/* this is to report a reservation conflict */
9464 		st_bioerror(bp, EACCES);
9465 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9466 		    "Reservation Conflict \n");
9467 		un->un_pos.pmode = invalid;
9468 
9469 		/*FALLTHROUGH*/
9470 	case COMMAND_DONE_ERROR:
9471 		if (un->un_pos.eof < ST_EOT_PENDING &&
9472 		    un->un_state >= ST_STATE_OPEN) {
9473 			/*
9474 			 * all errors set state of the tape to 'unknown'
9475 			 * unless we're at EOT or are doing append testing.
9476 			 * If sense key was illegal request, preserve state.
9477 			 */
9478 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9479 				un->un_pos.pmode = invalid;
9480 			}
9481 		}
9482 
9483 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9484 		/*
9485 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9486 		 * make sure an error ocurrs, so make sure at least EIO is
9487 		 * returned
9488 		 */
9489 		if (geterror(bp) == 0)
9490 			st_bioerror(bp, EIO);
9491 
9492 		st_set_pe_flag(un);
9493 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9494 		    (un->un_errno == EIO)) {
9495 			un->un_rqs_state &= ~(ST_RQS_VALID);
9496 		}
9497 		break;
9498 
9499 	case COMMAND_DONE_ERROR_RECOVERED:
9500 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9501 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9502 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9503 		if (geterror(bp) == 0) {
9504 			st_bioerror(bp, EIO);
9505 		}
9506 		st_set_pe_flag(un);
9507 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9508 		    (un->un_errno == EIO)) {
9509 			un->un_rqs_state &= ~(ST_RQS_VALID);
9510 		}
9511 		/*FALLTHROUGH*/
9512 	case COMMAND_DONE:
9513 		st_set_state(un, bp);
9514 		break;
9515 
9516 	case QUE_SENSE:
9517 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9518 			goto sense_error;
9519 
9520 		if (un->un_state != ST_STATE_SENSING) {
9521 			un->un_laststate = un->un_state;
9522 			un->un_state = ST_STATE_SENSING;
9523 		}
9524 
9525 		/* Whats going to happen here? */
9526 
9527 		((recov_info *)un->un_rqs->pkt_private)->cmd_bp = bp;
9528 
9529 		bzero(ST_RQSENSE, SENSE_LENGTH);
9530 
9531 		scsi_sync_pkt(un->un_rqs); /* HELLO */
9532 
9533 		if (un->un_throttle) {
9534 			un->un_last_throttle = un->un_throttle;
9535 			un->un_throttle = 0;
9536 		}
9537 
9538 		ST_CDB(ST_DEVINFO, "Queue sense CDB",
9539 		    (char *)BP_PKT(bp)->pkt_cdbp);
9540 
9541 		/*
9542 		 * never retry this, some other command will have nuked the
9543 		 * sense, anyway
9544 		 */
9545 		status = st_transport(un, un->un_rqs);
9546 
9547 		if (un->un_last_throttle) {
9548 			un->un_throttle = un->un_last_throttle;
9549 		}
9550 
9551 		if (status == TRAN_ACCEPT) {
9552 			mutex_exit(ST_MUTEX);
9553 			return;
9554 		}
9555 		if (status != TRAN_BUSY)
9556 			ST_DO_ERRSTATS(un, st_transerrs);
9557 sense_error:
9558 		un->un_pos.pmode = invalid;
9559 		st_bioerror(bp, EIO);
9560 		st_set_pe_flag(un);
9561 		break;
9562 
9563 	case QUE_BUSY_COMMAND:
9564 		/* longish timeout */
9565 		timout = ST_STATUS_BUSY_TIMEOUT;
9566 		goto que_it_up;
9567 
9568 	case QUE_COMMAND:
9569 		/* short timeout */
9570 		timout = ST_TRAN_BUSY_TIMEOUT;
9571 que_it_up:
9572 		/*
9573 		 * let st_handle_intr_busy put this bp back on waitq and make
9574 		 * checks to see if it is ok to requeue the command.
9575 		 */
9576 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9577 
9578 		/*
9579 		 * Save the throttle before setting up the timeout
9580 		 */
9581 		if (un->un_throttle) {
9582 			un->un_last_throttle = un->un_throttle;
9583 		}
9584 		mutex_exit(ST_MUTEX);
9585 		if (st_handle_intr_busy(un, bp, timout) == 0)
9586 			return;		/* timeout is setup again */
9587 
9588 		mutex_enter(ST_MUTEX);
9589 		un->un_pos.pmode = invalid;
9590 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9591 		st_bioerror(bp, EIO);
9592 		st_set_pe_flag(un);
9593 		break;
9594 
9595 	case QUE_LAST_COMMAND:
9596 
9597 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9598 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9599 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9600 			goto last_command_error;
9601 		}
9602 		mutex_exit(ST_MUTEX);
9603 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9604 			return;
9605 		mutex_enter(ST_MUTEX);
9606 last_command_error:
9607 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9608 		un->un_pos.pmode = invalid;
9609 		st_bioerror(bp, EIO);
9610 		st_set_pe_flag(un);
9611 		break;
9612 
9613 	case COMMAND_TIMEOUT:
9614 	case DEVICE_RESET:
9615 	case DEVICE_TAMPER:
9616 	case ATTEMPT_RETRY:
9617 		action = st_command_recovery(un, pkt, action);
9618 		goto again;
9619 
9620 	default:
9621 		ASSERT(0);
9622 		/* FALLTHRU */
9623 	case JUST_RETURN:
9624 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9625 		mutex_exit(ST_MUTEX);
9626 		return;
9627 	}
9628 
9629 	ST_DO_KSTATS(bp, kstat_runq_exit);
9630 	st_done_and_mutex_exit(un, bp);
9631 }
9632 
9633 static errstate
9634 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9635 {
9636 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9637 	recov_info *rinfo;
9638 	errstate rval = COMMAND_DONE_ERROR;
9639 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9640 	    un->un_rqs : BP_PKT(bp);
9641 	int result;
9642 
9643 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9644 
9645 	rinfo = (recov_info *)pkt->pkt_private;
9646 
9647 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9648 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9649 
9650 	ASSERT(mutex_owned(ST_MUTEX));
9651 
9652 	switch (pkt->pkt_reason) {
9653 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9654 		/*
9655 		 * this occurs when accessing a powered down drive, no
9656 		 * need to complain; just fail the open
9657 		 */
9658 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9659 
9660 		/*
9661 		 * if we have commands outstanding in HBA, and a command
9662 		 * comes back incomplete, we're hosed, so reset target
9663 		 * If we have the bus, but cmd_incomplete, we probably just
9664 		 * have a failed selection, so don't reset the target, just
9665 		 * requeue the command and try again
9666 		 */
9667 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9668 			goto reset_target;
9669 		}
9670 
9671 		/*
9672 		 * Retry selection a couple more times if we're
9673 		 * open.  If opening, we only try just once to
9674 		 * reduce probe time for nonexistant devices.
9675 		 */
9676 		if ((un->un_laststate > ST_STATE_OPENING) &&
9677 		    ((int)un->un_retry_ct < st_selection_retry_count)) {
9678 /* XXX check retriable? */
9679 			rval = QUE_COMMAND;
9680 		}
9681 		ST_DO_ERRSTATS(un, st_transerrs);
9682 		break;
9683 
9684 	case CMD_ABORTED:
9685 		/*
9686 		 * most likely this is caused by flush-on-error support. If
9687 		 * it was not there, the we're in trouble.
9688 		 */
9689 		if (!un->un_flush_on_errors) {
9690 			un->un_status = SUN_KEY_FATAL;
9691 			goto reset_target;
9692 		}
9693 
9694 		st_set_pe_errno(un);
9695 		bioerror(bp, un->un_errno);
9696 		if (un->un_errno)
9697 			return (COMMAND_DONE_ERROR);
9698 		else
9699 			return (COMMAND_DONE);
9700 
9701 	case CMD_TIMEOUT:	/* Command timed out */
9702 		un->un_status = SUN_KEY_TIMEOUT;
9703 		return (COMMAND_TIMEOUT);
9704 
9705 	case CMD_TRAN_ERR:
9706 	case CMD_RESET:
9707 		if (pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET)) {
9708 			if ((un->un_rsvd_status &
9709 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
9710 			    ST_RESERVE) {
9711 				un->un_rsvd_status |= ST_LOST_RESERVE;
9712 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
9713 				    "Lost Reservation\n");
9714 			}
9715 			rval = DEVICE_RESET;
9716 			return (rval);
9717 		}
9718 		if (pkt->pkt_statistics & (STAT_ABORTED | STAT_TERMINATED)) {
9719 			rval = DEVICE_RESET;
9720 			return (rval);
9721 		}
9722 		/*FALLTHROUGH*/
9723 	default:
9724 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9725 		    "Unhandled packet status reason = %s statistics = 0x%x\n",
9726 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9727 reset_target:
9728 
9729 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9730 		    "transport completed with %s\n",
9731 		    scsi_rname(pkt->pkt_reason));
9732 		ST_DO_ERRSTATS(un, st_transerrs);
9733 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
9734 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
9735 		    STAT_ABORTED)) == 0)) {
9736 
9737 			/*
9738 			 * If we haven't reserved the drive don't reset it.
9739 			 */
9740 			if ((un->un_rsvd_status &
9741 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9742 				return (rval);
9743 			}
9744 
9745 			/*
9746 			 * if we aren't lost yet we will be soon.
9747 			 */
9748 			un->un_pos.pmode = invalid;
9749 
9750 			result = st_reset(un, RESET_LUN);
9751 
9752 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
9753 				/* no hope left to recover */
9754 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
9755 				    "recovery by resets failed\n");
9756 				return (rval);
9757 			}
9758 		}
9759 	}
9760 
9761 
9762 	if ((int)un->un_retry_ct++ < st_retry_count) {
9763 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9764 			rval = QUE_COMMAND;
9765 		} else if (bp == un->un_sbufp) {
9766 			if (rinfo->privatelen == sizeof (recov_info)) {
9767 				if (rinfo->cmd_attrib->retriable) {
9768 					/*
9769 					 * These commands can be rerun
9770 					 * with impunity
9771 					 */
9772 					rval = QUE_COMMAND;
9773 				}
9774 			} else {
9775 				cmd_attribute const *attrib;
9776 				attrib =
9777 				    st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
9778 				if (attrib->retriable) {
9779 					rval = QUE_COMMAND;
9780 				}
9781 			}
9782 		}
9783 	} else {
9784 		rval = COMMAND_DONE_ERROR;
9785 	}
9786 
9787 	if (un->un_state >= ST_STATE_OPEN) {
9788 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9789 		    fail, scsi_rname(pkt->pkt_reason),
9790 		    (rval == COMMAND_DONE_ERROR)?
9791 		    "giving up" : "retrying command");
9792 	}
9793 	return (rval);
9794 }
9795 
9796 /*
9797  * if the device is busy, then put this bp back on the waitq, on the
9798  * interrupt thread, where we want the head of the queue and not the
9799  * end
9800  *
9801  * The callers of this routine should take measures to save the
9802  * un_throttle in un_last_throttle which will be restored in
9803  * st_intr_restart(). The only exception should be st_intr_restart()
9804  * calling this routine for which the saving is already done.
9805  */
9806 static int
9807 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
9808 	clock_t timeout_interval)
9809 {
9810 
9811 	int queued;
9812 	int rval = 0;
9813 
9814 	mutex_enter(ST_MUTEX);
9815 
9816 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
9817 
9818 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9819 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
9820 
9821 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
9822 		queued = 1;
9823 	} else {
9824 		queued = 0;
9825 	}
9826 
9827 	/*
9828 	 * Check to see if we hit the retry timeout. We check to make sure
9829 	 * this is the first one on the runq and make sure we have not
9830 	 * queued up any more, so this one has to be the last on the list
9831 	 * also. If it is not, we have to fail.  If it is not the first, but
9832 	 * is the last we are in trouble anyway, as we are in the interrupt
9833 	 * context here.
9834 	 */
9835 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
9836 	    ((un->un_runqf != bp) && (un->un_runql != bp) && (queued))) {
9837 		rval = -1;
9838 		goto exit;
9839 	}
9840 
9841 	/* put the bp back on the waitq */
9842 	if (queued) {
9843 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
9844 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
9845 	}
9846 
9847 	/*
9848 	 * We don't want any other commands being started in the mean time.
9849 	 * If start had just released mutex after putting something on the
9850 	 * runq, we won't even get here.
9851 	 */
9852 	un->un_throttle = 0;
9853 
9854 	/*
9855 	 * send a marker pkt, if appropriate
9856 	 */
9857 	st_hba_unflush(un);
9858 
9859 	/*
9860 	 * all queues are aligned, we are just waiting to
9861 	 * transport
9862 	 */
9863 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
9864 
9865 exit:
9866 	mutex_exit(ST_MUTEX);
9867 	return (rval);
9868 }
9869 
9870 /*
9871  * To get one error entry from error stack
9872  */
9873 static int
9874 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
9875 {
9876 #ifdef _MULTI_DATAMODEL
9877 	/*
9878 	 * For use when a 32 bit app makes a call into a
9879 	 * 64 bit ioctl
9880 	 */
9881 	struct mterror_entry32 err_entry32;
9882 #endif /* _MULTI_DATAMODEL */
9883 
9884 	int rval = 0;
9885 	struct mterror_entry err_entry;
9886 	struct mterror_entry_stack *err_link_entry_p;
9887 	size_t arq_status_len_in, arq_status_len_kr;
9888 
9889 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
9890 
9891 	ASSERT(mutex_owned(ST_MUTEX));
9892 
9893 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9894 	    "st_get_error_entry()\n");
9895 
9896 	/*
9897 	 * if error record stack empty, return ENXIO
9898 	 */
9899 	if (un->un_error_entry_stk == NULL) {
9900 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9901 		    "st_get_error_entry: Error Entry Stack Empty!\n");
9902 		rval = ENXIO;
9903 		goto ret;
9904 	}
9905 
9906 	/*
9907 	 * get the top entry from stack
9908 	 */
9909 	err_link_entry_p = un->un_error_entry_stk;
9910 	arq_status_len_kr =
9911 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
9912 
9913 #ifdef _MULTI_DATAMODEL
9914 	switch (ddi_model_convert_from(flag & FMODELS)) {
9915 	case DDI_MODEL_ILP32:
9916 		if (ddi_copyin((void *)arg, &err_entry32,
9917 		    MTERROR_ENTRY_SIZE_32, flag)) {
9918 			rval = EFAULT;
9919 			goto ret;
9920 		}
9921 
9922 		arq_status_len_in =
9923 		    (size_t)err_entry32.mtee_arq_status_len;
9924 
9925 		err_entry32.mtee_cdb_len =
9926 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
9927 
9928 		if (arq_status_len_in > arq_status_len_kr)
9929 			err_entry32.mtee_arq_status_len =
9930 			    (size32_t)arq_status_len_kr;
9931 
9932 		if (ddi_copyout(
9933 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
9934 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
9935 		    err_entry32.mtee_cdb_len, flag)) {
9936 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9937 			    "st_get_error_entry: Copy cdb buffer error!");
9938 			rval = EFAULT;
9939 		}
9940 
9941 		if (ddi_copyout(
9942 		    err_link_entry_p->mtees_entry.mtee_arq_status,
9943 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
9944 		    err_entry32.mtee_arq_status_len, flag)) {
9945 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9946 			    "st_get_error_entry: copy arq status error!");
9947 			rval = EFAULT;
9948 		}
9949 
9950 		if (ddi_copyout(&err_entry32, (void *)arg,
9951 		    MTERROR_ENTRY_SIZE_32, flag)) {
9952 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9953 			    "st_get_error_entry: copy arq status out error!");
9954 			rval = EFAULT;
9955 		}
9956 		break;
9957 
9958 	case DDI_MODEL_NONE:
9959 		if (ddi_copyin((void *)arg, &err_entry,
9960 		    MTERROR_ENTRY_SIZE_64, flag)) {
9961 			rval = EFAULT;
9962 			goto ret;
9963 		}
9964 		arq_status_len_in = err_entry.mtee_arq_status_len;
9965 
9966 		err_entry.mtee_cdb_len =
9967 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
9968 
9969 		if (arq_status_len_in > arq_status_len_kr)
9970 			err_entry.mtee_arq_status_len =
9971 			    arq_status_len_kr;
9972 
9973 		if (ddi_copyout(
9974 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
9975 		    err_entry.mtee_cdb_buf,
9976 		    err_entry.mtee_cdb_len, flag)) {
9977 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9978 			    "st_get_error_entry: Copy cdb buffer error!");
9979 			rval = EFAULT;
9980 		}
9981 
9982 		if (ddi_copyout(
9983 		    err_link_entry_p->mtees_entry.mtee_arq_status,
9984 		    err_entry.mtee_arq_status,
9985 		    err_entry.mtee_arq_status_len, flag)) {
9986 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9987 			    "st_get_error_entry: copy arq status error!");
9988 			rval = EFAULT;
9989 		}
9990 
9991 		if (ddi_copyout(&err_entry, (void *)arg,
9992 		    MTERROR_ENTRY_SIZE_64, flag)) {
9993 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9994 			    "st_get_error_entry: copy arq status out error!");
9995 			rval = EFAULT;
9996 		}
9997 		break;
9998 	}
9999 #else /* _MULTI_DATAMODEL */
10000 	if (ddi_copyin((void *)arg, &err_entry,
10001 	    MTERROR_ENTRY_SIZE_64, flag)) {
10002 		rval = EFAULT;
10003 		goto ret;
10004 	}
10005 	arq_status_len_in = err_entry.mtee_arq_status_len;
10006 
10007 	err_entry.mtee_cdb_len =
10008 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
10009 
10010 	if (arq_status_len_in > arq_status_len_kr)
10011 		err_entry.mtee_arq_status_len =
10012 		    arq_status_len_kr;
10013 
10014 	if (ddi_copyout(
10015 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10016 	    err_entry.mtee_cdb_buf,
10017 	    err_entry.mtee_cdb_len, flag)) {
10018 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10019 		    "st_get_error_entry: Copy cdb buffer error!");
10020 		rval = EFAULT;
10021 	}
10022 
10023 	if (ddi_copyout(
10024 	    err_link_entry_p->mtees_entry.mtee_arq_status,
10025 	    err_entry.mtee_arq_status,
10026 	    err_entry.mtee_arq_status_len, flag)) {
10027 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10028 		    "st_get_error_entry: copy arq status buffer error!");
10029 		rval = EFAULT;
10030 	}
10031 
10032 	if (ddi_copyout(&err_entry, (void *)arg,
10033 	    MTERROR_ENTRY_SIZE_64, flag)) {
10034 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10035 		    "st_get_error_entry: copy arq status out error!");
10036 		rval = EFAULT;
10037 	}
10038 #endif /* _MULTI_DATAMODEL */
10039 
10040 	/*
10041 	 * update stack
10042 	 */
10043 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
10044 
10045 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
10046 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
10047 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
10048 
10049 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
10050 	    SECMDS_STATUS_SIZE);
10051 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
10052 
10053 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
10054 	err_link_entry_p = NULL;
10055 ret:
10056 	return (rval);
10057 }
10058 
10059 /*
10060  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
10061  * the scsi CDB command which causes the error and generates sense data and
10062  * the scsi status.
10063  *
10064  *      error-record stack
10065  *
10066  *
10067  *             TOP                                     BOTTOM
10068  *              ------------------------------------------
10069  *              |   0   |   1   |   2   |   ...  |   n   |
10070  *              ------------------------------------------
10071  *                  ^
10072  *                  |
10073  *       pointer to error entry
10074  *
10075  * when st driver generates one sense data record, it creates a error-entry
10076  * and pushes it onto the stack.
10077  *
10078  */
10079 
10080 static void
10081 st_update_error_stack(struct scsi_tape *un,
10082 			struct scsi_pkt *pkt,
10083 			struct scsi_arq_status *cmd)
10084 {
10085 	struct mterror_entry_stack *err_entry_tmp;
10086 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
10087 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
10088 
10089 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
10090 
10091 	ASSERT(mutex_owned(ST_MUTEX));
10092 
10093 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10094 	    "st_update_error_stack()\n");
10095 
10096 	ASSERT(cmd);
10097 	ASSERT(cdbp);
10098 	if (cdblen == 0) {
10099 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10100 		    "st_update_error_stack: CDB length error!\n");
10101 		return;
10102 	}
10103 
10104 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
10105 	ASSERT(err_entry_tmp != NULL);
10106 
10107 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
10108 	    kmem_alloc(cdblen, KM_SLEEP);
10109 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
10110 
10111 	err_entry_tmp->mtees_entry.mtee_arq_status =
10112 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
10113 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
10114 
10115 	/*
10116 	 * copy cdb command & length to current error entry
10117 	 */
10118 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
10119 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
10120 
10121 	/*
10122 	 * copy scsi status length to current error entry
10123 	 */
10124 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
10125 	    SECMDS_STATUS_SIZE;
10126 
10127 	/*
10128 	 * copy sense data and scsi status to current error entry
10129 	 */
10130 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
10131 	    SECMDS_STATUS_SIZE);
10132 
10133 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
10134 	un->un_error_entry_stk = err_entry_tmp;
10135 
10136 }
10137 
10138 /*
10139  * Empty all the error entry in stack
10140  */
10141 static void
10142 st_empty_error_stack(struct scsi_tape *un)
10143 {
10144 	struct mterror_entry_stack *linkp;
10145 
10146 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
10147 
10148 	ASSERT(mutex_owned(ST_MUTEX));
10149 
10150 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10151 	    "st_empty_entry_stack()\n");
10152 
10153 	while (un->un_error_entry_stk != NULL) {
10154 		linkp = un->un_error_entry_stk;
10155 		un->un_error_entry_stk =
10156 		    un->un_error_entry_stk->mtees_nextp;
10157 
10158 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
10159 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
10160 			    linkp->mtees_entry.mtee_cdb_len);
10161 
10162 		if (linkp->mtees_entry.mtee_arq_status != NULL)
10163 			kmem_free(linkp->mtees_entry.mtee_arq_status,
10164 			    linkp->mtees_entry.mtee_arq_status_len);
10165 
10166 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
10167 		linkp = NULL;
10168 	}
10169 }
10170 
10171 static errstate
10172 st_handle_sense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10173 {
10174 	struct scsi_pkt *pkt = BP_PKT(bp);
10175 	struct scsi_pkt *rqpkt = un->un_rqs;
10176 	struct scsi_arq_status arqstat;
10177 
10178 	errstate rval = COMMAND_DONE_ERROR;
10179 	int amt;
10180 
10181 	ST_FUNC(ST_DEVINFO, st_handle_sense);
10182 
10183 	ASSERT(mutex_owned(ST_MUTEX));
10184 
10185 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10186 	    "st_handle_sense()\n");
10187 
10188 	if (SCBP(rqpkt)->sts_busy) {
10189 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10190 		    "busy unit on request sense\n");
10191 		if ((int)un->un_retry_ct++ < st_retry_count) {
10192 			rval = QUE_BUSY_COMMAND;
10193 		}
10194 		return (rval);
10195 	} else if (SCBP(rqpkt)->sts_chk) {
10196 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10197 		    "Check Condition on REQUEST SENSE\n");
10198 		return (rval);
10199 	}
10200 
10201 	/* was there enough data? */
10202 	amt = (int)MAX_SENSE_LENGTH - rqpkt->pkt_resid;
10203 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
10204 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10205 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10206 		    "REQUEST SENSE couldn't get sense data\n");
10207 		return (rval);
10208 	}
10209 
10210 	bcopy(SCBP(pkt), &arqstat.sts_status,
10211 	    sizeof (struct scsi_status));
10212 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
10213 	    sizeof (struct scsi_status));
10214 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
10215 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
10216 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
10217 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
10218 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
10219 
10220 	/*
10221 	 * copy one arqstat entry in the sense data buffer
10222 	 */
10223 	st_update_error_stack(un, pkt, &arqstat);
10224 	return (st_decode_sense(un, bp, amt, SCBP(rqpkt), pos));
10225 }
10226 
10227 static errstate
10228 st_handle_autosense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10229 {
10230 	struct scsi_pkt *pkt = BP_PKT(bp);
10231 	struct scsi_arq_status *arqstat =
10232 	    (struct scsi_arq_status *)pkt->pkt_scbp;
10233 	errstate rval = COMMAND_DONE_ERROR;
10234 	int amt;
10235 
10236 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
10237 
10238 	ASSERT(mutex_owned(ST_MUTEX));
10239 
10240 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10241 	    "st_handle_autosense()\n");
10242 
10243 	if (arqstat->sts_rqpkt_status.sts_busy) {
10244 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10245 		    "busy unit on request sense\n");
10246 		/*
10247 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
10248 		 * the disadvantage is that we do not have any delay for the
10249 		 * second retry of rqsense and we have to keep a packet around
10250 		 */
10251 		return (QUE_SENSE);
10252 
10253 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
10254 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10255 		    "transport error on REQUEST SENSE\n");
10256 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
10257 		    ((arqstat->sts_rqpkt_statistics &
10258 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
10259 			if (st_reset(un, RESET_LUN) == 0) {
10260 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10261 				    "recovery by resets failed\n");
10262 			}
10263 		}
10264 		return (rval);
10265 
10266 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
10267 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10268 		    "Check Condition on REQUEST SENSE\n");
10269 		return (rval);
10270 	}
10271 
10272 
10273 	/* was there enough data? */
10274 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10275 		amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10276 	} else {
10277 		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
10278 			amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10279 		} else {
10280 			amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10281 		}
10282 	}
10283 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
10284 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10285 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10286 		    "REQUEST SENSE couldn't get sense data\n");
10287 		return (rval);
10288 	}
10289 
10290 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10291 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, MAX_SENSE_LENGTH);
10292 	} else {
10293 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
10294 	}
10295 
10296 	/*
10297 	 * copy one arqstat entry in the sense data buffer
10298 	 */
10299 	st_update_error_stack(un, pkt, arqstat);
10300 
10301 	return (st_decode_sense(un, bp, amt, &arqstat->sts_rqpkt_status, pos));
10302 }
10303 
10304 static errstate
10305 st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
10306     struct scsi_status *statusp, tapepos_t *pos)
10307 {
10308 	struct scsi_pkt *pkt = BP_PKT(bp);
10309 	recov_info *ri = (recov_info *)pkt->pkt_private;
10310 	errstate rval = COMMAND_DONE_ERROR;
10311 	cmd_attribute const *attrib;
10312 	long resid;
10313 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10314 	int severity;
10315 	int get_error;
10316 
10317 	ST_FUNC(ST_DEVINFO, st_decode_sense);
10318 
10319 	ASSERT(mutex_owned(ST_MUTEX));
10320 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10321 	    "st_decode_sense()\n");
10322 
10323 	/*
10324 	 * For uscsi commands, squirrel away a copy of the
10325 	 * results of the Request Sense.
10326 	 */
10327 	if (USCSI_CMD(bp)) {
10328 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
10329 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
10330 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
10331 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
10332 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
10333 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
10334 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10335 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
10336 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
10337 		}
10338 	}
10339 
10340 	if (ri->privatelen == sizeof (recov_info)) {
10341 		attrib = ri->cmd_attrib;
10342 	} else {
10343 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10344 	}
10345 
10346 	/*
10347 	 * If the drive is an MT-02, reposition the
10348 	 * secondary error code into the proper place.
10349 	 *
10350 	 * XXX	MT-02 is non-CCS tape, so secondary error code
10351 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
10352 	 * so it's in byte 12.
10353 	 */
10354 	if (un->un_dp->type == ST_TYPE_EMULEX) {
10355 		sensep->es_code = sensep->es_add_info[0];
10356 	}
10357 
10358 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
10359 	    (caddr_t)&CDBP(pkt)->scc_cmd);
10360 
10361 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)sensep,
10362 	    sizeof (*sensep));
10363 
10364 	/* for normal I/O check extract the resid values. */
10365 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
10366 		if (sensep->es_valid) {
10367 			resid =
10368 			    (sensep->es_info_1 << 24) |
10369 			    (sensep->es_info_2 << 16) |
10370 			    (sensep->es_info_3 << 8)  |
10371 			    (sensep->es_info_4);
10372 			/* If fixed block */
10373 			if (un->un_bsize) {
10374 				resid *= un->un_bsize;
10375 			}
10376 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
10377 			resid = pkt->pkt_resid;
10378 		} else {
10379 			resid = bp->b_bcount;
10380 		}
10381 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10382 		    "st_decode_sense (rw): xferred bit = %d, resid=%ld (%d), "
10383 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
10384 		    resid,
10385 		    (sensep->es_info_1 << 24) |
10386 		    (sensep->es_info_2 << 16) |
10387 		    (sensep->es_info_3 << 8)  |
10388 		    (sensep->es_info_4),
10389 		    pkt->pkt_resid);
10390 		/*
10391 		 * The problem is, what should we believe?
10392 		 */
10393 		if (resid && (pkt->pkt_resid == 0)) {
10394 			pkt->pkt_resid = resid;
10395 		}
10396 	} else {
10397 		/*
10398 		 * If the command is SCMD_SPACE, we need to get the
10399 		 * residual as returned in the sense data, to adjust
10400 		 * our idea of current tape position correctly
10401 		 */
10402 		if ((sensep->es_valid) &&
10403 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10404 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10405 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
10406 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK)) {
10407 			resid =
10408 			    (sensep->es_info_1 << 24) |
10409 			    (sensep->es_info_2 << 16) |
10410 			    (sensep->es_info_3 << 8)  |
10411 			    (sensep->es_info_4);
10412 			bp->b_resid = resid;
10413 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10414 			    "st_decode_sense(other):	resid=%ld\n", resid);
10415 		} else {
10416 			/*
10417 			 * If the special command is SCMD_READ,
10418 			 * the correct resid will be set later.
10419 			 */
10420 			if (attrib->get_cnt != NULL) {
10421 				resid = attrib->get_cnt(pkt->pkt_cdbp);
10422 			} else {
10423 				resid = bp->b_bcount;
10424 			}
10425 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10426 			    "st_decode_sense(special read):  resid=%ld\n",
10427 			    resid);
10428 		}
10429 	}
10430 
10431 	if ((un->un_state >= ST_STATE_OPEN) &&
10432 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
10433 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
10434 		    "Failed CDB", (char *)pkt->pkt_cdbp);
10435 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10436 		    "sense data", (char *)sensep, amt);
10437 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10438 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10439 		    bp->b_bcount, resid, pkt->pkt_resid);
10440 	}
10441 
10442 	switch (un->un_status = sensep->es_key) {
10443 	case KEY_NO_SENSE:
10444 		severity = SCSI_ERR_INFO;
10445 
10446 		/*
10447 		 * Erase, locate or rewind operation in progress, retry
10448 		 * ASC  ASCQ
10449 		 *  00   18    Erase operation in progress
10450 		 *  00   19    Locate operation in progress
10451 		 *  00   1A    Rewind operation in progress
10452 		 */
10453 		if (sensep->es_add_code == 0 &&
10454 		    ((sensep->es_qual_code == 0x18) ||
10455 		    (sensep->es_qual_code == 0x19) ||
10456 		    (sensep->es_qual_code == 0x1a))) {
10457 			rval = QUE_BUSY_COMMAND;
10458 			break;
10459 		}
10460 
10461 		goto common;
10462 
10463 	case KEY_RECOVERABLE_ERROR:
10464 		severity = SCSI_ERR_RECOVERED;
10465 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10466 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10467 			if (un->un_dp->options &
10468 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10469 				rval = QUE_LAST_COMMAND;
10470 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10471 				    severity, pos->lgclblkno,
10472 				    un->un_err_pos.lgclblkno, scsi_cmds,
10473 				    sensep);
10474 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10475 				    "Command will be retried\n");
10476 			} else {
10477 				severity = SCSI_ERR_FATAL;
10478 				rval = COMMAND_DONE_ERROR_RECOVERED;
10479 				ST_DO_ERRSTATS(un, st_softerrs);
10480 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10481 				    severity, pos->lgclblkno,
10482 				    un->un_err_pos.lgclblkno, scsi_cmds,
10483 				    sensep);
10484 			}
10485 			break;
10486 		}
10487 common:
10488 		/*
10489 		 * XXX only want reads to be stopped by filemarks.
10490 		 * Don't want them to be stopped by EOT.  EOT matters
10491 		 * only on write.
10492 		 */
10493 		if (sensep->es_filmk && !sensep->es_eom) {
10494 			rval = COMMAND_DONE;
10495 		} else if (sensep->es_eom) {
10496 			rval = COMMAND_DONE;
10497 		} else if (sensep->es_ili) {
10498 			/*
10499 			 * Fun with variable length record devices:
10500 			 * for specifying larger blocks sizes than the
10501 			 * actual physical record size.
10502 			 */
10503 			if (un->un_bsize == 0 && resid > 0) {
10504 				/*
10505 				 * XXX! Ugly.
10506 				 * The requested blocksize is > tape blocksize,
10507 				 * so this is ok, so we just return the
10508 				 * actual size xferred.
10509 				 */
10510 				pkt->pkt_resid = resid;
10511 				rval = COMMAND_DONE;
10512 			} else if (un->un_bsize == 0 && resid < 0) {
10513 				/*
10514 				 * The requested blocksize is < tape blocksize,
10515 				 * so this is not ok, so we err with ENOMEM
10516 				 */
10517 				rval = COMMAND_DONE_ERROR_RECOVERED;
10518 				st_bioerror(bp, ENOMEM);
10519 			} else {
10520 				ST_DO_ERRSTATS(un, st_softerrs);
10521 				severity = SCSI_ERR_FATAL;
10522 				rval = COMMAND_DONE_ERROR;
10523 				st_bioerror(bp, EINVAL);
10524 				un->un_running.pmode = invalid;
10525 			}
10526 		} else {
10527 			/*
10528 			 * we hope and pray for this just being
10529 			 * something we can ignore (ie. a
10530 			 * truly recoverable soft error)
10531 			 */
10532 			rval = COMMAND_DONE;
10533 		}
10534 		if (sensep->es_filmk) {
10535 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10536 			    "filemark\n");
10537 			un->un_status = SUN_KEY_EOF;
10538 			pos->eof = ST_EOF_PENDING;
10539 			st_set_pe_flag(un);
10540 		}
10541 
10542 		/*
10543 		 * ignore eom when reading, a fmk should terminate reading
10544 		 */
10545 		if ((sensep->es_eom) &&
10546 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10547 			if ((sensep->es_add_code == 0) &&
10548 			    (sensep->es_qual_code == 4)) {
10549 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10550 				    "bot\n");
10551 				un->un_status = SUN_KEY_BOT;
10552 				pos->eof = ST_NO_EOF;
10553 				pos->lgclblkno = 0;
10554 				pos->fileno = 0;
10555 				pos->blkno = 0;
10556 				if (pos->pmode != legacy)
10557 					pos->pmode = legacy;
10558 			} else {
10559 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10560 				    "eom\n");
10561 				un->un_status = SUN_KEY_EOT;
10562 				pos->eof = ST_EOM;
10563 			}
10564 			st_set_pe_flag(un);
10565 		}
10566 
10567 		break;
10568 
10569 	case KEY_ILLEGAL_REQUEST:
10570 
10571 		if (un->un_laststate >= ST_STATE_OPEN) {
10572 			ST_DO_ERRSTATS(un, st_softerrs);
10573 			severity = SCSI_ERR_FATAL;
10574 		} else {
10575 			severity = SCSI_ERR_INFO;
10576 		}
10577 		break;
10578 
10579 	case KEY_MEDIUM_ERROR:
10580 		ST_DO_ERRSTATS(un, st_harderrs);
10581 		severity = SCSI_ERR_FATAL;
10582 
10583 		/*
10584 		 * for (buffered) writes, a medium error must be fatal
10585 		 */
10586 		if (CDBP(pkt)->scc_cmd != SCMD_WRITE) {
10587 			rval = COMMAND_DONE_ERROR_RECOVERED;
10588 		}
10589 
10590 check_keys:
10591 		/*
10592 		 * attempt to process the keys in the presence of
10593 		 * other errors
10594 		 */
10595 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10596 			/*
10597 			 * Fun with variable length record devices:
10598 			 * for specifying larger blocks sizes than the
10599 			 * actual physical record size.
10600 			 */
10601 			if (un->un_bsize == 0 && resid > 0) {
10602 				/*
10603 				 * XXX! Ugly
10604 				 */
10605 				pkt->pkt_resid = resid;
10606 			} else if (un->un_bsize == 0 && resid < 0) {
10607 				st_bioerror(bp, EINVAL);
10608 			} else {
10609 				severity = SCSI_ERR_FATAL;
10610 				rval = COMMAND_DONE_ERROR;
10611 				st_bioerror(bp, EINVAL);
10612 			}
10613 		}
10614 		if (sensep->es_filmk) {
10615 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10616 			    "filemark\n");
10617 			un->un_status = SUN_KEY_EOF;
10618 			pos->eof = ST_EOF_PENDING;
10619 			st_set_pe_flag(un);
10620 		}
10621 
10622 		/*
10623 		 * ignore eom when reading, a fmk should terminate reading
10624 		 */
10625 		if ((sensep->es_eom) &&
10626 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10627 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10628 			un->un_status = SUN_KEY_EOT;
10629 			pos->eof = ST_EOM;
10630 			st_set_pe_flag(un);
10631 		}
10632 
10633 		break;
10634 
10635 	case KEY_VOLUME_OVERFLOW:
10636 		ST_DO_ERRSTATS(un, st_softerrs);
10637 		pos->eof = ST_EOM;
10638 		severity = SCSI_ERR_FATAL;
10639 		rval = COMMAND_DONE_ERROR;
10640 		goto check_keys;
10641 
10642 	case KEY_HARDWARE_ERROR:
10643 		ST_DO_ERRSTATS(un, st_harderrs);
10644 		severity = SCSI_ERR_FATAL;
10645 		rval = COMMAND_DONE_ERROR;
10646 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10647 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10648 		break;
10649 
10650 	case KEY_BLANK_CHECK:
10651 		ST_DO_ERRSTATS(un, st_softerrs);
10652 		severity = SCSI_ERR_INFO;
10653 
10654 		/*
10655 		 * if not a special request and some data was xferred then it
10656 		 * it is not an error yet
10657 		 */
10658 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10659 			/*
10660 			 * no error for read with or without data xferred
10661 			 */
10662 			un->un_status = SUN_KEY_EOT;
10663 			pos->eof = ST_EOT;
10664 			rval = COMMAND_DONE_ERROR;
10665 			st_set_pe_flag(un);
10666 			goto check_keys;
10667 		} else if (bp != un->un_sbufp &&
10668 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10669 			rval = COMMAND_DONE;
10670 		} else {
10671 			rval = COMMAND_DONE_ERROR_RECOVERED;
10672 		}
10673 
10674 		if (un->un_laststate >= ST_STATE_OPEN) {
10675 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10676 			    "blank check\n");
10677 			pos->eof = ST_EOM;
10678 		}
10679 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10680 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10681 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
10682 		    (un->un_dp->options & ST_KNOWS_EOD)) {
10683 			/*
10684 			 * we were doing a fast forward by skipping
10685 			 * multiple fmk at the time
10686 			 */
10687 			st_bioerror(bp, EIO);
10688 			severity = SCSI_ERR_RECOVERED;
10689 			rval	 = COMMAND_DONE;
10690 		}
10691 		st_set_pe_flag(un);
10692 		goto check_keys;
10693 
10694 	case KEY_WRITE_PROTECT:
10695 		if (st_wrongtapetype(un)) {
10696 			un->un_status = SUN_KEY_WRONGMEDIA;
10697 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10698 			    "wrong tape for writing- use DC6150 tape "
10699 			    "(or equivalent)\n");
10700 			severity = SCSI_ERR_UNKNOWN;
10701 		} else {
10702 			severity = SCSI_ERR_FATAL;
10703 		}
10704 		ST_DO_ERRSTATS(un, st_harderrs);
10705 		rval = COMMAND_DONE_ERROR;
10706 		st_bioerror(bp, EACCES);
10707 		break;
10708 
10709 	case KEY_UNIT_ATTENTION:
10710 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10711 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
10712 
10713 		un->un_unit_attention_flags = 1;
10714 		/*
10715 		 * If we have detected a Bus Reset and the tape
10716 		 * drive has been reserved.
10717 		 */
10718 		if (ST_RQSENSE->es_add_code == 0x29) {
10719 			rval = DEVICE_RESET;
10720 			if ((un->un_rsvd_status &
10721 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
10722 			    ST_RESERVE) {
10723 				un->un_rsvd_status |= ST_LOST_RESERVE;
10724 				ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
10725 				    "st_decode_sense: Lost Reservation\n");
10726 			}
10727 		}
10728 
10729 		/*
10730 		 * If this is a recovery command and retrable, retry.
10731 		 */
10732 		if (bp == un->un_recov_buf) {
10733 			severity = SCSI_ERR_INFO;
10734 			if (attrib->retriable &&
10735 			    (int)un->un_retry_ct++ < st_retry_count) {
10736 				rval = QUE_COMMAND;
10737 			} else {
10738 				rval = COMMAND_DONE_ERROR;
10739 			}
10740 			break; /* Don't set position invalid */
10741 		}
10742 		if (un->un_state <= ST_STATE_OPENING) {
10743 			/*
10744 			 * Look, the tape isn't open yet, now determine
10745 			 * if the cause is a BUS RESET, Save the file
10746 			 * and Block positions for the callers to
10747 			 * recover from the loss of position.
10748 			 */
10749 			severity = SCSI_ERR_INFO;
10750 			if ((pos->pmode != invalid) &&
10751 			    (rval == DEVICE_RESET) &&
10752 			    (un->un_restore_pos != 1)) {
10753 				un->un_save_fileno = pos->fileno;
10754 				un->un_save_blkno = pos->blkno;
10755 				un->un_restore_pos = 1;
10756 			}
10757 
10758 			if (attrib->retriable &&
10759 			    (int)un->un_retry_ct++ < st_retry_count) {
10760 				rval = QUE_COMMAND;
10761 			} else if (rval == DEVICE_RESET) {
10762 				break;
10763 			} else {
10764 				rval = COMMAND_DONE_ERROR;
10765 			}
10766 		/*
10767 		 * Means it thinks the mode parameters have changed.
10768 		 * This is the result of a reset clearing settings or
10769 		 * another initiator changing what we set.
10770 		 */
10771 		} else if (ST_RQSENSE->es_add_code == 0x2a) {
10772 			if (ST_RQSENSE->es_qual_code == 0x1) {
10773 				/* Error recovery will modeselect and retry. */
10774 				rval = DEVICE_TAMPER;
10775 				severity = SCSI_ERR_INFO;
10776 				break; /* don't set position invalid */
10777 			}
10778 			if (ST_RQSENSE->es_qual_code == 0x0 ||
10779 			    ST_RQSENSE->es_qual_code == 0x2 ||
10780 			    ST_RQSENSE->es_qual_code == 0x3 ||
10781 			    ST_RQSENSE->es_qual_code == 0x4 ||
10782 			    ST_RQSENSE->es_qual_code == 0x5 ||
10783 			    ST_RQSENSE->es_qual_code == 0x6 ||
10784 			    ST_RQSENSE->es_qual_code == 0x7) {
10785 				rval = DEVICE_TAMPER;
10786 				severity = SCSI_ERR_INFO;
10787 			}
10788 		} else if (ST_RQSENSE->es_add_code == 0x28 &&
10789 		    ((ST_RQSENSE->es_qual_code == 0x0) ||
10790 		    ST_RQSENSE->es_qual_code == 0x5)) {
10791 			/*
10792 			 * Not Ready to Ready change, Media may have changed.
10793 			 */
10794 			rval = DEVICE_TAMPER;
10795 			severity = SCSI_ERR_RETRYABLE;
10796 		} else {
10797 			if (rval != DEVICE_RESET) {
10798 				rval = COMMAND_DONE_ERROR;
10799 			} else {
10800 				/*
10801 				 * Returning DEVICE_RESET will call
10802 				 * error recovery.
10803 				 */
10804 				severity = SCSI_ERR_INFO;
10805 				break; /* don't set position invalid */
10806 			}
10807 			/*
10808 			 * Check if it is an Unexpected Unit Attention.
10809 			 * If state is >= ST_STATE_OPEN, we have
10810 			 * already done the initialization .
10811 			 * In this case it is Fatal Error
10812 			 * since no further reading/writing
10813 			 * can be done with fileno set to < 0.
10814 			 */
10815 			if (un->un_state >= ST_STATE_OPEN) {
10816 				ST_DO_ERRSTATS(un, st_harderrs);
10817 				severity = SCSI_ERR_FATAL;
10818 			} else {
10819 				severity = SCSI_ERR_INFO;
10820 			}
10821 		}
10822 
10823 		pos->pmode = invalid;
10824 
10825 		break;
10826 
10827 	case KEY_NOT_READY:
10828 		/*
10829 		 * If in process of getting ready retry.
10830 		 */
10831 		if (sensep->es_add_code  == 0x04 &&
10832 		    sensep->es_qual_code == 0x01 &&
10833 		    un->un_retry_ct++ < st_retry_count) {
10834 			rval = QUE_COMMAND;
10835 			severity = SCSI_ERR_INFO;
10836 		} else {
10837 			/* give up */
10838 			rval = COMMAND_DONE_ERROR;
10839 			severity = SCSI_ERR_FATAL;
10840 		}
10841 
10842 		/*
10843 		 * If this was an error and after device opened
10844 		 * do error stats.
10845 		 */
10846 		if (rval == COMMAND_DONE_ERROR &&
10847 		    un->un_state > ST_STATE_OPENING) {
10848 			ST_DO_ERRSTATS(un, st_harderrs);
10849 		}
10850 
10851 		if (ST_RQSENSE->es_add_code == 0x3a) {
10852 			if (st_error_level >= SCSI_ERR_FATAL)
10853 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
10854 				    "Tape not inserted in drive\n");
10855 			un->un_mediastate = MTIO_EJECTED;
10856 			cv_broadcast(&un->un_state_cv);
10857 		}
10858 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
10859 		    (rval != QUE_COMMAND))
10860 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10861 		break;
10862 
10863 	case KEY_ABORTED_COMMAND:
10864 		/* XXX Do drives return this when they see a lost light? */
10865 		/* Testing would say yes */
10866 
10867 		if (un->un_retry_ct++ < st_retry_count) {
10868 			rval = ATTEMPT_RETRY;
10869 			severity = SCSI_ERR_RETRYABLE;
10870 			goto check_keys;
10871 		}
10872 		/*
10873 		 * Probably a parity error...
10874 		 * if we retry here then this may cause data to be
10875 		 * written twice or data skipped during reading
10876 		 */
10877 		ST_DO_ERRSTATS(un, st_harderrs);
10878 		severity = SCSI_ERR_FATAL;
10879 		rval = COMMAND_DONE_ERROR;
10880 		goto check_keys;
10881 
10882 	default:
10883 		/*
10884 		 * Undecoded sense key.	 Try retries and hope
10885 		 * that will fix the problem.  Otherwise, we're
10886 		 * dead.
10887 		 */
10888 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10889 		    "Unhandled Sense Key '%s'\n",
10890 		    sense_keys[un->un_status]);
10891 		ST_DO_ERRSTATS(un, st_harderrs);
10892 		severity = SCSI_ERR_FATAL;
10893 		rval = COMMAND_DONE_ERROR;
10894 		goto check_keys;
10895 	}
10896 
10897 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
10898 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
10899 	    (un->un_laststate > ST_STATE_OPENING) &&
10900 	    (severity >= st_error_level))) {
10901 
10902 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
10903 		    pos->lgclblkno, un->un_err_pos.lgclblkno,
10904 		    scsi_cmds, sensep);
10905 		if (sensep->es_filmk) {
10906 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10907 			    "File Mark Detected\n");
10908 		}
10909 		if (sensep->es_eom) {
10910 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10911 			    "End-of-Media Detected\n");
10912 		}
10913 		if (sensep->es_ili) {
10914 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10915 			    "Incorrect Length Indicator Set\n");
10916 		}
10917 	}
10918 	get_error = geterror(bp);
10919 	if (((rval == COMMAND_DONE_ERROR) ||
10920 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
10921 	    ((get_error == EIO) || (get_error == 0))) {
10922 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
10923 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
10924 		if (un->un_rqs_state & ST_RQS_READ) {
10925 			un->un_rqs_state &= ~(ST_RQS_READ);
10926 		} else {
10927 			un->un_rqs_state |= ST_RQS_OVR;
10928 		}
10929 	}
10930 
10931 	return (rval);
10932 }
10933 
10934 
10935 static int
10936 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
10937 {
10938 	int status = TRAN_ACCEPT;
10939 
10940 	mutex_enter(ST_MUTEX);
10941 
10942 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
10943 
10944 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10945 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
10946 
10947 	/*
10948 	 * Check to see if we hit the retry timeout. We check to make sure
10949 	 * this is the first one on the runq and make sure we have not
10950 	 * queued up any more, so this one has to be the last on the list
10951 	 * also. If it is not, we have to fail.  If it is not the first, but
10952 	 * is the last we are in trouble anyway, as we are in the interrupt
10953 	 * context here.
10954 	 */
10955 	if (((int)un->un_retry_ct > st_retry_count) ||
10956 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
10957 		goto exit;
10958 	}
10959 
10960 	if (un->un_throttle) {
10961 		un->un_last_throttle = un->un_throttle;
10962 		un->un_throttle = 0;
10963 	}
10964 
10965 	/*
10966 	 * Here we know : bp is the first and last one on the runq
10967 	 * it is not necessary to put it back on the head of the
10968 	 * waitq and then move from waitq to runq. Save this queuing
10969 	 * and call scsi_transport.
10970 	 */
10971 	ST_CDB(ST_DEVINFO, "Retry lcmd CDB", (char *)BP_PKT(bp)->pkt_cdbp);
10972 
10973 	status = st_transport(un, BP_PKT(bp));
10974 
10975 	if (status == TRAN_ACCEPT) {
10976 		un->un_tran_retry_ct = 0;
10977 		if (un->un_last_throttle) {
10978 			un->un_throttle = un->un_last_throttle;
10979 		}
10980 		mutex_exit(ST_MUTEX);
10981 
10982 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10983 		    "restart transport \n");
10984 		return (0);
10985 	}
10986 
10987 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
10988 	mutex_exit(ST_MUTEX);
10989 
10990 	if (status == TRAN_BUSY) {
10991 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
10992 			return (0);
10993 		}
10994 	}
10995 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10996 	    "restart transport rejected\n");
10997 	mutex_enter(ST_MUTEX);
10998 	ST_DO_ERRSTATS(un, st_transerrs);
10999 	if (un->un_last_throttle) {
11000 		un->un_throttle = un->un_last_throttle;
11001 	}
11002 exit:
11003 	mutex_exit(ST_MUTEX);
11004 	return (-1);
11005 }
11006 
11007 static int
11008 st_wrongtapetype(struct scsi_tape *un)
11009 {
11010 
11011 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
11012 
11013 	ASSERT(mutex_owned(ST_MUTEX));
11014 
11015 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
11016 
11017 	/*
11018 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
11019 	 */
11020 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
11021 		switch (un->un_dp->type) {
11022 		case ST_TYPE_WANGTEK:
11023 		case ST_TYPE_ARCHIVE:
11024 			/*
11025 			 * If this really worked, we could go off of
11026 			 * the density codes set in the modesense
11027 			 * page. For this drive, 0x10 == QIC-120,
11028 			 * 0xf == QIC-150, and 0x5 should be for
11029 			 * both QIC-24 and, maybe, QIC-11. However,
11030 			 * the h/w doesn't do what the manual says
11031 			 * that it should, so we'll key off of
11032 			 * getting a WRITE PROTECT error AND wp *not*
11033 			 * set in the mode sense information.
11034 			 */
11035 			/*
11036 			 * XXX but we already know that status is
11037 			 * write protect, so don't check it again.
11038 			 */
11039 
11040 			if (un->un_status == KEY_WRITE_PROTECT &&
11041 			    un->un_mspl->wp == 0) {
11042 				return (1);
11043 			}
11044 			break;
11045 		default:
11046 			break;
11047 		}
11048 	}
11049 	return (0);
11050 }
11051 
11052 static errstate
11053 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
11054 {
11055 	errstate action;
11056 
11057 	ST_FUNC(ST_DEVINFO, st_check_error);
11058 
11059 	ASSERT(mutex_owned(ST_MUTEX));
11060 
11061 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
11062 
11063 	if (SCBP_C(pkt) == STATUS_RESERVATION_CONFLICT) {
11064 		action = COMMAND_DONE_EACCES;
11065 		un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
11066 	} else if (SCBP(pkt)->sts_busy) {
11067 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
11068 		if ((int)un->un_retry_ct++ < st_retry_count) {
11069 			action = QUE_BUSY_COMMAND;
11070 		} else if ((un->un_rsvd_status &
11071 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
11072 			/*
11073 			 * If this is a command done before reserve is done
11074 			 * don't reset.
11075 			 */
11076 			action = COMMAND_DONE_ERROR;
11077 		} else {
11078 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11079 			    "unit busy too long\n");
11080 			(void) st_reset(un, RESET_ALL);
11081 			action = COMMAND_DONE_ERROR;
11082 		}
11083 	} else if (SCBP(pkt)->sts_chk) {
11084 		/*
11085 		 * we should only get here if the auto rqsense failed
11086 		 * thru a uscsi cmd without autorequest sense
11087 		 * so we just try again
11088 		 */
11089 		action = QUE_SENSE;
11090 	} else {
11091 		action = COMMAND_DONE;
11092 	}
11093 	return (action);
11094 }
11095 
11096 static void
11097 st_calc_bnum(struct scsi_tape *un, struct buf *bp, struct scsi_pkt *pkt)
11098 {
11099 	int nblks;
11100 	long count;
11101 	recov_info *ri = (recov_info *)pkt->pkt_private;
11102 	cmd_attribute const *attrib;
11103 
11104 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
11105 
11106 	ASSERT(mutex_owned(ST_MUTEX));
11107 
11108 	if (ri->privatelen == sizeof (recov_info)) {
11109 		attrib = ri->cmd_attrib;
11110 		ASSERT(attrib->recov_pos_type == POS_EXPECTED);
11111 		ASSERT(attrib->chg_tape_pos);
11112 	} else {
11113 		ri = NULL;
11114 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
11115 	}
11116 
11117 	count = bp->b_bcount - bp->b_resid;
11118 
11119 	/* If variable block mode */
11120 	if (un->un_bsize == 0) {
11121 		nblks = ((count == 0) ? 0 : 1);
11122 		un->un_kbytes_xferred += (count / ONE_K);
11123 	} else {
11124 		nblks = (count / un->un_bsize);
11125 		un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
11126 	}
11127 
11128 	/*
11129 	 * If some command failed after this one started and it seems
11130 	 * to have finshed without error count the position.
11131 	 */
11132 	if (un->un_persistence && un->un_persist_errors) {
11133 		ASSERT(un->un_pos.pmode != invalid);
11134 	}
11135 
11136 	if (attrib->chg_tape_direction == DIR_FORW) {
11137 		un->un_pos.blkno += nblks;
11138 		un->un_pos.lgclblkno += nblks;
11139 	} else if (attrib->chg_tape_direction == DIR_REVC) {
11140 		un->un_pos.blkno -= nblks;
11141 		un->un_pos.lgclblkno -= nblks;
11142 	} else {
11143 		ASSERT(0);
11144 	}
11145 
11146 	/* recovery disabled */
11147 	if (ri == NULL) {
11148 		un->un_running.pmode = invalid;
11149 		return;
11150 	}
11151 
11152 	/*
11153 	 * If we didn't just read a filemark.
11154 	 */
11155 	if (un->un_pos.eof != ST_EOF_PENDING) {
11156 		ASSERT(nblks != 0);
11157 		/*
11158 		 * If Previously calulated expected position does not match
11159 		 * debug the expected position.
11160 		 */
11161 		if ((ri->pos.pmode != invalid) && nblks &&
11162 		    ((un->un_pos.blkno != ri->pos.blkno) ||
11163 		    (un->un_pos.lgclblkno != ri->pos.lgclblkno))) {
11164 #ifdef STDEBUG
11165 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11166 			    "Expected", &ri->pos);
11167 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11168 			    "But Got", &un->un_pos);
11169 #endif
11170 			un->un_running.pmode = invalid;
11171 		}
11172 	} else {
11173 		ASSERT(nblks == 0);
11174 		if (un->un_running.pmode != invalid) {
11175 			/*
11176 			 * blkno and lgclblkno already counted in
11177 			 * st_add_recovery_info_to_pkt(). Since a block was not
11178 			 * read and a filemark was.
11179 			 */
11180 			if (attrib->chg_tape_direction == DIR_FORW) {
11181 				un->un_running.fileno++;
11182 				un->un_running.blkno = 0;
11183 			} else if (attrib->chg_tape_direction == DIR_REVC) {
11184 				un->un_running.fileno--;
11185 				un->un_running.blkno = LASTBLK;
11186 			}
11187 		}
11188 	}
11189 }
11190 
11191 static void
11192 st_set_state(struct scsi_tape *un, struct buf *bp)
11193 {
11194 	struct scsi_pkt *sp = BP_PKT(bp);
11195 	struct uscsi_cmd *ucmd;
11196 
11197 	ST_FUNC(ST_DEVINFO, st_set_state);
11198 
11199 	ASSERT(mutex_owned(ST_MUTEX));
11200 
11201 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11202 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
11203 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
11204 
11205 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
11206 #ifdef STDEBUG
11207 		if (DEBUGGING && sp->pkt_resid) {
11208 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11209 			    "pkt_resid %ld bcount %ld\n",
11210 			    sp->pkt_resid, bp->b_bcount);
11211 		}
11212 #endif
11213 		bp->b_resid = sp->pkt_resid;
11214 		st_calc_bnum(un, bp, sp);
11215 		if (bp->b_flags & B_READ) {
11216 			un->un_lastop = ST_OP_READ;
11217 			un->un_fmneeded = 0;
11218 		} else {
11219 			un->un_lastop = ST_OP_WRITE;
11220 			if (un->un_dp->options & ST_REEL) {
11221 				un->un_fmneeded = 2;
11222 			} else {
11223 				un->un_fmneeded = 1;
11224 			}
11225 		}
11226 		/*
11227 		 * all is honky dory at this point, so let's
11228 		 * readjust the throttle, to increase speed, if we
11229 		 * have not throttled down.
11230 		 */
11231 		if (un->un_throttle) {
11232 			un->un_throttle = un->un_max_throttle;
11233 		}
11234 	} else {
11235 		optype new_lastop;
11236 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
11237 
11238 		un->un_lastop = ST_OP_CTL;
11239 
11240 		switch (cmd) {
11241 		case SCMD_WRITE:
11242 		case SCMD_WRITE_G4:
11243 			bp->b_resid = sp->pkt_resid;
11244 			new_lastop = ST_OP_WRITE;
11245 			st_calc_bnum(un, bp, sp);
11246 			if (un->un_dp->options & ST_REEL) {
11247 				un->un_fmneeded = 2;
11248 			} else {
11249 				un->un_fmneeded = 1;
11250 			}
11251 			break;
11252 		case SCMD_READ:
11253 		case SCMD_READ_G4:
11254 			bp->b_resid = sp->pkt_resid;
11255 			new_lastop = ST_OP_READ;
11256 			st_calc_bnum(un, bp, sp);
11257 			un->un_fmneeded = 0;
11258 			break;
11259 		case SCMD_WRITE_FILE_MARK_G4:
11260 		case SCMD_WRITE_FILE_MARK:
11261 		{
11262 			int fmdone;
11263 
11264 			if (un->un_pos.eof != ST_EOM) {
11265 				un->un_pos.eof = ST_NO_EOF;
11266 			}
11267 			fmdone = (bp->b_bcount - bp->b_resid);
11268 			if (fmdone > 0) {
11269 				un->un_lastop = new_lastop = ST_OP_WEOF;
11270 				un->un_pos.lgclblkno += fmdone;
11271 				un->un_pos.fileno += fmdone;
11272 				un->un_pos.blkno = 0;
11273 			} else {
11274 				new_lastop = ST_OP_CTL;
11275 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11276 				    "Flushed buffer\n");
11277 			}
11278 			if (fmdone > un->un_fmneeded) {
11279 				un->un_fmneeded = 0;
11280 			} else {
11281 				un->un_fmneeded -= fmdone;
11282 			}
11283 			break;
11284 		}
11285 		case SCMD_REWIND:
11286 			un->un_pos.eof = ST_NO_EOF;
11287 			un->un_pos.fileno = 0;
11288 			un->un_pos.blkno = 0;
11289 			un->un_pos.lgclblkno = 0;
11290 			if (un->un_pos.pmode != legacy)
11291 				un->un_pos.pmode = legacy;
11292 			new_lastop = ST_OP_CTL;
11293 			un->un_restore_pos = 0;
11294 			break;
11295 
11296 		case SCMD_SPACE:
11297 		case SCMD_SPACE_G4:
11298 		{
11299 			int64_t count;
11300 			int64_t resid;
11301 			int64_t done;
11302 			cmd_attribute const *attrib;
11303 			recov_info *ri = (recov_info *)sp->pkt_private;
11304 
11305 			if (ri->privatelen == sizeof (recov_info)) {
11306 				attrib = ri->cmd_attrib;
11307 			} else {
11308 				attrib =
11309 				    st_lookup_cmd_attribute(sp->pkt_cdbp[0]);
11310 			}
11311 
11312 			resid = (int64_t)SPACE_CNT(bp->b_resid);
11313 			count = (int64_t)attrib->get_cnt(sp->pkt_cdbp);
11314 
11315 			if (count >= 0) {
11316 				done = (count - resid);
11317 			} else {
11318 				done = ((-count) - resid);
11319 			}
11320 			if (done > 0) {
11321 				un->un_lastop = new_lastop = ST_OP_CTL;
11322 			} else {
11323 				new_lastop = ST_OP_CTL;
11324 			}
11325 
11326 			ST_SPAC(ST_DEVINFO, st_label, SCSI_DEBUG,
11327 			    "space cmd: cdb[1] = %s\n"
11328 			    "space data:       = 0x%lx\n"
11329 			    "space count:      = %"PRId64"\n"
11330 			    "space resid:      = %"PRId64"\n"
11331 			    "spaces done:      = %"PRId64"\n"
11332 			    "fileno before     = %d\n"
11333 			    "blkno before      = %d\n",
11334 			    space_strs[sp->pkt_cdbp[1] & 7],
11335 			    bp->b_bcount,
11336 			    count, resid, done,
11337 			    un->un_pos.fileno, un->un_pos.blkno);
11338 
11339 			switch (sp->pkt_cdbp[1]) {
11340 			case SPACE_TYPE(SP_FLM):
11341 				/* Space file forward */
11342 				if (count >= 0) {
11343 					if (un->un_pos.eof <= ST_EOF) {
11344 						un->un_pos.eof = ST_NO_EOF;
11345 					}
11346 					un->un_pos.fileno += done;
11347 					un->un_pos.blkno = 0;
11348 					break;
11349 				}
11350 				/* Space file backward */
11351 				if (done > un->un_pos.fileno) {
11352 					un->un_pos.fileno = 0;
11353 					un->un_pos.blkno = 0;
11354 				} else {
11355 					un->un_pos.fileno -= done;
11356 					un->un_pos.blkno = LASTBLK;
11357 					un->un_running.pmode = invalid;
11358 				}
11359 				break;
11360 			case SPACE_TYPE(SP_BLK):
11361 				/* Space block forward */
11362 				if (count >= 0) {
11363 					un->un_pos.blkno += done;
11364 					break;
11365 				}
11366 				/* Space block backward */
11367 				if (un->un_pos.eof >= ST_EOF_PENDING) {
11368 				/*
11369 				 * we stepped back into
11370 				 * a previous file; we are not
11371 				 * making an effort to pretend that
11372 				 * we are still in the current file
11373 				 * ie. logical == physical position
11374 				 * and leave it to st_ioctl to correct
11375 				 */
11376 					if (done > un->un_pos.blkno) {
11377 						un->un_pos.blkno = 0;
11378 					} else {
11379 						un->un_pos.fileno--;
11380 						un->un_pos.blkno = LASTBLK;
11381 						un->un_running.pmode = invalid;
11382 					}
11383 				} else {
11384 					un->un_pos.blkno -= done;
11385 				}
11386 				break;
11387 			case SPACE_TYPE(SP_SQFLM):
11388 				un->un_pos.pmode = logical;
11389 				un->un_pos.blkno = 0;
11390 				un->un_lastop = new_lastop = ST_OP_CTL;
11391 				break;
11392 			case SPACE_TYPE(SP_EOD):
11393 				un->un_pos.pmode = logical;
11394 				un->un_pos.eof = ST_EOM;
11395 				un->un_status = KEY_BLANK_CHECK;
11396 				break;
11397 			default:
11398 				un->un_pos.pmode = invalid;
11399 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11400 				    "Unsupported space cmd: %s\n",
11401 				    space_strs[sp->pkt_cdbp[1] & 7]);
11402 
11403 				un->un_lastop = new_lastop = ST_OP_CTL;
11404 			}
11405 
11406 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11407 			    "after_space rs %"PRId64" fil %d blk %d\n",
11408 			    resid, un->un_pos.fileno, un->un_pos.blkno);
11409 
11410 			break;
11411 		}
11412 		case SCMD_LOAD:
11413 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
11414 				un->un_pos.fileno = 0;
11415 				if (un->un_pos.pmode != legacy)
11416 					un->un_pos.pmode = legacy;
11417 			} else {
11418 				un->un_state = ST_STATE_OFFLINE;
11419 				un->un_pos.pmode = invalid;
11420 			}
11421 			un->un_density_known = 0;
11422 			un->un_pos.eof = ST_NO_EOF;
11423 			un->un_pos.blkno = 0;
11424 			un->un_lastop = new_lastop = ST_OP_CTL;
11425 			break;
11426 		case SCMD_ERASE:
11427 			un->un_pos.eof = ST_NO_EOF;
11428 			un->un_pos.blkno = 0;
11429 			un->un_pos.fileno = 0;
11430 			un->un_pos.lgclblkno = 0;
11431 			if (un->un_pos.pmode != legacy)
11432 				un->un_pos.pmode = legacy;
11433 			new_lastop = ST_OP_CTL;
11434 			break;
11435 		case SCMD_RESERVE:
11436 			un->un_rsvd_status |= ST_RESERVE;
11437 			un->un_rsvd_status &=
11438 			    ~(ST_RELEASE | ST_LOST_RESERVE |
11439 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11440 			new_lastop = un->un_lastop;
11441 			break;
11442 		case SCMD_RELEASE:
11443 			un->un_rsvd_status |= ST_RELEASE;
11444 			un->un_rsvd_status &=
11445 			    ~(ST_RESERVE | ST_LOST_RESERVE |
11446 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11447 			new_lastop = ST_OP_CTL;
11448 			break;
11449 		case SCMD_PERSISTENT_RESERVE_IN:
11450 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11451 			    "PGR_IN command\n");
11452 			break;
11453 		case SCMD_PERSISTENT_RESERVE_OUT:
11454 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
11455 			case ST_SA_SCSI3_RESERVE:
11456 			case ST_SA_SCSI3_PREEMPT:
11457 			case ST_SA_SCSI3_PREEMPTANDABORT:
11458 				un->un_rsvd_status |=
11459 				    ST_APPLICATION_RESERVATIONS;
11460 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11461 				    "PGR Reserve and set: entering"
11462 				    " ST_APPLICATION_RESERVATIONS mode");
11463 				break;
11464 			case ST_SA_SCSI3_RELEASE:
11465 			case ST_SA_SCSI3_CLEAR:
11466 				un->un_rsvd_status &=
11467 				    ~ST_APPLICATION_RESERVATIONS;
11468 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11469 				    "PGR Release and reset: exiting"
11470 				    " ST_APPLICATION_RESERVATIONS mode");
11471 				break;
11472 			}
11473 			break;
11474 		case SCMD_TEST_UNIT_READY:
11475 		case SCMD_READ_BLKLIM:
11476 		case SCMD_REQUEST_SENSE:
11477 		case SCMD_INQUIRY:
11478 		case SCMD_RECOVER_BUF:
11479 		case SCMD_MODE_SELECT:
11480 		case SCMD_MODE_SENSE:
11481 		case SCMD_DOORLOCK:
11482 		case SCMD_READ_BUFFER:
11483 		case SCMD_REPORT_DENSITIES:
11484 		case SCMD_LOG_SELECT_G1:
11485 		case SCMD_LOG_SENSE_G1:
11486 		case SCMD_REPORT_LUNS:
11487 		case SCMD_READ_ATTRIBUTE:
11488 		case SCMD_WRITE_ATTRIBUTE:
11489 		case SCMD_SVC_ACTION_IN_G5:
11490 			new_lastop = ST_OP_CTL;
11491 			break;
11492 		case SCMD_READ_POSITION:
11493 			new_lastop = ST_OP_CTL;
11494 			/*
11495 			 * Only if the buf used was un_sbufp.
11496 			 * Among other things the prevents read positions used
11497 			 * as part of error recovery from messing up our
11498 			 * current position as they will use un_recov_buf.
11499 			 */
11500 			if (USCSI_CMD(bp)) {
11501 				(void) st_get_read_pos(un, bp);
11502 			}
11503 			break;
11504 		case SCMD_LOCATE:
11505 		case SCMD_LOCATE_G4:
11506 			/* Locate makes position mode no longer legacy */
11507 			un->un_lastop = new_lastop = ST_OP_CTL;
11508 			break;
11509 		default:
11510 			/*
11511 			 * Unknown command, If was USCSI and USCSI_SILENT
11512 			 * flag was not set, set position to unknown.
11513 			 */
11514 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
11515 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
11516 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11517 				    "unknown cmd 0x%X caused loss of state\n",
11518 				    cmd);
11519 			} else {
11520 				break;
11521 			}
11522 			/* FALLTHROUGH */
11523 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
11524 			un->un_pos.pmode = invalid;
11525 			un->un_lastop = new_lastop = ST_OP_CTL;
11526 			break;
11527 		}
11528 
11529 		/* new_lastop should have been changed */
11530 		ASSERT(new_lastop != ST_OP_NIL);
11531 
11532 		/* If un_lastop should copy new_lastop  */
11533 		if (((un->un_lastop == ST_OP_WRITE) ||
11534 		    (un->un_lastop == ST_OP_WEOF)) &&
11535 		    new_lastop != ST_OP_CTL) {
11536 			un->un_lastop = new_lastop;
11537 		}
11538 	}
11539 
11540 	/*
11541 	 * In the st driver we have a logical and physical file position.
11542 	 * Under BSD behavior, when you get a zero read, the logical position
11543 	 * is before the filemark but after the last record of the file.
11544 	 * The physical position is after the filemark. MTIOCGET should always
11545 	 * return the logical file position.
11546 	 *
11547 	 * The next read gives a silent skip to the next file.
11548 	 * Under SVR4, the logical file position remains before the filemark
11549 	 * until the file is closed or a space operation is performed.
11550 	 * Hence set err_resid and err_file before changing fileno if case
11551 	 * BSD Behaviour.
11552 	 */
11553 	un->un_err_resid = bp->b_resid;
11554 	COPY_POS(&un->un_err_pos, &un->un_pos);
11555 	un->un_retry_ct = 0;
11556 
11557 
11558 	/*
11559 	 * If we've seen a filemark via the last read operation
11560 	 * advance the file counter, but mark things such that
11561 	 * the next read operation gets a zero count. We have
11562 	 * to put this here to handle the case of sitting right
11563 	 * at the end of a tape file having seen the file mark,
11564 	 * but the tape is closed and then re-opened without
11565 	 * any further i/o. That is, the position information
11566 	 * must be updated before a close.
11567 	 */
11568 
11569 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
11570 		/*
11571 		 * If we're a 1/2" tape, and we get a filemark
11572 		 * right on block 0, *AND* we were not in the
11573 		 * first file on the tape, and we've hit logical EOM.
11574 		 * We'll mark the state so that later we do the
11575 		 * right thing (in st_close(), st_strategy() or
11576 		 * st_ioctl()).
11577 		 *
11578 		 */
11579 		if ((un->un_dp->options & ST_REEL) &&
11580 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
11581 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
11582 			un->un_pos.eof = ST_EOT_PENDING;
11583 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11584 			    "eot pending\n");
11585 			un->un_pos.fileno++;
11586 			un->un_pos.blkno = 0;
11587 		} else if (BSD_BEHAVIOR) {
11588 			/*
11589 			 * If the read of the filemark was a side effect
11590 			 * of reading some blocks (i.e., data was actually
11591 			 * read), then the EOF mark is pending and the
11592 			 * bump into the next file awaits the next read
11593 			 * operation (which will return a zero count), or
11594 			 * a close or a space operation, else the bump
11595 			 * into the next file occurs now.
11596 			 */
11597 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11598 			    "resid=%lx, bcount=%lx\n",
11599 			    bp->b_resid, bp->b_bcount);
11600 
11601 			if (bp->b_resid != bp->b_bcount) {
11602 				un->un_pos.eof = ST_EOF;
11603 			} else {
11604 				un->un_silent_skip = 1;
11605 				un->un_pos.eof = ST_NO_EOF;
11606 				un->un_pos.fileno++;
11607 				un->un_pos.lgclblkno++;
11608 				un->un_save_blkno = un->un_pos.blkno;
11609 				un->un_pos.blkno = 0;
11610 			}
11611 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11612 			    "eof of file %d, eof=%d\n",
11613 			    un->un_pos.fileno, un->un_pos.eof);
11614 		} else if (SVR4_BEHAVIOR) {
11615 			/*
11616 			 * If the read of the filemark was a side effect
11617 			 * of reading some blocks (i.e., data was actually
11618 			 * read), then the next read should return 0
11619 			 */
11620 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11621 			    "resid=%lx, bcount=%lx\n",
11622 			    bp->b_resid, bp->b_bcount);
11623 			if (bp->b_resid == bp->b_bcount) {
11624 				un->un_pos.eof = ST_EOF;
11625 			}
11626 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11627 			    "eof of file=%d, eof=%d\n",
11628 			    un->un_pos.fileno, un->un_pos.eof);
11629 		}
11630 	}
11631 }
11632 
11633 /*
11634  * set the correct un_errno, to take corner cases into consideration
11635  */
11636 static void
11637 st_set_pe_errno(struct scsi_tape *un)
11638 {
11639 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
11640 
11641 	ASSERT(mutex_owned(ST_MUTEX));
11642 
11643 	/* if errno is already set, don't reset it */
11644 	if (un->un_errno)
11645 		return;
11646 
11647 	/* here un_errno == 0 */
11648 	/*
11649 	 * if the last transfer before flushing all the
11650 	 * waiting I/O's, was 0 (resid = count), then we
11651 	 * want to give the user an error on all the rest,
11652 	 * so here.  If there was a transfer, we set the
11653 	 * resid and counts to 0, and let it drop through,
11654 	 * giving a zero return.  the next I/O will then
11655 	 * give an error.
11656 	 */
11657 	if (un->un_last_resid == un->un_last_count) {
11658 		switch (un->un_pos.eof) {
11659 		case ST_EOM:
11660 			un->un_errno = ENOMEM;
11661 			break;
11662 		case ST_EOT:
11663 		case ST_EOF:
11664 			un->un_errno = EIO;
11665 			break;
11666 		}
11667 	} else {
11668 		/*
11669 		 * we know they did not have a zero, so make
11670 		 * sure they get one
11671 		 */
11672 		un->un_last_resid = un->un_last_count = 0;
11673 	}
11674 }
11675 
11676 
11677 /*
11678  * send in a marker pkt to terminate flushing of commands by BBA (via
11679  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
11680  */
11681 static void
11682 st_hba_unflush(struct scsi_tape *un)
11683 {
11684 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
11685 
11686 	ASSERT(mutex_owned(ST_MUTEX));
11687 
11688 	if (!un->un_flush_on_errors)
11689 		return;
11690 
11691 #ifdef FLUSH_ON_ERRORS
11692 
11693 	if (!un->un_mkr_pkt) {
11694 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
11695 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
11696 
11697 		/* we slept, so it must be there */
11698 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
11699 	}
11700 
11701 	st_transport(un, un->un_mkr_pkt);
11702 #endif
11703 }
11704 
11705 static char *
11706 st_print_scsi_cmd(char cmd)
11707 {
11708 	char tmp[64];
11709 	char *cpnt;
11710 
11711 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
11712 	/* tmp goes out of scope on return and caller sees garbage */
11713 	if (cpnt == tmp) {
11714 		cpnt = "Unknown Command";
11715 	}
11716 	return (cpnt);
11717 }
11718 
11719 static void
11720 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
11721     char *title, char *cdb)
11722 {
11723 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
11724 	char buf[256];
11725 	struct scsi_tape *un;
11726 	int instance = ddi_get_instance(dip);
11727 
11728 	un = ddi_get_soft_state(st_state, instance);
11729 
11730 	ST_FUNC(dip, st_print_cdb);
11731 
11732 #ifdef STDEBUG
11733 	if ((st_debug & 0x180) == 0x100) {
11734 		scsi_log(dip, label, level, "node %s cmd %s\n",
11735 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
11736 		return;
11737 	}
11738 #endif
11739 	(void) sprintf(buf, "%s for cmd(%s)", title, st_print_scsi_cmd(*cdb));
11740 	st_clean_print(dip, label, level, buf, cdb, len);
11741 }
11742 
11743 static void
11744 st_clean_print(dev_info_t *dev, char *label, uint_t level,
11745     char *title, char *data, int len)
11746 {
11747 	int	i;
11748 	int 	c;
11749 	char	*format;
11750 	char	buf[256];
11751 	uchar_t	byte;
11752 
11753 	ST_FUNC(dev, st_clean_print);
11754 
11755 
11756 	(void) sprintf(buf, "%s:\n", title);
11757 	scsi_log(dev, label, level, "%s", buf);
11758 	level = CE_CONT;
11759 	for (i = 0; i < len; ) {
11760 		buf[0] = 0;
11761 		for (c = 0; c < 8 && i < len; c++, i++) {
11762 			byte = (uchar_t)data[i];
11763 			if (byte < 0x10)
11764 				format = "0x0%x ";
11765 			else
11766 				format = "0x%x ";
11767 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
11768 		}
11769 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
11770 
11771 		scsi_log(dev, label, level, "%s\n", buf);
11772 	}
11773 }
11774 
11775 /*
11776  * Conditionally enabled debugging
11777  */
11778 #ifdef	STDEBUG
11779 static void
11780 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
11781 {
11782 	char tmpbuf[64];
11783 
11784 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
11785 
11786 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11787 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
11788 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
11789 	    count, count,
11790 	    wait == ASYNC_CMD ? "a" : "");
11791 }
11792 
11793 /*
11794  * Returns pointer to name of minor node name of device 'dev'.
11795  */
11796 static char *
11797 st_dev_name(dev_t dev)
11798 {
11799 	struct scsi_tape *un;
11800 	const char density[] = { 'l', 'm', 'h', 'c' };
11801 	static char name[32];
11802 	minor_t minor;
11803 	int instance;
11804 	int nprt = 0;
11805 
11806 	minor = getminor(dev);
11807 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
11808 	un = ddi_get_soft_state(st_state, instance);
11809 	if (un) {
11810 		ST_FUNC(ST_DEVINFO, st_dev_name);
11811 	}
11812 
11813 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
11814 
11815 	if (minor & MT_BSD) {
11816 		name[++nprt] = 'b';
11817 	}
11818 
11819 	if (minor & MT_NOREWIND) {
11820 		name[++nprt] = 'n';
11821 	}
11822 
11823 	/* NULL terminator */
11824 	name[++nprt] = 0;
11825 
11826 	return (name);
11827 }
11828 #endif	/* STDEBUG */
11829 
11830 /*
11831  * Soft error reporting, so far unique to each drive
11832  *
11833  * Currently supported: exabyte and DAT soft error reporting
11834  */
11835 static int
11836 st_report_exabyte_soft_errors(dev_t dev, int flag)
11837 {
11838 	uchar_t *sensep;
11839 	int amt;
11840 	int rval = 0;
11841 	char cdb[CDB_GROUP0], *c = cdb;
11842 	struct uscsi_cmd *com;
11843 
11844 	GET_SOFT_STATE(dev);
11845 
11846 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
11847 
11848 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11849 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
11850 	    dev, flag);
11851 
11852 	ASSERT(mutex_owned(ST_MUTEX));
11853 
11854 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
11855 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
11856 
11857 	*c++ = SCMD_REQUEST_SENSE;
11858 	*c++ = 0;
11859 	*c++ = 0;
11860 	*c++ = 0;
11861 	*c++ = TAPE_SENSE_LENGTH;
11862 	/*
11863 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
11864 	 */
11865 	*c   = (char)0x80;
11866 
11867 	com->uscsi_cdb = cdb;
11868 	com->uscsi_cdblen = CDB_GROUP0;
11869 	com->uscsi_bufaddr = (caddr_t)sensep;
11870 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
11871 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11872 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11873 
11874 	rval = st_uscsi_cmd(un, com, FKIOCTL);
11875 	if (rval || com->uscsi_status) {
11876 		goto done;
11877 	}
11878 
11879 	/*
11880 	 * was there enough data?
11881 	 */
11882 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
11883 
11884 	if ((amt >= 19) && un->un_kbytes_xferred) {
11885 		uint_t count, error_rate;
11886 		uint_t rate;
11887 
11888 		if (sensep[21] & CLN) {
11889 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11890 			    "Periodic head cleaning required");
11891 		}
11892 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
11893 			goto done;
11894 		}
11895 		/*
11896 		 * check if soft error reporting needs to be done.
11897 		 */
11898 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
11899 		count &= 0xffffff;
11900 		error_rate = (count * 100)/un->un_kbytes_xferred;
11901 
11902 #ifdef	STDEBUG
11903 		if (st_soft_error_report_debug) {
11904 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11905 			    "Exabyte Soft Error Report:\n");
11906 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11907 			    "read/write error counter: %d\n", count);
11908 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11909 			    "number of bytes transferred: %dK\n",
11910 			    un->un_kbytes_xferred);
11911 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11912 			    "error_rate: %d%%\n", error_rate);
11913 
11914 			if (amt >= 22) {
11915 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11916 				    "unit sense: 0x%b 0x%b 0x%b\n",
11917 				    sensep[19], SENSE_19_BITS,
11918 				    sensep[20], SENSE_20_BITS,
11919 				    sensep[21], SENSE_21_BITS);
11920 			}
11921 			if (amt >= 27) {
11922 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11923 				    "tracking retry counter: %d\n",
11924 				    sensep[26]);
11925 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11926 				    "read/write retry counter: %d\n",
11927 				    sensep[27]);
11928 			}
11929 		}
11930 #endif
11931 
11932 		if (flag & FWRITE) {
11933 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
11934 		} else {
11935 			rate = EXABYTE_READ_ERROR_THRESHOLD;
11936 		}
11937 		if (error_rate >= rate) {
11938 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11939 			    "Soft error rate (%d%%) during %s was too high",
11940 			    error_rate,
11941 			    ((flag & FWRITE) ? wrg_str : rdg_str));
11942 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11943 			    "Please, replace tape cartridge\n");
11944 		}
11945 	}
11946 
11947 done:
11948 	kmem_free(com, sizeof (*com));
11949 	kmem_free(sensep, TAPE_SENSE_LENGTH);
11950 
11951 	if (rval != 0) {
11952 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
11953 		    "exabyte soft error reporting failed\n");
11954 	}
11955 	return (rval);
11956 }
11957 
11958 /*
11959  * this is very specific to Archive 4mm dat
11960  */
11961 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
11962 
11963 static int
11964 st_report_dat_soft_errors(dev_t dev, int flag)
11965 {
11966 	uchar_t *sensep;
11967 	int amt, i;
11968 	int rval = 0;
11969 	char cdb[CDB_GROUP1], *c = cdb;
11970 	struct uscsi_cmd *com;
11971 
11972 	GET_SOFT_STATE(dev);
11973 
11974 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
11975 
11976 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11977 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
11978 
11979 	ASSERT(mutex_owned(ST_MUTEX));
11980 
11981 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
11982 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
11983 
11984 	*c++ = SCMD_LOG_SENSE_G1;
11985 	*c++ = 0;
11986 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
11987 	*c++ = 0;
11988 	*c++ = 0;
11989 	*c++ = 0;
11990 	*c++ = 2;
11991 	*c++ = 0;
11992 	*c++ = (char)LOG_SENSE_LENGTH;
11993 	*c   = 0;
11994 	com->uscsi_cdb    = cdb;
11995 	com->uscsi_cdblen  = CDB_GROUP1;
11996 	com->uscsi_bufaddr = (caddr_t)sensep;
11997 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
11998 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11999 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12000 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12001 	if (rval) {
12002 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12003 		    "DAT soft error reporting failed\n");
12004 	}
12005 	if (rval || com->uscsi_status) {
12006 		goto done;
12007 	}
12008 
12009 	/*
12010 	 * was there enough data?
12011 	 */
12012 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
12013 
12014 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
12015 		int total, retries, param_code;
12016 
12017 		total = -1;
12018 		retries = -1;
12019 		amt = sensep[3] + 4;
12020 
12021 
12022 #ifdef STDEBUG
12023 		if (st_soft_error_report_debug) {
12024 			(void) printf("logsense:");
12025 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
12026 				if (i % 16 == 0) {
12027 					(void) printf("\t\n");
12028 				}
12029 				(void) printf(" %x", sensep[i]);
12030 			}
12031 			(void) printf("\n");
12032 		}
12033 #endif
12034 
12035 		/*
12036 		 * parse the param_codes
12037 		 */
12038 		if (sensep[0] == 2 || sensep[0] == 3) {
12039 			for (i = 4; i < amt; i++) {
12040 				param_code = (sensep[i++] << 8);
12041 				param_code += sensep[i++];
12042 				i++; /* skip control byte */
12043 				if (param_code == 5) {
12044 					if (sensep[i++] == 4) {
12045 						total = (sensep[i++] << 24);
12046 						total += (sensep[i++] << 16);
12047 						total += (sensep[i++] << 8);
12048 						total += sensep[i];
12049 					}
12050 				} else if (param_code == 0x8007) {
12051 					if (sensep[i++] == 2) {
12052 						retries = sensep[i++] << 8;
12053 						retries += sensep[i];
12054 					}
12055 				} else {
12056 					i += sensep[i];
12057 				}
12058 			}
12059 		}
12060 
12061 		/*
12062 		 * if the log sense returned valid numbers then determine
12063 		 * the read and write error thresholds based on the amount of
12064 		 * data transferred
12065 		 */
12066 
12067 		if (total > 0 && retries > 0) {
12068 			short normal_retries = 0;
12069 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12070 			    "total xferred (%s) =%x, retries=%x\n",
12071 			    ((flag & FWRITE) ? wrg_str : rdg_str),
12072 			    total, retries);
12073 
12074 			if (flag & FWRITE) {
12075 				if (total <=
12076 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
12077 					normal_retries =
12078 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
12079 				} else {
12080 					normal_retries =
12081 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
12082 				}
12083 			} else {
12084 				if (total <=
12085 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
12086 					normal_retries =
12087 					    DAT_SMALL_READ_ERROR_THRESHOLD;
12088 				} else {
12089 					normal_retries =
12090 					    DAT_LARGE_READ_ERROR_THRESHOLD;
12091 				}
12092 			}
12093 
12094 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12095 			"normal retries=%d\n", normal_retries);
12096 
12097 			if (retries >= normal_retries) {
12098 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12099 				    "Soft error rate (retries = %d) during "
12100 				    "%s was too high",  retries,
12101 				    ((flag & FWRITE) ? wrg_str : rdg_str));
12102 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12103 				    "Periodic head cleaning required "
12104 				    "and/or replace tape cartridge\n");
12105 			}
12106 
12107 		} else if (total == -1 || retries == -1) {
12108 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12109 			    "log sense parameter code does not make sense\n");
12110 		}
12111 	}
12112 
12113 	/*
12114 	 * reset all values
12115 	 */
12116 	c = cdb;
12117 	*c++ = SCMD_LOG_SELECT_G1;
12118 	*c++ = 2;	/* this resets all values */
12119 	*c++ = (char)0xc0;
12120 	*c++ = 0;
12121 	*c++ = 0;
12122 	*c++ = 0;
12123 	*c++ = 0;
12124 	*c++ = 0;
12125 	*c++ = 0;
12126 	*c   = 0;
12127 	com->uscsi_bufaddr = NULL;
12128 	com->uscsi_buflen  = 0;
12129 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
12130 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12131 	if (rval) {
12132 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12133 		    "DAT soft error reset failed\n");
12134 	}
12135 done:
12136 	kmem_free(com, sizeof (*com));
12137 	kmem_free(sensep, LOG_SENSE_LENGTH);
12138 	return (rval);
12139 }
12140 
12141 static int
12142 st_report_soft_errors(dev_t dev, int flag)
12143 {
12144 	GET_SOFT_STATE(dev);
12145 
12146 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
12147 
12148 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12149 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12150 
12151 	ASSERT(mutex_owned(ST_MUTEX));
12152 
12153 	switch (un->un_dp->type) {
12154 	case ST_TYPE_EXB8500:
12155 	case ST_TYPE_EXABYTE:
12156 		return (st_report_exabyte_soft_errors(dev, flag));
12157 		/*NOTREACHED*/
12158 	case ST_TYPE_PYTHON:
12159 		return (st_report_dat_soft_errors(dev, flag));
12160 		/*NOTREACHED*/
12161 	default:
12162 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
12163 		return (-1);
12164 	}
12165 }
12166 
12167 /*
12168  * persistent error routines
12169  */
12170 
12171 /*
12172  * enable persistent errors, and set the throttle appropriately, checking
12173  * for flush-on-errors capability
12174  */
12175 static void
12176 st_turn_pe_on(struct scsi_tape *un)
12177 {
12178 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
12179 
12180 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
12181 	ASSERT(mutex_owned(ST_MUTEX));
12182 
12183 	un->un_persistence = 1;
12184 
12185 	/*
12186 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
12187 	 * enabled.  This will simplify the error handling for request senses
12188 	 */
12189 
12190 	if (un->un_arq_enabled && un->un_untagged_qing) {
12191 		uchar_t f_o_e;
12192 
12193 		mutex_exit(ST_MUTEX);
12194 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
12195 		    1 : 0;
12196 		mutex_enter(ST_MUTEX);
12197 
12198 		un->un_flush_on_errors = f_o_e;
12199 	} else {
12200 		un->un_flush_on_errors = 0;
12201 	}
12202 
12203 	if (un->un_flush_on_errors)
12204 		un->un_max_throttle = (uchar_t)st_max_throttle;
12205 	else
12206 		un->un_max_throttle = 1;
12207 
12208 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
12209 		un->un_max_throttle = 1;
12210 
12211 	/* this will send a marker pkt */
12212 	st_clear_pe(un);
12213 }
12214 
12215 /*
12216  * This turns persistent errors permanently off
12217  */
12218 static void
12219 st_turn_pe_off(struct scsi_tape *un)
12220 {
12221 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
12222 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
12223 	ASSERT(mutex_owned(ST_MUTEX));
12224 
12225 	/* turn it off for good */
12226 	un->un_persistence = 0;
12227 
12228 	/* this will send a marker pkt */
12229 	st_clear_pe(un);
12230 
12231 	/* turn off flush on error capability, if enabled */
12232 	if (un->un_flush_on_errors) {
12233 		mutex_exit(ST_MUTEX);
12234 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
12235 		mutex_enter(ST_MUTEX);
12236 	}
12237 
12238 
12239 	un->un_flush_on_errors = 0;
12240 }
12241 
12242 /*
12243  * This clear persistent errors, allowing more commands through, and also
12244  * sending a marker packet.
12245  */
12246 static void
12247 st_clear_pe(struct scsi_tape *un)
12248 {
12249 	ST_FUNC(ST_DEVINFO, st_clear_pe);
12250 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
12251 	ASSERT(mutex_owned(ST_MUTEX));
12252 
12253 	un->un_persist_errors = 0;
12254 	un->un_throttle = un->un_last_throttle = 1;
12255 	un->un_errno = 0;
12256 	st_hba_unflush(un);
12257 }
12258 
12259 /*
12260  * This will flag persistent errors, shutting everything down, if the
12261  * application had enabled persistent errors via MTIOCPERSISTENT
12262  */
12263 static void
12264 st_set_pe_flag(struct scsi_tape *un)
12265 {
12266 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
12267 	ASSERT(mutex_owned(ST_MUTEX));
12268 
12269 	if (un->un_persistence) {
12270 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
12271 		un->un_persist_errors = 1;
12272 		un->un_throttle = un->un_last_throttle = 0;
12273 		cv_broadcast(&un->un_sbuf_cv);
12274 	}
12275 }
12276 
12277 static int
12278 st_do_reserve(struct scsi_tape *un)
12279 {
12280 	int rval;
12281 
12282 	ST_FUNC(ST_DEVINFO, st_do_reserve);
12283 
12284 	/*
12285 	 * Issue a Throw-Away reserve command to clear the
12286 	 * check condition.
12287 	 * If the current behaviour of reserve/release is to
12288 	 * hold reservation across opens , and if a Bus reset
12289 	 * has been issued between opens then this command
12290 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
12291 	 * In this case return an EACCES so that user knows that
12292 	 * reservation has been lost in between opens.
12293 	 * If this error is not returned and we continue with
12294 	 * successful open , then user may think position of the
12295 	 * tape is still the same but inreality we would rewind the
12296 	 * tape and continue from BOT.
12297 	 */
12298 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12299 	if (rval) {
12300 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
12301 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
12302 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
12303 			un->un_errno = EACCES;
12304 			return (EACCES);
12305 		}
12306 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12307 	}
12308 	if (rval == 0) {
12309 		un->un_rsvd_status |= ST_INIT_RESERVE;
12310 	}
12311 
12312 	return (rval);
12313 }
12314 
12315 static int
12316 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb)
12317 {
12318 	int rval;
12319 	cmd_attribute const *attrib;
12320 
12321 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
12322 
12323 	/*
12324 	 * If already reserved no need to do it again.
12325 	 * Also if Reserve and Release are disabled Just return.
12326 	 */
12327 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12328 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12329 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12330 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12331 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
12332 		    st_print_scsi_cmd((uchar_t)cdb[0]));
12333 		return (0);
12334 	}
12335 
12336 	/* See if command is on the list */
12337 	attrib = st_lookup_cmd_attribute(cdb[0]);
12338 
12339 	if (attrib == NULL) {
12340 		rval = 1; /* Not found, when in doubt reserve */
12341 	} else if ((attrib->requires_reserve) != 0) {
12342 		rval = 1;
12343 	} else if ((attrib->reserve_byte) != 0) {
12344 		/*
12345 		 * cmd is on list.
12346 		 * if byte is zero always allowed.
12347 		 */
12348 		rval = 1;
12349 	} else if (((cdb[attrib->reserve_byte]) &
12350 	    (attrib->reserve_mask)) != 0) {
12351 		rval = 1;
12352 	} else {
12353 		rval = 0;
12354 	}
12355 
12356 	if (rval) {
12357 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12358 		    "Command %s requires reservation",
12359 		    st_print_scsi_cmd(cdb[0]));
12360 
12361 		rval = st_do_reserve(un);
12362 	}
12363 
12364 	return (rval);
12365 }
12366 
12367 static int
12368 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
12369 {
12370 	int rval;
12371 	cmd_attribute const *attrib;
12372 
12373 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
12374 
12375 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12376 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12377 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12378 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12379 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
12380 		    st_print_scsi_cmd(cmd));
12381 		return (0);
12382 	}
12383 
12384 	/* search for this command on the list */
12385 	attrib = st_lookup_cmd_attribute(cmd);
12386 
12387 	if (attrib == NULL) {
12388 		rval = 1; /* Not found, when in doubt reserve */
12389 	} else if ((attrib->requires_reserve) != 0) {
12390 		rval = 1;
12391 	} else if ((attrib->reserve_byte) != 0) {
12392 		/*
12393 		 * cmd is on list.
12394 		 * if byte is zero always allowed.
12395 		 */
12396 		rval = 1;
12397 	} else if (((attrib->reserve_mask) & cnt) != 0) {
12398 		rval = 1;
12399 	} else {
12400 		rval = 0;
12401 	}
12402 
12403 	if (rval) {
12404 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12405 		    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
12406 
12407 		rval = st_do_reserve(un);
12408 	}
12409 
12410 	return (rval);
12411 }
12412 
12413 static int
12414 st_reserve_release(struct scsi_tape *un, int cmd, ubufunc_t ubf)
12415 {
12416 	struct uscsi_cmd	uscsi_cmd;
12417 	int			rval;
12418 	char			cdb[CDB_GROUP0];
12419 	struct scsi_arq_status	stat;
12420 
12421 
12422 
12423 	ST_FUNC(ST_DEVINFO, st_reserve_release);
12424 
12425 	ASSERT(mutex_owned(ST_MUTEX));
12426 
12427 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12428 	    "st_reserve_release: %s \n",
12429 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
12430 
12431 	bzero(&cdb, CDB_GROUP0);
12432 	if (cmd == ST_RELEASE) {
12433 		cdb[0] = SCMD_RELEASE;
12434 	} else {
12435 		cdb[0] = SCMD_RESERVE;
12436 	}
12437 	bzero(&uscsi_cmd, sizeof (struct uscsi_cmd));
12438 	uscsi_cmd.uscsi_flags = USCSI_WRITE | USCSI_RQENABLE;
12439 	uscsi_cmd.uscsi_cdb = cdb;
12440 	uscsi_cmd.uscsi_cdblen = CDB_GROUP0;
12441 	uscsi_cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
12442 	uscsi_cmd.uscsi_rqbuf = (caddr_t)&stat;
12443 	uscsi_cmd.uscsi_rqlen = sizeof (stat);
12444 
12445 	rval = ubf(un, &uscsi_cmd, FKIOCTL);
12446 
12447 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12448 	    "st_reserve_release: rval(1)=%d\n", rval);
12449 
12450 	if (rval) {
12451 		if (uscsi_cmd.uscsi_status == STATUS_RESERVATION_CONFLICT) {
12452 			rval = EACCES;
12453 		}
12454 		/*
12455 		 * dynamically turn off reserve/release support
12456 		 * in case of drives which do not support
12457 		 * reserve/release command(ATAPI drives).
12458 		 */
12459 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
12460 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
12461 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
12462 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12463 				    "Tape unit does not support "
12464 				    "reserve/release \n");
12465 			}
12466 			rval = 0;
12467 		}
12468 	}
12469 	return (rval);
12470 }
12471 
12472 static int
12473 st_take_ownership(struct scsi_tape *un)
12474 {
12475 	int rval;
12476 
12477 	ST_FUNC(ST_DEVINFO, st_take_ownership);
12478 
12479 	ASSERT(mutex_owned(ST_MUTEX));
12480 
12481 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12482 	    "st_take_ownership: Entering ...\n");
12483 
12484 
12485 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12486 	/*
12487 	 * XXX -> Should reset be done only if we get EACCES.
12488 	 * .
12489 	 */
12490 	if (rval) {
12491 		if (st_reset(un, RESET_LUN) == 0) {
12492 			return (EIO);
12493 		}
12494 		un->un_rsvd_status &=
12495 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
12496 
12497 		mutex_exit(ST_MUTEX);
12498 		delay(drv_usectohz(ST_RESERVATION_DELAY));
12499 		mutex_enter(ST_MUTEX);
12500 		/*
12501 		 * remove the check condition.
12502 		 */
12503 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12504 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12505 		if (rval != 0) {
12506 			if ((st_reserve_release(un, ST_RESERVE, st_uscsi_cmd))
12507 			    != 0) {
12508 				rval = (un->un_rsvd_status &
12509 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
12510 				return (rval);
12511 			}
12512 		}
12513 		/*
12514 		 * Set tape state to ST_STATE_OFFLINE , in case if
12515 		 * the user wants to continue and start using
12516 		 * the tape.
12517 		 */
12518 		un->un_state = ST_STATE_OFFLINE;
12519 		un->un_rsvd_status |= ST_INIT_RESERVE;
12520 	}
12521 	return (rval);
12522 }
12523 
12524 static int
12525 st_create_errstats(struct scsi_tape *un, int instance)
12526 {
12527 	char	kstatname[KSTAT_STRLEN];
12528 
12529 	ST_FUNC(ST_DEVINFO, st_create_errstats);
12530 
12531 	/*
12532 	 * Create device error kstats
12533 	 */
12534 
12535 	if (un->un_errstats == (kstat_t *)0) {
12536 		(void) sprintf(kstatname, "st%d,err", instance);
12537 		un->un_errstats = kstat_create("sterr", instance, kstatname,
12538 		    "device_error", KSTAT_TYPE_NAMED,
12539 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
12540 		    KSTAT_FLAG_PERSISTENT);
12541 
12542 		if (un->un_errstats) {
12543 			struct st_errstats	*stp;
12544 
12545 			stp = (struct st_errstats *)un->un_errstats->ks_data;
12546 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
12547 			    KSTAT_DATA_ULONG);
12548 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
12549 			    KSTAT_DATA_ULONG);
12550 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
12551 			    KSTAT_DATA_ULONG);
12552 			kstat_named_init(&stp->st_vid, "Vendor",
12553 			    KSTAT_DATA_CHAR);
12554 			kstat_named_init(&stp->st_pid, "Product",
12555 			    KSTAT_DATA_CHAR);
12556 			kstat_named_init(&stp->st_revision, "Revision",
12557 			    KSTAT_DATA_CHAR);
12558 			kstat_named_init(&stp->st_serial, "Serial No",
12559 			    KSTAT_DATA_CHAR);
12560 			un->un_errstats->ks_private = un;
12561 			un->un_errstats->ks_update = nulldev;
12562 			kstat_install(un->un_errstats);
12563 			/*
12564 			 * Fill in the static data
12565 			 */
12566 			(void) strncpy(&stp->st_vid.value.c[0],
12567 			    ST_INQUIRY->inq_vid, 8);
12568 			/*
12569 			 * XXX:  Emulex MT-02 (and emulators) predates
12570 			 *	 SCSI-1 and has no vid & pid inquiry data.
12571 			 */
12572 			if (ST_INQUIRY->inq_len != 0) {
12573 				(void) strncpy(&stp->st_pid.value.c[0],
12574 				    ST_INQUIRY->inq_pid, 16);
12575 				(void) strncpy(&stp->st_revision.value.c[0],
12576 				    ST_INQUIRY->inq_revision, 4);
12577 				(void) strncpy(&stp->st_serial.value.c[0],
12578 				    ST_INQUIRY->inq_serial, 12);
12579 			}
12580 		}
12581 	}
12582 	return (0);
12583 }
12584 
12585 static int
12586 st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos)
12587 {
12588 	int rval;
12589 	bufunc_t bf = (ubf == st_uscsi_rcmd) ? st_rcmd : st_cmd;
12590 
12591 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
12592 
12593 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
12594 	ASSERT(mutex_owned(ST_MUTEX));
12595 
12596 	/* Can't restore an invalid position */
12597 	if (pos->pmode == invalid) {
12598 		return (4);
12599 	}
12600 
12601 	/*
12602 	 * Assumtions:
12603 	 *	If a position was read and is in logical position mode.
12604 	 *	If a drive supports read position it supports locate.
12605 	 *	If the read position type is not NO_POS. even though
12606 	 *	   a read position make not have been attemped yet.
12607 	 *
12608 	 *	The drive can locate to the position.
12609 	 */
12610 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
12611 		/*
12612 		 * If position mode is logical or legacy mode try
12613 		 * to locate there as it is faster.
12614 		 * If it fails try the old way.
12615 		 */
12616 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12617 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
12618 		    pos->lgclblkno);
12619 
12620 		if (st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
12621 		    pos->lgclblkno, pos->partition) == 0) {
12622 			/* Assume we are there copy rest of position back */
12623 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
12624 				COPY_POS(&un->un_pos, pos);
12625 			}
12626 			return (0);
12627 		}
12628 
12629 		/*
12630 		 * If logical block locate failed to restore a logical
12631 		 * position, can't recover.
12632 		 */
12633 		if (pos->pmode == logical) {
12634 			return (-1);
12635 		}
12636 	}
12637 
12638 
12639 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12640 	    "Restoring tape position at fileno=%x, blkno=%x....",
12641 	    pos->fileno, pos->blkno);
12642 
12643 	/*
12644 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
12645 	 * so as not to rewind tape on RESETS: Gee, Has life ever
12646 	 * been simple in tape land ?
12647 	 */
12648 	rval = bf(un, SCMD_REWIND, 0, SYNC_CMD);
12649 	if (rval) {
12650 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12651 		    "Failed to restore the last file and block position: In"
12652 		    " this state, Tape will be loaded at BOT during next open");
12653 		un->un_pos.pmode = invalid;
12654 		return (rval);
12655 	}
12656 
12657 	/* If the position was as the result of back space file */
12658 	if (pos->blkno > (INF / 2)) {
12659 		/* Go one extra file forward */
12660 		pos->fileno++;
12661 		/* Figure how many blocks to back into the previous file */
12662 		pos->blkno = -(INF - pos->blkno);
12663 	}
12664 
12665 	/* Go to requested fileno */
12666 	if (pos->fileno) {
12667 		rval = st_cmd(un, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
12668 		if (rval) {
12669 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12670 			    "Failed to restore the last file position: In this "
12671 			    " state, Tape will be loaded at BOT during next"
12672 			    " open %d", __LINE__);
12673 			un->un_pos.pmode = invalid;
12674 			pos->pmode = invalid;
12675 			return (rval);
12676 		}
12677 	}
12678 
12679 	/*
12680 	 * If backing into a file we already did an extra file forward.
12681 	 * Now we have to back over the filemark to get to the end of
12682 	 * the previous file. The blkno has been ajusted to a negative
12683 	 * value so we will get to the expected location.
12684 	 */
12685 	if (pos->blkno) {
12686 		rval = bf(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
12687 		if (rval) {
12688 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12689 			    "Failed to restore the last file position: In this "
12690 			    " state, Tape will be loaded at BOT during next"
12691 			    " open %d", __LINE__);
12692 			un->un_pos.pmode = invalid;
12693 			pos->pmode = invalid;
12694 			return (rval);
12695 		}
12696 	}
12697 
12698 	/*
12699 	 * The position mode, block and fileno should be correct,
12700 	 * This updates eof and logical position information.
12701 	 */
12702 	un->un_pos.eof = pos->eof;
12703 	un->un_pos.lgclblkno = pos->lgclblkno;
12704 
12705 	return (0);
12706 }
12707 
12708 /*
12709  * check sense key, ASC, ASCQ in order to determine if the tape needs
12710  * to be ejected
12711  */
12712 
12713 static int
12714 st_check_asc_ascq(struct scsi_tape *un)
12715 {
12716 	struct scsi_extended_sense *sensep = ST_RQSENSE;
12717 	struct tape_failure_code   *code;
12718 
12719 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
12720 
12721 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
12722 		if ((code->key  == sensep->es_key) &&
12723 		    (code->add_code  == sensep->es_add_code) &&
12724 		    (code->qual_code == sensep->es_qual_code))
12725 			return (1);
12726 	}
12727 	return (0);
12728 }
12729 
12730 /*
12731  * st_logpage_supported() sends a Log Sense command with
12732  * page code = 0 = Supported Log Pages Page to the device,
12733  * to see whether the page 'page' is supported.
12734  * Return values are:
12735  * -1 if the Log Sense command fails
12736  * 0 if page is not supported
12737  * 1 if page is supported
12738  */
12739 
12740 static int
12741 st_logpage_supported(struct scsi_tape *un, uchar_t page)
12742 {
12743 	uchar_t *sp, *sensep;
12744 	unsigned length;
12745 	struct uscsi_cmd *com;
12746 	int rval;
12747 	char cdb[CDB_GROUP1] = {
12748 		SCMD_LOG_SENSE_G1,
12749 		0,
12750 		SUPPORTED_LOG_PAGES_PAGE,
12751 		0,
12752 		0,
12753 		0,
12754 		0,
12755 		0,
12756 		(char)LOG_SENSE_LENGTH,
12757 		0
12758 	};
12759 
12760 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
12761 
12762 	ASSERT(mutex_owned(ST_MUTEX));
12763 
12764 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12765 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12766 
12767 	com->uscsi_cdb = cdb;
12768 	com->uscsi_cdblen = CDB_GROUP1;
12769 	com->uscsi_bufaddr = (caddr_t)sensep;
12770 	com->uscsi_buflen = LOG_SENSE_LENGTH;
12771 	com->uscsi_flags =
12772 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12773 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12774 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12775 	if (rval || com->uscsi_status) {
12776 		/* uscsi-command failed */
12777 		rval = -1;
12778 	} else {
12779 
12780 		sp = sensep + 3;
12781 
12782 		for (length = *sp++; length > 0; length--, sp++) {
12783 
12784 			if (*sp == page) {
12785 				rval = 1;
12786 				break;
12787 			}
12788 		}
12789 	}
12790 	kmem_free(com, sizeof (struct uscsi_cmd));
12791 	kmem_free(sensep, LOG_SENSE_LENGTH);
12792 	return (rval);
12793 }
12794 
12795 
12796 /*
12797  * st_check_clean_bit() gets the status of the tape's cleaning bit.
12798  *
12799  * If the device does support the TapeAlert log page, then the cleaning bit
12800  * information will be read from this page. Otherwise we will see if one of
12801  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
12802  * the device, which means, that we can get the cleaning bit information via
12803  * a RequestSense command.
12804  * If both methods of getting cleaning bit information are not supported
12805  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
12806  * returns with
12807  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
12808  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
12809  * If the call to st_uscsi_cmd() to do the Log Sense or the Request Sense
12810  * command fails, or if the amount of Request Sense data is not enough, then
12811  *  st_check_clean_bit() returns with -1.
12812  */
12813 
12814 static int
12815 st_check_clean_bit(struct scsi_tape *un)
12816 {
12817 	int rval = 0;
12818 
12819 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
12820 
12821 	ASSERT(mutex_owned(ST_MUTEX));
12822 
12823 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
12824 		return (rval);
12825 	}
12826 
12827 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
12828 
12829 		rval = st_logpage_supported(un, TAPE_SEQUENTIAL_PAGE);
12830 		if (rval == 1) {
12831 
12832 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
12833 		}
12834 
12835 		rval = st_logpage_supported(un, TAPE_ALERT_PAGE);
12836 		if (rval == 1) {
12837 
12838 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
12839 		}
12840 
12841 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
12842 
12843 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
12844 		}
12845 	}
12846 
12847 	rval = 0;
12848 
12849 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
12850 
12851 		rval = st_check_sequential_clean_bit(un);
12852 	}
12853 
12854 	if ((rval <= 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
12855 
12856 		rval = st_check_alert_flags(un);
12857 	}
12858 
12859 	if ((rval <= 0) && (un->un_dp->options & ST_CLN_MASK)) {
12860 
12861 		rval = st_check_sense_clean_bit(un);
12862 	}
12863 
12864 	if (rval < 0) {
12865 		return (rval);
12866 	}
12867 
12868 	/*
12869 	 * If found a supported means to check need to clean.
12870 	 */
12871 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
12872 
12873 		/*
12874 		 * head needs to be cleaned.
12875 		 */
12876 		if (rval & MTF_TAPE_HEAD_DIRTY) {
12877 
12878 			/*
12879 			 * Print log message only first time
12880 			 * found needing cleaned.
12881 			 */
12882 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
12883 
12884 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12885 				    "Periodic head cleaning required");
12886 
12887 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
12888 			}
12889 
12890 		} else {
12891 
12892 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
12893 		}
12894 	}
12895 
12896 	return (rval);
12897 }
12898 
12899 
12900 static int
12901 st_check_sequential_clean_bit(struct scsi_tape *un)
12902 {
12903 	int rval;
12904 	int ix;
12905 	ushort_t parameter;
12906 	struct uscsi_cmd *cmd;
12907 	struct log_sequential_page *sp;
12908 	struct log_sequential_page_parameter *prm;
12909 	char cdb[CDB_GROUP1] = {
12910 		SCMD_LOG_SENSE_G1,
12911 		0,
12912 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
12913 		0,
12914 		0,
12915 		0,
12916 		0,
12917 		(char)(sizeof (struct log_sequential_page) >> 8),
12918 		(char)(sizeof (struct log_sequential_page)),
12919 		0
12920 	};
12921 
12922 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
12923 
12924 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12925 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
12926 
12927 	cmd->uscsi_flags   =
12928 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12929 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12930 	cmd->uscsi_cdb	   = cdb;
12931 	cmd->uscsi_cdblen  = CDB_GROUP1;
12932 	cmd->uscsi_bufaddr = (caddr_t)sp;
12933 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
12934 
12935 	rval = st_uscsi_cmd(un, cmd, FKIOCTL);
12936 
12937 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
12938 
12939 		rval = -1;
12940 
12941 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
12942 
12943 		rval = -1;
12944 	}
12945 
12946 	prm = &sp->param[0];
12947 
12948 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
12949 
12950 		if (prm->log_param.length == 0) {
12951 			break;
12952 		}
12953 
12954 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
12955 		    (prm->log_param.pc_lo & 0xff));
12956 
12957 		if (parameter == SEQUENTIAL_NEED_CLN) {
12958 
12959 			rval = MTF_TAPE_CLN_SUPPORTED;
12960 			if (prm->param_value[prm->log_param.length - 1]) {
12961 
12962 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12963 				    "sequential log says head dirty\n");
12964 				rval |= MTF_TAPE_HEAD_DIRTY;
12965 			}
12966 		}
12967 		prm = (struct log_sequential_page_parameter *)
12968 		    &prm->param_value[prm->log_param.length];
12969 	}
12970 
12971 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12972 	kmem_free(sp,  sizeof (struct log_sequential_page));
12973 
12974 	return (rval);
12975 }
12976 
12977 
12978 static int
12979 st_check_alert_flags(struct scsi_tape *un)
12980 {
12981 	struct st_tape_alert *ta;
12982 	struct uscsi_cmd *com;
12983 	unsigned ix, length;
12984 	int rval;
12985 	tape_alert_flags flag;
12986 	char cdb[CDB_GROUP1] = {
12987 		SCMD_LOG_SENSE_G1,
12988 		0,
12989 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
12990 		0,
12991 		0,
12992 		0,
12993 		0,
12994 		(char)(sizeof (struct st_tape_alert) >> 8),
12995 		(char)(sizeof (struct st_tape_alert)),
12996 		0
12997 	};
12998 
12999 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
13000 
13001 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13002 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
13003 
13004 	com->uscsi_cdb = cdb;
13005 	com->uscsi_cdblen = CDB_GROUP1;
13006 	com->uscsi_bufaddr = (caddr_t)ta;
13007 	com->uscsi_buflen = sizeof (struct st_tape_alert);
13008 	com->uscsi_flags =
13009 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13010 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13011 
13012 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13013 
13014 	if (rval || com->uscsi_status || com->uscsi_resid) {
13015 
13016 		rval = -1; /* uscsi-command failed */
13017 
13018 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
13019 
13020 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13021 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
13022 		rval = -1;
13023 	}
13024 
13025 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
13026 
13027 
13028 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
13029 
13030 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13031 		    "TapeAlert length %d\n", length);
13032 	}
13033 
13034 
13035 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
13036 
13037 		/*
13038 		 * if rval is bad before the first pass don't bother
13039 		 */
13040 		if (ix == 0 && rval != 0) {
13041 
13042 			break;
13043 		}
13044 
13045 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
13046 		    ta->param[ix].log_param.pc_lo);
13047 
13048 		if ((ta->param[ix].param_value & 1) == 0) {
13049 			continue;
13050 		}
13051 		/*
13052 		 * check to see if current parameter is of interest.
13053 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
13054 		 */
13055 		if ((flag == TAF_CLEAN_NOW) ||
13056 		    (flag == TAF_CLEAN_PERIODIC) ||
13057 		    ((flag == CLEAN_FOR_ERRORS) &&
13058 		    (un->un_dp->type == ST_TYPE_STK9840))) {
13059 
13060 			rval = MTF_TAPE_CLN_SUPPORTED;
13061 
13062 
13063 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13064 			    "alert_page drive needs clean %d\n", flag);
13065 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
13066 			rval |= MTF_TAPE_HEAD_DIRTY;
13067 
13068 		} else if (flag == TAF_CLEANING_MEDIA) {
13069 
13070 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13071 			    "alert_page drive was cleaned\n");
13072 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
13073 		}
13074 
13075 	}
13076 
13077 	/*
13078 	 * Report it as dirty till we see it cleaned
13079 	 */
13080 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
13081 
13082 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13083 		    "alert_page still dirty\n");
13084 		rval |= MTF_TAPE_HEAD_DIRTY;
13085 	}
13086 
13087 	kmem_free(com, sizeof (struct uscsi_cmd));
13088 	kmem_free(ta,  sizeof (struct st_tape_alert));
13089 
13090 	return (rval);
13091 }
13092 
13093 
13094 static int
13095 st_check_sense_clean_bit(struct scsi_tape *un)
13096 {
13097 	uchar_t *sensep;
13098 	char cdb[CDB_GROUP0];
13099 	struct uscsi_cmd *com;
13100 	ushort_t byte_pos;
13101 	uchar_t bit_mask;
13102 	unsigned length;
13103 	int index;
13104 	int rval;
13105 
13106 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
13107 
13108 	/*
13109 	 * Since this tape does not support Tape Alert,
13110 	 * we now try to get the cleanbit status via
13111 	 * Request Sense.
13112 	 */
13113 
13114 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
13115 
13116 		index = 0;
13117 
13118 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
13119 
13120 		index = 1;
13121 
13122 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
13123 
13124 		index = 2;
13125 
13126 	} else {
13127 
13128 		return (-1);
13129 	}
13130 
13131 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
13132 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
13133 	length = byte_pos + 1;
13134 
13135 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13136 	sensep = kmem_zalloc(length, KM_SLEEP);
13137 
13138 	cdb[0] = SCMD_REQUEST_SENSE;
13139 	cdb[1] = 0;
13140 	cdb[2] = 0;
13141 	cdb[3] = 0;
13142 	cdb[4] = (char)length;
13143 	cdb[5] = 0;
13144 
13145 	com->uscsi_cdb = cdb;
13146 	com->uscsi_cdblen = CDB_GROUP0;
13147 	com->uscsi_bufaddr = (caddr_t)sensep;
13148 	com->uscsi_buflen = length;
13149 	com->uscsi_flags =
13150 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13151 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13152 
13153 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13154 
13155 	if (rval || com->uscsi_status || com->uscsi_resid) {
13156 
13157 		rval = -1;
13158 
13159 	} else {
13160 
13161 		rval = MTF_TAPE_CLN_SUPPORTED;
13162 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
13163 
13164 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13165 			    "sense data says head dirty\n");
13166 			rval |= MTF_TAPE_HEAD_DIRTY;
13167 		}
13168 	}
13169 
13170 	kmem_free(com, sizeof (struct uscsi_cmd));
13171 	kmem_free(sensep, length);
13172 	return (rval);
13173 }
13174 
13175 /*
13176  * st_clear_unit_attention
13177  *
13178  *  	run test unit ready's to clear out outstanding
13179  * 	unit attentions.
13180  * 	returns zero for SUCCESS or the errno from st_cmd call
13181  */
13182 static int
13183 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
13184 {
13185 	int	i    = 0;
13186 	int	rval;
13187 
13188 	GET_SOFT_STATE(dev_instance);
13189 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
13190 
13191 	do {
13192 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
13193 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
13194 	return (rval);
13195 }
13196 
13197 static void
13198 st_calculate_timeouts(struct scsi_tape *un)
13199 {
13200 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
13201 
13202 	if (un->un_dp->non_motion_timeout == 0) {
13203 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13204 			un->un_dp->non_motion_timeout =
13205 			    st_io_time * st_long_timeout_x;
13206 		} else {
13207 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
13208 		}
13209 	}
13210 
13211 	if (un->un_dp->io_timeout == 0) {
13212 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13213 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
13214 		} else {
13215 			un->un_dp->io_timeout = (ushort_t)st_io_time;
13216 		}
13217 	}
13218 
13219 	if (un->un_dp->rewind_timeout == 0) {
13220 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13221 			un->un_dp->rewind_timeout =
13222 			    st_space_time * st_long_timeout_x;
13223 		} else {
13224 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
13225 		}
13226 	}
13227 
13228 	if (un->un_dp->space_timeout == 0) {
13229 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13230 			un->un_dp->space_timeout =
13231 			    st_space_time * st_long_timeout_x;
13232 		} else {
13233 			un->un_dp->space_timeout = (ushort_t)st_space_time;
13234 		}
13235 	}
13236 
13237 	if (un->un_dp->load_timeout == 0) {
13238 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13239 			un->un_dp->load_timeout =
13240 			    st_space_time * st_long_timeout_x;
13241 		} else {
13242 			un->un_dp->load_timeout = (ushort_t)st_space_time;
13243 		}
13244 	}
13245 
13246 	if (un->un_dp->unload_timeout == 0) {
13247 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13248 			un->un_dp->unload_timeout =
13249 			    st_space_time * st_long_timeout_x;
13250 		} else {
13251 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
13252 		}
13253 	}
13254 
13255 	if (un->un_dp->erase_timeout == 0) {
13256 		if (un->un_dp->options & ST_LONG_ERASE) {
13257 			un->un_dp->erase_timeout =
13258 			    st_space_time * st_long_space_time_x;
13259 		} else {
13260 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
13261 		}
13262 	}
13263 }
13264 
13265 
13266 static writablity
13267 st_is_not_wormable(struct scsi_tape *un)
13268 {
13269 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
13270 	return (RDWR);
13271 }
13272 
13273 static writablity
13274 st_is_hp_dat_tape_worm(struct scsi_tape *un)
13275 {
13276 	writablity wrt;
13277 
13278 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
13279 
13280 	/* Mode sense should be current */
13281 	if (un->un_mspl->media_type == 1) {
13282 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13283 		    "Drive has WORM media loaded\n");
13284 		wrt = WORM;
13285 	} else {
13286 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13287 		    "Drive has non WORM media loaded\n");
13288 		wrt = RDWR;
13289 	}
13290 	return (wrt);
13291 }
13292 
13293 #define	HP_DAT_INQUIRY 0x4A
13294 static writablity
13295 st_is_hp_dat_worm(struct scsi_tape *un)
13296 {
13297 	char *buf;
13298 	int result;
13299 	writablity wrt;
13300 
13301 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
13302 
13303 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
13304 
13305 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
13306 
13307 	if (result != 0) {
13308 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13309 		    "Read Standard Inquiry for WORM support failed");
13310 		wrt = FAILED;
13311 	} else if ((buf[40] & 1) == 0) {
13312 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13313 		    "Drive is NOT WORMable\n");
13314 		/* This drive doesn't support it so don't check again */
13315 		un->un_dp->options &= ~ST_WORMABLE;
13316 		wrt = RDWR;
13317 		un->un_wormable = st_is_not_wormable;
13318 	} else {
13319 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13320 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13321 		un->un_wormable = st_is_hp_dat_tape_worm;
13322 		wrt = un->un_wormable(un);
13323 	}
13324 
13325 	kmem_free(buf, HP_DAT_INQUIRY);
13326 
13327 	/*
13328 	 * If drive doesn't support it no point in checking further.
13329 	 */
13330 	return (wrt);
13331 }
13332 
13333 static writablity
13334 st_is_hp_lto_tape_worm(struct scsi_tape *un)
13335 {
13336 	writablity wrt;
13337 
13338 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
13339 
13340 	/* Mode sense should be current */
13341 	switch (un->un_mspl->media_type) {
13342 	case 0x00:
13343 		switch (un->un_mspl->density) {
13344 		case 0x40:
13345 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13346 			    "Drive has standard Gen I media loaded\n");
13347 			break;
13348 		case 0x42:
13349 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13350 			    "Drive has standard Gen II media loaded\n");
13351 			break;
13352 		case 0x44:
13353 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13354 			    "Drive has standard Gen III media loaded\n");
13355 			break;
13356 		case 0x46:
13357 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13358 			    "Drive has standard Gen IV media loaded\n");
13359 			break;
13360 		default:
13361 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13362 			    "Drive has standard unknown 0x%X media loaded\n",
13363 			    un->un_mspl->density);
13364 		}
13365 		wrt = RDWR;
13366 		break;
13367 	case 0x01:
13368 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13369 		    "Drive has WORM medium loaded\n");
13370 		wrt = WORM;
13371 		break;
13372 	case 0x80:
13373 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13374 		    "Drive has CD-ROM emulation medium loaded\n");
13375 		wrt = WORM;
13376 		break;
13377 	default:
13378 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13379 		    "Drive has an unexpected medium type 0x%X loaded\n",
13380 		    un->un_mspl->media_type);
13381 		wrt = RDWR;
13382 	}
13383 
13384 	return (wrt);
13385 }
13386 
13387 #define	LTO_REQ_INQUIRY 44
13388 static writablity
13389 st_is_hp_lto_worm(struct scsi_tape *un)
13390 {
13391 	char *buf;
13392 	int result;
13393 	writablity wrt;
13394 
13395 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
13396 
13397 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
13398 
13399 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
13400 
13401 	if (result != 0) {
13402 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13403 		    "Read Standard Inquiry for WORM support failed");
13404 		wrt = FAILED;
13405 	} else if ((buf[40] & 1) == 0) {
13406 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13407 		    "Drive is NOT WORMable\n");
13408 		/* This drive doesn't support it so don't check again */
13409 		un->un_dp->options &= ~ST_WORMABLE;
13410 		wrt = RDWR;
13411 		un->un_wormable = st_is_not_wormable;
13412 	} else {
13413 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13414 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13415 		un->un_wormable = st_is_hp_lto_tape_worm;
13416 		wrt = un->un_wormable(un);
13417 	}
13418 
13419 	kmem_free(buf, LTO_REQ_INQUIRY);
13420 
13421 	/*
13422 	 * If drive doesn't support it no point in checking further.
13423 	 */
13424 	return (wrt);
13425 }
13426 
13427 static writablity
13428 st_is_t10_worm_device(struct scsi_tape *un)
13429 {
13430 	writablity wrt;
13431 
13432 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
13433 
13434 	if (un->un_mspl->media_type == 0x3c) {
13435 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13436 		    "Drive has WORM media loaded\n");
13437 		wrt = WORM;
13438 	} else {
13439 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13440 		    "Drive has non WORM media loaded\n");
13441 		wrt = RDWR;
13442 	}
13443 	return (wrt);
13444 }
13445 
13446 #define	SEQ_CAP_PAGE	(char)0xb0
13447 static writablity
13448 st_is_t10_worm(struct scsi_tape *un)
13449 {
13450 	char *buf;
13451 	int result;
13452 	writablity wrt;
13453 
13454 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
13455 
13456 	buf = kmem_zalloc(6, KM_SLEEP);
13457 
13458 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
13459 
13460 	if (result != 0) {
13461 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13462 		    "Read Vitial Inquiry for Sequental Capability"
13463 		    " WORM support failed %x", result);
13464 		wrt = FAILED;
13465 	} else if ((buf[4] & 1) == 0) {
13466 		ASSERT(buf[1] == SEQ_CAP_PAGE);
13467 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13468 		    "Drive is NOT WORMable\n");
13469 		/* This drive doesn't support it so don't check again */
13470 		un->un_dp->options &= ~ST_WORMABLE;
13471 		wrt = RDWR;
13472 		un->un_wormable = st_is_not_wormable;
13473 	} else {
13474 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13475 		    "Drive supports WORM\n");
13476 		un->un_wormable = st_is_t10_worm_device;
13477 		wrt = un->un_wormable(un);
13478 	}
13479 
13480 	kmem_free(buf, 6);
13481 
13482 	return (wrt);
13483 }
13484 
13485 
13486 #define	STK_REQ_SENSE 26
13487 
13488 static writablity
13489 st_is_stk_worm(struct scsi_tape *un)
13490 {
13491 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
13492 	struct scsi_extended_sense *sense;
13493 	struct uscsi_cmd *cmd;
13494 	char *buf;
13495 	int result;
13496 	writablity wrt;
13497 
13498 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
13499 
13500 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13501 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
13502 	sense = (struct scsi_extended_sense *)buf;
13503 
13504 	cmd->uscsi_flags = USCSI_READ;
13505 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13506 	cmd->uscsi_cdb = &cdb[0];
13507 	cmd->uscsi_bufaddr = buf;
13508 	cmd->uscsi_buflen = STK_REQ_SENSE;
13509 	cmd->uscsi_cdblen = CDB_GROUP0;
13510 	cmd->uscsi_rqlen = 0;
13511 	cmd->uscsi_rqbuf = NULL;
13512 
13513 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
13514 
13515 	if (result != 0 || cmd->uscsi_status != 0) {
13516 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13517 		    "Request Sense for WORM failed");
13518 		wrt = RDWR;
13519 	} else if (sense->es_add_len + 8 < 24) {
13520 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13521 		    "Drive didn't send enough sense data for WORM byte %d\n",
13522 		    sense->es_add_len + 8);
13523 		wrt = RDWR;
13524 		un->un_wormable = st_is_not_wormable;
13525 	} else if ((buf[24]) & 0x02) {
13526 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13527 		    "Drive has WORM tape loaded\n");
13528 		wrt = WORM;
13529 		un->un_wormable = st_is_stk_worm;
13530 	} else {
13531 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13532 		    "Drive has normal tape loaded\n");
13533 		wrt = RDWR;
13534 		un->un_wormable = st_is_stk_worm;
13535 	}
13536 
13537 	kmem_free(buf, STK_REQ_SENSE);
13538 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13539 	return (wrt);
13540 }
13541 
13542 #define	DLT_INQ_SZ 44
13543 
13544 static writablity
13545 st_is_dlt_tape_worm(struct scsi_tape *un)
13546 {
13547 	caddr_t buf;
13548 	int result;
13549 	writablity wrt;
13550 
13551 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
13552 
13553 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
13554 
13555 	/* Read Attribute Media Type */
13556 
13557 	result = st_read_attributes(un, 0x0408, buf, 10, st_uscsi_cmd);
13558 
13559 	/*
13560 	 * If this quantum drive is attached via an HBA that cannot
13561 	 * support thr read attributes command return error in the
13562 	 * hope that someday they will support the t10 method.
13563 	 */
13564 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
13565 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13566 		    "Read Attribute Command for WORM Media detection is not "
13567 		    "supported on the HBA that this drive is attached to.");
13568 		wrt = RDWR;
13569 		un->un_wormable = st_is_not_wormable;
13570 		goto out;
13571 	}
13572 
13573 	if (result != 0) {
13574 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13575 		    "Read Attribute Command for WORM Media returned 0x%x",
13576 		    result);
13577 		wrt = RDWR;
13578 		un->un_dp->options &= ~ST_WORMABLE;
13579 		goto out;
13580 	}
13581 
13582 	if ((uchar_t)buf[9] == 0x80) {
13583 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13584 		    "Drive media is WORM\n");
13585 		wrt = WORM;
13586 	} else {
13587 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13588 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
13589 		wrt = RDWR;
13590 	}
13591 
13592 out:
13593 	kmem_free(buf, DLT_INQ_SZ);
13594 	return (wrt);
13595 }
13596 
13597 static writablity
13598 st_is_dlt_worm(struct scsi_tape *un)
13599 {
13600 	caddr_t buf;
13601 	int result;
13602 	writablity wrt;
13603 
13604 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
13605 
13606 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
13607 
13608 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
13609 
13610 	if (result != 0) {
13611 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13612 		    "Read Vendor Specific Inquiry for WORM support failed");
13613 		wrt = RDWR;
13614 		goto out;
13615 	}
13616 
13617 	if ((buf[2] & 1) == 0) {
13618 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13619 		    "Drive is not WORMable\n");
13620 		wrt = RDWR;
13621 		un->un_dp->options &= ~ST_WORMABLE;
13622 		un->un_wormable = st_is_not_wormable;
13623 		goto out;
13624 	} else {
13625 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13626 		    "Drive is WORMable\n");
13627 		un->un_wormable = st_is_dlt_tape_worm;
13628 		wrt = un->un_wormable(un);
13629 	}
13630 out:
13631 	kmem_free(buf, DLT_INQ_SZ);
13632 
13633 	return (wrt);
13634 }
13635 
13636 typedef struct {
13637 	struct modeheader_seq header;
13638 #if defined(_BIT_FIELDS_LTOH) /* X86 */
13639 	uchar_t pagecode	:6,
13640 				:2;
13641 	uchar_t page_len;
13642 	uchar_t syslogalive	:2,
13643 		device		:1,
13644 		abs		:1,
13645 		ulpbot		:1,
13646 		prth		:1,
13647 		ponej		:1,
13648 		ait		:1;
13649 	uchar_t span;
13650 
13651 	uchar_t			:6,
13652 		worm		:1,
13653 		mic		:1;
13654 	uchar_t worm_cap	:1,
13655 				:7;
13656 	uint32_t		:32;
13657 #else /* SPARC */
13658 	uchar_t			:2,
13659 		pagecode	:6;
13660 	uchar_t page_len;
13661 	uchar_t ait		:1,
13662 		device		:1,
13663 		abs		:1,
13664 		ulpbot		:1,
13665 		prth		:1,
13666 		ponej		:1,
13667 		syslogalive	:2;
13668 	uchar_t span;
13669 	uchar_t mic		:1,
13670 		worm		:1,
13671 				:6;
13672 	uchar_t			:7,
13673 		worm_cap	:1;
13674 	uint32_t		:32;
13675 #endif
13676 }ait_dev_con;
13677 
13678 #define	AIT_DEV_PAGE 0x31
13679 static writablity
13680 st_is_sony_worm(struct scsi_tape *un)
13681 {
13682 	int result;
13683 	writablity wrt;
13684 	ait_dev_con *ait_conf;
13685 
13686 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
13687 
13688 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
13689 
13690 	result = st_gen_mode_sense(un, st_uscsi_cmd, AIT_DEV_PAGE,
13691 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
13692 
13693 	if (result == 0) {
13694 
13695 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
13696 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13697 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
13698 			    ait_conf->pagecode, AIT_DEV_PAGE);
13699 			wrt = RDWR;
13700 			un->un_wormable = st_is_not_wormable;
13701 
13702 		} else if (ait_conf->worm_cap) {
13703 
13704 			un->un_wormable = st_is_sony_worm;
13705 
13706 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13707 			    "Drives is WORMable\n");
13708 			if (ait_conf->worm) {
13709 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13710 				    "Media is WORM\n");
13711 				wrt = WORM;
13712 			} else {
13713 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13714 				    "Media is not WORM\n");
13715 				wrt = RDWR;
13716 			}
13717 
13718 		} else {
13719 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13720 			    "Drives not is WORMable\n");
13721 			wrt = RDWR;
13722 			/* No further checking required */
13723 			un->un_dp->options &= ~ST_WORMABLE;
13724 		}
13725 
13726 	} else {
13727 
13728 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13729 		    "AIT device config mode sense page read command failed"
13730 		    " result = %d ", result);
13731 		wrt = FAILED;
13732 		un->un_wormable = st_is_not_wormable;
13733 	}
13734 
13735 	kmem_free(ait_conf, sizeof (ait_dev_con));
13736 	return (wrt);
13737 }
13738 
13739 static writablity
13740 st_is_drive_worm(struct scsi_tape *un)
13741 {
13742 	writablity wrt;
13743 
13744 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
13745 
13746 	switch (un->un_dp->type) {
13747 	case MT_ISDLT:
13748 		wrt = st_is_dlt_worm(un);
13749 		break;
13750 
13751 	case MT_ISSTK9840:
13752 		wrt = st_is_stk_worm(un);
13753 		break;
13754 
13755 	case MT_IS8MM:
13756 	case MT_ISAIT:
13757 		wrt = st_is_sony_worm(un);
13758 		break;
13759 
13760 	case MT_LTO:
13761 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
13762 			wrt = st_is_hp_lto_worm(un);
13763 		} else {
13764 			wrt = st_is_t10_worm(un);
13765 		}
13766 		break;
13767 
13768 	case MT_ISDAT:
13769 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
13770 			wrt = st_is_hp_dat_worm(un);
13771 		} else {
13772 			wrt = st_is_t10_worm(un);
13773 		}
13774 		break;
13775 
13776 	default:
13777 		wrt = FAILED;
13778 		break;
13779 	}
13780 
13781 	/*
13782 	 * If any of the above failed try the t10 standard method.
13783 	 */
13784 	if (wrt == FAILED) {
13785 		wrt = st_is_t10_worm(un);
13786 	}
13787 
13788 	/*
13789 	 * Unknown method for detecting WORM media.
13790 	 */
13791 	if (wrt == FAILED) {
13792 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13793 		    "Unknown method for WORM media detection\n");
13794 		wrt = RDWR;
13795 		un->un_dp->options &= ~ST_WORMABLE;
13796 	}
13797 
13798 	return (wrt);
13799 }
13800 
13801 static int
13802 st_read_attributes(struct scsi_tape *un, uint16_t attribute, void *pnt,
13803     size_t size, ubufunc_t bufunc)
13804 {
13805 	char cdb[CDB_GROUP4];
13806 	int result;
13807 	struct uscsi_cmd *cmd;
13808 	caddr_t buf = (caddr_t)pnt;
13809 
13810 	ST_FUNC(ST_DEVINFO, st_read_attributes);
13811 
13812 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13813 
13814 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
13815 	cdb[1] = 0;
13816 	cdb[2] = 0;
13817 	cdb[3] = 0;
13818 	cdb[4] = 0;
13819 	cdb[5] = 0;
13820 	cdb[6] = 0;
13821 	cdb[7] = 0;
13822 	cdb[8] = (char)(attribute >> 8);
13823 	cdb[9] = (char)(attribute);
13824 	cdb[10] = (char)(size >> 24);
13825 	cdb[11] = (char)(size >> 16);
13826 	cdb[12] = (char)(size >> 8);
13827 	cdb[13] = (char)(size);
13828 	cdb[14] = 0;
13829 	cdb[15] = 0;
13830 
13831 
13832 	cmd->uscsi_flags = USCSI_READ | USCSI_DIAGNOSE;
13833 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13834 	cmd->uscsi_cdb = &cdb[0];
13835 	cmd->uscsi_bufaddr = (caddr_t)buf;
13836 	cmd->uscsi_buflen = size;
13837 	cmd->uscsi_cdblen = sizeof (cdb);
13838 
13839 	result = bufunc(un, cmd, FKIOCTL);
13840 
13841 	if (result != 0 || cmd->uscsi_status != 0) {
13842 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13843 		    "st_read_attribute failed: result %d status %d\n",
13844 		    result, cmd->uscsi_status);
13845 		/*
13846 		 * If this returns invalid operation code don't try again.
13847 		 */
13848 		if (un->un_sd->sd_sense->es_key == KEY_ILLEGAL_REQUEST &&
13849 		    un->un_sd->sd_sense->es_add_code == 0x20) {
13850 			result = ENOTTY;
13851 		} else if (result == 0) {
13852 			result = EIO;
13853 		}
13854 
13855 	} else {
13856 
13857 		/*
13858 		 * The attribute retured should match the attribute requested.
13859 		 */
13860 		if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
13861 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13862 			    "st_read_attribute got wrong data back expected "
13863 			    "0x%x got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
13864 			st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
13865 			    "bad? data", buf, size);
13866 			result = EIO;
13867 		}
13868 	}
13869 
13870 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13871 
13872 	return (result);
13873 }
13874 
13875 static int
13876 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
13877     uchar_t page)
13878 {
13879 	char cdb[CDB_GROUP0];
13880 	struct scsi_extended_sense *sense;
13881 	struct uscsi_cmd *cmd;
13882 	int result;
13883 
13884 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
13885 
13886 	cdb[0] = SCMD_INQUIRY;
13887 	cdb[1] = page ? 1 : 0;
13888 	cdb[2] = page;
13889 	cdb[3] = 0;
13890 	cdb[4] = size;
13891 	cdb[5] = 0;
13892 
13893 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13894 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
13895 
13896 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
13897 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13898 	cmd->uscsi_cdb = &cdb[0];
13899 	cmd->uscsi_bufaddr = dest;
13900 	cmd->uscsi_buflen = size;
13901 	cmd->uscsi_cdblen = CDB_GROUP0;
13902 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
13903 	cmd->uscsi_rqbuf = (caddr_t)sense;
13904 
13905 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
13906 
13907 	if (result != 0 || cmd->uscsi_status != 0) {
13908 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13909 		    "st_get_special_inquiry() failed for page %x", page);
13910 		if (result == 0) {
13911 			result = EIO;
13912 		}
13913 	}
13914 
13915 	kmem_free(sense, sizeof (struct scsi_extended_sense));
13916 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13917 
13918 	return (result);
13919 }
13920 
13921 
13922 static int
13923 st_update_block_pos(struct scsi_tape *un, bufunc_t bf, int post_space)
13924 {
13925 	int rval = ENOTTY;
13926 	uchar_t status = un->un_status;
13927 	posmode previous_pmode = un->un_running.pmode;
13928 
13929 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
13930 
13931 	while (un->un_read_pos_type != NO_POS) {
13932 		rval = bf(un, SCMD_READ_POSITION, 32, SYNC_CMD);
13933 
13934 		/*
13935 		 * If read position command returned good status
13936 		 * Parse the data to see if the position can be interpreted.
13937 		 */
13938 		if ((rval == 0) &&
13939 		    ((rval = st_interpret_read_pos(un, &un->un_pos,
13940 		    un->un_read_pos_type, 32, (caddr_t)un->un_read_pos_data,
13941 		    post_space)) == 0)) {
13942 			/*
13943 			 * Update the running position as well if un_pos was
13944 			 * ok. But only if recovery is enabled.
13945 			 */
13946 			if (st_recov_sz != sizeof (recov_info)) {
13947 				break;
13948 			}
13949 			rval = st_interpret_read_pos(un, &un->un_running,
13950 			    un->un_read_pos_type, 32,
13951 			    (caddr_t)un->un_read_pos_data, post_space);
13952 			un->un_status = status;
13953 			break;
13954 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
13955 			un->un_running.pmode = previous_pmode;
13956 			continue;
13957 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
13958 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13959 			    "st_update_block_pos() read position cmd 0x%x"
13960 			    " returned 0x%x un_status = %d",
13961 			    un->un_read_pos_type, rval, un->un_status);
13962 			/* ENOTTY means it read garbage. try something else. */
13963 			if (rval == ENOTTY) {
13964 				rval = EIO; /* so ENOTTY is not final rval */
13965 			} else {
13966 				break;
13967 			}
13968 		} else {
13969 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
13970 			    "st_update_block_pos() read position cmd %x"
13971 			    " returned %x", un->un_read_pos_type, rval);
13972 			un->un_running.pmode = previous_pmode;
13973 		}
13974 
13975 		switch (un->un_read_pos_type) {
13976 		case SHORT_POS:
13977 			un->un_read_pos_type = NO_POS;
13978 			break;
13979 
13980 		case LONG_POS:
13981 			un->un_read_pos_type = EXT_POS;
13982 			break;
13983 
13984 		case EXT_POS:
13985 			un->un_read_pos_type = SHORT_POS;
13986 			break;
13987 
13988 		default:
13989 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
13990 			    "Unexpected read position type 0x%x",
13991 			    un->un_read_pos_type);
13992 		}
13993 		un->un_status = KEY_NO_SENSE;
13994 	}
13995 
13996 	return (rval);
13997 }
13998 
13999 static int
14000 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
14001 {
14002 	int result;
14003 	size_t d_sz;
14004 	caddr_t pos_info;
14005 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
14006 
14007 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
14008 
14009 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
14010 		return (0);
14011 	}
14012 
14013 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
14014 
14015 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14016 		    "bp_mapin_common() failed");
14017 
14018 		return (EIO);
14019 	}
14020 
14021 	pos_info = bp->b_un.b_addr;
14022 	d_sz = bp->b_bcount - bp->b_resid;
14023 
14024 #ifdef STDEBUG
14025 	if ((st_debug & 0x7) > 2) {
14026 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14027 		    "st_get_read_pos() position info",
14028 		    pos_info, bp->b_bcount);
14029 	}
14030 #endif
14031 
14032 	result = st_interpret_read_pos(un, &un->un_pos, cmd->uscsi_cdb[1],
14033 	    d_sz, pos_info, 0);
14034 
14035 	COPY_POS(&un->un_running, &un->un_pos);
14036 
14037 	bp_mapout(bp);
14038 
14039 	return (result);
14040 }
14041 
14042 #if defined(_BIG_ENDIAN)
14043 
14044 #define	FIX_ENDIAN16(x)
14045 #define	FIX_ENDIAN32(x)
14046 #define	FIX_ENDIAN64(x)
14047 
14048 #elif defined(_LITTLE_ENDIAN)
14049 
14050 static void
14051 st_swap16(uint16_t *val)
14052 {
14053 	uint16_t tmp;
14054 
14055 	tmp = (*val >>  8) & 0xff;
14056 	tmp |= (*val <<  8) & 0xff00;
14057 
14058 	*val = tmp;
14059 }
14060 
14061 static void
14062 st_swap32(uint32_t *val)
14063 {
14064 	uint32_t tmp;
14065 
14066 	tmp =  (*val >> 24) & 0xff;
14067 	tmp |= (*val >>  8) & 0xff00;
14068 	tmp |= (*val <<  8) & 0xff0000;
14069 	tmp |= (*val << 24) & 0xff000000;
14070 
14071 	*val = tmp;
14072 }
14073 
14074 static void
14075 st_swap64(uint64_t *val)
14076 {
14077 	uint32_t low;
14078 	uint32_t high;
14079 
14080 	low =  (uint32_t)(*val);
14081 	high = (uint32_t)(*val >> 32);
14082 
14083 	st_swap32(&low);
14084 	st_swap32(&high);
14085 
14086 	*val =  high;
14087 	*val |= ((uint64_t)low << 32);
14088 }
14089 
14090 #define	FIX_ENDIAN16(x) st_swap16(x)
14091 #define	FIX_ENDIAN32(x) st_swap32(x)
14092 #define	FIX_ENDIAN64(x) st_swap64(x)
14093 #endif
14094 
14095 /*
14096  * st_interpret_read_pos()
14097  *
14098  * Returns:
14099  *	0	If secsessful.
14100  *	EIO	If read postion responce data was unuseable or invalid.
14101  *	ERANGE	If the position of the drive is too large for the read_p_type.
14102  *	ENOTTY	If the responce data looks invalid for the read position type.
14103  */
14104 
14105 static int
14106 st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
14107     read_p_types type, size_t data_sz, const caddr_t responce, int post_space)
14108 {
14109 	int rval = 0;
14110 	int flag = 0;
14111 	tapepos_t org;
14112 
14113 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
14114 
14115 	/*
14116 	 * We expect the position value to change after a space command.
14117 	 * So if post_space is set we don't print out what has changed.
14118 	 */
14119 	if ((dest != &un->un_pos) && (post_space == 0) &&
14120 	    (st_recov_sz == sizeof (recov_info))) {
14121 		COPY_POS(&org, dest);
14122 		flag = 1;
14123 	}
14124 
14125 	/*
14126 	 * See what kind of read position was requested.
14127 	 */
14128 	switch (type) {
14129 
14130 	case SHORT_POS: /* Short data format */
14131 	{
14132 		tape_position_t *pos_info = (tape_position_t *)responce;
14133 		uint32_t value;
14134 
14135 		/* If reserved fields are non zero don't use the data */
14136 		if (pos_info->reserved0 || pos_info->reserved1 ||
14137 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
14138 		    pos_info->reserved3) {
14139 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14140 			    "Invalid Read Short Position Data returned\n");
14141 			rval = EIO;
14142 			break;
14143 		}
14144 		/*
14145 		 * Position is to large to use this type of read position.
14146 		 */
14147 		if (pos_info->posi_err == 1) {
14148 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14149 			    "Drive reported position error\n");
14150 			rval = ERANGE;
14151 			break;
14152 		}
14153 		/*
14154 		 * If your at the begining of partition and end at the same
14155 		 * time it's very small partition or bad data.
14156 		 */
14157 		if (pos_info->begin_of_part && pos_info->end_of_part) {
14158 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14159 			    "SHORT_POS returned begin and end of"
14160 			    " partition\n");
14161 			rval = EIO;
14162 			break;
14163 		}
14164 
14165 		if (pos_info->blk_posi_unkwn == 0) {
14166 
14167 			value = pos_info->host_block;
14168 			FIX_ENDIAN32(&value);
14169 
14170 			/*
14171 			 * If the tape is rewound the host blcok should be 0.
14172 			 */
14173 			if ((pos_info->begin_of_part == 1) &&
14174 			    (value != 0)) {
14175 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14176 				    "SHORT_POS returned begin of partition"
14177 				    " but host block was 0x%x\n", value);
14178 				rval = EIO;
14179 				break;
14180 			}
14181 
14182 			if (dest->lgclblkno != value) {
14183 				if (flag)
14184 					flag++;
14185 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14186 				    "SHORT_POS current logical 0x%"PRIx64" read"
14187 				    " 0x%x\n", dest->lgclblkno, value);
14188 			}
14189 
14190 			dest->lgclblkno = (uint64_t)value;
14191 
14192 			/*
14193 			 * If the begining of partition is true and the
14194 			 * block number is zero we will beleive that it is
14195 			 * rewound. Promote the pmode to legacy.
14196 			 */
14197 			if ((pos_info->begin_of_part == 1) &&
14198 			    (value == 0)) {
14199 				dest->blkno = 0;
14200 				dest->fileno = 0;
14201 				if (dest->pmode != legacy)
14202 					dest->pmode = legacy;
14203 			/*
14204 			 * otherwise if the pmode was invalid,
14205 			 * promote it to logical.
14206 			 */
14207 			} else if (dest->pmode == invalid) {
14208 				dest->pmode = logical;
14209 			}
14210 
14211 			if (dest->partition != pos_info->partition_number) {
14212 				if (flag)
14213 					flag++;
14214 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14215 				    "SHORT_POS current partition %d read %d\n",
14216 				    dest->partition,
14217 				    pos_info->partition_number);
14218 			}
14219 
14220 			dest->partition = pos_info->partition_number;
14221 
14222 		} else {
14223 			dest->pmode = invalid;
14224 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14225 			    "Tape drive reported block position as unknown\n");
14226 		}
14227 		break;
14228 	}
14229 
14230 	case LONG_POS: /* Long data format */
14231 	{
14232 		uint64_t value;
14233 		tape_position_long_t *long_pos_info =
14234 		    (tape_position_long_t *)responce;
14235 
14236 		/* If reserved fields are non zero don't use the data */
14237 		if ((long_pos_info->reserved0) ||
14238 		    (long_pos_info->reserved1) ||
14239 		    (long_pos_info->reserved2)) {
14240 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14241 			    "Invalid Read Long Position Data returned\n");
14242 			rval = ENOTTY;
14243 			break;
14244 		}
14245 
14246 		/* Is position Valid */
14247 		if (long_pos_info->blk_posi_unkwn == 0) {
14248 			uint32_t part;
14249 
14250 			value = long_pos_info->block_number;
14251 			FIX_ENDIAN64(&value);
14252 
14253 			/*
14254 			 * If it says we are at the begining of partition
14255 			 * the block value better be 0.
14256 			 */
14257 			if ((long_pos_info->begin_of_part == 1) &&
14258 			    (value != 0)) {
14259 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14260 				    "LONG_POS returned begin of partition but"
14261 				    " block number was 0x%"PRIx64"\n", value);
14262 				rval = ENOTTY;
14263 				break;
14264 			}
14265 			/*
14266 			 * Can't be at the start and the end of the partition
14267 			 * at the same time if the partition is larger the 0.
14268 			 */
14269 			if (long_pos_info->begin_of_part &&
14270 			    long_pos_info->end_of_part) {
14271 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14272 				    "LONG_POS returned begin and end of"
14273 				    " partition\n");
14274 				rval = ENOTTY;
14275 				break;
14276 			}
14277 
14278 			/*
14279 			 * If the logical block number is not what we expected.
14280 			 */
14281 			if (dest->lgclblkno != value) {
14282 				if (flag)
14283 					flag++;
14284 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14285 				    "LONG_POS current logical 0x%"PRIx64
14286 				    " read 0x%"PRIx64"\n",
14287 				    dest->lgclblkno, value);
14288 			}
14289 			dest->lgclblkno = value;
14290 
14291 			/*
14292 			 * If the begining of partition is true and the
14293 			 * block number is zero we will beleive that it is
14294 			 * rewound. Promote the pmode to legacy.
14295 			 */
14296 			if ((long_pos_info->begin_of_part == 1) &&
14297 			    (long_pos_info->block_number == 0)) {
14298 				dest->blkno = 0;
14299 				dest->fileno = 0;
14300 				if (dest->pmode != legacy)
14301 					dest->pmode = legacy;
14302 			/*
14303 			 * otherwise if the pmode was invalid,
14304 			 * promote it to logical.
14305 			 */
14306 			} else if (dest->pmode == invalid) {
14307 				dest->pmode = logical;
14308 			}
14309 
14310 			part = long_pos_info->partition;
14311 			FIX_ENDIAN32(&part);
14312 			if (dest->partition != part) {
14313 				if (flag)
14314 					flag++;
14315 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14316 				    "LONG_POS current partition %d"
14317 				    " read %d\n", dest->partition, part);
14318 			}
14319 			dest->partition = part;
14320 		} else {
14321 			/*
14322 			 * If the drive doesn't know location,
14323 			 * we don't either.
14324 			 */
14325 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14326 			    "Tape drive reported block position as unknown\n");
14327 			dest->pmode = invalid;
14328 		}
14329 
14330 		/* Is file position valid */
14331 		if (long_pos_info->mrk_posi_unkwn == 0) {
14332 			value = long_pos_info->file_number;
14333 			FIX_ENDIAN64(&value);
14334 			/*
14335 			 * If it says we are at the begining of partition
14336 			 * the block value better be 0.
14337 			 */
14338 			if ((long_pos_info->begin_of_part == 1) &&
14339 			    (value != 0)) {
14340 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14341 				    "LONG_POS returned begin of partition but"
14342 				    " block number was 0x%"PRIx64"\n", value);
14343 				rval = ENOTTY;
14344 				break;
14345 			}
14346 			if (((dest->pmode == legacy) ||
14347 			    (dest->pmode == logical)) &&
14348 			    (dest->fileno != value)) {
14349 				if (flag)
14350 					flag++;
14351 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14352 				    "LONG_POS fileno 0x%"PRIx64
14353 				    " not un_pos %x\n", value,
14354 				    dest->fileno);
14355 			} else if (dest->pmode == invalid) {
14356 				dest->pmode = logical;
14357 			}
14358 			dest->fileno = (int32_t)value;
14359 		} else {
14360 			/*
14361 			 * If the drive doesn't know its position,
14362 			 * we don't either.
14363 			 */
14364 			dest->pmode = invalid;
14365 		}
14366 		if (dest->pmode != invalid && long_pos_info->end_of_part) {
14367 			dest->eof = ST_EOT;
14368 		}
14369 
14370 		break;
14371 	}
14372 
14373 	case EXT_POS: /* Extended data format */
14374 	{
14375 		uint64_t value;
14376 		uint16_t len;
14377 		tape_position_ext_t *ext_pos_info =
14378 		    (tape_position_ext_t *)responce;
14379 
14380 		/* Make sure that there is enough data there */
14381 		if (data_sz < 16) {
14382 			break;
14383 		}
14384 
14385 		/* If reserved fields are non zero don't use the data */
14386 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
14387 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14388 			    "EXT_POS reserved fields not zero\n");
14389 			rval = ENOTTY;
14390 			break;
14391 		}
14392 
14393 		/*
14394 		 * In the unlikely event of overflowing 64 bits of position.
14395 		 */
14396 		if (ext_pos_info->posi_err != 0) {
14397 			rval = ERANGE;
14398 			break;
14399 		}
14400 
14401 		len = ext_pos_info->parameter_len;
14402 		FIX_ENDIAN16(&len);
14403 
14404 		if (len != 0x1c) {
14405 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14406 			    "EXT_POS parameter_len should be 0x1c was 0x%x\n",
14407 			    len);
14408 			rval = ENOTTY;
14409 			break;
14410 		}
14411 
14412 		/* Is block position information valid */
14413 		if (ext_pos_info->blk_posi_unkwn == 0) {
14414 
14415 			value = ext_pos_info->host_block;
14416 			FIX_ENDIAN64(&value);
14417 			if ((ext_pos_info->begin_of_part == 1) &&
14418 			    (value != 0)) {
14419 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14420 				    "EXT_POS returned begining of partition but"
14421 				    " the host block was 0x%"PRIx64"\n", value);
14422 				rval = ENOTTY;
14423 				break;
14424 			}
14425 
14426 			if (dest->lgclblkno != value) {
14427 				if (flag)
14428 					flag++;
14429 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14430 				    "EXT_POS current logical 0x%"PRIx64
14431 				    " read 0x%"PRIx64"\n",
14432 				    dest->lgclblkno, value);
14433 			}
14434 			dest->lgclblkno = value;
14435 
14436 			/*
14437 			 * If the begining of partition is true and the
14438 			 * block number is zero we will beleive that it is
14439 			 * rewound. Promote the pmode to legacy.
14440 			 */
14441 			if ((ext_pos_info->begin_of_part == 1) &&
14442 			    (ext_pos_info->host_block == 0)) {
14443 				dest->blkno = 0;
14444 				dest->fileno = 0;
14445 				if (dest->pmode != legacy) {
14446 					dest->pmode = legacy;
14447 				}
14448 			/*
14449 			 * otherwise if the pmode was invalid,
14450 			 * promote it to logical.
14451 			 */
14452 			} else if (dest->pmode == invalid) {
14453 				dest->pmode = logical;
14454 			}
14455 
14456 			if (dest->partition != ext_pos_info->partition) {
14457 				if (flag)
14458 					flag++;
14459 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14460 				    "EXT_POS current partition %d read %d\n",
14461 				    dest->partition,
14462 				    ext_pos_info->partition);
14463 			}
14464 			dest->partition = ext_pos_info->partition;
14465 
14466 		} else {
14467 			dest->pmode = invalid;
14468 		}
14469 		break;
14470 	}
14471 
14472 	default:
14473 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14474 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
14475 		rval = EIO;
14476 	}
14477 
14478 	if ((flag > 1) && (rval == 0)) {
14479 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14480 		    "position read in", &org);
14481 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14482 		    "position read out", dest);
14483 	}
14484 
14485 	return (rval);
14486 }
14487 
14488 static int
14489 st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos,
14490     uint64_t lblk, uchar_t partition)
14491 {
14492 	int rval;
14493 	char cdb[CDB_GROUP4];
14494 	struct uscsi_cmd *cmd;
14495 	struct scsi_extended_sense sense;
14496 	bufunc_t bf = (ubf == st_uscsi_cmd) ? st_cmd : st_rcmd;
14497 
14498 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
14499 	/*
14500 	 * WTF Not sure what to do when doing recovery and not wanting
14501 	 * to update un_pos
14502 	 */
14503 
14504 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14505 
14506 	if (lblk <= INT32_MAX) {
14507 		cmd->uscsi_cdblen = CDB_GROUP1;
14508 		cdb[0] = SCMD_LOCATE;
14509 		cdb[1] = pos->partition == partition ? 0 : 2;
14510 		cdb[2] = 0;
14511 		cdb[3] = (char)(lblk >> 24);
14512 		cdb[4] = (char)(lblk >> 16);
14513 		cdb[5] = (char)(lblk >> 8);
14514 		cdb[6] = (char)(lblk);
14515 		cdb[7] = 0;
14516 		cdb[8] = partition;
14517 		cdb[9] = 0;
14518 	} else {
14519 		/*
14520 		 * If the drive doesn't give a 64 bit read position data
14521 		 * it is unlikely it will accept 64 bit locates.
14522 		 */
14523 		if (un->un_read_pos_type != LONG_POS) {
14524 			kmem_free(cmd, sizeof (struct uscsi_cmd));
14525 			return (ERANGE);
14526 		}
14527 		cmd->uscsi_cdblen = CDB_GROUP4;
14528 		cdb[0] = (char)SCMD_LOCATE_G4;
14529 		cdb[1] = pos->partition == partition ? 0 : 2;
14530 		cdb[2] = 0;
14531 		cdb[3] = partition;
14532 		cdb[4] = (char)(lblk >> 56);
14533 		cdb[5] = (char)(lblk >> 48);
14534 		cdb[6] = (char)(lblk >> 40);
14535 		cdb[7] = (char)(lblk >> 32);
14536 		cdb[8] = (char)(lblk >> 24);
14537 		cdb[9] = (char)(lblk >> 16);
14538 		cdb[10] = (char)(lblk >> 8);
14539 		cdb[11] = (char)(lblk);
14540 		cdb[12] = 0;
14541 		cdb[13] = 0;
14542 		cdb[14] = 0;
14543 		cdb[15] = 0;
14544 	}
14545 
14546 
14547 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
14548 	cmd->uscsi_rqbuf = (caddr_t)&sense;
14549 	cmd->uscsi_rqlen = sizeof (sense);
14550 	cmd->uscsi_timeout = un->un_dp->space_timeout;
14551 	cmd->uscsi_cdb = cdb;
14552 
14553 	rval = ubf(un, cmd, FKIOCTL);
14554 
14555 	pos->pmode = logical;
14556 	pos->eof = ST_NO_EOF;
14557 
14558 	if (lblk > INT32_MAX) {
14559 		/*
14560 		 * XXX This is a work around till we handle Descriptor format
14561 		 * sense data. Since we are sending a command where the standard
14562 		 * sense data can not correctly represent a correct residual in
14563 		 * 4 bytes.
14564 		 */
14565 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
14566 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14567 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
14568 			/* Doesn't like big locate command */
14569 			un->un_status = 0;
14570 			rval = ERANGE;
14571 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
14572 			/* Aborted big locate command */
14573 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14574 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
14575 			    rval);
14576 			un->un_status = 0;
14577 			rval = EIO;
14578 		} else if (st_update_block_pos(un, bf, 1)) {
14579 			/* read position failed */
14580 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14581 			    "Big LOCATE and read pos: rval = %d\n", rval);
14582 			rval = EIO;
14583 		} else if (lblk > un->un_pos.lgclblkno) {
14584 			/* read position worked but position was not expected */
14585 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14586 			    "Big LOCATE and recover read less then desired 0x%"
14587 			    PRIx64"\n", un->un_pos.lgclblkno);
14588 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
14589 			un->un_status = KEY_BLANK_CHECK;
14590 			rval = ESPIPE;
14591 		} else if (lblk == un->un_pos.lgclblkno) {
14592 			/* read position was what was expected */
14593 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14594 			    "Big LOCATE and recover seems to have worked\n");
14595 			un->un_err_resid = 0;
14596 			rval = 0;
14597 		} else {
14598 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14599 			    "BIGLOCATE end up going backwards");
14600 			un->un_err_resid = lblk;
14601 			rval = EIO;
14602 		}
14603 
14604 	} else if (rval == 0) {
14605 		/* Worked as requested */
14606 		pos->lgclblkno = lblk;
14607 
14608 	} else if (((cmd->uscsi_status & STATUS_MASK) == STATUS_CHECK) &&
14609 	    (cmd->uscsi_resid != 0)) {
14610 		/* Got part way there but wasn't enough blocks on tape */
14611 		pos->lgclblkno = lblk - cmd->uscsi_resid;
14612 		un->un_err_resid = cmd->uscsi_resid;
14613 		un->un_status = KEY_BLANK_CHECK;
14614 		rval = ESPIPE;
14615 
14616 	} else if (st_update_block_pos(un, bf, 1) == 0) {
14617 		/* Got part way there but drive didn't tell what we missed by */
14618 		un->un_err_resid = lblk - pos->lgclblkno;
14619 		un->un_status = KEY_BLANK_CHECK;
14620 		rval = ESPIPE;
14621 
14622 	} else {
14623 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14624 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
14625 		    rval, cmd->uscsi_status);
14626 		un->un_err_resid = lblk;
14627 		un->un_status = KEY_ILLEGAL_REQUEST;
14628 		pos->pmode = invalid;
14629 		rval = EIO;
14630 	}
14631 
14632 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14633 
14634 	return (rval);
14635 }
14636 
14637 static int
14638 st_mtfsf_ioctl(struct scsi_tape *un, int files)
14639 {
14640 	int rval;
14641 
14642 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
14643 
14644 
14645 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14646 	    "st_mtfsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
14647 #if 0
14648 	if ((IN_EOF(un->un_pos)) && (files == 1)) {
14649 		un->un_pos.fileno++;
14650 		un->un_pos.blkno = 0;
14651 		return (0);
14652 	}
14653 #endif
14654 	/* pmode == invalid already handled */
14655 	if (un->un_pos.pmode == legacy) {
14656 		/*
14657 		 * forward space over filemark
14658 		 *
14659 		 * For ASF we allow a count of 0 on fsf which means
14660 		 * we just want to go to beginning of current file.
14661 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
14662 		 * Allow stepping over double fmk with reel
14663 		 */
14664 		if ((un->un_pos.eof >= ST_EOT) &&
14665 		    (files > 0) &&
14666 		    ((un->un_dp->options & ST_REEL) == 0)) {
14667 			/* we're at EOM */
14668 			un->un_err_resid = files;
14669 			un->un_status = KEY_BLANK_CHECK;
14670 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14671 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
14672 			return (EIO);
14673 		}
14674 
14675 		/*
14676 		 * physical tape position may not be what we've been
14677 		 * telling the user; adjust the request accordingly
14678 		 */
14679 		if (IN_EOF(un->un_pos)) {
14680 			un->un_pos.fileno++;
14681 			un->un_pos.blkno = 0;
14682 			/*
14683 			 * For positive direction case, we're now covered.
14684 			 * For zero or negative direction, we're covered
14685 			 * (almost)
14686 			 */
14687 			files--;
14688 		}
14689 
14690 	}
14691 
14692 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
14693 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14694 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
14695 		return (EIO);
14696 	}
14697 
14698 
14699 	/*
14700 	 * Forward space file marks.
14701 	 * We leave ourselves at block zero
14702 	 * of the target file number.
14703 	 */
14704 	if (files < 0) {
14705 		rval = st_backward_space_files(un, -files, 0);
14706 	} else {
14707 		rval = st_forward_space_files(un, files);
14708 	}
14709 
14710 	return (rval);
14711 }
14712 
14713 static int
14714 st_forward_space_files(struct scsi_tape *un, int count)
14715 {
14716 	int rval;
14717 
14718 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
14719 
14720 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14721 	    "fspace: count=%x, eof=%x\n", count, un->un_pos.eof);
14722 
14723 	ASSERT(count >= 0);
14724 	ASSERT(un->un_pos.pmode != invalid);
14725 
14726 	/*
14727 	 * A space with a count of zero means take me to the start of file.
14728 	 */
14729 	if (count == 0) {
14730 
14731 		/* Hay look were already there */
14732 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0) {
14733 			un->un_err_resid = 0;
14734 			COPY_POS(&un->un_err_pos, &un->un_pos);
14735 			return (0);
14736 		}
14737 
14738 		/*
14739 		 * Well we are in the first file.
14740 		 * A rewind will get to the start.
14741 		 */
14742 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
14743 			rval = st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
14744 
14745 		/*
14746 		 * Can we backspace to get there?
14747 		 * This should work in logical mode.
14748 		 */
14749 		} else if (un->un_dp->options & ST_BSF) {
14750 			rval = st_space_to_begining_of_file(un);
14751 
14752 		/*
14753 		 * Can't back space but current file number is known,
14754 		 * So rewind and space from the begining of the partition.
14755 		 */
14756 		} else if (un->un_pos.pmode == legacy) {
14757 			rval = st_scenic_route_to_begining_of_file(un,
14758 			    un->un_pos.fileno);
14759 
14760 		/*
14761 		 * pmode is logical and ST_BSF is not set.
14762 		 * The LONG_POS read position contains the fileno.
14763 		 * If the read position works, rewind and space.
14764 		 */
14765 		} else if (un->un_read_pos_type == LONG_POS) {
14766 			rval = st_cmd(un, SCMD_READ_POSITION, 0, SYNC_CMD);
14767 			if (rval) {
14768 				/*
14769 				 * We didn't get the file position from the
14770 				 * read position command.
14771 				 * We are going to trust the drive to backspace
14772 				 * and then position after the filemark.
14773 				 */
14774 				rval = st_space_to_begining_of_file(un);
14775 			}
14776 			rval = st_interpret_read_pos(un, &un->un_pos, LONG_POS,
14777 			    32, (caddr_t)un->un_read_pos_data, 0);
14778 			if ((rval) && (un->un_pos.pmode == invalid)) {
14779 				rval = st_space_to_begining_of_file(un);
14780 			} else {
14781 				rval = st_scenic_route_to_begining_of_file(un,
14782 				    un->un_pos.fileno);
14783 			}
14784 		} else {
14785 			rval = EIO;
14786 		}
14787 		/*
14788 		 * If something didn't work we are lost
14789 		 */
14790 		if (rval != 0) {
14791 			un->un_pos.pmode = invalid;
14792 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14793 			    "st_mtioctop : EIO : fspace pmode invalid");
14794 
14795 			rval = EIO;
14796 		}
14797 
14798 	} else {
14799 		rval = st_space_fmks(un, count);
14800 	}
14801 
14802 	if (rval != EIO && count < 0) {
14803 		/*
14804 		 * we came here with a count < 0; we now need
14805 		 * to skip back to end up before the filemark
14806 		 */
14807 		rval = st_backward_space_files(un, 1, 1);
14808 	}
14809 
14810 	return (rval);
14811 }
14812 
14813 static int
14814 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
14815 {
14816 	int rval;
14817 
14818 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
14819 
14820 	if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
14821 		rval = EIO;
14822 	} else if (st_cmd(un, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
14823 		rval = EIO;
14824 	}
14825 
14826 	return (rval);
14827 }
14828 
14829 static int
14830 st_space_to_begining_of_file(struct scsi_tape *un)
14831 {
14832 	int rval;
14833 
14834 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
14835 
14836 	/*
14837 	 * Back space of the file at the begining of the file.
14838 	 */
14839 	rval = st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
14840 	if (rval) {
14841 		rval = EIO;
14842 		return (rval);
14843 	}
14844 
14845 	/*
14846 	 * Other interesting answers might be crashed BOT which isn't bad.
14847 	 */
14848 	if (un->un_status == SUN_KEY_BOT) {
14849 		return (rval);
14850 	}
14851 
14852 	un->un_running.pmode = invalid;
14853 
14854 	/*
14855 	 * Now we are on the BOP side of the filemark. Forward space to
14856 	 * the EOM side and we are at the begining of the file.
14857 	 */
14858 	rval = st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD);
14859 	if (rval) {
14860 		rval = EIO;
14861 	}
14862 
14863 	return (rval);
14864 }
14865 
14866 static int
14867 st_mtfsr_ioctl(struct scsi_tape *un, int count)
14868 {
14869 
14870 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
14871 
14872 	/*
14873 	 * forward space to inter-record gap
14874 	 *
14875 	 */
14876 
14877 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14878 	    "st_ioctl_fsr: count=%x, eof=%x\n", count, un->un_pos.eof);
14879 
14880 	if (un->un_pos.pmode == legacy) {
14881 		/*
14882 		 * If were are at end of tape and count is forward.
14883 		 * Return blank check.
14884 		 */
14885 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
14886 			/* we're at EOM */
14887 			un->un_err_resid = count;
14888 			un->un_status = KEY_BLANK_CHECK;
14889 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14890 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
14891 			return (EIO);
14892 		}
14893 
14894 		/*
14895 		 * If count is zero there is nothing to do.
14896 		 */
14897 		if (count == 0) {
14898 			un->un_err_pos.fileno = un->un_pos.fileno;
14899 			un->un_err_pos.blkno = un->un_pos.blkno;
14900 			un->un_err_resid = 0;
14901 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
14902 				un->un_status = SUN_KEY_EOF;
14903 			}
14904 			return (0);
14905 		}
14906 
14907 		/*
14908 		 * physical tape position may not be what we've been
14909 		 * telling the user; adjust the position accordingly
14910 		 */
14911 		if (IN_EOF(un->un_pos)) {
14912 			daddr_t blkno = un->un_pos.blkno;
14913 			int fileno = un->un_pos.fileno;
14914 
14915 			optype lastop = un->un_lastop;
14916 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)
14917 			    == -1) {
14918 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14919 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
14920 				return (EIO);
14921 			}
14922 
14923 			un->un_pos.blkno = blkno;
14924 			un->un_pos.fileno = fileno;
14925 			un->un_lastop = lastop;
14926 		}
14927 	}
14928 
14929 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
14930 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14931 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
14932 		return (EIO);
14933 	}
14934 
14935 	return (st_space_records(un, count));
14936 }
14937 
14938 static int
14939 st_space_records(struct scsi_tape *un, int count)
14940 {
14941 	int dblk;
14942 	int rval = 0;
14943 
14944 	ST_FUNC(ST_DEVINFO, st_space_records);
14945 
14946 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14947 	    "st_space_records: count=%x, eof=%x\n", count, un->un_pos.eof);
14948 
14949 	if (un->un_pos.pmode == logical) {
14950 		rval = st_cmd(un, SCMD_SPACE, Blk(count), SYNC_CMD);
14951 		if (rval != 0) {
14952 			rval = EIO;
14953 		}
14954 		return (rval);
14955 	}
14956 
14957 	dblk = un->un_pos.blkno + count;
14958 
14959 	/* Already there */
14960 	if (dblk == un->un_pos.blkno) {
14961 		un->un_err_resid = 0;
14962 		COPY_POS(&un->un_err_pos, &un->un_pos);
14963 		return (0);
14964 	}
14965 
14966 	/*
14967 	 * If the destination block is forward
14968 	 * or the drive will backspace records.
14969 	 */
14970 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
14971 		/*
14972 		 * If we're spacing forward, or the device can
14973 		 * backspace records, we can just use the SPACE
14974 		 * command.
14975 		 */
14976 		dblk -= un->un_pos.blkno;
14977 		if (st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
14978 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14979 			    "st_space_records:EIO:space_records can't spc");
14980 			rval = EIO;
14981 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
14982 			/*
14983 			 * check if we hit BOT/EOT
14984 			 */
14985 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
14986 				un->un_status = SUN_KEY_BOT;
14987 				un->un_pos.eof = ST_NO_EOF;
14988 			} else if (dblk < 0 &&
14989 			    un->un_pos.eof == ST_EOF_PENDING) {
14990 				int residue = un->un_err_resid;
14991 				/*
14992 				 * we skipped over a filemark
14993 				 * and need to go forward again
14994 				 */
14995 				if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
14996 					ST_DEBUG2(ST_DEVINFO, st_label,
14997 					    SCSI_DEBUG, "st_space_records: EIO"
14998 					    " : can't space #2");
14999 					rval = EIO;
15000 				}
15001 				un->un_err_resid = residue;
15002 			}
15003 			if (rval == 0) {
15004 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15005 				    "st_space_records: EIO : space_rec rval"
15006 				    " == 0");
15007 				rval = EIO;
15008 			}
15009 		}
15010 	} else {
15011 		/*
15012 		 * else we rewind, space forward across filemarks to
15013 		 * the desired file, and then space records to the
15014 		 * desired block.
15015 		 */
15016 
15017 		int dfile = un->un_pos.fileno;	/* save current file */
15018 
15019 		if (dblk < 0) {
15020 			/*
15021 			 * Wups - we're backing up over a filemark
15022 			 */
15023 			if (un->un_pos.blkno != 0 &&
15024 			    (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15025 			    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD))) {
15026 				un->un_pos.pmode = invalid;
15027 			}
15028 			un->un_err_resid = -dblk;
15029 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
15030 				un->un_status = SUN_KEY_BOT;
15031 				un->un_pos.eof = ST_NO_EOF;
15032 			} else if (un->un_pos.fileno > 0) {
15033 				un->un_status = SUN_KEY_EOF;
15034 				un->un_pos.eof = ST_NO_EOF;
15035 			}
15036 			COPY_POS(&un->un_err_pos, &un->un_pos);
15037 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15038 			    "st_space_records:EIO:space_records : dblk < 0");
15039 			rval = EIO;
15040 		} else if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15041 		    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
15042 		    st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15043 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15044 			    "st_space_records: EIO :space_records : rewind "
15045 			    "and space failed");
15046 			un->un_pos.pmode = invalid;
15047 			rval = EIO;
15048 		}
15049 	}
15050 
15051 	return (rval);
15052 }
15053 
15054 static int
15055 st_mtbsf_ioctl(struct scsi_tape *un, int files)
15056 {
15057 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
15058 
15059 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15060 	    "st_mtbsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
15061 	/*
15062 	 * backward space of file filemark (1/2" and 8mm)
15063 	 * tape position will end on the beginning of tape side
15064 	 * of the desired file mark
15065 	 */
15066 	if ((un->un_dp->options & ST_BSF) == 0) {
15067 		return (ENOTTY);
15068 	}
15069 
15070 	if (un->un_pos.pmode == legacy) {
15071 
15072 		/*
15073 		 * If a negative count (which implies a forward space op)
15074 		 * is specified, and we're at logical or physical eot,
15075 		 * bounce the request.
15076 		 */
15077 
15078 		if (un->un_pos.eof >= ST_EOT && files < 0) {
15079 			un->un_err_resid = files;
15080 			un->un_status = SUN_KEY_EOT;
15081 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15082 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
15083 			return (EIO);
15084 		}
15085 		/*
15086 		 * physical tape position may not be what we've been
15087 		 * telling the user; adjust the request accordingly
15088 		 */
15089 		if (IN_EOF(un->un_pos)) {
15090 			un->un_pos.fileno++;
15091 			un->un_pos.blkno = 0;
15092 			files++;
15093 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15094 			    "st_mtbsf_ioctl in eof: count=%d, op=%x\n",
15095 			    files, MTBSF);
15096 
15097 		}
15098 	}
15099 
15100 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15101 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15102 		    "st_ioctl : EIO : MTBSF : check den wfm");
15103 		return (EIO);
15104 	}
15105 
15106 	if (files <= 0) {
15107 		/*
15108 		 * for a negative count, we need to step forward
15109 		 * first and then step back again
15110 		 */
15111 		files = -files + 1;
15112 		return (st_forward_space_files(un, files));
15113 	}
15114 	return (st_backward_space_files(un, files, 1));
15115 }
15116 
15117 static int
15118 st_backward_space_files(struct scsi_tape *un, int count, int infront)
15119 {
15120 	int end_fileno;
15121 	int skip_cnt;
15122 	int rval = 0;
15123 
15124 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
15125 
15126 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15127 	    "st_backward_space_files: count=%x eof=%x\n",
15128 	    count, un->un_pos.eof);
15129 	/*
15130 	 * Backspace files (MTNBSF): infront == 0
15131 	 *
15132 	 *	For tapes that can backspace, backspace
15133 	 *	count+1 filemarks and then run forward over
15134 	 *	a filemark
15135 	 *
15136 	 *	For tapes that can't backspace,
15137 	 *		calculate desired filenumber
15138 	 *		(un->un_pos.fileno - count), rewind,
15139 	 *		and then space forward this amount
15140 	 *
15141 	 * Backspace filemarks (MTBSF) infront == 1
15142 	 *
15143 	 *	For tapes that can backspace, backspace count
15144 	 *	filemarks
15145 	 *
15146 	 *	For tapes that can't backspace, calculate
15147 	 *	desired filenumber (un->un_pos.fileno - count),
15148 	 *	add 1, rewind, space forward this amount,
15149 	 *	and mark state as ST_EOF_PENDING appropriately.
15150 	 */
15151 
15152 	if (un->un_pos.pmode == logical) {
15153 
15154 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15155 		    "st_backward_space_files: mt_op=%x count=%x"
15156 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
15157 		    un->un_pos.lgclblkno);
15158 
15159 
15160 		/* In case a drive that won't back space gets in logical mode */
15161 		if ((un->un_dp->options & ST_BSF) == 0) {
15162 			rval = EIO;
15163 			return (rval);
15164 		}
15165 		if (st_cmd(un, SCMD_SPACE, Fmk(-count), SYNC_CMD)) {
15166 			rval = EIO;
15167 			return (rval);
15168 		}
15169 		if ((infront != 0) &&
15170 		    (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
15171 			rval = EIO;
15172 			return (rval);
15173 		}
15174 		return (rval);
15175 	}
15176 
15177 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15178 	    "st_backward_space_files: mt_op=%x count=%x fileno=%x blkno=%x\n",
15179 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
15180 
15181 
15182 
15183 	/*
15184 	 * Handle the simple case of BOT
15185 	 * playing a role in these cmds.
15186 	 * We do this by calculating the
15187 	 * ending file number. If the ending
15188 	 * file is < BOT, rewind and set an
15189 	 * error and mark resid appropriately.
15190 	 * If we're backspacing a file (not a
15191 	 * filemark) and the target file is
15192 	 * the first file on the tape, just
15193 	 * rewind.
15194 	 */
15195 
15196 	/* figure expected destination of this SPACE command */
15197 	end_fileno = un->un_pos.fileno - count;
15198 
15199 	/*
15200 	 * Would the end effect of this SPACE be the same as rewinding?
15201 	 * If so just rewind instead.
15202 	 */
15203 	if ((infront != 0) && (end_fileno < 0) ||
15204 	    (infront == 0) && (end_fileno <= 0)) {
15205 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15206 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15207 			    "st_backward_space_files: EIO : "
15208 			    "rewind in lou of BSF failed\n");
15209 			rval = EIO;
15210 		}
15211 		if (end_fileno < 0) {
15212 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15213 			    "st_backward_space_files: EIO : "
15214 			    "back space file greater then fileno\n");
15215 			rval = EIO;
15216 			un->un_err_resid = -end_fileno;
15217 			un->un_status = SUN_KEY_BOT;
15218 		}
15219 		return (rval);
15220 	}
15221 
15222 	if (un->un_dp->options & ST_BSF) {
15223 		skip_cnt = 1 - infront;
15224 		/*
15225 		 * If we are going to end up at the beginning
15226 		 * of the file, we have to space one extra file
15227 		 * first, and then space forward later.
15228 		 */
15229 		end_fileno = -(count + skip_cnt);
15230 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15231 		    "skip_cnt=%x, tmp=%x\n", skip_cnt, end_fileno);
15232 		if (st_cmd(un, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
15233 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15234 			    "st_backward_space_files:EIO:back space fm failed");
15235 			rval = EIO;
15236 		}
15237 	} else {
15238 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15239 			rval = EIO;
15240 		} else {
15241 			skip_cnt = end_fileno + infront;
15242 		}
15243 	}
15244 
15245 	/*
15246 	 * If we have to space forward, do so...
15247 	 */
15248 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15249 	    "space forward skip_cnt=%x, rval=%x\n", skip_cnt, rval);
15250 
15251 	if (rval == 0 && skip_cnt) {
15252 		if (st_cmd(un, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
15253 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15254 			    "st_backward_space_files:EIO:space fm skip count");
15255 			rval = EIO;
15256 		} else if (infront) {
15257 			/*
15258 			 * If we had to space forward, and we're
15259 			 * not a tape that can backspace, mark state
15260 			 * as if we'd just seen a filemark during a
15261 			 * a read.
15262 			 */
15263 			if ((un->un_dp->options & ST_BSF) == 0) {
15264 				un->un_pos.eof = ST_EOF_PENDING;
15265 				un->un_pos.fileno -= 1;
15266 				un->un_pos.blkno = LASTBLK;
15267 				un->un_running.pmode = invalid;
15268 			}
15269 		}
15270 	}
15271 
15272 	if (rval != 0) {
15273 		un->un_pos.pmode = invalid;
15274 	}
15275 
15276 	return (rval);
15277 }
15278 
15279 static int
15280 st_mtnbsf_ioctl(struct scsi_tape *un, int count)
15281 {
15282 	int rval;
15283 
15284 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
15285 
15286 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15287 	    "nbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
15288 
15289 	if (un->un_pos.pmode == legacy) {
15290 		/*
15291 		 * backward space file to beginning of file
15292 		 *
15293 		 * If a negative count (which implies a forward space op)
15294 		 * is specified, and we're at logical or physical eot,
15295 		 * bounce the request.
15296 		 */
15297 
15298 		if (un->un_pos.eof >= ST_EOT && count < 0) {
15299 			un->un_err_resid = count;
15300 			un->un_status = SUN_KEY_EOT;
15301 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15302 			    "st_ioctl : EIO : > EOT and count < 0");
15303 			return (EIO);
15304 		}
15305 		/*
15306 		 * physical tape position may not be what we've been
15307 		 * telling the user; adjust the request accordingly
15308 		 */
15309 		if (IN_EOF(un->un_pos)) {
15310 			un->un_pos.fileno++;
15311 			un->un_pos.blkno = 0;
15312 			count++;
15313 		}
15314 	}
15315 
15316 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15317 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15318 		    "st_ioctl : EIO : MTNBSF check den and wfm");
15319 		return (EIO);
15320 	}
15321 
15322 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15323 	    "mtnbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
15324 
15325 	if (count <= 0) {
15326 		rval = st_forward_space_files(un, -count);
15327 	} else {
15328 		rval = st_backward_space_files(un, count, 0);
15329 	}
15330 	return (rval);
15331 }
15332 
15333 static int
15334 st_mtbsr_ioctl(struct scsi_tape *un, int num)
15335 {
15336 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
15337 
15338 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15339 	    "bsr: count=%x, eof=%x\n", num, un->un_pos.eof);
15340 
15341 	if (un->un_pos.pmode == legacy) {
15342 		/*
15343 		 * backward space into inter-record gap
15344 		 *
15345 		 * If a negative count (which implies a forward space op)
15346 		 * is specified, and we're at logical or physical eot,
15347 		 * bounce the request.
15348 		 */
15349 		if (un->un_pos.eof >= ST_EOT && num < 0) {
15350 			un->un_err_resid = num;
15351 			un->un_status = SUN_KEY_EOT;
15352 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15353 			    "st_ioctl : EIO : MTBSR > EOT");
15354 			return (EIO);
15355 		}
15356 
15357 		if (num == 0) {
15358 			COPY_POS(&un->un_err_pos, &un->un_pos);
15359 			un->un_err_resid = 0;
15360 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15361 				un->un_status = SUN_KEY_EOF;
15362 			}
15363 			return (0);
15364 		}
15365 
15366 		/*
15367 		 * physical tape position may not be what we've been
15368 		 * telling the user; adjust the position accordingly.
15369 		 * bsr can not skip filemarks and continue to skip records
15370 		 * therefore if we are logically before the filemark but
15371 		 * physically at the EOT side of the filemark, we need to step
15372 		 * back; this allows fsr N where N > number of blocks in file
15373 		 * followed by bsr 1 to position at the beginning of last block
15374 		 */
15375 		if (IN_EOF(un->un_pos)) {
15376 			tapepos_t save;
15377 			optype lastop = un->un_lastop;
15378 
15379 			COPY_POS(&save, &un->un_pos);
15380 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD) == -1) {
15381 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15382 				    "st_mtbsr_ioctl: EIO : MTBSR can't space");
15383 				return (EIO);
15384 			}
15385 
15386 			COPY_POS(&un->un_pos, &save);
15387 			un->un_lastop = lastop;
15388 		}
15389 	}
15390 
15391 	un->un_pos.eof = ST_NO_EOF;
15392 
15393 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15394 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15395 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
15396 		return (EIO);
15397 	}
15398 
15399 	num = -num;
15400 	return (st_space_records(un, num));
15401 }
15402 
15403 static int
15404 st_mtfsfm_ioctl(struct scsi_tape *un, int cnt)
15405 {
15406 	int rval;
15407 
15408 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
15409 
15410 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
15411 	if (rval == 0) {
15412 		un->un_pos.pmode = logical;
15413 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15414 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15415 		/*
15416 		 * Drive says invalid field in cdb.
15417 		 * Doesn't like space multiple. Position isn't lost.
15418 		 */
15419 		un->un_err_resid = cnt;
15420 		un->un_status = 0;
15421 		rval = ENOTTY;
15422 	} else {
15423 		un->un_err_resid = cnt;
15424 		un->un_pos.pmode = invalid;
15425 	}
15426 	return (rval);
15427 }
15428 
15429 static int
15430 st_mtbsfm_ioctl(struct scsi_tape *un, int cnt)
15431 {
15432 	int rval;
15433 
15434 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
15435 
15436 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
15437 	if (rval == 0) {
15438 		un->un_pos.pmode = logical;
15439 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15440 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15441 		/*
15442 		 * Drive says invalid field in cdb.
15443 		 * Doesn't like space multiple. Position isn't lost.
15444 		 */
15445 		un->un_err_resid = cnt;
15446 		un->un_status = 0;
15447 		rval = ENOTTY;
15448 	} else {
15449 		un->un_err_resid = cnt;
15450 		un->un_pos.pmode = invalid;
15451 	}
15452 	return (rval);
15453 }
15454 
15455 #ifdef	__x86
15456 
15457 /*
15458  * release contig_mem and wake up waiting thread, if any
15459  */
15460 static void
15461 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
15462 {
15463 	mutex_enter(ST_MUTEX);
15464 
15465 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
15466 
15467 	cp->cm_next = un->un_contig_mem;
15468 	un->un_contig_mem = cp;
15469 	un->un_contig_mem_available_num++;
15470 	cv_broadcast(&un->un_contig_mem_cv);
15471 
15472 	mutex_exit(ST_MUTEX);
15473 }
15474 
15475 /*
15476  * St_get_contig_mem will return a contig_mem if there is one available
15477  * in current system. Otherwise, it will try to alloc one, if the total
15478  * number of contig_mem is within st_max_contig_mem_num.
15479  * It will sleep, if allowed by caller or return NULL, if no contig_mem
15480  * is available for now.
15481  */
15482 static struct contig_mem *
15483 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
15484 {
15485 	size_t rlen;
15486 	struct contig_mem *cp = NULL;
15487 	ddi_acc_handle_t acc_hdl;
15488 	caddr_t addr;
15489 	int big_enough = 0;
15490 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
15491 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
15492 
15493 	/* Try to get one available contig_mem */
15494 	mutex_enter(ST_MUTEX);
15495 
15496 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
15497 
15498 	if (un->un_contig_mem_available_num > 0) {
15499 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15500 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
15501 		/*
15502 		 * we failed to get one. we're going to
15503 		 * alloc one more contig_mem for this I/O
15504 		 */
15505 		mutex_exit(ST_MUTEX);
15506 		cp = (struct contig_mem *)kmem_zalloc(
15507 		    sizeof (struct contig_mem) + biosize(),
15508 		    alloc_flags);
15509 		if (cp == NULL) {
15510 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15511 			    "alloc contig_mem failure\n");
15512 			return (NULL); /* cannot get one */
15513 		}
15514 		cp->cm_bp = (struct buf *)
15515 		    (((caddr_t)cp) + sizeof (struct contig_mem));
15516 		bioinit(cp->cm_bp);
15517 		mutex_enter(ST_MUTEX);
15518 		un->un_contig_mem_total_num++; /* one more available */
15519 	} else {
15520 		/*
15521 		 * we failed to get one and we're NOT allowed to
15522 		 * alloc more contig_mem
15523 		 */
15524 		if (alloc_flags == KM_SLEEP) {
15525 			while (un->un_contig_mem_available_num <= 0) {
15526 				cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
15527 			}
15528 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15529 		} else {
15530 			mutex_exit(ST_MUTEX);
15531 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15532 			    "alloc contig_mem failure\n");
15533 			return (NULL); /* cannot get one */
15534 		}
15535 	}
15536 	mutex_exit(ST_MUTEX);
15537 
15538 	/* We need to check if this block of mem is big enough for this I/O */
15539 	if (cp->cm_len < len) {
15540 		/* not big enough, need to alloc a new one */
15541 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
15542 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
15543 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
15544 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15545 			    "alloc contig_mem failure: not enough mem\n");
15546 			st_release_contig_mem(un, cp);
15547 			cp = NULL;
15548 		} else {
15549 			if (cp->cm_addr) {
15550 				/* release previous one before attach new one */
15551 				ddi_dma_mem_free(&cp->cm_acc_hdl);
15552 			}
15553 			mutex_enter(ST_MUTEX);
15554 			un->un_max_contig_mem_len =
15555 			    un->un_max_contig_mem_len >= len ?
15556 			    un->un_max_contig_mem_len : len;
15557 			mutex_exit(ST_MUTEX);
15558 
15559 			/* attach new mem to this cp */
15560 			cp->cm_addr = addr;
15561 			cp->cm_acc_hdl = acc_hdl;
15562 			cp->cm_len = len;
15563 
15564 			goto alloc_ok; /* get one usable cp */
15565 		}
15566 	} else {
15567 		goto alloc_ok; /* get one usable cp */
15568 	}
15569 
15570 	/* cannot find/alloc a usable cp, when we get here */
15571 
15572 	mutex_enter(ST_MUTEX);
15573 	if ((un->un_max_contig_mem_len < len) ||
15574 	    (alloc_flags != KM_SLEEP)) {
15575 		mutex_exit(ST_MUTEX);
15576 		return (NULL);
15577 	}
15578 
15579 	/*
15580 	 * we're allowed to sleep, and there is one big enough
15581 	 * contig mem in the system, which is currently in use,
15582 	 * wait for it...
15583 	 */
15584 	big_enough = 1;
15585 	do {
15586 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
15587 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15588 	} while (cp == NULL);
15589 	mutex_exit(ST_MUTEX);
15590 
15591 	/* we get the big enough contig mem, finally */
15592 
15593 alloc_ok:
15594 	/* init bp attached to this cp */
15595 	bioreset(cp->cm_bp);
15596 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
15597 	cp->cm_bp->b_private = (void *)cp;
15598 
15599 	return (cp);
15600 }
15601 
15602 /*
15603  * this is the biodone func for the bp used in big block I/O
15604  */
15605 static int
15606 st_bigblk_xfer_done(struct buf *bp)
15607 {
15608 	struct contig_mem *cp;
15609 	struct buf *orig_bp;
15610 	int ioerr;
15611 	struct scsi_tape *un;
15612 
15613 	/* sanity check */
15614 	if (bp == NULL) {
15615 		return (DDI_FAILURE);
15616 	}
15617 
15618 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
15619 	if (un == NULL) {
15620 		return (DDI_FAILURE);
15621 	}
15622 
15623 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
15624 
15625 	cp = (struct contig_mem *)bp->b_private;
15626 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
15627 	cp->cm_bp = bp;
15628 
15629 	/* special handling for special I/O */
15630 	if (cp->cm_use_sbuf) {
15631 #ifndef __lock_lint
15632 		ASSERT(un->un_sbuf_busy);
15633 #endif
15634 		un->un_sbufp = orig_bp;
15635 		cp->cm_use_sbuf = 0;
15636 	}
15637 
15638 	orig_bp->b_resid = bp->b_resid;
15639 	ioerr = geterror(bp);
15640 	if (ioerr != 0) {
15641 		bioerror(orig_bp, ioerr);
15642 	} else if (orig_bp->b_flags & B_READ) {
15643 		/* copy data back to original bp */
15644 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
15645 		    bp->b_bcount - bp->b_resid);
15646 	}
15647 
15648 	st_release_contig_mem(un, cp);
15649 
15650 	biodone(orig_bp);
15651 
15652 	return (DDI_SUCCESS);
15653 }
15654 
15655 /*
15656  * We use this func to replace original bp that may not be able to do I/O
15657  * in big block size with one that can
15658  */
15659 static struct buf *
15660 st_get_bigblk_bp(struct buf *bp)
15661 {
15662 	struct contig_mem *cp;
15663 	struct scsi_tape *un;
15664 	struct buf *cont_bp;
15665 
15666 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
15667 	if (un == NULL) {
15668 		return (bp);
15669 	}
15670 
15671 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
15672 
15673 	/* try to get one contig_mem */
15674 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
15675 	if (!cp) {
15676 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
15677 		    "Cannot alloc contig buf for I/O for %lu blk size",
15678 		    bp->b_bcount);
15679 		return (bp);
15680 	}
15681 	cont_bp = cp->cm_bp;
15682 	cp->cm_bp = bp;
15683 
15684 	/* make sure that we "are" using un_sbufp for special I/O */
15685 	if (bp == un->un_sbufp) {
15686 #ifndef __lock_lint
15687 		ASSERT(un->un_sbuf_busy);
15688 #endif
15689 		un->un_sbufp = cont_bp;
15690 		cp->cm_use_sbuf = 1;
15691 	}
15692 
15693 	/* clone bp */
15694 	cont_bp->b_bcount = bp->b_bcount;
15695 	cont_bp->b_resid = bp->b_resid;
15696 	cont_bp->b_iodone = st_bigblk_xfer_done;
15697 	cont_bp->b_file = bp->b_file;
15698 	cont_bp->b_offset = bp->b_offset;
15699 	cont_bp->b_dip = bp->b_dip;
15700 	cont_bp->b_error = 0;
15701 	cont_bp->b_proc = NULL;
15702 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
15703 	cont_bp->b_shadow = NULL;
15704 	cont_bp->b_pages = NULL;
15705 	cont_bp->b_edev = bp->b_edev;
15706 	cont_bp->b_dev = bp->b_dev;
15707 	cont_bp->b_lblkno = bp->b_lblkno;
15708 	cont_bp->b_forw = bp->b_forw;
15709 	cont_bp->b_back = bp->b_back;
15710 	cont_bp->av_forw = bp->av_forw;
15711 	cont_bp->av_back = bp->av_back;
15712 	cont_bp->b_bufsize = bp->b_bufsize;
15713 
15714 	/* get data in original bp */
15715 	if (bp->b_flags & B_WRITE) {
15716 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
15717 	}
15718 
15719 	return (cont_bp);
15720 }
15721 #else
15722 #ifdef __lock_lint
15723 static int
15724 st_bigblk_xfer_done(struct buf *bp)
15725 {
15726 	return (0);
15727 }
15728 #endif
15729 #endif
15730 
15731 static const char *eof_status[] =
15732 {
15733 	"NO_EOF",
15734 	"EOF_PENDING",
15735 	"EOF",
15736 	"EOT_PENDING",
15737 	"EOT",
15738 	"EOM",
15739 	"AFTER_EOM"
15740 };
15741 static const char *mode[] = {
15742 	"invalid",
15743 	"legacy",
15744 	"logical"
15745 };
15746 
15747 static void
15748 st_print_position(dev_info_t *dev, char *label, uint_t level,
15749 const char *comment, tapepos_t *pos)
15750 {
15751 	ST_FUNC(dev, st_print_position);
15752 
15753 	scsi_log(dev, label, level,
15754 	    "%s Position data:\n", comment);
15755 	scsi_log(dev, label, CE_CONT,
15756 	    "Positioning mode = %s", mode[pos->pmode]);
15757 	scsi_log(dev, label, CE_CONT,
15758 	    "End Of File/Tape = %s", eof_status[pos->eof]);
15759 	scsi_log(dev, label, CE_CONT,
15760 	    "File Number      = 0x%x", pos->fileno);
15761 	scsi_log(dev, label, CE_CONT,
15762 	    "Block Number     = 0x%x", pos->blkno);
15763 	scsi_log(dev, label, CE_CONT,
15764 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
15765 	scsi_log(dev, label, CE_CONT,
15766 	    "Partition Number = 0x%x", pos->partition);
15767 }
15768 static int
15769 st_check_if_media_changed(struct scsi_tape *un, caddr_t data, int size)
15770 {
15771 
15772 	int result = 0;
15773 	int i;
15774 	ST_FUNC(ST_DEVINFO, st_check_if_media_changed);
15775 
15776 	/*
15777 	 * find non alpha numeric working from the end.
15778 	 */
15779 	for (i = size - 1; i; i--) {
15780 		if (ISALNUM(data[i]) == 0 || data[i] == ' ') {
15781 			data[i] = 0;
15782 			size = i;
15783 		}
15784 	}
15785 
15786 	if (size == 1) {
15787 		/*
15788 		 * Drive seems to think its returning useful data
15789 		 * but it looks like all junk
15790 		 */
15791 		return (result);
15792 	}
15793 
15794 	size++;
15795 
15796 	/*
15797 	 * Actually got a valid serial number.
15798 	 * If never stored one before alloc space for it.
15799 	 */
15800 	if (un->un_media_id_len == 0) {
15801 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
15802 		un->un_media_id_len = size;
15803 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
15804 		un->un_media_id[min(size, strlen(data))] = 0;
15805 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
15806 		    "Found Media Id %s length = %d\n", un->un_media_id, size);
15807 	} else if (size > un->un_media_id_len) {
15808 		if (strncmp(un->un_media_id, data, size) != 0) {
15809 			result = ESPIPE;
15810 		}
15811 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
15812 		    "Longer Media Id old ID:%s new ID:%s\n",
15813 		    un->un_media_id, data);
15814 		kmem_free(un->un_media_id, un->un_media_id_len);
15815 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
15816 		un->un_media_id_len = size;
15817 		(void) strncpy(un->un_media_id, data, size);
15818 		un->un_media_id[size] = 0;
15819 	} else if (strncmp(data, un->un_media_id,
15820 	    min(size, un->un_media_id_len)) != 0) {
15821 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
15822 		    "Old Media Id %s length = %d New %s length = %d\n",
15823 		    un->un_media_id, un->un_media_id_len, data, size);
15824 		bzero(un->un_media_id, un->un_media_id_len);
15825 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
15826 		un->un_media_id[min(size, strlen(data))] = 0;
15827 		result = ESPIPE;
15828 	} else {
15829 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15830 		    "Media Id still %s\n", un->un_media_id);
15831 	}
15832 
15833 	ASSERT(strlen(un->un_media_id) <= size);
15834 
15835 	return (result);
15836 }
15837 #define	ID_SIZE 32
15838 typedef struct
15839 {
15840 	uchar_t avilable_data0;
15841 	uchar_t avilable_data1;
15842 	uchar_t avilable_data2;
15843 	uchar_t avilable_data3;
15844 	uchar_t attribute_msb;
15845 	uchar_t attribute_lsb;
15846 #ifdef _BIT_FIELDS_LTOH
15847 	uchar_t format		: 2,
15848 				: 5,
15849 		read_only	: 1;
15850 #else
15851 	uchar_t read_only	: 1,
15852 				: 5,
15853 		format		: 2;
15854 #endif
15855 	uchar_t attribute_len_msb;
15856 	uchar_t attribute_len_lsb;
15857 }attribute_header;
15858 
15859 typedef struct {
15860 	attribute_header header;
15861 	char data[1];
15862 }mam_attribute;
15863 
15864 static int
15865 st_handle_hex_media_id(struct scsi_tape *un, void *pnt, int size)
15866 {
15867 	int result;
15868 	int newsize = (size + 1) << 1;
15869 	int i;
15870 	char byte;
15871 	char *format;
15872 	char *data = (char *)pnt;
15873 	char *buf = kmem_alloc(newsize, KM_SLEEP);
15874 
15875 	ST_FUNC(ST_DEVINFO, st_handle_hex_media_id);
15876 
15877 	(void) sprintf(buf, "0x");
15878 	for (i = 0; i < size; i++) {
15879 		byte = (uchar_t)data[i];
15880 		if (byte < 0x10)
15881 			format = "0%x";
15882 		else
15883 			format = "%x";
15884 		(void) sprintf(&buf[(int)strlen(buf)], format, byte);
15885 	}
15886 	result = st_check_if_media_changed(un, buf, newsize);
15887 
15888 	kmem_free(buf, newsize);
15889 
15890 	return (result);
15891 }
15892 
15893 
15894 static int
15895 st_get_media_id_via_read_attribute(struct scsi_tape *un, ubufunc_t bufunc)
15896 {
15897 	int result;
15898 	mam_attribute *buffer;
15899 	int size;
15900 	int newsize;
15901 
15902 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_read_attribute);
15903 	size = sizeof (attribute_header) + max(un->un_media_id_len, ID_SIZE);
15904 again:
15905 	buffer = kmem_zalloc(size, KM_SLEEP);
15906 	result = st_read_attributes(un, 0x0401, buffer, size, bufunc);
15907 	if (result == 0) {
15908 
15909 		newsize = (buffer->header.attribute_len_msb << 8) |
15910 		    buffer->header.attribute_len_lsb;
15911 
15912 		if (newsize + sizeof (attribute_header) > size) {
15913 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15914 			    "resizing read attribute data from %d to %d format"
15915 			    " %d\n", size, (int)sizeof (attribute_header) +
15916 			    newsize, buffer->header.format);
15917 			kmem_free(buffer, size);
15918 			size = newsize + sizeof (attribute_header);
15919 			goto again;
15920 		}
15921 
15922 		un->un_media_id_method = st_get_media_id_via_read_attribute;
15923 		if (buffer->header.format == 0) {
15924 			result =
15925 			    st_handle_hex_media_id(un, buffer->data, newsize);
15926 		} else {
15927 			result = st_check_if_media_changed(un, buffer->data,
15928 			    newsize);
15929 		}
15930 	} else if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
15931 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
15932 		    "Read Attribute Command for Media Identification is not "
15933 		    "supported on the HBA that this drive is attached to.");
15934 		result = ENOTTY;
15935 	}
15936 
15937 	kmem_free(buffer, size);
15938 	un->un_status = 0;
15939 
15940 	return (result);
15941 }
15942 
15943 
15944 static int
15945 st_get_media_id_via_media_serial_cmd(struct scsi_tape *un, ubufunc_t bufunc)
15946 {
15947 	char cdb[CDB_GROUP5];
15948 	struct uscsi_cmd *ucmd;
15949 	struct scsi_extended_sense sense;
15950 	int rval;
15951 	int size = max(un->un_media_id_len, ID_SIZE);
15952 	caddr_t buf;
15953 
15954 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_media_serial_cmd);
15955 
15956 	ucmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
15957 upsize:
15958 	buf = kmem_alloc(size, KM_SLEEP);
15959 
15960 	cdb[0] = (char)SCMD_SVC_ACTION_IN_G5;
15961 	cdb[1] = 1; /* READ MEDIA SERIAL NUMBER */
15962 	cdb[2] = 0;
15963 	cdb[3] = 0;
15964 	cdb[4] = 0;
15965 	cdb[5] = 0;
15966 	cdb[6] = (char)(size >> 24);
15967 	cdb[7] = (char)(size >> 16);
15968 	cdb[8] = (char)(size >> 8);
15969 	cdb[9] = (char)(size);
15970 	cdb[10] = 0;
15971 	cdb[11] = 0;
15972 
15973 	ucmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
15974 	ucmd->uscsi_timeout = un->un_dp->non_motion_timeout;
15975 	ucmd->uscsi_cdb = &cdb[0];
15976 	ucmd->uscsi_cdblen = sizeof (cdb);
15977 	ucmd->uscsi_bufaddr = buf;
15978 	ucmd->uscsi_buflen = size;
15979 	ucmd->uscsi_rqbuf = (caddr_t)&sense;
15980 	ucmd->uscsi_rqlen = sizeof (sense);
15981 
15982 	rval = bufunc(un, ucmd, FKIOCTL);
15983 
15984 	if (rval || ucmd->uscsi_status != 0) {
15985 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
15986 		    "media serial command returned %d scsi_status %d"
15987 		    " rqstatus %d", rval, ucmd->uscsi_status,
15988 		    ucmd->uscsi_rqstatus);
15989 		/*
15990 		 * If this returns invalid operation code don't try again.
15991 		 */
15992 		if (sense.es_key == KEY_ILLEGAL_REQUEST &&
15993 		    sense.es_add_code == 0x20) {
15994 			rval = ENOTTY;
15995 		} else if (rval == 0) {
15996 			rval = EIO;
15997 		}
15998 		un->un_status = 0;
15999 	} else {
16000 		int act_size;
16001 
16002 		/*
16003 		 * get reported size.
16004 		 */
16005 		act_size = (int)buf[3] | (int)(buf[2] << 8) |
16006 		    (int)(buf[1] << 16) | (int)(buf[0] << 24);
16007 
16008 		/* documentation says mod 4. */
16009 		while (act_size & 3) {
16010 			act_size++;
16011 		}
16012 
16013 		/*
16014 		 * If reported size is larger that we our buffer.
16015 		 * Free the old one and allocate one that is larger
16016 		 * enough and re-issuse the command.
16017 		 */
16018 		if (act_size + 4 > size) {
16019 			kmem_free(buf, size);
16020 			size = act_size + 4;
16021 			goto upsize;
16022 		}
16023 
16024 		/*
16025 		 * set data pointer to point to the start of that serial number.
16026 		 */
16027 		un->un_media_id_method = st_get_media_id_via_media_serial_cmd;
16028 		rval = st_check_if_media_changed(un, &buf[4], act_size);
16029 	}
16030 
16031 	kmem_free(ucmd, sizeof (struct uscsi_cmd));
16032 	kmem_free(buf, size);
16033 
16034 	return (rval);
16035 }
16036 
16037 
16038 /* ARGSUSED */
16039 static int
16040 st_bogus_media_id(struct scsi_tape *un, ubufunc_t bufunc)
16041 {
16042 	ST_FUNC(ST_DEVINFO, st_bogus_media_id);
16043 
16044 	ASSERT(un->un_media_id == NULL || un->un_media_id == bogusID);
16045 	ASSERT(un->un_media_id_len == 0);
16046 	un->un_media_id = (char *)bogusID;
16047 	un->un_media_id_len = 0;
16048 	return (0);
16049 }
16050 
16051 typedef int (*media_chk_function)(struct scsi_tape *, ubufunc_t bufunc);
16052 
16053 media_chk_function media_chk_functions[] = {
16054 	st_get_media_id_via_media_serial_cmd,
16055 	st_get_media_id_via_read_attribute,
16056 	st_bogus_media_id
16057 };
16058 
16059 static int
16060 st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc)
16061 {
16062 	int result = 0;
16063 	int i;
16064 
16065 	ST_FUNC(ST_DEVINFO, st_get_media_identification);
16066 
16067 	for (i = 0; i < ST_NUM_MEMBERS(media_chk_functions); i++) {
16068 		if (result == ENOTTY) {
16069 			/*
16070 			 * Last operation type not supported by this device.
16071 			 * Make so next time it doesn`t do that again.
16072 			 */
16073 			un->un_media_id_method = media_chk_functions[i];
16074 		} else if (un->un_media_id_method != media_chk_functions[i] &&
16075 		    un->un_media_id_method != st_get_media_identification) {
16076 			continue;
16077 		}
16078 		result = media_chk_functions[i](un, bufunc);
16079 		/*
16080 		 * If result indicates the function was successful or
16081 		 * that the media is not the same as last known, break.
16082 		 */
16083 		if (result == 0 || result == ESPIPE) {
16084 			break;
16085 		}
16086 	}
16087 
16088 	return (result);
16089 }
16090 
16091 static errstate
16092 st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
16093     errstate onentry)
16094 {
16095 
16096 	int ret;
16097 	st_err_info *errinfo;
16098 	recov_info *ri = (recov_info *)pkt->pkt_private;
16099 
16100 	ST_FUNC(ST_DEVINFO, st_command_recovery);
16101 
16102 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16103 
16104 	ASSERT(un->un_recov_buf_busy == 0);
16105 
16106 	/*
16107 	 * Don't try and recover a reset that this device sent.
16108 	 */
16109 	if (un->un_rsvd_status & ST_INITIATED_RESET &&
16110 	    onentry == DEVICE_RESET) {
16111 		return (COMMAND_DONE_ERROR);
16112 	}
16113 
16114 	/*
16115 	 * See if expected position was passed with scsi_pkt.
16116 	 */
16117 	if (ri->privatelen == sizeof (recov_info)) {
16118 
16119 		/*
16120 		 * Not for this command.
16121 		 */
16122 		if (ri->cmd_attrib->do_not_recover) {
16123 			return (COMMAND_DONE_ERROR);
16124 		}
16125 
16126 		/*
16127 		 * Create structure to hold all error state info.
16128 		 */
16129 		errinfo = kmem_zalloc(sizeof (st_err_info), KM_SLEEP);
16130 		errinfo->ei_error_type = onentry;
16131 		errinfo->ei_failing_bp = ri->cmd_bp;
16132 		COPY_POS(&errinfo->ei_expected_pos, &ri->pos);
16133 	} else {
16134 		/* disabled */
16135 		return (COMMAND_DONE_ERROR);
16136 	}
16137 
16138 	bcopy(pkt, &errinfo->ei_failed_pkt, sizeof (struct scsi_pkt));
16139 	bcopy(pkt->pkt_scbp, &errinfo->ei_failing_status, SECMDS_STATUS_SIZE);
16140 	ret = ddi_taskq_dispatch(un->un_recov_taskq, st_recover, errinfo,
16141 	    DDI_NOSLEEP);
16142 	ASSERT(ret == DDI_SUCCESS);
16143 	if (ret != DDI_SUCCESS) {
16144 		kmem_free(errinfo, sizeof (st_err_info));
16145 		return (COMMAND_DONE_ERROR);
16146 	}
16147 	return (JUST_RETURN); /* release calling thread */
16148 }
16149 
16150 static void
16151 st_recov_ret(struct scsi_tape *un, st_err_info *errinfo, errstate err)
16152 {
16153 	int error_number;
16154 	buf_t *bp;
16155 
16156 
16157 	ST_FUNC(ST_DEVINFO, st_recov_ret);
16158 
16159 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16160 
16161 	bp = errinfo->ei_failing_bp;
16162 	kmem_free(errinfo, sizeof (st_err_info));
16163 
16164 	switch (err) {
16165 	case JUST_RETURN:
16166 		mutex_exit(&un->un_sd->sd_mutex);
16167 		return;
16168 
16169 	case COMMAND_DONE:
16170 	case COMMAND_DONE_ERROR_RECOVERED:
16171 		ST_DO_KSTATS(bp, kstat_runq_exit);
16172 		error_number = 0;
16173 		break;
16174 
16175 	case COMMAND_DONE_ERROR:
16176 	case COMMAND_DONE_EACCES:
16177 		ST_DO_KSTATS(bp, kstat_waitq_exit);
16178 		ST_DO_ERRSTATS(un, st_transerrs);
16179 		error_number = EIO;
16180 		st_set_pe_flag(un);
16181 		break;
16182 
16183 	default:
16184 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16185 		    "st_recov_ret with unhandled errstat %d\n", err);
16186 	}
16187 	st_bioerror(bp, error_number);
16188 	st_done_and_mutex_exit(un, bp);
16189 }
16190 
16191 static void
16192 st_recover(void *arg)
16193 {
16194 	st_err_info *const errinfo = (st_err_info *)arg;
16195 	uchar_t com = errinfo->ei_failed_pkt.pkt_cdbp[0];
16196 	struct scsi_tape *un;
16197 	tapepos_t cur_pos;
16198 	int rval;
16199 	errstate status = COMMAND_DONE_ERROR;
16200 	recov_info *rcv;
16201 	buf_t *bp;
16202 
16203 
16204 	rcv = errinfo->ei_failed_pkt.pkt_private;
16205 	ASSERT(rcv->privatelen == sizeof (recov_info));
16206 	bp = rcv->cmd_bp;
16207 
16208 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16209 
16210 	ASSERT(un != NULL);
16211 
16212 	mutex_enter(ST_MUTEX);
16213 
16214 	ST_FUNC(ST_DEVINFO, st_recover);
16215 
16216 	ST_CDB(ST_DEVINFO, "Recovering command",
16217 	    (caddr_t)errinfo->ei_failed_pkt.pkt_cdbp);
16218 	ST_SENSE(ST_DEVINFO, "sense status for failed command",
16219 	    (caddr_t)&errinfo->ei_failing_status,
16220 	    sizeof (struct scsi_arq_status));
16221 	ST_POS(ST_DEVINFO, rcv->cmd_attrib->recov_pos_type == POS_STARTING ?
16222 	    "starting position for recovery command" :
16223 	    "expected position for recovery command",
16224 	    &errinfo->ei_expected_pos);
16225 
16226 	rval = st_test_path_to_device(un);
16227 
16228 	/*
16229 	 * If the drive responed to the TUR lets try and get it to sync
16230 	 * any data it have in the buffer.
16231 	 */
16232 	if (rval == 0 && rcv->cmd_attrib->chg_tape_data) {
16233 		(void) st_rcmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
16234 	}
16235 	switch (errinfo->ei_error_type) {
16236 	case ATTEMPT_RETRY:
16237 	case COMMAND_TIMEOUT:
16238 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16239 		    "st_recover called with COMMAND_TIMEOUT, TUR returned %d\n",
16240 		    rval);
16241 		if (rval != 0) {
16242 			/* ping failed, we're done. */
16243 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16244 			return;
16245 		}
16246 
16247 		/*
16248 		 * If a reset occured fall through.
16249 		 */
16250 		if (un->un_unit_attention_flags == 0) {
16251 			break;
16252 		}
16253 		/* FALLTHROUGH */
16254 	case DEVICE_RESET:
16255 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16256 		    "st_recover called with DEVICE_RESET, TUR returned %d\n",
16257 		    rval);
16258 		/*
16259 		 * For now if we can't talk to the device we are done.
16260 		 */
16261 		if (rval) {
16262 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16263 			return;
16264 		}
16265 
16266 		if ((un->un_rsvd_status & ST_LOST_RESERVE) &&
16267 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] != SCMD_RELEASE)) {
16268 			rval = st_reserve_release(un, ST_RESERVE,
16269 			    st_uscsi_rcmd);
16270 			if (rval == 0) {
16271 				un->un_rsvd_status |= ST_RESERVE;
16272 				un->un_rsvd_status &= ~(ST_RELEASE |
16273 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
16274 				    ST_INITIATED_RESET);
16275 			} else {
16276 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16277 				return;
16278 			}
16279 			rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16280 			if (rval) {
16281 				rval = st_gen_mode_select(un, st_uscsi_rcmd,
16282 				    un->un_mspl, sizeof (struct seq_mode));
16283 			}
16284 			if (rval) {
16285 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16286 				return;
16287 			}
16288 		}
16289 		break;
16290 	case PATH_FAILED:
16291 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16292 		    "st_recover called with PATH_FAILED, TUR returned %d\n",
16293 		    rval);
16294 		if (rval != 0) {
16295 			/* ping failed, we're done. */
16296 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16297 			return;
16298 		}
16299 		break;
16300 	case DEVICE_TAMPER:
16301 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16302 		    "st_recover called with DEVICE_TAMPER, TUR returned %d\n",
16303 		    rval);
16304 		/*
16305 		 * Check if the ASC/ASCQ says mode data has changed.
16306 		 */
16307 		if (errinfo->ei_failing_status.sts_sensedata.es_add_code ==
16308 		    0x2a &&
16309 		    errinfo->ei_failing_status.sts_sensedata.es_qual_code ==
16310 		    0x01) {
16311 			/*
16312 			 * See if mode sense changed.
16313 			 */
16314 			rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16315 			/*
16316 			 * if not cross your fingers and go for it.
16317 			 */
16318 			if (rval == 0) {
16319 				st_recov_ret(un, errinfo, COMMAND_DONE);
16320 				return;
16321 			}
16322 			/*
16323 			 * If so change it back.
16324 			 */
16325 			rval = st_gen_mode_select(un, st_uscsi_rcmd,
16326 			    un->un_mspl, sizeof (struct seq_mode));
16327 			if (rval) {
16328 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16329 			}
16330 			st_recov_ret(un, errinfo, COMMAND_DONE);
16331 			return;
16332 		}
16333 		/*
16334 		 * if we have a media id and its not bogus.
16335 		 * Check to see if it the same.
16336 		 */
16337 		if (un->un_media_id != NULL && un->un_media_id != bogusID) {
16338 			rval = st_get_media_identification(un, st_uscsi_rcmd);
16339 			if (rval == ESPIPE) {
16340 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16341 				return;
16342 			}
16343 		}
16344 		break;
16345 	default:
16346 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16347 		    "Unhandled error type 0x%x in st_recover()\n", com);
16348 	}
16349 
16350 	/*
16351 	 * if command is retriable retry it
16352 	 */
16353 	if (rcv->cmd_attrib->retriable) {
16354 		status = st_recover_reissue_pkt(un, &errinfo->ei_failed_pkt);
16355 
16356 	/*
16357 	 * if drive doesn't support read position we are done
16358 	 */
16359 	} else if (un->un_read_pos_type == NO_POS) {
16360 		status = COMMAND_DONE_ERROR;
16361 	/*
16362 	 * If this command results in a changed tape position,
16363 	 * lets see where we are.
16364 	 */
16365 	} else if (rcv->cmd_attrib->chg_tape_pos) {
16366 		/*
16367 		 * XXX May be a reason to choose a different type here.
16368 		 * Long format has file position information.
16369 		 * Short and Extended have information about whats
16370 		 * in the buffer. St's positioning assumes in the buffer
16371 		 * to be the same as on tape.
16372 		 */
16373 		rval = st_compare_expected_position(un, errinfo,
16374 		    rcv->cmd_attrib, &cur_pos);
16375 		if (rval == 0) {
16376 			status = COMMAND_DONE;
16377 		} else if (rval == EAGAIN) {
16378 			status = st_recover_reissue_pkt(un,
16379 			    &errinfo->ei_failed_pkt);
16380 		} else {
16381 			status = COMMAND_DONE_ERROR;
16382 		}
16383 	} else {
16384 		ASSERT(0);
16385 	}
16386 
16387 	st_recov_ret(un, errinfo, status);
16388 }
16389 
16390 static void
16391 st_recov_cb(struct scsi_pkt *pkt)
16392 {
16393 	struct scsi_tape *un;
16394 	struct buf *bp;
16395 	recov_info *rcv;
16396 	errstate action = COMMAND_DONE;
16397 	int timout = ST_TRAN_BUSY_TIMEOUT; /* short (default) timeout */
16398 
16399 	/*
16400 	 * Get the buf from the packet.
16401 	 */
16402 	rcv = pkt->pkt_private;
16403 	ASSERT(rcv->privatelen == sizeof (recov_info));
16404 	bp = rcv->cmd_bp;
16405 
16406 	/*
16407 	 * get the unit from the buf.
16408 	 */
16409 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16410 	ASSERT(un != NULL);
16411 
16412 	ST_FUNC(ST_DEVINFO, st_recov_cb);
16413 
16414 	mutex_enter(ST_MUTEX);
16415 
16416 	ASSERT(bp == un->un_recov_buf);
16417 
16418 
16419 	switch (pkt->pkt_reason) {
16420 	case CMD_CMPLT:
16421 		if (un->un_arq_enabled && pkt->pkt_state & STATE_ARQ_DONE) {
16422 			action = st_handle_autosense(un, bp, &rcv->pos);
16423 		} else if (*pkt->pkt_scbp & (STATUS_BUSY | STATUS_CHECK)) {
16424 			action = st_check_error(un, pkt);
16425 		}
16426 		break;
16427 	case CMD_TIMEOUT:
16428 		action = COMMAND_TIMEOUT;
16429 		break;
16430 	default:
16431 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16432 		    "pkt_reason not handled yet %s",
16433 		    scsi_rname(pkt->pkt_reason));
16434 	}
16435 
16436 	switch (action) {
16437 	case COMMAND_DONE:
16438 		break;
16439 
16440 	case COMMAND_DONE_EACCES:
16441 		bioerror(bp, EACCES);
16442 		break;
16443 
16444 	case COMMAND_TIMEOUT:
16445 	case COMMAND_DONE_ERROR:
16446 		bioerror(bp, EIO);
16447 		break;
16448 
16449 	case QUE_BUSY_COMMAND:
16450 		/* longish timeout */
16451 		timout = ST_STATUS_BUSY_TIMEOUT;
16452 		/* FALLTHRU */
16453 	case QUE_COMMAND:
16454 	case DEVICE_TAMPER:
16455 	case ATTEMPT_RETRY:
16456 		/*
16457 		 * let st_handle_intr_busy put this bp back on waitq and make
16458 		 * checks to see if it is ok to requeue the command.
16459 		 */
16460 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
16461 
16462 		/*
16463 		 * Save the throttle before setting up the timeout
16464 		 */
16465 		if (un->un_throttle) {
16466 			un->un_last_throttle = un->un_throttle;
16467 		}
16468 		mutex_exit(ST_MUTEX);
16469 		if (st_handle_intr_busy(un, bp, timout) == 0) {
16470 			return;		/* timeout is setup again */
16471 		}
16472 		mutex_enter(ST_MUTEX);
16473 		un->un_pos.pmode = invalid;
16474 		un->un_err_resid = bp->b_resid = bp->b_bcount;
16475 		st_bioerror(bp, EIO);
16476 		st_set_pe_flag(un);
16477 		break;
16478 
16479 	default:
16480 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16481 		    "Unhandled recovery state 0x%x\n", action);
16482 	}
16483 
16484 	st_done_and_mutex_exit(un, bp);
16485 }
16486 
16487 static int
16488 st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait)
16489 {
16490 	struct buf *bp;
16491 	int err;
16492 
16493 	ST_FUNC(ST_DEVINFO, st_rcmd);
16494 
16495 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16496 	    "st_rcmd(un = 0x%p, com = 0x%x, count = %"PRIx64", wait = %d)\n",
16497 	    (void *)un, com, count, wait);
16498 
16499 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16500 	ASSERT(mutex_owned(ST_MUTEX));
16501 
16502 #ifdef STDEBUG
16503 	if ((st_debug & 0x7)) {
16504 		st_debug_cmds(un, com, count, wait);
16505 	}
16506 #endif
16507 
16508 	while (un->un_recov_buf_busy)
16509 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
16510 	un->un_recov_buf_busy = 1;
16511 
16512 	bp = un->un_recov_buf;
16513 	bzero(bp, sizeof (buf_t));
16514 
16515 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
16516 
16517 	err = st_setup_cmd(un, bp, com, count);
16518 
16519 	un->un_recov_buf_busy = 0;
16520 
16521 	cv_signal(&un->un_recov_buf_cv);
16522 
16523 	return (err);
16524 }
16525 
16526 /* args used */
16527 static int
16528 st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
16529 {
16530 	int rval;
16531 	buf_t *bp;
16532 
16533 	ST_FUNC(ST_DEVINFO, st_uscsi_rcmd);
16534 	ASSERT(flag == FKIOCTL);
16535 
16536 	/*
16537 	 * Get buffer resources...
16538 	 */
16539 	while (un->un_recov_buf_busy)
16540 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
16541 	un->un_recov_buf_busy = 1;
16542 
16543 	bp = un->un_recov_buf;
16544 	bzero(bp, sizeof (buf_t));
16545 
16546 	bp->b_forw = (struct buf *)(uintptr_t)ucmd->uscsi_cdb[0];
16547 	bp->b_back = (struct buf *)ucmd;
16548 
16549 	mutex_exit(ST_MUTEX);
16550 	rval = scsi_uscsi_handle_cmd(un->un_dev, UIO_SYSSPACE, ucmd,
16551 	    st_strategy, bp, NULL);
16552 	mutex_enter(ST_MUTEX);
16553 
16554 	ucmd->uscsi_resid = bp->b_resid;
16555 
16556 	/*
16557 	 * Free resources
16558 	 */
16559 	un->un_recov_buf_busy = 0;
16560 	cv_signal(&un->un_recov_buf_cv);
16561 
16562 	return (rval);
16563 }
16564 
16565 /*
16566  * Add data to scsi_pkt to help know what to do if the command fails.
16567  */
16568 static void
16569 st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
16570     struct scsi_pkt *pkt)
16571 {
16572 	uint64_t count;
16573 	recov_info *rinfo = (recov_info *)pkt->pkt_private;
16574 
16575 	ST_FUNC(ST_DEVINFO, st_add_recovery_info_to_pkt);
16576 
16577 	ASSERT(rinfo->privatelen == sizeof (pkt_info) ||
16578 	    rinfo->privatelen == sizeof (recov_info));
16579 
16580 	SET_BP_PKT(bp, pkt);
16581 	rinfo->cmd_bp = bp;
16582 
16583 	if (rinfo->privatelen != sizeof (recov_info)) {
16584 		return;
16585 	}
16586 
16587 	rinfo->cmd_bp = bp;
16588 
16589 	rinfo->cmd_attrib = NULL;
16590 
16591 	/*
16592 	 * lookup the command attributes and add them to the recovery info.
16593 	 */
16594 	rinfo->cmd_attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
16595 
16596 	ASSERT(rinfo->cmd_attrib);
16597 
16598 	/*
16599 	 * For commands that there is no way to figure the expected position
16600 	 * once completed, we save the position the command was started from
16601 	 * so that if they fail we can position back and try again.
16602 	 * This has already been done in st_cmd() or st_iscsi_cmd().
16603 	 */
16604 	if (rinfo->cmd_attrib->recov_pos_type == POS_STARTING) {
16605 		/* save current position as the starting position. */
16606 		COPY_POS(&rinfo->pos, &un->un_pos);
16607 		un->un_running.pmode = invalid;
16608 		return;
16609 	}
16610 
16611 	/*
16612 	 * Don't want to update the running position for recovery.
16613 	 */
16614 	if (bp == un->un_recov_buf) {
16615 		rinfo->pos.pmode = un->un_running.pmode;
16616 		return;
16617 	}
16618 	/*
16619 	 * If running position is invalid copy the current position.
16620 	 * Running being set invalid means we are not in a read, write
16621 	 * or write filemark sequence.
16622 	 * We'll copy the current position and start from there.
16623 	 */
16624 	if (un->un_running.pmode == invalid) {
16625 		COPY_POS(&un->un_running, &un->un_pos);
16626 		COPY_POS(&rinfo->pos, &un->un_running);
16627 	} else {
16628 		COPY_POS(&rinfo->pos, &un->un_running);
16629 		if (rinfo->pos.pmode == legacy) {
16630 			/*
16631 			 * Always should be more logical blocks then
16632 			 * data blocks and files marks.
16633 			 */
16634 			ASSERT((rinfo->pos.blkno >= 0) ?
16635 			    rinfo->pos.lgclblkno >=
16636 			    (rinfo->pos.blkno + rinfo->pos.fileno) : 1);
16637 		}
16638 	}
16639 
16640 	/*
16641 	 * If the command is not expected to change the drive position
16642 	 * then the running position should be the expected position.
16643 	 */
16644 	if (rinfo->cmd_attrib->chg_tape_pos == 0) {
16645 		ASSERT(rinfo->cmd_attrib->chg_tape_direction == DIR_NONE);
16646 		return;
16647 	}
16648 
16649 	if (rinfo->cmd_attrib->explicit) {
16650 		ASSERT(rinfo->pos.pmode != invalid);
16651 		ASSERT(rinfo->cmd_attrib->get_cnt);
16652 		count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
16653 		/*
16654 		 * This is a user generated CDB.
16655 		 */
16656 		if (bp == un->un_sbufp) {
16657 			uint64_t lbn;
16658 
16659 			lbn = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
16660 
16661 			/*
16662 			 * See if this CDB will generate a locate or change
16663 			 * partition.
16664 			 */
16665 			if ((lbn != un->un_running.lgclblkno) ||
16666 			    (pkt->pkt_cdbp[3] != un->un_running.partition)) {
16667 				rinfo->pos.partition = pkt->pkt_cdbp[3];
16668 				rinfo->pos.pmode = logical;
16669 				rinfo->pos.lgclblkno = lbn;
16670 				un->un_running.partition = pkt->pkt_cdbp[3];
16671 				un->un_running.pmode = logical;
16672 				un->un_running.lgclblkno = lbn;
16673 			}
16674 		} else {
16675 			uint64_t lbn = un->un_running.lgclblkno;
16676 
16677 			pkt->pkt_cdbp[3]  = (uchar_t)un->un_running.partition;
16678 
16679 			pkt->pkt_cdbp[4]  = (uchar_t)(lbn >> 56);
16680 			pkt->pkt_cdbp[5]  = (uchar_t)(lbn >> 48);
16681 			pkt->pkt_cdbp[6]  = (uchar_t)(lbn >> 40);
16682 			pkt->pkt_cdbp[7]  = (uchar_t)(lbn >> 32);
16683 			pkt->pkt_cdbp[8]  = (uchar_t)(lbn >> 24);
16684 			pkt->pkt_cdbp[9]  = (uchar_t)(lbn >> 16);
16685 			pkt->pkt_cdbp[10] = (uchar_t)(lbn >> 8);
16686 			pkt->pkt_cdbp[11] = (uchar_t)(lbn);
16687 		}
16688 		rinfo->pos.lgclblkno += count;
16689 		rinfo->pos.blkno += count;
16690 		un->un_running.lgclblkno += count;
16691 		return;
16692 	}
16693 
16694 	if (rinfo->cmd_attrib->chg_tape_pos) {
16695 
16696 		/* should not have got an invalid position from running. */
16697 		if (un->un_mediastate == MTIO_INSERTED) {
16698 			ASSERT(rinfo->pos.pmode != invalid);
16699 		}
16700 
16701 		/* should have either a get count or or get lba function */
16702 		ASSERT(rinfo->cmd_attrib->get_cnt != NULL ||
16703 		    rinfo->cmd_attrib->get_lba != NULL);
16704 
16705 		/* only explicit commands have both and they're handled above */
16706 		ASSERT(!(rinfo->cmd_attrib->get_cnt != NULL &&
16707 		    rinfo->cmd_attrib->get_lba != NULL));
16708 
16709 		/* if it has a get count function */
16710 		if (rinfo->cmd_attrib->get_cnt != NULL) {
16711 			count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
16712 			if (count == 0) {
16713 				return;
16714 			}
16715 			/*
16716 			 * Changes position but doesn't transfer data.
16717 			 * i.e. rewind, write_file_mark and load.
16718 			 */
16719 			if (rinfo->cmd_attrib->transfers_data == TRAN_NONE) {
16720 				switch (rinfo->cmd_attrib->chg_tape_direction) {
16721 				case DIR_NONE: /* Erase */
16722 					ASSERT(rinfo->cmd_attrib->cmd ==
16723 					    SCMD_ERASE);
16724 					break;
16725 				case DIR_FORW: /* write_file_mark */
16726 					rinfo->pos.fileno += count;
16727 					rinfo->pos.lgclblkno += count;
16728 					rinfo->pos.blkno = 0;
16729 					un->un_running.fileno += count;
16730 					un->un_running.lgclblkno += count;
16731 					un->un_running.blkno = 0;
16732 					break;
16733 				case DIR_REVC: /* rewind */
16734 					rinfo->pos.fileno = 0;
16735 					rinfo->pos.lgclblkno = 0;
16736 					rinfo->pos.blkno = 0;
16737 					rinfo->pos.eof = ST_NO_EOF;
16738 					rinfo->pos.pmode = legacy;
16739 					un->un_running.fileno = 0;
16740 					un->un_running.lgclblkno = 0;
16741 					un->un_running.blkno = 0;
16742 					un->un_running.eof = ST_NO_EOF;
16743 					if (un->un_running.pmode != legacy)
16744 						un->un_running.pmode = legacy;
16745 					break;
16746 				case DIR_EITH: /* Load unload */
16747 					ASSERT(rinfo->cmd_attrib->cmd ==
16748 					    SCMD_LOAD);
16749 					switch (count & (LD_LOAD | LD_RETEN |
16750 					    LD_RETEN | LD_HOLD)) {
16751 					case LD_UNLOAD:
16752 					case LD_RETEN:
16753 					case LD_HOLD:
16754 					case LD_LOAD | LD_HOLD:
16755 					case LD_EOT | LD_HOLD:
16756 					case LD_RETEN | LD_HOLD:
16757 						rinfo->pos.pmode = invalid;
16758 						un->un_running.pmode = invalid;
16759 						break;
16760 					case LD_EOT:
16761 					case LD_LOAD | LD_EOT:
16762 						rinfo->pos.eof = ST_EOT;
16763 						rinfo->pos.pmode = invalid;
16764 						un->un_running.eof = ST_EOT;
16765 						un->un_running.pmode = invalid;
16766 						break;
16767 					case LD_LOAD:
16768 					case LD_RETEN | LD_LOAD:
16769 						rinfo->pos.fileno = 0;
16770 						rinfo->pos.lgclblkno = 0;
16771 						rinfo->pos.blkno = 0;
16772 						rinfo->pos.eof = ST_NO_EOF;
16773 						rinfo->pos.pmode = legacy;
16774 						un->un_running.fileno = 0;
16775 						un->un_running.lgclblkno = 0;
16776 						un->un_running.blkno = 0;
16777 						un->un_running.eof = ST_NO_EOF;
16778 						break;
16779 					default:
16780 						ASSERT(0);
16781 					}
16782 					break;
16783 				default:
16784 					ASSERT(0);
16785 					break;
16786 				}
16787 			} else {
16788 				/*
16789 				 * Changes position and does transfer data.
16790 				 * i.e. read or write.
16791 				 */
16792 				switch (rinfo->cmd_attrib->chg_tape_direction) {
16793 				case DIR_FORW:
16794 					rinfo->pos.lgclblkno += count;
16795 					rinfo->pos.blkno += count;
16796 					un->un_running.lgclblkno += count;
16797 					un->un_running.blkno += count;
16798 					break;
16799 				case DIR_REVC:
16800 					rinfo->pos.lgclblkno -= count;
16801 					rinfo->pos.blkno -= count;
16802 					un->un_running.lgclblkno -= count;
16803 					un->un_running.blkno -= count;
16804 					break;
16805 				default:
16806 					ASSERT(0);
16807 					break;
16808 				}
16809 			}
16810 		} else if (rinfo->cmd_attrib->get_lba != NULL) {
16811 			/* Have a get LBA fuction. i.e. Locate */
16812 			ASSERT(rinfo->cmd_attrib->chg_tape_direction ==
16813 			    DIR_EITH);
16814 			count = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
16815 			un->un_running.lgclblkno = count;
16816 			un->un_running.blkno = 0;
16817 			un->un_running.fileno = 0;
16818 			un->un_running.pmode = logical;
16819 			rinfo->pos.lgclblkno = count;
16820 			rinfo->pos.pmode = invalid;
16821 		} else {
16822 			ASSERT(0);
16823 		}
16824 		return;
16825 	}
16826 
16827 	ST_CDB(ST_DEVINFO, "Unhanded CDB for position prediction",
16828 	    (char *)pkt->pkt_cdbp);
16829 
16830 }
16831 
16832 static int
16833 st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf)
16834 {
16835 	struct seq_mode *current;
16836 	int rval;
16837 	int i;
16838 	caddr_t this;
16839 	caddr_t that;
16840 
16841 	ST_FUNC(ST_DEVINFO, st_check_mode_for_change);
16842 
16843 	/* recovery called with mode tamper before mode selection */
16844 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
16845 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16846 		    "Mode Select not done yet");
16847 		return (0);
16848 	}
16849 
16850 	current = kmem_zalloc(sizeof (struct seq_mode), KM_SLEEP);
16851 
16852 	rval = st_gen_mode_sense(un, ubf, un->un_comp_page, current,
16853 	    sizeof (struct seq_mode));
16854 	if (rval != 0) {
16855 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16856 		    "Mode Sense for mode verification failed");
16857 		kmem_free(current, sizeof (struct seq_mode));
16858 		return (rval);
16859 	}
16860 
16861 	this = (caddr_t)current;
16862 	that = (caddr_t)un->un_mspl;
16863 
16864 	rval = bcmp(this, that, sizeof (struct seq_mode));
16865 	if (rval == 0) {
16866 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16867 		    "Found no changes in mode data");
16868 	}
16869 #ifdef STDEBUG
16870 	else {
16871 		for (i = 1; i < sizeof (struct seq_mode); i++) {
16872 			if (this[i] != that[i]) {
16873 				ST_RECOV(ST_DEVINFO, st_label, CE_CONT,
16874 				    "sense data changed at byte %d was "
16875 				    "0x%x now 0x%x", i,
16876 				    (uchar_t)that[i], (uchar_t)this[i]);
16877 			}
16878 		}
16879 	}
16880 #endif
16881 	kmem_free(current, sizeof (struct seq_mode));
16882 
16883 	return (rval);
16884 }
16885 
16886 static int
16887 st_test_path_to_device(struct scsi_tape *un)
16888 {
16889 	int rval;
16890 
16891 	ST_FUNC(ST_DEVINFO, st_test_path_to_device);
16892 
16893 	/*
16894 	 * XXX Newer drives may not RESEVATION CONFLICT a TUR.
16895 	 */
16896 	do {
16897 		rval = st_rcmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
16898 	} while (rval == DEVICE_RESET);
16899 
16900 	return (rval);
16901 }
16902 
16903 /*
16904  * Does read position using recov_buf and doesn't update un_pos.
16905  * Does what ever kind of read position you want.
16906  */
16907 static int
16908 st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
16909     read_pos_data_t *raw)
16910 {
16911 	int rval;
16912 	struct uscsi_cmd cmd;
16913 	char cdb[CDB_GROUP1];
16914 
16915 	ST_FUNC(ST_DEVINFO, st_recovery_read_pos);
16916 	bzero(&cmd, sizeof (cmd));
16917 
16918 	cdb[0] = SCMD_READ_POSITION;
16919 	cdb[1] = type;
16920 	cdb[2] = 0;
16921 	cdb[3] = 0;
16922 	cdb[4] = 0;
16923 	cdb[5] = 0;
16924 	cdb[6] = 0;
16925 	cdb[7] = 0;
16926 	cdb[8] =  (type == EXT_POS) ? 28 : 0;
16927 	cdb[9] = 0;
16928 
16929 	cmd.uscsi_flags = USCSI_READ;
16930 	cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
16931 	cmd.uscsi_cdb = cdb;
16932 	cmd.uscsi_cdblen = sizeof (cdb);
16933 	cmd.uscsi_bufaddr = (caddr_t)raw;
16934 	switch (type) {
16935 	case SHORT_POS:
16936 		cmd.uscsi_buflen = sizeof (tape_position_t);
16937 		break;
16938 	case LONG_POS:
16939 		cmd.uscsi_buflen = sizeof (tape_position_long_t);
16940 		break;
16941 	case EXT_POS:
16942 		cmd.uscsi_buflen = sizeof (tape_position_ext_t);
16943 		break;
16944 	default:
16945 		ASSERT(0);
16946 	}
16947 
16948 	rval = st_uscsi_rcmd(un, &cmd, FKIOCTL);
16949 	if (cmd.uscsi_status) {
16950 		rval = EIO;
16951 	}
16952 	return (rval);
16953 }
16954 
16955 static int
16956 st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
16957     read_pos_data_t *raw)
16958 {
16959 	int rval;
16960 	read_p_types type = un->un_read_pos_type;
16961 
16962 	ST_FUNC(ST_DEVINFO, st_recovery_get_position);
16963 
16964 	rval = st_recovery_read_pos(un, type, raw);
16965 	if (rval != 0) {
16966 		return (rval);
16967 	}
16968 	rval = st_interpret_read_pos(un, read, type, sizeof (read_pos_data_t),
16969 	    (caddr_t)raw, 1);
16970 
16971 	return (rval);
16972 }
16973 
16974 /*
16975  * based on the command do we retry, continue or give up?
16976  * possable return values?
16977  *	zero do nothing looks fine.
16978  *	EAGAIN retry.
16979  *	EIO failed makes no sense.
16980  */
16981 static int
16982 st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
16983     cmd_attribute const * cmd_att, tapepos_t *read)
16984 {
16985 	int rval;
16986 	read_pos_data_t *readp_datap;
16987 
16988 	ST_FUNC(ST_DEVINFO, st_compare_expected_position);
16989 
16990 	ASSERT(un != NULL);
16991 	ASSERT(ei != NULL);
16992 	ASSERT(read != NULL);
16993 	ASSERT(cmd_att->chg_tape_pos);
16994 
16995 	COPY_POS(read, &ei->ei_expected_pos);
16996 
16997 	readp_datap = kmem_zalloc(sizeof (read_pos_data_t), KM_SLEEP);
16998 
16999 	rval = st_recovery_get_position(un, read, readp_datap);
17000 
17001 	kmem_free(readp_datap, sizeof (read_pos_data_t));
17002 
17003 	if (rval != 0) {
17004 		return (EIO);
17005 	}
17006 
17007 	ST_POS(ST_DEVINFO, "st_compare_expected_position", read);
17008 
17009 	if ((read->pmode == invalid) ||
17010 	    (ei->ei_expected_pos.pmode == invalid)) {
17011 		return (EIO);
17012 	}
17013 
17014 	/*
17015 	 * Command that changes tape position and have an expected position
17016 	 * if it were to chave completed sucessfully.
17017 	 */
17018 	if (cmd_att->recov_pos_type == POS_EXPECTED) {
17019 		uint32_t count;
17020 		int64_t difference;
17021 
17022 		/* At expected? */
17023 		if (read->lgclblkno == ei->ei_expected_pos.lgclblkno) {
17024 			ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17025 			    "Found drive to be at expected position\n");
17026 			return (0); /* Good */
17027 		}
17028 		ASSERT(cmd_att->get_cnt);
17029 		count = cmd_att->get_cnt(ei->ei_failed_pkt.pkt_cdbp);
17030 
17031 		ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17032 		    "Got count from CDB and it was %d\n", count);
17033 		if (cmd_att->chg_tape_direction == DIR_FORW) {
17034 			difference =
17035 			    ei->ei_expected_pos.lgclblkno - read->lgclblkno;
17036 			ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17037 			    "difference between expected and actual is %"
17038 			    PRId64"\n", difference);
17039 			if (count == difference) {
17040 				ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17041 				    "Found failed FORW command, retrying\n");
17042 				return (EAGAIN);
17043 			}
17044 
17045 			/*
17046 			 * If rewound or somewhere between the starting position
17047 			 * and the expected position (partial read or write).
17048 			 * Locate to the starting position and try the whole
17049 			 * thing over again.
17050 			 */
17051 			if ((read->lgclblkno == 0) ||
17052 			    ((difference > 0) && (difference < count))) {
17053 				rval = st_logical_block_locate(un,
17054 				    st_uscsi_rcmd, read,
17055 				    ei->ei_expected_pos.lgclblkno - count,
17056 				    ei->ei_expected_pos.partition);
17057 				if (rval == 0) {
17058 					ST_RECOV(ST_DEVINFO, st_label,
17059 					    SCSI_DEBUG, "reestablished FORW"
17060 					    " command retrying\n");
17061 					return (EAGAIN);
17062 				}
17063 			/* This handles flushed read ahead on the drive */
17064 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17065 			    (difference < 0)) {
17066 				rval = st_logical_block_locate(un,
17067 				    st_uscsi_rcmd, read,
17068 				    ei->ei_expected_pos.lgclblkno - count,
17069 				    ei->ei_expected_pos.partition);
17070 				if (rval == 0) {
17071 					ST_RECOV(ST_DEVINFO, st_label,
17072 					    SCSI_DEBUG, "reestablished FORW"
17073 					    " read command retrying\n");
17074 					return (EAGAIN);
17075 				}
17076 			/*
17077 			 * XXX swag seeing difference of 2 on write filemark.
17078 			 * If the space to the starting position works on a
17079 			 * write that means the previous write made it to tape.
17080 			 * If not we lost data and have to give up.
17081 			 *
17082 			 * The plot thickens. Now I am attempting to cover a
17083 			 * count of 1 and a differance of 2 on a write.
17084 			 */
17085 			} else if (difference > count) {
17086 				rval = st_logical_block_locate(un,
17087 				    st_uscsi_rcmd, read,
17088 				    ei->ei_expected_pos.lgclblkno - count,
17089 				    ei->ei_expected_pos.partition);
17090 				if (rval == 0) {
17091 					ST_RECOV(ST_DEVINFO, st_label,
17092 					    SCSI_DEBUG, "reestablished FORW"
17093 					    " write command retrying\n");
17094 					return (EAGAIN);
17095 				}
17096 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17097 				    "Seek to block %"PRId64" returned %d\n",
17098 				    ei->ei_expected_pos.lgclblkno - count,
17099 				    rval);
17100 			} else {
17101 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17102 				    "Not expected transfers_data = %d "
17103 				    "difference = %"PRId64,
17104 				    cmd_att->transfers_data, difference);
17105 			}
17106 
17107 			return (EIO);
17108 
17109 		} else if (cmd_att->chg_tape_direction == DIR_REVC) {
17110 			/* Don't think we can write backwards */
17111 			ASSERT(cmd_att->transfers_data != TRAN_WRTE);
17112 			difference =
17113 			    read->lgclblkno - ei->ei_expected_pos.lgclblkno;
17114 			ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17115 			    "difference between expected and actual is %"
17116 			    PRId64"\n", difference);
17117 			if (count == difference) {
17118 				ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17119 				    "Found failed REVC command, retrying\n");
17120 				return (EAGAIN);
17121 			}
17122 			if ((read->lgclblkno == 0) ||
17123 			    ((difference > 0) && (difference < count))) {
17124 				rval = st_logical_block_locate(un,
17125 				    st_uscsi_rcmd, read,
17126 				    ei->ei_expected_pos.lgclblkno + count,
17127 				    ei->ei_expected_pos.partition);
17128 				if (rval == 0) {
17129 					ST_RECOV(ST_DEVINFO, st_label,
17130 					    SCSI_DEBUG, "reestablished REVC"
17131 					    " command retrying\n");
17132 					return (EAGAIN);
17133 				}
17134 			/* This handles read ahead in reverse direction */
17135 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17136 			    (difference < 0)) {
17137 				rval = st_logical_block_locate(un,
17138 				    st_uscsi_rcmd, read,
17139 				    ei->ei_expected_pos.lgclblkno - count,
17140 				    ei->ei_expected_pos.partition);
17141 				if (rval == 0) {
17142 					ST_RECOV(ST_DEVINFO, st_label,
17143 					    SCSI_DEBUG, "reestablished REVC"
17144 					    " read command retrying\n");
17145 					return (EAGAIN);
17146 				}
17147 			} else {
17148 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17149 				    "Not expected transfers_data = %d "
17150 				    "difference = %"PRId64,
17151 				    cmd_att->transfers_data, difference);
17152 			}
17153 			return (EIO);
17154 
17155 		} else {
17156 			/*
17157 			 * Commands that change tape position either
17158 			 * direction or don't change position should not
17159 			 * get here.
17160 			 */
17161 			ASSERT(0);
17162 		}
17163 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17164 		    "Didn't find a recoverable position, Failing\n");
17165 
17166 	/*
17167 	 * Command that changes tape position and can only be recovered
17168 	 * by going back to the point of origin and retrying.
17169 	 *
17170 	 * Example SCMD_SPACE.
17171 	 */
17172 	} else if (cmd_att->recov_pos_type == POS_STARTING) {
17173 		/*
17174 		 * This type of command stores the starting position.
17175 		 * If the read position is the starting position,
17176 		 * reissue the command.
17177 		 */
17178 		if (ei->ei_expected_pos.lgclblkno == read->lgclblkno) {
17179 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17180 			    "Found Space command at starting position, "
17181 			    "Reissuing\n");
17182 			return (EAGAIN);
17183 		}
17184 		/*
17185 		 * Not in the position that the command was originally issued,
17186 		 * Attempt to locate to that position.
17187 		 */
17188 		rval = st_logical_block_locate(un, st_uscsi_rcmd, read,
17189 		    ei->ei_expected_pos.lgclblkno,
17190 		    ei->ei_expected_pos.partition);
17191 		if (rval) {
17192 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17193 			    "Found Space at an unexpected position and locate "
17194 			    "back to starting position failed\n");
17195 			return (EIO);
17196 		}
17197 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17198 		    "Found Space at an unexpected position and locate "
17199 		    "back to starting position worked, Reissuing\n");
17200 		return (EAGAIN);
17201 	}
17202 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17203 	    "Unhandled attribute/expected position", &ei->ei_expected_pos);
17204 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17205 	    "Read position above did not make sense", read);
17206 	ASSERT(0);
17207 	return (EIO);
17208 }
17209 
17210 static errstate
17211 st_recover_reissue_pkt(struct scsi_tape *un, struct scsi_pkt *oldpkt)
17212 {
17213 	buf_t *bp;
17214 	buf_t *pkt_bp;
17215 	struct scsi_pkt *newpkt;
17216 	cmd_attribute const *attrib;
17217 	recov_info *rcv = oldpkt->pkt_private;
17218 	uint_t cdblen;
17219 	int rval;
17220 	int stat_size =
17221 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
17222 
17223 	ST_FUNC(ST_DEVINFO, st_recover_reissue_pkt);
17224 
17225 	bp = rcv->cmd_bp;
17226 
17227 	if (rcv->privatelen == sizeof (recov_info)) {
17228 		attrib = rcv->cmd_attrib;
17229 	} else {
17230 		attrib = st_lookup_cmd_attribute(oldpkt->pkt_cdbp[0]);
17231 	}
17232 
17233 	/*
17234 	 * Some non-uscsi commands use the b_bcount for values that
17235 	 * have nothing to do with how much data is transfered.
17236 	 * In those cases we need to hide the buf_t from scsi_init_pkt().
17237 	 */
17238 	if ((BP_UCMD(bp)) && (bp->b_bcount)) {
17239 		pkt_bp = bp;
17240 	} else if (attrib->transfers_data == TRAN_NONE) {
17241 		pkt_bp = NULL;
17242 	} else {
17243 		pkt_bp = bp;
17244 	}
17245 	/*
17246 	 * if this is a queued command make sure it the only one in the
17247 	 * run queue.
17248 	 */
17249 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
17250 		ASSERT(un->un_runqf == un->un_runql);
17251 		ASSERT(un->un_runqf == bp);
17252 	}
17253 
17254 	cdblen = scsi_cdb_size[CDB_GROUPID(oldpkt->pkt_cdbp[0])];
17255 
17256 	newpkt = scsi_init_pkt(ROUTE, NULL, pkt_bp, cdblen,
17257 	    stat_size, rcv->privatelen, 0, NULL_FUNC, NULL);
17258 	if (newpkt == NULL) {
17259 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17260 		    "Reissue pkt scsi_init_pkt() failure\n");
17261 		return (COMMAND_DONE_ERROR);
17262 	}
17263 
17264 	ASSERT(newpkt->pkt_resid == 0);
17265 	bp->b_flags &= ~(B_DONE);
17266 	bp->b_resid = 0;
17267 	st_bioerror(bp, 0);
17268 
17269 	bcopy(oldpkt->pkt_private, newpkt->pkt_private, rcv->privatelen);
17270 
17271 	newpkt->pkt_comp = oldpkt->pkt_comp;
17272 	newpkt->pkt_time = oldpkt->pkt_time;
17273 
17274 	bzero(newpkt->pkt_scbp, stat_size);
17275 	bcopy(oldpkt->pkt_cdbp, newpkt->pkt_cdbp, cdblen);
17276 
17277 	newpkt->pkt_state = 0;
17278 	newpkt->pkt_statistics = 0;
17279 
17280 	oldpkt = BP_PKT(bp);
17281 
17282 	SET_BP_PKT(bp, newpkt);
17283 
17284 	scsi_destroy_pkt(oldpkt);
17285 
17286 	rval = st_transport(un, newpkt);
17287 	if (rval == TRAN_ACCEPT) {
17288 		return (JUST_RETURN);
17289 	}
17290 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17291 	    "Reissue pkt st_transport(0x%x) failure\n", rval);
17292 	if (rval != TRAN_BUSY) {
17293 		return (COMMAND_DONE_ERROR);
17294 	}
17295 	rval = st_handle_start_busy(un, bp, ST_TRAN_BUSY_TIMEOUT, 0);
17296 	if (rval) {
17297 		return (COMMAND_DONE_ERROR);
17298 	}
17299 
17300 	return (JUST_RETURN);
17301 }
17302 
17303 static int
17304 st_transport(struct scsi_tape *un, struct scsi_pkt *pkt)
17305 {
17306 	int status;
17307 
17308 	ST_FUNC(ST_DEVINFO, st_transport);
17309 
17310 	ST_CDB(ST_DEVINFO, "transport CDB", (caddr_t)pkt->pkt_cdbp);
17311 
17312 	mutex_exit(ST_MUTEX);
17313 
17314 	status = scsi_transport(pkt);
17315 
17316 	mutex_enter(ST_MUTEX);
17317 
17318 	return (status);
17319 }
17320 
17321 /*
17322  * Removed the buf_t bp from the queue referenced to by head and tail.
17323  * Returns the buf_t pointer if it is found in the queue.
17324  * Returns NULL if it is not found.
17325  */
17326 static buf_t *
17327 st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp)
17328 {
17329 	buf_t *runqbp;
17330 	buf_t *prevbp = NULL;
17331 
17332 	for (runqbp = *head; runqbp != 0; runqbp = runqbp->av_forw) {
17333 		if (runqbp == bp) {
17334 			/* found it, is it at the head? */
17335 			if (runqbp == *head) {
17336 				*head = bp->av_forw;
17337 			} else {
17338 				prevbp->av_forw = bp->av_forw;
17339 			}
17340 			if (*tail == bp) {
17341 				*tail = prevbp;
17342 			}
17343 			bp->av_forw = NULL;
17344 			return (bp); /* found and removed */
17345 		}
17346 		prevbp = runqbp;
17347 	}
17348 	return (NULL);
17349 }
17350 
17351 /*
17352  * Adds a buf_t to the queue pointed to by head and tail.
17353  * Adds it either to the head end or the tail end based on which
17354  * the passed variable end (head or tail) points at.
17355  */
17356 static void
17357 st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp)
17358 {
17359 
17360 	bp->av_forw = NULL;
17361 	if (*head) {
17362 		/* Queue is not empty */
17363 		if (end == *head) {
17364 			/* Add at front of queue */
17365 			bp->av_forw = *head;
17366 			*head = bp;
17367 		} else if (end == *tail) {
17368 			/* Add at end of queue */
17369 			(*tail)->av_forw = bp;
17370 			*tail = bp;
17371 		} else {
17372 			ASSERT(0);
17373 		}
17374 	} else {
17375 		/* Queue is empty */
17376 		*head = bp;
17377 		*tail = bp;
17378 	}
17379 }
17380 
17381 
17382 static uint64_t
17383 st_get_cdb_g0_rw_count(uchar_t *cdb)
17384 {
17385 	uint64_t count;
17386 
17387 	if ((cdb[1]) & 1) {
17388 		/* fixed block mode, the count is the number of blocks */
17389 		count =
17390 		    cdb[2] << 16 |
17391 		    cdb[3] << 8 |
17392 		    cdb[4];
17393 	} else {
17394 		/* variable block mode, the count is the block size */
17395 		count = 1;
17396 	}
17397 	return (count);
17398 }
17399 
17400 static uint64_t
17401 st_get_cdb_g0_sign_count(uchar_t *cdb)
17402 {
17403 	uint64_t count;
17404 
17405 	count =
17406 	    cdb[2] << 16 |
17407 	    cdb[3] << 8 |
17408 	    cdb[4];
17409 	/*
17410 	 * If the sign bit of the 3 byte value is set, extended it.
17411 	 */
17412 	if (count & 0x800000) {
17413 		count |= 0xffffffffff000000;
17414 	}
17415 	return (count);
17416 }
17417 
17418 static uint64_t
17419 st_get_cdb_g0_count(uchar_t *cdb)
17420 {
17421 	uint64_t count;
17422 
17423 	count =
17424 	    cdb[2] << 16 |
17425 	    cdb[3] << 8 |
17426 	    cdb[4];
17427 	return (count);
17428 }
17429 
17430 static uint64_t
17431 st_get_cdb_g5_rw_cnt(uchar_t *cdb)
17432 {
17433 	uint64_t count;
17434 
17435 	if ((cdb[1]) & 1) {
17436 		/* fixed block mode */
17437 		count =
17438 		    cdb[12] << 16 |
17439 		    cdb[13] << 8 |
17440 		    cdb[14];
17441 	} else {
17442 		/* variable block mode */
17443 		count = 1;
17444 	}
17445 	return (count);
17446 }
17447 
17448 static uint64_t
17449 st_get_no_count(uchar_t *cdb)
17450 {
17451 	ASSERT(cdb[0] == SCMD_REWIND);
17452 	return ((uint64_t)cdb[0]);
17453 }
17454 
17455 static uint64_t
17456 st_get_load_options(uchar_t *cdb)
17457 {
17458 	return ((uint64_t)(cdb[4] | (LD_HOLD << 1)));
17459 }
17460 
17461 static uint64_t
17462 st_get_erase_options(uchar_t *cdb)
17463 {
17464 	return (cdb[1] | (cdb[0] << 8));
17465 }
17466 
17467 static uint64_t
17468 st_get_cdb_g1_lba(uchar_t *cdb)
17469 {
17470 	uint64_t lba;
17471 
17472 	lba =
17473 	    cdb[3] << 24 |
17474 	    cdb[4] << 16 |
17475 	    cdb[5] << 8 |
17476 	    cdb[6];
17477 	return (lba);
17478 }
17479 
17480 static uint64_t
17481 st_get_cdb_g5_count(uchar_t *cdb)
17482 {
17483 	uint64_t count =
17484 	    cdb[12] << 16 |
17485 	    cdb[13] << 8 |
17486 	    cdb[14];
17487 
17488 	return (count);
17489 }
17490 
17491 static uint64_t
17492 st_get_cdb_g4g5_cnt(uchar_t *cdb)
17493 {
17494 	uint64_t lba;
17495 
17496 	lba =
17497 	    (uint64_t)cdb[4] << 56 |
17498 	    (uint64_t)cdb[5] << 48 |
17499 	    (uint64_t)cdb[6] << 40 |
17500 	    (uint64_t)cdb[7] << 32 |
17501 	    (uint64_t)cdb[8] << 24 |
17502 	    (uint64_t)cdb[9] << 16 |
17503 	    (uint64_t)cdb[10] << 8 |
17504 	    (uint64_t)cdb[11];
17505 	return (lba);
17506 }
17507 
17508 static const cmd_attribute cmd_attributes[] = {
17509 	{ SCMD_TEST_UNIT_READY,
17510 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17511 	    0, 0, 0 },
17512 	{ SCMD_REWIND,
17513 	    1, 1, 1, 0, 0, DIR_REVC, TRAN_NONE, POS_EXPECTED,
17514 	    0, 0, 0, st_get_no_count },
17515 	{ SCMD_REQUEST_SENSE,
17516 	    0, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17517 	    0, 0, 0 },
17518 	{ SCMD_READ_BLKLIM,
17519 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17520 	    0, 0, 0 },
17521 	{ SCMD_READ,
17522 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_READ, POS_EXPECTED,
17523 	    0, 0, 0, st_get_cdb_g0_rw_count },
17524 	{ SCMD_WRITE,
17525 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
17526 	    0, 0, 0, st_get_cdb_g0_rw_count },
17527 	{ SCMD_READ_G4,
17528 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_READ, POS_EXPECTED,
17529 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17530 	{ SCMD_WRITE_G4,
17531 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
17532 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17533 	{ SCMD_READ_REVERSE,
17534 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
17535 	    0, 0, 0, st_get_cdb_g0_rw_count },
17536 	{ SCMD_READ_REVERSE_G4,
17537 	    1, 0, 1, 1, 1, DIR_REVC, TRAN_READ, POS_EXPECTED,
17538 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17539 	{ SCMD_WRITE_FILE_MARK,
17540 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17541 	    0, 0, 0, st_get_cdb_g0_count },
17542 	{ SCMD_WRITE_FILE_MARK_G4,
17543 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17544 	    0, 0, 0, st_get_cdb_g5_count, st_get_cdb_g4g5_cnt },
17545 	{ SCMD_SPACE,
17546 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
17547 	    0, 0, 0, st_get_cdb_g0_sign_count },
17548 	{ SCMD_SPACE_G4,
17549 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
17550 	    0, 0, 0, st_get_cdb_g4g5_cnt },
17551 	{ SCMD_INQUIRY,
17552 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17553 	    0, 0, 0 },
17554 	{ SCMD_VERIFY_G0,
17555 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17556 	    0, 0, 0, st_get_cdb_g0_rw_count },
17557 	{ SCMD_VERIFY_G4,
17558 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17559 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17560 	{ SCMD_RECOVER_BUF,
17561 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
17562 	    0, 0, 0 },
17563 	{ SCMD_MODE_SELECT,
17564 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17565 	    0, 0, 0 },
17566 	{ SCMD_RESERVE,
17567 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17568 	    0, 0, 0 },
17569 	{ SCMD_RELEASE,
17570 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17571 	    0, 0, 0 },
17572 	{ SCMD_ERASE,
17573 	    1, 0, 1, 1, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17574 	    0, 0, 0, st_get_erase_options },
17575 	{ SCMD_MODE_SENSE,
17576 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17577 	    0, 0, 0 },
17578 	{ SCMD_LOAD,
17579 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
17580 	    0, 0, 0, st_get_load_options },
17581 	{ SCMD_GDIAG,
17582 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17583 	    1, 0, 0 },
17584 	{ SCMD_SDIAG,
17585 	    1, 0, 1, 1, 0, DIR_EITH, TRAN_WRTE, POS_EXPECTED,
17586 	    1, 0, 0 },
17587 	{ SCMD_DOORLOCK,
17588 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17589 	    0, 4, 3 },
17590 	{ SCMD_LOCATE,
17591 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
17592 	    0, 0, 0, NULL, st_get_cdb_g1_lba },
17593 	{ SCMD_READ_POSITION,
17594 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17595 	    0, 0, 0 },
17596 	{ SCMD_WRITE_BUFFER,
17597 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17598 	    1, 0, 0 },
17599 	{ SCMD_READ_BUFFER,
17600 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17601 	    1, 0, 0 },
17602 	{ SCMD_REPORT_DENSITIES,
17603 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17604 	    0, 0, 0 },
17605 	{ SCMD_LOG_SELECT_G1,
17606 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17607 	    0, 0, 0 },
17608 	{ SCMD_LOG_SENSE_G1,
17609 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17610 	    0, 0, 0 },
17611 	{ SCMD_PRIN,
17612 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17613 	    0, 0, 0 },
17614 	{ SCMD_PROUT,
17615 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17616 	    0, 0, 0 },
17617 	{ SCMD_READ_ATTRIBUTE,
17618 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17619 	    0, 0, 0 },
17620 	{ SCMD_WRITE_ATTRIBUTE,
17621 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17622 	    0, 0, 0 },
17623 	{ SCMD_LOCATE_G4,
17624 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
17625 	    0, 0, 0, NULL, st_get_cdb_g4g5_cnt },
17626 	{ SCMD_REPORT_LUNS,
17627 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17628 	    0, 0, 0 },
17629 	{ SCMD_SVC_ACTION_IN_G5,
17630 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17631 	    0, 0, 0 },
17632 	{ SCMD_MAINTENANCE_IN,
17633 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17634 	    0, 0, 0 },
17635 	{ SCMD_MAINTENANCE_OUT,
17636 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17637 	    0, 0, 0 },
17638 	{ 0xff, /* Default attribute for unsupported commands */
17639 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_STARTING,
17640 	    1, 0, 0, NULL, NULL }
17641 };
17642 
17643 static const cmd_attribute *
17644 st_lookup_cmd_attribute(unsigned char cmd)
17645 {
17646 	int i;
17647 	cmd_attribute const *attribute;
17648 
17649 	for (i = 0; i < ST_NUM_MEMBERS(cmd_attributes); i++) {
17650 		attribute = &cmd_attributes[i];
17651 		if (attribute->cmd == cmd) {
17652 			return (attribute);
17653 		}
17654 	}
17655 	ASSERT(attribute);
17656 	return (attribute);
17657 }
17658 
17659 static int
17660 st_reset(struct scsi_tape *un, int reset_type)
17661 {
17662 	int rval;
17663 
17664 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
17665 
17666 	ST_FUNC(ST_DEVINFO, st_reset);
17667 	un->un_rsvd_status |= ST_INITIATED_RESET;
17668 	mutex_exit(ST_MUTEX);
17669 	do {
17670 		rval = scsi_reset(&un->un_sd->sd_address, reset_type);
17671 		if (rval == 0) {
17672 			switch (reset_type) {
17673 			case RESET_LUN:
17674 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
17675 				    "LUN reset failed trying target reset");
17676 				reset_type = RESET_TARGET;
17677 				break;
17678 			case RESET_TARGET:
17679 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
17680 				    "target reset failed trying bus reset");
17681 				reset_type = RESET_BUS;
17682 				break;
17683 			case RESET_BUS:
17684 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
17685 				    "bus reset failed trying all reset");
17686 				reset_type = RESET_ALL;
17687 			default:
17688 				mutex_enter(ST_MUTEX);
17689 				return (rval);
17690 			}
17691 		}
17692 	} while (rval == 0);
17693 	mutex_enter(ST_MUTEX);
17694 	return (rval);
17695 }
17696 
17697 
17698 static void
17699 st_reset_notification(caddr_t arg)
17700 {
17701 	struct scsi_tape *un = (struct scsi_tape *)arg;
17702 
17703 	ST_FUNC(ST_DEVINFO, st_reset_notification);
17704 	mutex_enter(ST_MUTEX);
17705 
17706 	un->un_unit_attention_flags = 2;
17707 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
17708 	    ST_RESERVE) {
17709 		un->un_rsvd_status |= ST_LOST_RESERVE;
17710 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
17711 		    "Lost Reservation notification");
17712 	} else {
17713 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
17714 		    "reset notification");
17715 	}
17716 
17717 	if ((un->un_restore_pos == 0) &&
17718 	    (un->un_state == ST_STATE_CLOSED) ||
17719 	    (un->un_state == ST_STATE_OPEN_PENDING_IO) ||
17720 	    (un->un_state == ST_STATE_CLOSING)) {
17721 		un->un_restore_pos = 1;
17722 	}
17723 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
17724 	    "reset and state was %d\n", un->un_state);
17725 	mutex_exit(ST_MUTEX);
17726 }
17727