xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/st.c (revision 9edfcb98cbf50b8e2ca35c6c7dd041cc42df94a4)
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 #ifdef	__x86
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 #ifdef	__x86
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 #ifdef	__x86
993 	/*
994 	 * for x86, the device may be able to DMA more than the system will
995 	 * allow under some circumstances. We need account for both the HBA's
996 	 * and system's contraints.
997 	 *
998 	 * Get the maximum DMA under worse case conditions. e.g. looking at the
999 	 * device constraints, the max copy buffer size, and the worse case
1000 	 * fragmentation. NOTE: this may differ from dma-max since dma-max
1001 	 * doesn't take the worse case framentation into account.
1002 	 *
1003 	 * e.g. a device may be able to DMA 16MBytes, but can only DMA 1MByte
1004 	 * if none of the pages are contiguous. Keeping track of both of these
1005 	 * values allows us to support larger tape block sizes on some devices.
1006 	 */
1007 	un->un_maxdma_arch = scsi_ifgetcap(&devp->sd_address, "dma-max-arch",
1008 	    1);
1009 
1010 	/*
1011 	 * If the dma-max-arch capability is not implemented, or the value
1012 	 * comes back higher than what was reported in dma-max, use dma-max.
1013 	 */
1014 	if ((un->un_maxdma_arch == -1) ||
1015 	    ((uint_t)un->un_maxdma < (uint_t)un->un_maxdma_arch)) {
1016 		un->un_maxdma_arch = un->un_maxdma;
1017 	}
1018 #endif
1019 
1020 	/*
1021 	 * Get the max allowable cdb size
1022 	 */
1023 	un->un_max_cdb_sz =
1024 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
1025 	if (un->un_max_cdb_sz < CDB_GROUP0) {
1026 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1027 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
1028 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
1029 	}
1030 
1031 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1032 
1033 	un->un_mediastate = MTIO_NONE;
1034 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1035 
1036 	/*
1037 	 * initialize kstats
1038 	 */
1039 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1040 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1041 	if (un->un_stats) {
1042 		un->un_stats->ks_lock = ST_MUTEX;
1043 		kstat_install(un->un_stats);
1044 	}
1045 	(void) st_create_errstats(un, instance);
1046 
1047 	return (DDI_SUCCESS);
1048 }
1049 
1050 /*
1051  * st_detach:
1052  *
1053  * we allow a detach if and only if:
1054  *	- no tape is currently inserted
1055  *	- tape position is at BOT or unknown
1056  *		(if it is not at BOT then a no rewind
1057  *		device was opened and we have to preserve state)
1058  *	- it must be in a closed state : no timeouts or scsi_watch requests
1059  *		will exist if it is closed, so we don't need to check for
1060  *		them here.
1061  */
1062 /*ARGSUSED*/
1063 static int
1064 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1065 {
1066 	int 	instance;
1067 	int 	dev_instance;
1068 	struct scsi_device *devp;
1069 	struct scsi_tape *un;
1070 	clock_t wait_cmds_complete;
1071 
1072 	ST_ENTR(devi, st_detach);
1073 
1074 	instance = ddi_get_instance(devi);
1075 
1076 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1077 		return (DDI_FAILURE);
1078 	}
1079 
1080 	mutex_enter(ST_MUTEX);
1081 
1082 	/*
1083 	 * Clear error entry stack
1084 	 */
1085 	st_empty_error_stack(un);
1086 
1087 	mutex_exit(ST_MUTEX);
1088 
1089 	switch (cmd) {
1090 
1091 	case DDI_DETACH:
1092 		/*
1093 		 * Undo what we did in st_attach & st_doattach,
1094 		 * freeing resources and removing things we installed.
1095 		 * The system framework guarantees we are not active
1096 		 * with this devinfo node in any other entry points at
1097 		 * this time.
1098 		 */
1099 
1100 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1101 		    "st_detach: instance=%x, un=%p\n", instance,
1102 		    (void *)un);
1103 
1104 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1105 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1106 		    (un->un_state != ST_STATE_CLOSED)) {
1107 			/*
1108 			 * we cannot unload some targets because the
1109 			 * inquiry returns junk unless immediately
1110 			 * after a reset
1111 			 */
1112 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1113 			    "cannot unload instance %x\n", instance);
1114 			return (DDI_FAILURE);
1115 		}
1116 
1117 		/*
1118 		 * if the tape has been removed then we may unload;
1119 		 * do a test unit ready and if it returns NOT READY
1120 		 * then we assume that it is safe to unload.
1121 		 * as a side effect, pmode may be set to invalid if the
1122 		 * the test unit ready fails;
1123 		 * also un_state may be set to non-closed, so reset it
1124 		 */
1125 		if ((un->un_dev) &&		/* Been opened since attach */
1126 		    ((un->un_pos.pmode == legacy) &&
1127 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1128 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1129 		    ((un->un_pos.pmode == logical) &&
1130 		    (un->un_pos.lgclblkno > 0))) {
1131 			mutex_enter(ST_MUTEX);
1132 			/*
1133 			 * Send Test Unit Ready in the hopes that if
1134 			 * the drive is not in the state we think it is.
1135 			 * And the state will be changed so it can be detached.
1136 			 * If the command fails to reach the device and
1137 			 * the drive was not rewound or unloaded we want
1138 			 * to fail the detach till a user command fails
1139 			 * where after the detach will succead.
1140 			 */
1141 			(void) st_cmd(un->un_dev, SCMD_TEST_UNIT_READY,
1142 			    0, SYNC_CMD);
1143 			/*
1144 			 * After TUR un_state may be set to non-closed,
1145 			 * so reset it back.
1146 			 */
1147 			un->un_state = ST_STATE_CLOSED;
1148 			mutex_exit(ST_MUTEX);
1149 		}
1150 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1151 		    "un_status=%x, fileno=%x, blkno=%x\n",
1152 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1153 
1154 		/*
1155 		 * check again:
1156 		 * if we are not at BOT then it is not safe to unload
1157 		 */
1158 		if ((un->un_dev) &&		/* Been opened since attach */
1159 		    (((un->un_pos.pmode == legacy) &&
1160 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1161 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1162 		    ((un->un_pos.pmode == logical) &&
1163 		    (un->un_pos.lgclblkno > 0)))) {
1164 
1165 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1166 			    "cannot detach: pmode=%d fileno=%x, blkno=%x"
1167 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1168 			    un->un_pos.fileno, un->un_pos.blkno,
1169 			    un->un_pos.lgclblkno);
1170 			return (DDI_FAILURE);
1171 		}
1172 
1173 		/*
1174 		 * Just To make sure that we have released the
1175 		 * tape unit .
1176 		 */
1177 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1178 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1179 			mutex_enter(ST_MUTEX);
1180 			(void) st_reserve_release(un, ST_RELEASE);
1181 			mutex_exit(ST_MUTEX);
1182 		}
1183 
1184 		/*
1185 		 * now remove other data structures allocated in st_doattach()
1186 		 */
1187 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1188 		    "destroying/freeing\n");
1189 		cv_destroy(&un->un_clscv);
1190 		cv_destroy(&un->un_sbuf_cv);
1191 		cv_destroy(&un->un_queue_cv);
1192 		cv_destroy(&un->un_suspend_cv);
1193 		cv_destroy(&un->un_tape_busy_cv);
1194 
1195 		if (un->un_hib_tid) {
1196 			(void) untimeout(un->un_hib_tid);
1197 			un->un_hib_tid = 0;
1198 		}
1199 
1200 		if (un->un_delay_tid) {
1201 			(void) untimeout(un->un_delay_tid);
1202 			un->un_delay_tid = 0;
1203 		}
1204 		cv_destroy(&un->un_state_cv);
1205 
1206 #ifdef	__x86
1207 		if (un->un_contig_mem_hdl != NULL) {
1208 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1209 		}
1210 #endif
1211 		if (un->un_sbufp) {
1212 			freerbuf(un->un_sbufp);
1213 		}
1214 		if (un->un_uscsi_rqs_buf) {
1215 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1216 		}
1217 		if (un->un_mspl) {
1218 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1219 		}
1220 		if (un->un_rqs) {
1221 			scsi_destroy_pkt(un->un_rqs);
1222 			scsi_free_consistent_buf(un->un_rqs_bp);
1223 		}
1224 		if (un->un_mkr_pkt) {
1225 			scsi_destroy_pkt(un->un_mkr_pkt);
1226 		}
1227 		if (un->un_arq_enabled) {
1228 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1229 		}
1230 		if (un->un_dp_size) {
1231 			kmem_free(un->un_dp, un->un_dp_size);
1232 		}
1233 		if (un->un_stats) {
1234 			kstat_delete(un->un_stats);
1235 			un->un_stats = (kstat_t *)0;
1236 		}
1237 		if (un->un_errstats) {
1238 			kstat_delete(un->un_errstats);
1239 			un->un_errstats = (kstat_t *)0;
1240 		}
1241 		devp = ST_SCSI_DEVP;
1242 		ddi_soft_state_free(st_state, instance);
1243 		devp->sd_private = NULL;
1244 		devp->sd_sense = NULL;
1245 		scsi_unprobe(devp);
1246 		ddi_prop_remove_all(devi);
1247 		ddi_remove_minor_node(devi, NULL);
1248 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1249 		return (DDI_SUCCESS);
1250 
1251 	case DDI_SUSPEND:
1252 
1253 		/*
1254 		 * Suspend/Resume
1255 		 *
1256 		 * To process DDI_SUSPEND, we must do the following:
1257 		 *
1258 		 *  - check ddi_removing_power to see if power will be turned
1259 		 *    off. if so, return DDI_FAILURE
1260 		 *  - check if we are already suspended,
1261 		 *    if so, return DDI_FAILURE
1262 		 *  - check if device state is CLOSED,
1263 		 *    if not, return DDI_FAILURE.
1264 		 *  - wait until outstanding operations complete
1265 		 *  - save tape state
1266 		 *  - block new operations
1267 		 *  - cancel pending timeouts
1268 		 *
1269 		 */
1270 
1271 		if (ddi_removing_power(devi)) {
1272 			return (DDI_FAILURE);
1273 		}
1274 		mutex_enter(ST_MUTEX);
1275 
1276 		/*
1277 		 * Shouldn't already be suspended, if so return failure
1278 		 */
1279 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1280 			mutex_exit(ST_MUTEX);
1281 			return (DDI_FAILURE);
1282 		}
1283 		if (un->un_state != ST_STATE_CLOSED) {
1284 			mutex_exit(ST_MUTEX);
1285 			return (DDI_FAILURE);
1286 		}
1287 
1288 		/*
1289 		 * Wait for all outstanding I/O's to complete
1290 		 *
1291 		 * we wait on both ncmds and the wait queue for times
1292 		 * when we are flushing after persistent errors are
1293 		 * flagged, which is when ncmds can be 0, and the
1294 		 * queue can still have I/O's.  This way we preserve
1295 		 * order of biodone's.
1296 		 */
1297 		wait_cmds_complete = ddi_get_lbolt();
1298 		wait_cmds_complete +=
1299 		    st_wait_cmds_complete * drv_usectohz(1000000);
1300 		while (un->un_ncmds || un->un_quef ||
1301 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1302 
1303 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1304 			    wait_cmds_complete) == -1) {
1305 				/*
1306 				 * Time expired then cancel the command
1307 				 */
1308 				mutex_exit(ST_MUTEX);
1309 				if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
1310 					mutex_enter(ST_MUTEX);
1311 					if (un->un_last_throttle) {
1312 						un->un_throttle =
1313 						    un->un_last_throttle;
1314 					}
1315 					mutex_exit(ST_MUTEX);
1316 					return (DDI_FAILURE);
1317 				} else {
1318 					mutex_enter(ST_MUTEX);
1319 					break;
1320 				}
1321 			}
1322 		}
1323 
1324 		/*
1325 		 * DDI_SUSPEND says that the system "may" power down, we
1326 		 * remember the file and block number before rewinding.
1327 		 * we also need to save state before issuing
1328 		 * any WRITE_FILE_MARK command.
1329 		 */
1330 		(void) st_update_block_pos(un);
1331 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1332 
1333 		dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
1334 		    un->un_dev);
1335 
1336 		/*
1337 		 * Issue a zero write file fmk command to tell the drive to
1338 		 * flush any buffered tape marks
1339 		 */
1340 		(void) st_cmd(dev_instance, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1341 
1342 		/*
1343 		 * Because not all tape drives correctly implement buffer
1344 		 * flushing with the zero write file fmk command, issue a
1345 		 * synchronous rewind command to force data flushing.
1346 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1347 		 * anyway.
1348 		 */
1349 		(void) st_cmd(dev_instance, SCMD_REWIND, 0, SYNC_CMD);
1350 
1351 		/* stop any new operations */
1352 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1353 		un->un_throttle = 0;
1354 
1355 		/*
1356 		 * cancel any outstanding timeouts
1357 		 */
1358 		if (un->un_delay_tid) {
1359 			timeout_id_t temp_id = un->un_delay_tid;
1360 			un->un_delay_tid = 0;
1361 			un->un_tids_at_suspend |= ST_DELAY_TID;
1362 			mutex_exit(ST_MUTEX);
1363 			(void) untimeout(temp_id);
1364 			mutex_enter(ST_MUTEX);
1365 		}
1366 
1367 		if (un->un_hib_tid) {
1368 			timeout_id_t temp_id = un->un_hib_tid;
1369 			un->un_hib_tid = 0;
1370 			un->un_tids_at_suspend |= ST_HIB_TID;
1371 			mutex_exit(ST_MUTEX);
1372 			(void) untimeout(temp_id);
1373 			mutex_enter(ST_MUTEX);
1374 		}
1375 
1376 		/*
1377 		 * Suspend the scsi_watch_thread
1378 		 */
1379 		if (un->un_swr_token) {
1380 			opaque_t temp_token = un->un_swr_token;
1381 			mutex_exit(ST_MUTEX);
1382 			scsi_watch_suspend(temp_token);
1383 		} else {
1384 			mutex_exit(ST_MUTEX);
1385 		}
1386 
1387 		return (DDI_SUCCESS);
1388 
1389 	default:
1390 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1391 		return (DDI_FAILURE);
1392 	}
1393 }
1394 
1395 
1396 /* ARGSUSED */
1397 static int
1398 stinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1399 {
1400 	dev_t dev;
1401 	struct scsi_tape *un;
1402 	int instance, error;
1403 
1404 	ST_ENTR(dip, stinfo);
1405 
1406 	switch (infocmd) {
1407 	case DDI_INFO_DEVT2DEVINFO:
1408 		dev = (dev_t)arg;
1409 		instance = MTUNIT(dev);
1410 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1411 			return (DDI_FAILURE);
1412 		*result = (void *) ST_DEVINFO;
1413 		error = DDI_SUCCESS;
1414 		break;
1415 	case DDI_INFO_DEVT2INSTANCE:
1416 		dev = (dev_t)arg;
1417 		instance = MTUNIT(dev);
1418 		*result = (void *)(uintptr_t)instance;
1419 		error = DDI_SUCCESS;
1420 		break;
1421 	default:
1422 		error = DDI_FAILURE;
1423 	}
1424 	return (error);
1425 }
1426 
1427 static int
1428 st_doattach(struct scsi_device *devp, int (*canwait)())
1429 {
1430 	struct scsi_pkt *rqpkt = NULL;
1431 	struct scsi_tape *un = NULL;
1432 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1433 	int instance;
1434 	struct buf *bp;
1435 	size_t rlen;
1436 
1437 	ST_FUNC(devp->sd_dev, st_doattach);
1438 	/*
1439 	 * Call the routine scsi_probe to do some of the dirty work.
1440 	 * If the INQUIRY command succeeds, the field sd_inq in the
1441 	 * device structure will be filled in.
1442 	 */
1443 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1444 	    "st_doattach(): probing\n");
1445 
1446 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1447 
1448 		/*
1449 		 * In checking the whole inq_dtype byte we are looking at both
1450 		 * the Peripheral Qualifier and the Peripheral Device Type.
1451 		 * For this driver we are only interested in sequential devices
1452 		 * that are connected or capable if connecting to this logical
1453 		 * unit.
1454 		 */
1455 		if (devp->sd_inq->inq_dtype ==
1456 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1457 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1458 			    "probe exists\n");
1459 		} else {
1460 			/* Something there but not a tape device */
1461 			scsi_unprobe(devp);
1462 			return (DDI_FAILURE);
1463 		}
1464 	} else {
1465 		/* Nothing there */
1466 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1467 		    "probe failure: nothing there\n");
1468 		scsi_unprobe(devp);
1469 		return (DDI_FAILURE);
1470 	}
1471 
1472 	bp = scsi_alloc_consistent_buf(&devp->sd_address, (struct buf *)NULL,
1473 	    SENSE_LENGTH, B_READ, canwait, NULL);
1474 	if (!bp) {
1475 		goto error;
1476 	}
1477 	rqpkt = scsi_init_pkt(&devp->sd_address, NULL, bp, CDB_GROUP0, 1, 0,
1478 	    PKT_CONSISTENT, canwait, NULL);
1479 	if (!rqpkt) {
1480 		goto error;
1481 	}
1482 	devp->sd_sense = (struct scsi_extended_sense *)bp->b_un.b_addr;
1483 	ASSERT(geterror(bp) == NULL);
1484 
1485 	(void) scsi_setup_cdb((union scsi_cdb *)rqpkt->pkt_cdbp,
1486 	    SCMD_REQUEST_SENSE, 0, SENSE_LENGTH, 0);
1487 	FILL_SCSI1_LUN(devp, rqpkt);
1488 
1489 	/*
1490 	 * The actual unit is present.
1491 	 * Now is the time to fill in the rest of our info..
1492 	 */
1493 	instance = ddi_get_instance(devp->sd_dev);
1494 
1495 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1496 		goto error;
1497 	}
1498 	un = ddi_get_soft_state(st_state, instance);
1499 
1500 	ASSERT(un != NULL);
1501 
1502 	un->un_sbufp = getrbuf(km_flags);
1503 
1504 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1505 
1506 	/*
1507 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1508 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1509 	 * is obsolete and we want more flexibility in controlling the DMA
1510 	 * address constraints.
1511 	 */
1512 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1513 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1514 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1515 
1516 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1517 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1518 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1519 
1520 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1521 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1522 		    "probe partial failure: no space\n");
1523 		goto error;
1524 	}
1525 
1526 	bzero(un->un_mspl, sizeof (struct seq_mode));
1527 
1528 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1529 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1530 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1531 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1532 #ifdef	__x86
1533 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1534 #endif
1535 
1536 	/* Initialize power managemnet condition variable */
1537 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1538 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1539 
1540 	rqpkt->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1541 
1542 	un->un_pos.pmode = invalid;
1543 	rqpkt->pkt_time = st_io_time;
1544 	rqpkt->pkt_comp = st_intr;
1545 	un->un_rqs	= rqpkt;
1546 	un->un_sd	= devp;
1547 	un->un_rqs_bp	= bp;
1548 	un->un_swr_token = (opaque_t)NULL;
1549 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1550 	un->un_wormable = st_is_drive_worm;
1551 	un->un_read_pos_type = LONG_POS;
1552 
1553 	un->un_suspend_pos.pmode = invalid;
1554 
1555 #ifdef	__x86
1556 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1557 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1558 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1559 		    "allocation of contiguous memory dma handle failed!");
1560 		un->un_contig_mem_hdl = NULL;
1561 		goto error;
1562 	}
1563 #endif
1564 
1565 	/*
1566 	 * Since this driver manages devices with "remote" hardware,
1567 	 * i.e. the devices themselves have no "reg" properties,
1568 	 * the SUSPEND/RESUME commands in detach/attach will not be
1569 	 * called by the power management framework unless we request
1570 	 * it by creating a "pm-hardware-state" property and setting it
1571 	 * to value "needs-suspend-resume".
1572 	 */
1573 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1574 	    "pm-hardware-state", "needs-suspend-resume") !=
1575 	    DDI_PROP_SUCCESS) {
1576 
1577 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1578 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1579 		goto error;
1580 	}
1581 
1582 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1583 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1584 
1585 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1586 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1587 		    "failed\n");
1588 		goto error;
1589 	}
1590 
1591 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "probe success\n");
1592 	return (DDI_SUCCESS);
1593 
1594 error:
1595 	devp->sd_sense = NULL;
1596 
1597 	ddi_remove_minor_node(devp->sd_dev, NULL);
1598 	if (un) {
1599 		if (un->un_mspl) {
1600 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1601 		}
1602 		if (un->un_read_pos_data) {
1603 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1604 		}
1605 		if (un->un_sbufp) {
1606 			freerbuf(un->un_sbufp);
1607 		}
1608 		if (un->un_uscsi_rqs_buf) {
1609 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1610 		}
1611 #ifdef	__x86
1612 		if (un->un_contig_mem_hdl != NULL) {
1613 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1614 		}
1615 #endif
1616 		ddi_soft_state_free(st_state, instance);
1617 		devp->sd_private = NULL;
1618 	}
1619 
1620 	if (rqpkt) {
1621 		scsi_destroy_pkt(rqpkt);
1622 	}
1623 
1624 	if (bp) {
1625 		scsi_free_consistent_buf(bp);
1626 	}
1627 
1628 	if (devp->sd_inq) {
1629 		scsi_unprobe(devp);
1630 	}
1631 	return (DDI_FAILURE);
1632 }
1633 
1634 typedef int
1635 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1636 
1637 static cfg_functp config_functs[] = {
1638 	st_get_conf_from_st_dot_conf,
1639 	st_get_conf_from_st_conf_dot_c,
1640 	st_get_default_conf
1641 };
1642 
1643 
1644 /*
1645  * determine tape type, using tape-config-list or built-in table or
1646  * use a generic tape config entry
1647  */
1648 static void
1649 st_known_tape_type(struct scsi_tape *un)
1650 {
1651 	struct st_drivetype *dp;
1652 	cfg_functp *config_funct;
1653 
1654 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1655 	/*
1656 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1657 	 *	 no vid & pid inquiry data.  So, we provide one.
1658 	 */
1659 	if (ST_INQUIRY->inq_len == 0 ||
1660 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1661 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1662 	}
1663 
1664 	un->un_dp_size = sizeof (struct st_drivetype);
1665 	dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1666 	un->un_dp = dp;
1667 
1668 	/*
1669 	 * Loop through the configuration methods till one works.
1670 	 */
1671 	for (config_funct = &config_functs[0]; ; config_funct++) {
1672 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1673 			break;
1674 		}
1675 	}
1676 
1677 	/*
1678 	 * If we didn't just make up this configuration and
1679 	 * all the density codes are the same..
1680 	 * Set Auto Density over ride.
1681 	 */
1682 	if (*config_funct != st_get_default_conf) {
1683 		/*
1684 		 * If this device is one that is configured and all
1685 		 * densities are the same, This saves doing gets and set
1686 		 * that yield nothing.
1687 		 */
1688 		if ((dp->densities[0]) == (dp->densities[1]) &&
1689 		    (dp->densities[0]) == (dp->densities[2]) &&
1690 		    (dp->densities[0]) == (dp->densities[3])) {
1691 
1692 			dp->options |= ST_AUTODEN_OVERRIDE;
1693 		}
1694 	}
1695 
1696 
1697 	/*
1698 	 * Store tape drive characteristics.
1699 	 */
1700 	un->un_status = 0;
1701 	un->un_attached = 1;
1702 	un->un_init_options = dp->options;
1703 
1704 	/* setup operation time-outs based on options */
1705 	st_calculate_timeouts(un);
1706 
1707 	/* make sure if we are supposed to be variable, make it variable */
1708 	if (dp->options & ST_VARIABLE) {
1709 		dp->bsize = 0;
1710 	}
1711 
1712 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1713 }
1714 
1715 
1716 typedef struct {
1717 	int mask;
1718 	int bottom;
1719 	int top;
1720 	char *name;
1721 } conf_limit;
1722 
1723 static const conf_limit conf_limits[] = {
1724 
1725 	-1,		1,		2,		"conf version",
1726 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1727 	-1,		0,		0xffffff,	"block size",
1728 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1729 	-1,		0,		4,		"number of densities",
1730 	-1,		0,		UINT8_MAX,	"density code",
1731 	-1,		0,		3,		"default density",
1732 	-1,		0,		UINT16_MAX,	"non motion timeout",
1733 	-1,		0,		UINT16_MAX,	"I/O timeout",
1734 	-1,		0,		UINT16_MAX,	"space timeout",
1735 	-1,		0,		UINT16_MAX,	"load timeout",
1736 	-1,		0,		UINT16_MAX,	"unload timeout",
1737 	-1,		0,		UINT16_MAX,	"erase timeout",
1738 	0,		0,		0,		NULL
1739 };
1740 
1741 static int
1742 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1743     const char *conf_name)
1744 {
1745 	int dens;
1746 	int ndens;
1747 	int value;
1748 	int type;
1749 	int count;
1750 	const conf_limit *limit = &conf_limits[0];
1751 
1752 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1753 
1754 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1755 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1756 
1757 	count = list_len;
1758 	type = *list;
1759 	for (;  count && limit->name; count--, list++, limit++) {
1760 
1761 		value = *list;
1762 		if (value & ~limit->mask) {
1763 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1764 			    "%s %s value invalid bits set: 0x%X\n",
1765 			    conf_name, limit->name, value & ~limit->mask);
1766 			*list &= limit->mask;
1767 		} else if (value < limit->bottom) {
1768 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1769 			    "%s %s value too low: value = %d limit %d\n",
1770 			    conf_name, limit->name, value, limit->bottom);
1771 		} else if (value > limit->top) {
1772 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1773 			    "%s %s value too high: value = %d limit %d\n",
1774 			    conf_name, limit->name, value, limit->top);
1775 		} else {
1776 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1777 			    "%s %s value = 0x%X\n",
1778 			    conf_name, limit->name, value);
1779 		}
1780 
1781 		/* If not the number of densities continue */
1782 		if (limit != &conf_limits[4]) {
1783 			continue;
1784 		}
1785 
1786 		/* If number of densities is not in range can't use config */
1787 		if (value < limit->bottom || value > limit->top) {
1788 			return (-1);
1789 		}
1790 
1791 		ndens = min(value, NDENSITIES);
1792 		if ((type == 1) && (list_len - ndens) != 6) {
1793 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1794 			    "%s conf version 1 with %d densities has %d items"
1795 			    " should have %d",
1796 			    conf_name, ndens, list_len, 6 + ndens);
1797 		} else if ((type == 2) && (list_len - ndens) != 13) {
1798 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1799 			    "%s conf version 2 with %d densities has %d items"
1800 			    " should have %d",
1801 			    conf_name, ndens, list_len, 13 + ndens);
1802 		}
1803 
1804 		limit++;
1805 		for (dens = 0; dens < ndens && count; dens++) {
1806 			count--;
1807 			list++;
1808 			value = *list;
1809 			if (value < limit->bottom) {
1810 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1811 				    "%s density[%d] value too low: value ="
1812 				    " 0x%X limit 0x%X\n",
1813 				    conf_name, dens, value, limit->bottom);
1814 			} else if (value > limit->top) {
1815 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1816 				    "%s density[%d] value too high: value ="
1817 				    " 0x%X limit 0x%X\n",
1818 				    conf_name, dens, value, limit->top);
1819 			} else {
1820 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1821 				    "%s density[%d] value = 0x%X\n",
1822 				    conf_name, dens, value);
1823 			}
1824 		}
1825 	}
1826 
1827 	return (0);
1828 }
1829 
1830 static int
1831 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
1832     struct st_drivetype *dp)
1833 {
1834 	caddr_t config_list = NULL;
1835 	caddr_t data_list = NULL;
1836 	int	*data_ptr;
1837 	caddr_t vidptr, prettyptr, datanameptr;
1838 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
1839 	int config_list_len, data_list_len, len, i;
1840 	int version;
1841 	int found = 0;
1842 
1843 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
1844 
1845 	/*
1846 	 * Determine type of tape controller. Type is determined by
1847 	 * checking the vendor ids of the earlier inquiry command and
1848 	 * comparing those with vids in tape-config-list defined in st.conf
1849 	 */
1850 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
1851 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
1852 	    != DDI_PROP_SUCCESS) {
1853 		return (found);
1854 	}
1855 
1856 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
1857 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
1858 
1859 	/*
1860 	 * Compare vids in each triplet - if it matches, get value for
1861 	 * data_name and contruct a st_drivetype struct
1862 	 * tripletlen is not set yet!
1863 	 */
1864 	for (len = config_list_len, vidptr = config_list;
1865 	    len > 0;
1866 	    vidptr += tripletlen, len -= tripletlen) {
1867 
1868 		vidlen = strlen(vidptr);
1869 		prettyptr = vidptr + vidlen + 1;
1870 		prettylen = strlen(prettyptr);
1871 		datanameptr = prettyptr + prettylen + 1;
1872 		datanamelen = strlen(datanameptr);
1873 		tripletlen = vidlen + prettylen + datanamelen + 3;
1874 
1875 		if (vidlen == 0) {
1876 			continue;
1877 		}
1878 
1879 		/*
1880 		 * If inquiry vid dosen't match this triplets vid,
1881 		 * try the next.
1882 		 */
1883 		if (strncasecmp(vidpid, vidptr, vidlen)) {
1884 			continue;
1885 		}
1886 
1887 		/*
1888 		 * if prettylen is zero then use the vid string
1889 		 */
1890 		if (prettylen == 0) {
1891 			prettyptr = vidptr;
1892 			prettylen = vidlen;
1893 		}
1894 
1895 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1896 		    "vid = %s, pretty=%s, dataname = %s\n",
1897 		    vidptr, prettyptr, datanameptr);
1898 
1899 		/*
1900 		 * get the data list
1901 		 */
1902 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
1903 		    datanameptr, (caddr_t)&data_list,
1904 		    &data_list_len) != DDI_PROP_SUCCESS) {
1905 			/*
1906 			 * Error in getting property value
1907 			 * print warning!
1908 			 */
1909 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1910 			    "data property (%s) has no value\n",
1911 			    datanameptr);
1912 			continue;
1913 		}
1914 
1915 		/*
1916 		 * now initialize the st_drivetype struct
1917 		 */
1918 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
1919 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
1920 		(void) strncpy(dp->vid, vidptr, dp->length);
1921 		data_ptr = (int *)data_list;
1922 		/*
1923 		 * check if data is enough for version, type,
1924 		 * bsize, options, # of densities, density1,
1925 		 * density2, ..., default_density
1926 		 */
1927 		if ((data_list_len < 5 * sizeof (int)) ||
1928 		    (data_list_len < 6 * sizeof (int) +
1929 		    *(data_ptr + 4) * sizeof (int))) {
1930 			/*
1931 			 * print warning and skip to next triplet.
1932 			 */
1933 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1934 			    "data property (%s) incomplete\n",
1935 			    datanameptr);
1936 			kmem_free(data_list, data_list_len);
1937 			continue;
1938 		}
1939 
1940 		if (st_validate_conf_data(un, data_ptr,
1941 		    data_list_len / sizeof (int), datanameptr)) {
1942 			kmem_free(data_list, data_list_len);
1943 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1944 			    "data property (%s) rejected\n",
1945 			    datanameptr);
1946 			continue;
1947 		}
1948 
1949 		/*
1950 		 * check version
1951 		 */
1952 		version = *data_ptr++;
1953 		if (version != 1 && version != 2) {
1954 			/* print warning but accept it */
1955 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1956 			    "Version # for data property (%s) "
1957 			    "not set to 1 or 2\n", datanameptr);
1958 		}
1959 
1960 		dp->type    = *data_ptr++;
1961 		dp->bsize   = *data_ptr++;
1962 		dp->options = *data_ptr++;
1963 		dp->options |= ST_DYNAMIC;
1964 		len = *data_ptr++;
1965 		for (i = 0; i < NDENSITIES; i++) {
1966 			if (i < len) {
1967 				dp->densities[i] = *data_ptr++;
1968 			}
1969 		}
1970 		dp->default_density = *data_ptr << 3;
1971 		if (version == 2 &&
1972 		    data_list_len >= (13 + len) * sizeof (int)) {
1973 			data_ptr++;
1974 			dp->non_motion_timeout	= *data_ptr++;
1975 			dp->io_timeout		= *data_ptr++;
1976 			dp->rewind_timeout	= *data_ptr++;
1977 			dp->space_timeout	= *data_ptr++;
1978 			dp->load_timeout	= *data_ptr++;
1979 			dp->unload_timeout	= *data_ptr++;
1980 			dp->erase_timeout	= *data_ptr++;
1981 		}
1982 		kmem_free(data_list, data_list_len);
1983 		found = 1;
1984 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1985 		    "found in st.conf: vid = %s, pretty=%s\n",
1986 		    dp->vid, dp->name);
1987 		break;
1988 	}
1989 
1990 	/*
1991 	 * free up the memory allocated by ddi_getlongprop
1992 	 */
1993 	if (config_list) {
1994 		kmem_free(config_list, config_list_len);
1995 	}
1996 	return (found);
1997 }
1998 
1999 static int
2000 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2001     struct st_drivetype *dp)
2002 {
2003 	int i;
2004 
2005 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2006 	/*
2007 	 * Determine type of tape controller.  Type is determined by
2008 	 * checking the result of the earlier inquiry command and
2009 	 * comparing vendor ids with strings in a table declared in st_conf.c.
2010 	 */
2011 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2012 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2013 
2014 	for (i = 0; i < st_ndrivetypes; i++) {
2015 		if (st_drivetypes[i].length == 0) {
2016 			continue;
2017 		}
2018 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2019 		    st_drivetypes[i].length)) {
2020 			continue;
2021 		}
2022 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2023 		return (1);
2024 	}
2025 	return (0);
2026 }
2027 
2028 static int
2029 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2030 {
2031 	int i;
2032 
2033 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2034 
2035 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2036 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2037 
2038 
2039 	/*
2040 	 * Make up a name
2041 	 */
2042 	bcopy("Vendor '", dp->name, 8);
2043 	bcopy(vidpid, &dp->name[8], VIDLEN);
2044 	bcopy("' Product '", &dp->name[16], 11);
2045 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2046 	dp->name[ST_NAMESIZE - 2] = '\'';
2047 	dp->name[ST_NAMESIZE - 1] = '\0';
2048 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2049 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2050 	/*
2051 	 * 'clean' vendor and product strings of non-printing chars
2052 	 */
2053 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2054 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2055 			dp->name[i] = '.';
2056 		}
2057 	}
2058 	dp->type = ST_TYPE_INVALID;
2059 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2060 
2061 	return (1); /* Can Not Fail */
2062 }
2063 
2064 /*
2065  * Regular Unix Entry points
2066  */
2067 
2068 
2069 
2070 /* ARGSUSED */
2071 static int
2072 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2073 {
2074 	dev_t dev = *dev_p;
2075 	int rval = 0;
2076 
2077 	GET_SOFT_STATE(dev);
2078 
2079 	ST_ENTR(ST_DEVINFO, st_open);
2080 
2081 	/*
2082 	 * validate that we are addressing a sensible unit
2083 	 */
2084 	mutex_enter(ST_MUTEX);
2085 
2086 #ifdef	STDEBUG
2087 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2088 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2089 	    st_dev_name(dev), *dev_p, flag, otyp);
2090 #endif
2091 
2092 	/*
2093 	 * All device accesss go thru st_strategy() where we check
2094 	 * suspend status
2095 	 */
2096 
2097 	if (!un->un_attached) {
2098 		st_known_tape_type(un);
2099 		if (!un->un_attached) {
2100 			rval = ENXIO;
2101 			goto exit;
2102 		}
2103 
2104 	}
2105 
2106 	/*
2107 	 * Check for the case of the tape in the middle of closing.
2108 	 * This isn't simply a check of the current state, because
2109 	 * we could be in state of sensing with the previous state
2110 	 * that of closing.
2111 	 *
2112 	 * And don't allow multiple opens.
2113 	 */
2114 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2115 		un->un_laststate = un->un_state;
2116 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2117 		while (IS_CLOSING(un) ||
2118 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2119 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2120 				rval = EINTR;
2121 				un->un_state = un->un_laststate;
2122 				goto exit;
2123 			}
2124 		}
2125 	} else if (un->un_state != ST_STATE_CLOSED) {
2126 		rval = EBUSY;
2127 		goto busy;
2128 	}
2129 
2130 	/*
2131 	 * record current dev
2132 	 */
2133 	un->un_dev = dev;
2134 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2135 	un->un_errno = 0;	/* no errors yet */
2136 	un->un_restore_pos = 0;
2137 	un->un_rqs_state = 0;
2138 
2139 	/*
2140 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2141 	 * anything, leave internal states alone, if fileno >= 0
2142 	 */
2143 	if (flag & (FNDELAY | FNONBLOCK)) {
2144 		switch (un->un_pos.pmode) {
2145 
2146 		case invalid:
2147 			un->un_state = ST_STATE_OFFLINE;
2148 			break;
2149 
2150 		case legacy:
2151 			/*
2152 			 * If position is anything other than rewound.
2153 			 */
2154 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2155 				/*
2156 				 * set un_read_only/write-protect status.
2157 				 *
2158 				 * If the tape is not bot we can assume
2159 				 * that mspl->wp_status is set properly.
2160 				 * else
2161 				 * we need to do a mode sense/Tur once
2162 				 * again to get the actual tape status.(since
2163 				 * user might have replaced the tape)
2164 				 * Hence make the st state OFFLINE so that
2165 				 * we re-intialize the tape once again.
2166 				 */
2167 				un->un_read_only =
2168 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2169 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2170 			} else {
2171 				un->un_state = ST_STATE_OFFLINE;
2172 			}
2173 			break;
2174 		case logical:
2175 			/* swag not sure how we were open last time */
2176 			(void) st_update_block_pos(un);
2177 			if (un->un_pos.lgclblkno == 0) {
2178 				un->un_state = ST_STATE_OFFLINE;
2179 			} else {
2180 				un->un_read_only =
2181 				    (un->un_oflags & FWRITE) ? 0 : 1;
2182 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2183 			}
2184 			break;
2185 		}
2186 		rval = 0;
2187 	} else {
2188 		/*
2189 		 * Not opening O_NDELAY.
2190 		 */
2191 		un->un_state = ST_STATE_OPENING;
2192 
2193 		/*
2194 		 * Clear error entry stack
2195 		 */
2196 		st_empty_error_stack(un);
2197 
2198 		rval = st_tape_init(dev);
2199 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2200 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2201 			rval = 0; /* so open doesn't fail */
2202 		} else if (rval) {
2203 			/*
2204 			 * Release the tape unit, if reserved and not
2205 			 * preserve reserve.
2206 			 */
2207 			if ((un->un_rsvd_status &
2208 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2209 				(void) st_reserve_release(un, ST_RELEASE);
2210 			}
2211 		} else {
2212 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2213 		}
2214 	}
2215 
2216 exit:
2217 	/*
2218 	 * we don't want any uninvited guests scrogging our data when we're
2219 	 * busy with something, so for successful opens or failed opens
2220 	 * (except for EBUSY), reset these counters and state appropriately.
2221 	 */
2222 	if (rval != EBUSY) {
2223 		if (rval) {
2224 			un->un_state = ST_STATE_CLOSED;
2225 		}
2226 		un->un_err_resid = 0;
2227 		un->un_retry_ct = 0;
2228 		un->un_tran_retry_ct = 0;
2229 	}
2230 busy:
2231 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2232 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2233 	mutex_exit(ST_MUTEX);
2234 	return (rval);
2235 
2236 }
2237 
2238 static int
2239 st_tape_init(dev_t dev)
2240 {
2241 	int err;
2242 	int rval = 0;
2243 
2244 	GET_SOFT_STATE(dev);
2245 
2246 	ST_FUNC(ST_DEVINFO, st_tape_init);
2247 
2248 	ASSERT(mutex_owned(ST_MUTEX));
2249 
2250 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2251 	    "st_tape_init(dev = 0x%lx, oflags = %d)\n", dev, un->un_oflags);
2252 
2253 	/*
2254 	 * Clean up after any errors left by 'last' close.
2255 	 * This also handles the case of the initial open.
2256 	 */
2257 	if (un->un_state != ST_STATE_INITIALIZING) {
2258 		un->un_laststate = un->un_state;
2259 		un->un_state = ST_STATE_OPENING;
2260 	}
2261 
2262 	un->un_kbytes_xferred = 0;
2263 
2264 	/*
2265 	 * do a throw away TUR to clear check condition
2266 	 */
2267 	err = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2268 
2269 	/*
2270 	 * If test unit ready fails because the drive is reserved
2271 	 * by another host fail the open for no access.
2272 	 */
2273 	if (err) {
2274 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2275 			un->un_state = ST_STATE_CLOSED;
2276 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2277 			    "st_tape_init: RESERVATION CONFLICT\n");
2278 			rval = EACCES;
2279 			goto exit;
2280 		}
2281 	}
2282 
2283 	/*
2284 	 * See whether this is a generic device that we haven't figured
2285 	 * anything out about yet.
2286 	 */
2287 	if (un->un_dp->type == ST_TYPE_INVALID) {
2288 		rval = st_determine_generic(dev);
2289 		if (rval) {
2290 			if (rval != EACCES) {
2291 				rval = EIO;
2292 			}
2293 			un->un_state = ST_STATE_CLOSED;
2294 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2295 			    "st_tape_init: %s invalid type\n",
2296 			    rval == EACCES ? "EACCES" : "EIO");
2297 			goto exit;
2298 		}
2299 		/*
2300 		 * If this is a Unknown Type drive,
2301 		 * Use the READ BLOCK LIMITS to determine if
2302 		 * allow large xfer is approprate if not globally
2303 		 * disabled with st_allow_large_xfer.
2304 		 */
2305 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
2306 	} else {
2307 
2308 		/*
2309 		 * If we allow_large_xfer (ie >64k) and have not yet found out
2310 		 * the max block size supported by the drive,
2311 		 * find it by issueing a READ_BLKLIM command.
2312 		 * if READ_BLKLIM cmd fails, assume drive doesn't
2313 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
2314 		 */
2315 		un->un_allow_large_xfer = st_allow_large_xfer &&
2316 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
2317 	}
2318 	/*
2319 	 * if maxbsize is unknown, set the maximum block size.
2320 	 */
2321 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
2322 
2323 		/*
2324 		 * Get the Block limits of the tape drive.
2325 		 * if un->un_allow_large_xfer = 0 , then make sure
2326 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
2327 		 */
2328 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
2329 
2330 		err = st_cmd(dev, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2331 		if (err) {
2332 			/* Retry */
2333 			err = st_cmd(dev, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2334 		}
2335 		if (!err) {
2336 
2337 			/*
2338 			 * if cmd successful, use limit returned
2339 			 */
2340 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
2341 			    (un->un_rbl->max_mid << 8) +
2342 			    un->un_rbl->max_lo;
2343 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
2344 			    un->un_rbl->min_lo;
2345 			un->un_data_mod = 1 << un->un_rbl->granularity;
2346 			if ((un->un_maxbsize == 0) ||
2347 			    (un->un_allow_large_xfer == 0 &&
2348 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
2349 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2350 
2351 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
2352 				/*
2353 				 * Drive is not one that is configured, But the
2354 				 * READ BLOCK LIMITS tells us it can do large
2355 				 * xfers.
2356 				 */
2357 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
2358 					un->un_dp->options |=
2359 					    ST_NO_RECSIZE_LIMIT;
2360 				}
2361 				/*
2362 				 * If max and mimimum block limits are the
2363 				 * same this is a fixed block size device.
2364 				 */
2365 				if (un->un_maxbsize == un->un_minbsize) {
2366 					un->un_dp->options &= ~ST_VARIABLE;
2367 				}
2368 			}
2369 
2370 			if (un->un_minbsize == 0) {
2371 				un->un_minbsize = 1;
2372 			}
2373 
2374 		} else { /* error on read block limits */
2375 
2376 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2377 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
2378 			    " errno = %d un_rsvd_status = 0x%X\n",
2379 			    err, un->un_rsvd_status);
2380 
2381 			/*
2382 			 * since read block limits cmd failed,
2383 			 * do not allow large xfers.
2384 			 * use old values in st_minphys
2385 			 */
2386 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2387 				rval = EACCES;
2388 			} else {
2389 				un->un_allow_large_xfer = 0;
2390 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2391 				    "!Disabling large transfers\n");
2392 
2393 				/*
2394 				 * we guess maxbsize and minbsize
2395 				 */
2396 				if (un->un_bsize) {
2397 					un->un_maxbsize = un->un_minbsize =
2398 					    un->un_bsize;
2399 				} else {
2400 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2401 					un->un_minbsize = 1;
2402 				}
2403 				/*
2404 				 * Data Mod must be set,
2405 				 * Even if read block limits fails.
2406 				 * Prevents Divide By Zero in st_rw().
2407 				 */
2408 				un->un_data_mod = 1;
2409 			}
2410 		}
2411 		if (un->un_rbl) {
2412 			kmem_free(un->un_rbl, RBLSIZE);
2413 			un->un_rbl = NULL;
2414 		}
2415 
2416 		if (rval) {
2417 			goto exit;
2418 		}
2419 	}
2420 
2421 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
2422 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
2423 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
2424 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
2425 
2426 	err = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2427 
2428 	if (err != 0) {
2429 		if (err == EINTR) {
2430 			un->un_laststate = un->un_state;
2431 			un->un_state = ST_STATE_CLOSED;
2432 			rval = EINTR;
2433 			goto exit;
2434 		}
2435 		/*
2436 		 * Make sure the tape is ready
2437 		 */
2438 		un->un_pos.pmode = invalid;
2439 		if (un->un_status != KEY_UNIT_ATTENTION) {
2440 			/*
2441 			 * allow open no media.  Subsequent MTIOCSTATE
2442 			 * with media present will complete the open
2443 			 * logic.
2444 			 */
2445 			un->un_laststate = un->un_state;
2446 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
2447 				un->un_mediastate = MTIO_EJECTED;
2448 				un->un_state = ST_STATE_OFFLINE;
2449 				rval = 0;
2450 				goto exit;
2451 			} else {
2452 				un->un_state = ST_STATE_CLOSED;
2453 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2454 				    "st_tape_init EIO no media, not opened "
2455 				    "O_NONBLOCK|O_EXCL\n");
2456 				rval = EIO;
2457 				goto exit;
2458 			}
2459 		}
2460 	}
2461 
2462 	/*
2463 	 * On each open, initialize block size from drivetype struct,
2464 	 * as it could have been changed by MTSRSZ ioctl.
2465 	 * Now, ST_VARIABLE simply means drive is capable of variable
2466 	 * mode. All drives are assumed to support fixed records.
2467 	 * Hence, un_bsize tells what mode the drive is in.
2468 	 *	un_bsize	= 0	- variable record length
2469 	 *			= x	- fixed record length is x
2470 	 */
2471 	un->un_bsize = un->un_dp->bsize;
2472 
2473 	/*
2474 	 * If saved position is valid go there
2475 	 */
2476 	if (un->un_restore_pos) {
2477 		rval = st_validate_tapemarks(un, &un->un_pos);
2478 		if (rval != 0) {
2479 			if (rval != EACCES) {
2480 				rval = EIO;
2481 			}
2482 			un->un_restore_pos = 0;
2483 			un->un_laststate = un->un_state;
2484 			un->un_state = ST_STATE_CLOSED;
2485 			goto exit;
2486 		}
2487 		un->un_pos.fileno = un->un_save_fileno;
2488 		un->un_pos.blkno = un->un_save_blkno;
2489 		un->un_restore_pos = 0;
2490 	}
2491 
2492 	if (un->un_pos.pmode == invalid) {
2493 		rval = st_loadtape(dev);
2494 		if (rval) {
2495 			if (rval != EACCES) {
2496 				rval = EIO;
2497 			}
2498 			un->un_laststate = un->un_state;
2499 			un->un_state = ST_STATE_CLOSED;
2500 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2501 			    "st_tape_init: %s can't open tape\n",
2502 			    rval == EACCES ? "EACCES" : "EIO");
2503 			goto exit;
2504 		}
2505 	}
2506 
2507 	/*
2508 	 * do a mode sense to pick up state of current write-protect,
2509 	 * Could cause reserve and fail due to conflict.
2510 	 */
2511 	rval = st_modesense(un);
2512 	if (rval == EACCES) {
2513 		goto exit;
2514 	}
2515 
2516 	/*
2517 	 * If we are opening the tape for writing, check
2518 	 * to make sure that the tape can be written.
2519 	 */
2520 	if (un->un_oflags & FWRITE) {
2521 		err = 0;
2522 		if (un->un_mspl->wp) {
2523 			un->un_status = KEY_WRITE_PROTECT;
2524 			un->un_laststate = un->un_state;
2525 			un->un_state = ST_STATE_CLOSED;
2526 			rval = EACCES;
2527 			/*
2528 			 * STK sets the wp bit if volsafe tape is loaded.
2529 			 */
2530 			if ((un->un_dp->type == MT_ISSTK9840) &&
2531 			    (un->un_dp->options & ST_WORMABLE)) {
2532 				un->un_read_only = RDONLY;
2533 			} else {
2534 				goto exit;
2535 			}
2536 		} else {
2537 			un->un_read_only = RDWR;
2538 		}
2539 	} else {
2540 		un->un_read_only = RDONLY;
2541 	}
2542 
2543 	if (un->un_dp->options & ST_WORMABLE) {
2544 		un->un_read_only |= un->un_wormable(un);
2545 
2546 		if (((un->un_read_only == WORM) ||
2547 		    (un->un_read_only == RDWORM)) &&
2548 		    ((un->un_oflags & FWRITE) == FWRITE)) {
2549 			un->un_status = KEY_DATA_PROTECT;
2550 			rval = EACCES;
2551 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
2552 			    "read_only = %d eof = %d oflag = %d\n",
2553 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
2554 		}
2555 	}
2556 
2557 	/*
2558 	 * If we're opening the tape write-only, we need to
2559 	 * write 2 filemarks on the HP 1/2 inch drive, to
2560 	 * create a null file.
2561 	 */
2562 	if ((un->un_read_only == RDWR) ||
2563 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
2564 		if (un->un_dp->options & ST_REEL) {
2565 			un->un_fmneeded = 2;
2566 		} else {
2567 			un->un_fmneeded = 1;
2568 		}
2569 	} else {
2570 		un->un_fmneeded = 0;
2571 	}
2572 
2573 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
2574 	    "fmneeded = %x\n", un->un_fmneeded);
2575 
2576 	/*
2577 	 * Make sure the density can be selected correctly.
2578 	 * If WORM can only write at the append point which in most cases
2579 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
2580 	 * to set and try densities if a BOP.
2581 	 */
2582 	if (st_determine_density(dev,
2583 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
2584 		un->un_status = KEY_ILLEGAL_REQUEST;
2585 		un->un_laststate = un->un_state;
2586 		un->un_state = ST_STATE_CLOSED;
2587 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2588 		    "st_tape_init: EIO can't determine density\n");
2589 		rval = EIO;
2590 		goto exit;
2591 	}
2592 
2593 	/*
2594 	 * Destroy the knowledge that we have 'determined'
2595 	 * density so that a later read at BOT comes along
2596 	 * does the right density determination.
2597 	 */
2598 
2599 	un->un_density_known = 0;
2600 
2601 
2602 	/*
2603 	 * Okay, the tape is loaded and either at BOT or somewhere past.
2604 	 * Mark the state such that any I/O or tape space operations
2605 	 * will get/set the right density, etc..
2606 	 */
2607 	un->un_laststate = un->un_state;
2608 	un->un_lastop = ST_OP_NIL;
2609 	un->un_mediastate = MTIO_INSERTED;
2610 	cv_broadcast(&un->un_state_cv);
2611 
2612 	/*
2613 	 *  Set test append flag if writing.
2614 	 *  First write must check that tape is positioned correctly.
2615 	 */
2616 	un->un_test_append = (un->un_oflags & FWRITE);
2617 
2618 exit:
2619 	un->un_err_resid = 0;
2620 	un->un_last_resid = 0;
2621 	un->un_last_count = 0;
2622 
2623 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2624 	    "st_tape_init: return val = %x\n", rval);
2625 	return (rval);
2626 
2627 }
2628 
2629 
2630 
2631 /* ARGSUSED */
2632 static int
2633 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
2634 {
2635 	int err = 0;
2636 	int norew, count, last_state;
2637 #ifdef	__x86
2638 	struct contig_mem *cp, *cp_temp;
2639 #endif
2640 
2641 	GET_SOFT_STATE(dev);
2642 
2643 	ST_ENTR(ST_DEVINFO, st_close);
2644 
2645 	/*
2646 	 * wait till all cmds in the pipeline have been completed
2647 	 */
2648 	mutex_enter(ST_MUTEX);
2649 
2650 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2651 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
2652 
2653 	st_wait_for_io(un);
2654 
2655 	/* turn off persistent errors on close, as we want close to succeed */
2656 	TURN_PE_OFF(un);
2657 
2658 	/*
2659 	 * set state to indicate that we are in process of closing
2660 	 */
2661 	last_state = un->un_laststate = un->un_state;
2662 	un->un_state = ST_STATE_CLOSING;
2663 
2664 	/*
2665 	 * BSD behavior:
2666 	 * a close always causes a silent span to the next file if we've hit
2667 	 * an EOF (but not yet read across it).
2668 	 */
2669 #ifdef DEBUG
2670 	if ((st_debug & 0xf) >= 6)
2671 		st_print_position(un, "st_close1:", &un->un_pos);
2672 #endif
2673 
2674 	if (BSD_BEHAVIOR && (un->un_pos.eof == ST_EOF)) {
2675 		if (un->un_pos.pmode != invalid) {
2676 			un->un_pos.fileno++;
2677 			un->un_pos.blkno = 0;
2678 		}
2679 		un->un_pos.eof = ST_NO_EOF;
2680 	}
2681 
2682 	/*
2683 	 * rewinding?
2684 	 */
2685 	norew = (getminor(dev) & MT_NOREWIND);
2686 
2687 	/*
2688 	 * SVR4 behavior for skipping to next file:
2689 	 *
2690 	 * If we have not seen a filemark, space to the next file
2691 	 *
2692 	 * If we have already seen the filemark we are physically in the next
2693 	 * file and we only increment the filenumber
2694 	 */
2695 
2696 
2697 	if (norew && SVR4_BEHAVIOR && (flag & FREAD) &&
2698 	    (un->un_pos.blkno != 0) &&
2699 	    ((un->un_lastop != ST_OP_WRITE) && (un->un_lastop != ST_OP_WEOF))) {
2700 		switch (un->un_pos.eof) {
2701 		case ST_NO_EOF:
2702 			/*
2703 			 * if we were reading and did not read the complete file
2704 			 * skip to the next file, leaving the tape correctly
2705 			 * positioned to read the first record of the next file
2706 			 * Check first for REEL if we are at EOT by trying to
2707 			 * read a block
2708 			 */
2709 			if ((un->un_dp->options & ST_REEL) &&
2710 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
2711 			    (un->un_pos.blkno == 0)) {
2712 				if (st_cmd(dev, SCMD_SPACE, Blk(1), SYNC_CMD)) {
2713 					ST_DEBUG2(ST_DEVINFO, st_label,
2714 					    SCSI_DEBUG,
2715 					    "st_close : EIO can't space\n");
2716 					err = EIO;
2717 					break;
2718 				}
2719 				if (un->un_pos.eof >= ST_EOF_PENDING) {
2720 					un->un_pos.eof = ST_EOT_PENDING;
2721 					un->un_pos.fileno += 1;
2722 					un->un_pos.blkno   = 0;
2723 					break;
2724 				}
2725 			}
2726 			if (st_cmd(dev, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
2727 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2728 				    "st_close: EIO can't space #2\n");
2729 				err = EIO;
2730 			} else {
2731 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2732 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
2733 				    un->un_pos.fileno, un->un_pos.blkno,
2734 				    un->un_pos.eof);
2735 				un->un_pos.eof = ST_NO_EOF;
2736 			}
2737 			break;
2738 
2739 		case ST_EOF_PENDING:
2740 		case ST_EOF:
2741 			un->un_pos.fileno += 1;
2742 			un->un_pos.blkno   = 0;
2743 			un->un_pos.eof = ST_NO_EOF;
2744 			break;
2745 
2746 		case ST_EOT:
2747 		case ST_EOT_PENDING:
2748 			/* nothing to do */
2749 			break;
2750 		default:
2751 			scsi_log(ST_DEVINFO, st_label, CE_PANIC,
2752 			    "Undefined state 0x%x", un->un_pos.eof);
2753 
2754 		}
2755 	}
2756 
2757 
2758 	/*
2759 	 * For performance reasons (HP 88780), the driver should
2760 	 * postpone writing the second tape mark until just before a file
2761 	 * positioning ioctl is issued (e.g., rewind).	This means that
2762 	 * the user must not manually rewind the tape because the tape will
2763 	 * be missing the second tape mark which marks EOM.
2764 	 * However, this small performance improvement is not worth the risk.
2765 	 */
2766 
2767 	/*
2768 	 * We need to back up over the filemark we inadvertently popped
2769 	 * over doing a read in between the two filemarks that constitute
2770 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
2771 	 * set while reading.
2772 	 *
2773 	 * If we happen to be at physical eot (ST_EOM) (writing case),
2774 	 * the writing of filemark(s) will clear the ST_EOM state, which
2775 	 * we don't want, so we save this state and restore it later.
2776 	 */
2777 
2778 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2779 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
2780 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
2781 
2782 	if (un->un_pos.eof == ST_EOT_PENDING) {
2783 		if (norew) {
2784 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
2785 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2786 				    "st_close: EIO can't space #3\n");
2787 				err = EIO;
2788 			} else {
2789 				un->un_pos.blkno = 0;
2790 				un->un_pos.eof = ST_EOT;
2791 			}
2792 		} else {
2793 			un->un_pos.eof = ST_NO_EOF;
2794 		}
2795 
2796 	/*
2797 	 * Do we need to write a file mark?
2798 	 *
2799 	 * only write filemarks if there are fmks to be written and
2800 	 *   - open for write (possibly read/write)
2801 	 *   - the last operation was a write
2802 	 * or:
2803 	 *   -	opened for wronly
2804 	 *   -	no data was written
2805 	 */
2806 	} else if ((un->un_pos.pmode != invalid) && (un->un_fmneeded > 0) &&
2807 	    (((flag & FWRITE) && (un->un_lastop == ST_OP_WRITE)) ||
2808 	    ((flag & FWRITE) && (un->un_lastop == ST_OP_WEOF)) ||
2809 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
2810 
2811 		/* save ST_EOM state */
2812 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
2813 
2814 		/*
2815 		 * Note that we will write a filemark if we had opened
2816 		 * the tape write only and no data was written, thus
2817 		 * creating a null file.
2818 		 *
2819 		 * If the user already wrote one, we only have to write 1 more.
2820 		 * If they wrote two, we don't have to write any.
2821 		 */
2822 
2823 		count = un->un_fmneeded;
2824 		if (count > 0) {
2825 			if (st_cmd(dev, SCMD_WRITE_FILE_MARK,
2826 			    count, SYNC_CMD)) {
2827 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2828 				    "st_close : EIO can't wfm\n");
2829 				err = EIO;
2830 			}
2831 			if ((un->un_dp->options & ST_REEL) && norew) {
2832 				if (st_cmd(dev, SCMD_SPACE, Fmk((-1)),
2833 				    SYNC_CMD)) {
2834 					ST_DEBUG2(ST_DEVINFO, st_label,
2835 					    SCSI_DEBUG,
2836 					    "st_close : EIO space fmk(-1)\n");
2837 					err = EIO;
2838 				}
2839 				un->un_pos.eof = ST_NO_EOF;
2840 				/* fix up block number */
2841 				un->un_pos.blkno = 0;
2842 			}
2843 		}
2844 
2845 		/*
2846 		 * If we aren't going to be rewinding, and we were at
2847 		 * physical eot, restore the state that indicates we
2848 		 * are at physical eot. Once you have reached physical
2849 		 * eot, and you close the tape, the only thing you can
2850 		 * do on the next open is to rewind. Access to trailer
2851 		 * records is only allowed without closing the device.
2852 		 */
2853 		if (norew == 0 && was_at_eom) {
2854 			un->un_pos.eof = ST_EOM;
2855 		}
2856 	}
2857 
2858 	/*
2859 	 * report soft errors if enabled and available, if we never accessed
2860 	 * the drive, don't get errors. This will prevent some DAT error
2861 	 * messages upon LOG SENSE.
2862 	 */
2863 	if (st_report_soft_errors_on_close &&
2864 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
2865 	    (last_state != ST_STATE_OFFLINE)) {
2866 		(void) st_report_soft_errors(dev, flag);
2867 	}
2868 
2869 
2870 	/*
2871 	 * Do we need to rewind? Can we rewind?
2872 	 */
2873 	if (norew == 0 && un->un_pos.pmode != invalid && err == 0) {
2874 		/*
2875 		 * We'd like to rewind with the
2876 		 * 'immediate' bit set, but this
2877 		 * causes problems on some drives
2878 		 * where subsequent opens get a
2879 		 * 'NOT READY' error condition
2880 		 * back while the tape is rewinding,
2881 		 * which is impossible to distinguish
2882 		 * from the condition of 'no tape loaded'.
2883 		 *
2884 		 * Also, for some targets, if you disconnect
2885 		 * with the 'immediate' bit set, you don't
2886 		 * actually return right away, i.e., the
2887 		 * target ignores your request for immediate
2888 		 * return.
2889 		 *
2890 		 * Instead, we'll fire off an async rewind
2891 		 * command. We'll mark the device as closed,
2892 		 * and any subsequent open will stall on
2893 		 * the first TEST_UNIT_READY until the rewind
2894 		 * completes.
2895 		 */
2896 
2897 		/*
2898 		 * Used to be if reserve was not supported we'd send an
2899 		 * asynchronious rewind. Comments above may be slightly invalid
2900 		 * as the immediate bit was never set. Doing an immedate rewind
2901 		 * makes sense, I think fixes to not ready status might handle
2902 		 * the problems described above.
2903 		 */
2904 		if (un->un_sd->sd_inq->inq_ansi < 2) {
2905 			(void) st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
2906 		} else {
2907 			(void) st_cmd(dev, SCMD_REWIND, 0, ASYNC_CMD);
2908 		}
2909 	}
2910 
2911 	/*
2912 	 * eject tape if necessary
2913 	 */
2914 	if (un->un_eject_tape_on_failure) {
2915 		un->un_eject_tape_on_failure = 0;
2916 		if (st_cmd(dev, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
2917 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2918 			    "st_close : can't unload tape\n");
2919 		} else {
2920 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2921 			    "st_close : tape unloaded \n");
2922 			un->un_pos.eof = ST_NO_EOF;
2923 			un->un_mediastate = MTIO_EJECTED;
2924 		}
2925 	}
2926 	/*
2927 	 * Release the tape unit, if default reserve/release
2928 	 * behaviour.
2929 	 */
2930 	if ((un->un_rsvd_status &
2931 	    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2932 		(void) st_reserve_release(un, ST_RELEASE);
2933 	}
2934 
2935 	/*
2936 	 * clear up state
2937 	 */
2938 	un->un_laststate = un->un_state;
2939 	un->un_state = ST_STATE_CLOSED;
2940 	un->un_lastop = ST_OP_NIL;
2941 	un->un_throttle = 1;	/* assume one request at time, for now */
2942 	un->un_retry_ct = 0;
2943 	un->un_tran_retry_ct = 0;
2944 	un->un_errno = 0;
2945 	un->un_swr_token = (opaque_t)NULL;
2946 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
2947 
2948 	/* Restore the options to the init time settings */
2949 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
2950 		un->un_dp->options |= ST_READ_IGNORE_ILI;
2951 	} else {
2952 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
2953 	}
2954 
2955 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
2956 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
2957 	} else {
2958 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
2959 	}
2960 
2961 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
2962 		un->un_dp->options |= ST_SHORT_FILEMARKS;
2963 	} else {
2964 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
2965 	}
2966 
2967 	ASSERT(mutex_owned(ST_MUTEX));
2968 
2969 	/*
2970 	 * Signal anyone awaiting a close operation to complete.
2971 	 */
2972 	cv_signal(&un->un_clscv);
2973 
2974 	/*
2975 	 * any kind of error on closing causes all state to be tossed
2976 	 */
2977 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
2978 		/*
2979 		 * note that st_intr has already set
2980 		 * un_pos.pmode to invalid.
2981 		 */
2982 		un->un_density_known = 0;
2983 	}
2984 
2985 #ifdef	__x86
2986 	/*
2987 	 * free any contiguous mem alloc'ed for big block I/O
2988 	 */
2989 	cp = un->un_contig_mem;
2990 	while (cp) {
2991 		if (cp->cm_addr) {
2992 			ddi_dma_mem_free(&cp->cm_acc_hdl);
2993 		}
2994 		cp_temp = cp;
2995 		cp = cp->cm_next;
2996 		kmem_free(cp_temp,
2997 		    sizeof (struct contig_mem) + biosize());
2998 	}
2999 	un->un_contig_mem_total_num = 0;
3000 	un->un_contig_mem_available_num = 0;
3001 	un->un_contig_mem = NULL;
3002 	un->un_max_contig_mem_len = 0;
3003 #endif
3004 
3005 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3006 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3007 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3008 
3009 	mutex_exit(ST_MUTEX);
3010 	return (err);
3011 }
3012 
3013 /*
3014  * These routines perform raw i/o operations.
3015  */
3016 
3017 /* ARGSUSED2 */
3018 static int
3019 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3020 {
3021 #ifdef DEBUG
3022 	GET_SOFT_STATE(dev);
3023 	ST_ENTR(ST_DEVINFO, st_aread);
3024 #endif
3025 	return (st_arw(dev, aio, B_READ));
3026 }
3027 
3028 
3029 /* ARGSUSED2 */
3030 static int
3031 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3032 {
3033 #ifdef DEBUG
3034 	GET_SOFT_STATE(dev);
3035 	ST_ENTR(ST_DEVINFO, st_awrite);
3036 #endif
3037 	return (st_arw(dev, aio, B_WRITE));
3038 }
3039 
3040 
3041 
3042 /* ARGSUSED */
3043 static int
3044 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3045 {
3046 #ifdef DEBUG
3047 	GET_SOFT_STATE(dev);
3048 	ST_ENTR(ST_DEVINFO, st_read);
3049 #endif
3050 	return (st_rw(dev, uiop, B_READ));
3051 }
3052 
3053 /* ARGSUSED */
3054 static int
3055 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3056 {
3057 #ifdef DEBUG
3058 	GET_SOFT_STATE(dev);
3059 	ST_ENTR(ST_DEVINFO, st_write);
3060 #endif
3061 	return (st_rw(dev, uiop, B_WRITE));
3062 }
3063 
3064 /*
3065  * Due to historical reasons, old limits are: For variable-length devices:
3066  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3067  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3068  * (let it through unmodified. For fixed-length record devices:
3069  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3070  *
3071  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3072  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3073  * command to the drive).
3074  *
3075  */
3076 static void
3077 st_minphys(struct buf *bp)
3078 {
3079 	struct scsi_tape *un;
3080 
3081 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3082 
3083 	ST_FUNC(ST_DEVINFO, st_minphys);
3084 
3085 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3086 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3087 	    bp->b_bcount);
3088 
3089 	if (un->un_allow_large_xfer) {
3090 
3091 		/*
3092 		 * check un_maxbsize for variable length devices only
3093 		 */
3094 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3095 			bp->b_bcount = un->un_maxbsize;
3096 		}
3097 		/*
3098 		 * can't go more that HBA maxdma limit in either fixed-length
3099 		 * or variable-length tape drives.
3100 		 */
3101 		if (bp->b_bcount > un->un_maxdma) {
3102 			bp->b_bcount = un->un_maxdma;
3103 		}
3104 	} else {
3105 
3106 		/*
3107 		 *  use old fixed limits
3108 		 */
3109 		if (un->un_bsize == 0) {
3110 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3111 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3112 			}
3113 		} else {
3114 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3115 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3116 			}
3117 		}
3118 	}
3119 
3120 	/*
3121 	 * For regular raw I/O and Fixed Block length devices, make sure
3122 	 * the adjusted block count is a whole multiple of the device
3123 	 * block size.
3124 	 */
3125 	if (bp != un->un_sbufp && un->un_bsize) {
3126 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3127 	}
3128 }
3129 
3130 static int
3131 st_rw(dev_t dev, struct uio *uio, int flag)
3132 {
3133 	int rval = 0;
3134 	long len;
3135 
3136 	GET_SOFT_STATE(dev);
3137 
3138 	ST_FUNC(ST_DEVINFO, st_rw);
3139 
3140 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3141 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3142 	    (flag == B_READ ? rd_str: wr_str));
3143 
3144 	/* get local copy of transfer length */
3145 	len = uio->uio_iov->iov_len;
3146 
3147 	mutex_enter(ST_MUTEX);
3148 
3149 	/*
3150 	 * Clear error entry stack
3151 	 */
3152 	st_empty_error_stack(un);
3153 
3154 	/*
3155 	 * If in fixed block size mode and requested read or write
3156 	 * is not an even multiple of that block size.
3157 	 */
3158 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3159 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3160 		    "%s: not modulo %d block size\n",
3161 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3162 		rval = EINVAL;
3163 	}
3164 
3165 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3166 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3167 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3168 		    "%s: not modulo %d device granularity\n",
3169 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3170 		rval = EINVAL;
3171 	}
3172 
3173 	if (rval != 0) {
3174 		un->un_errno = rval;
3175 		mutex_exit(ST_MUTEX);
3176 		return (rval);
3177 	}
3178 
3179 	/*
3180 	 * Reset this so it can be set if Berkeley and read over a filemark.
3181 	 */
3182 	un->un_silent_skip = 0;
3183 	mutex_exit(ST_MUTEX);
3184 
3185 	len = uio->uio_resid;
3186 
3187 	rval = physio(st_strategy, (struct buf *)NULL,
3188 	    dev, flag, st_minphys, uio);
3189 	/*
3190 	 * if we have hit logical EOT during this xfer and there is not a
3191 	 * full residue, then set eof back  to ST_EOM to make sure that
3192 	 * the user will see at least one zero write
3193 	 * after this short write
3194 	 */
3195 	mutex_enter(ST_MUTEX);
3196 	if (un->un_pos.eof > ST_NO_EOF) {
3197 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3198 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3199 	}
3200 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3201 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3202 			un->un_pos.eof = ST_EOM;
3203 		} else if (uio->uio_resid == len) {
3204 			un->un_pos.eof = ST_NO_EOF;
3205 		}
3206 	}
3207 
3208 	if (un->un_silent_skip && uio->uio_resid != len) {
3209 		un->un_pos.eof = ST_EOF;
3210 		un->un_pos.blkno = un->un_save_blkno;
3211 		un->un_pos.fileno--;
3212 	}
3213 
3214 	un->un_errno = rval;
3215 
3216 	mutex_exit(ST_MUTEX);
3217 
3218 	return (rval);
3219 }
3220 
3221 static int
3222 st_arw(dev_t dev, struct aio_req *aio, int flag)
3223 {
3224 	struct uio *uio = aio->aio_uio;
3225 	int rval = 0;
3226 	long len;
3227 
3228 	GET_SOFT_STATE(dev);
3229 
3230 	ST_FUNC(ST_DEVINFO, st_arw);
3231 
3232 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3233 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3234 	    (flag == B_READ ? rd_str: wr_str));
3235 
3236 	/* get local copy of transfer length */
3237 	len = uio->uio_iov->iov_len;
3238 
3239 	mutex_enter(ST_MUTEX);
3240 
3241 	/*
3242 	 * If in fixed block size mode and requested read or write
3243 	 * is not an even multiple of that block size.
3244 	 */
3245 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3246 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3247 		    "%s: not modulo %d block size\n",
3248 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3249 		rval = EINVAL;
3250 	}
3251 
3252 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3253 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3254 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3255 		    "%s: not modulo %d device granularity\n",
3256 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3257 		rval = EINVAL;
3258 	}
3259 
3260 	if (rval != 0) {
3261 		un->un_errno = rval;
3262 		mutex_exit(ST_MUTEX);
3263 		return (rval);
3264 	}
3265 
3266 	mutex_exit(ST_MUTEX);
3267 
3268 	len = uio->uio_resid;
3269 
3270 	rval = aphysio(st_strategy, anocancel, dev, flag, st_minphys, aio);
3271 
3272 	/*
3273 	 * if we have hit logical EOT during this xfer and there is not a
3274 	 * full residue, then set eof back  to ST_EOM to make sure that
3275 	 * the user will see at least one zero write
3276 	 * after this short write
3277 	 *
3278 	 * we keep this here just in case the application is not using
3279 	 * persistent errors
3280 	 */
3281 	mutex_enter(ST_MUTEX);
3282 	if (un->un_pos.eof > ST_NO_EOF) {
3283 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3284 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3285 	}
3286 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3287 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3288 			un->un_pos.eof = ST_EOM;
3289 		} else if (uio->uio_resid == len && !IS_PE_FLAG_SET(un)) {
3290 			un->un_pos.eof = ST_NO_EOF;
3291 		}
3292 	}
3293 	un->un_errno = rval;
3294 	mutex_exit(ST_MUTEX);
3295 
3296 	return (rval);
3297 }
3298 
3299 
3300 
3301 static int
3302 st_strategy(struct buf *bp)
3303 {
3304 	struct scsi_tape *un;
3305 	dev_t dev = bp->b_edev;
3306 
3307 	/*
3308 	 * validate arguments
3309 	 */
3310 	if ((un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev))) == NULL) {
3311 		bp->b_resid = bp->b_bcount;
3312 		mutex_enter(ST_MUTEX);
3313 		st_bioerror(bp, ENXIO);
3314 		mutex_exit(ST_MUTEX);
3315 		goto error;
3316 	}
3317 
3318 	ST_ENTR(ST_DEVINFO, st_strategy);
3319 
3320 	mutex_enter(ST_MUTEX);
3321 
3322 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
3323 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
3324 	}
3325 
3326 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3327 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
3328 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3329 
3330 	/*
3331 	 * If persistent errors have been flagged, just nix this one. We wait
3332 	 * for any outstanding I/O's below, so we will be in order.
3333 	 */
3334 	if (IS_PE_FLAG_SET(un)) {
3335 		goto exit;
3336 	}
3337 
3338 	if (bp != un->un_sbufp) {
3339 		char reading = bp->b_flags & B_READ;
3340 		int wasopening = 0;
3341 
3342 		/*
3343 		 * If we haven't done/checked reservation on the tape unit
3344 		 * do it now.
3345 		 */
3346 		if ((un->un_rsvd_status &
3347 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
3348 			if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
3349 				if (st_reserve_release(un, ST_RESERVE)) {
3350 					st_bioerror(bp, un->un_errno);
3351 					goto exit;
3352 				}
3353 			} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3354 				/*
3355 				 * Enter here to restore position for possible
3356 				 * resets when the device was closed and opened
3357 				 * in O_NDELAY mode subsequently
3358 				 */
3359 				un->un_state = ST_STATE_INITIALIZING;
3360 				(void) st_cmd(dev, SCMD_TEST_UNIT_READY,
3361 				    0, SYNC_CMD);
3362 				un->un_state = ST_STATE_OPEN_PENDING_IO;
3363 			}
3364 			un->un_rsvd_status |= ST_INIT_RESERVE;
3365 		}
3366 
3367 		/*
3368 		 * If we are offline, we have to initialize everything first.
3369 		 * This is to handle either when opened with O_NDELAY, or
3370 		 * we just got a new tape in the drive, after an offline.
3371 		 * We don't observe O_NDELAY past the open,
3372 		 * as it will not make sense for tapes.
3373 		 */
3374 		if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
3375 			/* reset state to avoid recursion */
3376 			un->un_state = ST_STATE_INITIALIZING;
3377 			if (st_tape_init(dev)) {
3378 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3379 				    "stioctl : OFFLINE init failure ");
3380 				un->un_state = ST_STATE_OFFLINE;
3381 				un->un_pos.pmode = invalid;
3382 				goto b_done_err;
3383 			}
3384 			un->un_state = ST_STATE_OPEN_PENDING_IO;
3385 		}
3386 		/*
3387 		 * Check for legal operations
3388 		 */
3389 		if (un->un_pos.pmode == invalid) {
3390 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3391 			    "strategy with un->un_pos.pmode invalid\n");
3392 			goto b_done_err;
3393 		}
3394 
3395 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3396 		    "st_strategy(): regular io\n");
3397 
3398 		/*
3399 		 * Process this first. If we were reading, and we're pending
3400 		 * logical eot, that means we've bumped one file mark too far.
3401 		 */
3402 
3403 		/*
3404 		 * Recursion warning: st_cmd will route back through here.
3405 		 */
3406 		if (un->un_pos.eof == ST_EOT_PENDING) {
3407 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
3408 				un->un_pos.pmode = invalid;
3409 				un->un_density_known = 0;
3410 				goto b_done_err;
3411 			}
3412 			un->un_pos.blkno = 0; /* fix up block number.. */
3413 			un->un_pos.eof = ST_EOT;
3414 		}
3415 
3416 		/*
3417 		 * If we are in the process of opening, we may have to
3418 		 * determine/set the correct density. We also may have
3419 		 * to do a test_append (if QIC) to see whether we are
3420 		 * in a position to append to the end of the tape.
3421 		 *
3422 		 * If we're already at logical eot, we transition
3423 		 * to ST_NO_EOF. If we're at physical eot, we punt
3424 		 * to the switch statement below to handle.
3425 		 */
3426 		if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
3427 		    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
3428 
3429 			if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3430 				if (st_determine_density(dev, (int)reading)) {
3431 					goto b_done_err;
3432 				}
3433 			}
3434 
3435 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3436 			    "pending_io@fileno %d rw %d qic %d eof %d\n",
3437 			    un->un_pos.fileno, (int)reading,
3438 			    (un->un_dp->options & ST_QIC) ? 1 : 0,
3439 			    un->un_pos.eof);
3440 
3441 			if (!reading && un->un_pos.eof != ST_EOM) {
3442 				if (un->un_pos.eof == ST_EOT) {
3443 					un->un_pos.eof = ST_NO_EOF;
3444 				} else if (un->un_pos.pmode != invalid &&
3445 				    (un->un_dp->options & ST_QIC)) {
3446 					/*
3447 					 * st_test_append() will do it all
3448 					 */
3449 					st_test_append(bp);
3450 					goto done;
3451 				}
3452 			}
3453 			if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3454 				wasopening = 1;
3455 			}
3456 			un->un_laststate = un->un_state;
3457 			un->un_state = ST_STATE_OPEN;
3458 		}
3459 
3460 
3461 		/*
3462 		 * Process rest of END OF FILE and END OF TAPE conditions
3463 		 */
3464 
3465 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3466 		    "eof=%x, wasopening=%x\n",
3467 		    un->un_pos.eof, wasopening);
3468 
3469 		switch (un->un_pos.eof) {
3470 		case ST_EOM:
3471 			/*
3472 			 * This allows writes to proceed past physical
3473 			 * eot. We'll *really* be in trouble if the
3474 			 * user continues blindly writing data too
3475 			 * much past this point (unwind the tape).
3476 			 * Physical eot really means 'early warning
3477 			 * eot' in this context.
3478 			 *
3479 			 * Every other write from now on will succeed
3480 			 * (if sufficient  tape left).
3481 			 * This write will return with resid == count
3482 			 * but the next one should be successful
3483 			 *
3484 			 * Note that we only transition to logical EOT
3485 			 * if the last state wasn't the OPENING state.
3486 			 * We explicitly prohibit running up to physical
3487 			 * eot, closing the device, and then re-opening
3488 			 * to proceed. Trailer records may only be gotten
3489 			 * at by keeping the tape open after hitting eot.
3490 			 *
3491 			 * Also note that ST_EOM cannot be set by reading-
3492 			 * this can only be set during writing. Reading
3493 			 * up to the end of the tape gets a blank check
3494 			 * or a double-filemark indication (ST_EOT_PENDING),
3495 			 * and we prohibit reading after that point.
3496 			 *
3497 			 */
3498 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
3499 			if (wasopening == 0) {
3500 				/*
3501 				 * this allows st_rw() to reset it back to
3502 				 * ST_EOM to make sure that the application
3503 				 * will see a zero write
3504 				 */
3505 				un->un_pos.eof = ST_WRITE_AFTER_EOM;
3506 			}
3507 			un->un_status = SUN_KEY_EOT;
3508 			goto b_done;
3509 
3510 		case ST_WRITE_AFTER_EOM:
3511 		case ST_EOT:
3512 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
3513 			un->un_status = SUN_KEY_EOT;
3514 			if (SVR4_BEHAVIOR && reading) {
3515 				goto b_done_err;
3516 			}
3517 
3518 			if (reading) {
3519 				goto b_done;
3520 			}
3521 			un->un_pos.eof = ST_NO_EOF;
3522 			break;
3523 
3524 		case ST_EOF_PENDING:
3525 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3526 			    "EOF PENDING\n");
3527 			un->un_status = SUN_KEY_EOF;
3528 			if (SVR4_BEHAVIOR) {
3529 				un->un_pos.eof = ST_EOF;
3530 				goto b_done;
3531 			}
3532 			/* FALLTHROUGH */
3533 		case ST_EOF:
3534 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
3535 			un->un_status = SUN_KEY_EOF;
3536 			if (SVR4_BEHAVIOR) {
3537 				goto b_done_err;
3538 			}
3539 
3540 			if (BSD_BEHAVIOR) {
3541 				un->un_pos.eof = ST_NO_EOF;
3542 				un->un_pos.fileno += 1;
3543 				un->un_pos.blkno   = 0;
3544 			}
3545 
3546 			if (reading) {
3547 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3548 				    "now file %d (read)\n",
3549 				    un->un_pos.fileno);
3550 				goto b_done;
3551 			}
3552 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3553 			    "now file %d (write)\n", un->un_pos.fileno);
3554 			break;
3555 		default:
3556 			un->un_status = 0;
3557 			break;
3558 		}
3559 	}
3560 
3561 	bp->b_flags &= ~(B_DONE);
3562 	st_bioerror(bp, 0);
3563 	bp->av_forw = NULL;
3564 	bp->b_resid = 0;
3565 	SET_BP_PKT(bp, 0);
3566 
3567 
3568 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3569 	    "st_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
3570 	    " pkt=0x%p\n",
3571 	    (void *)bp->b_forw, bp->b_bcount,
3572 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
3573 
3574 #ifdef	__x86
3575 	/*
3576 	 * We will replace bp with a new bp that can do big blk xfer
3577 	 * if the requested xfer size is bigger than un->un_maxdma_arch
3578 	 *
3579 	 * Also, we need to make sure that we're handling real I/O
3580 	 * by checking group 0/1 SCSI I/O commands, if needed
3581 	 */
3582 	if (bp->b_bcount > un->un_maxdma_arch &&
3583 	    (bp != un->un_sbufp					||
3584 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ		||
3585 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G1	||
3586 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE	||
3587 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G1)) {
3588 		mutex_exit(ST_MUTEX);
3589 		bp = st_get_bigblk_bp(bp);
3590 		mutex_enter(ST_MUTEX);
3591 	}
3592 #endif
3593 
3594 	/* put on wait queue */
3595 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3596 	    "st_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
3597 	    (void *)un->un_quef, (void *)bp);
3598 
3599 	if (un->un_quef) {
3600 		un->un_quel->b_actf = bp;
3601 	} else {
3602 		un->un_quef = bp;
3603 	}
3604 	un->un_quel = bp;
3605 
3606 	ST_DO_KSTATS(bp, kstat_waitq_enter);
3607 
3608 	st_start(un);
3609 
3610 done:
3611 	mutex_exit(ST_MUTEX);
3612 	return (0);
3613 
3614 
3615 error:
3616 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3617 	    "st_strategy: error exit\n");
3618 
3619 	biodone(bp);
3620 	return (0);
3621 
3622 b_done_err:
3623 	st_bioerror(bp, EIO);
3624 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3625 	    "st_strategy : EIO b_done_err\n");
3626 
3627 b_done:
3628 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3629 	    "st_strategy: b_done\n");
3630 
3631 exit:
3632 	/*
3633 	 * make sure no commands are outstanding or waiting before closing,
3634 	 * so we can guarantee order
3635 	 */
3636 	st_wait_for_io(un);
3637 	un->un_err_resid = bp->b_resid = bp->b_bcount;
3638 
3639 	/* override errno here, if persistent errors were flagged */
3640 	if (IS_PE_FLAG_SET(un))
3641 		bioerror(bp, un->un_errno);
3642 
3643 	mutex_exit(ST_MUTEX);
3644 
3645 	biodone(bp);
3646 	ASSERT(mutex_owned(ST_MUTEX) == 0);
3647 	return (0);
3648 }
3649 
3650 
3651 
3652 /*
3653  * this routine spaces forward over filemarks
3654  */
3655 static int
3656 st_space_fmks(dev_t dev, int count)
3657 {
3658 	int rval = 0;
3659 
3660 	GET_SOFT_STATE(dev);
3661 
3662 	ST_FUNC(ST_DEVINFO, st_space_fmks);
3663 
3664 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3665 	    "st_space_fmks(dev = 0x%lx, count = %d)\n", dev, count);
3666 
3667 	ASSERT(mutex_owned(ST_MUTEX));
3668 
3669 	/*
3670 	 * the risk with doing only one space operation is that we
3671 	 * may accidentily jump in old data
3672 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
3673 	 * because the 8200 does not append a marker; in order not to
3674 	 * sacrifice the fast file skip, we do a slow skip if the low
3675 	 * density device has been opened
3676 	 */
3677 
3678 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
3679 	    !((un->un_dp->type == ST_TYPE_EXB8500 && MT_DENSITY(dev) == 0))) {
3680 		if (st_cmd(dev, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
3681 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3682 			    "space_fmks : EIO can't do space cmd #1\n");
3683 			rval = EIO;
3684 		}
3685 	} else {
3686 		while (count > 0) {
3687 			if (st_cmd(dev, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3688 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3689 				    "space_fmks : EIO can't do space cmd #2\n");
3690 				rval = EIO;
3691 				break;
3692 			}
3693 			count -= 1;
3694 			/*
3695 			 * read a block to see if we have reached
3696 			 * end of medium (double filemark for reel or
3697 			 * medium error for others)
3698 			 */
3699 			if (count > 0) {
3700 				if (st_cmd(dev, SCMD_SPACE, Blk(1),
3701 				    SYNC_CMD)) {
3702 					ST_DEBUG2(ST_DEVINFO, st_label,
3703 					    SCSI_DEBUG,
3704 					    "space_fmks : EIO can't do "
3705 					    "space cmd #3\n");
3706 					rval = EIO;
3707 					break;
3708 				}
3709 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
3710 				    (un->un_dp->options & ST_REEL)) {
3711 					un->un_status = SUN_KEY_EOT;
3712 					ST_DEBUG2(ST_DEVINFO, st_label,
3713 					    SCSI_DEBUG,
3714 					    "space_fmks : EIO ST_REEL\n");
3715 					rval = EIO;
3716 					break;
3717 				} else if (IN_EOF(un->un_pos)) {
3718 					un->un_pos.eof = ST_NO_EOF;
3719 					un->un_pos.fileno++;
3720 					un->un_pos.blkno = 0;
3721 					count--;
3722 				} else if (un->un_pos.eof > ST_EOF) {
3723 					ST_DEBUG2(ST_DEVINFO, st_label,
3724 					    SCSI_DEBUG,
3725 					    "space_fmks, EIO > ST_EOF\n");
3726 					rval = EIO;
3727 					break;
3728 				}
3729 
3730 			}
3731 		}
3732 		un->un_err_resid = count;
3733 		COPY_POS(&un->un_pos, &un->un_err_pos);
3734 	}
3735 	ASSERT(mutex_owned(ST_MUTEX));
3736 	return (rval);
3737 }
3738 
3739 /*
3740  * this routine spaces to EOD
3741  *
3742  * it keeps track of the current filenumber and returns the filenumber after
3743  * the last successful space operation, we keep the number high because as
3744  * tapes are getting larger, the possibility of more and more files exist,
3745  * 0x100000 (1 Meg of files) probably will never have to be changed any time
3746  * soon
3747  */
3748 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
3749 
3750 static int
3751 st_find_eod(dev_t dev)
3752 {
3753 	tapepos_t savepos;
3754 	int sp_type;
3755 	struct scsi_tape *un;
3756 	int instance;
3757 	int result;
3758 
3759 	instance = MTUNIT(dev);
3760 	un = ddi_get_soft_state(st_state, instance);
3761 	if (un == NULL) {
3762 		return (-1);
3763 	}
3764 
3765 	ST_FUNC(ST_DEVINFO, st_find_eod);
3766 
3767 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3768 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", dev, un->un_pos.fileno);
3769 
3770 	ASSERT(mutex_owned(ST_MUTEX));
3771 
3772 	COPY_POS(&savepos, &un->un_pos);
3773 
3774 	/*
3775 	 * see if the drive is smart enough to do the skips in
3776 	 * one operation; 1/2" use two filemarks
3777 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
3778 	 * because the 8200 does not append a marker; in order not to
3779 	 * sacrifice the fast file skip, we do a slow skip if the low
3780 	 * density device has been opened
3781 	 */
3782 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
3783 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
3784 		    (MT_DENSITY(dev) == 0)) {
3785 			sp_type = Fmk(1);
3786 		} else if (un->un_pos.pmode == logical) {
3787 			sp_type = SPACE(SP_EOD, 0);
3788 		} else {
3789 			sp_type = Fmk(MAX_SKIP);
3790 		}
3791 	} else {
3792 		sp_type = Fmk(1);
3793 	}
3794 
3795 	for (;;) {
3796 		result = st_cmd(dev, SCMD_SPACE, sp_type, SYNC_CMD);
3797 
3798 		if (result == 0) {
3799 			COPY_POS(&savepos, &un->un_pos);
3800 		}
3801 
3802 		if (sp_type == SPACE(SP_EOD, 0)) {
3803 			if (result != 0) {
3804 				sp_type = Fmk(MAX_SKIP);
3805 				continue;
3806 			}
3807 
3808 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3809 			    "st_find_eod: 0x%"PRIx64"\n",
3810 			    savepos.lgclblkno);
3811 			/*
3812 			 * What we return will become the current file position.
3813 			 * After completing the space command with the position
3814 			 * mode that is not invalid a read position command will
3815 			 * be automaticly issued. If the drive support the long
3816 			 * read position format a valid file position can be
3817 			 * returned.
3818 			 */
3819 			return (un->un_pos.fileno);
3820 		}
3821 
3822 		if (result != 0) {
3823 			break;
3824 		}
3825 
3826 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3827 		    "count=%x, eof=%x, status=%x\n",
3828 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
3829 
3830 		/*
3831 		 * If we're not EOM smart,  space a record
3832 		 * to see whether we're now in the slot between
3833 		 * the two sequential filemarks that logical
3834 		 * EOM consists of (REEL) or hit nowhere land
3835 		 * (8mm).
3836 		 */
3837 		if (sp_type == Fmk(1)) {
3838 			/*
3839 			 * no fast skipping, check a record
3840 			 */
3841 			if (st_cmd(dev, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
3842 				break;
3843 			}
3844 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
3845 			    (un->un_dp->options & ST_REEL)) {
3846 				un->un_status = KEY_BLANK_CHECK;
3847 				un->un_pos.fileno++;
3848 				un->un_pos.blkno = 0;
3849 				break;
3850 			}
3851 			if (IN_EOF(un->un_pos)) {
3852 				un->un_pos.eof = ST_NO_EOF;
3853 				un->un_pos.fileno++;
3854 				un->un_pos.blkno = 0;
3855 			}
3856 			if (un->un_pos.eof > ST_EOF) {
3857 				break;
3858 			}
3859 		} else {
3860 			if (un->un_pos.eof > ST_EOF) {
3861 				break;
3862 			}
3863 		}
3864 	}
3865 
3866 	if (un->un_dp->options & ST_KNOWS_EOD) {
3867 		COPY_POS(&savepos, &un->un_pos);
3868 	}
3869 
3870 	ASSERT(mutex_owned(ST_MUTEX));
3871 
3872 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3873 	    "st_find_eod: %x\n", savepos.fileno);
3874 	return (savepos.fileno);
3875 }
3876 
3877 
3878 /*
3879  * this routine is frequently used in ioctls below;
3880  * it determines whether we know the density and if not will
3881  * determine it
3882  * if we have written the tape before, one or more filemarks are written
3883  *
3884  * depending on the stepflag, the head is repositioned to where it was before
3885  * the filemarks were written in order not to confuse step counts
3886  */
3887 #define	STEPBACK    0
3888 #define	NO_STEPBACK 1
3889 
3890 static int
3891 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
3892 {
3893 
3894 	GET_SOFT_STATE(dev);
3895 
3896 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
3897 
3898 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3899 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
3900 	    "\n", dev, wfm, mode, stepflag);
3901 
3902 	ASSERT(mutex_owned(ST_MUTEX));
3903 
3904 	/*
3905 	 * If we don't yet know the density of the tape we have inserted,
3906 	 * we have to either unconditionally set it (if we're 'writing'),
3907 	 * or we have to determine it. As side effects, check for any
3908 	 * write-protect errors, and for the need to put out any file-marks
3909 	 * before positioning a tape.
3910 	 *
3911 	 * If we are going to be spacing forward, and we haven't determined
3912 	 * the tape density yet, we have to do so now...
3913 	 */
3914 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3915 		if (st_determine_density(dev, mode)) {
3916 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3917 			    "check_density_or_wfm : EIO can't determine "
3918 			    "density\n");
3919 			un->un_errno = EIO;
3920 			return (EIO);
3921 		}
3922 		/*
3923 		 * Presumably we are at BOT. If we attempt to write, it will
3924 		 * either work okay, or bomb. We don't do a st_test_append
3925 		 * unless we're past BOT.
3926 		 */
3927 		un->un_laststate = un->un_state;
3928 		un->un_state = ST_STATE_OPEN;
3929 
3930 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
3931 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
3932 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
3933 
3934 		tapepos_t spos;
3935 
3936 		COPY_POS(&spos, &un->un_pos);
3937 
3938 		/*
3939 		 * We need to write one or two filemarks.
3940 		 * In the case of the HP, we need to
3941 		 * position the head between the two
3942 		 * marks.
3943 		 */
3944 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
3945 			wfm = un->un_fmneeded;
3946 			un->un_fmneeded = 0;
3947 		}
3948 
3949 		if (st_write_fm(dev, wfm)) {
3950 			un->un_pos.pmode = invalid;
3951 			un->un_density_known = 0;
3952 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3953 			    "check_density_or_wfm : EIO can't write fm\n");
3954 			un->un_errno = EIO;
3955 			return (EIO);
3956 		}
3957 
3958 		if (stepflag == STEPBACK) {
3959 			if (st_cmd(dev, SCMD_SPACE, Fmk((-wfm)), SYNC_CMD)) {
3960 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3961 				    "check_density_or_wfm : EIO can't space "
3962 				    "(-wfm)\n");
3963 				un->un_errno = EIO;
3964 				return (EIO);
3965 			}
3966 			COPY_POS(&un->un_pos, &spos);
3967 		}
3968 	}
3969 
3970 	/*
3971 	 * Whatever we do at this point clears the state of the eof flag.
3972 	 */
3973 
3974 	un->un_pos.eof = ST_NO_EOF;
3975 
3976 	/*
3977 	 * If writing, let's check that we're positioned correctly
3978 	 * at the end of tape before issuing the next write.
3979 	 */
3980 	if (un->un_read_only == RDWR) {
3981 		un->un_test_append = 1;
3982 	}
3983 
3984 	ASSERT(mutex_owned(ST_MUTEX));
3985 	return (0);
3986 }
3987 
3988 
3989 /*
3990  * Wait for all outstaning I/O's to complete
3991  *
3992  * we wait on both ncmds and the wait queue for times when we are flushing
3993  * after persistent errors are flagged, which is when ncmds can be 0, and the
3994  * queue can still have I/O's.  This way we preserve order of biodone's.
3995  */
3996 static void
3997 st_wait_for_io(struct scsi_tape *un)
3998 {
3999 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4000 	ASSERT(mutex_owned(ST_MUTEX));
4001 	while (un->un_ncmds && un->un_quef) { /* XXX fix for async write@EOM */
4002 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4003 	}
4004 }
4005 
4006 /*
4007  * This routine implements the ioctl calls.  It is called
4008  * from the device switch at normal priority.
4009  */
4010 /*ARGSUSED*/
4011 static int
4012 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4013     int *rval_p)
4014 {
4015 	int tmp, rval = 0;
4016 
4017 	GET_SOFT_STATE(dev);
4018 
4019 	ST_ENTR(ST_DEVINFO, st_ioctl);
4020 
4021 	mutex_enter(ST_MUTEX);
4022 
4023 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4024 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4025 	    "pe_flag = %d\n",
4026 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4027 	    IS_PE_FLAG_SET(un));
4028 
4029 	/*
4030 	 * We don't want to block on these, so let them through
4031 	 * and we don't care about setting driver states here.
4032 	 */
4033 	if ((cmd == MTIOCGETDRIVETYPE) ||
4034 	    (cmd == MTIOCGUARANTEEDORDER) ||
4035 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4036 		goto check_commands;
4037 	}
4038 
4039 	/*
4040 	 * We clear error entry stack except command
4041 	 * MTIOCGETERROR and MTIOCGET
4042 	 */
4043 	if ((cmd != MTIOCGETERROR) &&
4044 	    (cmd != MTIOCGET)) {
4045 		st_empty_error_stack(un);
4046 	}
4047 
4048 	/*
4049 	 * wait for all outstanding commands to complete, or be dequeued.
4050 	 * And because ioctl's are synchronous commands, any return value
4051 	 * after this,  will be in order
4052 	 */
4053 	st_wait_for_io(un);
4054 
4055 	/*
4056 	 * allow only a through clear errors and persistent status, and
4057 	 * status
4058 	 */
4059 	if (IS_PE_FLAG_SET(un)) {
4060 		if ((cmd == MTIOCLRERR) ||
4061 		    (cmd == MTIOCPERSISTENT) ||
4062 		    (cmd == MTIOCGET)) {
4063 			goto check_commands;
4064 		} else {
4065 			rval = un->un_errno;
4066 			goto exit;
4067 		}
4068 	}
4069 
4070 	un->un_throttle = 1;	/* > 1 will never happen here */
4071 	un->un_errno = 0;	/* start clean from here */
4072 
4073 	/*
4074 	 * first and foremost, handle any ST_EOT_PENDING cases.
4075 	 * That is, if a logical eot is pending notice, notice it.
4076 	 */
4077 	if (un->un_pos.eof == ST_EOT_PENDING) {
4078 		int resid = un->un_err_resid;
4079 		uchar_t status = un->un_status;
4080 		uchar_t lastop = un->un_lastop;
4081 
4082 		if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
4083 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4084 			    "stioctl : EIO can't space fmk(-1)\n");
4085 			rval = EIO;
4086 			goto exit;
4087 		}
4088 		un->un_lastop = lastop; /* restore last operation */
4089 		if (status == SUN_KEY_EOF) {
4090 			un->un_status = SUN_KEY_EOT;
4091 		} else {
4092 			un->un_status = status;
4093 		}
4094 		un->un_err_resid  = resid;
4095 		/* fix up block number */
4096 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4097 		/* now we're at logical eot */
4098 		un->un_pos.eof = ST_EOT;
4099 	}
4100 
4101 	/*
4102 	 * now, handle the rest of the situations
4103 	 */
4104 check_commands:
4105 	switch (cmd) {
4106 	case MTIOCGET:
4107 	{
4108 #ifdef _MULTI_DATAMODEL
4109 		/*
4110 		 * For use when a 32 bit app makes a call into a
4111 		 * 64 bit ioctl
4112 		 */
4113 		struct mtget32		mtg_local32;
4114 		struct mtget32 		*mtget_32 = &mtg_local32;
4115 #endif /* _MULTI_DATAMODEL */
4116 
4117 			/* Get tape status */
4118 		struct mtget mtg_local;
4119 		struct mtget *mtget = &mtg_local;
4120 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4121 		    "st_ioctl: MTIOCGET\n");
4122 
4123 		bzero((caddr_t)mtget, sizeof (struct mtget));
4124 		mtget->mt_erreg = un->un_status;
4125 		mtget->mt_resid = un->un_err_resid;
4126 		mtget->mt_dsreg = un->un_retry_ct;
4127 		if (un->un_err_pos.pmode == legacy) {
4128 			mtget->mt_fileno = un->un_err_pos.fileno;
4129 		} else {
4130 			mtget->mt_fileno = -1;
4131 		}
4132 		mtget->mt_blkno = un->un_err_pos.blkno;
4133 		mtget->mt_type = un->un_dp->type;
4134 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
4135 		if (un->un_read_pos_type != NO_POS) {
4136 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
4137 		}
4138 		if (un->un_dp->options & ST_REEL) {
4139 			mtget->mt_flags |= MTF_REEL;
4140 			mtget->mt_bf = 20;
4141 		} else {		/* 1/4" cartridges */
4142 			switch (mtget->mt_type) {
4143 			/* Emulex cartridge tape */
4144 			case MT_ISMT02:
4145 				mtget->mt_bf = 40;
4146 				break;
4147 			default:
4148 				mtget->mt_bf = 126;
4149 				break;
4150 			}
4151 		}
4152 
4153 		/*
4154 		 * If large transfers are allowed and drive options
4155 		 * has no record size limit set. Calculate blocking
4156 		 * factor from the lesser of maxbsize and maxdma.
4157 		 */
4158 		if ((un->un_allow_large_xfer) &&
4159 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
4160 			mtget->mt_bf = min(un->un_maxbsize,
4161 			    un->un_maxdma) / SECSIZE;
4162 		}
4163 
4164 			if (un->un_read_only == WORM ||
4165 			    un->un_read_only == RDWORM) {
4166 				mtget->mt_flags |= MTF_WORM_MEDIA;
4167 			}
4168 
4169 			rval = st_check_clean_bit(dev);
4170 			if (rval == -1) {
4171 				rval = EIO;
4172 				goto exit;
4173 			} else {
4174 				mtget->mt_flags |= (ushort_t)rval;
4175 				rval = 0;
4176 			}
4177 
4178 		un->un_status = 0;		/* Reset status */
4179 		un->un_err_resid = 0;
4180 		tmp = sizeof (struct mtget);
4181 
4182 #ifdef _MULTI_DATAMODEL
4183 
4184 		switch (ddi_model_convert_from(flag & FMODELS)) {
4185 		case DDI_MODEL_ILP32:
4186 			/*
4187 			 * Convert 64 bit back to 32 bit before doing
4188 			 * copyout. This is what the ILP32 app expects.
4189 			 */
4190 			mtget_32->mt_erreg = 	mtget->mt_erreg;
4191 			mtget_32->mt_resid = 	mtget->mt_resid;
4192 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
4193 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
4194 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
4195 			mtget_32->mt_type =  	mtget->mt_type;
4196 			mtget_32->mt_flags = 	mtget->mt_flags;
4197 			mtget_32->mt_bf = 	mtget->mt_bf;
4198 
4199 			if (ddi_copyout(mtget_32, (void *)arg,
4200 			    sizeof (struct mtget32), flag)) {
4201 				rval = EFAULT;
4202 			}
4203 			break;
4204 
4205 		case DDI_MODEL_NONE:
4206 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4207 				rval = EFAULT;
4208 			}
4209 			break;
4210 		}
4211 #else /* ! _MULTI_DATAMODE */
4212 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
4213 			rval = EFAULT;
4214 		}
4215 #endif /* _MULTI_DATAMODE */
4216 
4217 		break;
4218 	}
4219 	case MTIOCGETERROR:
4220 			/*
4221 			 * get error entry from error stack
4222 			 */
4223 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4224 			    "st_ioctl: MTIOCGETERROR\n");
4225 
4226 			rval = st_get_error_entry(un, arg, flag);
4227 
4228 			break;
4229 
4230 	case MTIOCSTATE:
4231 		{
4232 			/*
4233 			 * return when media presence matches state
4234 			 */
4235 			enum mtio_state state;
4236 
4237 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4238 			    "st_ioctl: MTIOCSTATE\n");
4239 
4240 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
4241 				rval = EFAULT;
4242 
4243 			mutex_exit(ST_MUTEX);
4244 
4245 			rval = st_check_media(dev, state);
4246 
4247 			mutex_enter(ST_MUTEX);
4248 
4249 			if (rval != 0) {
4250 				break;
4251 			}
4252 
4253 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
4254 			    sizeof (int), flag))
4255 				rval = EFAULT;
4256 			break;
4257 
4258 		}
4259 
4260 	case MTIOCGETDRIVETYPE:
4261 		{
4262 #ifdef _MULTI_DATAMODEL
4263 		/*
4264 		 * For use when a 32 bit app makes a call into a
4265 		 * 64 bit ioctl
4266 		 */
4267 		struct mtdrivetype_request32	mtdtrq32;
4268 #endif /* _MULTI_DATAMODEL */
4269 
4270 			/*
4271 			 * return mtdrivetype
4272 			 */
4273 			struct mtdrivetype_request mtdtrq;
4274 			struct mtdrivetype mtdrtyp;
4275 			struct mtdrivetype *mtdt = &mtdrtyp;
4276 			struct st_drivetype *stdt = un->un_dp;
4277 
4278 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4279 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
4280 
4281 #ifdef _MULTI_DATAMODEL
4282 		switch (ddi_model_convert_from(flag & FMODELS)) {
4283 		case DDI_MODEL_ILP32:
4284 		{
4285 			if (ddi_copyin((void *)arg, &mtdtrq32,
4286 			    sizeof (struct mtdrivetype_request32), flag)) {
4287 				rval = EFAULT;
4288 				break;
4289 			}
4290 			mtdtrq.size = mtdtrq32.size;
4291 			mtdtrq.mtdtp =
4292 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
4293 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4294 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
4295 			break;
4296 		}
4297 		case DDI_MODEL_NONE:
4298 			if (ddi_copyin((void *)arg, &mtdtrq,
4299 			    sizeof (struct mtdrivetype_request), flag)) {
4300 				rval = EFAULT;
4301 				break;
4302 			}
4303 			break;
4304 		}
4305 
4306 #else /* ! _MULTI_DATAMODEL */
4307 		if (ddi_copyin((void *)arg, &mtdtrq,
4308 		    sizeof (struct mtdrivetype_request), flag)) {
4309 			rval = EFAULT;
4310 			break;
4311 		}
4312 #endif /* _MULTI_DATAMODEL */
4313 
4314 			/*
4315 			 * if requested size is < 0 then return
4316 			 * error.
4317 			 */
4318 			if (mtdtrq.size < 0) {
4319 				rval = EINVAL;
4320 				break;
4321 			}
4322 			bzero(mtdt, sizeof (struct mtdrivetype));
4323 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
4324 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
4325 			mtdt->type = stdt->type;
4326 			mtdt->bsize = stdt->bsize;
4327 			mtdt->options = stdt->options;
4328 			mtdt->max_rretries = stdt->max_rretries;
4329 			mtdt->max_wretries = stdt->max_wretries;
4330 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
4331 				mtdt->densities[tmp] = stdt->densities[tmp];
4332 			}
4333 			mtdt->default_density = stdt->default_density;
4334 			/*
4335 			 * Speed hasn't been used since the hayday of reel tape.
4336 			 * For all drives not setting the option ST_KNOWS_MEDIA
4337 			 * the speed member renamed to mediatype are zeros.
4338 			 * Those drives that have ST_KNOWS_MEDIA set use the
4339 			 * new mediatype member which is used to figure the
4340 			 * type of media loaded.
4341 			 *
4342 			 * So as to not break applications speed in the
4343 			 * mtdrivetype structure is not renamed.
4344 			 */
4345 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
4346 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
4347 			}
4348 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
4349 			mtdt->io_timeout = stdt->io_timeout;
4350 			mtdt->rewind_timeout = stdt->rewind_timeout;
4351 			mtdt->space_timeout = stdt->space_timeout;
4352 			mtdt->load_timeout = stdt->load_timeout;
4353 			mtdt->unload_timeout = stdt->unload_timeout;
4354 			mtdt->erase_timeout = stdt->erase_timeout;
4355 
4356 			/*
4357 			 * Limit the maximum length of the result to
4358 			 * sizeof (struct mtdrivetype).
4359 			 */
4360 			tmp = sizeof (struct mtdrivetype);
4361 			if (mtdtrq.size < tmp)
4362 				tmp = mtdtrq.size;
4363 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
4364 				rval = EFAULT;
4365 			}
4366 			break;
4367 		}
4368 	case MTIOCPERSISTENT:
4369 		{
4370 			int persistence = 0;
4371 
4372 			if (ddi_copyin((void *)arg, &persistence,
4373 			    sizeof (int), flag)) {
4374 				rval = EFAULT;
4375 				break;
4376 			}
4377 
4378 			/* non zero sets it, only 0 turns it off */
4379 			un->un_persistence = (uchar_t)persistence ? 1 : 0;
4380 
4381 			if (un->un_persistence) {
4382 				TURN_PE_ON(un);
4383 			} else {
4384 				TURN_PE_OFF(un);
4385 			}
4386 
4387 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4388 			    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
4389 			    un->un_persistence);
4390 
4391 			break;
4392 		}
4393 	case MTIOCPERSISTENTSTATUS:
4394 		{
4395 			int persistence = (int)un->un_persistence;
4396 
4397 			if (ddi_copyout(&persistence, (void *)arg,
4398 			    sizeof (int), flag)) {
4399 				rval = EFAULT;
4400 			}
4401 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4402 			    "st_ioctl: MTIOCPERSISTENTSTATUS:persistece = %d\n",
4403 			    un->un_persistence);
4404 
4405 			break;
4406 		}
4407 
4408 
4409 	case MTIOCLRERR:
4410 		{
4411 			/* clear persistent errors */
4412 
4413 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4414 			    "st_ioctl: MTIOCLRERR\n");
4415 
4416 			CLEAR_PE(un);
4417 
4418 			break;
4419 		}
4420 
4421 	case MTIOCGUARANTEEDORDER:
4422 		{
4423 			/*
4424 			 * this is just a holder to make a valid ioctl and
4425 			 * it won't be in any earlier release
4426 			 */
4427 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4428 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
4429 
4430 			break;
4431 		}
4432 
4433 	case MTIOCRESERVE:
4434 		{
4435 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4436 			    "st_ioctl: MTIOCRESERVE\n");
4437 
4438 			/*
4439 			 * Check if Reserve/Release is supported.
4440 			 */
4441 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
4442 				rval = ENOTTY;
4443 				break;
4444 			}
4445 
4446 			rval = st_reserve_release(un, ST_RESERVE);
4447 
4448 			if (rval == 0) {
4449 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
4450 			}
4451 			break;
4452 		}
4453 
4454 	case MTIOCRELEASE:
4455 		{
4456 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4457 			    "st_ioctl: MTIOCRELEASE\n");
4458 
4459 			/*
4460 			 * Check if Reserve/Release is supported.
4461 			 */
4462 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
4463 				rval = ENOTTY;
4464 				break;
4465 			}
4466 
4467 			/*
4468 			 * Used to just clear ST_PRESERVE_RESERVE which
4469 			 * made the reservation release at next close.
4470 			 * As the user may have opened and then done a
4471 			 * persistant reservation we now need to drop
4472 			 * the reservation without closing if the user
4473 			 * attempts to do this.
4474 			 */
4475 			rval = st_reserve_release(un, ST_RELEASE);
4476 
4477 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
4478 
4479 			break;
4480 		}
4481 
4482 	case MTIOCFORCERESERVE:
4483 		{
4484 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4485 			    "st_ioctl: MTIOCFORCERESERVE\n");
4486 
4487 			/*
4488 			 * Check if Reserve/Release is supported.
4489 			 */
4490 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
4491 				rval = ENOTTY;
4492 				break;
4493 			}
4494 			/*
4495 			 * allow only super user to run this.
4496 			 */
4497 			if (drv_priv(cred_p) != 0) {
4498 				rval = EPERM;
4499 				break;
4500 			}
4501 			/*
4502 			 * Throw away reserve,
4503 			 * not using test-unit-ready
4504 			 * since reserve can succeed without tape being
4505 			 * present in the drive.
4506 			 */
4507 			(void) st_reserve_release(un, ST_RESERVE);
4508 
4509 			rval = st_take_ownership(dev);
4510 
4511 			break;
4512 		}
4513 
4514 	case USCSICMD:
4515 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4516 		    "st_ioctl: USCSICMD\n");
4517 	{
4518 		cred_t	*cr;
4519 		cr = ddi_get_cred();
4520 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
4521 			rval = EPERM;
4522 		} else {
4523 			rval = st_ioctl_cmd(dev, (struct uscsi_cmd *)arg,
4524 			    flag);
4525 		}
4526 	}
4527 		break;
4528 
4529 	case MTIOCTOP:
4530 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4531 		    "st_ioctl: MTIOCTOP\n");
4532 		rval = st_mtioctop(un, arg, flag);
4533 		break;
4534 
4535 	case MTIOCLTOP:
4536 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4537 		    "st_ioctl: MTIOLCTOP\n");
4538 		rval = st_mtiocltop(un, arg, flag);
4539 		break;
4540 
4541 	case MTIOCREADIGNOREILI:
4542 		{
4543 			int set_ili;
4544 
4545 			if (ddi_copyin((void *)arg, &set_ili,
4546 			    sizeof (set_ili), flag)) {
4547 				rval = EFAULT;
4548 				break;
4549 			}
4550 
4551 			if (un->un_bsize) {
4552 				rval = ENOTTY;
4553 				break;
4554 			}
4555 
4556 			switch (set_ili) {
4557 			case 0:
4558 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
4559 				break;
4560 
4561 			case 1:
4562 				un->un_dp->options |= ST_READ_IGNORE_ILI;
4563 				break;
4564 
4565 			default:
4566 				rval = EINVAL;
4567 				break;
4568 			}
4569 			break;
4570 		}
4571 
4572 	case MTIOCREADIGNOREEOFS:
4573 		{
4574 			int ignore_eof;
4575 
4576 			if (ddi_copyin((void *)arg, &ignore_eof,
4577 			    sizeof (ignore_eof), flag)) {
4578 				rval = EFAULT;
4579 				break;
4580 			}
4581 
4582 			if (!(un->un_dp->options & ST_REEL)) {
4583 				rval = ENOTTY;
4584 				break;
4585 			}
4586 
4587 			switch (ignore_eof) {
4588 			case 0:
4589 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
4590 				break;
4591 
4592 			case 1:
4593 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
4594 				break;
4595 
4596 			default:
4597 				rval = EINVAL;
4598 				break;
4599 			}
4600 			break;
4601 		}
4602 
4603 	case MTIOCSHORTFMK:
4604 	{
4605 		int short_fmk;
4606 
4607 		if (ddi_copyin((void *)arg, &short_fmk,
4608 		    sizeof (short_fmk), flag)) {
4609 			rval = EFAULT;
4610 			break;
4611 		}
4612 
4613 		switch (un->un_dp->type) {
4614 		case ST_TYPE_EXB8500:
4615 		case ST_TYPE_EXABYTE:
4616 			if (!short_fmk) {
4617 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
4618 			} else if (short_fmk == 1) {
4619 				un->un_dp->options |= ST_SHORT_FILEMARKS;
4620 			} else {
4621 				rval = EINVAL;
4622 			}
4623 			break;
4624 
4625 		default:
4626 			rval = ENOTTY;
4627 			break;
4628 		}
4629 		break;
4630 	}
4631 
4632 	case MTIOCGETPOS:
4633 		rval = st_update_block_pos(un);
4634 		if (rval == 0) {
4635 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
4636 			    sizeof (tapepos_t), flag)) {
4637 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
4638 				    "MTIOCGETPOS copy out failed\n");
4639 				rval = EFAULT;
4640 			}
4641 		}
4642 		break;
4643 
4644 	case MTIOCRESTPOS:
4645 	{
4646 		tapepos_t dest;
4647 
4648 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
4649 		    flag) != 0) {
4650 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
4651 			    "MTIOCRESTPOS copy in failed\n");
4652 			rval = EFAULT;
4653 			break;
4654 		}
4655 		rval = st_validate_tapemarks(un, &dest);
4656 		if (rval != 0) {
4657 			rval = EIO;
4658 		}
4659 		break;
4660 	}
4661 	default:
4662 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4663 		    "st_ioctl: unknown ioctl\n");
4664 		rval = ENOTTY;
4665 	}
4666 
4667 exit:
4668 	if (!IS_PE_FLAG_SET(un)) {
4669 		un->un_errno = rval;
4670 	}
4671 
4672 	mutex_exit(ST_MUTEX);
4673 
4674 	return (rval);
4675 }
4676 
4677 
4678 /*
4679  * do some MTIOCTOP tape operations
4680  */
4681 static int
4682 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
4683 {
4684 #ifdef _MULTI_DATAMODEL
4685 	/*
4686 	 * For use when a 32 bit app makes a call into a
4687 	 * 64 bit ioctl
4688 	 */
4689 	struct mtop32	mtop_32_for_64;
4690 #endif /* _MULTI_DATAMODEL */
4691 	struct mtop passed;
4692 	struct mtlop local;
4693 	int rval = 0;
4694 
4695 	ST_FUNC(ST_DEVINFO, st_mtioctop);
4696 
4697 	ASSERT(mutex_owned(ST_MUTEX));
4698 
4699 #ifdef _MULTI_DATAMODEL
4700 	switch (ddi_model_convert_from(flag & FMODELS)) {
4701 	case DDI_MODEL_ILP32:
4702 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
4703 		    sizeof (struct mtop32), flag)) {
4704 			return (EFAULT);
4705 		}
4706 		local.mt_op = mtop_32_for_64.mt_op;
4707 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
4708 		break;
4709 
4710 	case DDI_MODEL_NONE:
4711 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
4712 			return (EFAULT);
4713 		}
4714 		local.mt_op = passed.mt_op;
4715 		/* prevent sign extention */
4716 		local.mt_count = (UINT32_MAX & passed.mt_count);
4717 		break;
4718 	}
4719 
4720 #else /* ! _MULTI_DATAMODEL */
4721 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
4722 		return (EFAULT);
4723 	}
4724 	local.mt_op = passed.mt_op;
4725 	/* prevent sign extention */
4726 	local.mt_count = (UINT32_MAX & passed.mt_count);
4727 #endif /* _MULTI_DATAMODEL */
4728 
4729 	rval = st_do_mtioctop(un, &local);
4730 
4731 #ifdef _MULTI_DATAMODEL
4732 	switch (ddi_model_convert_from(flag & FMODELS)) {
4733 	case DDI_MODEL_ILP32:
4734 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
4735 			rval = ERANGE;
4736 			break;
4737 		}
4738 		/*
4739 		 * Convert 64 bit back to 32 bit before doing
4740 		 * copyout. This is what the ILP32 app expects.
4741 		 */
4742 		mtop_32_for_64.mt_op = local.mt_op;
4743 		mtop_32_for_64.mt_count = local.mt_count;
4744 
4745 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
4746 		    sizeof (struct mtop32), flag)) {
4747 			rval = EFAULT;
4748 		}
4749 		break;
4750 
4751 	case DDI_MODEL_NONE:
4752 		passed.mt_count = local.mt_count;
4753 		passed.mt_op = local.mt_op;
4754 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
4755 			rval = EFAULT;
4756 		}
4757 		break;
4758 	}
4759 #else /* ! _MULTI_DATAMODE */
4760 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
4761 		rval = ERANGE;
4762 	} else {
4763 		passed.mt_op = local.mt_op;
4764 		passed.mt_count = local.mt_count;
4765 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
4766 			rval = EFAULT;
4767 		}
4768 	}
4769 #endif /* _MULTI_DATAMODE */
4770 
4771 
4772 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4773 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
4774 	    un->un_pos.blkno, un->un_pos.eof);
4775 
4776 	if (un->un_pos.pmode == invalid) {
4777 		un->un_density_known = 0;
4778 	}
4779 
4780 	ASSERT(mutex_owned(ST_MUTEX));
4781 	return (rval);
4782 }
4783 
4784 static int
4785 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
4786 {
4787 	struct mtlop local;
4788 	int rval;
4789 
4790 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
4791 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
4792 		return (EFAULT);
4793 	}
4794 
4795 	rval = st_do_mtioctop(un, &local);
4796 
4797 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
4798 		rval = EFAULT;
4799 	}
4800 	return (rval);
4801 }
4802 
4803 
4804 static int
4805 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
4806 {
4807 	dev_t dev = un->un_dev;
4808 	int savefile;
4809 	int rval = 0;
4810 
4811 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
4812 
4813 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4814 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
4815 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4816 	    "fileno=%x, blkno=%x, eof=%x\n",
4817 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4818 
4819 	un->un_status = 0;
4820 
4821 	/*
4822 	 * if we are going to mess with a tape, we have to make sure we have
4823 	 * one and are not offline (i.e. no tape is initialized).  We let
4824 	 * commands pass here that don't actually touch the tape, except for
4825 	 * loading and initialization (rewinding).
4826 	 */
4827 	if (un->un_state == ST_STATE_OFFLINE) {
4828 		switch (mtop->mt_op) {
4829 		case MTLOAD:
4830 		case MTNOP:
4831 			/*
4832 			 * We don't want strategy calling st_tape_init here,
4833 			 * so, change state
4834 			 */
4835 			un->un_state = ST_STATE_INITIALIZING;
4836 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4837 			    "st_do_mtioctop : OFFLINE state = %d\n",
4838 			    un->un_state);
4839 			break;
4840 		default:
4841 			/*
4842 			 * reinitialize by normal means
4843 			 */
4844 			rval = st_tape_init(dev);
4845 			if (rval) {
4846 				un->un_state = ST_STATE_INITIALIZING;
4847 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4848 				    "st_do_mtioctop : OFFLINE init failure ");
4849 				un->un_state = ST_STATE_OFFLINE;
4850 				un->un_pos.pmode = invalid;
4851 				if (rval != EACCES) {
4852 					rval = EIO;
4853 				}
4854 				return (rval);
4855 			}
4856 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4857 			break;
4858 		}
4859 	}
4860 
4861 	/*
4862 	 * If the file position is invalid, allow only those
4863 	 * commands that properly position the tape and fail
4864 	 * the rest with EIO
4865 	 */
4866 	if (un->un_pos.pmode == invalid) {
4867 		switch (mtop->mt_op) {
4868 		case MTWEOF:
4869 		case MTRETEN:
4870 		case MTERASE:
4871 		case MTEOM:
4872 		case MTFSF:
4873 		case MTFSR:
4874 		case MTBSF:
4875 		case MTNBSF:
4876 		case MTBSR:
4877 		case MTSRSZ:
4878 		case MTGRSZ:
4879 		case MTSEEK:
4880 		case MTBSSF:
4881 		case MTFSSF:
4882 			return (EIO);
4883 			/* NOTREACHED */
4884 		case MTREW:
4885 		case MTLOAD:
4886 		case MTOFFL:
4887 		case MTNOP:
4888 		case MTTELL:
4889 		case MTLOCK:
4890 		case MTUNLOCK:
4891 			break;
4892 
4893 		default:
4894 			return (ENOTTY);
4895 			/* NOTREACHED */
4896 		}
4897 	}
4898 
4899 	switch (mtop->mt_op) {
4900 	case MTERASE:
4901 		/*
4902 		 * MTERASE rewinds the tape, erase it completely, and returns
4903 		 * to the beginning of the tape
4904 		 */
4905 		if (un->un_mspl->wp || un->un_read_only & WORM) {
4906 			un->un_status = KEY_WRITE_PROTECT;
4907 			un->un_err_resid = mtop->mt_count;
4908 			COPY_POS(&un->un_err_pos, &un->un_pos);
4909 			return (EACCES);
4910 		}
4911 		if (un->un_dp->options & ST_REEL) {
4912 			un->un_fmneeded = 2;
4913 		} else {
4914 			un->un_fmneeded = 1;
4915 		}
4916 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
4917 		    st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD) ||
4918 		    st_cmd(dev, SCMD_ERASE, 0, SYNC_CMD)) {
4919 			un->un_pos.pmode = invalid;
4920 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4921 			    "st_do_mtioctop : EIO space or erase or "
4922 			    "check den)\n");
4923 			rval = EIO;
4924 		} else {
4925 			/* QIC and helical scan rewind after erase */
4926 			if (un->un_dp->options & ST_REEL) {
4927 				(void) st_cmd(dev, SCMD_REWIND, 0, ASYNC_CMD);
4928 			}
4929 		}
4930 		break;
4931 
4932 	case MTWEOF:
4933 		/*
4934 		 * write an end-of-file record
4935 		 */
4936 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
4937 			un->un_status = KEY_WRITE_PROTECT;
4938 			un->un_err_resid = mtop->mt_count;
4939 			COPY_POS(&un->un_err_pos, &un->un_pos);
4940 			return (EACCES);
4941 		}
4942 
4943 		/*
4944 		 * zero count means just flush buffers
4945 		 * negative count is not permitted
4946 		 */
4947 		if (mtop->mt_count < 0) {
4948 			return (EINVAL);
4949 		}
4950 
4951 		/* Not on worm */
4952 		if (un->un_read_only == RDWR) {
4953 			un->un_test_append = 1;
4954 		}
4955 
4956 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4957 			if (st_determine_density(dev, B_WRITE)) {
4958 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4959 				    "st_do_mtioctop : EIO : MTWEOF can't "
4960 				    "determine density");
4961 				return (EIO);
4962 			}
4963 		}
4964 
4965 		rval = st_write_fm(dev, (int)mtop->mt_count);
4966 		if ((rval != 0) && (rval != EACCES)) {
4967 			/*
4968 			 * Failure due to something other than illegal
4969 			 * request results in loss of state (st_intr).
4970 			 */
4971 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4972 			    "st_do_mtioctop : EIO : MTWEOF can't write "
4973 			    "file mark");
4974 			rval = EIO;
4975 		}
4976 		break;
4977 
4978 	case MTRETEN:
4979 		/*
4980 		 * retension the tape
4981 		 */
4982 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
4983 		    st_cmd(dev, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
4984 			un->un_pos.pmode = invalid;
4985 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4986 			    "st_do_mtioctop : EIO : MTRETEN ");
4987 			rval = EIO;
4988 		}
4989 		break;
4990 
4991 	case MTREW:
4992 		/*
4993 		 * rewind  the tape
4994 		 */
4995 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
4996 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4997 			    "st_do_mtioctop : EIO:MTREW check "
4998 			    "density/wfm failed");
4999 			return (EIO);
5000 		}
5001 		if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
5002 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5003 			    "st_do_mtioctop : EIO : MTREW ");
5004 			rval = EIO;
5005 		}
5006 		break;
5007 
5008 	case MTOFFL:
5009 		/*
5010 		 * rewinds, and, if appropriate, takes the device offline by
5011 		 * unloading the tape
5012 		 */
5013 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5014 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5015 			    "st_do_mtioctop :EIO:MTOFFL check "
5016 			    "density/wfm failed");
5017 			return (EIO);
5018 		}
5019 		(void) st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
5020 		if (st_cmd(dev, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5021 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5022 			    "st_do_mtioctop : EIO : MTOFFL");
5023 			return (EIO);
5024 		}
5025 		un->un_pos.eof = ST_NO_EOF;
5026 		un->un_laststate = un->un_state;
5027 		un->un_state = ST_STATE_OFFLINE;
5028 		un->un_mediastate = MTIO_EJECTED;
5029 		break;
5030 
5031 	case MTLOAD:
5032 		/*
5033 		 * This is to load a tape into the drive
5034 		 * Note that if the tape is not loaded, the device will have
5035 		 * to be opened via O_NDELAY or O_NONBLOCK.
5036 		 */
5037 		/*
5038 		 * Let's try and clean things up, if we are not
5039 		 * initializing, and then send in the load command, no
5040 		 * matter what.
5041 		 *
5042 		 * load after a media change by the user.
5043 		 */
5044 
5045 		if (un->un_state > ST_STATE_INITIALIZING) {
5046 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5047 		}
5048 		rval = st_cmd(dev, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5049 		/* Load command to a drive that doesn't support load */
5050 		if ((rval == EIO) &&
5051 		    ((un->un_status == KEY_NOT_READY) &&
5052 			/* Medium not present */
5053 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5054 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5055 		    (un->un_dp->type == MT_ISSTK9840) &&
5056 			/* CSL not present */
5057 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5058 			rval = ENOTTY;
5059 			break;
5060 		} else if (rval != EACCES) {
5061 			rval = EIO;
5062 		}
5063 		if (rval) {
5064 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5065 			    "st_do_mtioctop : %s : MTLOAD\n",
5066 			    rval == EACCES ? "EACCES" : "EIO");
5067 			/*
5068 			 * If load tape fails, who knows what happened...
5069 			 */
5070 			un->un_pos.pmode = invalid;
5071 			break;
5072 		}
5073 
5074 		/*
5075 		 * reset all counters appropriately using rewind, as if LOAD
5076 		 * succeeds, we are at BOT
5077 		 */
5078 		un->un_state = ST_STATE_INITIALIZING;
5079 
5080 		rval = st_tape_init(dev);
5081 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5082 			rval = 0;
5083 			break;
5084 		}
5085 
5086 		if (rval != 0) {
5087 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5088 			    "st_do_mtioctop : EIO : MTLOAD calls "
5089 			    "st_tape_init\n");
5090 			rval = EIO;
5091 			un->un_state = ST_STATE_OFFLINE;
5092 		}
5093 
5094 		break;
5095 
5096 	case MTNOP:
5097 		un->un_status = 0;		/* Reset status */
5098 		un->un_err_resid = 0;
5099 		mtop->mt_count = MTUNIT(dev);
5100 		break;
5101 
5102 	case MTEOM:
5103 		/*
5104 		 * positions the tape at a location just after the last file
5105 		 * written on the tape. For cartridge and 8 mm, this after
5106 		 * the last file mark; for reel, this is inbetween the two
5107 		 * last 2 file marks
5108 		 */
5109 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5110 		    (un->un_lastop == ST_OP_WRITE) ||
5111 		    (un->un_lastop == ST_OP_WEOF)) {
5112 			/*
5113 			 * If the command wants to move to logical end
5114 			 * of media, and we're already there, we're done.
5115 			 * If we were at logical eot, we reset the state
5116 			 * to be *not* at logical eot.
5117 			 *
5118 			 * If we're at physical or logical eot, we prohibit
5119 			 * forward space operations (unconditionally).
5120 			 *
5121 			 * Also if the last operation was a write of any
5122 			 * kind the tape is at EOD.
5123 			 */
5124 			return (0);
5125 		}
5126 		/*
5127 		 * physical tape position may not be what we've been
5128 		 * telling the user; adjust the request accordingly
5129 		 */
5130 		if (IN_EOF(un->un_pos)) {
5131 			un->un_pos.fileno++;
5132 			un->un_pos.blkno = 0;
5133 		}
5134 
5135 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
5136 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5137 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
5138 			    " failed");
5139 			return (EIO);
5140 		}
5141 
5142 		/*
5143 		 * st_find_eod() returns the last fileno we knew about;
5144 		 */
5145 		savefile = st_find_eod(dev);
5146 
5147 		if ((un->un_status != KEY_BLANK_CHECK) &&
5148 		    (un->un_status != SUN_KEY_EOT)) {
5149 			un->un_pos.pmode = invalid;
5150 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5151 			    "st_do_mtioctop : EIO : MTEOM status check failed");
5152 			rval = EIO;
5153 		} else {
5154 			/*
5155 			 * For 1/2" reel tapes assume logical EOT marked
5156 			 * by two file marks or we don't care that we may
5157 			 * be extending the last file on the tape.
5158 			 */
5159 			if (un->un_dp->options & ST_REEL) {
5160 				if (st_cmd(dev, SCMD_SPACE, Fmk((-1)),
5161 				    SYNC_CMD)) {
5162 					un->un_pos.pmode = invalid;
5163 					ST_DEBUG2(ST_DEVINFO, st_label,
5164 					    SCSI_DEBUG,
5165 					    "st_do_mtioctop : EIO : MTEOM space"
5166 					    " cmd failed");
5167 					rval = EIO;
5168 					break;
5169 				}
5170 				/*
5171 				 * Fix up the block number.
5172 				 */
5173 				un->un_pos.blkno = 0;
5174 				un->un_err_pos.blkno = 0;
5175 			}
5176 			un->un_err_resid = 0;
5177 			un->un_pos.fileno = savefile;
5178 			un->un_pos.eof = ST_EOT;
5179 		}
5180 		un->un_status = 0;
5181 		break;
5182 
5183 	case MTFSF:
5184 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
5185 		break;
5186 
5187 	case MTFSR:
5188 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
5189 		break;
5190 
5191 	case MTBSF:
5192 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
5193 		break;
5194 
5195 	case MTNBSF:
5196 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
5197 		break;
5198 
5199 	case MTBSR:
5200 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
5201 		break;
5202 
5203 	case MTBSSF:
5204 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
5205 		break;
5206 
5207 	case MTFSSF:
5208 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
5209 		break;
5210 
5211 	case MTSRSZ:
5212 
5213 		/*
5214 		 * Set record-size to that sent by user
5215 		 * Check to see if there is reason that the requested
5216 		 * block size should not be set.
5217 		 */
5218 
5219 		/* If requesting variable block size is it ok? */
5220 		if ((mtop->mt_count == 0) &&
5221 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
5222 			return (ENOTTY);
5223 		}
5224 
5225 		/*
5226 		 * If requested block size is not variable "0",
5227 		 * is it less then minimum.
5228 		 */
5229 		if ((mtop->mt_count != 0) &&
5230 		    (mtop->mt_count < un->un_minbsize)) {
5231 			return (EINVAL);
5232 		}
5233 
5234 		/* Is the requested block size more then maximum */
5235 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
5236 		    (un->un_maxbsize != 0)) {
5237 			return (EINVAL);
5238 		}
5239 
5240 		/* Is requested block size a modulus the device likes */
5241 		if ((mtop->mt_count % un->un_data_mod) != 0) {
5242 			return (EINVAL);
5243 		}
5244 
5245 		if (st_change_block_size(dev, (uint32_t)mtop->mt_count) != 0) {
5246 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5247 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
5248 			return (EIO);
5249 		}
5250 
5251 		return (0);
5252 
5253 	case MTGRSZ:
5254 		/*
5255 		 * Get record-size to the user
5256 		 */
5257 		mtop->mt_count = un->un_bsize;
5258 		rval = 0;
5259 		break;
5260 
5261 	case MTTELL:
5262 		rval = st_update_block_pos(un);
5263 		mtop->mt_count = un->un_pos.lgclblkno;
5264 		break;
5265 
5266 	case MTSEEK:
5267 		rval = st_logical_block_locate(un, (uint64_t)mtop->mt_count,
5268 		    un->un_pos.partition);
5269 		/*
5270 		 * This bit of magic make mt print the actual position if
5271 		 * the resulting position was not what was asked for.
5272 		 */
5273 		if (rval == ESPIPE) {
5274 			rval = EIO;
5275 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
5276 				mtop->mt_op = MTTELL;
5277 				mtop->mt_count = un->un_pos.lgclblkno;
5278 			}
5279 		}
5280 		break;
5281 
5282 	case MTLOCK:
5283 		if (st_cmd(dev, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
5284 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5285 			    "st_do_mtioctop : EIO : MTLOCK");
5286 			rval = EIO;
5287 		}
5288 		break;
5289 
5290 	case MTUNLOCK:
5291 		if (st_cmd(dev, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
5292 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5293 			    "st_do_mtioctop : EIO : MTUNLOCK");
5294 			rval = EIO;
5295 		}
5296 		break;
5297 
5298 	default:
5299 		rval = ENOTTY;
5300 	}
5301 
5302 	return (rval);
5303 }
5304 
5305 
5306 /*
5307  * Run a command for uscsi ioctl.
5308  */
5309 static int
5310 st_ioctl_cmd(dev_t dev, struct uscsi_cmd *ucmd, int flag)
5311 {
5312 	struct uscsi_cmd	*uscmd;
5313 	struct buf	*bp;
5314 	enum uio_seg	uioseg;
5315 	int	offline_state = 0;
5316 	int	err = 0;
5317 
5318 	GET_SOFT_STATE(dev);
5319 
5320 	ST_FUNC(ST_DEVINFO, st_ioctl_cmd);
5321 
5322 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5323 	    "st_ioctl_cmd(dev = 0x%lx)\n", dev);
5324 
5325 	ASSERT(mutex_owned(ST_MUTEX));
5326 
5327 	/*
5328 	 * We really don't know what commands are coming in here and
5329 	 * we don't want to limit the commands coming in.
5330 	 *
5331 	 * If st_tape_init() gets called from st_strategy(), then we
5332 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
5333 	 * which it never will, as we set it below.  To prevent
5334 	 * st_tape_init() from getting called, we have to set state to other
5335 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
5336 	 * achieves this purpose already.
5337 	 *
5338 	 * We use offline_state to preserve the OFFLINE state, if it exists,
5339 	 * so other entry points to the driver might have the chance to call
5340 	 * st_tape_init().
5341 	 */
5342 	if (un->un_state == ST_STATE_OFFLINE) {
5343 		un->un_laststate = ST_STATE_OFFLINE;
5344 		un->un_state = ST_STATE_INITIALIZING;
5345 		offline_state = 1;
5346 	}
5347 
5348 	mutex_exit(ST_MUTEX);
5349 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag,
5350 	    ROUTE, &uscmd);
5351 	mutex_enter(ST_MUTEX);
5352 	if (err != 0) {
5353 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5354 		    "st_ioctl_cmd: scsi_uscsi_alloc_and_copyin failed\n");
5355 		goto exit;
5356 	}
5357 
5358 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
5359 
5360 	/* check to see if this command requires the drive to be reserved */
5361 	if (uscmd->uscsi_cdb != NULL) {
5362 		err = st_check_cdb_for_need_to_reserve(un,
5363 		    &((char *)uscmd->uscsi_cdb)[0]);
5364 		if (err) {
5365 			goto exit_free;
5366 		}
5367 	}
5368 
5369 	/*
5370 	 * Get buffer resources...
5371 	 */
5372 	while (un->un_sbuf_busy)
5373 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
5374 	un->un_sbuf_busy = 1;
5375 
5376 #ifdef STDEBUG
5377 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0xf) > 6) {
5378 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
5379 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
5380 		    "uscsi cdb", uscmd->uscsi_cdb);
5381 		if (uscmd->uscsi_buflen) {
5382 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5383 			    "uscsi %s of %ld bytes %s %s space\n",
5384 			    (rw == B_READ) ? rd_str : wr_str,
5385 			    uscmd->uscsi_buflen,
5386 			    (rw == B_READ) ? "to" : "from",
5387 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
5388 		}
5389 	}
5390 #endif /* ST_DEBUG */
5391 
5392 	/*
5393 	 * Although st_ioctl_cmd() never makes use of these
5394 	 * now, we are just being safe and consistent.
5395 	 */
5396 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
5397 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
5398 
5399 	un->un_srqbufp = uscmd->uscsi_rqbuf;
5400 	bp = un->un_sbufp;
5401 	bzero(bp, sizeof (buf_t));
5402 	if (uscmd->uscsi_cdb != NULL) {
5403 		bp->b_forw =
5404 		    (struct buf *)(uintptr_t)((char *)uscmd->uscsi_cdb)[0];
5405 		bp->b_back = (struct buf *)uscmd;
5406 	}
5407 
5408 	mutex_exit(ST_MUTEX);
5409 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd,
5410 	    st_strategy, bp, NULL);
5411 	mutex_enter(ST_MUTEX);
5412 
5413 	/*
5414 	 * If scsi reset successful, don't write any filemarks.
5415 	 */
5416 	if ((err == 0) && (uscmd->uscsi_flags &
5417 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
5418 		un->un_fmneeded = 0;
5419 	}
5420 
5421 exit_free:
5422 	/*
5423 	 * Free resources
5424 	 */
5425 	un->un_sbuf_busy = 0;
5426 	un->un_srqbufp = NULL;
5427 
5428 	/*
5429 	 * If was a space command need to update logical block position.
5430 	 * If the command failed such that positioning is invalid, Don't
5431 	 * update the position as the user must do this to validate the
5432 	 * position for data protection.
5433 	 */
5434 	if ((uscmd->uscsi_cdb != NULL) &&
5435 	    (uscmd->uscsi_cdb[0] == SCMD_SPACE) &&
5436 	    (un->un_pos.pmode != invalid)) {
5437 		uchar_t status = un->un_status;
5438 		(void) st_update_block_pos(un);
5439 		un->un_status = status;
5440 	}
5441 	cv_signal(&un->un_sbuf_cv);
5442 	mutex_exit(ST_MUTEX);
5443 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
5444 	mutex_enter(ST_MUTEX);
5445 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5446 	    "st_ioctl_cmd returns 0x%x\n", err);
5447 
5448 exit:
5449 	/* don't lose offline state */
5450 	if (offline_state) {
5451 		un->un_state = ST_STATE_OFFLINE;
5452 	}
5453 
5454 	ASSERT(mutex_owned(ST_MUTEX));
5455 	return (err);
5456 }
5457 
5458 static int
5459 st_write_fm(dev_t dev, int wfm)
5460 {
5461 	int i;
5462 	int rval;
5463 
5464 	GET_SOFT_STATE(dev);
5465 
5466 	ST_FUNC(ST_DEVINFO, st_write_fm);
5467 
5468 	ASSERT(mutex_owned(ST_MUTEX));
5469 
5470 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5471 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
5472 
5473 	/*
5474 	 * write one filemark at the time after EOT
5475 	 */
5476 	if (un->un_pos.eof >= ST_EOT) {
5477 		for (i = 0; i < wfm; i++) {
5478 			rval = st_cmd(dev, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
5479 			if (rval == EACCES) {
5480 				return (rval);
5481 			}
5482 			if (rval != 0) {
5483 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5484 				    "st_write_fm : EIO : write EOT file mark");
5485 				return (EIO);
5486 			}
5487 		}
5488 	} else {
5489 		rval = st_cmd(dev, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
5490 		if (rval == EACCES) {
5491 			return (rval);
5492 		}
5493 		if (rval) {
5494 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5495 			    "st_write_fm : EIO : write file mark");
5496 			return (EIO);
5497 		}
5498 	}
5499 
5500 	ASSERT(mutex_owned(ST_MUTEX));
5501 	return (0);
5502 }
5503 
5504 #ifdef STDEBUG
5505 static void
5506 start_dump(struct scsi_tape *un, struct buf *bp)
5507 {
5508 	struct scsi_pkt *pkt = BP_PKT(bp);
5509 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
5510 
5511 	ST_FUNC(ST_DEVINFO, start_dump);
5512 
5513 	if ((st_debug & 0xf) < 6)
5514 		return;
5515 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5516 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
5517 	    (void *)bp->b_forw, bp->b_bcount,
5518 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
5519 
5520 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
5521 	    "st_start: cdb",  (caddr_t)cdbp);
5522 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5523 	    "st_start: fileno=%d, blk=%d\n",
5524 	    un->un_pos.fileno, un->un_pos.blkno);
5525 }
5526 #endif
5527 
5528 
5529 /*
5530  * Command start && done functions
5531  */
5532 
5533 /*
5534  * st_start()
5535  *
5536  * Called from:
5537  *  st_strategy() to start a command.
5538  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
5539  *  st_attach() when resuming from power down state.
5540  *  st_start_restart() to retry transport when device was previously busy.
5541  *  st_done_and_mutex_exit() to start the next command when previous is done.
5542  *
5543  * On entry:
5544  *  scsi_pkt may or may not be allocated.
5545  *
5546  */
5547 static void
5548 st_start(struct scsi_tape *un)
5549 {
5550 	struct buf *bp;
5551 	int status;
5552 
5553 	ST_FUNC(ST_DEVINFO, st_start);
5554 	ASSERT(mutex_owned(ST_MUTEX));
5555 
5556 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5557 	    "st_start(): dev = 0x%lx\n", un->un_dev);
5558 
5559 	if ((bp = un->un_quef) == NULL) {
5560 		return;
5561 	}
5562 
5563 	ASSERT((bp->b_flags & B_DONE) == 0);
5564 
5565 	/*
5566 	 * Don't send more than un_throttle commands to the HBA
5567 	 */
5568 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
5569 		return;
5570 	}
5571 
5572 	/*
5573 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
5574 	 * build the command.
5575 	 */
5576 	if (BP_PKT(bp) == NULL) {
5577 		ASSERT((bp->b_flags & B_DONE) == 0);
5578 		st_make_cmd(un, bp, st_runout);
5579 		ASSERT((bp->b_flags & B_DONE) == 0);
5580 		status = geterror(bp);
5581 
5582 		/*
5583 		 * Some HBA's don't call bioerror() to set an error.
5584 		 * And geterror() returns zero if B_ERROR is not set.
5585 		 * So if we get zero we must check b_error.
5586 		 */
5587 		if (status == 0 && bp->b_error != 0) {
5588 			status = bp->b_error;
5589 			bioerror(bp, status);
5590 		}
5591 
5592 		/*
5593 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
5594 		 * In tape ENOMEM has special meaning so we'll change it.
5595 		 */
5596 		if (status == ENOMEM) {
5597 			status = 0;
5598 			bioerror(bp, status);
5599 		}
5600 
5601 		/*
5602 		 * Did it fail and is it retryable?
5603 		 * If so return and wait for the callback through st_runout.
5604 		 * Also looks like scsi_init_pkt() will setup a callback even
5605 		 * if it isn't retryable.
5606 		 */
5607 		if (BP_PKT(bp) == NULL) {
5608 			if (status == 0) {
5609 				/*
5610 				 * If first attempt save state.
5611 				 */
5612 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
5613 					un->un_laststate = un->un_state;
5614 					un->un_state = ST_STATE_RESOURCE_WAIT;
5615 				}
5616 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5617 				    "temp no resources for pkt\n");
5618 			} else {
5619 				/*
5620 				 * Unlikely that it would be retryable then not.
5621 				 */
5622 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
5623 					un->un_state = un->un_laststate;
5624 				}
5625 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5626 				    "perm no resources for pkt errno = 0x%x\n",
5627 				    status);
5628 			}
5629 			return;
5630 		}
5631 		/*
5632 		 * Worked this time set the state back.
5633 		 */
5634 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
5635 			un->un_state = un->un_laststate;
5636 		}
5637 	}
5638 
5639 	/*
5640 	 * move from waitq to runq
5641 	 */
5642 	un->un_quef = bp->b_actf;
5643 	if (un->un_quel == bp) {
5644 		/*
5645 		 *  For the case of queue having one
5646 		 *  element, set the tail pointer to
5647 		 *  point to the element.
5648 		 */
5649 		un->un_quel = bp->b_actf;
5650 	}
5651 
5652 	bp->b_actf = NULL;
5653 
5654 	if (un->un_runqf) {
5655 		un->un_runql->b_actf = bp;
5656 	} else {
5657 		un->un_runqf = bp;
5658 	}
5659 	un->un_runql = bp;
5660 
5661 
5662 	ST_CDB(ST_DEVINFO, "Start CDB", (char *)BP_PKT(bp)->pkt_cdbp);
5663 
5664 #ifdef STDEBUG
5665 	start_dump(un, bp);
5666 #endif
5667 
5668 	/* could not get here if throttle was zero */
5669 	un->un_last_throttle = un->un_throttle;
5670 	un->un_throttle = 0;	/* so nothing else will come in here */
5671 	un->un_ncmds++;
5672 
5673 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
5674 
5675 	mutex_exit(ST_MUTEX);
5676 
5677 	status = scsi_transport(BP_PKT(bp));
5678 
5679 	mutex_enter(ST_MUTEX);
5680 
5681 	if (un->un_last_throttle) {
5682 		un->un_throttle = un->un_last_throttle;
5683 	}
5684 
5685 	if (status != TRAN_ACCEPT) {
5686 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
5687 		mutex_exit(ST_MUTEX);
5688 
5689 		if (status == TRAN_BUSY) {
5690 			/* if too many retries, fail the transport */
5691 			if (st_handle_start_busy(un, bp,
5692 			    ST_TRAN_BUSY_TIMEOUT) == 0)
5693 				goto done;
5694 		}
5695 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
5696 		    "transport rejected\n");
5697 		bp->b_resid = bp->b_bcount;
5698 
5699 
5700 #ifndef __lock_lint
5701 		/*
5702 		 * warlock doesn't understand this potential
5703 		 * recursion?
5704 		 */
5705 		mutex_enter(ST_MUTEX);
5706 		ST_DO_KSTATS(bp, kstat_waitq_exit);
5707 		ST_DO_ERRSTATS(un, st_transerrs);
5708 		st_bioerror(bp, EIO);
5709 		SET_PE_FLAG(un);
5710 		st_done_and_mutex_exit(un, bp);
5711 #endif
5712 	} else {
5713 		un->un_tran_retry_ct = 0;
5714 		mutex_exit(ST_MUTEX);
5715 	}
5716 
5717 done:
5718 
5719 	mutex_enter(ST_MUTEX);
5720 }
5721 
5722 /*
5723  * if the transport is busy, then put this bp back on the waitq
5724  */
5725 static int
5726 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
5727     clock_t timeout_interval)
5728 {
5729 	struct buf *last_quef, *runq_bp;
5730 	int rval = 0;
5731 
5732 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
5733 
5734 	mutex_enter(ST_MUTEX);
5735 
5736 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5737 	    "st_handle_start_busy()\n");
5738 
5739 	/*
5740 	 * Check to see if we hit the retry timeout and one last check for
5741 	 * making sure this is the last on the runq, if it is not, we have
5742 	 * to fail
5743 	 */
5744 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
5745 	    (un->un_runql != bp)) {
5746 		rval = -1;
5747 		goto exit;
5748 	}
5749 
5750 	/* put the bp back on the waitq */
5751 	if (un->un_quef) {
5752 		last_quef = un->un_quef;
5753 		un->un_quef = bp;
5754 		bp->b_actf = last_quef;
5755 	} else  {
5756 		bp->b_actf = NULL;
5757 		un->un_quef = bp;
5758 		un->un_quel = bp;
5759 	}
5760 
5761 	/*
5762 	 * Decrement un_ncmds so that this
5763 	 * gets thru' st_start() again.
5764 	 */
5765 	un->un_ncmds--;
5766 
5767 	/*
5768 	 * since this is an error case, we won't have to do
5769 	 * this list walking much.  We've already made sure this bp was the
5770 	 * last on the runq
5771 	 */
5772 	runq_bp = un->un_runqf;
5773 
5774 	if (un->un_runqf == bp) {
5775 		un->un_runqf = NULL;
5776 		un->un_runql = NULL;
5777 	} else {
5778 		while (runq_bp) {
5779 			if (runq_bp->b_actf == bp) {
5780 				runq_bp->b_actf = NULL;
5781 				un->un_runql = runq_bp;
5782 				break;
5783 			}
5784 			runq_bp = runq_bp->b_actf;
5785 		}
5786 	}
5787 
5788 
5789 	/*
5790 	 * send a marker pkt, if appropriate
5791 	 */
5792 	st_hba_unflush(un);
5793 
5794 	/*
5795 	 * all queues are aligned, we are just waiting to
5796 	 * transport, don't alloc any more buf p's, when
5797 	 * st_start is reentered.
5798 	 */
5799 	(void) timeout(st_start_restart, un, timeout_interval);
5800 
5801 exit:
5802 	mutex_exit(ST_MUTEX);
5803 	return (rval);
5804 }
5805 
5806 
5807 /*
5808  * st_runout a callback that is called what a resource allocatation failed
5809  */
5810 static int
5811 st_runout(caddr_t arg)
5812 {
5813 	struct scsi_tape *un = (struct scsi_tape *)arg;
5814 	struct buf *bp;
5815 	ASSERT(un != NULL);
5816 
5817 	ST_FUNC(ST_DEVINFO, st_runout);
5818 
5819 	mutex_enter(ST_MUTEX);
5820 
5821 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
5822 
5823 	bp = un->un_quef;
5824 
5825 	/*
5826 	 * failed scsi_init_pkt(). If errno is zero its retryable.
5827 	 */
5828 	if ((bp != NULL) && (geterror(bp) != 0)) {
5829 
5830 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
5831 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
5832 		    bp->b_flags, geterror(bp));
5833 		ASSERT((bp->b_flags & B_DONE) == 0);
5834 
5835 		un->un_quef = bp->b_actf;
5836 		if (un->un_quel == bp) {
5837 			/*
5838 			 *  For the case of queue having one
5839 			 *  element, set the tail pointer to
5840 			 *  point to the element.
5841 			 */
5842 			un->un_quel = bp->b_actf;
5843 		}
5844 		mutex_exit(ST_MUTEX);
5845 		bp->b_actf = NULL;
5846 
5847 		ASSERT((bp->b_flags & B_DONE) == 0);
5848 
5849 		/*
5850 		 * Set resid, Error already set, then unblock calling thread.
5851 		 */
5852 		bp->b_resid = bp->b_bcount;
5853 		biodone(bp);
5854 	} else {
5855 		/*
5856 		 * Try Again
5857 		 */
5858 		st_start(un);
5859 		mutex_exit(ST_MUTEX);
5860 	}
5861 
5862 	/*
5863 	 * Comments courtesy of sd.c
5864 	 * The scsi_init_pkt routine allows for the callback function to
5865 	 * return a 0 indicating the callback should be rescheduled or a 1
5866 	 * indicating not to reschedule. This routine always returns 1
5867 	 * because the driver always provides a callback function to
5868 	 * scsi_init_pkt. This results in a callback always being scheduled
5869 	 * (via the scsi_init_pkt callback implementation) if a resource
5870 	 * failure occurs.
5871 	 */
5872 
5873 	return (1);
5874 }
5875 
5876 /*
5877  * st_done_and_mutex_exit()
5878  *	- remove bp from runq
5879  *	- start up the next request
5880  *	- if this was an asynch bp, clean up
5881  *	- exit with released mutex
5882  */
5883 static void
5884 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
5885 {
5886 	struct buf *runqbp, *prevbp;
5887 	int	pe_flagged = 0;
5888 
5889 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
5890 #if !defined(lint)
5891 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
5892 #endif
5893 
5894 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
5895 
5896 	ASSERT(mutex_owned(ST_MUTEX));
5897 
5898 	/*
5899 	 * if bp is still on the runq (anywhere), then remove it
5900 	 */
5901 	prevbp = NULL;
5902 	for (runqbp = un->un_runqf; runqbp != 0; runqbp = runqbp->b_actf) {
5903 		if (runqbp == bp) {
5904 			if (runqbp == un->un_runqf) {
5905 				un->un_runqf = bp->b_actf;
5906 			} else {
5907 				prevbp->b_actf = bp->b_actf;
5908 			}
5909 			if (un->un_runql == bp) {
5910 				un->un_runql = prevbp;
5911 			}
5912 			break;
5913 		}
5914 		prevbp = runqbp;
5915 	}
5916 	bp->b_actf = NULL;
5917 
5918 	un->un_ncmds--;
5919 	cv_signal(&un->un_queue_cv);
5920 
5921 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5922 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
5923 	    "0x%x\n", (uchar_t)*((caddr_t)(BP_PKT(bp))->pkt_cdbp), bp->b_bcount,
5924 	    bp->b_resid, bp->b_flags);
5925 
5926 
5927 	/*
5928 	 * update kstats with transfer count info
5929 	 */
5930 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
5931 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
5932 		if (bp->b_flags & B_READ) {
5933 			IOSP->reads++;
5934 			IOSP->nread += n_done;
5935 		} else {
5936 			IOSP->writes++;
5937 			IOSP->nwritten += n_done;
5938 		}
5939 	}
5940 
5941 	/*
5942 	 * Start the next one before releasing resources on this one, if
5943 	 * there is something on the queue and persistent errors has not been
5944 	 * flagged
5945 	 */
5946 
5947 	if ((pe_flagged = IS_PE_FLAG_SET(un)) != 0) {
5948 		un->un_last_resid = bp->b_resid;
5949 		un->un_last_count = bp->b_bcount;
5950 	}
5951 
5952 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
5953 		cv_broadcast(&un->un_tape_busy_cv);
5954 	} else if (un->un_quef && un->un_throttle && !pe_flagged) {
5955 		st_start(un);
5956 	}
5957 
5958 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
5959 		/*
5960 		 * Since we marked this ourselves as ASYNC,
5961 		 * there isn't anybody around waiting for
5962 		 * completion any more.
5963 		 */
5964 		uchar_t com = (uchar_t)(uintptr_t)bp->b_forw;
5965 		if (com == SCMD_READ || com == SCMD_WRITE) {
5966 			bp->b_un.b_addr = (caddr_t)0;
5967 		}
5968 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5969 		    "st_done_and_mutex_exit(async): freeing pkt\n");
5970 		scsi_destroy_pkt(BP_PKT(bp));
5971 		un->un_sbuf_busy = 0;
5972 		cv_signal(&un->un_sbuf_cv);
5973 		mutex_exit(ST_MUTEX);
5974 		return;
5975 	}
5976 
5977 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
5978 		/*
5979 		 * Copy status from scsi_pkt to uscsi_cmd
5980 		 * since st_ioctl_cmd needs it
5981 		 */
5982 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
5983 	}
5984 
5985 
5986 #ifdef STDEBUG
5987 	if (((st_debug & 0xf) >= 4) &&
5988 	    (((un->un_pos.blkno % 100) == 0) || IS_PE_FLAG_SET(un))) {
5989 
5990 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
5991 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
5992 		    "un_errno = %d, un_pe = %d\n",
5993 		    un->un_ncmds, un->un_throttle, un->un_errno,
5994 		    un->un_persist_errors);
5995 	}
5996 
5997 #endif
5998 
5999 	mutex_exit(ST_MUTEX);
6000 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6001 	    "st_done_and_mutex_exit: freeing pkt\n");
6002 
6003 	scsi_destroy_pkt(BP_PKT(bp));
6004 
6005 	biodone(bp);
6006 
6007 	/*
6008 	 * now that we biodoned that command, if persistent errors have been
6009 	 * flagged, flush the waitq
6010 	 */
6011 	if (pe_flagged)
6012 		st_flush(un);
6013 }
6014 
6015 
6016 /*
6017  * Tape error, flush tape driver queue.
6018  */
6019 static void
6020 st_flush(struct scsi_tape *un)
6021 {
6022 	struct buf *bp;
6023 
6024 	ST_FUNC(ST_DEVINFO, st_flush);
6025 
6026 	mutex_enter(ST_MUTEX);
6027 
6028 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6029 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6030 	    un->un_ncmds, (void *)un->un_quef);
6031 
6032 	/*
6033 	 * if we still have commands outstanding, wait for them to come in
6034 	 * before flushing the queue, and make sure there is a queue
6035 	 */
6036 	if (un->un_ncmds || !un->un_quef)
6037 		goto exit;
6038 
6039 	/*
6040 	 * we have no more commands outstanding, so let's deal with special
6041 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6042 	 * is 0, then we know there was no error and we return a 0 read or
6043 	 * write before showing errors
6044 	 */
6045 
6046 	/* Flush the wait queue. */
6047 	while ((bp = un->un_quef) != NULL) {
6048 		un->un_quef = bp->b_actf;
6049 
6050 		bp->b_resid = bp->b_bcount;
6051 
6052 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6053 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6054 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6055 
6056 		st_set_pe_errno(un);
6057 
6058 		bioerror(bp, un->un_errno);
6059 
6060 		mutex_exit(ST_MUTEX);
6061 		/* it should have one, but check anyway */
6062 		if (BP_PKT(bp)) {
6063 			scsi_destroy_pkt(BP_PKT(bp));
6064 		}
6065 		biodone(bp);
6066 		mutex_enter(ST_MUTEX);
6067 	}
6068 
6069 	/*
6070 	 * It's not a bad practice to reset the
6071 	 * waitq tail pointer to NULL.
6072 	 */
6073 	un->un_quel = NULL;
6074 
6075 exit:
6076 	/* we mucked with the queue, so let others know about it */
6077 	cv_signal(&un->un_queue_cv);
6078 	mutex_exit(ST_MUTEX);
6079 }
6080 
6081 
6082 /*
6083  * Utility functions
6084  */
6085 static int
6086 st_determine_generic(dev_t dev)
6087 {
6088 	int bsize;
6089 	static char *cart = "0.25 inch cartridge";
6090 	char *sizestr;
6091 
6092 	GET_SOFT_STATE(dev);
6093 
6094 	ST_FUNC(ST_DEVINFO, st_determine_generic);
6095 
6096 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6097 	    "st_determine_generic(dev = 0x%lx)\n", dev);
6098 
6099 	ASSERT(mutex_owned(ST_MUTEX));
6100 
6101 	if (st_modesense(un)) {
6102 		return (-1);
6103 	}
6104 
6105 	bsize = (un->un_mspl->high_bl << 16)	|
6106 	    (un->un_mspl->mid_bl << 8)	|
6107 	    (un->un_mspl->low_bl);
6108 
6109 	if (bsize == 0) {
6110 		un->un_dp->options |= ST_VARIABLE;
6111 		un->un_dp->bsize = 0;
6112 		un->un_bsize = 0;
6113 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
6114 		/*
6115 		 * record size of this device too big.
6116 		 * try and convert it to variable record length.
6117 		 *
6118 		 */
6119 		un->un_dp->options |= ST_VARIABLE;
6120 		if (st_change_block_size(dev, 0) != 0) {
6121 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6122 			    "Fixed Record Size %d is too large\n", bsize);
6123 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6124 			    "Cannot switch to variable record size\n");
6125 			un->un_dp->options &= ~ST_VARIABLE;
6126 			return (-1);
6127 		}
6128 	} else if (st_change_block_size(dev, 0) == 0) {
6129 		/*
6130 		 * If the drive was set to a non zero block size,
6131 		 * See if it can be set to a zero block size.
6132 		 * If it works, ST_VARIABLE so user can set it as they want.
6133 		 */
6134 		un->un_dp->options |= ST_VARIABLE;
6135 		un->un_dp->bsize = 0;
6136 		un->un_bsize = 0;
6137 	} else {
6138 		un->un_dp->bsize = bsize;
6139 		un->un_bsize = bsize;
6140 	}
6141 
6142 
6143 	switch (un->un_mspl->density) {
6144 	default:
6145 	case 0x0:
6146 		/*
6147 		 * default density, cannot determine any other
6148 		 * information.
6149 		 */
6150 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
6151 		un->un_dp->type = ST_TYPE_DEFAULT;
6152 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
6153 		break;
6154 	case 0x1:
6155 	case 0x2:
6156 	case 0x3:
6157 	case 0x6:
6158 		/*
6159 		 * 1/2" reel
6160 		 */
6161 		sizestr = "0.50 inch reel";
6162 		un->un_dp->type = ST_TYPE_REEL;
6163 		un->un_dp->options |= ST_REEL;
6164 		un->un_dp->densities[0] = 0x1;
6165 		un->un_dp->densities[1] = 0x2;
6166 		un->un_dp->densities[2] = 0x6;
6167 		un->un_dp->densities[3] = 0x3;
6168 		break;
6169 	case 0x4:
6170 	case 0x5:
6171 	case 0x7:
6172 	case 0x0b:
6173 
6174 		/*
6175 		 * Quarter inch.
6176 		 */
6177 		sizestr = cart;
6178 		un->un_dp->type = ST_TYPE_DEFAULT;
6179 		un->un_dp->options |= ST_QIC;
6180 
6181 		un->un_dp->densities[1] = 0x4;
6182 		un->un_dp->densities[2] = 0x5;
6183 		un->un_dp->densities[3] = 0x7;
6184 		un->un_dp->densities[0] = 0x0b;
6185 		break;
6186 
6187 	case 0x0f:
6188 	case 0x10:
6189 	case 0x11:
6190 	case 0x12:
6191 		/*
6192 		 * QIC-120, QIC-150, QIC-320, QIC-600
6193 		 */
6194 		sizestr = cart;
6195 		un->un_dp->type = ST_TYPE_DEFAULT;
6196 		un->un_dp->options |= ST_QIC;
6197 		un->un_dp->densities[0] = 0x0f;
6198 		un->un_dp->densities[1] = 0x10;
6199 		un->un_dp->densities[2] = 0x11;
6200 		un->un_dp->densities[3] = 0x12;
6201 		break;
6202 
6203 	case 0x09:
6204 	case 0x0a:
6205 	case 0x0c:
6206 	case 0x0d:
6207 		/*
6208 		 * 1/2" cartridge tapes. Include HI-TC.
6209 		 */
6210 		sizestr = cart;
6211 		sizestr[2] = '5';
6212 		sizestr[3] = '0';
6213 		un->un_dp->type = ST_TYPE_HIC;
6214 		un->un_dp->densities[0] = 0x09;
6215 		un->un_dp->densities[1] = 0x0a;
6216 		un->un_dp->densities[2] = 0x0c;
6217 		un->un_dp->densities[3] = 0x0d;
6218 		break;
6219 
6220 	case 0x13:
6221 			/* DDS-2/DDS-3 scsi spec densities */
6222 	case 0x24:
6223 	case 0x25:
6224 	case 0x26:
6225 		sizestr = "DAT Data Storage (DDS)";
6226 		un->un_dp->type = ST_TYPE_DAT;
6227 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6228 		break;
6229 
6230 	case 0x14:
6231 		/*
6232 		 * Helical Scan (Exabyte) devices
6233 		 */
6234 		sizestr = "8mm helical scan cartridge";
6235 		un->un_dp->type = ST_TYPE_EXABYTE;
6236 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6237 		break;
6238 	}
6239 
6240 	/*
6241 	 * Assume LONG ERASE, BSF and BSR
6242 	 */
6243 
6244 	un->un_dp->options |=
6245 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
6246 
6247 	/*
6248 	 * Only if mode sense data says no buffered write, set NOBUF
6249 	 */
6250 	if (un->un_mspl->bufm == 0)
6251 		un->un_dp->options |= ST_NOBUF;
6252 
6253 	/*
6254 	 * set up large read and write retry counts
6255 	 */
6256 
6257 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
6258 
6259 	/*
6260 	 * If this is a 0.50 inch reel tape, and
6261 	 * it is *not* variable mode, try and
6262 	 * set it to variable record length
6263 	 * mode.
6264 	 */
6265 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
6266 	    (un->un_dp->options & ST_VARIABLE)) {
6267 		if (st_change_block_size(dev, 0) == 0) {
6268 			un->un_dp->bsize = 0;
6269 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
6270 			    un->un_mspl->low_bl = 0;
6271 		}
6272 	}
6273 
6274 	/*
6275 	 * Write to console about type of device found
6276 	 */
6277 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
6278 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
6279 	    sizestr);
6280 	if (un->un_dp->options & ST_VARIABLE) {
6281 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6282 		    "!Variable record length I/O\n");
6283 	} else {
6284 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6285 		    "!Fixed record length (%d byte blocks) I/O\n",
6286 		    un->un_dp->bsize);
6287 	}
6288 	ASSERT(mutex_owned(ST_MUTEX));
6289 	return (0);
6290 }
6291 
6292 static int
6293 st_determine_density(dev_t dev, int rw)
6294 {
6295 	int rval = 0;
6296 
6297 	GET_SOFT_STATE(dev);
6298 
6299 	ST_FUNC(ST_DEVINFO, st_determine_density);
6300 
6301 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6302 	    "st_determine_density(dev = 0x%lx, rw = %s)\n",
6303 	    dev, (rw == B_WRITE ? wr_str: rd_str));
6304 
6305 	ASSERT(mutex_owned(ST_MUTEX));
6306 
6307 	/*
6308 	 * If we're past BOT, density is determined already.
6309 	 */
6310 	if (un->un_pos.pmode == logical) {
6311 		if (un->un_pos.lgclblkno != 0) {
6312 			goto exit;
6313 		}
6314 	} else if (un->un_pos.pmode == legacy) {
6315 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
6316 			/*
6317 			 * XXX: put in a bitch message about attempting to
6318 			 * XXX: change density past BOT.
6319 			 */
6320 			goto exit;
6321 		}
6322 	} else {
6323 		goto exit;
6324 	}
6325 
6326 
6327 	/*
6328 	 * If we're going to be writing, we set the density
6329 	 */
6330 	if (rw == 0 || rw == B_WRITE) {
6331 		/* un_curdens is used as an index into densities table */
6332 		un->un_curdens = MT_DENSITY(un->un_dev);
6333 		if (st_set_density(dev)) {
6334 			rval = -1;
6335 		}
6336 		goto exit;
6337 	}
6338 
6339 	/*
6340 	 * If density is known already,
6341 	 * we don't have to get it again.(?)
6342 	 */
6343 	if (!un->un_density_known) {
6344 		if (st_get_density(dev)) {
6345 			rval = -1;
6346 		}
6347 	}
6348 
6349 exit:
6350 	ASSERT(mutex_owned(ST_MUTEX));
6351 	return (rval);
6352 }
6353 
6354 
6355 /*
6356  * Try to determine density. We do this by attempting to read the
6357  * first record off the tape, cycling through the available density
6358  * codes as we go.
6359  */
6360 
6361 static int
6362 st_get_density(dev_t dev)
6363 {
6364 	int succes = 0, rval = -1, i;
6365 	uint_t size;
6366 	uchar_t dens, olddens;
6367 
6368 	GET_SOFT_STATE(dev);
6369 
6370 	ST_FUNC(ST_DEVINFO, st_get_density);
6371 
6372 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6373 	    "st_get_density(dev = 0x%lx)\n", dev);
6374 
6375 	ASSERT(mutex_owned(ST_MUTEX));
6376 
6377 	/*
6378 	 * If Auto Density override is enabled The drive has
6379 	 * only one density and there is no point in attempting
6380 	 * find the correct one.
6381 	 *
6382 	 * Since most modern drives auto detect the density
6383 	 * and format of the recorded media before they come
6384 	 * ready. What this function does is a legacy behavior
6385 	 * and modern drives not only don't need it, The backup
6386 	 * utilities that do positioning via uscsi find the un-
6387 	 * expected rewinds problematic.
6388 	 *
6389 	 * The drives that need this are old reel to reel devices.
6390 	 * I took a swag and said they must be scsi-1 or older.
6391 	 * I don't beleave there will any of the newer devices
6392 	 * that need this. There will be some scsi-1 devices that
6393 	 * don't need this but I don't think they will be using the
6394 	 * BIG aftermarket backup and restore utilitys.
6395 	 */
6396 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
6397 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
6398 		un->un_density_known = 1;
6399 		rval = 0;
6400 		goto exit;
6401 	}
6402 
6403 	/*
6404 	 * This will only work on variable record length tapes
6405 	 * if and only if all variable record length tapes autodensity
6406 	 * select.
6407 	 */
6408 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
6409 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
6410 
6411 	/*
6412 	 * Start at the specified density
6413 	 */
6414 
6415 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
6416 
6417 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
6418 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
6419 		/*
6420 		 * If we've done this density before,
6421 		 * don't bother to do it again.
6422 		 */
6423 		dens = un->un_dp->densities[un->un_curdens];
6424 		if (i > 0 && dens == olddens)
6425 			continue;
6426 		olddens = dens;
6427 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6428 		    "trying density 0x%x\n", dens);
6429 		if (st_set_density(dev)) {
6430 			continue;
6431 		}
6432 
6433 		/*
6434 		 * XXX - the creates lots of headaches and slowdowns - must
6435 		 * fix.
6436 		 */
6437 		succes = (st_cmd(dev, SCMD_READ, (int)size, SYNC_CMD) == 0);
6438 		if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
6439 			break;
6440 		}
6441 		if (succes) {
6442 			st_init(un);
6443 			rval = 0;
6444 			un->un_density_known = 1;
6445 			break;
6446 		}
6447 	}
6448 	kmem_free(un->un_tmpbuf, size);
6449 	un->un_tmpbuf = 0;
6450 
6451 exit:
6452 	ASSERT(mutex_owned(ST_MUTEX));
6453 	return (rval);
6454 }
6455 
6456 static int
6457 st_set_density(dev_t dev)
6458 {
6459 	int rval = 0;
6460 
6461 	GET_SOFT_STATE(dev);
6462 
6463 	ST_FUNC(ST_DEVINFO, st_set_density);
6464 
6465 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6466 	    "st_set_density(dev = 0x%lx): density = 0x%x\n", dev,
6467 	    un->un_dp->densities[un->un_curdens]);
6468 
6469 	ASSERT(mutex_owned(ST_MUTEX));
6470 
6471 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
6472 
6473 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
6474 		/*
6475 		 * If auto density override is not set, Use mode select
6476 		 * to set density and compression.
6477 		 */
6478 		if (st_modeselect(un)) {
6479 			rval = -1;
6480 		}
6481 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
6482 		/*
6483 		 * If auto density and mode select compression are set,
6484 		 * This is a drive with one density code but compression
6485 		 * can be enabled or disabled.
6486 		 * Set compression but no need to set density.
6487 		 */
6488 		rval = st_set_compression(un);
6489 		if ((rval != 0) && (rval != EALREADY)) {
6490 			rval = -1;
6491 		} else {
6492 			rval = 0;
6493 		}
6494 	}
6495 
6496 	/* If sucessful set density and/or compression, mark density known */
6497 	if (rval == 0) {
6498 		un->un_density_known = 1;
6499 	}
6500 
6501 	ASSERT(mutex_owned(ST_MUTEX));
6502 	return (rval);
6503 }
6504 
6505 static int
6506 st_loadtape(dev_t dev)
6507 {
6508 	int rval;
6509 
6510 	GET_SOFT_STATE(dev);
6511 
6512 	ST_FUNC(ST_DEVINFO, st_load_tape);
6513 
6514 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6515 	    "st_loadtape(dev = 0x%lx)\n", dev);
6516 
6517 	ASSERT(mutex_owned(ST_MUTEX));
6518 
6519 	/*
6520 	 * 'LOAD' the tape to BOT by rewinding
6521 	 */
6522 	rval = st_cmd(dev, SCMD_REWIND, 1, SYNC_CMD);
6523 	if (rval == 0) {
6524 		st_init(un);
6525 		un->un_density_known = 0;
6526 	}
6527 
6528 	ASSERT(mutex_owned(ST_MUTEX));
6529 	return (rval);
6530 }
6531 
6532 
6533 /*
6534  * Note: QIC devices aren't so smart.  If you try to append
6535  * after EOM, the write can fail because the device doesn't know
6536  * it's at EOM.	 In that case, issue a read.  The read should fail
6537  * because there's no data, but the device knows it's at EOM,
6538  * so a subsequent write should succeed.  To further confuse matters,
6539  * the target returns the same error if the tape is positioned
6540  * such that a write would overwrite existing data.  That's why
6541  * we have to do the append test.  A read in the middle of
6542  * recorded data would succeed, thus indicating we're attempting
6543  * something illegal.
6544  */
6545 
6546 
6547 static void
6548 st_test_append(struct buf *bp)
6549 {
6550 	dev_t dev = bp->b_edev;
6551 	struct scsi_tape *un;
6552 	uchar_t status;
6553 	unsigned bcount;
6554 
6555 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
6556 
6557 	ST_FUNC(ST_DEVINFO, st_test_append);
6558 
6559 	ASSERT(mutex_owned(ST_MUTEX));
6560 
6561 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6562 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
6563 
6564 	un->un_laststate = un->un_state;
6565 	un->un_state = ST_STATE_APPEND_TESTING;
6566 	un->un_test_append = 0;
6567 
6568 	/*
6569 	 * first, map in the buffer, because we're doing a double write --
6570 	 * first into the kernel, then onto the tape.
6571 	 */
6572 	bp_mapin(bp);
6573 
6574 	/*
6575 	 * get a copy of the data....
6576 	 */
6577 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
6578 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
6579 
6580 	/*
6581 	 * attempt the write..
6582 	 */
6583 
6584 	if (st_cmd(dev, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
6585 success:
6586 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6587 		    "append write succeeded\n");
6588 		bp->b_resid = un->un_sbufp->b_resid;
6589 		mutex_exit(ST_MUTEX);
6590 		bcount = (unsigned)bp->b_bcount;
6591 		biodone(bp);
6592 		mutex_enter(ST_MUTEX);
6593 		un->un_laststate = un->un_state;
6594 		un->un_state = ST_STATE_OPEN;
6595 		kmem_free(un->un_tmpbuf, bcount);
6596 		un->un_tmpbuf = NULL;
6597 		return;
6598 	}
6599 
6600 	/*
6601 	 * The append failed. Do a short read. If that fails,  we are at EOM
6602 	 * so we can retry the write command. If that succeeds, than we're
6603 	 * all screwed up (the controller reported a real error).
6604 	 *
6605 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
6606 	 * XXX: block size?
6607 	 *
6608 	 */
6609 	status = un->un_status;
6610 	un->un_status = 0;
6611 	(void) st_cmd(dev, SCMD_READ, SECSIZE, SYNC_CMD);
6612 	if (un->un_status == KEY_BLANK_CHECK) {
6613 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6614 		    "append at EOM\n");
6615 		/*
6616 		 * Okay- the read failed. We should actually have confused
6617 		 * the controller enough to allow writing. In any case, the
6618 		 * i/o is on its own from here on out.
6619 		 */
6620 		un->un_laststate = un->un_state;
6621 		un->un_state = ST_STATE_OPEN;
6622 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
6623 		if (st_cmd(dev, (int)SCMD_WRITE, (int)bp->b_bcount,
6624 		    SYNC_CMD) == 0) {
6625 			goto success;
6626 		}
6627 	}
6628 
6629 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6630 	    "append write failed- not at EOM\n");
6631 	bp->b_resid = bp->b_bcount;
6632 	st_bioerror(bp, EIO);
6633 
6634 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6635 	    "st_test_append : EIO : append write failed - not at EOM");
6636 
6637 	/*
6638 	 * backspace one record to get back to where we were
6639 	 */
6640 	if (st_cmd(dev, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
6641 		un->un_pos.pmode = invalid;
6642 	}
6643 
6644 	un->un_err_resid = bp->b_resid;
6645 	un->un_status = status;
6646 
6647 	/*
6648 	 * Note: biodone will do a bp_mapout()
6649 	 */
6650 	mutex_exit(ST_MUTEX);
6651 	bcount = (unsigned)bp->b_bcount;
6652 	biodone(bp);
6653 	mutex_enter(ST_MUTEX);
6654 	un->un_laststate = un->un_state;
6655 	un->un_state = ST_STATE_OPEN_PENDING_IO;
6656 	kmem_free(un->un_tmpbuf, bcount);
6657 	un->un_tmpbuf = NULL;
6658 }
6659 
6660 /*
6661  * Special command handler
6662  */
6663 
6664 /*
6665  * common st_cmd code. The fourth parameter states
6666  * whether the caller wishes to await the results
6667  * Note the release of the mutex during most of the function
6668  */
6669 static int
6670 st_cmd(dev_t dev, int com, int count, int wait)
6671 {
6672 	struct buf *bp;
6673 	int err;
6674 
6675 	GET_SOFT_STATE(dev);
6676 
6677 	ST_FUNC(ST_DEVINFO, st_cmd);
6678 
6679 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6680 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %x, wait = %d)\n",
6681 	    dev, com, count, wait);
6682 
6683 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6684 	ASSERT(mutex_owned(ST_MUTEX));
6685 
6686 #ifdef STDEBUG
6687 	if ((st_debug & 0xf)) {
6688 		st_debug_cmds(un, com, count, wait);
6689 	}
6690 #endif
6691 
6692 	/* check to see if this command requires the drive to be reserved */
6693 	err = st_check_cmd_for_need_to_reserve(un, com, count);
6694 
6695 	if (err) {
6696 		return (err);
6697 	}
6698 
6699 	while (un->un_sbuf_busy)
6700 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6701 	un->un_sbuf_busy = 1;
6702 
6703 	bp = un->un_sbufp;
6704 	bzero(bp, sizeof (buf_t));
6705 
6706 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
6707 
6708 	/*
6709 	 * Set count to the actual size of the data tranfer.
6710 	 * For commands with no data transfer, set bp->b_bcount
6711 	 * to the value to be used when constructing the
6712 	 * cdb in st_make_cmd().
6713 	 */
6714 	switch (com) {
6715 	case SCMD_READ:
6716 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6717 		    "special read %d\n", count);
6718 		bp->b_flags |= B_READ;
6719 		bp->b_un.b_addr = un->un_tmpbuf;
6720 		break;
6721 
6722 	case SCMD_WRITE:
6723 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6724 		    "special write %d\n", count);
6725 		bp->b_un.b_addr = un->un_tmpbuf;
6726 		break;
6727 
6728 	case SCMD_WRITE_FILE_MARK:
6729 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6730 		    "write %d file marks\n", count);
6731 		bp->b_bcount = count;
6732 		count = 0;
6733 		break;
6734 
6735 	case SCMD_REWIND:
6736 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
6737 		bp->b_bcount = 0;
6738 		count = 0;
6739 		break;
6740 
6741 	case SCMD_SPACE:
6742 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
6743 		/*
6744 		 * XXX The user could have entered a number that will
6745 		 * not fit in the 12 bit count field. Whats new here
6746 		 * checking that. Down the road this should use space(16).
6747 		 */
6748 		if ((SPACE_CNT(count) > 0x7fffff) ||
6749 		    (SPACE_CNT(count) < -(0x7fffff))) {
6750 			un->un_sbuf_busy = 0;
6751 			cv_signal(&un->un_sbuf_cv);
6752 			return (EINVAL);
6753 		}
6754 		bp->b_bcount = count;
6755 		count = 0;
6756 		break;
6757 
6758 	case SCMD_RESERVE:
6759 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
6760 		bp->b_bcount = 0;
6761 		count = 0;
6762 		break;
6763 
6764 	case SCMD_RELEASE:
6765 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
6766 		bp->b_bcount = 0;
6767 		count = 0;
6768 		break;
6769 
6770 	case SCMD_LOAD:
6771 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6772 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
6773 		bp->b_bcount = count;
6774 		count = 0;
6775 		break;
6776 
6777 	case SCMD_ERASE:
6778 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6779 		    "erase tape\n");
6780 		bp->b_bcount = 0;
6781 		count = 0;
6782 		break;
6783 
6784 	case SCMD_MODE_SENSE:
6785 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6786 		    "mode sense\n");
6787 		bp->b_flags |= B_READ;
6788 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
6789 		break;
6790 
6791 	case SCMD_MODE_SELECT:
6792 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6793 		    "mode select\n");
6794 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
6795 		break;
6796 
6797 	case SCMD_READ_BLKLIM:
6798 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6799 		    "read block limits\n");
6800 		bp->b_flags |= B_READ;
6801 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
6802 		break;
6803 
6804 	case SCMD_TEST_UNIT_READY:
6805 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6806 		    "test unit ready\n");
6807 		bp->b_bcount = 0;
6808 		count = 0;
6809 		break;
6810 
6811 	case SCMD_DOORLOCK:
6812 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6813 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
6814 		bp->b_bcount = count = 0;
6815 		break;
6816 
6817 	case SCMD_READ_POSITION:
6818 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6819 		    "read position\n");
6820 		switch (un->un_read_pos_type) {
6821 		case LONG_POS:
6822 			count = sizeof (tape_position_long_t);
6823 			break;
6824 		case EXT_POS:
6825 			count = min(count, sizeof (tape_position_ext_t));
6826 			break;
6827 		case SHORT_POS:
6828 			count = sizeof (tape_position_t);
6829 			break;
6830 		default:
6831 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
6832 			    "Unknown read position type 0x%x in "
6833 			    "st_make_cmd()\n", un->un_read_pos_type);
6834 		}
6835 		bp->b_bcount = count;
6836 		bp->b_flags |= B_READ;
6837 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
6838 		break;
6839 
6840 	default:
6841 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
6842 		    "Unhandled scsi command 0x%x in st_cmd()\n", com);
6843 	}
6844 
6845 	mutex_exit(ST_MUTEX);
6846 
6847 	if (count > 0) {
6848 		/*
6849 		 * We're going to do actual I/O.
6850 		 * Set things up for physio.
6851 		 */
6852 		struct iovec aiov;
6853 		struct uio auio;
6854 		struct uio *uio = &auio;
6855 
6856 		bzero(&auio, sizeof (struct uio));
6857 		bzero(&aiov, sizeof (struct iovec));
6858 		aiov.iov_base = bp->b_un.b_addr;
6859 		aiov.iov_len = count;
6860 
6861 		uio->uio_iov = &aiov;
6862 		uio->uio_iovcnt = 1;
6863 		uio->uio_resid = aiov.iov_len;
6864 		uio->uio_segflg = UIO_SYSSPACE;
6865 
6866 		/*
6867 		 * Let physio do the rest...
6868 		 */
6869 		bp->b_forw = (struct buf *)(uintptr_t)com;
6870 		bp->b_back = NULL;
6871 		err = physio(st_strategy, bp, dev,
6872 		    (bp->b_flags & B_READ) ? B_READ : B_WRITE,
6873 		    st_minphys, uio);
6874 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6875 		    "st_cmd: physio returns %d\n", err);
6876 	} else {
6877 		/*
6878 		 * Mimic physio
6879 		 */
6880 		bp->b_forw = (struct buf *)(uintptr_t)com;
6881 		bp->b_back = NULL;
6882 		bp->b_edev = dev;
6883 		bp->b_dev = cmpdev(dev);
6884 		bp->b_blkno = 0;
6885 		bp->b_resid = 0;
6886 		(void) st_strategy(bp);
6887 		if (!wait) {
6888 			/*
6889 			 * This is an async command- the caller won't wait
6890 			 * and doesn't care about errors.
6891 			 */
6892 			mutex_enter(ST_MUTEX);
6893 			return (0);
6894 		}
6895 
6896 		/*
6897 		 * BugTraq #4260046
6898 		 * ----------------
6899 		 * Restore Solaris 2.5.1 behavior, namely call biowait
6900 		 * unconditionally. The old comment said...
6901 		 *
6902 		 * "if strategy was flagged with  persistent errors, we would
6903 		 *  have an error here, and the bp would never be sent, so we
6904 		 *  don't want to wait on a bp that was never sent...or hang"
6905 		 *
6906 		 * The new rationale, courtesy of Chitrank...
6907 		 *
6908 		 * "we should unconditionally biowait() here because
6909 		 *  st_strategy() will do a biodone() in the persistent error
6910 		 *  case and the following biowait() will return immediately.
6911 		 *  If not, in the case of "errors after pkt alloc" in
6912 		 *  st_start(), we will not biowait here which will cause the
6913 		 *  next biowait() to return immediately which will cause
6914 		 *  us to send out the next command. In the case where both of
6915 		 *  these use the sbuf, when the first command completes we'll
6916 		 *  free the packet attached to sbuf and the same pkt will
6917 		 *  get freed again when we complete the second command.
6918 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
6919 		 *  st_start() for the pkt alloc failure case because physio()
6920 		 *  does biowait() and will hang if we don't do biodone()"
6921 		 */
6922 
6923 		err = biowait(bp);
6924 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6925 		    "st_cmd: biowait returns %d\n", err);
6926 	}
6927 	mutex_enter(ST_MUTEX);
6928 
6929 	un->un_sbuf_busy = 0;
6930 
6931 	/*
6932 	 * If was a space command need to update logical block position.
6933 	 * If the command failed such that positioning is invalid, Don't
6934 	 * update the position as the user must do this to validate the
6935 	 * position for data protection.
6936 	 */
6937 	if ((com == SCMD_SPACE) && (un->un_pos.pmode != invalid)) {
6938 		uchar_t status = un->un_status;
6939 		(void) st_update_block_pos(un);
6940 		un->un_status = status;
6941 	}
6942 
6943 	cv_signal(&un->un_sbuf_cv);
6944 	return (err);
6945 }
6946 
6947 static int
6948 st_set_compression(struct scsi_tape *un)
6949 {
6950 	int rval;
6951 	int turn_compression_on;
6952 	minor_t minor;
6953 
6954 	ST_FUNC(ST_DEVINFO, st_set_compression);
6955 
6956 	/*
6957 	 * Drive either dosn't have compression or it is controlled with
6958 	 * special density codes. Return ENOTTY so caller
6959 	 * knows nothing was done.
6960 	 */
6961 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
6962 		un->un_comp_page = 0;
6963 		return (ENOTTY);
6964 	}
6965 
6966 	/* set compression based on minor node opened */
6967 	minor = MT_DENSITY(un->un_dev);
6968 
6969 	/*
6970 	 * If this the compression density or
6971 	 * the drive has two densities and uses mode select for
6972 	 * control of compression turn on compression for MT_DENSITY2
6973 	 * as well.
6974 	 */
6975 	if ((minor == ST_COMPRESSION_DENSITY) ||
6976 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
6977 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
6978 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
6979 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
6980 
6981 		turn_compression_on = 1;
6982 	} else {
6983 		turn_compression_on = 0;
6984 	}
6985 
6986 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
6987 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
6988 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
6989 
6990 	/*
6991 	 * Need to determine which page does the device use for compression.
6992 	 * First try the data compression page. If this fails try the device
6993 	 * configuration page
6994 	 */
6995 
6996 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
6997 		rval = st_set_datacomp_page(un, turn_compression_on);
6998 		if (rval == EALREADY) {
6999 			return (rval);
7000 		}
7001 		if (rval != 0) {
7002 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7003 				/*
7004 				 * This device does not support data
7005 				 * compression page
7006 				 */
7007 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7008 			} else if (un->un_state >= ST_STATE_OPEN) {
7009 				un->un_pos.pmode = invalid;
7010 				rval = EIO;
7011 			} else {
7012 				rval = -1;
7013 			}
7014 		} else {
7015 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7016 		}
7017 	}
7018 
7019 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7020 		rval = st_set_devconfig_page(un, turn_compression_on);
7021 		if (rval == EALREADY) {
7022 			return (rval);
7023 		}
7024 		if (rval != 0) {
7025 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7026 				/*
7027 				 * This device does not support
7028 				 * compression at all advice the
7029 				 * user and unset ST_MODE_SEL_COMP
7030 				 */
7031 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7032 				un->un_comp_page = 0;
7033 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7034 				    "Device Does Not Support Compression\n");
7035 			} else if (un->un_state >= ST_STATE_OPEN) {
7036 				un->un_pos.pmode = invalid;
7037 				rval = EIO;
7038 			} else {
7039 				rval = -1;
7040 			}
7041 		}
7042 	}
7043 
7044 	return (rval);
7045 }
7046 
7047 /*
7048  * set or unset compression thru device configuration page.
7049  */
7050 static int
7051 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
7052 {
7053 	unsigned char cflag;
7054 	int rval = 0;
7055 
7056 
7057 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
7058 
7059 	ASSERT(mutex_owned(ST_MUTEX));
7060 	/*
7061 	 * Figure what to set compression flag to.
7062 	 */
7063 	if (compression_on) {
7064 		/* They have selected a compression node */
7065 		if (un->un_dp->type == ST_TYPE_FUJI) {
7066 			cflag = 0x84;   /* use EDRC */
7067 		} else {
7068 			cflag = ST_DEV_CONFIG_DEF_COMP;
7069 		}
7070 	} else {
7071 		cflag = ST_DEV_CONFIG_NO_COMP;
7072 	}
7073 
7074 	/*
7075 	 * If compression is already set the way it was requested.
7076 	 * And if this not the first time we has tried.
7077 	 */
7078 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
7079 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7080 		return (EALREADY);
7081 	}
7082 
7083 	un->un_mspl->page.dev.comp_alg = cflag;
7084 	/*
7085 	 * need to send mode select even if correct compression is
7086 	 * already set since need to set density code
7087 	 */
7088 
7089 #ifdef STDEBUG
7090 	if ((st_debug & 0xf) >= 6) {
7091 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7092 		    "st_set_devconfig_page: sense data for mode select",
7093 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7094 	}
7095 #endif
7096 	rval = st_gen_mode_select(un, un->un_mspl, sizeof (struct seq_mode));
7097 
7098 	return (rval);
7099 }
7100 
7101 /*
7102  * set/reset compression bit thru data compression page
7103  */
7104 static int
7105 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
7106 {
7107 	int compression_on_already;
7108 	int rval = 0;
7109 
7110 
7111 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
7112 
7113 	ASSERT(mutex_owned(ST_MUTEX));
7114 	/*
7115 	 * If drive is not capable of compression (at this time)
7116 	 * return EALREADY so caller doesn't think that this page
7117 	 * is not supported. This check is for drives that can
7118 	 * disable compression from the front panel or configuration.
7119 	 * I doubt that a drive that supports this page is not really
7120 	 * capable of compression.
7121 	 */
7122 	if (un->un_mspl->page.comp.dcc == 0) {
7123 		return (EALREADY);
7124 	}
7125 
7126 	/* See if compression currently turned on */
7127 	if (un->un_mspl->page.comp.dce) {
7128 		compression_on_already = 1;
7129 	} else {
7130 		compression_on_already = 0;
7131 	}
7132 
7133 	/*
7134 	 * If compression is already set the way it was requested.
7135 	 * And if this not the first time we has tried.
7136 	 */
7137 	if ((compression_on == compression_on_already) &&
7138 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7139 		return (EALREADY);
7140 	}
7141 
7142 	/*
7143 	 * if we are already set to the appropriate compression
7144 	 * mode, don't set it again
7145 	 */
7146 	if (compression_on) {
7147 		/* compression selected */
7148 		un->un_mspl->page.comp.dce = 1;
7149 	} else {
7150 		un->un_mspl->page.comp.dce = 0;
7151 	}
7152 
7153 
7154 #ifdef STDEBUG
7155 	if ((st_debug & 0xf) >= 6) {
7156 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7157 		    "st_set_datacomp_page: sense data for mode select",
7158 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7159 	}
7160 #endif
7161 	rval = st_gen_mode_select(un, un->un_mspl, sizeof (struct seq_mode));
7162 
7163 	return (rval);
7164 }
7165 
7166 static int
7167 st_modesense(struct scsi_tape *un)
7168 {
7169 	int rval;
7170 	uchar_t page;
7171 
7172 	ST_FUNC(ST_DEVINFO, st_modesense);
7173 
7174 	page = un->un_comp_page;
7175 
7176 	switch (page) {
7177 	case ST_DEV_DATACOMP_PAGE:
7178 	case ST_DEV_CONFIG_PAGE: /* fall through */
7179 		rval = st_gen_mode_sense(un, page, un->un_mspl,
7180 		    sizeof (struct seq_mode));
7181 		break;
7182 
7183 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
7184 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
7185 			page = ST_DEV_DATACOMP_PAGE;
7186 			rval = st_gen_mode_sense(un, page, un->un_mspl,
7187 			    sizeof (struct seq_mode));
7188 			if (rval == 0 && un->un_mspl->page_code == page) {
7189 				un->un_comp_page = page;
7190 				break;
7191 			}
7192 			page = ST_DEV_CONFIG_PAGE;
7193 			rval = st_gen_mode_sense(un, page, un->un_mspl,
7194 			    sizeof (struct seq_mode));
7195 			if (rval == 0 && un->un_mspl->page_code == page) {
7196 				un->un_comp_page = page;
7197 				break;
7198 			}
7199 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
7200 			un->un_comp_page = 0;
7201 		} else {
7202 			un->un_comp_page = 0;
7203 		}
7204 
7205 	default:	/* fall through */
7206 		rval = st_cmd(un->un_dev, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
7207 	}
7208 	return (rval);
7209 }
7210 
7211 static int
7212 st_modeselect(struct scsi_tape *un)
7213 {
7214 	int rval = 0;
7215 	int ix;
7216 
7217 	ST_FUNC(ST_DEVINFO, st_modeselect);
7218 
7219 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7220 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
7221 	    un->un_dev, un->un_mspl->density);
7222 
7223 	ASSERT(mutex_owned(ST_MUTEX));
7224 
7225 	/*
7226 	 * The parameter list should be the same for all of the
7227 	 * cases that follow so set them here
7228 	 *
7229 	 * Try mode select first if if fails set fields manually
7230 	 */
7231 	rval = st_modesense(un);
7232 	if (rval != 0) {
7233 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
7234 		    "st_modeselect: First mode sense failed\n");
7235 		un->un_mspl->bd_len  = 8;
7236 		un->un_mspl->high_nb = 0;
7237 		un->un_mspl->mid_nb  = 0;
7238 		un->un_mspl->low_nb  = 0;
7239 	}
7240 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7241 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7242 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7243 
7244 
7245 	/*
7246 	 * If configured to use a specific density code for a media type.
7247 	 * curdens is previously set by the minor node opened.
7248 	 * If the media type doesn't match the minor node we change it so it
7249 	 * looks like the correct one was opened.
7250 	 */
7251 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
7252 		uchar_t best;
7253 
7254 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
7255 			if (un->un_mspl->media_type ==
7256 			    un->un_dp->mediatype[ix]) {
7257 				best = ix;
7258 				/*
7259 				 * It matches but it might not be the only one.
7260 				 * Use the highest matching media type but not
7261 				 * to exceed the density selected by the open.
7262 				 */
7263 				if (ix < un->un_curdens) {
7264 					continue;
7265 				}
7266 				un->un_curdens = ix;
7267 				break;
7268 			}
7269 		}
7270 		/* If a match was found best will not be 0xff any more */
7271 		if (best < NDENSITIES) {
7272 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
7273 			    "found media 0x%X using density 0x%X\n",
7274 			    un->un_mspl->media_type,
7275 			    un->un_dp->densities[best]);
7276 			un->un_mspl->density = un->un_dp->densities[best];
7277 		} else {
7278 			/* Otherwise set density based on minor node opened */
7279 			un->un_mspl->density =
7280 			    un->un_dp->densities[un->un_curdens];
7281 		}
7282 	} else {
7283 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7284 	}
7285 
7286 	if (un->un_dp->options & ST_NOBUF) {
7287 		un->un_mspl->bufm = 0;
7288 	} else {
7289 		un->un_mspl->bufm = 1;
7290 	}
7291 
7292 	rval = st_set_compression(un);
7293 
7294 	/*
7295 	 * If st_set_compression returned invalid or already it
7296 	 * found no need to do the mode select.
7297 	 * So do it here.
7298 	 */
7299 	if ((rval == ENOTTY) || (rval == EALREADY)) {
7300 
7301 		/* Zero non-writeable fields */
7302 		un->un_mspl->data_len = 0;
7303 		un->un_mspl->media_type = 0;
7304 		un->un_mspl->wp = 0;
7305 
7306 		/* need to set the density code */
7307 		rval = st_cmd(un->un_dev, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
7308 		if (rval != 0) {
7309 			if (un->un_state >= ST_STATE_OPEN) {
7310 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7311 				    "unable to set tape mode\n");
7312 				un->un_pos.pmode = invalid;
7313 				rval = EIO;
7314 			} else {
7315 				rval = -1;
7316 			}
7317 		}
7318 	}
7319 
7320 	/*
7321 	 * The spec recommends to send a mode sense after a mode select
7322 	 */
7323 	(void) st_modesense(un);
7324 
7325 	ASSERT(mutex_owned(ST_MUTEX));
7326 
7327 	return (rval);
7328 }
7329 
7330 /*
7331  * st_gen_mode_sense
7332  *
7333  * generic mode sense.. it allows for any page
7334  */
7335 static int
7336 st_gen_mode_sense(struct scsi_tape *un, int page, struct seq_mode *page_data,
7337     int page_size)
7338 {
7339 
7340 	int r;
7341 	char	cdb[CDB_GROUP0];
7342 	struct uscsi_cmd *com;
7343 
7344 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
7345 
7346 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7347 
7348 	bzero(cdb, CDB_GROUP0);
7349 	cdb[0] = SCMD_MODE_SENSE;
7350 	cdb[2] = (char)page;
7351 	cdb[4] = (char)page_size;
7352 
7353 	com->uscsi_cdb = cdb;
7354 	com->uscsi_cdblen = CDB_GROUP0;
7355 	com->uscsi_bufaddr = (caddr_t)page_data;
7356 	com->uscsi_buflen = page_size;
7357 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7358 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
7359 
7360 	r = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
7361 	kmem_free(com, sizeof (*com));
7362 	return (r);
7363 }
7364 
7365 /*
7366  * st_gen_mode_select
7367  *
7368  * generic mode select.. it allows for any page
7369  */
7370 static int
7371 st_gen_mode_select(struct scsi_tape *un, struct seq_mode *page_data,
7372     int page_size)
7373 {
7374 
7375 	int r;
7376 	char cdb[CDB_GROUP0];
7377 	struct uscsi_cmd *com;
7378 
7379 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
7380 
7381 	/* Zero non-writeable fields */
7382 	page_data->data_len = 0;
7383 	page_data->media_type = 0;
7384 	page_data->wp = 0;
7385 
7386 	/*
7387 	 * If mode select has any page data, zero the ps (Page Savable) bit.
7388 	 */
7389 	if (page_size > MSIZE) {
7390 		page_data->ps = 0;
7391 	}
7392 
7393 
7394 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7395 
7396 	/*
7397 	 * then, do a mode select to set what ever info
7398 	 */
7399 	bzero(cdb, CDB_GROUP0);
7400 	cdb[0] = SCMD_MODE_SELECT;
7401 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
7402 	cdb[4] = (char)page_size;
7403 
7404 	com->uscsi_cdb = cdb;
7405 	com->uscsi_cdblen = CDB_GROUP0;
7406 	com->uscsi_bufaddr = (caddr_t)page_data;
7407 	com->uscsi_buflen = page_size;
7408 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7409 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_WRITE;
7410 
7411 	r = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
7412 
7413 	kmem_free(com, sizeof (*com));
7414 	return (r);
7415 }
7416 
7417 /*
7418  * Changes devices blocksize and bsize to requested blocksize nblksz.
7419  * Returns returned value from first failed call or zero on success.
7420  */
7421 static int
7422 st_change_block_size(dev_t dev, uint32_t nblksz)
7423 {
7424 	struct seq_mode *current;
7425 	int rval;
7426 	uint32_t oldblksz;
7427 
7428 	GET_SOFT_STATE(dev);
7429 
7430 	ST_FUNC(ST_DEVINFO, st_change_block_size);
7431 
7432 	current = kmem_zalloc(MSIZE, KM_SLEEP);
7433 
7434 	/* Read current settings */
7435 	rval = st_gen_mode_sense(un, 0, current, MSIZE);
7436 	if (rval != 0) {
7437 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7438 		    "mode sense for change block size failed: rval = %d", rval);
7439 		goto finish;
7440 	}
7441 
7442 	/* Figure the current block size */
7443 	oldblksz =
7444 	    (current->high_bl << 16) |
7445 	    (current->mid_bl << 8) |
7446 	    (current->low_bl);
7447 
7448 	/* If current block size is the same as requested were done */
7449 	if (oldblksz == nblksz) {
7450 		un->un_bsize = nblksz;
7451 		rval = 0;
7452 		goto finish;
7453 	}
7454 
7455 	/* Change to requested block size */
7456 	current->high_bl = (uchar_t)(nblksz >> 16);
7457 	current->mid_bl  = (uchar_t)(nblksz >> 8);
7458 	current->low_bl  = (uchar_t)(nblksz);
7459 
7460 	/* Attempt to change block size */
7461 	rval = st_gen_mode_select(un, current, MSIZE);
7462 	if (rval != 0) {
7463 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7464 		    "Set new block size failed: rval = %d", rval);
7465 		goto finish;
7466 	}
7467 
7468 	/* Read back and verify setting */
7469 	rval = st_modesense(un);
7470 	if (rval == 0) {
7471 		un->un_bsize =
7472 		    (un->un_mspl->high_bl << 16) |
7473 		    (un->un_mspl->mid_bl << 8) |
7474 		    (un->un_mspl->low_bl);
7475 
7476 		if (un->un_bsize != nblksz) {
7477 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7478 			    "Blocksize set does not equal requested blocksize"
7479 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
7480 			rval = EIO;
7481 		}
7482 	}
7483 finish:
7484 	kmem_free(current, MSIZE);
7485 	return (rval);
7486 }
7487 
7488 
7489 static void
7490 st_init(struct scsi_tape *un)
7491 {
7492 	ST_FUNC(ST_DEVINFO, st_init);
7493 
7494 	ASSERT(mutex_owned(ST_MUTEX));
7495 
7496 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7497 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
7498 	    un->un_dev);
7499 
7500 	un->un_pos.blkno = 0;
7501 	un->un_pos.fileno = 0;
7502 	un->un_lastop = ST_OP_NIL;
7503 	un->un_pos.eof = ST_NO_EOF;
7504 	un->un_pwr_mgmt = ST_PWR_NORMAL;
7505 	if (st_error_level != SCSI_ERR_ALL) {
7506 		if (DEBUGGING) {
7507 			st_error_level = SCSI_ERR_ALL;
7508 		} else {
7509 			st_error_level = SCSI_ERR_RETRYABLE;
7510 		}
7511 	}
7512 }
7513 
7514 
7515 static void
7516 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
7517 {
7518 	struct scsi_pkt *pkt;
7519 	struct uscsi_cmd *ucmd;
7520 	int count, tval = 0;
7521 	uint_t addr = 0;
7522 	int flags = 0;
7523 	int cdb_len = CDB_GROUP0; /* default */
7524 	uchar_t com;
7525 	char fixbit;
7526 
7527 	ST_FUNC(ST_DEVINFO, st_make_cmd);
7528 
7529 	ASSERT(mutex_owned(ST_MUTEX));
7530 
7531 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7532 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
7533 
7534 
7535 	/*
7536 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
7537 	 * Length Indicator bits on read/write commands, for setting
7538 	 * the Long bit on erase commands, and for setting the Code
7539 	 * Field bits on space commands.
7540 	 * XXX why do we set lastop here?
7541 	 */
7542 
7543 	if (bp != un->un_sbufp) {		/* regular raw I/O */
7544 		int stat_size = (un->un_arq_enabled ?
7545 		    sizeof (struct scsi_arq_status) : 1);
7546 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
7547 		    CDB_GROUP0, stat_size, 0, 0, func, (caddr_t)un);
7548 		if (pkt == NULL) {
7549 			goto exit;
7550 		}
7551 		SET_BP_PKT(bp, pkt);
7552 		if (un->un_bsize == 0) {
7553 			count = bp->b_bcount;
7554 			fixbit = 0;
7555 		} else {
7556 			count = bp->b_bcount / un->un_bsize;
7557 			fixbit = 1;
7558 		}
7559 		if (bp->b_flags & B_READ) {
7560 			com = SCMD_READ;
7561 			un->un_lastop = ST_OP_READ;
7562 			if ((un->un_bsize == 0) && /* Not Fixed Block */
7563 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
7564 				fixbit = 2;
7565 			}
7566 		} else {
7567 			com = SCMD_WRITE;
7568 			un->un_lastop = ST_OP_WRITE;
7569 		}
7570 
7571 		tval = un->un_dp->io_timeout;
7572 
7573 		/*
7574 		 * For really large xfers, increase timeout
7575 		 */
7576 		if (bp->b_bcount > (10 * ONE_MEG))
7577 			tval *= bp->b_bcount/(10 * ONE_MEG);
7578 
7579 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7580 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
7581 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
7582 
7583 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
7584 		/*
7585 		 * uscsi - build command, allocate scsi resources
7586 		 */
7587 		st_make_uscsi_cmd(un, ucmd, bp, func);
7588 		goto exit;
7589 
7590 	} else {				/* special I/O */
7591 		int stat_size = (un->un_arq_enabled ?
7592 		    sizeof (struct scsi_arq_status) : 1);
7593 		struct buf *allocbp = NULL;
7594 		com = (uchar_t)(uintptr_t)bp->b_forw;
7595 		count = bp->b_bcount;
7596 
7597 		switch (com) {
7598 		case SCMD_READ:
7599 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7600 			    "special read %d\n", count);
7601 			if (un->un_bsize == 0) {
7602 				fixbit = 2;	/* suppress SILI */
7603 			} else {
7604 				fixbit = 1;	/* Fixed Block Mode */
7605 				count /= un->un_bsize;
7606 			}
7607 			allocbp = bp;
7608 			un->un_lastop = ST_OP_READ;
7609 			tval = un->un_dp->io_timeout;
7610 			break;
7611 
7612 		case SCMD_WRITE:
7613 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7614 			    "special write %d\n", count);
7615 			if (un->un_bsize != 0) {
7616 				fixbit = 1;	/* Fixed Block Mode */
7617 				count /= un->un_bsize;
7618 			} else {
7619 				fixbit = 0;
7620 			}
7621 			allocbp = bp;
7622 			un->un_lastop = ST_OP_WRITE;
7623 			tval = un->un_dp->io_timeout;
7624 			break;
7625 
7626 		case SCMD_WRITE_FILE_MARK:
7627 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7628 			    "write %d file marks\n", count);
7629 			un->un_lastop = ST_OP_WEOF;
7630 			fixbit = 0;
7631 			tval = un->un_dp->io_timeout;
7632 			break;
7633 
7634 		case SCMD_REWIND:
7635 			if (bp->b_flags & B_ASYNC) {
7636 				fixbit = 1;
7637 			} else {
7638 				fixbit = 0;
7639 			}
7640 			count = 0;
7641 			un->un_lastop = ST_OP_CTL;
7642 			tval = un->un_dp->rewind_timeout;
7643 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7644 			    "rewind\n");
7645 			break;
7646 
7647 		case SCMD_SPACE:
7648 			fixbit = SPACE_TYPE(count);
7649 			count = (int)SPACE_CNT(count);
7650 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7651 			    "space %s %d from file %d blk %d\n",
7652 			    space_strs[fixbit & 7], count,
7653 			    un->un_pos.fileno, un->un_pos.blkno);
7654 			un->un_lastop = ST_OP_CTL;
7655 			tval = un->un_dp->space_timeout;
7656 			break;
7657 
7658 		case SCMD_LOAD:
7659 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7660 			    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7661 			fixbit = 0;
7662 
7663 			/* Loading or Unloading */
7664 			if (count & LD_LOAD) {
7665 				tval = un->un_dp->load_timeout;
7666 			} else {
7667 				tval = un->un_dp->unload_timeout;
7668 			}
7669 			/* Is Retension requested */
7670 			if (count & LD_RETEN) {
7671 				tval += un->un_dp->rewind_timeout;
7672 			}
7673 			un->un_lastop = ST_OP_CTL;
7674 			break;
7675 
7676 		case SCMD_ERASE:
7677 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7678 			    "erase tape\n");
7679 			count = 0;
7680 			/*
7681 			 * We support long erase only
7682 			 */
7683 			fixbit = 1;
7684 			tval = un->un_dp->erase_timeout;
7685 			un->un_lastop = ST_OP_CTL;
7686 			break;
7687 
7688 		case SCMD_MODE_SENSE:
7689 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7690 			    "mode sense\n");
7691 			allocbp = bp;
7692 			fixbit = 0;
7693 			tval = un->un_dp->non_motion_timeout;
7694 			un->un_lastop = ST_OP_CTL;
7695 			break;
7696 
7697 		case SCMD_MODE_SELECT:
7698 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7699 			    "mode select\n");
7700 			allocbp = bp;
7701 			fixbit = 0;
7702 			tval = un->un_dp->non_motion_timeout;
7703 			un->un_lastop = ST_OP_CTL;
7704 			break;
7705 
7706 		case SCMD_RESERVE:
7707 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7708 			    "reserve\n");
7709 			fixbit = 0;
7710 			tval = un->un_dp->non_motion_timeout;
7711 			un->un_lastop = ST_OP_CTL;
7712 			break;
7713 
7714 		case SCMD_RELEASE:
7715 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7716 			    "release\n");
7717 			fixbit = 0;
7718 			tval = un->un_dp->non_motion_timeout;
7719 			un->un_lastop = ST_OP_CTL;
7720 			break;
7721 
7722 		case SCMD_READ_BLKLIM:
7723 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7724 			    "read block limits\n");
7725 			allocbp = bp;
7726 			fixbit = count = 0;
7727 			tval = un->un_dp->non_motion_timeout;
7728 			un->un_lastop = ST_OP_CTL;
7729 			break;
7730 
7731 		case SCMD_TEST_UNIT_READY:
7732 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7733 			    "test unit ready\n");
7734 			fixbit = 0;
7735 			tval = un->un_dp->non_motion_timeout;
7736 			un->un_lastop = ST_OP_CTL;
7737 			break;
7738 
7739 		case SCMD_DOORLOCK:
7740 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7741 			    "prevent/allow media removal\n");
7742 			fixbit = 0;
7743 			tval = un->un_dp->non_motion_timeout;
7744 			un->un_lastop = ST_OP_CTL;
7745 			break;
7746 
7747 		case SCMD_READ_POSITION:
7748 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7749 			    "read position\n");
7750 			fixbit = un->un_read_pos_type;
7751 			cdb_len = CDB_GROUP1;
7752 			tval = un->un_dp->non_motion_timeout;
7753 			allocbp = bp;
7754 			un->un_lastop = ST_OP_CTL;
7755 			switch (un->un_read_pos_type) {
7756 			case LONG_POS:
7757 				count = 0;
7758 				break;
7759 			case EXT_POS:
7760 				count = sizeof (tape_position_ext_t);
7761 				break;
7762 			case SHORT_POS:
7763 				count = 0;
7764 				break;
7765 			default:
7766 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7767 				    "Unknown read position type 0x%x in "
7768 				    " st_make_cmd()\n", un->un_read_pos_type);
7769 			}
7770 			break;
7771 
7772 		default:
7773 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7774 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
7775 			    com);
7776 		}
7777 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
7778 		    0, 0, func, (caddr_t)un);
7779 		if (pkt == NULL) {
7780 			goto exit;
7781 		}
7782 		if (allocbp) {
7783 			ASSERT(geterror(allocbp) == 0);
7784 		}
7785 
7786 	}
7787 
7788 
7789 	(void) scsi_setup_cdb((union scsi_cdb *)pkt->pkt_cdbp,
7790 	    com, addr, (uint_t)count, 0);
7791 	FILL_SCSI1_LUN(un->un_sd, pkt);
7792 	/*
7793 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
7794 	 */
7795 	((union scsi_cdb *)(pkt->pkt_cdbp))->t_code = fixbit;
7796 	pkt->pkt_flags = flags;
7797 
7798 #ifdef STDEBUG
7799 	if ((st_debug & 0xf) >= 6) {
7800 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7801 		    "cmd cdb", (char *)pkt->pkt_cdbp, cdb_len);
7802 	}
7803 #endif
7804 
7805 	/*
7806 	 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
7807 	 * device, set the Vendor Unique bit to
7808 	 * write Short File Mark.
7809 	 */
7810 	if (com == SCMD_WRITE_FILE_MARK &&
7811 	    un->un_dp->options & ST_SHORT_FILEMARKS) {
7812 		switch (un->un_dp->type) {
7813 		case ST_TYPE_EXB8500:
7814 		case ST_TYPE_EXABYTE:
7815 			/*
7816 			 * Now the Vendor Unique bit 7 in Byte 5 of CDB
7817 			 * is set to to write Short File Mark
7818 			 */
7819 			((union scsi_cdb *)pkt->pkt_cdbp)->g0_vu_1 = 1;
7820 			break;
7821 
7822 		default:
7823 			/*
7824 			 * Well, if ST_SHORT_FILEMARKS is set for other
7825 			 * tape drives, it is just ignored
7826 			 */
7827 			break;
7828 		}
7829 	}
7830 	ASSERT(tval);
7831 	pkt->pkt_time = tval;
7832 	pkt->pkt_comp = st_intr;
7833 	pkt->pkt_private = (opaque_t)bp;
7834 
7835 	SET_BP_PKT(bp, pkt);
7836 
7837 exit:
7838 	ASSERT(mutex_owned(ST_MUTEX));
7839 }
7840 
7841 
7842 /*
7843  * Build a command based on a uscsi command;
7844  */
7845 static void
7846 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
7847     struct buf *bp, int (*func)(caddr_t))
7848 {
7849 	struct scsi_pkt *pkt;
7850 	caddr_t cdb;
7851 	int	cdblen;
7852 	int stat_size;
7853 
7854 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
7855 
7856 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7857 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
7858 
7859 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
7860 		stat_size = (un->un_arq_enabled ?
7861 		    sizeof (struct scsi_arq_status) : 1);
7862 	} else {
7863 		stat_size = 1;
7864 	}
7865 
7866 	ASSERT(mutex_owned(ST_MUTEX));
7867 
7868 	cdb = ucmd->uscsi_cdb;
7869 	cdblen = ucmd->uscsi_cdblen;
7870 
7871 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7872 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
7873 	    ucmd->uscsi_buflen, bp->b_bcount);
7874 	pkt = scsi_init_pkt(ROUTE, NULL,
7875 	    (bp->b_bcount > 0) ? bp : NULL,
7876 	    cdblen, stat_size, 0, 0, func, (caddr_t)un);
7877 	if (pkt == NULL) {
7878 		goto exit;
7879 	}
7880 
7881 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
7882 
7883 #ifdef STDEBUG
7884 	if ((st_debug & 0xf) >= 6) {
7885 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7886 		    "pkt_cdbp", (char *)cdb, cdblen);
7887 	}
7888 #endif
7889 
7890 	if (ucmd->uscsi_flags & USCSI_SILENT) {
7891 		pkt->pkt_flags |= FLAG_SILENT;
7892 	}
7893 
7894 	pkt->pkt_time = ucmd->uscsi_timeout;
7895 	pkt->pkt_comp = st_intr;
7896 	pkt->pkt_private = (opaque_t)bp;
7897 
7898 	SET_BP_PKT(bp, pkt);
7899 exit:
7900 	ASSERT(mutex_owned(ST_MUTEX));
7901 }
7902 
7903 
7904 /*
7905  * restart cmd currently at the head of the runq
7906  *
7907  * If scsi_transport() succeeds or the retries
7908  * count exhausted, restore the throttle that was
7909  * zeroed out in st_handle_intr_busy().
7910  *
7911  */
7912 static void
7913 st_intr_restart(void *arg)
7914 {
7915 	struct scsi_tape *un = arg;
7916 	struct buf *bp;
7917 	int status = TRAN_ACCEPT;
7918 
7919 	mutex_enter(ST_MUTEX);
7920 
7921 	ST_FUNC(ST_DEVINFO, st_intr_restart);
7922 
7923 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7924 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
7925 
7926 	un->un_hib_tid = 0;
7927 
7928 	/*
7929 	 * move from waitq to runq, if there is anything on the waitq
7930 	 */
7931 	if ((bp = un->un_quef) == NULL) {
7932 		mutex_exit(ST_MUTEX);
7933 		return;
7934 	}
7935 
7936 	/*
7937 	 * Here we know :
7938 	 *	throttle = 0, via st_handle_intr_busy
7939 	 */
7940 
7941 	if (un->un_quel == bp) {
7942 		un->un_quel = NULL;
7943 		un->un_quef = NULL;	/* we know it's the first one */
7944 	} else {
7945 		un->un_quef = bp->b_actf;
7946 	}
7947 	bp->b_actf = NULL;
7948 
7949 	if (un->un_runqf) {
7950 		/*
7951 		 * not good, we don't want to requeue something after
7952 		 * another.
7953 		 */
7954 		mutex_exit(ST_MUTEX);
7955 		goto done_error;
7956 	} else {
7957 		un->un_runqf = bp;
7958 		un->un_runql = bp;
7959 	}
7960 
7961 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
7962 
7963 	mutex_exit(ST_MUTEX);
7964 
7965 	status = scsi_transport(BP_PKT(bp));
7966 
7967 	mutex_enter(ST_MUTEX);
7968 
7969 	if (status != TRAN_ACCEPT) {
7970 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
7971 		mutex_exit(ST_MUTEX);
7972 
7973 		if (status == TRAN_BUSY) {
7974 			if (st_handle_intr_busy(un, bp,
7975 			    ST_TRAN_BUSY_TIMEOUT) == 0)
7976 				return;	/* timeout is setup again */
7977 		}
7978 
7979 	} else {
7980 		un->un_tran_retry_ct = 0;
7981 		if (un->un_last_throttle) {
7982 			un->un_throttle = un->un_last_throttle;
7983 		}
7984 		mutex_exit(ST_MUTEX);
7985 		return;
7986 	}
7987 
7988 done_error:
7989 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7990 	    "restart transport rejected\n");
7991 	bp->b_resid = bp->b_bcount;
7992 
7993 #ifndef __lock_lint
7994 	/*
7995 	 * warlock doesn't understand this potential
7996 	 * recursion?
7997 	 */
7998 	mutex_enter(ST_MUTEX);
7999 	if (un->un_last_throttle) {
8000 		un->un_throttle = un->un_last_throttle;
8001 	}
8002 	if (status != TRAN_ACCEPT)
8003 		ST_DO_ERRSTATS(un, st_transerrs);
8004 	ST_DO_KSTATS(bp, kstat_waitq_exit);
8005 	SET_PE_FLAG(un);
8006 	st_bioerror(bp, EIO);
8007 	st_done_and_mutex_exit(un, bp);
8008 #endif
8009 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8010 	    "busy restart aborted\n");
8011 }
8012 
8013 /*
8014  * st_check_media():
8015  * Periodically check the media state using scsi_watch service;
8016  * this service calls back after TUR and possibly request sense
8017  * the callback handler (st_media_watch_cb()) decodes the request sense
8018  * data (if any)
8019  */
8020 
8021 static int
8022 st_check_media(dev_t dev, enum mtio_state state)
8023 {
8024 	int rval = 0;
8025 	enum mtio_state	prev_state;
8026 	opaque_t token = NULL;
8027 
8028 	GET_SOFT_STATE(dev);
8029 
8030 	ST_FUNC(ST_DEVINFO, st_check_media);
8031 
8032 	mutex_enter(ST_MUTEX);
8033 
8034 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8035 	    "st_check_media:state=%x, mediastate=%x\n",
8036 	    state, un->un_mediastate);
8037 
8038 	prev_state = un->un_mediastate;
8039 
8040 	/*
8041 	 * is there anything to do?
8042 	 */
8043 retry:
8044 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
8045 		/*
8046 		 * submit the request to the scsi_watch service;
8047 		 * scsi_media_watch_cb() does the real work
8048 		 */
8049 		mutex_exit(ST_MUTEX);
8050 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
8051 		    st_check_media_time, SENSE_LENGTH,
8052 		    st_media_watch_cb, (caddr_t)dev);
8053 		if (token == NULL) {
8054 			rval = EAGAIN;
8055 			goto done;
8056 		}
8057 		mutex_enter(ST_MUTEX);
8058 
8059 		un->un_swr_token = token;
8060 		un->un_specified_mediastate = state;
8061 
8062 		/*
8063 		 * now wait for media change
8064 		 * we will not be signalled unless mediastate == state but it
8065 		 * still better to test for this condition, since there
8066 		 * is a 5 sec cv_broadcast delay when
8067 		 *  mediastate == MTIO_INSERTED
8068 		 */
8069 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8070 		    "st_check_media:waiting for media state change\n");
8071 		while (un->un_mediastate == state) {
8072 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
8073 				mutex_exit(ST_MUTEX);
8074 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8075 				    "st_check_media:waiting for media state "
8076 				    "was interrupted\n");
8077 				rval = EINTR;
8078 				goto done;
8079 			}
8080 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8081 			    "st_check_media:received signal, state=%x\n",
8082 			    un->un_mediastate);
8083 		}
8084 	}
8085 
8086 	/*
8087 	 * if we transitioned to MTIO_INSERTED, media has really been
8088 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
8089 	 * Reset and retry the state change.  If everything is ok, replay
8090 	 * the open() logic.
8091 	 */
8092 	if ((un->un_mediastate == MTIO_INSERTED) &&
8093 	    (un->un_state == ST_STATE_OFFLINE)) {
8094 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8095 		    "st_check_media: calling st_cmd to confirm inserted\n");
8096 
8097 		/*
8098 		 * set this early so that TUR will make it through strategy
8099 		 * without triggering a st_tape_init().  We needed it set
8100 		 * before calling st_tape_init() ourselves anyway.  If TUR
8101 		 * fails, set it back
8102 		 */
8103 		un->un_state = ST_STATE_INITIALIZING;
8104 
8105 		/*
8106 		 * If not reserved fail as getting reservation conflict
8107 		 * will make this hang forever.
8108 		 */
8109 		if ((un->un_rsvd_status &
8110 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
8111 			mutex_exit(ST_MUTEX);
8112 			rval = EACCES;
8113 			goto done;
8114 		}
8115 		rval = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
8116 		if (rval == EACCES) {
8117 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8118 			    "st_check_media: TUR got Reservation Conflict\n");
8119 			mutex_exit(ST_MUTEX);
8120 			goto done;
8121 		}
8122 		if (rval) {
8123 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8124 			    "st_check_media: TUR failed, going to retry\n");
8125 			un->un_mediastate = prev_state;
8126 			un->un_state = ST_STATE_OFFLINE;
8127 			goto retry;
8128 		}
8129 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8130 		    "st_check_media: media inserted\n");
8131 
8132 		/* this also rewinds the tape */
8133 		rval = st_tape_init(dev);
8134 		if (rval != 0) {
8135 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8136 			    "st_check_media : OFFLINE init failure ");
8137 			un->un_state = ST_STATE_OFFLINE;
8138 			un->un_pos.pmode = invalid;
8139 		} else {
8140 			un->un_state = ST_STATE_OPEN_PENDING_IO;
8141 			un->un_pos.fileno = 0;
8142 			un->un_pos.blkno = 0;
8143 			un->un_pos.lgclblkno = 0;
8144 		}
8145 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
8146 	    (un->un_state != ST_STATE_OFFLINE)) {
8147 		/*
8148 		 * supported devices must be rewound before ejection
8149 		 * rewind resets fileno & blkno
8150 		 */
8151 		un->un_laststate = un->un_state;
8152 		un->un_state = ST_STATE_OFFLINE;
8153 	}
8154 	mutex_exit(ST_MUTEX);
8155 done:
8156 	if (token) {
8157 		(void) scsi_watch_request_terminate(token,
8158 		    SCSI_WATCH_TERMINATE_WAIT);
8159 		mutex_enter(ST_MUTEX);
8160 		un->un_swr_token = (opaque_t)NULL;
8161 		mutex_exit(ST_MUTEX);
8162 	}
8163 
8164 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
8165 
8166 	return (rval);
8167 }
8168 
8169 /*
8170  * st_media_watch_cb() is called by scsi_watch_thread for
8171  * verifying the request sense data (if any)
8172  */
8173 static int
8174 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
8175 {
8176 	struct scsi_status *statusp = resultp->statusp;
8177 	struct scsi_extended_sense *sensep = resultp->sensep;
8178 	uchar_t actual_sense_length = resultp->actual_sense_length;
8179 	struct scsi_tape *un;
8180 	enum mtio_state state = MTIO_NONE;
8181 	int instance;
8182 	dev_t dev = (dev_t)arg;
8183 
8184 	instance = MTUNIT(dev);
8185 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
8186 		return (-1);
8187 	}
8188 
8189 	mutex_enter(ST_MUTEX);
8190 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
8191 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8192 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
8193 	    *((char *)statusp), (void *)sensep,
8194 	    actual_sense_length);
8195 
8196 
8197 	/*
8198 	 * if there was a check condition then sensep points to valid
8199 	 * sense data
8200 	 * if status was not a check condition but a reservation or busy
8201 	 * status then the new state is MTIO_NONE
8202 	 */
8203 	if (sensep) {
8204 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8205 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
8206 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
8207 
8208 		switch (un->un_dp->type) {
8209 		default:
8210 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8211 			    "st_media_watch_cb: unknown drive type %d, "
8212 			    "default to ST_TYPE_HP\n", un->un_dp->type);
8213 		/* FALLTHROUGH */
8214 
8215 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
8216 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
8217 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
8218 			if (un->un_dp->type == ST_TYPE_FUJI) {
8219 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8220 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
8221 			} else {
8222 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8223 				    "st_media_watch_cb: ST_TYPE_HP\n");
8224 			}
8225 			switch (sensep->es_key) {
8226 			case KEY_UNIT_ATTENTION:
8227 				/* not ready to ready transition */
8228 				/* hp/es_qual_code == 80 on>off>on */
8229 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
8230 				if (sensep->es_add_code == 0x28) {
8231 					state = MTIO_INSERTED;
8232 				}
8233 				break;
8234 			case KEY_NOT_READY:
8235 				/* in process, rewinding or loading */
8236 				if ((sensep->es_add_code == 0x04) &&
8237 				    (sensep->es_qual_code == 0x00)) {
8238 					state = MTIO_EJECTED;
8239 				}
8240 				break;
8241 			}
8242 			break;
8243 
8244 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
8245 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8246 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
8247 			switch (sensep->es_key) {
8248 			case KEY_UNIT_ATTENTION:
8249 				/* operator medium removal request */
8250 				if ((sensep->es_add_code == 0x5a) &&
8251 				    (sensep->es_qual_code == 0x01)) {
8252 					state = MTIO_EJECTED;
8253 				/* not ready to ready transition */
8254 				} else if ((sensep->es_add_code == 0x28) &&
8255 				    (sensep->es_qual_code == 0x00)) {
8256 					state = MTIO_INSERTED;
8257 				}
8258 				break;
8259 			case KEY_NOT_READY:
8260 				/* medium not present */
8261 				if (sensep->es_add_code == 0x3a) {
8262 					state = MTIO_EJECTED;
8263 				}
8264 				break;
8265 			}
8266 			break;
8267 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
8268 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8269 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
8270 			switch (sensep->es_key) {
8271 			case KEY_NOT_READY:
8272 				if ((sensep->es_add_code == 0x04) &&
8273 				    (sensep->es_qual_code == 0x00)) {
8274 					/* volume not mounted? */
8275 					state = MTIO_EJECTED;
8276 				} else if (sensep->es_add_code == 0x3a) {
8277 					state = MTIO_EJECTED;
8278 				}
8279 				break;
8280 			case KEY_UNIT_ATTENTION:
8281 				state = MTIO_EJECTED;
8282 				break;
8283 			}
8284 			break;
8285 
8286 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
8287 			switch (sensep->es_key) {
8288 			case KEY_UNIT_ATTENTION:
8289 				if (sensep->es_add_code == 0x28) {
8290 					state = MTIO_INSERTED;
8291 				}
8292 				break;
8293 			case KEY_NOT_READY:
8294 				if (sensep->es_add_code == 0x04) {
8295 					/* in transition but could be either */
8296 					state = un->un_specified_mediastate;
8297 				} else if ((sensep->es_add_code == 0x3a) &&
8298 				    (sensep->es_qual_code == 0x00)) {
8299 					state = MTIO_EJECTED;
8300 				}
8301 				break;
8302 			}
8303 			break;
8304 		}
8305 	} else if (*((char *)statusp) == STATUS_GOOD) {
8306 		state = MTIO_INSERTED;
8307 	}
8308 
8309 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8310 	    "st_media_watch_cb:state=%x, specified=%x\n",
8311 	    state, un->un_specified_mediastate);
8312 
8313 	/*
8314 	 * now signal the waiting thread if this is *not* the specified state;
8315 	 * delay the signal if the state is MTIO_INSERTED
8316 	 * to allow the target to recover
8317 	 */
8318 	if (state != un->un_specified_mediastate) {
8319 		un->un_mediastate = state;
8320 		if (state == MTIO_INSERTED) {
8321 			/*
8322 			 * delay the signal to give the drive a chance
8323 			 * to do what it apparently needs to do
8324 			 */
8325 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8326 			    "st_media_watch_cb:delayed cv_broadcast\n");
8327 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
8328 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
8329 		} else {
8330 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8331 			    "st_media_watch_cb:immediate cv_broadcast\n");
8332 			cv_broadcast(&un->un_state_cv);
8333 		}
8334 	}
8335 	mutex_exit(ST_MUTEX);
8336 	return (0);
8337 }
8338 
8339 /*
8340  * delayed cv_broadcast to allow for target to recover
8341  * from media insertion
8342  */
8343 static void
8344 st_delayed_cv_broadcast(void *arg)
8345 {
8346 	struct scsi_tape *un = arg;
8347 
8348 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
8349 
8350 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8351 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
8352 
8353 	mutex_enter(ST_MUTEX);
8354 	cv_broadcast(&un->un_state_cv);
8355 	mutex_exit(ST_MUTEX);
8356 }
8357 
8358 /*
8359  * restart cmd currently at the start of the waitq
8360  */
8361 static void
8362 st_start_restart(void *arg)
8363 {
8364 	struct scsi_tape *un = arg;
8365 
8366 	ST_FUNC(ST_DEVINFO, st_start_restart);
8367 
8368 	ASSERT(un != NULL);
8369 
8370 	mutex_enter(ST_MUTEX);
8371 
8372 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8373 	    "st_tran_restart()\n");
8374 
8375 	if (un->un_quef) {
8376 		st_start(un);
8377 	}
8378 
8379 	mutex_exit(ST_MUTEX);
8380 }
8381 
8382 
8383 /*
8384  * Command completion processing
8385  *
8386  */
8387 static void
8388 st_intr(struct scsi_pkt *pkt)
8389 {
8390 	struct scsi_tape *un;
8391 	struct buf *last_runqf;
8392 	struct buf *bp;
8393 	int action = COMMAND_DONE;
8394 	clock_t	timout;
8395 	int	status;
8396 
8397 
8398 	bp = pkt->pkt_private;
8399 
8400 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
8401 
8402 	ST_FUNC(ST_DEVINFO, st_intr);
8403 
8404 	mutex_enter(ST_MUTEX);
8405 
8406 	un->un_rqs_state &= ~(ST_RQS_ERROR);
8407 
8408 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
8409 
8410 	if (pkt->pkt_reason != CMD_CMPLT) {
8411 
8412 		/* If device has gone away not much else to do */
8413 		if (pkt->pkt_reason == CMD_DEV_GONE) {
8414 			action = COMMAND_DONE_ERROR;
8415 		} else if (un->un_state == ST_STATE_SENSING) {
8416 			ST_DO_ERRSTATS(un, st_transerrs);
8417 			action = COMMAND_DONE_ERROR;
8418 		} else {
8419 			action = st_handle_incomplete(un, bp);
8420 		}
8421 	/*
8422 	 * At this point we know that the command was successfully
8423 	 * completed. Now what?
8424 	 */
8425 	} else if (un->un_arq_enabled &&
8426 	    (pkt->pkt_state & STATE_ARQ_DONE)) {
8427 		/*
8428 		 * the transport layer successfully completed an autorqsense
8429 		 */
8430 		action = st_handle_autosense(un, bp);
8431 
8432 	} else if (un->un_state == ST_STATE_SENSING) {
8433 		/*
8434 		 * okay. We were running a REQUEST SENSE. Find
8435 		 * out what to do next.
8436 		 * some actions are based on un_state, hence
8437 		 * restore the state st was in before ST_STATE_SENSING.
8438 		 */
8439 		un->un_state = un->un_laststate;
8440 		action = st_handle_sense(un, bp);
8441 		/*
8442 		 * set pkt back to original packet in case we will have
8443 		 * to requeue it
8444 		 */
8445 		pkt = BP_PKT(bp);
8446 	} else  if ((SCBP(pkt)->sts_busy) || (SCBP(pkt)->sts_chk)) {
8447 		/*
8448 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
8449 		 * to see if the status bits we're okay. If a request sense
8450 		 * is to be run, that will happen.
8451 		 */
8452 		action = st_check_error(un, pkt);
8453 	}
8454 
8455 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
8456 		switch (action) {
8457 			case QUE_COMMAND:
8458 				/*
8459 				 * return cmd to head to the queue
8460 				 * since we are suspending so that
8461 				 * it gets restarted during resume
8462 				 */
8463 				if (un->un_runqf) {
8464 					last_runqf = un->un_runqf;
8465 					un->un_runqf = bp;
8466 					bp->b_actf = last_runqf;
8467 				} else {
8468 					bp->b_actf = NULL;
8469 					un->un_runqf = bp;
8470 					un->un_runql = bp;
8471 				}
8472 				action = JUST_RETURN;
8473 				break;
8474 
8475 			case QUE_SENSE:
8476 				action = COMMAND_DONE_ERROR;
8477 				break;
8478 
8479 			default:
8480 				break;
8481 		}
8482 	}
8483 
8484 	/*
8485 	 * Restore old state if we were sensing.
8486 	 */
8487 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
8488 		un->un_state = un->un_laststate;
8489 	}
8490 
8491 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8492 	    "st_intr: pkt=%p, bp=%p, action=%x, status=%x\n",
8493 	    (void *)pkt, (void *)bp, action, SCBP_C(pkt));
8494 
8495 
8496 	switch (action) {
8497 	case COMMAND_DONE_EACCES:
8498 		/* this is to report a reservation conflict */
8499 		st_bioerror(bp, EACCES);
8500 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8501 		    "Reservation Conflict \n");
8502 		un->un_pos.pmode = invalid;
8503 
8504 		/*FALLTHROUGH*/
8505 	case COMMAND_DONE_ERROR:
8506 		if (un->un_pos.eof < ST_EOT_PENDING &&
8507 		    un->un_state >= ST_STATE_OPEN) {
8508 			/*
8509 			 * all errors set state of the tape to 'unknown'
8510 			 * unless we're at EOT or are doing append testing.
8511 			 * If sense key was illegal request, preserve state.
8512 			 */
8513 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
8514 				un->un_pos.pmode = invalid;
8515 			}
8516 		}
8517 
8518 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8519 		/*
8520 		 * since we have an error (COMMAND_DONE_ERROR), we want to
8521 		 * make sure an error ocurrs, so make sure at least EIO is
8522 		 * returned
8523 		 */
8524 		if (geterror(bp) == 0)
8525 			st_bioerror(bp, EIO);
8526 
8527 		SET_PE_FLAG(un);
8528 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
8529 		    (un->un_errno == EIO)) {
8530 			un->un_rqs_state &= ~(ST_RQS_VALID);
8531 		}
8532 		goto done;
8533 
8534 	case COMMAND_DONE_ERROR_RECOVERED:
8535 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8536 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
8537 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
8538 		if (geterror(bp) == 0) {
8539 			st_bioerror(bp, EIO);
8540 		}
8541 		SET_PE_FLAG(un);
8542 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
8543 		    (un->un_errno == EIO)) {
8544 			un->un_rqs_state &= ~(ST_RQS_VALID);
8545 		}
8546 		/*FALLTHROUGH*/
8547 	case COMMAND_DONE:
8548 		st_set_state(un);
8549 done:
8550 		ST_DO_KSTATS(bp, kstat_runq_exit);
8551 		st_done_and_mutex_exit(un, bp);
8552 		return;
8553 
8554 	case QUE_SENSE:
8555 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
8556 			goto sense_error;
8557 
8558 		if (un->un_state != ST_STATE_SENSING) {
8559 			un->un_laststate = un->un_state;
8560 			un->un_state = ST_STATE_SENSING;
8561 		}
8562 
8563 		un->un_rqs->pkt_private = (opaque_t)bp;
8564 		bzero(ST_RQSENSE, SENSE_LENGTH);
8565 
8566 		if (un->un_throttle) {
8567 			un->un_last_throttle = un->un_throttle;
8568 			un->un_throttle = 0;
8569 		}
8570 
8571 		mutex_exit(ST_MUTEX);
8572 
8573 		/*
8574 		 * never retry this, some other command will have nuked the
8575 		 * sense, anyway
8576 		 */
8577 		status = scsi_transport(un->un_rqs);
8578 
8579 		mutex_enter(ST_MUTEX);
8580 
8581 		if (un->un_last_throttle) {
8582 			un->un_throttle = un->un_last_throttle;
8583 		}
8584 
8585 		if (status == TRAN_ACCEPT) {
8586 			mutex_exit(ST_MUTEX);
8587 			return;
8588 		}
8589 		if (status != TRAN_BUSY)
8590 			ST_DO_ERRSTATS(un, st_transerrs);
8591 sense_error:
8592 		un->un_pos.pmode = invalid;
8593 		st_bioerror(bp, EIO);
8594 		SET_PE_FLAG(un);
8595 		goto done;
8596 
8597 	case QUE_BUSY_COMMAND:
8598 		/* longish timeout */
8599 		timout = ST_STATUS_BUSY_TIMEOUT;
8600 		goto que_it_up;
8601 
8602 	case QUE_COMMAND:
8603 		/* short timeout */
8604 		timout = ST_TRAN_BUSY_TIMEOUT;
8605 que_it_up:
8606 		/*
8607 		 * let st_handle_intr_busy put this bp back on waitq and make
8608 		 * checks to see if it is ok to requeue the command.
8609 		 */
8610 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8611 
8612 		/*
8613 		 * Save the throttle before setting up the timeout
8614 		 */
8615 		if (un->un_throttle) {
8616 			un->un_last_throttle = un->un_throttle;
8617 		}
8618 		mutex_exit(ST_MUTEX);
8619 		if (st_handle_intr_busy(un, bp, timout) == 0)
8620 			return;		/* timeout is setup again */
8621 
8622 		mutex_enter(ST_MUTEX);
8623 		un->un_pos.pmode = invalid;
8624 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8625 		st_bioerror(bp, EIO);
8626 		SET_PE_FLAG(un);
8627 		goto done;
8628 
8629 	case QUE_LAST_COMMAND:
8630 
8631 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
8632 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
8633 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
8634 			goto last_command_error;
8635 		}
8636 		mutex_exit(ST_MUTEX);
8637 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
8638 			return;
8639 		mutex_enter(ST_MUTEX);
8640 last_command_error:
8641 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8642 		un->un_pos.pmode = invalid;
8643 		st_bioerror(bp, EIO);
8644 		SET_PE_FLAG(un);
8645 		goto done;
8646 
8647 	case JUST_RETURN:
8648 	default:
8649 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8650 		mutex_exit(ST_MUTEX);
8651 		return;
8652 	}
8653 	/*NOTREACHED*/
8654 }
8655 
8656 static int
8657 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
8658 {
8659 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
8660 	int rval = COMMAND_DONE_ERROR;
8661 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
8662 	    un->un_rqs : BP_PKT(bp);
8663 	int result;
8664 
8665 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
8666 
8667 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8668 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
8669 
8670 	ASSERT(mutex_owned(ST_MUTEX));
8671 
8672 	switch (pkt->pkt_reason) {
8673 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
8674 		/*
8675 		 * this occurs when accessing a powered down drive, no
8676 		 * need to complain; just fail the open
8677 		 */
8678 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
8679 
8680 		/*
8681 		 * if we have commands outstanding in HBA, and a command
8682 		 * comes back incomplete, we're hosed, so reset target
8683 		 * If we have the bus, but cmd_incomplete, we probably just
8684 		 * have a failed selection, so don't reset the target, just
8685 		 * requeue the command and try again
8686 		 */
8687 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
8688 			goto reset_target;
8689 		}
8690 
8691 		/*
8692 		 * Retry selection a couple more times if we're
8693 		 * open.  If opening, we only try just once to
8694 		 * reduce probe time for nonexistant devices.
8695 		 */
8696 		if ((un->un_laststate > ST_STATE_OPENING) &&
8697 		    ((int)un->un_retry_ct < st_selection_retry_count)) {
8698 			rval = QUE_COMMAND;
8699 		}
8700 		ST_DO_ERRSTATS(un, st_transerrs);
8701 		break;
8702 
8703 	case CMD_ABORTED:
8704 		/*
8705 		 * most likely this is caused by flush-on-error support. If
8706 		 * it was not there, the we're in trouble.
8707 		 */
8708 		if (!un->un_flush_on_errors) {
8709 			un->un_status = SUN_KEY_FATAL;
8710 			goto reset_target;
8711 		}
8712 
8713 		st_set_pe_errno(un);
8714 		bioerror(bp, un->un_errno);
8715 		if (un->un_errno)
8716 			return (COMMAND_DONE_ERROR);
8717 		else
8718 			return (COMMAND_DONE);
8719 
8720 	case CMD_TIMEOUT:	/* Command timed out */
8721 		un->un_status = SUN_KEY_TIMEOUT;
8722 
8723 		/*FALLTHROUGH*/
8724 	default:
8725 reset_target:
8726 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8727 		    "transport completed with %s\n",
8728 		    scsi_rname(pkt->pkt_reason));
8729 		ST_DO_ERRSTATS(un, st_transerrs);
8730 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
8731 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
8732 		    STAT_ABORTED)) == 0)) {
8733 
8734 			/*
8735 			 * If we haven't reserved the drive don't reset it.
8736 			 */
8737 			if ((un->un_rsvd_status &
8738 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
8739 				return (rval);
8740 			}
8741 
8742 			/*
8743 			 * if we aren't lost yet we will be soon.
8744 			 */
8745 			un->un_pos.pmode = invalid;
8746 
8747 			mutex_exit(ST_MUTEX);
8748 
8749 			result = scsi_reset(ROUTE, RESET_TARGET);
8750 			/*
8751 			 * if target reset fails, then pull the chain
8752 			 */
8753 			if (result == 0) {
8754 				result = scsi_reset(ROUTE, RESET_ALL);
8755 			}
8756 			mutex_enter(ST_MUTEX);
8757 
8758 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
8759 				/* no hope left to recover */
8760 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
8761 				    "recovery by resets failed\n");
8762 				return (rval);
8763 			}
8764 		}
8765 	}
8766 
8767 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
8768 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
8769 		if ((un->un_rsvd_status & ST_RESERVE)) {
8770 			un->un_rsvd_status |= ST_LOST_RESERVE;
8771 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8772 			    "Lost Reservation\n");
8773 		}
8774 	}
8775 
8776 	if ((int)un->un_retry_ct++ < st_retry_count) {
8777 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
8778 			rval = QUE_COMMAND;
8779 		} else if (bp == un->un_sbufp) {
8780 			switch ((uchar_t)(uintptr_t)bp->b_forw) {
8781 			case SCMD_MODE_SENSE:
8782 			case SCMD_MODE_SELECT:
8783 			case SCMD_READ_BLKLIM:
8784 			case SCMD_REWIND:
8785 			case SCMD_LOAD:
8786 			case SCMD_TEST_UNIT_READY:
8787 				/*
8788 				 * These commands can be rerun with impunity
8789 				 */
8790 				rval = QUE_COMMAND;
8791 				break;
8792 
8793 			default:
8794 				break;
8795 			}
8796 		}
8797 	} else {
8798 		rval = COMMAND_DONE_ERROR;
8799 	}
8800 
8801 	if (un->un_state >= ST_STATE_OPEN) {
8802 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
8803 		    fail, scsi_rname(pkt->pkt_reason),
8804 		    (rval == COMMAND_DONE_ERROR)?
8805 		    "giving up" : "retrying command");
8806 	}
8807 	return (rval);
8808 }
8809 
8810 /*
8811  * if the device is busy, then put this bp back on the waitq, on the
8812  * interrupt thread, where we want the head of the queue and not the
8813  * end
8814  *
8815  * The callers of this routine should take measures to save the
8816  * un_throttle in un_last_throttle which will be restored in
8817  * st_intr_restart(). The only exception should be st_intr_restart()
8818  * calling this routine for which the saving is already done.
8819  */
8820 static int
8821 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
8822 	clock_t timeout_interval)
8823 {
8824 	struct buf *last_quef;
8825 	int rval = 0;
8826 
8827 	mutex_enter(ST_MUTEX);
8828 
8829 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
8830 
8831 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8832 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
8833 
8834 	/*
8835 	 * Check to see if we hit the retry timeout. We check to make sure
8836 	 * this is the first one on the runq and make sure we have not
8837 	 * queued up any more, so this one has to be the last on the list
8838 	 * also. If it is not, we have to fail.  If it is not the first, but
8839 	 * is the last we are in trouble anyway, as we are in the interrupt
8840 	 * context here.
8841 	 */
8842 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
8843 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
8844 		rval = -1;
8845 		goto exit;
8846 	}
8847 
8848 	/* put the bp back on the waitq */
8849 	if (un->un_quef) {
8850 		last_quef = un->un_quef;
8851 		un->un_quef = bp;
8852 		bp->b_actf = last_quef;
8853 	} else  {
8854 		bp->b_actf = NULL;
8855 		un->un_quef = bp;
8856 		un->un_quel = bp;
8857 	}
8858 
8859 	/*
8860 	 * We know that this is the first and last on the runq at this time,
8861 	 * so we just nullify those two queues
8862 	 */
8863 	un->un_runqf = NULL;
8864 	un->un_runql = NULL;
8865 
8866 	/*
8867 	 * We don't want any other commands being started in the mean time.
8868 	 * If start had just released mutex after putting something on the
8869 	 * runq, we won't even get here.
8870 	 */
8871 	un->un_throttle = 0;
8872 
8873 	/*
8874 	 * send a marker pkt, if appropriate
8875 	 */
8876 	st_hba_unflush(un);
8877 
8878 	/*
8879 	 * all queues are aligned, we are just waiting to
8880 	 * transport
8881 	 */
8882 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
8883 
8884 exit:
8885 	mutex_exit(ST_MUTEX);
8886 	return (rval);
8887 }
8888 
8889 /*
8890  * To get one error entry from error stack
8891  */
8892 static int
8893 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
8894 {
8895 #ifdef _MULTI_DATAMODEL
8896 	/*
8897 	 * For use when a 32 bit app makes a call into a
8898 	 * 64 bit ioctl
8899 	 */
8900 	struct mterror_entry32 err_entry32;
8901 #endif /* _MULTI_DATAMODEL */
8902 
8903 	int rval = 0;
8904 	struct mterror_entry err_entry;
8905 	struct mterror_entry_stack *err_link_entry_p;
8906 	size_t arq_status_len_in, arq_status_len_kr;
8907 
8908 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
8909 
8910 	ASSERT(mutex_owned(ST_MUTEX));
8911 
8912 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8913 	    "st_get_error_entry()\n");
8914 
8915 	/*
8916 	 * if error record stack empty, return ENXIO
8917 	 */
8918 	if (un->un_error_entry_stk == NULL) {
8919 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8920 		    "st_get_error_entry: Error Entry Stack Empty!\n");
8921 		rval = ENXIO;
8922 		goto ret;
8923 	}
8924 
8925 	/*
8926 	 * get the top entry from stack
8927 	 */
8928 	err_link_entry_p = un->un_error_entry_stk;
8929 	arq_status_len_kr =
8930 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
8931 
8932 #ifdef _MULTI_DATAMODEL
8933 	switch (ddi_model_convert_from(flag & FMODELS)) {
8934 	case DDI_MODEL_ILP32:
8935 		if (ddi_copyin((void *)arg, &err_entry32,
8936 		    MTERROR_ENTRY_SIZE_32, flag)) {
8937 			rval = EFAULT;
8938 			goto ret;
8939 		}
8940 
8941 		arq_status_len_in =
8942 		    (size_t)err_entry32.mtee_arq_status_len;
8943 
8944 		err_entry32.mtee_cdb_len =
8945 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
8946 
8947 		if (arq_status_len_in > arq_status_len_kr)
8948 			err_entry32.mtee_arq_status_len =
8949 			    (size32_t)arq_status_len_kr;
8950 
8951 		if (ddi_copyout(
8952 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
8953 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
8954 		    err_entry32.mtee_cdb_len, flag)) {
8955 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8956 			    "st_get_error_entry: Copy cdb buffer error!");
8957 			rval = EFAULT;
8958 		}
8959 
8960 		if (ddi_copyout(
8961 		    err_link_entry_p->mtees_entry.mtee_arq_status,
8962 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
8963 		    err_entry32.mtee_arq_status_len, flag)) {
8964 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8965 			    "st_get_error_entry: copy arq status error!");
8966 			rval = EFAULT;
8967 		}
8968 
8969 		if (ddi_copyout(&err_entry32, (void *)arg,
8970 		    MTERROR_ENTRY_SIZE_32, flag)) {
8971 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8972 			    "st_get_error_entry: copy arq status out error!");
8973 			rval = EFAULT;
8974 		}
8975 		break;
8976 
8977 	case DDI_MODEL_NONE:
8978 		if (ddi_copyin((void *)arg, &err_entry,
8979 		    MTERROR_ENTRY_SIZE_64, flag)) {
8980 			rval = EFAULT;
8981 			goto ret;
8982 		}
8983 		arq_status_len_in = err_entry.mtee_arq_status_len;
8984 
8985 		err_entry.mtee_cdb_len =
8986 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
8987 
8988 		if (arq_status_len_in > arq_status_len_kr)
8989 			err_entry.mtee_arq_status_len =
8990 			    arq_status_len_kr;
8991 
8992 		if (ddi_copyout(
8993 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
8994 		    err_entry.mtee_cdb_buf,
8995 		    err_entry.mtee_cdb_len, flag)) {
8996 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8997 			    "st_get_error_entry: Copy cdb buffer error!");
8998 			rval = EFAULT;
8999 		}
9000 
9001 		if (ddi_copyout(
9002 		    err_link_entry_p->mtees_entry.mtee_arq_status,
9003 		    err_entry.mtee_arq_status,
9004 		    err_entry.mtee_arq_status_len, flag)) {
9005 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9006 			    "st_get_error_entry: copy arq status error!");
9007 			rval = EFAULT;
9008 		}
9009 
9010 		if (ddi_copyout(&err_entry, (void *)arg,
9011 		    MTERROR_ENTRY_SIZE_64, flag)) {
9012 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9013 			    "st_get_error_entry: copy arq status out error!");
9014 			rval = EFAULT;
9015 		}
9016 		break;
9017 	}
9018 #else /* _MULTI_DATAMODEL */
9019 	if (ddi_copyin((void *)arg, &err_entry,
9020 	    MTERROR_ENTRY_SIZE_64, flag)) {
9021 		rval = EFAULT;
9022 		goto ret;
9023 	}
9024 	arq_status_len_in = err_entry.mtee_arq_status_len;
9025 
9026 	err_entry.mtee_cdb_len =
9027 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
9028 
9029 	if (arq_status_len_in > arq_status_len_kr)
9030 		err_entry.mtee_arq_status_len =
9031 		    arq_status_len_kr;
9032 
9033 	if (ddi_copyout(
9034 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
9035 	    err_entry.mtee_cdb_buf,
9036 	    err_entry.mtee_cdb_len, flag)) {
9037 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9038 		    "st_get_error_entry: Copy cdb buffer error!");
9039 		rval = EFAULT;
9040 	}
9041 
9042 	if (ddi_copyout(
9043 	    err_link_entry_p->mtees_entry.mtee_arq_status,
9044 	    err_entry.mtee_arq_status,
9045 	    err_entry.mtee_arq_status_len, flag)) {
9046 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9047 		    "st_get_error_entry: copy arq status buffer error!");
9048 		rval = EFAULT;
9049 	}
9050 
9051 	if (ddi_copyout(&err_entry, (void *)arg,
9052 	    MTERROR_ENTRY_SIZE_64, flag)) {
9053 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9054 		    "st_get_error_entry: copy arq status out error!");
9055 		rval = EFAULT;
9056 	}
9057 #endif /* _MULTI_DATAMODEL */
9058 
9059 	/*
9060 	 * update stack
9061 	 */
9062 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
9063 
9064 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
9065 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
9066 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
9067 
9068 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
9069 	    SECMDS_STATUS_SIZE);
9070 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
9071 
9072 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
9073 	err_link_entry_p = NULL;
9074 ret:
9075 	return (rval);
9076 }
9077 
9078 /*
9079  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
9080  * the scsi CDB command which causes the error and generates sense data and
9081  * the scsi status.
9082  *
9083  *      error-record stack
9084  *
9085  *
9086  *             TOP                                     BOTTOM
9087  *              ------------------------------------------
9088  *              |   0   |   1   |   2   |   ...  |   n   |
9089  *              ------------------------------------------
9090  *                  ^
9091  *                  |
9092  *       pointer to error entry
9093  *
9094  * when st driver generates one sense data record, it creates a error-entry
9095  * and pushes it onto the stack.
9096  *
9097  */
9098 
9099 static void
9100 st_update_error_stack(struct scsi_tape *un,
9101 			struct scsi_pkt *pkt,
9102 			struct scsi_arq_status *cmd)
9103 {
9104 	struct mterror_entry_stack *err_entry_tmp;
9105 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
9106 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
9107 
9108 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
9109 
9110 	ASSERT(mutex_owned(ST_MUTEX));
9111 
9112 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9113 	    "st_update_error_stack()\n");
9114 
9115 	ASSERT(cmd);
9116 	ASSERT(cdbp);
9117 	if (cdblen == 0) {
9118 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9119 		    "st_update_error_stack: CDB length error!\n");
9120 		return;
9121 	}
9122 
9123 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
9124 	ASSERT(err_entry_tmp != NULL);
9125 
9126 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
9127 	    kmem_alloc(cdblen, KM_SLEEP);
9128 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
9129 
9130 	err_entry_tmp->mtees_entry.mtee_arq_status =
9131 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
9132 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
9133 
9134 	/*
9135 	 * copy cdb command & length to current error entry
9136 	 */
9137 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
9138 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
9139 
9140 	/*
9141 	 * copy scsi status length to current error entry
9142 	 */
9143 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
9144 	    SECMDS_STATUS_SIZE;
9145 
9146 	/*
9147 	 * copy sense data and scsi status to current error entry
9148 	 */
9149 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
9150 	    SECMDS_STATUS_SIZE);
9151 
9152 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
9153 	un->un_error_entry_stk = err_entry_tmp;
9154 
9155 }
9156 
9157 /*
9158  * Empty all the error entry in stack
9159  */
9160 static void
9161 st_empty_error_stack(struct scsi_tape *un)
9162 {
9163 	struct mterror_entry_stack *linkp;
9164 
9165 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
9166 
9167 	ASSERT(mutex_owned(ST_MUTEX));
9168 
9169 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9170 	    "st_empty_entry_stack()\n");
9171 
9172 	while (un->un_error_entry_stk != NULL) {
9173 		linkp = un->un_error_entry_stk;
9174 		un->un_error_entry_stk =
9175 		    un->un_error_entry_stk->mtees_nextp;
9176 
9177 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
9178 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
9179 			    linkp->mtees_entry.mtee_cdb_len);
9180 
9181 		if (linkp->mtees_entry.mtee_arq_status != NULL)
9182 			kmem_free(linkp->mtees_entry.mtee_arq_status,
9183 			    linkp->mtees_entry.mtee_arq_status_len);
9184 
9185 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
9186 		linkp = NULL;
9187 	}
9188 }
9189 
9190 static int
9191 st_handle_sense(struct scsi_tape *un, struct buf *bp)
9192 {
9193 	struct scsi_pkt *pkt = BP_PKT(bp);
9194 	struct scsi_pkt *rqpkt = un->un_rqs;
9195 	struct scsi_arq_status arqstat;
9196 
9197 	int rval = COMMAND_DONE_ERROR;
9198 	int amt;
9199 
9200 	ST_FUNC(ST_DEVINFO, st_handle_sense);
9201 
9202 	ASSERT(mutex_owned(ST_MUTEX));
9203 
9204 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9205 	    "st_handle_sense()\n");
9206 
9207 	if (SCBP(rqpkt)->sts_busy) {
9208 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
9209 		    "busy unit on request sense\n");
9210 		if ((int)un->un_retry_ct++ < st_retry_count) {
9211 			rval = QUE_BUSY_COMMAND;
9212 		}
9213 		return (rval);
9214 	} else if (SCBP(rqpkt)->sts_chk) {
9215 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9216 		    "Check Condition on REQUEST SENSE\n");
9217 		return (rval);
9218 	}
9219 
9220 	/* was there enough data? */
9221 	amt = (int)SENSE_LENGTH - rqpkt->pkt_resid;
9222 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
9223 	    (amt < SUN_MIN_SENSE_LENGTH)) {
9224 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9225 		    "REQUEST SENSE couldn't get sense data\n");
9226 		return (rval);
9227 	}
9228 
9229 	bcopy(SCBP(pkt), &arqstat.sts_status,
9230 	    sizeof (struct scsi_status));
9231 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
9232 	    sizeof (struct scsi_status));
9233 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
9234 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
9235 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
9236 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
9237 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
9238 
9239 	/*
9240 	 * copy one arqstat entry in the sense data buffer
9241 	 */
9242 	st_update_error_stack(un, pkt, &arqstat);
9243 	return (st_decode_sense(un, bp, amt, SCBP(rqpkt)));
9244 }
9245 
9246 static int
9247 st_handle_autosense(struct scsi_tape *un, struct buf *bp)
9248 {
9249 	struct scsi_pkt *pkt = BP_PKT(bp);
9250 	struct scsi_arq_status *arqstat =
9251 	    (struct scsi_arq_status *)pkt->pkt_scbp;
9252 	int rval = COMMAND_DONE_ERROR;
9253 	int amt;
9254 
9255 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
9256 
9257 	ASSERT(mutex_owned(ST_MUTEX));
9258 
9259 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9260 	    "st_handle_autosense()\n");
9261 
9262 	if (arqstat->sts_rqpkt_status.sts_busy) {
9263 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
9264 		    "busy unit on request sense\n");
9265 		/*
9266 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
9267 		 * the disadvantage is that we do not have any delay for the
9268 		 * second retry of rqsense and we have to keep a packet around
9269 		 */
9270 		return (QUE_SENSE);
9271 
9272 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
9273 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9274 		    "transport error on REQUEST SENSE\n");
9275 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
9276 		    ((arqstat->sts_rqpkt_statistics &
9277 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
9278 			mutex_exit(ST_MUTEX);
9279 			if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
9280 				/*
9281 				 * if target reset fails, then pull the chain
9282 				 */
9283 				if (scsi_reset(ROUTE, RESET_ALL) == 0) {
9284 					ST_DEBUG6(ST_DEVINFO, st_label,
9285 					    CE_WARN,
9286 					    "recovery by resets failed\n");
9287 				}
9288 			}
9289 			mutex_enter(ST_MUTEX);
9290 		}
9291 		return (rval);
9292 
9293 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
9294 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9295 		    "Check Condition on REQUEST SENSE\n");
9296 		return (rval);
9297 	}
9298 
9299 
9300 	/* was there enough data? */
9301 	amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
9302 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
9303 	    (amt < SUN_MIN_SENSE_LENGTH)) {
9304 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9305 		    "REQUEST SENSE couldn't get sense data\n");
9306 		return (rval);
9307 	}
9308 
9309 	/*
9310 	 * copy one arqstat entry in the sense data buffer
9311 	 */
9312 	st_update_error_stack(un, pkt, arqstat);
9313 
9314 	bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
9315 
9316 	return (st_decode_sense(un, bp, amt, &arqstat->sts_rqpkt_status));
9317 }
9318 
9319 static int
9320 st_decode_sense(struct scsi_tape *un, struct buf *bp,  int amt,
9321 	struct scsi_status *statusp)
9322 {
9323 	struct scsi_pkt *pkt = BP_PKT(bp);
9324 	int rval = COMMAND_DONE_ERROR;
9325 	long resid;
9326 	struct scsi_extended_sense *sensep = ST_RQSENSE;
9327 	int severity;
9328 	int get_error;
9329 
9330 	ST_FUNC(ST_DEVINFO, st_decode_sense);
9331 
9332 	ASSERT(mutex_owned(ST_MUTEX));
9333 
9334 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9335 	    "st_decode_sense()\n");
9336 
9337 	/*
9338 	 * For uscsi commands, squirrel away a copy of the
9339 	 * results of the Request Sense.
9340 	 */
9341 	if (USCSI_CMD(bp)) {
9342 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
9343 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
9344 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
9345 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
9346 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
9347 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
9348 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9349 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
9350 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
9351 		}
9352 	}
9353 
9354 	/*
9355 	 * If the drive is an MT-02, reposition the
9356 	 * secondary error code into the proper place.
9357 	 *
9358 	 * XXX	MT-02 is non-CCS tape, so secondary error code
9359 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
9360 	 * so it's in byte 12.
9361 	 */
9362 	if (un->un_dp->type == ST_TYPE_EMULEX) {
9363 		sensep->es_code = sensep->es_add_info[0];
9364 	}
9365 
9366 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
9367 	    (caddr_t)&CDBP(pkt)->scc_cmd);
9368 
9369 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)sensep,
9370 	    sizeof (*sensep));
9371 
9372 	/* for normal I/O check extract the resid values. */
9373 	if (bp != un->un_sbufp) {
9374 		if (sensep->es_valid) {
9375 			resid =
9376 			    (sensep->es_info_1 << 24) |
9377 			    (sensep->es_info_2 << 16) |
9378 			    (sensep->es_info_3 << 8)  |
9379 			    (sensep->es_info_4);
9380 			/* If fixed block */
9381 			if (un->un_bsize) {
9382 				resid *= un->un_bsize;
9383 			}
9384 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
9385 			resid = pkt->pkt_resid;
9386 		} else {
9387 			resid = bp->b_bcount;
9388 		}
9389 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9390 		    "st_handle_sense (rw): xferred bit = %d, resid=%ld (%d), "
9391 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
9392 		    resid,
9393 		    (sensep->es_info_1 << 24) |
9394 		    (sensep->es_info_2 << 16) |
9395 		    (sensep->es_info_3 << 8)  |
9396 		    (sensep->es_info_4),
9397 		    pkt->pkt_resid);
9398 		/*
9399 		 * The problem is, what should we believe?
9400 		 */
9401 		if (resid && (pkt->pkt_resid == 0)) {
9402 			pkt->pkt_resid = resid;
9403 		}
9404 	} else {
9405 		/*
9406 		 * If the command is SCMD_SPACE, we need to get the
9407 		 * residual as returned in the sense data, to adjust
9408 		 * our idea of current tape position correctly
9409 		 */
9410 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
9411 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
9412 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
9413 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK) &&
9414 		    (sensep->es_valid)) {
9415 			resid =
9416 			    (sensep->es_info_1 << 24) |
9417 			    (sensep->es_info_2 << 16) |
9418 			    (sensep->es_info_3 << 8)  |
9419 			    (sensep->es_info_4);
9420 			bp->b_resid = resid;
9421 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9422 			    "st_handle_sense(other):	resid=%ld\n", resid);
9423 		} else {
9424 			/*
9425 			 * If the special command is SCMD_READ,
9426 			 * the correct resid will be set later.
9427 			 */
9428 			resid = bp->b_bcount;
9429 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9430 			    "st_handle_sense(special read):  resid=%ld\n",
9431 			    resid);
9432 		}
9433 	}
9434 
9435 	if ((un->un_state >= ST_STATE_OPEN) &&
9436 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
9437 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
9438 		    "Failed CDB", (char *)pkt->pkt_cdbp);
9439 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
9440 		    "sense data", (char *)sensep, amt);
9441 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
9442 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
9443 		    bp->b_bcount, resid, pkt->pkt_resid);
9444 	}
9445 
9446 	switch (un->un_status = sensep->es_key) {
9447 	case KEY_NO_SENSE:
9448 		severity = SCSI_ERR_INFO;
9449 
9450 		/*
9451 		 * Erase, locate or rewind operation in progress, retry
9452 		 * ASC  ASCQ
9453 		 *  00   18    Erase operation in progress
9454 		 *  00   19    Locate operation in progress
9455 		 *  00   1A    Rewind operation in progress
9456 		 */
9457 		if (sensep->es_add_code == 0 &&
9458 		    ((sensep->es_qual_code == 0x18) ||
9459 		    (sensep->es_qual_code == 0x19) ||
9460 		    (sensep->es_qual_code == 0x1a))) {
9461 			rval = QUE_COMMAND;
9462 			break;
9463 		}
9464 
9465 		goto common;
9466 
9467 	case KEY_RECOVERABLE_ERROR:
9468 		severity = SCSI_ERR_RECOVERED;
9469 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
9470 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
9471 			if (un->un_dp->options &
9472 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
9473 				rval = QUE_LAST_COMMAND;
9474 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
9475 				    severity, un->un_pos.lgclblkno,
9476 				    un->un_err_pos.lgclblkno, scsi_cmds,
9477 				    sensep);
9478 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
9479 				    "Command will be retried\n");
9480 			} else {
9481 				severity = SCSI_ERR_FATAL;
9482 				rval = COMMAND_DONE_ERROR_RECOVERED;
9483 				ST_DO_ERRSTATS(un, st_softerrs);
9484 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
9485 				    severity, un->un_pos.lgclblkno,
9486 				    un->un_err_pos.lgclblkno, scsi_cmds,
9487 				    sensep);
9488 			}
9489 			break;
9490 		}
9491 common:
9492 		/*
9493 		 * XXX only want reads to be stopped by filemarks.
9494 		 * Don't want them to be stopped by EOT.  EOT matters
9495 		 * only on write.
9496 		 */
9497 		if (sensep->es_filmk && !sensep->es_eom) {
9498 			rval = COMMAND_DONE;
9499 		} else if (sensep->es_eom) {
9500 			rval = COMMAND_DONE;
9501 		} else if (sensep->es_ili) {
9502 			/*
9503 			 * Fun with variable length record devices:
9504 			 * for specifying larger blocks sizes than the
9505 			 * actual physical record size.
9506 			 */
9507 			if (un->un_bsize == 0 && resid > 0) {
9508 				/*
9509 				 * XXX! Ugly.
9510 				 * The requested blocksize is > tape blocksize,
9511 				 * so this is ok, so we just return the
9512 				 * actual size xferred.
9513 				 */
9514 				pkt->pkt_resid = resid;
9515 				rval = COMMAND_DONE;
9516 			} else if (un->un_bsize == 0 && resid < 0) {
9517 				/*
9518 				 * The requested blocksize is < tape blocksize,
9519 				 * so this is not ok, so we err with ENOMEM
9520 				 */
9521 				rval = COMMAND_DONE_ERROR_RECOVERED;
9522 				st_bioerror(bp, ENOMEM);
9523 			} else {
9524 				ST_DO_ERRSTATS(un, st_softerrs);
9525 				severity = SCSI_ERR_FATAL;
9526 				rval = COMMAND_DONE_ERROR;
9527 				st_bioerror(bp, EINVAL);
9528 			}
9529 		} else {
9530 			/*
9531 			 * we hope and pray for this just being
9532 			 * something we can ignore (ie. a
9533 			 * truly recoverable soft error)
9534 			 */
9535 			rval = COMMAND_DONE;
9536 		}
9537 		if (sensep->es_filmk) {
9538 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9539 			    "filemark\n");
9540 			un->un_status = SUN_KEY_EOF;
9541 			un->un_pos.eof = ST_EOF_PENDING;
9542 			SET_PE_FLAG(un);
9543 		}
9544 
9545 		/*
9546 		 * ignore eom when reading, a fmk should terminate reading
9547 		 */
9548 		if ((sensep->es_eom) &&
9549 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
9550 			if ((sensep->es_add_code == 0) &&
9551 			    (sensep->es_qual_code == 4)) {
9552 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9553 				    "bot\n");
9554 				un->un_status = SUN_KEY_BOT;
9555 				un->un_pos.eof = ST_NO_EOF;
9556 				un->un_pos.lgclblkno = 0;
9557 				un->un_pos.fileno = 0;
9558 				un->un_pos.blkno = 0;
9559 				un->un_pos.pmode = legacy;
9560 			} else {
9561 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9562 				    "eom\n");
9563 				un->un_status = SUN_KEY_EOT;
9564 				un->un_pos.eof = ST_EOM;
9565 			}
9566 			SET_PE_FLAG(un);
9567 		}
9568 
9569 		break;
9570 
9571 	case KEY_ILLEGAL_REQUEST:
9572 
9573 		if (un->un_laststate >= ST_STATE_OPEN) {
9574 			ST_DO_ERRSTATS(un, st_softerrs);
9575 			severity = SCSI_ERR_FATAL;
9576 		} else {
9577 			severity = SCSI_ERR_INFO;
9578 		}
9579 		break;
9580 
9581 	case KEY_MEDIUM_ERROR:
9582 		ST_DO_ERRSTATS(un, st_harderrs);
9583 		severity = SCSI_ERR_FATAL;
9584 
9585 		/*
9586 		 * for (buffered) writes, a medium error must be fatal
9587 		 */
9588 		if (CDBP(pkt)->scc_cmd != SCMD_WRITE) {
9589 			rval = COMMAND_DONE_ERROR_RECOVERED;
9590 		}
9591 
9592 check_keys:
9593 		/*
9594 		 * attempt to process the keys in the presence of
9595 		 * other errors
9596 		 */
9597 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
9598 			/*
9599 			 * Fun with variable length record devices:
9600 			 * for specifying larger blocks sizes than the
9601 			 * actual physical record size.
9602 			 */
9603 			if (un->un_bsize == 0 && resid > 0) {
9604 				/*
9605 				 * XXX! Ugly
9606 				 */
9607 				pkt->pkt_resid = resid;
9608 			} else if (un->un_bsize == 0 && resid < 0) {
9609 				st_bioerror(bp, EINVAL);
9610 			} else {
9611 				severity = SCSI_ERR_FATAL;
9612 				rval = COMMAND_DONE_ERROR;
9613 				st_bioerror(bp, EINVAL);
9614 			}
9615 		}
9616 		if (sensep->es_filmk) {
9617 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9618 			    "filemark\n");
9619 			un->un_status = SUN_KEY_EOF;
9620 			un->un_pos.eof = ST_EOF_PENDING;
9621 			SET_PE_FLAG(un);
9622 		}
9623 
9624 		/*
9625 		 * ignore eom when reading, a fmk should terminate reading
9626 		 */
9627 		if ((sensep->es_eom) &&
9628 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
9629 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
9630 			un->un_status = SUN_KEY_EOT;
9631 			un->un_pos.eof = ST_EOM;
9632 			SET_PE_FLAG(un);
9633 		}
9634 
9635 		break;
9636 
9637 	case KEY_VOLUME_OVERFLOW:
9638 		ST_DO_ERRSTATS(un, st_softerrs);
9639 		un->un_pos.eof = ST_EOM;
9640 		severity = SCSI_ERR_FATAL;
9641 		rval = COMMAND_DONE_ERROR;
9642 		goto check_keys;
9643 
9644 	case KEY_HARDWARE_ERROR:
9645 		ST_DO_ERRSTATS(un, st_harderrs);
9646 		severity = SCSI_ERR_FATAL;
9647 		rval = COMMAND_DONE_ERROR;
9648 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
9649 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
9650 		break;
9651 
9652 	case KEY_BLANK_CHECK:
9653 		ST_DO_ERRSTATS(un, st_softerrs);
9654 		severity = SCSI_ERR_INFO;
9655 
9656 		/*
9657 		 * if not a special request and some data was xferred then it
9658 		 * it is not an error yet
9659 		 */
9660 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
9661 			/*
9662 			 * no error for read with or without data xferred
9663 			 */
9664 			un->un_status = SUN_KEY_EOT;
9665 			un->un_pos.eof = ST_EOT;
9666 			rval = COMMAND_DONE_ERROR;
9667 			SET_PE_FLAG(un);
9668 			goto check_keys;
9669 		} else if (bp != un->un_sbufp &&
9670 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
9671 			rval = COMMAND_DONE;
9672 		} else {
9673 			rval = COMMAND_DONE_ERROR_RECOVERED;
9674 		}
9675 
9676 		if (un->un_laststate >= ST_STATE_OPEN) {
9677 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9678 			    "blank check\n");
9679 			un->un_pos.eof = ST_EOM;
9680 		}
9681 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
9682 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
9683 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
9684 		    (un->un_dp->options & ST_KNOWS_EOD)) {
9685 			/*
9686 			 * we were doing a fast forward by skipping
9687 			 * multiple fmk at the time
9688 			 */
9689 			st_bioerror(bp, EIO);
9690 			severity = SCSI_ERR_RECOVERED;
9691 			rval	 = COMMAND_DONE;
9692 		}
9693 		SET_PE_FLAG(un);
9694 		goto check_keys;
9695 
9696 	case KEY_WRITE_PROTECT:
9697 		if (st_wrongtapetype(un)) {
9698 			un->un_status = SUN_KEY_WRONGMEDIA;
9699 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9700 		"wrong tape for writing- use DC6150 tape (or equivalent)\n");
9701 			severity = SCSI_ERR_UNKNOWN;
9702 		} else {
9703 			severity = SCSI_ERR_FATAL;
9704 		}
9705 		ST_DO_ERRSTATS(un, st_harderrs);
9706 		rval = COMMAND_DONE_ERROR;
9707 		st_bioerror(bp, EACCES);
9708 		break;
9709 
9710 	case KEY_UNIT_ATTENTION:
9711 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9712 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
9713 
9714 		/*
9715 		 * If we have detected a Bus Reset and the tape
9716 		 * drive has been reserved.
9717 		 */
9718 		if (ST_RQSENSE->es_add_code == 0x29 &&
9719 		    (un->un_rsvd_status & ST_RESERVE)) {
9720 			un->un_rsvd_status |= ST_LOST_RESERVE;
9721 			ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9722 			    "st_decode_sense: Lost Reservation\n");
9723 		}
9724 
9725 		if (un->un_state <= ST_STATE_OPENING) {
9726 			/*
9727 			 * Look, the tape isn't open yet, now determine
9728 			 * if the cause is a BUS RESET, Save the file and
9729 			 * Block positions for the callers to recover from
9730 			 * the loss of position.
9731 			 */
9732 			if (un->un_pos.pmode != invalid) {
9733 				if (ST_RQSENSE->es_add_code == 0x29) {
9734 					un->un_save_fileno = un->un_pos.fileno;
9735 					un->un_save_blkno = un->un_pos.blkno;
9736 					un->un_restore_pos = 1;
9737 				}
9738 			}
9739 
9740 			if ((int)un->un_retry_ct++ < st_retry_count) {
9741 				rval = QUE_COMMAND;
9742 			} else {
9743 				rval = COMMAND_DONE_ERROR;
9744 			}
9745 			severity = SCSI_ERR_INFO;
9746 
9747 		} else {
9748 			/*
9749 			 * Check if it is an Unexpected Unit Attention.
9750 			 * If state is >= ST_STATE_OPEN, we have
9751 			 * already done the initialization .
9752 			 * In this case it is Fatal Error
9753 			 * since no further reading/writing
9754 			 * can be done with fileno set to < 0.
9755 			 */
9756 			if (un->un_state >= ST_STATE_OPEN) {
9757 				ST_DO_ERRSTATS(un, st_harderrs);
9758 				severity = SCSI_ERR_FATAL;
9759 			} else {
9760 				severity = SCSI_ERR_INFO;
9761 			}
9762 			rval = COMMAND_DONE_ERROR;
9763 		}
9764 		un->un_pos.pmode = invalid;
9765 
9766 		break;
9767 
9768 	case KEY_NOT_READY:
9769 		/*
9770 		 * If in process of getting ready retry.
9771 		 */
9772 		if (sensep->es_add_code  == 0x04 &&
9773 		    sensep->es_qual_code == 0x01 &&
9774 		    un->un_retry_ct++ < st_retry_count) {
9775 			rval = QUE_COMMAND;
9776 			severity = SCSI_ERR_INFO;
9777 		} else {
9778 			/* give up */
9779 			rval = COMMAND_DONE_ERROR;
9780 			severity = SCSI_ERR_FATAL;
9781 		}
9782 
9783 		/*
9784 		 * If this was an error and after device opened
9785 		 * do error stats.
9786 		 */
9787 		if (rval == COMMAND_DONE_ERROR &&
9788 		    un->un_state > ST_STATE_OPENING) {
9789 			ST_DO_ERRSTATS(un, st_harderrs);
9790 		}
9791 
9792 		if (ST_RQSENSE->es_add_code == 0x3a) {
9793 			if (st_error_level >= SCSI_ERR_FATAL)
9794 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
9795 				    "Tape not inserted in drive\n");
9796 			un->un_mediastate = MTIO_EJECTED;
9797 			cv_broadcast(&un->un_state_cv);
9798 		}
9799 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
9800 		    (rval != QUE_COMMAND))
9801 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
9802 		break;
9803 
9804 	case KEY_ABORTED_COMMAND:
9805 
9806 		/*
9807 		 * Probably a parity error...
9808 		 * if we retry here then this may cause data to be
9809 		 * written twice or data skipped during reading
9810 		 */
9811 		ST_DO_ERRSTATS(un, st_harderrs);
9812 		severity = SCSI_ERR_FATAL;
9813 		rval = COMMAND_DONE_ERROR;
9814 		goto check_keys;
9815 
9816 	default:
9817 		/*
9818 		 * Undecoded sense key.	 Try retries and hope
9819 		 * that will fix the problem.  Otherwise, we're
9820 		 * dead.
9821 		 */
9822 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9823 		    "Unhandled Sense Key '%s'\n",
9824 		    sense_keys[un->un_status]);
9825 		ST_DO_ERRSTATS(un, st_harderrs);
9826 		severity = SCSI_ERR_FATAL;
9827 		rval = COMMAND_DONE_ERROR;
9828 		goto check_keys;
9829 	}
9830 
9831 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
9832 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
9833 	    (un->un_laststate > ST_STATE_OPENING) &&
9834 	    (severity >= st_error_level))) {
9835 
9836 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
9837 		    un->un_pos.lgclblkno, un->un_err_pos.lgclblkno,
9838 		    scsi_cmds, sensep);
9839 		if (sensep->es_filmk) {
9840 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9841 			    "File Mark Detected\n");
9842 		}
9843 		if (sensep->es_eom) {
9844 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9845 			    "End-of-Media Detected\n");
9846 		}
9847 		if (sensep->es_ili) {
9848 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9849 			    "Incorrect Length Indicator Set\n");
9850 		}
9851 	}
9852 	get_error = geterror(bp);
9853 	if (((rval == COMMAND_DONE_ERROR) ||
9854 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
9855 	    ((get_error == EIO) || (get_error == 0))) {
9856 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
9857 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
9858 		if (un->un_rqs_state & ST_RQS_READ) {
9859 			un->un_rqs_state &= ~(ST_RQS_READ);
9860 		} else {
9861 			un->un_rqs_state |= ST_RQS_OVR;
9862 		}
9863 	}
9864 
9865 	return (rval);
9866 }
9867 
9868 
9869 static int
9870 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
9871 {
9872 	int status = TRAN_ACCEPT;
9873 
9874 	mutex_enter(ST_MUTEX);
9875 
9876 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
9877 
9878 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9879 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
9880 
9881 	/*
9882 	 * Check to see if we hit the retry timeout. We check to make sure
9883 	 * this is the first one on the runq and make sure we have not
9884 	 * queued up any more, so this one has to be the last on the list
9885 	 * also. If it is not, we have to fail.  If it is not the first, but
9886 	 * is the last we are in trouble anyway, as we are in the interrupt
9887 	 * context here.
9888 	 */
9889 	if (((int)un->un_retry_ct > st_retry_count) ||
9890 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
9891 		goto exit;
9892 	}
9893 
9894 	if (un->un_throttle) {
9895 		un->un_last_throttle = un->un_throttle;
9896 		un->un_throttle = 0;
9897 	}
9898 
9899 	/*
9900 	 * Here we know : bp is the first and last one on the runq
9901 	 * it is not necessary to put it back on the head of the
9902 	 * waitq and then move from waitq to runq. Save this queuing
9903 	 * and call scsi_transport.
9904 	 */
9905 
9906 	mutex_exit(ST_MUTEX);
9907 
9908 	status = scsi_transport(BP_PKT(bp));
9909 
9910 	mutex_enter(ST_MUTEX);
9911 
9912 	if (status == TRAN_ACCEPT) {
9913 		un->un_tran_retry_ct = 0;
9914 		if (un->un_last_throttle) {
9915 			un->un_throttle = un->un_last_throttle;
9916 		}
9917 		mutex_exit(ST_MUTEX);
9918 
9919 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9920 		    "restart transport \n");
9921 		return (0);
9922 	}
9923 
9924 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9925 	mutex_exit(ST_MUTEX);
9926 
9927 	if (status == TRAN_BUSY) {
9928 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
9929 			return (0);
9930 		}
9931 	}
9932 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9933 	    "restart transport rejected\n");
9934 	mutex_enter(ST_MUTEX);
9935 	ST_DO_ERRSTATS(un, st_transerrs);
9936 	if (un->un_last_throttle) {
9937 		un->un_throttle = un->un_last_throttle;
9938 	}
9939 exit:
9940 	mutex_exit(ST_MUTEX);
9941 	return (-1);
9942 }
9943 
9944 static int
9945 st_wrongtapetype(struct scsi_tape *un)
9946 {
9947 
9948 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
9949 
9950 	ASSERT(mutex_owned(ST_MUTEX));
9951 
9952 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
9953 
9954 	/*
9955 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
9956 	 */
9957 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
9958 		switch (un->un_dp->type) {
9959 		case ST_TYPE_WANGTEK:
9960 		case ST_TYPE_ARCHIVE:
9961 			/*
9962 			 * If this really worked, we could go off of
9963 			 * the density codes set in the modesense
9964 			 * page. For this drive, 0x10 == QIC-120,
9965 			 * 0xf == QIC-150, and 0x5 should be for
9966 			 * both QIC-24 and, maybe, QIC-11. However,
9967 			 * the h/w doesn't do what the manual says
9968 			 * that it should, so we'll key off of
9969 			 * getting a WRITE PROTECT error AND wp *not*
9970 			 * set in the mode sense information.
9971 			 */
9972 			/*
9973 			 * XXX but we already know that status is
9974 			 * write protect, so don't check it again.
9975 			 */
9976 
9977 			if (un->un_status == KEY_WRITE_PROTECT &&
9978 			    un->un_mspl->wp == 0) {
9979 				return (1);
9980 			}
9981 			break;
9982 		default:
9983 			break;
9984 		}
9985 	}
9986 	return (0);
9987 }
9988 
9989 static int
9990 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
9991 {
9992 	int action;
9993 
9994 	ST_FUNC(ST_DEVINFO, st_check_error);
9995 
9996 	ASSERT(mutex_owned(ST_MUTEX));
9997 
9998 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
9999 
10000 	if (SCBP_C(pkt) == STATUS_RESERVATION_CONFLICT) {
10001 		action = COMMAND_DONE_EACCES;
10002 		un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
10003 	} else if (SCBP(pkt)->sts_busy) {
10004 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
10005 		if ((int)un->un_retry_ct++ < st_retry_count) {
10006 			action = QUE_BUSY_COMMAND;
10007 		} else if ((un->un_rsvd_status &
10008 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
10009 			/*
10010 			 * If this is a command done before reserve is done
10011 			 * don't reset.
10012 			 */
10013 			action = COMMAND_DONE_ERROR;
10014 		} else {
10015 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
10016 			    "unit busy too long\n");
10017 			mutex_exit(ST_MUTEX);
10018 			if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
10019 				(void) scsi_reset(ROUTE, RESET_ALL);
10020 			}
10021 			mutex_enter(ST_MUTEX);
10022 			action = COMMAND_DONE_ERROR;
10023 		}
10024 	} else if (SCBP(pkt)->sts_chk) {
10025 		/*
10026 		 * we should only get here if the auto rqsense failed
10027 		 * thru a uscsi cmd without autorequest sense
10028 		 * so we just try again
10029 		 */
10030 		action = QUE_SENSE;
10031 	} else {
10032 		action = COMMAND_DONE;
10033 	}
10034 	return (action);
10035 }
10036 
10037 static void
10038 st_calc_bnum(struct scsi_tape *un, struct buf *bp)
10039 {
10040 	int nblks;
10041 
10042 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
10043 
10044 	ASSERT(mutex_owned(ST_MUTEX));
10045 
10046 	/* If variable block mode */
10047 	if (un->un_bsize == 0) {
10048 		nblks = ((bp->b_bcount - bp->b_resid  == 0) ? 0 : 1);
10049 		un->un_kbytes_xferred += (bp->b_bcount - bp->b_resid) / ONE_K;
10050 	} else {
10051 		nblks = ((bp->b_bcount - bp->b_resid) / un->un_bsize);
10052 		un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
10053 	}
10054 	un->un_pos.blkno += nblks;
10055 	un->un_pos.lgclblkno += nblks;
10056 }
10057 
10058 static void
10059 st_set_state(struct scsi_tape *un)
10060 {
10061 	struct buf *bp = un->un_runqf;
10062 	struct scsi_pkt *sp = BP_PKT(bp);
10063 	struct uscsi_cmd *ucmd;
10064 
10065 	ST_FUNC(ST_DEVINFO, st_set_state);
10066 
10067 	ASSERT(mutex_owned(ST_MUTEX));
10068 
10069 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10070 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
10071 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
10072 
10073 	if (bp != un->un_sbufp) {
10074 #ifdef STDEBUG
10075 		if (DEBUGGING && sp->pkt_resid) {
10076 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10077 			    "pkt_resid %ld bcount %ld\n",
10078 			    sp->pkt_resid, bp->b_bcount);
10079 		}
10080 #endif
10081 		bp->b_resid = sp->pkt_resid;
10082 		st_calc_bnum(un, bp);
10083 		if (bp->b_flags & B_READ) {
10084 			un->un_lastop = ST_OP_READ;
10085 			un->un_fmneeded = 0;
10086 		} else {
10087 			un->un_lastop = ST_OP_WRITE;
10088 			if (un->un_dp->options & ST_REEL) {
10089 				un->un_fmneeded = 2;
10090 			} else {
10091 				un->un_fmneeded = 1;
10092 			}
10093 		}
10094 		/*
10095 		 * all is honky dory at this point, so let's
10096 		 * readjust the throttle, to increase speed, if we
10097 		 * have not throttled down.
10098 		 */
10099 		if (un->un_throttle) {
10100 			un->un_throttle = un->un_max_throttle;
10101 		}
10102 	} else {
10103 		optype new_lastop;
10104 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
10105 
10106 		un->un_lastop = ST_OP_CTL;
10107 
10108 		switch (cmd) {
10109 		case SCMD_WRITE:
10110 			bp->b_resid = sp->pkt_resid;
10111 			new_lastop = ST_OP_WRITE;
10112 			st_calc_bnum(un, bp);
10113 			if (un->un_dp->options & ST_REEL) {
10114 				un->un_fmneeded = 2;
10115 			} else {
10116 				un->un_fmneeded = 1;
10117 			}
10118 			break;
10119 		case SCMD_READ:
10120 			bp->b_resid = sp->pkt_resid;
10121 			new_lastop = ST_OP_READ;
10122 			st_calc_bnum(un, bp);
10123 			un->un_fmneeded = 0;
10124 			break;
10125 		case SCMD_WRITE_FILE_MARK:
10126 		{
10127 			int fmdone;
10128 
10129 			if (un->un_pos.eof != ST_EOM) {
10130 				un->un_pos.eof = ST_NO_EOF;
10131 			}
10132 			fmdone = (bp->b_bcount - bp->b_resid);
10133 			if (fmdone > 0) {
10134 				un->un_lastop = new_lastop = ST_OP_WEOF;
10135 				un->un_pos.lgclblkno += fmdone;
10136 				un->un_pos.fileno += fmdone;
10137 				un->un_pos.blkno = 0;
10138 			} else {
10139 				new_lastop = ST_OP_CTL;
10140 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
10141 				    "Flushed buffer\n");
10142 			}
10143 			if (fmdone > un->un_fmneeded) {
10144 				un->un_fmneeded = 0;
10145 			} else {
10146 				un->un_fmneeded -= fmdone;
10147 			}
10148 			break;
10149 		}
10150 		case SCMD_REWIND:
10151 			un->un_pos.eof = ST_NO_EOF;
10152 			un->un_pos.fileno = 0;
10153 			un->un_pos.blkno = 0;
10154 			un->un_pos.lgclblkno = 0;
10155 			un->un_pos.pmode = legacy;
10156 			new_lastop = ST_OP_CTL;
10157 			break;
10158 
10159 		case SCMD_SPACE:
10160 		{
10161 			int count;
10162 			long resid;
10163 			int done;
10164 
10165 			count = (int)SPACE_CNT(bp->b_bcount);
10166 			/* if was a uscsi space cmd b_bcount == 0 */
10167 			if (count == 0) {
10168 				count =
10169 				    (sp->pkt_cdbp[2] << 16) |
10170 				    (sp->pkt_cdbp[3] << 8)  |
10171 				    (sp->pkt_cdbp[4]);
10172 			}
10173 			resid = (long)SPACE_CNT(bp->b_resid);
10174 			if (count >= 0) {
10175 				done = (count - resid);
10176 			} else {
10177 				done = ((-count) - resid);
10178 			}
10179 			if (done > 0) {
10180 				un->un_lastop = new_lastop = ST_OP_CTL;
10181 			} else {
10182 				new_lastop = ST_OP_CTL;
10183 			}
10184 
10185 			ST_SPAC(ST_DEVINFO, st_label, SCSI_DEBUG,
10186 			    "space cmd: cdb[1] = %s\n"
10187 			    "space data:       = 0x%lx\n"
10188 			    "space count:      = %d\n"
10189 			    "space resid:      = %ld\n"
10190 			    "spaces done:      = %d\n"
10191 			    "fileno before     = %d\n"
10192 			    "blkno before      = %d\n",
10193 			    space_strs[sp->pkt_cdbp[1] & 7],
10194 			    bp->b_bcount,
10195 			    count, resid, done,
10196 			    un->un_pos.fileno, un->un_pos.blkno);
10197 
10198 			switch (sp->pkt_cdbp[1]) {
10199 			case SPACE_TYPE(SP_FLM):
10200 				/* Space file forward */
10201 				if (count >= 0) {
10202 					if (un->un_pos.eof <= ST_EOF) {
10203 						un->un_pos.eof = ST_NO_EOF;
10204 					}
10205 					un->un_pos.fileno += done;
10206 					un->un_pos.blkno = 0;
10207 					break;
10208 				}
10209 				/* Space file backward */
10210 				if (done > un->un_pos.fileno) {
10211 					un->un_pos.fileno = 0;
10212 					un->un_pos.blkno = 0;
10213 				} else {
10214 					un->un_pos.fileno -= done;
10215 					un->un_pos.blkno = INF;
10216 				}
10217 				break;
10218 			case SPACE_TYPE(SP_BLK):
10219 				/* Space block forward */
10220 				if (count >= 0) {
10221 					un->un_pos.blkno += done;
10222 					break;
10223 				}
10224 				/* Space block backward */
10225 				if (un->un_pos.eof >= ST_EOF_PENDING) {
10226 				/*
10227 				 * we stepped back into
10228 				 * a previous file; we are not
10229 				 * making an effort to pretend that
10230 				 * we are still in the current file
10231 				 * ie. logical == physical position
10232 				 * and leave it to st_ioctl to correct
10233 				 */
10234 					if (done > un->un_pos.blkno) {
10235 						un->un_pos.blkno = 0;
10236 					} else {
10237 						un->un_pos.fileno--;
10238 						un->un_pos.blkno = INF;
10239 					}
10240 				} else {
10241 					un->un_pos.blkno -= done;
10242 				}
10243 				break;
10244 			case SPACE_TYPE(SP_SQFLM):
10245 				un->un_pos.pmode = logical;
10246 				un->un_pos.blkno = 0;
10247 				un->un_lastop = new_lastop = ST_OP_CTL;
10248 				break;
10249 			case SPACE_TYPE(SP_EOD):
10250 				un->un_pos.pmode = logical;
10251 				un->un_pos.eof = ST_EOM;
10252 				un->un_status = KEY_BLANK_CHECK;
10253 				break;
10254 			default:
10255 				un->un_pos.pmode = invalid;
10256 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
10257 				    "Unsupported space cmd: %s\n",
10258 				    space_strs[sp->pkt_cdbp[1] & 7]);
10259 
10260 				un->un_lastop = new_lastop = ST_OP_CTL;
10261 			}
10262 
10263 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10264 			    "after_space rs %ld fil %d blk %d\n",
10265 			    resid, un->un_pos.fileno, un->un_pos.blkno);
10266 
10267 			break;
10268 		}
10269 		case SCMD_LOAD:
10270 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
10271 				un->un_pos.fileno = 0;
10272 				un->un_pos.pmode = legacy;
10273 			} else {
10274 				un->un_state = ST_STATE_OFFLINE;
10275 				un->un_pos.pmode = invalid;
10276 			}
10277 			un->un_density_known = 0;
10278 			un->un_pos.eof = ST_NO_EOF;
10279 			un->un_pos.blkno = 0;
10280 			un->un_lastop = new_lastop = ST_OP_CTL;
10281 			break;
10282 		case SCMD_ERASE:
10283 			un->un_pos.eof = ST_NO_EOF;
10284 			un->un_pos.blkno = 0;
10285 			un->un_pos.fileno = 0;
10286 			un->un_pos.lgclblkno = 0;
10287 			un->un_pos.pmode = legacy;
10288 			new_lastop = ST_OP_CTL;
10289 			break;
10290 		case SCMD_RESERVE:
10291 			un->un_rsvd_status |= ST_RESERVE;
10292 			un->un_rsvd_status &=
10293 			    ~(ST_RELEASE | ST_LOST_RESERVE |
10294 			    ST_RESERVATION_CONFLICT);
10295 			new_lastop = un->un_lastop;
10296 			break;
10297 		case SCMD_RELEASE:
10298 			un->un_rsvd_status |= ST_RELEASE;
10299 			un->un_rsvd_status &=
10300 			    ~(ST_RESERVE | ST_LOST_RESERVE |
10301 			    ST_RESERVATION_CONFLICT);
10302 			new_lastop = ST_OP_CTL;
10303 			break;
10304 		case SCMD_PERSISTENT_RESERVE_IN:
10305 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10306 			    "PGR_IN command\n");
10307 			break;
10308 		case SCMD_PERSISTENT_RESERVE_OUT:
10309 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
10310 			case ST_SA_SCSI3_RESERVE:
10311 			case ST_SA_SCSI3_PREEMPT:
10312 			case ST_SA_SCSI3_PREEMPTANDABORT:
10313 				un->un_rsvd_status |=
10314 				    ST_APPLICATION_RESERVATIONS;
10315 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10316 				    "PGR Reserve and set: entering"
10317 				    " ST_APPLICATION_RESERVATIONS mode");
10318 				break;
10319 			case ST_SA_SCSI3_RELEASE:
10320 			case ST_SA_SCSI3_CLEAR:
10321 				un->un_rsvd_status &=
10322 				    ~ST_APPLICATION_RESERVATIONS;
10323 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10324 				    "PGR Release and reset: exiting"
10325 				    " ST_APPLICATION_RESERVATIONS mode");
10326 				break;
10327 			}
10328 			break;
10329 		case SCMD_TEST_UNIT_READY:
10330 		case SCMD_READ_BLKLIM:
10331 		case SCMD_REQUEST_SENSE:
10332 		case SCMD_INQUIRY:
10333 		case SCMD_RECOVER_BUF:
10334 		case SCMD_MODE_SELECT:
10335 		case SCMD_MODE_SENSE:
10336 		case SCMD_DOORLOCK:
10337 		case SCMD_READ_BUFFER:
10338 		case SCMD_REPORT_DENSITIES:
10339 		case SCMD_LOG_SELECT_G1:
10340 		case SCMD_LOG_SENSE_G1:
10341 		case SCMD_REPORT_LUNS:
10342 		case SCMD_READ_ATTRIBUTE:
10343 		case SCMD_READ_MEDIA_SERIAL:
10344 			new_lastop = ST_OP_CTL;
10345 			break;
10346 		case SCMD_READ_POSITION:
10347 			new_lastop = ST_OP_CTL;
10348 			if (USCSI_CMD(bp)) {
10349 				(void) st_get_read_pos(un, bp);
10350 			}
10351 			break;
10352 		case SCMD_LOCATE:
10353 		case SCMD_LOCATE_G4:
10354 			/* Locate makes position mode no longer legacy */
10355 			un->un_lastop = new_lastop = ST_OP_CTL;
10356 			break;
10357 		default:
10358 			/*
10359 			 * Unknown command, If was USCSI and USCSI_SILENT
10360 			 * flag was not set, set position to unknown.
10361 			 */
10362 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
10363 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
10364 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
10365 				    "unknown cmd 0x%X caused loss of state\n",
10366 				    cmd);
10367 			} else {
10368 				break;
10369 			}
10370 			/* FALLTHROUGH */
10371 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
10372 			un->un_pos.pmode = invalid;
10373 			un->un_lastop = new_lastop = ST_OP_CTL;
10374 			break;
10375 		}
10376 
10377 		/* new_lastop should have been changed */
10378 		ASSERT(new_lastop != ST_OP_NIL);
10379 
10380 		/* If un_lastop should copy new_lastop  */
10381 		if (((un->un_lastop == ST_OP_WRITE) ||
10382 		    (un->un_lastop == ST_OP_WEOF)) &&
10383 		    new_lastop != ST_OP_CTL) {
10384 			un->un_lastop = new_lastop;
10385 		}
10386 	}
10387 
10388 	/*
10389 	 * In the st driver we have a logical and physical file position.
10390 	 * Under BSD behavior, when you get a zero read, the logical position
10391 	 * is before the filemark but after the last record of the file.
10392 	 * The physical position is after the filemark. MTIOCGET should always
10393 	 * return the logical file position.
10394 	 *
10395 	 * The next read gives a silent skip to the next file.
10396 	 * Under SVR4, the logical file position remains before the filemark
10397 	 * until the file is closed or a space operation is performed.
10398 	 * Hence set err_resid and err_file before changing fileno if case
10399 	 * BSD Behaviour.
10400 	 */
10401 	un->un_err_resid = bp->b_resid;
10402 	COPY_POS(&un->un_err_pos, &un->un_pos);
10403 	un->un_retry_ct = 0;
10404 
10405 
10406 	/*
10407 	 * If we've seen a filemark via the last read operation
10408 	 * advance the file counter, but mark things such that
10409 	 * the next read operation gets a zero count. We have
10410 	 * to put this here to handle the case of sitting right
10411 	 * at the end of a tape file having seen the file mark,
10412 	 * but the tape is closed and then re-opened without
10413 	 * any further i/o. That is, the position information
10414 	 * must be updated before a close.
10415 	 */
10416 
10417 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
10418 		/*
10419 		 * If we're a 1/2" tape, and we get a filemark
10420 		 * right on block 0, *AND* we were not in the
10421 		 * first file on the tape, and we've hit logical EOM.
10422 		 * We'll mark the state so that later we do the
10423 		 * right thing (in st_close(), st_strategy() or
10424 		 * st_ioctl()).
10425 		 *
10426 		 */
10427 		if ((un->un_dp->options & ST_REEL) &&
10428 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
10429 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
10430 			un->un_pos.eof = ST_EOT_PENDING;
10431 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10432 			    "eot pending\n");
10433 			un->un_pos.fileno++;
10434 			un->un_pos.blkno = 0;
10435 		} else if (BSD_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 EOF mark is pending and the
10440 			 * bump into the next file awaits the next read
10441 			 * operation (which will return a zero count), or
10442 			 * a close or a space operation, else the bump
10443 			 * into the next file occurs now.
10444 			 */
10445 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10446 			    "resid=%lx, bcount=%lx\n",
10447 			    bp->b_resid, bp->b_bcount);
10448 
10449 			if (bp->b_resid != bp->b_bcount) {
10450 				un->un_pos.eof = ST_EOF;
10451 			} else {
10452 				un->un_silent_skip = 1;
10453 				un->un_pos.eof = ST_NO_EOF;
10454 				un->un_pos.fileno++;
10455 				un->un_pos.lgclblkno++;
10456 				un->un_save_blkno = un->un_pos.blkno;
10457 				un->un_pos.blkno = 0;
10458 			}
10459 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10460 			    "eof of file %d, eof=%d\n",
10461 			    un->un_pos.fileno, un->un_pos.eof);
10462 		} else if (SVR4_BEHAVIOR) {
10463 			/*
10464 			 * If the read of the filemark was a side effect
10465 			 * of reading some blocks (i.e., data was actually
10466 			 * read), then the next read should return 0
10467 			 */
10468 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10469 			    "resid=%lx, bcount=%lx\n",
10470 			    bp->b_resid, bp->b_bcount);
10471 			if (bp->b_resid == bp->b_bcount) {
10472 				un->un_pos.eof = ST_EOF;
10473 			}
10474 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10475 			    "eof of file=%d, eof=%d\n",
10476 			    un->un_pos.fileno, un->un_pos.eof);
10477 		}
10478 	}
10479 }
10480 
10481 /*
10482  * set the correct un_errno, to take corner cases into consideration
10483  */
10484 static void
10485 st_set_pe_errno(struct scsi_tape *un)
10486 {
10487 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
10488 
10489 	ASSERT(mutex_owned(ST_MUTEX));
10490 
10491 	/* if errno is already set, don't reset it */
10492 	if (un->un_errno)
10493 		return;
10494 
10495 	/* here un_errno == 0 */
10496 	/*
10497 	 * if the last transfer before flushing all the
10498 	 * waiting I/O's, was 0 (resid = count), then we
10499 	 * want to give the user an error on all the rest,
10500 	 * so here.  If there was a transfer, we set the
10501 	 * resid and counts to 0, and let it drop through,
10502 	 * giving a zero return.  the next I/O will then
10503 	 * give an error.
10504 	 */
10505 	if (un->un_last_resid == un->un_last_count) {
10506 		switch (un->un_pos.eof) {
10507 		case ST_EOM:
10508 			un->un_errno = ENOMEM;
10509 			break;
10510 		case ST_EOT:
10511 		case ST_EOF:
10512 			un->un_errno = EIO;
10513 			break;
10514 		}
10515 	} else {
10516 		/*
10517 		 * we know they did not have a zero, so make
10518 		 * sure they get one
10519 		 */
10520 		un->un_last_resid = un->un_last_count = 0;
10521 	}
10522 }
10523 
10524 
10525 /*
10526  * send in a marker pkt to terminate flushing of commands by BBA (via
10527  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
10528  */
10529 static void
10530 st_hba_unflush(struct scsi_tape *un)
10531 {
10532 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
10533 
10534 	ASSERT(mutex_owned(ST_MUTEX));
10535 
10536 	if (!un->un_flush_on_errors)
10537 		return;
10538 
10539 #ifdef FLUSH_ON_ERRORS
10540 
10541 	if (!un->un_mkr_pkt) {
10542 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
10543 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
10544 
10545 		/* we slept, so it must be there */
10546 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
10547 	}
10548 
10549 	mutex_exit(ST_MUTEX);
10550 	scsi_transport(un->un_mkr_pkt);
10551 	mutex_enter(ST_MUTEX);
10552 #endif
10553 }
10554 
10555 static char *
10556 st_print_scsi_cmd(char cmd)
10557 {
10558 	char tmp[64];
10559 	char *cpnt;
10560 
10561 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
10562 	/* tmp goes out of scope on return and caller sees garbage */
10563 	if (cpnt == tmp) {
10564 		cpnt = "Unknown Command";
10565 	}
10566 	return (cpnt);
10567 }
10568 
10569 static void
10570 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
10571     char *title, char *cdb)
10572 {
10573 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
10574 	char buf[256];
10575 	int instance = ddi_get_instance(dip);
10576 	struct scsi_tape *un;
10577 
10578 	un = ddi_get_soft_state(st_state, instance);
10579 
10580 	ST_FUNC(dip, st_print_cdb);
10581 
10582 #ifdef DEBUG
10583 	if ((st_debug & 0x180) == 0x100) {
10584 		scsi_log(dip, label, level, "node %s cmd %s\n",
10585 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
10586 		return;
10587 	}
10588 #endif
10589 	(void) sprintf(buf, "%s for cmd(%s)", title, st_print_scsi_cmd(*cdb));
10590 	st_clean_print(dip, label, level, buf, cdb, len);
10591 }
10592 
10593 static void
10594 st_clean_print(dev_info_t *dev, char *label, uint_t level,
10595     char *title, char *data, int len)
10596 {
10597 	int	i;
10598 	int 	c;
10599 	char	*format;
10600 	char	buf[256];
10601 	uchar_t	byte;
10602 
10603 	ST_FUNC(dev, st_clean_print);
10604 
10605 	(void) sprintf(buf, "%s:\n", title);
10606 	scsi_log(dev, label, level, "%s", buf);
10607 	level = CE_CONT;
10608 	for (i = 0; i < len; ) {
10609 		buf[0] = 0;
10610 		for (c = 0; c < 8 && i < len; c++, i++) {
10611 			byte = (uchar_t)data[i];
10612 			if (byte < 0x10)
10613 				format = "0x0%x ";
10614 			else
10615 				format = "0x%x ";
10616 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
10617 		}
10618 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
10619 
10620 		scsi_log(dev, label, level, "%s\n", buf);
10621 	}
10622 }
10623 
10624 /*
10625  * Conditionally enabled debugging
10626  */
10627 #ifdef	STDEBUG
10628 static void
10629 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
10630 {
10631 	char tmpbuf[64];
10632 
10633 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
10634 
10635 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10636 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
10637 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
10638 	    count, count,
10639 	    wait == ASYNC_CMD ? "a" : "");
10640 }
10641 
10642 /*
10643  * Returns pointer to name of minor node name of device 'dev'.
10644  */
10645 static char *
10646 st_dev_name(dev_t dev)
10647 {
10648 	struct scsi_tape *un;
10649 	const char density[] = { 'l', 'm', 'h', 'c' };
10650 	static char name[4];
10651 	minor_t minor;
10652 	int instance;
10653 	int nprt = 0;
10654 
10655 	minor = getminor(dev);
10656 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
10657 	un = ddi_get_soft_state(st_state, instance);
10658 	if (un) {
10659 		ST_FUNC(ST_DEVINFO, st_dev_name);
10660 	}
10661 
10662 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
10663 
10664 	if (minor & MT_BSD) {
10665 		name[++nprt] = 'b';
10666 	}
10667 
10668 	if (minor & MT_NOREWIND) {
10669 		name[++nprt] = 'n';
10670 	}
10671 
10672 	/* NULL terminator */
10673 	name[++nprt] = 0;
10674 
10675 	return (name);
10676 }
10677 #endif	/* STDEBUG */
10678 
10679 /*
10680  * Soft error reporting, so far unique to each drive
10681  *
10682  * Currently supported: exabyte and DAT soft error reporting
10683  */
10684 static int
10685 st_report_exabyte_soft_errors(dev_t dev, int flag)
10686 {
10687 	uchar_t *sensep;
10688 	int amt;
10689 	int rval = 0;
10690 	char cdb[CDB_GROUP0], *c = cdb;
10691 	struct uscsi_cmd *com;
10692 
10693 	GET_SOFT_STATE(dev);
10694 
10695 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
10696 
10697 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10698 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
10699 	    dev, flag);
10700 
10701 	ASSERT(mutex_owned(ST_MUTEX));
10702 
10703 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
10704 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
10705 
10706 	*c++ = SCMD_REQUEST_SENSE;
10707 	*c++ = 0;
10708 	*c++ = 0;
10709 	*c++ = 0;
10710 	*c++ = TAPE_SENSE_LENGTH;
10711 	/*
10712 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
10713 	 */
10714 	*c   = (char)0x80;
10715 
10716 	com->uscsi_cdb = cdb;
10717 	com->uscsi_cdblen = CDB_GROUP0;
10718 	com->uscsi_bufaddr = (caddr_t)sensep;
10719 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
10720 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
10721 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10722 
10723 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
10724 	if (rval || com->uscsi_status) {
10725 		goto done;
10726 	}
10727 
10728 	/*
10729 	 * was there enough data?
10730 	 */
10731 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
10732 
10733 	if ((amt >= 19) && un->un_kbytes_xferred) {
10734 		uint_t count, error_rate;
10735 		uint_t rate;
10736 
10737 		if (sensep[21] & CLN) {
10738 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10739 			    "Periodic head cleaning required");
10740 		}
10741 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
10742 			goto done;
10743 		}
10744 		/*
10745 		 * check if soft error reporting needs to be done.
10746 		 */
10747 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
10748 		count &= 0xffffff;
10749 		error_rate = (count * 100)/un->un_kbytes_xferred;
10750 
10751 #ifdef	STDEBUG
10752 		if (st_soft_error_report_debug) {
10753 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
10754 			    "Exabyte Soft Error Report:\n");
10755 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10756 			    "read/write error counter: %d\n", count);
10757 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10758 			    "number of bytes transferred: %dK\n",
10759 			    un->un_kbytes_xferred);
10760 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10761 			    "error_rate: %d%%\n", error_rate);
10762 
10763 			if (amt >= 22) {
10764 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10765 				    "unit sense: 0x%b 0x%b 0x%b\n",
10766 				    sensep[19], SENSE_19_BITS,
10767 				    sensep[20], SENSE_20_BITS,
10768 				    sensep[21], SENSE_21_BITS);
10769 			}
10770 			if (amt >= 27) {
10771 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10772 				    "tracking retry counter: %d\n",
10773 				    sensep[26]);
10774 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10775 				    "read/write retry counter: %d\n",
10776 				    sensep[27]);
10777 			}
10778 		}
10779 #endif
10780 
10781 		if (flag & FWRITE) {
10782 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
10783 		} else {
10784 			rate = EXABYTE_READ_ERROR_THRESHOLD;
10785 		}
10786 		if (error_rate >= rate) {
10787 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10788 			    "Soft error rate (%d%%) during %s was too high",
10789 			    error_rate,
10790 			    ((flag & FWRITE) ? wrg_str : rdg_str));
10791 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10792 			    "Please, replace tape cartridge\n");
10793 		}
10794 	}
10795 
10796 done:
10797 	kmem_free(com, sizeof (*com));
10798 	kmem_free(sensep, TAPE_SENSE_LENGTH);
10799 
10800 	if (rval != 0) {
10801 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10802 		    "exabyte soft error reporting failed\n");
10803 	}
10804 	return (rval);
10805 }
10806 
10807 /*
10808  * this is very specific to Archive 4mm dat
10809  */
10810 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
10811 
10812 static int
10813 st_report_dat_soft_errors(dev_t dev, int flag)
10814 {
10815 	uchar_t *sensep;
10816 	int amt, i;
10817 	int rval = 0;
10818 	char cdb[CDB_GROUP1], *c = cdb;
10819 	struct uscsi_cmd *com;
10820 
10821 	GET_SOFT_STATE(dev);
10822 
10823 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
10824 
10825 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10826 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
10827 
10828 	ASSERT(mutex_owned(ST_MUTEX));
10829 
10830 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
10831 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
10832 
10833 	*c++ = SCMD_LOG_SENSE_G1;
10834 	*c++ = 0;
10835 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
10836 	*c++ = 0;
10837 	*c++ = 0;
10838 	*c++ = 0;
10839 	*c++ = 2;
10840 	*c++ = 0;
10841 	*c++ = (char)LOG_SENSE_LENGTH;
10842 	*c   = 0;
10843 	com->uscsi_cdb    = cdb;
10844 	com->uscsi_cdblen  = CDB_GROUP1;
10845 	com->uscsi_bufaddr = (caddr_t)sensep;
10846 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
10847 	com->uscsi_flags   =
10848 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
10849 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10850 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
10851 	if (rval) {
10852 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10853 		    "DAT soft error reporting failed\n");
10854 	}
10855 	if (rval || com->uscsi_status) {
10856 		goto done;
10857 	}
10858 
10859 	/*
10860 	 * was there enough data?
10861 	 */
10862 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
10863 
10864 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
10865 		int total, retries, param_code;
10866 
10867 		total = -1;
10868 		retries = -1;
10869 		amt = sensep[3] + 4;
10870 
10871 
10872 #ifdef STDEBUG
10873 		if (st_soft_error_report_debug) {
10874 			(void) printf("logsense:");
10875 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
10876 				if (i % 16 == 0) {
10877 					(void) printf("\t\n");
10878 				}
10879 				(void) printf(" %x", sensep[i]);
10880 			}
10881 			(void) printf("\n");
10882 		}
10883 #endif
10884 
10885 		/*
10886 		 * parse the param_codes
10887 		 */
10888 		if (sensep[0] == 2 || sensep[0] == 3) {
10889 			for (i = 4; i < amt; i++) {
10890 				param_code = (sensep[i++] << 8);
10891 				param_code += sensep[i++];
10892 				i++; /* skip control byte */
10893 				if (param_code == 5) {
10894 					if (sensep[i++] == 4) {
10895 						total = (sensep[i++] << 24);
10896 						total += (sensep[i++] << 16);
10897 						total += (sensep[i++] << 8);
10898 						total += sensep[i];
10899 					}
10900 				} else if (param_code == 0x8007) {
10901 					if (sensep[i++] == 2) {
10902 						retries = sensep[i++] << 8;
10903 						retries += sensep[i];
10904 					}
10905 				} else {
10906 					i += sensep[i];
10907 				}
10908 			}
10909 		}
10910 
10911 		/*
10912 		 * if the log sense returned valid numbers then determine
10913 		 * the read and write error thresholds based on the amount of
10914 		 * data transferred
10915 		 */
10916 
10917 		if (total > 0 && retries > 0) {
10918 			short normal_retries = 0;
10919 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10920 			    "total xferred (%s) =%x, retries=%x\n",
10921 			    ((flag & FWRITE) ? wrg_str : rdg_str),
10922 			    total, retries);
10923 
10924 			if (flag & FWRITE) {
10925 				if (total <=
10926 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
10927 					normal_retries =
10928 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
10929 				} else {
10930 					normal_retries =
10931 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
10932 				}
10933 			} else {
10934 				if (total <=
10935 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
10936 					normal_retries =
10937 					    DAT_SMALL_READ_ERROR_THRESHOLD;
10938 				} else {
10939 					normal_retries =
10940 					    DAT_LARGE_READ_ERROR_THRESHOLD;
10941 				}
10942 			}
10943 
10944 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10945 			"normal retries=%d\n", normal_retries);
10946 
10947 			if (retries >= normal_retries) {
10948 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
10949 				    "Soft error rate (retries = %d) during "
10950 				    "%s was too high",  retries,
10951 				    ((flag & FWRITE) ? wrg_str : rdg_str));
10952 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10953 				    "Periodic head cleaning required "
10954 				    "and/or replace tape cartridge\n");
10955 			}
10956 
10957 		} else if (total == -1 || retries == -1) {
10958 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10959 			    "log sense parameter code does not make sense\n");
10960 		}
10961 	}
10962 
10963 	/*
10964 	 * reset all values
10965 	 */
10966 	c = cdb;
10967 	*c++ = SCMD_LOG_SELECT_G1;
10968 	*c++ = 2;	/* this resets all values */
10969 	*c++ = (char)0xc0;
10970 	*c++ = 0;
10971 	*c++ = 0;
10972 	*c++ = 0;
10973 	*c++ = 0;
10974 	*c++ = 0;
10975 	*c++ = 0;
10976 	*c   = 0;
10977 	com->uscsi_bufaddr = NULL;
10978 	com->uscsi_buflen  = 0;
10979 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
10980 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
10981 	if (rval) {
10982 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10983 		    "DAT soft error reset failed\n");
10984 	}
10985 done:
10986 	kmem_free(com, sizeof (*com));
10987 	kmem_free(sensep, LOG_SENSE_LENGTH);
10988 	return (rval);
10989 }
10990 
10991 static int
10992 st_report_soft_errors(dev_t dev, int flag)
10993 {
10994 	GET_SOFT_STATE(dev);
10995 
10996 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
10997 
10998 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10999 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
11000 
11001 	ASSERT(mutex_owned(ST_MUTEX));
11002 
11003 	switch (un->un_dp->type) {
11004 	case ST_TYPE_EXB8500:
11005 	case ST_TYPE_EXABYTE:
11006 		return (st_report_exabyte_soft_errors(dev, flag));
11007 		/*NOTREACHED*/
11008 	case ST_TYPE_PYTHON:
11009 		return (st_report_dat_soft_errors(dev, flag));
11010 		/*NOTREACHED*/
11011 	default:
11012 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
11013 		return (-1);
11014 	}
11015 }
11016 
11017 /*
11018  * persistent error routines
11019  */
11020 
11021 /*
11022  * enable persistent errors, and set the throttle appropriately, checking
11023  * for flush-on-errors capability
11024  */
11025 static void
11026 st_turn_pe_on(struct scsi_tape *un)
11027 {
11028 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
11029 
11030 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
11031 	ASSERT(mutex_owned(ST_MUTEX));
11032 
11033 	un->un_persistence = 1;
11034 
11035 	/*
11036 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
11037 	 * enabled.  This will simplify the error handling for request senses
11038 	 */
11039 
11040 	if (un->un_arq_enabled && un->un_untagged_qing) {
11041 		uchar_t f_o_e;
11042 
11043 		mutex_exit(ST_MUTEX);
11044 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
11045 		    1 : 0;
11046 		mutex_enter(ST_MUTEX);
11047 
11048 		un->un_flush_on_errors = f_o_e;
11049 	} else {
11050 		un->un_flush_on_errors = 0;
11051 	}
11052 
11053 	if (un->un_flush_on_errors)
11054 		un->un_max_throttle = (uchar_t)st_max_throttle;
11055 	else
11056 		un->un_max_throttle = 1;
11057 
11058 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
11059 		un->un_max_throttle = 1;
11060 
11061 	/* this will send a marker pkt */
11062 	CLEAR_PE(un);
11063 }
11064 
11065 /*
11066  * This turns persistent errors permanently off
11067  */
11068 static void
11069 st_turn_pe_off(struct scsi_tape *un)
11070 {
11071 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
11072 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
11073 	ASSERT(mutex_owned(ST_MUTEX));
11074 
11075 	/* turn it off for good */
11076 	un->un_persistence = 0;
11077 
11078 	/* this will send a marker pkt */
11079 	CLEAR_PE(un);
11080 
11081 	/* turn off flush on error capability, if enabled */
11082 	if (un->un_flush_on_errors) {
11083 		mutex_exit(ST_MUTEX);
11084 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
11085 		mutex_enter(ST_MUTEX);
11086 	}
11087 
11088 
11089 	un->un_flush_on_errors = 0;
11090 }
11091 
11092 /*
11093  * This clear persistent errors, allowing more commands through, and also
11094  * sending a marker packet.
11095  */
11096 static void
11097 st_clear_pe(struct scsi_tape *un)
11098 {
11099 	ST_FUNC(ST_DEVINFO, st_clear_pe);
11100 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
11101 	ASSERT(mutex_owned(ST_MUTEX));
11102 
11103 	un->un_persist_errors = 0;
11104 	un->un_throttle = un->un_last_throttle = 1;
11105 	un->un_errno = 0;
11106 	st_hba_unflush(un);
11107 }
11108 
11109 /*
11110  * This will flag persistent errors, shutting everything down, if the
11111  * application had enabled persistent errors via MTIOCPERSISTENT
11112  */
11113 static void
11114 st_set_pe_flag(struct scsi_tape *un)
11115 {
11116 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
11117 	ASSERT(mutex_owned(ST_MUTEX));
11118 
11119 	if (un->un_persistence) {
11120 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
11121 		un->un_persist_errors = 1;
11122 		un->un_throttle = un->un_last_throttle = 0;
11123 	}
11124 }
11125 
11126 /*
11127  * List of commands that are allowed to be done while another host holds
11128  * the reservation.
11129  */
11130 struct {
11131 	uchar_t cmd;
11132 	uchar_t byte;	/* byte to look for data */
11133 	uint32_t mask;	/* bits that matter in the above data */
11134 } rcmds[] = {
11135 	{ SCMD_TEST_UNIT_READY, 0, 0 }, /* may fail on older drives */
11136 	{ SCMD_REQUEST_SENSE, 0, 0 },
11137 	{ SCMD_READ_BLKLIM, 0, 0 },
11138 	{ SCMD_INQUIRY, 0, 0 },
11139 	{ SCMD_RESERVE, 0, 0 },
11140 	{ SCMD_RELEASE, 0, 0 },
11141 	{ SCMD_DOORLOCK, 4, 3 },	/* allow (unlock) media access only */
11142 	{ SCMD_REPORT_DENSITIES, 0, 0 },
11143 	{ SCMD_LOG_SENSE_G1, 0, 0 },
11144 	{ SCMD_PERSISTENT_RESERVE_IN, 0, 0 },
11145 	{ SCMD_PERSISTENT_RESERVE_OUT, 0, 0 },
11146 	{ SCMD_REPORT_LUNS, 0, 0 }
11147 };
11148 
11149 static int
11150 st_do_reserve(struct scsi_tape *un)
11151 {
11152 	int rval;
11153 
11154 	ST_FUNC(ST_DEVINFO, st_do_reserve);
11155 
11156 	/*
11157 	 * Issue a Throw-Away reserve command to clear the
11158 	 * check condition.
11159 	 * If the current behaviour of reserve/release is to
11160 	 * hold reservation across opens , and if a Bus reset
11161 	 * has been issued between opens then this command
11162 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
11163 	 * In this case return an EACCES so that user knows that
11164 	 * reservation has been lost in between opens.
11165 	 * If this error is not returned and we continue with
11166 	 * successful open , then user may think position of the
11167 	 * tape is still the same but inreality we would rewind the
11168 	 * tape and continue from BOT.
11169 	 */
11170 	rval = st_reserve_release(un, ST_RESERVE);
11171 	if (rval) {
11172 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
11173 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
11174 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
11175 			un->un_errno = EACCES;
11176 			return (EACCES);
11177 		}
11178 		rval = st_reserve_release(un, ST_RESERVE);
11179 	}
11180 	if (rval == 0) {
11181 		un->un_rsvd_status |= ST_INIT_RESERVE;
11182 	}
11183 
11184 	return (rval);
11185 }
11186 
11187 static int
11188 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, caddr_t cdb)
11189 {
11190 	int i;
11191 	int rval = 0;
11192 
11193 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
11194 
11195 	/*
11196 	 * If already reserved no need to do it again.
11197 	 * Also if Reserve and Release are disabled Just return.
11198 	 */
11199 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ||
11200 	    (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
11201 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11202 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
11203 		    st_print_scsi_cmd((uchar_t)cdb[0]));
11204 		return (0);
11205 	}
11206 
11207 	/* See if command is on the list */
11208 	for (i = 0; i < ST_NUM_MEMBERS(rcmds); i++) {
11209 		if ((uchar_t)cdb[0] == rcmds[i].cmd) {
11210 			/*
11211 			 * cmd is on list.
11212 			 * if byte is zero always allowed.
11213 			 */
11214 			if (rcmds[i].byte == 0) {
11215 				return (rval);
11216 			}
11217 			if (((cdb[rcmds[i].byte]) & (rcmds[i].mask)) == 0) {
11218 				return (rval);
11219 			}
11220 			break;
11221 		}
11222 	}
11223 
11224 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11225 	    "Command %s requires reservation", st_print_scsi_cmd(cdb[0]));
11226 
11227 	rval = st_do_reserve(un);
11228 
11229 	return (rval);
11230 }
11231 
11232 static int
11233 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
11234 {
11235 	int i;
11236 	int rval = 0;
11237 
11238 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
11239 
11240 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ||
11241 	    (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
11242 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11243 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
11244 		    st_print_scsi_cmd(cmd));
11245 		return (0);
11246 	}
11247 
11248 	/* See if command is on the list */
11249 	for (i = 0; i < ST_NUM_MEMBERS(rcmds); i++) {
11250 		if (cmd == rcmds[i].cmd) {
11251 			/*
11252 			 * cmd is on list.
11253 			 * if byte is zero always allowed.
11254 			 */
11255 			if (rcmds[i].byte == 0) {
11256 				return (rval);
11257 			}
11258 			if (((rcmds[i].mask) & cnt) == 0) {
11259 				return (rval);
11260 			}
11261 			break;
11262 		}
11263 	}
11264 
11265 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
11266 	    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
11267 
11268 	rval = st_do_reserve(un);
11269 
11270 	return (rval);
11271 }
11272 
11273 static int
11274 st_reserve_release(struct scsi_tape *un, int cmd)
11275 {
11276 	struct uscsi_cmd	uscsi_cmd;
11277 	struct uscsi_cmd	*com = &uscsi_cmd;
11278 	int			rval;
11279 	char			cdb[CDB_GROUP0];
11280 
11281 
11282 
11283 	ST_FUNC(ST_DEVINFO, st_reserve_release);
11284 
11285 	ASSERT(mutex_owned(ST_MUTEX));
11286 
11287 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11288 	    "st_reserve_release: %s \n",
11289 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
11290 
11291 	bzero(cdb, CDB_GROUP0);
11292 	if (cmd == ST_RELEASE) {
11293 		cdb[0] = SCMD_RELEASE;
11294 	} else {
11295 		cdb[0] = SCMD_RESERVE;
11296 	}
11297 	bzero(com, sizeof (struct uscsi_cmd));
11298 	com->uscsi_flags = USCSI_WRITE;
11299 	com->uscsi_cdb = cdb;
11300 	com->uscsi_cdblen = CDB_GROUP0;
11301 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11302 
11303 	rval = st_ioctl_cmd(un->un_dev, com, FKIOCTL);
11304 
11305 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11306 	    "st_reserve_release: rval(1)=%d\n", rval);
11307 
11308 	if (rval) {
11309 		if (com->uscsi_status == STATUS_RESERVATION_CONFLICT) {
11310 			rval = EACCES;
11311 		}
11312 		/*
11313 		 * dynamically turn off reserve/release support
11314 		 * in case of drives which do not support
11315 		 * reserve/release command(ATAPI drives).
11316 		 */
11317 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
11318 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
11319 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
11320 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11321 				    "Tape unit does not support "
11322 				    "reserve/release \n");
11323 			}
11324 			rval = 0;
11325 		}
11326 	}
11327 	return (rval);
11328 }
11329 
11330 static int
11331 st_take_ownership(dev_t dev)
11332 {
11333 	int rval;
11334 
11335 	GET_SOFT_STATE(dev);
11336 
11337 	ST_FUNC(ST_DEVINFO, st_take_ownership);
11338 
11339 	ASSERT(mutex_owned(ST_MUTEX));
11340 
11341 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11342 	    "st_take_ownership: Entering ...\n");
11343 
11344 
11345 	rval = st_reserve_release(un, ST_RESERVE);
11346 	/*
11347 	 * XXX -> Should reset be done only if we get EACCES.
11348 	 * .
11349 	 */
11350 	if (rval) {
11351 		mutex_exit(ST_MUTEX);
11352 		if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
11353 			if (scsi_reset(ROUTE, RESET_ALL) == 0) {
11354 				mutex_enter(ST_MUTEX);
11355 				return (EIO);
11356 			}
11357 		}
11358 		mutex_enter(ST_MUTEX);
11359 		un->un_rsvd_status &=
11360 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
11361 
11362 		mutex_exit(ST_MUTEX);
11363 		delay(drv_usectohz(ST_RESERVATION_DELAY));
11364 		mutex_enter(ST_MUTEX);
11365 		/*
11366 		 * remove the check condition.
11367 		 */
11368 		(void) st_reserve_release(un, ST_RESERVE);
11369 		if ((rval = st_reserve_release(un, ST_RESERVE)) != 0) {
11370 			if ((st_reserve_release(un, ST_RESERVE)) != 0) {
11371 				rval = (un->un_rsvd_status &
11372 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
11373 				return (rval);
11374 			}
11375 		}
11376 		/*
11377 		 * Set tape state to ST_STATE_OFFLINE , in case if
11378 		 * the user wants to continue and start using
11379 		 * the tape.
11380 		 */
11381 		un->un_state = ST_STATE_OFFLINE;
11382 		un->un_rsvd_status |= ST_INIT_RESERVE;
11383 	}
11384 	return (rval);
11385 }
11386 
11387 static int
11388 st_create_errstats(struct scsi_tape *un, int instance)
11389 {
11390 	char	kstatname[KSTAT_STRLEN];
11391 
11392 	ST_FUNC(ST_DEVINFO, st_create_errstats);
11393 
11394 	/*
11395 	 * Create device error kstats
11396 	 */
11397 
11398 	if (un->un_errstats == (kstat_t *)0) {
11399 		(void) sprintf(kstatname, "st%d,err", instance);
11400 		un->un_errstats = kstat_create("sterr", instance, kstatname,
11401 		    "device_error", KSTAT_TYPE_NAMED,
11402 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
11403 		    KSTAT_FLAG_PERSISTENT);
11404 
11405 		if (un->un_errstats) {
11406 			struct st_errstats	*stp;
11407 
11408 			stp = (struct st_errstats *)un->un_errstats->ks_data;
11409 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
11410 			    KSTAT_DATA_ULONG);
11411 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
11412 			    KSTAT_DATA_ULONG);
11413 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
11414 			    KSTAT_DATA_ULONG);
11415 			kstat_named_init(&stp->st_vid, "Vendor",
11416 			    KSTAT_DATA_CHAR);
11417 			kstat_named_init(&stp->st_pid, "Product",
11418 			    KSTAT_DATA_CHAR);
11419 			kstat_named_init(&stp->st_revision, "Revision",
11420 			    KSTAT_DATA_CHAR);
11421 			kstat_named_init(&stp->st_serial, "Serial No",
11422 			    KSTAT_DATA_CHAR);
11423 			un->un_errstats->ks_private = un;
11424 			un->un_errstats->ks_update = nulldev;
11425 			kstat_install(un->un_errstats);
11426 			/*
11427 			 * Fill in the static data
11428 			 */
11429 			(void) strncpy(&stp->st_vid.value.c[0],
11430 			    ST_INQUIRY->inq_vid, 8);
11431 			/*
11432 			 * XXX:  Emulex MT-02 (and emulators) predates
11433 			 *	 SCSI-1 and has no vid & pid inquiry data.
11434 			 */
11435 			if (ST_INQUIRY->inq_len != 0) {
11436 				(void) strncpy(&stp->st_pid.value.c[0],
11437 				    ST_INQUIRY->inq_pid, 16);
11438 				(void) strncpy(&stp->st_revision.value.c[0],
11439 				    ST_INQUIRY->inq_revision, 4);
11440 				(void) strncpy(&stp->st_serial.value.c[0],
11441 				    ST_INQUIRY->inq_serial, 12);
11442 			}
11443 		}
11444 	}
11445 	return (0);
11446 }
11447 
11448 static int
11449 st_validate_tapemarks(struct scsi_tape *un, tapepos_t *pos)
11450 {
11451 	dev_t dev;
11452 	int rval;
11453 
11454 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
11455 
11456 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
11457 	ASSERT(mutex_owned(ST_MUTEX));
11458 
11459 	/* Can't restore an invalid position */
11460 	if (pos->pmode == invalid) {
11461 		return (4);
11462 	}
11463 
11464 	/*
11465 	 * Assumtions:
11466 	 *	If a position was read and is in logical position mode.
11467 	 *	If a drive supports read position it supports locate.
11468 	 *	If the read position type is not NO_POS. even though
11469 	 *	   a read position make not have been attemped yet.
11470 	 *
11471 	 *	The drive can locate to the position.
11472 	 */
11473 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
11474 		/*
11475 		 * If position mode is logical or legacy mode try
11476 		 * to locate there as it is faster.
11477 		 * If it fails try the old way.
11478 		 */
11479 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11480 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
11481 		    pos->lgclblkno);
11482 
11483 		if (st_logical_block_locate(un, pos->lgclblkno, pos->partition)
11484 		    == 0) {
11485 			/* Assume we are there copy rest of position back */
11486 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
11487 				COPY_POS(&un->un_pos, pos);
11488 			}
11489 			return (0);
11490 		}
11491 
11492 		/*
11493 		 * If logical block locate failed to restore a logical
11494 		 * position, can't recover.
11495 		 */
11496 		if (pos->pmode == logical) {
11497 			return (-1);
11498 		}
11499 	}
11500 
11501 	dev = un->un_dev;
11502 
11503 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11504 	    "Restoring tape position at fileno=%x, blkno=%x....",
11505 	    pos->fileno, pos->blkno);
11506 
11507 	/*
11508 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
11509 	 * so as not to rewind tape on RESETS: Gee, Has life ever
11510 	 * been simple in tape land ?
11511 	 */
11512 	rval = st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
11513 	if (rval) {
11514 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
11515 		"Failed to restore the last file and block position: In"
11516 		" this state, Tape will be loaded at BOT during next open");
11517 		un->un_pos.pmode = invalid;
11518 		return (rval);
11519 	}
11520 
11521 	/* If the position was as the result of back space file */
11522 	if (pos->blkno > (INF / 2)) {
11523 		/* Go one extra file forward */
11524 		pos->fileno++;
11525 		/* Figure how many blocks to back into the previous file */
11526 		pos->blkno = -(INF - pos->blkno);
11527 	}
11528 
11529 	/* Go to requested fileno */
11530 	if (pos->fileno) {
11531 		rval = st_cmd(dev, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
11532 		if (rval) {
11533 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11534 			    "Failed to restore the last file position: In this "
11535 			    " state, Tape will be loaded at BOT during next"
11536 			    " open %d", __LINE__);
11537 			un->un_pos.pmode = invalid;
11538 			pos->pmode = invalid;
11539 			return (rval);
11540 		}
11541 	}
11542 
11543 	/*
11544 	 * If backing into a file we already did an extra file forward.
11545 	 * Now we have to back over the filemark to get to the end of
11546 	 * the previous file. The blkno has been ajusted to a negative
11547 	 * value so we will get to the expected location.
11548 	 */
11549 	if (pos->blkno) {
11550 		rval = st_cmd(dev, SCMD_SPACE, Fmk(-1), SYNC_CMD);
11551 		if (rval) {
11552 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
11553 			    "Failed to restore the last file position: In this "
11554 			    " state, Tape will be loaded at BOT during next"
11555 			    " open %d", __LINE__);
11556 			un->un_pos.pmode = invalid;
11557 			pos->pmode = invalid;
11558 			return (rval);
11559 		}
11560 	}
11561 
11562 	/*
11563 	 * The position mode, block and fileno should be correct,
11564 	 * This updates eof and logical position information.
11565 	 */
11566 	un->un_pos.eof = pos->eof;
11567 	un->un_pos.lgclblkno = pos->lgclblkno;
11568 
11569 	return (0);
11570 }
11571 
11572 /*
11573  * check sense key, ASC, ASCQ in order to determine if the tape needs
11574  * to be ejected
11575  */
11576 
11577 static int
11578 st_check_asc_ascq(struct scsi_tape *un)
11579 {
11580 	struct scsi_extended_sense *sensep = ST_RQSENSE;
11581 	struct tape_failure_code   *code;
11582 
11583 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
11584 
11585 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
11586 		if ((code->key  == sensep->es_key) &&
11587 		    (code->add_code  == sensep->es_add_code) &&
11588 		    (code->qual_code == sensep->es_qual_code))
11589 			return (1);
11590 	}
11591 	return (0);
11592 }
11593 
11594 /*
11595  * st_logpage_supported() sends a Log Sense command with
11596  * page code = 0 = Supported Log Pages Page to the device,
11597  * to see whether the page 'page' is supported.
11598  * Return values are:
11599  * -1 if the Log Sense command fails
11600  * 0 if page is not supported
11601  * 1 if page is supported
11602  */
11603 
11604 static int
11605 st_logpage_supported(dev_t dev, uchar_t page)
11606 {
11607 	uchar_t *sp, *sensep;
11608 	unsigned length;
11609 	struct uscsi_cmd *com;
11610 	int rval;
11611 	char cdb[CDB_GROUP1] = {
11612 		SCMD_LOG_SENSE_G1,
11613 		0,
11614 		SUPPORTED_LOG_PAGES_PAGE,
11615 		0,
11616 		0,
11617 		0,
11618 		0,
11619 		0,
11620 		(char)LOG_SENSE_LENGTH,
11621 		0
11622 	};
11623 
11624 	GET_SOFT_STATE(dev);
11625 
11626 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
11627 
11628 	ASSERT(mutex_owned(ST_MUTEX));
11629 
11630 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11631 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
11632 
11633 	com->uscsi_cdb = cdb;
11634 	com->uscsi_cdblen = CDB_GROUP1;
11635 	com->uscsi_bufaddr = (caddr_t)sensep;
11636 	com->uscsi_buflen = LOG_SENSE_LENGTH;
11637 	com->uscsi_flags =
11638 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11639 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11640 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11641 	if (rval || com->uscsi_status) {
11642 		/* uscsi-command failed */
11643 		rval = -1;
11644 	} else {
11645 
11646 		sp = sensep + 3;
11647 
11648 		for (length = *sp++; length > 0; length--, sp++) {
11649 
11650 			if (*sp == page) {
11651 				rval = 1;
11652 				break;
11653 			}
11654 		}
11655 	}
11656 	kmem_free(com, sizeof (struct uscsi_cmd));
11657 	kmem_free(sensep, LOG_SENSE_LENGTH);
11658 	return (rval);
11659 }
11660 
11661 
11662 /*
11663  * st_check_clean_bit() gets the status of the tape's cleaning bit.
11664  *
11665  * If the device does support the TapeAlert log page, then the cleaning bit
11666  * information will be read from this page. Otherwise we will see if one of
11667  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
11668  * the device, which means, that we can get the cleaning bit information via
11669  * a RequestSense command.
11670  * If both methods of getting cleaning bit information are not supported
11671  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
11672  * returns with
11673  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
11674  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
11675  * If the call to st_ioctl_cmd() to do the Log Sense or the Request Sense
11676  * command fails, or if the amount of Request Sense data is not enough, then
11677  *  st_check_clean_bit() returns with -1.
11678  */
11679 
11680 static int
11681 st_check_clean_bit(dev_t dev)
11682 {
11683 	int rval = 0;
11684 
11685 	GET_SOFT_STATE(dev);
11686 
11687 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
11688 
11689 	ASSERT(mutex_owned(ST_MUTEX));
11690 
11691 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
11692 		return (rval);
11693 	}
11694 
11695 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
11696 
11697 		rval = st_logpage_supported(dev, TAPE_SEQUENTIAL_PAGE);
11698 		if (rval == 1) {
11699 
11700 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
11701 		}
11702 
11703 		rval = st_logpage_supported(dev, TAPE_ALERT_PAGE);
11704 		if (rval == 1) {
11705 
11706 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
11707 		}
11708 
11709 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
11710 
11711 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
11712 		}
11713 	}
11714 
11715 	rval = 0;
11716 
11717 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
11718 
11719 		rval = st_check_sequential_clean_bit(dev);
11720 	}
11721 
11722 	if ((rval <= 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
11723 
11724 		rval = st_check_alert_flags(dev);
11725 	}
11726 
11727 	if ((rval <= 0) && (un->un_dp->options & ST_CLN_MASK)) {
11728 
11729 		rval = st_check_sense_clean_bit(dev);
11730 	}
11731 
11732 	if (rval < 0) {
11733 		return (rval);
11734 	}
11735 
11736 	/*
11737 	 * If found a supported means to check need to clean.
11738 	 */
11739 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
11740 
11741 		/*
11742 		 * head needs to be cleaned.
11743 		 */
11744 		if (rval & MTF_TAPE_HEAD_DIRTY) {
11745 
11746 			/*
11747 			 * Print log message only first time
11748 			 * found needing cleaned.
11749 			 */
11750 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
11751 
11752 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
11753 				    "Periodic head cleaning required");
11754 
11755 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
11756 			}
11757 
11758 		} else {
11759 
11760 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
11761 		}
11762 	}
11763 
11764 	return (rval);
11765 }
11766 
11767 
11768 static int
11769 st_check_sequential_clean_bit(dev_t dev)
11770 {
11771 	int rval;
11772 	int ix;
11773 	ushort_t parameter;
11774 	struct uscsi_cmd *cmd;
11775 	struct log_sequential_page *sp;
11776 	struct log_sequential_page_parameter *prm;
11777 	char cdb[CDB_GROUP1] = {
11778 		SCMD_LOG_SENSE_G1,
11779 		0,
11780 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
11781 		0,
11782 		0,
11783 		0,
11784 		0,
11785 		(char)(sizeof (struct log_sequential_page) >> 8),
11786 		(char)(sizeof (struct log_sequential_page)),
11787 		0
11788 	};
11789 
11790 	GET_SOFT_STATE(dev);
11791 
11792 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
11793 
11794 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11795 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
11796 
11797 	cmd->uscsi_flags   =
11798 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11799 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
11800 	cmd->uscsi_cdb	   = cdb;
11801 	cmd->uscsi_cdblen  = CDB_GROUP1;
11802 	cmd->uscsi_bufaddr = (caddr_t)sp;
11803 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
11804 
11805 	rval = st_ioctl_cmd(dev, cmd, FKIOCTL);
11806 
11807 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
11808 
11809 		rval = -1;
11810 
11811 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
11812 
11813 		rval = -1;
11814 	}
11815 
11816 	prm = &sp->param[0];
11817 
11818 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
11819 
11820 		if (prm->log_param.length == 0) {
11821 			break;
11822 		}
11823 
11824 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
11825 		    (prm->log_param.pc_lo & 0xff));
11826 
11827 		if (parameter == SEQUENTIAL_NEED_CLN) {
11828 
11829 			rval = MTF_TAPE_CLN_SUPPORTED;
11830 			if (prm->param_value[prm->log_param.length - 1]) {
11831 
11832 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11833 				    "sequential log says head dirty\n");
11834 				rval |= MTF_TAPE_HEAD_DIRTY;
11835 			}
11836 		}
11837 		prm = (struct log_sequential_page_parameter *)
11838 		    &prm->param_value[prm->log_param.length];
11839 	}
11840 
11841 	kmem_free(cmd, sizeof (struct uscsi_cmd));
11842 	kmem_free(sp,  sizeof (struct log_sequential_page));
11843 
11844 	return (rval);
11845 }
11846 
11847 
11848 static int
11849 st_check_alert_flags(dev_t dev)
11850 {
11851 	struct st_tape_alert *ta;
11852 	struct uscsi_cmd *com;
11853 	unsigned ix, length;
11854 	int rval;
11855 	tape_alert_flags flag;
11856 	char cdb[CDB_GROUP1] = {
11857 		SCMD_LOG_SENSE_G1,
11858 		0,
11859 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
11860 		0,
11861 		0,
11862 		0,
11863 		0,
11864 		(char)(sizeof (struct st_tape_alert) >> 8),
11865 		(char)(sizeof (struct st_tape_alert)),
11866 		0
11867 	};
11868 
11869 	GET_SOFT_STATE(dev);
11870 
11871 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
11872 
11873 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11874 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
11875 
11876 	com->uscsi_cdb = cdb;
11877 	com->uscsi_cdblen = CDB_GROUP1;
11878 	com->uscsi_bufaddr = (caddr_t)ta;
11879 	com->uscsi_buflen = sizeof (struct st_tape_alert);
11880 	com->uscsi_flags =
11881 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
11882 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11883 
11884 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
11885 
11886 	if (rval || com->uscsi_status || com->uscsi_resid) {
11887 
11888 		rval = -1; /* uscsi-command failed */
11889 
11890 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
11891 
11892 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11893 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
11894 		rval = -1;
11895 	}
11896 
11897 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
11898 
11899 
11900 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
11901 
11902 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11903 		    "TapeAlert length %d\n", length);
11904 	}
11905 
11906 
11907 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
11908 
11909 		/*
11910 		 * if rval is bad before the first pass don't bother
11911 		 */
11912 		if (ix == 0 && rval != 0) {
11913 
11914 			break;
11915 		}
11916 
11917 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
11918 		    ta->param[ix].log_param.pc_lo);
11919 
11920 		if ((ta->param[ix].param_value & 1) == 0) {
11921 			continue;
11922 		}
11923 		/*
11924 		 * check to see if current parameter is of interest.
11925 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
11926 		 */
11927 		if ((flag == TAF_CLEAN_NOW) ||
11928 		    (flag == TAF_CLEAN_PERIODIC) ||
11929 		    ((flag == CLEAN_FOR_ERRORS) &&
11930 		    (un->un_dp->type == ST_TYPE_STK9840))) {
11931 
11932 			rval = MTF_TAPE_CLN_SUPPORTED;
11933 
11934 
11935 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11936 			    "alert_page drive needs clean %d\n", flag);
11937 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
11938 			rval |= MTF_TAPE_HEAD_DIRTY;
11939 
11940 		} else if (flag == TAF_CLEANING_MEDIA) {
11941 
11942 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11943 			    "alert_page drive was cleaned\n");
11944 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
11945 		}
11946 
11947 	}
11948 
11949 	/*
11950 	 * Report it as dirty till we see it cleaned
11951 	 */
11952 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
11953 
11954 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11955 		    "alert_page still dirty\n");
11956 		rval |= MTF_TAPE_HEAD_DIRTY;
11957 	}
11958 
11959 	kmem_free(com, sizeof (struct uscsi_cmd));
11960 	kmem_free(ta,  sizeof (struct st_tape_alert));
11961 
11962 	return (rval);
11963 }
11964 
11965 
11966 static int
11967 st_check_sense_clean_bit(dev_t dev)
11968 {
11969 	uchar_t *sensep;
11970 	char cdb[CDB_GROUP0];
11971 	struct uscsi_cmd *com;
11972 	ushort_t byte_pos;
11973 	uchar_t bit_mask;
11974 	unsigned length;
11975 	int index;
11976 	int rval;
11977 
11978 	GET_SOFT_STATE(dev);
11979 
11980 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
11981 
11982 	/*
11983 	 * Since this tape does not support Tape Alert,
11984 	 * we now try to get the cleanbit status via
11985 	 * Request Sense.
11986 	 */
11987 
11988 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
11989 
11990 		index = 0;
11991 
11992 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
11993 
11994 		index = 1;
11995 
11996 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
11997 
11998 		index = 2;
11999 
12000 	} else {
12001 
12002 		return (-1);
12003 	}
12004 
12005 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
12006 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
12007 	length = byte_pos + 1;
12008 
12009 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12010 	sensep = kmem_zalloc(length, KM_SLEEP);
12011 
12012 	cdb[0] = SCMD_REQUEST_SENSE;
12013 	cdb[1] = 0;
12014 	cdb[2] = 0;
12015 	cdb[3] = 0;
12016 	cdb[4] = (char)length;
12017 	cdb[5] = 0;
12018 
12019 	com->uscsi_cdb = cdb;
12020 	com->uscsi_cdblen = CDB_GROUP0;
12021 	com->uscsi_bufaddr = (caddr_t)sensep;
12022 	com->uscsi_buflen = length;
12023 	com->uscsi_flags =
12024 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12025 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12026 
12027 	rval = st_ioctl_cmd(dev, com, FKIOCTL);
12028 
12029 	if (rval || com->uscsi_status || com->uscsi_resid) {
12030 
12031 		rval = -1;
12032 
12033 	} else {
12034 
12035 		rval = MTF_TAPE_CLN_SUPPORTED;
12036 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
12037 
12038 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12039 			    "sense data says head dirty\n");
12040 			rval |= MTF_TAPE_HEAD_DIRTY;
12041 		}
12042 	}
12043 
12044 	kmem_free(com, sizeof (struct uscsi_cmd));
12045 	kmem_free(sensep, length);
12046 	return (rval);
12047 }
12048 
12049 /*
12050  * st_clear_unit_attention
12051  *
12052  *  	run test unit ready's to clear out outstanding
12053  * 	unit attentions.
12054  * 	returns zero for SUCCESS or the errno from st_cmd call
12055  */
12056 static int
12057 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
12058 {
12059 	int	i    = 0;
12060 	int	rval;
12061 
12062 #ifdef DEBUG
12063 	GET_SOFT_STATE(dev_instance);
12064 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
12065 #endif
12066 
12067 	do {
12068 		rval = st_cmd(dev_instance, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
12069 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
12070 	return (rval);
12071 }
12072 
12073 static void
12074 st_calculate_timeouts(struct scsi_tape *un)
12075 {
12076 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
12077 
12078 	if (un->un_dp->non_motion_timeout == 0) {
12079 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12080 			un->un_dp->non_motion_timeout =
12081 			    st_io_time * st_long_timeout_x;
12082 		} else {
12083 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
12084 		}
12085 	}
12086 
12087 	if (un->un_dp->io_timeout == 0) {
12088 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12089 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
12090 		} else {
12091 			un->un_dp->io_timeout = (ushort_t)st_io_time;
12092 		}
12093 	}
12094 
12095 	if (un->un_dp->rewind_timeout == 0) {
12096 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12097 			un->un_dp->rewind_timeout =
12098 			    st_space_time * st_long_timeout_x;
12099 		} else {
12100 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
12101 		}
12102 	}
12103 
12104 	if (un->un_dp->space_timeout == 0) {
12105 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12106 			un->un_dp->space_timeout =
12107 			    st_space_time * st_long_timeout_x;
12108 		} else {
12109 			un->un_dp->space_timeout = (ushort_t)st_space_time;
12110 		}
12111 	}
12112 
12113 	if (un->un_dp->load_timeout == 0) {
12114 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12115 			un->un_dp->load_timeout =
12116 			    st_space_time * st_long_timeout_x;
12117 		} else {
12118 			un->un_dp->load_timeout = (ushort_t)st_space_time;
12119 		}
12120 	}
12121 
12122 	if (un->un_dp->unload_timeout == 0) {
12123 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
12124 			un->un_dp->unload_timeout =
12125 			    st_space_time * st_long_timeout_x;
12126 		} else {
12127 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
12128 		}
12129 	}
12130 
12131 	if (un->un_dp->erase_timeout == 0) {
12132 		if (un->un_dp->options & ST_LONG_ERASE) {
12133 			un->un_dp->erase_timeout =
12134 			    st_space_time * st_long_space_time_x;
12135 		} else {
12136 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
12137 		}
12138 	}
12139 }
12140 
12141 
12142 static writablity
12143 st_is_not_wormable(struct scsi_tape *un)
12144 {
12145 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
12146 	return (RDWR);
12147 }
12148 
12149 static writablity
12150 st_is_hp_dat_tape_worm(struct scsi_tape *un)
12151 {
12152 	writablity wrt;
12153 
12154 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
12155 
12156 	/* Mode sense should be current */
12157 	if (un->un_mspl->media_type == 1) {
12158 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12159 		    "Drive has WORM media loaded\n");
12160 		wrt = WORM;
12161 	} else {
12162 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12163 		    "Drive has non WORM media loaded\n");
12164 		wrt = RDWR;
12165 	}
12166 	return (wrt);
12167 }
12168 
12169 #define	HP_DAT_INQUIRY 0x4A
12170 static writablity
12171 st_is_hp_dat_worm(struct scsi_tape *un)
12172 {
12173 	char *buf;
12174 	int result;
12175 	writablity wrt;
12176 
12177 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
12178 
12179 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
12180 
12181 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
12182 
12183 	if (result != 0) {
12184 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12185 		    "Read Standard Inquiry for WORM support failed");
12186 		wrt = FAILED;
12187 	} else if ((buf[40] & 1) == 0) {
12188 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12189 		    "Drive is NOT WORMable\n");
12190 		/* This drive doesn't support it so don't check again */
12191 		un->un_dp->options &= ~ST_WORMABLE;
12192 		wrt = RDWR;
12193 		un->un_wormable = st_is_not_wormable;
12194 	} else {
12195 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12196 		    "Drive supports WORM version %d\n", buf[40] >> 1);
12197 		un->un_wormable = st_is_hp_dat_tape_worm;
12198 		wrt = un->un_wormable(un);
12199 	}
12200 
12201 	kmem_free(buf, HP_DAT_INQUIRY);
12202 
12203 	/*
12204 	 * If drive doesn't support it no point in checking further.
12205 	 */
12206 	return (wrt);
12207 }
12208 
12209 static writablity
12210 st_is_hp_lto_tape_worm(struct scsi_tape *un)
12211 {
12212 	writablity wrt;
12213 
12214 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
12215 
12216 	/* Mode sense should be current */
12217 	switch (un->un_mspl->media_type) {
12218 	case 0x00:
12219 		switch (un->un_mspl->density) {
12220 		case 0x40:
12221 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12222 			    "Drive has standard Gen I media loaded\n");
12223 			break;
12224 		case 0x42:
12225 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12226 			    "Drive has standard Gen II media loaded\n");
12227 			break;
12228 		case 0x44:
12229 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12230 			    "Drive has standard Gen III media loaded\n");
12231 			break;
12232 		case 0x46:
12233 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12234 			    "Drive has standard Gen IV media loaded\n");
12235 			break;
12236 		default:
12237 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12238 			    "Drive has standard unknown 0x%X media loaded\n",
12239 			    un->un_mspl->density);
12240 		}
12241 		wrt = RDWR;
12242 		break;
12243 	case 0x01:
12244 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12245 		    "Drive has WORM medium loaded\n");
12246 		wrt = WORM;
12247 		break;
12248 	case 0x80:
12249 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12250 		    "Drive has CD-ROM emulation medium loaded\n");
12251 		wrt = WORM;
12252 		break;
12253 	default:
12254 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12255 		    "Drive has an unexpected medium type 0x%X loaded\n",
12256 		    un->un_mspl->media_type);
12257 		wrt = RDWR;
12258 	}
12259 
12260 	return (wrt);
12261 }
12262 
12263 #define	LTO_REQ_INQUIRY 44
12264 static writablity
12265 st_is_hp_lto_worm(struct scsi_tape *un)
12266 {
12267 	char *buf;
12268 	int result;
12269 	writablity wrt;
12270 
12271 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
12272 
12273 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
12274 
12275 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
12276 
12277 	if (result != 0) {
12278 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12279 		    "Read Standard Inquiry for WORM support failed");
12280 		wrt = FAILED;
12281 	} else if ((buf[40] & 1) == 0) {
12282 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12283 		    "Drive is NOT WORMable\n");
12284 		/* This drive doesn't support it so don't check again */
12285 		un->un_dp->options &= ~ST_WORMABLE;
12286 		wrt = RDWR;
12287 		un->un_wormable = st_is_not_wormable;
12288 	} else {
12289 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12290 		    "Drive supports WORM version %d\n", buf[40] >> 1);
12291 		un->un_wormable = st_is_hp_lto_tape_worm;
12292 		wrt = un->un_wormable(un);
12293 	}
12294 
12295 	kmem_free(buf, LTO_REQ_INQUIRY);
12296 
12297 	/*
12298 	 * If drive doesn't support it no point in checking further.
12299 	 */
12300 	return (wrt);
12301 }
12302 
12303 static writablity
12304 st_is_t10_worm_device(struct scsi_tape *un)
12305 {
12306 	writablity wrt;
12307 
12308 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
12309 
12310 	if (un->un_mspl->media_type == 0x3c) {
12311 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12312 		    "Drive has WORM media loaded\n");
12313 		wrt = WORM;
12314 	} else {
12315 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12316 		    "Drive has non WORM media loaded\n");
12317 		wrt = RDWR;
12318 	}
12319 	return (wrt);
12320 }
12321 
12322 #define	SEQ_CAP_PAGE	(char)0xb0
12323 static writablity
12324 st_is_t10_worm(struct scsi_tape *un)
12325 {
12326 	char *buf;
12327 	int result;
12328 	writablity wrt;
12329 
12330 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
12331 
12332 	buf = kmem_zalloc(6, KM_SLEEP);
12333 
12334 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
12335 
12336 	if (result != 0) {
12337 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12338 		    "Read Vitial Inquiry for Sequental Capability"
12339 		    " WORM support failed %x", result);
12340 		wrt = FAILED;
12341 	} else if ((buf[4] & 1) == 0) {
12342 		ASSERT(buf[1] == SEQ_CAP_PAGE);
12343 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12344 		    "Drive is NOT WORMable\n");
12345 		/* This drive doesn't support it so don't check again */
12346 		un->un_dp->options &= ~ST_WORMABLE;
12347 		wrt = RDWR;
12348 		un->un_wormable = st_is_not_wormable;
12349 	} else {
12350 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12351 		    "Drive supports WORM\n");
12352 		un->un_wormable = st_is_t10_worm_device;
12353 		wrt = un->un_wormable(un);
12354 	}
12355 
12356 	kmem_free(buf, 6);
12357 
12358 	return (wrt);
12359 }
12360 
12361 
12362 #define	STK_REQ_SENSE 26
12363 
12364 static writablity
12365 st_is_stk_worm(struct scsi_tape *un)
12366 {
12367 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
12368 	struct scsi_extended_sense *sense;
12369 	struct uscsi_cmd *cmd;
12370 	char *buf;
12371 	int result;
12372 	writablity wrt;
12373 
12374 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
12375 
12376 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12377 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
12378 	sense = (struct scsi_extended_sense *)buf;
12379 
12380 	cmd->uscsi_flags = USCSI_READ;
12381 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12382 	cmd->uscsi_cdb = &cdb[0];
12383 	cmd->uscsi_bufaddr = buf;
12384 	cmd->uscsi_buflen = STK_REQ_SENSE;
12385 	cmd->uscsi_cdblen = CDB_GROUP0;
12386 	cmd->uscsi_rqlen = 0;
12387 	cmd->uscsi_rqbuf = NULL;
12388 
12389 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
12390 
12391 	if (result != 0 || cmd->uscsi_status != 0) {
12392 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12393 		    "Request Sense for WORM failed");
12394 		wrt = RDWR;
12395 	} else if (sense->es_add_len + 8 < 24) {
12396 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12397 		    "Drive didn't send enough sense data for WORM byte %d\n",
12398 		    sense->es_add_len + 8);
12399 		wrt = RDWR;
12400 		un->un_wormable = st_is_not_wormable;
12401 	} else if ((buf[24]) & 0x02) {
12402 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12403 		    "Drive has WORM tape loaded\n");
12404 		wrt = WORM;
12405 		un->un_wormable = st_is_stk_worm;
12406 	} else {
12407 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12408 		    "Drive has normal tape loaded\n");
12409 		wrt = RDWR;
12410 		un->un_wormable = st_is_stk_worm;
12411 	}
12412 
12413 	kmem_free(buf, STK_REQ_SENSE);
12414 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12415 	return (wrt);
12416 }
12417 
12418 #define	DLT_INQ_SZ 44
12419 
12420 static writablity
12421 st_is_dlt_tape_worm(struct scsi_tape *un)
12422 {
12423 	caddr_t buf;
12424 	int result;
12425 	writablity wrt;
12426 
12427 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
12428 
12429 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
12430 
12431 	/* Read Attribute Media Type */
12432 
12433 	result = st_read_attributes(un, 0x0408, buf, 10);
12434 
12435 	/*
12436 	 * If this quantum drive is attached via an HBA that cannot
12437 	 * support thr read attributes command return error in the
12438 	 * hope that someday they will support the t10 method.
12439 	 */
12440 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
12441 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12442 		    "Read Attribute Command for WORM Media detection is not "
12443 		    "supported on the HBA that this drive is attached to.");
12444 		wrt = RDWR;
12445 		un->un_wormable = st_is_not_wormable;
12446 		goto out;
12447 	}
12448 
12449 	if (result != 0) {
12450 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12451 		    "Read Attribute Command for WORM Media returned 0x%x",
12452 		    result);
12453 		wrt = RDWR;
12454 		un->un_dp->options &= ~ST_WORMABLE;
12455 		goto out;
12456 	}
12457 
12458 	if ((uchar_t)buf[9] == 0x80) {
12459 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12460 		    "Drive media is WORM\n");
12461 		wrt = WORM;
12462 	} else {
12463 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12464 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
12465 		wrt = RDWR;
12466 	}
12467 
12468 out:
12469 	kmem_free(buf, DLT_INQ_SZ);
12470 	return (wrt);
12471 }
12472 
12473 static writablity
12474 st_is_dlt_worm(struct scsi_tape *un)
12475 {
12476 	caddr_t buf;
12477 	int result;
12478 	writablity wrt;
12479 
12480 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
12481 
12482 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
12483 
12484 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
12485 
12486 	if (result != 0) {
12487 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12488 		    "Read Vendor Specific Inquiry for WORM support failed");
12489 		wrt = RDWR;
12490 		goto out;
12491 	}
12492 
12493 	if ((buf[2] & 1) == 0) {
12494 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12495 		    "Drive is not WORMable\n");
12496 		wrt = RDWR;
12497 		un->un_dp->options &= ~ST_WORMABLE;
12498 		un->un_wormable = st_is_not_wormable;
12499 		goto out;
12500 	} else {
12501 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12502 		    "Drive is WORMable\n");
12503 		un->un_wormable = st_is_dlt_tape_worm;
12504 		wrt = un->un_wormable(un);
12505 	}
12506 out:
12507 	kmem_free(buf, DLT_INQ_SZ);
12508 
12509 	return (wrt);
12510 }
12511 
12512 typedef struct {
12513 	struct modeheader_seq header;
12514 #if defined(_BIT_FIELDS_LTOH) /* X86 */
12515 	uchar_t pagecode	:6,
12516 				:2;
12517 	uchar_t page_len;
12518 	uchar_t syslogalive	:2,
12519 		device		:1,
12520 		abs		:1,
12521 		ulpbot		:1,
12522 		prth		:1,
12523 		ponej		:1,
12524 		ait		:1;
12525 	uchar_t span;
12526 
12527 	uchar_t			:6,
12528 		worm		:1,
12529 		mic		:1;
12530 	uchar_t worm_cap	:1,
12531 				:7;
12532 	uint32_t		:32;
12533 #else /* SPARC */
12534 	uchar_t			:2,
12535 		pagecode	:6;
12536 	uchar_t page_len;
12537 	uchar_t ait		:1,
12538 		device		:1,
12539 		abs		:1,
12540 		ulpbot		:1,
12541 		prth		:1,
12542 		ponej		:1,
12543 		syslogalive	:2;
12544 	uchar_t span;
12545 	uchar_t mic		:1,
12546 		worm		:1,
12547 				:6;
12548 	uchar_t			:7,
12549 		worm_cap	:1;
12550 	uint32_t		:32;
12551 #endif
12552 }ait_dev_con;
12553 
12554 #define	AIT_DEV_PAGE 0x31
12555 static writablity
12556 st_is_sony_worm(struct scsi_tape *un)
12557 {
12558 	int result;
12559 	writablity wrt;
12560 	ait_dev_con *ait_conf;
12561 
12562 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
12563 
12564 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
12565 
12566 	result = st_gen_mode_sense(un, AIT_DEV_PAGE,
12567 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
12568 
12569 	if (result == 0) {
12570 
12571 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
12572 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12573 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
12574 			    ait_conf->pagecode, AIT_DEV_PAGE);
12575 			wrt = RDWR;
12576 			un->un_wormable = st_is_not_wormable;
12577 
12578 		} else if (ait_conf->worm_cap) {
12579 
12580 			un->un_wormable = st_is_sony_worm;
12581 
12582 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12583 			    "Drives is WORMable\n");
12584 			if (ait_conf->worm) {
12585 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12586 				    "Media is WORM\n");
12587 				wrt = WORM;
12588 			} else {
12589 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12590 				    "Media is not WORM\n");
12591 				wrt = RDWR;
12592 			}
12593 
12594 		} else {
12595 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12596 			    "Drives not is WORMable\n");
12597 			wrt = RDWR;
12598 			/* No further checking required */
12599 			un->un_dp->options &= ~ST_WORMABLE;
12600 		}
12601 
12602 	} else {
12603 
12604 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12605 		    "AIT device config mode sense page read command failed"
12606 		    " result = %d ", result);
12607 		wrt = FAILED;
12608 		un->un_wormable = st_is_not_wormable;
12609 	}
12610 
12611 	kmem_free(ait_conf, sizeof (ait_dev_con));
12612 	return (wrt);
12613 }
12614 
12615 static writablity
12616 st_is_drive_worm(struct scsi_tape *un)
12617 {
12618 	writablity wrt;
12619 
12620 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
12621 
12622 	switch (un->un_dp->type) {
12623 	case MT_ISDLT:
12624 		wrt = st_is_dlt_worm(un);
12625 		break;
12626 
12627 	case MT_ISSTK9840:
12628 		wrt = st_is_stk_worm(un);
12629 		break;
12630 
12631 	case MT_IS8MM:
12632 	case MT_ISAIT:
12633 		wrt = st_is_sony_worm(un);
12634 		break;
12635 
12636 	case MT_LTO:
12637 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
12638 			wrt = st_is_hp_lto_worm(un);
12639 		} else {
12640 			wrt = st_is_t10_worm(un);
12641 		}
12642 		break;
12643 
12644 	case MT_ISDAT:
12645 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
12646 			wrt = st_is_hp_dat_worm(un);
12647 		} else {
12648 			wrt = st_is_t10_worm(un);
12649 		}
12650 		break;
12651 
12652 	default:
12653 		wrt = FAILED;
12654 		break;
12655 	}
12656 
12657 	/*
12658 	 * If any of the above failed try the t10 standard method.
12659 	 */
12660 	if (wrt == FAILED) {
12661 		wrt = st_is_t10_worm(un);
12662 	}
12663 
12664 	/*
12665 	 * Unknown method for detecting WORM media.
12666 	 */
12667 	if (wrt == FAILED) {
12668 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12669 		    "Unknown method for WORM media detection\n");
12670 		wrt = RDWR;
12671 		un->un_dp->options &= ~ST_WORMABLE;
12672 	}
12673 
12674 	return (wrt);
12675 }
12676 
12677 static int
12678 st_read_attributes(struct scsi_tape *un, uint16_t attribute, caddr_t buf,
12679     size_t size)
12680 {
12681 	char cdb[CDB_GROUP4];
12682 	int result;
12683 	struct uscsi_cmd *cmd;
12684 
12685 	ST_FUNC(ST_DEVINFO, st_read_attributes);
12686 
12687 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12688 
12689 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
12690 	cdb[1] = 0;
12691 	cdb[2] = 0;
12692 	cdb[3] = 0;
12693 	cdb[4] = 0;
12694 	cdb[5] = 0;
12695 	cdb[6] = 0;
12696 	cdb[7] = 0;
12697 	cdb[8] = (char)(attribute >> 8);
12698 	cdb[9] = (char)(attribute);
12699 	cdb[10] = (char)(size >> 24);
12700 	cdb[11] = (char)(size >> 16);
12701 	cdb[12] = (char)(size >> 8);
12702 	cdb[13] = (char)(size);
12703 	cdb[14] = 0;
12704 	cdb[15] = 0;
12705 
12706 
12707 	cmd->uscsi_flags = USCSI_READ | USCSI_DIAGNOSE;
12708 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12709 	cmd->uscsi_cdb = &cdb[0];
12710 	cmd->uscsi_bufaddr = (caddr_t)buf;
12711 	cmd->uscsi_buflen = size;
12712 	cmd->uscsi_cdblen = sizeof (cdb);
12713 
12714 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
12715 
12716 	if (result != 0 || cmd->uscsi_status != 0) {
12717 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12718 		    "st_read_attribute failed: result %d status %d\n",
12719 		    result, cmd->uscsi_status);
12720 		if (result == 0) {
12721 			result = EIO;
12722 		}
12723 		goto exit;
12724 	}
12725 
12726 	/*
12727 	 * The attribute retured should match the attribute requested.
12728 	 */
12729 	if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
12730 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
12731 		    "bad? data", buf, size);
12732 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12733 		    "st_read_attribute got wrong data back expected 0x%x"
12734 		    " got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
12735 		result = EIO;
12736 	}
12737 exit:
12738 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12739 
12740 	return (result);
12741 }
12742 
12743 static int
12744 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
12745     uchar_t page)
12746 {
12747 	char cdb[CDB_GROUP0];
12748 	struct scsi_extended_sense *sense;
12749 	struct uscsi_cmd *cmd;
12750 	int result;
12751 
12752 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
12753 
12754 	cdb[0] = SCMD_INQUIRY;
12755 	cdb[1] = page ? 1 : 0;
12756 	cdb[2] = page;
12757 	cdb[3] = 0;
12758 	cdb[4] = size;
12759 	cdb[5] = 0;
12760 
12761 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
12762 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
12763 
12764 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
12765 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
12766 	cmd->uscsi_cdb = &cdb[0];
12767 	cmd->uscsi_bufaddr = dest;
12768 	cmd->uscsi_buflen = size;
12769 	cmd->uscsi_cdblen = CDB_GROUP0;
12770 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
12771 	cmd->uscsi_rqbuf = (caddr_t)sense;
12772 
12773 	result = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
12774 
12775 	if (result != 0 || cmd->uscsi_status != 0) {
12776 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
12777 		    "st_get_special_inquiry() failed for page %x", page);
12778 		if (result == 0) {
12779 			result = EIO;
12780 		}
12781 	}
12782 
12783 	kmem_free(sense, sizeof (struct scsi_extended_sense));
12784 	kmem_free(cmd, sizeof (struct uscsi_cmd));
12785 
12786 	return (result);
12787 }
12788 
12789 
12790 static int
12791 st_update_block_pos(struct scsi_tape *un)
12792 {
12793 	int rval = ENOTTY;
12794 
12795 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
12796 
12797 	while (un->un_read_pos_type != NO_POS) {
12798 		rval = st_cmd(un->un_dev, SCMD_READ_POSITION, 32, SYNC_CMD);
12799 
12800 		if (rval == 0) {
12801 			rval = st_interpret_read_pos(un, un->un_read_pos_type,
12802 			    32, (caddr_t)un->un_read_pos_data);
12803 			break;
12804 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
12805 			continue;
12806 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
12807 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12808 			    "st_update_block_pos() read position cmd %x"
12809 			    " returned %x un_status = %d",
12810 			    un->un_read_pos_type, rval, un->un_status);
12811 			break;
12812 		} else {
12813 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
12814 			    "st_update_block_pos() read position cmd %x"
12815 			    " returned %x", un->un_read_pos_type, rval);
12816 		}
12817 
12818 		switch (un->un_read_pos_type) {
12819 		case SHORT_POS:
12820 			un->un_read_pos_type = NO_POS;
12821 			break;
12822 
12823 		case LONG_POS:
12824 			un->un_read_pos_type = EXT_POS;
12825 			break;
12826 
12827 		case EXT_POS:
12828 			un->un_read_pos_type = SHORT_POS;
12829 			break;
12830 
12831 		default:
12832 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
12833 			    "Unexpected read position type 0x%x",
12834 			    un->un_read_pos_type);
12835 		}
12836 	}
12837 
12838 	return (rval);
12839 }
12840 
12841 static int
12842 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
12843 {
12844 	int result;
12845 	size_t d_sz;
12846 	caddr_t pos_info;
12847 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
12848 
12849 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
12850 
12851 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
12852 		return (0);
12853 	}
12854 
12855 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
12856 
12857 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
12858 		    "bp_mapin_common() failed");
12859 
12860 		return (EIO);
12861 	}
12862 
12863 	pos_info = bp->b_un.b_addr;
12864 	d_sz = bp->b_bcount - bp->b_resid;
12865 
12866 #ifdef DEBUG
12867 	if ((st_debug & 0xf) > 2) {
12868 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
12869 		    "st_get_read_pos() position info",
12870 		    pos_info, bp->b_bcount);
12871 	}
12872 #endif
12873 
12874 	result = st_interpret_read_pos(un, cmd->uscsi_cdb[1], d_sz, pos_info);
12875 
12876 	bp_mapout(bp);
12877 
12878 	return (result);
12879 }
12880 
12881 #if defined(_BIG_ENDIAN)
12882 
12883 #define	FIX_ENDIAN32(x)
12884 #define	FIX_ENDIAN64(x)
12885 
12886 #elif defined(_LITTLE_ENDIAN)
12887 
12888 static void
12889 st_swap32(uint32_t *val)
12890 {
12891 	uint32_t tmp;
12892 
12893 	tmp =  (*val >> 24) & 0xff;
12894 	tmp |= (*val >>  8) & 0xff00;
12895 	tmp |= (*val <<  8) & 0xff0000;
12896 	tmp |= (*val << 24) & 0xff000000;
12897 
12898 	*val = tmp;
12899 }
12900 
12901 static void
12902 st_swap64(uint64_t *val)
12903 {
12904 	uint32_t low;
12905 	uint32_t high;
12906 
12907 	low =  (uint32_t)(*val);
12908 	high = (uint32_t)(*val >> 32);
12909 
12910 	st_swap32(&low);
12911 	st_swap32(&high);
12912 
12913 	*val =  high;
12914 	*val |= ((uint64_t)low << 32);
12915 }
12916 
12917 #define	FIX_ENDIAN32(x) st_swap32(x)
12918 #define	FIX_ENDIAN64(x) st_swap64(x)
12919 #endif
12920 
12921 static int
12922 st_interpret_read_pos(struct scsi_tape *un, read_p_types type,
12923     size_t data_sz, caddr_t responce)
12924 {
12925 	int rval = 0;
12926 
12927 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
12928 
12929 	/*
12930 	 * Look at byte 1 of cdb to see what kind of read position
12931 	 * was requested.
12932 	 */
12933 	switch (type) {
12934 
12935 	case SHORT_POS: /* Short data format */
12936 	{
12937 		tape_position_t *pos_info = (tape_position_t *)responce;
12938 		uint32_t value;
12939 
12940 		/* If reserved fields are non zero don't use the data */
12941 		if (pos_info->reserved0 || pos_info->reserved1 ||
12942 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
12943 		    pos_info->reserved3) {
12944 			rval = EIO;
12945 			break;
12946 		}
12947 		/*
12948 		 * Position is to large to use this type of read position.
12949 		 */
12950 		if (pos_info->posi_err == 1) {
12951 			rval = ERANGE;
12952 			break;
12953 		}
12954 
12955 		if (pos_info->blk_posi_unkwn == 0) {
12956 
12957 			if (un->un_pos.partition !=
12958 			    pos_info->partition_number) {
12959 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12960 				    "SHORT_POS current partition %d read %d\n",
12961 				    un->un_pos.partition,
12962 				    pos_info->partition_number);
12963 			}
12964 			un->un_pos.partition = pos_info->partition_number;
12965 			value = pos_info->host_block;
12966 			FIX_ENDIAN32(&value);
12967 
12968 			if (un->un_pos.lgclblkno != value) {
12969 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12970 				    "SHORT_POS current logical 0x%"PRIx64" read"
12971 				    " 0x%x\n", un->un_pos.lgclblkno, value);
12972 			}
12973 
12974 			un->un_pos.lgclblkno = (uint64_t)value;
12975 
12976 			if (pos_info->begin_of_part && pos_info->end_of_part) {
12977 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
12978 				    "SHORT_POS returned begin and end of"
12979 				    " partition\n");
12980 				break;
12981 			}
12982 			/* Is drive rewound */
12983 			if ((pos_info->begin_of_part == 1) &&
12984 			    (pos_info->host_block == 0)) {
12985 				un->un_pos.blkno = 0;
12986 				un->un_pos.fileno = 0;
12987 				un->un_pos.pmode = legacy;
12988 			} else if (un->un_pos.pmode == invalid) {
12989 				/* If we were lost now were found */
12990 				un->un_pos.pmode = logical;
12991 			}
12992 		} else {
12993 			un->un_pos.pmode = invalid;
12994 		}
12995 		break;
12996 	}
12997 
12998 	case LONG_POS: /* Long data format */
12999 	{
13000 		uint64_t value;
13001 		tape_position_long_t *long_pos_info =
13002 		    (tape_position_long_t *)responce;
13003 
13004 		/* If reserved fields are non zero don't use the data */
13005 		if ((long_pos_info->reserved0) ||
13006 		    (long_pos_info->reserved1) ||
13007 		    (long_pos_info->reserved2)) {
13008 			rval = EIO;
13009 			break;
13010 		}
13011 
13012 		/* Is position Valid */
13013 		if (long_pos_info->blk_posi_unkwn == 0) {
13014 			uint32_t part;
13015 
13016 			part = long_pos_info->partition;
13017 			FIX_ENDIAN32(&part);
13018 			if (un->un_pos.partition != part) {
13019 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13020 				    "LONG_POS current partition %d"
13021 				    " read %d\n", un->un_pos.partition, part);
13022 			}
13023 			un->un_pos.partition = part;
13024 			value = long_pos_info->block_number;
13025 			FIX_ENDIAN64(&value);
13026 			if (un->un_pos.lgclblkno != value) {
13027 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13028 				    "LONG_POS current logical 0x%"PRIx64
13029 				    " read 0x%"PRIx64"\n",
13030 				    un->un_pos.lgclblkno, value);
13031 			}
13032 			un->un_pos.lgclblkno = value;
13033 
13034 			if (long_pos_info->begin_of_part &&
13035 			    long_pos_info->end_of_part) {
13036 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
13037 				    "LONG_POS returned begin and end of"
13038 				    " partition\n");
13039 				break;
13040 			}
13041 			if ((long_pos_info->begin_of_part == 1) &&
13042 			    (long_pos_info->block_number == 0)) {
13043 				un->un_pos.blkno = 0;
13044 				un->un_pos.fileno = 0;
13045 				un->un_pos.pmode = legacy;
13046 			} else if (un->un_pos.pmode == invalid) {
13047 				un->un_pos.pmode = logical;
13048 			}
13049 		} else {
13050 			/*
13051 			 * If the drive doesn't know location,
13052 			 * we don't either.
13053 			 */
13054 			un->un_pos.pmode = invalid;
13055 		}
13056 
13057 		value = long_pos_info->file_number;
13058 		FIX_ENDIAN64(&value);
13059 		/* Is file position valid */
13060 		if (long_pos_info->mrk_posi_unkwn == 0) {
13061 			if (((un->un_pos.pmode == legacy) ||
13062 			    (un->un_pos.pmode == logical)) &&
13063 			    (un->un_pos.fileno != value)) {
13064 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13065 				    "LONG_POS fileno 0x%"PRIx64
13066 				    " not un_pos %x\n", value,
13067 				    un->un_pos.fileno);
13068 			} else if (un->un_pos.pmode == invalid) {
13069 				un->un_pos.pmode = logical;
13070 			}
13071 			un->un_pos.fileno = (int32_t)value;
13072 		} else {
13073 			/*
13074 			 * If the drive doesn't know its position,
13075 			 * we don't either.
13076 			 */
13077 			un->un_pos.pmode = invalid;
13078 		}
13079 		if (un->un_pos.pmode != invalid && long_pos_info->end_of_part) {
13080 			un->un_pos.eof = ST_EOT;
13081 		}
13082 
13083 		break;
13084 	}
13085 
13086 	case EXT_POS: /* Extended data format */
13087 	{
13088 		uint64_t value;
13089 		tape_position_ext_t *ext_pos_info =
13090 		    (tape_position_ext_t *)responce;
13091 
13092 		/* Make sure that there is enough data there */
13093 		if (data_sz < 16) {
13094 			break;
13095 		}
13096 
13097 		/* If reserved fields are non zero don't use the data */
13098 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
13099 			rval = EIO;
13100 			break;
13101 		}
13102 
13103 		/*
13104 		 * In the unlikely event of overflowing 64 bits of position.
13105 		 */
13106 		if (ext_pos_info->posi_err != 0) {
13107 			rval = ERANGE;
13108 			break;
13109 		}
13110 
13111 		/* Is block position information valid */
13112 		if (ext_pos_info->blk_posi_unkwn == 0) {
13113 
13114 			if (un->un_pos.partition != ext_pos_info->partition) {
13115 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13116 				    "EXT_POS current partition %d read %d\n",
13117 				    un->un_pos.partition,
13118 				    ext_pos_info->partition);
13119 			}
13120 			un->un_pos.partition = ext_pos_info->partition;
13121 
13122 			value = ext_pos_info->host_block;
13123 			FIX_ENDIAN64(&value);
13124 			if (un->un_pos.lgclblkno != value) {
13125 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13126 				    "EXT_POS current logical 0x%"PRIx64
13127 				    " read 0x%"PRIx64"\n",
13128 				    un->un_pos.lgclblkno, value);
13129 			}
13130 			un->un_pos.lgclblkno = value;
13131 			if ((ext_pos_info->begin_of_part == 1) &&
13132 			    (ext_pos_info->host_block == 0)) {
13133 				un->un_pos.blkno = 0;
13134 				un->un_pos.fileno = 0;
13135 				un->un_pos.pmode = legacy;
13136 			} else if (un->un_pos.pmode == invalid) {
13137 				un->un_pos.pmode = logical;
13138 			}
13139 		} else {
13140 			un->un_pos.pmode = invalid;
13141 		}
13142 		break;
13143 	}
13144 
13145 	default:
13146 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
13147 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
13148 		rval = EIO;
13149 	}
13150 
13151 	return (rval);
13152 }
13153 
13154 static int
13155 st_logical_block_locate(struct scsi_tape *un, uint64_t lblk, uchar_t partition)
13156 {
13157 	int rval;
13158 	char cdb[CDB_GROUP4];
13159 	struct uscsi_cmd *cmd;
13160 	struct scsi_extended_sense sense;
13161 
13162 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
13163 
13164 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13165 
13166 	if (lblk <= INT32_MAX) {
13167 		cmd->uscsi_cdblen = CDB_GROUP1;
13168 		cdb[0] = SCMD_LOCATE;
13169 		cdb[1] = un->un_pos.partition == partition ? 0 : 2;
13170 		cdb[2] = 0;
13171 		cdb[3] = (char)(lblk >> 24);
13172 		cdb[4] = (char)(lblk >> 16);
13173 		cdb[5] = (char)(lblk >> 8);
13174 		cdb[6] = (char)(lblk);
13175 		cdb[7] = 0;
13176 		cdb[8] = partition;
13177 		cdb[9] = 0;
13178 	} else {
13179 		/*
13180 		 * If the drive doesn't give a 64 bit read position data
13181 		 * it is unlikely it will accept 64 bit locates.
13182 		 */
13183 		if (un->un_read_pos_type != LONG_POS) {
13184 			kmem_free(cmd, sizeof (struct uscsi_cmd));
13185 			return (ERANGE);
13186 		}
13187 		cmd->uscsi_cdblen = CDB_GROUP4;
13188 		cdb[0] = (char)SCMD_LOCATE_G4;
13189 		cdb[1] = un->un_pos.partition == partition ? 0 : 2;
13190 		cdb[2] = 0;
13191 		cdb[3] = partition;
13192 		cdb[4] = (char)(lblk >> 56);
13193 		cdb[5] = (char)(lblk >> 48);
13194 		cdb[6] = (char)(lblk >> 40);
13195 		cdb[7] = (char)(lblk >> 32);
13196 		cdb[8] = (char)(lblk >> 24);
13197 		cdb[9] = (char)(lblk >> 16);
13198 		cdb[10] = (char)(lblk >> 8);
13199 		cdb[11] = (char)(lblk);
13200 		cdb[12] = 0;
13201 		cdb[13] = 0;
13202 		cdb[14] = 0;
13203 		cdb[15] = 0;
13204 	}
13205 
13206 
13207 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
13208 	cmd->uscsi_rqbuf = (caddr_t)&sense;
13209 	cmd->uscsi_rqlen = sizeof (sense);
13210 	cmd->uscsi_timeout = un->un_dp->space_timeout;
13211 	cmd->uscsi_cdb = cdb;
13212 
13213 	rval = st_ioctl_cmd(un->un_dev, cmd, FKIOCTL);
13214 
13215 	un->un_pos.pmode = logical;
13216 	un->un_pos.eof = ST_NO_EOF;
13217 
13218 	if (lblk > INT32_MAX) {
13219 		/*
13220 		 * XXX This is a work around till we handle Descriptor format
13221 		 * sense data. Since we are sending a command where the standard
13222 		 * sense data can not correctly represent a correct residual in
13223 		 * 4 bytes.
13224 		 */
13225 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
13226 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13227 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
13228 			/* Doesn't like big locate command */
13229 			un->un_status = 0;
13230 			rval = ERANGE;
13231 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
13232 			/* Aborted big locate command */
13233 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13234 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
13235 			    rval);
13236 			un->un_status = 0;
13237 			rval = EIO;
13238 		} else if (st_update_block_pos(un)) {
13239 			/* read position failed */
13240 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13241 			    "Big LOCATE and read pos: rval = %d\n", rval);
13242 			rval = EIO;
13243 		} else if (lblk > un->un_pos.lgclblkno) {
13244 			/* read position worked but position was not expected */
13245 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13246 			    "Big LOCATE and recover read less then desired 0x%"
13247 			    PRIx64"\n", un->un_pos.lgclblkno);
13248 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
13249 			un->un_status = KEY_BLANK_CHECK;
13250 			rval = ESPIPE;
13251 		} else if (lblk == un->un_pos.lgclblkno) {
13252 			/* read position was what was expected */
13253 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13254 			    "Big LOCATE and recover seems to have worked\n");
13255 			un->un_err_resid = 0;
13256 			rval = 0;
13257 		} else {
13258 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
13259 			    "BIGLOCATE end up going backwards");
13260 			un->un_err_resid = lblk;
13261 			rval = EIO;
13262 		}
13263 
13264 	} else if (rval == 0) {
13265 		/* Worked as requested */
13266 		un->un_pos.lgclblkno = lblk;
13267 
13268 	} else if (((cmd->uscsi_status & STATUS_MASK) == STATUS_CHECK) &&
13269 	    (cmd->uscsi_resid != 0)) {
13270 		/* Got part way there but wasn't enough blocks on tape */
13271 		un->un_pos.lgclblkno = lblk - cmd->uscsi_resid;
13272 		un->un_err_resid = cmd->uscsi_resid;
13273 		un->un_status = KEY_BLANK_CHECK;
13274 		rval = ESPIPE;
13275 
13276 	} else if (st_update_block_pos(un) == 0) {
13277 		/* Got part way there but drive didn't tell what we missed by */
13278 		un->un_err_resid = lblk - un->un_pos.lgclblkno;
13279 		un->un_status = KEY_BLANK_CHECK;
13280 		rval = ESPIPE;
13281 
13282 	} else {
13283 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
13284 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
13285 		    rval, cmd->uscsi_status);
13286 		un->un_err_resid = lblk;
13287 		un->un_status = KEY_ILLEGAL_REQUEST;
13288 		un->un_pos.pmode = invalid;
13289 		rval = EIO;
13290 	}
13291 
13292 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13293 
13294 	return (rval);
13295 }
13296 
13297 static int
13298 st_mtfsf_ioctl(struct scsi_tape *un, int files)
13299 {
13300 	int rval;
13301 
13302 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
13303 
13304 
13305 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13306 	    "st_mtfsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
13307 
13308 	/* pmode == invalid already handled */
13309 	if (un->un_pos.pmode == legacy) {
13310 		/*
13311 		 * forward space over filemark
13312 		 *
13313 		 * For ASF we allow a count of 0 on fsf which means
13314 		 * we just want to go to beginning of current file.
13315 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
13316 		 * Allow stepping over double fmk with reel
13317 		 */
13318 		if ((un->un_pos.eof >= ST_EOT) &&
13319 		    (files > 0) &&
13320 		    ((un->un_dp->options & ST_REEL) == 0)) {
13321 			/* we're at EOM */
13322 			un->un_err_resid = files;
13323 			un->un_status = KEY_BLANK_CHECK;
13324 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13325 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
13326 			return (EIO);
13327 		}
13328 
13329 		/*
13330 		 * physical tape position may not be what we've been
13331 		 * telling the user; adjust the request accordingly
13332 		 */
13333 		if (IN_EOF(un->un_pos)) {
13334 			un->un_pos.fileno++;
13335 			un->un_pos.blkno = 0;
13336 			/*
13337 			 * For positive direction case, we're now covered.
13338 			 * For zero or negative direction, we're covered
13339 			 * (almost)
13340 			 */
13341 			files--;
13342 		}
13343 
13344 	}
13345 
13346 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
13347 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13348 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
13349 		return (EIO);
13350 	}
13351 
13352 
13353 	/*
13354 	 * Forward space file marks.
13355 	 * We leave ourselves at block zero
13356 	 * of the target file number.
13357 	 */
13358 	if (files < 0) {
13359 		rval = st_backward_space_files(un, -files, 0);
13360 	} else {
13361 		rval = st_forward_space_files(un, files);
13362 	}
13363 
13364 	return (rval);
13365 }
13366 
13367 static int
13368 st_forward_space_files(struct scsi_tape *un, int count)
13369 {
13370 	dev_t dev;
13371 	int rval;
13372 
13373 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
13374 
13375 	dev = un->un_dev;
13376 
13377 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13378 	    "fspace: count=%x, eof=%x\n", count, un->un_pos.eof);
13379 
13380 	ASSERT(count >= 0);
13381 	ASSERT(un->un_pos.pmode != invalid);
13382 
13383 	/*
13384 	 * A space with a count of zero means take me to the start of file.
13385 	 */
13386 	if (count == 0) {
13387 
13388 		/* Hay look were already there */
13389 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0 &&
13390 		    un->un_pos.fileno == 0) {
13391 			un->un_err_resid = 0;
13392 			COPY_POS(&un->un_err_pos, &un->un_pos);
13393 			return (0);
13394 		}
13395 
13396 		/*
13397 		 * Well we are in the first file.
13398 		 * A rewind will get to the start.
13399 		 */
13400 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
13401 			rval = st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
13402 
13403 		/*
13404 		 * Can we backspace to get there?
13405 		 * This should work in logical mode.
13406 		 */
13407 		} else if (un->un_dp->options & ST_BSF) {
13408 			rval = st_space_to_begining_of_file(un);
13409 
13410 		/*
13411 		 * Can't back space but current file number is known,
13412 		 * So rewind and space from the begining of the partition.
13413 		 */
13414 		} else if (un->un_pos.pmode == legacy) {
13415 			rval = st_scenic_route_to_begining_of_file(un,
13416 			    un->un_pos.fileno);
13417 
13418 		/*
13419 		 * pmode is logical and ST_BSF is not set.
13420 		 * The LONG_POS read position contains the fileno.
13421 		 * If the read position works, rewind and space.
13422 		 */
13423 		} else if (un->un_read_pos_type == LONG_POS) {
13424 			rval = st_cmd(dev, SCMD_READ_POSITION, 0, SYNC_CMD);
13425 			if (rval) {
13426 				/*
13427 				 * We didn't get the file position from the
13428 				 * read position command.
13429 				 * We are going to trust the drive to backspace
13430 				 * and then position after the filemark.
13431 				 */
13432 				rval = st_space_to_begining_of_file(un);
13433 			}
13434 			rval = st_interpret_read_pos(un, LONG_POS, 32,
13435 			    (caddr_t)un->un_read_pos_data);
13436 			if ((rval) && (un->un_pos.pmode == invalid)) {
13437 				rval = st_space_to_begining_of_file(un);
13438 			} else {
13439 				rval = st_scenic_route_to_begining_of_file(un,
13440 				    un->un_pos.fileno);
13441 			}
13442 		} else {
13443 			rval = EIO;
13444 		}
13445 		/*
13446 		 * If something didn't work we are lost
13447 		 */
13448 		if (rval != 0) {
13449 			un->un_pos.pmode = invalid;
13450 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13451 			    "st_mtioctop : EIO : fspace pmode invalid");
13452 
13453 			rval = EIO;
13454 		}
13455 
13456 	} else {
13457 		rval = st_space_fmks(dev, count);
13458 	}
13459 
13460 	if (rval != EIO && count < 0) {
13461 		/*
13462 		 * we came here with a count < 0; we now need
13463 		 * to skip back to end up before the filemark
13464 		 */
13465 		rval = st_backward_space_files(un, 1, 1);
13466 	}
13467 
13468 	return (rval);
13469 }
13470 
13471 static int
13472 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
13473 {
13474 	int rval;
13475 
13476 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
13477 
13478 	if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
13479 		rval = EIO;
13480 	} else if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
13481 		rval = EIO;
13482 	}
13483 
13484 	return (rval);
13485 }
13486 
13487 static int
13488 st_space_to_begining_of_file(struct scsi_tape *un)
13489 {
13490 	int rval;
13491 
13492 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
13493 
13494 	/*
13495 	 * Back space of the file at the begining of the file.
13496 	 */
13497 	rval = st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD);
13498 	if (rval) {
13499 		rval = EIO;
13500 		return (rval);
13501 	}
13502 
13503 	/*
13504 	 * Other interesting answers might be crashed BOT which isn't bad.
13505 	 */
13506 	if (un->un_status == SUN_KEY_BOT) {
13507 		return (rval);
13508 	}
13509 
13510 	/*
13511 	 * Now we are on the BOP side of the filemark. Forward space to
13512 	 * the EOM side and we are at the begining of the file.
13513 	 */
13514 	rval = st_cmd(un->un_dev, SCMD_SPACE, Fmk(1), SYNC_CMD);
13515 	if (rval) {
13516 		rval = EIO;
13517 	}
13518 
13519 	return (rval);
13520 }
13521 
13522 static int
13523 st_mtfsr_ioctl(struct scsi_tape *un, int count)
13524 {
13525 
13526 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
13527 
13528 	/*
13529 	 * forward space to inter-record gap
13530 	 *
13531 	 */
13532 
13533 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13534 	    "st_ioctl_fsr: count=%x, eof=%x\n", count, un->un_pos.eof);
13535 
13536 	if (un->un_pos.pmode == legacy) {
13537 		/*
13538 		 * If were are at end of tape and count is forward.
13539 		 * Return blank check.
13540 		 */
13541 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
13542 			/* we're at EOM */
13543 			un->un_err_resid = count;
13544 			un->un_status = KEY_BLANK_CHECK;
13545 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13546 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
13547 			return (EIO);
13548 		}
13549 
13550 		/*
13551 		 * If count is zero there is nothing to do.
13552 		 */
13553 		if (count == 0) {
13554 			un->un_err_pos.fileno = un->un_pos.fileno;
13555 			un->un_err_pos.blkno = un->un_pos.blkno;
13556 			un->un_err_resid = 0;
13557 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
13558 				un->un_status = SUN_KEY_EOF;
13559 			}
13560 			return (0);
13561 		}
13562 
13563 		/*
13564 		 * physical tape position may not be what we've been
13565 		 * telling the user; adjust the position accordingly
13566 		 */
13567 		if (IN_EOF(un->un_pos)) {
13568 			daddr_t blkno = un->un_pos.blkno;
13569 			int fileno = un->un_pos.fileno;
13570 
13571 			optype lastop = un->un_lastop;
13572 			if (st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)
13573 			    == -1) {
13574 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13575 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
13576 				return (EIO);
13577 			}
13578 
13579 			un->un_pos.blkno = blkno;
13580 			un->un_pos.fileno = fileno;
13581 			un->un_lastop = lastop;
13582 		}
13583 	}
13584 
13585 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
13586 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13587 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
13588 		return (EIO);
13589 	}
13590 
13591 	return (st_space_records(un, count));
13592 }
13593 
13594 static int
13595 st_space_records(struct scsi_tape *un, int count)
13596 {
13597 	int dblk;
13598 	int rval = 0;
13599 
13600 	ST_FUNC(ST_DEVINFO, st_space_records);
13601 
13602 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13603 	    "st_space_records: count=%x, eof=%x\n", count, un->un_pos.eof);
13604 
13605 	if (un->un_pos.pmode == logical) {
13606 		rval = st_cmd(un->un_dev, SCMD_SPACE, Blk(count), SYNC_CMD);
13607 		if (rval != 0) {
13608 			rval = EIO;
13609 		}
13610 		return (rval);
13611 	}
13612 
13613 	dblk = un->un_pos.blkno + count;
13614 
13615 	/* Already there */
13616 	if (dblk == un->un_pos.blkno) {
13617 		un->un_err_resid = 0;
13618 		COPY_POS(&un->un_err_pos, &un->un_pos);
13619 		return (0);
13620 	}
13621 
13622 	/*
13623 	 * If the destination block is forward
13624 	 * or the drive will backspace records.
13625 	 */
13626 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
13627 		/*
13628 		 * If we're spacing forward, or the device can
13629 		 * backspace records, we can just use the SPACE
13630 		 * command.
13631 		 */
13632 		dblk -= un->un_pos.blkno;
13633 		if (st_cmd(un->un_dev, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
13634 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13635 			    "st_space_records:EIO:space_records can't spc");
13636 			rval = EIO;
13637 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
13638 			/*
13639 			 * check if we hit BOT/EOT
13640 			 */
13641 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
13642 				un->un_status = SUN_KEY_BOT;
13643 				un->un_pos.eof = ST_NO_EOF;
13644 			} else if (dblk < 0 &&
13645 			    un->un_pos.eof == ST_EOF_PENDING) {
13646 				int residue = un->un_err_resid;
13647 				/*
13648 				 * we skipped over a filemark
13649 				 * and need to go forward again
13650 				 */
13651 				if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(1),
13652 				    SYNC_CMD)) {
13653 					ST_DEBUG2(ST_DEVINFO, st_label,
13654 					    SCSI_DEBUG, "st_space_records: EIO"
13655 					    " : can't space #2");
13656 					rval = EIO;
13657 				}
13658 				un->un_err_resid = residue;
13659 			}
13660 			if (rval == 0) {
13661 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13662 				    "st_space_records: EIO : space_rec rval"
13663 				    " == 0");
13664 				rval = EIO;
13665 			}
13666 		}
13667 	} else {
13668 		/*
13669 		 * else we rewind, space forward across filemarks to
13670 		 * the desired file, and then space records to the
13671 		 * desired block.
13672 		 */
13673 
13674 		int dfile = un->un_pos.fileno;	/* save current file */
13675 
13676 		if (dblk < 0) {
13677 			/*
13678 			 * Wups - we're backing up over a filemark
13679 			 */
13680 			if (un->un_pos.blkno != 0 &&
13681 			    (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD) ||
13682 			    st_cmd(un->un_dev, SCMD_SPACE, Fmk(dfile),
13683 			    SYNC_CMD))) {
13684 				un->un_pos.pmode = invalid;
13685 			}
13686 			un->un_err_resid = -dblk;
13687 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
13688 				un->un_status = SUN_KEY_BOT;
13689 				un->un_pos.eof = ST_NO_EOF;
13690 			} else if (un->un_pos.fileno > 0) {
13691 				un->un_status = SUN_KEY_EOF;
13692 				un->un_pos.eof = ST_NO_EOF;
13693 			}
13694 			COPY_POS(&un->un_err_pos, &un->un_pos);
13695 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13696 			    "st_space_records:EIO:space_records : dblk < 0");
13697 			rval = EIO;
13698 		} else if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD) ||
13699 		    st_cmd(un->un_dev, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
13700 		    st_cmd(un->un_dev, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
13701 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13702 			    "st_space_records: EIO :space_records : rewind "
13703 			    "and space failed");
13704 			un->un_pos.pmode = invalid;
13705 			rval = EIO;
13706 		}
13707 	}
13708 
13709 	return (rval);
13710 }
13711 
13712 static int
13713 st_mtbsf_ioctl(struct scsi_tape *un, int files)
13714 {
13715 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
13716 
13717 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13718 	    "st_mtbsf_ioctl: count=%x, eof=%x\n", files, un->un_pos.eof);
13719 	/*
13720 	 * backward space of file filemark (1/2" and 8mm)
13721 	 * tape position will end on the beginning of tape side
13722 	 * of the desired file mark
13723 	 */
13724 	if ((un->un_dp->options & ST_BSF) == 0) {
13725 		return (ENOTTY);
13726 	}
13727 
13728 	if (un->un_pos.pmode == legacy) {
13729 
13730 		/*
13731 		 * If a negative count (which implies a forward space op)
13732 		 * is specified, and we're at logical or physical eot,
13733 		 * bounce the request.
13734 		 */
13735 
13736 		if (un->un_pos.eof >= ST_EOT && files < 0) {
13737 			un->un_err_resid = files;
13738 			un->un_status = SUN_KEY_EOT;
13739 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13740 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
13741 			return (EIO);
13742 		}
13743 		/*
13744 		 * physical tape position may not be what we've been
13745 		 * telling the user; adjust the request accordingly
13746 		 */
13747 		if (IN_EOF(un->un_pos)) {
13748 			un->un_pos.fileno++;
13749 			un->un_pos.blkno = 0;
13750 			files++;
13751 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13752 			    "st_mtbsf_ioctl in eof: count=%d, op=%x\n",
13753 			    files, MTBSF);
13754 
13755 		}
13756 	}
13757 
13758 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
13759 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13760 		    "st_ioctl : EIO : MTBSF : check den wfm");
13761 		return (EIO);
13762 	}
13763 
13764 	if (files <= 0) {
13765 		/*
13766 		 * for a negative count, we need to step forward
13767 		 * first and then step back again
13768 		 */
13769 		files = -files + 1;
13770 		return (st_forward_space_files(un, files));
13771 	}
13772 	return (st_backward_space_files(un, files, 1));
13773 }
13774 
13775 static int
13776 st_backward_space_files(struct scsi_tape *un, int count, int infront)
13777 {
13778 	int end_fileno;
13779 	int skip_cnt;
13780 	int rval = 0;
13781 
13782 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
13783 
13784 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13785 	    "st_backward_space_files: count=%x eof=%x\n",
13786 	    count, un->un_pos.eof);
13787 	/*
13788 	 * Backspace files (MTNBSF): infront == 0
13789 	 *
13790 	 *	For tapes that can backspace, backspace
13791 	 *	count+1 filemarks and then run forward over
13792 	 *	a filemark
13793 	 *
13794 	 *	For tapes that can't backspace,
13795 	 *		calculate desired filenumber
13796 	 *		(un->un_pos.fileno - count), rewind,
13797 	 *		and then space forward this amount
13798 	 *
13799 	 * Backspace filemarks (MTBSF) infront == 1
13800 	 *
13801 	 *	For tapes that can backspace, backspace count
13802 	 *	filemarks
13803 	 *
13804 	 *	For tapes that can't backspace, calculate
13805 	 *	desired filenumber (un->un_pos.fileno - count),
13806 	 *	add 1, rewind, space forward this amount,
13807 	 *	and mark state as ST_EOF_PENDING appropriately.
13808 	 */
13809 
13810 	if (un->un_pos.pmode == logical) {
13811 
13812 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13813 		    "st_backward_space_files: mt_op=%x count=%x"
13814 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
13815 		    un->un_pos.lgclblkno);
13816 
13817 
13818 		/* In case a drive that won't back space gets in logical mode */
13819 		if ((un->un_dp->options & ST_BSF) == 0) {
13820 			rval = EIO;
13821 			return (rval);
13822 		}
13823 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(-count), SYNC_CMD)) {
13824 			rval = EIO;
13825 			return (rval);
13826 		}
13827 		if ((infront != 0) &&
13828 		    (st_cmd(un->un_dev, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
13829 			rval = EIO;
13830 			return (rval);
13831 		}
13832 		return (rval);
13833 	}
13834 
13835 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13836 	    "st_backward_space_files: mt_op=%x count=%x fileno=%x blkno=%x\n",
13837 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
13838 
13839 
13840 
13841 	/*
13842 	 * Handle the simple case of BOT
13843 	 * playing a role in these cmds.
13844 	 * We do this by calculating the
13845 	 * ending file number. If the ending
13846 	 * file is < BOT, rewind and set an
13847 	 * error and mark resid appropriately.
13848 	 * If we're backspacing a file (not a
13849 	 * filemark) and the target file is
13850 	 * the first file on the tape, just
13851 	 * rewind.
13852 	 */
13853 
13854 	/* figure expected destination of this SPACE command */
13855 	end_fileno = un->un_pos.fileno - count;
13856 
13857 	/*
13858 	 * Would the end effect of this SPACE be the same as rewinding?
13859 	 * If so just rewind instead.
13860 	 */
13861 	if ((infront != 0) && (end_fileno < 0) ||
13862 	    (infront == 0) && (end_fileno <= 0)) {
13863 		if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
13864 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13865 			    "st_backward_space_files: EIO : "
13866 			    "rewind in lou of BSF failed\n");
13867 			rval = EIO;
13868 		}
13869 		if (end_fileno < 0) {
13870 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13871 			    "st_backward_space_files: EIO : "
13872 			    "back space file greater then fileno\n");
13873 			rval = EIO;
13874 			un->un_err_resid = -end_fileno;
13875 			un->un_status = SUN_KEY_BOT;
13876 		}
13877 		return (rval);
13878 	}
13879 
13880 	if (un->un_dp->options & ST_BSF) {
13881 		skip_cnt = 1 - infront;
13882 		/*
13883 		 * If we are going to end up at the beginning
13884 		 * of the file, we have to space one extra file
13885 		 * first, and then space forward later.
13886 		 */
13887 		end_fileno = -(count + skip_cnt);
13888 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
13889 		    "skip_cnt=%x, tmp=%x\n", skip_cnt, end_fileno);
13890 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
13891 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13892 			    "st_backward_space_files:EIO:back space fm failed");
13893 			rval = EIO;
13894 		}
13895 	} else {
13896 		if (st_cmd(un->un_dev, SCMD_REWIND, 0, SYNC_CMD)) {
13897 			rval = EIO;
13898 		} else {
13899 			skip_cnt = end_fileno + infront;
13900 		}
13901 	}
13902 
13903 	/*
13904 	 * If we have to space forward, do so...
13905 	 */
13906 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
13907 	    "space forward skip_cnt=%x, rval=%x\n", skip_cnt, rval);
13908 
13909 	if (rval == 0 && skip_cnt) {
13910 		if (st_cmd(un->un_dev, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
13911 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13912 			    "st_backward_space_files:EIO:space fm skip count");
13913 			rval = EIO;
13914 		} else if (infront) {
13915 			/*
13916 			 * If we had to space forward, and we're
13917 			 * not a tape that can backspace, mark state
13918 			 * as if we'd just seen a filemark during a
13919 			 * a read.
13920 			 */
13921 			if ((un->un_dp->options & ST_BSF) == 0) {
13922 				un->un_pos.eof = ST_EOF_PENDING;
13923 				un->un_pos.fileno -= 1;
13924 				un->un_pos.blkno = INF;
13925 			}
13926 		}
13927 	}
13928 
13929 	if (rval != 0) {
13930 		un->un_pos.pmode = invalid;
13931 	}
13932 
13933 	return (rval);
13934 }
13935 
13936 static int
13937 st_mtnbsf_ioctl(struct scsi_tape *un, int count)
13938 {
13939 	int rval;
13940 
13941 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
13942 
13943 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13944 	    "nbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
13945 
13946 	if (un->un_pos.pmode == legacy) {
13947 		/*
13948 		 * backward space file to beginning of file
13949 		 *
13950 		 * If a negative count (which implies a forward space op)
13951 		 * is specified, and we're at logical or physical eot,
13952 		 * bounce the request.
13953 		 */
13954 
13955 		if (un->un_pos.eof >= ST_EOT && count < 0) {
13956 			un->un_err_resid = count;
13957 			un->un_status = SUN_KEY_EOT;
13958 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13959 			    "st_ioctl : EIO : > EOT and count < 0");
13960 			return (EIO);
13961 		}
13962 		/*
13963 		 * physical tape position may not be what we've been
13964 		 * telling the user; adjust the request accordingly
13965 		 */
13966 		if (IN_EOF(un->un_pos)) {
13967 			un->un_pos.fileno++;
13968 			un->un_pos.blkno = 0;
13969 			count++;
13970 		}
13971 	}
13972 
13973 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
13974 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13975 		    "st_ioctl : EIO : MTNBSF check den and wfm");
13976 		return (EIO);
13977 	}
13978 
13979 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13980 	    "mtnbsf: count=%x, eof=%x\n", count, un->un_pos.eof);
13981 
13982 	if (count <= 0) {
13983 		rval = st_forward_space_files(un, -count);
13984 	} else {
13985 		rval = st_backward_space_files(un, count, 0);
13986 	}
13987 	return (rval);
13988 }
13989 
13990 static int
13991 st_mtbsr_ioctl(struct scsi_tape *un, int num)
13992 {
13993 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
13994 
13995 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
13996 	    "bsr: count=%x, eof=%x\n", num, un->un_pos.eof);
13997 
13998 	if (un->un_pos.pmode == legacy) {
13999 		/*
14000 		 * backward space into inter-record gap
14001 		 *
14002 		 * If a negative count (which implies a forward space op)
14003 		 * is specified, and we're at logical or physical eot,
14004 		 * bounce the request.
14005 		 */
14006 		if (un->un_pos.eof >= ST_EOT && num < 0) {
14007 			un->un_err_resid = num;
14008 			un->un_status = SUN_KEY_EOT;
14009 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14010 			    "st_ioctl : EIO : MTBSR > EOT");
14011 			return (EIO);
14012 		}
14013 
14014 		if (num == 0) {
14015 			COPY_POS(&un->un_err_pos, &un->un_pos);
14016 			un->un_err_resid = 0;
14017 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
14018 				un->un_status = SUN_KEY_EOF;
14019 			}
14020 			return (0);
14021 		}
14022 
14023 		/*
14024 		 * physical tape position may not be what we've been
14025 		 * telling the user; adjust the position accordingly.
14026 		 * bsr can not skip filemarks and continue to skip records
14027 		 * therefore if we are logically before the filemark but
14028 		 * physically at the EOT side of the filemark, we need to step
14029 		 * back; this allows fsr N where N > number of blocks in file
14030 		 * followed by bsr 1 to position at the beginning of last block
14031 		 */
14032 		if (IN_EOF(un->un_pos)) {
14033 			tapepos_t save;
14034 			optype lastop = un->un_lastop;
14035 
14036 			COPY_POS(&save, &un->un_pos);
14037 			if (st_cmd(un->un_dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)
14038 			    == -1) {
14039 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14040 				    "st_write_fm : EIO : MTBSR can't space");
14041 				return (EIO);
14042 			}
14043 
14044 			COPY_POS(&un->un_pos, &save);
14045 			un->un_lastop = lastop;
14046 		}
14047 	}
14048 
14049 	un->un_pos.eof = ST_NO_EOF;
14050 
14051 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
14052 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14053 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
14054 		return (EIO);
14055 	}
14056 
14057 	num = -num;
14058 	return (st_space_records(un, num));
14059 }
14060 
14061 static int
14062 st_mtfsfm_ioctl(struct scsi_tape *un, int cnt)
14063 {
14064 	int rval;
14065 
14066 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
14067 
14068 	rval = st_cmd(un->un_dev, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
14069 	if (rval == 0) {
14070 		un->un_pos.pmode = logical;
14071 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
14072 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
14073 		/*
14074 		 * Drive says invalid field in cdb.
14075 		 * Doesn't like space multiple. Position isn't lost.
14076 		 */
14077 		un->un_err_resid = cnt;
14078 		un->un_status = 0;
14079 		rval = ENOTTY;
14080 	} else {
14081 		un->un_err_resid = cnt;
14082 		un->un_pos.pmode = invalid;
14083 	}
14084 	return (rval);
14085 }
14086 
14087 static int
14088 st_mtbsfm_ioctl(struct scsi_tape *un, int cnt)
14089 {
14090 	int rval;
14091 
14092 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
14093 
14094 	rval = st_cmd(un->un_dev, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
14095 	if (rval == 0) {
14096 		un->un_pos.pmode = logical;
14097 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
14098 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
14099 		/*
14100 		 * Drive says invalid field in cdb.
14101 		 * Doesn't like space multiple. Position isn't lost.
14102 		 */
14103 		un->un_err_resid = cnt;
14104 		un->un_status = 0;
14105 		rval = ENOTTY;
14106 	} else {
14107 		un->un_err_resid = cnt;
14108 		un->un_pos.pmode = invalid;
14109 	}
14110 	return (rval);
14111 }
14112 
14113 #ifdef	__x86
14114 
14115 /*
14116  * release contig_mem and wake up waiting thread, if any
14117  */
14118 static void
14119 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
14120 {
14121 	mutex_enter(ST_MUTEX);
14122 
14123 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
14124 
14125 	cp->cm_next = un->un_contig_mem;
14126 	un->un_contig_mem = cp;
14127 	un->un_contig_mem_available_num++;
14128 	cv_broadcast(&un->un_contig_mem_cv);
14129 
14130 	mutex_exit(ST_MUTEX);
14131 }
14132 
14133 /*
14134  * St_get_contig_mem will return a contig_mem if there is one available
14135  * in current system. Otherwise, it will try to alloc one, if the total
14136  * number of contig_mem is within st_max_contig_mem_num.
14137  * It will sleep, if allowed by caller or return NULL, if no contig_mem
14138  * is available for now.
14139  */
14140 static struct contig_mem *
14141 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
14142 {
14143 	size_t rlen;
14144 	struct contig_mem *cp = NULL;
14145 	ddi_acc_handle_t acc_hdl;
14146 	caddr_t addr;
14147 	int big_enough = 0;
14148 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
14149 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
14150 
14151 	/* Try to get one available contig_mem */
14152 	mutex_enter(ST_MUTEX);
14153 
14154 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
14155 
14156 	if (un->un_contig_mem_available_num > 0) {
14157 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
14158 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
14159 		/*
14160 		 * we failed to get one. we're going to
14161 		 * alloc one more contig_mem for this I/O
14162 		 */
14163 		mutex_exit(ST_MUTEX);
14164 		cp = (struct contig_mem *)kmem_zalloc(
14165 		    sizeof (struct contig_mem) + biosize(),
14166 		    alloc_flags);
14167 		if (cp == NULL) {
14168 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14169 			    "alloc contig_mem failure\n");
14170 			return (NULL); /* cannot get one */
14171 		}
14172 		cp->cm_bp = (struct buf *)
14173 		    (((caddr_t)cp) + sizeof (struct contig_mem));
14174 		bioinit(cp->cm_bp);
14175 		mutex_enter(ST_MUTEX);
14176 		un->un_contig_mem_total_num++; /* one more available */
14177 	} else {
14178 		/*
14179 		 * we failed to get one and we're NOT allowed to
14180 		 * alloc more contig_mem
14181 		 */
14182 		if (alloc_flags == KM_SLEEP) {
14183 			while (un->un_contig_mem_available_num <= 0) {
14184 				cv_wait(&un->un_contig_mem_cv,
14185 				    ST_MUTEX);
14186 			}
14187 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
14188 		} else {
14189 			mutex_exit(ST_MUTEX);
14190 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14191 			    "alloc contig_mem failure\n");
14192 			return (NULL); /* cannot get one */
14193 		}
14194 	}
14195 	mutex_exit(ST_MUTEX);
14196 
14197 	/* We need to check if this block of mem is big enough for this I/O */
14198 	if (cp->cm_len < len) {
14199 		/* not big enough, need to alloc a new one */
14200 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
14201 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
14202 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
14203 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14204 			    "alloc contig_mem failure: not enough mem\n");
14205 			st_release_contig_mem(un, cp);
14206 			cp = NULL;
14207 		} else {
14208 			if (cp->cm_addr) {
14209 				/* release previous one before attach new one */
14210 				ddi_dma_mem_free(&cp->cm_acc_hdl);
14211 			}
14212 			mutex_enter(ST_MUTEX);
14213 			un->un_max_contig_mem_len =
14214 			    un->un_max_contig_mem_len >= len ?
14215 			    un->un_max_contig_mem_len : len;
14216 			mutex_exit(ST_MUTEX);
14217 
14218 			/* attach new mem to this cp */
14219 			cp->cm_addr = addr;
14220 			cp->cm_acc_hdl = acc_hdl;
14221 			cp->cm_len = len;
14222 
14223 			goto alloc_ok; /* get one usable cp */
14224 		}
14225 	} else {
14226 		goto alloc_ok; /* get one usable cp */
14227 	}
14228 
14229 	/* cannot find/alloc a usable cp, when we get here */
14230 
14231 	mutex_enter(ST_MUTEX);
14232 	if ((un->un_max_contig_mem_len < len) ||
14233 	    (alloc_flags != KM_SLEEP)) {
14234 		mutex_exit(ST_MUTEX);
14235 		return (NULL);
14236 	}
14237 
14238 	/*
14239 	 * we're allowed to sleep, and there is one big enough
14240 	 * contig mem in the system, which is currently in use,
14241 	 * wait for it...
14242 	 */
14243 	big_enough = 1;
14244 	do {
14245 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
14246 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
14247 	} while (cp == NULL);
14248 	mutex_exit(ST_MUTEX);
14249 
14250 	/* we get the big enough contig mem, finally */
14251 
14252 alloc_ok:
14253 	/* init bp attached to this cp */
14254 	bioreset(cp->cm_bp);
14255 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
14256 	cp->cm_bp->b_private = (void *)cp;
14257 
14258 	return (cp);
14259 }
14260 
14261 /*
14262  * this is the biodone func for the bp used in big block I/O
14263  */
14264 static int
14265 st_bigblk_xfer_done(struct buf *bp)
14266 {
14267 	struct contig_mem *cp;
14268 	struct buf *orig_bp;
14269 	int ioerr;
14270 	struct scsi_tape *un;
14271 
14272 	/* sanity check */
14273 	if (bp == NULL) {
14274 		return (DDI_FAILURE);
14275 	}
14276 
14277 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
14278 	if (un == NULL) {
14279 		return (DDI_FAILURE);
14280 	}
14281 
14282 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
14283 
14284 	cp = (struct contig_mem *)bp->b_private;
14285 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
14286 	cp->cm_bp = bp;
14287 
14288 	/* special handling for special I/O */
14289 	if (cp->cm_use_sbuf) {
14290 #ifndef __lock_lint
14291 		ASSERT(un->un_sbuf_busy);
14292 #endif
14293 		un->un_sbufp = orig_bp;
14294 		cp->cm_use_sbuf = 0;
14295 	}
14296 
14297 	orig_bp->b_resid = bp->b_resid;
14298 	ioerr = geterror(bp);
14299 	if (ioerr != 0) {
14300 		bioerror(orig_bp, ioerr);
14301 	} else if (orig_bp->b_flags & B_READ) {
14302 		/* copy data back to original bp */
14303 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
14304 		    bp->b_bcount - bp->b_resid);
14305 	}
14306 
14307 	st_release_contig_mem(un, cp);
14308 
14309 	biodone(orig_bp);
14310 
14311 	return (DDI_SUCCESS);
14312 }
14313 
14314 /*
14315  * We use this func to replace original bp that may not be able to do I/O
14316  * in big block size with one that can
14317  */
14318 static struct buf *
14319 st_get_bigblk_bp(struct buf *bp)
14320 {
14321 	struct contig_mem *cp;
14322 	struct scsi_tape *un;
14323 	struct buf *cont_bp;
14324 
14325 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
14326 	if (un == NULL) {
14327 		return (bp);
14328 	}
14329 
14330 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
14331 
14332 	/* try to get one contig_mem */
14333 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
14334 	if (!cp) {
14335 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
14336 		    "Cannot alloc contig buf for I/O for %lu blk size",
14337 		    bp->b_bcount);
14338 		return (bp);
14339 	}
14340 	cont_bp = cp->cm_bp;
14341 	cp->cm_bp = bp;
14342 
14343 	/* make sure that we "are" using un_sbufp for special I/O */
14344 	if (bp == un->un_sbufp) {
14345 #ifndef __lock_lint
14346 		ASSERT(un->un_sbuf_busy);
14347 #endif
14348 		un->un_sbufp = cont_bp;
14349 		cp->cm_use_sbuf = 1;
14350 	}
14351 
14352 	/* clone bp */
14353 	cont_bp->b_bcount = bp->b_bcount;
14354 	cont_bp->b_resid = bp->b_resid;
14355 	cont_bp->b_iodone = st_bigblk_xfer_done;
14356 	cont_bp->b_file = bp->b_file;
14357 	cont_bp->b_offset = bp->b_offset;
14358 	cont_bp->b_dip = bp->b_dip;
14359 	cont_bp->b_error = 0;
14360 	cont_bp->b_proc = NULL;
14361 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
14362 	cont_bp->b_shadow = NULL;
14363 	cont_bp->b_pages = NULL;
14364 	cont_bp->b_edev = bp->b_edev;
14365 	cont_bp->b_dev = bp->b_dev;
14366 	cont_bp->b_lblkno = bp->b_lblkno;
14367 	cont_bp->b_forw = bp->b_forw;
14368 	cont_bp->b_back = bp->b_back;
14369 	cont_bp->av_forw = bp->av_forw;
14370 	cont_bp->av_back = bp->av_back;
14371 	cont_bp->b_bufsize = bp->b_bufsize;
14372 
14373 	/* get data in original bp */
14374 	if (bp->b_flags & B_WRITE) {
14375 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
14376 	}
14377 
14378 	return (cont_bp);
14379 }
14380 #else
14381 #ifdef __lock_lint
14382 static int
14383 st_bigblk_xfer_done(struct buf *bp)
14384 {
14385 	return (0);
14386 }
14387 #endif
14388 #endif
14389 
14390 static const char *eof_status[] =
14391 {
14392 	"NO_EOF",
14393 	"EOF_PENDING",
14394 	"EOF",
14395 	"EOT_PENDING",
14396 	"EOT",
14397 	"EOM",
14398 	"AFTER_EOM"
14399 };
14400 static const char *mode[] = {
14401 	"invalid",
14402 	"legacy",
14403 	"logical"
14404 };
14405 
14406 static void
14407 st_print_position(struct scsi_tape *un, const char *comment, tapepos_t *pos)
14408 {
14409 	ST_FUNC(ST_DEVINFO, st_print_position);
14410 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
14411 	    "%s Position data:\n", comment);
14412 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14413 	    "Positioning mode = %s", mode[pos->pmode]);
14414 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14415 	    "End Of File/Tape = %s", eof_status[pos->eof]);
14416 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14417 	    "File Number      = 0x%x", pos->fileno);
14418 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14419 	    "Block Number     = 0x%x", pos->blkno);
14420 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14421 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
14422 	scsi_log(ST_DEVINFO, st_label, CE_CONT,
14423 	    "Partition Number = 0x%x", pos->partition);
14424 }
14425