xref: /titanic_44/usr/src/uts/common/io/scsi/targets/st.c (revision cec46d775eb90ec3bcda95b59e0c3e8aa9206b22)
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 2007 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 		mtget->mt_blkno = un->un_err_pos.blkno;
4840 		mtget->mt_type = un->un_dp->type;
4841 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
4842 		if (un->un_read_pos_type != NO_POS) {
4843 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
4844 		}
4845 		if (un->un_dp->options & ST_REEL) {
4846 			mtget->mt_flags |= MTF_REEL;
4847 			mtget->mt_bf = 20;
4848 		} else {		/* 1/4" cartridges */
4849 			switch (mtget->mt_type) {
4850 			/* Emulex cartridge tape */
4851 			case MT_ISMT02:
4852 				mtget->mt_bf = 40;
4853 				break;
4854 			default:
4855 				mtget->mt_bf = 126;
4856 				break;
4857 			}
4858 		}
4859 
4860 		/*
4861 		 * If large transfers are allowed and drive options
4862 		 * has no record size limit set. Calculate blocking
4863 		 * factor from the lesser of maxbsize and maxdma.
4864 		 */
4865 		if ((un->un_allow_large_xfer) &&
4866 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
4867 			mtget->mt_bf = min(un->un_maxbsize,
4868 			    un->un_maxdma) / SECSIZE;
4869 		}
4870 
4871 		if (un->un_read_only == WORM ||
4872 		    un->un_read_only == RDWORM) {
4873 			mtget->mt_flags |= MTF_WORM_MEDIA;
4874 		}
4875 
4876 		/*
4877 		 * In persistent error mode sending a non-queued can hang
4878 		 * because this ioctl gets to be run without turning off
4879 		 * persistense. Fake the answer based on previous info.
4880 		 */
4881 		if (un->un_persistence) {
4882 			if ((un->un_HeadClean & (TAPE_ALERT_SUPPORTED |
4883 			    TAPE_SEQUENTIAL_SUPPORTED|TAPE_ALERT_NOT_SUPPORTED))
4884 			    != TAPE_ALERT_NOT_SUPPORTED) {
4885 				mtget->mt_flags |= MTF_TAPE_CLN_SUPPORTED;
4886 			}
4887 			if (un->un_HeadClean & (TAPE_PREVIOUSLY_DIRTY |
4888 			    TAPE_ALERT_STILL_DIRTY)) {
4889 				mtget->mt_flags |= MTF_TAPE_HEAD_DIRTY;
4890 			}
4891 			rval = 0;
4892 		} else {
4893 			rval = st_check_clean_bit(un);
4894 		}
4895 		if (rval == -1) {
4896 			rval = EIO;
4897 			goto exit;
4898 		} else {
4899 			mtget->mt_flags |= (ushort_t)rval;
4900 			rval = 0;
4901 		}
4902 
4903 		un->un_status = 0;		/* Reset status */
4904 		un->un_err_resid = 0;
4905 		tmp = sizeof (struct mtget);
4906 
4907 #ifdef _MULTI_DATAMODEL
4908 
4909 		switch (ddi_model_convert_from(flag & FMODELS)) {
4910 		case DDI_MODEL_ILP32:
4911 			/*
4912 			 * Convert 64 bit back to 32 bit before doing
4913 			 * copyout. This is what the ILP32 app expects.
4914 			 */
4915 			mtget_32->mt_erreg = 	mtget->mt_erreg;
4916 			mtget_32->mt_resid = 	mtget->mt_resid;
4917 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
4918 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
4919 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
4920 			mtget_32->mt_type =  	mtget->mt_type;
4921 			mtget_32->mt_flags = 	mtget->mt_flags;
4922 			mtget_32->mt_bf = 	mtget->mt_bf;
4923 
4924 			if (ddi_copyout(mtget_32, (void *)arg,
4925 			    sizeof (struct mtget32), flag)) {
4926 				rval = EFAULT;
4927 			}
4928 			break;
4929 
4930 		case DDI_MODEL_NONE:
4931 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4932 				rval = EFAULT;
4933 			}
4934 			break;
4935 		}
4936 #else /* ! _MULTI_DATAMODE */
4937 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4938 			rval = EFAULT;
4939 		}
4940 #endif /* _MULTI_DATAMODE */
4941 
4942 		break;
4943 	}
4944 	case MTIOCGETERROR:
4945 			/*
4946 			 * get error entry from error stack
4947 			 */
4948 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4949 			    "st_ioctl: MTIOCGETERROR\n");
4950 
4951 			rval = st_get_error_entry(un, arg, flag);
4952 
4953 			break;
4954 
4955 	case MTIOCSTATE:
4956 		{
4957 			/*
4958 			 * return when media presence matches state
4959 			 */
4960 			enum mtio_state state;
4961 
4962 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4963 			    "st_ioctl: MTIOCSTATE\n");
4964 
4965 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
4966 				rval = EFAULT;
4967 
4968 			mutex_exit(ST_MUTEX);
4969 
4970 			rval = st_check_media(dev, state);
4971 
4972 			mutex_enter(ST_MUTEX);
4973 
4974 			if (rval != 0) {
4975 				break;
4976 			}
4977 
4978 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
4979 			    sizeof (int), flag))
4980 				rval = EFAULT;
4981 			break;
4982 
4983 		}
4984 
4985 	case MTIOCGETDRIVETYPE:
4986 		{
4987 #ifdef _MULTI_DATAMODEL
4988 		/*
4989 		 * For use when a 32 bit app makes a call into a
4990 		 * 64 bit ioctl
4991 		 */
4992 		struct mtdrivetype_request32	mtdtrq32;
4993 #endif /* _MULTI_DATAMODEL */
4994 
4995 			/*
4996 			 * return mtdrivetype
4997 			 */
4998 			struct mtdrivetype_request mtdtrq;
4999 			struct mtdrivetype mtdrtyp;
5000 			struct mtdrivetype *mtdt = &mtdrtyp;
5001 			struct st_drivetype *stdt = un->un_dp;
5002 
5003 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5004 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
5005 
5006 #ifdef _MULTI_DATAMODEL
5007 		switch (ddi_model_convert_from(flag & FMODELS)) {
5008 		case DDI_MODEL_ILP32:
5009 		{
5010 			if (ddi_copyin((void *)arg, &mtdtrq32,
5011 			    sizeof (struct mtdrivetype_request32), flag)) {
5012 				rval = EFAULT;
5013 				break;
5014 			}
5015 			mtdtrq.size = mtdtrq32.size;
5016 			mtdtrq.mtdtp =
5017 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
5018 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5019 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
5020 			break;
5021 		}
5022 		case DDI_MODEL_NONE:
5023 			if (ddi_copyin((void *)arg, &mtdtrq,
5024 			    sizeof (struct mtdrivetype_request), flag)) {
5025 				rval = EFAULT;
5026 				break;
5027 			}
5028 			break;
5029 		}
5030 
5031 #else /* ! _MULTI_DATAMODEL */
5032 		if (ddi_copyin((void *)arg, &mtdtrq,
5033 		    sizeof (struct mtdrivetype_request), flag)) {
5034 			rval = EFAULT;
5035 			break;
5036 		}
5037 #endif /* _MULTI_DATAMODEL */
5038 
5039 			/*
5040 			 * if requested size is < 0 then return
5041 			 * error.
5042 			 */
5043 			if (mtdtrq.size < 0) {
5044 				rval = EINVAL;
5045 				break;
5046 			}
5047 			bzero(mtdt, sizeof (struct mtdrivetype));
5048 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
5049 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
5050 			mtdt->type = stdt->type;
5051 			mtdt->bsize = stdt->bsize;
5052 			mtdt->options = stdt->options;
5053 			mtdt->max_rretries = stdt->max_rretries;
5054 			mtdt->max_wretries = stdt->max_wretries;
5055 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5056 				mtdt->densities[tmp] = stdt->densities[tmp];
5057 			}
5058 			mtdt->default_density = stdt->default_density;
5059 			/*
5060 			 * Speed hasn't been used since the hayday of reel tape.
5061 			 * For all drives not setting the option ST_KNOWS_MEDIA
5062 			 * the speed member renamed to mediatype are zeros.
5063 			 * Those drives that have ST_KNOWS_MEDIA set use the
5064 			 * new mediatype member which is used to figure the
5065 			 * type of media loaded.
5066 			 *
5067 			 * So as to not break applications speed in the
5068 			 * mtdrivetype structure is not renamed.
5069 			 */
5070 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5071 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
5072 			}
5073 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
5074 			mtdt->io_timeout = stdt->io_timeout;
5075 			mtdt->rewind_timeout = stdt->rewind_timeout;
5076 			mtdt->space_timeout = stdt->space_timeout;
5077 			mtdt->load_timeout = stdt->load_timeout;
5078 			mtdt->unload_timeout = stdt->unload_timeout;
5079 			mtdt->erase_timeout = stdt->erase_timeout;
5080 
5081 			/*
5082 			 * Limit the maximum length of the result to
5083 			 * sizeof (struct mtdrivetype).
5084 			 */
5085 			tmp = sizeof (struct mtdrivetype);
5086 			if (mtdtrq.size < tmp)
5087 				tmp = mtdtrq.size;
5088 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
5089 				rval = EFAULT;
5090 			}
5091 			break;
5092 		}
5093 	case MTIOCPERSISTENT:
5094 
5095 		if (ddi_copyin((void *)arg, &tmp, sizeof (tmp), flag)) {
5096 			rval = EFAULT;
5097 			break;
5098 		}
5099 
5100 		if (tmp) {
5101 			st_turn_pe_on(un);
5102 		} else {
5103 			st_turn_pe_off(un);
5104 		}
5105 
5106 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5107 		    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
5108 		    un->un_persistence);
5109 
5110 		break;
5111 
5112 	case MTIOCPERSISTENTSTATUS:
5113 		tmp = (int)un->un_persistence;
5114 
5115 		if (ddi_copyout(&tmp, (void *)arg, sizeof (tmp), flag)) {
5116 			rval = EFAULT;
5117 		}
5118 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5119 		    "st_ioctl: MTIOCPERSISTENTSTATUS:persistence = %d\n",
5120 		    un->un_persistence);
5121 
5122 		break;
5123 
5124 	case MTIOCLRERR:
5125 		{
5126 			/* clear persistent errors */
5127 
5128 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5129 			    "st_ioctl: MTIOCLRERR\n");
5130 
5131 			st_clear_pe(un);
5132 
5133 			break;
5134 		}
5135 
5136 	case MTIOCGUARANTEEDORDER:
5137 		{
5138 			/*
5139 			 * this is just a holder to make a valid ioctl and
5140 			 * it won't be in any earlier release
5141 			 */
5142 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5143 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
5144 
5145 			break;
5146 		}
5147 
5148 	case MTIOCRESERVE:
5149 		{
5150 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5151 			    "st_ioctl: MTIOCRESERVE\n");
5152 
5153 			/*
5154 			 * Check if Reserve/Release is supported.
5155 			 */
5156 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5157 				rval = ENOTTY;
5158 				break;
5159 			}
5160 
5161 			rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5162 
5163 			if (rval == 0) {
5164 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
5165 			}
5166 			break;
5167 		}
5168 
5169 	case MTIOCRELEASE:
5170 		{
5171 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5172 			    "st_ioctl: MTIOCRELEASE\n");
5173 
5174 			/*
5175 			 * Check if Reserve/Release is supported.
5176 			 */
5177 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5178 				rval = ENOTTY;
5179 				break;
5180 			}
5181 
5182 			/*
5183 			 * Used to just clear ST_PRESERVE_RESERVE which
5184 			 * made the reservation release at next close.
5185 			 * As the user may have opened and then done a
5186 			 * persistant reservation we now need to drop
5187 			 * the reservation without closing if the user
5188 			 * attempts to do this.
5189 			 */
5190 			rval = st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
5191 
5192 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5193 
5194 			break;
5195 		}
5196 
5197 	case MTIOCFORCERESERVE:
5198 	{
5199 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5200 		    "st_ioctl: MTIOCFORCERESERVE\n");
5201 
5202 		/*
5203 		 * Check if Reserve/Release is supported.
5204 		 */
5205 		if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5206 			rval = ENOTTY;
5207 			break;
5208 		}
5209 		/*
5210 		 * allow only super user to run this.
5211 		 */
5212 		if (drv_priv(cred_p) != 0) {
5213 			rval = EPERM;
5214 			break;
5215 		}
5216 		/*
5217 		 * Throw away reserve,
5218 		 * not using test-unit-ready
5219 		 * since reserve can succeed without tape being
5220 		 * present in the drive.
5221 		 */
5222 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5223 
5224 		rval = st_take_ownership(un);
5225 
5226 		break;
5227 	}
5228 
5229 	case USCSICMD:
5230 	{
5231 		cred_t	*cr;
5232 
5233 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5234 		    "st_ioctl: USCSICMD\n");
5235 
5236 		cr = ddi_get_cred();
5237 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5238 			rval = EPERM;
5239 		} else {
5240 			rval = st_uscsi_cmd(un, (struct uscsi_cmd *)arg, flag);
5241 		}
5242 		break;
5243 	}
5244 	case MTIOCTOP:
5245 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5246 		    "st_ioctl: MTIOCTOP\n");
5247 		rval = st_mtioctop(un, arg, flag);
5248 		break;
5249 
5250 	case MTIOCLTOP:
5251 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5252 		    "st_ioctl: MTIOLCTOP\n");
5253 		rval = st_mtiocltop(un, arg, flag);
5254 		break;
5255 
5256 	case MTIOCREADIGNOREILI:
5257 		{
5258 			int set_ili;
5259 
5260 			if (ddi_copyin((void *)arg, &set_ili,
5261 			    sizeof (set_ili), flag)) {
5262 				rval = EFAULT;
5263 				break;
5264 			}
5265 
5266 			if (un->un_bsize) {
5267 				rval = ENOTTY;
5268 				break;
5269 			}
5270 
5271 			switch (set_ili) {
5272 			case 0:
5273 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5274 				break;
5275 
5276 			case 1:
5277 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5278 				break;
5279 
5280 			default:
5281 				rval = EINVAL;
5282 				break;
5283 			}
5284 			break;
5285 		}
5286 
5287 	case MTIOCREADIGNOREEOFS:
5288 		{
5289 			int ignore_eof;
5290 
5291 			if (ddi_copyin((void *)arg, &ignore_eof,
5292 			    sizeof (ignore_eof), flag)) {
5293 				rval = EFAULT;
5294 				break;
5295 			}
5296 
5297 			if (!(un->un_dp->options & ST_REEL)) {
5298 				rval = ENOTTY;
5299 				break;
5300 			}
5301 
5302 			switch (ignore_eof) {
5303 			case 0:
5304 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5305 				break;
5306 
5307 			case 1:
5308 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5309 				break;
5310 
5311 			default:
5312 				rval = EINVAL;
5313 				break;
5314 			}
5315 			break;
5316 		}
5317 
5318 	case MTIOCSHORTFMK:
5319 	{
5320 		int short_fmk;
5321 
5322 		if (ddi_copyin((void *)arg, &short_fmk,
5323 		    sizeof (short_fmk), flag)) {
5324 			rval = EFAULT;
5325 			break;
5326 		}
5327 
5328 		switch (un->un_dp->type) {
5329 		case ST_TYPE_EXB8500:
5330 		case ST_TYPE_EXABYTE:
5331 			if (!short_fmk) {
5332 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5333 			} else if (short_fmk == 1) {
5334 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5335 			} else {
5336 				rval = EINVAL;
5337 			}
5338 			break;
5339 
5340 		default:
5341 			rval = ENOTTY;
5342 			break;
5343 		}
5344 		break;
5345 	}
5346 
5347 	case MTIOCGETPOS:
5348 		rval = st_update_block_pos(un, st_cmd, 0);
5349 		if (rval == 0) {
5350 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5351 			    sizeof (tapepos_t), flag)) {
5352 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5353 				    "MTIOCGETPOS copy out failed\n");
5354 				rval = EFAULT;
5355 			}
5356 		}
5357 		break;
5358 
5359 	case MTIOCRESTPOS:
5360 	{
5361 		tapepos_t dest;
5362 
5363 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5364 		    flag) != 0) {
5365 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5366 			    "MTIOCRESTPOS copy in failed\n");
5367 			rval = EFAULT;
5368 			break;
5369 		}
5370 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &dest);
5371 		if (rval != 0) {
5372 			rval = EIO;
5373 		}
5374 		break;
5375 	}
5376 	default:
5377 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5378 		    "st_ioctl: unknown ioctl\n");
5379 		rval = ENOTTY;
5380 	}
5381 
5382 exit:
5383 	if (!(un->un_persistence && un->un_persist_errors)) {
5384 		un->un_errno = rval;
5385 	}
5386 
5387 	mutex_exit(ST_MUTEX);
5388 
5389 	return (rval);
5390 }
5391 
5392 
5393 /*
5394  * do some MTIOCTOP tape operations
5395  */
5396 static int
5397 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5398 {
5399 #ifdef _MULTI_DATAMODEL
5400 	/*
5401 	 * For use when a 32 bit app makes a call into a
5402 	 * 64 bit ioctl
5403 	 */
5404 	struct mtop32	mtop_32_for_64;
5405 #endif /* _MULTI_DATAMODEL */
5406 	struct mtop passed;
5407 	struct mtlop local;
5408 	int rval = 0;
5409 
5410 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5411 
5412 	ASSERT(mutex_owned(ST_MUTEX));
5413 
5414 #ifdef _MULTI_DATAMODEL
5415 	switch (ddi_model_convert_from(flag & FMODELS)) {
5416 	case DDI_MODEL_ILP32:
5417 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5418 		    sizeof (struct mtop32), flag)) {
5419 			return (EFAULT);
5420 		}
5421 		local.mt_op = mtop_32_for_64.mt_op;
5422 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5423 		break;
5424 
5425 	case DDI_MODEL_NONE:
5426 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5427 			return (EFAULT);
5428 		}
5429 		local.mt_op = passed.mt_op;
5430 		/* prevent sign extention */
5431 		local.mt_count = (UINT32_MAX & passed.mt_count);
5432 		break;
5433 	}
5434 
5435 #else /* ! _MULTI_DATAMODEL */
5436 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5437 		return (EFAULT);
5438 	}
5439 	local.mt_op = passed.mt_op;
5440 	/* prevent sign extention */
5441 	local.mt_count = (UINT32_MAX & passed.mt_count);
5442 #endif /* _MULTI_DATAMODEL */
5443 
5444 	rval = st_do_mtioctop(un, &local);
5445 
5446 #ifdef _MULTI_DATAMODEL
5447 	switch (ddi_model_convert_from(flag & FMODELS)) {
5448 	case DDI_MODEL_ILP32:
5449 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5450 			rval = ERANGE;
5451 			break;
5452 		}
5453 		/*
5454 		 * Convert 64 bit back to 32 bit before doing
5455 		 * copyout. This is what the ILP32 app expects.
5456 		 */
5457 		mtop_32_for_64.mt_op = local.mt_op;
5458 		mtop_32_for_64.mt_count = local.mt_count;
5459 
5460 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5461 		    sizeof (struct mtop32), flag)) {
5462 			rval = EFAULT;
5463 		}
5464 		break;
5465 
5466 	case DDI_MODEL_NONE:
5467 		passed.mt_count = local.mt_count;
5468 		passed.mt_op = local.mt_op;
5469 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5470 			rval = EFAULT;
5471 		}
5472 		break;
5473 	}
5474 #else /* ! _MULTI_DATAMODE */
5475 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5476 		rval = ERANGE;
5477 	} else {
5478 		passed.mt_op = local.mt_op;
5479 		passed.mt_count = local.mt_count;
5480 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5481 			rval = EFAULT;
5482 		}
5483 	}
5484 #endif /* _MULTI_DATAMODE */
5485 
5486 
5487 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5488 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5489 	    un->un_pos.blkno, un->un_pos.eof);
5490 
5491 	if (un->un_pos.pmode == invalid) {
5492 		un->un_density_known = 0;
5493 	}
5494 
5495 	ASSERT(mutex_owned(ST_MUTEX));
5496 	return (rval);
5497 }
5498 
5499 static int
5500 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5501 {
5502 	struct mtlop local;
5503 	int rval;
5504 
5505 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5506 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5507 		return (EFAULT);
5508 	}
5509 
5510 	rval = st_do_mtioctop(un, &local);
5511 
5512 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5513 		rval = EFAULT;
5514 	}
5515 	return (rval);
5516 }
5517 
5518 
5519 static int
5520 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5521 {
5522 	dev_t dev = un->un_dev;
5523 	int savefile;
5524 	int rval = 0;
5525 
5526 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5527 
5528 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5529 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5530 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5531 	    "fileno=%x, blkno=%x, eof=%x\n",
5532 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5533 
5534 	un->un_status = 0;
5535 
5536 	/*
5537 	 * if we are going to mess with a tape, we have to make sure we have
5538 	 * one and are not offline (i.e. no tape is initialized).  We let
5539 	 * commands pass here that don't actually touch the tape, except for
5540 	 * loading and initialization (rewinding).
5541 	 */
5542 	if (un->un_state == ST_STATE_OFFLINE) {
5543 		switch (mtop->mt_op) {
5544 		case MTLOAD:
5545 		case MTNOP:
5546 			/*
5547 			 * We don't want strategy calling st_tape_init here,
5548 			 * so, change state
5549 			 */
5550 			un->un_state = ST_STATE_INITIALIZING;
5551 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5552 			    "st_do_mtioctop : OFFLINE state = %d\n",
5553 			    un->un_state);
5554 			break;
5555 		default:
5556 			/*
5557 			 * reinitialize by normal means
5558 			 */
5559 			rval = st_tape_init(un);
5560 			if (rval) {
5561 				un->un_state = ST_STATE_INITIALIZING;
5562 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5563 				    "st_do_mtioctop : OFFLINE init failure ");
5564 				un->un_state = ST_STATE_OFFLINE;
5565 				un->un_pos.pmode = invalid;
5566 				if (rval != EACCES) {
5567 					rval = EIO;
5568 				}
5569 				return (rval);
5570 			}
5571 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5572 			break;
5573 		}
5574 	}
5575 
5576 	/*
5577 	 * If the file position is invalid, allow only those
5578 	 * commands that properly position the tape and fail
5579 	 * the rest with EIO
5580 	 */
5581 	if (un->un_pos.pmode == invalid) {
5582 		switch (mtop->mt_op) {
5583 		case MTWEOF:
5584 		case MTRETEN:
5585 		case MTERASE:
5586 		case MTEOM:
5587 		case MTFSF:
5588 		case MTFSR:
5589 		case MTBSF:
5590 		case MTNBSF:
5591 		case MTBSR:
5592 		case MTSRSZ:
5593 		case MTGRSZ:
5594 		case MTSEEK:
5595 		case MTBSSF:
5596 		case MTFSSF:
5597 			return (EIO);
5598 			/* NOTREACHED */
5599 		case MTREW:
5600 		case MTLOAD:
5601 		case MTOFFL:
5602 		case MTNOP:
5603 		case MTTELL:
5604 		case MTLOCK:
5605 		case MTUNLOCK:
5606 			break;
5607 
5608 		default:
5609 			return (ENOTTY);
5610 			/* NOTREACHED */
5611 		}
5612 	}
5613 
5614 	switch (mtop->mt_op) {
5615 	case MTERASE:
5616 		/*
5617 		 * MTERASE rewinds the tape, erase it completely, and returns
5618 		 * to the beginning of the tape
5619 		 */
5620 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5621 			un->un_status = KEY_WRITE_PROTECT;
5622 			un->un_err_resid = mtop->mt_count;
5623 			COPY_POS(&un->un_err_pos, &un->un_pos);
5624 			return (EACCES);
5625 		}
5626 		if (un->un_dp->options & ST_REEL) {
5627 			un->un_fmneeded = 2;
5628 		} else {
5629 			un->un_fmneeded = 1;
5630 		}
5631 		mtop->mt_count = mtop->mt_count ? 1 : 0;
5632 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5633 		    st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
5634 		    st_cmd(un, SCMD_ERASE, mtop->mt_count, SYNC_CMD)) {
5635 			un->un_pos.pmode = invalid;
5636 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5637 			    "st_do_mtioctop : EIO space or erase or "
5638 			    "check den)\n");
5639 			rval = EIO;
5640 		} else {
5641 			/* QIC and helical scan rewind after erase */
5642 			if (un->un_dp->options & ST_REEL) {
5643 				(void) st_cmd(un, SCMD_REWIND, 0, ASYNC_CMD);
5644 			}
5645 		}
5646 		break;
5647 
5648 	case MTWEOF:
5649 		/*
5650 		 * write an end-of-file record
5651 		 */
5652 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5653 			un->un_status = KEY_WRITE_PROTECT;
5654 			un->un_err_resid = mtop->mt_count;
5655 			COPY_POS(&un->un_err_pos, &un->un_pos);
5656 			return (EACCES);
5657 		}
5658 
5659 		/*
5660 		 * zero count means just flush buffers
5661 		 * negative count is not permitted
5662 		 */
5663 		if (mtop->mt_count < 0) {
5664 			return (EINVAL);
5665 		}
5666 
5667 		/* Not on worm */
5668 		if (un->un_read_only == RDWR) {
5669 			un->un_test_append = 1;
5670 		}
5671 
5672 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5673 			if (st_determine_density(un, B_WRITE)) {
5674 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5675 				    "st_do_mtioctop : EIO : MTWEOF can't "
5676 				    "determine density");
5677 				return (EIO);
5678 			}
5679 		}
5680 
5681 		rval = st_write_fm(dev, (int)mtop->mt_count);
5682 		if ((rval != 0) && (rval != EACCES)) {
5683 			/*
5684 			 * Failure due to something other than illegal
5685 			 * request results in loss of state (st_intr).
5686 			 */
5687 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5688 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5689 			    "file mark");
5690 			rval = EIO;
5691 		}
5692 		break;
5693 
5694 	case MTRETEN:
5695 		/*
5696 		 * retension the tape
5697 		 */
5698 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5699 		    st_cmd(un, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5700 			un->un_pos.pmode = invalid;
5701 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5702 			    "st_do_mtioctop : EIO : MTRETEN ");
5703 			rval = EIO;
5704 		}
5705 		break;
5706 
5707 	case MTREW:
5708 		/*
5709 		 * rewind  the tape
5710 		 */
5711 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5712 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5713 			    "st_do_mtioctop : EIO:MTREW check "
5714 			    "density/wfm failed");
5715 			return (EIO);
5716 		}
5717 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
5718 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5719 			    "st_do_mtioctop : EIO : MTREW ");
5720 			rval = EIO;
5721 		}
5722 		break;
5723 
5724 	case MTOFFL:
5725 		/*
5726 		 * rewinds, and, if appropriate, takes the device offline by
5727 		 * unloading the tape
5728 		 */
5729 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5730 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5731 			    "st_do_mtioctop :EIO:MTOFFL check "
5732 			    "density/wfm failed");
5733 			return (EIO);
5734 		}
5735 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
5736 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5737 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5738 			    "st_do_mtioctop : EIO : MTOFFL");
5739 			return (EIO);
5740 		}
5741 		un->un_pos.eof = ST_NO_EOF;
5742 		un->un_laststate = un->un_state;
5743 		un->un_state = ST_STATE_OFFLINE;
5744 		un->un_mediastate = MTIO_EJECTED;
5745 		break;
5746 
5747 	case MTLOAD:
5748 		/*
5749 		 * This is to load a tape into the drive
5750 		 * Note that if the tape is not loaded, the device will have
5751 		 * to be opened via O_NDELAY or O_NONBLOCK.
5752 		 */
5753 		/*
5754 		 * Let's try and clean things up, if we are not
5755 		 * initializing, and then send in the load command, no
5756 		 * matter what.
5757 		 *
5758 		 * load after a media change by the user.
5759 		 */
5760 
5761 		if (un->un_state > ST_STATE_INITIALIZING) {
5762 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5763 		}
5764 		rval = st_cmd(un, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5765 		/* Load command to a drive that doesn't support load */
5766 		if ((rval == EIO) &&
5767 		    ((un->un_status == KEY_NOT_READY) &&
5768 			/* Medium not present */
5769 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5770 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5771 		    (un->un_dp->type == MT_ISSTK9840) &&
5772 			/* CSL not present */
5773 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5774 			rval = ENOTTY;
5775 			break;
5776 		} else if (rval != EACCES && rval != 0) {
5777 			rval = EIO;
5778 		}
5779 		if (rval) {
5780 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5781 			    "st_do_mtioctop : %s : MTLOAD\n",
5782 			    rval == EACCES ? "EACCES" : "EIO");
5783 			/*
5784 			 * If load tape fails, who knows what happened...
5785 			 */
5786 			un->un_pos.pmode = invalid;
5787 			break;
5788 		}
5789 
5790 		/*
5791 		 * reset all counters appropriately using rewind, as if LOAD
5792 		 * succeeds, we are at BOT
5793 		 */
5794 		un->un_state = ST_STATE_INITIALIZING;
5795 
5796 		rval = st_tape_init(un);
5797 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5798 			rval = 0;
5799 			break;
5800 		}
5801 
5802 		if (rval != 0) {
5803 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5804 			    "st_do_mtioctop : EIO : MTLOAD calls "
5805 			    "st_tape_init\n");
5806 			rval = EIO;
5807 			un->un_state = ST_STATE_OFFLINE;
5808 		}
5809 
5810 		break;
5811 
5812 	case MTNOP:
5813 		un->un_status = 0;		/* Reset status */
5814 		un->un_err_resid = 0;
5815 		mtop->mt_count = MTUNIT(dev);
5816 		break;
5817 
5818 	case MTEOM:
5819 		/*
5820 		 * positions the tape at a location just after the last file
5821 		 * written on the tape. For cartridge and 8 mm, this after
5822 		 * the last file mark; for reel, this is inbetween the two
5823 		 * last 2 file marks
5824 		 */
5825 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5826 		    (un->un_lastop == ST_OP_WRITE) ||
5827 		    (un->un_lastop == ST_OP_WEOF)) {
5828 			/*
5829 			 * If the command wants to move to logical end
5830 			 * of media, and we're already there, we're done.
5831 			 * If we were at logical eot, we reset the state
5832 			 * to be *not* at logical eot.
5833 			 *
5834 			 * If we're at physical or logical eot, we prohibit
5835 			 * forward space operations (unconditionally).
5836 			 *
5837 			 * Also if the last operation was a write of any
5838 			 * kind the tape is at EOD.
5839 			 */
5840 			return (0);
5841 		}
5842 		/*
5843 		 * physical tape position may not be what we've been
5844 		 * telling the user; adjust the request accordingly
5845 		 */
5846 		if (IN_EOF(un->un_pos)) {
5847 			un->un_pos.fileno++;
5848 			un->un_pos.blkno = 0;
5849 		}
5850 
5851 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
5852 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5853 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
5854 			    " failed");
5855 			return (EIO);
5856 		}
5857 
5858 		/*
5859 		 * st_find_eod() returns the last fileno we knew about;
5860 		 */
5861 		savefile = st_find_eod(un);
5862 
5863 		if ((un->un_status != KEY_BLANK_CHECK) &&
5864 		    (un->un_status != SUN_KEY_EOT)) {
5865 			un->un_pos.pmode = invalid;
5866 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5867 			    "st_do_mtioctop : EIO : MTEOM status check failed");
5868 			rval = EIO;
5869 		} else {
5870 			/*
5871 			 * For 1/2" reel tapes assume logical EOT marked
5872 			 * by two file marks or we don't care that we may
5873 			 * be extending the last file on the tape.
5874 			 */
5875 			if (un->un_dp->options & ST_REEL) {
5876 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
5877 					un->un_pos.pmode = invalid;
5878 					ST_DEBUG2(ST_DEVINFO, st_label,
5879 					    SCSI_DEBUG,
5880 					    "st_do_mtioctop : EIO : MTEOM space"
5881 					    " cmd failed");
5882 					rval = EIO;
5883 					break;
5884 				}
5885 				/*
5886 				 * Fix up the block number.
5887 				 */
5888 				un->un_pos.blkno = 0;
5889 				un->un_err_pos.blkno = 0;
5890 			}
5891 			un->un_err_resid = 0;
5892 			un->un_pos.fileno = savefile;
5893 			un->un_pos.eof = ST_EOT;
5894 		}
5895 		un->un_status = 0;
5896 		break;
5897 
5898 	case MTFSF:
5899 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
5900 		break;
5901 
5902 	case MTFSR:
5903 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
5904 		break;
5905 
5906 	case MTBSF:
5907 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
5908 		break;
5909 
5910 	case MTNBSF:
5911 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
5912 		break;
5913 
5914 	case MTBSR:
5915 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
5916 		break;
5917 
5918 	case MTBSSF:
5919 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
5920 		break;
5921 
5922 	case MTFSSF:
5923 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
5924 		break;
5925 
5926 	case MTSRSZ:
5927 
5928 		/*
5929 		 * Set record-size to that sent by user
5930 		 * Check to see if there is reason that the requested
5931 		 * block size should not be set.
5932 		 */
5933 
5934 		/* If requesting variable block size is it ok? */
5935 		if ((mtop->mt_count == 0) &&
5936 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
5937 			return (ENOTTY);
5938 		}
5939 
5940 		/*
5941 		 * If requested block size is not variable "0",
5942 		 * is it less then minimum.
5943 		 */
5944 		if ((mtop->mt_count != 0) &&
5945 		    (mtop->mt_count < un->un_minbsize)) {
5946 			return (EINVAL);
5947 		}
5948 
5949 		/* Is the requested block size more then maximum */
5950 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
5951 		    (un->un_maxbsize != 0)) {
5952 			return (EINVAL);
5953 		}
5954 
5955 		/* Is requested block size a modulus the device likes */
5956 		if ((mtop->mt_count % un->un_data_mod) != 0) {
5957 			return (EINVAL);
5958 		}
5959 
5960 		if (st_change_block_size(un, (uint32_t)mtop->mt_count) != 0) {
5961 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5962 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
5963 			return (EIO);
5964 		}
5965 
5966 		return (0);
5967 
5968 	case MTGRSZ:
5969 		/*
5970 		 * Get record-size to the user
5971 		 */
5972 		mtop->mt_count = un->un_bsize;
5973 		rval = 0;
5974 		break;
5975 
5976 	case MTTELL:
5977 		rval = st_update_block_pos(un, st_cmd, 0);
5978 		mtop->mt_count = un->un_pos.lgclblkno;
5979 		break;
5980 
5981 	case MTSEEK:
5982 		rval = st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
5983 		    (uint64_t)mtop->mt_count, un->un_pos.partition);
5984 		/*
5985 		 * This bit of magic make mt print the actual position if
5986 		 * the resulting position was not what was asked for.
5987 		 */
5988 		if (rval == ESPIPE) {
5989 			rval = EIO;
5990 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
5991 				mtop->mt_op = MTTELL;
5992 				mtop->mt_count = un->un_pos.lgclblkno;
5993 			}
5994 		}
5995 		break;
5996 
5997 	case MTLOCK:
5998 		if (st_cmd(un, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
5999 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6000 			    "st_do_mtioctop : EIO : MTLOCK");
6001 			rval = EIO;
6002 		}
6003 		break;
6004 
6005 	case MTUNLOCK:
6006 		if (st_cmd(un, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
6007 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6008 			    "st_do_mtioctop : EIO : MTUNLOCK");
6009 			rval = EIO;
6010 		}
6011 		break;
6012 
6013 	default:
6014 		rval = ENOTTY;
6015 	}
6016 
6017 	return (rval);
6018 }
6019 
6020 
6021 /*
6022  * Run a command for uscsi ioctl.
6023  */
6024 static int
6025 st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
6026 {
6027 	struct uscsi_cmd	*uscmd;
6028 	struct buf	*bp;
6029 	enum uio_seg	uioseg;
6030 	int	offline_state = 0;
6031 	int	err = 0;
6032 	dev_t dev = un->un_dev;
6033 
6034 	ST_FUNC(ST_DEVINFO, st_uscsi_cmd);
6035 
6036 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6037 	    "st_uscsi_cmd(dev = 0x%lx)\n", un->un_dev);
6038 
6039 	ASSERT(mutex_owned(ST_MUTEX));
6040 
6041 	/*
6042 	 * We really don't know what commands are coming in here and
6043 	 * we don't want to limit the commands coming in.
6044 	 *
6045 	 * If st_tape_init() gets called from st_strategy(), then we
6046 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
6047 	 * which it never will, as we set it below.  To prevent
6048 	 * st_tape_init() from getting called, we have to set state to other
6049 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
6050 	 * achieves this purpose already.
6051 	 *
6052 	 * We use offline_state to preserve the OFFLINE state, if it exists,
6053 	 * so other entry points to the driver might have the chance to call
6054 	 * st_tape_init().
6055 	 */
6056 	if (un->un_state == ST_STATE_OFFLINE) {
6057 		un->un_laststate = ST_STATE_OFFLINE;
6058 		un->un_state = ST_STATE_INITIALIZING;
6059 		offline_state = 1;
6060 	}
6061 
6062 	mutex_exit(ST_MUTEX);
6063 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag, ROUTE, &uscmd);
6064 	mutex_enter(ST_MUTEX);
6065 	if (err != 0) {
6066 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6067 		    "st_uscsi_cmd: scsi_uscsi_alloc_and_copyin failed\n");
6068 		goto exit;
6069 	}
6070 
6071 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
6072 
6073 	/* check to see if this command requires the drive to be reserved */
6074 	if (uscmd->uscsi_cdb != NULL) {
6075 		err = st_check_cdb_for_need_to_reserve(un,
6076 		    (uchar_t *)uscmd->uscsi_cdb);
6077 		if (err) {
6078 			goto exit_free;
6079 		}
6080 		/*
6081 		 * If this is a space command we need to save the starting
6082 		 * point so we can retry from there if the command fails.
6083 		 */
6084 		if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6085 		    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) {
6086 			(void) st_update_block_pos(un, st_cmd, 0);
6087 		}
6088 	}
6089 
6090 	/*
6091 	 * Forground should not be doing anything while recovery is active.
6092 	 */
6093 	ASSERT(un->un_recov_buf_busy == 0);
6094 
6095 	/*
6096 	 * Get buffer resources...
6097 	 */
6098 	while (un->un_sbuf_busy)
6099 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6100 	un->un_sbuf_busy = 1;
6101 
6102 #ifdef STDEBUG
6103 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0x7) > 6) {
6104 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
6105 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6106 		    "uscsi cdb", uscmd->uscsi_cdb);
6107 		if (uscmd->uscsi_buflen) {
6108 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6109 			    "uscsi %s of %ld bytes %s %s space\n",
6110 			    (rw == B_READ) ? rd_str : wr_str,
6111 			    uscmd->uscsi_buflen,
6112 			    (rw == B_READ) ? "to" : "from",
6113 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
6114 		}
6115 	}
6116 #endif /* STDEBUG */
6117 
6118 	/*
6119 	 * Although st_uscsi_cmd() never makes use of these
6120 	 * now, we are just being safe and consistent.
6121 	 */
6122 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
6123 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
6124 
6125 	un->un_srqbufp = uscmd->uscsi_rqbuf;
6126 	bp = un->un_sbufp;
6127 	bzero(bp, sizeof (buf_t));
6128 	if (uscmd->uscsi_cdb != NULL) {
6129 		bp->b_forw = (struct buf *)(uintptr_t)uscmd->uscsi_cdb[0];
6130 	}
6131 	bp->b_back = (struct buf *)uscmd;
6132 
6133 	mutex_exit(ST_MUTEX);
6134 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, st_strategy, bp, NULL);
6135 	mutex_enter(ST_MUTEX);
6136 
6137 	/*
6138 	 * If scsi reset successful, don't write any filemarks.
6139 	 */
6140 	if ((err == 0) && (uscmd->uscsi_flags &
6141 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
6142 		un->un_fmneeded = 0;
6143 	}
6144 
6145 exit_free:
6146 	/*
6147 	 * Free resources
6148 	 */
6149 	un->un_sbuf_busy = 0;
6150 	un->un_srqbufp = NULL;
6151 
6152 	/*
6153 	 * If was a space command need to update logical block position.
6154 	 * If the command failed such that positioning is invalid, Don't
6155 	 * update the position as the user must do this to validate the
6156 	 * position for data protection.
6157 	 */
6158 	if ((uscmd->uscsi_cdb != NULL) &&
6159 	    ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6160 	    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) &&
6161 	    (un->un_pos.pmode != invalid)) {
6162 		un->un_running.pmode = invalid;
6163 		(void) st_update_block_pos(un, st_cmd, 1);
6164 		/*
6165 		 * Set running position to invalid so it updates on the
6166 		 * next command.
6167 		 */
6168 		un->un_running.pmode = invalid;
6169 	}
6170 	cv_signal(&un->un_sbuf_cv);
6171 	mutex_exit(ST_MUTEX);
6172 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
6173 	mutex_enter(ST_MUTEX);
6174 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6175 	    "st_uscsi_cmd returns 0x%x\n", err);
6176 
6177 exit:
6178 	/* don't lose offline state */
6179 	if (offline_state) {
6180 		un->un_state = ST_STATE_OFFLINE;
6181 	}
6182 
6183 	ASSERT(mutex_owned(ST_MUTEX));
6184 	return (err);
6185 }
6186 
6187 static int
6188 st_write_fm(dev_t dev, int wfm)
6189 {
6190 	int i;
6191 	int rval;
6192 
6193 	GET_SOFT_STATE(dev);
6194 
6195 	ST_FUNC(ST_DEVINFO, st_write_fm);
6196 
6197 	ASSERT(mutex_owned(ST_MUTEX));
6198 
6199 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6200 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6201 
6202 	/*
6203 	 * write one filemark at the time after EOT
6204 	 */
6205 	if (un->un_pos.eof >= ST_EOT) {
6206 		for (i = 0; i < wfm; i++) {
6207 			rval = st_cmd(un, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6208 			if (rval == EACCES) {
6209 				return (rval);
6210 			}
6211 			if (rval != 0) {
6212 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6213 				    "st_write_fm : EIO : write EOT file mark");
6214 				return (EIO);
6215 			}
6216 		}
6217 	} else {
6218 		rval = st_cmd(un, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6219 		if (rval == EACCES) {
6220 			return (rval);
6221 		}
6222 		if (rval) {
6223 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6224 			    "st_write_fm : EIO : write file mark");
6225 			return (EIO);
6226 		}
6227 	}
6228 
6229 	ASSERT(mutex_owned(ST_MUTEX));
6230 	return (0);
6231 }
6232 
6233 #ifdef STDEBUG
6234 static void
6235 st_start_dump(struct scsi_tape *un, struct buf *bp)
6236 {
6237 	struct scsi_pkt *pkt = BP_PKT(bp);
6238 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6239 
6240 	ST_FUNC(ST_DEVINFO, st_start_dump);
6241 
6242 	if ((st_debug & 0x7) < 6)
6243 		return;
6244 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6245 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6246 	    (void *)bp->b_forw, bp->b_bcount,
6247 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6248 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6249 	    "st_start: cdb",  (caddr_t)cdbp);
6250 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6251 	    "st_start: fileno=%d, blk=%d\n",
6252 	    un->un_pos.fileno, un->un_pos.blkno);
6253 }
6254 #endif
6255 
6256 
6257 /*
6258  * Command start && done functions
6259  */
6260 
6261 /*
6262  * st_start()
6263  *
6264  * Called from:
6265  *  st_strategy() to start a command.
6266  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6267  *  st_attach() when resuming from power down state.
6268  *  st_start_restart() to retry transport when device was previously busy.
6269  *  st_done_and_mutex_exit() to start the next command when previous is done.
6270  *
6271  * On entry:
6272  *  scsi_pkt may or may not be allocated.
6273  *
6274  */
6275 static void
6276 st_start(struct scsi_tape *un)
6277 {
6278 	struct buf *bp;
6279 	int status;
6280 	int queued;
6281 
6282 	ST_FUNC(ST_DEVINFO, st_start);
6283 	ASSERT(mutex_owned(ST_MUTEX));
6284 
6285 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6286 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6287 
6288 	if (un->un_recov_buf_busy) {
6289 		/* recovery commands can happen anytime */
6290 		bp = un->un_recov_buf;
6291 		queued = 0;
6292 	} else if (un->un_sbuf_busy) {
6293 		/* sbuf commands should only happen with an empty queue. */
6294 		ASSERT(un->un_quef == NULL);
6295 		ASSERT(un->un_runqf == NULL);
6296 		bp = un->un_sbufp;
6297 		queued = 0;
6298 	} else if (un->un_quef != NULL) {
6299 		if (un->un_persistence && un->un_persist_errors) {
6300 			return;
6301 		}
6302 		bp = un->un_quef;
6303 		queued = 1;
6304 	} else {
6305 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6306 		    "st_start() returning no buf found\n");
6307 		return;
6308 	}
6309 
6310 	ASSERT((bp->b_flags & B_DONE) == 0);
6311 
6312 	/*
6313 	 * Don't send more than un_throttle commands to the HBA
6314 	 */
6315 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6316 		/*
6317 		 * if doing recovery we know there is outstanding commands.
6318 		 */
6319 		if (bp != un->un_recov_buf) {
6320 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6321 			    "st_start returning throttle = %d or ncmds = %d\n",
6322 			    un->un_throttle, un->un_ncmds);
6323 			if (un->un_ncmds == 0) {
6324 				typedef void (*func)();
6325 				func fnc = (func)st_runout;
6326 
6327 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6328 				    "Sending delayed start to st_runout()\n");
6329 				mutex_exit(ST_MUTEX);
6330 				(void) timeout(fnc, un, drv_usectohz(1000000));
6331 			}
6332 			return;
6333 		}
6334 	}
6335 
6336 	/*
6337 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6338 	 * build the command.
6339 	 */
6340 	if (BP_PKT(bp) == NULL) {
6341 		ASSERT((bp->b_flags & B_DONE) == 0);
6342 		st_make_cmd(un, bp, st_runout);
6343 		ASSERT((bp->b_flags & B_DONE) == 0);
6344 		status = geterror(bp);
6345 
6346 		/*
6347 		 * Some HBA's don't call bioerror() to set an error.
6348 		 * And geterror() returns zero if B_ERROR is not set.
6349 		 * So if we get zero we must check b_error.
6350 		 */
6351 		if (status == 0 && bp->b_error != 0) {
6352 			status = bp->b_error;
6353 			bioerror(bp, status);
6354 		}
6355 
6356 		/*
6357 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6358 		 * In tape ENOMEM has special meaning so we'll change it.
6359 		 */
6360 		if (status == ENOMEM) {
6361 			status = 0;
6362 			bioerror(bp, status);
6363 		}
6364 
6365 		/*
6366 		 * Did it fail and is it retryable?
6367 		 * If so return and wait for the callback through st_runout.
6368 		 * Also looks like scsi_init_pkt() will setup a callback even
6369 		 * if it isn't retryable.
6370 		 */
6371 		if (BP_PKT(bp) == NULL) {
6372 			if (status == 0) {
6373 				/*
6374 				 * If first attempt save state.
6375 				 */
6376 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6377 					un->un_laststate = un->un_state;
6378 					un->un_state = ST_STATE_RESOURCE_WAIT;
6379 				}
6380 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6381 				    "temp no resources for pkt\n");
6382 			} else if (status == EINVAL) {
6383 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6384 				    "scsi_init_pkt rejected pkt as too big\n");
6385 				if (un->un_persistence) {
6386 					st_set_pe_flag(un);
6387 				}
6388 			} else {
6389 				/*
6390 				 * Unlikely that it would be retryable then not.
6391 				 */
6392 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6393 					un->un_state = un->un_laststate;
6394 				}
6395 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6396 				    "perm no resources for pkt errno = 0x%x\n",
6397 				    status);
6398 			}
6399 			return;
6400 		}
6401 		/*
6402 		 * Worked this time set the state back.
6403 		 */
6404 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6405 			un->un_state = un->un_laststate;
6406 		}
6407 	}
6408 
6409 	if (queued) {
6410 		/*
6411 		 * move from waitq to runq
6412 		 */
6413 		(void) st_remove_from_queue(&un->un_quef, &un->un_quel, bp);
6414 		st_add_to_queue(&un->un_runqf, &un->un_runql, un->un_runql, bp);
6415 	}
6416 
6417 
6418 #ifdef STDEBUG
6419 	st_start_dump(un, bp);
6420 #endif
6421 
6422 	/* could not get here if throttle was zero */
6423 	un->un_last_throttle = un->un_throttle;
6424 	un->un_throttle = 0;	/* so nothing else will come in here */
6425 	un->un_ncmds++;
6426 
6427 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6428 
6429 	status = st_transport(un, BP_PKT(bp));
6430 
6431 	if (un->un_last_throttle) {
6432 		un->un_throttle = un->un_last_throttle;
6433 	}
6434 
6435 	if (status != TRAN_ACCEPT) {
6436 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6437 		mutex_exit(ST_MUTEX);
6438 
6439 		if (status == TRAN_BUSY) {
6440 			/* if too many retries, fail the transport */
6441 			if (st_handle_start_busy(un, bp,
6442 			    ST_TRAN_BUSY_TIMEOUT, queued) == 0)
6443 				goto done;
6444 		}
6445 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6446 		    "transport rejected %d\n", status);
6447 		bp->b_resid = bp->b_bcount;
6448 
6449 
6450 #ifndef __lock_lint
6451 		/*
6452 		 * warlock doesn't understand this potential
6453 		 * recursion?
6454 		 */
6455 		mutex_enter(ST_MUTEX);
6456 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6457 		ST_DO_ERRSTATS(un, st_transerrs);
6458 		st_bioerror(bp, EIO);
6459 		st_set_pe_flag(un);
6460 		st_done_and_mutex_exit(un, bp);
6461 #endif
6462 	} else {
6463 		un->un_tran_retry_ct = 0;
6464 		mutex_exit(ST_MUTEX);
6465 	}
6466 
6467 done:
6468 
6469 	mutex_enter(ST_MUTEX);
6470 }
6471 
6472 /*
6473  * if the transport is busy, then put this bp back on the waitq
6474  */
6475 static int
6476 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6477     clock_t timeout_interval, int queued)
6478 {
6479 
6480 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6481 
6482 	mutex_enter(ST_MUTEX);
6483 
6484 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6485 	    "st_handle_start_busy()\n");
6486 
6487 	/*
6488 	 * Check to see if we hit the retry timeout and one last check for
6489 	 * making sure this is the last on the runq, if it is not, we have
6490 	 * to fail
6491 	 */
6492 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
6493 	    ((queued) && (un->un_runql != bp))) {
6494 		mutex_exit(ST_MUTEX);
6495 		return (-1);
6496 	}
6497 
6498 	if (queued) {
6499 		/* put the bp back on the waitq */
6500 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
6501 	}
6502 
6503 	/*
6504 	 * Decrement un_ncmds so that this
6505 	 * gets thru' st_start() again.
6506 	 */
6507 	un->un_ncmds--;
6508 
6509 	if (queued) {
6510 		/*
6511 		 * since this is an error case, we won't have to do this list
6512 		 * walking much. We've already made sure this bp was the
6513 		 * last on the runq
6514 		 */
6515 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6516 
6517 		/*
6518 		 * send a marker pkt, if appropriate
6519 		 */
6520 		st_hba_unflush(un);
6521 
6522 	}
6523 	/*
6524 	 * all queues are aligned, we are just waiting to
6525 	 * transport, don't alloc any more buf p's, when
6526 	 * st_start is reentered.
6527 	 */
6528 	(void) timeout(st_start_restart, un, timeout_interval);
6529 
6530 	mutex_exit(ST_MUTEX);
6531 	return (0);
6532 }
6533 
6534 
6535 /*
6536  * st_runout a callback that is called what a resource allocatation failed
6537  */
6538 static int
6539 st_runout(caddr_t arg)
6540 {
6541 	struct scsi_tape *un = (struct scsi_tape *)arg;
6542 	struct buf *bp;
6543 	int queued;
6544 
6545 	ASSERT(un != NULL);
6546 
6547 	ST_FUNC(ST_DEVINFO, st_runout);
6548 
6549 	mutex_enter(ST_MUTEX);
6550 
6551 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6552 
6553 	if (un->un_recov_buf_busy != 0) {
6554 		bp = un->un_recov_buf;
6555 		queued = 0;
6556 	} else if (un->un_sbuf_busy != 0) {
6557 		/* sbuf commands should only happen with an empty queue. */
6558 		ASSERT(un->un_quef == NULL);
6559 		ASSERT(un->un_runqf == NULL);
6560 		bp = un->un_sbufp;
6561 		queued = 0;
6562 	} else if (un->un_quef != NULL) {
6563 		bp = un->un_quef;
6564 		if (un->un_persistence && un->un_persist_errors) {
6565 			mutex_exit(ST_MUTEX);
6566 			bp->b_resid = bp->b_bcount;
6567 			biodone(bp);
6568 			return (1);
6569 		}
6570 		queued = 1;
6571 	} else {
6572 		ASSERT(1 == 0);
6573 		mutex_exit(ST_MUTEX);
6574 		return (1);
6575 	}
6576 
6577 	/*
6578 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6579 	 */
6580 	if ((bp != NULL) && (geterror(bp) != 0)) {
6581 
6582 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6583 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6584 		    bp->b_flags, geterror(bp));
6585 		ASSERT((bp->b_flags & B_DONE) == 0);
6586 
6587 		if (queued) {
6588 			(void) st_remove_from_queue(&un->un_quef, &un->un_quel,
6589 			    bp);
6590 		}
6591 		mutex_exit(ST_MUTEX);
6592 
6593 		ASSERT((bp->b_flags & B_DONE) == 0);
6594 
6595 		/*
6596 		 * Set resid, Error already set, then unblock calling thread.
6597 		 */
6598 		bp->b_resid = bp->b_bcount;
6599 		biodone(bp);
6600 	} else {
6601 		/*
6602 		 * Try Again
6603 		 */
6604 		st_start(un);
6605 		mutex_exit(ST_MUTEX);
6606 	}
6607 
6608 	/*
6609 	 * Comments courtesy of sd.c
6610 	 * The scsi_init_pkt routine allows for the callback function to
6611 	 * return a 0 indicating the callback should be rescheduled or a 1
6612 	 * indicating not to reschedule. This routine always returns 1
6613 	 * because the driver always provides a callback function to
6614 	 * scsi_init_pkt. This results in a callback always being scheduled
6615 	 * (via the scsi_init_pkt callback implementation) if a resource
6616 	 * failure occurs.
6617 	 */
6618 
6619 	return (1);
6620 }
6621 
6622 /*
6623  * st_done_and_mutex_exit()
6624  *	- remove bp from runq
6625  *	- start up the next request
6626  *	- if this was an asynch bp, clean up
6627  *	- exit with released mutex
6628  */
6629 static void
6630 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6631 {
6632 	int	pe_flagged = 0;
6633 
6634 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6635 #if !defined(lint)
6636 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6637 #endif
6638 
6639 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6640 
6641 	ASSERT(mutex_owned(ST_MUTEX));
6642 
6643 	(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6644 
6645 	un->un_ncmds--;
6646 	cv_signal(&un->un_queue_cv);
6647 
6648 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6649 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6650 	    "0x%x\n", (uchar_t)*((caddr_t)(BP_PKT(bp))->pkt_cdbp), bp->b_bcount,
6651 	    bp->b_resid, bp->b_flags);
6652 
6653 
6654 	/*
6655 	 * update kstats with transfer count info
6656 	 */
6657 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6658 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6659 		if (bp->b_flags & B_READ) {
6660 			IOSP->reads++;
6661 			IOSP->nread += n_done;
6662 		} else {
6663 			IOSP->writes++;
6664 			IOSP->nwritten += n_done;
6665 		}
6666 	}
6667 
6668 	/*
6669 	 * Start the next one before releasing resources on this one, if
6670 	 * there is something on the queue and persistent errors has not been
6671 	 * flagged
6672 	 */
6673 
6674 	if ((pe_flagged = (un->un_persistence && un->un_persist_errors)) != 0) {
6675 		un->un_last_resid = bp->b_resid;
6676 		un->un_last_count = bp->b_bcount;
6677 	}
6678 
6679 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6680 		cv_broadcast(&un->un_tape_busy_cv);
6681 	} else if (un->un_quef && un->un_throttle && !pe_flagged &&
6682 	    (bp != un->un_recov_buf)) {
6683 		st_start(un);
6684 	}
6685 
6686 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6687 		/*
6688 		 * Since we marked this ourselves as ASYNC,
6689 		 * there isn't anybody around waiting for
6690 		 * completion any more.
6691 		 */
6692 		uchar_t *cdb = (uchar_t *)bp->b_forw;
6693 		if (*cdb == SCMD_READ || *cdb == SCMD_WRITE) {
6694 			bp->b_un.b_addr = (caddr_t)0;
6695 		}
6696 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6697 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6698 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
6699 		    "CDB sent with B_ASYNC",  (caddr_t)cdb);
6700 		if (BP_PKT(bp)) {
6701 			scsi_destroy_pkt(BP_PKT(bp));
6702 		}
6703 		un->un_sbuf_busy = 0;
6704 		cv_signal(&un->un_sbuf_cv);
6705 		mutex_exit(ST_MUTEX);
6706 		return;
6707 	}
6708 
6709 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6710 		/*
6711 		 * Copy status from scsi_pkt to uscsi_cmd
6712 		 * since st_uscsi_cmd needs it
6713 		 */
6714 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6715 	}
6716 
6717 
6718 #ifdef STDEBUG
6719 	if (((st_debug & 0x7) >= 4) &&
6720 	    (((un->un_pos.blkno % 100) == 0) ||
6721 	    (un->un_persistence && un->un_persist_errors))) {
6722 
6723 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6724 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6725 		    "un_errno = %d, un_pe = %d\n",
6726 		    un->un_ncmds, un->un_throttle, un->un_errno,
6727 		    un->un_persist_errors);
6728 	}
6729 
6730 #endif
6731 
6732 	mutex_exit(ST_MUTEX);
6733 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6734 	    "st_done_and_mutex_exit: freeing pkt\n");
6735 
6736 	if (BP_PKT(bp)) {
6737 		scsi_destroy_pkt(BP_PKT(bp));
6738 	}
6739 
6740 	biodone(bp);
6741 
6742 	/*
6743 	 * now that we biodoned that command, if persistent errors have been
6744 	 * flagged, flush the waitq
6745 	 */
6746 	if (pe_flagged)
6747 		st_flush(un);
6748 }
6749 
6750 
6751 /*
6752  * Tape error, flush tape driver queue.
6753  */
6754 static void
6755 st_flush(struct scsi_tape *un)
6756 {
6757 	struct buf *bp;
6758 
6759 	ST_FUNC(ST_DEVINFO, st_flush);
6760 
6761 	mutex_enter(ST_MUTEX);
6762 
6763 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6764 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6765 	    un->un_ncmds, (void *)un->un_quef);
6766 
6767 	/*
6768 	 * if we still have commands outstanding, wait for them to come in
6769 	 * before flushing the queue, and make sure there is a queue
6770 	 */
6771 	if (un->un_ncmds || !un->un_quef)
6772 		goto exit;
6773 
6774 	/*
6775 	 * we have no more commands outstanding, so let's deal with special
6776 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6777 	 * is 0, then we know there was no error and we return a 0 read or
6778 	 * write before showing errors
6779 	 */
6780 
6781 	/* Flush the wait queue. */
6782 	while ((bp = un->un_quef) != NULL) {
6783 		un->un_quef = bp->b_actf;
6784 
6785 		bp->b_resid = bp->b_bcount;
6786 
6787 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6788 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6789 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6790 
6791 		st_set_pe_errno(un);
6792 
6793 		bioerror(bp, un->un_errno);
6794 
6795 		mutex_exit(ST_MUTEX);
6796 		/* it should have one, but check anyway */
6797 		if (BP_PKT(bp)) {
6798 			scsi_destroy_pkt(BP_PKT(bp));
6799 		}
6800 		biodone(bp);
6801 		mutex_enter(ST_MUTEX);
6802 	}
6803 
6804 	/*
6805 	 * It's not a bad practice to reset the
6806 	 * waitq tail pointer to NULL.
6807 	 */
6808 	un->un_quel = NULL;
6809 
6810 exit:
6811 	/* we mucked with the queue, so let others know about it */
6812 	cv_signal(&un->un_queue_cv);
6813 	mutex_exit(ST_MUTEX);
6814 }
6815 
6816 
6817 /*
6818  * Utility functions
6819  */
6820 static int
6821 st_determine_generic(struct scsi_tape *un)
6822 {
6823 	int bsize;
6824 	static char *cart = "0.25 inch cartridge";
6825 	char *sizestr;
6826 
6827 	ST_FUNC(ST_DEVINFO, st_determine_generic);
6828 
6829 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6830 	    "st_determine_generic(un = 0x%p)\n", (void*)un);
6831 
6832 	ASSERT(mutex_owned(ST_MUTEX));
6833 
6834 	if (st_modesense(un)) {
6835 		return (-1);
6836 	}
6837 
6838 	bsize = (un->un_mspl->high_bl << 16)	|
6839 	    (un->un_mspl->mid_bl << 8)	|
6840 	    (un->un_mspl->low_bl);
6841 
6842 	if (bsize == 0) {
6843 		un->un_dp->options |= ST_VARIABLE;
6844 		un->un_dp->bsize = 0;
6845 		un->un_bsize = 0;
6846 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
6847 		/*
6848 		 * record size of this device too big.
6849 		 * try and convert it to variable record length.
6850 		 *
6851 		 */
6852 		un->un_dp->options |= ST_VARIABLE;
6853 		if (st_change_block_size(un, 0) != 0) {
6854 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6855 			    "Fixed Record Size %d is too large\n", bsize);
6856 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6857 			    "Cannot switch to variable record size\n");
6858 			un->un_dp->options &= ~ST_VARIABLE;
6859 			return (-1);
6860 		}
6861 	} else if (st_change_block_size(un, 0) == 0) {
6862 		/*
6863 		 * If the drive was set to a non zero block size,
6864 		 * See if it can be set to a zero block size.
6865 		 * If it works, ST_VARIABLE so user can set it as they want.
6866 		 */
6867 		un->un_dp->options |= ST_VARIABLE;
6868 		un->un_dp->bsize = 0;
6869 		un->un_bsize = 0;
6870 	} else {
6871 		un->un_dp->bsize = bsize;
6872 		un->un_bsize = bsize;
6873 	}
6874 
6875 
6876 	switch (un->un_mspl->density) {
6877 	default:
6878 	case 0x0:
6879 		/*
6880 		 * default density, cannot determine any other
6881 		 * information.
6882 		 */
6883 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
6884 		un->un_dp->type = ST_TYPE_DEFAULT;
6885 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
6886 		break;
6887 	case 0x1:
6888 	case 0x2:
6889 	case 0x3:
6890 	case 0x6:
6891 		/*
6892 		 * 1/2" reel
6893 		 */
6894 		sizestr = "0.50 inch reel";
6895 		un->un_dp->type = ST_TYPE_REEL;
6896 		un->un_dp->options |= ST_REEL;
6897 		un->un_dp->densities[0] = 0x1;
6898 		un->un_dp->densities[1] = 0x2;
6899 		un->un_dp->densities[2] = 0x6;
6900 		un->un_dp->densities[3] = 0x3;
6901 		break;
6902 	case 0x4:
6903 	case 0x5:
6904 	case 0x7:
6905 	case 0x0b:
6906 
6907 		/*
6908 		 * Quarter inch.
6909 		 */
6910 		sizestr = cart;
6911 		un->un_dp->type = ST_TYPE_DEFAULT;
6912 		un->un_dp->options |= ST_QIC;
6913 
6914 		un->un_dp->densities[1] = 0x4;
6915 		un->un_dp->densities[2] = 0x5;
6916 		un->un_dp->densities[3] = 0x7;
6917 		un->un_dp->densities[0] = 0x0b;
6918 		break;
6919 
6920 	case 0x0f:
6921 	case 0x10:
6922 	case 0x11:
6923 	case 0x12:
6924 		/*
6925 		 * QIC-120, QIC-150, QIC-320, QIC-600
6926 		 */
6927 		sizestr = cart;
6928 		un->un_dp->type = ST_TYPE_DEFAULT;
6929 		un->un_dp->options |= ST_QIC;
6930 		un->un_dp->densities[0] = 0x0f;
6931 		un->un_dp->densities[1] = 0x10;
6932 		un->un_dp->densities[2] = 0x11;
6933 		un->un_dp->densities[3] = 0x12;
6934 		break;
6935 
6936 	case 0x09:
6937 	case 0x0a:
6938 	case 0x0c:
6939 	case 0x0d:
6940 		/*
6941 		 * 1/2" cartridge tapes. Include HI-TC.
6942 		 */
6943 		sizestr = cart;
6944 		sizestr[2] = '5';
6945 		sizestr[3] = '0';
6946 		un->un_dp->type = ST_TYPE_HIC;
6947 		un->un_dp->densities[0] = 0x09;
6948 		un->un_dp->densities[1] = 0x0a;
6949 		un->un_dp->densities[2] = 0x0c;
6950 		un->un_dp->densities[3] = 0x0d;
6951 		break;
6952 
6953 	case 0x13:
6954 			/* DDS-2/DDS-3 scsi spec densities */
6955 	case 0x24:
6956 	case 0x25:
6957 	case 0x26:
6958 		sizestr = "DAT Data Storage (DDS)";
6959 		un->un_dp->type = ST_TYPE_DAT;
6960 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6961 		break;
6962 
6963 	case 0x14:
6964 		/*
6965 		 * Helical Scan (Exabyte) devices
6966 		 */
6967 		sizestr = "8mm helical scan cartridge";
6968 		un->un_dp->type = ST_TYPE_EXABYTE;
6969 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6970 		break;
6971 	}
6972 
6973 	/*
6974 	 * Assume LONG ERASE, BSF and BSR
6975 	 */
6976 
6977 	un->un_dp->options |=
6978 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
6979 
6980 	/*
6981 	 * Only if mode sense data says no buffered write, set NOBUF
6982 	 */
6983 	if (un->un_mspl->bufm == 0)
6984 		un->un_dp->options |= ST_NOBUF;
6985 
6986 	/*
6987 	 * set up large read and write retry counts
6988 	 */
6989 
6990 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
6991 
6992 	/*
6993 	 * If this is a 0.50 inch reel tape, and
6994 	 * it is *not* variable mode, try and
6995 	 * set it to variable record length
6996 	 * mode.
6997 	 */
6998 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
6999 	    (un->un_dp->options & ST_VARIABLE)) {
7000 		if (st_change_block_size(un, 0) == 0) {
7001 			un->un_dp->bsize = 0;
7002 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
7003 			    un->un_mspl->low_bl = 0;
7004 		}
7005 	}
7006 
7007 	/*
7008 	 * Write to console about type of device found
7009 	 */
7010 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
7011 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
7012 	    sizestr);
7013 	if (un->un_dp->options & ST_VARIABLE) {
7014 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7015 		    "!Variable record length I/O\n");
7016 	} else {
7017 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7018 		    "!Fixed record length (%d byte blocks) I/O\n",
7019 		    un->un_dp->bsize);
7020 	}
7021 	ASSERT(mutex_owned(ST_MUTEX));
7022 	return (0);
7023 }
7024 
7025 static int
7026 st_determine_density(struct scsi_tape *un, int rw)
7027 {
7028 	int rval = 0;
7029 
7030 	ST_FUNC(ST_DEVINFO, st_determine_density);
7031 
7032 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7033 	    "st_determine_density(un = 0x%p, rw = %s)\n",
7034 	    (void*)un, (rw == B_WRITE ? wr_str: rd_str));
7035 
7036 	ASSERT(mutex_owned(ST_MUTEX));
7037 
7038 	/*
7039 	 * If we're past BOT, density is determined already.
7040 	 */
7041 	if (un->un_pos.pmode == logical) {
7042 		if (un->un_pos.lgclblkno != 0) {
7043 			goto exit;
7044 		}
7045 	} else if (un->un_pos.pmode == legacy) {
7046 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
7047 			/*
7048 			 * XXX: put in a bitch message about attempting to
7049 			 * XXX: change density past BOT.
7050 			 */
7051 			goto exit;
7052 		}
7053 	} else {
7054 		goto exit;
7055 	}
7056 	if ((un->un_pos.pmode == logical) &&
7057 	    (un->un_pos.lgclblkno != 0)) {
7058 		goto exit;
7059 	}
7060 
7061 
7062 	/*
7063 	 * If we're going to be writing, we set the density
7064 	 */
7065 	if (rw == 0 || rw == B_WRITE) {
7066 		/* un_curdens is used as an index into densities table */
7067 		un->un_curdens = MT_DENSITY(un->un_dev);
7068 		if (st_set_density(un)) {
7069 			rval = -1;
7070 		}
7071 		goto exit;
7072 	}
7073 
7074 	/*
7075 	 * If density is known already,
7076 	 * we don't have to get it again.(?)
7077 	 */
7078 	if (!un->un_density_known) {
7079 		if (st_get_density(un)) {
7080 			rval = -1;
7081 		}
7082 	}
7083 
7084 exit:
7085 	ASSERT(mutex_owned(ST_MUTEX));
7086 	return (rval);
7087 }
7088 
7089 
7090 /*
7091  * Try to determine density. We do this by attempting to read the
7092  * first record off the tape, cycling through the available density
7093  * codes as we go.
7094  */
7095 
7096 static int
7097 st_get_density(struct scsi_tape *un)
7098 {
7099 	int succes = 0, rval = -1, i;
7100 	uint_t size;
7101 	uchar_t dens, olddens;
7102 
7103 	ST_FUNC(ST_DEVINFO, st_get_density);
7104 
7105 	ST_FUNC(ST_DEVINFO, st_get_density);
7106 
7107 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7108 	    "st_get_density(un = 0x%p)\n", (void*)un);
7109 
7110 	ASSERT(mutex_owned(ST_MUTEX));
7111 
7112 	/*
7113 	 * If Auto Density override is enabled The drive has
7114 	 * only one density and there is no point in attempting
7115 	 * find the correct one.
7116 	 *
7117 	 * Since most modern drives auto detect the density
7118 	 * and format of the recorded media before they come
7119 	 * ready. What this function does is a legacy behavior
7120 	 * and modern drives not only don't need it, The backup
7121 	 * utilities that do positioning via uscsi find the un-
7122 	 * expected rewinds problematic.
7123 	 *
7124 	 * The drives that need this are old reel to reel devices.
7125 	 * I took a swag and said they must be scsi-1 or older.
7126 	 * I don't beleave there will any of the newer devices
7127 	 * that need this. There will be some scsi-1 devices that
7128 	 * don't need this but I don't think they will be using the
7129 	 * BIG aftermarket backup and restore utilitys.
7130 	 */
7131 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
7132 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
7133 		un->un_density_known = 1;
7134 		rval = 0;
7135 		goto exit;
7136 	}
7137 
7138 	/*
7139 	 * This will only work on variable record length tapes
7140 	 * if and only if all variable record length tapes autodensity
7141 	 * select.
7142 	 */
7143 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
7144 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
7145 
7146 	/*
7147 	 * Start at the specified density
7148 	 */
7149 
7150 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
7151 
7152 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
7153 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
7154 		/*
7155 		 * If we've done this density before,
7156 		 * don't bother to do it again.
7157 		 */
7158 		dens = un->un_dp->densities[un->un_curdens];
7159 		if (i > 0 && dens == olddens)
7160 			continue;
7161 		olddens = dens;
7162 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7163 		    "trying density 0x%x\n", dens);
7164 		if (st_set_density(un)) {
7165 			continue;
7166 		}
7167 
7168 		/*
7169 		 * XXX - the creates lots of headaches and slowdowns - must
7170 		 * fix.
7171 		 */
7172 		succes = (st_cmd(un, SCMD_READ, (int)size, SYNC_CMD) == 0);
7173 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
7174 			break;
7175 		}
7176 		if (succes) {
7177 			st_init(un);
7178 			rval = 0;
7179 			un->un_density_known = 1;
7180 			break;
7181 		}
7182 	}
7183 	kmem_free(un->un_tmpbuf, size);
7184 	un->un_tmpbuf = 0;
7185 
7186 exit:
7187 	ASSERT(mutex_owned(ST_MUTEX));
7188 	return (rval);
7189 }
7190 
7191 static int
7192 st_set_density(struct scsi_tape *un)
7193 {
7194 	int rval = 0;
7195 
7196 	ST_FUNC(ST_DEVINFO, st_set_density);
7197 
7198 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7199 	    "st_set_density(un = 0x%p): density = 0x%x\n", (void*)un,
7200 	    un->un_dp->densities[un->un_curdens]);
7201 
7202 	ASSERT(mutex_owned(ST_MUTEX));
7203 
7204 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7205 
7206 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
7207 		/*
7208 		 * If auto density override is not set, Use mode select
7209 		 * to set density and compression.
7210 		 */
7211 		if (st_modeselect(un)) {
7212 			rval = -1;
7213 		}
7214 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
7215 		/*
7216 		 * If auto density and mode select compression are set,
7217 		 * This is a drive with one density code but compression
7218 		 * can be enabled or disabled.
7219 		 * Set compression but no need to set density.
7220 		 */
7221 		rval = st_set_compression(un);
7222 		if ((rval != 0) && (rval != EALREADY)) {
7223 			rval = -1;
7224 		} else {
7225 			rval = 0;
7226 		}
7227 	}
7228 
7229 	/* If sucessful set density and/or compression, mark density known */
7230 	if (rval == 0) {
7231 		un->un_density_known = 1;
7232 	}
7233 
7234 	ASSERT(mutex_owned(ST_MUTEX));
7235 	return (rval);
7236 }
7237 
7238 static int
7239 st_loadtape(struct scsi_tape *un)
7240 {
7241 	int rval;
7242 
7243 	ST_FUNC(ST_DEVINFO, st_loadtape);
7244 
7245 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7246 	    "st_loadtape(un = 0x%p)\n", (void*) un);
7247 
7248 	ASSERT(mutex_owned(ST_MUTEX));
7249 
7250 	rval = st_update_block_pos(un, st_cmd, 0);
7251 	if (rval == EACCES) {
7252 		return (rval);
7253 	}
7254 
7255 	/*
7256 	 * 'LOAD' the tape to BOT by rewinding
7257 	 */
7258 	rval = st_cmd(un, SCMD_REWIND, 1, SYNC_CMD);
7259 	if (rval == 0) {
7260 		st_init(un);
7261 		un->un_density_known = 0;
7262 	}
7263 
7264 	ASSERT(mutex_owned(ST_MUTEX));
7265 	return (rval);
7266 }
7267 
7268 
7269 /*
7270  * Note: QIC devices aren't so smart.  If you try to append
7271  * after EOM, the write can fail because the device doesn't know
7272  * it's at EOM.	 In that case, issue a read.  The read should fail
7273  * because there's no data, but the device knows it's at EOM,
7274  * so a subsequent write should succeed.  To further confuse matters,
7275  * the target returns the same error if the tape is positioned
7276  * such that a write would overwrite existing data.  That's why
7277  * we have to do the append test.  A read in the middle of
7278  * recorded data would succeed, thus indicating we're attempting
7279  * something illegal.
7280  */
7281 
7282 
7283 static void
7284 st_test_append(struct buf *bp)
7285 {
7286 	dev_t dev = bp->b_edev;
7287 	struct scsi_tape *un;
7288 	uchar_t status;
7289 	unsigned bcount;
7290 
7291 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7292 
7293 	ST_FUNC(ST_DEVINFO, st_test_append);
7294 
7295 	ASSERT(mutex_owned(ST_MUTEX));
7296 
7297 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7298 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7299 
7300 	un->un_laststate = un->un_state;
7301 	un->un_state = ST_STATE_APPEND_TESTING;
7302 	un->un_test_append = 0;
7303 
7304 	/*
7305 	 * first, map in the buffer, because we're doing a double write --
7306 	 * first into the kernel, then onto the tape.
7307 	 */
7308 	bp_mapin(bp);
7309 
7310 	/*
7311 	 * get a copy of the data....
7312 	 */
7313 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7314 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7315 
7316 	/*
7317 	 * attempt the write..
7318 	 */
7319 
7320 	if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7321 success:
7322 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7323 		    "append write succeeded\n");
7324 		bp->b_resid = un->un_sbufp->b_resid;
7325 		mutex_exit(ST_MUTEX);
7326 		bcount = (unsigned)bp->b_bcount;
7327 		biodone(bp);
7328 		mutex_enter(ST_MUTEX);
7329 		un->un_laststate = un->un_state;
7330 		un->un_state = ST_STATE_OPEN;
7331 		kmem_free(un->un_tmpbuf, bcount);
7332 		un->un_tmpbuf = NULL;
7333 		return;
7334 	}
7335 
7336 	/*
7337 	 * The append failed. Do a short read. If that fails,  we are at EOM
7338 	 * so we can retry the write command. If that succeeds, than we're
7339 	 * all screwed up (the controller reported a real error).
7340 	 *
7341 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7342 	 * XXX: block size?
7343 	 *
7344 	 */
7345 	status = un->un_status;
7346 	un->un_status = 0;
7347 	(void) st_cmd(un, SCMD_READ, SECSIZE, SYNC_CMD);
7348 	if (un->un_status == KEY_BLANK_CHECK) {
7349 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7350 		    "append at EOM\n");
7351 		/*
7352 		 * Okay- the read failed. We should actually have confused
7353 		 * the controller enough to allow writing. In any case, the
7354 		 * i/o is on its own from here on out.
7355 		 */
7356 		un->un_laststate = un->un_state;
7357 		un->un_state = ST_STATE_OPEN;
7358 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7359 		if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount,
7360 		    SYNC_CMD) == 0) {
7361 			goto success;
7362 		}
7363 	}
7364 
7365 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7366 	    "append write failed- not at EOM\n");
7367 	bp->b_resid = bp->b_bcount;
7368 	st_bioerror(bp, EIO);
7369 
7370 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7371 	    "st_test_append : EIO : append write failed - not at EOM");
7372 
7373 	/*
7374 	 * backspace one record to get back to where we were
7375 	 */
7376 	if (st_cmd(un, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7377 		un->un_pos.pmode = invalid;
7378 	}
7379 
7380 	un->un_err_resid = bp->b_resid;
7381 	un->un_status = status;
7382 
7383 	/*
7384 	 * Note: biodone will do a bp_mapout()
7385 	 */
7386 	mutex_exit(ST_MUTEX);
7387 	bcount = (unsigned)bp->b_bcount;
7388 	biodone(bp);
7389 	mutex_enter(ST_MUTEX);
7390 	un->un_laststate = un->un_state;
7391 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7392 	kmem_free(un->un_tmpbuf, bcount);
7393 	un->un_tmpbuf = NULL;
7394 }
7395 
7396 /*
7397  * Special command handler
7398  */
7399 
7400 /*
7401  * common st_cmd code. The fourth parameter states
7402  * whether the caller wishes to await the results
7403  * Note the release of the mutex during most of the function
7404  */
7405 static int
7406 st_cmd(struct scsi_tape *un, int com, int64_t count, int wait)
7407 {
7408 	struct buf *bp;
7409 	int err;
7410 
7411 	ST_FUNC(ST_DEVINFO, st_cmd);
7412 
7413 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7414 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %"PRIx64", wait = %d)\n",
7415 	    un->un_dev, com, count, wait);
7416 
7417 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7418 	ASSERT(mutex_owned(ST_MUTEX));
7419 
7420 #ifdef STDEBUG
7421 	if ((st_debug & 0x7)) {
7422 		st_debug_cmds(un, com, count, wait);
7423 	}
7424 #endif
7425 
7426 	st_wait_for_io(un);
7427 
7428 	/* check to see if this command requires the drive to be reserved */
7429 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7430 
7431 	if (err) {
7432 		return (err);
7433 	}
7434 
7435 	/*
7436 	 * A space command is not recoverable if we don't know were we
7437 	 * were when it was issued.
7438 	 */
7439 	if ((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) {
7440 		(void) st_update_block_pos(un, st_cmd, 0);
7441 	}
7442 
7443 	/*
7444 	 * Forground should not be doing anything while recovery is active.
7445 	 */
7446 	ASSERT(un->un_recov_buf_busy == 0);
7447 
7448 	while (un->un_sbuf_busy)
7449 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7450 	un->un_sbuf_busy = 1;
7451 
7452 	bp = un->un_sbufp;
7453 	bzero(bp, sizeof (buf_t));
7454 
7455 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7456 
7457 	err = st_setup_cmd(un, bp, com, count);
7458 
7459 	un->un_sbuf_busy = 0;
7460 
7461 	/*
7462 	 * If was a space command need to update logical block position.
7463 	 * Only do this if the command was sucessful or it will mask the fact
7464 	 * that the space command failed by promoting the pmode to logical.
7465 	 */
7466 	if (((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) &&
7467 	    (un->un_pos.pmode != invalid)) {
7468 		un->un_running.pmode = invalid;
7469 		(void) st_update_block_pos(un, st_cmd, 1);
7470 		/*
7471 		 * Set running position to invalid so it updates on the
7472 		 * next command.
7473 		 */
7474 		un->un_running.pmode = invalid;
7475 	}
7476 
7477 	cv_signal(&un->un_sbuf_cv);
7478 
7479 	return (err);
7480 }
7481 
7482 static int
7483 st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com, int64_t count)
7484 {
7485 	int err;
7486 	dev_t dev = un->un_dev;
7487 
7488 	ST_FUNC(ST_DEVINFO, st_setup_cmd);
7489 	/*
7490 	 * Set count to the actual size of the data tranfer.
7491 	 * For commands with no data transfer, set bp->b_bcount
7492 	 * to the value to be used when constructing the
7493 	 * cdb in st_make_cmd().
7494 	 */
7495 	switch (com) {
7496 	case SCMD_READ:
7497 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7498 		    "special read %"PRId64"\n", count);
7499 		bp->b_flags |= B_READ;
7500 		bp->b_un.b_addr = un->un_tmpbuf;
7501 		break;
7502 
7503 	case SCMD_WRITE:
7504 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7505 		    "special write %"PRId64"\n", count);
7506 		bp->b_un.b_addr = un->un_tmpbuf;
7507 		break;
7508 
7509 	case SCMD_WRITE_FILE_MARK:
7510 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7511 		    "write %"PRId64" file marks\n", count);
7512 		bp->b_bcount = count;
7513 		count = 0;
7514 		break;
7515 
7516 	case SCMD_REWIND:
7517 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7518 		bp->b_bcount = count;
7519 		count = 0;
7520 		break;
7521 
7522 	case SCMD_SPACE:
7523 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7524 		/*
7525 		 * If the user could have entered a number that will
7526 		 * not fit in the 12 bit count field of space(8),
7527 		 * use space(16).
7528 		 */
7529 		if (((int64_t)SPACE_CNT(count) > 0x7fffff) ||
7530 		    ((int64_t)SPACE_CNT(count) < -(0x7fffff))) {
7531 			com = SCMD_SPACE_G4;
7532 		}
7533 		bp->b_bcount = count;
7534 		count = 0;
7535 		break;
7536 
7537 	case SCMD_RESERVE:
7538 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7539 		bp->b_bcount = 0;
7540 		count = 0;
7541 		break;
7542 
7543 	case SCMD_RELEASE:
7544 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7545 		bp->b_bcount = 0;
7546 		count = 0;
7547 		break;
7548 
7549 	case SCMD_LOAD:
7550 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7551 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7552 		bp->b_bcount = count;
7553 		count = 0;
7554 		break;
7555 
7556 	case SCMD_ERASE:
7557 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7558 		    "erase tape\n");
7559 		bp->b_bcount = count;
7560 		count = 0;
7561 		break;
7562 
7563 	case SCMD_MODE_SENSE:
7564 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7565 		    "mode sense\n");
7566 		bp->b_flags |= B_READ;
7567 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7568 		break;
7569 
7570 	case SCMD_MODE_SELECT:
7571 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7572 		    "mode select\n");
7573 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7574 		break;
7575 
7576 	case SCMD_READ_BLKLIM:
7577 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7578 		    "read block limits\n");
7579 		bp->b_bcount = count;
7580 		bp->b_flags |= B_READ;
7581 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7582 		break;
7583 
7584 	case SCMD_TEST_UNIT_READY:
7585 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7586 		    "test unit ready\n");
7587 		bp->b_bcount = 0;
7588 		count = 0;
7589 		break;
7590 
7591 	case SCMD_DOORLOCK:
7592 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7593 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7594 		bp->b_bcount = count = 0;
7595 		break;
7596 
7597 	case SCMD_READ_POSITION:
7598 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7599 		    "read position\n");
7600 		switch (un->un_read_pos_type) {
7601 		case LONG_POS:
7602 			count = sizeof (tape_position_long_t);
7603 			break;
7604 		case EXT_POS:
7605 			count = min(count, sizeof (tape_position_ext_t));
7606 			break;
7607 		case SHORT_POS:
7608 			count = sizeof (tape_position_t);
7609 			break;
7610 		default:
7611 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7612 			    "Unknown read position type 0x%x in "
7613 			    "st_make_cmd()\n", un->un_read_pos_type);
7614 		}
7615 		bp->b_bcount = count;
7616 		bp->b_flags |= B_READ;
7617 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7618 		break;
7619 
7620 	default:
7621 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7622 		    "Unhandled scsi command 0x%x in st_setup_cmd()\n", com);
7623 	}
7624 
7625 	mutex_exit(ST_MUTEX);
7626 
7627 	if (count > 0) {
7628 		int flg = (bp->b_flags & B_READ) ? B_READ : B_WRITE;
7629 		/*
7630 		 * We're going to do actual I/O.
7631 		 * Set things up for physio.
7632 		 */
7633 		struct iovec aiov;
7634 		struct uio auio;
7635 		struct uio *uio = &auio;
7636 
7637 		bzero(&auio, sizeof (struct uio));
7638 		bzero(&aiov, sizeof (struct iovec));
7639 		aiov.iov_base = bp->b_un.b_addr;
7640 		aiov.iov_len = count;
7641 
7642 		uio->uio_iov = &aiov;
7643 		uio->uio_iovcnt = 1;
7644 		uio->uio_resid = aiov.iov_len;
7645 		uio->uio_segflg = UIO_SYSSPACE;
7646 
7647 		/*
7648 		 * Let physio do the rest...
7649 		 */
7650 		bp->b_forw = (struct buf *)(uintptr_t)com;
7651 		bp->b_back = NULL;
7652 		err = physio(st_strategy, bp, dev, flg, st_minphys, uio);
7653 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7654 		    "st_setup_cmd: physio returns %d\n", err);
7655 	} else {
7656 		/*
7657 		 * Mimic physio
7658 		 */
7659 		bp->b_forw = (struct buf *)(uintptr_t)com;
7660 		bp->b_back = NULL;
7661 		bp->b_edev = dev;
7662 		bp->b_dev = cmpdev(dev);
7663 		bp->b_blkno = 0;
7664 		bp->b_resid = 0;
7665 		(void) st_strategy(bp);
7666 		if (bp->b_flags & B_ASYNC) {
7667 			/*
7668 			 * This is an async command- the caller won't wait
7669 			 * and doesn't care about errors.
7670 			 */
7671 			mutex_enter(ST_MUTEX);
7672 			return (0);
7673 		}
7674 
7675 		/*
7676 		 * BugTraq #4260046
7677 		 * ----------------
7678 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7679 		 * unconditionally. The old comment said...
7680 		 *
7681 		 * "if strategy was flagged with  persistent errors, we would
7682 		 *  have an error here, and the bp would never be sent, so we
7683 		 *  don't want to wait on a bp that was never sent...or hang"
7684 		 *
7685 		 * The new rationale, courtesy of Chitrank...
7686 		 *
7687 		 * "we should unconditionally biowait() here because
7688 		 *  st_strategy() will do a biodone() in the persistent error
7689 		 *  case and the following biowait() will return immediately.
7690 		 *  If not, in the case of "errors after pkt alloc" in
7691 		 *  st_start(), we will not biowait here which will cause the
7692 		 *  next biowait() to return immediately which will cause
7693 		 *  us to send out the next command. In the case where both of
7694 		 *  these use the sbuf, when the first command completes we'll
7695 		 *  free the packet attached to sbuf and the same pkt will
7696 		 *  get freed again when we complete the second command.
7697 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7698 		 *  st_start() for the pkt alloc failure case because physio()
7699 		 *  does biowait() and will hang if we don't do biodone()"
7700 		 */
7701 
7702 		err = biowait(bp);
7703 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7704 		    "st_setup_cmd: biowait returns %d\n", err);
7705 	}
7706 
7707 	mutex_enter(ST_MUTEX);
7708 
7709 	return (err);
7710 }
7711 
7712 static int
7713 st_set_compression(struct scsi_tape *un)
7714 {
7715 	int rval;
7716 	int turn_compression_on;
7717 	minor_t minor;
7718 
7719 	ST_FUNC(ST_DEVINFO, st_set_compression);
7720 
7721 	/*
7722 	 * Drive either dosn't have compression or it is controlled with
7723 	 * special density codes. Return ENOTTY so caller
7724 	 * knows nothing was done.
7725 	 */
7726 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7727 		un->un_comp_page = 0;
7728 		return (ENOTTY);
7729 	}
7730 
7731 	/* set compression based on minor node opened */
7732 	minor = MT_DENSITY(un->un_dev);
7733 
7734 	/*
7735 	 * If this the compression density or
7736 	 * the drive has two densities and uses mode select for
7737 	 * control of compression turn on compression for MT_DENSITY2
7738 	 * as well.
7739 	 */
7740 	if ((minor == ST_COMPRESSION_DENSITY) ||
7741 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7742 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7743 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7744 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7745 
7746 		turn_compression_on = 1;
7747 	} else {
7748 		turn_compression_on = 0;
7749 	}
7750 
7751 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7752 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7753 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7754 
7755 	/*
7756 	 * Need to determine which page does the device use for compression.
7757 	 * First try the data compression page. If this fails try the device
7758 	 * configuration page
7759 	 */
7760 
7761 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7762 		rval = st_set_datacomp_page(un, turn_compression_on);
7763 		if (rval == EALREADY) {
7764 			return (rval);
7765 		}
7766 		if (rval != 0) {
7767 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7768 				/*
7769 				 * This device does not support data
7770 				 * compression page
7771 				 */
7772 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7773 			} else if (un->un_state >= ST_STATE_OPEN) {
7774 				un->un_pos.pmode = invalid;
7775 				rval = EIO;
7776 			} else {
7777 				rval = -1;
7778 			}
7779 		} else {
7780 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7781 		}
7782 	}
7783 
7784 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7785 		rval = st_set_devconfig_page(un, turn_compression_on);
7786 		if (rval == EALREADY) {
7787 			return (rval);
7788 		}
7789 		if (rval != 0) {
7790 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7791 				/*
7792 				 * This device does not support
7793 				 * compression at all advice the
7794 				 * user and unset ST_MODE_SEL_COMP
7795 				 */
7796 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7797 				un->un_comp_page = 0;
7798 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7799 				    "Device Does Not Support Compression\n");
7800 			} else if (un->un_state >= ST_STATE_OPEN) {
7801 				un->un_pos.pmode = invalid;
7802 				rval = EIO;
7803 			} else {
7804 				rval = -1;
7805 			}
7806 		}
7807 	}
7808 
7809 	return (rval);
7810 }
7811 
7812 /*
7813  * set or unset compression thru device configuration page.
7814  */
7815 static int
7816 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
7817 {
7818 	unsigned char cflag;
7819 	int rval = 0;
7820 
7821 
7822 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
7823 
7824 	ASSERT(mutex_owned(ST_MUTEX));
7825 	/*
7826 	 * Figure what to set compression flag to.
7827 	 */
7828 	if (compression_on) {
7829 		/* They have selected a compression node */
7830 		if (un->un_dp->type == ST_TYPE_FUJI) {
7831 			cflag = 0x84;   /* use EDRC */
7832 		} else {
7833 			cflag = ST_DEV_CONFIG_DEF_COMP;
7834 		}
7835 	} else {
7836 		cflag = ST_DEV_CONFIG_NO_COMP;
7837 	}
7838 
7839 	/*
7840 	 * If compression is already set the way it was requested.
7841 	 * And if this not the first time we has tried.
7842 	 */
7843 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
7844 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7845 		return (EALREADY);
7846 	}
7847 
7848 	un->un_mspl->page.dev.comp_alg = cflag;
7849 	/*
7850 	 * need to send mode select even if correct compression is
7851 	 * already set since need to set density code
7852 	 */
7853 
7854 #ifdef STDEBUG
7855 	if ((st_debug & 0x7) >= 6) {
7856 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7857 		    "st_set_devconfig_page: sense data for mode select",
7858 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7859 	}
7860 #endif
7861 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
7862 	    sizeof (struct seq_mode));
7863 
7864 	return (rval);
7865 }
7866 
7867 /*
7868  * set/reset compression bit thru data compression page
7869  */
7870 static int
7871 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
7872 {
7873 	int compression_on_already;
7874 	int rval = 0;
7875 
7876 
7877 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
7878 
7879 	ASSERT(mutex_owned(ST_MUTEX));
7880 	/*
7881 	 * If drive is not capable of compression (at this time)
7882 	 * return EALREADY so caller doesn't think that this page
7883 	 * is not supported. This check is for drives that can
7884 	 * disable compression from the front panel or configuration.
7885 	 * I doubt that a drive that supports this page is not really
7886 	 * capable of compression.
7887 	 */
7888 	if (un->un_mspl->page.comp.dcc == 0) {
7889 		return (EALREADY);
7890 	}
7891 
7892 	/* See if compression currently turned on */
7893 	if (un->un_mspl->page.comp.dce) {
7894 		compression_on_already = 1;
7895 	} else {
7896 		compression_on_already = 0;
7897 	}
7898 
7899 	/*
7900 	 * If compression is already set the way it was requested.
7901 	 * And if this not the first time we has tried.
7902 	 */
7903 	if ((compression_on == compression_on_already) &&
7904 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7905 		return (EALREADY);
7906 	}
7907 
7908 	/*
7909 	 * if we are already set to the appropriate compression
7910 	 * mode, don't set it again
7911 	 */
7912 	if (compression_on) {
7913 		/* compression selected */
7914 		un->un_mspl->page.comp.dce = 1;
7915 	} else {
7916 		un->un_mspl->page.comp.dce = 0;
7917 	}
7918 
7919 
7920 #ifdef STDEBUG
7921 	if ((st_debug & 0x7) >= 6) {
7922 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7923 		    "st_set_datacomp_page: sense data for mode select",
7924 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7925 	}
7926 #endif
7927 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
7928 	    sizeof (struct seq_mode));
7929 
7930 	return (rval);
7931 }
7932 
7933 static int
7934 st_modesense(struct scsi_tape *un)
7935 {
7936 	int rval;
7937 	uchar_t page;
7938 
7939 	ST_FUNC(ST_DEVINFO, st_modesense);
7940 
7941 	page = un->un_comp_page;
7942 
7943 	switch (page) {
7944 	case ST_DEV_DATACOMP_PAGE:
7945 	case ST_DEV_CONFIG_PAGE: /* FALLTHROUGH */
7946 		rval = st_gen_mode_sense(un, st_uscsi_cmd, page, un->un_mspl,
7947 		    sizeof (struct seq_mode));
7948 		break;
7949 
7950 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
7951 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
7952 			page = ST_DEV_CONFIG_PAGE;
7953 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
7954 			    un->un_mspl, sizeof (struct seq_mode));
7955 			if (rval == 0 && un->un_mspl->page_code == page) {
7956 				un->un_comp_page = page;
7957 				break;
7958 			}
7959 			page = ST_DEV_DATACOMP_PAGE;
7960 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
7961 			    un->un_mspl, sizeof (struct seq_mode));
7962 			if (rval == 0 && un->un_mspl->page_code == page) {
7963 				un->un_comp_page = page;
7964 				break;
7965 			}
7966 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
7967 			un->un_comp_page = 0;
7968 		} else {
7969 			un->un_comp_page = 0;
7970 		}
7971 
7972 	default:	/* FALLTHROUGH */
7973 		rval = st_cmd(un, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
7974 	}
7975 	return (rval);
7976 }
7977 
7978 static int
7979 st_modeselect(struct scsi_tape *un)
7980 {
7981 	int rval = 0;
7982 	int ix;
7983 
7984 	ST_FUNC(ST_DEVINFO, st_modeselect);
7985 
7986 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7987 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
7988 	    un->un_dev, un->un_mspl->density);
7989 
7990 	ASSERT(mutex_owned(ST_MUTEX));
7991 
7992 	/*
7993 	 * The parameter list should be the same for all of the
7994 	 * cases that follow so set them here
7995 	 *
7996 	 * Try mode select first if if fails set fields manually
7997 	 */
7998 	rval = st_modesense(un);
7999 	if (rval != 0) {
8000 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8001 		    "st_modeselect: First mode sense failed\n");
8002 		un->un_mspl->bd_len  = 8;
8003 		un->un_mspl->high_nb = 0;
8004 		un->un_mspl->mid_nb  = 0;
8005 		un->un_mspl->low_nb  = 0;
8006 	}
8007 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
8008 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
8009 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
8010 
8011 
8012 	/*
8013 	 * If configured to use a specific density code for a media type.
8014 	 * curdens is previously set by the minor node opened.
8015 	 * If the media type doesn't match the minor node we change it so it
8016 	 * looks like the correct one was opened.
8017 	 */
8018 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
8019 		uchar_t best;
8020 
8021 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
8022 			if (un->un_mspl->media_type ==
8023 			    un->un_dp->mediatype[ix]) {
8024 				best = ix;
8025 				/*
8026 				 * It matches but it might not be the only one.
8027 				 * Use the highest matching media type but not
8028 				 * to exceed the density selected by the open.
8029 				 */
8030 				if (ix < un->un_curdens) {
8031 					continue;
8032 				}
8033 				un->un_curdens = ix;
8034 				break;
8035 			}
8036 		}
8037 		/* If a match was found best will not be 0xff any more */
8038 		if (best < NDENSITIES) {
8039 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8040 			    "found media 0x%X using density 0x%X\n",
8041 			    un->un_mspl->media_type,
8042 			    un->un_dp->densities[best]);
8043 			un->un_mspl->density = un->un_dp->densities[best];
8044 		} else {
8045 			/* Otherwise set density based on minor node opened */
8046 			un->un_mspl->density =
8047 			    un->un_dp->densities[un->un_curdens];
8048 		}
8049 	} else {
8050 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
8051 	}
8052 
8053 	if (un->un_dp->options & ST_NOBUF) {
8054 		un->un_mspl->bufm = 0;
8055 	} else {
8056 		un->un_mspl->bufm = 1;
8057 	}
8058 
8059 	rval = st_set_compression(un);
8060 
8061 	/*
8062 	 * If st_set_compression returned invalid or already it
8063 	 * found no need to do the mode select.
8064 	 * So do it here.
8065 	 */
8066 	if ((rval == ENOTTY) || (rval == EALREADY)) {
8067 
8068 		/* Zero non-writeable fields */
8069 		un->un_mspl->data_len = 0;
8070 		un->un_mspl->media_type = 0;
8071 		un->un_mspl->wp = 0;
8072 
8073 		/* need to set the density code */
8074 		rval = st_cmd(un, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
8075 		if (rval != 0) {
8076 			if (un->un_state >= ST_STATE_OPEN) {
8077 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8078 				    "unable to set tape mode\n");
8079 				un->un_pos.pmode = invalid;
8080 				rval = EIO;
8081 			} else {
8082 				rval = -1;
8083 			}
8084 		}
8085 	}
8086 
8087 	/*
8088 	 * The spec recommends to send a mode sense after a mode select
8089 	 */
8090 	(void) st_modesense(un);
8091 
8092 	ASSERT(mutex_owned(ST_MUTEX));
8093 
8094 	return (rval);
8095 }
8096 
8097 /*
8098  * st_gen_mode_sense
8099  *
8100  * generic mode sense.. it allows for any page
8101  */
8102 static int
8103 st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
8104     struct seq_mode *page_data, int page_size)
8105 {
8106 
8107 	int r;
8108 	char	cdb[CDB_GROUP0];
8109 	struct uscsi_cmd *com;
8110 
8111 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
8112 
8113 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8114 
8115 	bzero(cdb, CDB_GROUP0);
8116 	cdb[0] = SCMD_MODE_SENSE;
8117 	cdb[2] = (char)page;
8118 	cdb[4] = (char)page_size;
8119 
8120 	com->uscsi_cdb = cdb;
8121 	com->uscsi_cdblen = CDB_GROUP0;
8122 	com->uscsi_bufaddr = (caddr_t)page_data;
8123 	com->uscsi_buflen = page_size;
8124 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8125 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8126 
8127 	r = ubf(un, com, FKIOCTL);
8128 	kmem_free(com, sizeof (*com));
8129 	return (r);
8130 }
8131 
8132 /*
8133  * st_gen_mode_select
8134  *
8135  * generic mode select.. it allows for any page
8136  */
8137 static int
8138 st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
8139     struct seq_mode *page_data, int page_size)
8140 {
8141 
8142 	int r;
8143 	char cdb[CDB_GROUP0];
8144 	struct uscsi_cmd *com;
8145 
8146 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
8147 
8148 	/* Zero non-writeable fields */
8149 	page_data->data_len = 0;
8150 	page_data->media_type = 0;
8151 	page_data->wp = 0;
8152 
8153 	/*
8154 	 * If mode select has any page data, zero the ps (Page Savable) bit.
8155 	 */
8156 	if (page_size > MSIZE) {
8157 		page_data->ps = 0;
8158 	}
8159 
8160 
8161 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8162 
8163 	/*
8164 	 * then, do a mode select to set what ever info
8165 	 */
8166 	bzero(cdb, CDB_GROUP0);
8167 	cdb[0] = SCMD_MODE_SELECT;
8168 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
8169 	cdb[4] = (char)page_size;
8170 
8171 	com->uscsi_cdb = cdb;
8172 	com->uscsi_cdblen = CDB_GROUP0;
8173 	com->uscsi_bufaddr = (caddr_t)page_data;
8174 	com->uscsi_buflen = page_size;
8175 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8176 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_WRITE;
8177 
8178 	r = ubf(un, com, FKIOCTL);
8179 
8180 	kmem_free(com, sizeof (*com));
8181 	return (r);
8182 }
8183 
8184 static int
8185 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
8186 {
8187 	int rval;
8188 	char cdb[CDB_GROUP0];
8189 	struct uscsi_cmd *com;
8190 
8191 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
8192 
8193 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8194 
8195 	bzero(cdb, CDB_GROUP0);
8196 	cdb[0] = SCMD_READ_BLKLIM;
8197 
8198 	com->uscsi_cdb = cdb;
8199 	com->uscsi_cdblen = CDB_GROUP0;
8200 	com->uscsi_bufaddr = (caddr_t)read_blk;
8201 	com->uscsi_buflen = sizeof (struct read_blklim);
8202 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8203 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8204 
8205 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8206 	if (com->uscsi_status || com->uscsi_resid) {
8207 		rval = -1;
8208 	}
8209 
8210 	kmem_free(com, sizeof (*com));
8211 	return (rval);
8212 }
8213 
8214 static int
8215 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
8216     size_t buflen)
8217 {
8218 	int rval;
8219 	char cdb[CDB_GROUP1];
8220 	struct uscsi_cmd *com;
8221 
8222 	ST_FUNC(ST_DEVINFO, st_report_density_support);
8223 
8224 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8225 
8226 	bzero(cdb, CDB_GROUP1);
8227 	cdb[0] = SCMD_REPORT_DENSITIES;
8228 	cdb[7] = (buflen & 0xff00) >> 8;
8229 	cdb[8] = buflen & 0xff;
8230 
8231 	com->uscsi_cdb = cdb;
8232 	com->uscsi_cdblen = CDB_GROUP1;
8233 	com->uscsi_bufaddr = (caddr_t)density_data;
8234 	com->uscsi_buflen = buflen;
8235 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8236 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8237 
8238 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8239 	if (com->uscsi_status || com->uscsi_resid) {
8240 		rval = -1;
8241 	}
8242 
8243 	kmem_free(com, sizeof (*com));
8244 	return (rval);
8245 }
8246 
8247 static int
8248 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
8249     uchar_t option_code, ushort_t service_action)
8250 {
8251 	int rval;
8252 	char cdb[CDB_GROUP5];
8253 	struct uscsi_cmd *com;
8254 	uint32_t allo_length;
8255 
8256 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
8257 
8258 	allo_length = sizeof (struct one_com_des) +
8259 	    sizeof (struct com_timeout_des);
8260 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8261 
8262 	bzero(cdb, CDB_GROUP5);
8263 	cdb[0] = (char)SCMD_MAINTENANCE_IN;
8264 	cdb[1] = 0x0c; /* service action */
8265 	if (service_action) {
8266 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
8267 		cdb[4] = (service_action & 0xff00) >> 8;
8268 		cdb[5] = service_action & 0xff;
8269 	} else {
8270 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
8271 		    0x80); /* RCTD */
8272 	}
8273 	cdb[3] = option_code;
8274 	cdb[6] = (allo_length & 0xff000000) >> 24;
8275 	cdb[7] = (allo_length & 0xff0000) >> 16;
8276 	cdb[8] = (allo_length & 0xff00) >> 8;
8277 	cdb[9] = allo_length & 0xff;
8278 
8279 	com->uscsi_cdb = cdb;
8280 	com->uscsi_cdblen = CDB_GROUP5;
8281 	com->uscsi_bufaddr = (caddr_t)oper_data;
8282 	com->uscsi_buflen = allo_length;
8283 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8284 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8285 
8286 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8287 	if (com->uscsi_status) {
8288 		rval = -1;
8289 	}
8290 
8291 	kmem_free(com, sizeof (*com));
8292 	return (rval);
8293 }
8294 
8295 /*
8296  * Changes devices blocksize and bsize to requested blocksize nblksz.
8297  * Returns returned value from first failed call or zero on success.
8298  */
8299 static int
8300 st_change_block_size(struct scsi_tape *un, uint32_t nblksz)
8301 {
8302 	struct seq_mode *current;
8303 	int rval;
8304 	uint32_t oldblksz;
8305 
8306 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8307 
8308 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8309 
8310 	current = kmem_zalloc(MSIZE, KM_SLEEP);
8311 
8312 	/*
8313 	 * If we haven't got the compression page yet, do that first.
8314 	 */
8315 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
8316 		(void) st_modesense(un);
8317 	}
8318 
8319 	/* Read current settings */
8320 	rval = st_gen_mode_sense(un, st_uscsi_cmd, 0, current, MSIZE);
8321 	if (rval != 0) {
8322 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8323 		    "mode sense for change block size failed: rval = %d", rval);
8324 		goto finish;
8325 	}
8326 
8327 	/* Figure the current block size */
8328 	oldblksz =
8329 	    (current->high_bl << 16) |
8330 	    (current->mid_bl << 8) |
8331 	    (current->low_bl);
8332 
8333 	/* If current block size is the same as requested were done */
8334 	if (oldblksz == nblksz) {
8335 		un->un_bsize = nblksz;
8336 		rval = 0;
8337 		goto finish;
8338 	}
8339 
8340 	/* Change to requested block size */
8341 	current->high_bl = (uchar_t)(nblksz >> 16);
8342 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8343 	current->low_bl  = (uchar_t)(nblksz);
8344 
8345 	/* Attempt to change block size */
8346 	rval = st_gen_mode_select(un, st_uscsi_cmd, current, MSIZE);
8347 	if (rval != 0) {
8348 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8349 		    "Set new block size failed: rval = %d", rval);
8350 		goto finish;
8351 	}
8352 
8353 	/* Read back and verify setting */
8354 	rval = st_modesense(un);
8355 	if (rval == 0) {
8356 		un->un_bsize =
8357 		    (un->un_mspl->high_bl << 16) |
8358 		    (un->un_mspl->mid_bl << 8) |
8359 		    (un->un_mspl->low_bl);
8360 
8361 		if (un->un_bsize != nblksz) {
8362 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8363 			    "Blocksize set does not equal requested blocksize"
8364 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8365 			rval = EIO;
8366 		}
8367 	}
8368 finish:
8369 	kmem_free(current, MSIZE);
8370 	return (rval);
8371 }
8372 
8373 
8374 static void
8375 st_init(struct scsi_tape *un)
8376 {
8377 	ST_FUNC(ST_DEVINFO, st_init);
8378 
8379 	ASSERT(mutex_owned(ST_MUTEX));
8380 
8381 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8382 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8383 	    un->un_dev);
8384 
8385 	un->un_pos.blkno = 0;
8386 	un->un_pos.fileno = 0;
8387 	un->un_lastop = ST_OP_NIL;
8388 	un->un_pos.eof = ST_NO_EOF;
8389 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8390 	if (st_error_level != SCSI_ERR_ALL) {
8391 		if (DEBUGGING) {
8392 			st_error_level = SCSI_ERR_ALL;
8393 		} else {
8394 			st_error_level = SCSI_ERR_RETRYABLE;
8395 		}
8396 	}
8397 }
8398 
8399 
8400 static void
8401 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8402 {
8403 	struct scsi_pkt *pkt;
8404 	struct uscsi_cmd *ucmd;
8405 	recov_info *ri;
8406 	int tval = 0;
8407 	uint64_t count;
8408 	uint32_t additional;
8409 	int flags = 0;
8410 	int cdb_len = CDB_GROUP0; /* default */
8411 	uchar_t com;
8412 	char fixbit;
8413 	char short_fm = 0;
8414 	int stat_size =
8415 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
8416 
8417 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8418 
8419 	ASSERT(mutex_owned(ST_MUTEX));
8420 
8421 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8422 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8423 
8424 
8425 	/*
8426 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8427 	 * Length Indicator bits on read/write commands, for setting
8428 	 * the Long bit on erase commands, and for setting the Code
8429 	 * Field bits on space commands.
8430 	 */
8431 
8432 	/* regular raw I/O */
8433 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
8434 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8435 		    CDB_GROUP0, stat_size, st_recov_sz, 0, func,
8436 		    (caddr_t)un);
8437 		if (pkt == NULL) {
8438 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8439 			    "Read Write scsi_init_pkt() failure\n");
8440 			goto exit;
8441 		}
8442 		ASSERT(pkt->pkt_resid == 0);
8443 #ifdef STDEBUG
8444 		bzero(pkt->pkt_private, st_recov_sz);
8445 		bzero(pkt->pkt_scbp, stat_size);
8446 #endif
8447 		ri = (recov_info *)pkt->pkt_private;
8448 		ri->privatelen = st_recov_sz;
8449 		if (un->un_bsize == 0) {
8450 			count = bp->b_bcount;
8451 			fixbit = 0;
8452 		} else {
8453 			count = bp->b_bcount / un->un_bsize;
8454 			fixbit = 1;
8455 		}
8456 		if (bp->b_flags & B_READ) {
8457 			com = SCMD_READ;
8458 			un->un_lastop = ST_OP_READ;
8459 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8460 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8461 				fixbit = 2;
8462 			}
8463 		} else {
8464 			com = SCMD_WRITE;
8465 			un->un_lastop = ST_OP_WRITE;
8466 		}
8467 		tval = un->un_dp->io_timeout;
8468 
8469 		/*
8470 		 * For really large xfers, increase timeout
8471 		 */
8472 		if (bp->b_bcount > (10 * ONE_MEG))
8473 			tval *= bp->b_bcount/(10 * ONE_MEG);
8474 
8475 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8476 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8477 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8478 
8479 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8480 		/*
8481 		 * uscsi - build command, allocate scsi resources
8482 		 */
8483 		st_make_uscsi_cmd(un, ucmd, bp, func);
8484 		goto exit;
8485 
8486 	} else {				/* special I/O */
8487 		int stat_size = (un->un_arq_enabled ?
8488 		    sizeof (struct scsi_arq_status) : 1);
8489 		struct buf *allocbp = NULL;
8490 		com = (uchar_t)(uintptr_t)bp->b_forw;
8491 		count = bp->b_bcount;
8492 
8493 		switch (com) {
8494 		case SCMD_READ:
8495 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8496 			    "special read %"PRId64"\n", count);
8497 			if (un->un_bsize == 0) {
8498 				fixbit = 2;	/* suppress SILI */
8499 			} else {
8500 				fixbit = 1;	/* Fixed Block Mode */
8501 				count /= un->un_bsize;
8502 			}
8503 			allocbp = bp;
8504 			un->un_lastop = ST_OP_READ;
8505 			tval = un->un_dp->io_timeout;
8506 			break;
8507 
8508 		case SCMD_WRITE:
8509 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8510 			    "special write %"PRId64"\n", count);
8511 			if (un->un_bsize != 0) {
8512 				fixbit = 1;	/* Fixed Block Mode */
8513 				count /= un->un_bsize;
8514 			} else {
8515 				fixbit = 0;
8516 			}
8517 			allocbp = bp;
8518 			un->un_lastop = ST_OP_WRITE;
8519 			tval = un->un_dp->io_timeout;
8520 			break;
8521 
8522 		case SCMD_WRITE_FILE_MARK:
8523 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8524 			    "write %"PRId64" file marks\n", count);
8525 			un->un_lastop = ST_OP_WEOF;
8526 			fixbit = 0;
8527 			tval = un->un_dp->io_timeout;
8528 			/*
8529 			 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8530 			 * device, set the Vendor Unique bit to
8531 			 * write Short File Mark.
8532 			 */
8533 			if ((un->un_dp->options & ST_SHORT_FILEMARKS) &&
8534 			    ((un->un_dp->type == ST_TYPE_EXB8500) ||
8535 			    (un->un_dp->type == ST_TYPE_EXABYTE))) {
8536 				/*
8537 				 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8538 				 * is set to to write Short File Mark
8539 				 */
8540 				short_fm = 1;
8541 			}
8542 			break;
8543 
8544 		case SCMD_REWIND:
8545 			/*
8546 			 * In the case of rewind we're gona do the rewind with
8547 			 * the immediate bit set so status will be retured when
8548 			 * the command is accepted by the device. We clear the
8549 			 * B_ASYNC flag so we wait for that acceptance.
8550 			 */
8551 			if (bp->b_flags & B_ASYNC) {
8552 				allocbp = bp;
8553 				if (count) {
8554 					fixbit = 1;
8555 					bp->b_flags &= ~B_ASYNC;
8556 				}
8557 			} else {
8558 				fixbit = 0;
8559 			}
8560 			count = 0;
8561 			bp->b_bcount = 0;
8562 			un->un_lastop = ST_OP_CTL;
8563 			tval = un->un_dp->rewind_timeout;
8564 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8565 			    "rewind\n");
8566 			break;
8567 
8568 		case SCMD_SPACE_G4:
8569 			cdb_len = CDB_GROUP4;
8570 		case SCMD_SPACE: /* FALL THROUGH */
8571 			fixbit = SPACE_TYPE(bp->b_bcount);
8572 			count = SPACE_CNT(bp->b_bcount);
8573 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8574 			    " %s space %s %"PRId64" from file %d blk %d\n",
8575 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8576 			    space_strs[fixbit & 7], count,
8577 			    un->un_pos.fileno, un->un_pos.blkno);
8578 			additional = count >> 32;
8579 			count &= 0xffffffff;
8580 			un->un_lastop = ST_OP_CTL;
8581 			tval = un->un_dp->space_timeout;
8582 			break;
8583 
8584 		case SCMD_LOAD:
8585 			ASSERT(count < 10);
8586 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8587 			    "%s tape\n", load_strs[count]);
8588 			fixbit = 0;
8589 
8590 			/* Loading or Unloading */
8591 			if (count & LD_LOAD) {
8592 				tval = un->un_dp->load_timeout;
8593 			} else {
8594 				tval = un->un_dp->unload_timeout;
8595 			}
8596 			/* Is Retension requested */
8597 			if (count & LD_RETEN) {
8598 				tval += un->un_dp->rewind_timeout;
8599 			}
8600 			un->un_lastop = ST_OP_CTL;
8601 			break;
8602 
8603 		case SCMD_ERASE:
8604 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8605 			    "erase tape\n");
8606 			ASSERT(count == 1); /* mt sets this */
8607 			if (count == 1) {
8608 				/*
8609 				 * do long erase
8610 				 */
8611 				fixbit = 1; /* Long */
8612 
8613 				/* Drive might not honor immidiate bit */
8614 				tval = un->un_dp->erase_timeout;
8615 			} else {
8616 				/* Short Erase */
8617 				tval = un->un_dp->erase_timeout;
8618 				fixbit = 0;
8619 			}
8620 			un->un_lastop = ST_OP_CTL;
8621 			count = 0;
8622 			break;
8623 
8624 		case SCMD_MODE_SENSE:
8625 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8626 			    "mode sense\n");
8627 			allocbp = bp;
8628 			fixbit = 0;
8629 			tval = un->un_dp->non_motion_timeout;
8630 			un->un_lastop = ST_OP_CTL;
8631 			break;
8632 
8633 		case SCMD_MODE_SELECT:
8634 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8635 			    "mode select\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_RESERVE:
8643 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8644 			    "reserve\n");
8645 			fixbit = 0;
8646 			tval = un->un_dp->non_motion_timeout;
8647 			un->un_lastop = ST_OP_CTL;
8648 			break;
8649 
8650 		case SCMD_RELEASE:
8651 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8652 			    "release\n");
8653 			fixbit = 0;
8654 			tval = un->un_dp->non_motion_timeout;
8655 			un->un_lastop = ST_OP_CTL;
8656 			break;
8657 
8658 		case SCMD_READ_BLKLIM:
8659 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8660 			    "read block limits\n");
8661 			allocbp = bp;
8662 			fixbit = count = 0;
8663 			tval = un->un_dp->non_motion_timeout;
8664 			un->un_lastop = ST_OP_CTL;
8665 			break;
8666 
8667 		case SCMD_TEST_UNIT_READY:
8668 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8669 			    "test unit ready\n");
8670 			fixbit = 0;
8671 			tval = un->un_dp->non_motion_timeout;
8672 			un->un_lastop = ST_OP_CTL;
8673 			break;
8674 
8675 		case SCMD_DOORLOCK:
8676 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8677 			    "prevent/allow media removal\n");
8678 			fixbit = 0;
8679 			tval = un->un_dp->non_motion_timeout;
8680 			un->un_lastop = ST_OP_CTL;
8681 			break;
8682 
8683 		case SCMD_READ_POSITION:
8684 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8685 			    "read position\n");
8686 			fixbit = un->un_read_pos_type;
8687 			cdb_len = CDB_GROUP1;
8688 			tval = un->un_dp->non_motion_timeout;
8689 			allocbp = bp;
8690 			un->un_lastop = ST_OP_CTL;
8691 			switch (un->un_read_pos_type) {
8692 			case LONG_POS:
8693 				count = 0;
8694 				break;
8695 			case EXT_POS:
8696 				count = sizeof (tape_position_ext_t);
8697 				break;
8698 			case SHORT_POS:
8699 				count = 0;
8700 				break;
8701 			default:
8702 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8703 				    "Unknown read position type 0x%x in "
8704 				    " st_make_cmd()\n", un->un_read_pos_type);
8705 			}
8706 			break;
8707 
8708 		default:
8709 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8710 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8711 			    com);
8712 		}
8713 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8714 		    st_recov_sz, 0, func, (caddr_t)un);
8715 		if (pkt == NULL) {
8716 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8717 			    "generic command scsi_init_pkt() failure\n");
8718 			goto exit;
8719 		}
8720 
8721 		ASSERT(pkt->pkt_resid == 0);
8722 #ifdef STDEBUG
8723 		bzero(pkt->pkt_private, st_recov_sz);
8724 		bzero(pkt->pkt_scbp, stat_size);
8725 #endif
8726 		ri = (recov_info *)pkt->pkt_private;
8727 		ri->privatelen = st_recov_sz;
8728 		if (allocbp) {
8729 			ASSERT(geterror(allocbp) == 0);
8730 		}
8731 
8732 	}
8733 
8734 
8735 	(void) scsi_setup_cdb((union scsi_cdb *)pkt->pkt_cdbp,
8736 	    com, 0, (uint_t)count, additional);
8737 	FILL_SCSI1_LUN(un->un_sd, pkt);
8738 	/*
8739 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8740 	 */
8741 	((union scsi_cdb *)(pkt->pkt_cdbp))->t_code = fixbit;
8742 	((union scsi_cdb *)pkt->pkt_cdbp)->g0_vu_1 = short_fm;
8743 	pkt->pkt_flags = flags;
8744 
8745 	ASSERT(tval);
8746 	pkt->pkt_time = tval;
8747 	if (bp == un->un_recov_buf) {
8748 		pkt->pkt_comp = st_recov_cb;
8749 	} else {
8750 		pkt->pkt_comp = st_intr;
8751 	}
8752 
8753 	st_add_recovery_info_to_pkt(un, bp, pkt);
8754 
8755 exit:
8756 	ASSERT(mutex_owned(ST_MUTEX));
8757 }
8758 
8759 
8760 /*
8761  * Build a command based on a uscsi command;
8762  */
8763 static void
8764 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
8765     struct buf *bp, int (*func)(caddr_t))
8766 {
8767 	struct scsi_pkt *pkt;
8768 	recov_info *ri;
8769 	caddr_t cdb;
8770 	int	cdblen;
8771 	int	stat_size = 1;
8772 	int	flags = 0;
8773 
8774 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
8775 
8776 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8777 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
8778 
8779 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
8780 		if (un->un_arq_enabled) {
8781 			if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
8782 				stat_size = (int)(ucmd->uscsi_rqlen) +
8783 				    sizeof (struct scsi_arq_status) -
8784 				    sizeof (struct scsi_extended_sense);
8785 				flags = PKT_XARQ;
8786 			} else {
8787 				stat_size = sizeof (struct scsi_arq_status);
8788 			}
8789 		}
8790 	}
8791 
8792 	ASSERT(mutex_owned(ST_MUTEX));
8793 
8794 	cdb = ucmd->uscsi_cdb;
8795 	cdblen = ucmd->uscsi_cdblen;
8796 
8797 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8798 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
8799 	    ucmd->uscsi_buflen, bp->b_bcount);
8800 	pkt = scsi_init_pkt(ROUTE, NULL,
8801 	    (bp->b_bcount > 0) ? bp : NULL,
8802 	    cdblen, stat_size, st_recov_sz, flags, func, (caddr_t)un);
8803 	if (pkt == NULL) {
8804 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8805 		    "uscsi command scsi_init_pkt() failure\n");
8806 		goto exit;
8807 	}
8808 
8809 	ASSERT(pkt->pkt_resid == 0);
8810 #ifdef STDEBUG
8811 	bzero(pkt->pkt_private, st_recov_sz);
8812 	bzero(pkt->pkt_scbp, stat_size);
8813 #endif
8814 	ri = (recov_info *)pkt->pkt_private;
8815 	ri->privatelen = st_recov_sz;
8816 
8817 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
8818 
8819 #ifdef STDEBUG
8820 	if ((st_debug & 0x7) >= 6) {
8821 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8822 		    "pkt_cdbp", (char *)cdb, cdblen);
8823 	}
8824 #endif
8825 
8826 	if (ucmd->uscsi_flags & USCSI_SILENT) {
8827 		pkt->pkt_flags |= FLAG_SILENT;
8828 	}
8829 
8830 	pkt->pkt_time = ucmd->uscsi_timeout;
8831 	if (bp == un->un_recov_buf) {
8832 		pkt->pkt_comp = st_recov_cb;
8833 	} else {
8834 		pkt->pkt_comp = st_intr;
8835 	}
8836 	st_add_recovery_info_to_pkt(un, bp, pkt);
8837 exit:
8838 	ASSERT(mutex_owned(ST_MUTEX));
8839 }
8840 
8841 
8842 /*
8843  * restart cmd currently at the head of the runq
8844  *
8845  * If scsi_transport() succeeds or the retries
8846  * count exhausted, restore the throttle that was
8847  * zeroed out in st_handle_intr_busy().
8848  *
8849  */
8850 static void
8851 st_intr_restart(void *arg)
8852 {
8853 	struct scsi_tape *un = arg;
8854 	struct buf *bp;
8855 	int queued;
8856 	int status = TRAN_ACCEPT;
8857 
8858 	mutex_enter(ST_MUTEX);
8859 
8860 	ST_FUNC(ST_DEVINFO, st_intr_restart);
8861 
8862 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8863 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
8864 
8865 	un->un_hib_tid = 0;
8866 
8867 	if (un->un_recov_buf_busy != 0) {
8868 		bp = un->un_recov_buf;
8869 		queued = 0;
8870 	} else if (un->un_sbuf_busy != 0) {
8871 		bp = un->un_sbufp;
8872 		queued = 0;
8873 	} else if (un->un_quef != NULL) {
8874 		bp = un->un_quef;
8875 		queued = 1;
8876 	} else {
8877 		mutex_exit(ST_MUTEX);
8878 		return;
8879 	}
8880 
8881 	/*
8882 	 * Here we know :
8883 	 *	throttle = 0, via st_handle_intr_busy
8884 	 */
8885 
8886 	if (queued) {
8887 		/*
8888 		 * move from waitq to runq, if there is anything on the waitq
8889 		 */
8890 		(void) st_remove_from_queue(&un->un_quef, &un->un_quef, bp);
8891 
8892 		if (un->un_runqf) {
8893 			/*
8894 			 * not good, we don't want to requeue something after
8895 			 * another.
8896 			 */
8897 			mutex_exit(ST_MUTEX);
8898 			goto done_error;
8899 		} else {
8900 			un->un_runqf = bp;
8901 			un->un_runql = bp;
8902 		}
8903 	}
8904 
8905 	ST_CDB(ST_DEVINFO, "Interrupt restart CDB",
8906 	    (char *)BP_PKT(bp)->pkt_cdbp);
8907 
8908 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
8909 
8910 	status = st_transport(un, BP_PKT(bp));
8911 
8912 	if (status != TRAN_ACCEPT) {
8913 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8914 		mutex_exit(ST_MUTEX);
8915 
8916 		if (status == TRAN_BUSY) {
8917 			if (st_handle_intr_busy(un, bp,
8918 			    ST_TRAN_BUSY_TIMEOUT) == 0)
8919 				return;	/* timeout is setup again */
8920 		}
8921 
8922 	} else {
8923 		un->un_tran_retry_ct = 0;
8924 		if (un->un_last_throttle) {
8925 			un->un_throttle = un->un_last_throttle;
8926 		}
8927 		mutex_exit(ST_MUTEX);
8928 		return;
8929 	}
8930 
8931 done_error:
8932 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8933 	    "restart transport rejected\n");
8934 	bp->b_resid = bp->b_bcount;
8935 
8936 #ifndef __lock_lint
8937 	/*
8938 	 * warlock doesn't understand this potential
8939 	 * recursion?
8940 	 */
8941 	mutex_enter(ST_MUTEX);
8942 	if (un->un_last_throttle) {
8943 		un->un_throttle = un->un_last_throttle;
8944 	}
8945 	if (status != TRAN_ACCEPT)
8946 		ST_DO_ERRSTATS(un, st_transerrs);
8947 	ST_DO_KSTATS(bp, kstat_waitq_exit);
8948 	st_set_pe_flag(un);
8949 	st_bioerror(bp, EIO);
8950 	st_done_and_mutex_exit(un, bp);
8951 #endif
8952 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8953 	    "busy restart aborted\n");
8954 }
8955 
8956 /*
8957  * st_check_media():
8958  * Periodically check the media state using scsi_watch service;
8959  * this service calls back after TUR and possibly request sense
8960  * the callback handler (st_media_watch_cb()) decodes the request sense
8961  * data (if any)
8962  */
8963 
8964 static int
8965 st_check_media(dev_t dev, enum mtio_state state)
8966 {
8967 	int rval = 0;
8968 	enum mtio_state	prev_state;
8969 	opaque_t token = NULL;
8970 
8971 	GET_SOFT_STATE(dev);
8972 
8973 	ST_FUNC(ST_DEVINFO, st_check_media);
8974 
8975 	mutex_enter(ST_MUTEX);
8976 
8977 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8978 	    "st_check_media:state=%x, mediastate=%x\n",
8979 	    state, un->un_mediastate);
8980 
8981 	prev_state = un->un_mediastate;
8982 
8983 	/*
8984 	 * is there anything to do?
8985 	 */
8986 retry:
8987 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
8988 		/*
8989 		 * submit the request to the scsi_watch service;
8990 		 * scsi_media_watch_cb() does the real work
8991 		 */
8992 		mutex_exit(ST_MUTEX);
8993 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
8994 		    st_check_media_time, SENSE_LENGTH,
8995 		    st_media_watch_cb, (caddr_t)dev);
8996 		if (token == NULL) {
8997 			rval = EAGAIN;
8998 			goto done;
8999 		}
9000 		mutex_enter(ST_MUTEX);
9001 
9002 		un->un_swr_token = token;
9003 		un->un_specified_mediastate = state;
9004 
9005 		/*
9006 		 * now wait for media change
9007 		 * we will not be signalled unless mediastate == state but it
9008 		 * still better to test for this condition, since there
9009 		 * is a 5 sec cv_broadcast delay when
9010 		 *  mediastate == MTIO_INSERTED
9011 		 */
9012 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9013 		    "st_check_media:waiting for media state change\n");
9014 		while (un->un_mediastate == state) {
9015 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
9016 				mutex_exit(ST_MUTEX);
9017 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9018 				    "st_check_media:waiting for media state "
9019 				    "was interrupted\n");
9020 				rval = EINTR;
9021 				goto done;
9022 			}
9023 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9024 			    "st_check_media:received signal, state=%x\n",
9025 			    un->un_mediastate);
9026 		}
9027 	}
9028 
9029 	/*
9030 	 * if we transitioned to MTIO_INSERTED, media has really been
9031 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
9032 	 * Reset and retry the state change.  If everything is ok, replay
9033 	 * the open() logic.
9034 	 */
9035 	if ((un->un_mediastate == MTIO_INSERTED) &&
9036 	    (un->un_state == ST_STATE_OFFLINE)) {
9037 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9038 		    "st_check_media: calling st_cmd to confirm inserted\n");
9039 
9040 		/*
9041 		 * set this early so that TUR will make it through strategy
9042 		 * without triggering a st_tape_init().  We needed it set
9043 		 * before calling st_tape_init() ourselves anyway.  If TUR
9044 		 * fails, set it back
9045 		 */
9046 		un->un_state = ST_STATE_INITIALIZING;
9047 
9048 		/*
9049 		 * If not reserved fail as getting reservation conflict
9050 		 * will make this hang forever.
9051 		 */
9052 		if ((un->un_rsvd_status &
9053 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9054 			mutex_exit(ST_MUTEX);
9055 			rval = EACCES;
9056 			goto done;
9057 		}
9058 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
9059 		if (rval == EACCES) {
9060 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9061 			    "st_check_media: TUR got Reservation Conflict\n");
9062 			mutex_exit(ST_MUTEX);
9063 			goto done;
9064 		}
9065 		if (rval) {
9066 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9067 			    "st_check_media: TUR failed, going to retry\n");
9068 			un->un_mediastate = prev_state;
9069 			un->un_state = ST_STATE_OFFLINE;
9070 			goto retry;
9071 		}
9072 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9073 		    "st_check_media: media inserted\n");
9074 
9075 		/* this also rewinds the tape */
9076 		rval = st_tape_init(un);
9077 		if (rval != 0) {
9078 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9079 			    "st_check_media : OFFLINE init failure ");
9080 			un->un_state = ST_STATE_OFFLINE;
9081 			un->un_pos.pmode = invalid;
9082 		} else {
9083 			un->un_state = ST_STATE_OPEN_PENDING_IO;
9084 		}
9085 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
9086 	    (un->un_state != ST_STATE_OFFLINE)) {
9087 		/*
9088 		 * supported devices must be rewound before ejection
9089 		 * rewind resets fileno & blkno
9090 		 */
9091 		un->un_laststate = un->un_state;
9092 		un->un_state = ST_STATE_OFFLINE;
9093 	}
9094 	mutex_exit(ST_MUTEX);
9095 done:
9096 	if (token) {
9097 		(void) scsi_watch_request_terminate(token,
9098 		    SCSI_WATCH_TERMINATE_WAIT);
9099 		mutex_enter(ST_MUTEX);
9100 		un->un_swr_token = (opaque_t)NULL;
9101 		mutex_exit(ST_MUTEX);
9102 	}
9103 
9104 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
9105 
9106 	return (rval);
9107 }
9108 
9109 /*
9110  * st_media_watch_cb() is called by scsi_watch_thread for
9111  * verifying the request sense data (if any)
9112  */
9113 static int
9114 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
9115 {
9116 	struct scsi_status *statusp = resultp->statusp;
9117 	struct scsi_extended_sense *sensep = resultp->sensep;
9118 	uchar_t actual_sense_length = resultp->actual_sense_length;
9119 	struct scsi_tape *un;
9120 	enum mtio_state state = MTIO_NONE;
9121 	int instance;
9122 	dev_t dev = (dev_t)arg;
9123 
9124 	instance = MTUNIT(dev);
9125 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
9126 		return (-1);
9127 	}
9128 
9129 	mutex_enter(ST_MUTEX);
9130 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
9131 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9132 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
9133 	    *((char *)statusp), (void *)sensep,
9134 	    actual_sense_length);
9135 
9136 
9137 	/*
9138 	 * if there was a check condition then sensep points to valid
9139 	 * sense data
9140 	 * if status was not a check condition but a reservation or busy
9141 	 * status then the new state is MTIO_NONE
9142 	 */
9143 	if (sensep) {
9144 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9145 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
9146 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
9147 
9148 		switch (un->un_dp->type) {
9149 		default:
9150 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9151 			    "st_media_watch_cb: unknown drive type %d, "
9152 			    "default to ST_TYPE_HP\n", un->un_dp->type);
9153 		/* FALLTHROUGH */
9154 
9155 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
9156 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
9157 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
9158 			if (un->un_dp->type == ST_TYPE_FUJI) {
9159 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9160 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
9161 			} else {
9162 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9163 				    "st_media_watch_cb: ST_TYPE_HP\n");
9164 			}
9165 			switch (sensep->es_key) {
9166 			case KEY_UNIT_ATTENTION:
9167 				/* not ready to ready transition */
9168 				/* hp/es_qual_code == 80 on>off>on */
9169 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
9170 				if (sensep->es_add_code == 0x28) {
9171 					state = MTIO_INSERTED;
9172 				}
9173 				break;
9174 			case KEY_NOT_READY:
9175 				/* in process, rewinding or loading */
9176 				if ((sensep->es_add_code == 0x04) &&
9177 				    (sensep->es_qual_code == 0x00)) {
9178 					state = MTIO_EJECTED;
9179 				}
9180 				break;
9181 			}
9182 			break;
9183 
9184 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
9185 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9186 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
9187 			switch (sensep->es_key) {
9188 			case KEY_UNIT_ATTENTION:
9189 				/* operator medium removal request */
9190 				if ((sensep->es_add_code == 0x5a) &&
9191 				    (sensep->es_qual_code == 0x01)) {
9192 					state = MTIO_EJECTED;
9193 				/* not ready to ready transition */
9194 				} else if ((sensep->es_add_code == 0x28) &&
9195 				    (sensep->es_qual_code == 0x00)) {
9196 					state = MTIO_INSERTED;
9197 				}
9198 				break;
9199 			case KEY_NOT_READY:
9200 				/* medium not present */
9201 				if (sensep->es_add_code == 0x3a) {
9202 					state = MTIO_EJECTED;
9203 				}
9204 				break;
9205 			}
9206 			break;
9207 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
9208 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9209 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
9210 			switch (sensep->es_key) {
9211 			case KEY_NOT_READY:
9212 				if ((sensep->es_add_code == 0x04) &&
9213 				    (sensep->es_qual_code == 0x00)) {
9214 					/* volume not mounted? */
9215 					state = MTIO_EJECTED;
9216 				} else if (sensep->es_add_code == 0x3a) {
9217 					state = MTIO_EJECTED;
9218 				}
9219 				break;
9220 			case KEY_UNIT_ATTENTION:
9221 				state = MTIO_EJECTED;
9222 				break;
9223 			}
9224 			break;
9225 
9226 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
9227 			switch (sensep->es_key) {
9228 			case KEY_UNIT_ATTENTION:
9229 				if (sensep->es_add_code == 0x28) {
9230 					state = MTIO_INSERTED;
9231 				}
9232 				break;
9233 			case KEY_NOT_READY:
9234 				if (sensep->es_add_code == 0x04) {
9235 					/* in transition but could be either */
9236 					state = un->un_specified_mediastate;
9237 				} else if ((sensep->es_add_code == 0x3a) &&
9238 				    (sensep->es_qual_code == 0x00)) {
9239 					state = MTIO_EJECTED;
9240 				}
9241 				break;
9242 			}
9243 			break;
9244 		}
9245 	} else if (*((char *)statusp) == STATUS_GOOD) {
9246 		state = MTIO_INSERTED;
9247 	}
9248 
9249 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9250 	    "st_media_watch_cb:state=%x, specified=%x\n",
9251 	    state, un->un_specified_mediastate);
9252 
9253 	/*
9254 	 * now signal the waiting thread if this is *not* the specified state;
9255 	 * delay the signal if the state is MTIO_INSERTED
9256 	 * to allow the target to recover
9257 	 */
9258 	if (state != un->un_specified_mediastate) {
9259 		un->un_mediastate = state;
9260 		if (state == MTIO_INSERTED) {
9261 			/*
9262 			 * delay the signal to give the drive a chance
9263 			 * to do what it apparently needs to do
9264 			 */
9265 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9266 			    "st_media_watch_cb:delayed cv_broadcast\n");
9267 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
9268 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
9269 		} else {
9270 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9271 			    "st_media_watch_cb:immediate cv_broadcast\n");
9272 			cv_broadcast(&un->un_state_cv);
9273 		}
9274 	}
9275 	mutex_exit(ST_MUTEX);
9276 	return (0);
9277 }
9278 
9279 /*
9280  * delayed cv_broadcast to allow for target to recover
9281  * from media insertion
9282  */
9283 static void
9284 st_delayed_cv_broadcast(void *arg)
9285 {
9286 	struct scsi_tape *un = arg;
9287 
9288 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
9289 
9290 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9291 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
9292 
9293 	mutex_enter(ST_MUTEX);
9294 	cv_broadcast(&un->un_state_cv);
9295 	mutex_exit(ST_MUTEX);
9296 }
9297 
9298 /*
9299  * restart cmd currently at the start of the waitq
9300  */
9301 static void
9302 st_start_restart(void *arg)
9303 {
9304 	struct scsi_tape *un = arg;
9305 
9306 	ST_FUNC(ST_DEVINFO, st_start_restart);
9307 
9308 	ASSERT(un != NULL);
9309 
9310 	mutex_enter(ST_MUTEX);
9311 
9312 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_tran_restart()\n");
9313 
9314 	st_start(un);
9315 
9316 	mutex_exit(ST_MUTEX);
9317 }
9318 
9319 
9320 /*
9321  * Command completion processing
9322  *
9323  */
9324 static void
9325 st_intr(struct scsi_pkt *pkt)
9326 {
9327 	recov_info *rcv = pkt->pkt_private;
9328 	struct buf *bp = rcv->cmd_bp;
9329 	struct scsi_tape *un;
9330 	errstate action = COMMAND_DONE;
9331 	clock_t	timout;
9332 	int	status;
9333 
9334 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
9335 
9336 	ST_FUNC(ST_DEVINFO, st_intr);
9337 
9338 	ASSERT(un != NULL);
9339 
9340 	mutex_enter(ST_MUTEX);
9341 
9342 	ASSERT(bp != un->un_recov_buf);
9343 
9344 	if (pkt == un->un_rqs) {
9345 		scsi_sync_pkt(pkt);
9346 	}
9347 
9348 	un->un_rqs_state &= ~(ST_RQS_ERROR);
9349 
9350 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
9351 
9352 	if (pkt->pkt_reason != CMD_CMPLT) {
9353 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9354 		    "Unhappy packet status reason = %s statistics = 0x%x\n",
9355 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9356 
9357 		/* If device has gone away not much else to do */
9358 		if (pkt->pkt_reason == CMD_DEV_GONE) {
9359 			action = COMMAND_DONE_ERROR;
9360 		} else if ((pkt == un->un_rqs) ||
9361 		    (un->un_state == ST_STATE_SENSING)) {
9362 			ASSERT(pkt == un->un_rqs);
9363 			ASSERT(un->un_state == ST_STATE_SENSING);
9364 			un->un_state = un->un_laststate;
9365 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp =
9366 			    un->un_rqs_bp;
9367 			ST_DO_ERRSTATS(un, st_transerrs);
9368 			action = COMMAND_DONE_ERROR;
9369 		} else {
9370 			action = st_handle_incomplete(un, bp);
9371 		}
9372 	/*
9373 	 * At this point we know that the command was successfully
9374 	 * completed. Now what?
9375 	 */
9376 	} else if ((pkt == un->un_rqs) || (un->un_state == ST_STATE_SENSING)) {
9377 		/*
9378 		 * okay. We were running a REQUEST SENSE. Find
9379 		 * out what to do next.
9380 		 */
9381 		ASSERT(pkt == un->un_rqs);
9382 		ASSERT(un->un_state == ST_STATE_SENSING);
9383 		action = st_handle_sense(un, bp, &un->un_pos);
9384 		/*
9385 		 * Make rqs isn't going to be retied.
9386 		 */
9387 		if (action != QUE_BUSY_COMMAND && action != QUE_COMMAND) {
9388 			/*
9389 			 * set pkt back to original packet in case we will have
9390 			 * to requeue it
9391 			 */
9392 			pkt = BP_PKT(bp);
9393 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp =
9394 			    un->un_rqs_bp;
9395 			/*
9396 			 * some actions are based on un_state, hence
9397 			 * restore the state st was in before ST_STATE_SENSING.
9398 			 */
9399 			un->un_state = un->un_laststate;
9400 		}
9401 
9402 	} else if (un->un_arq_enabled && (pkt->pkt_state & STATE_ARQ_DONE)) {
9403 		/*
9404 		 * the transport layer successfully completed an autorqsense
9405 		 */
9406 		action = st_handle_autosense(un, bp, &un->un_pos);
9407 
9408 	} else  if ((SCBP(pkt)->sts_busy) || (SCBP(pkt)->sts_chk)) {
9409 		/*
9410 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9411 		 * to see if the status bits we're okay. If a request sense
9412 		 * is to be run, that will happen.
9413 		 */
9414 		action = st_check_error(un, pkt);
9415 	}
9416 
9417 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9418 		switch (action) {
9419 			case QUE_COMMAND:
9420 				/*
9421 				 * return cmd to head to the queue
9422 				 * since we are suspending so that
9423 				 * it gets restarted during resume
9424 				 */
9425 				st_add_to_queue(&un->un_runqf, &un->un_runql,
9426 				    un->un_runqf, bp);
9427 
9428 				action = JUST_RETURN;
9429 				break;
9430 
9431 			case QUE_SENSE:
9432 				action = COMMAND_DONE_ERROR;
9433 				break;
9434 
9435 			default:
9436 				break;
9437 		}
9438 	}
9439 
9440 	/*
9441 	 * Restore old state if we were sensing.
9442 	 */
9443 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9444 		un->un_state = un->un_laststate;
9445 	}
9446 
9447 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9448 	    "st_intr: pkt=%p, bp=%p, action=%x, status=%x\n",
9449 	    (void *)pkt, (void *)bp, action, SCBP_C(pkt));
9450 
9451 again:
9452 	switch (action) {
9453 	case COMMAND_DONE_EACCES:
9454 		/* this is to report a reservation conflict */
9455 		st_bioerror(bp, EACCES);
9456 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9457 		    "Reservation Conflict \n");
9458 		un->un_pos.pmode = invalid;
9459 
9460 		/*FALLTHROUGH*/
9461 	case COMMAND_DONE_ERROR:
9462 		if (un->un_pos.eof < ST_EOT_PENDING &&
9463 		    un->un_state >= ST_STATE_OPEN) {
9464 			/*
9465 			 * all errors set state of the tape to 'unknown'
9466 			 * unless we're at EOT or are doing append testing.
9467 			 * If sense key was illegal request, preserve state.
9468 			 */
9469 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9470 				un->un_pos.pmode = invalid;
9471 			}
9472 		}
9473 
9474 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9475 		/*
9476 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9477 		 * make sure an error ocurrs, so make sure at least EIO is
9478 		 * returned
9479 		 */
9480 		if (geterror(bp) == 0)
9481 			st_bioerror(bp, EIO);
9482 
9483 		st_set_pe_flag(un);
9484 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9485 		    (un->un_errno == EIO)) {
9486 			un->un_rqs_state &= ~(ST_RQS_VALID);
9487 		}
9488 		break;
9489 
9490 	case COMMAND_DONE_ERROR_RECOVERED:
9491 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9492 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9493 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9494 		if (geterror(bp) == 0) {
9495 			st_bioerror(bp, EIO);
9496 		}
9497 		st_set_pe_flag(un);
9498 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9499 		    (un->un_errno == EIO)) {
9500 			un->un_rqs_state &= ~(ST_RQS_VALID);
9501 		}
9502 		/*FALLTHROUGH*/
9503 	case COMMAND_DONE:
9504 		st_set_state(un, bp);
9505 		break;
9506 
9507 	case QUE_SENSE:
9508 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9509 			goto sense_error;
9510 
9511 		if (un->un_state != ST_STATE_SENSING) {
9512 			un->un_laststate = un->un_state;
9513 			un->un_state = ST_STATE_SENSING;
9514 		}
9515 
9516 		/* Whats going to happen here? */
9517 
9518 		((recov_info *)un->un_rqs->pkt_private)->cmd_bp = bp;
9519 
9520 		bzero(ST_RQSENSE, SENSE_LENGTH);
9521 
9522 		scsi_sync_pkt(un->un_rqs); /* HELLO */
9523 
9524 		if (un->un_throttle) {
9525 			un->un_last_throttle = un->un_throttle;
9526 			un->un_throttle = 0;
9527 		}
9528 
9529 		ST_CDB(ST_DEVINFO, "Queue sense CDB",
9530 		    (char *)BP_PKT(bp)->pkt_cdbp);
9531 
9532 		/*
9533 		 * never retry this, some other command will have nuked the
9534 		 * sense, anyway
9535 		 */
9536 		status = st_transport(un, un->un_rqs);
9537 
9538 		if (un->un_last_throttle) {
9539 			un->un_throttle = un->un_last_throttle;
9540 		}
9541 
9542 		if (status == TRAN_ACCEPT) {
9543 			mutex_exit(ST_MUTEX);
9544 			return;
9545 		}
9546 		if (status != TRAN_BUSY)
9547 			ST_DO_ERRSTATS(un, st_transerrs);
9548 sense_error:
9549 		un->un_pos.pmode = invalid;
9550 		st_bioerror(bp, EIO);
9551 		st_set_pe_flag(un);
9552 		break;
9553 
9554 	case QUE_BUSY_COMMAND:
9555 		/* longish timeout */
9556 		timout = ST_STATUS_BUSY_TIMEOUT;
9557 		goto que_it_up;
9558 
9559 	case QUE_COMMAND:
9560 		/* short timeout */
9561 		timout = ST_TRAN_BUSY_TIMEOUT;
9562 que_it_up:
9563 		/*
9564 		 * let st_handle_intr_busy put this bp back on waitq and make
9565 		 * checks to see if it is ok to requeue the command.
9566 		 */
9567 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9568 
9569 		/*
9570 		 * Save the throttle before setting up the timeout
9571 		 */
9572 		if (un->un_throttle) {
9573 			un->un_last_throttle = un->un_throttle;
9574 		}
9575 		mutex_exit(ST_MUTEX);
9576 		if (st_handle_intr_busy(un, bp, timout) == 0)
9577 			return;		/* timeout is setup again */
9578 
9579 		mutex_enter(ST_MUTEX);
9580 		un->un_pos.pmode = invalid;
9581 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9582 		st_bioerror(bp, EIO);
9583 		st_set_pe_flag(un);
9584 		break;
9585 
9586 	case QUE_LAST_COMMAND:
9587 
9588 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9589 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9590 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9591 			goto last_command_error;
9592 		}
9593 		mutex_exit(ST_MUTEX);
9594 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9595 			return;
9596 		mutex_enter(ST_MUTEX);
9597 last_command_error:
9598 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9599 		un->un_pos.pmode = invalid;
9600 		st_bioerror(bp, EIO);
9601 		st_set_pe_flag(un);
9602 		break;
9603 
9604 	case COMMAND_TIMEOUT:
9605 	case DEVICE_RESET:
9606 	case DEVICE_TAMPER:
9607 	case ATTEMPT_RETRY:
9608 		action = st_command_recovery(un, pkt, action);
9609 		goto again;
9610 
9611 	default:
9612 		ASSERT(0);
9613 		/* FALLTHRU */
9614 	case JUST_RETURN:
9615 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9616 		mutex_exit(ST_MUTEX);
9617 		return;
9618 	}
9619 
9620 	ST_DO_KSTATS(bp, kstat_runq_exit);
9621 	st_done_and_mutex_exit(un, bp);
9622 }
9623 
9624 static errstate
9625 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9626 {
9627 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9628 	recov_info *rinfo;
9629 	errstate rval = COMMAND_DONE_ERROR;
9630 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9631 	    un->un_rqs : BP_PKT(bp);
9632 	int result;
9633 
9634 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9635 
9636 	rinfo = (recov_info *)pkt->pkt_private;
9637 
9638 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9639 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9640 
9641 	ASSERT(mutex_owned(ST_MUTEX));
9642 
9643 	switch (pkt->pkt_reason) {
9644 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9645 		/*
9646 		 * this occurs when accessing a powered down drive, no
9647 		 * need to complain; just fail the open
9648 		 */
9649 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9650 
9651 		/*
9652 		 * if we have commands outstanding in HBA, and a command
9653 		 * comes back incomplete, we're hosed, so reset target
9654 		 * If we have the bus, but cmd_incomplete, we probably just
9655 		 * have a failed selection, so don't reset the target, just
9656 		 * requeue the command and try again
9657 		 */
9658 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9659 			goto reset_target;
9660 		}
9661 
9662 		/*
9663 		 * Retry selection a couple more times if we're
9664 		 * open.  If opening, we only try just once to
9665 		 * reduce probe time for nonexistant devices.
9666 		 */
9667 		if ((un->un_laststate > ST_STATE_OPENING) &&
9668 		    ((int)un->un_retry_ct < st_selection_retry_count)) {
9669 /* XXX check retriable? */
9670 			rval = QUE_COMMAND;
9671 		}
9672 		ST_DO_ERRSTATS(un, st_transerrs);
9673 		break;
9674 
9675 	case CMD_ABORTED:
9676 		/*
9677 		 * most likely this is caused by flush-on-error support. If
9678 		 * it was not there, the we're in trouble.
9679 		 */
9680 		if (!un->un_flush_on_errors) {
9681 			un->un_status = SUN_KEY_FATAL;
9682 			goto reset_target;
9683 		}
9684 
9685 		st_set_pe_errno(un);
9686 		bioerror(bp, un->un_errno);
9687 		if (un->un_errno)
9688 			return (COMMAND_DONE_ERROR);
9689 		else
9690 			return (COMMAND_DONE);
9691 
9692 	case CMD_TIMEOUT:	/* Command timed out */
9693 		un->un_status = SUN_KEY_TIMEOUT;
9694 		return (COMMAND_TIMEOUT);
9695 
9696 	case CMD_TRAN_ERR:
9697 	case CMD_RESET:
9698 		if (pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET)) {
9699 			if ((un->un_rsvd_status &
9700 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
9701 			    ST_RESERVE) {
9702 				un->un_rsvd_status |= ST_LOST_RESERVE;
9703 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
9704 				    "Lost Reservation\n");
9705 			}
9706 			rval = DEVICE_RESET;
9707 			return (rval);
9708 		}
9709 		if (pkt->pkt_statistics & (STAT_ABORTED | STAT_TERMINATED)) {
9710 			rval = DEVICE_RESET;
9711 			return (rval);
9712 		}
9713 		/*FALLTHROUGH*/
9714 	default:
9715 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9716 		    "Unhandled packet status reason = %s statistics = 0x%x\n",
9717 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9718 reset_target:
9719 
9720 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9721 		    "transport completed with %s\n",
9722 		    scsi_rname(pkt->pkt_reason));
9723 		ST_DO_ERRSTATS(un, st_transerrs);
9724 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
9725 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
9726 		    STAT_ABORTED)) == 0)) {
9727 
9728 			/*
9729 			 * If we haven't reserved the drive don't reset it.
9730 			 */
9731 			if ((un->un_rsvd_status &
9732 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9733 				return (rval);
9734 			}
9735 
9736 			/*
9737 			 * if we aren't lost yet we will be soon.
9738 			 */
9739 			un->un_pos.pmode = invalid;
9740 
9741 			result = st_reset(un, RESET_LUN);
9742 
9743 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
9744 				/* no hope left to recover */
9745 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
9746 				    "recovery by resets failed\n");
9747 				return (rval);
9748 			}
9749 		}
9750 	}
9751 
9752 
9753 	if ((int)un->un_retry_ct++ < st_retry_count) {
9754 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9755 			rval = QUE_COMMAND;
9756 		} else if (bp == un->un_sbufp) {
9757 			if (rinfo->privatelen == sizeof (recov_info)) {
9758 				if (rinfo->cmd_attrib->retriable) {
9759 					/*
9760 					 * These commands can be rerun
9761 					 * with impunity
9762 					 */
9763 					rval = QUE_COMMAND;
9764 				}
9765 			} else {
9766 				cmd_attribute const *attrib;
9767 				attrib =
9768 				    st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
9769 				if (attrib->retriable) {
9770 					rval = QUE_COMMAND;
9771 				}
9772 			}
9773 		}
9774 	} else {
9775 		rval = COMMAND_DONE_ERROR;
9776 	}
9777 
9778 	if (un->un_state >= ST_STATE_OPEN) {
9779 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9780 		    fail, scsi_rname(pkt->pkt_reason),
9781 		    (rval == COMMAND_DONE_ERROR)?
9782 		    "giving up" : "retrying command");
9783 	}
9784 	return (rval);
9785 }
9786 
9787 /*
9788  * if the device is busy, then put this bp back on the waitq, on the
9789  * interrupt thread, where we want the head of the queue and not the
9790  * end
9791  *
9792  * The callers of this routine should take measures to save the
9793  * un_throttle in un_last_throttle which will be restored in
9794  * st_intr_restart(). The only exception should be st_intr_restart()
9795  * calling this routine for which the saving is already done.
9796  */
9797 static int
9798 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
9799 	clock_t timeout_interval)
9800 {
9801 
9802 	int queued;
9803 	int rval = 0;
9804 
9805 	mutex_enter(ST_MUTEX);
9806 
9807 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
9808 
9809 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9810 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
9811 
9812 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
9813 		queued = 1;
9814 	} else {
9815 		queued = 0;
9816 	}
9817 
9818 	/*
9819 	 * Check to see if we hit the retry timeout. We check to make sure
9820 	 * this is the first one on the runq and make sure we have not
9821 	 * queued up any more, so this one has to be the last on the list
9822 	 * also. If it is not, we have to fail.  If it is not the first, but
9823 	 * is the last we are in trouble anyway, as we are in the interrupt
9824 	 * context here.
9825 	 */
9826 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
9827 	    ((un->un_runqf != bp) && (un->un_runql != bp) && (queued))) {
9828 		rval = -1;
9829 		goto exit;
9830 	}
9831 
9832 	/* put the bp back on the waitq */
9833 	if (queued) {
9834 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
9835 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
9836 	}
9837 
9838 	/*
9839 	 * We don't want any other commands being started in the mean time.
9840 	 * If start had just released mutex after putting something on the
9841 	 * runq, we won't even get here.
9842 	 */
9843 	un->un_throttle = 0;
9844 
9845 	/*
9846 	 * send a marker pkt, if appropriate
9847 	 */
9848 	st_hba_unflush(un);
9849 
9850 	/*
9851 	 * all queues are aligned, we are just waiting to
9852 	 * transport
9853 	 */
9854 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
9855 
9856 exit:
9857 	mutex_exit(ST_MUTEX);
9858 	return (rval);
9859 }
9860 
9861 /*
9862  * To get one error entry from error stack
9863  */
9864 static int
9865 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
9866 {
9867 #ifdef _MULTI_DATAMODEL
9868 	/*
9869 	 * For use when a 32 bit app makes a call into a
9870 	 * 64 bit ioctl
9871 	 */
9872 	struct mterror_entry32 err_entry32;
9873 #endif /* _MULTI_DATAMODEL */
9874 
9875 	int rval = 0;
9876 	struct mterror_entry err_entry;
9877 	struct mterror_entry_stack *err_link_entry_p;
9878 	size_t arq_status_len_in, arq_status_len_kr;
9879 
9880 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
9881 
9882 	ASSERT(mutex_owned(ST_MUTEX));
9883 
9884 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9885 	    "st_get_error_entry()\n");
9886 
9887 	/*
9888 	 * if error record stack empty, return ENXIO
9889 	 */
9890 	if (un->un_error_entry_stk == NULL) {
9891 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9892 		    "st_get_error_entry: Error Entry Stack Empty!\n");
9893 		rval = ENXIO;
9894 		goto ret;
9895 	}
9896 
9897 	/*
9898 	 * get the top entry from stack
9899 	 */
9900 	err_link_entry_p = un->un_error_entry_stk;
9901 	arq_status_len_kr =
9902 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
9903 
9904 #ifdef _MULTI_DATAMODEL
9905 	switch (ddi_model_convert_from(flag & FMODELS)) {
9906 	case DDI_MODEL_ILP32:
9907 		if (ddi_copyin((void *)arg, &err_entry32,
9908 		    MTERROR_ENTRY_SIZE_32, flag)) {
9909 			rval = EFAULT;
9910 			goto ret;
9911 		}
9912 
9913 		arq_status_len_in =
9914 		    (size_t)err_entry32.mtee_arq_status_len;
9915 
9916 		err_entry32.mtee_cdb_len =
9917 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
9918 
9919 		if (arq_status_len_in > arq_status_len_kr)
9920 			err_entry32.mtee_arq_status_len =
9921 			    (size32_t)arq_status_len_kr;
9922 
9923 		if (ddi_copyout(
9924 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
9925 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
9926 		    err_entry32.mtee_cdb_len, flag)) {
9927 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9928 			    "st_get_error_entry: Copy cdb buffer error!");
9929 			rval = EFAULT;
9930 		}
9931 
9932 		if (ddi_copyout(
9933 		    err_link_entry_p->mtees_entry.mtee_arq_status,
9934 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
9935 		    err_entry32.mtee_arq_status_len, flag)) {
9936 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9937 			    "st_get_error_entry: copy arq status error!");
9938 			rval = EFAULT;
9939 		}
9940 
9941 		if (ddi_copyout(&err_entry32, (void *)arg,
9942 		    MTERROR_ENTRY_SIZE_32, flag)) {
9943 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9944 			    "st_get_error_entry: copy arq status out error!");
9945 			rval = EFAULT;
9946 		}
9947 		break;
9948 
9949 	case DDI_MODEL_NONE:
9950 		if (ddi_copyin((void *)arg, &err_entry,
9951 		    MTERROR_ENTRY_SIZE_64, flag)) {
9952 			rval = EFAULT;
9953 			goto ret;
9954 		}
9955 		arq_status_len_in = err_entry.mtee_arq_status_len;
9956 
9957 		err_entry.mtee_cdb_len =
9958 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
9959 
9960 		if (arq_status_len_in > arq_status_len_kr)
9961 			err_entry.mtee_arq_status_len =
9962 			    arq_status_len_kr;
9963 
9964 		if (ddi_copyout(
9965 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
9966 		    err_entry.mtee_cdb_buf,
9967 		    err_entry.mtee_cdb_len, flag)) {
9968 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9969 			    "st_get_error_entry: Copy cdb buffer error!");
9970 			rval = EFAULT;
9971 		}
9972 
9973 		if (ddi_copyout(
9974 		    err_link_entry_p->mtees_entry.mtee_arq_status,
9975 		    err_entry.mtee_arq_status,
9976 		    err_entry.mtee_arq_status_len, flag)) {
9977 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9978 			    "st_get_error_entry: copy arq status error!");
9979 			rval = EFAULT;
9980 		}
9981 
9982 		if (ddi_copyout(&err_entry, (void *)arg,
9983 		    MTERROR_ENTRY_SIZE_64, flag)) {
9984 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9985 			    "st_get_error_entry: copy arq status out error!");
9986 			rval = EFAULT;
9987 		}
9988 		break;
9989 	}
9990 #else /* _MULTI_DATAMODEL */
9991 	if (ddi_copyin((void *)arg, &err_entry,
9992 	    MTERROR_ENTRY_SIZE_64, flag)) {
9993 		rval = EFAULT;
9994 		goto ret;
9995 	}
9996 	arq_status_len_in = err_entry.mtee_arq_status_len;
9997 
9998 	err_entry.mtee_cdb_len =
9999 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
10000 
10001 	if (arq_status_len_in > arq_status_len_kr)
10002 		err_entry.mtee_arq_status_len =
10003 		    arq_status_len_kr;
10004 
10005 	if (ddi_copyout(
10006 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10007 	    err_entry.mtee_cdb_buf,
10008 	    err_entry.mtee_cdb_len, flag)) {
10009 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10010 		    "st_get_error_entry: Copy cdb buffer error!");
10011 		rval = EFAULT;
10012 	}
10013 
10014 	if (ddi_copyout(
10015 	    err_link_entry_p->mtees_entry.mtee_arq_status,
10016 	    err_entry.mtee_arq_status,
10017 	    err_entry.mtee_arq_status_len, flag)) {
10018 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10019 		    "st_get_error_entry: copy arq status buffer error!");
10020 		rval = EFAULT;
10021 	}
10022 
10023 	if (ddi_copyout(&err_entry, (void *)arg,
10024 	    MTERROR_ENTRY_SIZE_64, flag)) {
10025 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10026 		    "st_get_error_entry: copy arq status out error!");
10027 		rval = EFAULT;
10028 	}
10029 #endif /* _MULTI_DATAMODEL */
10030 
10031 	/*
10032 	 * update stack
10033 	 */
10034 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
10035 
10036 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
10037 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
10038 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
10039 
10040 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
10041 	    SECMDS_STATUS_SIZE);
10042 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
10043 
10044 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
10045 	err_link_entry_p = NULL;
10046 ret:
10047 	return (rval);
10048 }
10049 
10050 /*
10051  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
10052  * the scsi CDB command which causes the error and generates sense data and
10053  * the scsi status.
10054  *
10055  *      error-record stack
10056  *
10057  *
10058  *             TOP                                     BOTTOM
10059  *              ------------------------------------------
10060  *              |   0   |   1   |   2   |   ...  |   n   |
10061  *              ------------------------------------------
10062  *                  ^
10063  *                  |
10064  *       pointer to error entry
10065  *
10066  * when st driver generates one sense data record, it creates a error-entry
10067  * and pushes it onto the stack.
10068  *
10069  */
10070 
10071 static void
10072 st_update_error_stack(struct scsi_tape *un,
10073 			struct scsi_pkt *pkt,
10074 			struct scsi_arq_status *cmd)
10075 {
10076 	struct mterror_entry_stack *err_entry_tmp;
10077 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
10078 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
10079 
10080 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
10081 
10082 	ASSERT(mutex_owned(ST_MUTEX));
10083 
10084 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10085 	    "st_update_error_stack()\n");
10086 
10087 	ASSERT(cmd);
10088 	ASSERT(cdbp);
10089 	if (cdblen == 0) {
10090 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10091 		    "st_update_error_stack: CDB length error!\n");
10092 		return;
10093 	}
10094 
10095 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
10096 	ASSERT(err_entry_tmp != NULL);
10097 
10098 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
10099 	    kmem_alloc(cdblen, KM_SLEEP);
10100 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
10101 
10102 	err_entry_tmp->mtees_entry.mtee_arq_status =
10103 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
10104 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
10105 
10106 	/*
10107 	 * copy cdb command & length to current error entry
10108 	 */
10109 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
10110 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
10111 
10112 	/*
10113 	 * copy scsi status length to current error entry
10114 	 */
10115 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
10116 	    SECMDS_STATUS_SIZE;
10117 
10118 	/*
10119 	 * copy sense data and scsi status to current error entry
10120 	 */
10121 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
10122 	    SECMDS_STATUS_SIZE);
10123 
10124 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
10125 	un->un_error_entry_stk = err_entry_tmp;
10126 
10127 }
10128 
10129 /*
10130  * Empty all the error entry in stack
10131  */
10132 static void
10133 st_empty_error_stack(struct scsi_tape *un)
10134 {
10135 	struct mterror_entry_stack *linkp;
10136 
10137 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
10138 
10139 	ASSERT(mutex_owned(ST_MUTEX));
10140 
10141 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10142 	    "st_empty_entry_stack()\n");
10143 
10144 	while (un->un_error_entry_stk != NULL) {
10145 		linkp = un->un_error_entry_stk;
10146 		un->un_error_entry_stk =
10147 		    un->un_error_entry_stk->mtees_nextp;
10148 
10149 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
10150 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
10151 			    linkp->mtees_entry.mtee_cdb_len);
10152 
10153 		if (linkp->mtees_entry.mtee_arq_status != NULL)
10154 			kmem_free(linkp->mtees_entry.mtee_arq_status,
10155 			    linkp->mtees_entry.mtee_arq_status_len);
10156 
10157 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
10158 		linkp = NULL;
10159 	}
10160 }
10161 
10162 static errstate
10163 st_handle_sense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10164 {
10165 	struct scsi_pkt *pkt = BP_PKT(bp);
10166 	struct scsi_pkt *rqpkt = un->un_rqs;
10167 	struct scsi_arq_status arqstat;
10168 
10169 	errstate rval = COMMAND_DONE_ERROR;
10170 	int amt;
10171 
10172 	ST_FUNC(ST_DEVINFO, st_handle_sense);
10173 
10174 	ASSERT(mutex_owned(ST_MUTEX));
10175 
10176 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10177 	    "st_handle_sense()\n");
10178 
10179 	if (SCBP(rqpkt)->sts_busy) {
10180 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10181 		    "busy unit on request sense\n");
10182 		if ((int)un->un_retry_ct++ < st_retry_count) {
10183 			rval = QUE_BUSY_COMMAND;
10184 		}
10185 		return (rval);
10186 	} else if (SCBP(rqpkt)->sts_chk) {
10187 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10188 		    "Check Condition on REQUEST SENSE\n");
10189 		return (rval);
10190 	}
10191 
10192 	/* was there enough data? */
10193 	amt = (int)MAX_SENSE_LENGTH - rqpkt->pkt_resid;
10194 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
10195 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10196 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10197 		    "REQUEST SENSE couldn't get sense data\n");
10198 		return (rval);
10199 	}
10200 
10201 	bcopy(SCBP(pkt), &arqstat.sts_status,
10202 	    sizeof (struct scsi_status));
10203 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
10204 	    sizeof (struct scsi_status));
10205 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
10206 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
10207 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
10208 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
10209 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
10210 
10211 	/*
10212 	 * copy one arqstat entry in the sense data buffer
10213 	 */
10214 	st_update_error_stack(un, pkt, &arqstat);
10215 	return (st_decode_sense(un, bp, amt, SCBP(rqpkt), pos));
10216 }
10217 
10218 static errstate
10219 st_handle_autosense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10220 {
10221 	struct scsi_pkt *pkt = BP_PKT(bp);
10222 	struct scsi_arq_status *arqstat =
10223 	    (struct scsi_arq_status *)pkt->pkt_scbp;
10224 	errstate rval = COMMAND_DONE_ERROR;
10225 	int amt;
10226 
10227 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
10228 
10229 	ASSERT(mutex_owned(ST_MUTEX));
10230 
10231 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10232 	    "st_handle_autosense()\n");
10233 
10234 	if (arqstat->sts_rqpkt_status.sts_busy) {
10235 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10236 		    "busy unit on request sense\n");
10237 		/*
10238 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
10239 		 * the disadvantage is that we do not have any delay for the
10240 		 * second retry of rqsense and we have to keep a packet around
10241 		 */
10242 		return (QUE_SENSE);
10243 
10244 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
10245 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10246 		    "transport error on REQUEST SENSE\n");
10247 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
10248 		    ((arqstat->sts_rqpkt_statistics &
10249 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
10250 			if (st_reset(un, RESET_LUN) == 0) {
10251 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10252 				    "recovery by resets failed\n");
10253 			}
10254 		}
10255 		return (rval);
10256 
10257 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
10258 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10259 		    "Check Condition on REQUEST SENSE\n");
10260 		return (rval);
10261 	}
10262 
10263 
10264 	/* was there enough data? */
10265 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10266 		amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10267 	} else {
10268 		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
10269 			amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10270 		} else {
10271 			amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10272 		}
10273 	}
10274 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
10275 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10276 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10277 		    "REQUEST SENSE couldn't get sense data\n");
10278 		return (rval);
10279 	}
10280 
10281 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10282 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, MAX_SENSE_LENGTH);
10283 	} else {
10284 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
10285 	}
10286 
10287 	/*
10288 	 * copy one arqstat entry in the sense data buffer
10289 	 */
10290 	st_update_error_stack(un, pkt, arqstat);
10291 
10292 	return (st_decode_sense(un, bp, amt, &arqstat->sts_rqpkt_status, pos));
10293 }
10294 
10295 static errstate
10296 st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
10297     struct scsi_status *statusp, tapepos_t *pos)
10298 {
10299 	struct scsi_pkt *pkt = BP_PKT(bp);
10300 	recov_info *ri = (recov_info *)pkt->pkt_private;
10301 	errstate rval = COMMAND_DONE_ERROR;
10302 	cmd_attribute const *attrib;
10303 	long resid;
10304 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10305 	int severity;
10306 	int get_error;
10307 
10308 	ST_FUNC(ST_DEVINFO, st_decode_sense);
10309 
10310 	ASSERT(mutex_owned(ST_MUTEX));
10311 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10312 	    "st_decode_sense()\n");
10313 
10314 	/*
10315 	 * For uscsi commands, squirrel away a copy of the
10316 	 * results of the Request Sense.
10317 	 */
10318 	if (USCSI_CMD(bp)) {
10319 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
10320 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
10321 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
10322 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
10323 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
10324 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
10325 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10326 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
10327 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
10328 		}
10329 	}
10330 
10331 	if (ri->privatelen == sizeof (recov_info)) {
10332 		attrib = ri->cmd_attrib;
10333 	} else {
10334 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10335 	}
10336 
10337 	/*
10338 	 * If the drive is an MT-02, reposition the
10339 	 * secondary error code into the proper place.
10340 	 *
10341 	 * XXX	MT-02 is non-CCS tape, so secondary error code
10342 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
10343 	 * so it's in byte 12.
10344 	 */
10345 	if (un->un_dp->type == ST_TYPE_EMULEX) {
10346 		sensep->es_code = sensep->es_add_info[0];
10347 	}
10348 
10349 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
10350 	    (caddr_t)&CDBP(pkt)->scc_cmd);
10351 
10352 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)sensep,
10353 	    sizeof (*sensep));
10354 
10355 	/* for normal I/O check extract the resid values. */
10356 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
10357 		if (sensep->es_valid) {
10358 			resid =
10359 			    (sensep->es_info_1 << 24) |
10360 			    (sensep->es_info_2 << 16) |
10361 			    (sensep->es_info_3 << 8)  |
10362 			    (sensep->es_info_4);
10363 			/* If fixed block */
10364 			if (un->un_bsize) {
10365 				resid *= un->un_bsize;
10366 			}
10367 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
10368 			resid = pkt->pkt_resid;
10369 		} else {
10370 			resid = bp->b_bcount;
10371 		}
10372 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10373 		    "st_decode_sense (rw): xferred bit = %d, resid=%ld (%d), "
10374 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
10375 		    resid,
10376 		    (sensep->es_info_1 << 24) |
10377 		    (sensep->es_info_2 << 16) |
10378 		    (sensep->es_info_3 << 8)  |
10379 		    (sensep->es_info_4),
10380 		    pkt->pkt_resid);
10381 		/*
10382 		 * The problem is, what should we believe?
10383 		 */
10384 		if (resid && (pkt->pkt_resid == 0)) {
10385 			pkt->pkt_resid = resid;
10386 		}
10387 	} else {
10388 		/*
10389 		 * If the command is SCMD_SPACE, we need to get the
10390 		 * residual as returned in the sense data, to adjust
10391 		 * our idea of current tape position correctly
10392 		 */
10393 		if ((sensep->es_valid) &&
10394 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10395 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10396 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
10397 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK)) {
10398 			resid =
10399 			    (sensep->es_info_1 << 24) |
10400 			    (sensep->es_info_2 << 16) |
10401 			    (sensep->es_info_3 << 8)  |
10402 			    (sensep->es_info_4);
10403 			bp->b_resid = resid;
10404 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10405 			    "st_decode_sense(other):	resid=%ld\n", resid);
10406 		} else {
10407 			/*
10408 			 * If the special command is SCMD_READ,
10409 			 * the correct resid will be set later.
10410 			 */
10411 			if (attrib->get_cnt != NULL) {
10412 				resid = attrib->get_cnt(pkt->pkt_cdbp);
10413 			} else {
10414 				resid = bp->b_bcount;
10415 			}
10416 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10417 			    "st_decode_sense(special read):  resid=%ld\n",
10418 			    resid);
10419 		}
10420 	}
10421 
10422 	if ((un->un_state >= ST_STATE_OPEN) &&
10423 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
10424 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
10425 		    "Failed CDB", (char *)pkt->pkt_cdbp);
10426 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10427 		    "sense data", (char *)sensep, amt);
10428 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10429 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10430 		    bp->b_bcount, resid, pkt->pkt_resid);
10431 	}
10432 
10433 	switch (un->un_status = sensep->es_key) {
10434 	case KEY_NO_SENSE:
10435 		severity = SCSI_ERR_INFO;
10436 
10437 		/*
10438 		 * Erase, locate or rewind operation in progress, retry
10439 		 * ASC  ASCQ
10440 		 *  00   18    Erase operation in progress
10441 		 *  00   19    Locate operation in progress
10442 		 *  00   1A    Rewind operation in progress
10443 		 */
10444 		if (sensep->es_add_code == 0 &&
10445 		    ((sensep->es_qual_code == 0x18) ||
10446 		    (sensep->es_qual_code == 0x19) ||
10447 		    (sensep->es_qual_code == 0x1a))) {
10448 			rval = QUE_BUSY_COMMAND;
10449 			break;
10450 		}
10451 
10452 		goto common;
10453 
10454 	case KEY_RECOVERABLE_ERROR:
10455 		severity = SCSI_ERR_RECOVERED;
10456 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10457 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10458 			if (un->un_dp->options &
10459 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10460 				rval = QUE_LAST_COMMAND;
10461 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10462 				    severity, pos->lgclblkno,
10463 				    un->un_err_pos.lgclblkno, scsi_cmds,
10464 				    sensep);
10465 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10466 				    "Command will be retried\n");
10467 			} else {
10468 				severity = SCSI_ERR_FATAL;
10469 				rval = COMMAND_DONE_ERROR_RECOVERED;
10470 				ST_DO_ERRSTATS(un, st_softerrs);
10471 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10472 				    severity, pos->lgclblkno,
10473 				    un->un_err_pos.lgclblkno, scsi_cmds,
10474 				    sensep);
10475 			}
10476 			break;
10477 		}
10478 common:
10479 		/*
10480 		 * XXX only want reads to be stopped by filemarks.
10481 		 * Don't want them to be stopped by EOT.  EOT matters
10482 		 * only on write.
10483 		 */
10484 		if (sensep->es_filmk && !sensep->es_eom) {
10485 			rval = COMMAND_DONE;
10486 		} else if (sensep->es_eom) {
10487 			rval = COMMAND_DONE;
10488 		} else if (sensep->es_ili) {
10489 			/*
10490 			 * Fun with variable length record devices:
10491 			 * for specifying larger blocks sizes than the
10492 			 * actual physical record size.
10493 			 */
10494 			if (un->un_bsize == 0 && resid > 0) {
10495 				/*
10496 				 * XXX! Ugly.
10497 				 * The requested blocksize is > tape blocksize,
10498 				 * so this is ok, so we just return the
10499 				 * actual size xferred.
10500 				 */
10501 				pkt->pkt_resid = resid;
10502 				rval = COMMAND_DONE;
10503 			} else if (un->un_bsize == 0 && resid < 0) {
10504 				/*
10505 				 * The requested blocksize is < tape blocksize,
10506 				 * so this is not ok, so we err with ENOMEM
10507 				 */
10508 				rval = COMMAND_DONE_ERROR_RECOVERED;
10509 				st_bioerror(bp, ENOMEM);
10510 			} else {
10511 				ST_DO_ERRSTATS(un, st_softerrs);
10512 				severity = SCSI_ERR_FATAL;
10513 				rval = COMMAND_DONE_ERROR;
10514 				st_bioerror(bp, EINVAL);
10515 				un->un_running.pmode = invalid;
10516 			}
10517 		} else {
10518 			/*
10519 			 * we hope and pray for this just being
10520 			 * something we can ignore (ie. a
10521 			 * truly recoverable soft error)
10522 			 */
10523 			rval = COMMAND_DONE;
10524 		}
10525 		if (sensep->es_filmk) {
10526 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10527 			    "filemark\n");
10528 			un->un_status = SUN_KEY_EOF;
10529 			pos->eof = ST_EOF_PENDING;
10530 			st_set_pe_flag(un);
10531 		}
10532 
10533 		/*
10534 		 * ignore eom when reading, a fmk should terminate reading
10535 		 */
10536 		if ((sensep->es_eom) &&
10537 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10538 			if ((sensep->es_add_code == 0) &&
10539 			    (sensep->es_qual_code == 4)) {
10540 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10541 				    "bot\n");
10542 				un->un_status = SUN_KEY_BOT;
10543 				pos->eof = ST_NO_EOF;
10544 				pos->lgclblkno = 0;
10545 				pos->fileno = 0;
10546 				pos->blkno = 0;
10547 				if (pos->pmode != legacy)
10548 					pos->pmode = legacy;
10549 			} else {
10550 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10551 				    "eom\n");
10552 				un->un_status = SUN_KEY_EOT;
10553 				pos->eof = ST_EOM;
10554 			}
10555 			st_set_pe_flag(un);
10556 		}
10557 
10558 		break;
10559 
10560 	case KEY_ILLEGAL_REQUEST:
10561 
10562 		if (un->un_laststate >= ST_STATE_OPEN) {
10563 			ST_DO_ERRSTATS(un, st_softerrs);
10564 			severity = SCSI_ERR_FATAL;
10565 		} else {
10566 			severity = SCSI_ERR_INFO;
10567 		}
10568 		break;
10569 
10570 	case KEY_MEDIUM_ERROR:
10571 		ST_DO_ERRSTATS(un, st_harderrs);
10572 		severity = SCSI_ERR_FATAL;
10573 
10574 		/*
10575 		 * for (buffered) writes, a medium error must be fatal
10576 		 */
10577 		if (CDBP(pkt)->scc_cmd != SCMD_WRITE) {
10578 			rval = COMMAND_DONE_ERROR_RECOVERED;
10579 		}
10580 
10581 check_keys:
10582 		/*
10583 		 * attempt to process the keys in the presence of
10584 		 * other errors
10585 		 */
10586 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10587 			/*
10588 			 * Fun with variable length record devices:
10589 			 * for specifying larger blocks sizes than the
10590 			 * actual physical record size.
10591 			 */
10592 			if (un->un_bsize == 0 && resid > 0) {
10593 				/*
10594 				 * XXX! Ugly
10595 				 */
10596 				pkt->pkt_resid = resid;
10597 			} else if (un->un_bsize == 0 && resid < 0) {
10598 				st_bioerror(bp, EINVAL);
10599 			} else {
10600 				severity = SCSI_ERR_FATAL;
10601 				rval = COMMAND_DONE_ERROR;
10602 				st_bioerror(bp, EINVAL);
10603 			}
10604 		}
10605 		if (sensep->es_filmk) {
10606 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10607 			    "filemark\n");
10608 			un->un_status = SUN_KEY_EOF;
10609 			pos->eof = ST_EOF_PENDING;
10610 			st_set_pe_flag(un);
10611 		}
10612 
10613 		/*
10614 		 * ignore eom when reading, a fmk should terminate reading
10615 		 */
10616 		if ((sensep->es_eom) &&
10617 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10618 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10619 			un->un_status = SUN_KEY_EOT;
10620 			pos->eof = ST_EOM;
10621 			st_set_pe_flag(un);
10622 		}
10623 
10624 		break;
10625 
10626 	case KEY_VOLUME_OVERFLOW:
10627 		ST_DO_ERRSTATS(un, st_softerrs);
10628 		pos->eof = ST_EOM;
10629 		severity = SCSI_ERR_FATAL;
10630 		rval = COMMAND_DONE_ERROR;
10631 		goto check_keys;
10632 
10633 	case KEY_HARDWARE_ERROR:
10634 		ST_DO_ERRSTATS(un, st_harderrs);
10635 		severity = SCSI_ERR_FATAL;
10636 		rval = COMMAND_DONE_ERROR;
10637 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10638 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10639 		break;
10640 
10641 	case KEY_BLANK_CHECK:
10642 		ST_DO_ERRSTATS(un, st_softerrs);
10643 		severity = SCSI_ERR_INFO;
10644 
10645 		/*
10646 		 * if not a special request and some data was xferred then it
10647 		 * it is not an error yet
10648 		 */
10649 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10650 			/*
10651 			 * no error for read with or without data xferred
10652 			 */
10653 			un->un_status = SUN_KEY_EOT;
10654 			pos->eof = ST_EOT;
10655 			rval = COMMAND_DONE_ERROR;
10656 			st_set_pe_flag(un);
10657 			goto check_keys;
10658 		} else if (bp != un->un_sbufp &&
10659 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10660 			rval = COMMAND_DONE;
10661 		} else {
10662 			rval = COMMAND_DONE_ERROR_RECOVERED;
10663 		}
10664 
10665 		if (un->un_laststate >= ST_STATE_OPEN) {
10666 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10667 			    "blank check\n");
10668 			pos->eof = ST_EOM;
10669 		}
10670 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10671 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10672 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
10673 		    (un->un_dp->options & ST_KNOWS_EOD)) {
10674 			/*
10675 			 * we were doing a fast forward by skipping
10676 			 * multiple fmk at the time
10677 			 */
10678 			st_bioerror(bp, EIO);
10679 			severity = SCSI_ERR_RECOVERED;
10680 			rval	 = COMMAND_DONE;
10681 		}
10682 		st_set_pe_flag(un);
10683 		goto check_keys;
10684 
10685 	case KEY_WRITE_PROTECT:
10686 		if (st_wrongtapetype(un)) {
10687 			un->un_status = SUN_KEY_WRONGMEDIA;
10688 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10689 			    "wrong tape for writing- use DC6150 tape "
10690 			    "(or equivalent)\n");
10691 			severity = SCSI_ERR_UNKNOWN;
10692 		} else {
10693 			severity = SCSI_ERR_FATAL;
10694 		}
10695 		ST_DO_ERRSTATS(un, st_harderrs);
10696 		rval = COMMAND_DONE_ERROR;
10697 		st_bioerror(bp, EACCES);
10698 		break;
10699 
10700 	case KEY_UNIT_ATTENTION:
10701 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10702 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
10703 
10704 		un->un_unit_attention_flags = 1;
10705 		/*
10706 		 * If we have detected a Bus Reset and the tape
10707 		 * drive has been reserved.
10708 		 */
10709 		if (ST_RQSENSE->es_add_code == 0x29) {
10710 			rval = DEVICE_RESET;
10711 			if ((un->un_rsvd_status &
10712 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
10713 			    ST_RESERVE) {
10714 				un->un_rsvd_status |= ST_LOST_RESERVE;
10715 				ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
10716 				    "st_decode_sense: Lost Reservation\n");
10717 			}
10718 		}
10719 
10720 		/*
10721 		 * If this is a recovery command and retrable, retry.
10722 		 */
10723 		if (bp == un->un_recov_buf) {
10724 			severity = SCSI_ERR_INFO;
10725 			if (attrib->retriable &&
10726 			    (int)un->un_retry_ct++ < st_retry_count) {
10727 				rval = QUE_COMMAND;
10728 			} else {
10729 				rval = COMMAND_DONE_ERROR;
10730 			}
10731 			break; /* Don't set position invalid */
10732 		}
10733 		if (un->un_state <= ST_STATE_OPENING) {
10734 			/*
10735 			 * Look, the tape isn't open yet, now determine
10736 			 * if the cause is a BUS RESET, Save the file
10737 			 * and Block positions for the callers to
10738 			 * recover from the loss of position.
10739 			 */
10740 			severity = SCSI_ERR_INFO;
10741 			if ((pos->pmode != invalid) &&
10742 			    (rval == DEVICE_RESET) &&
10743 			    (un->un_restore_pos != 1)) {
10744 				un->un_save_fileno = pos->fileno;
10745 				un->un_save_blkno = pos->blkno;
10746 				un->un_restore_pos = 1;
10747 			}
10748 
10749 			if (attrib->retriable &&
10750 			    (int)un->un_retry_ct++ < st_retry_count) {
10751 				rval = QUE_COMMAND;
10752 			} else if (rval == DEVICE_RESET) {
10753 				break;
10754 			} else {
10755 				rval = COMMAND_DONE_ERROR;
10756 			}
10757 		/*
10758 		 * Means it thinks the mode parameters have changed.
10759 		 * This is the result of a reset clearing settings or
10760 		 * another initiator changing what we set.
10761 		 */
10762 		} else if (ST_RQSENSE->es_add_code == 0x2a) {
10763 			if (ST_RQSENSE->es_qual_code == 0x1) {
10764 				/* Error recovery will modeselect and retry. */
10765 				rval = DEVICE_TAMPER;
10766 				severity = SCSI_ERR_INFO;
10767 				break; /* don't set position invalid */
10768 			}
10769 			if (ST_RQSENSE->es_qual_code == 0x0 ||
10770 			    ST_RQSENSE->es_qual_code == 0x2 ||
10771 			    ST_RQSENSE->es_qual_code == 0x3 ||
10772 			    ST_RQSENSE->es_qual_code == 0x4 ||
10773 			    ST_RQSENSE->es_qual_code == 0x5 ||
10774 			    ST_RQSENSE->es_qual_code == 0x6 ||
10775 			    ST_RQSENSE->es_qual_code == 0x7) {
10776 				rval = DEVICE_TAMPER;
10777 				severity = SCSI_ERR_INFO;
10778 			}
10779 		} else if (ST_RQSENSE->es_add_code == 0x28 &&
10780 		    ((ST_RQSENSE->es_qual_code == 0x0) ||
10781 		    ST_RQSENSE->es_qual_code == 0x5)) {
10782 			/*
10783 			 * Not Ready to Ready change, Media may have changed.
10784 			 */
10785 			rval = DEVICE_TAMPER;
10786 			severity = SCSI_ERR_RETRYABLE;
10787 		} else {
10788 			if (rval != DEVICE_RESET) {
10789 				rval = COMMAND_DONE_ERROR;
10790 			} else {
10791 				/*
10792 				 * Returning DEVICE_RESET will call
10793 				 * error recovery.
10794 				 */
10795 				severity = SCSI_ERR_INFO;
10796 				break; /* don't set position invalid */
10797 			}
10798 			/*
10799 			 * Check if it is an Unexpected Unit Attention.
10800 			 * If state is >= ST_STATE_OPEN, we have
10801 			 * already done the initialization .
10802 			 * In this case it is Fatal Error
10803 			 * since no further reading/writing
10804 			 * can be done with fileno set to < 0.
10805 			 */
10806 			if (un->un_state >= ST_STATE_OPEN) {
10807 				ST_DO_ERRSTATS(un, st_harderrs);
10808 				severity = SCSI_ERR_FATAL;
10809 			} else {
10810 				severity = SCSI_ERR_INFO;
10811 			}
10812 		}
10813 
10814 		pos->pmode = invalid;
10815 
10816 		break;
10817 
10818 	case KEY_NOT_READY:
10819 		/*
10820 		 * If in process of getting ready retry.
10821 		 */
10822 		if (sensep->es_add_code  == 0x04 &&
10823 		    sensep->es_qual_code == 0x01 &&
10824 		    un->un_retry_ct++ < st_retry_count) {
10825 			rval = QUE_COMMAND;
10826 			severity = SCSI_ERR_INFO;
10827 		} else {
10828 			/* give up */
10829 			rval = COMMAND_DONE_ERROR;
10830 			severity = SCSI_ERR_FATAL;
10831 		}
10832 
10833 		/*
10834 		 * If this was an error and after device opened
10835 		 * do error stats.
10836 		 */
10837 		if (rval == COMMAND_DONE_ERROR &&
10838 		    un->un_state > ST_STATE_OPENING) {
10839 			ST_DO_ERRSTATS(un, st_harderrs);
10840 		}
10841 
10842 		if (ST_RQSENSE->es_add_code == 0x3a) {
10843 			if (st_error_level >= SCSI_ERR_FATAL)
10844 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
10845 				    "Tape not inserted in drive\n");
10846 			un->un_mediastate = MTIO_EJECTED;
10847 			cv_broadcast(&un->un_state_cv);
10848 		}
10849 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
10850 		    (rval != QUE_COMMAND))
10851 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10852 		break;
10853 
10854 	case KEY_ABORTED_COMMAND:
10855 		/* XXX Do drives return this when they see a lost light? */
10856 		/* Testing would say yes */
10857 
10858 		if (un->un_retry_ct++ < st_retry_count) {
10859 			rval = ATTEMPT_RETRY;
10860 			severity = SCSI_ERR_RETRYABLE;
10861 			goto check_keys;
10862 		}
10863 		/*
10864 		 * Probably a parity error...
10865 		 * if we retry here then this may cause data to be
10866 		 * written twice or data skipped during reading
10867 		 */
10868 		ST_DO_ERRSTATS(un, st_harderrs);
10869 		severity = SCSI_ERR_FATAL;
10870 		rval = COMMAND_DONE_ERROR;
10871 		goto check_keys;
10872 
10873 	default:
10874 		/*
10875 		 * Undecoded sense key.	 Try retries and hope
10876 		 * that will fix the problem.  Otherwise, we're
10877 		 * dead.
10878 		 */
10879 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10880 		    "Unhandled Sense Key '%s'\n",
10881 		    sense_keys[un->un_status]);
10882 		ST_DO_ERRSTATS(un, st_harderrs);
10883 		severity = SCSI_ERR_FATAL;
10884 		rval = COMMAND_DONE_ERROR;
10885 		goto check_keys;
10886 	}
10887 
10888 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
10889 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
10890 	    (un->un_laststate > ST_STATE_OPENING) &&
10891 	    (severity >= st_error_level))) {
10892 
10893 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
10894 		    pos->lgclblkno, un->un_err_pos.lgclblkno,
10895 		    scsi_cmds, sensep);
10896 		if (sensep->es_filmk) {
10897 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10898 			    "File Mark Detected\n");
10899 		}
10900 		if (sensep->es_eom) {
10901 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10902 			    "End-of-Media Detected\n");
10903 		}
10904 		if (sensep->es_ili) {
10905 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10906 			    "Incorrect Length Indicator Set\n");
10907 		}
10908 	}
10909 	get_error = geterror(bp);
10910 	if (((rval == COMMAND_DONE_ERROR) ||
10911 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
10912 	    ((get_error == EIO) || (get_error == 0))) {
10913 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
10914 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
10915 		if (un->un_rqs_state & ST_RQS_READ) {
10916 			un->un_rqs_state &= ~(ST_RQS_READ);
10917 		} else {
10918 			un->un_rqs_state |= ST_RQS_OVR;
10919 		}
10920 	}
10921 
10922 	return (rval);
10923 }
10924 
10925 
10926 static int
10927 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
10928 {
10929 	int status = TRAN_ACCEPT;
10930 
10931 	mutex_enter(ST_MUTEX);
10932 
10933 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
10934 
10935 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10936 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
10937 
10938 	/*
10939 	 * Check to see if we hit the retry timeout. We check to make sure
10940 	 * this is the first one on the runq and make sure we have not
10941 	 * queued up any more, so this one has to be the last on the list
10942 	 * also. If it is not, we have to fail.  If it is not the first, but
10943 	 * is the last we are in trouble anyway, as we are in the interrupt
10944 	 * context here.
10945 	 */
10946 	if (((int)un->un_retry_ct > st_retry_count) ||
10947 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
10948 		goto exit;
10949 	}
10950 
10951 	if (un->un_throttle) {
10952 		un->un_last_throttle = un->un_throttle;
10953 		un->un_throttle = 0;
10954 	}
10955 
10956 	/*
10957 	 * Here we know : bp is the first and last one on the runq
10958 	 * it is not necessary to put it back on the head of the
10959 	 * waitq and then move from waitq to runq. Save this queuing
10960 	 * and call scsi_transport.
10961 	 */
10962 	ST_CDB(ST_DEVINFO, "Retry lcmd CDB", (char *)BP_PKT(bp)->pkt_cdbp);
10963 
10964 	status = st_transport(un, BP_PKT(bp));
10965 
10966 	if (status == TRAN_ACCEPT) {
10967 		un->un_tran_retry_ct = 0;
10968 		if (un->un_last_throttle) {
10969 			un->un_throttle = un->un_last_throttle;
10970 		}
10971 		mutex_exit(ST_MUTEX);
10972 
10973 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10974 		    "restart transport \n");
10975 		return (0);
10976 	}
10977 
10978 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
10979 	mutex_exit(ST_MUTEX);
10980 
10981 	if (status == TRAN_BUSY) {
10982 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
10983 			return (0);
10984 		}
10985 	}
10986 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10987 	    "restart transport rejected\n");
10988 	mutex_enter(ST_MUTEX);
10989 	ST_DO_ERRSTATS(un, st_transerrs);
10990 	if (un->un_last_throttle) {
10991 		un->un_throttle = un->un_last_throttle;
10992 	}
10993 exit:
10994 	mutex_exit(ST_MUTEX);
10995 	return (-1);
10996 }
10997 
10998 static int
10999 st_wrongtapetype(struct scsi_tape *un)
11000 {
11001 
11002 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
11003 
11004 	ASSERT(mutex_owned(ST_MUTEX));
11005 
11006 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
11007 
11008 	/*
11009 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
11010 	 */
11011 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
11012 		switch (un->un_dp->type) {
11013 		case ST_TYPE_WANGTEK:
11014 		case ST_TYPE_ARCHIVE:
11015 			/*
11016 			 * If this really worked, we could go off of
11017 			 * the density codes set in the modesense
11018 			 * page. For this drive, 0x10 == QIC-120,
11019 			 * 0xf == QIC-150, and 0x5 should be for
11020 			 * both QIC-24 and, maybe, QIC-11. However,
11021 			 * the h/w doesn't do what the manual says
11022 			 * that it should, so we'll key off of
11023 			 * getting a WRITE PROTECT error AND wp *not*
11024 			 * set in the mode sense information.
11025 			 */
11026 			/*
11027 			 * XXX but we already know that status is
11028 			 * write protect, so don't check it again.
11029 			 */
11030 
11031 			if (un->un_status == KEY_WRITE_PROTECT &&
11032 			    un->un_mspl->wp == 0) {
11033 				return (1);
11034 			}
11035 			break;
11036 		default:
11037 			break;
11038 		}
11039 	}
11040 	return (0);
11041 }
11042 
11043 static errstate
11044 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
11045 {
11046 	errstate action;
11047 
11048 	ST_FUNC(ST_DEVINFO, st_check_error);
11049 
11050 	ASSERT(mutex_owned(ST_MUTEX));
11051 
11052 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
11053 
11054 	if (SCBP_C(pkt) == STATUS_RESERVATION_CONFLICT) {
11055 		action = COMMAND_DONE_EACCES;
11056 		un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
11057 	} else if (SCBP(pkt)->sts_busy) {
11058 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
11059 		if ((int)un->un_retry_ct++ < st_retry_count) {
11060 			action = QUE_BUSY_COMMAND;
11061 		} else if ((un->un_rsvd_status &
11062 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
11063 			/*
11064 			 * If this is a command done before reserve is done
11065 			 * don't reset.
11066 			 */
11067 			action = COMMAND_DONE_ERROR;
11068 		} else {
11069 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11070 			    "unit busy too long\n");
11071 			(void) st_reset(un, RESET_ALL);
11072 			action = COMMAND_DONE_ERROR;
11073 		}
11074 	} else if (SCBP(pkt)->sts_chk) {
11075 		/*
11076 		 * we should only get here if the auto rqsense failed
11077 		 * thru a uscsi cmd without autorequest sense
11078 		 * so we just try again
11079 		 */
11080 		action = QUE_SENSE;
11081 	} else {
11082 		action = COMMAND_DONE;
11083 	}
11084 	return (action);
11085 }
11086 
11087 static void
11088 st_calc_bnum(struct scsi_tape *un, struct buf *bp, struct scsi_pkt *pkt)
11089 {
11090 	int nblks;
11091 	long count;
11092 	recov_info *ri = (recov_info *)pkt->pkt_private;
11093 	cmd_attribute const *attrib;
11094 
11095 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
11096 
11097 	ASSERT(mutex_owned(ST_MUTEX));
11098 
11099 	if (ri->privatelen == sizeof (recov_info)) {
11100 		attrib = ri->cmd_attrib;
11101 		ASSERT(attrib->recov_pos_type == POS_EXPECTED);
11102 		ASSERT(attrib->chg_tape_pos);
11103 	} else {
11104 		ri = NULL;
11105 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
11106 	}
11107 
11108 	count = bp->b_bcount - bp->b_resid;
11109 
11110 	/* If variable block mode */
11111 	if (un->un_bsize == 0) {
11112 		nblks = ((count == 0) ? 0 : 1);
11113 		un->un_kbytes_xferred += (count / ONE_K);
11114 	} else {
11115 		nblks = (count / un->un_bsize);
11116 		un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
11117 	}
11118 
11119 	/*
11120 	 * If some command failed after this one started and it seems
11121 	 * to have finshed without error count the position.
11122 	 */
11123 	if (un->un_persistence && un->un_persist_errors) {
11124 		ASSERT(un->un_pos.pmode != invalid);
11125 	}
11126 
11127 	if (attrib->chg_tape_direction == DIR_FORW) {
11128 		un->un_pos.blkno += nblks;
11129 		un->un_pos.lgclblkno += nblks;
11130 	} else if (attrib->chg_tape_direction == DIR_REVC) {
11131 		un->un_pos.blkno -= nblks;
11132 		un->un_pos.lgclblkno -= nblks;
11133 	} else {
11134 		ASSERT(0);
11135 	}
11136 
11137 	/* recovery disabled */
11138 	if (ri == NULL) {
11139 		un->un_running.pmode = invalid;
11140 		return;
11141 	}
11142 
11143 	/*
11144 	 * If we didn't just read a filemark.
11145 	 */
11146 	if (un->un_pos.eof != ST_EOF_PENDING) {
11147 		ASSERT(nblks != 0);
11148 		/*
11149 		 * If Previously calulated expected position does not match
11150 		 * debug the expected position.
11151 		 */
11152 		if ((ri->pos.pmode != invalid) && nblks &&
11153 		    ((un->un_pos.blkno != ri->pos.blkno) ||
11154 		    (un->un_pos.lgclblkno != ri->pos.lgclblkno))) {
11155 #ifdef STDEBUG
11156 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11157 			    "Expected", &ri->pos);
11158 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11159 			    "But Got", &un->un_pos);
11160 #endif
11161 			un->un_running.pmode = invalid;
11162 		}
11163 	} else {
11164 		ASSERT(nblks == 0);
11165 		if (un->un_running.pmode != invalid) {
11166 			/*
11167 			 * blkno and lgclblkno already counted in
11168 			 * st_add_recovery_info_to_pkt(). Since a block was not
11169 			 * read and a filemark was.
11170 			 */
11171 			if (attrib->chg_tape_direction == DIR_FORW) {
11172 				un->un_running.fileno++;
11173 				un->un_running.blkno = 0;
11174 			} else if (attrib->chg_tape_direction == DIR_REVC) {
11175 				un->un_running.fileno--;
11176 				un->un_running.blkno = INF;
11177 			}
11178 		}
11179 	}
11180 }
11181 
11182 static void
11183 st_set_state(struct scsi_tape *un, struct buf *bp)
11184 {
11185 	struct scsi_pkt *sp = BP_PKT(bp);
11186 	struct uscsi_cmd *ucmd;
11187 
11188 	ST_FUNC(ST_DEVINFO, st_set_state);
11189 
11190 	ASSERT(mutex_owned(ST_MUTEX));
11191 
11192 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11193 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
11194 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
11195 
11196 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
11197 #ifdef STDEBUG
11198 		if (DEBUGGING && sp->pkt_resid) {
11199 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11200 			    "pkt_resid %ld bcount %ld\n",
11201 			    sp->pkt_resid, bp->b_bcount);
11202 		}
11203 #endif
11204 		bp->b_resid = sp->pkt_resid;
11205 		st_calc_bnum(un, bp, sp);
11206 		if (bp->b_flags & B_READ) {
11207 			un->un_lastop = ST_OP_READ;
11208 			un->un_fmneeded = 0;
11209 		} else {
11210 			un->un_lastop = ST_OP_WRITE;
11211 			if (un->un_dp->options & ST_REEL) {
11212 				un->un_fmneeded = 2;
11213 			} else {
11214 				un->un_fmneeded = 1;
11215 			}
11216 		}
11217 		/*
11218 		 * all is honky dory at this point, so let's
11219 		 * readjust the throttle, to increase speed, if we
11220 		 * have not throttled down.
11221 		 */
11222 		if (un->un_throttle) {
11223 			un->un_throttle = un->un_max_throttle;
11224 		}
11225 	} else {
11226 		optype new_lastop;
11227 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
11228 
11229 		un->un_lastop = ST_OP_CTL;
11230 
11231 		switch (cmd) {
11232 		case SCMD_WRITE:
11233 		case SCMD_WRITE_G4:
11234 			bp->b_resid = sp->pkt_resid;
11235 			new_lastop = ST_OP_WRITE;
11236 			st_calc_bnum(un, bp, sp);
11237 			if (un->un_dp->options & ST_REEL) {
11238 				un->un_fmneeded = 2;
11239 			} else {
11240 				un->un_fmneeded = 1;
11241 			}
11242 			break;
11243 		case SCMD_READ:
11244 		case SCMD_READ_G4:
11245 			bp->b_resid = sp->pkt_resid;
11246 			new_lastop = ST_OP_READ;
11247 			st_calc_bnum(un, bp, sp);
11248 			un->un_fmneeded = 0;
11249 			break;
11250 		case SCMD_WRITE_FILE_MARK_G4:
11251 		case SCMD_WRITE_FILE_MARK:
11252 		{
11253 			int fmdone;
11254 
11255 			if (un->un_pos.eof != ST_EOM) {
11256 				un->un_pos.eof = ST_NO_EOF;
11257 			}
11258 			fmdone = (bp->b_bcount - bp->b_resid);
11259 			if (fmdone > 0) {
11260 				un->un_lastop = new_lastop = ST_OP_WEOF;
11261 				un->un_pos.lgclblkno += fmdone;
11262 				un->un_pos.fileno += fmdone;
11263 				un->un_pos.blkno = 0;
11264 			} else {
11265 				new_lastop = ST_OP_CTL;
11266 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11267 				    "Flushed buffer\n");
11268 			}
11269 			if (fmdone > un->un_fmneeded) {
11270 				un->un_fmneeded = 0;
11271 			} else {
11272 				un->un_fmneeded -= fmdone;
11273 			}
11274 			break;
11275 		}
11276 		case SCMD_REWIND:
11277 			un->un_pos.eof = ST_NO_EOF;
11278 			un->un_pos.fileno = 0;
11279 			un->un_pos.blkno = 0;
11280 			un->un_pos.lgclblkno = 0;
11281 			if (un->un_pos.pmode != legacy)
11282 				un->un_pos.pmode = legacy;
11283 			new_lastop = ST_OP_CTL;
11284 			un->un_restore_pos = 0;
11285 			break;
11286 
11287 		case SCMD_SPACE:
11288 		case SCMD_SPACE_G4:
11289 		{
11290 			int64_t count;
11291 			int64_t resid;
11292 			int64_t done;
11293 			cmd_attribute const *attrib;
11294 			recov_info *ri = (recov_info *)sp->pkt_private;
11295 
11296 			if (ri->privatelen == sizeof (recov_info)) {
11297 				attrib = ri->cmd_attrib;
11298 			} else {
11299 				attrib =
11300 				    st_lookup_cmd_attribute(sp->pkt_cdbp[0]);
11301 			}
11302 
11303 			resid = (int64_t)SPACE_CNT(bp->b_resid);
11304 			count = (int64_t)attrib->get_cnt(sp->pkt_cdbp);
11305 
11306 			if (count >= 0) {
11307 				done = (count - resid);
11308 			} else {
11309 				done = ((-count) - resid);
11310 			}
11311 			if (done > 0) {
11312 				un->un_lastop = new_lastop = ST_OP_CTL;
11313 			} else {
11314 				new_lastop = ST_OP_CTL;
11315 			}
11316 
11317 			ST_SPAC(ST_DEVINFO, st_label, SCSI_DEBUG,
11318 			    "space cmd: cdb[1] = %s\n"
11319 			    "space data:       = 0x%lx\n"
11320 			    "space count:      = %"PRId64"\n"
11321 			    "space resid:      = %"PRId64"\n"
11322 			    "spaces done:      = %"PRId64"\n"
11323 			    "fileno before     = %d\n"
11324 			    "blkno before      = %d\n",
11325 			    space_strs[sp->pkt_cdbp[1] & 7],
11326 			    bp->b_bcount,
11327 			    count, resid, done,
11328 			    un->un_pos.fileno, un->un_pos.blkno);
11329 
11330 			switch (sp->pkt_cdbp[1]) {
11331 			case SPACE_TYPE(SP_FLM):
11332 				/* Space file forward */
11333 				if (count >= 0) {
11334 					if (un->un_pos.eof <= ST_EOF) {
11335 						un->un_pos.eof = ST_NO_EOF;
11336 					}
11337 					un->un_pos.fileno += done;
11338 					un->un_pos.blkno = 0;
11339 					break;
11340 				}
11341 				/* Space file backward */
11342 				if (done > un->un_pos.fileno) {
11343 					un->un_pos.fileno = 0;
11344 					un->un_pos.blkno = 0;
11345 				} else {
11346 					un->un_pos.fileno -= done;
11347 					un->un_pos.blkno = INF;
11348 					un->un_running.pmode = invalid;
11349 				}
11350 				break;
11351 			case SPACE_TYPE(SP_BLK):
11352 				/* Space block forward */
11353 				if (count >= 0) {
11354 					un->un_pos.blkno += done;
11355 					break;
11356 				}
11357 				/* Space block backward */
11358 				if (un->un_pos.eof >= ST_EOF_PENDING) {
11359 				/*
11360 				 * we stepped back into
11361 				 * a previous file; we are not
11362 				 * making an effort to pretend that
11363 				 * we are still in the current file
11364 				 * ie. logical == physical position
11365 				 * and leave it to st_ioctl to correct
11366 				 */
11367 					if (done > un->un_pos.blkno) {
11368 						un->un_pos.blkno = 0;
11369 					} else {
11370 						un->un_pos.fileno--;
11371 						un->un_pos.blkno = INF;
11372 						un->un_running.pmode = invalid;
11373 					}
11374 				} else {
11375 					un->un_pos.blkno -= done;
11376 				}
11377 				break;
11378 			case SPACE_TYPE(SP_SQFLM):
11379 				un->un_pos.pmode = logical;
11380 				un->un_pos.blkno = 0;
11381 				un->un_lastop = new_lastop = ST_OP_CTL;
11382 				break;
11383 			case SPACE_TYPE(SP_EOD):
11384 				un->un_pos.pmode = logical;
11385 				un->un_pos.eof = ST_EOM;
11386 				un->un_status = KEY_BLANK_CHECK;
11387 				break;
11388 			default:
11389 				un->un_pos.pmode = invalid;
11390 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11391 				    "Unsupported space cmd: %s\n",
11392 				    space_strs[sp->pkt_cdbp[1] & 7]);
11393 
11394 				un->un_lastop = new_lastop = ST_OP_CTL;
11395 			}
11396 
11397 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11398 			    "after_space rs %"PRId64" fil %d blk %d\n",
11399 			    resid, un->un_pos.fileno, un->un_pos.blkno);
11400 
11401 			break;
11402 		}
11403 		case SCMD_LOAD:
11404 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
11405 				un->un_pos.fileno = 0;
11406 				if (un->un_pos.pmode != legacy)
11407 					un->un_pos.pmode = legacy;
11408 			} else {
11409 				un->un_state = ST_STATE_OFFLINE;
11410 				un->un_pos.pmode = invalid;
11411 			}
11412 			un->un_density_known = 0;
11413 			un->un_pos.eof = ST_NO_EOF;
11414 			un->un_pos.blkno = 0;
11415 			un->un_lastop = new_lastop = ST_OP_CTL;
11416 			break;
11417 		case SCMD_ERASE:
11418 			un->un_pos.eof = ST_NO_EOF;
11419 			un->un_pos.blkno = 0;
11420 			un->un_pos.fileno = 0;
11421 			un->un_pos.lgclblkno = 0;
11422 			if (un->un_pos.pmode != legacy)
11423 				un->un_pos.pmode = legacy;
11424 			new_lastop = ST_OP_CTL;
11425 			break;
11426 		case SCMD_RESERVE:
11427 			un->un_rsvd_status |= ST_RESERVE;
11428 			un->un_rsvd_status &=
11429 			    ~(ST_RELEASE | ST_LOST_RESERVE |
11430 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11431 			new_lastop = un->un_lastop;
11432 			break;
11433 		case SCMD_RELEASE:
11434 			un->un_rsvd_status |= ST_RELEASE;
11435 			un->un_rsvd_status &=
11436 			    ~(ST_RESERVE | ST_LOST_RESERVE |
11437 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11438 			new_lastop = ST_OP_CTL;
11439 			break;
11440 		case SCMD_PERSISTENT_RESERVE_IN:
11441 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11442 			    "PGR_IN command\n");
11443 			break;
11444 		case SCMD_PERSISTENT_RESERVE_OUT:
11445 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
11446 			case ST_SA_SCSI3_RESERVE:
11447 			case ST_SA_SCSI3_PREEMPT:
11448 			case ST_SA_SCSI3_PREEMPTANDABORT:
11449 				un->un_rsvd_status |=
11450 				    ST_APPLICATION_RESERVATIONS;
11451 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11452 				    "PGR Reserve and set: entering"
11453 				    " ST_APPLICATION_RESERVATIONS mode");
11454 				break;
11455 			case ST_SA_SCSI3_RELEASE:
11456 			case ST_SA_SCSI3_CLEAR:
11457 				un->un_rsvd_status &=
11458 				    ~ST_APPLICATION_RESERVATIONS;
11459 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11460 				    "PGR Release and reset: exiting"
11461 				    " ST_APPLICATION_RESERVATIONS mode");
11462 				break;
11463 			}
11464 			break;
11465 		case SCMD_TEST_UNIT_READY:
11466 		case SCMD_READ_BLKLIM:
11467 		case SCMD_REQUEST_SENSE:
11468 		case SCMD_INQUIRY:
11469 		case SCMD_RECOVER_BUF:
11470 		case SCMD_MODE_SELECT:
11471 		case SCMD_MODE_SENSE:
11472 		case SCMD_DOORLOCK:
11473 		case SCMD_READ_BUFFER:
11474 		case SCMD_REPORT_DENSITIES:
11475 		case SCMD_LOG_SELECT_G1:
11476 		case SCMD_LOG_SENSE_G1:
11477 		case SCMD_REPORT_LUNS:
11478 		case SCMD_READ_ATTRIBUTE:
11479 		case SCMD_WRITE_ATTRIBUTE:
11480 		case SCMD_SVC_ACTION_IN_G5:
11481 			new_lastop = ST_OP_CTL;
11482 			break;
11483 		case SCMD_READ_POSITION:
11484 			new_lastop = ST_OP_CTL;
11485 			/*
11486 			 * Only if the buf used was un_sbufp.
11487 			 * Among other things the prevents read positions used
11488 			 * as part of error recovery from messing up our
11489 			 * current position as they will use un_recov_buf.
11490 			 */
11491 			if (USCSI_CMD(bp)) {
11492 				(void) st_get_read_pos(un, bp);
11493 			}
11494 			break;
11495 		case SCMD_LOCATE:
11496 		case SCMD_LOCATE_G4:
11497 			/* Locate makes position mode no longer legacy */
11498 			un->un_lastop = new_lastop = ST_OP_CTL;
11499 			break;
11500 		default:
11501 			/*
11502 			 * Unknown command, If was USCSI and USCSI_SILENT
11503 			 * flag was not set, set position to unknown.
11504 			 */
11505 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
11506 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
11507 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11508 				    "unknown cmd 0x%X caused loss of state\n",
11509 				    cmd);
11510 			} else {
11511 				break;
11512 			}
11513 			/* FALLTHROUGH */
11514 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
11515 			un->un_pos.pmode = invalid;
11516 			un->un_lastop = new_lastop = ST_OP_CTL;
11517 			break;
11518 		}
11519 
11520 		/* new_lastop should have been changed */
11521 		ASSERT(new_lastop != ST_OP_NIL);
11522 
11523 		/* If un_lastop should copy new_lastop  */
11524 		if (((un->un_lastop == ST_OP_WRITE) ||
11525 		    (un->un_lastop == ST_OP_WEOF)) &&
11526 		    new_lastop != ST_OP_CTL) {
11527 			un->un_lastop = new_lastop;
11528 		}
11529 	}
11530 
11531 	/*
11532 	 * In the st driver we have a logical and physical file position.
11533 	 * Under BSD behavior, when you get a zero read, the logical position
11534 	 * is before the filemark but after the last record of the file.
11535 	 * The physical position is after the filemark. MTIOCGET should always
11536 	 * return the logical file position.
11537 	 *
11538 	 * The next read gives a silent skip to the next file.
11539 	 * Under SVR4, the logical file position remains before the filemark
11540 	 * until the file is closed or a space operation is performed.
11541 	 * Hence set err_resid and err_file before changing fileno if case
11542 	 * BSD Behaviour.
11543 	 */
11544 	un->un_err_resid = bp->b_resid;
11545 	COPY_POS(&un->un_err_pos, &un->un_pos);
11546 	un->un_retry_ct = 0;
11547 
11548 
11549 	/*
11550 	 * If we've seen a filemark via the last read operation
11551 	 * advance the file counter, but mark things such that
11552 	 * the next read operation gets a zero count. We have
11553 	 * to put this here to handle the case of sitting right
11554 	 * at the end of a tape file having seen the file mark,
11555 	 * but the tape is closed and then re-opened without
11556 	 * any further i/o. That is, the position information
11557 	 * must be updated before a close.
11558 	 */
11559 
11560 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
11561 		/*
11562 		 * If we're a 1/2" tape, and we get a filemark
11563 		 * right on block 0, *AND* we were not in the
11564 		 * first file on the tape, and we've hit logical EOM.
11565 		 * We'll mark the state so that later we do the
11566 		 * right thing (in st_close(), st_strategy() or
11567 		 * st_ioctl()).
11568 		 *
11569 		 */
11570 		if ((un->un_dp->options & ST_REEL) &&
11571 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
11572 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
11573 			un->un_pos.eof = ST_EOT_PENDING;
11574 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11575 			    "eot pending\n");
11576 			un->un_pos.fileno++;
11577 			un->un_pos.blkno = 0;
11578 		} else if (BSD_BEHAVIOR) {
11579 			/*
11580 			 * If the read of the filemark was a side effect
11581 			 * of reading some blocks (i.e., data was actually
11582 			 * read), then the EOF mark is pending and the
11583 			 * bump into the next file awaits the next read
11584 			 * operation (which will return a zero count), or
11585 			 * a close or a space operation, else the bump
11586 			 * into the next file occurs now.
11587 			 */
11588 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11589 			    "resid=%lx, bcount=%lx\n",
11590 			    bp->b_resid, bp->b_bcount);
11591 
11592 			if (bp->b_resid != bp->b_bcount) {
11593 				un->un_pos.eof = ST_EOF;
11594 			} else {
11595 				un->un_silent_skip = 1;
11596 				un->un_pos.eof = ST_NO_EOF;
11597 				un->un_pos.fileno++;
11598 				un->un_pos.lgclblkno++;
11599 				un->un_save_blkno = un->un_pos.blkno;
11600 				un->un_pos.blkno = 0;
11601 			}
11602 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11603 			    "eof of file %d, eof=%d\n",
11604 			    un->un_pos.fileno, un->un_pos.eof);
11605 		} else if (SVR4_BEHAVIOR) {
11606 			/*
11607 			 * If the read of the filemark was a side effect
11608 			 * of reading some blocks (i.e., data was actually
11609 			 * read), then the next read should return 0
11610 			 */
11611 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11612 			    "resid=%lx, bcount=%lx\n",
11613 			    bp->b_resid, bp->b_bcount);
11614 			if (bp->b_resid == bp->b_bcount) {
11615 				un->un_pos.eof = ST_EOF;
11616 			}
11617 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11618 			    "eof of file=%d, eof=%d\n",
11619 			    un->un_pos.fileno, un->un_pos.eof);
11620 		}
11621 	}
11622 }
11623 
11624 /*
11625  * set the correct un_errno, to take corner cases into consideration
11626  */
11627 static void
11628 st_set_pe_errno(struct scsi_tape *un)
11629 {
11630 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
11631 
11632 	ASSERT(mutex_owned(ST_MUTEX));
11633 
11634 	/* if errno is already set, don't reset it */
11635 	if (un->un_errno)
11636 		return;
11637 
11638 	/* here un_errno == 0 */
11639 	/*
11640 	 * if the last transfer before flushing all the
11641 	 * waiting I/O's, was 0 (resid = count), then we
11642 	 * want to give the user an error on all the rest,
11643 	 * so here.  If there was a transfer, we set the
11644 	 * resid and counts to 0, and let it drop through,
11645 	 * giving a zero return.  the next I/O will then
11646 	 * give an error.
11647 	 */
11648 	if (un->un_last_resid == un->un_last_count) {
11649 		switch (un->un_pos.eof) {
11650 		case ST_EOM:
11651 			un->un_errno = ENOMEM;
11652 			break;
11653 		case ST_EOT:
11654 		case ST_EOF:
11655 			un->un_errno = EIO;
11656 			break;
11657 		}
11658 	} else {
11659 		/*
11660 		 * we know they did not have a zero, so make
11661 		 * sure they get one
11662 		 */
11663 		un->un_last_resid = un->un_last_count = 0;
11664 	}
11665 }
11666 
11667 
11668 /*
11669  * send in a marker pkt to terminate flushing of commands by BBA (via
11670  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
11671  */
11672 static void
11673 st_hba_unflush(struct scsi_tape *un)
11674 {
11675 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
11676 
11677 	ASSERT(mutex_owned(ST_MUTEX));
11678 
11679 	if (!un->un_flush_on_errors)
11680 		return;
11681 
11682 #ifdef FLUSH_ON_ERRORS
11683 
11684 	if (!un->un_mkr_pkt) {
11685 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
11686 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
11687 
11688 		/* we slept, so it must be there */
11689 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
11690 	}
11691 
11692 	st_transport(un, un->un_mkr_pkt);
11693 #endif
11694 }
11695 
11696 static char *
11697 st_print_scsi_cmd(char cmd)
11698 {
11699 	char tmp[64];
11700 	char *cpnt;
11701 
11702 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
11703 	/* tmp goes out of scope on return and caller sees garbage */
11704 	if (cpnt == tmp) {
11705 		cpnt = "Unknown Command";
11706 	}
11707 	return (cpnt);
11708 }
11709 
11710 static void
11711 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
11712     char *title, char *cdb)
11713 {
11714 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
11715 	char buf[256];
11716 	struct scsi_tape *un;
11717 	int instance = ddi_get_instance(dip);
11718 
11719 	un = ddi_get_soft_state(st_state, instance);
11720 
11721 	ST_FUNC(dip, st_print_cdb);
11722 
11723 #ifdef STDEBUG
11724 	if ((st_debug & 0x180) == 0x100) {
11725 		scsi_log(dip, label, level, "node %s cmd %s\n",
11726 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
11727 		return;
11728 	}
11729 #endif
11730 	(void) sprintf(buf, "%s for cmd(%s)", title, st_print_scsi_cmd(*cdb));
11731 	st_clean_print(dip, label, level, buf, cdb, len);
11732 }
11733 
11734 static void
11735 st_clean_print(dev_info_t *dev, char *label, uint_t level,
11736     char *title, char *data, int len)
11737 {
11738 	int	i;
11739 	int 	c;
11740 	char	*format;
11741 	char	buf[256];
11742 	uchar_t	byte;
11743 
11744 	ST_FUNC(dev, st_clean_print);
11745 
11746 
11747 	(void) sprintf(buf, "%s:\n", title);
11748 	scsi_log(dev, label, level, "%s", buf);
11749 	level = CE_CONT;
11750 	for (i = 0; i < len; ) {
11751 		buf[0] = 0;
11752 		for (c = 0; c < 8 && i < len; c++, i++) {
11753 			byte = (uchar_t)data[i];
11754 			if (byte < 0x10)
11755 				format = "0x0%x ";
11756 			else
11757 				format = "0x%x ";
11758 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
11759 		}
11760 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
11761 
11762 		scsi_log(dev, label, level, "%s\n", buf);
11763 	}
11764 }
11765 
11766 /*
11767  * Conditionally enabled debugging
11768  */
11769 #ifdef	STDEBUG
11770 static void
11771 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
11772 {
11773 	char tmpbuf[64];
11774 
11775 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
11776 
11777 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11778 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
11779 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
11780 	    count, count,
11781 	    wait == ASYNC_CMD ? "a" : "");
11782 }
11783 
11784 /*
11785  * Returns pointer to name of minor node name of device 'dev'.
11786  */
11787 static char *
11788 st_dev_name(dev_t dev)
11789 {
11790 	struct scsi_tape *un;
11791 	const char density[] = { 'l', 'm', 'h', 'c' };
11792 	static char name[32];
11793 	minor_t minor;
11794 	int instance;
11795 	int nprt = 0;
11796 
11797 	minor = getminor(dev);
11798 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
11799 	un = ddi_get_soft_state(st_state, instance);
11800 	if (un) {
11801 		ST_FUNC(ST_DEVINFO, st_dev_name);
11802 	}
11803 
11804 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
11805 
11806 	if (minor & MT_BSD) {
11807 		name[++nprt] = 'b';
11808 	}
11809 
11810 	if (minor & MT_NOREWIND) {
11811 		name[++nprt] = 'n';
11812 	}
11813 
11814 	/* NULL terminator */
11815 	name[++nprt] = 0;
11816 
11817 	return (name);
11818 }
11819 #endif	/* STDEBUG */
11820 
11821 /*
11822  * Soft error reporting, so far unique to each drive
11823  *
11824  * Currently supported: exabyte and DAT soft error reporting
11825  */
11826 static int
11827 st_report_exabyte_soft_errors(dev_t dev, int flag)
11828 {
11829 	uchar_t *sensep;
11830 	int amt;
11831 	int rval = 0;
11832 	char cdb[CDB_GROUP0], *c = cdb;
11833 	struct uscsi_cmd *com;
11834 
11835 	GET_SOFT_STATE(dev);
11836 
11837 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
11838 
11839 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11840 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
11841 	    dev, flag);
11842 
11843 	ASSERT(mutex_owned(ST_MUTEX));
11844 
11845 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
11846 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
11847 
11848 	*c++ = SCMD_REQUEST_SENSE;
11849 	*c++ = 0;
11850 	*c++ = 0;
11851 	*c++ = 0;
11852 	*c++ = TAPE_SENSE_LENGTH;
11853 	/*
11854 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
11855 	 */
11856 	*c   = (char)0x80;
11857 
11858 	com->uscsi_cdb = cdb;
11859 	com->uscsi_cdblen = CDB_GROUP0;
11860 	com->uscsi_bufaddr = (caddr_t)sensep;
11861 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
11862 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11863 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11864 
11865 	rval = st_uscsi_cmd(un, com, FKIOCTL);
11866 	if (rval || com->uscsi_status) {
11867 		goto done;
11868 	}
11869 
11870 	/*
11871 	 * was there enough data?
11872 	 */
11873 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
11874 
11875 	if ((amt >= 19) && un->un_kbytes_xferred) {
11876 		uint_t count, error_rate;
11877 		uint_t rate;
11878 
11879 		if (sensep[21] & CLN) {
11880 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11881 			    "Periodic head cleaning required");
11882 		}
11883 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
11884 			goto done;
11885 		}
11886 		/*
11887 		 * check if soft error reporting needs to be done.
11888 		 */
11889 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
11890 		count &= 0xffffff;
11891 		error_rate = (count * 100)/un->un_kbytes_xferred;
11892 
11893 #ifdef	STDEBUG
11894 		if (st_soft_error_report_debug) {
11895 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11896 			    "Exabyte Soft Error Report:\n");
11897 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11898 			    "read/write error counter: %d\n", count);
11899 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11900 			    "number of bytes transferred: %dK\n",
11901 			    un->un_kbytes_xferred);
11902 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11903 			    "error_rate: %d%%\n", error_rate);
11904 
11905 			if (amt >= 22) {
11906 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11907 				    "unit sense: 0x%b 0x%b 0x%b\n",
11908 				    sensep[19], SENSE_19_BITS,
11909 				    sensep[20], SENSE_20_BITS,
11910 				    sensep[21], SENSE_21_BITS);
11911 			}
11912 			if (amt >= 27) {
11913 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11914 				    "tracking retry counter: %d\n",
11915 				    sensep[26]);
11916 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11917 				    "read/write retry counter: %d\n",
11918 				    sensep[27]);
11919 			}
11920 		}
11921 #endif
11922 
11923 		if (flag & FWRITE) {
11924 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
11925 		} else {
11926 			rate = EXABYTE_READ_ERROR_THRESHOLD;
11927 		}
11928 		if (error_rate >= rate) {
11929 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11930 			    "Soft error rate (%d%%) during %s was too high",
11931 			    error_rate,
11932 			    ((flag & FWRITE) ? wrg_str : rdg_str));
11933 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11934 			    "Please, replace tape cartridge\n");
11935 		}
11936 	}
11937 
11938 done:
11939 	kmem_free(com, sizeof (*com));
11940 	kmem_free(sensep, TAPE_SENSE_LENGTH);
11941 
11942 	if (rval != 0) {
11943 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
11944 		    "exabyte soft error reporting failed\n");
11945 	}
11946 	return (rval);
11947 }
11948 
11949 /*
11950  * this is very specific to Archive 4mm dat
11951  */
11952 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
11953 
11954 static int
11955 st_report_dat_soft_errors(dev_t dev, int flag)
11956 {
11957 	uchar_t *sensep;
11958 	int amt, i;
11959 	int rval = 0;
11960 	char cdb[CDB_GROUP1], *c = cdb;
11961 	struct uscsi_cmd *com;
11962 
11963 	GET_SOFT_STATE(dev);
11964 
11965 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
11966 
11967 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11968 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
11969 
11970 	ASSERT(mutex_owned(ST_MUTEX));
11971 
11972 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
11973 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
11974 
11975 	*c++ = SCMD_LOG_SENSE_G1;
11976 	*c++ = 0;
11977 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
11978 	*c++ = 0;
11979 	*c++ = 0;
11980 	*c++ = 0;
11981 	*c++ = 2;
11982 	*c++ = 0;
11983 	*c++ = (char)LOG_SENSE_LENGTH;
11984 	*c   = 0;
11985 	com->uscsi_cdb    = cdb;
11986 	com->uscsi_cdblen  = CDB_GROUP1;
11987 	com->uscsi_bufaddr = (caddr_t)sensep;
11988 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
11989 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11990 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11991 	rval = st_uscsi_cmd(un, com, FKIOCTL);
11992 	if (rval) {
11993 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
11994 		    "DAT soft error reporting failed\n");
11995 	}
11996 	if (rval || com->uscsi_status) {
11997 		goto done;
11998 	}
11999 
12000 	/*
12001 	 * was there enough data?
12002 	 */
12003 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
12004 
12005 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
12006 		int total, retries, param_code;
12007 
12008 		total = -1;
12009 		retries = -1;
12010 		amt = sensep[3] + 4;
12011 
12012 
12013 #ifdef STDEBUG
12014 		if (st_soft_error_report_debug) {
12015 			(void) printf("logsense:");
12016 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
12017 				if (i % 16 == 0) {
12018 					(void) printf("\t\n");
12019 				}
12020 				(void) printf(" %x", sensep[i]);
12021 			}
12022 			(void) printf("\n");
12023 		}
12024 #endif
12025 
12026 		/*
12027 		 * parse the param_codes
12028 		 */
12029 		if (sensep[0] == 2 || sensep[0] == 3) {
12030 			for (i = 4; i < amt; i++) {
12031 				param_code = (sensep[i++] << 8);
12032 				param_code += sensep[i++];
12033 				i++; /* skip control byte */
12034 				if (param_code == 5) {
12035 					if (sensep[i++] == 4) {
12036 						total = (sensep[i++] << 24);
12037 						total += (sensep[i++] << 16);
12038 						total += (sensep[i++] << 8);
12039 						total += sensep[i];
12040 					}
12041 				} else if (param_code == 0x8007) {
12042 					if (sensep[i++] == 2) {
12043 						retries = sensep[i++] << 8;
12044 						retries += sensep[i];
12045 					}
12046 				} else {
12047 					i += sensep[i];
12048 				}
12049 			}
12050 		}
12051 
12052 		/*
12053 		 * if the log sense returned valid numbers then determine
12054 		 * the read and write error thresholds based on the amount of
12055 		 * data transferred
12056 		 */
12057 
12058 		if (total > 0 && retries > 0) {
12059 			short normal_retries = 0;
12060 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12061 			    "total xferred (%s) =%x, retries=%x\n",
12062 			    ((flag & FWRITE) ? wrg_str : rdg_str),
12063 			    total, retries);
12064 
12065 			if (flag & FWRITE) {
12066 				if (total <=
12067 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
12068 					normal_retries =
12069 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
12070 				} else {
12071 					normal_retries =
12072 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
12073 				}
12074 			} else {
12075 				if (total <=
12076 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
12077 					normal_retries =
12078 					    DAT_SMALL_READ_ERROR_THRESHOLD;
12079 				} else {
12080 					normal_retries =
12081 					    DAT_LARGE_READ_ERROR_THRESHOLD;
12082 				}
12083 			}
12084 
12085 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12086 			"normal retries=%d\n", normal_retries);
12087 
12088 			if (retries >= normal_retries) {
12089 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12090 				    "Soft error rate (retries = %d) during "
12091 				    "%s was too high",  retries,
12092 				    ((flag & FWRITE) ? wrg_str : rdg_str));
12093 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12094 				    "Periodic head cleaning required "
12095 				    "and/or replace tape cartridge\n");
12096 			}
12097 
12098 		} else if (total == -1 || retries == -1) {
12099 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12100 			    "log sense parameter code does not make sense\n");
12101 		}
12102 	}
12103 
12104 	/*
12105 	 * reset all values
12106 	 */
12107 	c = cdb;
12108 	*c++ = SCMD_LOG_SELECT_G1;
12109 	*c++ = 2;	/* this resets all values */
12110 	*c++ = (char)0xc0;
12111 	*c++ = 0;
12112 	*c++ = 0;
12113 	*c++ = 0;
12114 	*c++ = 0;
12115 	*c++ = 0;
12116 	*c++ = 0;
12117 	*c   = 0;
12118 	com->uscsi_bufaddr = NULL;
12119 	com->uscsi_buflen  = 0;
12120 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
12121 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12122 	if (rval) {
12123 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12124 		    "DAT soft error reset failed\n");
12125 	}
12126 done:
12127 	kmem_free(com, sizeof (*com));
12128 	kmem_free(sensep, LOG_SENSE_LENGTH);
12129 	return (rval);
12130 }
12131 
12132 static int
12133 st_report_soft_errors(dev_t dev, int flag)
12134 {
12135 	GET_SOFT_STATE(dev);
12136 
12137 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
12138 
12139 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12140 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12141 
12142 	ASSERT(mutex_owned(ST_MUTEX));
12143 
12144 	switch (un->un_dp->type) {
12145 	case ST_TYPE_EXB8500:
12146 	case ST_TYPE_EXABYTE:
12147 		return (st_report_exabyte_soft_errors(dev, flag));
12148 		/*NOTREACHED*/
12149 	case ST_TYPE_PYTHON:
12150 		return (st_report_dat_soft_errors(dev, flag));
12151 		/*NOTREACHED*/
12152 	default:
12153 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
12154 		return (-1);
12155 	}
12156 }
12157 
12158 /*
12159  * persistent error routines
12160  */
12161 
12162 /*
12163  * enable persistent errors, and set the throttle appropriately, checking
12164  * for flush-on-errors capability
12165  */
12166 static void
12167 st_turn_pe_on(struct scsi_tape *un)
12168 {
12169 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
12170 
12171 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
12172 	ASSERT(mutex_owned(ST_MUTEX));
12173 
12174 	un->un_persistence = 1;
12175 
12176 	/*
12177 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
12178 	 * enabled.  This will simplify the error handling for request senses
12179 	 */
12180 
12181 	if (un->un_arq_enabled && un->un_untagged_qing) {
12182 		uchar_t f_o_e;
12183 
12184 		mutex_exit(ST_MUTEX);
12185 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
12186 		    1 : 0;
12187 		mutex_enter(ST_MUTEX);
12188 
12189 		un->un_flush_on_errors = f_o_e;
12190 	} else {
12191 		un->un_flush_on_errors = 0;
12192 	}
12193 
12194 	if (un->un_flush_on_errors)
12195 		un->un_max_throttle = (uchar_t)st_max_throttle;
12196 	else
12197 		un->un_max_throttle = 1;
12198 
12199 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
12200 		un->un_max_throttle = 1;
12201 
12202 	/* this will send a marker pkt */
12203 	st_clear_pe(un);
12204 }
12205 
12206 /*
12207  * This turns persistent errors permanently off
12208  */
12209 static void
12210 st_turn_pe_off(struct scsi_tape *un)
12211 {
12212 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
12213 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
12214 	ASSERT(mutex_owned(ST_MUTEX));
12215 
12216 	/* turn it off for good */
12217 	un->un_persistence = 0;
12218 
12219 	/* this will send a marker pkt */
12220 	st_clear_pe(un);
12221 
12222 	/* turn off flush on error capability, if enabled */
12223 	if (un->un_flush_on_errors) {
12224 		mutex_exit(ST_MUTEX);
12225 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
12226 		mutex_enter(ST_MUTEX);
12227 	}
12228 
12229 
12230 	un->un_flush_on_errors = 0;
12231 }
12232 
12233 /*
12234  * This clear persistent errors, allowing more commands through, and also
12235  * sending a marker packet.
12236  */
12237 static void
12238 st_clear_pe(struct scsi_tape *un)
12239 {
12240 	ST_FUNC(ST_DEVINFO, st_clear_pe);
12241 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
12242 	ASSERT(mutex_owned(ST_MUTEX));
12243 
12244 	un->un_persist_errors = 0;
12245 	un->un_throttle = un->un_last_throttle = 1;
12246 	un->un_errno = 0;
12247 	st_hba_unflush(un);
12248 }
12249 
12250 /*
12251  * This will flag persistent errors, shutting everything down, if the
12252  * application had enabled persistent errors via MTIOCPERSISTENT
12253  */
12254 static void
12255 st_set_pe_flag(struct scsi_tape *un)
12256 {
12257 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
12258 	ASSERT(mutex_owned(ST_MUTEX));
12259 
12260 	if (un->un_persistence) {
12261 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
12262 		un->un_persist_errors = 1;
12263 		un->un_throttle = un->un_last_throttle = 0;
12264 		cv_broadcast(&un->un_sbuf_cv);
12265 	}
12266 }
12267 
12268 static int
12269 st_do_reserve(struct scsi_tape *un)
12270 {
12271 	int rval;
12272 
12273 	ST_FUNC(ST_DEVINFO, st_do_reserve);
12274 
12275 	/*
12276 	 * Issue a Throw-Away reserve command to clear the
12277 	 * check condition.
12278 	 * If the current behaviour of reserve/release is to
12279 	 * hold reservation across opens , and if a Bus reset
12280 	 * has been issued between opens then this command
12281 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
12282 	 * In this case return an EACCES so that user knows that
12283 	 * reservation has been lost in between opens.
12284 	 * If this error is not returned and we continue with
12285 	 * successful open , then user may think position of the
12286 	 * tape is still the same but inreality we would rewind the
12287 	 * tape and continue from BOT.
12288 	 */
12289 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12290 	if (rval) {
12291 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
12292 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
12293 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
12294 			un->un_errno = EACCES;
12295 			return (EACCES);
12296 		}
12297 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12298 	}
12299 	if (rval == 0) {
12300 		un->un_rsvd_status |= ST_INIT_RESERVE;
12301 	}
12302 
12303 	return (rval);
12304 }
12305 
12306 static int
12307 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb)
12308 {
12309 	int rval;
12310 	cmd_attribute const *attrib;
12311 
12312 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
12313 
12314 	/*
12315 	 * If already reserved no need to do it again.
12316 	 * Also if Reserve and Release are disabled Just return.
12317 	 */
12318 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12319 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12320 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12321 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12322 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
12323 		    st_print_scsi_cmd((uchar_t)cdb[0]));
12324 		return (0);
12325 	}
12326 
12327 	/* See if command is on the list */
12328 	attrib = st_lookup_cmd_attribute(cdb[0]);
12329 
12330 	if (attrib == NULL) {
12331 		rval = 1; /* Not found, when in doubt reserve */
12332 	} else if ((attrib->requires_reserve) != 0) {
12333 		rval = 1;
12334 	} else if ((attrib->reserve_byte) != 0) {
12335 		/*
12336 		 * cmd is on list.
12337 		 * if byte is zero always allowed.
12338 		 */
12339 		rval = 1;
12340 	} else if (((cdb[attrib->reserve_byte]) &
12341 	    (attrib->reserve_mask)) != 0) {
12342 		rval = 1;
12343 	} else {
12344 		rval = 0;
12345 	}
12346 
12347 	if (rval) {
12348 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12349 		    "Command %s requires reservation",
12350 		    st_print_scsi_cmd(cdb[0]));
12351 
12352 		rval = st_do_reserve(un);
12353 	}
12354 
12355 	return (rval);
12356 }
12357 
12358 static int
12359 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
12360 {
12361 	int rval;
12362 	cmd_attribute const *attrib;
12363 
12364 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
12365 
12366 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12367 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12368 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12369 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12370 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
12371 		    st_print_scsi_cmd(cmd));
12372 		return (0);
12373 	}
12374 
12375 	/* search for this command on the list */
12376 	attrib = st_lookup_cmd_attribute(cmd);
12377 
12378 	if (attrib == NULL) {
12379 		rval = 1; /* Not found, when in doubt reserve */
12380 	} else if ((attrib->requires_reserve) != 0) {
12381 		rval = 1;
12382 	} else if ((attrib->reserve_byte) != 0) {
12383 		/*
12384 		 * cmd is on list.
12385 		 * if byte is zero always allowed.
12386 		 */
12387 		rval = 1;
12388 	} else if (((attrib->reserve_mask) & cnt) != 0) {
12389 		rval = 1;
12390 	} else {
12391 		rval = 0;
12392 	}
12393 
12394 	if (rval) {
12395 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12396 		    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
12397 
12398 		rval = st_do_reserve(un);
12399 	}
12400 
12401 	return (rval);
12402 }
12403 
12404 static int
12405 st_reserve_release(struct scsi_tape *un, int cmd, ubufunc_t ubf)
12406 {
12407 	struct uscsi_cmd	uscsi_cmd;
12408 	int			rval;
12409 	char			cdb[CDB_GROUP0];
12410 	struct scsi_arq_status	stat;
12411 
12412 
12413 
12414 	ST_FUNC(ST_DEVINFO, st_reserve_release);
12415 
12416 	ASSERT(mutex_owned(ST_MUTEX));
12417 
12418 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12419 	    "st_reserve_release: %s \n",
12420 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
12421 
12422 	bzero(&cdb, CDB_GROUP0);
12423 	if (cmd == ST_RELEASE) {
12424 		cdb[0] = SCMD_RELEASE;
12425 	} else {
12426 		cdb[0] = SCMD_RESERVE;
12427 	}
12428 	bzero(&uscsi_cmd, sizeof (struct uscsi_cmd));
12429 	uscsi_cmd.uscsi_flags = USCSI_WRITE | USCSI_RQENABLE;
12430 	uscsi_cmd.uscsi_cdb = cdb;
12431 	uscsi_cmd.uscsi_cdblen = CDB_GROUP0;
12432 	uscsi_cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
12433 	uscsi_cmd.uscsi_rqbuf = (caddr_t)&stat;
12434 	uscsi_cmd.uscsi_rqlen = sizeof (stat);
12435 
12436 	rval = ubf(un, &uscsi_cmd, FKIOCTL);
12437 
12438 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12439 	    "st_reserve_release: rval(1)=%d\n", rval);
12440 
12441 	if (rval) {
12442 		if (uscsi_cmd.uscsi_status == STATUS_RESERVATION_CONFLICT) {
12443 			rval = EACCES;
12444 		}
12445 		/*
12446 		 * dynamically turn off reserve/release support
12447 		 * in case of drives which do not support
12448 		 * reserve/release command(ATAPI drives).
12449 		 */
12450 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
12451 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
12452 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
12453 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12454 				    "Tape unit does not support "
12455 				    "reserve/release \n");
12456 			}
12457 			rval = 0;
12458 		}
12459 	}
12460 	return (rval);
12461 }
12462 
12463 static int
12464 st_take_ownership(struct scsi_tape *un)
12465 {
12466 	int rval;
12467 
12468 	ST_FUNC(ST_DEVINFO, st_take_ownership);
12469 
12470 	ASSERT(mutex_owned(ST_MUTEX));
12471 
12472 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12473 	    "st_take_ownership: Entering ...\n");
12474 
12475 
12476 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12477 	/*
12478 	 * XXX -> Should reset be done only if we get EACCES.
12479 	 * .
12480 	 */
12481 	if (rval) {
12482 		if (st_reset(un, RESET_LUN) == 0) {
12483 			return (EIO);
12484 		}
12485 		un->un_rsvd_status &=
12486 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
12487 
12488 		mutex_exit(ST_MUTEX);
12489 		delay(drv_usectohz(ST_RESERVATION_DELAY));
12490 		mutex_enter(ST_MUTEX);
12491 		/*
12492 		 * remove the check condition.
12493 		 */
12494 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12495 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12496 		if (rval != 0) {
12497 			if ((st_reserve_release(un, ST_RESERVE, st_uscsi_cmd))
12498 			    != 0) {
12499 				rval = (un->un_rsvd_status &
12500 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
12501 				return (rval);
12502 			}
12503 		}
12504 		/*
12505 		 * Set tape state to ST_STATE_OFFLINE , in case if
12506 		 * the user wants to continue and start using
12507 		 * the tape.
12508 		 */
12509 		un->un_state = ST_STATE_OFFLINE;
12510 		un->un_rsvd_status |= ST_INIT_RESERVE;
12511 	}
12512 	return (rval);
12513 }
12514 
12515 static int
12516 st_create_errstats(struct scsi_tape *un, int instance)
12517 {
12518 	char	kstatname[KSTAT_STRLEN];
12519 
12520 	ST_FUNC(ST_DEVINFO, st_create_errstats);
12521 
12522 	/*
12523 	 * Create device error kstats
12524 	 */
12525 
12526 	if (un->un_errstats == (kstat_t *)0) {
12527 		(void) sprintf(kstatname, "st%d,err", instance);
12528 		un->un_errstats = kstat_create("sterr", instance, kstatname,
12529 		    "device_error", KSTAT_TYPE_NAMED,
12530 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
12531 		    KSTAT_FLAG_PERSISTENT);
12532 
12533 		if (un->un_errstats) {
12534 			struct st_errstats	*stp;
12535 
12536 			stp = (struct st_errstats *)un->un_errstats->ks_data;
12537 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
12538 			    KSTAT_DATA_ULONG);
12539 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
12540 			    KSTAT_DATA_ULONG);
12541 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
12542 			    KSTAT_DATA_ULONG);
12543 			kstat_named_init(&stp->st_vid, "Vendor",
12544 			    KSTAT_DATA_CHAR);
12545 			kstat_named_init(&stp->st_pid, "Product",
12546 			    KSTAT_DATA_CHAR);
12547 			kstat_named_init(&stp->st_revision, "Revision",
12548 			    KSTAT_DATA_CHAR);
12549 			kstat_named_init(&stp->st_serial, "Serial No",
12550 			    KSTAT_DATA_CHAR);
12551 			un->un_errstats->ks_private = un;
12552 			un->un_errstats->ks_update = nulldev;
12553 			kstat_install(un->un_errstats);
12554 			/*
12555 			 * Fill in the static data
12556 			 */
12557 			(void) strncpy(&stp->st_vid.value.c[0],
12558 			    ST_INQUIRY->inq_vid, 8);
12559 			/*
12560 			 * XXX:  Emulex MT-02 (and emulators) predates
12561 			 *	 SCSI-1 and has no vid & pid inquiry data.
12562 			 */
12563 			if (ST_INQUIRY->inq_len != 0) {
12564 				(void) strncpy(&stp->st_pid.value.c[0],
12565 				    ST_INQUIRY->inq_pid, 16);
12566 				(void) strncpy(&stp->st_revision.value.c[0],
12567 				    ST_INQUIRY->inq_revision, 4);
12568 				(void) strncpy(&stp->st_serial.value.c[0],
12569 				    ST_INQUIRY->inq_serial, 12);
12570 			}
12571 		}
12572 	}
12573 	return (0);
12574 }
12575 
12576 static int
12577 st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos)
12578 {
12579 	int rval;
12580 	bufunc_t bf = (ubf == st_uscsi_rcmd) ? st_rcmd : st_cmd;
12581 
12582 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
12583 
12584 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
12585 	ASSERT(mutex_owned(ST_MUTEX));
12586 
12587 	/* Can't restore an invalid position */
12588 	if (pos->pmode == invalid) {
12589 		return (4);
12590 	}
12591 
12592 	/*
12593 	 * Assumtions:
12594 	 *	If a position was read and is in logical position mode.
12595 	 *	If a drive supports read position it supports locate.
12596 	 *	If the read position type is not NO_POS. even though
12597 	 *	   a read position make not have been attemped yet.
12598 	 *
12599 	 *	The drive can locate to the position.
12600 	 */
12601 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
12602 		/*
12603 		 * If position mode is logical or legacy mode try
12604 		 * to locate there as it is faster.
12605 		 * If it fails try the old way.
12606 		 */
12607 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12608 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
12609 		    pos->lgclblkno);
12610 
12611 		if (st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
12612 		    pos->lgclblkno, pos->partition) == 0) {
12613 			/* Assume we are there copy rest of position back */
12614 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
12615 				COPY_POS(&un->un_pos, pos);
12616 			}
12617 			return (0);
12618 		}
12619 
12620 		/*
12621 		 * If logical block locate failed to restore a logical
12622 		 * position, can't recover.
12623 		 */
12624 		if (pos->pmode == logical) {
12625 			return (-1);
12626 		}
12627 	}
12628 
12629 
12630 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12631 	    "Restoring tape position at fileno=%x, blkno=%x....",
12632 	    pos->fileno, pos->blkno);
12633 
12634 	/*
12635 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
12636 	 * so as not to rewind tape on RESETS: Gee, Has life ever
12637 	 * been simple in tape land ?
12638 	 */
12639 	rval = bf(un, SCMD_REWIND, 0, SYNC_CMD);
12640 	if (rval) {
12641 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12642 		    "Failed to restore the last file and block position: In"
12643 		    " this state, Tape will be loaded at BOT during next open");
12644 		un->un_pos.pmode = invalid;
12645 		return (rval);
12646 	}
12647 
12648 	/* If the position was as the result of back space file */
12649 	if (pos->blkno > (INF / 2)) {
12650 		/* Go one extra file forward */
12651 		pos->fileno++;
12652 		/* Figure how many blocks to back into the previous file */
12653 		pos->blkno = -(INF - pos->blkno);
12654 	}
12655 
12656 	/* Go to requested fileno */
12657 	if (pos->fileno) {
12658 		rval = st_cmd(un, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
12659 		if (rval) {
12660 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12661 			    "Failed to restore the last file position: In this "
12662 			    " state, Tape will be loaded at BOT during next"
12663 			    " open %d", __LINE__);
12664 			un->un_pos.pmode = invalid;
12665 			pos->pmode = invalid;
12666 			return (rval);
12667 		}
12668 	}
12669 
12670 	/*
12671 	 * If backing into a file we already did an extra file forward.
12672 	 * Now we have to back over the filemark to get to the end of
12673 	 * the previous file. The blkno has been ajusted to a negative
12674 	 * value so we will get to the expected location.
12675 	 */
12676 	if (pos->blkno) {
12677 		rval = bf(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
12678 		if (rval) {
12679 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12680 			    "Failed to restore the last file position: In this "
12681 			    " state, Tape will be loaded at BOT during next"
12682 			    " open %d", __LINE__);
12683 			un->un_pos.pmode = invalid;
12684 			pos->pmode = invalid;
12685 			return (rval);
12686 		}
12687 	}
12688 
12689 	/*
12690 	 * The position mode, block and fileno should be correct,
12691 	 * This updates eof and logical position information.
12692 	 */
12693 	un->un_pos.eof = pos->eof;
12694 	un->un_pos.lgclblkno = pos->lgclblkno;
12695 
12696 	return (0);
12697 }
12698 
12699 /*
12700  * check sense key, ASC, ASCQ in order to determine if the tape needs
12701  * to be ejected
12702  */
12703 
12704 static int
12705 st_check_asc_ascq(struct scsi_tape *un)
12706 {
12707 	struct scsi_extended_sense *sensep = ST_RQSENSE;
12708 	struct tape_failure_code   *code;
12709 
12710 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
12711 
12712 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
12713 		if ((code->key  == sensep->es_key) &&
12714 		    (code->add_code  == sensep->es_add_code) &&
12715 		    (code->qual_code == sensep->es_qual_code))
12716 			return (1);
12717 	}
12718 	return (0);
12719 }
12720 
12721 /*
12722  * st_logpage_supported() sends a Log Sense command with
12723  * page code = 0 = Supported Log Pages Page to the device,
12724  * to see whether the page 'page' is supported.
12725  * Return values are:
12726  * -1 if the Log Sense command fails
12727  * 0 if page is not supported
12728  * 1 if page is supported
12729  */
12730 
12731 static int
12732 st_logpage_supported(struct scsi_tape *un, uchar_t page)
12733 {
12734 	uchar_t *sp, *sensep;
12735 	unsigned length;
12736 	struct uscsi_cmd *com;
12737 	int rval;
12738 	char cdb[CDB_GROUP1] = {
12739 		SCMD_LOG_SENSE_G1,
12740 		0,
12741 		SUPPORTED_LOG_PAGES_PAGE,
12742 		0,
12743 		0,
12744 		0,
12745 		0,
12746 		0,
12747 		(char)LOG_SENSE_LENGTH,
12748 		0
12749 	};
12750 
12751 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
12752 
12753 	ASSERT(mutex_owned(ST_MUTEX));
12754 
12755 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12756 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12757 
12758 	com->uscsi_cdb = cdb;
12759 	com->uscsi_cdblen = CDB_GROUP1;
12760 	com->uscsi_bufaddr = (caddr_t)sensep;
12761 	com->uscsi_buflen = LOG_SENSE_LENGTH;
12762 	com->uscsi_flags =
12763 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12764 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12765 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12766 	if (rval || com->uscsi_status) {
12767 		/* uscsi-command failed */
12768 		rval = -1;
12769 	} else {
12770 
12771 		sp = sensep + 3;
12772 
12773 		for (length = *sp++; length > 0; length--, sp++) {
12774 
12775 			if (*sp == page) {
12776 				rval = 1;
12777 				break;
12778 			}
12779 		}
12780 	}
12781 	kmem_free(com, sizeof (struct uscsi_cmd));
12782 	kmem_free(sensep, LOG_SENSE_LENGTH);
12783 	return (rval);
12784 }
12785 
12786 
12787 /*
12788  * st_check_clean_bit() gets the status of the tape's cleaning bit.
12789  *
12790  * If the device does support the TapeAlert log page, then the cleaning bit
12791  * information will be read from this page. Otherwise we will see if one of
12792  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
12793  * the device, which means, that we can get the cleaning bit information via
12794  * a RequestSense command.
12795  * If both methods of getting cleaning bit information are not supported
12796  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
12797  * returns with
12798  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
12799  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
12800  * If the call to st_uscsi_cmd() to do the Log Sense or the Request Sense
12801  * command fails, or if the amount of Request Sense data is not enough, then
12802  *  st_check_clean_bit() returns with -1.
12803  */
12804 
12805 static int
12806 st_check_clean_bit(struct scsi_tape *un)
12807 {
12808 	int rval = 0;
12809 
12810 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
12811 
12812 	ASSERT(mutex_owned(ST_MUTEX));
12813 
12814 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
12815 		return (rval);
12816 	}
12817 
12818 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
12819 
12820 		rval = st_logpage_supported(un, TAPE_SEQUENTIAL_PAGE);
12821 		if (rval == 1) {
12822 
12823 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
12824 		}
12825 
12826 		rval = st_logpage_supported(un, TAPE_ALERT_PAGE);
12827 		if (rval == 1) {
12828 
12829 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
12830 		}
12831 
12832 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
12833 
12834 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
12835 		}
12836 	}
12837 
12838 	rval = 0;
12839 
12840 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
12841 
12842 		rval = st_check_sequential_clean_bit(un);
12843 	}
12844 
12845 	if ((rval <= 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
12846 
12847 		rval = st_check_alert_flags(un);
12848 	}
12849 
12850 	if ((rval <= 0) && (un->un_dp->options & ST_CLN_MASK)) {
12851 
12852 		rval = st_check_sense_clean_bit(un);
12853 	}
12854 
12855 	if (rval < 0) {
12856 		return (rval);
12857 	}
12858 
12859 	/*
12860 	 * If found a supported means to check need to clean.
12861 	 */
12862 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
12863 
12864 		/*
12865 		 * head needs to be cleaned.
12866 		 */
12867 		if (rval & MTF_TAPE_HEAD_DIRTY) {
12868 
12869 			/*
12870 			 * Print log message only first time
12871 			 * found needing cleaned.
12872 			 */
12873 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
12874 
12875 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12876 				    "Periodic head cleaning required");
12877 
12878 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
12879 			}
12880 
12881 		} else {
12882 
12883 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
12884 		}
12885 	}
12886 
12887 	return (rval);
12888 }
12889 
12890 
12891 static int
12892 st_check_sequential_clean_bit(struct scsi_tape *un)
12893 {
12894 	int rval;
12895 	int ix;
12896 	ushort_t parameter;
12897 	struct uscsi_cmd *cmd;
12898 	struct log_sequential_page *sp;
12899 	struct log_sequential_page_parameter *prm;
12900 	char cdb[CDB_GROUP1] = {
12901 		SCMD_LOG_SENSE_G1,
12902 		0,
12903 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
12904 		0,
12905 		0,
12906 		0,
12907 		0,
12908 		(char)(sizeof (struct log_sequential_page) >> 8),
12909 		(char)(sizeof (struct log_sequential_page)),
12910 		0
12911 	};
12912 
12913 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
12914 
12915 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12916 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
12917 
12918 	cmd->uscsi_flags   =
12919 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12920 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12921 	cmd->uscsi_cdb	   = cdb;
12922 	cmd->uscsi_cdblen  = CDB_GROUP1;
12923 	cmd->uscsi_bufaddr = (caddr_t)sp;
12924 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
12925 
12926 	rval = st_uscsi_cmd(un, cmd, FKIOCTL);
12927 
12928 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
12929 
12930 		rval = -1;
12931 
12932 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
12933 
12934 		rval = -1;
12935 	}
12936 
12937 	prm = &sp->param[0];
12938 
12939 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
12940 
12941 		if (prm->log_param.length == 0) {
12942 			break;
12943 		}
12944 
12945 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
12946 		    (prm->log_param.pc_lo & 0xff));
12947 
12948 		if (parameter == SEQUENTIAL_NEED_CLN) {
12949 
12950 			rval = MTF_TAPE_CLN_SUPPORTED;
12951 			if (prm->param_value[prm->log_param.length - 1]) {
12952 
12953 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12954 				    "sequential log says head dirty\n");
12955 				rval |= MTF_TAPE_HEAD_DIRTY;
12956 			}
12957 		}
12958 		prm = (struct log_sequential_page_parameter *)
12959 		    &prm->param_value[prm->log_param.length];
12960 	}
12961 
12962 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12963 	kmem_free(sp,  sizeof (struct log_sequential_page));
12964 
12965 	return (rval);
12966 }
12967 
12968 
12969 static int
12970 st_check_alert_flags(struct scsi_tape *un)
12971 {
12972 	struct st_tape_alert *ta;
12973 	struct uscsi_cmd *com;
12974 	unsigned ix, length;
12975 	int rval;
12976 	tape_alert_flags flag;
12977 	char cdb[CDB_GROUP1] = {
12978 		SCMD_LOG_SENSE_G1,
12979 		0,
12980 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
12981 		0,
12982 		0,
12983 		0,
12984 		0,
12985 		(char)(sizeof (struct st_tape_alert) >> 8),
12986 		(char)(sizeof (struct st_tape_alert)),
12987 		0
12988 	};
12989 
12990 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
12991 
12992 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12993 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
12994 
12995 	com->uscsi_cdb = cdb;
12996 	com->uscsi_cdblen = CDB_GROUP1;
12997 	com->uscsi_bufaddr = (caddr_t)ta;
12998 	com->uscsi_buflen = sizeof (struct st_tape_alert);
12999 	com->uscsi_flags =
13000 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13001 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13002 
13003 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13004 
13005 	if (rval || com->uscsi_status || com->uscsi_resid) {
13006 
13007 		rval = -1; /* uscsi-command failed */
13008 
13009 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
13010 
13011 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13012 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
13013 		rval = -1;
13014 	}
13015 
13016 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
13017 
13018 
13019 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
13020 
13021 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13022 		    "TapeAlert length %d\n", length);
13023 	}
13024 
13025 
13026 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
13027 
13028 		/*
13029 		 * if rval is bad before the first pass don't bother
13030 		 */
13031 		if (ix == 0 && rval != 0) {
13032 
13033 			break;
13034 		}
13035 
13036 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
13037 		    ta->param[ix].log_param.pc_lo);
13038 
13039 		if ((ta->param[ix].param_value & 1) == 0) {
13040 			continue;
13041 		}
13042 		/*
13043 		 * check to see if current parameter is of interest.
13044 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
13045 		 */
13046 		if ((flag == TAF_CLEAN_NOW) ||
13047 		    (flag == TAF_CLEAN_PERIODIC) ||
13048 		    ((flag == CLEAN_FOR_ERRORS) &&
13049 		    (un->un_dp->type == ST_TYPE_STK9840))) {
13050 
13051 			rval = MTF_TAPE_CLN_SUPPORTED;
13052 
13053 
13054 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13055 			    "alert_page drive needs clean %d\n", flag);
13056 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
13057 			rval |= MTF_TAPE_HEAD_DIRTY;
13058 
13059 		} else if (flag == TAF_CLEANING_MEDIA) {
13060 
13061 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13062 			    "alert_page drive was cleaned\n");
13063 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
13064 		}
13065 
13066 	}
13067 
13068 	/*
13069 	 * Report it as dirty till we see it cleaned
13070 	 */
13071 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
13072 
13073 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13074 		    "alert_page still dirty\n");
13075 		rval |= MTF_TAPE_HEAD_DIRTY;
13076 	}
13077 
13078 	kmem_free(com, sizeof (struct uscsi_cmd));
13079 	kmem_free(ta,  sizeof (struct st_tape_alert));
13080 
13081 	return (rval);
13082 }
13083 
13084 
13085 static int
13086 st_check_sense_clean_bit(struct scsi_tape *un)
13087 {
13088 	uchar_t *sensep;
13089 	char cdb[CDB_GROUP0];
13090 	struct uscsi_cmd *com;
13091 	ushort_t byte_pos;
13092 	uchar_t bit_mask;
13093 	unsigned length;
13094 	int index;
13095 	int rval;
13096 
13097 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
13098 
13099 	/*
13100 	 * Since this tape does not support Tape Alert,
13101 	 * we now try to get the cleanbit status via
13102 	 * Request Sense.
13103 	 */
13104 
13105 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
13106 
13107 		index = 0;
13108 
13109 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
13110 
13111 		index = 1;
13112 
13113 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
13114 
13115 		index = 2;
13116 
13117 	} else {
13118 
13119 		return (-1);
13120 	}
13121 
13122 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
13123 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
13124 	length = byte_pos + 1;
13125 
13126 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13127 	sensep = kmem_zalloc(length, KM_SLEEP);
13128 
13129 	cdb[0] = SCMD_REQUEST_SENSE;
13130 	cdb[1] = 0;
13131 	cdb[2] = 0;
13132 	cdb[3] = 0;
13133 	cdb[4] = (char)length;
13134 	cdb[5] = 0;
13135 
13136 	com->uscsi_cdb = cdb;
13137 	com->uscsi_cdblen = CDB_GROUP0;
13138 	com->uscsi_bufaddr = (caddr_t)sensep;
13139 	com->uscsi_buflen = length;
13140 	com->uscsi_flags =
13141 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13142 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13143 
13144 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13145 
13146 	if (rval || com->uscsi_status || com->uscsi_resid) {
13147 
13148 		rval = -1;
13149 
13150 	} else {
13151 
13152 		rval = MTF_TAPE_CLN_SUPPORTED;
13153 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
13154 
13155 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13156 			    "sense data says head dirty\n");
13157 			rval |= MTF_TAPE_HEAD_DIRTY;
13158 		}
13159 	}
13160 
13161 	kmem_free(com, sizeof (struct uscsi_cmd));
13162 	kmem_free(sensep, length);
13163 	return (rval);
13164 }
13165 
13166 /*
13167  * st_clear_unit_attention
13168  *
13169  *  	run test unit ready's to clear out outstanding
13170  * 	unit attentions.
13171  * 	returns zero for SUCCESS or the errno from st_cmd call
13172  */
13173 static int
13174 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
13175 {
13176 	int	i    = 0;
13177 	int	rval;
13178 
13179 	GET_SOFT_STATE(dev_instance);
13180 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
13181 
13182 	do {
13183 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
13184 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
13185 	return (rval);
13186 }
13187 
13188 static void
13189 st_calculate_timeouts(struct scsi_tape *un)
13190 {
13191 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
13192 
13193 	if (un->un_dp->non_motion_timeout == 0) {
13194 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13195 			un->un_dp->non_motion_timeout =
13196 			    st_io_time * st_long_timeout_x;
13197 		} else {
13198 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
13199 		}
13200 	}
13201 
13202 	if (un->un_dp->io_timeout == 0) {
13203 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13204 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
13205 		} else {
13206 			un->un_dp->io_timeout = (ushort_t)st_io_time;
13207 		}
13208 	}
13209 
13210 	if (un->un_dp->rewind_timeout == 0) {
13211 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13212 			un->un_dp->rewind_timeout =
13213 			    st_space_time * st_long_timeout_x;
13214 		} else {
13215 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
13216 		}
13217 	}
13218 
13219 	if (un->un_dp->space_timeout == 0) {
13220 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13221 			un->un_dp->space_timeout =
13222 			    st_space_time * st_long_timeout_x;
13223 		} else {
13224 			un->un_dp->space_timeout = (ushort_t)st_space_time;
13225 		}
13226 	}
13227 
13228 	if (un->un_dp->load_timeout == 0) {
13229 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13230 			un->un_dp->load_timeout =
13231 			    st_space_time * st_long_timeout_x;
13232 		} else {
13233 			un->un_dp->load_timeout = (ushort_t)st_space_time;
13234 		}
13235 	}
13236 
13237 	if (un->un_dp->unload_timeout == 0) {
13238 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13239 			un->un_dp->unload_timeout =
13240 			    st_space_time * st_long_timeout_x;
13241 		} else {
13242 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
13243 		}
13244 	}
13245 
13246 	if (un->un_dp->erase_timeout == 0) {
13247 		if (un->un_dp->options & ST_LONG_ERASE) {
13248 			un->un_dp->erase_timeout =
13249 			    st_space_time * st_long_space_time_x;
13250 		} else {
13251 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
13252 		}
13253 	}
13254 }
13255 
13256 
13257 static writablity
13258 st_is_not_wormable(struct scsi_tape *un)
13259 {
13260 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
13261 	return (RDWR);
13262 }
13263 
13264 static writablity
13265 st_is_hp_dat_tape_worm(struct scsi_tape *un)
13266 {
13267 	writablity wrt;
13268 
13269 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
13270 
13271 	/* Mode sense should be current */
13272 	if (un->un_mspl->media_type == 1) {
13273 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13274 		    "Drive has WORM media loaded\n");
13275 		wrt = WORM;
13276 	} else {
13277 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13278 		    "Drive has non WORM media loaded\n");
13279 		wrt = RDWR;
13280 	}
13281 	return (wrt);
13282 }
13283 
13284 #define	HP_DAT_INQUIRY 0x4A
13285 static writablity
13286 st_is_hp_dat_worm(struct scsi_tape *un)
13287 {
13288 	char *buf;
13289 	int result;
13290 	writablity wrt;
13291 
13292 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
13293 
13294 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
13295 
13296 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
13297 
13298 	if (result != 0) {
13299 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13300 		    "Read Standard Inquiry for WORM support failed");
13301 		wrt = FAILED;
13302 	} else if ((buf[40] & 1) == 0) {
13303 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13304 		    "Drive is NOT WORMable\n");
13305 		/* This drive doesn't support it so don't check again */
13306 		un->un_dp->options &= ~ST_WORMABLE;
13307 		wrt = RDWR;
13308 		un->un_wormable = st_is_not_wormable;
13309 	} else {
13310 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13311 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13312 		un->un_wormable = st_is_hp_dat_tape_worm;
13313 		wrt = un->un_wormable(un);
13314 	}
13315 
13316 	kmem_free(buf, HP_DAT_INQUIRY);
13317 
13318 	/*
13319 	 * If drive doesn't support it no point in checking further.
13320 	 */
13321 	return (wrt);
13322 }
13323 
13324 static writablity
13325 st_is_hp_lto_tape_worm(struct scsi_tape *un)
13326 {
13327 	writablity wrt;
13328 
13329 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
13330 
13331 	/* Mode sense should be current */
13332 	switch (un->un_mspl->media_type) {
13333 	case 0x00:
13334 		switch (un->un_mspl->density) {
13335 		case 0x40:
13336 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13337 			    "Drive has standard Gen I media loaded\n");
13338 			break;
13339 		case 0x42:
13340 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13341 			    "Drive has standard Gen II media loaded\n");
13342 			break;
13343 		case 0x44:
13344 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13345 			    "Drive has standard Gen III media loaded\n");
13346 			break;
13347 		case 0x46:
13348 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13349 			    "Drive has standard Gen IV media loaded\n");
13350 			break;
13351 		default:
13352 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13353 			    "Drive has standard unknown 0x%X media loaded\n",
13354 			    un->un_mspl->density);
13355 		}
13356 		wrt = RDWR;
13357 		break;
13358 	case 0x01:
13359 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13360 		    "Drive has WORM medium loaded\n");
13361 		wrt = WORM;
13362 		break;
13363 	case 0x80:
13364 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13365 		    "Drive has CD-ROM emulation medium loaded\n");
13366 		wrt = WORM;
13367 		break;
13368 	default:
13369 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13370 		    "Drive has an unexpected medium type 0x%X loaded\n",
13371 		    un->un_mspl->media_type);
13372 		wrt = RDWR;
13373 	}
13374 
13375 	return (wrt);
13376 }
13377 
13378 #define	LTO_REQ_INQUIRY 44
13379 static writablity
13380 st_is_hp_lto_worm(struct scsi_tape *un)
13381 {
13382 	char *buf;
13383 	int result;
13384 	writablity wrt;
13385 
13386 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
13387 
13388 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
13389 
13390 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
13391 
13392 	if (result != 0) {
13393 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13394 		    "Read Standard Inquiry for WORM support failed");
13395 		wrt = FAILED;
13396 	} else if ((buf[40] & 1) == 0) {
13397 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13398 		    "Drive is NOT WORMable\n");
13399 		/* This drive doesn't support it so don't check again */
13400 		un->un_dp->options &= ~ST_WORMABLE;
13401 		wrt = RDWR;
13402 		un->un_wormable = st_is_not_wormable;
13403 	} else {
13404 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13405 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13406 		un->un_wormable = st_is_hp_lto_tape_worm;
13407 		wrt = un->un_wormable(un);
13408 	}
13409 
13410 	kmem_free(buf, LTO_REQ_INQUIRY);
13411 
13412 	/*
13413 	 * If drive doesn't support it no point in checking further.
13414 	 */
13415 	return (wrt);
13416 }
13417 
13418 static writablity
13419 st_is_t10_worm_device(struct scsi_tape *un)
13420 {
13421 	writablity wrt;
13422 
13423 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
13424 
13425 	if (un->un_mspl->media_type == 0x3c) {
13426 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13427 		    "Drive has WORM media loaded\n");
13428 		wrt = WORM;
13429 	} else {
13430 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13431 		    "Drive has non WORM media loaded\n");
13432 		wrt = RDWR;
13433 	}
13434 	return (wrt);
13435 }
13436 
13437 #define	SEQ_CAP_PAGE	(char)0xb0
13438 static writablity
13439 st_is_t10_worm(struct scsi_tape *un)
13440 {
13441 	char *buf;
13442 	int result;
13443 	writablity wrt;
13444 
13445 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
13446 
13447 	buf = kmem_zalloc(6, KM_SLEEP);
13448 
13449 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
13450 
13451 	if (result != 0) {
13452 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13453 		    "Read Vitial Inquiry for Sequental Capability"
13454 		    " WORM support failed %x", result);
13455 		wrt = FAILED;
13456 	} else if ((buf[4] & 1) == 0) {
13457 		ASSERT(buf[1] == SEQ_CAP_PAGE);
13458 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13459 		    "Drive is NOT WORMable\n");
13460 		/* This drive doesn't support it so don't check again */
13461 		un->un_dp->options &= ~ST_WORMABLE;
13462 		wrt = RDWR;
13463 		un->un_wormable = st_is_not_wormable;
13464 	} else {
13465 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13466 		    "Drive supports WORM\n");
13467 		un->un_wormable = st_is_t10_worm_device;
13468 		wrt = un->un_wormable(un);
13469 	}
13470 
13471 	kmem_free(buf, 6);
13472 
13473 	return (wrt);
13474 }
13475 
13476 
13477 #define	STK_REQ_SENSE 26
13478 
13479 static writablity
13480 st_is_stk_worm(struct scsi_tape *un)
13481 {
13482 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
13483 	struct scsi_extended_sense *sense;
13484 	struct uscsi_cmd *cmd;
13485 	char *buf;
13486 	int result;
13487 	writablity wrt;
13488 
13489 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
13490 
13491 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13492 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
13493 	sense = (struct scsi_extended_sense *)buf;
13494 
13495 	cmd->uscsi_flags = USCSI_READ;
13496 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13497 	cmd->uscsi_cdb = &cdb[0];
13498 	cmd->uscsi_bufaddr = buf;
13499 	cmd->uscsi_buflen = STK_REQ_SENSE;
13500 	cmd->uscsi_cdblen = CDB_GROUP0;
13501 	cmd->uscsi_rqlen = 0;
13502 	cmd->uscsi_rqbuf = NULL;
13503 
13504 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
13505 
13506 	if (result != 0 || cmd->uscsi_status != 0) {
13507 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13508 		    "Request Sense for WORM failed");
13509 		wrt = RDWR;
13510 	} else if (sense->es_add_len + 8 < 24) {
13511 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13512 		    "Drive didn't send enough sense data for WORM byte %d\n",
13513 		    sense->es_add_len + 8);
13514 		wrt = RDWR;
13515 		un->un_wormable = st_is_not_wormable;
13516 	} else if ((buf[24]) & 0x02) {
13517 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13518 		    "Drive has WORM tape loaded\n");
13519 		wrt = WORM;
13520 		un->un_wormable = st_is_stk_worm;
13521 	} else {
13522 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13523 		    "Drive has normal tape loaded\n");
13524 		wrt = RDWR;
13525 		un->un_wormable = st_is_stk_worm;
13526 	}
13527 
13528 	kmem_free(buf, STK_REQ_SENSE);
13529 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13530 	return (wrt);
13531 }
13532 
13533 #define	DLT_INQ_SZ 44
13534 
13535 static writablity
13536 st_is_dlt_tape_worm(struct scsi_tape *un)
13537 {
13538 	caddr_t buf;
13539 	int result;
13540 	writablity wrt;
13541 
13542 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
13543 
13544 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
13545 
13546 	/* Read Attribute Media Type */
13547 
13548 	result = st_read_attributes(un, 0x0408, buf, 10, st_uscsi_cmd);
13549 
13550 	/*
13551 	 * If this quantum drive is attached via an HBA that cannot
13552 	 * support thr read attributes command return error in the
13553 	 * hope that someday they will support the t10 method.
13554 	 */
13555 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
13556 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13557 		    "Read Attribute Command for WORM Media detection is not "
13558 		    "supported on the HBA that this drive is attached to.");
13559 		wrt = RDWR;
13560 		un->un_wormable = st_is_not_wormable;
13561 		goto out;
13562 	}
13563 
13564 	if (result != 0) {
13565 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13566 		    "Read Attribute Command for WORM Media returned 0x%x",
13567 		    result);
13568 		wrt = RDWR;
13569 		un->un_dp->options &= ~ST_WORMABLE;
13570 		goto out;
13571 	}
13572 
13573 	if ((uchar_t)buf[9] == 0x80) {
13574 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13575 		    "Drive media is WORM\n");
13576 		wrt = WORM;
13577 	} else {
13578 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13579 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
13580 		wrt = RDWR;
13581 	}
13582 
13583 out:
13584 	kmem_free(buf, DLT_INQ_SZ);
13585 	return (wrt);
13586 }
13587 
13588 static writablity
13589 st_is_dlt_worm(struct scsi_tape *un)
13590 {
13591 	caddr_t buf;
13592 	int result;
13593 	writablity wrt;
13594 
13595 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
13596 
13597 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
13598 
13599 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
13600 
13601 	if (result != 0) {
13602 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13603 		    "Read Vendor Specific Inquiry for WORM support failed");
13604 		wrt = RDWR;
13605 		goto out;
13606 	}
13607 
13608 	if ((buf[2] & 1) == 0) {
13609 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13610 		    "Drive is not WORMable\n");
13611 		wrt = RDWR;
13612 		un->un_dp->options &= ~ST_WORMABLE;
13613 		un->un_wormable = st_is_not_wormable;
13614 		goto out;
13615 	} else {
13616 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13617 		    "Drive is WORMable\n");
13618 		un->un_wormable = st_is_dlt_tape_worm;
13619 		wrt = un->un_wormable(un);
13620 	}
13621 out:
13622 	kmem_free(buf, DLT_INQ_SZ);
13623 
13624 	return (wrt);
13625 }
13626 
13627 typedef struct {
13628 	struct modeheader_seq header;
13629 #if defined(_BIT_FIELDS_LTOH) /* X86 */
13630 	uchar_t pagecode	:6,
13631 				:2;
13632 	uchar_t page_len;
13633 	uchar_t syslogalive	:2,
13634 		device		:1,
13635 		abs		:1,
13636 		ulpbot		:1,
13637 		prth		:1,
13638 		ponej		:1,
13639 		ait		:1;
13640 	uchar_t span;
13641 
13642 	uchar_t			:6,
13643 		worm		:1,
13644 		mic		:1;
13645 	uchar_t worm_cap	:1,
13646 				:7;
13647 	uint32_t		:32;
13648 #else /* SPARC */
13649 	uchar_t			:2,
13650 		pagecode	:6;
13651 	uchar_t page_len;
13652 	uchar_t ait		:1,
13653 		device		:1,
13654 		abs		:1,
13655 		ulpbot		:1,
13656 		prth		:1,
13657 		ponej		:1,
13658 		syslogalive	:2;
13659 	uchar_t span;
13660 	uchar_t mic		:1,
13661 		worm		:1,
13662 				:6;
13663 	uchar_t			:7,
13664 		worm_cap	:1;
13665 	uint32_t		:32;
13666 #endif
13667 }ait_dev_con;
13668 
13669 #define	AIT_DEV_PAGE 0x31
13670 static writablity
13671 st_is_sony_worm(struct scsi_tape *un)
13672 {
13673 	int result;
13674 	writablity wrt;
13675 	ait_dev_con *ait_conf;
13676 
13677 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
13678 
13679 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
13680 
13681 	result = st_gen_mode_sense(un, st_uscsi_cmd, AIT_DEV_PAGE,
13682 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
13683 
13684 	if (result == 0) {
13685 
13686 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
13687 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13688 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
13689 			    ait_conf->pagecode, AIT_DEV_PAGE);
13690 			wrt = RDWR;
13691 			un->un_wormable = st_is_not_wormable;
13692 
13693 		} else if (ait_conf->worm_cap) {
13694 
13695 			un->un_wormable = st_is_sony_worm;
13696 
13697 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13698 			    "Drives is WORMable\n");
13699 			if (ait_conf->worm) {
13700 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13701 				    "Media is WORM\n");
13702 				wrt = WORM;
13703 			} else {
13704 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13705 				    "Media is not WORM\n");
13706 				wrt = RDWR;
13707 			}
13708 
13709 		} else {
13710 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13711 			    "Drives not is WORMable\n");
13712 			wrt = RDWR;
13713 			/* No further checking required */
13714 			un->un_dp->options &= ~ST_WORMABLE;
13715 		}
13716 
13717 	} else {
13718 
13719 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13720 		    "AIT device config mode sense page read command failed"
13721 		    " result = %d ", result);
13722 		wrt = FAILED;
13723 		un->un_wormable = st_is_not_wormable;
13724 	}
13725 
13726 	kmem_free(ait_conf, sizeof (ait_dev_con));
13727 	return (wrt);
13728 }
13729 
13730 static writablity
13731 st_is_drive_worm(struct scsi_tape *un)
13732 {
13733 	writablity wrt;
13734 
13735 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
13736 
13737 	switch (un->un_dp->type) {
13738 	case MT_ISDLT:
13739 		wrt = st_is_dlt_worm(un);
13740 		break;
13741 
13742 	case MT_ISSTK9840:
13743 		wrt = st_is_stk_worm(un);
13744 		break;
13745 
13746 	case MT_IS8MM:
13747 	case MT_ISAIT:
13748 		wrt = st_is_sony_worm(un);
13749 		break;
13750 
13751 	case MT_LTO:
13752 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
13753 			wrt = st_is_hp_lto_worm(un);
13754 		} else {
13755 			wrt = st_is_t10_worm(un);
13756 		}
13757 		break;
13758 
13759 	case MT_ISDAT:
13760 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
13761 			wrt = st_is_hp_dat_worm(un);
13762 		} else {
13763 			wrt = st_is_t10_worm(un);
13764 		}
13765 		break;
13766 
13767 	default:
13768 		wrt = FAILED;
13769 		break;
13770 	}
13771 
13772 	/*
13773 	 * If any of the above failed try the t10 standard method.
13774 	 */
13775 	if (wrt == FAILED) {
13776 		wrt = st_is_t10_worm(un);
13777 	}
13778 
13779 	/*
13780 	 * Unknown method for detecting WORM media.
13781 	 */
13782 	if (wrt == FAILED) {
13783 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13784 		    "Unknown method for WORM media detection\n");
13785 		wrt = RDWR;
13786 		un->un_dp->options &= ~ST_WORMABLE;
13787 	}
13788 
13789 	return (wrt);
13790 }
13791 
13792 static int
13793 st_read_attributes(struct scsi_tape *un, uint16_t attribute, void *pnt,
13794     size_t size, ubufunc_t bufunc)
13795 {
13796 	char cdb[CDB_GROUP4];
13797 	int result;
13798 	struct uscsi_cmd *cmd;
13799 	caddr_t buf = (caddr_t)pnt;
13800 
13801 	ST_FUNC(ST_DEVINFO, st_read_attributes);
13802 
13803 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13804 
13805 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
13806 	cdb[1] = 0;
13807 	cdb[2] = 0;
13808 	cdb[3] = 0;
13809 	cdb[4] = 0;
13810 	cdb[5] = 0;
13811 	cdb[6] = 0;
13812 	cdb[7] = 0;
13813 	cdb[8] = (char)(attribute >> 8);
13814 	cdb[9] = (char)(attribute);
13815 	cdb[10] = (char)(size >> 24);
13816 	cdb[11] = (char)(size >> 16);
13817 	cdb[12] = (char)(size >> 8);
13818 	cdb[13] = (char)(size);
13819 	cdb[14] = 0;
13820 	cdb[15] = 0;
13821 
13822 
13823 	cmd->uscsi_flags = USCSI_READ | USCSI_DIAGNOSE;
13824 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13825 	cmd->uscsi_cdb = &cdb[0];
13826 	cmd->uscsi_bufaddr = (caddr_t)buf;
13827 	cmd->uscsi_buflen = size;
13828 	cmd->uscsi_cdblen = sizeof (cdb);
13829 
13830 	result = bufunc(un, cmd, FKIOCTL);
13831 
13832 	if (result != 0 || cmd->uscsi_status != 0) {
13833 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13834 		    "st_read_attribute failed: result %d status %d\n",
13835 		    result, cmd->uscsi_status);
13836 		/*
13837 		 * If this returns invalid operation code don't try again.
13838 		 */
13839 		if (un->un_sd->sd_sense->es_key == KEY_ILLEGAL_REQUEST &&
13840 		    un->un_sd->sd_sense->es_add_code == 0x20) {
13841 			result = ENOTTY;
13842 		} else if (result == 0) {
13843 			result = EIO;
13844 		}
13845 
13846 	} else {
13847 
13848 		/*
13849 		 * The attribute retured should match the attribute requested.
13850 		 */
13851 		if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
13852 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13853 			    "st_read_attribute got wrong data back expected "
13854 			    "0x%x got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
13855 			st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
13856 			    "bad? data", buf, size);
13857 			result = EIO;
13858 		}
13859 	}
13860 
13861 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13862 
13863 	return (result);
13864 }
13865 
13866 static int
13867 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
13868     uchar_t page)
13869 {
13870 	char cdb[CDB_GROUP0];
13871 	struct scsi_extended_sense *sense;
13872 	struct uscsi_cmd *cmd;
13873 	int result;
13874 
13875 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
13876 
13877 	cdb[0] = SCMD_INQUIRY;
13878 	cdb[1] = page ? 1 : 0;
13879 	cdb[2] = page;
13880 	cdb[3] = 0;
13881 	cdb[4] = size;
13882 	cdb[5] = 0;
13883 
13884 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13885 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
13886 
13887 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
13888 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13889 	cmd->uscsi_cdb = &cdb[0];
13890 	cmd->uscsi_bufaddr = dest;
13891 	cmd->uscsi_buflen = size;
13892 	cmd->uscsi_cdblen = CDB_GROUP0;
13893 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
13894 	cmd->uscsi_rqbuf = (caddr_t)sense;
13895 
13896 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
13897 
13898 	if (result != 0 || cmd->uscsi_status != 0) {
13899 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13900 		    "st_get_special_inquiry() failed for page %x", page);
13901 		if (result == 0) {
13902 			result = EIO;
13903 		}
13904 	}
13905 
13906 	kmem_free(sense, sizeof (struct scsi_extended_sense));
13907 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13908 
13909 	return (result);
13910 }
13911 
13912 
13913 static int
13914 st_update_block_pos(struct scsi_tape *un, bufunc_t bf, int post_space)
13915 {
13916 	int rval = ENOTTY;
13917 	uchar_t status = un->un_status;
13918 	posmode previous_pmode = un->un_running.pmode;
13919 
13920 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
13921 
13922 	while (un->un_read_pos_type != NO_POS) {
13923 		rval = bf(un, SCMD_READ_POSITION, 32, SYNC_CMD);
13924 
13925 		/*
13926 		 * If read position command returned good status
13927 		 * Parse the data to see if the position can be interpreted.
13928 		 */
13929 		if ((rval == 0) &&
13930 		    ((rval = st_interpret_read_pos(un, &un->un_pos,
13931 		    un->un_read_pos_type, 32, (caddr_t)un->un_read_pos_data,
13932 		    post_space)) == 0)) {
13933 			/*
13934 			 * Update the running position as well if un_pos was
13935 			 * ok. But only if recovery is enabled.
13936 			 */
13937 			if (st_recov_sz != sizeof (recov_info)) {
13938 				break;
13939 			}
13940 			rval = st_interpret_read_pos(un, &un->un_running,
13941 			    un->un_read_pos_type, 32,
13942 			    (caddr_t)un->un_read_pos_data, post_space);
13943 			un->un_status = status;
13944 			break;
13945 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
13946 			un->un_running.pmode = previous_pmode;
13947 			continue;
13948 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
13949 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13950 			    "st_update_block_pos() read position cmd 0x%x"
13951 			    " returned 0x%x un_status = %d",
13952 			    un->un_read_pos_type, rval, un->un_status);
13953 			/* ENOTTY means it read garbage. try something else. */
13954 			if (rval == ENOTTY) {
13955 				rval = EIO; /* so ENOTTY is not final rval */
13956 			} else {
13957 				break;
13958 			}
13959 		} else {
13960 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
13961 			    "st_update_block_pos() read position cmd %x"
13962 			    " returned %x", un->un_read_pos_type, rval);
13963 			un->un_running.pmode = previous_pmode;
13964 		}
13965 
13966 		switch (un->un_read_pos_type) {
13967 		case SHORT_POS:
13968 			un->un_read_pos_type = NO_POS;
13969 			break;
13970 
13971 		case LONG_POS:
13972 			un->un_read_pos_type = EXT_POS;
13973 			break;
13974 
13975 		case EXT_POS:
13976 			un->un_read_pos_type = SHORT_POS;
13977 			break;
13978 
13979 		default:
13980 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
13981 			    "Unexpected read position type 0x%x",
13982 			    un->un_read_pos_type);
13983 		}
13984 		un->un_status = KEY_NO_SENSE;
13985 	}
13986 
13987 	return (rval);
13988 }
13989 
13990 static int
13991 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
13992 {
13993 	int result;
13994 	size_t d_sz;
13995 	caddr_t pos_info;
13996 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
13997 
13998 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
13999 
14000 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
14001 		return (0);
14002 	}
14003 
14004 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
14005 
14006 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14007 		    "bp_mapin_common() failed");
14008 
14009 		return (EIO);
14010 	}
14011 
14012 	pos_info = bp->b_un.b_addr;
14013 	d_sz = bp->b_bcount - bp->b_resid;
14014 
14015 #ifdef STDEBUG
14016 	if ((st_debug & 0x7) > 2) {
14017 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14018 		    "st_get_read_pos() position info",
14019 		    pos_info, bp->b_bcount);
14020 	}
14021 #endif
14022 
14023 	result = st_interpret_read_pos(un, &un->un_pos, cmd->uscsi_cdb[1],
14024 	    d_sz, pos_info, 0);
14025 
14026 	COPY_POS(&un->un_running, &un->un_pos);
14027 
14028 	bp_mapout(bp);
14029 
14030 	return (result);
14031 }
14032 
14033 #if defined(_BIG_ENDIAN)
14034 
14035 #define	FIX_ENDIAN16(x)
14036 #define	FIX_ENDIAN32(x)
14037 #define	FIX_ENDIAN64(x)
14038 
14039 #elif defined(_LITTLE_ENDIAN)
14040 
14041 static void
14042 st_swap16(uint16_t *val)
14043 {
14044 	uint16_t tmp;
14045 
14046 	tmp = (*val >>  8) & 0xff;
14047 	tmp |= (*val <<  8) & 0xff00;
14048 
14049 	*val = tmp;
14050 }
14051 
14052 static void
14053 st_swap32(uint32_t *val)
14054 {
14055 	uint32_t tmp;
14056 
14057 	tmp =  (*val >> 24) & 0xff;
14058 	tmp |= (*val >>  8) & 0xff00;
14059 	tmp |= (*val <<  8) & 0xff0000;
14060 	tmp |= (*val << 24) & 0xff000000;
14061 
14062 	*val = tmp;
14063 }
14064 
14065 static void
14066 st_swap64(uint64_t *val)
14067 {
14068 	uint32_t low;
14069 	uint32_t high;
14070 
14071 	low =  (uint32_t)(*val);
14072 	high = (uint32_t)(*val >> 32);
14073 
14074 	st_swap32(&low);
14075 	st_swap32(&high);
14076 
14077 	*val =  high;
14078 	*val |= ((uint64_t)low << 32);
14079 }
14080 
14081 #define	FIX_ENDIAN16(x) st_swap16(x)
14082 #define	FIX_ENDIAN32(x) st_swap32(x)
14083 #define	FIX_ENDIAN64(x) st_swap64(x)
14084 #endif
14085 
14086 /*
14087  * st_interpret_read_pos()
14088  *
14089  * Returns:
14090  *	0	If secsessful.
14091  *	EIO	If read postion responce data was unuseable or invalid.
14092  *	ERANGE	If the position of the drive is too large for the read_p_type.
14093  *	ENOTTY	If the responce data looks invalid for the read position type.
14094  */
14095 
14096 static int
14097 st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
14098     read_p_types type, size_t data_sz, const caddr_t responce, int post_space)
14099 {
14100 	int rval = 0;
14101 	int flag = 0;
14102 	tapepos_t org;
14103 
14104 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
14105 
14106 	/*
14107 	 * We expect the position value to change after a space command.
14108 	 * So if post_space is set we don't print out what has changed.
14109 	 */
14110 	if ((dest != &un->un_pos) && (post_space == 0) &&
14111 	    (st_recov_sz == sizeof (recov_info))) {
14112 		COPY_POS(&org, dest);
14113 		flag = 1;
14114 	}
14115 
14116 	/*
14117 	 * See what kind of read position was requested.
14118 	 */
14119 	switch (type) {
14120 
14121 	case SHORT_POS: /* Short data format */
14122 	{
14123 		tape_position_t *pos_info = (tape_position_t *)responce;
14124 		uint32_t value;
14125 
14126 		/* If reserved fields are non zero don't use the data */
14127 		if (pos_info->reserved0 || pos_info->reserved1 ||
14128 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
14129 		    pos_info->reserved3) {
14130 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14131 			    "Invalid Read Short Position Data returned\n");
14132 			rval = EIO;
14133 			break;
14134 		}
14135 		/*
14136 		 * Position is to large to use this type of read position.
14137 		 */
14138 		if (pos_info->posi_err == 1) {
14139 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14140 			    "Drive reported position error\n");
14141 			rval = ERANGE;
14142 			break;
14143 		}
14144 		/*
14145 		 * If your at the begining of partition and end at the same
14146 		 * time it's very small partition or bad data.
14147 		 */
14148 		if (pos_info->begin_of_part && pos_info->end_of_part) {
14149 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14150 			    "SHORT_POS returned begin and end of"
14151 			    " partition\n");
14152 			rval = EIO;
14153 			break;
14154 		}
14155 
14156 		if (pos_info->blk_posi_unkwn == 0) {
14157 
14158 			value = pos_info->host_block;
14159 			FIX_ENDIAN32(&value);
14160 
14161 			/*
14162 			 * If the tape is rewound the host blcok should be 0.
14163 			 */
14164 			if ((pos_info->begin_of_part == 1) &&
14165 			    (value != 0)) {
14166 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14167 				    "SHORT_POS returned begin of partition"
14168 				    " but host block was 0x%x\n", value);
14169 				rval = EIO;
14170 				break;
14171 			}
14172 
14173 			if (dest->lgclblkno != value) {
14174 				if (flag)
14175 					flag++;
14176 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14177 				    "SHORT_POS current logical 0x%"PRIx64" read"
14178 				    " 0x%x\n", dest->lgclblkno, value);
14179 			}
14180 
14181 			dest->lgclblkno = (uint64_t)value;
14182 
14183 			/*
14184 			 * If the begining of partition is true and the
14185 			 * block number is zero we will beleive that it is
14186 			 * rewound. Promote the pmode to legacy.
14187 			 */
14188 			if ((pos_info->begin_of_part == 1) &&
14189 			    (value == 0)) {
14190 				dest->blkno = 0;
14191 				dest->fileno = 0;
14192 				if (dest->pmode != legacy)
14193 					dest->pmode = legacy;
14194 			/*
14195 			 * otherwise if the pmode was invalid,
14196 			 * promote it to logical.
14197 			 */
14198 			} else if (dest->pmode == invalid) {
14199 				dest->pmode = logical;
14200 			}
14201 
14202 			if (dest->partition != pos_info->partition_number) {
14203 				if (flag)
14204 					flag++;
14205 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14206 				    "SHORT_POS current partition %d read %d\n",
14207 				    dest->partition,
14208 				    pos_info->partition_number);
14209 			}
14210 
14211 			dest->partition = pos_info->partition_number;
14212 
14213 		} else {
14214 			dest->pmode = invalid;
14215 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14216 			    "Tape drive reported block position as unknown\n");
14217 		}
14218 		break;
14219 	}
14220 
14221 	case LONG_POS: /* Long data format */
14222 	{
14223 		uint64_t value;
14224 		tape_position_long_t *long_pos_info =
14225 		    (tape_position_long_t *)responce;
14226 
14227 		/* If reserved fields are non zero don't use the data */
14228 		if ((long_pos_info->reserved0) ||
14229 		    (long_pos_info->reserved1) ||
14230 		    (long_pos_info->reserved2)) {
14231 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14232 			    "Invalid Read Long Position Data returned\n");
14233 			rval = ENOTTY;
14234 			break;
14235 		}
14236 
14237 		/* Is position Valid */
14238 		if (long_pos_info->blk_posi_unkwn == 0) {
14239 			uint32_t part;
14240 
14241 			value = long_pos_info->block_number;
14242 			FIX_ENDIAN64(&value);
14243 
14244 			/*
14245 			 * If it says we are at the begining of partition
14246 			 * the block value better be 0.
14247 			 */
14248 			if ((long_pos_info->begin_of_part == 1) &&
14249 			    (value != 0)) {
14250 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14251 				    "LONG_POS returned begin of partition but"
14252 				    " block number was 0x%"PRIx64"\n", value);
14253 				rval = ENOTTY;
14254 				break;
14255 			}
14256 			/*
14257 			 * Can't be at the start and the end of the partition
14258 			 * at the same time if the partition is larger the 0.
14259 			 */
14260 			if (long_pos_info->begin_of_part &&
14261 			    long_pos_info->end_of_part) {
14262 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14263 				    "LONG_POS returned begin and end of"
14264 				    " partition\n");
14265 				rval = ENOTTY;
14266 				break;
14267 			}
14268 
14269 			/*
14270 			 * If the logical block number is not what we expected.
14271 			 */
14272 			if (dest->lgclblkno != value) {
14273 				if (flag)
14274 					flag++;
14275 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14276 				    "LONG_POS current logical 0x%"PRIx64
14277 				    " read 0x%"PRIx64"\n",
14278 				    dest->lgclblkno, value);
14279 			}
14280 			dest->lgclblkno = value;
14281 
14282 			/*
14283 			 * If the begining of partition is true and the
14284 			 * block number is zero we will beleive that it is
14285 			 * rewound. Promote the pmode to legacy.
14286 			 */
14287 			if ((long_pos_info->begin_of_part == 1) &&
14288 			    (long_pos_info->block_number == 0)) {
14289 				dest->blkno = 0;
14290 				dest->fileno = 0;
14291 				if (dest->pmode != legacy)
14292 					dest->pmode = legacy;
14293 			/*
14294 			 * otherwise if the pmode was invalid,
14295 			 * promote it to logical.
14296 			 */
14297 			} else if (dest->pmode == invalid) {
14298 				dest->pmode = logical;
14299 			}
14300 
14301 			part = long_pos_info->partition;
14302 			FIX_ENDIAN32(&part);
14303 			if (dest->partition != part) {
14304 				if (flag)
14305 					flag++;
14306 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14307 				    "LONG_POS current partition %d"
14308 				    " read %d\n", dest->partition, part);
14309 			}
14310 			dest->partition = part;
14311 		} else {
14312 			/*
14313 			 * If the drive doesn't know location,
14314 			 * we don't either.
14315 			 */
14316 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14317 			    "Tape drive reported block position as unknown\n");
14318 			dest->pmode = invalid;
14319 		}
14320 
14321 		/* Is file position valid */
14322 		if (long_pos_info->mrk_posi_unkwn == 0) {
14323 			value = long_pos_info->file_number;
14324 			FIX_ENDIAN64(&value);
14325 			/*
14326 			 * If it says we are at the begining of partition
14327 			 * the block value better be 0.
14328 			 */
14329 			if ((long_pos_info->begin_of_part == 1) &&
14330 			    (value != 0)) {
14331 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14332 				    "LONG_POS returned begin of partition but"
14333 				    " block number was 0x%"PRIx64"\n", value);
14334 				rval = ENOTTY;
14335 				break;
14336 			}
14337 			if (((dest->pmode == legacy) ||
14338 			    (dest->pmode == logical)) &&
14339 			    (dest->fileno != value)) {
14340 				if (flag)
14341 					flag++;
14342 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14343 				    "LONG_POS fileno 0x%"PRIx64
14344 				    " not un_pos %x\n", value,
14345 				    dest->fileno);
14346 			} else if (dest->pmode == invalid) {
14347 				dest->pmode = logical;
14348 			}
14349 			dest->fileno = (int32_t)value;
14350 		} else {
14351 			/*
14352 			 * If the drive doesn't know its position,
14353 			 * we don't either.
14354 			 */
14355 			dest->pmode = invalid;
14356 		}
14357 		if (dest->pmode != invalid && long_pos_info->end_of_part) {
14358 			dest->eof = ST_EOT;
14359 		}
14360 
14361 		break;
14362 	}
14363 
14364 	case EXT_POS: /* Extended data format */
14365 	{
14366 		uint64_t value;
14367 		uint16_t len;
14368 		tape_position_ext_t *ext_pos_info =
14369 		    (tape_position_ext_t *)responce;
14370 
14371 		/* Make sure that there is enough data there */
14372 		if (data_sz < 16) {
14373 			break;
14374 		}
14375 
14376 		/* If reserved fields are non zero don't use the data */
14377 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
14378 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14379 			    "EXT_POS reserved fields not zero\n");
14380 			rval = ENOTTY;
14381 			break;
14382 		}
14383 
14384 		/*
14385 		 * In the unlikely event of overflowing 64 bits of position.
14386 		 */
14387 		if (ext_pos_info->posi_err != 0) {
14388 			rval = ERANGE;
14389 			break;
14390 		}
14391 
14392 		len = ext_pos_info->parameter_len;
14393 		FIX_ENDIAN16(&len);
14394 
14395 		if (len != 0x1c) {
14396 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14397 			    "EXT_POS parameter_len should be 0x1c was 0x%x\n",
14398 			    len);
14399 			rval = ENOTTY;
14400 			break;
14401 		}
14402 
14403 		/* Is block position information valid */
14404 		if (ext_pos_info->blk_posi_unkwn == 0) {
14405 
14406 			value = ext_pos_info->host_block;
14407 			FIX_ENDIAN64(&value);
14408 			if ((ext_pos_info->begin_of_part == 1) &&
14409 			    (value != 0)) {
14410 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14411 				    "EXT_POS returned begining of partition but"
14412 				    " the host block was 0x%"PRIx64"\n", value);
14413 				rval = ENOTTY;
14414 				break;
14415 			}
14416 
14417 			if (dest->lgclblkno != value) {
14418 				if (flag)
14419 					flag++;
14420 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14421 				    "EXT_POS current logical 0x%"PRIx64
14422 				    " read 0x%"PRIx64"\n",
14423 				    dest->lgclblkno, value);
14424 			}
14425 			dest->lgclblkno = value;
14426 
14427 			/*
14428 			 * If the begining of partition is true and the
14429 			 * block number is zero we will beleive that it is
14430 			 * rewound. Promote the pmode to legacy.
14431 			 */
14432 			if ((ext_pos_info->begin_of_part == 1) &&
14433 			    (ext_pos_info->host_block == 0)) {
14434 				dest->blkno = 0;
14435 				dest->fileno = 0;
14436 				if (dest->pmode != legacy) {
14437 					dest->pmode = legacy;
14438 				}
14439 			/*
14440 			 * otherwise if the pmode was invalid,
14441 			 * promote it to logical.
14442 			 */
14443 			} else if (dest->pmode == invalid) {
14444 				dest->pmode = logical;
14445 			}
14446 
14447 			if (dest->partition != ext_pos_info->partition) {
14448 				if (flag)
14449 					flag++;
14450 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14451 				    "EXT_POS current partition %d read %d\n",
14452 				    dest->partition,
14453 				    ext_pos_info->partition);
14454 			}
14455 			dest->partition = ext_pos_info->partition;
14456 
14457 		} else {
14458 			dest->pmode = invalid;
14459 		}
14460 		break;
14461 	}
14462 
14463 	default:
14464 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14465 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
14466 		rval = EIO;
14467 	}
14468 
14469 	if ((flag > 1) && (rval == 0)) {
14470 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14471 		    "position read in", &org);
14472 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14473 		    "position read out", dest);
14474 	}
14475 
14476 	return (rval);
14477 }
14478 
14479 static int
14480 st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos,
14481     uint64_t lblk, uchar_t partition)
14482 {
14483 	int rval;
14484 	char cdb[CDB_GROUP4];
14485 	struct uscsi_cmd *cmd;
14486 	struct scsi_extended_sense sense;
14487 	bufunc_t bf = (ubf == st_uscsi_cmd) ? st_cmd : st_rcmd;
14488 
14489 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
14490 	/*
14491 	 * WTF Not sure what to do when doing recovery and not wanting
14492 	 * to update un_pos
14493 	 */
14494 
14495 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14496 
14497 	if (lblk <= INT32_MAX) {
14498 		cmd->uscsi_cdblen = CDB_GROUP1;
14499 		cdb[0] = SCMD_LOCATE;
14500 		cdb[1] = pos->partition == partition ? 0 : 2;
14501 		cdb[2] = 0;
14502 		cdb[3] = (char)(lblk >> 24);
14503 		cdb[4] = (char)(lblk >> 16);
14504 		cdb[5] = (char)(lblk >> 8);
14505 		cdb[6] = (char)(lblk);
14506 		cdb[7] = 0;
14507 		cdb[8] = partition;
14508 		cdb[9] = 0;
14509 	} else {
14510 		/*
14511 		 * If the drive doesn't give a 64 bit read position data
14512 		 * it is unlikely it will accept 64 bit locates.
14513 		 */
14514 		if (un->un_read_pos_type != LONG_POS) {
14515 			kmem_free(cmd, sizeof (struct uscsi_cmd));
14516 			return (ERANGE);
14517 		}
14518 		cmd->uscsi_cdblen = CDB_GROUP4;
14519 		cdb[0] = (char)SCMD_LOCATE_G4;
14520 		cdb[1] = pos->partition == partition ? 0 : 2;
14521 		cdb[2] = 0;
14522 		cdb[3] = partition;
14523 		cdb[4] = (char)(lblk >> 56);
14524 		cdb[5] = (char)(lblk >> 48);
14525 		cdb[6] = (char)(lblk >> 40);
14526 		cdb[7] = (char)(lblk >> 32);
14527 		cdb[8] = (char)(lblk >> 24);
14528 		cdb[9] = (char)(lblk >> 16);
14529 		cdb[10] = (char)(lblk >> 8);
14530 		cdb[11] = (char)(lblk);
14531 		cdb[12] = 0;
14532 		cdb[13] = 0;
14533 		cdb[14] = 0;
14534 		cdb[15] = 0;
14535 	}
14536 
14537 
14538 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
14539 	cmd->uscsi_rqbuf = (caddr_t)&sense;
14540 	cmd->uscsi_rqlen = sizeof (sense);
14541 	cmd->uscsi_timeout = un->un_dp->space_timeout;
14542 	cmd->uscsi_cdb = cdb;
14543 
14544 	rval = ubf(un, cmd, FKIOCTL);
14545 
14546 	pos->pmode = logical;
14547 	pos->eof = ST_NO_EOF;
14548 
14549 	if (lblk > INT32_MAX) {
14550 		/*
14551 		 * XXX This is a work around till we handle Descriptor format
14552 		 * sense data. Since we are sending a command where the standard
14553 		 * sense data can not correctly represent a correct residual in
14554 		 * 4 bytes.
14555 		 */
14556 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
14557 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14558 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
14559 			/* Doesn't like big locate command */
14560 			un->un_status = 0;
14561 			rval = ERANGE;
14562 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
14563 			/* Aborted big locate command */
14564 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14565 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
14566 			    rval);
14567 			un->un_status = 0;
14568 			rval = EIO;
14569 		} else if (st_update_block_pos(un, bf, 1)) {
14570 			/* read position failed */
14571 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14572 			    "Big LOCATE and read pos: rval = %d\n", rval);
14573 			rval = EIO;
14574 		} else if (lblk > un->un_pos.lgclblkno) {
14575 			/* read position worked but position was not expected */
14576 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14577 			    "Big LOCATE and recover read less then desired 0x%"
14578 			    PRIx64"\n", un->un_pos.lgclblkno);
14579 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
14580 			un->un_status = KEY_BLANK_CHECK;
14581 			rval = ESPIPE;
14582 		} else if (lblk == un->un_pos.lgclblkno) {
14583 			/* read position was what was expected */
14584 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14585 			    "Big LOCATE and recover seems to have worked\n");
14586 			un->un_err_resid = 0;
14587 			rval = 0;
14588 		} else {
14589 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14590 			    "BIGLOCATE end up going backwards");
14591 			un->un_err_resid = lblk;
14592 			rval = EIO;
14593 		}
14594 
14595 	} else if (rval == 0) {
14596 		/* Worked as requested */
14597 		pos->lgclblkno = lblk;
14598 
14599 	} else if (((cmd->uscsi_status & STATUS_MASK) == STATUS_CHECK) &&
14600 	    (cmd->uscsi_resid != 0)) {
14601 		/* Got part way there but wasn't enough blocks on tape */
14602 		pos->lgclblkno = lblk - cmd->uscsi_resid;
14603 		un->un_err_resid = cmd->uscsi_resid;
14604 		un->un_status = KEY_BLANK_CHECK;
14605 		rval = ESPIPE;
14606 
14607 	} else if (st_update_block_pos(un, bf, 1) == 0) {
14608 		/* Got part way there but drive didn't tell what we missed by */
14609 		un->un_err_resid = lblk - pos->lgclblkno;
14610 		un->un_status = KEY_BLANK_CHECK;
14611 		rval = ESPIPE;
14612 
14613 	} else {
14614 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14615 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
14616 		    rval, cmd->uscsi_status);
14617 		un->un_err_resid = lblk;
14618 		un->un_status = KEY_ILLEGAL_REQUEST;
14619 		pos->pmode = invalid;
14620 		rval = EIO;
14621 	}
14622 
14623 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14624 
14625 	return (rval);
14626 }
14627 
14628 static int
14629 st_mtfsf_ioctl(struct scsi_tape *un, int files)
14630 {
14631 	int rval;
14632 
14633 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
14634 
14635 
14636 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14637 	    "st_mtfsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
14638 #if 0
14639 	if ((IN_EOF(un->un_pos)) && (files == 1)) {
14640 		un->un_pos.fileno++;
14641 		un->un_pos.blkno = 0;
14642 		return (0);
14643 	}
14644 #endif
14645 	/* pmode == invalid already handled */
14646 	if (un->un_pos.pmode == legacy) {
14647 		/*
14648 		 * forward space over filemark
14649 		 *
14650 		 * For ASF we allow a count of 0 on fsf which means
14651 		 * we just want to go to beginning of current file.
14652 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
14653 		 * Allow stepping over double fmk with reel
14654 		 */
14655 		if ((un->un_pos.eof >= ST_EOT) &&
14656 		    (files > 0) &&
14657 		    ((un->un_dp->options & ST_REEL) == 0)) {
14658 			/* we're at EOM */
14659 			un->un_err_resid = files;
14660 			un->un_status = KEY_BLANK_CHECK;
14661 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14662 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
14663 			return (EIO);
14664 		}
14665 
14666 		/*
14667 		 * physical tape position may not be what we've been
14668 		 * telling the user; adjust the request accordingly
14669 		 */
14670 		if (IN_EOF(un->un_pos)) {
14671 			un->un_pos.fileno++;
14672 			un->un_pos.blkno = 0;
14673 			/*
14674 			 * For positive direction case, we're now covered.
14675 			 * For zero or negative direction, we're covered
14676 			 * (almost)
14677 			 */
14678 			files--;
14679 		}
14680 
14681 	}
14682 
14683 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
14684 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14685 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
14686 		return (EIO);
14687 	}
14688 
14689 
14690 	/*
14691 	 * Forward space file marks.
14692 	 * We leave ourselves at block zero
14693 	 * of the target file number.
14694 	 */
14695 	if (files < 0) {
14696 		rval = st_backward_space_files(un, -files, 0);
14697 	} else {
14698 		rval = st_forward_space_files(un, files);
14699 	}
14700 
14701 	return (rval);
14702 }
14703 
14704 static int
14705 st_forward_space_files(struct scsi_tape *un, int count)
14706 {
14707 	int rval;
14708 
14709 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
14710 
14711 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14712 	    "fspace: count=%x, eof=%x\n", count, un->un_pos.eof);
14713 
14714 	ASSERT(count >= 0);
14715 	ASSERT(un->un_pos.pmode != invalid);
14716 
14717 	/*
14718 	 * A space with a count of zero means take me to the start of file.
14719 	 */
14720 	if (count == 0) {
14721 
14722 		/* Hay look were already there */
14723 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0) {
14724 			un->un_err_resid = 0;
14725 			COPY_POS(&un->un_err_pos, &un->un_pos);
14726 			return (0);
14727 		}
14728 
14729 		/*
14730 		 * Well we are in the first file.
14731 		 * A rewind will get to the start.
14732 		 */
14733 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
14734 			rval = st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
14735 
14736 		/*
14737 		 * Can we backspace to get there?
14738 		 * This should work in logical mode.
14739 		 */
14740 		} else if (un->un_dp->options & ST_BSF) {
14741 			rval = st_space_to_begining_of_file(un);
14742 
14743 		/*
14744 		 * Can't back space but current file number is known,
14745 		 * So rewind and space from the begining of the partition.
14746 		 */
14747 		} else if (un->un_pos.pmode == legacy) {
14748 			rval = st_scenic_route_to_begining_of_file(un,
14749 			    un->un_pos.fileno);
14750 
14751 		/*
14752 		 * pmode is logical and ST_BSF is not set.
14753 		 * The LONG_POS read position contains the fileno.
14754 		 * If the read position works, rewind and space.
14755 		 */
14756 		} else if (un->un_read_pos_type == LONG_POS) {
14757 			rval = st_cmd(un, SCMD_READ_POSITION, 0, SYNC_CMD);
14758 			if (rval) {
14759 				/*
14760 				 * We didn't get the file position from the
14761 				 * read position command.
14762 				 * We are going to trust the drive to backspace
14763 				 * and then position after the filemark.
14764 				 */
14765 				rval = st_space_to_begining_of_file(un);
14766 			}
14767 			rval = st_interpret_read_pos(un, &un->un_pos, LONG_POS,
14768 			    32, (caddr_t)un->un_read_pos_data, 0);
14769 			if ((rval) && (un->un_pos.pmode == invalid)) {
14770 				rval = st_space_to_begining_of_file(un);
14771 			} else {
14772 				rval = st_scenic_route_to_begining_of_file(un,
14773 				    un->un_pos.fileno);
14774 			}
14775 		} else {
14776 			rval = EIO;
14777 		}
14778 		/*
14779 		 * If something didn't work we are lost
14780 		 */
14781 		if (rval != 0) {
14782 			un->un_pos.pmode = invalid;
14783 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14784 			    "st_mtioctop : EIO : fspace pmode invalid");
14785 
14786 			rval = EIO;
14787 		}
14788 
14789 	} else {
14790 		rval = st_space_fmks(un, count);
14791 	}
14792 
14793 	if (rval != EIO && count < 0) {
14794 		/*
14795 		 * we came here with a count < 0; we now need
14796 		 * to skip back to end up before the filemark
14797 		 */
14798 		rval = st_backward_space_files(un, 1, 1);
14799 	}
14800 
14801 	return (rval);
14802 }
14803 
14804 static int
14805 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
14806 {
14807 	int rval;
14808 
14809 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
14810 
14811 	if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
14812 		rval = EIO;
14813 	} else if (st_cmd(un, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
14814 		rval = EIO;
14815 	}
14816 
14817 	return (rval);
14818 }
14819 
14820 static int
14821 st_space_to_begining_of_file(struct scsi_tape *un)
14822 {
14823 	int rval;
14824 
14825 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
14826 
14827 	/*
14828 	 * Back space of the file at the begining of the file.
14829 	 */
14830 	rval = st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
14831 	if (rval) {
14832 		rval = EIO;
14833 		return (rval);
14834 	}
14835 
14836 	/*
14837 	 * Other interesting answers might be crashed BOT which isn't bad.
14838 	 */
14839 	if (un->un_status == SUN_KEY_BOT) {
14840 		return (rval);
14841 	}
14842 
14843 	un->un_running.pmode = invalid;
14844 
14845 	/*
14846 	 * Now we are on the BOP side of the filemark. Forward space to
14847 	 * the EOM side and we are at the begining of the file.
14848 	 */
14849 	rval = st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD);
14850 	if (rval) {
14851 		rval = EIO;
14852 	}
14853 
14854 	return (rval);
14855 }
14856 
14857 static int
14858 st_mtfsr_ioctl(struct scsi_tape *un, int count)
14859 {
14860 
14861 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
14862 
14863 	/*
14864 	 * forward space to inter-record gap
14865 	 *
14866 	 */
14867 
14868 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14869 	    "st_ioctl_fsr: count=%x, eof=%x\n", count, un->un_pos.eof);
14870 
14871 	if (un->un_pos.pmode == legacy) {
14872 		/*
14873 		 * If were are at end of tape and count is forward.
14874 		 * Return blank check.
14875 		 */
14876 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
14877 			/* we're at EOM */
14878 			un->un_err_resid = count;
14879 			un->un_status = KEY_BLANK_CHECK;
14880 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14881 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
14882 			return (EIO);
14883 		}
14884 
14885 		/*
14886 		 * If count is zero there is nothing to do.
14887 		 */
14888 		if (count == 0) {
14889 			un->un_err_pos.fileno = un->un_pos.fileno;
14890 			un->un_err_pos.blkno = un->un_pos.blkno;
14891 			un->un_err_resid = 0;
14892 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
14893 				un->un_status = SUN_KEY_EOF;
14894 			}
14895 			return (0);
14896 		}
14897 
14898 		/*
14899 		 * physical tape position may not be what we've been
14900 		 * telling the user; adjust the position accordingly
14901 		 */
14902 		if (IN_EOF(un->un_pos)) {
14903 			daddr_t blkno = un->un_pos.blkno;
14904 			int fileno = un->un_pos.fileno;
14905 
14906 			optype lastop = un->un_lastop;
14907 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)
14908 			    == -1) {
14909 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14910 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
14911 				return (EIO);
14912 			}
14913 
14914 			un->un_pos.blkno = blkno;
14915 			un->un_pos.fileno = fileno;
14916 			un->un_lastop = lastop;
14917 		}
14918 	}
14919 
14920 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
14921 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14922 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
14923 		return (EIO);
14924 	}
14925 
14926 	return (st_space_records(un, count));
14927 }
14928 
14929 static int
14930 st_space_records(struct scsi_tape *un, int count)
14931 {
14932 	int dblk;
14933 	int rval = 0;
14934 
14935 	ST_FUNC(ST_DEVINFO, st_space_records);
14936 
14937 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14938 	    "st_space_records: count=%x, eof=%x\n", count, un->un_pos.eof);
14939 
14940 	if (un->un_pos.pmode == logical) {
14941 		rval = st_cmd(un, SCMD_SPACE, Blk(count), SYNC_CMD);
14942 		if (rval != 0) {
14943 			rval = EIO;
14944 		}
14945 		return (rval);
14946 	}
14947 
14948 	dblk = un->un_pos.blkno + count;
14949 
14950 	/* Already there */
14951 	if (dblk == un->un_pos.blkno) {
14952 		un->un_err_resid = 0;
14953 		COPY_POS(&un->un_err_pos, &un->un_pos);
14954 		return (0);
14955 	}
14956 
14957 	/*
14958 	 * If the destination block is forward
14959 	 * or the drive will backspace records.
14960 	 */
14961 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
14962 		/*
14963 		 * If we're spacing forward, or the device can
14964 		 * backspace records, we can just use the SPACE
14965 		 * command.
14966 		 */
14967 		dblk -= un->un_pos.blkno;
14968 		if (st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
14969 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14970 			    "st_space_records:EIO:space_records can't spc");
14971 			rval = EIO;
14972 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
14973 			/*
14974 			 * check if we hit BOT/EOT
14975 			 */
14976 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
14977 				un->un_status = SUN_KEY_BOT;
14978 				un->un_pos.eof = ST_NO_EOF;
14979 			} else if (dblk < 0 &&
14980 			    un->un_pos.eof == ST_EOF_PENDING) {
14981 				int residue = un->un_err_resid;
14982 				/*
14983 				 * we skipped over a filemark
14984 				 * and need to go forward again
14985 				 */
14986 				if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
14987 					ST_DEBUG2(ST_DEVINFO, st_label,
14988 					    SCSI_DEBUG, "st_space_records: EIO"
14989 					    " : can't space #2");
14990 					rval = EIO;
14991 				}
14992 				un->un_err_resid = residue;
14993 			}
14994 			if (rval == 0) {
14995 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14996 				    "st_space_records: EIO : space_rec rval"
14997 				    " == 0");
14998 				rval = EIO;
14999 			}
15000 		}
15001 	} else {
15002 		/*
15003 		 * else we rewind, space forward across filemarks to
15004 		 * the desired file, and then space records to the
15005 		 * desired block.
15006 		 */
15007 
15008 		int dfile = un->un_pos.fileno;	/* save current file */
15009 
15010 		if (dblk < 0) {
15011 			/*
15012 			 * Wups - we're backing up over a filemark
15013 			 */
15014 			if (un->un_pos.blkno != 0 &&
15015 			    (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15016 			    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD))) {
15017 				un->un_pos.pmode = invalid;
15018 			}
15019 			un->un_err_resid = -dblk;
15020 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
15021 				un->un_status = SUN_KEY_BOT;
15022 				un->un_pos.eof = ST_NO_EOF;
15023 			} else if (un->un_pos.fileno > 0) {
15024 				un->un_status = SUN_KEY_EOF;
15025 				un->un_pos.eof = ST_NO_EOF;
15026 			}
15027 			COPY_POS(&un->un_err_pos, &un->un_pos);
15028 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15029 			    "st_space_records:EIO:space_records : dblk < 0");
15030 			rval = EIO;
15031 		} else if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15032 		    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
15033 		    st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15034 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15035 			    "st_space_records: EIO :space_records : rewind "
15036 			    "and space failed");
15037 			un->un_pos.pmode = invalid;
15038 			rval = EIO;
15039 		}
15040 	}
15041 
15042 	return (rval);
15043 }
15044 
15045 static int
15046 st_mtbsf_ioctl(struct scsi_tape *un, int files)
15047 {
15048 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
15049 
15050 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15051 	    "st_mtbsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
15052 	/*
15053 	 * backward space of file filemark (1/2" and 8mm)
15054 	 * tape position will end on the beginning of tape side
15055 	 * of the desired file mark
15056 	 */
15057 	if ((un->un_dp->options & ST_BSF) == 0) {
15058 		return (ENOTTY);
15059 	}
15060 
15061 	if (un->un_pos.pmode == legacy) {
15062 
15063 		/*
15064 		 * If a negative count (which implies a forward space op)
15065 		 * is specified, and we're at logical or physical eot,
15066 		 * bounce the request.
15067 		 */
15068 
15069 		if (un->un_pos.eof >= ST_EOT && files < 0) {
15070 			un->un_err_resid = files;
15071 			un->un_status = SUN_KEY_EOT;
15072 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15073 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
15074 			return (EIO);
15075 		}
15076 		/*
15077 		 * physical tape position may not be what we've been
15078 		 * telling the user; adjust the request accordingly
15079 		 */
15080 		if (IN_EOF(un->un_pos)) {
15081 			un->un_pos.fileno++;
15082 			un->un_pos.blkno = 0;
15083 			files++;
15084 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15085 			    "st_mtbsf_ioctl in eof: count=%d, op=%x\n",
15086 			    files, MTBSF);
15087 
15088 		}
15089 	}
15090 
15091 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15092 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15093 		    "st_ioctl : EIO : MTBSF : check den wfm");
15094 		return (EIO);
15095 	}
15096 
15097 	if (files <= 0) {
15098 		/*
15099 		 * for a negative count, we need to step forward
15100 		 * first and then step back again
15101 		 */
15102 		files = -files + 1;
15103 		return (st_forward_space_files(un, files));
15104 	}
15105 	return (st_backward_space_files(un, files, 1));
15106 }
15107 
15108 static int
15109 st_backward_space_files(struct scsi_tape *un, int count, int infront)
15110 {
15111 	int end_fileno;
15112 	int skip_cnt;
15113 	int rval = 0;
15114 
15115 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
15116 
15117 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15118 	    "st_backward_space_files: count=%x eof=%x\n",
15119 	    count, un->un_pos.eof);
15120 	/*
15121 	 * Backspace files (MTNBSF): infront == 0
15122 	 *
15123 	 *	For tapes that can backspace, backspace
15124 	 *	count+1 filemarks and then run forward over
15125 	 *	a filemark
15126 	 *
15127 	 *	For tapes that can't backspace,
15128 	 *		calculate desired filenumber
15129 	 *		(un->un_pos.fileno - count), rewind,
15130 	 *		and then space forward this amount
15131 	 *
15132 	 * Backspace filemarks (MTBSF) infront == 1
15133 	 *
15134 	 *	For tapes that can backspace, backspace count
15135 	 *	filemarks
15136 	 *
15137 	 *	For tapes that can't backspace, calculate
15138 	 *	desired filenumber (un->un_pos.fileno - count),
15139 	 *	add 1, rewind, space forward this amount,
15140 	 *	and mark state as ST_EOF_PENDING appropriately.
15141 	 */
15142 
15143 	if (un->un_pos.pmode == logical) {
15144 
15145 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15146 		    "st_backward_space_files: mt_op=%x count=%x"
15147 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
15148 		    un->un_pos.lgclblkno);
15149 
15150 
15151 		/* In case a drive that won't back space gets in logical mode */
15152 		if ((un->un_dp->options & ST_BSF) == 0) {
15153 			rval = EIO;
15154 			return (rval);
15155 		}
15156 		if (st_cmd(un, SCMD_SPACE, Fmk(-count), SYNC_CMD)) {
15157 			rval = EIO;
15158 			return (rval);
15159 		}
15160 		if ((infront != 0) &&
15161 		    (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
15162 			rval = EIO;
15163 			return (rval);
15164 		}
15165 		return (rval);
15166 	}
15167 
15168 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15169 	    "st_backward_space_files: mt_op=%x count=%x fileno=%x blkno=%x\n",
15170 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
15171 
15172 
15173 
15174 	/*
15175 	 * Handle the simple case of BOT
15176 	 * playing a role in these cmds.
15177 	 * We do this by calculating the
15178 	 * ending file number. If the ending
15179 	 * file is < BOT, rewind and set an
15180 	 * error and mark resid appropriately.
15181 	 * If we're backspacing a file (not a
15182 	 * filemark) and the target file is
15183 	 * the first file on the tape, just
15184 	 * rewind.
15185 	 */
15186 
15187 	/* figure expected destination of this SPACE command */
15188 	end_fileno = un->un_pos.fileno - count;
15189 
15190 	/*
15191 	 * Would the end effect of this SPACE be the same as rewinding?
15192 	 * If so just rewind instead.
15193 	 */
15194 	if ((infront != 0) && (end_fileno < 0) ||
15195 	    (infront == 0) && (end_fileno <= 0)) {
15196 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15197 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15198 			    "st_backward_space_files: EIO : "
15199 			    "rewind in lou of BSF failed\n");
15200 			rval = EIO;
15201 		}
15202 		if (end_fileno < 0) {
15203 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15204 			    "st_backward_space_files: EIO : "
15205 			    "back space file greater then fileno\n");
15206 			rval = EIO;
15207 			un->un_err_resid = -end_fileno;
15208 			un->un_status = SUN_KEY_BOT;
15209 		}
15210 		return (rval);
15211 	}
15212 
15213 	if (un->un_dp->options & ST_BSF) {
15214 		skip_cnt = 1 - infront;
15215 		/*
15216 		 * If we are going to end up at the beginning
15217 		 * of the file, we have to space one extra file
15218 		 * first, and then space forward later.
15219 		 */
15220 		end_fileno = -(count + skip_cnt);
15221 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15222 		    "skip_cnt=%x, tmp=%x\n", skip_cnt, end_fileno);
15223 		if (st_cmd(un, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
15224 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15225 			    "st_backward_space_files:EIO:back space fm failed");
15226 			rval = EIO;
15227 		}
15228 	} else {
15229 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15230 			rval = EIO;
15231 		} else {
15232 			skip_cnt = end_fileno + infront;
15233 		}
15234 	}
15235 
15236 	/*
15237 	 * If we have to space forward, do so...
15238 	 */
15239 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15240 	    "space forward skip_cnt=%x, rval=%x\n", skip_cnt, rval);
15241 
15242 	if (rval == 0 && skip_cnt) {
15243 		if (st_cmd(un, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
15244 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15245 			    "st_backward_space_files:EIO:space fm skip count");
15246 			rval = EIO;
15247 		} else if (infront) {
15248 			/*
15249 			 * If we had to space forward, and we're
15250 			 * not a tape that can backspace, mark state
15251 			 * as if we'd just seen a filemark during a
15252 			 * a read.
15253 			 */
15254 			if ((un->un_dp->options & ST_BSF) == 0) {
15255 				un->un_pos.eof = ST_EOF_PENDING;
15256 				un->un_pos.fileno -= 1;
15257 				un->un_pos.blkno = INF;
15258 				un->un_running.pmode = invalid;
15259 			}
15260 		}
15261 	}
15262 
15263 	if (rval != 0) {
15264 		un->un_pos.pmode = invalid;
15265 	}
15266 
15267 	return (rval);
15268 }
15269 
15270 static int
15271 st_mtnbsf_ioctl(struct scsi_tape *un, int count)
15272 {
15273 	int rval;
15274 
15275 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
15276 
15277 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15278 	    "nbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
15279 
15280 	if (un->un_pos.pmode == legacy) {
15281 		/*
15282 		 * backward space file to beginning of file
15283 		 *
15284 		 * If a negative count (which implies a forward space op)
15285 		 * is specified, and we're at logical or physical eot,
15286 		 * bounce the request.
15287 		 */
15288 
15289 		if (un->un_pos.eof >= ST_EOT && count < 0) {
15290 			un->un_err_resid = count;
15291 			un->un_status = SUN_KEY_EOT;
15292 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15293 			    "st_ioctl : EIO : > EOT and count < 0");
15294 			return (EIO);
15295 		}
15296 		/*
15297 		 * physical tape position may not be what we've been
15298 		 * telling the user; adjust the request accordingly
15299 		 */
15300 		if (IN_EOF(un->un_pos)) {
15301 			un->un_pos.fileno++;
15302 			un->un_pos.blkno = 0;
15303 			count++;
15304 		}
15305 	}
15306 
15307 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15308 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15309 		    "st_ioctl : EIO : MTNBSF check den and wfm");
15310 		return (EIO);
15311 	}
15312 
15313 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15314 	    "mtnbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
15315 
15316 	if (count <= 0) {
15317 		rval = st_forward_space_files(un, -count);
15318 	} else {
15319 		rval = st_backward_space_files(un, count, 0);
15320 	}
15321 	return (rval);
15322 }
15323 
15324 static int
15325 st_mtbsr_ioctl(struct scsi_tape *un, int num)
15326 {
15327 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
15328 
15329 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15330 	    "bsr: count=%x, eof=%x\n", num, un->un_pos.eof);
15331 
15332 	if (un->un_pos.pmode == legacy) {
15333 		/*
15334 		 * backward space into inter-record gap
15335 		 *
15336 		 * If a negative count (which implies a forward space op)
15337 		 * is specified, and we're at logical or physical eot,
15338 		 * bounce the request.
15339 		 */
15340 		if (un->un_pos.eof >= ST_EOT && num < 0) {
15341 			un->un_err_resid = num;
15342 			un->un_status = SUN_KEY_EOT;
15343 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15344 			    "st_ioctl : EIO : MTBSR > EOT");
15345 			return (EIO);
15346 		}
15347 
15348 		if (num == 0) {
15349 			COPY_POS(&un->un_err_pos, &un->un_pos);
15350 			un->un_err_resid = 0;
15351 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15352 				un->un_status = SUN_KEY_EOF;
15353 			}
15354 			return (0);
15355 		}
15356 
15357 		/*
15358 		 * physical tape position may not be what we've been
15359 		 * telling the user; adjust the position accordingly.
15360 		 * bsr can not skip filemarks and continue to skip records
15361 		 * therefore if we are logically before the filemark but
15362 		 * physically at the EOT side of the filemark, we need to step
15363 		 * back; this allows fsr N where N > number of blocks in file
15364 		 * followed by bsr 1 to position at the beginning of last block
15365 		 */
15366 		if (IN_EOF(un->un_pos)) {
15367 			tapepos_t save;
15368 			optype lastop = un->un_lastop;
15369 
15370 			COPY_POS(&save, &un->un_pos);
15371 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD) == -1) {
15372 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15373 				    "st_mtbsr_ioctl: EIO : MTBSR can't space");
15374 				return (EIO);
15375 			}
15376 
15377 			COPY_POS(&un->un_pos, &save);
15378 			un->un_lastop = lastop;
15379 		}
15380 	}
15381 
15382 	un->un_pos.eof = ST_NO_EOF;
15383 
15384 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15385 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15386 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
15387 		return (EIO);
15388 	}
15389 
15390 	num = -num;
15391 	return (st_space_records(un, num));
15392 }
15393 
15394 static int
15395 st_mtfsfm_ioctl(struct scsi_tape *un, int cnt)
15396 {
15397 	int rval;
15398 
15399 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
15400 
15401 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
15402 	if (rval == 0) {
15403 		un->un_pos.pmode = logical;
15404 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15405 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15406 		/*
15407 		 * Drive says invalid field in cdb.
15408 		 * Doesn't like space multiple. Position isn't lost.
15409 		 */
15410 		un->un_err_resid = cnt;
15411 		un->un_status = 0;
15412 		rval = ENOTTY;
15413 	} else {
15414 		un->un_err_resid = cnt;
15415 		un->un_pos.pmode = invalid;
15416 	}
15417 	return (rval);
15418 }
15419 
15420 static int
15421 st_mtbsfm_ioctl(struct scsi_tape *un, int cnt)
15422 {
15423 	int rval;
15424 
15425 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
15426 
15427 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
15428 	if (rval == 0) {
15429 		un->un_pos.pmode = logical;
15430 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15431 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15432 		/*
15433 		 * Drive says invalid field in cdb.
15434 		 * Doesn't like space multiple. Position isn't lost.
15435 		 */
15436 		un->un_err_resid = cnt;
15437 		un->un_status = 0;
15438 		rval = ENOTTY;
15439 	} else {
15440 		un->un_err_resid = cnt;
15441 		un->un_pos.pmode = invalid;
15442 	}
15443 	return (rval);
15444 }
15445 
15446 #ifdef	__x86
15447 
15448 /*
15449  * release contig_mem and wake up waiting thread, if any
15450  */
15451 static void
15452 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
15453 {
15454 	mutex_enter(ST_MUTEX);
15455 
15456 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
15457 
15458 	cp->cm_next = un->un_contig_mem;
15459 	un->un_contig_mem = cp;
15460 	un->un_contig_mem_available_num++;
15461 	cv_broadcast(&un->un_contig_mem_cv);
15462 
15463 	mutex_exit(ST_MUTEX);
15464 }
15465 
15466 /*
15467  * St_get_contig_mem will return a contig_mem if there is one available
15468  * in current system. Otherwise, it will try to alloc one, if the total
15469  * number of contig_mem is within st_max_contig_mem_num.
15470  * It will sleep, if allowed by caller or return NULL, if no contig_mem
15471  * is available for now.
15472  */
15473 static struct contig_mem *
15474 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
15475 {
15476 	size_t rlen;
15477 	struct contig_mem *cp = NULL;
15478 	ddi_acc_handle_t acc_hdl;
15479 	caddr_t addr;
15480 	int big_enough = 0;
15481 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
15482 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
15483 
15484 	/* Try to get one available contig_mem */
15485 	mutex_enter(ST_MUTEX);
15486 
15487 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
15488 
15489 	if (un->un_contig_mem_available_num > 0) {
15490 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15491 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
15492 		/*
15493 		 * we failed to get one. we're going to
15494 		 * alloc one more contig_mem for this I/O
15495 		 */
15496 		mutex_exit(ST_MUTEX);
15497 		cp = (struct contig_mem *)kmem_zalloc(
15498 		    sizeof (struct contig_mem) + biosize(),
15499 		    alloc_flags);
15500 		if (cp == NULL) {
15501 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15502 			    "alloc contig_mem failure\n");
15503 			return (NULL); /* cannot get one */
15504 		}
15505 		cp->cm_bp = (struct buf *)
15506 		    (((caddr_t)cp) + sizeof (struct contig_mem));
15507 		bioinit(cp->cm_bp);
15508 		mutex_enter(ST_MUTEX);
15509 		un->un_contig_mem_total_num++; /* one more available */
15510 	} else {
15511 		/*
15512 		 * we failed to get one and we're NOT allowed to
15513 		 * alloc more contig_mem
15514 		 */
15515 		if (alloc_flags == KM_SLEEP) {
15516 			while (un->un_contig_mem_available_num <= 0) {
15517 				cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
15518 			}
15519 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15520 		} else {
15521 			mutex_exit(ST_MUTEX);
15522 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15523 			    "alloc contig_mem failure\n");
15524 			return (NULL); /* cannot get one */
15525 		}
15526 	}
15527 	mutex_exit(ST_MUTEX);
15528 
15529 	/* We need to check if this block of mem is big enough for this I/O */
15530 	if (cp->cm_len < len) {
15531 		/* not big enough, need to alloc a new one */
15532 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
15533 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
15534 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
15535 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15536 			    "alloc contig_mem failure: not enough mem\n");
15537 			st_release_contig_mem(un, cp);
15538 			cp = NULL;
15539 		} else {
15540 			if (cp->cm_addr) {
15541 				/* release previous one before attach new one */
15542 				ddi_dma_mem_free(&cp->cm_acc_hdl);
15543 			}
15544 			mutex_enter(ST_MUTEX);
15545 			un->un_max_contig_mem_len =
15546 			    un->un_max_contig_mem_len >= len ?
15547 			    un->un_max_contig_mem_len : len;
15548 			mutex_exit(ST_MUTEX);
15549 
15550 			/* attach new mem to this cp */
15551 			cp->cm_addr = addr;
15552 			cp->cm_acc_hdl = acc_hdl;
15553 			cp->cm_len = len;
15554 
15555 			goto alloc_ok; /* get one usable cp */
15556 		}
15557 	} else {
15558 		goto alloc_ok; /* get one usable cp */
15559 	}
15560 
15561 	/* cannot find/alloc a usable cp, when we get here */
15562 
15563 	mutex_enter(ST_MUTEX);
15564 	if ((un->un_max_contig_mem_len < len) ||
15565 	    (alloc_flags != KM_SLEEP)) {
15566 		mutex_exit(ST_MUTEX);
15567 		return (NULL);
15568 	}
15569 
15570 	/*
15571 	 * we're allowed to sleep, and there is one big enough
15572 	 * contig mem in the system, which is currently in use,
15573 	 * wait for it...
15574 	 */
15575 	big_enough = 1;
15576 	do {
15577 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
15578 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15579 	} while (cp == NULL);
15580 	mutex_exit(ST_MUTEX);
15581 
15582 	/* we get the big enough contig mem, finally */
15583 
15584 alloc_ok:
15585 	/* init bp attached to this cp */
15586 	bioreset(cp->cm_bp);
15587 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
15588 	cp->cm_bp->b_private = (void *)cp;
15589 
15590 	return (cp);
15591 }
15592 
15593 /*
15594  * this is the biodone func for the bp used in big block I/O
15595  */
15596 static int
15597 st_bigblk_xfer_done(struct buf *bp)
15598 {
15599 	struct contig_mem *cp;
15600 	struct buf *orig_bp;
15601 	int ioerr;
15602 	struct scsi_tape *un;
15603 
15604 	/* sanity check */
15605 	if (bp == NULL) {
15606 		return (DDI_FAILURE);
15607 	}
15608 
15609 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
15610 	if (un == NULL) {
15611 		return (DDI_FAILURE);
15612 	}
15613 
15614 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
15615 
15616 	cp = (struct contig_mem *)bp->b_private;
15617 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
15618 	cp->cm_bp = bp;
15619 
15620 	/* special handling for special I/O */
15621 	if (cp->cm_use_sbuf) {
15622 #ifndef __lock_lint
15623 		ASSERT(un->un_sbuf_busy);
15624 #endif
15625 		un->un_sbufp = orig_bp;
15626 		cp->cm_use_sbuf = 0;
15627 	}
15628 
15629 	orig_bp->b_resid = bp->b_resid;
15630 	ioerr = geterror(bp);
15631 	if (ioerr != 0) {
15632 		bioerror(orig_bp, ioerr);
15633 	} else if (orig_bp->b_flags & B_READ) {
15634 		/* copy data back to original bp */
15635 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
15636 		    bp->b_bcount - bp->b_resid);
15637 	}
15638 
15639 	st_release_contig_mem(un, cp);
15640 
15641 	biodone(orig_bp);
15642 
15643 	return (DDI_SUCCESS);
15644 }
15645 
15646 /*
15647  * We use this func to replace original bp that may not be able to do I/O
15648  * in big block size with one that can
15649  */
15650 static struct buf *
15651 st_get_bigblk_bp(struct buf *bp)
15652 {
15653 	struct contig_mem *cp;
15654 	struct scsi_tape *un;
15655 	struct buf *cont_bp;
15656 
15657 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
15658 	if (un == NULL) {
15659 		return (bp);
15660 	}
15661 
15662 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
15663 
15664 	/* try to get one contig_mem */
15665 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
15666 	if (!cp) {
15667 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
15668 		    "Cannot alloc contig buf for I/O for %lu blk size",
15669 		    bp->b_bcount);
15670 		return (bp);
15671 	}
15672 	cont_bp = cp->cm_bp;
15673 	cp->cm_bp = bp;
15674 
15675 	/* make sure that we "are" using un_sbufp for special I/O */
15676 	if (bp == un->un_sbufp) {
15677 #ifndef __lock_lint
15678 		ASSERT(un->un_sbuf_busy);
15679 #endif
15680 		un->un_sbufp = cont_bp;
15681 		cp->cm_use_sbuf = 1;
15682 	}
15683 
15684 	/* clone bp */
15685 	cont_bp->b_bcount = bp->b_bcount;
15686 	cont_bp->b_resid = bp->b_resid;
15687 	cont_bp->b_iodone = st_bigblk_xfer_done;
15688 	cont_bp->b_file = bp->b_file;
15689 	cont_bp->b_offset = bp->b_offset;
15690 	cont_bp->b_dip = bp->b_dip;
15691 	cont_bp->b_error = 0;
15692 	cont_bp->b_proc = NULL;
15693 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
15694 	cont_bp->b_shadow = NULL;
15695 	cont_bp->b_pages = NULL;
15696 	cont_bp->b_edev = bp->b_edev;
15697 	cont_bp->b_dev = bp->b_dev;
15698 	cont_bp->b_lblkno = bp->b_lblkno;
15699 	cont_bp->b_forw = bp->b_forw;
15700 	cont_bp->b_back = bp->b_back;
15701 	cont_bp->av_forw = bp->av_forw;
15702 	cont_bp->av_back = bp->av_back;
15703 	cont_bp->b_bufsize = bp->b_bufsize;
15704 
15705 	/* get data in original bp */
15706 	if (bp->b_flags & B_WRITE) {
15707 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
15708 	}
15709 
15710 	return (cont_bp);
15711 }
15712 #else
15713 #ifdef __lock_lint
15714 static int
15715 st_bigblk_xfer_done(struct buf *bp)
15716 {
15717 	return (0);
15718 }
15719 #endif
15720 #endif
15721 
15722 static const char *eof_status[] =
15723 {
15724 	"NO_EOF",
15725 	"EOF_PENDING",
15726 	"EOF",
15727 	"EOT_PENDING",
15728 	"EOT",
15729 	"EOM",
15730 	"AFTER_EOM"
15731 };
15732 static const char *mode[] = {
15733 	"invalid",
15734 	"legacy",
15735 	"logical"
15736 };
15737 
15738 static void
15739 st_print_position(dev_info_t *dev, char *label, uint_t level,
15740 const char *comment, tapepos_t *pos)
15741 {
15742 	ST_FUNC(dev, st_print_position);
15743 
15744 	scsi_log(dev, label, level,
15745 	    "%s Position data:\n", comment);
15746 	scsi_log(dev, label, CE_CONT,
15747 	    "Positioning mode = %s", mode[pos->pmode]);
15748 	scsi_log(dev, label, CE_CONT,
15749 	    "End Of File/Tape = %s", eof_status[pos->eof]);
15750 	scsi_log(dev, label, CE_CONT,
15751 	    "File Number      = 0x%x", pos->fileno);
15752 	scsi_log(dev, label, CE_CONT,
15753 	    "Block Number     = 0x%x", pos->blkno);
15754 	scsi_log(dev, label, CE_CONT,
15755 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
15756 	scsi_log(dev, label, CE_CONT,
15757 	    "Partition Number = 0x%x", pos->partition);
15758 }
15759 static int
15760 st_check_if_media_changed(struct scsi_tape *un, caddr_t data, int size)
15761 {
15762 
15763 	int result = 0;
15764 	int i;
15765 	ST_FUNC(ST_DEVINFO, st_check_if_media_changed);
15766 
15767 	/*
15768 	 * find non alpha numeric working from the end.
15769 	 */
15770 	for (i = size - 1; i; i--) {
15771 		if (ISALNUM(data[i]) == 0 || data[i] == ' ') {
15772 			data[i] = 0;
15773 			size = i;
15774 		}
15775 	}
15776 
15777 	if (size == 1) {
15778 		/*
15779 		 * Drive seems to think its returning useful data
15780 		 * but it looks like all junk
15781 		 */
15782 		return (result);
15783 	}
15784 
15785 	size++;
15786 
15787 	/*
15788 	 * Actually got a valid serial number.
15789 	 * If never stored one before alloc space for it.
15790 	 */
15791 	if (un->un_media_id_len == 0) {
15792 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
15793 		un->un_media_id_len = size;
15794 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
15795 		un->un_media_id[min(size, strlen(data))] = 0;
15796 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
15797 		    "Found Media Id %s length = %d\n", un->un_media_id, size);
15798 	} else if (size > un->un_media_id_len) {
15799 		if (strncmp(un->un_media_id, data, size) != 0) {
15800 			result = ESPIPE;
15801 		}
15802 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
15803 		    "Longer Media Id old ID:%s new ID:%s\n",
15804 		    un->un_media_id, data);
15805 		kmem_free(un->un_media_id, un->un_media_id_len);
15806 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
15807 		un->un_media_id_len = size;
15808 		(void) strncpy(un->un_media_id, data, size);
15809 		un->un_media_id[size] = 0;
15810 	} else if (strncmp(data, un->un_media_id,
15811 	    min(size, un->un_media_id_len)) != 0) {
15812 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
15813 		    "Old Media Id %s length = %d New %s length = %d\n",
15814 		    un->un_media_id, un->un_media_id_len, data, size);
15815 		bzero(un->un_media_id, un->un_media_id_len);
15816 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
15817 		un->un_media_id[min(size, strlen(data))] = 0;
15818 		result = ESPIPE;
15819 	} else {
15820 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15821 		    "Media Id still %s\n", un->un_media_id);
15822 	}
15823 
15824 	ASSERT(strlen(un->un_media_id) <= size);
15825 
15826 	return (result);
15827 }
15828 #define	ID_SIZE 32
15829 typedef struct
15830 {
15831 	uchar_t avilable_data0;
15832 	uchar_t avilable_data1;
15833 	uchar_t avilable_data2;
15834 	uchar_t avilable_data3;
15835 	uchar_t attribute_msb;
15836 	uchar_t attribute_lsb;
15837 #ifdef _BIT_FIELDS_LTOH
15838 	uchar_t format		: 2,
15839 				: 5,
15840 		read_only	: 1;
15841 #else
15842 	uchar_t read_only	: 1,
15843 				: 5,
15844 		format		: 2;
15845 #endif
15846 	uchar_t attribute_len_msb;
15847 	uchar_t attribute_len_lsb;
15848 }attribute_header;
15849 
15850 typedef struct {
15851 	attribute_header header;
15852 	char data[1];
15853 }mam_attribute;
15854 
15855 static int
15856 st_handle_hex_media_id(struct scsi_tape *un, void *pnt, int size)
15857 {
15858 	int result;
15859 	int newsize = (size + 1) << 1;
15860 	int i;
15861 	char byte;
15862 	char *format;
15863 	char *data = (char *)pnt;
15864 	char *buf = kmem_alloc(newsize, KM_SLEEP);
15865 
15866 	ST_FUNC(ST_DEVINFO, st_handle_hex_media_id);
15867 
15868 	(void) sprintf(buf, "0x");
15869 	for (i = 0; i < size; i++) {
15870 		byte = (uchar_t)data[i];
15871 		if (byte < 0x10)
15872 			format = "0%x";
15873 		else
15874 			format = "%x";
15875 		(void) sprintf(&buf[(int)strlen(buf)], format, byte);
15876 	}
15877 	result = st_check_if_media_changed(un, buf, newsize);
15878 
15879 	kmem_free(buf, newsize);
15880 
15881 	return (result);
15882 }
15883 
15884 
15885 static int
15886 st_get_media_id_via_read_attribute(struct scsi_tape *un, ubufunc_t bufunc)
15887 {
15888 	int result;
15889 	mam_attribute *buffer;
15890 	int size;
15891 	int newsize;
15892 
15893 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_read_attribute);
15894 	size = sizeof (attribute_header) + max(un->un_media_id_len, ID_SIZE);
15895 again:
15896 	buffer = kmem_zalloc(size, KM_SLEEP);
15897 	result = st_read_attributes(un, 0x0401, buffer, size, bufunc);
15898 	if (result == 0) {
15899 
15900 		newsize = (buffer->header.attribute_len_msb << 8) |
15901 		    buffer->header.attribute_len_lsb;
15902 
15903 		if (newsize + sizeof (attribute_header) > size) {
15904 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15905 			    "resizing read attribute data from %d to %d format"
15906 			    " %d\n", size, (int)sizeof (attribute_header) +
15907 			    newsize, buffer->header.format);
15908 			kmem_free(buffer, size);
15909 			size = newsize + sizeof (attribute_header);
15910 			goto again;
15911 		}
15912 
15913 		un->un_media_id_method = st_get_media_id_via_read_attribute;
15914 		if (buffer->header.format == 0) {
15915 			result =
15916 			    st_handle_hex_media_id(un, buffer->data, newsize);
15917 		} else {
15918 			result = st_check_if_media_changed(un, buffer->data,
15919 			    newsize);
15920 		}
15921 	} else if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
15922 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
15923 		    "Read Attribute Command for Media Identification is not "
15924 		    "supported on the HBA that this drive is attached to.");
15925 		result = ENOTTY;
15926 	}
15927 
15928 	kmem_free(buffer, size);
15929 	un->un_status = 0;
15930 
15931 	return (result);
15932 }
15933 
15934 
15935 static int
15936 st_get_media_id_via_media_serial_cmd(struct scsi_tape *un, ubufunc_t bufunc)
15937 {
15938 	char cdb[CDB_GROUP5];
15939 	struct uscsi_cmd *ucmd;
15940 	struct scsi_extended_sense sense;
15941 	int rval;
15942 	int size = max(un->un_media_id_len, ID_SIZE);
15943 	caddr_t buf;
15944 
15945 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_media_serial_cmd);
15946 
15947 	ucmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
15948 upsize:
15949 	buf = kmem_alloc(size, KM_SLEEP);
15950 
15951 	cdb[0] = (char)SCMD_SVC_ACTION_IN_G5;
15952 	cdb[1] = 1; /* READ MEDIA SERIAL NUMBER */
15953 	cdb[2] = 0;
15954 	cdb[3] = 0;
15955 	cdb[4] = 0;
15956 	cdb[5] = 0;
15957 	cdb[6] = (char)(size >> 24);
15958 	cdb[7] = (char)(size >> 16);
15959 	cdb[8] = (char)(size >> 8);
15960 	cdb[9] = (char)(size);
15961 	cdb[10] = 0;
15962 	cdb[11] = 0;
15963 
15964 	ucmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
15965 	ucmd->uscsi_timeout = un->un_dp->non_motion_timeout;
15966 	ucmd->uscsi_cdb = &cdb[0];
15967 	ucmd->uscsi_cdblen = sizeof (cdb);
15968 	ucmd->uscsi_bufaddr = buf;
15969 	ucmd->uscsi_buflen = size;
15970 	ucmd->uscsi_rqbuf = (caddr_t)&sense;
15971 	ucmd->uscsi_rqlen = sizeof (sense);
15972 
15973 	rval = bufunc(un, ucmd, FKIOCTL);
15974 
15975 	if (rval || ucmd->uscsi_status != 0) {
15976 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
15977 		    "media serial command returned %d scsi_status %d"
15978 		    " rqstatus %d", rval, ucmd->uscsi_status,
15979 		    ucmd->uscsi_rqstatus);
15980 		/*
15981 		 * If this returns invalid operation code don't try again.
15982 		 */
15983 		if (sense.es_key == KEY_ILLEGAL_REQUEST &&
15984 		    sense.es_add_code == 0x20) {
15985 			rval = ENOTTY;
15986 		} else if (rval == 0) {
15987 			rval = EIO;
15988 		}
15989 		un->un_status = 0;
15990 	} else {
15991 		int act_size;
15992 
15993 		/*
15994 		 * get reported size.
15995 		 */
15996 		act_size = (int)buf[3] | (int)(buf[2] << 8) |
15997 		    (int)(buf[1] << 16) | (int)(buf[0] << 24);
15998 
15999 		/* documentation says mod 4. */
16000 		while (act_size & 3) {
16001 			act_size++;
16002 		}
16003 
16004 		/*
16005 		 * If reported size is larger that we our buffer.
16006 		 * Free the old one and allocate one that is larger
16007 		 * enough and re-issuse the command.
16008 		 */
16009 		if (act_size + 4 > size) {
16010 			kmem_free(buf, size);
16011 			size = act_size + 4;
16012 			goto upsize;
16013 		}
16014 
16015 		/*
16016 		 * set data pointer to point to the start of that serial number.
16017 		 */
16018 		un->un_media_id_method = st_get_media_id_via_media_serial_cmd;
16019 		rval = st_check_if_media_changed(un, &buf[4], act_size);
16020 	}
16021 
16022 	kmem_free(ucmd, sizeof (struct uscsi_cmd));
16023 	kmem_free(buf, size);
16024 
16025 	return (rval);
16026 }
16027 
16028 
16029 /* ARGSUSED */
16030 static int
16031 st_bogus_media_id(struct scsi_tape *un, ubufunc_t bufunc)
16032 {
16033 	ST_FUNC(ST_DEVINFO, st_bogus_media_id);
16034 
16035 	ASSERT(un->un_media_id == NULL || un->un_media_id == bogusID);
16036 	ASSERT(un->un_media_id_len == 0);
16037 	un->un_media_id = (char *)bogusID;
16038 	un->un_media_id_len = 0;
16039 	return (0);
16040 }
16041 
16042 typedef int (*media_chk_function)(struct scsi_tape *, ubufunc_t bufunc);
16043 
16044 media_chk_function media_chk_functions[] = {
16045 	st_get_media_id_via_media_serial_cmd,
16046 	st_get_media_id_via_read_attribute,
16047 	st_bogus_media_id
16048 };
16049 
16050 static int
16051 st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc)
16052 {
16053 	int result = 0;
16054 	int i;
16055 
16056 	ST_FUNC(ST_DEVINFO, st_get_media_identification);
16057 
16058 	for (i = 0; i < ST_NUM_MEMBERS(media_chk_functions); i++) {
16059 		if (result == ENOTTY) {
16060 			/*
16061 			 * Last operation type not supported by this device.
16062 			 * Make so next time it doesn`t do that again.
16063 			 */
16064 			un->un_media_id_method = media_chk_functions[i];
16065 		} else if (un->un_media_id_method != media_chk_functions[i] &&
16066 		    un->un_media_id_method != st_get_media_identification) {
16067 			continue;
16068 		}
16069 		result = media_chk_functions[i](un, bufunc);
16070 		/*
16071 		 * If result indicates the function was successful or
16072 		 * that the media is not the same as last known, break.
16073 		 */
16074 		if (result == 0 || result == ESPIPE) {
16075 			break;
16076 		}
16077 	}
16078 
16079 	return (result);
16080 }
16081 
16082 static errstate
16083 st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
16084     errstate onentry)
16085 {
16086 
16087 	int ret;
16088 	st_err_info *errinfo;
16089 	recov_info *ri = (recov_info *)pkt->pkt_private;
16090 
16091 	ST_FUNC(ST_DEVINFO, st_command_recovery);
16092 
16093 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16094 
16095 	ASSERT(un->un_recov_buf_busy == 0);
16096 
16097 	/*
16098 	 * Don't try and recover a reset that this device sent.
16099 	 */
16100 	if (un->un_rsvd_status & ST_INITIATED_RESET &&
16101 	    onentry == DEVICE_RESET) {
16102 		return (COMMAND_DONE_ERROR);
16103 	}
16104 
16105 	/*
16106 	 * See if expected position was passed with scsi_pkt.
16107 	 */
16108 	if (ri->privatelen == sizeof (recov_info)) {
16109 
16110 		/*
16111 		 * Not for this command.
16112 		 */
16113 		if (ri->cmd_attrib->do_not_recover) {
16114 			return (COMMAND_DONE_ERROR);
16115 		}
16116 
16117 		/*
16118 		 * Create structure to hold all error state info.
16119 		 */
16120 		errinfo = kmem_zalloc(sizeof (st_err_info), KM_SLEEP);
16121 		errinfo->ei_error_type = onentry;
16122 		errinfo->ei_failing_bp = ri->cmd_bp;
16123 		COPY_POS(&errinfo->ei_expected_pos, &ri->pos);
16124 	} else {
16125 		/* disabled */
16126 		return (COMMAND_DONE_ERROR);
16127 	}
16128 
16129 	bcopy(pkt, &errinfo->ei_failed_pkt, sizeof (struct scsi_pkt));
16130 	bcopy(pkt->pkt_scbp, &errinfo->ei_failing_status, SECMDS_STATUS_SIZE);
16131 	ret = ddi_taskq_dispatch(un->un_recov_taskq, st_recover, errinfo,
16132 	    DDI_NOSLEEP);
16133 	ASSERT(ret == DDI_SUCCESS);
16134 	if (ret != DDI_SUCCESS) {
16135 		kmem_free(errinfo, sizeof (st_err_info));
16136 		return (COMMAND_DONE_ERROR);
16137 	}
16138 	return (JUST_RETURN); /* release calling thread */
16139 }
16140 
16141 static void
16142 st_recov_ret(struct scsi_tape *un, st_err_info *errinfo, errstate err)
16143 {
16144 	int error_number;
16145 	buf_t *bp;
16146 
16147 
16148 	ST_FUNC(ST_DEVINFO, st_recov_ret);
16149 
16150 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16151 
16152 	bp = errinfo->ei_failing_bp;
16153 	kmem_free(errinfo, sizeof (st_err_info));
16154 
16155 	switch (err) {
16156 	case JUST_RETURN:
16157 		mutex_exit(&un->un_sd->sd_mutex);
16158 		return;
16159 
16160 	case COMMAND_DONE:
16161 	case COMMAND_DONE_ERROR_RECOVERED:
16162 		ST_DO_KSTATS(bp, kstat_runq_exit);
16163 		error_number = 0;
16164 		break;
16165 
16166 	case COMMAND_DONE_ERROR:
16167 	case COMMAND_DONE_EACCES:
16168 		ST_DO_KSTATS(bp, kstat_waitq_exit);
16169 		ST_DO_ERRSTATS(un, st_transerrs);
16170 		error_number = EIO;
16171 		st_set_pe_flag(un);
16172 		break;
16173 
16174 	default:
16175 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16176 		    "st_recov_ret with unhandled errstat %d\n", err);
16177 	}
16178 	st_bioerror(bp, error_number);
16179 	st_done_and_mutex_exit(un, bp);
16180 }
16181 
16182 static void
16183 st_recover(void *arg)
16184 {
16185 	st_err_info *const errinfo = (st_err_info *)arg;
16186 	uchar_t com = errinfo->ei_failed_pkt.pkt_cdbp[0];
16187 	struct scsi_tape *un;
16188 	tapepos_t cur_pos;
16189 	int rval;
16190 	errstate status = COMMAND_DONE_ERROR;
16191 	recov_info *rcv;
16192 	buf_t *bp;
16193 
16194 
16195 	rcv = errinfo->ei_failed_pkt.pkt_private;
16196 	ASSERT(rcv->privatelen == sizeof (recov_info));
16197 	bp = rcv->cmd_bp;
16198 
16199 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16200 
16201 	ASSERT(un != NULL);
16202 
16203 	mutex_enter(ST_MUTEX);
16204 
16205 	ST_FUNC(ST_DEVINFO, st_recover);
16206 
16207 	ST_CDB(ST_DEVINFO, "Recovering command",
16208 	    (caddr_t)errinfo->ei_failed_pkt.pkt_cdbp);
16209 	ST_SENSE(ST_DEVINFO, "sense status for failed command",
16210 	    (caddr_t)&errinfo->ei_failing_status,
16211 	    sizeof (struct scsi_arq_status));
16212 	ST_POS(ST_DEVINFO, rcv->cmd_attrib->recov_pos_type == POS_STARTING ?
16213 	    "starting position for recovery command" :
16214 	    "expected position for recovery command",
16215 	    &errinfo->ei_expected_pos);
16216 
16217 	rval = st_test_path_to_device(un);
16218 
16219 	/*
16220 	 * If the drive responed to the TUR lets try and get it to sync
16221 	 * any data it have in the buffer.
16222 	 */
16223 	if (rval == 0 && rcv->cmd_attrib->chg_tape_data) {
16224 		(void) st_rcmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
16225 	}
16226 	switch (errinfo->ei_error_type) {
16227 	case ATTEMPT_RETRY:
16228 	case COMMAND_TIMEOUT:
16229 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16230 		    "st_recover called with COMMAND_TIMEOUT, TUR returned %d\n",
16231 		    rval);
16232 		if (rval != 0) {
16233 			/* ping failed, we're done. */
16234 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16235 			return;
16236 		}
16237 
16238 		/*
16239 		 * If a reset occured fall through.
16240 		 */
16241 		if (un->un_unit_attention_flags == 0) {
16242 			break;
16243 		}
16244 		/* FALLTHROUGH */
16245 	case DEVICE_RESET:
16246 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16247 		    "st_recover called with DEVICE_RESET, TUR returned %d\n",
16248 		    rval);
16249 		/*
16250 		 * For now if we can't talk to the device we are done.
16251 		 */
16252 		if (rval) {
16253 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16254 			return;
16255 		}
16256 
16257 		if ((un->un_rsvd_status & ST_LOST_RESERVE) &&
16258 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] != SCMD_RELEASE)) {
16259 			rval = st_reserve_release(un, ST_RESERVE,
16260 			    st_uscsi_rcmd);
16261 			if (rval == 0) {
16262 				un->un_rsvd_status |= ST_RESERVE;
16263 				un->un_rsvd_status &= ~(ST_RELEASE |
16264 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
16265 				    ST_INITIATED_RESET);
16266 			} else {
16267 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16268 				return;
16269 			}
16270 			rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16271 			if (rval) {
16272 				rval = st_gen_mode_select(un, st_uscsi_rcmd,
16273 				    un->un_mspl, sizeof (struct seq_mode));
16274 			}
16275 			if (rval) {
16276 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16277 				return;
16278 			}
16279 		}
16280 		break;
16281 	case PATH_FAILED:
16282 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16283 		    "st_recover called with PATH_FAILED, TUR returned %d\n",
16284 		    rval);
16285 		if (rval != 0) {
16286 			/* ping failed, we're done. */
16287 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16288 			return;
16289 		}
16290 		break;
16291 	case DEVICE_TAMPER:
16292 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16293 		    "st_recover called with DEVICE_TAMPER, TUR returned %d\n",
16294 		    rval);
16295 		/*
16296 		 * Check if the ASC/ASCQ says mode data has changed.
16297 		 */
16298 		if (errinfo->ei_failing_status.sts_sensedata.es_add_code ==
16299 		    0x2a &&
16300 		    errinfo->ei_failing_status.sts_sensedata.es_qual_code ==
16301 		    0x01) {
16302 			/*
16303 			 * See if mode sense changed.
16304 			 */
16305 			rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16306 			/*
16307 			 * if not cross your fingers and go for it.
16308 			 */
16309 			if (rval == 0) {
16310 				st_recov_ret(un, errinfo, COMMAND_DONE);
16311 				return;
16312 			}
16313 			/*
16314 			 * If so change it back.
16315 			 */
16316 			rval = st_gen_mode_select(un, st_uscsi_rcmd,
16317 			    un->un_mspl, sizeof (struct seq_mode));
16318 			if (rval) {
16319 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16320 			}
16321 			st_recov_ret(un, errinfo, COMMAND_DONE);
16322 			return;
16323 		}
16324 		/*
16325 		 * if we have a media id and its not bogus.
16326 		 * Check to see if it the same.
16327 		 */
16328 		if (un->un_media_id != NULL && un->un_media_id != bogusID) {
16329 			rval = st_get_media_identification(un, st_uscsi_rcmd);
16330 			if (rval == ESPIPE) {
16331 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16332 				return;
16333 			}
16334 		}
16335 		break;
16336 	default:
16337 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16338 		    "Unhandled error type 0x%x in st_recover()\n", com);
16339 	}
16340 
16341 	/*
16342 	 * if command is retriable retry it
16343 	 */
16344 	if (rcv->cmd_attrib->retriable) {
16345 		status = st_recover_reissue_pkt(un, &errinfo->ei_failed_pkt);
16346 
16347 	/*
16348 	 * if drive doesn't support read position we are done
16349 	 */
16350 	} else if (un->un_read_pos_type == NO_POS) {
16351 		status = COMMAND_DONE_ERROR;
16352 	/*
16353 	 * If this command results in a changed tape position,
16354 	 * lets see where we are.
16355 	 */
16356 	} else if (rcv->cmd_attrib->chg_tape_pos) {
16357 		/*
16358 		 * XXX May be a reason to choose a different type here.
16359 		 * Long format has file position information.
16360 		 * Short and Extended have information about whats
16361 		 * in the buffer. St's positioning assumes in the buffer
16362 		 * to be the same as on tape.
16363 		 */
16364 		rval = st_compare_expected_position(un, errinfo,
16365 		    rcv->cmd_attrib, &cur_pos);
16366 		if (rval == 0) {
16367 			status = COMMAND_DONE;
16368 		} else if (rval == EAGAIN) {
16369 			status = st_recover_reissue_pkt(un,
16370 			    &errinfo->ei_failed_pkt);
16371 		} else {
16372 			status = COMMAND_DONE_ERROR;
16373 		}
16374 	} else {
16375 		ASSERT(0);
16376 	}
16377 
16378 	st_recov_ret(un, errinfo, status);
16379 }
16380 
16381 static void
16382 st_recov_cb(struct scsi_pkt *pkt)
16383 {
16384 	struct scsi_tape *un;
16385 	struct buf *bp;
16386 	recov_info *rcv;
16387 	errstate action = COMMAND_DONE;
16388 	int timout = ST_TRAN_BUSY_TIMEOUT; /* short (default) timeout */
16389 
16390 	/*
16391 	 * Get the buf from the packet.
16392 	 */
16393 	rcv = pkt->pkt_private;
16394 	ASSERT(rcv->privatelen == sizeof (recov_info));
16395 	bp = rcv->cmd_bp;
16396 
16397 	/*
16398 	 * get the unit from the buf.
16399 	 */
16400 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16401 	ASSERT(un != NULL);
16402 
16403 	ST_FUNC(ST_DEVINFO, st_recov_cb);
16404 
16405 	mutex_enter(ST_MUTEX);
16406 
16407 	ASSERT(bp == un->un_recov_buf);
16408 
16409 
16410 	switch (pkt->pkt_reason) {
16411 	case CMD_CMPLT:
16412 		if (un->un_arq_enabled && pkt->pkt_state & STATE_ARQ_DONE) {
16413 			action = st_handle_autosense(un, bp, &rcv->pos);
16414 		} else if (*pkt->pkt_scbp & (STATUS_BUSY | STATUS_CHECK)) {
16415 			action = st_check_error(un, pkt);
16416 		}
16417 		break;
16418 	case CMD_TIMEOUT:
16419 		action = COMMAND_TIMEOUT;
16420 		break;
16421 	default:
16422 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16423 		    "pkt_reason not handled yet %s",
16424 		    scsi_rname(pkt->pkt_reason));
16425 	}
16426 
16427 	switch (action) {
16428 	case COMMAND_DONE:
16429 		break;
16430 
16431 	case COMMAND_DONE_EACCES:
16432 		bioerror(bp, EACCES);
16433 		break;
16434 
16435 	case COMMAND_TIMEOUT:
16436 	case COMMAND_DONE_ERROR:
16437 		bioerror(bp, EIO);
16438 		break;
16439 
16440 	case QUE_BUSY_COMMAND:
16441 		/* longish timeout */
16442 		timout = ST_STATUS_BUSY_TIMEOUT;
16443 		/* FALLTHRU */
16444 	case QUE_COMMAND:
16445 	case DEVICE_TAMPER:
16446 	case ATTEMPT_RETRY:
16447 		/*
16448 		 * let st_handle_intr_busy put this bp back on waitq and make
16449 		 * checks to see if it is ok to requeue the command.
16450 		 */
16451 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
16452 
16453 		/*
16454 		 * Save the throttle before setting up the timeout
16455 		 */
16456 		if (un->un_throttle) {
16457 			un->un_last_throttle = un->un_throttle;
16458 		}
16459 		mutex_exit(ST_MUTEX);
16460 		if (st_handle_intr_busy(un, bp, timout) == 0) {
16461 			return;		/* timeout is setup again */
16462 		}
16463 		mutex_enter(ST_MUTEX);
16464 		un->un_pos.pmode = invalid;
16465 		un->un_err_resid = bp->b_resid = bp->b_bcount;
16466 		st_bioerror(bp, EIO);
16467 		st_set_pe_flag(un);
16468 		break;
16469 
16470 	default:
16471 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16472 		    "Unhandled recovery state 0x%x\n", action);
16473 	}
16474 
16475 	st_done_and_mutex_exit(un, bp);
16476 }
16477 
16478 static int
16479 st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait)
16480 {
16481 	struct buf *bp;
16482 	int err;
16483 
16484 	ST_FUNC(ST_DEVINFO, st_rcmd);
16485 
16486 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16487 	    "st_rcmd(un = 0x%p, com = 0x%x, count = %"PRIx64", wait = %d)\n",
16488 	    (void *)un, com, count, wait);
16489 
16490 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16491 	ASSERT(mutex_owned(ST_MUTEX));
16492 
16493 #ifdef STDEBUG
16494 	if ((st_debug & 0x7)) {
16495 		st_debug_cmds(un, com, count, wait);
16496 	}
16497 #endif
16498 
16499 	while (un->un_recov_buf_busy)
16500 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
16501 	un->un_recov_buf_busy = 1;
16502 
16503 	bp = un->un_recov_buf;
16504 	bzero(bp, sizeof (buf_t));
16505 
16506 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
16507 
16508 	err = st_setup_cmd(un, bp, com, count);
16509 
16510 	un->un_recov_buf_busy = 0;
16511 
16512 	cv_signal(&un->un_recov_buf_cv);
16513 
16514 	return (err);
16515 }
16516 
16517 /* args used */
16518 static int
16519 st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
16520 {
16521 	int rval;
16522 	buf_t *bp;
16523 
16524 	ST_FUNC(ST_DEVINFO, st_uscsi_rcmd);
16525 	ASSERT(flag == FKIOCTL);
16526 
16527 	/*
16528 	 * Get buffer resources...
16529 	 */
16530 	while (un->un_recov_buf_busy)
16531 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
16532 	un->un_recov_buf_busy = 1;
16533 
16534 	bp = un->un_recov_buf;
16535 	bzero(bp, sizeof (buf_t));
16536 
16537 	bp->b_forw = (struct buf *)(uintptr_t)ucmd->uscsi_cdb[0];
16538 	bp->b_back = (struct buf *)ucmd;
16539 
16540 	mutex_exit(ST_MUTEX);
16541 	rval = scsi_uscsi_handle_cmd(un->un_dev, UIO_SYSSPACE, ucmd,
16542 	    st_strategy, bp, NULL);
16543 	mutex_enter(ST_MUTEX);
16544 
16545 	ucmd->uscsi_resid = bp->b_resid;
16546 
16547 	/*
16548 	 * Free resources
16549 	 */
16550 	un->un_recov_buf_busy = 0;
16551 	cv_signal(&un->un_recov_buf_cv);
16552 
16553 	return (rval);
16554 }
16555 
16556 /*
16557  * Add data to scsi_pkt to help know what to do if the command fails.
16558  */
16559 static void
16560 st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
16561     struct scsi_pkt *pkt)
16562 {
16563 	uint64_t count;
16564 	recov_info *rinfo = (recov_info *)pkt->pkt_private;
16565 
16566 	ST_FUNC(ST_DEVINFO, st_add_recovery_info_to_pkt);
16567 
16568 	ASSERT(rinfo->privatelen == sizeof (pkt_info) ||
16569 	    rinfo->privatelen == sizeof (recov_info));
16570 
16571 	SET_BP_PKT(bp, pkt);
16572 	rinfo->cmd_bp = bp;
16573 
16574 	if (rinfo->privatelen != sizeof (recov_info)) {
16575 		return;
16576 	}
16577 
16578 	rinfo->cmd_bp = bp;
16579 
16580 	rinfo->cmd_attrib = NULL;
16581 
16582 	/*
16583 	 * lookup the command attributes and add them to the recovery info.
16584 	 */
16585 	rinfo->cmd_attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
16586 
16587 	ASSERT(rinfo->cmd_attrib);
16588 
16589 	/*
16590 	 * For commands that there is no way to figure the expected position
16591 	 * once completed, we save the position the command was started from
16592 	 * so that if they fail we can position back and try again.
16593 	 * This has already been done in st_cmd() or st_iscsi_cmd().
16594 	 */
16595 	if (rinfo->cmd_attrib->recov_pos_type == POS_STARTING) {
16596 		/* save current position as the starting position. */
16597 		COPY_POS(&rinfo->pos, &un->un_pos);
16598 		un->un_running.pmode = invalid;
16599 		return;
16600 	}
16601 
16602 	/*
16603 	 * Don't want to update the running position for recovery.
16604 	 */
16605 	if (bp == un->un_recov_buf) {
16606 		rinfo->pos.pmode = un->un_running.pmode;
16607 		return;
16608 	}
16609 	/*
16610 	 * If running position is invalid copy the current position.
16611 	 * Running being set invalid means we are not in a read, write
16612 	 * or write filemark sequence.
16613 	 * We'll copy the current position and start from there.
16614 	 */
16615 	if (un->un_running.pmode == invalid) {
16616 		COPY_POS(&un->un_running, &un->un_pos);
16617 		COPY_POS(&rinfo->pos, &un->un_running);
16618 	} else {
16619 		COPY_POS(&rinfo->pos, &un->un_running);
16620 		if (rinfo->pos.pmode == legacy) {
16621 			/*
16622 			 * Always should be more logical blocks then
16623 			 * data blocks and files marks.
16624 			 */
16625 			ASSERT(rinfo->pos.lgclblkno >= rinfo->pos.blkno +
16626 			    rinfo->pos.fileno);
16627 		}
16628 	}
16629 
16630 	/*
16631 	 * If the command is not expected to change the drive position
16632 	 * then the running position should be the expected position.
16633 	 */
16634 	if (rinfo->cmd_attrib->chg_tape_pos == 0) {
16635 		ASSERT(rinfo->cmd_attrib->chg_tape_direction == DIR_NONE);
16636 		return;
16637 	}
16638 
16639 	if (rinfo->cmd_attrib->explicit) {
16640 		ASSERT(rinfo->pos.pmode != invalid);
16641 		ASSERT(rinfo->cmd_attrib->get_cnt);
16642 		count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
16643 		/*
16644 		 * This is a user generated CDB.
16645 		 */
16646 		if (bp == un->un_sbufp) {
16647 			uint64_t lbn;
16648 
16649 			lbn = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
16650 
16651 			/*
16652 			 * See if this CDB will generate a locate or change
16653 			 * partition.
16654 			 */
16655 			if ((lbn != un->un_running.lgclblkno) ||
16656 			    (pkt->pkt_cdbp[3] != un->un_running.partition)) {
16657 				rinfo->pos.partition = pkt->pkt_cdbp[3];
16658 				rinfo->pos.pmode = logical;
16659 				rinfo->pos.lgclblkno = lbn;
16660 				un->un_running.partition = pkt->pkt_cdbp[3];
16661 				un->un_running.pmode = logical;
16662 				un->un_running.lgclblkno = lbn;
16663 			}
16664 		} else {
16665 			uint64_t lbn = un->un_running.lgclblkno;
16666 
16667 			pkt->pkt_cdbp[3]  = (uchar_t)un->un_running.partition;
16668 
16669 			pkt->pkt_cdbp[4]  = (uchar_t)(lbn >> 56);
16670 			pkt->pkt_cdbp[5]  = (uchar_t)(lbn >> 48);
16671 			pkt->pkt_cdbp[6]  = (uchar_t)(lbn >> 40);
16672 			pkt->pkt_cdbp[7]  = (uchar_t)(lbn >> 32);
16673 			pkt->pkt_cdbp[8]  = (uchar_t)(lbn >> 24);
16674 			pkt->pkt_cdbp[9]  = (uchar_t)(lbn >> 16);
16675 			pkt->pkt_cdbp[10] = (uchar_t)(lbn >> 8);
16676 			pkt->pkt_cdbp[11] = (uchar_t)(lbn);
16677 		}
16678 		rinfo->pos.lgclblkno += count;
16679 		rinfo->pos.blkno += count;
16680 		un->un_running.lgclblkno += count;
16681 		return;
16682 	}
16683 
16684 	if (rinfo->cmd_attrib->chg_tape_pos) {
16685 
16686 		/* should not have got an invalid position from running. */
16687 		if (un->un_mediastate == MTIO_INSERTED) {
16688 			ASSERT(rinfo->pos.pmode != invalid);
16689 		}
16690 
16691 		/* should have either a get count or or get lba function */
16692 		ASSERT(rinfo->cmd_attrib->get_cnt != NULL ||
16693 		    rinfo->cmd_attrib->get_lba != NULL);
16694 
16695 		/* only explicit commands have both and they're handled above */
16696 		ASSERT(!(rinfo->cmd_attrib->get_cnt != NULL &&
16697 		    rinfo->cmd_attrib->get_lba != NULL));
16698 
16699 		/* if it has a get count function */
16700 		if (rinfo->cmd_attrib->get_cnt != NULL) {
16701 			count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
16702 			if (count == 0) {
16703 				return;
16704 			}
16705 			/*
16706 			 * Changes position but doesn't transfer data.
16707 			 * i.e. rewind, write_file_mark and load.
16708 			 */
16709 			if (rinfo->cmd_attrib->transfers_data == TRAN_NONE) {
16710 				switch (rinfo->cmd_attrib->chg_tape_direction) {
16711 				case DIR_NONE: /* Erase */
16712 					ASSERT(rinfo->cmd_attrib->cmd ==
16713 					    SCMD_ERASE);
16714 					break;
16715 				case DIR_FORW: /* write_file_mark */
16716 					rinfo->pos.fileno += count;
16717 					rinfo->pos.lgclblkno += count;
16718 					rinfo->pos.blkno = 0;
16719 					un->un_running.fileno += count;
16720 					un->un_running.lgclblkno += count;
16721 					un->un_running.blkno = 0;
16722 					break;
16723 				case DIR_REVC: /* rewind */
16724 					rinfo->pos.fileno = 0;
16725 					rinfo->pos.lgclblkno = 0;
16726 					rinfo->pos.blkno = 0;
16727 					rinfo->pos.eof = ST_NO_EOF;
16728 					rinfo->pos.pmode = legacy;
16729 					un->un_running.fileno = 0;
16730 					un->un_running.lgclblkno = 0;
16731 					un->un_running.blkno = 0;
16732 					un->un_running.eof = ST_NO_EOF;
16733 					if (un->un_running.pmode != legacy)
16734 						un->un_running.pmode = legacy;
16735 					break;
16736 				case DIR_EITH: /* Load unload */
16737 					ASSERT(rinfo->cmd_attrib->cmd ==
16738 					    SCMD_LOAD);
16739 					switch (count & (LD_LOAD | LD_RETEN |
16740 					    LD_RETEN | LD_HOLD)) {
16741 					case LD_UNLOAD:
16742 					case LD_RETEN:
16743 					case LD_HOLD:
16744 					case LD_LOAD | LD_HOLD:
16745 					case LD_EOT | LD_HOLD:
16746 					case LD_RETEN | LD_HOLD:
16747 						rinfo->pos.pmode = invalid;
16748 						un->un_running.pmode = invalid;
16749 						break;
16750 					case LD_EOT:
16751 					case LD_LOAD | LD_EOT:
16752 						rinfo->pos.eof = ST_EOT;
16753 						rinfo->pos.pmode = invalid;
16754 						un->un_running.eof = ST_EOT;
16755 						un->un_running.pmode = invalid;
16756 						break;
16757 					case LD_LOAD:
16758 					case LD_RETEN | LD_LOAD:
16759 						rinfo->pos.fileno = 0;
16760 						rinfo->pos.lgclblkno = 0;
16761 						rinfo->pos.blkno = 0;
16762 						rinfo->pos.eof = ST_NO_EOF;
16763 						rinfo->pos.pmode = legacy;
16764 						un->un_running.fileno = 0;
16765 						un->un_running.lgclblkno = 0;
16766 						un->un_running.blkno = 0;
16767 						un->un_running.eof = ST_NO_EOF;
16768 						break;
16769 					default:
16770 						ASSERT(0);
16771 					}
16772 					break;
16773 				default:
16774 					ASSERT(0);
16775 					break;
16776 				}
16777 			} else {
16778 				/*
16779 				 * Changes position and does transfer data.
16780 				 * i.e. read or write.
16781 				 */
16782 				switch (rinfo->cmd_attrib->chg_tape_direction) {
16783 				case DIR_FORW:
16784 					rinfo->pos.lgclblkno += count;
16785 					rinfo->pos.blkno += count;
16786 					un->un_running.lgclblkno += count;
16787 					un->un_running.blkno += count;
16788 					break;
16789 				case DIR_REVC:
16790 					rinfo->pos.lgclblkno -= count;
16791 					rinfo->pos.blkno -= count;
16792 					un->un_running.lgclblkno -= count;
16793 					un->un_running.blkno -= count;
16794 					break;
16795 				default:
16796 					ASSERT(0);
16797 					break;
16798 				}
16799 			}
16800 		} else if (rinfo->cmd_attrib->get_lba != NULL) {
16801 			/* Have a get LBA fuction. i.e. Locate */
16802 			ASSERT(rinfo->cmd_attrib->chg_tape_direction ==
16803 			    DIR_EITH);
16804 			count = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
16805 			un->un_running.lgclblkno = count;
16806 			un->un_running.blkno = 0;
16807 			un->un_running.fileno = 0;
16808 			un->un_running.pmode = logical;
16809 			rinfo->pos.lgclblkno = count;
16810 			rinfo->pos.pmode = invalid;
16811 		} else {
16812 			ASSERT(0);
16813 		}
16814 		return;
16815 	}
16816 
16817 	ST_CDB(ST_DEVINFO, "Unhanded CDB for position prediction",
16818 	    (char *)pkt->pkt_cdbp);
16819 
16820 }
16821 
16822 static int
16823 st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf)
16824 {
16825 	struct seq_mode *current;
16826 	int rval;
16827 	int i;
16828 	caddr_t this;
16829 	caddr_t that;
16830 
16831 	ST_FUNC(ST_DEVINFO, st_check_mode_for_change);
16832 
16833 	/* recovery called with mode tamper before mode selection */
16834 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
16835 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16836 		    "Mode Select not done yet");
16837 		return (0);
16838 	}
16839 
16840 	current = kmem_zalloc(sizeof (struct seq_mode), KM_SLEEP);
16841 
16842 	rval = st_gen_mode_sense(un, ubf, un->un_comp_page, current,
16843 	    sizeof (struct seq_mode));
16844 	if (rval != 0) {
16845 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16846 		    "Mode Sense for mode verification failed");
16847 		kmem_free(current, sizeof (struct seq_mode));
16848 		return (rval);
16849 	}
16850 
16851 	this = (caddr_t)current;
16852 	that = (caddr_t)un->un_mspl;
16853 
16854 	rval = bcmp(this, that, sizeof (struct seq_mode));
16855 	if (rval == 0) {
16856 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16857 		    "Found no changes in mode data");
16858 	}
16859 #ifdef STDEBUG
16860 	else {
16861 		for (i = 1; i < sizeof (struct seq_mode); i++) {
16862 			if (this[i] != that[i]) {
16863 				ST_RECOV(ST_DEVINFO, st_label, CE_CONT,
16864 				    "sense data changed at byte %d was "
16865 				    "0x%x now 0x%x", i,
16866 				    (uchar_t)that[i], (uchar_t)this[i]);
16867 			}
16868 		}
16869 	}
16870 #endif
16871 	kmem_free(current, sizeof (struct seq_mode));
16872 
16873 	return (rval);
16874 }
16875 
16876 static int
16877 st_test_path_to_device(struct scsi_tape *un)
16878 {
16879 	int rval;
16880 
16881 	ST_FUNC(ST_DEVINFO, st_test_path_to_device);
16882 
16883 	/*
16884 	 * XXX Newer drives may not RESEVATION CONFLICT a TUR.
16885 	 */
16886 	do {
16887 		rval = st_rcmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
16888 	} while (rval == DEVICE_RESET);
16889 
16890 	return (rval);
16891 }
16892 
16893 /*
16894  * Does read position using recov_buf and doesn't update un_pos.
16895  * Does what ever kind of read position you want.
16896  */
16897 static int
16898 st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
16899     read_pos_data_t *raw)
16900 {
16901 	int rval;
16902 	struct uscsi_cmd cmd;
16903 	char cdb[CDB_GROUP1];
16904 
16905 	ST_FUNC(ST_DEVINFO, st_recovery_read_pos);
16906 	bzero(&cmd, sizeof (cmd));
16907 
16908 	cdb[0] = SCMD_READ_POSITION;
16909 	cdb[1] = type;
16910 	cdb[2] = 0;
16911 	cdb[3] = 0;
16912 	cdb[4] = 0;
16913 	cdb[5] = 0;
16914 	cdb[6] = 0;
16915 	cdb[7] = 0;
16916 	cdb[8] =  (type == EXT_POS) ? 28 : 0;
16917 	cdb[9] = 0;
16918 
16919 	cmd.uscsi_flags = USCSI_READ;
16920 	cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
16921 	cmd.uscsi_cdb = cdb;
16922 	cmd.uscsi_cdblen = sizeof (cdb);
16923 	cmd.uscsi_bufaddr = (caddr_t)raw;
16924 	switch (type) {
16925 	case SHORT_POS:
16926 		cmd.uscsi_buflen = sizeof (tape_position_t);
16927 		break;
16928 	case LONG_POS:
16929 		cmd.uscsi_buflen = sizeof (tape_position_long_t);
16930 		break;
16931 	case EXT_POS:
16932 		cmd.uscsi_buflen = sizeof (tape_position_ext_t);
16933 		break;
16934 	default:
16935 		ASSERT(0);
16936 	}
16937 
16938 	rval = st_uscsi_rcmd(un, &cmd, FKIOCTL);
16939 	if (cmd.uscsi_status) {
16940 		rval = EIO;
16941 	}
16942 	return (rval);
16943 }
16944 
16945 static int
16946 st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
16947     read_pos_data_t *raw)
16948 {
16949 	int rval;
16950 	read_p_types type = un->un_read_pos_type;
16951 
16952 	ST_FUNC(ST_DEVINFO, st_recovery_get_position);
16953 
16954 	rval = st_recovery_read_pos(un, type, raw);
16955 	if (rval != 0) {
16956 		return (rval);
16957 	}
16958 	rval = st_interpret_read_pos(un, read, type, sizeof (read_pos_data_t),
16959 	    (caddr_t)raw, 1);
16960 
16961 	return (rval);
16962 }
16963 
16964 /*
16965  * based on the command do we retry, continue or give up?
16966  * possable return values?
16967  *	zero do nothing looks fine.
16968  *	EAGAIN retry.
16969  *	EIO failed makes no sense.
16970  */
16971 static int
16972 st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
16973     cmd_attribute const * cmd_att, tapepos_t *read)
16974 {
16975 	int rval;
16976 	read_pos_data_t *readp_datap;
16977 
16978 	ST_FUNC(ST_DEVINFO, st_compare_expected_position);
16979 
16980 	ASSERT(un != NULL);
16981 	ASSERT(ei != NULL);
16982 	ASSERT(read != NULL);
16983 	ASSERT(cmd_att->chg_tape_pos);
16984 
16985 	COPY_POS(read, &ei->ei_expected_pos);
16986 
16987 	readp_datap = kmem_zalloc(sizeof (read_pos_data_t), KM_SLEEP);
16988 
16989 	rval = st_recovery_get_position(un, read, readp_datap);
16990 
16991 	kmem_free(readp_datap, sizeof (read_pos_data_t));
16992 
16993 	if (rval != 0) {
16994 		return (EIO);
16995 	}
16996 
16997 	ST_POS(ST_DEVINFO, "st_compare_expected_position", read);
16998 
16999 	if ((read->pmode == invalid) ||
17000 	    (ei->ei_expected_pos.pmode == invalid)) {
17001 		return (EIO);
17002 	}
17003 
17004 	/*
17005 	 * Command that changes tape position and have an expected position
17006 	 * if it were to chave completed sucessfully.
17007 	 */
17008 	if (cmd_att->recov_pos_type == POS_EXPECTED) {
17009 		uint32_t count;
17010 		int64_t difference;
17011 
17012 		/* At expected? */
17013 		if (read->lgclblkno == ei->ei_expected_pos.lgclblkno) {
17014 			ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17015 			    "Found drive to be at expected position\n");
17016 			return (0); /* Good */
17017 		}
17018 		ASSERT(cmd_att->get_cnt);
17019 		count = cmd_att->get_cnt(ei->ei_failed_pkt.pkt_cdbp);
17020 
17021 		ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17022 		    "Got count from CDB and it was %d\n", count);
17023 		if (cmd_att->chg_tape_direction == DIR_FORW) {
17024 			difference =
17025 			    ei->ei_expected_pos.lgclblkno - read->lgclblkno;
17026 			ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17027 			    "difference between expected and actual is %"
17028 			    PRId64"\n", difference);
17029 			if (count == difference) {
17030 				ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17031 				    "Found failed FORW command, retrying\n");
17032 				return (EAGAIN);
17033 			}
17034 
17035 			/*
17036 			 * If rewound or somewhere between the starting position
17037 			 * and the expected position (partial read or write).
17038 			 * Locate to the starting position and try the whole
17039 			 * thing over again.
17040 			 */
17041 			if ((read->lgclblkno == 0) ||
17042 			    ((difference > 0) && (difference < count))) {
17043 				rval = st_logical_block_locate(un,
17044 				    st_uscsi_rcmd, read,
17045 				    ei->ei_expected_pos.lgclblkno - count,
17046 				    ei->ei_expected_pos.partition);
17047 				if (rval == 0) {
17048 					ST_RECOV(ST_DEVINFO, st_label,
17049 					    SCSI_DEBUG, "reestablished FORW"
17050 					    " command retrying\n");
17051 					return (EAGAIN);
17052 				}
17053 			/* This handles flushed read ahead on the drive */
17054 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17055 			    (difference < 0)) {
17056 				rval = st_logical_block_locate(un,
17057 				    st_uscsi_rcmd, read,
17058 				    ei->ei_expected_pos.lgclblkno - count,
17059 				    ei->ei_expected_pos.partition);
17060 				if (rval == 0) {
17061 					ST_RECOV(ST_DEVINFO, st_label,
17062 					    SCSI_DEBUG, "reestablished FORW"
17063 					    " read command retrying\n");
17064 					return (EAGAIN);
17065 				}
17066 			/*
17067 			 * XXX swag seeing difference of 2 on write filemark.
17068 			 * If the space to the starting position works on a
17069 			 * write that means the previous write made it to tape.
17070 			 * If not we lost data and have to give up.
17071 			 *
17072 			 * The plot thickens. Now I am attempting to cover a
17073 			 * count of 1 and a differance of 2 on a write.
17074 			 */
17075 			} else if (difference > count) {
17076 				rval = st_logical_block_locate(un,
17077 				    st_uscsi_rcmd, read,
17078 				    ei->ei_expected_pos.lgclblkno - count,
17079 				    ei->ei_expected_pos.partition);
17080 				if (rval == 0) {
17081 					ST_RECOV(ST_DEVINFO, st_label,
17082 					    SCSI_DEBUG, "reestablished FORW"
17083 					    " write command retrying\n");
17084 					return (EAGAIN);
17085 				}
17086 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17087 				    "Seek to block %"PRId64" returned %d\n",
17088 				    ei->ei_expected_pos.lgclblkno - count,
17089 				    rval);
17090 			} else {
17091 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17092 				    "Not expected transfers_data = %d "
17093 				    "difference = %"PRId64,
17094 				    cmd_att->transfers_data, difference);
17095 			}
17096 
17097 			return (EIO);
17098 
17099 		} else if (cmd_att->chg_tape_direction == DIR_REVC) {
17100 			/* Don't think we can write backwards */
17101 			ASSERT(cmd_att->transfers_data != TRAN_WRTE);
17102 			difference =
17103 			    read->lgclblkno - ei->ei_expected_pos.lgclblkno;
17104 			ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17105 			    "difference between expected and actual is %"
17106 			    PRId64"\n", difference);
17107 			if (count == difference) {
17108 				ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17109 				    "Found failed REVC command, retrying\n");
17110 				return (EAGAIN);
17111 			}
17112 			if ((read->lgclblkno == 0) ||
17113 			    ((difference > 0) && (difference < count))) {
17114 				rval = st_logical_block_locate(un,
17115 				    st_uscsi_rcmd, read,
17116 				    ei->ei_expected_pos.lgclblkno + count,
17117 				    ei->ei_expected_pos.partition);
17118 				if (rval == 0) {
17119 					ST_RECOV(ST_DEVINFO, st_label,
17120 					    SCSI_DEBUG, "reestablished REVC"
17121 					    " command retrying\n");
17122 					return (EAGAIN);
17123 				}
17124 			/* This handles read ahead in reverse direction */
17125 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17126 			    (difference < 0)) {
17127 				rval = st_logical_block_locate(un,
17128 				    st_uscsi_rcmd, read,
17129 				    ei->ei_expected_pos.lgclblkno - count,
17130 				    ei->ei_expected_pos.partition);
17131 				if (rval == 0) {
17132 					ST_RECOV(ST_DEVINFO, st_label,
17133 					    SCSI_DEBUG, "reestablished REVC"
17134 					    " read command retrying\n");
17135 					return (EAGAIN);
17136 				}
17137 			} else {
17138 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17139 				    "Not expected transfers_data = %d "
17140 				    "difference = %"PRId64,
17141 				    cmd_att->transfers_data, difference);
17142 			}
17143 			return (EIO);
17144 
17145 		} else {
17146 			/*
17147 			 * Commands that change tape position either
17148 			 * direction or don't change position should not
17149 			 * get here.
17150 			 */
17151 			ASSERT(0);
17152 		}
17153 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17154 		    "Didn't find a recoverable position, Failing\n");
17155 
17156 	/*
17157 	 * Command that changes tape position and can only be recovered
17158 	 * by going back to the point of origin and retrying.
17159 	 *
17160 	 * Example SCMD_SPACE.
17161 	 */
17162 	} else if (cmd_att->recov_pos_type == POS_STARTING) {
17163 		/*
17164 		 * This type of command stores the starting position.
17165 		 * If the read position is the starting position,
17166 		 * reissue the command.
17167 		 */
17168 		if (ei->ei_expected_pos.lgclblkno == read->lgclblkno) {
17169 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17170 			    "Found Space command at starting position, "
17171 			    "Reissuing\n");
17172 			return (EAGAIN);
17173 		}
17174 		/*
17175 		 * Not in the position that the command was originally issued,
17176 		 * Attempt to locate to that position.
17177 		 */
17178 		rval = st_logical_block_locate(un, st_uscsi_rcmd, read,
17179 		    ei->ei_expected_pos.lgclblkno,
17180 		    ei->ei_expected_pos.partition);
17181 		if (rval) {
17182 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17183 			    "Found Space at an unexpected position and locate "
17184 			    "back to starting position failed\n");
17185 			return (EIO);
17186 		}
17187 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17188 		    "Found Space at an unexpected position and locate "
17189 		    "back to starting position worked, Reissuing\n");
17190 		return (EAGAIN);
17191 	}
17192 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17193 	    "Unhandled attribute/expected position", &ei->ei_expected_pos);
17194 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17195 	    "Read position above did not make sense", read);
17196 	ASSERT(0);
17197 	return (EIO);
17198 }
17199 
17200 static errstate
17201 st_recover_reissue_pkt(struct scsi_tape *un, struct scsi_pkt *oldpkt)
17202 {
17203 	buf_t *bp;
17204 	buf_t *pkt_bp;
17205 	struct scsi_pkt *newpkt;
17206 	cmd_attribute const *attrib;
17207 	recov_info *rcv = oldpkt->pkt_private;
17208 	uint_t cdblen;
17209 	int rval;
17210 	int stat_size =
17211 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
17212 
17213 	ST_FUNC(ST_DEVINFO, st_recover_reissue_pkt);
17214 
17215 	bp = rcv->cmd_bp;
17216 
17217 	if (rcv->privatelen == sizeof (recov_info)) {
17218 		attrib = rcv->cmd_attrib;
17219 	} else {
17220 		attrib = st_lookup_cmd_attribute(oldpkt->pkt_cdbp[0]);
17221 	}
17222 
17223 	/*
17224 	 * Some non-uscsi commands use the b_bcount for values that
17225 	 * have nothing to do with how much data is transfered.
17226 	 * In those cases we need to hide the buf_t from scsi_init_pkt().
17227 	 */
17228 	if ((BP_UCMD(bp)) && (bp->b_bcount)) {
17229 		pkt_bp = bp;
17230 	} else if (attrib->transfers_data == TRAN_NONE) {
17231 		pkt_bp = NULL;
17232 	} else {
17233 		pkt_bp = bp;
17234 	}
17235 	/*
17236 	 * if this is a queued command make sure it the only one in the
17237 	 * run queue.
17238 	 */
17239 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
17240 		ASSERT(un->un_runqf == un->un_runql);
17241 		ASSERT(un->un_runqf == bp);
17242 	}
17243 
17244 	cdblen = scsi_cdb_size[CDB_GROUPID(oldpkt->pkt_cdbp[0])];
17245 
17246 	newpkt = scsi_init_pkt(ROUTE, NULL, pkt_bp, cdblen,
17247 	    stat_size, rcv->privatelen, 0, NULL_FUNC, NULL);
17248 	if (newpkt == NULL) {
17249 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17250 		    "Reissue pkt scsi_init_pkt() failure\n");
17251 		return (COMMAND_DONE_ERROR);
17252 	}
17253 
17254 	ASSERT(newpkt->pkt_resid == 0);
17255 	bp->b_flags &= ~(B_DONE);
17256 	bp->b_resid = 0;
17257 	st_bioerror(bp, 0);
17258 
17259 	bcopy(oldpkt->pkt_private, newpkt->pkt_private, rcv->privatelen);
17260 
17261 	newpkt->pkt_comp = oldpkt->pkt_comp;
17262 	newpkt->pkt_time = oldpkt->pkt_time;
17263 
17264 	bzero(newpkt->pkt_scbp, stat_size);
17265 	bcopy(oldpkt->pkt_cdbp, newpkt->pkt_cdbp, cdblen);
17266 
17267 	newpkt->pkt_state = 0;
17268 	newpkt->pkt_statistics = 0;
17269 
17270 	SET_BP_PKT(bp, newpkt);
17271 
17272 	scsi_destroy_pkt(oldpkt);
17273 
17274 	rval = st_transport(un, newpkt);
17275 	if (rval == TRAN_ACCEPT) {
17276 		return (JUST_RETURN);
17277 	}
17278 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17279 	    "Reissue pkt st_transport(0x%x) failure\n", rval);
17280 	if (rval != TRAN_BUSY) {
17281 		return (COMMAND_DONE_ERROR);
17282 	}
17283 	rval = st_handle_start_busy(un, bp, ST_TRAN_BUSY_TIMEOUT, 0);
17284 	if (rval) {
17285 		return (COMMAND_DONE_ERROR);
17286 	}
17287 
17288 	return (JUST_RETURN);
17289 }
17290 
17291 static int
17292 st_transport(struct scsi_tape *un, struct scsi_pkt *pkt)
17293 {
17294 	int status;
17295 
17296 	ST_FUNC(ST_DEVINFO, st_transport);
17297 
17298 	ST_CDB(ST_DEVINFO, "transport CDB", (caddr_t)pkt->pkt_cdbp);
17299 
17300 	mutex_exit(ST_MUTEX);
17301 
17302 	status = scsi_transport(pkt);
17303 
17304 	mutex_enter(ST_MUTEX);
17305 
17306 	return (status);
17307 }
17308 
17309 /*
17310  * Removed the buf_t bp from the queue referenced to by head and tail.
17311  * Returns the buf_t pointer if it is found in the queue.
17312  * Returns NULL if it is not found.
17313  */
17314 static buf_t *
17315 st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp)
17316 {
17317 	buf_t *runqbp;
17318 	buf_t *prevbp = NULL;
17319 
17320 	for (runqbp = *head; runqbp != 0; runqbp = runqbp->av_forw) {
17321 		if (runqbp == bp) {
17322 			/* found it, is it at the head? */
17323 			if (runqbp == *head) {
17324 				*head = bp->av_forw;
17325 			} else {
17326 				prevbp->av_forw = bp->av_forw;
17327 			}
17328 			if (*tail == bp) {
17329 				*tail = prevbp;
17330 			}
17331 			bp->av_forw = NULL;
17332 			return (bp); /* found and removed */
17333 		}
17334 		prevbp = runqbp;
17335 	}
17336 	return (NULL);
17337 }
17338 
17339 /*
17340  * Adds a buf_t to the queue pointed to by head and tail.
17341  * Adds it either to the head end or the tail end based on which
17342  * the passed variable end (head or tail) points at.
17343  */
17344 static void
17345 st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp)
17346 {
17347 
17348 	bp->av_forw = NULL;
17349 	if (*head) {
17350 		/* Queue is not empty */
17351 		if (end == *head) {
17352 			/* Add at front of queue */
17353 			bp->av_forw = *head;
17354 			*head = bp;
17355 		} else if (end == *tail) {
17356 			/* Add at end of queue */
17357 			(*tail)->av_forw = bp;
17358 			*tail = bp;
17359 		} else {
17360 			ASSERT(0);
17361 		}
17362 	} else {
17363 		/* Queue is empty */
17364 		*head = bp;
17365 		*tail = bp;
17366 	}
17367 }
17368 
17369 
17370 static uint64_t
17371 st_get_cdb_g0_rw_count(uchar_t *cdb)
17372 {
17373 	uint64_t count;
17374 
17375 	if ((cdb[1]) & 1) {
17376 		/* fixed block mode, the count is the number of blocks */
17377 		count =
17378 		    cdb[2] << 16 |
17379 		    cdb[3] << 8 |
17380 		    cdb[4];
17381 	} else {
17382 		/* variable block mode, the count is the block size */
17383 		count = 1;
17384 	}
17385 	return (count);
17386 }
17387 
17388 static uint64_t
17389 st_get_cdb_g0_sign_count(uchar_t *cdb)
17390 {
17391 	uint64_t count;
17392 
17393 	count =
17394 	    cdb[2] << 16 |
17395 	    cdb[3] << 8 |
17396 	    cdb[4];
17397 	/*
17398 	 * If the sign bit of the 3 byte value is set, extended it.
17399 	 */
17400 	if (count & 0x800000) {
17401 		count |= 0xffffffffff000000;
17402 	}
17403 	return (count);
17404 }
17405 
17406 static uint64_t
17407 st_get_cdb_g0_count(uchar_t *cdb)
17408 {
17409 	uint64_t count;
17410 
17411 	count =
17412 	    cdb[2] << 16 |
17413 	    cdb[3] << 8 |
17414 	    cdb[4];
17415 	return (count);
17416 }
17417 
17418 static uint64_t
17419 st_get_cdb_g5_rw_cnt(uchar_t *cdb)
17420 {
17421 	uint64_t count;
17422 
17423 	if ((cdb[1]) & 1) {
17424 		/* fixed block mode */
17425 		count =
17426 		    cdb[12] << 16 |
17427 		    cdb[13] << 8 |
17428 		    cdb[14];
17429 	} else {
17430 		/* variable block mode */
17431 		count = 1;
17432 	}
17433 	return (count);
17434 }
17435 
17436 static uint64_t
17437 st_get_no_count(uchar_t *cdb)
17438 {
17439 	ASSERT(cdb[0] == SCMD_REWIND);
17440 	return ((uint64_t)cdb[0]);
17441 }
17442 
17443 static uint64_t
17444 st_get_load_options(uchar_t *cdb)
17445 {
17446 	return ((uint64_t)(cdb[4] | (LD_HOLD << 1)));
17447 }
17448 
17449 static uint64_t
17450 st_get_erase_options(uchar_t *cdb)
17451 {
17452 	return (cdb[1] | (cdb[0] << 8));
17453 }
17454 
17455 static uint64_t
17456 st_get_cdb_g1_lba(uchar_t *cdb)
17457 {
17458 	uint64_t lba;
17459 
17460 	lba =
17461 	    cdb[3] << 24 |
17462 	    cdb[4] << 16 |
17463 	    cdb[5] << 8 |
17464 	    cdb[6];
17465 	return (lba);
17466 }
17467 
17468 static uint64_t
17469 st_get_cdb_g5_count(uchar_t *cdb)
17470 {
17471 	uint64_t count =
17472 	    cdb[12] << 16 |
17473 	    cdb[13] << 8 |
17474 	    cdb[14];
17475 
17476 	return (count);
17477 }
17478 
17479 static uint64_t
17480 st_get_cdb_g4g5_cnt(uchar_t *cdb)
17481 {
17482 	uint64_t lba;
17483 
17484 	lba =
17485 	    (uint64_t)cdb[4] << 56 |
17486 	    (uint64_t)cdb[5] << 48 |
17487 	    (uint64_t)cdb[6] << 40 |
17488 	    (uint64_t)cdb[7] << 32 |
17489 	    (uint64_t)cdb[8] << 24 |
17490 	    (uint64_t)cdb[9] << 16 |
17491 	    (uint64_t)cdb[10] << 8 |
17492 	    (uint64_t)cdb[11];
17493 	return (lba);
17494 }
17495 
17496 static const cmd_attribute cmd_attributes[] = {
17497 	{ SCMD_TEST_UNIT_READY,
17498 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17499 	    0, 0, 0 },
17500 	{ SCMD_REWIND,
17501 	    1, 1, 1, 0, 0, DIR_REVC, TRAN_NONE, POS_EXPECTED,
17502 	    0, 0, 0, st_get_no_count },
17503 	{ SCMD_REQUEST_SENSE,
17504 	    0, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17505 	    0, 0, 0 },
17506 	{ SCMD_READ_BLKLIM,
17507 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17508 	    0, 0, 0 },
17509 	{ SCMD_READ,
17510 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_READ, POS_EXPECTED,
17511 	    0, 0, 0, st_get_cdb_g0_rw_count },
17512 	{ SCMD_WRITE,
17513 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
17514 	    0, 0, 0, st_get_cdb_g0_rw_count },
17515 	{ SCMD_READ_G4,
17516 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_READ, POS_EXPECTED,
17517 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17518 	{ SCMD_WRITE_G4,
17519 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
17520 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17521 	{ SCMD_READ_REVERSE,
17522 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
17523 	    0, 0, 0, st_get_cdb_g0_rw_count },
17524 	{ SCMD_READ_REVERSE_G4,
17525 	    1, 0, 1, 1, 1, DIR_REVC, TRAN_READ, POS_EXPECTED,
17526 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17527 	{ SCMD_WRITE_FILE_MARK,
17528 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17529 	    0, 0, 0, st_get_cdb_g0_count },
17530 	{ SCMD_WRITE_FILE_MARK_G4,
17531 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17532 	    0, 0, 0, st_get_cdb_g5_count, st_get_cdb_g4g5_cnt },
17533 	{ SCMD_SPACE,
17534 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
17535 	    0, 0, 0, st_get_cdb_g0_sign_count },
17536 	{ SCMD_SPACE_G4,
17537 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
17538 	    0, 0, 0, st_get_cdb_g4g5_cnt },
17539 	{ SCMD_INQUIRY,
17540 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17541 	    0, 0, 0 },
17542 	{ SCMD_VERIFY_G0,
17543 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17544 	    0, 0, 0, st_get_cdb_g0_rw_count },
17545 	{ SCMD_VERIFY_G4,
17546 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17547 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17548 	{ SCMD_RECOVER_BUF,
17549 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
17550 	    0, 0, 0 },
17551 	{ SCMD_MODE_SELECT,
17552 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17553 	    0, 0, 0 },
17554 	{ SCMD_RESERVE,
17555 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17556 	    0, 0, 0 },
17557 	{ SCMD_RELEASE,
17558 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17559 	    0, 0, 0 },
17560 	{ SCMD_ERASE,
17561 	    1, 0, 1, 1, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17562 	    0, 0, 0, st_get_erase_options },
17563 	{ SCMD_MODE_SENSE,
17564 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17565 	    0, 0, 0 },
17566 	{ SCMD_LOAD,
17567 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
17568 	    0, 0, 0, st_get_load_options },
17569 	{ SCMD_GDIAG,
17570 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17571 	    1, 0, 0 },
17572 	{ SCMD_SDIAG,
17573 	    1, 0, 1, 1, 0, DIR_EITH, TRAN_WRTE, POS_EXPECTED,
17574 	    1, 0, 0 },
17575 	{ SCMD_DOORLOCK,
17576 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17577 	    0, 4, 3 },
17578 	{ SCMD_LOCATE,
17579 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
17580 	    0, 0, 0, NULL, st_get_cdb_g1_lba },
17581 	{ SCMD_READ_POSITION,
17582 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17583 	    0, 0, 0 },
17584 	{ SCMD_WRITE_BUFFER,
17585 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17586 	    1, 0, 0 },
17587 	{ SCMD_READ_BUFFER,
17588 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17589 	    1, 0, 0 },
17590 	{ SCMD_REPORT_DENSITIES,
17591 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17592 	    0, 0, 0 },
17593 	{ SCMD_LOG_SELECT_G1,
17594 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17595 	    0, 0, 0 },
17596 	{ SCMD_LOG_SENSE_G1,
17597 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17598 	    0, 0, 0 },
17599 	{ SCMD_PRIN,
17600 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17601 	    0, 0, 0 },
17602 	{ SCMD_PROUT,
17603 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17604 	    0, 0, 0 },
17605 	{ SCMD_READ_ATTRIBUTE,
17606 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17607 	    0, 0, 0 },
17608 	{ SCMD_WRITE_ATTRIBUTE,
17609 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17610 	    0, 0, 0 },
17611 	{ SCMD_LOCATE_G4,
17612 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
17613 	    0, 0, 0, NULL, st_get_cdb_g4g5_cnt },
17614 	{ SCMD_REPORT_LUNS,
17615 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17616 	    0, 0, 0 },
17617 	{ SCMD_SVC_ACTION_IN_G5,
17618 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17619 	    0, 0, 0 },
17620 	{ SCMD_MAINTENANCE_IN,
17621 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17622 	    0, 0, 0 },
17623 	{ SCMD_MAINTENANCE_OUT,
17624 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17625 	    0, 0, 0 },
17626 	{ 0xff, /* Default attribute for unsupported commands */
17627 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_STARTING,
17628 	    1, 0, 0, NULL, NULL }
17629 };
17630 
17631 static const cmd_attribute *
17632 st_lookup_cmd_attribute(unsigned char cmd)
17633 {
17634 	int i;
17635 	cmd_attribute const *attribute;
17636 
17637 	for (i = 0; i < ST_NUM_MEMBERS(cmd_attributes); i++) {
17638 		attribute = &cmd_attributes[i];
17639 		if (attribute->cmd == cmd) {
17640 			return (attribute);
17641 		}
17642 	}
17643 	ASSERT(attribute);
17644 	return (attribute);
17645 }
17646 
17647 static int
17648 st_reset(struct scsi_tape *un, int reset_type)
17649 {
17650 	int rval;
17651 
17652 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
17653 
17654 	ST_FUNC(ST_DEVINFO, st_reset);
17655 	un->un_rsvd_status |= ST_INITIATED_RESET;
17656 	mutex_exit(ST_MUTEX);
17657 	do {
17658 		rval = scsi_reset(&un->un_sd->sd_address, reset_type);
17659 		if (rval == 0) {
17660 			switch (reset_type) {
17661 			case RESET_LUN:
17662 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
17663 				    "LUN reset failed trying target reset");
17664 				reset_type = RESET_TARGET;
17665 				break;
17666 			case RESET_TARGET:
17667 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
17668 				    "target reset failed trying bus reset");
17669 				reset_type = RESET_BUS;
17670 				break;
17671 			case RESET_BUS:
17672 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
17673 				    "bus reset failed trying all reset");
17674 				reset_type = RESET_ALL;
17675 			default:
17676 				mutex_enter(ST_MUTEX);
17677 				return (rval);
17678 			}
17679 		}
17680 	} while (rval == 0);
17681 	mutex_enter(ST_MUTEX);
17682 	return (rval);
17683 }
17684 
17685 
17686 static void
17687 st_reset_notification(caddr_t arg)
17688 {
17689 	struct scsi_tape *un = (struct scsi_tape *)arg;
17690 
17691 	ST_FUNC(ST_DEVINFO, st_reset_notification);
17692 	mutex_enter(ST_MUTEX);
17693 
17694 	un->un_unit_attention_flags = 2;
17695 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
17696 	    ST_RESERVE) {
17697 		un->un_rsvd_status |= ST_LOST_RESERVE;
17698 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
17699 		    "Lost Reservation notification");
17700 	} else {
17701 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
17702 		    "reset notification");
17703 	}
17704 
17705 	if ((un->un_restore_pos == 0) &&
17706 	    (un->un_state == ST_STATE_CLOSED) ||
17707 	    (un->un_state == ST_STATE_OPEN_PENDING_IO) ||
17708 	    (un->un_state == ST_STATE_CLOSING)) {
17709 		un->un_restore_pos = 1;
17710 	}
17711 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
17712 	    "reset and state was %d\n", un->un_state);
17713 	mutex_exit(ST_MUTEX);
17714 }
17715