xref: /titanic_50/usr/src/uts/common/io/scsi/targets/st.c (revision 275c9da86e89f8abf71135cf63d9fc23671b2e60)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * SCSI	 SCSA-compliant and not-so-DDI-compliant Tape Driver
31  */
32 
33 #if defined(lint) && !defined(DEBUG)
34 #define	DEBUG	1
35 #endif
36 
37 #include <sys/modctl.h>
38 #include <sys/scsi/scsi.h>
39 #include <sys/mtio.h>
40 #include <sys/scsi/targets/stdef.h>
41 #include <sys/file.h>
42 #include <sys/kstat.h>
43 #include <sys/ddidmareq.h>
44 #include <sys/ddi.h>
45 #include <sys/sunddi.h>
46 #include <sys/byteorder.h>
47 
48 #define	IOSP	KSTAT_IO_PTR(un->un_stats)
49 /*
50  * stats maintained only for reads/writes as commands
51  * like rewind etc skew the wait/busy times
52  */
53 #define	IS_RW(bp) 	((bp)->b_bcount > 0)
54 #define	ST_DO_KSTATS(bp, kstat_function) \
55 	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
56 		kstat_function(IOSP); \
57 	}
58 
59 #define	ST_DO_ERRSTATS(un, x)  \
60 	if (un->un_errstats) { \
61 		struct st_errstats *stp; \
62 		stp = (struct st_errstats *)un->un_errstats->ks_data; \
63 		stp->x.value.ul++; \
64 	}
65 
66 #define	FILL_SCSI1_LUN(devp, pkt) 					\
67 	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
68 		int _lun;						\
69 		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
70 		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
71 		if (_lun > 0) {						\
72 			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
73 			    _lun;					\
74 		}							\
75 	}
76 
77 /*
78  * get an available contig mem header, cp.
79  * when big_enough is true, we will return NULL, if no big enough
80  * contig mem is found.
81  * when big_enough is false, we will try to find cp containing big
82  * enough contig mem. if not found, we will ruturn the last cp available.
83  *
84  * used by st_get_contig_mem()
85  */
86 #define	ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough) {		\
87 	struct contig_mem *tmp_cp = NULL;				\
88 	for ((cp) = (un)->un_contig_mem;				\
89 	    (cp) != NULL;						\
90 	    tmp_cp = (cp), (cp) = (cp)->cm_next) { 			\
91 		if (((cp)->cm_len >= (len)) || 				\
92 		    (!(big_enough) && ((cp)->cm_next == NULL))) { 	\
93 			if (tmp_cp == NULL) { 				\
94 				(un)->un_contig_mem = (cp)->cm_next; 	\
95 			} else { 					\
96 				tmp_cp->cm_next = (cp)->cm_next; 	\
97 			} 						\
98 			(cp)->cm_next = NULL; 				\
99 			(un)->un_contig_mem_available_num--; 		\
100 			break; 						\
101 		} 							\
102 	} 								\
103 }
104 
105 #define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
106 #define	COPY_POS(dest, source) bcopy(source, dest, sizeof (tapepos_t))
107 #define	ISALNUM(byte) \
108 	(((byte) >= 'a' && (byte) <= 'z') || \
109 	((byte) >= 'A' && (byte) <= 'Z') || \
110 	((byte) >= '0' && (byte) <= '9'))
111 
112 #define	ONE_K	1024
113 
114 /*
115  * Global External Data Definitions
116  */
117 extern struct scsi_key_strings scsi_cmds[];
118 extern uchar_t	scsi_cdb_size[];
119 
120 /*
121  * Local Static Data
122  */
123 static void *st_state;
124 static char *const st_label = "st";
125 static volatile dev_info_t *st_lastdev;
126 static volatile int st_recov_sz = sizeof (recov_info);
127 
128 #ifdef	__x86
129 /*
130  * We need to use below DMA attr to alloc physically contiguous
131  * memory to do I/O in big block size
132  */
133 static ddi_dma_attr_t st_contig_mem_dma_attr = {
134 	DMA_ATTR_V0,    /* version number */
135 	0x0,		/* lowest usable address */
136 	0xFFFFFFFFull,  /* high DMA address range */
137 	0xFFFFFFFFull,  /* DMA counter register */
138 	1,		/* DMA address alignment */
139 	1,		/* DMA burstsizes */
140 	1,		/* min effective DMA size */
141 	0xFFFFFFFFull,  /* max DMA xfer size */
142 	0xFFFFFFFFull,  /* segment boundary */
143 	1,		/* s/g list length */
144 	1,		/* granularity of device */
145 	0		/* DMA transfer flags */
146 };
147 
148 static ddi_device_acc_attr_t st_acc_attr = {
149 	DDI_DEVICE_ATTR_V0,
150 	DDI_NEVERSWAP_ACC,
151 	DDI_STRICTORDER_ACC
152 };
153 
154 /* set limitation for the number of contig_mem */
155 static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
156 #endif
157 
158 /*
159  * Tunable parameters
160  *
161  * DISCLAIMER
162  * ----------
163  * These parameters are intended for use only in system testing; if you use
164  * them in production systems, you do so at your own risk. Altering any
165  * variable not listed below may cause unpredictable system behavior.
166  *
167  * st_check_media_time
168  *
169  *   Three second state check
170  *
171  * st_allow_large_xfer
172  *
173  *   Gated with ST_NO_RECSIZE_LIMIT
174  *
175  *   0 - Transfers larger than 64KB will not be allowed
176  *       regardless of the setting of ST_NO_RECSIZE_LIMIT
177  *   1 - Transfers larger than 64KB will be allowed
178  *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
179  *
180  * st_report_soft_errors_on_close
181  *
182  *  Gated with ST_SOFT_ERROR_REPORTING
183  *
184  *  0 - Errors will not be reported on close regardless
185  *      of the setting of ST_SOFT_ERROR_REPORTING
186  *
187  *  1 - Errors will be reported on close if
188  *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
189  */
190 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
191 static int st_retry_count	= ST_RETRY_COUNT;
192 
193 static int st_io_time		= ST_IO_TIME;
194 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
195 
196 static int st_space_time	= ST_SPACE_TIME;
197 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
198 
199 static int st_error_level	= SCSI_ERR_RETRYABLE;
200 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
201 
202 static int st_max_throttle	= ST_MAX_THROTTLE;
203 
204 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
205 
206 static int st_allow_large_xfer = 1;
207 static int st_report_soft_errors_on_close = 1;
208 
209 /*
210  * End of tunable parameters list
211  */
212 
213 
214 
215 /*
216  * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
217  *
218  * Asynchronous I/O's main offering is that it is a non-blocking way to do
219  * reads and writes.  The driver will queue up all the requests it gets and
220  * have them ready to transport to the HBA.  Unfortunately, we cannot always
221  * just ship the I/O requests to the HBA, as there errors and exceptions
222  * that may happen when we don't want the HBA to continue.  Therein comes
223  * the flush-on-errors capability.  If the HBA supports it, then st will
224  * send in st_max_throttle I/O requests at the same time.
225  *
226  * Persistent errors : This was also reasonably simple.  In the interrupt
227  * routines, if there was an error or exception (FM, LEOT, media error,
228  * transport error), the persistent error bits are set and shuts everything
229  * down, but setting the throttle to zero.  If we hit and exception in the
230  * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
231  * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
232  * the appropriate error, and this will preserve order. Of course, depending
233  * on the exception we have to show a zero read or write before we show
234  * errors back to the application.
235  */
236 
237 extern const int st_ndrivetypes;	/* defined in st_conf.c */
238 extern const struct st_drivetype st_drivetypes[];
239 extern const char st_conf_version[];
240 
241 #ifdef STDEBUG
242 static int st_soft_error_report_debug = 0;
243 volatile int st_debug = 0;
244 #endif
245 
246 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
247 
248 static const struct vid_drivetype {
249 	char	*vid;
250 	char	type;
251 } st_vid_dt[] = {
252 	{"LTO-CVE ",	MT_LTO},
253 	{"QUANTUM ",    MT_ISDLT},
254 	{"SONY    ",    MT_ISAIT},
255 	{"STK     ",	MT_ISSTK9840}
256 };
257 
258 static const struct driver_minor_data {
259 	char	*name;
260 	int	minor;
261 } st_minor_data[] = {
262 	/*
263 	 * The top 4 entries are for the default densities,
264 	 * don't alter their position.
265 	 */
266 	{"",	0},
267 	{"n",	MT_NOREWIND},
268 	{"b",	MT_BSD},
269 	{"bn",	MT_NOREWIND | MT_BSD},
270 	{"l",	MT_DENSITY1},
271 	{"m",	MT_DENSITY2},
272 	{"h",	MT_DENSITY3},
273 	{"c",	MT_DENSITY4},
274 	{"u",	MT_DENSITY4},
275 	{"ln",	MT_DENSITY1 | MT_NOREWIND},
276 	{"mn",	MT_DENSITY2 | MT_NOREWIND},
277 	{"hn",	MT_DENSITY3 | MT_NOREWIND},
278 	{"cn",	MT_DENSITY4 | MT_NOREWIND},
279 	{"un",	MT_DENSITY4 | MT_NOREWIND},
280 	{"lb",	MT_DENSITY1 | MT_BSD},
281 	{"mb",	MT_DENSITY2 | MT_BSD},
282 	{"hb",	MT_DENSITY3 | MT_BSD},
283 	{"cb",	MT_DENSITY4 | MT_BSD},
284 	{"ub",	MT_DENSITY4 | MT_BSD},
285 	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
286 	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
287 	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
288 	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
289 	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
290 };
291 
292 /* strings used in many debug and warning messages */
293 static const char wr_str[]  = "write";
294 static const char rd_str[]  = "read";
295 static const char wrg_str[] = "writing";
296 static const char rdg_str[] = "reading";
297 static const char *space_strs[] = {
298 	"records",
299 	"filemarks",
300 	"sequential filemarks",
301 	"eod",
302 	"setmarks",
303 	"sequential setmarks",
304 	"Reserved",
305 	"Reserved"
306 };
307 static const char *load_strs[] = {
308 	"unload",		/* LD_UNLOAD		0 */
309 	"load",			/* LD_LOAD		1 */
310 	"retension",		/* LD_RETEN		2 */
311 	"load reten",		/* LD_LOAD | LD_RETEN	3 */
312 	"eod",			/* LD_EOT		4 */
313 	"load EOD",		/* LD_LOAD | LD_EOT	5 */
314 	"reten EOD",		/* LD_RETEN | LD_EOT	6 */
315 	"load reten EOD"	/* LD_LOAD|LD_RETEN|LD_EOT 7 */
316 	"hold",			/* LD_HOLD		8 */
317 	"load and hold"		/* LD_LOAD | LD_HOLD	9 */
318 };
319 
320 const char *bogusID = "Unknown Media ID";
321 
322 /* default density offsets in the table above */
323 #define	DEF_BLANK	0
324 #define	DEF_NOREWIND	1
325 #define	DEF_BSD		2
326 #define	DEF_BSD_NR	3
327 
328 /* Sense Key, ASC/ASCQ for which tape ejection is needed */
329 
330 static struct tape_failure_code {
331 	uchar_t key;
332 	uchar_t add_code;
333 	uchar_t qual_code;
334 } st_tape_failure_code[] = {
335 	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
336 	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
337 	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
338 	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
339 	{ KEY_NOT_READY, 0x53, 0x00},
340 	{ 0xff}
341 };
342 
343 /*  clean bit position and mask */
344 
345 static struct cln_bit_position {
346 	ushort_t cln_bit_byte;
347 	uchar_t cln_bit_mask;
348 } st_cln_bit_position[] = {
349 	{ 21, 0x08},
350 	{ 70, 0xc0},
351 	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
352 };
353 
354 /*
355  * architecture dependent allocation restrictions. For x86, we'll set
356  * dma_attr_addr_hi to st_max_phys_addr and dma_attr_sgllen to
357  * st_sgl_size during _init().
358  */
359 #if defined(__sparc)
360 static ddi_dma_attr_t st_alloc_attr = {
361 	DMA_ATTR_V0,	/* version number */
362 	0x0,		/* lowest usable address */
363 	0xFFFFFFFFull,	/* high DMA address range */
364 	0xFFFFFFFFull,	/* DMA counter register */
365 	1,		/* DMA address alignment */
366 	1,		/* DMA burstsizes */
367 	1,		/* min effective DMA size */
368 	0xFFFFFFFFull,	/* max DMA xfer size */
369 	0xFFFFFFFFull,	/* segment boundary */
370 	1,		/* s/g list length */
371 	512,		/* granularity of device */
372 	0		/* DMA transfer flags */
373 };
374 #elif defined(__x86)
375 static ddi_dma_attr_t st_alloc_attr = {
376 	DMA_ATTR_V0,	/* version number */
377 	0x0,		/* lowest usable address */
378 	0x0,		/* high DMA address range [set in _init()] */
379 	0xFFFFull,	/* DMA counter register */
380 	512,		/* DMA address alignment */
381 	1,		/* DMA burstsizes */
382 	1,		/* min effective DMA size */
383 	0xFFFFFFFFull,	/* max DMA xfer size */
384 	0xFFFFFFFFull,  /* segment boundary */
385 	0,		/* s/g list length */
386 	512,		/* granularity of device [set in _init()] */
387 	0		/* DMA transfer flags */
388 };
389 uint64_t st_max_phys_addr = 0xFFFFFFFFull;
390 int st_sgl_size = 0xF;
391 
392 #endif
393 
394 /*
395  * Configuration Data:
396  *
397  * Device driver ops vector
398  */
399 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
400 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
401 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
402 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
403 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
404 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
405 static int st_strategy(struct buf *bp);
406 static int st_queued_strategy(buf_t *bp);
407 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
408 	cred_t *cred_p, int *rval_p);
409 extern int nulldev(), nodev();
410 
411 static struct cb_ops st_cb_ops = {
412 	st_open,		/* open */
413 	st_close,		/* close */
414 	st_queued_strategy,	/* strategy Not Block device but async checks */
415 	nodev,			/* print */
416 	nodev,			/* dump */
417 	st_read,		/* read */
418 	st_write,		/* write */
419 	st_ioctl,		/* ioctl */
420 	nodev,			/* devmap */
421 	nodev,			/* mmap */
422 	nodev,			/* segmap */
423 	nochpoll,		/* poll */
424 	ddi_prop_op,		/* cb_prop_op */
425 	0,			/* streamtab  */
426 	D_64BIT | D_MP | D_NEW | D_HOTPLUG |
427 	D_OPEN_RETURNS_EINTR,	/* cb_flag */
428 	CB_REV,			/* cb_rev */
429 	st_aread, 		/* async I/O read entry point */
430 	st_awrite		/* async I/O write entry point */
431 
432 };
433 
434 static int st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
435 		void **result);
436 static int st_probe(dev_info_t *dev);
437 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
438 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
439 
440 static struct dev_ops st_ops = {
441 	DEVO_REV,		/* devo_rev, */
442 	0,			/* refcnt  */
443 	st_info,		/* info */
444 	nulldev,		/* identify */
445 	st_probe,		/* probe */
446 	st_attach,		/* attach */
447 	st_detach,		/* detach */
448 	nodev,			/* reset */
449 	&st_cb_ops,		/* driver operations */
450 	(struct bus_ops *)0,	/* bus operations */
451 	nulldev			/* power */
452 };
453 
454 /*
455  * Local Function Declarations
456  */
457 static char *st_print_scsi_cmd(char cmd);
458 static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
459     char *title, char *cdb);
460 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
461     char *title, char *data, int len);
462 static int st_doattach(struct scsi_device *devp, int (*canwait)());
463 static void st_known_tape_type(struct scsi_tape *un);
464 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
465     struct st_drivetype *);
466 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
467     struct st_drivetype *);
468 static int st_get_conf_from_tape_drive(struct scsi_tape *, char *,
469     struct st_drivetype *);
470 static int st_get_densities_from_tape_drive(struct scsi_tape *,
471     struct st_drivetype *);
472 static int st_get_timeout_values_from_tape_drive(struct scsi_tape *,
473     struct st_drivetype *);
474 static int st_get_timeouts_value(struct scsi_tape *, uchar_t, ushort_t *,
475     ushort_t);
476 static int st_get_default_conf(struct scsi_tape *, char *,
477     struct st_drivetype *);
478 static int st_rw(dev_t dev, struct uio *uio, int flag);
479 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
480 static int st_find_eod(struct scsi_tape *un);
481 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
482 static int st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *, int flag);
483 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
484 static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
485 static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
486 static void st_start(struct scsi_tape *un);
487 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
488     clock_t timeout_interval, int queued);
489 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
490     clock_t timeout_interval);
491 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
492 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
493 static void st_init(struct scsi_tape *un);
494 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
495     int (*func)(caddr_t));
496 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
497     struct buf *bp, int (*func)(caddr_t));
498 static void st_intr(struct scsi_pkt *pkt);
499 static void st_set_state(struct scsi_tape *un, buf_t *bp);
500 static void st_test_append(struct buf *bp);
501 static int st_runout(caddr_t);
502 static int st_cmd(struct scsi_tape *un, int com, int64_t count, int wait);
503 static int st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com,
504     int64_t count);
505 static int st_set_compression(struct scsi_tape *un);
506 static int st_write_fm(dev_t dev, int wfm);
507 static int st_determine_generic(struct scsi_tape *un);
508 static int st_determine_density(struct scsi_tape *un, int rw);
509 static int st_get_density(struct scsi_tape *un);
510 static int st_set_density(struct scsi_tape *un);
511 static int st_loadtape(struct scsi_tape *un);
512 static int st_modesense(struct scsi_tape *un);
513 static int st_modeselect(struct scsi_tape *un);
514 static errstate st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
515 static int st_wrongtapetype(struct scsi_tape *un);
516 static errstate st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
517 static errstate st_handle_sense(struct scsi_tape *un, struct buf *bp,
518     tapepos_t *);
519 static errstate st_handle_autosense(struct scsi_tape *un, struct buf *bp,
520     tapepos_t *);
521 static int st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag);
522 static void st_update_error_stack(struct scsi_tape *un, struct scsi_pkt *pkt,
523     struct scsi_arq_status *cmd);
524 static void st_empty_error_stack(struct scsi_tape *un);
525 static errstate st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
526     struct scsi_status *, tapepos_t *);
527 static int st_report_soft_errors(dev_t dev, int flag);
528 static void st_delayed_cv_broadcast(void *arg);
529 static int st_check_media(dev_t dev, enum mtio_state state);
530 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
531 static void st_intr_restart(void *arg);
532 static void st_start_restart(void *arg);
533 static int st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
534     struct seq_mode *page_data, int page_size);
535 static int st_change_block_size(struct scsi_tape *un, uint32_t nblksz);
536 static int st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
537     struct seq_mode *page_data, int page_size);
538 static int st_read_block_limits(struct scsi_tape *un,
539     struct read_blklim *read_blk);
540 static int st_report_density_support(struct scsi_tape *un,
541     uchar_t *density_data, size_t buflen);
542 static int st_report_supported_operation(struct scsi_tape *un,
543     uchar_t *oper_data, uchar_t option_code, ushort_t service_action);
544 static int st_tape_init(struct scsi_tape *un);
545 static void st_flush(struct scsi_tape *un);
546 static void st_set_pe_errno(struct scsi_tape *un);
547 static void st_hba_unflush(struct scsi_tape *un);
548 static void st_turn_pe_on(struct scsi_tape *un);
549 static void st_turn_pe_off(struct scsi_tape *un);
550 static void st_set_pe_flag(struct scsi_tape *un);
551 static void st_clear_pe(struct scsi_tape *un);
552 static void st_wait_for_io(struct scsi_tape *un);
553 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
554 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
555 static int st_reserve_release(struct scsi_tape *un, int command, ubufunc_t ubf);
556 static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb);
557 static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
558     int count);
559 static int st_take_ownership(struct scsi_tape *un);
560 static int st_check_asc_ascq(struct scsi_tape *un);
561 static int st_check_clean_bit(struct scsi_tape *un);
562 static int st_check_alert_flags(struct scsi_tape *un);
563 static int st_check_sequential_clean_bit(struct scsi_tape *un);
564 static int st_check_sense_clean_bit(struct scsi_tape *un);
565 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
566 static void st_calculate_timeouts(struct scsi_tape *un);
567 static writablity st_is_drive_worm(struct scsi_tape *un);
568 static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
569     void *buf, size_t size, ubufunc_t bufunc);
570 static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
571     caddr_t dest, uchar_t page);
572 static int st_update_block_pos(struct scsi_tape *un, bufunc_t bf,
573     int post_space);
574 static int st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
575     read_p_types type, size_t data_sz, const caddr_t responce, int post_space);
576 static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
577 static int st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf,
578     tapepos_t *pos, uint64_t lblk, uchar_t partition);
579 static int st_mtfsf_ioctl(struct scsi_tape *un, int files);
580 static int st_mtfsr_ioctl(struct scsi_tape *un, int count);
581 static int st_mtbsf_ioctl(struct scsi_tape *un, int files);
582 static int st_mtnbsf_ioctl(struct scsi_tape *un, int count);
583 static int st_mtbsr_ioctl(struct scsi_tape *un, int num);
584 static int st_mtfsfm_ioctl(struct scsi_tape *un, int cnt);
585 static int st_mtbsfm_ioctl(struct scsi_tape *un, int cnt);
586 static int st_backward_space_files(struct scsi_tape *un, int count,
587     int infront);
588 static int st_forward_space_files(struct scsi_tape *un, int files);
589 static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
590     int32_t fileno);
591 static int st_space_to_begining_of_file(struct scsi_tape *un);
592 static int st_space_records(struct scsi_tape *un, int records);
593 static int st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc);
594 static errstate st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
595     errstate onentry);
596 static void st_recover(void *arg);
597 static void st_recov_cb(struct scsi_pkt *pkt);
598 static int st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait);
599 static int st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
600     int flag);
601 static void st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
602     struct scsi_pkt *cmd);
603 static int st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf);
604 static int st_test_path_to_device(struct scsi_tape *un);
605 static int st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
606     read_pos_data_t *raw);
607 static int st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
608     read_pos_data_t *raw);
609 static int st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
610     cmd_attribute const * cmd_att, tapepos_t *read);
611 static errstate st_recover_reissue_pkt(struct scsi_tape *us,
612     struct scsi_pkt *pkt);
613 static int st_transport(struct scsi_tape *un, struct scsi_pkt *pkt);
614 static buf_t *st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp);
615 static void st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp);
616 static int st_reset(struct scsi_tape *un, int reset_type);
617 static void st_reset_notification(caddr_t arg);
618 static const cmd_attribute *st_lookup_cmd_attribute(unsigned char cmd);
619 
620 #ifdef	__x86
621 /*
622  * routines for I/O in big block size
623  */
624 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
625 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
626     int alloc_flags);
627 static int st_bigblk_xfer_done(struct buf *bp);
628 static struct buf *st_get_bigblk_bp(struct buf *bp);
629 #endif
630 static void st_print_position(dev_info_t *dev, char *label, uint_t level,
631     const char *comment, tapepos_t *pos);
632 
633 /*
634  * error statistics create/update functions
635  */
636 static int st_create_errstats(struct scsi_tape *, int);
637 static int st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf,
638     tapepos_t *pos);
639 
640 #ifdef STDEBUG
641 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
642 static char *st_dev_name(dev_t dev);
643 #endif /* STDEBUG */
644 
645 #if !defined(lint)
646 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
647     scsi_pkt buf uio scsi_cdb uscsi_cmd))
648 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
649 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
650 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
651 #endif
652 
653 /*
654  * autoconfiguration routines.
655  */
656 char _depends_on[] = "misc/scsi";
657 
658 static struct modldrv modldrv = {
659 	&mod_driverops,		/* Type of module. This one is a driver */
660 	"SCSI tape Driver %I%", /* Name of the module. */
661 	&st_ops			/* driver ops */
662 };
663 
664 static struct modlinkage modlinkage = {
665 	MODREV_1, &modldrv, NULL
666 };
667 
668 /*
669  * Notes on Post Reset Behavior in the tape driver:
670  *
671  * When the tape drive is opened, the driver  attempts  to make sure that
672  * the tape head is positioned exactly where it was left when it was last
673  * closed  provided  the  medium  is not  changed.  If the tape  drive is
674  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
675  * of position due to reset) will happen when the first tape operation or
676  * I/O occurs.  The repositioning (if required) may not be possible under
677  * certain situations such as when the device firmware not able to report
678  * the medium  change in the REQUEST  SENSE data  because of a reset or a
679  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
680  * extraordinary  situations, where the driver fails to position the head
681  * at its  original  position,  it will fail the open the first  time, to
682  * save the applications from overwriting the data.  All further attempts
683  * to open the tape device will result in the driver  attempting  to load
684  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
685  * indicate  that further  attempts to open the tape device may result in
686  * the tape being  loaded at BOT will be printed on the  console.  If the
687  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
688  * original tape head  position,  will result in the failure of the first
689  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
690  * internal tape position  which will  necessitate  the  applications  to
691  * validate the position by using either a tape  positioning  ioctl (such
692  * as MTREW) or closing and reopening the tape device.
693  *
694  */
695 
696 int
697 _init(void)
698 {
699 	int e;
700 
701 	if (((e = ddi_soft_state_init(&st_state,
702 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
703 		return (e);
704 	}
705 
706 	if ((e = mod_install(&modlinkage)) != 0) {
707 		ddi_soft_state_fini(&st_state);
708 	}
709 
710 #if defined(__x86)
711 	/* set the max physical address for iob allocs on x86 */
712 	st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
713 
714 	/*
715 	 * set the sgllen for iob allocs on x86. If this is set less than
716 	 * the number of pages the buffer will take (taking into account
717 	 * alignment), it would force the allocator to try and allocate
718 	 * contiguous pages.
719 	 */
720 	st_alloc_attr.dma_attr_sgllen = st_sgl_size;
721 #endif
722 
723 	return (e);
724 }
725 
726 int
727 _fini(void)
728 {
729 	int e;
730 
731 	if ((e = mod_remove(&modlinkage)) != 0) {
732 		return (e);
733 	}
734 
735 	ddi_soft_state_fini(&st_state);
736 
737 	return (e);
738 }
739 
740 int
741 _info(struct modinfo *modinfop)
742 {
743 	return (mod_info(&modlinkage, modinfop));
744 }
745 
746 
747 static int
748 st_probe(dev_info_t *devi)
749 {
750 	int instance;
751 	struct scsi_device *devp;
752 	int rval;
753 
754 #if !defined(__sparc)
755 	char    *tape_prop;
756 	int	tape_prop_len;
757 #endif
758 
759 	ST_ENTR(devi, st_probe);
760 
761 	/* If self identifying device */
762 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
763 		return (DDI_PROBE_DONTCARE);
764 	}
765 
766 #if !defined(__sparc)
767 	/*
768 	 * Since some x86 HBAs have devnodes that look like SCSI as
769 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
770 	 * we check for the presence of the "tape" property.
771 	 */
772 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
773 	    DDI_PROP_CANSLEEP, "tape",
774 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
775 		return (DDI_PROBE_FAILURE);
776 	}
777 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
778 		kmem_free(tape_prop, tape_prop_len);
779 		return (DDI_PROBE_FAILURE);
780 	}
781 	kmem_free(tape_prop, tape_prop_len);
782 #endif
783 
784 	devp = ddi_get_driver_private(devi);
785 	instance = ddi_get_instance(devi);
786 
787 	if (ddi_get_soft_state(st_state, instance) != NULL) {
788 		return (DDI_PROBE_PARTIAL);
789 	}
790 
791 
792 	/*
793 	 * Turn around and call probe routine to see whether
794 	 * we actually have a tape at this SCSI nexus.
795 	 */
796 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
797 
798 		/*
799 		 * In checking the whole inq_dtype byte we are looking at both
800 		 * the Peripheral Qualifier and the Peripheral Device Type.
801 		 * For this driver we are only interested in sequential devices
802 		 * that are connected or capable if connecting to this logical
803 		 * unit.
804 		 */
805 		if (devp->sd_inq->inq_dtype ==
806 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
807 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
808 			    "probe exists\n");
809 			rval = DDI_PROBE_SUCCESS;
810 		} else {
811 			rval = DDI_PROBE_FAILURE;
812 		}
813 	} else {
814 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
815 		    "probe failure: nothing there\n");
816 		rval = DDI_PROBE_FAILURE;
817 	}
818 	scsi_unprobe(devp);
819 	return (rval);
820 }
821 
822 static int
823 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
824 {
825 	int 	instance;
826 	int	wide;
827 	int 	dev_instance;
828 	int	ret_status;
829 	struct	scsi_device *devp;
830 	int	node_ix;
831 	struct	scsi_tape *un;
832 
833 	ST_ENTR(devi, st_attach);
834 
835 	devp = ddi_get_driver_private(devi);
836 	instance = ddi_get_instance(devi);
837 
838 	switch (cmd) {
839 		case DDI_ATTACH:
840 			if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
841 			    "tape-command-recovery-disable", 0) != 0) {
842 				st_recov_sz = sizeof (pkt_info);
843 			}
844 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
845 				return (DDI_FAILURE);
846 			}
847 			break;
848 		case DDI_RESUME:
849 			/*
850 			 * Suspend/Resume
851 			 *
852 			 * When the driver suspended, there might be
853 			 * outstanding cmds and therefore we need to
854 			 * reset the suspended flag and resume the scsi
855 			 * watch thread and restart commands and timeouts
856 			 */
857 
858 			if (!(un = ddi_get_soft_state(st_state, instance))) {
859 				return (DDI_FAILURE);
860 			}
861 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
862 			    un->un_dev);
863 
864 			mutex_enter(ST_MUTEX);
865 
866 			un->un_throttle = un->un_max_throttle;
867 			un->un_tids_at_suspend = 0;
868 			un->un_pwr_mgmt = ST_PWR_NORMAL;
869 
870 			if (un->un_swr_token) {
871 				scsi_watch_resume(un->un_swr_token);
872 			}
873 
874 			/*
875 			 * Restart timeouts
876 			 */
877 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
878 				mutex_exit(ST_MUTEX);
879 				un->un_delay_tid = timeout(
880 				    st_delayed_cv_broadcast, un,
881 				    drv_usectohz((clock_t)
882 				    MEDIA_ACCESS_DELAY));
883 				mutex_enter(ST_MUTEX);
884 			}
885 
886 			if (un->un_tids_at_suspend & ST_HIB_TID) {
887 				mutex_exit(ST_MUTEX);
888 				un->un_hib_tid = timeout(st_intr_restart, un,
889 				    ST_STATUS_BUSY_TIMEOUT);
890 				mutex_enter(ST_MUTEX);
891 			}
892 
893 			ret_status = st_clear_unit_attentions(dev_instance, 5);
894 
895 			/*
896 			 * now check if we need to restore the tape position
897 			 */
898 			if ((un->un_suspend_pos.pmode != invalid) &&
899 			    ((un->un_suspend_pos.fileno > 0) ||
900 			    (un->un_suspend_pos.blkno > 0)) ||
901 			    (un->un_suspend_pos.lgclblkno > 0)) {
902 				if (ret_status != 0) {
903 					/*
904 					 * tape didn't get good TUR
905 					 * just print out error messages
906 					 */
907 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
908 					    "st_attach-RESUME: tape failure "
909 					    " tape position will be lost");
910 				} else {
911 					/* this prints errors */
912 					(void) st_validate_tapemarks(un,
913 					    st_uscsi_cmd, &un->un_suspend_pos);
914 				}
915 				/*
916 				 * there are no retries, if there is an error
917 				 * we don't know if the tape has changed
918 				 */
919 				un->un_suspend_pos.pmode = invalid;
920 			}
921 
922 			/* now we are ready to start up any queued I/Os */
923 			if (un->un_ncmds || un->un_quef) {
924 				st_start(un);
925 			}
926 
927 			cv_broadcast(&un->un_suspend_cv);
928 			mutex_exit(ST_MUTEX);
929 			return (DDI_SUCCESS);
930 
931 		default:
932 			return (DDI_FAILURE);
933 	}
934 
935 	un = ddi_get_soft_state(st_state, instance);
936 
937 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
938 	    "st_attach: instance=%x\n", instance);
939 
940 	/*
941 	 * Add a zero-length attribute to tell the world we support
942 	 * kernel ioctls (for layered drivers)
943 	 */
944 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
945 	    DDI_KERNEL_IOCTL, NULL, 0);
946 
947 	ddi_report_dev((dev_info_t *)devi);
948 
949 	/*
950 	 * If it's a SCSI-2 tape drive which supports wide,
951 	 * tell the host adapter to use wide.
952 	 */
953 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
954 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
955 
956 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
957 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
958 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
959 	}
960 
961 	/*
962 	 * enable autorequest sense; keep the rq packet around in case
963 	 * the autorequest sense fails because of a busy condition
964 	 * do a getcap first in case the capability is not variable
965 	 */
966 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
967 		un->un_arq_enabled = 1;
968 	} else {
969 		un->un_arq_enabled =
970 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
971 	}
972 
973 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
974 	    (un->un_arq_enabled ? "enabled" : "disabled"));
975 
976 	un->un_untagged_qing =
977 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
978 
979 	/*
980 	 * XXX - This is just for 2.6.  to tell users that write buffering
981 	 *	has gone away.
982 	 */
983 	if (un->un_arq_enabled && un->un_untagged_qing) {
984 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
985 		    "tape-driver-buffering", 0) != 0) {
986 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
987 			    "Write Data Buffering has been depricated. Your "
988 			    "applications should continue to work normally.\n"
989 			    " But, they should  ported to use Asynchronous "
990 			    " I/O\n"
991 			    " For more information, read about "
992 			    " tape-driver-buffering "
993 			    "property in the st(7d) man page\n");
994 		}
995 	}
996 
997 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
998 	un->un_flush_on_errors = 0;
999 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
1000 
1001 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
1002 	    "throttle=%x, max_throttle = %x\n",
1003 	    un->un_throttle, un->un_max_throttle);
1004 
1005 	/* initialize persistent errors to nil */
1006 	un->un_persistence = 0;
1007 	un->un_persist_errors = 0;
1008 
1009 	/*
1010 	 * Get dma-max from HBA driver. If it is not defined, use 64k
1011 	 */
1012 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
1013 	if (un->un_maxdma == -1) {
1014 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1015 		    "Received a value that looked like -1. Using 64k maxdma");
1016 		un->un_maxdma = (64 * ONE_K);
1017 	}
1018 
1019 #ifdef	__x86
1020 	/*
1021 	 * for x86, the device may be able to DMA more than the system will
1022 	 * allow under some circumstances. We need account for both the HBA's
1023 	 * and system's contraints.
1024 	 *
1025 	 * Get the maximum DMA under worse case conditions. e.g. looking at the
1026 	 * device constraints, the max copy buffer size, and the worse case
1027 	 * fragmentation. NOTE: this may differ from dma-max since dma-max
1028 	 * doesn't take the worse case framentation into account.
1029 	 *
1030 	 * e.g. a device may be able to DMA 16MBytes, but can only DMA 1MByte
1031 	 * if none of the pages are contiguous. Keeping track of both of these
1032 	 * values allows us to support larger tape block sizes on some devices.
1033 	 */
1034 	un->un_maxdma_arch = scsi_ifgetcap(&devp->sd_address, "dma-max-arch",
1035 	    1);
1036 
1037 	/*
1038 	 * If the dma-max-arch capability is not implemented, or the value
1039 	 * comes back higher than what was reported in dma-max, use dma-max.
1040 	 */
1041 	if ((un->un_maxdma_arch == -1) ||
1042 	    ((uint_t)un->un_maxdma < (uint_t)un->un_maxdma_arch)) {
1043 		un->un_maxdma_arch = un->un_maxdma;
1044 	}
1045 #endif
1046 
1047 	/*
1048 	 * Get the max allowable cdb size
1049 	 */
1050 	un->un_max_cdb_sz =
1051 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
1052 	if (un->un_max_cdb_sz < CDB_GROUP0) {
1053 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1054 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
1055 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
1056 	}
1057 
1058 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1059 
1060 	un->un_mediastate = MTIO_NONE;
1061 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1062 
1063 	/*
1064 	 * initialize kstats
1065 	 */
1066 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1067 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1068 	if (un->un_stats) {
1069 		un->un_stats->ks_lock = ST_MUTEX;
1070 		kstat_install(un->un_stats);
1071 	}
1072 	(void) st_create_errstats(un, instance);
1073 
1074 	/*
1075 	 * find the drive type for this target
1076 	 */
1077 	mutex_enter(ST_MUTEX);
1078 	un->un_dev = MT_TEM_DEV(instance);
1079 	st_known_tape_type(un);
1080 	un->un_dev = 0;
1081 	mutex_exit(ST_MUTEX);
1082 
1083 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
1084 		int minor;
1085 		char *name;
1086 
1087 		name  = st_minor_data[node_ix].name;
1088 		minor = st_minor_data[node_ix].minor;
1089 
1090 		/*
1091 		 * For default devices set the density to the
1092 		 * preferred default density for this device.
1093 		 */
1094 		if (node_ix <= DEF_BSD_NR) {
1095 			minor |= un->un_dp->default_density;
1096 		}
1097 		minor |= MTMINOR(instance);
1098 
1099 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
1100 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
1101 			continue;
1102 		}
1103 
1104 		ddi_remove_minor_node(devi, NULL);
1105 
1106 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1107 		    st_reset_notification, (caddr_t)un);
1108 		cv_destroy(&un->un_clscv);
1109 		cv_destroy(&un->un_sbuf_cv);
1110 		cv_destroy(&un->un_queue_cv);
1111 		cv_destroy(&un->un_state_cv);
1112 #ifdef	__x86
1113 		cv_destroy(&un->un_contig_mem_cv);
1114 #endif
1115 		cv_destroy(&un->un_suspend_cv);
1116 		cv_destroy(&un->un_tape_busy_cv);
1117 		cv_destroy(&un->un_recov_buf_cv);
1118 		if (un->un_recov_taskq) {
1119 			ddi_taskq_destroy(un->un_recov_taskq);
1120 		}
1121 		if (un->un_sbufp) {
1122 			freerbuf(un->un_sbufp);
1123 		}
1124 		if (un->un_recov_buf) {
1125 			freerbuf(un->un_recov_buf);
1126 		}
1127 		if (un->un_uscsi_rqs_buf) {
1128 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1129 		}
1130 		if (un->un_mspl) {
1131 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1132 		}
1133 		if (un->un_dp_size) {
1134 			kmem_free(un->un_dp, un->un_dp_size);
1135 		}
1136 		if (un->un_state) {
1137 			kstat_delete(un->un_stats);
1138 		}
1139 		if (un->un_errstats) {
1140 			kstat_delete(un->un_errstats);
1141 		}
1142 
1143 		scsi_destroy_pkt(un->un_rqs);
1144 		scsi_free_consistent_buf(un->un_rqs_bp);
1145 		ddi_soft_state_free(st_state, instance);
1146 		devp->sd_private = NULL;
1147 		devp->sd_sense = NULL;
1148 
1149 		ddi_prop_remove_all(devi);
1150 		return (DDI_FAILURE);
1151 	}
1152 
1153 	return (DDI_SUCCESS);
1154 }
1155 
1156 /*
1157  * st_detach:
1158  *
1159  * we allow a detach if and only if:
1160  *	- no tape is currently inserted
1161  *	- tape position is at BOT or unknown
1162  *		(if it is not at BOT then a no rewind
1163  *		device was opened and we have to preserve state)
1164  *	- it must be in a closed state : no timeouts or scsi_watch requests
1165  *		will exist if it is closed, so we don't need to check for
1166  *		them here.
1167  */
1168 /*ARGSUSED*/
1169 static int
1170 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1171 {
1172 	int 	instance;
1173 	struct scsi_device *devp;
1174 	struct scsi_tape *un;
1175 	clock_t wait_cmds_complete;
1176 
1177 	ST_ENTR(devi, st_detach);
1178 
1179 	instance = ddi_get_instance(devi);
1180 
1181 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1182 		return (DDI_FAILURE);
1183 	}
1184 
1185 	mutex_enter(ST_MUTEX);
1186 
1187 	/*
1188 	 * Clear error entry stack
1189 	 */
1190 	st_empty_error_stack(un);
1191 
1192 	mutex_exit(ST_MUTEX);
1193 
1194 	switch (cmd) {
1195 
1196 	case DDI_DETACH:
1197 		/*
1198 		 * Undo what we did in st_attach & st_doattach,
1199 		 * freeing resources and removing things we installed.
1200 		 * The system framework guarantees we are not active
1201 		 * with this devinfo node in any other entry points at
1202 		 * this time.
1203 		 */
1204 
1205 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1206 		    "st_detach: instance=%x, un=%p\n", instance,
1207 		    (void *)un);
1208 
1209 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1210 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1211 		    (un->un_state != ST_STATE_CLOSED)) {
1212 			/*
1213 			 * we cannot unload some targets because the
1214 			 * inquiry returns junk unless immediately
1215 			 * after a reset
1216 			 */
1217 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1218 			    "cannot unload instance %x\n", instance);
1219 			return (DDI_FAILURE);
1220 		}
1221 
1222 		/*
1223 		 * if the tape has been removed then we may unload;
1224 		 * do a test unit ready and if it returns NOT READY
1225 		 * then we assume that it is safe to unload.
1226 		 * as a side effect, pmode may be set to invalid if the
1227 		 * the test unit ready fails;
1228 		 * also un_state may be set to non-closed, so reset it
1229 		 */
1230 		if ((un->un_dev) &&		/* Been opened since attach */
1231 		    ((un->un_pos.pmode == legacy) &&
1232 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1233 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1234 		    ((un->un_pos.pmode == logical) &&
1235 		    (un->un_pos.lgclblkno > 0))) {
1236 			mutex_enter(ST_MUTEX);
1237 			/*
1238 			 * Send Test Unit Ready in the hopes that if
1239 			 * the drive is not in the state we think it is.
1240 			 * And the state will be changed so it can be detached.
1241 			 * If the command fails to reach the device and
1242 			 * the drive was not rewound or unloaded we want
1243 			 * to fail the detach till a user command fails
1244 			 * where after the detach will succead.
1245 			 */
1246 			(void) st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
1247 			/*
1248 			 * After TUR un_state may be set to non-closed,
1249 			 * so reset it back.
1250 			 */
1251 			un->un_state = ST_STATE_CLOSED;
1252 			mutex_exit(ST_MUTEX);
1253 		}
1254 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1255 		    "un_status=%x, fileno=%x, blkno=%x\n",
1256 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1257 
1258 		/*
1259 		 * check again:
1260 		 * if we are not at BOT then it is not safe to unload
1261 		 */
1262 		if ((un->un_dev) &&		/* Been opened since attach */
1263 		    (((un->un_pos.pmode == legacy) &&
1264 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1265 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1266 		    ((un->un_pos.pmode == logical) &&
1267 		    (un->un_pos.lgclblkno > 0)))) {
1268 
1269 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1270 			    "cannot detach: pmode=%d fileno=0x%x, blkno=0x%x"
1271 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1272 			    un->un_pos.fileno, un->un_pos.blkno,
1273 			    un->un_pos.lgclblkno);
1274 			return (DDI_FAILURE);
1275 		}
1276 
1277 		/*
1278 		 * Just To make sure that we have released the
1279 		 * tape unit .
1280 		 */
1281 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1282 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1283 			mutex_enter(ST_MUTEX);
1284 			(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
1285 			mutex_exit(ST_MUTEX);
1286 		}
1287 
1288 		/*
1289 		 * now remove other data structures allocated in st_doattach()
1290 		 */
1291 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1292 		    "destroying/freeing\n");
1293 
1294 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1295 		    st_reset_notification, (caddr_t)un);
1296 		cv_destroy(&un->un_clscv);
1297 		cv_destroy(&un->un_sbuf_cv);
1298 		cv_destroy(&un->un_queue_cv);
1299 		cv_destroy(&un->un_suspend_cv);
1300 		cv_destroy(&un->un_tape_busy_cv);
1301 		cv_destroy(&un->un_recov_buf_cv);
1302 
1303 		if (un->un_recov_taskq) {
1304 			ddi_taskq_destroy(un->un_recov_taskq);
1305 		}
1306 
1307 		if (un->un_hib_tid) {
1308 			(void) untimeout(un->un_hib_tid);
1309 			un->un_hib_tid = 0;
1310 		}
1311 
1312 		if (un->un_delay_tid) {
1313 			(void) untimeout(un->un_delay_tid);
1314 			un->un_delay_tid = 0;
1315 		}
1316 		cv_destroy(&un->un_state_cv);
1317 
1318 #ifdef	__x86
1319 		cv_destroy(&un->un_contig_mem_cv);
1320 
1321 		if (un->un_contig_mem_hdl != NULL) {
1322 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1323 		}
1324 #endif
1325 		if (un->un_sbufp) {
1326 			freerbuf(un->un_sbufp);
1327 		}
1328 		if (un->un_recov_buf) {
1329 			freerbuf(un->un_recov_buf);
1330 		}
1331 		if (un->un_uscsi_rqs_buf) {
1332 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1333 		}
1334 		if (un->un_mspl) {
1335 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1336 		}
1337 		if (un->un_rqs) {
1338 			scsi_destroy_pkt(un->un_rqs);
1339 			scsi_free_consistent_buf(un->un_rqs_bp);
1340 		}
1341 		if (un->un_mkr_pkt) {
1342 			scsi_destroy_pkt(un->un_mkr_pkt);
1343 		}
1344 		if (un->un_arq_enabled) {
1345 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1346 		}
1347 		if (un->un_dp_size) {
1348 			kmem_free(un->un_dp, un->un_dp_size);
1349 		}
1350 		if (un->un_stats) {
1351 			kstat_delete(un->un_stats);
1352 			un->un_stats = (kstat_t *)0;
1353 		}
1354 		if (un->un_errstats) {
1355 			kstat_delete(un->un_errstats);
1356 			un->un_errstats = (kstat_t *)0;
1357 		}
1358 		if (un->un_media_id_len) {
1359 			kmem_free(un->un_media_id, un->un_media_id_len);
1360 		}
1361 		devp = ST_SCSI_DEVP;
1362 		ddi_soft_state_free(st_state, instance);
1363 		devp->sd_private = NULL;
1364 		devp->sd_sense = NULL;
1365 		scsi_unprobe(devp);
1366 		ddi_prop_remove_all(devi);
1367 		ddi_remove_minor_node(devi, NULL);
1368 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1369 		return (DDI_SUCCESS);
1370 
1371 	case DDI_SUSPEND:
1372 
1373 		/*
1374 		 * Suspend/Resume
1375 		 *
1376 		 * To process DDI_SUSPEND, we must do the following:
1377 		 *
1378 		 *  - check ddi_removing_power to see if power will be turned
1379 		 *    off. if so, return DDI_FAILURE
1380 		 *  - check if we are already suspended,
1381 		 *    if so, return DDI_FAILURE
1382 		 *  - check if device state is CLOSED,
1383 		 *    if not, return DDI_FAILURE.
1384 		 *  - wait until outstanding operations complete
1385 		 *  - save tape state
1386 		 *  - block new operations
1387 		 *  - cancel pending timeouts
1388 		 *
1389 		 */
1390 
1391 		if (ddi_removing_power(devi)) {
1392 			return (DDI_FAILURE);
1393 		}
1394 		mutex_enter(ST_MUTEX);
1395 
1396 		/*
1397 		 * Shouldn't already be suspended, if so return failure
1398 		 */
1399 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1400 			mutex_exit(ST_MUTEX);
1401 			return (DDI_FAILURE);
1402 		}
1403 		if (un->un_state != ST_STATE_CLOSED) {
1404 			mutex_exit(ST_MUTEX);
1405 			return (DDI_FAILURE);
1406 		}
1407 
1408 		/*
1409 		 * Wait for all outstanding I/O's to complete
1410 		 *
1411 		 * we wait on both ncmds and the wait queue for times
1412 		 * when we are flushing after persistent errors are
1413 		 * flagged, which is when ncmds can be 0, and the
1414 		 * queue can still have I/O's.  This way we preserve
1415 		 * order of biodone's.
1416 		 */
1417 		wait_cmds_complete = ddi_get_lbolt();
1418 		wait_cmds_complete +=
1419 		    st_wait_cmds_complete * drv_usectohz(1000000);
1420 		while (un->un_ncmds || un->un_quef ||
1421 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1422 
1423 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1424 			    wait_cmds_complete) == -1) {
1425 				/*
1426 				 * Time expired then cancel the command
1427 				 */
1428 				if (st_reset(un, RESET_LUN) == 0) {
1429 					if (un->un_last_throttle) {
1430 						un->un_throttle =
1431 						    un->un_last_throttle;
1432 					}
1433 					mutex_exit(ST_MUTEX);
1434 					return (DDI_FAILURE);
1435 				} else {
1436 					break;
1437 				}
1438 			}
1439 		}
1440 
1441 		/*
1442 		 * DDI_SUSPEND says that the system "may" power down, we
1443 		 * remember the file and block number before rewinding.
1444 		 * we also need to save state before issuing
1445 		 * any WRITE_FILE_MARK command.
1446 		 */
1447 		(void) st_update_block_pos(un, st_cmd, 0);
1448 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1449 
1450 
1451 		/*
1452 		 * Issue a zero write file fmk command to tell the drive to
1453 		 * flush any buffered tape marks
1454 		 */
1455 		(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1456 
1457 		/*
1458 		 * Because not all tape drives correctly implement buffer
1459 		 * flushing with the zero write file fmk command, issue a
1460 		 * synchronous rewind command to force data flushing.
1461 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1462 		 * anyway.
1463 		 */
1464 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
1465 
1466 		/* stop any new operations */
1467 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1468 		un->un_throttle = 0;
1469 
1470 		/*
1471 		 * cancel any outstanding timeouts
1472 		 */
1473 		if (un->un_delay_tid) {
1474 			timeout_id_t temp_id = un->un_delay_tid;
1475 			un->un_delay_tid = 0;
1476 			un->un_tids_at_suspend |= ST_DELAY_TID;
1477 			mutex_exit(ST_MUTEX);
1478 			(void) untimeout(temp_id);
1479 			mutex_enter(ST_MUTEX);
1480 		}
1481 
1482 		if (un->un_hib_tid) {
1483 			timeout_id_t temp_id = un->un_hib_tid;
1484 			un->un_hib_tid = 0;
1485 			un->un_tids_at_suspend |= ST_HIB_TID;
1486 			mutex_exit(ST_MUTEX);
1487 			(void) untimeout(temp_id);
1488 			mutex_enter(ST_MUTEX);
1489 		}
1490 
1491 		/*
1492 		 * Suspend the scsi_watch_thread
1493 		 */
1494 		if (un->un_swr_token) {
1495 			opaque_t temp_token = un->un_swr_token;
1496 			mutex_exit(ST_MUTEX);
1497 			scsi_watch_suspend(temp_token);
1498 		} else {
1499 			mutex_exit(ST_MUTEX);
1500 		}
1501 
1502 		return (DDI_SUCCESS);
1503 
1504 	default:
1505 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1506 		return (DDI_FAILURE);
1507 	}
1508 }
1509 
1510 
1511 /* ARGSUSED */
1512 static int
1513 st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1514 {
1515 	dev_t dev;
1516 	struct scsi_tape *un;
1517 	int instance, error;
1518 
1519 	ST_ENTR(dip, st_info);
1520 
1521 	switch (infocmd) {
1522 	case DDI_INFO_DEVT2DEVINFO:
1523 		dev = (dev_t)arg;
1524 		instance = MTUNIT(dev);
1525 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1526 			return (DDI_FAILURE);
1527 		*result = (void *) ST_DEVINFO;
1528 		error = DDI_SUCCESS;
1529 		break;
1530 	case DDI_INFO_DEVT2INSTANCE:
1531 		dev = (dev_t)arg;
1532 		instance = MTUNIT(dev);
1533 		*result = (void *)(uintptr_t)instance;
1534 		error = DDI_SUCCESS;
1535 		break;
1536 	default:
1537 		error = DDI_FAILURE;
1538 	}
1539 	return (error);
1540 }
1541 
1542 static int
1543 st_doattach(struct scsi_device *devp, int (*canwait)())
1544 {
1545 	struct scsi_tape *un = NULL;
1546 	recov_info *ri;
1547 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1548 	int instance;
1549 	size_t rlen;
1550 
1551 	ST_FUNC(devp->sd_dev, st_doattach);
1552 	/*
1553 	 * Call the routine scsi_probe to do some of the dirty work.
1554 	 * If the INQUIRY command succeeds, the field sd_inq in the
1555 	 * device structure will be filled in.
1556 	 */
1557 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1558 	    "st_doattach(): probing\n");
1559 
1560 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1561 
1562 		/*
1563 		 * In checking the whole inq_dtype byte we are looking at both
1564 		 * the Peripheral Qualifier and the Peripheral Device Type.
1565 		 * For this driver we are only interested in sequential devices
1566 		 * that are connected or capable if connecting to this logical
1567 		 * unit.
1568 		 */
1569 		if (devp->sd_inq->inq_dtype ==
1570 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1571 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1572 			    "probe exists\n");
1573 		} else {
1574 			/* Something there but not a tape device */
1575 			scsi_unprobe(devp);
1576 			return (DDI_FAILURE);
1577 		}
1578 	} else {
1579 		/* Nothing there */
1580 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1581 		    "probe failure: nothing there\n");
1582 		scsi_unprobe(devp);
1583 		return (DDI_FAILURE);
1584 	}
1585 
1586 
1587 	/*
1588 	 * The actual unit is present.
1589 	 * Now is the time to fill in the rest of our info..
1590 	 */
1591 	instance = ddi_get_instance(devp->sd_dev);
1592 
1593 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1594 		goto error;
1595 	}
1596 	un = ddi_get_soft_state(st_state, instance);
1597 
1598 	ASSERT(un != NULL);
1599 
1600 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
1601 	    MAX_SENSE_LENGTH, B_READ, canwait, NULL);
1602 	if (un->un_rqs_bp == NULL) {
1603 		goto error;
1604 	}
1605 	un->un_rqs = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
1606 	    CDB_GROUP0, 1, st_recov_sz, PKT_CONSISTENT, canwait, NULL);
1607 	if (!un->un_rqs) {
1608 		goto error;
1609 	}
1610 	ASSERT(un->un_rqs->pkt_resid == 0);
1611 	devp->sd_sense =
1612 	    (struct scsi_extended_sense *)un->un_rqs_bp->b_un.b_addr;
1613 	ASSERT(geterror(un->un_rqs_bp) == NULL);
1614 
1615 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs->pkt_cdbp,
1616 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
1617 	FILL_SCSI1_LUN(devp, un->un_rqs);
1618 	un->un_rqs->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1619 	un->un_rqs->pkt_time = st_io_time;
1620 	un->un_rqs->pkt_comp = st_intr;
1621 	ri = (recov_info *)un->un_rqs->pkt_private;
1622 	if (st_recov_sz == sizeof (recov_info)) {
1623 		ri->privatelen = sizeof (recov_info);
1624 	} else {
1625 		ri->privatelen = sizeof (pkt_info);
1626 	}
1627 
1628 	un->un_sbufp = getrbuf(km_flags);
1629 	un->un_recov_buf = getrbuf(km_flags);
1630 
1631 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1632 
1633 	/*
1634 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1635 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1636 	 * is obsolete and we want more flexibility in controlling the DMA
1637 	 * address constraints.
1638 	 */
1639 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1640 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1641 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1642 
1643 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1644 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1645 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1646 
1647 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1648 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1649 		    "probe partial failure: no space\n");
1650 		goto error;
1651 	}
1652 
1653 	bzero(un->un_mspl, sizeof (struct seq_mode));
1654 
1655 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1656 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1657 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1658 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1659 #ifdef	__x86
1660 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1661 #endif
1662 
1663 	/* Initialize power managemnet condition variable */
1664 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1665 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1666 	cv_init(&un->un_recov_buf_cv, NULL, CV_DRIVER, NULL);
1667 
1668 	un->un_recov_taskq = ddi_taskq_create(devp->sd_dev,
1669 	    "un_recov_taskq", 1, TASKQ_DEFAULTPRI, km_flags);
1670 
1671 	ASSERT(un->un_recov_taskq != NULL);
1672 
1673 	un->un_pos.pmode = invalid;
1674 	un->un_sd	= devp;
1675 	un->un_swr_token = (opaque_t)NULL;
1676 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1677 	un->un_wormable = st_is_drive_worm;
1678 	un->un_media_id_method = st_get_media_identification;
1679 	/*
1680 	 * setting long a initial as it contains logical file info.
1681 	 * support for long format is mandatory but many drive don't do it.
1682 	 */
1683 	un->un_read_pos_type = LONG_POS;
1684 
1685 	un->un_suspend_pos.pmode = invalid;
1686 
1687 #ifdef	__x86
1688 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1689 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1690 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1691 		    "allocation of contiguous memory dma handle failed!");
1692 		un->un_contig_mem_hdl = NULL;
1693 		goto error;
1694 	}
1695 #endif
1696 
1697 	/*
1698 	 * Since this driver manages devices with "remote" hardware,
1699 	 * i.e. the devices themselves have no "reg" properties,
1700 	 * the SUSPEND/RESUME commands in detach/attach will not be
1701 	 * called by the power management framework unless we request
1702 	 * it by creating a "pm-hardware-state" property and setting it
1703 	 * to value "needs-suspend-resume".
1704 	 */
1705 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1706 	    "pm-hardware-state", "needs-suspend-resume") !=
1707 	    DDI_PROP_SUCCESS) {
1708 
1709 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1710 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1711 		goto error;
1712 	}
1713 
1714 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1715 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1716 
1717 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1718 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1719 		    "failed\n");
1720 		goto error;
1721 	}
1722 
1723 	(void) scsi_reset_notify(ROUTE, SCSI_RESET_NOTIFY,
1724 	    st_reset_notification, (caddr_t)un);
1725 
1726 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "attach success\n");
1727 	return (DDI_SUCCESS);
1728 
1729 error:
1730 	devp->sd_sense = NULL;
1731 
1732 	ddi_remove_minor_node(devp->sd_dev, NULL);
1733 	if (un) {
1734 		if (un->un_mspl) {
1735 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1736 		}
1737 		if (un->un_read_pos_data) {
1738 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1739 		}
1740 		if (un->un_sbufp) {
1741 			freerbuf(un->un_sbufp);
1742 		}
1743 		if (un->un_recov_buf) {
1744 			freerbuf(un->un_recov_buf);
1745 		}
1746 		if (un->un_uscsi_rqs_buf) {
1747 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1748 		}
1749 #ifdef	__x86
1750 		if (un->un_contig_mem_hdl != NULL) {
1751 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1752 		}
1753 #endif
1754 		if (un->un_rqs) {
1755 			scsi_destroy_pkt(un->un_rqs);
1756 		}
1757 
1758 		if (un->un_rqs_bp) {
1759 			scsi_free_consistent_buf(un->un_rqs_bp);
1760 		}
1761 
1762 		ddi_soft_state_free(st_state, instance);
1763 		devp->sd_private = NULL;
1764 	}
1765 
1766 	if (devp->sd_inq) {
1767 		scsi_unprobe(devp);
1768 	}
1769 	return (DDI_FAILURE);
1770 }
1771 
1772 typedef int
1773 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1774 
1775 static cfg_functp config_functs[] = {
1776 	st_get_conf_from_st_dot_conf,
1777 	st_get_conf_from_st_conf_dot_c,
1778 	st_get_conf_from_tape_drive,
1779 	st_get_default_conf
1780 };
1781 
1782 
1783 /*
1784  * determine tape type, using tape-config-list or built-in table or
1785  * use a generic tape config entry
1786  */
1787 static void
1788 st_known_tape_type(struct scsi_tape *un)
1789 {
1790 	struct st_drivetype *dp;
1791 	cfg_functp *config_funct;
1792 	uchar_t reserved;
1793 
1794 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1795 
1796 	reserved = (un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1797 	    : ST_RELEASE;
1798 
1799 	/*
1800 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1801 	 *	 no vid & pid inquiry data.  So, we provide one.
1802 	 */
1803 	if (ST_INQUIRY->inq_len == 0 ||
1804 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1805 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1806 	}
1807 
1808 	if (un->un_dp_size == 0) {
1809 		un->un_dp_size = sizeof (struct st_drivetype);
1810 		dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1811 		un->un_dp = dp;
1812 	} else {
1813 		dp = un->un_dp;
1814 	}
1815 
1816 	un->un_dp->non_motion_timeout = st_io_time;
1817 	/*
1818 	 * Loop through the configuration methods till one works.
1819 	 */
1820 	for (config_funct = &config_functs[0]; ; config_funct++) {
1821 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1822 			break;
1823 		}
1824 	}
1825 
1826 	/*
1827 	 * If we didn't just make up this configuration and
1828 	 * all the density codes are the same..
1829 	 * Set Auto Density over ride.
1830 	 */
1831 	if (*config_funct != st_get_default_conf) {
1832 		/*
1833 		 * If this device is one that is configured and all
1834 		 * densities are the same, This saves doing gets and set
1835 		 * that yield nothing.
1836 		 */
1837 		if ((dp->densities[0]) == (dp->densities[1]) &&
1838 		    (dp->densities[0]) == (dp->densities[2]) &&
1839 		    (dp->densities[0]) == (dp->densities[3])) {
1840 
1841 			dp->options |= ST_AUTODEN_OVERRIDE;
1842 		}
1843 	}
1844 
1845 
1846 	/*
1847 	 * Store tape drive characteristics.
1848 	 */
1849 	un->un_status = 0;
1850 	un->un_attached = 1;
1851 	un->un_init_options = dp->options;
1852 
1853 	/* setup operation time-outs based on options */
1854 	st_calculate_timeouts(un);
1855 
1856 	/* make sure if we are supposed to be variable, make it variable */
1857 	if (dp->options & ST_VARIABLE) {
1858 		dp->bsize = 0;
1859 	}
1860 
1861 	if (reserved != ((un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1862 	    : ST_RELEASE)) {
1863 		(void) st_reserve_release(un, reserved, st_uscsi_cmd);
1864 	}
1865 
1866 	un->un_unit_attention_flags = 1;
1867 
1868 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1869 
1870 }
1871 
1872 
1873 typedef struct {
1874 	int mask;
1875 	int bottom;
1876 	int top;
1877 	char *name;
1878 } conf_limit;
1879 
1880 static const conf_limit conf_limits[] = {
1881 
1882 	-1,		1,		2,		"conf version",
1883 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1884 	-1,		0,		0xffffff,	"block size",
1885 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1886 	-1,		0,		4,		"number of densities",
1887 	-1,		0,		UINT8_MAX,	"density code",
1888 	-1,		0,		3,		"default density",
1889 	-1,		0,		UINT16_MAX,	"non motion timeout",
1890 	-1,		0,		UINT16_MAX,	"I/O timeout",
1891 	-1,		0,		UINT16_MAX,	"space timeout",
1892 	-1,		0,		UINT16_MAX,	"load timeout",
1893 	-1,		0,		UINT16_MAX,	"unload timeout",
1894 	-1,		0,		UINT16_MAX,	"erase timeout",
1895 	0,		0,		0,		NULL
1896 };
1897 
1898 static int
1899 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1900     const char *conf_name)
1901 {
1902 	int dens;
1903 	int ndens;
1904 	int value;
1905 	int type;
1906 	int count;
1907 	const conf_limit *limit = &conf_limits[0];
1908 
1909 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1910 
1911 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1912 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1913 
1914 	count = list_len;
1915 	type = *list;
1916 	for (;  count && limit->name; count--, list++, limit++) {
1917 
1918 		value = *list;
1919 		if (value & ~limit->mask) {
1920 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1921 			    "%s %s value invalid bits set: 0x%X\n",
1922 			    conf_name, limit->name, value & ~limit->mask);
1923 			*list &= limit->mask;
1924 		} else if (value < limit->bottom) {
1925 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1926 			    "%s %s value too low: value = %d limit %d\n",
1927 			    conf_name, limit->name, value, limit->bottom);
1928 		} else if (value > limit->top) {
1929 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1930 			    "%s %s value too high: value = %d limit %d\n",
1931 			    conf_name, limit->name, value, limit->top);
1932 		} else {
1933 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1934 			    "%s %s value = 0x%X\n",
1935 			    conf_name, limit->name, value);
1936 		}
1937 
1938 		/* If not the number of densities continue */
1939 		if (limit != &conf_limits[4]) {
1940 			continue;
1941 		}
1942 
1943 		/* If number of densities is not in range can't use config */
1944 		if (value < limit->bottom || value > limit->top) {
1945 			return (-1);
1946 		}
1947 
1948 		ndens = min(value, NDENSITIES);
1949 		if ((type == 1) && (list_len - ndens) != 6) {
1950 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1951 			    "%s conf version 1 with %d densities has %d items"
1952 			    " should have %d",
1953 			    conf_name, ndens, list_len, 6 + ndens);
1954 		} else if ((type == 2) && (list_len - ndens) != 13) {
1955 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1956 			    "%s conf version 2 with %d densities has %d items"
1957 			    " should have %d",
1958 			    conf_name, ndens, list_len, 13 + ndens);
1959 		}
1960 
1961 		limit++;
1962 		for (dens = 0; dens < ndens && count; dens++) {
1963 			count--;
1964 			list++;
1965 			value = *list;
1966 			if (value < limit->bottom) {
1967 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1968 				    "%s density[%d] value too low: value ="
1969 				    " 0x%X limit 0x%X\n",
1970 				    conf_name, dens, value, limit->bottom);
1971 			} else if (value > limit->top) {
1972 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1973 				    "%s density[%d] value too high: value ="
1974 				    " 0x%X limit 0x%X\n",
1975 				    conf_name, dens, value, limit->top);
1976 			} else {
1977 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1978 				    "%s density[%d] value = 0x%X\n",
1979 				    conf_name, dens, value);
1980 			}
1981 		}
1982 	}
1983 
1984 	return (0);
1985 }
1986 
1987 static int
1988 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
1989     struct st_drivetype *dp)
1990 {
1991 	caddr_t config_list = NULL;
1992 	caddr_t data_list = NULL;
1993 	int	*data_ptr;
1994 	caddr_t vidptr, prettyptr, datanameptr;
1995 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
1996 	int config_list_len, data_list_len, len, i;
1997 	int version;
1998 	int found = 0;
1999 
2000 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
2001 
2002 	/*
2003 	 * Determine type of tape controller. Type is determined by
2004 	 * checking the vendor ids of the earlier inquiry command and
2005 	 * comparing those with vids in tape-config-list defined in st.conf
2006 	 */
2007 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
2008 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
2009 	    != DDI_PROP_SUCCESS) {
2010 		return (found);
2011 	}
2012 
2013 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2014 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
2015 
2016 	/*
2017 	 * Compare vids in each triplet - if it matches, get value for
2018 	 * data_name and contruct a st_drivetype struct
2019 	 * tripletlen is not set yet!
2020 	 */
2021 	for (len = config_list_len, vidptr = config_list;
2022 	    len > 0;
2023 	    vidptr += tripletlen, len -= tripletlen) {
2024 
2025 		vidlen = strlen(vidptr);
2026 		prettyptr = vidptr + vidlen + 1;
2027 		prettylen = strlen(prettyptr);
2028 		datanameptr = prettyptr + prettylen + 1;
2029 		datanamelen = strlen(datanameptr);
2030 		tripletlen = vidlen + prettylen + datanamelen + 3;
2031 
2032 		if (vidlen == 0) {
2033 			continue;
2034 		}
2035 
2036 		/*
2037 		 * If inquiry vid dosen't match this triplets vid,
2038 		 * try the next.
2039 		 */
2040 		if (strncasecmp(vidpid, vidptr, vidlen)) {
2041 			continue;
2042 		}
2043 
2044 		/*
2045 		 * if prettylen is zero then use the vid string
2046 		 */
2047 		if (prettylen == 0) {
2048 			prettyptr = vidptr;
2049 			prettylen = vidlen;
2050 		}
2051 
2052 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2053 		    "vid = %s, pretty=%s, dataname = %s\n",
2054 		    vidptr, prettyptr, datanameptr);
2055 
2056 		/*
2057 		 * get the data list
2058 		 */
2059 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
2060 		    datanameptr, (caddr_t)&data_list,
2061 		    &data_list_len) != DDI_PROP_SUCCESS) {
2062 			/*
2063 			 * Error in getting property value
2064 			 * print warning!
2065 			 */
2066 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2067 			    "data property (%s) has no value\n",
2068 			    datanameptr);
2069 			continue;
2070 		}
2071 
2072 		/*
2073 		 * now initialize the st_drivetype struct
2074 		 */
2075 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
2076 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
2077 		(void) strncpy(dp->vid, vidptr, dp->length);
2078 		data_ptr = (int *)data_list;
2079 		/*
2080 		 * check if data is enough for version, type,
2081 		 * bsize, options, # of densities, density1,
2082 		 * density2, ..., default_density
2083 		 */
2084 		if ((data_list_len < 5 * sizeof (int)) ||
2085 		    (data_list_len < 6 * sizeof (int) +
2086 		    *(data_ptr + 4) * sizeof (int))) {
2087 			/*
2088 			 * print warning and skip to next triplet.
2089 			 */
2090 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2091 			    "data property (%s) incomplete\n",
2092 			    datanameptr);
2093 			kmem_free(data_list, data_list_len);
2094 			continue;
2095 		}
2096 
2097 		if (st_validate_conf_data(un, data_ptr,
2098 		    data_list_len / sizeof (int), datanameptr)) {
2099 			kmem_free(data_list, data_list_len);
2100 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2101 			    "data property (%s) rejected\n",
2102 			    datanameptr);
2103 			continue;
2104 		}
2105 
2106 		/*
2107 		 * check version
2108 		 */
2109 		version = *data_ptr++;
2110 		if (version != 1 && version != 2) {
2111 			/* print warning but accept it */
2112 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2113 			    "Version # for data property (%s) "
2114 			    "not set to 1 or 2\n", datanameptr);
2115 		}
2116 
2117 		dp->type    = *data_ptr++;
2118 		dp->bsize   = *data_ptr++;
2119 		dp->options = *data_ptr++;
2120 		dp->options |= ST_DYNAMIC;
2121 		len = *data_ptr++;
2122 		for (i = 0; i < NDENSITIES; i++) {
2123 			if (i < len) {
2124 				dp->densities[i] = *data_ptr++;
2125 			}
2126 		}
2127 		dp->default_density = *data_ptr << 3;
2128 		if (version == 2 &&
2129 		    data_list_len >= (13 + len) * sizeof (int)) {
2130 			data_ptr++;
2131 			dp->non_motion_timeout	= *data_ptr++;
2132 			dp->io_timeout		= *data_ptr++;
2133 			dp->rewind_timeout	= *data_ptr++;
2134 			dp->space_timeout	= *data_ptr++;
2135 			dp->load_timeout	= *data_ptr++;
2136 			dp->unload_timeout	= *data_ptr++;
2137 			dp->erase_timeout	= *data_ptr++;
2138 		}
2139 		kmem_free(data_list, data_list_len);
2140 		found = 1;
2141 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2142 		    "found in st.conf: vid = %s, pretty=%s\n",
2143 		    dp->vid, dp->name);
2144 		break;
2145 	}
2146 
2147 	/*
2148 	 * free up the memory allocated by ddi_getlongprop
2149 	 */
2150 	if (config_list) {
2151 		kmem_free(config_list, config_list_len);
2152 	}
2153 	return (found);
2154 }
2155 
2156 static int
2157 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2158     struct st_drivetype *dp)
2159 {
2160 	int i;
2161 
2162 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2163 	/*
2164 	 * Determine type of tape controller.  Type is determined by
2165 	 * checking the result of the earlier inquiry command and
2166 	 * comparing vendor ids with strings in a table declared in st_conf.c.
2167 	 */
2168 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2169 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2170 
2171 	for (i = 0; i < st_ndrivetypes; i++) {
2172 		if (st_drivetypes[i].length == 0) {
2173 			continue;
2174 		}
2175 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2176 		    st_drivetypes[i].length)) {
2177 			continue;
2178 		}
2179 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2180 		return (1);
2181 	}
2182 	return (0);
2183 }
2184 
2185 static int
2186 st_get_conf_from_tape_drive(struct scsi_tape *un, char *vidpid,
2187     struct st_drivetype *dp)
2188 {
2189 	int bsize;
2190 	ulong_t maxbsize;
2191 	caddr_t buf;
2192 	struct st_drivetype *tem_dp;
2193 	struct read_blklim *blklim;
2194 	int rval;
2195 	int i;
2196 
2197 	ST_FUNC(ST_DEVINFO, st_get_conf_from_tape_drive);
2198 
2199 	/*
2200 	 * Determine the type of tape controller. Type is determined by
2201 	 * sending SCSI commands to tape drive and deriving the type from
2202 	 * the returned data.
2203 	 */
2204 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2205 	    "st_get_conf_from_tape_drive(): asking tape drive\n");
2206 
2207 	tem_dp = kmem_zalloc(sizeof (struct st_drivetype), KM_SLEEP);
2208 
2209 	/*
2210 	 * Make up a name
2211 	 */
2212 	bcopy(vidpid, tem_dp->name, VIDPIDLEN);
2213 	tem_dp->name[VIDPIDLEN] = '\0';
2214 	tem_dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2215 	(void) strncpy(tem_dp->vid, ST_INQUIRY->inq_vid, tem_dp->length);
2216 	/*
2217 	 * 'clean' vendor and product strings of non-printing chars
2218 	 */
2219 	for (i = 0; i < VIDPIDLEN - 1; i ++) {
2220 		if (tem_dp->name[i] < ' ' || tem_dp->name[i] > '~') {
2221 			tem_dp->name[i] = '.';
2222 		}
2223 	}
2224 
2225 	/*
2226 	 * MODE SENSE to determine block size.
2227 	 */
2228 	un->un_dp->options |= ST_MODE_SEL_COMP | ST_UNLOADABLE;
2229 	rval = st_modesense(un);
2230 	if (rval) {
2231 		if (rval == EACCES) {
2232 			un->un_dp->type = ST_TYPE_INVALID;
2233 			rval = 1;
2234 		} else {
2235 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
2236 			rval = 0;
2237 		}
2238 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2239 		    "st_get_conf_from_tape_drive(): fail to mode sense\n");
2240 		goto exit;
2241 	}
2242 
2243 	/* Can mode sense page 0x10 or 0xf */
2244 	tem_dp->options |= ST_MODE_SEL_COMP;
2245 	bsize = (un->un_mspl->high_bl << 16)	|
2246 	    (un->un_mspl->mid_bl << 8)		|
2247 	    (un->un_mspl->low_bl);
2248 
2249 	if (bsize == 0) {
2250 		tem_dp->options |= ST_VARIABLE;
2251 		tem_dp->bsize = 0;
2252 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
2253 		rval = st_change_block_size(un, 0);
2254 		if (rval) {
2255 			if (rval == EACCES) {
2256 				un->un_dp->type = ST_TYPE_INVALID;
2257 				rval = 1;
2258 			} else {
2259 				rval = 0;
2260 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2261 				    "st_get_conf_from_tape_drive(): "
2262 				    "Fixed record size is too large and"
2263 				    "cannot switch to variable record size");
2264 			}
2265 			goto exit;
2266 		}
2267 		tem_dp->options |= ST_VARIABLE;
2268 	} else {
2269 		rval = st_change_block_size(un, 0);
2270 		if (rval == 0) {
2271 			tem_dp->options |= ST_VARIABLE;
2272 			tem_dp->bsize = 0;
2273 		} else if (rval != EACCES) {
2274 			tem_dp->bsize = bsize;
2275 		} else {
2276 			un->un_dp->type = ST_TYPE_INVALID;
2277 			rval = 1;
2278 			goto exit;
2279 		}
2280 	}
2281 
2282 	/*
2283 	 * If READ BLOCk LIMITS works and upper block size limit is
2284 	 * more than 64K, ST_NO_RECSIZE_LIMIT is supported.
2285 	 */
2286 	blklim = kmem_zalloc(sizeof (struct read_blklim), KM_SLEEP);
2287 	rval = st_read_block_limits(un, blklim);
2288 	if (rval) {
2289 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2290 		    "st_get_conf_from_tape_drive(): "
2291 		    "fail to read block limits.\n");
2292 		rval = 0;
2293 		kmem_free(blklim, sizeof (struct read_blklim));
2294 		goto exit;
2295 	}
2296 	maxbsize = (blklim->max_hi << 16) +
2297 	    (blklim->max_mid << 8) + blklim->max_lo;
2298 	if (maxbsize > ST_MAXRECSIZE_VARIABLE) {
2299 		tem_dp->options |= ST_NO_RECSIZE_LIMIT;
2300 	}
2301 	kmem_free(blklim, sizeof (struct read_blklim));
2302 
2303 	/*
2304 	 * Inquiry VPD page 0xb0 to see if the tape drive supports WORM
2305 	 */
2306 	buf = kmem_zalloc(6, KM_SLEEP);
2307 	rval = st_get_special_inquiry(un, 6, buf, 0xb0);
2308 	if (rval) {
2309 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2310 		    "st_get_conf_from_tape_drive(): "
2311 		    "fail to read vitial inquiry.\n");
2312 		rval = 0;
2313 		kmem_free(buf, 6);
2314 		goto exit;
2315 	}
2316 	if (buf[4] & 1) {
2317 		tem_dp->options |= ST_WORMABLE;
2318 	}
2319 	kmem_free(buf, 6);
2320 
2321 	/* Assume BSD BSR KNOWS_EOD */
2322 	tem_dp->options |= ST_BSF | ST_BSR | ST_KNOWS_EOD | ST_UNLOADABLE;
2323 	tem_dp->max_rretries = -1;
2324 	tem_dp->max_wretries = -1;
2325 
2326 	/*
2327 	 * Decide the densities supported by tape drive by sending
2328 	 * REPORT DENSITY SUPPORT command.
2329 	 */
2330 	if (st_get_densities_from_tape_drive(un, tem_dp) == 0) {
2331 		goto exit;
2332 	}
2333 
2334 	/*
2335 	 * Decide the timeout values for several commands by sending
2336 	 * REPORT SUPPORTED OPERATION CODES command.
2337 	 */
2338 	rval = st_get_timeout_values_from_tape_drive(un, tem_dp);
2339 	if (rval == 0 || ((rval == 1) && (tem_dp->type == ST_TYPE_INVALID))) {
2340 		goto exit;
2341 	}
2342 
2343 	bcopy(tem_dp, dp, sizeof (struct st_drivetype));
2344 	rval = 1;
2345 
2346 exit:
2347 	un->un_status = KEY_NO_SENSE;
2348 	kmem_free(tem_dp, sizeof (struct st_drivetype));
2349 	return (rval);
2350 }
2351 
2352 static int
2353 st_get_densities_from_tape_drive(struct scsi_tape *un,
2354     struct st_drivetype *dp)
2355 {
2356 	int i, p;
2357 	size_t buflen;
2358 	ushort_t des_len;
2359 	uchar_t *den_header;
2360 	uchar_t num_den;
2361 	uchar_t den[NDENSITIES];
2362 	uchar_t deflt[NDENSITIES];
2363 	struct report_density_desc *den_desc;
2364 
2365 	ST_FUNC(ST_DEVINFO, st_get_densities_from_type_drive);
2366 
2367 	/*
2368 	 * Since we have no idea how many densitiy support entries
2369 	 * will be returned, we send the command firstly assuming
2370 	 * there is only one. Then we can decide the number of
2371 	 * entries by available density support length. If multiple
2372 	 * entries exist, we will resend the command with enough
2373 	 * buffer size.
2374 	 */
2375 	buflen = sizeof (struct report_density_header) +
2376 	    sizeof (struct report_density_desc);
2377 	den_header = kmem_zalloc(buflen, KM_SLEEP);
2378 	if (st_report_density_support(un, den_header, buflen) != 0) {
2379 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2380 		    "st_get_conf_from_tape_drive(): fail to report density.\n");
2381 		kmem_free(den_header, buflen);
2382 		return (0);
2383 	}
2384 	des_len =
2385 	    BE_16(((struct report_density_header *)den_header)->ava_dens_len);
2386 	num_den = (des_len - 2) / sizeof (struct report_density_desc);
2387 
2388 	if (num_den > 1) {
2389 		kmem_free(den_header, buflen);
2390 		buflen = sizeof (struct report_density_header) +
2391 		    sizeof (struct report_density_desc) * num_den;
2392 		den_header = kmem_zalloc(buflen, KM_SLEEP);
2393 		if (st_report_density_support(un, den_header, buflen) != 0) {
2394 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2395 			    "st_get_conf_from_tape_drive(): "
2396 			    "fail to report density.\n");
2397 			kmem_free(den_header, buflen);
2398 			return (0);
2399 		}
2400 	}
2401 
2402 	den_desc = (struct report_density_desc *)(den_header
2403 	    + sizeof (struct report_density_header));
2404 
2405 	/*
2406 	 * Decide the drive type by assigning organization
2407 	 */
2408 	for (i = 0; i < ST_NUM_MEMBERS(st_vid_dt); i ++) {
2409 		if (strncmp(st_vid_dt[i].vid, (char *)(den_desc->ass_org),
2410 		    8) == 0) {
2411 			dp->type = st_vid_dt[i].type;
2412 			break;
2413 		}
2414 	}
2415 	if (i == ST_NUM_MEMBERS(st_vid_dt)) {
2416 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2417 		    "st_get_conf_from_tape_drive(): "
2418 		    "can't find match of assigned ort.\n");
2419 		kmem_free(den_header, buflen);
2420 		return (0);
2421 	}
2422 
2423 	/*
2424 	 * The tape drive may support many tape formats, but the st driver
2425 	 * supports only the four highest densities. Since density code
2426 	 * values are returned by ascending sequence, we start from the
2427 	 * last entry of density support data block descriptor.
2428 	 */
2429 	p = 0;
2430 	den_desc += num_den - 1;
2431 	for (i = 0; i < num_den && p < NDENSITIES; i ++, den_desc --) {
2432 		if ((den_desc->pri_den != 0) && (den_desc->wrtok)) {
2433 			if (p != 0) {
2434 				if (den_desc->pri_den >= den[p - 1]) {
2435 					continue;
2436 				}
2437 			}
2438 			den[p] = den_desc->pri_den;
2439 			deflt[p] = den_desc->deflt;
2440 			p ++;
2441 		}
2442 	}
2443 
2444 	switch (p) {
2445 	case 0:
2446 		bzero(dp->densities, NDENSITIES);
2447 		dp->options |= ST_AUTODEN_OVERRIDE;
2448 		dp->default_density = MT_DENSITY4;
2449 		break;
2450 
2451 	case 1:
2452 		(void) memset(dp->densities, den[0], NDENSITIES);
2453 		dp->options |= ST_AUTODEN_OVERRIDE;
2454 		dp->default_density = MT_DENSITY4;
2455 		break;
2456 
2457 	case 2:
2458 		dp->densities[0] = den[1];
2459 		dp->densities[1] = den[1];
2460 		dp->densities[2] = den[0];
2461 		dp->densities[3] = den[0];
2462 		if (deflt[0]) {
2463 			dp->default_density = MT_DENSITY4;
2464 		} else {
2465 			dp->default_density = MT_DENSITY2;
2466 		}
2467 		break;
2468 
2469 	case 3:
2470 		dp->densities[0] = den[2];
2471 		dp->densities[1] = den[1];
2472 		dp->densities[2] = den[0];
2473 		dp->densities[3] = den[0];
2474 		if (deflt[0]) {
2475 			dp->default_density = MT_DENSITY4;
2476 		} else if (deflt[1]) {
2477 			dp->default_density = MT_DENSITY2;
2478 		} else {
2479 			dp->default_density = MT_DENSITY1;
2480 		}
2481 		break;
2482 
2483 	default:
2484 		for (i = p; i > p - NDENSITIES; i --) {
2485 			dp->densities[i - 1] = den[p - i];
2486 		}
2487 		if (deflt[0]) {
2488 			dp->default_density = MT_DENSITY4;
2489 		} else if (deflt[1]) {
2490 			dp->default_density = MT_DENSITY3;
2491 		} else if (deflt[2]) {
2492 			dp->default_density = MT_DENSITY2;
2493 		} else {
2494 			dp->default_density = MT_DENSITY1;
2495 		}
2496 		break;
2497 	}
2498 
2499 	bzero(dp->mediatype, NDENSITIES);
2500 
2501 	kmem_free(den_header, buflen);
2502 	return (1);
2503 }
2504 
2505 static int
2506 st_get_timeout_values_from_tape_drive(struct scsi_tape *un,
2507     struct st_drivetype *dp)
2508 {
2509 	ushort_t timeout;
2510 	int rval;
2511 
2512 	ST_FUNC(ST_DEVINFO, st_get_timeout_values_from_type_drive);
2513 
2514 	rval = st_get_timeouts_value(un, SCMD_ERASE, &timeout, 0);
2515 	if (rval) {
2516 		if (rval == EACCES) {
2517 			un->un_dp->type = ST_TYPE_INVALID;
2518 			dp->type = ST_TYPE_INVALID;
2519 			return (1);
2520 		}
2521 		return (0);
2522 	}
2523 	dp->erase_timeout = timeout;
2524 
2525 	rval = st_get_timeouts_value(un, SCMD_READ, &timeout, 0);
2526 	if (rval) {
2527 		if (rval == EACCES) {
2528 			un->un_dp->type = ST_TYPE_INVALID;
2529 			dp->type = ST_TYPE_INVALID;
2530 			return (1);
2531 		}
2532 		return (0);
2533 	}
2534 	dp->io_timeout = timeout;
2535 
2536 	rval = st_get_timeouts_value(un, SCMD_WRITE, &timeout, 0);
2537 	if (rval) {
2538 		if (rval == EACCES) {
2539 			un->un_dp->type = ST_TYPE_INVALID;
2540 			dp->type = ST_TYPE_INVALID;
2541 			return (1);
2542 		}
2543 		return (0);
2544 	}
2545 	dp->io_timeout = max(dp->io_timeout, timeout);
2546 
2547 	rval = st_get_timeouts_value(un, SCMD_SPACE, &timeout, 0);
2548 	if (rval) {
2549 		if (rval == EACCES) {
2550 			un->un_dp->type = ST_TYPE_INVALID;
2551 			dp->type = ST_TYPE_INVALID;
2552 			return (1);
2553 		}
2554 		return (0);
2555 	}
2556 	dp->space_timeout = timeout;
2557 
2558 	rval = st_get_timeouts_value(un, SCMD_LOAD, &timeout, 0);
2559 	if (rval) {
2560 		if (rval == EACCES) {
2561 			un->un_dp->type = ST_TYPE_INVALID;
2562 			dp->type = ST_TYPE_INVALID;
2563 			return (1);
2564 		}
2565 		return (0);
2566 	}
2567 	dp->load_timeout = timeout;
2568 	dp->unload_timeout = timeout;
2569 
2570 	rval = st_get_timeouts_value(un, SCMD_REWIND, &timeout, 0);
2571 	if (rval) {
2572 		if (rval == EACCES) {
2573 			un->un_dp->type = ST_TYPE_INVALID;
2574 			dp->type = ST_TYPE_INVALID;
2575 			return (1);
2576 		}
2577 		return (0);
2578 	}
2579 	dp->rewind_timeout = timeout;
2580 
2581 	rval = st_get_timeouts_value(un, SCMD_INQUIRY, &timeout, 0);
2582 	if (rval) {
2583 		if (rval == EACCES) {
2584 			un->un_dp->type = ST_TYPE_INVALID;
2585 			dp->type = ST_TYPE_INVALID;
2586 			return (1);
2587 		}
2588 		return (0);
2589 	}
2590 	dp->non_motion_timeout = timeout;
2591 
2592 	return (1);
2593 }
2594 
2595 static int
2596 st_get_timeouts_value(struct scsi_tape *un, uchar_t option_code,
2597     ushort_t *timeout_value, ushort_t service_action)
2598 {
2599 	uchar_t *timeouts;
2600 	uchar_t *oper;
2601 	uchar_t support;
2602 	uchar_t cdbsize;
2603 	uchar_t ctdp;
2604 	size_t buflen;
2605 	int rval;
2606 
2607 	ST_FUNC(ST_DEVINFO, st_get_timeouts_value);
2608 
2609 	buflen = sizeof (struct one_com_des) +
2610 	    sizeof (struct com_timeout_des);
2611 	oper = kmem_zalloc(buflen, KM_SLEEP);
2612 	rval = st_report_supported_operation(un, oper, option_code,
2613 	    service_action);
2614 
2615 	if (rval) {
2616 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2617 		    "st_get_timeouts_value(): "
2618 		    "fail to timeouts value for command %d.\n", option_code);
2619 		kmem_free(oper, buflen);
2620 		return (rval);
2621 	}
2622 
2623 	support = ((struct one_com_des *)oper)->support;
2624 	if ((support != SUPPORT_VALUES_SUPPORT_SCSI) &&
2625 	    (support != SUPPORT_VALUES_SUPPORT_VENDOR)) {
2626 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2627 		    "st_get_timeouts_value(): "
2628 		    "command %d is not supported.\n", option_code);
2629 		kmem_free(oper, buflen);
2630 		return (ENOTSUP);
2631 	}
2632 
2633 	ctdp = ((struct one_com_des *)oper)->ctdp;
2634 	if (!ctdp) {
2635 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2636 		    "st_get_timeouts_value(): "
2637 		    "command timeout is not included.\n");
2638 		kmem_free(oper, buflen);
2639 		return (ENOTSUP);
2640 	}
2641 
2642 	cdbsize = BE_16(((struct one_com_des *)oper)->cdb_size);
2643 	timeouts = (uchar_t *)(oper + cdbsize + 4);
2644 
2645 	/*
2646 	 * Timeout value in seconds is 4 bytes, but we only support the lower 2
2647 	 * bytes. If the higher 2 bytes are not zero, the timeout value is set
2648 	 * to 0xFFFF.
2649 	 */
2650 	if (*(timeouts + 8) != 0 || *(timeouts + 9) != 0) {
2651 		*timeout_value = USHRT_MAX;
2652 	} else {
2653 		*timeout_value = ((*(timeouts + 10)) << 8) |
2654 		    (*(timeouts + 11));
2655 	}
2656 
2657 	kmem_free(oper, buflen);
2658 	return (0);
2659 }
2660 
2661 static int
2662 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2663 {
2664 	int i;
2665 
2666 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2667 
2668 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2669 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2670 
2671 	/*
2672 	 * Make up a name
2673 	 */
2674 	bcopy("Vendor '", dp->name, 8);
2675 	bcopy(vidpid, &dp->name[8], VIDLEN);
2676 	bcopy("' Product '", &dp->name[16], 11);
2677 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2678 	dp->name[ST_NAMESIZE - 2] = '\'';
2679 	dp->name[ST_NAMESIZE - 1] = '\0';
2680 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2681 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2682 	/*
2683 	 * 'clean' vendor and product strings of non-printing chars
2684 	 */
2685 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2686 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2687 			dp->name[i] = '.';
2688 		}
2689 	}
2690 	dp->type = ST_TYPE_INVALID;
2691 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2692 
2693 	return (1); /* Can Not Fail */
2694 }
2695 
2696 /*
2697  * Regular Unix Entry points
2698  */
2699 
2700 
2701 
2702 /* ARGSUSED */
2703 static int
2704 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2705 {
2706 	dev_t dev = *dev_p;
2707 	int rval = 0;
2708 
2709 	GET_SOFT_STATE(dev);
2710 
2711 	ST_ENTR(ST_DEVINFO, st_open);
2712 
2713 	/*
2714 	 * validate that we are addressing a sensible unit
2715 	 */
2716 	mutex_enter(ST_MUTEX);
2717 
2718 #ifdef	STDEBUG
2719 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2720 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2721 	    st_dev_name(dev), *dev_p, flag, otyp);
2722 #endif
2723 
2724 	/*
2725 	 * All device accesss go thru st_strategy() where we check
2726 	 * suspend status
2727 	 */
2728 
2729 	if (!un->un_attached) {
2730 		st_known_tape_type(un);
2731 		if (!un->un_attached) {
2732 			rval = ENXIO;
2733 			goto exit;
2734 		}
2735 
2736 	}
2737 
2738 	/*
2739 	 * Check for the case of the tape in the middle of closing.
2740 	 * This isn't simply a check of the current state, because
2741 	 * we could be in state of sensing with the previous state
2742 	 * that of closing.
2743 	 *
2744 	 * And don't allow multiple opens.
2745 	 */
2746 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2747 		un->un_laststate = un->un_state;
2748 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2749 		while (IS_CLOSING(un) ||
2750 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2751 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2752 				rval = EINTR;
2753 				un->un_state = un->un_laststate;
2754 				goto exit;
2755 			}
2756 		}
2757 	} else if (un->un_state != ST_STATE_CLOSED) {
2758 		rval = EBUSY;
2759 		goto busy;
2760 	}
2761 
2762 	/*
2763 	 * record current dev
2764 	 */
2765 	un->un_dev = dev;
2766 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2767 	un->un_errno = 0;	/* no errors yet */
2768 	un->un_restore_pos = 0;
2769 	un->un_rqs_state = 0;
2770 
2771 	/*
2772 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2773 	 * anything, leave internal states alone, if fileno >= 0
2774 	 */
2775 	if (flag & (FNDELAY | FNONBLOCK)) {
2776 		switch (un->un_pos.pmode) {
2777 
2778 		case invalid:
2779 			un->un_state = ST_STATE_OFFLINE;
2780 			break;
2781 
2782 		case legacy:
2783 			/*
2784 			 * If position is anything other than rewound.
2785 			 */
2786 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2787 				/*
2788 				 * set un_read_only/write-protect status.
2789 				 *
2790 				 * If the tape is not bot we can assume
2791 				 * that mspl->wp_status is set properly.
2792 				 * else
2793 				 * we need to do a mode sense/Tur once
2794 				 * again to get the actual tape status.(since
2795 				 * user might have replaced the tape)
2796 				 * Hence make the st state OFFLINE so that
2797 				 * we re-intialize the tape once again.
2798 				 */
2799 				un->un_read_only =
2800 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2801 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2802 			} else {
2803 				un->un_state = ST_STATE_OFFLINE;
2804 			}
2805 			break;
2806 		case logical:
2807 			if (un->un_pos.lgclblkno == 0) {
2808 				un->un_state = ST_STATE_OFFLINE;
2809 			} else {
2810 				un->un_read_only =
2811 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2812 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2813 			}
2814 			break;
2815 		}
2816 		rval = 0;
2817 	} else {
2818 		/*
2819 		 * Not opening O_NDELAY.
2820 		 */
2821 		un->un_state = ST_STATE_OPENING;
2822 
2823 		/*
2824 		 * Clear error entry stack
2825 		 */
2826 		st_empty_error_stack(un);
2827 
2828 		rval = st_tape_init(un);
2829 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2830 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2831 			rval = 0; /* so open doesn't fail */
2832 		} else if (rval) {
2833 			/*
2834 			 * Release the tape unit, if reserved and not
2835 			 * preserve reserve.
2836 			 */
2837 			if ((un->un_rsvd_status &
2838 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2839 				(void) st_reserve_release(un, ST_RELEASE,
2840 				    st_uscsi_cmd);
2841 			}
2842 		} else {
2843 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2844 		}
2845 	}
2846 
2847 exit:
2848 	/*
2849 	 * we don't want any uninvited guests scrogging our data when we're
2850 	 * busy with something, so for successful opens or failed opens
2851 	 * (except for EBUSY), reset these counters and state appropriately.
2852 	 */
2853 	if (rval != EBUSY) {
2854 		if (rval) {
2855 			un->un_state = ST_STATE_CLOSED;
2856 		}
2857 		un->un_err_resid = 0;
2858 		un->un_retry_ct = 0;
2859 		un->un_tran_retry_ct = 0;
2860 	}
2861 busy:
2862 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2863 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2864 	mutex_exit(ST_MUTEX);
2865 	return (rval);
2866 
2867 }
2868 
2869 static int
2870 st_tape_init(struct scsi_tape *un)
2871 {
2872 	int err;
2873 	int rval = 0;
2874 
2875 	ST_FUNC(ST_DEVINFO, st_tape_init);
2876 
2877 	ASSERT(mutex_owned(ST_MUTEX));
2878 
2879 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2880 	    "st_tape_init(un = 0x%p, oflags = %d)\n", (void*)un, un->un_oflags);
2881 
2882 	/*
2883 	 * Clean up after any errors left by 'last' close.
2884 	 * This also handles the case of the initial open.
2885 	 */
2886 	if (un->un_state != ST_STATE_INITIALIZING) {
2887 		un->un_laststate = un->un_state;
2888 		un->un_state = ST_STATE_OPENING;
2889 	}
2890 
2891 	un->un_kbytes_xferred = 0;
2892 
2893 	/*
2894 	 * do a throw away TUR to clear check condition
2895 	 */
2896 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2897 
2898 	/*
2899 	 * If test unit ready fails because the drive is reserved
2900 	 * by another host fail the open for no access.
2901 	 */
2902 	if (err) {
2903 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2904 			un->un_state = ST_STATE_CLOSED;
2905 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2906 			    "st_tape_init: RESERVATION CONFLICT\n");
2907 			rval = EACCES;
2908 			goto exit;
2909 		}
2910 	}
2911 
2912 	/*
2913 	 * Tape self identification could fail if the tape drive is used by
2914 	 * another host during attach time. We try to get the tape type
2915 	 * again. This is also applied to any posponed configuration methods.
2916 	 */
2917 	if (un->un_dp->type == ST_TYPE_INVALID) {
2918 		un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
2919 		st_known_tape_type(un);
2920 	}
2921 
2922 	/*
2923 	 * If the tape type is still invalid, try to determine the generic
2924 	 * configuration.
2925 	 */
2926 	if (un->un_dp->type == ST_TYPE_INVALID) {
2927 		rval = st_determine_generic(un);
2928 		if (rval) {
2929 			if (rval != EACCES) {
2930 				rval = EIO;
2931 			}
2932 			un->un_state = ST_STATE_CLOSED;
2933 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2934 			    "st_tape_init: %s invalid type\n",
2935 			    rval == EACCES ? "EACCES" : "EIO");
2936 			goto exit;
2937 		}
2938 		/*
2939 		 * If this is a Unknown Type drive,
2940 		 * Use the READ BLOCK LIMITS to determine if
2941 		 * allow large xfer is approprate if not globally
2942 		 * disabled with st_allow_large_xfer.
2943 		 */
2944 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
2945 	} else {
2946 
2947 		/*
2948 		 * If we allow_large_xfer (ie >64k) and have not yet found out
2949 		 * the max block size supported by the drive,
2950 		 * find it by issueing a READ_BLKLIM command.
2951 		 * if READ_BLKLIM cmd fails, assume drive doesn't
2952 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
2953 		 */
2954 		un->un_allow_large_xfer = st_allow_large_xfer &&
2955 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
2956 	}
2957 	/*
2958 	 * if maxbsize is unknown, set the maximum block size.
2959 	 */
2960 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
2961 
2962 		/*
2963 		 * Get the Block limits of the tape drive.
2964 		 * if un->un_allow_large_xfer = 0 , then make sure
2965 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
2966 		 */
2967 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
2968 
2969 		err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2970 		if (err) {
2971 			/* Retry */
2972 			err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2973 		}
2974 		if (!err) {
2975 
2976 			/*
2977 			 * if cmd successful, use limit returned
2978 			 */
2979 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
2980 			    (un->un_rbl->max_mid << 8) +
2981 			    un->un_rbl->max_lo;
2982 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
2983 			    un->un_rbl->min_lo;
2984 			un->un_data_mod = 1 << un->un_rbl->granularity;
2985 			if ((un->un_maxbsize == 0) ||
2986 			    (un->un_allow_large_xfer == 0 &&
2987 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
2988 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2989 
2990 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
2991 				/*
2992 				 * Drive is not one that is configured, But the
2993 				 * READ BLOCK LIMITS tells us it can do large
2994 				 * xfers.
2995 				 */
2996 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
2997 					un->un_dp->options |=
2998 					    ST_NO_RECSIZE_LIMIT;
2999 				}
3000 				/*
3001 				 * If max and mimimum block limits are the
3002 				 * same this is a fixed block size device.
3003 				 */
3004 				if (un->un_maxbsize == un->un_minbsize) {
3005 					un->un_dp->options &= ~ST_VARIABLE;
3006 				}
3007 			}
3008 
3009 			if (un->un_minbsize == 0) {
3010 				un->un_minbsize = 1;
3011 			}
3012 
3013 		} else { /* error on read block limits */
3014 
3015 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3016 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
3017 			    " errno = %d un_rsvd_status = 0x%X\n",
3018 			    err, un->un_rsvd_status);
3019 
3020 			/*
3021 			 * since read block limits cmd failed,
3022 			 * do not allow large xfers.
3023 			 * use old values in st_minphys
3024 			 */
3025 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
3026 				rval = EACCES;
3027 			} else {
3028 				un->un_allow_large_xfer = 0;
3029 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3030 				    "!Disabling large transfers\n");
3031 
3032 				/*
3033 				 * we guess maxbsize and minbsize
3034 				 */
3035 				if (un->un_bsize) {
3036 					un->un_maxbsize = un->un_minbsize =
3037 					    un->un_bsize;
3038 				} else {
3039 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3040 					un->un_minbsize = 1;
3041 				}
3042 				/*
3043 				 * Data Mod must be set,
3044 				 * Even if read block limits fails.
3045 				 * Prevents Divide By Zero in st_rw().
3046 				 */
3047 				un->un_data_mod = 1;
3048 			}
3049 		}
3050 		if (un->un_rbl) {
3051 			kmem_free(un->un_rbl, RBLSIZE);
3052 			un->un_rbl = NULL;
3053 		}
3054 
3055 		if (rval) {
3056 			goto exit;
3057 		}
3058 	}
3059 
3060 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3061 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
3062 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
3063 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
3064 
3065 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
3066 
3067 	if (err != 0) {
3068 		if (err == EINTR) {
3069 			un->un_laststate = un->un_state;
3070 			un->un_state = ST_STATE_CLOSED;
3071 			rval = EINTR;
3072 			goto exit;
3073 		}
3074 		/*
3075 		 * Make sure the tape is ready
3076 		 */
3077 		un->un_pos.pmode = invalid;
3078 		if (un->un_status != KEY_UNIT_ATTENTION) {
3079 			/*
3080 			 * allow open no media.  Subsequent MTIOCSTATE
3081 			 * with media present will complete the open
3082 			 * logic.
3083 			 */
3084 			un->un_laststate = un->un_state;
3085 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
3086 				un->un_mediastate = MTIO_EJECTED;
3087 				un->un_state = ST_STATE_OFFLINE;
3088 				rval = 0;
3089 				goto exit;
3090 			} else {
3091 				un->un_state = ST_STATE_CLOSED;
3092 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3093 				    "st_tape_init EIO no media, not opened "
3094 				    "O_NONBLOCK|O_EXCL\n");
3095 				rval = EIO;
3096 				goto exit;
3097 			}
3098 		}
3099 	}
3100 
3101 	/*
3102 	 * On each open, initialize block size from drivetype struct,
3103 	 * as it could have been changed by MTSRSZ ioctl.
3104 	 * Now, ST_VARIABLE simply means drive is capable of variable
3105 	 * mode. All drives are assumed to support fixed records.
3106 	 * Hence, un_bsize tells what mode the drive is in.
3107 	 *	un_bsize	= 0	- variable record length
3108 	 *			= x	- fixed record length is x
3109 	 */
3110 	un->un_bsize = un->un_dp->bsize;
3111 
3112 	/*
3113 	 * If saved position is valid go there
3114 	 */
3115 	if (un->un_restore_pos) {
3116 		un->un_restore_pos = 0;
3117 		un->un_pos.fileno = un->un_save_fileno;
3118 		un->un_pos.blkno = un->un_save_blkno;
3119 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &un->un_pos);
3120 		if (rval != 0) {
3121 			if (rval != EACCES) {
3122 				rval = EIO;
3123 			}
3124 			un->un_laststate = un->un_state;
3125 			un->un_state = ST_STATE_CLOSED;
3126 			goto exit;
3127 		}
3128 	}
3129 
3130 	if (un->un_pos.pmode == invalid) {
3131 		rval = st_loadtape(un);
3132 		if (rval) {
3133 			if (rval != EACCES) {
3134 				rval = EIO;
3135 			}
3136 			un->un_laststate = un->un_state;
3137 			un->un_state = ST_STATE_CLOSED;
3138 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3139 			    "st_tape_init: %s can't open tape\n",
3140 			    rval == EACCES ? "EACCES" : "EIO");
3141 			goto exit;
3142 		}
3143 	}
3144 
3145 	/*
3146 	 * do a mode sense to pick up state of current write-protect,
3147 	 * Could cause reserve and fail due to conflict.
3148 	 */
3149 	if (un->un_unit_attention_flags) {
3150 		rval = st_modesense(un);
3151 		if (rval == EACCES) {
3152 			goto exit;
3153 		}
3154 	}
3155 
3156 	/*
3157 	 * If we are opening the tape for writing, check
3158 	 * to make sure that the tape can be written.
3159 	 */
3160 	if (un->un_oflags & FWRITE) {
3161 		err = 0;
3162 		if (un->un_mspl->wp) {
3163 			un->un_status = KEY_WRITE_PROTECT;
3164 			un->un_laststate = un->un_state;
3165 			un->un_state = ST_STATE_CLOSED;
3166 			rval = EACCES;
3167 			/*
3168 			 * STK sets the wp bit if volsafe tape is loaded.
3169 			 */
3170 			if ((un->un_dp->type == MT_ISSTK9840) &&
3171 			    (un->un_dp->options & ST_WORMABLE)) {
3172 				un->un_read_only = RDONLY;
3173 			} else {
3174 				goto exit;
3175 			}
3176 		} else {
3177 			un->un_read_only = RDWR;
3178 		}
3179 	} else {
3180 		un->un_read_only = RDONLY;
3181 	}
3182 
3183 	if (un->un_dp->options & ST_WORMABLE &&
3184 	    un->un_unit_attention_flags) {
3185 		un->un_read_only |= un->un_wormable(un);
3186 
3187 		if (((un->un_read_only == WORM) ||
3188 		    (un->un_read_only == RDWORM)) &&
3189 		    ((un->un_oflags & FWRITE) == FWRITE)) {
3190 			un->un_status = KEY_DATA_PROTECT;
3191 			rval = EACCES;
3192 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3193 			    "read_only = %d eof = %d oflag = %d\n",
3194 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3195 		}
3196 	}
3197 
3198 	/*
3199 	 * If we're opening the tape write-only, we need to
3200 	 * write 2 filemarks on the HP 1/2 inch drive, to
3201 	 * create a null file.
3202 	 */
3203 	if ((un->un_read_only == RDWR) ||
3204 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3205 		if (un->un_dp->options & ST_REEL) {
3206 			un->un_fmneeded = 2;
3207 		} else {
3208 			un->un_fmneeded = 1;
3209 		}
3210 	} else {
3211 		un->un_fmneeded = 0;
3212 	}
3213 
3214 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3215 	    "fmneeded = %x\n", un->un_fmneeded);
3216 
3217 	/*
3218 	 * Make sure the density can be selected correctly.
3219 	 * If WORM can only write at the append point which in most cases
3220 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3221 	 * to set and try densities if a BOP.
3222 	 */
3223 	if (st_determine_density(un,
3224 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3225 		un->un_status = KEY_ILLEGAL_REQUEST;
3226 		un->un_laststate = un->un_state;
3227 		un->un_state = ST_STATE_CLOSED;
3228 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3229 		    "st_tape_init: EIO can't determine density\n");
3230 		rval = EIO;
3231 		goto exit;
3232 	}
3233 
3234 	/*
3235 	 * Destroy the knowledge that we have 'determined'
3236 	 * density so that a later read at BOT comes along
3237 	 * does the right density determination.
3238 	 */
3239 
3240 	un->un_density_known = 0;
3241 
3242 
3243 	/*
3244 	 * Okay, the tape is loaded and either at BOT or somewhere past.
3245 	 * Mark the state such that any I/O or tape space operations
3246 	 * will get/set the right density, etc..
3247 	 */
3248 	un->un_laststate = un->un_state;
3249 	un->un_lastop = ST_OP_NIL;
3250 	un->un_mediastate = MTIO_INSERTED;
3251 	cv_broadcast(&un->un_state_cv);
3252 
3253 	/*
3254 	 *  Set test append flag if writing.
3255 	 *  First write must check that tape is positioned correctly.
3256 	 */
3257 	un->un_test_append = (un->un_oflags & FWRITE);
3258 
3259 	/*
3260 	 * if there are pending unit attention flags.
3261 	 * Check that the media has not changed.
3262 	 */
3263 	if (un->un_unit_attention_flags) {
3264 		rval = st_get_media_identification(un, st_uscsi_cmd);
3265 		if (rval != 0 && rval != EACCES) {
3266 			rval = EIO;
3267 		}
3268 		un->un_unit_attention_flags = 0;
3269 	}
3270 
3271 exit:
3272 	un->un_err_resid = 0;
3273 	un->un_last_resid = 0;
3274 	un->un_last_count = 0;
3275 
3276 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3277 	    "st_tape_init: return val = %x\n", rval);
3278 	return (rval);
3279 
3280 }
3281 
3282 
3283 
3284 /* ARGSUSED */
3285 static int
3286 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3287 {
3288 	int err = 0;
3289 	int count, last_state;
3290 	minor_t minor = getminor(dev);
3291 #ifdef	__x86
3292 	struct contig_mem *cp, *cp_temp;
3293 #endif
3294 
3295 	GET_SOFT_STATE(dev);
3296 
3297 	ST_ENTR(ST_DEVINFO, st_close);
3298 
3299 	/*
3300 	 * wait till all cmds in the pipeline have been completed
3301 	 */
3302 	mutex_enter(ST_MUTEX);
3303 
3304 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3305 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3306 
3307 	st_wait_for_io(un);
3308 
3309 	/* turn off persistent errors on close, as we want close to succeed */
3310 	st_turn_pe_off(un);
3311 
3312 	/*
3313 	 * set state to indicate that we are in process of closing
3314 	 */
3315 	last_state = un->un_laststate = un->un_state;
3316 	un->un_state = ST_STATE_CLOSING;
3317 
3318 	ST_POS(ST_DEVINFO, "st_close1:", &un->un_pos);
3319 
3320 	/*
3321 	 * BSD behavior:
3322 	 * a close always causes a silent span to the next file if we've hit
3323 	 * an EOF (but not yet read across it).
3324 	 */
3325 	if ((minor & MT_BSD) && (un->un_pos.eof == ST_EOF)) {
3326 		if (un->un_pos.pmode != invalid) {
3327 			un->un_pos.fileno++;
3328 			un->un_pos.blkno = 0;
3329 		}
3330 		un->un_pos.eof = ST_NO_EOF;
3331 	}
3332 
3333 	/*
3334 	 * SVR4 behavior for skipping to next file:
3335 	 *
3336 	 * If we have not seen a filemark, space to the next file
3337 	 *
3338 	 * If we have already seen the filemark we are physically in the next
3339 	 * file and we only increment the filenumber
3340 	 */
3341 	if (((minor & (MT_BSD | MT_NOREWIND)) == MT_NOREWIND) &&
3342 	    (flag & FREAD) &&		/* reading or at least asked to */
3343 	    ((un->un_pos.blkno != 0) && 		/* inside a file */
3344 	    (un->un_lastop != ST_OP_WRITE) &&		/* Didn't just write */
3345 	    (un->un_lastop != ST_OP_WEOF))) {		/* or write filemarks */
3346 		switch (un->un_pos.eof) {
3347 		case ST_NO_EOF:
3348 			/*
3349 			 * if we were reading and did not read the complete file
3350 			 * skip to the next file, leaving the tape correctly
3351 			 * positioned to read the first record of the next file
3352 			 * Check first for REEL if we are at EOT by trying to
3353 			 * read a block
3354 			 */
3355 			if ((un->un_dp->options & ST_REEL) &&
3356 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3357 			    (un->un_pos.blkno == 0)) {
3358 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3359 					ST_DEBUG2(ST_DEVINFO, st_label,
3360 					    SCSI_DEBUG,
3361 					    "st_close : EIO can't space\n");
3362 					err = EIO;
3363 					break;
3364 				}
3365 				if (un->un_pos.eof >= ST_EOF_PENDING) {
3366 					un->un_pos.eof = ST_EOT_PENDING;
3367 					un->un_pos.fileno += 1;
3368 					un->un_pos.blkno   = 0;
3369 					break;
3370 				}
3371 			}
3372 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3373 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3374 				    "st_close: EIO can't space #2\n");
3375 				err = EIO;
3376 			} else {
3377 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3378 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3379 				    un->un_pos.fileno, un->un_pos.blkno,
3380 				    un->un_pos.eof);
3381 				un->un_pos.eof = ST_NO_EOF;
3382 			}
3383 			break;
3384 
3385 		case ST_EOF_PENDING:
3386 		case ST_EOF:
3387 			un->un_pos.fileno += 1;
3388 			un->un_pos.lgclblkno += 1;
3389 			un->un_pos.blkno   = 0;
3390 			un->un_pos.eof = ST_NO_EOF;
3391 			break;
3392 
3393 		case ST_EOT:
3394 		case ST_EOT_PENDING:
3395 			/* nothing to do */
3396 			break;
3397 		default:
3398 			scsi_log(ST_DEVINFO, st_label, CE_PANIC,
3399 			    "Undefined state 0x%x", un->un_pos.eof);
3400 
3401 		}
3402 	}
3403 
3404 
3405 	/*
3406 	 * For performance reasons (HP 88780), the driver should
3407 	 * postpone writing the second tape mark until just before a file
3408 	 * positioning ioctl is issued (e.g., rewind).	This means that
3409 	 * the user must not manually rewind the tape because the tape will
3410 	 * be missing the second tape mark which marks EOM.
3411 	 * However, this small performance improvement is not worth the risk.
3412 	 */
3413 
3414 	/*
3415 	 * We need to back up over the filemark we inadvertently popped
3416 	 * over doing a read in between the two filemarks that constitute
3417 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3418 	 * set while reading.
3419 	 *
3420 	 * If we happen to be at physical eot (ST_EOM) (writing case),
3421 	 * the writing of filemark(s) will clear the ST_EOM state, which
3422 	 * we don't want, so we save this state and restore it later.
3423 	 */
3424 
3425 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3426 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3427 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3428 
3429 	if (un->un_pos.eof == ST_EOT_PENDING) {
3430 		if (minor & MT_NOREWIND) {
3431 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3432 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3433 				    "st_close: EIO can't space #3\n");
3434 				err = EIO;
3435 			} else {
3436 				un->un_pos.blkno = 0;
3437 				un->un_pos.eof = ST_EOT;
3438 			}
3439 		} else {
3440 			un->un_pos.eof = ST_NO_EOF;
3441 		}
3442 
3443 	/*
3444 	 * Do we need to write a file mark?
3445 	 *
3446 	 * only write filemarks if there are fmks to be written and
3447 	 *   - open for write (possibly read/write)
3448 	 *   - the last operation was a write
3449 	 * or:
3450 	 *   -	opened for wronly
3451 	 *   -	no data was written
3452 	 */
3453 	} else if ((un->un_pos.pmode != invalid) &&
3454 	    (un->un_fmneeded > 0) &&
3455 	    (((flag & FWRITE) &&
3456 	    ((un->un_lastop == ST_OP_WRITE)||(un->un_lastop == ST_OP_WEOF))) ||
3457 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3458 
3459 		/* save ST_EOM state */
3460 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3461 
3462 		/*
3463 		 * Note that we will write a filemark if we had opened
3464 		 * the tape write only and no data was written, thus
3465 		 * creating a null file.
3466 		 *
3467 		 * If the user already wrote one, we only have to write 1 more.
3468 		 * If they wrote two, we don't have to write any.
3469 		 */
3470 
3471 		count = un->un_fmneeded;
3472 		if (count > 0) {
3473 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, count, SYNC_CMD)) {
3474 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3475 				    "st_close : EIO can't wfm\n");
3476 				err = EIO;
3477 			}
3478 			if ((un->un_dp->options & ST_REEL) &&
3479 			    (minor & MT_NOREWIND)) {
3480 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3481 					ST_DEBUG2(ST_DEVINFO, st_label,
3482 					    SCSI_DEBUG,
3483 					    "st_close : EIO space fmk(-1)\n");
3484 					err = EIO;
3485 				}
3486 				un->un_pos.eof = ST_NO_EOF;
3487 				/* fix up block number */
3488 				un->un_pos.blkno = 0;
3489 			}
3490 		}
3491 
3492 		/*
3493 		 * If we aren't going to be rewinding, and we were at
3494 		 * physical eot, restore the state that indicates we
3495 		 * are at physical eot. Once you have reached physical
3496 		 * eot, and you close the tape, the only thing you can
3497 		 * do on the next open is to rewind. Access to trailer
3498 		 * records is only allowed without closing the device.
3499 		 */
3500 		if ((minor & MT_NOREWIND) == 0 && was_at_eom) {
3501 			un->un_pos.eof = ST_EOM;
3502 		}
3503 	}
3504 
3505 	/*
3506 	 * report soft errors if enabled and available, if we never accessed
3507 	 * the drive, don't get errors. This will prevent some DAT error
3508 	 * messages upon LOG SENSE.
3509 	 */
3510 	if (st_report_soft_errors_on_close &&
3511 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3512 	    (last_state != ST_STATE_OFFLINE)) {
3513 		(void) st_report_soft_errors(dev, flag);
3514 	}
3515 
3516 
3517 	/*
3518 	 * Do we need to rewind? Can we rewind?
3519 	 */
3520 	if ((minor & MT_NOREWIND) == 0 &&
3521 	    un->un_pos.pmode != invalid && err == 0) {
3522 		/*
3523 		 * We'd like to rewind with the
3524 		 * 'immediate' bit set, but this
3525 		 * causes problems on some drives
3526 		 * where subsequent opens get a
3527 		 * 'NOT READY' error condition
3528 		 * back while the tape is rewinding,
3529 		 * which is impossible to distinguish
3530 		 * from the condition of 'no tape loaded'.
3531 		 *
3532 		 * Also, for some targets, if you disconnect
3533 		 * with the 'immediate' bit set, you don't
3534 		 * actually return right away, i.e., the
3535 		 * target ignores your request for immediate
3536 		 * return.
3537 		 *
3538 		 * Instead, we'll fire off an async rewind
3539 		 * command. We'll mark the device as closed,
3540 		 * and any subsequent open will stall on
3541 		 * the first TEST_UNIT_READY until the rewind
3542 		 * completes.
3543 		 */
3544 
3545 		/*
3546 		 * Used to be if reserve was not supported we'd send an
3547 		 * asynchronious rewind. Comments above may be slightly invalid
3548 		 * as the immediate bit was never set. Doing an immedate rewind
3549 		 * makes sense, I think fixes to not ready status might handle
3550 		 * the problems described above.
3551 		 */
3552 		if (un->un_sd->sd_inq->inq_ansi < 2) {
3553 			(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
3554 		} else {
3555 			/* flush data for older drives per scsi spec. */
3556 			(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
3557 			(void) st_cmd(un, SCMD_REWIND, 1, ASYNC_CMD);
3558 		}
3559 	}
3560 
3561 	/*
3562 	 * eject tape if necessary
3563 	 */
3564 	if (un->un_eject_tape_on_failure) {
3565 		un->un_eject_tape_on_failure = 0;
3566 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3567 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3568 			    "st_close : can't unload tape\n");
3569 		} else {
3570 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3571 			    "st_close : tape unloaded \n");
3572 			un->un_pos.eof = ST_NO_EOF;
3573 			un->un_mediastate = MTIO_EJECTED;
3574 		}
3575 	}
3576 	/*
3577 	 * Release the tape unit, if default reserve/release
3578 	 * behaviour.
3579 	 */
3580 	if ((un->un_rsvd_status &
3581 	    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
3582 		(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
3583 	}
3584 
3585 	/*
3586 	 * clear up state
3587 	 */
3588 	un->un_laststate = un->un_state;
3589 	un->un_state = ST_STATE_CLOSED;
3590 	un->un_lastop = ST_OP_NIL;
3591 	un->un_throttle = 1;	/* assume one request at time, for now */
3592 	un->un_retry_ct = 0;
3593 	un->un_tran_retry_ct = 0;
3594 	un->un_errno = 0;
3595 	un->un_swr_token = (opaque_t)NULL;
3596 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3597 
3598 	/* Restore the options to the init time settings */
3599 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3600 		un->un_dp->options |= ST_READ_IGNORE_ILI;
3601 	} else {
3602 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3603 	}
3604 
3605 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3606 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3607 	} else {
3608 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3609 	}
3610 
3611 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3612 		un->un_dp->options |= ST_SHORT_FILEMARKS;
3613 	} else {
3614 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3615 	}
3616 
3617 	ASSERT(mutex_owned(ST_MUTEX));
3618 
3619 	/*
3620 	 * Signal anyone awaiting a close operation to complete.
3621 	 */
3622 	cv_signal(&un->un_clscv);
3623 
3624 	/*
3625 	 * any kind of error on closing causes all state to be tossed
3626 	 */
3627 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3628 		/*
3629 		 * note that st_intr has already set
3630 		 * un_pos.pmode to invalid.
3631 		 */
3632 		un->un_density_known = 0;
3633 	}
3634 
3635 #ifdef	__x86
3636 	/*
3637 	 * free any contiguous mem alloc'ed for big block I/O
3638 	 */
3639 	cp = un->un_contig_mem;
3640 	while (cp) {
3641 		if (cp->cm_addr) {
3642 			ddi_dma_mem_free(&cp->cm_acc_hdl);
3643 		}
3644 		cp_temp = cp;
3645 		cp = cp->cm_next;
3646 		kmem_free(cp_temp,
3647 		    sizeof (struct contig_mem) + biosize());
3648 	}
3649 	un->un_contig_mem_total_num = 0;
3650 	un->un_contig_mem_available_num = 0;
3651 	un->un_contig_mem = NULL;
3652 	un->un_max_contig_mem_len = 0;
3653 #endif
3654 
3655 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3656 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3657 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3658 
3659 	mutex_exit(ST_MUTEX);
3660 	return (err);
3661 }
3662 
3663 /*
3664  * These routines perform raw i/o operations.
3665  */
3666 
3667 /* ARGSUSED2 */
3668 static int
3669 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3670 {
3671 #ifdef STDEBUG
3672 	GET_SOFT_STATE(dev);
3673 	ST_ENTR(ST_DEVINFO, st_aread);
3674 #endif
3675 	return (st_arw(dev, aio, B_READ));
3676 }
3677 
3678 
3679 /* ARGSUSED2 */
3680 static int
3681 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3682 {
3683 #ifdef STDEBUG
3684 	GET_SOFT_STATE(dev);
3685 	ST_ENTR(ST_DEVINFO, st_awrite);
3686 #endif
3687 	return (st_arw(dev, aio, B_WRITE));
3688 }
3689 
3690 
3691 
3692 /* ARGSUSED */
3693 static int
3694 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3695 {
3696 #ifdef STDEBUG
3697 	GET_SOFT_STATE(dev);
3698 	ST_ENTR(ST_DEVINFO, st_read);
3699 #endif
3700 	return (st_rw(dev, uiop, B_READ));
3701 }
3702 
3703 /* ARGSUSED */
3704 static int
3705 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3706 {
3707 #ifdef STDEBUG
3708 	GET_SOFT_STATE(dev);
3709 	ST_ENTR(ST_DEVINFO, st_write);
3710 #endif
3711 	return (st_rw(dev, uiop, B_WRITE));
3712 }
3713 
3714 /*
3715  * Due to historical reasons, old limits are: For variable-length devices:
3716  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3717  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3718  * (let it through unmodified. For fixed-length record devices:
3719  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3720  *
3721  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3722  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3723  * command to the drive).
3724  *
3725  */
3726 static void
3727 st_minphys(struct buf *bp)
3728 {
3729 	struct scsi_tape *un;
3730 
3731 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3732 
3733 	ST_FUNC(ST_DEVINFO, st_minphys);
3734 
3735 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3736 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3737 	    bp->b_bcount);
3738 
3739 	if (un->un_allow_large_xfer) {
3740 
3741 		/*
3742 		 * check un_maxbsize for variable length devices only
3743 		 */
3744 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3745 			bp->b_bcount = un->un_maxbsize;
3746 		}
3747 		/*
3748 		 * can't go more that HBA maxdma limit in either fixed-length
3749 		 * or variable-length tape drives.
3750 		 */
3751 		if (bp->b_bcount > un->un_maxdma) {
3752 			bp->b_bcount = un->un_maxdma;
3753 		}
3754 	} else {
3755 
3756 		/*
3757 		 *  use old fixed limits
3758 		 */
3759 		if (un->un_bsize == 0) {
3760 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3761 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3762 			}
3763 		} else {
3764 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3765 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3766 			}
3767 		}
3768 	}
3769 
3770 	/*
3771 	 * For regular raw I/O and Fixed Block length devices, make sure
3772 	 * the adjusted block count is a whole multiple of the device
3773 	 * block size.
3774 	 */
3775 	if (bp != un->un_sbufp && un->un_bsize) {
3776 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3777 	}
3778 }
3779 
3780 static int
3781 st_rw(dev_t dev, struct uio *uio, int flag)
3782 {
3783 	int rval = 0;
3784 	long len;
3785 
3786 	GET_SOFT_STATE(dev);
3787 
3788 	ST_FUNC(ST_DEVINFO, st_rw);
3789 
3790 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3791 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3792 	    (flag == B_READ ? rd_str: wr_str));
3793 
3794 	/* get local copy of transfer length */
3795 	len = uio->uio_iov->iov_len;
3796 
3797 	mutex_enter(ST_MUTEX);
3798 
3799 	/*
3800 	 * Clear error entry stack
3801 	 */
3802 	st_empty_error_stack(un);
3803 
3804 	/*
3805 	 * If in fixed block size mode and requested read or write
3806 	 * is not an even multiple of that block size.
3807 	 */
3808 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3809 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3810 		    "%s: not modulo %d block size\n",
3811 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3812 		rval = EINVAL;
3813 	}
3814 
3815 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3816 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3817 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3818 		    "%s: not modulo %d device granularity\n",
3819 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3820 		rval = EINVAL;
3821 	}
3822 
3823 	if (rval != 0) {
3824 		un->un_errno = rval;
3825 		mutex_exit(ST_MUTEX);
3826 		return (rval);
3827 	}
3828 
3829 	/*
3830 	 * Reset this so it can be set if Berkeley and read over a filemark.
3831 	 */
3832 	un->un_silent_skip = 0;
3833 	mutex_exit(ST_MUTEX);
3834 
3835 	len = uio->uio_resid;
3836 
3837 	rval = physio(st_queued_strategy, (struct buf *)NULL,
3838 	    dev, flag, st_minphys, uio);
3839 	/*
3840 	 * if we have hit logical EOT during this xfer and there is not a
3841 	 * full residue, then set eof back  to ST_EOM to make sure that
3842 	 * the user will see at least one zero write
3843 	 * after this short write
3844 	 */
3845 	mutex_enter(ST_MUTEX);
3846 	if (un->un_pos.eof > ST_NO_EOF) {
3847 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3848 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3849 	}
3850 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3851 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3852 			un->un_pos.eof = ST_EOM;
3853 		} else if (uio->uio_resid == len) {
3854 			un->un_pos.eof = ST_NO_EOF;
3855 		}
3856 	}
3857 
3858 	if (un->un_silent_skip && uio->uio_resid != len) {
3859 		un->un_pos.eof = ST_EOF;
3860 		un->un_pos.blkno = un->un_save_blkno;
3861 		un->un_pos.fileno--;
3862 	}
3863 
3864 	un->un_errno = rval;
3865 
3866 	mutex_exit(ST_MUTEX);
3867 
3868 	return (rval);
3869 }
3870 
3871 static int
3872 st_arw(dev_t dev, struct aio_req *aio, int flag)
3873 {
3874 	struct uio *uio = aio->aio_uio;
3875 	int rval = 0;
3876 	long len;
3877 
3878 	GET_SOFT_STATE(dev);
3879 
3880 	ST_FUNC(ST_DEVINFO, st_arw);
3881 
3882 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3883 	    "st_arw(dev = 0x%lx, flag = %s)\n", dev,
3884 	    (flag == B_READ ? rd_str: wr_str));
3885 
3886 	/* get local copy of transfer length */
3887 	len = uio->uio_iov->iov_len;
3888 
3889 	mutex_enter(ST_MUTEX);
3890 
3891 	/*
3892 	 * If in fixed block size mode and requested read or write
3893 	 * is not an even multiple of that block size.
3894 	 */
3895 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3896 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3897 		    "%s: not modulo %d block size\n",
3898 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3899 		rval = EINVAL;
3900 	}
3901 
3902 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3903 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3904 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3905 		    "%s: not modulo %d device granularity\n",
3906 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3907 		rval = EINVAL;
3908 	}
3909 
3910 	if (rval != 0) {
3911 		un->un_errno = rval;
3912 		mutex_exit(ST_MUTEX);
3913 		return (rval);
3914 	}
3915 
3916 	mutex_exit(ST_MUTEX);
3917 
3918 	len = uio->uio_resid;
3919 
3920 	rval =
3921 	    aphysio(st_queued_strategy, anocancel, dev, flag, st_minphys, aio);
3922 
3923 	/*
3924 	 * if we have hit logical EOT during this xfer and there is not a
3925 	 * full residue, then set eof back  to ST_EOM to make sure that
3926 	 * the user will see at least one zero write
3927 	 * after this short write
3928 	 *
3929 	 * we keep this here just in case the application is not using
3930 	 * persistent errors
3931 	 */
3932 	mutex_enter(ST_MUTEX);
3933 	if (un->un_pos.eof > ST_NO_EOF) {
3934 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3935 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3936 	}
3937 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3938 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3939 			un->un_pos.eof = ST_EOM;
3940 		} else if (uio->uio_resid == len &&
3941 		    !(un->un_persistence && un->un_persist_errors)) {
3942 			un->un_pos.eof = ST_NO_EOF;
3943 		}
3944 	}
3945 	un->un_errno = rval;
3946 	mutex_exit(ST_MUTEX);
3947 
3948 	return (rval);
3949 }
3950 
3951 
3952 
3953 static int
3954 st_queued_strategy(buf_t *bp)
3955 {
3956 	struct scsi_tape *un;
3957 	char reading = bp->b_flags & B_READ;
3958 	int wasopening = 0;
3959 
3960 	/*
3961 	 * validate arguments
3962 	 */
3963 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3964 	if (un == NULL) {
3965 		bp->b_resid = bp->b_bcount;
3966 		bioerror(bp, ENXIO);
3967 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
3968 		    "st_queued_strategy: ENXIO error exit\n");
3969 		biodone(bp);
3970 		return (0);
3971 	}
3972 
3973 	ST_ENTR(ST_DEVINFO, st_queued_strategy);
3974 
3975 	mutex_enter(ST_MUTEX);
3976 
3977 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
3978 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
3979 	}
3980 
3981 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3982 	    "st_queued_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
3983 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3984 
3985 	/*
3986 	 * If persistent errors have been flagged, just nix this one. We wait
3987 	 * for any outstanding I/O's below, so we will be in order.
3988 	 */
3989 	if (un->un_persistence && un->un_persist_errors) {
3990 		goto exit;
3991 	}
3992 
3993 	/*
3994 	 * If last command was non queued, wait till it finishes.
3995 	 */
3996 	while (un->un_sbuf_busy) {
3997 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
3998 		/* woke up because of an error */
3999 		if (un->un_persistence && un->un_persist_errors) {
4000 			goto exit;
4001 		}
4002 	}
4003 
4004 	/*
4005 	 * s_buf and recovery commands shouldn't come here.
4006 	 */
4007 	ASSERT(bp != un->un_recov_buf);
4008 	ASSERT(bp != un->un_sbufp);
4009 
4010 	/*
4011 	 * If we haven't done/checked reservation on the tape unit
4012 	 * do it now.
4013 	 */
4014 	if ((un->un_rsvd_status &
4015 	    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
4016 		if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
4017 			if (st_reserve_release(un, ST_RESERVE, st_uscsi_cmd)) {
4018 				st_bioerror(bp, un->un_errno);
4019 				goto exit;
4020 			}
4021 		} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4022 			/*
4023 			 * Enter here to restore position for possible
4024 			 * resets when the device was closed and opened
4025 			 * in O_NDELAY mode subsequently
4026 			 */
4027 			un->un_state = ST_STATE_INITIALIZING;
4028 			(void) st_cmd(un, SCMD_TEST_UNIT_READY,
4029 			    0, SYNC_CMD);
4030 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4031 		}
4032 		un->un_rsvd_status |= ST_INIT_RESERVE;
4033 	}
4034 
4035 	/*
4036 	 * If we are offline, we have to initialize everything first.
4037 	 * This is to handle either when opened with O_NDELAY, or
4038 	 * we just got a new tape in the drive, after an offline.
4039 	 * We don't observe O_NDELAY past the open,
4040 	 * as it will not make sense for tapes.
4041 	 */
4042 	if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
4043 		/*
4044 		 * reset state to avoid recursion
4045 		 */
4046 		un->un_laststate = un->un_state;
4047 		un->un_state = ST_STATE_INITIALIZING;
4048 		if (st_tape_init(un)) {
4049 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4050 			    "stioctl : OFFLINE init failure ");
4051 			un->un_state = ST_STATE_OFFLINE;
4052 			un->un_pos.pmode = invalid;
4053 			goto b_done_err;
4054 		}
4055 		/* WTF un_restore_pos make invalid */
4056 		un->un_state = ST_STATE_OPEN_PENDING_IO;
4057 		un->un_restore_pos = 0;
4058 	}
4059 	/*
4060 	 * Check for legal operations
4061 	 */
4062 	if (un->un_pos.pmode == invalid) {
4063 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4064 		    "strategy with un->un_pos.pmode invalid\n");
4065 		goto b_done_err;
4066 	}
4067 
4068 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4069 	    "st_queued_strategy(): regular io\n");
4070 
4071 	/*
4072 	 * Process this first. If we were reading, and we're pending
4073 	 * logical eot, that means we've bumped one file mark too far.
4074 	 */
4075 
4076 	/*
4077 	 * Recursion warning: st_cmd will route back through here.
4078 	 * Not anymore st_cmd will go through st_strategy()!
4079 	 */
4080 	if (un->un_pos.eof == ST_EOT_PENDING) {
4081 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4082 			un->un_pos.pmode = invalid;
4083 			un->un_density_known = 0;
4084 			goto b_done_err;
4085 		}
4086 		un->un_pos.blkno = 0; /* fix up block number.. */
4087 		un->un_pos.eof = ST_EOT;
4088 	}
4089 
4090 	/*
4091 	 * If we are in the process of opening, we may have to
4092 	 * determine/set the correct density. We also may have
4093 	 * to do a test_append (if QIC) to see whether we are
4094 	 * in a position to append to the end of the tape.
4095 	 *
4096 	 * If we're already at logical eot, we transition
4097 	 * to ST_NO_EOF. If we're at physical eot, we punt
4098 	 * to the switch statement below to handle.
4099 	 */
4100 	if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
4101 	    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
4102 
4103 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4104 			if (st_determine_density(un, (int)reading)) {
4105 				goto b_done_err;
4106 			}
4107 		}
4108 
4109 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4110 		    "pending_io@fileno %d rw %d qic %d eof %d\n",
4111 		    un->un_pos.fileno, (int)reading,
4112 		    (un->un_dp->options & ST_QIC) ? 1 : 0,
4113 		    un->un_pos.eof);
4114 
4115 		if (!reading && un->un_pos.eof != ST_EOM) {
4116 			if (un->un_pos.eof == ST_EOT) {
4117 				un->un_pos.eof = ST_NO_EOF;
4118 			} else if (un->un_pos.pmode != invalid &&
4119 			    (un->un_dp->options & ST_QIC)) {
4120 				/*
4121 				 * st_test_append() will do it all
4122 				 */
4123 				st_test_append(bp);
4124 				mutex_exit(ST_MUTEX);
4125 				return (0);
4126 			}
4127 		}
4128 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4129 			wasopening = 1;
4130 		}
4131 		un->un_laststate = un->un_state;
4132 		un->un_state = ST_STATE_OPEN;
4133 	}
4134 
4135 
4136 	/*
4137 	 * Process rest of END OF FILE and END OF TAPE conditions
4138 	 */
4139 
4140 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4141 	    "eof=%x, wasopening=%x\n",
4142 	    un->un_pos.eof, wasopening);
4143 
4144 	switch (un->un_pos.eof) {
4145 	case ST_EOM:
4146 		/*
4147 		 * This allows writes to proceed past physical
4148 		 * eot. We'll *really* be in trouble if the
4149 		 * user continues blindly writing data too
4150 		 * much past this point (unwind the tape).
4151 		 * Physical eot really means 'early warning
4152 		 * eot' in this context.
4153 		 *
4154 		 * Every other write from now on will succeed
4155 		 * (if sufficient  tape left).
4156 		 * This write will return with resid == count
4157 		 * but the next one should be successful
4158 		 *
4159 		 * Note that we only transition to logical EOT
4160 		 * if the last state wasn't the OPENING state.
4161 		 * We explicitly prohibit running up to physical
4162 		 * eot, closing the device, and then re-opening
4163 		 * to proceed. Trailer records may only be gotten
4164 		 * at by keeping the tape open after hitting eot.
4165 		 *
4166 		 * Also note that ST_EOM cannot be set by reading-
4167 		 * this can only be set during writing. Reading
4168 		 * up to the end of the tape gets a blank check
4169 		 * or a double-filemark indication (ST_EOT_PENDING),
4170 		 * and we prohibit reading after that point.
4171 		 *
4172 		 */
4173 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
4174 		if (wasopening == 0) {
4175 			/*
4176 			 * this allows st_rw() to reset it back to
4177 			 * will see a zero write
4178 			 */
4179 			un->un_pos.eof = ST_WRITE_AFTER_EOM;
4180 		}
4181 		un->un_status = SUN_KEY_EOT;
4182 		goto b_done;
4183 
4184 	case ST_WRITE_AFTER_EOM:
4185 	case ST_EOT:
4186 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
4187 		un->un_status = SUN_KEY_EOT;
4188 		if (SVR4_BEHAVIOR && reading) {
4189 			goto b_done_err;
4190 		}
4191 
4192 		if (reading) {
4193 			goto b_done;
4194 		}
4195 		un->un_pos.eof = ST_NO_EOF;
4196 		break;
4197 
4198 	case ST_EOF_PENDING:
4199 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4200 		    "EOF PENDING\n");
4201 		un->un_status = SUN_KEY_EOF;
4202 		if (SVR4_BEHAVIOR) {
4203 			un->un_pos.eof = ST_EOF;
4204 			goto b_done;
4205 		}
4206 		/* FALLTHROUGH */
4207 	case ST_EOF:
4208 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
4209 		un->un_status = SUN_KEY_EOF;
4210 		if (SVR4_BEHAVIOR) {
4211 			goto b_done_err;
4212 		}
4213 
4214 		if (BSD_BEHAVIOR) {
4215 			un->un_pos.eof = ST_NO_EOF;
4216 			un->un_pos.fileno += 1;
4217 			un->un_pos.blkno   = 0;
4218 		}
4219 
4220 		if (reading) {
4221 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4222 			    "now file %d (read)\n",
4223 			    un->un_pos.fileno);
4224 			goto b_done;
4225 		}
4226 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4227 		    "now file %d (write)\n", un->un_pos.fileno);
4228 		break;
4229 	default:
4230 		un->un_status = 0;
4231 		break;
4232 	}
4233 
4234 	bp->b_flags &= ~(B_DONE);
4235 	st_bioerror(bp, 0);
4236 	bp->av_forw = NULL;
4237 	bp->b_resid = 0;
4238 	SET_BP_PKT(bp, 0);
4239 
4240 
4241 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4242 	    "st_queued_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4243 	    " pkt=0x%p\n",
4244 	    (void *)bp->b_forw, bp->b_bcount,
4245 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4246 
4247 #ifdef	__x86
4248 	/*
4249 	 * We will replace bp with a new bp that can do big blk xfer
4250 	 * if the requested xfer size is bigger than un->un_maxdma_arch
4251 	 *
4252 	 * Also, we need to make sure that we're handling real I/O
4253 	 * by checking group 0/1 SCSI I/O commands, if needed
4254 	 */
4255 	if (bp->b_bcount > un->un_maxdma_arch &&
4256 	    ((uchar_t)(uintptr_t)bp->b_forw == SCMD_READ ||
4257 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G4 ||
4258 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE ||
4259 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G4)) {
4260 		mutex_exit(ST_MUTEX);
4261 		bp = st_get_bigblk_bp(bp);
4262 		mutex_enter(ST_MUTEX);
4263 	}
4264 #endif
4265 
4266 	/* put on wait queue */
4267 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4268 	    "st_queued_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4269 	    (void *)un->un_quef, (void *)bp);
4270 
4271 	st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quel, bp);
4272 
4273 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4274 
4275 	st_start(un);
4276 
4277 	mutex_exit(ST_MUTEX);
4278 	return (0);
4279 
4280 b_done_err:
4281 	st_bioerror(bp, EIO);
4282 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4283 	    "st_queued_strategy : EIO b_done_err\n");
4284 
4285 b_done:
4286 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4287 	    "st_queued_strategy: b_done\n");
4288 
4289 exit:
4290 	/*
4291 	 * make sure no commands are outstanding or waiting before closing,
4292 	 * so we can guarantee order
4293 	 */
4294 	st_wait_for_io(un);
4295 	un->un_err_resid = bp->b_resid = bp->b_bcount;
4296 
4297 	/* override errno here, if persistent errors were flagged */
4298 	if (un->un_persistence && un->un_persist_errors)
4299 		bioerror(bp, un->un_errno);
4300 
4301 	mutex_exit(ST_MUTEX);
4302 
4303 	biodone(bp);
4304 	ASSERT(mutex_owned(ST_MUTEX) == 0);
4305 	return (0);
4306 }
4307 
4308 
4309 static int
4310 st_strategy(struct buf *bp)
4311 {
4312 	struct scsi_tape *un;
4313 
4314 	/*
4315 	 * validate arguments
4316 	 */
4317 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4318 	if (un == NULL) {
4319 		bp->b_resid = bp->b_bcount;
4320 		bioerror(bp, ENXIO);
4321 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4322 		    "st_strategy: ENXIO error exit\n");
4323 
4324 		biodone(bp);
4325 		return (0);
4326 
4327 	}
4328 
4329 	ST_ENTR(ST_DEVINFO, st_strategy);
4330 
4331 	mutex_enter(ST_MUTEX);
4332 
4333 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4334 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4335 	}
4336 
4337 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4338 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4339 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4340 
4341 	ASSERT((bp == un->un_recov_buf) || (bp == un->un_sbufp));
4342 
4343 	bp->b_flags &= ~(B_DONE);
4344 	st_bioerror(bp, 0);
4345 	bp->av_forw = NULL;
4346 	bp->b_resid = 0;
4347 	SET_BP_PKT(bp, 0);
4348 
4349 
4350 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4351 	    "st_strategy: cmd=0x%x  count=%ld  resid=%ld flags=0x%x"
4352 	    " pkt=0x%p\n",
4353 	    (unsigned char)(uintptr_t)bp->b_forw, bp->b_bcount,
4354 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4355 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4356 
4357 	st_start(un);
4358 
4359 	mutex_exit(ST_MUTEX);
4360 	return (0);
4361 }
4362 
4363 /*
4364  * this routine spaces forward over filemarks
4365  */
4366 static int
4367 st_space_fmks(struct scsi_tape *un, long count)
4368 {
4369 	int rval = 0;
4370 
4371 	ST_FUNC(ST_DEVINFO, st_space_fmks);
4372 
4373 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4374 	    "st_space_fmks(dev = 0x%lx, count = %ld)\n", un->un_dev, count);
4375 
4376 	ASSERT(mutex_owned(ST_MUTEX));
4377 
4378 	/*
4379 	 * the risk with doing only one space operation is that we
4380 	 * may accidentily jump in old data
4381 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4382 	 * because the 8200 does not append a marker; in order not to
4383 	 * sacrifice the fast file skip, we do a slow skip if the low
4384 	 * density device has been opened
4385 	 */
4386 
4387 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4388 	    !((un->un_dp->type == ST_TYPE_EXB8500 &&
4389 	    MT_DENSITY(un->un_dev) == 0))) {
4390 		if (st_cmd(un, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4391 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4392 			    "space_fmks : EIO can't do space cmd #1\n");
4393 			rval = EIO;
4394 		}
4395 	} else {
4396 		while (count > 0) {
4397 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4398 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4399 				    "space_fmks : EIO can't do space cmd #2\n");
4400 				rval = EIO;
4401 				break;
4402 			}
4403 			count -= 1;
4404 			/*
4405 			 * read a block to see if we have reached
4406 			 * end of medium (double filemark for reel or
4407 			 * medium error for others)
4408 			 */
4409 			if (count > 0) {
4410 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
4411 					ST_DEBUG2(ST_DEVINFO, st_label,
4412 					    SCSI_DEBUG,
4413 					    "space_fmks : EIO can't do "
4414 					    "space cmd #3\n");
4415 					rval = EIO;
4416 					break;
4417 				}
4418 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4419 				    (un->un_dp->options & ST_REEL)) {
4420 					un->un_status = SUN_KEY_EOT;
4421 					ST_DEBUG2(ST_DEVINFO, st_label,
4422 					    SCSI_DEBUG,
4423 					    "space_fmks : EIO ST_REEL\n");
4424 					rval = EIO;
4425 					break;
4426 				} else if (IN_EOF(un->un_pos)) {
4427 					un->un_pos.eof = ST_NO_EOF;
4428 					un->un_pos.fileno++;
4429 					un->un_pos.blkno = 0;
4430 					count--;
4431 				} else if (un->un_pos.eof > ST_EOF) {
4432 					ST_DEBUG2(ST_DEVINFO, st_label,
4433 					    SCSI_DEBUG,
4434 					    "space_fmks, EIO > ST_EOF\n");
4435 					rval = EIO;
4436 					break;
4437 				}
4438 
4439 			}
4440 		}
4441 		un->un_err_resid = count;
4442 		COPY_POS(&un->un_pos, &un->un_err_pos);
4443 	}
4444 	ASSERT(mutex_owned(ST_MUTEX));
4445 	return (rval);
4446 }
4447 
4448 /*
4449  * this routine spaces to EOD
4450  *
4451  * it keeps track of the current filenumber and returns the filenumber after
4452  * the last successful space operation, we keep the number high because as
4453  * tapes are getting larger, the possibility of more and more files exist,
4454  * 0x100000 (1 Meg of files) probably will never have to be changed any time
4455  * soon
4456  */
4457 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4458 
4459 static int
4460 st_find_eod(struct scsi_tape *un)
4461 {
4462 	tapepos_t savepos;
4463 	int64_t sp_type;
4464 	int result;
4465 
4466 	if (un == NULL) {
4467 		return (-1);
4468 	}
4469 
4470 	ST_FUNC(ST_DEVINFO, st_find_eod);
4471 
4472 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4473 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", un->un_dev,
4474 	    un->un_pos.fileno);
4475 
4476 	ASSERT(mutex_owned(ST_MUTEX));
4477 
4478 	COPY_POS(&savepos, &un->un_pos);
4479 
4480 	/*
4481 	 * see if the drive is smart enough to do the skips in
4482 	 * one operation; 1/2" use two filemarks
4483 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4484 	 * because the 8200 does not append a marker; in order not to
4485 	 * sacrifice the fast file skip, we do a slow skip if the low
4486 	 * density device has been opened
4487 	 */
4488 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4489 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4490 		    (MT_DENSITY(un->un_dev) == 0)) {
4491 			sp_type = Fmk(1);
4492 		} else if (un->un_pos.pmode == logical) {
4493 			sp_type = SPACE(SP_EOD, 0);
4494 		} else {
4495 			sp_type = Fmk(MAX_SKIP);
4496 		}
4497 	} else {
4498 		sp_type = Fmk(1);
4499 	}
4500 
4501 	for (;;) {
4502 		result = st_cmd(un, SCMD_SPACE, sp_type, SYNC_CMD);
4503 
4504 		if (result == 0) {
4505 			COPY_POS(&savepos, &un->un_pos);
4506 		}
4507 
4508 		if (sp_type == SPACE(SP_EOD, 0)) {
4509 			if (result != 0) {
4510 				sp_type = Fmk(MAX_SKIP);
4511 				continue;
4512 			}
4513 
4514 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4515 			    "st_find_eod: 0x%"PRIx64"\n",
4516 			    savepos.lgclblkno);
4517 			/*
4518 			 * What we return will become the current file position.
4519 			 * After completing the space command with the position
4520 			 * mode that is not invalid a read position command will
4521 			 * be automaticly issued. If the drive support the long
4522 			 * read position format a valid file position can be
4523 			 * returned.
4524 			 */
4525 			return (un->un_pos.fileno);
4526 		}
4527 
4528 		if (result != 0) {
4529 			break;
4530 		}
4531 
4532 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4533 		    "count=%"PRIx64", eof=%x, status=%x\n",
4534 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4535 
4536 		/*
4537 		 * If we're not EOM smart,  space a record
4538 		 * to see whether we're now in the slot between
4539 		 * the two sequential filemarks that logical
4540 		 * EOM consists of (REEL) or hit nowhere land
4541 		 * (8mm).
4542 		 */
4543 		if (sp_type == Fmk(1)) {
4544 			/*
4545 			 * no fast skipping, check a record
4546 			 */
4547 			if (st_cmd(un, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4548 				break;
4549 			}
4550 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4551 			    (un->un_dp->options & ST_REEL)) {
4552 				un->un_status = KEY_BLANK_CHECK;
4553 				un->un_pos.fileno++;
4554 				un->un_pos.blkno = 0;
4555 				break;
4556 			}
4557 			if (IN_EOF(un->un_pos)) {
4558 				un->un_pos.eof = ST_NO_EOF;
4559 				un->un_pos.fileno++;
4560 				un->un_pos.blkno = 0;
4561 			}
4562 			if (un->un_pos.eof > ST_EOF) {
4563 				break;
4564 			}
4565 		} else {
4566 			if (un->un_pos.eof > ST_EOF) {
4567 				break;
4568 			}
4569 		}
4570 	}
4571 
4572 	if (un->un_dp->options & ST_KNOWS_EOD) {
4573 		COPY_POS(&savepos, &un->un_pos);
4574 	}
4575 
4576 	ASSERT(mutex_owned(ST_MUTEX));
4577 
4578 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4579 	    "st_find_eod: %x\n", savepos.fileno);
4580 	return (savepos.fileno);
4581 }
4582 
4583 
4584 /*
4585  * this routine is frequently used in ioctls below;
4586  * it determines whether we know the density and if not will
4587  * determine it
4588  * if we have written the tape before, one or more filemarks are written
4589  *
4590  * depending on the stepflag, the head is repositioned to where it was before
4591  * the filemarks were written in order not to confuse step counts
4592  */
4593 #define	STEPBACK    0
4594 #define	NO_STEPBACK 1
4595 
4596 static int
4597 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4598 {
4599 
4600 	GET_SOFT_STATE(dev);
4601 
4602 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4603 
4604 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4605 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4606 	    "\n", dev, wfm, mode, stepflag);
4607 
4608 	ASSERT(mutex_owned(ST_MUTEX));
4609 
4610 	/*
4611 	 * If we don't yet know the density of the tape we have inserted,
4612 	 * we have to either unconditionally set it (if we're 'writing'),
4613 	 * or we have to determine it. As side effects, check for any
4614 	 * write-protect errors, and for the need to put out any file-marks
4615 	 * before positioning a tape.
4616 	 *
4617 	 * If we are going to be spacing forward, and we haven't determined
4618 	 * the tape density yet, we have to do so now...
4619 	 */
4620 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4621 		if (st_determine_density(un, mode)) {
4622 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4623 			    "check_density_or_wfm : EIO can't determine "
4624 			    "density\n");
4625 			un->un_errno = EIO;
4626 			return (EIO);
4627 		}
4628 		/*
4629 		 * Presumably we are at BOT. If we attempt to write, it will
4630 		 * either work okay, or bomb. We don't do a st_test_append
4631 		 * unless we're past BOT.
4632 		 */
4633 		un->un_laststate = un->un_state;
4634 		un->un_state = ST_STATE_OPEN;
4635 
4636 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4637 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4638 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4639 
4640 		tapepos_t spos;
4641 
4642 		COPY_POS(&spos, &un->un_pos);
4643 
4644 		/*
4645 		 * We need to write one or two filemarks.
4646 		 * In the case of the HP, we need to
4647 		 * position the head between the two
4648 		 * marks.
4649 		 */
4650 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4651 			wfm = un->un_fmneeded;
4652 			un->un_fmneeded = 0;
4653 		}
4654 
4655 		if (st_write_fm(dev, wfm)) {
4656 			un->un_pos.pmode = invalid;
4657 			un->un_density_known = 0;
4658 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4659 			    "check_density_or_wfm : EIO can't write fm\n");
4660 			un->un_errno = EIO;
4661 			return (EIO);
4662 		}
4663 
4664 		if (stepflag == STEPBACK) {
4665 			if (st_cmd(un, SCMD_SPACE, Fmk(-wfm), SYNC_CMD)) {
4666 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4667 				    "check_density_or_wfm : EIO can't space "
4668 				    "(-wfm)\n");
4669 				un->un_errno = EIO;
4670 				return (EIO);
4671 			}
4672 			COPY_POS(&un->un_pos, &spos);
4673 		}
4674 	}
4675 
4676 	/*
4677 	 * Whatever we do at this point clears the state of the eof flag.
4678 	 */
4679 
4680 	un->un_pos.eof = ST_NO_EOF;
4681 
4682 	/*
4683 	 * If writing, let's check that we're positioned correctly
4684 	 * at the end of tape before issuing the next write.
4685 	 */
4686 	if (un->un_read_only == RDWR) {
4687 		un->un_test_append = 1;
4688 	}
4689 
4690 	ASSERT(mutex_owned(ST_MUTEX));
4691 	return (0);
4692 }
4693 
4694 
4695 /*
4696  * Wait for all outstaning I/O's to complete
4697  *
4698  * we wait on both ncmds and the wait queue for times when we are flushing
4699  * after persistent errors are flagged, which is when ncmds can be 0, and the
4700  * queue can still have I/O's.  This way we preserve order of biodone's.
4701  */
4702 static void
4703 st_wait_for_io(struct scsi_tape *un)
4704 {
4705 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4706 	ASSERT(mutex_owned(ST_MUTEX));
4707 	while ((un->un_ncmds) || (un->un_quef) || (un->un_runqf)) {
4708 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4709 	}
4710 }
4711 
4712 /*
4713  * This routine implements the ioctl calls.  It is called
4714  * from the device switch at normal priority.
4715  */
4716 /*ARGSUSED*/
4717 static int
4718 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4719     int *rval_p)
4720 {
4721 	int tmp, rval = 0;
4722 
4723 	GET_SOFT_STATE(dev);
4724 
4725 	ST_ENTR(ST_DEVINFO, st_ioctl);
4726 
4727 	mutex_enter(ST_MUTEX);
4728 
4729 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4730 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4731 	    "pe_flag = %d\n",
4732 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4733 	    un->un_persistence && un->un_persist_errors);
4734 
4735 	/*
4736 	 * We don't want to block on these, so let them through
4737 	 * and we don't care about setting driver states here.
4738 	 */
4739 	if ((cmd == MTIOCGETDRIVETYPE) ||
4740 	    (cmd == MTIOCGUARANTEEDORDER) ||
4741 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4742 		goto check_commands;
4743 	}
4744 
4745 	/*
4746 	 * We clear error entry stack except command
4747 	 * MTIOCGETERROR and MTIOCGET
4748 	 */
4749 	if ((cmd != MTIOCGETERROR) &&
4750 	    (cmd != MTIOCGET)) {
4751 		st_empty_error_stack(un);
4752 	}
4753 
4754 	/*
4755 	 * wait for all outstanding commands to complete, or be dequeued.
4756 	 * And because ioctl's are synchronous commands, any return value
4757 	 * after this,  will be in order
4758 	 */
4759 	st_wait_for_io(un);
4760 
4761 	/*
4762 	 * allow only a through clear errors and persistent status, and
4763 	 * status
4764 	 */
4765 	if (un->un_persistence && un->un_persist_errors) {
4766 		if ((cmd == MTIOCLRERR) ||
4767 		    (cmd == MTIOCPERSISTENT) ||
4768 		    (cmd == MTIOCGET)) {
4769 			goto check_commands;
4770 		} else {
4771 			rval = un->un_errno;
4772 			goto exit;
4773 		}
4774 	}
4775 
4776 	ASSERT(un->un_throttle != 0);
4777 	un->un_throttle = 1;	/* > 1 will never happen here */
4778 	un->un_errno = 0;	/* start clean from here */
4779 
4780 	/*
4781 	 * first and foremost, handle any ST_EOT_PENDING cases.
4782 	 * That is, if a logical eot is pending notice, notice it.
4783 	 */
4784 	if (un->un_pos.eof == ST_EOT_PENDING) {
4785 		int resid = un->un_err_resid;
4786 		uchar_t status = un->un_status;
4787 		uchar_t lastop = un->un_lastop;
4788 
4789 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4790 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4791 			    "stioctl : EIO can't space fmk(-1)\n");
4792 			rval = EIO;
4793 			goto exit;
4794 		}
4795 		un->un_lastop = lastop; /* restore last operation */
4796 		if (status == SUN_KEY_EOF) {
4797 			un->un_status = SUN_KEY_EOT;
4798 		} else {
4799 			un->un_status = status;
4800 		}
4801 		un->un_err_resid  = resid;
4802 		/* fix up block number */
4803 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4804 		/* now we're at logical eot */
4805 		un->un_pos.eof = ST_EOT;
4806 	}
4807 
4808 	/*
4809 	 * now, handle the rest of the situations
4810 	 */
4811 check_commands:
4812 	switch (cmd) {
4813 	case MTIOCGET:
4814 	{
4815 #ifdef _MULTI_DATAMODEL
4816 		/*
4817 		 * For use when a 32 bit app makes a call into a
4818 		 * 64 bit ioctl
4819 		 */
4820 		struct mtget32		mtg_local32;
4821 		struct mtget32 		*mtget_32 = &mtg_local32;
4822 #endif /* _MULTI_DATAMODEL */
4823 
4824 			/* Get tape status */
4825 		struct mtget mtg_local;
4826 		struct mtget *mtget = &mtg_local;
4827 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4828 		    "st_ioctl: MTIOCGET\n");
4829 
4830 		bzero((caddr_t)mtget, sizeof (struct mtget));
4831 		mtget->mt_erreg = un->un_status;
4832 		mtget->mt_resid = un->un_err_resid;
4833 		mtget->mt_dsreg = un->un_retry_ct;
4834 		if (un->un_err_pos.pmode == legacy) {
4835 			mtget->mt_fileno = un->un_err_pos.fileno;
4836 		} else {
4837 			mtget->mt_fileno = -1;
4838 		}
4839 		/*
4840 		 * If the value is positive fine.
4841 		 * If its negative we need to return a value based on the
4842 		 * old way if counting backwards from INF (1,000,000,000).
4843 		 */
4844 		if (un->un_err_pos.blkno >= 0) {
4845 			mtget->mt_blkno = un->un_err_pos.blkno;
4846 		} else {
4847 			mtget->mt_blkno = INF + 1 - (-un->un_err_pos.blkno);
4848 		}
4849 		mtget->mt_type = un->un_dp->type;
4850 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
4851 		if (un->un_read_pos_type != NO_POS) {
4852 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
4853 		}
4854 		if (un->un_dp->options & ST_REEL) {
4855 			mtget->mt_flags |= MTF_REEL;
4856 			mtget->mt_bf = 20;
4857 		} else {		/* 1/4" cartridges */
4858 			switch (mtget->mt_type) {
4859 			/* Emulex cartridge tape */
4860 			case MT_ISMT02:
4861 				mtget->mt_bf = 40;
4862 				break;
4863 			default:
4864 				mtget->mt_bf = 126;
4865 				break;
4866 			}
4867 		}
4868 
4869 		/*
4870 		 * If large transfers are allowed and drive options
4871 		 * has no record size limit set. Calculate blocking
4872 		 * factor from the lesser of maxbsize and maxdma.
4873 		 */
4874 		if ((un->un_allow_large_xfer) &&
4875 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
4876 			mtget->mt_bf = min(un->un_maxbsize,
4877 			    un->un_maxdma) / SECSIZE;
4878 		}
4879 
4880 		if (un->un_read_only == WORM ||
4881 		    un->un_read_only == RDWORM) {
4882 			mtget->mt_flags |= MTF_WORM_MEDIA;
4883 		}
4884 
4885 		/*
4886 		 * In persistent error mode sending a non-queued can hang
4887 		 * because this ioctl gets to be run without turning off
4888 		 * persistense. Fake the answer based on previous info.
4889 		 */
4890 		if (un->un_persistence) {
4891 			if ((un->un_HeadClean & (TAPE_ALERT_SUPPORTED |
4892 			    TAPE_SEQUENTIAL_SUPPORTED|TAPE_ALERT_NOT_SUPPORTED))
4893 			    != TAPE_ALERT_NOT_SUPPORTED) {
4894 				mtget->mt_flags |= MTF_TAPE_CLN_SUPPORTED;
4895 			}
4896 			if (un->un_HeadClean & (TAPE_PREVIOUSLY_DIRTY |
4897 			    TAPE_ALERT_STILL_DIRTY)) {
4898 				mtget->mt_flags |= MTF_TAPE_HEAD_DIRTY;
4899 			}
4900 			rval = 0;
4901 		} else {
4902 			rval = st_check_clean_bit(un);
4903 		}
4904 		if (rval == -1) {
4905 			rval = EIO;
4906 			goto exit;
4907 		} else {
4908 			mtget->mt_flags |= (ushort_t)rval;
4909 			rval = 0;
4910 		}
4911 
4912 		un->un_status = 0;		/* Reset status */
4913 		un->un_err_resid = 0;
4914 		tmp = sizeof (struct mtget);
4915 
4916 #ifdef _MULTI_DATAMODEL
4917 
4918 		switch (ddi_model_convert_from(flag & FMODELS)) {
4919 		case DDI_MODEL_ILP32:
4920 			/*
4921 			 * Convert 64 bit back to 32 bit before doing
4922 			 * copyout. This is what the ILP32 app expects.
4923 			 */
4924 			mtget_32->mt_erreg = 	mtget->mt_erreg;
4925 			mtget_32->mt_resid = 	mtget->mt_resid;
4926 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
4927 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
4928 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
4929 			mtget_32->mt_type =  	mtget->mt_type;
4930 			mtget_32->mt_flags = 	mtget->mt_flags;
4931 			mtget_32->mt_bf = 	mtget->mt_bf;
4932 
4933 			if (ddi_copyout(mtget_32, (void *)arg,
4934 			    sizeof (struct mtget32), flag)) {
4935 				rval = EFAULT;
4936 			}
4937 			break;
4938 
4939 		case DDI_MODEL_NONE:
4940 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4941 				rval = EFAULT;
4942 			}
4943 			break;
4944 		}
4945 #else /* ! _MULTI_DATAMODE */
4946 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4947 			rval = EFAULT;
4948 		}
4949 #endif /* _MULTI_DATAMODE */
4950 
4951 		break;
4952 	}
4953 	case MTIOCGETERROR:
4954 			/*
4955 			 * get error entry from error stack
4956 			 */
4957 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4958 			    "st_ioctl: MTIOCGETERROR\n");
4959 
4960 			rval = st_get_error_entry(un, arg, flag);
4961 
4962 			break;
4963 
4964 	case MTIOCSTATE:
4965 		{
4966 			/*
4967 			 * return when media presence matches state
4968 			 */
4969 			enum mtio_state state;
4970 
4971 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4972 			    "st_ioctl: MTIOCSTATE\n");
4973 
4974 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
4975 				rval = EFAULT;
4976 
4977 			mutex_exit(ST_MUTEX);
4978 
4979 			rval = st_check_media(dev, state);
4980 
4981 			mutex_enter(ST_MUTEX);
4982 
4983 			if (rval != 0) {
4984 				break;
4985 			}
4986 
4987 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
4988 			    sizeof (int), flag))
4989 				rval = EFAULT;
4990 			break;
4991 
4992 		}
4993 
4994 	case MTIOCGETDRIVETYPE:
4995 		{
4996 #ifdef _MULTI_DATAMODEL
4997 		/*
4998 		 * For use when a 32 bit app makes a call into a
4999 		 * 64 bit ioctl
5000 		 */
5001 		struct mtdrivetype_request32	mtdtrq32;
5002 #endif /* _MULTI_DATAMODEL */
5003 
5004 			/*
5005 			 * return mtdrivetype
5006 			 */
5007 			struct mtdrivetype_request mtdtrq;
5008 			struct mtdrivetype mtdrtyp;
5009 			struct mtdrivetype *mtdt = &mtdrtyp;
5010 			struct st_drivetype *stdt = un->un_dp;
5011 
5012 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5013 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
5014 
5015 #ifdef _MULTI_DATAMODEL
5016 		switch (ddi_model_convert_from(flag & FMODELS)) {
5017 		case DDI_MODEL_ILP32:
5018 		{
5019 			if (ddi_copyin((void *)arg, &mtdtrq32,
5020 			    sizeof (struct mtdrivetype_request32), flag)) {
5021 				rval = EFAULT;
5022 				break;
5023 			}
5024 			mtdtrq.size = mtdtrq32.size;
5025 			mtdtrq.mtdtp =
5026 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
5027 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5028 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
5029 			break;
5030 		}
5031 		case DDI_MODEL_NONE:
5032 			if (ddi_copyin((void *)arg, &mtdtrq,
5033 			    sizeof (struct mtdrivetype_request), flag)) {
5034 				rval = EFAULT;
5035 				break;
5036 			}
5037 			break;
5038 		}
5039 
5040 #else /* ! _MULTI_DATAMODEL */
5041 		if (ddi_copyin((void *)arg, &mtdtrq,
5042 		    sizeof (struct mtdrivetype_request), flag)) {
5043 			rval = EFAULT;
5044 			break;
5045 		}
5046 #endif /* _MULTI_DATAMODEL */
5047 
5048 			/*
5049 			 * if requested size is < 0 then return
5050 			 * error.
5051 			 */
5052 			if (mtdtrq.size < 0) {
5053 				rval = EINVAL;
5054 				break;
5055 			}
5056 			bzero(mtdt, sizeof (struct mtdrivetype));
5057 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
5058 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
5059 			mtdt->type = stdt->type;
5060 			mtdt->bsize = stdt->bsize;
5061 			mtdt->options = stdt->options;
5062 			mtdt->max_rretries = stdt->max_rretries;
5063 			mtdt->max_wretries = stdt->max_wretries;
5064 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5065 				mtdt->densities[tmp] = stdt->densities[tmp];
5066 			}
5067 			mtdt->default_density = stdt->default_density;
5068 			/*
5069 			 * Speed hasn't been used since the hayday of reel tape.
5070 			 * For all drives not setting the option ST_KNOWS_MEDIA
5071 			 * the speed member renamed to mediatype are zeros.
5072 			 * Those drives that have ST_KNOWS_MEDIA set use the
5073 			 * new mediatype member which is used to figure the
5074 			 * type of media loaded.
5075 			 *
5076 			 * So as to not break applications speed in the
5077 			 * mtdrivetype structure is not renamed.
5078 			 */
5079 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5080 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
5081 			}
5082 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
5083 			mtdt->io_timeout = stdt->io_timeout;
5084 			mtdt->rewind_timeout = stdt->rewind_timeout;
5085 			mtdt->space_timeout = stdt->space_timeout;
5086 			mtdt->load_timeout = stdt->load_timeout;
5087 			mtdt->unload_timeout = stdt->unload_timeout;
5088 			mtdt->erase_timeout = stdt->erase_timeout;
5089 
5090 			/*
5091 			 * Limit the maximum length of the result to
5092 			 * sizeof (struct mtdrivetype).
5093 			 */
5094 			tmp = sizeof (struct mtdrivetype);
5095 			if (mtdtrq.size < tmp)
5096 				tmp = mtdtrq.size;
5097 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
5098 				rval = EFAULT;
5099 			}
5100 			break;
5101 		}
5102 	case MTIOCPERSISTENT:
5103 
5104 		if (ddi_copyin((void *)arg, &tmp, sizeof (tmp), flag)) {
5105 			rval = EFAULT;
5106 			break;
5107 		}
5108 
5109 		if (tmp) {
5110 			st_turn_pe_on(un);
5111 		} else {
5112 			st_turn_pe_off(un);
5113 		}
5114 
5115 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5116 		    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
5117 		    un->un_persistence);
5118 
5119 		break;
5120 
5121 	case MTIOCPERSISTENTSTATUS:
5122 		tmp = (int)un->un_persistence;
5123 
5124 		if (ddi_copyout(&tmp, (void *)arg, sizeof (tmp), flag)) {
5125 			rval = EFAULT;
5126 		}
5127 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5128 		    "st_ioctl: MTIOCPERSISTENTSTATUS:persistence = %d\n",
5129 		    un->un_persistence);
5130 
5131 		break;
5132 
5133 	case MTIOCLRERR:
5134 		{
5135 			/* clear persistent errors */
5136 
5137 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5138 			    "st_ioctl: MTIOCLRERR\n");
5139 
5140 			st_clear_pe(un);
5141 
5142 			break;
5143 		}
5144 
5145 	case MTIOCGUARANTEEDORDER:
5146 		{
5147 			/*
5148 			 * this is just a holder to make a valid ioctl and
5149 			 * it won't be in any earlier release
5150 			 */
5151 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5152 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
5153 
5154 			break;
5155 		}
5156 
5157 	case MTIOCRESERVE:
5158 		{
5159 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5160 			    "st_ioctl: MTIOCRESERVE\n");
5161 
5162 			/*
5163 			 * Check if Reserve/Release is supported.
5164 			 */
5165 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5166 				rval = ENOTTY;
5167 				break;
5168 			}
5169 
5170 			rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5171 
5172 			if (rval == 0) {
5173 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
5174 			}
5175 			break;
5176 		}
5177 
5178 	case MTIOCRELEASE:
5179 		{
5180 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5181 			    "st_ioctl: MTIOCRELEASE\n");
5182 
5183 			/*
5184 			 * Check if Reserve/Release is supported.
5185 			 */
5186 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5187 				rval = ENOTTY;
5188 				break;
5189 			}
5190 
5191 			/*
5192 			 * Used to just clear ST_PRESERVE_RESERVE which
5193 			 * made the reservation release at next close.
5194 			 * As the user may have opened and then done a
5195 			 * persistant reservation we now need to drop
5196 			 * the reservation without closing if the user
5197 			 * attempts to do this.
5198 			 */
5199 			rval = st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
5200 
5201 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5202 
5203 			break;
5204 		}
5205 
5206 	case MTIOCFORCERESERVE:
5207 	{
5208 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5209 		    "st_ioctl: MTIOCFORCERESERVE\n");
5210 
5211 		/*
5212 		 * Check if Reserve/Release is supported.
5213 		 */
5214 		if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5215 			rval = ENOTTY;
5216 			break;
5217 		}
5218 		/*
5219 		 * allow only super user to run this.
5220 		 */
5221 		if (drv_priv(cred_p) != 0) {
5222 			rval = EPERM;
5223 			break;
5224 		}
5225 		/*
5226 		 * Throw away reserve,
5227 		 * not using test-unit-ready
5228 		 * since reserve can succeed without tape being
5229 		 * present in the drive.
5230 		 */
5231 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5232 
5233 		rval = st_take_ownership(un);
5234 
5235 		break;
5236 	}
5237 
5238 	case USCSICMD:
5239 	{
5240 		cred_t	*cr;
5241 
5242 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5243 		    "st_ioctl: USCSICMD\n");
5244 
5245 		cr = ddi_get_cred();
5246 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5247 			rval = EPERM;
5248 		} else {
5249 			rval = st_uscsi_cmd(un, (struct uscsi_cmd *)arg, flag);
5250 		}
5251 		break;
5252 	}
5253 	case MTIOCTOP:
5254 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5255 		    "st_ioctl: MTIOCTOP\n");
5256 		rval = st_mtioctop(un, arg, flag);
5257 		break;
5258 
5259 	case MTIOCLTOP:
5260 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5261 		    "st_ioctl: MTIOLCTOP\n");
5262 		rval = st_mtiocltop(un, arg, flag);
5263 		break;
5264 
5265 	case MTIOCREADIGNOREILI:
5266 		{
5267 			int set_ili;
5268 
5269 			if (ddi_copyin((void *)arg, &set_ili,
5270 			    sizeof (set_ili), flag)) {
5271 				rval = EFAULT;
5272 				break;
5273 			}
5274 
5275 			if (un->un_bsize) {
5276 				rval = ENOTTY;
5277 				break;
5278 			}
5279 
5280 			switch (set_ili) {
5281 			case 0:
5282 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5283 				break;
5284 
5285 			case 1:
5286 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5287 				break;
5288 
5289 			default:
5290 				rval = EINVAL;
5291 				break;
5292 			}
5293 			break;
5294 		}
5295 
5296 	case MTIOCREADIGNOREEOFS:
5297 		{
5298 			int ignore_eof;
5299 
5300 			if (ddi_copyin((void *)arg, &ignore_eof,
5301 			    sizeof (ignore_eof), flag)) {
5302 				rval = EFAULT;
5303 				break;
5304 			}
5305 
5306 			if (!(un->un_dp->options & ST_REEL)) {
5307 				rval = ENOTTY;
5308 				break;
5309 			}
5310 
5311 			switch (ignore_eof) {
5312 			case 0:
5313 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5314 				break;
5315 
5316 			case 1:
5317 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5318 				break;
5319 
5320 			default:
5321 				rval = EINVAL;
5322 				break;
5323 			}
5324 			break;
5325 		}
5326 
5327 	case MTIOCSHORTFMK:
5328 	{
5329 		int short_fmk;
5330 
5331 		if (ddi_copyin((void *)arg, &short_fmk,
5332 		    sizeof (short_fmk), flag)) {
5333 			rval = EFAULT;
5334 			break;
5335 		}
5336 
5337 		switch (un->un_dp->type) {
5338 		case ST_TYPE_EXB8500:
5339 		case ST_TYPE_EXABYTE:
5340 			if (!short_fmk) {
5341 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5342 			} else if (short_fmk == 1) {
5343 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5344 			} else {
5345 				rval = EINVAL;
5346 			}
5347 			break;
5348 
5349 		default:
5350 			rval = ENOTTY;
5351 			break;
5352 		}
5353 		break;
5354 	}
5355 
5356 	case MTIOCGETPOS:
5357 		rval = st_update_block_pos(un, st_cmd, 0);
5358 		if (rval == 0) {
5359 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5360 			    sizeof (tapepos_t), flag)) {
5361 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5362 				    "MTIOCGETPOS copy out failed\n");
5363 				rval = EFAULT;
5364 			}
5365 		}
5366 		break;
5367 
5368 	case MTIOCRESTPOS:
5369 	{
5370 		tapepos_t dest;
5371 
5372 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5373 		    flag) != 0) {
5374 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5375 			    "MTIOCRESTPOS copy in failed\n");
5376 			rval = EFAULT;
5377 			break;
5378 		}
5379 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &dest);
5380 		if (rval != 0) {
5381 			rval = EIO;
5382 		}
5383 		break;
5384 	}
5385 	default:
5386 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5387 		    "st_ioctl: unknown ioctl\n");
5388 		rval = ENOTTY;
5389 	}
5390 
5391 exit:
5392 	if (!(un->un_persistence && un->un_persist_errors)) {
5393 		un->un_errno = rval;
5394 	}
5395 
5396 	mutex_exit(ST_MUTEX);
5397 
5398 	return (rval);
5399 }
5400 
5401 
5402 /*
5403  * do some MTIOCTOP tape operations
5404  */
5405 static int
5406 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5407 {
5408 #ifdef _MULTI_DATAMODEL
5409 	/*
5410 	 * For use when a 32 bit app makes a call into a
5411 	 * 64 bit ioctl
5412 	 */
5413 	struct mtop32	mtop_32_for_64;
5414 #endif /* _MULTI_DATAMODEL */
5415 	struct mtop passed;
5416 	struct mtlop local;
5417 	int rval = 0;
5418 
5419 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5420 
5421 	ASSERT(mutex_owned(ST_MUTEX));
5422 
5423 #ifdef _MULTI_DATAMODEL
5424 	switch (ddi_model_convert_from(flag & FMODELS)) {
5425 	case DDI_MODEL_ILP32:
5426 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5427 		    sizeof (struct mtop32), flag)) {
5428 			return (EFAULT);
5429 		}
5430 		local.mt_op = mtop_32_for_64.mt_op;
5431 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5432 		break;
5433 
5434 	case DDI_MODEL_NONE:
5435 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5436 			return (EFAULT);
5437 		}
5438 		local.mt_op = passed.mt_op;
5439 		/* prevent sign extention */
5440 		local.mt_count = (UINT32_MAX & passed.mt_count);
5441 		break;
5442 	}
5443 
5444 #else /* ! _MULTI_DATAMODEL */
5445 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5446 		return (EFAULT);
5447 	}
5448 	local.mt_op = passed.mt_op;
5449 	/* prevent sign extention */
5450 	local.mt_count = (UINT32_MAX & passed.mt_count);
5451 #endif /* _MULTI_DATAMODEL */
5452 
5453 	rval = st_do_mtioctop(un, &local);
5454 
5455 #ifdef _MULTI_DATAMODEL
5456 	switch (ddi_model_convert_from(flag & FMODELS)) {
5457 	case DDI_MODEL_ILP32:
5458 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5459 			rval = ERANGE;
5460 			break;
5461 		}
5462 		/*
5463 		 * Convert 64 bit back to 32 bit before doing
5464 		 * copyout. This is what the ILP32 app expects.
5465 		 */
5466 		mtop_32_for_64.mt_op = local.mt_op;
5467 		mtop_32_for_64.mt_count = local.mt_count;
5468 
5469 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5470 		    sizeof (struct mtop32), flag)) {
5471 			rval = EFAULT;
5472 		}
5473 		break;
5474 
5475 	case DDI_MODEL_NONE:
5476 		passed.mt_count = local.mt_count;
5477 		passed.mt_op = local.mt_op;
5478 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5479 			rval = EFAULT;
5480 		}
5481 		break;
5482 	}
5483 #else /* ! _MULTI_DATAMODE */
5484 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5485 		rval = ERANGE;
5486 	} else {
5487 		passed.mt_op = local.mt_op;
5488 		passed.mt_count = local.mt_count;
5489 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5490 			rval = EFAULT;
5491 		}
5492 	}
5493 #endif /* _MULTI_DATAMODE */
5494 
5495 
5496 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5497 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5498 	    un->un_pos.blkno, un->un_pos.eof);
5499 
5500 	if (un->un_pos.pmode == invalid) {
5501 		un->un_density_known = 0;
5502 	}
5503 
5504 	ASSERT(mutex_owned(ST_MUTEX));
5505 	return (rval);
5506 }
5507 
5508 static int
5509 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5510 {
5511 	struct mtlop local;
5512 	int rval;
5513 
5514 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5515 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5516 		return (EFAULT);
5517 	}
5518 
5519 	rval = st_do_mtioctop(un, &local);
5520 
5521 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5522 		rval = EFAULT;
5523 	}
5524 	return (rval);
5525 }
5526 
5527 
5528 static int
5529 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5530 {
5531 	dev_t dev = un->un_dev;
5532 	int savefile;
5533 	int rval = 0;
5534 
5535 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5536 
5537 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5538 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5539 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5540 	    "fileno=%x, blkno=%x, eof=%x\n",
5541 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5542 
5543 	un->un_status = 0;
5544 
5545 	/*
5546 	 * if we are going to mess with a tape, we have to make sure we have
5547 	 * one and are not offline (i.e. no tape is initialized).  We let
5548 	 * commands pass here that don't actually touch the tape, except for
5549 	 * loading and initialization (rewinding).
5550 	 */
5551 	if (un->un_state == ST_STATE_OFFLINE) {
5552 		switch (mtop->mt_op) {
5553 		case MTLOAD:
5554 		case MTNOP:
5555 			/*
5556 			 * We don't want strategy calling st_tape_init here,
5557 			 * so, change state
5558 			 */
5559 			un->un_state = ST_STATE_INITIALIZING;
5560 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5561 			    "st_do_mtioctop : OFFLINE state = %d\n",
5562 			    un->un_state);
5563 			break;
5564 		default:
5565 			/*
5566 			 * reinitialize by normal means
5567 			 */
5568 			rval = st_tape_init(un);
5569 			if (rval) {
5570 				un->un_state = ST_STATE_INITIALIZING;
5571 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5572 				    "st_do_mtioctop : OFFLINE init failure ");
5573 				un->un_state = ST_STATE_OFFLINE;
5574 				un->un_pos.pmode = invalid;
5575 				if (rval != EACCES) {
5576 					rval = EIO;
5577 				}
5578 				return (rval);
5579 			}
5580 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5581 			break;
5582 		}
5583 	}
5584 
5585 	/*
5586 	 * If the file position is invalid, allow only those
5587 	 * commands that properly position the tape and fail
5588 	 * the rest with EIO
5589 	 */
5590 	if (un->un_pos.pmode == invalid) {
5591 		switch (mtop->mt_op) {
5592 		case MTWEOF:
5593 		case MTRETEN:
5594 		case MTERASE:
5595 		case MTEOM:
5596 		case MTFSF:
5597 		case MTFSR:
5598 		case MTBSF:
5599 		case MTNBSF:
5600 		case MTBSR:
5601 		case MTSRSZ:
5602 		case MTGRSZ:
5603 		case MTSEEK:
5604 		case MTBSSF:
5605 		case MTFSSF:
5606 			return (EIO);
5607 			/* NOTREACHED */
5608 		case MTREW:
5609 		case MTLOAD:
5610 		case MTOFFL:
5611 		case MTNOP:
5612 		case MTTELL:
5613 		case MTLOCK:
5614 		case MTUNLOCK:
5615 			break;
5616 
5617 		default:
5618 			return (ENOTTY);
5619 			/* NOTREACHED */
5620 		}
5621 	}
5622 
5623 	switch (mtop->mt_op) {
5624 	case MTERASE:
5625 		/*
5626 		 * MTERASE rewinds the tape, erase it completely, and returns
5627 		 * to the beginning of the tape
5628 		 */
5629 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5630 			un->un_status = KEY_WRITE_PROTECT;
5631 			un->un_err_resid = mtop->mt_count;
5632 			COPY_POS(&un->un_err_pos, &un->un_pos);
5633 			return (EACCES);
5634 		}
5635 		if (un->un_dp->options & ST_REEL) {
5636 			un->un_fmneeded = 2;
5637 		} else {
5638 			un->un_fmneeded = 1;
5639 		}
5640 		mtop->mt_count = mtop->mt_count ? 1 : 0;
5641 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5642 		    st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
5643 		    st_cmd(un, SCMD_ERASE, mtop->mt_count, SYNC_CMD)) {
5644 			un->un_pos.pmode = invalid;
5645 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5646 			    "st_do_mtioctop : EIO space or erase or "
5647 			    "check den)\n");
5648 			rval = EIO;
5649 		} else {
5650 			/* QIC and helical scan rewind after erase */
5651 			if (un->un_dp->options & ST_REEL) {
5652 				(void) st_cmd(un, SCMD_REWIND, 0, ASYNC_CMD);
5653 			}
5654 		}
5655 		break;
5656 
5657 	case MTWEOF:
5658 		/*
5659 		 * write an end-of-file record
5660 		 */
5661 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5662 			un->un_status = KEY_WRITE_PROTECT;
5663 			un->un_err_resid = mtop->mt_count;
5664 			COPY_POS(&un->un_err_pos, &un->un_pos);
5665 			return (EACCES);
5666 		}
5667 
5668 		/*
5669 		 * zero count means just flush buffers
5670 		 * negative count is not permitted
5671 		 */
5672 		if (mtop->mt_count < 0) {
5673 			return (EINVAL);
5674 		}
5675 
5676 		/* Not on worm */
5677 		if (un->un_read_only == RDWR) {
5678 			un->un_test_append = 1;
5679 		}
5680 
5681 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5682 			if (st_determine_density(un, B_WRITE)) {
5683 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5684 				    "st_do_mtioctop : EIO : MTWEOF can't "
5685 				    "determine density");
5686 				return (EIO);
5687 			}
5688 		}
5689 
5690 		rval = st_write_fm(dev, (int)mtop->mt_count);
5691 		if ((rval != 0) && (rval != EACCES)) {
5692 			/*
5693 			 * Failure due to something other than illegal
5694 			 * request results in loss of state (st_intr).
5695 			 */
5696 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5697 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5698 			    "file mark");
5699 			rval = EIO;
5700 		}
5701 		break;
5702 
5703 	case MTRETEN:
5704 		/*
5705 		 * retension the tape
5706 		 */
5707 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5708 		    st_cmd(un, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5709 			un->un_pos.pmode = invalid;
5710 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5711 			    "st_do_mtioctop : EIO : MTRETEN ");
5712 			rval = EIO;
5713 		}
5714 		break;
5715 
5716 	case MTREW:
5717 		/*
5718 		 * rewind  the tape
5719 		 */
5720 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5721 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5722 			    "st_do_mtioctop : EIO:MTREW check "
5723 			    "density/wfm failed");
5724 			return (EIO);
5725 		}
5726 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
5727 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5728 			    "st_do_mtioctop : EIO : MTREW ");
5729 			rval = EIO;
5730 		}
5731 		break;
5732 
5733 	case MTOFFL:
5734 		/*
5735 		 * rewinds, and, if appropriate, takes the device offline by
5736 		 * unloading the tape
5737 		 */
5738 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5739 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5740 			    "st_do_mtioctop :EIO:MTOFFL check "
5741 			    "density/wfm failed");
5742 			return (EIO);
5743 		}
5744 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
5745 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5746 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5747 			    "st_do_mtioctop : EIO : MTOFFL");
5748 			return (EIO);
5749 		}
5750 		un->un_pos.eof = ST_NO_EOF;
5751 		un->un_laststate = un->un_state;
5752 		un->un_state = ST_STATE_OFFLINE;
5753 		un->un_mediastate = MTIO_EJECTED;
5754 		break;
5755 
5756 	case MTLOAD:
5757 		/*
5758 		 * This is to load a tape into the drive
5759 		 * Note that if the tape is not loaded, the device will have
5760 		 * to be opened via O_NDELAY or O_NONBLOCK.
5761 		 */
5762 		/*
5763 		 * Let's try and clean things up, if we are not
5764 		 * initializing, and then send in the load command, no
5765 		 * matter what.
5766 		 *
5767 		 * load after a media change by the user.
5768 		 */
5769 
5770 		if (un->un_state > ST_STATE_INITIALIZING) {
5771 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5772 		}
5773 		rval = st_cmd(un, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5774 		/* Load command to a drive that doesn't support load */
5775 		if ((rval == EIO) &&
5776 		    ((un->un_status == KEY_NOT_READY) &&
5777 			/* Medium not present */
5778 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5779 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5780 		    (un->un_dp->type == MT_ISSTK9840) &&
5781 			/* CSL not present */
5782 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5783 			rval = ENOTTY;
5784 			break;
5785 		} else if (rval != EACCES && rval != 0) {
5786 			rval = EIO;
5787 		}
5788 		if (rval) {
5789 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5790 			    "st_do_mtioctop : %s : MTLOAD\n",
5791 			    rval == EACCES ? "EACCES" : "EIO");
5792 			/*
5793 			 * If load tape fails, who knows what happened...
5794 			 */
5795 			un->un_pos.pmode = invalid;
5796 			break;
5797 		}
5798 
5799 		/*
5800 		 * reset all counters appropriately using rewind, as if LOAD
5801 		 * succeeds, we are at BOT
5802 		 */
5803 		un->un_state = ST_STATE_INITIALIZING;
5804 
5805 		rval = st_tape_init(un);
5806 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5807 			rval = 0;
5808 			break;
5809 		}
5810 
5811 		if (rval != 0) {
5812 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5813 			    "st_do_mtioctop : EIO : MTLOAD calls "
5814 			    "st_tape_init\n");
5815 			rval = EIO;
5816 			un->un_state = ST_STATE_OFFLINE;
5817 		}
5818 
5819 		break;
5820 
5821 	case MTNOP:
5822 		un->un_status = 0;		/* Reset status */
5823 		un->un_err_resid = 0;
5824 		mtop->mt_count = MTUNIT(dev);
5825 		break;
5826 
5827 	case MTEOM:
5828 		/*
5829 		 * positions the tape at a location just after the last file
5830 		 * written on the tape. For cartridge and 8 mm, this after
5831 		 * the last file mark; for reel, this is inbetween the two
5832 		 * last 2 file marks
5833 		 */
5834 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5835 		    (un->un_lastop == ST_OP_WRITE) ||
5836 		    (un->un_lastop == ST_OP_WEOF)) {
5837 			/*
5838 			 * If the command wants to move to logical end
5839 			 * of media, and we're already there, we're done.
5840 			 * If we were at logical eot, we reset the state
5841 			 * to be *not* at logical eot.
5842 			 *
5843 			 * If we're at physical or logical eot, we prohibit
5844 			 * forward space operations (unconditionally).
5845 			 *
5846 			 * Also if the last operation was a write of any
5847 			 * kind the tape is at EOD.
5848 			 */
5849 			return (0);
5850 		}
5851 		/*
5852 		 * physical tape position may not be what we've been
5853 		 * telling the user; adjust the request accordingly
5854 		 */
5855 		if (IN_EOF(un->un_pos)) {
5856 			un->un_pos.fileno++;
5857 			un->un_pos.blkno = 0;
5858 		}
5859 
5860 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
5861 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5862 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
5863 			    " failed");
5864 			return (EIO);
5865 		}
5866 
5867 		/*
5868 		 * st_find_eod() returns the last fileno we knew about;
5869 		 */
5870 		savefile = st_find_eod(un);
5871 
5872 		if ((un->un_status != KEY_BLANK_CHECK) &&
5873 		    (un->un_status != SUN_KEY_EOT)) {
5874 			un->un_pos.pmode = invalid;
5875 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5876 			    "st_do_mtioctop : EIO : MTEOM status check failed");
5877 			rval = EIO;
5878 		} else {
5879 			/*
5880 			 * For 1/2" reel tapes assume logical EOT marked
5881 			 * by two file marks or we don't care that we may
5882 			 * be extending the last file on the tape.
5883 			 */
5884 			if (un->un_dp->options & ST_REEL) {
5885 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
5886 					un->un_pos.pmode = invalid;
5887 					ST_DEBUG2(ST_DEVINFO, st_label,
5888 					    SCSI_DEBUG,
5889 					    "st_do_mtioctop : EIO : MTEOM space"
5890 					    " cmd failed");
5891 					rval = EIO;
5892 					break;
5893 				}
5894 				/*
5895 				 * Fix up the block number.
5896 				 */
5897 				un->un_pos.blkno = 0;
5898 				un->un_err_pos.blkno = 0;
5899 			}
5900 			un->un_err_resid = 0;
5901 			un->un_pos.fileno = savefile;
5902 			un->un_pos.eof = ST_EOT;
5903 		}
5904 		un->un_status = 0;
5905 		break;
5906 
5907 	case MTFSF:
5908 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
5909 		break;
5910 
5911 	case MTFSR:
5912 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
5913 		break;
5914 
5915 	case MTBSF:
5916 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
5917 		break;
5918 
5919 	case MTNBSF:
5920 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
5921 		break;
5922 
5923 	case MTBSR:
5924 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
5925 		break;
5926 
5927 	case MTBSSF:
5928 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
5929 		break;
5930 
5931 	case MTFSSF:
5932 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
5933 		break;
5934 
5935 	case MTSRSZ:
5936 
5937 		/*
5938 		 * Set record-size to that sent by user
5939 		 * Check to see if there is reason that the requested
5940 		 * block size should not be set.
5941 		 */
5942 
5943 		/* If requesting variable block size is it ok? */
5944 		if ((mtop->mt_count == 0) &&
5945 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
5946 			return (ENOTTY);
5947 		}
5948 
5949 		/*
5950 		 * If requested block size is not variable "0",
5951 		 * is it less then minimum.
5952 		 */
5953 		if ((mtop->mt_count != 0) &&
5954 		    (mtop->mt_count < un->un_minbsize)) {
5955 			return (EINVAL);
5956 		}
5957 
5958 		/* Is the requested block size more then maximum */
5959 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
5960 		    (un->un_maxbsize != 0)) {
5961 			return (EINVAL);
5962 		}
5963 
5964 		/* Is requested block size a modulus the device likes */
5965 		if ((mtop->mt_count % un->un_data_mod) != 0) {
5966 			return (EINVAL);
5967 		}
5968 
5969 		if (st_change_block_size(un, (uint32_t)mtop->mt_count) != 0) {
5970 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5971 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
5972 			return (EIO);
5973 		}
5974 
5975 		return (0);
5976 
5977 	case MTGRSZ:
5978 		/*
5979 		 * Get record-size to the user
5980 		 */
5981 		mtop->mt_count = un->un_bsize;
5982 		rval = 0;
5983 		break;
5984 
5985 	case MTTELL:
5986 		rval = st_update_block_pos(un, st_cmd, 0);
5987 		mtop->mt_count = un->un_pos.lgclblkno;
5988 		break;
5989 
5990 	case MTSEEK:
5991 		rval = st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
5992 		    (uint64_t)mtop->mt_count, un->un_pos.partition);
5993 		/*
5994 		 * This bit of magic make mt print the actual position if
5995 		 * the resulting position was not what was asked for.
5996 		 */
5997 		if (rval == ESPIPE) {
5998 			rval = EIO;
5999 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
6000 				mtop->mt_op = MTTELL;
6001 				mtop->mt_count = un->un_pos.lgclblkno;
6002 			}
6003 		}
6004 		break;
6005 
6006 	case MTLOCK:
6007 		if (st_cmd(un, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
6008 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6009 			    "st_do_mtioctop : EIO : MTLOCK");
6010 			rval = EIO;
6011 		}
6012 		break;
6013 
6014 	case MTUNLOCK:
6015 		if (st_cmd(un, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
6016 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6017 			    "st_do_mtioctop : EIO : MTUNLOCK");
6018 			rval = EIO;
6019 		}
6020 		break;
6021 
6022 	default:
6023 		rval = ENOTTY;
6024 	}
6025 
6026 	return (rval);
6027 }
6028 
6029 
6030 /*
6031  * Run a command for uscsi ioctl.
6032  */
6033 static int
6034 st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
6035 {
6036 	struct uscsi_cmd	*uscmd;
6037 	struct buf	*bp;
6038 	enum uio_seg	uioseg;
6039 	int	offline_state = 0;
6040 	int	err = 0;
6041 	dev_t dev = un->un_dev;
6042 
6043 	ST_FUNC(ST_DEVINFO, st_uscsi_cmd);
6044 
6045 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6046 	    "st_uscsi_cmd(dev = 0x%lx)\n", un->un_dev);
6047 
6048 	ASSERT(mutex_owned(ST_MUTEX));
6049 
6050 	/*
6051 	 * We really don't know what commands are coming in here and
6052 	 * we don't want to limit the commands coming in.
6053 	 *
6054 	 * If st_tape_init() gets called from st_strategy(), then we
6055 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
6056 	 * which it never will, as we set it below.  To prevent
6057 	 * st_tape_init() from getting called, we have to set state to other
6058 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
6059 	 * achieves this purpose already.
6060 	 *
6061 	 * We use offline_state to preserve the OFFLINE state, if it exists,
6062 	 * so other entry points to the driver might have the chance to call
6063 	 * st_tape_init().
6064 	 */
6065 	if (un->un_state == ST_STATE_OFFLINE) {
6066 		un->un_laststate = ST_STATE_OFFLINE;
6067 		un->un_state = ST_STATE_INITIALIZING;
6068 		offline_state = 1;
6069 	}
6070 
6071 	mutex_exit(ST_MUTEX);
6072 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag, ROUTE, &uscmd);
6073 	mutex_enter(ST_MUTEX);
6074 	if (err != 0) {
6075 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6076 		    "st_uscsi_cmd: scsi_uscsi_alloc_and_copyin failed\n");
6077 		goto exit;
6078 	}
6079 
6080 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
6081 
6082 	/* check to see if this command requires the drive to be reserved */
6083 	if (uscmd->uscsi_cdb != NULL) {
6084 		err = st_check_cdb_for_need_to_reserve(un,
6085 		    (uchar_t *)uscmd->uscsi_cdb);
6086 		if (err) {
6087 			goto exit_free;
6088 		}
6089 		/*
6090 		 * If this is a space command we need to save the starting
6091 		 * point so we can retry from there if the command fails.
6092 		 */
6093 		if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6094 		    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) {
6095 			(void) st_update_block_pos(un, st_cmd, 0);
6096 		}
6097 	}
6098 
6099 	/*
6100 	 * Forground should not be doing anything while recovery is active.
6101 	 */
6102 	ASSERT(un->un_recov_buf_busy == 0);
6103 
6104 	/*
6105 	 * Get buffer resources...
6106 	 */
6107 	while (un->un_sbuf_busy)
6108 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6109 	un->un_sbuf_busy = 1;
6110 
6111 #ifdef STDEBUG
6112 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0x7) > 6) {
6113 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
6114 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6115 		    "uscsi cdb", uscmd->uscsi_cdb);
6116 		if (uscmd->uscsi_buflen) {
6117 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6118 			    "uscsi %s of %ld bytes %s %s space\n",
6119 			    (rw == B_READ) ? rd_str : wr_str,
6120 			    uscmd->uscsi_buflen,
6121 			    (rw == B_READ) ? "to" : "from",
6122 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
6123 		}
6124 	}
6125 #endif /* STDEBUG */
6126 
6127 	/*
6128 	 * Although st_uscsi_cmd() never makes use of these
6129 	 * now, we are just being safe and consistent.
6130 	 */
6131 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
6132 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
6133 
6134 	un->un_srqbufp = uscmd->uscsi_rqbuf;
6135 	bp = un->un_sbufp;
6136 	bzero(bp, sizeof (buf_t));
6137 	if (uscmd->uscsi_cdb != NULL) {
6138 		bp->b_forw = (struct buf *)(uintptr_t)uscmd->uscsi_cdb[0];
6139 	}
6140 	bp->b_back = (struct buf *)uscmd;
6141 
6142 	mutex_exit(ST_MUTEX);
6143 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, st_strategy, bp, NULL);
6144 	mutex_enter(ST_MUTEX);
6145 
6146 	/*
6147 	 * If scsi reset successful, don't write any filemarks.
6148 	 */
6149 	if ((err == 0) && (uscmd->uscsi_flags &
6150 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
6151 		un->un_fmneeded = 0;
6152 	}
6153 
6154 exit_free:
6155 	/*
6156 	 * Free resources
6157 	 */
6158 	un->un_sbuf_busy = 0;
6159 	un->un_srqbufp = NULL;
6160 
6161 	/*
6162 	 * If was a space command need to update logical block position.
6163 	 * If the command failed such that positioning is invalid, Don't
6164 	 * update the position as the user must do this to validate the
6165 	 * position for data protection.
6166 	 */
6167 	if ((uscmd->uscsi_cdb != NULL) &&
6168 	    ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6169 	    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) &&
6170 	    (un->un_pos.pmode != invalid)) {
6171 		un->un_running.pmode = invalid;
6172 		(void) st_update_block_pos(un, st_cmd, 1);
6173 		/*
6174 		 * Set running position to invalid so it updates on the
6175 		 * next command.
6176 		 */
6177 		un->un_running.pmode = invalid;
6178 	}
6179 	cv_signal(&un->un_sbuf_cv);
6180 	mutex_exit(ST_MUTEX);
6181 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
6182 	mutex_enter(ST_MUTEX);
6183 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6184 	    "st_uscsi_cmd returns 0x%x\n", err);
6185 
6186 exit:
6187 	/* don't lose offline state */
6188 	if (offline_state) {
6189 		un->un_state = ST_STATE_OFFLINE;
6190 	}
6191 
6192 	ASSERT(mutex_owned(ST_MUTEX));
6193 	return (err);
6194 }
6195 
6196 static int
6197 st_write_fm(dev_t dev, int wfm)
6198 {
6199 	int i;
6200 	int rval;
6201 
6202 	GET_SOFT_STATE(dev);
6203 
6204 	ST_FUNC(ST_DEVINFO, st_write_fm);
6205 
6206 	ASSERT(mutex_owned(ST_MUTEX));
6207 
6208 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6209 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6210 
6211 	/*
6212 	 * write one filemark at the time after EOT
6213 	 */
6214 	if (un->un_pos.eof >= ST_EOT) {
6215 		for (i = 0; i < wfm; i++) {
6216 			rval = st_cmd(un, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6217 			if (rval == EACCES) {
6218 				return (rval);
6219 			}
6220 			if (rval != 0) {
6221 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6222 				    "st_write_fm : EIO : write EOT file mark");
6223 				return (EIO);
6224 			}
6225 		}
6226 	} else {
6227 		rval = st_cmd(un, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6228 		if (rval == EACCES) {
6229 			return (rval);
6230 		}
6231 		if (rval) {
6232 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6233 			    "st_write_fm : EIO : write file mark");
6234 			return (EIO);
6235 		}
6236 	}
6237 
6238 	ASSERT(mutex_owned(ST_MUTEX));
6239 	return (0);
6240 }
6241 
6242 #ifdef STDEBUG
6243 static void
6244 st_start_dump(struct scsi_tape *un, struct buf *bp)
6245 {
6246 	struct scsi_pkt *pkt = BP_PKT(bp);
6247 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6248 
6249 	ST_FUNC(ST_DEVINFO, st_start_dump);
6250 
6251 	if ((st_debug & 0x7) < 6)
6252 		return;
6253 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6254 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6255 	    (void *)bp->b_forw, bp->b_bcount,
6256 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6257 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6258 	    "st_start: cdb",  (caddr_t)cdbp);
6259 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6260 	    "st_start: fileno=%d, blk=%d\n",
6261 	    un->un_pos.fileno, un->un_pos.blkno);
6262 }
6263 #endif
6264 
6265 
6266 /*
6267  * Command start && done functions
6268  */
6269 
6270 /*
6271  * st_start()
6272  *
6273  * Called from:
6274  *  st_strategy() to start a command.
6275  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6276  *  st_attach() when resuming from power down state.
6277  *  st_start_restart() to retry transport when device was previously busy.
6278  *  st_done_and_mutex_exit() to start the next command when previous is done.
6279  *
6280  * On entry:
6281  *  scsi_pkt may or may not be allocated.
6282  *
6283  */
6284 static void
6285 st_start(struct scsi_tape *un)
6286 {
6287 	struct buf *bp;
6288 	int status;
6289 	int queued;
6290 
6291 	ST_FUNC(ST_DEVINFO, st_start);
6292 	ASSERT(mutex_owned(ST_MUTEX));
6293 
6294 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6295 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6296 
6297 	if (un->un_recov_buf_busy) {
6298 		/* recovery commands can happen anytime */
6299 		bp = un->un_recov_buf;
6300 		queued = 0;
6301 	} else if (un->un_sbuf_busy) {
6302 		/* sbuf commands should only happen with an empty queue. */
6303 		ASSERT(un->un_quef == NULL);
6304 		ASSERT(un->un_runqf == NULL);
6305 		bp = un->un_sbufp;
6306 		queued = 0;
6307 	} else if (un->un_quef != NULL) {
6308 		if (un->un_persistence && un->un_persist_errors) {
6309 			return;
6310 		}
6311 		bp = un->un_quef;
6312 		queued = 1;
6313 	} else {
6314 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6315 		    "st_start() returning no buf found\n");
6316 		return;
6317 	}
6318 
6319 	ASSERT((bp->b_flags & B_DONE) == 0);
6320 
6321 	/*
6322 	 * Don't send more than un_throttle commands to the HBA
6323 	 */
6324 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6325 		/*
6326 		 * if doing recovery we know there is outstanding commands.
6327 		 */
6328 		if (bp != un->un_recov_buf) {
6329 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6330 			    "st_start returning throttle = %d or ncmds = %d\n",
6331 			    un->un_throttle, un->un_ncmds);
6332 			if (un->un_ncmds == 0) {
6333 				typedef void (*func)();
6334 				func fnc = (func)st_runout;
6335 
6336 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6337 				    "Sending delayed start to st_runout()\n");
6338 				mutex_exit(ST_MUTEX);
6339 				(void) timeout(fnc, un, drv_usectohz(1000000));
6340 			}
6341 			return;
6342 		}
6343 	}
6344 
6345 	/*
6346 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6347 	 * build the command.
6348 	 */
6349 	if (BP_PKT(bp) == NULL) {
6350 		ASSERT((bp->b_flags & B_DONE) == 0);
6351 		st_make_cmd(un, bp, st_runout);
6352 		ASSERT((bp->b_flags & B_DONE) == 0);
6353 		status = geterror(bp);
6354 
6355 		/*
6356 		 * Some HBA's don't call bioerror() to set an error.
6357 		 * And geterror() returns zero if B_ERROR is not set.
6358 		 * So if we get zero we must check b_error.
6359 		 */
6360 		if (status == 0 && bp->b_error != 0) {
6361 			status = bp->b_error;
6362 			bioerror(bp, status);
6363 		}
6364 
6365 		/*
6366 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6367 		 * In tape ENOMEM has special meaning so we'll change it.
6368 		 */
6369 		if (status == ENOMEM) {
6370 			status = 0;
6371 			bioerror(bp, status);
6372 		}
6373 
6374 		/*
6375 		 * Did it fail and is it retryable?
6376 		 * If so return and wait for the callback through st_runout.
6377 		 * Also looks like scsi_init_pkt() will setup a callback even
6378 		 * if it isn't retryable.
6379 		 */
6380 		if (BP_PKT(bp) == NULL) {
6381 			if (status == 0) {
6382 				/*
6383 				 * If first attempt save state.
6384 				 */
6385 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6386 					un->un_laststate = un->un_state;
6387 					un->un_state = ST_STATE_RESOURCE_WAIT;
6388 				}
6389 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6390 				    "temp no resources for pkt\n");
6391 			} else if (status == EINVAL) {
6392 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6393 				    "scsi_init_pkt rejected pkt as too big\n");
6394 				if (un->un_persistence) {
6395 					st_set_pe_flag(un);
6396 				}
6397 			} else {
6398 				/*
6399 				 * Unlikely that it would be retryable then not.
6400 				 */
6401 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6402 					un->un_state = un->un_laststate;
6403 				}
6404 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6405 				    "perm no resources for pkt errno = 0x%x\n",
6406 				    status);
6407 			}
6408 			return;
6409 		}
6410 		/*
6411 		 * Worked this time set the state back.
6412 		 */
6413 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6414 			un->un_state = un->un_laststate;
6415 		}
6416 	}
6417 
6418 	if (queued) {
6419 		/*
6420 		 * move from waitq to runq
6421 		 */
6422 		(void) st_remove_from_queue(&un->un_quef, &un->un_quel, bp);
6423 		st_add_to_queue(&un->un_runqf, &un->un_runql, un->un_runql, bp);
6424 	}
6425 
6426 
6427 #ifdef STDEBUG
6428 	st_start_dump(un, bp);
6429 #endif
6430 
6431 	/* could not get here if throttle was zero */
6432 	un->un_last_throttle = un->un_throttle;
6433 	un->un_throttle = 0;	/* so nothing else will come in here */
6434 	un->un_ncmds++;
6435 
6436 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6437 
6438 	status = st_transport(un, BP_PKT(bp));
6439 
6440 	if (un->un_last_throttle) {
6441 		un->un_throttle = un->un_last_throttle;
6442 	}
6443 
6444 	if (status != TRAN_ACCEPT) {
6445 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6446 		mutex_exit(ST_MUTEX);
6447 
6448 		if (status == TRAN_BUSY) {
6449 			/* if too many retries, fail the transport */
6450 			if (st_handle_start_busy(un, bp,
6451 			    ST_TRAN_BUSY_TIMEOUT, queued) == 0)
6452 				goto done;
6453 		}
6454 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6455 		    "transport rejected %d\n", status);
6456 		bp->b_resid = bp->b_bcount;
6457 
6458 
6459 #ifndef __lock_lint
6460 		/*
6461 		 * warlock doesn't understand this potential
6462 		 * recursion?
6463 		 */
6464 		mutex_enter(ST_MUTEX);
6465 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6466 		ST_DO_ERRSTATS(un, st_transerrs);
6467 		st_bioerror(bp, EIO);
6468 		st_set_pe_flag(un);
6469 		st_done_and_mutex_exit(un, bp);
6470 #endif
6471 	} else {
6472 		un->un_tran_retry_ct = 0;
6473 		mutex_exit(ST_MUTEX);
6474 	}
6475 
6476 done:
6477 
6478 	mutex_enter(ST_MUTEX);
6479 }
6480 
6481 /*
6482  * if the transport is busy, then put this bp back on the waitq
6483  */
6484 static int
6485 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6486     clock_t timeout_interval, int queued)
6487 {
6488 
6489 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6490 
6491 	mutex_enter(ST_MUTEX);
6492 
6493 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6494 	    "st_handle_start_busy()\n");
6495 
6496 	/*
6497 	 * Check to see if we hit the retry timeout and one last check for
6498 	 * making sure this is the last on the runq, if it is not, we have
6499 	 * to fail
6500 	 */
6501 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
6502 	    ((queued) && (un->un_runql != bp))) {
6503 		mutex_exit(ST_MUTEX);
6504 		return (-1);
6505 	}
6506 
6507 	if (queued) {
6508 		/* put the bp back on the waitq */
6509 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
6510 	}
6511 
6512 	/*
6513 	 * Decrement un_ncmds so that this
6514 	 * gets thru' st_start() again.
6515 	 */
6516 	un->un_ncmds--;
6517 
6518 	if (queued) {
6519 		/*
6520 		 * since this is an error case, we won't have to do this list
6521 		 * walking much. We've already made sure this bp was the
6522 		 * last on the runq
6523 		 */
6524 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6525 
6526 		/*
6527 		 * send a marker pkt, if appropriate
6528 		 */
6529 		st_hba_unflush(un);
6530 
6531 	}
6532 	/*
6533 	 * all queues are aligned, we are just waiting to
6534 	 * transport, don't alloc any more buf p's, when
6535 	 * st_start is reentered.
6536 	 */
6537 	(void) timeout(st_start_restart, un, timeout_interval);
6538 
6539 	mutex_exit(ST_MUTEX);
6540 	return (0);
6541 }
6542 
6543 
6544 /*
6545  * st_runout a callback that is called what a resource allocatation failed
6546  */
6547 static int
6548 st_runout(caddr_t arg)
6549 {
6550 	struct scsi_tape *un = (struct scsi_tape *)arg;
6551 	struct buf *bp;
6552 	int queued;
6553 
6554 	ASSERT(un != NULL);
6555 
6556 	ST_FUNC(ST_DEVINFO, st_runout);
6557 
6558 	mutex_enter(ST_MUTEX);
6559 
6560 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6561 
6562 	if (un->un_recov_buf_busy != 0) {
6563 		bp = un->un_recov_buf;
6564 		queued = 0;
6565 	} else if (un->un_sbuf_busy != 0) {
6566 		/* sbuf commands should only happen with an empty queue. */
6567 		ASSERT(un->un_quef == NULL);
6568 		ASSERT(un->un_runqf == NULL);
6569 		bp = un->un_sbufp;
6570 		queued = 0;
6571 	} else if (un->un_quef != NULL) {
6572 		bp = un->un_quef;
6573 		if (un->un_persistence && un->un_persist_errors) {
6574 			mutex_exit(ST_MUTEX);
6575 			bp->b_resid = bp->b_bcount;
6576 			biodone(bp);
6577 			return (1);
6578 		}
6579 		queued = 1;
6580 	} else {
6581 		ASSERT(1 == 0);
6582 		mutex_exit(ST_MUTEX);
6583 		return (1);
6584 	}
6585 
6586 	/*
6587 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6588 	 */
6589 	if ((bp != NULL) && (geterror(bp) != 0)) {
6590 
6591 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6592 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6593 		    bp->b_flags, geterror(bp));
6594 		ASSERT((bp->b_flags & B_DONE) == 0);
6595 
6596 		if (queued) {
6597 			(void) st_remove_from_queue(&un->un_quef, &un->un_quel,
6598 			    bp);
6599 		}
6600 		mutex_exit(ST_MUTEX);
6601 
6602 		ASSERT((bp->b_flags & B_DONE) == 0);
6603 
6604 		/*
6605 		 * Set resid, Error already set, then unblock calling thread.
6606 		 */
6607 		bp->b_resid = bp->b_bcount;
6608 		biodone(bp);
6609 	} else {
6610 		/*
6611 		 * Try Again
6612 		 */
6613 		st_start(un);
6614 		mutex_exit(ST_MUTEX);
6615 	}
6616 
6617 	/*
6618 	 * Comments courtesy of sd.c
6619 	 * The scsi_init_pkt routine allows for the callback function to
6620 	 * return a 0 indicating the callback should be rescheduled or a 1
6621 	 * indicating not to reschedule. This routine always returns 1
6622 	 * because the driver always provides a callback function to
6623 	 * scsi_init_pkt. This results in a callback always being scheduled
6624 	 * (via the scsi_init_pkt callback implementation) if a resource
6625 	 * failure occurs.
6626 	 */
6627 
6628 	return (1);
6629 }
6630 
6631 /*
6632  * st_done_and_mutex_exit()
6633  *	- remove bp from runq
6634  *	- start up the next request
6635  *	- if this was an asynch bp, clean up
6636  *	- exit with released mutex
6637  */
6638 static void
6639 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6640 {
6641 	int	pe_flagged = 0;
6642 
6643 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6644 #if !defined(lint)
6645 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6646 #endif
6647 
6648 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6649 
6650 	ASSERT(mutex_owned(ST_MUTEX));
6651 
6652 	(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6653 
6654 	un->un_ncmds--;
6655 	cv_signal(&un->un_queue_cv);
6656 
6657 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6658 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6659 	    "0x%x\n", (uchar_t)*((caddr_t)(BP_PKT(bp))->pkt_cdbp), bp->b_bcount,
6660 	    bp->b_resid, bp->b_flags);
6661 
6662 
6663 	/*
6664 	 * update kstats with transfer count info
6665 	 */
6666 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6667 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6668 		if (bp->b_flags & B_READ) {
6669 			IOSP->reads++;
6670 			IOSP->nread += n_done;
6671 		} else {
6672 			IOSP->writes++;
6673 			IOSP->nwritten += n_done;
6674 		}
6675 	}
6676 
6677 	/*
6678 	 * Start the next one before releasing resources on this one, if
6679 	 * there is something on the queue and persistent errors has not been
6680 	 * flagged
6681 	 */
6682 
6683 	if ((pe_flagged = (un->un_persistence && un->un_persist_errors)) != 0) {
6684 		un->un_last_resid = bp->b_resid;
6685 		un->un_last_count = bp->b_bcount;
6686 	}
6687 
6688 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6689 		cv_broadcast(&un->un_tape_busy_cv);
6690 	} else if (un->un_quef && un->un_throttle && !pe_flagged &&
6691 	    (bp != un->un_recov_buf)) {
6692 		st_start(un);
6693 	}
6694 
6695 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6696 		/*
6697 		 * Since we marked this ourselves as ASYNC,
6698 		 * there isn't anybody around waiting for
6699 		 * completion any more.
6700 		 */
6701 		uchar_t *cdb = (uchar_t *)bp->b_forw;
6702 		if (*cdb == SCMD_READ || *cdb == SCMD_WRITE) {
6703 			bp->b_un.b_addr = (caddr_t)0;
6704 		}
6705 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6706 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6707 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
6708 		    "CDB sent with B_ASYNC",  (caddr_t)cdb);
6709 		if (BP_PKT(bp)) {
6710 			scsi_destroy_pkt(BP_PKT(bp));
6711 		}
6712 		un->un_sbuf_busy = 0;
6713 		cv_signal(&un->un_sbuf_cv);
6714 		mutex_exit(ST_MUTEX);
6715 		return;
6716 	}
6717 
6718 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6719 		/*
6720 		 * Copy status from scsi_pkt to uscsi_cmd
6721 		 * since st_uscsi_cmd needs it
6722 		 */
6723 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6724 	}
6725 
6726 
6727 #ifdef STDEBUG
6728 	if (((st_debug & 0x7) >= 4) &&
6729 	    (((un->un_pos.blkno % 100) == 0) ||
6730 	    (un->un_persistence && un->un_persist_errors))) {
6731 
6732 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6733 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6734 		    "un_errno = %d, un_pe = %d\n",
6735 		    un->un_ncmds, un->un_throttle, un->un_errno,
6736 		    un->un_persist_errors);
6737 	}
6738 
6739 #endif
6740 
6741 	mutex_exit(ST_MUTEX);
6742 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6743 	    "st_done_and_mutex_exit: freeing pkt\n");
6744 
6745 	if (BP_PKT(bp)) {
6746 		scsi_destroy_pkt(BP_PKT(bp));
6747 	}
6748 
6749 	biodone(bp);
6750 
6751 	/*
6752 	 * now that we biodoned that command, if persistent errors have been
6753 	 * flagged, flush the waitq
6754 	 */
6755 	if (pe_flagged)
6756 		st_flush(un);
6757 }
6758 
6759 
6760 /*
6761  * Tape error, flush tape driver queue.
6762  */
6763 static void
6764 st_flush(struct scsi_tape *un)
6765 {
6766 	struct buf *bp;
6767 
6768 	ST_FUNC(ST_DEVINFO, st_flush);
6769 
6770 	mutex_enter(ST_MUTEX);
6771 
6772 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6773 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6774 	    un->un_ncmds, (void *)un->un_quef);
6775 
6776 	/*
6777 	 * if we still have commands outstanding, wait for them to come in
6778 	 * before flushing the queue, and make sure there is a queue
6779 	 */
6780 	if (un->un_ncmds || !un->un_quef)
6781 		goto exit;
6782 
6783 	/*
6784 	 * we have no more commands outstanding, so let's deal with special
6785 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6786 	 * is 0, then we know there was no error and we return a 0 read or
6787 	 * write before showing errors
6788 	 */
6789 
6790 	/* Flush the wait queue. */
6791 	while ((bp = un->un_quef) != NULL) {
6792 		un->un_quef = bp->b_actf;
6793 
6794 		bp->b_resid = bp->b_bcount;
6795 
6796 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6797 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6798 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6799 
6800 		st_set_pe_errno(un);
6801 
6802 		bioerror(bp, un->un_errno);
6803 
6804 		mutex_exit(ST_MUTEX);
6805 		/* it should have one, but check anyway */
6806 		if (BP_PKT(bp)) {
6807 			scsi_destroy_pkt(BP_PKT(bp));
6808 		}
6809 		biodone(bp);
6810 		mutex_enter(ST_MUTEX);
6811 	}
6812 
6813 	/*
6814 	 * It's not a bad practice to reset the
6815 	 * waitq tail pointer to NULL.
6816 	 */
6817 	un->un_quel = NULL;
6818 
6819 exit:
6820 	/* we mucked with the queue, so let others know about it */
6821 	cv_signal(&un->un_queue_cv);
6822 	mutex_exit(ST_MUTEX);
6823 }
6824 
6825 
6826 /*
6827  * Utility functions
6828  */
6829 static int
6830 st_determine_generic(struct scsi_tape *un)
6831 {
6832 	int bsize;
6833 	static char *cart = "0.25 inch cartridge";
6834 	char *sizestr;
6835 
6836 	ST_FUNC(ST_DEVINFO, st_determine_generic);
6837 
6838 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6839 	    "st_determine_generic(un = 0x%p)\n", (void*)un);
6840 
6841 	ASSERT(mutex_owned(ST_MUTEX));
6842 
6843 	if (st_modesense(un)) {
6844 		return (-1);
6845 	}
6846 
6847 	bsize = (un->un_mspl->high_bl << 16)	|
6848 	    (un->un_mspl->mid_bl << 8)	|
6849 	    (un->un_mspl->low_bl);
6850 
6851 	if (bsize == 0) {
6852 		un->un_dp->options |= ST_VARIABLE;
6853 		un->un_dp->bsize = 0;
6854 		un->un_bsize = 0;
6855 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
6856 		/*
6857 		 * record size of this device too big.
6858 		 * try and convert it to variable record length.
6859 		 *
6860 		 */
6861 		un->un_dp->options |= ST_VARIABLE;
6862 		if (st_change_block_size(un, 0) != 0) {
6863 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6864 			    "Fixed Record Size %d is too large\n", bsize);
6865 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6866 			    "Cannot switch to variable record size\n");
6867 			un->un_dp->options &= ~ST_VARIABLE;
6868 			return (-1);
6869 		}
6870 	} else if (st_change_block_size(un, 0) == 0) {
6871 		/*
6872 		 * If the drive was set to a non zero block size,
6873 		 * See if it can be set to a zero block size.
6874 		 * If it works, ST_VARIABLE so user can set it as they want.
6875 		 */
6876 		un->un_dp->options |= ST_VARIABLE;
6877 		un->un_dp->bsize = 0;
6878 		un->un_bsize = 0;
6879 	} else {
6880 		un->un_dp->bsize = bsize;
6881 		un->un_bsize = bsize;
6882 	}
6883 
6884 
6885 	switch (un->un_mspl->density) {
6886 	default:
6887 	case 0x0:
6888 		/*
6889 		 * default density, cannot determine any other
6890 		 * information.
6891 		 */
6892 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
6893 		un->un_dp->type = ST_TYPE_DEFAULT;
6894 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
6895 		break;
6896 	case 0x1:
6897 	case 0x2:
6898 	case 0x3:
6899 	case 0x6:
6900 		/*
6901 		 * 1/2" reel
6902 		 */
6903 		sizestr = "0.50 inch reel";
6904 		un->un_dp->type = ST_TYPE_REEL;
6905 		un->un_dp->options |= ST_REEL;
6906 		un->un_dp->densities[0] = 0x1;
6907 		un->un_dp->densities[1] = 0x2;
6908 		un->un_dp->densities[2] = 0x6;
6909 		un->un_dp->densities[3] = 0x3;
6910 		break;
6911 	case 0x4:
6912 	case 0x5:
6913 	case 0x7:
6914 	case 0x0b:
6915 
6916 		/*
6917 		 * Quarter inch.
6918 		 */
6919 		sizestr = cart;
6920 		un->un_dp->type = ST_TYPE_DEFAULT;
6921 		un->un_dp->options |= ST_QIC;
6922 
6923 		un->un_dp->densities[1] = 0x4;
6924 		un->un_dp->densities[2] = 0x5;
6925 		un->un_dp->densities[3] = 0x7;
6926 		un->un_dp->densities[0] = 0x0b;
6927 		break;
6928 
6929 	case 0x0f:
6930 	case 0x10:
6931 	case 0x11:
6932 	case 0x12:
6933 		/*
6934 		 * QIC-120, QIC-150, QIC-320, QIC-600
6935 		 */
6936 		sizestr = cart;
6937 		un->un_dp->type = ST_TYPE_DEFAULT;
6938 		un->un_dp->options |= ST_QIC;
6939 		un->un_dp->densities[0] = 0x0f;
6940 		un->un_dp->densities[1] = 0x10;
6941 		un->un_dp->densities[2] = 0x11;
6942 		un->un_dp->densities[3] = 0x12;
6943 		break;
6944 
6945 	case 0x09:
6946 	case 0x0a:
6947 	case 0x0c:
6948 	case 0x0d:
6949 		/*
6950 		 * 1/2" cartridge tapes. Include HI-TC.
6951 		 */
6952 		sizestr = cart;
6953 		sizestr[2] = '5';
6954 		sizestr[3] = '0';
6955 		un->un_dp->type = ST_TYPE_HIC;
6956 		un->un_dp->densities[0] = 0x09;
6957 		un->un_dp->densities[1] = 0x0a;
6958 		un->un_dp->densities[2] = 0x0c;
6959 		un->un_dp->densities[3] = 0x0d;
6960 		break;
6961 
6962 	case 0x13:
6963 			/* DDS-2/DDS-3 scsi spec densities */
6964 	case 0x24:
6965 	case 0x25:
6966 	case 0x26:
6967 		sizestr = "DAT Data Storage (DDS)";
6968 		un->un_dp->type = ST_TYPE_DAT;
6969 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6970 		break;
6971 
6972 	case 0x14:
6973 		/*
6974 		 * Helical Scan (Exabyte) devices
6975 		 */
6976 		sizestr = "8mm helical scan cartridge";
6977 		un->un_dp->type = ST_TYPE_EXABYTE;
6978 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6979 		break;
6980 	}
6981 
6982 	/*
6983 	 * Assume LONG ERASE, BSF and BSR
6984 	 */
6985 
6986 	un->un_dp->options |=
6987 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
6988 
6989 	/*
6990 	 * Only if mode sense data says no buffered write, set NOBUF
6991 	 */
6992 	if (un->un_mspl->bufm == 0)
6993 		un->un_dp->options |= ST_NOBUF;
6994 
6995 	/*
6996 	 * set up large read and write retry counts
6997 	 */
6998 
6999 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
7000 
7001 	/*
7002 	 * If this is a 0.50 inch reel tape, and
7003 	 * it is *not* variable mode, try and
7004 	 * set it to variable record length
7005 	 * mode.
7006 	 */
7007 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
7008 	    (un->un_dp->options & ST_VARIABLE)) {
7009 		if (st_change_block_size(un, 0) == 0) {
7010 			un->un_dp->bsize = 0;
7011 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
7012 			    un->un_mspl->low_bl = 0;
7013 		}
7014 	}
7015 
7016 	/*
7017 	 * Write to console about type of device found
7018 	 */
7019 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
7020 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
7021 	    sizestr);
7022 	if (un->un_dp->options & ST_VARIABLE) {
7023 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7024 		    "!Variable record length I/O\n");
7025 	} else {
7026 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7027 		    "!Fixed record length (%d byte blocks) I/O\n",
7028 		    un->un_dp->bsize);
7029 	}
7030 	ASSERT(mutex_owned(ST_MUTEX));
7031 	return (0);
7032 }
7033 
7034 static int
7035 st_determine_density(struct scsi_tape *un, int rw)
7036 {
7037 	int rval = 0;
7038 
7039 	ST_FUNC(ST_DEVINFO, st_determine_density);
7040 
7041 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7042 	    "st_determine_density(un = 0x%p, rw = %s)\n",
7043 	    (void*)un, (rw == B_WRITE ? wr_str: rd_str));
7044 
7045 	ASSERT(mutex_owned(ST_MUTEX));
7046 
7047 	/*
7048 	 * If we're past BOT, density is determined already.
7049 	 */
7050 	if (un->un_pos.pmode == logical) {
7051 		if (un->un_pos.lgclblkno != 0) {
7052 			goto exit;
7053 		}
7054 	} else if (un->un_pos.pmode == legacy) {
7055 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
7056 			/*
7057 			 * XXX: put in a bitch message about attempting to
7058 			 * XXX: change density past BOT.
7059 			 */
7060 			goto exit;
7061 		}
7062 	} else {
7063 		goto exit;
7064 	}
7065 	if ((un->un_pos.pmode == logical) &&
7066 	    (un->un_pos.lgclblkno != 0)) {
7067 		goto exit;
7068 	}
7069 
7070 
7071 	/*
7072 	 * If we're going to be writing, we set the density
7073 	 */
7074 	if (rw == 0 || rw == B_WRITE) {
7075 		/* un_curdens is used as an index into densities table */
7076 		un->un_curdens = MT_DENSITY(un->un_dev);
7077 		if (st_set_density(un)) {
7078 			rval = -1;
7079 		}
7080 		goto exit;
7081 	}
7082 
7083 	/*
7084 	 * If density is known already,
7085 	 * we don't have to get it again.(?)
7086 	 */
7087 	if (!un->un_density_known) {
7088 		if (st_get_density(un)) {
7089 			rval = -1;
7090 		}
7091 	}
7092 
7093 exit:
7094 	ASSERT(mutex_owned(ST_MUTEX));
7095 	return (rval);
7096 }
7097 
7098 
7099 /*
7100  * Try to determine density. We do this by attempting to read the
7101  * first record off the tape, cycling through the available density
7102  * codes as we go.
7103  */
7104 
7105 static int
7106 st_get_density(struct scsi_tape *un)
7107 {
7108 	int succes = 0, rval = -1, i;
7109 	uint_t size;
7110 	uchar_t dens, olddens;
7111 
7112 	ST_FUNC(ST_DEVINFO, st_get_density);
7113 
7114 	ST_FUNC(ST_DEVINFO, st_get_density);
7115 
7116 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7117 	    "st_get_density(un = 0x%p)\n", (void*)un);
7118 
7119 	ASSERT(mutex_owned(ST_MUTEX));
7120 
7121 	/*
7122 	 * If Auto Density override is enabled The drive has
7123 	 * only one density and there is no point in attempting
7124 	 * find the correct one.
7125 	 *
7126 	 * Since most modern drives auto detect the density
7127 	 * and format of the recorded media before they come
7128 	 * ready. What this function does is a legacy behavior
7129 	 * and modern drives not only don't need it, The backup
7130 	 * utilities that do positioning via uscsi find the un-
7131 	 * expected rewinds problematic.
7132 	 *
7133 	 * The drives that need this are old reel to reel devices.
7134 	 * I took a swag and said they must be scsi-1 or older.
7135 	 * I don't beleave there will any of the newer devices
7136 	 * that need this. There will be some scsi-1 devices that
7137 	 * don't need this but I don't think they will be using the
7138 	 * BIG aftermarket backup and restore utilitys.
7139 	 */
7140 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
7141 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
7142 		un->un_density_known = 1;
7143 		rval = 0;
7144 		goto exit;
7145 	}
7146 
7147 	/*
7148 	 * This will only work on variable record length tapes
7149 	 * if and only if all variable record length tapes autodensity
7150 	 * select.
7151 	 */
7152 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
7153 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
7154 
7155 	/*
7156 	 * Start at the specified density
7157 	 */
7158 
7159 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
7160 
7161 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
7162 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
7163 		/*
7164 		 * If we've done this density before,
7165 		 * don't bother to do it again.
7166 		 */
7167 		dens = un->un_dp->densities[un->un_curdens];
7168 		if (i > 0 && dens == olddens)
7169 			continue;
7170 		olddens = dens;
7171 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7172 		    "trying density 0x%x\n", dens);
7173 		if (st_set_density(un)) {
7174 			continue;
7175 		}
7176 
7177 		/*
7178 		 * XXX - the creates lots of headaches and slowdowns - must
7179 		 * fix.
7180 		 */
7181 		succes = (st_cmd(un, SCMD_READ, (int)size, SYNC_CMD) == 0);
7182 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
7183 			break;
7184 		}
7185 		if (succes) {
7186 			st_init(un);
7187 			rval = 0;
7188 			un->un_density_known = 1;
7189 			break;
7190 		}
7191 	}
7192 	kmem_free(un->un_tmpbuf, size);
7193 	un->un_tmpbuf = 0;
7194 
7195 exit:
7196 	ASSERT(mutex_owned(ST_MUTEX));
7197 	return (rval);
7198 }
7199 
7200 static int
7201 st_set_density(struct scsi_tape *un)
7202 {
7203 	int rval = 0;
7204 
7205 	ST_FUNC(ST_DEVINFO, st_set_density);
7206 
7207 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7208 	    "st_set_density(un = 0x%p): density = 0x%x\n", (void*)un,
7209 	    un->un_dp->densities[un->un_curdens]);
7210 
7211 	ASSERT(mutex_owned(ST_MUTEX));
7212 
7213 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7214 
7215 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
7216 		/*
7217 		 * If auto density override is not set, Use mode select
7218 		 * to set density and compression.
7219 		 */
7220 		if (st_modeselect(un)) {
7221 			rval = -1;
7222 		}
7223 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
7224 		/*
7225 		 * If auto density and mode select compression are set,
7226 		 * This is a drive with one density code but compression
7227 		 * can be enabled or disabled.
7228 		 * Set compression but no need to set density.
7229 		 */
7230 		rval = st_set_compression(un);
7231 		if ((rval != 0) && (rval != EALREADY)) {
7232 			rval = -1;
7233 		} else {
7234 			rval = 0;
7235 		}
7236 	}
7237 
7238 	/* If sucessful set density and/or compression, mark density known */
7239 	if (rval == 0) {
7240 		un->un_density_known = 1;
7241 	}
7242 
7243 	ASSERT(mutex_owned(ST_MUTEX));
7244 	return (rval);
7245 }
7246 
7247 static int
7248 st_loadtape(struct scsi_tape *un)
7249 {
7250 	int rval;
7251 
7252 	ST_FUNC(ST_DEVINFO, st_loadtape);
7253 
7254 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7255 	    "st_loadtape(un = 0x%p)\n", (void*) un);
7256 
7257 	ASSERT(mutex_owned(ST_MUTEX));
7258 
7259 	rval = st_update_block_pos(un, st_cmd, 0);
7260 	if (rval == EACCES) {
7261 		return (rval);
7262 	}
7263 
7264 	/*
7265 	 * 'LOAD' the tape to BOT by rewinding
7266 	 */
7267 	rval = st_cmd(un, SCMD_REWIND, 1, SYNC_CMD);
7268 	if (rval == 0) {
7269 		st_init(un);
7270 		un->un_density_known = 0;
7271 	}
7272 
7273 	ASSERT(mutex_owned(ST_MUTEX));
7274 	return (rval);
7275 }
7276 
7277 
7278 /*
7279  * Note: QIC devices aren't so smart.  If you try to append
7280  * after EOM, the write can fail because the device doesn't know
7281  * it's at EOM.	 In that case, issue a read.  The read should fail
7282  * because there's no data, but the device knows it's at EOM,
7283  * so a subsequent write should succeed.  To further confuse matters,
7284  * the target returns the same error if the tape is positioned
7285  * such that a write would overwrite existing data.  That's why
7286  * we have to do the append test.  A read in the middle of
7287  * recorded data would succeed, thus indicating we're attempting
7288  * something illegal.
7289  */
7290 
7291 
7292 static void
7293 st_test_append(struct buf *bp)
7294 {
7295 	dev_t dev = bp->b_edev;
7296 	struct scsi_tape *un;
7297 	uchar_t status;
7298 	unsigned bcount;
7299 
7300 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7301 
7302 	ST_FUNC(ST_DEVINFO, st_test_append);
7303 
7304 	ASSERT(mutex_owned(ST_MUTEX));
7305 
7306 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7307 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7308 
7309 	un->un_laststate = un->un_state;
7310 	un->un_state = ST_STATE_APPEND_TESTING;
7311 	un->un_test_append = 0;
7312 
7313 	/*
7314 	 * first, map in the buffer, because we're doing a double write --
7315 	 * first into the kernel, then onto the tape.
7316 	 */
7317 	bp_mapin(bp);
7318 
7319 	/*
7320 	 * get a copy of the data....
7321 	 */
7322 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7323 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7324 
7325 	/*
7326 	 * attempt the write..
7327 	 */
7328 
7329 	if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7330 success:
7331 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7332 		    "append write succeeded\n");
7333 		bp->b_resid = un->un_sbufp->b_resid;
7334 		mutex_exit(ST_MUTEX);
7335 		bcount = (unsigned)bp->b_bcount;
7336 		biodone(bp);
7337 		mutex_enter(ST_MUTEX);
7338 		un->un_laststate = un->un_state;
7339 		un->un_state = ST_STATE_OPEN;
7340 		kmem_free(un->un_tmpbuf, bcount);
7341 		un->un_tmpbuf = NULL;
7342 		return;
7343 	}
7344 
7345 	/*
7346 	 * The append failed. Do a short read. If that fails,  we are at EOM
7347 	 * so we can retry the write command. If that succeeds, than we're
7348 	 * all screwed up (the controller reported a real error).
7349 	 *
7350 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7351 	 * XXX: block size?
7352 	 *
7353 	 */
7354 	status = un->un_status;
7355 	un->un_status = 0;
7356 	(void) st_cmd(un, SCMD_READ, SECSIZE, SYNC_CMD);
7357 	if (un->un_status == KEY_BLANK_CHECK) {
7358 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7359 		    "append at EOM\n");
7360 		/*
7361 		 * Okay- the read failed. We should actually have confused
7362 		 * the controller enough to allow writing. In any case, the
7363 		 * i/o is on its own from here on out.
7364 		 */
7365 		un->un_laststate = un->un_state;
7366 		un->un_state = ST_STATE_OPEN;
7367 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7368 		if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount,
7369 		    SYNC_CMD) == 0) {
7370 			goto success;
7371 		}
7372 	}
7373 
7374 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7375 	    "append write failed- not at EOM\n");
7376 	bp->b_resid = bp->b_bcount;
7377 	st_bioerror(bp, EIO);
7378 
7379 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7380 	    "st_test_append : EIO : append write failed - not at EOM");
7381 
7382 	/*
7383 	 * backspace one record to get back to where we were
7384 	 */
7385 	if (st_cmd(un, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7386 		un->un_pos.pmode = invalid;
7387 	}
7388 
7389 	un->un_err_resid = bp->b_resid;
7390 	un->un_status = status;
7391 
7392 	/*
7393 	 * Note: biodone will do a bp_mapout()
7394 	 */
7395 	mutex_exit(ST_MUTEX);
7396 	bcount = (unsigned)bp->b_bcount;
7397 	biodone(bp);
7398 	mutex_enter(ST_MUTEX);
7399 	un->un_laststate = un->un_state;
7400 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7401 	kmem_free(un->un_tmpbuf, bcount);
7402 	un->un_tmpbuf = NULL;
7403 }
7404 
7405 /*
7406  * Special command handler
7407  */
7408 
7409 /*
7410  * common st_cmd code. The fourth parameter states
7411  * whether the caller wishes to await the results
7412  * Note the release of the mutex during most of the function
7413  */
7414 static int
7415 st_cmd(struct scsi_tape *un, int com, int64_t count, int wait)
7416 {
7417 	struct buf *bp;
7418 	int err;
7419 	uint_t last_err_resid;
7420 
7421 	ST_FUNC(ST_DEVINFO, st_cmd);
7422 
7423 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7424 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %"PRIx64", wait = %d)\n",
7425 	    un->un_dev, com, count, wait);
7426 
7427 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7428 	ASSERT(mutex_owned(ST_MUTEX));
7429 
7430 #ifdef STDEBUG
7431 	if ((st_debug & 0x7)) {
7432 		st_debug_cmds(un, com, count, wait);
7433 	}
7434 #endif
7435 
7436 	st_wait_for_io(un);
7437 
7438 	/* check to see if this command requires the drive to be reserved */
7439 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7440 
7441 	if (err) {
7442 		return (err);
7443 	}
7444 
7445 	/*
7446 	 * A space command is not recoverable if we don't know were we
7447 	 * were when it was issued.
7448 	 */
7449 	if ((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) {
7450 		(void) st_update_block_pos(un, st_cmd, 0);
7451 	}
7452 
7453 	/*
7454 	 * Forground should not be doing anything while recovery is active.
7455 	 */
7456 	ASSERT(un->un_recov_buf_busy == 0);
7457 
7458 	while (un->un_sbuf_busy)
7459 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7460 	un->un_sbuf_busy = 1;
7461 
7462 	bp = un->un_sbufp;
7463 	bzero(bp, sizeof (buf_t));
7464 
7465 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7466 
7467 	err = st_setup_cmd(un, bp, com, count);
7468 
7469 	un->un_sbuf_busy = 0;
7470 
7471 	/*
7472 	 * If was a space command need to update logical block position.
7473 	 * Only do this if the command was sucessful or it will mask the fact
7474 	 * that the space command failed by promoting the pmode to logical.
7475 	 */
7476 	if (((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) &&
7477 	    (un->un_pos.pmode != invalid)) {
7478 		un->un_running.pmode = invalid;
7479 		last_err_resid = un->un_err_resid;
7480 		(void) st_update_block_pos(un, st_cmd, 1);
7481 		/*
7482 		 * Set running position to invalid so it updates on the
7483 		 * next command.
7484 		 */
7485 		un->un_running.pmode = invalid;
7486 		un->un_err_resid = last_err_resid;
7487 	}
7488 
7489 	cv_signal(&un->un_sbuf_cv);
7490 
7491 	return (err);
7492 }
7493 
7494 static int
7495 st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com, int64_t count)
7496 {
7497 	int err;
7498 	dev_t dev = un->un_dev;
7499 
7500 	ST_FUNC(ST_DEVINFO, st_setup_cmd);
7501 	/*
7502 	 * Set count to the actual size of the data tranfer.
7503 	 * For commands with no data transfer, set bp->b_bcount
7504 	 * to the value to be used when constructing the
7505 	 * cdb in st_make_cmd().
7506 	 */
7507 	switch (com) {
7508 	case SCMD_READ:
7509 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7510 		    "special read %"PRId64"\n", count);
7511 		bp->b_flags |= B_READ;
7512 		bp->b_un.b_addr = un->un_tmpbuf;
7513 		break;
7514 
7515 	case SCMD_WRITE:
7516 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7517 		    "special write %"PRId64"\n", count);
7518 		bp->b_un.b_addr = un->un_tmpbuf;
7519 		break;
7520 
7521 	case SCMD_WRITE_FILE_MARK:
7522 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7523 		    "write %"PRId64" file marks\n", count);
7524 		bp->b_bcount = count;
7525 		count = 0;
7526 		break;
7527 
7528 	case SCMD_REWIND:
7529 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7530 		bp->b_bcount = count;
7531 		count = 0;
7532 		break;
7533 
7534 	case SCMD_SPACE:
7535 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7536 		/*
7537 		 * If the user could have entered a number that will
7538 		 * not fit in the 12 bit count field of space(8),
7539 		 * use space(16).
7540 		 */
7541 		if (((int64_t)SPACE_CNT(count) > 0x7fffff) ||
7542 		    ((int64_t)SPACE_CNT(count) < -(0x7fffff))) {
7543 			com = SCMD_SPACE_G4;
7544 		}
7545 		bp->b_bcount = count;
7546 		count = 0;
7547 		break;
7548 
7549 	case SCMD_RESERVE:
7550 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7551 		bp->b_bcount = 0;
7552 		count = 0;
7553 		break;
7554 
7555 	case SCMD_RELEASE:
7556 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7557 		bp->b_bcount = 0;
7558 		count = 0;
7559 		break;
7560 
7561 	case SCMD_LOAD:
7562 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7563 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7564 		bp->b_bcount = count;
7565 		count = 0;
7566 		break;
7567 
7568 	case SCMD_ERASE:
7569 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7570 		    "erase tape\n");
7571 		bp->b_bcount = count;
7572 		count = 0;
7573 		break;
7574 
7575 	case SCMD_MODE_SENSE:
7576 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7577 		    "mode sense\n");
7578 		bp->b_flags |= B_READ;
7579 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7580 		break;
7581 
7582 	case SCMD_MODE_SELECT:
7583 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7584 		    "mode select\n");
7585 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7586 		break;
7587 
7588 	case SCMD_READ_BLKLIM:
7589 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7590 		    "read block limits\n");
7591 		bp->b_bcount = count;
7592 		bp->b_flags |= B_READ;
7593 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7594 		break;
7595 
7596 	case SCMD_TEST_UNIT_READY:
7597 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7598 		    "test unit ready\n");
7599 		bp->b_bcount = 0;
7600 		count = 0;
7601 		break;
7602 
7603 	case SCMD_DOORLOCK:
7604 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7605 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7606 		bp->b_bcount = count = 0;
7607 		break;
7608 
7609 	case SCMD_READ_POSITION:
7610 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7611 		    "read position\n");
7612 		switch (un->un_read_pos_type) {
7613 		case LONG_POS:
7614 			count = sizeof (tape_position_long_t);
7615 			break;
7616 		case EXT_POS:
7617 			count = min(count, sizeof (tape_position_ext_t));
7618 			break;
7619 		case SHORT_POS:
7620 			count = sizeof (tape_position_t);
7621 			break;
7622 		default:
7623 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7624 			    "Unknown read position type 0x%x in "
7625 			    "st_make_cmd()\n", un->un_read_pos_type);
7626 		}
7627 		bp->b_bcount = count;
7628 		bp->b_flags |= B_READ;
7629 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7630 		break;
7631 
7632 	default:
7633 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7634 		    "Unhandled scsi command 0x%x in st_setup_cmd()\n", com);
7635 	}
7636 
7637 	mutex_exit(ST_MUTEX);
7638 
7639 	if (count > 0) {
7640 		int flg = (bp->b_flags & B_READ) ? B_READ : B_WRITE;
7641 		/*
7642 		 * We're going to do actual I/O.
7643 		 * Set things up for physio.
7644 		 */
7645 		struct iovec aiov;
7646 		struct uio auio;
7647 		struct uio *uio = &auio;
7648 
7649 		bzero(&auio, sizeof (struct uio));
7650 		bzero(&aiov, sizeof (struct iovec));
7651 		aiov.iov_base = bp->b_un.b_addr;
7652 		aiov.iov_len = count;
7653 
7654 		uio->uio_iov = &aiov;
7655 		uio->uio_iovcnt = 1;
7656 		uio->uio_resid = aiov.iov_len;
7657 		uio->uio_segflg = UIO_SYSSPACE;
7658 
7659 		/*
7660 		 * Let physio do the rest...
7661 		 */
7662 		bp->b_forw = (struct buf *)(uintptr_t)com;
7663 		bp->b_back = NULL;
7664 		err = physio(st_strategy, bp, dev, flg, st_minphys, uio);
7665 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7666 		    "st_setup_cmd: physio returns %d\n", err);
7667 	} else {
7668 		/*
7669 		 * Mimic physio
7670 		 */
7671 		bp->b_forw = (struct buf *)(uintptr_t)com;
7672 		bp->b_back = NULL;
7673 		bp->b_edev = dev;
7674 		bp->b_dev = cmpdev(dev);
7675 		bp->b_blkno = 0;
7676 		bp->b_resid = 0;
7677 		(void) st_strategy(bp);
7678 		if (bp->b_flags & B_ASYNC) {
7679 			/*
7680 			 * This is an async command- the caller won't wait
7681 			 * and doesn't care about errors.
7682 			 */
7683 			mutex_enter(ST_MUTEX);
7684 			return (0);
7685 		}
7686 
7687 		/*
7688 		 * BugTraq #4260046
7689 		 * ----------------
7690 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7691 		 * unconditionally. The old comment said...
7692 		 *
7693 		 * "if strategy was flagged with  persistent errors, we would
7694 		 *  have an error here, and the bp would never be sent, so we
7695 		 *  don't want to wait on a bp that was never sent...or hang"
7696 		 *
7697 		 * The new rationale, courtesy of Chitrank...
7698 		 *
7699 		 * "we should unconditionally biowait() here because
7700 		 *  st_strategy() will do a biodone() in the persistent error
7701 		 *  case and the following biowait() will return immediately.
7702 		 *  If not, in the case of "errors after pkt alloc" in
7703 		 *  st_start(), we will not biowait here which will cause the
7704 		 *  next biowait() to return immediately which will cause
7705 		 *  us to send out the next command. In the case where both of
7706 		 *  these use the sbuf, when the first command completes we'll
7707 		 *  free the packet attached to sbuf and the same pkt will
7708 		 *  get freed again when we complete the second command.
7709 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7710 		 *  st_start() for the pkt alloc failure case because physio()
7711 		 *  does biowait() and will hang if we don't do biodone()"
7712 		 */
7713 
7714 		err = biowait(bp);
7715 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7716 		    "st_setup_cmd: biowait returns %d\n", err);
7717 	}
7718 
7719 	mutex_enter(ST_MUTEX);
7720 
7721 	return (err);
7722 }
7723 
7724 static int
7725 st_set_compression(struct scsi_tape *un)
7726 {
7727 	int rval;
7728 	int turn_compression_on;
7729 	minor_t minor;
7730 
7731 	ST_FUNC(ST_DEVINFO, st_set_compression);
7732 
7733 	/*
7734 	 * Drive either dosn't have compression or it is controlled with
7735 	 * special density codes. Return ENOTTY so caller
7736 	 * knows nothing was done.
7737 	 */
7738 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7739 		un->un_comp_page = 0;
7740 		return (ENOTTY);
7741 	}
7742 
7743 	/* set compression based on minor node opened */
7744 	minor = MT_DENSITY(un->un_dev);
7745 
7746 	/*
7747 	 * If this the compression density or
7748 	 * the drive has two densities and uses mode select for
7749 	 * control of compression turn on compression for MT_DENSITY2
7750 	 * as well.
7751 	 */
7752 	if ((minor == ST_COMPRESSION_DENSITY) ||
7753 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7754 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7755 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7756 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7757 
7758 		turn_compression_on = 1;
7759 	} else {
7760 		turn_compression_on = 0;
7761 	}
7762 
7763 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7764 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7765 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7766 
7767 	/*
7768 	 * Need to determine which page does the device use for compression.
7769 	 * First try the data compression page. If this fails try the device
7770 	 * configuration page
7771 	 */
7772 
7773 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7774 		rval = st_set_datacomp_page(un, turn_compression_on);
7775 		if (rval == EALREADY) {
7776 			return (rval);
7777 		}
7778 		if (rval != 0) {
7779 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7780 				/*
7781 				 * This device does not support data
7782 				 * compression page
7783 				 */
7784 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7785 			} else if (un->un_state >= ST_STATE_OPEN) {
7786 				un->un_pos.pmode = invalid;
7787 				rval = EIO;
7788 			} else {
7789 				rval = -1;
7790 			}
7791 		} else {
7792 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7793 		}
7794 	}
7795 
7796 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7797 		rval = st_set_devconfig_page(un, turn_compression_on);
7798 		if (rval == EALREADY) {
7799 			return (rval);
7800 		}
7801 		if (rval != 0) {
7802 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7803 				/*
7804 				 * This device does not support
7805 				 * compression at all advice the
7806 				 * user and unset ST_MODE_SEL_COMP
7807 				 */
7808 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7809 				un->un_comp_page = 0;
7810 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7811 				    "Device Does Not Support Compression\n");
7812 			} else if (un->un_state >= ST_STATE_OPEN) {
7813 				un->un_pos.pmode = invalid;
7814 				rval = EIO;
7815 			} else {
7816 				rval = -1;
7817 			}
7818 		}
7819 	}
7820 
7821 	return (rval);
7822 }
7823 
7824 /*
7825  * set or unset compression thru device configuration page.
7826  */
7827 static int
7828 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
7829 {
7830 	unsigned char cflag;
7831 	int rval = 0;
7832 
7833 
7834 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
7835 
7836 	ASSERT(mutex_owned(ST_MUTEX));
7837 	/*
7838 	 * Figure what to set compression flag to.
7839 	 */
7840 	if (compression_on) {
7841 		/* They have selected a compression node */
7842 		if (un->un_dp->type == ST_TYPE_FUJI) {
7843 			cflag = 0x84;   /* use EDRC */
7844 		} else {
7845 			cflag = ST_DEV_CONFIG_DEF_COMP;
7846 		}
7847 	} else {
7848 		cflag = ST_DEV_CONFIG_NO_COMP;
7849 	}
7850 
7851 	/*
7852 	 * If compression is already set the way it was requested.
7853 	 * And if this not the first time we has tried.
7854 	 */
7855 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
7856 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7857 		return (EALREADY);
7858 	}
7859 
7860 	un->un_mspl->page.dev.comp_alg = cflag;
7861 	/*
7862 	 * need to send mode select even if correct compression is
7863 	 * already set since need to set density code
7864 	 */
7865 
7866 #ifdef STDEBUG
7867 	if ((st_debug & 0x7) >= 6) {
7868 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7869 		    "st_set_devconfig_page: sense data for mode select",
7870 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7871 	}
7872 #endif
7873 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
7874 	    sizeof (struct seq_mode));
7875 
7876 	return (rval);
7877 }
7878 
7879 /*
7880  * set/reset compression bit thru data compression page
7881  */
7882 static int
7883 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
7884 {
7885 	int compression_on_already;
7886 	int rval = 0;
7887 
7888 
7889 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
7890 
7891 	ASSERT(mutex_owned(ST_MUTEX));
7892 	/*
7893 	 * If drive is not capable of compression (at this time)
7894 	 * return EALREADY so caller doesn't think that this page
7895 	 * is not supported. This check is for drives that can
7896 	 * disable compression from the front panel or configuration.
7897 	 * I doubt that a drive that supports this page is not really
7898 	 * capable of compression.
7899 	 */
7900 	if (un->un_mspl->page.comp.dcc == 0) {
7901 		return (EALREADY);
7902 	}
7903 
7904 	/* See if compression currently turned on */
7905 	if (un->un_mspl->page.comp.dce) {
7906 		compression_on_already = 1;
7907 	} else {
7908 		compression_on_already = 0;
7909 	}
7910 
7911 	/*
7912 	 * If compression is already set the way it was requested.
7913 	 * And if this not the first time we has tried.
7914 	 */
7915 	if ((compression_on == compression_on_already) &&
7916 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7917 		return (EALREADY);
7918 	}
7919 
7920 	/*
7921 	 * if we are already set to the appropriate compression
7922 	 * mode, don't set it again
7923 	 */
7924 	if (compression_on) {
7925 		/* compression selected */
7926 		un->un_mspl->page.comp.dce = 1;
7927 	} else {
7928 		un->un_mspl->page.comp.dce = 0;
7929 	}
7930 
7931 
7932 #ifdef STDEBUG
7933 	if ((st_debug & 0x7) >= 6) {
7934 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7935 		    "st_set_datacomp_page: sense data for mode select",
7936 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7937 	}
7938 #endif
7939 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
7940 	    sizeof (struct seq_mode));
7941 
7942 	return (rval);
7943 }
7944 
7945 static int
7946 st_modesense(struct scsi_tape *un)
7947 {
7948 	int rval;
7949 	uchar_t page;
7950 
7951 	ST_FUNC(ST_DEVINFO, st_modesense);
7952 
7953 	page = un->un_comp_page;
7954 
7955 	switch (page) {
7956 	case ST_DEV_DATACOMP_PAGE:
7957 	case ST_DEV_CONFIG_PAGE: /* FALLTHROUGH */
7958 		rval = st_gen_mode_sense(un, st_uscsi_cmd, page, un->un_mspl,
7959 		    sizeof (struct seq_mode));
7960 		break;
7961 
7962 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
7963 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
7964 			page = ST_DEV_CONFIG_PAGE;
7965 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
7966 			    un->un_mspl, sizeof (struct seq_mode));
7967 			if (rval == 0 && un->un_mspl->page_code == page) {
7968 				un->un_comp_page = page;
7969 				break;
7970 			}
7971 			page = ST_DEV_DATACOMP_PAGE;
7972 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
7973 			    un->un_mspl, sizeof (struct seq_mode));
7974 			if (rval == 0 && un->un_mspl->page_code == page) {
7975 				un->un_comp_page = page;
7976 				break;
7977 			}
7978 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
7979 			un->un_comp_page = 0;
7980 		} else {
7981 			un->un_comp_page = 0;
7982 		}
7983 
7984 	default:	/* FALLTHROUGH */
7985 		rval = st_cmd(un, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
7986 	}
7987 	return (rval);
7988 }
7989 
7990 static int
7991 st_modeselect(struct scsi_tape *un)
7992 {
7993 	int rval = 0;
7994 	int ix;
7995 
7996 	ST_FUNC(ST_DEVINFO, st_modeselect);
7997 
7998 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7999 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
8000 	    un->un_dev, un->un_mspl->density);
8001 
8002 	ASSERT(mutex_owned(ST_MUTEX));
8003 
8004 	/*
8005 	 * The parameter list should be the same for all of the
8006 	 * cases that follow so set them here
8007 	 *
8008 	 * Try mode select first if if fails set fields manually
8009 	 */
8010 	rval = st_modesense(un);
8011 	if (rval != 0) {
8012 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8013 		    "st_modeselect: First mode sense failed\n");
8014 		un->un_mspl->bd_len  = 8;
8015 		un->un_mspl->high_nb = 0;
8016 		un->un_mspl->mid_nb  = 0;
8017 		un->un_mspl->low_nb  = 0;
8018 	}
8019 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
8020 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
8021 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
8022 
8023 
8024 	/*
8025 	 * If configured to use a specific density code for a media type.
8026 	 * curdens is previously set by the minor node opened.
8027 	 * If the media type doesn't match the minor node we change it so it
8028 	 * looks like the correct one was opened.
8029 	 */
8030 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
8031 		uchar_t best;
8032 
8033 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
8034 			if (un->un_mspl->media_type ==
8035 			    un->un_dp->mediatype[ix]) {
8036 				best = ix;
8037 				/*
8038 				 * It matches but it might not be the only one.
8039 				 * Use the highest matching media type but not
8040 				 * to exceed the density selected by the open.
8041 				 */
8042 				if (ix < un->un_curdens) {
8043 					continue;
8044 				}
8045 				un->un_curdens = ix;
8046 				break;
8047 			}
8048 		}
8049 		/* If a match was found best will not be 0xff any more */
8050 		if (best < NDENSITIES) {
8051 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8052 			    "found media 0x%X using density 0x%X\n",
8053 			    un->un_mspl->media_type,
8054 			    un->un_dp->densities[best]);
8055 			un->un_mspl->density = un->un_dp->densities[best];
8056 		} else {
8057 			/* Otherwise set density based on minor node opened */
8058 			un->un_mspl->density =
8059 			    un->un_dp->densities[un->un_curdens];
8060 		}
8061 	} else {
8062 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
8063 	}
8064 
8065 	if (un->un_dp->options & ST_NOBUF) {
8066 		un->un_mspl->bufm = 0;
8067 	} else {
8068 		un->un_mspl->bufm = 1;
8069 	}
8070 
8071 	rval = st_set_compression(un);
8072 
8073 	/*
8074 	 * If st_set_compression returned invalid or already it
8075 	 * found no need to do the mode select.
8076 	 * So do it here.
8077 	 */
8078 	if ((rval == ENOTTY) || (rval == EALREADY)) {
8079 
8080 		/* Zero non-writeable fields */
8081 		un->un_mspl->data_len = 0;
8082 		un->un_mspl->media_type = 0;
8083 		un->un_mspl->wp = 0;
8084 
8085 		/* need to set the density code */
8086 		rval = st_cmd(un, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
8087 		if (rval != 0) {
8088 			if (un->un_state >= ST_STATE_OPEN) {
8089 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8090 				    "unable to set tape mode\n");
8091 				un->un_pos.pmode = invalid;
8092 				rval = EIO;
8093 			} else {
8094 				rval = -1;
8095 			}
8096 		}
8097 	}
8098 
8099 	/*
8100 	 * The spec recommends to send a mode sense after a mode select
8101 	 */
8102 	(void) st_modesense(un);
8103 
8104 	ASSERT(mutex_owned(ST_MUTEX));
8105 
8106 	return (rval);
8107 }
8108 
8109 /*
8110  * st_gen_mode_sense
8111  *
8112  * generic mode sense.. it allows for any page
8113  */
8114 static int
8115 st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
8116     struct seq_mode *page_data, int page_size)
8117 {
8118 
8119 	int r;
8120 	char	cdb[CDB_GROUP0];
8121 	struct uscsi_cmd *com;
8122 
8123 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
8124 
8125 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8126 
8127 	bzero(cdb, CDB_GROUP0);
8128 	cdb[0] = SCMD_MODE_SENSE;
8129 	cdb[2] = (char)page;
8130 	cdb[4] = (char)page_size;
8131 
8132 	com->uscsi_cdb = cdb;
8133 	com->uscsi_cdblen = CDB_GROUP0;
8134 	com->uscsi_bufaddr = (caddr_t)page_data;
8135 	com->uscsi_buflen = page_size;
8136 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8137 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8138 
8139 	r = ubf(un, com, FKIOCTL);
8140 	kmem_free(com, sizeof (*com));
8141 	return (r);
8142 }
8143 
8144 /*
8145  * st_gen_mode_select
8146  *
8147  * generic mode select.. it allows for any page
8148  */
8149 static int
8150 st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
8151     struct seq_mode *page_data, int page_size)
8152 {
8153 
8154 	int r;
8155 	char cdb[CDB_GROUP0];
8156 	struct uscsi_cmd *com;
8157 
8158 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
8159 
8160 	/* Zero non-writeable fields */
8161 	page_data->data_len = 0;
8162 	page_data->media_type = 0;
8163 	page_data->wp = 0;
8164 
8165 	/*
8166 	 * If mode select has any page data, zero the ps (Page Savable) bit.
8167 	 */
8168 	if (page_size > MSIZE) {
8169 		page_data->ps = 0;
8170 	}
8171 
8172 
8173 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8174 
8175 	/*
8176 	 * then, do a mode select to set what ever info
8177 	 */
8178 	bzero(cdb, CDB_GROUP0);
8179 	cdb[0] = SCMD_MODE_SELECT;
8180 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
8181 	cdb[4] = (char)page_size;
8182 
8183 	com->uscsi_cdb = cdb;
8184 	com->uscsi_cdblen = CDB_GROUP0;
8185 	com->uscsi_bufaddr = (caddr_t)page_data;
8186 	com->uscsi_buflen = page_size;
8187 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8188 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_WRITE;
8189 
8190 	r = ubf(un, com, FKIOCTL);
8191 
8192 	kmem_free(com, sizeof (*com));
8193 	return (r);
8194 }
8195 
8196 static int
8197 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
8198 {
8199 	int rval;
8200 	char cdb[CDB_GROUP0];
8201 	struct uscsi_cmd *com;
8202 
8203 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
8204 
8205 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8206 
8207 	bzero(cdb, CDB_GROUP0);
8208 	cdb[0] = SCMD_READ_BLKLIM;
8209 
8210 	com->uscsi_cdb = cdb;
8211 	com->uscsi_cdblen = CDB_GROUP0;
8212 	com->uscsi_bufaddr = (caddr_t)read_blk;
8213 	com->uscsi_buflen = sizeof (struct read_blklim);
8214 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8215 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8216 
8217 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8218 	if (com->uscsi_status || com->uscsi_resid) {
8219 		rval = -1;
8220 	}
8221 
8222 	kmem_free(com, sizeof (*com));
8223 	return (rval);
8224 }
8225 
8226 static int
8227 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
8228     size_t buflen)
8229 {
8230 	int rval;
8231 	char cdb[CDB_GROUP1];
8232 	struct uscsi_cmd *com;
8233 
8234 	ST_FUNC(ST_DEVINFO, st_report_density_support);
8235 
8236 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8237 
8238 	bzero(cdb, CDB_GROUP1);
8239 	cdb[0] = SCMD_REPORT_DENSITIES;
8240 	cdb[7] = (buflen & 0xff00) >> 8;
8241 	cdb[8] = buflen & 0xff;
8242 
8243 	com->uscsi_cdb = cdb;
8244 	com->uscsi_cdblen = CDB_GROUP1;
8245 	com->uscsi_bufaddr = (caddr_t)density_data;
8246 	com->uscsi_buflen = buflen;
8247 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8248 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8249 
8250 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8251 	if (com->uscsi_status || com->uscsi_resid) {
8252 		rval = -1;
8253 	}
8254 
8255 	kmem_free(com, sizeof (*com));
8256 	return (rval);
8257 }
8258 
8259 static int
8260 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
8261     uchar_t option_code, ushort_t service_action)
8262 {
8263 	int rval;
8264 	char cdb[CDB_GROUP5];
8265 	struct uscsi_cmd *com;
8266 	uint32_t allo_length;
8267 
8268 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
8269 
8270 	allo_length = sizeof (struct one_com_des) +
8271 	    sizeof (struct com_timeout_des);
8272 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8273 
8274 	bzero(cdb, CDB_GROUP5);
8275 	cdb[0] = (char)SCMD_MAINTENANCE_IN;
8276 	cdb[1] = 0x0c; /* service action */
8277 	if (service_action) {
8278 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
8279 		cdb[4] = (service_action & 0xff00) >> 8;
8280 		cdb[5] = service_action & 0xff;
8281 	} else {
8282 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
8283 		    0x80); /* RCTD */
8284 	}
8285 	cdb[3] = option_code;
8286 	cdb[6] = (allo_length & 0xff000000) >> 24;
8287 	cdb[7] = (allo_length & 0xff0000) >> 16;
8288 	cdb[8] = (allo_length & 0xff00) >> 8;
8289 	cdb[9] = allo_length & 0xff;
8290 
8291 	com->uscsi_cdb = cdb;
8292 	com->uscsi_cdblen = CDB_GROUP5;
8293 	com->uscsi_bufaddr = (caddr_t)oper_data;
8294 	com->uscsi_buflen = allo_length;
8295 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8296 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8297 
8298 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8299 	if (com->uscsi_status) {
8300 		rval = -1;
8301 	}
8302 
8303 	kmem_free(com, sizeof (*com));
8304 	return (rval);
8305 }
8306 
8307 /*
8308  * Changes devices blocksize and bsize to requested blocksize nblksz.
8309  * Returns returned value from first failed call or zero on success.
8310  */
8311 static int
8312 st_change_block_size(struct scsi_tape *un, uint32_t nblksz)
8313 {
8314 	struct seq_mode *current;
8315 	int rval;
8316 	uint32_t oldblksz;
8317 
8318 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8319 
8320 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8321 
8322 	current = kmem_zalloc(MSIZE, KM_SLEEP);
8323 
8324 	/*
8325 	 * If we haven't got the compression page yet, do that first.
8326 	 */
8327 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
8328 		(void) st_modesense(un);
8329 	}
8330 
8331 	/* Read current settings */
8332 	rval = st_gen_mode_sense(un, st_uscsi_cmd, 0, current, MSIZE);
8333 	if (rval != 0) {
8334 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8335 		    "mode sense for change block size failed: rval = %d", rval);
8336 		goto finish;
8337 	}
8338 
8339 	/* Figure the current block size */
8340 	oldblksz =
8341 	    (current->high_bl << 16) |
8342 	    (current->mid_bl << 8) |
8343 	    (current->low_bl);
8344 
8345 	/* If current block size is the same as requested were done */
8346 	if (oldblksz == nblksz) {
8347 		un->un_bsize = nblksz;
8348 		rval = 0;
8349 		goto finish;
8350 	}
8351 
8352 	/* Change to requested block size */
8353 	current->high_bl = (uchar_t)(nblksz >> 16);
8354 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8355 	current->low_bl  = (uchar_t)(nblksz);
8356 
8357 	/* Attempt to change block size */
8358 	rval = st_gen_mode_select(un, st_uscsi_cmd, current, MSIZE);
8359 	if (rval != 0) {
8360 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8361 		    "Set new block size failed: rval = %d", rval);
8362 		goto finish;
8363 	}
8364 
8365 	/* Read back and verify setting */
8366 	rval = st_modesense(un);
8367 	if (rval == 0) {
8368 		un->un_bsize =
8369 		    (un->un_mspl->high_bl << 16) |
8370 		    (un->un_mspl->mid_bl << 8) |
8371 		    (un->un_mspl->low_bl);
8372 
8373 		if (un->un_bsize != nblksz) {
8374 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8375 			    "Blocksize set does not equal requested blocksize"
8376 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8377 			rval = EIO;
8378 		}
8379 	}
8380 finish:
8381 	kmem_free(current, MSIZE);
8382 	return (rval);
8383 }
8384 
8385 
8386 static void
8387 st_init(struct scsi_tape *un)
8388 {
8389 	ST_FUNC(ST_DEVINFO, st_init);
8390 
8391 	ASSERT(mutex_owned(ST_MUTEX));
8392 
8393 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8394 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8395 	    un->un_dev);
8396 
8397 	un->un_pos.blkno = 0;
8398 	un->un_pos.fileno = 0;
8399 	un->un_lastop = ST_OP_NIL;
8400 	un->un_pos.eof = ST_NO_EOF;
8401 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8402 	if (st_error_level != SCSI_ERR_ALL) {
8403 		if (DEBUGGING) {
8404 			st_error_level = SCSI_ERR_ALL;
8405 		} else {
8406 			st_error_level = SCSI_ERR_RETRYABLE;
8407 		}
8408 	}
8409 }
8410 
8411 
8412 static void
8413 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8414 {
8415 	struct scsi_pkt *pkt;
8416 	struct uscsi_cmd *ucmd;
8417 	recov_info *ri;
8418 	int tval = 0;
8419 	uint64_t count;
8420 	uint32_t additional;
8421 	int flags = 0;
8422 	int cdb_len = CDB_GROUP0; /* default */
8423 	uchar_t com;
8424 	char fixbit;
8425 	char short_fm = 0;
8426 	int stat_size =
8427 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
8428 
8429 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8430 
8431 	ASSERT(mutex_owned(ST_MUTEX));
8432 
8433 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8434 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8435 
8436 
8437 	/*
8438 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8439 	 * Length Indicator bits on read/write commands, for setting
8440 	 * the Long bit on erase commands, and for setting the Code
8441 	 * Field bits on space commands.
8442 	 */
8443 
8444 	/* regular raw I/O */
8445 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
8446 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8447 		    CDB_GROUP0, stat_size, st_recov_sz, 0, func,
8448 		    (caddr_t)un);
8449 		if (pkt == NULL) {
8450 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8451 			    "Read Write scsi_init_pkt() failure\n");
8452 			goto exit;
8453 		}
8454 		ASSERT(pkt->pkt_resid == 0);
8455 #ifdef STDEBUG
8456 		bzero(pkt->pkt_private, st_recov_sz);
8457 		bzero(pkt->pkt_scbp, stat_size);
8458 #endif
8459 		ri = (recov_info *)pkt->pkt_private;
8460 		ri->privatelen = st_recov_sz;
8461 		if (un->un_bsize == 0) {
8462 			count = bp->b_bcount;
8463 			fixbit = 0;
8464 		} else {
8465 			count = bp->b_bcount / un->un_bsize;
8466 			fixbit = 1;
8467 		}
8468 		if (bp->b_flags & B_READ) {
8469 			com = SCMD_READ;
8470 			un->un_lastop = ST_OP_READ;
8471 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8472 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8473 				fixbit = 2;
8474 			}
8475 		} else {
8476 			com = SCMD_WRITE;
8477 			un->un_lastop = ST_OP_WRITE;
8478 		}
8479 		tval = un->un_dp->io_timeout;
8480 
8481 		/*
8482 		 * For really large xfers, increase timeout
8483 		 */
8484 		if (bp->b_bcount > (10 * ONE_MEG))
8485 			tval *= bp->b_bcount/(10 * ONE_MEG);
8486 
8487 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8488 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8489 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8490 
8491 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8492 		/*
8493 		 * uscsi - build command, allocate scsi resources
8494 		 */
8495 		st_make_uscsi_cmd(un, ucmd, bp, func);
8496 		goto exit;
8497 
8498 	} else {				/* special I/O */
8499 		struct buf *allocbp = NULL;
8500 		com = (uchar_t)(uintptr_t)bp->b_forw;
8501 		count = bp->b_bcount;
8502 
8503 		switch (com) {
8504 		case SCMD_READ:
8505 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8506 			    "special read %"PRId64"\n", count);
8507 			if (un->un_bsize == 0) {
8508 				fixbit = 2;	/* suppress SILI */
8509 			} else {
8510 				fixbit = 1;	/* Fixed Block Mode */
8511 				count /= un->un_bsize;
8512 			}
8513 			allocbp = bp;
8514 			un->un_lastop = ST_OP_READ;
8515 			tval = un->un_dp->io_timeout;
8516 			break;
8517 
8518 		case SCMD_WRITE:
8519 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8520 			    "special write %"PRId64"\n", count);
8521 			if (un->un_bsize != 0) {
8522 				fixbit = 1;	/* Fixed Block Mode */
8523 				count /= un->un_bsize;
8524 			} else {
8525 				fixbit = 0;
8526 			}
8527 			allocbp = bp;
8528 			un->un_lastop = ST_OP_WRITE;
8529 			tval = un->un_dp->io_timeout;
8530 			break;
8531 
8532 		case SCMD_WRITE_FILE_MARK:
8533 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8534 			    "write %"PRId64" file marks\n", count);
8535 			un->un_lastop = ST_OP_WEOF;
8536 			fixbit = 0;
8537 			tval = un->un_dp->io_timeout;
8538 			/*
8539 			 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8540 			 * device, set the Vendor Unique bit to
8541 			 * write Short File Mark.
8542 			 */
8543 			if ((un->un_dp->options & ST_SHORT_FILEMARKS) &&
8544 			    ((un->un_dp->type == ST_TYPE_EXB8500) ||
8545 			    (un->un_dp->type == ST_TYPE_EXABYTE))) {
8546 				/*
8547 				 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8548 				 * is set to to write Short File Mark
8549 				 */
8550 				short_fm = 1;
8551 			}
8552 			break;
8553 
8554 		case SCMD_REWIND:
8555 			/*
8556 			 * In the case of rewind we're gona do the rewind with
8557 			 * the immediate bit set so status will be retured when
8558 			 * the command is accepted by the device. We clear the
8559 			 * B_ASYNC flag so we wait for that acceptance.
8560 			 */
8561 			if (bp->b_flags & B_ASYNC) {
8562 				allocbp = bp;
8563 				if (count) {
8564 					fixbit = 1;
8565 					bp->b_flags &= ~B_ASYNC;
8566 				}
8567 			} else {
8568 				fixbit = 0;
8569 			}
8570 			count = 0;
8571 			bp->b_bcount = 0;
8572 			un->un_lastop = ST_OP_CTL;
8573 			tval = un->un_dp->rewind_timeout;
8574 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8575 			    "rewind\n");
8576 			break;
8577 
8578 		case SCMD_SPACE_G4:
8579 			cdb_len = CDB_GROUP4;
8580 		case SCMD_SPACE: /* FALL THROUGH */
8581 			fixbit = SPACE_TYPE(bp->b_bcount);
8582 			count = SPACE_CNT(bp->b_bcount);
8583 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8584 			    " %s space %s %"PRId64" from file %d blk %d\n",
8585 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8586 			    space_strs[fixbit & 7], count,
8587 			    un->un_pos.fileno, un->un_pos.blkno);
8588 			additional = count >> 32;
8589 			count &= 0xffffffff;
8590 			un->un_lastop = ST_OP_CTL;
8591 			tval = un->un_dp->space_timeout;
8592 			break;
8593 
8594 		case SCMD_LOAD:
8595 			ASSERT(count < 10);
8596 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8597 			    "%s tape\n", load_strs[count]);
8598 			fixbit = 0;
8599 
8600 			/* Loading or Unloading */
8601 			if (count & LD_LOAD) {
8602 				tval = un->un_dp->load_timeout;
8603 			} else {
8604 				tval = un->un_dp->unload_timeout;
8605 			}
8606 			/* Is Retension requested */
8607 			if (count & LD_RETEN) {
8608 				tval += un->un_dp->rewind_timeout;
8609 			}
8610 			un->un_lastop = ST_OP_CTL;
8611 			break;
8612 
8613 		case SCMD_ERASE:
8614 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8615 			    "erase tape\n");
8616 			ASSERT(count == 1); /* mt sets this */
8617 			if (count == 1) {
8618 				/*
8619 				 * do long erase
8620 				 */
8621 				fixbit = 1; /* Long */
8622 
8623 				/* Drive might not honor immidiate bit */
8624 				tval = un->un_dp->erase_timeout;
8625 			} else {
8626 				/* Short Erase */
8627 				tval = un->un_dp->erase_timeout;
8628 				fixbit = 0;
8629 			}
8630 			un->un_lastop = ST_OP_CTL;
8631 			count = 0;
8632 			break;
8633 
8634 		case SCMD_MODE_SENSE:
8635 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8636 			    "mode sense\n");
8637 			allocbp = bp;
8638 			fixbit = 0;
8639 			tval = un->un_dp->non_motion_timeout;
8640 			un->un_lastop = ST_OP_CTL;
8641 			break;
8642 
8643 		case SCMD_MODE_SELECT:
8644 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8645 			    "mode select\n");
8646 			allocbp = bp;
8647 			fixbit = 0;
8648 			tval = un->un_dp->non_motion_timeout;
8649 			un->un_lastop = ST_OP_CTL;
8650 			break;
8651 
8652 		case SCMD_RESERVE:
8653 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8654 			    "reserve\n");
8655 			fixbit = 0;
8656 			tval = un->un_dp->non_motion_timeout;
8657 			un->un_lastop = ST_OP_CTL;
8658 			break;
8659 
8660 		case SCMD_RELEASE:
8661 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8662 			    "release\n");
8663 			fixbit = 0;
8664 			tval = un->un_dp->non_motion_timeout;
8665 			un->un_lastop = ST_OP_CTL;
8666 			break;
8667 
8668 		case SCMD_READ_BLKLIM:
8669 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8670 			    "read block limits\n");
8671 			allocbp = bp;
8672 			fixbit = count = 0;
8673 			tval = un->un_dp->non_motion_timeout;
8674 			un->un_lastop = ST_OP_CTL;
8675 			break;
8676 
8677 		case SCMD_TEST_UNIT_READY:
8678 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8679 			    "test unit ready\n");
8680 			fixbit = 0;
8681 			tval = un->un_dp->non_motion_timeout;
8682 			un->un_lastop = ST_OP_CTL;
8683 			break;
8684 
8685 		case SCMD_DOORLOCK:
8686 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8687 			    "prevent/allow media removal\n");
8688 			fixbit = 0;
8689 			tval = un->un_dp->non_motion_timeout;
8690 			un->un_lastop = ST_OP_CTL;
8691 			break;
8692 
8693 		case SCMD_READ_POSITION:
8694 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8695 			    "read position\n");
8696 			fixbit = un->un_read_pos_type;
8697 			cdb_len = CDB_GROUP1;
8698 			tval = un->un_dp->non_motion_timeout;
8699 			allocbp = bp;
8700 			un->un_lastop = ST_OP_CTL;
8701 			switch (un->un_read_pos_type) {
8702 			case LONG_POS:
8703 				count = 0;
8704 				break;
8705 			case EXT_POS:
8706 				count = sizeof (tape_position_ext_t);
8707 				break;
8708 			case SHORT_POS:
8709 				count = 0;
8710 				break;
8711 			default:
8712 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8713 				    "Unknown read position type 0x%x in "
8714 				    " st_make_cmd()\n", un->un_read_pos_type);
8715 			}
8716 			break;
8717 
8718 		default:
8719 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8720 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8721 			    com);
8722 		}
8723 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8724 		    st_recov_sz, 0, func, (caddr_t)un);
8725 		if (pkt == NULL) {
8726 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8727 			    "generic command scsi_init_pkt() failure\n");
8728 			goto exit;
8729 		}
8730 
8731 		ASSERT(pkt->pkt_resid == 0);
8732 #ifdef STDEBUG
8733 		bzero(pkt->pkt_private, st_recov_sz);
8734 		bzero(pkt->pkt_scbp, stat_size);
8735 #endif
8736 		ri = (recov_info *)pkt->pkt_private;
8737 		ri->privatelen = st_recov_sz;
8738 		if (allocbp) {
8739 			ASSERT(geterror(allocbp) == 0);
8740 		}
8741 
8742 	}
8743 
8744 
8745 	(void) scsi_setup_cdb((union scsi_cdb *)pkt->pkt_cdbp,
8746 	    com, 0, (uint_t)count, additional);
8747 	FILL_SCSI1_LUN(un->un_sd, pkt);
8748 	/*
8749 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8750 	 */
8751 	((union scsi_cdb *)(pkt->pkt_cdbp))->t_code = fixbit;
8752 	((union scsi_cdb *)pkt->pkt_cdbp)->g0_vu_1 = short_fm;
8753 	pkt->pkt_flags = flags;
8754 
8755 	ASSERT(tval);
8756 	pkt->pkt_time = tval;
8757 	if (bp == un->un_recov_buf) {
8758 		pkt->pkt_comp = st_recov_cb;
8759 	} else {
8760 		pkt->pkt_comp = st_intr;
8761 	}
8762 
8763 	st_add_recovery_info_to_pkt(un, bp, pkt);
8764 
8765 exit:
8766 	ASSERT(mutex_owned(ST_MUTEX));
8767 }
8768 
8769 
8770 /*
8771  * Build a command based on a uscsi command;
8772  */
8773 static void
8774 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
8775     struct buf *bp, int (*func)(caddr_t))
8776 {
8777 	struct scsi_pkt *pkt;
8778 	recov_info *ri;
8779 	caddr_t cdb;
8780 	int	cdblen;
8781 	int	stat_size = 1;
8782 	int	flags = 0;
8783 
8784 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
8785 
8786 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8787 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
8788 
8789 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
8790 		if (un->un_arq_enabled) {
8791 			if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
8792 				stat_size = (int)(ucmd->uscsi_rqlen) +
8793 				    sizeof (struct scsi_arq_status) -
8794 				    sizeof (struct scsi_extended_sense);
8795 				flags = PKT_XARQ;
8796 			} else {
8797 				stat_size = sizeof (struct scsi_arq_status);
8798 			}
8799 		}
8800 	}
8801 
8802 	ASSERT(mutex_owned(ST_MUTEX));
8803 
8804 	cdb = ucmd->uscsi_cdb;
8805 	cdblen = ucmd->uscsi_cdblen;
8806 
8807 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8808 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
8809 	    ucmd->uscsi_buflen, bp->b_bcount);
8810 	pkt = scsi_init_pkt(ROUTE, NULL,
8811 	    (bp->b_bcount > 0) ? bp : NULL,
8812 	    cdblen, stat_size, st_recov_sz, flags, func, (caddr_t)un);
8813 	if (pkt == NULL) {
8814 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8815 		    "uscsi command scsi_init_pkt() failure\n");
8816 		goto exit;
8817 	}
8818 
8819 	ASSERT(pkt->pkt_resid == 0);
8820 #ifdef STDEBUG
8821 	bzero(pkt->pkt_private, st_recov_sz);
8822 	bzero(pkt->pkt_scbp, stat_size);
8823 #endif
8824 	ri = (recov_info *)pkt->pkt_private;
8825 	ri->privatelen = st_recov_sz;
8826 
8827 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
8828 
8829 #ifdef STDEBUG
8830 	if ((st_debug & 0x7) >= 6) {
8831 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8832 		    "pkt_cdbp", (char *)cdb, cdblen);
8833 	}
8834 #endif
8835 
8836 	if (ucmd->uscsi_flags & USCSI_SILENT) {
8837 		pkt->pkt_flags |= FLAG_SILENT;
8838 	}
8839 
8840 	pkt->pkt_time = ucmd->uscsi_timeout;
8841 	if (bp == un->un_recov_buf) {
8842 		pkt->pkt_comp = st_recov_cb;
8843 	} else {
8844 		pkt->pkt_comp = st_intr;
8845 	}
8846 	st_add_recovery_info_to_pkt(un, bp, pkt);
8847 exit:
8848 	ASSERT(mutex_owned(ST_MUTEX));
8849 }
8850 
8851 
8852 /*
8853  * restart cmd currently at the head of the runq
8854  *
8855  * If scsi_transport() succeeds or the retries
8856  * count exhausted, restore the throttle that was
8857  * zeroed out in st_handle_intr_busy().
8858  *
8859  */
8860 static void
8861 st_intr_restart(void *arg)
8862 {
8863 	struct scsi_tape *un = arg;
8864 	struct buf *bp;
8865 	int queued;
8866 	int status = TRAN_ACCEPT;
8867 
8868 	mutex_enter(ST_MUTEX);
8869 
8870 	ST_FUNC(ST_DEVINFO, st_intr_restart);
8871 
8872 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8873 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
8874 
8875 	un->un_hib_tid = 0;
8876 
8877 	if (un->un_recov_buf_busy != 0) {
8878 		bp = un->un_recov_buf;
8879 		queued = 0;
8880 	} else if (un->un_sbuf_busy != 0) {
8881 		bp = un->un_sbufp;
8882 		queued = 0;
8883 	} else if (un->un_quef != NULL) {
8884 		bp = un->un_quef;
8885 		queued = 1;
8886 	} else {
8887 		mutex_exit(ST_MUTEX);
8888 		return;
8889 	}
8890 
8891 	/*
8892 	 * Here we know :
8893 	 *	throttle = 0, via st_handle_intr_busy
8894 	 */
8895 
8896 	if (queued) {
8897 		/*
8898 		 * move from waitq to runq, if there is anything on the waitq
8899 		 */
8900 		(void) st_remove_from_queue(&un->un_quef, &un->un_quef, bp);
8901 
8902 		if (un->un_runqf) {
8903 			/*
8904 			 * not good, we don't want to requeue something after
8905 			 * another.
8906 			 */
8907 			mutex_exit(ST_MUTEX);
8908 			goto done_error;
8909 		} else {
8910 			un->un_runqf = bp;
8911 			un->un_runql = bp;
8912 		}
8913 	}
8914 
8915 	ST_CDB(ST_DEVINFO, "Interrupt restart CDB",
8916 	    (char *)BP_PKT(bp)->pkt_cdbp);
8917 
8918 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
8919 
8920 	status = st_transport(un, BP_PKT(bp));
8921 
8922 	if (status != TRAN_ACCEPT) {
8923 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8924 		mutex_exit(ST_MUTEX);
8925 
8926 		if (status == TRAN_BUSY) {
8927 			if (st_handle_intr_busy(un, bp,
8928 			    ST_TRAN_BUSY_TIMEOUT) == 0)
8929 				return;	/* timeout is setup again */
8930 		}
8931 
8932 	} else {
8933 		un->un_tran_retry_ct = 0;
8934 		if (un->un_last_throttle) {
8935 			un->un_throttle = un->un_last_throttle;
8936 		}
8937 		mutex_exit(ST_MUTEX);
8938 		return;
8939 	}
8940 
8941 done_error:
8942 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8943 	    "restart transport rejected\n");
8944 	bp->b_resid = bp->b_bcount;
8945 
8946 #ifndef __lock_lint
8947 	/*
8948 	 * warlock doesn't understand this potential
8949 	 * recursion?
8950 	 */
8951 	mutex_enter(ST_MUTEX);
8952 	if (un->un_last_throttle) {
8953 		un->un_throttle = un->un_last_throttle;
8954 	}
8955 	if (status != TRAN_ACCEPT)
8956 		ST_DO_ERRSTATS(un, st_transerrs);
8957 	ST_DO_KSTATS(bp, kstat_waitq_exit);
8958 	st_set_pe_flag(un);
8959 	st_bioerror(bp, EIO);
8960 	st_done_and_mutex_exit(un, bp);
8961 #endif
8962 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8963 	    "busy restart aborted\n");
8964 }
8965 
8966 /*
8967  * st_check_media():
8968  * Periodically check the media state using scsi_watch service;
8969  * this service calls back after TUR and possibly request sense
8970  * the callback handler (st_media_watch_cb()) decodes the request sense
8971  * data (if any)
8972  */
8973 
8974 static int
8975 st_check_media(dev_t dev, enum mtio_state state)
8976 {
8977 	int rval = 0;
8978 	enum mtio_state	prev_state;
8979 	opaque_t token = NULL;
8980 
8981 	GET_SOFT_STATE(dev);
8982 
8983 	ST_FUNC(ST_DEVINFO, st_check_media);
8984 
8985 	mutex_enter(ST_MUTEX);
8986 
8987 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8988 	    "st_check_media:state=%x, mediastate=%x\n",
8989 	    state, un->un_mediastate);
8990 
8991 	prev_state = un->un_mediastate;
8992 
8993 	/*
8994 	 * is there anything to do?
8995 	 */
8996 retry:
8997 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
8998 		/*
8999 		 * submit the request to the scsi_watch service;
9000 		 * scsi_media_watch_cb() does the real work
9001 		 */
9002 		mutex_exit(ST_MUTEX);
9003 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
9004 		    st_check_media_time, SENSE_LENGTH,
9005 		    st_media_watch_cb, (caddr_t)dev);
9006 		if (token == NULL) {
9007 			rval = EAGAIN;
9008 			goto done;
9009 		}
9010 		mutex_enter(ST_MUTEX);
9011 
9012 		un->un_swr_token = token;
9013 		un->un_specified_mediastate = state;
9014 
9015 		/*
9016 		 * now wait for media change
9017 		 * we will not be signalled unless mediastate == state but it
9018 		 * still better to test for this condition, since there
9019 		 * is a 5 sec cv_broadcast delay when
9020 		 *  mediastate == MTIO_INSERTED
9021 		 */
9022 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9023 		    "st_check_media:waiting for media state change\n");
9024 		while (un->un_mediastate == state) {
9025 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
9026 				mutex_exit(ST_MUTEX);
9027 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9028 				    "st_check_media:waiting for media state "
9029 				    "was interrupted\n");
9030 				rval = EINTR;
9031 				goto done;
9032 			}
9033 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9034 			    "st_check_media:received signal, state=%x\n",
9035 			    un->un_mediastate);
9036 		}
9037 	}
9038 
9039 	/*
9040 	 * if we transitioned to MTIO_INSERTED, media has really been
9041 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
9042 	 * Reset and retry the state change.  If everything is ok, replay
9043 	 * the open() logic.
9044 	 */
9045 	if ((un->un_mediastate == MTIO_INSERTED) &&
9046 	    (un->un_state == ST_STATE_OFFLINE)) {
9047 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9048 		    "st_check_media: calling st_cmd to confirm inserted\n");
9049 
9050 		/*
9051 		 * set this early so that TUR will make it through strategy
9052 		 * without triggering a st_tape_init().  We needed it set
9053 		 * before calling st_tape_init() ourselves anyway.  If TUR
9054 		 * fails, set it back
9055 		 */
9056 		un->un_state = ST_STATE_INITIALIZING;
9057 
9058 		/*
9059 		 * If not reserved fail as getting reservation conflict
9060 		 * will make this hang forever.
9061 		 */
9062 		if ((un->un_rsvd_status &
9063 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9064 			mutex_exit(ST_MUTEX);
9065 			rval = EACCES;
9066 			goto done;
9067 		}
9068 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
9069 		if (rval == EACCES) {
9070 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9071 			    "st_check_media: TUR got Reservation Conflict\n");
9072 			mutex_exit(ST_MUTEX);
9073 			goto done;
9074 		}
9075 		if (rval) {
9076 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9077 			    "st_check_media: TUR failed, going to retry\n");
9078 			un->un_mediastate = prev_state;
9079 			un->un_state = ST_STATE_OFFLINE;
9080 			goto retry;
9081 		}
9082 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9083 		    "st_check_media: media inserted\n");
9084 
9085 		/* this also rewinds the tape */
9086 		rval = st_tape_init(un);
9087 		if (rval != 0) {
9088 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9089 			    "st_check_media : OFFLINE init failure ");
9090 			un->un_state = ST_STATE_OFFLINE;
9091 			un->un_pos.pmode = invalid;
9092 		} else {
9093 			un->un_state = ST_STATE_OPEN_PENDING_IO;
9094 		}
9095 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
9096 	    (un->un_state != ST_STATE_OFFLINE)) {
9097 		/*
9098 		 * supported devices must be rewound before ejection
9099 		 * rewind resets fileno & blkno
9100 		 */
9101 		un->un_laststate = un->un_state;
9102 		un->un_state = ST_STATE_OFFLINE;
9103 	}
9104 	mutex_exit(ST_MUTEX);
9105 done:
9106 	if (token) {
9107 		(void) scsi_watch_request_terminate(token,
9108 		    SCSI_WATCH_TERMINATE_WAIT);
9109 		mutex_enter(ST_MUTEX);
9110 		un->un_swr_token = (opaque_t)NULL;
9111 		mutex_exit(ST_MUTEX);
9112 	}
9113 
9114 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
9115 
9116 	return (rval);
9117 }
9118 
9119 /*
9120  * st_media_watch_cb() is called by scsi_watch_thread for
9121  * verifying the request sense data (if any)
9122  */
9123 static int
9124 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
9125 {
9126 	struct scsi_status *statusp = resultp->statusp;
9127 	struct scsi_extended_sense *sensep = resultp->sensep;
9128 	uchar_t actual_sense_length = resultp->actual_sense_length;
9129 	struct scsi_tape *un;
9130 	enum mtio_state state = MTIO_NONE;
9131 	int instance;
9132 	dev_t dev = (dev_t)arg;
9133 
9134 	instance = MTUNIT(dev);
9135 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
9136 		return (-1);
9137 	}
9138 
9139 	mutex_enter(ST_MUTEX);
9140 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
9141 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9142 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
9143 	    *((char *)statusp), (void *)sensep,
9144 	    actual_sense_length);
9145 
9146 
9147 	/*
9148 	 * if there was a check condition then sensep points to valid
9149 	 * sense data
9150 	 * if status was not a check condition but a reservation or busy
9151 	 * status then the new state is MTIO_NONE
9152 	 */
9153 	if (sensep) {
9154 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9155 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
9156 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
9157 
9158 		switch (un->un_dp->type) {
9159 		default:
9160 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9161 			    "st_media_watch_cb: unknown drive type %d, "
9162 			    "default to ST_TYPE_HP\n", un->un_dp->type);
9163 		/* FALLTHROUGH */
9164 
9165 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
9166 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
9167 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
9168 			if (un->un_dp->type == ST_TYPE_FUJI) {
9169 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9170 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
9171 			} else {
9172 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9173 				    "st_media_watch_cb: ST_TYPE_HP\n");
9174 			}
9175 			switch (sensep->es_key) {
9176 			case KEY_UNIT_ATTENTION:
9177 				/* not ready to ready transition */
9178 				/* hp/es_qual_code == 80 on>off>on */
9179 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
9180 				if (sensep->es_add_code == 0x28) {
9181 					state = MTIO_INSERTED;
9182 				}
9183 				break;
9184 			case KEY_NOT_READY:
9185 				/* in process, rewinding or loading */
9186 				if ((sensep->es_add_code == 0x04) &&
9187 				    (sensep->es_qual_code == 0x00)) {
9188 					state = MTIO_EJECTED;
9189 				}
9190 				break;
9191 			}
9192 			break;
9193 
9194 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
9195 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9196 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
9197 			switch (sensep->es_key) {
9198 			case KEY_UNIT_ATTENTION:
9199 				/* operator medium removal request */
9200 				if ((sensep->es_add_code == 0x5a) &&
9201 				    (sensep->es_qual_code == 0x01)) {
9202 					state = MTIO_EJECTED;
9203 				/* not ready to ready transition */
9204 				} else if ((sensep->es_add_code == 0x28) &&
9205 				    (sensep->es_qual_code == 0x00)) {
9206 					state = MTIO_INSERTED;
9207 				}
9208 				break;
9209 			case KEY_NOT_READY:
9210 				/* medium not present */
9211 				if (sensep->es_add_code == 0x3a) {
9212 					state = MTIO_EJECTED;
9213 				}
9214 				break;
9215 			}
9216 			break;
9217 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
9218 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9219 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
9220 			switch (sensep->es_key) {
9221 			case KEY_NOT_READY:
9222 				if ((sensep->es_add_code == 0x04) &&
9223 				    (sensep->es_qual_code == 0x00)) {
9224 					/* volume not mounted? */
9225 					state = MTIO_EJECTED;
9226 				} else if (sensep->es_add_code == 0x3a) {
9227 					state = MTIO_EJECTED;
9228 				}
9229 				break;
9230 			case KEY_UNIT_ATTENTION:
9231 				state = MTIO_EJECTED;
9232 				break;
9233 			}
9234 			break;
9235 
9236 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
9237 			switch (sensep->es_key) {
9238 			case KEY_UNIT_ATTENTION:
9239 				if (sensep->es_add_code == 0x28) {
9240 					state = MTIO_INSERTED;
9241 				}
9242 				break;
9243 			case KEY_NOT_READY:
9244 				if (sensep->es_add_code == 0x04) {
9245 					/* in transition but could be either */
9246 					state = un->un_specified_mediastate;
9247 				} else if ((sensep->es_add_code == 0x3a) &&
9248 				    (sensep->es_qual_code == 0x00)) {
9249 					state = MTIO_EJECTED;
9250 				}
9251 				break;
9252 			}
9253 			break;
9254 		}
9255 	} else if (*((char *)statusp) == STATUS_GOOD) {
9256 		state = MTIO_INSERTED;
9257 	}
9258 
9259 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9260 	    "st_media_watch_cb:state=%x, specified=%x\n",
9261 	    state, un->un_specified_mediastate);
9262 
9263 	/*
9264 	 * now signal the waiting thread if this is *not* the specified state;
9265 	 * delay the signal if the state is MTIO_INSERTED
9266 	 * to allow the target to recover
9267 	 */
9268 	if (state != un->un_specified_mediastate) {
9269 		un->un_mediastate = state;
9270 		if (state == MTIO_INSERTED) {
9271 			/*
9272 			 * delay the signal to give the drive a chance
9273 			 * to do what it apparently needs to do
9274 			 */
9275 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9276 			    "st_media_watch_cb:delayed cv_broadcast\n");
9277 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
9278 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
9279 		} else {
9280 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9281 			    "st_media_watch_cb:immediate cv_broadcast\n");
9282 			cv_broadcast(&un->un_state_cv);
9283 		}
9284 	}
9285 	mutex_exit(ST_MUTEX);
9286 	return (0);
9287 }
9288 
9289 /*
9290  * delayed cv_broadcast to allow for target to recover
9291  * from media insertion
9292  */
9293 static void
9294 st_delayed_cv_broadcast(void *arg)
9295 {
9296 	struct scsi_tape *un = arg;
9297 
9298 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
9299 
9300 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9301 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
9302 
9303 	mutex_enter(ST_MUTEX);
9304 	cv_broadcast(&un->un_state_cv);
9305 	mutex_exit(ST_MUTEX);
9306 }
9307 
9308 /*
9309  * restart cmd currently at the start of the waitq
9310  */
9311 static void
9312 st_start_restart(void *arg)
9313 {
9314 	struct scsi_tape *un = arg;
9315 
9316 	ST_FUNC(ST_DEVINFO, st_start_restart);
9317 
9318 	ASSERT(un != NULL);
9319 
9320 	mutex_enter(ST_MUTEX);
9321 
9322 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_tran_restart()\n");
9323 
9324 	st_start(un);
9325 
9326 	mutex_exit(ST_MUTEX);
9327 }
9328 
9329 
9330 /*
9331  * Command completion processing
9332  *
9333  */
9334 static void
9335 st_intr(struct scsi_pkt *pkt)
9336 {
9337 	recov_info *rcv = pkt->pkt_private;
9338 	struct buf *bp = rcv->cmd_bp;
9339 	struct scsi_tape *un;
9340 	errstate action = COMMAND_DONE;
9341 	clock_t	timout;
9342 	int	status;
9343 
9344 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
9345 
9346 	ST_FUNC(ST_DEVINFO, st_intr);
9347 
9348 	ASSERT(un != NULL);
9349 
9350 	mutex_enter(ST_MUTEX);
9351 
9352 	ASSERT(bp != un->un_recov_buf);
9353 
9354 	un->un_rqs_state &= ~(ST_RQS_ERROR);
9355 
9356 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
9357 
9358 	if (pkt->pkt_reason != CMD_CMPLT) {
9359 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9360 		    "Unhappy packet status reason = %s statistics = 0x%x\n",
9361 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9362 
9363 		/* If device has gone away not much else to do */
9364 		if (pkt->pkt_reason == CMD_DEV_GONE) {
9365 			action = COMMAND_DONE_ERROR;
9366 		} else if ((pkt == un->un_rqs) ||
9367 		    (un->un_state == ST_STATE_SENSING)) {
9368 			ASSERT(pkt == un->un_rqs);
9369 			ASSERT(un->un_state == ST_STATE_SENSING);
9370 			un->un_state = un->un_laststate;
9371 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp =
9372 			    un->un_rqs_bp;
9373 			ST_DO_ERRSTATS(un, st_transerrs);
9374 			action = COMMAND_DONE_ERROR;
9375 		} else {
9376 			action = st_handle_incomplete(un, bp);
9377 		}
9378 	/*
9379 	 * At this point we know that the command was successfully
9380 	 * completed. Now what?
9381 	 */
9382 	} else if ((pkt == un->un_rqs) || (un->un_state == ST_STATE_SENSING)) {
9383 		/*
9384 		 * okay. We were running a REQUEST SENSE. Find
9385 		 * out what to do next.
9386 		 */
9387 		ASSERT(pkt == un->un_rqs);
9388 		ASSERT(un->un_state == ST_STATE_SENSING);
9389 		scsi_sync_pkt(pkt);
9390 		action = st_handle_sense(un, bp, &un->un_pos);
9391 		/*
9392 		 * Make rqs isn't going to be retied.
9393 		 */
9394 		if (action != QUE_BUSY_COMMAND && action != QUE_COMMAND) {
9395 			/*
9396 			 * set pkt back to original packet in case we will have
9397 			 * to requeue it
9398 			 */
9399 			pkt = BP_PKT(bp);
9400 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp =
9401 			    un->un_rqs_bp;
9402 			/*
9403 			 * some actions are based on un_state, hence
9404 			 * restore the state st was in before ST_STATE_SENSING.
9405 			 */
9406 			un->un_state = un->un_laststate;
9407 		}
9408 
9409 	} else if (un->un_arq_enabled && (pkt->pkt_state & STATE_ARQ_DONE)) {
9410 		/*
9411 		 * the transport layer successfully completed an autorqsense
9412 		 */
9413 		action = st_handle_autosense(un, bp, &un->un_pos);
9414 
9415 	} else  if ((SCBP(pkt)->sts_busy) ||
9416 	    (SCBP(pkt)->sts_chk) ||
9417 	    (SCBP(pkt)->sts_vu7)) {
9418 		/*
9419 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9420 		 * to see if the status bits we're okay. If a request sense
9421 		 * is to be run, that will happen.
9422 		 */
9423 		action = st_check_error(un, pkt);
9424 	}
9425 
9426 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9427 		switch (action) {
9428 			case QUE_COMMAND:
9429 				/*
9430 				 * return cmd to head to the queue
9431 				 * since we are suspending so that
9432 				 * it gets restarted during resume
9433 				 */
9434 				st_add_to_queue(&un->un_runqf, &un->un_runql,
9435 				    un->un_runqf, bp);
9436 
9437 				action = JUST_RETURN;
9438 				break;
9439 
9440 			case QUE_SENSE:
9441 				action = COMMAND_DONE_ERROR;
9442 				break;
9443 
9444 			default:
9445 				break;
9446 		}
9447 	}
9448 
9449 	/*
9450 	 * Restore old state if we were sensing.
9451 	 */
9452 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9453 		un->un_state = un->un_laststate;
9454 	}
9455 
9456 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9457 	    "st_intr: pkt=%p, bp=%p, action=%x, status=%x\n",
9458 	    (void *)pkt, (void *)bp, action, SCBP_C(pkt));
9459 
9460 again:
9461 	switch (action) {
9462 	case COMMAND_DONE_EACCES:
9463 		/* this is to report a reservation conflict */
9464 		st_bioerror(bp, EACCES);
9465 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9466 		    "Reservation Conflict \n");
9467 		un->un_pos.pmode = invalid;
9468 
9469 		/*FALLTHROUGH*/
9470 	case COMMAND_DONE_ERROR:
9471 		if (un->un_pos.eof < ST_EOT_PENDING &&
9472 		    un->un_state >= ST_STATE_OPEN) {
9473 			/*
9474 			 * all errors set state of the tape to 'unknown'
9475 			 * unless we're at EOT or are doing append testing.
9476 			 * If sense key was illegal request, preserve state.
9477 			 */
9478 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9479 				un->un_pos.pmode = invalid;
9480 			}
9481 		}
9482 
9483 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9484 		/*
9485 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9486 		 * make sure an error ocurrs, so make sure at least EIO is
9487 		 * returned
9488 		 */
9489 		if (geterror(bp) == 0)
9490 			st_bioerror(bp, EIO);
9491 
9492 		st_set_pe_flag(un);
9493 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9494 		    (un->un_errno == EIO)) {
9495 			un->un_rqs_state &= ~(ST_RQS_VALID);
9496 		}
9497 		break;
9498 
9499 	case COMMAND_DONE_ERROR_RECOVERED:
9500 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9501 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9502 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9503 		if (geterror(bp) == 0) {
9504 			st_bioerror(bp, EIO);
9505 		}
9506 		st_set_pe_flag(un);
9507 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9508 		    (un->un_errno == EIO)) {
9509 			un->un_rqs_state &= ~(ST_RQS_VALID);
9510 		}
9511 		/*FALLTHROUGH*/
9512 	case COMMAND_DONE:
9513 		st_set_state(un, bp);
9514 		break;
9515 
9516 	case QUE_SENSE:
9517 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9518 			goto sense_error;
9519 
9520 		if (un->un_state != ST_STATE_SENSING) {
9521 			un->un_laststate = un->un_state;
9522 			un->un_state = ST_STATE_SENSING;
9523 		}
9524 
9525 		/*
9526 		 * zero the sense data.
9527 		 */
9528 		bzero(un->un_rqs->pkt_scbp, SENSE_LENGTH);
9529 
9530 		/*
9531 		 * If this is not a retry on QUE_SENSE point to the original
9532 		 * bp of the command that got us here.
9533 		 */
9534 		if (pkt != un->un_rqs) {
9535 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp = bp;
9536 		}
9537 
9538 		if (un->un_throttle) {
9539 			un->un_last_throttle = un->un_throttle;
9540 			un->un_throttle = 0;
9541 		}
9542 
9543 		ST_CDB(ST_DEVINFO, "Queue sense CDB",
9544 		    (char *)BP_PKT(bp)->pkt_cdbp);
9545 
9546 		/*
9547 		 * never retry this, some other command will have nuked the
9548 		 * sense, anyway
9549 		 */
9550 		status = st_transport(un, un->un_rqs);
9551 
9552 		if (un->un_last_throttle) {
9553 			un->un_throttle = un->un_last_throttle;
9554 		}
9555 
9556 		if (status == TRAN_ACCEPT) {
9557 			mutex_exit(ST_MUTEX);
9558 			return;
9559 		}
9560 		if (status != TRAN_BUSY)
9561 			ST_DO_ERRSTATS(un, st_transerrs);
9562 sense_error:
9563 		un->un_pos.pmode = invalid;
9564 		st_bioerror(bp, EIO);
9565 		st_set_pe_flag(un);
9566 		break;
9567 
9568 	case QUE_BUSY_COMMAND:
9569 		/* longish timeout */
9570 		timout = ST_STATUS_BUSY_TIMEOUT;
9571 		goto que_it_up;
9572 
9573 	case QUE_COMMAND:
9574 		/* short timeout */
9575 		timout = ST_TRAN_BUSY_TIMEOUT;
9576 que_it_up:
9577 		/*
9578 		 * let st_handle_intr_busy put this bp back on waitq and make
9579 		 * checks to see if it is ok to requeue the command.
9580 		 */
9581 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9582 
9583 		/*
9584 		 * Save the throttle before setting up the timeout
9585 		 */
9586 		if (un->un_throttle) {
9587 			un->un_last_throttle = un->un_throttle;
9588 		}
9589 		mutex_exit(ST_MUTEX);
9590 		if (st_handle_intr_busy(un, bp, timout) == 0)
9591 			return;		/* timeout is setup again */
9592 
9593 		mutex_enter(ST_MUTEX);
9594 		un->un_pos.pmode = invalid;
9595 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9596 		st_bioerror(bp, EIO);
9597 		st_set_pe_flag(un);
9598 		break;
9599 
9600 	case QUE_LAST_COMMAND:
9601 
9602 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9603 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9604 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9605 			goto last_command_error;
9606 		}
9607 		mutex_exit(ST_MUTEX);
9608 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9609 			return;
9610 		mutex_enter(ST_MUTEX);
9611 last_command_error:
9612 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9613 		un->un_pos.pmode = invalid;
9614 		st_bioerror(bp, EIO);
9615 		st_set_pe_flag(un);
9616 		break;
9617 
9618 	case COMMAND_TIMEOUT:
9619 	case DEVICE_RESET:
9620 	case DEVICE_TAMPER:
9621 	case ATTEMPT_RETRY:
9622 		action = st_command_recovery(un, pkt, action);
9623 		goto again;
9624 
9625 	default:
9626 		ASSERT(0);
9627 		/* FALLTHRU */
9628 	case JUST_RETURN:
9629 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9630 		mutex_exit(ST_MUTEX);
9631 		return;
9632 	}
9633 
9634 	ST_DO_KSTATS(bp, kstat_runq_exit);
9635 	st_done_and_mutex_exit(un, bp);
9636 }
9637 
9638 static errstate
9639 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9640 {
9641 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9642 	recov_info *rinfo;
9643 	errstate rval = COMMAND_DONE_ERROR;
9644 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9645 	    un->un_rqs : BP_PKT(bp);
9646 	int result;
9647 
9648 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9649 
9650 	rinfo = (recov_info *)pkt->pkt_private;
9651 
9652 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9653 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9654 
9655 	ASSERT(mutex_owned(ST_MUTEX));
9656 
9657 	switch (pkt->pkt_reason) {
9658 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9659 		/*
9660 		 * this occurs when accessing a powered down drive, no
9661 		 * need to complain; just fail the open
9662 		 */
9663 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9664 
9665 		/*
9666 		 * if we have commands outstanding in HBA, and a command
9667 		 * comes back incomplete, we're hosed, so reset target
9668 		 * If we have the bus, but cmd_incomplete, we probably just
9669 		 * have a failed selection, so don't reset the target, just
9670 		 * requeue the command and try again
9671 		 */
9672 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9673 			goto reset_target;
9674 		}
9675 
9676 		/*
9677 		 * Retry selection a couple more times if we're
9678 		 * open.  If opening, we only try just once to
9679 		 * reduce probe time for nonexistant devices.
9680 		 */
9681 		if ((un->un_laststate > ST_STATE_OPENING) &&
9682 		    ((int)un->un_retry_ct < st_selection_retry_count)) {
9683 /* XXX check retriable? */
9684 			rval = QUE_COMMAND;
9685 		}
9686 		ST_DO_ERRSTATS(un, st_transerrs);
9687 		break;
9688 
9689 	case CMD_ABORTED:
9690 		/*
9691 		 * most likely this is caused by flush-on-error support. If
9692 		 * it was not there, the we're in trouble.
9693 		 */
9694 		if (!un->un_flush_on_errors) {
9695 			un->un_status = SUN_KEY_FATAL;
9696 			goto reset_target;
9697 		}
9698 
9699 		st_set_pe_errno(un);
9700 		bioerror(bp, un->un_errno);
9701 		if (un->un_errno)
9702 			return (COMMAND_DONE_ERROR);
9703 		else
9704 			return (COMMAND_DONE);
9705 
9706 	case CMD_TIMEOUT:	/* Command timed out */
9707 		un->un_status = SUN_KEY_TIMEOUT;
9708 		return (COMMAND_TIMEOUT);
9709 
9710 	case CMD_TRAN_ERR:
9711 	case CMD_RESET:
9712 		if (pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET)) {
9713 			if ((un->un_rsvd_status &
9714 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
9715 			    ST_RESERVE) {
9716 				un->un_rsvd_status |= ST_LOST_RESERVE;
9717 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
9718 				    "Lost Reservation\n");
9719 			}
9720 			rval = DEVICE_RESET;
9721 			return (rval);
9722 		}
9723 		if (pkt->pkt_statistics & (STAT_ABORTED | STAT_TERMINATED)) {
9724 			rval = DEVICE_RESET;
9725 			return (rval);
9726 		}
9727 		/*FALLTHROUGH*/
9728 	default:
9729 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9730 		    "Unhandled packet status reason = %s statistics = 0x%x\n",
9731 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9732 reset_target:
9733 
9734 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9735 		    "transport completed with %s\n",
9736 		    scsi_rname(pkt->pkt_reason));
9737 		ST_DO_ERRSTATS(un, st_transerrs);
9738 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
9739 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
9740 		    STAT_ABORTED)) == 0)) {
9741 
9742 			/*
9743 			 * If we haven't reserved the drive don't reset it.
9744 			 */
9745 			if ((un->un_rsvd_status &
9746 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9747 				return (rval);
9748 			}
9749 
9750 			/*
9751 			 * if we aren't lost yet we will be soon.
9752 			 */
9753 			un->un_pos.pmode = invalid;
9754 
9755 			result = st_reset(un, RESET_LUN);
9756 
9757 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
9758 				/* no hope left to recover */
9759 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
9760 				    "recovery by resets failed\n");
9761 				return (rval);
9762 			}
9763 		}
9764 	}
9765 
9766 
9767 	if ((int)un->un_retry_ct++ < st_retry_count) {
9768 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9769 			rval = QUE_COMMAND;
9770 		} else if (bp == un->un_sbufp) {
9771 			if (rinfo->privatelen == sizeof (recov_info)) {
9772 				if (rinfo->cmd_attrib->retriable) {
9773 					/*
9774 					 * These commands can be rerun
9775 					 * with impunity
9776 					 */
9777 					rval = QUE_COMMAND;
9778 				}
9779 			} else {
9780 				cmd_attribute const *attrib;
9781 				attrib =
9782 				    st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
9783 				if (attrib->retriable) {
9784 					rval = QUE_COMMAND;
9785 				}
9786 			}
9787 		}
9788 	} else {
9789 		rval = COMMAND_DONE_ERROR;
9790 	}
9791 
9792 	if (un->un_state >= ST_STATE_OPEN) {
9793 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9794 		    fail, scsi_rname(pkt->pkt_reason),
9795 		    (rval == COMMAND_DONE_ERROR)?
9796 		    "giving up" : "retrying command");
9797 	}
9798 	return (rval);
9799 }
9800 
9801 /*
9802  * if the device is busy, then put this bp back on the waitq, on the
9803  * interrupt thread, where we want the head of the queue and not the
9804  * end
9805  *
9806  * The callers of this routine should take measures to save the
9807  * un_throttle in un_last_throttle which will be restored in
9808  * st_intr_restart(). The only exception should be st_intr_restart()
9809  * calling this routine for which the saving is already done.
9810  */
9811 static int
9812 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
9813 	clock_t timeout_interval)
9814 {
9815 
9816 	int queued;
9817 	int rval = 0;
9818 
9819 	mutex_enter(ST_MUTEX);
9820 
9821 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
9822 
9823 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9824 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
9825 
9826 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
9827 		queued = 1;
9828 	} else {
9829 		queued = 0;
9830 	}
9831 
9832 	/*
9833 	 * Check to see if we hit the retry timeout. We check to make sure
9834 	 * this is the first one on the runq and make sure we have not
9835 	 * queued up any more, so this one has to be the last on the list
9836 	 * also. If it is not, we have to fail.  If it is not the first, but
9837 	 * is the last we are in trouble anyway, as we are in the interrupt
9838 	 * context here.
9839 	 */
9840 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
9841 	    ((un->un_runqf != bp) && (un->un_runql != bp) && (queued))) {
9842 		rval = -1;
9843 		goto exit;
9844 	}
9845 
9846 	/* put the bp back on the waitq */
9847 	if (queued) {
9848 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
9849 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
9850 	}
9851 
9852 	/*
9853 	 * We don't want any other commands being started in the mean time.
9854 	 * If start had just released mutex after putting something on the
9855 	 * runq, we won't even get here.
9856 	 */
9857 	un->un_throttle = 0;
9858 
9859 	/*
9860 	 * send a marker pkt, if appropriate
9861 	 */
9862 	st_hba_unflush(un);
9863 
9864 	/*
9865 	 * all queues are aligned, we are just waiting to
9866 	 * transport
9867 	 */
9868 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
9869 
9870 exit:
9871 	mutex_exit(ST_MUTEX);
9872 	return (rval);
9873 }
9874 
9875 /*
9876  * To get one error entry from error stack
9877  */
9878 static int
9879 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
9880 {
9881 #ifdef _MULTI_DATAMODEL
9882 	/*
9883 	 * For use when a 32 bit app makes a call into a
9884 	 * 64 bit ioctl
9885 	 */
9886 	struct mterror_entry32 err_entry32;
9887 #endif /* _MULTI_DATAMODEL */
9888 
9889 	int rval = 0;
9890 	struct mterror_entry err_entry;
9891 	struct mterror_entry_stack *err_link_entry_p;
9892 	size_t arq_status_len_in, arq_status_len_kr;
9893 
9894 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
9895 
9896 	ASSERT(mutex_owned(ST_MUTEX));
9897 
9898 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9899 	    "st_get_error_entry()\n");
9900 
9901 	/*
9902 	 * if error record stack empty, return ENXIO
9903 	 */
9904 	if (un->un_error_entry_stk == NULL) {
9905 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9906 		    "st_get_error_entry: Error Entry Stack Empty!\n");
9907 		rval = ENXIO;
9908 		goto ret;
9909 	}
9910 
9911 	/*
9912 	 * get the top entry from stack
9913 	 */
9914 	err_link_entry_p = un->un_error_entry_stk;
9915 	arq_status_len_kr =
9916 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
9917 
9918 #ifdef _MULTI_DATAMODEL
9919 	switch (ddi_model_convert_from(flag & FMODELS)) {
9920 	case DDI_MODEL_ILP32:
9921 		if (ddi_copyin((void *)arg, &err_entry32,
9922 		    MTERROR_ENTRY_SIZE_32, flag)) {
9923 			rval = EFAULT;
9924 			goto ret;
9925 		}
9926 
9927 		arq_status_len_in =
9928 		    (size_t)err_entry32.mtee_arq_status_len;
9929 
9930 		err_entry32.mtee_cdb_len =
9931 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
9932 
9933 		if (arq_status_len_in > arq_status_len_kr)
9934 			err_entry32.mtee_arq_status_len =
9935 			    (size32_t)arq_status_len_kr;
9936 
9937 		if (ddi_copyout(
9938 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
9939 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
9940 		    err_entry32.mtee_cdb_len, flag)) {
9941 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9942 			    "st_get_error_entry: Copy cdb buffer error!");
9943 			rval = EFAULT;
9944 		}
9945 
9946 		if (ddi_copyout(
9947 		    err_link_entry_p->mtees_entry.mtee_arq_status,
9948 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
9949 		    err_entry32.mtee_arq_status_len, flag)) {
9950 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9951 			    "st_get_error_entry: copy arq status error!");
9952 			rval = EFAULT;
9953 		}
9954 
9955 		if (ddi_copyout(&err_entry32, (void *)arg,
9956 		    MTERROR_ENTRY_SIZE_32, flag)) {
9957 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9958 			    "st_get_error_entry: copy arq status out error!");
9959 			rval = EFAULT;
9960 		}
9961 		break;
9962 
9963 	case DDI_MODEL_NONE:
9964 		if (ddi_copyin((void *)arg, &err_entry,
9965 		    MTERROR_ENTRY_SIZE_64, flag)) {
9966 			rval = EFAULT;
9967 			goto ret;
9968 		}
9969 		arq_status_len_in = err_entry.mtee_arq_status_len;
9970 
9971 		err_entry.mtee_cdb_len =
9972 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
9973 
9974 		if (arq_status_len_in > arq_status_len_kr)
9975 			err_entry.mtee_arq_status_len =
9976 			    arq_status_len_kr;
9977 
9978 		if (ddi_copyout(
9979 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
9980 		    err_entry.mtee_cdb_buf,
9981 		    err_entry.mtee_cdb_len, flag)) {
9982 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9983 			    "st_get_error_entry: Copy cdb buffer error!");
9984 			rval = EFAULT;
9985 		}
9986 
9987 		if (ddi_copyout(
9988 		    err_link_entry_p->mtees_entry.mtee_arq_status,
9989 		    err_entry.mtee_arq_status,
9990 		    err_entry.mtee_arq_status_len, flag)) {
9991 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9992 			    "st_get_error_entry: copy arq status error!");
9993 			rval = EFAULT;
9994 		}
9995 
9996 		if (ddi_copyout(&err_entry, (void *)arg,
9997 		    MTERROR_ENTRY_SIZE_64, flag)) {
9998 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9999 			    "st_get_error_entry: copy arq status out error!");
10000 			rval = EFAULT;
10001 		}
10002 		break;
10003 	}
10004 #else /* _MULTI_DATAMODEL */
10005 	if (ddi_copyin((void *)arg, &err_entry,
10006 	    MTERROR_ENTRY_SIZE_64, flag)) {
10007 		rval = EFAULT;
10008 		goto ret;
10009 	}
10010 	arq_status_len_in = err_entry.mtee_arq_status_len;
10011 
10012 	err_entry.mtee_cdb_len =
10013 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
10014 
10015 	if (arq_status_len_in > arq_status_len_kr)
10016 		err_entry.mtee_arq_status_len =
10017 		    arq_status_len_kr;
10018 
10019 	if (ddi_copyout(
10020 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10021 	    err_entry.mtee_cdb_buf,
10022 	    err_entry.mtee_cdb_len, flag)) {
10023 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10024 		    "st_get_error_entry: Copy cdb buffer error!");
10025 		rval = EFAULT;
10026 	}
10027 
10028 	if (ddi_copyout(
10029 	    err_link_entry_p->mtees_entry.mtee_arq_status,
10030 	    err_entry.mtee_arq_status,
10031 	    err_entry.mtee_arq_status_len, flag)) {
10032 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10033 		    "st_get_error_entry: copy arq status buffer error!");
10034 		rval = EFAULT;
10035 	}
10036 
10037 	if (ddi_copyout(&err_entry, (void *)arg,
10038 	    MTERROR_ENTRY_SIZE_64, flag)) {
10039 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10040 		    "st_get_error_entry: copy arq status out error!");
10041 		rval = EFAULT;
10042 	}
10043 #endif /* _MULTI_DATAMODEL */
10044 
10045 	/*
10046 	 * update stack
10047 	 */
10048 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
10049 
10050 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
10051 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
10052 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
10053 
10054 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
10055 	    SECMDS_STATUS_SIZE);
10056 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
10057 
10058 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
10059 	err_link_entry_p = NULL;
10060 ret:
10061 	return (rval);
10062 }
10063 
10064 /*
10065  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
10066  * the scsi CDB command which causes the error and generates sense data and
10067  * the scsi status.
10068  *
10069  *      error-record stack
10070  *
10071  *
10072  *             TOP                                     BOTTOM
10073  *              ------------------------------------------
10074  *              |   0   |   1   |   2   |   ...  |   n   |
10075  *              ------------------------------------------
10076  *                  ^
10077  *                  |
10078  *       pointer to error entry
10079  *
10080  * when st driver generates one sense data record, it creates a error-entry
10081  * and pushes it onto the stack.
10082  *
10083  */
10084 
10085 static void
10086 st_update_error_stack(struct scsi_tape *un,
10087 			struct scsi_pkt *pkt,
10088 			struct scsi_arq_status *cmd)
10089 {
10090 	struct mterror_entry_stack *err_entry_tmp;
10091 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
10092 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
10093 
10094 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
10095 
10096 	ASSERT(mutex_owned(ST_MUTEX));
10097 
10098 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10099 	    "st_update_error_stack()\n");
10100 
10101 	ASSERT(cmd);
10102 	ASSERT(cdbp);
10103 	if (cdblen == 0) {
10104 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10105 		    "st_update_error_stack: CDB length error!\n");
10106 		return;
10107 	}
10108 
10109 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
10110 	ASSERT(err_entry_tmp != NULL);
10111 
10112 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
10113 	    kmem_alloc(cdblen, KM_SLEEP);
10114 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
10115 
10116 	err_entry_tmp->mtees_entry.mtee_arq_status =
10117 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
10118 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
10119 
10120 	/*
10121 	 * copy cdb command & length to current error entry
10122 	 */
10123 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
10124 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
10125 
10126 	/*
10127 	 * copy scsi status length to current error entry
10128 	 */
10129 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
10130 	    SECMDS_STATUS_SIZE;
10131 
10132 	/*
10133 	 * copy sense data and scsi status to current error entry
10134 	 */
10135 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
10136 	    SECMDS_STATUS_SIZE);
10137 
10138 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
10139 	un->un_error_entry_stk = err_entry_tmp;
10140 
10141 }
10142 
10143 /*
10144  * Empty all the error entry in stack
10145  */
10146 static void
10147 st_empty_error_stack(struct scsi_tape *un)
10148 {
10149 	struct mterror_entry_stack *linkp;
10150 
10151 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
10152 
10153 	ASSERT(mutex_owned(ST_MUTEX));
10154 
10155 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10156 	    "st_empty_entry_stack()\n");
10157 
10158 	while (un->un_error_entry_stk != NULL) {
10159 		linkp = un->un_error_entry_stk;
10160 		un->un_error_entry_stk =
10161 		    un->un_error_entry_stk->mtees_nextp;
10162 
10163 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
10164 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
10165 			    linkp->mtees_entry.mtee_cdb_len);
10166 
10167 		if (linkp->mtees_entry.mtee_arq_status != NULL)
10168 			kmem_free(linkp->mtees_entry.mtee_arq_status,
10169 			    linkp->mtees_entry.mtee_arq_status_len);
10170 
10171 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
10172 		linkp = NULL;
10173 	}
10174 }
10175 
10176 static errstate
10177 st_handle_sense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10178 {
10179 	struct scsi_pkt *pkt = BP_PKT(bp);
10180 	struct scsi_pkt *rqpkt = un->un_rqs;
10181 	struct scsi_arq_status arqstat;
10182 
10183 	errstate rval = COMMAND_DONE_ERROR;
10184 	int amt;
10185 
10186 	ST_FUNC(ST_DEVINFO, st_handle_sense);
10187 
10188 	ASSERT(mutex_owned(ST_MUTEX));
10189 
10190 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10191 	    "st_handle_sense()\n");
10192 
10193 	if (SCBP(rqpkt)->sts_busy) {
10194 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10195 		    "busy unit on request sense\n");
10196 		if ((int)un->un_retry_ct++ < st_retry_count) {
10197 			rval = QUE_BUSY_COMMAND;
10198 		}
10199 		return (rval);
10200 	} else if (SCBP(rqpkt)->sts_chk) {
10201 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10202 		    "Check Condition on REQUEST SENSE\n");
10203 		return (rval);
10204 	}
10205 
10206 	/* was there enough data? */
10207 	amt = (int)MAX_SENSE_LENGTH - rqpkt->pkt_resid;
10208 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
10209 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10210 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10211 		    "REQUEST SENSE couldn't get sense data\n");
10212 		return (rval);
10213 	}
10214 
10215 	bcopy(SCBP(pkt), &arqstat.sts_status,
10216 	    sizeof (struct scsi_status));
10217 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
10218 	    sizeof (struct scsi_status));
10219 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
10220 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
10221 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
10222 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
10223 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
10224 
10225 	/*
10226 	 * copy one arqstat entry in the sense data buffer
10227 	 */
10228 	st_update_error_stack(un, pkt, &arqstat);
10229 	return (st_decode_sense(un, bp, amt, SCBP(rqpkt), pos));
10230 }
10231 
10232 static errstate
10233 st_handle_autosense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10234 {
10235 	struct scsi_pkt *pkt = BP_PKT(bp);
10236 	struct scsi_arq_status *arqstat =
10237 	    (struct scsi_arq_status *)pkt->pkt_scbp;
10238 	errstate rval = COMMAND_DONE_ERROR;
10239 	int amt;
10240 
10241 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
10242 
10243 	ASSERT(mutex_owned(ST_MUTEX));
10244 
10245 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10246 	    "st_handle_autosense()\n");
10247 
10248 	if (arqstat->sts_rqpkt_status.sts_busy) {
10249 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10250 		    "busy unit on request sense\n");
10251 		/*
10252 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
10253 		 * the disadvantage is that we do not have any delay for the
10254 		 * second retry of rqsense and we have to keep a packet around
10255 		 */
10256 		return (QUE_SENSE);
10257 
10258 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
10259 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10260 		    "transport error on REQUEST SENSE\n");
10261 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
10262 		    ((arqstat->sts_rqpkt_statistics &
10263 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
10264 			if (st_reset(un, RESET_LUN) == 0) {
10265 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10266 				    "recovery by resets failed\n");
10267 			}
10268 		}
10269 		return (rval);
10270 
10271 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
10272 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10273 		    "Check Condition on REQUEST SENSE\n");
10274 		return (rval);
10275 	}
10276 
10277 
10278 	/* was there enough data? */
10279 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10280 		amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10281 	} else {
10282 		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
10283 			amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10284 		} else {
10285 			amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10286 		}
10287 	}
10288 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
10289 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10290 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10291 		    "REQUEST SENSE couldn't get sense data\n");
10292 		return (rval);
10293 	}
10294 
10295 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10296 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, MAX_SENSE_LENGTH);
10297 	} else {
10298 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
10299 	}
10300 
10301 	/*
10302 	 * copy one arqstat entry in the sense data buffer
10303 	 */
10304 	st_update_error_stack(un, pkt, arqstat);
10305 
10306 	return (st_decode_sense(un, bp, amt, &arqstat->sts_rqpkt_status, pos));
10307 }
10308 
10309 static errstate
10310 st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
10311     struct scsi_status *statusp, tapepos_t *pos)
10312 {
10313 	struct scsi_pkt *pkt = BP_PKT(bp);
10314 	recov_info *ri = (recov_info *)pkt->pkt_private;
10315 	errstate rval = COMMAND_DONE_ERROR;
10316 	cmd_attribute const *attrib;
10317 	long resid;
10318 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10319 	int severity;
10320 	int get_error;
10321 
10322 	ST_FUNC(ST_DEVINFO, st_decode_sense);
10323 
10324 	ASSERT(mutex_owned(ST_MUTEX));
10325 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10326 	    "st_decode_sense()\n");
10327 
10328 	/*
10329 	 * For uscsi commands, squirrel away a copy of the
10330 	 * results of the Request Sense.
10331 	 */
10332 	if (USCSI_CMD(bp)) {
10333 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
10334 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
10335 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
10336 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
10337 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
10338 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
10339 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10340 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
10341 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
10342 		}
10343 	}
10344 
10345 	if (ri->privatelen == sizeof (recov_info)) {
10346 		attrib = ri->cmd_attrib;
10347 	} else {
10348 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10349 	}
10350 
10351 	/*
10352 	 * If the drive is an MT-02, reposition the
10353 	 * secondary error code into the proper place.
10354 	 *
10355 	 * XXX	MT-02 is non-CCS tape, so secondary error code
10356 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
10357 	 * so it's in byte 12.
10358 	 */
10359 	if (un->un_dp->type == ST_TYPE_EMULEX) {
10360 		sensep->es_code = sensep->es_add_info[0];
10361 	}
10362 
10363 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
10364 	    (caddr_t)&CDBP(pkt)->scc_cmd);
10365 
10366 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)sensep,
10367 	    sizeof (*sensep));
10368 
10369 	/* for normal I/O check extract the resid values. */
10370 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
10371 		if (sensep->es_valid) {
10372 			resid =
10373 			    (sensep->es_info_1 << 24) |
10374 			    (sensep->es_info_2 << 16) |
10375 			    (sensep->es_info_3 << 8)  |
10376 			    (sensep->es_info_4);
10377 			/* If fixed block */
10378 			if (un->un_bsize) {
10379 				resid *= un->un_bsize;
10380 			}
10381 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
10382 			resid = pkt->pkt_resid;
10383 		} else {
10384 			resid = bp->b_bcount;
10385 		}
10386 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10387 		    "st_decode_sense (rw): xferred bit = %d, resid=%ld (%d), "
10388 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
10389 		    resid,
10390 		    (sensep->es_info_1 << 24) |
10391 		    (sensep->es_info_2 << 16) |
10392 		    (sensep->es_info_3 << 8)  |
10393 		    (sensep->es_info_4),
10394 		    pkt->pkt_resid);
10395 		/*
10396 		 * The problem is, what should we believe?
10397 		 */
10398 		if (resid && (pkt->pkt_resid == 0)) {
10399 			pkt->pkt_resid = resid;
10400 		}
10401 	} else {
10402 		/*
10403 		 * If the command is SCMD_SPACE, we need to get the
10404 		 * residual as returned in the sense data, to adjust
10405 		 * our idea of current tape position correctly
10406 		 */
10407 		if ((sensep->es_valid) &&
10408 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10409 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10410 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
10411 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK)) {
10412 			resid =
10413 			    (sensep->es_info_1 << 24) |
10414 			    (sensep->es_info_2 << 16) |
10415 			    (sensep->es_info_3 << 8)  |
10416 			    (sensep->es_info_4);
10417 			bp->b_resid = resid;
10418 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10419 			    "st_decode_sense(other):	resid=%ld\n", resid);
10420 		} else {
10421 			/*
10422 			 * If the special command is SCMD_READ,
10423 			 * the correct resid will be set later.
10424 			 */
10425 			if (attrib->get_cnt != NULL) {
10426 				resid = attrib->get_cnt(pkt->pkt_cdbp);
10427 			} else {
10428 				resid = bp->b_bcount;
10429 			}
10430 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10431 			    "st_decode_sense(special read):  resid=%ld\n",
10432 			    resid);
10433 		}
10434 	}
10435 
10436 	if ((un->un_state >= ST_STATE_OPEN) &&
10437 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
10438 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
10439 		    "Failed CDB", (char *)pkt->pkt_cdbp);
10440 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10441 		    "sense data", (char *)sensep, amt);
10442 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10443 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10444 		    bp->b_bcount, resid, pkt->pkt_resid);
10445 	}
10446 
10447 	switch (un->un_status = sensep->es_key) {
10448 	case KEY_NO_SENSE:
10449 		severity = SCSI_ERR_INFO;
10450 
10451 		/*
10452 		 * Erase, locate or rewind operation in progress, retry
10453 		 * ASC  ASCQ
10454 		 *  00   18    Erase operation in progress
10455 		 *  00   19    Locate operation in progress
10456 		 *  00   1A    Rewind operation in progress
10457 		 */
10458 		if (sensep->es_add_code == 0 &&
10459 		    ((sensep->es_qual_code == 0x18) ||
10460 		    (sensep->es_qual_code == 0x19) ||
10461 		    (sensep->es_qual_code == 0x1a))) {
10462 			rval = QUE_BUSY_COMMAND;
10463 			break;
10464 		}
10465 
10466 		goto common;
10467 
10468 	case KEY_RECOVERABLE_ERROR:
10469 		severity = SCSI_ERR_RECOVERED;
10470 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10471 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10472 			if (un->un_dp->options &
10473 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10474 				rval = QUE_LAST_COMMAND;
10475 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10476 				    severity, pos->lgclblkno,
10477 				    un->un_err_pos.lgclblkno, scsi_cmds,
10478 				    sensep);
10479 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10480 				    "Command will be retried\n");
10481 			} else {
10482 				severity = SCSI_ERR_FATAL;
10483 				rval = COMMAND_DONE_ERROR_RECOVERED;
10484 				ST_DO_ERRSTATS(un, st_softerrs);
10485 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10486 				    severity, pos->lgclblkno,
10487 				    un->un_err_pos.lgclblkno, scsi_cmds,
10488 				    sensep);
10489 			}
10490 			break;
10491 		}
10492 common:
10493 		/*
10494 		 * XXX only want reads to be stopped by filemarks.
10495 		 * Don't want them to be stopped by EOT.  EOT matters
10496 		 * only on write.
10497 		 */
10498 		if (sensep->es_filmk && !sensep->es_eom) {
10499 			rval = COMMAND_DONE;
10500 		} else if (sensep->es_eom) {
10501 			rval = COMMAND_DONE;
10502 		} else if (sensep->es_ili) {
10503 			/*
10504 			 * Fun with variable length record devices:
10505 			 * for specifying larger blocks sizes than the
10506 			 * actual physical record size.
10507 			 */
10508 			if (un->un_bsize == 0 && resid > 0) {
10509 				/*
10510 				 * XXX! Ugly.
10511 				 * The requested blocksize is > tape blocksize,
10512 				 * so this is ok, so we just return the
10513 				 * actual size xferred.
10514 				 */
10515 				pkt->pkt_resid = resid;
10516 				rval = COMMAND_DONE;
10517 			} else if (un->un_bsize == 0 && resid < 0) {
10518 				/*
10519 				 * The requested blocksize is < tape blocksize,
10520 				 * so this is not ok, so we err with ENOMEM
10521 				 */
10522 				rval = COMMAND_DONE_ERROR_RECOVERED;
10523 				st_bioerror(bp, ENOMEM);
10524 			} else {
10525 				ST_DO_ERRSTATS(un, st_softerrs);
10526 				severity = SCSI_ERR_FATAL;
10527 				rval = COMMAND_DONE_ERROR;
10528 				st_bioerror(bp, EINVAL);
10529 				un->un_running.pmode = invalid;
10530 			}
10531 		} else {
10532 			/*
10533 			 * we hope and pray for this just being
10534 			 * something we can ignore (ie. a
10535 			 * truly recoverable soft error)
10536 			 */
10537 			rval = COMMAND_DONE;
10538 		}
10539 		if (sensep->es_filmk) {
10540 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10541 			    "filemark\n");
10542 			un->un_status = SUN_KEY_EOF;
10543 			pos->eof = ST_EOF_PENDING;
10544 			st_set_pe_flag(un);
10545 		}
10546 
10547 		/*
10548 		 * ignore eom when reading, a fmk should terminate reading
10549 		 */
10550 		if ((sensep->es_eom) &&
10551 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10552 			if ((sensep->es_add_code == 0) &&
10553 			    (sensep->es_qual_code == 4)) {
10554 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10555 				    "bot\n");
10556 				un->un_status = SUN_KEY_BOT;
10557 				pos->eof = ST_NO_EOF;
10558 				pos->lgclblkno = 0;
10559 				pos->fileno = 0;
10560 				pos->blkno = 0;
10561 				if (pos->pmode != legacy)
10562 					pos->pmode = legacy;
10563 			} else {
10564 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10565 				    "eom\n");
10566 				un->un_status = SUN_KEY_EOT;
10567 				pos->eof = ST_EOM;
10568 			}
10569 			st_set_pe_flag(un);
10570 		}
10571 
10572 		break;
10573 
10574 	case KEY_ILLEGAL_REQUEST:
10575 
10576 		if (un->un_laststate >= ST_STATE_OPEN) {
10577 			ST_DO_ERRSTATS(un, st_softerrs);
10578 			severity = SCSI_ERR_FATAL;
10579 		} else {
10580 			severity = SCSI_ERR_INFO;
10581 		}
10582 		break;
10583 
10584 	case KEY_MEDIUM_ERROR:
10585 		ST_DO_ERRSTATS(un, st_harderrs);
10586 		severity = SCSI_ERR_FATAL;
10587 
10588 		/*
10589 		 * for (buffered) writes, a medium error must be fatal
10590 		 */
10591 		if (CDBP(pkt)->scc_cmd != SCMD_WRITE) {
10592 			rval = COMMAND_DONE_ERROR_RECOVERED;
10593 		}
10594 
10595 check_keys:
10596 		/*
10597 		 * attempt to process the keys in the presence of
10598 		 * other errors
10599 		 */
10600 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10601 			/*
10602 			 * Fun with variable length record devices:
10603 			 * for specifying larger blocks sizes than the
10604 			 * actual physical record size.
10605 			 */
10606 			if (un->un_bsize == 0 && resid > 0) {
10607 				/*
10608 				 * XXX! Ugly
10609 				 */
10610 				pkt->pkt_resid = resid;
10611 			} else if (un->un_bsize == 0 && resid < 0) {
10612 				st_bioerror(bp, EINVAL);
10613 			} else {
10614 				severity = SCSI_ERR_FATAL;
10615 				rval = COMMAND_DONE_ERROR;
10616 				st_bioerror(bp, EINVAL);
10617 			}
10618 		}
10619 		if (sensep->es_filmk) {
10620 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10621 			    "filemark\n");
10622 			un->un_status = SUN_KEY_EOF;
10623 			pos->eof = ST_EOF_PENDING;
10624 			st_set_pe_flag(un);
10625 		}
10626 
10627 		/*
10628 		 * ignore eom when reading, a fmk should terminate reading
10629 		 */
10630 		if ((sensep->es_eom) &&
10631 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10632 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10633 			un->un_status = SUN_KEY_EOT;
10634 			pos->eof = ST_EOM;
10635 			st_set_pe_flag(un);
10636 		}
10637 
10638 		break;
10639 
10640 	case KEY_VOLUME_OVERFLOW:
10641 		ST_DO_ERRSTATS(un, st_softerrs);
10642 		pos->eof = ST_EOM;
10643 		severity = SCSI_ERR_FATAL;
10644 		rval = COMMAND_DONE_ERROR;
10645 		goto check_keys;
10646 
10647 	case KEY_HARDWARE_ERROR:
10648 		ST_DO_ERRSTATS(un, st_harderrs);
10649 		severity = SCSI_ERR_FATAL;
10650 		rval = COMMAND_DONE_ERROR;
10651 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10652 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10653 		break;
10654 
10655 	case KEY_BLANK_CHECK:
10656 		ST_DO_ERRSTATS(un, st_softerrs);
10657 		severity = SCSI_ERR_INFO;
10658 
10659 		/*
10660 		 * if not a special request and some data was xferred then it
10661 		 * it is not an error yet
10662 		 */
10663 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10664 			/*
10665 			 * no error for read with or without data xferred
10666 			 */
10667 			un->un_status = SUN_KEY_EOT;
10668 			pos->eof = ST_EOT;
10669 			rval = COMMAND_DONE_ERROR;
10670 			st_set_pe_flag(un);
10671 			goto check_keys;
10672 		} else if (bp != un->un_sbufp &&
10673 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10674 			rval = COMMAND_DONE;
10675 		} else {
10676 			rval = COMMAND_DONE_ERROR_RECOVERED;
10677 		}
10678 
10679 		if (un->un_laststate >= ST_STATE_OPEN) {
10680 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10681 			    "blank check\n");
10682 			pos->eof = ST_EOM;
10683 		}
10684 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10685 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10686 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
10687 		    (un->un_dp->options & ST_KNOWS_EOD)) {
10688 			/*
10689 			 * we were doing a fast forward by skipping
10690 			 * multiple fmk at the time
10691 			 */
10692 			st_bioerror(bp, EIO);
10693 			severity = SCSI_ERR_RECOVERED;
10694 			rval	 = COMMAND_DONE;
10695 		}
10696 		st_set_pe_flag(un);
10697 		goto check_keys;
10698 
10699 	case KEY_WRITE_PROTECT:
10700 		if (st_wrongtapetype(un)) {
10701 			un->un_status = SUN_KEY_WRONGMEDIA;
10702 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10703 			    "wrong tape for writing- use DC6150 tape "
10704 			    "(or equivalent)\n");
10705 			severity = SCSI_ERR_UNKNOWN;
10706 		} else {
10707 			severity = SCSI_ERR_FATAL;
10708 		}
10709 		ST_DO_ERRSTATS(un, st_harderrs);
10710 		rval = COMMAND_DONE_ERROR;
10711 		st_bioerror(bp, EACCES);
10712 		break;
10713 
10714 	case KEY_UNIT_ATTENTION:
10715 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10716 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
10717 
10718 		un->un_unit_attention_flags = 1;
10719 		/*
10720 		 * If we have detected a Bus Reset and the tape
10721 		 * drive has been reserved.
10722 		 */
10723 		if (ST_RQSENSE->es_add_code == 0x29) {
10724 			rval = DEVICE_RESET;
10725 			if ((un->un_rsvd_status &
10726 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
10727 			    ST_RESERVE) {
10728 				un->un_rsvd_status |= ST_LOST_RESERVE;
10729 				ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
10730 				    "st_decode_sense: Lost Reservation\n");
10731 			}
10732 		}
10733 
10734 		/*
10735 		 * If this is a recovery command and retrable, retry.
10736 		 */
10737 		if (bp == un->un_recov_buf) {
10738 			severity = SCSI_ERR_INFO;
10739 			if (attrib->retriable &&
10740 			    (int)un->un_retry_ct++ < st_retry_count) {
10741 				rval = QUE_COMMAND;
10742 			} else {
10743 				rval = COMMAND_DONE_ERROR;
10744 			}
10745 			break; /* Don't set position invalid */
10746 		}
10747 		if (un->un_state <= ST_STATE_OPENING) {
10748 			/*
10749 			 * Look, the tape isn't open yet, now determine
10750 			 * if the cause is a BUS RESET, Save the file
10751 			 * and Block positions for the callers to
10752 			 * recover from the loss of position.
10753 			 */
10754 			severity = SCSI_ERR_INFO;
10755 			if ((pos->pmode != invalid) &&
10756 			    (rval == DEVICE_RESET) &&
10757 			    (un->un_restore_pos != 1)) {
10758 				un->un_save_fileno = pos->fileno;
10759 				un->un_save_blkno = pos->blkno;
10760 				un->un_restore_pos = 1;
10761 			}
10762 
10763 			if (attrib->retriable &&
10764 			    (int)un->un_retry_ct++ < st_retry_count) {
10765 				rval = QUE_COMMAND;
10766 			} else if (rval == DEVICE_RESET) {
10767 				break;
10768 			} else {
10769 				rval = COMMAND_DONE_ERROR;
10770 			}
10771 		/*
10772 		 * Means it thinks the mode parameters have changed.
10773 		 * This is the result of a reset clearing settings or
10774 		 * another initiator changing what we set.
10775 		 */
10776 		} else if (ST_RQSENSE->es_add_code == 0x2a) {
10777 			if (ST_RQSENSE->es_qual_code == 0x1) {
10778 				/* Error recovery will modeselect and retry. */
10779 				rval = DEVICE_TAMPER;
10780 				severity = SCSI_ERR_INFO;
10781 				break; /* don't set position invalid */
10782 			}
10783 			if (ST_RQSENSE->es_qual_code == 0x0 ||
10784 			    ST_RQSENSE->es_qual_code == 0x2 ||
10785 			    ST_RQSENSE->es_qual_code == 0x3 ||
10786 			    ST_RQSENSE->es_qual_code == 0x4 ||
10787 			    ST_RQSENSE->es_qual_code == 0x5 ||
10788 			    ST_RQSENSE->es_qual_code == 0x6 ||
10789 			    ST_RQSENSE->es_qual_code == 0x7) {
10790 				rval = DEVICE_TAMPER;
10791 				severity = SCSI_ERR_INFO;
10792 			}
10793 		} else if (ST_RQSENSE->es_add_code == 0x28 &&
10794 		    ((ST_RQSENSE->es_qual_code == 0x0) ||
10795 		    ST_RQSENSE->es_qual_code == 0x5)) {
10796 			/*
10797 			 * Not Ready to Ready change, Media may have changed.
10798 			 */
10799 			rval = DEVICE_TAMPER;
10800 			severity = SCSI_ERR_RETRYABLE;
10801 		} else {
10802 			if (rval != DEVICE_RESET) {
10803 				rval = COMMAND_DONE_ERROR;
10804 			} else {
10805 				/*
10806 				 * Returning DEVICE_RESET will call
10807 				 * error recovery.
10808 				 */
10809 				severity = SCSI_ERR_INFO;
10810 				break; /* don't set position invalid */
10811 			}
10812 			/*
10813 			 * Check if it is an Unexpected Unit Attention.
10814 			 * If state is >= ST_STATE_OPEN, we have
10815 			 * already done the initialization .
10816 			 * In this case it is Fatal Error
10817 			 * since no further reading/writing
10818 			 * can be done with fileno set to < 0.
10819 			 */
10820 			if (un->un_state >= ST_STATE_OPEN) {
10821 				ST_DO_ERRSTATS(un, st_harderrs);
10822 				severity = SCSI_ERR_FATAL;
10823 			} else {
10824 				severity = SCSI_ERR_INFO;
10825 			}
10826 		}
10827 
10828 		pos->pmode = invalid;
10829 
10830 		break;
10831 
10832 	case KEY_NOT_READY:
10833 		/*
10834 		 * If in process of getting ready retry.
10835 		 */
10836 		if (sensep->es_add_code  == 0x04 &&
10837 		    sensep->es_qual_code == 0x01 &&
10838 		    un->un_retry_ct++ < st_retry_count) {
10839 			rval = QUE_COMMAND;
10840 			severity = SCSI_ERR_INFO;
10841 		} else {
10842 			/* give up */
10843 			rval = COMMAND_DONE_ERROR;
10844 			severity = SCSI_ERR_FATAL;
10845 		}
10846 
10847 		/*
10848 		 * If this was an error and after device opened
10849 		 * do error stats.
10850 		 */
10851 		if (rval == COMMAND_DONE_ERROR &&
10852 		    un->un_state > ST_STATE_OPENING) {
10853 			ST_DO_ERRSTATS(un, st_harderrs);
10854 		}
10855 
10856 		if (ST_RQSENSE->es_add_code == 0x3a) {
10857 			if (st_error_level >= SCSI_ERR_FATAL)
10858 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
10859 				    "Tape not inserted in drive\n");
10860 			un->un_mediastate = MTIO_EJECTED;
10861 			cv_broadcast(&un->un_state_cv);
10862 		}
10863 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
10864 		    (rval != QUE_COMMAND))
10865 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10866 		break;
10867 
10868 	case KEY_ABORTED_COMMAND:
10869 		/* XXX Do drives return this when they see a lost light? */
10870 		/* Testing would say yes */
10871 
10872 		if (un->un_retry_ct++ < st_retry_count) {
10873 			rval = ATTEMPT_RETRY;
10874 			severity = SCSI_ERR_RETRYABLE;
10875 			goto check_keys;
10876 		}
10877 		/*
10878 		 * Probably a parity error...
10879 		 * if we retry here then this may cause data to be
10880 		 * written twice or data skipped during reading
10881 		 */
10882 		ST_DO_ERRSTATS(un, st_harderrs);
10883 		severity = SCSI_ERR_FATAL;
10884 		rval = COMMAND_DONE_ERROR;
10885 		goto check_keys;
10886 
10887 	default:
10888 		/*
10889 		 * Undecoded sense key.	 Try retries and hope
10890 		 * that will fix the problem.  Otherwise, we're
10891 		 * dead.
10892 		 */
10893 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10894 		    "Unhandled Sense Key '%s'\n",
10895 		    sense_keys[un->un_status]);
10896 		ST_DO_ERRSTATS(un, st_harderrs);
10897 		severity = SCSI_ERR_FATAL;
10898 		rval = COMMAND_DONE_ERROR;
10899 		goto check_keys;
10900 	}
10901 
10902 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
10903 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
10904 	    (un->un_laststate > ST_STATE_OPENING) &&
10905 	    (severity >= st_error_level))) {
10906 
10907 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
10908 		    pos->lgclblkno, un->un_err_pos.lgclblkno,
10909 		    scsi_cmds, sensep);
10910 		if (sensep->es_filmk) {
10911 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10912 			    "File Mark Detected\n");
10913 		}
10914 		if (sensep->es_eom) {
10915 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10916 			    "End-of-Media Detected\n");
10917 		}
10918 		if (sensep->es_ili) {
10919 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10920 			    "Incorrect Length Indicator Set\n");
10921 		}
10922 	}
10923 	get_error = geterror(bp);
10924 	if (((rval == COMMAND_DONE_ERROR) ||
10925 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
10926 	    ((get_error == EIO) || (get_error == 0))) {
10927 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
10928 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
10929 		if (un->un_rqs_state & ST_RQS_READ) {
10930 			un->un_rqs_state &= ~(ST_RQS_READ);
10931 		} else {
10932 			un->un_rqs_state |= ST_RQS_OVR;
10933 		}
10934 	}
10935 
10936 	return (rval);
10937 }
10938 
10939 
10940 static int
10941 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
10942 {
10943 	int status = TRAN_ACCEPT;
10944 
10945 	mutex_enter(ST_MUTEX);
10946 
10947 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
10948 
10949 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10950 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
10951 
10952 	/*
10953 	 * Check to see if we hit the retry timeout. We check to make sure
10954 	 * this is the first one on the runq and make sure we have not
10955 	 * queued up any more, so this one has to be the last on the list
10956 	 * also. If it is not, we have to fail.  If it is not the first, but
10957 	 * is the last we are in trouble anyway, as we are in the interrupt
10958 	 * context here.
10959 	 */
10960 	if (((int)un->un_retry_ct > st_retry_count) ||
10961 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
10962 		goto exit;
10963 	}
10964 
10965 	if (un->un_throttle) {
10966 		un->un_last_throttle = un->un_throttle;
10967 		un->un_throttle = 0;
10968 	}
10969 
10970 	/*
10971 	 * Here we know : bp is the first and last one on the runq
10972 	 * it is not necessary to put it back on the head of the
10973 	 * waitq and then move from waitq to runq. Save this queuing
10974 	 * and call scsi_transport.
10975 	 */
10976 	ST_CDB(ST_DEVINFO, "Retry lcmd CDB", (char *)BP_PKT(bp)->pkt_cdbp);
10977 
10978 	status = st_transport(un, BP_PKT(bp));
10979 
10980 	if (status == TRAN_ACCEPT) {
10981 		un->un_tran_retry_ct = 0;
10982 		if (un->un_last_throttle) {
10983 			un->un_throttle = un->un_last_throttle;
10984 		}
10985 		mutex_exit(ST_MUTEX);
10986 
10987 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10988 		    "restart transport \n");
10989 		return (0);
10990 	}
10991 
10992 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
10993 	mutex_exit(ST_MUTEX);
10994 
10995 	if (status == TRAN_BUSY) {
10996 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
10997 			return (0);
10998 		}
10999 	}
11000 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11001 	    "restart transport rejected\n");
11002 	mutex_enter(ST_MUTEX);
11003 	ST_DO_ERRSTATS(un, st_transerrs);
11004 	if (un->un_last_throttle) {
11005 		un->un_throttle = un->un_last_throttle;
11006 	}
11007 exit:
11008 	mutex_exit(ST_MUTEX);
11009 	return (-1);
11010 }
11011 
11012 static int
11013 st_wrongtapetype(struct scsi_tape *un)
11014 {
11015 
11016 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
11017 
11018 	ASSERT(mutex_owned(ST_MUTEX));
11019 
11020 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
11021 
11022 	/*
11023 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
11024 	 */
11025 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
11026 		switch (un->un_dp->type) {
11027 		case ST_TYPE_WANGTEK:
11028 		case ST_TYPE_ARCHIVE:
11029 			/*
11030 			 * If this really worked, we could go off of
11031 			 * the density codes set in the modesense
11032 			 * page. For this drive, 0x10 == QIC-120,
11033 			 * 0xf == QIC-150, and 0x5 should be for
11034 			 * both QIC-24 and, maybe, QIC-11. However,
11035 			 * the h/w doesn't do what the manual says
11036 			 * that it should, so we'll key off of
11037 			 * getting a WRITE PROTECT error AND wp *not*
11038 			 * set in the mode sense information.
11039 			 */
11040 			/*
11041 			 * XXX but we already know that status is
11042 			 * write protect, so don't check it again.
11043 			 */
11044 
11045 			if (un->un_status == KEY_WRITE_PROTECT &&
11046 			    un->un_mspl->wp == 0) {
11047 				return (1);
11048 			}
11049 			break;
11050 		default:
11051 			break;
11052 		}
11053 	}
11054 	return (0);
11055 }
11056 
11057 static errstate
11058 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
11059 {
11060 	errstate action;
11061 
11062 	ST_FUNC(ST_DEVINFO, st_check_error);
11063 
11064 	ASSERT(mutex_owned(ST_MUTEX));
11065 
11066 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
11067 
11068 	if (SCBP_C(pkt) == STATUS_RESERVATION_CONFLICT) {
11069 		action = COMMAND_DONE_EACCES;
11070 		un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
11071 	} else if (SCBP(pkt)->sts_busy) {
11072 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
11073 		if ((int)un->un_retry_ct++ < st_retry_count) {
11074 			action = QUE_BUSY_COMMAND;
11075 		} else if ((un->un_rsvd_status &
11076 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
11077 			/*
11078 			 * If this is a command done before reserve is done
11079 			 * don't reset.
11080 			 */
11081 			action = COMMAND_DONE_ERROR;
11082 		} else {
11083 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11084 			    "unit busy too long\n");
11085 			(void) st_reset(un, RESET_ALL);
11086 			action = COMMAND_DONE_ERROR;
11087 		}
11088 	} else if (SCBP(pkt)->sts_chk) {
11089 		/*
11090 		 * we should only get here if the auto rqsense failed
11091 		 * thru a uscsi cmd without autorequest sense
11092 		 * so we just try again
11093 		 */
11094 		action = QUE_SENSE;
11095 	} else if (SCBP(pkt)->sts_vu7) {
11096 		/*
11097 		 * This is an aborted task. This can be a reset on the other
11098 		 * port of a multiport drive. Lets try and recover it.
11099 		 */
11100 		action = DEVICE_RESET;
11101 	} else {
11102 		action = COMMAND_DONE;
11103 	}
11104 	return (action);
11105 }
11106 
11107 static void
11108 st_calc_bnum(struct scsi_tape *un, struct buf *bp, struct scsi_pkt *pkt)
11109 {
11110 	int nblks;
11111 	long count;
11112 	recov_info *ri = (recov_info *)pkt->pkt_private;
11113 	cmd_attribute const *attrib;
11114 
11115 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
11116 
11117 	ASSERT(mutex_owned(ST_MUTEX));
11118 
11119 	if (ri->privatelen == sizeof (recov_info)) {
11120 		attrib = ri->cmd_attrib;
11121 		ASSERT(attrib->recov_pos_type == POS_EXPECTED);
11122 		ASSERT(attrib->chg_tape_pos);
11123 	} else {
11124 		ri = NULL;
11125 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
11126 	}
11127 
11128 	count = bp->b_bcount - bp->b_resid;
11129 
11130 	/* If variable block mode */
11131 	if (un->un_bsize == 0) {
11132 		nblks = ((count == 0) ? 0 : 1);
11133 		un->un_kbytes_xferred += (count / ONE_K);
11134 	} else {
11135 		nblks = (count / un->un_bsize);
11136 		un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
11137 	}
11138 
11139 	/*
11140 	 * If some command failed after this one started and it seems
11141 	 * to have finshed without error count the position.
11142 	 */
11143 	if (un->un_persistence && un->un_persist_errors) {
11144 		ASSERT(un->un_pos.pmode != invalid);
11145 	}
11146 
11147 	if (attrib->chg_tape_direction == DIR_FORW) {
11148 		un->un_pos.blkno += nblks;
11149 		un->un_pos.lgclblkno += nblks;
11150 	} else if (attrib->chg_tape_direction == DIR_REVC) {
11151 		un->un_pos.blkno -= nblks;
11152 		un->un_pos.lgclblkno -= nblks;
11153 	} else {
11154 		ASSERT(0);
11155 	}
11156 
11157 	/* recovery disabled */
11158 	if (ri == NULL) {
11159 		un->un_running.pmode = invalid;
11160 		return;
11161 	}
11162 
11163 	/*
11164 	 * If we didn't just read a filemark.
11165 	 */
11166 	if (un->un_pos.eof != ST_EOF_PENDING) {
11167 		ASSERT(nblks != 0);
11168 		/*
11169 		 * If Previously calulated expected position does not match
11170 		 * debug the expected position.
11171 		 */
11172 		if ((ri->pos.pmode != invalid) && nblks &&
11173 		    ((un->un_pos.blkno != ri->pos.blkno) ||
11174 		    (un->un_pos.lgclblkno != ri->pos.lgclblkno))) {
11175 #ifdef STDEBUG
11176 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11177 			    "Expected", &ri->pos);
11178 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11179 			    "But Got", &un->un_pos);
11180 #endif
11181 			un->un_running.pmode = invalid;
11182 		}
11183 	} else {
11184 		ASSERT(nblks == 0);
11185 		if (un->un_running.pmode != invalid) {
11186 			/*
11187 			 * blkno and lgclblkno already counted in
11188 			 * st_add_recovery_info_to_pkt(). Since a block was not
11189 			 * read and a filemark was.
11190 			 */
11191 			if (attrib->chg_tape_direction == DIR_FORW) {
11192 				un->un_running.fileno++;
11193 				un->un_running.blkno = 0;
11194 			} else if (attrib->chg_tape_direction == DIR_REVC) {
11195 				un->un_running.fileno--;
11196 				un->un_running.blkno = LASTBLK;
11197 			}
11198 		}
11199 	}
11200 }
11201 
11202 static void
11203 st_set_state(struct scsi_tape *un, struct buf *bp)
11204 {
11205 	struct scsi_pkt *sp = BP_PKT(bp);
11206 	struct uscsi_cmd *ucmd;
11207 
11208 	ST_FUNC(ST_DEVINFO, st_set_state);
11209 
11210 	ASSERT(mutex_owned(ST_MUTEX));
11211 	ASSERT(bp != un->un_recov_buf);
11212 
11213 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11214 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
11215 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
11216 
11217 	if (bp != un->un_sbufp) {
11218 #ifdef STDEBUG
11219 		if (DEBUGGING && sp->pkt_resid) {
11220 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11221 			    "pkt_resid %ld bcount %ld\n",
11222 			    sp->pkt_resid, bp->b_bcount);
11223 		}
11224 #endif
11225 		bp->b_resid = sp->pkt_resid;
11226 		if (geterror(bp) != EIO) {
11227 			st_calc_bnum(un, bp, sp);
11228 		}
11229 		if (bp->b_flags & B_READ) {
11230 			un->un_lastop = ST_OP_READ;
11231 			un->un_fmneeded = 0;
11232 		} else {
11233 			un->un_lastop = ST_OP_WRITE;
11234 			if (un->un_dp->options & ST_REEL) {
11235 				un->un_fmneeded = 2;
11236 			} else {
11237 				un->un_fmneeded = 1;
11238 			}
11239 		}
11240 		/*
11241 		 * all is honky dory at this point, so let's
11242 		 * readjust the throttle, to increase speed, if we
11243 		 * have not throttled down.
11244 		 */
11245 		if (un->un_throttle) {
11246 			un->un_throttle = un->un_max_throttle;
11247 		}
11248 	} else {
11249 		optype new_lastop;
11250 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
11251 
11252 		un->un_lastop = ST_OP_CTL;
11253 
11254 		switch (cmd) {
11255 		case SCMD_WRITE:
11256 		case SCMD_WRITE_G4:
11257 			bp->b_resid = sp->pkt_resid;
11258 			if (geterror(bp) == EIO) {
11259 				break;
11260 			}
11261 			new_lastop = ST_OP_WRITE;
11262 			st_calc_bnum(un, bp, sp);
11263 			if (un->un_dp->options & ST_REEL) {
11264 				un->un_fmneeded = 2;
11265 			} else {
11266 				un->un_fmneeded = 1;
11267 			}
11268 			break;
11269 		case SCMD_READ:
11270 		case SCMD_READ_G4:
11271 			bp->b_resid = sp->pkt_resid;
11272 			if (geterror(bp) == EIO) {
11273 				break;
11274 			}
11275 			new_lastop = ST_OP_READ;
11276 			st_calc_bnum(un, bp, sp);
11277 			un->un_fmneeded = 0;
11278 			break;
11279 		case SCMD_WRITE_FILE_MARK_G4:
11280 		case SCMD_WRITE_FILE_MARK:
11281 		{
11282 			int fmdone;
11283 
11284 			if (un->un_pos.eof != ST_EOM) {
11285 				un->un_pos.eof = ST_NO_EOF;
11286 			}
11287 			fmdone = (bp->b_bcount - bp->b_resid);
11288 			if (fmdone > 0) {
11289 				un->un_lastop = new_lastop = ST_OP_WEOF;
11290 				un->un_pos.lgclblkno += fmdone;
11291 				un->un_pos.fileno += fmdone;
11292 				un->un_pos.blkno = 0;
11293 			} else {
11294 				new_lastop = ST_OP_CTL;
11295 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11296 				    "Flushed buffer\n");
11297 			}
11298 			if (fmdone > un->un_fmneeded) {
11299 				un->un_fmneeded = 0;
11300 			} else {
11301 				un->un_fmneeded -= fmdone;
11302 			}
11303 			break;
11304 		}
11305 		case SCMD_REWIND:
11306 			un->un_pos.eof = ST_NO_EOF;
11307 			un->un_pos.fileno = 0;
11308 			un->un_pos.blkno = 0;
11309 			un->un_pos.lgclblkno = 0;
11310 			if (un->un_pos.pmode != legacy)
11311 				un->un_pos.pmode = legacy;
11312 			new_lastop = ST_OP_CTL;
11313 			un->un_restore_pos = 0;
11314 			break;
11315 
11316 		case SCMD_SPACE:
11317 		case SCMD_SPACE_G4:
11318 		{
11319 			int64_t count;
11320 			int64_t resid;
11321 			int64_t done;
11322 			cmd_attribute const *attrib;
11323 			recov_info *ri = (recov_info *)sp->pkt_private;
11324 
11325 			if (ri->privatelen == sizeof (recov_info)) {
11326 				attrib = ri->cmd_attrib;
11327 			} else {
11328 				attrib =
11329 				    st_lookup_cmd_attribute(sp->pkt_cdbp[0]);
11330 			}
11331 
11332 			resid = (int64_t)SPACE_CNT(bp->b_resid);
11333 			count = (int64_t)attrib->get_cnt(sp->pkt_cdbp);
11334 
11335 			if (count >= 0) {
11336 				done = (count - resid);
11337 			} else {
11338 				done = ((-count) - resid);
11339 			}
11340 			if (done > 0) {
11341 				un->un_lastop = new_lastop = ST_OP_CTL;
11342 			} else {
11343 				new_lastop = ST_OP_CTL;
11344 			}
11345 
11346 			ST_SPAC(ST_DEVINFO, st_label, SCSI_DEBUG,
11347 			    "space cmd: cdb[1] = %s\n"
11348 			    "space data:       = 0x%lx\n"
11349 			    "space count:      = %"PRId64"\n"
11350 			    "space resid:      = %"PRId64"\n"
11351 			    "spaces done:      = %"PRId64"\n"
11352 			    "fileno before     = %d\n"
11353 			    "blkno before      = %d\n",
11354 			    space_strs[sp->pkt_cdbp[1] & 7],
11355 			    bp->b_bcount,
11356 			    count, resid, done,
11357 			    un->un_pos.fileno, un->un_pos.blkno);
11358 
11359 			switch (sp->pkt_cdbp[1]) {
11360 			case SPACE_TYPE(SP_FLM):
11361 				/* Space file forward */
11362 				if (count >= 0) {
11363 					if (un->un_pos.eof <= ST_EOF) {
11364 						un->un_pos.eof = ST_NO_EOF;
11365 					}
11366 					un->un_pos.fileno += done;
11367 					un->un_pos.blkno = 0;
11368 					break;
11369 				}
11370 				/* Space file backward */
11371 				if (done > un->un_pos.fileno) {
11372 					un->un_pos.fileno = 0;
11373 					un->un_pos.blkno = 0;
11374 				} else {
11375 					un->un_pos.fileno -= done;
11376 					un->un_pos.blkno = LASTBLK;
11377 					un->un_running.pmode = invalid;
11378 				}
11379 				break;
11380 			case SPACE_TYPE(SP_BLK):
11381 				/* Space block forward */
11382 				if (count >= 0) {
11383 					un->un_pos.blkno += done;
11384 					break;
11385 				}
11386 				/* Space block backward */
11387 				if (un->un_pos.eof >= ST_EOF_PENDING) {
11388 				/*
11389 				 * we stepped back into
11390 				 * a previous file; we are not
11391 				 * making an effort to pretend that
11392 				 * we are still in the current file
11393 				 * ie. logical == physical position
11394 				 * and leave it to st_ioctl to correct
11395 				 */
11396 					if (done > un->un_pos.blkno) {
11397 						un->un_pos.blkno = 0;
11398 					} else {
11399 						un->un_pos.fileno--;
11400 						un->un_pos.blkno = LASTBLK;
11401 						un->un_running.pmode = invalid;
11402 					}
11403 				} else {
11404 					un->un_pos.blkno -= done;
11405 				}
11406 				break;
11407 			case SPACE_TYPE(SP_SQFLM):
11408 				un->un_pos.pmode = logical;
11409 				un->un_pos.blkno = 0;
11410 				un->un_lastop = new_lastop = ST_OP_CTL;
11411 				break;
11412 			case SPACE_TYPE(SP_EOD):
11413 				un->un_pos.pmode = logical;
11414 				un->un_pos.eof = ST_EOM;
11415 				un->un_status = KEY_BLANK_CHECK;
11416 				break;
11417 			default:
11418 				un->un_pos.pmode = invalid;
11419 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11420 				    "Unsupported space cmd: %s\n",
11421 				    space_strs[sp->pkt_cdbp[1] & 7]);
11422 
11423 				un->un_lastop = new_lastop = ST_OP_CTL;
11424 			}
11425 
11426 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11427 			    "after_space rs %"PRId64" fil %d blk %d\n",
11428 			    resid, un->un_pos.fileno, un->un_pos.blkno);
11429 
11430 			break;
11431 		}
11432 		case SCMD_LOAD:
11433 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
11434 				un->un_pos.fileno = 0;
11435 				if (un->un_pos.pmode != legacy)
11436 					un->un_pos.pmode = legacy;
11437 			} else {
11438 				un->un_state = ST_STATE_OFFLINE;
11439 				un->un_pos.pmode = invalid;
11440 			}
11441 			un->un_density_known = 0;
11442 			un->un_pos.eof = ST_NO_EOF;
11443 			un->un_pos.blkno = 0;
11444 			un->un_lastop = new_lastop = ST_OP_CTL;
11445 			break;
11446 		case SCMD_ERASE:
11447 			un->un_pos.eof = ST_NO_EOF;
11448 			un->un_pos.blkno = 0;
11449 			un->un_pos.fileno = 0;
11450 			un->un_pos.lgclblkno = 0;
11451 			if (un->un_pos.pmode != legacy)
11452 				un->un_pos.pmode = legacy;
11453 			new_lastop = ST_OP_CTL;
11454 			break;
11455 		case SCMD_RESERVE:
11456 			un->un_rsvd_status |= ST_RESERVE;
11457 			un->un_rsvd_status &=
11458 			    ~(ST_RELEASE | ST_LOST_RESERVE |
11459 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11460 			new_lastop = un->un_lastop;
11461 			break;
11462 		case SCMD_RELEASE:
11463 			un->un_rsvd_status |= ST_RELEASE;
11464 			un->un_rsvd_status &=
11465 			    ~(ST_RESERVE | ST_LOST_RESERVE |
11466 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11467 			new_lastop = ST_OP_CTL;
11468 			break;
11469 		case SCMD_PERSISTENT_RESERVE_IN:
11470 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11471 			    "PGR_IN command\n");
11472 			break;
11473 		case SCMD_PERSISTENT_RESERVE_OUT:
11474 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
11475 			case ST_SA_SCSI3_RESERVE:
11476 			case ST_SA_SCSI3_PREEMPT:
11477 			case ST_SA_SCSI3_PREEMPTANDABORT:
11478 				un->un_rsvd_status |=
11479 				    ST_APPLICATION_RESERVATIONS;
11480 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11481 				    "PGR Reserve and set: entering"
11482 				    " ST_APPLICATION_RESERVATIONS mode");
11483 				break;
11484 			case ST_SA_SCSI3_RELEASE:
11485 			case ST_SA_SCSI3_CLEAR:
11486 				un->un_rsvd_status &=
11487 				    ~ST_APPLICATION_RESERVATIONS;
11488 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11489 				    "PGR Release and reset: exiting"
11490 				    " ST_APPLICATION_RESERVATIONS mode");
11491 				break;
11492 			}
11493 			break;
11494 		case SCMD_TEST_UNIT_READY:
11495 		case SCMD_READ_BLKLIM:
11496 		case SCMD_REQUEST_SENSE:
11497 		case SCMD_INQUIRY:
11498 		case SCMD_RECOVER_BUF:
11499 		case SCMD_MODE_SELECT:
11500 		case SCMD_MODE_SENSE:
11501 		case SCMD_DOORLOCK:
11502 		case SCMD_READ_BUFFER:
11503 		case SCMD_REPORT_DENSITIES:
11504 		case SCMD_LOG_SELECT_G1:
11505 		case SCMD_LOG_SENSE_G1:
11506 		case SCMD_REPORT_LUNS:
11507 		case SCMD_READ_ATTRIBUTE:
11508 		case SCMD_WRITE_ATTRIBUTE:
11509 		case SCMD_SVC_ACTION_IN_G5:
11510 			new_lastop = ST_OP_CTL;
11511 			break;
11512 		case SCMD_READ_POSITION:
11513 			new_lastop = ST_OP_CTL;
11514 			/*
11515 			 * Only if the buf used was un_sbufp.
11516 			 * Among other things the prevents read positions used
11517 			 * as part of error recovery from messing up our
11518 			 * current position as they will use un_recov_buf.
11519 			 */
11520 			if (USCSI_CMD(bp)) {
11521 				(void) st_get_read_pos(un, bp);
11522 			}
11523 			break;
11524 		case SCMD_LOCATE:
11525 		case SCMD_LOCATE_G4:
11526 			/* Locate makes position mode no longer legacy */
11527 			un->un_lastop = new_lastop = ST_OP_CTL;
11528 			break;
11529 		default:
11530 			/*
11531 			 * Unknown command, If was USCSI and USCSI_SILENT
11532 			 * flag was not set, set position to unknown.
11533 			 */
11534 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
11535 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
11536 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11537 				    "unknown cmd 0x%X caused loss of state\n",
11538 				    cmd);
11539 			} else {
11540 				break;
11541 			}
11542 			/* FALLTHROUGH */
11543 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
11544 			un->un_pos.pmode = invalid;
11545 			un->un_lastop = new_lastop = ST_OP_CTL;
11546 			break;
11547 		}
11548 
11549 		/* new_lastop should have been changed */
11550 		ASSERT(new_lastop != ST_OP_NIL);
11551 
11552 		/* If un_lastop should copy new_lastop  */
11553 		if (((un->un_lastop == ST_OP_WRITE) ||
11554 		    (un->un_lastop == ST_OP_WEOF)) &&
11555 		    new_lastop != ST_OP_CTL) {
11556 			un->un_lastop = new_lastop;
11557 		}
11558 	}
11559 
11560 	/*
11561 	 * In the st driver we have a logical and physical file position.
11562 	 * Under BSD behavior, when you get a zero read, the logical position
11563 	 * is before the filemark but after the last record of the file.
11564 	 * The physical position is after the filemark. MTIOCGET should always
11565 	 * return the logical file position.
11566 	 *
11567 	 * The next read gives a silent skip to the next file.
11568 	 * Under SVR4, the logical file position remains before the filemark
11569 	 * until the file is closed or a space operation is performed.
11570 	 * Hence set err_resid and err_file before changing fileno if case
11571 	 * BSD Behaviour.
11572 	 */
11573 	un->un_err_resid = bp->b_resid;
11574 	COPY_POS(&un->un_err_pos, &un->un_pos);
11575 	un->un_retry_ct = 0;
11576 
11577 
11578 	/*
11579 	 * If we've seen a filemark via the last read operation
11580 	 * advance the file counter, but mark things such that
11581 	 * the next read operation gets a zero count. We have
11582 	 * to put this here to handle the case of sitting right
11583 	 * at the end of a tape file having seen the file mark,
11584 	 * but the tape is closed and then re-opened without
11585 	 * any further i/o. That is, the position information
11586 	 * must be updated before a close.
11587 	 */
11588 
11589 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
11590 		/*
11591 		 * If we're a 1/2" tape, and we get a filemark
11592 		 * right on block 0, *AND* we were not in the
11593 		 * first file on the tape, and we've hit logical EOM.
11594 		 * We'll mark the state so that later we do the
11595 		 * right thing (in st_close(), st_strategy() or
11596 		 * st_ioctl()).
11597 		 *
11598 		 */
11599 		if ((un->un_dp->options & ST_REEL) &&
11600 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
11601 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
11602 			un->un_pos.eof = ST_EOT_PENDING;
11603 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11604 			    "eot pending\n");
11605 			un->un_pos.fileno++;
11606 			un->un_pos.blkno = 0;
11607 		} else if (BSD_BEHAVIOR) {
11608 			/*
11609 			 * If the read of the filemark was a side effect
11610 			 * of reading some blocks (i.e., data was actually
11611 			 * read), then the EOF mark is pending and the
11612 			 * bump into the next file awaits the next read
11613 			 * operation (which will return a zero count), or
11614 			 * a close or a space operation, else the bump
11615 			 * into the next file occurs now.
11616 			 */
11617 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11618 			    "resid=%lx, bcount=%lx\n",
11619 			    bp->b_resid, bp->b_bcount);
11620 
11621 			if (bp->b_resid != bp->b_bcount) {
11622 				un->un_pos.eof = ST_EOF;
11623 			} else {
11624 				un->un_silent_skip = 1;
11625 				un->un_pos.eof = ST_NO_EOF;
11626 				un->un_pos.fileno++;
11627 				un->un_pos.lgclblkno++;
11628 				un->un_save_blkno = un->un_pos.blkno;
11629 				un->un_pos.blkno = 0;
11630 			}
11631 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11632 			    "eof of file %d, eof=%d\n",
11633 			    un->un_pos.fileno, un->un_pos.eof);
11634 		} else if (SVR4_BEHAVIOR) {
11635 			/*
11636 			 * If the read of the filemark was a side effect
11637 			 * of reading some blocks (i.e., data was actually
11638 			 * read), then the next read should return 0
11639 			 */
11640 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11641 			    "resid=%lx, bcount=%lx\n",
11642 			    bp->b_resid, bp->b_bcount);
11643 			if (bp->b_resid == bp->b_bcount) {
11644 				un->un_pos.eof = ST_EOF;
11645 			}
11646 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11647 			    "eof of file=%d, eof=%d\n",
11648 			    un->un_pos.fileno, un->un_pos.eof);
11649 		}
11650 	}
11651 }
11652 
11653 /*
11654  * set the correct un_errno, to take corner cases into consideration
11655  */
11656 static void
11657 st_set_pe_errno(struct scsi_tape *un)
11658 {
11659 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
11660 
11661 	ASSERT(mutex_owned(ST_MUTEX));
11662 
11663 	/* if errno is already set, don't reset it */
11664 	if (un->un_errno)
11665 		return;
11666 
11667 	/* here un_errno == 0 */
11668 	/*
11669 	 * if the last transfer before flushing all the
11670 	 * waiting I/O's, was 0 (resid = count), then we
11671 	 * want to give the user an error on all the rest,
11672 	 * so here.  If there was a transfer, we set the
11673 	 * resid and counts to 0, and let it drop through,
11674 	 * giving a zero return.  the next I/O will then
11675 	 * give an error.
11676 	 */
11677 	if (un->un_last_resid == un->un_last_count) {
11678 		switch (un->un_pos.eof) {
11679 		case ST_EOM:
11680 			un->un_errno = ENOMEM;
11681 			break;
11682 		case ST_EOT:
11683 		case ST_EOF:
11684 			un->un_errno = EIO;
11685 			break;
11686 		}
11687 	} else {
11688 		/*
11689 		 * we know they did not have a zero, so make
11690 		 * sure they get one
11691 		 */
11692 		un->un_last_resid = un->un_last_count = 0;
11693 	}
11694 }
11695 
11696 
11697 /*
11698  * send in a marker pkt to terminate flushing of commands by BBA (via
11699  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
11700  */
11701 static void
11702 st_hba_unflush(struct scsi_tape *un)
11703 {
11704 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
11705 
11706 	ASSERT(mutex_owned(ST_MUTEX));
11707 
11708 	if (!un->un_flush_on_errors)
11709 		return;
11710 
11711 #ifdef FLUSH_ON_ERRORS
11712 
11713 	if (!un->un_mkr_pkt) {
11714 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
11715 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
11716 
11717 		/* we slept, so it must be there */
11718 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
11719 	}
11720 
11721 	st_transport(un, un->un_mkr_pkt);
11722 #endif
11723 }
11724 
11725 static char *
11726 st_print_scsi_cmd(char cmd)
11727 {
11728 	char tmp[64];
11729 	char *cpnt;
11730 
11731 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
11732 	/* tmp goes out of scope on return and caller sees garbage */
11733 	if (cpnt == tmp) {
11734 		cpnt = "Unknown Command";
11735 	}
11736 	return (cpnt);
11737 }
11738 
11739 static void
11740 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
11741     char *title, char *cdb)
11742 {
11743 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
11744 	char buf[256];
11745 	struct scsi_tape *un;
11746 	int instance = ddi_get_instance(dip);
11747 
11748 	un = ddi_get_soft_state(st_state, instance);
11749 
11750 	ST_FUNC(dip, st_print_cdb);
11751 
11752 #ifdef STDEBUG
11753 	if ((st_debug & 0x180) == 0x100) {
11754 		scsi_log(dip, label, level, "node %s cmd %s\n",
11755 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
11756 		return;
11757 	}
11758 #endif
11759 	(void) sprintf(buf, "%s for cmd(%s)", title, st_print_scsi_cmd(*cdb));
11760 	st_clean_print(dip, label, level, buf, cdb, len);
11761 }
11762 
11763 static void
11764 st_clean_print(dev_info_t *dev, char *label, uint_t level,
11765     char *title, char *data, int len)
11766 {
11767 	int	i;
11768 	int 	c;
11769 	char	*format;
11770 	char	buf[256];
11771 	uchar_t	byte;
11772 
11773 	ST_FUNC(dev, st_clean_print);
11774 
11775 
11776 	(void) sprintf(buf, "%s:\n", title);
11777 	scsi_log(dev, label, level, "%s", buf);
11778 	level = CE_CONT;
11779 	for (i = 0; i < len; ) {
11780 		buf[0] = 0;
11781 		for (c = 0; c < 8 && i < len; c++, i++) {
11782 			byte = (uchar_t)data[i];
11783 			if (byte < 0x10)
11784 				format = "0x0%x ";
11785 			else
11786 				format = "0x%x ";
11787 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
11788 		}
11789 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
11790 
11791 		scsi_log(dev, label, level, "%s\n", buf);
11792 	}
11793 }
11794 
11795 /*
11796  * Conditionally enabled debugging
11797  */
11798 #ifdef	STDEBUG
11799 static void
11800 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
11801 {
11802 	char tmpbuf[64];
11803 
11804 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
11805 
11806 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11807 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
11808 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
11809 	    count, count,
11810 	    wait == ASYNC_CMD ? "a" : "");
11811 }
11812 
11813 /*
11814  * Returns pointer to name of minor node name of device 'dev'.
11815  */
11816 static char *
11817 st_dev_name(dev_t dev)
11818 {
11819 	struct scsi_tape *un;
11820 	const char density[] = { 'l', 'm', 'h', 'c' };
11821 	static char name[32];
11822 	minor_t minor;
11823 	int instance;
11824 	int nprt = 0;
11825 
11826 	minor = getminor(dev);
11827 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
11828 	un = ddi_get_soft_state(st_state, instance);
11829 	if (un) {
11830 		ST_FUNC(ST_DEVINFO, st_dev_name);
11831 	}
11832 
11833 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
11834 
11835 	if (minor & MT_BSD) {
11836 		name[++nprt] = 'b';
11837 	}
11838 
11839 	if (minor & MT_NOREWIND) {
11840 		name[++nprt] = 'n';
11841 	}
11842 
11843 	/* NULL terminator */
11844 	name[++nprt] = 0;
11845 
11846 	return (name);
11847 }
11848 #endif	/* STDEBUG */
11849 
11850 /*
11851  * Soft error reporting, so far unique to each drive
11852  *
11853  * Currently supported: exabyte and DAT soft error reporting
11854  */
11855 static int
11856 st_report_exabyte_soft_errors(dev_t dev, int flag)
11857 {
11858 	uchar_t *sensep;
11859 	int amt;
11860 	int rval = 0;
11861 	char cdb[CDB_GROUP0], *c = cdb;
11862 	struct uscsi_cmd *com;
11863 
11864 	GET_SOFT_STATE(dev);
11865 
11866 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
11867 
11868 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11869 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
11870 	    dev, flag);
11871 
11872 	ASSERT(mutex_owned(ST_MUTEX));
11873 
11874 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
11875 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
11876 
11877 	*c++ = SCMD_REQUEST_SENSE;
11878 	*c++ = 0;
11879 	*c++ = 0;
11880 	*c++ = 0;
11881 	*c++ = TAPE_SENSE_LENGTH;
11882 	/*
11883 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
11884 	 */
11885 	*c   = (char)0x80;
11886 
11887 	com->uscsi_cdb = cdb;
11888 	com->uscsi_cdblen = CDB_GROUP0;
11889 	com->uscsi_bufaddr = (caddr_t)sensep;
11890 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
11891 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11892 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11893 
11894 	rval = st_uscsi_cmd(un, com, FKIOCTL);
11895 	if (rval || com->uscsi_status) {
11896 		goto done;
11897 	}
11898 
11899 	/*
11900 	 * was there enough data?
11901 	 */
11902 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
11903 
11904 	if ((amt >= 19) && un->un_kbytes_xferred) {
11905 		uint_t count, error_rate;
11906 		uint_t rate;
11907 
11908 		if (sensep[21] & CLN) {
11909 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11910 			    "Periodic head cleaning required");
11911 		}
11912 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
11913 			goto done;
11914 		}
11915 		/*
11916 		 * check if soft error reporting needs to be done.
11917 		 */
11918 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
11919 		count &= 0xffffff;
11920 		error_rate = (count * 100)/un->un_kbytes_xferred;
11921 
11922 #ifdef	STDEBUG
11923 		if (st_soft_error_report_debug) {
11924 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11925 			    "Exabyte Soft Error Report:\n");
11926 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11927 			    "read/write error counter: %d\n", count);
11928 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11929 			    "number of bytes transferred: %dK\n",
11930 			    un->un_kbytes_xferred);
11931 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11932 			    "error_rate: %d%%\n", error_rate);
11933 
11934 			if (amt >= 22) {
11935 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11936 				    "unit sense: 0x%b 0x%b 0x%b\n",
11937 				    sensep[19], SENSE_19_BITS,
11938 				    sensep[20], SENSE_20_BITS,
11939 				    sensep[21], SENSE_21_BITS);
11940 			}
11941 			if (amt >= 27) {
11942 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11943 				    "tracking retry counter: %d\n",
11944 				    sensep[26]);
11945 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11946 				    "read/write retry counter: %d\n",
11947 				    sensep[27]);
11948 			}
11949 		}
11950 #endif
11951 
11952 		if (flag & FWRITE) {
11953 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
11954 		} else {
11955 			rate = EXABYTE_READ_ERROR_THRESHOLD;
11956 		}
11957 		if (error_rate >= rate) {
11958 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11959 			    "Soft error rate (%d%%) during %s was too high",
11960 			    error_rate,
11961 			    ((flag & FWRITE) ? wrg_str : rdg_str));
11962 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11963 			    "Please, replace tape cartridge\n");
11964 		}
11965 	}
11966 
11967 done:
11968 	kmem_free(com, sizeof (*com));
11969 	kmem_free(sensep, TAPE_SENSE_LENGTH);
11970 
11971 	if (rval != 0) {
11972 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
11973 		    "exabyte soft error reporting failed\n");
11974 	}
11975 	return (rval);
11976 }
11977 
11978 /*
11979  * this is very specific to Archive 4mm dat
11980  */
11981 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
11982 
11983 static int
11984 st_report_dat_soft_errors(dev_t dev, int flag)
11985 {
11986 	uchar_t *sensep;
11987 	int amt, i;
11988 	int rval = 0;
11989 	char cdb[CDB_GROUP1], *c = cdb;
11990 	struct uscsi_cmd *com;
11991 
11992 	GET_SOFT_STATE(dev);
11993 
11994 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
11995 
11996 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11997 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
11998 
11999 	ASSERT(mutex_owned(ST_MUTEX));
12000 
12001 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12002 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12003 
12004 	*c++ = SCMD_LOG_SENSE_G1;
12005 	*c++ = 0;
12006 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
12007 	*c++ = 0;
12008 	*c++ = 0;
12009 	*c++ = 0;
12010 	*c++ = 2;
12011 	*c++ = 0;
12012 	*c++ = (char)LOG_SENSE_LENGTH;
12013 	*c   = 0;
12014 	com->uscsi_cdb    = cdb;
12015 	com->uscsi_cdblen  = CDB_GROUP1;
12016 	com->uscsi_bufaddr = (caddr_t)sensep;
12017 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
12018 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12019 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12020 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12021 	if (rval) {
12022 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12023 		    "DAT soft error reporting failed\n");
12024 	}
12025 	if (rval || com->uscsi_status) {
12026 		goto done;
12027 	}
12028 
12029 	/*
12030 	 * was there enough data?
12031 	 */
12032 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
12033 
12034 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
12035 		int total, retries, param_code;
12036 
12037 		total = -1;
12038 		retries = -1;
12039 		amt = sensep[3] + 4;
12040 
12041 
12042 #ifdef STDEBUG
12043 		if (st_soft_error_report_debug) {
12044 			(void) printf("logsense:");
12045 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
12046 				if (i % 16 == 0) {
12047 					(void) printf("\t\n");
12048 				}
12049 				(void) printf(" %x", sensep[i]);
12050 			}
12051 			(void) printf("\n");
12052 		}
12053 #endif
12054 
12055 		/*
12056 		 * parse the param_codes
12057 		 */
12058 		if (sensep[0] == 2 || sensep[0] == 3) {
12059 			for (i = 4; i < amt; i++) {
12060 				param_code = (sensep[i++] << 8);
12061 				param_code += sensep[i++];
12062 				i++; /* skip control byte */
12063 				if (param_code == 5) {
12064 					if (sensep[i++] == 4) {
12065 						total = (sensep[i++] << 24);
12066 						total += (sensep[i++] << 16);
12067 						total += (sensep[i++] << 8);
12068 						total += sensep[i];
12069 					}
12070 				} else if (param_code == 0x8007) {
12071 					if (sensep[i++] == 2) {
12072 						retries = sensep[i++] << 8;
12073 						retries += sensep[i];
12074 					}
12075 				} else {
12076 					i += sensep[i];
12077 				}
12078 			}
12079 		}
12080 
12081 		/*
12082 		 * if the log sense returned valid numbers then determine
12083 		 * the read and write error thresholds based on the amount of
12084 		 * data transferred
12085 		 */
12086 
12087 		if (total > 0 && retries > 0) {
12088 			short normal_retries = 0;
12089 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12090 			    "total xferred (%s) =%x, retries=%x\n",
12091 			    ((flag & FWRITE) ? wrg_str : rdg_str),
12092 			    total, retries);
12093 
12094 			if (flag & FWRITE) {
12095 				if (total <=
12096 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
12097 					normal_retries =
12098 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
12099 				} else {
12100 					normal_retries =
12101 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
12102 				}
12103 			} else {
12104 				if (total <=
12105 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
12106 					normal_retries =
12107 					    DAT_SMALL_READ_ERROR_THRESHOLD;
12108 				} else {
12109 					normal_retries =
12110 					    DAT_LARGE_READ_ERROR_THRESHOLD;
12111 				}
12112 			}
12113 
12114 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12115 			"normal retries=%d\n", normal_retries);
12116 
12117 			if (retries >= normal_retries) {
12118 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12119 				    "Soft error rate (retries = %d) during "
12120 				    "%s was too high",  retries,
12121 				    ((flag & FWRITE) ? wrg_str : rdg_str));
12122 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12123 				    "Periodic head cleaning required "
12124 				    "and/or replace tape cartridge\n");
12125 			}
12126 
12127 		} else if (total == -1 || retries == -1) {
12128 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12129 			    "log sense parameter code does not make sense\n");
12130 		}
12131 	}
12132 
12133 	/*
12134 	 * reset all values
12135 	 */
12136 	c = cdb;
12137 	*c++ = SCMD_LOG_SELECT_G1;
12138 	*c++ = 2;	/* this resets all values */
12139 	*c++ = (char)0xc0;
12140 	*c++ = 0;
12141 	*c++ = 0;
12142 	*c++ = 0;
12143 	*c++ = 0;
12144 	*c++ = 0;
12145 	*c++ = 0;
12146 	*c   = 0;
12147 	com->uscsi_bufaddr = NULL;
12148 	com->uscsi_buflen  = 0;
12149 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
12150 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12151 	if (rval) {
12152 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12153 		    "DAT soft error reset failed\n");
12154 	}
12155 done:
12156 	kmem_free(com, sizeof (*com));
12157 	kmem_free(sensep, LOG_SENSE_LENGTH);
12158 	return (rval);
12159 }
12160 
12161 static int
12162 st_report_soft_errors(dev_t dev, int flag)
12163 {
12164 	GET_SOFT_STATE(dev);
12165 
12166 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
12167 
12168 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12169 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12170 
12171 	ASSERT(mutex_owned(ST_MUTEX));
12172 
12173 	switch (un->un_dp->type) {
12174 	case ST_TYPE_EXB8500:
12175 	case ST_TYPE_EXABYTE:
12176 		return (st_report_exabyte_soft_errors(dev, flag));
12177 		/*NOTREACHED*/
12178 	case ST_TYPE_PYTHON:
12179 		return (st_report_dat_soft_errors(dev, flag));
12180 		/*NOTREACHED*/
12181 	default:
12182 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
12183 		return (-1);
12184 	}
12185 }
12186 
12187 /*
12188  * persistent error routines
12189  */
12190 
12191 /*
12192  * enable persistent errors, and set the throttle appropriately, checking
12193  * for flush-on-errors capability
12194  */
12195 static void
12196 st_turn_pe_on(struct scsi_tape *un)
12197 {
12198 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
12199 
12200 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
12201 	ASSERT(mutex_owned(ST_MUTEX));
12202 
12203 	un->un_persistence = 1;
12204 
12205 	/*
12206 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
12207 	 * enabled.  This will simplify the error handling for request senses
12208 	 */
12209 
12210 	if (un->un_arq_enabled && un->un_untagged_qing) {
12211 		uchar_t f_o_e;
12212 
12213 		mutex_exit(ST_MUTEX);
12214 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
12215 		    1 : 0;
12216 		mutex_enter(ST_MUTEX);
12217 
12218 		un->un_flush_on_errors = f_o_e;
12219 	} else {
12220 		un->un_flush_on_errors = 0;
12221 	}
12222 
12223 	if (un->un_flush_on_errors)
12224 		un->un_max_throttle = (uchar_t)st_max_throttle;
12225 	else
12226 		un->un_max_throttle = 1;
12227 
12228 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
12229 		un->un_max_throttle = 1;
12230 
12231 	/* this will send a marker pkt */
12232 	st_clear_pe(un);
12233 }
12234 
12235 /*
12236  * This turns persistent errors permanently off
12237  */
12238 static void
12239 st_turn_pe_off(struct scsi_tape *un)
12240 {
12241 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
12242 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
12243 	ASSERT(mutex_owned(ST_MUTEX));
12244 
12245 	/* turn it off for good */
12246 	un->un_persistence = 0;
12247 
12248 	/* this will send a marker pkt */
12249 	st_clear_pe(un);
12250 
12251 	/* turn off flush on error capability, if enabled */
12252 	if (un->un_flush_on_errors) {
12253 		mutex_exit(ST_MUTEX);
12254 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
12255 		mutex_enter(ST_MUTEX);
12256 	}
12257 
12258 
12259 	un->un_flush_on_errors = 0;
12260 }
12261 
12262 /*
12263  * This clear persistent errors, allowing more commands through, and also
12264  * sending a marker packet.
12265  */
12266 static void
12267 st_clear_pe(struct scsi_tape *un)
12268 {
12269 	ST_FUNC(ST_DEVINFO, st_clear_pe);
12270 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
12271 	ASSERT(mutex_owned(ST_MUTEX));
12272 
12273 	un->un_persist_errors = 0;
12274 	un->un_throttle = un->un_last_throttle = 1;
12275 	un->un_errno = 0;
12276 	st_hba_unflush(un);
12277 }
12278 
12279 /*
12280  * This will flag persistent errors, shutting everything down, if the
12281  * application had enabled persistent errors via MTIOCPERSISTENT
12282  */
12283 static void
12284 st_set_pe_flag(struct scsi_tape *un)
12285 {
12286 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
12287 	ASSERT(mutex_owned(ST_MUTEX));
12288 
12289 	if (un->un_persistence) {
12290 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
12291 		un->un_persist_errors = 1;
12292 		un->un_throttle = un->un_last_throttle = 0;
12293 		cv_broadcast(&un->un_sbuf_cv);
12294 	}
12295 }
12296 
12297 static int
12298 st_do_reserve(struct scsi_tape *un)
12299 {
12300 	int rval;
12301 
12302 	ST_FUNC(ST_DEVINFO, st_do_reserve);
12303 
12304 	/*
12305 	 * Issue a Throw-Away reserve command to clear the
12306 	 * check condition.
12307 	 * If the current behaviour of reserve/release is to
12308 	 * hold reservation across opens , and if a Bus reset
12309 	 * has been issued between opens then this command
12310 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
12311 	 * In this case return an EACCES so that user knows that
12312 	 * reservation has been lost in between opens.
12313 	 * If this error is not returned and we continue with
12314 	 * successful open , then user may think position of the
12315 	 * tape is still the same but inreality we would rewind the
12316 	 * tape and continue from BOT.
12317 	 */
12318 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12319 	if (rval) {
12320 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
12321 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
12322 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
12323 			un->un_errno = EACCES;
12324 			return (EACCES);
12325 		}
12326 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12327 	}
12328 	if (rval == 0) {
12329 		un->un_rsvd_status |= ST_INIT_RESERVE;
12330 	}
12331 
12332 	return (rval);
12333 }
12334 
12335 static int
12336 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb)
12337 {
12338 	int rval;
12339 	cmd_attribute const *attrib;
12340 
12341 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
12342 
12343 	/*
12344 	 * If already reserved no need to do it again.
12345 	 * Also if Reserve and Release are disabled Just return.
12346 	 */
12347 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12348 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12349 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12350 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12351 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
12352 		    st_print_scsi_cmd((uchar_t)cdb[0]));
12353 		return (0);
12354 	}
12355 
12356 	/* See if command is on the list */
12357 	attrib = st_lookup_cmd_attribute(cdb[0]);
12358 
12359 	if (attrib == NULL) {
12360 		rval = 1; /* Not found, when in doubt reserve */
12361 	} else if ((attrib->requires_reserve) != 0) {
12362 		rval = 1;
12363 	} else if ((attrib->reserve_byte) != 0) {
12364 		/*
12365 		 * cmd is on list.
12366 		 * if byte is zero always allowed.
12367 		 */
12368 		rval = 1;
12369 	} else if (((cdb[attrib->reserve_byte]) &
12370 	    (attrib->reserve_mask)) != 0) {
12371 		rval = 1;
12372 	} else {
12373 		rval = 0;
12374 	}
12375 
12376 	if (rval) {
12377 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12378 		    "Command %s requires reservation",
12379 		    st_print_scsi_cmd(cdb[0]));
12380 
12381 		rval = st_do_reserve(un);
12382 	}
12383 
12384 	return (rval);
12385 }
12386 
12387 static int
12388 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
12389 {
12390 	int rval;
12391 	cmd_attribute const *attrib;
12392 
12393 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
12394 
12395 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12396 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12397 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12398 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12399 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
12400 		    st_print_scsi_cmd(cmd));
12401 		return (0);
12402 	}
12403 
12404 	/* search for this command on the list */
12405 	attrib = st_lookup_cmd_attribute(cmd);
12406 
12407 	if (attrib == NULL) {
12408 		rval = 1; /* Not found, when in doubt reserve */
12409 	} else if ((attrib->requires_reserve) != 0) {
12410 		rval = 1;
12411 	} else if ((attrib->reserve_byte) != 0) {
12412 		/*
12413 		 * cmd is on list.
12414 		 * if byte is zero always allowed.
12415 		 */
12416 		rval = 1;
12417 	} else if (((attrib->reserve_mask) & cnt) != 0) {
12418 		rval = 1;
12419 	} else {
12420 		rval = 0;
12421 	}
12422 
12423 	if (rval) {
12424 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12425 		    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
12426 
12427 		rval = st_do_reserve(un);
12428 	}
12429 
12430 	return (rval);
12431 }
12432 
12433 static int
12434 st_reserve_release(struct scsi_tape *un, int cmd, ubufunc_t ubf)
12435 {
12436 	struct uscsi_cmd	uscsi_cmd;
12437 	int			rval;
12438 	char			cdb[CDB_GROUP0];
12439 	struct scsi_arq_status	stat;
12440 
12441 
12442 
12443 	ST_FUNC(ST_DEVINFO, st_reserve_release);
12444 
12445 	ASSERT(mutex_owned(ST_MUTEX));
12446 
12447 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12448 	    "st_reserve_release: %s \n",
12449 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
12450 
12451 	bzero(&cdb, CDB_GROUP0);
12452 	if (cmd == ST_RELEASE) {
12453 		cdb[0] = SCMD_RELEASE;
12454 	} else {
12455 		cdb[0] = SCMD_RESERVE;
12456 	}
12457 	bzero(&uscsi_cmd, sizeof (struct uscsi_cmd));
12458 	uscsi_cmd.uscsi_flags = USCSI_WRITE | USCSI_RQENABLE;
12459 	uscsi_cmd.uscsi_cdb = cdb;
12460 	uscsi_cmd.uscsi_cdblen = CDB_GROUP0;
12461 	uscsi_cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
12462 	uscsi_cmd.uscsi_rqbuf = (caddr_t)&stat;
12463 	uscsi_cmd.uscsi_rqlen = sizeof (stat);
12464 
12465 	rval = ubf(un, &uscsi_cmd, FKIOCTL);
12466 
12467 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12468 	    "st_reserve_release: rval(1)=%d\n", rval);
12469 
12470 	if (rval) {
12471 		if (uscsi_cmd.uscsi_status == STATUS_RESERVATION_CONFLICT) {
12472 			rval = EACCES;
12473 		}
12474 		/*
12475 		 * dynamically turn off reserve/release support
12476 		 * in case of drives which do not support
12477 		 * reserve/release command(ATAPI drives).
12478 		 */
12479 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
12480 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
12481 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
12482 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12483 				    "Tape unit does not support "
12484 				    "reserve/release \n");
12485 			}
12486 			rval = 0;
12487 		}
12488 	}
12489 	return (rval);
12490 }
12491 
12492 static int
12493 st_take_ownership(struct scsi_tape *un)
12494 {
12495 	int rval;
12496 
12497 	ST_FUNC(ST_DEVINFO, st_take_ownership);
12498 
12499 	ASSERT(mutex_owned(ST_MUTEX));
12500 
12501 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12502 	    "st_take_ownership: Entering ...\n");
12503 
12504 
12505 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12506 	/*
12507 	 * XXX -> Should reset be done only if we get EACCES.
12508 	 * .
12509 	 */
12510 	if (rval) {
12511 		if (st_reset(un, RESET_LUN) == 0) {
12512 			return (EIO);
12513 		}
12514 		un->un_rsvd_status &=
12515 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
12516 
12517 		mutex_exit(ST_MUTEX);
12518 		delay(drv_usectohz(ST_RESERVATION_DELAY));
12519 		mutex_enter(ST_MUTEX);
12520 		/*
12521 		 * remove the check condition.
12522 		 */
12523 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12524 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12525 		if (rval != 0) {
12526 			if ((st_reserve_release(un, ST_RESERVE, st_uscsi_cmd))
12527 			    != 0) {
12528 				rval = (un->un_rsvd_status &
12529 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
12530 				return (rval);
12531 			}
12532 		}
12533 		/*
12534 		 * Set tape state to ST_STATE_OFFLINE , in case if
12535 		 * the user wants to continue and start using
12536 		 * the tape.
12537 		 */
12538 		un->un_state = ST_STATE_OFFLINE;
12539 		un->un_rsvd_status |= ST_INIT_RESERVE;
12540 	}
12541 	return (rval);
12542 }
12543 
12544 static int
12545 st_create_errstats(struct scsi_tape *un, int instance)
12546 {
12547 	char	kstatname[KSTAT_STRLEN];
12548 
12549 	ST_FUNC(ST_DEVINFO, st_create_errstats);
12550 
12551 	/*
12552 	 * Create device error kstats
12553 	 */
12554 
12555 	if (un->un_errstats == (kstat_t *)0) {
12556 		(void) sprintf(kstatname, "st%d,err", instance);
12557 		un->un_errstats = kstat_create("sterr", instance, kstatname,
12558 		    "device_error", KSTAT_TYPE_NAMED,
12559 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
12560 		    KSTAT_FLAG_PERSISTENT);
12561 
12562 		if (un->un_errstats) {
12563 			struct st_errstats	*stp;
12564 
12565 			stp = (struct st_errstats *)un->un_errstats->ks_data;
12566 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
12567 			    KSTAT_DATA_ULONG);
12568 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
12569 			    KSTAT_DATA_ULONG);
12570 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
12571 			    KSTAT_DATA_ULONG);
12572 			kstat_named_init(&stp->st_vid, "Vendor",
12573 			    KSTAT_DATA_CHAR);
12574 			kstat_named_init(&stp->st_pid, "Product",
12575 			    KSTAT_DATA_CHAR);
12576 			kstat_named_init(&stp->st_revision, "Revision",
12577 			    KSTAT_DATA_CHAR);
12578 			kstat_named_init(&stp->st_serial, "Serial No",
12579 			    KSTAT_DATA_CHAR);
12580 			un->un_errstats->ks_private = un;
12581 			un->un_errstats->ks_update = nulldev;
12582 			kstat_install(un->un_errstats);
12583 			/*
12584 			 * Fill in the static data
12585 			 */
12586 			(void) strncpy(&stp->st_vid.value.c[0],
12587 			    ST_INQUIRY->inq_vid, 8);
12588 			/*
12589 			 * XXX:  Emulex MT-02 (and emulators) predates
12590 			 *	 SCSI-1 and has no vid & pid inquiry data.
12591 			 */
12592 			if (ST_INQUIRY->inq_len != 0) {
12593 				(void) strncpy(&stp->st_pid.value.c[0],
12594 				    ST_INQUIRY->inq_pid, 16);
12595 				(void) strncpy(&stp->st_revision.value.c[0],
12596 				    ST_INQUIRY->inq_revision, 4);
12597 				(void) strncpy(&stp->st_serial.value.c[0],
12598 				    ST_INQUIRY->inq_serial, 12);
12599 			}
12600 		}
12601 	}
12602 	return (0);
12603 }
12604 
12605 static int
12606 st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos)
12607 {
12608 	int rval;
12609 	bufunc_t bf = (ubf == st_uscsi_rcmd) ? st_rcmd : st_cmd;
12610 
12611 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
12612 
12613 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
12614 	ASSERT(mutex_owned(ST_MUTEX));
12615 
12616 	/* Can't restore an invalid position */
12617 	if (pos->pmode == invalid) {
12618 		return (4);
12619 	}
12620 
12621 	/*
12622 	 * Assumtions:
12623 	 *	If a position was read and is in logical position mode.
12624 	 *	If a drive supports read position it supports locate.
12625 	 *	If the read position type is not NO_POS. even though
12626 	 *	   a read position make not have been attemped yet.
12627 	 *
12628 	 *	The drive can locate to the position.
12629 	 */
12630 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
12631 		/*
12632 		 * If position mode is logical or legacy mode try
12633 		 * to locate there as it is faster.
12634 		 * If it fails try the old way.
12635 		 */
12636 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12637 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
12638 		    pos->lgclblkno);
12639 
12640 		if (st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
12641 		    pos->lgclblkno, pos->partition) == 0) {
12642 			/* Assume we are there copy rest of position back */
12643 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
12644 				COPY_POS(&un->un_pos, pos);
12645 			}
12646 			return (0);
12647 		}
12648 
12649 		/*
12650 		 * If logical block locate failed to restore a logical
12651 		 * position, can't recover.
12652 		 */
12653 		if (pos->pmode == logical) {
12654 			return (-1);
12655 		}
12656 	}
12657 
12658 
12659 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12660 	    "Restoring tape position at fileno=%x, blkno=%x....",
12661 	    pos->fileno, pos->blkno);
12662 
12663 	/*
12664 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
12665 	 * so as not to rewind tape on RESETS: Gee, Has life ever
12666 	 * been simple in tape land ?
12667 	 */
12668 	rval = bf(un, SCMD_REWIND, 0, SYNC_CMD);
12669 	if (rval) {
12670 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12671 		    "Failed to restore the last file and block position: In"
12672 		    " this state, Tape will be loaded at BOT during next open");
12673 		un->un_pos.pmode = invalid;
12674 		return (rval);
12675 	}
12676 
12677 	/* If the position was as the result of back space file */
12678 	if (pos->blkno > (INF / 2)) {
12679 		/* Go one extra file forward */
12680 		pos->fileno++;
12681 		/* Figure how many blocks to back into the previous file */
12682 		pos->blkno = -(INF - pos->blkno);
12683 	}
12684 
12685 	/* Go to requested fileno */
12686 	if (pos->fileno) {
12687 		rval = st_cmd(un, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
12688 		if (rval) {
12689 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12690 			    "Failed to restore the last file position: In this "
12691 			    " state, Tape will be loaded at BOT during next"
12692 			    " open %d", __LINE__);
12693 			un->un_pos.pmode = invalid;
12694 			pos->pmode = invalid;
12695 			return (rval);
12696 		}
12697 	}
12698 
12699 	/*
12700 	 * If backing into a file we already did an extra file forward.
12701 	 * Now we have to back over the filemark to get to the end of
12702 	 * the previous file. The blkno has been ajusted to a negative
12703 	 * value so we will get to the expected location.
12704 	 */
12705 	if (pos->blkno) {
12706 		rval = bf(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
12707 		if (rval) {
12708 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12709 			    "Failed to restore the last file position: In this "
12710 			    " state, Tape will be loaded at BOT during next"
12711 			    " open %d", __LINE__);
12712 			un->un_pos.pmode = invalid;
12713 			pos->pmode = invalid;
12714 			return (rval);
12715 		}
12716 	}
12717 
12718 	/*
12719 	 * The position mode, block and fileno should be correct,
12720 	 * This updates eof and logical position information.
12721 	 */
12722 	un->un_pos.eof = pos->eof;
12723 	un->un_pos.lgclblkno = pos->lgclblkno;
12724 
12725 	return (0);
12726 }
12727 
12728 /*
12729  * check sense key, ASC, ASCQ in order to determine if the tape needs
12730  * to be ejected
12731  */
12732 
12733 static int
12734 st_check_asc_ascq(struct scsi_tape *un)
12735 {
12736 	struct scsi_extended_sense *sensep = ST_RQSENSE;
12737 	struct tape_failure_code   *code;
12738 
12739 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
12740 
12741 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
12742 		if ((code->key  == sensep->es_key) &&
12743 		    (code->add_code  == sensep->es_add_code) &&
12744 		    (code->qual_code == sensep->es_qual_code))
12745 			return (1);
12746 	}
12747 	return (0);
12748 }
12749 
12750 /*
12751  * st_logpage_supported() sends a Log Sense command with
12752  * page code = 0 = Supported Log Pages Page to the device,
12753  * to see whether the page 'page' is supported.
12754  * Return values are:
12755  * -1 if the Log Sense command fails
12756  * 0 if page is not supported
12757  * 1 if page is supported
12758  */
12759 
12760 static int
12761 st_logpage_supported(struct scsi_tape *un, uchar_t page)
12762 {
12763 	uchar_t *sp, *sensep;
12764 	unsigned length;
12765 	struct uscsi_cmd *com;
12766 	int rval;
12767 	char cdb[CDB_GROUP1] = {
12768 		SCMD_LOG_SENSE_G1,
12769 		0,
12770 		SUPPORTED_LOG_PAGES_PAGE,
12771 		0,
12772 		0,
12773 		0,
12774 		0,
12775 		0,
12776 		(char)LOG_SENSE_LENGTH,
12777 		0
12778 	};
12779 
12780 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
12781 
12782 	ASSERT(mutex_owned(ST_MUTEX));
12783 
12784 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12785 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12786 
12787 	com->uscsi_cdb = cdb;
12788 	com->uscsi_cdblen = CDB_GROUP1;
12789 	com->uscsi_bufaddr = (caddr_t)sensep;
12790 	com->uscsi_buflen = LOG_SENSE_LENGTH;
12791 	com->uscsi_flags =
12792 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12793 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12794 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12795 	if (rval || com->uscsi_status) {
12796 		/* uscsi-command failed */
12797 		rval = -1;
12798 	} else {
12799 
12800 		sp = sensep + 3;
12801 
12802 		for (length = *sp++; length > 0; length--, sp++) {
12803 
12804 			if (*sp == page) {
12805 				rval = 1;
12806 				break;
12807 			}
12808 		}
12809 	}
12810 	kmem_free(com, sizeof (struct uscsi_cmd));
12811 	kmem_free(sensep, LOG_SENSE_LENGTH);
12812 	return (rval);
12813 }
12814 
12815 
12816 /*
12817  * st_check_clean_bit() gets the status of the tape's cleaning bit.
12818  *
12819  * If the device does support the TapeAlert log page, then the cleaning bit
12820  * information will be read from this page. Otherwise we will see if one of
12821  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
12822  * the device, which means, that we can get the cleaning bit information via
12823  * a RequestSense command.
12824  * If both methods of getting cleaning bit information are not supported
12825  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
12826  * returns with
12827  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
12828  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
12829  * If the call to st_uscsi_cmd() to do the Log Sense or the Request Sense
12830  * command fails, or if the amount of Request Sense data is not enough, then
12831  *  st_check_clean_bit() returns with -1.
12832  */
12833 
12834 static int
12835 st_check_clean_bit(struct scsi_tape *un)
12836 {
12837 	int rval = 0;
12838 
12839 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
12840 
12841 	ASSERT(mutex_owned(ST_MUTEX));
12842 
12843 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
12844 		return (rval);
12845 	}
12846 
12847 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
12848 
12849 		rval = st_logpage_supported(un, TAPE_SEQUENTIAL_PAGE);
12850 		if (rval == 1) {
12851 
12852 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
12853 		}
12854 
12855 		rval = st_logpage_supported(un, TAPE_ALERT_PAGE);
12856 		if (rval == 1) {
12857 
12858 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
12859 		}
12860 
12861 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
12862 
12863 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
12864 		}
12865 	}
12866 
12867 	rval = 0;
12868 
12869 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
12870 
12871 		rval = st_check_sequential_clean_bit(un);
12872 	}
12873 
12874 	if ((rval <= 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
12875 
12876 		rval = st_check_alert_flags(un);
12877 	}
12878 
12879 	if ((rval <= 0) && (un->un_dp->options & ST_CLN_MASK)) {
12880 
12881 		rval = st_check_sense_clean_bit(un);
12882 	}
12883 
12884 	if (rval < 0) {
12885 		return (rval);
12886 	}
12887 
12888 	/*
12889 	 * If found a supported means to check need to clean.
12890 	 */
12891 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
12892 
12893 		/*
12894 		 * head needs to be cleaned.
12895 		 */
12896 		if (rval & MTF_TAPE_HEAD_DIRTY) {
12897 
12898 			/*
12899 			 * Print log message only first time
12900 			 * found needing cleaned.
12901 			 */
12902 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
12903 
12904 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12905 				    "Periodic head cleaning required");
12906 
12907 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
12908 			}
12909 
12910 		} else {
12911 
12912 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
12913 		}
12914 	}
12915 
12916 	return (rval);
12917 }
12918 
12919 
12920 static int
12921 st_check_sequential_clean_bit(struct scsi_tape *un)
12922 {
12923 	int rval;
12924 	int ix;
12925 	ushort_t parameter;
12926 	struct uscsi_cmd *cmd;
12927 	struct log_sequential_page *sp;
12928 	struct log_sequential_page_parameter *prm;
12929 	char cdb[CDB_GROUP1] = {
12930 		SCMD_LOG_SENSE_G1,
12931 		0,
12932 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
12933 		0,
12934 		0,
12935 		0,
12936 		0,
12937 		(char)(sizeof (struct log_sequential_page) >> 8),
12938 		(char)(sizeof (struct log_sequential_page)),
12939 		0
12940 	};
12941 
12942 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
12943 
12944 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12945 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
12946 
12947 	cmd->uscsi_flags   =
12948 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12949 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12950 	cmd->uscsi_cdb	   = cdb;
12951 	cmd->uscsi_cdblen  = CDB_GROUP1;
12952 	cmd->uscsi_bufaddr = (caddr_t)sp;
12953 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
12954 
12955 	rval = st_uscsi_cmd(un, cmd, FKIOCTL);
12956 
12957 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
12958 
12959 		rval = -1;
12960 
12961 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
12962 
12963 		rval = -1;
12964 	}
12965 
12966 	prm = &sp->param[0];
12967 
12968 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
12969 
12970 		if (prm->log_param.length == 0) {
12971 			break;
12972 		}
12973 
12974 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
12975 		    (prm->log_param.pc_lo & 0xff));
12976 
12977 		if (parameter == SEQUENTIAL_NEED_CLN) {
12978 
12979 			rval = MTF_TAPE_CLN_SUPPORTED;
12980 			if (prm->param_value[prm->log_param.length - 1]) {
12981 
12982 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12983 				    "sequential log says head dirty\n");
12984 				rval |= MTF_TAPE_HEAD_DIRTY;
12985 			}
12986 		}
12987 		prm = (struct log_sequential_page_parameter *)
12988 		    &prm->param_value[prm->log_param.length];
12989 	}
12990 
12991 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12992 	kmem_free(sp,  sizeof (struct log_sequential_page));
12993 
12994 	return (rval);
12995 }
12996 
12997 
12998 static int
12999 st_check_alert_flags(struct scsi_tape *un)
13000 {
13001 	struct st_tape_alert *ta;
13002 	struct uscsi_cmd *com;
13003 	unsigned ix, length;
13004 	int rval;
13005 	tape_alert_flags flag;
13006 	char cdb[CDB_GROUP1] = {
13007 		SCMD_LOG_SENSE_G1,
13008 		0,
13009 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
13010 		0,
13011 		0,
13012 		0,
13013 		0,
13014 		(char)(sizeof (struct st_tape_alert) >> 8),
13015 		(char)(sizeof (struct st_tape_alert)),
13016 		0
13017 	};
13018 
13019 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
13020 
13021 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13022 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
13023 
13024 	com->uscsi_cdb = cdb;
13025 	com->uscsi_cdblen = CDB_GROUP1;
13026 	com->uscsi_bufaddr = (caddr_t)ta;
13027 	com->uscsi_buflen = sizeof (struct st_tape_alert);
13028 	com->uscsi_flags =
13029 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13030 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13031 
13032 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13033 
13034 	if (rval || com->uscsi_status || com->uscsi_resid) {
13035 
13036 		rval = -1; /* uscsi-command failed */
13037 
13038 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
13039 
13040 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13041 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
13042 		rval = -1;
13043 	}
13044 
13045 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
13046 
13047 
13048 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
13049 
13050 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13051 		    "TapeAlert length %d\n", length);
13052 	}
13053 
13054 
13055 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
13056 
13057 		/*
13058 		 * if rval is bad before the first pass don't bother
13059 		 */
13060 		if (ix == 0 && rval != 0) {
13061 
13062 			break;
13063 		}
13064 
13065 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
13066 		    ta->param[ix].log_param.pc_lo);
13067 
13068 		if ((ta->param[ix].param_value & 1) == 0) {
13069 			continue;
13070 		}
13071 		/*
13072 		 * check to see if current parameter is of interest.
13073 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
13074 		 */
13075 		if ((flag == TAF_CLEAN_NOW) ||
13076 		    (flag == TAF_CLEAN_PERIODIC) ||
13077 		    ((flag == CLEAN_FOR_ERRORS) &&
13078 		    (un->un_dp->type == ST_TYPE_STK9840))) {
13079 
13080 			rval = MTF_TAPE_CLN_SUPPORTED;
13081 
13082 
13083 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13084 			    "alert_page drive needs clean %d\n", flag);
13085 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
13086 			rval |= MTF_TAPE_HEAD_DIRTY;
13087 
13088 		} else if (flag == TAF_CLEANING_MEDIA) {
13089 
13090 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13091 			    "alert_page drive was cleaned\n");
13092 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
13093 		}
13094 
13095 	}
13096 
13097 	/*
13098 	 * Report it as dirty till we see it cleaned
13099 	 */
13100 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
13101 
13102 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13103 		    "alert_page still dirty\n");
13104 		rval |= MTF_TAPE_HEAD_DIRTY;
13105 	}
13106 
13107 	kmem_free(com, sizeof (struct uscsi_cmd));
13108 	kmem_free(ta,  sizeof (struct st_tape_alert));
13109 
13110 	return (rval);
13111 }
13112 
13113 
13114 static int
13115 st_check_sense_clean_bit(struct scsi_tape *un)
13116 {
13117 	uchar_t *sensep;
13118 	char cdb[CDB_GROUP0];
13119 	struct uscsi_cmd *com;
13120 	ushort_t byte_pos;
13121 	uchar_t bit_mask;
13122 	unsigned length;
13123 	int index;
13124 	int rval;
13125 
13126 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
13127 
13128 	/*
13129 	 * Since this tape does not support Tape Alert,
13130 	 * we now try to get the cleanbit status via
13131 	 * Request Sense.
13132 	 */
13133 
13134 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
13135 
13136 		index = 0;
13137 
13138 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
13139 
13140 		index = 1;
13141 
13142 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
13143 
13144 		index = 2;
13145 
13146 	} else {
13147 
13148 		return (-1);
13149 	}
13150 
13151 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
13152 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
13153 	length = byte_pos + 1;
13154 
13155 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13156 	sensep = kmem_zalloc(length, KM_SLEEP);
13157 
13158 	cdb[0] = SCMD_REQUEST_SENSE;
13159 	cdb[1] = 0;
13160 	cdb[2] = 0;
13161 	cdb[3] = 0;
13162 	cdb[4] = (char)length;
13163 	cdb[5] = 0;
13164 
13165 	com->uscsi_cdb = cdb;
13166 	com->uscsi_cdblen = CDB_GROUP0;
13167 	com->uscsi_bufaddr = (caddr_t)sensep;
13168 	com->uscsi_buflen = length;
13169 	com->uscsi_flags =
13170 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13171 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13172 
13173 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13174 
13175 	if (rval || com->uscsi_status || com->uscsi_resid) {
13176 
13177 		rval = -1;
13178 
13179 	} else {
13180 
13181 		rval = MTF_TAPE_CLN_SUPPORTED;
13182 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
13183 
13184 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13185 			    "sense data says head dirty\n");
13186 			rval |= MTF_TAPE_HEAD_DIRTY;
13187 		}
13188 	}
13189 
13190 	kmem_free(com, sizeof (struct uscsi_cmd));
13191 	kmem_free(sensep, length);
13192 	return (rval);
13193 }
13194 
13195 /*
13196  * st_clear_unit_attention
13197  *
13198  *  	run test unit ready's to clear out outstanding
13199  * 	unit attentions.
13200  * 	returns zero for SUCCESS or the errno from st_cmd call
13201  */
13202 static int
13203 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
13204 {
13205 	int	i    = 0;
13206 	int	rval;
13207 
13208 	GET_SOFT_STATE(dev_instance);
13209 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
13210 
13211 	do {
13212 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
13213 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
13214 	return (rval);
13215 }
13216 
13217 static void
13218 st_calculate_timeouts(struct scsi_tape *un)
13219 {
13220 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
13221 
13222 	if (un->un_dp->non_motion_timeout == 0) {
13223 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13224 			un->un_dp->non_motion_timeout =
13225 			    st_io_time * st_long_timeout_x;
13226 		} else {
13227 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
13228 		}
13229 	}
13230 
13231 	if (un->un_dp->io_timeout == 0) {
13232 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13233 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
13234 		} else {
13235 			un->un_dp->io_timeout = (ushort_t)st_io_time;
13236 		}
13237 	}
13238 
13239 	if (un->un_dp->rewind_timeout == 0) {
13240 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13241 			un->un_dp->rewind_timeout =
13242 			    st_space_time * st_long_timeout_x;
13243 		} else {
13244 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
13245 		}
13246 	}
13247 
13248 	if (un->un_dp->space_timeout == 0) {
13249 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13250 			un->un_dp->space_timeout =
13251 			    st_space_time * st_long_timeout_x;
13252 		} else {
13253 			un->un_dp->space_timeout = (ushort_t)st_space_time;
13254 		}
13255 	}
13256 
13257 	if (un->un_dp->load_timeout == 0) {
13258 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13259 			un->un_dp->load_timeout =
13260 			    st_space_time * st_long_timeout_x;
13261 		} else {
13262 			un->un_dp->load_timeout = (ushort_t)st_space_time;
13263 		}
13264 	}
13265 
13266 	if (un->un_dp->unload_timeout == 0) {
13267 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13268 			un->un_dp->unload_timeout =
13269 			    st_space_time * st_long_timeout_x;
13270 		} else {
13271 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
13272 		}
13273 	}
13274 
13275 	if (un->un_dp->erase_timeout == 0) {
13276 		if (un->un_dp->options & ST_LONG_ERASE) {
13277 			un->un_dp->erase_timeout =
13278 			    st_space_time * st_long_space_time_x;
13279 		} else {
13280 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
13281 		}
13282 	}
13283 }
13284 
13285 
13286 static writablity
13287 st_is_not_wormable(struct scsi_tape *un)
13288 {
13289 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
13290 	return (RDWR);
13291 }
13292 
13293 static writablity
13294 st_is_hp_dat_tape_worm(struct scsi_tape *un)
13295 {
13296 	writablity wrt;
13297 
13298 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
13299 
13300 	/* Mode sense should be current */
13301 	if (un->un_mspl->media_type == 1) {
13302 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13303 		    "Drive has WORM media loaded\n");
13304 		wrt = WORM;
13305 	} else {
13306 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13307 		    "Drive has non WORM media loaded\n");
13308 		wrt = RDWR;
13309 	}
13310 	return (wrt);
13311 }
13312 
13313 #define	HP_DAT_INQUIRY 0x4A
13314 static writablity
13315 st_is_hp_dat_worm(struct scsi_tape *un)
13316 {
13317 	char *buf;
13318 	int result;
13319 	writablity wrt;
13320 
13321 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
13322 
13323 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
13324 
13325 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
13326 
13327 	if (result != 0) {
13328 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13329 		    "Read Standard Inquiry for WORM support failed");
13330 		wrt = FAILED;
13331 	} else if ((buf[40] & 1) == 0) {
13332 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13333 		    "Drive is NOT WORMable\n");
13334 		/* This drive doesn't support it so don't check again */
13335 		un->un_dp->options &= ~ST_WORMABLE;
13336 		wrt = RDWR;
13337 		un->un_wormable = st_is_not_wormable;
13338 	} else {
13339 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13340 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13341 		un->un_wormable = st_is_hp_dat_tape_worm;
13342 		wrt = un->un_wormable(un);
13343 	}
13344 
13345 	kmem_free(buf, HP_DAT_INQUIRY);
13346 
13347 	/*
13348 	 * If drive doesn't support it no point in checking further.
13349 	 */
13350 	return (wrt);
13351 }
13352 
13353 static writablity
13354 st_is_hp_lto_tape_worm(struct scsi_tape *un)
13355 {
13356 	writablity wrt;
13357 
13358 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
13359 
13360 	/* Mode sense should be current */
13361 	switch (un->un_mspl->media_type) {
13362 	case 0x00:
13363 		switch (un->un_mspl->density) {
13364 		case 0x40:
13365 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13366 			    "Drive has standard Gen I media loaded\n");
13367 			break;
13368 		case 0x42:
13369 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13370 			    "Drive has standard Gen II media loaded\n");
13371 			break;
13372 		case 0x44:
13373 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13374 			    "Drive has standard Gen III media loaded\n");
13375 			break;
13376 		case 0x46:
13377 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13378 			    "Drive has standard Gen IV media loaded\n");
13379 			break;
13380 		default:
13381 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13382 			    "Drive has standard unknown 0x%X media loaded\n",
13383 			    un->un_mspl->density);
13384 		}
13385 		wrt = RDWR;
13386 		break;
13387 	case 0x01:
13388 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13389 		    "Drive has WORM medium loaded\n");
13390 		wrt = WORM;
13391 		break;
13392 	case 0x80:
13393 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13394 		    "Drive has CD-ROM emulation medium loaded\n");
13395 		wrt = WORM;
13396 		break;
13397 	default:
13398 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13399 		    "Drive has an unexpected medium type 0x%X loaded\n",
13400 		    un->un_mspl->media_type);
13401 		wrt = RDWR;
13402 	}
13403 
13404 	return (wrt);
13405 }
13406 
13407 #define	LTO_REQ_INQUIRY 44
13408 static writablity
13409 st_is_hp_lto_worm(struct scsi_tape *un)
13410 {
13411 	char *buf;
13412 	int result;
13413 	writablity wrt;
13414 
13415 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
13416 
13417 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
13418 
13419 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
13420 
13421 	if (result != 0) {
13422 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13423 		    "Read Standard Inquiry for WORM support failed");
13424 		wrt = FAILED;
13425 	} else if ((buf[40] & 1) == 0) {
13426 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13427 		    "Drive is NOT WORMable\n");
13428 		/* This drive doesn't support it so don't check again */
13429 		un->un_dp->options &= ~ST_WORMABLE;
13430 		wrt = RDWR;
13431 		un->un_wormable = st_is_not_wormable;
13432 	} else {
13433 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13434 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13435 		un->un_wormable = st_is_hp_lto_tape_worm;
13436 		wrt = un->un_wormable(un);
13437 	}
13438 
13439 	kmem_free(buf, LTO_REQ_INQUIRY);
13440 
13441 	/*
13442 	 * If drive doesn't support it no point in checking further.
13443 	 */
13444 	return (wrt);
13445 }
13446 
13447 static writablity
13448 st_is_t10_worm_device(struct scsi_tape *un)
13449 {
13450 	writablity wrt;
13451 
13452 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
13453 
13454 	if (un->un_mspl->media_type == 0x3c) {
13455 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13456 		    "Drive has WORM media loaded\n");
13457 		wrt = WORM;
13458 	} else {
13459 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13460 		    "Drive has non WORM media loaded\n");
13461 		wrt = RDWR;
13462 	}
13463 	return (wrt);
13464 }
13465 
13466 #define	SEQ_CAP_PAGE	(char)0xb0
13467 static writablity
13468 st_is_t10_worm(struct scsi_tape *un)
13469 {
13470 	char *buf;
13471 	int result;
13472 	writablity wrt;
13473 
13474 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
13475 
13476 	buf = kmem_zalloc(6, KM_SLEEP);
13477 
13478 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
13479 
13480 	if (result != 0) {
13481 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13482 		    "Read Vitial Inquiry for Sequental Capability"
13483 		    " WORM support failed %x", result);
13484 		wrt = FAILED;
13485 	} else if ((buf[4] & 1) == 0) {
13486 		ASSERT(buf[1] == SEQ_CAP_PAGE);
13487 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13488 		    "Drive is NOT WORMable\n");
13489 		/* This drive doesn't support it so don't check again */
13490 		un->un_dp->options &= ~ST_WORMABLE;
13491 		wrt = RDWR;
13492 		un->un_wormable = st_is_not_wormable;
13493 	} else {
13494 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13495 		    "Drive supports WORM\n");
13496 		un->un_wormable = st_is_t10_worm_device;
13497 		wrt = un->un_wormable(un);
13498 	}
13499 
13500 	kmem_free(buf, 6);
13501 
13502 	return (wrt);
13503 }
13504 
13505 
13506 #define	STK_REQ_SENSE 26
13507 
13508 static writablity
13509 st_is_stk_worm(struct scsi_tape *un)
13510 {
13511 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
13512 	struct scsi_extended_sense *sense;
13513 	struct uscsi_cmd *cmd;
13514 	char *buf;
13515 	int result;
13516 	writablity wrt;
13517 
13518 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
13519 
13520 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13521 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
13522 	sense = (struct scsi_extended_sense *)buf;
13523 
13524 	cmd->uscsi_flags = USCSI_READ;
13525 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13526 	cmd->uscsi_cdb = &cdb[0];
13527 	cmd->uscsi_bufaddr = buf;
13528 	cmd->uscsi_buflen = STK_REQ_SENSE;
13529 	cmd->uscsi_cdblen = CDB_GROUP0;
13530 	cmd->uscsi_rqlen = 0;
13531 	cmd->uscsi_rqbuf = NULL;
13532 
13533 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
13534 
13535 	if (result != 0 || cmd->uscsi_status != 0) {
13536 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13537 		    "Request Sense for WORM failed");
13538 		wrt = RDWR;
13539 	} else if (sense->es_add_len + 8 < 24) {
13540 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13541 		    "Drive didn't send enough sense data for WORM byte %d\n",
13542 		    sense->es_add_len + 8);
13543 		wrt = RDWR;
13544 		un->un_wormable = st_is_not_wormable;
13545 	} else if ((buf[24]) & 0x02) {
13546 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13547 		    "Drive has WORM tape loaded\n");
13548 		wrt = WORM;
13549 		un->un_wormable = st_is_stk_worm;
13550 	} else {
13551 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13552 		    "Drive has normal tape loaded\n");
13553 		wrt = RDWR;
13554 		un->un_wormable = st_is_stk_worm;
13555 	}
13556 
13557 	kmem_free(buf, STK_REQ_SENSE);
13558 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13559 	return (wrt);
13560 }
13561 
13562 #define	DLT_INQ_SZ 44
13563 
13564 static writablity
13565 st_is_dlt_tape_worm(struct scsi_tape *un)
13566 {
13567 	caddr_t buf;
13568 	int result;
13569 	writablity wrt;
13570 
13571 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
13572 
13573 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
13574 
13575 	/* Read Attribute Media Type */
13576 
13577 	result = st_read_attributes(un, 0x0408, buf, 10, st_uscsi_cmd);
13578 
13579 	/*
13580 	 * If this quantum drive is attached via an HBA that cannot
13581 	 * support thr read attributes command return error in the
13582 	 * hope that someday they will support the t10 method.
13583 	 */
13584 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
13585 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13586 		    "Read Attribute Command for WORM Media detection is not "
13587 		    "supported on the HBA that this drive is attached to.");
13588 		wrt = RDWR;
13589 		un->un_wormable = st_is_not_wormable;
13590 		goto out;
13591 	}
13592 
13593 	if (result != 0) {
13594 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13595 		    "Read Attribute Command for WORM Media returned 0x%x",
13596 		    result);
13597 		wrt = RDWR;
13598 		un->un_dp->options &= ~ST_WORMABLE;
13599 		goto out;
13600 	}
13601 
13602 	if ((uchar_t)buf[9] == 0x80) {
13603 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13604 		    "Drive media is WORM\n");
13605 		wrt = WORM;
13606 	} else {
13607 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13608 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
13609 		wrt = RDWR;
13610 	}
13611 
13612 out:
13613 	kmem_free(buf, DLT_INQ_SZ);
13614 	return (wrt);
13615 }
13616 
13617 static writablity
13618 st_is_dlt_worm(struct scsi_tape *un)
13619 {
13620 	caddr_t buf;
13621 	int result;
13622 	writablity wrt;
13623 
13624 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
13625 
13626 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
13627 
13628 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
13629 
13630 	if (result != 0) {
13631 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13632 		    "Read Vendor Specific Inquiry for WORM support failed");
13633 		wrt = RDWR;
13634 		goto out;
13635 	}
13636 
13637 	if ((buf[2] & 1) == 0) {
13638 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13639 		    "Drive is not WORMable\n");
13640 		wrt = RDWR;
13641 		un->un_dp->options &= ~ST_WORMABLE;
13642 		un->un_wormable = st_is_not_wormable;
13643 		goto out;
13644 	} else {
13645 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13646 		    "Drive is WORMable\n");
13647 		un->un_wormable = st_is_dlt_tape_worm;
13648 		wrt = un->un_wormable(un);
13649 	}
13650 out:
13651 	kmem_free(buf, DLT_INQ_SZ);
13652 
13653 	return (wrt);
13654 }
13655 
13656 typedef struct {
13657 	struct modeheader_seq header;
13658 #if defined(_BIT_FIELDS_LTOH) /* X86 */
13659 	uchar_t pagecode	:6,
13660 				:2;
13661 	uchar_t page_len;
13662 	uchar_t syslogalive	:2,
13663 		device		:1,
13664 		abs		:1,
13665 		ulpbot		:1,
13666 		prth		:1,
13667 		ponej		:1,
13668 		ait		:1;
13669 	uchar_t span;
13670 
13671 	uchar_t			:6,
13672 		worm		:1,
13673 		mic		:1;
13674 	uchar_t worm_cap	:1,
13675 				:7;
13676 	uint32_t		:32;
13677 #else /* SPARC */
13678 	uchar_t			:2,
13679 		pagecode	:6;
13680 	uchar_t page_len;
13681 	uchar_t ait		:1,
13682 		device		:1,
13683 		abs		:1,
13684 		ulpbot		:1,
13685 		prth		:1,
13686 		ponej		:1,
13687 		syslogalive	:2;
13688 	uchar_t span;
13689 	uchar_t mic		:1,
13690 		worm		:1,
13691 				:6;
13692 	uchar_t			:7,
13693 		worm_cap	:1;
13694 	uint32_t		:32;
13695 #endif
13696 }ait_dev_con;
13697 
13698 #define	AIT_DEV_PAGE 0x31
13699 static writablity
13700 st_is_sony_worm(struct scsi_tape *un)
13701 {
13702 	int result;
13703 	writablity wrt;
13704 	ait_dev_con *ait_conf;
13705 
13706 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
13707 
13708 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
13709 
13710 	result = st_gen_mode_sense(un, st_uscsi_cmd, AIT_DEV_PAGE,
13711 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
13712 
13713 	if (result == 0) {
13714 
13715 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
13716 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13717 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
13718 			    ait_conf->pagecode, AIT_DEV_PAGE);
13719 			wrt = RDWR;
13720 			un->un_wormable = st_is_not_wormable;
13721 
13722 		} else if (ait_conf->worm_cap) {
13723 
13724 			un->un_wormable = st_is_sony_worm;
13725 
13726 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13727 			    "Drives is WORMable\n");
13728 			if (ait_conf->worm) {
13729 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13730 				    "Media is WORM\n");
13731 				wrt = WORM;
13732 			} else {
13733 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13734 				    "Media is not WORM\n");
13735 				wrt = RDWR;
13736 			}
13737 
13738 		} else {
13739 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13740 			    "Drives not is WORMable\n");
13741 			wrt = RDWR;
13742 			/* No further checking required */
13743 			un->un_dp->options &= ~ST_WORMABLE;
13744 		}
13745 
13746 	} else {
13747 
13748 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13749 		    "AIT device config mode sense page read command failed"
13750 		    " result = %d ", result);
13751 		wrt = FAILED;
13752 		un->un_wormable = st_is_not_wormable;
13753 	}
13754 
13755 	kmem_free(ait_conf, sizeof (ait_dev_con));
13756 	return (wrt);
13757 }
13758 
13759 static writablity
13760 st_is_drive_worm(struct scsi_tape *un)
13761 {
13762 	writablity wrt;
13763 
13764 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
13765 
13766 	switch (un->un_dp->type) {
13767 	case MT_ISDLT:
13768 		wrt = st_is_dlt_worm(un);
13769 		break;
13770 
13771 	case MT_ISSTK9840:
13772 		wrt = st_is_stk_worm(un);
13773 		break;
13774 
13775 	case MT_IS8MM:
13776 	case MT_ISAIT:
13777 		wrt = st_is_sony_worm(un);
13778 		break;
13779 
13780 	case MT_LTO:
13781 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
13782 			wrt = st_is_hp_lto_worm(un);
13783 		} else {
13784 			wrt = st_is_t10_worm(un);
13785 		}
13786 		break;
13787 
13788 	case MT_ISDAT:
13789 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
13790 			wrt = st_is_hp_dat_worm(un);
13791 		} else {
13792 			wrt = st_is_t10_worm(un);
13793 		}
13794 		break;
13795 
13796 	default:
13797 		wrt = FAILED;
13798 		break;
13799 	}
13800 
13801 	/*
13802 	 * If any of the above failed try the t10 standard method.
13803 	 */
13804 	if (wrt == FAILED) {
13805 		wrt = st_is_t10_worm(un);
13806 	}
13807 
13808 	/*
13809 	 * Unknown method for detecting WORM media.
13810 	 */
13811 	if (wrt == FAILED) {
13812 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13813 		    "Unknown method for WORM media detection\n");
13814 		wrt = RDWR;
13815 		un->un_dp->options &= ~ST_WORMABLE;
13816 	}
13817 
13818 	return (wrt);
13819 }
13820 
13821 static int
13822 st_read_attributes(struct scsi_tape *un, uint16_t attribute, void *pnt,
13823     size_t size, ubufunc_t bufunc)
13824 {
13825 	char cdb[CDB_GROUP4];
13826 	int result;
13827 	struct uscsi_cmd *cmd;
13828 	caddr_t buf = (caddr_t)pnt;
13829 
13830 	ST_FUNC(ST_DEVINFO, st_read_attributes);
13831 
13832 	if (un->un_sd->sd_inq->inq_ansi < 3) {
13833 		return (ENOTTY);
13834 	}
13835 
13836 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13837 
13838 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
13839 	cdb[1] = 0;
13840 	cdb[2] = 0;
13841 	cdb[3] = 0;
13842 	cdb[4] = 0;
13843 	cdb[5] = 0;
13844 	cdb[6] = 0;
13845 	cdb[7] = 0;
13846 	cdb[8] = (char)(attribute >> 8);
13847 	cdb[9] = (char)(attribute);
13848 	cdb[10] = (char)(size >> 24);
13849 	cdb[11] = (char)(size >> 16);
13850 	cdb[12] = (char)(size >> 8);
13851 	cdb[13] = (char)(size);
13852 	cdb[14] = 0;
13853 	cdb[15] = 0;
13854 
13855 
13856 	cmd->uscsi_flags = USCSI_READ | USCSI_DIAGNOSE;
13857 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13858 	cmd->uscsi_cdb = &cdb[0];
13859 	cmd->uscsi_bufaddr = (caddr_t)buf;
13860 	cmd->uscsi_buflen = size;
13861 	cmd->uscsi_cdblen = sizeof (cdb);
13862 
13863 	result = bufunc(un, cmd, FKIOCTL);
13864 
13865 	if (result != 0 || cmd->uscsi_status != 0) {
13866 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13867 		    "st_read_attribute failed: result %d status %d\n",
13868 		    result, cmd->uscsi_status);
13869 		/*
13870 		 * If this returns invalid operation code don't try again.
13871 		 */
13872 		if (un->un_sd->sd_sense->es_key == KEY_ILLEGAL_REQUEST &&
13873 		    un->un_sd->sd_sense->es_add_code == 0x20) {
13874 			result = ENOTTY;
13875 		} else if (result == 0) {
13876 			result = EIO;
13877 		}
13878 
13879 	} else {
13880 
13881 		/*
13882 		 * The attribute retured should match the attribute requested.
13883 		 */
13884 		if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
13885 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13886 			    "st_read_attribute got wrong data back expected "
13887 			    "0x%x got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
13888 			st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
13889 			    "bad? data", buf, size);
13890 			result = EIO;
13891 		}
13892 	}
13893 
13894 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13895 
13896 	return (result);
13897 }
13898 
13899 static int
13900 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
13901     uchar_t page)
13902 {
13903 	char cdb[CDB_GROUP0];
13904 	struct scsi_extended_sense *sense;
13905 	struct uscsi_cmd *cmd;
13906 	int result;
13907 
13908 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
13909 
13910 	cdb[0] = SCMD_INQUIRY;
13911 	cdb[1] = page ? 1 : 0;
13912 	cdb[2] = page;
13913 	cdb[3] = 0;
13914 	cdb[4] = size;
13915 	cdb[5] = 0;
13916 
13917 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13918 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
13919 
13920 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
13921 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13922 	cmd->uscsi_cdb = &cdb[0];
13923 	cmd->uscsi_bufaddr = dest;
13924 	cmd->uscsi_buflen = size;
13925 	cmd->uscsi_cdblen = CDB_GROUP0;
13926 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
13927 	cmd->uscsi_rqbuf = (caddr_t)sense;
13928 
13929 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
13930 
13931 	if (result != 0 || cmd->uscsi_status != 0) {
13932 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13933 		    "st_get_special_inquiry() failed for page %x", page);
13934 		if (result == 0) {
13935 			result = EIO;
13936 		}
13937 	}
13938 
13939 	kmem_free(sense, sizeof (struct scsi_extended_sense));
13940 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13941 
13942 	return (result);
13943 }
13944 
13945 
13946 static int
13947 st_update_block_pos(struct scsi_tape *un, bufunc_t bf, int post_space)
13948 {
13949 	int rval = ENOTTY;
13950 	uchar_t status = un->un_status;
13951 	posmode previous_pmode = un->un_running.pmode;
13952 
13953 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
13954 
13955 	while (un->un_read_pos_type != NO_POS) {
13956 		rval = bf(un, SCMD_READ_POSITION, 32, SYNC_CMD);
13957 
13958 		/*
13959 		 * If read position command returned good status
13960 		 * Parse the data to see if the position can be interpreted.
13961 		 */
13962 		if ((rval == 0) &&
13963 		    ((rval = st_interpret_read_pos(un, &un->un_pos,
13964 		    un->un_read_pos_type, 32, (caddr_t)un->un_read_pos_data,
13965 		    post_space)) == 0)) {
13966 			/*
13967 			 * Update the running position as well if un_pos was
13968 			 * ok. But only if recovery is enabled.
13969 			 */
13970 			if (st_recov_sz != sizeof (recov_info)) {
13971 				break;
13972 			}
13973 			rval = st_interpret_read_pos(un, &un->un_running,
13974 			    un->un_read_pos_type, 32,
13975 			    (caddr_t)un->un_read_pos_data, post_space);
13976 			un->un_status = status;
13977 			break;
13978 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
13979 			un->un_running.pmode = previous_pmode;
13980 			continue;
13981 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
13982 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13983 			    "st_update_block_pos() read position cmd 0x%x"
13984 			    " returned 0x%x un_status = %d",
13985 			    un->un_read_pos_type, rval, un->un_status);
13986 			/* ENOTTY means it read garbage. try something else. */
13987 			if (rval == ENOTTY) {
13988 				rval = EIO; /* so ENOTTY is not final rval */
13989 			} else {
13990 				break;
13991 			}
13992 		} else {
13993 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
13994 			    "st_update_block_pos() read position cmd %x"
13995 			    " returned %x", un->un_read_pos_type, rval);
13996 			un->un_running.pmode = previous_pmode;
13997 		}
13998 
13999 		switch (un->un_read_pos_type) {
14000 		case SHORT_POS:
14001 			un->un_read_pos_type = NO_POS;
14002 			break;
14003 
14004 		case LONG_POS:
14005 			un->un_read_pos_type = EXT_POS;
14006 			break;
14007 
14008 		case EXT_POS:
14009 			un->un_read_pos_type = SHORT_POS;
14010 			break;
14011 
14012 		default:
14013 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14014 			    "Unexpected read position type 0x%x",
14015 			    un->un_read_pos_type);
14016 		}
14017 		un->un_status = KEY_NO_SENSE;
14018 	}
14019 
14020 	return (rval);
14021 }
14022 
14023 static int
14024 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
14025 {
14026 	int result;
14027 	size_t d_sz;
14028 	caddr_t pos_info;
14029 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
14030 
14031 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
14032 
14033 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
14034 		return (0);
14035 	}
14036 
14037 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
14038 
14039 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14040 		    "bp_mapin_common() failed");
14041 
14042 		return (EIO);
14043 	}
14044 
14045 	d_sz = bp->b_bcount - bp->b_resid;
14046 	if (d_sz == 0) {
14047 		bp_mapout(bp);
14048 		return (EIO);
14049 	}
14050 
14051 	/*
14052 	 * Copy the buf to a double-word aligned memory that can hold the
14053 	 * tape_position_t data structure.
14054 	 */
14055 	if ((pos_info = kmem_alloc(d_sz, KM_NOSLEEP)) == NULL) {
14056 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14057 		    "kmem_alloc() failed");
14058 		bp_mapout(bp);
14059 		return (EIO);
14060 	}
14061 	bcopy(bp->b_un.b_addr, pos_info, d_sz);
14062 
14063 #ifdef STDEBUG
14064 	if ((st_debug & 0x7) > 2) {
14065 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14066 		    "st_get_read_pos() position info",
14067 		    pos_info, bp->b_bcount);
14068 	}
14069 #endif
14070 
14071 	result = st_interpret_read_pos(un, &un->un_pos, cmd->uscsi_cdb[1],
14072 	    d_sz, pos_info, 0);
14073 
14074 	COPY_POS(&un->un_running, &un->un_pos);
14075 
14076 	kmem_free(pos_info, d_sz);
14077 	bp_mapout(bp);
14078 
14079 	return (result);
14080 }
14081 
14082 #if defined(_BIG_ENDIAN)
14083 
14084 #define	FIX_ENDIAN16(x)
14085 #define	FIX_ENDIAN32(x)
14086 #define	FIX_ENDIAN64(x)
14087 
14088 #elif defined(_LITTLE_ENDIAN)
14089 
14090 static void
14091 st_swap16(uint16_t *val)
14092 {
14093 	uint16_t tmp;
14094 
14095 	tmp = (*val >>  8) & 0xff;
14096 	tmp |= (*val <<  8) & 0xff00;
14097 
14098 	*val = tmp;
14099 }
14100 
14101 static void
14102 st_swap32(uint32_t *val)
14103 {
14104 	uint32_t tmp;
14105 
14106 	tmp =  (*val >> 24) & 0xff;
14107 	tmp |= (*val >>  8) & 0xff00;
14108 	tmp |= (*val <<  8) & 0xff0000;
14109 	tmp |= (*val << 24) & 0xff000000;
14110 
14111 	*val = tmp;
14112 }
14113 
14114 static void
14115 st_swap64(uint64_t *val)
14116 {
14117 	uint32_t low;
14118 	uint32_t high;
14119 
14120 	low =  (uint32_t)(*val);
14121 	high = (uint32_t)(*val >> 32);
14122 
14123 	st_swap32(&low);
14124 	st_swap32(&high);
14125 
14126 	*val =  high;
14127 	*val |= ((uint64_t)low << 32);
14128 }
14129 
14130 #define	FIX_ENDIAN16(x) st_swap16(x)
14131 #define	FIX_ENDIAN32(x) st_swap32(x)
14132 #define	FIX_ENDIAN64(x) st_swap64(x)
14133 #endif
14134 
14135 /*
14136  * st_interpret_read_pos()
14137  *
14138  * Returns:
14139  *	0	If secsessful.
14140  *	EIO	If read postion responce data was unuseable or invalid.
14141  *	ERANGE	If the position of the drive is too large for the read_p_type.
14142  *	ENOTTY	If the responce data looks invalid for the read position type.
14143  */
14144 
14145 static int
14146 st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
14147     read_p_types type, size_t data_sz, const caddr_t responce, int post_space)
14148 {
14149 	int rval = 0;
14150 	int flag = 0;
14151 	tapepos_t org;
14152 
14153 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
14154 
14155 	/*
14156 	 * We expect the position value to change after a space command.
14157 	 * So if post_space is set we don't print out what has changed.
14158 	 */
14159 	if ((dest != &un->un_pos) && (post_space == 0) &&
14160 	    (st_recov_sz == sizeof (recov_info))) {
14161 		COPY_POS(&org, dest);
14162 		flag = 1;
14163 	}
14164 
14165 	/*
14166 	 * See what kind of read position was requested.
14167 	 */
14168 	switch (type) {
14169 
14170 	case SHORT_POS: /* Short data format */
14171 	{
14172 		tape_position_t *pos_info = (tape_position_t *)responce;
14173 		uint32_t value;
14174 
14175 		/* If reserved fields are non zero don't use the data */
14176 		if (pos_info->reserved0 || pos_info->reserved1 ||
14177 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
14178 		    pos_info->reserved3) {
14179 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14180 			    "Invalid Read Short Position Data returned\n");
14181 			rval = EIO;
14182 			break;
14183 		}
14184 		/*
14185 		 * Position is to large to use this type of read position.
14186 		 */
14187 		if (pos_info->posi_err == 1) {
14188 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14189 			    "Drive reported position error\n");
14190 			rval = ERANGE;
14191 			break;
14192 		}
14193 		/*
14194 		 * If your at the begining of partition and end at the same
14195 		 * time it's very small partition or bad data.
14196 		 */
14197 		if (pos_info->begin_of_part && pos_info->end_of_part) {
14198 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14199 			    "SHORT_POS returned begin and end of"
14200 			    " partition\n");
14201 			rval = EIO;
14202 			break;
14203 		}
14204 
14205 		if (pos_info->blk_posi_unkwn == 0) {
14206 
14207 			value = pos_info->host_block;
14208 			FIX_ENDIAN32(&value);
14209 
14210 			/*
14211 			 * If the tape is rewound the host blcok should be 0.
14212 			 */
14213 			if ((pos_info->begin_of_part == 1) &&
14214 			    (value != 0)) {
14215 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14216 				    "SHORT_POS returned begin of partition"
14217 				    " but host block was 0x%x\n", value);
14218 				rval = EIO;
14219 				break;
14220 			}
14221 
14222 			if (dest->lgclblkno != value) {
14223 				if (flag)
14224 					flag++;
14225 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14226 				    "SHORT_POS current logical 0x%"PRIx64" read"
14227 				    " 0x%x\n", dest->lgclblkno, value);
14228 			}
14229 
14230 			dest->lgclblkno = (uint64_t)value;
14231 
14232 			/*
14233 			 * If the begining of partition is true and the
14234 			 * block number is zero we will beleive that it is
14235 			 * rewound. Promote the pmode to legacy.
14236 			 */
14237 			if ((pos_info->begin_of_part == 1) &&
14238 			    (value == 0)) {
14239 				dest->blkno = 0;
14240 				dest->fileno = 0;
14241 				if (dest->pmode != legacy)
14242 					dest->pmode = legacy;
14243 			/*
14244 			 * otherwise if the pmode was invalid,
14245 			 * promote it to logical.
14246 			 */
14247 			} else if (dest->pmode == invalid) {
14248 				dest->pmode = logical;
14249 			}
14250 
14251 			if (dest->partition != pos_info->partition_number) {
14252 				if (flag)
14253 					flag++;
14254 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14255 				    "SHORT_POS current partition %d read %d\n",
14256 				    dest->partition,
14257 				    pos_info->partition_number);
14258 			}
14259 
14260 			dest->partition = pos_info->partition_number;
14261 
14262 		} else {
14263 			dest->pmode = invalid;
14264 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14265 			    "Tape drive reported block position as unknown\n");
14266 		}
14267 		break;
14268 	}
14269 
14270 	case LONG_POS: /* Long data format */
14271 	{
14272 		uint64_t value;
14273 		tape_position_long_t *long_pos_info =
14274 		    (tape_position_long_t *)responce;
14275 
14276 		/* If reserved fields are non zero don't use the data */
14277 		if ((long_pos_info->reserved0) ||
14278 		    (long_pos_info->reserved1) ||
14279 		    (long_pos_info->reserved2)) {
14280 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14281 			    "Invalid Read Long Position Data returned\n");
14282 			rval = ENOTTY;
14283 			break;
14284 		}
14285 
14286 		/* Is position Valid */
14287 		if (long_pos_info->blk_posi_unkwn == 0) {
14288 			uint32_t part;
14289 
14290 			value = long_pos_info->block_number;
14291 			FIX_ENDIAN64(&value);
14292 
14293 			/*
14294 			 * If it says we are at the begining of partition
14295 			 * the block value better be 0.
14296 			 */
14297 			if ((long_pos_info->begin_of_part == 1) &&
14298 			    (value != 0)) {
14299 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14300 				    "LONG_POS returned begin of partition but"
14301 				    " block number was 0x%"PRIx64"\n", value);
14302 				rval = ENOTTY;
14303 				break;
14304 			}
14305 			/*
14306 			 * Can't be at the start and the end of the partition
14307 			 * at the same time if the partition is larger the 0.
14308 			 */
14309 			if (long_pos_info->begin_of_part &&
14310 			    long_pos_info->end_of_part) {
14311 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14312 				    "LONG_POS returned begin and end of"
14313 				    " partition\n");
14314 				rval = ENOTTY;
14315 				break;
14316 			}
14317 
14318 			/*
14319 			 * If the logical block number is not what we expected.
14320 			 */
14321 			if (dest->lgclblkno != value) {
14322 				if (flag)
14323 					flag++;
14324 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14325 				    "LONG_POS current logical 0x%"PRIx64
14326 				    " read 0x%"PRIx64"\n",
14327 				    dest->lgclblkno, value);
14328 			}
14329 			dest->lgclblkno = value;
14330 
14331 			/*
14332 			 * If the begining of partition is true and the
14333 			 * block number is zero we will beleive that it is
14334 			 * rewound. Promote the pmode to legacy.
14335 			 */
14336 			if ((long_pos_info->begin_of_part == 1) &&
14337 			    (long_pos_info->block_number == 0)) {
14338 				dest->blkno = 0;
14339 				dest->fileno = 0;
14340 				if (dest->pmode != legacy)
14341 					dest->pmode = legacy;
14342 			/*
14343 			 * otherwise if the pmode was invalid,
14344 			 * promote it to logical.
14345 			 */
14346 			} else if (dest->pmode == invalid) {
14347 				dest->pmode = logical;
14348 			}
14349 
14350 			part = long_pos_info->partition;
14351 			FIX_ENDIAN32(&part);
14352 			if (dest->partition != part) {
14353 				if (flag)
14354 					flag++;
14355 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14356 				    "LONG_POS current partition %d"
14357 				    " read %d\n", dest->partition, part);
14358 			}
14359 			dest->partition = part;
14360 		} else {
14361 			/*
14362 			 * If the drive doesn't know location,
14363 			 * we don't either.
14364 			 */
14365 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14366 			    "Tape drive reported block position as unknown\n");
14367 			dest->pmode = invalid;
14368 		}
14369 
14370 		/* Is file position valid */
14371 		if (long_pos_info->mrk_posi_unkwn == 0) {
14372 			value = long_pos_info->file_number;
14373 			FIX_ENDIAN64(&value);
14374 			/*
14375 			 * If it says we are at the begining of partition
14376 			 * the block value better be 0.
14377 			 */
14378 			if ((long_pos_info->begin_of_part == 1) &&
14379 			    (value != 0)) {
14380 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14381 				    "LONG_POS returned begin of partition but"
14382 				    " block number was 0x%"PRIx64"\n", value);
14383 				rval = ENOTTY;
14384 				break;
14385 			}
14386 			if (((dest->pmode == legacy) ||
14387 			    (dest->pmode == logical)) &&
14388 			    (dest->fileno != value)) {
14389 				if (flag)
14390 					flag++;
14391 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14392 				    "LONG_POS fileno 0x%"PRIx64
14393 				    " not un_pos %x\n", value,
14394 				    dest->fileno);
14395 			} else if (dest->pmode == invalid) {
14396 				dest->pmode = logical;
14397 			}
14398 			dest->fileno = (int32_t)value;
14399 		} else {
14400 			/*
14401 			 * If the drive doesn't know its position,
14402 			 * we don't either.
14403 			 */
14404 			dest->pmode = invalid;
14405 		}
14406 		if (dest->pmode != invalid && long_pos_info->end_of_part) {
14407 			dest->eof = ST_EOT;
14408 		}
14409 
14410 		break;
14411 	}
14412 
14413 	case EXT_POS: /* Extended data format */
14414 	{
14415 		uint64_t value;
14416 		uint16_t len;
14417 		tape_position_ext_t *ext_pos_info =
14418 		    (tape_position_ext_t *)responce;
14419 
14420 		/* Make sure that there is enough data there */
14421 		if (data_sz < 16) {
14422 			break;
14423 		}
14424 
14425 		/* If reserved fields are non zero don't use the data */
14426 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
14427 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14428 			    "EXT_POS reserved fields not zero\n");
14429 			rval = ENOTTY;
14430 			break;
14431 		}
14432 
14433 		/*
14434 		 * In the unlikely event of overflowing 64 bits of position.
14435 		 */
14436 		if (ext_pos_info->posi_err != 0) {
14437 			rval = ERANGE;
14438 			break;
14439 		}
14440 
14441 		len = ext_pos_info->parameter_len;
14442 		FIX_ENDIAN16(&len);
14443 
14444 		if (len != 0x1c) {
14445 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14446 			    "EXT_POS parameter_len should be 0x1c was 0x%x\n",
14447 			    len);
14448 			rval = ENOTTY;
14449 			break;
14450 		}
14451 
14452 		/* Is block position information valid */
14453 		if (ext_pos_info->blk_posi_unkwn == 0) {
14454 
14455 			value = ext_pos_info->host_block;
14456 			FIX_ENDIAN64(&value);
14457 			if ((ext_pos_info->begin_of_part == 1) &&
14458 			    (value != 0)) {
14459 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14460 				    "EXT_POS returned begining of partition but"
14461 				    " the host block was 0x%"PRIx64"\n", value);
14462 				rval = ENOTTY;
14463 				break;
14464 			}
14465 
14466 			if (dest->lgclblkno != value) {
14467 				if (flag)
14468 					flag++;
14469 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14470 				    "EXT_POS current logical 0x%"PRIx64
14471 				    " read 0x%"PRIx64"\n",
14472 				    dest->lgclblkno, value);
14473 			}
14474 			dest->lgclblkno = value;
14475 
14476 			/*
14477 			 * If the begining of partition is true and the
14478 			 * block number is zero we will beleive that it is
14479 			 * rewound. Promote the pmode to legacy.
14480 			 */
14481 			if ((ext_pos_info->begin_of_part == 1) &&
14482 			    (ext_pos_info->host_block == 0)) {
14483 				dest->blkno = 0;
14484 				dest->fileno = 0;
14485 				if (dest->pmode != legacy) {
14486 					dest->pmode = legacy;
14487 				}
14488 			/*
14489 			 * otherwise if the pmode was invalid,
14490 			 * promote it to logical.
14491 			 */
14492 			} else if (dest->pmode == invalid) {
14493 				dest->pmode = logical;
14494 			}
14495 
14496 			if (dest->partition != ext_pos_info->partition) {
14497 				if (flag)
14498 					flag++;
14499 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14500 				    "EXT_POS current partition %d read %d\n",
14501 				    dest->partition,
14502 				    ext_pos_info->partition);
14503 			}
14504 			dest->partition = ext_pos_info->partition;
14505 
14506 		} else {
14507 			dest->pmode = invalid;
14508 		}
14509 		break;
14510 	}
14511 
14512 	default:
14513 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14514 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
14515 		rval = EIO;
14516 	}
14517 
14518 	if ((flag > 1) && (rval == 0)) {
14519 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14520 		    "position read in", &org);
14521 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14522 		    "position read out", dest);
14523 	}
14524 
14525 	return (rval);
14526 }
14527 
14528 static int
14529 st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos,
14530     uint64_t lblk, uchar_t partition)
14531 {
14532 	int rval;
14533 	char cdb[CDB_GROUP4];
14534 	struct uscsi_cmd *cmd;
14535 	struct scsi_extended_sense sense;
14536 	bufunc_t bf = (ubf == st_uscsi_cmd) ? st_cmd : st_rcmd;
14537 
14538 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
14539 	/*
14540 	 * WTF Not sure what to do when doing recovery and not wanting
14541 	 * to update un_pos
14542 	 */
14543 
14544 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14545 
14546 	if (lblk <= INT32_MAX) {
14547 		cmd->uscsi_cdblen = CDB_GROUP1;
14548 		cdb[0] = SCMD_LOCATE;
14549 		cdb[1] = pos->partition == partition ? 0 : 2;
14550 		cdb[2] = 0;
14551 		cdb[3] = (char)(lblk >> 24);
14552 		cdb[4] = (char)(lblk >> 16);
14553 		cdb[5] = (char)(lblk >> 8);
14554 		cdb[6] = (char)(lblk);
14555 		cdb[7] = 0;
14556 		cdb[8] = partition;
14557 		cdb[9] = 0;
14558 	} else {
14559 		/*
14560 		 * If the drive doesn't give a 64 bit read position data
14561 		 * it is unlikely it will accept 64 bit locates.
14562 		 */
14563 		if (un->un_read_pos_type != LONG_POS) {
14564 			kmem_free(cmd, sizeof (struct uscsi_cmd));
14565 			return (ERANGE);
14566 		}
14567 		cmd->uscsi_cdblen = CDB_GROUP4;
14568 		cdb[0] = (char)SCMD_LOCATE_G4;
14569 		cdb[1] = pos->partition == partition ? 0 : 2;
14570 		cdb[2] = 0;
14571 		cdb[3] = partition;
14572 		cdb[4] = (char)(lblk >> 56);
14573 		cdb[5] = (char)(lblk >> 48);
14574 		cdb[6] = (char)(lblk >> 40);
14575 		cdb[7] = (char)(lblk >> 32);
14576 		cdb[8] = (char)(lblk >> 24);
14577 		cdb[9] = (char)(lblk >> 16);
14578 		cdb[10] = (char)(lblk >> 8);
14579 		cdb[11] = (char)(lblk);
14580 		cdb[12] = 0;
14581 		cdb[13] = 0;
14582 		cdb[14] = 0;
14583 		cdb[15] = 0;
14584 	}
14585 
14586 
14587 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
14588 	cmd->uscsi_rqbuf = (caddr_t)&sense;
14589 	cmd->uscsi_rqlen = sizeof (sense);
14590 	cmd->uscsi_timeout = un->un_dp->space_timeout;
14591 	cmd->uscsi_cdb = cdb;
14592 
14593 	rval = ubf(un, cmd, FKIOCTL);
14594 
14595 	pos->pmode = logical;
14596 	pos->eof = ST_NO_EOF;
14597 
14598 	if (lblk > INT32_MAX) {
14599 		/*
14600 		 * XXX This is a work around till we handle Descriptor format
14601 		 * sense data. Since we are sending a command where the standard
14602 		 * sense data can not correctly represent a correct residual in
14603 		 * 4 bytes.
14604 		 */
14605 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
14606 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14607 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
14608 			/* Doesn't like big locate command */
14609 			un->un_status = 0;
14610 			rval = ERANGE;
14611 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
14612 			/* Aborted big locate command */
14613 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14614 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
14615 			    rval);
14616 			un->un_status = 0;
14617 			rval = EIO;
14618 		} else if (st_update_block_pos(un, bf, 1)) {
14619 			/* read position failed */
14620 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14621 			    "Big LOCATE and read pos: rval = %d\n", rval);
14622 			rval = EIO;
14623 		} else if (lblk > un->un_pos.lgclblkno) {
14624 			/* read position worked but position was not expected */
14625 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14626 			    "Big LOCATE and recover read less then desired 0x%"
14627 			    PRIx64"\n", un->un_pos.lgclblkno);
14628 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
14629 			un->un_status = KEY_BLANK_CHECK;
14630 			rval = ESPIPE;
14631 		} else if (lblk == un->un_pos.lgclblkno) {
14632 			/* read position was what was expected */
14633 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14634 			    "Big LOCATE and recover seems to have worked\n");
14635 			un->un_err_resid = 0;
14636 			rval = 0;
14637 		} else {
14638 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14639 			    "BIGLOCATE end up going backwards");
14640 			un->un_err_resid = lblk;
14641 			rval = EIO;
14642 		}
14643 
14644 	} else if (rval == 0) {
14645 		/* Worked as requested */
14646 		pos->lgclblkno = lblk;
14647 
14648 	} else if (((cmd->uscsi_status & STATUS_MASK) == STATUS_CHECK) &&
14649 	    (cmd->uscsi_resid != 0)) {
14650 		/* Got part way there but wasn't enough blocks on tape */
14651 		pos->lgclblkno = lblk - cmd->uscsi_resid;
14652 		un->un_err_resid = cmd->uscsi_resid;
14653 		un->un_status = KEY_BLANK_CHECK;
14654 		rval = ESPIPE;
14655 
14656 	} else if (st_update_block_pos(un, bf, 1) == 0) {
14657 		/* Got part way there but drive didn't tell what we missed by */
14658 		un->un_err_resid = lblk - pos->lgclblkno;
14659 		un->un_status = KEY_BLANK_CHECK;
14660 		rval = ESPIPE;
14661 
14662 	} else {
14663 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14664 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
14665 		    rval, cmd->uscsi_status);
14666 		un->un_err_resid = lblk;
14667 		un->un_status = KEY_ILLEGAL_REQUEST;
14668 		pos->pmode = invalid;
14669 		rval = EIO;
14670 	}
14671 
14672 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14673 
14674 	return (rval);
14675 }
14676 
14677 static int
14678 st_mtfsf_ioctl(struct scsi_tape *un, int files)
14679 {
14680 	int rval;
14681 
14682 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
14683 
14684 
14685 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14686 	    "st_mtfsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
14687 #if 0
14688 	if ((IN_EOF(un->un_pos)) && (files == 1)) {
14689 		un->un_pos.fileno++;
14690 		un->un_pos.blkno = 0;
14691 		return (0);
14692 	}
14693 #endif
14694 	/* pmode == invalid already handled */
14695 	if (un->un_pos.pmode == legacy) {
14696 		/*
14697 		 * forward space over filemark
14698 		 *
14699 		 * For ASF we allow a count of 0 on fsf which means
14700 		 * we just want to go to beginning of current file.
14701 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
14702 		 * Allow stepping over double fmk with reel
14703 		 */
14704 		if ((un->un_pos.eof >= ST_EOT) &&
14705 		    (files > 0) &&
14706 		    ((un->un_dp->options & ST_REEL) == 0)) {
14707 			/* we're at EOM */
14708 			un->un_err_resid = files;
14709 			un->un_status = KEY_BLANK_CHECK;
14710 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14711 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
14712 			return (EIO);
14713 		}
14714 
14715 		/*
14716 		 * physical tape position may not be what we've been
14717 		 * telling the user; adjust the request accordingly
14718 		 */
14719 		if (IN_EOF(un->un_pos)) {
14720 			un->un_pos.fileno++;
14721 			un->un_pos.blkno = 0;
14722 			/*
14723 			 * For positive direction case, we're now covered.
14724 			 * For zero or negative direction, we're covered
14725 			 * (almost)
14726 			 */
14727 			files--;
14728 		}
14729 
14730 	}
14731 
14732 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
14733 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14734 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
14735 		return (EIO);
14736 	}
14737 
14738 
14739 	/*
14740 	 * Forward space file marks.
14741 	 * We leave ourselves at block zero
14742 	 * of the target file number.
14743 	 */
14744 	if (files < 0) {
14745 		rval = st_backward_space_files(un, -files, 0);
14746 	} else {
14747 		rval = st_forward_space_files(un, files);
14748 	}
14749 
14750 	return (rval);
14751 }
14752 
14753 static int
14754 st_forward_space_files(struct scsi_tape *un, int count)
14755 {
14756 	int rval;
14757 
14758 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
14759 
14760 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14761 	    "fspace: count=%x, eof=%x\n", count, un->un_pos.eof);
14762 
14763 	ASSERT(count >= 0);
14764 	ASSERT(un->un_pos.pmode != invalid);
14765 
14766 	/*
14767 	 * A space with a count of zero means take me to the start of file.
14768 	 */
14769 	if (count == 0) {
14770 
14771 		/* Hay look were already there */
14772 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0) {
14773 			un->un_err_resid = 0;
14774 			COPY_POS(&un->un_err_pos, &un->un_pos);
14775 			return (0);
14776 		}
14777 
14778 		/*
14779 		 * Well we are in the first file.
14780 		 * A rewind will get to the start.
14781 		 */
14782 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
14783 			rval = st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
14784 
14785 		/*
14786 		 * Can we backspace to get there?
14787 		 * This should work in logical mode.
14788 		 */
14789 		} else if (un->un_dp->options & ST_BSF) {
14790 			rval = st_space_to_begining_of_file(un);
14791 
14792 		/*
14793 		 * Can't back space but current file number is known,
14794 		 * So rewind and space from the begining of the partition.
14795 		 */
14796 		} else if (un->un_pos.pmode == legacy) {
14797 			rval = st_scenic_route_to_begining_of_file(un,
14798 			    un->un_pos.fileno);
14799 
14800 		/*
14801 		 * pmode is logical and ST_BSF is not set.
14802 		 * The LONG_POS read position contains the fileno.
14803 		 * If the read position works, rewind and space.
14804 		 */
14805 		} else if (un->un_read_pos_type == LONG_POS) {
14806 			rval = st_cmd(un, SCMD_READ_POSITION, 0, SYNC_CMD);
14807 			if (rval) {
14808 				/*
14809 				 * We didn't get the file position from the
14810 				 * read position command.
14811 				 * We are going to trust the drive to backspace
14812 				 * and then position after the filemark.
14813 				 */
14814 				rval = st_space_to_begining_of_file(un);
14815 			}
14816 			rval = st_interpret_read_pos(un, &un->un_pos, LONG_POS,
14817 			    32, (caddr_t)un->un_read_pos_data, 0);
14818 			if ((rval) && (un->un_pos.pmode == invalid)) {
14819 				rval = st_space_to_begining_of_file(un);
14820 			} else {
14821 				rval = st_scenic_route_to_begining_of_file(un,
14822 				    un->un_pos.fileno);
14823 			}
14824 		} else {
14825 			rval = EIO;
14826 		}
14827 		/*
14828 		 * If something didn't work we are lost
14829 		 */
14830 		if (rval != 0) {
14831 			un->un_pos.pmode = invalid;
14832 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14833 			    "st_mtioctop : EIO : fspace pmode invalid");
14834 
14835 			rval = EIO;
14836 		}
14837 
14838 	} else {
14839 		rval = st_space_fmks(un, count);
14840 	}
14841 
14842 	if (rval != EIO && count < 0) {
14843 		/*
14844 		 * we came here with a count < 0; we now need
14845 		 * to skip back to end up before the filemark
14846 		 */
14847 		rval = st_backward_space_files(un, 1, 1);
14848 	}
14849 
14850 	return (rval);
14851 }
14852 
14853 static int
14854 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
14855 {
14856 	int rval;
14857 
14858 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
14859 
14860 	if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
14861 		rval = EIO;
14862 	} else if (st_cmd(un, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
14863 		rval = EIO;
14864 	}
14865 
14866 	return (rval);
14867 }
14868 
14869 static int
14870 st_space_to_begining_of_file(struct scsi_tape *un)
14871 {
14872 	int rval;
14873 
14874 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
14875 
14876 	/*
14877 	 * Back space of the file at the begining of the file.
14878 	 */
14879 	rval = st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
14880 	if (rval) {
14881 		rval = EIO;
14882 		return (rval);
14883 	}
14884 
14885 	/*
14886 	 * Other interesting answers might be crashed BOT which isn't bad.
14887 	 */
14888 	if (un->un_status == SUN_KEY_BOT) {
14889 		return (rval);
14890 	}
14891 
14892 	un->un_running.pmode = invalid;
14893 
14894 	/*
14895 	 * Now we are on the BOP side of the filemark. Forward space to
14896 	 * the EOM side and we are at the begining of the file.
14897 	 */
14898 	rval = st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD);
14899 	if (rval) {
14900 		rval = EIO;
14901 	}
14902 
14903 	return (rval);
14904 }
14905 
14906 static int
14907 st_mtfsr_ioctl(struct scsi_tape *un, int count)
14908 {
14909 
14910 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
14911 
14912 	/*
14913 	 * forward space to inter-record gap
14914 	 *
14915 	 */
14916 
14917 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14918 	    "st_ioctl_fsr: count=%x, eof=%x\n", count, un->un_pos.eof);
14919 
14920 	if (un->un_pos.pmode == legacy) {
14921 		/*
14922 		 * If were are at end of tape and count is forward.
14923 		 * Return blank check.
14924 		 */
14925 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
14926 			/* we're at EOM */
14927 			un->un_err_resid = count;
14928 			un->un_status = KEY_BLANK_CHECK;
14929 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14930 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
14931 			return (EIO);
14932 		}
14933 
14934 		/*
14935 		 * If count is zero there is nothing to do.
14936 		 */
14937 		if (count == 0) {
14938 			un->un_err_pos.fileno = un->un_pos.fileno;
14939 			un->un_err_pos.blkno = un->un_pos.blkno;
14940 			un->un_err_resid = 0;
14941 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
14942 				un->un_status = SUN_KEY_EOF;
14943 			}
14944 			return (0);
14945 		}
14946 
14947 		/*
14948 		 * physical tape position may not be what we've been
14949 		 * telling the user; adjust the position accordingly
14950 		 */
14951 		if (IN_EOF(un->un_pos)) {
14952 			daddr_t blkno = un->un_pos.blkno;
14953 			int fileno = un->un_pos.fileno;
14954 
14955 			optype lastop = un->un_lastop;
14956 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)
14957 			    == -1) {
14958 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14959 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
14960 				return (EIO);
14961 			}
14962 
14963 			un->un_pos.blkno = blkno;
14964 			un->un_pos.fileno = fileno;
14965 			un->un_lastop = lastop;
14966 		}
14967 	}
14968 
14969 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
14970 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14971 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
14972 		return (EIO);
14973 	}
14974 
14975 	return (st_space_records(un, count));
14976 }
14977 
14978 static int
14979 st_space_records(struct scsi_tape *un, int count)
14980 {
14981 	int dblk;
14982 	int rval = 0;
14983 
14984 	ST_FUNC(ST_DEVINFO, st_space_records);
14985 
14986 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14987 	    "st_space_records: count=%x, eof=%x\n", count, un->un_pos.eof);
14988 
14989 	if (un->un_pos.pmode == logical) {
14990 		rval = st_cmd(un, SCMD_SPACE, Blk(count), SYNC_CMD);
14991 		if (rval != 0) {
14992 			rval = EIO;
14993 		}
14994 		return (rval);
14995 	}
14996 
14997 	dblk = un->un_pos.blkno + count;
14998 
14999 	/* Already there */
15000 	if (dblk == un->un_pos.blkno) {
15001 		un->un_err_resid = 0;
15002 		COPY_POS(&un->un_err_pos, &un->un_pos);
15003 		return (0);
15004 	}
15005 
15006 	/*
15007 	 * If the destination block is forward
15008 	 * or the drive will backspace records.
15009 	 */
15010 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
15011 		/*
15012 		 * If we're spacing forward, or the device can
15013 		 * backspace records, we can just use the SPACE
15014 		 * command.
15015 		 */
15016 		dblk -= un->un_pos.blkno;
15017 		if (st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15018 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15019 			    "st_space_records:EIO:space_records can't spc");
15020 			rval = EIO;
15021 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
15022 			/*
15023 			 * check if we hit BOT/EOT
15024 			 */
15025 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
15026 				un->un_status = SUN_KEY_BOT;
15027 				un->un_pos.eof = ST_NO_EOF;
15028 			} else if (dblk < 0 &&
15029 			    un->un_pos.eof == ST_EOF_PENDING) {
15030 				int residue = un->un_err_resid;
15031 				/*
15032 				 * we skipped over a filemark
15033 				 * and need to go forward again
15034 				 */
15035 				if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
15036 					ST_DEBUG2(ST_DEVINFO, st_label,
15037 					    SCSI_DEBUG, "st_space_records: EIO"
15038 					    " : can't space #2");
15039 					rval = EIO;
15040 				}
15041 				un->un_err_resid = residue;
15042 			}
15043 			if (rval == 0) {
15044 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15045 				    "st_space_records: EIO : space_rec rval"
15046 				    " == 0");
15047 				rval = EIO;
15048 			}
15049 		}
15050 	} else {
15051 		/*
15052 		 * else we rewind, space forward across filemarks to
15053 		 * the desired file, and then space records to the
15054 		 * desired block.
15055 		 */
15056 
15057 		int dfile = un->un_pos.fileno;	/* save current file */
15058 
15059 		if (dblk < 0) {
15060 			/*
15061 			 * Wups - we're backing up over a filemark
15062 			 */
15063 			if (un->un_pos.blkno != 0 &&
15064 			    (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15065 			    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD))) {
15066 				un->un_pos.pmode = invalid;
15067 			}
15068 			un->un_err_resid = -dblk;
15069 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
15070 				un->un_status = SUN_KEY_BOT;
15071 				un->un_pos.eof = ST_NO_EOF;
15072 			} else if (un->un_pos.fileno > 0) {
15073 				un->un_status = SUN_KEY_EOF;
15074 				un->un_pos.eof = ST_NO_EOF;
15075 			}
15076 			COPY_POS(&un->un_err_pos, &un->un_pos);
15077 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15078 			    "st_space_records:EIO:space_records : dblk < 0");
15079 			rval = EIO;
15080 		} else if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15081 		    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
15082 		    st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15083 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15084 			    "st_space_records: EIO :space_records : rewind "
15085 			    "and space failed");
15086 			un->un_pos.pmode = invalid;
15087 			rval = EIO;
15088 		}
15089 	}
15090 
15091 	return (rval);
15092 }
15093 
15094 static int
15095 st_mtbsf_ioctl(struct scsi_tape *un, int files)
15096 {
15097 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
15098 
15099 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15100 	    "st_mtbsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
15101 	/*
15102 	 * backward space of file filemark (1/2" and 8mm)
15103 	 * tape position will end on the beginning of tape side
15104 	 * of the desired file mark
15105 	 */
15106 	if ((un->un_dp->options & ST_BSF) == 0) {
15107 		return (ENOTTY);
15108 	}
15109 
15110 	if (un->un_pos.pmode == legacy) {
15111 
15112 		/*
15113 		 * If a negative count (which implies a forward space op)
15114 		 * is specified, and we're at logical or physical eot,
15115 		 * bounce the request.
15116 		 */
15117 
15118 		if (un->un_pos.eof >= ST_EOT && files < 0) {
15119 			un->un_err_resid = files;
15120 			un->un_status = SUN_KEY_EOT;
15121 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15122 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
15123 			return (EIO);
15124 		}
15125 		/*
15126 		 * physical tape position may not be what we've been
15127 		 * telling the user; adjust the request accordingly
15128 		 */
15129 		if (IN_EOF(un->un_pos)) {
15130 			un->un_pos.fileno++;
15131 			un->un_pos.blkno = 0;
15132 			files++;
15133 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15134 			    "st_mtbsf_ioctl in eof: count=%d, op=%x\n",
15135 			    files, MTBSF);
15136 
15137 		}
15138 	}
15139 
15140 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15141 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15142 		    "st_ioctl : EIO : MTBSF : check den wfm");
15143 		return (EIO);
15144 	}
15145 
15146 	if (files <= 0) {
15147 		/*
15148 		 * for a negative count, we need to step forward
15149 		 * first and then step back again
15150 		 */
15151 		files = -files + 1;
15152 		return (st_forward_space_files(un, files));
15153 	}
15154 	return (st_backward_space_files(un, files, 1));
15155 }
15156 
15157 static int
15158 st_backward_space_files(struct scsi_tape *un, int count, int infront)
15159 {
15160 	int end_fileno;
15161 	int skip_cnt;
15162 	int rval = 0;
15163 
15164 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
15165 
15166 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15167 	    "st_backward_space_files: count=%x eof=%x\n",
15168 	    count, un->un_pos.eof);
15169 	/*
15170 	 * Backspace files (MTNBSF): infront == 0
15171 	 *
15172 	 *	For tapes that can backspace, backspace
15173 	 *	count+1 filemarks and then run forward over
15174 	 *	a filemark
15175 	 *
15176 	 *	For tapes that can't backspace,
15177 	 *		calculate desired filenumber
15178 	 *		(un->un_pos.fileno - count), rewind,
15179 	 *		and then space forward this amount
15180 	 *
15181 	 * Backspace filemarks (MTBSF) infront == 1
15182 	 *
15183 	 *	For tapes that can backspace, backspace count
15184 	 *	filemarks
15185 	 *
15186 	 *	For tapes that can't backspace, calculate
15187 	 *	desired filenumber (un->un_pos.fileno - count),
15188 	 *	add 1, rewind, space forward this amount,
15189 	 *	and mark state as ST_EOF_PENDING appropriately.
15190 	 */
15191 
15192 	if (un->un_pos.pmode == logical) {
15193 
15194 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15195 		    "st_backward_space_files: mt_op=%x count=%x"
15196 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
15197 		    un->un_pos.lgclblkno);
15198 
15199 
15200 		/* In case a drive that won't back space gets in logical mode */
15201 		if ((un->un_dp->options & ST_BSF) == 0) {
15202 			rval = EIO;
15203 			return (rval);
15204 		}
15205 		if ((infront == 1) &&
15206 		    (st_cmd(un, SCMD_SPACE, Fmk(-count), SYNC_CMD))) {
15207 			rval = EIO;
15208 			return (rval);
15209 		} else if ((infront == 0) &&
15210 		    (st_cmd(un, SCMD_SPACE, Fmk((-count)-1), SYNC_CMD)) &&
15211 		    (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
15212 			rval = EIO;
15213 			return (rval);
15214 		}
15215 		return (rval);
15216 	}
15217 
15218 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15219 	    "st_backward_space_files: mt_op=%x count=%x fileno=%x blkno=%x\n",
15220 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
15221 
15222 
15223 
15224 	/*
15225 	 * Handle the simple case of BOT
15226 	 * playing a role in these cmds.
15227 	 * We do this by calculating the
15228 	 * ending file number. If the ending
15229 	 * file is < BOT, rewind and set an
15230 	 * error and mark resid appropriately.
15231 	 * If we're backspacing a file (not a
15232 	 * filemark) and the target file is
15233 	 * the first file on the tape, just
15234 	 * rewind.
15235 	 */
15236 
15237 	/* figure expected destination of this SPACE command */
15238 	end_fileno = un->un_pos.fileno - count;
15239 
15240 	/*
15241 	 * Would the end effect of this SPACE be the same as rewinding?
15242 	 * If so just rewind instead.
15243 	 */
15244 	if ((infront != 0) && (end_fileno < 0) ||
15245 	    (infront == 0) && (end_fileno <= 0)) {
15246 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15247 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15248 			    "st_backward_space_files: EIO : "
15249 			    "rewind in lou of BSF failed\n");
15250 			rval = EIO;
15251 		}
15252 		if (end_fileno < 0) {
15253 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15254 			    "st_backward_space_files: EIO : "
15255 			    "back space file greater then fileno\n");
15256 			rval = EIO;
15257 			un->un_err_resid = -end_fileno;
15258 			un->un_status = SUN_KEY_BOT;
15259 		}
15260 		return (rval);
15261 	}
15262 
15263 	if (un->un_dp->options & ST_BSF) {
15264 		skip_cnt = 1 - infront;
15265 		/*
15266 		 * If we are going to end up at the beginning
15267 		 * of the file, we have to space one extra file
15268 		 * first, and then space forward later.
15269 		 */
15270 		end_fileno = -(count + skip_cnt);
15271 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15272 		    "skip_cnt=%x, tmp=%x\n", skip_cnt, end_fileno);
15273 		if (st_cmd(un, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
15274 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15275 			    "st_backward_space_files:EIO:back space fm failed");
15276 			rval = EIO;
15277 		}
15278 	} else {
15279 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15280 			rval = EIO;
15281 		} else {
15282 			skip_cnt = end_fileno + infront;
15283 		}
15284 	}
15285 
15286 	/*
15287 	 * If we have to space forward, do so...
15288 	 */
15289 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15290 	    "space forward skip_cnt=%x, rval=%x\n", skip_cnt, rval);
15291 
15292 	if (rval == 0 && skip_cnt) {
15293 		if (st_cmd(un, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
15294 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15295 			    "st_backward_space_files:EIO:space fm skip count");
15296 			rval = EIO;
15297 		} else if (infront) {
15298 			/*
15299 			 * If we had to space forward, and we're
15300 			 * not a tape that can backspace, mark state
15301 			 * as if we'd just seen a filemark during a
15302 			 * a read.
15303 			 */
15304 			if ((un->un_dp->options & ST_BSF) == 0) {
15305 				un->un_pos.eof = ST_EOF_PENDING;
15306 				un->un_pos.fileno -= 1;
15307 				un->un_pos.blkno = LASTBLK;
15308 				un->un_running.pmode = invalid;
15309 			}
15310 		}
15311 	}
15312 
15313 	if (rval != 0) {
15314 		un->un_pos.pmode = invalid;
15315 	}
15316 
15317 	return (rval);
15318 }
15319 
15320 static int
15321 st_mtnbsf_ioctl(struct scsi_tape *un, int count)
15322 {
15323 	int rval;
15324 
15325 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
15326 
15327 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15328 	    "nbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
15329 
15330 	if (un->un_pos.pmode == legacy) {
15331 		/*
15332 		 * backward space file to beginning of file
15333 		 *
15334 		 * If a negative count (which implies a forward space op)
15335 		 * is specified, and we're at logical or physical eot,
15336 		 * bounce the request.
15337 		 */
15338 
15339 		if (un->un_pos.eof >= ST_EOT && count < 0) {
15340 			un->un_err_resid = count;
15341 			un->un_status = SUN_KEY_EOT;
15342 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15343 			    "st_ioctl : EIO : > EOT and count < 0");
15344 			return (EIO);
15345 		}
15346 		/*
15347 		 * physical tape position may not be what we've been
15348 		 * telling the user; adjust the request accordingly
15349 		 */
15350 		if (IN_EOF(un->un_pos)) {
15351 			un->un_pos.fileno++;
15352 			un->un_pos.blkno = 0;
15353 			count++;
15354 		}
15355 	}
15356 
15357 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15358 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15359 		    "st_ioctl : EIO : MTNBSF check den and wfm");
15360 		return (EIO);
15361 	}
15362 
15363 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15364 	    "mtnbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
15365 
15366 	if (count <= 0) {
15367 		rval = st_forward_space_files(un, -count);
15368 	} else {
15369 		rval = st_backward_space_files(un, count, 0);
15370 	}
15371 	return (rval);
15372 }
15373 
15374 static int
15375 st_mtbsr_ioctl(struct scsi_tape *un, int num)
15376 {
15377 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
15378 
15379 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15380 	    "bsr: count=%x, eof=%x\n", num, un->un_pos.eof);
15381 
15382 	if (un->un_pos.pmode == legacy) {
15383 		/*
15384 		 * backward space into inter-record gap
15385 		 *
15386 		 * If a negative count (which implies a forward space op)
15387 		 * is specified, and we're at logical or physical eot,
15388 		 * bounce the request.
15389 		 */
15390 		if (un->un_pos.eof >= ST_EOT && num < 0) {
15391 			un->un_err_resid = num;
15392 			un->un_status = SUN_KEY_EOT;
15393 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15394 			    "st_ioctl : EIO : MTBSR > EOT");
15395 			return (EIO);
15396 		}
15397 
15398 		if (num == 0) {
15399 			COPY_POS(&un->un_err_pos, &un->un_pos);
15400 			un->un_err_resid = 0;
15401 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15402 				un->un_status = SUN_KEY_EOF;
15403 			}
15404 			return (0);
15405 		}
15406 
15407 		/*
15408 		 * physical tape position may not be what we've been
15409 		 * telling the user; adjust the position accordingly.
15410 		 * bsr can not skip filemarks and continue to skip records
15411 		 * therefore if we are logically before the filemark but
15412 		 * physically at the EOT side of the filemark, we need to step
15413 		 * back; this allows fsr N where N > number of blocks in file
15414 		 * followed by bsr 1 to position at the beginning of last block
15415 		 */
15416 		if (IN_EOF(un->un_pos)) {
15417 			tapepos_t save;
15418 			optype lastop = un->un_lastop;
15419 
15420 			COPY_POS(&save, &un->un_pos);
15421 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD) == -1) {
15422 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15423 				    "st_mtbsr_ioctl: EIO : MTBSR can't space");
15424 				return (EIO);
15425 			}
15426 
15427 			COPY_POS(&un->un_pos, &save);
15428 			un->un_lastop = lastop;
15429 		}
15430 	}
15431 
15432 	un->un_pos.eof = ST_NO_EOF;
15433 
15434 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15435 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15436 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
15437 		return (EIO);
15438 	}
15439 
15440 	num = -num;
15441 	return (st_space_records(un, num));
15442 }
15443 
15444 static int
15445 st_mtfsfm_ioctl(struct scsi_tape *un, int cnt)
15446 {
15447 	int rval;
15448 
15449 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
15450 
15451 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
15452 	if (rval == 0) {
15453 		un->un_pos.pmode = logical;
15454 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15455 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15456 		/*
15457 		 * Drive says invalid field in cdb.
15458 		 * Doesn't like space multiple. Position isn't lost.
15459 		 */
15460 		un->un_err_resid = cnt;
15461 		un->un_status = 0;
15462 		rval = ENOTTY;
15463 	} else {
15464 		un->un_err_resid = cnt;
15465 		un->un_pos.pmode = invalid;
15466 	}
15467 	return (rval);
15468 }
15469 
15470 static int
15471 st_mtbsfm_ioctl(struct scsi_tape *un, int cnt)
15472 {
15473 	int rval;
15474 
15475 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
15476 
15477 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
15478 	if (rval == 0) {
15479 		un->un_pos.pmode = logical;
15480 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15481 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15482 		/*
15483 		 * Drive says invalid field in cdb.
15484 		 * Doesn't like space multiple. Position isn't lost.
15485 		 */
15486 		un->un_err_resid = cnt;
15487 		un->un_status = 0;
15488 		rval = ENOTTY;
15489 	} else {
15490 		un->un_err_resid = cnt;
15491 		un->un_pos.pmode = invalid;
15492 	}
15493 	return (rval);
15494 }
15495 
15496 #ifdef	__x86
15497 
15498 /*
15499  * release contig_mem and wake up waiting thread, if any
15500  */
15501 static void
15502 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
15503 {
15504 	mutex_enter(ST_MUTEX);
15505 
15506 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
15507 
15508 	cp->cm_next = un->un_contig_mem;
15509 	un->un_contig_mem = cp;
15510 	un->un_contig_mem_available_num++;
15511 	cv_broadcast(&un->un_contig_mem_cv);
15512 
15513 	mutex_exit(ST_MUTEX);
15514 }
15515 
15516 /*
15517  * St_get_contig_mem will return a contig_mem if there is one available
15518  * in current system. Otherwise, it will try to alloc one, if the total
15519  * number of contig_mem is within st_max_contig_mem_num.
15520  * It will sleep, if allowed by caller or return NULL, if no contig_mem
15521  * is available for now.
15522  */
15523 static struct contig_mem *
15524 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
15525 {
15526 	size_t rlen;
15527 	struct contig_mem *cp = NULL;
15528 	ddi_acc_handle_t acc_hdl;
15529 	caddr_t addr;
15530 	int big_enough = 0;
15531 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
15532 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
15533 
15534 	/* Try to get one available contig_mem */
15535 	mutex_enter(ST_MUTEX);
15536 
15537 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
15538 
15539 	if (un->un_contig_mem_available_num > 0) {
15540 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15541 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
15542 		/*
15543 		 * we failed to get one. we're going to
15544 		 * alloc one more contig_mem for this I/O
15545 		 */
15546 		mutex_exit(ST_MUTEX);
15547 		cp = (struct contig_mem *)kmem_zalloc(
15548 		    sizeof (struct contig_mem) + biosize(),
15549 		    alloc_flags);
15550 		if (cp == NULL) {
15551 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15552 			    "alloc contig_mem failure\n");
15553 			return (NULL); /* cannot get one */
15554 		}
15555 		cp->cm_bp = (struct buf *)
15556 		    (((caddr_t)cp) + sizeof (struct contig_mem));
15557 		bioinit(cp->cm_bp);
15558 		mutex_enter(ST_MUTEX);
15559 		un->un_contig_mem_total_num++; /* one more available */
15560 	} else {
15561 		/*
15562 		 * we failed to get one and we're NOT allowed to
15563 		 * alloc more contig_mem
15564 		 */
15565 		if (alloc_flags == KM_SLEEP) {
15566 			while (un->un_contig_mem_available_num <= 0) {
15567 				cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
15568 			}
15569 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15570 		} else {
15571 			mutex_exit(ST_MUTEX);
15572 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15573 			    "alloc contig_mem failure\n");
15574 			return (NULL); /* cannot get one */
15575 		}
15576 	}
15577 	mutex_exit(ST_MUTEX);
15578 
15579 	/* We need to check if this block of mem is big enough for this I/O */
15580 	if (cp->cm_len < len) {
15581 		/* not big enough, need to alloc a new one */
15582 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
15583 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
15584 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
15585 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15586 			    "alloc contig_mem failure: not enough mem\n");
15587 			st_release_contig_mem(un, cp);
15588 			cp = NULL;
15589 		} else {
15590 			if (cp->cm_addr) {
15591 				/* release previous one before attach new one */
15592 				ddi_dma_mem_free(&cp->cm_acc_hdl);
15593 			}
15594 			mutex_enter(ST_MUTEX);
15595 			un->un_max_contig_mem_len =
15596 			    un->un_max_contig_mem_len >= len ?
15597 			    un->un_max_contig_mem_len : len;
15598 			mutex_exit(ST_MUTEX);
15599 
15600 			/* attach new mem to this cp */
15601 			cp->cm_addr = addr;
15602 			cp->cm_acc_hdl = acc_hdl;
15603 			cp->cm_len = len;
15604 
15605 			goto alloc_ok; /* get one usable cp */
15606 		}
15607 	} else {
15608 		goto alloc_ok; /* get one usable cp */
15609 	}
15610 
15611 	/* cannot find/alloc a usable cp, when we get here */
15612 
15613 	mutex_enter(ST_MUTEX);
15614 	if ((un->un_max_contig_mem_len < len) ||
15615 	    (alloc_flags != KM_SLEEP)) {
15616 		mutex_exit(ST_MUTEX);
15617 		return (NULL);
15618 	}
15619 
15620 	/*
15621 	 * we're allowed to sleep, and there is one big enough
15622 	 * contig mem in the system, which is currently in use,
15623 	 * wait for it...
15624 	 */
15625 	big_enough = 1;
15626 	do {
15627 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
15628 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15629 	} while (cp == NULL);
15630 	mutex_exit(ST_MUTEX);
15631 
15632 	/* we get the big enough contig mem, finally */
15633 
15634 alloc_ok:
15635 	/* init bp attached to this cp */
15636 	bioreset(cp->cm_bp);
15637 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
15638 	cp->cm_bp->b_private = (void *)cp;
15639 
15640 	return (cp);
15641 }
15642 
15643 /*
15644  * this is the biodone func for the bp used in big block I/O
15645  */
15646 static int
15647 st_bigblk_xfer_done(struct buf *bp)
15648 {
15649 	struct contig_mem *cp;
15650 	struct buf *orig_bp;
15651 	int ioerr;
15652 	struct scsi_tape *un;
15653 
15654 	/* sanity check */
15655 	if (bp == NULL) {
15656 		return (DDI_FAILURE);
15657 	}
15658 
15659 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
15660 	if (un == NULL) {
15661 		return (DDI_FAILURE);
15662 	}
15663 
15664 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
15665 
15666 	cp = (struct contig_mem *)bp->b_private;
15667 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
15668 	cp->cm_bp = bp;
15669 
15670 	/* special handling for special I/O */
15671 	if (cp->cm_use_sbuf) {
15672 #ifndef __lock_lint
15673 		ASSERT(un->un_sbuf_busy);
15674 #endif
15675 		un->un_sbufp = orig_bp;
15676 		cp->cm_use_sbuf = 0;
15677 	}
15678 
15679 	orig_bp->b_resid = bp->b_resid;
15680 	ioerr = geterror(bp);
15681 	if (ioerr != 0) {
15682 		bioerror(orig_bp, ioerr);
15683 	} else if (orig_bp->b_flags & B_READ) {
15684 		/* copy data back to original bp */
15685 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
15686 		    bp->b_bcount - bp->b_resid);
15687 	}
15688 
15689 	st_release_contig_mem(un, cp);
15690 
15691 	biodone(orig_bp);
15692 
15693 	return (DDI_SUCCESS);
15694 }
15695 
15696 /*
15697  * We use this func to replace original bp that may not be able to do I/O
15698  * in big block size with one that can
15699  */
15700 static struct buf *
15701 st_get_bigblk_bp(struct buf *bp)
15702 {
15703 	struct contig_mem *cp;
15704 	struct scsi_tape *un;
15705 	struct buf *cont_bp;
15706 
15707 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
15708 	if (un == NULL) {
15709 		return (bp);
15710 	}
15711 
15712 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
15713 
15714 	/* try to get one contig_mem */
15715 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
15716 	if (!cp) {
15717 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
15718 		    "Cannot alloc contig buf for I/O for %lu blk size",
15719 		    bp->b_bcount);
15720 		return (bp);
15721 	}
15722 	cont_bp = cp->cm_bp;
15723 	cp->cm_bp = bp;
15724 
15725 	/* make sure that we "are" using un_sbufp for special I/O */
15726 	if (bp == un->un_sbufp) {
15727 #ifndef __lock_lint
15728 		ASSERT(un->un_sbuf_busy);
15729 #endif
15730 		un->un_sbufp = cont_bp;
15731 		cp->cm_use_sbuf = 1;
15732 	}
15733 
15734 	/* clone bp */
15735 	cont_bp->b_bcount = bp->b_bcount;
15736 	cont_bp->b_resid = bp->b_resid;
15737 	cont_bp->b_iodone = st_bigblk_xfer_done;
15738 	cont_bp->b_file = bp->b_file;
15739 	cont_bp->b_offset = bp->b_offset;
15740 	cont_bp->b_dip = bp->b_dip;
15741 	cont_bp->b_error = 0;
15742 	cont_bp->b_proc = NULL;
15743 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
15744 	cont_bp->b_shadow = NULL;
15745 	cont_bp->b_pages = NULL;
15746 	cont_bp->b_edev = bp->b_edev;
15747 	cont_bp->b_dev = bp->b_dev;
15748 	cont_bp->b_lblkno = bp->b_lblkno;
15749 	cont_bp->b_forw = bp->b_forw;
15750 	cont_bp->b_back = bp->b_back;
15751 	cont_bp->av_forw = bp->av_forw;
15752 	cont_bp->av_back = bp->av_back;
15753 	cont_bp->b_bufsize = bp->b_bufsize;
15754 
15755 	/* get data in original bp */
15756 	if (bp->b_flags & B_WRITE) {
15757 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
15758 	}
15759 
15760 	return (cont_bp);
15761 }
15762 #else
15763 #ifdef __lock_lint
15764 static int
15765 st_bigblk_xfer_done(struct buf *bp)
15766 {
15767 	return (0);
15768 }
15769 #endif
15770 #endif
15771 
15772 static const char *eof_status[] =
15773 {
15774 	"NO_EOF",
15775 	"EOF_PENDING",
15776 	"EOF",
15777 	"EOT_PENDING",
15778 	"EOT",
15779 	"EOM",
15780 	"AFTER_EOM"
15781 };
15782 static const char *mode[] = {
15783 	"invalid",
15784 	"legacy",
15785 	"logical"
15786 };
15787 
15788 static void
15789 st_print_position(dev_info_t *dev, char *label, uint_t level,
15790 const char *comment, tapepos_t *pos)
15791 {
15792 	ST_FUNC(dev, st_print_position);
15793 
15794 	scsi_log(dev, label, level,
15795 	    "%s Position data:\n", comment);
15796 	scsi_log(dev, label, CE_CONT,
15797 	    "Positioning mode = %s", mode[pos->pmode]);
15798 	scsi_log(dev, label, CE_CONT,
15799 	    "End Of File/Tape = %s", eof_status[pos->eof]);
15800 	scsi_log(dev, label, CE_CONT,
15801 	    "File Number      = 0x%x", pos->fileno);
15802 	scsi_log(dev, label, CE_CONT,
15803 	    "Block Number     = 0x%x", pos->blkno);
15804 	scsi_log(dev, label, CE_CONT,
15805 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
15806 	scsi_log(dev, label, CE_CONT,
15807 	    "Partition Number = 0x%x", pos->partition);
15808 }
15809 static int
15810 st_check_if_media_changed(struct scsi_tape *un, caddr_t data, int size)
15811 {
15812 
15813 	int result = 0;
15814 	int i;
15815 	ST_FUNC(ST_DEVINFO, st_check_if_media_changed);
15816 
15817 	/*
15818 	 * find non alpha numeric working from the end.
15819 	 */
15820 	for (i = size - 1; i; i--) {
15821 		if (ISALNUM(data[i]) == 0 || data[i] == ' ') {
15822 			data[i] = 0;
15823 			size = i;
15824 		}
15825 	}
15826 
15827 	if (size == 1) {
15828 		/*
15829 		 * Drive seems to think its returning useful data
15830 		 * but it looks like all junk
15831 		 */
15832 		return (result);
15833 	}
15834 
15835 	size++;
15836 
15837 	/*
15838 	 * Actually got a valid serial number.
15839 	 * If never stored one before alloc space for it.
15840 	 */
15841 	if (un->un_media_id_len == 0) {
15842 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
15843 		un->un_media_id_len = size;
15844 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
15845 		un->un_media_id[min(size, strlen(data))] = 0;
15846 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
15847 		    "Found Media Id %s length = %d\n", un->un_media_id, size);
15848 	} else if (size > un->un_media_id_len) {
15849 		if (strncmp(un->un_media_id, data, size) != 0) {
15850 			result = ESPIPE;
15851 		}
15852 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
15853 		    "Longer Media Id old ID:%s new ID:%s\n",
15854 		    un->un_media_id, data);
15855 		kmem_free(un->un_media_id, un->un_media_id_len);
15856 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
15857 		un->un_media_id_len = size;
15858 		(void) strncpy(un->un_media_id, data, size);
15859 		un->un_media_id[size] = 0;
15860 	} else if (strncmp(data, un->un_media_id,
15861 	    min(size, un->un_media_id_len)) != 0) {
15862 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
15863 		    "Old Media Id %s length = %d New %s length = %d\n",
15864 		    un->un_media_id, un->un_media_id_len, data, size);
15865 		bzero(un->un_media_id, un->un_media_id_len);
15866 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
15867 		un->un_media_id[min(size, strlen(data))] = 0;
15868 		result = ESPIPE;
15869 	} else {
15870 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15871 		    "Media Id still %s\n", un->un_media_id);
15872 	}
15873 
15874 	ASSERT(strlen(un->un_media_id) <= size);
15875 
15876 	return (result);
15877 }
15878 #define	ID_SIZE 32
15879 typedef struct
15880 {
15881 	uchar_t avilable_data0;
15882 	uchar_t avilable_data1;
15883 	uchar_t avilable_data2;
15884 	uchar_t avilable_data3;
15885 	uchar_t attribute_msb;
15886 	uchar_t attribute_lsb;
15887 #ifdef _BIT_FIELDS_LTOH
15888 	uchar_t format		: 2,
15889 				: 5,
15890 		read_only	: 1;
15891 #else
15892 	uchar_t read_only	: 1,
15893 				: 5,
15894 		format		: 2;
15895 #endif
15896 	uchar_t attribute_len_msb;
15897 	uchar_t attribute_len_lsb;
15898 }attribute_header;
15899 
15900 typedef struct {
15901 	attribute_header header;
15902 	char data[1];
15903 }mam_attribute;
15904 
15905 static int
15906 st_handle_hex_media_id(struct scsi_tape *un, void *pnt, int size)
15907 {
15908 	int result;
15909 	int newsize = (size + 1) << 1;
15910 	int i;
15911 	char byte;
15912 	char *format;
15913 	char *data = (char *)pnt;
15914 	char *buf = kmem_alloc(newsize, KM_SLEEP);
15915 
15916 	ST_FUNC(ST_DEVINFO, st_handle_hex_media_id);
15917 
15918 	(void) sprintf(buf, "0x");
15919 	for (i = 0; i < size; i++) {
15920 		byte = (uchar_t)data[i];
15921 		if (byte < 0x10)
15922 			format = "0%x";
15923 		else
15924 			format = "%x";
15925 		(void) sprintf(&buf[(int)strlen(buf)], format, byte);
15926 	}
15927 	result = st_check_if_media_changed(un, buf, newsize);
15928 
15929 	kmem_free(buf, newsize);
15930 
15931 	return (result);
15932 }
15933 
15934 
15935 static int
15936 st_get_media_id_via_read_attribute(struct scsi_tape *un, ubufunc_t bufunc)
15937 {
15938 	int result;
15939 	mam_attribute *buffer;
15940 	int size;
15941 	int newsize;
15942 
15943 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_read_attribute);
15944 	size = sizeof (attribute_header) + max(un->un_media_id_len, ID_SIZE);
15945 again:
15946 	buffer = kmem_zalloc(size, KM_SLEEP);
15947 	result = st_read_attributes(un, 0x0401, buffer, size, bufunc);
15948 	if (result == 0) {
15949 
15950 		newsize = (buffer->header.attribute_len_msb << 8) |
15951 		    buffer->header.attribute_len_lsb;
15952 
15953 		if (newsize + sizeof (attribute_header) > size) {
15954 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15955 			    "resizing read attribute data from %d to %d format"
15956 			    " %d\n", size, (int)sizeof (attribute_header) +
15957 			    newsize, buffer->header.format);
15958 			kmem_free(buffer, size);
15959 			size = newsize + sizeof (attribute_header);
15960 			goto again;
15961 		}
15962 
15963 		un->un_media_id_method = st_get_media_id_via_read_attribute;
15964 		if (buffer->header.format == 0) {
15965 			result =
15966 			    st_handle_hex_media_id(un, buffer->data, newsize);
15967 		} else {
15968 			result = st_check_if_media_changed(un, buffer->data,
15969 			    newsize);
15970 		}
15971 	} else if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
15972 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
15973 		    "Read Attribute Command for Media Identification is not "
15974 		    "supported on the HBA that this drive is attached to.");
15975 		result = ENOTTY;
15976 	}
15977 
15978 	kmem_free(buffer, size);
15979 	un->un_status = 0;
15980 
15981 	return (result);
15982 }
15983 
15984 
15985 static int
15986 st_get_media_id_via_media_serial_cmd(struct scsi_tape *un, ubufunc_t bufunc)
15987 {
15988 	char cdb[CDB_GROUP5];
15989 	struct uscsi_cmd *ucmd;
15990 	struct scsi_extended_sense sense;
15991 	int rval;
15992 	int size = max(un->un_media_id_len, ID_SIZE);
15993 	caddr_t buf;
15994 
15995 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_media_serial_cmd);
15996 
15997 	if (un->un_sd->sd_inq->inq_ansi < 3) {
15998 		return (ENOTTY);
15999 	}
16000 
16001 	ucmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
16002 upsize:
16003 	buf = kmem_alloc(size, KM_SLEEP);
16004 
16005 	cdb[0] = (char)SCMD_SVC_ACTION_IN_G5;
16006 	cdb[1] = 1; /* READ MEDIA SERIAL NUMBER */
16007 	cdb[2] = 0;
16008 	cdb[3] = 0;
16009 	cdb[4] = 0;
16010 	cdb[5] = 0;
16011 	cdb[6] = (char)(size >> 24);
16012 	cdb[7] = (char)(size >> 16);
16013 	cdb[8] = (char)(size >> 8);
16014 	cdb[9] = (char)(size);
16015 	cdb[10] = 0;
16016 	cdb[11] = 0;
16017 
16018 	ucmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
16019 	ucmd->uscsi_timeout = un->un_dp->non_motion_timeout;
16020 	ucmd->uscsi_cdb = &cdb[0];
16021 	ucmd->uscsi_cdblen = sizeof (cdb);
16022 	ucmd->uscsi_bufaddr = buf;
16023 	ucmd->uscsi_buflen = size;
16024 	ucmd->uscsi_rqbuf = (caddr_t)&sense;
16025 	ucmd->uscsi_rqlen = sizeof (sense);
16026 
16027 	rval = bufunc(un, ucmd, FKIOCTL);
16028 
16029 	if (rval || ucmd->uscsi_status != 0) {
16030 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16031 		    "media serial command returned %d scsi_status %d"
16032 		    " rqstatus %d", rval, ucmd->uscsi_status,
16033 		    ucmd->uscsi_rqstatus);
16034 		/*
16035 		 * If this returns invalid operation code don't try again.
16036 		 */
16037 		if (sense.es_key == KEY_ILLEGAL_REQUEST &&
16038 		    sense.es_add_code == 0x20) {
16039 			rval = ENOTTY;
16040 		} else if (rval == 0) {
16041 			rval = EIO;
16042 		}
16043 		un->un_status = 0;
16044 	} else {
16045 		int act_size;
16046 
16047 		/*
16048 		 * get reported size.
16049 		 */
16050 		act_size = (int)buf[3] | (int)(buf[2] << 8) |
16051 		    (int)(buf[1] << 16) | (int)(buf[0] << 24);
16052 
16053 		/* documentation says mod 4. */
16054 		while (act_size & 3) {
16055 			act_size++;
16056 		}
16057 
16058 		/*
16059 		 * If reported size is larger that we our buffer.
16060 		 * Free the old one and allocate one that is larger
16061 		 * enough and re-issuse the command.
16062 		 */
16063 		if (act_size + 4 > size) {
16064 			kmem_free(buf, size);
16065 			size = act_size + 4;
16066 			goto upsize;
16067 		}
16068 
16069 		/*
16070 		 * set data pointer to point to the start of that serial number.
16071 		 */
16072 		un->un_media_id_method = st_get_media_id_via_media_serial_cmd;
16073 		rval = st_check_if_media_changed(un, &buf[4], act_size);
16074 	}
16075 
16076 	kmem_free(ucmd, sizeof (struct uscsi_cmd));
16077 	kmem_free(buf, size);
16078 
16079 	return (rval);
16080 }
16081 
16082 
16083 /* ARGSUSED */
16084 static int
16085 st_bogus_media_id(struct scsi_tape *un, ubufunc_t bufunc)
16086 {
16087 	ST_FUNC(ST_DEVINFO, st_bogus_media_id);
16088 
16089 	ASSERT(un->un_media_id == NULL || un->un_media_id == bogusID);
16090 	ASSERT(un->un_media_id_len == 0);
16091 	un->un_media_id = (char *)bogusID;
16092 	un->un_media_id_len = 0;
16093 	return (0);
16094 }
16095 
16096 typedef int (*media_chk_function)(struct scsi_tape *, ubufunc_t bufunc);
16097 
16098 media_chk_function media_chk_functions[] = {
16099 	st_get_media_id_via_media_serial_cmd,
16100 	st_get_media_id_via_read_attribute,
16101 	st_bogus_media_id
16102 };
16103 
16104 static int
16105 st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc)
16106 {
16107 	int result = 0;
16108 	int i;
16109 
16110 	ST_FUNC(ST_DEVINFO, st_get_media_identification);
16111 
16112 	for (i = 0; i < ST_NUM_MEMBERS(media_chk_functions); i++) {
16113 		if (result == ENOTTY) {
16114 			/*
16115 			 * Last operation type not supported by this device.
16116 			 * Make so next time it doesn`t do that again.
16117 			 */
16118 			un->un_media_id_method = media_chk_functions[i];
16119 		} else if (un->un_media_id_method != media_chk_functions[i] &&
16120 		    un->un_media_id_method != st_get_media_identification) {
16121 			continue;
16122 		}
16123 		result = media_chk_functions[i](un, bufunc);
16124 		/*
16125 		 * If result indicates the function was successful or
16126 		 * that the media is not the same as last known, break.
16127 		 */
16128 		if (result == 0 || result == ESPIPE) {
16129 			break;
16130 		}
16131 	}
16132 
16133 	return (result);
16134 }
16135 
16136 static errstate
16137 st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
16138     errstate onentry)
16139 {
16140 
16141 	int ret;
16142 	st_err_info *errinfo;
16143 	recov_info *ri = (recov_info *)pkt->pkt_private;
16144 
16145 	ST_FUNC(ST_DEVINFO, st_command_recovery);
16146 
16147 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16148 
16149 	ASSERT(un->un_recov_buf_busy == 0);
16150 
16151 	/*
16152 	 * Don't try and recover a reset that this device sent.
16153 	 */
16154 	if (un->un_rsvd_status & ST_INITIATED_RESET &&
16155 	    onentry == DEVICE_RESET) {
16156 		return (COMMAND_DONE_ERROR);
16157 	}
16158 
16159 	/*
16160 	 * See if expected position was passed with scsi_pkt.
16161 	 */
16162 	if (ri->privatelen == sizeof (recov_info)) {
16163 
16164 		/*
16165 		 * Not for this command.
16166 		 */
16167 		if (ri->cmd_attrib->do_not_recover) {
16168 			return (COMMAND_DONE_ERROR);
16169 		}
16170 
16171 		/*
16172 		 * Create structure to hold all error state info.
16173 		 */
16174 		errinfo = kmem_zalloc(sizeof (st_err_info), KM_SLEEP);
16175 		errinfo->ei_error_type = onentry;
16176 		errinfo->ei_failing_bp = ri->cmd_bp;
16177 		COPY_POS(&errinfo->ei_expected_pos, &ri->pos);
16178 	} else {
16179 		/* disabled */
16180 		return (COMMAND_DONE_ERROR);
16181 	}
16182 
16183 	bcopy(pkt, &errinfo->ei_failed_pkt, sizeof (struct scsi_pkt));
16184 	bcopy(pkt->pkt_scbp, &errinfo->ei_failing_status, SECMDS_STATUS_SIZE);
16185 	ret = ddi_taskq_dispatch(un->un_recov_taskq, st_recover, errinfo,
16186 	    DDI_NOSLEEP);
16187 	ASSERT(ret == DDI_SUCCESS);
16188 	if (ret != DDI_SUCCESS) {
16189 		kmem_free(errinfo, sizeof (st_err_info));
16190 		return (COMMAND_DONE_ERROR);
16191 	}
16192 	return (JUST_RETURN); /* release calling thread */
16193 }
16194 
16195 static void
16196 st_recov_ret(struct scsi_tape *un, st_err_info *errinfo, errstate err)
16197 {
16198 	int error_number;
16199 	buf_t *bp;
16200 
16201 
16202 	ST_FUNC(ST_DEVINFO, st_recov_ret);
16203 
16204 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16205 
16206 	bp = errinfo->ei_failing_bp;
16207 	kmem_free(errinfo, sizeof (st_err_info));
16208 
16209 	switch (err) {
16210 	case JUST_RETURN:
16211 		mutex_exit(&un->un_sd->sd_mutex);
16212 		return;
16213 
16214 	case COMMAND_DONE:
16215 	case COMMAND_DONE_ERROR_RECOVERED:
16216 		ST_DO_KSTATS(bp, kstat_runq_exit);
16217 		error_number = 0;
16218 		break;
16219 
16220 	default:
16221 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16222 		    "st_recov_ret with unhandled errstat %d\n", err);
16223 		/* FALLTHROUGH */
16224 	case COMMAND_DONE_ERROR:
16225 	case COMMAND_DONE_EACCES:
16226 		ST_DO_KSTATS(bp, kstat_waitq_exit);
16227 		ST_DO_ERRSTATS(un, st_transerrs);
16228 		error_number = EIO;
16229 		st_set_pe_flag(un);
16230 		break;
16231 
16232 	}
16233 	st_bioerror(bp, error_number);
16234 	st_done_and_mutex_exit(un, bp);
16235 }
16236 
16237 static void
16238 st_recover(void *arg)
16239 {
16240 	st_err_info *const errinfo = (st_err_info *)arg;
16241 	uchar_t com = errinfo->ei_failed_pkt.pkt_cdbp[0];
16242 	struct scsi_tape *un;
16243 	tapepos_t cur_pos;
16244 	int rval;
16245 	errstate status = COMMAND_DONE_ERROR;
16246 	recov_info *rcv;
16247 	buf_t *bp;
16248 
16249 
16250 	rcv = errinfo->ei_failed_pkt.pkt_private;
16251 	ASSERT(rcv->privatelen == sizeof (recov_info));
16252 	bp = rcv->cmd_bp;
16253 
16254 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16255 
16256 	ASSERT(un != NULL);
16257 
16258 	mutex_enter(ST_MUTEX);
16259 
16260 	ST_FUNC(ST_DEVINFO, st_recover);
16261 
16262 	ST_CDB(ST_DEVINFO, "Recovering command",
16263 	    (caddr_t)errinfo->ei_failed_pkt.pkt_cdbp);
16264 	ST_SENSE(ST_DEVINFO, "sense status for failed command",
16265 	    (caddr_t)&errinfo->ei_failing_status,
16266 	    sizeof (struct scsi_arq_status));
16267 	ST_POS(ST_DEVINFO, rcv->cmd_attrib->recov_pos_type == POS_STARTING ?
16268 	    "starting position for recovery command" :
16269 	    "expected position for recovery command",
16270 	    &errinfo->ei_expected_pos);
16271 
16272 	rval = st_test_path_to_device(un);
16273 
16274 	/*
16275 	 * If the drive responed to the TUR lets try and get it to sync
16276 	 * any data it have in the buffer.
16277 	 */
16278 	if (rval == 0 && rcv->cmd_attrib->chg_tape_data) {
16279 		(void) st_rcmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
16280 	}
16281 	switch (errinfo->ei_error_type) {
16282 	case ATTEMPT_RETRY:
16283 	case COMMAND_TIMEOUT:
16284 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16285 		    "st_recover called with COMMAND_TIMEOUT, TUR returned %d\n",
16286 		    rval);
16287 		if (rval != 0) {
16288 			/* ping failed, we're done. */
16289 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16290 			return;
16291 		}
16292 
16293 		/*
16294 		 * If a reset occured fall through.
16295 		 */
16296 		if (un->un_unit_attention_flags == 0) {
16297 			break;
16298 		}
16299 		/* FALLTHROUGH */
16300 	case DEVICE_RESET:
16301 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16302 		    "st_recover called with DEVICE_RESET, TUR returned %d\n",
16303 		    rval);
16304 		/*
16305 		 * For now if we can't talk to the device we are done.
16306 		 */
16307 		if (rval) {
16308 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16309 			return;
16310 		}
16311 
16312 		if ((un->un_rsvd_status & ST_LOST_RESERVE) &&
16313 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] != SCMD_RELEASE)) {
16314 			rval = st_reserve_release(un, ST_RESERVE,
16315 			    st_uscsi_rcmd);
16316 			if (rval == 0) {
16317 				un->un_rsvd_status |= ST_RESERVE;
16318 				un->un_rsvd_status &= ~(ST_RELEASE |
16319 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
16320 				    ST_INITIATED_RESET);
16321 			} else {
16322 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16323 				return;
16324 			}
16325 			rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16326 			if (rval) {
16327 				rval = st_gen_mode_select(un, st_uscsi_rcmd,
16328 				    un->un_mspl, sizeof (struct seq_mode));
16329 			}
16330 			if (rval) {
16331 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16332 				return;
16333 			}
16334 		}
16335 		break;
16336 	case PATH_FAILED:
16337 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16338 		    "st_recover called with PATH_FAILED, TUR returned %d\n",
16339 		    rval);
16340 		if (rval != 0) {
16341 			/* ping failed, we're done. */
16342 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16343 			return;
16344 		}
16345 		break;
16346 	case DEVICE_TAMPER:
16347 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16348 		    "st_recover called with DEVICE_TAMPER, TUR returned %d\n",
16349 		    rval);
16350 		/*
16351 		 * Check if the ASC/ASCQ says mode data has changed.
16352 		 */
16353 		if (errinfo->ei_failing_status.sts_sensedata.es_add_code ==
16354 		    0x2a &&
16355 		    errinfo->ei_failing_status.sts_sensedata.es_qual_code ==
16356 		    0x01) {
16357 			/*
16358 			 * See if mode sense changed.
16359 			 */
16360 			rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16361 			/*
16362 			 * if not cross your fingers and go for it.
16363 			 */
16364 			if (rval == 0) {
16365 				st_recov_ret(un, errinfo, COMMAND_DONE);
16366 				return;
16367 			}
16368 			/*
16369 			 * If so change it back.
16370 			 */
16371 			rval = st_gen_mode_select(un, st_uscsi_rcmd,
16372 			    un->un_mspl, sizeof (struct seq_mode));
16373 			if (rval) {
16374 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16375 			} else {
16376 				st_recov_ret(un, errinfo, COMMAND_DONE);
16377 			}
16378 			return;
16379 		}
16380 		/*
16381 		 * if we have a media id and its not bogus.
16382 		 * Check to see if it the same.
16383 		 */
16384 		if (un->un_media_id != NULL && un->un_media_id != bogusID) {
16385 			rval = st_get_media_identification(un, st_uscsi_rcmd);
16386 			if (rval == ESPIPE) {
16387 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16388 				return;
16389 			}
16390 		}
16391 		break;
16392 	default:
16393 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16394 		    "Unhandled error type 0x%x in st_recover()\n", com);
16395 	}
16396 
16397 	/*
16398 	 * if command is retriable retry it
16399 	 */
16400 	if (rcv->cmd_attrib->retriable) {
16401 		status = st_recover_reissue_pkt(un, &errinfo->ei_failed_pkt);
16402 
16403 	/*
16404 	 * if drive doesn't support read position we are done
16405 	 */
16406 	} else if (un->un_read_pos_type == NO_POS) {
16407 		status = COMMAND_DONE_ERROR;
16408 	/*
16409 	 * If this command results in a changed tape position,
16410 	 * lets see where we are.
16411 	 */
16412 	} else if (rcv->cmd_attrib->chg_tape_pos) {
16413 		/*
16414 		 * XXX May be a reason to choose a different type here.
16415 		 * Long format has file position information.
16416 		 * Short and Extended have information about whats
16417 		 * in the buffer. St's positioning assumes in the buffer
16418 		 * to be the same as on tape.
16419 		 */
16420 		rval = st_compare_expected_position(un, errinfo,
16421 		    rcv->cmd_attrib, &cur_pos);
16422 		if (rval == 0) {
16423 			status = COMMAND_DONE;
16424 		} else if (rval == EAGAIN) {
16425 			status = st_recover_reissue_pkt(un,
16426 			    &errinfo->ei_failed_pkt);
16427 		} else {
16428 			status = COMMAND_DONE_ERROR;
16429 		}
16430 	} else {
16431 		ASSERT(0);
16432 	}
16433 
16434 	st_recov_ret(un, errinfo, status);
16435 }
16436 
16437 static void
16438 st_recov_cb(struct scsi_pkt *pkt)
16439 {
16440 	struct scsi_tape *un;
16441 	struct buf *bp;
16442 	recov_info *rcv;
16443 	errstate action = COMMAND_DONE;
16444 	int timout = ST_TRAN_BUSY_TIMEOUT; /* short (default) timeout */
16445 
16446 	/*
16447 	 * Get the buf from the packet.
16448 	 */
16449 	rcv = pkt->pkt_private;
16450 	ASSERT(rcv->privatelen == sizeof (recov_info));
16451 	bp = rcv->cmd_bp;
16452 
16453 	/*
16454 	 * get the unit from the buf.
16455 	 */
16456 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16457 	ASSERT(un != NULL);
16458 
16459 	ST_FUNC(ST_DEVINFO, st_recov_cb);
16460 
16461 	mutex_enter(ST_MUTEX);
16462 
16463 	ASSERT(bp == un->un_recov_buf);
16464 
16465 
16466 	switch (pkt->pkt_reason) {
16467 	case CMD_CMPLT:
16468 		if (un->un_arq_enabled && pkt->pkt_state & STATE_ARQ_DONE) {
16469 			action = st_handle_autosense(un, bp, &rcv->pos);
16470 		} else if (*pkt->pkt_scbp & (STATUS_BUSY | STATUS_CHECK)) {
16471 			action = st_check_error(un, pkt);
16472 		}
16473 		break;
16474 	case CMD_TIMEOUT:
16475 		action = COMMAND_TIMEOUT;
16476 		break;
16477 	default:
16478 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16479 		    "pkt_reason not handled yet %s",
16480 		    scsi_rname(pkt->pkt_reason));
16481 		action = COMMAND_DONE_ERROR;
16482 	}
16483 
16484 	switch (action) {
16485 	case COMMAND_DONE:
16486 		break;
16487 
16488 	case COMMAND_DONE_EACCES:
16489 		bioerror(bp, EACCES);
16490 		break;
16491 
16492 	case COMMAND_TIMEOUT:
16493 	case COMMAND_DONE_ERROR:
16494 		bioerror(bp, EIO);
16495 		break;
16496 
16497 	case DEVICE_RESET:
16498 	case QUE_BUSY_COMMAND:
16499 		/* longish timeout */
16500 		timout = ST_STATUS_BUSY_TIMEOUT;
16501 		/* FALLTHRU */
16502 	case QUE_COMMAND:
16503 	case DEVICE_TAMPER:
16504 	case ATTEMPT_RETRY:
16505 		/*
16506 		 * let st_handle_intr_busy put this bp back on waitq and make
16507 		 * checks to see if it is ok to requeue the command.
16508 		 */
16509 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
16510 
16511 		/*
16512 		 * Save the throttle before setting up the timeout
16513 		 */
16514 		if (un->un_throttle) {
16515 			un->un_last_throttle = un->un_throttle;
16516 		}
16517 		mutex_exit(ST_MUTEX);
16518 		if (st_handle_intr_busy(un, bp, timout) == 0) {
16519 			return;		/* timeout is setup again */
16520 		}
16521 		mutex_enter(ST_MUTEX);
16522 		un->un_pos.pmode = invalid;
16523 		un->un_err_resid = bp->b_resid = bp->b_bcount;
16524 		st_bioerror(bp, EIO);
16525 		st_set_pe_flag(un);
16526 		break;
16527 
16528 	default:
16529 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16530 		    "Unhandled recovery state 0x%x\n", action);
16531 		un->un_pos.pmode = invalid;
16532 		un->un_err_resid = bp->b_resid = bp->b_bcount;
16533 		st_bioerror(bp, EIO);
16534 		st_set_pe_flag(un);
16535 		break;
16536 	}
16537 
16538 	st_done_and_mutex_exit(un, bp);
16539 }
16540 
16541 static int
16542 st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait)
16543 {
16544 	struct buf *bp;
16545 	int err;
16546 
16547 	ST_FUNC(ST_DEVINFO, st_rcmd);
16548 
16549 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16550 	    "st_rcmd(un = 0x%p, com = 0x%x, count = %"PRIx64", wait = %d)\n",
16551 	    (void *)un, com, count, wait);
16552 
16553 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16554 	ASSERT(mutex_owned(ST_MUTEX));
16555 
16556 #ifdef STDEBUG
16557 	if ((st_debug & 0x7)) {
16558 		st_debug_cmds(un, com, count, wait);
16559 	}
16560 #endif
16561 
16562 	while (un->un_recov_buf_busy)
16563 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
16564 	un->un_recov_buf_busy = 1;
16565 
16566 	bp = un->un_recov_buf;
16567 	bzero(bp, sizeof (buf_t));
16568 
16569 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
16570 
16571 	err = st_setup_cmd(un, bp, com, count);
16572 
16573 	un->un_recov_buf_busy = 0;
16574 
16575 	cv_signal(&un->un_recov_buf_cv);
16576 
16577 	return (err);
16578 }
16579 
16580 /* args used */
16581 static int
16582 st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
16583 {
16584 	int rval;
16585 	buf_t *bp;
16586 
16587 	ST_FUNC(ST_DEVINFO, st_uscsi_rcmd);
16588 	ASSERT(flag == FKIOCTL);
16589 
16590 	/*
16591 	 * Get buffer resources...
16592 	 */
16593 	while (un->un_recov_buf_busy)
16594 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
16595 	un->un_recov_buf_busy = 1;
16596 
16597 	bp = un->un_recov_buf;
16598 	bzero(bp, sizeof (buf_t));
16599 
16600 	bp->b_forw = (struct buf *)(uintptr_t)ucmd->uscsi_cdb[0];
16601 	bp->b_back = (struct buf *)ucmd;
16602 
16603 	mutex_exit(ST_MUTEX);
16604 	rval = scsi_uscsi_handle_cmd(un->un_dev, UIO_SYSSPACE, ucmd,
16605 	    st_strategy, bp, NULL);
16606 	mutex_enter(ST_MUTEX);
16607 
16608 	ucmd->uscsi_resid = bp->b_resid;
16609 
16610 	/*
16611 	 * Free resources
16612 	 */
16613 	un->un_recov_buf_busy = 0;
16614 	cv_signal(&un->un_recov_buf_cv);
16615 
16616 	return (rval);
16617 }
16618 
16619 /*
16620  * Add data to scsi_pkt to help know what to do if the command fails.
16621  */
16622 static void
16623 st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
16624     struct scsi_pkt *pkt)
16625 {
16626 	uint64_t count;
16627 	recov_info *rinfo = (recov_info *)pkt->pkt_private;
16628 
16629 	ST_FUNC(ST_DEVINFO, st_add_recovery_info_to_pkt);
16630 
16631 	ASSERT(rinfo->privatelen == sizeof (pkt_info) ||
16632 	    rinfo->privatelen == sizeof (recov_info));
16633 
16634 	SET_BP_PKT(bp, pkt);
16635 	rinfo->cmd_bp = bp;
16636 
16637 	if (rinfo->privatelen != sizeof (recov_info)) {
16638 		return;
16639 	}
16640 
16641 	rinfo->cmd_bp = bp;
16642 
16643 	rinfo->cmd_attrib = NULL;
16644 
16645 	/*
16646 	 * lookup the command attributes and add them to the recovery info.
16647 	 */
16648 	rinfo->cmd_attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
16649 
16650 	ASSERT(rinfo->cmd_attrib);
16651 
16652 	/*
16653 	 * For commands that there is no way to figure the expected position
16654 	 * once completed, we save the position the command was started from
16655 	 * so that if they fail we can position back and try again.
16656 	 * This has already been done in st_cmd() or st_iscsi_cmd().
16657 	 */
16658 	if (rinfo->cmd_attrib->recov_pos_type == POS_STARTING) {
16659 		/* save current position as the starting position. */
16660 		COPY_POS(&rinfo->pos, &un->un_pos);
16661 		un->un_running.pmode = invalid;
16662 		return;
16663 	}
16664 
16665 	/*
16666 	 * Don't want to update the running position for recovery.
16667 	 */
16668 	if (bp == un->un_recov_buf) {
16669 		rinfo->pos.pmode = un->un_running.pmode;
16670 		return;
16671 	}
16672 	/*
16673 	 * If running position is invalid copy the current position.
16674 	 * Running being set invalid means we are not in a read, write
16675 	 * or write filemark sequence.
16676 	 * We'll copy the current position and start from there.
16677 	 */
16678 	if (un->un_running.pmode == invalid) {
16679 		COPY_POS(&un->un_running, &un->un_pos);
16680 		COPY_POS(&rinfo->pos, &un->un_running);
16681 	} else {
16682 		COPY_POS(&rinfo->pos, &un->un_running);
16683 		if (rinfo->pos.pmode == legacy) {
16684 			/*
16685 			 * Always should be more logical blocks then
16686 			 * data blocks and files marks.
16687 			 */
16688 			ASSERT((rinfo->pos.blkno >= 0) ?
16689 			    rinfo->pos.lgclblkno >=
16690 			    (rinfo->pos.blkno + rinfo->pos.fileno) : 1);
16691 		}
16692 	}
16693 
16694 	/*
16695 	 * If the command is not expected to change the drive position
16696 	 * then the running position should be the expected position.
16697 	 */
16698 	if (rinfo->cmd_attrib->chg_tape_pos == 0) {
16699 		ASSERT(rinfo->cmd_attrib->chg_tape_direction == DIR_NONE);
16700 		return;
16701 	}
16702 
16703 	if (rinfo->cmd_attrib->explicit) {
16704 		ASSERT(rinfo->pos.pmode != invalid);
16705 		ASSERT(rinfo->cmd_attrib->get_cnt);
16706 		count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
16707 		/*
16708 		 * This is a user generated CDB.
16709 		 */
16710 		if (bp == un->un_sbufp) {
16711 			uint64_t lbn;
16712 
16713 			lbn = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
16714 
16715 			/*
16716 			 * See if this CDB will generate a locate or change
16717 			 * partition.
16718 			 */
16719 			if ((lbn != un->un_running.lgclblkno) ||
16720 			    (pkt->pkt_cdbp[3] != un->un_running.partition)) {
16721 				rinfo->pos.partition = pkt->pkt_cdbp[3];
16722 				rinfo->pos.pmode = logical;
16723 				rinfo->pos.lgclblkno = lbn;
16724 				un->un_running.partition = pkt->pkt_cdbp[3];
16725 				un->un_running.pmode = logical;
16726 				un->un_running.lgclblkno = lbn;
16727 			}
16728 		} else {
16729 			uint64_t lbn = un->un_running.lgclblkno;
16730 
16731 			pkt->pkt_cdbp[3]  = (uchar_t)un->un_running.partition;
16732 
16733 			pkt->pkt_cdbp[4]  = (uchar_t)(lbn >> 56);
16734 			pkt->pkt_cdbp[5]  = (uchar_t)(lbn >> 48);
16735 			pkt->pkt_cdbp[6]  = (uchar_t)(lbn >> 40);
16736 			pkt->pkt_cdbp[7]  = (uchar_t)(lbn >> 32);
16737 			pkt->pkt_cdbp[8]  = (uchar_t)(lbn >> 24);
16738 			pkt->pkt_cdbp[9]  = (uchar_t)(lbn >> 16);
16739 			pkt->pkt_cdbp[10] = (uchar_t)(lbn >> 8);
16740 			pkt->pkt_cdbp[11] = (uchar_t)(lbn);
16741 		}
16742 		rinfo->pos.lgclblkno += count;
16743 		rinfo->pos.blkno += count;
16744 		un->un_running.lgclblkno += count;
16745 		return;
16746 	}
16747 
16748 	if (rinfo->cmd_attrib->chg_tape_pos) {
16749 
16750 		/* should not have got an invalid position from running. */
16751 		if (un->un_mediastate == MTIO_INSERTED) {
16752 			ASSERT(rinfo->pos.pmode != invalid);
16753 		}
16754 
16755 		/* should have either a get count or or get lba function */
16756 		ASSERT(rinfo->cmd_attrib->get_cnt != NULL ||
16757 		    rinfo->cmd_attrib->get_lba != NULL);
16758 
16759 		/* only explicit commands have both and they're handled above */
16760 		ASSERT(!(rinfo->cmd_attrib->get_cnt != NULL &&
16761 		    rinfo->cmd_attrib->get_lba != NULL));
16762 
16763 		/* if it has a get count function */
16764 		if (rinfo->cmd_attrib->get_cnt != NULL) {
16765 			count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
16766 			if (count == 0) {
16767 				return;
16768 			}
16769 			/*
16770 			 * Changes position but doesn't transfer data.
16771 			 * i.e. rewind, write_file_mark and load.
16772 			 */
16773 			if (rinfo->cmd_attrib->transfers_data == TRAN_NONE) {
16774 				switch (rinfo->cmd_attrib->chg_tape_direction) {
16775 				case DIR_NONE: /* Erase */
16776 					ASSERT(rinfo->cmd_attrib->cmd ==
16777 					    SCMD_ERASE);
16778 					break;
16779 				case DIR_FORW: /* write_file_mark */
16780 					rinfo->pos.fileno += count;
16781 					rinfo->pos.lgclblkno += count;
16782 					rinfo->pos.blkno = 0;
16783 					un->un_running.fileno += count;
16784 					un->un_running.lgclblkno += count;
16785 					un->un_running.blkno = 0;
16786 					break;
16787 				case DIR_REVC: /* rewind */
16788 					rinfo->pos.fileno = 0;
16789 					rinfo->pos.lgclblkno = 0;
16790 					rinfo->pos.blkno = 0;
16791 					rinfo->pos.eof = ST_NO_EOF;
16792 					rinfo->pos.pmode = legacy;
16793 					un->un_running.fileno = 0;
16794 					un->un_running.lgclblkno = 0;
16795 					un->un_running.blkno = 0;
16796 					un->un_running.eof = ST_NO_EOF;
16797 					if (un->un_running.pmode != legacy)
16798 						un->un_running.pmode = legacy;
16799 					break;
16800 				case DIR_EITH: /* Load unload */
16801 					ASSERT(rinfo->cmd_attrib->cmd ==
16802 					    SCMD_LOAD);
16803 					switch (count & (LD_LOAD | LD_RETEN |
16804 					    LD_RETEN | LD_HOLD)) {
16805 					case LD_UNLOAD:
16806 					case LD_RETEN:
16807 					case LD_HOLD:
16808 					case LD_LOAD | LD_HOLD:
16809 					case LD_EOT | LD_HOLD:
16810 					case LD_RETEN | LD_HOLD:
16811 						rinfo->pos.pmode = invalid;
16812 						un->un_running.pmode = invalid;
16813 						break;
16814 					case LD_EOT:
16815 					case LD_LOAD | LD_EOT:
16816 						rinfo->pos.eof = ST_EOT;
16817 						rinfo->pos.pmode = invalid;
16818 						un->un_running.eof = ST_EOT;
16819 						un->un_running.pmode = invalid;
16820 						break;
16821 					case LD_LOAD:
16822 					case LD_RETEN | LD_LOAD:
16823 						rinfo->pos.fileno = 0;
16824 						rinfo->pos.lgclblkno = 0;
16825 						rinfo->pos.blkno = 0;
16826 						rinfo->pos.eof = ST_NO_EOF;
16827 						rinfo->pos.pmode = legacy;
16828 						un->un_running.fileno = 0;
16829 						un->un_running.lgclblkno = 0;
16830 						un->un_running.blkno = 0;
16831 						un->un_running.eof = ST_NO_EOF;
16832 						break;
16833 					default:
16834 						ASSERT(0);
16835 					}
16836 					break;
16837 				default:
16838 					ASSERT(0);
16839 					break;
16840 				}
16841 			} else {
16842 				/*
16843 				 * Changes position and does transfer data.
16844 				 * i.e. read or write.
16845 				 */
16846 				switch (rinfo->cmd_attrib->chg_tape_direction) {
16847 				case DIR_FORW:
16848 					rinfo->pos.lgclblkno += count;
16849 					rinfo->pos.blkno += count;
16850 					un->un_running.lgclblkno += count;
16851 					un->un_running.blkno += count;
16852 					break;
16853 				case DIR_REVC:
16854 					rinfo->pos.lgclblkno -= count;
16855 					rinfo->pos.blkno -= count;
16856 					un->un_running.lgclblkno -= count;
16857 					un->un_running.blkno -= count;
16858 					break;
16859 				default:
16860 					ASSERT(0);
16861 					break;
16862 				}
16863 			}
16864 		} else if (rinfo->cmd_attrib->get_lba != NULL) {
16865 			/* Have a get LBA fuction. i.e. Locate */
16866 			ASSERT(rinfo->cmd_attrib->chg_tape_direction ==
16867 			    DIR_EITH);
16868 			count = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
16869 			un->un_running.lgclblkno = count;
16870 			un->un_running.blkno = 0;
16871 			un->un_running.fileno = 0;
16872 			un->un_running.pmode = logical;
16873 			rinfo->pos.lgclblkno = count;
16874 			rinfo->pos.pmode = invalid;
16875 		} else {
16876 			ASSERT(0);
16877 		}
16878 		return;
16879 	}
16880 
16881 	ST_CDB(ST_DEVINFO, "Unhanded CDB for position prediction",
16882 	    (char *)pkt->pkt_cdbp);
16883 
16884 }
16885 
16886 static int
16887 st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf)
16888 {
16889 	struct seq_mode *current;
16890 	int rval;
16891 	int i;
16892 	caddr_t this;
16893 	caddr_t that;
16894 
16895 	ST_FUNC(ST_DEVINFO, st_check_mode_for_change);
16896 
16897 	/* recovery called with mode tamper before mode selection */
16898 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
16899 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16900 		    "Mode Select not done yet");
16901 		return (0);
16902 	}
16903 
16904 	current = kmem_zalloc(sizeof (struct seq_mode), KM_SLEEP);
16905 
16906 	rval = st_gen_mode_sense(un, ubf, un->un_comp_page, current,
16907 	    sizeof (struct seq_mode));
16908 	if (rval != 0) {
16909 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16910 		    "Mode Sense for mode verification failed");
16911 		kmem_free(current, sizeof (struct seq_mode));
16912 		return (rval);
16913 	}
16914 
16915 	this = (caddr_t)current;
16916 	that = (caddr_t)un->un_mspl;
16917 
16918 	rval = bcmp(this, that, sizeof (struct seq_mode));
16919 	if (rval == 0) {
16920 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16921 		    "Found no changes in mode data");
16922 	}
16923 #ifdef STDEBUG
16924 	else {
16925 		for (i = 1; i < sizeof (struct seq_mode); i++) {
16926 			if (this[i] != that[i]) {
16927 				ST_RECOV(ST_DEVINFO, st_label, CE_CONT,
16928 				    "sense data changed at byte %d was "
16929 				    "0x%x now 0x%x", i,
16930 				    (uchar_t)that[i], (uchar_t)this[i]);
16931 			}
16932 		}
16933 	}
16934 #endif
16935 	kmem_free(current, sizeof (struct seq_mode));
16936 
16937 	return (rval);
16938 }
16939 
16940 static int
16941 st_test_path_to_device(struct scsi_tape *un)
16942 {
16943 	int rval;
16944 
16945 	ST_FUNC(ST_DEVINFO, st_test_path_to_device);
16946 
16947 	/*
16948 	 * XXX Newer drives may not RESEVATION CONFLICT a TUR.
16949 	 */
16950 	do {
16951 		rval = st_rcmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
16952 	} while (rval == DEVICE_RESET);
16953 
16954 	return (rval);
16955 }
16956 
16957 /*
16958  * Does read position using recov_buf and doesn't update un_pos.
16959  * Does what ever kind of read position you want.
16960  */
16961 static int
16962 st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
16963     read_pos_data_t *raw)
16964 {
16965 	int rval;
16966 	struct uscsi_cmd cmd;
16967 	char cdb[CDB_GROUP1];
16968 
16969 	ST_FUNC(ST_DEVINFO, st_recovery_read_pos);
16970 	bzero(&cmd, sizeof (cmd));
16971 
16972 	cdb[0] = SCMD_READ_POSITION;
16973 	cdb[1] = type;
16974 	cdb[2] = 0;
16975 	cdb[3] = 0;
16976 	cdb[4] = 0;
16977 	cdb[5] = 0;
16978 	cdb[6] = 0;
16979 	cdb[7] = 0;
16980 	cdb[8] =  (type == EXT_POS) ? 28 : 0;
16981 	cdb[9] = 0;
16982 
16983 	cmd.uscsi_flags = USCSI_READ;
16984 	cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
16985 	cmd.uscsi_cdb = cdb;
16986 	cmd.uscsi_cdblen = sizeof (cdb);
16987 	cmd.uscsi_bufaddr = (caddr_t)raw;
16988 	switch (type) {
16989 	case SHORT_POS:
16990 		cmd.uscsi_buflen = sizeof (tape_position_t);
16991 		break;
16992 	case LONG_POS:
16993 		cmd.uscsi_buflen = sizeof (tape_position_long_t);
16994 		break;
16995 	case EXT_POS:
16996 		cmd.uscsi_buflen = sizeof (tape_position_ext_t);
16997 		break;
16998 	default:
16999 		ASSERT(0);
17000 	}
17001 
17002 	rval = st_uscsi_rcmd(un, &cmd, FKIOCTL);
17003 	if (cmd.uscsi_status) {
17004 		rval = EIO;
17005 	}
17006 	return (rval);
17007 }
17008 
17009 static int
17010 st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
17011     read_pos_data_t *raw)
17012 {
17013 	int rval;
17014 	read_p_types type = un->un_read_pos_type;
17015 
17016 	ST_FUNC(ST_DEVINFO, st_recovery_get_position);
17017 
17018 	rval = st_recovery_read_pos(un, type, raw);
17019 	if (rval != 0) {
17020 		return (rval);
17021 	}
17022 	rval = st_interpret_read_pos(un, read, type, sizeof (read_pos_data_t),
17023 	    (caddr_t)raw, 1);
17024 
17025 	return (rval);
17026 }
17027 
17028 /*
17029  * based on the command do we retry, continue or give up?
17030  * possable return values?
17031  *	zero do nothing looks fine.
17032  *	EAGAIN retry.
17033  *	EIO failed makes no sense.
17034  */
17035 static int
17036 st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
17037     cmd_attribute const * cmd_att, tapepos_t *read)
17038 {
17039 	int rval;
17040 	read_pos_data_t *readp_datap;
17041 
17042 	ST_FUNC(ST_DEVINFO, st_compare_expected_position);
17043 
17044 	ASSERT(un != NULL);
17045 	ASSERT(ei != NULL);
17046 	ASSERT(read != NULL);
17047 	ASSERT(cmd_att->chg_tape_pos);
17048 
17049 	COPY_POS(read, &ei->ei_expected_pos);
17050 
17051 	readp_datap = kmem_zalloc(sizeof (read_pos_data_t), KM_SLEEP);
17052 
17053 	rval = st_recovery_get_position(un, read, readp_datap);
17054 
17055 	kmem_free(readp_datap, sizeof (read_pos_data_t));
17056 
17057 	if (rval != 0) {
17058 		return (EIO);
17059 	}
17060 
17061 	ST_POS(ST_DEVINFO, "st_compare_expected_position", read);
17062 
17063 	if ((read->pmode == invalid) ||
17064 	    (ei->ei_expected_pos.pmode == invalid)) {
17065 		return (EIO);
17066 	}
17067 
17068 	/*
17069 	 * Command that changes tape position and have an expected position
17070 	 * if it were to chave completed sucessfully.
17071 	 */
17072 	if (cmd_att->recov_pos_type == POS_EXPECTED) {
17073 		uint32_t count;
17074 		int64_t difference;
17075 
17076 		/* At expected? */
17077 		if (read->lgclblkno == ei->ei_expected_pos.lgclblkno) {
17078 			ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17079 			    "Found drive to be at expected position\n");
17080 			return (0); /* Good */
17081 		}
17082 		ASSERT(cmd_att->get_cnt);
17083 		count = cmd_att->get_cnt(ei->ei_failed_pkt.pkt_cdbp);
17084 
17085 		ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17086 		    "Got count from CDB and it was %d\n", count);
17087 		if (cmd_att->chg_tape_direction == DIR_FORW) {
17088 			difference =
17089 			    ei->ei_expected_pos.lgclblkno - read->lgclblkno;
17090 			ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17091 			    "difference between expected and actual is %"
17092 			    PRId64"\n", difference);
17093 			if (count == difference) {
17094 				ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17095 				    "Found failed FORW command, retrying\n");
17096 				return (EAGAIN);
17097 			}
17098 
17099 			/*
17100 			 * If rewound or somewhere between the starting position
17101 			 * and the expected position (partial read or write).
17102 			 * Locate to the starting position and try the whole
17103 			 * thing over again.
17104 			 */
17105 			if ((read->lgclblkno == 0) ||
17106 			    ((difference > 0) && (difference < count))) {
17107 				rval = st_logical_block_locate(un,
17108 				    st_uscsi_rcmd, read,
17109 				    ei->ei_expected_pos.lgclblkno - count,
17110 				    ei->ei_expected_pos.partition);
17111 				if (rval == 0) {
17112 					ST_RECOV(ST_DEVINFO, st_label,
17113 					    SCSI_DEBUG, "reestablished FORW"
17114 					    " command retrying\n");
17115 					return (EAGAIN);
17116 				}
17117 			/* This handles flushed read ahead on the drive */
17118 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17119 			    (difference < 0)) {
17120 				rval = st_logical_block_locate(un,
17121 				    st_uscsi_rcmd, read,
17122 				    ei->ei_expected_pos.lgclblkno - count,
17123 				    ei->ei_expected_pos.partition);
17124 				if (rval == 0) {
17125 					ST_RECOV(ST_DEVINFO, st_label,
17126 					    SCSI_DEBUG, "reestablished FORW"
17127 					    " read command retrying\n");
17128 					return (EAGAIN);
17129 				}
17130 			/*
17131 			 * XXX swag seeing difference of 2 on write filemark.
17132 			 * If the space to the starting position works on a
17133 			 * write that means the previous write made it to tape.
17134 			 * If not we lost data and have to give up.
17135 			 *
17136 			 * The plot thickens. Now I am attempting to cover a
17137 			 * count of 1 and a differance of 2 on a write.
17138 			 */
17139 			} else if (difference > count) {
17140 				rval = st_logical_block_locate(un,
17141 				    st_uscsi_rcmd, read,
17142 				    ei->ei_expected_pos.lgclblkno - count,
17143 				    ei->ei_expected_pos.partition);
17144 				if (rval == 0) {
17145 					ST_RECOV(ST_DEVINFO, st_label,
17146 					    SCSI_DEBUG, "reestablished FORW"
17147 					    " write command retrying\n");
17148 					return (EAGAIN);
17149 				}
17150 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17151 				    "Seek to block %"PRId64" returned %d\n",
17152 				    ei->ei_expected_pos.lgclblkno - count,
17153 				    rval);
17154 			} else {
17155 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17156 				    "Not expected transfers_data = %d "
17157 				    "difference = %"PRId64,
17158 				    cmd_att->transfers_data, difference);
17159 			}
17160 
17161 			return (EIO);
17162 
17163 		} else if (cmd_att->chg_tape_direction == DIR_REVC) {
17164 			/* Don't think we can write backwards */
17165 			ASSERT(cmd_att->transfers_data != TRAN_WRTE);
17166 			difference =
17167 			    read->lgclblkno - ei->ei_expected_pos.lgclblkno;
17168 			ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17169 			    "difference between expected and actual is %"
17170 			    PRId64"\n", difference);
17171 			if (count == difference) {
17172 				ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17173 				    "Found failed REVC command, retrying\n");
17174 				return (EAGAIN);
17175 			}
17176 			if ((read->lgclblkno == 0) ||
17177 			    ((difference > 0) && (difference < count))) {
17178 				rval = st_logical_block_locate(un,
17179 				    st_uscsi_rcmd, read,
17180 				    ei->ei_expected_pos.lgclblkno + count,
17181 				    ei->ei_expected_pos.partition);
17182 				if (rval == 0) {
17183 					ST_RECOV(ST_DEVINFO, st_label,
17184 					    SCSI_DEBUG, "reestablished REVC"
17185 					    " command retrying\n");
17186 					return (EAGAIN);
17187 				}
17188 			/* This handles read ahead in reverse direction */
17189 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17190 			    (difference < 0)) {
17191 				rval = st_logical_block_locate(un,
17192 				    st_uscsi_rcmd, read,
17193 				    ei->ei_expected_pos.lgclblkno - count,
17194 				    ei->ei_expected_pos.partition);
17195 				if (rval == 0) {
17196 					ST_RECOV(ST_DEVINFO, st_label,
17197 					    SCSI_DEBUG, "reestablished REVC"
17198 					    " read command retrying\n");
17199 					return (EAGAIN);
17200 				}
17201 			} else {
17202 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17203 				    "Not expected transfers_data = %d "
17204 				    "difference = %"PRId64,
17205 				    cmd_att->transfers_data, difference);
17206 			}
17207 			return (EIO);
17208 
17209 		} else {
17210 			/*
17211 			 * Commands that change tape position either
17212 			 * direction or don't change position should not
17213 			 * get here.
17214 			 */
17215 			ASSERT(0);
17216 		}
17217 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17218 		    "Didn't find a recoverable position, Failing\n");
17219 
17220 	/*
17221 	 * Command that changes tape position and can only be recovered
17222 	 * by going back to the point of origin and retrying.
17223 	 *
17224 	 * Example SCMD_SPACE.
17225 	 */
17226 	} else if (cmd_att->recov_pos_type == POS_STARTING) {
17227 		/*
17228 		 * This type of command stores the starting position.
17229 		 * If the read position is the starting position,
17230 		 * reissue the command.
17231 		 */
17232 		if (ei->ei_expected_pos.lgclblkno == read->lgclblkno) {
17233 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17234 			    "Found Space command at starting position, "
17235 			    "Reissuing\n");
17236 			return (EAGAIN);
17237 		}
17238 		/*
17239 		 * Not in the position that the command was originally issued,
17240 		 * Attempt to locate to that position.
17241 		 */
17242 		rval = st_logical_block_locate(un, st_uscsi_rcmd, read,
17243 		    ei->ei_expected_pos.lgclblkno,
17244 		    ei->ei_expected_pos.partition);
17245 		if (rval) {
17246 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17247 			    "Found Space at an unexpected position and locate "
17248 			    "back to starting position failed\n");
17249 			return (EIO);
17250 		}
17251 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17252 		    "Found Space at an unexpected position and locate "
17253 		    "back to starting position worked, Reissuing\n");
17254 		return (EAGAIN);
17255 	}
17256 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17257 	    "Unhandled attribute/expected position", &ei->ei_expected_pos);
17258 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17259 	    "Read position above did not make sense", read);
17260 	ASSERT(0);
17261 	return (EIO);
17262 }
17263 
17264 static errstate
17265 st_recover_reissue_pkt(struct scsi_tape *un, struct scsi_pkt *oldpkt)
17266 {
17267 	buf_t *bp;
17268 	buf_t *pkt_bp;
17269 	struct scsi_pkt *newpkt;
17270 	cmd_attribute const *attrib;
17271 	recov_info *rcv = oldpkt->pkt_private;
17272 	uint_t cdblen;
17273 	int rval;
17274 	int stat_size =
17275 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
17276 
17277 	ST_FUNC(ST_DEVINFO, st_recover_reissue_pkt);
17278 
17279 	bp = rcv->cmd_bp;
17280 
17281 	if (rcv->privatelen == sizeof (recov_info)) {
17282 		attrib = rcv->cmd_attrib;
17283 	} else {
17284 		attrib = st_lookup_cmd_attribute(oldpkt->pkt_cdbp[0]);
17285 	}
17286 
17287 	/*
17288 	 * Some non-uscsi commands use the b_bcount for values that
17289 	 * have nothing to do with how much data is transfered.
17290 	 * In those cases we need to hide the buf_t from scsi_init_pkt().
17291 	 */
17292 	if ((BP_UCMD(bp)) && (bp->b_bcount)) {
17293 		pkt_bp = bp;
17294 	} else if (attrib->transfers_data == TRAN_NONE) {
17295 		pkt_bp = NULL;
17296 	} else {
17297 		pkt_bp = bp;
17298 	}
17299 	/*
17300 	 * if this is a queued command make sure it the only one in the
17301 	 * run queue.
17302 	 */
17303 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
17304 		ASSERT(un->un_runqf == un->un_runql);
17305 		ASSERT(un->un_runqf == bp);
17306 	}
17307 
17308 	cdblen = scsi_cdb_size[CDB_GROUPID(oldpkt->pkt_cdbp[0])];
17309 
17310 	newpkt = scsi_init_pkt(ROUTE, NULL, pkt_bp, cdblen,
17311 	    stat_size, rcv->privatelen, 0, NULL_FUNC, NULL);
17312 	if (newpkt == NULL) {
17313 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17314 		    "Reissue pkt scsi_init_pkt() failure\n");
17315 		return (COMMAND_DONE_ERROR);
17316 	}
17317 
17318 	ASSERT(newpkt->pkt_resid == 0);
17319 	bp->b_flags &= ~(B_DONE);
17320 	bp->b_resid = 0;
17321 	st_bioerror(bp, 0);
17322 
17323 	bcopy(oldpkt->pkt_private, newpkt->pkt_private, rcv->privatelen);
17324 
17325 	newpkt->pkt_comp = oldpkt->pkt_comp;
17326 	newpkt->pkt_time = oldpkt->pkt_time;
17327 
17328 	bzero(newpkt->pkt_scbp, stat_size);
17329 	bcopy(oldpkt->pkt_cdbp, newpkt->pkt_cdbp, cdblen);
17330 
17331 	newpkt->pkt_state = 0;
17332 	newpkt->pkt_statistics = 0;
17333 
17334 	oldpkt = BP_PKT(bp);
17335 
17336 	SET_BP_PKT(bp, newpkt);
17337 
17338 	scsi_destroy_pkt(oldpkt);
17339 
17340 	rval = st_transport(un, newpkt);
17341 	if (rval == TRAN_ACCEPT) {
17342 		return (JUST_RETURN);
17343 	}
17344 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17345 	    "Reissue pkt st_transport(0x%x) failure\n", rval);
17346 	if (rval != TRAN_BUSY) {
17347 		return (COMMAND_DONE_ERROR);
17348 	}
17349 	mutex_exit(ST_MUTEX);
17350 	rval = st_handle_start_busy(un, bp, ST_TRAN_BUSY_TIMEOUT, 0);
17351 	mutex_enter(ST_MUTEX);
17352 	if (rval) {
17353 		return (COMMAND_DONE_ERROR);
17354 	}
17355 
17356 	return (JUST_RETURN);
17357 }
17358 
17359 static int
17360 st_transport(struct scsi_tape *un, struct scsi_pkt *pkt)
17361 {
17362 	int status;
17363 
17364 	ST_FUNC(ST_DEVINFO, st_transport);
17365 
17366 	ST_CDB(ST_DEVINFO, "transport CDB", (caddr_t)pkt->pkt_cdbp);
17367 
17368 	mutex_exit(ST_MUTEX);
17369 
17370 	status = scsi_transport(pkt);
17371 
17372 	mutex_enter(ST_MUTEX);
17373 
17374 	return (status);
17375 }
17376 
17377 /*
17378  * Removed the buf_t bp from the queue referenced to by head and tail.
17379  * Returns the buf_t pointer if it is found in the queue.
17380  * Returns NULL if it is not found.
17381  */
17382 static buf_t *
17383 st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp)
17384 {
17385 	buf_t *runqbp;
17386 	buf_t *prevbp = NULL;
17387 
17388 	for (runqbp = *head; runqbp != 0; runqbp = runqbp->av_forw) {
17389 		if (runqbp == bp) {
17390 			/* found it, is it at the head? */
17391 			if (runqbp == *head) {
17392 				*head = bp->av_forw;
17393 			} else {
17394 				prevbp->av_forw = bp->av_forw;
17395 			}
17396 			if (*tail == bp) {
17397 				*tail = prevbp;
17398 			}
17399 			bp->av_forw = NULL;
17400 			return (bp); /* found and removed */
17401 		}
17402 		prevbp = runqbp;
17403 	}
17404 	return (NULL);
17405 }
17406 
17407 /*
17408  * Adds a buf_t to the queue pointed to by head and tail.
17409  * Adds it either to the head end or the tail end based on which
17410  * the passed variable end (head or tail) points at.
17411  */
17412 static void
17413 st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp)
17414 {
17415 
17416 	bp->av_forw = NULL;
17417 	if (*head) {
17418 		/* Queue is not empty */
17419 		if (end == *head) {
17420 			/* Add at front of queue */
17421 			bp->av_forw = *head;
17422 			*head = bp;
17423 		} else if (end == *tail) {
17424 			/* Add at end of queue */
17425 			(*tail)->av_forw = bp;
17426 			*tail = bp;
17427 		} else {
17428 			ASSERT(0);
17429 		}
17430 	} else {
17431 		/* Queue is empty */
17432 		*head = bp;
17433 		*tail = bp;
17434 	}
17435 }
17436 
17437 
17438 static uint64_t
17439 st_get_cdb_g0_rw_count(uchar_t *cdb)
17440 {
17441 	uint64_t count;
17442 
17443 	if ((cdb[1]) & 1) {
17444 		/* fixed block mode, the count is the number of blocks */
17445 		count =
17446 		    cdb[2] << 16 |
17447 		    cdb[3] << 8 |
17448 		    cdb[4];
17449 	} else {
17450 		/* variable block mode, the count is the block size */
17451 		count = 1;
17452 	}
17453 	return (count);
17454 }
17455 
17456 static uint64_t
17457 st_get_cdb_g0_sign_count(uchar_t *cdb)
17458 {
17459 	uint64_t count;
17460 
17461 	count =
17462 	    cdb[2] << 16 |
17463 	    cdb[3] << 8 |
17464 	    cdb[4];
17465 	/*
17466 	 * If the sign bit of the 3 byte value is set, extended it.
17467 	 */
17468 	if (count & 0x800000) {
17469 		count |= 0xffffffffff000000;
17470 	}
17471 	return (count);
17472 }
17473 
17474 static uint64_t
17475 st_get_cdb_g0_count(uchar_t *cdb)
17476 {
17477 	uint64_t count;
17478 
17479 	count =
17480 	    cdb[2] << 16 |
17481 	    cdb[3] << 8 |
17482 	    cdb[4];
17483 	return (count);
17484 }
17485 
17486 static uint64_t
17487 st_get_cdb_g5_rw_cnt(uchar_t *cdb)
17488 {
17489 	uint64_t count;
17490 
17491 	if ((cdb[1]) & 1) {
17492 		/* fixed block mode */
17493 		count =
17494 		    cdb[12] << 16 |
17495 		    cdb[13] << 8 |
17496 		    cdb[14];
17497 	} else {
17498 		/* variable block mode */
17499 		count = 1;
17500 	}
17501 	return (count);
17502 }
17503 
17504 static uint64_t
17505 st_get_no_count(uchar_t *cdb)
17506 {
17507 	ASSERT(cdb[0] == SCMD_REWIND);
17508 	return ((uint64_t)cdb[0]);
17509 }
17510 
17511 static uint64_t
17512 st_get_load_options(uchar_t *cdb)
17513 {
17514 	return ((uint64_t)(cdb[4] | (LD_HOLD << 1)));
17515 }
17516 
17517 static uint64_t
17518 st_get_erase_options(uchar_t *cdb)
17519 {
17520 	return (cdb[1] | (cdb[0] << 8));
17521 }
17522 
17523 static uint64_t
17524 st_get_cdb_g1_lba(uchar_t *cdb)
17525 {
17526 	uint64_t lba;
17527 
17528 	lba =
17529 	    cdb[3] << 24 |
17530 	    cdb[4] << 16 |
17531 	    cdb[5] << 8 |
17532 	    cdb[6];
17533 	return (lba);
17534 }
17535 
17536 static uint64_t
17537 st_get_cdb_g5_count(uchar_t *cdb)
17538 {
17539 	uint64_t count =
17540 	    cdb[12] << 16 |
17541 	    cdb[13] << 8 |
17542 	    cdb[14];
17543 
17544 	return (count);
17545 }
17546 
17547 static uint64_t
17548 st_get_cdb_g4g5_cnt(uchar_t *cdb)
17549 {
17550 	uint64_t lba;
17551 
17552 	lba =
17553 	    (uint64_t)cdb[4] << 56 |
17554 	    (uint64_t)cdb[5] << 48 |
17555 	    (uint64_t)cdb[6] << 40 |
17556 	    (uint64_t)cdb[7] << 32 |
17557 	    (uint64_t)cdb[8] << 24 |
17558 	    (uint64_t)cdb[9] << 16 |
17559 	    (uint64_t)cdb[10] << 8 |
17560 	    (uint64_t)cdb[11];
17561 	return (lba);
17562 }
17563 
17564 static const cmd_attribute cmd_attributes[] = {
17565 	{ SCMD_TEST_UNIT_READY,
17566 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17567 	    0, 0, 0 },
17568 	{ SCMD_REWIND,
17569 	    1, 1, 1, 0, 0, DIR_REVC, TRAN_NONE, POS_EXPECTED,
17570 	    0, 0, 0, st_get_no_count },
17571 	{ SCMD_REQUEST_SENSE,
17572 	    0, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17573 	    0, 0, 0 },
17574 	{ SCMD_READ_BLKLIM,
17575 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17576 	    0, 0, 0 },
17577 	{ SCMD_READ,
17578 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_READ, POS_EXPECTED,
17579 	    0, 0, 0, st_get_cdb_g0_rw_count },
17580 	{ SCMD_WRITE,
17581 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
17582 	    0, 0, 0, st_get_cdb_g0_rw_count },
17583 	{ SCMD_READ_G4,
17584 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_READ, POS_EXPECTED,
17585 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17586 	{ SCMD_WRITE_G4,
17587 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
17588 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17589 	{ SCMD_READ_REVERSE,
17590 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
17591 	    0, 0, 0, st_get_cdb_g0_rw_count },
17592 	{ SCMD_READ_REVERSE_G4,
17593 	    1, 0, 1, 1, 1, DIR_REVC, TRAN_READ, POS_EXPECTED,
17594 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17595 	{ SCMD_WRITE_FILE_MARK,
17596 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17597 	    0, 0, 0, st_get_cdb_g0_count },
17598 	{ SCMD_WRITE_FILE_MARK_G4,
17599 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17600 	    0, 0, 0, st_get_cdb_g5_count, st_get_cdb_g4g5_cnt },
17601 	{ SCMD_SPACE,
17602 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
17603 	    0, 0, 0, st_get_cdb_g0_sign_count },
17604 	{ SCMD_SPACE_G4,
17605 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
17606 	    0, 0, 0, st_get_cdb_g4g5_cnt },
17607 	{ SCMD_INQUIRY,
17608 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17609 	    0, 0, 0 },
17610 	{ SCMD_VERIFY_G0,
17611 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17612 	    0, 0, 0, st_get_cdb_g0_rw_count },
17613 	{ SCMD_VERIFY_G4,
17614 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17615 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17616 	{ SCMD_RECOVER_BUF,
17617 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
17618 	    0, 0, 0 },
17619 	{ SCMD_MODE_SELECT,
17620 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17621 	    0, 0, 0 },
17622 	{ SCMD_RESERVE,
17623 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17624 	    0, 0, 0 },
17625 	{ SCMD_RELEASE,
17626 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17627 	    0, 0, 0 },
17628 	{ SCMD_ERASE,
17629 	    1, 0, 1, 1, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17630 	    0, 0, 0, st_get_erase_options },
17631 	{ SCMD_MODE_SENSE,
17632 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17633 	    0, 0, 0 },
17634 	{ SCMD_LOAD,
17635 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
17636 	    0, 0, 0, st_get_load_options },
17637 	{ SCMD_GDIAG,
17638 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17639 	    1, 0, 0 },
17640 	{ SCMD_SDIAG,
17641 	    1, 0, 1, 1, 0, DIR_EITH, TRAN_WRTE, POS_EXPECTED,
17642 	    1, 0, 0 },
17643 	{ SCMD_DOORLOCK,
17644 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17645 	    0, 4, 3 },
17646 	{ SCMD_LOCATE,
17647 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
17648 	    0, 0, 0, NULL, st_get_cdb_g1_lba },
17649 	{ SCMD_READ_POSITION,
17650 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17651 	    0, 0, 0 },
17652 	{ SCMD_WRITE_BUFFER,
17653 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17654 	    1, 0, 0 },
17655 	{ SCMD_READ_BUFFER,
17656 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17657 	    1, 0, 0 },
17658 	{ SCMD_REPORT_DENSITIES,
17659 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17660 	    0, 0, 0 },
17661 	{ SCMD_LOG_SELECT_G1,
17662 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17663 	    0, 0, 0 },
17664 	{ SCMD_LOG_SENSE_G1,
17665 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17666 	    0, 0, 0 },
17667 	{ SCMD_PRIN,
17668 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17669 	    0, 0, 0 },
17670 	{ SCMD_PROUT,
17671 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17672 	    0, 0, 0 },
17673 	{ SCMD_READ_ATTRIBUTE,
17674 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17675 	    0, 0, 0 },
17676 	{ SCMD_WRITE_ATTRIBUTE,
17677 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17678 	    0, 0, 0 },
17679 	{ SCMD_LOCATE_G4,
17680 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
17681 	    0, 0, 0, NULL, st_get_cdb_g4g5_cnt },
17682 	{ SCMD_REPORT_LUNS,
17683 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17684 	    0, 0, 0 },
17685 	{ SCMD_SVC_ACTION_IN_G5,
17686 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17687 	    0, 0, 0 },
17688 	{ SCMD_MAINTENANCE_IN,
17689 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17690 	    0, 0, 0 },
17691 	{ SCMD_MAINTENANCE_OUT,
17692 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17693 	    0, 0, 0 },
17694 	{ 0xff, /* Default attribute for unsupported commands */
17695 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_STARTING,
17696 	    1, 0, 0, NULL, NULL }
17697 };
17698 
17699 static const cmd_attribute *
17700 st_lookup_cmd_attribute(unsigned char cmd)
17701 {
17702 	int i;
17703 	cmd_attribute const *attribute;
17704 
17705 	for (i = 0; i < ST_NUM_MEMBERS(cmd_attributes); i++) {
17706 		attribute = &cmd_attributes[i];
17707 		if (attribute->cmd == cmd) {
17708 			return (attribute);
17709 		}
17710 	}
17711 	ASSERT(attribute);
17712 	return (attribute);
17713 }
17714 
17715 static int
17716 st_reset(struct scsi_tape *un, int reset_type)
17717 {
17718 	int rval;
17719 
17720 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
17721 
17722 	ST_FUNC(ST_DEVINFO, st_reset);
17723 	un->un_rsvd_status |= ST_INITIATED_RESET;
17724 	mutex_exit(ST_MUTEX);
17725 	do {
17726 		rval = scsi_reset(&un->un_sd->sd_address, reset_type);
17727 		if (rval == 0) {
17728 			switch (reset_type) {
17729 			case RESET_LUN:
17730 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
17731 				    "LUN reset failed trying target reset");
17732 				reset_type = RESET_TARGET;
17733 				break;
17734 			case RESET_TARGET:
17735 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
17736 				    "target reset failed trying bus reset");
17737 				reset_type = RESET_BUS;
17738 				break;
17739 			case RESET_BUS:
17740 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
17741 				    "bus reset failed trying all reset");
17742 				reset_type = RESET_ALL;
17743 			default:
17744 				mutex_enter(ST_MUTEX);
17745 				return (rval);
17746 			}
17747 		}
17748 	} while (rval == 0);
17749 	mutex_enter(ST_MUTEX);
17750 	return (rval);
17751 }
17752 
17753 
17754 static void
17755 st_reset_notification(caddr_t arg)
17756 {
17757 	struct scsi_tape *un = (struct scsi_tape *)arg;
17758 
17759 	ST_FUNC(ST_DEVINFO, st_reset_notification);
17760 	mutex_enter(ST_MUTEX);
17761 
17762 	un->un_unit_attention_flags = 2;
17763 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
17764 	    ST_RESERVE) {
17765 		un->un_rsvd_status |= ST_LOST_RESERVE;
17766 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
17767 		    "Lost Reservation notification");
17768 	} else {
17769 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
17770 		    "reset notification");
17771 	}
17772 
17773 	if ((un->un_restore_pos == 0) &&
17774 	    (un->un_state == ST_STATE_CLOSED) ||
17775 	    (un->un_state == ST_STATE_OPEN_PENDING_IO) ||
17776 	    (un->un_state == ST_STATE_CLOSING)) {
17777 		un->un_restore_pos = 1;
17778 	}
17779 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
17780 	    "reset and state was %d\n", un->un_state);
17781 	mutex_exit(ST_MUTEX);
17782 }
17783