xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/st.c (revision a024987b)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * SCSI	 SCSA-compliant and not-so-DDI-compliant Tape Driver
31  */
32 
33 #if defined(lint) && !defined(DEBUG)
34 #define	DEBUG	1
35 #endif
36 
37 #include <sys/modctl.h>
38 #include <sys/scsi/scsi.h>
39 #include <sys/mtio.h>
40 #include <sys/scsi/targets/stdef.h>
41 #include <sys/file.h>
42 #include <sys/kstat.h>
43 #include <sys/ddidmareq.h>
44 #include <sys/ddi.h>
45 #include <sys/sunddi.h>
46 #include <sys/byteorder.h>
47 
48 #define	IOSP	KSTAT_IO_PTR(un->un_stats)
49 /*
50  * stats maintained only for reads/writes as commands
51  * like rewind etc skew the wait/busy times
52  */
53 #define	IS_RW(bp) 	((bp)->b_bcount > 0)
54 #define	ST_DO_KSTATS(bp, kstat_function) \
55 	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
56 		kstat_function(IOSP); \
57 	}
58 
59 #define	ST_DO_ERRSTATS(un, x)  \
60 	if (un->un_errstats) { \
61 		struct st_errstats *stp; \
62 		stp = (struct st_errstats *)un->un_errstats->ks_data; \
63 		stp->x.value.ul++; \
64 	}
65 
66 #define	FILL_SCSI1_LUN(devp, pkt) 					\
67 	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
68 		int _lun;						\
69 		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
70 		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
71 		if (_lun > 0) {						\
72 			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
73 			    _lun;					\
74 		}							\
75 	}
76 
77 /*
78  * get an available contig mem header, cp.
79  * when big_enough is true, we will return NULL, if no big enough
80  * contig mem is found.
81  * when big_enough is false, we will try to find cp containing big
82  * enough contig mem. if not found, we will ruturn the last cp available.
83  *
84  * used by st_get_contig_mem()
85  */
86 #define	ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough) {		\
87 	struct contig_mem *tmp_cp = NULL;				\
88 	for ((cp) = (un)->un_contig_mem;				\
89 	    (cp) != NULL;						\
90 	    tmp_cp = (cp), (cp) = (cp)->cm_next) { 			\
91 		if (((cp)->cm_len >= (len)) || 				\
92 		    (!(big_enough) && ((cp)->cm_next == NULL))) { 	\
93 			if (tmp_cp == NULL) { 				\
94 				(un)->un_contig_mem = (cp)->cm_next; 	\
95 			} else { 					\
96 				tmp_cp->cm_next = (cp)->cm_next; 	\
97 			} 						\
98 			(cp)->cm_next = NULL; 				\
99 			(un)->un_contig_mem_available_num--; 		\
100 			break; 						\
101 		} 							\
102 	} 								\
103 }
104 
105 #define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
106 #define	COPY_POS(dest, source) bcopy(source, dest, sizeof (tapepos_t))
107 #define	ISALNUM(byte) \
108 	(((byte) >= 'a' && (byte) <= 'z') || \
109 	((byte) >= 'A' && (byte) <= 'Z') || \
110 	((byte) >= '0' && (byte) <= '9'))
111 
112 #define	ONE_K	1024
113 
114 /*
115  * Global External Data Definitions
116  */
117 extern struct scsi_key_strings scsi_cmds[];
118 extern uchar_t	scsi_cdb_size[];
119 
120 /*
121  * Local Static Data
122  */
123 static void *st_state;
124 static char *const st_label = "st";
125 static volatile dev_info_t *st_lastdev;
126 static volatile int st_recov_sz = sizeof (recov_info);
127 
128 #ifdef	__x86
129 /*
130  * We need to use below DMA attr to alloc physically contiguous
131  * memory to do I/O in big block size
132  */
133 static ddi_dma_attr_t st_contig_mem_dma_attr = {
134 	DMA_ATTR_V0,    /* version number */
135 	0x0,		/* lowest usable address */
136 	0xFFFFFFFFull,  /* high DMA address range */
137 	0xFFFFFFFFull,  /* DMA counter register */
138 	1,		/* DMA address alignment */
139 	1,		/* DMA burstsizes */
140 	1,		/* min effective DMA size */
141 	0xFFFFFFFFull,  /* max DMA xfer size */
142 	0xFFFFFFFFull,  /* segment boundary */
143 	1,		/* s/g list length */
144 	1,		/* granularity of device */
145 	0		/* DMA transfer flags */
146 };
147 
148 static ddi_device_acc_attr_t st_acc_attr = {
149 	DDI_DEVICE_ATTR_V0,
150 	DDI_NEVERSWAP_ACC,
151 	DDI_STRICTORDER_ACC
152 };
153 
154 /* set limitation for the number of contig_mem */
155 static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
156 #endif
157 
158 /*
159  * Tunable parameters
160  *
161  * DISCLAIMER
162  * ----------
163  * These parameters are intended for use only in system testing; if you use
164  * them in production systems, you do so at your own risk. Altering any
165  * variable not listed below may cause unpredictable system behavior.
166  *
167  * st_check_media_time
168  *
169  *   Three second state check
170  *
171  * st_allow_large_xfer
172  *
173  *   Gated with ST_NO_RECSIZE_LIMIT
174  *
175  *   0 - Transfers larger than 64KB will not be allowed
176  *       regardless of the setting of ST_NO_RECSIZE_LIMIT
177  *   1 - Transfers larger than 64KB will be allowed
178  *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
179  *
180  * st_report_soft_errors_on_close
181  *
182  *  Gated with ST_SOFT_ERROR_REPORTING
183  *
184  *  0 - Errors will not be reported on close regardless
185  *      of the setting of ST_SOFT_ERROR_REPORTING
186  *
187  *  1 - Errors will be reported on close if
188  *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
189  */
190 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
191 static int st_retry_count	= ST_RETRY_COUNT;
192 
193 static int st_io_time		= ST_IO_TIME;
194 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
195 
196 static int st_space_time	= ST_SPACE_TIME;
197 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
198 
199 static int st_error_level	= SCSI_ERR_RETRYABLE;
200 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
201 
202 static int st_max_throttle	= ST_MAX_THROTTLE;
203 
204 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
205 
206 static int st_allow_large_xfer = 1;
207 static int st_report_soft_errors_on_close = 1;
208 
209 /*
210  * End of tunable parameters list
211  */
212 
213 
214 
215 /*
216  * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
217  *
218  * Asynchronous I/O's main offering is that it is a non-blocking way to do
219  * reads and writes.  The driver will queue up all the requests it gets and
220  * have them ready to transport to the HBA.  Unfortunately, we cannot always
221  * just ship the I/O requests to the HBA, as there errors and exceptions
222  * that may happen when we don't want the HBA to continue.  Therein comes
223  * the flush-on-errors capability.  If the HBA supports it, then st will
224  * send in st_max_throttle I/O requests at the same time.
225  *
226  * Persistent errors : This was also reasonably simple.  In the interrupt
227  * routines, if there was an error or exception (FM, LEOT, media error,
228  * transport error), the persistent error bits are set and shuts everything
229  * down, but setting the throttle to zero.  If we hit and exception in the
230  * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
231  * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
232  * the appropriate error, and this will preserve order. Of course, depending
233  * on the exception we have to show a zero read or write before we show
234  * errors back to the application.
235  */
236 
237 extern const int st_ndrivetypes;	/* defined in st_conf.c */
238 extern const struct st_drivetype st_drivetypes[];
239 extern const char st_conf_version[];
240 
241 #ifdef STDEBUG
242 static int st_soft_error_report_debug = 0;
243 volatile int st_debug = 0;
244 #endif
245 
246 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
247 
248 static const struct vid_drivetype {
249 	char	*vid;
250 	char	type;
251 } st_vid_dt[] = {
252 	{"LTO-CVE ",	MT_LTO},
253 	{"QUANTUM ",    MT_ISDLT},
254 	{"SONY    ",    MT_ISAIT},
255 	{"STK     ",	MT_ISSTK9840}
256 };
257 
258 static const struct driver_minor_data {
259 	char	*name;
260 	int	minor;
261 } st_minor_data[] = {
262 	/*
263 	 * The top 4 entries are for the default densities,
264 	 * don't alter their position.
265 	 */
266 	{"",	0},
267 	{"n",	MT_NOREWIND},
268 	{"b",	MT_BSD},
269 	{"bn",	MT_NOREWIND | MT_BSD},
270 	{"l",	MT_DENSITY1},
271 	{"m",	MT_DENSITY2},
272 	{"h",	MT_DENSITY3},
273 	{"c",	MT_DENSITY4},
274 	{"u",	MT_DENSITY4},
275 	{"ln",	MT_DENSITY1 | MT_NOREWIND},
276 	{"mn",	MT_DENSITY2 | MT_NOREWIND},
277 	{"hn",	MT_DENSITY3 | MT_NOREWIND},
278 	{"cn",	MT_DENSITY4 | MT_NOREWIND},
279 	{"un",	MT_DENSITY4 | MT_NOREWIND},
280 	{"lb",	MT_DENSITY1 | MT_BSD},
281 	{"mb",	MT_DENSITY2 | MT_BSD},
282 	{"hb",	MT_DENSITY3 | MT_BSD},
283 	{"cb",	MT_DENSITY4 | MT_BSD},
284 	{"ub",	MT_DENSITY4 | MT_BSD},
285 	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
286 	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
287 	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
288 	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
289 	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
290 };
291 
292 /* strings used in many debug and warning messages */
293 static const char wr_str[]  = "write";
294 static const char rd_str[]  = "read";
295 static const char wrg_str[] = "writing";
296 static const char rdg_str[] = "reading";
297 static const char *space_strs[] = {
298 	"records",
299 	"filemarks",
300 	"sequential filemarks",
301 	"eod",
302 	"setmarks",
303 	"sequential setmarks",
304 	"Reserved",
305 	"Reserved"
306 };
307 static const char *load_strs[] = {
308 	"unload",		/* LD_UNLOAD		0 */
309 	"load",			/* LD_LOAD		1 */
310 	"retension",		/* LD_RETEN		2 */
311 	"load reten",		/* LD_LOAD | LD_RETEN	3 */
312 	"eod",			/* LD_EOT		4 */
313 	"load EOD",		/* LD_LOAD | LD_EOT	5 */
314 	"reten EOD",		/* LD_RETEN | LD_EOT	6 */
315 	"load reten EOD"	/* LD_LOAD|LD_RETEN|LD_EOT 7 */
316 	"hold",			/* LD_HOLD		8 */
317 	"load and hold"		/* LD_LOAD | LD_HOLD	9 */
318 };
319 
320 const char *bogusID = "Unknown Media ID";
321 
322 /* default density offsets in the table above */
323 #define	DEF_BLANK	0
324 #define	DEF_NOREWIND	1
325 #define	DEF_BSD		2
326 #define	DEF_BSD_NR	3
327 
328 /* Sense Key, ASC/ASCQ for which tape ejection is needed */
329 
330 static struct tape_failure_code {
331 	uchar_t key;
332 	uchar_t add_code;
333 	uchar_t qual_code;
334 } st_tape_failure_code[] = {
335 	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
336 	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
337 	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
338 	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
339 	{ KEY_NOT_READY, 0x53, 0x00},
340 	{ 0xff}
341 };
342 
343 /*  clean bit position and mask */
344 
345 static struct cln_bit_position {
346 	ushort_t cln_bit_byte;
347 	uchar_t cln_bit_mask;
348 } st_cln_bit_position[] = {
349 	{ 21, 0x08},
350 	{ 70, 0xc0},
351 	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
352 };
353 
354 /*
355  * architecture dependent allocation restrictions. For x86, we'll set
356  * dma_attr_addr_hi to st_max_phys_addr and dma_attr_sgllen to
357  * st_sgl_size during _init().
358  */
359 #if defined(__sparc)
360 static ddi_dma_attr_t st_alloc_attr = {
361 	DMA_ATTR_V0,	/* version number */
362 	0x0,		/* lowest usable address */
363 	0xFFFFFFFFull,	/* high DMA address range */
364 	0xFFFFFFFFull,	/* DMA counter register */
365 	1,		/* DMA address alignment */
366 	1,		/* DMA burstsizes */
367 	1,		/* min effective DMA size */
368 	0xFFFFFFFFull,	/* max DMA xfer size */
369 	0xFFFFFFFFull,	/* segment boundary */
370 	1,		/* s/g list length */
371 	512,		/* granularity of device */
372 	0		/* DMA transfer flags */
373 };
374 #elif defined(__x86)
375 static ddi_dma_attr_t st_alloc_attr = {
376 	DMA_ATTR_V0,	/* version number */
377 	0x0,		/* lowest usable address */
378 	0x0,		/* high DMA address range [set in _init()] */
379 	0xFFFFull,	/* DMA counter register */
380 	512,		/* DMA address alignment */
381 	1,		/* DMA burstsizes */
382 	1,		/* min effective DMA size */
383 	0xFFFFFFFFull,	/* max DMA xfer size */
384 	0xFFFFFFFFull,  /* segment boundary */
385 	0,		/* s/g list length */
386 	512,		/* granularity of device [set in _init()] */
387 	0		/* DMA transfer flags */
388 };
389 uint64_t st_max_phys_addr = 0xFFFFFFFFull;
390 int st_sgl_size = 0xF;
391 
392 #endif
393 
394 /*
395  * Configuration Data:
396  *
397  * Device driver ops vector
398  */
399 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
400 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
401 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
402 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
403 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
404 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
405 static int st_strategy(struct buf *bp);
406 static int st_queued_strategy(buf_t *bp);
407 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
408 	cred_t *cred_p, int *rval_p);
409 extern int nulldev(), nodev();
410 
411 static struct cb_ops st_cb_ops = {
412 	st_open,		/* open */
413 	st_close,		/* close */
414 	st_queued_strategy,	/* strategy Not Block device but async checks */
415 	nodev,			/* print */
416 	nodev,			/* dump */
417 	st_read,		/* read */
418 	st_write,		/* write */
419 	st_ioctl,		/* ioctl */
420 	nodev,			/* devmap */
421 	nodev,			/* mmap */
422 	nodev,			/* segmap */
423 	nochpoll,		/* poll */
424 	ddi_prop_op,		/* cb_prop_op */
425 	0,			/* streamtab  */
426 	D_64BIT | D_MP | D_NEW | D_HOTPLUG |
427 	D_OPEN_RETURNS_EINTR,	/* cb_flag */
428 	CB_REV,			/* cb_rev */
429 	st_aread, 		/* async I/O read entry point */
430 	st_awrite		/* async I/O write entry point */
431 
432 };
433 
434 static int st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
435 		void **result);
436 static int st_probe(dev_info_t *dev);
437 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
438 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
439 
440 static struct dev_ops st_ops = {
441 	DEVO_REV,		/* devo_rev, */
442 	0,			/* refcnt  */
443 	st_info,		/* info */
444 	nulldev,		/* identify */
445 	st_probe,		/* probe */
446 	st_attach,		/* attach */
447 	st_detach,		/* detach */
448 	nodev,			/* reset */
449 	&st_cb_ops,		/* driver operations */
450 	(struct bus_ops *)0,	/* bus operations */
451 	nulldev			/* power */
452 };
453 
454 /*
455  * Local Function Declarations
456  */
457 static char *st_print_scsi_cmd(char cmd);
458 static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
459     char *title, char *cdb);
460 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
461     char *title, char *data, int len);
462 static int st_doattach(struct scsi_device *devp, int (*canwait)());
463 static void st_known_tape_type(struct scsi_tape *un);
464 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
465     struct st_drivetype *);
466 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
467     struct st_drivetype *);
468 static int st_get_conf_from_tape_drive(struct scsi_tape *, char *,
469     struct st_drivetype *);
470 static int st_get_densities_from_tape_drive(struct scsi_tape *,
471     struct st_drivetype *);
472 static int st_get_timeout_values_from_tape_drive(struct scsi_tape *,
473     struct st_drivetype *);
474 static int st_get_timeouts_value(struct scsi_tape *, uchar_t, ushort_t *,
475     ushort_t);
476 static int st_get_default_conf(struct scsi_tape *, char *,
477     struct st_drivetype *);
478 static int st_rw(dev_t dev, struct uio *uio, int flag);
479 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
480 static int st_find_eod(struct scsi_tape *un);
481 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
482 static int st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *, int flag);
483 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
484 static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
485 static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
486 static void st_start(struct scsi_tape *un);
487 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
488     clock_t timeout_interval, int queued);
489 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
490     clock_t timeout_interval);
491 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
492 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
493 static void st_init(struct scsi_tape *un);
494 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
495     int (*func)(caddr_t));
496 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
497     struct buf *bp, int (*func)(caddr_t));
498 static void st_intr(struct scsi_pkt *pkt);
499 static void st_set_state(struct scsi_tape *un, buf_t *bp);
500 static void st_test_append(struct buf *bp);
501 static int st_runout(caddr_t);
502 static int st_cmd(struct scsi_tape *un, int com, int64_t count, int wait);
503 static int st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com,
504     int64_t count);
505 static int st_set_compression(struct scsi_tape *un);
506 static int st_write_fm(dev_t dev, int wfm);
507 static int st_determine_generic(struct scsi_tape *un);
508 static int st_determine_density(struct scsi_tape *un, int rw);
509 static int st_get_density(struct scsi_tape *un);
510 static int st_set_density(struct scsi_tape *un);
511 static int st_loadtape(struct scsi_tape *un);
512 static int st_modesense(struct scsi_tape *un);
513 static int st_modeselect(struct scsi_tape *un);
514 static errstate st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
515 static int st_wrongtapetype(struct scsi_tape *un);
516 static errstate st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
517 static errstate st_handle_sense(struct scsi_tape *un, struct buf *bp,
518     tapepos_t *);
519 static errstate st_handle_autosense(struct scsi_tape *un, struct buf *bp,
520     tapepos_t *);
521 static int st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag);
522 static void st_update_error_stack(struct scsi_tape *un, struct scsi_pkt *pkt,
523     struct scsi_arq_status *cmd);
524 static void st_empty_error_stack(struct scsi_tape *un);
525 static errstate st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
526     struct scsi_status *, tapepos_t *);
527 static int st_report_soft_errors(dev_t dev, int flag);
528 static void st_delayed_cv_broadcast(void *arg);
529 static int st_check_media(dev_t dev, enum mtio_state state);
530 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
531 static void st_intr_restart(void *arg);
532 static void st_start_restart(void *arg);
533 static int st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
534     struct seq_mode *page_data, int page_size);
535 static int st_change_block_size(struct scsi_tape *un, uint32_t nblksz);
536 static int st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
537     struct seq_mode *page_data, int page_size);
538 static int st_read_block_limits(struct scsi_tape *un,
539     struct read_blklim *read_blk);
540 static int st_report_density_support(struct scsi_tape *un,
541     uchar_t *density_data, size_t buflen);
542 static int st_report_supported_operation(struct scsi_tape *un,
543     uchar_t *oper_data, uchar_t option_code, ushort_t service_action);
544 static int st_tape_init(struct scsi_tape *un);
545 static void st_flush(struct scsi_tape *un);
546 static void st_set_pe_errno(struct scsi_tape *un);
547 static void st_hba_unflush(struct scsi_tape *un);
548 static void st_turn_pe_on(struct scsi_tape *un);
549 static void st_turn_pe_off(struct scsi_tape *un);
550 static void st_set_pe_flag(struct scsi_tape *un);
551 static void st_clear_pe(struct scsi_tape *un);
552 static void st_wait_for_io(struct scsi_tape *un);
553 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
554 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
555 static int st_reserve_release(struct scsi_tape *un, int command, ubufunc_t ubf);
556 static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb);
557 static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
558     int count);
559 static int st_take_ownership(struct scsi_tape *un);
560 static int st_check_asc_ascq(struct scsi_tape *un);
561 static int st_check_clean_bit(struct scsi_tape *un);
562 static int st_check_alert_flags(struct scsi_tape *un);
563 static int st_check_sequential_clean_bit(struct scsi_tape *un);
564 static int st_check_sense_clean_bit(struct scsi_tape *un);
565 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
566 static void st_calculate_timeouts(struct scsi_tape *un);
567 static writablity st_is_drive_worm(struct scsi_tape *un);
568 static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
569     void *buf, size_t size, ubufunc_t bufunc);
570 static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
571     caddr_t dest, uchar_t page);
572 static int st_update_block_pos(struct scsi_tape *un, bufunc_t bf,
573     int post_space);
574 static int st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
575     read_p_types type, size_t data_sz, const caddr_t responce, int post_space);
576 static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
577 static int st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf,
578     tapepos_t *pos, uint64_t lblk, uchar_t partition);
579 static int st_mtfsf_ioctl(struct scsi_tape *un, int files);
580 static int st_mtfsr_ioctl(struct scsi_tape *un, int count);
581 static int st_mtbsf_ioctl(struct scsi_tape *un, int files);
582 static int st_mtnbsf_ioctl(struct scsi_tape *un, int count);
583 static int st_mtbsr_ioctl(struct scsi_tape *un, int num);
584 static int st_mtfsfm_ioctl(struct scsi_tape *un, int cnt);
585 static int st_mtbsfm_ioctl(struct scsi_tape *un, int cnt);
586 static int st_backward_space_files(struct scsi_tape *un, int count,
587     int infront);
588 static int st_forward_space_files(struct scsi_tape *un, int files);
589 static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
590     int32_t fileno);
591 static int st_space_to_begining_of_file(struct scsi_tape *un);
592 static int st_space_records(struct scsi_tape *un, int records);
593 static int st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc);
594 static errstate st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
595     errstate onentry);
596 static void st_recover(void *arg);
597 static void st_recov_cb(struct scsi_pkt *pkt);
598 static int st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait);
599 static int st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
600     int flag);
601 static void st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
602     struct scsi_pkt *cmd);
603 static int st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf);
604 static int st_test_path_to_device(struct scsi_tape *un);
605 static int st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
606     read_pos_data_t *raw);
607 static int st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
608     read_pos_data_t *raw);
609 static int st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
610     cmd_attribute const * cmd_att, tapepos_t *read);
611 static errstate st_recover_reissue_pkt(struct scsi_tape *us,
612     struct scsi_pkt *pkt);
613 static int st_transport(struct scsi_tape *un, struct scsi_pkt *pkt);
614 static buf_t *st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp);
615 static void st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp);
616 static int st_reset(struct scsi_tape *un, int reset_type);
617 static void st_reset_notification(caddr_t arg);
618 static const cmd_attribute *st_lookup_cmd_attribute(unsigned char cmd);
619 
620 #ifdef	__x86
621 /*
622  * routines for I/O in big block size
623  */
624 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
625 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
626     int alloc_flags);
627 static int st_bigblk_xfer_done(struct buf *bp);
628 static struct buf *st_get_bigblk_bp(struct buf *bp);
629 #endif
630 static void st_print_position(dev_info_t *dev, char *label, uint_t level,
631     const char *comment, tapepos_t *pos);
632 
633 /*
634  * error statistics create/update functions
635  */
636 static int st_create_errstats(struct scsi_tape *, int);
637 static int st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf,
638     tapepos_t *pos);
639 
640 #ifdef STDEBUG
641 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
642 static char *st_dev_name(dev_t dev);
643 #endif /* STDEBUG */
644 
645 #if !defined(lint)
646 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
647     scsi_pkt buf uio scsi_cdb uscsi_cmd))
648 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
649 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
650 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
651 #endif
652 
653 /*
654  * autoconfiguration routines.
655  */
656 char _depends_on[] = "misc/scsi";
657 
658 static struct modldrv modldrv = {
659 	&mod_driverops,		/* Type of module. This one is a driver */
660 	"SCSI tape Driver %I%", /* Name of the module. */
661 	&st_ops			/* driver ops */
662 };
663 
664 static struct modlinkage modlinkage = {
665 	MODREV_1, &modldrv, NULL
666 };
667 
668 /*
669  * Notes on Post Reset Behavior in the tape driver:
670  *
671  * When the tape drive is opened, the driver  attempts  to make sure that
672  * the tape head is positioned exactly where it was left when it was last
673  * closed  provided  the  medium  is not  changed.  If the tape  drive is
674  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
675  * of position due to reset) will happen when the first tape operation or
676  * I/O occurs.  The repositioning (if required) may not be possible under
677  * certain situations such as when the device firmware not able to report
678  * the medium  change in the REQUEST  SENSE data  because of a reset or a
679  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
680  * extraordinary  situations, where the driver fails to position the head
681  * at its  original  position,  it will fail the open the first  time, to
682  * save the applications from overwriting the data.  All further attempts
683  * to open the tape device will result in the driver  attempting  to load
684  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
685  * indicate  that further  attempts to open the tape device may result in
686  * the tape being  loaded at BOT will be printed on the  console.  If the
687  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
688  * original tape head  position,  will result in the failure of the first
689  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
690  * internal tape position  which will  necessitate  the  applications  to
691  * validate the position by using either a tape  positioning  ioctl (such
692  * as MTREW) or closing and reopening the tape device.
693  *
694  */
695 
696 int
697 _init(void)
698 {
699 	int e;
700 
701 	if (((e = ddi_soft_state_init(&st_state,
702 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
703 		return (e);
704 	}
705 
706 	if ((e = mod_install(&modlinkage)) != 0) {
707 		ddi_soft_state_fini(&st_state);
708 	}
709 
710 #if defined(__x86)
711 	/* set the max physical address for iob allocs on x86 */
712 	st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
713 
714 	/*
715 	 * set the sgllen for iob allocs on x86. If this is set less than
716 	 * the number of pages the buffer will take (taking into account
717 	 * alignment), it would force the allocator to try and allocate
718 	 * contiguous pages.
719 	 */
720 	st_alloc_attr.dma_attr_sgllen = st_sgl_size;
721 #endif
722 
723 	return (e);
724 }
725 
726 int
727 _fini(void)
728 {
729 	int e;
730 
731 	if ((e = mod_remove(&modlinkage)) != 0) {
732 		return (e);
733 	}
734 
735 	ddi_soft_state_fini(&st_state);
736 
737 	return (e);
738 }
739 
740 int
741 _info(struct modinfo *modinfop)
742 {
743 	return (mod_info(&modlinkage, modinfop));
744 }
745 
746 
747 static int
748 st_probe(dev_info_t *devi)
749 {
750 	int instance;
751 	struct scsi_device *devp;
752 	int rval;
753 
754 #if !defined(__sparc)
755 	char    *tape_prop;
756 	int	tape_prop_len;
757 #endif
758 
759 	ST_ENTR(devi, st_probe);
760 
761 	/* If self identifying device */
762 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
763 		return (DDI_PROBE_DONTCARE);
764 	}
765 
766 #if !defined(__sparc)
767 	/*
768 	 * Since some x86 HBAs have devnodes that look like SCSI as
769 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
770 	 * we check for the presence of the "tape" property.
771 	 */
772 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
773 	    DDI_PROP_CANSLEEP, "tape",
774 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
775 		return (DDI_PROBE_FAILURE);
776 	}
777 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
778 		kmem_free(tape_prop, tape_prop_len);
779 		return (DDI_PROBE_FAILURE);
780 	}
781 	kmem_free(tape_prop, tape_prop_len);
782 #endif
783 
784 	devp = ddi_get_driver_private(devi);
785 	instance = ddi_get_instance(devi);
786 
787 	if (ddi_get_soft_state(st_state, instance) != NULL) {
788 		return (DDI_PROBE_PARTIAL);
789 	}
790 
791 
792 	/*
793 	 * Turn around and call probe routine to see whether
794 	 * we actually have a tape at this SCSI nexus.
795 	 */
796 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
797 
798 		/*
799 		 * In checking the whole inq_dtype byte we are looking at both
800 		 * the Peripheral Qualifier and the Peripheral Device Type.
801 		 * For this driver we are only interested in sequential devices
802 		 * that are connected or capable if connecting to this logical
803 		 * unit.
804 		 */
805 		if (devp->sd_inq->inq_dtype ==
806 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
807 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
808 			    "probe exists\n");
809 			rval = DDI_PROBE_SUCCESS;
810 		} else {
811 			rval = DDI_PROBE_FAILURE;
812 		}
813 	} else {
814 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
815 		    "probe failure: nothing there\n");
816 		rval = DDI_PROBE_FAILURE;
817 	}
818 	scsi_unprobe(devp);
819 	return (rval);
820 }
821 
822 static int
823 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
824 {
825 	int 	instance;
826 	int	wide;
827 	int 	dev_instance;
828 	int	ret_status;
829 	struct	scsi_device *devp;
830 	int	node_ix;
831 	struct	scsi_tape *un;
832 
833 	ST_ENTR(devi, st_attach);
834 
835 	devp = ddi_get_driver_private(devi);
836 	instance = ddi_get_instance(devi);
837 
838 	switch (cmd) {
839 		case DDI_ATTACH:
840 			if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
841 			    "tape-command-recovery-disable", 0) != 0) {
842 				st_recov_sz = sizeof (pkt_info);
843 			}
844 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
845 				return (DDI_FAILURE);
846 			}
847 			break;
848 		case DDI_RESUME:
849 			/*
850 			 * Suspend/Resume
851 			 *
852 			 * When the driver suspended, there might be
853 			 * outstanding cmds and therefore we need to
854 			 * reset the suspended flag and resume the scsi
855 			 * watch thread and restart commands and timeouts
856 			 */
857 
858 			if (!(un = ddi_get_soft_state(st_state, instance))) {
859 				return (DDI_FAILURE);
860 			}
861 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
862 			    un->un_dev);
863 
864 			mutex_enter(ST_MUTEX);
865 
866 			un->un_throttle = un->un_max_throttle;
867 			un->un_tids_at_suspend = 0;
868 			un->un_pwr_mgmt = ST_PWR_NORMAL;
869 
870 			if (un->un_swr_token) {
871 				scsi_watch_resume(un->un_swr_token);
872 			}
873 
874 			/*
875 			 * Restart timeouts
876 			 */
877 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
878 				mutex_exit(ST_MUTEX);
879 				un->un_delay_tid = timeout(
880 				    st_delayed_cv_broadcast, un,
881 				    drv_usectohz((clock_t)
882 				    MEDIA_ACCESS_DELAY));
883 				mutex_enter(ST_MUTEX);
884 			}
885 
886 			if (un->un_tids_at_suspend & ST_HIB_TID) {
887 				mutex_exit(ST_MUTEX);
888 				un->un_hib_tid = timeout(st_intr_restart, un,
889 				    ST_STATUS_BUSY_TIMEOUT);
890 				mutex_enter(ST_MUTEX);
891 			}
892 
893 			ret_status = st_clear_unit_attentions(dev_instance, 5);
894 
895 			/*
896 			 * now check if we need to restore the tape position
897 			 */
898 			if ((un->un_suspend_pos.pmode != invalid) &&
899 			    ((un->un_suspend_pos.fileno > 0) ||
900 			    (un->un_suspend_pos.blkno > 0)) ||
901 			    (un->un_suspend_pos.lgclblkno > 0)) {
902 				if (ret_status != 0) {
903 					/*
904 					 * tape didn't get good TUR
905 					 * just print out error messages
906 					 */
907 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
908 					    "st_attach-RESUME: tape failure "
909 					    " tape position will be lost");
910 				} else {
911 					/* this prints errors */
912 					(void) st_validate_tapemarks(un,
913 					    st_uscsi_cmd, &un->un_suspend_pos);
914 				}
915 				/*
916 				 * there are no retries, if there is an error
917 				 * we don't know if the tape has changed
918 				 */
919 				un->un_suspend_pos.pmode = invalid;
920 			}
921 
922 			/* now we are ready to start up any queued I/Os */
923 			if (un->un_ncmds || un->un_quef) {
924 				st_start(un);
925 			}
926 
927 			cv_broadcast(&un->un_suspend_cv);
928 			mutex_exit(ST_MUTEX);
929 			return (DDI_SUCCESS);
930 
931 		default:
932 			return (DDI_FAILURE);
933 	}
934 
935 	un = ddi_get_soft_state(st_state, instance);
936 
937 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
938 	    "st_attach: instance=%x\n", instance);
939 
940 	/*
941 	 * Add a zero-length attribute to tell the world we support
942 	 * kernel ioctls (for layered drivers)
943 	 */
944 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
945 	    DDI_KERNEL_IOCTL, NULL, 0);
946 
947 	ddi_report_dev((dev_info_t *)devi);
948 
949 	/*
950 	 * If it's a SCSI-2 tape drive which supports wide,
951 	 * tell the host adapter to use wide.
952 	 */
953 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
954 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
955 
956 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
957 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
958 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
959 	}
960 
961 	/*
962 	 * enable autorequest sense; keep the rq packet around in case
963 	 * the autorequest sense fails because of a busy condition
964 	 * do a getcap first in case the capability is not variable
965 	 */
966 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
967 		un->un_arq_enabled = 1;
968 	} else {
969 		un->un_arq_enabled =
970 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
971 	}
972 
973 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
974 	    (un->un_arq_enabled ? "enabled" : "disabled"));
975 
976 	un->un_untagged_qing =
977 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
978 
979 	/*
980 	 * XXX - This is just for 2.6.  to tell users that write buffering
981 	 *	has gone away.
982 	 */
983 	if (un->un_arq_enabled && un->un_untagged_qing) {
984 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
985 		    "tape-driver-buffering", 0) != 0) {
986 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
987 			    "Write Data Buffering has been depricated. Your "
988 			    "applications should continue to work normally.\n"
989 			    " But, they should  ported to use Asynchronous "
990 			    " I/O\n"
991 			    " For more information, read about "
992 			    " tape-driver-buffering "
993 			    "property in the st(7d) man page\n");
994 		}
995 	}
996 
997 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
998 	un->un_flush_on_errors = 0;
999 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
1000 
1001 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
1002 	    "throttle=%x, max_throttle = %x\n",
1003 	    un->un_throttle, un->un_max_throttle);
1004 
1005 	/* initialize persistent errors to nil */
1006 	un->un_persistence = 0;
1007 	un->un_persist_errors = 0;
1008 
1009 	/*
1010 	 * Get dma-max from HBA driver. If it is not defined, use 64k
1011 	 */
1012 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
1013 	if (un->un_maxdma == -1) {
1014 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1015 		    "Received a value that looked like -1. Using 64k maxdma");
1016 		un->un_maxdma = (64 * ONE_K);
1017 	}
1018 
1019 #ifdef	__x86
1020 	/*
1021 	 * for x86, the device may be able to DMA more than the system will
1022 	 * allow under some circumstances. We need account for both the HBA's
1023 	 * and system's contraints.
1024 	 *
1025 	 * Get the maximum DMA under worse case conditions. e.g. looking at the
1026 	 * device constraints, the max copy buffer size, and the worse case
1027 	 * fragmentation. NOTE: this may differ from dma-max since dma-max
1028 	 * doesn't take the worse case framentation into account.
1029 	 *
1030 	 * e.g. a device may be able to DMA 16MBytes, but can only DMA 1MByte
1031 	 * if none of the pages are contiguous. Keeping track of both of these
1032 	 * values allows us to support larger tape block sizes on some devices.
1033 	 */
1034 	un->un_maxdma_arch = scsi_ifgetcap(&devp->sd_address, "dma-max-arch",
1035 	    1);
1036 
1037 	/*
1038 	 * If the dma-max-arch capability is not implemented, or the value
1039 	 * comes back higher than what was reported in dma-max, use dma-max.
1040 	 */
1041 	if ((un->un_maxdma_arch == -1) ||
1042 	    ((uint_t)un->un_maxdma < (uint_t)un->un_maxdma_arch)) {
1043 		un->un_maxdma_arch = un->un_maxdma;
1044 	}
1045 #endif
1046 
1047 	/*
1048 	 * Get the max allowable cdb size
1049 	 */
1050 	un->un_max_cdb_sz =
1051 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
1052 	if (un->un_max_cdb_sz < CDB_GROUP0) {
1053 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1054 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
1055 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
1056 	}
1057 
1058 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1059 
1060 	un->un_mediastate = MTIO_NONE;
1061 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1062 
1063 	/*
1064 	 * initialize kstats
1065 	 */
1066 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1067 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1068 	if (un->un_stats) {
1069 		un->un_stats->ks_lock = ST_MUTEX;
1070 		kstat_install(un->un_stats);
1071 	}
1072 	(void) st_create_errstats(un, instance);
1073 
1074 	/*
1075 	 * find the drive type for this target
1076 	 */
1077 	mutex_enter(ST_MUTEX);
1078 	un->un_dev = MT_TEM_DEV(instance);
1079 	st_known_tape_type(un);
1080 	un->un_dev = 0;
1081 	mutex_exit(ST_MUTEX);
1082 
1083 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
1084 		int minor;
1085 		char *name;
1086 
1087 		name  = st_minor_data[node_ix].name;
1088 		minor = st_minor_data[node_ix].minor;
1089 
1090 		/*
1091 		 * For default devices set the density to the
1092 		 * preferred default density for this device.
1093 		 */
1094 		if (node_ix <= DEF_BSD_NR) {
1095 			minor |= un->un_dp->default_density;
1096 		}
1097 		minor |= MTMINOR(instance);
1098 
1099 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
1100 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
1101 			continue;
1102 		}
1103 
1104 		ddi_remove_minor_node(devi, NULL);
1105 
1106 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1107 		    st_reset_notification, (caddr_t)un);
1108 		cv_destroy(&un->un_clscv);
1109 		cv_destroy(&un->un_sbuf_cv);
1110 		cv_destroy(&un->un_queue_cv);
1111 		cv_destroy(&un->un_state_cv);
1112 #ifdef	__x86
1113 		cv_destroy(&un->un_contig_mem_cv);
1114 #endif
1115 		cv_destroy(&un->un_suspend_cv);
1116 		cv_destroy(&un->un_tape_busy_cv);
1117 		cv_destroy(&un->un_recov_buf_cv);
1118 		if (un->un_recov_taskq) {
1119 			ddi_taskq_destroy(un->un_recov_taskq);
1120 		}
1121 		if (un->un_sbufp) {
1122 			freerbuf(un->un_sbufp);
1123 		}
1124 		if (un->un_recov_buf) {
1125 			freerbuf(un->un_recov_buf);
1126 		}
1127 		if (un->un_uscsi_rqs_buf) {
1128 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1129 		}
1130 		if (un->un_mspl) {
1131 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1132 		}
1133 		if (un->un_dp_size) {
1134 			kmem_free(un->un_dp, un->un_dp_size);
1135 		}
1136 		if (un->un_state) {
1137 			kstat_delete(un->un_stats);
1138 		}
1139 		if (un->un_errstats) {
1140 			kstat_delete(un->un_errstats);
1141 		}
1142 
1143 		scsi_destroy_pkt(un->un_rqs);
1144 		scsi_free_consistent_buf(un->un_rqs_bp);
1145 		ddi_soft_state_free(st_state, instance);
1146 		devp->sd_private = NULL;
1147 		devp->sd_sense = NULL;
1148 
1149 		ddi_prop_remove_all(devi);
1150 		return (DDI_FAILURE);
1151 	}
1152 
1153 	return (DDI_SUCCESS);
1154 }
1155 
1156 /*
1157  * st_detach:
1158  *
1159  * we allow a detach if and only if:
1160  *	- no tape is currently inserted
1161  *	- tape position is at BOT or unknown
1162  *		(if it is not at BOT then a no rewind
1163  *		device was opened and we have to preserve state)
1164  *	- it must be in a closed state : no timeouts or scsi_watch requests
1165  *		will exist if it is closed, so we don't need to check for
1166  *		them here.
1167  */
1168 /*ARGSUSED*/
1169 static int
1170 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1171 {
1172 	int 	instance;
1173 	struct scsi_device *devp;
1174 	struct scsi_tape *un;
1175 	clock_t wait_cmds_complete;
1176 
1177 	ST_ENTR(devi, st_detach);
1178 
1179 	instance = ddi_get_instance(devi);
1180 
1181 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1182 		return (DDI_FAILURE);
1183 	}
1184 
1185 	mutex_enter(ST_MUTEX);
1186 
1187 	/*
1188 	 * Clear error entry stack
1189 	 */
1190 	st_empty_error_stack(un);
1191 
1192 	mutex_exit(ST_MUTEX);
1193 
1194 	switch (cmd) {
1195 
1196 	case DDI_DETACH:
1197 		/*
1198 		 * Undo what we did in st_attach & st_doattach,
1199 		 * freeing resources and removing things we installed.
1200 		 * The system framework guarantees we are not active
1201 		 * with this devinfo node in any other entry points at
1202 		 * this time.
1203 		 */
1204 
1205 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1206 		    "st_detach: instance=%x, un=%p\n", instance,
1207 		    (void *)un);
1208 
1209 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1210 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1211 		    (un->un_state != ST_STATE_CLOSED)) {
1212 			/*
1213 			 * we cannot unload some targets because the
1214 			 * inquiry returns junk unless immediately
1215 			 * after a reset
1216 			 */
1217 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1218 			    "cannot unload instance %x\n", instance);
1219 			return (DDI_FAILURE);
1220 		}
1221 
1222 		/*
1223 		 * if the tape has been removed then we may unload;
1224 		 * do a test unit ready and if it returns NOT READY
1225 		 * then we assume that it is safe to unload.
1226 		 * as a side effect, pmode may be set to invalid if the
1227 		 * the test unit ready fails;
1228 		 * also un_state may be set to non-closed, so reset it
1229 		 */
1230 		if ((un->un_dev) &&		/* Been opened since attach */
1231 		    ((un->un_pos.pmode == legacy) &&
1232 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1233 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1234 		    ((un->un_pos.pmode == logical) &&
1235 		    (un->un_pos.lgclblkno > 0))) {
1236 			mutex_enter(ST_MUTEX);
1237 			/*
1238 			 * Send Test Unit Ready in the hopes that if
1239 			 * the drive is not in the state we think it is.
1240 			 * And the state will be changed so it can be detached.
1241 			 * If the command fails to reach the device and
1242 			 * the drive was not rewound or unloaded we want
1243 			 * to fail the detach till a user command fails
1244 			 * where after the detach will succead.
1245 			 */
1246 			(void) st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
1247 			/*
1248 			 * After TUR un_state may be set to non-closed,
1249 			 * so reset it back.
1250 			 */
1251 			un->un_state = ST_STATE_CLOSED;
1252 			mutex_exit(ST_MUTEX);
1253 		}
1254 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1255 		    "un_status=%x, fileno=%x, blkno=%x\n",
1256 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1257 
1258 		/*
1259 		 * check again:
1260 		 * if we are not at BOT then it is not safe to unload
1261 		 */
1262 		if ((un->un_dev) &&		/* Been opened since attach */
1263 		    (((un->un_pos.pmode == legacy) &&
1264 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1265 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1266 		    ((un->un_pos.pmode == logical) &&
1267 		    (un->un_pos.lgclblkno > 0)))) {
1268 
1269 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1270 			    "cannot detach: pmode=%d fileno=0x%x, blkno=0x%x"
1271 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1272 			    un->un_pos.fileno, un->un_pos.blkno,
1273 			    un->un_pos.lgclblkno);
1274 			return (DDI_FAILURE);
1275 		}
1276 
1277 		/*
1278 		 * Just To make sure that we have released the
1279 		 * tape unit .
1280 		 */
1281 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1282 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1283 			mutex_enter(ST_MUTEX);
1284 			(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
1285 			mutex_exit(ST_MUTEX);
1286 		}
1287 
1288 		/*
1289 		 * now remove other data structures allocated in st_doattach()
1290 		 */
1291 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1292 		    "destroying/freeing\n");
1293 
1294 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1295 		    st_reset_notification, (caddr_t)un);
1296 		cv_destroy(&un->un_clscv);
1297 		cv_destroy(&un->un_sbuf_cv);
1298 		cv_destroy(&un->un_queue_cv);
1299 		cv_destroy(&un->un_suspend_cv);
1300 		cv_destroy(&un->un_tape_busy_cv);
1301 		cv_destroy(&un->un_recov_buf_cv);
1302 
1303 		if (un->un_recov_taskq) {
1304 			ddi_taskq_destroy(un->un_recov_taskq);
1305 		}
1306 
1307 		if (un->un_hib_tid) {
1308 			(void) untimeout(un->un_hib_tid);
1309 			un->un_hib_tid = 0;
1310 		}
1311 
1312 		if (un->un_delay_tid) {
1313 			(void) untimeout(un->un_delay_tid);
1314 			un->un_delay_tid = 0;
1315 		}
1316 		cv_destroy(&un->un_state_cv);
1317 
1318 #ifdef	__x86
1319 		cv_destroy(&un->un_contig_mem_cv);
1320 
1321 		if (un->un_contig_mem_hdl != NULL) {
1322 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1323 		}
1324 #endif
1325 		if (un->un_sbufp) {
1326 			freerbuf(un->un_sbufp);
1327 		}
1328 		if (un->un_recov_buf) {
1329 			freerbuf(un->un_recov_buf);
1330 		}
1331 		if (un->un_uscsi_rqs_buf) {
1332 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1333 		}
1334 		if (un->un_mspl) {
1335 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1336 		}
1337 		if (un->un_rqs) {
1338 			scsi_destroy_pkt(un->un_rqs);
1339 			scsi_free_consistent_buf(un->un_rqs_bp);
1340 		}
1341 		if (un->un_mkr_pkt) {
1342 			scsi_destroy_pkt(un->un_mkr_pkt);
1343 		}
1344 		if (un->un_arq_enabled) {
1345 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1346 		}
1347 		if (un->un_dp_size) {
1348 			kmem_free(un->un_dp, un->un_dp_size);
1349 		}
1350 		if (un->un_stats) {
1351 			kstat_delete(un->un_stats);
1352 			un->un_stats = (kstat_t *)0;
1353 		}
1354 		if (un->un_errstats) {
1355 			kstat_delete(un->un_errstats);
1356 			un->un_errstats = (kstat_t *)0;
1357 		}
1358 		if (un->un_media_id_len) {
1359 			kmem_free(un->un_media_id, un->un_media_id_len);
1360 		}
1361 		devp = ST_SCSI_DEVP;
1362 		ddi_soft_state_free(st_state, instance);
1363 		devp->sd_private = NULL;
1364 		devp->sd_sense = NULL;
1365 		scsi_unprobe(devp);
1366 		ddi_prop_remove_all(devi);
1367 		ddi_remove_minor_node(devi, NULL);
1368 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1369 		return (DDI_SUCCESS);
1370 
1371 	case DDI_SUSPEND:
1372 
1373 		/*
1374 		 * Suspend/Resume
1375 		 *
1376 		 * To process DDI_SUSPEND, we must do the following:
1377 		 *
1378 		 *  - check ddi_removing_power to see if power will be turned
1379 		 *    off. if so, return DDI_FAILURE
1380 		 *  - check if we are already suspended,
1381 		 *    if so, return DDI_FAILURE
1382 		 *  - check if device state is CLOSED,
1383 		 *    if not, return DDI_FAILURE.
1384 		 *  - wait until outstanding operations complete
1385 		 *  - save tape state
1386 		 *  - block new operations
1387 		 *  - cancel pending timeouts
1388 		 *
1389 		 */
1390 
1391 		if (ddi_removing_power(devi)) {
1392 			return (DDI_FAILURE);
1393 		}
1394 		mutex_enter(ST_MUTEX);
1395 
1396 		/*
1397 		 * Shouldn't already be suspended, if so return failure
1398 		 */
1399 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1400 			mutex_exit(ST_MUTEX);
1401 			return (DDI_FAILURE);
1402 		}
1403 		if (un->un_state != ST_STATE_CLOSED) {
1404 			mutex_exit(ST_MUTEX);
1405 			return (DDI_FAILURE);
1406 		}
1407 
1408 		/*
1409 		 * Wait for all outstanding I/O's to complete
1410 		 *
1411 		 * we wait on both ncmds and the wait queue for times
1412 		 * when we are flushing after persistent errors are
1413 		 * flagged, which is when ncmds can be 0, and the
1414 		 * queue can still have I/O's.  This way we preserve
1415 		 * order of biodone's.
1416 		 */
1417 		wait_cmds_complete = ddi_get_lbolt();
1418 		wait_cmds_complete +=
1419 		    st_wait_cmds_complete * drv_usectohz(1000000);
1420 		while (un->un_ncmds || un->un_quef ||
1421 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1422 
1423 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1424 			    wait_cmds_complete) == -1) {
1425 				/*
1426 				 * Time expired then cancel the command
1427 				 */
1428 				if (st_reset(un, RESET_LUN) == 0) {
1429 					if (un->un_last_throttle) {
1430 						un->un_throttle =
1431 						    un->un_last_throttle;
1432 					}
1433 					mutex_exit(ST_MUTEX);
1434 					return (DDI_FAILURE);
1435 				} else {
1436 					break;
1437 				}
1438 			}
1439 		}
1440 
1441 		/*
1442 		 * DDI_SUSPEND says that the system "may" power down, we
1443 		 * remember the file and block number before rewinding.
1444 		 * we also need to save state before issuing
1445 		 * any WRITE_FILE_MARK command.
1446 		 */
1447 		(void) st_update_block_pos(un, st_cmd, 0);
1448 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1449 
1450 
1451 		/*
1452 		 * Issue a zero write file fmk command to tell the drive to
1453 		 * flush any buffered tape marks
1454 		 */
1455 		(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1456 
1457 		/*
1458 		 * Because not all tape drives correctly implement buffer
1459 		 * flushing with the zero write file fmk command, issue a
1460 		 * synchronous rewind command to force data flushing.
1461 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1462 		 * anyway.
1463 		 */
1464 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
1465 
1466 		/* stop any new operations */
1467 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1468 		un->un_throttle = 0;
1469 
1470 		/*
1471 		 * cancel any outstanding timeouts
1472 		 */
1473 		if (un->un_delay_tid) {
1474 			timeout_id_t temp_id = un->un_delay_tid;
1475 			un->un_delay_tid = 0;
1476 			un->un_tids_at_suspend |= ST_DELAY_TID;
1477 			mutex_exit(ST_MUTEX);
1478 			(void) untimeout(temp_id);
1479 			mutex_enter(ST_MUTEX);
1480 		}
1481 
1482 		if (un->un_hib_tid) {
1483 			timeout_id_t temp_id = un->un_hib_tid;
1484 			un->un_hib_tid = 0;
1485 			un->un_tids_at_suspend |= ST_HIB_TID;
1486 			mutex_exit(ST_MUTEX);
1487 			(void) untimeout(temp_id);
1488 			mutex_enter(ST_MUTEX);
1489 		}
1490 
1491 		/*
1492 		 * Suspend the scsi_watch_thread
1493 		 */
1494 		if (un->un_swr_token) {
1495 			opaque_t temp_token = un->un_swr_token;
1496 			mutex_exit(ST_MUTEX);
1497 			scsi_watch_suspend(temp_token);
1498 		} else {
1499 			mutex_exit(ST_MUTEX);
1500 		}
1501 
1502 		return (DDI_SUCCESS);
1503 
1504 	default:
1505 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1506 		return (DDI_FAILURE);
1507 	}
1508 }
1509 
1510 
1511 /* ARGSUSED */
1512 static int
1513 st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1514 {
1515 	dev_t dev;
1516 	struct scsi_tape *un;
1517 	int instance, error;
1518 
1519 	ST_ENTR(dip, st_info);
1520 
1521 	switch (infocmd) {
1522 	case DDI_INFO_DEVT2DEVINFO:
1523 		dev = (dev_t)arg;
1524 		instance = MTUNIT(dev);
1525 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1526 			return (DDI_FAILURE);
1527 		*result = (void *) ST_DEVINFO;
1528 		error = DDI_SUCCESS;
1529 		break;
1530 	case DDI_INFO_DEVT2INSTANCE:
1531 		dev = (dev_t)arg;
1532 		instance = MTUNIT(dev);
1533 		*result = (void *)(uintptr_t)instance;
1534 		error = DDI_SUCCESS;
1535 		break;
1536 	default:
1537 		error = DDI_FAILURE;
1538 	}
1539 	return (error);
1540 }
1541 
1542 static int
1543 st_doattach(struct scsi_device *devp, int (*canwait)())
1544 {
1545 	struct scsi_tape *un = NULL;
1546 	recov_info *ri;
1547 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1548 	int instance;
1549 	size_t rlen;
1550 
1551 	ST_FUNC(devp->sd_dev, st_doattach);
1552 	/*
1553 	 * Call the routine scsi_probe to do some of the dirty work.
1554 	 * If the INQUIRY command succeeds, the field sd_inq in the
1555 	 * device structure will be filled in.
1556 	 */
1557 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1558 	    "st_doattach(): probing\n");
1559 
1560 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1561 
1562 		/*
1563 		 * In checking the whole inq_dtype byte we are looking at both
1564 		 * the Peripheral Qualifier and the Peripheral Device Type.
1565 		 * For this driver we are only interested in sequential devices
1566 		 * that are connected or capable if connecting to this logical
1567 		 * unit.
1568 		 */
1569 		if (devp->sd_inq->inq_dtype ==
1570 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1571 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1572 			    "probe exists\n");
1573 		} else {
1574 			/* Something there but not a tape device */
1575 			scsi_unprobe(devp);
1576 			return (DDI_FAILURE);
1577 		}
1578 	} else {
1579 		/* Nothing there */
1580 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1581 		    "probe failure: nothing there\n");
1582 		scsi_unprobe(devp);
1583 		return (DDI_FAILURE);
1584 	}
1585 
1586 
1587 	/*
1588 	 * The actual unit is present.
1589 	 * Now is the time to fill in the rest of our info..
1590 	 */
1591 	instance = ddi_get_instance(devp->sd_dev);
1592 
1593 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1594 		goto error;
1595 	}
1596 	un = ddi_get_soft_state(st_state, instance);
1597 
1598 	ASSERT(un != NULL);
1599 
1600 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
1601 	    MAX_SENSE_LENGTH, B_READ, canwait, NULL);
1602 	if (un->un_rqs_bp == NULL) {
1603 		goto error;
1604 	}
1605 	un->un_rqs = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
1606 	    CDB_GROUP0, 1, st_recov_sz, PKT_CONSISTENT, canwait, NULL);
1607 	if (!un->un_rqs) {
1608 		goto error;
1609 	}
1610 	ASSERT(un->un_rqs->pkt_resid == 0);
1611 	devp->sd_sense =
1612 	    (struct scsi_extended_sense *)un->un_rqs_bp->b_un.b_addr;
1613 	ASSERT(geterror(un->un_rqs_bp) == NULL);
1614 
1615 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs->pkt_cdbp,
1616 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
1617 	FILL_SCSI1_LUN(devp, un->un_rqs);
1618 	un->un_rqs->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1619 	un->un_rqs->pkt_time = st_io_time;
1620 	un->un_rqs->pkt_comp = st_intr;
1621 	ri = (recov_info *)un->un_rqs->pkt_private;
1622 	if (st_recov_sz == sizeof (recov_info)) {
1623 		ri->privatelen = sizeof (recov_info);
1624 	} else {
1625 		ri->privatelen = sizeof (pkt_info);
1626 	}
1627 
1628 	un->un_sbufp = getrbuf(km_flags);
1629 	un->un_recov_buf = getrbuf(km_flags);
1630 
1631 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1632 
1633 	/*
1634 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1635 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1636 	 * is obsolete and we want more flexibility in controlling the DMA
1637 	 * address constraints.
1638 	 */
1639 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1640 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1641 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1642 
1643 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1644 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1645 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1646 
1647 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1648 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1649 		    "probe partial failure: no space\n");
1650 		goto error;
1651 	}
1652 
1653 	bzero(un->un_mspl, sizeof (struct seq_mode));
1654 
1655 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1656 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1657 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1658 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1659 #ifdef	__x86
1660 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1661 #endif
1662 
1663 	/* Initialize power managemnet condition variable */
1664 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1665 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1666 	cv_init(&un->un_recov_buf_cv, NULL, CV_DRIVER, NULL);
1667 
1668 	un->un_recov_taskq = ddi_taskq_create(devp->sd_dev,
1669 	    "un_recov_taskq", 1, TASKQ_DEFAULTPRI, km_flags);
1670 
1671 	ASSERT(un->un_recov_taskq != NULL);
1672 
1673 	un->un_pos.pmode = invalid;
1674 	un->un_sd	= devp;
1675 	un->un_swr_token = (opaque_t)NULL;
1676 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1677 	un->un_wormable = st_is_drive_worm;
1678 	un->un_media_id_method = st_get_media_identification;
1679 	/*
1680 	 * setting long a initial as it contains logical file info.
1681 	 * support for long format is mandatory but many drive don't do it.
1682 	 */
1683 	un->un_read_pos_type = LONG_POS;
1684 
1685 	un->un_suspend_pos.pmode = invalid;
1686 
1687 #ifdef	__x86
1688 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1689 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1690 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1691 		    "allocation of contiguous memory dma handle failed!");
1692 		un->un_contig_mem_hdl = NULL;
1693 		goto error;
1694 	}
1695 #endif
1696 
1697 	/*
1698 	 * Since this driver manages devices with "remote" hardware,
1699 	 * i.e. the devices themselves have no "reg" properties,
1700 	 * the SUSPEND/RESUME commands in detach/attach will not be
1701 	 * called by the power management framework unless we request
1702 	 * it by creating a "pm-hardware-state" property and setting it
1703 	 * to value "needs-suspend-resume".
1704 	 */
1705 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1706 	    "pm-hardware-state", "needs-suspend-resume") !=
1707 	    DDI_PROP_SUCCESS) {
1708 
1709 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1710 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1711 		goto error;
1712 	}
1713 
1714 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1715 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1716 
1717 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1718 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1719 		    "failed\n");
1720 		goto error;
1721 	}
1722 
1723 	(void) scsi_reset_notify(ROUTE, SCSI_RESET_NOTIFY,
1724 	    st_reset_notification, (caddr_t)un);
1725 
1726 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "attach success\n");
1727 	return (DDI_SUCCESS);
1728 
1729 error:
1730 	devp->sd_sense = NULL;
1731 
1732 	ddi_remove_minor_node(devp->sd_dev, NULL);
1733 	if (un) {
1734 		if (un->un_mspl) {
1735 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1736 		}
1737 		if (un->un_read_pos_data) {
1738 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1739 		}
1740 		if (un->un_sbufp) {
1741 			freerbuf(un->un_sbufp);
1742 		}
1743 		if (un->un_recov_buf) {
1744 			freerbuf(un->un_recov_buf);
1745 		}
1746 		if (un->un_uscsi_rqs_buf) {
1747 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1748 		}
1749 #ifdef	__x86
1750 		if (un->un_contig_mem_hdl != NULL) {
1751 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1752 		}
1753 #endif
1754 		if (un->un_rqs) {
1755 			scsi_destroy_pkt(un->un_rqs);
1756 		}
1757 
1758 		if (un->un_rqs_bp) {
1759 			scsi_free_consistent_buf(un->un_rqs_bp);
1760 		}
1761 
1762 		ddi_soft_state_free(st_state, instance);
1763 		devp->sd_private = NULL;
1764 	}
1765 
1766 	if (devp->sd_inq) {
1767 		scsi_unprobe(devp);
1768 	}
1769 	return (DDI_FAILURE);
1770 }
1771 
1772 typedef int
1773 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1774 
1775 static cfg_functp config_functs[] = {
1776 	st_get_conf_from_st_dot_conf,
1777 	st_get_conf_from_st_conf_dot_c,
1778 	st_get_conf_from_tape_drive,
1779 	st_get_default_conf
1780 };
1781 
1782 
1783 /*
1784  * determine tape type, using tape-config-list or built-in table or
1785  * use a generic tape config entry
1786  */
1787 static void
1788 st_known_tape_type(struct scsi_tape *un)
1789 {
1790 	struct st_drivetype *dp;
1791 	cfg_functp *config_funct;
1792 	uchar_t reserved;
1793 
1794 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1795 
1796 	reserved = (un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1797 	    : ST_RELEASE;
1798 
1799 	/*
1800 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1801 	 *	 no vid & pid inquiry data.  So, we provide one.
1802 	 */
1803 	if (ST_INQUIRY->inq_len == 0 ||
1804 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1805 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1806 	}
1807 
1808 	if (un->un_dp_size == 0) {
1809 		un->un_dp_size = sizeof (struct st_drivetype);
1810 		dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1811 		un->un_dp = dp;
1812 	} else {
1813 		dp = un->un_dp;
1814 	}
1815 
1816 	un->un_dp->non_motion_timeout = st_io_time;
1817 	/*
1818 	 * Loop through the configuration methods till one works.
1819 	 */
1820 	for (config_funct = &config_functs[0]; ; config_funct++) {
1821 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1822 			break;
1823 		}
1824 	}
1825 
1826 	/*
1827 	 * If we didn't just make up this configuration and
1828 	 * all the density codes are the same..
1829 	 * Set Auto Density over ride.
1830 	 */
1831 	if (*config_funct != st_get_default_conf) {
1832 		/*
1833 		 * If this device is one that is configured and all
1834 		 * densities are the same, This saves doing gets and set
1835 		 * that yield nothing.
1836 		 */
1837 		if ((dp->densities[0]) == (dp->densities[1]) &&
1838 		    (dp->densities[0]) == (dp->densities[2]) &&
1839 		    (dp->densities[0]) == (dp->densities[3])) {
1840 
1841 			dp->options |= ST_AUTODEN_OVERRIDE;
1842 		}
1843 	}
1844 
1845 
1846 	/*
1847 	 * Store tape drive characteristics.
1848 	 */
1849 	un->un_status = 0;
1850 	un->un_attached = 1;
1851 	un->un_init_options = dp->options;
1852 
1853 	/* setup operation time-outs based on options */
1854 	st_calculate_timeouts(un);
1855 
1856 	/* make sure if we are supposed to be variable, make it variable */
1857 	if (dp->options & ST_VARIABLE) {
1858 		dp->bsize = 0;
1859 	}
1860 
1861 	if (reserved != ((un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1862 	    : ST_RELEASE)) {
1863 		(void) st_reserve_release(un, reserved, st_uscsi_cmd);
1864 	}
1865 
1866 	un->un_unit_attention_flags = 1;
1867 
1868 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1869 
1870 }
1871 
1872 
1873 typedef struct {
1874 	int mask;
1875 	int bottom;
1876 	int top;
1877 	char *name;
1878 } conf_limit;
1879 
1880 static const conf_limit conf_limits[] = {
1881 
1882 	-1,		1,		2,		"conf version",
1883 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1884 	-1,		0,		0xffffff,	"block size",
1885 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1886 	-1,		0,		4,		"number of densities",
1887 	-1,		0,		UINT8_MAX,	"density code",
1888 	-1,		0,		3,		"default density",
1889 	-1,		0,		UINT16_MAX,	"non motion timeout",
1890 	-1,		0,		UINT16_MAX,	"I/O timeout",
1891 	-1,		0,		UINT16_MAX,	"space timeout",
1892 	-1,		0,		UINT16_MAX,	"load timeout",
1893 	-1,		0,		UINT16_MAX,	"unload timeout",
1894 	-1,		0,		UINT16_MAX,	"erase timeout",
1895 	0,		0,		0,		NULL
1896 };
1897 
1898 static int
1899 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1900     const char *conf_name)
1901 {
1902 	int dens;
1903 	int ndens;
1904 	int value;
1905 	int type;
1906 	int count;
1907 	const conf_limit *limit = &conf_limits[0];
1908 
1909 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1910 
1911 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1912 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1913 
1914 	count = list_len;
1915 	type = *list;
1916 	for (;  count && limit->name; count--, list++, limit++) {
1917 
1918 		value = *list;
1919 		if (value & ~limit->mask) {
1920 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1921 			    "%s %s value invalid bits set: 0x%X\n",
1922 			    conf_name, limit->name, value & ~limit->mask);
1923 			*list &= limit->mask;
1924 		} else if (value < limit->bottom) {
1925 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1926 			    "%s %s value too low: value = %d limit %d\n",
1927 			    conf_name, limit->name, value, limit->bottom);
1928 		} else if (value > limit->top) {
1929 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1930 			    "%s %s value too high: value = %d limit %d\n",
1931 			    conf_name, limit->name, value, limit->top);
1932 		} else {
1933 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1934 			    "%s %s value = 0x%X\n",
1935 			    conf_name, limit->name, value);
1936 		}
1937 
1938 		/* If not the number of densities continue */
1939 		if (limit != &conf_limits[4]) {
1940 			continue;
1941 		}
1942 
1943 		/* If number of densities is not in range can't use config */
1944 		if (value < limit->bottom || value > limit->top) {
1945 			return (-1);
1946 		}
1947 
1948 		ndens = min(value, NDENSITIES);
1949 		if ((type == 1) && (list_len - ndens) != 6) {
1950 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1951 			    "%s conf version 1 with %d densities has %d items"
1952 			    " should have %d",
1953 			    conf_name, ndens, list_len, 6 + ndens);
1954 		} else if ((type == 2) && (list_len - ndens) != 13) {
1955 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1956 			    "%s conf version 2 with %d densities has %d items"
1957 			    " should have %d",
1958 			    conf_name, ndens, list_len, 13 + ndens);
1959 		}
1960 
1961 		limit++;
1962 		for (dens = 0; dens < ndens && count; dens++) {
1963 			count--;
1964 			list++;
1965 			value = *list;
1966 			if (value < limit->bottom) {
1967 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1968 				    "%s density[%d] value too low: value ="
1969 				    " 0x%X limit 0x%X\n",
1970 				    conf_name, dens, value, limit->bottom);
1971 			} else if (value > limit->top) {
1972 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1973 				    "%s density[%d] value too high: value ="
1974 				    " 0x%X limit 0x%X\n",
1975 				    conf_name, dens, value, limit->top);
1976 			} else {
1977 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1978 				    "%s density[%d] value = 0x%X\n",
1979 				    conf_name, dens, value);
1980 			}
1981 		}
1982 	}
1983 
1984 	return (0);
1985 }
1986 
1987 static int
1988 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
1989     struct st_drivetype *dp)
1990 {
1991 	caddr_t config_list = NULL;
1992 	caddr_t data_list = NULL;
1993 	int	*data_ptr;
1994 	caddr_t vidptr, prettyptr, datanameptr;
1995 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
1996 	int config_list_len, data_list_len, len, i;
1997 	int version;
1998 	int found = 0;
1999 
2000 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
2001 
2002 	/*
2003 	 * Determine type of tape controller. Type is determined by
2004 	 * checking the vendor ids of the earlier inquiry command and
2005 	 * comparing those with vids in tape-config-list defined in st.conf
2006 	 */
2007 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
2008 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
2009 	    != DDI_PROP_SUCCESS) {
2010 		return (found);
2011 	}
2012 
2013 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2014 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
2015 
2016 	/*
2017 	 * Compare vids in each triplet - if it matches, get value for
2018 	 * data_name and contruct a st_drivetype struct
2019 	 * tripletlen is not set yet!
2020 	 */
2021 	for (len = config_list_len, vidptr = config_list;
2022 	    len > 0;
2023 	    vidptr += tripletlen, len -= tripletlen) {
2024 
2025 		vidlen = strlen(vidptr);
2026 		prettyptr = vidptr + vidlen + 1;
2027 		prettylen = strlen(prettyptr);
2028 		datanameptr = prettyptr + prettylen + 1;
2029 		datanamelen = strlen(datanameptr);
2030 		tripletlen = vidlen + prettylen + datanamelen + 3;
2031 
2032 		if (vidlen == 0) {
2033 			continue;
2034 		}
2035 
2036 		/*
2037 		 * If inquiry vid dosen't match this triplets vid,
2038 		 * try the next.
2039 		 */
2040 		if (strncasecmp(vidpid, vidptr, vidlen)) {
2041 			continue;
2042 		}
2043 
2044 		/*
2045 		 * if prettylen is zero then use the vid string
2046 		 */
2047 		if (prettylen == 0) {
2048 			prettyptr = vidptr;
2049 			prettylen = vidlen;
2050 		}
2051 
2052 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2053 		    "vid = %s, pretty=%s, dataname = %s\n",
2054 		    vidptr, prettyptr, datanameptr);
2055 
2056 		/*
2057 		 * get the data list
2058 		 */
2059 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
2060 		    datanameptr, (caddr_t)&data_list,
2061 		    &data_list_len) != DDI_PROP_SUCCESS) {
2062 			/*
2063 			 * Error in getting property value
2064 			 * print warning!
2065 			 */
2066 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2067 			    "data property (%s) has no value\n",
2068 			    datanameptr);
2069 			continue;
2070 		}
2071 
2072 		/*
2073 		 * now initialize the st_drivetype struct
2074 		 */
2075 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
2076 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
2077 		(void) strncpy(dp->vid, vidptr, dp->length);
2078 		data_ptr = (int *)data_list;
2079 		/*
2080 		 * check if data is enough for version, type,
2081 		 * bsize, options, # of densities, density1,
2082 		 * density2, ..., default_density
2083 		 */
2084 		if ((data_list_len < 5 * sizeof (int)) ||
2085 		    (data_list_len < 6 * sizeof (int) +
2086 		    *(data_ptr + 4) * sizeof (int))) {
2087 			/*
2088 			 * print warning and skip to next triplet.
2089 			 */
2090 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2091 			    "data property (%s) incomplete\n",
2092 			    datanameptr);
2093 			kmem_free(data_list, data_list_len);
2094 			continue;
2095 		}
2096 
2097 		if (st_validate_conf_data(un, data_ptr,
2098 		    data_list_len / sizeof (int), datanameptr)) {
2099 			kmem_free(data_list, data_list_len);
2100 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2101 			    "data property (%s) rejected\n",
2102 			    datanameptr);
2103 			continue;
2104 		}
2105 
2106 		/*
2107 		 * check version
2108 		 */
2109 		version = *data_ptr++;
2110 		if (version != 1 && version != 2) {
2111 			/* print warning but accept it */
2112 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2113 			    "Version # for data property (%s) "
2114 			    "not set to 1 or 2\n", datanameptr);
2115 		}
2116 
2117 		dp->type    = *data_ptr++;
2118 		dp->bsize   = *data_ptr++;
2119 		dp->options = *data_ptr++;
2120 		dp->options |= ST_DYNAMIC;
2121 		len = *data_ptr++;
2122 		for (i = 0; i < NDENSITIES; i++) {
2123 			if (i < len) {
2124 				dp->densities[i] = *data_ptr++;
2125 			}
2126 		}
2127 		dp->default_density = *data_ptr << 3;
2128 		if (version == 2 &&
2129 		    data_list_len >= (13 + len) * sizeof (int)) {
2130 			data_ptr++;
2131 			dp->non_motion_timeout	= *data_ptr++;
2132 			dp->io_timeout		= *data_ptr++;
2133 			dp->rewind_timeout	= *data_ptr++;
2134 			dp->space_timeout	= *data_ptr++;
2135 			dp->load_timeout	= *data_ptr++;
2136 			dp->unload_timeout	= *data_ptr++;
2137 			dp->erase_timeout	= *data_ptr++;
2138 		}
2139 		kmem_free(data_list, data_list_len);
2140 		found = 1;
2141 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2142 		    "found in st.conf: vid = %s, pretty=%s\n",
2143 		    dp->vid, dp->name);
2144 		break;
2145 	}
2146 
2147 	/*
2148 	 * free up the memory allocated by ddi_getlongprop
2149 	 */
2150 	if (config_list) {
2151 		kmem_free(config_list, config_list_len);
2152 	}
2153 	return (found);
2154 }
2155 
2156 static int
2157 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2158     struct st_drivetype *dp)
2159 {
2160 	int i;
2161 
2162 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2163 	/*
2164 	 * Determine type of tape controller.  Type is determined by
2165 	 * checking the result of the earlier inquiry command and
2166 	 * comparing vendor ids with strings in a table declared in st_conf.c.
2167 	 */
2168 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2169 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2170 
2171 	for (i = 0; i < st_ndrivetypes; i++) {
2172 		if (st_drivetypes[i].length == 0) {
2173 			continue;
2174 		}
2175 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2176 		    st_drivetypes[i].length)) {
2177 			continue;
2178 		}
2179 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2180 		return (1);
2181 	}
2182 	return (0);
2183 }
2184 
2185 static int
2186 st_get_conf_from_tape_drive(struct scsi_tape *un, char *vidpid,
2187     struct st_drivetype *dp)
2188 {
2189 	int bsize;
2190 	ulong_t maxbsize;
2191 	caddr_t buf;
2192 	struct st_drivetype *tem_dp;
2193 	struct read_blklim *blklim;
2194 	int rval;
2195 	int i;
2196 
2197 	ST_FUNC(ST_DEVINFO, st_get_conf_from_tape_drive);
2198 
2199 	/*
2200 	 * Determine the type of tape controller. Type is determined by
2201 	 * sending SCSI commands to tape drive and deriving the type from
2202 	 * the returned data.
2203 	 */
2204 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2205 	    "st_get_conf_from_tape_drive(): asking tape drive\n");
2206 
2207 	tem_dp = kmem_zalloc(sizeof (struct st_drivetype), KM_SLEEP);
2208 
2209 	/*
2210 	 * Make up a name
2211 	 */
2212 	bcopy(vidpid, tem_dp->name, VIDPIDLEN);
2213 	tem_dp->name[VIDPIDLEN] = '\0';
2214 	tem_dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2215 	(void) strncpy(tem_dp->vid, ST_INQUIRY->inq_vid, tem_dp->length);
2216 	/*
2217 	 * 'clean' vendor and product strings of non-printing chars
2218 	 */
2219 	for (i = 0; i < VIDPIDLEN - 1; i ++) {
2220 		if (tem_dp->name[i] < ' ' || tem_dp->name[i] > '~') {
2221 			tem_dp->name[i] = '.';
2222 		}
2223 	}
2224 
2225 	/*
2226 	 * MODE SENSE to determine block size.
2227 	 */
2228 	un->un_dp->options |= ST_MODE_SEL_COMP | ST_UNLOADABLE;
2229 	rval = st_modesense(un);
2230 	if (rval) {
2231 		if (rval == EACCES) {
2232 			un->un_dp->type = ST_TYPE_INVALID;
2233 			rval = 1;
2234 		} else {
2235 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
2236 			rval = 0;
2237 		}
2238 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2239 		    "st_get_conf_from_tape_drive(): fail to mode sense\n");
2240 		goto exit;
2241 	}
2242 
2243 	/* Can mode sense page 0x10 or 0xf */
2244 	tem_dp->options |= ST_MODE_SEL_COMP;
2245 	bsize = (un->un_mspl->high_bl << 16)	|
2246 	    (un->un_mspl->mid_bl << 8)		|
2247 	    (un->un_mspl->low_bl);
2248 
2249 	if (bsize == 0) {
2250 		tem_dp->options |= ST_VARIABLE;
2251 		tem_dp->bsize = 0;
2252 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
2253 		rval = st_change_block_size(un, 0);
2254 		if (rval) {
2255 			if (rval == EACCES) {
2256 				un->un_dp->type = ST_TYPE_INVALID;
2257 				rval = 1;
2258 			} else {
2259 				rval = 0;
2260 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2261 				    "st_get_conf_from_tape_drive(): "
2262 				    "Fixed record size is too large and"
2263 				    "cannot switch to variable record size");
2264 			}
2265 			goto exit;
2266 		}
2267 		tem_dp->options |= ST_VARIABLE;
2268 	} else {
2269 		rval = st_change_block_size(un, 0);
2270 		if (rval == 0) {
2271 			tem_dp->options |= ST_VARIABLE;
2272 			tem_dp->bsize = 0;
2273 		} else if (rval != EACCES) {
2274 			tem_dp->bsize = bsize;
2275 		} else {
2276 			un->un_dp->type = ST_TYPE_INVALID;
2277 			rval = 1;
2278 			goto exit;
2279 		}
2280 	}
2281 
2282 	/*
2283 	 * If READ BLOCk LIMITS works and upper block size limit is
2284 	 * more than 64K, ST_NO_RECSIZE_LIMIT is supported.
2285 	 */
2286 	blklim = kmem_zalloc(sizeof (struct read_blklim), KM_SLEEP);
2287 	rval = st_read_block_limits(un, blklim);
2288 	if (rval) {
2289 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2290 		    "st_get_conf_from_tape_drive(): "
2291 		    "fail to read block limits.\n");
2292 		rval = 0;
2293 		kmem_free(blklim, sizeof (struct read_blklim));
2294 		goto exit;
2295 	}
2296 	maxbsize = (blklim->max_hi << 16) +
2297 	    (blklim->max_mid << 8) + blklim->max_lo;
2298 	if (maxbsize > ST_MAXRECSIZE_VARIABLE) {
2299 		tem_dp->options |= ST_NO_RECSIZE_LIMIT;
2300 	}
2301 	kmem_free(blklim, sizeof (struct read_blklim));
2302 
2303 	/*
2304 	 * Inquiry VPD page 0xb0 to see if the tape drive supports WORM
2305 	 */
2306 	buf = kmem_zalloc(6, KM_SLEEP);
2307 	rval = st_get_special_inquiry(un, 6, buf, 0xb0);
2308 	if (rval) {
2309 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2310 		    "st_get_conf_from_tape_drive(): "
2311 		    "fail to read vitial inquiry.\n");
2312 		rval = 0;
2313 		kmem_free(buf, 6);
2314 		goto exit;
2315 	}
2316 	if (buf[4] & 1) {
2317 		tem_dp->options |= ST_WORMABLE;
2318 	}
2319 	kmem_free(buf, 6);
2320 
2321 	/* Assume BSD BSR KNOWS_EOD */
2322 	tem_dp->options |= ST_BSF | ST_BSR | ST_KNOWS_EOD | ST_UNLOADABLE;
2323 	tem_dp->max_rretries = -1;
2324 	tem_dp->max_wretries = -1;
2325 
2326 	/*
2327 	 * Decide the densities supported by tape drive by sending
2328 	 * REPORT DENSITY SUPPORT command.
2329 	 */
2330 	if (st_get_densities_from_tape_drive(un, tem_dp) == 0) {
2331 		goto exit;
2332 	}
2333 
2334 	/*
2335 	 * Decide the timeout values for several commands by sending
2336 	 * REPORT SUPPORTED OPERATION CODES command.
2337 	 */
2338 	rval = st_get_timeout_values_from_tape_drive(un, tem_dp);
2339 	if (rval == 0 || ((rval == 1) && (tem_dp->type == ST_TYPE_INVALID))) {
2340 		goto exit;
2341 	}
2342 
2343 	bcopy(tem_dp, dp, sizeof (struct st_drivetype));
2344 	rval = 1;
2345 
2346 exit:
2347 	un->un_status = KEY_NO_SENSE;
2348 	kmem_free(tem_dp, sizeof (struct st_drivetype));
2349 	return (rval);
2350 }
2351 
2352 static int
2353 st_get_densities_from_tape_drive(struct scsi_tape *un,
2354     struct st_drivetype *dp)
2355 {
2356 	int i, p;
2357 	size_t buflen;
2358 	ushort_t des_len;
2359 	uchar_t *den_header;
2360 	uchar_t num_den;
2361 	uchar_t den[NDENSITIES];
2362 	uchar_t deflt[NDENSITIES];
2363 	struct report_density_desc *den_desc;
2364 
2365 	ST_FUNC(ST_DEVINFO, st_get_densities_from_type_drive);
2366 
2367 	/*
2368 	 * Since we have no idea how many densitiy support entries
2369 	 * will be returned, we send the command firstly assuming
2370 	 * there is only one. Then we can decide the number of
2371 	 * entries by available density support length. If multiple
2372 	 * entries exist, we will resend the command with enough
2373 	 * buffer size.
2374 	 */
2375 	buflen = sizeof (struct report_density_header) +
2376 	    sizeof (struct report_density_desc);
2377 	den_header = kmem_zalloc(buflen, KM_SLEEP);
2378 	if (st_report_density_support(un, den_header, buflen) != 0) {
2379 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2380 		    "st_get_conf_from_tape_drive(): fail to report density.\n");
2381 		kmem_free(den_header, buflen);
2382 		return (0);
2383 	}
2384 	des_len =
2385 	    BE_16(((struct report_density_header *)den_header)->ava_dens_len);
2386 	num_den = (des_len - 2) / sizeof (struct report_density_desc);
2387 
2388 	if (num_den > 1) {
2389 		kmem_free(den_header, buflen);
2390 		buflen = sizeof (struct report_density_header) +
2391 		    sizeof (struct report_density_desc) * num_den;
2392 		den_header = kmem_zalloc(buflen, KM_SLEEP);
2393 		if (st_report_density_support(un, den_header, buflen) != 0) {
2394 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2395 			    "st_get_conf_from_tape_drive(): "
2396 			    "fail to report density.\n");
2397 			kmem_free(den_header, buflen);
2398 			return (0);
2399 		}
2400 	}
2401 
2402 	den_desc = (struct report_density_desc *)(den_header
2403 	    + sizeof (struct report_density_header));
2404 
2405 	/*
2406 	 * Decide the drive type by assigning organization
2407 	 */
2408 	for (i = 0; i < ST_NUM_MEMBERS(st_vid_dt); i ++) {
2409 		if (strncmp(st_vid_dt[i].vid, (char *)(den_desc->ass_org),
2410 		    8) == 0) {
2411 			dp->type = st_vid_dt[i].type;
2412 			break;
2413 		}
2414 	}
2415 	if (i == ST_NUM_MEMBERS(st_vid_dt)) {
2416 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2417 		    "st_get_conf_from_tape_drive(): "
2418 		    "can't find match of assigned ort.\n");
2419 		kmem_free(den_header, buflen);
2420 		return (0);
2421 	}
2422 
2423 	/*
2424 	 * The tape drive may support many tape formats, but the st driver
2425 	 * supports only the four highest densities. Since density code
2426 	 * values are returned by ascending sequence, we start from the
2427 	 * last entry of density support data block descriptor.
2428 	 */
2429 	p = 0;
2430 	den_desc += num_den - 1;
2431 	for (i = 0; i < num_den && p < NDENSITIES; i ++, den_desc --) {
2432 		if ((den_desc->pri_den != 0) && (den_desc->wrtok)) {
2433 			if (p != 0) {
2434 				if (den_desc->pri_den >= den[p - 1]) {
2435 					continue;
2436 				}
2437 			}
2438 			den[p] = den_desc->pri_den;
2439 			deflt[p] = den_desc->deflt;
2440 			p ++;
2441 		}
2442 	}
2443 
2444 	switch (p) {
2445 	case 0:
2446 		bzero(dp->densities, NDENSITIES);
2447 		dp->options |= ST_AUTODEN_OVERRIDE;
2448 		dp->default_density = MT_DENSITY4;
2449 		break;
2450 
2451 	case 1:
2452 		(void) memset(dp->densities, den[0], NDENSITIES);
2453 		dp->options |= ST_AUTODEN_OVERRIDE;
2454 		dp->default_density = MT_DENSITY4;
2455 		break;
2456 
2457 	case 2:
2458 		dp->densities[0] = den[1];
2459 		dp->densities[1] = den[1];
2460 		dp->densities[2] = den[0];
2461 		dp->densities[3] = den[0];
2462 		if (deflt[0]) {
2463 			dp->default_density = MT_DENSITY4;
2464 		} else {
2465 			dp->default_density = MT_DENSITY2;
2466 		}
2467 		break;
2468 
2469 	case 3:
2470 		dp->densities[0] = den[2];
2471 		dp->densities[1] = den[1];
2472 		dp->densities[2] = den[0];
2473 		dp->densities[3] = den[0];
2474 		if (deflt[0]) {
2475 			dp->default_density = MT_DENSITY4;
2476 		} else if (deflt[1]) {
2477 			dp->default_density = MT_DENSITY2;
2478 		} else {
2479 			dp->default_density = MT_DENSITY1;
2480 		}
2481 		break;
2482 
2483 	default:
2484 		for (i = p; i > p - NDENSITIES; i --) {
2485 			dp->densities[i - 1] = den[p - i];
2486 		}
2487 		if (deflt[0]) {
2488 			dp->default_density = MT_DENSITY4;
2489 		} else if (deflt[1]) {
2490 			dp->default_density = MT_DENSITY3;
2491 		} else if (deflt[2]) {
2492 			dp->default_density = MT_DENSITY2;
2493 		} else {
2494 			dp->default_density = MT_DENSITY1;
2495 		}
2496 		break;
2497 	}
2498 
2499 	bzero(dp->mediatype, NDENSITIES);
2500 
2501 	kmem_free(den_header, buflen);
2502 	return (1);
2503 }
2504 
2505 static int
2506 st_get_timeout_values_from_tape_drive(struct scsi_tape *un,
2507     struct st_drivetype *dp)
2508 {
2509 	ushort_t timeout;
2510 	int rval;
2511 
2512 	ST_FUNC(ST_DEVINFO, st_get_timeout_values_from_type_drive);
2513 
2514 	rval = st_get_timeouts_value(un, SCMD_ERASE, &timeout, 0);
2515 	if (rval) {
2516 		if (rval == EACCES) {
2517 			un->un_dp->type = ST_TYPE_INVALID;
2518 			dp->type = ST_TYPE_INVALID;
2519 			return (1);
2520 		}
2521 		return (0);
2522 	}
2523 	dp->erase_timeout = timeout;
2524 
2525 	rval = st_get_timeouts_value(un, SCMD_READ, &timeout, 0);
2526 	if (rval) {
2527 		if (rval == EACCES) {
2528 			un->un_dp->type = ST_TYPE_INVALID;
2529 			dp->type = ST_TYPE_INVALID;
2530 			return (1);
2531 		}
2532 		return (0);
2533 	}
2534 	dp->io_timeout = timeout;
2535 
2536 	rval = st_get_timeouts_value(un, SCMD_WRITE, &timeout, 0);
2537 	if (rval) {
2538 		if (rval == EACCES) {
2539 			un->un_dp->type = ST_TYPE_INVALID;
2540 			dp->type = ST_TYPE_INVALID;
2541 			return (1);
2542 		}
2543 		return (0);
2544 	}
2545 	dp->io_timeout = max(dp->io_timeout, timeout);
2546 
2547 	rval = st_get_timeouts_value(un, SCMD_SPACE, &timeout, 0);
2548 	if (rval) {
2549 		if (rval == EACCES) {
2550 			un->un_dp->type = ST_TYPE_INVALID;
2551 			dp->type = ST_TYPE_INVALID;
2552 			return (1);
2553 		}
2554 		return (0);
2555 	}
2556 	dp->space_timeout = timeout;
2557 
2558 	rval = st_get_timeouts_value(un, SCMD_LOAD, &timeout, 0);
2559 	if (rval) {
2560 		if (rval == EACCES) {
2561 			un->un_dp->type = ST_TYPE_INVALID;
2562 			dp->type = ST_TYPE_INVALID;
2563 			return (1);
2564 		}
2565 		return (0);
2566 	}
2567 	dp->load_timeout = timeout;
2568 	dp->unload_timeout = timeout;
2569 
2570 	rval = st_get_timeouts_value(un, SCMD_REWIND, &timeout, 0);
2571 	if (rval) {
2572 		if (rval == EACCES) {
2573 			un->un_dp->type = ST_TYPE_INVALID;
2574 			dp->type = ST_TYPE_INVALID;
2575 			return (1);
2576 		}
2577 		return (0);
2578 	}
2579 	dp->rewind_timeout = timeout;
2580 
2581 	rval = st_get_timeouts_value(un, SCMD_INQUIRY, &timeout, 0);
2582 	if (rval) {
2583 		if (rval == EACCES) {
2584 			un->un_dp->type = ST_TYPE_INVALID;
2585 			dp->type = ST_TYPE_INVALID;
2586 			return (1);
2587 		}
2588 		return (0);
2589 	}
2590 	dp->non_motion_timeout = timeout;
2591 
2592 	return (1);
2593 }
2594 
2595 static int
2596 st_get_timeouts_value(struct scsi_tape *un, uchar_t option_code,
2597     ushort_t *timeout_value, ushort_t service_action)
2598 {
2599 	uchar_t *timeouts;
2600 	uchar_t *oper;
2601 	uchar_t support;
2602 	uchar_t cdbsize;
2603 	uchar_t ctdp;
2604 	size_t buflen;
2605 	int rval;
2606 
2607 	ST_FUNC(ST_DEVINFO, st_get_timeouts_value);
2608 
2609 	buflen = sizeof (struct one_com_des) +
2610 	    sizeof (struct com_timeout_des);
2611 	oper = kmem_zalloc(buflen, KM_SLEEP);
2612 	rval = st_report_supported_operation(un, oper, option_code,
2613 	    service_action);
2614 
2615 	if (rval) {
2616 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2617 		    "st_get_timeouts_value(): "
2618 		    "fail to timeouts value for command %d.\n", option_code);
2619 		kmem_free(oper, buflen);
2620 		return (rval);
2621 	}
2622 
2623 	support = ((struct one_com_des *)oper)->support;
2624 	if ((support != SUPPORT_VALUES_SUPPORT_SCSI) &&
2625 	    (support != SUPPORT_VALUES_SUPPORT_VENDOR)) {
2626 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2627 		    "st_get_timeouts_value(): "
2628 		    "command %d is not supported.\n", option_code);
2629 		kmem_free(oper, buflen);
2630 		return (ENOTSUP);
2631 	}
2632 
2633 	ctdp = ((struct one_com_des *)oper)->ctdp;
2634 	if (!ctdp) {
2635 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2636 		    "st_get_timeouts_value(): "
2637 		    "command timeout is not included.\n");
2638 		kmem_free(oper, buflen);
2639 		return (ENOTSUP);
2640 	}
2641 
2642 	cdbsize = BE_16(((struct one_com_des *)oper)->cdb_size);
2643 	timeouts = (uchar_t *)(oper + cdbsize + 4);
2644 
2645 	/*
2646 	 * Timeout value in seconds is 4 bytes, but we only support the lower 2
2647 	 * bytes. If the higher 2 bytes are not zero, the timeout value is set
2648 	 * to 0xFFFF.
2649 	 */
2650 	if (*(timeouts + 8) != 0 || *(timeouts + 9) != 0) {
2651 		*timeout_value = USHRT_MAX;
2652 	} else {
2653 		*timeout_value = ((*(timeouts + 10)) << 8) |
2654 		    (*(timeouts + 11));
2655 	}
2656 
2657 	kmem_free(oper, buflen);
2658 	return (0);
2659 }
2660 
2661 static int
2662 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2663 {
2664 	int i;
2665 
2666 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2667 
2668 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2669 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2670 
2671 	/*
2672 	 * Make up a name
2673 	 */
2674 	bcopy("Vendor '", dp->name, 8);
2675 	bcopy(vidpid, &dp->name[8], VIDLEN);
2676 	bcopy("' Product '", &dp->name[16], 11);
2677 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2678 	dp->name[ST_NAMESIZE - 2] = '\'';
2679 	dp->name[ST_NAMESIZE - 1] = '\0';
2680 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2681 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2682 	/*
2683 	 * 'clean' vendor and product strings of non-printing chars
2684 	 */
2685 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2686 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2687 			dp->name[i] = '.';
2688 		}
2689 	}
2690 	dp->type = ST_TYPE_INVALID;
2691 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2692 
2693 	return (1); /* Can Not Fail */
2694 }
2695 
2696 /*
2697  * Regular Unix Entry points
2698  */
2699 
2700 
2701 
2702 /* ARGSUSED */
2703 static int
2704 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2705 {
2706 	dev_t dev = *dev_p;
2707 	int rval = 0;
2708 
2709 	GET_SOFT_STATE(dev);
2710 
2711 	ST_ENTR(ST_DEVINFO, st_open);
2712 
2713 	/*
2714 	 * validate that we are addressing a sensible unit
2715 	 */
2716 	mutex_enter(ST_MUTEX);
2717 
2718 #ifdef	STDEBUG
2719 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2720 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2721 	    st_dev_name(dev), *dev_p, flag, otyp);
2722 #endif
2723 
2724 	/*
2725 	 * All device accesss go thru st_strategy() where we check
2726 	 * suspend status
2727 	 */
2728 
2729 	if (!un->un_attached) {
2730 		st_known_tape_type(un);
2731 		if (!un->un_attached) {
2732 			rval = ENXIO;
2733 			goto exit;
2734 		}
2735 
2736 	}
2737 
2738 	/*
2739 	 * Check for the case of the tape in the middle of closing.
2740 	 * This isn't simply a check of the current state, because
2741 	 * we could be in state of sensing with the previous state
2742 	 * that of closing.
2743 	 *
2744 	 * And don't allow multiple opens.
2745 	 */
2746 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2747 		un->un_laststate = un->un_state;
2748 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2749 		while (IS_CLOSING(un) ||
2750 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2751 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2752 				rval = EINTR;
2753 				un->un_state = un->un_laststate;
2754 				goto exit;
2755 			}
2756 		}
2757 	} else if (un->un_state != ST_STATE_CLOSED) {
2758 		rval = EBUSY;
2759 		goto busy;
2760 	}
2761 
2762 	/*
2763 	 * record current dev
2764 	 */
2765 	un->un_dev = dev;
2766 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2767 	un->un_errno = 0;	/* no errors yet */
2768 	un->un_restore_pos = 0;
2769 	un->un_rqs_state = 0;
2770 
2771 	/*
2772 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2773 	 * anything, leave internal states alone, if fileno >= 0
2774 	 */
2775 	if (flag & (FNDELAY | FNONBLOCK)) {
2776 		switch (un->un_pos.pmode) {
2777 
2778 		case invalid:
2779 			un->un_state = ST_STATE_OFFLINE;
2780 			break;
2781 
2782 		case legacy:
2783 			/*
2784 			 * If position is anything other than rewound.
2785 			 */
2786 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2787 				/*
2788 				 * set un_read_only/write-protect status.
2789 				 *
2790 				 * If the tape is not bot we can assume
2791 				 * that mspl->wp_status is set properly.
2792 				 * else
2793 				 * we need to do a mode sense/Tur once
2794 				 * again to get the actual tape status.(since
2795 				 * user might have replaced the tape)
2796 				 * Hence make the st state OFFLINE so that
2797 				 * we re-intialize the tape once again.
2798 				 */
2799 				un->un_read_only =
2800 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2801 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2802 			} else {
2803 				un->un_state = ST_STATE_OFFLINE;
2804 			}
2805 			break;
2806 		case logical:
2807 			if (un->un_pos.lgclblkno == 0) {
2808 				un->un_state = ST_STATE_OFFLINE;
2809 			} else {
2810 				un->un_read_only =
2811 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2812 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2813 			}
2814 			break;
2815 		}
2816 		rval = 0;
2817 	} else {
2818 		/*
2819 		 * Not opening O_NDELAY.
2820 		 */
2821 		un->un_state = ST_STATE_OPENING;
2822 
2823 		/*
2824 		 * Clear error entry stack
2825 		 */
2826 		st_empty_error_stack(un);
2827 
2828 		rval = st_tape_init(un);
2829 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2830 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2831 			rval = 0; /* so open doesn't fail */
2832 		} else if (rval) {
2833 			/*
2834 			 * Release the tape unit, if reserved and not
2835 			 * preserve reserve.
2836 			 */
2837 			if ((un->un_rsvd_status &
2838 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2839 				(void) st_reserve_release(un, ST_RELEASE,
2840 				    st_uscsi_cmd);
2841 			}
2842 		} else {
2843 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2844 		}
2845 	}
2846 
2847 exit:
2848 	/*
2849 	 * we don't want any uninvited guests scrogging our data when we're
2850 	 * busy with something, so for successful opens or failed opens
2851 	 * (except for EBUSY), reset these counters and state appropriately.
2852 	 */
2853 	if (rval != EBUSY) {
2854 		if (rval) {
2855 			un->un_state = ST_STATE_CLOSED;
2856 		}
2857 		un->un_err_resid = 0;
2858 		un->un_retry_ct = 0;
2859 		un->un_tran_retry_ct = 0;
2860 	}
2861 busy:
2862 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2863 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2864 	mutex_exit(ST_MUTEX);
2865 	return (rval);
2866 
2867 }
2868 
2869 static int
2870 st_tape_init(struct scsi_tape *un)
2871 {
2872 	int err;
2873 	int rval = 0;
2874 
2875 	ST_FUNC(ST_DEVINFO, st_tape_init);
2876 
2877 	ASSERT(mutex_owned(ST_MUTEX));
2878 
2879 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2880 	    "st_tape_init(un = 0x%p, oflags = %d)\n", (void*)un, un->un_oflags);
2881 
2882 	/*
2883 	 * Clean up after any errors left by 'last' close.
2884 	 * This also handles the case of the initial open.
2885 	 */
2886 	if (un->un_state != ST_STATE_INITIALIZING) {
2887 		un->un_laststate = un->un_state;
2888 		un->un_state = ST_STATE_OPENING;
2889 	}
2890 
2891 	un->un_kbytes_xferred = 0;
2892 
2893 	/*
2894 	 * do a throw away TUR to clear check condition
2895 	 */
2896 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2897 
2898 	/*
2899 	 * If test unit ready fails because the drive is reserved
2900 	 * by another host fail the open for no access.
2901 	 */
2902 	if (err) {
2903 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2904 			un->un_state = ST_STATE_CLOSED;
2905 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2906 			    "st_tape_init: RESERVATION CONFLICT\n");
2907 			rval = EACCES;
2908 			goto exit;
2909 		}
2910 	}
2911 
2912 	/*
2913 	 * Tape self identification could fail if the tape drive is used by
2914 	 * another host during attach time. We try to get the tape type
2915 	 * again. This is also applied to any posponed configuration methods.
2916 	 */
2917 	if (un->un_dp->type == ST_TYPE_INVALID) {
2918 		un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
2919 		st_known_tape_type(un);
2920 	}
2921 
2922 	/*
2923 	 * If the tape type is still invalid, try to determine the generic
2924 	 * configuration.
2925 	 */
2926 	if (un->un_dp->type == ST_TYPE_INVALID) {
2927 		rval = st_determine_generic(un);
2928 		if (rval) {
2929 			if (rval != EACCES) {
2930 				rval = EIO;
2931 			}
2932 			un->un_state = ST_STATE_CLOSED;
2933 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2934 			    "st_tape_init: %s invalid type\n",
2935 			    rval == EACCES ? "EACCES" : "EIO");
2936 			goto exit;
2937 		}
2938 		/*
2939 		 * If this is a Unknown Type drive,
2940 		 * Use the READ BLOCK LIMITS to determine if
2941 		 * allow large xfer is approprate if not globally
2942 		 * disabled with st_allow_large_xfer.
2943 		 */
2944 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
2945 	} else {
2946 
2947 		/*
2948 		 * If we allow_large_xfer (ie >64k) and have not yet found out
2949 		 * the max block size supported by the drive,
2950 		 * find it by issueing a READ_BLKLIM command.
2951 		 * if READ_BLKLIM cmd fails, assume drive doesn't
2952 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
2953 		 */
2954 		un->un_allow_large_xfer = st_allow_large_xfer &&
2955 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
2956 	}
2957 	/*
2958 	 * if maxbsize is unknown, set the maximum block size.
2959 	 */
2960 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
2961 
2962 		/*
2963 		 * Get the Block limits of the tape drive.
2964 		 * if un->un_allow_large_xfer = 0 , then make sure
2965 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
2966 		 */
2967 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
2968 
2969 		err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2970 		if (err) {
2971 			/* Retry */
2972 			err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2973 		}
2974 		if (!err) {
2975 
2976 			/*
2977 			 * if cmd successful, use limit returned
2978 			 */
2979 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
2980 			    (un->un_rbl->max_mid << 8) +
2981 			    un->un_rbl->max_lo;
2982 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
2983 			    un->un_rbl->min_lo;
2984 			un->un_data_mod = 1 << un->un_rbl->granularity;
2985 			if ((un->un_maxbsize == 0) ||
2986 			    (un->un_allow_large_xfer == 0 &&
2987 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
2988 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2989 
2990 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
2991 				/*
2992 				 * Drive is not one that is configured, But the
2993 				 * READ BLOCK LIMITS tells us it can do large
2994 				 * xfers.
2995 				 */
2996 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
2997 					un->un_dp->options |=
2998 					    ST_NO_RECSIZE_LIMIT;
2999 				}
3000 				/*
3001 				 * If max and mimimum block limits are the
3002 				 * same this is a fixed block size device.
3003 				 */
3004 				if (un->un_maxbsize == un->un_minbsize) {
3005 					un->un_dp->options &= ~ST_VARIABLE;
3006 				}
3007 			}
3008 
3009 			if (un->un_minbsize == 0) {
3010 				un->un_minbsize = 1;
3011 			}
3012 
3013 		} else { /* error on read block limits */
3014 
3015 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3016 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
3017 			    " errno = %d un_rsvd_status = 0x%X\n",
3018 			    err, un->un_rsvd_status);
3019 
3020 			/*
3021 			 * since read block limits cmd failed,
3022 			 * do not allow large xfers.
3023 			 * use old values in st_minphys
3024 			 */
3025 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
3026 				rval = EACCES;
3027 			} else {
3028 				un->un_allow_large_xfer = 0;
3029 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3030 				    "!Disabling large transfers\n");
3031 
3032 				/*
3033 				 * we guess maxbsize and minbsize
3034 				 */
3035 				if (un->un_bsize) {
3036 					un->un_maxbsize = un->un_minbsize =
3037 					    un->un_bsize;
3038 				} else {
3039 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3040 					un->un_minbsize = 1;
3041 				}
3042 				/*
3043 				 * Data Mod must be set,
3044 				 * Even if read block limits fails.
3045 				 * Prevents Divide By Zero in st_rw().
3046 				 */
3047 				un->un_data_mod = 1;
3048 			}
3049 		}
3050 		if (un->un_rbl) {
3051 			kmem_free(un->un_rbl, RBLSIZE);
3052 			un->un_rbl = NULL;
3053 		}
3054 
3055 		if (rval) {
3056 			goto exit;
3057 		}
3058 	}
3059 
3060 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3061 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
3062 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
3063 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
3064 
3065 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
3066 
3067 	if (err != 0) {
3068 		if (err == EINTR) {
3069 			un->un_laststate = un->un_state;
3070 			un->un_state = ST_STATE_CLOSED;
3071 			rval = EINTR;
3072 			goto exit;
3073 		}
3074 		/*
3075 		 * Make sure the tape is ready
3076 		 */
3077 		un->un_pos.pmode = invalid;
3078 		if (un->un_status != KEY_UNIT_ATTENTION) {
3079 			/*
3080 			 * allow open no media.  Subsequent MTIOCSTATE
3081 			 * with media present will complete the open
3082 			 * logic.
3083 			 */
3084 			un->un_laststate = un->un_state;
3085 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
3086 				un->un_mediastate = MTIO_EJECTED;
3087 				un->un_state = ST_STATE_OFFLINE;
3088 				rval = 0;
3089 				goto exit;
3090 			} else {
3091 				un->un_state = ST_STATE_CLOSED;
3092 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3093 				    "st_tape_init EIO no media, not opened "
3094 				    "O_NONBLOCK|O_EXCL\n");
3095 				rval = EIO;
3096 				goto exit;
3097 			}
3098 		}
3099 	}
3100 
3101 	/*
3102 	 * On each open, initialize block size from drivetype struct,
3103 	 * as it could have been changed by MTSRSZ ioctl.
3104 	 * Now, ST_VARIABLE simply means drive is capable of variable
3105 	 * mode. All drives are assumed to support fixed records.
3106 	 * Hence, un_bsize tells what mode the drive is in.
3107 	 *	un_bsize	= 0	- variable record length
3108 	 *			= x	- fixed record length is x
3109 	 */
3110 	un->un_bsize = un->un_dp->bsize;
3111 
3112 	/*
3113 	 * If saved position is valid go there
3114 	 */
3115 	if (un->un_restore_pos) {
3116 		un->un_restore_pos = 0;
3117 		un->un_pos.fileno = un->un_save_fileno;
3118 		un->un_pos.blkno = un->un_save_blkno;
3119 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &un->un_pos);
3120 		if (rval != 0) {
3121 			if (rval != EACCES) {
3122 				rval = EIO;
3123 			}
3124 			un->un_laststate = un->un_state;
3125 			un->un_state = ST_STATE_CLOSED;
3126 			goto exit;
3127 		}
3128 	}
3129 
3130 	if (un->un_pos.pmode == invalid) {
3131 		rval = st_loadtape(un);
3132 		if (rval) {
3133 			if (rval != EACCES) {
3134 				rval = EIO;
3135 			}
3136 			un->un_laststate = un->un_state;
3137 			un->un_state = ST_STATE_CLOSED;
3138 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3139 			    "st_tape_init: %s can't open tape\n",
3140 			    rval == EACCES ? "EACCES" : "EIO");
3141 			goto exit;
3142 		}
3143 	}
3144 
3145 	/*
3146 	 * do a mode sense to pick up state of current write-protect,
3147 	 * Could cause reserve and fail due to conflict.
3148 	 */
3149 	if (un->un_unit_attention_flags) {
3150 		rval = st_modesense(un);
3151 		if (rval == EACCES) {
3152 			goto exit;
3153 		}
3154 	}
3155 
3156 	/*
3157 	 * If we are opening the tape for writing, check
3158 	 * to make sure that the tape can be written.
3159 	 */
3160 	if (un->un_oflags & FWRITE) {
3161 		err = 0;
3162 		if (un->un_mspl->wp) {
3163 			un->un_status = KEY_WRITE_PROTECT;
3164 			un->un_laststate = un->un_state;
3165 			un->un_state = ST_STATE_CLOSED;
3166 			rval = EACCES;
3167 			/*
3168 			 * STK sets the wp bit if volsafe tape is loaded.
3169 			 */
3170 			if ((un->un_dp->type == MT_ISSTK9840) &&
3171 			    (un->un_dp->options & ST_WORMABLE)) {
3172 				un->un_read_only = RDONLY;
3173 			} else {
3174 				goto exit;
3175 			}
3176 		} else {
3177 			un->un_read_only = RDWR;
3178 		}
3179 	} else {
3180 		un->un_read_only = RDONLY;
3181 	}
3182 
3183 	if (un->un_dp->options & ST_WORMABLE &&
3184 	    un->un_unit_attention_flags) {
3185 		un->un_read_only |= un->un_wormable(un);
3186 
3187 		if (((un->un_read_only == WORM) ||
3188 		    (un->un_read_only == RDWORM)) &&
3189 		    ((un->un_oflags & FWRITE) == FWRITE)) {
3190 			un->un_status = KEY_DATA_PROTECT;
3191 			rval = EACCES;
3192 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3193 			    "read_only = %d eof = %d oflag = %d\n",
3194 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3195 		}
3196 	}
3197 
3198 	/*
3199 	 * If we're opening the tape write-only, we need to
3200 	 * write 2 filemarks on the HP 1/2 inch drive, to
3201 	 * create a null file.
3202 	 */
3203 	if ((un->un_read_only == RDWR) ||
3204 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3205 		if (un->un_dp->options & ST_REEL) {
3206 			un->un_fmneeded = 2;
3207 		} else {
3208 			un->un_fmneeded = 1;
3209 		}
3210 	} else {
3211 		un->un_fmneeded = 0;
3212 	}
3213 
3214 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3215 	    "fmneeded = %x\n", un->un_fmneeded);
3216 
3217 	/*
3218 	 * Make sure the density can be selected correctly.
3219 	 * If WORM can only write at the append point which in most cases
3220 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3221 	 * to set and try densities if a BOP.
3222 	 */
3223 	if (st_determine_density(un,
3224 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3225 		un->un_status = KEY_ILLEGAL_REQUEST;
3226 		un->un_laststate = un->un_state;
3227 		un->un_state = ST_STATE_CLOSED;
3228 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3229 		    "st_tape_init: EIO can't determine density\n");
3230 		rval = EIO;
3231 		goto exit;
3232 	}
3233 
3234 	/*
3235 	 * Destroy the knowledge that we have 'determined'
3236 	 * density so that a later read at BOT comes along
3237 	 * does the right density determination.
3238 	 */
3239 
3240 	un->un_density_known = 0;
3241 
3242 
3243 	/*
3244 	 * Okay, the tape is loaded and either at BOT or somewhere past.
3245 	 * Mark the state such that any I/O or tape space operations
3246 	 * will get/set the right density, etc..
3247 	 */
3248 	un->un_laststate = un->un_state;
3249 	un->un_lastop = ST_OP_NIL;
3250 	un->un_mediastate = MTIO_INSERTED;
3251 	cv_broadcast(&un->un_state_cv);
3252 
3253 	/*
3254 	 *  Set test append flag if writing.
3255 	 *  First write must check that tape is positioned correctly.
3256 	 */
3257 	un->un_test_append = (un->un_oflags & FWRITE);
3258 
3259 	/*
3260 	 * if there are pending unit attention flags.
3261 	 * Check that the media has not changed.
3262 	 */
3263 	if (un->un_unit_attention_flags) {
3264 		rval = st_get_media_identification(un, st_uscsi_cmd);
3265 		if (rval != 0 && rval != EACCES) {
3266 			rval = EIO;
3267 		}
3268 		un->un_unit_attention_flags = 0;
3269 	}
3270 
3271 exit:
3272 	un->un_err_resid = 0;
3273 	un->un_last_resid = 0;
3274 	un->un_last_count = 0;
3275 
3276 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3277 	    "st_tape_init: return val = %x\n", rval);
3278 	return (rval);
3279 
3280 }
3281 
3282 
3283 
3284 /* ARGSUSED */
3285 static int
3286 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3287 {
3288 	int err = 0;
3289 	int count, last_state;
3290 	minor_t minor = getminor(dev);
3291 #ifdef	__x86
3292 	struct contig_mem *cp, *cp_temp;
3293 #endif
3294 
3295 	GET_SOFT_STATE(dev);
3296 
3297 	ST_ENTR(ST_DEVINFO, st_close);
3298 
3299 	/*
3300 	 * wait till all cmds in the pipeline have been completed
3301 	 */
3302 	mutex_enter(ST_MUTEX);
3303 
3304 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3305 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3306 
3307 	st_wait_for_io(un);
3308 
3309 	/* turn off persistent errors on close, as we want close to succeed */
3310 	st_turn_pe_off(un);
3311 
3312 	/*
3313 	 * set state to indicate that we are in process of closing
3314 	 */
3315 	last_state = un->un_laststate = un->un_state;
3316 	un->un_state = ST_STATE_CLOSING;
3317 
3318 	ST_POS(ST_DEVINFO, "st_close1:", &un->un_pos);
3319 
3320 	/*
3321 	 * BSD behavior:
3322 	 * a close always causes a silent span to the next file if we've hit
3323 	 * an EOF (but not yet read across it).
3324 	 */
3325 	if ((minor & MT_BSD) && (un->un_pos.eof == ST_EOF)) {
3326 		if (un->un_pos.pmode != invalid) {
3327 			un->un_pos.fileno++;
3328 			un->un_pos.blkno = 0;
3329 		}
3330 		un->un_pos.eof = ST_NO_EOF;
3331 	}
3332 
3333 	/*
3334 	 * SVR4 behavior for skipping to next file:
3335 	 *
3336 	 * If we have not seen a filemark, space to the next file
3337 	 *
3338 	 * If we have already seen the filemark we are physically in the next
3339 	 * file and we only increment the filenumber
3340 	 */
3341 	if (((minor & (MT_BSD | MT_NOREWIND)) == MT_NOREWIND) &&
3342 	    (flag & FREAD) &&		/* reading or at least asked to */
3343 	    ((un->un_pos.blkno != 0) && 		/* inside a file */
3344 	    (un->un_lastop != ST_OP_WRITE) &&		/* Didn't just write */
3345 	    (un->un_lastop != ST_OP_WEOF))) {		/* or write filemarks */
3346 		switch (un->un_pos.eof) {
3347 		case ST_NO_EOF:
3348 			/*
3349 			 * if we were reading and did not read the complete file
3350 			 * skip to the next file, leaving the tape correctly
3351 			 * positioned to read the first record of the next file
3352 			 * Check first for REEL if we are at EOT by trying to
3353 			 * read a block
3354 			 */
3355 			if ((un->un_dp->options & ST_REEL) &&
3356 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3357 			    (un->un_pos.blkno == 0)) {
3358 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3359 					ST_DEBUG2(ST_DEVINFO, st_label,
3360 					    SCSI_DEBUG,
3361 					    "st_close : EIO can't space\n");
3362 					err = EIO;
3363 					break;
3364 				}
3365 				if (un->un_pos.eof >= ST_EOF_PENDING) {
3366 					un->un_pos.eof = ST_EOT_PENDING;
3367 					un->un_pos.fileno += 1;
3368 					un->un_pos.blkno   = 0;
3369 					break;
3370 				}
3371 			}
3372 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3373 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3374 				    "st_close: EIO can't space #2\n");
3375 				err = EIO;
3376 			} else {
3377 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3378 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3379 				    un->un_pos.fileno, un->un_pos.blkno,
3380 				    un->un_pos.eof);
3381 				un->un_pos.eof = ST_NO_EOF;
3382 			}
3383 			break;
3384 
3385 		case ST_EOF_PENDING:
3386 		case ST_EOF:
3387 			un->un_pos.fileno += 1;
3388 			un->un_pos.lgclblkno += 1;
3389 			un->un_pos.blkno   = 0;
3390 			un->un_pos.eof = ST_NO_EOF;
3391 			break;
3392 
3393 		case ST_EOT:
3394 		case ST_EOT_PENDING:
3395 			/* nothing to do */
3396 			break;
3397 		default:
3398 			scsi_log(ST_DEVINFO, st_label, CE_PANIC,
3399 			    "Undefined state 0x%x", un->un_pos.eof);
3400 
3401 		}
3402 	}
3403 
3404 
3405 	/*
3406 	 * For performance reasons (HP 88780), the driver should
3407 	 * postpone writing the second tape mark until just before a file
3408 	 * positioning ioctl is issued (e.g., rewind).	This means that
3409 	 * the user must not manually rewind the tape because the tape will
3410 	 * be missing the second tape mark which marks EOM.
3411 	 * However, this small performance improvement is not worth the risk.
3412 	 */
3413 
3414 	/*
3415 	 * We need to back up over the filemark we inadvertently popped
3416 	 * over doing a read in between the two filemarks that constitute
3417 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3418 	 * set while reading.
3419 	 *
3420 	 * If we happen to be at physical eot (ST_EOM) (writing case),
3421 	 * the writing of filemark(s) will clear the ST_EOM state, which
3422 	 * we don't want, so we save this state and restore it later.
3423 	 */
3424 
3425 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3426 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3427 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3428 
3429 	if (un->un_pos.eof == ST_EOT_PENDING) {
3430 		if (minor & MT_NOREWIND) {
3431 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3432 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3433 				    "st_close: EIO can't space #3\n");
3434 				err = EIO;
3435 			} else {
3436 				un->un_pos.blkno = 0;
3437 				un->un_pos.eof = ST_EOT;
3438 			}
3439 		} else {
3440 			un->un_pos.eof = ST_NO_EOF;
3441 		}
3442 
3443 	/*
3444 	 * Do we need to write a file mark?
3445 	 *
3446 	 * only write filemarks if there are fmks to be written and
3447 	 *   - open for write (possibly read/write)
3448 	 *   - the last operation was a write
3449 	 * or:
3450 	 *   -	opened for wronly
3451 	 *   -	no data was written
3452 	 */
3453 	} else if ((un->un_pos.pmode != invalid) &&
3454 	    (un->un_fmneeded > 0) &&
3455 	    (((flag & FWRITE) &&
3456 	    ((un->un_lastop == ST_OP_WRITE)||(un->un_lastop == ST_OP_WEOF))) ||
3457 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3458 
3459 		/* save ST_EOM state */
3460 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3461 
3462 		/*
3463 		 * Note that we will write a filemark if we had opened
3464 		 * the tape write only and no data was written, thus
3465 		 * creating a null file.
3466 		 *
3467 		 * If the user already wrote one, we only have to write 1 more.
3468 		 * If they wrote two, we don't have to write any.
3469 		 */
3470 
3471 		count = un->un_fmneeded;
3472 		if (count > 0) {
3473 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, count, SYNC_CMD)) {
3474 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3475 				    "st_close : EIO can't wfm\n");
3476 				err = EIO;
3477 			}
3478 			if ((un->un_dp->options & ST_REEL) &&
3479 			    (minor & MT_NOREWIND)) {
3480 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3481 					ST_DEBUG2(ST_DEVINFO, st_label,
3482 					    SCSI_DEBUG,
3483 					    "st_close : EIO space fmk(-1)\n");
3484 					err = EIO;
3485 				}
3486 				un->un_pos.eof = ST_NO_EOF;
3487 				/* fix up block number */
3488 				un->un_pos.blkno = 0;
3489 			}
3490 		}
3491 
3492 		/*
3493 		 * If we aren't going to be rewinding, and we were at
3494 		 * physical eot, restore the state that indicates we
3495 		 * are at physical eot. Once you have reached physical
3496 		 * eot, and you close the tape, the only thing you can
3497 		 * do on the next open is to rewind. Access to trailer
3498 		 * records is only allowed without closing the device.
3499 		 */
3500 		if ((minor & MT_NOREWIND) == 0 && was_at_eom) {
3501 			un->un_pos.eof = ST_EOM;
3502 		}
3503 	}
3504 
3505 	/*
3506 	 * report soft errors if enabled and available, if we never accessed
3507 	 * the drive, don't get errors. This will prevent some DAT error
3508 	 * messages upon LOG SENSE.
3509 	 */
3510 	if (st_report_soft_errors_on_close &&
3511 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3512 	    (last_state != ST_STATE_OFFLINE)) {
3513 		(void) st_report_soft_errors(dev, flag);
3514 	}
3515 
3516 
3517 	/*
3518 	 * Do we need to rewind? Can we rewind?
3519 	 */
3520 	if ((minor & MT_NOREWIND) == 0 &&
3521 	    un->un_pos.pmode != invalid && err == 0) {
3522 		/*
3523 		 * We'd like to rewind with the
3524 		 * 'immediate' bit set, but this
3525 		 * causes problems on some drives
3526 		 * where subsequent opens get a
3527 		 * 'NOT READY' error condition
3528 		 * back while the tape is rewinding,
3529 		 * which is impossible to distinguish
3530 		 * from the condition of 'no tape loaded'.
3531 		 *
3532 		 * Also, for some targets, if you disconnect
3533 		 * with the 'immediate' bit set, you don't
3534 		 * actually return right away, i.e., the
3535 		 * target ignores your request for immediate
3536 		 * return.
3537 		 *
3538 		 * Instead, we'll fire off an async rewind
3539 		 * command. We'll mark the device as closed,
3540 		 * and any subsequent open will stall on
3541 		 * the first TEST_UNIT_READY until the rewind
3542 		 * completes.
3543 		 */
3544 
3545 		/*
3546 		 * Used to be if reserve was not supported we'd send an
3547 		 * asynchronious rewind. Comments above may be slightly invalid
3548 		 * as the immediate bit was never set. Doing an immedate rewind
3549 		 * makes sense, I think fixes to not ready status might handle
3550 		 * the problems described above.
3551 		 */
3552 		if (un->un_sd->sd_inq->inq_ansi < 2) {
3553 			(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
3554 		} else {
3555 			/* flush data for older drives per scsi spec. */
3556 			(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
3557 			(void) st_cmd(un, SCMD_REWIND, 1, ASYNC_CMD);
3558 		}
3559 	}
3560 
3561 	/*
3562 	 * eject tape if necessary
3563 	 */
3564 	if (un->un_eject_tape_on_failure) {
3565 		un->un_eject_tape_on_failure = 0;
3566 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3567 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3568 			    "st_close : can't unload tape\n");
3569 		} else {
3570 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3571 			    "st_close : tape unloaded \n");
3572 			un->un_pos.eof = ST_NO_EOF;
3573 			un->un_mediastate = MTIO_EJECTED;
3574 		}
3575 	}
3576 	/*
3577 	 * Release the tape unit, if default reserve/release
3578 	 * behaviour.
3579 	 */
3580 	if ((un->un_rsvd_status &
3581 	    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
3582 		(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
3583 	}
3584 
3585 	/*
3586 	 * clear up state
3587 	 */
3588 	un->un_laststate = un->un_state;
3589 	un->un_state = ST_STATE_CLOSED;
3590 	un->un_lastop = ST_OP_NIL;
3591 	un->un_throttle = 1;	/* assume one request at time, for now */
3592 	un->un_retry_ct = 0;
3593 	un->un_tran_retry_ct = 0;
3594 	un->un_errno = 0;
3595 	un->un_swr_token = (opaque_t)NULL;
3596 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3597 
3598 	/* Restore the options to the init time settings */
3599 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3600 		un->un_dp->options |= ST_READ_IGNORE_ILI;
3601 	} else {
3602 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3603 	}
3604 
3605 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3606 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3607 	} else {
3608 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3609 	}
3610 
3611 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3612 		un->un_dp->options |= ST_SHORT_FILEMARKS;
3613 	} else {
3614 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3615 	}
3616 
3617 	ASSERT(mutex_owned(ST_MUTEX));
3618 
3619 	/*
3620 	 * Signal anyone awaiting a close operation to complete.
3621 	 */
3622 	cv_signal(&un->un_clscv);
3623 
3624 	/*
3625 	 * any kind of error on closing causes all state to be tossed
3626 	 */
3627 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3628 		/*
3629 		 * note that st_intr has already set
3630 		 * un_pos.pmode to invalid.
3631 		 */
3632 		un->un_density_known = 0;
3633 	}
3634 
3635 #ifdef	__x86
3636 	/*
3637 	 * free any contiguous mem alloc'ed for big block I/O
3638 	 */
3639 	cp = un->un_contig_mem;
3640 	while (cp) {
3641 		if (cp->cm_addr) {
3642 			ddi_dma_mem_free(&cp->cm_acc_hdl);
3643 		}
3644 		cp_temp = cp;
3645 		cp = cp->cm_next;
3646 		kmem_free(cp_temp,
3647 		    sizeof (struct contig_mem) + biosize());
3648 	}
3649 	un->un_contig_mem_total_num = 0;
3650 	un->un_contig_mem_available_num = 0;
3651 	un->un_contig_mem = NULL;
3652 	un->un_max_contig_mem_len = 0;
3653 #endif
3654 
3655 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3656 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3657 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3658 
3659 	mutex_exit(ST_MUTEX);
3660 	return (err);
3661 }
3662 
3663 /*
3664  * These routines perform raw i/o operations.
3665  */
3666 
3667 /* ARGSUSED2 */
3668 static int
3669 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3670 {
3671 #ifdef STDEBUG
3672 	GET_SOFT_STATE(dev);
3673 	ST_ENTR(ST_DEVINFO, st_aread);
3674 #endif
3675 	return (st_arw(dev, aio, B_READ));
3676 }
3677 
3678 
3679 /* ARGSUSED2 */
3680 static int
3681 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3682 {
3683 #ifdef STDEBUG
3684 	GET_SOFT_STATE(dev);
3685 	ST_ENTR(ST_DEVINFO, st_awrite);
3686 #endif
3687 	return (st_arw(dev, aio, B_WRITE));
3688 }
3689 
3690 
3691 
3692 /* ARGSUSED */
3693 static int
3694 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3695 {
3696 #ifdef STDEBUG
3697 	GET_SOFT_STATE(dev);
3698 	ST_ENTR(ST_DEVINFO, st_read);
3699 #endif
3700 	return (st_rw(dev, uiop, B_READ));
3701 }
3702 
3703 /* ARGSUSED */
3704 static int
3705 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3706 {
3707 #ifdef STDEBUG
3708 	GET_SOFT_STATE(dev);
3709 	ST_ENTR(ST_DEVINFO, st_write);
3710 #endif
3711 	return (st_rw(dev, uiop, B_WRITE));
3712 }
3713 
3714 /*
3715  * Due to historical reasons, old limits are: For variable-length devices:
3716  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3717  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3718  * (let it through unmodified. For fixed-length record devices:
3719  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3720  *
3721  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3722  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3723  * command to the drive).
3724  *
3725  */
3726 static void
3727 st_minphys(struct buf *bp)
3728 {
3729 	struct scsi_tape *un;
3730 
3731 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3732 
3733 	ST_FUNC(ST_DEVINFO, st_minphys);
3734 
3735 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3736 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3737 	    bp->b_bcount);
3738 
3739 	if (un->un_allow_large_xfer) {
3740 
3741 		/*
3742 		 * check un_maxbsize for variable length devices only
3743 		 */
3744 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3745 			bp->b_bcount = un->un_maxbsize;
3746 		}
3747 		/*
3748 		 * can't go more that HBA maxdma limit in either fixed-length
3749 		 * or variable-length tape drives.
3750 		 */
3751 		if (bp->b_bcount > un->un_maxdma) {
3752 			bp->b_bcount = un->un_maxdma;
3753 		}
3754 	} else {
3755 
3756 		/*
3757 		 *  use old fixed limits
3758 		 */
3759 		if (un->un_bsize == 0) {
3760 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3761 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3762 			}
3763 		} else {
3764 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3765 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3766 			}
3767 		}
3768 	}
3769 
3770 	/*
3771 	 * For regular raw I/O and Fixed Block length devices, make sure
3772 	 * the adjusted block count is a whole multiple of the device
3773 	 * block size.
3774 	 */
3775 	if (bp != un->un_sbufp && un->un_bsize) {
3776 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3777 	}
3778 }
3779 
3780 static int
3781 st_rw(dev_t dev, struct uio *uio, int flag)
3782 {
3783 	int rval = 0;
3784 	long len;
3785 
3786 	GET_SOFT_STATE(dev);
3787 
3788 	ST_FUNC(ST_DEVINFO, st_rw);
3789 
3790 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3791 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3792 	    (flag == B_READ ? rd_str: wr_str));
3793 
3794 	/* get local copy of transfer length */
3795 	len = uio->uio_iov->iov_len;
3796 
3797 	mutex_enter(ST_MUTEX);
3798 
3799 	/*
3800 	 * Clear error entry stack
3801 	 */
3802 	st_empty_error_stack(un);
3803 
3804 	/*
3805 	 * If in fixed block size mode and requested read or write
3806 	 * is not an even multiple of that block size.
3807 	 */
3808 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3809 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3810 		    "%s: not modulo %d block size\n",
3811 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3812 		rval = EINVAL;
3813 	}
3814 
3815 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3816 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3817 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3818 		    "%s: not modulo %d device granularity\n",
3819 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3820 		rval = EINVAL;
3821 	}
3822 
3823 	if (rval != 0) {
3824 		un->un_errno = rval;
3825 		mutex_exit(ST_MUTEX);
3826 		return (rval);
3827 	}
3828 
3829 	/*
3830 	 * Reset this so it can be set if Berkeley and read over a filemark.
3831 	 */
3832 	un->un_silent_skip = 0;
3833 	mutex_exit(ST_MUTEX);
3834 
3835 	len = uio->uio_resid;
3836 
3837 	rval = physio(st_queued_strategy, (struct buf *)NULL,
3838 	    dev, flag, st_minphys, uio);
3839 	/*
3840 	 * if we have hit logical EOT during this xfer and there is not a
3841 	 * full residue, then set eof back  to ST_EOM to make sure that
3842 	 * the user will see at least one zero write
3843 	 * after this short write
3844 	 */
3845 	mutex_enter(ST_MUTEX);
3846 	if (un->un_pos.eof > ST_NO_EOF) {
3847 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3848 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3849 	}
3850 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3851 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3852 			un->un_pos.eof = ST_EOM;
3853 		} else if (uio->uio_resid == len) {
3854 			un->un_pos.eof = ST_NO_EOF;
3855 		}
3856 	}
3857 
3858 	if (un->un_silent_skip && uio->uio_resid != len) {
3859 		un->un_pos.eof = ST_EOF;
3860 		un->un_pos.blkno = un->un_save_blkno;
3861 		un->un_pos.fileno--;
3862 	}
3863 
3864 	un->un_errno = rval;
3865 
3866 	mutex_exit(ST_MUTEX);
3867 
3868 	return (rval);
3869 }
3870 
3871 static int
3872 st_arw(dev_t dev, struct aio_req *aio, int flag)
3873 {
3874 	struct uio *uio = aio->aio_uio;
3875 	int rval = 0;
3876 	long len;
3877 
3878 	GET_SOFT_STATE(dev);
3879 
3880 	ST_FUNC(ST_DEVINFO, st_arw);
3881 
3882 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3883 	    "st_arw(dev = 0x%lx, flag = %s)\n", dev,
3884 	    (flag == B_READ ? rd_str: wr_str));
3885 
3886 	/* get local copy of transfer length */
3887 	len = uio->uio_iov->iov_len;
3888 
3889 	mutex_enter(ST_MUTEX);
3890 
3891 	/*
3892 	 * If in fixed block size mode and requested read or write
3893 	 * is not an even multiple of that block size.
3894 	 */
3895 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3896 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3897 		    "%s: not modulo %d block size\n",
3898 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3899 		rval = EINVAL;
3900 	}
3901 
3902 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3903 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3904 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3905 		    "%s: not modulo %d device granularity\n",
3906 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3907 		rval = EINVAL;
3908 	}
3909 
3910 	if (rval != 0) {
3911 		un->un_errno = rval;
3912 		mutex_exit(ST_MUTEX);
3913 		return (rval);
3914 	}
3915 
3916 	mutex_exit(ST_MUTEX);
3917 
3918 	len = uio->uio_resid;
3919 
3920 	rval =
3921 	    aphysio(st_queued_strategy, anocancel, dev, flag, st_minphys, aio);
3922 
3923 	/*
3924 	 * if we have hit logical EOT during this xfer and there is not a
3925 	 * full residue, then set eof back  to ST_EOM to make sure that
3926 	 * the user will see at least one zero write
3927 	 * after this short write
3928 	 *
3929 	 * we keep this here just in case the application is not using
3930 	 * persistent errors
3931 	 */
3932 	mutex_enter(ST_MUTEX);
3933 	if (un->un_pos.eof > ST_NO_EOF) {
3934 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3935 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3936 	}
3937 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3938 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3939 			un->un_pos.eof = ST_EOM;
3940 		} else if (uio->uio_resid == len &&
3941 		    !(un->un_persistence && un->un_persist_errors)) {
3942 			un->un_pos.eof = ST_NO_EOF;
3943 		}
3944 	}
3945 	un->un_errno = rval;
3946 	mutex_exit(ST_MUTEX);
3947 
3948 	return (rval);
3949 }
3950 
3951 
3952 
3953 static int
3954 st_queued_strategy(buf_t *bp)
3955 {
3956 	struct scsi_tape *un;
3957 	char reading = bp->b_flags & B_READ;
3958 	int wasopening = 0;
3959 
3960 	/*
3961 	 * validate arguments
3962 	 */
3963 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3964 	if (un == NULL) {
3965 		bp->b_resid = bp->b_bcount;
3966 		bioerror(bp, ENXIO);
3967 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
3968 		    "st_queued_strategy: ENXIO error exit\n");
3969 		biodone(bp);
3970 		return (0);
3971 	}
3972 
3973 	ST_ENTR(ST_DEVINFO, st_queued_strategy);
3974 
3975 	mutex_enter(ST_MUTEX);
3976 
3977 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
3978 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
3979 	}
3980 
3981 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3982 	    "st_queued_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
3983 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3984 
3985 	/*
3986 	 * If persistent errors have been flagged, just nix this one. We wait
3987 	 * for any outstanding I/O's below, so we will be in order.
3988 	 */
3989 	if (un->un_persistence && un->un_persist_errors) {
3990 		goto exit;
3991 	}
3992 
3993 	/*
3994 	 * If last command was non queued, wait till it finishes.
3995 	 */
3996 	while (un->un_sbuf_busy) {
3997 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
3998 		/* woke up because of an error */
3999 		if (un->un_persistence && un->un_persist_errors) {
4000 			goto exit;
4001 		}
4002 	}
4003 
4004 	/*
4005 	 * s_buf and recovery commands shouldn't come here.
4006 	 */
4007 	ASSERT(bp != un->un_recov_buf);
4008 	ASSERT(bp != un->un_sbufp);
4009 
4010 	/*
4011 	 * If we haven't done/checked reservation on the tape unit
4012 	 * do it now.
4013 	 */
4014 	if ((un->un_rsvd_status &
4015 	    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
4016 		if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
4017 			if (st_reserve_release(un, ST_RESERVE, st_uscsi_cmd)) {
4018 				st_bioerror(bp, un->un_errno);
4019 				goto exit;
4020 			}
4021 		} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4022 			/*
4023 			 * Enter here to restore position for possible
4024 			 * resets when the device was closed and opened
4025 			 * in O_NDELAY mode subsequently
4026 			 */
4027 			un->un_state = ST_STATE_INITIALIZING;
4028 			(void) st_cmd(un, SCMD_TEST_UNIT_READY,
4029 			    0, SYNC_CMD);
4030 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4031 		}
4032 		un->un_rsvd_status |= ST_INIT_RESERVE;
4033 	}
4034 
4035 	/*
4036 	 * If we are offline, we have to initialize everything first.
4037 	 * This is to handle either when opened with O_NDELAY, or
4038 	 * we just got a new tape in the drive, after an offline.
4039 	 * We don't observe O_NDELAY past the open,
4040 	 * as it will not make sense for tapes.
4041 	 */
4042 	if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
4043 		/*
4044 		 * reset state to avoid recursion
4045 		 */
4046 		un->un_laststate = un->un_state;
4047 		un->un_state = ST_STATE_INITIALIZING;
4048 		if (st_tape_init(un)) {
4049 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4050 			    "stioctl : OFFLINE init failure ");
4051 			un->un_state = ST_STATE_OFFLINE;
4052 			un->un_pos.pmode = invalid;
4053 			goto b_done_err;
4054 		}
4055 		/* WTF un_restore_pos make invalid */
4056 		un->un_state = ST_STATE_OPEN_PENDING_IO;
4057 		un->un_restore_pos = 0;
4058 	}
4059 	/*
4060 	 * Check for legal operations
4061 	 */
4062 	if (un->un_pos.pmode == invalid) {
4063 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4064 		    "strategy with un->un_pos.pmode invalid\n");
4065 		goto b_done_err;
4066 	}
4067 
4068 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4069 	    "st_queued_strategy(): regular io\n");
4070 
4071 	/*
4072 	 * Process this first. If we were reading, and we're pending
4073 	 * logical eot, that means we've bumped one file mark too far.
4074 	 */
4075 
4076 	/*
4077 	 * Recursion warning: st_cmd will route back through here.
4078 	 * Not anymore st_cmd will go through st_strategy()!
4079 	 */
4080 	if (un->un_pos.eof == ST_EOT_PENDING) {
4081 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4082 			un->un_pos.pmode = invalid;
4083 			un->un_density_known = 0;
4084 			goto b_done_err;
4085 		}
4086 		un->un_pos.blkno = 0; /* fix up block number.. */
4087 		un->un_pos.eof = ST_EOT;
4088 	}
4089 
4090 	/*
4091 	 * If we are in the process of opening, we may have to
4092 	 * determine/set the correct density. We also may have
4093 	 * to do a test_append (if QIC) to see whether we are
4094 	 * in a position to append to the end of the tape.
4095 	 *
4096 	 * If we're already at logical eot, we transition
4097 	 * to ST_NO_EOF. If we're at physical eot, we punt
4098 	 * to the switch statement below to handle.
4099 	 */
4100 	if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
4101 	    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
4102 
4103 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4104 			if (st_determine_density(un, (int)reading)) {
4105 				goto b_done_err;
4106 			}
4107 		}
4108 
4109 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4110 		    "pending_io@fileno %d rw %d qic %d eof %d\n",
4111 		    un->un_pos.fileno, (int)reading,
4112 		    (un->un_dp->options & ST_QIC) ? 1 : 0,
4113 		    un->un_pos.eof);
4114 
4115 		if (!reading && un->un_pos.eof != ST_EOM) {
4116 			if (un->un_pos.eof == ST_EOT) {
4117 				un->un_pos.eof = ST_NO_EOF;
4118 			} else if (un->un_pos.pmode != invalid &&
4119 			    (un->un_dp->options & ST_QIC)) {
4120 				/*
4121 				 * st_test_append() will do it all
4122 				 */
4123 				st_test_append(bp);
4124 				mutex_exit(ST_MUTEX);
4125 				return (0);
4126 			}
4127 		}
4128 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4129 			wasopening = 1;
4130 		}
4131 		un->un_laststate = un->un_state;
4132 		un->un_state = ST_STATE_OPEN;
4133 	}
4134 
4135 
4136 	/*
4137 	 * Process rest of END OF FILE and END OF TAPE conditions
4138 	 */
4139 
4140 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4141 	    "eof=%x, wasopening=%x\n",
4142 	    un->un_pos.eof, wasopening);
4143 
4144 	switch (un->un_pos.eof) {
4145 	case ST_EOM:
4146 		/*
4147 		 * This allows writes to proceed past physical
4148 		 * eot. We'll *really* be in trouble if the
4149 		 * user continues blindly writing data too
4150 		 * much past this point (unwind the tape).
4151 		 * Physical eot really means 'early warning
4152 		 * eot' in this context.
4153 		 *
4154 		 * Every other write from now on will succeed
4155 		 * (if sufficient  tape left).
4156 		 * This write will return with resid == count
4157 		 * but the next one should be successful
4158 		 *
4159 		 * Note that we only transition to logical EOT
4160 		 * if the last state wasn't the OPENING state.
4161 		 * We explicitly prohibit running up to physical
4162 		 * eot, closing the device, and then re-opening
4163 		 * to proceed. Trailer records may only be gotten
4164 		 * at by keeping the tape open after hitting eot.
4165 		 *
4166 		 * Also note that ST_EOM cannot be set by reading-
4167 		 * this can only be set during writing. Reading
4168 		 * up to the end of the tape gets a blank check
4169 		 * or a double-filemark indication (ST_EOT_PENDING),
4170 		 * and we prohibit reading after that point.
4171 		 *
4172 		 */
4173 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
4174 		if (wasopening == 0) {
4175 			/*
4176 			 * this allows st_rw() to reset it back to
4177 			 * will see a zero write
4178 			 */
4179 			un->un_pos.eof = ST_WRITE_AFTER_EOM;
4180 		}
4181 		un->un_status = SUN_KEY_EOT;
4182 		goto b_done;
4183 
4184 	case ST_WRITE_AFTER_EOM:
4185 	case ST_EOT:
4186 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
4187 		un->un_status = SUN_KEY_EOT;
4188 		if (SVR4_BEHAVIOR && reading) {
4189 			goto b_done_err;
4190 		}
4191 
4192 		if (reading) {
4193 			goto b_done;
4194 		}
4195 		un->un_pos.eof = ST_NO_EOF;
4196 		break;
4197 
4198 	case ST_EOF_PENDING:
4199 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4200 		    "EOF PENDING\n");
4201 		un->un_status = SUN_KEY_EOF;
4202 		if (SVR4_BEHAVIOR) {
4203 			un->un_pos.eof = ST_EOF;
4204 			goto b_done;
4205 		}
4206 		/* FALLTHROUGH */
4207 	case ST_EOF:
4208 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
4209 		un->un_status = SUN_KEY_EOF;
4210 		if (SVR4_BEHAVIOR) {
4211 			goto b_done_err;
4212 		}
4213 
4214 		if (BSD_BEHAVIOR) {
4215 			un->un_pos.eof = ST_NO_EOF;
4216 			un->un_pos.fileno += 1;
4217 			un->un_pos.blkno   = 0;
4218 		}
4219 
4220 		if (reading) {
4221 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4222 			    "now file %d (read)\n",
4223 			    un->un_pos.fileno);
4224 			goto b_done;
4225 		}
4226 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4227 		    "now file %d (write)\n", un->un_pos.fileno);
4228 		break;
4229 	default:
4230 		un->un_status = 0;
4231 		break;
4232 	}
4233 
4234 	bp->b_flags &= ~(B_DONE);
4235 	st_bioerror(bp, 0);
4236 	bp->av_forw = NULL;
4237 	bp->b_resid = 0;
4238 	SET_BP_PKT(bp, 0);
4239 
4240 
4241 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4242 	    "st_queued_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4243 	    " pkt=0x%p\n",
4244 	    (void *)bp->b_forw, bp->b_bcount,
4245 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4246 
4247 #ifdef	__x86
4248 	/*
4249 	 * We will replace bp with a new bp that can do big blk xfer
4250 	 * if the requested xfer size is bigger than un->un_maxdma_arch
4251 	 *
4252 	 * Also, we need to make sure that we're handling real I/O
4253 	 * by checking group 0/1 SCSI I/O commands, if needed
4254 	 */
4255 	if (bp->b_bcount > un->un_maxdma_arch &&
4256 	    ((uchar_t)(uintptr_t)bp->b_forw == SCMD_READ ||
4257 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G4 ||
4258 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE ||
4259 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G4)) {
4260 		mutex_exit(ST_MUTEX);
4261 		bp = st_get_bigblk_bp(bp);
4262 		mutex_enter(ST_MUTEX);
4263 	}
4264 #endif
4265 
4266 	/* put on wait queue */
4267 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4268 	    "st_queued_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4269 	    (void *)un->un_quef, (void *)bp);
4270 
4271 	st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quel, bp);
4272 
4273 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4274 
4275 	st_start(un);
4276 
4277 	mutex_exit(ST_MUTEX);
4278 	return (0);
4279 
4280 b_done_err:
4281 	st_bioerror(bp, EIO);
4282 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4283 	    "st_queued_strategy : EIO b_done_err\n");
4284 
4285 b_done:
4286 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4287 	    "st_queued_strategy: b_done\n");
4288 
4289 exit:
4290 	/*
4291 	 * make sure no commands are outstanding or waiting before closing,
4292 	 * so we can guarantee order
4293 	 */
4294 	st_wait_for_io(un);
4295 	un->un_err_resid = bp->b_resid = bp->b_bcount;
4296 
4297 	/* override errno here, if persistent errors were flagged */
4298 	if (un->un_persistence && un->un_persist_errors)
4299 		bioerror(bp, un->un_errno);
4300 
4301 	mutex_exit(ST_MUTEX);
4302 
4303 	biodone(bp);
4304 	ASSERT(mutex_owned(ST_MUTEX) == 0);
4305 	return (0);
4306 }
4307 
4308 
4309 static int
4310 st_strategy(struct buf *bp)
4311 {
4312 	struct scsi_tape *un;
4313 
4314 	/*
4315 	 * validate arguments
4316 	 */
4317 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4318 	if (un == NULL) {
4319 		bp->b_resid = bp->b_bcount;
4320 		bioerror(bp, ENXIO);
4321 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4322 		    "st_strategy: ENXIO error exit\n");
4323 
4324 		biodone(bp);
4325 		return (0);
4326 
4327 	}
4328 
4329 	ST_ENTR(ST_DEVINFO, st_strategy);
4330 
4331 	mutex_enter(ST_MUTEX);
4332 
4333 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4334 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4335 	}
4336 
4337 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4338 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4339 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4340 
4341 	ASSERT((bp == un->un_recov_buf) || (bp == un->un_sbufp));
4342 
4343 	bp->b_flags &= ~(B_DONE);
4344 	st_bioerror(bp, 0);
4345 	bp->av_forw = NULL;
4346 	bp->b_resid = 0;
4347 	SET_BP_PKT(bp, 0);
4348 
4349 
4350 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4351 	    "st_strategy: cmd=0x%x  count=%ld  resid=%ld flags=0x%x"
4352 	    " pkt=0x%p\n",
4353 	    (unsigned char)(uintptr_t)bp->b_forw, bp->b_bcount,
4354 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4355 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4356 
4357 	st_start(un);
4358 
4359 	mutex_exit(ST_MUTEX);
4360 	return (0);
4361 }
4362 
4363 /*
4364  * this routine spaces forward over filemarks
4365  */
4366 static int
4367 st_space_fmks(struct scsi_tape *un, long count)
4368 {
4369 	int rval = 0;
4370 
4371 	ST_FUNC(ST_DEVINFO, st_space_fmks);
4372 
4373 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4374 	    "st_space_fmks(dev = 0x%lx, count = %ld)\n", un->un_dev, count);
4375 
4376 	ASSERT(mutex_owned(ST_MUTEX));
4377 
4378 	/*
4379 	 * the risk with doing only one space operation is that we
4380 	 * may accidentily jump in old data
4381 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4382 	 * because the 8200 does not append a marker; in order not to
4383 	 * sacrifice the fast file skip, we do a slow skip if the low
4384 	 * density device has been opened
4385 	 */
4386 
4387 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4388 	    !((un->un_dp->type == ST_TYPE_EXB8500 &&
4389 	    MT_DENSITY(un->un_dev) == 0))) {
4390 		if (st_cmd(un, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4391 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4392 			    "space_fmks : EIO can't do space cmd #1\n");
4393 			rval = EIO;
4394 		}
4395 	} else {
4396 		while (count > 0) {
4397 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4398 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4399 				    "space_fmks : EIO can't do space cmd #2\n");
4400 				rval = EIO;
4401 				break;
4402 			}
4403 			count -= 1;
4404 			/*
4405 			 * read a block to see if we have reached
4406 			 * end of medium (double filemark for reel or
4407 			 * medium error for others)
4408 			 */
4409 			if (count > 0) {
4410 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
4411 					ST_DEBUG2(ST_DEVINFO, st_label,
4412 					    SCSI_DEBUG,
4413 					    "space_fmks : EIO can't do "
4414 					    "space cmd #3\n");
4415 					rval = EIO;
4416 					break;
4417 				}
4418 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4419 				    (un->un_dp->options & ST_REEL)) {
4420 					un->un_status = SUN_KEY_EOT;
4421 					ST_DEBUG2(ST_DEVINFO, st_label,
4422 					    SCSI_DEBUG,
4423 					    "space_fmks : EIO ST_REEL\n");
4424 					rval = EIO;
4425 					break;
4426 				} else if (IN_EOF(un->un_pos)) {
4427 					un->un_pos.eof = ST_NO_EOF;
4428 					un->un_pos.fileno++;
4429 					un->un_pos.blkno = 0;
4430 					count--;
4431 				} else if (un->un_pos.eof > ST_EOF) {
4432 					ST_DEBUG2(ST_DEVINFO, st_label,
4433 					    SCSI_DEBUG,
4434 					    "space_fmks, EIO > ST_EOF\n");
4435 					rval = EIO;
4436 					break;
4437 				}
4438 
4439 			}
4440 		}
4441 		un->un_err_resid = count;
4442 		COPY_POS(&un->un_pos, &un->un_err_pos);
4443 	}
4444 	ASSERT(mutex_owned(ST_MUTEX));
4445 	return (rval);
4446 }
4447 
4448 /*
4449  * this routine spaces to EOD
4450  *
4451  * it keeps track of the current filenumber and returns the filenumber after
4452  * the last successful space operation, we keep the number high because as
4453  * tapes are getting larger, the possibility of more and more files exist,
4454  * 0x100000 (1 Meg of files) probably will never have to be changed any time
4455  * soon
4456  */
4457 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4458 
4459 static int
4460 st_find_eod(struct scsi_tape *un)
4461 {
4462 	tapepos_t savepos;
4463 	int64_t sp_type;
4464 	int result;
4465 
4466 	if (un == NULL) {
4467 		return (-1);
4468 	}
4469 
4470 	ST_FUNC(ST_DEVINFO, st_find_eod);
4471 
4472 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4473 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", un->un_dev,
4474 	    un->un_pos.fileno);
4475 
4476 	ASSERT(mutex_owned(ST_MUTEX));
4477 
4478 	COPY_POS(&savepos, &un->un_pos);
4479 
4480 	/*
4481 	 * see if the drive is smart enough to do the skips in
4482 	 * one operation; 1/2" use two filemarks
4483 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4484 	 * because the 8200 does not append a marker; in order not to
4485 	 * sacrifice the fast file skip, we do a slow skip if the low
4486 	 * density device has been opened
4487 	 */
4488 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4489 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4490 		    (MT_DENSITY(un->un_dev) == 0)) {
4491 			sp_type = Fmk(1);
4492 		} else if (un->un_pos.pmode == logical) {
4493 			sp_type = SPACE(SP_EOD, 0);
4494 		} else {
4495 			sp_type = Fmk(MAX_SKIP);
4496 		}
4497 	} else {
4498 		sp_type = Fmk(1);
4499 	}
4500 
4501 	for (;;) {
4502 		result = st_cmd(un, SCMD_SPACE, sp_type, SYNC_CMD);
4503 
4504 		if (result == 0) {
4505 			COPY_POS(&savepos, &un->un_pos);
4506 		}
4507 
4508 		if (sp_type == SPACE(SP_EOD, 0)) {
4509 			if (result != 0) {
4510 				sp_type = Fmk(MAX_SKIP);
4511 				continue;
4512 			}
4513 
4514 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4515 			    "st_find_eod: 0x%"PRIx64"\n",
4516 			    savepos.lgclblkno);
4517 			/*
4518 			 * What we return will become the current file position.
4519 			 * After completing the space command with the position
4520 			 * mode that is not invalid a read position command will
4521 			 * be automaticly issued. If the drive support the long
4522 			 * read position format a valid file position can be
4523 			 * returned.
4524 			 */
4525 			return (un->un_pos.fileno);
4526 		}
4527 
4528 		if (result != 0) {
4529 			break;
4530 		}
4531 
4532 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4533 		    "count=%"PRIx64", eof=%x, status=%x\n",
4534 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4535 
4536 		/*
4537 		 * If we're not EOM smart,  space a record
4538 		 * to see whether we're now in the slot between
4539 		 * the two sequential filemarks that logical
4540 		 * EOM consists of (REEL) or hit nowhere land
4541 		 * (8mm).
4542 		 */
4543 		if (sp_type == Fmk(1)) {
4544 			/*
4545 			 * no fast skipping, check a record
4546 			 */
4547 			if (st_cmd(un, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4548 				break;
4549 			}
4550 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4551 			    (un->un_dp->options & ST_REEL)) {
4552 				un->un_status = KEY_BLANK_CHECK;
4553 				un->un_pos.fileno++;
4554 				un->un_pos.blkno = 0;
4555 				break;
4556 			}
4557 			if (IN_EOF(un->un_pos)) {
4558 				un->un_pos.eof = ST_NO_EOF;
4559 				un->un_pos.fileno++;
4560 				un->un_pos.blkno = 0;
4561 			}
4562 			if (un->un_pos.eof > ST_EOF) {
4563 				break;
4564 			}
4565 		} else {
4566 			if (un->un_pos.eof > ST_EOF) {
4567 				break;
4568 			}
4569 		}
4570 	}
4571 
4572 	if (un->un_dp->options & ST_KNOWS_EOD) {
4573 		COPY_POS(&savepos, &un->un_pos);
4574 	}
4575 
4576 	ASSERT(mutex_owned(ST_MUTEX));
4577 
4578 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4579 	    "st_find_eod: %x\n", savepos.fileno);
4580 	return (savepos.fileno);
4581 }
4582 
4583 
4584 /*
4585  * this routine is frequently used in ioctls below;
4586  * it determines whether we know the density and if not will
4587  * determine it
4588  * if we have written the tape before, one or more filemarks are written
4589  *
4590  * depending on the stepflag, the head is repositioned to where it was before
4591  * the filemarks were written in order not to confuse step counts
4592  */
4593 #define	STEPBACK    0
4594 #define	NO_STEPBACK 1
4595 
4596 static int
4597 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4598 {
4599 
4600 	GET_SOFT_STATE(dev);
4601 
4602 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4603 
4604 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4605 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4606 	    "\n", dev, wfm, mode, stepflag);
4607 
4608 	ASSERT(mutex_owned(ST_MUTEX));
4609 
4610 	/*
4611 	 * If we don't yet know the density of the tape we have inserted,
4612 	 * we have to either unconditionally set it (if we're 'writing'),
4613 	 * or we have to determine it. As side effects, check for any
4614 	 * write-protect errors, and for the need to put out any file-marks
4615 	 * before positioning a tape.
4616 	 *
4617 	 * If we are going to be spacing forward, and we haven't determined
4618 	 * the tape density yet, we have to do so now...
4619 	 */
4620 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4621 		if (st_determine_density(un, mode)) {
4622 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4623 			    "check_density_or_wfm : EIO can't determine "
4624 			    "density\n");
4625 			un->un_errno = EIO;
4626 			return (EIO);
4627 		}
4628 		/*
4629 		 * Presumably we are at BOT. If we attempt to write, it will
4630 		 * either work okay, or bomb. We don't do a st_test_append
4631 		 * unless we're past BOT.
4632 		 */
4633 		un->un_laststate = un->un_state;
4634 		un->un_state = ST_STATE_OPEN;
4635 
4636 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4637 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4638 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4639 
4640 		tapepos_t spos;
4641 
4642 		COPY_POS(&spos, &un->un_pos);
4643 
4644 		/*
4645 		 * We need to write one or two filemarks.
4646 		 * In the case of the HP, we need to
4647 		 * position the head between the two
4648 		 * marks.
4649 		 */
4650 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4651 			wfm = un->un_fmneeded;
4652 			un->un_fmneeded = 0;
4653 		}
4654 
4655 		if (st_write_fm(dev, wfm)) {
4656 			un->un_pos.pmode = invalid;
4657 			un->un_density_known = 0;
4658 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4659 			    "check_density_or_wfm : EIO can't write fm\n");
4660 			un->un_errno = EIO;
4661 			return (EIO);
4662 		}
4663 
4664 		if (stepflag == STEPBACK) {
4665 			if (st_cmd(un, SCMD_SPACE, Fmk(-wfm), SYNC_CMD)) {
4666 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4667 				    "check_density_or_wfm : EIO can't space "
4668 				    "(-wfm)\n");
4669 				un->un_errno = EIO;
4670 				return (EIO);
4671 			}
4672 			COPY_POS(&un->un_pos, &spos);
4673 		}
4674 	}
4675 
4676 	/*
4677 	 * Whatever we do at this point clears the state of the eof flag.
4678 	 */
4679 
4680 	un->un_pos.eof = ST_NO_EOF;
4681 
4682 	/*
4683 	 * If writing, let's check that we're positioned correctly
4684 	 * at the end of tape before issuing the next write.
4685 	 */
4686 	if (un->un_read_only == RDWR) {
4687 		un->un_test_append = 1;
4688 	}
4689 
4690 	ASSERT(mutex_owned(ST_MUTEX));
4691 	return (0);
4692 }
4693 
4694 
4695 /*
4696  * Wait for all outstaning I/O's to complete
4697  *
4698  * we wait on both ncmds and the wait queue for times when we are flushing
4699  * after persistent errors are flagged, which is when ncmds can be 0, and the
4700  * queue can still have I/O's.  This way we preserve order of biodone's.
4701  */
4702 static void
4703 st_wait_for_io(struct scsi_tape *un)
4704 {
4705 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4706 	ASSERT(mutex_owned(ST_MUTEX));
4707 	while ((un->un_ncmds) || (un->un_quef) || (un->un_runqf)) {
4708 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4709 	}
4710 }
4711 
4712 /*
4713  * This routine implements the ioctl calls.  It is called
4714  * from the device switch at normal priority.
4715  */
4716 /*ARGSUSED*/
4717 static int
4718 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4719     int *rval_p)
4720 {
4721 	int tmp, rval = 0;
4722 
4723 	GET_SOFT_STATE(dev);
4724 
4725 	ST_ENTR(ST_DEVINFO, st_ioctl);
4726 
4727 	mutex_enter(ST_MUTEX);
4728 
4729 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4730 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4731 	    "pe_flag = %d\n",
4732 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4733 	    un->un_persistence && un->un_persist_errors);
4734 
4735 	/*
4736 	 * We don't want to block on these, so let them through
4737 	 * and we don't care about setting driver states here.
4738 	 */
4739 	if ((cmd == MTIOCGETDRIVETYPE) ||
4740 	    (cmd == MTIOCGUARANTEEDORDER) ||
4741 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4742 		goto check_commands;
4743 	}
4744 
4745 	/*
4746 	 * We clear error entry stack except command
4747 	 * MTIOCGETERROR and MTIOCGET
4748 	 */
4749 	if ((cmd != MTIOCGETERROR) &&
4750 	    (cmd != MTIOCGET)) {
4751 		st_empty_error_stack(un);
4752 	}
4753 
4754 	/*
4755 	 * wait for all outstanding commands to complete, or be dequeued.
4756 	 * And because ioctl's are synchronous commands, any return value
4757 	 * after this,  will be in order
4758 	 */
4759 	st_wait_for_io(un);
4760 
4761 	/*
4762 	 * allow only a through clear errors and persistent status, and
4763 	 * status
4764 	 */
4765 	if (un->un_persistence && un->un_persist_errors) {
4766 		if ((cmd == MTIOCLRERR) ||
4767 		    (cmd == MTIOCPERSISTENT) ||
4768 		    (cmd == MTIOCGET)) {
4769 			goto check_commands;
4770 		} else {
4771 			rval = un->un_errno;
4772 			goto exit;
4773 		}
4774 	}
4775 
4776 	ASSERT(un->un_throttle != 0);
4777 	un->un_throttle = 1;	/* > 1 will never happen here */
4778 	un->un_errno = 0;	/* start clean from here */
4779 
4780 	/*
4781 	 * first and foremost, handle any ST_EOT_PENDING cases.
4782 	 * That is, if a logical eot is pending notice, notice it.
4783 	 */
4784 	if (un->un_pos.eof == ST_EOT_PENDING) {
4785 		int resid = un->un_err_resid;
4786 		uchar_t status = un->un_status;
4787 		uchar_t lastop = un->un_lastop;
4788 
4789 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4790 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4791 			    "stioctl : EIO can't space fmk(-1)\n");
4792 			rval = EIO;
4793 			goto exit;
4794 		}
4795 		un->un_lastop = lastop; /* restore last operation */
4796 		if (status == SUN_KEY_EOF) {
4797 			un->un_status = SUN_KEY_EOT;
4798 		} else {
4799 			un->un_status = status;
4800 		}
4801 		un->un_err_resid  = resid;
4802 		/* fix up block number */
4803 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4804 		/* now we're at logical eot */
4805 		un->un_pos.eof = ST_EOT;
4806 	}
4807 
4808 	/*
4809 	 * now, handle the rest of the situations
4810 	 */
4811 check_commands:
4812 	switch (cmd) {
4813 	case MTIOCGET:
4814 	{
4815 #ifdef _MULTI_DATAMODEL
4816 		/*
4817 		 * For use when a 32 bit app makes a call into a
4818 		 * 64 bit ioctl
4819 		 */
4820 		struct mtget32		mtg_local32;
4821 		struct mtget32 		*mtget_32 = &mtg_local32;
4822 #endif /* _MULTI_DATAMODEL */
4823 
4824 			/* Get tape status */
4825 		struct mtget mtg_local;
4826 		struct mtget *mtget = &mtg_local;
4827 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4828 		    "st_ioctl: MTIOCGET\n");
4829 
4830 		bzero((caddr_t)mtget, sizeof (struct mtget));
4831 		mtget->mt_erreg = un->un_status;
4832 		mtget->mt_resid = un->un_err_resid;
4833 		mtget->mt_dsreg = un->un_retry_ct;
4834 		if (un->un_err_pos.pmode == legacy) {
4835 			mtget->mt_fileno = un->un_err_pos.fileno;
4836 		} else {
4837 			mtget->mt_fileno = -1;
4838 		}
4839 		/*
4840 		 * If the value is positive fine.
4841 		 * If its negative we need to return a value based on the
4842 		 * old way if counting backwards from INF (1,000,000,000).
4843 		 */
4844 		if (un->un_err_pos.blkno >= 0) {
4845 			mtget->mt_blkno = un->un_err_pos.blkno;
4846 		} else {
4847 			mtget->mt_blkno = INF + 1 - (-un->un_err_pos.blkno);
4848 		}
4849 		mtget->mt_type = un->un_dp->type;
4850 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
4851 		if (un->un_read_pos_type != NO_POS) {
4852 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
4853 		}
4854 		if (un->un_dp->options & ST_REEL) {
4855 			mtget->mt_flags |= MTF_REEL;
4856 			mtget->mt_bf = 20;
4857 		} else {		/* 1/4" cartridges */
4858 			switch (mtget->mt_type) {
4859 			/* Emulex cartridge tape */
4860 			case MT_ISMT02:
4861 				mtget->mt_bf = 40;
4862 				break;
4863 			default:
4864 				mtget->mt_bf = 126;
4865 				break;
4866 			}
4867 		}
4868 
4869 		/*
4870 		 * If large transfers are allowed and drive options
4871 		 * has no record size limit set. Calculate blocking
4872 		 * factor from the lesser of maxbsize and maxdma.
4873 		 */
4874 		if ((un->un_allow_large_xfer) &&
4875 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
4876 			mtget->mt_bf = min(un->un_maxbsize,
4877 			    un->un_maxdma) / SECSIZE;
4878 		}
4879 
4880 		if (un->un_read_only == WORM ||
4881 		    un->un_read_only == RDWORM) {
4882 			mtget->mt_flags |= MTF_WORM_MEDIA;
4883 		}
4884 
4885 		/*
4886 		 * In persistent error mode sending a non-queued can hang
4887 		 * because this ioctl gets to be run without turning off
4888 		 * persistense. Fake the answer based on previous info.
4889 		 */
4890 		if (un->un_persistence) {
4891 			if ((un->un_HeadClean & (TAPE_ALERT_SUPPORTED |
4892 			    TAPE_SEQUENTIAL_SUPPORTED|TAPE_ALERT_NOT_SUPPORTED))
4893 			    != TAPE_ALERT_NOT_SUPPORTED) {
4894 				mtget->mt_flags |= MTF_TAPE_CLN_SUPPORTED;
4895 			}
4896 			if (un->un_HeadClean & (TAPE_PREVIOUSLY_DIRTY |
4897 			    TAPE_ALERT_STILL_DIRTY)) {
4898 				mtget->mt_flags |= MTF_TAPE_HEAD_DIRTY;
4899 			}
4900 			rval = 0;
4901 		} else {
4902 			rval = st_check_clean_bit(un);
4903 		}
4904 		if (rval == -1) {
4905 			rval = EIO;
4906 			goto exit;
4907 		} else {
4908 			mtget->mt_flags |= (ushort_t)rval;
4909 			rval = 0;
4910 		}
4911 
4912 		un->un_status = 0;		/* Reset status */
4913 		un->un_err_resid = 0;
4914 		tmp = sizeof (struct mtget);
4915 
4916 #ifdef _MULTI_DATAMODEL
4917 
4918 		switch (ddi_model_convert_from(flag & FMODELS)) {
4919 		case DDI_MODEL_ILP32:
4920 			/*
4921 			 * Convert 64 bit back to 32 bit before doing
4922 			 * copyout. This is what the ILP32 app expects.
4923 			 */
4924 			mtget_32->mt_erreg = 	mtget->mt_erreg;
4925 			mtget_32->mt_resid = 	mtget->mt_resid;
4926 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
4927 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
4928 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
4929 			mtget_32->mt_type =  	mtget->mt_type;
4930 			mtget_32->mt_flags = 	mtget->mt_flags;
4931 			mtget_32->mt_bf = 	mtget->mt_bf;
4932 
4933 			if (ddi_copyout(mtget_32, (void *)arg,
4934 			    sizeof (struct mtget32), flag)) {
4935 				rval = EFAULT;
4936 			}
4937 			break;
4938 
4939 		case DDI_MODEL_NONE:
4940 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4941 				rval = EFAULT;
4942 			}
4943 			break;
4944 		}
4945 #else /* ! _MULTI_DATAMODE */
4946 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4947 			rval = EFAULT;
4948 		}
4949 #endif /* _MULTI_DATAMODE */
4950 
4951 		break;
4952 	}
4953 	case MTIOCGETERROR:
4954 			/*
4955 			 * get error entry from error stack
4956 			 */
4957 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4958 			    "st_ioctl: MTIOCGETERROR\n");
4959 
4960 			rval = st_get_error_entry(un, arg, flag);
4961 
4962 			break;
4963 
4964 	case MTIOCSTATE:
4965 		{
4966 			/*
4967 			 * return when media presence matches state
4968 			 */
4969 			enum mtio_state state;
4970 
4971 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4972 			    "st_ioctl: MTIOCSTATE\n");
4973 
4974 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
4975 				rval = EFAULT;
4976 
4977 			mutex_exit(ST_MUTEX);
4978 
4979 			rval = st_check_media(dev, state);
4980 
4981 			mutex_enter(ST_MUTEX);
4982 
4983 			if (rval != 0) {
4984 				break;
4985 			}
4986 
4987 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
4988 			    sizeof (int), flag))
4989 				rval = EFAULT;
4990 			break;
4991 
4992 		}
4993 
4994 	case MTIOCGETDRIVETYPE:
4995 		{
4996 #ifdef _MULTI_DATAMODEL
4997 		/*
4998 		 * For use when a 32 bit app makes a call into a
4999 		 * 64 bit ioctl
5000 		 */
5001 		struct mtdrivetype_request32	mtdtrq32;
5002 #endif /* _MULTI_DATAMODEL */
5003 
5004 			/*
5005 			 * return mtdrivetype
5006 			 */
5007 			struct mtdrivetype_request mtdtrq;
5008 			struct mtdrivetype mtdrtyp;
5009 			struct mtdrivetype *mtdt = &mtdrtyp;
5010 			struct st_drivetype *stdt = un->un_dp;
5011 
5012 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5013 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
5014 
5015 #ifdef _MULTI_DATAMODEL
5016 		switch (ddi_model_convert_from(flag & FMODELS)) {
5017 		case DDI_MODEL_ILP32:
5018 		{
5019 			if (ddi_copyin((void *)arg, &mtdtrq32,
5020 			    sizeof (struct mtdrivetype_request32), flag)) {
5021 				rval = EFAULT;
5022 				break;
5023 			}
5024 			mtdtrq.size = mtdtrq32.size;
5025 			mtdtrq.mtdtp =
5026 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
5027 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5028 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
5029 			break;
5030 		}
5031 		case DDI_MODEL_NONE:
5032 			if (ddi_copyin((void *)arg, &mtdtrq,
5033 			    sizeof (struct mtdrivetype_request), flag)) {
5034 				rval = EFAULT;
5035 				break;
5036 			}
5037 			break;
5038 		}
5039 
5040 #else /* ! _MULTI_DATAMODEL */
5041 		if (ddi_copyin((void *)arg, &mtdtrq,
5042 		    sizeof (struct mtdrivetype_request), flag)) {
5043 			rval = EFAULT;
5044 			break;
5045 		}
5046 #endif /* _MULTI_DATAMODEL */
5047 
5048 			/*
5049 			 * if requested size is < 0 then return
5050 			 * error.
5051 			 */
5052 			if (mtdtrq.size < 0) {
5053 				rval = EINVAL;
5054 				break;
5055 			}
5056 			bzero(mtdt, sizeof (struct mtdrivetype));
5057 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
5058 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
5059 			mtdt->type = stdt->type;
5060 			mtdt->bsize = stdt->bsize;
5061 			mtdt->options = stdt->options;
5062 			mtdt->max_rretries = stdt->max_rretries;
5063 			mtdt->max_wretries = stdt->max_wretries;
5064 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5065 				mtdt->densities[tmp] = stdt->densities[tmp];
5066 			}
5067 			mtdt->default_density = stdt->default_density;
5068 			/*
5069 			 * Speed hasn't been used since the hayday of reel tape.
5070 			 * For all drives not setting the option ST_KNOWS_MEDIA
5071 			 * the speed member renamed to mediatype are zeros.
5072 			 * Those drives that have ST_KNOWS_MEDIA set use the
5073 			 * new mediatype member which is used to figure the
5074 			 * type of media loaded.
5075 			 *
5076 			 * So as to not break applications speed in the
5077 			 * mtdrivetype structure is not renamed.
5078 			 */
5079 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5080 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
5081 			}
5082 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
5083 			mtdt->io_timeout = stdt->io_timeout;
5084 			mtdt->rewind_timeout = stdt->rewind_timeout;
5085 			mtdt->space_timeout = stdt->space_timeout;
5086 			mtdt->load_timeout = stdt->load_timeout;
5087 			mtdt->unload_timeout = stdt->unload_timeout;
5088 			mtdt->erase_timeout = stdt->erase_timeout;
5089 
5090 			/*
5091 			 * Limit the maximum length of the result to
5092 			 * sizeof (struct mtdrivetype).
5093 			 */
5094 			tmp = sizeof (struct mtdrivetype);
5095 			if (mtdtrq.size < tmp)
5096 				tmp = mtdtrq.size;
5097 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
5098 				rval = EFAULT;
5099 			}
5100 			break;
5101 		}
5102 	case MTIOCPERSISTENT:
5103 
5104 		if (ddi_copyin((void *)arg, &tmp, sizeof (tmp), flag)) {
5105 			rval = EFAULT;
5106 			break;
5107 		}
5108 
5109 		if (tmp) {
5110 			st_turn_pe_on(un);
5111 		} else {
5112 			st_turn_pe_off(un);
5113 		}
5114 
5115 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5116 		    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
5117 		    un->un_persistence);
5118 
5119 		break;
5120 
5121 	case MTIOCPERSISTENTSTATUS:
5122 		tmp = (int)un->un_persistence;
5123 
5124 		if (ddi_copyout(&tmp, (void *)arg, sizeof (tmp), flag)) {
5125 			rval = EFAULT;
5126 		}
5127 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5128 		    "st_ioctl: MTIOCPERSISTENTSTATUS:persistence = %d\n",
5129 		    un->un_persistence);
5130 
5131 		break;
5132 
5133 	case MTIOCLRERR:
5134 		{
5135 			/* clear persistent errors */
5136 
5137 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5138 			    "st_ioctl: MTIOCLRERR\n");
5139 
5140 			st_clear_pe(un);
5141 
5142 			break;
5143 		}
5144 
5145 	case MTIOCGUARANTEEDORDER:
5146 		{
5147 			/*
5148 			 * this is just a holder to make a valid ioctl and
5149 			 * it won't be in any earlier release
5150 			 */
5151 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5152 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
5153 
5154 			break;
5155 		}
5156 
5157 	case MTIOCRESERVE:
5158 		{
5159 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5160 			    "st_ioctl: MTIOCRESERVE\n");
5161 
5162 			/*
5163 			 * Check if Reserve/Release is supported.
5164 			 */
5165 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5166 				rval = ENOTTY;
5167 				break;
5168 			}
5169 
5170 			rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5171 
5172 			if (rval == 0) {
5173 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
5174 			}
5175 			break;
5176 		}
5177 
5178 	case MTIOCRELEASE:
5179 		{
5180 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5181 			    "st_ioctl: MTIOCRELEASE\n");
5182 
5183 			/*
5184 			 * Check if Reserve/Release is supported.
5185 			 */
5186 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5187 				rval = ENOTTY;
5188 				break;
5189 			}
5190 
5191 			/*
5192 			 * Used to just clear ST_PRESERVE_RESERVE which
5193 			 * made the reservation release at next close.
5194 			 * As the user may have opened and then done a
5195 			 * persistant reservation we now need to drop
5196 			 * the reservation without closing if the user
5197 			 * attempts to do this.
5198 			 */
5199 			rval = st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
5200 
5201 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5202 
5203 			break;
5204 		}
5205 
5206 	case MTIOCFORCERESERVE:
5207 	{
5208 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5209 		    "st_ioctl: MTIOCFORCERESERVE\n");
5210 
5211 		/*
5212 		 * Check if Reserve/Release is supported.
5213 		 */
5214 		if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5215 			rval = ENOTTY;
5216 			break;
5217 		}
5218 		/*
5219 		 * allow only super user to run this.
5220 		 */
5221 		if (drv_priv(cred_p) != 0) {
5222 			rval = EPERM;
5223 			break;
5224 		}
5225 		/*
5226 		 * Throw away reserve,
5227 		 * not using test-unit-ready
5228 		 * since reserve can succeed without tape being
5229 		 * present in the drive.
5230 		 */
5231 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5232 
5233 		rval = st_take_ownership(un);
5234 
5235 		break;
5236 	}
5237 
5238 	case USCSICMD:
5239 	{
5240 		cred_t	*cr;
5241 
5242 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5243 		    "st_ioctl: USCSICMD\n");
5244 
5245 		cr = ddi_get_cred();
5246 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5247 			rval = EPERM;
5248 		} else {
5249 			rval = st_uscsi_cmd(un, (struct uscsi_cmd *)arg, flag);
5250 		}
5251 		break;
5252 	}
5253 	case MTIOCTOP:
5254 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5255 		    "st_ioctl: MTIOCTOP\n");
5256 		rval = st_mtioctop(un, arg, flag);
5257 		break;
5258 
5259 	case MTIOCLTOP:
5260 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5261 		    "st_ioctl: MTIOLCTOP\n");
5262 		rval = st_mtiocltop(un, arg, flag);
5263 		break;
5264 
5265 	case MTIOCREADIGNOREILI:
5266 		{
5267 			int set_ili;
5268 
5269 			if (ddi_copyin((void *)arg, &set_ili,
5270 			    sizeof (set_ili), flag)) {
5271 				rval = EFAULT;
5272 				break;
5273 			}
5274 
5275 			if (un->un_bsize) {
5276 				rval = ENOTTY;
5277 				break;
5278 			}
5279 
5280 			switch (set_ili) {
5281 			case 0:
5282 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5283 				break;
5284 
5285 			case 1:
5286 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5287 				break;
5288 
5289 			default:
5290 				rval = EINVAL;
5291 				break;
5292 			}
5293 			break;
5294 		}
5295 
5296 	case MTIOCREADIGNOREEOFS:
5297 		{
5298 			int ignore_eof;
5299 
5300 			if (ddi_copyin((void *)arg, &ignore_eof,
5301 			    sizeof (ignore_eof), flag)) {
5302 				rval = EFAULT;
5303 				break;
5304 			}
5305 
5306 			if (!(un->un_dp->options & ST_REEL)) {
5307 				rval = ENOTTY;
5308 				break;
5309 			}
5310 
5311 			switch (ignore_eof) {
5312 			case 0:
5313 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5314 				break;
5315 
5316 			case 1:
5317 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5318 				break;
5319 
5320 			default:
5321 				rval = EINVAL;
5322 				break;
5323 			}
5324 			break;
5325 		}
5326 
5327 	case MTIOCSHORTFMK:
5328 	{
5329 		int short_fmk;
5330 
5331 		if (ddi_copyin((void *)arg, &short_fmk,
5332 		    sizeof (short_fmk), flag)) {
5333 			rval = EFAULT;
5334 			break;
5335 		}
5336 
5337 		switch (un->un_dp->type) {
5338 		case ST_TYPE_EXB8500:
5339 		case ST_TYPE_EXABYTE:
5340 			if (!short_fmk) {
5341 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5342 			} else if (short_fmk == 1) {
5343 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5344 			} else {
5345 				rval = EINVAL;
5346 			}
5347 			break;
5348 
5349 		default:
5350 			rval = ENOTTY;
5351 			break;
5352 		}
5353 		break;
5354 	}
5355 
5356 	case MTIOCGETPOS:
5357 		rval = st_update_block_pos(un, st_cmd, 0);
5358 		if (rval == 0) {
5359 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5360 			    sizeof (tapepos_t), flag)) {
5361 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5362 				    "MTIOCGETPOS copy out failed\n");
5363 				rval = EFAULT;
5364 			}
5365 		}
5366 		break;
5367 
5368 	case MTIOCRESTPOS:
5369 	{
5370 		tapepos_t dest;
5371 
5372 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5373 		    flag) != 0) {
5374 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5375 			    "MTIOCRESTPOS copy in failed\n");
5376 			rval = EFAULT;
5377 			break;
5378 		}
5379 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &dest);
5380 		if (rval != 0) {
5381 			rval = EIO;
5382 		}
5383 		break;
5384 	}
5385 	default:
5386 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5387 		    "st_ioctl: unknown ioctl\n");
5388 		rval = ENOTTY;
5389 	}
5390 
5391 exit:
5392 	if (!(un->un_persistence && un->un_persist_errors)) {
5393 		un->un_errno = rval;
5394 	}
5395 
5396 	mutex_exit(ST_MUTEX);
5397 
5398 	return (rval);
5399 }
5400 
5401 
5402 /*
5403  * do some MTIOCTOP tape operations
5404  */
5405 static int
5406 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5407 {
5408 #ifdef _MULTI_DATAMODEL
5409 	/*
5410 	 * For use when a 32 bit app makes a call into a
5411 	 * 64 bit ioctl
5412 	 */
5413 	struct mtop32	mtop_32_for_64;
5414 #endif /* _MULTI_DATAMODEL */
5415 	struct mtop passed;
5416 	struct mtlop local;
5417 	int rval = 0;
5418 
5419 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5420 
5421 	ASSERT(mutex_owned(ST_MUTEX));
5422 
5423 #ifdef _MULTI_DATAMODEL
5424 	switch (ddi_model_convert_from(flag & FMODELS)) {
5425 	case DDI_MODEL_ILP32:
5426 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5427 		    sizeof (struct mtop32), flag)) {
5428 			return (EFAULT);
5429 		}
5430 		local.mt_op = mtop_32_for_64.mt_op;
5431 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5432 		break;
5433 
5434 	case DDI_MODEL_NONE:
5435 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5436 			return (EFAULT);
5437 		}
5438 		local.mt_op = passed.mt_op;
5439 		/* prevent sign extention */
5440 		local.mt_count = (UINT32_MAX & passed.mt_count);
5441 		break;
5442 	}
5443 
5444 #else /* ! _MULTI_DATAMODEL */
5445 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5446 		return (EFAULT);
5447 	}
5448 	local.mt_op = passed.mt_op;
5449 	/* prevent sign extention */
5450 	local.mt_count = (UINT32_MAX & passed.mt_count);
5451 #endif /* _MULTI_DATAMODEL */
5452 
5453 	rval = st_do_mtioctop(un, &local);
5454 
5455 #ifdef _MULTI_DATAMODEL
5456 	switch (ddi_model_convert_from(flag & FMODELS)) {
5457 	case DDI_MODEL_ILP32:
5458 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5459 			rval = ERANGE;
5460 			break;
5461 		}
5462 		/*
5463 		 * Convert 64 bit back to 32 bit before doing
5464 		 * copyout. This is what the ILP32 app expects.
5465 		 */
5466 		mtop_32_for_64.mt_op = local.mt_op;
5467 		mtop_32_for_64.mt_count = local.mt_count;
5468 
5469 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5470 		    sizeof (struct mtop32), flag)) {
5471 			rval = EFAULT;
5472 		}
5473 		break;
5474 
5475 	case DDI_MODEL_NONE:
5476 		passed.mt_count = local.mt_count;
5477 		passed.mt_op = local.mt_op;
5478 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5479 			rval = EFAULT;
5480 		}
5481 		break;
5482 	}
5483 #else /* ! _MULTI_DATAMODE */
5484 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5485 		rval = ERANGE;
5486 	} else {
5487 		passed.mt_op = local.mt_op;
5488 		passed.mt_count = local.mt_count;
5489 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5490 			rval = EFAULT;
5491 		}
5492 	}
5493 #endif /* _MULTI_DATAMODE */
5494 
5495 
5496 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5497 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5498 	    un->un_pos.blkno, un->un_pos.eof);
5499 
5500 	if (un->un_pos.pmode == invalid) {
5501 		un->un_density_known = 0;
5502 	}
5503 
5504 	ASSERT(mutex_owned(ST_MUTEX));
5505 	return (rval);
5506 }
5507 
5508 static int
5509 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5510 {
5511 	struct mtlop local;
5512 	int rval;
5513 
5514 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5515 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5516 		return (EFAULT);
5517 	}
5518 
5519 	rval = st_do_mtioctop(un, &local);
5520 
5521 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5522 		rval = EFAULT;
5523 	}
5524 	return (rval);
5525 }
5526 
5527 
5528 static int
5529 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5530 {
5531 	dev_t dev = un->un_dev;
5532 	int savefile;
5533 	int rval = 0;
5534 
5535 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5536 
5537 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5538 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5539 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5540 	    "fileno=%x, blkno=%x, eof=%x\n",
5541 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5542 
5543 	un->un_status = 0;
5544 
5545 	/*
5546 	 * if we are going to mess with a tape, we have to make sure we have
5547 	 * one and are not offline (i.e. no tape is initialized).  We let
5548 	 * commands pass here that don't actually touch the tape, except for
5549 	 * loading and initialization (rewinding).
5550 	 */
5551 	if (un->un_state == ST_STATE_OFFLINE) {
5552 		switch (mtop->mt_op) {
5553 		case MTLOAD:
5554 		case MTNOP:
5555 			/*
5556 			 * We don't want strategy calling st_tape_init here,
5557 			 * so, change state
5558 			 */
5559 			un->un_state = ST_STATE_INITIALIZING;
5560 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5561 			    "st_do_mtioctop : OFFLINE state = %d\n",
5562 			    un->un_state);
5563 			break;
5564 		default:
5565 			/*
5566 			 * reinitialize by normal means
5567 			 */
5568 			rval = st_tape_init(un);
5569 			if (rval) {
5570 				un->un_state = ST_STATE_INITIALIZING;
5571 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5572 				    "st_do_mtioctop : OFFLINE init failure ");
5573 				un->un_state = ST_STATE_OFFLINE;
5574 				un->un_pos.pmode = invalid;
5575 				if (rval != EACCES) {
5576 					rval = EIO;
5577 				}
5578 				return (rval);
5579 			}
5580 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5581 			break;
5582 		}
5583 	}
5584 
5585 	/*
5586 	 * If the file position is invalid, allow only those
5587 	 * commands that properly position the tape and fail
5588 	 * the rest with EIO
5589 	 */
5590 	if (un->un_pos.pmode == invalid) {
5591 		switch (mtop->mt_op) {
5592 		case MTWEOF:
5593 		case MTRETEN:
5594 		case MTERASE:
5595 		case MTEOM:
5596 		case MTFSF:
5597 		case MTFSR:
5598 		case MTBSF:
5599 		case MTNBSF:
5600 		case MTBSR:
5601 		case MTSRSZ:
5602 		case MTGRSZ:
5603 		case MTSEEK:
5604 		case MTBSSF:
5605 		case MTFSSF:
5606 			return (EIO);
5607 			/* NOTREACHED */
5608 		case MTREW:
5609 		case MTLOAD:
5610 		case MTOFFL:
5611 		case MTNOP:
5612 		case MTTELL:
5613 		case MTLOCK:
5614 		case MTUNLOCK:
5615 			break;
5616 
5617 		default:
5618 			return (ENOTTY);
5619 			/* NOTREACHED */
5620 		}
5621 	}
5622 
5623 	switch (mtop->mt_op) {
5624 	case MTERASE:
5625 		/*
5626 		 * MTERASE rewinds the tape, erase it completely, and returns
5627 		 * to the beginning of the tape
5628 		 */
5629 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5630 			un->un_status = KEY_WRITE_PROTECT;
5631 			un->un_err_resid = mtop->mt_count;
5632 			COPY_POS(&un->un_err_pos, &un->un_pos);
5633 			return (EACCES);
5634 		}
5635 		if (un->un_dp->options & ST_REEL) {
5636 			un->un_fmneeded = 2;
5637 		} else {
5638 			un->un_fmneeded = 1;
5639 		}
5640 		mtop->mt_count = mtop->mt_count ? 1 : 0;
5641 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5642 		    st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
5643 		    st_cmd(un, SCMD_ERASE, mtop->mt_count, SYNC_CMD)) {
5644 			un->un_pos.pmode = invalid;
5645 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5646 			    "st_do_mtioctop : EIO space or erase or "
5647 			    "check den)\n");
5648 			rval = EIO;
5649 		} else {
5650 			/* QIC and helical scan rewind after erase */
5651 			if (un->un_dp->options & ST_REEL) {
5652 				(void) st_cmd(un, SCMD_REWIND, 0, ASYNC_CMD);
5653 			}
5654 		}
5655 		break;
5656 
5657 	case MTWEOF:
5658 		/*
5659 		 * write an end-of-file record
5660 		 */
5661 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5662 			un->un_status = KEY_WRITE_PROTECT;
5663 			un->un_err_resid = mtop->mt_count;
5664 			COPY_POS(&un->un_err_pos, &un->un_pos);
5665 			return (EACCES);
5666 		}
5667 
5668 		/*
5669 		 * zero count means just flush buffers
5670 		 * negative count is not permitted
5671 		 */
5672 		if (mtop->mt_count < 0) {
5673 			return (EINVAL);
5674 		}
5675 
5676 		/* Not on worm */
5677 		if (un->un_read_only == RDWR) {
5678 			un->un_test_append = 1;
5679 		}
5680 
5681 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5682 			if (st_determine_density(un, B_WRITE)) {
5683 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5684 				    "st_do_mtioctop : EIO : MTWEOF can't "
5685 				    "determine density");
5686 				return (EIO);
5687 			}
5688 		}
5689 
5690 		rval = st_write_fm(dev, (int)mtop->mt_count);
5691 		if ((rval != 0) && (rval != EACCES)) {
5692 			/*
5693 			 * Failure due to something other than illegal
5694 			 * request results in loss of state (st_intr).
5695 			 */
5696 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5697 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5698 			    "file mark");
5699 			rval = EIO;
5700 		}
5701 		break;
5702 
5703 	case MTRETEN:
5704 		/*
5705 		 * retension the tape
5706 		 */
5707 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5708 		    st_cmd(un, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5709 			un->un_pos.pmode = invalid;
5710 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5711 			    "st_do_mtioctop : EIO : MTRETEN ");
5712 			rval = EIO;
5713 		}
5714 		break;
5715 
5716 	case MTREW:
5717 		/*
5718 		 * rewind  the tape
5719 		 */
5720 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5721 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5722 			    "st_do_mtioctop : EIO:MTREW check "
5723 			    "density/wfm failed");
5724 			return (EIO);
5725 		}
5726 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
5727 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5728 			    "st_do_mtioctop : EIO : MTREW ");
5729 			rval = EIO;
5730 		}
5731 		break;
5732 
5733 	case MTOFFL:
5734 		/*
5735 		 * rewinds, and, if appropriate, takes the device offline by
5736 		 * unloading the tape
5737 		 */
5738 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5739 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5740 			    "st_do_mtioctop :EIO:MTOFFL check "
5741 			    "density/wfm failed");
5742 			return (EIO);
5743 		}
5744 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
5745 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5746 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5747 			    "st_do_mtioctop : EIO : MTOFFL");
5748 			return (EIO);
5749 		}
5750 		un->un_pos.eof = ST_NO_EOF;
5751 		un->un_laststate = un->un_state;
5752 		un->un_state = ST_STATE_OFFLINE;
5753 		un->un_mediastate = MTIO_EJECTED;
5754 		break;
5755 
5756 	case MTLOAD:
5757 		/*
5758 		 * This is to load a tape into the drive
5759 		 * Note that if the tape is not loaded, the device will have
5760 		 * to be opened via O_NDELAY or O_NONBLOCK.
5761 		 */
5762 		/*
5763 		 * Let's try and clean things up, if we are not
5764 		 * initializing, and then send in the load command, no
5765 		 * matter what.
5766 		 *
5767 		 * load after a media change by the user.
5768 		 */
5769 
5770 		if (un->un_state > ST_STATE_INITIALIZING) {
5771 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5772 		}
5773 		rval = st_cmd(un, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5774 		/* Load command to a drive that doesn't support load */
5775 		if ((rval == EIO) &&
5776 		    ((un->un_status == KEY_NOT_READY) &&
5777 			/* Medium not present */
5778 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5779 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5780 		    (un->un_dp->type == MT_ISSTK9840) &&
5781 			/* CSL not present */
5782 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5783 			rval = ENOTTY;
5784 			break;
5785 		} else if (rval != EACCES && rval != 0) {
5786 			rval = EIO;
5787 		}
5788 		if (rval) {
5789 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5790 			    "st_do_mtioctop : %s : MTLOAD\n",
5791 			    rval == EACCES ? "EACCES" : "EIO");
5792 			/*
5793 			 * If load tape fails, who knows what happened...
5794 			 */
5795 			un->un_pos.pmode = invalid;
5796 			break;
5797 		}
5798 
5799 		/*
5800 		 * reset all counters appropriately using rewind, as if LOAD
5801 		 * succeeds, we are at BOT
5802 		 */
5803 		un->un_state = ST_STATE_INITIALIZING;
5804 
5805 		rval = st_tape_init(un);
5806 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5807 			rval = 0;
5808 			break;
5809 		}
5810 
5811 		if (rval != 0) {
5812 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5813 			    "st_do_mtioctop : EIO : MTLOAD calls "
5814 			    "st_tape_init\n");
5815 			rval = EIO;
5816 			un->un_state = ST_STATE_OFFLINE;
5817 		}
5818 
5819 		break;
5820 
5821 	case MTNOP:
5822 		un->un_status = 0;		/* Reset status */
5823 		un->un_err_resid = 0;
5824 		mtop->mt_count = MTUNIT(dev);
5825 		break;
5826 
5827 	case MTEOM:
5828 		/*
5829 		 * positions the tape at a location just after the last file
5830 		 * written on the tape. For cartridge and 8 mm, this after
5831 		 * the last file mark; for reel, this is inbetween the two
5832 		 * last 2 file marks
5833 		 */
5834 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5835 		    (un->un_lastop == ST_OP_WRITE) ||
5836 		    (un->un_lastop == ST_OP_WEOF)) {
5837 			/*
5838 			 * If the command wants to move to logical end
5839 			 * of media, and we're already there, we're done.
5840 			 * If we were at logical eot, we reset the state
5841 			 * to be *not* at logical eot.
5842 			 *
5843 			 * If we're at physical or logical eot, we prohibit
5844 			 * forward space operations (unconditionally).
5845 			 *
5846 			 * Also if the last operation was a write of any
5847 			 * kind the tape is at EOD.
5848 			 */
5849 			return (0);
5850 		}
5851 		/*
5852 		 * physical tape position may not be what we've been
5853 		 * telling the user; adjust the request accordingly
5854 		 */
5855 		if (IN_EOF(un->un_pos)) {
5856 			un->un_pos.fileno++;
5857 			un->un_pos.blkno = 0;
5858 		}
5859 
5860 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
5861 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5862 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
5863 			    " failed");
5864 			return (EIO);
5865 		}
5866 
5867 		/*
5868 		 * st_find_eod() returns the last fileno we knew about;
5869 		 */
5870 		savefile = st_find_eod(un);
5871 
5872 		if ((un->un_status != KEY_BLANK_CHECK) &&
5873 		    (un->un_status != SUN_KEY_EOT)) {
5874 			un->un_pos.pmode = invalid;
5875 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5876 			    "st_do_mtioctop : EIO : MTEOM status check failed");
5877 			rval = EIO;
5878 		} else {
5879 			/*
5880 			 * For 1/2" reel tapes assume logical EOT marked
5881 			 * by two file marks or we don't care that we may
5882 			 * be extending the last file on the tape.
5883 			 */
5884 			if (un->un_dp->options & ST_REEL) {
5885 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
5886 					un->un_pos.pmode = invalid;
5887 					ST_DEBUG2(ST_DEVINFO, st_label,
5888 					    SCSI_DEBUG,
5889 					    "st_do_mtioctop : EIO : MTEOM space"
5890 					    " cmd failed");
5891 					rval = EIO;
5892 					break;
5893 				}
5894 				/*
5895 				 * Fix up the block number.
5896 				 */
5897 				un->un_pos.blkno = 0;
5898 				un->un_err_pos.blkno = 0;
5899 			}
5900 			un->un_err_resid = 0;
5901 			un->un_pos.fileno = savefile;
5902 			un->un_pos.eof = ST_EOT;
5903 		}
5904 		un->un_status = 0;
5905 		break;
5906 
5907 	case MTFSF:
5908 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
5909 		break;
5910 
5911 	case MTFSR:
5912 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
5913 		break;
5914 
5915 	case MTBSF:
5916 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
5917 		break;
5918 
5919 	case MTNBSF:
5920 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
5921 		break;
5922 
5923 	case MTBSR:
5924 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
5925 		break;
5926 
5927 	case MTBSSF:
5928 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
5929 		break;
5930 
5931 	case MTFSSF:
5932 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
5933 		break;
5934 
5935 	case MTSRSZ:
5936 
5937 		/*
5938 		 * Set record-size to that sent by user
5939 		 * Check to see if there is reason that the requested
5940 		 * block size should not be set.
5941 		 */
5942 
5943 		/* If requesting variable block size is it ok? */
5944 		if ((mtop->mt_count == 0) &&
5945 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
5946 			return (ENOTTY);
5947 		}
5948 
5949 		/*
5950 		 * If requested block size is not variable "0",
5951 		 * is it less then minimum.
5952 		 */
5953 		if ((mtop->mt_count != 0) &&
5954 		    (mtop->mt_count < un->un_minbsize)) {
5955 			return (EINVAL);
5956 		}
5957 
5958 		/* Is the requested block size more then maximum */
5959 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
5960 		    (un->un_maxbsize != 0)) {
5961 			return (EINVAL);
5962 		}
5963 
5964 		/* Is requested block size a modulus the device likes */
5965 		if ((mtop->mt_count % un->un_data_mod) != 0) {
5966 			return (EINVAL);
5967 		}
5968 
5969 		if (st_change_block_size(un, (uint32_t)mtop->mt_count) != 0) {
5970 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5971 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
5972 			return (EIO);
5973 		}
5974 
5975 		return (0);
5976 
5977 	case MTGRSZ:
5978 		/*
5979 		 * Get record-size to the user
5980 		 */
5981 		mtop->mt_count = un->un_bsize;
5982 		rval = 0;
5983 		break;
5984 
5985 	case MTTELL:
5986 		rval = st_update_block_pos(un, st_cmd, 0);
5987 		mtop->mt_count = un->un_pos.lgclblkno;
5988 		break;
5989 
5990 	case MTSEEK:
5991 		rval = st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
5992 		    (uint64_t)mtop->mt_count, un->un_pos.partition);
5993 		/*
5994 		 * This bit of magic make mt print the actual position if
5995 		 * the resulting position was not what was asked for.
5996 		 */
5997 		if (rval == ESPIPE) {
5998 			rval = EIO;
5999 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
6000 				mtop->mt_op = MTTELL;
6001 				mtop->mt_count = un->un_pos.lgclblkno;
6002 			}
6003 		}
6004 		break;
6005 
6006 	case MTLOCK:
6007 		if (st_cmd(un, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
6008 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6009 			    "st_do_mtioctop : EIO : MTLOCK");
6010 			rval = EIO;
6011 		}
6012 		break;
6013 
6014 	case MTUNLOCK:
6015 		if (st_cmd(un, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
6016 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6017 			    "st_do_mtioctop : EIO : MTUNLOCK");
6018 			rval = EIO;
6019 		}
6020 		break;
6021 
6022 	default:
6023 		rval = ENOTTY;
6024 	}
6025 
6026 	return (rval);
6027 }
6028 
6029 
6030 /*
6031  * Run a command for uscsi ioctl.
6032  */
6033 static int
6034 st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
6035 {
6036 	struct uscsi_cmd	*uscmd;
6037 	struct buf	*bp;
6038 	enum uio_seg	uioseg;
6039 	int	offline_state = 0;
6040 	int	err = 0;
6041 	dev_t dev = un->un_dev;
6042 
6043 	ST_FUNC(ST_DEVINFO, st_uscsi_cmd);
6044 
6045 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6046 	    "st_uscsi_cmd(dev = 0x%lx)\n", un->un_dev);
6047 
6048 	ASSERT(mutex_owned(ST_MUTEX));
6049 
6050 	/*
6051 	 * We really don't know what commands are coming in here and
6052 	 * we don't want to limit the commands coming in.
6053 	 *
6054 	 * If st_tape_init() gets called from st_strategy(), then we
6055 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
6056 	 * which it never will, as we set it below.  To prevent
6057 	 * st_tape_init() from getting called, we have to set state to other
6058 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
6059 	 * achieves this purpose already.
6060 	 *
6061 	 * We use offline_state to preserve the OFFLINE state, if it exists,
6062 	 * so other entry points to the driver might have the chance to call
6063 	 * st_tape_init().
6064 	 */
6065 	if (un->un_state == ST_STATE_OFFLINE) {
6066 		un->un_laststate = ST_STATE_OFFLINE;
6067 		un->un_state = ST_STATE_INITIALIZING;
6068 		offline_state = 1;
6069 	}
6070 
6071 	mutex_exit(ST_MUTEX);
6072 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag, ROUTE, &uscmd);
6073 	mutex_enter(ST_MUTEX);
6074 	if (err != 0) {
6075 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6076 		    "st_uscsi_cmd: scsi_uscsi_alloc_and_copyin failed\n");
6077 		goto exit;
6078 	}
6079 
6080 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
6081 
6082 	/* check to see if this command requires the drive to be reserved */
6083 	if (uscmd->uscsi_cdb != NULL) {
6084 		err = st_check_cdb_for_need_to_reserve(un,
6085 		    (uchar_t *)uscmd->uscsi_cdb);
6086 		if (err) {
6087 			goto exit_free;
6088 		}
6089 		/*
6090 		 * If this is a space command we need to save the starting
6091 		 * point so we can retry from there if the command fails.
6092 		 */
6093 		if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6094 		    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) {
6095 			(void) st_update_block_pos(un, st_cmd, 0);
6096 		}
6097 	}
6098 
6099 	/*
6100 	 * Forground should not be doing anything while recovery is active.
6101 	 */
6102 	ASSERT(un->un_recov_buf_busy == 0);
6103 
6104 	/*
6105 	 * Get buffer resources...
6106 	 */
6107 	while (un->un_sbuf_busy)
6108 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6109 	un->un_sbuf_busy = 1;
6110 
6111 #ifdef STDEBUG
6112 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0x7) > 6) {
6113 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
6114 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6115 		    "uscsi cdb", uscmd->uscsi_cdb);
6116 		if (uscmd->uscsi_buflen) {
6117 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6118 			    "uscsi %s of %ld bytes %s %s space\n",
6119 			    (rw == B_READ) ? rd_str : wr_str,
6120 			    uscmd->uscsi_buflen,
6121 			    (rw == B_READ) ? "to" : "from",
6122 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
6123 		}
6124 	}
6125 #endif /* STDEBUG */
6126 
6127 	/*
6128 	 * Although st_uscsi_cmd() never makes use of these
6129 	 * now, we are just being safe and consistent.
6130 	 */
6131 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
6132 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
6133 
6134 	un->un_srqbufp = uscmd->uscsi_rqbuf;
6135 	bp = un->un_sbufp;
6136 	bzero(bp, sizeof (buf_t));
6137 	if (uscmd->uscsi_cdb != NULL) {
6138 		bp->b_forw = (struct buf *)(uintptr_t)uscmd->uscsi_cdb[0];
6139 	}
6140 	bp->b_back = (struct buf *)uscmd;
6141 
6142 	mutex_exit(ST_MUTEX);
6143 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, st_strategy, bp, NULL);
6144 	mutex_enter(ST_MUTEX);
6145 
6146 	/*
6147 	 * If scsi reset successful, don't write any filemarks.
6148 	 */
6149 	if ((err == 0) && (uscmd->uscsi_flags &
6150 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
6151 		un->un_fmneeded = 0;
6152 	}
6153 
6154 exit_free:
6155 	/*
6156 	 * Free resources
6157 	 */
6158 	un->un_sbuf_busy = 0;
6159 	un->un_srqbufp = NULL;
6160 
6161 	/*
6162 	 * If was a space command need to update logical block position.
6163 	 * If the command failed such that positioning is invalid, Don't
6164 	 * update the position as the user must do this to validate the
6165 	 * position for data protection.
6166 	 */
6167 	if ((uscmd->uscsi_cdb != NULL) &&
6168 	    ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6169 	    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) &&
6170 	    (un->un_pos.pmode != invalid)) {
6171 		un->un_running.pmode = invalid;
6172 		(void) st_update_block_pos(un, st_cmd, 1);
6173 		/*
6174 		 * Set running position to invalid so it updates on the
6175 		 * next command.
6176 		 */
6177 		un->un_running.pmode = invalid;
6178 	}
6179 	cv_signal(&un->un_sbuf_cv);
6180 	mutex_exit(ST_MUTEX);
6181 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
6182 	mutex_enter(ST_MUTEX);
6183 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6184 	    "st_uscsi_cmd returns 0x%x\n", err);
6185 
6186 exit:
6187 	/* don't lose offline state */
6188 	if (offline_state) {
6189 		un->un_state = ST_STATE_OFFLINE;
6190 	}
6191 
6192 	ASSERT(mutex_owned(ST_MUTEX));
6193 	return (err);
6194 }
6195 
6196 static int
6197 st_write_fm(dev_t dev, int wfm)
6198 {
6199 	int i;
6200 	int rval;
6201 
6202 	GET_SOFT_STATE(dev);
6203 
6204 	ST_FUNC(ST_DEVINFO, st_write_fm);
6205 
6206 	ASSERT(mutex_owned(ST_MUTEX));
6207 
6208 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6209 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6210 
6211 	/*
6212 	 * write one filemark at the time after EOT
6213 	 */
6214 	if (un->un_pos.eof >= ST_EOT) {
6215 		for (i = 0; i < wfm; i++) {
6216 			rval = st_cmd(un, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6217 			if (rval == EACCES) {
6218 				return (rval);
6219 			}
6220 			if (rval != 0) {
6221 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6222 				    "st_write_fm : EIO : write EOT file mark");
6223 				return (EIO);
6224 			}
6225 		}
6226 	} else {
6227 		rval = st_cmd(un, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6228 		if (rval == EACCES) {
6229 			return (rval);
6230 		}
6231 		if (rval) {
6232 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6233 			    "st_write_fm : EIO : write file mark");
6234 			return (EIO);
6235 		}
6236 	}
6237 
6238 	ASSERT(mutex_owned(ST_MUTEX));
6239 	return (0);
6240 }
6241 
6242 #ifdef STDEBUG
6243 static void
6244 st_start_dump(struct scsi_tape *un, struct buf *bp)
6245 {
6246 	struct scsi_pkt *pkt = BP_PKT(bp);
6247 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6248 
6249 	ST_FUNC(ST_DEVINFO, st_start_dump);
6250 
6251 	if ((st_debug & 0x7) < 6)
6252 		return;
6253 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6254 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6255 	    (void *)bp->b_forw, bp->b_bcount,
6256 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6257 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6258 	    "st_start: cdb",  (caddr_t)cdbp);
6259 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6260 	    "st_start: fileno=%d, blk=%d\n",
6261 	    un->un_pos.fileno, un->un_pos.blkno);
6262 }
6263 #endif
6264 
6265 
6266 /*
6267  * Command start && done functions
6268  */
6269 
6270 /*
6271  * st_start()
6272  *
6273  * Called from:
6274  *  st_strategy() to start a command.
6275  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6276  *  st_attach() when resuming from power down state.
6277  *  st_start_restart() to retry transport when device was previously busy.
6278  *  st_done_and_mutex_exit() to start the next command when previous is done.
6279  *
6280  * On entry:
6281  *  scsi_pkt may or may not be allocated.
6282  *
6283  */
6284 static void
6285 st_start(struct scsi_tape *un)
6286 {
6287 	struct buf *bp;
6288 	int status;
6289 	int queued;
6290 
6291 	ST_FUNC(ST_DEVINFO, st_start);
6292 	ASSERT(mutex_owned(ST_MUTEX));
6293 
6294 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6295 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6296 
6297 	if (un->un_recov_buf_busy) {
6298 		/* recovery commands can happen anytime */
6299 		bp = un->un_recov_buf;
6300 		queued = 0;
6301 	} else if (un->un_sbuf_busy) {
6302 		/* sbuf commands should only happen with an empty queue. */
6303 		ASSERT(un->un_quef == NULL);
6304 		ASSERT(un->un_runqf == NULL);
6305 		bp = un->un_sbufp;
6306 		queued = 0;
6307 	} else if (un->un_quef != NULL) {
6308 		if (un->un_persistence && un->un_persist_errors) {
6309 			return;
6310 		}
6311 		bp = un->un_quef;
6312 		queued = 1;
6313 	} else {
6314 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6315 		    "st_start() returning no buf found\n");
6316 		return;
6317 	}
6318 
6319 	ASSERT((bp->b_flags & B_DONE) == 0);
6320 
6321 	/*
6322 	 * Don't send more than un_throttle commands to the HBA
6323 	 */
6324 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6325 		/*
6326 		 * if doing recovery we know there is outstanding commands.
6327 		 */
6328 		if (bp != un->un_recov_buf) {
6329 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6330 			    "st_start returning throttle = %d or ncmds = %d\n",
6331 			    un->un_throttle, un->un_ncmds);
6332 			if (un->un_ncmds == 0) {
6333 				typedef void (*func)();
6334 				func fnc = (func)st_runout;
6335 
6336 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6337 				    "Sending delayed start to st_runout()\n");
6338 				mutex_exit(ST_MUTEX);
6339 				(void) timeout(fnc, un, drv_usectohz(1000000));
6340 			}
6341 			return;
6342 		}
6343 	}
6344 
6345 	/*
6346 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6347 	 * build the command.
6348 	 */
6349 	if (BP_PKT(bp) == NULL) {
6350 		ASSERT((bp->b_flags & B_DONE) == 0);
6351 		st_make_cmd(un, bp, st_runout);
6352 		ASSERT((bp->b_flags & B_DONE) == 0);
6353 		status = geterror(bp);
6354 
6355 		/*
6356 		 * Some HBA's don't call bioerror() to set an error.
6357 		 * And geterror() returns zero if B_ERROR is not set.
6358 		 * So if we get zero we must check b_error.
6359 		 */
6360 		if (status == 0 && bp->b_error != 0) {
6361 			status = bp->b_error;
6362 			bioerror(bp, status);
6363 		}
6364 
6365 		/*
6366 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6367 		 * In tape ENOMEM has special meaning so we'll change it.
6368 		 */
6369 		if (status == ENOMEM) {
6370 			status = 0;
6371 			bioerror(bp, status);
6372 		}
6373 
6374 		/*
6375 		 * Did it fail and is it retryable?
6376 		 * If so return and wait for the callback through st_runout.
6377 		 * Also looks like scsi_init_pkt() will setup a callback even
6378 		 * if it isn't retryable.
6379 		 */
6380 		if (BP_PKT(bp) == NULL) {
6381 			if (status == 0) {
6382 				/*
6383 				 * If first attempt save state.
6384 				 */
6385 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6386 					un->un_laststate = un->un_state;
6387 					un->un_state = ST_STATE_RESOURCE_WAIT;
6388 				}
6389 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6390 				    "temp no resources for pkt\n");
6391 			} else if (status == EINVAL) {
6392 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6393 				    "scsi_init_pkt rejected pkt as too big\n");
6394 				if (un->un_persistence) {
6395 					st_set_pe_flag(un);
6396 				}
6397 			} else {
6398 				/*
6399 				 * Unlikely that it would be retryable then not.
6400 				 */
6401 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6402 					un->un_state = un->un_laststate;
6403 				}
6404 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6405 				    "perm no resources for pkt errno = 0x%x\n",
6406 				    status);
6407 			}
6408 			return;
6409 		}
6410 		/*
6411 		 * Worked this time set the state back.
6412 		 */
6413 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6414 			un->un_state = un->un_laststate;
6415 		}
6416 	}
6417 
6418 	if (queued) {
6419 		/*
6420 		 * move from waitq to runq
6421 		 */
6422 		(void) st_remove_from_queue(&un->un_quef, &un->un_quel, bp);
6423 		st_add_to_queue(&un->un_runqf, &un->un_runql, un->un_runql, bp);
6424 	}
6425 
6426 
6427 #ifdef STDEBUG
6428 	st_start_dump(un, bp);
6429 #endif
6430 
6431 	/* could not get here if throttle was zero */
6432 	un->un_last_throttle = un->un_throttle;
6433 	un->un_throttle = 0;	/* so nothing else will come in here */
6434 	un->un_ncmds++;
6435 
6436 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6437 
6438 	status = st_transport(un, BP_PKT(bp));
6439 
6440 	if (un->un_last_throttle) {
6441 		un->un_throttle = un->un_last_throttle;
6442 	}
6443 
6444 	if (status != TRAN_ACCEPT) {
6445 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6446 		mutex_exit(ST_MUTEX);
6447 
6448 		if (status == TRAN_BUSY) {
6449 			/* if too many retries, fail the transport */
6450 			if (st_handle_start_busy(un, bp,
6451 			    ST_TRAN_BUSY_TIMEOUT, queued) == 0)
6452 				goto done;
6453 		}
6454 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6455 		    "transport rejected %d\n", status);
6456 		bp->b_resid = bp->b_bcount;
6457 
6458 
6459 #ifndef __lock_lint
6460 		/*
6461 		 * warlock doesn't understand this potential
6462 		 * recursion?
6463 		 */
6464 		mutex_enter(ST_MUTEX);
6465 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6466 		ST_DO_ERRSTATS(un, st_transerrs);
6467 		st_bioerror(bp, EIO);
6468 		st_set_pe_flag(un);
6469 		st_done_and_mutex_exit(un, bp);
6470 #endif
6471 	} else {
6472 		un->un_tran_retry_ct = 0;
6473 		mutex_exit(ST_MUTEX);
6474 	}
6475 
6476 done:
6477 
6478 	mutex_enter(ST_MUTEX);
6479 }
6480 
6481 /*
6482  * if the transport is busy, then put this bp back on the waitq
6483  */
6484 static int
6485 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6486     clock_t timeout_interval, int queued)
6487 {
6488 
6489 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6490 
6491 	mutex_enter(ST_MUTEX);
6492 
6493 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6494 	    "st_handle_start_busy()\n");
6495 
6496 	/*
6497 	 * Check to see if we hit the retry timeout and one last check for
6498 	 * making sure this is the last on the runq, if it is not, we have
6499 	 * to fail
6500 	 */
6501 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
6502 	    ((queued) && (un->un_runql != bp))) {
6503 		mutex_exit(ST_MUTEX);
6504 		return (-1);
6505 	}
6506 
6507 	if (queued) {
6508 		/* put the bp back on the waitq */
6509 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
6510 	}
6511 
6512 	/*
6513 	 * Decrement un_ncmds so that this
6514 	 * gets thru' st_start() again.
6515 	 */
6516 	un->un_ncmds--;
6517 
6518 	if (queued) {
6519 		/*
6520 		 * since this is an error case, we won't have to do this list
6521 		 * walking much. We've already made sure this bp was the
6522 		 * last on the runq
6523 		 */
6524 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6525 
6526 		/*
6527 		 * send a marker pkt, if appropriate
6528 		 */
6529 		st_hba_unflush(un);
6530 
6531 	}
6532 	/*
6533 	 * all queues are aligned, we are just waiting to
6534 	 * transport, don't alloc any more buf p's, when
6535 	 * st_start is reentered.
6536 	 */
6537 	(void) timeout(st_start_restart, un, timeout_interval);
6538 
6539 	mutex_exit(ST_MUTEX);
6540 	return (0);
6541 }
6542 
6543 
6544 /*
6545  * st_runout a callback that is called what a resource allocatation failed
6546  */
6547 static int
6548 st_runout(caddr_t arg)
6549 {
6550 	struct scsi_tape *un = (struct scsi_tape *)arg;
6551 	struct buf *bp;
6552 	int queued;
6553 
6554 	ASSERT(un != NULL);
6555 
6556 	ST_FUNC(ST_DEVINFO, st_runout);
6557 
6558 	mutex_enter(ST_MUTEX);
6559 
6560 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6561 
6562 	if (un->un_recov_buf_busy != 0) {
6563 		bp = un->un_recov_buf;
6564 		queued = 0;
6565 	} else if (un->un_sbuf_busy != 0) {
6566 		/* sbuf commands should only happen with an empty queue. */
6567 		ASSERT(un->un_quef == NULL);
6568 		ASSERT(un->un_runqf == NULL);
6569 		bp = un->un_sbufp;
6570 		queued = 0;
6571 	} else if (un->un_quef != NULL) {
6572 		bp = un->un_quef;
6573 		if (un->un_persistence && un->un_persist_errors) {
6574 			mutex_exit(ST_MUTEX);
6575 			bp->b_resid = bp->b_bcount;
6576 			biodone(bp);
6577 			return (1);
6578 		}
6579 		queued = 1;
6580 	} else {
6581 		ASSERT(1 == 0);
6582 		mutex_exit(ST_MUTEX);
6583 		return (1);
6584 	}
6585 
6586 	/*
6587 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6588 	 */
6589 	if ((bp != NULL) && (geterror(bp) != 0)) {
6590 
6591 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6592 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6593 		    bp->b_flags, geterror(bp));
6594 		ASSERT((bp->b_flags & B_DONE) == 0);
6595 
6596 		if (queued) {
6597 			(void) st_remove_from_queue(&un->un_quef, &un->un_quel,
6598 			    bp);
6599 		}
6600 		mutex_exit(ST_MUTEX);
6601 
6602 		ASSERT((bp->b_flags & B_DONE) == 0);
6603 
6604 		/*
6605 		 * Set resid, Error already set, then unblock calling thread.
6606 		 */
6607 		bp->b_resid = bp->b_bcount;
6608 		biodone(bp);
6609 	} else {
6610 		/*
6611 		 * Try Again
6612 		 */
6613 		st_start(un);
6614 		mutex_exit(ST_MUTEX);
6615 	}
6616 
6617 	/*
6618 	 * Comments courtesy of sd.c
6619 	 * The scsi_init_pkt routine allows for the callback function to
6620 	 * return a 0 indicating the callback should be rescheduled or a 1
6621 	 * indicating not to reschedule. This routine always returns 1
6622 	 * because the driver always provides a callback function to
6623 	 * scsi_init_pkt. This results in a callback always being scheduled
6624 	 * (via the scsi_init_pkt callback implementation) if a resource
6625 	 * failure occurs.
6626 	 */
6627 
6628 	return (1);
6629 }
6630 
6631 /*
6632  * st_done_and_mutex_exit()
6633  *	- remove bp from runq
6634  *	- start up the next request
6635  *	- if this was an asynch bp, clean up
6636  *	- exit with released mutex
6637  */
6638 static void
6639 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6640 {
6641 	int	pe_flagged = 0;
6642 
6643 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6644 #if !defined(lint)
6645 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6646 #endif
6647 
6648 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6649 
6650 	ASSERT(mutex_owned(ST_MUTEX));
6651 
6652 	(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6653 
6654 	un->un_ncmds--;
6655 	cv_signal(&un->un_queue_cv);
6656 
6657 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6658 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6659 	    "0x%x\n", (uchar_t)*((caddr_t)(BP_PKT(bp))->pkt_cdbp), bp->b_bcount,
6660 	    bp->b_resid, bp->b_flags);
6661 
6662 
6663 	/*
6664 	 * update kstats with transfer count info
6665 	 */
6666 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6667 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6668 		if (bp->b_flags & B_READ) {
6669 			IOSP->reads++;
6670 			IOSP->nread += n_done;
6671 		} else {
6672 			IOSP->writes++;
6673 			IOSP->nwritten += n_done;
6674 		}
6675 	}
6676 
6677 	/*
6678 	 * Start the next one before releasing resources on this one, if
6679 	 * there is something on the queue and persistent errors has not been
6680 	 * flagged
6681 	 */
6682 
6683 	if ((pe_flagged = (un->un_persistence && un->un_persist_errors)) != 0) {
6684 		un->un_last_resid = bp->b_resid;
6685 		un->un_last_count = bp->b_bcount;
6686 	}
6687 
6688 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6689 		cv_broadcast(&un->un_tape_busy_cv);
6690 	} else if (un->un_quef && un->un_throttle && !pe_flagged &&
6691 	    (bp != un->un_recov_buf)) {
6692 		st_start(un);
6693 	}
6694 
6695 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6696 		/*
6697 		 * Since we marked this ourselves as ASYNC,
6698 		 * there isn't anybody around waiting for
6699 		 * completion any more.
6700 		 */
6701 		uchar_t *cdb = (uchar_t *)bp->b_forw;
6702 		if (*cdb == SCMD_READ || *cdb == SCMD_WRITE) {
6703 			bp->b_un.b_addr = (caddr_t)0;
6704 		}
6705 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6706 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6707 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
6708 		    "CDB sent with B_ASYNC",  (caddr_t)cdb);
6709 		if (BP_PKT(bp)) {
6710 			scsi_destroy_pkt(BP_PKT(bp));
6711 		}
6712 		un->un_sbuf_busy = 0;
6713 		cv_signal(&un->un_sbuf_cv);
6714 		mutex_exit(ST_MUTEX);
6715 		return;
6716 	}
6717 
6718 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6719 		/*
6720 		 * Copy status from scsi_pkt to uscsi_cmd
6721 		 * since st_uscsi_cmd needs it
6722 		 */
6723 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6724 	}
6725 
6726 
6727 #ifdef STDEBUG
6728 	if (((st_debug & 0x7) >= 4) &&
6729 	    (((un->un_pos.blkno % 100) == 0) ||
6730 	    (un->un_persistence && un->un_persist_errors))) {
6731 
6732 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6733 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6734 		    "un_errno = %d, un_pe = %d\n",
6735 		    un->un_ncmds, un->un_throttle, un->un_errno,
6736 		    un->un_persist_errors);
6737 	}
6738 
6739 #endif
6740 
6741 	mutex_exit(ST_MUTEX);
6742 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6743 	    "st_done_and_mutex_exit: freeing pkt\n");
6744 
6745 	if (BP_PKT(bp)) {
6746 		scsi_destroy_pkt(BP_PKT(bp));
6747 	}
6748 
6749 	biodone(bp);
6750 
6751 	/*
6752 	 * now that we biodoned that command, if persistent errors have been
6753 	 * flagged, flush the waitq
6754 	 */
6755 	if (pe_flagged)
6756 		st_flush(un);
6757 }
6758 
6759 
6760 /*
6761  * Tape error, flush tape driver queue.
6762  */
6763 static void
6764 st_flush(struct scsi_tape *un)
6765 {
6766 	struct buf *bp;
6767 
6768 	ST_FUNC(ST_DEVINFO, st_flush);
6769 
6770 	mutex_enter(ST_MUTEX);
6771 
6772 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6773 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6774 	    un->un_ncmds, (void *)un->un_quef);
6775 
6776 	/*
6777 	 * if we still have commands outstanding, wait for them to come in
6778 	 * before flushing the queue, and make sure there is a queue
6779 	 */
6780 	if (un->un_ncmds || !un->un_quef)
6781 		goto exit;
6782 
6783 	/*
6784 	 * we have no more commands outstanding, so let's deal with special
6785 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6786 	 * is 0, then we know there was no error and we return a 0 read or
6787 	 * write before showing errors
6788 	 */
6789 
6790 	/* Flush the wait queue. */
6791 	while ((bp = un->un_quef) != NULL) {
6792 		un->un_quef = bp->b_actf;
6793 
6794 		bp->b_resid = bp->b_bcount;
6795 
6796 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6797 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6798 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6799 
6800 		st_set_pe_errno(un);
6801 
6802 		bioerror(bp, un->un_errno);
6803 
6804 		mutex_exit(ST_MUTEX);
6805 		/* it should have one, but check anyway */
6806 		if (BP_PKT(bp)) {
6807 			scsi_destroy_pkt(BP_PKT(bp));
6808 		}
6809 		biodone(bp);
6810 		mutex_enter(ST_MUTEX);
6811 	}
6812 
6813 	/*
6814 	 * It's not a bad practice to reset the
6815 	 * waitq tail pointer to NULL.
6816 	 */
6817 	un->un_quel = NULL;
6818 
6819 exit:
6820 	/* we mucked with the queue, so let others know about it */
6821 	cv_signal(&un->un_queue_cv);
6822 	mutex_exit(ST_MUTEX);
6823 }
6824 
6825 
6826 /*
6827  * Utility functions
6828  */
6829 static int
6830 st_determine_generic(struct scsi_tape *un)
6831 {
6832 	int bsize;
6833 	static char *cart = "0.25 inch cartridge";
6834 	char *sizestr;
6835 
6836 	ST_FUNC(ST_DEVINFO, st_determine_generic);
6837 
6838 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6839 	    "st_determine_generic(un = 0x%p)\n", (void*)un);
6840 
6841 	ASSERT(mutex_owned(ST_MUTEX));
6842 
6843 	if (st_modesense(un)) {
6844 		return (-1);
6845 	}
6846 
6847 	bsize = (un->un_mspl->high_bl << 16)	|
6848 	    (un->un_mspl->mid_bl << 8)	|
6849 	    (un->un_mspl->low_bl);
6850 
6851 	if (bsize == 0) {
6852 		un->un_dp->options |= ST_VARIABLE;
6853 		un->un_dp->bsize = 0;
6854 		un->un_bsize = 0;
6855 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
6856 		/*
6857 		 * record size of this device too big.
6858 		 * try and convert it to variable record length.
6859 		 *
6860 		 */
6861 		un->un_dp->options |= ST_VARIABLE;
6862 		if (st_change_block_size(un, 0) != 0) {
6863 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6864 			    "Fixed Record Size %d is too large\n", bsize);
6865 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6866 			    "Cannot switch to variable record size\n");
6867 			un->un_dp->options &= ~ST_VARIABLE;
6868 			return (-1);
6869 		}
6870 	} else if (st_change_block_size(un, 0) == 0) {
6871 		/*
6872 		 * If the drive was set to a non zero block size,
6873 		 * See if it can be set to a zero block size.
6874 		 * If it works, ST_VARIABLE so user can set it as they want.
6875 		 */
6876 		un->un_dp->options |= ST_VARIABLE;
6877 		un->un_dp->bsize = 0;
6878 		un->un_bsize = 0;
6879 	} else {
6880 		un->un_dp->bsize = bsize;
6881 		un->un_bsize = bsize;
6882 	}
6883 
6884 
6885 	switch (un->un_mspl->density) {
6886 	default:
6887 	case 0x0:
6888 		/*
6889 		 * default density, cannot determine any other
6890 		 * information.
6891 		 */
6892 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
6893 		un->un_dp->type = ST_TYPE_DEFAULT;
6894 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
6895 		break;
6896 	case 0x1:
6897 	case 0x2:
6898 	case 0x3:
6899 	case 0x6:
6900 		/*
6901 		 * 1/2" reel
6902 		 */
6903 		sizestr = "0.50 inch reel";
6904 		un->un_dp->type = ST_TYPE_REEL;
6905 		un->un_dp->options |= ST_REEL;
6906 		un->un_dp->densities[0] = 0x1;
6907 		un->un_dp->densities[1] = 0x2;
6908 		un->un_dp->densities[2] = 0x6;
6909 		un->un_dp->densities[3] = 0x3;
6910 		break;
6911 	case 0x4:
6912 	case 0x5:
6913 	case 0x7:
6914 	case 0x0b:
6915 
6916 		/*
6917 		 * Quarter inch.
6918 		 */
6919 		sizestr = cart;
6920 		un->un_dp->type = ST_TYPE_DEFAULT;
6921 		un->un_dp->options |= ST_QIC;
6922 
6923 		un->un_dp->densities[1] = 0x4;
6924 		un->un_dp->densities[2] = 0x5;
6925 		un->un_dp->densities[3] = 0x7;
6926 		un->un_dp->densities[0] = 0x0b;
6927 		break;
6928 
6929 	case 0x0f:
6930 	case 0x10:
6931 	case 0x11:
6932 	case 0x12:
6933 		/*
6934 		 * QIC-120, QIC-150, QIC-320, QIC-600
6935 		 */
6936 		sizestr = cart;
6937 		un->un_dp->type = ST_TYPE_DEFAULT;
6938 		un->un_dp->options |= ST_QIC;
6939 		un->un_dp->densities[0] = 0x0f;
6940 		un->un_dp->densities[1] = 0x10;
6941 		un->un_dp->densities[2] = 0x11;
6942 		un->un_dp->densities[3] = 0x12;
6943 		break;
6944 
6945 	case 0x09:
6946 	case 0x0a:
6947 	case 0x0c:
6948 	case 0x0d:
6949 		/*
6950 		 * 1/2" cartridge tapes. Include HI-TC.
6951 		 */
6952 		sizestr = cart;
6953 		sizestr[2] = '5';
6954 		sizestr[3] = '0';
6955 		un->un_dp->type = ST_TYPE_HIC;
6956 		un->un_dp->densities[0] = 0x09;
6957 		un->un_dp->densities[1] = 0x0a;
6958 		un->un_dp->densities[2] = 0x0c;
6959 		un->un_dp->densities[3] = 0x0d;
6960 		break;
6961 
6962 	case 0x13:
6963 			/* DDS-2/DDS-3 scsi spec densities */
6964 	case 0x24:
6965 	case 0x25:
6966 	case 0x26:
6967 		sizestr = "DAT Data Storage (DDS)";
6968 		un->un_dp->type = ST_TYPE_DAT;
6969 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6970 		break;
6971 
6972 	case 0x14:
6973 		/*
6974 		 * Helical Scan (Exabyte) devices
6975 		 */
6976 		sizestr = "8mm helical scan cartridge";
6977 		un->un_dp->type = ST_TYPE_EXABYTE;
6978 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6979 		break;
6980 	}
6981 
6982 	/*
6983 	 * Assume LONG ERASE, BSF and BSR
6984 	 */
6985 
6986 	un->un_dp->options |=
6987 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
6988 
6989 	/*
6990 	 * Only if mode sense data says no buffered write, set NOBUF
6991 	 */
6992 	if (un->un_mspl->bufm == 0)
6993 		un->un_dp->options |= ST_NOBUF;
6994 
6995 	/*
6996 	 * set up large read and write retry counts
6997 	 */
6998 
6999 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
7000 
7001 	/*
7002 	 * If this is a 0.50 inch reel tape, and
7003 	 * it is *not* variable mode, try and
7004 	 * set it to variable record length
7005 	 * mode.
7006 	 */
7007 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
7008 	    (un->un_dp->options & ST_VARIABLE)) {
7009 		if (st_change_block_size(un, 0) == 0) {
7010 			un->un_dp->bsize = 0;
7011 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
7012 			    un->un_mspl->low_bl = 0;
7013 		}
7014 	}
7015 
7016 	/*
7017 	 * Write to console about type of device found
7018 	 */
7019 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
7020 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
7021 	    sizestr);
7022 	if (un->un_dp->options & ST_VARIABLE) {
7023 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7024 		    "!Variable record length I/O\n");
7025 	} else {
7026 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7027 		    "!Fixed record length (%d byte blocks) I/O\n",
7028 		    un->un_dp->bsize);
7029 	}
7030 	ASSERT(mutex_owned(ST_MUTEX));
7031 	return (0);
7032 }
7033 
7034 static int
7035 st_determine_density(struct scsi_tape *un, int rw)
7036 {
7037 	int rval = 0;
7038 
7039 	ST_FUNC(ST_DEVINFO, st_determine_density);
7040 
7041 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7042 	    "st_determine_density(un = 0x%p, rw = %s)\n",
7043 	    (void*)un, (rw == B_WRITE ? wr_str: rd_str));
7044 
7045 	ASSERT(mutex_owned(ST_MUTEX));
7046 
7047 	/*
7048 	 * If we're past BOT, density is determined already.
7049 	 */
7050 	if (un->un_pos.pmode == logical) {
7051 		if (un->un_pos.lgclblkno != 0) {
7052 			goto exit;
7053 		}
7054 	} else if (un->un_pos.pmode == legacy) {
7055 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
7056 			/*
7057 			 * XXX: put in a bitch message about attempting to
7058 			 * XXX: change density past BOT.
7059 			 */
7060 			goto exit;
7061 		}
7062 	} else {
7063 		goto exit;
7064 	}
7065 	if ((un->un_pos.pmode == logical) &&
7066 	    (un->un_pos.lgclblkno != 0)) {
7067 		goto exit;
7068 	}
7069 
7070 
7071 	/*
7072 	 * If we're going to be writing, we set the density
7073 	 */
7074 	if (rw == 0 || rw == B_WRITE) {
7075 		/* un_curdens is used as an index into densities table */
7076 		un->un_curdens = MT_DENSITY(un->un_dev);
7077 		if (st_set_density(un)) {
7078 			rval = -1;
7079 		}
7080 		goto exit;
7081 	}
7082 
7083 	/*
7084 	 * If density is known already,
7085 	 * we don't have to get it again.(?)
7086 	 */
7087 	if (!un->un_density_known) {
7088 		if (st_get_density(un)) {
7089 			rval = -1;
7090 		}
7091 	}
7092 
7093 exit:
7094 	ASSERT(mutex_owned(ST_MUTEX));
7095 	return (rval);
7096 }
7097 
7098 
7099 /*
7100  * Try to determine density. We do this by attempting to read the
7101  * first record off the tape, cycling through the available density
7102  * codes as we go.
7103  */
7104 
7105 static int
7106 st_get_density(struct scsi_tape *un)
7107 {
7108 	int succes = 0, rval = -1, i;
7109 	uint_t size;
7110 	uchar_t dens, olddens;
7111 
7112 	ST_FUNC(ST_DEVINFO, st_get_density);
7113 
7114 	ST_FUNC(ST_DEVINFO, st_get_density);
7115 
7116 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7117 	    "st_get_density(un = 0x%p)\n", (void*)un);
7118 
7119 	ASSERT(mutex_owned(ST_MUTEX));
7120 
7121 	/*
7122 	 * If Auto Density override is enabled The drive has
7123 	 * only one density and there is no point in attempting
7124 	 * find the correct one.
7125 	 *
7126 	 * Since most modern drives auto detect the density
7127 	 * and format of the recorded media before they come
7128 	 * ready. What this function does is a legacy behavior
7129 	 * and modern drives not only don't need it, The backup
7130 	 * utilities that do positioning via uscsi find the un-
7131 	 * expected rewinds problematic.
7132 	 *
7133 	 * The drives that need this are old reel to reel devices.
7134 	 * I took a swag and said they must be scsi-1 or older.
7135 	 * I don't beleave there will any of the newer devices
7136 	 * that need this. There will be some scsi-1 devices that
7137 	 * don't need this but I don't think they will be using the
7138 	 * BIG aftermarket backup and restore utilitys.
7139 	 */
7140 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
7141 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
7142 		un->un_density_known = 1;
7143 		rval = 0;
7144 		goto exit;
7145 	}
7146 
7147 	/*
7148 	 * This will only work on variable record length tapes
7149 	 * if and only if all variable record length tapes autodensity
7150 	 * select.
7151 	 */
7152 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
7153 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
7154 
7155 	/*
7156 	 * Start at the specified density
7157 	 */
7158 
7159 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
7160 
7161 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
7162 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
7163 		/*
7164 		 * If we've done this density before,
7165 		 * don't bother to do it again.
7166 		 */
7167 		dens = un->un_dp->densities[un->un_curdens];
7168 		if (i > 0 && dens == olddens)
7169 			continue;
7170 		olddens = dens;
7171 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7172 		    "trying density 0x%x\n", dens);
7173 		if (st_set_density(un)) {
7174 			continue;
7175 		}
7176 
7177 		/*
7178 		 * XXX - the creates lots of headaches and slowdowns - must
7179 		 * fix.
7180 		 */
7181 		succes = (st_cmd(un, SCMD_READ, (int)size, SYNC_CMD) == 0);
7182 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
7183 			break;
7184 		}
7185 		if (succes) {
7186 			st_init(un);
7187 			rval = 0;
7188 			un->un_density_known = 1;
7189 			break;
7190 		}
7191 	}
7192 	kmem_free(un->un_tmpbuf, size);
7193 	un->un_tmpbuf = 0;
7194 
7195 exit:
7196 	ASSERT(mutex_owned(ST_MUTEX));
7197 	return (rval);
7198 }
7199 
7200 static int
7201 st_set_density(struct scsi_tape *un)
7202 {
7203 	int rval = 0;
7204 
7205 	ST_FUNC(ST_DEVINFO, st_set_density);
7206 
7207 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7208 	    "st_set_density(un = 0x%p): density = 0x%x\n", (void*)un,
7209 	    un->un_dp->densities[un->un_curdens]);
7210 
7211 	ASSERT(mutex_owned(ST_MUTEX));
7212 
7213 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7214 
7215 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
7216 		/*
7217 		 * If auto density override is not set, Use mode select
7218 		 * to set density and compression.
7219 		 */
7220 		if (st_modeselect(un)) {
7221 			rval = -1;
7222 		}
7223 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
7224 		/*
7225 		 * If auto density and mode select compression are set,
7226 		 * This is a drive with one density code but compression
7227 		 * can be enabled or disabled.
7228 		 * Set compression but no need to set density.
7229 		 */
7230 		rval = st_set_compression(un);
7231 		if ((rval != 0) && (rval != EALREADY)) {
7232 			rval = -1;
7233 		} else {
7234 			rval = 0;
7235 		}
7236 	}
7237 
7238 	/* If sucessful set density and/or compression, mark density known */
7239 	if (rval == 0) {
7240 		un->un_density_known = 1;
7241 	}
7242 
7243 	ASSERT(mutex_owned(ST_MUTEX));
7244 	return (rval);
7245 }
7246 
7247 static int
7248 st_loadtape(struct scsi_tape *un)
7249 {
7250 	int rval;
7251 
7252 	ST_FUNC(ST_DEVINFO, st_loadtape);
7253 
7254 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7255 	    "st_loadtape(un = 0x%p)\n", (void*) un);
7256 
7257 	ASSERT(mutex_owned(ST_MUTEX));
7258 
7259 	rval = st_update_block_pos(un, st_cmd, 0);
7260 	if (rval == EACCES) {
7261 		return (rval);
7262 	}
7263 
7264 	/*
7265 	 * 'LOAD' the tape to BOT by rewinding
7266 	 */
7267 	rval = st_cmd(un, SCMD_REWIND, 1, SYNC_CMD);
7268 	if (rval == 0) {
7269 		st_init(un);
7270 		un->un_density_known = 0;
7271 	}
7272 
7273 	ASSERT(mutex_owned(ST_MUTEX));
7274 	return (rval);
7275 }
7276 
7277 
7278 /*
7279  * Note: QIC devices aren't so smart.  If you try to append
7280  * after EOM, the write can fail because the device doesn't know
7281  * it's at EOM.	 In that case, issue a read.  The read should fail
7282  * because there's no data, but the device knows it's at EOM,
7283  * so a subsequent write should succeed.  To further confuse matters,
7284  * the target returns the same error if the tape is positioned
7285  * such that a write would overwrite existing data.  That's why
7286  * we have to do the append test.  A read in the middle of
7287  * recorded data would succeed, thus indicating we're attempting
7288  * something illegal.
7289  */
7290 
7291 
7292 static void
7293 st_test_append(struct buf *bp)
7294 {
7295 	dev_t dev = bp->b_edev;
7296 	struct scsi_tape *un;
7297 	uchar_t status;
7298 	unsigned bcount;
7299 
7300 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7301 
7302 	ST_FUNC(ST_DEVINFO, st_test_append);
7303 
7304 	ASSERT(mutex_owned(ST_MUTEX));
7305 
7306 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7307 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7308 
7309 	un->un_laststate = un->un_state;
7310 	un->un_state = ST_STATE_APPEND_TESTING;
7311 	un->un_test_append = 0;
7312 
7313 	/*
7314 	 * first, map in the buffer, because we're doing a double write --
7315 	 * first into the kernel, then onto the tape.
7316 	 */
7317 	bp_mapin(bp);
7318 
7319 	/*
7320 	 * get a copy of the data....
7321 	 */
7322 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7323 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7324 
7325 	/*
7326 	 * attempt the write..
7327 	 */
7328 
7329 	if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7330 success:
7331 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7332 		    "append write succeeded\n");
7333 		bp->b_resid = un->un_sbufp->b_resid;
7334 		mutex_exit(ST_MUTEX);
7335 		bcount = (unsigned)bp->b_bcount;
7336 		biodone(bp);
7337 		mutex_enter(ST_MUTEX);
7338 		un->un_laststate = un->un_state;
7339 		un->un_state = ST_STATE_OPEN;
7340 		kmem_free(un->un_tmpbuf, bcount);
7341 		un->un_tmpbuf = NULL;
7342 		return;
7343 	}
7344 
7345 	/*
7346 	 * The append failed. Do a short read. If that fails,  we are at EOM
7347 	 * so we can retry the write command. If that succeeds, than we're
7348 	 * all screwed up (the controller reported a real error).
7349 	 *
7350 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7351 	 * XXX: block size?
7352 	 *
7353 	 */
7354 	status = un->un_status;
7355 	un->un_status = 0;
7356 	(void) st_cmd(un, SCMD_READ, SECSIZE, SYNC_CMD);
7357 	if (un->un_status == KEY_BLANK_CHECK) {
7358 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7359 		    "append at EOM\n");
7360 		/*
7361 		 * Okay- the read failed. We should actually have confused
7362 		 * the controller enough to allow writing. In any case, the
7363 		 * i/o is on its own from here on out.
7364 		 */
7365 		un->un_laststate = un->un_state;
7366 		un->un_state = ST_STATE_OPEN;
7367 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7368 		if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount,
7369 		    SYNC_CMD) == 0) {
7370 			goto success;
7371 		}
7372 	}
7373 
7374 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7375 	    "append write failed- not at EOM\n");
7376 	bp->b_resid = bp->b_bcount;
7377 	st_bioerror(bp, EIO);
7378 
7379 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7380 	    "st_test_append : EIO : append write failed - not at EOM");
7381 
7382 	/*
7383 	 * backspace one record to get back to where we were
7384 	 */
7385 	if (st_cmd(un, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7386 		un->un_pos.pmode = invalid;
7387 	}
7388 
7389 	un->un_err_resid = bp->b_resid;
7390 	un->un_status = status;
7391 
7392 	/*
7393 	 * Note: biodone will do a bp_mapout()
7394 	 */
7395 	mutex_exit(ST_MUTEX);
7396 	bcount = (unsigned)bp->b_bcount;
7397 	biodone(bp);
7398 	mutex_enter(ST_MUTEX);
7399 	un->un_laststate = un->un_state;
7400 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7401 	kmem_free(un->un_tmpbuf, bcount);
7402 	un->un_tmpbuf = NULL;
7403 }
7404 
7405 /*
7406  * Special command handler
7407  */
7408 
7409 /*
7410  * common st_cmd code. The fourth parameter states
7411  * whether the caller wishes to await the results
7412  * Note the release of the mutex during most of the function
7413  */
7414 static int
7415 st_cmd(struct scsi_tape *un, int com, int64_t count, int wait)
7416 {
7417 	struct buf *bp;
7418 	int err;
7419 
7420 	ST_FUNC(ST_DEVINFO, st_cmd);
7421 
7422 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7423 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %"PRIx64", wait = %d)\n",
7424 	    un->un_dev, com, count, wait);
7425 
7426 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7427 	ASSERT(mutex_owned(ST_MUTEX));
7428 
7429 #ifdef STDEBUG
7430 	if ((st_debug & 0x7)) {
7431 		st_debug_cmds(un, com, count, wait);
7432 	}
7433 #endif
7434 
7435 	st_wait_for_io(un);
7436 
7437 	/* check to see if this command requires the drive to be reserved */
7438 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7439 
7440 	if (err) {
7441 		return (err);
7442 	}
7443 
7444 	/*
7445 	 * A space command is not recoverable if we don't know were we
7446 	 * were when it was issued.
7447 	 */
7448 	if ((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) {
7449 		(void) st_update_block_pos(un, st_cmd, 0);
7450 	}
7451 
7452 	/*
7453 	 * Forground should not be doing anything while recovery is active.
7454 	 */
7455 	ASSERT(un->un_recov_buf_busy == 0);
7456 
7457 	while (un->un_sbuf_busy)
7458 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7459 	un->un_sbuf_busy = 1;
7460 
7461 	bp = un->un_sbufp;
7462 	bzero(bp, sizeof (buf_t));
7463 
7464 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7465 
7466 	err = st_setup_cmd(un, bp, com, count);
7467 
7468 	un->un_sbuf_busy = 0;
7469 
7470 	/*
7471 	 * If was a space command need to update logical block position.
7472 	 * Only do this if the command was sucessful or it will mask the fact
7473 	 * that the space command failed by promoting the pmode to logical.
7474 	 */
7475 	if (((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) &&
7476 	    (un->un_pos.pmode != invalid)) {
7477 		un->un_running.pmode = invalid;
7478 		(void) st_update_block_pos(un, st_cmd, 1);
7479 		/*
7480 		 * Set running position to invalid so it updates on the
7481 		 * next command.
7482 		 */
7483 		un->un_running.pmode = invalid;
7484 	}
7485 
7486 	cv_signal(&un->un_sbuf_cv);
7487 
7488 	return (err);
7489 }
7490 
7491 static int
7492 st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com, int64_t count)
7493 {
7494 	int err;
7495 	dev_t dev = un->un_dev;
7496 
7497 	ST_FUNC(ST_DEVINFO, st_setup_cmd);
7498 	/*
7499 	 * Set count to the actual size of the data tranfer.
7500 	 * For commands with no data transfer, set bp->b_bcount
7501 	 * to the value to be used when constructing the
7502 	 * cdb in st_make_cmd().
7503 	 */
7504 	switch (com) {
7505 	case SCMD_READ:
7506 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7507 		    "special read %"PRId64"\n", count);
7508 		bp->b_flags |= B_READ;
7509 		bp->b_un.b_addr = un->un_tmpbuf;
7510 		break;
7511 
7512 	case SCMD_WRITE:
7513 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7514 		    "special write %"PRId64"\n", count);
7515 		bp->b_un.b_addr = un->un_tmpbuf;
7516 		break;
7517 
7518 	case SCMD_WRITE_FILE_MARK:
7519 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7520 		    "write %"PRId64" file marks\n", count);
7521 		bp->b_bcount = count;
7522 		count = 0;
7523 		break;
7524 
7525 	case SCMD_REWIND:
7526 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7527 		bp->b_bcount = count;
7528 		count = 0;
7529 		break;
7530 
7531 	case SCMD_SPACE:
7532 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7533 		/*
7534 		 * If the user could have entered a number that will
7535 		 * not fit in the 12 bit count field of space(8),
7536 		 * use space(16).
7537 		 */
7538 		if (((int64_t)SPACE_CNT(count) > 0x7fffff) ||
7539 		    ((int64_t)SPACE_CNT(count) < -(0x7fffff))) {
7540 			com = SCMD_SPACE_G4;
7541 		}
7542 		bp->b_bcount = count;
7543 		count = 0;
7544 		break;
7545 
7546 	case SCMD_RESERVE:
7547 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7548 		bp->b_bcount = 0;
7549 		count = 0;
7550 		break;
7551 
7552 	case SCMD_RELEASE:
7553 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7554 		bp->b_bcount = 0;
7555 		count = 0;
7556 		break;
7557 
7558 	case SCMD_LOAD:
7559 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7560 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7561 		bp->b_bcount = count;
7562 		count = 0;
7563 		break;
7564 
7565 	case SCMD_ERASE:
7566 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7567 		    "erase tape\n");
7568 		bp->b_bcount = count;
7569 		count = 0;
7570 		break;
7571 
7572 	case SCMD_MODE_SENSE:
7573 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7574 		    "mode sense\n");
7575 		bp->b_flags |= B_READ;
7576 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7577 		break;
7578 
7579 	case SCMD_MODE_SELECT:
7580 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7581 		    "mode select\n");
7582 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7583 		break;
7584 
7585 	case SCMD_READ_BLKLIM:
7586 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7587 		    "read block limits\n");
7588 		bp->b_bcount = count;
7589 		bp->b_flags |= B_READ;
7590 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7591 		break;
7592 
7593 	case SCMD_TEST_UNIT_READY:
7594 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7595 		    "test unit ready\n");
7596 		bp->b_bcount = 0;
7597 		count = 0;
7598 		break;
7599 
7600 	case SCMD_DOORLOCK:
7601 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7602 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7603 		bp->b_bcount = count = 0;
7604 		break;
7605 
7606 	case SCMD_READ_POSITION:
7607 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7608 		    "read position\n");
7609 		switch (un->un_read_pos_type) {
7610 		case LONG_POS:
7611 			count = sizeof (tape_position_long_t);
7612 			break;
7613 		case EXT_POS:
7614 			count = min(count, sizeof (tape_position_ext_t));
7615 			break;
7616 		case SHORT_POS:
7617 			count = sizeof (tape_position_t);
7618 			break;
7619 		default:
7620 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7621 			    "Unknown read position type 0x%x in "
7622 			    "st_make_cmd()\n", un->un_read_pos_type);
7623 		}
7624 		bp->b_bcount = count;
7625 		bp->b_flags |= B_READ;
7626 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7627 		break;
7628 
7629 	default:
7630 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7631 		    "Unhandled scsi command 0x%x in st_setup_cmd()\n", com);
7632 	}
7633 
7634 	mutex_exit(ST_MUTEX);
7635 
7636 	if (count > 0) {
7637 		int flg = (bp->b_flags & B_READ) ? B_READ : B_WRITE;
7638 		/*
7639 		 * We're going to do actual I/O.
7640 		 * Set things up for physio.
7641 		 */
7642 		struct iovec aiov;
7643 		struct uio auio;
7644 		struct uio *uio = &auio;
7645 
7646 		bzero(&auio, sizeof (struct uio));
7647 		bzero(&aiov, sizeof (struct iovec));
7648 		aiov.iov_base = bp->b_un.b_addr;
7649 		aiov.iov_len = count;
7650 
7651 		uio->uio_iov = &aiov;
7652 		uio->uio_iovcnt = 1;
7653 		uio->uio_resid = aiov.iov_len;
7654 		uio->uio_segflg = UIO_SYSSPACE;
7655 
7656 		/*
7657 		 * Let physio do the rest...
7658 		 */
7659 		bp->b_forw = (struct buf *)(uintptr_t)com;
7660 		bp->b_back = NULL;
7661 		err = physio(st_strategy, bp, dev, flg, st_minphys, uio);
7662 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7663 		    "st_setup_cmd: physio returns %d\n", err);
7664 	} else {
7665 		/*
7666 		 * Mimic physio
7667 		 */
7668 		bp->b_forw = (struct buf *)(uintptr_t)com;
7669 		bp->b_back = NULL;
7670 		bp->b_edev = dev;
7671 		bp->b_dev = cmpdev(dev);
7672 		bp->b_blkno = 0;
7673 		bp->b_resid = 0;
7674 		(void) st_strategy(bp);
7675 		if (bp->b_flags & B_ASYNC) {
7676 			/*
7677 			 * This is an async command- the caller won't wait
7678 			 * and doesn't care about errors.
7679 			 */
7680 			mutex_enter(ST_MUTEX);
7681 			return (0);
7682 		}
7683 
7684 		/*
7685 		 * BugTraq #4260046
7686 		 * ----------------
7687 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7688 		 * unconditionally. The old comment said...
7689 		 *
7690 		 * "if strategy was flagged with  persistent errors, we would
7691 		 *  have an error here, and the bp would never be sent, so we
7692 		 *  don't want to wait on a bp that was never sent...or hang"
7693 		 *
7694 		 * The new rationale, courtesy of Chitrank...
7695 		 *
7696 		 * "we should unconditionally biowait() here because
7697 		 *  st_strategy() will do a biodone() in the persistent error
7698 		 *  case and the following biowait() will return immediately.
7699 		 *  If not, in the case of "errors after pkt alloc" in
7700 		 *  st_start(), we will not biowait here which will cause the
7701 		 *  next biowait() to return immediately which will cause
7702 		 *  us to send out the next command. In the case where both of
7703 		 *  these use the sbuf, when the first command completes we'll
7704 		 *  free the packet attached to sbuf and the same pkt will
7705 		 *  get freed again when we complete the second command.
7706 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7707 		 *  st_start() for the pkt alloc failure case because physio()
7708 		 *  does biowait() and will hang if we don't do biodone()"
7709 		 */
7710 
7711 		err = biowait(bp);
7712 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7713 		    "st_setup_cmd: biowait returns %d\n", err);
7714 	}
7715 
7716 	mutex_enter(ST_MUTEX);
7717 
7718 	return (err);
7719 }
7720 
7721 static int
7722 st_set_compression(struct scsi_tape *un)
7723 {
7724 	int rval;
7725 	int turn_compression_on;
7726 	minor_t minor;
7727 
7728 	ST_FUNC(ST_DEVINFO, st_set_compression);
7729 
7730 	/*
7731 	 * Drive either dosn't have compression or it is controlled with
7732 	 * special density codes. Return ENOTTY so caller
7733 	 * knows nothing was done.
7734 	 */
7735 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7736 		un->un_comp_page = 0;
7737 		return (ENOTTY);
7738 	}
7739 
7740 	/* set compression based on minor node opened */
7741 	minor = MT_DENSITY(un->un_dev);
7742 
7743 	/*
7744 	 * If this the compression density or
7745 	 * the drive has two densities and uses mode select for
7746 	 * control of compression turn on compression for MT_DENSITY2
7747 	 * as well.
7748 	 */
7749 	if ((minor == ST_COMPRESSION_DENSITY) ||
7750 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7751 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7752 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7753 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7754 
7755 		turn_compression_on = 1;
7756 	} else {
7757 		turn_compression_on = 0;
7758 	}
7759 
7760 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7761 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7762 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7763 
7764 	/*
7765 	 * Need to determine which page does the device use for compression.
7766 	 * First try the data compression page. If this fails try the device
7767 	 * configuration page
7768 	 */
7769 
7770 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7771 		rval = st_set_datacomp_page(un, turn_compression_on);
7772 		if (rval == EALREADY) {
7773 			return (rval);
7774 		}
7775 		if (rval != 0) {
7776 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7777 				/*
7778 				 * This device does not support data
7779 				 * compression page
7780 				 */
7781 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7782 			} else if (un->un_state >= ST_STATE_OPEN) {
7783 				un->un_pos.pmode = invalid;
7784 				rval = EIO;
7785 			} else {
7786 				rval = -1;
7787 			}
7788 		} else {
7789 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7790 		}
7791 	}
7792 
7793 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7794 		rval = st_set_devconfig_page(un, turn_compression_on);
7795 		if (rval == EALREADY) {
7796 			return (rval);
7797 		}
7798 		if (rval != 0) {
7799 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7800 				/*
7801 				 * This device does not support
7802 				 * compression at all advice the
7803 				 * user and unset ST_MODE_SEL_COMP
7804 				 */
7805 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7806 				un->un_comp_page = 0;
7807 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7808 				    "Device Does Not Support Compression\n");
7809 			} else if (un->un_state >= ST_STATE_OPEN) {
7810 				un->un_pos.pmode = invalid;
7811 				rval = EIO;
7812 			} else {
7813 				rval = -1;
7814 			}
7815 		}
7816 	}
7817 
7818 	return (rval);
7819 }
7820 
7821 /*
7822  * set or unset compression thru device configuration page.
7823  */
7824 static int
7825 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
7826 {
7827 	unsigned char cflag;
7828 	int rval = 0;
7829 
7830 
7831 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
7832 
7833 	ASSERT(mutex_owned(ST_MUTEX));
7834 	/*
7835 	 * Figure what to set compression flag to.
7836 	 */
7837 	if (compression_on) {
7838 		/* They have selected a compression node */
7839 		if (un->un_dp->type == ST_TYPE_FUJI) {
7840 			cflag = 0x84;   /* use EDRC */
7841 		} else {
7842 			cflag = ST_DEV_CONFIG_DEF_COMP;
7843 		}
7844 	} else {
7845 		cflag = ST_DEV_CONFIG_NO_COMP;
7846 	}
7847 
7848 	/*
7849 	 * If compression is already set the way it was requested.
7850 	 * And if this not the first time we has tried.
7851 	 */
7852 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
7853 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7854 		return (EALREADY);
7855 	}
7856 
7857 	un->un_mspl->page.dev.comp_alg = cflag;
7858 	/*
7859 	 * need to send mode select even if correct compression is
7860 	 * already set since need to set density code
7861 	 */
7862 
7863 #ifdef STDEBUG
7864 	if ((st_debug & 0x7) >= 6) {
7865 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7866 		    "st_set_devconfig_page: sense data for mode select",
7867 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7868 	}
7869 #endif
7870 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
7871 	    sizeof (struct seq_mode));
7872 
7873 	return (rval);
7874 }
7875 
7876 /*
7877  * set/reset compression bit thru data compression page
7878  */
7879 static int
7880 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
7881 {
7882 	int compression_on_already;
7883 	int rval = 0;
7884 
7885 
7886 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
7887 
7888 	ASSERT(mutex_owned(ST_MUTEX));
7889 	/*
7890 	 * If drive is not capable of compression (at this time)
7891 	 * return EALREADY so caller doesn't think that this page
7892 	 * is not supported. This check is for drives that can
7893 	 * disable compression from the front panel or configuration.
7894 	 * I doubt that a drive that supports this page is not really
7895 	 * capable of compression.
7896 	 */
7897 	if (un->un_mspl->page.comp.dcc == 0) {
7898 		return (EALREADY);
7899 	}
7900 
7901 	/* See if compression currently turned on */
7902 	if (un->un_mspl->page.comp.dce) {
7903 		compression_on_already = 1;
7904 	} else {
7905 		compression_on_already = 0;
7906 	}
7907 
7908 	/*
7909 	 * If compression is already set the way it was requested.
7910 	 * And if this not the first time we has tried.
7911 	 */
7912 	if ((compression_on == compression_on_already) &&
7913 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7914 		return (EALREADY);
7915 	}
7916 
7917 	/*
7918 	 * if we are already set to the appropriate compression
7919 	 * mode, don't set it again
7920 	 */
7921 	if (compression_on) {
7922 		/* compression selected */
7923 		un->un_mspl->page.comp.dce = 1;
7924 	} else {
7925 		un->un_mspl->page.comp.dce = 0;
7926 	}
7927 
7928 
7929 #ifdef STDEBUG
7930 	if ((st_debug & 0x7) >= 6) {
7931 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7932 		    "st_set_datacomp_page: sense data for mode select",
7933 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7934 	}
7935 #endif
7936 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
7937 	    sizeof (struct seq_mode));
7938 
7939 	return (rval);
7940 }
7941 
7942 static int
7943 st_modesense(struct scsi_tape *un)
7944 {
7945 	int rval;
7946 	uchar_t page;
7947 
7948 	ST_FUNC(ST_DEVINFO, st_modesense);
7949 
7950 	page = un->un_comp_page;
7951 
7952 	switch (page) {
7953 	case ST_DEV_DATACOMP_PAGE:
7954 	case ST_DEV_CONFIG_PAGE: /* FALLTHROUGH */
7955 		rval = st_gen_mode_sense(un, st_uscsi_cmd, page, un->un_mspl,
7956 		    sizeof (struct seq_mode));
7957 		break;
7958 
7959 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
7960 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
7961 			page = ST_DEV_CONFIG_PAGE;
7962 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
7963 			    un->un_mspl, sizeof (struct seq_mode));
7964 			if (rval == 0 && un->un_mspl->page_code == page) {
7965 				un->un_comp_page = page;
7966 				break;
7967 			}
7968 			page = ST_DEV_DATACOMP_PAGE;
7969 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
7970 			    un->un_mspl, sizeof (struct seq_mode));
7971 			if (rval == 0 && un->un_mspl->page_code == page) {
7972 				un->un_comp_page = page;
7973 				break;
7974 			}
7975 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
7976 			un->un_comp_page = 0;
7977 		} else {
7978 			un->un_comp_page = 0;
7979 		}
7980 
7981 	default:	/* FALLTHROUGH */
7982 		rval = st_cmd(un, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
7983 	}
7984 	return (rval);
7985 }
7986 
7987 static int
7988 st_modeselect(struct scsi_tape *un)
7989 {
7990 	int rval = 0;
7991 	int ix;
7992 
7993 	ST_FUNC(ST_DEVINFO, st_modeselect);
7994 
7995 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7996 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
7997 	    un->un_dev, un->un_mspl->density);
7998 
7999 	ASSERT(mutex_owned(ST_MUTEX));
8000 
8001 	/*
8002 	 * The parameter list should be the same for all of the
8003 	 * cases that follow so set them here
8004 	 *
8005 	 * Try mode select first if if fails set fields manually
8006 	 */
8007 	rval = st_modesense(un);
8008 	if (rval != 0) {
8009 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8010 		    "st_modeselect: First mode sense failed\n");
8011 		un->un_mspl->bd_len  = 8;
8012 		un->un_mspl->high_nb = 0;
8013 		un->un_mspl->mid_nb  = 0;
8014 		un->un_mspl->low_nb  = 0;
8015 	}
8016 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
8017 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
8018 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
8019 
8020 
8021 	/*
8022 	 * If configured to use a specific density code for a media type.
8023 	 * curdens is previously set by the minor node opened.
8024 	 * If the media type doesn't match the minor node we change it so it
8025 	 * looks like the correct one was opened.
8026 	 */
8027 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
8028 		uchar_t best;
8029 
8030 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
8031 			if (un->un_mspl->media_type ==
8032 			    un->un_dp->mediatype[ix]) {
8033 				best = ix;
8034 				/*
8035 				 * It matches but it might not be the only one.
8036 				 * Use the highest matching media type but not
8037 				 * to exceed the density selected by the open.
8038 				 */
8039 				if (ix < un->un_curdens) {
8040 					continue;
8041 				}
8042 				un->un_curdens = ix;
8043 				break;
8044 			}
8045 		}
8046 		/* If a match was found best will not be 0xff any more */
8047 		if (best < NDENSITIES) {
8048 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8049 			    "found media 0x%X using density 0x%X\n",
8050 			    un->un_mspl->media_type,
8051 			    un->un_dp->densities[best]);
8052 			un->un_mspl->density = un->un_dp->densities[best];
8053 		} else {
8054 			/* Otherwise set density based on minor node opened */
8055 			un->un_mspl->density =
8056 			    un->un_dp->densities[un->un_curdens];
8057 		}
8058 	} else {
8059 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
8060 	}
8061 
8062 	if (un->un_dp->options & ST_NOBUF) {
8063 		un->un_mspl->bufm = 0;
8064 	} else {
8065 		un->un_mspl->bufm = 1;
8066 	}
8067 
8068 	rval = st_set_compression(un);
8069 
8070 	/*
8071 	 * If st_set_compression returned invalid or already it
8072 	 * found no need to do the mode select.
8073 	 * So do it here.
8074 	 */
8075 	if ((rval == ENOTTY) || (rval == EALREADY)) {
8076 
8077 		/* Zero non-writeable fields */
8078 		un->un_mspl->data_len = 0;
8079 		un->un_mspl->media_type = 0;
8080 		un->un_mspl->wp = 0;
8081 
8082 		/* need to set the density code */
8083 		rval = st_cmd(un, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
8084 		if (rval != 0) {
8085 			if (un->un_state >= ST_STATE_OPEN) {
8086 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8087 				    "unable to set tape mode\n");
8088 				un->un_pos.pmode = invalid;
8089 				rval = EIO;
8090 			} else {
8091 				rval = -1;
8092 			}
8093 		}
8094 	}
8095 
8096 	/*
8097 	 * The spec recommends to send a mode sense after a mode select
8098 	 */
8099 	(void) st_modesense(un);
8100 
8101 	ASSERT(mutex_owned(ST_MUTEX));
8102 
8103 	return (rval);
8104 }
8105 
8106 /*
8107  * st_gen_mode_sense
8108  *
8109  * generic mode sense.. it allows for any page
8110  */
8111 static int
8112 st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
8113     struct seq_mode *page_data, int page_size)
8114 {
8115 
8116 	int r;
8117 	char	cdb[CDB_GROUP0];
8118 	struct uscsi_cmd *com;
8119 
8120 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
8121 
8122 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8123 
8124 	bzero(cdb, CDB_GROUP0);
8125 	cdb[0] = SCMD_MODE_SENSE;
8126 	cdb[2] = (char)page;
8127 	cdb[4] = (char)page_size;
8128 
8129 	com->uscsi_cdb = cdb;
8130 	com->uscsi_cdblen = CDB_GROUP0;
8131 	com->uscsi_bufaddr = (caddr_t)page_data;
8132 	com->uscsi_buflen = page_size;
8133 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8134 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8135 
8136 	r = ubf(un, com, FKIOCTL);
8137 	kmem_free(com, sizeof (*com));
8138 	return (r);
8139 }
8140 
8141 /*
8142  * st_gen_mode_select
8143  *
8144  * generic mode select.. it allows for any page
8145  */
8146 static int
8147 st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
8148     struct seq_mode *page_data, int page_size)
8149 {
8150 
8151 	int r;
8152 	char cdb[CDB_GROUP0];
8153 	struct uscsi_cmd *com;
8154 
8155 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
8156 
8157 	/* Zero non-writeable fields */
8158 	page_data->data_len = 0;
8159 	page_data->media_type = 0;
8160 	page_data->wp = 0;
8161 
8162 	/*
8163 	 * If mode select has any page data, zero the ps (Page Savable) bit.
8164 	 */
8165 	if (page_size > MSIZE) {
8166 		page_data->ps = 0;
8167 	}
8168 
8169 
8170 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8171 
8172 	/*
8173 	 * then, do a mode select to set what ever info
8174 	 */
8175 	bzero(cdb, CDB_GROUP0);
8176 	cdb[0] = SCMD_MODE_SELECT;
8177 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
8178 	cdb[4] = (char)page_size;
8179 
8180 	com->uscsi_cdb = cdb;
8181 	com->uscsi_cdblen = CDB_GROUP0;
8182 	com->uscsi_bufaddr = (caddr_t)page_data;
8183 	com->uscsi_buflen = page_size;
8184 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8185 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_WRITE;
8186 
8187 	r = ubf(un, com, FKIOCTL);
8188 
8189 	kmem_free(com, sizeof (*com));
8190 	return (r);
8191 }
8192 
8193 static int
8194 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
8195 {
8196 	int rval;
8197 	char cdb[CDB_GROUP0];
8198 	struct uscsi_cmd *com;
8199 
8200 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
8201 
8202 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8203 
8204 	bzero(cdb, CDB_GROUP0);
8205 	cdb[0] = SCMD_READ_BLKLIM;
8206 
8207 	com->uscsi_cdb = cdb;
8208 	com->uscsi_cdblen = CDB_GROUP0;
8209 	com->uscsi_bufaddr = (caddr_t)read_blk;
8210 	com->uscsi_buflen = sizeof (struct read_blklim);
8211 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8212 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8213 
8214 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8215 	if (com->uscsi_status || com->uscsi_resid) {
8216 		rval = -1;
8217 	}
8218 
8219 	kmem_free(com, sizeof (*com));
8220 	return (rval);
8221 }
8222 
8223 static int
8224 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
8225     size_t buflen)
8226 {
8227 	int rval;
8228 	char cdb[CDB_GROUP1];
8229 	struct uscsi_cmd *com;
8230 
8231 	ST_FUNC(ST_DEVINFO, st_report_density_support);
8232 
8233 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8234 
8235 	bzero(cdb, CDB_GROUP1);
8236 	cdb[0] = SCMD_REPORT_DENSITIES;
8237 	cdb[7] = (buflen & 0xff00) >> 8;
8238 	cdb[8] = buflen & 0xff;
8239 
8240 	com->uscsi_cdb = cdb;
8241 	com->uscsi_cdblen = CDB_GROUP1;
8242 	com->uscsi_bufaddr = (caddr_t)density_data;
8243 	com->uscsi_buflen = buflen;
8244 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8245 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8246 
8247 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8248 	if (com->uscsi_status || com->uscsi_resid) {
8249 		rval = -1;
8250 	}
8251 
8252 	kmem_free(com, sizeof (*com));
8253 	return (rval);
8254 }
8255 
8256 static int
8257 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
8258     uchar_t option_code, ushort_t service_action)
8259 {
8260 	int rval;
8261 	char cdb[CDB_GROUP5];
8262 	struct uscsi_cmd *com;
8263 	uint32_t allo_length;
8264 
8265 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
8266 
8267 	allo_length = sizeof (struct one_com_des) +
8268 	    sizeof (struct com_timeout_des);
8269 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8270 
8271 	bzero(cdb, CDB_GROUP5);
8272 	cdb[0] = (char)SCMD_MAINTENANCE_IN;
8273 	cdb[1] = 0x0c; /* service action */
8274 	if (service_action) {
8275 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
8276 		cdb[4] = (service_action & 0xff00) >> 8;
8277 		cdb[5] = service_action & 0xff;
8278 	} else {
8279 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
8280 		    0x80); /* RCTD */
8281 	}
8282 	cdb[3] = option_code;
8283 	cdb[6] = (allo_length & 0xff000000) >> 24;
8284 	cdb[7] = (allo_length & 0xff0000) >> 16;
8285 	cdb[8] = (allo_length & 0xff00) >> 8;
8286 	cdb[9] = allo_length & 0xff;
8287 
8288 	com->uscsi_cdb = cdb;
8289 	com->uscsi_cdblen = CDB_GROUP5;
8290 	com->uscsi_bufaddr = (caddr_t)oper_data;
8291 	com->uscsi_buflen = allo_length;
8292 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8293 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
8294 
8295 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8296 	if (com->uscsi_status) {
8297 		rval = -1;
8298 	}
8299 
8300 	kmem_free(com, sizeof (*com));
8301 	return (rval);
8302 }
8303 
8304 /*
8305  * Changes devices blocksize and bsize to requested blocksize nblksz.
8306  * Returns returned value from first failed call or zero on success.
8307  */
8308 static int
8309 st_change_block_size(struct scsi_tape *un, uint32_t nblksz)
8310 {
8311 	struct seq_mode *current;
8312 	int rval;
8313 	uint32_t oldblksz;
8314 
8315 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8316 
8317 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8318 
8319 	current = kmem_zalloc(MSIZE, KM_SLEEP);
8320 
8321 	/*
8322 	 * If we haven't got the compression page yet, do that first.
8323 	 */
8324 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
8325 		(void) st_modesense(un);
8326 	}
8327 
8328 	/* Read current settings */
8329 	rval = st_gen_mode_sense(un, st_uscsi_cmd, 0, current, MSIZE);
8330 	if (rval != 0) {
8331 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8332 		    "mode sense for change block size failed: rval = %d", rval);
8333 		goto finish;
8334 	}
8335 
8336 	/* Figure the current block size */
8337 	oldblksz =
8338 	    (current->high_bl << 16) |
8339 	    (current->mid_bl << 8) |
8340 	    (current->low_bl);
8341 
8342 	/* If current block size is the same as requested were done */
8343 	if (oldblksz == nblksz) {
8344 		un->un_bsize = nblksz;
8345 		rval = 0;
8346 		goto finish;
8347 	}
8348 
8349 	/* Change to requested block size */
8350 	current->high_bl = (uchar_t)(nblksz >> 16);
8351 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8352 	current->low_bl  = (uchar_t)(nblksz);
8353 
8354 	/* Attempt to change block size */
8355 	rval = st_gen_mode_select(un, st_uscsi_cmd, current, MSIZE);
8356 	if (rval != 0) {
8357 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8358 		    "Set new block size failed: rval = %d", rval);
8359 		goto finish;
8360 	}
8361 
8362 	/* Read back and verify setting */
8363 	rval = st_modesense(un);
8364 	if (rval == 0) {
8365 		un->un_bsize =
8366 		    (un->un_mspl->high_bl << 16) |
8367 		    (un->un_mspl->mid_bl << 8) |
8368 		    (un->un_mspl->low_bl);
8369 
8370 		if (un->un_bsize != nblksz) {
8371 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8372 			    "Blocksize set does not equal requested blocksize"
8373 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8374 			rval = EIO;
8375 		}
8376 	}
8377 finish:
8378 	kmem_free(current, MSIZE);
8379 	return (rval);
8380 }
8381 
8382 
8383 static void
8384 st_init(struct scsi_tape *un)
8385 {
8386 	ST_FUNC(ST_DEVINFO, st_init);
8387 
8388 	ASSERT(mutex_owned(ST_MUTEX));
8389 
8390 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8391 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8392 	    un->un_dev);
8393 
8394 	un->un_pos.blkno = 0;
8395 	un->un_pos.fileno = 0;
8396 	un->un_lastop = ST_OP_NIL;
8397 	un->un_pos.eof = ST_NO_EOF;
8398 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8399 	if (st_error_level != SCSI_ERR_ALL) {
8400 		if (DEBUGGING) {
8401 			st_error_level = SCSI_ERR_ALL;
8402 		} else {
8403 			st_error_level = SCSI_ERR_RETRYABLE;
8404 		}
8405 	}
8406 }
8407 
8408 
8409 static void
8410 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8411 {
8412 	struct scsi_pkt *pkt;
8413 	struct uscsi_cmd *ucmd;
8414 	recov_info *ri;
8415 	int tval = 0;
8416 	uint64_t count;
8417 	uint32_t additional;
8418 	int flags = 0;
8419 	int cdb_len = CDB_GROUP0; /* default */
8420 	uchar_t com;
8421 	char fixbit;
8422 	char short_fm = 0;
8423 	int stat_size =
8424 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
8425 
8426 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8427 
8428 	ASSERT(mutex_owned(ST_MUTEX));
8429 
8430 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8431 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8432 
8433 
8434 	/*
8435 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8436 	 * Length Indicator bits on read/write commands, for setting
8437 	 * the Long bit on erase commands, and for setting the Code
8438 	 * Field bits on space commands.
8439 	 */
8440 
8441 	/* regular raw I/O */
8442 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
8443 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8444 		    CDB_GROUP0, stat_size, st_recov_sz, 0, func,
8445 		    (caddr_t)un);
8446 		if (pkt == NULL) {
8447 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8448 			    "Read Write scsi_init_pkt() failure\n");
8449 			goto exit;
8450 		}
8451 		ASSERT(pkt->pkt_resid == 0);
8452 #ifdef STDEBUG
8453 		bzero(pkt->pkt_private, st_recov_sz);
8454 		bzero(pkt->pkt_scbp, stat_size);
8455 #endif
8456 		ri = (recov_info *)pkt->pkt_private;
8457 		ri->privatelen = st_recov_sz;
8458 		if (un->un_bsize == 0) {
8459 			count = bp->b_bcount;
8460 			fixbit = 0;
8461 		} else {
8462 			count = bp->b_bcount / un->un_bsize;
8463 			fixbit = 1;
8464 		}
8465 		if (bp->b_flags & B_READ) {
8466 			com = SCMD_READ;
8467 			un->un_lastop = ST_OP_READ;
8468 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8469 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8470 				fixbit = 2;
8471 			}
8472 		} else {
8473 			com = SCMD_WRITE;
8474 			un->un_lastop = ST_OP_WRITE;
8475 		}
8476 		tval = un->un_dp->io_timeout;
8477 
8478 		/*
8479 		 * For really large xfers, increase timeout
8480 		 */
8481 		if (bp->b_bcount > (10 * ONE_MEG))
8482 			tval *= bp->b_bcount/(10 * ONE_MEG);
8483 
8484 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8485 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8486 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8487 
8488 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8489 		/*
8490 		 * uscsi - build command, allocate scsi resources
8491 		 */
8492 		st_make_uscsi_cmd(un, ucmd, bp, func);
8493 		goto exit;
8494 
8495 	} else {				/* special I/O */
8496 		struct buf *allocbp = NULL;
8497 		com = (uchar_t)(uintptr_t)bp->b_forw;
8498 		count = bp->b_bcount;
8499 
8500 		switch (com) {
8501 		case SCMD_READ:
8502 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8503 			    "special read %"PRId64"\n", count);
8504 			if (un->un_bsize == 0) {
8505 				fixbit = 2;	/* suppress SILI */
8506 			} else {
8507 				fixbit = 1;	/* Fixed Block Mode */
8508 				count /= un->un_bsize;
8509 			}
8510 			allocbp = bp;
8511 			un->un_lastop = ST_OP_READ;
8512 			tval = un->un_dp->io_timeout;
8513 			break;
8514 
8515 		case SCMD_WRITE:
8516 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8517 			    "special write %"PRId64"\n", count);
8518 			if (un->un_bsize != 0) {
8519 				fixbit = 1;	/* Fixed Block Mode */
8520 				count /= un->un_bsize;
8521 			} else {
8522 				fixbit = 0;
8523 			}
8524 			allocbp = bp;
8525 			un->un_lastop = ST_OP_WRITE;
8526 			tval = un->un_dp->io_timeout;
8527 			break;
8528 
8529 		case SCMD_WRITE_FILE_MARK:
8530 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8531 			    "write %"PRId64" file marks\n", count);
8532 			un->un_lastop = ST_OP_WEOF;
8533 			fixbit = 0;
8534 			tval = un->un_dp->io_timeout;
8535 			/*
8536 			 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8537 			 * device, set the Vendor Unique bit to
8538 			 * write Short File Mark.
8539 			 */
8540 			if ((un->un_dp->options & ST_SHORT_FILEMARKS) &&
8541 			    ((un->un_dp->type == ST_TYPE_EXB8500) ||
8542 			    (un->un_dp->type == ST_TYPE_EXABYTE))) {
8543 				/*
8544 				 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8545 				 * is set to to write Short File Mark
8546 				 */
8547 				short_fm = 1;
8548 			}
8549 			break;
8550 
8551 		case SCMD_REWIND:
8552 			/*
8553 			 * In the case of rewind we're gona do the rewind with
8554 			 * the immediate bit set so status will be retured when
8555 			 * the command is accepted by the device. We clear the
8556 			 * B_ASYNC flag so we wait for that acceptance.
8557 			 */
8558 			if (bp->b_flags & B_ASYNC) {
8559 				allocbp = bp;
8560 				if (count) {
8561 					fixbit = 1;
8562 					bp->b_flags &= ~B_ASYNC;
8563 				}
8564 			} else {
8565 				fixbit = 0;
8566 			}
8567 			count = 0;
8568 			bp->b_bcount = 0;
8569 			un->un_lastop = ST_OP_CTL;
8570 			tval = un->un_dp->rewind_timeout;
8571 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8572 			    "rewind\n");
8573 			break;
8574 
8575 		case SCMD_SPACE_G4:
8576 			cdb_len = CDB_GROUP4;
8577 		case SCMD_SPACE: /* FALL THROUGH */
8578 			fixbit = SPACE_TYPE(bp->b_bcount);
8579 			count = SPACE_CNT(bp->b_bcount);
8580 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8581 			    " %s space %s %"PRId64" from file %d blk %d\n",
8582 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8583 			    space_strs[fixbit & 7], count,
8584 			    un->un_pos.fileno, un->un_pos.blkno);
8585 			additional = count >> 32;
8586 			count &= 0xffffffff;
8587 			un->un_lastop = ST_OP_CTL;
8588 			tval = un->un_dp->space_timeout;
8589 			break;
8590 
8591 		case SCMD_LOAD:
8592 			ASSERT(count < 10);
8593 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8594 			    "%s tape\n", load_strs[count]);
8595 			fixbit = 0;
8596 
8597 			/* Loading or Unloading */
8598 			if (count & LD_LOAD) {
8599 				tval = un->un_dp->load_timeout;
8600 			} else {
8601 				tval = un->un_dp->unload_timeout;
8602 			}
8603 			/* Is Retension requested */
8604 			if (count & LD_RETEN) {
8605 				tval += un->un_dp->rewind_timeout;
8606 			}
8607 			un->un_lastop = ST_OP_CTL;
8608 			break;
8609 
8610 		case SCMD_ERASE:
8611 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8612 			    "erase tape\n");
8613 			ASSERT(count == 1); /* mt sets this */
8614 			if (count == 1) {
8615 				/*
8616 				 * do long erase
8617 				 */
8618 				fixbit = 1; /* Long */
8619 
8620 				/* Drive might not honor immidiate bit */
8621 				tval = un->un_dp->erase_timeout;
8622 			} else {
8623 				/* Short Erase */
8624 				tval = un->un_dp->erase_timeout;
8625 				fixbit = 0;
8626 			}
8627 			un->un_lastop = ST_OP_CTL;
8628 			count = 0;
8629 			break;
8630 
8631 		case SCMD_MODE_SENSE:
8632 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8633 			    "mode sense\n");
8634 			allocbp = bp;
8635 			fixbit = 0;
8636 			tval = un->un_dp->non_motion_timeout;
8637 			un->un_lastop = ST_OP_CTL;
8638 			break;
8639 
8640 		case SCMD_MODE_SELECT:
8641 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8642 			    "mode select\n");
8643 			allocbp = bp;
8644 			fixbit = 0;
8645 			tval = un->un_dp->non_motion_timeout;
8646 			un->un_lastop = ST_OP_CTL;
8647 			break;
8648 
8649 		case SCMD_RESERVE:
8650 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8651 			    "reserve\n");
8652 			fixbit = 0;
8653 			tval = un->un_dp->non_motion_timeout;
8654 			un->un_lastop = ST_OP_CTL;
8655 			break;
8656 
8657 		case SCMD_RELEASE:
8658 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8659 			    "release\n");
8660 			fixbit = 0;
8661 			tval = un->un_dp->non_motion_timeout;
8662 			un->un_lastop = ST_OP_CTL;
8663 			break;
8664 
8665 		case SCMD_READ_BLKLIM:
8666 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8667 			    "read block limits\n");
8668 			allocbp = bp;
8669 			fixbit = count = 0;
8670 			tval = un->un_dp->non_motion_timeout;
8671 			un->un_lastop = ST_OP_CTL;
8672 			break;
8673 
8674 		case SCMD_TEST_UNIT_READY:
8675 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8676 			    "test unit ready\n");
8677 			fixbit = 0;
8678 			tval = un->un_dp->non_motion_timeout;
8679 			un->un_lastop = ST_OP_CTL;
8680 			break;
8681 
8682 		case SCMD_DOORLOCK:
8683 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8684 			    "prevent/allow media removal\n");
8685 			fixbit = 0;
8686 			tval = un->un_dp->non_motion_timeout;
8687 			un->un_lastop = ST_OP_CTL;
8688 			break;
8689 
8690 		case SCMD_READ_POSITION:
8691 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8692 			    "read position\n");
8693 			fixbit = un->un_read_pos_type;
8694 			cdb_len = CDB_GROUP1;
8695 			tval = un->un_dp->non_motion_timeout;
8696 			allocbp = bp;
8697 			un->un_lastop = ST_OP_CTL;
8698 			switch (un->un_read_pos_type) {
8699 			case LONG_POS:
8700 				count = 0;
8701 				break;
8702 			case EXT_POS:
8703 				count = sizeof (tape_position_ext_t);
8704 				break;
8705 			case SHORT_POS:
8706 				count = 0;
8707 				break;
8708 			default:
8709 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8710 				    "Unknown read position type 0x%x in "
8711 				    " st_make_cmd()\n", un->un_read_pos_type);
8712 			}
8713 			break;
8714 
8715 		default:
8716 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8717 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8718 			    com);
8719 		}
8720 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8721 		    st_recov_sz, 0, func, (caddr_t)un);
8722 		if (pkt == NULL) {
8723 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8724 			    "generic command scsi_init_pkt() failure\n");
8725 			goto exit;
8726 		}
8727 
8728 		ASSERT(pkt->pkt_resid == 0);
8729 #ifdef STDEBUG
8730 		bzero(pkt->pkt_private, st_recov_sz);
8731 		bzero(pkt->pkt_scbp, stat_size);
8732 #endif
8733 		ri = (recov_info *)pkt->pkt_private;
8734 		ri->privatelen = st_recov_sz;
8735 		if (allocbp) {
8736 			ASSERT(geterror(allocbp) == 0);
8737 		}
8738 
8739 	}
8740 
8741 
8742 	(void) scsi_setup_cdb((union scsi_cdb *)pkt->pkt_cdbp,
8743 	    com, 0, (uint_t)count, additional);
8744 	FILL_SCSI1_LUN(un->un_sd, pkt);
8745 	/*
8746 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8747 	 */
8748 	((union scsi_cdb *)(pkt->pkt_cdbp))->t_code = fixbit;
8749 	((union scsi_cdb *)pkt->pkt_cdbp)->g0_vu_1 = short_fm;
8750 	pkt->pkt_flags = flags;
8751 
8752 	ASSERT(tval);
8753 	pkt->pkt_time = tval;
8754 	if (bp == un->un_recov_buf) {
8755 		pkt->pkt_comp = st_recov_cb;
8756 	} else {
8757 		pkt->pkt_comp = st_intr;
8758 	}
8759 
8760 	st_add_recovery_info_to_pkt(un, bp, pkt);
8761 
8762 exit:
8763 	ASSERT(mutex_owned(ST_MUTEX));
8764 }
8765 
8766 
8767 /*
8768  * Build a command based on a uscsi command;
8769  */
8770 static void
8771 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
8772     struct buf *bp, int (*func)(caddr_t))
8773 {
8774 	struct scsi_pkt *pkt;
8775 	recov_info *ri;
8776 	caddr_t cdb;
8777 	int	cdblen;
8778 	int	stat_size = 1;
8779 	int	flags = 0;
8780 
8781 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
8782 
8783 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8784 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
8785 
8786 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
8787 		if (un->un_arq_enabled) {
8788 			if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
8789 				stat_size = (int)(ucmd->uscsi_rqlen) +
8790 				    sizeof (struct scsi_arq_status) -
8791 				    sizeof (struct scsi_extended_sense);
8792 				flags = PKT_XARQ;
8793 			} else {
8794 				stat_size = sizeof (struct scsi_arq_status);
8795 			}
8796 		}
8797 	}
8798 
8799 	ASSERT(mutex_owned(ST_MUTEX));
8800 
8801 	cdb = ucmd->uscsi_cdb;
8802 	cdblen = ucmd->uscsi_cdblen;
8803 
8804 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8805 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
8806 	    ucmd->uscsi_buflen, bp->b_bcount);
8807 	pkt = scsi_init_pkt(ROUTE, NULL,
8808 	    (bp->b_bcount > 0) ? bp : NULL,
8809 	    cdblen, stat_size, st_recov_sz, flags, func, (caddr_t)un);
8810 	if (pkt == NULL) {
8811 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8812 		    "uscsi command scsi_init_pkt() failure\n");
8813 		goto exit;
8814 	}
8815 
8816 	ASSERT(pkt->pkt_resid == 0);
8817 #ifdef STDEBUG
8818 	bzero(pkt->pkt_private, st_recov_sz);
8819 	bzero(pkt->pkt_scbp, stat_size);
8820 #endif
8821 	ri = (recov_info *)pkt->pkt_private;
8822 	ri->privatelen = st_recov_sz;
8823 
8824 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
8825 
8826 #ifdef STDEBUG
8827 	if ((st_debug & 0x7) >= 6) {
8828 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8829 		    "pkt_cdbp", (char *)cdb, cdblen);
8830 	}
8831 #endif
8832 
8833 	if (ucmd->uscsi_flags & USCSI_SILENT) {
8834 		pkt->pkt_flags |= FLAG_SILENT;
8835 	}
8836 
8837 	pkt->pkt_time = ucmd->uscsi_timeout;
8838 	if (bp == un->un_recov_buf) {
8839 		pkt->pkt_comp = st_recov_cb;
8840 	} else {
8841 		pkt->pkt_comp = st_intr;
8842 	}
8843 	st_add_recovery_info_to_pkt(un, bp, pkt);
8844 exit:
8845 	ASSERT(mutex_owned(ST_MUTEX));
8846 }
8847 
8848 
8849 /*
8850  * restart cmd currently at the head of the runq
8851  *
8852  * If scsi_transport() succeeds or the retries
8853  * count exhausted, restore the throttle that was
8854  * zeroed out in st_handle_intr_busy().
8855  *
8856  */
8857 static void
8858 st_intr_restart(void *arg)
8859 {
8860 	struct scsi_tape *un = arg;
8861 	struct buf *bp;
8862 	int queued;
8863 	int status = TRAN_ACCEPT;
8864 
8865 	mutex_enter(ST_MUTEX);
8866 
8867 	ST_FUNC(ST_DEVINFO, st_intr_restart);
8868 
8869 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8870 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
8871 
8872 	un->un_hib_tid = 0;
8873 
8874 	if (un->un_recov_buf_busy != 0) {
8875 		bp = un->un_recov_buf;
8876 		queued = 0;
8877 	} else if (un->un_sbuf_busy != 0) {
8878 		bp = un->un_sbufp;
8879 		queued = 0;
8880 	} else if (un->un_quef != NULL) {
8881 		bp = un->un_quef;
8882 		queued = 1;
8883 	} else {
8884 		mutex_exit(ST_MUTEX);
8885 		return;
8886 	}
8887 
8888 	/*
8889 	 * Here we know :
8890 	 *	throttle = 0, via st_handle_intr_busy
8891 	 */
8892 
8893 	if (queued) {
8894 		/*
8895 		 * move from waitq to runq, if there is anything on the waitq
8896 		 */
8897 		(void) st_remove_from_queue(&un->un_quef, &un->un_quef, bp);
8898 
8899 		if (un->un_runqf) {
8900 			/*
8901 			 * not good, we don't want to requeue something after
8902 			 * another.
8903 			 */
8904 			mutex_exit(ST_MUTEX);
8905 			goto done_error;
8906 		} else {
8907 			un->un_runqf = bp;
8908 			un->un_runql = bp;
8909 		}
8910 	}
8911 
8912 	ST_CDB(ST_DEVINFO, "Interrupt restart CDB",
8913 	    (char *)BP_PKT(bp)->pkt_cdbp);
8914 
8915 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
8916 
8917 	status = st_transport(un, BP_PKT(bp));
8918 
8919 	if (status != TRAN_ACCEPT) {
8920 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8921 		mutex_exit(ST_MUTEX);
8922 
8923 		if (status == TRAN_BUSY) {
8924 			if (st_handle_intr_busy(un, bp,
8925 			    ST_TRAN_BUSY_TIMEOUT) == 0)
8926 				return;	/* timeout is setup again */
8927 		}
8928 
8929 	} else {
8930 		un->un_tran_retry_ct = 0;
8931 		if (un->un_last_throttle) {
8932 			un->un_throttle = un->un_last_throttle;
8933 		}
8934 		mutex_exit(ST_MUTEX);
8935 		return;
8936 	}
8937 
8938 done_error:
8939 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8940 	    "restart transport rejected\n");
8941 	bp->b_resid = bp->b_bcount;
8942 
8943 #ifndef __lock_lint
8944 	/*
8945 	 * warlock doesn't understand this potential
8946 	 * recursion?
8947 	 */
8948 	mutex_enter(ST_MUTEX);
8949 	if (un->un_last_throttle) {
8950 		un->un_throttle = un->un_last_throttle;
8951 	}
8952 	if (status != TRAN_ACCEPT)
8953 		ST_DO_ERRSTATS(un, st_transerrs);
8954 	ST_DO_KSTATS(bp, kstat_waitq_exit);
8955 	st_set_pe_flag(un);
8956 	st_bioerror(bp, EIO);
8957 	st_done_and_mutex_exit(un, bp);
8958 #endif
8959 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8960 	    "busy restart aborted\n");
8961 }
8962 
8963 /*
8964  * st_check_media():
8965  * Periodically check the media state using scsi_watch service;
8966  * this service calls back after TUR and possibly request sense
8967  * the callback handler (st_media_watch_cb()) decodes the request sense
8968  * data (if any)
8969  */
8970 
8971 static int
8972 st_check_media(dev_t dev, enum mtio_state state)
8973 {
8974 	int rval = 0;
8975 	enum mtio_state	prev_state;
8976 	opaque_t token = NULL;
8977 
8978 	GET_SOFT_STATE(dev);
8979 
8980 	ST_FUNC(ST_DEVINFO, st_check_media);
8981 
8982 	mutex_enter(ST_MUTEX);
8983 
8984 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8985 	    "st_check_media:state=%x, mediastate=%x\n",
8986 	    state, un->un_mediastate);
8987 
8988 	prev_state = un->un_mediastate;
8989 
8990 	/*
8991 	 * is there anything to do?
8992 	 */
8993 retry:
8994 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
8995 		/*
8996 		 * submit the request to the scsi_watch service;
8997 		 * scsi_media_watch_cb() does the real work
8998 		 */
8999 		mutex_exit(ST_MUTEX);
9000 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
9001 		    st_check_media_time, SENSE_LENGTH,
9002 		    st_media_watch_cb, (caddr_t)dev);
9003 		if (token == NULL) {
9004 			rval = EAGAIN;
9005 			goto done;
9006 		}
9007 		mutex_enter(ST_MUTEX);
9008 
9009 		un->un_swr_token = token;
9010 		un->un_specified_mediastate = state;
9011 
9012 		/*
9013 		 * now wait for media change
9014 		 * we will not be signalled unless mediastate == state but it
9015 		 * still better to test for this condition, since there
9016 		 * is a 5 sec cv_broadcast delay when
9017 		 *  mediastate == MTIO_INSERTED
9018 		 */
9019 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9020 		    "st_check_media:waiting for media state change\n");
9021 		while (un->un_mediastate == state) {
9022 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
9023 				mutex_exit(ST_MUTEX);
9024 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9025 				    "st_check_media:waiting for media state "
9026 				    "was interrupted\n");
9027 				rval = EINTR;
9028 				goto done;
9029 			}
9030 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9031 			    "st_check_media:received signal, state=%x\n",
9032 			    un->un_mediastate);
9033 		}
9034 	}
9035 
9036 	/*
9037 	 * if we transitioned to MTIO_INSERTED, media has really been
9038 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
9039 	 * Reset and retry the state change.  If everything is ok, replay
9040 	 * the open() logic.
9041 	 */
9042 	if ((un->un_mediastate == MTIO_INSERTED) &&
9043 	    (un->un_state == ST_STATE_OFFLINE)) {
9044 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9045 		    "st_check_media: calling st_cmd to confirm inserted\n");
9046 
9047 		/*
9048 		 * set this early so that TUR will make it through strategy
9049 		 * without triggering a st_tape_init().  We needed it set
9050 		 * before calling st_tape_init() ourselves anyway.  If TUR
9051 		 * fails, set it back
9052 		 */
9053 		un->un_state = ST_STATE_INITIALIZING;
9054 
9055 		/*
9056 		 * If not reserved fail as getting reservation conflict
9057 		 * will make this hang forever.
9058 		 */
9059 		if ((un->un_rsvd_status &
9060 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9061 			mutex_exit(ST_MUTEX);
9062 			rval = EACCES;
9063 			goto done;
9064 		}
9065 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
9066 		if (rval == EACCES) {
9067 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9068 			    "st_check_media: TUR got Reservation Conflict\n");
9069 			mutex_exit(ST_MUTEX);
9070 			goto done;
9071 		}
9072 		if (rval) {
9073 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9074 			    "st_check_media: TUR failed, going to retry\n");
9075 			un->un_mediastate = prev_state;
9076 			un->un_state = ST_STATE_OFFLINE;
9077 			goto retry;
9078 		}
9079 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9080 		    "st_check_media: media inserted\n");
9081 
9082 		/* this also rewinds the tape */
9083 		rval = st_tape_init(un);
9084 		if (rval != 0) {
9085 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9086 			    "st_check_media : OFFLINE init failure ");
9087 			un->un_state = ST_STATE_OFFLINE;
9088 			un->un_pos.pmode = invalid;
9089 		} else {
9090 			un->un_state = ST_STATE_OPEN_PENDING_IO;
9091 		}
9092 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
9093 	    (un->un_state != ST_STATE_OFFLINE)) {
9094 		/*
9095 		 * supported devices must be rewound before ejection
9096 		 * rewind resets fileno & blkno
9097 		 */
9098 		un->un_laststate = un->un_state;
9099 		un->un_state = ST_STATE_OFFLINE;
9100 	}
9101 	mutex_exit(ST_MUTEX);
9102 done:
9103 	if (token) {
9104 		(void) scsi_watch_request_terminate(token,
9105 		    SCSI_WATCH_TERMINATE_WAIT);
9106 		mutex_enter(ST_MUTEX);
9107 		un->un_swr_token = (opaque_t)NULL;
9108 		mutex_exit(ST_MUTEX);
9109 	}
9110 
9111 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
9112 
9113 	return (rval);
9114 }
9115 
9116 /*
9117  * st_media_watch_cb() is called by scsi_watch_thread for
9118  * verifying the request sense data (if any)
9119  */
9120 static int
9121 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
9122 {
9123 	struct scsi_status *statusp = resultp->statusp;
9124 	struct scsi_extended_sense *sensep = resultp->sensep;
9125 	uchar_t actual_sense_length = resultp->actual_sense_length;
9126 	struct scsi_tape *un;
9127 	enum mtio_state state = MTIO_NONE;
9128 	int instance;
9129 	dev_t dev = (dev_t)arg;
9130 
9131 	instance = MTUNIT(dev);
9132 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
9133 		return (-1);
9134 	}
9135 
9136 	mutex_enter(ST_MUTEX);
9137 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
9138 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9139 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
9140 	    *((char *)statusp), (void *)sensep,
9141 	    actual_sense_length);
9142 
9143 
9144 	/*
9145 	 * if there was a check condition then sensep points to valid
9146 	 * sense data
9147 	 * if status was not a check condition but a reservation or busy
9148 	 * status then the new state is MTIO_NONE
9149 	 */
9150 	if (sensep) {
9151 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9152 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
9153 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
9154 
9155 		switch (un->un_dp->type) {
9156 		default:
9157 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9158 			    "st_media_watch_cb: unknown drive type %d, "
9159 			    "default to ST_TYPE_HP\n", un->un_dp->type);
9160 		/* FALLTHROUGH */
9161 
9162 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
9163 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
9164 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
9165 			if (un->un_dp->type == ST_TYPE_FUJI) {
9166 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9167 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
9168 			} else {
9169 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9170 				    "st_media_watch_cb: ST_TYPE_HP\n");
9171 			}
9172 			switch (sensep->es_key) {
9173 			case KEY_UNIT_ATTENTION:
9174 				/* not ready to ready transition */
9175 				/* hp/es_qual_code == 80 on>off>on */
9176 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
9177 				if (sensep->es_add_code == 0x28) {
9178 					state = MTIO_INSERTED;
9179 				}
9180 				break;
9181 			case KEY_NOT_READY:
9182 				/* in process, rewinding or loading */
9183 				if ((sensep->es_add_code == 0x04) &&
9184 				    (sensep->es_qual_code == 0x00)) {
9185 					state = MTIO_EJECTED;
9186 				}
9187 				break;
9188 			}
9189 			break;
9190 
9191 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
9192 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9193 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
9194 			switch (sensep->es_key) {
9195 			case KEY_UNIT_ATTENTION:
9196 				/* operator medium removal request */
9197 				if ((sensep->es_add_code == 0x5a) &&
9198 				    (sensep->es_qual_code == 0x01)) {
9199 					state = MTIO_EJECTED;
9200 				/* not ready to ready transition */
9201 				} else if ((sensep->es_add_code == 0x28) &&
9202 				    (sensep->es_qual_code == 0x00)) {
9203 					state = MTIO_INSERTED;
9204 				}
9205 				break;
9206 			case KEY_NOT_READY:
9207 				/* medium not present */
9208 				if (sensep->es_add_code == 0x3a) {
9209 					state = MTIO_EJECTED;
9210 				}
9211 				break;
9212 			}
9213 			break;
9214 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
9215 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9216 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
9217 			switch (sensep->es_key) {
9218 			case KEY_NOT_READY:
9219 				if ((sensep->es_add_code == 0x04) &&
9220 				    (sensep->es_qual_code == 0x00)) {
9221 					/* volume not mounted? */
9222 					state = MTIO_EJECTED;
9223 				} else if (sensep->es_add_code == 0x3a) {
9224 					state = MTIO_EJECTED;
9225 				}
9226 				break;
9227 			case KEY_UNIT_ATTENTION:
9228 				state = MTIO_EJECTED;
9229 				break;
9230 			}
9231 			break;
9232 
9233 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
9234 			switch (sensep->es_key) {
9235 			case KEY_UNIT_ATTENTION:
9236 				if (sensep->es_add_code == 0x28) {
9237 					state = MTIO_INSERTED;
9238 				}
9239 				break;
9240 			case KEY_NOT_READY:
9241 				if (sensep->es_add_code == 0x04) {
9242 					/* in transition but could be either */
9243 					state = un->un_specified_mediastate;
9244 				} else if ((sensep->es_add_code == 0x3a) &&
9245 				    (sensep->es_qual_code == 0x00)) {
9246 					state = MTIO_EJECTED;
9247 				}
9248 				break;
9249 			}
9250 			break;
9251 		}
9252 	} else if (*((char *)statusp) == STATUS_GOOD) {
9253 		state = MTIO_INSERTED;
9254 	}
9255 
9256 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9257 	    "st_media_watch_cb:state=%x, specified=%x\n",
9258 	    state, un->un_specified_mediastate);
9259 
9260 	/*
9261 	 * now signal the waiting thread if this is *not* the specified state;
9262 	 * delay the signal if the state is MTIO_INSERTED
9263 	 * to allow the target to recover
9264 	 */
9265 	if (state != un->un_specified_mediastate) {
9266 		un->un_mediastate = state;
9267 		if (state == MTIO_INSERTED) {
9268 			/*
9269 			 * delay the signal to give the drive a chance
9270 			 * to do what it apparently needs to do
9271 			 */
9272 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9273 			    "st_media_watch_cb:delayed cv_broadcast\n");
9274 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
9275 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
9276 		} else {
9277 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9278 			    "st_media_watch_cb:immediate cv_broadcast\n");
9279 			cv_broadcast(&un->un_state_cv);
9280 		}
9281 	}
9282 	mutex_exit(ST_MUTEX);
9283 	return (0);
9284 }
9285 
9286 /*
9287  * delayed cv_broadcast to allow for target to recover
9288  * from media insertion
9289  */
9290 static void
9291 st_delayed_cv_broadcast(void *arg)
9292 {
9293 	struct scsi_tape *un = arg;
9294 
9295 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
9296 
9297 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9298 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
9299 
9300 	mutex_enter(ST_MUTEX);
9301 	cv_broadcast(&un->un_state_cv);
9302 	mutex_exit(ST_MUTEX);
9303 }
9304 
9305 /*
9306  * restart cmd currently at the start of the waitq
9307  */
9308 static void
9309 st_start_restart(void *arg)
9310 {
9311 	struct scsi_tape *un = arg;
9312 
9313 	ST_FUNC(ST_DEVINFO, st_start_restart);
9314 
9315 	ASSERT(un != NULL);
9316 
9317 	mutex_enter(ST_MUTEX);
9318 
9319 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_tran_restart()\n");
9320 
9321 	st_start(un);
9322 
9323 	mutex_exit(ST_MUTEX);
9324 }
9325 
9326 
9327 /*
9328  * Command completion processing
9329  *
9330  */
9331 static void
9332 st_intr(struct scsi_pkt *pkt)
9333 {
9334 	recov_info *rcv = pkt->pkt_private;
9335 	struct buf *bp = rcv->cmd_bp;
9336 	struct scsi_tape *un;
9337 	errstate action = COMMAND_DONE;
9338 	clock_t	timout;
9339 	int	status;
9340 
9341 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
9342 
9343 	ST_FUNC(ST_DEVINFO, st_intr);
9344 
9345 	ASSERT(un != NULL);
9346 
9347 	mutex_enter(ST_MUTEX);
9348 
9349 	ASSERT(bp != un->un_recov_buf);
9350 
9351 	un->un_rqs_state &= ~(ST_RQS_ERROR);
9352 
9353 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
9354 
9355 	if (pkt->pkt_reason != CMD_CMPLT) {
9356 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9357 		    "Unhappy packet status reason = %s statistics = 0x%x\n",
9358 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9359 
9360 		/* If device has gone away not much else to do */
9361 		if (pkt->pkt_reason == CMD_DEV_GONE) {
9362 			action = COMMAND_DONE_ERROR;
9363 		} else if ((pkt == un->un_rqs) ||
9364 		    (un->un_state == ST_STATE_SENSING)) {
9365 			ASSERT(pkt == un->un_rqs);
9366 			ASSERT(un->un_state == ST_STATE_SENSING);
9367 			un->un_state = un->un_laststate;
9368 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp =
9369 			    un->un_rqs_bp;
9370 			ST_DO_ERRSTATS(un, st_transerrs);
9371 			action = COMMAND_DONE_ERROR;
9372 		} else {
9373 			action = st_handle_incomplete(un, bp);
9374 		}
9375 	/*
9376 	 * At this point we know that the command was successfully
9377 	 * completed. Now what?
9378 	 */
9379 	} else if ((pkt == un->un_rqs) || (un->un_state == ST_STATE_SENSING)) {
9380 		/*
9381 		 * okay. We were running a REQUEST SENSE. Find
9382 		 * out what to do next.
9383 		 */
9384 		ASSERT(pkt == un->un_rqs);
9385 		ASSERT(un->un_state == ST_STATE_SENSING);
9386 		scsi_sync_pkt(pkt);
9387 		action = st_handle_sense(un, bp, &un->un_pos);
9388 		/*
9389 		 * Make rqs isn't going to be retied.
9390 		 */
9391 		if (action != QUE_BUSY_COMMAND && action != QUE_COMMAND) {
9392 			/*
9393 			 * set pkt back to original packet in case we will have
9394 			 * to requeue it
9395 			 */
9396 			pkt = BP_PKT(bp);
9397 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp =
9398 			    un->un_rqs_bp;
9399 			/*
9400 			 * some actions are based on un_state, hence
9401 			 * restore the state st was in before ST_STATE_SENSING.
9402 			 */
9403 			un->un_state = un->un_laststate;
9404 		}
9405 
9406 	} else if (un->un_arq_enabled && (pkt->pkt_state & STATE_ARQ_DONE)) {
9407 		/*
9408 		 * the transport layer successfully completed an autorqsense
9409 		 */
9410 		action = st_handle_autosense(un, bp, &un->un_pos);
9411 
9412 	} else  if ((SCBP(pkt)->sts_busy) ||
9413 	    (SCBP(pkt)->sts_chk) ||
9414 	    (SCBP(pkt)->sts_vu7)) {
9415 		/*
9416 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9417 		 * to see if the status bits we're okay. If a request sense
9418 		 * is to be run, that will happen.
9419 		 */
9420 		action = st_check_error(un, pkt);
9421 	}
9422 
9423 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9424 		switch (action) {
9425 			case QUE_COMMAND:
9426 				/*
9427 				 * return cmd to head to the queue
9428 				 * since we are suspending so that
9429 				 * it gets restarted during resume
9430 				 */
9431 				st_add_to_queue(&un->un_runqf, &un->un_runql,
9432 				    un->un_runqf, bp);
9433 
9434 				action = JUST_RETURN;
9435 				break;
9436 
9437 			case QUE_SENSE:
9438 				action = COMMAND_DONE_ERROR;
9439 				break;
9440 
9441 			default:
9442 				break;
9443 		}
9444 	}
9445 
9446 	/*
9447 	 * Restore old state if we were sensing.
9448 	 */
9449 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9450 		un->un_state = un->un_laststate;
9451 	}
9452 
9453 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9454 	    "st_intr: pkt=%p, bp=%p, action=%x, status=%x\n",
9455 	    (void *)pkt, (void *)bp, action, SCBP_C(pkt));
9456 
9457 again:
9458 	switch (action) {
9459 	case COMMAND_DONE_EACCES:
9460 		/* this is to report a reservation conflict */
9461 		st_bioerror(bp, EACCES);
9462 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9463 		    "Reservation Conflict \n");
9464 		un->un_pos.pmode = invalid;
9465 
9466 		/*FALLTHROUGH*/
9467 	case COMMAND_DONE_ERROR:
9468 		if (un->un_pos.eof < ST_EOT_PENDING &&
9469 		    un->un_state >= ST_STATE_OPEN) {
9470 			/*
9471 			 * all errors set state of the tape to 'unknown'
9472 			 * unless we're at EOT or are doing append testing.
9473 			 * If sense key was illegal request, preserve state.
9474 			 */
9475 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9476 				un->un_pos.pmode = invalid;
9477 			}
9478 		}
9479 
9480 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9481 		/*
9482 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9483 		 * make sure an error ocurrs, so make sure at least EIO is
9484 		 * returned
9485 		 */
9486 		if (geterror(bp) == 0)
9487 			st_bioerror(bp, EIO);
9488 
9489 		st_set_pe_flag(un);
9490 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9491 		    (un->un_errno == EIO)) {
9492 			un->un_rqs_state &= ~(ST_RQS_VALID);
9493 		}
9494 		break;
9495 
9496 	case COMMAND_DONE_ERROR_RECOVERED:
9497 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9498 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9499 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9500 		if (geterror(bp) == 0) {
9501 			st_bioerror(bp, EIO);
9502 		}
9503 		st_set_pe_flag(un);
9504 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9505 		    (un->un_errno == EIO)) {
9506 			un->un_rqs_state &= ~(ST_RQS_VALID);
9507 		}
9508 		/*FALLTHROUGH*/
9509 	case COMMAND_DONE:
9510 		st_set_state(un, bp);
9511 		break;
9512 
9513 	case QUE_SENSE:
9514 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9515 			goto sense_error;
9516 
9517 		if (un->un_state != ST_STATE_SENSING) {
9518 			un->un_laststate = un->un_state;
9519 			un->un_state = ST_STATE_SENSING;
9520 		}
9521 
9522 		/*
9523 		 * zero the sense data.
9524 		 */
9525 		bzero(un->un_rqs->pkt_scbp, SENSE_LENGTH);
9526 
9527 		/*
9528 		 * If this is not a retry on QUE_SENSE point to the original
9529 		 * bp of the command that got us here.
9530 		 */
9531 		if (pkt != un->un_rqs) {
9532 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp = bp;
9533 		}
9534 
9535 		if (un->un_throttle) {
9536 			un->un_last_throttle = un->un_throttle;
9537 			un->un_throttle = 0;
9538 		}
9539 
9540 		ST_CDB(ST_DEVINFO, "Queue sense CDB",
9541 		    (char *)BP_PKT(bp)->pkt_cdbp);
9542 
9543 		/*
9544 		 * never retry this, some other command will have nuked the
9545 		 * sense, anyway
9546 		 */
9547 		status = st_transport(un, un->un_rqs);
9548 
9549 		if (un->un_last_throttle) {
9550 			un->un_throttle = un->un_last_throttle;
9551 		}
9552 
9553 		if (status == TRAN_ACCEPT) {
9554 			mutex_exit(ST_MUTEX);
9555 			return;
9556 		}
9557 		if (status != TRAN_BUSY)
9558 			ST_DO_ERRSTATS(un, st_transerrs);
9559 sense_error:
9560 		un->un_pos.pmode = invalid;
9561 		st_bioerror(bp, EIO);
9562 		st_set_pe_flag(un);
9563 		break;
9564 
9565 	case QUE_BUSY_COMMAND:
9566 		/* longish timeout */
9567 		timout = ST_STATUS_BUSY_TIMEOUT;
9568 		goto que_it_up;
9569 
9570 	case QUE_COMMAND:
9571 		/* short timeout */
9572 		timout = ST_TRAN_BUSY_TIMEOUT;
9573 que_it_up:
9574 		/*
9575 		 * let st_handle_intr_busy put this bp back on waitq and make
9576 		 * checks to see if it is ok to requeue the command.
9577 		 */
9578 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9579 
9580 		/*
9581 		 * Save the throttle before setting up the timeout
9582 		 */
9583 		if (un->un_throttle) {
9584 			un->un_last_throttle = un->un_throttle;
9585 		}
9586 		mutex_exit(ST_MUTEX);
9587 		if (st_handle_intr_busy(un, bp, timout) == 0)
9588 			return;		/* timeout is setup again */
9589 
9590 		mutex_enter(ST_MUTEX);
9591 		un->un_pos.pmode = invalid;
9592 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9593 		st_bioerror(bp, EIO);
9594 		st_set_pe_flag(un);
9595 		break;
9596 
9597 	case QUE_LAST_COMMAND:
9598 
9599 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9600 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9601 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9602 			goto last_command_error;
9603 		}
9604 		mutex_exit(ST_MUTEX);
9605 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9606 			return;
9607 		mutex_enter(ST_MUTEX);
9608 last_command_error:
9609 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9610 		un->un_pos.pmode = invalid;
9611 		st_bioerror(bp, EIO);
9612 		st_set_pe_flag(un);
9613 		break;
9614 
9615 	case COMMAND_TIMEOUT:
9616 	case DEVICE_RESET:
9617 	case DEVICE_TAMPER:
9618 	case ATTEMPT_RETRY:
9619 		action = st_command_recovery(un, pkt, action);
9620 		goto again;
9621 
9622 	default:
9623 		ASSERT(0);
9624 		/* FALLTHRU */
9625 	case JUST_RETURN:
9626 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9627 		mutex_exit(ST_MUTEX);
9628 		return;
9629 	}
9630 
9631 	ST_DO_KSTATS(bp, kstat_runq_exit);
9632 	st_done_and_mutex_exit(un, bp);
9633 }
9634 
9635 static errstate
9636 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9637 {
9638 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9639 	recov_info *rinfo;
9640 	errstate rval = COMMAND_DONE_ERROR;
9641 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9642 	    un->un_rqs : BP_PKT(bp);
9643 	int result;
9644 
9645 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9646 
9647 	rinfo = (recov_info *)pkt->pkt_private;
9648 
9649 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9650 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9651 
9652 	ASSERT(mutex_owned(ST_MUTEX));
9653 
9654 	switch (pkt->pkt_reason) {
9655 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9656 		/*
9657 		 * this occurs when accessing a powered down drive, no
9658 		 * need to complain; just fail the open
9659 		 */
9660 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9661 
9662 		/*
9663 		 * if we have commands outstanding in HBA, and a command
9664 		 * comes back incomplete, we're hosed, so reset target
9665 		 * If we have the bus, but cmd_incomplete, we probably just
9666 		 * have a failed selection, so don't reset the target, just
9667 		 * requeue the command and try again
9668 		 */
9669 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9670 			goto reset_target;
9671 		}
9672 
9673 		/*
9674 		 * Retry selection a couple more times if we're
9675 		 * open.  If opening, we only try just once to
9676 		 * reduce probe time for nonexistant devices.
9677 		 */
9678 		if ((un->un_laststate > ST_STATE_OPENING) &&
9679 		    ((int)un->un_retry_ct < st_selection_retry_count)) {
9680 /* XXX check retriable? */
9681 			rval = QUE_COMMAND;
9682 		}
9683 		ST_DO_ERRSTATS(un, st_transerrs);
9684 		break;
9685 
9686 	case CMD_ABORTED:
9687 		/*
9688 		 * most likely this is caused by flush-on-error support. If
9689 		 * it was not there, the we're in trouble.
9690 		 */
9691 		if (!un->un_flush_on_errors) {
9692 			un->un_status = SUN_KEY_FATAL;
9693 			goto reset_target;
9694 		}
9695 
9696 		st_set_pe_errno(un);
9697 		bioerror(bp, un->un_errno);
9698 		if (un->un_errno)
9699 			return (COMMAND_DONE_ERROR);
9700 		else
9701 			return (COMMAND_DONE);
9702 
9703 	case CMD_TIMEOUT:	/* Command timed out */
9704 		un->un_status = SUN_KEY_TIMEOUT;
9705 		return (COMMAND_TIMEOUT);
9706 
9707 	case CMD_TRAN_ERR:
9708 	case CMD_RESET:
9709 		if (pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET)) {
9710 			if ((un->un_rsvd_status &
9711 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
9712 			    ST_RESERVE) {
9713 				un->un_rsvd_status |= ST_LOST_RESERVE;
9714 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
9715 				    "Lost Reservation\n");
9716 			}
9717 			rval = DEVICE_RESET;
9718 			return (rval);
9719 		}
9720 		if (pkt->pkt_statistics & (STAT_ABORTED | STAT_TERMINATED)) {
9721 			rval = DEVICE_RESET;
9722 			return (rval);
9723 		}
9724 		/*FALLTHROUGH*/
9725 	default:
9726 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9727 		    "Unhandled packet status reason = %s statistics = 0x%x\n",
9728 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9729 reset_target:
9730 
9731 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9732 		    "transport completed with %s\n",
9733 		    scsi_rname(pkt->pkt_reason));
9734 		ST_DO_ERRSTATS(un, st_transerrs);
9735 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
9736 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
9737 		    STAT_ABORTED)) == 0)) {
9738 
9739 			/*
9740 			 * If we haven't reserved the drive don't reset it.
9741 			 */
9742 			if ((un->un_rsvd_status &
9743 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9744 				return (rval);
9745 			}
9746 
9747 			/*
9748 			 * if we aren't lost yet we will be soon.
9749 			 */
9750 			un->un_pos.pmode = invalid;
9751 
9752 			result = st_reset(un, RESET_LUN);
9753 
9754 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
9755 				/* no hope left to recover */
9756 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
9757 				    "recovery by resets failed\n");
9758 				return (rval);
9759 			}
9760 		}
9761 	}
9762 
9763 
9764 	if ((int)un->un_retry_ct++ < st_retry_count) {
9765 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9766 			rval = QUE_COMMAND;
9767 		} else if (bp == un->un_sbufp) {
9768 			if (rinfo->privatelen == sizeof (recov_info)) {
9769 				if (rinfo->cmd_attrib->retriable) {
9770 					/*
9771 					 * These commands can be rerun
9772 					 * with impunity
9773 					 */
9774 					rval = QUE_COMMAND;
9775 				}
9776 			} else {
9777 				cmd_attribute const *attrib;
9778 				attrib =
9779 				    st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
9780 				if (attrib->retriable) {
9781 					rval = QUE_COMMAND;
9782 				}
9783 			}
9784 		}
9785 	} else {
9786 		rval = COMMAND_DONE_ERROR;
9787 	}
9788 
9789 	if (un->un_state >= ST_STATE_OPEN) {
9790 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9791 		    fail, scsi_rname(pkt->pkt_reason),
9792 		    (rval == COMMAND_DONE_ERROR)?
9793 		    "giving up" : "retrying command");
9794 	}
9795 	return (rval);
9796 }
9797 
9798 /*
9799  * if the device is busy, then put this bp back on the waitq, on the
9800  * interrupt thread, where we want the head of the queue and not the
9801  * end
9802  *
9803  * The callers of this routine should take measures to save the
9804  * un_throttle in un_last_throttle which will be restored in
9805  * st_intr_restart(). The only exception should be st_intr_restart()
9806  * calling this routine for which the saving is already done.
9807  */
9808 static int
9809 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
9810 	clock_t timeout_interval)
9811 {
9812 
9813 	int queued;
9814 	int rval = 0;
9815 
9816 	mutex_enter(ST_MUTEX);
9817 
9818 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
9819 
9820 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9821 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
9822 
9823 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
9824 		queued = 1;
9825 	} else {
9826 		queued = 0;
9827 	}
9828 
9829 	/*
9830 	 * Check to see if we hit the retry timeout. We check to make sure
9831 	 * this is the first one on the runq and make sure we have not
9832 	 * queued up any more, so this one has to be the last on the list
9833 	 * also. If it is not, we have to fail.  If it is not the first, but
9834 	 * is the last we are in trouble anyway, as we are in the interrupt
9835 	 * context here.
9836 	 */
9837 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
9838 	    ((un->un_runqf != bp) && (un->un_runql != bp) && (queued))) {
9839 		rval = -1;
9840 		goto exit;
9841 	}
9842 
9843 	/* put the bp back on the waitq */
9844 	if (queued) {
9845 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
9846 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
9847 	}
9848 
9849 	/*
9850 	 * We don't want any other commands being started in the mean time.
9851 	 * If start had just released mutex after putting something on the
9852 	 * runq, we won't even get here.
9853 	 */
9854 	un->un_throttle = 0;
9855 
9856 	/*
9857 	 * send a marker pkt, if appropriate
9858 	 */
9859 	st_hba_unflush(un);
9860 
9861 	/*
9862 	 * all queues are aligned, we are just waiting to
9863 	 * transport
9864 	 */
9865 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
9866 
9867 exit:
9868 	mutex_exit(ST_MUTEX);
9869 	return (rval);
9870 }
9871 
9872 /*
9873  * To get one error entry from error stack
9874  */
9875 static int
9876 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
9877 {
9878 #ifdef _MULTI_DATAMODEL
9879 	/*
9880 	 * For use when a 32 bit app makes a call into a
9881 	 * 64 bit ioctl
9882 	 */
9883 	struct mterror_entry32 err_entry32;
9884 #endif /* _MULTI_DATAMODEL */
9885 
9886 	int rval = 0;
9887 	struct mterror_entry err_entry;
9888 	struct mterror_entry_stack *err_link_entry_p;
9889 	size_t arq_status_len_in, arq_status_len_kr;
9890 
9891 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
9892 
9893 	ASSERT(mutex_owned(ST_MUTEX));
9894 
9895 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9896 	    "st_get_error_entry()\n");
9897 
9898 	/*
9899 	 * if error record stack empty, return ENXIO
9900 	 */
9901 	if (un->un_error_entry_stk == NULL) {
9902 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9903 		    "st_get_error_entry: Error Entry Stack Empty!\n");
9904 		rval = ENXIO;
9905 		goto ret;
9906 	}
9907 
9908 	/*
9909 	 * get the top entry from stack
9910 	 */
9911 	err_link_entry_p = un->un_error_entry_stk;
9912 	arq_status_len_kr =
9913 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
9914 
9915 #ifdef _MULTI_DATAMODEL
9916 	switch (ddi_model_convert_from(flag & FMODELS)) {
9917 	case DDI_MODEL_ILP32:
9918 		if (ddi_copyin((void *)arg, &err_entry32,
9919 		    MTERROR_ENTRY_SIZE_32, flag)) {
9920 			rval = EFAULT;
9921 			goto ret;
9922 		}
9923 
9924 		arq_status_len_in =
9925 		    (size_t)err_entry32.mtee_arq_status_len;
9926 
9927 		err_entry32.mtee_cdb_len =
9928 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
9929 
9930 		if (arq_status_len_in > arq_status_len_kr)
9931 			err_entry32.mtee_arq_status_len =
9932 			    (size32_t)arq_status_len_kr;
9933 
9934 		if (ddi_copyout(
9935 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
9936 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
9937 		    err_entry32.mtee_cdb_len, flag)) {
9938 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9939 			    "st_get_error_entry: Copy cdb buffer error!");
9940 			rval = EFAULT;
9941 		}
9942 
9943 		if (ddi_copyout(
9944 		    err_link_entry_p->mtees_entry.mtee_arq_status,
9945 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
9946 		    err_entry32.mtee_arq_status_len, flag)) {
9947 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9948 			    "st_get_error_entry: copy arq status error!");
9949 			rval = EFAULT;
9950 		}
9951 
9952 		if (ddi_copyout(&err_entry32, (void *)arg,
9953 		    MTERROR_ENTRY_SIZE_32, flag)) {
9954 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9955 			    "st_get_error_entry: copy arq status out error!");
9956 			rval = EFAULT;
9957 		}
9958 		break;
9959 
9960 	case DDI_MODEL_NONE:
9961 		if (ddi_copyin((void *)arg, &err_entry,
9962 		    MTERROR_ENTRY_SIZE_64, flag)) {
9963 			rval = EFAULT;
9964 			goto ret;
9965 		}
9966 		arq_status_len_in = err_entry.mtee_arq_status_len;
9967 
9968 		err_entry.mtee_cdb_len =
9969 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
9970 
9971 		if (arq_status_len_in > arq_status_len_kr)
9972 			err_entry.mtee_arq_status_len =
9973 			    arq_status_len_kr;
9974 
9975 		if (ddi_copyout(
9976 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
9977 		    err_entry.mtee_cdb_buf,
9978 		    err_entry.mtee_cdb_len, flag)) {
9979 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9980 			    "st_get_error_entry: Copy cdb buffer error!");
9981 			rval = EFAULT;
9982 		}
9983 
9984 		if (ddi_copyout(
9985 		    err_link_entry_p->mtees_entry.mtee_arq_status,
9986 		    err_entry.mtee_arq_status,
9987 		    err_entry.mtee_arq_status_len, flag)) {
9988 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9989 			    "st_get_error_entry: copy arq status error!");
9990 			rval = EFAULT;
9991 		}
9992 
9993 		if (ddi_copyout(&err_entry, (void *)arg,
9994 		    MTERROR_ENTRY_SIZE_64, flag)) {
9995 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9996 			    "st_get_error_entry: copy arq status out error!");
9997 			rval = EFAULT;
9998 		}
9999 		break;
10000 	}
10001 #else /* _MULTI_DATAMODEL */
10002 	if (ddi_copyin((void *)arg, &err_entry,
10003 	    MTERROR_ENTRY_SIZE_64, flag)) {
10004 		rval = EFAULT;
10005 		goto ret;
10006 	}
10007 	arq_status_len_in = err_entry.mtee_arq_status_len;
10008 
10009 	err_entry.mtee_cdb_len =
10010 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
10011 
10012 	if (arq_status_len_in > arq_status_len_kr)
10013 		err_entry.mtee_arq_status_len =
10014 		    arq_status_len_kr;
10015 
10016 	if (ddi_copyout(
10017 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10018 	    err_entry.mtee_cdb_buf,
10019 	    err_entry.mtee_cdb_len, flag)) {
10020 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10021 		    "st_get_error_entry: Copy cdb buffer error!");
10022 		rval = EFAULT;
10023 	}
10024 
10025 	if (ddi_copyout(
10026 	    err_link_entry_p->mtees_entry.mtee_arq_status,
10027 	    err_entry.mtee_arq_status,
10028 	    err_entry.mtee_arq_status_len, flag)) {
10029 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10030 		    "st_get_error_entry: copy arq status buffer error!");
10031 		rval = EFAULT;
10032 	}
10033 
10034 	if (ddi_copyout(&err_entry, (void *)arg,
10035 	    MTERROR_ENTRY_SIZE_64, flag)) {
10036 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10037 		    "st_get_error_entry: copy arq status out error!");
10038 		rval = EFAULT;
10039 	}
10040 #endif /* _MULTI_DATAMODEL */
10041 
10042 	/*
10043 	 * update stack
10044 	 */
10045 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
10046 
10047 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
10048 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
10049 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
10050 
10051 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
10052 	    SECMDS_STATUS_SIZE);
10053 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
10054 
10055 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
10056 	err_link_entry_p = NULL;
10057 ret:
10058 	return (rval);
10059 }
10060 
10061 /*
10062  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
10063  * the scsi CDB command which causes the error and generates sense data and
10064  * the scsi status.
10065  *
10066  *      error-record stack
10067  *
10068  *
10069  *             TOP                                     BOTTOM
10070  *              ------------------------------------------
10071  *              |   0   |   1   |   2   |   ...  |   n   |
10072  *              ------------------------------------------
10073  *                  ^
10074  *                  |
10075  *       pointer to error entry
10076  *
10077  * when st driver generates one sense data record, it creates a error-entry
10078  * and pushes it onto the stack.
10079  *
10080  */
10081 
10082 static void
10083 st_update_error_stack(struct scsi_tape *un,
10084 			struct scsi_pkt *pkt,
10085 			struct scsi_arq_status *cmd)
10086 {
10087 	struct mterror_entry_stack *err_entry_tmp;
10088 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
10089 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
10090 
10091 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
10092 
10093 	ASSERT(mutex_owned(ST_MUTEX));
10094 
10095 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10096 	    "st_update_error_stack()\n");
10097 
10098 	ASSERT(cmd);
10099 	ASSERT(cdbp);
10100 	if (cdblen == 0) {
10101 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10102 		    "st_update_error_stack: CDB length error!\n");
10103 		return;
10104 	}
10105 
10106 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
10107 	ASSERT(err_entry_tmp != NULL);
10108 
10109 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
10110 	    kmem_alloc(cdblen, KM_SLEEP);
10111 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
10112 
10113 	err_entry_tmp->mtees_entry.mtee_arq_status =
10114 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
10115 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
10116 
10117 	/*
10118 	 * copy cdb command & length to current error entry
10119 	 */
10120 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
10121 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
10122 
10123 	/*
10124 	 * copy scsi status length to current error entry
10125 	 */
10126 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
10127 	    SECMDS_STATUS_SIZE;
10128 
10129 	/*
10130 	 * copy sense data and scsi status to current error entry
10131 	 */
10132 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
10133 	    SECMDS_STATUS_SIZE);
10134 
10135 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
10136 	un->un_error_entry_stk = err_entry_tmp;
10137 
10138 }
10139 
10140 /*
10141  * Empty all the error entry in stack
10142  */
10143 static void
10144 st_empty_error_stack(struct scsi_tape *un)
10145 {
10146 	struct mterror_entry_stack *linkp;
10147 
10148 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
10149 
10150 	ASSERT(mutex_owned(ST_MUTEX));
10151 
10152 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10153 	    "st_empty_entry_stack()\n");
10154 
10155 	while (un->un_error_entry_stk != NULL) {
10156 		linkp = un->un_error_entry_stk;
10157 		un->un_error_entry_stk =
10158 		    un->un_error_entry_stk->mtees_nextp;
10159 
10160 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
10161 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
10162 			    linkp->mtees_entry.mtee_cdb_len);
10163 
10164 		if (linkp->mtees_entry.mtee_arq_status != NULL)
10165 			kmem_free(linkp->mtees_entry.mtee_arq_status,
10166 			    linkp->mtees_entry.mtee_arq_status_len);
10167 
10168 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
10169 		linkp = NULL;
10170 	}
10171 }
10172 
10173 static errstate
10174 st_handle_sense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10175 {
10176 	struct scsi_pkt *pkt = BP_PKT(bp);
10177 	struct scsi_pkt *rqpkt = un->un_rqs;
10178 	struct scsi_arq_status arqstat;
10179 
10180 	errstate rval = COMMAND_DONE_ERROR;
10181 	int amt;
10182 
10183 	ST_FUNC(ST_DEVINFO, st_handle_sense);
10184 
10185 	ASSERT(mutex_owned(ST_MUTEX));
10186 
10187 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10188 	    "st_handle_sense()\n");
10189 
10190 	if (SCBP(rqpkt)->sts_busy) {
10191 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10192 		    "busy unit on request sense\n");
10193 		if ((int)un->un_retry_ct++ < st_retry_count) {
10194 			rval = QUE_BUSY_COMMAND;
10195 		}
10196 		return (rval);
10197 	} else if (SCBP(rqpkt)->sts_chk) {
10198 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10199 		    "Check Condition on REQUEST SENSE\n");
10200 		return (rval);
10201 	}
10202 
10203 	/* was there enough data? */
10204 	amt = (int)MAX_SENSE_LENGTH - rqpkt->pkt_resid;
10205 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
10206 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10207 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10208 		    "REQUEST SENSE couldn't get sense data\n");
10209 		return (rval);
10210 	}
10211 
10212 	bcopy(SCBP(pkt), &arqstat.sts_status,
10213 	    sizeof (struct scsi_status));
10214 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
10215 	    sizeof (struct scsi_status));
10216 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
10217 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
10218 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
10219 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
10220 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
10221 
10222 	/*
10223 	 * copy one arqstat entry in the sense data buffer
10224 	 */
10225 	st_update_error_stack(un, pkt, &arqstat);
10226 	return (st_decode_sense(un, bp, amt, SCBP(rqpkt), pos));
10227 }
10228 
10229 static errstate
10230 st_handle_autosense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10231 {
10232 	struct scsi_pkt *pkt = BP_PKT(bp);
10233 	struct scsi_arq_status *arqstat =
10234 	    (struct scsi_arq_status *)pkt->pkt_scbp;
10235 	errstate rval = COMMAND_DONE_ERROR;
10236 	int amt;
10237 
10238 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
10239 
10240 	ASSERT(mutex_owned(ST_MUTEX));
10241 
10242 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10243 	    "st_handle_autosense()\n");
10244 
10245 	if (arqstat->sts_rqpkt_status.sts_busy) {
10246 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10247 		    "busy unit on request sense\n");
10248 		/*
10249 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
10250 		 * the disadvantage is that we do not have any delay for the
10251 		 * second retry of rqsense and we have to keep a packet around
10252 		 */
10253 		return (QUE_SENSE);
10254 
10255 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
10256 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10257 		    "transport error on REQUEST SENSE\n");
10258 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
10259 		    ((arqstat->sts_rqpkt_statistics &
10260 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
10261 			if (st_reset(un, RESET_LUN) == 0) {
10262 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10263 				    "recovery by resets failed\n");
10264 			}
10265 		}
10266 		return (rval);
10267 
10268 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
10269 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10270 		    "Check Condition on REQUEST SENSE\n");
10271 		return (rval);
10272 	}
10273 
10274 
10275 	/* was there enough data? */
10276 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10277 		amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10278 	} else {
10279 		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
10280 			amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10281 		} else {
10282 			amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10283 		}
10284 	}
10285 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
10286 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10287 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10288 		    "REQUEST SENSE couldn't get sense data\n");
10289 		return (rval);
10290 	}
10291 
10292 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10293 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, MAX_SENSE_LENGTH);
10294 	} else {
10295 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
10296 	}
10297 
10298 	/*
10299 	 * copy one arqstat entry in the sense data buffer
10300 	 */
10301 	st_update_error_stack(un, pkt, arqstat);
10302 
10303 	return (st_decode_sense(un, bp, amt, &arqstat->sts_rqpkt_status, pos));
10304 }
10305 
10306 static errstate
10307 st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
10308     struct scsi_status *statusp, tapepos_t *pos)
10309 {
10310 	struct scsi_pkt *pkt = BP_PKT(bp);
10311 	recov_info *ri = (recov_info *)pkt->pkt_private;
10312 	errstate rval = COMMAND_DONE_ERROR;
10313 	cmd_attribute const *attrib;
10314 	long resid;
10315 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10316 	int severity;
10317 	int get_error;
10318 
10319 	ST_FUNC(ST_DEVINFO, st_decode_sense);
10320 
10321 	ASSERT(mutex_owned(ST_MUTEX));
10322 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10323 	    "st_decode_sense()\n");
10324 
10325 	/*
10326 	 * For uscsi commands, squirrel away a copy of the
10327 	 * results of the Request Sense.
10328 	 */
10329 	if (USCSI_CMD(bp)) {
10330 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
10331 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
10332 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
10333 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
10334 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
10335 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
10336 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10337 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
10338 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
10339 		}
10340 	}
10341 
10342 	if (ri->privatelen == sizeof (recov_info)) {
10343 		attrib = ri->cmd_attrib;
10344 	} else {
10345 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10346 	}
10347 
10348 	/*
10349 	 * If the drive is an MT-02, reposition the
10350 	 * secondary error code into the proper place.
10351 	 *
10352 	 * XXX	MT-02 is non-CCS tape, so secondary error code
10353 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
10354 	 * so it's in byte 12.
10355 	 */
10356 	if (un->un_dp->type == ST_TYPE_EMULEX) {
10357 		sensep->es_code = sensep->es_add_info[0];
10358 	}
10359 
10360 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
10361 	    (caddr_t)&CDBP(pkt)->scc_cmd);
10362 
10363 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)sensep,
10364 	    sizeof (*sensep));
10365 
10366 	/* for normal I/O check extract the resid values. */
10367 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
10368 		if (sensep->es_valid) {
10369 			resid =
10370 			    (sensep->es_info_1 << 24) |
10371 			    (sensep->es_info_2 << 16) |
10372 			    (sensep->es_info_3 << 8)  |
10373 			    (sensep->es_info_4);
10374 			/* If fixed block */
10375 			if (un->un_bsize) {
10376 				resid *= un->un_bsize;
10377 			}
10378 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
10379 			resid = pkt->pkt_resid;
10380 		} else {
10381 			resid = bp->b_bcount;
10382 		}
10383 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10384 		    "st_decode_sense (rw): xferred bit = %d, resid=%ld (%d), "
10385 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
10386 		    resid,
10387 		    (sensep->es_info_1 << 24) |
10388 		    (sensep->es_info_2 << 16) |
10389 		    (sensep->es_info_3 << 8)  |
10390 		    (sensep->es_info_4),
10391 		    pkt->pkt_resid);
10392 		/*
10393 		 * The problem is, what should we believe?
10394 		 */
10395 		if (resid && (pkt->pkt_resid == 0)) {
10396 			pkt->pkt_resid = resid;
10397 		}
10398 	} else {
10399 		/*
10400 		 * If the command is SCMD_SPACE, we need to get the
10401 		 * residual as returned in the sense data, to adjust
10402 		 * our idea of current tape position correctly
10403 		 */
10404 		if ((sensep->es_valid) &&
10405 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10406 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10407 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
10408 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK)) {
10409 			resid =
10410 			    (sensep->es_info_1 << 24) |
10411 			    (sensep->es_info_2 << 16) |
10412 			    (sensep->es_info_3 << 8)  |
10413 			    (sensep->es_info_4);
10414 			bp->b_resid = resid;
10415 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10416 			    "st_decode_sense(other):	resid=%ld\n", resid);
10417 		} else {
10418 			/*
10419 			 * If the special command is SCMD_READ,
10420 			 * the correct resid will be set later.
10421 			 */
10422 			if (attrib->get_cnt != NULL) {
10423 				resid = attrib->get_cnt(pkt->pkt_cdbp);
10424 			} else {
10425 				resid = bp->b_bcount;
10426 			}
10427 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10428 			    "st_decode_sense(special read):  resid=%ld\n",
10429 			    resid);
10430 		}
10431 	}
10432 
10433 	if ((un->un_state >= ST_STATE_OPEN) &&
10434 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
10435 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
10436 		    "Failed CDB", (char *)pkt->pkt_cdbp);
10437 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10438 		    "sense data", (char *)sensep, amt);
10439 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10440 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10441 		    bp->b_bcount, resid, pkt->pkt_resid);
10442 	}
10443 
10444 	switch (un->un_status = sensep->es_key) {
10445 	case KEY_NO_SENSE:
10446 		severity = SCSI_ERR_INFO;
10447 
10448 		/*
10449 		 * Erase, locate or rewind operation in progress, retry
10450 		 * ASC  ASCQ
10451 		 *  00   18    Erase operation in progress
10452 		 *  00   19    Locate operation in progress
10453 		 *  00   1A    Rewind operation in progress
10454 		 */
10455 		if (sensep->es_add_code == 0 &&
10456 		    ((sensep->es_qual_code == 0x18) ||
10457 		    (sensep->es_qual_code == 0x19) ||
10458 		    (sensep->es_qual_code == 0x1a))) {
10459 			rval = QUE_BUSY_COMMAND;
10460 			break;
10461 		}
10462 
10463 		goto common;
10464 
10465 	case KEY_RECOVERABLE_ERROR:
10466 		severity = SCSI_ERR_RECOVERED;
10467 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10468 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10469 			if (un->un_dp->options &
10470 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10471 				rval = QUE_LAST_COMMAND;
10472 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10473 				    severity, pos->lgclblkno,
10474 				    un->un_err_pos.lgclblkno, scsi_cmds,
10475 				    sensep);
10476 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10477 				    "Command will be retried\n");
10478 			} else {
10479 				severity = SCSI_ERR_FATAL;
10480 				rval = COMMAND_DONE_ERROR_RECOVERED;
10481 				ST_DO_ERRSTATS(un, st_softerrs);
10482 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10483 				    severity, pos->lgclblkno,
10484 				    un->un_err_pos.lgclblkno, scsi_cmds,
10485 				    sensep);
10486 			}
10487 			break;
10488 		}
10489 common:
10490 		/*
10491 		 * XXX only want reads to be stopped by filemarks.
10492 		 * Don't want them to be stopped by EOT.  EOT matters
10493 		 * only on write.
10494 		 */
10495 		if (sensep->es_filmk && !sensep->es_eom) {
10496 			rval = COMMAND_DONE;
10497 		} else if (sensep->es_eom) {
10498 			rval = COMMAND_DONE;
10499 		} else if (sensep->es_ili) {
10500 			/*
10501 			 * Fun with variable length record devices:
10502 			 * for specifying larger blocks sizes than the
10503 			 * actual physical record size.
10504 			 */
10505 			if (un->un_bsize == 0 && resid > 0) {
10506 				/*
10507 				 * XXX! Ugly.
10508 				 * The requested blocksize is > tape blocksize,
10509 				 * so this is ok, so we just return the
10510 				 * actual size xferred.
10511 				 */
10512 				pkt->pkt_resid = resid;
10513 				rval = COMMAND_DONE;
10514 			} else if (un->un_bsize == 0 && resid < 0) {
10515 				/*
10516 				 * The requested blocksize is < tape blocksize,
10517 				 * so this is not ok, so we err with ENOMEM
10518 				 */
10519 				rval = COMMAND_DONE_ERROR_RECOVERED;
10520 				st_bioerror(bp, ENOMEM);
10521 			} else {
10522 				ST_DO_ERRSTATS(un, st_softerrs);
10523 				severity = SCSI_ERR_FATAL;
10524 				rval = COMMAND_DONE_ERROR;
10525 				st_bioerror(bp, EINVAL);
10526 				un->un_running.pmode = invalid;
10527 			}
10528 		} else {
10529 			/*
10530 			 * we hope and pray for this just being
10531 			 * something we can ignore (ie. a
10532 			 * truly recoverable soft error)
10533 			 */
10534 			rval = COMMAND_DONE;
10535 		}
10536 		if (sensep->es_filmk) {
10537 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10538 			    "filemark\n");
10539 			un->un_status = SUN_KEY_EOF;
10540 			pos->eof = ST_EOF_PENDING;
10541 			st_set_pe_flag(un);
10542 		}
10543 
10544 		/*
10545 		 * ignore eom when reading, a fmk should terminate reading
10546 		 */
10547 		if ((sensep->es_eom) &&
10548 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10549 			if ((sensep->es_add_code == 0) &&
10550 			    (sensep->es_qual_code == 4)) {
10551 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10552 				    "bot\n");
10553 				un->un_status = SUN_KEY_BOT;
10554 				pos->eof = ST_NO_EOF;
10555 				pos->lgclblkno = 0;
10556 				pos->fileno = 0;
10557 				pos->blkno = 0;
10558 				if (pos->pmode != legacy)
10559 					pos->pmode = legacy;
10560 			} else {
10561 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10562 				    "eom\n");
10563 				un->un_status = SUN_KEY_EOT;
10564 				pos->eof = ST_EOM;
10565 			}
10566 			st_set_pe_flag(un);
10567 		}
10568 
10569 		break;
10570 
10571 	case KEY_ILLEGAL_REQUEST:
10572 
10573 		if (un->un_laststate >= ST_STATE_OPEN) {
10574 			ST_DO_ERRSTATS(un, st_softerrs);
10575 			severity = SCSI_ERR_FATAL;
10576 		} else {
10577 			severity = SCSI_ERR_INFO;
10578 		}
10579 		break;
10580 
10581 	case KEY_MEDIUM_ERROR:
10582 		ST_DO_ERRSTATS(un, st_harderrs);
10583 		severity = SCSI_ERR_FATAL;
10584 
10585 		/*
10586 		 * for (buffered) writes, a medium error must be fatal
10587 		 */
10588 		if (CDBP(pkt)->scc_cmd != SCMD_WRITE) {
10589 			rval = COMMAND_DONE_ERROR_RECOVERED;
10590 		}
10591 
10592 check_keys:
10593 		/*
10594 		 * attempt to process the keys in the presence of
10595 		 * other errors
10596 		 */
10597 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10598 			/*
10599 			 * Fun with variable length record devices:
10600 			 * for specifying larger blocks sizes than the
10601 			 * actual physical record size.
10602 			 */
10603 			if (un->un_bsize == 0 && resid > 0) {
10604 				/*
10605 				 * XXX! Ugly
10606 				 */
10607 				pkt->pkt_resid = resid;
10608 			} else if (un->un_bsize == 0 && resid < 0) {
10609 				st_bioerror(bp, EINVAL);
10610 			} else {
10611 				severity = SCSI_ERR_FATAL;
10612 				rval = COMMAND_DONE_ERROR;
10613 				st_bioerror(bp, EINVAL);
10614 			}
10615 		}
10616 		if (sensep->es_filmk) {
10617 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10618 			    "filemark\n");
10619 			un->un_status = SUN_KEY_EOF;
10620 			pos->eof = ST_EOF_PENDING;
10621 			st_set_pe_flag(un);
10622 		}
10623 
10624 		/*
10625 		 * ignore eom when reading, a fmk should terminate reading
10626 		 */
10627 		if ((sensep->es_eom) &&
10628 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10629 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10630 			un->un_status = SUN_KEY_EOT;
10631 			pos->eof = ST_EOM;
10632 			st_set_pe_flag(un);
10633 		}
10634 
10635 		break;
10636 
10637 	case KEY_VOLUME_OVERFLOW:
10638 		ST_DO_ERRSTATS(un, st_softerrs);
10639 		pos->eof = ST_EOM;
10640 		severity = SCSI_ERR_FATAL;
10641 		rval = COMMAND_DONE_ERROR;
10642 		goto check_keys;
10643 
10644 	case KEY_HARDWARE_ERROR:
10645 		ST_DO_ERRSTATS(un, st_harderrs);
10646 		severity = SCSI_ERR_FATAL;
10647 		rval = COMMAND_DONE_ERROR;
10648 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10649 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10650 		break;
10651 
10652 	case KEY_BLANK_CHECK:
10653 		ST_DO_ERRSTATS(un, st_softerrs);
10654 		severity = SCSI_ERR_INFO;
10655 
10656 		/*
10657 		 * if not a special request and some data was xferred then it
10658 		 * it is not an error yet
10659 		 */
10660 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10661 			/*
10662 			 * no error for read with or without data xferred
10663 			 */
10664 			un->un_status = SUN_KEY_EOT;
10665 			pos->eof = ST_EOT;
10666 			rval = COMMAND_DONE_ERROR;
10667 			st_set_pe_flag(un);
10668 			goto check_keys;
10669 		} else if (bp != un->un_sbufp &&
10670 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10671 			rval = COMMAND_DONE;
10672 		} else {
10673 			rval = COMMAND_DONE_ERROR_RECOVERED;
10674 		}
10675 
10676 		if (un->un_laststate >= ST_STATE_OPEN) {
10677 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10678 			    "blank check\n");
10679 			pos->eof = ST_EOM;
10680 		}
10681 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10682 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10683 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
10684 		    (un->un_dp->options & ST_KNOWS_EOD)) {
10685 			/*
10686 			 * we were doing a fast forward by skipping
10687 			 * multiple fmk at the time
10688 			 */
10689 			st_bioerror(bp, EIO);
10690 			severity = SCSI_ERR_RECOVERED;
10691 			rval	 = COMMAND_DONE;
10692 		}
10693 		st_set_pe_flag(un);
10694 		goto check_keys;
10695 
10696 	case KEY_WRITE_PROTECT:
10697 		if (st_wrongtapetype(un)) {
10698 			un->un_status = SUN_KEY_WRONGMEDIA;
10699 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10700 			    "wrong tape for writing- use DC6150 tape "
10701 			    "(or equivalent)\n");
10702 			severity = SCSI_ERR_UNKNOWN;
10703 		} else {
10704 			severity = SCSI_ERR_FATAL;
10705 		}
10706 		ST_DO_ERRSTATS(un, st_harderrs);
10707 		rval = COMMAND_DONE_ERROR;
10708 		st_bioerror(bp, EACCES);
10709 		break;
10710 
10711 	case KEY_UNIT_ATTENTION:
10712 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10713 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
10714 
10715 		un->un_unit_attention_flags = 1;
10716 		/*
10717 		 * If we have detected a Bus Reset and the tape
10718 		 * drive has been reserved.
10719 		 */
10720 		if (ST_RQSENSE->es_add_code == 0x29) {
10721 			rval = DEVICE_RESET;
10722 			if ((un->un_rsvd_status &
10723 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
10724 			    ST_RESERVE) {
10725 				un->un_rsvd_status |= ST_LOST_RESERVE;
10726 				ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
10727 				    "st_decode_sense: Lost Reservation\n");
10728 			}
10729 		}
10730 
10731 		/*
10732 		 * If this is a recovery command and retrable, retry.
10733 		 */
10734 		if (bp == un->un_recov_buf) {
10735 			severity = SCSI_ERR_INFO;
10736 			if (attrib->retriable &&
10737 			    (int)un->un_retry_ct++ < st_retry_count) {
10738 				rval = QUE_COMMAND;
10739 			} else {
10740 				rval = COMMAND_DONE_ERROR;
10741 			}
10742 			break; /* Don't set position invalid */
10743 		}
10744 		if (un->un_state <= ST_STATE_OPENING) {
10745 			/*
10746 			 * Look, the tape isn't open yet, now determine
10747 			 * if the cause is a BUS RESET, Save the file
10748 			 * and Block positions for the callers to
10749 			 * recover from the loss of position.
10750 			 */
10751 			severity = SCSI_ERR_INFO;
10752 			if ((pos->pmode != invalid) &&
10753 			    (rval == DEVICE_RESET) &&
10754 			    (un->un_restore_pos != 1)) {
10755 				un->un_save_fileno = pos->fileno;
10756 				un->un_save_blkno = pos->blkno;
10757 				un->un_restore_pos = 1;
10758 			}
10759 
10760 			if (attrib->retriable &&
10761 			    (int)un->un_retry_ct++ < st_retry_count) {
10762 				rval = QUE_COMMAND;
10763 			} else if (rval == DEVICE_RESET) {
10764 				break;
10765 			} else {
10766 				rval = COMMAND_DONE_ERROR;
10767 			}
10768 		/*
10769 		 * Means it thinks the mode parameters have changed.
10770 		 * This is the result of a reset clearing settings or
10771 		 * another initiator changing what we set.
10772 		 */
10773 		} else if (ST_RQSENSE->es_add_code == 0x2a) {
10774 			if (ST_RQSENSE->es_qual_code == 0x1) {
10775 				/* Error recovery will modeselect and retry. */
10776 				rval = DEVICE_TAMPER;
10777 				severity = SCSI_ERR_INFO;
10778 				break; /* don't set position invalid */
10779 			}
10780 			if (ST_RQSENSE->es_qual_code == 0x0 ||
10781 			    ST_RQSENSE->es_qual_code == 0x2 ||
10782 			    ST_RQSENSE->es_qual_code == 0x3 ||
10783 			    ST_RQSENSE->es_qual_code == 0x4 ||
10784 			    ST_RQSENSE->es_qual_code == 0x5 ||
10785 			    ST_RQSENSE->es_qual_code == 0x6 ||
10786 			    ST_RQSENSE->es_qual_code == 0x7) {
10787 				rval = DEVICE_TAMPER;
10788 				severity = SCSI_ERR_INFO;
10789 			}
10790 		} else if (ST_RQSENSE->es_add_code == 0x28 &&
10791 		    ((ST_RQSENSE->es_qual_code == 0x0) ||
10792 		    ST_RQSENSE->es_qual_code == 0x5)) {
10793 			/*
10794 			 * Not Ready to Ready change, Media may have changed.
10795 			 */
10796 			rval = DEVICE_TAMPER;
10797 			severity = SCSI_ERR_RETRYABLE;
10798 		} else {
10799 			if (rval != DEVICE_RESET) {
10800 				rval = COMMAND_DONE_ERROR;
10801 			} else {
10802 				/*
10803 				 * Returning DEVICE_RESET will call
10804 				 * error recovery.
10805 				 */
10806 				severity = SCSI_ERR_INFO;
10807 				break; /* don't set position invalid */
10808 			}
10809 			/*
10810 			 * Check if it is an Unexpected Unit Attention.
10811 			 * If state is >= ST_STATE_OPEN, we have
10812 			 * already done the initialization .
10813 			 * In this case it is Fatal Error
10814 			 * since no further reading/writing
10815 			 * can be done with fileno set to < 0.
10816 			 */
10817 			if (un->un_state >= ST_STATE_OPEN) {
10818 				ST_DO_ERRSTATS(un, st_harderrs);
10819 				severity = SCSI_ERR_FATAL;
10820 			} else {
10821 				severity = SCSI_ERR_INFO;
10822 			}
10823 		}
10824 
10825 		pos->pmode = invalid;
10826 
10827 		break;
10828 
10829 	case KEY_NOT_READY:
10830 		/*
10831 		 * If in process of getting ready retry.
10832 		 */
10833 		if (sensep->es_add_code  == 0x04 &&
10834 		    sensep->es_qual_code == 0x01 &&
10835 		    un->un_retry_ct++ < st_retry_count) {
10836 			rval = QUE_COMMAND;
10837 			severity = SCSI_ERR_INFO;
10838 		} else {
10839 			/* give up */
10840 			rval = COMMAND_DONE_ERROR;
10841 			severity = SCSI_ERR_FATAL;
10842 		}
10843 
10844 		/*
10845 		 * If this was an error and after device opened
10846 		 * do error stats.
10847 		 */
10848 		if (rval == COMMAND_DONE_ERROR &&
10849 		    un->un_state > ST_STATE_OPENING) {
10850 			ST_DO_ERRSTATS(un, st_harderrs);
10851 		}
10852 
10853 		if (ST_RQSENSE->es_add_code == 0x3a) {
10854 			if (st_error_level >= SCSI_ERR_FATAL)
10855 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
10856 				    "Tape not inserted in drive\n");
10857 			un->un_mediastate = MTIO_EJECTED;
10858 			cv_broadcast(&un->un_state_cv);
10859 		}
10860 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
10861 		    (rval != QUE_COMMAND))
10862 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10863 		break;
10864 
10865 	case KEY_ABORTED_COMMAND:
10866 		/* XXX Do drives return this when they see a lost light? */
10867 		/* Testing would say yes */
10868 
10869 		if (un->un_retry_ct++ < st_retry_count) {
10870 			rval = ATTEMPT_RETRY;
10871 			severity = SCSI_ERR_RETRYABLE;
10872 			goto check_keys;
10873 		}
10874 		/*
10875 		 * Probably a parity error...
10876 		 * if we retry here then this may cause data to be
10877 		 * written twice or data skipped during reading
10878 		 */
10879 		ST_DO_ERRSTATS(un, st_harderrs);
10880 		severity = SCSI_ERR_FATAL;
10881 		rval = COMMAND_DONE_ERROR;
10882 		goto check_keys;
10883 
10884 	default:
10885 		/*
10886 		 * Undecoded sense key.	 Try retries and hope
10887 		 * that will fix the problem.  Otherwise, we're
10888 		 * dead.
10889 		 */
10890 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10891 		    "Unhandled Sense Key '%s'\n",
10892 		    sense_keys[un->un_status]);
10893 		ST_DO_ERRSTATS(un, st_harderrs);
10894 		severity = SCSI_ERR_FATAL;
10895 		rval = COMMAND_DONE_ERROR;
10896 		goto check_keys;
10897 	}
10898 
10899 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
10900 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
10901 	    (un->un_laststate > ST_STATE_OPENING) &&
10902 	    (severity >= st_error_level))) {
10903 
10904 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
10905 		    pos->lgclblkno, un->un_err_pos.lgclblkno,
10906 		    scsi_cmds, sensep);
10907 		if (sensep->es_filmk) {
10908 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10909 			    "File Mark Detected\n");
10910 		}
10911 		if (sensep->es_eom) {
10912 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10913 			    "End-of-Media Detected\n");
10914 		}
10915 		if (sensep->es_ili) {
10916 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10917 			    "Incorrect Length Indicator Set\n");
10918 		}
10919 	}
10920 	get_error = geterror(bp);
10921 	if (((rval == COMMAND_DONE_ERROR) ||
10922 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
10923 	    ((get_error == EIO) || (get_error == 0))) {
10924 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
10925 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
10926 		if (un->un_rqs_state & ST_RQS_READ) {
10927 			un->un_rqs_state &= ~(ST_RQS_READ);
10928 		} else {
10929 			un->un_rqs_state |= ST_RQS_OVR;
10930 		}
10931 	}
10932 
10933 	return (rval);
10934 }
10935 
10936 
10937 static int
10938 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
10939 {
10940 	int status = TRAN_ACCEPT;
10941 
10942 	mutex_enter(ST_MUTEX);
10943 
10944 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
10945 
10946 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10947 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
10948 
10949 	/*
10950 	 * Check to see if we hit the retry timeout. We check to make sure
10951 	 * this is the first one on the runq and make sure we have not
10952 	 * queued up any more, so this one has to be the last on the list
10953 	 * also. If it is not, we have to fail.  If it is not the first, but
10954 	 * is the last we are in trouble anyway, as we are in the interrupt
10955 	 * context here.
10956 	 */
10957 	if (((int)un->un_retry_ct > st_retry_count) ||
10958 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
10959 		goto exit;
10960 	}
10961 
10962 	if (un->un_throttle) {
10963 		un->un_last_throttle = un->un_throttle;
10964 		un->un_throttle = 0;
10965 	}
10966 
10967 	/*
10968 	 * Here we know : bp is the first and last one on the runq
10969 	 * it is not necessary to put it back on the head of the
10970 	 * waitq and then move from waitq to runq. Save this queuing
10971 	 * and call scsi_transport.
10972 	 */
10973 	ST_CDB(ST_DEVINFO, "Retry lcmd CDB", (char *)BP_PKT(bp)->pkt_cdbp);
10974 
10975 	status = st_transport(un, BP_PKT(bp));
10976 
10977 	if (status == TRAN_ACCEPT) {
10978 		un->un_tran_retry_ct = 0;
10979 		if (un->un_last_throttle) {
10980 			un->un_throttle = un->un_last_throttle;
10981 		}
10982 		mutex_exit(ST_MUTEX);
10983 
10984 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10985 		    "restart transport \n");
10986 		return (0);
10987 	}
10988 
10989 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
10990 	mutex_exit(ST_MUTEX);
10991 
10992 	if (status == TRAN_BUSY) {
10993 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
10994 			return (0);
10995 		}
10996 	}
10997 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10998 	    "restart transport rejected\n");
10999 	mutex_enter(ST_MUTEX);
11000 	ST_DO_ERRSTATS(un, st_transerrs);
11001 	if (un->un_last_throttle) {
11002 		un->un_throttle = un->un_last_throttle;
11003 	}
11004 exit:
11005 	mutex_exit(ST_MUTEX);
11006 	return (-1);
11007 }
11008 
11009 static int
11010 st_wrongtapetype(struct scsi_tape *un)
11011 {
11012 
11013 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
11014 
11015 	ASSERT(mutex_owned(ST_MUTEX));
11016 
11017 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
11018 
11019 	/*
11020 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
11021 	 */
11022 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
11023 		switch (un->un_dp->type) {
11024 		case ST_TYPE_WANGTEK:
11025 		case ST_TYPE_ARCHIVE:
11026 			/*
11027 			 * If this really worked, we could go off of
11028 			 * the density codes set in the modesense
11029 			 * page. For this drive, 0x10 == QIC-120,
11030 			 * 0xf == QIC-150, and 0x5 should be for
11031 			 * both QIC-24 and, maybe, QIC-11. However,
11032 			 * the h/w doesn't do what the manual says
11033 			 * that it should, so we'll key off of
11034 			 * getting a WRITE PROTECT error AND wp *not*
11035 			 * set in the mode sense information.
11036 			 */
11037 			/*
11038 			 * XXX but we already know that status is
11039 			 * write protect, so don't check it again.
11040 			 */
11041 
11042 			if (un->un_status == KEY_WRITE_PROTECT &&
11043 			    un->un_mspl->wp == 0) {
11044 				return (1);
11045 			}
11046 			break;
11047 		default:
11048 			break;
11049 		}
11050 	}
11051 	return (0);
11052 }
11053 
11054 static errstate
11055 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
11056 {
11057 	errstate action;
11058 
11059 	ST_FUNC(ST_DEVINFO, st_check_error);
11060 
11061 	ASSERT(mutex_owned(ST_MUTEX));
11062 
11063 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
11064 
11065 	if (SCBP_C(pkt) == STATUS_RESERVATION_CONFLICT) {
11066 		action = COMMAND_DONE_EACCES;
11067 		un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
11068 	} else if (SCBP(pkt)->sts_busy) {
11069 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
11070 		if ((int)un->un_retry_ct++ < st_retry_count) {
11071 			action = QUE_BUSY_COMMAND;
11072 		} else if ((un->un_rsvd_status &
11073 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
11074 			/*
11075 			 * If this is a command done before reserve is done
11076 			 * don't reset.
11077 			 */
11078 			action = COMMAND_DONE_ERROR;
11079 		} else {
11080 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11081 			    "unit busy too long\n");
11082 			(void) st_reset(un, RESET_ALL);
11083 			action = COMMAND_DONE_ERROR;
11084 		}
11085 	} else if (SCBP(pkt)->sts_chk) {
11086 		/*
11087 		 * we should only get here if the auto rqsense failed
11088 		 * thru a uscsi cmd without autorequest sense
11089 		 * so we just try again
11090 		 */
11091 		action = QUE_SENSE;
11092 	} else if (SCBP(pkt)->sts_vu7) {
11093 		/*
11094 		 * This is an aborted task. This can be a reset on the other
11095 		 * port of a multiport drive. Lets try and recover it.
11096 		 */
11097 		action = DEVICE_RESET;
11098 	} else {
11099 		action = COMMAND_DONE;
11100 	}
11101 	return (action);
11102 }
11103 
11104 static void
11105 st_calc_bnum(struct scsi_tape *un, struct buf *bp, struct scsi_pkt *pkt)
11106 {
11107 	int nblks;
11108 	long count;
11109 	recov_info *ri = (recov_info *)pkt->pkt_private;
11110 	cmd_attribute const *attrib;
11111 
11112 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
11113 
11114 	ASSERT(mutex_owned(ST_MUTEX));
11115 
11116 	if (ri->privatelen == sizeof (recov_info)) {
11117 		attrib = ri->cmd_attrib;
11118 		ASSERT(attrib->recov_pos_type == POS_EXPECTED);
11119 		ASSERT(attrib->chg_tape_pos);
11120 	} else {
11121 		ri = NULL;
11122 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
11123 	}
11124 
11125 	count = bp->b_bcount - bp->b_resid;
11126 
11127 	/* If variable block mode */
11128 	if (un->un_bsize == 0) {
11129 		nblks = ((count == 0) ? 0 : 1);
11130 		un->un_kbytes_xferred += (count / ONE_K);
11131 	} else {
11132 		nblks = (count / un->un_bsize);
11133 		un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
11134 	}
11135 
11136 	/*
11137 	 * If some command failed after this one started and it seems
11138 	 * to have finshed without error count the position.
11139 	 */
11140 	if (un->un_persistence && un->un_persist_errors) {
11141 		ASSERT(un->un_pos.pmode != invalid);
11142 	}
11143 
11144 	if (attrib->chg_tape_direction == DIR_FORW) {
11145 		un->un_pos.blkno += nblks;
11146 		un->un_pos.lgclblkno += nblks;
11147 	} else if (attrib->chg_tape_direction == DIR_REVC) {
11148 		un->un_pos.blkno -= nblks;
11149 		un->un_pos.lgclblkno -= nblks;
11150 	} else {
11151 		ASSERT(0);
11152 	}
11153 
11154 	/* recovery disabled */
11155 	if (ri == NULL) {
11156 		un->un_running.pmode = invalid;
11157 		return;
11158 	}
11159 
11160 	/*
11161 	 * If we didn't just read a filemark.
11162 	 */
11163 	if (un->un_pos.eof != ST_EOF_PENDING) {
11164 		ASSERT(nblks != 0);
11165 		/*
11166 		 * If Previously calulated expected position does not match
11167 		 * debug the expected position.
11168 		 */
11169 		if ((ri->pos.pmode != invalid) && nblks &&
11170 		    ((un->un_pos.blkno != ri->pos.blkno) ||
11171 		    (un->un_pos.lgclblkno != ri->pos.lgclblkno))) {
11172 #ifdef STDEBUG
11173 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11174 			    "Expected", &ri->pos);
11175 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11176 			    "But Got", &un->un_pos);
11177 #endif
11178 			un->un_running.pmode = invalid;
11179 		}
11180 	} else {
11181 		ASSERT(nblks == 0);
11182 		if (un->un_running.pmode != invalid) {
11183 			/*
11184 			 * blkno and lgclblkno already counted in
11185 			 * st_add_recovery_info_to_pkt(). Since a block was not
11186 			 * read and a filemark was.
11187 			 */
11188 			if (attrib->chg_tape_direction == DIR_FORW) {
11189 				un->un_running.fileno++;
11190 				un->un_running.blkno = 0;
11191 			} else if (attrib->chg_tape_direction == DIR_REVC) {
11192 				un->un_running.fileno--;
11193 				un->un_running.blkno = LASTBLK;
11194 			}
11195 		}
11196 	}
11197 }
11198 
11199 static void
11200 st_set_state(struct scsi_tape *un, struct buf *bp)
11201 {
11202 	struct scsi_pkt *sp = BP_PKT(bp);
11203 	struct uscsi_cmd *ucmd;
11204 
11205 	ST_FUNC(ST_DEVINFO, st_set_state);
11206 
11207 	ASSERT(mutex_owned(ST_MUTEX));
11208 	ASSERT(bp != un->un_recov_buf);
11209 
11210 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11211 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
11212 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
11213 
11214 	if (bp != un->un_sbufp) {
11215 #ifdef STDEBUG
11216 		if (DEBUGGING && sp->pkt_resid) {
11217 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11218 			    "pkt_resid %ld bcount %ld\n",
11219 			    sp->pkt_resid, bp->b_bcount);
11220 		}
11221 #endif
11222 		bp->b_resid = sp->pkt_resid;
11223 		if (geterror(bp) != EIO) {
11224 			st_calc_bnum(un, bp, sp);
11225 		}
11226 		if (bp->b_flags & B_READ) {
11227 			un->un_lastop = ST_OP_READ;
11228 			un->un_fmneeded = 0;
11229 		} else {
11230 			un->un_lastop = ST_OP_WRITE;
11231 			if (un->un_dp->options & ST_REEL) {
11232 				un->un_fmneeded = 2;
11233 			} else {
11234 				un->un_fmneeded = 1;
11235 			}
11236 		}
11237 		/*
11238 		 * all is honky dory at this point, so let's
11239 		 * readjust the throttle, to increase speed, if we
11240 		 * have not throttled down.
11241 		 */
11242 		if (un->un_throttle) {
11243 			un->un_throttle = un->un_max_throttle;
11244 		}
11245 	} else {
11246 		optype new_lastop;
11247 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
11248 
11249 		un->un_lastop = ST_OP_CTL;
11250 
11251 		switch (cmd) {
11252 		case SCMD_WRITE:
11253 		case SCMD_WRITE_G4:
11254 			bp->b_resid = sp->pkt_resid;
11255 			if (geterror(bp) == EIO) {
11256 				break;
11257 			}
11258 			new_lastop = ST_OP_WRITE;
11259 			st_calc_bnum(un, bp, sp);
11260 			if (un->un_dp->options & ST_REEL) {
11261 				un->un_fmneeded = 2;
11262 			} else {
11263 				un->un_fmneeded = 1;
11264 			}
11265 			break;
11266 		case SCMD_READ:
11267 		case SCMD_READ_G4:
11268 			bp->b_resid = sp->pkt_resid;
11269 			if (geterror(bp) == EIO) {
11270 				break;
11271 			}
11272 			new_lastop = ST_OP_READ;
11273 			st_calc_bnum(un, bp, sp);
11274 			un->un_fmneeded = 0;
11275 			break;
11276 		case SCMD_WRITE_FILE_MARK_G4:
11277 		case SCMD_WRITE_FILE_MARK:
11278 		{
11279 			int fmdone;
11280 
11281 			if (un->un_pos.eof != ST_EOM) {
11282 				un->un_pos.eof = ST_NO_EOF;
11283 			}
11284 			fmdone = (bp->b_bcount - bp->b_resid);
11285 			if (fmdone > 0) {
11286 				un->un_lastop = new_lastop = ST_OP_WEOF;
11287 				un->un_pos.lgclblkno += fmdone;
11288 				un->un_pos.fileno += fmdone;
11289 				un->un_pos.blkno = 0;
11290 			} else {
11291 				new_lastop = ST_OP_CTL;
11292 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11293 				    "Flushed buffer\n");
11294 			}
11295 			if (fmdone > un->un_fmneeded) {
11296 				un->un_fmneeded = 0;
11297 			} else {
11298 				un->un_fmneeded -= fmdone;
11299 			}
11300 			break;
11301 		}
11302 		case SCMD_REWIND:
11303 			un->un_pos.eof = ST_NO_EOF;
11304 			un->un_pos.fileno = 0;
11305 			un->un_pos.blkno = 0;
11306 			un->un_pos.lgclblkno = 0;
11307 			if (un->un_pos.pmode != legacy)
11308 				un->un_pos.pmode = legacy;
11309 			new_lastop = ST_OP_CTL;
11310 			un->un_restore_pos = 0;
11311 			break;
11312 
11313 		case SCMD_SPACE:
11314 		case SCMD_SPACE_G4:
11315 		{
11316 			int64_t count;
11317 			int64_t resid;
11318 			int64_t done;
11319 			cmd_attribute const *attrib;
11320 			recov_info *ri = (recov_info *)sp->pkt_private;
11321 
11322 			if (ri->privatelen == sizeof (recov_info)) {
11323 				attrib = ri->cmd_attrib;
11324 			} else {
11325 				attrib =
11326 				    st_lookup_cmd_attribute(sp->pkt_cdbp[0]);
11327 			}
11328 
11329 			resid = (int64_t)SPACE_CNT(bp->b_resid);
11330 			count = (int64_t)attrib->get_cnt(sp->pkt_cdbp);
11331 
11332 			if (count >= 0) {
11333 				done = (count - resid);
11334 			} else {
11335 				done = ((-count) - resid);
11336 			}
11337 			if (done > 0) {
11338 				un->un_lastop = new_lastop = ST_OP_CTL;
11339 			} else {
11340 				new_lastop = ST_OP_CTL;
11341 			}
11342 
11343 			ST_SPAC(ST_DEVINFO, st_label, SCSI_DEBUG,
11344 			    "space cmd: cdb[1] = %s\n"
11345 			    "space data:       = 0x%lx\n"
11346 			    "space count:      = %"PRId64"\n"
11347 			    "space resid:      = %"PRId64"\n"
11348 			    "spaces done:      = %"PRId64"\n"
11349 			    "fileno before     = %d\n"
11350 			    "blkno before      = %d\n",
11351 			    space_strs[sp->pkt_cdbp[1] & 7],
11352 			    bp->b_bcount,
11353 			    count, resid, done,
11354 			    un->un_pos.fileno, un->un_pos.blkno);
11355 
11356 			switch (sp->pkt_cdbp[1]) {
11357 			case SPACE_TYPE(SP_FLM):
11358 				/* Space file forward */
11359 				if (count >= 0) {
11360 					if (un->un_pos.eof <= ST_EOF) {
11361 						un->un_pos.eof = ST_NO_EOF;
11362 					}
11363 					un->un_pos.fileno += done;
11364 					un->un_pos.blkno = 0;
11365 					break;
11366 				}
11367 				/* Space file backward */
11368 				if (done > un->un_pos.fileno) {
11369 					un->un_pos.fileno = 0;
11370 					un->un_pos.blkno = 0;
11371 				} else {
11372 					un->un_pos.fileno -= done;
11373 					un->un_pos.blkno = LASTBLK;
11374 					un->un_running.pmode = invalid;
11375 				}
11376 				break;
11377 			case SPACE_TYPE(SP_BLK):
11378 				/* Space block forward */
11379 				if (count >= 0) {
11380 					un->un_pos.blkno += done;
11381 					break;
11382 				}
11383 				/* Space block backward */
11384 				if (un->un_pos.eof >= ST_EOF_PENDING) {
11385 				/*
11386 				 * we stepped back into
11387 				 * a previous file; we are not
11388 				 * making an effort to pretend that
11389 				 * we are still in the current file
11390 				 * ie. logical == physical position
11391 				 * and leave it to st_ioctl to correct
11392 				 */
11393 					if (done > un->un_pos.blkno) {
11394 						un->un_pos.blkno = 0;
11395 					} else {
11396 						un->un_pos.fileno--;
11397 						un->un_pos.blkno = LASTBLK;
11398 						un->un_running.pmode = invalid;
11399 					}
11400 				} else {
11401 					un->un_pos.blkno -= done;
11402 				}
11403 				break;
11404 			case SPACE_TYPE(SP_SQFLM):
11405 				un->un_pos.pmode = logical;
11406 				un->un_pos.blkno = 0;
11407 				un->un_lastop = new_lastop = ST_OP_CTL;
11408 				break;
11409 			case SPACE_TYPE(SP_EOD):
11410 				un->un_pos.pmode = logical;
11411 				un->un_pos.eof = ST_EOM;
11412 				un->un_status = KEY_BLANK_CHECK;
11413 				break;
11414 			default:
11415 				un->un_pos.pmode = invalid;
11416 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11417 				    "Unsupported space cmd: %s\n",
11418 				    space_strs[sp->pkt_cdbp[1] & 7]);
11419 
11420 				un->un_lastop = new_lastop = ST_OP_CTL;
11421 			}
11422 
11423 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11424 			    "after_space rs %"PRId64" fil %d blk %d\n",
11425 			    resid, un->un_pos.fileno, un->un_pos.blkno);
11426 
11427 			break;
11428 		}
11429 		case SCMD_LOAD:
11430 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
11431 				un->un_pos.fileno = 0;
11432 				if (un->un_pos.pmode != legacy)
11433 					un->un_pos.pmode = legacy;
11434 			} else {
11435 				un->un_state = ST_STATE_OFFLINE;
11436 				un->un_pos.pmode = invalid;
11437 			}
11438 			un->un_density_known = 0;
11439 			un->un_pos.eof = ST_NO_EOF;
11440 			un->un_pos.blkno = 0;
11441 			un->un_lastop = new_lastop = ST_OP_CTL;
11442 			break;
11443 		case SCMD_ERASE:
11444 			un->un_pos.eof = ST_NO_EOF;
11445 			un->un_pos.blkno = 0;
11446 			un->un_pos.fileno = 0;
11447 			un->un_pos.lgclblkno = 0;
11448 			if (un->un_pos.pmode != legacy)
11449 				un->un_pos.pmode = legacy;
11450 			new_lastop = ST_OP_CTL;
11451 			break;
11452 		case SCMD_RESERVE:
11453 			un->un_rsvd_status |= ST_RESERVE;
11454 			un->un_rsvd_status &=
11455 			    ~(ST_RELEASE | ST_LOST_RESERVE |
11456 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11457 			new_lastop = un->un_lastop;
11458 			break;
11459 		case SCMD_RELEASE:
11460 			un->un_rsvd_status |= ST_RELEASE;
11461 			un->un_rsvd_status &=
11462 			    ~(ST_RESERVE | ST_LOST_RESERVE |
11463 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11464 			new_lastop = ST_OP_CTL;
11465 			break;
11466 		case SCMD_PERSISTENT_RESERVE_IN:
11467 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11468 			    "PGR_IN command\n");
11469 			break;
11470 		case SCMD_PERSISTENT_RESERVE_OUT:
11471 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
11472 			case ST_SA_SCSI3_RESERVE:
11473 			case ST_SA_SCSI3_PREEMPT:
11474 			case ST_SA_SCSI3_PREEMPTANDABORT:
11475 				un->un_rsvd_status |=
11476 				    ST_APPLICATION_RESERVATIONS;
11477 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11478 				    "PGR Reserve and set: entering"
11479 				    " ST_APPLICATION_RESERVATIONS mode");
11480 				break;
11481 			case ST_SA_SCSI3_RELEASE:
11482 			case ST_SA_SCSI3_CLEAR:
11483 				un->un_rsvd_status &=
11484 				    ~ST_APPLICATION_RESERVATIONS;
11485 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11486 				    "PGR Release and reset: exiting"
11487 				    " ST_APPLICATION_RESERVATIONS mode");
11488 				break;
11489 			}
11490 			break;
11491 		case SCMD_TEST_UNIT_READY:
11492 		case SCMD_READ_BLKLIM:
11493 		case SCMD_REQUEST_SENSE:
11494 		case SCMD_INQUIRY:
11495 		case SCMD_RECOVER_BUF:
11496 		case SCMD_MODE_SELECT:
11497 		case SCMD_MODE_SENSE:
11498 		case SCMD_DOORLOCK:
11499 		case SCMD_READ_BUFFER:
11500 		case SCMD_REPORT_DENSITIES:
11501 		case SCMD_LOG_SELECT_G1:
11502 		case SCMD_LOG_SENSE_G1:
11503 		case SCMD_REPORT_LUNS:
11504 		case SCMD_READ_ATTRIBUTE:
11505 		case SCMD_WRITE_ATTRIBUTE:
11506 		case SCMD_SVC_ACTION_IN_G5:
11507 			new_lastop = ST_OP_CTL;
11508 			break;
11509 		case SCMD_READ_POSITION:
11510 			new_lastop = ST_OP_CTL;
11511 			/*
11512 			 * Only if the buf used was un_sbufp.
11513 			 * Among other things the prevents read positions used
11514 			 * as part of error recovery from messing up our
11515 			 * current position as they will use un_recov_buf.
11516 			 */
11517 			if (USCSI_CMD(bp)) {
11518 				(void) st_get_read_pos(un, bp);
11519 			}
11520 			break;
11521 		case SCMD_LOCATE:
11522 		case SCMD_LOCATE_G4:
11523 			/* Locate makes position mode no longer legacy */
11524 			un->un_lastop = new_lastop = ST_OP_CTL;
11525 			break;
11526 		default:
11527 			/*
11528 			 * Unknown command, If was USCSI and USCSI_SILENT
11529 			 * flag was not set, set position to unknown.
11530 			 */
11531 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
11532 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
11533 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11534 				    "unknown cmd 0x%X caused loss of state\n",
11535 				    cmd);
11536 			} else {
11537 				break;
11538 			}
11539 			/* FALLTHROUGH */
11540 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
11541 			un->un_pos.pmode = invalid;
11542 			un->un_lastop = new_lastop = ST_OP_CTL;
11543 			break;
11544 		}
11545 
11546 		/* new_lastop should have been changed */
11547 		ASSERT(new_lastop != ST_OP_NIL);
11548 
11549 		/* If un_lastop should copy new_lastop  */
11550 		if (((un->un_lastop == ST_OP_WRITE) ||
11551 		    (un->un_lastop == ST_OP_WEOF)) &&
11552 		    new_lastop != ST_OP_CTL) {
11553 			un->un_lastop = new_lastop;
11554 		}
11555 	}
11556 
11557 	/*
11558 	 * In the st driver we have a logical and physical file position.
11559 	 * Under BSD behavior, when you get a zero read, the logical position
11560 	 * is before the filemark but after the last record of the file.
11561 	 * The physical position is after the filemark. MTIOCGET should always
11562 	 * return the logical file position.
11563 	 *
11564 	 * The next read gives a silent skip to the next file.
11565 	 * Under SVR4, the logical file position remains before the filemark
11566 	 * until the file is closed or a space operation is performed.
11567 	 * Hence set err_resid and err_file before changing fileno if case
11568 	 * BSD Behaviour.
11569 	 */
11570 	un->un_err_resid = bp->b_resid;
11571 	COPY_POS(&un->un_err_pos, &un->un_pos);
11572 	un->un_retry_ct = 0;
11573 
11574 
11575 	/*
11576 	 * If we've seen a filemark via the last read operation
11577 	 * advance the file counter, but mark things such that
11578 	 * the next read operation gets a zero count. We have
11579 	 * to put this here to handle the case of sitting right
11580 	 * at the end of a tape file having seen the file mark,
11581 	 * but the tape is closed and then re-opened without
11582 	 * any further i/o. That is, the position information
11583 	 * must be updated before a close.
11584 	 */
11585 
11586 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
11587 		/*
11588 		 * If we're a 1/2" tape, and we get a filemark
11589 		 * right on block 0, *AND* we were not in the
11590 		 * first file on the tape, and we've hit logical EOM.
11591 		 * We'll mark the state so that later we do the
11592 		 * right thing (in st_close(), st_strategy() or
11593 		 * st_ioctl()).
11594 		 *
11595 		 */
11596 		if ((un->un_dp->options & ST_REEL) &&
11597 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
11598 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
11599 			un->un_pos.eof = ST_EOT_PENDING;
11600 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11601 			    "eot pending\n");
11602 			un->un_pos.fileno++;
11603 			un->un_pos.blkno = 0;
11604 		} else if (BSD_BEHAVIOR) {
11605 			/*
11606 			 * If the read of the filemark was a side effect
11607 			 * of reading some blocks (i.e., data was actually
11608 			 * read), then the EOF mark is pending and the
11609 			 * bump into the next file awaits the next read
11610 			 * operation (which will return a zero count), or
11611 			 * a close or a space operation, else the bump
11612 			 * into the next file occurs now.
11613 			 */
11614 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11615 			    "resid=%lx, bcount=%lx\n",
11616 			    bp->b_resid, bp->b_bcount);
11617 
11618 			if (bp->b_resid != bp->b_bcount) {
11619 				un->un_pos.eof = ST_EOF;
11620 			} else {
11621 				un->un_silent_skip = 1;
11622 				un->un_pos.eof = ST_NO_EOF;
11623 				un->un_pos.fileno++;
11624 				un->un_pos.lgclblkno++;
11625 				un->un_save_blkno = un->un_pos.blkno;
11626 				un->un_pos.blkno = 0;
11627 			}
11628 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11629 			    "eof of file %d, eof=%d\n",
11630 			    un->un_pos.fileno, un->un_pos.eof);
11631 		} else if (SVR4_BEHAVIOR) {
11632 			/*
11633 			 * If the read of the filemark was a side effect
11634 			 * of reading some blocks (i.e., data was actually
11635 			 * read), then the next read should return 0
11636 			 */
11637 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11638 			    "resid=%lx, bcount=%lx\n",
11639 			    bp->b_resid, bp->b_bcount);
11640 			if (bp->b_resid == bp->b_bcount) {
11641 				un->un_pos.eof = ST_EOF;
11642 			}
11643 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11644 			    "eof of file=%d, eof=%d\n",
11645 			    un->un_pos.fileno, un->un_pos.eof);
11646 		}
11647 	}
11648 }
11649 
11650 /*
11651  * set the correct un_errno, to take corner cases into consideration
11652  */
11653 static void
11654 st_set_pe_errno(struct scsi_tape *un)
11655 {
11656 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
11657 
11658 	ASSERT(mutex_owned(ST_MUTEX));
11659 
11660 	/* if errno is already set, don't reset it */
11661 	if (un->un_errno)
11662 		return;
11663 
11664 	/* here un_errno == 0 */
11665 	/*
11666 	 * if the last transfer before flushing all the
11667 	 * waiting I/O's, was 0 (resid = count), then we
11668 	 * want to give the user an error on all the rest,
11669 	 * so here.  If there was a transfer, we set the
11670 	 * resid and counts to 0, and let it drop through,
11671 	 * giving a zero return.  the next I/O will then
11672 	 * give an error.
11673 	 */
11674 	if (un->un_last_resid == un->un_last_count) {
11675 		switch (un->un_pos.eof) {
11676 		case ST_EOM:
11677 			un->un_errno = ENOMEM;
11678 			break;
11679 		case ST_EOT:
11680 		case ST_EOF:
11681 			un->un_errno = EIO;
11682 			break;
11683 		}
11684 	} else {
11685 		/*
11686 		 * we know they did not have a zero, so make
11687 		 * sure they get one
11688 		 */
11689 		un->un_last_resid = un->un_last_count = 0;
11690 	}
11691 }
11692 
11693 
11694 /*
11695  * send in a marker pkt to terminate flushing of commands by BBA (via
11696  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
11697  */
11698 static void
11699 st_hba_unflush(struct scsi_tape *un)
11700 {
11701 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
11702 
11703 	ASSERT(mutex_owned(ST_MUTEX));
11704 
11705 	if (!un->un_flush_on_errors)
11706 		return;
11707 
11708 #ifdef FLUSH_ON_ERRORS
11709 
11710 	if (!un->un_mkr_pkt) {
11711 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
11712 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
11713 
11714 		/* we slept, so it must be there */
11715 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
11716 	}
11717 
11718 	st_transport(un, un->un_mkr_pkt);
11719 #endif
11720 }
11721 
11722 static char *
11723 st_print_scsi_cmd(char cmd)
11724 {
11725 	char tmp[64];
11726 	char *cpnt;
11727 
11728 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
11729 	/* tmp goes out of scope on return and caller sees garbage */
11730 	if (cpnt == tmp) {
11731 		cpnt = "Unknown Command";
11732 	}
11733 	return (cpnt);
11734 }
11735 
11736 static void
11737 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
11738     char *title, char *cdb)
11739 {
11740 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
11741 	char buf[256];
11742 	struct scsi_tape *un;
11743 	int instance = ddi_get_instance(dip);
11744 
11745 	un = ddi_get_soft_state(st_state, instance);
11746 
11747 	ST_FUNC(dip, st_print_cdb);
11748 
11749 #ifdef STDEBUG
11750 	if ((st_debug & 0x180) == 0x100) {
11751 		scsi_log(dip, label, level, "node %s cmd %s\n",
11752 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
11753 		return;
11754 	}
11755 #endif
11756 	(void) sprintf(buf, "%s for cmd(%s)", title, st_print_scsi_cmd(*cdb));
11757 	st_clean_print(dip, label, level, buf, cdb, len);
11758 }
11759 
11760 static void
11761 st_clean_print(dev_info_t *dev, char *label, uint_t level,
11762     char *title, char *data, int len)
11763 {
11764 	int	i;
11765 	int 	c;
11766 	char	*format;
11767 	char	buf[256];
11768 	uchar_t	byte;
11769 
11770 	ST_FUNC(dev, st_clean_print);
11771 
11772 
11773 	(void) sprintf(buf, "%s:\n", title);
11774 	scsi_log(dev, label, level, "%s", buf);
11775 	level = CE_CONT;
11776 	for (i = 0; i < len; ) {
11777 		buf[0] = 0;
11778 		for (c = 0; c < 8 && i < len; c++, i++) {
11779 			byte = (uchar_t)data[i];
11780 			if (byte < 0x10)
11781 				format = "0x0%x ";
11782 			else
11783 				format = "0x%x ";
11784 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
11785 		}
11786 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
11787 
11788 		scsi_log(dev, label, level, "%s\n", buf);
11789 	}
11790 }
11791 
11792 /*
11793  * Conditionally enabled debugging
11794  */
11795 #ifdef	STDEBUG
11796 static void
11797 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
11798 {
11799 	char tmpbuf[64];
11800 
11801 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
11802 
11803 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11804 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
11805 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
11806 	    count, count,
11807 	    wait == ASYNC_CMD ? "a" : "");
11808 }
11809 
11810 /*
11811  * Returns pointer to name of minor node name of device 'dev'.
11812  */
11813 static char *
11814 st_dev_name(dev_t dev)
11815 {
11816 	struct scsi_tape *un;
11817 	const char density[] = { 'l', 'm', 'h', 'c' };
11818 	static char name[32];
11819 	minor_t minor;
11820 	int instance;
11821 	int nprt = 0;
11822 
11823 	minor = getminor(dev);
11824 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
11825 	un = ddi_get_soft_state(st_state, instance);
11826 	if (un) {
11827 		ST_FUNC(ST_DEVINFO, st_dev_name);
11828 	}
11829 
11830 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
11831 
11832 	if (minor & MT_BSD) {
11833 		name[++nprt] = 'b';
11834 	}
11835 
11836 	if (minor & MT_NOREWIND) {
11837 		name[++nprt] = 'n';
11838 	}
11839 
11840 	/* NULL terminator */
11841 	name[++nprt] = 0;
11842 
11843 	return (name);
11844 }
11845 #endif	/* STDEBUG */
11846 
11847 /*
11848  * Soft error reporting, so far unique to each drive
11849  *
11850  * Currently supported: exabyte and DAT soft error reporting
11851  */
11852 static int
11853 st_report_exabyte_soft_errors(dev_t dev, int flag)
11854 {
11855 	uchar_t *sensep;
11856 	int amt;
11857 	int rval = 0;
11858 	char cdb[CDB_GROUP0], *c = cdb;
11859 	struct uscsi_cmd *com;
11860 
11861 	GET_SOFT_STATE(dev);
11862 
11863 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
11864 
11865 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11866 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
11867 	    dev, flag);
11868 
11869 	ASSERT(mutex_owned(ST_MUTEX));
11870 
11871 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
11872 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
11873 
11874 	*c++ = SCMD_REQUEST_SENSE;
11875 	*c++ = 0;
11876 	*c++ = 0;
11877 	*c++ = 0;
11878 	*c++ = TAPE_SENSE_LENGTH;
11879 	/*
11880 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
11881 	 */
11882 	*c   = (char)0x80;
11883 
11884 	com->uscsi_cdb = cdb;
11885 	com->uscsi_cdblen = CDB_GROUP0;
11886 	com->uscsi_bufaddr = (caddr_t)sensep;
11887 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
11888 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11889 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11890 
11891 	rval = st_uscsi_cmd(un, com, FKIOCTL);
11892 	if (rval || com->uscsi_status) {
11893 		goto done;
11894 	}
11895 
11896 	/*
11897 	 * was there enough data?
11898 	 */
11899 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
11900 
11901 	if ((amt >= 19) && un->un_kbytes_xferred) {
11902 		uint_t count, error_rate;
11903 		uint_t rate;
11904 
11905 		if (sensep[21] & CLN) {
11906 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11907 			    "Periodic head cleaning required");
11908 		}
11909 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
11910 			goto done;
11911 		}
11912 		/*
11913 		 * check if soft error reporting needs to be done.
11914 		 */
11915 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
11916 		count &= 0xffffff;
11917 		error_rate = (count * 100)/un->un_kbytes_xferred;
11918 
11919 #ifdef	STDEBUG
11920 		if (st_soft_error_report_debug) {
11921 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11922 			    "Exabyte Soft Error Report:\n");
11923 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11924 			    "read/write error counter: %d\n", count);
11925 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11926 			    "number of bytes transferred: %dK\n",
11927 			    un->un_kbytes_xferred);
11928 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11929 			    "error_rate: %d%%\n", error_rate);
11930 
11931 			if (amt >= 22) {
11932 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11933 				    "unit sense: 0x%b 0x%b 0x%b\n",
11934 				    sensep[19], SENSE_19_BITS,
11935 				    sensep[20], SENSE_20_BITS,
11936 				    sensep[21], SENSE_21_BITS);
11937 			}
11938 			if (amt >= 27) {
11939 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11940 				    "tracking retry counter: %d\n",
11941 				    sensep[26]);
11942 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
11943 				    "read/write retry counter: %d\n",
11944 				    sensep[27]);
11945 			}
11946 		}
11947 #endif
11948 
11949 		if (flag & FWRITE) {
11950 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
11951 		} else {
11952 			rate = EXABYTE_READ_ERROR_THRESHOLD;
11953 		}
11954 		if (error_rate >= rate) {
11955 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11956 			    "Soft error rate (%d%%) during %s was too high",
11957 			    error_rate,
11958 			    ((flag & FWRITE) ? wrg_str : rdg_str));
11959 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11960 			    "Please, replace tape cartridge\n");
11961 		}
11962 	}
11963 
11964 done:
11965 	kmem_free(com, sizeof (*com));
11966 	kmem_free(sensep, TAPE_SENSE_LENGTH);
11967 
11968 	if (rval != 0) {
11969 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
11970 		    "exabyte soft error reporting failed\n");
11971 	}
11972 	return (rval);
11973 }
11974 
11975 /*
11976  * this is very specific to Archive 4mm dat
11977  */
11978 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
11979 
11980 static int
11981 st_report_dat_soft_errors(dev_t dev, int flag)
11982 {
11983 	uchar_t *sensep;
11984 	int amt, i;
11985 	int rval = 0;
11986 	char cdb[CDB_GROUP1], *c = cdb;
11987 	struct uscsi_cmd *com;
11988 
11989 	GET_SOFT_STATE(dev);
11990 
11991 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
11992 
11993 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11994 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
11995 
11996 	ASSERT(mutex_owned(ST_MUTEX));
11997 
11998 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
11999 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12000 
12001 	*c++ = SCMD_LOG_SENSE_G1;
12002 	*c++ = 0;
12003 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
12004 	*c++ = 0;
12005 	*c++ = 0;
12006 	*c++ = 0;
12007 	*c++ = 2;
12008 	*c++ = 0;
12009 	*c++ = (char)LOG_SENSE_LENGTH;
12010 	*c   = 0;
12011 	com->uscsi_cdb    = cdb;
12012 	com->uscsi_cdblen  = CDB_GROUP1;
12013 	com->uscsi_bufaddr = (caddr_t)sensep;
12014 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
12015 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12016 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12017 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12018 	if (rval) {
12019 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12020 		    "DAT soft error reporting failed\n");
12021 	}
12022 	if (rval || com->uscsi_status) {
12023 		goto done;
12024 	}
12025 
12026 	/*
12027 	 * was there enough data?
12028 	 */
12029 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
12030 
12031 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
12032 		int total, retries, param_code;
12033 
12034 		total = -1;
12035 		retries = -1;
12036 		amt = sensep[3] + 4;
12037 
12038 
12039 #ifdef STDEBUG
12040 		if (st_soft_error_report_debug) {
12041 			(void) printf("logsense:");
12042 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
12043 				if (i % 16 == 0) {
12044 					(void) printf("\t\n");
12045 				}
12046 				(void) printf(" %x", sensep[i]);
12047 			}
12048 			(void) printf("\n");
12049 		}
12050 #endif
12051 
12052 		/*
12053 		 * parse the param_codes
12054 		 */
12055 		if (sensep[0] == 2 || sensep[0] == 3) {
12056 			for (i = 4; i < amt; i++) {
12057 				param_code = (sensep[i++] << 8);
12058 				param_code += sensep[i++];
12059 				i++; /* skip control byte */
12060 				if (param_code == 5) {
12061 					if (sensep[i++] == 4) {
12062 						total = (sensep[i++] << 24);
12063 						total += (sensep[i++] << 16);
12064 						total += (sensep[i++] << 8);
12065 						total += sensep[i];
12066 					}
12067 				} else if (param_code == 0x8007) {
12068 					if (sensep[i++] == 2) {
12069 						retries = sensep[i++] << 8;
12070 						retries += sensep[i];
12071 					}
12072 				} else {
12073 					i += sensep[i];
12074 				}
12075 			}
12076 		}
12077 
12078 		/*
12079 		 * if the log sense returned valid numbers then determine
12080 		 * the read and write error thresholds based on the amount of
12081 		 * data transferred
12082 		 */
12083 
12084 		if (total > 0 && retries > 0) {
12085 			short normal_retries = 0;
12086 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12087 			    "total xferred (%s) =%x, retries=%x\n",
12088 			    ((flag & FWRITE) ? wrg_str : rdg_str),
12089 			    total, retries);
12090 
12091 			if (flag & FWRITE) {
12092 				if (total <=
12093 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
12094 					normal_retries =
12095 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
12096 				} else {
12097 					normal_retries =
12098 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
12099 				}
12100 			} else {
12101 				if (total <=
12102 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
12103 					normal_retries =
12104 					    DAT_SMALL_READ_ERROR_THRESHOLD;
12105 				} else {
12106 					normal_retries =
12107 					    DAT_LARGE_READ_ERROR_THRESHOLD;
12108 				}
12109 			}
12110 
12111 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12112 			"normal retries=%d\n", normal_retries);
12113 
12114 			if (retries >= normal_retries) {
12115 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12116 				    "Soft error rate (retries = %d) during "
12117 				    "%s was too high",  retries,
12118 				    ((flag & FWRITE) ? wrg_str : rdg_str));
12119 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12120 				    "Periodic head cleaning required "
12121 				    "and/or replace tape cartridge\n");
12122 			}
12123 
12124 		} else if (total == -1 || retries == -1) {
12125 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12126 			    "log sense parameter code does not make sense\n");
12127 		}
12128 	}
12129 
12130 	/*
12131 	 * reset all values
12132 	 */
12133 	c = cdb;
12134 	*c++ = SCMD_LOG_SELECT_G1;
12135 	*c++ = 2;	/* this resets all values */
12136 	*c++ = (char)0xc0;
12137 	*c++ = 0;
12138 	*c++ = 0;
12139 	*c++ = 0;
12140 	*c++ = 0;
12141 	*c++ = 0;
12142 	*c++ = 0;
12143 	*c   = 0;
12144 	com->uscsi_bufaddr = NULL;
12145 	com->uscsi_buflen  = 0;
12146 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
12147 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12148 	if (rval) {
12149 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12150 		    "DAT soft error reset failed\n");
12151 	}
12152 done:
12153 	kmem_free(com, sizeof (*com));
12154 	kmem_free(sensep, LOG_SENSE_LENGTH);
12155 	return (rval);
12156 }
12157 
12158 static int
12159 st_report_soft_errors(dev_t dev, int flag)
12160 {
12161 	GET_SOFT_STATE(dev);
12162 
12163 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
12164 
12165 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12166 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12167 
12168 	ASSERT(mutex_owned(ST_MUTEX));
12169 
12170 	switch (un->un_dp->type) {
12171 	case ST_TYPE_EXB8500:
12172 	case ST_TYPE_EXABYTE:
12173 		return (st_report_exabyte_soft_errors(dev, flag));
12174 		/*NOTREACHED*/
12175 	case ST_TYPE_PYTHON:
12176 		return (st_report_dat_soft_errors(dev, flag));
12177 		/*NOTREACHED*/
12178 	default:
12179 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
12180 		return (-1);
12181 	}
12182 }
12183 
12184 /*
12185  * persistent error routines
12186  */
12187 
12188 /*
12189  * enable persistent errors, and set the throttle appropriately, checking
12190  * for flush-on-errors capability
12191  */
12192 static void
12193 st_turn_pe_on(struct scsi_tape *un)
12194 {
12195 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
12196 
12197 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
12198 	ASSERT(mutex_owned(ST_MUTEX));
12199 
12200 	un->un_persistence = 1;
12201 
12202 	/*
12203 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
12204 	 * enabled.  This will simplify the error handling for request senses
12205 	 */
12206 
12207 	if (un->un_arq_enabled && un->un_untagged_qing) {
12208 		uchar_t f_o_e;
12209 
12210 		mutex_exit(ST_MUTEX);
12211 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
12212 		    1 : 0;
12213 		mutex_enter(ST_MUTEX);
12214 
12215 		un->un_flush_on_errors = f_o_e;
12216 	} else {
12217 		un->un_flush_on_errors = 0;
12218 	}
12219 
12220 	if (un->un_flush_on_errors)
12221 		un->un_max_throttle = (uchar_t)st_max_throttle;
12222 	else
12223 		un->un_max_throttle = 1;
12224 
12225 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
12226 		un->un_max_throttle = 1;
12227 
12228 	/* this will send a marker pkt */
12229 	st_clear_pe(un);
12230 }
12231 
12232 /*
12233  * This turns persistent errors permanently off
12234  */
12235 static void
12236 st_turn_pe_off(struct scsi_tape *un)
12237 {
12238 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
12239 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
12240 	ASSERT(mutex_owned(ST_MUTEX));
12241 
12242 	/* turn it off for good */
12243 	un->un_persistence = 0;
12244 
12245 	/* this will send a marker pkt */
12246 	st_clear_pe(un);
12247 
12248 	/* turn off flush on error capability, if enabled */
12249 	if (un->un_flush_on_errors) {
12250 		mutex_exit(ST_MUTEX);
12251 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
12252 		mutex_enter(ST_MUTEX);
12253 	}
12254 
12255 
12256 	un->un_flush_on_errors = 0;
12257 }
12258 
12259 /*
12260  * This clear persistent errors, allowing more commands through, and also
12261  * sending a marker packet.
12262  */
12263 static void
12264 st_clear_pe(struct scsi_tape *un)
12265 {
12266 	ST_FUNC(ST_DEVINFO, st_clear_pe);
12267 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
12268 	ASSERT(mutex_owned(ST_MUTEX));
12269 
12270 	un->un_persist_errors = 0;
12271 	un->un_throttle = un->un_last_throttle = 1;
12272 	un->un_errno = 0;
12273 	st_hba_unflush(un);
12274 }
12275 
12276 /*
12277  * This will flag persistent errors, shutting everything down, if the
12278  * application had enabled persistent errors via MTIOCPERSISTENT
12279  */
12280 static void
12281 st_set_pe_flag(struct scsi_tape *un)
12282 {
12283 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
12284 	ASSERT(mutex_owned(ST_MUTEX));
12285 
12286 	if (un->un_persistence) {
12287 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
12288 		un->un_persist_errors = 1;
12289 		un->un_throttle = un->un_last_throttle = 0;
12290 		cv_broadcast(&un->un_sbuf_cv);
12291 	}
12292 }
12293 
12294 static int
12295 st_do_reserve(struct scsi_tape *un)
12296 {
12297 	int rval;
12298 
12299 	ST_FUNC(ST_DEVINFO, st_do_reserve);
12300 
12301 	/*
12302 	 * Issue a Throw-Away reserve command to clear the
12303 	 * check condition.
12304 	 * If the current behaviour of reserve/release is to
12305 	 * hold reservation across opens , and if a Bus reset
12306 	 * has been issued between opens then this command
12307 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
12308 	 * In this case return an EACCES so that user knows that
12309 	 * reservation has been lost in between opens.
12310 	 * If this error is not returned and we continue with
12311 	 * successful open , then user may think position of the
12312 	 * tape is still the same but inreality we would rewind the
12313 	 * tape and continue from BOT.
12314 	 */
12315 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12316 	if (rval) {
12317 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
12318 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
12319 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
12320 			un->un_errno = EACCES;
12321 			return (EACCES);
12322 		}
12323 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12324 	}
12325 	if (rval == 0) {
12326 		un->un_rsvd_status |= ST_INIT_RESERVE;
12327 	}
12328 
12329 	return (rval);
12330 }
12331 
12332 static int
12333 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb)
12334 {
12335 	int rval;
12336 	cmd_attribute const *attrib;
12337 
12338 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
12339 
12340 	/*
12341 	 * If already reserved no need to do it again.
12342 	 * Also if Reserve and Release are disabled Just return.
12343 	 */
12344 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12345 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12346 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12347 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12348 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
12349 		    st_print_scsi_cmd((uchar_t)cdb[0]));
12350 		return (0);
12351 	}
12352 
12353 	/* See if command is on the list */
12354 	attrib = st_lookup_cmd_attribute(cdb[0]);
12355 
12356 	if (attrib == NULL) {
12357 		rval = 1; /* Not found, when in doubt reserve */
12358 	} else if ((attrib->requires_reserve) != 0) {
12359 		rval = 1;
12360 	} else if ((attrib->reserve_byte) != 0) {
12361 		/*
12362 		 * cmd is on list.
12363 		 * if byte is zero always allowed.
12364 		 */
12365 		rval = 1;
12366 	} else if (((cdb[attrib->reserve_byte]) &
12367 	    (attrib->reserve_mask)) != 0) {
12368 		rval = 1;
12369 	} else {
12370 		rval = 0;
12371 	}
12372 
12373 	if (rval) {
12374 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12375 		    "Command %s requires reservation",
12376 		    st_print_scsi_cmd(cdb[0]));
12377 
12378 		rval = st_do_reserve(un);
12379 	}
12380 
12381 	return (rval);
12382 }
12383 
12384 static int
12385 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
12386 {
12387 	int rval;
12388 	cmd_attribute const *attrib;
12389 
12390 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
12391 
12392 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12393 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12394 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12395 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12396 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
12397 		    st_print_scsi_cmd(cmd));
12398 		return (0);
12399 	}
12400 
12401 	/* search for this command on the list */
12402 	attrib = st_lookup_cmd_attribute(cmd);
12403 
12404 	if (attrib == NULL) {
12405 		rval = 1; /* Not found, when in doubt reserve */
12406 	} else if ((attrib->requires_reserve) != 0) {
12407 		rval = 1;
12408 	} else if ((attrib->reserve_byte) != 0) {
12409 		/*
12410 		 * cmd is on list.
12411 		 * if byte is zero always allowed.
12412 		 */
12413 		rval = 1;
12414 	} else if (((attrib->reserve_mask) & cnt) != 0) {
12415 		rval = 1;
12416 	} else {
12417 		rval = 0;
12418 	}
12419 
12420 	if (rval) {
12421 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12422 		    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
12423 
12424 		rval = st_do_reserve(un);
12425 	}
12426 
12427 	return (rval);
12428 }
12429 
12430 static int
12431 st_reserve_release(struct scsi_tape *un, int cmd, ubufunc_t ubf)
12432 {
12433 	struct uscsi_cmd	uscsi_cmd;
12434 	int			rval;
12435 	char			cdb[CDB_GROUP0];
12436 	struct scsi_arq_status	stat;
12437 
12438 
12439 
12440 	ST_FUNC(ST_DEVINFO, st_reserve_release);
12441 
12442 	ASSERT(mutex_owned(ST_MUTEX));
12443 
12444 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12445 	    "st_reserve_release: %s \n",
12446 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
12447 
12448 	bzero(&cdb, CDB_GROUP0);
12449 	if (cmd == ST_RELEASE) {
12450 		cdb[0] = SCMD_RELEASE;
12451 	} else {
12452 		cdb[0] = SCMD_RESERVE;
12453 	}
12454 	bzero(&uscsi_cmd, sizeof (struct uscsi_cmd));
12455 	uscsi_cmd.uscsi_flags = USCSI_WRITE | USCSI_RQENABLE;
12456 	uscsi_cmd.uscsi_cdb = cdb;
12457 	uscsi_cmd.uscsi_cdblen = CDB_GROUP0;
12458 	uscsi_cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
12459 	uscsi_cmd.uscsi_rqbuf = (caddr_t)&stat;
12460 	uscsi_cmd.uscsi_rqlen = sizeof (stat);
12461 
12462 	rval = ubf(un, &uscsi_cmd, FKIOCTL);
12463 
12464 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12465 	    "st_reserve_release: rval(1)=%d\n", rval);
12466 
12467 	if (rval) {
12468 		if (uscsi_cmd.uscsi_status == STATUS_RESERVATION_CONFLICT) {
12469 			rval = EACCES;
12470 		}
12471 		/*
12472 		 * dynamically turn off reserve/release support
12473 		 * in case of drives which do not support
12474 		 * reserve/release command(ATAPI drives).
12475 		 */
12476 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
12477 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
12478 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
12479 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12480 				    "Tape unit does not support "
12481 				    "reserve/release \n");
12482 			}
12483 			rval = 0;
12484 		}
12485 	}
12486 	return (rval);
12487 }
12488 
12489 static int
12490 st_take_ownership(struct scsi_tape *un)
12491 {
12492 	int rval;
12493 
12494 	ST_FUNC(ST_DEVINFO, st_take_ownership);
12495 
12496 	ASSERT(mutex_owned(ST_MUTEX));
12497 
12498 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12499 	    "st_take_ownership: Entering ...\n");
12500 
12501 
12502 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12503 	/*
12504 	 * XXX -> Should reset be done only if we get EACCES.
12505 	 * .
12506 	 */
12507 	if (rval) {
12508 		if (st_reset(un, RESET_LUN) == 0) {
12509 			return (EIO);
12510 		}
12511 		un->un_rsvd_status &=
12512 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
12513 
12514 		mutex_exit(ST_MUTEX);
12515 		delay(drv_usectohz(ST_RESERVATION_DELAY));
12516 		mutex_enter(ST_MUTEX);
12517 		/*
12518 		 * remove the check condition.
12519 		 */
12520 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12521 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12522 		if (rval != 0) {
12523 			if ((st_reserve_release(un, ST_RESERVE, st_uscsi_cmd))
12524 			    != 0) {
12525 				rval = (un->un_rsvd_status &
12526 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
12527 				return (rval);
12528 			}
12529 		}
12530 		/*
12531 		 * Set tape state to ST_STATE_OFFLINE , in case if
12532 		 * the user wants to continue and start using
12533 		 * the tape.
12534 		 */
12535 		un->un_state = ST_STATE_OFFLINE;
12536 		un->un_rsvd_status |= ST_INIT_RESERVE;
12537 	}
12538 	return (rval);
12539 }
12540 
12541 static int
12542 st_create_errstats(struct scsi_tape *un, int instance)
12543 {
12544 	char	kstatname[KSTAT_STRLEN];
12545 
12546 	ST_FUNC(ST_DEVINFO, st_create_errstats);
12547 
12548 	/*
12549 	 * Create device error kstats
12550 	 */
12551 
12552 	if (un->un_errstats == (kstat_t *)0) {
12553 		(void) sprintf(kstatname, "st%d,err", instance);
12554 		un->un_errstats = kstat_create("sterr", instance, kstatname,
12555 		    "device_error", KSTAT_TYPE_NAMED,
12556 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
12557 		    KSTAT_FLAG_PERSISTENT);
12558 
12559 		if (un->un_errstats) {
12560 			struct st_errstats	*stp;
12561 
12562 			stp = (struct st_errstats *)un->un_errstats->ks_data;
12563 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
12564 			    KSTAT_DATA_ULONG);
12565 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
12566 			    KSTAT_DATA_ULONG);
12567 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
12568 			    KSTAT_DATA_ULONG);
12569 			kstat_named_init(&stp->st_vid, "Vendor",
12570 			    KSTAT_DATA_CHAR);
12571 			kstat_named_init(&stp->st_pid, "Product",
12572 			    KSTAT_DATA_CHAR);
12573 			kstat_named_init(&stp->st_revision, "Revision",
12574 			    KSTAT_DATA_CHAR);
12575 			kstat_named_init(&stp->st_serial, "Serial No",
12576 			    KSTAT_DATA_CHAR);
12577 			un->un_errstats->ks_private = un;
12578 			un->un_errstats->ks_update = nulldev;
12579 			kstat_install(un->un_errstats);
12580 			/*
12581 			 * Fill in the static data
12582 			 */
12583 			(void) strncpy(&stp->st_vid.value.c[0],
12584 			    ST_INQUIRY->inq_vid, 8);
12585 			/*
12586 			 * XXX:  Emulex MT-02 (and emulators) predates
12587 			 *	 SCSI-1 and has no vid & pid inquiry data.
12588 			 */
12589 			if (ST_INQUIRY->inq_len != 0) {
12590 				(void) strncpy(&stp->st_pid.value.c[0],
12591 				    ST_INQUIRY->inq_pid, 16);
12592 				(void) strncpy(&stp->st_revision.value.c[0],
12593 				    ST_INQUIRY->inq_revision, 4);
12594 				(void) strncpy(&stp->st_serial.value.c[0],
12595 				    ST_INQUIRY->inq_serial, 12);
12596 			}
12597 		}
12598 	}
12599 	return (0);
12600 }
12601 
12602 static int
12603 st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos)
12604 {
12605 	int rval;
12606 	bufunc_t bf = (ubf == st_uscsi_rcmd) ? st_rcmd : st_cmd;
12607 
12608 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
12609 
12610 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
12611 	ASSERT(mutex_owned(ST_MUTEX));
12612 
12613 	/* Can't restore an invalid position */
12614 	if (pos->pmode == invalid) {
12615 		return (4);
12616 	}
12617 
12618 	/*
12619 	 * Assumtions:
12620 	 *	If a position was read and is in logical position mode.
12621 	 *	If a drive supports read position it supports locate.
12622 	 *	If the read position type is not NO_POS. even though
12623 	 *	   a read position make not have been attemped yet.
12624 	 *
12625 	 *	The drive can locate to the position.
12626 	 */
12627 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
12628 		/*
12629 		 * If position mode is logical or legacy mode try
12630 		 * to locate there as it is faster.
12631 		 * If it fails try the old way.
12632 		 */
12633 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12634 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
12635 		    pos->lgclblkno);
12636 
12637 		if (st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
12638 		    pos->lgclblkno, pos->partition) == 0) {
12639 			/* Assume we are there copy rest of position back */
12640 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
12641 				COPY_POS(&un->un_pos, pos);
12642 			}
12643 			return (0);
12644 		}
12645 
12646 		/*
12647 		 * If logical block locate failed to restore a logical
12648 		 * position, can't recover.
12649 		 */
12650 		if (pos->pmode == logical) {
12651 			return (-1);
12652 		}
12653 	}
12654 
12655 
12656 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12657 	    "Restoring tape position at fileno=%x, blkno=%x....",
12658 	    pos->fileno, pos->blkno);
12659 
12660 	/*
12661 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
12662 	 * so as not to rewind tape on RESETS: Gee, Has life ever
12663 	 * been simple in tape land ?
12664 	 */
12665 	rval = bf(un, SCMD_REWIND, 0, SYNC_CMD);
12666 	if (rval) {
12667 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12668 		    "Failed to restore the last file and block position: In"
12669 		    " this state, Tape will be loaded at BOT during next open");
12670 		un->un_pos.pmode = invalid;
12671 		return (rval);
12672 	}
12673 
12674 	/* If the position was as the result of back space file */
12675 	if (pos->blkno > (INF / 2)) {
12676 		/* Go one extra file forward */
12677 		pos->fileno++;
12678 		/* Figure how many blocks to back into the previous file */
12679 		pos->blkno = -(INF - pos->blkno);
12680 	}
12681 
12682 	/* Go to requested fileno */
12683 	if (pos->fileno) {
12684 		rval = st_cmd(un, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
12685 		if (rval) {
12686 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12687 			    "Failed to restore the last file position: In this "
12688 			    " state, Tape will be loaded at BOT during next"
12689 			    " open %d", __LINE__);
12690 			un->un_pos.pmode = invalid;
12691 			pos->pmode = invalid;
12692 			return (rval);
12693 		}
12694 	}
12695 
12696 	/*
12697 	 * If backing into a file we already did an extra file forward.
12698 	 * Now we have to back over the filemark to get to the end of
12699 	 * the previous file. The blkno has been ajusted to a negative
12700 	 * value so we will get to the expected location.
12701 	 */
12702 	if (pos->blkno) {
12703 		rval = bf(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
12704 		if (rval) {
12705 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12706 			    "Failed to restore the last file position: In this "
12707 			    " state, Tape will be loaded at BOT during next"
12708 			    " open %d", __LINE__);
12709 			un->un_pos.pmode = invalid;
12710 			pos->pmode = invalid;
12711 			return (rval);
12712 		}
12713 	}
12714 
12715 	/*
12716 	 * The position mode, block and fileno should be correct,
12717 	 * This updates eof and logical position information.
12718 	 */
12719 	un->un_pos.eof = pos->eof;
12720 	un->un_pos.lgclblkno = pos->lgclblkno;
12721 
12722 	return (0);
12723 }
12724 
12725 /*
12726  * check sense key, ASC, ASCQ in order to determine if the tape needs
12727  * to be ejected
12728  */
12729 
12730 static int
12731 st_check_asc_ascq(struct scsi_tape *un)
12732 {
12733 	struct scsi_extended_sense *sensep = ST_RQSENSE;
12734 	struct tape_failure_code   *code;
12735 
12736 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
12737 
12738 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
12739 		if ((code->key  == sensep->es_key) &&
12740 		    (code->add_code  == sensep->es_add_code) &&
12741 		    (code->qual_code == sensep->es_qual_code))
12742 			return (1);
12743 	}
12744 	return (0);
12745 }
12746 
12747 /*
12748  * st_logpage_supported() sends a Log Sense command with
12749  * page code = 0 = Supported Log Pages Page to the device,
12750  * to see whether the page 'page' is supported.
12751  * Return values are:
12752  * -1 if the Log Sense command fails
12753  * 0 if page is not supported
12754  * 1 if page is supported
12755  */
12756 
12757 static int
12758 st_logpage_supported(struct scsi_tape *un, uchar_t page)
12759 {
12760 	uchar_t *sp, *sensep;
12761 	unsigned length;
12762 	struct uscsi_cmd *com;
12763 	int rval;
12764 	char cdb[CDB_GROUP1] = {
12765 		SCMD_LOG_SENSE_G1,
12766 		0,
12767 		SUPPORTED_LOG_PAGES_PAGE,
12768 		0,
12769 		0,
12770 		0,
12771 		0,
12772 		0,
12773 		(char)LOG_SENSE_LENGTH,
12774 		0
12775 	};
12776 
12777 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
12778 
12779 	ASSERT(mutex_owned(ST_MUTEX));
12780 
12781 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12782 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12783 
12784 	com->uscsi_cdb = cdb;
12785 	com->uscsi_cdblen = CDB_GROUP1;
12786 	com->uscsi_bufaddr = (caddr_t)sensep;
12787 	com->uscsi_buflen = LOG_SENSE_LENGTH;
12788 	com->uscsi_flags =
12789 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12790 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12791 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12792 	if (rval || com->uscsi_status) {
12793 		/* uscsi-command failed */
12794 		rval = -1;
12795 	} else {
12796 
12797 		sp = sensep + 3;
12798 
12799 		for (length = *sp++; length > 0; length--, sp++) {
12800 
12801 			if (*sp == page) {
12802 				rval = 1;
12803 				break;
12804 			}
12805 		}
12806 	}
12807 	kmem_free(com, sizeof (struct uscsi_cmd));
12808 	kmem_free(sensep, LOG_SENSE_LENGTH);
12809 	return (rval);
12810 }
12811 
12812 
12813 /*
12814  * st_check_clean_bit() gets the status of the tape's cleaning bit.
12815  *
12816  * If the device does support the TapeAlert log page, then the cleaning bit
12817  * information will be read from this page. Otherwise we will see if one of
12818  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
12819  * the device, which means, that we can get the cleaning bit information via
12820  * a RequestSense command.
12821  * If both methods of getting cleaning bit information are not supported
12822  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
12823  * returns with
12824  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
12825  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
12826  * If the call to st_uscsi_cmd() to do the Log Sense or the Request Sense
12827  * command fails, or if the amount of Request Sense data is not enough, then
12828  *  st_check_clean_bit() returns with -1.
12829  */
12830 
12831 static int
12832 st_check_clean_bit(struct scsi_tape *un)
12833 {
12834 	int rval = 0;
12835 
12836 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
12837 
12838 	ASSERT(mutex_owned(ST_MUTEX));
12839 
12840 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
12841 		return (rval);
12842 	}
12843 
12844 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
12845 
12846 		rval = st_logpage_supported(un, TAPE_SEQUENTIAL_PAGE);
12847 		if (rval == 1) {
12848 
12849 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
12850 		}
12851 
12852 		rval = st_logpage_supported(un, TAPE_ALERT_PAGE);
12853 		if (rval == 1) {
12854 
12855 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
12856 		}
12857 
12858 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
12859 
12860 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
12861 		}
12862 	}
12863 
12864 	rval = 0;
12865 
12866 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
12867 
12868 		rval = st_check_sequential_clean_bit(un);
12869 	}
12870 
12871 	if ((rval <= 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
12872 
12873 		rval = st_check_alert_flags(un);
12874 	}
12875 
12876 	if ((rval <= 0) && (un->un_dp->options & ST_CLN_MASK)) {
12877 
12878 		rval = st_check_sense_clean_bit(un);
12879 	}
12880 
12881 	if (rval < 0) {
12882 		return (rval);
12883 	}
12884 
12885 	/*
12886 	 * If found a supported means to check need to clean.
12887 	 */
12888 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
12889 
12890 		/*
12891 		 * head needs to be cleaned.
12892 		 */
12893 		if (rval & MTF_TAPE_HEAD_DIRTY) {
12894 
12895 			/*
12896 			 * Print log message only first time
12897 			 * found needing cleaned.
12898 			 */
12899 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
12900 
12901 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12902 				    "Periodic head cleaning required");
12903 
12904 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
12905 			}
12906 
12907 		} else {
12908 
12909 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
12910 		}
12911 	}
12912 
12913 	return (rval);
12914 }
12915 
12916 
12917 static int
12918 st_check_sequential_clean_bit(struct scsi_tape *un)
12919 {
12920 	int rval;
12921 	int ix;
12922 	ushort_t parameter;
12923 	struct uscsi_cmd *cmd;
12924 	struct log_sequential_page *sp;
12925 	struct log_sequential_page_parameter *prm;
12926 	char cdb[CDB_GROUP1] = {
12927 		SCMD_LOG_SENSE_G1,
12928 		0,
12929 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
12930 		0,
12931 		0,
12932 		0,
12933 		0,
12934 		(char)(sizeof (struct log_sequential_page) >> 8),
12935 		(char)(sizeof (struct log_sequential_page)),
12936 		0
12937 	};
12938 
12939 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
12940 
12941 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12942 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
12943 
12944 	cmd->uscsi_flags   =
12945 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12946 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12947 	cmd->uscsi_cdb	   = cdb;
12948 	cmd->uscsi_cdblen  = CDB_GROUP1;
12949 	cmd->uscsi_bufaddr = (caddr_t)sp;
12950 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
12951 
12952 	rval = st_uscsi_cmd(un, cmd, FKIOCTL);
12953 
12954 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
12955 
12956 		rval = -1;
12957 
12958 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
12959 
12960 		rval = -1;
12961 	}
12962 
12963 	prm = &sp->param[0];
12964 
12965 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
12966 
12967 		if (prm->log_param.length == 0) {
12968 			break;
12969 		}
12970 
12971 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
12972 		    (prm->log_param.pc_lo & 0xff));
12973 
12974 		if (parameter == SEQUENTIAL_NEED_CLN) {
12975 
12976 			rval = MTF_TAPE_CLN_SUPPORTED;
12977 			if (prm->param_value[prm->log_param.length - 1]) {
12978 
12979 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12980 				    "sequential log says head dirty\n");
12981 				rval |= MTF_TAPE_HEAD_DIRTY;
12982 			}
12983 		}
12984 		prm = (struct log_sequential_page_parameter *)
12985 		    &prm->param_value[prm->log_param.length];
12986 	}
12987 
12988 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12989 	kmem_free(sp,  sizeof (struct log_sequential_page));
12990 
12991 	return (rval);
12992 }
12993 
12994 
12995 static int
12996 st_check_alert_flags(struct scsi_tape *un)
12997 {
12998 	struct st_tape_alert *ta;
12999 	struct uscsi_cmd *com;
13000 	unsigned ix, length;
13001 	int rval;
13002 	tape_alert_flags flag;
13003 	char cdb[CDB_GROUP1] = {
13004 		SCMD_LOG_SENSE_G1,
13005 		0,
13006 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
13007 		0,
13008 		0,
13009 		0,
13010 		0,
13011 		(char)(sizeof (struct st_tape_alert) >> 8),
13012 		(char)(sizeof (struct st_tape_alert)),
13013 		0
13014 	};
13015 
13016 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
13017 
13018 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13019 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
13020 
13021 	com->uscsi_cdb = cdb;
13022 	com->uscsi_cdblen = CDB_GROUP1;
13023 	com->uscsi_bufaddr = (caddr_t)ta;
13024 	com->uscsi_buflen = sizeof (struct st_tape_alert);
13025 	com->uscsi_flags =
13026 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13027 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13028 
13029 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13030 
13031 	if (rval || com->uscsi_status || com->uscsi_resid) {
13032 
13033 		rval = -1; /* uscsi-command failed */
13034 
13035 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
13036 
13037 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13038 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
13039 		rval = -1;
13040 	}
13041 
13042 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
13043 
13044 
13045 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
13046 
13047 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13048 		    "TapeAlert length %d\n", length);
13049 	}
13050 
13051 
13052 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
13053 
13054 		/*
13055 		 * if rval is bad before the first pass don't bother
13056 		 */
13057 		if (ix == 0 && rval != 0) {
13058 
13059 			break;
13060 		}
13061 
13062 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
13063 		    ta->param[ix].log_param.pc_lo);
13064 
13065 		if ((ta->param[ix].param_value & 1) == 0) {
13066 			continue;
13067 		}
13068 		/*
13069 		 * check to see if current parameter is of interest.
13070 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
13071 		 */
13072 		if ((flag == TAF_CLEAN_NOW) ||
13073 		    (flag == TAF_CLEAN_PERIODIC) ||
13074 		    ((flag == CLEAN_FOR_ERRORS) &&
13075 		    (un->un_dp->type == ST_TYPE_STK9840))) {
13076 
13077 			rval = MTF_TAPE_CLN_SUPPORTED;
13078 
13079 
13080 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13081 			    "alert_page drive needs clean %d\n", flag);
13082 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
13083 			rval |= MTF_TAPE_HEAD_DIRTY;
13084 
13085 		} else if (flag == TAF_CLEANING_MEDIA) {
13086 
13087 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13088 			    "alert_page drive was cleaned\n");
13089 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
13090 		}
13091 
13092 	}
13093 
13094 	/*
13095 	 * Report it as dirty till we see it cleaned
13096 	 */
13097 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
13098 
13099 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13100 		    "alert_page still dirty\n");
13101 		rval |= MTF_TAPE_HEAD_DIRTY;
13102 	}
13103 
13104 	kmem_free(com, sizeof (struct uscsi_cmd));
13105 	kmem_free(ta,  sizeof (struct st_tape_alert));
13106 
13107 	return (rval);
13108 }
13109 
13110 
13111 static int
13112 st_check_sense_clean_bit(struct scsi_tape *un)
13113 {
13114 	uchar_t *sensep;
13115 	char cdb[CDB_GROUP0];
13116 	struct uscsi_cmd *com;
13117 	ushort_t byte_pos;
13118 	uchar_t bit_mask;
13119 	unsigned length;
13120 	int index;
13121 	int rval;
13122 
13123 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
13124 
13125 	/*
13126 	 * Since this tape does not support Tape Alert,
13127 	 * we now try to get the cleanbit status via
13128 	 * Request Sense.
13129 	 */
13130 
13131 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
13132 
13133 		index = 0;
13134 
13135 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
13136 
13137 		index = 1;
13138 
13139 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
13140 
13141 		index = 2;
13142 
13143 	} else {
13144 
13145 		return (-1);
13146 	}
13147 
13148 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
13149 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
13150 	length = byte_pos + 1;
13151 
13152 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13153 	sensep = kmem_zalloc(length, KM_SLEEP);
13154 
13155 	cdb[0] = SCMD_REQUEST_SENSE;
13156 	cdb[1] = 0;
13157 	cdb[2] = 0;
13158 	cdb[3] = 0;
13159 	cdb[4] = (char)length;
13160 	cdb[5] = 0;
13161 
13162 	com->uscsi_cdb = cdb;
13163 	com->uscsi_cdblen = CDB_GROUP0;
13164 	com->uscsi_bufaddr = (caddr_t)sensep;
13165 	com->uscsi_buflen = length;
13166 	com->uscsi_flags =
13167 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13168 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13169 
13170 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13171 
13172 	if (rval || com->uscsi_status || com->uscsi_resid) {
13173 
13174 		rval = -1;
13175 
13176 	} else {
13177 
13178 		rval = MTF_TAPE_CLN_SUPPORTED;
13179 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
13180 
13181 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13182 			    "sense data says head dirty\n");
13183 			rval |= MTF_TAPE_HEAD_DIRTY;
13184 		}
13185 	}
13186 
13187 	kmem_free(com, sizeof (struct uscsi_cmd));
13188 	kmem_free(sensep, length);
13189 	return (rval);
13190 }
13191 
13192 /*
13193  * st_clear_unit_attention
13194  *
13195  *  	run test unit ready's to clear out outstanding
13196  * 	unit attentions.
13197  * 	returns zero for SUCCESS or the errno from st_cmd call
13198  */
13199 static int
13200 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
13201 {
13202 	int	i    = 0;
13203 	int	rval;
13204 
13205 	GET_SOFT_STATE(dev_instance);
13206 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
13207 
13208 	do {
13209 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
13210 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
13211 	return (rval);
13212 }
13213 
13214 static void
13215 st_calculate_timeouts(struct scsi_tape *un)
13216 {
13217 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
13218 
13219 	if (un->un_dp->non_motion_timeout == 0) {
13220 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13221 			un->un_dp->non_motion_timeout =
13222 			    st_io_time * st_long_timeout_x;
13223 		} else {
13224 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
13225 		}
13226 	}
13227 
13228 	if (un->un_dp->io_timeout == 0) {
13229 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13230 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
13231 		} else {
13232 			un->un_dp->io_timeout = (ushort_t)st_io_time;
13233 		}
13234 	}
13235 
13236 	if (un->un_dp->rewind_timeout == 0) {
13237 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13238 			un->un_dp->rewind_timeout =
13239 			    st_space_time * st_long_timeout_x;
13240 		} else {
13241 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
13242 		}
13243 	}
13244 
13245 	if (un->un_dp->space_timeout == 0) {
13246 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13247 			un->un_dp->space_timeout =
13248 			    st_space_time * st_long_timeout_x;
13249 		} else {
13250 			un->un_dp->space_timeout = (ushort_t)st_space_time;
13251 		}
13252 	}
13253 
13254 	if (un->un_dp->load_timeout == 0) {
13255 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13256 			un->un_dp->load_timeout =
13257 			    st_space_time * st_long_timeout_x;
13258 		} else {
13259 			un->un_dp->load_timeout = (ushort_t)st_space_time;
13260 		}
13261 	}
13262 
13263 	if (un->un_dp->unload_timeout == 0) {
13264 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13265 			un->un_dp->unload_timeout =
13266 			    st_space_time * st_long_timeout_x;
13267 		} else {
13268 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
13269 		}
13270 	}
13271 
13272 	if (un->un_dp->erase_timeout == 0) {
13273 		if (un->un_dp->options & ST_LONG_ERASE) {
13274 			un->un_dp->erase_timeout =
13275 			    st_space_time * st_long_space_time_x;
13276 		} else {
13277 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
13278 		}
13279 	}
13280 }
13281 
13282 
13283 static writablity
13284 st_is_not_wormable(struct scsi_tape *un)
13285 {
13286 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
13287 	return (RDWR);
13288 }
13289 
13290 static writablity
13291 st_is_hp_dat_tape_worm(struct scsi_tape *un)
13292 {
13293 	writablity wrt;
13294 
13295 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
13296 
13297 	/* Mode sense should be current */
13298 	if (un->un_mspl->media_type == 1) {
13299 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13300 		    "Drive has WORM media loaded\n");
13301 		wrt = WORM;
13302 	} else {
13303 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13304 		    "Drive has non WORM media loaded\n");
13305 		wrt = RDWR;
13306 	}
13307 	return (wrt);
13308 }
13309 
13310 #define	HP_DAT_INQUIRY 0x4A
13311 static writablity
13312 st_is_hp_dat_worm(struct scsi_tape *un)
13313 {
13314 	char *buf;
13315 	int result;
13316 	writablity wrt;
13317 
13318 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
13319 
13320 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
13321 
13322 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
13323 
13324 	if (result != 0) {
13325 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13326 		    "Read Standard Inquiry for WORM support failed");
13327 		wrt = FAILED;
13328 	} else if ((buf[40] & 1) == 0) {
13329 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13330 		    "Drive is NOT WORMable\n");
13331 		/* This drive doesn't support it so don't check again */
13332 		un->un_dp->options &= ~ST_WORMABLE;
13333 		wrt = RDWR;
13334 		un->un_wormable = st_is_not_wormable;
13335 	} else {
13336 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13337 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13338 		un->un_wormable = st_is_hp_dat_tape_worm;
13339 		wrt = un->un_wormable(un);
13340 	}
13341 
13342 	kmem_free(buf, HP_DAT_INQUIRY);
13343 
13344 	/*
13345 	 * If drive doesn't support it no point in checking further.
13346 	 */
13347 	return (wrt);
13348 }
13349 
13350 static writablity
13351 st_is_hp_lto_tape_worm(struct scsi_tape *un)
13352 {
13353 	writablity wrt;
13354 
13355 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
13356 
13357 	/* Mode sense should be current */
13358 	switch (un->un_mspl->media_type) {
13359 	case 0x00:
13360 		switch (un->un_mspl->density) {
13361 		case 0x40:
13362 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13363 			    "Drive has standard Gen I media loaded\n");
13364 			break;
13365 		case 0x42:
13366 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13367 			    "Drive has standard Gen II media loaded\n");
13368 			break;
13369 		case 0x44:
13370 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13371 			    "Drive has standard Gen III media loaded\n");
13372 			break;
13373 		case 0x46:
13374 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13375 			    "Drive has standard Gen IV media loaded\n");
13376 			break;
13377 		default:
13378 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13379 			    "Drive has standard unknown 0x%X media loaded\n",
13380 			    un->un_mspl->density);
13381 		}
13382 		wrt = RDWR;
13383 		break;
13384 	case 0x01:
13385 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13386 		    "Drive has WORM medium loaded\n");
13387 		wrt = WORM;
13388 		break;
13389 	case 0x80:
13390 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13391 		    "Drive has CD-ROM emulation medium loaded\n");
13392 		wrt = WORM;
13393 		break;
13394 	default:
13395 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13396 		    "Drive has an unexpected medium type 0x%X loaded\n",
13397 		    un->un_mspl->media_type);
13398 		wrt = RDWR;
13399 	}
13400 
13401 	return (wrt);
13402 }
13403 
13404 #define	LTO_REQ_INQUIRY 44
13405 static writablity
13406 st_is_hp_lto_worm(struct scsi_tape *un)
13407 {
13408 	char *buf;
13409 	int result;
13410 	writablity wrt;
13411 
13412 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
13413 
13414 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
13415 
13416 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
13417 
13418 	if (result != 0) {
13419 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13420 		    "Read Standard Inquiry for WORM support failed");
13421 		wrt = FAILED;
13422 	} else if ((buf[40] & 1) == 0) {
13423 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13424 		    "Drive is NOT WORMable\n");
13425 		/* This drive doesn't support it so don't check again */
13426 		un->un_dp->options &= ~ST_WORMABLE;
13427 		wrt = RDWR;
13428 		un->un_wormable = st_is_not_wormable;
13429 	} else {
13430 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13431 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13432 		un->un_wormable = st_is_hp_lto_tape_worm;
13433 		wrt = un->un_wormable(un);
13434 	}
13435 
13436 	kmem_free(buf, LTO_REQ_INQUIRY);
13437 
13438 	/*
13439 	 * If drive doesn't support it no point in checking further.
13440 	 */
13441 	return (wrt);
13442 }
13443 
13444 static writablity
13445 st_is_t10_worm_device(struct scsi_tape *un)
13446 {
13447 	writablity wrt;
13448 
13449 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
13450 
13451 	if (un->un_mspl->media_type == 0x3c) {
13452 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13453 		    "Drive has WORM media loaded\n");
13454 		wrt = WORM;
13455 	} else {
13456 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13457 		    "Drive has non WORM media loaded\n");
13458 		wrt = RDWR;
13459 	}
13460 	return (wrt);
13461 }
13462 
13463 #define	SEQ_CAP_PAGE	(char)0xb0
13464 static writablity
13465 st_is_t10_worm(struct scsi_tape *un)
13466 {
13467 	char *buf;
13468 	int result;
13469 	writablity wrt;
13470 
13471 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
13472 
13473 	buf = kmem_zalloc(6, KM_SLEEP);
13474 
13475 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
13476 
13477 	if (result != 0) {
13478 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13479 		    "Read Vitial Inquiry for Sequental Capability"
13480 		    " WORM support failed %x", result);
13481 		wrt = FAILED;
13482 	} else if ((buf[4] & 1) == 0) {
13483 		ASSERT(buf[1] == SEQ_CAP_PAGE);
13484 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13485 		    "Drive is NOT WORMable\n");
13486 		/* This drive doesn't support it so don't check again */
13487 		un->un_dp->options &= ~ST_WORMABLE;
13488 		wrt = RDWR;
13489 		un->un_wormable = st_is_not_wormable;
13490 	} else {
13491 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13492 		    "Drive supports WORM\n");
13493 		un->un_wormable = st_is_t10_worm_device;
13494 		wrt = un->un_wormable(un);
13495 	}
13496 
13497 	kmem_free(buf, 6);
13498 
13499 	return (wrt);
13500 }
13501 
13502 
13503 #define	STK_REQ_SENSE 26
13504 
13505 static writablity
13506 st_is_stk_worm(struct scsi_tape *un)
13507 {
13508 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
13509 	struct scsi_extended_sense *sense;
13510 	struct uscsi_cmd *cmd;
13511 	char *buf;
13512 	int result;
13513 	writablity wrt;
13514 
13515 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
13516 
13517 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13518 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
13519 	sense = (struct scsi_extended_sense *)buf;
13520 
13521 	cmd->uscsi_flags = USCSI_READ;
13522 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13523 	cmd->uscsi_cdb = &cdb[0];
13524 	cmd->uscsi_bufaddr = buf;
13525 	cmd->uscsi_buflen = STK_REQ_SENSE;
13526 	cmd->uscsi_cdblen = CDB_GROUP0;
13527 	cmd->uscsi_rqlen = 0;
13528 	cmd->uscsi_rqbuf = NULL;
13529 
13530 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
13531 
13532 	if (result != 0 || cmd->uscsi_status != 0) {
13533 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13534 		    "Request Sense for WORM failed");
13535 		wrt = RDWR;
13536 	} else if (sense->es_add_len + 8 < 24) {
13537 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13538 		    "Drive didn't send enough sense data for WORM byte %d\n",
13539 		    sense->es_add_len + 8);
13540 		wrt = RDWR;
13541 		un->un_wormable = st_is_not_wormable;
13542 	} else if ((buf[24]) & 0x02) {
13543 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13544 		    "Drive has WORM tape loaded\n");
13545 		wrt = WORM;
13546 		un->un_wormable = st_is_stk_worm;
13547 	} else {
13548 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13549 		    "Drive has normal tape loaded\n");
13550 		wrt = RDWR;
13551 		un->un_wormable = st_is_stk_worm;
13552 	}
13553 
13554 	kmem_free(buf, STK_REQ_SENSE);
13555 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13556 	return (wrt);
13557 }
13558 
13559 #define	DLT_INQ_SZ 44
13560 
13561 static writablity
13562 st_is_dlt_tape_worm(struct scsi_tape *un)
13563 {
13564 	caddr_t buf;
13565 	int result;
13566 	writablity wrt;
13567 
13568 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
13569 
13570 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
13571 
13572 	/* Read Attribute Media Type */
13573 
13574 	result = st_read_attributes(un, 0x0408, buf, 10, st_uscsi_cmd);
13575 
13576 	/*
13577 	 * If this quantum drive is attached via an HBA that cannot
13578 	 * support thr read attributes command return error in the
13579 	 * hope that someday they will support the t10 method.
13580 	 */
13581 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
13582 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13583 		    "Read Attribute Command for WORM Media detection is not "
13584 		    "supported on the HBA that this drive is attached to.");
13585 		wrt = RDWR;
13586 		un->un_wormable = st_is_not_wormable;
13587 		goto out;
13588 	}
13589 
13590 	if (result != 0) {
13591 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13592 		    "Read Attribute Command for WORM Media returned 0x%x",
13593 		    result);
13594 		wrt = RDWR;
13595 		un->un_dp->options &= ~ST_WORMABLE;
13596 		goto out;
13597 	}
13598 
13599 	if ((uchar_t)buf[9] == 0x80) {
13600 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13601 		    "Drive media is WORM\n");
13602 		wrt = WORM;
13603 	} else {
13604 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13605 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
13606 		wrt = RDWR;
13607 	}
13608 
13609 out:
13610 	kmem_free(buf, DLT_INQ_SZ);
13611 	return (wrt);
13612 }
13613 
13614 static writablity
13615 st_is_dlt_worm(struct scsi_tape *un)
13616 {
13617 	caddr_t buf;
13618 	int result;
13619 	writablity wrt;
13620 
13621 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
13622 
13623 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
13624 
13625 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
13626 
13627 	if (result != 0) {
13628 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13629 		    "Read Vendor Specific Inquiry for WORM support failed");
13630 		wrt = RDWR;
13631 		goto out;
13632 	}
13633 
13634 	if ((buf[2] & 1) == 0) {
13635 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13636 		    "Drive is not WORMable\n");
13637 		wrt = RDWR;
13638 		un->un_dp->options &= ~ST_WORMABLE;
13639 		un->un_wormable = st_is_not_wormable;
13640 		goto out;
13641 	} else {
13642 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13643 		    "Drive is WORMable\n");
13644 		un->un_wormable = st_is_dlt_tape_worm;
13645 		wrt = un->un_wormable(un);
13646 	}
13647 out:
13648 	kmem_free(buf, DLT_INQ_SZ);
13649 
13650 	return (wrt);
13651 }
13652 
13653 typedef struct {
13654 	struct modeheader_seq header;
13655 #if defined(_BIT_FIELDS_LTOH) /* X86 */
13656 	uchar_t pagecode	:6,
13657 				:2;
13658 	uchar_t page_len;
13659 	uchar_t syslogalive	:2,
13660 		device		:1,
13661 		abs		:1,
13662 		ulpbot		:1,
13663 		prth		:1,
13664 		ponej		:1,
13665 		ait		:1;
13666 	uchar_t span;
13667 
13668 	uchar_t			:6,
13669 		worm		:1,
13670 		mic		:1;
13671 	uchar_t worm_cap	:1,
13672 				:7;
13673 	uint32_t		:32;
13674 #else /* SPARC */
13675 	uchar_t			:2,
13676 		pagecode	:6;
13677 	uchar_t page_len;
13678 	uchar_t ait		:1,
13679 		device		:1,
13680 		abs		:1,
13681 		ulpbot		:1,
13682 		prth		:1,
13683 		ponej		:1,
13684 		syslogalive	:2;
13685 	uchar_t span;
13686 	uchar_t mic		:1,
13687 		worm		:1,
13688 				:6;
13689 	uchar_t			:7,
13690 		worm_cap	:1;
13691 	uint32_t		:32;
13692 #endif
13693 }ait_dev_con;
13694 
13695 #define	AIT_DEV_PAGE 0x31
13696 static writablity
13697 st_is_sony_worm(struct scsi_tape *un)
13698 {
13699 	int result;
13700 	writablity wrt;
13701 	ait_dev_con *ait_conf;
13702 
13703 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
13704 
13705 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
13706 
13707 	result = st_gen_mode_sense(un, st_uscsi_cmd, AIT_DEV_PAGE,
13708 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
13709 
13710 	if (result == 0) {
13711 
13712 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
13713 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13714 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
13715 			    ait_conf->pagecode, AIT_DEV_PAGE);
13716 			wrt = RDWR;
13717 			un->un_wormable = st_is_not_wormable;
13718 
13719 		} else if (ait_conf->worm_cap) {
13720 
13721 			un->un_wormable = st_is_sony_worm;
13722 
13723 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13724 			    "Drives is WORMable\n");
13725 			if (ait_conf->worm) {
13726 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13727 				    "Media is WORM\n");
13728 				wrt = WORM;
13729 			} else {
13730 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13731 				    "Media is not WORM\n");
13732 				wrt = RDWR;
13733 			}
13734 
13735 		} else {
13736 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13737 			    "Drives not is WORMable\n");
13738 			wrt = RDWR;
13739 			/* No further checking required */
13740 			un->un_dp->options &= ~ST_WORMABLE;
13741 		}
13742 
13743 	} else {
13744 
13745 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13746 		    "AIT device config mode sense page read command failed"
13747 		    " result = %d ", result);
13748 		wrt = FAILED;
13749 		un->un_wormable = st_is_not_wormable;
13750 	}
13751 
13752 	kmem_free(ait_conf, sizeof (ait_dev_con));
13753 	return (wrt);
13754 }
13755 
13756 static writablity
13757 st_is_drive_worm(struct scsi_tape *un)
13758 {
13759 	writablity wrt;
13760 
13761 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
13762 
13763 	switch (un->un_dp->type) {
13764 	case MT_ISDLT:
13765 		wrt = st_is_dlt_worm(un);
13766 		break;
13767 
13768 	case MT_ISSTK9840:
13769 		wrt = st_is_stk_worm(un);
13770 		break;
13771 
13772 	case MT_IS8MM:
13773 	case MT_ISAIT:
13774 		wrt = st_is_sony_worm(un);
13775 		break;
13776 
13777 	case MT_LTO:
13778 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
13779 			wrt = st_is_hp_lto_worm(un);
13780 		} else {
13781 			wrt = st_is_t10_worm(un);
13782 		}
13783 		break;
13784 
13785 	case MT_ISDAT:
13786 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
13787 			wrt = st_is_hp_dat_worm(un);
13788 		} else {
13789 			wrt = st_is_t10_worm(un);
13790 		}
13791 		break;
13792 
13793 	default:
13794 		wrt = FAILED;
13795 		break;
13796 	}
13797 
13798 	/*
13799 	 * If any of the above failed try the t10 standard method.
13800 	 */
13801 	if (wrt == FAILED) {
13802 		wrt = st_is_t10_worm(un);
13803 	}
13804 
13805 	/*
13806 	 * Unknown method for detecting WORM media.
13807 	 */
13808 	if (wrt == FAILED) {
13809 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13810 		    "Unknown method for WORM media detection\n");
13811 		wrt = RDWR;
13812 		un->un_dp->options &= ~ST_WORMABLE;
13813 	}
13814 
13815 	return (wrt);
13816 }
13817 
13818 static int
13819 st_read_attributes(struct scsi_tape *un, uint16_t attribute, void *pnt,
13820     size_t size, ubufunc_t bufunc)
13821 {
13822 	char cdb[CDB_GROUP4];
13823 	int result;
13824 	struct uscsi_cmd *cmd;
13825 	caddr_t buf = (caddr_t)pnt;
13826 
13827 	ST_FUNC(ST_DEVINFO, st_read_attributes);
13828 
13829 	if (un->un_sd->sd_inq->inq_ansi < 3) {
13830 		return (ENOTTY);
13831 	}
13832 
13833 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13834 
13835 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
13836 	cdb[1] = 0;
13837 	cdb[2] = 0;
13838 	cdb[3] = 0;
13839 	cdb[4] = 0;
13840 	cdb[5] = 0;
13841 	cdb[6] = 0;
13842 	cdb[7] = 0;
13843 	cdb[8] = (char)(attribute >> 8);
13844 	cdb[9] = (char)(attribute);
13845 	cdb[10] = (char)(size >> 24);
13846 	cdb[11] = (char)(size >> 16);
13847 	cdb[12] = (char)(size >> 8);
13848 	cdb[13] = (char)(size);
13849 	cdb[14] = 0;
13850 	cdb[15] = 0;
13851 
13852 
13853 	cmd->uscsi_flags = USCSI_READ | USCSI_DIAGNOSE;
13854 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13855 	cmd->uscsi_cdb = &cdb[0];
13856 	cmd->uscsi_bufaddr = (caddr_t)buf;
13857 	cmd->uscsi_buflen = size;
13858 	cmd->uscsi_cdblen = sizeof (cdb);
13859 
13860 	result = bufunc(un, cmd, FKIOCTL);
13861 
13862 	if (result != 0 || cmd->uscsi_status != 0) {
13863 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
13864 		    "st_read_attribute failed: result %d status %d\n",
13865 		    result, cmd->uscsi_status);
13866 		/*
13867 		 * If this returns invalid operation code don't try again.
13868 		 */
13869 		if (un->un_sd->sd_sense->es_key == KEY_ILLEGAL_REQUEST &&
13870 		    un->un_sd->sd_sense->es_add_code == 0x20) {
13871 			result = ENOTTY;
13872 		} else if (result == 0) {
13873 			result = EIO;
13874 		}
13875 
13876 	} else {
13877 
13878 		/*
13879 		 * The attribute retured should match the attribute requested.
13880 		 */
13881 		if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
13882 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13883 			    "st_read_attribute got wrong data back expected "
13884 			    "0x%x got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
13885 			st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
13886 			    "bad? data", buf, size);
13887 			result = EIO;
13888 		}
13889 	}
13890 
13891 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13892 
13893 	return (result);
13894 }
13895 
13896 static int
13897 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
13898     uchar_t page)
13899 {
13900 	char cdb[CDB_GROUP0];
13901 	struct scsi_extended_sense *sense;
13902 	struct uscsi_cmd *cmd;
13903 	int result;
13904 
13905 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
13906 
13907 	cdb[0] = SCMD_INQUIRY;
13908 	cdb[1] = page ? 1 : 0;
13909 	cdb[2] = page;
13910 	cdb[3] = 0;
13911 	cdb[4] = size;
13912 	cdb[5] = 0;
13913 
13914 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13915 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
13916 
13917 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
13918 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13919 	cmd->uscsi_cdb = &cdb[0];
13920 	cmd->uscsi_bufaddr = dest;
13921 	cmd->uscsi_buflen = size;
13922 	cmd->uscsi_cdblen = CDB_GROUP0;
13923 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
13924 	cmd->uscsi_rqbuf = (caddr_t)sense;
13925 
13926 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
13927 
13928 	if (result != 0 || cmd->uscsi_status != 0) {
13929 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13930 		    "st_get_special_inquiry() failed for page %x", page);
13931 		if (result == 0) {
13932 			result = EIO;
13933 		}
13934 	}
13935 
13936 	kmem_free(sense, sizeof (struct scsi_extended_sense));
13937 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13938 
13939 	return (result);
13940 }
13941 
13942 
13943 static int
13944 st_update_block_pos(struct scsi_tape *un, bufunc_t bf, int post_space)
13945 {
13946 	int rval = ENOTTY;
13947 	uchar_t status = un->un_status;
13948 	posmode previous_pmode = un->un_running.pmode;
13949 
13950 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
13951 
13952 	while (un->un_read_pos_type != NO_POS) {
13953 		rval = bf(un, SCMD_READ_POSITION, 32, SYNC_CMD);
13954 
13955 		/*
13956 		 * If read position command returned good status
13957 		 * Parse the data to see if the position can be interpreted.
13958 		 */
13959 		if ((rval == 0) &&
13960 		    ((rval = st_interpret_read_pos(un, &un->un_pos,
13961 		    un->un_read_pos_type, 32, (caddr_t)un->un_read_pos_data,
13962 		    post_space)) == 0)) {
13963 			/*
13964 			 * Update the running position as well if un_pos was
13965 			 * ok. But only if recovery is enabled.
13966 			 */
13967 			if (st_recov_sz != sizeof (recov_info)) {
13968 				break;
13969 			}
13970 			rval = st_interpret_read_pos(un, &un->un_running,
13971 			    un->un_read_pos_type, 32,
13972 			    (caddr_t)un->un_read_pos_data, post_space);
13973 			un->un_status = status;
13974 			break;
13975 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
13976 			un->un_running.pmode = previous_pmode;
13977 			continue;
13978 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
13979 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13980 			    "st_update_block_pos() read position cmd 0x%x"
13981 			    " returned 0x%x un_status = %d",
13982 			    un->un_read_pos_type, rval, un->un_status);
13983 			/* ENOTTY means it read garbage. try something else. */
13984 			if (rval == ENOTTY) {
13985 				rval = EIO; /* so ENOTTY is not final rval */
13986 			} else {
13987 				break;
13988 			}
13989 		} else {
13990 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
13991 			    "st_update_block_pos() read position cmd %x"
13992 			    " returned %x", un->un_read_pos_type, rval);
13993 			un->un_running.pmode = previous_pmode;
13994 		}
13995 
13996 		switch (un->un_read_pos_type) {
13997 		case SHORT_POS:
13998 			un->un_read_pos_type = NO_POS;
13999 			break;
14000 
14001 		case LONG_POS:
14002 			un->un_read_pos_type = EXT_POS;
14003 			break;
14004 
14005 		case EXT_POS:
14006 			un->un_read_pos_type = SHORT_POS;
14007 			break;
14008 
14009 		default:
14010 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14011 			    "Unexpected read position type 0x%x",
14012 			    un->un_read_pos_type);
14013 		}
14014 		un->un_status = KEY_NO_SENSE;
14015 	}
14016 
14017 	return (rval);
14018 }
14019 
14020 static int
14021 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
14022 {
14023 	int result;
14024 	size_t d_sz;
14025 	caddr_t pos_info;
14026 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
14027 
14028 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
14029 
14030 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
14031 		return (0);
14032 	}
14033 
14034 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
14035 
14036 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14037 		    "bp_mapin_common() failed");
14038 
14039 		return (EIO);
14040 	}
14041 
14042 	d_sz = bp->b_bcount - bp->b_resid;
14043 	if (d_sz == 0) {
14044 		bp_mapout(bp);
14045 		return (EIO);
14046 	}
14047 
14048 	/*
14049 	 * Copy the buf to a double-word aligned memory that can hold the
14050 	 * tape_position_t data structure.
14051 	 */
14052 	if ((pos_info = kmem_alloc(d_sz, KM_NOSLEEP)) == NULL) {
14053 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14054 		    "kmem_alloc() failed");
14055 		bp_mapout(bp);
14056 		return (EIO);
14057 	}
14058 	bcopy(bp->b_un.b_addr, pos_info, d_sz);
14059 
14060 #ifdef STDEBUG
14061 	if ((st_debug & 0x7) > 2) {
14062 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14063 		    "st_get_read_pos() position info",
14064 		    pos_info, bp->b_bcount);
14065 	}
14066 #endif
14067 
14068 	result = st_interpret_read_pos(un, &un->un_pos, cmd->uscsi_cdb[1],
14069 	    d_sz, pos_info, 0);
14070 
14071 	COPY_POS(&un->un_running, &un->un_pos);
14072 
14073 	kmem_free(pos_info, d_sz);
14074 	bp_mapout(bp);
14075 
14076 	return (result);
14077 }
14078 
14079 #if defined(_BIG_ENDIAN)
14080 
14081 #define	FIX_ENDIAN16(x)
14082 #define	FIX_ENDIAN32(x)
14083 #define	FIX_ENDIAN64(x)
14084 
14085 #elif defined(_LITTLE_ENDIAN)
14086 
14087 static void
14088 st_swap16(uint16_t *val)
14089 {
14090 	uint16_t tmp;
14091 
14092 	tmp = (*val >>  8) & 0xff;
14093 	tmp |= (*val <<  8) & 0xff00;
14094 
14095 	*val = tmp;
14096 }
14097 
14098 static void
14099 st_swap32(uint32_t *val)
14100 {
14101 	uint32_t tmp;
14102 
14103 	tmp =  (*val >> 24) & 0xff;
14104 	tmp |= (*val >>  8) & 0xff00;
14105 	tmp |= (*val <<  8) & 0xff0000;
14106 	tmp |= (*val << 24) & 0xff000000;
14107 
14108 	*val = tmp;
14109 }
14110 
14111 static void
14112 st_swap64(uint64_t *val)
14113 {
14114 	uint32_t low;
14115 	uint32_t high;
14116 
14117 	low =  (uint32_t)(*val);
14118 	high = (uint32_t)(*val >> 32);
14119 
14120 	st_swap32(&low);
14121 	st_swap32(&high);
14122 
14123 	*val =  high;
14124 	*val |= ((uint64_t)low << 32);
14125 }
14126 
14127 #define	FIX_ENDIAN16(x) st_swap16(x)
14128 #define	FIX_ENDIAN32(x) st_swap32(x)
14129 #define	FIX_ENDIAN64(x) st_swap64(x)
14130 #endif
14131 
14132 /*
14133  * st_interpret_read_pos()
14134  *
14135  * Returns:
14136  *	0	If secsessful.
14137  *	EIO	If read postion responce data was unuseable or invalid.
14138  *	ERANGE	If the position of the drive is too large for the read_p_type.
14139  *	ENOTTY	If the responce data looks invalid for the read position type.
14140  */
14141 
14142 static int
14143 st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
14144     read_p_types type, size_t data_sz, const caddr_t responce, int post_space)
14145 {
14146 	int rval = 0;
14147 	int flag = 0;
14148 	tapepos_t org;
14149 
14150 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
14151 
14152 	/*
14153 	 * We expect the position value to change after a space command.
14154 	 * So if post_space is set we don't print out what has changed.
14155 	 */
14156 	if ((dest != &un->un_pos) && (post_space == 0) &&
14157 	    (st_recov_sz == sizeof (recov_info))) {
14158 		COPY_POS(&org, dest);
14159 		flag = 1;
14160 	}
14161 
14162 	/*
14163 	 * See what kind of read position was requested.
14164 	 */
14165 	switch (type) {
14166 
14167 	case SHORT_POS: /* Short data format */
14168 	{
14169 		tape_position_t *pos_info = (tape_position_t *)responce;
14170 		uint32_t value;
14171 
14172 		/* If reserved fields are non zero don't use the data */
14173 		if (pos_info->reserved0 || pos_info->reserved1 ||
14174 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
14175 		    pos_info->reserved3) {
14176 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14177 			    "Invalid Read Short Position Data returned\n");
14178 			rval = EIO;
14179 			break;
14180 		}
14181 		/*
14182 		 * Position is to large to use this type of read position.
14183 		 */
14184 		if (pos_info->posi_err == 1) {
14185 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14186 			    "Drive reported position error\n");
14187 			rval = ERANGE;
14188 			break;
14189 		}
14190 		/*
14191 		 * If your at the begining of partition and end at the same
14192 		 * time it's very small partition or bad data.
14193 		 */
14194 		if (pos_info->begin_of_part && pos_info->end_of_part) {
14195 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14196 			    "SHORT_POS returned begin and end of"
14197 			    " partition\n");
14198 			rval = EIO;
14199 			break;
14200 		}
14201 
14202 		if (pos_info->blk_posi_unkwn == 0) {
14203 
14204 			value = pos_info->host_block;
14205 			FIX_ENDIAN32(&value);
14206 
14207 			/*
14208 			 * If the tape is rewound the host blcok should be 0.
14209 			 */
14210 			if ((pos_info->begin_of_part == 1) &&
14211 			    (value != 0)) {
14212 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14213 				    "SHORT_POS returned begin of partition"
14214 				    " but host block was 0x%x\n", value);
14215 				rval = EIO;
14216 				break;
14217 			}
14218 
14219 			if (dest->lgclblkno != value) {
14220 				if (flag)
14221 					flag++;
14222 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14223 				    "SHORT_POS current logical 0x%"PRIx64" read"
14224 				    " 0x%x\n", dest->lgclblkno, value);
14225 			}
14226 
14227 			dest->lgclblkno = (uint64_t)value;
14228 
14229 			/*
14230 			 * If the begining of partition is true and the
14231 			 * block number is zero we will beleive that it is
14232 			 * rewound. Promote the pmode to legacy.
14233 			 */
14234 			if ((pos_info->begin_of_part == 1) &&
14235 			    (value == 0)) {
14236 				dest->blkno = 0;
14237 				dest->fileno = 0;
14238 				if (dest->pmode != legacy)
14239 					dest->pmode = legacy;
14240 			/*
14241 			 * otherwise if the pmode was invalid,
14242 			 * promote it to logical.
14243 			 */
14244 			} else if (dest->pmode == invalid) {
14245 				dest->pmode = logical;
14246 			}
14247 
14248 			if (dest->partition != pos_info->partition_number) {
14249 				if (flag)
14250 					flag++;
14251 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14252 				    "SHORT_POS current partition %d read %d\n",
14253 				    dest->partition,
14254 				    pos_info->partition_number);
14255 			}
14256 
14257 			dest->partition = pos_info->partition_number;
14258 
14259 		} else {
14260 			dest->pmode = invalid;
14261 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14262 			    "Tape drive reported block position as unknown\n");
14263 		}
14264 		break;
14265 	}
14266 
14267 	case LONG_POS: /* Long data format */
14268 	{
14269 		uint64_t value;
14270 		tape_position_long_t *long_pos_info =
14271 		    (tape_position_long_t *)responce;
14272 
14273 		/* If reserved fields are non zero don't use the data */
14274 		if ((long_pos_info->reserved0) ||
14275 		    (long_pos_info->reserved1) ||
14276 		    (long_pos_info->reserved2)) {
14277 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14278 			    "Invalid Read Long Position Data returned\n");
14279 			rval = ENOTTY;
14280 			break;
14281 		}
14282 
14283 		/* Is position Valid */
14284 		if (long_pos_info->blk_posi_unkwn == 0) {
14285 			uint32_t part;
14286 
14287 			value = long_pos_info->block_number;
14288 			FIX_ENDIAN64(&value);
14289 
14290 			/*
14291 			 * If it says we are at the begining of partition
14292 			 * the block value better be 0.
14293 			 */
14294 			if ((long_pos_info->begin_of_part == 1) &&
14295 			    (value != 0)) {
14296 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14297 				    "LONG_POS returned begin of partition but"
14298 				    " block number was 0x%"PRIx64"\n", value);
14299 				rval = ENOTTY;
14300 				break;
14301 			}
14302 			/*
14303 			 * Can't be at the start and the end of the partition
14304 			 * at the same time if the partition is larger the 0.
14305 			 */
14306 			if (long_pos_info->begin_of_part &&
14307 			    long_pos_info->end_of_part) {
14308 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14309 				    "LONG_POS returned begin and end of"
14310 				    " partition\n");
14311 				rval = ENOTTY;
14312 				break;
14313 			}
14314 
14315 			/*
14316 			 * If the logical block number is not what we expected.
14317 			 */
14318 			if (dest->lgclblkno != value) {
14319 				if (flag)
14320 					flag++;
14321 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14322 				    "LONG_POS current logical 0x%"PRIx64
14323 				    " read 0x%"PRIx64"\n",
14324 				    dest->lgclblkno, value);
14325 			}
14326 			dest->lgclblkno = value;
14327 
14328 			/*
14329 			 * If the begining of partition is true and the
14330 			 * block number is zero we will beleive that it is
14331 			 * rewound. Promote the pmode to legacy.
14332 			 */
14333 			if ((long_pos_info->begin_of_part == 1) &&
14334 			    (long_pos_info->block_number == 0)) {
14335 				dest->blkno = 0;
14336 				dest->fileno = 0;
14337 				if (dest->pmode != legacy)
14338 					dest->pmode = legacy;
14339 			/*
14340 			 * otherwise if the pmode was invalid,
14341 			 * promote it to logical.
14342 			 */
14343 			} else if (dest->pmode == invalid) {
14344 				dest->pmode = logical;
14345 			}
14346 
14347 			part = long_pos_info->partition;
14348 			FIX_ENDIAN32(&part);
14349 			if (dest->partition != part) {
14350 				if (flag)
14351 					flag++;
14352 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14353 				    "LONG_POS current partition %d"
14354 				    " read %d\n", dest->partition, part);
14355 			}
14356 			dest->partition = part;
14357 		} else {
14358 			/*
14359 			 * If the drive doesn't know location,
14360 			 * we don't either.
14361 			 */
14362 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14363 			    "Tape drive reported block position as unknown\n");
14364 			dest->pmode = invalid;
14365 		}
14366 
14367 		/* Is file position valid */
14368 		if (long_pos_info->mrk_posi_unkwn == 0) {
14369 			value = long_pos_info->file_number;
14370 			FIX_ENDIAN64(&value);
14371 			/*
14372 			 * If it says we are at the begining of partition
14373 			 * the block value better be 0.
14374 			 */
14375 			if ((long_pos_info->begin_of_part == 1) &&
14376 			    (value != 0)) {
14377 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14378 				    "LONG_POS returned begin of partition but"
14379 				    " block number was 0x%"PRIx64"\n", value);
14380 				rval = ENOTTY;
14381 				break;
14382 			}
14383 			if (((dest->pmode == legacy) ||
14384 			    (dest->pmode == logical)) &&
14385 			    (dest->fileno != value)) {
14386 				if (flag)
14387 					flag++;
14388 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14389 				    "LONG_POS fileno 0x%"PRIx64
14390 				    " not un_pos %x\n", value,
14391 				    dest->fileno);
14392 			} else if (dest->pmode == invalid) {
14393 				dest->pmode = logical;
14394 			}
14395 			dest->fileno = (int32_t)value;
14396 		} else {
14397 			/*
14398 			 * If the drive doesn't know its position,
14399 			 * we don't either.
14400 			 */
14401 			dest->pmode = invalid;
14402 		}
14403 		if (dest->pmode != invalid && long_pos_info->end_of_part) {
14404 			dest->eof = ST_EOT;
14405 		}
14406 
14407 		break;
14408 	}
14409 
14410 	case EXT_POS: /* Extended data format */
14411 	{
14412 		uint64_t value;
14413 		uint16_t len;
14414 		tape_position_ext_t *ext_pos_info =
14415 		    (tape_position_ext_t *)responce;
14416 
14417 		/* Make sure that there is enough data there */
14418 		if (data_sz < 16) {
14419 			break;
14420 		}
14421 
14422 		/* If reserved fields are non zero don't use the data */
14423 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
14424 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14425 			    "EXT_POS reserved fields not zero\n");
14426 			rval = ENOTTY;
14427 			break;
14428 		}
14429 
14430 		/*
14431 		 * In the unlikely event of overflowing 64 bits of position.
14432 		 */
14433 		if (ext_pos_info->posi_err != 0) {
14434 			rval = ERANGE;
14435 			break;
14436 		}
14437 
14438 		len = ext_pos_info->parameter_len;
14439 		FIX_ENDIAN16(&len);
14440 
14441 		if (len != 0x1c) {
14442 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14443 			    "EXT_POS parameter_len should be 0x1c was 0x%x\n",
14444 			    len);
14445 			rval = ENOTTY;
14446 			break;
14447 		}
14448 
14449 		/* Is block position information valid */
14450 		if (ext_pos_info->blk_posi_unkwn == 0) {
14451 
14452 			value = ext_pos_info->host_block;
14453 			FIX_ENDIAN64(&value);
14454 			if ((ext_pos_info->begin_of_part == 1) &&
14455 			    (value != 0)) {
14456 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14457 				    "EXT_POS returned begining of partition but"
14458 				    " the host block was 0x%"PRIx64"\n", value);
14459 				rval = ENOTTY;
14460 				break;
14461 			}
14462 
14463 			if (dest->lgclblkno != value) {
14464 				if (flag)
14465 					flag++;
14466 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14467 				    "EXT_POS current logical 0x%"PRIx64
14468 				    " read 0x%"PRIx64"\n",
14469 				    dest->lgclblkno, value);
14470 			}
14471 			dest->lgclblkno = value;
14472 
14473 			/*
14474 			 * If the begining of partition is true and the
14475 			 * block number is zero we will beleive that it is
14476 			 * rewound. Promote the pmode to legacy.
14477 			 */
14478 			if ((ext_pos_info->begin_of_part == 1) &&
14479 			    (ext_pos_info->host_block == 0)) {
14480 				dest->blkno = 0;
14481 				dest->fileno = 0;
14482 				if (dest->pmode != legacy) {
14483 					dest->pmode = legacy;
14484 				}
14485 			/*
14486 			 * otherwise if the pmode was invalid,
14487 			 * promote it to logical.
14488 			 */
14489 			} else if (dest->pmode == invalid) {
14490 				dest->pmode = logical;
14491 			}
14492 
14493 			if (dest->partition != ext_pos_info->partition) {
14494 				if (flag)
14495 					flag++;
14496 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14497 				    "EXT_POS current partition %d read %d\n",
14498 				    dest->partition,
14499 				    ext_pos_info->partition);
14500 			}
14501 			dest->partition = ext_pos_info->partition;
14502 
14503 		} else {
14504 			dest->pmode = invalid;
14505 		}
14506 		break;
14507 	}
14508 
14509 	default:
14510 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14511 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
14512 		rval = EIO;
14513 	}
14514 
14515 	if ((flag > 1) && (rval == 0)) {
14516 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14517 		    "position read in", &org);
14518 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14519 		    "position read out", dest);
14520 	}
14521 
14522 	return (rval);
14523 }
14524 
14525 static int
14526 st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos,
14527     uint64_t lblk, uchar_t partition)
14528 {
14529 	int rval;
14530 	char cdb[CDB_GROUP4];
14531 	struct uscsi_cmd *cmd;
14532 	struct scsi_extended_sense sense;
14533 	bufunc_t bf = (ubf == st_uscsi_cmd) ? st_cmd : st_rcmd;
14534 
14535 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
14536 	/*
14537 	 * WTF Not sure what to do when doing recovery and not wanting
14538 	 * to update un_pos
14539 	 */
14540 
14541 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14542 
14543 	if (lblk <= INT32_MAX) {
14544 		cmd->uscsi_cdblen = CDB_GROUP1;
14545 		cdb[0] = SCMD_LOCATE;
14546 		cdb[1] = pos->partition == partition ? 0 : 2;
14547 		cdb[2] = 0;
14548 		cdb[3] = (char)(lblk >> 24);
14549 		cdb[4] = (char)(lblk >> 16);
14550 		cdb[5] = (char)(lblk >> 8);
14551 		cdb[6] = (char)(lblk);
14552 		cdb[7] = 0;
14553 		cdb[8] = partition;
14554 		cdb[9] = 0;
14555 	} else {
14556 		/*
14557 		 * If the drive doesn't give a 64 bit read position data
14558 		 * it is unlikely it will accept 64 bit locates.
14559 		 */
14560 		if (un->un_read_pos_type != LONG_POS) {
14561 			kmem_free(cmd, sizeof (struct uscsi_cmd));
14562 			return (ERANGE);
14563 		}
14564 		cmd->uscsi_cdblen = CDB_GROUP4;
14565 		cdb[0] = (char)SCMD_LOCATE_G4;
14566 		cdb[1] = pos->partition == partition ? 0 : 2;
14567 		cdb[2] = 0;
14568 		cdb[3] = partition;
14569 		cdb[4] = (char)(lblk >> 56);
14570 		cdb[5] = (char)(lblk >> 48);
14571 		cdb[6] = (char)(lblk >> 40);
14572 		cdb[7] = (char)(lblk >> 32);
14573 		cdb[8] = (char)(lblk >> 24);
14574 		cdb[9] = (char)(lblk >> 16);
14575 		cdb[10] = (char)(lblk >> 8);
14576 		cdb[11] = (char)(lblk);
14577 		cdb[12] = 0;
14578 		cdb[13] = 0;
14579 		cdb[14] = 0;
14580 		cdb[15] = 0;
14581 	}
14582 
14583 
14584 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
14585 	cmd->uscsi_rqbuf = (caddr_t)&sense;
14586 	cmd->uscsi_rqlen = sizeof (sense);
14587 	cmd->uscsi_timeout = un->un_dp->space_timeout;
14588 	cmd->uscsi_cdb = cdb;
14589 
14590 	rval = ubf(un, cmd, FKIOCTL);
14591 
14592 	pos->pmode = logical;
14593 	pos->eof = ST_NO_EOF;
14594 
14595 	if (lblk > INT32_MAX) {
14596 		/*
14597 		 * XXX This is a work around till we handle Descriptor format
14598 		 * sense data. Since we are sending a command where the standard
14599 		 * sense data can not correctly represent a correct residual in
14600 		 * 4 bytes.
14601 		 */
14602 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
14603 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14604 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
14605 			/* Doesn't like big locate command */
14606 			un->un_status = 0;
14607 			rval = ERANGE;
14608 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
14609 			/* Aborted big locate command */
14610 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14611 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
14612 			    rval);
14613 			un->un_status = 0;
14614 			rval = EIO;
14615 		} else if (st_update_block_pos(un, bf, 1)) {
14616 			/* read position failed */
14617 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14618 			    "Big LOCATE and read pos: rval = %d\n", rval);
14619 			rval = EIO;
14620 		} else if (lblk > un->un_pos.lgclblkno) {
14621 			/* read position worked but position was not expected */
14622 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14623 			    "Big LOCATE and recover read less then desired 0x%"
14624 			    PRIx64"\n", un->un_pos.lgclblkno);
14625 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
14626 			un->un_status = KEY_BLANK_CHECK;
14627 			rval = ESPIPE;
14628 		} else if (lblk == un->un_pos.lgclblkno) {
14629 			/* read position was what was expected */
14630 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14631 			    "Big LOCATE and recover seems to have worked\n");
14632 			un->un_err_resid = 0;
14633 			rval = 0;
14634 		} else {
14635 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14636 			    "BIGLOCATE end up going backwards");
14637 			un->un_err_resid = lblk;
14638 			rval = EIO;
14639 		}
14640 
14641 	} else if (rval == 0) {
14642 		/* Worked as requested */
14643 		pos->lgclblkno = lblk;
14644 
14645 	} else if (((cmd->uscsi_status & STATUS_MASK) == STATUS_CHECK) &&
14646 	    (cmd->uscsi_resid != 0)) {
14647 		/* Got part way there but wasn't enough blocks on tape */
14648 		pos->lgclblkno = lblk - cmd->uscsi_resid;
14649 		un->un_err_resid = cmd->uscsi_resid;
14650 		un->un_status = KEY_BLANK_CHECK;
14651 		rval = ESPIPE;
14652 
14653 	} else if (st_update_block_pos(un, bf, 1) == 0) {
14654 		/* Got part way there but drive didn't tell what we missed by */
14655 		un->un_err_resid = lblk - pos->lgclblkno;
14656 		un->un_status = KEY_BLANK_CHECK;
14657 		rval = ESPIPE;
14658 
14659 	} else {
14660 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14661 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
14662 		    rval, cmd->uscsi_status);
14663 		un->un_err_resid = lblk;
14664 		un->un_status = KEY_ILLEGAL_REQUEST;
14665 		pos->pmode = invalid;
14666 		rval = EIO;
14667 	}
14668 
14669 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14670 
14671 	return (rval);
14672 }
14673 
14674 static int
14675 st_mtfsf_ioctl(struct scsi_tape *un, int files)
14676 {
14677 	int rval;
14678 
14679 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
14680 
14681 
14682 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14683 	    "st_mtfsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
14684 #if 0
14685 	if ((IN_EOF(un->un_pos)) && (files == 1)) {
14686 		un->un_pos.fileno++;
14687 		un->un_pos.blkno = 0;
14688 		return (0);
14689 	}
14690 #endif
14691 	/* pmode == invalid already handled */
14692 	if (un->un_pos.pmode == legacy) {
14693 		/*
14694 		 * forward space over filemark
14695 		 *
14696 		 * For ASF we allow a count of 0 on fsf which means
14697 		 * we just want to go to beginning of current file.
14698 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
14699 		 * Allow stepping over double fmk with reel
14700 		 */
14701 		if ((un->un_pos.eof >= ST_EOT) &&
14702 		    (files > 0) &&
14703 		    ((un->un_dp->options & ST_REEL) == 0)) {
14704 			/* we're at EOM */
14705 			un->un_err_resid = files;
14706 			un->un_status = KEY_BLANK_CHECK;
14707 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14708 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
14709 			return (EIO);
14710 		}
14711 
14712 		/*
14713 		 * physical tape position may not be what we've been
14714 		 * telling the user; adjust the request accordingly
14715 		 */
14716 		if (IN_EOF(un->un_pos)) {
14717 			un->un_pos.fileno++;
14718 			un->un_pos.blkno = 0;
14719 			/*
14720 			 * For positive direction case, we're now covered.
14721 			 * For zero or negative direction, we're covered
14722 			 * (almost)
14723 			 */
14724 			files--;
14725 		}
14726 
14727 	}
14728 
14729 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
14730 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14731 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
14732 		return (EIO);
14733 	}
14734 
14735 
14736 	/*
14737 	 * Forward space file marks.
14738 	 * We leave ourselves at block zero
14739 	 * of the target file number.
14740 	 */
14741 	if (files < 0) {
14742 		rval = st_backward_space_files(un, -files, 0);
14743 	} else {
14744 		rval = st_forward_space_files(un, files);
14745 	}
14746 
14747 	return (rval);
14748 }
14749 
14750 static int
14751 st_forward_space_files(struct scsi_tape *un, int count)
14752 {
14753 	int rval;
14754 
14755 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
14756 
14757 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14758 	    "fspace: count=%x, eof=%x\n", count, un->un_pos.eof);
14759 
14760 	ASSERT(count >= 0);
14761 	ASSERT(un->un_pos.pmode != invalid);
14762 
14763 	/*
14764 	 * A space with a count of zero means take me to the start of file.
14765 	 */
14766 	if (count == 0) {
14767 
14768 		/* Hay look were already there */
14769 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0) {
14770 			un->un_err_resid = 0;
14771 			COPY_POS(&un->un_err_pos, &un->un_pos);
14772 			return (0);
14773 		}
14774 
14775 		/*
14776 		 * Well we are in the first file.
14777 		 * A rewind will get to the start.
14778 		 */
14779 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
14780 			rval = st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
14781 
14782 		/*
14783 		 * Can we backspace to get there?
14784 		 * This should work in logical mode.
14785 		 */
14786 		} else if (un->un_dp->options & ST_BSF) {
14787 			rval = st_space_to_begining_of_file(un);
14788 
14789 		/*
14790 		 * Can't back space but current file number is known,
14791 		 * So rewind and space from the begining of the partition.
14792 		 */
14793 		} else if (un->un_pos.pmode == legacy) {
14794 			rval = st_scenic_route_to_begining_of_file(un,
14795 			    un->un_pos.fileno);
14796 
14797 		/*
14798 		 * pmode is logical and ST_BSF is not set.
14799 		 * The LONG_POS read position contains the fileno.
14800 		 * If the read position works, rewind and space.
14801 		 */
14802 		} else if (un->un_read_pos_type == LONG_POS) {
14803 			rval = st_cmd(un, SCMD_READ_POSITION, 0, SYNC_CMD);
14804 			if (rval) {
14805 				/*
14806 				 * We didn't get the file position from the
14807 				 * read position command.
14808 				 * We are going to trust the drive to backspace
14809 				 * and then position after the filemark.
14810 				 */
14811 				rval = st_space_to_begining_of_file(un);
14812 			}
14813 			rval = st_interpret_read_pos(un, &un->un_pos, LONG_POS,
14814 			    32, (caddr_t)un->un_read_pos_data, 0);
14815 			if ((rval) && (un->un_pos.pmode == invalid)) {
14816 				rval = st_space_to_begining_of_file(un);
14817 			} else {
14818 				rval = st_scenic_route_to_begining_of_file(un,
14819 				    un->un_pos.fileno);
14820 			}
14821 		} else {
14822 			rval = EIO;
14823 		}
14824 		/*
14825 		 * If something didn't work we are lost
14826 		 */
14827 		if (rval != 0) {
14828 			un->un_pos.pmode = invalid;
14829 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14830 			    "st_mtioctop : EIO : fspace pmode invalid");
14831 
14832 			rval = EIO;
14833 		}
14834 
14835 	} else {
14836 		rval = st_space_fmks(un, count);
14837 	}
14838 
14839 	if (rval != EIO && count < 0) {
14840 		/*
14841 		 * we came here with a count < 0; we now need
14842 		 * to skip back to end up before the filemark
14843 		 */
14844 		rval = st_backward_space_files(un, 1, 1);
14845 	}
14846 
14847 	return (rval);
14848 }
14849 
14850 static int
14851 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
14852 {
14853 	int rval;
14854 
14855 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
14856 
14857 	if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
14858 		rval = EIO;
14859 	} else if (st_cmd(un, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
14860 		rval = EIO;
14861 	}
14862 
14863 	return (rval);
14864 }
14865 
14866 static int
14867 st_space_to_begining_of_file(struct scsi_tape *un)
14868 {
14869 	int rval;
14870 
14871 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
14872 
14873 	/*
14874 	 * Back space of the file at the begining of the file.
14875 	 */
14876 	rval = st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
14877 	if (rval) {
14878 		rval = EIO;
14879 		return (rval);
14880 	}
14881 
14882 	/*
14883 	 * Other interesting answers might be crashed BOT which isn't bad.
14884 	 */
14885 	if (un->un_status == SUN_KEY_BOT) {
14886 		return (rval);
14887 	}
14888 
14889 	un->un_running.pmode = invalid;
14890 
14891 	/*
14892 	 * Now we are on the BOP side of the filemark. Forward space to
14893 	 * the EOM side and we are at the begining of the file.
14894 	 */
14895 	rval = st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD);
14896 	if (rval) {
14897 		rval = EIO;
14898 	}
14899 
14900 	return (rval);
14901 }
14902 
14903 static int
14904 st_mtfsr_ioctl(struct scsi_tape *un, int count)
14905 {
14906 
14907 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
14908 
14909 	/*
14910 	 * forward space to inter-record gap
14911 	 *
14912 	 */
14913 
14914 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14915 	    "st_ioctl_fsr: count=%x, eof=%x\n", count, un->un_pos.eof);
14916 
14917 	if (un->un_pos.pmode == legacy) {
14918 		/*
14919 		 * If were are at end of tape and count is forward.
14920 		 * Return blank check.
14921 		 */
14922 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
14923 			/* we're at EOM */
14924 			un->un_err_resid = count;
14925 			un->un_status = KEY_BLANK_CHECK;
14926 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14927 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
14928 			return (EIO);
14929 		}
14930 
14931 		/*
14932 		 * If count is zero there is nothing to do.
14933 		 */
14934 		if (count == 0) {
14935 			un->un_err_pos.fileno = un->un_pos.fileno;
14936 			un->un_err_pos.blkno = un->un_pos.blkno;
14937 			un->un_err_resid = 0;
14938 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
14939 				un->un_status = SUN_KEY_EOF;
14940 			}
14941 			return (0);
14942 		}
14943 
14944 		/*
14945 		 * physical tape position may not be what we've been
14946 		 * telling the user; adjust the position accordingly
14947 		 */
14948 		if (IN_EOF(un->un_pos)) {
14949 			daddr_t blkno = un->un_pos.blkno;
14950 			int fileno = un->un_pos.fileno;
14951 
14952 			optype lastop = un->un_lastop;
14953 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)
14954 			    == -1) {
14955 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14956 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
14957 				return (EIO);
14958 			}
14959 
14960 			un->un_pos.blkno = blkno;
14961 			un->un_pos.fileno = fileno;
14962 			un->un_lastop = lastop;
14963 		}
14964 	}
14965 
14966 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
14967 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14968 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
14969 		return (EIO);
14970 	}
14971 
14972 	return (st_space_records(un, count));
14973 }
14974 
14975 static int
14976 st_space_records(struct scsi_tape *un, int count)
14977 {
14978 	int dblk;
14979 	int rval = 0;
14980 
14981 	ST_FUNC(ST_DEVINFO, st_space_records);
14982 
14983 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
14984 	    "st_space_records: count=%x, eof=%x\n", count, un->un_pos.eof);
14985 
14986 	if (un->un_pos.pmode == logical) {
14987 		rval = st_cmd(un, SCMD_SPACE, Blk(count), SYNC_CMD);
14988 		if (rval != 0) {
14989 			rval = EIO;
14990 		}
14991 		return (rval);
14992 	}
14993 
14994 	dblk = un->un_pos.blkno + count;
14995 
14996 	/* Already there */
14997 	if (dblk == un->un_pos.blkno) {
14998 		un->un_err_resid = 0;
14999 		COPY_POS(&un->un_err_pos, &un->un_pos);
15000 		return (0);
15001 	}
15002 
15003 	/*
15004 	 * If the destination block is forward
15005 	 * or the drive will backspace records.
15006 	 */
15007 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
15008 		/*
15009 		 * If we're spacing forward, or the device can
15010 		 * backspace records, we can just use the SPACE
15011 		 * command.
15012 		 */
15013 		dblk -= un->un_pos.blkno;
15014 		if (st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15015 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15016 			    "st_space_records:EIO:space_records can't spc");
15017 			rval = EIO;
15018 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
15019 			/*
15020 			 * check if we hit BOT/EOT
15021 			 */
15022 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
15023 				un->un_status = SUN_KEY_BOT;
15024 				un->un_pos.eof = ST_NO_EOF;
15025 			} else if (dblk < 0 &&
15026 			    un->un_pos.eof == ST_EOF_PENDING) {
15027 				int residue = un->un_err_resid;
15028 				/*
15029 				 * we skipped over a filemark
15030 				 * and need to go forward again
15031 				 */
15032 				if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
15033 					ST_DEBUG2(ST_DEVINFO, st_label,
15034 					    SCSI_DEBUG, "st_space_records: EIO"
15035 					    " : can't space #2");
15036 					rval = EIO;
15037 				}
15038 				un->un_err_resid = residue;
15039 			}
15040 			if (rval == 0) {
15041 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15042 				    "st_space_records: EIO : space_rec rval"
15043 				    " == 0");
15044 				rval = EIO;
15045 			}
15046 		}
15047 	} else {
15048 		/*
15049 		 * else we rewind, space forward across filemarks to
15050 		 * the desired file, and then space records to the
15051 		 * desired block.
15052 		 */
15053 
15054 		int dfile = un->un_pos.fileno;	/* save current file */
15055 
15056 		if (dblk < 0) {
15057 			/*
15058 			 * Wups - we're backing up over a filemark
15059 			 */
15060 			if (un->un_pos.blkno != 0 &&
15061 			    (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15062 			    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD))) {
15063 				un->un_pos.pmode = invalid;
15064 			}
15065 			un->un_err_resid = -dblk;
15066 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
15067 				un->un_status = SUN_KEY_BOT;
15068 				un->un_pos.eof = ST_NO_EOF;
15069 			} else if (un->un_pos.fileno > 0) {
15070 				un->un_status = SUN_KEY_EOF;
15071 				un->un_pos.eof = ST_NO_EOF;
15072 			}
15073 			COPY_POS(&un->un_err_pos, &un->un_pos);
15074 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15075 			    "st_space_records:EIO:space_records : dblk < 0");
15076 			rval = EIO;
15077 		} else if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15078 		    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
15079 		    st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15080 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15081 			    "st_space_records: EIO :space_records : rewind "
15082 			    "and space failed");
15083 			un->un_pos.pmode = invalid;
15084 			rval = EIO;
15085 		}
15086 	}
15087 
15088 	return (rval);
15089 }
15090 
15091 static int
15092 st_mtbsf_ioctl(struct scsi_tape *un, int files)
15093 {
15094 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
15095 
15096 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15097 	    "st_mtbsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
15098 	/*
15099 	 * backward space of file filemark (1/2" and 8mm)
15100 	 * tape position will end on the beginning of tape side
15101 	 * of the desired file mark
15102 	 */
15103 	if ((un->un_dp->options & ST_BSF) == 0) {
15104 		return (ENOTTY);
15105 	}
15106 
15107 	if (un->un_pos.pmode == legacy) {
15108 
15109 		/*
15110 		 * If a negative count (which implies a forward space op)
15111 		 * is specified, and we're at logical or physical eot,
15112 		 * bounce the request.
15113 		 */
15114 
15115 		if (un->un_pos.eof >= ST_EOT && files < 0) {
15116 			un->un_err_resid = files;
15117 			un->un_status = SUN_KEY_EOT;
15118 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15119 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
15120 			return (EIO);
15121 		}
15122 		/*
15123 		 * physical tape position may not be what we've been
15124 		 * telling the user; adjust the request accordingly
15125 		 */
15126 		if (IN_EOF(un->un_pos)) {
15127 			un->un_pos.fileno++;
15128 			un->un_pos.blkno = 0;
15129 			files++;
15130 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15131 			    "st_mtbsf_ioctl in eof: count=%d, op=%x\n",
15132 			    files, MTBSF);
15133 
15134 		}
15135 	}
15136 
15137 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15138 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15139 		    "st_ioctl : EIO : MTBSF : check den wfm");
15140 		return (EIO);
15141 	}
15142 
15143 	if (files <= 0) {
15144 		/*
15145 		 * for a negative count, we need to step forward
15146 		 * first and then step back again
15147 		 */
15148 		files = -files + 1;
15149 		return (st_forward_space_files(un, files));
15150 	}
15151 	return (st_backward_space_files(un, files, 1));
15152 }
15153 
15154 static int
15155 st_backward_space_files(struct scsi_tape *un, int count, int infront)
15156 {
15157 	int end_fileno;
15158 	int skip_cnt;
15159 	int rval = 0;
15160 
15161 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
15162 
15163 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15164 	    "st_backward_space_files: count=%x eof=%x\n",
15165 	    count, un->un_pos.eof);
15166 	/*
15167 	 * Backspace files (MTNBSF): infront == 0
15168 	 *
15169 	 *	For tapes that can backspace, backspace
15170 	 *	count+1 filemarks and then run forward over
15171 	 *	a filemark
15172 	 *
15173 	 *	For tapes that can't backspace,
15174 	 *		calculate desired filenumber
15175 	 *		(un->un_pos.fileno - count), rewind,
15176 	 *		and then space forward this amount
15177 	 *
15178 	 * Backspace filemarks (MTBSF) infront == 1
15179 	 *
15180 	 *	For tapes that can backspace, backspace count
15181 	 *	filemarks
15182 	 *
15183 	 *	For tapes that can't backspace, calculate
15184 	 *	desired filenumber (un->un_pos.fileno - count),
15185 	 *	add 1, rewind, space forward this amount,
15186 	 *	and mark state as ST_EOF_PENDING appropriately.
15187 	 */
15188 
15189 	if (un->un_pos.pmode == logical) {
15190 
15191 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15192 		    "st_backward_space_files: mt_op=%x count=%x"
15193 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
15194 		    un->un_pos.lgclblkno);
15195 
15196 
15197 		/* In case a drive that won't back space gets in logical mode */
15198 		if ((un->un_dp->options & ST_BSF) == 0) {
15199 			rval = EIO;
15200 			return (rval);
15201 		}
15202 		if (st_cmd(un, SCMD_SPACE, Fmk(-count), SYNC_CMD)) {
15203 			rval = EIO;
15204 			return (rval);
15205 		}
15206 		if ((infront != 0) &&
15207 		    (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
15208 			rval = EIO;
15209 			return (rval);
15210 		}
15211 		return (rval);
15212 	}
15213 
15214 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15215 	    "st_backward_space_files: mt_op=%x count=%x fileno=%x blkno=%x\n",
15216 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
15217 
15218 
15219 
15220 	/*
15221 	 * Handle the simple case of BOT
15222 	 * playing a role in these cmds.
15223 	 * We do this by calculating the
15224 	 * ending file number. If the ending
15225 	 * file is < BOT, rewind and set an
15226 	 * error and mark resid appropriately.
15227 	 * If we're backspacing a file (not a
15228 	 * filemark) and the target file is
15229 	 * the first file on the tape, just
15230 	 * rewind.
15231 	 */
15232 
15233 	/* figure expected destination of this SPACE command */
15234 	end_fileno = un->un_pos.fileno - count;
15235 
15236 	/*
15237 	 * Would the end effect of this SPACE be the same as rewinding?
15238 	 * If so just rewind instead.
15239 	 */
15240 	if ((infront != 0) && (end_fileno < 0) ||
15241 	    (infront == 0) && (end_fileno <= 0)) {
15242 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15243 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15244 			    "st_backward_space_files: EIO : "
15245 			    "rewind in lou of BSF failed\n");
15246 			rval = EIO;
15247 		}
15248 		if (end_fileno < 0) {
15249 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15250 			    "st_backward_space_files: EIO : "
15251 			    "back space file greater then fileno\n");
15252 			rval = EIO;
15253 			un->un_err_resid = -end_fileno;
15254 			un->un_status = SUN_KEY_BOT;
15255 		}
15256 		return (rval);
15257 	}
15258 
15259 	if (un->un_dp->options & ST_BSF) {
15260 		skip_cnt = 1 - infront;
15261 		/*
15262 		 * If we are going to end up at the beginning
15263 		 * of the file, we have to space one extra file
15264 		 * first, and then space forward later.
15265 		 */
15266 		end_fileno = -(count + skip_cnt);
15267 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15268 		    "skip_cnt=%x, tmp=%x\n", skip_cnt, end_fileno);
15269 		if (st_cmd(un, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
15270 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15271 			    "st_backward_space_files:EIO:back space fm failed");
15272 			rval = EIO;
15273 		}
15274 	} else {
15275 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15276 			rval = EIO;
15277 		} else {
15278 			skip_cnt = end_fileno + infront;
15279 		}
15280 	}
15281 
15282 	/*
15283 	 * If we have to space forward, do so...
15284 	 */
15285 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15286 	    "space forward skip_cnt=%x, rval=%x\n", skip_cnt, rval);
15287 
15288 	if (rval == 0 && skip_cnt) {
15289 		if (st_cmd(un, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
15290 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15291 			    "st_backward_space_files:EIO:space fm skip count");
15292 			rval = EIO;
15293 		} else if (infront) {
15294 			/*
15295 			 * If we had to space forward, and we're
15296 			 * not a tape that can backspace, mark state
15297 			 * as if we'd just seen a filemark during a
15298 			 * a read.
15299 			 */
15300 			if ((un->un_dp->options & ST_BSF) == 0) {
15301 				un->un_pos.eof = ST_EOF_PENDING;
15302 				un->un_pos.fileno -= 1;
15303 				un->un_pos.blkno = LASTBLK;
15304 				un->un_running.pmode = invalid;
15305 			}
15306 		}
15307 	}
15308 
15309 	if (rval != 0) {
15310 		un->un_pos.pmode = invalid;
15311 	}
15312 
15313 	return (rval);
15314 }
15315 
15316 static int
15317 st_mtnbsf_ioctl(struct scsi_tape *un, int count)
15318 {
15319 	int rval;
15320 
15321 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
15322 
15323 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15324 	    "nbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
15325 
15326 	if (un->un_pos.pmode == legacy) {
15327 		/*
15328 		 * backward space file to beginning of file
15329 		 *
15330 		 * If a negative count (which implies a forward space op)
15331 		 * is specified, and we're at logical or physical eot,
15332 		 * bounce the request.
15333 		 */
15334 
15335 		if (un->un_pos.eof >= ST_EOT && count < 0) {
15336 			un->un_err_resid = count;
15337 			un->un_status = SUN_KEY_EOT;
15338 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15339 			    "st_ioctl : EIO : > EOT and count < 0");
15340 			return (EIO);
15341 		}
15342 		/*
15343 		 * physical tape position may not be what we've been
15344 		 * telling the user; adjust the request accordingly
15345 		 */
15346 		if (IN_EOF(un->un_pos)) {
15347 			un->un_pos.fileno++;
15348 			un->un_pos.blkno = 0;
15349 			count++;
15350 		}
15351 	}
15352 
15353 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15354 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15355 		    "st_ioctl : EIO : MTNBSF check den and wfm");
15356 		return (EIO);
15357 	}
15358 
15359 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15360 	    "mtnbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
15361 
15362 	if (count <= 0) {
15363 		rval = st_forward_space_files(un, -count);
15364 	} else {
15365 		rval = st_backward_space_files(un, count, 0);
15366 	}
15367 	return (rval);
15368 }
15369 
15370 static int
15371 st_mtbsr_ioctl(struct scsi_tape *un, int num)
15372 {
15373 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
15374 
15375 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15376 	    "bsr: count=%x, eof=%x\n", num, un->un_pos.eof);
15377 
15378 	if (un->un_pos.pmode == legacy) {
15379 		/*
15380 		 * backward space into inter-record gap
15381 		 *
15382 		 * If a negative count (which implies a forward space op)
15383 		 * is specified, and we're at logical or physical eot,
15384 		 * bounce the request.
15385 		 */
15386 		if (un->un_pos.eof >= ST_EOT && num < 0) {
15387 			un->un_err_resid = num;
15388 			un->un_status = SUN_KEY_EOT;
15389 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15390 			    "st_ioctl : EIO : MTBSR > EOT");
15391 			return (EIO);
15392 		}
15393 
15394 		if (num == 0) {
15395 			COPY_POS(&un->un_err_pos, &un->un_pos);
15396 			un->un_err_resid = 0;
15397 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15398 				un->un_status = SUN_KEY_EOF;
15399 			}
15400 			return (0);
15401 		}
15402 
15403 		/*
15404 		 * physical tape position may not be what we've been
15405 		 * telling the user; adjust the position accordingly.
15406 		 * bsr can not skip filemarks and continue to skip records
15407 		 * therefore if we are logically before the filemark but
15408 		 * physically at the EOT side of the filemark, we need to step
15409 		 * back; this allows fsr N where N > number of blocks in file
15410 		 * followed by bsr 1 to position at the beginning of last block
15411 		 */
15412 		if (IN_EOF(un->un_pos)) {
15413 			tapepos_t save;
15414 			optype lastop = un->un_lastop;
15415 
15416 			COPY_POS(&save, &un->un_pos);
15417 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD) == -1) {
15418 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15419 				    "st_mtbsr_ioctl: EIO : MTBSR can't space");
15420 				return (EIO);
15421 			}
15422 
15423 			COPY_POS(&un->un_pos, &save);
15424 			un->un_lastop = lastop;
15425 		}
15426 	}
15427 
15428 	un->un_pos.eof = ST_NO_EOF;
15429 
15430 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15431 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15432 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
15433 		return (EIO);
15434 	}
15435 
15436 	num = -num;
15437 	return (st_space_records(un, num));
15438 }
15439 
15440 static int
15441 st_mtfsfm_ioctl(struct scsi_tape *un, int cnt)
15442 {
15443 	int rval;
15444 
15445 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
15446 
15447 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
15448 	if (rval == 0) {
15449 		un->un_pos.pmode = logical;
15450 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15451 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15452 		/*
15453 		 * Drive says invalid field in cdb.
15454 		 * Doesn't like space multiple. Position isn't lost.
15455 		 */
15456 		un->un_err_resid = cnt;
15457 		un->un_status = 0;
15458 		rval = ENOTTY;
15459 	} else {
15460 		un->un_err_resid = cnt;
15461 		un->un_pos.pmode = invalid;
15462 	}
15463 	return (rval);
15464 }
15465 
15466 static int
15467 st_mtbsfm_ioctl(struct scsi_tape *un, int cnt)
15468 {
15469 	int rval;
15470 
15471 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
15472 
15473 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
15474 	if (rval == 0) {
15475 		un->un_pos.pmode = logical;
15476 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15477 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15478 		/*
15479 		 * Drive says invalid field in cdb.
15480 		 * Doesn't like space multiple. Position isn't lost.
15481 		 */
15482 		un->un_err_resid = cnt;
15483 		un->un_status = 0;
15484 		rval = ENOTTY;
15485 	} else {
15486 		un->un_err_resid = cnt;
15487 		un->un_pos.pmode = invalid;
15488 	}
15489 	return (rval);
15490 }
15491 
15492 #ifdef	__x86
15493 
15494 /*
15495  * release contig_mem and wake up waiting thread, if any
15496  */
15497 static void
15498 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
15499 {
15500 	mutex_enter(ST_MUTEX);
15501 
15502 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
15503 
15504 	cp->cm_next = un->un_contig_mem;
15505 	un->un_contig_mem = cp;
15506 	un->un_contig_mem_available_num++;
15507 	cv_broadcast(&un->un_contig_mem_cv);
15508 
15509 	mutex_exit(ST_MUTEX);
15510 }
15511 
15512 /*
15513  * St_get_contig_mem will return a contig_mem if there is one available
15514  * in current system. Otherwise, it will try to alloc one, if the total
15515  * number of contig_mem is within st_max_contig_mem_num.
15516  * It will sleep, if allowed by caller or return NULL, if no contig_mem
15517  * is available for now.
15518  */
15519 static struct contig_mem *
15520 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
15521 {
15522 	size_t rlen;
15523 	struct contig_mem *cp = NULL;
15524 	ddi_acc_handle_t acc_hdl;
15525 	caddr_t addr;
15526 	int big_enough = 0;
15527 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
15528 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
15529 
15530 	/* Try to get one available contig_mem */
15531 	mutex_enter(ST_MUTEX);
15532 
15533 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
15534 
15535 	if (un->un_contig_mem_available_num > 0) {
15536 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15537 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
15538 		/*
15539 		 * we failed to get one. we're going to
15540 		 * alloc one more contig_mem for this I/O
15541 		 */
15542 		mutex_exit(ST_MUTEX);
15543 		cp = (struct contig_mem *)kmem_zalloc(
15544 		    sizeof (struct contig_mem) + biosize(),
15545 		    alloc_flags);
15546 		if (cp == NULL) {
15547 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15548 			    "alloc contig_mem failure\n");
15549 			return (NULL); /* cannot get one */
15550 		}
15551 		cp->cm_bp = (struct buf *)
15552 		    (((caddr_t)cp) + sizeof (struct contig_mem));
15553 		bioinit(cp->cm_bp);
15554 		mutex_enter(ST_MUTEX);
15555 		un->un_contig_mem_total_num++; /* one more available */
15556 	} else {
15557 		/*
15558 		 * we failed to get one and we're NOT allowed to
15559 		 * alloc more contig_mem
15560 		 */
15561 		if (alloc_flags == KM_SLEEP) {
15562 			while (un->un_contig_mem_available_num <= 0) {
15563 				cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
15564 			}
15565 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15566 		} else {
15567 			mutex_exit(ST_MUTEX);
15568 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15569 			    "alloc contig_mem failure\n");
15570 			return (NULL); /* cannot get one */
15571 		}
15572 	}
15573 	mutex_exit(ST_MUTEX);
15574 
15575 	/* We need to check if this block of mem is big enough for this I/O */
15576 	if (cp->cm_len < len) {
15577 		/* not big enough, need to alloc a new one */
15578 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
15579 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
15580 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
15581 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15582 			    "alloc contig_mem failure: not enough mem\n");
15583 			st_release_contig_mem(un, cp);
15584 			cp = NULL;
15585 		} else {
15586 			if (cp->cm_addr) {
15587 				/* release previous one before attach new one */
15588 				ddi_dma_mem_free(&cp->cm_acc_hdl);
15589 			}
15590 			mutex_enter(ST_MUTEX);
15591 			un->un_max_contig_mem_len =
15592 			    un->un_max_contig_mem_len >= len ?
15593 			    un->un_max_contig_mem_len : len;
15594 			mutex_exit(ST_MUTEX);
15595 
15596 			/* attach new mem to this cp */
15597 			cp->cm_addr = addr;
15598 			cp->cm_acc_hdl = acc_hdl;
15599 			cp->cm_len = len;
15600 
15601 			goto alloc_ok; /* get one usable cp */
15602 		}
15603 	} else {
15604 		goto alloc_ok; /* get one usable cp */
15605 	}
15606 
15607 	/* cannot find/alloc a usable cp, when we get here */
15608 
15609 	mutex_enter(ST_MUTEX);
15610 	if ((un->un_max_contig_mem_len < len) ||
15611 	    (alloc_flags != KM_SLEEP)) {
15612 		mutex_exit(ST_MUTEX);
15613 		return (NULL);
15614 	}
15615 
15616 	/*
15617 	 * we're allowed to sleep, and there is one big enough
15618 	 * contig mem in the system, which is currently in use,
15619 	 * wait for it...
15620 	 */
15621 	big_enough = 1;
15622 	do {
15623 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
15624 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15625 	} while (cp == NULL);
15626 	mutex_exit(ST_MUTEX);
15627 
15628 	/* we get the big enough contig mem, finally */
15629 
15630 alloc_ok:
15631 	/* init bp attached to this cp */
15632 	bioreset(cp->cm_bp);
15633 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
15634 	cp->cm_bp->b_private = (void *)cp;
15635 
15636 	return (cp);
15637 }
15638 
15639 /*
15640  * this is the biodone func for the bp used in big block I/O
15641  */
15642 static int
15643 st_bigblk_xfer_done(struct buf *bp)
15644 {
15645 	struct contig_mem *cp;
15646 	struct buf *orig_bp;
15647 	int ioerr;
15648 	struct scsi_tape *un;
15649 
15650 	/* sanity check */
15651 	if (bp == NULL) {
15652 		return (DDI_FAILURE);
15653 	}
15654 
15655 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
15656 	if (un == NULL) {
15657 		return (DDI_FAILURE);
15658 	}
15659 
15660 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
15661 
15662 	cp = (struct contig_mem *)bp->b_private;
15663 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
15664 	cp->cm_bp = bp;
15665 
15666 	/* special handling for special I/O */
15667 	if (cp->cm_use_sbuf) {
15668 #ifndef __lock_lint
15669 		ASSERT(un->un_sbuf_busy);
15670 #endif
15671 		un->un_sbufp = orig_bp;
15672 		cp->cm_use_sbuf = 0;
15673 	}
15674 
15675 	orig_bp->b_resid = bp->b_resid;
15676 	ioerr = geterror(bp);
15677 	if (ioerr != 0) {
15678 		bioerror(orig_bp, ioerr);
15679 	} else if (orig_bp->b_flags & B_READ) {
15680 		/* copy data back to original bp */
15681 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
15682 		    bp->b_bcount - bp->b_resid);
15683 	}
15684 
15685 	st_release_contig_mem(un, cp);
15686 
15687 	biodone(orig_bp);
15688 
15689 	return (DDI_SUCCESS);
15690 }
15691 
15692 /*
15693  * We use this func to replace original bp that may not be able to do I/O
15694  * in big block size with one that can
15695  */
15696 static struct buf *
15697 st_get_bigblk_bp(struct buf *bp)
15698 {
15699 	struct contig_mem *cp;
15700 	struct scsi_tape *un;
15701 	struct buf *cont_bp;
15702 
15703 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
15704 	if (un == NULL) {
15705 		return (bp);
15706 	}
15707 
15708 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
15709 
15710 	/* try to get one contig_mem */
15711 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
15712 	if (!cp) {
15713 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
15714 		    "Cannot alloc contig buf for I/O for %lu blk size",
15715 		    bp->b_bcount);
15716 		return (bp);
15717 	}
15718 	cont_bp = cp->cm_bp;
15719 	cp->cm_bp = bp;
15720 
15721 	/* make sure that we "are" using un_sbufp for special I/O */
15722 	if (bp == un->un_sbufp) {
15723 #ifndef __lock_lint
15724 		ASSERT(un->un_sbuf_busy);
15725 #endif
15726 		un->un_sbufp = cont_bp;
15727 		cp->cm_use_sbuf = 1;
15728 	}
15729 
15730 	/* clone bp */
15731 	cont_bp->b_bcount = bp->b_bcount;
15732 	cont_bp->b_resid = bp->b_resid;
15733 	cont_bp->b_iodone = st_bigblk_xfer_done;
15734 	cont_bp->b_file = bp->b_file;
15735 	cont_bp->b_offset = bp->b_offset;
15736 	cont_bp->b_dip = bp->b_dip;
15737 	cont_bp->b_error = 0;
15738 	cont_bp->b_proc = NULL;
15739 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
15740 	cont_bp->b_shadow = NULL;
15741 	cont_bp->b_pages = NULL;
15742 	cont_bp->b_edev = bp->b_edev;
15743 	cont_bp->b_dev = bp->b_dev;
15744 	cont_bp->b_lblkno = bp->b_lblkno;
15745 	cont_bp->b_forw = bp->b_forw;
15746 	cont_bp->b_back = bp->b_back;
15747 	cont_bp->av_forw = bp->av_forw;
15748 	cont_bp->av_back = bp->av_back;
15749 	cont_bp->b_bufsize = bp->b_bufsize;
15750 
15751 	/* get data in original bp */
15752 	if (bp->b_flags & B_WRITE) {
15753 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
15754 	}
15755 
15756 	return (cont_bp);
15757 }
15758 #else
15759 #ifdef __lock_lint
15760 static int
15761 st_bigblk_xfer_done(struct buf *bp)
15762 {
15763 	return (0);
15764 }
15765 #endif
15766 #endif
15767 
15768 static const char *eof_status[] =
15769 {
15770 	"NO_EOF",
15771 	"EOF_PENDING",
15772 	"EOF",
15773 	"EOT_PENDING",
15774 	"EOT",
15775 	"EOM",
15776 	"AFTER_EOM"
15777 };
15778 static const char *mode[] = {
15779 	"invalid",
15780 	"legacy",
15781 	"logical"
15782 };
15783 
15784 static void
15785 st_print_position(dev_info_t *dev, char *label, uint_t level,
15786 const char *comment, tapepos_t *pos)
15787 {
15788 	ST_FUNC(dev, st_print_position);
15789 
15790 	scsi_log(dev, label, level,
15791 	    "%s Position data:\n", comment);
15792 	scsi_log(dev, label, CE_CONT,
15793 	    "Positioning mode = %s", mode[pos->pmode]);
15794 	scsi_log(dev, label, CE_CONT,
15795 	    "End Of File/Tape = %s", eof_status[pos->eof]);
15796 	scsi_log(dev, label, CE_CONT,
15797 	    "File Number      = 0x%x", pos->fileno);
15798 	scsi_log(dev, label, CE_CONT,
15799 	    "Block Number     = 0x%x", pos->blkno);
15800 	scsi_log(dev, label, CE_CONT,
15801 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
15802 	scsi_log(dev, label, CE_CONT,
15803 	    "Partition Number = 0x%x", pos->partition);
15804 }
15805 static int
15806 st_check_if_media_changed(struct scsi_tape *un, caddr_t data, int size)
15807 {
15808 
15809 	int result = 0;
15810 	int i;
15811 	ST_FUNC(ST_DEVINFO, st_check_if_media_changed);
15812 
15813 	/*
15814 	 * find non alpha numeric working from the end.
15815 	 */
15816 	for (i = size - 1; i; i--) {
15817 		if (ISALNUM(data[i]) == 0 || data[i] == ' ') {
15818 			data[i] = 0;
15819 			size = i;
15820 		}
15821 	}
15822 
15823 	if (size == 1) {
15824 		/*
15825 		 * Drive seems to think its returning useful data
15826 		 * but it looks like all junk
15827 		 */
15828 		return (result);
15829 	}
15830 
15831 	size++;
15832 
15833 	/*
15834 	 * Actually got a valid serial number.
15835 	 * If never stored one before alloc space for it.
15836 	 */
15837 	if (un->un_media_id_len == 0) {
15838 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
15839 		un->un_media_id_len = size;
15840 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
15841 		un->un_media_id[min(size, strlen(data))] = 0;
15842 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
15843 		    "Found Media Id %s length = %d\n", un->un_media_id, size);
15844 	} else if (size > un->un_media_id_len) {
15845 		if (strncmp(un->un_media_id, data, size) != 0) {
15846 			result = ESPIPE;
15847 		}
15848 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
15849 		    "Longer Media Id old ID:%s new ID:%s\n",
15850 		    un->un_media_id, data);
15851 		kmem_free(un->un_media_id, un->un_media_id_len);
15852 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
15853 		un->un_media_id_len = size;
15854 		(void) strncpy(un->un_media_id, data, size);
15855 		un->un_media_id[size] = 0;
15856 	} else if (strncmp(data, un->un_media_id,
15857 	    min(size, un->un_media_id_len)) != 0) {
15858 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
15859 		    "Old Media Id %s length = %d New %s length = %d\n",
15860 		    un->un_media_id, un->un_media_id_len, data, size);
15861 		bzero(un->un_media_id, un->un_media_id_len);
15862 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
15863 		un->un_media_id[min(size, strlen(data))] = 0;
15864 		result = ESPIPE;
15865 	} else {
15866 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15867 		    "Media Id still %s\n", un->un_media_id);
15868 	}
15869 
15870 	ASSERT(strlen(un->un_media_id) <= size);
15871 
15872 	return (result);
15873 }
15874 #define	ID_SIZE 32
15875 typedef struct
15876 {
15877 	uchar_t avilable_data0;
15878 	uchar_t avilable_data1;
15879 	uchar_t avilable_data2;
15880 	uchar_t avilable_data3;
15881 	uchar_t attribute_msb;
15882 	uchar_t attribute_lsb;
15883 #ifdef _BIT_FIELDS_LTOH
15884 	uchar_t format		: 2,
15885 				: 5,
15886 		read_only	: 1;
15887 #else
15888 	uchar_t read_only	: 1,
15889 				: 5,
15890 		format		: 2;
15891 #endif
15892 	uchar_t attribute_len_msb;
15893 	uchar_t attribute_len_lsb;
15894 }attribute_header;
15895 
15896 typedef struct {
15897 	attribute_header header;
15898 	char data[1];
15899 }mam_attribute;
15900 
15901 static int
15902 st_handle_hex_media_id(struct scsi_tape *un, void *pnt, int size)
15903 {
15904 	int result;
15905 	int newsize = (size + 1) << 1;
15906 	int i;
15907 	char byte;
15908 	char *format;
15909 	char *data = (char *)pnt;
15910 	char *buf = kmem_alloc(newsize, KM_SLEEP);
15911 
15912 	ST_FUNC(ST_DEVINFO, st_handle_hex_media_id);
15913 
15914 	(void) sprintf(buf, "0x");
15915 	for (i = 0; i < size; i++) {
15916 		byte = (uchar_t)data[i];
15917 		if (byte < 0x10)
15918 			format = "0%x";
15919 		else
15920 			format = "%x";
15921 		(void) sprintf(&buf[(int)strlen(buf)], format, byte);
15922 	}
15923 	result = st_check_if_media_changed(un, buf, newsize);
15924 
15925 	kmem_free(buf, newsize);
15926 
15927 	return (result);
15928 }
15929 
15930 
15931 static int
15932 st_get_media_id_via_read_attribute(struct scsi_tape *un, ubufunc_t bufunc)
15933 {
15934 	int result;
15935 	mam_attribute *buffer;
15936 	int size;
15937 	int newsize;
15938 
15939 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_read_attribute);
15940 	size = sizeof (attribute_header) + max(un->un_media_id_len, ID_SIZE);
15941 again:
15942 	buffer = kmem_zalloc(size, KM_SLEEP);
15943 	result = st_read_attributes(un, 0x0401, buffer, size, bufunc);
15944 	if (result == 0) {
15945 
15946 		newsize = (buffer->header.attribute_len_msb << 8) |
15947 		    buffer->header.attribute_len_lsb;
15948 
15949 		if (newsize + sizeof (attribute_header) > size) {
15950 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15951 			    "resizing read attribute data from %d to %d format"
15952 			    " %d\n", size, (int)sizeof (attribute_header) +
15953 			    newsize, buffer->header.format);
15954 			kmem_free(buffer, size);
15955 			size = newsize + sizeof (attribute_header);
15956 			goto again;
15957 		}
15958 
15959 		un->un_media_id_method = st_get_media_id_via_read_attribute;
15960 		if (buffer->header.format == 0) {
15961 			result =
15962 			    st_handle_hex_media_id(un, buffer->data, newsize);
15963 		} else {
15964 			result = st_check_if_media_changed(un, buffer->data,
15965 			    newsize);
15966 		}
15967 	} else if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
15968 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
15969 		    "Read Attribute Command for Media Identification is not "
15970 		    "supported on the HBA that this drive is attached to.");
15971 		result = ENOTTY;
15972 	}
15973 
15974 	kmem_free(buffer, size);
15975 	un->un_status = 0;
15976 
15977 	return (result);
15978 }
15979 
15980 
15981 static int
15982 st_get_media_id_via_media_serial_cmd(struct scsi_tape *un, ubufunc_t bufunc)
15983 {
15984 	char cdb[CDB_GROUP5];
15985 	struct uscsi_cmd *ucmd;
15986 	struct scsi_extended_sense sense;
15987 	int rval;
15988 	int size = max(un->un_media_id_len, ID_SIZE);
15989 	caddr_t buf;
15990 
15991 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_media_serial_cmd);
15992 
15993 	if (un->un_sd->sd_inq->inq_ansi < 3) {
15994 		return (ENOTTY);
15995 	}
15996 
15997 	ucmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
15998 upsize:
15999 	buf = kmem_alloc(size, KM_SLEEP);
16000 
16001 	cdb[0] = (char)SCMD_SVC_ACTION_IN_G5;
16002 	cdb[1] = 1; /* READ MEDIA SERIAL NUMBER */
16003 	cdb[2] = 0;
16004 	cdb[3] = 0;
16005 	cdb[4] = 0;
16006 	cdb[5] = 0;
16007 	cdb[6] = (char)(size >> 24);
16008 	cdb[7] = (char)(size >> 16);
16009 	cdb[8] = (char)(size >> 8);
16010 	cdb[9] = (char)(size);
16011 	cdb[10] = 0;
16012 	cdb[11] = 0;
16013 
16014 	ucmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
16015 	ucmd->uscsi_timeout = un->un_dp->non_motion_timeout;
16016 	ucmd->uscsi_cdb = &cdb[0];
16017 	ucmd->uscsi_cdblen = sizeof (cdb);
16018 	ucmd->uscsi_bufaddr = buf;
16019 	ucmd->uscsi_buflen = size;
16020 	ucmd->uscsi_rqbuf = (caddr_t)&sense;
16021 	ucmd->uscsi_rqlen = sizeof (sense);
16022 
16023 	rval = bufunc(un, ucmd, FKIOCTL);
16024 
16025 	if (rval || ucmd->uscsi_status != 0) {
16026 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16027 		    "media serial command returned %d scsi_status %d"
16028 		    " rqstatus %d", rval, ucmd->uscsi_status,
16029 		    ucmd->uscsi_rqstatus);
16030 		/*
16031 		 * If this returns invalid operation code don't try again.
16032 		 */
16033 		if (sense.es_key == KEY_ILLEGAL_REQUEST &&
16034 		    sense.es_add_code == 0x20) {
16035 			rval = ENOTTY;
16036 		} else if (rval == 0) {
16037 			rval = EIO;
16038 		}
16039 		un->un_status = 0;
16040 	} else {
16041 		int act_size;
16042 
16043 		/*
16044 		 * get reported size.
16045 		 */
16046 		act_size = (int)buf[3] | (int)(buf[2] << 8) |
16047 		    (int)(buf[1] << 16) | (int)(buf[0] << 24);
16048 
16049 		/* documentation says mod 4. */
16050 		while (act_size & 3) {
16051 			act_size++;
16052 		}
16053 
16054 		/*
16055 		 * If reported size is larger that we our buffer.
16056 		 * Free the old one and allocate one that is larger
16057 		 * enough and re-issuse the command.
16058 		 */
16059 		if (act_size + 4 > size) {
16060 			kmem_free(buf, size);
16061 			size = act_size + 4;
16062 			goto upsize;
16063 		}
16064 
16065 		/*
16066 		 * set data pointer to point to the start of that serial number.
16067 		 */
16068 		un->un_media_id_method = st_get_media_id_via_media_serial_cmd;
16069 		rval = st_check_if_media_changed(un, &buf[4], act_size);
16070 	}
16071 
16072 	kmem_free(ucmd, sizeof (struct uscsi_cmd));
16073 	kmem_free(buf, size);
16074 
16075 	return (rval);
16076 }
16077 
16078 
16079 /* ARGSUSED */
16080 static int
16081 st_bogus_media_id(struct scsi_tape *un, ubufunc_t bufunc)
16082 {
16083 	ST_FUNC(ST_DEVINFO, st_bogus_media_id);
16084 
16085 	ASSERT(un->un_media_id == NULL || un->un_media_id == bogusID);
16086 	ASSERT(un->un_media_id_len == 0);
16087 	un->un_media_id = (char *)bogusID;
16088 	un->un_media_id_len = 0;
16089 	return (0);
16090 }
16091 
16092 typedef int (*media_chk_function)(struct scsi_tape *, ubufunc_t bufunc);
16093 
16094 media_chk_function media_chk_functions[] = {
16095 	st_get_media_id_via_media_serial_cmd,
16096 	st_get_media_id_via_read_attribute,
16097 	st_bogus_media_id
16098 };
16099 
16100 static int
16101 st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc)
16102 {
16103 	int result = 0;
16104 	int i;
16105 
16106 	ST_FUNC(ST_DEVINFO, st_get_media_identification);
16107 
16108 	for (i = 0; i < ST_NUM_MEMBERS(media_chk_functions); i++) {
16109 		if (result == ENOTTY) {
16110 			/*
16111 			 * Last operation type not supported by this device.
16112 			 * Make so next time it doesn`t do that again.
16113 			 */
16114 			un->un_media_id_method = media_chk_functions[i];
16115 		} else if (un->un_media_id_method != media_chk_functions[i] &&
16116 		    un->un_media_id_method != st_get_media_identification) {
16117 			continue;
16118 		}
16119 		result = media_chk_functions[i](un, bufunc);
16120 		/*
16121 		 * If result indicates the function was successful or
16122 		 * that the media is not the same as last known, break.
16123 		 */
16124 		if (result == 0 || result == ESPIPE) {
16125 			break;
16126 		}
16127 	}
16128 
16129 	return (result);
16130 }
16131 
16132 static errstate
16133 st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
16134     errstate onentry)
16135 {
16136 
16137 	int ret;
16138 	st_err_info *errinfo;
16139 	recov_info *ri = (recov_info *)pkt->pkt_private;
16140 
16141 	ST_FUNC(ST_DEVINFO, st_command_recovery);
16142 
16143 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16144 
16145 	ASSERT(un->un_recov_buf_busy == 0);
16146 
16147 	/*
16148 	 * Don't try and recover a reset that this device sent.
16149 	 */
16150 	if (un->un_rsvd_status & ST_INITIATED_RESET &&
16151 	    onentry == DEVICE_RESET) {
16152 		return (COMMAND_DONE_ERROR);
16153 	}
16154 
16155 	/*
16156 	 * See if expected position was passed with scsi_pkt.
16157 	 */
16158 	if (ri->privatelen == sizeof (recov_info)) {
16159 
16160 		/*
16161 		 * Not for this command.
16162 		 */
16163 		if (ri->cmd_attrib->do_not_recover) {
16164 			return (COMMAND_DONE_ERROR);
16165 		}
16166 
16167 		/*
16168 		 * Create structure to hold all error state info.
16169 		 */
16170 		errinfo = kmem_zalloc(sizeof (st_err_info), KM_SLEEP);
16171 		errinfo->ei_error_type = onentry;
16172 		errinfo->ei_failing_bp = ri->cmd_bp;
16173 		COPY_POS(&errinfo->ei_expected_pos, &ri->pos);
16174 	} else {
16175 		/* disabled */
16176 		return (COMMAND_DONE_ERROR);
16177 	}
16178 
16179 	bcopy(pkt, &errinfo->ei_failed_pkt, sizeof (struct scsi_pkt));
16180 	bcopy(pkt->pkt_scbp, &errinfo->ei_failing_status, SECMDS_STATUS_SIZE);
16181 	ret = ddi_taskq_dispatch(un->un_recov_taskq, st_recover, errinfo,
16182 	    DDI_NOSLEEP);
16183 	ASSERT(ret == DDI_SUCCESS);
16184 	if (ret != DDI_SUCCESS) {
16185 		kmem_free(errinfo, sizeof (st_err_info));
16186 		return (COMMAND_DONE_ERROR);
16187 	}
16188 	return (JUST_RETURN); /* release calling thread */
16189 }
16190 
16191 static void
16192 st_recov_ret(struct scsi_tape *un, st_err_info *errinfo, errstate err)
16193 {
16194 	int error_number;
16195 	buf_t *bp;
16196 
16197 
16198 	ST_FUNC(ST_DEVINFO, st_recov_ret);
16199 
16200 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16201 
16202 	bp = errinfo->ei_failing_bp;
16203 	kmem_free(errinfo, sizeof (st_err_info));
16204 
16205 	switch (err) {
16206 	case JUST_RETURN:
16207 		mutex_exit(&un->un_sd->sd_mutex);
16208 		return;
16209 
16210 	case COMMAND_DONE:
16211 	case COMMAND_DONE_ERROR_RECOVERED:
16212 		ST_DO_KSTATS(bp, kstat_runq_exit);
16213 		error_number = 0;
16214 		break;
16215 
16216 	default:
16217 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16218 		    "st_recov_ret with unhandled errstat %d\n", err);
16219 		/* FALLTHROUGH */
16220 	case COMMAND_DONE_ERROR:
16221 	case COMMAND_DONE_EACCES:
16222 		ST_DO_KSTATS(bp, kstat_waitq_exit);
16223 		ST_DO_ERRSTATS(un, st_transerrs);
16224 		error_number = EIO;
16225 		st_set_pe_flag(un);
16226 		break;
16227 
16228 	}
16229 	st_bioerror(bp, error_number);
16230 	st_done_and_mutex_exit(un, bp);
16231 }
16232 
16233 static void
16234 st_recover(void *arg)
16235 {
16236 	st_err_info *const errinfo = (st_err_info *)arg;
16237 	uchar_t com = errinfo->ei_failed_pkt.pkt_cdbp[0];
16238 	struct scsi_tape *un;
16239 	tapepos_t cur_pos;
16240 	int rval;
16241 	errstate status = COMMAND_DONE_ERROR;
16242 	recov_info *rcv;
16243 	buf_t *bp;
16244 
16245 
16246 	rcv = errinfo->ei_failed_pkt.pkt_private;
16247 	ASSERT(rcv->privatelen == sizeof (recov_info));
16248 	bp = rcv->cmd_bp;
16249 
16250 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16251 
16252 	ASSERT(un != NULL);
16253 
16254 	mutex_enter(ST_MUTEX);
16255 
16256 	ST_FUNC(ST_DEVINFO, st_recover);
16257 
16258 	ST_CDB(ST_DEVINFO, "Recovering command",
16259 	    (caddr_t)errinfo->ei_failed_pkt.pkt_cdbp);
16260 	ST_SENSE(ST_DEVINFO, "sense status for failed command",
16261 	    (caddr_t)&errinfo->ei_failing_status,
16262 	    sizeof (struct scsi_arq_status));
16263 	ST_POS(ST_DEVINFO, rcv->cmd_attrib->recov_pos_type == POS_STARTING ?
16264 	    "starting position for recovery command" :
16265 	    "expected position for recovery command",
16266 	    &errinfo->ei_expected_pos);
16267 
16268 	rval = st_test_path_to_device(un);
16269 
16270 	/*
16271 	 * If the drive responed to the TUR lets try and get it to sync
16272 	 * any data it have in the buffer.
16273 	 */
16274 	if (rval == 0 && rcv->cmd_attrib->chg_tape_data) {
16275 		(void) st_rcmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
16276 	}
16277 	switch (errinfo->ei_error_type) {
16278 	case ATTEMPT_RETRY:
16279 	case COMMAND_TIMEOUT:
16280 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16281 		    "st_recover called with COMMAND_TIMEOUT, TUR returned %d\n",
16282 		    rval);
16283 		if (rval != 0) {
16284 			/* ping failed, we're done. */
16285 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16286 			return;
16287 		}
16288 
16289 		/*
16290 		 * If a reset occured fall through.
16291 		 */
16292 		if (un->un_unit_attention_flags == 0) {
16293 			break;
16294 		}
16295 		/* FALLTHROUGH */
16296 	case DEVICE_RESET:
16297 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16298 		    "st_recover called with DEVICE_RESET, TUR returned %d\n",
16299 		    rval);
16300 		/*
16301 		 * For now if we can't talk to the device we are done.
16302 		 */
16303 		if (rval) {
16304 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16305 			return;
16306 		}
16307 
16308 		if ((un->un_rsvd_status & ST_LOST_RESERVE) &&
16309 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] != SCMD_RELEASE)) {
16310 			rval = st_reserve_release(un, ST_RESERVE,
16311 			    st_uscsi_rcmd);
16312 			if (rval == 0) {
16313 				un->un_rsvd_status |= ST_RESERVE;
16314 				un->un_rsvd_status &= ~(ST_RELEASE |
16315 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
16316 				    ST_INITIATED_RESET);
16317 			} else {
16318 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16319 				return;
16320 			}
16321 			rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16322 			if (rval) {
16323 				rval = st_gen_mode_select(un, st_uscsi_rcmd,
16324 				    un->un_mspl, sizeof (struct seq_mode));
16325 			}
16326 			if (rval) {
16327 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16328 				return;
16329 			}
16330 		}
16331 		break;
16332 	case PATH_FAILED:
16333 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16334 		    "st_recover called with PATH_FAILED, TUR returned %d\n",
16335 		    rval);
16336 		if (rval != 0) {
16337 			/* ping failed, we're done. */
16338 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16339 			return;
16340 		}
16341 		break;
16342 	case DEVICE_TAMPER:
16343 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16344 		    "st_recover called with DEVICE_TAMPER, TUR returned %d\n",
16345 		    rval);
16346 		/*
16347 		 * Check if the ASC/ASCQ says mode data has changed.
16348 		 */
16349 		if (errinfo->ei_failing_status.sts_sensedata.es_add_code ==
16350 		    0x2a &&
16351 		    errinfo->ei_failing_status.sts_sensedata.es_qual_code ==
16352 		    0x01) {
16353 			/*
16354 			 * See if mode sense changed.
16355 			 */
16356 			rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16357 			/*
16358 			 * if not cross your fingers and go for it.
16359 			 */
16360 			if (rval == 0) {
16361 				st_recov_ret(un, errinfo, COMMAND_DONE);
16362 				return;
16363 			}
16364 			/*
16365 			 * If so change it back.
16366 			 */
16367 			rval = st_gen_mode_select(un, st_uscsi_rcmd,
16368 			    un->un_mspl, sizeof (struct seq_mode));
16369 			if (rval) {
16370 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16371 			} else {
16372 				st_recov_ret(un, errinfo, COMMAND_DONE);
16373 			}
16374 			return;
16375 		}
16376 		/*
16377 		 * if we have a media id and its not bogus.
16378 		 * Check to see if it the same.
16379 		 */
16380 		if (un->un_media_id != NULL && un->un_media_id != bogusID) {
16381 			rval = st_get_media_identification(un, st_uscsi_rcmd);
16382 			if (rval == ESPIPE) {
16383 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16384 				return;
16385 			}
16386 		}
16387 		break;
16388 	default:
16389 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16390 		    "Unhandled error type 0x%x in st_recover()\n", com);
16391 	}
16392 
16393 	/*
16394 	 * if command is retriable retry it
16395 	 */
16396 	if (rcv->cmd_attrib->retriable) {
16397 		status = st_recover_reissue_pkt(un, &errinfo->ei_failed_pkt);
16398 
16399 	/*
16400 	 * if drive doesn't support read position we are done
16401 	 */
16402 	} else if (un->un_read_pos_type == NO_POS) {
16403 		status = COMMAND_DONE_ERROR;
16404 	/*
16405 	 * If this command results in a changed tape position,
16406 	 * lets see where we are.
16407 	 */
16408 	} else if (rcv->cmd_attrib->chg_tape_pos) {
16409 		/*
16410 		 * XXX May be a reason to choose a different type here.
16411 		 * Long format has file position information.
16412 		 * Short and Extended have information about whats
16413 		 * in the buffer. St's positioning assumes in the buffer
16414 		 * to be the same as on tape.
16415 		 */
16416 		rval = st_compare_expected_position(un, errinfo,
16417 		    rcv->cmd_attrib, &cur_pos);
16418 		if (rval == 0) {
16419 			status = COMMAND_DONE;
16420 		} else if (rval == EAGAIN) {
16421 			status = st_recover_reissue_pkt(un,
16422 			    &errinfo->ei_failed_pkt);
16423 		} else {
16424 			status = COMMAND_DONE_ERROR;
16425 		}
16426 	} else {
16427 		ASSERT(0);
16428 	}
16429 
16430 	st_recov_ret(un, errinfo, status);
16431 }
16432 
16433 static void
16434 st_recov_cb(struct scsi_pkt *pkt)
16435 {
16436 	struct scsi_tape *un;
16437 	struct buf *bp;
16438 	recov_info *rcv;
16439 	errstate action = COMMAND_DONE;
16440 	int timout = ST_TRAN_BUSY_TIMEOUT; /* short (default) timeout */
16441 
16442 	/*
16443 	 * Get the buf from the packet.
16444 	 */
16445 	rcv = pkt->pkt_private;
16446 	ASSERT(rcv->privatelen == sizeof (recov_info));
16447 	bp = rcv->cmd_bp;
16448 
16449 	/*
16450 	 * get the unit from the buf.
16451 	 */
16452 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16453 	ASSERT(un != NULL);
16454 
16455 	ST_FUNC(ST_DEVINFO, st_recov_cb);
16456 
16457 	mutex_enter(ST_MUTEX);
16458 
16459 	ASSERT(bp == un->un_recov_buf);
16460 
16461 
16462 	switch (pkt->pkt_reason) {
16463 	case CMD_CMPLT:
16464 		if (un->un_arq_enabled && pkt->pkt_state & STATE_ARQ_DONE) {
16465 			action = st_handle_autosense(un, bp, &rcv->pos);
16466 		} else if (*pkt->pkt_scbp & (STATUS_BUSY | STATUS_CHECK)) {
16467 			action = st_check_error(un, pkt);
16468 		}
16469 		break;
16470 	case CMD_TIMEOUT:
16471 		action = COMMAND_TIMEOUT;
16472 		break;
16473 	default:
16474 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16475 		    "pkt_reason not handled yet %s",
16476 		    scsi_rname(pkt->pkt_reason));
16477 		action = COMMAND_DONE_ERROR;
16478 	}
16479 
16480 	switch (action) {
16481 	case COMMAND_DONE:
16482 		break;
16483 
16484 	case COMMAND_DONE_EACCES:
16485 		bioerror(bp, EACCES);
16486 		break;
16487 
16488 	case COMMAND_TIMEOUT:
16489 	case COMMAND_DONE_ERROR:
16490 		bioerror(bp, EIO);
16491 		break;
16492 
16493 	case DEVICE_RESET:
16494 	case QUE_BUSY_COMMAND:
16495 		/* longish timeout */
16496 		timout = ST_STATUS_BUSY_TIMEOUT;
16497 		/* FALLTHRU */
16498 	case QUE_COMMAND:
16499 	case DEVICE_TAMPER:
16500 	case ATTEMPT_RETRY:
16501 		/*
16502 		 * let st_handle_intr_busy put this bp back on waitq and make
16503 		 * checks to see if it is ok to requeue the command.
16504 		 */
16505 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
16506 
16507 		/*
16508 		 * Save the throttle before setting up the timeout
16509 		 */
16510 		if (un->un_throttle) {
16511 			un->un_last_throttle = un->un_throttle;
16512 		}
16513 		mutex_exit(ST_MUTEX);
16514 		if (st_handle_intr_busy(un, bp, timout) == 0) {
16515 			return;		/* timeout is setup again */
16516 		}
16517 		mutex_enter(ST_MUTEX);
16518 		un->un_pos.pmode = invalid;
16519 		un->un_err_resid = bp->b_resid = bp->b_bcount;
16520 		st_bioerror(bp, EIO);
16521 		st_set_pe_flag(un);
16522 		break;
16523 
16524 	default:
16525 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16526 		    "Unhandled recovery state 0x%x\n", action);
16527 		un->un_pos.pmode = invalid;
16528 		un->un_err_resid = bp->b_resid = bp->b_bcount;
16529 		st_bioerror(bp, EIO);
16530 		st_set_pe_flag(un);
16531 		break;
16532 	}
16533 
16534 	st_done_and_mutex_exit(un, bp);
16535 }
16536 
16537 static int
16538 st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait)
16539 {
16540 	struct buf *bp;
16541 	int err;
16542 
16543 	ST_FUNC(ST_DEVINFO, st_rcmd);
16544 
16545 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16546 	    "st_rcmd(un = 0x%p, com = 0x%x, count = %"PRIx64", wait = %d)\n",
16547 	    (void *)un, com, count, wait);
16548 
16549 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16550 	ASSERT(mutex_owned(ST_MUTEX));
16551 
16552 #ifdef STDEBUG
16553 	if ((st_debug & 0x7)) {
16554 		st_debug_cmds(un, com, count, wait);
16555 	}
16556 #endif
16557 
16558 	while (un->un_recov_buf_busy)
16559 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
16560 	un->un_recov_buf_busy = 1;
16561 
16562 	bp = un->un_recov_buf;
16563 	bzero(bp, sizeof (buf_t));
16564 
16565 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
16566 
16567 	err = st_setup_cmd(un, bp, com, count);
16568 
16569 	un->un_recov_buf_busy = 0;
16570 
16571 	cv_signal(&un->un_recov_buf_cv);
16572 
16573 	return (err);
16574 }
16575 
16576 /* args used */
16577 static int
16578 st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
16579 {
16580 	int rval;
16581 	buf_t *bp;
16582 
16583 	ST_FUNC(ST_DEVINFO, st_uscsi_rcmd);
16584 	ASSERT(flag == FKIOCTL);
16585 
16586 	/*
16587 	 * Get buffer resources...
16588 	 */
16589 	while (un->un_recov_buf_busy)
16590 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
16591 	un->un_recov_buf_busy = 1;
16592 
16593 	bp = un->un_recov_buf;
16594 	bzero(bp, sizeof (buf_t));
16595 
16596 	bp->b_forw = (struct buf *)(uintptr_t)ucmd->uscsi_cdb[0];
16597 	bp->b_back = (struct buf *)ucmd;
16598 
16599 	mutex_exit(ST_MUTEX);
16600 	rval = scsi_uscsi_handle_cmd(un->un_dev, UIO_SYSSPACE, ucmd,
16601 	    st_strategy, bp, NULL);
16602 	mutex_enter(ST_MUTEX);
16603 
16604 	ucmd->uscsi_resid = bp->b_resid;
16605 
16606 	/*
16607 	 * Free resources
16608 	 */
16609 	un->un_recov_buf_busy = 0;
16610 	cv_signal(&un->un_recov_buf_cv);
16611 
16612 	return (rval);
16613 }
16614 
16615 /*
16616  * Add data to scsi_pkt to help know what to do if the command fails.
16617  */
16618 static void
16619 st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
16620     struct scsi_pkt *pkt)
16621 {
16622 	uint64_t count;
16623 	recov_info *rinfo = (recov_info *)pkt->pkt_private;
16624 
16625 	ST_FUNC(ST_DEVINFO, st_add_recovery_info_to_pkt);
16626 
16627 	ASSERT(rinfo->privatelen == sizeof (pkt_info) ||
16628 	    rinfo->privatelen == sizeof (recov_info));
16629 
16630 	SET_BP_PKT(bp, pkt);
16631 	rinfo->cmd_bp = bp;
16632 
16633 	if (rinfo->privatelen != sizeof (recov_info)) {
16634 		return;
16635 	}
16636 
16637 	rinfo->cmd_bp = bp;
16638 
16639 	rinfo->cmd_attrib = NULL;
16640 
16641 	/*
16642 	 * lookup the command attributes and add them to the recovery info.
16643 	 */
16644 	rinfo->cmd_attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
16645 
16646 	ASSERT(rinfo->cmd_attrib);
16647 
16648 	/*
16649 	 * For commands that there is no way to figure the expected position
16650 	 * once completed, we save the position the command was started from
16651 	 * so that if they fail we can position back and try again.
16652 	 * This has already been done in st_cmd() or st_iscsi_cmd().
16653 	 */
16654 	if (rinfo->cmd_attrib->recov_pos_type == POS_STARTING) {
16655 		/* save current position as the starting position. */
16656 		COPY_POS(&rinfo->pos, &un->un_pos);
16657 		un->un_running.pmode = invalid;
16658 		return;
16659 	}
16660 
16661 	/*
16662 	 * Don't want to update the running position for recovery.
16663 	 */
16664 	if (bp == un->un_recov_buf) {
16665 		rinfo->pos.pmode = un->un_running.pmode;
16666 		return;
16667 	}
16668 	/*
16669 	 * If running position is invalid copy the current position.
16670 	 * Running being set invalid means we are not in a read, write
16671 	 * or write filemark sequence.
16672 	 * We'll copy the current position and start from there.
16673 	 */
16674 	if (un->un_running.pmode == invalid) {
16675 		COPY_POS(&un->un_running, &un->un_pos);
16676 		COPY_POS(&rinfo->pos, &un->un_running);
16677 	} else {
16678 		COPY_POS(&rinfo->pos, &un->un_running);
16679 		if (rinfo->pos.pmode == legacy) {
16680 			/*
16681 			 * Always should be more logical blocks then
16682 			 * data blocks and files marks.
16683 			 */
16684 			ASSERT((rinfo->pos.blkno >= 0) ?
16685 			    rinfo->pos.lgclblkno >=
16686 			    (rinfo->pos.blkno + rinfo->pos.fileno) : 1);
16687 		}
16688 	}
16689 
16690 	/*
16691 	 * If the command is not expected to change the drive position
16692 	 * then the running position should be the expected position.
16693 	 */
16694 	if (rinfo->cmd_attrib->chg_tape_pos == 0) {
16695 		ASSERT(rinfo->cmd_attrib->chg_tape_direction == DIR_NONE);
16696 		return;
16697 	}
16698 
16699 	if (rinfo->cmd_attrib->explicit) {
16700 		ASSERT(rinfo->pos.pmode != invalid);
16701 		ASSERT(rinfo->cmd_attrib->get_cnt);
16702 		count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
16703 		/*
16704 		 * This is a user generated CDB.
16705 		 */
16706 		if (bp == un->un_sbufp) {
16707 			uint64_t lbn;
16708 
16709 			lbn = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
16710 
16711 			/*
16712 			 * See if this CDB will generate a locate or change
16713 			 * partition.
16714 			 */
16715 			if ((lbn != un->un_running.lgclblkno) ||
16716 			    (pkt->pkt_cdbp[3] != un->un_running.partition)) {
16717 				rinfo->pos.partition = pkt->pkt_cdbp[3];
16718 				rinfo->pos.pmode = logical;
16719 				rinfo->pos.lgclblkno = lbn;
16720 				un->un_running.partition = pkt->pkt_cdbp[3];
16721 				un->un_running.pmode = logical;
16722 				un->un_running.lgclblkno = lbn;
16723 			}
16724 		} else {
16725 			uint64_t lbn = un->un_running.lgclblkno;
16726 
16727 			pkt->pkt_cdbp[3]  = (uchar_t)un->un_running.partition;
16728 
16729 			pkt->pkt_cdbp[4]  = (uchar_t)(lbn >> 56);
16730 			pkt->pkt_cdbp[5]  = (uchar_t)(lbn >> 48);
16731 			pkt->pkt_cdbp[6]  = (uchar_t)(lbn >> 40);
16732 			pkt->pkt_cdbp[7]  = (uchar_t)(lbn >> 32);
16733 			pkt->pkt_cdbp[8]  = (uchar_t)(lbn >> 24);
16734 			pkt->pkt_cdbp[9]  = (uchar_t)(lbn >> 16);
16735 			pkt->pkt_cdbp[10] = (uchar_t)(lbn >> 8);
16736 			pkt->pkt_cdbp[11] = (uchar_t)(lbn);
16737 		}
16738 		rinfo->pos.lgclblkno += count;
16739 		rinfo->pos.blkno += count;
16740 		un->un_running.lgclblkno += count;
16741 		return;
16742 	}
16743 
16744 	if (rinfo->cmd_attrib->chg_tape_pos) {
16745 
16746 		/* should not have got an invalid position from running. */
16747 		if (un->un_mediastate == MTIO_INSERTED) {
16748 			ASSERT(rinfo->pos.pmode != invalid);
16749 		}
16750 
16751 		/* should have either a get count or or get lba function */
16752 		ASSERT(rinfo->cmd_attrib->get_cnt != NULL ||
16753 		    rinfo->cmd_attrib->get_lba != NULL);
16754 
16755 		/* only explicit commands have both and they're handled above */
16756 		ASSERT(!(rinfo->cmd_attrib->get_cnt != NULL &&
16757 		    rinfo->cmd_attrib->get_lba != NULL));
16758 
16759 		/* if it has a get count function */
16760 		if (rinfo->cmd_attrib->get_cnt != NULL) {
16761 			count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
16762 			if (count == 0) {
16763 				return;
16764 			}
16765 			/*
16766 			 * Changes position but doesn't transfer data.
16767 			 * i.e. rewind, write_file_mark and load.
16768 			 */
16769 			if (rinfo->cmd_attrib->transfers_data == TRAN_NONE) {
16770 				switch (rinfo->cmd_attrib->chg_tape_direction) {
16771 				case DIR_NONE: /* Erase */
16772 					ASSERT(rinfo->cmd_attrib->cmd ==
16773 					    SCMD_ERASE);
16774 					break;
16775 				case DIR_FORW: /* write_file_mark */
16776 					rinfo->pos.fileno += count;
16777 					rinfo->pos.lgclblkno += count;
16778 					rinfo->pos.blkno = 0;
16779 					un->un_running.fileno += count;
16780 					un->un_running.lgclblkno += count;
16781 					un->un_running.blkno = 0;
16782 					break;
16783 				case DIR_REVC: /* rewind */
16784 					rinfo->pos.fileno = 0;
16785 					rinfo->pos.lgclblkno = 0;
16786 					rinfo->pos.blkno = 0;
16787 					rinfo->pos.eof = ST_NO_EOF;
16788 					rinfo->pos.pmode = legacy;
16789 					un->un_running.fileno = 0;
16790 					un->un_running.lgclblkno = 0;
16791 					un->un_running.blkno = 0;
16792 					un->un_running.eof = ST_NO_EOF;
16793 					if (un->un_running.pmode != legacy)
16794 						un->un_running.pmode = legacy;
16795 					break;
16796 				case DIR_EITH: /* Load unload */
16797 					ASSERT(rinfo->cmd_attrib->cmd ==
16798 					    SCMD_LOAD);
16799 					switch (count & (LD_LOAD | LD_RETEN |
16800 					    LD_RETEN | LD_HOLD)) {
16801 					case LD_UNLOAD:
16802 					case LD_RETEN:
16803 					case LD_HOLD:
16804 					case LD_LOAD | LD_HOLD:
16805 					case LD_EOT | LD_HOLD:
16806 					case LD_RETEN | LD_HOLD:
16807 						rinfo->pos.pmode = invalid;
16808 						un->un_running.pmode = invalid;
16809 						break;
16810 					case LD_EOT:
16811 					case LD_LOAD | LD_EOT:
16812 						rinfo->pos.eof = ST_EOT;
16813 						rinfo->pos.pmode = invalid;
16814 						un->un_running.eof = ST_EOT;
16815 						un->un_running.pmode = invalid;
16816 						break;
16817 					case LD_LOAD:
16818 					case LD_RETEN | LD_LOAD:
16819 						rinfo->pos.fileno = 0;
16820 						rinfo->pos.lgclblkno = 0;
16821 						rinfo->pos.blkno = 0;
16822 						rinfo->pos.eof = ST_NO_EOF;
16823 						rinfo->pos.pmode = legacy;
16824 						un->un_running.fileno = 0;
16825 						un->un_running.lgclblkno = 0;
16826 						un->un_running.blkno = 0;
16827 						un->un_running.eof = ST_NO_EOF;
16828 						break;
16829 					default:
16830 						ASSERT(0);
16831 					}
16832 					break;
16833 				default:
16834 					ASSERT(0);
16835 					break;
16836 				}
16837 			} else {
16838 				/*
16839 				 * Changes position and does transfer data.
16840 				 * i.e. read or write.
16841 				 */
16842 				switch (rinfo->cmd_attrib->chg_tape_direction) {
16843 				case DIR_FORW:
16844 					rinfo->pos.lgclblkno += count;
16845 					rinfo->pos.blkno += count;
16846 					un->un_running.lgclblkno += count;
16847 					un->un_running.blkno += count;
16848 					break;
16849 				case DIR_REVC:
16850 					rinfo->pos.lgclblkno -= count;
16851 					rinfo->pos.blkno -= count;
16852 					un->un_running.lgclblkno -= count;
16853 					un->un_running.blkno -= count;
16854 					break;
16855 				default:
16856 					ASSERT(0);
16857 					break;
16858 				}
16859 			}
16860 		} else if (rinfo->cmd_attrib->get_lba != NULL) {
16861 			/* Have a get LBA fuction. i.e. Locate */
16862 			ASSERT(rinfo->cmd_attrib->chg_tape_direction ==
16863 			    DIR_EITH);
16864 			count = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
16865 			un->un_running.lgclblkno = count;
16866 			un->un_running.blkno = 0;
16867 			un->un_running.fileno = 0;
16868 			un->un_running.pmode = logical;
16869 			rinfo->pos.lgclblkno = count;
16870 			rinfo->pos.pmode = invalid;
16871 		} else {
16872 			ASSERT(0);
16873 		}
16874 		return;
16875 	}
16876 
16877 	ST_CDB(ST_DEVINFO, "Unhanded CDB for position prediction",
16878 	    (char *)pkt->pkt_cdbp);
16879 
16880 }
16881 
16882 static int
16883 st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf)
16884 {
16885 	struct seq_mode *current;
16886 	int rval;
16887 	int i;
16888 	caddr_t this;
16889 	caddr_t that;
16890 
16891 	ST_FUNC(ST_DEVINFO, st_check_mode_for_change);
16892 
16893 	/* recovery called with mode tamper before mode selection */
16894 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
16895 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16896 		    "Mode Select not done yet");
16897 		return (0);
16898 	}
16899 
16900 	current = kmem_zalloc(sizeof (struct seq_mode), KM_SLEEP);
16901 
16902 	rval = st_gen_mode_sense(un, ubf, un->un_comp_page, current,
16903 	    sizeof (struct seq_mode));
16904 	if (rval != 0) {
16905 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16906 		    "Mode Sense for mode verification failed");
16907 		kmem_free(current, sizeof (struct seq_mode));
16908 		return (rval);
16909 	}
16910 
16911 	this = (caddr_t)current;
16912 	that = (caddr_t)un->un_mspl;
16913 
16914 	rval = bcmp(this, that, sizeof (struct seq_mode));
16915 	if (rval == 0) {
16916 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16917 		    "Found no changes in mode data");
16918 	}
16919 #ifdef STDEBUG
16920 	else {
16921 		for (i = 1; i < sizeof (struct seq_mode); i++) {
16922 			if (this[i] != that[i]) {
16923 				ST_RECOV(ST_DEVINFO, st_label, CE_CONT,
16924 				    "sense data changed at byte %d was "
16925 				    "0x%x now 0x%x", i,
16926 				    (uchar_t)that[i], (uchar_t)this[i]);
16927 			}
16928 		}
16929 	}
16930 #endif
16931 	kmem_free(current, sizeof (struct seq_mode));
16932 
16933 	return (rval);
16934 }
16935 
16936 static int
16937 st_test_path_to_device(struct scsi_tape *un)
16938 {
16939 	int rval;
16940 
16941 	ST_FUNC(ST_DEVINFO, st_test_path_to_device);
16942 
16943 	/*
16944 	 * XXX Newer drives may not RESEVATION CONFLICT a TUR.
16945 	 */
16946 	do {
16947 		rval = st_rcmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
16948 	} while (rval == DEVICE_RESET);
16949 
16950 	return (rval);
16951 }
16952 
16953 /*
16954  * Does read position using recov_buf and doesn't update un_pos.
16955  * Does what ever kind of read position you want.
16956  */
16957 static int
16958 st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
16959     read_pos_data_t *raw)
16960 {
16961 	int rval;
16962 	struct uscsi_cmd cmd;
16963 	char cdb[CDB_GROUP1];
16964 
16965 	ST_FUNC(ST_DEVINFO, st_recovery_read_pos);
16966 	bzero(&cmd, sizeof (cmd));
16967 
16968 	cdb[0] = SCMD_READ_POSITION;
16969 	cdb[1] = type;
16970 	cdb[2] = 0;
16971 	cdb[3] = 0;
16972 	cdb[4] = 0;
16973 	cdb[5] = 0;
16974 	cdb[6] = 0;
16975 	cdb[7] = 0;
16976 	cdb[8] =  (type == EXT_POS) ? 28 : 0;
16977 	cdb[9] = 0;
16978 
16979 	cmd.uscsi_flags = USCSI_READ;
16980 	cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
16981 	cmd.uscsi_cdb = cdb;
16982 	cmd.uscsi_cdblen = sizeof (cdb);
16983 	cmd.uscsi_bufaddr = (caddr_t)raw;
16984 	switch (type) {
16985 	case SHORT_POS:
16986 		cmd.uscsi_buflen = sizeof (tape_position_t);
16987 		break;
16988 	case LONG_POS:
16989 		cmd.uscsi_buflen = sizeof (tape_position_long_t);
16990 		break;
16991 	case EXT_POS:
16992 		cmd.uscsi_buflen = sizeof (tape_position_ext_t);
16993 		break;
16994 	default:
16995 		ASSERT(0);
16996 	}
16997 
16998 	rval = st_uscsi_rcmd(un, &cmd, FKIOCTL);
16999 	if (cmd.uscsi_status) {
17000 		rval = EIO;
17001 	}
17002 	return (rval);
17003 }
17004 
17005 static int
17006 st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
17007     read_pos_data_t *raw)
17008 {
17009 	int rval;
17010 	read_p_types type = un->un_read_pos_type;
17011 
17012 	ST_FUNC(ST_DEVINFO, st_recovery_get_position);
17013 
17014 	rval = st_recovery_read_pos(un, type, raw);
17015 	if (rval != 0) {
17016 		return (rval);
17017 	}
17018 	rval = st_interpret_read_pos(un, read, type, sizeof (read_pos_data_t),
17019 	    (caddr_t)raw, 1);
17020 
17021 	return (rval);
17022 }
17023 
17024 /*
17025  * based on the command do we retry, continue or give up?
17026  * possable return values?
17027  *	zero do nothing looks fine.
17028  *	EAGAIN retry.
17029  *	EIO failed makes no sense.
17030  */
17031 static int
17032 st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
17033     cmd_attribute const * cmd_att, tapepos_t *read)
17034 {
17035 	int rval;
17036 	read_pos_data_t *readp_datap;
17037 
17038 	ST_FUNC(ST_DEVINFO, st_compare_expected_position);
17039 
17040 	ASSERT(un != NULL);
17041 	ASSERT(ei != NULL);
17042 	ASSERT(read != NULL);
17043 	ASSERT(cmd_att->chg_tape_pos);
17044 
17045 	COPY_POS(read, &ei->ei_expected_pos);
17046 
17047 	readp_datap = kmem_zalloc(sizeof (read_pos_data_t), KM_SLEEP);
17048 
17049 	rval = st_recovery_get_position(un, read, readp_datap);
17050 
17051 	kmem_free(readp_datap, sizeof (read_pos_data_t));
17052 
17053 	if (rval != 0) {
17054 		return (EIO);
17055 	}
17056 
17057 	ST_POS(ST_DEVINFO, "st_compare_expected_position", read);
17058 
17059 	if ((read->pmode == invalid) ||
17060 	    (ei->ei_expected_pos.pmode == invalid)) {
17061 		return (EIO);
17062 	}
17063 
17064 	/*
17065 	 * Command that changes tape position and have an expected position
17066 	 * if it were to chave completed sucessfully.
17067 	 */
17068 	if (cmd_att->recov_pos_type == POS_EXPECTED) {
17069 		uint32_t count;
17070 		int64_t difference;
17071 
17072 		/* At expected? */
17073 		if (read->lgclblkno == ei->ei_expected_pos.lgclblkno) {
17074 			ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17075 			    "Found drive to be at expected position\n");
17076 			return (0); /* Good */
17077 		}
17078 		ASSERT(cmd_att->get_cnt);
17079 		count = cmd_att->get_cnt(ei->ei_failed_pkt.pkt_cdbp);
17080 
17081 		ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17082 		    "Got count from CDB and it was %d\n", count);
17083 		if (cmd_att->chg_tape_direction == DIR_FORW) {
17084 			difference =
17085 			    ei->ei_expected_pos.lgclblkno - read->lgclblkno;
17086 			ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17087 			    "difference between expected and actual is %"
17088 			    PRId64"\n", difference);
17089 			if (count == difference) {
17090 				ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17091 				    "Found failed FORW command, retrying\n");
17092 				return (EAGAIN);
17093 			}
17094 
17095 			/*
17096 			 * If rewound or somewhere between the starting position
17097 			 * and the expected position (partial read or write).
17098 			 * Locate to the starting position and try the whole
17099 			 * thing over again.
17100 			 */
17101 			if ((read->lgclblkno == 0) ||
17102 			    ((difference > 0) && (difference < count))) {
17103 				rval = st_logical_block_locate(un,
17104 				    st_uscsi_rcmd, read,
17105 				    ei->ei_expected_pos.lgclblkno - count,
17106 				    ei->ei_expected_pos.partition);
17107 				if (rval == 0) {
17108 					ST_RECOV(ST_DEVINFO, st_label,
17109 					    SCSI_DEBUG, "reestablished FORW"
17110 					    " command retrying\n");
17111 					return (EAGAIN);
17112 				}
17113 			/* This handles flushed read ahead on the drive */
17114 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17115 			    (difference < 0)) {
17116 				rval = st_logical_block_locate(un,
17117 				    st_uscsi_rcmd, read,
17118 				    ei->ei_expected_pos.lgclblkno - count,
17119 				    ei->ei_expected_pos.partition);
17120 				if (rval == 0) {
17121 					ST_RECOV(ST_DEVINFO, st_label,
17122 					    SCSI_DEBUG, "reestablished FORW"
17123 					    " read command retrying\n");
17124 					return (EAGAIN);
17125 				}
17126 			/*
17127 			 * XXX swag seeing difference of 2 on write filemark.
17128 			 * If the space to the starting position works on a
17129 			 * write that means the previous write made it to tape.
17130 			 * If not we lost data and have to give up.
17131 			 *
17132 			 * The plot thickens. Now I am attempting to cover a
17133 			 * count of 1 and a differance of 2 on a write.
17134 			 */
17135 			} else if (difference > count) {
17136 				rval = st_logical_block_locate(un,
17137 				    st_uscsi_rcmd, read,
17138 				    ei->ei_expected_pos.lgclblkno - count,
17139 				    ei->ei_expected_pos.partition);
17140 				if (rval == 0) {
17141 					ST_RECOV(ST_DEVINFO, st_label,
17142 					    SCSI_DEBUG, "reestablished FORW"
17143 					    " write command retrying\n");
17144 					return (EAGAIN);
17145 				}
17146 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17147 				    "Seek to block %"PRId64" returned %d\n",
17148 				    ei->ei_expected_pos.lgclblkno - count,
17149 				    rval);
17150 			} else {
17151 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17152 				    "Not expected transfers_data = %d "
17153 				    "difference = %"PRId64,
17154 				    cmd_att->transfers_data, difference);
17155 			}
17156 
17157 			return (EIO);
17158 
17159 		} else if (cmd_att->chg_tape_direction == DIR_REVC) {
17160 			/* Don't think we can write backwards */
17161 			ASSERT(cmd_att->transfers_data != TRAN_WRTE);
17162 			difference =
17163 			    read->lgclblkno - ei->ei_expected_pos.lgclblkno;
17164 			ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17165 			    "difference between expected and actual is %"
17166 			    PRId64"\n", difference);
17167 			if (count == difference) {
17168 				ST_RECOV(ST_DEVINFO, st_label, SCSI_DEBUG,
17169 				    "Found failed REVC command, retrying\n");
17170 				return (EAGAIN);
17171 			}
17172 			if ((read->lgclblkno == 0) ||
17173 			    ((difference > 0) && (difference < count))) {
17174 				rval = st_logical_block_locate(un,
17175 				    st_uscsi_rcmd, read,
17176 				    ei->ei_expected_pos.lgclblkno + count,
17177 				    ei->ei_expected_pos.partition);
17178 				if (rval == 0) {
17179 					ST_RECOV(ST_DEVINFO, st_label,
17180 					    SCSI_DEBUG, "reestablished REVC"
17181 					    " command retrying\n");
17182 					return (EAGAIN);
17183 				}
17184 			/* This handles read ahead in reverse direction */
17185 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17186 			    (difference < 0)) {
17187 				rval = st_logical_block_locate(un,
17188 				    st_uscsi_rcmd, read,
17189 				    ei->ei_expected_pos.lgclblkno - count,
17190 				    ei->ei_expected_pos.partition);
17191 				if (rval == 0) {
17192 					ST_RECOV(ST_DEVINFO, st_label,
17193 					    SCSI_DEBUG, "reestablished REVC"
17194 					    " read command retrying\n");
17195 					return (EAGAIN);
17196 				}
17197 			} else {
17198 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17199 				    "Not expected transfers_data = %d "
17200 				    "difference = %"PRId64,
17201 				    cmd_att->transfers_data, difference);
17202 			}
17203 			return (EIO);
17204 
17205 		} else {
17206 			/*
17207 			 * Commands that change tape position either
17208 			 * direction or don't change position should not
17209 			 * get here.
17210 			 */
17211 			ASSERT(0);
17212 		}
17213 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
17214 		    "Didn't find a recoverable position, Failing\n");
17215 
17216 	/*
17217 	 * Command that changes tape position and can only be recovered
17218 	 * by going back to the point of origin and retrying.
17219 	 *
17220 	 * Example SCMD_SPACE.
17221 	 */
17222 	} else if (cmd_att->recov_pos_type == POS_STARTING) {
17223 		/*
17224 		 * This type of command stores the starting position.
17225 		 * If the read position is the starting position,
17226 		 * reissue the command.
17227 		 */
17228 		if (ei->ei_expected_pos.lgclblkno == read->lgclblkno) {
17229 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17230 			    "Found Space command at starting position, "
17231 			    "Reissuing\n");
17232 			return (EAGAIN);
17233 		}
17234 		/*
17235 		 * Not in the position that the command was originally issued,
17236 		 * Attempt to locate to that position.
17237 		 */
17238 		rval = st_logical_block_locate(un, st_uscsi_rcmd, read,
17239 		    ei->ei_expected_pos.lgclblkno,
17240 		    ei->ei_expected_pos.partition);
17241 		if (rval) {
17242 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17243 			    "Found Space at an unexpected position and locate "
17244 			    "back to starting position failed\n");
17245 			return (EIO);
17246 		}
17247 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17248 		    "Found Space at an unexpected position and locate "
17249 		    "back to starting position worked, Reissuing\n");
17250 		return (EAGAIN);
17251 	}
17252 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17253 	    "Unhandled attribute/expected position", &ei->ei_expected_pos);
17254 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17255 	    "Read position above did not make sense", read);
17256 	ASSERT(0);
17257 	return (EIO);
17258 }
17259 
17260 static errstate
17261 st_recover_reissue_pkt(struct scsi_tape *un, struct scsi_pkt *oldpkt)
17262 {
17263 	buf_t *bp;
17264 	buf_t *pkt_bp;
17265 	struct scsi_pkt *newpkt;
17266 	cmd_attribute const *attrib;
17267 	recov_info *rcv = oldpkt->pkt_private;
17268 	uint_t cdblen;
17269 	int rval;
17270 	int stat_size =
17271 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
17272 
17273 	ST_FUNC(ST_DEVINFO, st_recover_reissue_pkt);
17274 
17275 	bp = rcv->cmd_bp;
17276 
17277 	if (rcv->privatelen == sizeof (recov_info)) {
17278 		attrib = rcv->cmd_attrib;
17279 	} else {
17280 		attrib = st_lookup_cmd_attribute(oldpkt->pkt_cdbp[0]);
17281 	}
17282 
17283 	/*
17284 	 * Some non-uscsi commands use the b_bcount for values that
17285 	 * have nothing to do with how much data is transfered.
17286 	 * In those cases we need to hide the buf_t from scsi_init_pkt().
17287 	 */
17288 	if ((BP_UCMD(bp)) && (bp->b_bcount)) {
17289 		pkt_bp = bp;
17290 	} else if (attrib->transfers_data == TRAN_NONE) {
17291 		pkt_bp = NULL;
17292 	} else {
17293 		pkt_bp = bp;
17294 	}
17295 	/*
17296 	 * if this is a queued command make sure it the only one in the
17297 	 * run queue.
17298 	 */
17299 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
17300 		ASSERT(un->un_runqf == un->un_runql);
17301 		ASSERT(un->un_runqf == bp);
17302 	}
17303 
17304 	cdblen = scsi_cdb_size[CDB_GROUPID(oldpkt->pkt_cdbp[0])];
17305 
17306 	newpkt = scsi_init_pkt(ROUTE, NULL, pkt_bp, cdblen,
17307 	    stat_size, rcv->privatelen, 0, NULL_FUNC, NULL);
17308 	if (newpkt == NULL) {
17309 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17310 		    "Reissue pkt scsi_init_pkt() failure\n");
17311 		return (COMMAND_DONE_ERROR);
17312 	}
17313 
17314 	ASSERT(newpkt->pkt_resid == 0);
17315 	bp->b_flags &= ~(B_DONE);
17316 	bp->b_resid = 0;
17317 	st_bioerror(bp, 0);
17318 
17319 	bcopy(oldpkt->pkt_private, newpkt->pkt_private, rcv->privatelen);
17320 
17321 	newpkt->pkt_comp = oldpkt->pkt_comp;
17322 	newpkt->pkt_time = oldpkt->pkt_time;
17323 
17324 	bzero(newpkt->pkt_scbp, stat_size);
17325 	bcopy(oldpkt->pkt_cdbp, newpkt->pkt_cdbp, cdblen);
17326 
17327 	newpkt->pkt_state = 0;
17328 	newpkt->pkt_statistics = 0;
17329 
17330 	oldpkt = BP_PKT(bp);
17331 
17332 	SET_BP_PKT(bp, newpkt);
17333 
17334 	scsi_destroy_pkt(oldpkt);
17335 
17336 	rval = st_transport(un, newpkt);
17337 	if (rval == TRAN_ACCEPT) {
17338 		return (JUST_RETURN);
17339 	}
17340 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17341 	    "Reissue pkt st_transport(0x%x) failure\n", rval);
17342 	if (rval != TRAN_BUSY) {
17343 		return (COMMAND_DONE_ERROR);
17344 	}
17345 	mutex_exit(ST_MUTEX);
17346 	rval = st_handle_start_busy(un, bp, ST_TRAN_BUSY_TIMEOUT, 0);
17347 	mutex_enter(ST_MUTEX);
17348 	if (rval) {
17349 		return (COMMAND_DONE_ERROR);
17350 	}
17351 
17352 	return (JUST_RETURN);
17353 }
17354 
17355 static int
17356 st_transport(struct scsi_tape *un, struct scsi_pkt *pkt)
17357 {
17358 	int status;
17359 
17360 	ST_FUNC(ST_DEVINFO, st_transport);
17361 
17362 	ST_CDB(ST_DEVINFO, "transport CDB", (caddr_t)pkt->pkt_cdbp);
17363 
17364 	mutex_exit(ST_MUTEX);
17365 
17366 	status = scsi_transport(pkt);
17367 
17368 	mutex_enter(ST_MUTEX);
17369 
17370 	return (status);
17371 }
17372 
17373 /*
17374  * Removed the buf_t bp from the queue referenced to by head and tail.
17375  * Returns the buf_t pointer if it is found in the queue.
17376  * Returns NULL if it is not found.
17377  */
17378 static buf_t *
17379 st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp)
17380 {
17381 	buf_t *runqbp;
17382 	buf_t *prevbp = NULL;
17383 
17384 	for (runqbp = *head; runqbp != 0; runqbp = runqbp->av_forw) {
17385 		if (runqbp == bp) {
17386 			/* found it, is it at the head? */
17387 			if (runqbp == *head) {
17388 				*head = bp->av_forw;
17389 			} else {
17390 				prevbp->av_forw = bp->av_forw;
17391 			}
17392 			if (*tail == bp) {
17393 				*tail = prevbp;
17394 			}
17395 			bp->av_forw = NULL;
17396 			return (bp); /* found and removed */
17397 		}
17398 		prevbp = runqbp;
17399 	}
17400 	return (NULL);
17401 }
17402 
17403 /*
17404  * Adds a buf_t to the queue pointed to by head and tail.
17405  * Adds it either to the head end or the tail end based on which
17406  * the passed variable end (head or tail) points at.
17407  */
17408 static void
17409 st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp)
17410 {
17411 
17412 	bp->av_forw = NULL;
17413 	if (*head) {
17414 		/* Queue is not empty */
17415 		if (end == *head) {
17416 			/* Add at front of queue */
17417 			bp->av_forw = *head;
17418 			*head = bp;
17419 		} else if (end == *tail) {
17420 			/* Add at end of queue */
17421 			(*tail)->av_forw = bp;
17422 			*tail = bp;
17423 		} else {
17424 			ASSERT(0);
17425 		}
17426 	} else {
17427 		/* Queue is empty */
17428 		*head = bp;
17429 		*tail = bp;
17430 	}
17431 }
17432 
17433 
17434 static uint64_t
17435 st_get_cdb_g0_rw_count(uchar_t *cdb)
17436 {
17437 	uint64_t count;
17438 
17439 	if ((cdb[1]) & 1) {
17440 		/* fixed block mode, the count is the number of blocks */
17441 		count =
17442 		    cdb[2] << 16 |
17443 		    cdb[3] << 8 |
17444 		    cdb[4];
17445 	} else {
17446 		/* variable block mode, the count is the block size */
17447 		count = 1;
17448 	}
17449 	return (count);
17450 }
17451 
17452 static uint64_t
17453 st_get_cdb_g0_sign_count(uchar_t *cdb)
17454 {
17455 	uint64_t count;
17456 
17457 	count =
17458 	    cdb[2] << 16 |
17459 	    cdb[3] << 8 |
17460 	    cdb[4];
17461 	/*
17462 	 * If the sign bit of the 3 byte value is set, extended it.
17463 	 */
17464 	if (count & 0x800000) {
17465 		count |= 0xffffffffff000000;
17466 	}
17467 	return (count);
17468 }
17469 
17470 static uint64_t
17471 st_get_cdb_g0_count(uchar_t *cdb)
17472 {
17473 	uint64_t count;
17474 
17475 	count =
17476 	    cdb[2] << 16 |
17477 	    cdb[3] << 8 |
17478 	    cdb[4];
17479 	return (count);
17480 }
17481 
17482 static uint64_t
17483 st_get_cdb_g5_rw_cnt(uchar_t *cdb)
17484 {
17485 	uint64_t count;
17486 
17487 	if ((cdb[1]) & 1) {
17488 		/* fixed block mode */
17489 		count =
17490 		    cdb[12] << 16 |
17491 		    cdb[13] << 8 |
17492 		    cdb[14];
17493 	} else {
17494 		/* variable block mode */
17495 		count = 1;
17496 	}
17497 	return (count);
17498 }
17499 
17500 static uint64_t
17501 st_get_no_count(uchar_t *cdb)
17502 {
17503 	ASSERT(cdb[0] == SCMD_REWIND);
17504 	return ((uint64_t)cdb[0]);
17505 }
17506 
17507 static uint64_t
17508 st_get_load_options(uchar_t *cdb)
17509 {
17510 	return ((uint64_t)(cdb[4] | (LD_HOLD << 1)));
17511 }
17512 
17513 static uint64_t
17514 st_get_erase_options(uchar_t *cdb)
17515 {
17516 	return (cdb[1] | (cdb[0] << 8));
17517 }
17518 
17519 static uint64_t
17520 st_get_cdb_g1_lba(uchar_t *cdb)
17521 {
17522 	uint64_t lba;
17523 
17524 	lba =
17525 	    cdb[3] << 24 |
17526 	    cdb[4] << 16 |
17527 	    cdb[5] << 8 |
17528 	    cdb[6];
17529 	return (lba);
17530 }
17531 
17532 static uint64_t
17533 st_get_cdb_g5_count(uchar_t *cdb)
17534 {
17535 	uint64_t count =
17536 	    cdb[12] << 16 |
17537 	    cdb[13] << 8 |
17538 	    cdb[14];
17539 
17540 	return (count);
17541 }
17542 
17543 static uint64_t
17544 st_get_cdb_g4g5_cnt(uchar_t *cdb)
17545 {
17546 	uint64_t lba;
17547 
17548 	lba =
17549 	    (uint64_t)cdb[4] << 56 |
17550 	    (uint64_t)cdb[5] << 48 |
17551 	    (uint64_t)cdb[6] << 40 |
17552 	    (uint64_t)cdb[7] << 32 |
17553 	    (uint64_t)cdb[8] << 24 |
17554 	    (uint64_t)cdb[9] << 16 |
17555 	    (uint64_t)cdb[10] << 8 |
17556 	    (uint64_t)cdb[11];
17557 	return (lba);
17558 }
17559 
17560 static const cmd_attribute cmd_attributes[] = {
17561 	{ SCMD_TEST_UNIT_READY,
17562 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17563 	    0, 0, 0 },
17564 	{ SCMD_REWIND,
17565 	    1, 1, 1, 0, 0, DIR_REVC, TRAN_NONE, POS_EXPECTED,
17566 	    0, 0, 0, st_get_no_count },
17567 	{ SCMD_REQUEST_SENSE,
17568 	    0, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17569 	    0, 0, 0 },
17570 	{ SCMD_READ_BLKLIM,
17571 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17572 	    0, 0, 0 },
17573 	{ SCMD_READ,
17574 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_READ, POS_EXPECTED,
17575 	    0, 0, 0, st_get_cdb_g0_rw_count },
17576 	{ SCMD_WRITE,
17577 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
17578 	    0, 0, 0, st_get_cdb_g0_rw_count },
17579 	{ SCMD_READ_G4,
17580 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_READ, POS_EXPECTED,
17581 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17582 	{ SCMD_WRITE_G4,
17583 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
17584 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17585 	{ SCMD_READ_REVERSE,
17586 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
17587 	    0, 0, 0, st_get_cdb_g0_rw_count },
17588 	{ SCMD_READ_REVERSE_G4,
17589 	    1, 0, 1, 1, 1, DIR_REVC, TRAN_READ, POS_EXPECTED,
17590 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17591 	{ SCMD_WRITE_FILE_MARK,
17592 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17593 	    0, 0, 0, st_get_cdb_g0_count },
17594 	{ SCMD_WRITE_FILE_MARK_G4,
17595 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17596 	    0, 0, 0, st_get_cdb_g5_count, st_get_cdb_g4g5_cnt },
17597 	{ SCMD_SPACE,
17598 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
17599 	    0, 0, 0, st_get_cdb_g0_sign_count },
17600 	{ SCMD_SPACE_G4,
17601 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
17602 	    0, 0, 0, st_get_cdb_g4g5_cnt },
17603 	{ SCMD_INQUIRY,
17604 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17605 	    0, 0, 0 },
17606 	{ SCMD_VERIFY_G0,
17607 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17608 	    0, 0, 0, st_get_cdb_g0_rw_count },
17609 	{ SCMD_VERIFY_G4,
17610 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
17611 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
17612 	{ SCMD_RECOVER_BUF,
17613 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
17614 	    0, 0, 0 },
17615 	{ SCMD_MODE_SELECT,
17616 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17617 	    0, 0, 0 },
17618 	{ SCMD_RESERVE,
17619 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17620 	    0, 0, 0 },
17621 	{ SCMD_RELEASE,
17622 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17623 	    0, 0, 0 },
17624 	{ SCMD_ERASE,
17625 	    1, 0, 1, 1, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17626 	    0, 0, 0, st_get_erase_options },
17627 	{ SCMD_MODE_SENSE,
17628 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17629 	    0, 0, 0 },
17630 	{ SCMD_LOAD,
17631 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
17632 	    0, 0, 0, st_get_load_options },
17633 	{ SCMD_GDIAG,
17634 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17635 	    1, 0, 0 },
17636 	{ SCMD_SDIAG,
17637 	    1, 0, 1, 1, 0, DIR_EITH, TRAN_WRTE, POS_EXPECTED,
17638 	    1, 0, 0 },
17639 	{ SCMD_DOORLOCK,
17640 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
17641 	    0, 4, 3 },
17642 	{ SCMD_LOCATE,
17643 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
17644 	    0, 0, 0, NULL, st_get_cdb_g1_lba },
17645 	{ SCMD_READ_POSITION,
17646 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17647 	    0, 0, 0 },
17648 	{ SCMD_WRITE_BUFFER,
17649 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17650 	    1, 0, 0 },
17651 	{ SCMD_READ_BUFFER,
17652 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17653 	    1, 0, 0 },
17654 	{ SCMD_REPORT_DENSITIES,
17655 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17656 	    0, 0, 0 },
17657 	{ SCMD_LOG_SELECT_G1,
17658 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17659 	    0, 0, 0 },
17660 	{ SCMD_LOG_SENSE_G1,
17661 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17662 	    0, 0, 0 },
17663 	{ SCMD_PRIN,
17664 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17665 	    0, 0, 0 },
17666 	{ SCMD_PROUT,
17667 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17668 	    0, 0, 0 },
17669 	{ SCMD_READ_ATTRIBUTE,
17670 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17671 	    0, 0, 0 },
17672 	{ SCMD_WRITE_ATTRIBUTE,
17673 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17674 	    0, 0, 0 },
17675 	{ SCMD_LOCATE_G4,
17676 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
17677 	    0, 0, 0, NULL, st_get_cdb_g4g5_cnt },
17678 	{ SCMD_REPORT_LUNS,
17679 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17680 	    0, 0, 0 },
17681 	{ SCMD_SVC_ACTION_IN_G5,
17682 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17683 	    0, 0, 0 },
17684 	{ SCMD_MAINTENANCE_IN,
17685 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
17686 	    0, 0, 0 },
17687 	{ SCMD_MAINTENANCE_OUT,
17688 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
17689 	    0, 0, 0 },
17690 	{ 0xff, /* Default attribute for unsupported commands */
17691 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_STARTING,
17692 	    1, 0, 0, NULL, NULL }
17693 };
17694 
17695 static const cmd_attribute *
17696 st_lookup_cmd_attribute(unsigned char cmd)
17697 {
17698 	int i;
17699 	cmd_attribute const *attribute;
17700 
17701 	for (i = 0; i < ST_NUM_MEMBERS(cmd_attributes); i++) {
17702 		attribute = &cmd_attributes[i];
17703 		if (attribute->cmd == cmd) {
17704 			return (attribute);
17705 		}
17706 	}
17707 	ASSERT(attribute);
17708 	return (attribute);
17709 }
17710 
17711 static int
17712 st_reset(struct scsi_tape *un, int reset_type)
17713 {
17714 	int rval;
17715 
17716 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
17717 
17718 	ST_FUNC(ST_DEVINFO, st_reset);
17719 	un->un_rsvd_status |= ST_INITIATED_RESET;
17720 	mutex_exit(ST_MUTEX);
17721 	do {
17722 		rval = scsi_reset(&un->un_sd->sd_address, reset_type);
17723 		if (rval == 0) {
17724 			switch (reset_type) {
17725 			case RESET_LUN:
17726 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
17727 				    "LUN reset failed trying target reset");
17728 				reset_type = RESET_TARGET;
17729 				break;
17730 			case RESET_TARGET:
17731 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
17732 				    "target reset failed trying bus reset");
17733 				reset_type = RESET_BUS;
17734 				break;
17735 			case RESET_BUS:
17736 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
17737 				    "bus reset failed trying all reset");
17738 				reset_type = RESET_ALL;
17739 			default:
17740 				mutex_enter(ST_MUTEX);
17741 				return (rval);
17742 			}
17743 		}
17744 	} while (rval == 0);
17745 	mutex_enter(ST_MUTEX);
17746 	return (rval);
17747 }
17748 
17749 
17750 static void
17751 st_reset_notification(caddr_t arg)
17752 {
17753 	struct scsi_tape *un = (struct scsi_tape *)arg;
17754 
17755 	ST_FUNC(ST_DEVINFO, st_reset_notification);
17756 	mutex_enter(ST_MUTEX);
17757 
17758 	un->un_unit_attention_flags = 2;
17759 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
17760 	    ST_RESERVE) {
17761 		un->un_rsvd_status |= ST_LOST_RESERVE;
17762 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
17763 		    "Lost Reservation notification");
17764 	} else {
17765 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
17766 		    "reset notification");
17767 	}
17768 
17769 	if ((un->un_restore_pos == 0) &&
17770 	    (un->un_state == ST_STATE_CLOSED) ||
17771 	    (un->un_state == ST_STATE_OPEN_PENDING_IO) ||
17772 	    (un->un_state == ST_STATE_CLOSING)) {
17773 		un->un_restore_pos = 1;
17774 	}
17775 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
17776 	    "reset and state was %d\n", un->un_state);
17777 	mutex_exit(ST_MUTEX);
17778 }
17779