xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/st.c (revision 2b098703ef923462f146ba7da47baeb859c93a4d)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * SCSI	 SCSA-compliant and not-so-DDI-compliant Tape Driver
31  */
32 
33 #if defined(lint) && !defined(DEBUG)
34 #define	DEBUG	1
35 #endif
36 
37 #include <sys/modctl.h>
38 #include <sys/scsi/scsi.h>
39 #include <sys/mtio.h>
40 #include <sys/scsi/targets/stdef.h>
41 #include <sys/file.h>
42 #include <sys/kstat.h>
43 #include <sys/ddidmareq.h>
44 #include <sys/ddi.h>
45 #include <sys/sunddi.h>
46 
47 #define	IOSP	KSTAT_IO_PTR(un->un_stats)
48 /*
49  * stats maintained only for reads/writes as commands
50  * like rewind etc skew the wait/busy times
51  */
52 #define	IS_RW(bp) 	((bp)->b_bcount > 0)
53 #define	ST_DO_KSTATS(bp, kstat_function) \
54 	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
55 		kstat_function(IOSP); \
56 	}
57 
58 #define	ST_DO_ERRSTATS(un, x)  \
59 	if (un->un_errstats) { \
60 		struct st_errstats *stp; \
61 		stp = (struct st_errstats *)un->un_errstats->ks_data; \
62 		stp->x.value.ul++; \
63 	}
64 
65 #define	FILL_SCSI1_LUN(devp, pkt) 					\
66 	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
67 		int _lun;						\
68 		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
69 		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
70 		if (_lun > 0) {						\
71 			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
72 			    _lun;					\
73 		}							\
74 	}
75 
76 /*
77  * get an available contig mem header, cp.
78  * when big_enough is true, we will return NULL, if no big enough
79  * contig mem is found.
80  * when big_enough is false, we will try to find cp containing big
81  * enough contig mem. if not found, we will ruturn the last cp available.
82  *
83  * used by st_get_contig_mem()
84  */
85 #define	ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough) {		\
86 	struct contig_mem *tmp_cp = NULL;				\
87 	for ((cp) = (un)->un_contig_mem;				\
88 	    (cp) != NULL;						\
89 	    tmp_cp = (cp), (cp) = (cp)->cm_next) { 			\
90 		if (((cp)->cm_len >= (len)) || 				\
91 		    (!(big_enough) && ((cp)->cm_next == NULL))) { 	\
92 			if (tmp_cp == NULL) { 				\
93 				(un)->un_contig_mem = (cp)->cm_next; 	\
94 			} else { 					\
95 				tmp_cp->cm_next = (cp)->cm_next; 	\
96 			} 						\
97 			(cp)->cm_next = NULL; 				\
98 			(un)->un_contig_mem_available_num--; 		\
99 			break; 						\
100 		} 							\
101 	} 								\
102 }
103 
104 #define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
105 #define	COPY_POS(dest, source) bcopy(source, dest, sizeof (tapepos_t))
106 
107 #define	ONE_K	1024
108 
109 /*
110  * Global External Data Definitions
111  */
112 extern struct scsi_key_strings scsi_cmds[];
113 extern uchar_t	scsi_cdb_size[];
114 
115 /*
116  * Local Static Data
117  */
118 static void *st_state;
119 static char *const st_label = "st";
120 
121 #if defined(__i386) || defined(__amd64)
122 /*
123  * We need to use below DMA attr to alloc physically contiguous
124  * memory to do I/O in big block size
125  */
126 static ddi_dma_attr_t st_contig_mem_dma_attr = {
127 	DMA_ATTR_V0,    /* version number */
128 	0x0,		/* lowest usable address */
129 	0xFFFFFFFFull,  /* high DMA address range */
130 	0xFFFFFFFFull,  /* DMA counter register */
131 	1,		/* DMA address alignment */
132 	1,		/* DMA burstsizes */
133 	1,		/* min effective DMA size */
134 	0xFFFFFFFFull,  /* max DMA xfer size */
135 	0xFFFFFFFFull,  /* segment boundary */
136 	1,		/* s/g list length */
137 	1,		/* granularity of device */
138 	0		/* DMA transfer flags */
139 };
140 
141 static ddi_device_acc_attr_t st_acc_attr = {
142 	DDI_DEVICE_ATTR_V0,
143 	DDI_NEVERSWAP_ACC,
144 	DDI_STRICTORDER_ACC
145 };
146 
147 /* set limitation for the number of contig_mem */
148 static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
149 #endif
150 
151 /*
152  * Tunable parameters
153  *
154  * DISCLAIMER
155  * ----------
156  * These parameters are intended for use only in system testing; if you use
157  * them in production systems, you do so at your own risk. Altering any
158  * variable not listed below may cause unpredictable system behavior.
159  *
160  * st_check_media_time
161  *
162  *   Three second state check
163  *
164  * st_allow_large_xfer
165  *
166  *   Gated with ST_NO_RECSIZE_LIMIT
167  *
168  *   0 - Transfers larger than 64KB will not be allowed
169  *       regardless of the setting of ST_NO_RECSIZE_LIMIT
170  *   1 - Transfers larger than 64KB will be allowed
171  *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
172  *
173  * st_report_soft_errors_on_close
174  *
175  *  Gated with ST_SOFT_ERROR_REPORTING
176  *
177  *  0 - Errors will not be reported on close regardless
178  *      of the setting of ST_SOFT_ERROR_REPORTING
179  *
180  *  1 - Errors will be reported on close if
181  *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
182  */
183 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
184 static int st_retry_count	= ST_RETRY_COUNT;
185 
186 static int st_io_time		= ST_IO_TIME;
187 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
188 
189 static int st_space_time	= ST_SPACE_TIME;
190 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
191 
192 static int st_error_level	= SCSI_ERR_RETRYABLE;
193 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
194 
195 static int st_max_throttle	= ST_MAX_THROTTLE;
196 
197 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
198 
199 static int st_allow_large_xfer = 1;
200 static int st_report_soft_errors_on_close = 1;
201 
202 /*
203  * End of tunable parameters list
204  */
205 
206 
207 
208 /*
209  * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
210  *
211  * Asynchronous I/O's main offering is that it is a non-blocking way to do
212  * reads and writes.  The driver will queue up all the requests it gets and
213  * have them ready to transport to the HBA.  Unfortunately, we cannot always
214  * just ship the I/O requests to the HBA, as there errors and exceptions
215  * that may happen when we don't want the HBA to continue.  Therein comes
216  * the flush-on-errors capability.  If the HBA supports it, then st will
217  * send in st_max_throttle I/O requests at the same time.
218  *
219  * Persistent errors : This was also reasonably simple.  In the interrupt
220  * routines, if there was an error or exception (FM, LEOT, media error,
221  * transport error), the persistent error bits are set and shuts everything
222  * down, but setting the throttle to zero.  If we hit and exception in the
223  * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
224  * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
225  * the appropriate error, and this will preserve order. Of course, depending
226  * on the exception we have to show a zero read or write before we show
227  * errors back to the application.
228  */
229 
230 extern const int st_ndrivetypes;	/* defined in st_conf.c */
231 extern const struct st_drivetype st_drivetypes[];
232 extern const char st_conf_version[];
233 
234 #ifdef STDEBUG
235 static int st_soft_error_report_debug = 0;
236 volatile int st_debug = 0;
237 #endif
238 
239 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
240 
241 static const struct driver_minor_data {
242 	char	*name;
243 	int	minor;
244 } st_minor_data[] = {
245 	/*
246 	 * The top 4 entries are for the default densities,
247 	 * don't alter their position.
248 	 */
249 	{"",	0},
250 	{"n",	MT_NOREWIND},
251 	{"b",	MT_BSD},
252 	{"bn",	MT_NOREWIND | MT_BSD},
253 	{"l",	MT_DENSITY1},
254 	{"m",	MT_DENSITY2},
255 	{"h",	MT_DENSITY3},
256 	{"c",	MT_DENSITY4},
257 	{"u",	MT_DENSITY4},
258 	{"ln",	MT_DENSITY1 | MT_NOREWIND},
259 	{"mn",	MT_DENSITY2 | MT_NOREWIND},
260 	{"hn",	MT_DENSITY3 | MT_NOREWIND},
261 	{"cn",	MT_DENSITY4 | MT_NOREWIND},
262 	{"un",	MT_DENSITY4 | MT_NOREWIND},
263 	{"lb",	MT_DENSITY1 | MT_BSD},
264 	{"mb",	MT_DENSITY2 | MT_BSD},
265 	{"hb",	MT_DENSITY3 | MT_BSD},
266 	{"cb",	MT_DENSITY4 | MT_BSD},
267 	{"ub",	MT_DENSITY4 | MT_BSD},
268 	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
269 	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
270 	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
271 	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
272 	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
273 };
274 
275 /* strings used in many debug and warning messages */
276 static const char wr_str[]  = "write";
277 static const char rd_str[]  = "read";
278 static const char wrg_str[] = "writing";
279 static const char rdg_str[] = "reading";
280 static const char *space_strs[] = {
281 	"records",
282 	"filemarks",
283 	"sequential filemarks",
284 	"eod",
285 	"setmarks",
286 	"sequential setmarks",
287 	"Reserved",
288 	"Reserved"
289 };
290 
291 /* default density offsets in the table above */
292 #define	DEF_BLANK	0
293 #define	DEF_NOREWIND	1
294 #define	DEF_BSD		2
295 #define	DEF_BSD_NR	3
296 
297 /* Sense Key, ASC/ASCQ for which tape ejection is needed */
298 
299 static struct tape_failure_code {
300 	uchar_t key;
301 	uchar_t add_code;
302 	uchar_t qual_code;
303 } st_tape_failure_code[] = {
304 	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
305 	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
306 	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
307 	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
308 	{ KEY_NOT_READY, 0x53, 0x00},
309 	{ 0xff}
310 };
311 
312 /*  clean bit position and mask */
313 
314 static struct cln_bit_position {
315 	ushort_t cln_bit_byte;
316 	uchar_t cln_bit_mask;
317 } st_cln_bit_position[] = {
318 	{ 21, 0x08},
319 	{ 70, 0xc0},
320 	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
321 };
322 
323 /*
324  * architecture dependent allocation restrictions. For x86, we'll set
325  * dma_attr_addr_hi to st_max_phys_addr and dma_attr_sgllen to
326  * st_sgl_size during _init().
327  */
328 #if defined(__sparc)
329 static ddi_dma_attr_t st_alloc_attr = {
330 	DMA_ATTR_V0,	/* version number */
331 	0x0,		/* lowest usable address */
332 	0xFFFFFFFFull,	/* high DMA address range */
333 	0xFFFFFFFFull,	/* DMA counter register */
334 	1,		/* DMA address alignment */
335 	1,		/* DMA burstsizes */
336 	1,		/* min effective DMA size */
337 	0xFFFFFFFFull,	/* max DMA xfer size */
338 	0xFFFFFFFFull,	/* segment boundary */
339 	1,		/* s/g list length */
340 	512,		/* granularity of device */
341 	0		/* DMA transfer flags */
342 };
343 #elif defined(__x86)
344 static ddi_dma_attr_t st_alloc_attr = {
345 	DMA_ATTR_V0,	/* version number */
346 	0x0,		/* lowest usable address */
347 	0x0,		/* high DMA address range [set in _init()] */
348 	0xFFFFull,	/* DMA counter register */
349 	512,		/* DMA address alignment */
350 	1,		/* DMA burstsizes */
351 	1,		/* min effective DMA size */
352 	0xFFFFFFFFull,	/* max DMA xfer size */
353 	0xFFFFFFFFull,  /* segment boundary */
354 	0,		/* s/g list length */
355 	512,		/* granularity of device [set in _init()] */
356 	0		/* DMA transfer flags */
357 };
358 uint64_t st_max_phys_addr = 0xFFFFFFFFull;
359 int st_sgl_size = 0xF;
360 
361 #endif
362 
363 /*
364  * Configuration Data:
365  *
366  * Device driver ops vector
367  */
368 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
369 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
370 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
371 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
372 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
373 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
374 static int st_strategy(struct buf *bp);
375 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
376 	cred_t *cred_p, int *rval_p);
377 extern int nulldev(), nodev();
378 
379 static struct cb_ops st_cb_ops = {
380 	st_open,		/* open */
381 	st_close,		/* close */
382 	st_strategy,		/* strategy */
383 	nodev,			/* print */
384 	nodev,			/* dump */
385 	st_read,		/* read */
386 	st_write,		/* write */
387 	st_ioctl,		/* ioctl */
388 	nodev,			/* devmap */
389 	nodev,			/* mmap */
390 	nodev,			/* segmap */
391 	nochpoll,		/* poll */
392 	ddi_prop_op,		/* cb_prop_op */
393 	0,			/* streamtab  */
394 	D_64BIT | D_MP | D_NEW | D_HOTPLUG |
395 	D_OPEN_RETURNS_EINTR,	/* cb_flag */
396 	CB_REV,			/* cb_rev */
397 	st_aread, 		/* async I/O read entry point */
398 	st_awrite		/* async I/O write entry point */
399 
400 };
401 
402 static int stinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
403 		void **result);
404 static int st_probe(dev_info_t *dev);
405 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
406 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
407 
408 static struct dev_ops st_ops = {
409 	DEVO_REV,		/* devo_rev, */
410 	0,			/* refcnt  */
411 	stinfo,			/* info */
412 	nulldev,		/* identify */
413 	st_probe,		/* probe */
414 	st_attach,		/* attach */
415 	st_detach,		/* detach */
416 	nodev,			/* reset */
417 	&st_cb_ops,		/* driver operations */
418 	(struct bus_ops *)0,	/* bus operations */
419 	nulldev			/* power */
420 };
421 
422 /*
423  * Local Function Declarations
424  */
425 static char *st_print_scsi_cmd(char cmd);
426 static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
427     char *title, char *cdb);
428 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
429 	char *title, char *data, int len);
430 static int st_doattach(struct scsi_device *devp, int (*canwait)());
431 static void st_known_tape_type(struct scsi_tape *un);
432 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
433     struct st_drivetype *);
434 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
435     struct st_drivetype *);
436 static int st_get_default_conf(struct scsi_tape *, char *,
437     struct st_drivetype *);
438 static int st_rw(dev_t dev, struct uio *uio, int flag);
439 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
440 static int st_find_eod(dev_t dev);
441 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
442 static int st_ioctl_cmd(dev_t dev, struct uscsi_cmd *, int flag);
443 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
444 static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
445 static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
446 static void st_start(struct scsi_tape *un);
447 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
448     clock_t timeout_interval);
449 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
450     clock_t timeout_interval);
451 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
452 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
453 static void st_init(struct scsi_tape *un);
454 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
455     int (*func)(caddr_t));
456 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
457     struct buf *bp, int (*func)(caddr_t));
458 static void st_intr(struct scsi_pkt *pkt);
459 static void st_set_state(struct scsi_tape *un);
460 static void st_test_append(struct buf *bp);
461 static int st_runout(caddr_t);
462 static int st_cmd(dev_t dev, int com, int count, int wait);
463 static int st_set_compression(struct scsi_tape *un);
464 static int st_write_fm(dev_t dev, int wfm);
465 static int st_determine_generic(dev_t dev);
466 static int st_determine_density(dev_t dev, int rw);
467 static int st_get_density(dev_t dev);
468 static int st_set_density(dev_t dev);
469 static int st_loadtape(dev_t dev);
470 static int st_modesense(struct scsi_tape *un);
471 static int st_modeselect(struct scsi_tape *un);
472 static int st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
473 static int st_wrongtapetype(struct scsi_tape *un);
474 static int st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
475 static int st_handle_sense(struct scsi_tape *un, struct buf *bp);
476 static int st_handle_autosense(struct scsi_tape *un, struct buf *bp);
477 static int st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
478     struct scsi_status *);
479 static int st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag);
480 static void st_update_error_stack(struct scsi_tape *un, struct scsi_pkt *pkt,
481     struct scsi_arq_status *cmd);
482 static void st_empty_error_stack(struct scsi_tape *un);
483 static int st_report_soft_errors(dev_t dev, int flag);
484 static void st_delayed_cv_broadcast(void *arg);
485 static int st_check_media(dev_t dev, enum mtio_state state);
486 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
487 static void st_intr_restart(void *arg);
488 static void st_start_restart(void *arg);
489 static int st_gen_mode_sense(struct scsi_tape *un, int page,
490     struct seq_mode *page_data, int page_size);
491 static int st_change_block_size(dev_t dev, uint32_t nblksz);
492 static int st_gen_mode_select(struct scsi_tape *un, struct seq_mode *page_data,
493     int page_size);
494 static int st_tape_init(dev_t dev);
495 static void st_flush(struct scsi_tape *un);
496 static void st_set_pe_errno(struct scsi_tape *un);
497 static void st_hba_unflush(struct scsi_tape *un);
498 static void st_turn_pe_on(struct scsi_tape *un);
499 static void st_turn_pe_off(struct scsi_tape *un);
500 static void st_set_pe_flag(struct scsi_tape *un);
501 static void st_clear_pe(struct scsi_tape *un);
502 static void st_wait_for_io(struct scsi_tape *un);
503 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
504 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
505 static int st_reserve_release(struct scsi_tape *un, int command);
506 static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, caddr_t cdb);
507 static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
508     int count);
509 static int st_take_ownership(dev_t dev);
510 static int st_check_asc_ascq(struct scsi_tape *un);
511 static int st_check_clean_bit(dev_t dev);
512 static int st_check_alert_flags(dev_t dev);
513 static int st_check_sequential_clean_bit(dev_t dev);
514 static int st_check_sense_clean_bit(dev_t dev);
515 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
516 static void st_calculate_timeouts(struct scsi_tape *un);
517 static writablity st_is_drive_worm(struct scsi_tape *un);
518 static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
519     caddr_t buf, size_t size);
520 static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
521     caddr_t dest, uchar_t page);
522 static int st_update_block_pos(struct scsi_tape *un);
523 static int st_interpret_read_pos(struct scsi_tape *un, read_p_types type,
524     size_t data_sz, caddr_t responce);
525 static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
526 static int st_logical_block_locate(struct scsi_tape *un, uint64_t lblk,
527     uchar_t partition);
528 static int st_mtfsf_ioctl(struct scsi_tape *un, int files);
529 static int st_mtfsr_ioctl(struct scsi_tape *un, int count);
530 static int st_mtbsf_ioctl(struct scsi_tape *un, int files);
531 static int st_mtnbsf_ioctl(struct scsi_tape *un, int count);
532 static int st_mtbsr_ioctl(struct scsi_tape *un, int num);
533 static int st_mtfsfm_ioctl(struct scsi_tape *un, int cnt);
534 static int st_mtbsfm_ioctl(struct scsi_tape *un, int cnt);
535 static int st_backward_space_files(struct scsi_tape *un, int count,
536     int infront);
537 static int st_forward_space_files(struct scsi_tape *un, int files);
538 static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
539     int32_t fileno);
540 static int st_space_to_begining_of_file(struct scsi_tape *un);
541 static int st_space_records(struct scsi_tape *un, int records);
542 
543 #if defined(__i386) || defined(__amd64)
544 /*
545  * routines for I/O in big block size
546  */
547 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
548 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
549     int alloc_flags);
550 static int st_bigblk_xfer_done(struct buf *bp);
551 static struct buf *st_get_bigblk_bp(struct buf *bp);
552 #endif
553 static void st_print_position(struct scsi_tape *un, const char *comment,
554     tapepos_t *pos);
555 
556 /*
557  * error statistics create/update functions
558  */
559 static int st_create_errstats(struct scsi_tape *, int);
560 static int st_validate_tapemarks(struct scsi_tape *un, tapepos_t *pos);
561 
562 #ifdef STDEBUG
563 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
564 static char *st_dev_name(dev_t dev);
565 #endif /* STDEBUG */
566 
567 #if !defined(lint)
568 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
569     scsi_pkt buf uio scsi_cdb uscsi_cmd))
570 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
571 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
572 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
573 #endif
574 
575 /*
576  * autoconfiguration routines.
577  */
578 char _depends_on[] = "misc/scsi";
579 
580 static struct modldrv modldrv = {
581 	&mod_driverops,		/* Type of module. This one is a driver */
582 	"SCSI tape Driver %I%", /* Name of the module. */
583 	&st_ops			/* driver ops */
584 };
585 
586 static struct modlinkage modlinkage = {
587 	MODREV_1, &modldrv, NULL
588 };
589 
590 /*
591  * Notes on Post Reset Behavior in the tape driver:
592  *
593  * When the tape drive is opened, the driver  attempts  to make sure that
594  * the tape head is positioned exactly where it was left when it was last
595  * closed  provided  the  medium  is not  changed.  If the tape  drive is
596  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
597  * of position due to reset) will happen when the first tape operation or
598  * I/O occurs.  The repositioning (if required) may not be possible under
599  * certain situations such as when the device firmware not able to report
600  * the medium  change in the REQUEST  SENSE data  because of a reset or a
601  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
602  * extraordinary  situations, where the driver fails to position the head
603  * at its  original  position,  it will fail the open the first  time, to
604  * save the applications from overwriting the data.  All further attempts
605  * to open the tape device will result in the driver  attempting  to load
606  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
607  * indicate  that further  attempts to open the tape device may result in
608  * the tape being  loaded at BOT will be printed on the  console.  If the
609  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
610  * original tape head  position,  will result in the failure of the first
611  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
612  * internal tape position  which will  necessitate  the  applications  to
613  * validate the position by using either a tape  positioning  ioctl (such
614  * as MTREW) or closing and reopening the tape device.
615  *
616  */
617 
618 int
619 _init(void)
620 {
621 	int	e;
622 
623 	if (((e = ddi_soft_state_init(&st_state,
624 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
625 		return (e);
626 	}
627 
628 	if ((e = mod_install(&modlinkage)) != 0) {
629 		ddi_soft_state_fini(&st_state);
630 	}
631 
632 #if defined(__x86)
633 	/* set the max physical address for iob allocs on x86 */
634 	st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
635 
636 	/*
637 	 * set the sgllen for iob allocs on x86. If this is set less than
638 	 * the number of pages the buffer will take (taking into account
639 	 * alignment), it would force the allocator to try and allocate
640 	 * contiguous pages.
641 	 */
642 	st_alloc_attr.dma_attr_sgllen = st_sgl_size;
643 #endif
644 
645 	return (e);
646 }
647 
648 int
649 _fini(void)
650 {
651 	int e;
652 
653 	if ((e = mod_remove(&modlinkage)) != 0) {
654 		return (e);
655 	}
656 
657 	ddi_soft_state_fini(&st_state);
658 
659 	return (e);
660 }
661 
662 int
663 _info(struct modinfo *modinfop)
664 {
665 	return (mod_info(&modlinkage, modinfop));
666 }
667 
668 
669 static int
670 st_probe(dev_info_t *devi)
671 {
672 	int instance;
673 	struct scsi_device *devp;
674 	int rval;
675 
676 #if !defined(__sparc)
677 	char    *tape_prop;
678 	int	tape_prop_len;
679 #endif
680 
681 	ST_ENTR(devi, st_probe);
682 
683 	/* If self identifying device */
684 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
685 		return (DDI_PROBE_DONTCARE);
686 	}
687 
688 #if !defined(__sparc)
689 	/*
690 	 * Since some x86 HBAs have devnodes that look like SCSI as
691 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
692 	 * we check for the presence of the "tape" property.
693 	 */
694 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
695 	    DDI_PROP_CANSLEEP, "tape",
696 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
697 		return (DDI_PROBE_FAILURE);
698 	}
699 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
700 		kmem_free(tape_prop, tape_prop_len);
701 		return (DDI_PROBE_FAILURE);
702 	}
703 	kmem_free(tape_prop, tape_prop_len);
704 #endif
705 
706 	devp = ddi_get_driver_private(devi);
707 	instance = ddi_get_instance(devi);
708 
709 	if (ddi_get_soft_state(st_state, instance) != NULL) {
710 		return (DDI_PROBE_PARTIAL);
711 	}
712 
713 
714 	/*
715 	 * Turn around and call probe routine to see whether
716 	 * we actually have a tape at this SCSI nexus.
717 	 */
718 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
719 
720 		/*
721 		 * In checking the whole inq_dtype byte we are looking at both
722 		 * the Peripheral Qualifier and the Peripheral Device Type.
723 		 * For this driver we are only interested in sequential devices
724 		 * that are connected or capable if connecting to this logical
725 		 * unit.
726 		 */
727 		if (devp->sd_inq->inq_dtype ==
728 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
729 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
730 			    "probe exists\n");
731 			rval = DDI_PROBE_SUCCESS;
732 		} else {
733 			rval = DDI_PROBE_FAILURE;
734 		}
735 	} else {
736 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
737 		    "probe failure: nothing there\n");
738 		rval = DDI_PROBE_FAILURE;
739 	}
740 	scsi_unprobe(devp);
741 	return (rval);
742 }
743 
744 static int
745 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
746 {
747 	int 	instance;
748 	int	wide;
749 	int 	dev_instance;
750 	int	ret_status;
751 	struct	scsi_device *devp;
752 	int	node_ix;
753 	struct	scsi_tape *un;
754 
755 	ST_ENTR(devi, st_attach);
756 
757 	devp = ddi_get_driver_private(devi);
758 	instance = ddi_get_instance(devi);
759 
760 	switch (cmd) {
761 		case DDI_ATTACH:
762 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
763 				return (DDI_FAILURE);
764 			}
765 			break;
766 		case DDI_RESUME:
767 			/*
768 			 * Suspend/Resume
769 			 *
770 			 * When the driver suspended, there might be
771 			 * outstanding cmds and therefore we need to
772 			 * reset the suspended flag and resume the scsi
773 			 * watch thread and restart commands and timeouts
774 			 */
775 
776 			if (!(un = ddi_get_soft_state(st_state, instance))) {
777 				return (DDI_FAILURE);
778 			}
779 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
780 			    un->un_dev);
781 
782 			mutex_enter(ST_MUTEX);
783 
784 			un->un_throttle = un->un_max_throttle;
785 			un->un_tids_at_suspend = 0;
786 			un->un_pwr_mgmt = ST_PWR_NORMAL;
787 
788 			if (un->un_swr_token) {
789 				scsi_watch_resume(un->un_swr_token);
790 			}
791 
792 			/*
793 			 * Restart timeouts
794 			 */
795 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
796 				mutex_exit(ST_MUTEX);
797 				un->un_delay_tid = timeout(
798 				    st_delayed_cv_broadcast, un,
799 				    drv_usectohz((clock_t)
800 				    MEDIA_ACCESS_DELAY));
801 				mutex_enter(ST_MUTEX);
802 			}
803 
804 			if (un->un_tids_at_suspend & ST_HIB_TID) {
805 				mutex_exit(ST_MUTEX);
806 				un->un_hib_tid = timeout(st_intr_restart, un,
807 				    ST_STATUS_BUSY_TIMEOUT);
808 				mutex_enter(ST_MUTEX);
809 			}
810 
811 			ret_status = st_clear_unit_attentions(dev_instance, 5);
812 
813 			/*
814 			 * now check if we need to restore the tape position
815 			 */
816 			if ((un->un_suspend_pos.pmode != invalid) &&
817 			    ((un->un_suspend_pos.fileno > 0) ||
818 			    (un->un_suspend_pos.blkno > 0)) ||
819 			    (un->un_suspend_pos.lgclblkno > 0)) {
820 				if (ret_status != 0) {
821 					/*
822 					 * tape didn't get good TUR
823 					 * just print out error messages
824 					 */
825 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
826 					    "st_attach-RESUME: tape failure "
827 					    " tape position will be lost");
828 				} else {
829 					/* this prints errors */
830 					(void) st_validate_tapemarks(un,
831 					    &un->un_suspend_pos);
832 				}
833 				/*
834 				 * there are no retries, if there is an error
835 				 * we don't know if the tape has changed
836 				 */
837 				un->un_suspend_pos.pmode = invalid;
838 			}
839 
840 			/* now we are ready to start up any queued I/Os */
841 			if (un->un_ncmds || un->un_quef) {
842 				st_start(un);
843 			}
844 
845 			cv_broadcast(&un->un_suspend_cv);
846 			mutex_exit(ST_MUTEX);
847 			return (DDI_SUCCESS);
848 
849 		default:
850 			return (DDI_FAILURE);
851 	}
852 
853 	un = ddi_get_soft_state(st_state, instance);
854 
855 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
856 	    "st_attach: instance=%x\n", instance);
857 
858 	/*
859 	 * find the drive type for this target
860 	 */
861 	st_known_tape_type(un);
862 
863 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
864 		int minor;
865 		char *name;
866 
867 		name  = st_minor_data[node_ix].name;
868 		minor = st_minor_data[node_ix].minor;
869 
870 		/*
871 		 * For default devices set the density to the
872 		 * preferred default density for this device.
873 		 */
874 		if (node_ix <= DEF_BSD_NR) {
875 			minor |= un->un_dp->default_density;
876 		}
877 		minor |= MTMINOR(instance);
878 
879 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
880 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
881 			continue;
882 		}
883 
884 		ddi_remove_minor_node(devi, NULL);
885 		if (un) {
886 			cv_destroy(&un->un_clscv);
887 			cv_destroy(&un->un_sbuf_cv);
888 			cv_destroy(&un->un_queue_cv);
889 			cv_destroy(&un->un_state_cv);
890 			cv_destroy(&un->un_suspend_cv);
891 			cv_destroy(&un->un_tape_busy_cv);
892 
893 			if (un->un_sbufp) {
894 				freerbuf(un->un_sbufp);
895 			}
896 			if (un->un_uscsi_rqs_buf) {
897 				kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
898 			}
899 			if (un->un_mspl) {
900 				i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
901 			}
902 			scsi_destroy_pkt(un->un_rqs);
903 			scsi_free_consistent_buf(un->un_rqs_bp);
904 			ddi_soft_state_free(st_state, instance);
905 			devp->sd_private = NULL;
906 			devp->sd_sense = NULL;
907 
908 		}
909 		ddi_prop_remove_all(devi);
910 		return (DDI_FAILURE);
911 	}
912 
913 	/*
914 	 * Add a zero-length attribute to tell the world we support
915 	 * kernel ioctls (for layered drivers)
916 	 */
917 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
918 	    DDI_KERNEL_IOCTL, NULL, 0);
919 
920 	ddi_report_dev((dev_info_t *)devi);
921 
922 	/*
923 	 * If it's a SCSI-2 tape drive which supports wide,
924 	 * tell the host adapter to use wide.
925 	 */
926 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
927 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
928 
929 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
930 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
931 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
932 	}
933 
934 	/*
935 	 * enable autorequest sense; keep the rq packet around in case
936 	 * the autorequest sense fails because of a busy condition
937 	 * do a getcap first in case the capability is not variable
938 	 */
939 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
940 		un->un_arq_enabled = 1;
941 	} else {
942 		un->un_arq_enabled =
943 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
944 	}
945 
946 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
947 	    (un->un_arq_enabled ? "enabled" : "disabled"));
948 
949 	un->un_untagged_qing =
950 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
951 
952 	/*
953 	 * XXX - This is just for 2.6.  to tell users that write buffering
954 	 *	has gone away.
955 	 */
956 	if (un->un_arq_enabled && un->un_untagged_qing) {
957 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
958 		    "tape-driver-buffering", 0) != 0) {
959 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
960 			    "Write Data Buffering has been depricated. Your "
961 			    "applications should continue to work normally.\n"
962 			    " But, they should  ported to use Asynchronous "
963 			    " I/O\n"
964 			    " For more information, read about "
965 			    " tape-driver-buffering "
966 			    "property in the st(7d) man page\n");
967 		}
968 	}
969 
970 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
971 	un->un_flush_on_errors = 0;
972 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
973 
974 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
975 	    "throttle=%x, max_throttle = %x\n",
976 	    un->un_throttle, un->un_max_throttle);
977 
978 	/* initialize persistent errors to nil */
979 	un->un_persistence = 0;
980 	un->un_persist_errors = 0;
981 
982 	/*
983 	 * Get dma-max from HBA driver. If it is not defined, use 64k
984 	 */
985 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
986 	if (un->un_maxdma == -1) {
987 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
988 		    "Received a value that looked like -1. Using 64k maxdma");
989 		un->un_maxdma = (64 * ONE_K);
990 	}
991 
992 	/*
993 	 * Get the max allowable cdb size
994 	 */
995 	un->un_max_cdb_sz =
996 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
997 	if (un->un_max_cdb_sz < CDB_GROUP0) {
998 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
999 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
1000 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
1001 	}
1002 
1003 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1004 
1005 	un->un_mediastate = MTIO_NONE;
1006 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1007 
1008 	/*
1009 	 * initialize kstats
1010 	 */
1011 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1012 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1013 	if (un->un_stats) {
1014 		un->un_stats->ks_lock = ST_MUTEX;
1015 		kstat_install(un->un_stats);
1016 	}
1017 	(void) st_create_errstats(un, instance);
1018 
1019 	return (DDI_SUCCESS);
1020 }
1021 
1022 /*
1023  * st_detach:
1024  *
1025  * we allow a detach if and only if:
1026  *	- no tape is currently inserted
1027  *	- tape position is at BOT or unknown
1028  *		(if it is not at BOT then a no rewind
1029  *		device was opened and we have to preserve state)
1030  *	- it must be in a closed state : no timeouts or scsi_watch requests
1031  *		will exist if it is closed, so we don't need to check for
1032  *		them here.
1033  */
1034 /*ARGSUSED*/
1035 static int
1036 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1037 {
1038 	int 	instance;
1039 	int 	dev_instance;
1040 	struct scsi_device *devp;
1041 	struct scsi_tape *un;
1042 	clock_t wait_cmds_complete;
1043 
1044 	ST_ENTR(devi, st_detach);
1045 
1046 	instance = ddi_get_instance(devi);
1047 
1048 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1049 		return (DDI_FAILURE);
1050 	}
1051 
1052 	switch (cmd) {
1053 
1054 	case DDI_DETACH:
1055 		/*
1056 		 * Undo what we did in st_attach & st_doattach,
1057 		 * freeing resources and removing things we installed.
1058 		 * The system framework guarantees we are not active
1059 		 * with this devinfo node in any other entry points at
1060 		 * this time.
1061 		 */
1062 
1063 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1064 		    "st_detach: instance=%x, un=%p\n", instance,
1065 		    (void *)un);
1066 
1067 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1068 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1069 		    (un->un_state != ST_STATE_CLOSED)) {
1070 			/*
1071 			 * we cannot unload some targets because the
1072 			 * inquiry returns junk unless immediately
1073 			 * after a reset
1074 			 */
1075 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1076 			    "cannot unload instance %x\n", instance);
1077 			return (DDI_FAILURE);
1078 		}
1079 
1080 		/*
1081 		 * if the tape has been removed then we may unload;
1082 		 * do a test unit ready and if it returns NOT READY
1083 		 * then we assume that it is safe to unload.
1084 		 * as a side effect, pmode may be set to invalid if the
1085 		 * the test unit ready fails;
1086 		 * also un_state may be set to non-closed, so reset it
1087 		 */
1088 		if ((un->un_dev) &&		/* Been opened since attach */
1089 		    ((un->un_pos.pmode == legacy) &&
1090 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1091 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1092 		    ((un->un_pos.pmode == logical) &&
1093 		    (un->un_pos.lgclblkno > 0))) {
1094 			mutex_enter(ST_MUTEX);
1095 			/*
1096 			 * Send Test Unit Ready in the hopes that if
1097 			 * the drive is not in the state we think it is.
1098 			 * And the state will be changed so it can be detached.
1099 			 * If the command fails to reach the device and
1100 			 * the drive was not rewound or unloaded we want
1101 			 * to fail the detach till a user command fails
1102 			 * where after the detach will succead.
1103 			 */
1104 			(void) st_cmd(un->un_dev, SCMD_TEST_UNIT_READY,
1105 			    0, SYNC_CMD);
1106 			/*
1107 			 * After TUR un_state may be set to non-closed,
1108 			 * so reset it back.
1109 			 */
1110 			un->un_state = ST_STATE_CLOSED;
1111 			mutex_exit(ST_MUTEX);
1112 		}
1113 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1114 		    "un_status=%x, fileno=%x, blkno=%x\n",
1115 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1116 
1117 		/*
1118 		 * check again:
1119 		 * if we are not at BOT then it is not safe to unload
1120 		 */
1121 		if ((un->un_dev) &&		/* Been opened since attach */
1122 		    (((un->un_pos.pmode == legacy) &&
1123 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1124 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1125 		    ((un->un_pos.pmode == logical) &&
1126 		    (un->un_pos.lgclblkno > 0)))) {
1127 
1128 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1129 			    "cannot detach: pmode=%d fileno=%x, blkno=%x"
1130 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1131 			    un->un_pos.fileno, un->un_pos.blkno,
1132 			    un->un_pos.lgclblkno);
1133 			return (DDI_FAILURE);
1134 		}
1135 
1136 		/*
1137 		 * Just To make sure that we have released the
1138 		 * tape unit .
1139 		 */
1140 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1141 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1142 			mutex_enter(ST_MUTEX);
1143 			(void) st_reserve_release(un, ST_RELEASE);
1144 			mutex_exit(ST_MUTEX);
1145 		}
1146 
1147 		/*
1148 		 * now remove other data structures allocated in st_doattach()
1149 		 */
1150 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1151 		    "destroying/freeing\n");
1152 		cv_destroy(&un->un_clscv);
1153 		cv_destroy(&un->un_sbuf_cv);
1154 		cv_destroy(&un->un_queue_cv);
1155 		cv_destroy(&un->un_suspend_cv);
1156 		cv_destroy(&un->un_tape_busy_cv);
1157 
1158 		if (un->un_hib_tid) {
1159 			(void) untimeout(un->un_hib_tid);
1160 			un->un_hib_tid = 0;
1161 		}
1162 
1163 		if (un->un_delay_tid) {
1164 			(void) untimeout(un->un_delay_tid);
1165 			un->un_delay_tid = 0;
1166 		}
1167 		cv_destroy(&un->un_state_cv);
1168 
1169 #if defined(__i386) || defined(__amd64)
1170 		if (un->un_contig_mem_hdl != NULL) {
1171 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1172 		}
1173 #endif
1174 		if (un->un_sbufp) {
1175 			freerbuf(un->un_sbufp);
1176 		}
1177 		if (un->un_uscsi_rqs_buf) {
1178 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1179 		}
1180 		if (un->un_mspl) {
1181 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1182 		}
1183 		if (un->un_rqs) {
1184 			scsi_destroy_pkt(un->un_rqs);
1185 			scsi_free_consistent_buf(un->un_rqs_bp);
1186 		}
1187 		if (un->un_mkr_pkt) {
1188 			scsi_destroy_pkt(un->un_mkr_pkt);
1189 		}
1190 		if (un->un_arq_enabled) {
1191 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1192 		}
1193 		if (un->un_dp_size) {
1194 			kmem_free(un->un_dp, un->un_dp_size);
1195 		}
1196 		if (un->un_stats) {
1197 			kstat_delete(un->un_stats);
1198 			un->un_stats = (kstat_t *)0;
1199 		}
1200 		if (un->un_errstats) {
1201 			kstat_delete(un->un_errstats);
1202 			un->un_errstats = (kstat_t *)0;
1203 		}
1204 		devp = ST_SCSI_DEVP;
1205 		ddi_soft_state_free(st_state, instance);
1206 		devp->sd_private = NULL;
1207 		devp->sd_sense = NULL;
1208 		scsi_unprobe(devp);
1209 		ddi_prop_remove_all(devi);
1210 		ddi_remove_minor_node(devi, NULL);
1211 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1212 		return (DDI_SUCCESS);
1213 
1214 	case DDI_SUSPEND:
1215 
1216 		/*
1217 		 * Suspend/Resume
1218 		 *
1219 		 * To process DDI_SUSPEND, we must do the following:
1220 		 *
1221 		 *  - check ddi_removing_power to see if power will be turned
1222 		 *    off. if so, return DDI_FAILURE
1223 		 *  - check if we are already suspended,
1224 		 *    if so, return DDI_FAILURE
1225 		 *  - check if device state is CLOSED,
1226 		 *    if not, return DDI_FAILURE.
1227 		 *  - wait until outstanding operations complete
1228 		 *  - save tape state
1229 		 *  - block new operations
1230 		 *  - cancel pending timeouts
1231 		 *
1232 		 */
1233 
1234 		if (ddi_removing_power(devi)) {
1235 			return (DDI_FAILURE);
1236 		}
1237 		mutex_enter(ST_MUTEX);
1238 
1239 		/*
1240 		 * Shouldn't already be suspended, if so return failure
1241 		 */
1242 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1243 			mutex_exit(ST_MUTEX);
1244 			return (DDI_FAILURE);
1245 		}
1246 		if (un->un_state != ST_STATE_CLOSED) {
1247 			mutex_exit(ST_MUTEX);
1248 			return (DDI_FAILURE);
1249 		}
1250 
1251 		/*
1252 		 * Wait for all outstanding I/O's to complete
1253 		 *
1254 		 * we wait on both ncmds and the wait queue for times
1255 		 * when we are flushing after persistent errors are
1256 		 * flagged, which is when ncmds can be 0, and the
1257 		 * queue can still have I/O's.  This way we preserve
1258 		 * order of biodone's.
1259 		 */
1260 		wait_cmds_complete = ddi_get_lbolt();
1261 		wait_cmds_complete +=
1262 		    st_wait_cmds_complete * drv_usectohz(1000000);
1263 		while (un->un_ncmds || un->un_quef ||
1264 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1265 
1266 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1267 			    wait_cmds_complete) == -1) {
1268 				/*
1269 				 * Time expired then cancel the command
1270 				 */
1271 				mutex_exit(ST_MUTEX);
1272 				if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
1273 					mutex_enter(ST_MUTEX);
1274 					if (un->un_last_throttle) {
1275 						un->un_throttle =
1276 						    un->un_last_throttle;
1277 					}
1278 					mutex_exit(ST_MUTEX);
1279 					return (DDI_FAILURE);
1280 				} else {
1281 					mutex_enter(ST_MUTEX);
1282 					break;
1283 				}
1284 			}
1285 		}
1286 
1287 		/*
1288 		 * DDI_SUSPEND says that the system "may" power down, we
1289 		 * remember the file and block number before rewinding.
1290 		 * we also need to save state before issuing
1291 		 * any WRITE_FILE_MARK command.
1292 		 */
1293 		(void) st_update_block_pos(un);
1294 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1295 
1296 		dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
1297 		    un->un_dev);
1298 
1299 		/*
1300 		 * Issue a zero write file fmk command to tell the drive to
1301 		 * flush any buffered tape marks
1302 		 */
1303 		(void) st_cmd(dev_instance, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1304 
1305 		/*
1306 		 * Because not all tape drives correctly implement buffer
1307 		 * flushing with the zero write file fmk command, issue a
1308 		 * synchronous rewind command to force data flushing.
1309 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1310 		 * anyway.
1311 		 */
1312 		(void) st_cmd(dev_instance, SCMD_REWIND, 0, SYNC_CMD);
1313 
1314 		/* stop any new operations */
1315 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1316 		un->un_throttle = 0;
1317 
1318 		/*
1319 		 * cancel any outstanding timeouts
1320 		 */
1321 		if (un->un_delay_tid) {
1322 			timeout_id_t temp_id = un->un_delay_tid;
1323 			un->un_delay_tid = 0;
1324 			un->un_tids_at_suspend |= ST_DELAY_TID;
1325 			mutex_exit(ST_MUTEX);
1326 			(void) untimeout(temp_id);
1327 			mutex_enter(ST_MUTEX);
1328 		}
1329 
1330 		if (un->un_hib_tid) {
1331 			timeout_id_t temp_id = un->un_hib_tid;
1332 			un->un_hib_tid = 0;
1333 			un->un_tids_at_suspend |= ST_HIB_TID;
1334 			mutex_exit(ST_MUTEX);
1335 			(void) untimeout(temp_id);
1336 			mutex_enter(ST_MUTEX);
1337 		}
1338 
1339 		/*
1340 		 * Suspend the scsi_watch_thread
1341 		 */
1342 		if (un->un_swr_token) {
1343 			opaque_t temp_token = un->un_swr_token;
1344 			mutex_exit(ST_MUTEX);
1345 			scsi_watch_suspend(temp_token);
1346 		} else {
1347 			mutex_exit(ST_MUTEX);
1348 		}
1349 
1350 		return (DDI_SUCCESS);
1351 
1352 	default:
1353 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1354 		return (DDI_FAILURE);
1355 	}
1356 }
1357 
1358 
1359 /* ARGSUSED */
1360 static int
1361 stinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1362 {
1363 	dev_t dev;
1364 	struct scsi_tape *un;
1365 	int instance, error;
1366 
1367 	ST_ENTR(dip, stinfo);
1368 
1369 	switch (infocmd) {
1370 	case DDI_INFO_DEVT2DEVINFO:
1371 		dev = (dev_t)arg;
1372 		instance = MTUNIT(dev);
1373 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1374 			return (DDI_FAILURE);
1375 		*result = (void *) ST_DEVINFO;
1376 		error = DDI_SUCCESS;
1377 		break;
1378 	case DDI_INFO_DEVT2INSTANCE:
1379 		dev = (dev_t)arg;
1380 		instance = MTUNIT(dev);
1381 		*result = (void *)(uintptr_t)instance;
1382 		error = DDI_SUCCESS;
1383 		break;
1384 	default:
1385 		error = DDI_FAILURE;
1386 	}
1387 	return (error);
1388 }
1389 
1390 static int
1391 st_doattach(struct scsi_device *devp, int (*canwait)())
1392 {
1393 	struct scsi_pkt *rqpkt = NULL;
1394 	struct scsi_tape *un = NULL;
1395 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1396 	int instance;
1397 	struct buf *bp;
1398 	size_t rlen;
1399 
1400 	ST_FUNC(devp->sd_dev, st_doattach);
1401 	/*
1402 	 * Call the routine scsi_probe to do some of the dirty work.
1403 	 * If the INQUIRY command succeeds, the field sd_inq in the
1404 	 * device structure will be filled in.
1405 	 */
1406 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1407 	    "st_doattach(): probing\n");
1408 
1409 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1410 
1411 		/*
1412 		 * In checking the whole inq_dtype byte we are looking at both
1413 		 * the Peripheral Qualifier and the Peripheral Device Type.
1414 		 * For this driver we are only interested in sequential devices
1415 		 * that are connected or capable if connecting to this logical
1416 		 * unit.
1417 		 */
1418 		if (devp->sd_inq->inq_dtype ==
1419 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1420 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1421 			    "probe exists\n");
1422 		} else {
1423 			/* Something there but not a tape device */
1424 			scsi_unprobe(devp);
1425 			return (DDI_FAILURE);
1426 		}
1427 	} else {
1428 		/* Nothing there */
1429 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1430 		    "probe failure: nothing there\n");
1431 		scsi_unprobe(devp);
1432 		return (DDI_FAILURE);
1433 	}
1434 
1435 	bp = scsi_alloc_consistent_buf(&devp->sd_address, (struct buf *)NULL,
1436 	    MAX_SENSE_LENGTH, B_READ, canwait, NULL);
1437 	if (!bp) {
1438 		goto error;
1439 	}
1440 	rqpkt = scsi_init_pkt(&devp->sd_address, NULL, bp, CDB_GROUP0, 1, 0,
1441 	    PKT_CONSISTENT, canwait, NULL);
1442 	if (!rqpkt) {
1443 		goto error;
1444 	}
1445 	devp->sd_sense = (struct scsi_extended_sense *)bp->b_un.b_addr;
1446 	ASSERT(geterror(bp) == NULL);
1447 
1448 	(void) scsi_setup_cdb((union scsi_cdb *)rqpkt->pkt_cdbp,
1449 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
1450 	FILL_SCSI1_LUN(devp, rqpkt);
1451 
1452 	/*
1453 	 * The actual unit is present.
1454 	 * Now is the time to fill in the rest of our info..
1455 	 */
1456 	instance = ddi_get_instance(devp->sd_dev);
1457 
1458 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1459 		goto error;
1460 	}
1461 	un = ddi_get_soft_state(st_state, instance);
1462 
1463 	ASSERT(un != NULL);
1464 
1465 	un->un_sbufp = getrbuf(km_flags);
1466 
1467 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1468 
1469 	/*
1470 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1471 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1472 	 * is obsolete and we want more flexibility in controlling the DMA
1473 	 * address constraints.
1474 	 */
1475 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1476 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1477 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1478 
1479 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1480 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1481 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1482 
1483 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1484 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1485 		    "probe partial failure: no space\n");
1486 		goto error;
1487 	}
1488 
1489 	bzero(un->un_mspl, sizeof (struct seq_mode));
1490 
1491 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1492 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1493 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1494 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1495 #if defined(__i386) || defined(__amd64)
1496 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1497 #endif
1498 
1499 	/* Initialize power managemnet condition variable */
1500 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1501 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1502 
1503 	rqpkt->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1504 
1505 	un->un_pos.pmode = invalid;
1506 	rqpkt->pkt_time = st_io_time;
1507 	rqpkt->pkt_comp = st_intr;
1508 	un->un_rqs	= rqpkt;
1509 	un->un_sd	= devp;
1510 	un->un_rqs_bp	= bp;
1511 	un->un_swr_token = (opaque_t)NULL;
1512 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1513 	un->un_wormable = st_is_drive_worm;
1514 	un->un_read_pos_type = LONG_POS;
1515 
1516 	un->un_suspend_pos.pmode = invalid;
1517 
1518 #if defined(__i386) || defined(__amd64)
1519 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1520 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1521 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1522 		    "allocation of contiguous memory dma handle failed!");
1523 		un->un_contig_mem_hdl = NULL;
1524 		goto error;
1525 	}
1526 #endif
1527 
1528 	/*
1529 	 * Since this driver manages devices with "remote" hardware,
1530 	 * i.e. the devices themselves have no "reg" properties,
1531 	 * the SUSPEND/RESUME commands in detach/attach will not be
1532 	 * called by the power management framework unless we request
1533 	 * it by creating a "pm-hardware-state" property and setting it
1534 	 * to value "needs-suspend-resume".
1535 	 */
1536 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1537 	    "pm-hardware-state", "needs-suspend-resume") !=
1538 	    DDI_PROP_SUCCESS) {
1539 
1540 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1541 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1542 		goto error;
1543 	}
1544 
1545 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1546 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1547 
1548 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1549 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1550 		    "failed\n");
1551 		goto error;
1552 	}
1553 
1554 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "probe success\n");
1555 	return (DDI_SUCCESS);
1556 
1557 error:
1558 	devp->sd_sense = NULL;
1559 
1560 	ddi_remove_minor_node(devp->sd_dev, NULL);
1561 	if (un) {
1562 		if (un->un_mspl) {
1563 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1564 		}
1565 		if (un->un_read_pos_data) {
1566 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1567 		}
1568 		if (un->un_sbufp) {
1569 			freerbuf(un->un_sbufp);
1570 		}
1571 		if (un->un_uscsi_rqs_buf) {
1572 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1573 		}
1574 #if defined(__i386) || defined(__amd64)
1575 		if (un->un_contig_mem_hdl != NULL) {
1576 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1577 		}
1578 #endif
1579 		ddi_soft_state_free(st_state, instance);
1580 		devp->sd_private = NULL;
1581 	}
1582 
1583 	if (rqpkt) {
1584 		scsi_destroy_pkt(rqpkt);
1585 	}
1586 
1587 	if (bp) {
1588 		scsi_free_consistent_buf(bp);
1589 	}
1590 
1591 	if (devp->sd_inq) {
1592 		scsi_unprobe(devp);
1593 	}
1594 	return (DDI_FAILURE);
1595 }
1596 
1597 typedef int
1598 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1599 
1600 static cfg_functp config_functs[] = {
1601 	st_get_conf_from_st_dot_conf,
1602 	st_get_conf_from_st_conf_dot_c,
1603 	st_get_default_conf
1604 };
1605 
1606 
1607 /*
1608  * determine tape type, using tape-config-list or built-in table or
1609  * use a generic tape config entry
1610  */
1611 static void
1612 st_known_tape_type(struct scsi_tape *un)
1613 {
1614 	struct st_drivetype *dp;
1615 	cfg_functp *config_funct;
1616 
1617 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1618 	/*
1619 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1620 	 *	 no vid & pid inquiry data.  So, we provide one.
1621 	 */
1622 	if (ST_INQUIRY->inq_len == 0 ||
1623 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1624 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1625 	}
1626 
1627 	un->un_dp_size = sizeof (struct st_drivetype);
1628 	dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1629 	un->un_dp = dp;
1630 
1631 	/*
1632 	 * Loop through the configuration methods till one works.
1633 	 */
1634 	for (config_funct = &config_functs[0]; ; config_funct++) {
1635 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1636 			break;
1637 		}
1638 	}
1639 
1640 	/*
1641 	 * If we didn't just make up this configuration and
1642 	 * all the density codes are the same..
1643 	 * Set Auto Density over ride.
1644 	 */
1645 	if (*config_funct != st_get_default_conf) {
1646 		/*
1647 		 * If this device is one that is configured and all
1648 		 * densities are the same, This saves doing gets and set
1649 		 * that yield nothing.
1650 		 */
1651 		if ((dp->densities[0]) == (dp->densities[1]) &&
1652 		    (dp->densities[0]) == (dp->densities[2]) &&
1653 		    (dp->densities[0]) == (dp->densities[3])) {
1654 
1655 			dp->options |= ST_AUTODEN_OVERRIDE;
1656 		}
1657 	}
1658 
1659 
1660 	/*
1661 	 * Store tape drive characteristics.
1662 	 */
1663 	un->un_status = 0;
1664 	un->un_attached = 1;
1665 	un->un_init_options = dp->options;
1666 
1667 	/* setup operation time-outs based on options */
1668 	st_calculate_timeouts(un);
1669 
1670 	/* make sure if we are supposed to be variable, make it variable */
1671 	if (dp->options & ST_VARIABLE) {
1672 		dp->bsize = 0;
1673 	}
1674 
1675 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1676 }
1677 
1678 
1679 typedef struct {
1680 	int mask;
1681 	int bottom;
1682 	int top;
1683 	char *name;
1684 } conf_limit;
1685 
1686 static const conf_limit conf_limits[] = {
1687 
1688 	-1,		1,		2,		"conf version",
1689 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1690 	-1,		0,		0xffffff,	"block size",
1691 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1692 	-1,		0,		4,		"number of densities",
1693 	-1,		0,		UINT8_MAX,	"density code",
1694 	-1,		0,		3,		"default density",
1695 	-1,		0,		UINT16_MAX,	"non motion timeout",
1696 	-1,		0,		UINT16_MAX,	"I/O timeout",
1697 	-1,		0,		UINT16_MAX,	"space timeout",
1698 	-1,		0,		UINT16_MAX,	"load timeout",
1699 	-1,		0,		UINT16_MAX,	"unload timeout",
1700 	-1,		0,		UINT16_MAX,	"erase timeout",
1701 	0,		0,		0,		NULL
1702 };
1703 
1704 static int
1705 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1706     const char *conf_name)
1707 {
1708 	int dens;
1709 	int ndens;
1710 	int value;
1711 	int type;
1712 	int count;
1713 	const conf_limit *limit = &conf_limits[0];
1714 
1715 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1716 
1717 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1718 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1719 
1720 	count = list_len;
1721 	type = *list;
1722 	for (;  count && limit->name; count--, list++, limit++) {
1723 
1724 		value = *list;
1725 		if (value & ~limit->mask) {
1726 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1727 			    "%s %s value invalid bits set: 0x%X\n",
1728 			    conf_name, limit->name, value & ~limit->mask);
1729 			*list &= limit->mask;
1730 		} else if (value < limit->bottom) {
1731 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1732 			    "%s %s value too low: value = %d limit %d\n",
1733 			    conf_name, limit->name, value, limit->bottom);
1734 		} else if (value > limit->top) {
1735 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1736 			    "%s %s value too high: value = %d limit %d\n",
1737 			    conf_name, limit->name, value, limit->top);
1738 		} else {
1739 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1740 			    "%s %s value = 0x%X\n",
1741 			    conf_name, limit->name, value);
1742 		}
1743 
1744 		/* If not the number of densities continue */
1745 		if (limit != &conf_limits[4]) {
1746 			continue;
1747 		}
1748 
1749 		/* If number of densities is not in range can't use config */
1750 		if (value < limit->bottom || value > limit->top) {
1751 			return (-1);
1752 		}
1753 
1754 		ndens = min(value, NDENSITIES);
1755 		if ((type == 1) && (list_len - ndens) != 6) {
1756 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1757 			    "%s conf version 1 with %d densities has %d items"
1758 			    " should have %d",
1759 			    conf_name, ndens, list_len, 6 + ndens);
1760 		} else if ((type == 2) && (list_len - ndens) != 13) {
1761 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1762 			    "%s conf version 2 with %d densities has %d items"
1763 			    " should have %d",
1764 			    conf_name, ndens, list_len, 13 + ndens);
1765 		}
1766 
1767 		limit++;
1768 		for (dens = 0; dens < ndens && count; dens++) {
1769 			count--;
1770 			list++;
1771 			value = *list;
1772 			if (value < limit->bottom) {
1773 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1774 				    "%s density[%d] value too low: value ="
1775 				    " 0x%X limit 0x%X\n",
1776 				    conf_name, dens, value, limit->bottom);
1777 			} else if (value > limit->top) {
1778 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1779 				    "%s density[%d] value too high: value ="
1780 				    " 0x%X limit 0x%X\n",
1781 				    conf_name, dens, value, limit->top);
1782 			} else {
1783 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1784 				    "%s density[%d] value = 0x%X\n",
1785 				    conf_name, dens, value);
1786 			}
1787 		}
1788 	}
1789 
1790 	return (0);
1791 }
1792 
1793 static int
1794 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
1795     struct st_drivetype *dp)
1796 {
1797 	caddr_t config_list = NULL;
1798 	caddr_t data_list = NULL;
1799 	int	*data_ptr;
1800 	caddr_t vidptr, prettyptr, datanameptr;
1801 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
1802 	int config_list_len, data_list_len, len, i;
1803 	int version;
1804 	int found = 0;
1805 
1806 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
1807 
1808 	/*
1809 	 * Determine type of tape controller. Type is determined by
1810 	 * checking the vendor ids of the earlier inquiry command and
1811 	 * comparing those with vids in tape-config-list defined in st.conf
1812 	 */
1813 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
1814 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
1815 	    != DDI_PROP_SUCCESS) {
1816 		return (found);
1817 	}
1818 
1819 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
1820 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
1821 
1822 	/*
1823 	 * Compare vids in each triplet - if it matches, get value for
1824 	 * data_name and contruct a st_drivetype struct
1825 	 * tripletlen is not set yet!
1826 	 */
1827 	for (len = config_list_len, vidptr = config_list;
1828 	    len > 0;
1829 	    vidptr += tripletlen, len -= tripletlen) {
1830 
1831 		vidlen = strlen(vidptr);
1832 		prettyptr = vidptr + vidlen + 1;
1833 		prettylen = strlen(prettyptr);
1834 		datanameptr = prettyptr + prettylen + 1;
1835 		datanamelen = strlen(datanameptr);
1836 		tripletlen = vidlen + prettylen + datanamelen + 3;
1837 
1838 		if (vidlen == 0) {
1839 			continue;
1840 		}
1841 
1842 		/*
1843 		 * If inquiry vid dosen't match this triplets vid,
1844 		 * try the next.
1845 		 */
1846 		if (strncasecmp(vidpid, vidptr, vidlen)) {
1847 			continue;
1848 		}
1849 
1850 		/*
1851 		 * if prettylen is zero then use the vid string
1852 		 */
1853 		if (prettylen == 0) {
1854 			prettyptr = vidptr;
1855 			prettylen = vidlen;
1856 		}
1857 
1858 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1859 		    "vid = %s, pretty=%s, dataname = %s\n",
1860 		    vidptr, prettyptr, datanameptr);
1861 
1862 		/*
1863 		 * get the data list
1864 		 */
1865 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
1866 		    datanameptr, (caddr_t)&data_list,
1867 		    &data_list_len) != DDI_PROP_SUCCESS) {
1868 			/*
1869 			 * Error in getting property value
1870 			 * print warning!
1871 			 */
1872 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1873 			    "data property (%s) has no value\n",
1874 			    datanameptr);
1875 			continue;
1876 		}
1877 
1878 		/*
1879 		 * now initialize the st_drivetype struct
1880 		 */
1881 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
1882 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
1883 		(void) strncpy(dp->vid, vidptr, dp->length);
1884 		data_ptr = (int *)data_list;
1885 		/*
1886 		 * check if data is enough for version, type,
1887 		 * bsize, options, # of densities, density1,
1888 		 * density2, ..., default_density
1889 		 */
1890 		if ((data_list_len < 5 * sizeof (int)) ||
1891 		    (data_list_len < 6 * sizeof (int) +
1892 		    *(data_ptr + 4) * sizeof (int))) {
1893 			/*
1894 			 * print warning and skip to next triplet.
1895 			 */
1896 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1897 			    "data property (%s) incomplete\n",
1898 			    datanameptr);
1899 			kmem_free(data_list, data_list_len);
1900 			continue;
1901 		}
1902 
1903 		if (st_validate_conf_data(un, data_ptr,
1904 		    data_list_len / sizeof (int), datanameptr)) {
1905 			kmem_free(data_list, data_list_len);
1906 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1907 			    "data property (%s) rejected\n",
1908 			    datanameptr);
1909 			continue;
1910 		}
1911 
1912 		/*
1913 		 * check version
1914 		 */
1915 		version = *data_ptr++;
1916 		if (version != 1 && version != 2) {
1917 			/* print warning but accept it */
1918 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1919 			    "Version # for data property (%s) "
1920 			    "not set to 1 or 2\n", datanameptr);
1921 		}
1922 
1923 		dp->type    = *data_ptr++;
1924 		dp->bsize   = *data_ptr++;
1925 		dp->options = *data_ptr++;
1926 		dp->options |= ST_DYNAMIC;
1927 		len = *data_ptr++;
1928 		for (i = 0; i < NDENSITIES; i++) {
1929 			if (i < len) {
1930 				dp->densities[i] = *data_ptr++;
1931 			}
1932 		}
1933 		dp->default_density = *data_ptr << 3;
1934 		if (version == 2 &&
1935 		    data_list_len >= (13 + len) * sizeof (int)) {
1936 			data_ptr++;
1937 			dp->non_motion_timeout	= *data_ptr++;
1938 			dp->io_timeout		= *data_ptr++;
1939 			dp->rewind_timeout	= *data_ptr++;
1940 			dp->space_timeout	= *data_ptr++;
1941 			dp->load_timeout	= *data_ptr++;
1942 			dp->unload_timeout	= *data_ptr++;
1943 			dp->erase_timeout	= *data_ptr++;
1944 		}
1945 		kmem_free(data_list, data_list_len);
1946 		found = 1;
1947 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1948 		    "found in st.conf: vid = %s, pretty=%s\n",
1949 		    dp->vid, dp->name);
1950 		break;
1951 	}
1952 
1953 	/*
1954 	 * free up the memory allocated by ddi_getlongprop
1955 	 */
1956 	if (config_list) {
1957 		kmem_free(config_list, config_list_len);
1958 	}
1959 	return (found);
1960 }
1961 
1962 static int
1963 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
1964     struct st_drivetype *dp)
1965 {
1966 	int i;
1967 
1968 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
1969 	/*
1970 	 * Determine type of tape controller.  Type is determined by
1971 	 * checking the result of the earlier inquiry command and
1972 	 * comparing vendor ids with strings in a table declared in st_conf.c.
1973 	 */
1974 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1975 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
1976 
1977 	for (i = 0; i < st_ndrivetypes; i++) {
1978 		if (st_drivetypes[i].length == 0) {
1979 			continue;
1980 		}
1981 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
1982 		    st_drivetypes[i].length)) {
1983 			continue;
1984 		}
1985 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
1986 		return (1);
1987 	}
1988 	return (0);
1989 }
1990 
1991 static int
1992 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
1993 {
1994 	int i;
1995 
1996 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
1997 
1998 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
1999 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2000 
2001 
2002 	/*
2003 	 * Make up a name
2004 	 */
2005 	bcopy("Vendor '", dp->name, 8);
2006 	bcopy(vidpid, &dp->name[8], VIDLEN);
2007 	bcopy("' Product '", &dp->name[16], 11);
2008 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2009 	dp->name[ST_NAMESIZE - 2] = '\'';
2010 	dp->name[ST_NAMESIZE - 1] = '\0';
2011 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2012 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2013 	/*
2014 	 * 'clean' vendor and product strings of non-printing chars
2015 	 */
2016 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2017 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2018 			dp->name[i] = '.';
2019 		}
2020 	}
2021 	dp->type = ST_TYPE_INVALID;
2022 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2023 
2024 	return (1); /* Can Not Fail */
2025 }
2026 
2027 /*
2028  * Regular Unix Entry points
2029  */
2030 
2031 
2032 
2033 /* ARGSUSED */
2034 static int
2035 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2036 {
2037 	dev_t dev = *dev_p;
2038 	int rval = 0;
2039 
2040 	GET_SOFT_STATE(dev);
2041 
2042 	ST_ENTR(ST_DEVINFO, st_open);
2043 
2044 	/*
2045 	 * validate that we are addressing a sensible unit
2046 	 */
2047 	mutex_enter(ST_MUTEX);
2048 
2049 #ifdef	STDEBUG
2050 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2051 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2052 	    st_dev_name(dev), *dev_p, flag, otyp);
2053 #endif
2054 
2055 	/*
2056 	 * All device accesss go thru st_strategy() where we check
2057 	 * suspend status
2058 	 */
2059 
2060 	if (!un->un_attached) {
2061 		st_known_tape_type(un);
2062 		if (!un->un_attached) {
2063 			rval = ENXIO;
2064 			goto exit;
2065 		}
2066 
2067 	}
2068 
2069 	/*
2070 	 * Check for the case of the tape in the middle of closing.
2071 	 * This isn't simply a check of the current state, because
2072 	 * we could be in state of sensing with the previous state
2073 	 * that of closing.
2074 	 *
2075 	 * And don't allow multiple opens.
2076 	 */
2077 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2078 		un->un_laststate = un->un_state;
2079 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2080 		while (IS_CLOSING(un) ||
2081 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2082 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2083 				rval = EINTR;
2084 				un->un_state = un->un_laststate;
2085 				goto exit;
2086 			}
2087 		}
2088 	} else if (un->un_state != ST_STATE_CLOSED) {
2089 		rval = EBUSY;
2090 		goto busy;
2091 	}
2092 
2093 	/*
2094 	 * record current dev
2095 	 */
2096 	un->un_dev = dev;
2097 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2098 	un->un_errno = 0;	/* no errors yet */
2099 	un->un_restore_pos = 0;
2100 	un->un_rqs_state = 0;
2101 
2102 	/*
2103 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2104 	 * anything, leave internal states alone, if fileno >= 0
2105 	 */
2106 	if (flag & (FNDELAY | FNONBLOCK)) {
2107 		switch (un->un_pos.pmode) {
2108 
2109 		case invalid:
2110 			un->un_state = ST_STATE_OFFLINE;
2111 			break;
2112 
2113 		case legacy:
2114 			/*
2115 			 * If position is anything other than rewound.
2116 			 */
2117 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2118 				/*
2119 				 * set un_read_only/write-protect status.
2120 				 *
2121 				 * If the tape is not bot we can assume
2122 				 * that mspl->wp_status is set properly.
2123 				 * else
2124 				 * we need to do a mode sense/Tur once
2125 				 * again to get the actual tape status.(since
2126 				 * user might have replaced the tape)
2127 				 * Hence make the st state OFFLINE so that
2128 				 * we re-intialize the tape once again.
2129 				 */
2130 				un->un_read_only =
2131 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2132 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2133 			} else {
2134 				un->un_state = ST_STATE_OFFLINE;
2135 			}
2136 			break;
2137 		case logical:
2138 			/* swag not sure how we were open last time */
2139 			(void) st_update_block_pos(un);
2140 			if (un->un_pos.lgclblkno == 0) {
2141 				un->un_state = ST_STATE_OFFLINE;
2142 			} else {
2143 				un->un_read_only =
2144 				    (un->un_oflags & FWRITE) ? 0 : 1;
2145 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2146 			}
2147 			break;
2148 		}
2149 		rval = 0;
2150 	} else {
2151 		/*
2152 		 * Not opening O_NDELAY.
2153 		 */
2154 		un->un_state = ST_STATE_OPENING;
2155 
2156 		/*
2157 		 * Clear error entry stack
2158 		 */
2159 		st_empty_error_stack(un);
2160 
2161 		rval = st_tape_init(dev);
2162 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2163 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2164 			rval = 0; /* so open doesn't fail */
2165 		} else if (rval) {
2166 			/*
2167 			 * Release the tape unit, if reserved and not
2168 			 * preserve reserve.
2169 			 */
2170 			if ((un->un_rsvd_status &
2171 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2172 				(void) st_reserve_release(un, ST_RELEASE);
2173 			}
2174 		} else {
2175 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2176 		}
2177 	}
2178 
2179 exit:
2180 	/*
2181 	 * we don't want any uninvited guests scrogging our data when we're
2182 	 * busy with something, so for successful opens or failed opens
2183 	 * (except for EBUSY), reset these counters and state appropriately.
2184 	 */
2185 	if (rval != EBUSY) {
2186 		if (rval) {
2187 			un->un_state = ST_STATE_CLOSED;
2188 		}
2189 		un->un_err_resid = 0;
2190 		un->un_retry_ct = 0;
2191 		un->un_tran_retry_ct = 0;
2192 	}
2193 busy:
2194 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2195 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2196 	mutex_exit(ST_MUTEX);
2197 	return (rval);
2198 
2199 }
2200 
2201 static int
2202 st_tape_init(dev_t dev)
2203 {
2204 	int err;
2205 	int rval = 0;
2206 
2207 	GET_SOFT_STATE(dev);
2208 
2209 	ST_FUNC(ST_DEVINFO, st_tape_init);
2210 
2211 	ASSERT(mutex_owned(ST_MUTEX));
2212 
2213 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2214 	    "st_tape_init(dev = 0x%lx, oflags = %d)\n", dev, un->un_oflags);
2215 
2216 	/*
2217 	 * Clean up after any errors left by 'last' close.
2218 	 * This also handles the case of the initial open.
2219 	 */
2220 	if (un->un_state != ST_STATE_INITIALIZING) {
2221 		un->un_laststate = un->un_state;
2222 		un->un_state = ST_STATE_OPENING;
2223 	}
2224 
2225 	un->un_kbytes_xferred = 0;
2226 
2227 	/*
2228 	 * do a throw away TUR to clear check condition
2229 	 */
2230 	err = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2231 
2232 	/*
2233 	 * If test unit ready fails because the drive is reserved
2234 	 * by another host fail the open for no access.
2235 	 */
2236 	if (err) {
2237 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2238 			un->un_state = ST_STATE_CLOSED;
2239 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2240 			    "st_tape_init: RESERVATION CONFLICT\n");
2241 			rval = EACCES;
2242 			goto exit;
2243 		}
2244 	}
2245 
2246 	/*
2247 	 * See whether this is a generic device that we haven't figured
2248 	 * anything out about yet.
2249 	 */
2250 	if (un->un_dp->type == ST_TYPE_INVALID) {
2251 		rval = st_determine_generic(dev);
2252 		if (rval) {
2253 			if (rval != EACCES) {
2254 				rval = EIO;
2255 			}
2256 			un->un_state = ST_STATE_CLOSED;
2257 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2258 			    "st_tape_init: %s invalid type\n",
2259 			    rval == EACCES ? "EACCES" : "EIO");
2260 			goto exit;
2261 		}
2262 		/*
2263 		 * If this is a Unknown Type drive,
2264 		 * Use the READ BLOCK LIMITS to determine if
2265 		 * allow large xfer is approprate if not globally
2266 		 * disabled with st_allow_large_xfer.
2267 		 */
2268 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
2269 	} else {
2270 
2271 		/*
2272 		 * If we allow_large_xfer (ie >64k) and have not yet found out
2273 		 * the max block size supported by the drive,
2274 		 * find it by issueing a READ_BLKLIM command.
2275 		 * if READ_BLKLIM cmd fails, assume drive doesn't
2276 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
2277 		 */
2278 		un->un_allow_large_xfer = st_allow_large_xfer &&
2279 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
2280 	}
2281 	/*
2282 	 * if maxbsize is unknown, set the maximum block size.
2283 	 */
2284 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
2285 
2286 		/*
2287 		 * Get the Block limits of the tape drive.
2288 		 * if un->un_allow_large_xfer = 0 , then make sure
2289 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
2290 		 */
2291 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
2292 
2293 		err = st_cmd(dev, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2294 		if (err) {
2295 			/* Retry */
2296 			err = st_cmd(dev, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2297 		}
2298 		if (!err) {
2299 
2300 			/*
2301 			 * if cmd successful, use limit returned
2302 			 */
2303 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
2304 			    (un->un_rbl->max_mid << 8) +
2305 			    un->un_rbl->max_lo;
2306 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
2307 			    un->un_rbl->min_lo;
2308 			un->un_data_mod = 1 << un->un_rbl->granularity;
2309 			if ((un->un_maxbsize == 0) ||
2310 			    (un->un_allow_large_xfer == 0 &&
2311 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
2312 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2313 
2314 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
2315 				/*
2316 				 * Drive is not one that is configured, But the
2317 				 * READ BLOCK LIMITS tells us it can do large
2318 				 * xfers.
2319 				 */
2320 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
2321 					un->un_dp->options |=
2322 					    ST_NO_RECSIZE_LIMIT;
2323 				}
2324 				/*
2325 				 * If max and mimimum block limits are the
2326 				 * same this is a fixed block size device.
2327 				 */
2328 				if (un->un_maxbsize == un->un_minbsize) {
2329 					un->un_dp->options &= ~ST_VARIABLE;
2330 				}
2331 			}
2332 
2333 			if (un->un_minbsize == 0) {
2334 				un->un_minbsize = 1;
2335 			}
2336 
2337 		} else { /* error on read block limits */
2338 
2339 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2340 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
2341 			    " errno = %d un_rsvd_status = 0x%X\n",
2342 			    err, un->un_rsvd_status);
2343 
2344 			/*
2345 			 * since read block limits cmd failed,
2346 			 * do not allow large xfers.
2347 			 * use old values in st_minphys
2348 			 */
2349 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2350 				rval = EACCES;
2351 			} else {
2352 				un->un_allow_large_xfer = 0;
2353 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2354 				    "!Disabling large transfers\n");
2355 
2356 				/*
2357 				 * we guess maxbsize and minbsize
2358 				 */
2359 				if (un->un_bsize) {
2360 					un->un_maxbsize = un->un_minbsize =
2361 					    un->un_bsize;
2362 				} else {
2363 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2364 					un->un_minbsize = 1;
2365 				}
2366 				/*
2367 				 * Data Mod must be set,
2368 				 * Even if read block limits fails.
2369 				 * Prevents Divide By Zero in st_rw().
2370 				 */
2371 				un->un_data_mod = 1;
2372 			}
2373 		}
2374 		if (un->un_rbl) {
2375 			kmem_free(un->un_rbl, RBLSIZE);
2376 			un->un_rbl = NULL;
2377 		}
2378 
2379 		if (rval) {
2380 			goto exit;
2381 		}
2382 	}
2383 
2384 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
2385 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
2386 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
2387 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
2388 
2389 	err = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2390 
2391 	if (err != 0) {
2392 		if (err == EINTR) {
2393 			un->un_laststate = un->un_state;
2394 			un->un_state = ST_STATE_CLOSED;
2395 			rval = EINTR;
2396 			goto exit;
2397 		}
2398 		/*
2399 		 * Make sure the tape is ready
2400 		 */
2401 		un->un_pos.pmode = invalid;
2402 		if (un->un_status != KEY_UNIT_ATTENTION) {
2403 			/*
2404 			 * allow open no media.  Subsequent MTIOCSTATE
2405 			 * with media present will complete the open
2406 			 * logic.
2407 			 */
2408 			un->un_laststate = un->un_state;
2409 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
2410 				un->un_mediastate = MTIO_EJECTED;
2411 				un->un_state = ST_STATE_OFFLINE;
2412 				rval = 0;
2413 				goto exit;
2414 			} else {
2415 				un->un_state = ST_STATE_CLOSED;
2416 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2417 				    "st_tape_init EIO no media, not opened "
2418 				    "O_NONBLOCK|O_EXCL\n");
2419 				rval = EIO;
2420 				goto exit;
2421 			}
2422 		}
2423 	}
2424 
2425 	/*
2426 	 * On each open, initialize block size from drivetype struct,
2427 	 * as it could have been changed by MTSRSZ ioctl.
2428 	 * Now, ST_VARIABLE simply means drive is capable of variable
2429 	 * mode. All drives are assumed to support fixed records.
2430 	 * Hence, un_bsize tells what mode the drive is in.
2431 	 *	un_bsize	= 0	- variable record length
2432 	 *			= x	- fixed record length is x
2433 	 */
2434 	un->un_bsize = un->un_dp->bsize;
2435 
2436 	/*
2437 	 * If saved position is valid go there
2438 	 */
2439 	if (un->un_restore_pos) {
2440 		rval = st_validate_tapemarks(un, &un->un_pos);
2441 		if (rval != 0) {
2442 			if (rval != EACCES) {
2443 				rval = EIO;
2444 			}
2445 			un->un_restore_pos = 0;
2446 			un->un_laststate = un->un_state;
2447 			un->un_state = ST_STATE_CLOSED;
2448 			goto exit;
2449 		}
2450 		un->un_pos.fileno = un->un_save_fileno;
2451 		un->un_pos.blkno = un->un_save_blkno;
2452 		un->un_restore_pos = 0;
2453 	}
2454 
2455 	if (un->un_pos.pmode == invalid) {
2456 		rval = st_loadtape(dev);
2457 		if (rval) {
2458 			if (rval != EACCES) {
2459 				rval = EIO;
2460 			}
2461 			un->un_laststate = un->un_state;
2462 			un->un_state = ST_STATE_CLOSED;
2463 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2464 			    "st_tape_init: %s can't open tape\n",
2465 			    rval == EACCES ? "EACCES" : "EIO");
2466 			goto exit;
2467 		}
2468 	}
2469 
2470 	/*
2471 	 * do a mode sense to pick up state of current write-protect,
2472 	 * Could cause reserve and fail due to conflict.
2473 	 */
2474 	rval = st_modesense(un);
2475 	if (rval == EACCES) {
2476 		goto exit;
2477 	}
2478 
2479 	/*
2480 	 * If we are opening the tape for writing, check
2481 	 * to make sure that the tape can be written.
2482 	 */
2483 	if (un->un_oflags & FWRITE) {
2484 		err = 0;
2485 		if (un->un_mspl->wp) {
2486 			un->un_status = KEY_WRITE_PROTECT;
2487 			un->un_laststate = un->un_state;
2488 			un->un_state = ST_STATE_CLOSED;
2489 			rval = EACCES;
2490 			/*
2491 			 * STK sets the wp bit if volsafe tape is loaded.
2492 			 */
2493 			if ((un->un_dp->type == MT_ISSTK9840) &&
2494 			    (un->un_dp->options & ST_WORMABLE)) {
2495 				un->un_read_only = RDONLY;
2496 			} else {
2497 				goto exit;
2498 			}
2499 		} else {
2500 			un->un_read_only = RDWR;
2501 		}
2502 	} else {
2503 		un->un_read_only = RDONLY;
2504 	}
2505 
2506 	if (un->un_dp->options & ST_WORMABLE) {
2507 		un->un_read_only |= un->un_wormable(un);
2508 
2509 		if (((un->un_read_only == WORM) ||
2510 		    (un->un_read_only == RDWORM)) &&
2511 		    ((un->un_oflags & FWRITE) == FWRITE)) {
2512 			un->un_status = KEY_DATA_PROTECT;
2513 			rval = EACCES;
2514 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
2515 			    "read_only = %d eof = %d oflag = %d\n",
2516 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
2517 		}
2518 	}
2519 
2520 	/*
2521 	 * If we're opening the tape write-only, we need to
2522 	 * write 2 filemarks on the HP 1/2 inch drive, to
2523 	 * create a null file.
2524 	 */
2525 	if ((un->un_read_only == RDWR) ||
2526 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
2527 		if (un->un_dp->options & ST_REEL) {
2528 			un->un_fmneeded = 2;
2529 		} else {
2530 			un->un_fmneeded = 1;
2531 		}
2532 	} else {
2533 		un->un_fmneeded = 0;
2534 	}
2535 
2536 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
2537 	    "fmneeded = %x\n", un->un_fmneeded);
2538 
2539 	/*
2540 	 * Make sure the density can be selected correctly.
2541 	 * If WORM can only write at the append point which in most cases
2542 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
2543 	 * to set and try densities if a BOP.
2544 	 */
2545 	if (st_determine_density(dev,
2546 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
2547 		un->un_status = KEY_ILLEGAL_REQUEST;
2548 		un->un_laststate = un->un_state;
2549 		un->un_state = ST_STATE_CLOSED;
2550 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2551 		    "st_tape_init: EIO can't determine density\n");
2552 		rval = EIO;
2553 		goto exit;
2554 	}
2555 
2556 	/*
2557 	 * Destroy the knowledge that we have 'determined'
2558 	 * density so that a later read at BOT comes along
2559 	 * does the right density determination.
2560 	 */
2561 
2562 	un->un_density_known = 0;
2563 
2564 
2565 	/*
2566 	 * Okay, the tape is loaded and either at BOT or somewhere past.
2567 	 * Mark the state such that any I/O or tape space operations
2568 	 * will get/set the right density, etc..
2569 	 */
2570 	un->un_laststate = un->un_state;
2571 	un->un_lastop = ST_OP_NIL;
2572 	un->un_mediastate = MTIO_INSERTED;
2573 	cv_broadcast(&un->un_state_cv);
2574 
2575 	/*
2576 	 *  Set test append flag if writing.
2577 	 *  First write must check that tape is positioned correctly.
2578 	 */
2579 	un->un_test_append = (un->un_oflags & FWRITE);
2580 
2581 exit:
2582 	un->un_err_resid = 0;
2583 	un->un_last_resid = 0;
2584 	un->un_last_count = 0;
2585 
2586 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2587 	    "st_tape_init: return val = %x\n", rval);
2588 	return (rval);
2589 
2590 }
2591 
2592 
2593 
2594 /* ARGSUSED */
2595 static int
2596 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
2597 {
2598 	int err = 0;
2599 	int norew, count, last_state;
2600 #if defined(__i386) || defined(__amd64)
2601 	struct contig_mem *cp, *cp_temp;
2602 #endif
2603 
2604 	GET_SOFT_STATE(dev);
2605 
2606 	ST_ENTR(ST_DEVINFO, st_close);
2607 
2608 	/*
2609 	 * wait till all cmds in the pipeline have been completed
2610 	 */
2611 	mutex_enter(ST_MUTEX);
2612 
2613 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2614 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
2615 
2616 	st_wait_for_io(un);
2617 
2618 	/* turn off persistent errors on close, as we want close to succeed */
2619 	TURN_PE_OFF(un);
2620 
2621 	/*
2622 	 * set state to indicate that we are in process of closing
2623 	 */
2624 	last_state = un->un_laststate = un->un_state;
2625 	un->un_state = ST_STATE_CLOSING;
2626 
2627 	/*
2628 	 * BSD behavior:
2629 	 * a close always causes a silent span to the next file if we've hit
2630 	 * an EOF (but not yet read across it).
2631 	 */
2632 #ifdef DEBUG
2633 	if ((st_debug & 0xf) >= 6)
2634 		st_print_position(un, "st_close1:", &un->un_pos);
2635 #endif
2636 
2637 	if (BSD_BEHAVIOR && (un->un_pos.eof == ST_EOF)) {
2638 		if (un->un_pos.pmode != invalid) {
2639 			un->un_pos.fileno++;
2640 			un->un_pos.blkno = 0;
2641 		}
2642 		un->un_pos.eof = ST_NO_EOF;
2643 	}
2644 
2645 	/*
2646 	 * rewinding?
2647 	 */
2648 	norew = (getminor(dev) & MT_NOREWIND);
2649 
2650 	/*
2651 	 * SVR4 behavior for skipping to next file:
2652 	 *
2653 	 * If we have not seen a filemark, space to the next file
2654 	 *
2655 	 * If we have already seen the filemark we are physically in the next
2656 	 * file and we only increment the filenumber
2657 	 */
2658 
2659 
2660 	if (norew && SVR4_BEHAVIOR && (flag & FREAD) &&
2661 	    (un->un_pos.blkno != 0) &&
2662 	    ((un->un_lastop != ST_OP_WRITE) && (un->un_lastop != ST_OP_WEOF))) {
2663 		switch (un->un_pos.eof) {
2664 		case ST_NO_EOF:
2665 			/*
2666 			 * if we were reading and did not read the complete file
2667 			 * skip to the next file, leaving the tape correctly
2668 			 * positioned to read the first record of the next file
2669 			 * Check first for REEL if we are at EOT by trying to
2670 			 * read a block
2671 			 */
2672 			if ((un->un_dp->options & ST_REEL) &&
2673 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
2674 			    (un->un_pos.blkno == 0)) {
2675 				if (st_cmd(dev, SCMD_SPACE, Blk(1), SYNC_CMD)) {
2676 					ST_DEBUG2(ST_DEVINFO, st_label,
2677 					    SCSI_DEBUG,
2678 					    "st_close : EIO can't space\n");
2679 					err = EIO;
2680 					break;
2681 				}
2682 				if (un->un_pos.eof >= ST_EOF_PENDING) {
2683 					un->un_pos.eof = ST_EOT_PENDING;
2684 					un->un_pos.fileno += 1;
2685 					un->un_pos.blkno   = 0;
2686 					break;
2687 				}
2688 			}
2689 			if (st_cmd(dev, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
2690 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2691 				    "st_close: EIO can't space #2\n");
2692 				err = EIO;
2693 			} else {
2694 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2695 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
2696 				    un->un_pos.fileno, un->un_pos.blkno,
2697 				    un->un_pos.eof);
2698 				un->un_pos.eof = ST_NO_EOF;
2699 			}
2700 			break;
2701 
2702 		case ST_EOF_PENDING:
2703 		case ST_EOF:
2704 			un->un_pos.fileno += 1;
2705 			un->un_pos.blkno   = 0;
2706 			un->un_pos.eof = ST_NO_EOF;
2707 			break;
2708 
2709 		case ST_EOT:
2710 		case ST_EOT_PENDING:
2711 			/* nothing to do */
2712 			break;
2713 		default:
2714 			scsi_log(ST_DEVINFO, st_label, CE_PANIC,
2715 			    "Undefined state 0x%x", un->un_pos.eof);
2716 
2717 		}
2718 	}
2719 
2720 
2721 	/*
2722 	 * For performance reasons (HP 88780), the driver should
2723 	 * postpone writing the second tape mark until just before a file
2724 	 * positioning ioctl is issued (e.g., rewind).	This means that
2725 	 * the user must not manually rewind the tape because the tape will
2726 	 * be missing the second tape mark which marks EOM.
2727 	 * However, this small performance improvement is not worth the risk.
2728 	 */
2729 
2730 	/*
2731 	 * We need to back up over the filemark we inadvertently popped
2732 	 * over doing a read in between the two filemarks that constitute
2733 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
2734 	 * set while reading.
2735 	 *
2736 	 * If we happen to be at physical eot (ST_EOM) (writing case),
2737 	 * the writing of filemark(s) will clear the ST_EOM state, which
2738 	 * we don't want, so we save this state and restore it later.
2739 	 */
2740 
2741 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2742 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
2743 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
2744 
2745 	if (un->un_pos.eof == ST_EOT_PENDING) {
2746 		if (norew) {
2747 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
2748 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2749 				    "st_close: EIO can't space #3\n");
2750 				err = EIO;
2751 			} else {
2752 				un->un_pos.blkno = 0;
2753 				un->un_pos.eof = ST_EOT;
2754 			}
2755 		} else {
2756 			un->un_pos.eof = ST_NO_EOF;
2757 		}
2758 
2759 	/*
2760 	 * Do we need to write a file mark?
2761 	 *
2762 	 * only write filemarks if there are fmks to be written and
2763 	 *   - open for write (possibly read/write)
2764 	 *   - the last operation was a write
2765 	 * or:
2766 	 *   -	opened for wronly
2767 	 *   -	no data was written
2768 	 */
2769 	} else if ((un->un_pos.pmode != invalid) && (un->un_fmneeded > 0) &&
2770 	    (((flag & FWRITE) && (un->un_lastop == ST_OP_WRITE)) ||
2771 	    ((flag & FWRITE) && (un->un_lastop == ST_OP_WEOF)) ||
2772 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
2773 
2774 		/* save ST_EOM state */
2775 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
2776 
2777 		/*
2778 		 * Note that we will write a filemark if we had opened
2779 		 * the tape write only and no data was written, thus
2780 		 * creating a null file.
2781 		 *
2782 		 * If the user already wrote one, we only have to write 1 more.
2783 		 * If they wrote two, we don't have to write any.
2784 		 */
2785 
2786 		count = un->un_fmneeded;
2787 		if (count > 0) {
2788 			if (st_cmd(dev, SCMD_WRITE_FILE_MARK,
2789 			    count, SYNC_CMD)) {
2790 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2791 				    "st_close : EIO can't wfm\n");
2792 				err = EIO;
2793 			}
2794 			if ((un->un_dp->options & ST_REEL) && norew) {
2795 				if (st_cmd(dev, SCMD_SPACE, Fmk((-1)),
2796 				    SYNC_CMD)) {
2797 					ST_DEBUG2(ST_DEVINFO, st_label,
2798 					    SCSI_DEBUG,
2799 					    "st_close : EIO space fmk(-1)\n");
2800 					err = EIO;
2801 				}
2802 				un->un_pos.eof = ST_NO_EOF;
2803 				/* fix up block number */
2804 				un->un_pos.blkno = 0;
2805 			}
2806 		}
2807 
2808 		/*
2809 		 * If we aren't going to be rewinding, and we were at
2810 		 * physical eot, restore the state that indicates we
2811 		 * are at physical eot. Once you have reached physical
2812 		 * eot, and you close the tape, the only thing you can
2813 		 * do on the next open is to rewind. Access to trailer
2814 		 * records is only allowed without closing the device.
2815 		 */
2816 		if (norew == 0 && was_at_eom) {
2817 			un->un_pos.eof = ST_EOM;
2818 		}
2819 	}
2820 
2821 	/*
2822 	 * report soft errors if enabled and available, if we never accessed
2823 	 * the drive, don't get errors. This will prevent some DAT error
2824 	 * messages upon LOG SENSE.
2825 	 */
2826 	if (st_report_soft_errors_on_close &&
2827 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
2828 	    (last_state != ST_STATE_OFFLINE)) {
2829 		(void) st_report_soft_errors(dev, flag);
2830 	}
2831 
2832 
2833 	/*
2834 	 * Do we need to rewind? Can we rewind?
2835 	 */
2836 	if (norew == 0 && un->un_pos.pmode != invalid && err == 0) {
2837 		/*
2838 		 * We'd like to rewind with the
2839 		 * 'immediate' bit set, but this
2840 		 * causes problems on some drives
2841 		 * where subsequent opens get a
2842 		 * 'NOT READY' error condition
2843 		 * back while the tape is rewinding,
2844 		 * which is impossible to distinguish
2845 		 * from the condition of 'no tape loaded'.
2846 		 *
2847 		 * Also, for some targets, if you disconnect
2848 		 * with the 'immediate' bit set, you don't
2849 		 * actually return right away, i.e., the
2850 		 * target ignores your request for immediate
2851 		 * return.
2852 		 *
2853 		 * Instead, we'll fire off an async rewind
2854 		 * command. We'll mark the device as closed,
2855 		 * and any subsequent open will stall on
2856 		 * the first TEST_UNIT_READY until the rewind
2857 		 * completes.
2858 		 */
2859 
2860 		/*
2861 		 * Used to be if reserve was not supported we'd send an
2862 		 * asynchronious rewind. Comments above may be slightly invalid
2863 		 * as the immediate bit was never set. Doing an immedate rewind
2864 		 * makes sense, I think fixes to not ready status might handle
2865 		 * the problems described above.
2866 		 */
2867 		if (un->un_sd->sd_inq->inq_ansi < 2) {
2868 			(void) st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
2869 		} else {
2870 			(void) st_cmd(dev, SCMD_REWIND, 0, ASYNC_CMD);
2871 		}
2872 	}
2873 
2874 	/*
2875 	 * eject tape if necessary
2876 	 */
2877 	if (un->un_eject_tape_on_failure) {
2878 		un->un_eject_tape_on_failure = 0;
2879 		if (st_cmd(dev, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
2880 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2881 			    "st_close : can't unload tape\n");
2882 		} else {
2883 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2884 			    "st_close : tape unloaded \n");
2885 			un->un_pos.eof = ST_NO_EOF;
2886 			un->un_mediastate = MTIO_EJECTED;
2887 		}
2888 	}
2889 	/*
2890 	 * Release the tape unit, if default reserve/release
2891 	 * behaviour.
2892 	 */
2893 	if ((un->un_rsvd_status &
2894 	    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2895 		(void) st_reserve_release(un, ST_RELEASE);
2896 	}
2897 
2898 	/*
2899 	 * clear up state
2900 	 */
2901 	un->un_laststate = un->un_state;
2902 	un->un_state = ST_STATE_CLOSED;
2903 	un->un_lastop = ST_OP_NIL;
2904 	un->un_throttle = 1;	/* assume one request at time, for now */
2905 	un->un_retry_ct = 0;
2906 	un->un_tran_retry_ct = 0;
2907 	un->un_errno = 0;
2908 	un->un_swr_token = (opaque_t)NULL;
2909 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
2910 
2911 	/* Restore the options to the init time settings */
2912 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
2913 		un->un_dp->options |= ST_READ_IGNORE_ILI;
2914 	} else {
2915 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
2916 	}
2917 
2918 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
2919 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
2920 	} else {
2921 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
2922 	}
2923 
2924 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
2925 		un->un_dp->options |= ST_SHORT_FILEMARKS;
2926 	} else {
2927 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
2928 	}
2929 
2930 	ASSERT(mutex_owned(ST_MUTEX));
2931 
2932 	/*
2933 	 * Signal anyone awaiting a close operation to complete.
2934 	 */
2935 	cv_signal(&un->un_clscv);
2936 
2937 	/*
2938 	 * any kind of error on closing causes all state to be tossed
2939 	 */
2940 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
2941 		/*
2942 		 * note that st_intr has already set
2943 		 * un_pos.pmode to invalid.
2944 		 */
2945 		un->un_density_known = 0;
2946 	}
2947 
2948 #if defined(__i386) || defined(__amd64)
2949 	/*
2950 	 * free any contiguous mem alloc'ed for big block I/O
2951 	 */
2952 	cp = un->un_contig_mem;
2953 	while (cp) {
2954 		if (cp->cm_addr) {
2955 			ddi_dma_mem_free(&cp->cm_acc_hdl);
2956 		}
2957 		cp_temp = cp;
2958 		cp = cp->cm_next;
2959 		kmem_free(cp_temp,
2960 		    sizeof (struct contig_mem) + biosize());
2961 	}
2962 	un->un_contig_mem_total_num = 0;
2963 	un->un_contig_mem_available_num = 0;
2964 	un->un_contig_mem = NULL;
2965 	un->un_max_contig_mem_len = 0;
2966 #endif
2967 
2968 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2969 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
2970 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
2971 
2972 	mutex_exit(ST_MUTEX);
2973 	return (err);
2974 }
2975 
2976 /*
2977  * These routines perform raw i/o operations.
2978  */
2979 
2980 /* ARGSUSED2 */
2981 static int
2982 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
2983 {
2984 #ifdef DEBUG
2985 	GET_SOFT_STATE(dev);
2986 	ST_ENTR(ST_DEVINFO, st_aread);
2987 #endif
2988 	return (st_arw(dev, aio, B_READ));
2989 }
2990 
2991 
2992 /* ARGSUSED2 */
2993 static int
2994 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
2995 {
2996 #ifdef DEBUG
2997 	GET_SOFT_STATE(dev);
2998 	ST_ENTR(ST_DEVINFO, st_awrite);
2999 #endif
3000 	return (st_arw(dev, aio, B_WRITE));
3001 }
3002 
3003 
3004 
3005 /* ARGSUSED */
3006 static int
3007 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3008 {
3009 #ifdef DEBUG
3010 	GET_SOFT_STATE(dev);
3011 	ST_ENTR(ST_DEVINFO, st_read);
3012 #endif
3013 	return (st_rw(dev, uiop, B_READ));
3014 }
3015 
3016 /* ARGSUSED */
3017 static int
3018 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3019 {
3020 #ifdef DEBUG
3021 	GET_SOFT_STATE(dev);
3022 	ST_ENTR(ST_DEVINFO, st_write);
3023 #endif
3024 	return (st_rw(dev, uiop, B_WRITE));
3025 }
3026 
3027 /*
3028  * Due to historical reasons, old limits are: For variable-length devices:
3029  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3030  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3031  * (let it through unmodified. For fixed-length record devices:
3032  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3033  *
3034  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3035  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3036  * command to the drive).
3037  *
3038  */
3039 static void
3040 st_minphys(struct buf *bp)
3041 {
3042 	struct scsi_tape *un;
3043 
3044 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3045 
3046 	ST_FUNC(ST_DEVINFO, st_minphys);
3047 
3048 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3049 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3050 	    bp->b_bcount);
3051 
3052 	if (un->un_allow_large_xfer) {
3053 
3054 		/*
3055 		 * check un_maxbsize for variable length devices only
3056 		 */
3057 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3058 			bp->b_bcount = un->un_maxbsize;
3059 		}
3060 		/*
3061 		 * can't go more that HBA maxdma limit in either fixed-length
3062 		 * or variable-length tape drives.
3063 		 */
3064 		if (bp->b_bcount > un->un_maxdma) {
3065 			bp->b_bcount = un->un_maxdma;
3066 		}
3067 	} else {
3068 
3069 		/*
3070 		 *  use old fixed limits
3071 		 */
3072 		if (un->un_bsize == 0) {
3073 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3074 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3075 			}
3076 		} else {
3077 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3078 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3079 			}
3080 		}
3081 	}
3082 
3083 	/*
3084 	 * For regular raw I/O and Fixed Block length devices, make sure
3085 	 * the adjusted block count is a whole multiple of the device
3086 	 * block size.
3087 	 */
3088 	if (bp != un->un_sbufp && un->un_bsize) {
3089 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3090 	}
3091 }
3092 
3093 static int
3094 st_rw(dev_t dev, struct uio *uio, int flag)
3095 {
3096 	int rval = 0;
3097 	long len;
3098 
3099 	GET_SOFT_STATE(dev);
3100 
3101 	ST_FUNC(ST_DEVINFO, st_rw);
3102 
3103 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3104 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3105 	    (flag == B_READ ? rd_str: wr_str));
3106 
3107 	/* get local copy of transfer length */
3108 	len = uio->uio_iov->iov_len;
3109 
3110 	mutex_enter(ST_MUTEX);
3111 
3112 	/*
3113 	 * Clear error entry stack
3114 	 */
3115 	st_empty_error_stack(un);
3116 
3117 	/*
3118 	 * If in fixed block size mode and requested read or write
3119 	 * is not an even multiple of that block size.
3120 	 */
3121 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3122 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3123 		    "%s: not modulo %d block size\n",
3124 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3125 		rval = EINVAL;
3126 	}
3127 
3128 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3129 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3130 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3131 		    "%s: not modulo %d device granularity\n",
3132 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3133 		rval = EINVAL;
3134 	}
3135 
3136 	if (rval != 0) {
3137 		un->un_errno = rval;
3138 		mutex_exit(ST_MUTEX);
3139 		return (rval);
3140 	}
3141 
3142 	/*
3143 	 * Reset this so it can be set if Berkeley and read over a filemark.
3144 	 */
3145 	un->un_silent_skip = 0;
3146 	mutex_exit(ST_MUTEX);
3147 
3148 	len = uio->uio_resid;
3149 
3150 	rval = physio(st_strategy, (struct buf *)NULL,
3151 	    dev, flag, st_minphys, uio);
3152 	/*
3153 	 * if we have hit logical EOT during this xfer and there is not a
3154 	 * full residue, then set eof back  to ST_EOM to make sure that
3155 	 * the user will see at least one zero write
3156 	 * after this short write
3157 	 */
3158 	mutex_enter(ST_MUTEX);
3159 	if (un->un_pos.eof > ST_NO_EOF) {
3160 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3161 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3162 	}
3163 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3164 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3165 			un->un_pos.eof = ST_EOM;
3166 		} else if (uio->uio_resid == len) {
3167 			un->un_pos.eof = ST_NO_EOF;
3168 		}
3169 	}
3170 
3171 	if (un->un_silent_skip && uio->uio_resid != len) {
3172 		un->un_pos.eof = ST_EOF;
3173 		un->un_pos.blkno = un->un_save_blkno;
3174 		un->un_pos.fileno--;
3175 	}
3176 
3177 	un->un_errno = rval;
3178 
3179 	mutex_exit(ST_MUTEX);
3180 
3181 	return (rval);
3182 }
3183 
3184 static int
3185 st_arw(dev_t dev, struct aio_req *aio, int flag)
3186 {
3187 	struct uio *uio = aio->aio_uio;
3188 	int rval = 0;
3189 	long len;
3190 
3191 	GET_SOFT_STATE(dev);
3192 
3193 	ST_FUNC(ST_DEVINFO, st_arw);
3194 
3195 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3196 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3197 	    (flag == B_READ ? rd_str: wr_str));
3198 
3199 	/* get local copy of transfer length */
3200 	len = uio->uio_iov->iov_len;
3201 
3202 	mutex_enter(ST_MUTEX);
3203 
3204 	/*
3205 	 * If in fixed block size mode and requested read or write
3206 	 * is not an even multiple of that block size.
3207 	 */
3208 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3209 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3210 		    "%s: not modulo %d block size\n",
3211 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3212 		rval = EINVAL;
3213 	}
3214 
3215 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3216 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3217 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3218 		    "%s: not modulo %d device granularity\n",
3219 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3220 		rval = EINVAL;
3221 	}
3222 
3223 	if (rval != 0) {
3224 		un->un_errno = rval;
3225 		mutex_exit(ST_MUTEX);
3226 		return (rval);
3227 	}
3228 
3229 	mutex_exit(ST_MUTEX);
3230 
3231 	len = uio->uio_resid;
3232 
3233 	rval = aphysio(st_strategy, anocancel, dev, flag, st_minphys, aio);
3234 
3235 	/*
3236 	 * if we have hit logical EOT during this xfer and there is not a
3237 	 * full residue, then set eof back  to ST_EOM to make sure that
3238 	 * the user will see at least one zero write
3239 	 * after this short write
3240 	 *
3241 	 * we keep this here just in case the application is not using
3242 	 * persistent errors
3243 	 */
3244 	mutex_enter(ST_MUTEX);
3245 	if (un->un_pos.eof > ST_NO_EOF) {
3246 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3247 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3248 	}
3249 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3250 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3251 			un->un_pos.eof = ST_EOM;
3252 		} else if (uio->uio_resid == len && !IS_PE_FLAG_SET(un)) {
3253 			un->un_pos.eof = ST_NO_EOF;
3254 		}
3255 	}
3256 	un->un_errno = rval;
3257 	mutex_exit(ST_MUTEX);
3258 
3259 	return (rval);
3260 }
3261 
3262 
3263 
3264 static int
3265 st_strategy(struct buf *bp)
3266 {
3267 	struct scsi_tape *un;
3268 	dev_t dev = bp->b_edev;
3269 
3270 	/*
3271 	 * validate arguments
3272 	 */
3273 	if ((un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev))) == NULL) {
3274 		bp->b_resid = bp->b_bcount;
3275 		mutex_enter(ST_MUTEX);
3276 		st_bioerror(bp, ENXIO);
3277 		mutex_exit(ST_MUTEX);
3278 		goto error;
3279 	}
3280 
3281 	ST_ENTR(ST_DEVINFO, st_strategy);
3282 
3283 	mutex_enter(ST_MUTEX);
3284 
3285 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
3286 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
3287 	}
3288 
3289 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3290 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
3291 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3292 
3293 	/*
3294 	 * If persistent errors have been flagged, just nix this one. We wait
3295 	 * for any outstanding I/O's below, so we will be in order.
3296 	 */
3297 	if (IS_PE_FLAG_SET(un)) {
3298 		goto exit;
3299 	}
3300 
3301 	if (bp != un->un_sbufp) {
3302 		char reading = bp->b_flags & B_READ;
3303 		int wasopening = 0;
3304 
3305 		/*
3306 		 * If we haven't done/checked reservation on the tape unit
3307 		 * do it now.
3308 		 */
3309 		if ((un->un_rsvd_status &
3310 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
3311 			if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
3312 				if (st_reserve_release(un, ST_RESERVE)) {
3313 					st_bioerror(bp, un->un_errno);
3314 					goto exit;
3315 				}
3316 			} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3317 				/*
3318 				 * Enter here to restore position for possible
3319 				 * resets when the device was closed and opened
3320 				 * in O_NDELAY mode subsequently
3321 				 */
3322 				un->un_state = ST_STATE_INITIALIZING;
3323 				(void) st_cmd(dev, SCMD_TEST_UNIT_READY,
3324 				    0, SYNC_CMD);
3325 				un->un_state = ST_STATE_OPEN_PENDING_IO;
3326 			}
3327 			un->un_rsvd_status |= ST_INIT_RESERVE;
3328 		}
3329 
3330 		/*
3331 		 * If we are offline, we have to initialize everything first.
3332 		 * This is to handle either when opened with O_NDELAY, or
3333 		 * we just got a new tape in the drive, after an offline.
3334 		 * We don't observe O_NDELAY past the open,
3335 		 * as it will not make sense for tapes.
3336 		 */
3337 		if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
3338 			/* reset state to avoid recursion */
3339 			un->un_state = ST_STATE_INITIALIZING;
3340 			if (st_tape_init(dev)) {
3341 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3342 				    "stioctl : OFFLINE init failure ");
3343 				un->un_state = ST_STATE_OFFLINE;
3344 				un->un_pos.pmode = invalid;
3345 				goto b_done_err;
3346 			}
3347 			un->un_state = ST_STATE_OPEN_PENDING_IO;
3348 		}
3349 		/*
3350 		 * Check for legal operations
3351 		 */
3352 		if (un->un_pos.pmode == invalid) {
3353 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3354 			    "strategy with un->un_pos.pmode invalid\n");
3355 			goto b_done_err;
3356 		}
3357 
3358 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3359 		    "st_strategy(): regular io\n");
3360 
3361 		/*
3362 		 * Process this first. If we were reading, and we're pending
3363 		 * logical eot, that means we've bumped one file mark too far.
3364 		 */
3365 
3366 		/*
3367 		 * Recursion warning: st_cmd will route back through here.
3368 		 */
3369 		if (un->un_pos.eof == ST_EOT_PENDING) {
3370 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
3371 				un->un_pos.pmode = invalid;
3372 				un->un_density_known = 0;
3373 				goto b_done_err;
3374 			}
3375 			un->un_pos.blkno = 0; /* fix up block number.. */
3376 			un->un_pos.eof = ST_EOT;
3377 		}
3378 
3379 		/*
3380 		 * If we are in the process of opening, we may have to
3381 		 * determine/set the correct density. We also may have
3382 		 * to do a test_append (if QIC) to see whether we are
3383 		 * in a position to append to the end of the tape.
3384 		 *
3385 		 * If we're already at logical eot, we transition
3386 		 * to ST_NO_EOF. If we're at physical eot, we punt
3387 		 * to the switch statement below to handle.
3388 		 */
3389 		if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
3390 		    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
3391 
3392 			if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3393 				if (st_determine_density(dev, (int)reading)) {
3394 					goto b_done_err;
3395 				}
3396 			}
3397 
3398 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3399 			    "pending_io@fileno %d rw %d qic %d eof %d\n",
3400 			    un->un_pos.fileno, (int)reading,
3401 			    (un->un_dp->options & ST_QIC) ? 1 : 0,
3402 			    un->un_pos.eof);
3403 
3404 			if (!reading && un->un_pos.eof != ST_EOM) {
3405 				if (un->un_pos.eof == ST_EOT) {
3406 					un->un_pos.eof = ST_NO_EOF;
3407 				} else if (un->un_pos.pmode != invalid &&
3408 				    (un->un_dp->options & ST_QIC)) {
3409 					/*
3410 					 * st_test_append() will do it all
3411 					 */
3412 					st_test_append(bp);
3413 					goto done;
3414 				}
3415 			}
3416 			if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3417 				wasopening = 1;
3418 			}
3419 			un->un_laststate = un->un_state;
3420 			un->un_state = ST_STATE_OPEN;
3421 		}
3422 
3423 
3424 		/*
3425 		 * Process rest of END OF FILE and END OF TAPE conditions
3426 		 */
3427 
3428 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3429 		    "eof=%x, wasopening=%x\n",
3430 		    un->un_pos.eof, wasopening);
3431 
3432 		switch (un->un_pos.eof) {
3433 		case ST_EOM:
3434 			/*
3435 			 * This allows writes to proceed past physical
3436 			 * eot. We'll *really* be in trouble if the
3437 			 * user continues blindly writing data too
3438 			 * much past this point (unwind the tape).
3439 			 * Physical eot really means 'early warning
3440 			 * eot' in this context.
3441 			 *
3442 			 * Every other write from now on will succeed
3443 			 * (if sufficient  tape left).
3444 			 * This write will return with resid == count
3445 			 * but the next one should be successful
3446 			 *
3447 			 * Note that we only transition to logical EOT
3448 			 * if the last state wasn't the OPENING state.
3449 			 * We explicitly prohibit running up to physical
3450 			 * eot, closing the device, and then re-opening
3451 			 * to proceed. Trailer records may only be gotten
3452 			 * at by keeping the tape open after hitting eot.
3453 			 *
3454 			 * Also note that ST_EOM cannot be set by reading-
3455 			 * this can only be set during writing. Reading
3456 			 * up to the end of the tape gets a blank check
3457 			 * or a double-filemark indication (ST_EOT_PENDING),
3458 			 * and we prohibit reading after that point.
3459 			 *
3460 			 */
3461 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
3462 			if (wasopening == 0) {
3463 				/*
3464 				 * this allows st_rw() to reset it back to
3465 				 * ST_EOM to make sure that the application
3466 				 * will see a zero write
3467 				 */
3468 				un->un_pos.eof = ST_WRITE_AFTER_EOM;
3469 			}
3470 			un->un_status = SUN_KEY_EOT;
3471 			goto b_done;
3472 
3473 		case ST_WRITE_AFTER_EOM:
3474 		case ST_EOT:
3475 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
3476 			un->un_status = SUN_KEY_EOT;
3477 			if (SVR4_BEHAVIOR && reading) {
3478 				goto b_done_err;
3479 			}
3480 
3481 			if (reading) {
3482 				goto b_done;
3483 			}
3484 			un->un_pos.eof = ST_NO_EOF;
3485 			break;
3486 
3487 		case ST_EOF_PENDING:
3488 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3489 			    "EOF PENDING\n");
3490 			un->un_status = SUN_KEY_EOF;
3491 			if (SVR4_BEHAVIOR) {
3492 				un->un_pos.eof = ST_EOF;
3493 				goto b_done;
3494 			}
3495 			/* FALLTHROUGH */
3496 		case ST_EOF:
3497 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
3498 			un->un_status = SUN_KEY_EOF;
3499 			if (SVR4_BEHAVIOR) {
3500 				goto b_done_err;
3501 			}
3502 
3503 			if (BSD_BEHAVIOR) {
3504 				un->un_pos.eof = ST_NO_EOF;
3505 				un->un_pos.fileno += 1;
3506 				un->un_pos.blkno   = 0;
3507 			}
3508 
3509 			if (reading) {
3510 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3511 				    "now file %d (read)\n",
3512 				    un->un_pos.fileno);
3513 				goto b_done;
3514 			}
3515 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3516 			    "now file %d (write)\n", un->un_pos.fileno);
3517 			break;
3518 		default:
3519 			un->un_status = 0;
3520 			break;
3521 		}
3522 	}
3523 
3524 	bp->b_flags &= ~(B_DONE);
3525 	st_bioerror(bp, 0);
3526 	bp->av_forw = NULL;
3527 	bp->b_resid = 0;
3528 	SET_BP_PKT(bp, 0);
3529 
3530 
3531 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3532 	    "st_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
3533 	    " pkt=0x%p\n",
3534 	    (void *)bp->b_forw, bp->b_bcount,
3535 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
3536 
3537 #if defined(__i386) || defined(__amd64)
3538 	/*
3539 	 * We will replace bp with a new bp that can do big blk xfer
3540 	 * if the requested xfer size is bigger than ST_BIGBLK_XFER
3541 	 *
3542 	 * Also, we need to make sure that we're handling real I/O
3543 	 * by checking group 0/1 SCSI I/O commands, if needed
3544 	 */
3545 	if (bp->b_bcount > ST_BIGBLK_XFER &&
3546 	    (bp != un->un_sbufp					||
3547 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ		||
3548 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G1	||
3549 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE	||
3550 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G1)) {
3551 		mutex_exit(ST_MUTEX);
3552 		bp = st_get_bigblk_bp(bp);
3553 		mutex_enter(ST_MUTEX);
3554 	}
3555 #endif
3556 
3557 	/* put on wait queue */
3558 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3559 	    "st_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
3560 	    (void *)un->un_quef, (void *)bp);
3561 
3562 	if (un->un_quef) {
3563 		un->un_quel->b_actf = bp;
3564 	} else {
3565 		un->un_quef = bp;
3566 	}
3567 	un->un_quel = bp;
3568 
3569 	ST_DO_KSTATS(bp, kstat_waitq_enter);
3570 
3571 	st_start(un);
3572 
3573 done:
3574 	mutex_exit(ST_MUTEX);
3575 	return (0);
3576 
3577 
3578 error:
3579 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3580 	    "st_strategy: error exit\n");
3581 
3582 	biodone(bp);
3583 	return (0);
3584 
3585 b_done_err:
3586 	st_bioerror(bp, EIO);
3587 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3588 	    "st_strategy : EIO b_done_err\n");
3589 
3590 b_done:
3591 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3592 	    "st_strategy: b_done\n");
3593 
3594 exit:
3595 	/*
3596 	 * make sure no commands are outstanding or waiting before closing,
3597 	 * so we can guarantee order
3598 	 */
3599 	st_wait_for_io(un);
3600 	un->un_err_resid = bp->b_resid = bp->b_bcount;
3601 
3602 	/* override errno here, if persistent errors were flagged */
3603 	if (IS_PE_FLAG_SET(un))
3604 		bioerror(bp, un->un_errno);
3605 
3606 	mutex_exit(ST_MUTEX);
3607 
3608 	biodone(bp);
3609 	ASSERT(mutex_owned(ST_MUTEX) == 0);
3610 	return (0);
3611 }
3612 
3613 
3614 
3615 /*
3616  * this routine spaces forward over filemarks
3617  */
3618 static int
3619 st_space_fmks(dev_t dev, int count)
3620 {
3621 	int rval = 0;
3622 
3623 	GET_SOFT_STATE(dev);
3624 
3625 	ST_FUNC(ST_DEVINFO, st_space_fmks);
3626 
3627 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3628 	    "st_space_fmks(dev = 0x%lx, count = %d)\n", dev, count);
3629 
3630 	ASSERT(mutex_owned(ST_MUTEX));
3631 
3632 	/*
3633 	 * the risk with doing only one space operation is that we
3634 	 * may accidentily jump in old data
3635 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
3636 	 * because the 8200 does not append a marker; in order not to
3637 	 * sacrifice the fast file skip, we do a slow skip if the low
3638 	 * density device has been opened
3639 	 */
3640 
3641 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
3642 	    !((un->un_dp->type == ST_TYPE_EXB8500 && MT_DENSITY(dev) == 0))) {
3643 		if (st_cmd(dev, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
3644 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3645 			    "space_fmks : EIO can't do space cmd #1\n");
3646 			rval = EIO;
3647 		}
3648 	} else {
3649 		while (count > 0) {
3650 			if (st_cmd(dev, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3651 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3652 				    "space_fmks : EIO can't do space cmd #2\n");
3653 				rval = EIO;
3654 				break;
3655 			}
3656 			count -= 1;
3657 			/*
3658 			 * read a block to see if we have reached
3659 			 * end of medium (double filemark for reel or
3660 			 * medium error for others)
3661 			 */
3662 			if (count > 0) {
3663 				if (st_cmd(dev, SCMD_SPACE, Blk(1),
3664 				    SYNC_CMD)) {
3665 					ST_DEBUG2(ST_DEVINFO, st_label,
3666 					    SCSI_DEBUG,
3667 					    "space_fmks : EIO can't do "
3668 					    "space cmd #3\n");
3669 					rval = EIO;
3670 					break;
3671 				}
3672 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
3673 				    (un->un_dp->options & ST_REEL)) {
3674 					un->un_status = SUN_KEY_EOT;
3675 					ST_DEBUG2(ST_DEVINFO, st_label,
3676 					    SCSI_DEBUG,
3677 					    "space_fmks : EIO ST_REEL\n");
3678 					rval = EIO;
3679 					break;
3680 				} else if (IN_EOF(un->un_pos)) {
3681 					un->un_pos.eof = ST_NO_EOF;
3682 					un->un_pos.fileno++;
3683 					un->un_pos.blkno = 0;
3684 					count--;
3685 				} else if (un->un_pos.eof > ST_EOF) {
3686 					ST_DEBUG2(ST_DEVINFO, st_label,
3687 					    SCSI_DEBUG,
3688 					    "space_fmks, EIO > ST_EOF\n");
3689 					rval = EIO;
3690 					break;
3691 				}
3692 
3693 			}
3694 		}
3695 		un->un_err_resid = count;
3696 		COPY_POS(&un->un_pos, &un->un_err_pos);
3697 	}
3698 	ASSERT(mutex_owned(ST_MUTEX));
3699 	return (rval);
3700 }
3701 
3702 /*
3703  * this routine spaces to EOD
3704  *
3705  * it keeps track of the current filenumber and returns the filenumber after
3706  * the last successful space operation, we keep the number high because as
3707  * tapes are getting larger, the possibility of more and more files exist,
3708  * 0x100000 (1 Meg of files) probably will never have to be changed any time
3709  * soon
3710  */
3711 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
3712 
3713 static int
3714 st_find_eod(dev_t dev)
3715 {
3716 	tapepos_t savepos;
3717 	int sp_type;
3718 	struct scsi_tape *un;
3719 	int instance;
3720 	int result;
3721 
3722 	instance = MTUNIT(dev);
3723 	un = ddi_get_soft_state(st_state, instance);
3724 	if (un == NULL) {
3725 		return (-1);
3726 	}
3727 
3728 	ST_FUNC(ST_DEVINFO, st_find_eod);
3729 
3730 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3731 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", dev, un->un_pos.fileno);
3732 
3733 	ASSERT(mutex_owned(ST_MUTEX));
3734 
3735 	COPY_POS(&savepos, &un->un_pos);
3736 
3737 	/*
3738 	 * see if the drive is smart enough to do the skips in
3739 	 * one operation; 1/2" use two filemarks
3740 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
3741 	 * because the 8200 does not append a marker; in order not to
3742 	 * sacrifice the fast file skip, we do a slow skip if the low
3743 	 * density device has been opened
3744 	 */
3745 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
3746 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
3747 		    (MT_DENSITY(dev) == 0)) {
3748 			sp_type = Fmk(1);
3749 		} else if (un->un_pos.pmode == logical) {
3750 			sp_type = SPACE(SP_EOD, 0);
3751 		} else {
3752 			sp_type = Fmk(MAX_SKIP);
3753 		}
3754 	} else {
3755 		sp_type = Fmk(1);
3756 	}
3757 
3758 	for (;;) {
3759 		result = st_cmd(dev, SCMD_SPACE, sp_type, SYNC_CMD);
3760 
3761 		if (result == 0) {
3762 			COPY_POS(&savepos, &un->un_pos);
3763 		}
3764 
3765 		if (sp_type == SPACE(SP_EOD, 0)) {
3766 			if (result != 0) {
3767 				sp_type = Fmk(MAX_SKIP);
3768 				continue;
3769 			}
3770 
3771 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3772 			    "st_find_eod: 0x%"PRIx64"\n",
3773 			    savepos.lgclblkno);
3774 			/*
3775 			 * What we return will become the current file position.
3776 			 * After completing the space command with the position
3777 			 * mode that is not invalid a read position command will
3778 			 * be automaticly issued. If the drive support the long
3779 			 * read position format a valid file position can be
3780 			 * returned.
3781 			 */
3782 			return (un->un_pos.fileno);
3783 		}
3784 
3785 		if (result != 0) {
3786 			break;
3787 		}
3788 
3789 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3790 		    "count=%x, eof=%x, status=%x\n",
3791 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
3792 
3793 		/*
3794 		 * If we're not EOM smart,  space a record
3795 		 * to see whether we're now in the slot between
3796 		 * the two sequential filemarks that logical
3797 		 * EOM consists of (REEL) or hit nowhere land
3798 		 * (8mm).
3799 		 */
3800 		if (sp_type == Fmk(1)) {
3801 			/*
3802 			 * no fast skipping, check a record
3803 			 */
3804 			if (st_cmd(dev, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
3805 				break;
3806 			}
3807 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
3808 			    (un->un_dp->options & ST_REEL)) {
3809 				un->un_status = KEY_BLANK_CHECK;
3810 				un->un_pos.fileno++;
3811 				un->un_pos.blkno = 0;
3812 				break;
3813 			}
3814 			if (IN_EOF(un->un_pos)) {
3815 				un->un_pos.eof = ST_NO_EOF;
3816 				un->un_pos.fileno++;
3817 				un->un_pos.blkno = 0;
3818 			}
3819 			if (un->un_pos.eof > ST_EOF) {
3820 				break;
3821 			}
3822 		} else {
3823 			if (un->un_pos.eof > ST_EOF) {
3824 				break;
3825 			}
3826 		}
3827 	}
3828 
3829 	if (un->un_dp->options & ST_KNOWS_EOD) {
3830 		COPY_POS(&savepos, &un->un_pos);
3831 	}
3832 
3833 	ASSERT(mutex_owned(ST_MUTEX));
3834 
3835 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3836 	    "st_find_eod: %x\n", savepos.fileno);
3837 	return (savepos.fileno);
3838 }
3839 
3840 
3841 /*
3842  * this routine is frequently used in ioctls below;
3843  * it determines whether we know the density and if not will
3844  * determine it
3845  * if we have written the tape before, one or more filemarks are written
3846  *
3847  * depending on the stepflag, the head is repositioned to where it was before
3848  * the filemarks were written in order not to confuse step counts
3849  */
3850 #define	STEPBACK    0
3851 #define	NO_STEPBACK 1
3852 
3853 static int
3854 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
3855 {
3856 
3857 	GET_SOFT_STATE(dev);
3858 
3859 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
3860 
3861 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3862 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
3863 	    "\n", dev, wfm, mode, stepflag);
3864 
3865 	ASSERT(mutex_owned(ST_MUTEX));
3866 
3867 	/*
3868 	 * If we don't yet know the density of the tape we have inserted,
3869 	 * we have to either unconditionally set it (if we're 'writing'),
3870 	 * or we have to determine it. As side effects, check for any
3871 	 * write-protect errors, and for the need to put out any file-marks
3872 	 * before positioning a tape.
3873 	 *
3874 	 * If we are going to be spacing forward, and we haven't determined
3875 	 * the tape density yet, we have to do so now...
3876 	 */
3877 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3878 		if (st_determine_density(dev, mode)) {
3879 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3880 			    "check_density_or_wfm : EIO can't determine "
3881 			    "density\n");
3882 			un->un_errno = EIO;
3883 			return (EIO);
3884 		}
3885 		/*
3886 		 * Presumably we are at BOT. If we attempt to write, it will
3887 		 * either work okay, or bomb. We don't do a st_test_append
3888 		 * unless we're past BOT.
3889 		 */
3890 		un->un_laststate = un->un_state;
3891 		un->un_state = ST_STATE_OPEN;
3892 
3893 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
3894 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
3895 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
3896 
3897 		tapepos_t spos;
3898 
3899 		COPY_POS(&spos, &un->un_pos);
3900 
3901 		/*
3902 		 * We need to write one or two filemarks.
3903 		 * In the case of the HP, we need to
3904 		 * position the head between the two
3905 		 * marks.
3906 		 */
3907 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
3908 			wfm = un->un_fmneeded;
3909 			un->un_fmneeded = 0;
3910 		}
3911 
3912 		if (st_write_fm(dev, wfm)) {
3913 			un->un_pos.pmode = invalid;
3914 			un->un_density_known = 0;
3915 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3916 			    "check_density_or_wfm : EIO can't write fm\n");
3917 			un->un_errno = EIO;
3918 			return (EIO);
3919 		}
3920 
3921 		if (stepflag == STEPBACK) {
3922 			if (st_cmd(dev, SCMD_SPACE, Fmk((-wfm)), SYNC_CMD)) {
3923 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3924 				    "check_density_or_wfm : EIO can't space "
3925 				    "(-wfm)\n");
3926 				un->un_errno = EIO;
3927 				return (EIO);
3928 			}
3929 			COPY_POS(&un->un_pos, &spos);
3930 		}
3931 	}
3932 
3933 	/*
3934 	 * Whatever we do at this point clears the state of the eof flag.
3935 	 */
3936 
3937 	un->un_pos.eof = ST_NO_EOF;
3938 
3939 	/*
3940 	 * If writing, let's check that we're positioned correctly
3941 	 * at the end of tape before issuing the next write.
3942 	 */
3943 	if (un->un_read_only == RDWR) {
3944 		un->un_test_append = 1;
3945 	}
3946 
3947 	ASSERT(mutex_owned(ST_MUTEX));
3948 	return (0);
3949 }
3950 
3951 
3952 /*
3953  * Wait for all outstaning I/O's to complete
3954  *
3955  * we wait on both ncmds and the wait queue for times when we are flushing
3956  * after persistent errors are flagged, which is when ncmds can be 0, and the
3957  * queue can still have I/O's.  This way we preserve order of biodone's.
3958  */
3959 static void
3960 st_wait_for_io(struct scsi_tape *un)
3961 {
3962 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
3963 	ASSERT(mutex_owned(ST_MUTEX));
3964 	while (un->un_ncmds && un->un_quef) { /* XXX fix for async write@EOM */
3965 		cv_wait(&un->un_queue_cv, ST_MUTEX);
3966 	}
3967 }
3968 
3969 /*
3970  * This routine implements the ioctl calls.  It is called
3971  * from the device switch at normal priority.
3972  */
3973 /*ARGSUSED*/
3974 static int
3975 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
3976     int *rval_p)
3977 {
3978 	int tmp, rval = 0;
3979 
3980 	GET_SOFT_STATE(dev);
3981 
3982 	ST_ENTR(ST_DEVINFO, st_ioctl);
3983 
3984 	mutex_enter(ST_MUTEX);
3985 
3986 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3987 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
3988 	    "pe_flag = %d\n",
3989 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
3990 	    IS_PE_FLAG_SET(un));
3991 
3992 	/*
3993 	 * We don't want to block on these, so let them through
3994 	 * and we don't care about setting driver states here.
3995 	 */
3996 	if ((cmd == MTIOCGETDRIVETYPE) ||
3997 	    (cmd == MTIOCGUARANTEEDORDER) ||
3998 	    (cmd == MTIOCPERSISTENTSTATUS)) {
3999 		goto check_commands;
4000 	}
4001 
4002 	/*
4003 	 * We clear error entry stack except command
4004 	 * MTIOCGETERROR and MTIOCGET
4005 	 */
4006 	if ((cmd != MTIOCGETERROR) &&
4007 	    (cmd != MTIOCGET)) {
4008 		st_empty_error_stack(un);
4009 	}
4010 
4011 	/*
4012 	 * wait for all outstanding commands to complete, or be dequeued.
4013 	 * And because ioctl's are synchronous commands, any return value
4014 	 * after this,  will be in order
4015 	 */
4016 	st_wait_for_io(un);
4017 
4018 	/*
4019 	 * allow only a through clear errors and persistent status, and
4020 	 * status
4021 	 */
4022 	if (IS_PE_FLAG_SET(un)) {
4023 		if ((cmd == MTIOCLRERR) ||
4024 		    (cmd == MTIOCPERSISTENT) ||
4025 		    (cmd == MTIOCGET)) {
4026 			goto check_commands;
4027 		} else {
4028 			rval = un->un_errno;
4029 			goto exit;
4030 		}
4031 	}
4032 
4033 	un->un_throttle = 1;	/* > 1 will never happen here */
4034 	un->un_errno = 0;	/* start clean from here */
4035 
4036 	/*
4037 	 * first and foremost, handle any ST_EOT_PENDING cases.
4038 	 * That is, if a logical eot is pending notice, notice it.
4039 	 */
4040 	if (un->un_pos.eof == ST_EOT_PENDING) {
4041 		int resid = un->un_err_resid;
4042 		uchar_t status = un->un_status;
4043 		uchar_t lastop = un->un_lastop;
4044 
4045 		if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
4046 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4047 			    "stioctl : EIO can't space fmk(-1)\n");
4048 			rval = EIO;
4049 			goto exit;
4050 		}
4051 		un->un_lastop = lastop; /* restore last operation */
4052 		if (status == SUN_KEY_EOF) {
4053 			un->un_status = SUN_KEY_EOT;
4054 		} else {
4055 			un->un_status = status;
4056 		}
4057 		un->un_err_resid  = resid;
4058 		/* fix up block number */
4059 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4060 		/* now we're at logical eot */
4061 		un->un_pos.eof = ST_EOT;
4062 	}
4063 
4064 	/*
4065 	 * now, handle the rest of the situations
4066 	 */
4067 check_commands:
4068 	switch (cmd) {
4069 	case MTIOCGET:
4070 	{
4071 #ifdef _MULTI_DATAMODEL
4072 		/*
4073 		 * For use when a 32 bit app makes a call into a
4074 		 * 64 bit ioctl
4075 		 */
4076 		struct mtget32		mtg_local32;
4077 		struct mtget32 		*mtget_32 = &mtg_local32;
4078 #endif /* _MULTI_DATAMODEL */
4079 
4080 			/* Get tape status */
4081 		struct mtget mtg_local;
4082 		struct mtget *mtget = &mtg_local;
4083 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4084 		    "st_ioctl: MTIOCGET\n");
4085 
4086 		bzero((caddr_t)mtget, sizeof (struct mtget));
4087 		mtget->mt_erreg = un->un_status;
4088 		mtget->mt_resid = un->un_err_resid;
4089 		mtget->mt_dsreg = un->un_retry_ct;
4090 		if (un->un_err_pos.pmode == legacy) {
4091 			mtget->mt_fileno = un->un_err_pos.fileno;
4092 		} else {
4093 			mtget->mt_fileno = -1;
4094 		}
4095 		mtget->mt_blkno = un->un_err_pos.blkno;
4096 		mtget->mt_type = un->un_dp->type;
4097 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
4098 		if (un->un_read_pos_type != NO_POS) {
4099 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
4100 		}
4101 		if (un->un_dp->options & ST_REEL) {
4102 			mtget->mt_flags |= MTF_REEL;
4103 			mtget->mt_bf = 20;
4104 		} else {		/* 1/4" cartridges */
4105 			switch (mtget->mt_type) {
4106 			/* Emulex cartridge tape */
4107 			case MT_ISMT02:
4108 				mtget->mt_bf = 40;
4109 				break;
4110 			default:
4111 				mtget->mt_bf = 126;
4112 				break;
4113 			}
4114 		}
4115 
4116 		/*
4117 		 * If large transfers are allowed and drive options
4118 		 * has no record size limit set. Calculate blocking
4119 		 * factor from the lesser of maxbsize and maxdma.
4120 		 */
4121 		if ((un->un_allow_large_xfer) &&
4122 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
4123 			mtget->mt_bf = min(un->un_maxbsize,
4124 			    un->un_maxdma) / SECSIZE;
4125 		}
4126 
4127 			if (un->un_read_only == WORM ||
4128 			    un->un_read_only == RDWORM) {
4129 				mtget->mt_flags |= MTF_WORM_MEDIA;
4130 			}
4131 
4132 			rval = st_check_clean_bit(dev);
4133 			if (rval == -1) {
4134 				rval = EIO;
4135 				goto exit;
4136 			} else {
4137 				mtget->mt_flags |= (ushort_t)rval;
4138 				rval = 0;
4139 			}
4140 
4141 		un->un_status = 0;		/* Reset status */
4142 		un->un_err_resid = 0;
4143 		tmp = sizeof (struct mtget);
4144 
4145 #ifdef _MULTI_DATAMODEL
4146 
4147 		switch (ddi_model_convert_from(flag & FMODELS)) {
4148 		case DDI_MODEL_ILP32:
4149 			/*
4150 			 * Convert 64 bit back to 32 bit before doing
4151 			 * copyout. This is what the ILP32 app expects.
4152 			 */
4153 			mtget_32->mt_erreg = 	mtget->mt_erreg;
4154 			mtget_32->mt_resid = 	mtget->mt_resid;
4155 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
4156 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
4157 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
4158 			mtget_32->mt_type =  	mtget->mt_type;
4159 			mtget_32->mt_flags = 	mtget->mt_flags;
4160 			mtget_32->mt_bf = 	mtget->mt_bf;
4161 
4162 			if (ddi_copyout(mtget_32, (void *)arg,
4163 			    sizeof (struct mtget32), flag)) {
4164 				rval = EFAULT;
4165 			}
4166 			break;
4167 
4168 		case DDI_MODEL_NONE:
4169 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4170 				rval = EFAULT;
4171 			}
4172 			break;
4173 		}
4174 #else /* ! _MULTI_DATAMODE */
4175 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4176 			rval = EFAULT;
4177 		}
4178 #endif /* _MULTI_DATAMODE */
4179 
4180 		break;
4181 	}
4182 	case MTIOCGETERROR:
4183 			/*
4184 			 * get error entry from error stack
4185 			 */
4186 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4187 			    "st_ioctl: MTIOCGETERROR\n");
4188 
4189 			rval = st_get_error_entry(un, arg, flag);
4190 
4191 			break;
4192 
4193 	case MTIOCSTATE:
4194 		{
4195 			/*
4196 			 * return when media presence matches state
4197 			 */
4198 			enum mtio_state state;
4199 
4200 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4201 			    "st_ioctl: MTIOCSTATE\n");
4202 
4203 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
4204 				rval = EFAULT;
4205 
4206 			mutex_exit(ST_MUTEX);
4207 
4208 			rval = st_check_media(dev, state);
4209 
4210 			mutex_enter(ST_MUTEX);
4211 
4212 			if (rval != 0) {
4213 				break;
4214 			}
4215 
4216 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
4217 			    sizeof (int), flag))
4218 				rval = EFAULT;
4219 			break;
4220 
4221 		}
4222 
4223 	case MTIOCGETDRIVETYPE:
4224 		{
4225 #ifdef _MULTI_DATAMODEL
4226 		/*
4227 		 * For use when a 32 bit app makes a call into a
4228 		 * 64 bit ioctl
4229 		 */
4230 		struct mtdrivetype_request32	mtdtrq32;
4231 #endif /* _MULTI_DATAMODEL */
4232 
4233 			/*
4234 			 * return mtdrivetype
4235 			 */
4236 			struct mtdrivetype_request mtdtrq;
4237 			struct mtdrivetype mtdrtyp;
4238 			struct mtdrivetype *mtdt = &mtdrtyp;
4239 			struct st_drivetype *stdt = un->un_dp;
4240 
4241 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4242 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
4243 
4244 #ifdef _MULTI_DATAMODEL
4245 		switch (ddi_model_convert_from(flag & FMODELS)) {
4246 		case DDI_MODEL_ILP32:
4247 		{
4248 			if (ddi_copyin((void *)arg, &mtdtrq32,
4249 			    sizeof (struct mtdrivetype_request32), flag)) {
4250 				rval = EFAULT;
4251 				break;
4252 			}
4253 			mtdtrq.size = mtdtrq32.size;
4254 			mtdtrq.mtdtp =
4255 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
4256 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4257 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
4258 			break;
4259 		}
4260 		case DDI_MODEL_NONE:
4261 			if (ddi_copyin((void *)arg, &mtdtrq,
4262 			    sizeof (struct mtdrivetype_request), flag)) {
4263 				rval = EFAULT;
4264 				break;
4265 			}
4266 			break;
4267 		}
4268 
4269 #else /* ! _MULTI_DATAMODEL */
4270 		if (ddi_copyin((void *)arg, &mtdtrq,
4271 		    sizeof (struct mtdrivetype_request), flag)) {
4272 			rval = EFAULT;
4273 			break;
4274 		}
4275 #endif /* _MULTI_DATAMODEL */
4276 
4277 			/*
4278 			 * if requested size is < 0 then return
4279 			 * error.
4280 			 */
4281 			if (mtdtrq.size < 0) {
4282 				rval = EINVAL;
4283 				break;
4284 			}
4285 			bzero(mtdt, sizeof (struct mtdrivetype));
4286 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
4287 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
4288 			mtdt->type = stdt->type;
4289 			mtdt->bsize = stdt->bsize;
4290 			mtdt->options = stdt->options;
4291 			mtdt->max_rretries = stdt->max_rretries;
4292 			mtdt->max_wretries = stdt->max_wretries;
4293 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
4294 				mtdt->densities[tmp] = stdt->densities[tmp];
4295 			}
4296 			mtdt->default_density = stdt->default_density;
4297 			/*
4298 			 * Speed hasn't been used since the hayday of reel tape.
4299 			 * For all drives not setting the option ST_KNOWS_MEDIA
4300 			 * the speed member renamed to mediatype are zeros.
4301 			 * Those drives that have ST_KNOWS_MEDIA set use the
4302 			 * new mediatype member which is used to figure the
4303 			 * type of media loaded.
4304 			 *
4305 			 * So as to not break applications speed in the
4306 			 * mtdrivetype structure is not renamed.
4307 			 */
4308 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
4309 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
4310 			}
4311 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
4312 			mtdt->io_timeout = stdt->io_timeout;
4313 			mtdt->rewind_timeout = stdt->rewind_timeout;
4314 			mtdt->space_timeout = stdt->space_timeout;
4315 			mtdt->load_timeout = stdt->load_timeout;
4316 			mtdt->unload_timeout = stdt->unload_timeout;
4317 			mtdt->erase_timeout = stdt->erase_timeout;
4318 
4319 			/*
4320 			 * Limit the maximum length of the result to
4321 			 * sizeof (struct mtdrivetype).
4322 			 */
4323 			tmp = sizeof (struct mtdrivetype);
4324 			if (mtdtrq.size < tmp)
4325 				tmp = mtdtrq.size;
4326 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
4327 				rval = EFAULT;
4328 			}
4329 			break;
4330 		}
4331 	case MTIOCPERSISTENT:
4332 		{
4333 			int persistence = 0;
4334 
4335 			if (ddi_copyin((void *)arg, &persistence,
4336 			    sizeof (int), flag)) {
4337 				rval = EFAULT;
4338 				break;
4339 			}
4340 
4341 			/* non zero sets it, only 0 turns it off */
4342 			un->un_persistence = (uchar_t)persistence ? 1 : 0;
4343 
4344 			if (un->un_persistence) {
4345 				TURN_PE_ON(un);
4346 			} else {
4347 				TURN_PE_OFF(un);
4348 			}
4349 
4350 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4351 			    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
4352 			    un->un_persistence);
4353 
4354 			break;
4355 		}
4356 	case MTIOCPERSISTENTSTATUS:
4357 		{
4358 			int persistence = (int)un->un_persistence;
4359 
4360 			if (ddi_copyout(&persistence, (void *)arg,
4361 			    sizeof (int), flag)) {
4362 				rval = EFAULT;
4363 			}
4364 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4365 			    "st_ioctl: MTIOCPERSISTENTSTATUS:persistece = %d\n",
4366 			    un->un_persistence);
4367 
4368 			break;
4369 		}
4370 
4371 
4372 	case MTIOCLRERR:
4373 		{
4374 			/* clear persistent errors */
4375 
4376 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4377 			    "st_ioctl: MTIOCLRERR\n");
4378 
4379 			CLEAR_PE(un);
4380 
4381 			break;
4382 		}
4383 
4384 	case MTIOCGUARANTEEDORDER:
4385 		{
4386 			/*
4387 			 * this is just a holder to make a valid ioctl and
4388 			 * it won't be in any earlier release
4389 			 */
4390 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4391 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
4392 
4393 			break;
4394 		}
4395 
4396 	case MTIOCRESERVE:
4397 		{
4398 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4399 			    "st_ioctl: MTIOCRESERVE\n");
4400 
4401 			/*
4402 			 * Check if Reserve/Release is supported.
4403 			 */
4404 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
4405 				rval = ENOTTY;
4406 				break;
4407 			}
4408 
4409 			rval = st_reserve_release(un, ST_RESERVE);
4410 
4411 			if (rval == 0) {
4412 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
4413 			}
4414 			break;
4415 		}
4416 
4417 	case MTIOCRELEASE:
4418 		{
4419 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4420 			    "st_ioctl: MTIOCRELEASE\n");
4421 
4422 			/*
4423 			 * Check if Reserve/Release is supported.
4424 			 */
4425 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
4426 				rval = ENOTTY;
4427 				break;
4428 			}
4429 
4430 			/*
4431 			 * Used to just clear ST_PRESERVE_RESERVE which
4432 			 * made the reservation release at next close.
4433 			 * As the user may have opened and then done a
4434 			 * persistant reservation we now need to drop
4435 			 * the reservation without closing if the user
4436 			 * attempts to do this.
4437 			 */
4438 			rval = st_reserve_release(un, ST_RELEASE);
4439 
4440 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
4441 
4442 			break;
4443 		}
4444 
4445 	case MTIOCFORCERESERVE:
4446 		{
4447 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4448 			    "st_ioctl: MTIOCFORCERESERVE\n");
4449 
4450 			/*
4451 			 * Check if Reserve/Release is supported.
4452 			 */
4453 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
4454 				rval = ENOTTY;
4455 				break;
4456 			}
4457 			/*
4458 			 * allow only super user to run this.
4459 			 */
4460 			if (drv_priv(cred_p) != 0) {
4461 				rval = EPERM;
4462 				break;
4463 			}
4464 			/*
4465 			 * Throw away reserve,
4466 			 * not using test-unit-ready
4467 			 * since reserve can succeed without tape being
4468 			 * present in the drive.
4469 			 */
4470 			(void) st_reserve_release(un, ST_RESERVE);
4471 
4472 			rval = st_take_ownership(dev);
4473 
4474 			break;
4475 		}
4476 
4477 	case USCSICMD:
4478 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4479 		    "st_ioctl: USCSICMD\n");
4480 	{
4481 		cred_t	*cr;
4482 		cr = ddi_get_cred();
4483 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
4484 			rval = EPERM;
4485 		} else {
4486 			rval = st_ioctl_cmd(dev, (struct uscsi_cmd *)arg,
4487 			    flag);
4488 		}
4489 	}
4490 		break;
4491 
4492 	case MTIOCTOP:
4493 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4494 		    "st_ioctl: MTIOCTOP\n");
4495 		rval = st_mtioctop(un, arg, flag);
4496 		break;
4497 
4498 	case MTIOCLTOP:
4499 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4500 		    "st_ioctl: MTIOLCTOP\n");
4501 		rval = st_mtiocltop(un, arg, flag);
4502 		break;
4503 
4504 	case MTIOCREADIGNOREILI:
4505 		{
4506 			int set_ili;
4507 
4508 			if (ddi_copyin((void *)arg, &set_ili,
4509 			    sizeof (set_ili), flag)) {
4510 				rval = EFAULT;
4511 				break;
4512 			}
4513 
4514 			if (un->un_bsize) {
4515 				rval = ENOTTY;
4516 				break;
4517 			}
4518 
4519 			switch (set_ili) {
4520 			case 0:
4521 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
4522 				break;
4523 
4524 			case 1:
4525 				un->un_dp->options |= ST_READ_IGNORE_ILI;
4526 				break;
4527 
4528 			default:
4529 				rval = EINVAL;
4530 				break;
4531 			}
4532 			break;
4533 		}
4534 
4535 	case MTIOCREADIGNOREEOFS:
4536 		{
4537 			int ignore_eof;
4538 
4539 			if (ddi_copyin((void *)arg, &ignore_eof,
4540 			    sizeof (ignore_eof), flag)) {
4541 				rval = EFAULT;
4542 				break;
4543 			}
4544 
4545 			if (!(un->un_dp->options & ST_REEL)) {
4546 				rval = ENOTTY;
4547 				break;
4548 			}
4549 
4550 			switch (ignore_eof) {
4551 			case 0:
4552 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
4553 				break;
4554 
4555 			case 1:
4556 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
4557 				break;
4558 
4559 			default:
4560 				rval = EINVAL;
4561 				break;
4562 			}
4563 			break;
4564 		}
4565 
4566 	case MTIOCSHORTFMK:
4567 	{
4568 		int short_fmk;
4569 
4570 		if (ddi_copyin((void *)arg, &short_fmk,
4571 		    sizeof (short_fmk), flag)) {
4572 			rval = EFAULT;
4573 			break;
4574 		}
4575 
4576 		switch (un->un_dp->type) {
4577 		case ST_TYPE_EXB8500:
4578 		case ST_TYPE_EXABYTE:
4579 			if (!short_fmk) {
4580 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
4581 			} else if (short_fmk == 1) {
4582 				un->un_dp->options |= ST_SHORT_FILEMARKS;
4583 			} else {
4584 				rval = EINVAL;
4585 			}
4586 			break;
4587 
4588 		default:
4589 			rval = ENOTTY;
4590 			break;
4591 		}
4592 		break;
4593 	}
4594 
4595 	case MTIOCGETPOS:
4596 		rval = st_update_block_pos(un);
4597 		if (rval == 0) {
4598 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
4599 			    sizeof (tapepos_t), flag)) {
4600 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
4601 				    "MTIOCGETPOS copy out failed\n");
4602 				rval = EFAULT;
4603 			}
4604 		}
4605 		break;
4606 
4607 	case MTIOCRESTPOS:
4608 	{
4609 		tapepos_t dest;
4610 
4611 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
4612 		    flag) != 0) {
4613 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
4614 			    "MTIOCRESTPOS copy in failed\n");
4615 			rval = EFAULT;
4616 			break;
4617 		}
4618 		rval = st_validate_tapemarks(un, &dest);
4619 		if (rval != 0) {
4620 			rval = EIO;
4621 		}
4622 		break;
4623 	}
4624 	default:
4625 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4626 		    "st_ioctl: unknown ioctl\n");
4627 		rval = ENOTTY;
4628 	}
4629 
4630 exit:
4631 	if (!IS_PE_FLAG_SET(un)) {
4632 		un->un_errno = rval;
4633 	}
4634 
4635 	mutex_exit(ST_MUTEX);
4636 
4637 	return (rval);
4638 }
4639 
4640 
4641 /*
4642  * do some MTIOCTOP tape operations
4643  */
4644 static int
4645 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
4646 {
4647 #ifdef _MULTI_DATAMODEL
4648 	/*
4649 	 * For use when a 32 bit app makes a call into a
4650 	 * 64 bit ioctl
4651 	 */
4652 	struct mtop32	mtop_32_for_64;
4653 #endif /* _MULTI_DATAMODEL */
4654 	struct mtop passed;
4655 	struct mtlop local;
4656 	int rval = 0;
4657 
4658 	ST_FUNC(ST_DEVINFO, st_mtioctop);
4659 
4660 	ASSERT(mutex_owned(ST_MUTEX));
4661 
4662 #ifdef _MULTI_DATAMODEL
4663 	switch (ddi_model_convert_from(flag & FMODELS)) {
4664 	case DDI_MODEL_ILP32:
4665 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
4666 		    sizeof (struct mtop32), flag)) {
4667 			return (EFAULT);
4668 		}
4669 		local.mt_op = mtop_32_for_64.mt_op;
4670 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
4671 		break;
4672 
4673 	case DDI_MODEL_NONE:
4674 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
4675 			return (EFAULT);
4676 		}
4677 		local.mt_op = passed.mt_op;
4678 		/* prevent sign extention */
4679 		local.mt_count = (UINT32_MAX & passed.mt_count);
4680 		break;
4681 	}
4682 
4683 #else /* ! _MULTI_DATAMODEL */
4684 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
4685 		return (EFAULT);
4686 	}
4687 	local.mt_op = passed.mt_op;
4688 	/* prevent sign extention */
4689 	local.mt_count = (UINT32_MAX & passed.mt_count);
4690 #endif /* _MULTI_DATAMODEL */
4691 
4692 	rval = st_do_mtioctop(un, &local);
4693 
4694 #ifdef _MULTI_DATAMODEL
4695 	switch (ddi_model_convert_from(flag & FMODELS)) {
4696 	case DDI_MODEL_ILP32:
4697 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
4698 			rval = ERANGE;
4699 			break;
4700 		}
4701 		/*
4702 		 * Convert 64 bit back to 32 bit before doing
4703 		 * copyout. This is what the ILP32 app expects.
4704 		 */
4705 		mtop_32_for_64.mt_op = local.mt_op;
4706 		mtop_32_for_64.mt_count = local.mt_count;
4707 
4708 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
4709 		    sizeof (struct mtop32), flag)) {
4710 			rval = EFAULT;
4711 		}
4712 		break;
4713 
4714 	case DDI_MODEL_NONE:
4715 		passed.mt_count = local.mt_count;
4716 		passed.mt_op = local.mt_op;
4717 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
4718 			rval = EFAULT;
4719 		}
4720 		break;
4721 	}
4722 #else /* ! _MULTI_DATAMODE */
4723 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
4724 		rval = ERANGE;
4725 	} else {
4726 		passed.mt_op = local.mt_op;
4727 		passed.mt_count = local.mt_count;
4728 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
4729 			rval = EFAULT;
4730 		}
4731 	}
4732 #endif /* _MULTI_DATAMODE */
4733 
4734 
4735 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4736 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
4737 	    un->un_pos.blkno, un->un_pos.eof);
4738 
4739 	if (un->un_pos.pmode == invalid) {
4740 		un->un_density_known = 0;
4741 	}
4742 
4743 	ASSERT(mutex_owned(ST_MUTEX));
4744 	return (rval);
4745 }
4746 
4747 static int
4748 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
4749 {
4750 	struct mtlop local;
4751 	int rval;
4752 
4753 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
4754 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
4755 		return (EFAULT);
4756 	}
4757 
4758 	rval = st_do_mtioctop(un, &local);
4759 
4760 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
4761 		rval = EFAULT;
4762 	}
4763 	return (rval);
4764 }
4765 
4766 
4767 static int
4768 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
4769 {
4770 	dev_t dev = un->un_dev;
4771 	int savefile;
4772 	int rval = 0;
4773 
4774 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
4775 
4776 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4777 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
4778 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4779 	    "fileno=%x, blkno=%x, eof=%x\n",
4780 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4781 
4782 	un->un_status = 0;
4783 
4784 	/*
4785 	 * if we are going to mess with a tape, we have to make sure we have
4786 	 * one and are not offline (i.e. no tape is initialized).  We let
4787 	 * commands pass here that don't actually touch the tape, except for
4788 	 * loading and initialization (rewinding).
4789 	 */
4790 	if (un->un_state == ST_STATE_OFFLINE) {
4791 		switch (mtop->mt_op) {
4792 		case MTLOAD:
4793 		case MTNOP:
4794 			/*
4795 			 * We don't want strategy calling st_tape_init here,
4796 			 * so, change state
4797 			 */
4798 			un->un_state = ST_STATE_INITIALIZING;
4799 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4800 			    "st_do_mtioctop : OFFLINE state = %d\n",
4801 			    un->un_state);
4802 			break;
4803 		default:
4804 			/*
4805 			 * reinitialize by normal means
4806 			 */
4807 			rval = st_tape_init(dev);
4808 			if (rval) {
4809 				un->un_state = ST_STATE_INITIALIZING;
4810 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4811 				    "st_do_mtioctop : OFFLINE init failure ");
4812 				un->un_state = ST_STATE_OFFLINE;
4813 				un->un_pos.pmode = invalid;
4814 				if (rval != EACCES) {
4815 					rval = EIO;
4816 				}
4817 				return (rval);
4818 			}
4819 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4820 			break;
4821 		}
4822 	}
4823 
4824 	/*
4825 	 * If the file position is invalid, allow only those
4826 	 * commands that properly position the tape and fail
4827 	 * the rest with EIO
4828 	 */
4829 	if (un->un_pos.pmode == invalid) {
4830 		switch (mtop->mt_op) {
4831 		case MTWEOF:
4832 		case MTRETEN:
4833 		case MTERASE:
4834 		case MTEOM:
4835 		case MTFSF:
4836 		case MTFSR:
4837 		case MTBSF:
4838 		case MTNBSF:
4839 		case MTBSR:
4840 		case MTSRSZ:
4841 		case MTGRSZ:
4842 		case MTSEEK:
4843 		case MTBSSF:
4844 		case MTFSSF:
4845 			return (EIO);
4846 			/* NOTREACHED */
4847 		case MTREW:
4848 		case MTLOAD:
4849 		case MTOFFL:
4850 		case MTNOP:
4851 		case MTTELL:
4852 		case MTLOCK:
4853 		case MTUNLOCK:
4854 			break;
4855 
4856 		default:
4857 			return (ENOTTY);
4858 			/* NOTREACHED */
4859 		}
4860 	}
4861 
4862 	switch (mtop->mt_op) {
4863 	case MTERASE:
4864 		/*
4865 		 * MTERASE rewinds the tape, erase it completely, and returns
4866 		 * to the beginning of the tape
4867 		 */
4868 		if (un->un_mspl->wp || un->un_read_only & WORM) {
4869 			un->un_status = KEY_WRITE_PROTECT;
4870 			un->un_err_resid = mtop->mt_count;
4871 			COPY_POS(&un->un_err_pos, &un->un_pos);
4872 			return (EACCES);
4873 		}
4874 		if (un->un_dp->options & ST_REEL) {
4875 			un->un_fmneeded = 2;
4876 		} else {
4877 			un->un_fmneeded = 1;
4878 		}
4879 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
4880 		    st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD) ||
4881 		    st_cmd(dev, SCMD_ERASE, 0, SYNC_CMD)) {
4882 			un->un_pos.pmode = invalid;
4883 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4884 			    "st_do_mtioctop : EIO space or erase or "
4885 			    "check den)\n");
4886 			rval = EIO;
4887 		} else {
4888 			/* QIC and helical scan rewind after erase */
4889 			if (un->un_dp->options & ST_REEL) {
4890 				(void) st_cmd(dev, SCMD_REWIND, 0, ASYNC_CMD);
4891 			}
4892 		}
4893 		break;
4894 
4895 	case MTWEOF:
4896 		/*
4897 		 * write an end-of-file record
4898 		 */
4899 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
4900 			un->un_status = KEY_WRITE_PROTECT;
4901 			un->un_err_resid = mtop->mt_count;
4902 			COPY_POS(&un->un_err_pos, &un->un_pos);
4903 			return (EACCES);
4904 		}
4905 
4906 		/*
4907 		 * zero count means just flush buffers
4908 		 * negative count is not permitted
4909 		 */
4910 		if (mtop->mt_count < 0) {
4911 			return (EINVAL);
4912 		}
4913 
4914 		/* Not on worm */
4915 		if (un->un_read_only == RDWR) {
4916 			un->un_test_append = 1;
4917 		}
4918 
4919 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4920 			if (st_determine_density(dev, B_WRITE)) {
4921 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4922 				    "st_do_mtioctop : EIO : MTWEOF can't "
4923 				    "determine density");
4924 				return (EIO);
4925 			}
4926 		}
4927 
4928 		rval = st_write_fm(dev, (int)mtop->mt_count);
4929 		if ((rval != 0) && (rval != EACCES)) {
4930 			/*
4931 			 * Failure due to something other than illegal
4932 			 * request results in loss of state (st_intr).
4933 			 */
4934 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4935 			    "st_do_mtioctop : EIO : MTWEOF can't write "
4936 			    "file mark");
4937 			rval = EIO;
4938 		}
4939 		break;
4940 
4941 	case MTRETEN:
4942 		/*
4943 		 * retension the tape
4944 		 */
4945 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
4946 		    st_cmd(dev, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
4947 			un->un_pos.pmode = invalid;
4948 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4949 			    "st_do_mtioctop : EIO : MTRETEN ");
4950 			rval = EIO;
4951 		}
4952 		break;
4953 
4954 	case MTREW:
4955 		/*
4956 		 * rewind  the tape
4957 		 */
4958 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
4959 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4960 			    "st_do_mtioctop : EIO:MTREW check "
4961 			    "density/wfm failed");
4962 			return (EIO);
4963 		}
4964 		if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
4965 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4966 			    "st_do_mtioctop : EIO : MTREW ");
4967 			rval = EIO;
4968 		}
4969 		break;
4970 
4971 	case MTOFFL:
4972 		/*
4973 		 * rewinds, and, if appropriate, takes the device offline by
4974 		 * unloading the tape
4975 		 */
4976 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
4977 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4978 			    "st_do_mtioctop :EIO:MTOFFL check "
4979 			    "density/wfm failed");
4980 			return (EIO);
4981 		}
4982 		(void) st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
4983 		if (st_cmd(dev, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
4984 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4985 			    "st_do_mtioctop : EIO : MTOFFL");
4986 			return (EIO);
4987 		}
4988 		un->un_pos.eof = ST_NO_EOF;
4989 		un->un_laststate = un->un_state;
4990 		un->un_state = ST_STATE_OFFLINE;
4991 		un->un_mediastate = MTIO_EJECTED;
4992 		break;
4993 
4994 	case MTLOAD:
4995 		/*
4996 		 * This is to load a tape into the drive
4997 		 * Note that if the tape is not loaded, the device will have
4998 		 * to be opened via O_NDELAY or O_NONBLOCK.
4999 		 */
5000 		/*
5001 		 * Let's try and clean things up, if we are not
5002 		 * initializing, and then send in the load command, no
5003 		 * matter what.
5004 		 *
5005 		 * load after a media change by the user.
5006 		 */
5007 
5008 		if (un->un_state > ST_STATE_INITIALIZING) {
5009 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5010 		}
5011 		rval = st_cmd(dev, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5012 		/* Load command to a drive that doesn't support load */
5013 		if ((rval == EIO) &&
5014 		    ((un->un_status == KEY_NOT_READY) &&
5015 			/* Medium not present */
5016 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5017 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5018 		    (un->un_dp->type == MT_ISSTK9840) &&
5019 			/* CSL not present */
5020 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5021 			rval = ENOTTY;
5022 			break;
5023 		} else if (rval != EACCES) {
5024 			rval = EIO;
5025 		}
5026 		if (rval) {
5027 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5028 			    "st_do_mtioctop : %s : MTLOAD\n",
5029 			    rval == EACCES ? "EACCES" : "EIO");
5030 			/*
5031 			 * If load tape fails, who knows what happened...
5032 			 */
5033 			un->un_pos.pmode = invalid;
5034 			break;
5035 		}
5036 
5037 		/*
5038 		 * reset all counters appropriately using rewind, as if LOAD
5039 		 * succeeds, we are at BOT
5040 		 */
5041 		un->un_state = ST_STATE_INITIALIZING;
5042 
5043 		rval = st_tape_init(dev);
5044 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5045 			rval = 0;
5046 			break;
5047 		}
5048 
5049 		if (rval != 0) {
5050 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5051 			    "st_do_mtioctop : EIO : MTLOAD calls "
5052 			    "st_tape_init\n");
5053 			rval = EIO;
5054 			un->un_state = ST_STATE_OFFLINE;
5055 		}
5056 
5057 		break;
5058 
5059 	case MTNOP:
5060 		un->un_status = 0;		/* Reset status */
5061 		un->un_err_resid = 0;
5062 		mtop->mt_count = MTUNIT(dev);
5063 		break;
5064 
5065 	case MTEOM:
5066 		/*
5067 		 * positions the tape at a location just after the last file
5068 		 * written on the tape. For cartridge and 8 mm, this after
5069 		 * the last file mark; for reel, this is inbetween the two
5070 		 * last 2 file marks
5071 		 */
5072 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5073 		    (un->un_lastop == ST_OP_WRITE) ||
5074 		    (un->un_lastop == ST_OP_WEOF)) {
5075 			/*
5076 			 * If the command wants to move to logical end
5077 			 * of media, and we're already there, we're done.
5078 			 * If we were at logical eot, we reset the state
5079 			 * to be *not* at logical eot.
5080 			 *
5081 			 * If we're at physical or logical eot, we prohibit
5082 			 * forward space operations (unconditionally).
5083 			 *
5084 			 * Also if the last operation was a write of any
5085 			 * kind the tape is at EOD.
5086 			 */
5087 			return (0);
5088 		}
5089 		/*
5090 		 * physical tape position may not be what we've been
5091 		 * telling the user; adjust the request accordingly
5092 		 */
5093 		if (IN_EOF(un->un_pos)) {
5094 			un->un_pos.fileno++;
5095 			un->un_pos.blkno = 0;
5096 		}
5097 
5098 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
5099 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5100 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
5101 			    " failed");
5102 			return (EIO);
5103 		}
5104 
5105 		/*
5106 		 * st_find_eod() returns the last fileno we knew about;
5107 		 */
5108 		savefile = st_find_eod(dev);
5109 
5110 		if ((un->un_status != KEY_BLANK_CHECK) &&
5111 		    (un->un_status != SUN_KEY_EOT)) {
5112 			un->un_pos.pmode = invalid;
5113 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5114 			    "st_do_mtioctop : EIO : MTEOM status check failed");
5115 			rval = EIO;
5116 		} else {
5117 			/*
5118 			 * For 1/2" reel tapes assume logical EOT marked
5119 			 * by two file marks or we don't care that we may
5120 			 * be extending the last file on the tape.
5121 			 */
5122 			if (un->un_dp->options & ST_REEL) {
5123 				if (st_cmd(dev, SCMD_SPACE, Fmk((-1)),
5124 				    SYNC_CMD)) {
5125 					un->un_pos.pmode = invalid;
5126 					ST_DEBUG2(ST_DEVINFO, st_label,
5127 					    SCSI_DEBUG,
5128 					    "st_do_mtioctop : EIO : MTEOM space"
5129 					    " cmd failed");
5130 					rval = EIO;
5131 					break;
5132 				}
5133 				/*
5134 				 * Fix up the block number.
5135 				 */
5136 				un->un_pos.blkno = 0;
5137 				un->un_err_pos.blkno = 0;
5138 			}
5139 			un->un_err_resid = 0;
5140 			un->un_pos.fileno = savefile;
5141 			un->un_pos.eof = ST_EOT;
5142 		}
5143 		un->un_status = 0;
5144 		break;
5145 
5146 	case MTFSF:
5147 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
5148 		break;
5149 
5150 	case MTFSR:
5151 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
5152 		break;
5153 
5154 	case MTBSF:
5155 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
5156 		break;
5157 
5158 	case MTNBSF:
5159 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
5160 		break;
5161 
5162 	case MTBSR:
5163 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
5164 		break;
5165 
5166 	case MTBSSF:
5167 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
5168 		break;
5169 
5170 	case MTFSSF:
5171 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
5172 		break;
5173 
5174 	case MTSRSZ:
5175 
5176 		/*
5177 		 * Set record-size to that sent by user
5178 		 * Check to see if there is reason that the requested
5179 		 * block size should not be set.
5180 		 */
5181 
5182 		/* If requesting variable block size is it ok? */
5183 		if ((mtop->mt_count == 0) &&
5184 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
5185 			return (ENOTTY);
5186 		}
5187 
5188 		/*
5189 		 * If requested block size is not variable "0",
5190 		 * is it less then minimum.
5191 		 */
5192 		if ((mtop->mt_count != 0) &&
5193 		    (mtop->mt_count < un->un_minbsize)) {
5194 			return (EINVAL);
5195 		}
5196 
5197 		/* Is the requested block size more then maximum */
5198 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
5199 		    (un->un_maxbsize != 0)) {
5200 			return (EINVAL);
5201 		}
5202 
5203 		/* Is requested block size a modulus the device likes */
5204 		if ((mtop->mt_count % un->un_data_mod) != 0) {
5205 			return (EINVAL);
5206 		}
5207 
5208 		if (st_change_block_size(dev, (uint32_t)mtop->mt_count) != 0) {
5209 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5210 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
5211 			return (EIO);
5212 		}
5213 
5214 		return (0);
5215 
5216 	case MTGRSZ:
5217 		/*
5218 		 * Get record-size to the user
5219 		 */
5220 		mtop->mt_count = un->un_bsize;
5221 		rval = 0;
5222 		break;
5223 
5224 	case MTTELL:
5225 		rval = st_update_block_pos(un);
5226 		mtop->mt_count = un->un_pos.lgclblkno;
5227 		break;
5228 
5229 	case MTSEEK:
5230 		rval = st_logical_block_locate(un, (uint64_t)mtop->mt_count,
5231 		    un->un_pos.partition);
5232 		/*
5233 		 * This bit of magic make mt print the actual position if
5234 		 * the resulting position was not what was asked for.
5235 		 */
5236 		if (rval == ESPIPE) {
5237 			rval = EIO;
5238 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
5239 				mtop->mt_op = MTTELL;
5240 				mtop->mt_count = un->un_pos.lgclblkno;
5241 			}
5242 		}
5243 		break;
5244 
5245 	case MTLOCK:
5246 		if (st_cmd(dev, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
5247 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5248 			    "st_do_mtioctop : EIO : MTLOCK");
5249 			rval = EIO;
5250 		}
5251 		break;
5252 
5253 	case MTUNLOCK:
5254 		if (st_cmd(dev, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
5255 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5256 			    "st_do_mtioctop : EIO : MTUNLOCK");
5257 			rval = EIO;
5258 		}
5259 		break;
5260 
5261 	default:
5262 		rval = ENOTTY;
5263 	}
5264 
5265 	return (rval);
5266 }
5267 
5268 
5269 /*
5270  * Run a command for uscsi ioctl.
5271  */
5272 static int
5273 st_ioctl_cmd(dev_t dev, struct uscsi_cmd *ucmd, int flag)
5274 {
5275 	struct uscsi_cmd	*uscmd;
5276 	struct buf	*bp;
5277 	enum uio_seg	uioseg;
5278 	int	offline_state = 0;
5279 	int	err = 0;
5280 
5281 	GET_SOFT_STATE(dev);
5282 
5283 	ST_FUNC(ST_DEVINFO, st_ioctl_cmd);
5284 
5285 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5286 	    "st_ioctl_cmd(dev = 0x%lx)\n", dev);
5287 
5288 	ASSERT(mutex_owned(ST_MUTEX));
5289 
5290 	/*
5291 	 * We really don't know what commands are coming in here and
5292 	 * we don't want to limit the commands coming in.
5293 	 *
5294 	 * If st_tape_init() gets called from st_strategy(), then we
5295 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
5296 	 * which it never will, as we set it below.  To prevent
5297 	 * st_tape_init() from getting called, we have to set state to other
5298 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
5299 	 * achieves this purpose already.
5300 	 *
5301 	 * We use offline_state to preserve the OFFLINE state, if it exists,
5302 	 * so other entry points to the driver might have the chance to call
5303 	 * st_tape_init().
5304 	 */
5305 	if (un->un_state == ST_STATE_OFFLINE) {
5306 		un->un_laststate = ST_STATE_OFFLINE;
5307 		un->un_state = ST_STATE_INITIALIZING;
5308 		offline_state = 1;
5309 	}
5310 
5311 	mutex_exit(ST_MUTEX);
5312 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag,
5313 	    ROUTE, &uscmd);
5314 	mutex_enter(ST_MUTEX);
5315 	if (err != 0) {
5316 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5317 		    "st_ioctl_cmd: scsi_uscsi_alloc_and_copyin failed\n");
5318 		goto exit;
5319 	}
5320 
5321 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
5322 
5323 	/* check to see if this command requires the drive to be reserved */
5324 	if (uscmd->uscsi_cdb != NULL) {
5325 		err = st_check_cdb_for_need_to_reserve(un,
5326 		    &((char *)uscmd->uscsi_cdb)[0]);
5327 		if (err) {
5328 			goto exit_free;
5329 		}
5330 	}
5331 
5332 	/*
5333 	 * Get buffer resources...
5334 	 */
5335 	while (un->un_sbuf_busy)
5336 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
5337 	un->un_sbuf_busy = 1;
5338 
5339 #ifdef STDEBUG
5340 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0xf) > 6) {
5341 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
5342 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
5343 		    "uscsi cdb", uscmd->uscsi_cdb);
5344 		if (uscmd->uscsi_buflen) {
5345 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5346 			    "uscsi %s of %ld bytes %s %s space\n",
5347 			    (rw == B_READ) ? rd_str : wr_str,
5348 			    uscmd->uscsi_buflen,
5349 			    (rw == B_READ) ? "to" : "from",
5350 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
5351 		}
5352 	}
5353 #endif /* ST_DEBUG */
5354 
5355 	/*
5356 	 * Although st_ioctl_cmd() never makes use of these
5357 	 * now, we are just being safe and consistent.
5358 	 */
5359 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
5360 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
5361 
5362 	un->un_srqbufp = uscmd->uscsi_rqbuf;
5363 	bp = un->un_sbufp;
5364 	bzero(bp, sizeof (buf_t));
5365 	if (uscmd->uscsi_cdb != NULL) {
5366 		bp->b_forw =
5367 		    (struct buf *)(uintptr_t)((char *)uscmd->uscsi_cdb)[0];
5368 	}
5369 	bp->b_back = (struct buf *)uscmd;
5370 
5371 	mutex_exit(ST_MUTEX);
5372 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd,
5373 	    st_strategy, bp, NULL);
5374 	mutex_enter(ST_MUTEX);
5375 
5376 	/*
5377 	 * If scsi reset successful, don't write any filemarks.
5378 	 */
5379 	if ((err == 0) && (uscmd->uscsi_flags &
5380 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
5381 		un->un_fmneeded = 0;
5382 	}
5383 
5384 exit_free:
5385 	/*
5386 	 * Free resources
5387 	 */
5388 	un->un_sbuf_busy = 0;
5389 	un->un_srqbufp = NULL;
5390 
5391 	/*
5392 	 * If was a space command need to update logical block position.
5393 	 * If the command failed such that positioning is invalid, Don't
5394 	 * update the position as the user must do this to validate the
5395 	 * position for data protection.
5396 	 */
5397 	if ((uscmd->uscsi_cdb != NULL) &&
5398 	    (uscmd->uscsi_cdb[0] == SCMD_SPACE) &&
5399 	    (un->un_pos.pmode != invalid)) {
5400 		uchar_t status = un->un_status;
5401 		(void) st_update_block_pos(un);
5402 		un->un_status = status;
5403 	}
5404 	cv_signal(&un->un_sbuf_cv);
5405 	mutex_exit(ST_MUTEX);
5406 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
5407 	mutex_enter(ST_MUTEX);
5408 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5409 	    "st_ioctl_cmd returns 0x%x\n", err);
5410 
5411 exit:
5412 	/* don't lose offline state */
5413 	if (offline_state) {
5414 		un->un_state = ST_STATE_OFFLINE;
5415 	}
5416 
5417 	ASSERT(mutex_owned(ST_MUTEX));
5418 	return (err);
5419 }
5420 
5421 static int
5422 st_write_fm(dev_t dev, int wfm)
5423 {
5424 	int i;
5425 	int rval;
5426 
5427 	GET_SOFT_STATE(dev);
5428 
5429 	ST_FUNC(ST_DEVINFO, st_write_fm);
5430 
5431 	ASSERT(mutex_owned(ST_MUTEX));
5432 
5433 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5434 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
5435 
5436 	/*
5437 	 * write one filemark at the time after EOT
5438 	 */
5439 	if (un->un_pos.eof >= ST_EOT) {
5440 		for (i = 0; i < wfm; i++) {
5441 			rval = st_cmd(dev, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
5442 			if (rval == EACCES) {
5443 				return (rval);
5444 			}
5445 			if (rval != 0) {
5446 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5447 				    "st_write_fm : EIO : write EOT file mark");
5448 				return (EIO);
5449 			}
5450 		}
5451 	} else {
5452 		rval = st_cmd(dev, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
5453 		if (rval == EACCES) {
5454 			return (rval);
5455 		}
5456 		if (rval) {
5457 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5458 			    "st_write_fm : EIO : write file mark");
5459 			return (EIO);
5460 		}
5461 	}
5462 
5463 	ASSERT(mutex_owned(ST_MUTEX));
5464 	return (0);
5465 }
5466 
5467 #ifdef STDEBUG
5468 static void
5469 start_dump(struct scsi_tape *un, struct buf *bp)
5470 {
5471 	struct scsi_pkt *pkt = BP_PKT(bp);
5472 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
5473 
5474 	ST_FUNC(ST_DEVINFO, start_dump);
5475 
5476 	if ((st_debug & 0xf) < 6)
5477 		return;
5478 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5479 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
5480 	    (void *)bp->b_forw, bp->b_bcount,
5481 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
5482 
5483 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
5484 	    "st_start: cdb",  (caddr_t)cdbp);
5485 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5486 	    "st_start: fileno=%d, blk=%d\n",
5487 	    un->un_pos.fileno, un->un_pos.blkno);
5488 }
5489 #endif
5490 
5491 
5492 /*
5493  * Command start && done functions
5494  */
5495 
5496 /*
5497  * st_start()
5498  *
5499  * Called from:
5500  *  st_strategy() to start a command.
5501  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
5502  *  st_attach() when resuming from power down state.
5503  *  st_start_restart() to retry transport when device was previously busy.
5504  *  st_done_and_mutex_exit() to start the next command when previous is done.
5505  *
5506  * On entry:
5507  *  scsi_pkt may or may not be allocated.
5508  *
5509  */
5510 static void
5511 st_start(struct scsi_tape *un)
5512 {
5513 	struct buf *bp;
5514 	int status;
5515 
5516 	ST_FUNC(ST_DEVINFO, st_start);
5517 	ASSERT(mutex_owned(ST_MUTEX));
5518 
5519 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5520 	    "st_start(): dev = 0x%lx\n", un->un_dev);
5521 
5522 	if ((bp = un->un_quef) == NULL) {
5523 		return;
5524 	}
5525 
5526 	ASSERT((bp->b_flags & B_DONE) == 0);
5527 
5528 	/*
5529 	 * Don't send more than un_throttle commands to the HBA
5530 	 */
5531 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
5532 		return;
5533 	}
5534 
5535 	/*
5536 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
5537 	 * build the command.
5538 	 */
5539 	if (BP_PKT(bp) == NULL) {
5540 		ASSERT((bp->b_flags & B_DONE) == 0);
5541 		st_make_cmd(un, bp, st_runout);
5542 		ASSERT((bp->b_flags & B_DONE) == 0);
5543 		status = geterror(bp);
5544 
5545 		/*
5546 		 * Some HBA's don't call bioerror() to set an error.
5547 		 * And geterror() returns zero if B_ERROR is not set.
5548 		 * So if we get zero we must check b_error.
5549 		 */
5550 		if (status == 0 && bp->b_error != 0) {
5551 			status = bp->b_error;
5552 			bioerror(bp, status);
5553 		}
5554 
5555 		/*
5556 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
5557 		 * In tape ENOMEM has special meaning so we'll change it.
5558 		 */
5559 		if (status == ENOMEM) {
5560 			status = 0;
5561 			bioerror(bp, status);
5562 		}
5563 
5564 		/*
5565 		 * Did it fail and is it retryable?
5566 		 * If so return and wait for the callback through st_runout.
5567 		 * Also looks like scsi_init_pkt() will setup a callback even
5568 		 * if it isn't retryable.
5569 		 */
5570 		if (BP_PKT(bp) == NULL) {
5571 			if (status == 0) {
5572 				/*
5573 				 * If first attempt save state.
5574 				 */
5575 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
5576 					un->un_laststate = un->un_state;
5577 					un->un_state = ST_STATE_RESOURCE_WAIT;
5578 				}
5579 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5580 				    "temp no resources for pkt\n");
5581 			} else {
5582 				/*
5583 				 * Unlikely that it would be retryable then not.
5584 				 */
5585 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
5586 					un->un_state = un->un_laststate;
5587 				}
5588 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5589 				    "perm no resources for pkt errno = 0x%x\n",
5590 				    status);
5591 			}
5592 			return;
5593 		}
5594 		/*
5595 		 * Worked this time set the state back.
5596 		 */
5597 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
5598 			un->un_state = un->un_laststate;
5599 		}
5600 	}
5601 
5602 	/*
5603 	 * move from waitq to runq
5604 	 */
5605 	un->un_quef = bp->b_actf;
5606 	if (un->un_quel == bp) {
5607 		/*
5608 		 *  For the case of queue having one
5609 		 *  element, set the tail pointer to
5610 		 *  point to the element.
5611 		 */
5612 		un->un_quel = bp->b_actf;
5613 	}
5614 
5615 	bp->b_actf = NULL;
5616 
5617 	if (un->un_runqf) {
5618 		un->un_runql->b_actf = bp;
5619 	} else {
5620 		un->un_runqf = bp;
5621 	}
5622 	un->un_runql = bp;
5623 
5624 
5625 	ST_CDB(ST_DEVINFO, "Start CDB", (char *)BP_PKT(bp)->pkt_cdbp);
5626 
5627 #ifdef STDEBUG
5628 	start_dump(un, bp);
5629 #endif
5630 
5631 	/* could not get here if throttle was zero */
5632 	un->un_last_throttle = un->un_throttle;
5633 	un->un_throttle = 0;	/* so nothing else will come in here */
5634 	un->un_ncmds++;
5635 
5636 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
5637 
5638 	mutex_exit(ST_MUTEX);
5639 
5640 	status = scsi_transport(BP_PKT(bp));
5641 
5642 	mutex_enter(ST_MUTEX);
5643 
5644 	if (un->un_last_throttle) {
5645 		un->un_throttle = un->un_last_throttle;
5646 	}
5647 
5648 	if (status != TRAN_ACCEPT) {
5649 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
5650 		mutex_exit(ST_MUTEX);
5651 
5652 		if (status == TRAN_BUSY) {
5653 			/* if too many retries, fail the transport */
5654 			if (st_handle_start_busy(un, bp,
5655 			    ST_TRAN_BUSY_TIMEOUT) == 0)
5656 				goto done;
5657 		}
5658 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
5659 		    "transport rejected\n");
5660 		bp->b_resid = bp->b_bcount;
5661 
5662 
5663 #ifndef __lock_lint
5664 		/*
5665 		 * warlock doesn't understand this potential
5666 		 * recursion?
5667 		 */
5668 		mutex_enter(ST_MUTEX);
5669 		ST_DO_KSTATS(bp, kstat_waitq_exit);
5670 		ST_DO_ERRSTATS(un, st_transerrs);
5671 		st_bioerror(bp, EIO);
5672 		SET_PE_FLAG(un);
5673 		st_done_and_mutex_exit(un, bp);
5674 #endif
5675 	} else {
5676 		un->un_tran_retry_ct = 0;
5677 		mutex_exit(ST_MUTEX);
5678 	}
5679 
5680 done:
5681 
5682 	mutex_enter(ST_MUTEX);
5683 }
5684 
5685 /*
5686  * if the transport is busy, then put this bp back on the waitq
5687  */
5688 static int
5689 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
5690     clock_t timeout_interval)
5691 {
5692 	struct buf *last_quef, *runq_bp;
5693 	int rval = 0;
5694 
5695 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
5696 
5697 	mutex_enter(ST_MUTEX);
5698 
5699 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5700 	    "st_handle_start_busy()\n");
5701 
5702 	/*
5703 	 * Check to see if we hit the retry timeout and one last check for
5704 	 * making sure this is the last on the runq, if it is not, we have
5705 	 * to fail
5706 	 */
5707 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
5708 	    (un->un_runql != bp)) {
5709 		rval = -1;
5710 		goto exit;
5711 	}
5712 
5713 	/* put the bp back on the waitq */
5714 	if (un->un_quef) {
5715 		last_quef = un->un_quef;
5716 		un->un_quef = bp;
5717 		bp->b_actf = last_quef;
5718 	} else  {
5719 		bp->b_actf = NULL;
5720 		un->un_quef = bp;
5721 		un->un_quel = bp;
5722 	}
5723 
5724 	/*
5725 	 * Decrement un_ncmds so that this
5726 	 * gets thru' st_start() again.
5727 	 */
5728 	un->un_ncmds--;
5729 
5730 	/*
5731 	 * since this is an error case, we won't have to do
5732 	 * this list walking much.  We've already made sure this bp was the
5733 	 * last on the runq
5734 	 */
5735 	runq_bp = un->un_runqf;
5736 
5737 	if (un->un_runqf == bp) {
5738 		un->un_runqf = NULL;
5739 		un->un_runql = NULL;
5740 	} else {
5741 		while (runq_bp) {
5742 			if (runq_bp->b_actf == bp) {
5743 				runq_bp->b_actf = NULL;
5744 				un->un_runql = runq_bp;
5745 				break;
5746 			}
5747 			runq_bp = runq_bp->b_actf;
5748 		}
5749 	}
5750 
5751 
5752 	/*
5753 	 * send a marker pkt, if appropriate
5754 	 */
5755 	st_hba_unflush(un);
5756 
5757 	/*
5758 	 * all queues are aligned, we are just waiting to
5759 	 * transport, don't alloc any more buf p's, when
5760 	 * st_start is reentered.
5761 	 */
5762 	(void) timeout(st_start_restart, un, timeout_interval);
5763 
5764 exit:
5765 	mutex_exit(ST_MUTEX);
5766 	return (rval);
5767 }
5768 
5769 
5770 /*
5771  * st_runout a callback that is called what a resource allocatation failed
5772  */
5773 static int
5774 st_runout(caddr_t arg)
5775 {
5776 	struct scsi_tape *un = (struct scsi_tape *)arg;
5777 	struct buf *bp;
5778 	ASSERT(un != NULL);
5779 
5780 	ST_FUNC(ST_DEVINFO, st_runout);
5781 
5782 	mutex_enter(ST_MUTEX);
5783 
5784 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
5785 
5786 	bp = un->un_quef;
5787 
5788 	/*
5789 	 * failed scsi_init_pkt(). If errno is zero its retryable.
5790 	 */
5791 	if ((bp != NULL) && (geterror(bp) != 0)) {
5792 
5793 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
5794 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
5795 		    bp->b_flags, geterror(bp));
5796 		ASSERT((bp->b_flags & B_DONE) == 0);
5797 
5798 		un->un_quef = bp->b_actf;
5799 		if (un->un_quel == bp) {
5800 			/*
5801 			 *  For the case of queue having one
5802 			 *  element, set the tail pointer to
5803 			 *  point to the element.
5804 			 */
5805 			un->un_quel = bp->b_actf;
5806 		}
5807 		mutex_exit(ST_MUTEX);
5808 		bp->b_actf = NULL;
5809 
5810 		ASSERT((bp->b_flags & B_DONE) == 0);
5811 
5812 		/*
5813 		 * Set resid, Error already set, then unblock calling thread.
5814 		 */
5815 		bp->b_resid = bp->b_bcount;
5816 		biodone(bp);
5817 	} else {
5818 		/*
5819 		 * Try Again
5820 		 */
5821 		st_start(un);
5822 		mutex_exit(ST_MUTEX);
5823 	}
5824 
5825 	/*
5826 	 * Comments courtesy of sd.c
5827 	 * The scsi_init_pkt routine allows for the callback function to
5828 	 * return a 0 indicating the callback should be rescheduled or a 1
5829 	 * indicating not to reschedule. This routine always returns 1
5830 	 * because the driver always provides a callback function to
5831 	 * scsi_init_pkt. This results in a callback always being scheduled
5832 	 * (via the scsi_init_pkt callback implementation) if a resource
5833 	 * failure occurs.
5834 	 */
5835 
5836 	return (1);
5837 }
5838 
5839 /*
5840  * st_done_and_mutex_exit()
5841  *	- remove bp from runq
5842  *	- start up the next request
5843  *	- if this was an asynch bp, clean up
5844  *	- exit with released mutex
5845  */
5846 static void
5847 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
5848 {
5849 	struct buf *runqbp, *prevbp;
5850 	int	pe_flagged = 0;
5851 
5852 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
5853 #if !defined(lint)
5854 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
5855 #endif
5856 
5857 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
5858 
5859 	ASSERT(mutex_owned(ST_MUTEX));
5860 
5861 	/*
5862 	 * if bp is still on the runq (anywhere), then remove it
5863 	 */
5864 	prevbp = NULL;
5865 	for (runqbp = un->un_runqf; runqbp != 0; runqbp = runqbp->b_actf) {
5866 		if (runqbp == bp) {
5867 			if (runqbp == un->un_runqf) {
5868 				un->un_runqf = bp->b_actf;
5869 			} else {
5870 				prevbp->b_actf = bp->b_actf;
5871 			}
5872 			if (un->un_runql == bp) {
5873 				un->un_runql = prevbp;
5874 			}
5875 			break;
5876 		}
5877 		prevbp = runqbp;
5878 	}
5879 	bp->b_actf = NULL;
5880 
5881 	un->un_ncmds--;
5882 	cv_signal(&un->un_queue_cv);
5883 
5884 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5885 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
5886 	    "0x%x\n", (uchar_t)*((caddr_t)(BP_PKT(bp))->pkt_cdbp), bp->b_bcount,
5887 	    bp->b_resid, bp->b_flags);
5888 
5889 
5890 	/*
5891 	 * update kstats with transfer count info
5892 	 */
5893 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
5894 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
5895 		if (bp->b_flags & B_READ) {
5896 			IOSP->reads++;
5897 			IOSP->nread += n_done;
5898 		} else {
5899 			IOSP->writes++;
5900 			IOSP->nwritten += n_done;
5901 		}
5902 	}
5903 
5904 	/*
5905 	 * Start the next one before releasing resources on this one, if
5906 	 * there is something on the queue and persistent errors has not been
5907 	 * flagged
5908 	 */
5909 
5910 	if ((pe_flagged = IS_PE_FLAG_SET(un)) != 0) {
5911 		un->un_last_resid = bp->b_resid;
5912 		un->un_last_count = bp->b_bcount;
5913 	}
5914 
5915 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
5916 		cv_broadcast(&un->un_tape_busy_cv);
5917 	} else if (un->un_quef && un->un_throttle && !pe_flagged) {
5918 		st_start(un);
5919 	}
5920 
5921 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
5922 		/*
5923 		 * Since we marked this ourselves as ASYNC,
5924 		 * there isn't anybody around waiting for
5925 		 * completion any more.
5926 		 */
5927 		uchar_t com = (uchar_t)(uintptr_t)bp->b_forw;
5928 		if (com == SCMD_READ || com == SCMD_WRITE) {
5929 			bp->b_un.b_addr = (caddr_t)0;
5930 		}
5931 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5932 		    "st_done_and_mutex_exit(async): freeing pkt\n");
5933 		scsi_destroy_pkt(BP_PKT(bp));
5934 		un->un_sbuf_busy = 0;
5935 		cv_signal(&un->un_sbuf_cv);
5936 		mutex_exit(ST_MUTEX);
5937 		return;
5938 	}
5939 
5940 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
5941 		/*
5942 		 * Copy status from scsi_pkt to uscsi_cmd
5943 		 * since st_ioctl_cmd needs it
5944 		 */
5945 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
5946 	}
5947 
5948 
5949 #ifdef STDEBUG
5950 	if (((st_debug & 0xf) >= 4) &&
5951 	    (((un->un_pos.blkno % 100) == 0) || IS_PE_FLAG_SET(un))) {
5952 
5953 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
5954 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
5955 		    "un_errno = %d, un_pe = %d\n",
5956 		    un->un_ncmds, un->un_throttle, un->un_errno,
5957 		    un->un_persist_errors);
5958 	}
5959 
5960 #endif
5961 
5962 	mutex_exit(ST_MUTEX);
5963 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5964 	    "st_done_and_mutex_exit: freeing pkt\n");
5965 
5966 	scsi_destroy_pkt(BP_PKT(bp));
5967 
5968 	biodone(bp);
5969 
5970 	/*
5971 	 * now that we biodoned that command, if persistent errors have been
5972 	 * flagged, flush the waitq
5973 	 */
5974 	if (pe_flagged)
5975 		st_flush(un);
5976 }
5977 
5978 
5979 /*
5980  * Tape error, flush tape driver queue.
5981  */
5982 static void
5983 st_flush(struct scsi_tape *un)
5984 {
5985 	struct buf *bp;
5986 
5987 	ST_FUNC(ST_DEVINFO, st_flush);
5988 
5989 	mutex_enter(ST_MUTEX);
5990 
5991 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
5992 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
5993 	    un->un_ncmds, (void *)un->un_quef);
5994 
5995 	/*
5996 	 * if we still have commands outstanding, wait for them to come in
5997 	 * before flushing the queue, and make sure there is a queue
5998 	 */
5999 	if (un->un_ncmds || !un->un_quef)
6000 		goto exit;
6001 
6002 	/*
6003 	 * we have no more commands outstanding, so let's deal with special
6004 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6005 	 * is 0, then we know there was no error and we return a 0 read or
6006 	 * write before showing errors
6007 	 */
6008 
6009 	/* Flush the wait queue. */
6010 	while ((bp = un->un_quef) != NULL) {
6011 		un->un_quef = bp->b_actf;
6012 
6013 		bp->b_resid = bp->b_bcount;
6014 
6015 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6016 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6017 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6018 
6019 		st_set_pe_errno(un);
6020 
6021 		bioerror(bp, un->un_errno);
6022 
6023 		mutex_exit(ST_MUTEX);
6024 		/* it should have one, but check anyway */
6025 		if (BP_PKT(bp)) {
6026 			scsi_destroy_pkt(BP_PKT(bp));
6027 		}
6028 		biodone(bp);
6029 		mutex_enter(ST_MUTEX);
6030 	}
6031 
6032 	/*
6033 	 * It's not a bad practice to reset the
6034 	 * waitq tail pointer to NULL.
6035 	 */
6036 	un->un_quel = NULL;
6037 
6038 exit:
6039 	/* we mucked with the queue, so let others know about it */
6040 	cv_signal(&un->un_queue_cv);
6041 	mutex_exit(ST_MUTEX);
6042 }
6043 
6044 
6045 /*
6046  * Utility functions
6047  */
6048 static int
6049 st_determine_generic(dev_t dev)
6050 {
6051 	int bsize;
6052 	static char *cart = "0.25 inch cartridge";
6053 	char *sizestr;
6054 
6055 	GET_SOFT_STATE(dev);
6056 
6057 	ST_FUNC(ST_DEVINFO, st_determine_generic);
6058 
6059 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6060 	    "st_determine_generic(dev = 0x%lx)\n", dev);
6061 
6062 	ASSERT(mutex_owned(ST_MUTEX));
6063 
6064 	if (st_modesense(un)) {
6065 		return (-1);
6066 	}
6067 
6068 	bsize = (un->un_mspl->high_bl << 16)	|
6069 	    (un->un_mspl->mid_bl << 8)	|
6070 	    (un->un_mspl->low_bl);
6071 
6072 	if (bsize == 0) {
6073 		un->un_dp->options |= ST_VARIABLE;
6074 		un->un_dp->bsize = 0;
6075 		un->un_bsize = 0;
6076 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
6077 		/*
6078 		 * record size of this device too big.
6079 		 * try and convert it to variable record length.
6080 		 *
6081 		 */
6082 		un->un_dp->options |= ST_VARIABLE;
6083 		if (st_change_block_size(dev, 0) != 0) {
6084 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6085 			    "Fixed Record Size %d is too large\n", bsize);
6086 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6087 			    "Cannot switch to variable record size\n");
6088 			un->un_dp->options &= ~ST_VARIABLE;
6089 			return (-1);
6090 		}
6091 	} else if (st_change_block_size(dev, 0) == 0) {
6092 		/*
6093 		 * If the drive was set to a non zero block size,
6094 		 * See if it can be set to a zero block size.
6095 		 * If it works, ST_VARIABLE so user can set it as they want.
6096 		 */
6097 		un->un_dp->options |= ST_VARIABLE;
6098 		un->un_dp->bsize = 0;
6099 		un->un_bsize = 0;
6100 	} else {
6101 		un->un_dp->bsize = bsize;
6102 		un->un_bsize = bsize;
6103 	}
6104 
6105 
6106 	switch (un->un_mspl->density) {
6107 	default:
6108 	case 0x0:
6109 		/*
6110 		 * default density, cannot determine any other
6111 		 * information.
6112 		 */
6113 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
6114 		un->un_dp->type = ST_TYPE_DEFAULT;
6115 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
6116 		break;
6117 	case 0x1:
6118 	case 0x2:
6119 	case 0x3:
6120 	case 0x6:
6121 		/*
6122 		 * 1/2" reel
6123 		 */
6124 		sizestr = "0.50 inch reel";
6125 		un->un_dp->type = ST_TYPE_REEL;
6126 		un->un_dp->options |= ST_REEL;
6127 		un->un_dp->densities[0] = 0x1;
6128 		un->un_dp->densities[1] = 0x2;
6129 		un->un_dp->densities[2] = 0x6;
6130 		un->un_dp->densities[3] = 0x3;
6131 		break;
6132 	case 0x4:
6133 	case 0x5:
6134 	case 0x7:
6135 	case 0x0b:
6136 
6137 		/*
6138 		 * Quarter inch.
6139 		 */
6140 		sizestr = cart;
6141 		un->un_dp->type = ST_TYPE_DEFAULT;
6142 		un->un_dp->options |= ST_QIC;
6143 
6144 		un->un_dp->densities[1] = 0x4;
6145 		un->un_dp->densities[2] = 0x5;
6146 		un->un_dp->densities[3] = 0x7;
6147 		un->un_dp->densities[0] = 0x0b;
6148 		break;
6149 
6150 	case 0x0f:
6151 	case 0x10:
6152 	case 0x11:
6153 	case 0x12:
6154 		/*
6155 		 * QIC-120, QIC-150, QIC-320, QIC-600
6156 		 */
6157 		sizestr = cart;
6158 		un->un_dp->type = ST_TYPE_DEFAULT;
6159 		un->un_dp->options |= ST_QIC;
6160 		un->un_dp->densities[0] = 0x0f;
6161 		un->un_dp->densities[1] = 0x10;
6162 		un->un_dp->densities[2] = 0x11;
6163 		un->un_dp->densities[3] = 0x12;
6164 		break;
6165 
6166 	case 0x09:
6167 	case 0x0a:
6168 	case 0x0c:
6169 	case 0x0d:
6170 		/*
6171 		 * 1/2" cartridge tapes. Include HI-TC.
6172 		 */
6173 		sizestr = cart;
6174 		sizestr[2] = '5';
6175 		sizestr[3] = '0';
6176 		un->un_dp->type = ST_TYPE_HIC;
6177 		un->un_dp->densities[0] = 0x09;
6178 		un->un_dp->densities[1] = 0x0a;
6179 		un->un_dp->densities[2] = 0x0c;
6180 		un->un_dp->densities[3] = 0x0d;
6181 		break;
6182 
6183 	case 0x13:
6184 			/* DDS-2/DDS-3 scsi spec densities */
6185 	case 0x24:
6186 	case 0x25:
6187 	case 0x26:
6188 		sizestr = "DAT Data Storage (DDS)";
6189 		un->un_dp->type = ST_TYPE_DAT;
6190 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6191 		break;
6192 
6193 	case 0x14:
6194 		/*
6195 		 * Helical Scan (Exabyte) devices
6196 		 */
6197 		sizestr = "8mm helical scan cartridge";
6198 		un->un_dp->type = ST_TYPE_EXABYTE;
6199 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6200 		break;
6201 	}
6202 
6203 	/*
6204 	 * Assume LONG ERASE, BSF and BSR
6205 	 */
6206 
6207 	un->un_dp->options |=
6208 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
6209 
6210 	/*
6211 	 * Only if mode sense data says no buffered write, set NOBUF
6212 	 */
6213 	if (un->un_mspl->bufm == 0)
6214 		un->un_dp->options |= ST_NOBUF;
6215 
6216 	/*
6217 	 * set up large read and write retry counts
6218 	 */
6219 
6220 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
6221 
6222 	/*
6223 	 * If this is a 0.50 inch reel tape, and
6224 	 * it is *not* variable mode, try and
6225 	 * set it to variable record length
6226 	 * mode.
6227 	 */
6228 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
6229 	    (un->un_dp->options & ST_VARIABLE)) {
6230 		if (st_change_block_size(dev, 0) == 0) {
6231 			un->un_dp->bsize = 0;
6232 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
6233 			    un->un_mspl->low_bl = 0;
6234 		}
6235 	}
6236 
6237 	/*
6238 	 * Write to console about type of device found
6239 	 */
6240 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
6241 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
6242 	    sizestr);
6243 	if (un->un_dp->options & ST_VARIABLE) {
6244 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6245 		    "!Variable record length I/O\n");
6246 	} else {
6247 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6248 		    "!Fixed record length (%d byte blocks) I/O\n",
6249 		    un->un_dp->bsize);
6250 	}
6251 	ASSERT(mutex_owned(ST_MUTEX));
6252 	return (0);
6253 }
6254 
6255 static int
6256 st_determine_density(dev_t dev, int rw)
6257 {
6258 	int rval = 0;
6259 
6260 	GET_SOFT_STATE(dev);
6261 
6262 	ST_FUNC(ST_DEVINFO, st_determine_density);
6263 
6264 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6265 	    "st_determine_density(dev = 0x%lx, rw = %s)\n",
6266 	    dev, (rw == B_WRITE ? wr_str: rd_str));
6267 
6268 	ASSERT(mutex_owned(ST_MUTEX));
6269 
6270 	/*
6271 	 * If we're past BOT, density is determined already.
6272 	 */
6273 	if (un->un_pos.pmode == logical) {
6274 		if (un->un_pos.lgclblkno != 0) {
6275 			goto exit;
6276 		}
6277 	} else if (un->un_pos.pmode == legacy) {
6278 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
6279 			/*
6280 			 * XXX: put in a bitch message about attempting to
6281 			 * XXX: change density past BOT.
6282 			 */
6283 			goto exit;
6284 		}
6285 	} else {
6286 		goto exit;
6287 	}
6288 
6289 
6290 	/*
6291 	 * If we're going to be writing, we set the density
6292 	 */
6293 	if (rw == 0 || rw == B_WRITE) {
6294 		/* un_curdens is used as an index into densities table */
6295 		un->un_curdens = MT_DENSITY(un->un_dev);
6296 		if (st_set_density(dev)) {
6297 			rval = -1;
6298 		}
6299 		goto exit;
6300 	}
6301 
6302 	/*
6303 	 * If density is known already,
6304 	 * we don't have to get it again.(?)
6305 	 */
6306 	if (!un->un_density_known) {
6307 		if (st_get_density(dev)) {
6308 			rval = -1;
6309 		}
6310 	}
6311 
6312 exit:
6313 	ASSERT(mutex_owned(ST_MUTEX));
6314 	return (rval);
6315 }
6316 
6317 
6318 /*
6319  * Try to determine density. We do this by attempting to read the
6320  * first record off the tape, cycling through the available density
6321  * codes as we go.
6322  */
6323 
6324 static int
6325 st_get_density(dev_t dev)
6326 {
6327 	int succes = 0, rval = -1, i;
6328 	uint_t size;
6329 	uchar_t dens, olddens;
6330 
6331 	GET_SOFT_STATE(dev);
6332 
6333 	ST_FUNC(ST_DEVINFO, st_get_density);
6334 
6335 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6336 	    "st_get_density(dev = 0x%lx)\n", dev);
6337 
6338 	ASSERT(mutex_owned(ST_MUTEX));
6339 
6340 	/*
6341 	 * If Auto Density override is enabled The drive has
6342 	 * only one density and there is no point in attempting
6343 	 * find the correct one.
6344 	 *
6345 	 * Since most modern drives auto detect the density
6346 	 * and format of the recorded media before they come
6347 	 * ready. What this function does is a legacy behavior
6348 	 * and modern drives not only don't need it, The backup
6349 	 * utilities that do positioning via uscsi find the un-
6350 	 * expected rewinds problematic.
6351 	 *
6352 	 * The drives that need this are old reel to reel devices.
6353 	 * I took a swag and said they must be scsi-1 or older.
6354 	 * I don't beleave there will any of the newer devices
6355 	 * that need this. There will be some scsi-1 devices that
6356 	 * don't need this but I don't think they will be using the
6357 	 * BIG aftermarket backup and restore utilitys.
6358 	 */
6359 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
6360 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
6361 		un->un_density_known = 1;
6362 		rval = 0;
6363 		goto exit;
6364 	}
6365 
6366 	/*
6367 	 * This will only work on variable record length tapes
6368 	 * if and only if all variable record length tapes autodensity
6369 	 * select.
6370 	 */
6371 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
6372 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
6373 
6374 	/*
6375 	 * Start at the specified density
6376 	 */
6377 
6378 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
6379 
6380 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
6381 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
6382 		/*
6383 		 * If we've done this density before,
6384 		 * don't bother to do it again.
6385 		 */
6386 		dens = un->un_dp->densities[un->un_curdens];
6387 		if (i > 0 && dens == olddens)
6388 			continue;
6389 		olddens = dens;
6390 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6391 		    "trying density 0x%x\n", dens);
6392 		if (st_set_density(dev)) {
6393 			continue;
6394 		}
6395 
6396 		/*
6397 		 * XXX - the creates lots of headaches and slowdowns - must
6398 		 * fix.
6399 		 */
6400 		succes = (st_cmd(dev, SCMD_READ, (int)size, SYNC_CMD) == 0);
6401 		if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
6402 			break;
6403 		}
6404 		if (succes) {
6405 			st_init(un);
6406 			rval = 0;
6407 			un->un_density_known = 1;
6408 			break;
6409 		}
6410 	}
6411 	kmem_free(un->un_tmpbuf, size);
6412 	un->un_tmpbuf = 0;
6413 
6414 exit:
6415 	ASSERT(mutex_owned(ST_MUTEX));
6416 	return (rval);
6417 }
6418 
6419 static int
6420 st_set_density(dev_t dev)
6421 {
6422 	int rval = 0;
6423 
6424 	GET_SOFT_STATE(dev);
6425 
6426 	ST_FUNC(ST_DEVINFO, st_set_density);
6427 
6428 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6429 	    "st_set_density(dev = 0x%lx): density = 0x%x\n", dev,
6430 	    un->un_dp->densities[un->un_curdens]);
6431 
6432 	ASSERT(mutex_owned(ST_MUTEX));
6433 
6434 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
6435 
6436 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
6437 		/*
6438 		 * If auto density override is not set, Use mode select
6439 		 * to set density and compression.
6440 		 */
6441 		if (st_modeselect(un)) {
6442 			rval = -1;
6443 		}
6444 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
6445 		/*
6446 		 * If auto density and mode select compression are set,
6447 		 * This is a drive with one density code but compression
6448 		 * can be enabled or disabled.
6449 		 * Set compression but no need to set density.
6450 		 */
6451 		rval = st_set_compression(un);
6452 		if ((rval != 0) && (rval != EALREADY)) {
6453 			rval = -1;
6454 		} else {
6455 			rval = 0;
6456 		}
6457 	}
6458 
6459 	/* If sucessful set density and/or compression, mark density known */
6460 	if (rval == 0) {
6461 		un->un_density_known = 1;
6462 	}
6463 
6464 	ASSERT(mutex_owned(ST_MUTEX));
6465 	return (rval);
6466 }
6467 
6468 static int
6469 st_loadtape(dev_t dev)
6470 {
6471 	int rval;
6472 
6473 	GET_SOFT_STATE(dev);
6474 
6475 	ST_FUNC(ST_DEVINFO, st_load_tape);
6476 
6477 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6478 	    "st_loadtape(dev = 0x%lx)\n", dev);
6479 
6480 	ASSERT(mutex_owned(ST_MUTEX));
6481 
6482 	/*
6483 	 * 'LOAD' the tape to BOT by rewinding
6484 	 */
6485 	rval = st_cmd(dev, SCMD_REWIND, 1, SYNC_CMD);
6486 	if (rval == 0) {
6487 		st_init(un);
6488 		un->un_density_known = 0;
6489 	}
6490 
6491 	ASSERT(mutex_owned(ST_MUTEX));
6492 	return (rval);
6493 }
6494 
6495 
6496 /*
6497  * Note: QIC devices aren't so smart.  If you try to append
6498  * after EOM, the write can fail because the device doesn't know
6499  * it's at EOM.	 In that case, issue a read.  The read should fail
6500  * because there's no data, but the device knows it's at EOM,
6501  * so a subsequent write should succeed.  To further confuse matters,
6502  * the target returns the same error if the tape is positioned
6503  * such that a write would overwrite existing data.  That's why
6504  * we have to do the append test.  A read in the middle of
6505  * recorded data would succeed, thus indicating we're attempting
6506  * something illegal.
6507  */
6508 
6509 
6510 static void
6511 st_test_append(struct buf *bp)
6512 {
6513 	dev_t dev = bp->b_edev;
6514 	struct scsi_tape *un;
6515 	uchar_t status;
6516 	unsigned bcount;
6517 
6518 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
6519 
6520 	ST_FUNC(ST_DEVINFO, st_test_append);
6521 
6522 	ASSERT(mutex_owned(ST_MUTEX));
6523 
6524 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6525 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
6526 
6527 	un->un_laststate = un->un_state;
6528 	un->un_state = ST_STATE_APPEND_TESTING;
6529 	un->un_test_append = 0;
6530 
6531 	/*
6532 	 * first, map in the buffer, because we're doing a double write --
6533 	 * first into the kernel, then onto the tape.
6534 	 */
6535 	bp_mapin(bp);
6536 
6537 	/*
6538 	 * get a copy of the data....
6539 	 */
6540 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
6541 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
6542 
6543 	/*
6544 	 * attempt the write..
6545 	 */
6546 
6547 	if (st_cmd(dev, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
6548 success:
6549 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6550 		    "append write succeeded\n");
6551 		bp->b_resid = un->un_sbufp->b_resid;
6552 		mutex_exit(ST_MUTEX);
6553 		bcount = (unsigned)bp->b_bcount;
6554 		biodone(bp);
6555 		mutex_enter(ST_MUTEX);
6556 		un->un_laststate = un->un_state;
6557 		un->un_state = ST_STATE_OPEN;
6558 		kmem_free(un->un_tmpbuf, bcount);
6559 		un->un_tmpbuf = NULL;
6560 		return;
6561 	}
6562 
6563 	/*
6564 	 * The append failed. Do a short read. If that fails,  we are at EOM
6565 	 * so we can retry the write command. If that succeeds, than we're
6566 	 * all screwed up (the controller reported a real error).
6567 	 *
6568 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
6569 	 * XXX: block size?
6570 	 *
6571 	 */
6572 	status = un->un_status;
6573 	un->un_status = 0;
6574 	(void) st_cmd(dev, SCMD_READ, SECSIZE, SYNC_CMD);
6575 	if (un->un_status == KEY_BLANK_CHECK) {
6576 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6577 		    "append at EOM\n");
6578 		/*
6579 		 * Okay- the read failed. We should actually have confused
6580 		 * the controller enough to allow writing. In any case, the
6581 		 * i/o is on its own from here on out.
6582 		 */
6583 		un->un_laststate = un->un_state;
6584 		un->un_state = ST_STATE_OPEN;
6585 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
6586 		if (st_cmd(dev, (int)SCMD_WRITE, (int)bp->b_bcount,
6587 		    SYNC_CMD) == 0) {
6588 			goto success;
6589 		}
6590 	}
6591 
6592 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6593 	    "append write failed- not at EOM\n");
6594 	bp->b_resid = bp->b_bcount;
6595 	st_bioerror(bp, EIO);
6596 
6597 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6598 	    "st_test_append : EIO : append write failed - not at EOM");
6599 
6600 	/*
6601 	 * backspace one record to get back to where we were
6602 	 */
6603 	if (st_cmd(dev, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
6604 		un->un_pos.pmode = invalid;
6605 	}
6606 
6607 	un->un_err_resid = bp->b_resid;
6608 	un->un_status = status;
6609 
6610 	/*
6611 	 * Note: biodone will do a bp_mapout()
6612 	 */
6613 	mutex_exit(ST_MUTEX);
6614 	bcount = (unsigned)bp->b_bcount;
6615 	biodone(bp);
6616 	mutex_enter(ST_MUTEX);
6617 	un->un_laststate = un->un_state;
6618 	un->un_state = ST_STATE_OPEN_PENDING_IO;
6619 	kmem_free(un->un_tmpbuf, bcount);
6620 	un->un_tmpbuf = NULL;
6621 }
6622 
6623 /*
6624  * Special command handler
6625  */
6626 
6627 /*
6628  * common st_cmd code. The fourth parameter states
6629  * whether the caller wishes to await the results
6630  * Note the release of the mutex during most of the function
6631  */
6632 static int
6633 st_cmd(dev_t dev, int com, int count, int wait)
6634 {
6635 	struct buf *bp;
6636 	int err;
6637 
6638 	GET_SOFT_STATE(dev);
6639 
6640 	ST_FUNC(ST_DEVINFO, st_cmd);
6641 
6642 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6643 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %x, wait = %d)\n",
6644 	    dev, com, count, wait);
6645 
6646 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6647 	ASSERT(mutex_owned(ST_MUTEX));
6648 
6649 #ifdef STDEBUG
6650 	if ((st_debug & 0xf)) {
6651 		st_debug_cmds(un, com, count, wait);
6652 	}
6653 #endif
6654 
6655 	/* check to see if this command requires the drive to be reserved */
6656 	err = st_check_cmd_for_need_to_reserve(un, com, count);
6657 
6658 	if (err) {
6659 		return (err);
6660 	}
6661 
6662 	while (un->un_sbuf_busy)
6663 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6664 	un->un_sbuf_busy = 1;
6665 
6666 	bp = un->un_sbufp;
6667 	bzero(bp, sizeof (buf_t));
6668 
6669 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
6670 
6671 	/*
6672 	 * Set count to the actual size of the data tranfer.
6673 	 * For commands with no data transfer, set bp->b_bcount
6674 	 * to the value to be used when constructing the
6675 	 * cdb in st_make_cmd().
6676 	 */
6677 	switch (com) {
6678 	case SCMD_READ:
6679 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6680 		    "special read %d\n", count);
6681 		bp->b_flags |= B_READ;
6682 		bp->b_un.b_addr = un->un_tmpbuf;
6683 		break;
6684 
6685 	case SCMD_WRITE:
6686 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6687 		    "special write %d\n", count);
6688 		bp->b_un.b_addr = un->un_tmpbuf;
6689 		break;
6690 
6691 	case SCMD_WRITE_FILE_MARK:
6692 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6693 		    "write %d file marks\n", count);
6694 		bp->b_bcount = count;
6695 		count = 0;
6696 		break;
6697 
6698 	case SCMD_REWIND:
6699 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
6700 		bp->b_bcount = 0;
6701 		count = 0;
6702 		break;
6703 
6704 	case SCMD_SPACE:
6705 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
6706 		/*
6707 		 * XXX The user could have entered a number that will
6708 		 * not fit in the 12 bit count field. Whats new here
6709 		 * checking that. Down the road this should use space(16).
6710 		 */
6711 		if ((SPACE_CNT(count) > 0x7fffff) ||
6712 		    (SPACE_CNT(count) < -(0x7fffff))) {
6713 			un->un_sbuf_busy = 0;
6714 			cv_signal(&un->un_sbuf_cv);
6715 			return (EINVAL);
6716 		}
6717 		bp->b_bcount = count;
6718 		count = 0;
6719 		break;
6720 
6721 	case SCMD_RESERVE:
6722 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
6723 		bp->b_bcount = 0;
6724 		count = 0;
6725 		break;
6726 
6727 	case SCMD_RELEASE:
6728 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
6729 		bp->b_bcount = 0;
6730 		count = 0;
6731 		break;
6732 
6733 	case SCMD_LOAD:
6734 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6735 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
6736 		bp->b_bcount = count;
6737 		count = 0;
6738 		break;
6739 
6740 	case SCMD_ERASE:
6741 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6742 		    "erase tape\n");
6743 		bp->b_bcount = 0;
6744 		count = 0;
6745 		break;
6746 
6747 	case SCMD_MODE_SENSE:
6748 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6749 		    "mode sense\n");
6750 		bp->b_flags |= B_READ;
6751 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
6752 		break;
6753 
6754 	case SCMD_MODE_SELECT:
6755 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6756 		    "mode select\n");
6757 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
6758 		break;
6759 
6760 	case SCMD_READ_BLKLIM:
6761 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6762 		    "read block limits\n");
6763 		bp->b_flags |= B_READ;
6764 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
6765 		break;
6766 
6767 	case SCMD_TEST_UNIT_READY:
6768 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6769 		    "test unit ready\n");
6770 		bp->b_bcount = 0;
6771 		count = 0;
6772 		break;
6773 
6774 	case SCMD_DOORLOCK:
6775 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6776 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
6777 		bp->b_bcount = count = 0;
6778 		break;
6779 
6780 	case SCMD_READ_POSITION:
6781 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6782 		    "read position\n");
6783 		switch (un->un_read_pos_type) {
6784 		case LONG_POS:
6785 			count = sizeof (tape_position_long_t);
6786 			break;
6787 		case EXT_POS:
6788 			count = min(count, sizeof (tape_position_ext_t));
6789 			break;
6790 		case SHORT_POS:
6791 			count = sizeof (tape_position_t);
6792 			break;
6793 		default:
6794 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
6795 			    "Unknown read position type 0x%x in "
6796 			    "st_make_cmd()\n", un->un_read_pos_type);
6797 		}
6798 		bp->b_bcount = count;
6799 		bp->b_flags |= B_READ;
6800 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
6801 		break;
6802 
6803 	default:
6804 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
6805 		    "Unhandled scsi command 0x%x in st_cmd()\n", com);
6806 	}
6807 
6808 	mutex_exit(ST_MUTEX);
6809 
6810 	if (count > 0) {
6811 		/*
6812 		 * We're going to do actual I/O.
6813 		 * Set things up for physio.
6814 		 */
6815 		struct iovec aiov;
6816 		struct uio auio;
6817 		struct uio *uio = &auio;
6818 
6819 		bzero(&auio, sizeof (struct uio));
6820 		bzero(&aiov, sizeof (struct iovec));
6821 		aiov.iov_base = bp->b_un.b_addr;
6822 		aiov.iov_len = count;
6823 
6824 		uio->uio_iov = &aiov;
6825 		uio->uio_iovcnt = 1;
6826 		uio->uio_resid = aiov.iov_len;
6827 		uio->uio_segflg = UIO_SYSSPACE;
6828 
6829 		/*
6830 		 * Let physio do the rest...
6831 		 */
6832 		bp->b_forw = (struct buf *)(uintptr_t)com;
6833 		bp->b_back = NULL;
6834 		err = physio(st_strategy, bp, dev,
6835 		    (bp->b_flags & B_READ) ? B_READ : B_WRITE,
6836 		    st_minphys, uio);
6837 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6838 		    "st_cmd: physio returns %d\n", err);
6839 	} else {
6840 		/*
6841 		 * Mimic physio
6842 		 */
6843 		bp->b_forw = (struct buf *)(uintptr_t)com;
6844 		bp->b_back = NULL;
6845 		bp->b_edev = dev;
6846 		bp->b_dev = cmpdev(dev);
6847 		bp->b_blkno = 0;
6848 		bp->b_resid = 0;
6849 		(void) st_strategy(bp);
6850 		if (!wait) {
6851 			/*
6852 			 * This is an async command- the caller won't wait
6853 			 * and doesn't care about errors.
6854 			 */
6855 			mutex_enter(ST_MUTEX);
6856 			return (0);
6857 		}
6858 
6859 		/*
6860 		 * BugTraq #4260046
6861 		 * ----------------
6862 		 * Restore Solaris 2.5.1 behavior, namely call biowait
6863 		 * unconditionally. The old comment said...
6864 		 *
6865 		 * "if strategy was flagged with  persistent errors, we would
6866 		 *  have an error here, and the bp would never be sent, so we
6867 		 *  don't want to wait on a bp that was never sent...or hang"
6868 		 *
6869 		 * The new rationale, courtesy of Chitrank...
6870 		 *
6871 		 * "we should unconditionally biowait() here because
6872 		 *  st_strategy() will do a biodone() in the persistent error
6873 		 *  case and the following biowait() will return immediately.
6874 		 *  If not, in the case of "errors after pkt alloc" in
6875 		 *  st_start(), we will not biowait here which will cause the
6876 		 *  next biowait() to return immediately which will cause
6877 		 *  us to send out the next command. In the case where both of
6878 		 *  these use the sbuf, when the first command completes we'll
6879 		 *  free the packet attached to sbuf and the same pkt will
6880 		 *  get freed again when we complete the second command.
6881 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
6882 		 *  st_start() for the pkt alloc failure case because physio()
6883 		 *  does biowait() and will hang if we don't do biodone()"
6884 		 */
6885 
6886 		err = biowait(bp);
6887 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6888 		    "st_cmd: biowait returns %d\n", err);
6889 	}
6890 	mutex_enter(ST_MUTEX);
6891 
6892 	un->un_sbuf_busy = 0;
6893 
6894 	/*
6895 	 * If was a space command need to update logical block position.
6896 	 * If the command failed such that positioning is invalid, Don't
6897 	 * update the position as the user must do this to validate the
6898 	 * position for data protection.
6899 	 */
6900 	if ((com == SCMD_SPACE) && (un->un_pos.pmode != invalid)) {
6901 		uchar_t status = un->un_status;
6902 		(void) st_update_block_pos(un);
6903 		un->un_status = status;
6904 	}
6905 
6906 	cv_signal(&un->un_sbuf_cv);
6907 	return (err);
6908 }
6909 
6910 static int
6911 st_set_compression(struct scsi_tape *un)
6912 {
6913 	int rval;
6914 	int turn_compression_on;
6915 	minor_t minor;
6916 
6917 	ST_FUNC(ST_DEVINFO, st_set_compression);
6918 
6919 	/*
6920 	 * Drive either dosn't have compression or it is controlled with
6921 	 * special density codes. Return ENOTTY so caller
6922 	 * knows nothing was done.
6923 	 */
6924 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
6925 		un->un_comp_page = 0;
6926 		return (ENOTTY);
6927 	}
6928 
6929 	/* set compression based on minor node opened */
6930 	minor = MT_DENSITY(un->un_dev);
6931 
6932 	/*
6933 	 * If this the compression density or
6934 	 * the drive has two densities and uses mode select for
6935 	 * control of compression turn on compression for MT_DENSITY2
6936 	 * as well.
6937 	 */
6938 	if ((minor == ST_COMPRESSION_DENSITY) ||
6939 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
6940 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
6941 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
6942 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
6943 
6944 		turn_compression_on = 1;
6945 	} else {
6946 		turn_compression_on = 0;
6947 	}
6948 
6949 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
6950 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
6951 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
6952 
6953 	/*
6954 	 * Need to determine which page does the device use for compression.
6955 	 * First try the data compression page. If this fails try the device
6956 	 * configuration page
6957 	 */
6958 
6959 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
6960 		rval = st_set_datacomp_page(un, turn_compression_on);
6961 		if (rval == EALREADY) {
6962 			return (rval);
6963 		}
6964 		if (rval != 0) {
6965 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
6966 				/*
6967 				 * This device does not support data
6968 				 * compression page
6969 				 */
6970 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
6971 			} else if (un->un_state >= ST_STATE_OPEN) {
6972 				un->un_pos.pmode = invalid;
6973 				rval = EIO;
6974 			} else {
6975 				rval = -1;
6976 			}
6977 		} else {
6978 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
6979 		}
6980 	}
6981 
6982 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
6983 		rval = st_set_devconfig_page(un, turn_compression_on);
6984 		if (rval == EALREADY) {
6985 			return (rval);
6986 		}
6987 		if (rval != 0) {
6988 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
6989 				/*
6990 				 * This device does not support
6991 				 * compression at all advice the
6992 				 * user and unset ST_MODE_SEL_COMP
6993 				 */
6994 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
6995 				un->un_comp_page = 0;
6996 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6997 				    "Device Does Not Support Compression\n");
6998 			} else if (un->un_state >= ST_STATE_OPEN) {
6999 				un->un_pos.pmode = invalid;
7000 				rval = EIO;
7001 			} else {
7002 				rval = -1;
7003 			}
7004 		}
7005 	}
7006 
7007 	return (rval);
7008 }
7009 
7010 /*
7011  * set or unset compression thru device configuration page.
7012  */
7013 static int
7014 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
7015 {
7016 	unsigned char cflag;
7017 	int rval = 0;
7018 
7019 
7020 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
7021 
7022 	ASSERT(mutex_owned(ST_MUTEX));
7023 	/*
7024 	 * Figure what to set compression flag to.
7025 	 */
7026 	if (compression_on) {
7027 		/* They have selected a compression node */
7028 		if (un->un_dp->type == ST_TYPE_FUJI) {
7029 			cflag = 0x84;   /* use EDRC */
7030 		} else {
7031 			cflag = ST_DEV_CONFIG_DEF_COMP;
7032 		}
7033 	} else {
7034 		cflag = ST_DEV_CONFIG_NO_COMP;
7035 	}
7036 
7037 	/*
7038 	 * If compression is already set the way it was requested.
7039 	 * And if this not the first time we has tried.
7040 	 */
7041 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
7042 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7043 		return (EALREADY);
7044 	}
7045 
7046 	un->un_mspl->page.dev.comp_alg = cflag;
7047 	/*
7048 	 * need to send mode select even if correct compression is
7049 	 * already set since need to set density code
7050 	 */
7051 
7052 #ifdef STDEBUG
7053 	if ((st_debug & 0xf) >= 6) {
7054 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7055 		    "st_set_devconfig_page: sense data for mode select",
7056 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7057 	}
7058 #endif
7059 	rval = st_gen_mode_select(un, un->un_mspl, sizeof (struct seq_mode));
7060 
7061 	return (rval);
7062 }
7063 
7064 /*
7065  * set/reset compression bit thru data compression page
7066  */
7067 static int
7068 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
7069 {
7070 	int compression_on_already;
7071 	int rval = 0;
7072 
7073 
7074 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
7075 
7076 	ASSERT(mutex_owned(ST_MUTEX));
7077 	/*
7078 	 * If drive is not capable of compression (at this time)
7079 	 * return EALREADY so caller doesn't think that this page
7080 	 * is not supported. This check is for drives that can
7081 	 * disable compression from the front panel or configuration.
7082 	 * I doubt that a drive that supports this page is not really
7083 	 * capable of compression.
7084 	 */
7085 	if (un->un_mspl->page.comp.dcc == 0) {
7086 		return (EALREADY);
7087 	}
7088 
7089 	/* See if compression currently turned on */
7090 	if (un->un_mspl->page.comp.dce) {
7091 		compression_on_already = 1;
7092 	} else {
7093 		compression_on_already = 0;
7094 	}
7095 
7096 	/*
7097 	 * If compression is already set the way it was requested.
7098 	 * And if this not the first time we has tried.
7099 	 */
7100 	if ((compression_on == compression_on_already) &&
7101 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7102 		return (EALREADY);
7103 	}
7104 
7105 	/*
7106 	 * if we are already set to the appropriate compression
7107 	 * mode, don't set it again
7108 	 */
7109 	if (compression_on) {
7110 		/* compression selected */
7111 		un->un_mspl->page.comp.dce = 1;
7112 	} else {
7113 		un->un_mspl->page.comp.dce = 0;
7114 	}
7115 
7116 
7117 #ifdef STDEBUG
7118 	if ((st_debug & 0xf) >= 6) {
7119 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7120 		    "st_set_datacomp_page: sense data for mode select",
7121 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7122 	}
7123 #endif
7124 	rval = st_gen_mode_select(un, un->un_mspl, sizeof (struct seq_mode));
7125 
7126 	return (rval);
7127 }
7128 
7129 static int
7130 st_modesense(struct scsi_tape *un)
7131 {
7132 	int rval;
7133 	uchar_t page;
7134 
7135 	ST_FUNC(ST_DEVINFO, st_modesense);
7136 
7137 	page = un->un_comp_page;
7138 
7139 	switch (page) {
7140 	case ST_DEV_DATACOMP_PAGE:
7141 	case ST_DEV_CONFIG_PAGE: /* fall through */
7142 		rval = st_gen_mode_sense(un, page, un->un_mspl,
7143 		    sizeof (struct seq_mode));
7144 		break;
7145 
7146 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
7147 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
7148 			page = ST_DEV_DATACOMP_PAGE;
7149 			rval = st_gen_mode_sense(un, page, un->un_mspl,
7150 			    sizeof (struct seq_mode));
7151 			if (rval == 0 && un->un_mspl->page_code == page) {
7152 				un->un_comp_page = page;
7153 				break;
7154 			}
7155 			page = ST_DEV_CONFIG_PAGE;
7156 			rval = st_gen_mode_sense(un, page, un->un_mspl,
7157 			    sizeof (struct seq_mode));
7158 			if (rval == 0 && un->un_mspl->page_code == page) {
7159 				un->un_comp_page = page;
7160 				break;
7161 			}
7162 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
7163 			un->un_comp_page = 0;
7164 		} else {
7165 			un->un_comp_page = 0;
7166 		}
7167 
7168 	default:	/* fall through */
7169 		rval = st_cmd(un->un_dev, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
7170 	}
7171 	return (rval);
7172 }
7173 
7174 static int
7175 st_modeselect(struct scsi_tape *un)
7176 {
7177 	int rval = 0;
7178 	int ix;
7179 
7180 	ST_FUNC(ST_DEVINFO, st_modeselect);
7181 
7182 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7183 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
7184 	    un->un_dev, un->un_mspl->density);
7185 
7186 	ASSERT(mutex_owned(ST_MUTEX));
7187 
7188 	/*
7189 	 * The parameter list should be the same for all of the
7190 	 * cases that follow so set them here
7191 	 *
7192 	 * Try mode select first if if fails set fields manually
7193 	 */
7194 	rval = st_modesense(un);
7195 	if (rval != 0) {
7196 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
7197 		    "st_modeselect: First mode sense failed\n");
7198 		un->un_mspl->bd_len  = 8;
7199 		un->un_mspl->high_nb = 0;
7200 		un->un_mspl->mid_nb  = 0;
7201 		un->un_mspl->low_nb  = 0;
7202 	}
7203 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7204 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7205 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7206 
7207 
7208 	/*
7209 	 * If configured to use a specific density code for a media type.
7210 	 * curdens is previously set by the minor node opened.
7211 	 * If the media type doesn't match the minor node we change it so it
7212 	 * looks like the correct one was opened.
7213 	 */
7214 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
7215 		uchar_t best;
7216 
7217 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
7218 			if (un->un_mspl->media_type ==
7219 			    un->un_dp->mediatype[ix]) {
7220 				best = ix;
7221 				/*
7222 				 * It matches but it might not be the only one.
7223 				 * Use the highest matching media type but not
7224 				 * to exceed the density selected by the open.
7225 				 */
7226 				if (ix < un->un_curdens) {
7227 					continue;
7228 				}
7229 				un->un_curdens = ix;
7230 				break;
7231 			}
7232 		}
7233 		/* If a match was found best will not be 0xff any more */
7234 		if (best < NDENSITIES) {
7235 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
7236 			    "found media 0x%X using density 0x%X\n",
7237 			    un->un_mspl->media_type,
7238 			    un->un_dp->densities[best]);
7239 			un->un_mspl->density = un->un_dp->densities[best];
7240 		} else {
7241 			/* Otherwise set density based on minor node opened */
7242 			un->un_mspl->density =
7243 			    un->un_dp->densities[un->un_curdens];
7244 		}
7245 	} else {
7246 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7247 	}
7248 
7249 	if (un->un_dp->options & ST_NOBUF) {
7250 		un->un_mspl->bufm = 0;
7251 	} else {
7252 		un->un_mspl->bufm = 1;
7253 	}
7254 
7255 	rval = st_set_compression(un);
7256 
7257 	/*
7258 	 * If st_set_compression returned invalid or already it
7259 	 * found no need to do the mode select.
7260 	 * So do it here.
7261 	 */
7262 	if ((rval == ENOTTY) || (rval == EALREADY)) {
7263 
7264 		/* Zero non-writeable fields */
7265 		un->un_mspl->data_len = 0;
7266 		un->un_mspl->media_type = 0;
7267 		un->un_mspl->wp = 0;
7268 
7269 		/* need to set the density code */
7270 		rval = st_cmd(un->un_dev, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
7271 		if (rval != 0) {
7272 			if (un->un_state >= ST_STATE_OPEN) {
7273 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7274 				    "unable to set tape mode\n");
7275 				un->un_pos.pmode = invalid;
7276 				rval = EIO;
7277 			} else {
7278 				rval = -1;
7279 			}
7280 		}
7281 	}
7282 
7283 	/*
7284 	 * The spec recommends to send a mode sense after a mode select
7285 	 */
7286 	(void) st_modesense(un);
7287 
7288 	ASSERT(mutex_owned(ST_MUTEX));
7289 
7290 	return (rval);
7291 }
7292 
7293 /*
7294  * st_gen_mode_sense
7295  *
7296  * generic mode sense.. it allows for any page
7297  */
7298 static int
7299 st_gen_mode_sense(struct scsi_tape *un, int page, struct seq_mode *page_data,
7300     int page_size)
7301 {
7302 
7303 	int r;
7304 	char	cdb[CDB_GROUP0];
7305 	struct uscsi_cmd *com;
7306 
7307 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
7308 
7309 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7310 
7311 	bzero(cdb, CDB_GROUP0);
7312 	cdb[0] = SCMD_MODE_SENSE;
7313 	cdb[2] = (char)page;
7314 	cdb[4] = (char)page_size;
7315 
7316 	com->uscsi_cdb = cdb;
7317 	com->uscsi_cdblen = CDB_GROUP0;
7318 	com->uscsi_bufaddr = (caddr_t)page_data;
7319 	com->uscsi_buflen = page_size;
7320 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7321 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
7322 
7323 	r = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
7324 	kmem_free(com, sizeof (*com));
7325 	return (r);
7326 }
7327 
7328 /*
7329  * st_gen_mode_select
7330  *
7331  * generic mode select.. it allows for any page
7332  */
7333 static int
7334 st_gen_mode_select(struct scsi_tape *un, struct seq_mode *page_data,
7335     int page_size)
7336 {
7337 
7338 	int r;
7339 	char cdb[CDB_GROUP0];
7340 	struct uscsi_cmd *com;
7341 
7342 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
7343 
7344 	/* Zero non-writeable fields */
7345 	page_data->data_len = 0;
7346 	page_data->media_type = 0;
7347 	page_data->wp = 0;
7348 
7349 	/*
7350 	 * If mode select has any page data, zero the ps (Page Savable) bit.
7351 	 */
7352 	if (page_size > MSIZE) {
7353 		page_data->ps = 0;
7354 	}
7355 
7356 
7357 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7358 
7359 	/*
7360 	 * then, do a mode select to set what ever info
7361 	 */
7362 	bzero(cdb, CDB_GROUP0);
7363 	cdb[0] = SCMD_MODE_SELECT;
7364 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
7365 	cdb[4] = (char)page_size;
7366 
7367 	com->uscsi_cdb = cdb;
7368 	com->uscsi_cdblen = CDB_GROUP0;
7369 	com->uscsi_bufaddr = (caddr_t)page_data;
7370 	com->uscsi_buflen = page_size;
7371 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7372 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_WRITE;
7373 
7374 	r = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
7375 
7376 	kmem_free(com, sizeof (*com));
7377 	return (r);
7378 }
7379 
7380 /*
7381  * Changes devices blocksize and bsize to requested blocksize nblksz.
7382  * Returns returned value from first failed call or zero on success.
7383  */
7384 static int
7385 st_change_block_size(dev_t dev, uint32_t nblksz)
7386 {
7387 	struct seq_mode *current;
7388 	int rval;
7389 	uint32_t oldblksz;
7390 
7391 	GET_SOFT_STATE(dev);
7392 
7393 	ST_FUNC(ST_DEVINFO, st_change_block_size);
7394 
7395 	current = kmem_zalloc(MSIZE, KM_SLEEP);
7396 
7397 	/* Read current settings */
7398 	rval = st_gen_mode_sense(un, 0, current, MSIZE);
7399 	if (rval != 0) {
7400 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7401 		    "mode sense for change block size failed: rval = %d", rval);
7402 		goto finish;
7403 	}
7404 
7405 	/* Figure the current block size */
7406 	oldblksz =
7407 	    (current->high_bl << 16) |
7408 	    (current->mid_bl << 8) |
7409 	    (current->low_bl);
7410 
7411 	/* If current block size is the same as requested were done */
7412 	if (oldblksz == nblksz) {
7413 		un->un_bsize = nblksz;
7414 		rval = 0;
7415 		goto finish;
7416 	}
7417 
7418 	/* Change to requested block size */
7419 	current->high_bl = (uchar_t)(nblksz >> 16);
7420 	current->mid_bl  = (uchar_t)(nblksz >> 8);
7421 	current->low_bl  = (uchar_t)(nblksz);
7422 
7423 	/* Attempt to change block size */
7424 	rval = st_gen_mode_select(un, current, MSIZE);
7425 	if (rval != 0) {
7426 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7427 		    "Set new block size failed: rval = %d", rval);
7428 		goto finish;
7429 	}
7430 
7431 	/* Read back and verify setting */
7432 	rval = st_modesense(un);
7433 	if (rval == 0) {
7434 		un->un_bsize =
7435 		    (un->un_mspl->high_bl << 16) |
7436 		    (un->un_mspl->mid_bl << 8) |
7437 		    (un->un_mspl->low_bl);
7438 
7439 		if (un->un_bsize != nblksz) {
7440 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7441 			    "Blocksize set does not equal requested blocksize"
7442 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
7443 			rval = EIO;
7444 		}
7445 	}
7446 finish:
7447 	kmem_free(current, MSIZE);
7448 	return (rval);
7449 }
7450 
7451 
7452 static void
7453 st_init(struct scsi_tape *un)
7454 {
7455 	ST_FUNC(ST_DEVINFO, st_init);
7456 
7457 	ASSERT(mutex_owned(ST_MUTEX));
7458 
7459 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7460 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
7461 	    un->un_dev);
7462 
7463 	un->un_pos.blkno = 0;
7464 	un->un_pos.fileno = 0;
7465 	un->un_lastop = ST_OP_NIL;
7466 	un->un_pos.eof = ST_NO_EOF;
7467 	un->un_pwr_mgmt = ST_PWR_NORMAL;
7468 	if (st_error_level != SCSI_ERR_ALL) {
7469 		if (DEBUGGING) {
7470 			st_error_level = SCSI_ERR_ALL;
7471 		} else {
7472 			st_error_level = SCSI_ERR_RETRYABLE;
7473 		}
7474 	}
7475 }
7476 
7477 
7478 static void
7479 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
7480 {
7481 	struct scsi_pkt *pkt;
7482 	struct uscsi_cmd *ucmd;
7483 	int count, tval = 0;
7484 	uint_t addr = 0;
7485 	int flags = 0;
7486 	int cdb_len = CDB_GROUP0; /* default */
7487 	uchar_t com;
7488 	char fixbit;
7489 
7490 	ST_FUNC(ST_DEVINFO, st_make_cmd);
7491 
7492 	ASSERT(mutex_owned(ST_MUTEX));
7493 
7494 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7495 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
7496 
7497 
7498 	/*
7499 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
7500 	 * Length Indicator bits on read/write commands, for setting
7501 	 * the Long bit on erase commands, and for setting the Code
7502 	 * Field bits on space commands.
7503 	 * XXX why do we set lastop here?
7504 	 */
7505 
7506 	if (bp != un->un_sbufp) {		/* regular raw I/O */
7507 		int stat_size = (un->un_arq_enabled ?
7508 		    sizeof (struct scsi_arq_status) : 1);
7509 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
7510 		    CDB_GROUP0, stat_size, 0, 0, func, (caddr_t)un);
7511 		if (pkt == NULL) {
7512 			goto exit;
7513 		}
7514 		SET_BP_PKT(bp, pkt);
7515 		if (un->un_bsize == 0) {
7516 			count = bp->b_bcount;
7517 			fixbit = 0;
7518 		} else {
7519 			count = bp->b_bcount / un->un_bsize;
7520 			fixbit = 1;
7521 		}
7522 		if (bp->b_flags & B_READ) {
7523 			com = SCMD_READ;
7524 			un->un_lastop = ST_OP_READ;
7525 			if ((un->un_bsize == 0) && /* Not Fixed Block */
7526 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
7527 				fixbit = 2;
7528 			}
7529 		} else {
7530 			com = SCMD_WRITE;
7531 			un->un_lastop = ST_OP_WRITE;
7532 		}
7533 
7534 		tval = un->un_dp->io_timeout;
7535 
7536 		/*
7537 		 * For really large xfers, increase timeout
7538 		 */
7539 		if (bp->b_bcount > (10 * ONE_MEG))
7540 			tval *= bp->b_bcount/(10 * ONE_MEG);
7541 
7542 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7543 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
7544 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
7545 
7546 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
7547 		/*
7548 		 * uscsi - build command, allocate scsi resources
7549 		 */
7550 		st_make_uscsi_cmd(un, ucmd, bp, func);
7551 		goto exit;
7552 
7553 	} else {				/* special I/O */
7554 		int stat_size = (un->un_arq_enabled ?
7555 		    sizeof (struct scsi_arq_status) : 1);
7556 		struct buf *allocbp = NULL;
7557 		com = (uchar_t)(uintptr_t)bp->b_forw;
7558 		count = bp->b_bcount;
7559 
7560 		switch (com) {
7561 		case SCMD_READ:
7562 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7563 			    "special read %d\n", count);
7564 			if (un->un_bsize == 0) {
7565 				fixbit = 2;	/* suppress SILI */
7566 			} else {
7567 				fixbit = 1;	/* Fixed Block Mode */
7568 				count /= un->un_bsize;
7569 			}
7570 			allocbp = bp;
7571 			un->un_lastop = ST_OP_READ;
7572 			tval = un->un_dp->io_timeout;
7573 			break;
7574 
7575 		case SCMD_WRITE:
7576 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7577 			    "special write %d\n", count);
7578 			if (un->un_bsize != 0) {
7579 				fixbit = 1;	/* Fixed Block Mode */
7580 				count /= un->un_bsize;
7581 			} else {
7582 				fixbit = 0;
7583 			}
7584 			allocbp = bp;
7585 			un->un_lastop = ST_OP_WRITE;
7586 			tval = un->un_dp->io_timeout;
7587 			break;
7588 
7589 		case SCMD_WRITE_FILE_MARK:
7590 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7591 			    "write %d file marks\n", count);
7592 			un->un_lastop = ST_OP_WEOF;
7593 			fixbit = 0;
7594 			tval = un->un_dp->io_timeout;
7595 			break;
7596 
7597 		case SCMD_REWIND:
7598 			if (bp->b_flags & B_ASYNC) {
7599 				fixbit = 1;
7600 			} else {
7601 				fixbit = 0;
7602 			}
7603 			count = 0;
7604 			un->un_lastop = ST_OP_CTL;
7605 			tval = un->un_dp->rewind_timeout;
7606 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7607 			    "rewind\n");
7608 			break;
7609 
7610 		case SCMD_SPACE:
7611 			fixbit = SPACE_TYPE(count);
7612 			count = (int)SPACE_CNT(count);
7613 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7614 			    "space %s %d from file %d blk %d\n",
7615 			    space_strs[fixbit & 7], count,
7616 			    un->un_pos.fileno, un->un_pos.blkno);
7617 			un->un_lastop = ST_OP_CTL;
7618 			tval = un->un_dp->space_timeout;
7619 			break;
7620 
7621 		case SCMD_LOAD:
7622 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7623 			    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7624 			fixbit = 0;
7625 
7626 			/* Loading or Unloading */
7627 			if (count & LD_LOAD) {
7628 				tval = un->un_dp->load_timeout;
7629 			} else {
7630 				tval = un->un_dp->unload_timeout;
7631 			}
7632 			/* Is Retension requested */
7633 			if (count & LD_RETEN) {
7634 				tval += un->un_dp->rewind_timeout;
7635 			}
7636 			un->un_lastop = ST_OP_CTL;
7637 			break;
7638 
7639 		case SCMD_ERASE:
7640 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7641 			    "erase tape\n");
7642 			count = 0;
7643 			/*
7644 			 * We support long erase only
7645 			 */
7646 			fixbit = 1;
7647 			tval = un->un_dp->erase_timeout;
7648 			un->un_lastop = ST_OP_CTL;
7649 			break;
7650 
7651 		case SCMD_MODE_SENSE:
7652 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7653 			    "mode sense\n");
7654 			allocbp = bp;
7655 			fixbit = 0;
7656 			tval = un->un_dp->non_motion_timeout;
7657 			un->un_lastop = ST_OP_CTL;
7658 			break;
7659 
7660 		case SCMD_MODE_SELECT:
7661 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7662 			    "mode select\n");
7663 			allocbp = bp;
7664 			fixbit = 0;
7665 			tval = un->un_dp->non_motion_timeout;
7666 			un->un_lastop = ST_OP_CTL;
7667 			break;
7668 
7669 		case SCMD_RESERVE:
7670 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7671 			    "reserve\n");
7672 			fixbit = 0;
7673 			tval = un->un_dp->non_motion_timeout;
7674 			un->un_lastop = ST_OP_CTL;
7675 			break;
7676 
7677 		case SCMD_RELEASE:
7678 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7679 			    "release\n");
7680 			fixbit = 0;
7681 			tval = un->un_dp->non_motion_timeout;
7682 			un->un_lastop = ST_OP_CTL;
7683 			break;
7684 
7685 		case SCMD_READ_BLKLIM:
7686 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7687 			    "read block limits\n");
7688 			allocbp = bp;
7689 			fixbit = count = 0;
7690 			tval = un->un_dp->non_motion_timeout;
7691 			un->un_lastop = ST_OP_CTL;
7692 			break;
7693 
7694 		case SCMD_TEST_UNIT_READY:
7695 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7696 			    "test unit ready\n");
7697 			fixbit = 0;
7698 			tval = un->un_dp->non_motion_timeout;
7699 			un->un_lastop = ST_OP_CTL;
7700 			break;
7701 
7702 		case SCMD_DOORLOCK:
7703 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7704 			    "prevent/allow media removal\n");
7705 			fixbit = 0;
7706 			tval = un->un_dp->non_motion_timeout;
7707 			un->un_lastop = ST_OP_CTL;
7708 			break;
7709 
7710 		case SCMD_READ_POSITION:
7711 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7712 			    "read position\n");
7713 			fixbit = un->un_read_pos_type;
7714 			cdb_len = CDB_GROUP1;
7715 			tval = un->un_dp->non_motion_timeout;
7716 			allocbp = bp;
7717 			un->un_lastop = ST_OP_CTL;
7718 			switch (un->un_read_pos_type) {
7719 			case LONG_POS:
7720 				count = 0;
7721 				break;
7722 			case EXT_POS:
7723 				count = sizeof (tape_position_ext_t);
7724 				break;
7725 			case SHORT_POS:
7726 				count = 0;
7727 				break;
7728 			default:
7729 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7730 				    "Unknown read position type 0x%x in "
7731 				    " st_make_cmd()\n", un->un_read_pos_type);
7732 			}
7733 			break;
7734 
7735 		default:
7736 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7737 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
7738 			    com);
7739 		}
7740 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
7741 		    0, 0, func, (caddr_t)un);
7742 		if (pkt == NULL) {
7743 			goto exit;
7744 		}
7745 		if (allocbp) {
7746 			ASSERT(geterror(allocbp) == 0);
7747 		}
7748 
7749 	}
7750 
7751 
7752 	(void) scsi_setup_cdb((union scsi_cdb *)pkt->pkt_cdbp,
7753 	    com, addr, (uint_t)count, 0);
7754 	FILL_SCSI1_LUN(un->un_sd, pkt);
7755 	/*
7756 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
7757 	 */
7758 	((union scsi_cdb *)(pkt->pkt_cdbp))->t_code = fixbit;
7759 	pkt->pkt_flags = flags;
7760 
7761 #ifdef STDEBUG
7762 	if ((st_debug & 0xf) >= 6) {
7763 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7764 		    "cmd cdb", (char *)pkt->pkt_cdbp, cdb_len);
7765 	}
7766 #endif
7767 
7768 	/*
7769 	 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
7770 	 * device, set the Vendor Unique bit to
7771 	 * write Short File Mark.
7772 	 */
7773 	if (com == SCMD_WRITE_FILE_MARK &&
7774 	    un->un_dp->options & ST_SHORT_FILEMARKS) {
7775 		switch (un->un_dp->type) {
7776 		case ST_TYPE_EXB8500:
7777 		case ST_TYPE_EXABYTE:
7778 			/*
7779 			 * Now the Vendor Unique bit 7 in Byte 5 of CDB
7780 			 * is set to to write Short File Mark
7781 			 */
7782 			((union scsi_cdb *)pkt->pkt_cdbp)->g0_vu_1 = 1;
7783 			break;
7784 
7785 		default:
7786 			/*
7787 			 * Well, if ST_SHORT_FILEMARKS is set for other
7788 			 * tape drives, it is just ignored
7789 			 */
7790 			break;
7791 		}
7792 	}
7793 	ASSERT(tval);
7794 	pkt->pkt_time = tval;
7795 	pkt->pkt_comp = st_intr;
7796 	pkt->pkt_private = (opaque_t)bp;
7797 
7798 	SET_BP_PKT(bp, pkt);
7799 
7800 exit:
7801 	ASSERT(mutex_owned(ST_MUTEX));
7802 }
7803 
7804 
7805 /*
7806  * Build a command based on a uscsi command;
7807  */
7808 static void
7809 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
7810     struct buf *bp, int (*func)(caddr_t))
7811 {
7812 	struct scsi_pkt *pkt;
7813 	caddr_t cdb;
7814 	int	cdblen;
7815 	int	stat_size = 1;
7816 	int	flags = 0;
7817 
7818 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
7819 
7820 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7821 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
7822 
7823 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
7824 		if (un->un_arq_enabled) {
7825 			if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
7826 				stat_size = (int)(ucmd->uscsi_rqlen) +
7827 				    sizeof (struct scsi_arq_status) -
7828 				    sizeof (struct scsi_extended_sense);
7829 				flags = PKT_XARQ;
7830 			} else {
7831 				stat_size = sizeof (struct scsi_arq_status);
7832 			}
7833 		}
7834 	}
7835 
7836 	ASSERT(mutex_owned(ST_MUTEX));
7837 
7838 	cdb = ucmd->uscsi_cdb;
7839 	cdblen = ucmd->uscsi_cdblen;
7840 
7841 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7842 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
7843 	    ucmd->uscsi_buflen, bp->b_bcount);
7844 	pkt = scsi_init_pkt(ROUTE, NULL,
7845 	    (bp->b_bcount > 0) ? bp : NULL,
7846 	    cdblen, stat_size, 0, flags, func, (caddr_t)un);
7847 	if (pkt == NULL) {
7848 		goto exit;
7849 	}
7850 
7851 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
7852 
7853 #ifdef STDEBUG
7854 	if ((st_debug & 0xf) >= 6) {
7855 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7856 		    "pkt_cdbp", (char *)cdb, cdblen);
7857 	}
7858 #endif
7859 
7860 	if (ucmd->uscsi_flags & USCSI_SILENT) {
7861 		pkt->pkt_flags |= FLAG_SILENT;
7862 	}
7863 
7864 	pkt->pkt_time = ucmd->uscsi_timeout;
7865 	pkt->pkt_comp = st_intr;
7866 	pkt->pkt_private = (opaque_t)bp;
7867 
7868 	SET_BP_PKT(bp, pkt);
7869 exit:
7870 	ASSERT(mutex_owned(ST_MUTEX));
7871 }
7872 
7873 
7874 /*
7875  * restart cmd currently at the head of the runq
7876  *
7877  * If scsi_transport() succeeds or the retries
7878  * count exhausted, restore the throttle that was
7879  * zeroed out in st_handle_intr_busy().
7880  *
7881  */
7882 static void
7883 st_intr_restart(void *arg)
7884 {
7885 	struct scsi_tape *un = arg;
7886 	struct buf *bp;
7887 	int status = TRAN_ACCEPT;
7888 
7889 	mutex_enter(ST_MUTEX);
7890 
7891 	ST_FUNC(ST_DEVINFO, st_intr_restart);
7892 
7893 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7894 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
7895 
7896 	un->un_hib_tid = 0;
7897 
7898 	/*
7899 	 * move from waitq to runq, if there is anything on the waitq
7900 	 */
7901 	if ((bp = un->un_quef) == NULL) {
7902 		mutex_exit(ST_MUTEX);
7903 		return;
7904 	}
7905 
7906 	/*
7907 	 * Here we know :
7908 	 *	throttle = 0, via st_handle_intr_busy
7909 	 */
7910 
7911 	if (un->un_quel == bp) {
7912 		un->un_quel = NULL;
7913 		un->un_quef = NULL;	/* we know it's the first one */
7914 	} else {
7915 		un->un_quef = bp->b_actf;
7916 	}
7917 	bp->b_actf = NULL;
7918 
7919 	if (un->un_runqf) {
7920 		/*
7921 		 * not good, we don't want to requeue something after
7922 		 * another.
7923 		 */
7924 		mutex_exit(ST_MUTEX);
7925 		goto done_error;
7926 	} else {
7927 		un->un_runqf = bp;
7928 		un->un_runql = bp;
7929 	}
7930 
7931 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
7932 
7933 	mutex_exit(ST_MUTEX);
7934 
7935 	status = scsi_transport(BP_PKT(bp));
7936 
7937 	mutex_enter(ST_MUTEX);
7938 
7939 	if (status != TRAN_ACCEPT) {
7940 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
7941 		mutex_exit(ST_MUTEX);
7942 
7943 		if (status == TRAN_BUSY) {
7944 			if (st_handle_intr_busy(un, bp,
7945 			    ST_TRAN_BUSY_TIMEOUT) == 0)
7946 				return;	/* timeout is setup again */
7947 		}
7948 
7949 	} else {
7950 		un->un_tran_retry_ct = 0;
7951 		if (un->un_last_throttle) {
7952 			un->un_throttle = un->un_last_throttle;
7953 		}
7954 		mutex_exit(ST_MUTEX);
7955 		return;
7956 	}
7957 
7958 done_error:
7959 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7960 	    "restart transport rejected\n");
7961 	bp->b_resid = bp->b_bcount;
7962 
7963 #ifndef __lock_lint
7964 	/*
7965 	 * warlock doesn't understand this potential
7966 	 * recursion?
7967 	 */
7968 	mutex_enter(ST_MUTEX);
7969 	if (un->un_last_throttle) {
7970 		un->un_throttle = un->un_last_throttle;
7971 	}
7972 	if (status != TRAN_ACCEPT)
7973 		ST_DO_ERRSTATS(un, st_transerrs);
7974 	ST_DO_KSTATS(bp, kstat_waitq_exit);
7975 	SET_PE_FLAG(un);
7976 	st_bioerror(bp, EIO);
7977 	st_done_and_mutex_exit(un, bp);
7978 #endif
7979 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7980 	    "busy restart aborted\n");
7981 }
7982 
7983 /*
7984  * st_check_media():
7985  * Periodically check the media state using scsi_watch service;
7986  * this service calls back after TUR and possibly request sense
7987  * the callback handler (st_media_watch_cb()) decodes the request sense
7988  * data (if any)
7989  */
7990 
7991 static int
7992 st_check_media(dev_t dev, enum mtio_state state)
7993 {
7994 	int rval = 0;
7995 	enum mtio_state	prev_state;
7996 	opaque_t token = NULL;
7997 
7998 	GET_SOFT_STATE(dev);
7999 
8000 	ST_FUNC(ST_DEVINFO, st_check_media);
8001 
8002 	mutex_enter(ST_MUTEX);
8003 
8004 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8005 	    "st_check_media:state=%x, mediastate=%x\n",
8006 	    state, un->un_mediastate);
8007 
8008 	prev_state = un->un_mediastate;
8009 
8010 	/*
8011 	 * is there anything to do?
8012 	 */
8013 retry:
8014 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
8015 		/*
8016 		 * submit the request to the scsi_watch service;
8017 		 * scsi_media_watch_cb() does the real work
8018 		 */
8019 		mutex_exit(ST_MUTEX);
8020 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
8021 		    st_check_media_time, SENSE_LENGTH,
8022 		    st_media_watch_cb, (caddr_t)dev);
8023 		if (token == NULL) {
8024 			rval = EAGAIN;
8025 			goto done;
8026 		}
8027 		mutex_enter(ST_MUTEX);
8028 
8029 		un->un_swr_token = token;
8030 		un->un_specified_mediastate = state;
8031 
8032 		/*
8033 		 * now wait for media change
8034 		 * we will not be signalled unless mediastate == state but it
8035 		 * still better to test for this condition, since there
8036 		 * is a 5 sec cv_broadcast delay when
8037 		 *  mediastate == MTIO_INSERTED
8038 		 */
8039 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8040 		    "st_check_media:waiting for media state change\n");
8041 		while (un->un_mediastate == state) {
8042 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
8043 				mutex_exit(ST_MUTEX);
8044 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8045 				    "st_check_media:waiting for media state "
8046 				    "was interrupted\n");
8047 				rval = EINTR;
8048 				goto done;
8049 			}
8050 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8051 			    "st_check_media:received signal, state=%x\n",
8052 			    un->un_mediastate);
8053 		}
8054 	}
8055 
8056 	/*
8057 	 * if we transitioned to MTIO_INSERTED, media has really been
8058 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
8059 	 * Reset and retry the state change.  If everything is ok, replay
8060 	 * the open() logic.
8061 	 */
8062 	if ((un->un_mediastate == MTIO_INSERTED) &&
8063 	    (un->un_state == ST_STATE_OFFLINE)) {
8064 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8065 		    "st_check_media: calling st_cmd to confirm inserted\n");
8066 
8067 		/*
8068 		 * set this early so that TUR will make it through strategy
8069 		 * without triggering a st_tape_init().  We needed it set
8070 		 * before calling st_tape_init() ourselves anyway.  If TUR
8071 		 * fails, set it back
8072 		 */
8073 		un->un_state = ST_STATE_INITIALIZING;
8074 
8075 		/*
8076 		 * If not reserved fail as getting reservation conflict
8077 		 * will make this hang forever.
8078 		 */
8079 		if ((un->un_rsvd_status &
8080 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
8081 			mutex_exit(ST_MUTEX);
8082 			rval = EACCES;
8083 			goto done;
8084 		}
8085 		rval = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
8086 		if (rval == EACCES) {
8087 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8088 			    "st_check_media: TUR got Reservation Conflict\n");
8089 			mutex_exit(ST_MUTEX);
8090 			goto done;
8091 		}
8092 		if (rval) {
8093 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8094 			    "st_check_media: TUR failed, going to retry\n");
8095 			un->un_mediastate = prev_state;
8096 			un->un_state = ST_STATE_OFFLINE;
8097 			goto retry;
8098 		}
8099 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8100 		    "st_check_media: media inserted\n");
8101 
8102 		/* this also rewinds the tape */
8103 		rval = st_tape_init(dev);
8104 		if (rval != 0) {
8105 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8106 			    "st_check_media : OFFLINE init failure ");
8107 			un->un_state = ST_STATE_OFFLINE;
8108 			un->un_pos.pmode = invalid;
8109 		} else {
8110 			un->un_state = ST_STATE_OPEN_PENDING_IO;
8111 			un->un_pos.fileno = 0;
8112 			un->un_pos.blkno = 0;
8113 			un->un_pos.lgclblkno = 0;
8114 		}
8115 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
8116 	    (un->un_state != ST_STATE_OFFLINE)) {
8117 		/*
8118 		 * supported devices must be rewound before ejection
8119 		 * rewind resets fileno & blkno
8120 		 */
8121 		un->un_laststate = un->un_state;
8122 		un->un_state = ST_STATE_OFFLINE;
8123 	}
8124 	mutex_exit(ST_MUTEX);
8125 done:
8126 	if (token) {
8127 		(void) scsi_watch_request_terminate(token,
8128 		    SCSI_WATCH_TERMINATE_WAIT);
8129 		mutex_enter(ST_MUTEX);
8130 		un->un_swr_token = (opaque_t)NULL;
8131 		mutex_exit(ST_MUTEX);
8132 	}
8133 
8134 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
8135 
8136 	return (rval);
8137 }
8138 
8139 /*
8140  * st_media_watch_cb() is called by scsi_watch_thread for
8141  * verifying the request sense data (if any)
8142  */
8143 static int
8144 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
8145 {
8146 	struct scsi_status *statusp = resultp->statusp;
8147 	struct scsi_extended_sense *sensep = resultp->sensep;
8148 	uchar_t actual_sense_length = resultp->actual_sense_length;
8149 	struct scsi_tape *un;
8150 	enum mtio_state state = MTIO_NONE;
8151 	int instance;
8152 	dev_t dev = (dev_t)arg;
8153 
8154 	instance = MTUNIT(dev);
8155 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
8156 		return (-1);
8157 	}
8158 
8159 	mutex_enter(ST_MUTEX);
8160 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
8161 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8162 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
8163 	    *((char *)statusp), (void *)sensep,
8164 	    actual_sense_length);
8165 
8166 
8167 	/*
8168 	 * if there was a check condition then sensep points to valid
8169 	 * sense data
8170 	 * if status was not a check condition but a reservation or busy
8171 	 * status then the new state is MTIO_NONE
8172 	 */
8173 	if (sensep) {
8174 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8175 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
8176 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
8177 
8178 		switch (un->un_dp->type) {
8179 		default:
8180 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8181 			    "st_media_watch_cb: unknown drive type %d, "
8182 			    "default to ST_TYPE_HP\n", un->un_dp->type);
8183 		/* FALLTHROUGH */
8184 
8185 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
8186 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
8187 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
8188 			if (un->un_dp->type == ST_TYPE_FUJI) {
8189 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8190 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
8191 			} else {
8192 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8193 				    "st_media_watch_cb: ST_TYPE_HP\n");
8194 			}
8195 			switch (sensep->es_key) {
8196 			case KEY_UNIT_ATTENTION:
8197 				/* not ready to ready transition */
8198 				/* hp/es_qual_code == 80 on>off>on */
8199 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
8200 				if (sensep->es_add_code == 0x28) {
8201 					state = MTIO_INSERTED;
8202 				}
8203 				break;
8204 			case KEY_NOT_READY:
8205 				/* in process, rewinding or loading */
8206 				if ((sensep->es_add_code == 0x04) &&
8207 				    (sensep->es_qual_code == 0x00)) {
8208 					state = MTIO_EJECTED;
8209 				}
8210 				break;
8211 			}
8212 			break;
8213 
8214 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
8215 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8216 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
8217 			switch (sensep->es_key) {
8218 			case KEY_UNIT_ATTENTION:
8219 				/* operator medium removal request */
8220 				if ((sensep->es_add_code == 0x5a) &&
8221 				    (sensep->es_qual_code == 0x01)) {
8222 					state = MTIO_EJECTED;
8223 				/* not ready to ready transition */
8224 				} else if ((sensep->es_add_code == 0x28) &&
8225 				    (sensep->es_qual_code == 0x00)) {
8226 					state = MTIO_INSERTED;
8227 				}
8228 				break;
8229 			case KEY_NOT_READY:
8230 				/* medium not present */
8231 				if (sensep->es_add_code == 0x3a) {
8232 					state = MTIO_EJECTED;
8233 				}
8234 				break;
8235 			}
8236 			break;
8237 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
8238 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8239 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
8240 			switch (sensep->es_key) {
8241 			case KEY_NOT_READY:
8242 				if ((sensep->es_add_code == 0x04) &&
8243 				    (sensep->es_qual_code == 0x00)) {
8244 					/* volume not mounted? */
8245 					state = MTIO_EJECTED;
8246 				} else if (sensep->es_add_code == 0x3a) {
8247 					state = MTIO_EJECTED;
8248 				}
8249 				break;
8250 			case KEY_UNIT_ATTENTION:
8251 				state = MTIO_EJECTED;
8252 				break;
8253 			}
8254 			break;
8255 
8256 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
8257 			switch (sensep->es_key) {
8258 			case KEY_UNIT_ATTENTION:
8259 				if (sensep->es_add_code == 0x28) {
8260 					state = MTIO_INSERTED;
8261 				}
8262 				break;
8263 			case KEY_NOT_READY:
8264 				if (sensep->es_add_code == 0x04) {
8265 					/* in transition but could be either */
8266 					state = un->un_specified_mediastate;
8267 				} else if ((sensep->es_add_code == 0x3a) &&
8268 				    (sensep->es_qual_code == 0x00)) {
8269 					state = MTIO_EJECTED;
8270 				}
8271 				break;
8272 			}
8273 			break;
8274 		}
8275 	} else if (*((char *)statusp) == STATUS_GOOD) {
8276 		state = MTIO_INSERTED;
8277 	}
8278 
8279 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8280 	    "st_media_watch_cb:state=%x, specified=%x\n",
8281 	    state, un->un_specified_mediastate);
8282 
8283 	/*
8284 	 * now signal the waiting thread if this is *not* the specified state;
8285 	 * delay the signal if the state is MTIO_INSERTED
8286 	 * to allow the target to recover
8287 	 */
8288 	if (state != un->un_specified_mediastate) {
8289 		un->un_mediastate = state;
8290 		if (state == MTIO_INSERTED) {
8291 			/*
8292 			 * delay the signal to give the drive a chance
8293 			 * to do what it apparently needs to do
8294 			 */
8295 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8296 			    "st_media_watch_cb:delayed cv_broadcast\n");
8297 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
8298 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
8299 		} else {
8300 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8301 			    "st_media_watch_cb:immediate cv_broadcast\n");
8302 			cv_broadcast(&un->un_state_cv);
8303 		}
8304 	}
8305 	mutex_exit(ST_MUTEX);
8306 	return (0);
8307 }
8308 
8309 /*
8310  * delayed cv_broadcast to allow for target to recover
8311  * from media insertion
8312  */
8313 static void
8314 st_delayed_cv_broadcast(void *arg)
8315 {
8316 	struct scsi_tape *un = arg;
8317 
8318 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
8319 
8320 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8321 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
8322 
8323 	mutex_enter(ST_MUTEX);
8324 	cv_broadcast(&un->un_state_cv);
8325 	mutex_exit(ST_MUTEX);
8326 }
8327 
8328 /*
8329  * restart cmd currently at the start of the waitq
8330  */
8331 static void
8332 st_start_restart(void *arg)
8333 {
8334 	struct scsi_tape *un = arg;
8335 
8336 	ST_FUNC(ST_DEVINFO, st_start_restart);
8337 
8338 	ASSERT(un != NULL);
8339 
8340 	mutex_enter(ST_MUTEX);
8341 
8342 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8343 	    "st_tran_restart()\n");
8344 
8345 	if (un->un_quef) {
8346 		st_start(un);
8347 	}
8348 
8349 	mutex_exit(ST_MUTEX);
8350 }
8351 
8352 
8353 /*
8354  * Command completion processing
8355  *
8356  */
8357 static void
8358 st_intr(struct scsi_pkt *pkt)
8359 {
8360 	struct scsi_tape *un;
8361 	struct buf *last_runqf;
8362 	struct buf *bp;
8363 	int action = COMMAND_DONE;
8364 	clock_t	timout;
8365 	int	status;
8366 
8367 
8368 	bp = pkt->pkt_private;
8369 
8370 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
8371 
8372 	ST_FUNC(ST_DEVINFO, st_intr);
8373 
8374 	mutex_enter(ST_MUTEX);
8375 
8376 	un->un_rqs_state &= ~(ST_RQS_ERROR);
8377 
8378 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
8379 
8380 	if (pkt->pkt_reason != CMD_CMPLT) {
8381 
8382 		/* If device has gone away not much else to do */
8383 		if (pkt->pkt_reason == CMD_DEV_GONE) {
8384 			action = COMMAND_DONE_ERROR;
8385 		} else if (un->un_state == ST_STATE_SENSING) {
8386 			ST_DO_ERRSTATS(un, st_transerrs);
8387 			action = COMMAND_DONE_ERROR;
8388 		} else {
8389 			action = st_handle_incomplete(un, bp);
8390 		}
8391 	/*
8392 	 * At this point we know that the command was successfully
8393 	 * completed. Now what?
8394 	 */
8395 	} else if (un->un_arq_enabled &&
8396 	    (pkt->pkt_state & STATE_ARQ_DONE)) {
8397 		/*
8398 		 * the transport layer successfully completed an autorqsense
8399 		 */
8400 		action = st_handle_autosense(un, bp);
8401 
8402 	} else if (un->un_state == ST_STATE_SENSING) {
8403 		/*
8404 		 * okay. We were running a REQUEST SENSE. Find
8405 		 * out what to do next.
8406 		 * some actions are based on un_state, hence
8407 		 * restore the state st was in before ST_STATE_SENSING.
8408 		 */
8409 		un->un_state = un->un_laststate;
8410 		action = st_handle_sense(un, bp);
8411 		/*
8412 		 * set pkt back to original packet in case we will have
8413 		 * to requeue it
8414 		 */
8415 		pkt = BP_PKT(bp);
8416 	} else  if ((SCBP(pkt)->sts_busy) || (SCBP(pkt)->sts_chk)) {
8417 		/*
8418 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
8419 		 * to see if the status bits we're okay. If a request sense
8420 		 * is to be run, that will happen.
8421 		 */
8422 		action = st_check_error(un, pkt);
8423 	}
8424 
8425 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
8426 		switch (action) {
8427 			case QUE_COMMAND:
8428 				/*
8429 				 * return cmd to head to the queue
8430 				 * since we are suspending so that
8431 				 * it gets restarted during resume
8432 				 */
8433 				if (un->un_runqf) {
8434 					last_runqf = un->un_runqf;
8435 					un->un_runqf = bp;
8436 					bp->b_actf = last_runqf;
8437 				} else {
8438 					bp->b_actf = NULL;
8439 					un->un_runqf = bp;
8440 					un->un_runql = bp;
8441 				}
8442 				action = JUST_RETURN;
8443 				break;
8444 
8445 			case QUE_SENSE:
8446 				action = COMMAND_DONE_ERROR;
8447 				break;
8448 
8449 			default:
8450 				break;
8451 		}
8452 	}
8453 
8454 	/*
8455 	 * Restore old state if we were sensing.
8456 	 */
8457 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
8458 		un->un_state = un->un_laststate;
8459 	}
8460 
8461 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8462 	    "st_intr: pkt=%p, bp=%p, action=%x, status=%x\n",
8463 	    (void *)pkt, (void *)bp, action, SCBP_C(pkt));
8464 
8465 
8466 	switch (action) {
8467 	case COMMAND_DONE_EACCES:
8468 		/* this is to report a reservation conflict */
8469 		st_bioerror(bp, EACCES);
8470 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8471 		    "Reservation Conflict \n");
8472 		un->un_pos.pmode = invalid;
8473 
8474 		/*FALLTHROUGH*/
8475 	case COMMAND_DONE_ERROR:
8476 		if (un->un_pos.eof < ST_EOT_PENDING &&
8477 		    un->un_state >= ST_STATE_OPEN) {
8478 			/*
8479 			 * all errors set state of the tape to 'unknown'
8480 			 * unless we're at EOT or are doing append testing.
8481 			 * If sense key was illegal request, preserve state.
8482 			 */
8483 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
8484 				un->un_pos.pmode = invalid;
8485 			}
8486 		}
8487 
8488 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8489 		/*
8490 		 * since we have an error (COMMAND_DONE_ERROR), we want to
8491 		 * make sure an error ocurrs, so make sure at least EIO is
8492 		 * returned
8493 		 */
8494 		if (geterror(bp) == 0)
8495 			st_bioerror(bp, EIO);
8496 
8497 		SET_PE_FLAG(un);
8498 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
8499 		    (un->un_errno == EIO)) {
8500 			un->un_rqs_state &= ~(ST_RQS_VALID);
8501 		}
8502 		goto done;
8503 
8504 	case COMMAND_DONE_ERROR_RECOVERED:
8505 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8506 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
8507 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
8508 		if (geterror(bp) == 0) {
8509 			st_bioerror(bp, EIO);
8510 		}
8511 		SET_PE_FLAG(un);
8512 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
8513 		    (un->un_errno == EIO)) {
8514 			un->un_rqs_state &= ~(ST_RQS_VALID);
8515 		}
8516 		/*FALLTHROUGH*/
8517 	case COMMAND_DONE:
8518 		st_set_state(un);
8519 done:
8520 		ST_DO_KSTATS(bp, kstat_runq_exit);
8521 		st_done_and_mutex_exit(un, bp);
8522 		return;
8523 
8524 	case QUE_SENSE:
8525 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
8526 			goto sense_error;
8527 
8528 		if (un->un_state != ST_STATE_SENSING) {
8529 			un->un_laststate = un->un_state;
8530 			un->un_state = ST_STATE_SENSING;
8531 		}
8532 
8533 		un->un_rqs->pkt_private = (opaque_t)bp;
8534 		bzero(ST_RQSENSE, SENSE_LENGTH);
8535 
8536 		if (un->un_throttle) {
8537 			un->un_last_throttle = un->un_throttle;
8538 			un->un_throttle = 0;
8539 		}
8540 
8541 		mutex_exit(ST_MUTEX);
8542 
8543 		/*
8544 		 * never retry this, some other command will have nuked the
8545 		 * sense, anyway
8546 		 */
8547 		status = scsi_transport(un->un_rqs);
8548 
8549 		mutex_enter(ST_MUTEX);
8550 
8551 		if (un->un_last_throttle) {
8552 			un->un_throttle = un->un_last_throttle;
8553 		}
8554 
8555 		if (status == TRAN_ACCEPT) {
8556 			mutex_exit(ST_MUTEX);
8557 			return;
8558 		}
8559 		if (status != TRAN_BUSY)
8560 			ST_DO_ERRSTATS(un, st_transerrs);
8561 sense_error:
8562 		un->un_pos.pmode = invalid;
8563 		st_bioerror(bp, EIO);
8564 		SET_PE_FLAG(un);
8565 		goto done;
8566 
8567 	case QUE_BUSY_COMMAND:
8568 		/* longish timeout */
8569 		timout = ST_STATUS_BUSY_TIMEOUT;
8570 		goto que_it_up;
8571 
8572 	case QUE_COMMAND:
8573 		/* short timeout */
8574 		timout = ST_TRAN_BUSY_TIMEOUT;
8575 que_it_up:
8576 		/*
8577 		 * let st_handle_intr_busy put this bp back on waitq and make
8578 		 * checks to see if it is ok to requeue the command.
8579 		 */
8580 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8581 
8582 		/*
8583 		 * Save the throttle before setting up the timeout
8584 		 */
8585 		if (un->un_throttle) {
8586 			un->un_last_throttle = un->un_throttle;
8587 		}
8588 		mutex_exit(ST_MUTEX);
8589 		if (st_handle_intr_busy(un, bp, timout) == 0)
8590 			return;		/* timeout is setup again */
8591 
8592 		mutex_enter(ST_MUTEX);
8593 		un->un_pos.pmode = invalid;
8594 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8595 		st_bioerror(bp, EIO);
8596 		SET_PE_FLAG(un);
8597 		goto done;
8598 
8599 	case QUE_LAST_COMMAND:
8600 
8601 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
8602 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
8603 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
8604 			goto last_command_error;
8605 		}
8606 		mutex_exit(ST_MUTEX);
8607 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
8608 			return;
8609 		mutex_enter(ST_MUTEX);
8610 last_command_error:
8611 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8612 		un->un_pos.pmode = invalid;
8613 		st_bioerror(bp, EIO);
8614 		SET_PE_FLAG(un);
8615 		goto done;
8616 
8617 	case JUST_RETURN:
8618 	default:
8619 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8620 		mutex_exit(ST_MUTEX);
8621 		return;
8622 	}
8623 	/*NOTREACHED*/
8624 }
8625 
8626 static int
8627 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
8628 {
8629 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
8630 	int rval = COMMAND_DONE_ERROR;
8631 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
8632 	    un->un_rqs : BP_PKT(bp);
8633 	int result;
8634 
8635 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
8636 
8637 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8638 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
8639 
8640 	ASSERT(mutex_owned(ST_MUTEX));
8641 
8642 	switch (pkt->pkt_reason) {
8643 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
8644 		/*
8645 		 * this occurs when accessing a powered down drive, no
8646 		 * need to complain; just fail the open
8647 		 */
8648 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
8649 
8650 		/*
8651 		 * if we have commands outstanding in HBA, and a command
8652 		 * comes back incomplete, we're hosed, so reset target
8653 		 * If we have the bus, but cmd_incomplete, we probably just
8654 		 * have a failed selection, so don't reset the target, just
8655 		 * requeue the command and try again
8656 		 */
8657 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
8658 			goto reset_target;
8659 		}
8660 
8661 		/*
8662 		 * Retry selection a couple more times if we're
8663 		 * open.  If opening, we only try just once to
8664 		 * reduce probe time for nonexistant devices.
8665 		 */
8666 		if ((un->un_laststate > ST_STATE_OPENING) &&
8667 		    ((int)un->un_retry_ct < st_selection_retry_count)) {
8668 			rval = QUE_COMMAND;
8669 		}
8670 		ST_DO_ERRSTATS(un, st_transerrs);
8671 		break;
8672 
8673 	case CMD_ABORTED:
8674 		/*
8675 		 * most likely this is caused by flush-on-error support. If
8676 		 * it was not there, the we're in trouble.
8677 		 */
8678 		if (!un->un_flush_on_errors) {
8679 			un->un_status = SUN_KEY_FATAL;
8680 			goto reset_target;
8681 		}
8682 
8683 		st_set_pe_errno(un);
8684 		bioerror(bp, un->un_errno);
8685 		if (un->un_errno)
8686 			return (COMMAND_DONE_ERROR);
8687 		else
8688 			return (COMMAND_DONE);
8689 
8690 	case CMD_TIMEOUT:	/* Command timed out */
8691 		un->un_status = SUN_KEY_TIMEOUT;
8692 
8693 		/*FALLTHROUGH*/
8694 	default:
8695 reset_target:
8696 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8697 		    "transport completed with %s\n",
8698 		    scsi_rname(pkt->pkt_reason));
8699 		ST_DO_ERRSTATS(un, st_transerrs);
8700 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
8701 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
8702 		    STAT_ABORTED)) == 0)) {
8703 
8704 			/*
8705 			 * If we haven't reserved the drive don't reset it.
8706 			 */
8707 			if ((un->un_rsvd_status &
8708 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
8709 				return (rval);
8710 			}
8711 
8712 			/*
8713 			 * if we aren't lost yet we will be soon.
8714 			 */
8715 			un->un_pos.pmode = invalid;
8716 
8717 			mutex_exit(ST_MUTEX);
8718 
8719 			result = scsi_reset(ROUTE, RESET_TARGET);
8720 			/*
8721 			 * if target reset fails, then pull the chain
8722 			 */
8723 			if (result == 0) {
8724 				result = scsi_reset(ROUTE, RESET_ALL);
8725 			}
8726 			mutex_enter(ST_MUTEX);
8727 
8728 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
8729 				/* no hope left to recover */
8730 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
8731 				    "recovery by resets failed\n");
8732 				return (rval);
8733 			}
8734 		}
8735 	}
8736 
8737 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
8738 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
8739 		if ((un->un_rsvd_status & ST_RESERVE)) {
8740 			un->un_rsvd_status |= ST_LOST_RESERVE;
8741 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8742 			    "Lost Reservation\n");
8743 		}
8744 	}
8745 
8746 	if ((int)un->un_retry_ct++ < st_retry_count) {
8747 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
8748 			rval = QUE_COMMAND;
8749 		} else if (bp == un->un_sbufp) {
8750 			switch ((uchar_t)(uintptr_t)bp->b_forw) {
8751 			case SCMD_MODE_SENSE:
8752 			case SCMD_MODE_SELECT:
8753 			case SCMD_READ_BLKLIM:
8754 			case SCMD_REWIND:
8755 			case SCMD_LOAD:
8756 			case SCMD_TEST_UNIT_READY:
8757 				/*
8758 				 * These commands can be rerun with impunity
8759 				 */
8760 				rval = QUE_COMMAND;
8761 				break;
8762 
8763 			default:
8764 				break;
8765 			}
8766 		}
8767 	} else {
8768 		rval = COMMAND_DONE_ERROR;
8769 	}
8770 
8771 	if (un->un_state >= ST_STATE_OPEN) {
8772 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
8773 		    fail, scsi_rname(pkt->pkt_reason),
8774 		    (rval == COMMAND_DONE_ERROR)?
8775 		    "giving up" : "retrying command");
8776 	}
8777 	return (rval);
8778 }
8779 
8780 /*
8781  * if the device is busy, then put this bp back on the waitq, on the
8782  * interrupt thread, where we want the head of the queue and not the
8783  * end
8784  *
8785  * The callers of this routine should take measures to save the
8786  * un_throttle in un_last_throttle which will be restored in
8787  * st_intr_restart(). The only exception should be st_intr_restart()
8788  * calling this routine for which the saving is already done.
8789  */
8790 static int
8791 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
8792 	clock_t timeout_interval)
8793 {
8794 	struct buf *last_quef;
8795 	int rval = 0;
8796 
8797 	mutex_enter(ST_MUTEX);
8798 
8799 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
8800 
8801 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8802 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
8803 
8804 	/*
8805 	 * Check to see if we hit the retry timeout. We check to make sure
8806 	 * this is the first one on the runq and make sure we have not
8807 	 * queued up any more, so this one has to be the last on the list
8808 	 * also. If it is not, we have to fail.  If it is not the first, but
8809 	 * is the last we are in trouble anyway, as we are in the interrupt
8810 	 * context here.
8811 	 */
8812 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
8813 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
8814 		rval = -1;
8815 		goto exit;
8816 	}
8817 
8818 	/* put the bp back on the waitq */
8819 	if (un->un_quef) {
8820 		last_quef = un->un_quef;
8821 		un->un_quef = bp;
8822 		bp->b_actf = last_quef;
8823 	} else  {
8824 		bp->b_actf = NULL;
8825 		un->un_quef = bp;
8826 		un->un_quel = bp;
8827 	}
8828 
8829 	/*
8830 	 * We know that this is the first and last on the runq at this time,
8831 	 * so we just nullify those two queues
8832 	 */
8833 	un->un_runqf = NULL;
8834 	un->un_runql = NULL;
8835 
8836 	/*
8837 	 * We don't want any other commands being started in the mean time.
8838 	 * If start had just released mutex after putting something on the
8839 	 * runq, we won't even get here.
8840 	 */
8841 	un->un_throttle = 0;
8842 
8843 	/*
8844 	 * send a marker pkt, if appropriate
8845 	 */
8846 	st_hba_unflush(un);
8847 
8848 	/*
8849 	 * all queues are aligned, we are just waiting to
8850 	 * transport
8851 	 */
8852 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
8853 
8854 exit:
8855 	mutex_exit(ST_MUTEX);
8856 	return (rval);
8857 }
8858 
8859 /*
8860  * To get one error entry from error stack
8861  */
8862 static int
8863 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
8864 {
8865 #ifdef _MULTI_DATAMODEL
8866 	/*
8867 	 * For use when a 32 bit app makes a call into a
8868 	 * 64 bit ioctl
8869 	 */
8870 	struct mterror_entry32 err_entry32;
8871 #endif /* _MULTI_DATAMODEL */
8872 
8873 	int rval = 0;
8874 	struct mterror_entry err_entry;
8875 	struct mterror_entry_stack *err_link_entry_p;
8876 	size_t arq_status_len_in, arq_status_len_kr;
8877 
8878 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
8879 
8880 	ASSERT(mutex_owned(ST_MUTEX));
8881 
8882 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8883 	    "st_get_error_entry()\n");
8884 
8885 	/*
8886 	 * if error record stack empty, return ENXIO
8887 	 */
8888 	if (un->un_error_entry_stk == NULL) {
8889 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8890 		    "st_get_error_entry: Error Entry Stack Empty!\n");
8891 		rval = ENXIO;
8892 		goto ret;
8893 	}
8894 
8895 	/*
8896 	 * get the top entry from stack
8897 	 */
8898 	err_link_entry_p = un->un_error_entry_stk;
8899 	arq_status_len_kr =
8900 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
8901 
8902 #ifdef _MULTI_DATAMODEL
8903 	switch (ddi_model_convert_from(flag & FMODELS)) {
8904 	case DDI_MODEL_ILP32:
8905 		if (ddi_copyin((void *)arg, &err_entry32,
8906 		    MTERROR_ENTRY_SIZE_32, flag)) {
8907 			rval = EFAULT;
8908 			goto ret;
8909 		}
8910 
8911 		arq_status_len_in =
8912 		    (size_t)err_entry32.mtee_arq_status_len;
8913 
8914 		err_entry32.mtee_cdb_len =
8915 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
8916 
8917 		if (arq_status_len_in > arq_status_len_kr)
8918 			err_entry32.mtee_arq_status_len =
8919 			    (size32_t)arq_status_len_kr;
8920 
8921 		if (ddi_copyout(
8922 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
8923 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
8924 		    err_entry32.mtee_cdb_len, flag)) {
8925 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8926 			    "st_get_error_entry: Copy cdb buffer error!");
8927 			rval = EFAULT;
8928 		}
8929 
8930 		if (ddi_copyout(
8931 		    err_link_entry_p->mtees_entry.mtee_arq_status,
8932 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
8933 		    err_entry32.mtee_arq_status_len, flag)) {
8934 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8935 			    "st_get_error_entry: copy arq status error!");
8936 			rval = EFAULT;
8937 		}
8938 
8939 		if (ddi_copyout(&err_entry32, (void *)arg,
8940 		    MTERROR_ENTRY_SIZE_32, flag)) {
8941 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8942 			    "st_get_error_entry: copy arq status out error!");
8943 			rval = EFAULT;
8944 		}
8945 		break;
8946 
8947 	case DDI_MODEL_NONE:
8948 		if (ddi_copyin((void *)arg, &err_entry,
8949 		    MTERROR_ENTRY_SIZE_64, flag)) {
8950 			rval = EFAULT;
8951 			goto ret;
8952 		}
8953 		arq_status_len_in = err_entry.mtee_arq_status_len;
8954 
8955 		err_entry.mtee_cdb_len =
8956 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
8957 
8958 		if (arq_status_len_in > arq_status_len_kr)
8959 			err_entry.mtee_arq_status_len =
8960 			    arq_status_len_kr;
8961 
8962 		if (ddi_copyout(
8963 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
8964 		    err_entry.mtee_cdb_buf,
8965 		    err_entry.mtee_cdb_len, flag)) {
8966 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8967 			    "st_get_error_entry: Copy cdb buffer error!");
8968 			rval = EFAULT;
8969 		}
8970 
8971 		if (ddi_copyout(
8972 		    err_link_entry_p->mtees_entry.mtee_arq_status,
8973 		    err_entry.mtee_arq_status,
8974 		    err_entry.mtee_arq_status_len, flag)) {
8975 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8976 			    "st_get_error_entry: copy arq status error!");
8977 			rval = EFAULT;
8978 		}
8979 
8980 		if (ddi_copyout(&err_entry, (void *)arg,
8981 		    MTERROR_ENTRY_SIZE_64, flag)) {
8982 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8983 			    "st_get_error_entry: copy arq status out error!");
8984 			rval = EFAULT;
8985 		}
8986 		break;
8987 	}
8988 #else /* _MULTI_DATAMODEL */
8989 	if (ddi_copyin((void *)arg, &err_entry,
8990 	    MTERROR_ENTRY_SIZE_64, flag)) {
8991 		rval = EFAULT;
8992 		goto ret;
8993 	}
8994 	arq_status_len_in = err_entry.mtee_arq_status_len;
8995 
8996 	err_entry.mtee_cdb_len =
8997 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
8998 
8999 	if (arq_status_len_in > arq_status_len_kr)
9000 		err_entry.mtee_arq_status_len =
9001 		    arq_status_len_kr;
9002 
9003 	if (ddi_copyout(
9004 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
9005 	    err_entry.mtee_cdb_buf,
9006 	    err_entry.mtee_cdb_len, flag)) {
9007 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9008 		    "st_get_error_entry: Copy cdb buffer error!");
9009 		rval = EFAULT;
9010 	}
9011 
9012 	if (ddi_copyout(
9013 	    err_link_entry_p->mtees_entry.mtee_arq_status,
9014 	    err_entry.mtee_arq_status,
9015 	    err_entry.mtee_arq_status_len, flag)) {
9016 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9017 		    "st_get_error_entry: copy arq status buffer error!");
9018 		rval = EFAULT;
9019 	}
9020 
9021 	if (ddi_copyout(&err_entry, (void *)arg,
9022 	    MTERROR_ENTRY_SIZE_64, flag)) {
9023 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9024 		    "st_get_error_entry: copy arq status out error!");
9025 		rval = EFAULT;
9026 	}
9027 #endif /* _MULTI_DATAMODEL */
9028 
9029 	/*
9030 	 * update stack
9031 	 */
9032 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
9033 
9034 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
9035 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
9036 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
9037 
9038 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
9039 	    SECMDS_STATUS_SIZE);
9040 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
9041 
9042 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
9043 	err_link_entry_p = NULL;
9044 ret:
9045 	return (rval);
9046 }
9047 
9048 /*
9049  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
9050  * the scsi CDB command which causes the error and generates sense data and
9051  * the scsi status.
9052  *
9053  *      error-record stack
9054  *
9055  *
9056  *             TOP                                     BOTTOM
9057  *              ------------------------------------------
9058  *              |   0   |   1   |   2   |   ...  |   n   |
9059  *              ------------------------------------------
9060  *                  ^
9061  *                  |
9062  *       pointer to error entry
9063  *
9064  * when st driver generates one sense data record, it creates a error-entry
9065  * and pushes it onto the stack.
9066  *
9067  */
9068 
9069 static void
9070 st_update_error_stack(struct scsi_tape *un,
9071 			struct scsi_pkt *pkt,
9072 			struct scsi_arq_status *cmd)
9073 {
9074 	struct mterror_entry_stack *err_entry_tmp;
9075 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
9076 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
9077 
9078 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
9079 
9080 	ASSERT(mutex_owned(ST_MUTEX));
9081 
9082 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9083 	    "st_update_error_stack()\n");
9084 
9085 	ASSERT(cmd);
9086 	ASSERT(cdbp);
9087 	if (cdblen == 0) {
9088 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9089 		    "st_update_error_stack: CDB length error!\n");
9090 		return;
9091 	}
9092 
9093 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
9094 	ASSERT(err_entry_tmp != NULL);
9095 
9096 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
9097 	    kmem_alloc(cdblen, KM_SLEEP);
9098 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
9099 
9100 	err_entry_tmp->mtees_entry.mtee_arq_status =
9101 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
9102 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
9103 
9104 	/*
9105 	 * copy cdb command & length to current error entry
9106 	 */
9107 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
9108 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
9109 
9110 	/*
9111 	 * copy scsi status length to current error entry
9112 	 */
9113 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
9114 	    SECMDS_STATUS_SIZE;
9115 
9116 	/*
9117 	 * copy sense data and scsi status to current error entry
9118 	 */
9119 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
9120 	    SECMDS_STATUS_SIZE);
9121 
9122 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
9123 	un->un_error_entry_stk = err_entry_tmp;
9124 
9125 }
9126 
9127 /*
9128  * Empty all the error entry in stack
9129  */
9130 static void
9131 st_empty_error_stack(struct scsi_tape *un)
9132 {
9133 	struct mterror_entry_stack *linkp;
9134 
9135 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
9136 
9137 	ASSERT(mutex_owned(ST_MUTEX));
9138 
9139 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9140 	    "st_empty_entry_stack()\n");
9141 
9142 	while (un->un_error_entry_stk != NULL) {
9143 		linkp = un->un_error_entry_stk;
9144 		un->un_error_entry_stk =
9145 		    un->un_error_entry_stk->mtees_nextp;
9146 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
9147 		linkp = NULL;
9148 	}
9149 }
9150 
9151 static int
9152 st_handle_sense(struct scsi_tape *un, struct buf *bp)
9153 {
9154 	struct scsi_pkt *pkt = BP_PKT(bp);
9155 	struct scsi_pkt *rqpkt = un->un_rqs;
9156 	struct scsi_arq_status arqstat;
9157 
9158 	int rval = COMMAND_DONE_ERROR;
9159 	int amt;
9160 
9161 	ST_FUNC(ST_DEVINFO, st_handle_sense);
9162 
9163 	ASSERT(mutex_owned(ST_MUTEX));
9164 
9165 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9166 	    "st_handle_sense()\n");
9167 
9168 	if (SCBP(rqpkt)->sts_busy) {
9169 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
9170 		    "busy unit on request sense\n");
9171 		if ((int)un->un_retry_ct++ < st_retry_count) {
9172 			rval = QUE_BUSY_COMMAND;
9173 		}
9174 		return (rval);
9175 	} else if (SCBP(rqpkt)->sts_chk) {
9176 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9177 		    "Check Condition on REQUEST SENSE\n");
9178 		return (rval);
9179 	}
9180 
9181 	/* was there enough data? */
9182 	amt = (int)MAX_SENSE_LENGTH - rqpkt->pkt_resid;
9183 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
9184 	    (amt < SUN_MIN_SENSE_LENGTH)) {
9185 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9186 		    "REQUEST SENSE couldn't get sense data\n");
9187 		return (rval);
9188 	}
9189 
9190 	bcopy(SCBP(pkt), &arqstat.sts_status,
9191 	    sizeof (struct scsi_status));
9192 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
9193 	    sizeof (struct scsi_status));
9194 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
9195 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
9196 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
9197 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
9198 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
9199 
9200 	/*
9201 	 * copy one arqstat entry in the sense data buffer
9202 	 */
9203 	st_update_error_stack(un, pkt, &arqstat);
9204 	return (st_decode_sense(un, bp, amt, SCBP(rqpkt)));
9205 }
9206 
9207 static int
9208 st_handle_autosense(struct scsi_tape *un, struct buf *bp)
9209 {
9210 	struct scsi_pkt *pkt = BP_PKT(bp);
9211 	struct scsi_arq_status *arqstat =
9212 	    (struct scsi_arq_status *)pkt->pkt_scbp;
9213 	int rval = COMMAND_DONE_ERROR;
9214 	int amt;
9215 
9216 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
9217 
9218 	ASSERT(mutex_owned(ST_MUTEX));
9219 
9220 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9221 	    "st_handle_autosense()\n");
9222 
9223 	if (arqstat->sts_rqpkt_status.sts_busy) {
9224 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
9225 		    "busy unit on request sense\n");
9226 		/*
9227 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
9228 		 * the disadvantage is that we do not have any delay for the
9229 		 * second retry of rqsense and we have to keep a packet around
9230 		 */
9231 		return (QUE_SENSE);
9232 
9233 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
9234 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9235 		    "transport error on REQUEST SENSE\n");
9236 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
9237 		    ((arqstat->sts_rqpkt_statistics &
9238 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
9239 			mutex_exit(ST_MUTEX);
9240 			if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
9241 				/*
9242 				 * if target reset fails, then pull the chain
9243 				 */
9244 				if (scsi_reset(ROUTE, RESET_ALL) == 0) {
9245 					ST_DEBUG6(ST_DEVINFO, st_label,
9246 					    CE_WARN,
9247 					    "recovery by resets failed\n");
9248 				}
9249 			}
9250 			mutex_enter(ST_MUTEX);
9251 		}
9252 		return (rval);
9253 
9254 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
9255 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9256 		    "Check Condition on REQUEST SENSE\n");
9257 		return (rval);
9258 	}
9259 
9260 
9261 	/* was there enough data? */
9262 	if (pkt->pkt_state & STATE_XARQ_DONE) {
9263 		amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
9264 	} else {
9265 		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
9266 			amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
9267 		} else {
9268 			amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
9269 		}
9270 	}
9271 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
9272 	    (amt < SUN_MIN_SENSE_LENGTH)) {
9273 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9274 		    "REQUEST SENSE couldn't get sense data\n");
9275 		return (rval);
9276 	}
9277 
9278 	if (pkt->pkt_state & STATE_XARQ_DONE) {
9279 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, MAX_SENSE_LENGTH);
9280 	} else {
9281 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
9282 	}
9283 
9284 	/*
9285 	 * copy one arqstat entry in the sense data buffer
9286 	 */
9287 	st_update_error_stack(un, pkt, arqstat);
9288 
9289 	return (st_decode_sense(un, bp, amt, &arqstat->sts_rqpkt_status));
9290 }
9291 
9292 static int
9293 st_decode_sense(struct scsi_tape *un, struct buf *bp,  int amt,
9294 	struct scsi_status *statusp)
9295 {
9296 	struct scsi_pkt *pkt = BP_PKT(bp);
9297 	int rval = COMMAND_DONE_ERROR;
9298 	long resid;
9299 	struct scsi_extended_sense *sensep = ST_RQSENSE;
9300 	int severity;
9301 	int get_error;
9302 
9303 	ST_FUNC(ST_DEVINFO, st_decode_sense);
9304 
9305 	ASSERT(mutex_owned(ST_MUTEX));
9306 
9307 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9308 	    "st_decode_sense()\n");
9309 
9310 	/*
9311 	 * For uscsi commands, squirrel away a copy of the
9312 	 * results of the Request Sense.
9313 	 */
9314 	if (USCSI_CMD(bp)) {
9315 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
9316 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
9317 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
9318 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
9319 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
9320 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
9321 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9322 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
9323 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
9324 		}
9325 	}
9326 
9327 	/*
9328 	 * If the drive is an MT-02, reposition the
9329 	 * secondary error code into the proper place.
9330 	 *
9331 	 * XXX	MT-02 is non-CCS tape, so secondary error code
9332 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
9333 	 * so it's in byte 12.
9334 	 */
9335 	if (un->un_dp->type == ST_TYPE_EMULEX) {
9336 		sensep->es_code = sensep->es_add_info[0];
9337 	}
9338 
9339 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
9340 	    (caddr_t)&CDBP(pkt)->scc_cmd);
9341 
9342 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)sensep,
9343 	    sizeof (*sensep));
9344 
9345 	/* for normal I/O check extract the resid values. */
9346 	if (bp != un->un_sbufp) {
9347 		if (sensep->es_valid) {
9348 			resid =
9349 			    (sensep->es_info_1 << 24) |
9350 			    (sensep->es_info_2 << 16) |
9351 			    (sensep->es_info_3 << 8)  |
9352 			    (sensep->es_info_4);
9353 			/* If fixed block */
9354 			if (un->un_bsize) {
9355 				resid *= un->un_bsize;
9356 			}
9357 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
9358 			resid = pkt->pkt_resid;
9359 		} else {
9360 			resid = bp->b_bcount;
9361 		}
9362 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9363 		    "st_handle_sense (rw): xferred bit = %d, resid=%ld (%d), "
9364 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
9365 		    resid,
9366 		    (sensep->es_info_1 << 24) |
9367 		    (sensep->es_info_2 << 16) |
9368 		    (sensep->es_info_3 << 8)  |
9369 		    (sensep->es_info_4),
9370 		    pkt->pkt_resid);
9371 		/*
9372 		 * The problem is, what should we believe?
9373 		 */
9374 		if (resid && (pkt->pkt_resid == 0)) {
9375 			pkt->pkt_resid = resid;
9376 		}
9377 	} else {
9378 		/*
9379 		 * If the command is SCMD_SPACE, we need to get the
9380 		 * residual as returned in the sense data, to adjust
9381 		 * our idea of current tape position correctly
9382 		 */
9383 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
9384 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
9385 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
9386 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK) &&
9387 		    (sensep->es_valid)) {
9388 			resid =
9389 			    (sensep->es_info_1 << 24) |
9390 			    (sensep->es_info_2 << 16) |
9391 			    (sensep->es_info_3 << 8)  |
9392 			    (sensep->es_info_4);
9393 			bp->b_resid = resid;
9394 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9395 			    "st_handle_sense(other):	resid=%ld\n", resid);
9396 		} else {
9397 			/*
9398 			 * If the special command is SCMD_READ,
9399 			 * the correct resid will be set later.
9400 			 */
9401 			resid = bp->b_bcount;
9402 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9403 			    "st_handle_sense(special read):  resid=%ld\n",
9404 			    resid);
9405 		}
9406 	}
9407 
9408 	if ((un->un_state >= ST_STATE_OPEN) &&
9409 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
9410 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
9411 		    "Failed CDB", (char *)pkt->pkt_cdbp);
9412 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
9413 		    "sense data", (char *)sensep, amt);
9414 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
9415 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
9416 		    bp->b_bcount, resid, pkt->pkt_resid);
9417 	}
9418 
9419 	switch (un->un_status = sensep->es_key) {
9420 	case KEY_NO_SENSE:
9421 		severity = SCSI_ERR_INFO;
9422 
9423 		/*
9424 		 * Erase, locate or rewind operation in progress, retry
9425 		 * ASC  ASCQ
9426 		 *  00   18    Erase operation in progress
9427 		 *  00   19    Locate operation in progress
9428 		 *  00   1A    Rewind operation in progress
9429 		 */
9430 		if (sensep->es_add_code == 0 &&
9431 		    ((sensep->es_qual_code == 0x18) ||
9432 		    (sensep->es_qual_code == 0x19) ||
9433 		    (sensep->es_qual_code == 0x1a))) {
9434 			rval = QUE_COMMAND;
9435 			break;
9436 		}
9437 
9438 		goto common;
9439 
9440 	case KEY_RECOVERABLE_ERROR:
9441 		severity = SCSI_ERR_RECOVERED;
9442 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
9443 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
9444 			if (un->un_dp->options &
9445 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
9446 				rval = QUE_LAST_COMMAND;
9447 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
9448 				    severity, un->un_pos.lgclblkno,
9449 				    un->un_err_pos.lgclblkno, scsi_cmds,
9450 				    sensep);
9451 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
9452 				    "Command will be retried\n");
9453 			} else {
9454 				severity = SCSI_ERR_FATAL;
9455 				rval = COMMAND_DONE_ERROR_RECOVERED;
9456 				ST_DO_ERRSTATS(un, st_softerrs);
9457 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
9458 				    severity, un->un_pos.lgclblkno,
9459 				    un->un_err_pos.lgclblkno, scsi_cmds,
9460 				    sensep);
9461 			}
9462 			break;
9463 		}
9464 common:
9465 		/*
9466 		 * XXX only want reads to be stopped by filemarks.
9467 		 * Don't want them to be stopped by EOT.  EOT matters
9468 		 * only on write.
9469 		 */
9470 		if (sensep->es_filmk && !sensep->es_eom) {
9471 			rval = COMMAND_DONE;
9472 		} else if (sensep->es_eom) {
9473 			rval = COMMAND_DONE;
9474 		} else if (sensep->es_ili) {
9475 			/*
9476 			 * Fun with variable length record devices:
9477 			 * for specifying larger blocks sizes than the
9478 			 * actual physical record size.
9479 			 */
9480 			if (un->un_bsize == 0 && resid > 0) {
9481 				/*
9482 				 * XXX! Ugly.
9483 				 * The requested blocksize is > tape blocksize,
9484 				 * so this is ok, so we just return the
9485 				 * actual size xferred.
9486 				 */
9487 				pkt->pkt_resid = resid;
9488 				rval = COMMAND_DONE;
9489 			} else if (un->un_bsize == 0 && resid < 0) {
9490 				/*
9491 				 * The requested blocksize is < tape blocksize,
9492 				 * so this is not ok, so we err with ENOMEM
9493 				 */
9494 				rval = COMMAND_DONE_ERROR_RECOVERED;
9495 				st_bioerror(bp, ENOMEM);
9496 			} else {
9497 				ST_DO_ERRSTATS(un, st_softerrs);
9498 				severity = SCSI_ERR_FATAL;
9499 				rval = COMMAND_DONE_ERROR;
9500 				st_bioerror(bp, EINVAL);
9501 			}
9502 		} else {
9503 			/*
9504 			 * we hope and pray for this just being
9505 			 * something we can ignore (ie. a
9506 			 * truly recoverable soft error)
9507 			 */
9508 			rval = COMMAND_DONE;
9509 		}
9510 		if (sensep->es_filmk) {
9511 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9512 			    "filemark\n");
9513 			un->un_status = SUN_KEY_EOF;
9514 			un->un_pos.eof = ST_EOF_PENDING;
9515 			SET_PE_FLAG(un);
9516 		}
9517 
9518 		/*
9519 		 * ignore eom when reading, a fmk should terminate reading
9520 		 */
9521 		if ((sensep->es_eom) &&
9522 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
9523 			if ((sensep->es_add_code == 0) &&
9524 			    (sensep->es_qual_code == 4)) {
9525 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9526 				    "bot\n");
9527 				un->un_status = SUN_KEY_BOT;
9528 				un->un_pos.eof = ST_NO_EOF;
9529 				un->un_pos.lgclblkno = 0;
9530 				un->un_pos.fileno = 0;
9531 				un->un_pos.blkno = 0;
9532 				un->un_pos.pmode = legacy;
9533 			} else {
9534 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9535 				    "eom\n");
9536 				un->un_status = SUN_KEY_EOT;
9537 				un->un_pos.eof = ST_EOM;
9538 			}
9539 			SET_PE_FLAG(un);
9540 		}
9541 
9542 		break;
9543 
9544 	case KEY_ILLEGAL_REQUEST:
9545 
9546 		if (un->un_laststate >= ST_STATE_OPEN) {
9547 			ST_DO_ERRSTATS(un, st_softerrs);
9548 			severity = SCSI_ERR_FATAL;
9549 		} else {
9550 			severity = SCSI_ERR_INFO;
9551 		}
9552 		break;
9553 
9554 	case KEY_MEDIUM_ERROR:
9555 		ST_DO_ERRSTATS(un, st_harderrs);
9556 		severity = SCSI_ERR_FATAL;
9557 
9558 		/*
9559 		 * for (buffered) writes, a medium error must be fatal
9560 		 */
9561 		if (CDBP(pkt)->scc_cmd != SCMD_WRITE) {
9562 			rval = COMMAND_DONE_ERROR_RECOVERED;
9563 		}
9564 
9565 check_keys:
9566 		/*
9567 		 * attempt to process the keys in the presence of
9568 		 * other errors
9569 		 */
9570 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
9571 			/*
9572 			 * Fun with variable length record devices:
9573 			 * for specifying larger blocks sizes than the
9574 			 * actual physical record size.
9575 			 */
9576 			if (un->un_bsize == 0 && resid > 0) {
9577 				/*
9578 				 * XXX! Ugly
9579 				 */
9580 				pkt->pkt_resid = resid;
9581 			} else if (un->un_bsize == 0 && resid < 0) {
9582 				st_bioerror(bp, EINVAL);
9583 			} else {
9584 				severity = SCSI_ERR_FATAL;
9585 				rval = COMMAND_DONE_ERROR;
9586 				st_bioerror(bp, EINVAL);
9587 			}
9588 		}
9589 		if (sensep->es_filmk) {
9590 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9591 			    "filemark\n");
9592 			un->un_status = SUN_KEY_EOF;
9593 			un->un_pos.eof = ST_EOF_PENDING;
9594 			SET_PE_FLAG(un);
9595 		}
9596 
9597 		/*
9598 		 * ignore eom when reading, a fmk should terminate reading
9599 		 */
9600 		if ((sensep->es_eom) &&
9601 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
9602 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
9603 			un->un_status = SUN_KEY_EOT;
9604 			un->un_pos.eof = ST_EOM;
9605 			SET_PE_FLAG(un);
9606 		}
9607 
9608 		break;
9609 
9610 	case KEY_VOLUME_OVERFLOW:
9611 		ST_DO_ERRSTATS(un, st_softerrs);
9612 		un->un_pos.eof = ST_EOM;
9613 		severity = SCSI_ERR_FATAL;
9614 		rval = COMMAND_DONE_ERROR;
9615 		goto check_keys;
9616 
9617 	case KEY_HARDWARE_ERROR:
9618 		ST_DO_ERRSTATS(un, st_harderrs);
9619 		severity = SCSI_ERR_FATAL;
9620 		rval = COMMAND_DONE_ERROR;
9621 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
9622 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
9623 		break;
9624 
9625 	case KEY_BLANK_CHECK:
9626 		ST_DO_ERRSTATS(un, st_softerrs);
9627 		severity = SCSI_ERR_INFO;
9628 
9629 		/*
9630 		 * if not a special request and some data was xferred then it
9631 		 * it is not an error yet
9632 		 */
9633 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
9634 			/*
9635 			 * no error for read with or without data xferred
9636 			 */
9637 			un->un_status = SUN_KEY_EOT;
9638 			un->un_pos.eof = ST_EOT;
9639 			rval = COMMAND_DONE_ERROR;
9640 			SET_PE_FLAG(un);
9641 			goto check_keys;
9642 		} else if (bp != un->un_sbufp &&
9643 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
9644 			rval = COMMAND_DONE;
9645 		} else {
9646 			rval = COMMAND_DONE_ERROR_RECOVERED;
9647 		}
9648 
9649 		if (un->un_laststate >= ST_STATE_OPEN) {
9650 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9651 			    "blank check\n");
9652 			un->un_pos.eof = ST_EOM;
9653 		}
9654 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
9655 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
9656 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
9657 		    (un->un_dp->options & ST_KNOWS_EOD)) {
9658 			/*
9659 			 * we were doing a fast forward by skipping
9660 			 * multiple fmk at the time
9661 			 */
9662 			st_bioerror(bp, EIO);
9663 			severity = SCSI_ERR_RECOVERED;
9664 			rval	 = COMMAND_DONE;
9665 		}
9666 		SET_PE_FLAG(un);
9667 		goto check_keys;
9668 
9669 	case KEY_WRITE_PROTECT:
9670 		if (st_wrongtapetype(un)) {
9671 			un->un_status = SUN_KEY_WRONGMEDIA;
9672 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9673 		"wrong tape for writing- use DC6150 tape (or equivalent)\n");
9674 			severity = SCSI_ERR_UNKNOWN;
9675 		} else {
9676 			severity = SCSI_ERR_FATAL;
9677 		}
9678 		ST_DO_ERRSTATS(un, st_harderrs);
9679 		rval = COMMAND_DONE_ERROR;
9680 		st_bioerror(bp, EACCES);
9681 		break;
9682 
9683 	case KEY_UNIT_ATTENTION:
9684 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9685 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
9686 
9687 		/*
9688 		 * If we have detected a Bus Reset and the tape
9689 		 * drive has been reserved.
9690 		 */
9691 		if (ST_RQSENSE->es_add_code == 0x29 &&
9692 		    (un->un_rsvd_status & ST_RESERVE)) {
9693 			un->un_rsvd_status |= ST_LOST_RESERVE;
9694 			ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9695 			    "st_decode_sense: Lost Reservation\n");
9696 		}
9697 
9698 		if (un->un_state <= ST_STATE_OPENING) {
9699 			/*
9700 			 * Look, the tape isn't open yet, now determine
9701 			 * if the cause is a BUS RESET, Save the file and
9702 			 * Block positions for the callers to recover from
9703 			 * the loss of position.
9704 			 */
9705 			if (un->un_pos.pmode != invalid) {
9706 				if (ST_RQSENSE->es_add_code == 0x29) {
9707 					un->un_save_fileno = un->un_pos.fileno;
9708 					un->un_save_blkno = un->un_pos.blkno;
9709 					un->un_restore_pos = 1;
9710 				}
9711 			}
9712 
9713 			if ((int)un->un_retry_ct++ < st_retry_count) {
9714 				rval = QUE_COMMAND;
9715 			} else {
9716 				rval = COMMAND_DONE_ERROR;
9717 			}
9718 			severity = SCSI_ERR_INFO;
9719 
9720 		} else {
9721 			/*
9722 			 * Check if it is an Unexpected Unit Attention.
9723 			 * If state is >= ST_STATE_OPEN, we have
9724 			 * already done the initialization .
9725 			 * In this case it is Fatal Error
9726 			 * since no further reading/writing
9727 			 * can be done with fileno set to < 0.
9728 			 */
9729 			if (un->un_state >= ST_STATE_OPEN) {
9730 				ST_DO_ERRSTATS(un, st_harderrs);
9731 				severity = SCSI_ERR_FATAL;
9732 			} else {
9733 				severity = SCSI_ERR_INFO;
9734 			}
9735 			rval = COMMAND_DONE_ERROR;
9736 		}
9737 		un->un_pos.pmode = invalid;
9738 
9739 		break;
9740 
9741 	case KEY_NOT_READY:
9742 		/*
9743 		 * If in process of getting ready retry.
9744 		 */
9745 		if (sensep->es_add_code  == 0x04 &&
9746 		    sensep->es_qual_code == 0x01 &&
9747 		    un->un_retry_ct++ < st_retry_count) {
9748 			rval = QUE_COMMAND;
9749 			severity = SCSI_ERR_INFO;
9750 		} else {
9751 			/* give up */
9752 			rval = COMMAND_DONE_ERROR;
9753 			severity = SCSI_ERR_FATAL;
9754 		}
9755 
9756 		/*
9757 		 * If this was an error and after device opened
9758 		 * do error stats.
9759 		 */
9760 		if (rval == COMMAND_DONE_ERROR &&
9761 		    un->un_state > ST_STATE_OPENING) {
9762 			ST_DO_ERRSTATS(un, st_harderrs);
9763 		}
9764 
9765 		if (ST_RQSENSE->es_add_code == 0x3a) {
9766 			if (st_error_level >= SCSI_ERR_FATAL)
9767 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
9768 				    "Tape not inserted in drive\n");
9769 			un->un_mediastate = MTIO_EJECTED;
9770 			cv_broadcast(&un->un_state_cv);
9771 		}
9772 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
9773 		    (rval != QUE_COMMAND))
9774 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
9775 		break;
9776 
9777 	case KEY_ABORTED_COMMAND:
9778 
9779 		/*
9780 		 * Probably a parity error...
9781 		 * if we retry here then this may cause data to be
9782 		 * written twice or data skipped during reading
9783 		 */
9784 		ST_DO_ERRSTATS(un, st_harderrs);
9785 		severity = SCSI_ERR_FATAL;
9786 		rval = COMMAND_DONE_ERROR;
9787 		goto check_keys;
9788 
9789 	default:
9790 		/*
9791 		 * Undecoded sense key.	 Try retries and hope
9792 		 * that will fix the problem.  Otherwise, we're
9793 		 * dead.
9794 		 */
9795 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9796 		    "Unhandled Sense Key '%s'\n",
9797 		    sense_keys[un->un_status]);
9798 		ST_DO_ERRSTATS(un, st_harderrs);
9799 		severity = SCSI_ERR_FATAL;
9800 		rval = COMMAND_DONE_ERROR;
9801 		goto check_keys;
9802 	}
9803 
9804 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
9805 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
9806 	    (un->un_laststate > ST_STATE_OPENING) &&
9807 	    (severity >= st_error_level))) {
9808 
9809 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
9810 		    un->un_pos.lgclblkno, un->un_err_pos.lgclblkno,
9811 		    scsi_cmds, sensep);
9812 		if (sensep->es_filmk) {
9813 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9814 			    "File Mark Detected\n");
9815 		}
9816 		if (sensep->es_eom) {
9817 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9818 			    "End-of-Media Detected\n");
9819 		}
9820 		if (sensep->es_ili) {
9821 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9822 			    "Incorrect Length Indicator Set\n");
9823 		}
9824 	}
9825 	get_error = geterror(bp);
9826 	if (((rval == COMMAND_DONE_ERROR) ||
9827 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
9828 	    ((get_error == EIO) || (get_error == 0))) {
9829 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
9830 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
9831 		if (un->un_rqs_state & ST_RQS_READ) {
9832 			un->un_rqs_state &= ~(ST_RQS_READ);
9833 		} else {
9834 			un->un_rqs_state |= ST_RQS_OVR;
9835 		}
9836 	}
9837 
9838 	return (rval);
9839 }
9840 
9841 
9842 static int
9843 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
9844 {
9845 	int status = TRAN_ACCEPT;
9846 
9847 	mutex_enter(ST_MUTEX);
9848 
9849 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
9850 
9851 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9852 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
9853 
9854 	/*
9855 	 * Check to see if we hit the retry timeout. We check to make sure
9856 	 * this is the first one on the runq and make sure we have not
9857 	 * queued up any more, so this one has to be the last on the list
9858 	 * also. If it is not, we have to fail.  If it is not the first, but
9859 	 * is the last we are in trouble anyway, as we are in the interrupt
9860 	 * context here.
9861 	 */
9862 	if (((int)un->un_retry_ct > st_retry_count) ||
9863 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
9864 		goto exit;
9865 	}
9866 
9867 	if (un->un_throttle) {
9868 		un->un_last_throttle = un->un_throttle;
9869 		un->un_throttle = 0;
9870 	}
9871 
9872 	/*
9873 	 * Here we know : bp is the first and last one on the runq
9874 	 * it is not necessary to put it back on the head of the
9875 	 * waitq and then move from waitq to runq. Save this queuing
9876 	 * and call scsi_transport.
9877 	 */
9878 
9879 	mutex_exit(ST_MUTEX);
9880 
9881 	status = scsi_transport(BP_PKT(bp));
9882 
9883 	mutex_enter(ST_MUTEX);
9884 
9885 	if (status == TRAN_ACCEPT) {
9886 		un->un_tran_retry_ct = 0;
9887 		if (un->un_last_throttle) {
9888 			un->un_throttle = un->un_last_throttle;
9889 		}
9890 		mutex_exit(ST_MUTEX);
9891 
9892 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9893 		    "restart transport \n");
9894 		return (0);
9895 	}
9896 
9897 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9898 	mutex_exit(ST_MUTEX);
9899 
9900 	if (status == TRAN_BUSY) {
9901 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
9902 			return (0);
9903 		}
9904 	}
9905 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9906 	    "restart transport rejected\n");
9907 	mutex_enter(ST_MUTEX);
9908 	ST_DO_ERRSTATS(un, st_transerrs);
9909 	if (un->un_last_throttle) {
9910 		un->un_throttle = un->un_last_throttle;
9911 	}
9912 exit:
9913 	mutex_exit(ST_MUTEX);
9914 	return (-1);
9915 }
9916 
9917 static int
9918 st_wrongtapetype(struct scsi_tape *un)
9919 {
9920 
9921 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
9922 
9923 	ASSERT(mutex_owned(ST_MUTEX));
9924 
9925 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
9926 
9927 	/*
9928 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
9929 	 */
9930 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
9931 		switch (un->un_dp->type) {
9932 		case ST_TYPE_WANGTEK:
9933 		case ST_TYPE_ARCHIVE:
9934 			/*
9935 			 * If this really worked, we could go off of
9936 			 * the density codes set in the modesense
9937 			 * page. For this drive, 0x10 == QIC-120,
9938 			 * 0xf == QIC-150, and 0x5 should be for
9939 			 * both QIC-24 and, maybe, QIC-11. However,
9940 			 * the h/w doesn't do what the manual says
9941 			 * that it should, so we'll key off of
9942 			 * getting a WRITE PROTECT error AND wp *not*
9943 			 * set in the mode sense information.
9944 			 */
9945 			/*
9946 			 * XXX but we already know that status is
9947 			 * write protect, so don't check it again.
9948 			 */
9949 
9950 			if (un->un_status == KEY_WRITE_PROTECT &&
9951 			    un->un_mspl->wp == 0) {
9952 				return (1);
9953 			}
9954 			break;
9955 		default:
9956 			break;
9957 		}
9958 	}
9959 	return (0);
9960 }
9961 
9962 static int
9963 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
9964 {
9965 	int action;
9966 
9967 	ST_FUNC(ST_DEVINFO, st_check_error);
9968 
9969 	ASSERT(mutex_owned(ST_MUTEX));
9970 
9971 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
9972 
9973 	if (SCBP_C(pkt) == STATUS_RESERVATION_CONFLICT) {
9974 		action = COMMAND_DONE_EACCES;
9975 		un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
9976 	} else if (SCBP(pkt)->sts_busy) {
9977 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
9978 		if ((int)un->un_retry_ct++ < st_retry_count) {
9979 			action = QUE_BUSY_COMMAND;
9980 		} else if ((un->un_rsvd_status &
9981 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9982 			/*
9983 			 * If this is a command done before reserve is done
9984 			 * don't reset.
9985 			 */
9986 			action = COMMAND_DONE_ERROR;
9987 		} else {
9988 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
9989 			    "unit busy too long\n");
9990 			mutex_exit(ST_MUTEX);
9991 			if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
9992 				(void) scsi_reset(ROUTE, RESET_ALL);
9993 			}
9994 			mutex_enter(ST_MUTEX);
9995 			action = COMMAND_DONE_ERROR;
9996 		}
9997 	} else if (SCBP(pkt)->sts_chk) {
9998 		/*
9999 		 * we should only get here if the auto rqsense failed
10000 		 * thru a uscsi cmd without autorequest sense
10001 		 * so we just try again
10002 		 */
10003 		action = QUE_SENSE;
10004 	} else {
10005 		action = COMMAND_DONE;
10006 	}
10007 	return (action);
10008 }
10009 
10010 static void
10011 st_calc_bnum(struct scsi_tape *un, struct buf *bp)
10012 {
10013 	int nblks;
10014 
10015 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
10016 
10017 	ASSERT(mutex_owned(ST_MUTEX));
10018 
10019 	/* If variable block mode */
10020 	if (un->un_bsize == 0) {
10021 		nblks = ((bp->b_bcount - bp->b_resid  == 0) ? 0 : 1);
10022 		un->un_kbytes_xferred += (bp->b_bcount - bp->b_resid) / ONE_K;
10023 	} else {
10024 		nblks = ((bp->b_bcount - bp->b_resid) / un->un_bsize);
10025 		un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
10026 	}
10027 	un->un_pos.blkno += nblks;
10028 	un->un_pos.lgclblkno += nblks;
10029 }
10030 
10031 static void
10032 st_set_state(struct scsi_tape *un)
10033 {
10034 	struct buf *bp = un->un_runqf;
10035 	struct scsi_pkt *sp = BP_PKT(bp);
10036 	struct uscsi_cmd *ucmd;
10037 
10038 	ST_FUNC(ST_DEVINFO, st_set_state);
10039 
10040 	ASSERT(mutex_owned(ST_MUTEX));
10041 
10042 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10043 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
10044 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
10045 
10046 	if (bp != un->un_sbufp) {
10047 #ifdef STDEBUG
10048 		if (DEBUGGING && sp->pkt_resid) {
10049 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10050 			    "pkt_resid %ld bcount %ld\n",
10051 			    sp->pkt_resid, bp->b_bcount);
10052 		}
10053 #endif
10054 		bp->b_resid = sp->pkt_resid;
10055 		st_calc_bnum(un, bp);
10056 		if (bp->b_flags & B_READ) {
10057 			un->un_lastop = ST_OP_READ;
10058 			un->un_fmneeded = 0;
10059 		} else {
10060 			un->un_lastop = ST_OP_WRITE;
10061 			if (un->un_dp->options & ST_REEL) {
10062 				un->un_fmneeded = 2;
10063 			} else {
10064 				un->un_fmneeded = 1;
10065 			}
10066 		}
10067 		/*
10068 		 * all is honky dory at this point, so let's
10069 		 * readjust the throttle, to increase speed, if we
10070 		 * have not throttled down.
10071 		 */
10072 		if (un->un_throttle) {
10073 			un->un_throttle = un->un_max_throttle;
10074 		}
10075 	} else {
10076 		optype new_lastop;
10077 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
10078 
10079 		un->un_lastop = ST_OP_CTL;
10080 
10081 		switch (cmd) {
10082 		case SCMD_WRITE:
10083 			bp->b_resid = sp->pkt_resid;
10084 			new_lastop = ST_OP_WRITE;
10085 			st_calc_bnum(un, bp);
10086 			if (un->un_dp->options & ST_REEL) {
10087 				un->un_fmneeded = 2;
10088 			} else {
10089 				un->un_fmneeded = 1;
10090 			}
10091 			break;
10092 		case SCMD_READ:
10093 			bp->b_resid = sp->pkt_resid;
10094 			new_lastop = ST_OP_READ;
10095 			st_calc_bnum(un, bp);
10096 			un->un_fmneeded = 0;
10097 			break;
10098 		case SCMD_WRITE_FILE_MARK:
10099 		{
10100 			int fmdone;
10101 
10102 			if (un->un_pos.eof != ST_EOM) {
10103 				un->un_pos.eof = ST_NO_EOF;
10104 			}
10105 			fmdone = (bp->b_bcount - bp->b_resid);
10106 			if (fmdone > 0) {
10107 				un->un_lastop = new_lastop = ST_OP_WEOF;
10108 				un->un_pos.lgclblkno += fmdone;
10109 				un->un_pos.fileno += fmdone;
10110 				un->un_pos.blkno = 0;
10111 			} else {
10112 				new_lastop = ST_OP_CTL;
10113 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
10114 				    "Flushed buffer\n");
10115 			}
10116 			if (fmdone > un->un_fmneeded) {
10117 				un->un_fmneeded = 0;
10118 			} else {
10119 				un->un_fmneeded -= fmdone;
10120 			}
10121 			break;
10122 		}
10123 		case SCMD_REWIND:
10124 			un->un_pos.eof = ST_NO_EOF;
10125 			un->un_pos.fileno = 0;
10126 			un->un_pos.blkno = 0;
10127 			un->un_pos.lgclblkno = 0;
10128 			un->un_pos.pmode = legacy;
10129 			new_lastop = ST_OP_CTL;
10130 			break;
10131 
10132 		case SCMD_SPACE:
10133 		{
10134 			int count;
10135 			long resid;
10136 			int done;
10137 
10138 			count = (int)SPACE_CNT(bp->b_bcount);
10139 			/* if was a uscsi space cmd b_bcount == 0 */
10140 			if (count == 0) {
10141 				count =
10142 				    (sp->pkt_cdbp[2] << 16) |
10143 				    (sp->pkt_cdbp[3] << 8)  |
10144 				    (sp->pkt_cdbp[4]);
10145 			}
10146 			resid = (long)SPACE_CNT(bp->b_resid);
10147 			if (count >= 0) {
10148 				done = (count - resid);
10149 			} else {
10150 				done = ((-count) - resid);
10151 			}
10152 			if (done > 0) {
10153 				un->un_lastop = new_lastop = ST_OP_CTL;
10154 			} else {
10155 				new_lastop = ST_OP_CTL;
10156 			}
10157 
10158 			ST_SPAC(ST_DEVINFO, st_label, SCSI_DEBUG,
10159 			    "space cmd: cdb[1] = %s\n"
10160 			    "space data:       = 0x%lx\n"
10161 			    "space count:      = %d\n"
10162 			    "space resid:      = %ld\n"
10163 			    "spaces done:      = %d\n"
10164 			    "fileno before     = %d\n"
10165 			    "blkno before      = %d\n",
10166 			    space_strs[sp->pkt_cdbp[1] & 7],
10167 			    bp->b_bcount,
10168 			    count, resid, done,
10169 			    un->un_pos.fileno, un->un_pos.blkno);
10170 
10171 			switch (sp->pkt_cdbp[1]) {
10172 			case SPACE_TYPE(SP_FLM):
10173 				/* Space file forward */
10174 				if (count >= 0) {
10175 					if (un->un_pos.eof <= ST_EOF) {
10176 						un->un_pos.eof = ST_NO_EOF;
10177 					}
10178 					un->un_pos.fileno += done;
10179 					un->un_pos.blkno = 0;
10180 					break;
10181 				}
10182 				/* Space file backward */
10183 				if (done > un->un_pos.fileno) {
10184 					un->un_pos.fileno = 0;
10185 					un->un_pos.blkno = 0;
10186 				} else {
10187 					un->un_pos.fileno -= done;
10188 					un->un_pos.blkno = INF;
10189 				}
10190 				break;
10191 			case SPACE_TYPE(SP_BLK):
10192 				/* Space block forward */
10193 				if (count >= 0) {
10194 					un->un_pos.blkno += done;
10195 					break;
10196 				}
10197 				/* Space block backward */
10198 				if (un->un_pos.eof >= ST_EOF_PENDING) {
10199 				/*
10200 				 * we stepped back into
10201 				 * a previous file; we are not
10202 				 * making an effort to pretend that
10203 				 * we are still in the current file
10204 				 * ie. logical == physical position
10205 				 * and leave it to st_ioctl to correct
10206 				 */
10207 					if (done > un->un_pos.blkno) {
10208 						un->un_pos.blkno = 0;
10209 					} else {
10210 						un->un_pos.fileno--;
10211 						un->un_pos.blkno = INF;
10212 					}
10213 				} else {
10214 					un->un_pos.blkno -= done;
10215 				}
10216 				break;
10217 			case SPACE_TYPE(SP_SQFLM):
10218 				un->un_pos.pmode = logical;
10219 				un->un_pos.blkno = 0;
10220 				un->un_lastop = new_lastop = ST_OP_CTL;
10221 				break;
10222 			case SPACE_TYPE(SP_EOD):
10223 				un->un_pos.pmode = logical;
10224 				un->un_pos.eof = ST_EOM;
10225 				un->un_status = KEY_BLANK_CHECK;
10226 				break;
10227 			default:
10228 				un->un_pos.pmode = invalid;
10229 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
10230 				    "Unsupported space cmd: %s\n",
10231 				    space_strs[sp->pkt_cdbp[1] & 7]);
10232 
10233 				un->un_lastop = new_lastop = ST_OP_CTL;
10234 			}
10235 
10236 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10237 			    "after_space rs %ld fil %d blk %d\n",
10238 			    resid, un->un_pos.fileno, un->un_pos.blkno);
10239 
10240 			break;
10241 		}
10242 		case SCMD_LOAD:
10243 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
10244 				un->un_pos.fileno = 0;
10245 				un->un_pos.pmode = legacy;
10246 			} else {
10247 				un->un_state = ST_STATE_OFFLINE;
10248 				un->un_pos.pmode = invalid;
10249 			}
10250 			un->un_density_known = 0;
10251 			un->un_pos.eof = ST_NO_EOF;
10252 			un->un_pos.blkno = 0;
10253 			un->un_lastop = new_lastop = ST_OP_CTL;
10254 			break;
10255 		case SCMD_ERASE:
10256 			un->un_pos.eof = ST_NO_EOF;
10257 			un->un_pos.blkno = 0;
10258 			un->un_pos.fileno = 0;
10259 			un->un_pos.lgclblkno = 0;
10260 			un->un_pos.pmode = legacy;
10261 			new_lastop = ST_OP_CTL;
10262 			break;
10263 		case SCMD_RESERVE:
10264 			un->un_rsvd_status |= ST_RESERVE;
10265 			un->un_rsvd_status &=
10266 			    ~(ST_RELEASE | ST_LOST_RESERVE |
10267 			    ST_RESERVATION_CONFLICT);
10268 			new_lastop = un->un_lastop;
10269 			break;
10270 		case SCMD_RELEASE:
10271 			un->un_rsvd_status |= ST_RELEASE;
10272 			un->un_rsvd_status &=
10273 			    ~(ST_RESERVE | ST_LOST_RESERVE |
10274 			    ST_RESERVATION_CONFLICT);
10275 			new_lastop = ST_OP_CTL;
10276 			break;
10277 		case SCMD_PERSISTENT_RESERVE_IN:
10278 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10279 			    "PGR_IN command\n");
10280 			break;
10281 		case SCMD_PERSISTENT_RESERVE_OUT:
10282 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
10283 			case ST_SA_SCSI3_RESERVE:
10284 			case ST_SA_SCSI3_PREEMPT:
10285 			case ST_SA_SCSI3_PREEMPTANDABORT:
10286 				un->un_rsvd_status |=
10287 				    ST_APPLICATION_RESERVATIONS;
10288 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10289 				    "PGR Reserve and set: entering"
10290 				    " ST_APPLICATION_RESERVATIONS mode");
10291 				break;
10292 			case ST_SA_SCSI3_RELEASE:
10293 			case ST_SA_SCSI3_CLEAR:
10294 				un->un_rsvd_status &=
10295 				    ~ST_APPLICATION_RESERVATIONS;
10296 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10297 				    "PGR Release and reset: exiting"
10298 				    " ST_APPLICATION_RESERVATIONS mode");
10299 				break;
10300 			}
10301 			break;
10302 		case SCMD_TEST_UNIT_READY:
10303 		case SCMD_READ_BLKLIM:
10304 		case SCMD_REQUEST_SENSE:
10305 		case SCMD_INQUIRY:
10306 		case SCMD_RECOVER_BUF:
10307 		case SCMD_MODE_SELECT:
10308 		case SCMD_MODE_SENSE:
10309 		case SCMD_DOORLOCK:
10310 		case SCMD_READ_BUFFER:
10311 		case SCMD_REPORT_DENSITIES:
10312 		case SCMD_LOG_SELECT_G1:
10313 		case SCMD_LOG_SENSE_G1:
10314 		case SCMD_REPORT_LUNS:
10315 		case SCMD_READ_ATTRIBUTE:
10316 		case SCMD_READ_MEDIA_SERIAL:
10317 			new_lastop = ST_OP_CTL;
10318 			break;
10319 		case SCMD_READ_POSITION:
10320 			new_lastop = ST_OP_CTL;
10321 			if (USCSI_CMD(bp)) {
10322 				(void) st_get_read_pos(un, bp);
10323 			}
10324 			break;
10325 		case SCMD_LOCATE:
10326 		case SCMD_LOCATE_G4:
10327 			/* Locate makes position mode no longer legacy */
10328 			un->un_lastop = new_lastop = ST_OP_CTL;
10329 			break;
10330 		default:
10331 			/*
10332 			 * Unknown command, If was USCSI and USCSI_SILENT
10333 			 * flag was not set, set position to unknown.
10334 			 */
10335 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
10336 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
10337 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
10338 				    "unknown cmd 0x%X caused loss of state\n",
10339 				    cmd);
10340 			} else {
10341 				break;
10342 			}
10343 			/* FALLTHROUGH */
10344 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
10345 			un->un_pos.pmode = invalid;
10346 			un->un_lastop = new_lastop = ST_OP_CTL;
10347 			break;
10348 		}
10349 
10350 		/* new_lastop should have been changed */
10351 		ASSERT(new_lastop != ST_OP_NIL);
10352 
10353 		/* If un_lastop should copy new_lastop  */
10354 		if (((un->un_lastop == ST_OP_WRITE) ||
10355 		    (un->un_lastop == ST_OP_WEOF)) &&
10356 		    new_lastop != ST_OP_CTL) {
10357 			un->un_lastop = new_lastop;
10358 		}
10359 	}
10360 
10361 	/*
10362 	 * In the st driver we have a logical and physical file position.
10363 	 * Under BSD behavior, when you get a zero read, the logical position
10364 	 * is before the filemark but after the last record of the file.
10365 	 * The physical position is after the filemark. MTIOCGET should always
10366 	 * return the logical file position.
10367 	 *
10368 	 * The next read gives a silent skip to the next file.
10369 	 * Under SVR4, the logical file position remains before the filemark
10370 	 * until the file is closed or a space operation is performed.
10371 	 * Hence set err_resid and err_file before changing fileno if case
10372 	 * BSD Behaviour.
10373 	 */
10374 	un->un_err_resid = bp->b_resid;
10375 	COPY_POS(&un->un_err_pos, &un->un_pos);
10376 	un->un_retry_ct = 0;
10377 
10378 
10379 	/*
10380 	 * If we've seen a filemark via the last read operation
10381 	 * advance the file counter, but mark things such that
10382 	 * the next read operation gets a zero count. We have
10383 	 * to put this here to handle the case of sitting right
10384 	 * at the end of a tape file having seen the file mark,
10385 	 * but the tape is closed and then re-opened without
10386 	 * any further i/o. That is, the position information
10387 	 * must be updated before a close.
10388 	 */
10389 
10390 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
10391 		/*
10392 		 * If we're a 1/2" tape, and we get a filemark
10393 		 * right on block 0, *AND* we were not in the
10394 		 * first file on the tape, and we've hit logical EOM.
10395 		 * We'll mark the state so that later we do the
10396 		 * right thing (in st_close(), st_strategy() or
10397 		 * st_ioctl()).
10398 		 *
10399 		 */
10400 		if ((un->un_dp->options & ST_REEL) &&
10401 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
10402 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
10403 			un->un_pos.eof = ST_EOT_PENDING;
10404 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10405 			    "eot pending\n");
10406 			un->un_pos.fileno++;
10407 			un->un_pos.blkno = 0;
10408 		} else if (BSD_BEHAVIOR) {
10409 			/*
10410 			 * If the read of the filemark was a side effect
10411 			 * of reading some blocks (i.e., data was actually
10412 			 * read), then the EOF mark is pending and the
10413 			 * bump into the next file awaits the next read
10414 			 * operation (which will return a zero count), or
10415 			 * a close or a space operation, else the bump
10416 			 * into the next file occurs now.
10417 			 */
10418 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10419 			    "resid=%lx, bcount=%lx\n",
10420 			    bp->b_resid, bp->b_bcount);
10421 
10422 			if (bp->b_resid != bp->b_bcount) {
10423 				un->un_pos.eof = ST_EOF;
10424 			} else {
10425 				un->un_silent_skip = 1;
10426 				un->un_pos.eof = ST_NO_EOF;
10427 				un->un_pos.fileno++;
10428 				un->un_pos.lgclblkno++;
10429 				un->un_save_blkno = un->un_pos.blkno;
10430 				un->un_pos.blkno = 0;
10431 			}
10432 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10433 			    "eof of file %d, eof=%d\n",
10434 			    un->un_pos.fileno, un->un_pos.eof);
10435 		} else if (SVR4_BEHAVIOR) {
10436 			/*
10437 			 * If the read of the filemark was a side effect
10438 			 * of reading some blocks (i.e., data was actually
10439 			 * read), then the next read should return 0
10440 			 */
10441 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10442 			    "resid=%lx, bcount=%lx\n",
10443 			    bp->b_resid, bp->b_bcount);
10444 			if (bp->b_resid == bp->b_bcount) {
10445 				un->un_pos.eof = ST_EOF;
10446 			}
10447 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10448 			    "eof of file=%d, eof=%d\n",
10449 			    un->un_pos.fileno, un->un_pos.eof);
10450 		}
10451 	}
10452 }
10453 
10454 /*
10455  * set the correct un_errno, to take corner cases into consideration
10456  */
10457 static void
10458 st_set_pe_errno(struct scsi_tape *un)
10459 {
10460 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
10461 
10462 	ASSERT(mutex_owned(ST_MUTEX));
10463 
10464 	/* if errno is already set, don't reset it */
10465 	if (un->un_errno)
10466 		return;
10467 
10468 	/* here un_errno == 0 */
10469 	/*
10470 	 * if the last transfer before flushing all the
10471 	 * waiting I/O's, was 0 (resid = count), then we
10472 	 * want to give the user an error on all the rest,
10473 	 * so here.  If there was a transfer, we set the
10474 	 * resid and counts to 0, and let it drop through,
10475 	 * giving a zero return.  the next I/O will then
10476 	 * give an error.
10477 	 */
10478 	if (un->un_last_resid == un->un_last_count) {
10479 		switch (un->un_pos.eof) {
10480 		case ST_EOM:
10481 			un->un_errno = ENOMEM;
10482 			break;
10483 		case ST_EOT:
10484 		case ST_EOF:
10485 			un->un_errno = EIO;
10486 			break;
10487 		}
10488 	} else {
10489 		/*
10490 		 * we know they did not have a zero, so make
10491 		 * sure they get one
10492 		 */
10493 		un->un_last_resid = un->un_last_count = 0;
10494 	}
10495 }
10496 
10497 
10498 /*
10499  * send in a marker pkt to terminate flushing of commands by BBA (via
10500  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
10501  */
10502 static void
10503 st_hba_unflush(struct scsi_tape *un)
10504 {
10505 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
10506 
10507 	ASSERT(mutex_owned(ST_MUTEX));
10508 
10509 	if (!un->un_flush_on_errors)
10510 		return;
10511 
10512 #ifdef FLUSH_ON_ERRORS
10513 
10514 	if (!un->un_mkr_pkt) {
10515 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
10516 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
10517 
10518 		/* we slept, so it must be there */
10519 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
10520 	}
10521 
10522 	mutex_exit(ST_MUTEX);
10523 	scsi_transport(un->un_mkr_pkt);
10524 	mutex_enter(ST_MUTEX);
10525 #endif
10526 }
10527 
10528 static char *
10529 st_print_scsi_cmd(char cmd)
10530 {
10531 	char tmp[64];
10532 	char *cpnt;
10533 
10534 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
10535 	/* tmp goes out of scope on return and caller sees garbage */
10536 	if (cpnt == tmp) {
10537 		cpnt = "Unknown Command";
10538 	}
10539 	return (cpnt);
10540 }
10541 
10542 static void
10543 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
10544     char *title, char *cdb)
10545 {
10546 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
10547 	char buf[256];
10548 	int instance = ddi_get_instance(dip);
10549 	struct scsi_tape *un;
10550 
10551 	un = ddi_get_soft_state(st_state, instance);
10552 
10553 	ST_FUNC(dip, st_print_cdb);
10554 
10555 #ifdef DEBUG
10556 	if ((st_debug & 0x180) == 0x100) {
10557 		scsi_log(dip, label, level, "node %s cmd %s\n",
10558 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
10559 		return;
10560 	}
10561 #endif
10562 	(void) sprintf(buf, "%s for cmd(%s)", title, st_print_scsi_cmd(*cdb));
10563 	st_clean_print(dip, label, level, buf, cdb, len);
10564 }
10565 
10566 static void
10567 st_clean_print(dev_info_t *dev, char *label, uint_t level,
10568     char *title, char *data, int len)
10569 {
10570 	int	i;
10571 	int 	c;
10572 	char	*format;
10573 	char	buf[256];
10574 	uchar_t	byte;
10575 
10576 	ST_FUNC(dev, st_clean_print);
10577 
10578 	(void) sprintf(buf, "%s:\n", title);
10579 	scsi_log(dev, label, level, "%s", buf);
10580 	level = CE_CONT;
10581 	for (i = 0; i < len; ) {
10582 		buf[0] = 0;
10583 		for (c = 0; c < 8 && i < len; c++, i++) {
10584 			byte = (uchar_t)data[i];
10585 			if (byte < 0x10)
10586 				format = "0x0%x ";
10587 			else
10588 				format = "0x%x ";
10589 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
10590 		}
10591 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
10592 
10593 		scsi_log(dev, label, level, "%s\n", buf);
10594 	}
10595 }
10596 
10597 /*
10598  * Conditionally enabled debugging
10599  */
10600 #ifdef	STDEBUG
10601 static void
10602 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
10603 {
10604 	char tmpbuf[64];
10605 
10606 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
10607 
10608 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10609 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
10610 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
10611 	    count, count,
10612 	    wait == ASYNC_CMD ? "a" : "");
10613 }
10614 
10615 /*
10616  * Returns pointer to name of minor node name of device 'dev'.
10617  */
10618 static char *
10619 st_dev_name(dev_t dev)
10620 {
10621 	struct scsi_tape *un;
10622 	const char density[] = { 'l', 'm', 'h', 'c' };
10623 	static char name[4];
10624 	minor_t minor;
10625 	int instance;
10626 	int nprt = 0;
10627 
10628 	minor = getminor(dev);
10629 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
10630 	un = ddi_get_soft_state(st_state, instance);
10631 	if (un) {
10632 		ST_FUNC(ST_DEVINFO, st_dev_name);
10633 	}
10634 
10635 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
10636 
10637 	if (minor & MT_BSD) {
10638 		name[++nprt] = 'b';
10639 	}
10640 
10641 	if (minor & MT_NOREWIND) {
10642 		name[++nprt] = 'n';
10643 	}
10644 
10645 	/* NULL terminator */
10646 	name[++nprt] = 0;
10647 
10648 	return (name);
10649 }
10650 #endif	/* STDEBUG */
10651 
10652 /*
10653  * Soft error reporting, so far unique to each drive
10654  *
10655  * Currently supported: exabyte and DAT soft error reporting
10656  */
10657 static int
10658 st_report_exabyte_soft_errors(dev_t dev, int flag)
10659 {
10660 	uchar_t *sensep;
10661 	int amt;
10662 	int rval = 0;
10663 	char cdb[CDB_GROUP0], *c = cdb;
10664 	struct uscsi_cmd *com;
10665 
10666 	GET_SOFT_STATE(dev);
10667 
10668 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
10669 
10670 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10671 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
10672 	    dev, flag);
10673 
10674 	ASSERT(mutex_owned(ST_MUTEX));
10675 
10676 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
10677 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
10678 
10679 	*c++ = SCMD_REQUEST_SENSE;
10680 	*c++ = 0;
10681 	*c++ = 0;
10682 	*c++ = 0;
10683 	*c++ = TAPE_SENSE_LENGTH;
10684 	/*
10685 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
10686 	 */
10687 	*c   = (char)0x80;
10688 
10689 	com->uscsi_cdb = cdb;
10690 	com->uscsi_cdblen = CDB_GROUP0;
10691 	com->uscsi_bufaddr = (caddr_t)sensep;
10692 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
10693 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
10694 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10695 
10696 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
10697 	if (rval || com->uscsi_status) {
10698 		goto done;
10699 	}
10700 
10701 	/*
10702 	 * was there enough data?
10703 	 */
10704 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
10705 
10706 	if ((amt >= 19) && un->un_kbytes_xferred) {
10707 		uint_t count, error_rate;
10708 		uint_t rate;
10709 
10710 		if (sensep[21] & CLN) {
10711 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10712 			    "Periodic head cleaning required");
10713 		}
10714 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
10715 			goto done;
10716 		}
10717 		/*
10718 		 * check if soft error reporting needs to be done.
10719 		 */
10720 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
10721 		count &= 0xffffff;
10722 		error_rate = (count * 100)/un->un_kbytes_xferred;
10723 
10724 #ifdef	STDEBUG
10725 		if (st_soft_error_report_debug) {
10726 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
10727 			    "Exabyte Soft Error Report:\n");
10728 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10729 			    "read/write error counter: %d\n", count);
10730 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10731 			    "number of bytes transferred: %dK\n",
10732 			    un->un_kbytes_xferred);
10733 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10734 			    "error_rate: %d%%\n", error_rate);
10735 
10736 			if (amt >= 22) {
10737 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10738 				    "unit sense: 0x%b 0x%b 0x%b\n",
10739 				    sensep[19], SENSE_19_BITS,
10740 				    sensep[20], SENSE_20_BITS,
10741 				    sensep[21], SENSE_21_BITS);
10742 			}
10743 			if (amt >= 27) {
10744 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10745 				    "tracking retry counter: %d\n",
10746 				    sensep[26]);
10747 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10748 				    "read/write retry counter: %d\n",
10749 				    sensep[27]);
10750 			}
10751 		}
10752 #endif
10753 
10754 		if (flag & FWRITE) {
10755 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
10756 		} else {
10757 			rate = EXABYTE_READ_ERROR_THRESHOLD;
10758 		}
10759 		if (error_rate >= rate) {
10760 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10761 			    "Soft error rate (%d%%) during %s was too high",
10762 			    error_rate,
10763 			    ((flag & FWRITE) ? wrg_str : rdg_str));
10764 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10765 			    "Please, replace tape cartridge\n");
10766 		}
10767 	}
10768 
10769 done:
10770 	kmem_free(com, sizeof (*com));
10771 	kmem_free(sensep, TAPE_SENSE_LENGTH);
10772 
10773 	if (rval != 0) {
10774 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10775 		    "exabyte soft error reporting failed\n");
10776 	}
10777 	return (rval);
10778 }
10779 
10780 /*
10781  * this is very specific to Archive 4mm dat
10782  */
10783 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
10784 
10785 static int
10786 st_report_dat_soft_errors(dev_t dev, int flag)
10787 {
10788 	uchar_t *sensep;
10789 	int amt, i;
10790 	int rval = 0;
10791 	char cdb[CDB_GROUP1], *c = cdb;
10792 	struct uscsi_cmd *com;
10793 
10794 	GET_SOFT_STATE(dev);
10795 
10796 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
10797 
10798 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10799 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
10800 
10801 	ASSERT(mutex_owned(ST_MUTEX));
10802 
10803 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
10804 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
10805 
10806 	*c++ = SCMD_LOG_SENSE_G1;
10807 	*c++ = 0;
10808 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
10809 	*c++ = 0;
10810 	*c++ = 0;
10811 	*c++ = 0;
10812 	*c++ = 2;
10813 	*c++ = 0;
10814 	*c++ = (char)LOG_SENSE_LENGTH;
10815 	*c   = 0;
10816 	com->uscsi_cdb    = cdb;
10817 	com->uscsi_cdblen  = CDB_GROUP1;
10818 	com->uscsi_bufaddr = (caddr_t)sensep;
10819 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
10820 	com->uscsi_flags   =
10821 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
10822 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10823 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
10824 	if (rval) {
10825 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10826 		    "DAT soft error reporting failed\n");
10827 	}
10828 	if (rval || com->uscsi_status) {
10829 		goto done;
10830 	}
10831 
10832 	/*
10833 	 * was there enough data?
10834 	 */
10835 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
10836 
10837 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
10838 		int total, retries, param_code;
10839 
10840 		total = -1;
10841 		retries = -1;
10842 		amt = sensep[3] + 4;
10843 
10844 
10845 #ifdef STDEBUG
10846 		if (st_soft_error_report_debug) {
10847 			(void) printf("logsense:");
10848 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
10849 				if (i % 16 == 0) {
10850 					(void) printf("\t\n");
10851 				}
10852 				(void) printf(" %x", sensep[i]);
10853 			}
10854 			(void) printf("\n");
10855 		}
10856 #endif
10857 
10858 		/*
10859 		 * parse the param_codes
10860 		 */
10861 		if (sensep[0] == 2 || sensep[0] == 3) {
10862 			for (i = 4; i < amt; i++) {
10863 				param_code = (sensep[i++] << 8);
10864 				param_code += sensep[i++];
10865 				i++; /* skip control byte */
10866 				if (param_code == 5) {
10867 					if (sensep[i++] == 4) {
10868 						total = (sensep[i++] << 24);
10869 						total += (sensep[i++] << 16);
10870 						total += (sensep[i++] << 8);
10871 						total += sensep[i];
10872 					}
10873 				} else if (param_code == 0x8007) {
10874 					if (sensep[i++] == 2) {
10875 						retries = sensep[i++] << 8;
10876 						retries += sensep[i];
10877 					}
10878 				} else {
10879 					i += sensep[i];
10880 				}
10881 			}
10882 		}
10883 
10884 		/*
10885 		 * if the log sense returned valid numbers then determine
10886 		 * the read and write error thresholds based on the amount of
10887 		 * data transferred
10888 		 */
10889 
10890 		if (total > 0 && retries > 0) {
10891 			short normal_retries = 0;
10892 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10893 			    "total xferred (%s) =%x, retries=%x\n",
10894 			    ((flag & FWRITE) ? wrg_str : rdg_str),
10895 			    total, retries);
10896 
10897 			if (flag & FWRITE) {
10898 				if (total <=
10899 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
10900 					normal_retries =
10901 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
10902 				} else {
10903 					normal_retries =
10904 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
10905 				}
10906 			} else {
10907 				if (total <=
10908 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
10909 					normal_retries =
10910 					    DAT_SMALL_READ_ERROR_THRESHOLD;
10911 				} else {
10912 					normal_retries =
10913 					    DAT_LARGE_READ_ERROR_THRESHOLD;
10914 				}
10915 			}
10916 
10917 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10918 			"normal retries=%d\n", normal_retries);
10919 
10920 			if (retries >= normal_retries) {
10921 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
10922 				    "Soft error rate (retries = %d) during "
10923 				    "%s was too high",  retries,
10924 				    ((flag & FWRITE) ? wrg_str : rdg_str));
10925 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10926 				    "Periodic head cleaning required "
10927 				    "and/or replace tape cartridge\n");
10928 			}
10929 
10930 		} else if (total == -1 || retries == -1) {
10931 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10932 			    "log sense parameter code does not make sense\n");
10933 		}
10934 	}
10935 
10936 	/*
10937 	 * reset all values
10938 	 */
10939 	c = cdb;
10940 	*c++ = SCMD_LOG_SELECT_G1;
10941 	*c++ = 2;	/* this resets all values */
10942 	*c++ = (char)0xc0;
10943 	*c++ = 0;
10944 	*c++ = 0;
10945 	*c++ = 0;
10946 	*c++ = 0;
10947 	*c++ = 0;
10948 	*c++ = 0;
10949 	*c   = 0;
10950 	com->uscsi_bufaddr = NULL;
10951 	com->uscsi_buflen  = 0;
10952 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
10953 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
10954 	if (rval) {
10955 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10956 		    "DAT soft error reset failed\n");
10957 	}
10958 done:
10959 	kmem_free(com, sizeof (*com));
10960 	kmem_free(sensep, LOG_SENSE_LENGTH);
10961 	return (rval);
10962 }
10963 
10964 static int
10965 st_report_soft_errors(dev_t dev, int flag)
10966 {
10967 	GET_SOFT_STATE(dev);
10968 
10969 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
10970 
10971 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10972 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
10973 
10974 	ASSERT(mutex_owned(ST_MUTEX));
10975 
10976 	switch (un->un_dp->type) {
10977 	case ST_TYPE_EXB8500:
10978 	case ST_TYPE_EXABYTE:
10979 		return (st_report_exabyte_soft_errors(dev, flag));
10980 		/*NOTREACHED*/
10981 	case ST_TYPE_PYTHON:
10982 		return (st_report_dat_soft_errors(dev, flag));
10983 		/*NOTREACHED*/
10984 	default:
10985 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
10986 		return (-1);
10987 	}
10988 }
10989 
10990 /*
10991  * persistent error routines
10992  */
10993 
10994 /*
10995  * enable persistent errors, and set the throttle appropriately, checking
10996  * for flush-on-errors capability
10997  */
10998 static void
10999 st_turn_pe_on(struct scsi_tape *un)
11000 {
11001 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
11002 
11003 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
11004 	ASSERT(mutex_owned(ST_MUTEX));
11005 
11006 	un->un_persistence = 1;
11007 
11008 	/*
11009 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
11010 	 * enabled.  This will simplify the error handling for request senses
11011 	 */
11012 
11013 	if (un->un_arq_enabled && un->un_untagged_qing) {
11014 		uchar_t f_o_e;
11015 
11016 		mutex_exit(ST_MUTEX);
11017 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
11018 		    1 : 0;
11019 		mutex_enter(ST_MUTEX);
11020 
11021 		un->un_flush_on_errors = f_o_e;
11022 	} else {
11023 		un->un_flush_on_errors = 0;
11024 	}
11025 
11026 	if (un->un_flush_on_errors)
11027 		un->un_max_throttle = (uchar_t)st_max_throttle;
11028 	else
11029 		un->un_max_throttle = 1;
11030 
11031 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
11032 		un->un_max_throttle = 1;
11033 
11034 	/* this will send a marker pkt */
11035 	CLEAR_PE(un);
11036 }
11037 
11038 /*
11039  * This turns persistent errors permanently off
11040  */
11041 static void
11042 st_turn_pe_off(struct scsi_tape *un)
11043 {
11044 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
11045 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
11046 	ASSERT(mutex_owned(ST_MUTEX));
11047 
11048 	/* turn it off for good */
11049 	un->un_persistence = 0;
11050 
11051 	/* this will send a marker pkt */
11052 	CLEAR_PE(un);
11053 
11054 	/* turn off flush on error capability, if enabled */
11055 	if (un->un_flush_on_errors) {
11056 		mutex_exit(ST_MUTEX);
11057 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
11058 		mutex_enter(ST_MUTEX);
11059 	}
11060 
11061 
11062 	un->un_flush_on_errors = 0;
11063 }
11064 
11065 /*
11066  * This clear persistent errors, allowing more commands through, and also
11067  * sending a marker packet.
11068  */
11069 static void
11070 st_clear_pe(struct scsi_tape *un)
11071 {
11072 	ST_FUNC(ST_DEVINFO, st_clear_pe);
11073 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
11074 	ASSERT(mutex_owned(ST_MUTEX));
11075 
11076 	un->un_persist_errors = 0;
11077 	un->un_throttle = un->un_last_throttle = 1;
11078 	un->un_errno = 0;
11079 	st_hba_unflush(un);
11080 }
11081 
11082 /*
11083  * This will flag persistent errors, shutting everything down, if the
11084  * application had enabled persistent errors via MTIOCPERSISTENT
11085  */
11086 static void
11087 st_set_pe_flag(struct scsi_tape *un)
11088 {
11089 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
11090 	ASSERT(mutex_owned(ST_MUTEX));
11091 
11092 	if (un->un_persistence) {
11093 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
11094 		un->un_persist_errors = 1;
11095 		un->un_throttle = un->un_last_throttle = 0;
11096 	}
11097 }
11098 
11099 /*
11100  * List of commands that are allowed to be done while another host holds
11101  * the reservation.
11102  */
11103 struct {
11104 	uchar_t cmd;
11105 	uchar_t byte;	/* byte to look for data */
11106 	uint32_t mask;	/* bits that matter in the above data */
11107 } rcmds[] = {
11108 	{ SCMD_TEST_UNIT_READY, 0, 0 }, /* may fail on older drives */
11109 	{ SCMD_REQUEST_SENSE, 0, 0 },
11110 	{ SCMD_READ_BLKLIM, 0, 0 },
11111 	{ SCMD_INQUIRY, 0, 0 },
11112 	{ SCMD_RESERVE, 0, 0 },
11113 	{ SCMD_RELEASE, 0, 0 },
11114 	{ SCMD_DOORLOCK, 4, 3 },	/* allow (unlock) media access only */
11115 	{ SCMD_REPORT_DENSITIES, 0, 0 },
11116 	{ SCMD_LOG_SENSE_G1, 0, 0 },
11117 	{ SCMD_PERSISTENT_RESERVE_IN, 0, 0 },
11118 	{ SCMD_PERSISTENT_RESERVE_OUT, 0, 0 },
11119 	{ SCMD_REPORT_LUNS, 0, 0 }
11120 };
11121 
11122 static int
11123 st_do_reserve(struct scsi_tape *un)
11124 {
11125 	int rval;
11126 
11127 	ST_FUNC(ST_DEVINFO, st_do_reserve);
11128 
11129 	/*
11130 	 * Issue a Throw-Away reserve command to clear the
11131 	 * check condition.
11132 	 * If the current behaviour of reserve/release is to
11133 	 * hold reservation across opens , and if a Bus reset
11134 	 * has been issued between opens then this command
11135 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
11136 	 * In this case return an EACCES so that user knows that
11137 	 * reservation has been lost in between opens.
11138 	 * If this error is not returned and we continue with
11139 	 * successful open , then user may think position of the
11140 	 * tape is still the same but inreality we would rewind the
11141 	 * tape and continue from BOT.
11142 	 */
11143 	rval = st_reserve_release(un, ST_RESERVE);
11144 	if (rval) {
11145 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
11146 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
11147 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
11148 			un->un_errno = EACCES;
11149 			return (EACCES);
11150 		}
11151 		rval = st_reserve_release(un, ST_RESERVE);
11152 	}
11153 	if (rval == 0) {
11154 		un->un_rsvd_status |= ST_INIT_RESERVE;
11155 	}
11156 
11157 	return (rval);
11158 }
11159 
11160 static int
11161 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, caddr_t cdb)
11162 {
11163 	int i;
11164 	int rval = 0;
11165 
11166 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
11167 
11168 	/*
11169 	 * If already reserved no need to do it again.
11170 	 * Also if Reserve and Release are disabled Just return.
11171 	 */
11172 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ||
11173 	    (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
11174 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11175 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
11176 		    st_print_scsi_cmd((uchar_t)cdb[0]));
11177 		return (0);
11178 	}
11179 
11180 	/* See if command is on the list */
11181 	for (i = 0; i < ST_NUM_MEMBERS(rcmds); i++) {
11182 		if ((uchar_t)cdb[0] == rcmds[i].cmd) {
11183 			/*
11184 			 * cmd is on list.
11185 			 * if byte is zero always allowed.
11186 			 */
11187 			if (rcmds[i].byte == 0) {
11188 				return (rval);
11189 			}
11190 			if (((cdb[rcmds[i].byte]) & (rcmds[i].mask)) == 0) {
11191 				return (rval);
11192 			}
11193 			break;
11194 		}
11195 	}
11196 
11197 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11198 	    "Command %s requires reservation", st_print_scsi_cmd(cdb[0]));
11199 
11200 	rval = st_do_reserve(un);
11201 
11202 	return (rval);
11203 }
11204 
11205 static int
11206 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
11207 {
11208 	int i;
11209 	int rval = 0;
11210 
11211 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
11212 
11213 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ||
11214 	    (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
11215 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11216 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
11217 		    st_print_scsi_cmd(cmd));
11218 		return (0);
11219 	}
11220 
11221 	/* See if command is on the list */
11222 	for (i = 0; i < ST_NUM_MEMBERS(rcmds); i++) {
11223 		if (cmd == rcmds[i].cmd) {
11224 			/*
11225 			 * cmd is on list.
11226 			 * if byte is zero always allowed.
11227 			 */
11228 			if (rcmds[i].byte == 0) {
11229 				return (rval);
11230 			}
11231 			if (((rcmds[i].mask) & cnt) == 0) {
11232 				return (rval);
11233 			}
11234 			break;
11235 		}
11236 	}
11237 
11238 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11239 	    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
11240 
11241 	rval = st_do_reserve(un);
11242 
11243 	return (rval);
11244 }
11245 
11246 static int
11247 st_reserve_release(struct scsi_tape *un, int cmd)
11248 {
11249 	struct uscsi_cmd	uscsi_cmd;
11250 	struct uscsi_cmd	*com = &uscsi_cmd;
11251 	int			rval;
11252 	char			cdb[CDB_GROUP0];
11253 
11254 
11255 
11256 	ST_FUNC(ST_DEVINFO, st_reserve_release);
11257 
11258 	ASSERT(mutex_owned(ST_MUTEX));
11259 
11260 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11261 	    "st_reserve_release: %s \n",
11262 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
11263 
11264 	bzero(cdb, CDB_GROUP0);
11265 	if (cmd == ST_RELEASE) {
11266 		cdb[0] = SCMD_RELEASE;
11267 	} else {
11268 		cdb[0] = SCMD_RESERVE;
11269 	}
11270 	bzero(com, sizeof (struct uscsi_cmd));
11271 	com->uscsi_flags = USCSI_WRITE;
11272 	com->uscsi_cdb = cdb;
11273 	com->uscsi_cdblen = CDB_GROUP0;
11274 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11275 
11276 	rval = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
11277 
11278 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11279 	    "st_reserve_release: rval(1)=%d\n", rval);
11280 
11281 	if (rval) {
11282 		if (com->uscsi_status == STATUS_RESERVATION_CONFLICT) {
11283 			rval = EACCES;
11284 		}
11285 		/*
11286 		 * dynamically turn off reserve/release support
11287 		 * in case of drives which do not support
11288 		 * reserve/release command(ATAPI drives).
11289 		 */
11290 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
11291 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
11292 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
11293 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11294 				    "Tape unit does not support "
11295 				    "reserve/release \n");
11296 			}
11297 			rval = 0;
11298 		}
11299 	}
11300 	return (rval);
11301 }
11302 
11303 static int
11304 st_take_ownership(dev_t dev)
11305 {
11306 	int rval;
11307 
11308 	GET_SOFT_STATE(dev);
11309 
11310 	ST_FUNC(ST_DEVINFO, st_take_ownership);
11311 
11312 	ASSERT(mutex_owned(ST_MUTEX));
11313 
11314 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11315 	    "st_take_ownership: Entering ...\n");
11316 
11317 
11318 	rval = st_reserve_release(un, ST_RESERVE);
11319 	/*
11320 	 * XXX -> Should reset be done only if we get EACCES.
11321 	 * .
11322 	 */
11323 	if (rval) {
11324 		mutex_exit(ST_MUTEX);
11325 		if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
11326 			if (scsi_reset(ROUTE, RESET_ALL) == 0) {
11327 				mutex_enter(ST_MUTEX);
11328 				return (EIO);
11329 			}
11330 		}
11331 		mutex_enter(ST_MUTEX);
11332 		un->un_rsvd_status &=
11333 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
11334 
11335 		mutex_exit(ST_MUTEX);
11336 		delay(drv_usectohz(ST_RESERVATION_DELAY));
11337 		mutex_enter(ST_MUTEX);
11338 		/*
11339 		 * remove the check condition.
11340 		 */
11341 		(void) st_reserve_release(un, ST_RESERVE);
11342 		if ((rval = st_reserve_release(un, ST_RESERVE)) != 0) {
11343 			if ((st_reserve_release(un, ST_RESERVE)) != 0) {
11344 				rval = (un->un_rsvd_status &
11345 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
11346 				return (rval);
11347 			}
11348 		}
11349 		/*
11350 		 * Set tape state to ST_STATE_OFFLINE , in case if
11351 		 * the user wants to continue and start using
11352 		 * the tape.
11353 		 */
11354 		un->un_state = ST_STATE_OFFLINE;
11355 		un->un_rsvd_status |= ST_INIT_RESERVE;
11356 	}
11357 	return (rval);
11358 }
11359 
11360 static int
11361 st_create_errstats(struct scsi_tape *un, int instance)
11362 {
11363 	char	kstatname[KSTAT_STRLEN];
11364 
11365 	ST_FUNC(ST_DEVINFO, st_create_errstats);
11366 
11367 	/*
11368 	 * Create device error kstats
11369 	 */
11370 
11371 	if (un->un_errstats == (kstat_t *)0) {
11372 		(void) sprintf(kstatname, "st%d,err", instance);
11373 		un->un_errstats = kstat_create("sterr", instance, kstatname,
11374 		    "device_error", KSTAT_TYPE_NAMED,
11375 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
11376 		    KSTAT_FLAG_PERSISTENT);
11377 
11378 		if (un->un_errstats) {
11379 			struct st_errstats	*stp;
11380 
11381 			stp = (struct st_errstats *)un->un_errstats->ks_data;
11382 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
11383 			    KSTAT_DATA_ULONG);
11384 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
11385 			    KSTAT_DATA_ULONG);
11386 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
11387 			    KSTAT_DATA_ULONG);
11388 			kstat_named_init(&stp->st_vid, "Vendor",
11389 			    KSTAT_DATA_CHAR);
11390 			kstat_named_init(&stp->st_pid, "Product",
11391 			    KSTAT_DATA_CHAR);
11392 			kstat_named_init(&stp->st_revision, "Revision",
11393 			    KSTAT_DATA_CHAR);
11394 			kstat_named_init(&stp->st_serial, "Serial No",
11395 			    KSTAT_DATA_CHAR);
11396 			un->un_errstats->ks_private = un;
11397 			un->un_errstats->ks_update = nulldev;
11398 			kstat_install(un->un_errstats);
11399 			/*
11400 			 * Fill in the static data
11401 			 */
11402 			(void) strncpy(&stp->st_vid.value.c[0],
11403 			    ST_INQUIRY->inq_vid, 8);
11404 			/*
11405 			 * XXX:  Emulex MT-02 (and emulators) predates
11406 			 *	 SCSI-1 and has no vid & pid inquiry data.
11407 			 */
11408 			if (ST_INQUIRY->inq_len != 0) {
11409 				(void) strncpy(&stp->st_pid.value.c[0],
11410 				    ST_INQUIRY->inq_pid, 16);
11411 				(void) strncpy(&stp->st_revision.value.c[0],
11412 				    ST_INQUIRY->inq_revision, 4);
11413 				(void) strncpy(&stp->st_serial.value.c[0],
11414 				    ST_INQUIRY->inq_serial, 12);
11415 			}
11416 		}
11417 	}
11418 	return (0);
11419 }
11420 
11421 static int
11422 st_validate_tapemarks(struct scsi_tape *un, tapepos_t *pos)
11423 {
11424 	dev_t dev;
11425 	int rval;
11426 
11427 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
11428 
11429 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
11430 	ASSERT(mutex_owned(ST_MUTEX));
11431 
11432 	/* Can't restore an invalid position */
11433 	if (pos->pmode == invalid) {
11434 		return (4);
11435 	}
11436 
11437 	/*
11438 	 * Assumtions:
11439 	 *	If a position was read and is in logical position mode.
11440 	 *	If a drive supports read position it supports locate.
11441 	 *	If the read position type is not NO_POS. even though
11442 	 *	   a read position make not have been attemped yet.
11443 	 *
11444 	 *	The drive can locate to the position.
11445 	 */
11446 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
11447 		/*
11448 		 * If position mode is logical or legacy mode try
11449 		 * to locate there as it is faster.
11450 		 * If it fails try the old way.
11451 		 */
11452 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11453 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
11454 		    pos->lgclblkno);
11455 
11456 		if (st_logical_block_locate(un, pos->lgclblkno, pos->partition)
11457 		    == 0) {
11458 			/* Assume we are there copy rest of position back */
11459 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
11460 				COPY_POS(&un->un_pos, pos);
11461 			}
11462 			return (0);
11463 		}
11464 
11465 		/*
11466 		 * If logical block locate failed to restore a logical
11467 		 * position, can't recover.
11468 		 */
11469 		if (pos->pmode == logical) {
11470 			return (-1);
11471 		}
11472 	}
11473 
11474 	dev = un->un_dev;
11475 
11476 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11477 	    "Restoring tape position at fileno=%x, blkno=%x....",
11478 	    pos->fileno, pos->blkno);
11479 
11480 	/*
11481 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
11482 	 * so as not to rewind tape on RESETS: Gee, Has life ever
11483 	 * been simple in tape land ?
11484 	 */
11485 	rval = st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
11486 	if (rval) {
11487 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
11488 		"Failed to restore the last file and block position: In"
11489 		" this state, Tape will be loaded at BOT during next open");
11490 		un->un_pos.pmode = invalid;
11491 		return (rval);
11492 	}
11493 
11494 	/* If the position was as the result of back space file */
11495 	if (pos->blkno > (INF / 2)) {
11496 		/* Go one extra file forward */
11497 		pos->fileno++;
11498 		/* Figure how many blocks to back into the previous file */
11499 		pos->blkno = -(INF - pos->blkno);
11500 	}
11501 
11502 	/* Go to requested fileno */
11503 	if (pos->fileno) {
11504 		rval = st_cmd(dev, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
11505 		if (rval) {
11506 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11507 			    "Failed to restore the last file position: In this "
11508 			    " state, Tape will be loaded at BOT during next"
11509 			    " open %d", __LINE__);
11510 			un->un_pos.pmode = invalid;
11511 			pos->pmode = invalid;
11512 			return (rval);
11513 		}
11514 	}
11515 
11516 	/*
11517 	 * If backing into a file we already did an extra file forward.
11518 	 * Now we have to back over the filemark to get to the end of
11519 	 * the previous file. The blkno has been ajusted to a negative
11520 	 * value so we will get to the expected location.
11521 	 */
11522 	if (pos->blkno) {
11523 		rval = st_cmd(dev, SCMD_SPACE, Fmk(-1), SYNC_CMD);
11524 		if (rval) {
11525 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11526 			    "Failed to restore the last file position: In this "
11527 			    " state, Tape will be loaded at BOT during next"
11528 			    " open %d", __LINE__);
11529 			un->un_pos.pmode = invalid;
11530 			pos->pmode = invalid;
11531 			return (rval);
11532 		}
11533 	}
11534 
11535 	/*
11536 	 * The position mode, block and fileno should be correct,
11537 	 * This updates eof and logical position information.
11538 	 */
11539 	un->un_pos.eof = pos->eof;
11540 	un->un_pos.lgclblkno = pos->lgclblkno;
11541 
11542 	return (0);
11543 }
11544 
11545 /*
11546  * check sense key, ASC, ASCQ in order to determine if the tape needs
11547  * to be ejected
11548  */
11549 
11550 static int
11551 st_check_asc_ascq(struct scsi_tape *un)
11552 {
11553 	struct scsi_extended_sense *sensep = ST_RQSENSE;
11554 	struct tape_failure_code   *code;
11555 
11556 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
11557 
11558 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
11559 		if ((code->key  == sensep->es_key) &&
11560 		    (code->add_code  == sensep->es_add_code) &&
11561 		    (code->qual_code == sensep->es_qual_code))
11562 			return (1);
11563 	}
11564 	return (0);
11565 }
11566 
11567 /*
11568  * st_logpage_supported() sends a Log Sense command with
11569  * page code = 0 = Supported Log Pages Page to the device,
11570  * to see whether the page 'page' is supported.
11571  * Return values are:
11572  * -1 if the Log Sense command fails
11573  * 0 if page is not supported
11574  * 1 if page is supported
11575  */
11576 
11577 static int
11578 st_logpage_supported(dev_t dev, uchar_t page)
11579 {
11580 	uchar_t *sp, *sensep;
11581 	unsigned length;
11582 	struct uscsi_cmd *com;
11583 	int rval;
11584 	char cdb[CDB_GROUP1] = {
11585 		SCMD_LOG_SENSE_G1,
11586 		0,
11587 		SUPPORTED_LOG_PAGES_PAGE,
11588 		0,
11589 		0,
11590 		0,
11591 		0,
11592 		0,
11593 		(char)LOG_SENSE_LENGTH,
11594 		0
11595 	};
11596 
11597 	GET_SOFT_STATE(dev);
11598 
11599 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
11600 
11601 	ASSERT(mutex_owned(ST_MUTEX));
11602 
11603 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11604 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
11605 
11606 	com->uscsi_cdb = cdb;
11607 	com->uscsi_cdblen = CDB_GROUP1;
11608 	com->uscsi_bufaddr = (caddr_t)sensep;
11609 	com->uscsi_buflen = LOG_SENSE_LENGTH;
11610 	com->uscsi_flags =
11611 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11612 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11613 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11614 	if (rval || com->uscsi_status) {
11615 		/* uscsi-command failed */
11616 		rval = -1;
11617 	} else {
11618 
11619 		sp = sensep + 3;
11620 
11621 		for (length = *sp++; length > 0; length--, sp++) {
11622 
11623 			if (*sp == page) {
11624 				rval = 1;
11625 				break;
11626 			}
11627 		}
11628 	}
11629 	kmem_free(com, sizeof (struct uscsi_cmd));
11630 	kmem_free(sensep, LOG_SENSE_LENGTH);
11631 	return (rval);
11632 }
11633 
11634 
11635 /*
11636  * st_check_clean_bit() gets the status of the tape's cleaning bit.
11637  *
11638  * If the device does support the TapeAlert log page, then the cleaning bit
11639  * information will be read from this page. Otherwise we will see if one of
11640  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
11641  * the device, which means, that we can get the cleaning bit information via
11642  * a RequestSense command.
11643  * If both methods of getting cleaning bit information are not supported
11644  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
11645  * returns with
11646  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
11647  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
11648  * If the call to st_ioctl_cmd() to do the Log Sense or the Request Sense
11649  * command fails, or if the amount of Request Sense data is not enough, then
11650  *  st_check_clean_bit() returns with -1.
11651  */
11652 
11653 static int
11654 st_check_clean_bit(dev_t dev)
11655 {
11656 	int rval = 0;
11657 
11658 	GET_SOFT_STATE(dev);
11659 
11660 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
11661 
11662 	ASSERT(mutex_owned(ST_MUTEX));
11663 
11664 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
11665 		return (rval);
11666 	}
11667 
11668 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
11669 
11670 		rval = st_logpage_supported(dev, TAPE_SEQUENTIAL_PAGE);
11671 		if (rval == 1) {
11672 
11673 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
11674 		}
11675 
11676 		rval = st_logpage_supported(dev, TAPE_ALERT_PAGE);
11677 		if (rval == 1) {
11678 
11679 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
11680 		}
11681 
11682 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
11683 
11684 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
11685 		}
11686 	}
11687 
11688 	rval = 0;
11689 
11690 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
11691 
11692 		rval = st_check_sequential_clean_bit(dev);
11693 	}
11694 
11695 	if ((rval <= 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
11696 
11697 		rval = st_check_alert_flags(dev);
11698 	}
11699 
11700 	if ((rval <= 0) && (un->un_dp->options & ST_CLN_MASK)) {
11701 
11702 		rval = st_check_sense_clean_bit(dev);
11703 	}
11704 
11705 	if (rval < 0) {
11706 		return (rval);
11707 	}
11708 
11709 	/*
11710 	 * If found a supported means to check need to clean.
11711 	 */
11712 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
11713 
11714 		/*
11715 		 * head needs to be cleaned.
11716 		 */
11717 		if (rval & MTF_TAPE_HEAD_DIRTY) {
11718 
11719 			/*
11720 			 * Print log message only first time
11721 			 * found needing cleaned.
11722 			 */
11723 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
11724 
11725 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
11726 				    "Periodic head cleaning required");
11727 
11728 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
11729 			}
11730 
11731 		} else {
11732 
11733 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
11734 		}
11735 	}
11736 
11737 	return (rval);
11738 }
11739 
11740 
11741 static int
11742 st_check_sequential_clean_bit(dev_t dev)
11743 {
11744 	int rval;
11745 	int ix;
11746 	ushort_t parameter;
11747 	struct uscsi_cmd *cmd;
11748 	struct log_sequential_page *sp;
11749 	struct log_sequential_page_parameter *prm;
11750 	char cdb[CDB_GROUP1] = {
11751 		SCMD_LOG_SENSE_G1,
11752 		0,
11753 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
11754 		0,
11755 		0,
11756 		0,
11757 		0,
11758 		(char)(sizeof (struct log_sequential_page) >> 8),
11759 		(char)(sizeof (struct log_sequential_page)),
11760 		0
11761 	};
11762 
11763 	GET_SOFT_STATE(dev);
11764 
11765 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
11766 
11767 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11768 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
11769 
11770 	cmd->uscsi_flags   =
11771 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11772 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
11773 	cmd->uscsi_cdb	   = cdb;
11774 	cmd->uscsi_cdblen  = CDB_GROUP1;
11775 	cmd->uscsi_bufaddr = (caddr_t)sp;
11776 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
11777 
11778 	rval = st_ioctl_cmd(dev, cmd, FKIOCTL);
11779 
11780 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
11781 
11782 		rval = -1;
11783 
11784 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
11785 
11786 		rval = -1;
11787 	}
11788 
11789 	prm = &sp->param[0];
11790 
11791 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
11792 
11793 		if (prm->log_param.length == 0) {
11794 			break;
11795 		}
11796 
11797 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
11798 		    (prm->log_param.pc_lo & 0xff));
11799 
11800 		if (parameter == SEQUENTIAL_NEED_CLN) {
11801 
11802 			rval = MTF_TAPE_CLN_SUPPORTED;
11803 			if (prm->param_value[prm->log_param.length - 1]) {
11804 
11805 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11806 				    "sequential log says head dirty\n");
11807 				rval |= MTF_TAPE_HEAD_DIRTY;
11808 			}
11809 		}
11810 		prm = (struct log_sequential_page_parameter *)
11811 		    &prm->param_value[prm->log_param.length];
11812 	}
11813 
11814 	kmem_free(cmd, sizeof (struct uscsi_cmd));
11815 	kmem_free(sp,  sizeof (struct log_sequential_page));
11816 
11817 	return (rval);
11818 }
11819 
11820 
11821 static int
11822 st_check_alert_flags(dev_t dev)
11823 {
11824 	struct st_tape_alert *ta;
11825 	struct uscsi_cmd *com;
11826 	unsigned ix, length;
11827 	int rval;
11828 	tape_alert_flags flag;
11829 	char cdb[CDB_GROUP1] = {
11830 		SCMD_LOG_SENSE_G1,
11831 		0,
11832 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
11833 		0,
11834 		0,
11835 		0,
11836 		0,
11837 		(char)(sizeof (struct st_tape_alert) >> 8),
11838 		(char)(sizeof (struct st_tape_alert)),
11839 		0
11840 	};
11841 
11842 	GET_SOFT_STATE(dev);
11843 
11844 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
11845 
11846 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11847 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
11848 
11849 	com->uscsi_cdb = cdb;
11850 	com->uscsi_cdblen = CDB_GROUP1;
11851 	com->uscsi_bufaddr = (caddr_t)ta;
11852 	com->uscsi_buflen = sizeof (struct st_tape_alert);
11853 	com->uscsi_flags =
11854 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11855 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11856 
11857 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11858 
11859 	if (rval || com->uscsi_status || com->uscsi_resid) {
11860 
11861 		rval = -1; /* uscsi-command failed */
11862 
11863 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
11864 
11865 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11866 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
11867 		rval = -1;
11868 	}
11869 
11870 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
11871 
11872 
11873 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
11874 
11875 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11876 		    "TapeAlert length %d\n", length);
11877 	}
11878 
11879 
11880 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
11881 
11882 		/*
11883 		 * if rval is bad before the first pass don't bother
11884 		 */
11885 		if (ix == 0 && rval != 0) {
11886 
11887 			break;
11888 		}
11889 
11890 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
11891 		    ta->param[ix].log_param.pc_lo);
11892 
11893 		if ((ta->param[ix].param_value & 1) == 0) {
11894 			continue;
11895 		}
11896 		/*
11897 		 * check to see if current parameter is of interest.
11898 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
11899 		 */
11900 		if ((flag == TAF_CLEAN_NOW) ||
11901 		    (flag == TAF_CLEAN_PERIODIC) ||
11902 		    ((flag == CLEAN_FOR_ERRORS) &&
11903 		    (un->un_dp->type == ST_TYPE_STK9840))) {
11904 
11905 			rval = MTF_TAPE_CLN_SUPPORTED;
11906 
11907 
11908 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11909 			    "alert_page drive needs clean %d\n", flag);
11910 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
11911 			rval |= MTF_TAPE_HEAD_DIRTY;
11912 
11913 		} else if (flag == TAF_CLEANING_MEDIA) {
11914 
11915 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11916 			    "alert_page drive was cleaned\n");
11917 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
11918 		}
11919 
11920 	}
11921 
11922 	/*
11923 	 * Report it as dirty till we see it cleaned
11924 	 */
11925 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
11926 
11927 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11928 		    "alert_page still dirty\n");
11929 		rval |= MTF_TAPE_HEAD_DIRTY;
11930 	}
11931 
11932 	kmem_free(com, sizeof (struct uscsi_cmd));
11933 	kmem_free(ta,  sizeof (struct st_tape_alert));
11934 
11935 	return (rval);
11936 }
11937 
11938 
11939 static int
11940 st_check_sense_clean_bit(dev_t dev)
11941 {
11942 	uchar_t *sensep;
11943 	char cdb[CDB_GROUP0];
11944 	struct uscsi_cmd *com;
11945 	ushort_t byte_pos;
11946 	uchar_t bit_mask;
11947 	unsigned length;
11948 	int index;
11949 	int rval;
11950 
11951 	GET_SOFT_STATE(dev);
11952 
11953 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
11954 
11955 	/*
11956 	 * Since this tape does not support Tape Alert,
11957 	 * we now try to get the cleanbit status via
11958 	 * Request Sense.
11959 	 */
11960 
11961 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
11962 
11963 		index = 0;
11964 
11965 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
11966 
11967 		index = 1;
11968 
11969 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
11970 
11971 		index = 2;
11972 
11973 	} else {
11974 
11975 		return (-1);
11976 	}
11977 
11978 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
11979 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
11980 	length = byte_pos + 1;
11981 
11982 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11983 	sensep = kmem_zalloc(length, KM_SLEEP);
11984 
11985 	cdb[0] = SCMD_REQUEST_SENSE;
11986 	cdb[1] = 0;
11987 	cdb[2] = 0;
11988 	cdb[3] = 0;
11989 	cdb[4] = (char)length;
11990 	cdb[5] = 0;
11991 
11992 	com->uscsi_cdb = cdb;
11993 	com->uscsi_cdblen = CDB_GROUP0;
11994 	com->uscsi_bufaddr = (caddr_t)sensep;
11995 	com->uscsi_buflen = length;
11996 	com->uscsi_flags =
11997 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11998 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11999 
12000 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
12001 
12002 	if (rval || com->uscsi_status || com->uscsi_resid) {
12003 
12004 		rval = -1;
12005 
12006 	} else {
12007 
12008 		rval = MTF_TAPE_CLN_SUPPORTED;
12009 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
12010 
12011 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12012 			    "sense data says head dirty\n");
12013 			rval |= MTF_TAPE_HEAD_DIRTY;
12014 		}
12015 	}
12016 
12017 	kmem_free(com, sizeof (struct uscsi_cmd));
12018 	kmem_free(sensep, length);
12019 	return (rval);
12020 }
12021 
12022 /*
12023  * st_clear_unit_attention
12024  *
12025  *  	run test unit ready's to clear out outstanding
12026  * 	unit attentions.
12027  * 	returns zero for SUCCESS or the errno from st_cmd call
12028  */
12029 static int
12030 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
12031 {
12032 	int	i    = 0;
12033 	int	rval;
12034 
12035 #ifdef DEBUG
12036 	GET_SOFT_STATE(dev_instance);
12037 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
12038 #endif
12039 
12040 	do {
12041 		rval = st_cmd(dev_instance, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
12042 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
12043 	return (rval);
12044 }
12045 
12046 static void
12047 st_calculate_timeouts(struct scsi_tape *un)
12048 {
12049 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
12050 
12051 	if (un->un_dp->non_motion_timeout == 0) {
12052 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12053 			un->un_dp->non_motion_timeout =
12054 			    st_io_time * st_long_timeout_x;
12055 		} else {
12056 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
12057 		}
12058 	}
12059 
12060 	if (un->un_dp->io_timeout == 0) {
12061 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12062 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
12063 		} else {
12064 			un->un_dp->io_timeout = (ushort_t)st_io_time;
12065 		}
12066 	}
12067 
12068 	if (un->un_dp->rewind_timeout == 0) {
12069 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12070 			un->un_dp->rewind_timeout =
12071 			    st_space_time * st_long_timeout_x;
12072 		} else {
12073 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
12074 		}
12075 	}
12076 
12077 	if (un->un_dp->space_timeout == 0) {
12078 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12079 			un->un_dp->space_timeout =
12080 			    st_space_time * st_long_timeout_x;
12081 		} else {
12082 			un->un_dp->space_timeout = (ushort_t)st_space_time;
12083 		}
12084 	}
12085 
12086 	if (un->un_dp->load_timeout == 0) {
12087 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12088 			un->un_dp->load_timeout =
12089 			    st_space_time * st_long_timeout_x;
12090 		} else {
12091 			un->un_dp->load_timeout = (ushort_t)st_space_time;
12092 		}
12093 	}
12094 
12095 	if (un->un_dp->unload_timeout == 0) {
12096 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12097 			un->un_dp->unload_timeout =
12098 			    st_space_time * st_long_timeout_x;
12099 		} else {
12100 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
12101 		}
12102 	}
12103 
12104 	if (un->un_dp->erase_timeout == 0) {
12105 		if (un->un_dp->options & ST_LONG_ERASE) {
12106 			un->un_dp->erase_timeout =
12107 			    st_space_time * st_long_space_time_x;
12108 		} else {
12109 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
12110 		}
12111 	}
12112 }
12113 
12114 
12115 static writablity
12116 st_is_not_wormable(struct scsi_tape *un)
12117 {
12118 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
12119 	return (RDWR);
12120 }
12121 
12122 static writablity
12123 st_is_hp_dat_tape_worm(struct scsi_tape *un)
12124 {
12125 	writablity wrt;
12126 
12127 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
12128 
12129 	/* Mode sense should be current */
12130 	if (un->un_mspl->media_type == 1) {
12131 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12132 		    "Drive has WORM media loaded\n");
12133 		wrt = WORM;
12134 	} else {
12135 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12136 		    "Drive has non WORM media loaded\n");
12137 		wrt = RDWR;
12138 	}
12139 	return (wrt);
12140 }
12141 
12142 #define	HP_DAT_INQUIRY 0x4A
12143 static writablity
12144 st_is_hp_dat_worm(struct scsi_tape *un)
12145 {
12146 	char *buf;
12147 	int result;
12148 	writablity wrt;
12149 
12150 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
12151 
12152 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
12153 
12154 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
12155 
12156 	if (result != 0) {
12157 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12158 		    "Read Standard Inquiry for WORM support failed");
12159 		wrt = FAILED;
12160 	} else if ((buf[40] & 1) == 0) {
12161 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12162 		    "Drive is NOT WORMable\n");
12163 		/* This drive doesn't support it so don't check again */
12164 		un->un_dp->options &= ~ST_WORMABLE;
12165 		wrt = RDWR;
12166 		un->un_wormable = st_is_not_wormable;
12167 	} else {
12168 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12169 		    "Drive supports WORM version %d\n", buf[40] >> 1);
12170 		un->un_wormable = st_is_hp_dat_tape_worm;
12171 		wrt = un->un_wormable(un);
12172 	}
12173 
12174 	kmem_free(buf, HP_DAT_INQUIRY);
12175 
12176 	/*
12177 	 * If drive doesn't support it no point in checking further.
12178 	 */
12179 	return (wrt);
12180 }
12181 
12182 static writablity
12183 st_is_hp_lto_tape_worm(struct scsi_tape *un)
12184 {
12185 	writablity wrt;
12186 
12187 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
12188 
12189 	/* Mode sense should be current */
12190 	switch (un->un_mspl->media_type) {
12191 	case 0x00:
12192 		switch (un->un_mspl->density) {
12193 		case 0x40:
12194 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12195 			    "Drive has standard Gen I media loaded\n");
12196 			break;
12197 		case 0x42:
12198 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12199 			    "Drive has standard Gen II media loaded\n");
12200 			break;
12201 		case 0x44:
12202 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12203 			    "Drive has standard Gen III media loaded\n");
12204 			break;
12205 		case 0x46:
12206 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12207 			    "Drive has standard Gen IV media loaded\n");
12208 			break;
12209 		default:
12210 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12211 			    "Drive has standard unknown 0x%X media loaded\n",
12212 			    un->un_mspl->density);
12213 		}
12214 		wrt = RDWR;
12215 		break;
12216 	case 0x01:
12217 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12218 		    "Drive has WORM medium loaded\n");
12219 		wrt = WORM;
12220 		break;
12221 	case 0x80:
12222 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12223 		    "Drive has CD-ROM emulation medium loaded\n");
12224 		wrt = WORM;
12225 		break;
12226 	default:
12227 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12228 		    "Drive has an unexpected medium type 0x%X loaded\n",
12229 		    un->un_mspl->media_type);
12230 		wrt = RDWR;
12231 	}
12232 
12233 	return (wrt);
12234 }
12235 
12236 #define	LTO_REQ_INQUIRY 44
12237 static writablity
12238 st_is_hp_lto_worm(struct scsi_tape *un)
12239 {
12240 	char *buf;
12241 	int result;
12242 	writablity wrt;
12243 
12244 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
12245 
12246 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
12247 
12248 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
12249 
12250 	if (result != 0) {
12251 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12252 		    "Read Standard Inquiry for WORM support failed");
12253 		wrt = FAILED;
12254 	} else if ((buf[40] & 1) == 0) {
12255 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12256 		    "Drive is NOT WORMable\n");
12257 		/* This drive doesn't support it so don't check again */
12258 		un->un_dp->options &= ~ST_WORMABLE;
12259 		wrt = RDWR;
12260 		un->un_wormable = st_is_not_wormable;
12261 	} else {
12262 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12263 		    "Drive supports WORM version %d\n", buf[40] >> 1);
12264 		un->un_wormable = st_is_hp_lto_tape_worm;
12265 		wrt = un->un_wormable(un);
12266 	}
12267 
12268 	kmem_free(buf, LTO_REQ_INQUIRY);
12269 
12270 	/*
12271 	 * If drive doesn't support it no point in checking further.
12272 	 */
12273 	return (wrt);
12274 }
12275 
12276 static writablity
12277 st_is_t10_worm_device(struct scsi_tape *un)
12278 {
12279 	writablity wrt;
12280 
12281 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
12282 
12283 	if (un->un_mspl->media_type == 0x3c) {
12284 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12285 		    "Drive has WORM media loaded\n");
12286 		wrt = WORM;
12287 	} else {
12288 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12289 		    "Drive has non WORM media loaded\n");
12290 		wrt = RDWR;
12291 	}
12292 	return (wrt);
12293 }
12294 
12295 #define	SEQ_CAP_PAGE	(char)0xb0
12296 static writablity
12297 st_is_t10_worm(struct scsi_tape *un)
12298 {
12299 	char *buf;
12300 	int result;
12301 	writablity wrt;
12302 
12303 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
12304 
12305 	buf = kmem_zalloc(6, KM_SLEEP);
12306 
12307 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
12308 
12309 	if (result != 0) {
12310 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12311 		    "Read Vitial Inquiry for Sequental Capability"
12312 		    " WORM support failed %x", result);
12313 		wrt = FAILED;
12314 	} else if ((buf[4] & 1) == 0) {
12315 		ASSERT(buf[1] == SEQ_CAP_PAGE);
12316 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12317 		    "Drive is NOT WORMable\n");
12318 		/* This drive doesn't support it so don't check again */
12319 		un->un_dp->options &= ~ST_WORMABLE;
12320 		wrt = RDWR;
12321 		un->un_wormable = st_is_not_wormable;
12322 	} else {
12323 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12324 		    "Drive supports WORM\n");
12325 		un->un_wormable = st_is_t10_worm_device;
12326 		wrt = un->un_wormable(un);
12327 	}
12328 
12329 	kmem_free(buf, 6);
12330 
12331 	return (wrt);
12332 }
12333 
12334 
12335 #define	STK_REQ_SENSE 26
12336 
12337 static writablity
12338 st_is_stk_worm(struct scsi_tape *un)
12339 {
12340 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
12341 	struct scsi_extended_sense *sense;
12342 	struct uscsi_cmd *cmd;
12343 	char *buf;
12344 	int result;
12345 	writablity wrt;
12346 
12347 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
12348 
12349 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12350 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
12351 	sense = (struct scsi_extended_sense *)buf;
12352 
12353 	cmd->uscsi_flags = USCSI_READ;
12354 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12355 	cmd->uscsi_cdb = &cdb[0];
12356 	cmd->uscsi_bufaddr = buf;
12357 	cmd->uscsi_buflen = STK_REQ_SENSE;
12358 	cmd->uscsi_cdblen = CDB_GROUP0;
12359 	cmd->uscsi_rqlen = 0;
12360 	cmd->uscsi_rqbuf = NULL;
12361 
12362 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
12363 
12364 	if (result != 0 || cmd->uscsi_status != 0) {
12365 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12366 		    "Request Sense for WORM failed");
12367 		wrt = RDWR;
12368 	} else if (sense->es_add_len + 8 < 24) {
12369 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12370 		    "Drive didn't send enough sense data for WORM byte %d\n",
12371 		    sense->es_add_len + 8);
12372 		wrt = RDWR;
12373 		un->un_wormable = st_is_not_wormable;
12374 	} else if ((buf[24]) & 0x02) {
12375 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12376 		    "Drive has WORM tape loaded\n");
12377 		wrt = WORM;
12378 		un->un_wormable = st_is_stk_worm;
12379 	} else {
12380 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12381 		    "Drive has normal tape loaded\n");
12382 		wrt = RDWR;
12383 		un->un_wormable = st_is_stk_worm;
12384 	}
12385 
12386 	kmem_free(buf, STK_REQ_SENSE);
12387 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12388 	return (wrt);
12389 }
12390 
12391 #define	DLT_INQ_SZ 44
12392 
12393 static writablity
12394 st_is_dlt_tape_worm(struct scsi_tape *un)
12395 {
12396 	caddr_t buf;
12397 	int result;
12398 	writablity wrt;
12399 
12400 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
12401 
12402 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
12403 
12404 	/* Read Attribute Media Type */
12405 
12406 	result = st_read_attributes(un, 0x0408, buf, 10);
12407 
12408 	/*
12409 	 * If this quantum drive is attached via an HBA that cannot
12410 	 * support thr read attributes command return error in the
12411 	 * hope that someday they will support the t10 method.
12412 	 */
12413 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
12414 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12415 		    "Read Attribute Command for WORM Media detection is not "
12416 		    "supported on the HBA that this drive is attached to.");
12417 		wrt = RDWR;
12418 		un->un_wormable = st_is_not_wormable;
12419 		goto out;
12420 	}
12421 
12422 	if (result != 0) {
12423 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12424 		    "Read Attribute Command for WORM Media returned 0x%x",
12425 		    result);
12426 		wrt = RDWR;
12427 		un->un_dp->options &= ~ST_WORMABLE;
12428 		goto out;
12429 	}
12430 
12431 	if ((uchar_t)buf[9] == 0x80) {
12432 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12433 		    "Drive media is WORM\n");
12434 		wrt = WORM;
12435 	} else {
12436 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12437 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
12438 		wrt = RDWR;
12439 	}
12440 
12441 out:
12442 	kmem_free(buf, DLT_INQ_SZ);
12443 	return (wrt);
12444 }
12445 
12446 static writablity
12447 st_is_dlt_worm(struct scsi_tape *un)
12448 {
12449 	caddr_t buf;
12450 	int result;
12451 	writablity wrt;
12452 
12453 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
12454 
12455 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
12456 
12457 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
12458 
12459 	if (result != 0) {
12460 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12461 		    "Read Vendor Specific Inquiry for WORM support failed");
12462 		wrt = RDWR;
12463 		goto out;
12464 	}
12465 
12466 	if ((buf[2] & 1) == 0) {
12467 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12468 		    "Drive is not WORMable\n");
12469 		wrt = RDWR;
12470 		un->un_dp->options &= ~ST_WORMABLE;
12471 		un->un_wormable = st_is_not_wormable;
12472 		goto out;
12473 	} else {
12474 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12475 		    "Drive is WORMable\n");
12476 		un->un_wormable = st_is_dlt_tape_worm;
12477 		wrt = un->un_wormable(un);
12478 	}
12479 out:
12480 	kmem_free(buf, DLT_INQ_SZ);
12481 
12482 	return (wrt);
12483 }
12484 
12485 typedef struct {
12486 	struct modeheader_seq header;
12487 #if defined(_BIT_FIELDS_LTOH) /* X86 */
12488 	uchar_t pagecode	:6,
12489 				:2;
12490 	uchar_t page_len;
12491 	uchar_t syslogalive	:2,
12492 		device		:1,
12493 		abs		:1,
12494 		ulpbot		:1,
12495 		prth		:1,
12496 		ponej		:1,
12497 		ait		:1;
12498 	uchar_t span;
12499 
12500 	uchar_t			:6,
12501 		worm		:1,
12502 		mic		:1;
12503 	uchar_t worm_cap	:1,
12504 				:7;
12505 	uint32_t		:32;
12506 #else /* SPARC */
12507 	uchar_t			:2,
12508 		pagecode	:6;
12509 	uchar_t page_len;
12510 	uchar_t ait		:1,
12511 		device		:1,
12512 		abs		:1,
12513 		ulpbot		:1,
12514 		prth		:1,
12515 		ponej		:1,
12516 		syslogalive	:2;
12517 	uchar_t span;
12518 	uchar_t mic		:1,
12519 		worm		:1,
12520 				:6;
12521 	uchar_t			:7,
12522 		worm_cap	:1;
12523 	uint32_t		:32;
12524 #endif
12525 }ait_dev_con;
12526 
12527 #define	AIT_DEV_PAGE 0x31
12528 static writablity
12529 st_is_sony_worm(struct scsi_tape *un)
12530 {
12531 	int result;
12532 	writablity wrt;
12533 	ait_dev_con *ait_conf;
12534 
12535 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
12536 
12537 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
12538 
12539 	result = st_gen_mode_sense(un, AIT_DEV_PAGE,
12540 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
12541 
12542 	if (result == 0) {
12543 
12544 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
12545 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12546 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
12547 			    ait_conf->pagecode, AIT_DEV_PAGE);
12548 			wrt = RDWR;
12549 			un->un_wormable = st_is_not_wormable;
12550 
12551 		} else if (ait_conf->worm_cap) {
12552 
12553 			un->un_wormable = st_is_sony_worm;
12554 
12555 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12556 			    "Drives is WORMable\n");
12557 			if (ait_conf->worm) {
12558 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12559 				    "Media is WORM\n");
12560 				wrt = WORM;
12561 			} else {
12562 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12563 				    "Media is not WORM\n");
12564 				wrt = RDWR;
12565 			}
12566 
12567 		} else {
12568 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12569 			    "Drives not is WORMable\n");
12570 			wrt = RDWR;
12571 			/* No further checking required */
12572 			un->un_dp->options &= ~ST_WORMABLE;
12573 		}
12574 
12575 	} else {
12576 
12577 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12578 		    "AIT device config mode sense page read command failed"
12579 		    " result = %d ", result);
12580 		wrt = FAILED;
12581 		un->un_wormable = st_is_not_wormable;
12582 	}
12583 
12584 	kmem_free(ait_conf, sizeof (ait_dev_con));
12585 	return (wrt);
12586 }
12587 
12588 static writablity
12589 st_is_drive_worm(struct scsi_tape *un)
12590 {
12591 	writablity wrt;
12592 
12593 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
12594 
12595 	switch (un->un_dp->type) {
12596 	case MT_ISDLT:
12597 		wrt = st_is_dlt_worm(un);
12598 		break;
12599 
12600 	case MT_ISSTK9840:
12601 		wrt = st_is_stk_worm(un);
12602 		break;
12603 
12604 	case MT_IS8MM:
12605 	case MT_ISAIT:
12606 		wrt = st_is_sony_worm(un);
12607 		break;
12608 
12609 	case MT_LTO:
12610 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
12611 			wrt = st_is_hp_lto_worm(un);
12612 		} else {
12613 			wrt = st_is_t10_worm(un);
12614 		}
12615 		break;
12616 
12617 	case MT_ISDAT:
12618 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
12619 			wrt = st_is_hp_dat_worm(un);
12620 		} else {
12621 			wrt = st_is_t10_worm(un);
12622 		}
12623 		break;
12624 
12625 	default:
12626 		wrt = FAILED;
12627 		break;
12628 	}
12629 
12630 	/*
12631 	 * If any of the above failed try the t10 standard method.
12632 	 */
12633 	if (wrt == FAILED) {
12634 		wrt = st_is_t10_worm(un);
12635 	}
12636 
12637 	/*
12638 	 * Unknown method for detecting WORM media.
12639 	 */
12640 	if (wrt == FAILED) {
12641 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12642 		    "Unknown method for WORM media detection\n");
12643 		wrt = RDWR;
12644 		un->un_dp->options &= ~ST_WORMABLE;
12645 	}
12646 
12647 	return (wrt);
12648 }
12649 
12650 static int
12651 st_read_attributes(struct scsi_tape *un, uint16_t attribute, caddr_t buf,
12652     size_t size)
12653 {
12654 	char cdb[CDB_GROUP4];
12655 	int result;
12656 	struct uscsi_cmd *cmd;
12657 
12658 	ST_FUNC(ST_DEVINFO, st_read_attributes);
12659 
12660 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12661 
12662 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
12663 	cdb[1] = 0;
12664 	cdb[2] = 0;
12665 	cdb[3] = 0;
12666 	cdb[4] = 0;
12667 	cdb[5] = 0;
12668 	cdb[6] = 0;
12669 	cdb[7] = 0;
12670 	cdb[8] = (char)(attribute >> 8);
12671 	cdb[9] = (char)(attribute);
12672 	cdb[10] = (char)(size >> 24);
12673 	cdb[11] = (char)(size >> 16);
12674 	cdb[12] = (char)(size >> 8);
12675 	cdb[13] = (char)(size);
12676 	cdb[14] = 0;
12677 	cdb[15] = 0;
12678 
12679 
12680 	cmd->uscsi_flags = USCSI_READ | USCSI_DIAGNOSE;
12681 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12682 	cmd->uscsi_cdb = &cdb[0];
12683 	cmd->uscsi_bufaddr = (caddr_t)buf;
12684 	cmd->uscsi_buflen = size;
12685 	cmd->uscsi_cdblen = sizeof (cdb);
12686 
12687 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
12688 
12689 	if (result != 0 || cmd->uscsi_status != 0) {
12690 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12691 		    "st_read_attribute failed: result %d status %d\n",
12692 		    result, cmd->uscsi_status);
12693 		if (result == 0) {
12694 			result = EIO;
12695 		}
12696 		goto exit;
12697 	}
12698 
12699 	/*
12700 	 * The attribute retured should match the attribute requested.
12701 	 */
12702 	if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
12703 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
12704 		    "bad? data", buf, size);
12705 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12706 		    "st_read_attribute got wrong data back expected 0x%x"
12707 		    " got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
12708 		result = EIO;
12709 	}
12710 exit:
12711 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12712 
12713 	return (result);
12714 }
12715 
12716 static int
12717 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
12718     uchar_t page)
12719 {
12720 	char cdb[CDB_GROUP0];
12721 	struct scsi_extended_sense *sense;
12722 	struct uscsi_cmd *cmd;
12723 	int result;
12724 
12725 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
12726 
12727 	cdb[0] = SCMD_INQUIRY;
12728 	cdb[1] = page ? 1 : 0;
12729 	cdb[2] = page;
12730 	cdb[3] = 0;
12731 	cdb[4] = size;
12732 	cdb[5] = 0;
12733 
12734 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12735 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
12736 
12737 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
12738 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12739 	cmd->uscsi_cdb = &cdb[0];
12740 	cmd->uscsi_bufaddr = dest;
12741 	cmd->uscsi_buflen = size;
12742 	cmd->uscsi_cdblen = CDB_GROUP0;
12743 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
12744 	cmd->uscsi_rqbuf = (caddr_t)sense;
12745 
12746 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
12747 
12748 	if (result != 0 || cmd->uscsi_status != 0) {
12749 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12750 		    "st_get_special_inquiry() failed for page %x", page);
12751 		if (result == 0) {
12752 			result = EIO;
12753 		}
12754 	}
12755 
12756 	kmem_free(sense, sizeof (struct scsi_extended_sense));
12757 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12758 
12759 	return (result);
12760 }
12761 
12762 
12763 static int
12764 st_update_block_pos(struct scsi_tape *un)
12765 {
12766 	int rval = ENOTTY;
12767 
12768 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
12769 
12770 	while (un->un_read_pos_type != NO_POS) {
12771 		rval = st_cmd(un->un_dev, SCMD_READ_POSITION, 32, SYNC_CMD);
12772 
12773 		if (rval == 0) {
12774 			rval = st_interpret_read_pos(un, un->un_read_pos_type,
12775 			    32, (caddr_t)un->un_read_pos_data);
12776 			break;
12777 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
12778 			continue;
12779 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
12780 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12781 			    "st_update_block_pos() read position cmd %x"
12782 			    " returned %x un_status = %d",
12783 			    un->un_read_pos_type, rval, un->un_status);
12784 			break;
12785 		} else {
12786 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
12787 			    "st_update_block_pos() read position cmd %x"
12788 			    " returned %x", un->un_read_pos_type, rval);
12789 		}
12790 
12791 		switch (un->un_read_pos_type) {
12792 		case SHORT_POS:
12793 			un->un_read_pos_type = NO_POS;
12794 			break;
12795 
12796 		case LONG_POS:
12797 			un->un_read_pos_type = EXT_POS;
12798 			break;
12799 
12800 		case EXT_POS:
12801 			un->un_read_pos_type = SHORT_POS;
12802 			break;
12803 
12804 		default:
12805 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
12806 			    "Unexpected read position type 0x%x",
12807 			    un->un_read_pos_type);
12808 		}
12809 	}
12810 
12811 	return (rval);
12812 }
12813 
12814 static int
12815 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
12816 {
12817 	int result;
12818 	size_t d_sz;
12819 	caddr_t pos_info;
12820 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
12821 
12822 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
12823 
12824 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
12825 		return (0);
12826 	}
12827 
12828 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
12829 
12830 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12831 		    "bp_mapin_common() failed");
12832 
12833 		return (EIO);
12834 	}
12835 
12836 	pos_info = bp->b_un.b_addr;
12837 	d_sz = bp->b_bcount - bp->b_resid;
12838 
12839 #ifdef DEBUG
12840 	if ((st_debug & 0xf) > 2) {
12841 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
12842 		    "st_get_read_pos() position info",
12843 		    pos_info, bp->b_bcount);
12844 	}
12845 #endif
12846 
12847 	result = st_interpret_read_pos(un, cmd->uscsi_cdb[1], d_sz, pos_info);
12848 
12849 	bp_mapout(bp);
12850 
12851 	return (result);
12852 }
12853 
12854 #if defined(_BIG_ENDIAN)
12855 
12856 #define	FIX_ENDIAN32(x)
12857 #define	FIX_ENDIAN64(x)
12858 
12859 #elif defined(_LITTLE_ENDIAN)
12860 
12861 static void
12862 st_swap32(uint32_t *val)
12863 {
12864 	uint32_t tmp;
12865 
12866 	tmp =  (*val >> 24) & 0xff;
12867 	tmp |= (*val >>  8) & 0xff00;
12868 	tmp |= (*val <<  8) & 0xff0000;
12869 	tmp |= (*val << 24) & 0xff000000;
12870 
12871 	*val = tmp;
12872 }
12873 
12874 static void
12875 st_swap64(uint64_t *val)
12876 {
12877 	uint32_t low;
12878 	uint32_t high;
12879 
12880 	low =  (uint32_t)(*val);
12881 	high = (uint32_t)(*val >> 32);
12882 
12883 	st_swap32(&low);
12884 	st_swap32(&high);
12885 
12886 	*val =  high;
12887 	*val |= ((uint64_t)low << 32);
12888 }
12889 
12890 #define	FIX_ENDIAN32(x) st_swap32(x)
12891 #define	FIX_ENDIAN64(x) st_swap64(x)
12892 #endif
12893 
12894 static int
12895 st_interpret_read_pos(struct scsi_tape *un, read_p_types type,
12896     size_t data_sz, caddr_t responce)
12897 {
12898 	int rval = 0;
12899 
12900 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
12901 
12902 	/*
12903 	 * Look at byte 1 of cdb to see what kind of read position
12904 	 * was requested.
12905 	 */
12906 	switch (type) {
12907 
12908 	case SHORT_POS: /* Short data format */
12909 	{
12910 		tape_position_t *pos_info = (tape_position_t *)responce;
12911 		uint32_t value;
12912 
12913 		/* If reserved fields are non zero don't use the data */
12914 		if (pos_info->reserved0 || pos_info->reserved1 ||
12915 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
12916 		    pos_info->reserved3) {
12917 			rval = EIO;
12918 			break;
12919 		}
12920 		/*
12921 		 * Position is to large to use this type of read position.
12922 		 */
12923 		if (pos_info->posi_err == 1) {
12924 			rval = ERANGE;
12925 			break;
12926 		}
12927 
12928 		if (pos_info->blk_posi_unkwn == 0) {
12929 
12930 			if (un->un_pos.partition !=
12931 			    pos_info->partition_number) {
12932 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12933 				    "SHORT_POS current partition %d read %d\n",
12934 				    un->un_pos.partition,
12935 				    pos_info->partition_number);
12936 			}
12937 			un->un_pos.partition = pos_info->partition_number;
12938 			value = pos_info->host_block;
12939 			FIX_ENDIAN32(&value);
12940 
12941 			if (un->un_pos.lgclblkno != value) {
12942 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12943 				    "SHORT_POS current logical 0x%"PRIx64" read"
12944 				    " 0x%x\n", un->un_pos.lgclblkno, value);
12945 			}
12946 
12947 			un->un_pos.lgclblkno = (uint64_t)value;
12948 
12949 			if (pos_info->begin_of_part && pos_info->end_of_part) {
12950 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
12951 				    "SHORT_POS returned begin and end of"
12952 				    " partition\n");
12953 				break;
12954 			}
12955 			/* Is drive rewound */
12956 			if ((pos_info->begin_of_part == 1) &&
12957 			    (pos_info->host_block == 0)) {
12958 				un->un_pos.blkno = 0;
12959 				un->un_pos.fileno = 0;
12960 				un->un_pos.pmode = legacy;
12961 			} else if (un->un_pos.pmode == invalid) {
12962 				/* If we were lost now were found */
12963 				un->un_pos.pmode = logical;
12964 			}
12965 		} else {
12966 			un->un_pos.pmode = invalid;
12967 		}
12968 		break;
12969 	}
12970 
12971 	case LONG_POS: /* Long data format */
12972 	{
12973 		uint64_t value;
12974 		tape_position_long_t *long_pos_info =
12975 		    (tape_position_long_t *)responce;
12976 
12977 		/* If reserved fields are non zero don't use the data */
12978 		if ((long_pos_info->reserved0) ||
12979 		    (long_pos_info->reserved1) ||
12980 		    (long_pos_info->reserved2)) {
12981 			rval = EIO;
12982 			break;
12983 		}
12984 
12985 		/* Is position Valid */
12986 		if (long_pos_info->blk_posi_unkwn == 0) {
12987 			uint32_t part;
12988 
12989 			part = long_pos_info->partition;
12990 			FIX_ENDIAN32(&part);
12991 			if (un->un_pos.partition != part) {
12992 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12993 				    "LONG_POS current partition %d"
12994 				    " read %d\n", un->un_pos.partition, part);
12995 			}
12996 			un->un_pos.partition = part;
12997 			value = long_pos_info->block_number;
12998 			FIX_ENDIAN64(&value);
12999 			if (un->un_pos.lgclblkno != value) {
13000 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13001 				    "LONG_POS current logical 0x%"PRIx64
13002 				    " read 0x%"PRIx64"\n",
13003 				    un->un_pos.lgclblkno, value);
13004 			}
13005 			un->un_pos.lgclblkno = value;
13006 
13007 			if (long_pos_info->begin_of_part &&
13008 			    long_pos_info->end_of_part) {
13009 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
13010 				    "LONG_POS returned begin and end of"
13011 				    " partition\n");
13012 				break;
13013 			}
13014 			if ((long_pos_info->begin_of_part == 1) &&
13015 			    (long_pos_info->block_number == 0)) {
13016 				un->un_pos.blkno = 0;
13017 				un->un_pos.fileno = 0;
13018 				un->un_pos.pmode = legacy;
13019 			} else if (un->un_pos.pmode == invalid) {
13020 				un->un_pos.pmode = logical;
13021 			}
13022 		} else {
13023 			/*
13024 			 * If the drive doesn't know location,
13025 			 * we don't either.
13026 			 */
13027 			un->un_pos.pmode = invalid;
13028 		}
13029 
13030 		value = long_pos_info->file_number;
13031 		FIX_ENDIAN64(&value);
13032 		/* Is file position valid */
13033 		if (long_pos_info->mrk_posi_unkwn == 0) {
13034 			if (((un->un_pos.pmode == legacy) ||
13035 			    (un->un_pos.pmode == logical)) &&
13036 			    (un->un_pos.fileno != value)) {
13037 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13038 				    "LONG_POS fileno 0x%"PRIx64
13039 				    " not un_pos %x\n", value,
13040 				    un->un_pos.fileno);
13041 			} else if (un->un_pos.pmode == invalid) {
13042 				un->un_pos.pmode = logical;
13043 			}
13044 			un->un_pos.fileno = (int32_t)value;
13045 		} else {
13046 			/*
13047 			 * If the drive doesn't know its position,
13048 			 * we don't either.
13049 			 */
13050 			un->un_pos.pmode = invalid;
13051 		}
13052 		if (un->un_pos.pmode != invalid && long_pos_info->end_of_part) {
13053 			un->un_pos.eof = ST_EOT;
13054 		}
13055 
13056 		break;
13057 	}
13058 
13059 	case EXT_POS: /* Extended data format */
13060 	{
13061 		uint64_t value;
13062 		tape_position_ext_t *ext_pos_info =
13063 		    (tape_position_ext_t *)responce;
13064 
13065 		/* Make sure that there is enough data there */
13066 		if (data_sz < 16) {
13067 			break;
13068 		}
13069 
13070 		/* If reserved fields are non zero don't use the data */
13071 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
13072 			rval = EIO;
13073 			break;
13074 		}
13075 
13076 		/*
13077 		 * In the unlikely event of overflowing 64 bits of position.
13078 		 */
13079 		if (ext_pos_info->posi_err != 0) {
13080 			rval = ERANGE;
13081 			break;
13082 		}
13083 
13084 		/* Is block position information valid */
13085 		if (ext_pos_info->blk_posi_unkwn == 0) {
13086 
13087 			if (un->un_pos.partition != ext_pos_info->partition) {
13088 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13089 				    "EXT_POS current partition %d read %d\n",
13090 				    un->un_pos.partition,
13091 				    ext_pos_info->partition);
13092 			}
13093 			un->un_pos.partition = ext_pos_info->partition;
13094 
13095 			value = ext_pos_info->host_block;
13096 			FIX_ENDIAN64(&value);
13097 			if (un->un_pos.lgclblkno != value) {
13098 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13099 				    "EXT_POS current logical 0x%"PRIx64
13100 				    " read 0x%"PRIx64"\n",
13101 				    un->un_pos.lgclblkno, value);
13102 			}
13103 			un->un_pos.lgclblkno = value;
13104 			if ((ext_pos_info->begin_of_part == 1) &&
13105 			    (ext_pos_info->host_block == 0)) {
13106 				un->un_pos.blkno = 0;
13107 				un->un_pos.fileno = 0;
13108 				un->un_pos.pmode = legacy;
13109 			} else if (un->un_pos.pmode == invalid) {
13110 				un->un_pos.pmode = logical;
13111 			}
13112 		} else {
13113 			un->un_pos.pmode = invalid;
13114 		}
13115 		break;
13116 	}
13117 
13118 	default:
13119 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
13120 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
13121 		rval = EIO;
13122 	}
13123 
13124 	return (rval);
13125 }
13126 
13127 static int
13128 st_logical_block_locate(struct scsi_tape *un, uint64_t lblk, uchar_t partition)
13129 {
13130 	int rval;
13131 	char cdb[CDB_GROUP4];
13132 	struct uscsi_cmd *cmd;
13133 	struct scsi_extended_sense sense;
13134 
13135 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
13136 
13137 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13138 
13139 	if (lblk <= INT32_MAX) {
13140 		cmd->uscsi_cdblen = CDB_GROUP1;
13141 		cdb[0] = SCMD_LOCATE;
13142 		cdb[1] = un->un_pos.partition == partition ? 0 : 2;
13143 		cdb[2] = 0;
13144 		cdb[3] = (char)(lblk >> 24);
13145 		cdb[4] = (char)(lblk >> 16);
13146 		cdb[5] = (char)(lblk >> 8);
13147 		cdb[6] = (char)(lblk);
13148 		cdb[7] = 0;
13149 		cdb[8] = partition;
13150 		cdb[9] = 0;
13151 	} else {
13152 		/*
13153 		 * If the drive doesn't give a 64 bit read position data
13154 		 * it is unlikely it will accept 64 bit locates.
13155 		 */
13156 		if (un->un_read_pos_type != LONG_POS) {
13157 			kmem_free(cmd, sizeof (struct uscsi_cmd));
13158 			return (ERANGE);
13159 		}
13160 		cmd->uscsi_cdblen = CDB_GROUP4;
13161 		cdb[0] = (char)SCMD_LOCATE_G4;
13162 		cdb[1] = un->un_pos.partition == partition ? 0 : 2;
13163 		cdb[2] = 0;
13164 		cdb[3] = partition;
13165 		cdb[4] = (char)(lblk >> 56);
13166 		cdb[5] = (char)(lblk >> 48);
13167 		cdb[6] = (char)(lblk >> 40);
13168 		cdb[7] = (char)(lblk >> 32);
13169 		cdb[8] = (char)(lblk >> 24);
13170 		cdb[9] = (char)(lblk >> 16);
13171 		cdb[10] = (char)(lblk >> 8);
13172 		cdb[11] = (char)(lblk);
13173 		cdb[12] = 0;
13174 		cdb[13] = 0;
13175 		cdb[14] = 0;
13176 		cdb[15] = 0;
13177 	}
13178 
13179 
13180 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
13181 	cmd->uscsi_rqbuf = (caddr_t)&sense;
13182 	cmd->uscsi_rqlen = sizeof (sense);
13183 	cmd->uscsi_timeout = un->un_dp->space_timeout;
13184 	cmd->uscsi_cdb = cdb;
13185 
13186 	rval = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
13187 
13188 	un->un_pos.pmode = logical;
13189 	un->un_pos.eof = ST_NO_EOF;
13190 
13191 	if (lblk > INT32_MAX) {
13192 		/*
13193 		 * XXX This is a work around till we handle Descriptor format
13194 		 * sense data. Since we are sending a command where the standard
13195 		 * sense data can not correctly represent a correct residual in
13196 		 * 4 bytes.
13197 		 */
13198 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
13199 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13200 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
13201 			/* Doesn't like big locate command */
13202 			un->un_status = 0;
13203 			rval = ERANGE;
13204 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
13205 			/* Aborted big locate command */
13206 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13207 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
13208 			    rval);
13209 			un->un_status = 0;
13210 			rval = EIO;
13211 		} else if (st_update_block_pos(un)) {
13212 			/* read position failed */
13213 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13214 			    "Big LOCATE and read pos: rval = %d\n", rval);
13215 			rval = EIO;
13216 		} else if (lblk > un->un_pos.lgclblkno) {
13217 			/* read position worked but position was not expected */
13218 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13219 			    "Big LOCATE and recover read less then desired 0x%"
13220 			    PRIx64"\n", un->un_pos.lgclblkno);
13221 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
13222 			un->un_status = KEY_BLANK_CHECK;
13223 			rval = ESPIPE;
13224 		} else if (lblk == un->un_pos.lgclblkno) {
13225 			/* read position was what was expected */
13226 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13227 			    "Big LOCATE and recover seems to have worked\n");
13228 			un->un_err_resid = 0;
13229 			rval = 0;
13230 		} else {
13231 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
13232 			    "BIGLOCATE end up going backwards");
13233 			un->un_err_resid = lblk;
13234 			rval = EIO;
13235 		}
13236 
13237 	} else if (rval == 0) {
13238 		/* Worked as requested */
13239 		un->un_pos.lgclblkno = lblk;
13240 
13241 	} else if (((cmd->uscsi_status & STATUS_MASK) == STATUS_CHECK) &&
13242 	    (cmd->uscsi_resid != 0)) {
13243 		/* Got part way there but wasn't enough blocks on tape */
13244 		un->un_pos.lgclblkno = lblk - cmd->uscsi_resid;
13245 		un->un_err_resid = cmd->uscsi_resid;
13246 		un->un_status = KEY_BLANK_CHECK;
13247 		rval = ESPIPE;
13248 
13249 	} else if (st_update_block_pos(un) == 0) {
13250 		/* Got part way there but drive didn't tell what we missed by */
13251 		un->un_err_resid = lblk - un->un_pos.lgclblkno;
13252 		un->un_status = KEY_BLANK_CHECK;
13253 		rval = ESPIPE;
13254 
13255 	} else {
13256 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13257 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
13258 		    rval, cmd->uscsi_status);
13259 		un->un_err_resid = lblk;
13260 		un->un_status = KEY_ILLEGAL_REQUEST;
13261 		un->un_pos.pmode = invalid;
13262 		rval = EIO;
13263 	}
13264 
13265 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13266 
13267 	return (rval);
13268 }
13269 
13270 static int
13271 st_mtfsf_ioctl(struct scsi_tape *un, int files)
13272 {
13273 	int rval;
13274 
13275 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
13276 
13277 
13278 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13279 	    "st_mtfsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
13280 
13281 	/* pmode == invalid already handled */
13282 	if (un->un_pos.pmode == legacy) {
13283 		/*
13284 		 * forward space over filemark
13285 		 *
13286 		 * For ASF we allow a count of 0 on fsf which means
13287 		 * we just want to go to beginning of current file.
13288 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
13289 		 * Allow stepping over double fmk with reel
13290 		 */
13291 		if ((un->un_pos.eof >= ST_EOT) &&
13292 		    (files > 0) &&
13293 		    ((un->un_dp->options & ST_REEL) == 0)) {
13294 			/* we're at EOM */
13295 			un->un_err_resid = files;
13296 			un->un_status = KEY_BLANK_CHECK;
13297 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13298 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
13299 			return (EIO);
13300 		}
13301 
13302 		/*
13303 		 * physical tape position may not be what we've been
13304 		 * telling the user; adjust the request accordingly
13305 		 */
13306 		if (IN_EOF(un->un_pos)) {
13307 			un->un_pos.fileno++;
13308 			un->un_pos.blkno = 0;
13309 			/*
13310 			 * For positive direction case, we're now covered.
13311 			 * For zero or negative direction, we're covered
13312 			 * (almost)
13313 			 */
13314 			files--;
13315 		}
13316 
13317 	}
13318 
13319 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
13320 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13321 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
13322 		return (EIO);
13323 	}
13324 
13325 
13326 	/*
13327 	 * Forward space file marks.
13328 	 * We leave ourselves at block zero
13329 	 * of the target file number.
13330 	 */
13331 	if (files < 0) {
13332 		rval = st_backward_space_files(un, -files, 0);
13333 	} else {
13334 		rval = st_forward_space_files(un, files);
13335 	}
13336 
13337 	return (rval);
13338 }
13339 
13340 static int
13341 st_forward_space_files(struct scsi_tape *un, int count)
13342 {
13343 	dev_t dev;
13344 	int rval;
13345 
13346 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
13347 
13348 	dev = un->un_dev;
13349 
13350 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13351 	    "fspace: count=%x, eof=%x\n", count, un->un_pos.eof);
13352 
13353 	ASSERT(count >= 0);
13354 	ASSERT(un->un_pos.pmode != invalid);
13355 
13356 	/*
13357 	 * A space with a count of zero means take me to the start of file.
13358 	 */
13359 	if (count == 0) {
13360 
13361 		/* Hay look were already there */
13362 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0 &&
13363 		    un->un_pos.fileno == 0) {
13364 			un->un_err_resid = 0;
13365 			COPY_POS(&un->un_err_pos, &un->un_pos);
13366 			return (0);
13367 		}
13368 
13369 		/*
13370 		 * Well we are in the first file.
13371 		 * A rewind will get to the start.
13372 		 */
13373 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
13374 			rval = st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
13375 
13376 		/*
13377 		 * Can we backspace to get there?
13378 		 * This should work in logical mode.
13379 		 */
13380 		} else if (un->un_dp->options & ST_BSF) {
13381 			rval = st_space_to_begining_of_file(un);
13382 
13383 		/*
13384 		 * Can't back space but current file number is known,
13385 		 * So rewind and space from the begining of the partition.
13386 		 */
13387 		} else if (un->un_pos.pmode == legacy) {
13388 			rval = st_scenic_route_to_begining_of_file(un,
13389 			    un->un_pos.fileno);
13390 
13391 		/*
13392 		 * pmode is logical and ST_BSF is not set.
13393 		 * The LONG_POS read position contains the fileno.
13394 		 * If the read position works, rewind and space.
13395 		 */
13396 		} else if (un->un_read_pos_type == LONG_POS) {
13397 			rval = st_cmd(dev, SCMD_READ_POSITION, 0, SYNC_CMD);
13398 			if (rval) {
13399 				/*
13400 				 * We didn't get the file position from the
13401 				 * read position command.
13402 				 * We are going to trust the drive to backspace
13403 				 * and then position after the filemark.
13404 				 */
13405 				rval = st_space_to_begining_of_file(un);
13406 			}
13407 			rval = st_interpret_read_pos(un, LONG_POS, 32,
13408 			    (caddr_t)un->un_read_pos_data);
13409 			if ((rval) && (un->un_pos.pmode == invalid)) {
13410 				rval = st_space_to_begining_of_file(un);
13411 			} else {
13412 				rval = st_scenic_route_to_begining_of_file(un,
13413 				    un->un_pos.fileno);
13414 			}
13415 		} else {
13416 			rval = EIO;
13417 		}
13418 		/*
13419 		 * If something didn't work we are lost
13420 		 */
13421 		if (rval != 0) {
13422 			un->un_pos.pmode = invalid;
13423 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13424 			    "st_mtioctop : EIO : fspace pmode invalid");
13425 
13426 			rval = EIO;
13427 		}
13428 
13429 	} else {
13430 		rval = st_space_fmks(dev, count);
13431 	}
13432 
13433 	if (rval != EIO && count < 0) {
13434 		/*
13435 		 * we came here with a count < 0; we now need
13436 		 * to skip back to end up before the filemark
13437 		 */
13438 		rval = st_backward_space_files(un, 1, 1);
13439 	}
13440 
13441 	return (rval);
13442 }
13443 
13444 static int
13445 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
13446 {
13447 	int rval;
13448 
13449 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
13450 
13451 	if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
13452 		rval = EIO;
13453 	} else if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
13454 		rval = EIO;
13455 	}
13456 
13457 	return (rval);
13458 }
13459 
13460 static int
13461 st_space_to_begining_of_file(struct scsi_tape *un)
13462 {
13463 	int rval;
13464 
13465 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
13466 
13467 	/*
13468 	 * Back space of the file at the begining of the file.
13469 	 */
13470 	rval = st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD);
13471 	if (rval) {
13472 		rval = EIO;
13473 		return (rval);
13474 	}
13475 
13476 	/*
13477 	 * Other interesting answers might be crashed BOT which isn't bad.
13478 	 */
13479 	if (un->un_status == SUN_KEY_BOT) {
13480 		return (rval);
13481 	}
13482 
13483 	/*
13484 	 * Now we are on the BOP side of the filemark. Forward space to
13485 	 * the EOM side and we are at the begining of the file.
13486 	 */
13487 	rval = st_cmd(un->un_dev, SCMD_SPACE, Fmk(1), SYNC_CMD);
13488 	if (rval) {
13489 		rval = EIO;
13490 	}
13491 
13492 	return (rval);
13493 }
13494 
13495 static int
13496 st_mtfsr_ioctl(struct scsi_tape *un, int count)
13497 {
13498 
13499 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
13500 
13501 	/*
13502 	 * forward space to inter-record gap
13503 	 *
13504 	 */
13505 
13506 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13507 	    "st_ioctl_fsr: count=%x, eof=%x\n", count, un->un_pos.eof);
13508 
13509 	if (un->un_pos.pmode == legacy) {
13510 		/*
13511 		 * If were are at end of tape and count is forward.
13512 		 * Return blank check.
13513 		 */
13514 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
13515 			/* we're at EOM */
13516 			un->un_err_resid = count;
13517 			un->un_status = KEY_BLANK_CHECK;
13518 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13519 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
13520 			return (EIO);
13521 		}
13522 
13523 		/*
13524 		 * If count is zero there is nothing to do.
13525 		 */
13526 		if (count == 0) {
13527 			un->un_err_pos.fileno = un->un_pos.fileno;
13528 			un->un_err_pos.blkno = un->un_pos.blkno;
13529 			un->un_err_resid = 0;
13530 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
13531 				un->un_status = SUN_KEY_EOF;
13532 			}
13533 			return (0);
13534 		}
13535 
13536 		/*
13537 		 * physical tape position may not be what we've been
13538 		 * telling the user; adjust the position accordingly
13539 		 */
13540 		if (IN_EOF(un->un_pos)) {
13541 			daddr_t blkno = un->un_pos.blkno;
13542 			int fileno = un->un_pos.fileno;
13543 
13544 			optype lastop = un->un_lastop;
13545 			if (st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)
13546 			    == -1) {
13547 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13548 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
13549 				return (EIO);
13550 			}
13551 
13552 			un->un_pos.blkno = blkno;
13553 			un->un_pos.fileno = fileno;
13554 			un->un_lastop = lastop;
13555 		}
13556 	}
13557 
13558 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
13559 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13560 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
13561 		return (EIO);
13562 	}
13563 
13564 	return (st_space_records(un, count));
13565 }
13566 
13567 static int
13568 st_space_records(struct scsi_tape *un, int count)
13569 {
13570 	int dblk;
13571 	int rval = 0;
13572 
13573 	ST_FUNC(ST_DEVINFO, st_space_records);
13574 
13575 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13576 	    "st_space_records: count=%x, eof=%x\n", count, un->un_pos.eof);
13577 
13578 	if (un->un_pos.pmode == logical) {
13579 		rval = st_cmd(un->un_dev, SCMD_SPACE, Blk(count), SYNC_CMD);
13580 		if (rval != 0) {
13581 			rval = EIO;
13582 		}
13583 		return (rval);
13584 	}
13585 
13586 	dblk = un->un_pos.blkno + count;
13587 
13588 	/* Already there */
13589 	if (dblk == un->un_pos.blkno) {
13590 		un->un_err_resid = 0;
13591 		COPY_POS(&un->un_err_pos, &un->un_pos);
13592 		return (0);
13593 	}
13594 
13595 	/*
13596 	 * If the destination block is forward
13597 	 * or the drive will backspace records.
13598 	 */
13599 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
13600 		/*
13601 		 * If we're spacing forward, or the device can
13602 		 * backspace records, we can just use the SPACE
13603 		 * command.
13604 		 */
13605 		dblk -= un->un_pos.blkno;
13606 		if (st_cmd(un->un_dev, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
13607 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13608 			    "st_space_records:EIO:space_records can't spc");
13609 			rval = EIO;
13610 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
13611 			/*
13612 			 * check if we hit BOT/EOT
13613 			 */
13614 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
13615 				un->un_status = SUN_KEY_BOT;
13616 				un->un_pos.eof = ST_NO_EOF;
13617 			} else if (dblk < 0 &&
13618 			    un->un_pos.eof == ST_EOF_PENDING) {
13619 				int residue = un->un_err_resid;
13620 				/*
13621 				 * we skipped over a filemark
13622 				 * and need to go forward again
13623 				 */
13624 				if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(1),
13625 				    SYNC_CMD)) {
13626 					ST_DEBUG2(ST_DEVINFO, st_label,
13627 					    SCSI_DEBUG, "st_space_records: EIO"
13628 					    " : can't space #2");
13629 					rval = EIO;
13630 				}
13631 				un->un_err_resid = residue;
13632 			}
13633 			if (rval == 0) {
13634 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13635 				    "st_space_records: EIO : space_rec rval"
13636 				    " == 0");
13637 				rval = EIO;
13638 			}
13639 		}
13640 	} else {
13641 		/*
13642 		 * else we rewind, space forward across filemarks to
13643 		 * the desired file, and then space records to the
13644 		 * desired block.
13645 		 */
13646 
13647 		int dfile = un->un_pos.fileno;	/* save current file */
13648 
13649 		if (dblk < 0) {
13650 			/*
13651 			 * Wups - we're backing up over a filemark
13652 			 */
13653 			if (un->un_pos.blkno != 0 &&
13654 			    (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD) ||
13655 			    st_cmd(un->un_dev, SCMD_SPACE, Fmk(dfile),
13656 			    SYNC_CMD))) {
13657 				un->un_pos.pmode = invalid;
13658 			}
13659 			un->un_err_resid = -dblk;
13660 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
13661 				un->un_status = SUN_KEY_BOT;
13662 				un->un_pos.eof = ST_NO_EOF;
13663 			} else if (un->un_pos.fileno > 0) {
13664 				un->un_status = SUN_KEY_EOF;
13665 				un->un_pos.eof = ST_NO_EOF;
13666 			}
13667 			COPY_POS(&un->un_err_pos, &un->un_pos);
13668 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13669 			    "st_space_records:EIO:space_records : dblk < 0");
13670 			rval = EIO;
13671 		} else if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD) ||
13672 		    st_cmd(un->un_dev, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
13673 		    st_cmd(un->un_dev, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
13674 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13675 			    "st_space_records: EIO :space_records : rewind "
13676 			    "and space failed");
13677 			un->un_pos.pmode = invalid;
13678 			rval = EIO;
13679 		}
13680 	}
13681 
13682 	return (rval);
13683 }
13684 
13685 static int
13686 st_mtbsf_ioctl(struct scsi_tape *un, int files)
13687 {
13688 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
13689 
13690 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13691 	    "st_mtbsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
13692 	/*
13693 	 * backward space of file filemark (1/2" and 8mm)
13694 	 * tape position will end on the beginning of tape side
13695 	 * of the desired file mark
13696 	 */
13697 	if ((un->un_dp->options & ST_BSF) == 0) {
13698 		return (ENOTTY);
13699 	}
13700 
13701 	if (un->un_pos.pmode == legacy) {
13702 
13703 		/*
13704 		 * If a negative count (which implies a forward space op)
13705 		 * is specified, and we're at logical or physical eot,
13706 		 * bounce the request.
13707 		 */
13708 
13709 		if (un->un_pos.eof >= ST_EOT && files < 0) {
13710 			un->un_err_resid = files;
13711 			un->un_status = SUN_KEY_EOT;
13712 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13713 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
13714 			return (EIO);
13715 		}
13716 		/*
13717 		 * physical tape position may not be what we've been
13718 		 * telling the user; adjust the request accordingly
13719 		 */
13720 		if (IN_EOF(un->un_pos)) {
13721 			un->un_pos.fileno++;
13722 			un->un_pos.blkno = 0;
13723 			files++;
13724 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13725 			    "st_mtbsf_ioctl in eof: count=%d, op=%x\n",
13726 			    files, MTBSF);
13727 
13728 		}
13729 	}
13730 
13731 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
13732 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13733 		    "st_ioctl : EIO : MTBSF : check den wfm");
13734 		return (EIO);
13735 	}
13736 
13737 	if (files <= 0) {
13738 		/*
13739 		 * for a negative count, we need to step forward
13740 		 * first and then step back again
13741 		 */
13742 		files = -files + 1;
13743 		return (st_forward_space_files(un, files));
13744 	}
13745 	return (st_backward_space_files(un, files, 1));
13746 }
13747 
13748 static int
13749 st_backward_space_files(struct scsi_tape *un, int count, int infront)
13750 {
13751 	int end_fileno;
13752 	int skip_cnt;
13753 	int rval = 0;
13754 
13755 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
13756 
13757 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13758 	    "st_backward_space_files: count=%x eof=%x\n",
13759 	    count, un->un_pos.eof);
13760 	/*
13761 	 * Backspace files (MTNBSF): infront == 0
13762 	 *
13763 	 *	For tapes that can backspace, backspace
13764 	 *	count+1 filemarks and then run forward over
13765 	 *	a filemark
13766 	 *
13767 	 *	For tapes that can't backspace,
13768 	 *		calculate desired filenumber
13769 	 *		(un->un_pos.fileno - count), rewind,
13770 	 *		and then space forward this amount
13771 	 *
13772 	 * Backspace filemarks (MTBSF) infront == 1
13773 	 *
13774 	 *	For tapes that can backspace, backspace count
13775 	 *	filemarks
13776 	 *
13777 	 *	For tapes that can't backspace, calculate
13778 	 *	desired filenumber (un->un_pos.fileno - count),
13779 	 *	add 1, rewind, space forward this amount,
13780 	 *	and mark state as ST_EOF_PENDING appropriately.
13781 	 */
13782 
13783 	if (un->un_pos.pmode == logical) {
13784 
13785 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13786 		    "st_backward_space_files: mt_op=%x count=%x"
13787 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
13788 		    un->un_pos.lgclblkno);
13789 
13790 
13791 		/* In case a drive that won't back space gets in logical mode */
13792 		if ((un->un_dp->options & ST_BSF) == 0) {
13793 			rval = EIO;
13794 			return (rval);
13795 		}
13796 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(-count), SYNC_CMD)) {
13797 			rval = EIO;
13798 			return (rval);
13799 		}
13800 		if ((infront != 0) &&
13801 		    (st_cmd(un->un_dev, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
13802 			rval = EIO;
13803 			return (rval);
13804 		}
13805 		return (rval);
13806 	}
13807 
13808 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13809 	    "st_backward_space_files: mt_op=%x count=%x fileno=%x blkno=%x\n",
13810 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
13811 
13812 
13813 
13814 	/*
13815 	 * Handle the simple case of BOT
13816 	 * playing a role in these cmds.
13817 	 * We do this by calculating the
13818 	 * ending file number. If the ending
13819 	 * file is < BOT, rewind and set an
13820 	 * error and mark resid appropriately.
13821 	 * If we're backspacing a file (not a
13822 	 * filemark) and the target file is
13823 	 * the first file on the tape, just
13824 	 * rewind.
13825 	 */
13826 
13827 	/* figure expected destination of this SPACE command */
13828 	end_fileno = un->un_pos.fileno - count;
13829 
13830 	/*
13831 	 * Would the end effect of this SPACE be the same as rewinding?
13832 	 * If so just rewind instead.
13833 	 */
13834 	if ((infront != 0) && (end_fileno < 0) ||
13835 	    (infront == 0) && (end_fileno <= 0)) {
13836 		if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
13837 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13838 			    "st_backward_space_files: EIO : "
13839 			    "rewind in lou of BSF failed\n");
13840 			rval = EIO;
13841 		}
13842 		if (end_fileno < 0) {
13843 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13844 			    "st_backward_space_files: EIO : "
13845 			    "back space file greater then fileno\n");
13846 			rval = EIO;
13847 			un->un_err_resid = -end_fileno;
13848 			un->un_status = SUN_KEY_BOT;
13849 		}
13850 		return (rval);
13851 	}
13852 
13853 	if (un->un_dp->options & ST_BSF) {
13854 		skip_cnt = 1 - infront;
13855 		/*
13856 		 * If we are going to end up at the beginning
13857 		 * of the file, we have to space one extra file
13858 		 * first, and then space forward later.
13859 		 */
13860 		end_fileno = -(count + skip_cnt);
13861 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
13862 		    "skip_cnt=%x, tmp=%x\n", skip_cnt, end_fileno);
13863 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
13864 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13865 			    "st_backward_space_files:EIO:back space fm failed");
13866 			rval = EIO;
13867 		}
13868 	} else {
13869 		if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
13870 			rval = EIO;
13871 		} else {
13872 			skip_cnt = end_fileno + infront;
13873 		}
13874 	}
13875 
13876 	/*
13877 	 * If we have to space forward, do so...
13878 	 */
13879 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
13880 	    "space forward skip_cnt=%x, rval=%x\n", skip_cnt, rval);
13881 
13882 	if (rval == 0 && skip_cnt) {
13883 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
13884 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13885 			    "st_backward_space_files:EIO:space fm skip count");
13886 			rval = EIO;
13887 		} else if (infront) {
13888 			/*
13889 			 * If we had to space forward, and we're
13890 			 * not a tape that can backspace, mark state
13891 			 * as if we'd just seen a filemark during a
13892 			 * a read.
13893 			 */
13894 			if ((un->un_dp->options & ST_BSF) == 0) {
13895 				un->un_pos.eof = ST_EOF_PENDING;
13896 				un->un_pos.fileno -= 1;
13897 				un->un_pos.blkno = INF;
13898 			}
13899 		}
13900 	}
13901 
13902 	if (rval != 0) {
13903 		un->un_pos.pmode = invalid;
13904 	}
13905 
13906 	return (rval);
13907 }
13908 
13909 static int
13910 st_mtnbsf_ioctl(struct scsi_tape *un, int count)
13911 {
13912 	int rval;
13913 
13914 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
13915 
13916 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13917 	    "nbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
13918 
13919 	if (un->un_pos.pmode == legacy) {
13920 		/*
13921 		 * backward space file to beginning of file
13922 		 *
13923 		 * If a negative count (which implies a forward space op)
13924 		 * is specified, and we're at logical or physical eot,
13925 		 * bounce the request.
13926 		 */
13927 
13928 		if (un->un_pos.eof >= ST_EOT && count < 0) {
13929 			un->un_err_resid = count;
13930 			un->un_status = SUN_KEY_EOT;
13931 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13932 			    "st_ioctl : EIO : > EOT and count < 0");
13933 			return (EIO);
13934 		}
13935 		/*
13936 		 * physical tape position may not be what we've been
13937 		 * telling the user; adjust the request accordingly
13938 		 */
13939 		if (IN_EOF(un->un_pos)) {
13940 			un->un_pos.fileno++;
13941 			un->un_pos.blkno = 0;
13942 			count++;
13943 		}
13944 	}
13945 
13946 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
13947 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13948 		    "st_ioctl : EIO : MTNBSF check den and wfm");
13949 		return (EIO);
13950 	}
13951 
13952 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13953 	    "mtnbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
13954 
13955 	if (count <= 0) {
13956 		rval = st_forward_space_files(un, -count);
13957 	} else {
13958 		rval = st_backward_space_files(un, count, 0);
13959 	}
13960 	return (rval);
13961 }
13962 
13963 static int
13964 st_mtbsr_ioctl(struct scsi_tape *un, int num)
13965 {
13966 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
13967 
13968 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13969 	    "bsr: count=%x, eof=%x\n", num, un->un_pos.eof);
13970 
13971 	if (un->un_pos.pmode == legacy) {
13972 		/*
13973 		 * backward space into inter-record gap
13974 		 *
13975 		 * If a negative count (which implies a forward space op)
13976 		 * is specified, and we're at logical or physical eot,
13977 		 * bounce the request.
13978 		 */
13979 		if (un->un_pos.eof >= ST_EOT && num < 0) {
13980 			un->un_err_resid = num;
13981 			un->un_status = SUN_KEY_EOT;
13982 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13983 			    "st_ioctl : EIO : MTBSR > EOT");
13984 			return (EIO);
13985 		}
13986 
13987 		if (num == 0) {
13988 			COPY_POS(&un->un_err_pos, &un->un_pos);
13989 			un->un_err_resid = 0;
13990 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
13991 				un->un_status = SUN_KEY_EOF;
13992 			}
13993 			return (0);
13994 		}
13995 
13996 		/*
13997 		 * physical tape position may not be what we've been
13998 		 * telling the user; adjust the position accordingly.
13999 		 * bsr can not skip filemarks and continue to skip records
14000 		 * therefore if we are logically before the filemark but
14001 		 * physically at the EOT side of the filemark, we need to step
14002 		 * back; this allows fsr N where N > number of blocks in file
14003 		 * followed by bsr 1 to position at the beginning of last block
14004 		 */
14005 		if (IN_EOF(un->un_pos)) {
14006 			tapepos_t save;
14007 			optype lastop = un->un_lastop;
14008 
14009 			COPY_POS(&save, &un->un_pos);
14010 			if (st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)
14011 			    == -1) {
14012 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14013 				    "st_write_fm : EIO : MTBSR can't space");
14014 				return (EIO);
14015 			}
14016 
14017 			COPY_POS(&un->un_pos, &save);
14018 			un->un_lastop = lastop;
14019 		}
14020 	}
14021 
14022 	un->un_pos.eof = ST_NO_EOF;
14023 
14024 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
14025 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14026 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
14027 		return (EIO);
14028 	}
14029 
14030 	num = -num;
14031 	return (st_space_records(un, num));
14032 }
14033 
14034 static int
14035 st_mtfsfm_ioctl(struct scsi_tape *un, int cnt)
14036 {
14037 	int rval;
14038 
14039 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
14040 
14041 	rval = st_cmd(un->un_dev, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
14042 	if (rval == 0) {
14043 		un->un_pos.pmode = logical;
14044 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
14045 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
14046 		/*
14047 		 * Drive says invalid field in cdb.
14048 		 * Doesn't like space multiple. Position isn't lost.
14049 		 */
14050 		un->un_err_resid = cnt;
14051 		un->un_status = 0;
14052 		rval = ENOTTY;
14053 	} else {
14054 		un->un_err_resid = cnt;
14055 		un->un_pos.pmode = invalid;
14056 	}
14057 	return (rval);
14058 }
14059 
14060 static int
14061 st_mtbsfm_ioctl(struct scsi_tape *un, int cnt)
14062 {
14063 	int rval;
14064 
14065 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
14066 
14067 	rval = st_cmd(un->un_dev, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
14068 	if (rval == 0) {
14069 		un->un_pos.pmode = logical;
14070 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
14071 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
14072 		/*
14073 		 * Drive says invalid field in cdb.
14074 		 * Doesn't like space multiple. Position isn't lost.
14075 		 */
14076 		un->un_err_resid = cnt;
14077 		un->un_status = 0;
14078 		rval = ENOTTY;
14079 	} else {
14080 		un->un_err_resid = cnt;
14081 		un->un_pos.pmode = invalid;
14082 	}
14083 	return (rval);
14084 }
14085 
14086 #if defined(__i386) || defined(__amd64)
14087 
14088 /*
14089  * release contig_mem and wake up waiting thread, if any
14090  */
14091 static void
14092 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
14093 {
14094 	mutex_enter(ST_MUTEX);
14095 
14096 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
14097 
14098 	cp->cm_next = un->un_contig_mem;
14099 	un->un_contig_mem = cp;
14100 	un->un_contig_mem_available_num++;
14101 	cv_broadcast(&un->un_contig_mem_cv);
14102 
14103 	mutex_exit(ST_MUTEX);
14104 }
14105 
14106 /*
14107  * St_get_contig_mem will return a contig_mem if there is one available
14108  * in current system. Otherwise, it will try to alloc one, if the total
14109  * number of contig_mem is within st_max_contig_mem_num.
14110  * It will sleep, if allowed by caller or return NULL, if no contig_mem
14111  * is available for now.
14112  */
14113 static struct contig_mem *
14114 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
14115 {
14116 	size_t rlen;
14117 	struct contig_mem *cp = NULL;
14118 	ddi_acc_handle_t acc_hdl;
14119 	caddr_t addr;
14120 	int big_enough = 0;
14121 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
14122 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
14123 
14124 	/* Try to get one available contig_mem */
14125 	mutex_enter(ST_MUTEX);
14126 
14127 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
14128 
14129 	if (un->un_contig_mem_available_num > 0) {
14130 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
14131 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
14132 		/*
14133 		 * we failed to get one. we're going to
14134 		 * alloc one more contig_mem for this I/O
14135 		 */
14136 		mutex_exit(ST_MUTEX);
14137 		cp = (struct contig_mem *)kmem_zalloc(
14138 		    sizeof (struct contig_mem) + biosize(),
14139 		    alloc_flags);
14140 		if (cp == NULL) {
14141 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14142 			    "alloc contig_mem failure\n");
14143 			return (NULL); /* cannot get one */
14144 		}
14145 		cp->cm_bp = (struct buf *)
14146 		    (((caddr_t)cp) + sizeof (struct contig_mem));
14147 		bioinit(cp->cm_bp);
14148 		mutex_enter(ST_MUTEX);
14149 		un->un_contig_mem_total_num++; /* one more available */
14150 	} else {
14151 		/*
14152 		 * we failed to get one and we're NOT allowed to
14153 		 * alloc more contig_mem
14154 		 */
14155 		if (alloc_flags == KM_SLEEP) {
14156 			while (un->un_contig_mem_available_num <= 0) {
14157 				cv_wait(&un->un_contig_mem_cv,
14158 				    ST_MUTEX);
14159 			}
14160 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
14161 		} else {
14162 			mutex_exit(ST_MUTEX);
14163 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14164 			    "alloc contig_mem failure\n");
14165 			return (NULL); /* cannot get one */
14166 		}
14167 	}
14168 	mutex_exit(ST_MUTEX);
14169 
14170 	/* We need to check if this block of mem is big enough for this I/O */
14171 	if (cp->cm_len < len) {
14172 		/* not big enough, need to alloc a new one */
14173 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
14174 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
14175 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
14176 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14177 			    "alloc contig_mem failure: not enough mem\n");
14178 			st_release_contig_mem(un, cp);
14179 			cp = NULL;
14180 		} else {
14181 			if (cp->cm_addr) {
14182 				/* release previous one before attach new one */
14183 				ddi_dma_mem_free(&cp->cm_acc_hdl);
14184 			}
14185 			mutex_enter(ST_MUTEX);
14186 			un->un_max_contig_mem_len =
14187 			    un->un_max_contig_mem_len >= len ?
14188 			    un->un_max_contig_mem_len : len;
14189 			mutex_exit(ST_MUTEX);
14190 
14191 			/* attach new mem to this cp */
14192 			cp->cm_addr = addr;
14193 			cp->cm_acc_hdl = acc_hdl;
14194 			cp->cm_len = len;
14195 
14196 			goto alloc_ok; /* get one usable cp */
14197 		}
14198 	} else {
14199 		goto alloc_ok; /* get one usable cp */
14200 	}
14201 
14202 	/* cannot find/alloc a usable cp, when we get here */
14203 
14204 	mutex_enter(ST_MUTEX);
14205 	if ((un->un_max_contig_mem_len < len) ||
14206 	    (alloc_flags != KM_SLEEP)) {
14207 		mutex_exit(ST_MUTEX);
14208 		return (NULL);
14209 	}
14210 
14211 	/*
14212 	 * we're allowed to sleep, and there is one big enough
14213 	 * contig mem in the system, which is currently in use,
14214 	 * wait for it...
14215 	 */
14216 	big_enough = 1;
14217 	do {
14218 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
14219 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
14220 	} while (cp == NULL);
14221 	mutex_exit(ST_MUTEX);
14222 
14223 	/* we get the big enough contig mem, finally */
14224 
14225 alloc_ok:
14226 	/* init bp attached to this cp */
14227 	bioreset(cp->cm_bp);
14228 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
14229 	cp->cm_bp->b_private = (void *)cp;
14230 
14231 	return (cp);
14232 }
14233 
14234 /*
14235  * this is the biodone func for the bp used in big block I/O
14236  */
14237 static int
14238 st_bigblk_xfer_done(struct buf *bp)
14239 {
14240 	struct contig_mem *cp;
14241 	struct buf *orig_bp;
14242 	int remapped = 0;
14243 	int ioerr;
14244 	struct scsi_tape *un;
14245 
14246 	/* sanity check */
14247 	if (bp == NULL) {
14248 		return (DDI_FAILURE);
14249 	}
14250 
14251 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
14252 	if (un == NULL) {
14253 		return (DDI_FAILURE);
14254 	}
14255 
14256 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
14257 
14258 	cp = (struct contig_mem *)bp->b_private;
14259 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
14260 	cp->cm_bp = bp;
14261 
14262 	/* special handling for special I/O */
14263 	if (cp->cm_use_sbuf) {
14264 #ifndef __lock_lint
14265 		ASSERT(un->un_sbuf_busy);
14266 #endif
14267 		un->un_sbufp = orig_bp;
14268 		cp->cm_use_sbuf = 0;
14269 	}
14270 
14271 	orig_bp->b_resid = bp->b_resid;
14272 	ioerr = geterror(bp);
14273 	if (ioerr != 0) {
14274 		bioerror(orig_bp, ioerr);
14275 	} else if (orig_bp->b_flags & B_READ) {
14276 		/* copy data back to original bp */
14277 		if (orig_bp->b_flags & (B_PHYS | B_PAGEIO)) {
14278 			bp_mapin(orig_bp);
14279 			remapped = 1;
14280 		}
14281 		bcopy(bp->b_un.b_addr, orig_bp->b_un.b_addr,
14282 		    bp->b_bcount - bp->b_resid);
14283 		if (remapped)
14284 			bp_mapout(orig_bp);
14285 	}
14286 
14287 	st_release_contig_mem(un, cp);
14288 
14289 	biodone(orig_bp);
14290 
14291 	return (DDI_SUCCESS);
14292 }
14293 
14294 /*
14295  * We use this func to replace original bp that may not be able to do I/O
14296  * in big block size with one that can
14297  */
14298 static struct buf *
14299 st_get_bigblk_bp(struct buf *bp)
14300 {
14301 	struct contig_mem *cp;
14302 	struct scsi_tape *un;
14303 	struct buf *cont_bp;
14304 	int remapped = 0;
14305 
14306 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
14307 	if (un == NULL) {
14308 		return (bp);
14309 	}
14310 
14311 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
14312 
14313 	/* try to get one contig_mem */
14314 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
14315 	if (!cp) {
14316 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
14317 		    "Cannot alloc contig buf for I/O for %lu blk size",
14318 		    bp->b_bcount);
14319 		return (bp);
14320 	}
14321 	cont_bp = cp->cm_bp;
14322 	cp->cm_bp = bp;
14323 
14324 	/* make sure that we "are" using un_sbufp for special I/O */
14325 	if (bp == un->un_sbufp) {
14326 #ifndef __lock_lint
14327 		ASSERT(un->un_sbuf_busy);
14328 #endif
14329 		un->un_sbufp = cont_bp;
14330 		cp->cm_use_sbuf = 1;
14331 	}
14332 
14333 	/* clone bp */
14334 	cont_bp->b_bcount = bp->b_bcount;
14335 	cont_bp->b_resid = bp->b_resid;
14336 	cont_bp->b_iodone = st_bigblk_xfer_done;
14337 	cont_bp->b_file = bp->b_file;
14338 	cont_bp->b_offset = bp->b_offset;
14339 	cont_bp->b_dip = bp->b_dip;
14340 	cont_bp->b_error = 0;
14341 	cont_bp->b_proc = NULL;
14342 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
14343 	cont_bp->b_shadow = NULL;
14344 	cont_bp->b_pages = NULL;
14345 	cont_bp->b_edev = bp->b_edev;
14346 	cont_bp->b_dev = bp->b_dev;
14347 	cont_bp->b_lblkno = bp->b_lblkno;
14348 	cont_bp->b_forw = bp->b_forw;
14349 	cont_bp->b_back = bp->b_back;
14350 	cont_bp->av_forw = bp->av_forw;
14351 	cont_bp->av_back = bp->av_back;
14352 	cont_bp->b_bufsize = bp->b_bufsize;
14353 
14354 	/* get data in original bp */
14355 	if (bp->b_flags & B_WRITE) {
14356 		if (bp->b_flags & (B_PHYS | B_PAGEIO)) {
14357 			bp_mapin(bp);
14358 			remapped = 1;
14359 		}
14360 		bcopy(bp->b_un.b_addr, cont_bp->b_un.b_addr, bp->b_bcount);
14361 		if (remapped)
14362 			bp_mapout(bp);
14363 	}
14364 
14365 	return (cont_bp);
14366 }
14367 #else
14368 #ifdef __lock_lint
14369 static int
14370 st_bigblk_xfer_done(struct buf *bp)
14371 {
14372 	return (0);
14373 }
14374 #endif
14375 #endif
14376 
14377 static const char *eof_status[] =
14378 {
14379 	"NO_EOF",
14380 	"EOF_PENDING",
14381 	"EOF",
14382 	"EOT_PENDING",
14383 	"EOT",
14384 	"EOM",
14385 	"AFTER_EOM"
14386 };
14387 static const char *mode[] = {
14388 	"invalid",
14389 	"legacy",
14390 	"logical"
14391 };
14392 
14393 static void
14394 st_print_position(struct scsi_tape *un, const char *comment, tapepos_t *pos)
14395 {
14396 	ST_FUNC(ST_DEVINFO, st_print_position);
14397 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
14398 	    "%s Position data:\n", comment);
14399 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14400 	    "Positioning mode = %s", mode[pos->pmode]);
14401 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14402 	    "End Of File/Tape = %s", eof_status[pos->eof]);
14403 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14404 	    "File Number      = 0x%x", pos->fileno);
14405 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14406 	    "Block Number     = 0x%x", pos->blkno);
14407 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14408 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
14409 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14410 	    "Partition Number = 0x%x", pos->partition);
14411 }
14412